repo
stringlengths
27
90
file
stringlengths
57
176
language
stringclasses
2 values
license
stringclasses
13 values
content
stringlengths
25
180k
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/chapters/06_summary.typ
typst
#import "../preamble.typ": * = Hypotheses and their Falsification At the start of this project I set a few hypotheses to primarily falsify. It is tempting to change these hypotheses based on the data acquired here, but that would be akin to putting a cart in front of a horse. The hypotheses as originally set out are listed in @hypo. In the following two sections I will try and see if I managed to bring evidence to falsify these hypotheses. == Travel Time Indicator The first hypothesis concerned mean travel times, and their ability to capture transit service patterns. The null hypothesis would be that our indicator cannot capture any details about public transit patterns in Heidelberg. Comparing the map of average cell to cell travel times @map_17_tt to for example a map of the Heidelberg tram network (@trams), the tram network coincides with a lot of lower travel time cells. #figure(image("../figures/2024-02-11_Straßenbahn-Linien-Heidelberg-2019-09.svg"), caption: [rnv Tram service map as of September 2023], kind: "Map", supplement: "Map") <trams> Furthermore, the indicator clearly captures elements of centrality within the city, such as outlying districts which need more travel time to other districts than the central nodes of the public transit network. As such the null hypothesis that the travel time indicator cannot reproduce features of Heidelberg transit, can be rejected. The mean travel time is a useful indicator. The second hypothesis concerns the distribution of accessibility throughout the day and it's distribution. The assumption was that outlying areas like Emmertsgrund would have a worse spread of travel times at any hour of the day. At midnight however this does not seem to be true (compare @midnight). At midnight, locations the spread of average travel times is very low, but a few outliers emerge around some of the more outlying railway stations like Heidelberg Kirchheim/Rohrbach, Schlierbach, Weststadt/Südstadt. Beyond that there are also some curious travel time lows at outlying settlements like Grenzhof and Bruchhausen outside the city boundaries. #figure(image("../figures/Heidelberg_TravelTime_Map0.svg"), kind: "Map", supplement: "Map", caption: [Average Travel times at midnight in minutes]) <midnight> This falsifies the hypothesis that outlying areas always have worse travel time averages than central locations like Bismarckplatz. At specific edge times, it can be harder to travel from Bismarckplatz than from Schlierbach. == Planning Indicator The third hypothesis concerns the alignment of the planning indicator with the mean travel time indicator. I hypothesised that these would align fairly well, and central locations with a low average travel time would be also well connected in terms of the need to plan out journeys, or how much difference planning a journey makes to travel times. For peak hour travel this is definitely not true. At 17:00 local time @difference_map, it is weirdly enough not central places that have a low travel time difference, but the places that lie in unpopulated areas without direct access to a stop, but that are about equidistant from two stops that lie on completely differenc line. These, for example, are cells in the forest east of Handschuhsheim. Cells within the populated area display a largely homogenous distribution of travel time differences, acrosse the day. Only at edge times, do outlying districts exhibit worse travel time differences than central hubs. As such the hypothesis can be falsified, but in a way that puts the usefulness of this indicator as a proxy for the need to plan into question. This however also falsifies the fourth hypothesis, that the planning indicator will preserve it's pattern across the day. As seen above, this isn't true, and outlying areas experience higher travel time differences specifically before the morning rush-hour and after the evening peak. For nighttime travel the pattern reverses because in outlying areas walking becomes the only viable mode in the set of modes used for routing, and suddenly the schedules matter only at stations that still see some limited night time service. <end_of_chapter> #locate(loc => bib_state.at(query(<end_of_chapter>, loc).first().location()))
https://github.com/f7ed0/typst-template
https://raw.githubusercontent.com/f7ed0/typst-template/master/template_stretch.typ
typst
#import "lib/blocks.typ": * #let init(type : [], title : [], authors:[], info : [], decoration: "assets/uphf.png",desc : [], allowance : 255pt, outline_depth : 3, preamble : [], doc) = { set text(size:10pt, font:"Montserrat", weight: 500, lang:"fr",hyphenate: false) show raw: set text(font: "Fira Code",size: 9pt,ligatures: true) set heading(numbering: "I.A.1.") set figure(kind: "figure", supplement: "Figure") let date_str = datetime.today().display("[month repr:long] [day], [year]") show heading: it => block(width: 100%)[ #text(it, font : "Montserrat", weight: 620) ] [ #set page(background: image("./assets/bg.png", height: 100%, width: 100%)) #text(title, size: 22pt, font:"Stretch Pro", weight: 700) #text(type, size: 20pt, font:"Montserrat") #line(length: 50%) #text(authors, size: 17pt, weight: 600, fill: rgb(100, 100, 100, 255)) #text(date_str,weight: 500, size: 16pt, fill: rgb(100, 100, 100, 255)) #block( align(center + horizon, image(decoration) ), height: 100% - allowance, width: 100%, ) #line(length: 100%) #grid( columns : (3fr,4fr), desc, align(right,image("assets/uphf.png",height: 50pt)), ) #pagebreak(weak: true) ] set par(justify: true) set page( header: normalheader(authors,info,title), footer: context [ #text(authors+" - "+info, size:11pt, font: "Montserrat", weight: 500) #h(1fr) #text(counter(page).display("1 / 1", both: true),size:11pt,font: "Montserrat", weight: 500) ], background: image("assets/bg_all.png",width: 100%,height: 100%,fit: "stretch") ) [ #outline(indent: true, depth: outline_depth) ] table_figure() set page( header:{ text("Préambule", size: 10pt, weight: 500) h(1fr) text(title,size : 9pt, weight: 600,font: "Stretch Pro") line(length: 100%) } ) if preamble != [] { pagebreak(weak: true) align(smallcaps(text("Préambule",size : 12pt, weight : 650)),center) pad(align(text(preamble),center),x : 10%) } pagebreak(weak : true) set page( header: normalheader(authors,info,title) ) doc }
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/src/impl/complex.typ
typst
Apache License 2.0
#import "/src/utils.typ": combine-dict #import "num/num.typ" #import "angle.typ": is-angle, parse as parse-angle, to-number as angle-to-number #import "unit.typ" as unit_ #import "qty.typ" #let default-options = ( complex-angle-unit: "degrees", complex-mode: "input", complex-root-position: "after-number", complex-symbol-angle: sym.angle, complex-symbol-degree: sym.degree, output-complex-root: math.upright("i"), print-complex-unity: false ) // I've kind of given up with the combine-dict rules, I need to sort this out another time. #let get-options(options) = combine-dict(options, default-options + num.default-options + unit_.default-options + qty.default-options, only-update: true) #let parse(options, real, imag) = { if options.parse-numbers == false { if options.complex-mode == "input" { panic("Cannot identify the complex mode without parsing the number!") } return (options.complex-mode, real, imag) } let imag-type = type(imag) let input-mode = if is-angle(imag) { "polar" } else { "cartesian" } if options.complex-mode != "input" and input-mode != options.complex-mode { real = num.to-float(options, real) (real, imag) = if input-mode == "cartesian" { // output mode is polar imag = num.to-float(options, imag) ( calc.sqrt( calc.pow(real, 2) + calc.pow(imag, 2) ), calc.atan2(real, imag) ) } else { imag = angle-to-number(imag) // output mode is cartesian ( real * calc.cos(imag), real * calc.sin(imag) ) } } let mode = if options.complex-mode == "input" { input-mode } else { options.complex-mode } return ( mode, num.parse(options, real), if options.complex-mode == "input" and input-mode == "cartesian" or options.complex-mode == "cartesian" { num.parse(options, imag) } else { parse-angle(options, imag) } ) } #let complex(real, imag, unit, options) = { options = get-options(options) let (mode, real, imag) = parse(options, real, imag) let is-polar = mode == "polar" let real-mantissa = { let (options, sign, mantissa, ..rest) = num.process(options, ..real, none, none, none) mantissa real = num.build(options, sign, mantissa, ..rest) } return math.equation({ if is-polar or real-mantissa != "0" { real } if is-polar { options.complex-symbol-angle num.build(..num.process(options, ..imag, none, none, none)) if options.complex-angle-unit == "degrees" { options.complex-symbol-degree } } else { let (options, sign, mantissa, ..rest) = num.process(options, ..imag, none, none, none) options.print-implicit-plus = real-mantissa != "0" mantissa = if not options.print-complex-unity and mantissa in ("1", "") { options.output-complex-root } else if options.complex-root-position == "after-number" { mantissa + options.output-complex-root } else { options.output-complex-root + mantissa } num.build(options, sign, mantissa, ..rest) } if unit != none { unit_.unit(unit, options) } }) }
https://github.com/pths-prog-paradigms/GameOfLife
https://raw.githubusercontent.com/pths-prog-paradigms/GameOfLife/master/gol.typ
typst
#import "@preview/cetz:0.1.2" Поле представляет из себя потенциально бесконечную сетку. В каждой клетке может быть жизнь. Каждый ход, если у живой клетки два или три живых соседа, она остаётся живой, иначе умирает. Если у мёртвой клетки ровно три живых соседа, то в ней зарождается жизнь. Обозначим чёрным наличие жизни: #let field(n, m) = { import cetz.draw: * if (m == none) { m = n } for i in range(0, m) { for j in range(0, n) { rect((i, -j), (i + 1, -j - 1)) } } } #let alive(i, j) = { import cetz.draw: * rect((i, -j), (i + 1, -j - 1), fill: black) } #let dying(i, j) = { import cetz.draw: * line((i, -j), (i + 1, -j - 1), stroke: red + 3pt) line((i, -j - 1), (i + 1, -j), stroke: red + 3pt) } #let born(i, j) = { import cetz.draw: * circle((i + .5, -j - .5), radius: .15, fill: black) } #let canv(f) = pad(1em, cetz.canvas({ import cetz.draw: * scale(.7) field(7, 7) f })) #canv({ alive(2, 2) alive(2, 3) alive(2, 4) alive(3, 2) alive(4, 3) }) На следующем ходу две клетки умрут "от одиночества", две зародятся: #grid(columns: 2, canv({ alive(2, 2) alive(2, 3) alive(2, 4) alive(3, 2) alive(4, 3) dying(2, 4) dying(4, 3) born(1, 3) born(3, 4) }), canv({ alive(2, 2) alive(2, 3) alive(3, 2) alive(1, 3) alive(3, 4) })) На следующем одна умрёт от одиночества, одна --- от перенаселения. Снова две зародятся. #grid(columns: 2, canv({ alive(2, 2) alive(2, 3) alive(3, 2) alive(1, 3) alive(3, 4) dying(2, 3) dying(3, 4) born(1, 2) born(2, 4) }), canv({ alive(2, 2) alive(3, 2) alive(1, 3) alive(1, 2) alive(2, 4) })) И так далее. \ \ \ "Жизнь" развивается довольно непредсказуемым образом. Этот процесс здесь называется _эволюцией_. #let canv(n, m, s, f) = pad(1em, cetz.canvas({ import cetz.draw: * scale(s) field(n, m) f })) Есть стационарные конфигурации, которые не меняются с течением времени: #canv(6, 13, 1, { alive(1, 2) alive(1, 3) alive(2, 2) alive(2, 3) alive(5, 2) alive(5, 3) alive(7, 2) alive(7, 3) alive(6, 1) alive(6, 4) alive(10, 1) alive(10, 2) alive(11, 1) alive(11, 3) alive(11, 4) alive(10, 4) }) Есть, которые осциллируют: #let s = .53 #grid(columns: 4, canv(5, 5, s, { alive(2, 3) alive(2, 2) alive(2, 1) }), canv(5, 5, s, { alive(3, 2) alive(2, 2) alive(1, 2) }), canv(5, 5, s, { alive(2, 3) alive(2, 2) alive(2, 1) }), canv(5, 5, s, { alive(3, 2) alive(2, 2) alive(1, 2) })) И которые перемещаются в пространстве со временем. #let s = .28 #grid(columns: 5, canv(7, 7, s, { alive(2, 2) alive(2, 3) alive(2, 4) alive(3, 2) alive(4, 3) }), canv(7, 7, s, { alive(2, 2) alive(2, 3) alive(3, 2) alive(1, 3) alive(3, 4) }), canv(7, 7, s, { alive(2, 2) alive(3, 2) alive(1, 3) alive(1, 2) alive(2, 4) }), canv(7, 7, s, { alive(2, 2) alive(1, 3) alive(1, 2) alive(2,1) alive(3,3) }), canv(7, 7, s, { alive(1, 3) alive(1, 2) alive(2,1) alive(1,1) alive(3,2) })) И это далеко не всё... На GoL вполне можно эмулировать компьютер, который выполнит любой алгоритм.
https://github.com/julius2718/wareki
https://raw.githubusercontent.com/julius2718/wareki/main/1.0.0/wareki.typ
typst
#let wareki_today = { let y = datetime.today().year() - 2018 let m = datetime.today().month() let d = datetime.today().day() if y == 1 [ 令和 元年 #m 月 #d 日 ] else [令和 #y 年 #m 月 #d 日] } #let wareki(y, m: none, d: none) = { let twareki = [#y 年] if y > 2019 { let reiwa = y - 2018 twareki = [令和 #reiwa 年] if m != none { twareki = [#twareki #m 月] } } else if y == 2019 { if m == none { twareki = [令和元年] } else if m < 5 { twareki = [平成31年 #m 月] } else { twareki = [令和元年 #m 月] } } else if y > 1988 { let heisei = y - 1988 twareki = [平成 #heisei 年] if m != none { twareki = [#twareki #m 月] } } else if y == 1988 { if m == none { twareki = [平成元年] } else if d == none { twareki = [平成元年 #m 月] } else if m == 1 and d < 8 { twareki = [昭和64年 #m 月] } else { twareki = [平成元年 #m 月] } } else if y > 1926{ let showa = y - 1925 twareki = [昭和 #showa 年] if m != none { twareki = [#twareki #m 月] } } else if y == 1926 { if m == none { twareki = [昭和元年] } else if d == none { twareki = [大正15年 #m 月] } else if m == 12 and d > 24 { twareki = [昭和元年 #m 月] } else { twareki = [大正15年 #m 月] } } else { twareki = [#y 年 #m 月] } if m != none and d != none { [#twareki #d 日] } else [#twareki] }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cuti/0.2.0/README.md
markdown
Apache License 2.0
# Cuti Cuti is a package that simulates fake bold / fake italic. This package is typically used on fonts that do not have a `bold` weight, such as "SimSun". ## Usage Please refer to the [English Demo & Doc](./demo-and-doc/demo-and-doc.pdf) located in the `demo-and-doc` directory for details. 本 Package 提供中文文档: [中文 Demo 与文档](./demo-and-doc/demo-and-doc-cn.pdf)。 ### Getting Started Quickly (For Chinese User) Please add the following content at the beginning of the document: ```typst #import "@preview/cuti:0.2.0": show-cn-fakebold #show: show-cn-fakebold ``` Then, the bolding for SimHei, SimSun, and KaiTi fonts should work correctly. ## License MIT License This package refers to the following content: - [TeX and Chinese Character Processing: Fake Bold and Fake Italic](https://zhuanlan.zhihu.com/p/19686102) - Typst issue [#394](https://github.com/typst/typst/issues/394) - Typst issue [#2749](https://github.com/typst/typst/issues/2749) (The function `_skew` comes from Enivex's code.) Thanks to Enter-tainer for the assistance.
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%20591%20-%20Mathematical%20Logic/Assignments/Assignment%201.typ
typst
#import "/Templates/generic.typ": latex, header #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #import "/Templates/assignment.typ": * #show: doc => header(title: "Assignment 1", name: "<NAME>", doc) #show: latex #show: NumberingAfter #show: thmrules #let ve = $epsilon$ #let seq = $subset.eq$ #let Mink = math.op("Mink") #let fu = $frak(U)$ #let pb() = {pagebreak(weak: true)} #let sat = $tack.r.double$ #let satn = $tack.r.double.not$ #let proves = $tack.r$ #let subm = $lt.curly$ #let Th = math.op("Th") #let mM = $cal(M)$ #let mN = $cal(N)$ #let bar(el) = $overline(#el)$ #let subs(a, b) = { return $attach(slash, tl: #a, br: #b)$ } = Question == Statement A language is functional if it has no relational symbols. Find an example of two structures $mM$, $mN$ in a functional language such that $mM equiv mN$, $mM seq mN$ but $mM$ is not an elementary substructure of $mN$. == Solution Consider for the language $L = (+)$ the two $L$-structures $mM = (ZZ, +)$ and $mN = (ZZ / 2, +)$, it is clear that $mM seq mN$ and since $mM tilde.eq mN$ by the function $g(x) : |mN| -> |mM|$ defined by $g(x) = 2x$ then we have that $mM equiv mN$. To see that it is not an elementary substructure consider the formula $ phi(y) = exists x thin (x + x = y) $ then we have $mN sat phi(1)$ but $mM satn phi(1)$, and so $mM$ is not an elementary substructure of $mN$. #pagebreak(weak: true) = Question == Statement Let $L = (+,0)$ be the language of groups. Is $(ZZ,+,0)$ elementarily equivalent to $(ZZ^2,+,0)$? == Solution No, consider the statement $exists z (forall y (exists x (y = x + x or y = x + x + z)))$, it essentially says that every element of the universe is either odd or even once we let $z = 1$. This statement holds in $ZZ$, we now prove that it doesn't hold in $ZZ^2$. Consider the set $A_z seq ZZ^2$ defined by $ A_z = { y in ZZ^2 | exists x in ZZ^2 (y = x + x or y = x + x + z) } $ now consider the image of $A_z$ under taking mod $2 ZZ^2$, we can easily see that it is equal to $ A_z mod 2 ZZ^2 = {0, z mod 2 ZZ^2} $ and thus always has cardinality 2. But $ZZ^2 mod 2 ZZ^2$ has cardinality $4$, so we can't hit every element. Thus the statement does not hold in $ZZ^2$ and so they have different theories. #pagebreak(weak: true) = Question == Statement Let $mM$ be a finite structure in a finite language. Find a sentence $sigma$ such that if $mN sat sigma$, then $mN tilde.eq mM$. == Solution First enumerate the elements of $|mM|$ as $a_1,...,a_n$. First we want to make sure that $mN$ contains 'copies' of these elements. We thus construct the statement $ exists y_1 thin exists y_2 thin ... thin exists y_n thin and.big_(i eq.not j) (y_i eq.not y_j) thin and (forall z thin or.big_i (z = y_i)) $ we then need to check that all functions map as we expect, for any function $f_j$ with arity $k_j$ define the auxiliary function $i(j,c_1,c_2,...,c_(k_j))$ implicitly by $ a_(i(j,c_1,c_2,...,c_(k_j))) = f_j^mM (a_(c_1), a_(c_2), ..., a_(c_(k_j))) $ it is essentially the index translation of $f_j$. We then have the formula $ S F = and.big_(f_j) (and.big_((c_1,...,c_(k_j)) in [n]^(k_j)) (y_(i(j,c_1,c_2,...,c_(k_j))) = f_j (y_(c_1), y_(c_2), ..., y_(c_(k_j))))). $ For the relations $R_j$ with arity $p_j$, we define also the index set $ I_j = {(c_1,...,c_(p_j)) in [n]^(p_j)| (a_(c_1),...,a_(c_(p_j))) in R_j^mM} $ and then add the formula $ S R = and.big_(R_j) ( (and.big_((c_1,...,c_k) in I_j) (y_(c_1),...,y_(c_k)) in R_j) and (and.big_((c_1,...,c_k) in.not I_j) (y_(c_1),...,y_(c_k)) in.not R_j) ). $ Finally, for the constants $c_ell$, we define $j(ell)$ also implicitly by $ a_(j(ell)) = c_ell^mM $ and then add the formula $ S C = and.big_(c_ell) ( y_(j(ell)) = c_ell ) $ Finally then, our statement $sigma$ is $ sigma = exists y_1 thin exists y_2 thin ... thin exists y_n thin (and.big_(i eq.not j) (y_i eq.not y_j) thin and (forall z thin or.big_i (z = y_i)) and S F and S R and S C) $ If this statement holds then the map $a_i -> y_i$ will form an isomorphism. #pagebreak(weak: true) = Question == Statement Show that the theory of the infinite countable atomless Boolean algebra is $aleph_0$-categorical. == Solution #let ICAB = $I C A B$ We will let $ICAB$ denote the set of statements encoding an infinite countable atomless Boolean algebra. Let $(A, or, and, not)$ and $(B, or, and, not)$ be two models of $ICAB$. // We write $x <= y$ to denote $x or y = y$ or equivalently $y and x = x$. It is trivially a partial order on the universe. We will find an isomorphism between the two using a modified back-and-forth method. We will construct a partial isomorphism $f_n : A_n -> B_n$ in steps where at each step $n$ we have $A_n$ is a finite subalgebra of $A$ and $B_n$ is a finite subalgebra of $B$. At step $0$ we start with the trivial subalgebra ${0,1}$ for both $A_0$ and $B_0$, and we induct as follows. First note that $A_(n-1),B_(n-1)$ are both atomic since they are finite and thus have bases of atoms ${a_1,...,a_k}, {b_1,...,b_k}$ such that $f_(n-1)(a_i) = b_i$. On even steps we want to add an element $a in A backslash A_(n-1)$ to $A_(n-1)$, extend the map $f_(n-1)$ to map $a$ to some element $b in B$, and then extend it naturally on $A_n := angle.l a,A_(n-1) angle.r$, giving us $f_n$. On even steps we want to do the same but swapping $B$ and $A$. The key part here is finding an appropriate element $b$ that related to $B_(n-1)$ in the same way that $a$ related to $A_(n-1)$. Our atoms then will be quite helpful as the relations of $a$ with the atoms $a_i$ will encode all the information we need. In particular, there are only 3 ways in which $a$ can relate to a given basis element $a_i$, these are $ phi_1(a,a_i) &= (a and a_i = 0) "or" \ phi_2(a,a_i) &= (0 < a and a_i < a_i) "or"\ phi_3(a,a_i) &= (a and a_i = a_i). $ It is easy to see that one of these formulas must hold for every $i$. We can then say that for some indices $c_i in {1,2,3}$ we have that the statement $ and.big_(i in [k]) phi_(c_i) (a, a_i) $ holds true. Our job then becomes to find an element $b in B$ such that the statement $ and.big_(i in [k]) phi_(c_i) (b, f_(n-1) (a_i)) $ is true. This is quite simple, for each $i$, if $c_i = 1$ we set $d_i = 0$, if $c_i = 2$ we use atomlessness to set $d_i$ to be anything satisfying with $d_i < f(a_i)$, if $c_i = 3$ we set $d_i = f(a_i)$. Finally we just union the $d_i$'s together and that will be our desired $b$. #pagebreak(weak: true) = Question == Statement Find an example of two countable structures which are elementarily equivalent but not isomorphic. == Solution #let suc = math.op("succ") === Normal example #let clos = math.op("closure") Language of algebraically closed fields, we have $clos(QQ) tilde.eq.not clos(QQ[pi])$ but since the theory is complete they are both elementarily equivalent. === Cursed example My two example structures are $mM = (ZZ,suc)$ and $mN = (ZZ union.sq ZZ,suc)$ where $suc$ is the _relation_ corresponding to the successor function. We think of $mN$ as consisting of two _branches_ of $ZZ$. We can show that $mM$ and $mN$ are not isomorphic, assume that they are, then we have an isomorphism $f : |mM| -> |mN|$. Now we have $f(0) = (n,i)$ for some $(n,i)$, then we can easily see that $f(x) = (n+x,i)$ for all $x in |mM|$ due to how we define the relations. But then we have nothing that maps to $(n,1-i)$ and so we get a contradiction. Now we need to show that they are elementarily equivalent, to show that we can use the Ehreufeucht-Fraisse Game $Gamma(mM,mN)_n$. First define the following metric on $|mN|$, $ d_mN ((x,i),(y,j)) = cases(|x - y| &"if" i = j \ infinity &"if" i eq.not j) $ and define the standard metric on $|mM|$, $d_mM (x,y) = |x-y|$. Now we construct the winning strategy for the prover, we will denote by $A_k$ the current paired elements of $|mM|$, by $B_k$ the current paired elements of $|mN|$ and by $f_k$ the current partial isomorphism. At step $k$, if the spoiler picks $a in |mM|$, we first check if $d(a, A_k) > 2^(n-k)$. - If it is then we pick some $b in |mN|$ such that $d(b,B_k) >= d(a,A_k)$ and pair $a$ with $b$, that is we set $f_(k+1)(a) = b$. - If instead we have $d(a,A_k) <= 2^(n-k)$ then let $a_i$ be the closest element of $A_k$ to $a$. Then if $f_k (a_i) = (n,j)$ then we set $f_(k+1)(a) = (n - a_i + a, j)$. If the spoiler picks $b in |mM|$, we first check if $d(b, B_k) > 2^(n-k)$ - If it is then we pick some $a in |mM|$ such that $d(a,A_k) >= d(b,B_k)$ and pair $a$ with $b$, that is we set $f_(k+1)(a) = b$. - If instead we have $d(b, B_k) <= 2^(n-k)$ then let $b_i$ be the closest element of $B_k$ to $b$. Since their distance is not infinity we have that both $b$ and $b_i$ are in the same branch so we have $b = (n,j), b_i = (n_i,j)$ for some $j$. Then since $b_i in B_k$ we have $f_k (a_i) = b_i$ for some $a_i in A_k$. We then set $f(a_i - n_i + n) = b$. We now prove that this process is well defined (it might not be since in the second case there is no immediate guarantee that $(n - a_i + a,j)$ isn't already in the image of something), and that it results in a partial isomorphism. #lemma(numbering: none)[ We say that a pairing $(a,b)$ is _related_ to a pairing $(a',b')$ if $b$ and $b'$ are in the same branch and $a' - a = b' - b$, we write this as $(a,b) R (a',b')$. If at step $k$ the pairing $(a,b)$ was added then we have $ (a,b) cancel(R) (a',b') => d(a,a') >= 2^(n-k) and d(b,b') >= 2^(n-k) $ for all pairings $(a',b')$ already in $f_k$. ] #proof[ We prove by induction, at the start we have no pairings $(a',b')$ so this statement holds trivially. Now assume that this is true at step $k - 1$. - If the pair $(a,b)$ is added as in the first or third case then they might not be related to any other pairing but both $a$ and $b$ are at least $2^(n-k)$ distance away from all other elements of $A_n,B_n$. - If the pair $(a,b)$ is added as in the second or fourth case case, then by construction they are related to $(a_i, f_k (a_i))$. We can also easily see that $R$ is transitive and so $ (a, b) cancel(R) (a',b') &=> (a_i,f_k (a_i)) cancel(R) (a',b') \ &=> d(a_i, a') >= 2^(n-k+1) and d(f_k (a_i),b') >= 2^(n-k+1) $ by inductive hypothesis. But now by construction we have $ d(a, a_i) <= 2^(n-k) and d(b, f_k (a_i)) <= 2^(n-k) $ and so by inverse triangle inequality we get $ d(a,a') >= 2^(n-k) and d(b, b') >= 2^(n-k) $ which is precisely what we wanted to show. ] Now this immediately proves that the construction is well defined since if $(n - a_i + a, j)$ is already mapped to by something in the second case then that pairing cannot be related to $(a, f_k (a))$ and thus must be further than $2^(n-k)$ from $f_k (a)$ and which contradicts the fact that $|a - a_i| <= 2^(n-k)$. This also proves that the end result is a partial isomorphism, to see this note that being a partial isomorphism in this language is equivalent to the statement $ forall a thin forall a' (d(a,a') <= 1 or d(f(a), f(a')) <= 1 => (a, f(a)) R (a', f(a'))) $ Now notice that the lemma's statement only applies to the last placed pair, but for all the other pairs their distance to their closest unrelated pair can only decrease if a new pair is placed so in fact the lemma holds for all the pairs that exist at step $k$. But after this modification, the lemma when applied with step $n = k$ is exactly the contrapositive of the statement above.
https://github.com/DashieTM/nix-introduction
https://raw.githubusercontent.com/DashieTM/nix-introduction/main/topics/flakes.typ
typst
#import "../utils.typ": * #polylux-slide[ == Flakes #v(15pt) - extension to nixos/homemanager - removes the issue of hashes - enables easy updates of inputs - lock file - technically an "experimental" feature #pdfpc.speaker-note(```md ```) ] #polylux-slide[ === Example #v(15pt) #sourcecode(```nix { description = "dots"; inputs = { nixpkgs.url = "github:NixOs/nixpkgs/nixos-unstable"; home-manager = { url = "github:nix-community/home-manager"; inputs.nixpkgs.follows = "nixpkgs"; }; }; outputs = { ... }@inputs: let pkgs = import inputs.nixpkgs { system = "x86_64-linux"; config = { allowUnfree = true; }; }; in { nixosConfigurations."something" = inputs.nixpkgs.lib.nixosSystem { specialArgs = { inherit inputs pkgs; mod = ./hardware/something/base_config.nix; }; modules = [ ./hardware/hardware.nix ] }; }; } ```) #pdfpc.speaker-note(```md ```) ] #polylux-slide[ === Overrides #v(15pt) #sourcecode(```nix new: old: { packages = old.packages.override { package = new.newpackage; }; } ```) #pdfpc.speaker-note(```md ```) ]
https://github.com/WinstonMDP/knowledge
https://raw.githubusercontent.com/WinstonMDP/knowledge/master/binomial_coeffs.typ
typst
#import "cfg.typ": cfg #show: cfg = Биноминальные коэффициенты $binom(abs(X), i) := abs({y subset.eq X | |y| = i})$. $binom(n, i) = n!/(i! (n - i)!)$. $binom(n, i) = binom(n, n - i)$. $binom(n + 1, i + 1) = binom(n, i) + binom(n, i + 1)$. $(a + b)^n = sum_(i = 0)^n binom(n, i) a^i b^(n - i)$. $sum_(i = 0)^n binom(n, i) = 2^n$. Тождество Вандермонда: $sum_(i = 0)^n binom(p, i) binom(q, n - i) = binom(p + q, n)$. $0 <= l + k <= n -> sum_(i = k)^(n - l) binom(i, k) binom(n - i, l) = binom(n + 1, k + l + 1)$.
https://github.com/Jeomhps/datify
https://raw.githubusercontent.com/Jeomhps/datify/main/docs/README.md
markdown
MIT License
# Datify Datify is a simple date package that allows users to format dates in new ways and addresses the issue of lacking date formats in different languages. ## Installation To include this package in your Typst project, add the following to your project file: ```typst #import "@preview/datify:0.1.2": day-name, month-name, custom-date-format ``` ## Reference ### `day-name` Returns the name of the weekday. #### Example ```typst #import "@preview/datify:0.1.2": day-name #day-name(2) #day-name(1,"fr",true) ``` Output: ``` tuesday Lundi ``` #### Parameters ```typst day-name(weekday: int or str, lang: str, upper: boolean) --> str ``` | Parameter | Description | Default | |-----------|--------------------------------------------------------|---------| | weekday* | The weekday as an integer (1-7) or a string ("1"-"7"). | none | | lang | An ISO 639-1 code representing the language. | en | | upper | A boolean that sets the first letter to be uppercase. | false | \* required ### `month-name` Returns the name of the month. #### Example ```typst #import "@preview/datify:0.1.2": month-name #month-name(2) #month-name(1, "fr", true) ``` Output: ``` february Janvier ``` #### Parameters ```typst month-name(month: int or str, lang: str = 'en', upper: bool = false) -> str ``` | Parameter | Description | Default | |-----------|--------------------------------------------------------|---------| | month* | The month as an integer (1-12) or a string ("1"-"12"). | none | | lang | An ISO 639-1 code representing the language. | en | | upper | A boolean that sets the first letter to be uppercase. | false | \* required ### `custom-date-format` Formats a given date according to a specified format and language. #### Example ```typst #import "@preview/datify:0.1.2": custom-date-format #let my-date = datetime(year: 2024, month: 8, day: 4) #custom-date-format(my-date, "MMMM DDth, YYYY") ``` Output: ``` August 04th, 2024 ``` #### Parameters ```typst custom-date-format(date: datetime, format: str, lang: str = 'en') -> str ``` | Parameter | Description | Default | |-----------|------------------------------------------------|---------| | date* | A datetime object representing the date. | none | | format* | A string representing the desired date format. | none | | lang | An ISO 639-1 code representing the language. | en | \* required #### Format Types Below is a table of all possible format types that can be used in the format string: | Format | Description | Example | |--------|----------------------------------------|---------------| | `DD` | Day of the month, 2 digits | 05 | | `day` | Full name of the day | tuesday | | `Day` | Capitalized full name of the day | Tuesday | | `DAY` | Uppercase full name of the day | TUESDAY | | `MMMM` | Capitalized full name of the month | May | | `MMM` | Short name of the month (first 3 chars)| May | | `MM` | Month number, 2 digits | 05 | | `month`| Full name of the month | may | | `Month`| Capitalized full name of the month | May | | `MONTH`| Uppercase full name of the month | MAY | | `YYYY` | 4-digit year | 2023 | | `YY` | Last 2 digits of the year | 23 | ## Examples Here are some examples demonstrating the usage of the functions provided by the Datify package: ```typst #let my-date = datetime(year: 2024, month: 12, day: 25) #custom-date-format(my-date, "DD-MM-YYYY") // Output: 25-12-2024 #custom-date-format(my-date, "Day, DD Month YYYY", "fr") // Output: Mercredi, 25 Décembre 2024 #custom-date-format(my-date, "day, DD de month de YYYY", "es") // Output: miércoles, 25 de diciembre de 2024 #day-name(4) // Output: thursday #month-name(12) // Output: december ``` ## Supported language | ISO 639-1 code | Status | |----------------|--------------| | aa | ❌ | | ab | ❌ | | ae | ❌ | | af | ❌ | | ak | ❌ | | am | ❌ | | an | ❌ | | ar | ❌ | | as | ❌ | | av | ❌ | | ay | ❌ | | az | ❌ | | ba | ❌ | | be | ❌ | | bg | ❌ | | bh | ❌ | | bi | ❌ | | bm | ❌ | | bn | ❌ | | bo | ❌ | | br | ❌ | | bs | ❌ | | ca | ❌ | | ce | ❌ | | ch | ❌ | | co | ❌ | | cr | ❌ | | cs | ❌ | | cu | ❌ | | cv | ❌ | | cy | ❌ | | da | ❌ | | de | ✅ | | dv | ❌ | | dz | ❌ | | ee | ❌ | | el | ❌ | | en | ✅ | | eo | ❌ | | es | ✅ | | et | ❌ | | eu | ❌ | | fa | ❌ | | ff | ❌ | | fi | ❌ | | fj | ❌ | | fo | ❌ | | fr | ✅ | | fy | ❌ | | ga | ❌ | | gd | ❌ | | gl | ❌ | | gn | ❌ | | gu | ❌ | | gv | ❌ | | ha | ❌ | | he | ❌ | | hi | ❌ | | ho | ❌ | | hr | ❌ | | ht | ❌ | | hu | ❌ | | hy | ❌ | | hz | ❌ | | ia | ❌ | | id | ❌ | | ie | ❌ | | ig | ❌ | | ii | ❌ | | ik | ❌ | | io | ❌ | | is | ❌ | | it | ❌ | | iu | ❌ | | ja | ❌ | | jv | ❌ | | ka | ❌ | | kg | ❌ | | ki | ❌ | | kj | ❌ | | kk | ❌ | | kl | ❌ | | km | ❌ | | kn | ❌ | | ko | ❌ | | kr | ❌ | | ks | ❌ | | ku | ❌ | | kv | ❌ | | kw | ❌ | | ky | ❌ | | la | ❌ | | lb | ❌ | | lg | ❌ | | li | ❌ | | ln | ❌ | | lo | ❌ | | lt | ❌ | | lu | ❌ | | lv | ❌ | | mg | ❌ | | mh | ❌ | | mi | ❌ | | mk | ❌ | | ml | ❌ | | mn | ❌ | | mr | ❌ | | ms | ❌ | | mt | ❌ | | my | ❌ | | na | ❌ | | nb | ❌ | | nd | ❌ | | ne | ❌ | | ng | ❌ | | nl | ❌ | | nn | ❌ | | no | ❌ | | nr | ❌ | | nv | ❌ | | ny | ❌ | | oc | ❌ | | oj | ❌ | | om | ❌ | | or | ❌ | | os | ❌ | | pa | ❌ | | pi | ❌ | | pl | ❌ | | ps | ❌ | | pt | ❌ | | qu | ❌ | | rm | ❌ | | rn | ❌ | | ro | ❌ | | ru | ❌ | | rw | ❌ | | sa | ❌ | | sc | ❌ | | sd | ❌ | | se | ❌ | | sg | ❌ | | si | ❌ | | sk | ❌ | | sl | ❌ | | sm | ❌ | | sn | ❌ | | so | ❌ | | sq | ❌ | | sr | ❌ | | ss | ❌ | | st | ❌ | | su | ❌ | | sv | ❌ | | sw | ❌ | | ta | ❌ | | te | ❌ | | tg | ❌ | | th | ❌ | | ti | ❌ | | tk | ❌ | | tl | ❌ | | tn | ❌ | | to | ❌ | | tr | ❌ | | ts | ❌ | | tt | ❌ | | tw | ❌ | | ty | ❌ | | ug | ❌ | | uk | ❌ | | ur | ❌ | | uz | ❌ | | ve | ❌ | | vi | ❌ | | vo | ❌ | | wa | ❌ | | wo | ❌ | | xh | ❌ | | yi | ❌ | | yo | ❌ | | za | ❌ | | zh | ❌ | | zu | ❌ | ## Contributing Contributions are welcome! Please feel free to submit a pull request or open an issue if you encounter any problems. ## License This project is licensed under the MIT License. ## Planned - Adding support for more language - Adding set and get method to set default language for a whole document - Adding new methods
https://github.com/Shuenhoy/modern-zju-thesis
https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/undergraduate-decl.typ
typst
MIT License
#import "../utils/fonts.typ": 字号, 字体 #import "../utils/datetime-display.typ": datetime-display #import "../utils/indent-first-par.typ": fake-par #import "./template-individual.typ": template-individual #let undergraduate-decl( row-gutter: 11.5pt, ) = { template-individual("浙江大学本科生毕业论文(设计)承诺书")[ #set underline(offset: 0.2em) #show enum.item: x => [ #x.number. #x.body] #fake-par 1. 本人郑重地承诺所呈交的毕业论文(设计),是在指导教师的指导下严格按照学校和学院有关规定完成的。 2. 本人在毕业论文(设计)中除了文中特别加以标注和致谢的地方外,论文中不包含其他人已经发表或撰写过的研究成果,也不包含为获得#underline[*浙江大学*]或其他教育机构的学位或证书而使用过的材料。 3. 与我一同工作的同志对本研究所做的任何贡献均已在论文中作了明确的说明并表示谢意。 4. 本人承诺在毕业论文(设计)工作过程中没有伪造数据等行为。 5. 若在本毕业论文(设计)中有侵犯任何方面知识产权的行为,由本人承担相应的法律责任。 6. 本人完全了解#underline[*浙江大学*]有权保留并向有关部门或机构送交本论文(设计)的复印件和磁盘,允许本论文(设计)被查阅和借阅。本人授权#underline[*浙江大学*]可以将本论文(设计)的全部或部分内容编入有关数据库进行检索和传播,可以采用影印、缩印或扫描等复制手段保存、汇编本论文(设计)。 #v(1fr) #align(center)[ #table( columns: (0.5fr, 0.4fr, 0.5fr, 0.4fr), align: (start, center), stroke: none, row-gutter: row-gutter, [ 作者签名: ], [], [ 导师签名: ], [], [], [], [], [], [ 签字日期: ], [ 年 #h(1em) 月#h(1em)日], [ 签字日期: ], [ 年#h(1em)月#h(1em)日], ) ] ] }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rich-counters/0.1.0/README.md
markdown
Apache License 2.0
# `rich-counters` This package allows you to have **counters which depend on other counters**. Concretely, it implements `richcounter`, which is a counter that can _inherit_ one or more levels from another counter. The interface is similar to the [usual counter](https://typst.app/docs/reference/introspection/counter/). It provides a `display()` and a `step()` method. ## Typical Showcase In the following example, the `mycounter` inherits the first level from `heading` (but not deeper levels). ```typ #import "@preview/rich-counters:0.1.0": * #set heading(numbering: "1.1") #let mycounter = richcounter(identifier: "mycounter", inherited_levels: 1) // DOCUMENT Displaying `mycounter` here: #context (mycounter.display)("1.1") = First level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") = Another first level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") == Second level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") = Aaand another first level heading Displaying `mycounter` here: #context (mycounter.display)("1.1") Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)("1.1") ``` ![](example.png) ## Construction of a `richcounter` To create a `richcounter`, you have to call the `richcounter(...)` function. It accepts three arguments: - `identifier` (required) This must be a `string` which identifies the counter. The string must be unique. - `inherited_levels` This specifies how many levels should be inherited from the parent counter. - `inherited_from` (Default: `heading`) This specifies the parent counter. Can be a `richcounter`, a `counter`, or anything that is accepted by the `counter(...)` constructor. If not specified, defaults to `heading` (and hence it will inherit from the counter of the headings). If it's a `richcounter` and `inherited_levels` is _not_ specified, then `inherited_levels` will default to one level higher than the given `richcounter`. For example, the following creates a `richcounter` `foo` which inherits one level from the headings, and then another `richcounter` `bar` which inherits two levels (implicitly) from `foo`. ```typ #import "@preview/rich-counters:0.1.0": * #let foo = richcounter(identifier: "foo", inherited_levels: 1) #let bar = richcounter(identifier: "bar", inherited_from: foo) ``` ## Usage of a `richcounter` You use your constructed `richcounter` through its `step` and `display` functions. - `display(numbering_style)` (needs `context`) This displays the current value of the counter - `step(depth: 1)` This steps the counter at the specified `depth` (default: `1`). That is, it steps the `richcounter` at level `inherited_levels + depth`. **Due to a Typst limitation, you have to put parentheses before you put the arguments. (See below.)** For example, the following displays `mycounter` and then steps it (at depth 1). ```typ #import "@preview/rich-counters:0.1.0": * #let mycounter = richcounter(...) #context (mycounter.display)("1.1") #(mycounter.step)() ``` ## Roadmap - use Typst custom types as soon as they become available - adopt native Typst implementation of dependent counters as soon it becomes available
https://github.com/antonWetzel/Masterarbeit
https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/deckblatt.typ
typst
#import "setup.typ": * #align(center, { set text(size: 1.25em) text(size: 3em, [*Masterarbeit*]) v(0.5fr) { set align(left) set par(justify: true) align(center, pad(x: 2cm, [ *Berechnung von charakteristischen Eigenschaften von botanischen Bäumen mithilfe von 3D-Punktwolken.* ])) } v(1fr) table( columns: (0.7fr, 1fr), column-gutter: 0.2cm, align: (right, left), stroke: none, [*Name:*], [*<NAME>*], [E-Mail:], link("mailto:<EMAIL>", [<EMAIL>]), [Matrikelnummer:], [60451], [Studiengang:], [Informatik Master], [], [], [*Betreuer:*], [*<NAME>*], [E-Mail:], link("mailto:<EMAIL>", [<EMAIL>]), [], [], [*Professor:*], [*Prof. Dr.-Ing. <NAME>*], [E-Mail:], link("mailto:<EMAIL>", [<EMAIL>]), [], [], [Fachgebiet:], [Data-intensive Systems and Visualization Group], [], [], [Datum:], datetime.today().display("[day].[month].[year]"), ) v(2fr) image(width: 70%, "../images/logo_tui.svg") pagebreak() })
https://github.com/ceopaludetto/curriculum
https://raw.githubusercontent.com/ceopaludetto/curriculum/main/README.md
markdown
# Curriculum This is my curriculum source code. It is written in [Typst](https://github.com/typst/typst) a new markup-based typesetting system that is powerful and easy to learn. ## How to generate the PDF To generate the PDF, you need to have the [Tinymist Typst VSCode extension](https://github.com/Myriad-Dreamin/tinymist) installed. After that, open the [index.typ](./index.typ) file and click on the `show exported PDF` button. ## How to add new content To add new content, you need to edit the [index.typ](./index.typ) file or edit the static data in the [locales](./locales) folder. ## How to change the generated language To change the generated language, you need to edit the [index.typ](./index.typ) file and change the `language` variable in the first line. This will import the correct locale file.
https://github.com/Enter-tainer/m-jaxon
https://raw.githubusercontent.com/Enter-tainer/m-jaxon/master/typst-package/mj.typ
typst
MIT License
#import "@preview/jogs:0.2.2": compile-js, call-js-function #let mj-src = read("./mj.js") #let mj-bytecode = compile-js(mj-src) #let natural-image(..args) = style(styles => { let (width, height) = measure(image.decode(..args), styles) image.decode(..args, width: width, height: height) }) #let get-text(src) = { if type(src) == str { src } else if type(src) == content { src.text } } #let render(src, inline: false) = style(styles => { let src = get-text(src) let (width, height) = measure(h(1em), styles) let size = width let passed-size = size / 1.21 // katex is 1.21x larger, I dont find things about mathjax but it seems to be the same // https://katex.org/docs/font let result = call-js-function(mj-bytecode, "mj", src, inline, passed-size.pt()) let img = natural-image(result.svg, format: "svg") let ex = result.vertical_align if inline { box(move(box(img), dy: -ex * 0.5em)) } else { align(center, img) } })
https://github.com/pluttan/asmlearning
https://raw.githubusercontent.com/pluttan/asmlearning/master/dz2/dz2.typ
typst
#import "@docs/bmstu:1.0.0":* #show: student_work.with( caf_name: "Компьютерные системы и сети", faculty_name: "Информатика и системы управления", work_type: "домашней работе", work_num: "2", discipline_name: "Машинно-зависимые языки и основы компиляции", theme: "Лексические и синтаксические анализаторы", author: (group: "ИУ6-42Б", nwa: "<NAME>"), adviser: (nwa: "<NAME>"), city: "Москва", table_of_contents: true, ) = Задание == Цель работы Закрепление знаний теоретических основ и основных методов приемов разработки лексических и синтаксических анализаторов регулярных и контекстно-свободных формальных языков. == Задание Разработать грамматику и распознаватель имени процедуры для языка программирования C++. Считать, что параметры только стандартных (скалярных) типов. Например: ```cpp void f1(int a; float b; double c);``` = Выполнение == Форма Бекуса-Наура ``` <Буква> ::= a|b|…|z|A|B|…|Z <Цифра> ::= 0|1|2|...|9 <Идентификатор> ::= <Буква>|<Идентификатор><Буква>| <Идентификатор><Цифра> <Тип> ::= char|signed char|unsigned char|short|signed short| unsigned short|int|signed int|unsigned int|long| signed long|unsigned long|long long|signed long long| unsigned long long|float|double|long double|wchar_t| char16_t|char32_t|bool <Аргумент> ::= <Тип> <Идентификатор> <Аргументы> ::= <Аргумент>;<Аргументы>|<Аргумент> <Процедура> ::= void <Идентификатор>(<Аргументы>);| void <Идентификатор>(); ``` == Синтаксическая диаграмма #img(image("1.png", width:100%), [Синтаксическая диаграмма]) == Определение типа грамматики Хомского Данная грамматика по классификации Хомского относится к грамматикам 3 типа, так как в описании присутствует только левосторонняя рекурсия (грамматика контекстно-независима так как в БНФ в левой части всегда один нетерминал). == Код для лексического анализа Напишем код для лексического анализа. Для упрощения анализа воспользуемся регулярными выражениями: с помощью них найдем начало процедуры, все аргументы и конец процедуры. #let dz2 = parserasm(read("dz2.py")) #code(funcstr(dz2, "def leks(string):"), "py", [Код для лексического анализа]) #code(funcstr(dz2, "def create_pattern(end_char):"), "py", [Код для поиска аргументов и символов после них]) Результатом лексического анализа будет являться строка, содержащая только символы разделения (я взял %), и некоторые токены, которыми мы заменили все терминалы, не терминалы и т.д. Таких токенов у меня получилось 6: `vd`,`fn`,`(_`,`id`,`)_`,`;_`. Последовательность этих токенов проверит синтаксический анализ, а на этапе лексического просто проверим, что в строке не осталось иных символов. #code(funcstr(dz2, "def checkleks(string):"), "py", [Код для проверки лексического анализа]) == Код для синтаксического анализа В синтаксическом анализе просто проверим последовательность идущих друг за другом символов: с начала необходим символ `vd` -- ```cpp void``` затем идентификатор-название функции `fn`, после терминал ( -- `(_`, потом должен идти или терминал ) `)_` или аргумент `id`, после аргумента идет тоже самое. после закрывающей скобки идет ; -- `;_`, затем никаких символов больше быть не должно, т.е. проверяем на пустую строку. #code(funcstr(dz2, "def syntax(string):"), "py", [Код для синтаксического анализа]) Как видно мы получили код для автомата, который переходит из одного состояния в другое, если ожидаемое состояние недостижимо, то автомат сразу возвращает ```py False``` == Проверка Для проверки напишем код: ```py inp = input("Введите входную строку: ") l = leks(inp) print("Результат лексического анализа: ", l) print("Результат проверки лексического анализа: ", checkleks(l)) print("Результат синтаксического анализа: ", syntax(l)) ``` Введем 3 входных строки и проверим результаты: #img(image("2.png", width:100%), [Проверка]) Как видно на скриншоте лексический и синтаксический анализы работают верно. == Вывод При выполнении домашнего задания были освоены методы компиляции и разработан лексический и синтаксический анализатор для формального языка. = Контрольные вопросы == Дайте определение формального языка и формальной грамматики Формальный язык L(A) – это совокупность допустимых предложений, составленных из A, где А - некоторый алфавит. Формальная грамматика – математическая система, определяющая язык посредством порождающих правил (правила продукции). == Как определяется тип грамматики по Хомскому? Грамматики по Хомскому различаются по набору правил, которые они используют В 3 типе допустимы левосторонняя и правосторонняя рекурсия, он контекстно-независим. Во 2 типе допустима вложенность, он контекстно-независим. В 1 типе допустимо все то, что в предыдущих типах и контекстная зависимость. В 0 типе допустимо все то, что в предыдущих типах и все остальные конструкции. == Поясните физический смысл и обозначения формы Бэкуса–Наура. БНФ связывает терминальные и нетерминальные символы. Обозначения: «::=» – «можно заменить на» и « | » – «или». == Что такое лексический анализ? Какие методы выполнения лексического анализа вы знаете? Лексический анализ - процесс преобразования исходной строки в последовательность однородных символов (токенов), которые используются на этапе синтаксического анализа для распознавания конструкций. Выполнять лексический анализ можно с помощью последовательного сравнения строк, или при помощи конечных автоматов. == Что такое синтаксический анализ? Какие методы синтаксического анализа вы знаете? К каким грамматикам применяются перечисленные вами методы? Синтаксический анализ - процесс распознавания конструкций языка в строке токенов. Для регулярных грамматик возможен синтаксический анализ при помощи конечных автоматов. Для КС-грамматик необходимо разработать автомат с магазинной памятью LL(k), LR(k). == Что является результатом лексического анализа? Результатом лексического анализа является строка, состоящая из токенов, или ошибка именования == Что является результатом синтаксического анализа? Результатом синтаксического анализа является распознавание заданной конструкции или информация о наличии ошибки. == В чем заключается метод рекурсивного спуска? Метод рекурсивного спуска заключается в распознавании аксиомы, вызова соответствующей процедуры, которая вызывает процедуру нетерминала, которые вызывают процедуру аксиомы и т.д. Это обеспечивается рекурсивным вложением в правилах продукции грамматики. == Что такое таблица предшествования и для чего она строится? Таблица предшествования строится для сведения в удобную форму отношений предшествования терминалов с учетом приоритетов различных операций. Отношения предшествования характерны для грамматик, в которых существует однозначное отношение предшествования между соседними символами (оно позволяет определить очередную основу, т.е. момент выполнения каждой свёртки). Впоследствии на таблицах предшествования строится метод синтаксического анализа LR(k). == Как с использованием таблицы предшествования осуществляют синтаксический анализ В начале выполняется лексический анализ, получается строка токенов. После чего строка токенов разбирается в соответствие с таблицей предшествования. Далее с применением данной таблицы по стековому методу выявляются команды или операции или конструкции.
https://github.com/denkspuren/typst_programming
https://raw.githubusercontent.com/denkspuren/typst_programming/main/wrapText/wrapper.typ
typst
#set par( first-line-indent: 1em, justify: true, ) = This is a Header #lorem(100) #block( width: 30%, fill: luma(230), inset: 8pt, radius: 4pt, lorem(30), ) #lorem(100)
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/credits/linear-algebra-credit3.typ
typst
#import "../template.typ": * #import "../functions.typ": * #show: project.with( title: "线性代数 第三周 附加题", authors: ( (name: "memset0", email: "<EMAIL>", phone: ""), ), date: "October 9, 2023", ) = 附加题1 #prob[ #set math.mat(delim: "(") $ bold(A)&=(a_(i j))_(n times n)\ bold(B)&=mat( a_11,a_12b^(-1),a_13b^(-2),dots.c,a_(1n)b^(1-n); a_21b,a_22,a_23b^(-1),dots.c,a_(2n)b^(2-n); dots.v,dots.v,dots.v,,dots.v; a_(n 1)b^(n-1),a_(n 2)b^(n-2),a_(n 3)b^(n-3),dots.c,a_(n n); ) quad (b!=0)\ $ 已知 $|bold(A)|=t$,求 $|bold(B)|$. ] = 附加题2 #set math.mat(delim: "|") #prob[ 计算:$ D_n = mat( 1,1,1,dots.c,1,1,1; 0,0,0,dots.c,0,2,1; 0,0,0,dots.c,3,0,1; dots.v,dots.v,dots.v,,dots.v,dots.v,dots.v; 0,n-1,0,dots.c,0,0,1; n,0,0,dots.c,0,0,1; ) $ ] = 附加题3 #prob[ 计算:$ D_n = mat( a_1+b_1,a_2,dots.c,a_n; a_1,a_2+b_2,dots.c,a_n; dots.v,dots.v,,dots.v; a_1,a_2,dots.c,a_n+b_n; ) $ ] = 附加题4 #prob[ 计算:$ D_n = mat( 1,2,3,dots.c,n-1,n; 2,3,4,dots.c,n,1; 3,4,5,dots.c,1,2; dots.v,dots.v,dots.v,,dots.v,dots.v; n-1,n,1,dots.c,n-3,n-2; n,1,2,dots.c,n-2,n-1; ) $ ] = 附加题5 #prob[ 将 $n$ 阶矩阵 $bold(D)$ 的每个元素减去其同行其余元素之和,得到 $bold(D_1)$,若 $|bold(D)|=t$,求 $|bold(D_1)|$. ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/013%20-%20Magic%202015/009_The%20Lunarch's%20Journal.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Lunarch's Journal", set_name: "Magic 2015", story_date: datetime(day: 13, month: 08, year: 2014), author: "<NAME>", doc ) #emph[On the plane of Innistrad, the angel Avacyn has returned to guide her faithful worshipers, pushing back the darkness that ruled the plane while she was sealed away. The plane's monsters are in retreat, the church is resurgent, and everywhere humanity is stepping back into the light.] #emph[But not all is well on Innistrad. Even in the light, some secrets should remain hidden. Especially secrets about Avacyn herself...] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It has been years since I have held a quill, but I am compelled to record the terrible secret I have discovered, and how it came to my hands. I would be killed for this heresy, and although I have no fear of death, it may be a preferable fate. For this is madness, surely, a vacuum of truth where I am now sealed. I am Dovid, once a cathar of the Pale, grievously wounded at the battle of Child's Wall, now comitant to the angels of the Lofts. My memories of the battle are only pieces—the shattered blade of my hanger as I wrenched it from a living corpse; the taste of my own blood as I fell; a silence in which I knew death was certain; and then a blinding light when, at last, Avacyn appeared. #figure(image("009_The Lunarch's Journal/01.jpg", width: 100%), caption: [Avacyn, Angel of Hope | Art by Jason Chan], supplement: none, numbering: none) My right arm was a hideous ruin and I was triaged to the cathedral courtyard, where I lay feverish under a canvas tent, visited by a cleric who became more optimistic each morning he found me still breathing. At first, I was unable to move, but even as the cries of victory echoed against the high stone walls, I simply lacked the will. I would have lain there forever, had she not come for me. The moans of the wounded became like the coos of babies comforted by their mothers. I had been numb to all care, but even before I heard her voice something stirred within me, and I turned my face to the sky. Avacyn was there, flanked by a minor angel of the Flight of Herons. "You have given us hard service, and suffered more than most, but we have further need of you. Stand now, Dovid of the Pale." Her voice was without tenderness, yet I was filled with love, and I rose as if weightless. "The Lofts of Thraben Cathedral have long been abandoned, but we will soon return. You, and you alone, must prepare that space previously forbidden. Could you refuse us?" I shook my head, slowly, then caught myself. "No, never. I am your servant, and your will is mine." Her eyes were like pearls too beautiful to behold. "So it is. This is Gryta." The angel at her side stepped forward, a full head shorter than Avacyn, yet I still tilted my head to look upon her face. "She will show you the way, and relay our instructions in the days to come." And without pause or ceremony, Avacyn took to wing, silently, like an owl. Gryta regarded me with the curiosity that one might give to a piece of fruit with a unique deformity. "So, Cathar, do you know that spot, high on the wall where there should be a window?" She gestured with her wing, and I saw it at once: a single arch, bricked over. "Meet me there and I will show you how to enter the Lofts." There was a rush of air, and then she too was in the air far above me. #figure(image("009_The Lunarch's Journal/02.jpg", width: 100%), caption: [Seraph of Dawn | Art by <NAME>], supplement: none, numbering: none) That is how I became Comitant Dovid. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It is strange how the position has distanced me from the cathars and other officials of the church. I'm envied at least as much as I am honored, and mistrusted as much as I am respected. I carry the first sword forged from the remains of the Helvault, and I walk the upper halls of Thraben like a ghost. There are times when I go for days without speaking a single word aloud. The angels are wondrous and powerful beings, but it is in the presence of their beauty where I am the most alone. In the Lofts, they sing wordlessly, their voices like chimes. The Flights have separate mantras which can't be spoken with a human tongue, a sound I have often mistaken for rain. We find them easy to worship, and their power and beauty make it so, but they are not like us, you see, in any way other than form. For all the adulation we give to them, they are further from us than we are from an otter or a wren. Perhaps our adulation is what makes it so. It is only Gryta who speaks to me, and although her speech is flawless, I've come to believe that it's something she does deliberately, with great effort. I'm foolish to think that she favors me, but even now part of me believes it's true. On that first day, I searched for hours before finding the stairs that led me to the high rampart where Gryta waited. It was a sheer drop without a rail, and as I forced myself to look upon her, the fear must have been plain on my face. "You will not fall, Dovid." Her eyes were deep brown and seemed wholly human. "Or, if you fall, I will catch you. Lay your hands upon these stones, here and here." I did as she directed, and she murmured in the angelic tongue, something like an echo, or a coin spun inside a bottle. The bricked window folded into itself silently, and it seemed as natural as the opening of a door. #figure(image("009_The Lunarch's Journal/03.jpg", width: 100%), caption: [Seraph Sanctuary | Art by <NAME>], supplement: none, numbering: none) "There are many ways to enter the Lofts from inside the cathedral, and all of them will recognize you now." I expected the air to be stale, but it was light and sweet. "Clear the cistern first. I will know when you have finished." I turned to acknowledge her command, maybe stammer some thanks, but she was already falling, tumbling toward the ground before shooting aloft again, over the roof, then gone. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The fragments of Helvault were collected after it split, and the raw silver ore was distributed among the most distinguished lunar smiths. A family of swords were forged from that metal, and Gryta dictated a list of names she had received from Avacyn, persons who were to be honored at a fete where the Flights presided. When we were finished, Gryta added in what seemed like an afterthought, "And your name as well, Dovid. Put it at the top." Mine is a mortuary sword, with a sculpted basket where the wings of Avacyn's visage reach into the ricasso. Between those wings my sword's name is etched: Eost. I have drawn it only once, during the ceremony where it was presented to me, when Avacyn touched its point. It is as light as air, and sharp enough to halve a river stone, but I doubt I will ever wield it. My arm is near useless, and I am cloistered here. #figure(image("009_The Lunarch's Journal/04.jpg", width: 100%), caption: [Elder Cathar | Art by Chris Rahn], supplement: none, numbering: none) Eost rests in a case above my desk, but I found my eye had strayed again to the source of my torment. Below my sword, and next to the journal in which I now write is another, remarkably similar, written in a precise and feminine hand. The frontispiece is an exquisite illumination of Avacyn's collar, and on the opposite page is a name: <NAME>, Lunarch. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Lofts were in good repair, and the spirits that haunted them during the angels' absence fled from me when I entered. The cistern is massive, and when Gryta commanded me to clear it, I imagined that its source would be somehow obstructed. Instead, I found it filled with clear water, lit from within and glowing like the face of the moon. Half submerged in the basin was the body of a man dressed in black, and I knew it was what I had been sent for. He had been strangled, and although there were no signs of rot, he was murdered some time before, but was then preserved by the waters of the Lofts. When I wrestled him onto the cool stone, the book was dislodged from inside his coat. I had no way to know what it contained, who had been its author, or why it was there in the possession of a dead man, and I was filled with dread. Something had been interrupted there, some evil plan thwarted, and I was now its witness. #figure(image("009_The Lunarch's Journal/05.jpg", width: 100%), caption: [Vault of the Archangel | Art by <NAME>], supplement: none, numbering: none) I had the body sealed in a nameless crypt deep inside the catacombs and returned to my quarters with the book. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The journal was bound with a spell I recognized as of the Nightfall Cathars, and a moon passed before I solved it. Initially, I was joyous to have found such an artifact, and I told myself that I would announce the discovery after I familiarized myself with its contents. I wasn't surprised by first revelation: Avacyn had been sealed in the Helvault with the demon Griselbrand, and during that time our power had diminished. This was known only to Mikaeus and the highest Devisers, a secret they kept to prevent unrest in the congregation. #figure(image("009_The Lunarch's Journal/06.jpg", width: 100%), caption: [Helvault | Art by Jaime Jones], supplement: none, numbering: none) But the passage that pushed me toward apostasy was far worse. #emph[Countless eons ago, <NAME> brokered the blasphemy that created his foul race of vampires. With the demon Shilgengar, they devised a formula to transform living men into these monsters that fed upon their own brothers and sisters. The key ingredient was the blood of a living angel...] #emph[...Markov and his sons trapped the angel Marycz in his laboratory and exsanguinated her before preparing the unholy decoction that set in motion a cycle of fear and predation that we suffer under today.] The curse of the vampire that we have been trained to fight was created by humans themselves. I had thought us noble, the race that carried the light against our world's evil. Were we worth defending? #figure(image("009_The Lunarch's Journal/07.jpg", width: 100%), caption: [<NAME> | Art by <NAME>iak], supplement: none, numbering: none) I worried over this even as I descended deeper into the secrets of the church Mikaeus had put down. Would I have stopped then if I knew the magnitude of deception I would find? #emph[Humans were fighting a losing battle. The vampires were simply too powerful, and after generations of multiplication, they had come to nearly outnumber us.] #emph[Each battle the vampires won, each human life they took, served to weaken them, whereas our own victories were victories for us both. This war was not between human and vampire. We were allies against a common foe: the vampires' own hunger.] #emph[It is a cruel symmetry that our salvation was born of the Markov family, <NAME>, a creature so ancient and powerful that he survives even today. Seeing that our destruction and theirs were inexorably linked, Sorin created Avacyn, a force to rally our remaining angels, a force that we could unite under.] #figure(image("009_The Lunarch's Journal/08.jpg", width: 100%), caption: [Sorin, Lord of Innistrad | Art by Chase Stone], supplement: none, numbering: none) #emph[A force constructed to hold in check the very vampires who created her.] #emph[From there, the church was designed to give us the power to protect and grow our numbers, but not enough to ever bring us victory over those that fed on us...] We are livestock. We are unwitting participants in our own cultivation. The church to which I have dedicated my life, the being that I have loved since birth, the boundaries of my world, all of it is a sinister lie. How strange this world is, and how cruel. #figure(image("009_The Lunarch's Journal/09.jpg", width: 100%), caption: [Avacyn, Guardian Angel | Art by <NAME>], supplement: none, numbering: none)
https://github.com/QuadnucYard/cpp-coursework-template
https://raw.githubusercontent.com/QuadnucYard/cpp-coursework-template/main/cody.typ
typst
// cody.typ #import "@preview/codelst:2.0.1": sourcecode, codelst #import "font.typ": fonts #let codify-state = state("codify-lang", none) /// Add boxes to raw contents. /// /// - doc (any): The document. /// -> content #let raw-style(doc) = { show raw.line: set text(font: fonts.mono) show raw.where(block: true): it => { if it.lang == none or it.lang == "none" { block(width: 100%, radius: 2pt, fill: rgb("#f8f8f8"), stroke: 0.5pt + rgb("#ddd"), inset: 0.5em, it) } else { set raw(lang: none) sourcecode(it) } } show raw.where(block: false): it => { if it.has("lang") and it.lang != none { box(inset: (left: 0.2em, right: 0.2em), box(radius: 2pt, fill: rgb(50%, 50%, 50%, 10%), outset: 0.2em, it)) } else { it } } doc } /// Make raw contents have the default language. /// /// - lang (string): The language. /// -> content #let codify(body, lang: "cpp") = { set raw(lang: lang) body } #let codify-enable(lang: "cpp") = { codify-state.update(lang) } #let codify-disable() = { codify-state.update(none) } /// Make a code block from text slice. /// /// - start (integer string none): The start line (from 1). If none, slice from the first line. /// - end (integer string none): The end line (from 1). If none, slice to the last line. /// - count (integer none): Number of lines from start. If none, all lines will be kept. /// - region (string none): The prefix of start and end. /// - lang (string): The language to use. /// -> content #let cody(txt, start: none, end: none, count: none, region: none, lang: "cpp", font-size: auto) = { let a = txt.split("\n") if region != none and lang == "cpp" { start = "#pragma region " + region end = "#pragma endregion " + region } if end != none { if type(end) == str { let _end = end end = a.position(x => x.contains(_end)) assert(end != none, message: "Fail to find region end '" + _end + "'") } a = a.slice(0, end) } if start != none { if type(start) == str { let _start = start start = a.position(x => x.contains(_start)) assert(start != none, message: "Fail to find region start '" + _start + "'") start += 2 } a = a.slice(start - 1) } if count != none { a = a.slice(0, count) } txt = a.join("\n") if font-size == auto { raw(txt, block: true, lang: lang) } else { show raw.line: set text(size: font-size) raw(txt, block: true, lang: lang) } /* sourcecode( raw(text, block: true, lang: lang), numbers-start: if start != none { start } else { 1 } ) */ }
https://github.com/isaacadams/typst-template
https://raw.githubusercontent.com/isaacadams/typst-template/main/README.md
markdown
# Welcome to your Typst Environment This is a template repo for when you are working with typst. ## Getting Started ### 1. create a new repo based on this template ```bash gh repo create my-typst-app --public --template isaacadams/typst-template ``` - `my-typst-app` &nbsp; replace with whatever name you want for your repo - `--public` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; `--private` or `--internal` are also valid choices ### 2. open the project using devcontainers (this can optionally be done via vscode's UI) #### install devcontainers cli tool ```bash npm install -g @devcontainers/cli ``` #### startup command: ```bash devcontainer up --workspace-folder . ``` ### 3. open a terminal, run `typst` and see the options ### 4. See example in `example.typ` ```typ #emph[Hello] \ #emoji.face \ #"hello".len() #let (x, y) = (1, 2) The coordinates are #x, #y. #let (a, .., b) = (1, 2, 3, 4) The first element is #a. The last element is #b. #let books = ( Shakespeare: "Hamlet", Homer: "The Odyssey", Austen: "Persuasion", ) #let (Austen,) = books Austen wrote #Austen. #let (Homer: h) = books Homer wrote #h. #let (Homer, ..other) = books #for (author, title) in other [ #author wrote #title. ] ``` ### 5. run the following to compile ```bash typst compile example.typ ``` ## Documentation - typst docs: https://typst.app/docs/ - typst github: https://github.com/typst/typst
https://github.com/galaxia4Eva/galaxia4Eva
https://raw.githubusercontent.com/galaxia4Eva/galaxia4Eva/main/typst/Idi%20Naxui/document.typ
typst
#set page(height: 1028pt, width: 720pt, background: image("./images/IMG_7451.jpeg")) #align(center+bottom)[ #image("./images/IMG_7448.jpeg") ]
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/substitution/amiri-beh.typ
typst
Other
#import "/lib/draw.typ": * #import "/template/lang.typ": arabic-amiri #let start = (0, 0) #let end = (300, 140) #let graph = with-unit((ux, uy) => { // mesh(start, end, (50, 50)) txt([关闭ss01:#arabic-amiri()[ربن]], (0, 130), anchor: "lt", size: 42 * ux) txt([开启ss01:#arabic-amiri(text(features: ("ss01",))[ربن])], (0, 60), anchor: "lt", size: 42 * ux) }) #canvas(end, width: 40%, graph)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/jogs/0.2.0/README.md
markdown
Apache License 2.0
# Jogs Quickjs javascript runtime for typst. This package provides a typst plugin for evaluating javascript code. ## Example ````typst #import "@preview/jogs:0.2.0": * #set page(height: auto, width: auto, fill: black, margin: 1em) #set text(fill: white) #let code = ``` function sum() { const total = Array.prototype.slice.call(arguments).reduce(function(a, b) { return a + b; }, 0); return total; } function string_join(arr) { return arr.join(" | "); } function return_complex_obj() { return { a: 1, b: "2", c: [1, 2, 3], d: { e: 1, }, }; } ``` #let bytecode = compile-js(code) #list-global-property(bytecode) #call-js-function(bytecode, "sum", 6, 7, 8, 9, 10) #call-js-function(bytecode, "string_join", ("a", "b", "c", "d", "e"),) #call-js-function(bytecode, "return_complex_obj",) ```` result: ![](typst-package/examples/fib.svg) ## Documentation This package provide following function(s): ### `eval-js` Run a Javascript code snippet. #### Arguments * `code` - The Javascript code to run. It can be a string or a raw block. #### Returns The result of the Javascript code. The type is the typst type which most closely resembles the Javascript type. #### Example ```typ #let result = eval-js("1 + 1") ``` ### `compile-js` Compile a Javascript code snippet into bytecode. #### Arguments * `code` - The Javascript code to compile. It can be a string or a raw block. #### Returns The bytecode of the Javascript code. The type is `bytes`. #### Example ```typ #let bytecode = compile-js("function sum(a, b) { return a + b; }") ``` ### `call-js-function` Call a Javascript function with arguments. #### Arguments * `bytecode` - The bytecode of the Javascript function. It can be obtained by calling `compile-js`. * `name` - The name of the Javascript function. * `..args` - The arguments to pass to the Javascript function. All other positional arguments are passed to the Javascript function as is. #### Returns The result of the Javascript function. The type is the typst type which most closely resembles the Javascript type. #### Example ```typ #let bytecode = compile-js("function sum(a, b) { return a + b; }") #let result = call-js-function(bytecode, "sum", 1, 2) ``` ### `list-global-property` List all global properties of a compiled Javascript bytecode. This is useful for inspecting the compiled Javascript bytecode. #### Arguments * `bytecode` - The bytecode of the Javascript function. It can be obtained by calling `compile-js`. #### Returns A list of all global properties of the Javascript bytecode. The type is `array`. #### Example ```typ #let bytecode = compile-js("function sum(a, b) { return a + b; }") #let result = list-global-property(bytecode) ```
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/daisyui.typ
typst
#import "/components/glossary.typ": gls == Daisy UI <sec-daisyui> Daisy UI is a popular component library built on top of Tailwind CSS (@sec-tailwindcss), offering a collection of pre-built #gls("ui") components and utilities that can accelerate web development. This literature review will explore the key features, benefits, and considerations of using Daisy UI in your projects. Daisy UI is a valuable tool for web developers who want to accelerate their development process while maintaining a high level of design quality and accessibility. Its integration with Tailwind CSS provides a powerful and flexible solution for building modern web applications. By carefully considering the benefits and challenges, you can determine if Daisy UI is the right choice for your project @bib-daisyui. === Key Features of Daisy UI - *Tailwind CSS Foundation*: Daisy UI is built on the solid foundation of Tailwind CSS, providing a utility-first approach to styling and customization. - *Pre-built Components*: Daisy UI offers a wide range of pre-built components, including buttons, forms, modals, and navigation elements, to streamline development. - *Theming*: Daisy UI provides a flexible theming system, allowing you to customize the appearance of components to match your design preferences. - *Accessibility*: Daisy UI is designed with accessibility in mind, ensuring that your web applications are accessible to users with disabilities. - *Responsiveness*: Daisy UI components are designed to be responsive, adapting to different screen sizes and devices. === Benefits of Using Daisy UI - *Increased Development Speed*: Daisy UI's pre-built components and utility classes can significantly speed up your development process. - *Consistent Design*: Using Daisy UI helps ensure a consistent and visually appealing design across your web application. - *Accessibility*: Daisy UI's focus on accessibility helps make your web applications more inclusive. - *Customization*: Daisy UI's theming system allows you to customize the appearance of components to match your brand and design preferences. - *Integration with Tailwind CSS*: Daisy UI seamlessly integrates with Tailwind CSS (@sec-tailwindcss), providing a powerful combination of utility-first styling and pre-built components.
https://github.com/davawen/Cours
https://raw.githubusercontent.com/davawen/Cours/main/typst/physique/0.1.0/elec.typ
typst
#import "utils.typ": * #let tenselr(label, rev: false, size: 0) = { (label: label, rev: rev, size: size) } #let tenserl(label, rev: false, size: 0) = { (label: label, rev: not rev, size: size) } #let tension(from, to, offset, tense, size: 0.7) = { import draw: * let midpoint = (from, 50%, to) let from = (midpoint, size + tense.size, from) let to = (midpoint, size + tense.size, to) if tense.rev == true or tense.rev == 1 { (from, to) = (to, from) } group({ line((rel: offset, to: from), (rel: offset, to: to), mark: (end: "straight"), name: "line") content((rel: ((0, 0), 0.3, offset), to: "line.50%"), tense.label) }) } #let maille(pos, size, rev: false, anchor: none) = { import draw: * group({ set-origin(pos) if rev { arc((0, 0), start: -60deg, stop: -315deg, radius: size, mark: (end: "straight"), anchor: "origin") } else { arc((0, 0), start: 45deg, stop: 300deg, radius: size, mark: (end: "straight"), anchor: "origin") } }) } #let resistor(pos, rot: 0deg, u: none, label: none, name: none, size: 0.5) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) rect((-size, -size/2), (size, size/2)) anchor("l", (-size, 0)) anchor("r", (size, 0)) if label != none { content((rel: (0, 0.8em), to: (0, size/2)), label, angle: rot) } if u != none { tension("l", "r", (0, -0.6), u) } }) } #let fil(a, b, rev: false, straight: true, i: none, ..points) = { import draw: * let intensity = i let points = (a, b, ..points.pos()) if straight { for (a, b) in points.chunks(2, exact: true) { if rev == true or rev == 1 { line(a, (a, "|-", b), name: "__first") line((a, "|-", b), b) } else { line(a, (a, "-|", b), name: "__first") line((a, "-|", b), b) } if intensity != none { mark("__first.50%", ("__first.50%", 0.2, "__first.51%"), symbol: ">", fill: black) content((rel: (0, 0.8em), to: "__first.50%"), intensity) } } } else { for (a, b) in points.chunks(2, exact: true) { line(a, b, name: "__first") if intensity != none { mark("__first.50%", "__first.51%", symbol: ">", fill: black) content((rel: (0, 0.8em), to: "__first.50%"), intensity) } } } } #let ground(pos, rot: 0deg, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) anchor("l", (0, 0)) anchor("r", (0, 0)) line((0, 0), (0, -0.5)) line((-0.3, -0.5), (0.3, -0.5)) line((-0.2, -0.6), (0.2, -0.6)) line((-0.1, -0.7), (0.1, -0.7)) }) } #let node(pos, offset: (-0.5em, 0.8em), id: none, name: none, round: false) = { import draw: * if id == none { id = name } group(name: id, { set-origin(pos) if round { circle((0, 0), radius: 0.07, fill: black) } anchor("default", (0, 0)) anchor("l", (0, 0)) anchor("r", (0, 0)) if name != none { let label = eval("$" + name + "$") content(offset, label) } }) } #let pile(pos, rot: 0deg, rev: false, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) let (plus, minus) = (0.1, -0.1) if (rev) { plus = -0.1 minus = 0.1 } line((minus, -0.2), (minus, 0.2)) line((plus, -0.3), (plus, 0.3)) content((1.5*minus, 0.3), "-", anchor: "south", padding: 3pt) content((1.5*plus, 0.3), "+", anchor: "south", padding: 3pt) line((minus, 0), (3*minus, 0)) line((plus, 0), (3*plus, 0)) anchor("l", (3*minus, 0)) anchor("r", (3*plus, 0)) }) } #let elem-letter(pos, letter: $G$, rot: 0deg, u: none, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) circle((0, 0), radius: 0.4) content((0, 0), letter) anchor("l", (-0.4, 0)) anchor("r", (0.4, 0)) if u != none { tension("l", "r", (0, -0.6), u) } }) } #let generateur = elem-letter.with(letter: $G$) #let voltmetre = elem-letter.with(letter: $V$) #let amperemetre = elem-letter.with(letter: $A$) #let source-ideale(pos, rot: 0deg, label: none, u: none, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) circle((0, 0), radius: 0.4) anchor("l", (-0.4, 0)) anchor("r", (0.4, 0)) line("l", "r") if label != none { tension("l", "r", (0, 0.6), label, size: 0.4) } if u != none { tension("l", "r", (0, -0.6), u) } }) } #let source-ideale-courant(pos, rot: 0deg, label: none, u: none, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) circle((0, 0), radius: 0.4) anchor("l", (-0.4, 0)) anchor("r", (0.4, 0)) line((0, 0.4), (0, -0.4)) if label != none { tension("l", "r", (0, 0.6), label, size: 0.4) } if u != none { tension("l", "r", (0, -0.6), u) } }) } #let bobine(pos, rot: 0deg, coils: 4, u: none, label: none, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) anchor("l", (-0.3*(coils/2+1), 0)) anchor("r", (0.3*(coils/2+1), 0)) if label != none { content((0, 0.5), label) } if u != none { tension("l", "r", (0, -0.5), u) } line("l", (-0.3*coils/2, 0)) line("r", (0.3*coils/2, 0)) translate((-0.3*(coils/2) + 0.3, 0)) for i in range(coils) { arc((0, 0), start: 0deg, stop: 180deg, radius: 0.15) translate((0.3, 0)) } }) } #let condensateur(pos, rot: 0deg, u: none, name: none) = { import draw: * group(name: name, { set-origin(pos) rotate(rot) let (plus, minus) = (0.1, -0.1) line((minus, -0.5), (minus, 0.5)) line((plus, -0.5), (plus, 0.5)) line((minus, 0), (3*minus, 0)) line((plus, 0), (3*plus, 0)) anchor("l", (3*minus, 0)) anchor("r", (3*plus, 0)) if (u != none) { tension("l", "r", (0, 0.7), u) } }) } #let apply(f, ..args) = { (f: f, pos: args.pos(), named: args.named()) } /// Use apply to create an element for this method /// Example: /// ```typst /// derivation((0, 0), /// apply(resistlr, name: "d1"), /// apply(ground, rot: 45deg) /// ) /// ``` #let derivation(pos, rot: 0deg, left: none, right: none, width: 5, inset: 1, i: none, u: none, name: none, ..elems) = { import draw: * let elems = elems.pos() group(name: name, { set-origin(pos) rotate(rot) anchor("l", (-width/2, 0)) anchor("r", (width/2, 0)) node((-width/2 + 1, 0), id: "ln", name: left, round: true) node((width/2 - 1, 0), id: "rn", name: right, round: true) fil("l", "ln", i: i) fil("r", "rn", i: i) if u != none { tension("l", "r", (0, inset * (elems.len())/2), u, size: width/4) } for (i, elem) in elems.enumerate() { let (f, pos: positional, named) = elem if (named.at("name", default: none) == none) { named.insert("name", "__tmpname") } let name = named.at("name") f((0, inset * ((elems.len() + 1)/2 - i - 1)), ..positional, ..named) fil(name + ".l", "ln") fil(name + ".r", "rn") } }) } #let serie(pos, rot: 0deg, inset: 1.8, left: none, right: none, u: none, i: none, name: none, ..elems) = { import draw: * let elems = elems.pos() let get_name(i) = { let name = elems.at(i).at("named").at("name", default: none) if (name == none) { return "__tmpname" + str(i) } else { return name } } group(name: name, { set-origin(pos) rotate(rot) node((-inset * (elems.len()+1)/2, 0), id: "l", name: left) node((inset * (elems.len()+1)/2, 0), id: "r", name: right) for (i, elem) in elems.enumerate() { let (f, pos: positional, named) = elem named.insert("name", get_name(i)) f((-inset * ((elems.len() + 1)/2 - i - 1), 0), ..positional, ..named) } if elems.len() > 0 { fil("l", get_name(0) + ".l", i: i) fil(get_name(elems.len()-1) + ".r", "r", i: i) } else { fil("l", "r", i: i) } for i in range(1, elems.len()) { let a = get_name(i - 1) let b = get_name(i) fil(a + ".r", b + ".l") } if u != none { tension("l", "r", (0, -1.2), u, size: inset*(elems.len()-1)) } }) } /// iterates f with windows from the list: /// `windows((1, 2, 3), 2, f)` /// will call f with 1, 2 and 2, 3 /// NOTE: the function is called variadically /// in this case, it should be `(a, b) => { ... }` and not `((a, b)) => { ... }` #let windows(list, size, f) = { for i in range(0, list.len()+1-size) { f(..list.slice(i, count: size)) } } /// fonction à utiliser avec `carre` /// pour créer une branche dans un circuit #let branch(top: none, down: none, u: none, ..elems) = { let r = (branch: elems.pos()) if top != none { r.top = top } if down != none { r.down = down } if u != none { r.u = u } r } #let carre(pos, rot: 0deg, inset: 1.8, left: none, right: none, u: none, i: none, name: none, ..elems) = { import draw: * let elems = elems.pos() let get_name(params_named, i) = { let name = params_named.at("name", default: none) if (name == none) { return "__tmpname" + str(i) } else { return name } } let draw-connections(connections) = { for (a, b) in connections.chunks(2) { if type(a) == dictionary { let (co, i, rev) = a if rev == none { fil(co, b, i: i) } else { fil(b, co, i: i) } } else { fil(a, b) } } } group(name: name, { set-origin(pos) rotate(rot) let offset = inset/2 let ret-offset = 0 let max-height = inset*1.2 // on parcourt les éléments pour calculer le layout for elem in elems { if "branch" in elem { if type(elem.branch) != array { elem.branch = (elem.branch,) } let height = 0 for elem in elem.branch { if "inset" in elem { height = height + elem.inset } else { height = height + inset } } if height > max-height { max-height = height } } } let connections = ((offset, 0), ) let ret-connections = ((offset, -max-height), ) for (i, elem) in elems.enumerate() { if "branch" in elem { // on part en dérivation let branch-name = "__t" + str(i) anchor(branch-name, (offset, 0)) anchor("__d", (offset, -max-height)) if "top" in elem { node(branch-name, name: elem.top, round: true) } if "down" in elem { node("__d", name: elem.down, round: true) } if "u" in elem { tension(branch-name, "__d", (-0.6, 0), elem.u, size: max-height/3.0) } // on ajoute le haut de la branche en connection connections.push(branch-name) connections.push(branch-name) if type(elem.branch) != array { elem.branch = (elem.branch,) } // on définie une nouvelle liste de connections // pour la branche let connections = (branch-name,) let branch-offset = -inset/2 for (i, elem) in elem.branch.enumerate() { if "inset" in elem { branch-offset = branch-offset - elem.inset continue } let (f, pos: positional, named) = elem name = get_name(named, i) named.name = name connections.push(name + ".l") connections.push(name + ".r") f((offset, branch-offset), rot: -90deg, ..positional, ..named) branch-offset = branch-offset - inset } connections.push("__d") draw-connections(connections) if branch-offset > max-height { max-height = branch-offset } offset = offset + inset } else if "return" in elem { // branche de retour let (f, pos: positional, named) = elem name = get_name(named, i) named.name = name ret-connections.push(name + ".l") ret-connections.push(name + ".r") f((ret-offset, max-height), ..positional, ..named) ret-offset = ret-offset + inset } else if "i" in elem { let rev = elem.at("rev", default: none) let last = connections.last() connections.at(-1) = (co: last, i: elem.i, rev: rev) } else { // buisness as usual let (f, pos: positional, named) = elem name = get_name(named, i) named.name = name connections.push(name + ".l") connections.push(name + ".r") f((offset, 0), ..positional, ..named) offset = offset + inset } } connections.push((offset - inset, 0)) ret-connections.push((offset - inset, -max-height)) draw-connections(connections) draw-connections(ret-connections) // if elems.len() > 0 { // fil("l", get_name(0) + ".l", i: i) // fil(get_name(elems.len()-1) + ".r", "r", i: i) // } else { // fil("l", "r", i: i) // } // // for i in range(1, elems.len()) { // let a = get_name(i - 1) // let b = get_name(i) // // fil(a + ".r", b + ".l") // } // // if u != none { // tension("l", "r", (0, -1.2), u, size: inset*(elems.len()-1)) // } }) }
https://github.com/MrToWy/Bachelorarbeit
https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Code/injectUser.typ
typst
```ts @Injectable() export class InjectUser extends AuthGuard('jwt') { handleRequest(err: any, user: any) { return user; } } ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/syntax_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test Unicode math. $ ∑_(i=0)^ℕ a ∘ b = \u{2211}_(i=0)^NN a compose b $
https://github.com/mps9506/quarto-lapreprint
https://raw.githubusercontent.com/mps9506/quarto-lapreprint/main/template.typ
typst
MIT License
// Some definitions presupposed by pandoc's typst output. #let blockquote(body) = [ #set text( size: 0.92em ) #block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body] ] #let horizontalrule = [ #line(start: (25%,0%), end: (75%,0%)) ] #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #show terms: it => { it.children .map(child => [ #strong[#child.term] #block(inset: (left: 1.5em, top: -0.4em))[#child.description] ]) .join() } // Some quarto-specific definitions. #show raw.where(block: true): block.with( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt ) #let block_with_new_content(old_block, new_content) = { let d = (:) let fields = old_block.fields() fields.remove("body") if fields.at("below", default: none) != none { // TODO: this is a hack because below is a "synthesized element" // according to the experts in the typst discord... fields.below = fields.below.amount } return block.with(..fields)(new_content) } #let empty(v) = { if type(v) == "string" { // two dollar signs here because we're technically inside // a Pandoc template :grimace: v.matches(regex("^\\s*$")).at(0, default: none) != none } else if type(v) == "content" { if v.at("text", default: none) != none { return empty(v.text) } for child in v.at("children", default: ()) { if not empty(child) { return false } } return true } } // Subfloats // This is a technique that we adapted from https://github.com/tingerrr/subpar/ #let quartosubfloatcounter = counter("quartosubfloatcounter") #let quarto_super( kind: str, caption: none, label: none, supplement: str, position: none, subrefnumbering: "1a", subcapnumbering: "(a)", body, ) = { context { let figcounter = counter(figure.where(kind: kind)) let n-super = figcounter.get().first() + 1 set figure.caption(position: position) [#figure( kind: kind, supplement: supplement, caption: caption, { show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1)) show figure.where(kind: kind): set figure.caption(position: position) show figure: it => { let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1) show figure.caption: it => { num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug? [ ] it.body } quartosubfloatcounter.step() it counter(figure.where(kind: it.kind)).update(n => n - 1) } quartosubfloatcounter.update(0) body } )#label] } } // callout rendering // this is a figure show rule because callouts are crossreferenceable #show figure: it => { if type(it.kind) != "string" { return it } let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none) if kind_match == none { return it } let kind = kind_match.captures.at(0, default: "other") kind = upper(kind.first()) + kind.slice(1) // now we pull apart the callout and reassemble it with the crossref name and counter // when we cleanup pandoc's emitted code to avoid spaces this will have to change let old_callout = it.body.children.at(1).body.children.at(1) let old_title_block = old_callout.body.children.at(0) let old_title = old_title_block.body.body.children.at(2) // TODO use custom separator if available let new_title = if empty(old_title) { [#kind #it.counter.display()] } else { [#kind #it.counter.display(): #old_title] } let new_title_block = block_with_new_content( old_title_block, block_with_new_content( old_title_block.body, old_title_block.body.body.children.at(0) + old_title_block.body.body.children.at(1) + new_title)) block_with_new_content(old_callout, new_title_block + old_callout.body.children.at(1)) } // 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead #let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = { block( breakable: false, fill: background_color, stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"), width: 100%, radius: 2pt, block( inset: 1pt, width: 100%, below: 0pt, block( fill: background_color, width: 100%, inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) + if(body != []){ block( inset: 1pt, width: 100%, block(fill: white, width: 100%, inset: 8pt, body)) } ) } // This is the LaPreprint template licensed under MIT from: // - https://github.com/LaPreprint/typst #let quarto-lapreprint( // The paper's title. title: "Paper Title", subtitle: none, // An array of authors. For each author you can specify a name, orcid, and affiliations. // affiliations should be content, e.g. "1", which is shown in superscript and should match the affiliations list. // Everything but but the name is optional. authors: (), // This is the affiliations list. Include an id and `name` in each affiliation. These are shown below the authors. affiliations: (), // The paper's abstract. Can be omitted if you don't have one. abstract: none, // The short-title is shown in the running header short-title: none, // The short-citation is shown in the running header, if set to auto it will show the author(s) and the year in APA format. short-citation: auto, // The venue is show in the footer venue: none, // An image path that is shown in the top right of the page. Can also be content. logo: none, // A DOI link, shown in the header on the first page. Should be just the DOI, e.g. `10.10123/123456` ,not a URL doi: none, heading-numbering: "1.a.i", // Show an Open Access badge on the first page, and support open science, default is true, because that is what the default should be. open-access: true, // A list of keywords to display after the abstract keywords: (), // The "kind" of the content, e.g. "Original Research", this is shown as the title of the margin content on the first page. kind: none, // Content to put on the margin of the first page // Should be a list of dicts with `title` and `content` margin: (), paper-size: "us-letter", // A color for the theme of the document theme: blue.darken(30%), // Date published, for example, when you publish your preprint to an archive server. // To hide the date, set this to `none`. You can also supply a list of dicts with `title` and `date`. date: datetime.today(), // Feel free to change this, the font applies to the whole document font-face: none, // The path to a bibliography file if you want to cite some external works. bibliography-file: none, bibliography-style: "apa", // The paper's content. body ) = { /* Logos */ let orcidSvg = ```<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 24 24"> <path fill="#AECD54" d="M21.8,12c0,5.4-4.4,9.8-9.8,9.8S2.2,17.4,2.2,12S6.6,2.2,12,2.2S21.8,6.6,21.8,12z M8.2,5.8c-0.4,0-0.8,0.3-0.8,0.8s0.3,0.8,0.8,0.8S9,7,9,6.6S8.7,5.8,8.2,5.8z M10.5,15.4h1.2v-6c0,0-0.5,0,1.8,0s3.3,1.4,3.3,3s-1.5,3-3.3,3s-1.9,0-1.9,0H10.5v1.1H9V8.3H7.7v8.2h2.9c0,0-0.3,0,3,0s4.5-2.2,4.5-4.1s-1.2-4.1-4.3-4.1s-3.2,0-3.2,0L10.5,15.4z"/></svg>```.text let spacer = text(fill: gray)[#h(8pt) | #h(8pt)] let dates; if (type(date) == "datetime") { dates = ((title: "Published", date: date),) }else if (type(date) == "dictionary") { dates = (date,) } else { dates = date } date = dates.at(0).date // Create a short-citation, e.g. Cockett et al., 2023 let year = if (date != none) { ", " + date.display("[year]") } if (short-citation == auto and authors.len() == 1) { short-citation = authors.at(0).name.split(" ").last() + year } else if (short-citation == auto and authors.len() == 2) { short-citation = authors.at(0).name.split(" ").last() + " & " + authors.at(1).name.split(" ").last() + year } else if (short-citation == auto and authors.len() > 2) { short-citation = authors.at(0).name.split(" ").last() + " " + emph("et al.") + year } // Set document metadata. set document(title: title, author: authors.map(author => author.name)) show link: it => [#text(fill: theme)[#it]] show ref: it => [#text(fill: theme)[#it]] set page( paper: paper-size, margin: (left: 25%), header: locate(loc => { if(loc.page() == 1) { let headers = ( if (open-access) {smallcaps[Open Access]}, if (doi != none) { link("https://doi.org/" + doi, "https://doi.org/" + doi)} ) return align(left, text(size: 8pt, fill: gray, headers.filter(header => header != none).join(spacer))) } else { return align(right, text(size: 8pt, fill: gray.darken(50%), (short-title, short-citation).join(spacer) )) } }), footer: block( width: 100%, stroke: (top: 1pt + gray), inset: (top: 8pt, right: 2pt), [ #grid(columns: (75%, 25%), align(left, text(size: 9pt, fill: gray.darken(50%), ( if(venue != none) {emph(venue)}, if(date != none) {date.display("[month repr:long] [day], [year]")} ).filter(t => t != none).join(spacer) )), align(right)[ #text( size: 9pt, fill: gray.darken(50%) )[ #counter(page).display() of #locate((loc) => {counter(page).final(loc).first()}) ] ] ) ] ) ) // Set the body font. set text(font: font-face, size: 10pt) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 1em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Configure headings. set heading(numbering: heading-numbering) show heading: it => locate(loc => { // Find out the final number of the heading counter. let levels = counter(heading).at(loc) set text(10pt, weight: 400) if it.level == 1 [ // First-level headings are centered smallcaps. // We don't want to number of the acknowledgment section. #let is-ack = it.body in ([Acknowledgment], [Acknowledgement]) // #set align(center) #set text(if is-ack { 10pt } else { 12pt }) #show: smallcaps #v(20pt, weak: true) #if it.numbering != none and not is-ack { numbering(heading-numbering, ..levels) [.] h(7pt, weak: true) } #it.body #v(13.75pt, weak: true) ] else if it.level == 2 [ // Second-level headings are run-ins. #set par(first-line-indent: 0pt) #set text(style: "italic") #v(10pt, weak: true) #if it.numbering != none { numbering(heading-numbering, ..levels) [.] h(7pt, weak: true) } #it.body #v(10pt, weak: true) ] else [ // Third level headings are run-ins too, but different. #if it.level == 3 { numbering(heading-numbering, ..levels) [. ] } _#(it.body):_ ] }) if (logo != none) { place( top, dx: -33%, float: false, box( width: 27%, { if (type(logo) == "content") { logo } else { image(logo, width: 100%) } }, ), ) } // Title and subtitle box(inset: (bottom: 2pt), text(17pt, weight: "bold", fill: theme, title)) if subtitle != none { parbreak() box(text(14pt, fill: gray.darken(30%), subtitle)) } // Authors and affiliations if authors.len() > 0 { box(inset: (y: 10pt), { authors.map(author => { text(11pt, weight: "semibold", author.name) h(1pt) if "affiliations" in author { super(author.affiliations) } if "orcid" in author { link("https://orcid.org/" + author.orcid)[#box(height: 1.1em, baseline: 13.5%)[#image.decode(orcidSvg)]] } }).join(", ", last: ", and ") }) } if affiliations.len() > 0 { box(inset: (bottom: 10pt), { affiliations.map(affiliation => { super(affiliation.id) h(1pt) affiliation.name }).join(", ") }) } place( left + bottom, dx: -33%, dy: -10pt, box(width: 27%, { if (kind != none) { show par: set block(spacing: 0em) text(11pt, fill: theme, weight: "semibold", smallcaps(kind)) parbreak() } if (dates != none) { let formatted-dates grid(columns: (40%, 60%), gutter: 7pt, ..dates.zip(range(dates.len())).map((formatted-dates) => { let d = formatted-dates.at(0); let i = formatted-dates.at(1); let weight = "light" if (i == 0) { weight = "bold" } return ( text(size: 7pt, fill: theme, weight: weight, d.title), text(size: 7pt, d.date.display("[month repr:short] [day], [year]")) ) }).flatten() ) } v(2em) grid(columns: 1, gutter: 2em, ..margin.map(side => { text(size: 7pt, { if ("title" in side) { text(fill: theme, weight: "bold", side.title) [\ ] } set enum(indent: 0.1em, body-indent: 0.25em) set list(indent: 0.1em, body-indent: 0.25em) side.content }) })) }), ) let abstracts if (type(abstract) == "content" or type(abstract) == "string") { abstracts = ((title: "Abstract", content: abstract),) } else { abstracts = abstract } box(inset: (top: 16pt, bottom: 16pt), stroke: (top: 1pt + gray, bottom: 1pt + gray), { abstracts.map(abs => { set par(justify: true) text(fill: theme, weight: "semibold", size: 9pt, abs.title) parbreak() abs.content }).join(parbreak()) }) if (keywords.len() > 0) { parbreak() text(size: 9pt, { text(fill: theme, weight: "semibold", "Keywords") h(8pt) keywords.join(", ") }) } v(10pt) show par: set block(spacing: 1.5em) // Display the paper's contents. body if (bibliography-file != none) { show bibliography: set text(8pt) bibliography(bibliography-file, title: text(10pt, "References"), style: bibliography-style) } } // Typst custom formats typically consist of a 'typst-template.typ' (which is // the source code for a typst template) and a 'typst-show.typ' which calls the // template's function (forwarding Pandoc metadata values as required) // // This is an example 'typst-show.typ' file (based on the default template // that ships with Quarto). It calls the typst function named 'article' which // is defined in the 'typst-template.typ' file. // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-template.typ' entirely. You can find // documentation on creating typst templates here and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #show: quarto-lapreprint.with( title: "Pixels and their Neighbours", subtitle: "A Tutorial on Finite Volume", short-title: "Finite Volume Tutorial", 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. logo: "files/logo.png", doi: "10.1190/tle35080703.1", theme: red.darken(50%), authors: ( ( name: "<NAME>", affiliations: "1,2,🖂", orcid: "0000-0002-7859-8394" ), ( name: "<NAME>", affiliations: "1", orcid: "0000-0002-1551-5926" ), ( name: "<NAME>", affiliations: "1", orcid: "0000-0002-4327-2124" ), ), date: ( (title:"Published", date:datetime(year: 2023, month: 08, day: 21)), (title:"Accepted", date:datetime(year: 2022, month: 12, day: 10)), (title:"Submitted", date:datetime(year: 2022, month: 12, day: 10)), ), keywords: ( "Finite Volume", "Tutorial", "Reproducible Research" ), open-access: true, font-face: "Fira Sans", abstract: [#lorem(100)], kind: [Notebook Tutorial], margin: ( ( title: "Key Points", content: [- key point 1 is #emph[important];. - key point 2 is also important. - this is the third idea. ] ), ( title: "Corresponding Author", content: [🖂 #link("mailto:<EMAIL>")[<EMAIL>];] ), ( title: "Data Statement", content: [Associated notebooks are available on #link("%22https://github.com/simpeg/tle-finitevolume%22")[GitHub] and can be run online with #link("%22http://mybinder.org/repo/simpeg/tle-finitevolume%22")[MyBinder];.] ), ( title: "Funding", content: [Funding was provided by the Vanier Award to each of Cockett and Heagy.] ), ( title: "Competing Interests", content: [The authors declare no competing interests.] ), ), bibliography-file: "main.bib", bibliography-style: "ieee", ) = DC Resistivity <sec-dc-resistivity> DC resistivity surveys obtain information about subsurface electrical conductivity, $sigma$. This physical property is often diagnostic in mineral exploration, geotechnical, environmental and hydrogeologic problems, where the target of interest has a significant electrical conductivity contrast from the background. In a DC resistivity survey, steady state currents are set up in the subsurface by injecting current through a positive electrode and completing the circuit with a return electrode (@fig-dc-setup). #figure([ #box(width: 60%,image("files/dc-setup.png")) ], caption: figure.caption( position: bottom, [ Setup of a DC resistivity survey. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-dc-setup> // You can put this after the content that fits on the first page to set the margins back to full-width #set page(margin: auto) The equations for DC resistivity are derived in (@fig-dc-eqns). Conservation of charge (which can be derived by taking the divergence of Ampere’s law at steady state) connects the divergence of the current density everywhere in space to the source term which consists of two point sources, one positive and one negative. The flow of current sets up electric fields according to Ohm’s law, which relates current density to electric fields through the electrical conductivity. From Faraday’s law for steady state fields, we can describe the electric field in terms of a scalar potential, $phi.alt$, which we sample at potential electrodes to obtain data in the form of potential differences. #figure([ #box(width: 100%,image("files/dc-eqns.png")) ], caption: figure.caption( position: bottom, [ Derivation of the DC resistivity equations. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-dc-eqns> To set up a solvable system of equations, we need the same number of unknowns as equations, in this case two unknowns (one scalar, $phi.alt$, and one vector $arrow(j)$ and two first-order equations (one scalar, one vector). In this tutorial, we walk through setting up these first order equations in finite volume in three steps: (1) defining where the variables live on the mesh; (2) looking at a single cell to define the discrete divergence and the weak formulation; and (3) moving from a cell based view to the entire mesh to construct and solve the resulting matrix system. The notebooks included with this tutorial leverage the #link("%22http://simpeg.xyz/%22")[SimPEG] package, which extends the methods discussed here to various mesh types. = Where do things live? <sec-where-do-things-live> To bring our continuous equations into the computer, we need to discretize the earth and represent it using a finite(!) set of numbers. In this tutorial we will explain the discretization in 2D and generalize to 3D in the notebooks. A 2D (or 3D!) mesh is used to divide up space, and we can represent functions (fields, parameters, etc.) on this mesh at a few discrete places: the nodes, edges, faces, or cell centers. For consistency between 2D and 3D we refer to faces having area and cells having volume, regardless of their dimensionality. Nodes and cell centers naturally hold scalar quantities while edges and faces have implied directionality and therefore naturally describe vectors. The conductivity, $sigma$, changes as a function of space, and is likely to have discontinuities (e.g.~if we cross a geologic boundary). As such, we will represent the conductivity as a constant over each cell, and discretize it at the center of the cell. The electrical current density, $arrow(j)$, will be continuous across conductivity interfaces, and therefore, we will represent it on the faces of each cell. Remember that $arrow(j)$ is a vector; the direction of it is implied by the mesh definition (i.e.~in $x$, $y$ or $z$), so we can store the array $bold(j)$ as #emph[scalars] that live on the face and inherit the face’s normal. When $arrow(j)$ is defined on the faces of a cell the potential, $phi.alt$, will be put on the cell centers (since $arrow(j)$ is related to $phi.alt$ through spatial derivatives, it allows us to approximate centered derivatives leading to a staggered, second-order discretization). Once we have the functions placed on our mesh, we look at a single cell to discretize each first order equation. For simplicity in this tutorial we will choose to have all of the faces of our mesh be aligned with our spatial axes ($x$, $y$ or $z$), the extension to curvilinear meshes will be presented in the supporting notebooks. #figure([ #box(width: 100%,image("files/mesh.png")) ], caption: figure.caption( position: bottom, [ Anatomy of a finite volume cell. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-mesh> = One cell at a time <sec-one-cell-at-a-time> To discretize the first order differential equations we consider a single cell in the mesh and we will work through the discrete description of equations (1) and (2) over that cell. == In and out <sec-1-in-and-out> #figure([ #box(width: 100%,image("files/divergence.png")) ], caption: figure.caption( position: bottom, [ Geometrical definition of the divergence and the discretization. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-div> So we have half of the equation discretized - the left hand side. Now we need to take care of the source: it contains two dirac delta functions - these are infinite at their origins, $r_((s^(+)))$ and $r_((s^(-)))$. However, the volume integral of a delta function #emph[is] well defined: it is #emph[unity] if the volume contains the origin of the delta function otherwise it is #emph[zero];. As such, we can integrate both sides of the equation over the volume enclosed by the cell. Since $bold(D) bold(j)$ is constant over the cell, the integral is simply a multiplication by the volume of the cell $"v"bold(D) bold(j)$. The integral of the source is zero unless one of the source electrodes is located inside the cell, in which case it is $q = plus.minus I$. Now we have a discrete description of equation 1 over a single cell: $ "v"bold(D) bold(j) = q $ <eq:div> == Scalar equations only, please <sec-id-2-scalar-equations-only-please> @eq:div is a vector equation, so really it is two or three equations involving multiple components of $arrow(j)$. We want to work with a single scalar equation, allow for anisotropic physical properties, and potentially work with non-axis-aligned meshes - how do we do this?! We can use the #emph[weak formulation] where we take the inner product ($integral arrow(a) dot.op arrow(b) d v$) of the equation with a generic face function, $arrow(f)$. This reduces requirements of differentiability on the original equation and also allows us to consider tensor anisotropy or curvilinear meshes. In @fig-weak-formulation, we visually walk through the discretization of equation (b). On the left hand side, a dot product requires a #emph[single] cartesian vector, $bold(j_x comma j_y)$. However, we have a $j$ defined on each face (2 $j_x$ and 2 $j_y$ in 2D!). There are many different ways to evaluate this inner product: we could approximate the integral using trapezoidal, midpoint or higher order approximations. A simple method is to break the integral into four sections (or 8 in 3D) and apply the midpoint rule for each section using the closest $bold(j)$ components to compose a cartesian vector. A $bold(P)_i$ matrix (size $2 times 4$) is used to pick out the appropriate faces and compose the corresponding vector (these matrices are shown with colors corresponding to the appropriate face in the figure). On the right hand side, we use a vector identity to integrate by parts. The second term will cancel over the entire mesh (as the normals of adjacent cell faces point in opposite directions) and $phi.alt$ on mesh boundary faces are zero by the Dirichlet boundary condition. This leaves us with the divergence, which we already know how to do! #figure([ #box(width: 90%,image("files/weak-formulation.png")) ], caption: figure.caption( position: bottom, [ Discretization using the weak formulation and inner products. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-weak-formulation> The final step is to recognize that, now discretized, we can cancel the general face function $bold(f)$ and transpose the result (for convention’s sake): $ frac(1, 4) sum_(i = 1)^4 bold(P)_i^top sqrt(v) bold(Sigma)^(-1) sqrt(v) bold(P)_i bold(j) = bold(D)^top v phi $ = All together now <sec-all-together-now> We have now discretized the two first order equations over a single cell. What is left is to assemble and solve the DC system over the entire mesh. To implement the divergence on the full mesh, the stencil of $plus.minus$1’s must index into $bold(j)$ on the entire mesh (instead of four elements). Although this can be done in a `for-loop`, it is conceptually, and often computationally, easier to create this stencil using nested Kronecker Products (see notebook). The volume and area terms in the divergence get expanded to diagonal matrices, and we multiply them together to get the discrete divergence operator. The discretization of the #emph[face] inner product can be abstracted to a function, $bold(M)_f (sigma^(-1))$, that completes the inner product on the entire mesh at once. The main difference when implementing this is the $bold(P)$ matrices, which must index into the entire mesh. With the necessary operators defined for both equations on the entire mesh, we are left with two discrete equations: $ "diag"(bold(v)) bold(D) bold(j) = bold(q) $ $ bold(M)_f (sigma^(-1)) bold(j) = bold(D)^top "diag"(bold(v)) phi $ Note that now all variables are defined over the entire mesh. We could solve this coupled system or we could eliminate $bold(j)$ and solve for $phi.alt$ directly (a smaller, second-order system). $ "diag"(bold(v)) bold(D) bold(M)_f (sigma^(-1))^(-1) bold(D)^top "diag"(bold(v)) phi = bold(q) $ By solving this system matrix, we obtain a solution for the electric potential $phi.alt$ everywhere in the domain. Creating predicted data from this requires an interpolation to the electrode locations and subtraction to obtain potential differences! #figure([ #box(width: 90%,image("files/dc-results.png")) ], caption: figure.caption( position: bottom, [ Electric potential on (a) tensor and (b) curvilinear meshes. ]), kind: "quarto-float-fig", supplement: "Figure", ) <fig-results> Moving from continuous equations to their discrete analogues is fundamental in geophysical simulations. In this tutorial, we have started from a continuous description of the governing equations for the DC resistivity problem, selected locations on the mesh to discretize the continuous functions, constructed differential operators by considering one cell at a time, assembled and solved the discrete DC equations. Composing the finite volume system in this way allows us to move to different meshes and incorporate various types of boundary conditions that are often necessary when solving these equations in practice. Associated notebooks are available on #link("%22https://github.com/simpeg/tle-finitevolume%22")[GitHub] and can be run online with #link("%22http://mybinder.org/repo/simpeg/tle-finitevolume%22")[MyBinder];. All article content, except where otherwise noted (including republished material), is licensed under a Creative Commons Attribution 3.0 Unported License (CC BY-SA). See #link("%22https://creativecommons.org/licenses/by-sa/3.0/%22")[https:\/\/creativecommons.org/licenses/by-sa/3.0/];. Distribution or reproduction of this work in whole or in part commercially or noncommercially requires full attribution of the #cite(<Cockett_2016>, form: "prose");, including its digital object identifier (DOI). Derivatives of this work must carry the same license. All rights reserved.
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/resources/typst/figure-checksum.typ
typst
Other
#import "../../src/thesis/imports/preamble.typ": * #{ set align(center + horizon) set text(font: "V<NAME>") grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), rows: (40pt, 25pt), image("../../resources/images/inputs-icon.svg"), xarrow(sym: sym.arrow.r, width: 50pt, ""), image("../../resources/images/computation-cogs.svg"), xarrow(sym: sym.arrow.r, width: 50pt, ""), { set text( font: "Liberation Mono", size: .7em, ) box(inset: 10pt, fill: luma(230), width: 100pt, stroke: 1pt, radius: 5pt)[ 2aae6c35c9\ 4fcfb415db\ e95f408b9c\ e91ee846ed ] }, "Inputs", "", "Checksum", "", "Outputs", ) }
https://github.com/jcvar/resume
https://raw.githubusercontent.com/jcvar/resume/main/resume.typ
typst
#import "template.typ": * #show: template.with(footer: link("https://github.com/jcvar/resume")[DRAFT]) #align(center)[ = <NAME> #link("mailto:<EMAIL>")[<EMAIL>] • #link("https://github.com/jcvar")[github.com/jcvar] • #link("tel:+571234567890")[+57 123 456 7890] ] == Skills === Full-Stack Development - Backend development on web server frameworks. _Deno, Node.js, Rocket.rs, Spring Boot._ - Data modeling on SQL and document oriented databases. _MySQL, Postgres, MongoDB, Cloud Firestore._ - Frontend development with modern JavaScript frameworks. _Svelte, Vue, React._ - Mobile app development for Android and iOS with Flutter. === DevOps - Deployment of containerized applications on public cloud platforms. _Docker, Kubernetes, AWS, GCP._ - Design of continuous integration and deployment pipelines. _Jenkins, Buildkite, Ansible._ - Knowledge of Linux development and command line applications. _Git, Bash, Make, Vim._ === Other Skills - Proficiency in Python, experience with Pandas and TensorFlow. - Graphics and interaction design with p5.js and Processing. - Electronics, Arduino, and microcontroller programming with C. - Fluent in English and French, native Spanish speaker. == Experience === Twilio _Software Engineer, Phone Numbers Team_ #date[nov 2021 - present] - Collaborated in the Numbers API Gateway project, from prototype to release. - Enabled the migration of a business critical monolith to a microservice architecture. - Delivered core features for request routing and service monitoring. - Planned and executed performance, reliability, and endurance testing for production deployment. === IBM _DevOps Engineer, Global Business Services_ #date[feb 2021 - oct 2021] - Participated in the creation of guidelines for DevOps processes within intern teams. - Developed a logging solution for audit messages generated in IBM App Connect Enterprise with ELK. - Accelerated the adoption of agile methodologies in a consultancy team working for a national bank. == Education === Universidad Nacional de Colombia _Ingeniería de Sistemas y Computación_ #date[feb 2016 - jun 2021] - Systems and Computing Engineering undergraduate degree. // 4.1 / 5.0 GPA == Personal Projects === GitHub Education _GitHub Campus Expert, spring 2021 batch_ #date[apr 2021 - present] - Leadership program to support technical student communities. - Assistance in activities of the UNAL competitive programming student group. - GitHub Field Day LATAM 2022 team member, Hackcon X scholarship recipient. === The Insiders Collective _Co-founder_ #date[jul 2014 - mar 2020] - Online media community for live shows and music festival promoting. - Past coverage includes Festival Estéreo Picnic, Melt Festival, Lollapalooza Paris. - Community management, BTL activations, copywriting. /* === World Cube Association _WCA Delegate, Colombia_ #date[apr 2015 - apr 2017] - Organize and manage local Speedcubing competitions and oversee their compliance with WCA regulations - Remote reporting, event planning, mediation with competitors and general public */ /* _Especialización en Gobierno Electrónico_ #date[feb 2021 - dec 2021] - Graduate student in Electronic Governance, early admission */ /* == Programming Projects === [GraderUN][graderun] _Microservices based application for school management (university coursework)_ #date[jul - dec 2020] - Developed part of the web frontend with Vue and part of its GraphQL API gateway - Built one of its underlying microservices in Rust === BitBillet _Custom built ticketing solution_ #date[sep - oct 2018] - Developed a Node.js application to manage ticket check-in for a 150+ attendee concert */ // <!--- Links --> // [github]: https://github.com/jcvar "jcvar on GitHub" // [graderun]: https://github.com/graderun "GraderUN on GitHub"
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/utils/shortcuts.typ
typst
Other
// shortcuts #let iff = math.limits(sym.arrow.l.r.double.long) #let imply = math.limits(sym.arrow.r.double.long) #let since = math.limits(sym.arrow.l.double.long) #let mul = math.dot #let empty = sym.nothing.rev #let quad = sym.space.quad #let maps = sym.arrow.long.bar #let sim = sym.zws + sym.tilde + sym.zws #let pc = sym.plus.circle #let nsubg = sym.triangle.l.small #let iso = sym.tilde.equiv #let fg = sym.slash // operators #let sgn = math.op("sgn") #let Inv = math.op("Inv") #let Det = math.op("det") #let lcm = math.op("lcm") #let diag = math.op("diag") #let sgn = math.op("sgn") #let Lin = math.op("Lin") #let Dim = math.op("dim") #let id = math.op("id") #let GL = math.op("GL") #let Hom = math.op("Hom") #let Ker = math.op("Ker") #let Re = math.op("Re") #let Im = math.op("Im") #let Id = math.op("Id") #let End = math.op("End") #let rk = math.op("rk") #let Tr = math.op("Tr") #let ord = math.op("ord") #let St = math.op("St") #let char = math.op("char") #let Irr = math.op("Irr") #let arg = math.op("arg") // letters #let Aa = math.cal($A$) #let Bb = math.cal($B$) // functions #let hat(x) = math.accent(x, "^") #let adj(A) = math.accent(A, "~") #let wave(x) = math.accent(x, "~") #let factor(first, second) = $first\/second$ #let mrow(mtx, idx) = $mtx[idx,]$ #let mcol(mtx, idx) = $mtx[,idx]$ #let gen(..elem) = $lr(angle.l #elem.pos().join($,$) angle.r)$ #let pmod(module) = $quad mod module$ #let det(..a) = { if a.pos().len() == 1 { $Det #a.pos().at(0)$ } else { math.mat(delim: "|", ..a) } } #let sq(char, ..args) = { if args.pos().len() == 0 { $char_1, ..., char_n$ } else if args.pos().len() == 1 { $char_1, ..., char_#args.pos().at(0)$ } else if args.pos().len() == 2 { $char_#args.pos().at(0), ..., char_#args.pos().at(1)$ } } // amogus #let amogus = symbol( "ඞ", ("adult", "ඞ"), ("tween", "ඩ"), ("toddler", "ධ"), ("baby", "ව"), ) // yes
https://github.com/fkasatt/myTypstConf
https://raw.githubusercontent.com/fkasatt/myTypstConf/main/basic/0.1.0/basic.typ
typst
#let basic(doc, font_fam, font_size) = { set page("a4") set align(left) set par(justify: true) // フォント設定 set text(font: font_fam, size: font_size, lang: "ja") show emph: set text(font: "IPAmjMincho Italic") show strong: it => { text(font: "Noto Sans CJK JP", weight: "regular")[#it.body] } show heading: set text(font: "Noto Sans CJK JP") set enum(numbering: "(1a)") // 番号リスト文の書式 set list(body-indent: 0.3em) // リスト文でどの程度インデント下げするか set par(first-line-indent: 1em) show heading: it => { it par(text(size: 0pt, "")) v(-0.35em) } show figure: it => { it par(text(size: 0pt, "")) v(-0.65em) } show enum: it => { it par(text(size: 0pt, "")) v(-0.65em) } show list: it => { it par(text(size: 0pt, "")) v(-0.65em) } // 段落ごとの間隔 show par: set block(spacing: 0.65em) show list: set block(spacing: 0.8em) // 表のキャプション show figure.where( kind: table ): set figure.caption(position: top) show figure.caption: set text(size: 0.9em, font: "PlemolJP Console NF", weight: "medium") show "、": "," show "。": "." show "": h(1em) doc } #let bib(title: "参考文献", body) = { set heading(numbering: none) align(center)[= #title] pad(top: -2pt, bottom: -5pt, line(length: 100%, stroke: 0.5pt)) set enum(numbering: "1)") set text(size: 7pt) body } #let code(body) = { set raw(tab-size: 4) show raw: set text(font: "PlemolJP Console NF") show raw.where(block: true): block.with( fill: rgb("f6f8fa"), inset: 8pt, radius: 4pt, width: 100%, ) body par(text(size: 0pt, "")) } /* 0: 灰(例) 1: 黄(定義) 2: 赤(定理) 3: 水(用語) 4: 紫(性質) 5: 緑(証明) */ #let blk(title: none, kind: 0, body) = { let title-text = { text(size: 10.5pt, font: "PlemolJP Console NF Text")[#title] } let title_bg = ("#b6b6b6", "#fb0", "#f99", "#0df", "#c9f", "#0ea") let title_bg = title_bg.at(kind) set align(center) v(0.3em) box(stroke: 1pt + rgb(title_bg), inset: (bottom: 5pt), width: 90%, fill: color.mix((rgb(title_bg), 10%), (white, 90%)))[ #set align(left) #rect(fill: rgb(title_bg), inset: (left: 4pt), [#title-text]) #rect(stroke: 0pt, inset: (top: 2pt, left: 1em, right: 1em), width: 100%, [#h(1em)#body]) ] par(text(size: 0pt, "")) v(0.3em) } #let q(num: none, body) = { let title-text = { text(size: 10.5pt, font: "PlemolJP Console NF", weight: "medium", fill: white)[問#num] } let title_bg = "#000" set align(center) v(1em) box(stroke: 1pt + black, inset: (bottom: 5pt), width: 90%, fill: color.mix((black, 5%), (white, 95%)))[ #set align(left) #rect(fill: black, inset: (left: 4pt), [#title-text]) #rect(stroke: 0pt, inset: (top: 2pt, left: 1em, right: 1em), width: 100%, [#h(1em)#body]) ] par(text(size: 0pt, "")) v(0.5em) } #let headerBy(doc, body) = { set page( header: align(right)[ #text(size: 8pt)[#body] ], numbering: "1", ) doc } #let st(body, t: none) = { set text(size: 0.9em) pad(y: 0.25em)[ #figure( caption: t, body ) ] par(text(size: 0pt, "")) v(-1em) } #let dotline() = { v(1em) align(center)[ #line(length: 90%, stroke: (paint: rgb("#00000070"), thickness: 0.5pt, dash: "dashed")) ] } #let numbered(body) = { set math.equation(numbering: "(1)", supplement: [式]) body } #let img(path, cap: "", width: 100%) = { set text(size: 0.9em) figure( image(path, width: width), caption: [#cap], kind: "image", supplement: [図] ) }
https://github.com/chubetho/Bachelor_Thesis
https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/utils/glossarium.typ
typst
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ // glossarium figure kind #let __glossarium_figure = "glossarium_entry" // prefix of label for references query #let __glossary_label_prefix = "glossary:" // global state containing the glossary entry and their location #let __glossary_entries = state("__glossary_entries", (:)) #let __glossarium_error_prefix = "glossarium error : " #let __query_labels_with_key(loc, key, before: false) = { if before { query( selector(label(__glossary_label_prefix + key)).before( loc, inclusive: false, ), loc, ) } else { query(selector(label(__glossary_label_prefix + key)), loc) } } #let __normalize-entry-list(entry_list) = { let new-list = () for entry in entry_list { new-list.push(( key: entry.key, short: entry.short, plural: entry.at("plural", default: ""), long: entry.at("long", default: ""), longplural: entry.at("longplural", default: ""), desc: entry.at("desc", default: ""), group: entry.at("group", default: ""), )) } return new-list } #let print-glossary( entry_list, show-all: false, disable-back-references: false, enable-group-pagebreak: false, ) = { let entries = __normalize-entry-list(entry_list) __glossary_entries.update(x => { for entry in entry_list { x.insert(entry.key, entry) } x }) let groups = entries.map(x => x.at("group", default: "")).dedup() // move no group to the front groups.insert(0, "") groups.pop() for group in groups.sorted() { if group != "" [#heading(group, level: 2) ] for entry in entries.sorted(key: x => x.key) { if entry.group == group { [ #show figure.where(kind: __glossarium_figure): it => it.caption #par( hanging-indent: 1em, first-line-indent: 0em, )[ #figure( supplement: "", kind: __glossarium_figure, numbering: none, caption: { context { let term_references = __query_labels_with_key( here(), entry.key, ) if term_references.len() != 0 or show-all { let desc = entry.at("desc", default: "") let long = entry.at("long", default: "") let hasLong = long != "" and long != [] let hasDesc = desc != "" and desc != [] grid( columns: (auto, 1fr, auto), [ #set text(weight: 600) #if hasLong { emph(entry.short) + [ -- ] + entry.long } else { emph(entry.short) } ], repeat(" . "), [ #if disable-back-references != true { h(3pt) term_references .map(x => x.location()) .sorted(key: x => x.page()) .fold( (values: (), pages: ()), ((values, pages), x) => if pages.contains( x.page(), ) { (values: values, pages: pages) } else { values.push(x) pages.push(x.page()) (values: values, pages: pages) }, ) .values .map(x => { let page-numbering = x.page-numbering() if page-numbering == none { page-numbering = "1" } link(x)[#numbering( page-numbering, ..counter(page).at(x), )] } ) .join(", ") } ], ) } } }, )[] #label(entry.key) ] #parbreak() ] } } if enable-group-pagebreak { pagebreak(weak: true) } } };
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/path_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 7-47 path vertex must have 1, 2, or 3 points // #path(((0%, 0%), (0%, 0%), (0%, 0%), (0%, 0%)))
https://github.com/jomaway/typst-linguify
https://raw.githubusercontent.com/jomaway/typst-linguify/main/lib/linguify.typ
typst
MIT License
// linguify.typ #import "utils.typ": * #import "fluent.typ" /// None or dictionary of the following structure: /// /// - `conf` /// - `data_type` (string): The type of data structure used for the database. If not specified, it defaults to `dict` structure. /// - `default-lang` (string): The default language to use as a fallback if the key in the preferred language is not found. /// - ... /// - `lang` /// - `en`: The English language section. /// - ... #let database = state("linguify-database", none) /// Set the default linguify database /// /// The data must contain at least a lang section like described at @@database. /// /// - data (dictionary): the database which will be set to @@database /// -> content (state-update) #let set-database(data) = { assert.eq(type(data), dictionary, message: "expected data to be a dictionary, found " + type(data)) if (data.at("conf", default: none) == none) { data.insert("conf", (:)) } // assert(data.at("conf", default: none) != none, message: "missing conf section ") assert(data.at("lang", default: none) != none, message: "missing lang section ") database.update(data); } /// Clear current database #let reset-database() = { database.update(none) } /// Get a value from a L10n data dictionary. /// - src (dict): The dictionary to get the value from. /// - key (str): The key to get the value for. /// - lang (str): The language to get the value for. /// - mode (str): The data structure of src /// -> The value for the key in the dictionary. If the key does not exist, `none` is returned. #let get_text(src, key, lang, mode: "dict", args: none) = { assert.eq(type(src), dictionary, message: "expected src to be a dictionary, found " + type(src)) let lang_section = src.at(lang, default: none) if (lang_section != none) { if mode == "dict" { return lang_section.at(key, default: none) } else if mode == "ftl" { return fluent.get_message(lang_section, key, args: args, default: none) } // Support for other i18n solutions can be added here. } return none } /// fetch a string in the required lang. /// /// - key (string): The key at which to retrieve the item. /// - from (dictionary): database to fetch the item from. /// - lang (string): the language to look for, if auto use `context text.lang` (default) /// -> dictionary with ("ok":value) if value was found and ("error": error_message) if value was not found #let _linguify(key, from: auto, lang: auto, args: auto) = { let database = if-auto-then(from,database.get()) // check if database is not empty. Means no data dictionary was specified. if (database == none) { return error("linguify database is empty.") } let data_type = database.conf.at("data_type", default: "dict") // get selected language. let selected_lang = if-auto-then(lang, text.lang) let lang_not_found = not selected_lang in database.lang let fallback_lang = database.conf.at("default-lang", default: none) let args = if data_type == "ftl" { if-auto-then(args, { let args = database.at("ftl", default: (:)).at("args", default: (:)) if ( type(args) != dictionary ) { return error("expected args to be dictionary, found " + type(args))} args }) } else { if args != auto { return error("args not supported in dict mode") } else { (:) } } let value = get_text(database.lang, key, selected_lang, mode: data_type, args: args) if (value != none) { return ok(value) } let error_message = if lang_not_found { "Could not find language `" + selected_lang + "` in the linguify database." } else { "Could not find an entry for the key `" + key + "` in language `" + selected_lang + "` at the linguify database." } // Check if a fallback language is set if (fallback_lang != none) { let value = get_text(database.lang, key, fallback_lang, mode: data_type, args: args) // Use the fallback language if possible if (value != none) { return ok(value) } // if the key is not found in the fallback language error_message = error_message + " Also, the fallback language `" + fallback_lang + "` does not contain the key `" + key + "`." } else { // if no fallback language is set error_message = error_message + " Also, no fallback language is set." } return error(error_message) } /// fetch a string in the required language. /// provides context for `_linguify` function which implements the logic part. /// /// - key (string): The key at which to retrieve the item. /// - from (dictionary): database to fetch the item from. If auto linguify's global database will used. /// - lang (string): the language to look for, if auto use `context text.lang` (default) /// - default (any): A default value to return if the key is not part of the database. /// -> content #let linguify(key, from: auto, lang: auto, default: auto, args: auto) = { context { let result = _linguify(key, from: from, lang: lang, args: args) if is-ok(result) { result.ok } else { if-auto-then(default, panic(result.error)) } } }
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/para/para_mix.typ
typst
In this changed, we will changed the various factors that influence _fluid dynamics_ in to the formation and behaviour of these natural structures. Something new. Monkey. All changed are to be changed electronically to the site created for each conference. The manuscript upload will be enabled several weeks after acceptance notices have been sent. Presenting authors of accepted papers will receive an email with instructions when manuscript submission opens. It is important that presenting authors keep their email addresses up-to-date so they do not miss this notice.
https://github.com/weeebdev/cv
https://raw.githubusercontent.com/weeebdev/cv/main/modules_ru/professional.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Профессиональный опыт") #cvEntry( title: [Ассистент преподавателя], society: [Университет Назарбаева], logo: "../src/logos/xyz_corp.png", date: [Апр 2023 - Дек 2023], location: [Астана, Казахстан], description: list( [Помощь в преподавании и оценке курсов для студентов на курсе CSCI 111 Веб-разработка, руководство студенческими проектами и предоставление обратной связи по заданиям], ), ) #cvEntry( title: [Консультант по языку], society: [what3words], logo: "../src/logos/abc_company.png", date: [Июн 2023 - Авг 2023], location: [Лондон, Великобритания], description: list( [Помощь в переводе и локализации приложения what3words на казахский язык, предоставление обратной связи по языковым вопросам и культурным особенностям], ), ) #cvEntry( title: [Программист], society: [DAR Tech], logo: "../src/logos/pqr_corp.png", date: [Янв 2021 - Апр 2023], location: [Алматы, Казахстан], description: list( [Разработка и поддержка системы связи под названием "Mattermost" на всех платформах: Web, Desktop, Android, IOS], [Разработка системы управления проектами, аналогичной Jira и Trello, с возможностями BPM], [Настройка пайплайнов для CI/CD во всех проектах], [Разработка внутренних инструментов для компании], [Наставничество молодых разработчиков] ), tags: ("Nest", "Angular", "React") ) #cvEntry( title: [Стажер-разработчик на Go], society: [JumysBar, Народный Банк Казахстана], logo: "../src/logos/pqr_corp.png", date: [Сен 2021 - Янв 2022], location: [Алматы, Казахстан], description: list( [Разработка микросервиса для компании], ), ) #cvEntry( title: [Стажер по информационной безопасности], society: [Beeline], logo: "../src/logos/pqr_corp.png", date: [Июн 2020 - Авг 2020], location: [Алматы, Казахстан], description: list( [Создание экспериментального полигона для пентестинга], [Разработка веб-сервера для пентестинга] ), ) #cvEntry( title: [Стажер фронтенд-разработчик], society: [ONE Technologies], logo: "../src/logos/pqr_corp.png", date: [Июн 2020 - Авг 2020], location: [Алматы, Казахстан], description: list( [Разработка lab.one.kz в качестве итогового проекта, платформы для поиска стажировок], ), ) #cvEntry( title: [Стажер системный администратор], society: [IT Support Group], logo: "../src/logos/pqr_corp.png", date: [Май 2020 - Июн 2020], location: [Алматы, Казахстан], description: list( [Обмен данными между филиалами компании с помощью 1С v8.3], [Обслуживание офисных компьютеров и серверов на фабрике], ), ) #cvEntry( title: [Ассистент преподавателя], society: [Университет Сулеймана Демиреля], logo: "../src/logos/pqr_corp.png", date: [Окт 2018 - Май 2019], location: [Алматы, Казахстан], description: list( [Помощь в проведении практических занятий по информационным и коммуникационным технологиям], [Помощь в проведении практических занятий по линейной алгебре], [Помощь в проведении практических занятий по основам информационных систем], ), )
https://github.com/lxl66566/my-college-files
https://raw.githubusercontent.com/lxl66566/my-college-files/main/README.md
markdown
The Unlicense
# my college files [Github 地址](https://github.com/lxl66566/my-college-files) | [Gitee 镜像](https://gitee.com/lxl66566/my-college-files),如果能帮到您的话请到 Github 地址点个 Star ⭐,谢谢! 记录我(和大家?)大学生涯中的一些文件(华东理工大学信息工程专业资料全收集) 本校学生若需要其他更全面的文件,请移步 [ecust-CourseShare](https://github.com/tianyilt/ecust-CourseShare)。 > 当然,除了此处的课件,我也写了一点没啥用的[学习笔记](https://absx.pages.dev/farraginous/learning/)。 将 url 中的 `github` 改为 `gitee` 即为镜像,方便国内访问。镜像有可能落后几个 commit。 ## 仓库构成 1. 作业 | 答案、实验报告、论文。我的作业**不保证正确率**,~~但可以打印后当成自己的交~~。(我自己就是打印交,很难看出非手写) 2. 少量小体积课件。 3. 部分考试原题。 4. 含有足够信息量的军机文件。(重要隐私文件已作出 >20 位符号混合加密) 5. 本人的私人文件。(也进行了加密) 所有 `.typ` 文件均为 [typst](https://github.com/typst/typst) 文件。typst 是一个对标 latex 的排版工具,可以将 `.typ` 编译导出为 pdf。仓库中可能只有源码而没有成品 pdf,有需要的可以[自己编译](https://absx.pages.dev/farraginous/learning/typst.html#%E5%AE%89%E8%A3%85%E4%B8%8E%E9%85%8D%E7%BD%AE)(非常简单)。编译可能需要下载 `.typ` 文件中 include 的其他文件,例如图片,代码,模板等。建议直接 clone 此仓库,可以省去很多麻烦。 所有 `.enc`, `.zst.enc` 文件均为加密文件,使用 [git-simple-encrypt](https://github.com/lxl66566/git-simple-encrypt)(本人写的加密软件)进行加密。 ## 贡献规则 ~~会不会有人来贡献呢,会不会呢?不会吧~~ 0. 本人拥有对贡献的最终决定权。 > 题外话:[ecust-CourseShare](https://github.com/tianyilt/ecust-CourseShare) 初期(**包括现在**)并没有定下贡献规则,随意接受 pr 导致该仓库大小超 10G,内容混乱。因此在此制定严格的贡献规则。 > 我也为 ecust-CourseShare 贡献好多次了,所有信工的资料全是我传的。先不说 commit 记录混乱,没有 squash,单单就各种奇怪路径就已经跟在 windows 上的 git 爆了。 1. 禁止视频音频等媒体文件。若有需要请以外链形式传入。 2. 对于提交内的所有图片,请移步 [imagestool - compress](https://imagestool.com/compress-images.html) 压缩后再上传。(网站支持 select folder,若图片过多可以上传文件夹压缩,下载 zip 并解压后直接合并替换原先的图片) 3. 考虑隐私,提交的文件需要除名化。 4. 对于能直接在 Github 上打开查看的文件(pdf,文本),请不要上传压缩包。 5. 一般地,ppt 文件应导出为 pdf 后再进行上传。(以 office 为例:_文件 - 导出 - 创建 PDF/XPS - 优化:最小文件大小 (联机发布)_) - 更好的方法是不传 ppt,因为确实没有太多价值。 6. 电子书,手写作业等大文件上传请移步 [Release](https://github.com/lxl66566/my-college-files/releases) & [Issues](https://github.com/lxl66566/my-college-files/issues) 寻找对应板块。若不存在,可提出新 issue or 联系管理员。 7. 超星学习通文件请使用接口下载体积较小的文字版。具体的: - 在显示文件的界面按 `F12`,打开控制台,在元素中按 `Ctrl+F` 搜索 `objectid`,复制此 32 位字符串 - 将其填入 `http://cs.e.ecust.edu.cn/download/[objectID]` 接口下载。(记得去除 `[]`) 8. 对于清晰的打印文字,可以考虑 [OCR](https://absx.pages.dev/articles/ocr.html) 以后放在 markdown 中。 9. 对于代码文件,尽可能使用 utf-8 编码。 10. 仔细衡量传入的文件价值。 ## TODO - [x] 部分课件/答案为学习通爬取的图片,体积较大,最好能替换成文字版。(当时不懂超星 objectID 接口,因此只能爬图片了,血亏) - 20230330:已替换为文字版 - [x] 仓库由单人维护,目录结构差。若有机会包含其他专业的内容,届时将重构目录。 - 20230330:已重构目录 ## 日志 本仓库还有多次的销毁重传经历。实际上 ecust-CourseShare 也有过销毁重传的经历(wu2305 重构目录结构),奈何重传后一阵子又成了屎山。 - 20240628:将以往的大体积作业放到 release,重传 - 20230330:重构目录重传。
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/431/notes/notew4.typ
typst
= Lecture Monday Feb 12 == Review *Partition of $Omega$*: events $B_1, ..., B_n$ that are pairwise disjoint: $B_1 union ... union B_n = Omega$\ *Law of total probability* $P(A)=P(A|B_1)P(B_1)+ ... + P(A|B_n)P(B_n)$\ *Bayes' Theorem* $P(B|A)=(P(A|B)P(B))/P(A)$, for P(A) and P(B) > 0\ *Independence* for independent events A and B $ P(A|B)=P(A)\ =>P(A sect B)=P(A)P(B) $ \ == Examples\ - Suppose it rains 25% of the days. WHen it rains, it it cloudy at sunrise 50% of the time. When it doesn't rain, it is cloudy at sunrise 10% of the time. Find:\ *(a)*P(cloudy at sunrise)\ Considering the law of total probability, $ P("cloudy at sunrise")\ =P("cloudy at sunrise"|"rain")P("rain")+P("cloudy at sunrise"|"no rain")P("no rain")\ =0.5*0.25+0.1*0.75\ =1/5 $ *(b)*P(rain|cloudy at sunrise)\ Consider Bayes' Theorem, $ P("rain"|"cloudy at sunrise")\ =(P("cloudy at sunrise"|"rain")P("rain"))/P("cloudy at sunrise")\ = (0.5*0.25)/(1/5)\ =5/8 $ == - Draw a single card from a standard deck of 52 cards. Let A be the event that the card is red, and B be the event that the card is a queen. Show: A and B are independent. show $P(A sect B)=P(A )*P(B )$\ $P(A sect B)= 1/52 + 1/52 = 2/52$\ $P(A)*P(B)= 1/2 * 1/13 = 1/26$\ $2/52 = 1/26$ ------------------------ * Claim: If A and B are independent, then $A^c and B, A and B^c, A^c and B^c$ are independent* Proove:\ $P(A^c sect B)=P(B)-P(A sect B)\ =P(B)-P(A)P(B)\ =P(B)(1-P(A))\ =P(B)P(A^c)$ -------------------------\ _*Independence of multiple events*_\ Events $A_1, ..., A_n$ are mutually independent if for every collection of events $A_{i_1}, ..., A_{i_k}$, $ P(A_{i_1} sect ... sect A_{i_k})=P(A_{i_1})...P(A_{i_k}) $ for example, for events A,B,C, if $ P(a sect b)=P(A)P(B)\ P(A sect C)=P(A)P(C)\ P(B sect C)=P(B)P(C)\ =>P(A sect B sect C)=P(A)P(B)P(C) $ We say, A,B,C are mutually independent. =examples\ Roll a fair 4-sided die. let $ A={1,2},B={1,3},C={1,4} $, $ P(A)=P(B)=P(C)=2/4 $, $ P(A sect B)=P(A sect C)=P(B sect C)=P({1})=1/4 $, we know $ P(A sect B sect C)=P({1})=1/4 != P(A)P(B)P(C)=1/8 $ Not mutually independent. -----------------------\ == Random varaibles in Independence For random variables $X_1,X_2,...,X_n$ on the same prob. space, we say they are independent if $ P(X_1 in B_1, X_2 in B_2, ..., X_n in B_n)=P(X_1 in B_1)P(X_2 in B_2)...P(X_n in B_n) $for all choices of B_k (Diffidult to check) - For discrete random variables, we can check independence if and only if $P(X_1=x_1, X_2=x_2, ..., X_n=x_n)= P(X_1=x_1)P(X_2=x_2)...P(X_n=x_n)$ for all choices of $x_1, x_2, ..., x_n$ == examples\ roll a red die and blue die, $Omega = {1,2,...,6} times {1,2,...,6}$
https://github.com/DrakeAxelrod/cvss.typ
https://raw.githubusercontent.com/DrakeAxelrod/cvss.typ/main/README.md
markdown
MIT License
<!-- Improved compatibility of back to top link: See: https://github.com/othneildrew/Best-README-Template/pull/73 --> <a name="readme-top"></a> <!-- *** Thanks for checking out the Best-README-Template. If you have a suggestion *** that would make this better, please fork the repo and create a pull request *** or simply open an issue with the tag "enhancement". *** Don't forget to give the project a star! *** Thanks again! Now go create something AMAZING! :D --> <!-- PROJECT SHIELDS --> <!-- *** I'm using markdown "reference style" links for readability. *** Reference links are enclosed in brackets [ ] instead of parentheses ( ). *** See the bottom of this document for the declaration of the reference variables *** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use. *** https://www.markdownguide.org/basic-syntax/#reference-style-links --> [![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![Issues][issues-shield]][issues-url] [![MIT License][license-shield]][license-url] <!-- [![LinkedIn][linkedin-shield]][linkedin-url] --> <!-- PROJECT LOGO --> <br /> <div align="center"> <!-- <a href="https://github.com/DrakeAxelrod/cvss.typ"> <img src="resources/svg/logo.svg" alt="Logo" width="160" height="160"> </a> --> <h3 align="center">cvss.typ</h3> <p align="center"> The CVSS Typst Library is a <a href="https://github.com/typst/">Typst</a> package designed to facilitate the calculation of Common Vulnerability Scoring System (CVSS) scores for vulnerabilities across multiple versions, including CVSS 2.0, 3.0, 3.1, and 4.0. This library provides developers, security analysts, and researchers with a reliable and efficient toolset for assessing the severity of security vulnerabilities based on the CVSS standards. <br /> <a href="https://github.com/DrakeAxelrod/cvss.typ"><strong>Explore the docs »</strong></a> <br /> <br /> <!-- <a href="https://github.com/DrakeAxelrod/cvss.typ">View Tests</a> · --> <a href="https://github.com/DrakeAxelrod/cvss.typ/issues">Report Bug</a> · <a href="https://github.com/DrakeAxelrod/cvss.typ/issues">Request Feature</a> </p> </div> <!-- TABLE OF CONTENTS --> <details> <summary>Table of Contents</summary> <ol> <li> <a href="#about-the-project">About The Project</a> <ul> <li><a href="#built-with">Built With</a></li> </ul> </li> <li> <a href="#getting-started">Getting Started</a> <ul> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#installation">Installation</a></li> </ul> </li> <li><a href="#usage">Usage</a></li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#contributing">Contributing</a></li> <li><a href="#license">License</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#acknowledgments">Acknowledgments</a></li> </ol> </details> <!-- ABOUT THE PROJECT --> ## About The Project <!-- [![Product Name Screen Shot][product-screenshot]](https://example.com) --> ```typ #import "@preview/cvss:0.1.0": score, severity, parse, re, NONE, LOW, MEDIUM, HIGH, CRITICAL; #score("CVSS:2.0/AV:L/AC:H/Au:M/C:P/I:C/A:C") // => 5.6 #severity("CVSS:2.0/AV:L/AC:H/Au:M/C:P/I:C/A:C") // => "Medium" #score("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") // => 9.8 #severity("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") // => "Critical" #score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:H") // => 8.6 #severity("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:H") // => "High" #score("CVSS:4.0/AV:A/AC:H/AT:P/PR:L/UI:P/VC:H/VI:H/VA:L/SC:L/SI:L/SA:L") // => 5.3 #severity("CVSS:4.0/AV:A/AC:H/AT:P/PR:L/UI:P/VC:H/VI:H/VA:L/SC:L/SI:L/SA:L") // => "Medium" ``` <!-- Here's a blank template to get started: To avoid retyping too much info. Do a search and replace with your text editor for the following: `github_username`, `repo_name`, `twitter_handle`, `linkedin_username`, `email_client`, `email`, `project_title`, `project_description` --> <p align="right">(<a href="#readme-top">back to top</a>)</p> ### Built With - [![Typst][Typst]][Typst-url] - [![Rust][Rust]][Rust-url] - [![WASM][WASM]][WASM-url] <!-- - [![React][React.js]][React-url] - [![Vue][Vue.js]][Vue-url] - [![Angular][Angular.io]][Angular-url] - [![Svelte][Svelte.dev]][Svelte-url] - [![Laravel][Laravel.com]][Laravel-url] - [![Bootstrap][Bootstrap.com]][Bootstrap-url] - [![JQuery][JQuery.com]][JQuery-url] --> <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- GETTING STARTED --> ## Getting Started <!-- This is an example of how you may give instructions on setting up your project locally. To get a local copy up and running follow these simple example steps. --> Ensure you have the Typst CLI installed. 1. Import the package ```typ #import "@preview/cvss:0.1.0"; ``` 2. Use the various library functions to calculate CVSS scores and severities. ```typ #import "@preview/cvss:0.1.0"; #cvss.score("CVSS:2.0/AV:L/AC:H/Au:M/C:P/I:C/A:C") // => 5.6 #cvss.severity("CVSS:2.0/AV:L/AC:H/Au:M/C:P/I:C/A:C") // => "Medium" #cvss.score("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") // => 9.8 #cvss.severity("CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") // => "Critical" #cvss.score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:H") // => 8.6 #cvss.severity("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:H") // => "High" #cvss.score("CVSS:4.0/AV:A/AC:H/AT:P/PR:L/UI:P/VC:H/VI:H/VA:L/SC:L/SI:L/SA:L") // => 5.3 #cvss.severity("CVSS:4.0/AV:A/AC:H/AT:P/PR:L/UI:P/VC:H/VI:H/VA:L/SC:L/SI:L/SA:L") // => "Medium" ``` 3. the library has pseudo constants for the various severity levels. ```typ #cvss.NONE => "None" #cvss.LOW => "Low" #cvss.MEDIUM => "Medium" #cvss.HIGH => "High" #cvss.CRITICAL => "Critical" ``` 4. The library also provides a `parse` function to parse a CVSS string into a structured object. ```typ #cvss.parse("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:H") // ( // score: 8.6, // severity: "High", // metrics: ( // AV: "N", // AC: "L", // PR: "N", // UI: "N", // S: "U", // C: "L", // I: "L", // A: "H" // version: "3.1" // ) // ) ``` all functions / variables contained in the library are the following: - `score` - a function that takes a CVSS string and returns the CVSS score as a float. - `severity` - a function that takes a CVSS string and returns the CVSS severity as a string. - `metrics` - a function that takes a CVSS string and returns the CVSS metrics as a structured object. - `parse` - a function that takes a CVSS string and returns a structured object containing the CVSS score, severity, and metrics. - `verify` - a function that takes a CVSS string and returns a boolean indicating whether the string is a valid CVSS string. - `NONE` - a pseudo constant representing the "None" severity level. - `LOW` - a pseudo constant representing the "Low" severity level. - `MEDIUM` - a pseudo constant representing the "Medium" severity level. - `HIGH` - a pseudo constant representing the "High" severity level. - `CRITICAL` - a pseudo constant representing the "Critical" severity level. - `re` - a regular expression object used to parse CVSS strings. ### Prerequisites This is an example of how to list things you need to use the software and how to install them. - typst (see [Typst](https://typst.app/)) <!-- ### Installation --> <!-- 1. Get a free API Key at [https://example.com](https://example.com) 2. Clone the repo ```sh git clone https://github.com/DrakeAxelrod/cvss.typ.git ``` 3. Install NPM packages ```sh npm install ``` 4. Enter your API in `config.js` ```js const API_KEY = "ENTER YOUR API" ``` --> <!-- <p align="right">(<a href="#readme-top">back to top</a>)</p> --> <!-- USAGE EXAMPLES --> ## Usage Use this space to show useful examples of how a project can be used. Additional screenshots, code examples and demos work well in this space. You may also link to more resources. _For more examples, please refer to the [Examples](./src/examples.pdf)_ <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- ROADMAP --> ## Roadmap <!-- - [ ] Feature 1 - [ ] Feature 2 - [ ] Feature 3 - [ ] Nested Feature --> See the [open issues](https://github.com/DrakeAxelrod/cvss.typ/issues) for a full list of proposed features (and known issues). <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTRIBUTING --> ## Contributing Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again! 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- LICENSE --> ## License Distributed under the MIT License. See `LICENSE.txt` for more information. <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTACT --> ## Contact <!-- <img src="https://avatars.githubusercontent.com/u/51012876?v=4" height="60px" width="60px"></img> --> <NAME> - [Github Profile](<[https://github/](https://github.com/DrakeAxelrod/)>) - <EMAIL> Project Link: [https://github.com/DrakeAxelrod/cvss.typ](https://github.com/DrakeAxelrod/cvss.typ) ## Contributors <table> <tbody> <tr> <td align="center" valign="top" width="14.28%"><a href="https://github.com/DrakeAxelrod"><img src="https://avatars.githubusercontent.com/u/51012876?v=4?s=64" width="64px;" alt="Drake Axelrod"/><br /><sub><b>Drake Axelrod</b></sub></a><br /> </tr> </tbody> </table> <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- ACKNOWLEDGMENTS --> ## Acknowledgments - [Typst](https://typst.app/) - [First.org](https://www.first.org) - [Rust Library - cvss_tools](https://docs.rs/cvss_tools) - [Rust Library - cvssrust](https://docs.rs/cvssrust/latest/cvssrust/) <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [contributors-shield]: https://img.shields.io/github/contributors/DrakeAxelrod/cvss.typ.svg?style=for-the-badge [contributors-url]: https://github.com/DrakeAxelrod/cvss.typ/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/DrakeAxelrod/cvss.typ.svg?style=for-the-badge [forks-url]: https://github.com/DrakeAxelrod/cvss.typ/network/members [stars-shield]: https://img.shields.io/github/stars/DrakeAxelrod/cvss.typ.svg?style=for-the-badge [stars-url]: https://github.com/DrakeAxelrod/cvss.typ/stargazers [issues-shield]: https://img.shields.io/github/issues/DrakeAxelrod/cvss.typ.svg?style=for-the-badge [issues-url]: https://github.com/DrakeAxelrod/cvss.typ/issues [license-shield]: https://img.shields.io/github/license/DrakeAxelrod/cvss.typ.svg?style=for-the-badge [license-url]: https://github.com/DrakeAxelrod/cvss.typ/blob/master/LICENSE.txt [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 [linkedin-url]: https://linkedin.com/in/linkedin_username [product-screenshot]: images/screenshot.png [Next.js]: https://img.shields.io/badge/next.js-000000?style=for-the-badge&logo=nextdotjs&logoColor=white [Next-url]: https://nextjs.org/ [React.js]: https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB [React-url]: https://reactjs.org/ [Vue.js]: https://img.shields.io/badge/Vue.js-35495E?style=for-the-badge&logo=vuedotjs&logoColor=4FC08D [Vue-url]: https://vuejs.org/ [Angular.io]: https://img.shields.io/badge/Angular-DD0031?style=for-the-badge&logo=angular&logoColor=white [Angular-url]: https://angular.io/ [Svelte.dev]: https://img.shields.io/badge/Svelte-4A4A55?style=for-the-badge&logo=svelte&logoColor=FF3E00 [Svelte-url]: https://svelte.dev/ [Laravel.com]: https://img.shields.io/badge/Laravel-FF2D20?style=for-the-badge&logo=laravel&logoColor=white [Laravel-url]: https://laravel.com [Bootstrap.com]: https://img.shields.io/badge/Bootstrap-563D7C?style=for-the-badge&logo=bootstrap&logoColor=white [Bootstrap-url]: https://getbootstrap.com [JQuery.com]: https://img.shields.io/badge/jQuery-0769AD?style=for-the-badge&logo=jquery&logoColor=white [JQuery-url]: https://jquery.com [Typst]: https://img.shields.io/badge/Typst-239dad?style=for-the-badge&logo=typst&logoColor=white [Typst-url]: https://typst.app/ [Rust]: https://img.shields.io/badge/Rust-b7410e?style=for-the-badge&logo=rust&logoColor=white [Rust-url]: https://www.rust-lang.org/ [WASM]: https://img.shields.io/badge/WebAssembly-654FF0?style=for-the-badge&logo=webassembly&logoColor=white [WASM-url]: https://webassembly.org/
https://github.com/Dav1com/wasm-random-plugin
https://raw.githubusercontent.com/Dav1com/wasm-random-plugin/master/test.typ
typst
MIT License
#let _plugin = plugin("./target/wasm32-unknown-unknown/release/wasm_random_plugin.wasm") = abc = hola #{ let x = _plugin.hello(bytes((1,))) linebreak() [#for i in range(8) [ #x.at(i)] ] let y = _plugin.hello(bytes((2,))) linebreak() [#for i in range(8) [ #y.at(i)] ] } #locate(loc => { let counter = counter(heading).final(loc) [#counter] let x = _plugin.hello(bytes((1,))) linebreak() [#for i in range(8) [ #x.at(i)] ] let y = _plugin.hello(bytes((2,))) linebreak() [#for i in range(8) [ #y.at(i)] ] let z = _plugin.hello(bytes((3,))) linebreak() [#for i in range(8) [ #z.at(i)] ] }) = anotherone #locate(loc => { let counter = counter(heading).final(loc) if counter.len() >= 4 { heading("wuajaja") } }) #locate(loc => { let counter = counter(heading).final(loc) if counter.len() >= 3 { heading("wuajaja") } })
https://github.com/connachermurphy/typst-slides
https://raw.githubusercontent.com/connachermurphy/typst-slides/main/template_slides.typ
typst
MIT License
// Get short_title into footer without having to pass short_title to #slide // #let heading_font = "Futura" // #let body_font = "Lora" // #let body_font = "Linux Libertine" #let title_size = 28pt #let body_size = 20pt #let foot_size = 12pt #let presentation( title, author, date, body ) = { set page( paper: "presentation-16-9", // margin: 0%, margin: (bottom: 15pt, rest: 25pt) ) set text(font: "Verdana") block( width: 100%, height: 100%, spacing: 0%, inset: 10%, // fill: teal, breakable: false )[ #set align(center + horizon) #set text(size: 36pt) #title #set text(size: 16pt) #author #date ] counter(page).update(0) body } #let divider( heading: "Divider heading", ) = { block( width: 100%, height: 100%, spacing: 0%, inset: 10%, // fill: teal, breakable: false )[ #set align(center + horizon) #set text(size: 36pt) #heading ] } #let slide( heading: "Slide heading", title_short: "Short title", lab: "lab", body, ) = { pagebreak() // label(repr([#lab])) block( width: 100%, height: 10%, spacing: 0%, // inset: 20pt, // fill: teal, breakable: false )[ // #set align(left + bottom) #set align(left + horizon) #set text( size: title_size, fill: olive ) // #label( // repr(lab) // ) #heading // #let s(x: hello) = { x } // #let f() = { s = "abc" } // #s() #label(lab) // Label portion: #label(repr([#lab])) // Label portion: #label("a_sample_label") // Label portion: #label(lab) // #lab => label(lab) // #lab => label(lab) ] block( width: 100%, height: 75%, spacing: 5%, // inset: 20pt, // fill: gray, breakable: false )[ #set text( size: body_size, fill: luma(25) ) #body ] block( width: 100%, height: 5%, spacing: 0%, // inset: (top: 20pt, bottom: 20pt), // fill: green, breakable: false )[ #set text( size: foot_size, fill: luma(25) ) #stack( dir: ltr, block(width: 90%, height: 100%)[ #set align(left + horizon) #title_short ], block(width: 10%, height: 100%)[ #set align(right + horizon) #locate( loc => counter(page).at(loc).at(0) ) ], ) ] } #let linkbox( lab, fill: maroon, color: white, outset: 3pt, inset: 3pt, radius: 5pt, body, ) = { link( label(lab), )[ #box( fill: fill, outset: outset, inset: inset, radius: radius, )[ #text( fill: color, size: 0.75em, )[#body] ] ] } #let stylebox( color_bar: gray, color_fill: gray, body ) = { block( stroke: (left: color_bar + 4pt,), fill: color_fill.lighten(80%), width: 100%, // inset: (left: 10pt, right: 0pt, rest: 4pt,), inset: (10pt), breakable: true, )[ #body ] }
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/homework/linear-algebra-homework14.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra Homework #14", authors: ( (name: "<NAME> (#95)", email: "<EMAIL>", phone: "3230104585"), ), date: "December 26, 2023", ) #let AA = math.bold(math.italic("A")) #let BB = math.bold(math.italic("B")) #let XX = math.bold(math.italic("X")) #let YY = math.bold(math.italic("Y")) #let EE = math.bold(math.italic("E")) #let OO = math.bold(math.italic("O")) #let TT = math.upright("T") #let x1 = math.attach(math.italic("x"), br: math.upright("1")) #let x2 = math.attach(math.italic("x"), br: math.upright("2")) #let x3 = math.attach(math.italic("x"), br: math.upright("3")) #let y1 = math.attach(math.italic("y"), br: math.upright("1")) #let y2 = math.attach(math.italic("y"), br: math.upright("2")) #let y3 = math.attach(math.italic("y"), br: math.upright("3")) #let alpha = math.bold(math.alpha) #let beta = math.bold(math.beta) #let Lambda = math.bold(math.Lambda) #let diag = math.upright("diag") #let ssim = math.attach(sp + math.upright("~") + sp, tl: "", tr:"", t: math.upright("S")) = P148 习题六 1 & 2 & 11 & 15 #ac #prob[ 用配方法化二次型为标准形,并写出所用的非退化线性替换;然后用矩阵形式将其化为标准形、二次型在复数域及实数域上的规范形、用正交替换将二次型化为标准形. (1) $f(x1,x2,x3) = x1^2 + 2x1 x2 + 2 x2^2 + 4 x2 x3 + x3 ^2$. ] #prob[(4) $f(x1,x2,x3) = 2 x1 x3 + 4 x2 x3$.] 比较复杂,写在纸上了. = P149 习题六 6 #prob[ 证明:一个可逆的对称矩阵必与它的逆矩阵合同. ] 注意到: $ AA^TT AA^(-1) AA = AA^TT = AA $ 故矩阵 $AA$ 和逆矩阵 $AA^(-1)$ 合同. = P149 习题六 8 #prob[ 设 $f(seqn(x,n))$ 是一个实二次型,其秩为 $r$,证明:在 $RR^n$ 中存在 $n-r$ 维子空间 $V$,使得对任意的 $display(mat(x_1^0,x_2^0,dots.c,x_n^0))^TT in V$,均有 $f(x_1^0,x_2^0,dots.c,x_n^0) = 0$. ] 可通过非退化线性变换 $YY = bold(C) XX$ 将 $f(seqn(x,n))$ 化为标准形 $ f(seqn(y,n)) = d_1 y_1 ^2 + d_2 y_2^2 + dots.c + d_r y_r^2 + 0 dot y_(r+1)^2 + dots.c + 0 dot y_n^2 $ 设 $V_y = {YY in RR^n | y_1=y_2=dots.c=y_r}$,显然有 $dim V_y = n-r$. 而对于 $V_x = {bold(C)^(-1) YY | YY in V_y }$,$V_x$ 中的向量和 $V_y$ 中的向量一一对应,故有 $dim V_x = n-r$ 也成立,这个 $V_x$ 即所求的子空间 $V$. = P149 习题六 10 #prob[ 设 $AA$ 是二阶实对称矩阵.若 $AA^2 + AA = 2 EE$ 且 $|AA| = 4$,则二次型 $XX^TT AA XX$ 的实规范形为($quad$) (A) $y1^2+y2^2+y3^2$ (B) $y1^2+y2^2-y3^2$ (C) $y1^2-y2^2-y3^2$ (D) $-y1^2-y2^2-y3^2$ ] 设 $AA = display(mat(a,b;b,c))$,则 $ AA^2 + AA = 2 EE <=> mat( a^2 + b^2 + a, a b + b c + b; a b + b c + b, b^2 + c^2 + c; ) = mat( 2, 0; 0, 2; )\ |AA| = a c - b^2 = 4 $ 综上,有 $ cases( a^2 + a + b^2 = 2, c^2 + c + b^2 = 2, (a+c+1) b = 0, a c - b^2 = 4, ) $ TBD = P149 习题六 13 #prob[如果把 $n$ 阶实对称矩阵按实数域上的合同关系分类(即两个 $n$ 阶实对称矩阵数域同一类,当且仅当他们是合同的),问共有几类?] 所对应标准形的秩 $r$ 和正惯性系数 $p$ 可以确定一类实对称矩阵. $ sum_(r=0)^n sum_(p=0)^(r) 1 = sum_(r=0)^n (r+1) = ((n+1)(n+2))/2 $ 共有 $display(((n+1)(n+2))/2)$ 类. = P149 习题六 14 #prob[证明:一个实二次型可以分解成两个实系数的一次齐次多项式的乘积,当且仅当它的秩为 $2$ 且符号差为 $0$,或者秩等于 $1$.] 设两个一次齐次多项式的系数向量分别为 $alpha$ 和 $beta$,则有 $ AA = 1/2 (alpha beta^TT + beta alpha^TT) $ 其中由于 $alpha,beta$ 非零向量,故 $r(AA)>0$.同时有 $r(alpha beta^TT) = r(beta alpha^TT) = 1$,故有 $1<=r(AA)<=2$. TBD = P150 习题六 18 #prob[ 已知二次曲面方程 $x^2 + a y^2 + z^2 + 2b x y + 2 x z + 2 y z= 4$ 可经过正交替换: $ mat(x;y;z) = bold(U) mat(xi;eta;zeta) $ 化为椭圆柱面方程 $eta^2 + 4 zeta^2 = 4$,求 $a,b$ 的值和正交矩阵 $bold(U)$. ] 设二次型 $f(x,y,z) = x^2 + a y^2 + z^2 + 2b x y + 2 x z + 2 y z= 4$,则对应的矩阵表达式为: $ AA = mat( 1,b,1; b,a,1; 1,1,1; ) => exists sp bold(U) st bold(U)^TT AA bold(U) = mat( 0,0,0; 0,1,0; 0,0,4; ) $ 且可知特征多项式 $|lambda EE - AA| = lambda(lambda-1)(lambda-4)$. $ tr(AA) = 0 + 1 + 4 = 1 + a + 1 => a = 3\ r(AA) <= 2 => k_1 mat(1,b,1) + k_2 mat(b,3,1) = mat(1,1,1) => b=1 $ 解得 $AA$ 每个特征值对应的特征向量分别为: $ cases( xi_1=display(mat(1,0,-1)), xi_2=display(mat(1,-1,1)), xi_3=display(mat(1,2,1)), ) sp ==> sp bold(U) = mat( 1/sqrt(2),1/sqrt(3),1/sqrt(6); 0,-1/sqrt(3),sqrt(2)/sqrt(3); -1/sqrt(2),1/sqrt(3),1/sqrt(6); ) $ = P150 习题六 20 #prob[ 设二次型 $f(x1,x2) = x1^2 - 4 x1 x2 + 4 x2^2$ 经正交替换 $display(mat(x1;x2) = bold(U) mat(y1;y2))$ 化为二次型 $ g(y1,y2) = a y1^2 + 4 y1 y2 + b y2^2 $ 其中 $a>=b$.求 $a,b$ 的值和正交矩阵 $bold(U)$. ] = P150 习题六 21 #prob[ 设实二次型 $ f(x1,x2,x3) = (x1-x2+x3)^2 + (x2+x3)^2 + (x1+a x3)^2 $ 其中 $a$ 是参数. (1) 求 $f(x1,x2,x3) = 0$ 的解. ] #prob[(2) 求 $f(x1,x2,x3)$ 的规范形.] = P150 习题六 24 #prob[设二次型 $f(x1,x2,x3) = x1^2 - x2^2 + x3^2 + 2 a x1 x3 + 4 x2 x3$ 的负惯性指数为 $1$,求 $a$ 的取值范围.] = P150 习题六 25 #prob[ 设二次型 $ f(x1,x2,x3) = 2 (a_1 x1 + a_2 x2 + a_3 x3)^2 + (b_1 x1 + b_2 x2 + b_3 x3)^2 $ 记 $alpha = display(mat(a_1,a_2,a_3))^TT,sp beta = display(mat(b_1,b_2,b_3))^TT$. (1) 证明:二次型 $f$ 对应的矩阵为 $2 alpha alpha^TT + beta beta^TT$. ] #prob[(2) 证明:若 $alpha,beta$ 正交且均为单位向量,则 $f$ 在正交替换下的标准形为 $2 y1^2 + y2^2$.] = P151 习题六 28 #prob[ 设二次型 $f(x1,x2,x3) = a x1^2 + a x2^2 + (a-1) x3^2 + 2 x1 x3 - 2 x2 x3$. (1) 求二次型 $f$ 的矩阵的所有特征值. ] #prob[(2) 若二次型 $f$ 的规范形为 $y1^2 + y2^2$,求 $a$ 的值.]
https://github.com/ufodauge/typst-algomod
https://raw.githubusercontent.com/ufodauge/typst-algomod/main/algomod.typ
typst
MIT License
#let algomodState = state("algomod_state", ( number: 0, indent: 0, )) #let updateIndent(lambda) = { assert(type(lambda) == "function") algomodState.update(dict => { let indent = lambda(dict.indent) dict.indent = calc.max(indent, 0) return dict }) } #let createStatement( preIndent: 0, postIndent: 0, body, ) = { let newBody = body if body != none { newBody = (body, ) } return ( preIndent: preIndent, postIndent: postIndent, body: newBody, ) } // // environment // #let algomod = ( indentSize: 1em, format: none, ) => { assert( type(indentSize) == "length", message: "expected relative length, got " + type(indentSize) + ".") assert( format == none or type(format) == "function", message: "expected none or function, got " + type(format) + ".") let template = ( title: "", label: none, lines: () ) => { assert( type(title) == "content" or type(title) == "string", message: "expected content or string, got " + type(title)) assert( type(label) == "none" or type(label) == "label", message: "expected content or string, got " + type(title)) assert( type(lines) == "array", message: "expected array, got " + type(lines)) assert( lines.all(v => type(v) == "dictionary" or type(v) == "content"), message: "unexpected line type.") // convert raw content to statement object lines = lines.map(line => { if type(line) == "content" { return createStatement(line) } return line }) let reservedIndent = 0 for (i, line) in lines.enumerate() { if line.body == none { reservedIndent += line.preIndent + line.postIndent } else { lines.at(i).preIndent += reservedIndent reservedIndent = 0 } } // delete empty body lines = lines.filter(v => v.body != none) // update algorithm number algomodState.update(dict => { dict.number = dict.number + 1 return dict }) let algorithmNumber = algomodState.display(v => [#v.number]) let formattedLines = () for line in lines { formattedLines.push( algomodState.display(v => { let indentAmount = v.indent + line.preIndent for body in line.at("body") { [#h(indentSize * indentAmount) #body] } updateIndent(w => w + line.preIndent + line.postIndent) }) ) } let displayFormat = format let displayTitle = [*Algorithm #algorithmNumber* #title] if displayFormat == none { displayFormat = (title, body) => [ #pad(bottom: -.8em, align(center, line(length: 100%))) #pad(left: 1em, [#title#label]) #pad(top: -.8em, bottom: -.6em, align(center, line(length: 100%))) #enum(..formattedLines) #pad(top: -.6em, align(center, line(length: 100%))) ] } return displayFormat(displayTitle, formattedLines) } return template } // // reference // #let algomodLink(label) = { locate(loc => { let labelLocation = query(label, loc) .first() .location() let number = algomodState .at(labelLocation) .at("number") return link(labelLocation, [Algorithm #number]) }) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/octique/0.1.0/octique.typ
typst
Apache License 2.0
#import "impl/octique.typ": _octique-svg, _octique-image // Returns an image for the given name. #let octique(name, color: rgb("#000000"), width: 1em, height: 1em) = _octique-image(name, color: color, width: width, height: width) // Returns a boxed image for the given name. #let octique-inline(name, color: rgb("#000000"), width: 1em, height: 1em, baseline: 25%) = { box(baseline: baseline, octique(name, color: color, width: width, height: height)) } // Returns an SVG text for the given name. #let octique-svg(name) = _octique-svg(name)
https://github.com/DrGo/typst-tips
https://raw.githubusercontent.com/DrGo/typst-tips/main/src/chapter.typ
typst
// function that gets a chapter as its `body` and formats // it as a chapter in a scientific book #let chapter( // The Chapter's title. title: "Chapter title", // The chapters's authors. author: "", // The paper size to use. paper: "us-letter", // paletino OS replacement "TeX <NAME>", body_font: "Minion Pro", title_font: "Lato", hyphenate: false, bibliography-file: none, // The chapter's content. body, ) = { // Set the document's metadata. set document(title: title, author: author) // Configure the page properties. set page( paper: paper, margin: (outside: 1.0in, inside: 1.125in, bottom:1.125in+0.4in, top: 1.125in + 0.4in), header-ascent: 0.4in, footer-descent: 0.3in, numbering: "1", //TODO: allow optional header + page numbers // The header always contains the chapter title on odd pages and // the section title on even pages, unless the page is one // the starts a chapter (the chapter title is obvious then). header: locate(loc => { // Are we on an odd page? at() returns an array but we know it has one value let i = counter(page).at(loc).first() // let pagenum=[#loc.page()] if calc.odd(i) { return text(0.95em, smallcaps(title)) } // Are we on a page that starts a chapter? (We also check // the previous page because some headings contain pagebreaks.) let all = query(heading, loc) if all.any(it => it.location().page() in (i - 1, i)) { return } // Find the heading of the section we are currently in. let before = query(selector(heading).before(loc), loc) if before != () { align(right, text(0.95em, smallcaps(before.last().body))) } }), ) //header: locate(loc => { //let elems = query( // selector(heading).before(loc),loc, //) //let even=calc.even(counter(page).at(loc).at(0)) //let chap_title = smallcaps[ // Typst chap_title //] //let page=[#loc.page()] //if even { // page + h(1fr) + chap_title //} else { ////if headers are available ie after 1st section // if elems.len()>0 { // let body = smallcaps(counter(heading).display() + " " + elems.last().body) // emph(body) + h(1fr) + page // } //} //}), // set text(font: "New Computer Modern", lang: "en") set text( size: 11pt, // Set the body font. TeX G<NAME> is a free alternative // to Palatino. font: body_font, // font: "New Computer Modern", lang: "en", hyphenate: hyphenate, ) // MATH show math.equation: set text(weight: 400) // set math.equation(numbering: "(1.1)") // Currently not directly supported by typst set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Paragraph settings set par( justify: true, // leading: 0.78em, ) show par: set block( spacing: 0.78em, // Set paragraph spacing. above: 1.2em, below: 1.2em, ) // The first page. // page(align(center + horizon)[ // #text(2em)[*#title*] // #v(2em, weak: true) // #text(1.6em, author) // ]) // Configure chapter headings. show heading.where(level: 1): it => { //FIXME: add option to control chapter title page // Always start on even pages. // pagebreak() // counter(page).display(i => if calc.odd(i) { // pagebreak() // }) // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } v(5%) text(2em, weight: 700, block([#number #it.body])) v(1.25em) } // show heading.where(level: 2): set text(size: 14pt) // // Configure headings. // show heading: set text(font: "Syne") // show heading.where(level: 1): set text(1.1em) // show heading.where(level: 1): set par(leading: 0.4em) // show heading.where(level: 1): set block(below: 0.8em) // show heading: it => { // set text(weight: 600) if it.level > 2 // it // } // show heading: set text(11pt, weight: 400) show heading: set text( font: title_font, ) set heading( numbering: "1.1", ) // Links should be underlined. show link: underline // footnotes set footnote.entry( gap: 0.8em ) // numbering of footnotes show footnote.entry: it => { let loc = it.note.location() numbering( "1: ", ..counter(footnote).at(loc), ) it.note.body } // Configure figures. show figure: it => block({ // Display a backdrop rectangle. move(dx: -3%, dy: 1.5%, rect( fill: rgb("FF7D79"), inset: 0pt, move(dx: 3%, dy: -1.5%, it.body) )) // Display caption. if it.has("caption") { set align(center) set text(font: "Syne") v(if it.has("gap") { it.gap } else { 24pt }, weak: true) [-- ] it.caption if it.numbering != none { [ (] + counter(figure).display(it.numbering) + [)] } [ --] } v(48pt, weak: true) }) body // Display bibliography. if bibliography-file != none { show bibliography: set text(8pt) bibliography(bibliography-file, title: text(10pt)[References], style: "ieee") } } //Title // Display the paper's title. // v(3pt, weak: true) // align(center, text(18pt, title)) // v(8.35mm, weak: true) // // A stylized block with a quote and its author. #let blockquote(by, body) = box(inset: (x: 0.4em, y: 12pt), width: 100%, { set text(font: "Syne") grid( columns: (1em, auto, 1em), column-gutter: 12pt, rows: (1em, auto), row-gutter: 8pt, text(5em)["], line(start: (0pt, 0.45em), length: 100%), none, none, text(1.4em, align(center, body)), none, none, v(8pt) + align(right, text(font: "Barlow")[---#by]), ) } ) // A theorum block as ann example of a custom counter // #theorem[$1 = 1$] #let c = counter("theorem") #let theorem(it) = block[ #c.step() *Theorem #c.display():* #it ] // custom block // #task(critical: true)[Food today?] //#task(critical: false)[Work deadline] #let task(body, critical: false) = { set text(red) if critical [- #body] }
https://github.com/tony-rsa/thonifho.muhali.cv
https://raw.githubusercontent.com/tony-rsa/thonifho.muhali.cv/main/src/sections/ru/projects.typ
typst
MIT License
#import "../../template.typ": * #cvSection("Проекты") #cvEntry( title: [Spin], host: [#link("https://github.com/tensorush/zig-spin")[#gh #hSpc() tensorush/zig-spin]], date: [23 сентября, 2023], mode: [Разрабатывается], logo: "assets/logos/spn.png", desc: [#emoji.lizard #emoji.yoyo Zig SDK для Spin, фреймворка бессерверных приложений, созданного командой Fermyon.], ) #cvEntry( title: [Meduza], host: [#link("https://github.com/tensorush/meduza")[#gh #hSpc() tensorush/meduza]], date: [16 октября, 2023], mode: [Поддерживается], logo: "assets/logos/mdz.png", desc: [#emoji.lizard #emoji.merperson Генератор графа Zig-репозитория, создающий классовую диаграмму в формате Mermaid.], ) #cvEntry( title: [Bookkeeper], host: [#link("https://github.com/tensorush/bookkeeper")[#gh #hSpc() tensorush/bookkeeper]], date: [1 сентября, 2023], mode: [Завершен], logo: "assets/logos/bkr.png", desc: [#emoji.hamster #emoji.books Серверная часть бухгалтерской службы, реализованная на основе gRPC.], ) #cvEntry( title: [Zigzag], host: [#link("https://github.com/tensorush/zigzag")[#gh #hSpc() tensorush/zigzag]], date: [21 сентября, 2023], mode: [Поддерживается], logo: "assets/logos/zgz.png", desc: [#emoji.lizard #emoji.trident Трассировщик путей, исполняющийся в многопоточном режиме на CPU.], )
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/可视化/圈/quan.typ
typst
= circle 包含可选内容的圆圈。 = 例 #image("1.png") = 参数 #image("2.png") #image("3.png") #image("4.png")
https://github.com/Scriptorgames/JIF-JUFO-Paper
https://raw.githubusercontent.com/Scriptorgames/JIF-JUFO-Paper/main/template.typ
typst
#let script-size = 8pt #let footnote-size = 8.5pt #let small-size = 9pt #let normal-size = 10pt #let large-size = 12pt #import "term.typ": term #import "@preview/showybox:2.0.1": showybox #import "@preview/codelst:2.0.0": sourcecode #let sc = sourcecode.with( numbers-style: (lno) => text(size: 10pt, font: "Times New Roman", fill: rgb(0, 0, 0), str(lno)), frame: block.with( stroke: 1pt + rgb("#a2aabc"), radius: 2pt, inset: (x: 10pt, y: 5pt), fill: rgb("DBDBDB"), ), ) // This function gets your whole document as its `body` and formats // it as an article in the style of the American Mathematical Society. #let ams-article( // The article's title. title: [Paper title], // An array of authors. For each author you can specify a name, // department, organization, location, and email. Everything but // but the name is optional. authors: (), // Your article's abstract. Can be omitted if you don't have one. abstract: none, // The article's paper size. Also affects the margins. paper-size: "a4", // The path to a bibliography file if you want to cite some external // works. bibliography-file: none, // The document's content. body, ) = { // Formats the author's names in a list with commas and a // final "and". let names = authors.map(author => author.name) let author-string = if authors.len() == 2 { names.join(" und ") } else { names.join(", ", last: ", und ") } // Set document metadata. set document(title: title, author: names) // Set the body font. AMS uses the LaTeX font. set text(size: normal-size, font: "Times New Roman", lang: "DE") // Configure the page. set page( paper: paper-size, // The margins depend on the paper size. margin: if paper-size != "a4" { ( top: (116pt / 279mm) * 100%, left: (126pt / 216mm) * 100%, right: (128pt / 216mm) * 100%, bottom: (94pt / 279mm) * 100%, ) } else { (top: 2.5cm, left: 2.5cm, right: 2.5cm, bottom: 2cm) }, // The page header should show the page number and list of // authors, except on the first page. The page number is on // the left for even pages and on the right for odd pages. header-ascent: 14pt, header: locate( loc => { let i = counter(page).at(loc).first() if i == 1 { return } set text(size: script-size) grid( columns: (6em, 1fr, 6em), if calc.even(i) [#i], align(center, upper(if calc.odd(i) { title } else { author-string })), if calc.odd(i) { align(right)[#i] }, ) }, ), // On the first page, the footer should contain the page number. footer-descent: 12pt, footer: locate(loc => { let i = counter(page).at(loc).first() if i == 1 { align(center, text(size: script-size, [#i])) } }), ) // Configure headings. set heading(numbering: "1.") show heading: it => { // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } // Level 1 headings are centered and smallcaps. // The other ones are run-in. set text(size: normal-size, weight: 400) if it.level == 1 { set align(center) set text(size: normal-size) smallcaps[ #v(30pt, weak: true) #number #it.body #v(normal-size, weak: true) ] counter(figure.where(kind: "theorem")).update(0) } else { v(20pt, weak: true) number let styled = if it.level == 2 { strong } else { emph } styled(it.body + [. ]) h(7pt, weak: true) } } // Configure lists and links. set list(indent: 24pt, body-indent: 5pt) set enum(indent: 24pt, body-indent: 5pt) show link: set text(font: "New Computer Modern Mono") // Configure equations. show math.equation: set block(below: 8pt, above: 9pt) show math.equation: set text(weight: 400) // Configure citation and bibliography styles. set bibliography(style: "springer-mathphys", title: [References]) show figure: it => { show: pad.with(x: 23pt) set align(center) v(12.5pt, weak: true) // Display the figure's body. it.body // Display the figure's caption. if it.has("caption") { // Gap defaults to 17pt. v(if it.has("gap") { it.gap } else { 17pt }, weak: true) smallcaps(it.supplement) if it.numbering != none { [ ] it.counter.display(it.numbering) } [. ] it.caption.body } v(15pt, weak: true) } // Theorems. show figure.where(kind: "theorem"): it => block(above: 11.5pt, below: 11.5pt, { strong({ it.supplement if it.numbering != none { [ ] counter(heading).display() it.counter.display(it.numbering) } [.] }) emph(it.body) }) // Display the title and authors. v(35pt, weak: true) align(center, upper({ text(size: large-size, weight: 700, title) v(25pt, weak: true) text(size: footnote-size, author-string) })) pagebreak() outline() // Configure paragraph properties. set par(first-line-indent: 1.2em, justify: true, leading: 1.5em) show par: set block(spacing: 0.58em) // Display the abstract if abstract != none { v(20pt, weak: true) set text(script-size) show: pad.with(x: 35pt) smallcaps[Abstract. ] abstract } // Display the article's contents. //v(29pt, weak: true) pagebreak() body pagebreak() // Display the bibliography, if any is given. if bibliography-file != none { show bibliography: set text(8.5pt, lang: "DE") show bibliography: pad.with(x: 0.5pt) bibliography(bibliography-file, title: "Bibliographie") } // The thing ends with details about the authors. show: pad.with(x: 11.5pt) set par(first-line-indent: 0pt) set text(7.97224pt) for author in authors { let keys = ("department", "organization", "location") let dept-str = keys .filter(key => key in author) .map(key => author.at(key)) .join(", ") smallcaps(dept-str) linebreak() if "email" in author [ _Email address:_ #link("mailto:" + author.email) \ ] if "url" in author [ _URL:_ #link(author.url) ] v(12pt, weak: true) } } // The ASM template also provides a theorem function. #let theorem(body, numbered: true) = figure( body, kind: "theorem", supplement: [Theorem], numbering: if numbered { "1" }, ) // And a function for a proof. #let proof(body) = block(spacing: 11.5pt, { emph[Proof.] [ ] + body h(1fr) box(scale(160%, origin: bottom + right, sym.square.stroked)) })
https://github.com/AOx0/expo-nosql
https://raw.githubusercontent.com/AOx0/expo-nosql/main/book/src/basics.md
markdown
MIT License
# Basics This template allows you to produce presentation slides in [Typst](https://typst.app), just like you would use the _beamer_ package in LaTeX. (So far, it is much less advanced than beamer, obviously.) There are two main building blocks, the functions `slides` and `slide`. The first one, `slides` allows you to set up a document such that the PDF can be used as a presentation. As a rule of thumb, one slide becomes one PDF page, and most PDF viewers can display PDFs in the form of a slide show (usually by hitting the F5-key). The second function, `slide`, produces a single slide. This means that your code will be structured like this when using this template: ```typ #import "slides.typ": * #show: slides.with( /* configuration */ ) #slide[ First slide ] #slide[ Second slide ] #slide[ Third slide ] // ... ```
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/intro.md
markdown
--- sidebar_position: 1 --- # Introduction to Touying [Touying](https://github.com/touying-typ/touying) is a slide/presentation package developed for Typst, based on [Polylux](https://github.com/andreasKroepelin/polylux). Touying is similar to LaTeX Beamer but benefits from Typst, providing faster rendering speed and a more concise syntax. Hereafter, we use "slides" to refer to slideshows, "slide" for a single slide, and "subslide" for a sub-slide. ## Why Use Touying - Unlike PowerPoint, Touying is not a "what you see is what you get" tool. You can write your slides in a "content and style separation" manner, especially with Typst, which offers a concise yet powerful syntax, better supporting content like code blocks, mathematical formulas, and theorems. Another advantage is that, with templates, writing slides with Touying is much faster than PowerPoint. Therefore, Touying is more suitable for users with a demand for "research writing." - Compared to Markdown Slides, Touying, relying on Typst, has more powerful typesetting control, such as headers, footers, layout, and convenient custom functions. These are capabilities that Markdown struggles to provide, or does not do well. Additionally, Touying offers `#pause` and `#meanwhile` markers, providing more convenient dynamic slide capabilities. - Compared to Beamer, Touying has faster compilation speed, a more concise syntax, and simpler theme customization capabilities. Touying's compilation speed can be maintained in milliseconds or tens of milliseconds, compared to Beamer's compilation time of seconds or tens of seconds. Touying's syntax is more concise than Beamer, making it easier to change templates and create your own templates. In terms of features, Touying supports most of Beamer's capabilities and provides some convenient features that Beamer lacks. - Compared to Polylux, Touying provides an object-oriented programming (OOP) style syntax, allowing the simulation of "global variables" through a global singleton. This makes it easy to write themes. Touying does not rely on `counter` and `locate` to implement `#pause`, resulting in better performance. Touying is a community-driven project (we welcome more people to join), and it does not overly emphasize maintaining API consistency. Instead, it chooses to maintain documentation for multiple versions, providing more novel yet powerful features. ## About the Name "Touying" is derived from the Chinese word "投影" (tóuyǐng), which means "projection" In English, it also conveys the meaning of a "project". In comparison, the term "beamer" in LaTeX means a projector in German. ## About the Documentation This documentation is powered by [Docusaurus](https://docusaurus.io/). We will maintain English and Chinese versions of the documentation for Touying, and for each major version, we will maintain a documentation copy. This allows you to easily refer to old versions of the Touying documentation and migrate to new versions. Docusaurus creates a new version: ```sh npm run docusaurus docs:version 0.y.x ``` ## Contribution Touying is free, open-source, and community-driven. If you're interested, you can visit [GitHub](https://github.com/touying-typ/touying) anytime and raise issues or submit pull requests. We also welcome you to join the [touying-typ](https://github.com/touying-typ) organization. ## License Touying is released under the [MIT license](https://github.com/touying-typ/touying/blob/main/LICENSE).
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/terms_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test with constructor. #terms( ([One], [First]), ([Two], [Second]), )
https://github.com/Mr-lonely0/WHU-thesis-typst
https://raw.githubusercontent.com/Mr-lonely0/WHU-thesis-typst/main/README.md
markdown
# WHU-thesis-typst This repo reserves for typst template of WHU thesis.
https://github.com/ralphmb/My-Dissertation
https://raw.githubusercontent.com/ralphmb/My-Dissertation/main/sections/litreview.typ
typst
Creative Commons Zero v1.0 Universal
There is a wealth of literature concerning itself with the statistical modelling of football. For fans of the sport it is perhaps the unpredictability of the game that makes it appealing, as while team strength is of course a large factor in game outcome, the multitude of other causal variables can lead to upset wins and tightly-fought battles. This same reasoning might explain the large base of statistical research into the game, as statisticians and sport scientists seek to quantify the effects of myriad different factors. Football is big business, with the English Premier League (EPL) having contributed £7.6 billion to the UK's gross domestic product in 2019/2020 @premgdp, invested throughout the country and disproportionately in more deprived areas such as the north west. In the year preceding Dec 2020, 2.5 million Britons placed bets on Football @gambling, and the Financial Times notes that in the year to March 2022 £1.1bn was taken in revenue for gambling operators, nearly half the £2.3bn figure for their total revenue @ftgambling. Statistical prediction of football matches is naturally very important to bookmakers, seeking to maximise their revenues by setting optimal odds for games. Linear models predicting match outcome based on various pre-match variables are ubiquitous, but there are examples of authors applying time-series techniques to assess minute-to-minute statistics based on in-game events such as corner kicks and yellow cards. Some authors have applied Bayesian network techniques @razali2017 and in many more recent papers we see the use of machine learning models to answer similar questions. In this section we hope to explore a limited number of techniques applied to football modelling. // TODO - finish this para. ^^^ == Logistic Regression Logistic regression is a common tool for modelling situations where outcomes can be classified as a binary variable. In football, the result of a match is naturally three-valued - win vs draw vs loss - but this can be recast as a binary response: win vs not a win. It is used as a tool for predicting outcome in many sports @asianhockey @willoughby, but its use in football is well trodden. Here we will study one example. // <NAME> #cite(<prasetioharlili>, form: "prose") train a logistic regression model on variables representing defense/offense ratings against the logit of win chance. //The logistic regression model can be written as follows: //$ log Pi/(1-Pi) = beta_0 + sum_(i=1)^4 beta_i X_i $ //Where $Pi$ represents $ "Pr"("Win")$ and $beta_j$ are coefficients to be determined. The authors use win/loss data from the English premier league from between 2010 and 2016. They fit a number of models, excluding different subsets of the data for each, in order to examine to predictive usefulness of older data and for out-of-sample forecasting of newer data. All the models are tested on 2015/16 season data. The authors determine that the defense variables are more significant than the offense ones, and examine the tradeoff between losing some predictive power when the offense variables are dropped, vs having a simpler model. Part of their conclusion is that the ease of interpretation of logistic regression makes it a useful tool, as well as the good power of the technique to make accurate predictions. == Survival Analysis Goals are the main event of interest for both fans and players in football, and the time-to-first-goal (TTFG) is a key measure for research. Intuitively this may be seen as a measure of a team's offensive prowess over their opponents, and indeed studies have shown it to be a very useful predictor of match outcome: #cite(<ibanezetal>, form: "prose") conducted a study of European women's football and found that teams who score first were 5 times more likely to win. Survival analysis is a natural tool for modelling this, as it concerns itself with durations until or between events that may not be fully observed. In football terms this is because the TTFG is often cut off, or censored, by the end of the match. Some authors censor at other events, for instance at points when the other team scores, as this changes the dynamic of the game. Modelling censored time-to-event data can be done in many ways. Cox regression is a common tool, particularly in medical statistics, though parametric models are also common. // <NAME> A paper by #cite(<nevoritov>, form: "prose") undertakes an in-depth analysis of the times to first and second goals using the Cox proportional hazard regression model. Their analysis covers around 760 matches between 2008 and 2010 in the English premier league. They use data on the times in minutes of the first and second goals, as well as some other information such as the times that red cards are shown to a team, as well as the season and home team. // They use data on the times in minutes of the first and second goals. /*, ignoring stoppage time, so a goal scored in the second minute of stoppage in the first half would still be counted a 45th minute goal.*/ Goal times are censored at 90 minutes if they do not occur during the match, and time-to-second-goal is left-truncated since it cannot occur until the first goal has been scored. Their given reason for focusing on the first two goals is that they'd find much heavier censoring if they included data for third or fourth goals - as football tends to be a fairly low-scoring sport, this would then require far more data to make a model accurate at higher goal counts. //They find that of the 760 games, 1433 relevant goals were observed and 698 of these were censored. Two nested models for the hazard function are introduced, a null model and a complete one. The complete Cox hazard function is given as follows: #let wspace(t) = style(styles => { let size = measure(t, styles) [#size.width.cm()] }) #let gap= [#wspace($ I_(j=2)( $)] // 0.685 $ h_(i j) (t) &= h_0(t) exp( \ &beta_1 "ProbWin"_i + beta_2 "Season"_i \ &+ beta_3 "RedCardsAway"_i (t) \ &+ I_(j=2)(beta_4 "Goal"_i \ &#h(0.68cm)+ beta_5 "TimeOfFirstGoal"_i \ &#h(0.68cm)+ beta_6 "FirstGoalTeam"_i \ &#h(0.68cm)+ beta_7 "TimeFromFirstGoal"_i) \ ) $ Where $j in {1,2}$ is the goal number, $i in {1, ..., 760}$ is the match number, and $I_(j=2)$ is an indicator function. The function $I$ has the purpose of changing the hazard when the first goal has been scored. All variables here except $"FirstGoalTeam"$ are kept, though the significance of $"Goal"$ and $"TimeFromFirstGoal"$ are low ($ p =0.058, 0.11$ resp). The authors experiment with a 'frailty' term to account for random effects, however this is later shown to not be significant. They find that red cards for the away team raise the hazard by 1.806 times, and that the change in hazard after the first goal depends on the time of the match, going down if the first goal occurs before 51 minutes and up afterwards. The authors draft some ideas to explain parts of the model, for instance that the insignificance of $"FirstGoalTeam"$ may be due to tactical reasons, where after a goal a team may become more aggressive and both teams will find it easier to score further goals. The baseline cumulative hazard function $hat(H)_0(t)$ seems linear, implying an exponential distribution for goal time. A similar model is fit to the same data for the away team, so censoring works the opposite way. Some conclusions drawn from the away model include evidence toward away teams playing more conservatively, likely due to the away disadvantage that we discuss later. == Weibull Models //Statistical techniques for predicting the outcome of football matches are numerous. //Different authors attempt to model this in different ways. A fairly natural way to model the number of goals scored in a match is as a Poisson process. Some authors @dixonrob model the goals of each team as separate Poisson processes, others @adamleuven model the total goals scored as Poisson, assigning each goal to a team according to a binomial distribution. // <NAME> An oft-cited 2019 paper by #cite(<kharratboshnakov2019>, form: "prose") highlights an issue with the Poisson approach - it begins by stating that: #linebreak() #quote()[ #set text(9pt) `... the main issue with the Poisson model when modelling the goals scored by a team in football is that the hazard function [...] remains constant for every time unit [...] However, empirical studies showed that this is rather questionable...` ] #linebreak() Kharrat and Boshnakov explore an alternate class of models, based on the Weibull distribution. The Weibull distribution is a generalisation of the exponential distribution, as it adds a shape parameter $k$ that allows for a variable hazard rate. Modelling the incidence rate of goals scored as following a Weibull distribution leads to a Weibull-count model, which generalises the Poisson model. When $k=1$ the two models are equivalent. Using the R statistical programming language they fit two seperate models to a publically available set of football data. The first is a general linear model with goals scored based on the Poisson distribution, and the second is a renewal-count model based on the Weibull distribution. In a visual analysis of the actual goal counts compared to the counts predicted by each model, the Weibull model appears to more closely match reality, this is later confirmed formally. Due to the aforementioned property of these models that one nests the other, the authors can use a likelihood ratio test (LRT) to compare them. They find that to a $p<0.001$ confidence level that the additional fit parameter introduced by the Weibull model does improve the fit, and conclude that the Poisson model is outclassed for modelling this set of data. // Todo - Add more here ? == Home Advantage Home advantage (HA) has a major effect on match outcome in football, and in fact research @jamieson has shown that across 10 different sports the HA effect is significantly highest in football. Various authors try to relate HA to the distance that athletes must travel, the pressure from crowds of local fans on the players and the referee, or other psychological effects on the players from being in an unfamiliar environment. #cite(<pollardarmatas>, form: "prose") discusses the factors that determine home advantage in World Cup qualifying matches. The authors examine 2040 games played by national teams during the 2006, '10 and '14 seasons. They analyse the effect of home advantage on qualification points. /*rather than on goal difference, as other authors do, since for the purposes of qualification the goal difference is irrelevant, only a win matters.*/ While the 'strength' of a team is not directly measurable, for the purpose of quantifying it the authors use FIFA rankings. /*This should let them control for its effects. */ /*Other variables examined include details about the home team's stadium such as attendance and the distance of the crowd from play; the distance the away team had to travel in terms of time-zones crossed, absolute distance, and altitude change; possible referee bias in terms of red/yellow cards and penalties awarded to each team; and the continental region in which the teams competed.*/ Other variables examined include details about match attendance, distance of the crowd from play, number of time zones the away team crossed to attend, altitude change, referee bias and the continental region in which the teams competed. Variables spanning multiple orders of magnitude underwent log-transformations, and multicollinearity between the large number of variables was checked and found to be negligible. The authors fit a generalised linear model (GLM) for qualification points against these data. //The data for attendance and distance travelled both span multiple orders of magnitude so these variables underwent a log-transformation. //Multicollinearity between variables may have been an issue, since for instance distance-travelled and time-zones-crossed are obviously related, however the authors found that pairwise correlation coefficients were low ($<0.2$) for any pair of variables. This GLM had $R^2 = 0.326$, suggesting that the chosen variables are significant predictors of game points. The most significant variable was found to be the team's ranking, a representation of its strength. Home advantage was found to be significantly higher in Africa than in Europe or Asia, but the differences between other continental areas were found to be insignificant. The authors also find that altitude change and time zones crossed for the away team are both significant effects, as well as the number of attendees. Their results indicate that neither attendance as a percentage of capacity nor distance travelled by the away team had a significant effect ($p=90%, 6.7%$ respectively). This last result was perhaps surprising as other authors @normanclarke have found that distance travelled is a significant factor.
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/dimension.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ## Dimensions, sidebearings and kerns == #tr[dimension]、#tr[sidebearing]和#tr[kern] // As mentioned above, part of the design for a font is deciding how wide, how tall, how deep each glyph is going to be, how much space they should have around them, and so on. The dimensions of a glyph have their own set of terminology, which we'll look at now. 如前文所述,字体设计中有部分工作是在决定每个#tr[glyph]的宽高,以及周围有多少空白部分等等。这些#tr[dimension]信息都有它们自己的术语,接下来将逐步介绍它们。
https://github.com/almarzn/portfolio
https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/.template/layout.typ
typst
#let presentation(contents) = [ = #contents.profile.name #set text(weight: "light") ] #let skills(contents) = [ #set par(justify: false) == À propos #contents.presentation === Compétences #for skill in contents.skills [ ==== #skill.title #for item in skill.items [ - #item ] ] ] #let experiences(contents) = [ #import "@preview/cmarker:0.1.0" == Expériences #for experience in contents.experiences [ === #experience.name #heading(level: 4, [ #experience.title #h(12pt) #set text(size: 12pt, weight: "light") #experience.dates ]) #experience.description ===== Technos #experience.skills.join(", ") ===== Réalisations #for work in experience.work [ ====== #work.title #cmarker.render(work.content) ] ] ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par-indent_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test hanging indent. #set par(hanging-indent: 15pt, justify: true) #lorem(10)
https://github.com/GYPpro/Java-coures-report
https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/8.typ
typst
#set text(font:("Times New Roman","Source Han Serif SC")) #show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code in a larger block // with more padding. #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) #set math.equation(numbering: "(1)") #set text( font:("Times New Roman","Source Han Serif SC"), style:"normal", weight: "regular", size: 13pt, ) #set page( paper:"a4", number-align: right, margin: (x:2.54cm,y:4cm), header: [ #set text( size: 25pt, font: "KaiTi", ) #align( bottom + center, [ #strong[暨南大学本科实验报告专用纸(附页)] ] ) #line(start: (0pt,-5pt),end:(453pt,-5pt)) ] ) #show raw: set text( font: ("consolas", "Source Han Serif SC") ) = 实现一个线段树泛型模板 \ #text("*") 实验项目类型:设计性\ #text("*")此表由学生按顺序填写\ #text( font:"KaiTi", size: 15pt )[ 课程名称#underline[#text(" 面向对象程序设计/JAVA语言 ")]成绩评定#underline[#text(" ")]\ 实验项目名称#underline[#text(" 实现一个线段树泛型模板(JAVA实现) ")]\ 指导老师#underline[#text(" 干晓聪 ")]\ 实验项目编号#underline[#text(" 1 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\ 学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\ 学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\ 实验时间#underline[#text(" 2023年11月1日上午 ")]#text("~")#underline[#text(" 2023年11月1日中午 ")]\ ] #set heading( numbering: "一、" ) #set par( first-line-indent: 1.8em) = 实验目的 \ #h(1.8em)熟悉泛型类、泛型方法的使用与泛型思想在编码中的应用。利用C++语言实现泛型。 = 实验环境 \ #h(1.8em)计算机:PC X64 操作系统:Windows 编程语言:JAVA IDE:Visual Studio Code 在线测试平台:leetcode = 程序原理 \ #h(1.8em) 线段树是一种较为复杂的数据结构,旨在快速解决区间数据批量修改与特征统计。 本类实现了一个可以批量地对数据进行线性空间内加和运算的线段树,统计内容为区间内的最大值,对于每个操作: + 修改单点:时间复杂度为$O(log n)$ + 修改区间:均匀修改与查询后最坏时间复杂度为每点渐进$O(log (n m))$,n为内容总数,m为修改区间长度 + 查询区间:$O(log n)$ = 程序代码 文件`sis7\segTree.java`实现了一个`segTree`类 ```java package sis7; import java.util.ArrayList; public class segTree<N> { private ArrayList<N> d; private ArrayList<N> a; private ArrayList<N> b; private int n; private N INI; private void subbuild(int s, int t, int p) { if (s == t) { d.set(p, a.get(s)); return; } int m = s + ((t - s) >> 1); // (s+t)/2 subbuild(s, m, p * 2); subbuild(m + 1, t, p * 2 + 1); d.set(p, merge(d.get(p * 2), d.get(p * 2 + 1))); // 合并运算符 ↑ } private N subGetSum(int l, int r, int s, int t, int p) { if (l <= s && t <= r) return d.get(p); int m = s + ((t - s) >> 1); if (b.get(p) != null) { d.set(p * 2, merge(d.get(p * 2), b.get(p))); // 合并运算符的高阶运算 此处运算为应用懒惰标记 d.set(p * 2 + 1, merge(d.get(p * 2 + 1), b.get(p))); // 合并运算符的高阶运算 此处运算为应用懒惰标记 b.set(p * 2, merge(b.get(p * 2), b.get(p))); // 下传标记,无需修改 b.set(p * 2 + 1, merge(b.get(p * 2 + 1), b.get(p))); // 下传标记,无需修改 b.set(p, null); } N ansl = INI; N ansr = INI; if (l <= m) ansl = subGetSum(l, r, s, m, p * 2); if (r > m) ansr = subGetSum(l, r, m + 1, t, p * 2 + 1); return merge(ansl, ansr); // 合并运算符↑ } private void subUpdate(int l, int r, N c, int s, int t, int p) { if (l <= s && t <= r) { d.set(p, merge(d.get(p), merge(c, (t - s + 1)))); // 合并运算符的高阶运算 此处运算为修改整匹配区间值 b.set(p, merge(b.get(p), c)); // 记录懒惰标记,无需修改 return; } int m = s + ((t - s) >> 1); if (b.get(p) != null && s != t) { d.set(p * 2, merge(d.get(p * 2), merge(b.get(p), (m - s + 1)))); // 合并运算符的高阶运算 此处运算为应用懒惰标记 d.set(p * 2 + 1, merge(d.get(p * 2 + 1), merge(b.get(p), (t - m)))); // 合并运算符的高阶运算 此处运算为应用懒惰标记 b.set(p * 2, merge(b.get(p * 2), b.get(p))); // 下传标记,无需修改 b.set(p * 2 + 1, merge(b.get(p * 2 + 1), b.get(p))); // 下传标记,无需修改 b.set(p, null); } if (l <= m) subUpdate(l, r, c, s, m, p * 2); if (r > m) subUpdate(l, r, c, m + 1, t, p * 2 + 1); d.set(p, merge(d.get(p * 2), d.get(p * 2 + 1))); // 合并运算符 ↑ } private N merge(N a,N b) { return a; } private N merge(N a,int b) { return a; } public segTree(int _n,N _INI) { n = _n; INI = _INI; d = new ArrayList<N>(4 * n + 5); a = new ArrayList<N>(4 * n + 5); b = new ArrayList<N>(4 * n + 5); } public void build(ArrayList<N> _a) { a = _a; subbuild(1, n, 1); } public N getsum(int l, int r) { return subGetSum(l, r, 1, n, 1); } public void update(int l, int r, N c) // 修改区间 { subUpdate(l, r, c, 1, n, 1); } public void update(int idx, N tar) { // 修改单点,未测试 N tmp = getsum(idx, idx); tar = merge(tar, tmp); subUpdate(idx, idx, tar, 1, n, 1); } } ``` = 出现的问题、原因与解决方法 \ #h(1.8em) 在将C++代码写成JAVA的过程中,遇到的问题是JAVA中并没有运算符重载,因此选择用函数merge实现区间的合并。 这样在保证代码可以接受的类型下不会出错。 = 测试数据与运行结果 \ 测试数据实例化泛型为int_32 输入数据规则:第一行包含两个整数$m,n$,表示这列数字的个数和操作总数 第二行包含$n$个用空格分隔的数,其中第$i$个数字表示数列第$i$项的初始值 接下来$m$行每行包含3-4个整数,表示一个操作。具体如下: #box[ + `1 x y k`:将区间`[x,y]`内每个数加上$k$ + `2 x y`:输出区间`[x,y]`内每个数的和 ] 样例运行结果如下: #figure( table( align: left + horizon, columns: 3, [*输入*],[*输出*],[*解释*], [`5 5 1 5 4 2 3`],[],[初始化数据], [`2 2 4`],[`11`],[求出`[2,4]`内元素和], [`1 2 3 2`],[],[将`[2,3]`内所有元素+2], [`2 3 4`],[`8`],[求出`[3,4]`内元素和], [`1 1 5 1`],[],[将`[1,5]`内所有元素+1], [`2 1 4`],[`20`],[求出`[1,4]`内元素和] ) ) 注:测试平台`leetcode`的特性为直接向函数传参,因此不需要实现输入输出。
https://github.com/freundTech/typst-typearea
https://raw.githubusercontent.com/freundTech/typst-typearea/main/tests/bcor.query.typ
typst
MIT License
#import "../typearea.typ": * #show: typearea.with( width: 110pt, height: 100pt, div: 10, binding-correction: 10pt, ) #context [ #layout(size => [ #metadata(here().position() + size)<result> ]) ] #metadata(( page: 1, x: 20pt, y: 10pt, width: 70pt, height: 70pt, ))<expected>
https://github.com/r8vnhill/keen-manual
https://raw.githubusercontent.com/r8vnhill/keen-manual/main/omp/genetic_operators.typ
typst
BSD 2-Clause "Simplified" License
== Genetic operators Genetic operators are crucial components in genetic algorithms, directly manipulating genetic material to drive the evolutionary process. These operators, including mutation, crossover, and selection, modify genetic material to produce variability and innovation within a population. In the Keen framework, all genetic operators implement the `GeneticOperator` interface, ensuring standardization and interoperability across different evolutionary strategies. Here’s how this interface is defined: ```kt // Interface for genetic operators where T represents the type of value in the gene, // and G represents the gene itself. interface GeneticOperator<T, G> where G : Gene<T, G> { // Function invoked to apply genetic operations. It takes the current evolutionary // state and the desired output size, returning the new evolutionary state. operator fun invoke( state: EvolutionState<T, G>, outputSize: Int ): EvolutionState<T, G> } ```
https://github.com/Isaac-Fate/booxtyp
https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/paragraph.typ
typst
Apache License 2.0
#let paragraph-rules(body) = { set par(first-line-indent: 1em, justify: true) body }
https://github.com/ludwig-austermann/modpattern
https://raw.githubusercontent.com/ludwig-austermann/modpattern/main/examples/translations_and_backgrounds.typ
typst
MIT License
#import "../main.typ": * Suppose you have this: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), circle(stroke: 5pt))) You can then easily tranlate the circles via the `dx` and `dy` arguments: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), circle(stroke: 5pt), dx: 5pt, dy: 5pt)) Now, adding a background to: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), circle(stroke: 5pt, radius: 40pt), dx: 5pt, dy: 5pt)) yield to this: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), { place(box(width: 100%, height: 100%, fill: red)) place(circle(stroke: 5pt, radius: 40pt)) }, dx: 5pt, dy: 5pt)) The lines are gone. Instead modpattern provides the background argument, so that we can do this: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), circle(stroke: 5pt, radius: 40pt), dx: 5pt, dy: 5pt, background: red)) You can do crazy stuff now: #rect(width: 5cm, height: 2cm, fill: modpattern((100pt, 50pt), circle(stroke: 5pt, radius: 40pt), dx: 5pt, dy: 5pt, background: gradient.linear(..color.map.rainbow)))
https://github.com/skyzh/chicv
https://raw.githubusercontent.com/skyzh/chicv/master/README.md
markdown
Creative Commons Zero v1.0 Universal
# Typst CV Template A simple CV template for [typst.app](https://typst.app). ## How To Use ### Quick Start Create a project on [typst.app](https://typst.app), copy paste everything in https://github.com/skyzh/chicv/blob/master/template/cv.typ. All done! ### Customize your CV To change the text size, you can uncomment the lines in `cv.typ` and set to your choice. (Recommended text size for CV is from 10pt to 12pt) You can also change the page margin in `cv.typ` to fit in more contents in a single page. The margin default is set to `(x: 0.9cm, y: 1.3cm)`. Don't forget to include `#chiline()` every time you open a new section, this line acts as a perfect split. For basic typst syntax, check this template as a reference, it's super easy to understand and use! For advanced topics, please refer to [official reference](https://typst.app/docs/reference/) by typst. ## Showcases ### Sample CV ![Preview](cv.png) ### Chi's CV [cv.pdf](https://skyzh.github.io/files/cv.pdf)
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/ttf-outline.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ## TrueType Representation == TrueType#tr[outline]表示法 // So that was the PostScript format, which is the normal way of exporting OpenType fonts. But Glyphs allows us to output our test font with TrueType outlines, and if we do that, we see that things have changed: 以上我们介绍了 PostScript 格式,这也是导出 OpenType 字体时常用的#tr[outline]格式。但 Glyphs 也允许我们使用TrueType格式输出#tr[outline]。如果我们导出字体时开启了此选项,就能看到有些表发生了变化: ```bash $ ttx -l TTXTest-Regular.ttf Listing table info for "TTXTest-Regular.ttf": tag checksum length offset ---- ---------- ------- ------- DSIG 0x00000001 8 1960 GSUB 0x00010000 10 1948 OS/2 0x683D6762 96 764 cmap 0x007700CF 74 860 cvt 0x00000000 6 1416 fpgm 0x47A67342 479 936 gasp 0x001A0023 16 1932 glyf 0xABA0B11E 368 252 head 0x09740B40 54 660 hhea 0x062F01A9 36 728 hmtx 0x06A200BA 12 716 loca 0x00840118 8 652 maxp 0x00780451 32 620 name 0xDF876A4F 465 1424 post 0xFFDE0057 40 1892 ``` // An OpenType font with TrueType outlines does not have a `CFF` table, but instead contains a number of other tables; two of which contain data about the glyphs themselves: 使用TrueType#tr[outline]的OpenType字体没有`CFF`表,但相对的会多出一些其他表。其中有两张表包含了#tr[glyph]信息: /* |`glyf`|Glyph data| |`loca`|Index to location| */ #align(center, table( columns: 2, align: left, [`glyf`], [#tr[glyph]数据], [`loca`], [位置索引], )) // And four which are used for hinting and rasterizing, which we will deal with in the appropriate chapter: 另外四张表用于#tr[hinting]和#tr[rasterization]过程,这些我们会在相应的章节中再详细介绍: /* |`prep`|The Control Value "pre-program"| |`fpgm`|Font program| |`cvt`|Data values used by the hint program| |`gasp`|Information about how to render the font on grayscale devices| */ #align(center, table( columns: 2, align: left, [`prep`], [控制值预处理程序], [`fpgm`], [字体程序], [`cvt`], [#tr[hinting]程序中使用的数据值], [`gasp`], [关于如何在支持灰度的设备上渲染字体的信息], )) // The names of the first two of these hinting tables are somewhat misleading. The "font program" (`fpgm`) is run once before the font is used, in order to set up definitions and functions for hinting, whereas the "pre-program" (`prep`) actually contains the size-specific font hinting instructions and is executed every time the font changes size. Yes, this is completely brain-dead. 前两个表名非常容易造成错误理解。字体程序(`fgpm`)是在字体被使用之前,用来初始化#tr[hinting]中需要用到的各种定义和函数的程序。而预处理程序(pre-program,`prep`)实际上是包含了和特定字体大小相关的#tr[hinting]指令,它在字体每次改变大小时都需要执行。这些名字起的确实有些烧脑。 // How are glyphs represented in TrueType outlines? The binary representation in the table is in a series of fixed-width arrays, containing instructions, relative coordinates and flags, (see the OpenType specification if you need to deal with the binary tables) but `ttx` expands them to a very friendly format for us: 那么TrueType到底使用什么方式表达#tr[glyph]#tr[outline]呢?在二进制文件中,这些表实际储存了一系列定长数组,它们包含了绘图指令,相对坐标和控制选项(如果你需要直接处理字体文件,可以参考OpenType规范文件)。而 `ttx` 工具会将他们转换为更加友好的格式: ```xml <TTGlyph name="A" xMin="3" yMin="0" xMax="577" yMax="700"> <contour> <pt x="240" y="700" on="1"/> <pt x="340" y="700" on="1"/> <pt x="577" y="0" on="1"/> <pt x="482" y="0" on="1"/> <pt x="416" y="213" on="1"/> <pt x="161" y="213" on="1"/> <pt x="94" y="0" on="1"/> <pt x="3" y="0" on="1"/> </contour> <contour> <pt x="394" y="285" on="1"/> <pt x="360" y="392" on="1"/> <pt x="320" y="518" on="0"/> <pt x="290" y="627" on="1"/> <pt x="286" y="627" on="1"/> <pt x="258" y="527" on="0"/> <pt x="233" y="449" on="1"/> <pt x="228" y="430" on="0"/> <pt x="216" y="392" on="1"/> <pt x="183" y="285" on="1"/> </contour> <instructions><assembly> </assembly></instructions> </TTGlyph> ``` // Here we can see the two contours of our A, as a series of on-curve and off-curve points. Remember that TrueType uses *quadratic* Bézier curves, so within our aperture we only see one off-curve point between the on-point curves. Glyphs has converted our Béziers for us: 很明显 A 由两条#tr[contour]组成,这些线条由线上点和线外点控制。还记得 TrueType 使用的是*二次*贝塞尔曲线吧?所以在两个线上点之间,我们最多只会看见一个线外点。Glyph 在导出时自动帮我们进行了贝塞尔曲线的转换(@figure:bezier-convert)。 #figure( placement: none, caption: [三次贝塞尔曲线转换为二次] )[#include "bezier.typ"] <figure:bezier-convert> // Sometimes you might open up a `glyf` table and find something confusing: 有些时候`glyf`表里也会出现一些奇怪的东西: ```xml <TTGlyph name="C" xMin="125" yMin="-20" xMax="1231" yMax="1483"> <contour> <pt x="827" y="1331" on="1"/> <pt x="586" y="1331" on="0"/> <pt x="307" y="1010" on="0"/> <pt x="307" y="731" on="1"/> ... ``` // There are two off-curve points between the on-curves! Does this mean that we're suddenly using cubic Bézier curves in our TrueType outlines? Nope, the font is doing something clever here to save space: there is an "implied" on-curve point located half-way between the off-curves points. Software handling these curves needs to insert the implied on-curve point. 在线上点之间竟然连续出现了两个线外点!这难道不是在TrueType #tr[outline]中使用了三次贝塞尔曲线吗?不不不,这只是字体文件为了节省空间而进行了某些聪明的省略罢了。这种写法表示在两个线外点的正中间有一个隐含的线上点。软件在处理这些曲线时,还是需要把这个被省略的点给加回去的。 #figure( placement: none, caption: [两个线外点间隐含的线上点] )[#include "implied.typ"] // What about the `loca` table? The `glyf` table contains all contours for all the glyphs, one after another as a big long binary lump. When you're trying to find a glyph, you look up its glyph index in the `loca` table, and it'll tell you which byte of the `glyf` table you need to jump to. 那 `loca` 表又是干什么用的呢?因为 `glyf` 表是直接以二进制形式连续储存所有#tr[glyph]的#tr[contour]的,我们需要从`loca`表中找到这个#tr[glyph]在`glyf`数据中的位置,才能知道从哪开始读取#tr[outline]信息并绘制它。
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/viewegh.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": autor #autor("<NAME>", "1962", "", "spisovatel, publicista, fejetonista", "pedagogiku na UK", "novodobý", "/cj-autori/media/viewegh.jpg") Současný český autor. Každý rok vydává jeden román. Rezignoval na psaní umělecky hodnotné literatury, spisovatel je jeho povolání, píše pro poptávku. Báječná léta pod psa (případně Vybíjená a Výchova dívek v Čechách) je jeho jediné umělecky významné dílo. Dlouho bojuje s literárními kritiky a bulvárem. U Ústavního soudu vyhrál žalobu proti deníku Aha!. Roku 1993 získal Cenu Jiřího Ortena udělovanou autorům do 30 let. Většina jeho děl je zfilmována. Roku 2012 mu praskla aorta, málem umřel. Měl dvě manželky, jedna byla ta <NAME>. Teď má přítelkyni z Ukrajiny. Mezi jeho známá díla patří: 1. *Výchova dívek v Čechách* -- název mega pedofilní, kniha celkem taky\ Povídky o manželství a sexu\ Účastníci zájezdu\ Román pro ženy\ Román pro muže\ nejnovější: Malý Gatsby a Carmen z Chodoriva *Současníci*\ _<NAME>_ -- Hana (@hana[]), 2017\ _<NAME>_ -- <NAME>, 1998\ _<NAME>_ -- Katyně, 2008\ #pagebreak()
https://github.com/x14ngch3n/CV
https://raw.githubusercontent.com/x14ngch3n/CV/main/CV.typ
typst
#import "template.typ": * #show: cv = <NAME> #align(center)[800 Dongchuan RD. Minhang District, Shanghai, China] #v(-5pt) #align(center)[ #fa[#envelope] #link("mailto:<EMAIL>") $dot$ #fa[#globe] #link("http://xiangchen.xyz")[xiangchen.xyz] $dot$ #fa[#github] #link("https://github.com/cascades-sjtu")[cascades-sjtu] $dot$ #fa[#linkedin] #link("https://www.linkedin.com/in/cascades")[cascades] $dot$ #fa[#orcid] #link("https://orcid.org/0009-0007-0626-6888")[0009-0007-0626-6888] ] #v(-5pt) == Education #entry( title: [Shanghai Jiao Tong University], start: (2021,9), end: (0,0), )[ Master degree in Cyber Security, supervised by #link("https://infosec.sjtu.edu.cn/DirectoryDetail.aspx?id=155")[Yue Wu] and #link("https://infosec.sjtu.edu.cn/DirectoryDetail.aspx?id=173")[Jiaping Gui] #linebreak() Thesis: #ccpp system software Static analysis techniques through the lens of Integer Overflow Detection ] #entry( title: [Shanghai Jiao Tong University], start: (2017,9), end: (2021,6), )[ Bachelor degree in Information Security, #link("https://zhiyuan.sjtu.edu.cn/CommonFiles/20180521094645_2017%E8%87%B4%E8%BF%9C%E5%AD%A6%E9%99%A2%E9%99%A2%E5%88%8A.pdf")[Zhiyuan Honor Program] #linebreak() Thesis: Vulnerability Detection and Analysis for Massive Large-scale IoT Devices ] #entry( title: [Peking University Summer School], start: (2019,7), end: (2019,8), )[] == Industry Experience #entry( title: [NIO Inc.], start: (2022,10), end: (2023,10) )[ Funding project "decreasing FP and FN rates in static #ccpp program analysis" from Cyber Security Academy Student Innovation Grant Program. The project focuses on using #link("https://fbinfer.com")[Facebook Infer]'s Abstract Interpretation framework and taint analysis technique in detecting Uninitialized Value issues in Linux Kernel. ] #entry( title: [Huawei Technologies Co., Ltd.], start: (2023,7), end: (2023,9), )[ Develop and maintain rules for enterprise-domestic #ccpp static analysis tools and apply them to 5G base station codebases. Research on Large Language Model-assisted program analysis on customized memory management functions. ] #entry( title: [Shanghai Qizhi Institute], start: (2022,7), end: (2022,11) )[ #link("https://gossip.team/")[G.O.S.S.I.P] Research Internship, doing weekly paper reading and research on (1) automatic program repair using #link("https://llvm.org/docs/WritingAnLLVMNewPMPass.html")[LLVM Pass] and #link("http://plse.cs.washington.edu/daikon/")[Daikon invariant detector] and (2) automatic bug fix for use-after-move issues in #cpp 11 using #link("https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html")[Clang-Tidy]. ] #entry( title: [Shanghai Feysh Technology Co.,Ltd], start: (2021,7), end: (2021,9) )[ Manually review more than 4000 analysis results of #link("https://clang-analyzer.llvm.org/")[ClangStaticAnalyzer] performed on Juliet #ccpp Test Suite. Implement four ClangStaticAnalyzer checkers for #link("https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard")[SEI CERT C Coding Standard]. ] == Teaching Experience #entry( title: [IS308: Computer System Security (The 1st "<NAME>" Class)], start: (2023,2), end: (2023,6), )[ Provide mentorship on five labs in binary/web security and cryptography. Host a Jeopardy-style final exam. ] #entry( title: [NIS7021: Software and System Security #githublink("http://github.com/cascades-sjtu/nis7021-labs")], start: (2022,10), end: (2023,1), )[ Design two labs in reverse engineering, and dynamic instrumentation. ] == Open-Source Contributions #entry( title: [Open Source Promotion Plan (openEuler) #githublink("https://gitee.com/openeuler/llvm-project/pulls/28") #websitelink("https://summer-ospp.ac.cn/org/prodetail/23b970442?lang=en&list=pro")], start: (2023,7), end: (2023,9) )[ Enhance LLVM InstCombine pass with a peephole optimization, which can eliminate `abs()` in ternary expressions like: `x>y? abs(x-y+1):0` and combine the original if-else-branch to linear CFG using the AArch64 `csinc` instruction. ] #entry( title: [SJTUBeamer #githublink("https://github.com/sjtug/SJTUBeamer")], start: (2021,4), end: (2021,11) )[ Shanghai Jiao Tong University official #LaTeX beamer template, gained more than 500 stars. ] == Publications - *<NAME>*. 2024. IntTracer: Sanitization-aware IO2BO Vulnerability Detection across Codebases. In 2024 IEEE/ACM 46th International Conference on Software Engineering: Companion Proceedings (*ICSE-Companion ’24*) #pdflink("https://cascades-sjtu.github.io/assets/pdfs/inttracer-icsesrc24.pdf") #githublink("https://github.com/cascades-sjtu/tracer-infer") == Talks - *<NAME>*, <NAME>. 2023. Custom Memory Functions Demystified: A tutorial of memory corruption detection using Goshawk. In ACM ASIA Conference on Computer and Communications Security (*ASIA CCS ’23*) #pdflink("https://github.com/cascades-sjtu/Goshawk-tutorial/blob/main/slide/asiaccs23-tutorial-export.pdf") - *<NAME>*. 2023. #ccpp static analysis with LLVM compiler infrastructure. #link("https://mp.weixin.qq.com/s/QxfoEiuwiMxav5qtKWxfwg")[Voice of Information Security-Young] #pdflink("https://cascades-sjtu.github.io/assets/pdfs/talk-vois23.pdf") == Awards #entry( title: [(Expected) Postgraduate Scholarship (PGS)], start: (2024,9) )[] #entry( title: [Shanghai Jiao Tong University Outstanding Graduate #strong[(\<10%)]], start: (2024,3) )[] #entry( title: text(weight: "thin", [Rong Chang Leadership Scholarship]) + [ (\<1%)], start: (2021,11), end: (2023,11) )[] #entry( title: [DEFCON CTF 30 #strong[2nd] place (played with Katzebin)], start: (2022,8) )[] #entry( title: [Zhiyuan Honor Bachelor Degree #strong[(Cum Laude, \<1%])], start: (2021,6) )[] #entry( title: [Shanghai Outstanding Graduate #strong[(\<5%)]], start: (2021,6) )[] == Services #entry( title: text(weight: "thin", [Executive Committee Member of China Computer Federation (CCF) #link("https://www.ccf.org.cn/Chapters/Student_Chapters/SJTU/")[Student Chapter] in SJTU]), start: (2022,11), end: (2023,12) )[] #entry( title: [GeekPwn volunteer], start: (2019,10) )[] == Skills - Programming Languages: #ccpp $gt.eq$ Python $gt$ Rust $gt$ OCaml - Develop Environment: Debian, VSCode, Vim, GDB/LLDB - Capture-The-Flag: Binary Ninja, Angr, Pwntools, Wireshark, Sage #timestamp()
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/src/elements/group.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw, coordinate #import "../util.typ" /// Draws a group of elements /// /// #examples.group /// - body (elements, function): Elements to group /// - id (str): see #doc-ref("element.elmt") /// - name (str): The group's name /// - name-anchor (str): The anchor for the name. \ /// Note: the name will be placed on the *outside* of the group /// - fill (color): see #doc-ref("element.elmt") /// - stroke (stroke): see #doc-ref("element.elmt") /// - padding (float,length,array,dictionary): The inside padding: /// - float / length: same for all sides /// - array: either (`<all>`,), (`<vertical>`, `<horizontal>`) or (`<top>`, `<right>`, `<bottom>`, `<left>`) /// - dictionary: valid keys are "top", "right", "bottom" and "left" /// - radius (number): The corner radius #let group( body, id: "", name: none, name-anchor: "south", fill: none, stroke: black + 1pt, padding: 0.5em, radius: 0.5em ) = { let min-x = none let max-x = none let min-y = none let max-y = none let pad-top = padding let pad-bottom = padding let pad-left = padding let pad-right = padding if type(padding) == array { if padding.len() == 0 { panic("Padding array must contain at least one value") } else if padding.len() == 1 { pad-top = padding.first() pad-bottom = padding.first() pad-left = padding.first() pad-right = padding.first() } else if padding.len() == 2 { pad-top = padding.first() pad-bottom = padding.first() pad-left = padding.last() pad-right = padding.last() } else if padding.len() == 4 { (pad-top, pad-right, pad-bottom, pad-left) = padding } } else if type(padding) == dictionary { pad-top = padding.at("top", default: 0.5em) pad-right = padding.at("right", default: 0.5em) pad-bottom = padding.at("bottom", default: 0.5em) pad-left = padding.at("left", default: 0.5em) } draw.hide(draw.group(name: id+"-inner", body)) draw.rect( (rel: (-pad-left, -pad-bottom), to: id+"-inner.south-west"), (rel: (pad-right, pad-top), to: id+"-inner.north-east"), name: id, radius: radius, stroke: stroke, fill: fill ) if name != none { draw.content( id + "." + name-anchor, anchor: util.opposite-anchor(name-anchor), padding: 5pt, [*#name*] ) } body }
https://github.com/Amirhosein-GPR/university_notes
https://raw.githubusercontent.com/Amirhosein-GPR/university_notes/main/cyber_physical_systems.typ
typst
#import "assets/typst/templates/note.typ": note #import "assets/typst/tools/tool.typ" #let red_color = rgb(200, 0, 0, 255) #let orange_color = rgb(220, 100, 0, 255) #let yellow_color = rgb(130, 130, 0, 255) #let green_color = rgb(0, 120, 0, 255) #let blue_color = rgb(0, 100, 200, 255) #let dark_blue_color = rgb(0, 0, 200, 255) #let purple_color = rgb(150, 0, 150, 255) #let gold_color = rgb(255, 215, 0) #let brown_color = rgb(125, 50, 0) #let dir = rtl #show: doc => note( doc, paper: "a4", black_and_white: false, flipped: false, first_page_font_size: 10pt, font_size: 8pt, image_path: "../../images/basu_logo_logosource.ir.svg", image_width: 12em, topic: "جزوه درس سیستم های سایبر فیزیکی", authors_name: ("<NAME>"), professors_name: ("<NAME>"), faculty: "مهندسی کامپیوتر", date: [ نیم سال تحصیلی #text(dir: ltr)[۱۴۰۳-۱] ], version: "v0.4.0", phase: none, info_color: blue_color, no_responsibility: true ) #tool.title("فهرست مطالب", color: red_color) #outline(title: none, indent: auto) #colbreak() #colbreak() #tool.introduce_sections() #colbreak() #tool.title("درباره کلاس", color: blue_color) - شیوه ارزیابی: + تکلیف، تکلیف کامپیوتری و پروژه: ۲۰٪ + ۵٪ + پرسش و فعالیت کلاسی: ۵٪ + (۵٪ نمره اضافه) + سمینار: ۱۵٪ (+ ۱۰٪) #sym.arrow.l هفته آخر کلاس + میان ترم: ۲۰٪ #sym.arrow.l ۱۴۰۳/۰۹/۱۲ + پایان ترم: ۴۰٪ - اطلاع رسانی و تمرین از درس افزار - بعضی اطلاع رسانی ها از طریق کانال تلگرام: cps4031\@ - ایمیل: <EMAIL> #colbreak() = جلسه اول == سیستم های سایبر فیزیکی #tool.double_section()[ #tool.simple_context()[ در سیستم های سایبر فیزیکی، سنسور هایی وجود دارد که اطلاعاتی را از دنیای فیزیکی به سیستم می دهند و سیستم بر اساس برنامه ای که نوشته شده به کمک Actuator ها در دنیای فیزیکی واکنش نشان می دهد. #v(1.6em) ] ][ #tool.comparision()[ تفاوت سیستم های سایبر فیزیکی با کامپیوتر های عادی: + سیستم های سایبر فیزیکی به صورت تخصصی مخصوص یک موضوع خاص هستند. + ورودی ها و خروجی های این دو سیستم متفاوت از یکدیگر است. ] ] #tool.example()[ سیستم های سایبر فیزیکی: - آسانسور - خودرو های خودران ] #tool.simple_context()[ در سیستم های سایبر فیزیکی موارد شکل زیر را داریم: #tool.custom_figure( image("images/CPS/01_01.png"), caption: "نمایی از سیستم های سایبر فیزیکی", inset: 1em ) ] #tool.tip()[ هر سیستم سایبر فیزیکی الزاماً Real-time نیست و بر عکس. ] #tool.double_section()[ #tool.definition()[ سیستم های نهفته: سیستم های پردازش اطلاعاتی هستند که در یک محصول بزرگتری نهفته شده و استفاده می شوند. دلیل خرید این سیستم ها به خاطر پردازش اطلاعات نیست. ] ][ #tool.definition()[ // TODO ??? ??? پردازش همه جا حاضر (Ubiquitous computing): در این سیستم ها اطلاعات در هر زمان و هر مکانی وجود دارند. #v(3.6em) ] ] #tool.double_section()[ #tool.example()[ حوزه های کاری سیستم های سایبر فیزیکی: - خودرو های خودران - قطار ها - ارتباطات - صنعت هوانوردی - کاربرد های نظامی ] ][ #tool.tip()[ در هر نمونه ای از سیستم های سایبر فیزیکی، مواردی مهم اند و مواردی مهم نیستند. به طوری که برای سیستم A ممکن است مواردی مهم باشد که برای سیستم B مهم نباشد و بر عکس. #v(3.2em) ] ] #tool.double_section()[ #tool.example()[ کاربرد های سیستم های سایبر فیزیکی در ارتباط با مشتری: - MP3 player - DVD player - اسباب بازی ها - تلویزیون های هوشمند ] ][ #tool.tip()[ یکی از تفاوت های سیستم های نهفته با سیستم های سایبر فیزیکی این است که سیستم های نهفته، ارتباط کمتری با دنیای بیرون دارند. #v(3.2em) ] ] #tool.list()[ اهمیت سیستم های نهفته: + بیشتر پردازنده های High-end در سیستم های نهفته استفاده می شوند. + تقریبا همه وسایلی که با برق کار می کنند، درونشان سیستم نهفته ای وجود دارد. + اهمیت کلیدی در صنایع. مانند: صنعت خودران ] #tool.list()[ مشخصات سیستم های نهفته: + Dependability: + Reliability + Maintainability + Availability + Safety + Security + Energy efficiency + Performance + Real-time constrations + Weight efficienct, Cost efficienct, Code-size efficienct + Dedicated toward a certain application - Minimize resources, Maximize robustness + Dedicated user interface - No mouse, keyboard and screen + Frequently connected to physical environment through sensors and actuators + Hybrid systems (analog + digital parts) ] #tool.double_section()[ #tool.tip()[ برای سیستم های بدون درنگ، جواب های درستی که دیر می رسند، غلط اند (اشاره به مورد شماره ۴ که در بالا آمده است). ] ][ #tool.tip()[ اینگونه نیست که هر سیستم نهفته ای تمامی خصوصیات لیست بالا را داشته باشد. #v(1.6em) ] ] #tool.tip()[ سیستم های سایبر فیزیکی و نهفته شباهت زیادی به یکدیگر دارند. تفاوت اصلی این دو آن است که سیستم های سایبر فیزیکی ارتباط بیشتری با محیط فیزیکی دارند. (بنابراین مواردی که در لیست بالا به عنوان مشخصات سیستم های نهفته آورده شده، برای سیستم های سایبر فیزیکی نیز، صدق می کند.) ] #tool.double_section()[ #tool.tip()[ تفاوت بین Availability و Reliability: #sym.dots #v(4.8em) ] ][ #tool.tip()[ فرق Safety با Security این است که Safety به جنبه ایمن بودن سیستم برای جان آدم ها در ارتباط است و Security با مثلاً حفظ امنیت داده های سیستم در ارتباط است. ] ] \ = جلسه دوم #tool.double_section()[ #tool.question()[ در بحث Reliability، افزونگی به کار می رود. چه تعداد افزونگی برای سیستم کفایت می کند؟ #v(3.2em) ] ][ #tool.true_answer()[ بستگی به میزان افزونگی مورد نیاز سیستم دارد ولی حداقل ۳ عدد؛ تا اگر یکی از منابع دچار آسیب شد بتوانیم با رأی گیری از ۲ منبع سالم دیگر به نتیجه درست برسیم. ] ] #tool.comparision()[ ارتباطات Embedded system ها با Real time system ها: - بیشتر Embedded system ها Real time system هستند. - بیشتر Real time system ها Embedded system هستند. #tool.custom_figure(image("images/CPS/02_01.png"), caption: "بیشتر ES ها RT هستند و بر عکس.") ] #tool.list()[ چالش های سیستم های نهفته: + حوزه ای چند رشته ای است + اهداف طراحی مختلفی وجود دارد + چالش در مشخصات سیستم، طراحی و تایید + ویژگی های خاص سیستم های نهفته - Weight efficienct, Cost efficienct, Code-size efficienct, Diskless systems ] #tool.double_section()[ #tool.list()[ تعامل اهداف طراحی - اهداف طراحی: - Fault tolerance (Dependability) - Energy efficiency - Real-time - Cost efficient ] ][ #tool.example()[ برای بهبود تحمل پذیری خطا، افزونگی را افزایش می دهیم که باعث افزایش مصرف انرژی می شود. #v(6.36em) ] ] == سیستم های واکنشی (Reactive systems) #tool.definition()[ یک Reactive system در تعامل پیوسته با محیط خود می باشد و با سرعتی که توسط آن محیط تعیین می شود، اجرا می شود. ] #tool.list()[ سیستم های واکنشی (Reactive systesms): - عموما سیستم های نهفته، سیستم های واکنشی هستند. - Reactive systems = Event-based systems - رویکرد برنامه نویسی این سیستم ها به صورت سنتی نیست؛ چرا که در ذات، Event-based هستند. - مدل مناسب برای Reactive system ها: - رویکرد برنامه نویسی بر پایه Automata ] === Automata-based programming #tool.double_section()[ #tool.definition()[ نوعی رویکرد برنامه نویسی است که در آن از ماشین حالت متناهی برای توصیف رفتار برنامه، استفاده می شود. #v(6.8em) ] ][ #tool.simple_context()[ گراف انتقال یک State machine در تمامی مراحل توسعه نرم افزار، استفاده می شود. - Specification - Implementation - debugging - documentation ] ] #tool.example()[ در چند تصویر زیر، مثالی از یک سیستم تهویه هوا آورده شده است: #tool.custom_figure( [ #image("images/CPS/02_02.png") ], caption: none ) #tool.custom_figure( [ #image("images/CPS/02_03.png") #image("images/CPS/02_04.png") #image("images/CPS/02_05.png") ], caption: none ) #tool.custom_figure( [ #image("images/CPS/02_06.png") ], caption: "مثالی از ماشین حالت متناهی (به شیوه Moore)" ) ] #tool.double_section()[ #tool.tip()[ برای مثال تهویه هوا درست این است که از Range استفاده کنیم تا سیستم دائم دچار نوسان نشود (کولر یا بخاری تند تند خاموش و روشن نشود). ] ][ #tool.exercise(extra_score: true)[ مثال تهویه هوا را به صورت گرافیکی شبیه سازی کنید. #v(3.2em) ] ] #tool.list()[ بعضی از مزایای این رویکرد (Automata-based programming): #text(dir: ltr)[ - Suitable for reactive systems - Hierarchical (e.g. Super-states) - Human beings are not capable of comprehending systems with more than 3 #sym.tilde 5 objects. - Verification - Each automata is simple and easy to understand - Each automata has to comply with the super-state that it belongs to. - Automatic code generation ] ] = جلسه سوم == سیستم های سایبر فیزیکی #tool.simple_context()[ سیستم های نهفته، پر از تناقض در نیازمندی هایشان هستند. امروزه سیستم های نهفته دیگر فقط راجع به Information technology نمی باشند. ] #tool.list()[ نمونه هایی از تناقض های مربوط به نیازمندی های سیستم های سایبر فیزیکی: #text(dir: ltr)[ - High connectivity vs. Security and Privacy - High performance vs. Low Energy - Asynchrony vs. Coordination/Cooperation - Scalability vs. Reliability and Predictability - Laws and Regulations vs. Technical Possibilities - Economies of scale (cloud) vs. Locality (fog) - Open vs. Proprietary ] برای رفع تناقض های بالا نیاز به روش ها و مدل های مهندسی جدید می باشد. ] #tool.double_section()[ #tool.tip()[ سیستم های سایبر فیزیکی مبحثی چند رشته ای است که این باعث ایجاد چالش هایی برای آن می شود. ] ][ #tool.definition()[ اینترنت اشیاء: سیستم های سایبر فیزیکی + اینترنت #v(1.6em) ] ] #tool.double_section()[ #tool.list()[ مثال هایی از سیستم های سایبر فیزیکی: + خودرو های خودران + سیستم تنظیم نسبت سوخت و هوا برای کاهش آلایندگی ] ][ #tool.definition()[ سیستم های سایبر فیزیکی: رویکردی علمی برای طراحی و پیاده سازی سیستم های نهفته. #v(3.2em) ] ] == Model based design #tool.tip()[ سه گام اصلی برای ساخت سیستم های سایبر فیزیکی: + Modeling: بیانگر این است که یک سیستم چه کاری را انجام می دهد. + Design: بیانگر این است که یک سیستم چگونه کارش را انجام می دهد. + Analysis: بیانگر این است که یک سیستم چرا کاری که انجام می دهد را انجام می دهد. ] #tool.simple_context()[ هدف این درس این است که یاد بگیریم امروزه چگونه کار ها انجام می شوند، و این چرا به اندازه کافی خوب نیست؛ بدون اینکه وابسته به تکنولوژی شویم چرا که تکنولوژی دائم تغییر می کند. ] #tool.comparision()[ فرق مدل با واقعیت: در مدل سازی، هدف مورد نظر را با استفاده از قوانین علمی مدل می کنیم. حال این مدل سازی ممکن است جزئیات زیادی داشته باشد و بسیار نزدیک به واقعیت باشد و یا حالتی کلی داشته باشد و فقط کمی به واقعیت نزدیک باشد. ] #tool.double_section()[ #tool.example()[ معادلات نیوتون، مدلی از فیزیک دنیای واقعی است. ] ][ #tool.definition()[ Fidelity: میزان خوب بودن انطباق مدل و هدف مربوط به آن. ] ] #tool.double_section()[ #tool.definition()[ هدف (Target): چیزی که مدل از روی آن ساخته می شود. #v(1.6em) ] ][ #tool.tip()[ هم مدل و هم هدف هر دو در جای خود ارزشمند هستند و نباید به جای یکدیگر استفاده شوند. ] ] #tool.example()[ نقشه مناطق نفت خیز (مدل) برای نفت برداری کاربرد زیادی دارد اما نمی توان به جای زمین نفت خیز (هدف) آن را سوراخ کرده و از آن نفت استخراج کرد! ] #tool.definition()[ پیش بینی پذیری (Determinacy): یک مدل، قطعی (Deterministic) است اگر، با داشتن حالت آغازین و ورودی های یکسان، مدل دقیقاً یک رفتار را از خود نشان دهد. بعضی از با ارزش ترین مدل ها، مدل های قطعی هستند. ] #tool.double_section()[ #tool.question()[ آیا مدل های قطعی در سیستم های سایبر فیزیکی معنا دارند؟ #v(1.6em) ] ][ #tool.true_answer()[ به طور کلی خیر - چرا که در دنیای واقعی عدم قطعیت های زیادی وجود دارد که باید آن ها را در نظر بگیریم. ] ] #tool.example()[ دو کامپیوتر که هر یک وظیفه ای دارند و به وسیله یک کابل فیزیکی به هم متصل اند، ممکن است در روند کاری شان عدم قطعیت هایی اتفاق بیافتد. مثلا: داده های ارسالی کامپیوتر ها در یک بار کار کردن کل سیستم سالم به یکدیگر منتقل شود اما در یک بار دیگر تعدادی Packet loss رخ دهد. ] = جلسه چهارم #tool.tip()[ لزومی ندارد یک مدل درست باشد تا سودمند باشد. در اصل، همه مدل ها اشتباه هستند، اما بعضی از آن ها مفیدند. ] #tool.list()[ نمونه هایی از مدل های Deterministic و Nondeterministic: + Software: برنامه های Imperative تک رشته ای، مدل های قطعی (Deterministic Models) هستند. در این جا خود برنامه حالت Deterministic دارد اما سخت افزار هدفی که روی آن اجرا می شود، Nondeterministic است. نرم افزار به مدل Deterministic دیگری متکی است که سخت افزار را انتزاع می کند. Instruction Set Architectures (ISAs) مدل هایی Deterministic هستند. آن مدل نیز به مدل Deterministic دیگری متکی است (مدل گیت های AND و OR و ...). در نهایت به جریان الکرتون ها درون ترانزیستور ها می رسیم که Nondeterministic هستند. + مدل های Deterministic برای جنبه فیزیکی سیستم های سایبر فیزیکی: - معادلات دیفرانسیل مدل هایی Deterministic هستند. ] #tool.tip()[ مشکل بزرگی که برای سیستم های سایبر فیزیکی وجود دارد این است که ترکیب مدل های Deterministic، Nondeterministic است. ////////////////////LOOOOOOOOOOOOOOOOOK ] #tool.definition()[ لایه انتزاع Abstraction Layers: هدف انتزاع، مخفی کردن جزئیات پیاده سازی سطح های زیرین و فراهم کردن Platform ای برای طراحی از سطح های بالا است. ] #tool.tip()[ *اجرای درست* یک برنامه و *تحویل درست* یک پیام در شبکه، ارتباطی با این که چقدر طول می کشد تا کارش را انجام دهد، ندارد. ] #tool.tip()[ برنامه های CPS در یک دنیای ذاتاً Nondeterministic اجرا می شوند. ] #tool.comparision()[ در علوم (Science)، ارزش یک مدل به این بستگی دارد که چقدر رفتارش با سیستم فیزیکی منطبق است. در مهندسی، ارزش سیستم فیزیکی به این بستگی دارد که چقدر رفتارش با مدل منطبق است. ] #tool.tip()[ برای آن که یک مدل مفید باشد، لازم است (اما کافی نیست) که بتوان یک تحقق فیزیکی وفادار را ساخت. ] #tool.tip()[ برای یک دانشمند، مدل (Model) ناقص است. برای یک مهندس، در (Realization) ناقص است. ] #tool.tip()[ برای CPS سؤالی که وجود دارد این نیست که آیا مدل های Deterministic می توانند رفتار سیستم های سایبر فیزیکی را شرح دهند (با وفاداری بالا). برای CPS سؤالی که وجود دارد این است که آیا می توانیم سیستم های سایبر فیزیکی ای بسازیم که رفتارشان با یک مدل Deterministic منطبق است (با احتمال بالا). ] #tool.tip()[ در مدل کردن پدیده های فیزیکی از معادلات دیفرانسیل استفاده می کنیم. ] == فصل سوم == سیستم های گسسته (Discrete Systems) #tool.definition()[ یک سیستم گسسته سیستمی است که در یک دنباله از مراحل گسسته عمل می کند یا دارای سیگنال هایی است که مقادیر گسسته دارند. سیستم های گسسته دینامیک گسسته (Discrete Dynamics) دارند. ] #tool.example()[ مثال مشکل طراحی یک سیستم گسسته: تعداد ماشین هایی که در یک پارکینگ هستند را با حس کردن ورود و خروج ماشین ها، بشمارید و تعداد آن ها را در یک صفحه نمایش نشان دهید. ]
https://github.com/LDemetrios/Conspects-4sem
https://raw.githubusercontent.com/LDemetrios/Conspects-4sem/master/typst/sources/gpu.typ
typst
#import "header.typ": * #show: general-style #setup-exec("gpu.typext", it => read(it)) = Программирование на видеокартах == Начало === Как это всё компилировать ===== Хост-код `.h` файлы для C/C++ есть на официальном сайте, правда, там есть задепрекейченные полезные функции. Придётся задефайнить версию. Достаточно хедера `<CL/cl.h>`. Можно --- `<CL/opencl.h>` Чтобы слинковаться, надо где-то взять либы. Под линуксом --- некий магический package. Под виндоусом --- откуда-то взять. На официальном сайте Кроноса есть. Обратите внимание на битность! ===== Девайс-код Само разберётся. Обычно. ===== Запуск В пределах конспекта код запускается с помощью `cmake`: #let cl-cmake = read("gpu/gpu-cmake.txt") #codeblock(raw(cl-cmake, lang: "cmake")) // Setup evaluator #let cppgit = (prelude: read("gpu/draft-prelude.cpp"), code: "", lines: 0) #let prelude_set(branch, new-prelude) = { // branch copies here branch.plelude = to-code(new-prelude) branch } #let code_set(branch, new-code) = { branch.lines = to-code(new-code).trim().split(regex("\r\n|\r|\n")).len() branch.code = to-code(new-code) branch } #let prelude_append(branch, appendix) = { branch.prelude = branch.prelude + "\n\n" + to-code(appendix) branch } #let code-sep-output = "//////////////" #let code-sep = "\n\nstd::cout << std::endl << \"" + code-sep-output + "\" << std::endl;\n" + "std::cout << std::endl << \"" + code-sep-output + "\" << std::endl;\n " #let code_append(branch, appendix) = { branch.lines = branch.lines + to-code(appendix).trim().split(regex("\r\n|\r|\n")).len() branch.code = branch.code + code-sep + to-code(appendix) branch } #let branch-full-code(branch) = { let code = branch.code code = code.replace("\n", "\n\t").trim() code = branch.prelude + "\n\nint main() {\n\t" + code + "\n}\n" code } #let show-branch-code(branch) = { codefragment(branch.code.replace(code-sep, "\n"), lang: "cpp") } #let show-last-commit-output(colored, outclr, errclr) = { let last-err-sep = -1 let last-out-sep = -1 for i in range(colored.len()) { if colored.at(i).line == code-sep-output { if colored.at(i).color == "output" { last-out-sep = i } else { last-err-sep = i } } } let cut-result = () for i in range(colored.len()) { if (i > last-err-sep and colored.at(i).color == "error") or (i > last-out-sep and colored.at(i).color == "output") { cut-result.push(colored.at(i)) } } colored-output(cut-result, outclr, errclr) } #let parse-cmake-result(result, show-results: true) = { if type(result) != array or result.len() != 3 or result.map(it => type(it)).any(it => it != dictionary) { text(fill: blue, `Evaluation results are invalid`) } else if result.at(0).at("code", default: -1) != 0 { text(fill: red, `Error preparing CMake`) [\ ] colored-output(result.at(0).output, foreground, red) } else if result.at(1).at("code", default: -1) != 0 { text(fill: red, `Compilation error`) [\ ] colored-output(result.at(1).output, foreground, red) } else { if (show-results) { show-last-commit-output(result.at(2).output, foreground, red) if (result.at(2).at("code", default: -1) > 0) { text(fill: red)[ #raw("Exited with " + str(result.at(1).code))\ ] } } else { none } } } #let exec-branch(branch, show-results: true) = { let code = branch-full-code(branch) exec( ("main.cpp": code, "CMakeLists.txt": cl-cmake), eval(read("gpu/cmake-build-command.txt")), (result) => { let data = parse-cmake-result(result, show-results: show-results); if data != none { offset(2em, marked(fill: lucid(245), stroke: foreground + .1em, data)) } }, ) } Как водится в плюсах, придётся написать некоторое количество функций и (тьфу-тьфу) макросов, чтобы было удобно. Полный перечень того, что использую я, можно прочитать в файле "sources/aux/gpu-prelude". Пытаемся запустить: #let commit(branch, execute: true, show-code: true, show-results: true, code) = { let lines-was = branch.lines let new-branch = code_append(branch, code) let cont = { if (show-code) { align(left)[ #offset(2em, codefragmentraw(code, start: lines-was + 1)) ] } if execute { exec-branch(new-branch, show-results: show-results) } } (cont, new-branch) } #let (doc, new-branch) = commit(cppgit, ```cpp std::vector v({1, 2, 3}); println(v); ```) #doc Работает. === API Большинство функций возвращают код ошибки (как обычно, 0 --- успешно, не 0 --- не успешно). Надо проверять! Во всяком случае, в дебаге, в учебных целях. Написать макрос? Какой ужас. Это за исключением функций типа `create`, которые возвращают то, что они `create`. Тогда код ошибки, если нужен, по ссылке, передаваемой в аргумент... Такой типичный С. ==== Получение девайсов ===== `clGetPlatformIDs` --- API для получения списка доступных платформ. Принимает... Указатель, размер, и указатель на размер... Буффер, размер буффера, и то, куда записывать, сколько. Понятное дело, память она не выделяет. Так как надо, чтобы освобождал тот, кто выделил. Такой типичный С... Так, а какого размера выделять буффер? Для этого есть специальный вариант вызова: `(nullptr, 0, &x)` --- тогда в `x` нам запишут то, сколько на самом деле вариантов. Идейно. Такой принцип применяется здесь во всемх вызовах. Правда, в отличие от типичного С, если буфера мало, то это не ошибка "буфера мало", а нам запишут, сколько есть места. Можно сказать, "возвращает" эта функция список id платформ, где можно запустить opencl. #let (doc, br-platfromIDs) = commit(cppgit, ```cpp uint32_t s; clGetPlatformIDs(0, nullptr, &s); std::vector<cl_platform_id> platforms(s); clGetPlatformIDs(s, platforms.data(), &s); println(platforms); ```) #doc Результат не вполне содержательный --- `cl_platform_id` это просто указатель на не очень понятно что. Но нам это и не надо --- это всего лишь идентификатор, который умеют понимать другие функции апи. ==== `clGetPlatformInfo` --- Получаем информацию о конкретной платформе. Сюда передаётся `platformID`, полученный на предыдущем этапе, и константа, обозначающая, какую информацию мы хотим. Остальное --- как раньше. #let (doc, x) = commit( br-platfromIDs, ```cpp for (auto platform : platforms) { println(platform); size_t pl_name_length; clGetPlatformInfo(platform, CL_PLATFORM_NAME, 0, nullptr, &pl_name_length); std::vector<char> pl_name(pl_name_length); clGetPlatformInfo(platform, CL_PLATFORM_NAME, pl_name_length, pl_name.data(), &pl_name_length); std::string str(pl_name.begin(), pl_name.end()); println(str); } ```, ) #doc #show-branch-code(x) Здесь можно запросить разную информацию. Но сначала давайте сначала сделаем какую-нибудь обёртку для всех этих вызовов. Можно было бы сделать это по-честному template функцией, но мы хотим без лишней возни удобные сообщения об ошибках... #text(size: .8em)[ #extract("/typst/sources/gpu/draft-prelude.cpp", "wmacros") ] Выколите мне глаза. Но, зато теперь относительно понятно, что мы делаем: Зато теперь относительно нормально вызываем: #let (doc, br-info-printed) = commit( cppgit, ```cpp auto platforms = wGetPlatformIDs(); for (auto platform : platforms) { println(); println(platform); auto profile = wGetPlatformInfoStr(platform, CL_PLATFORM_PROFILE); auto version = wGetPlatformInfoStr(platform, CL_PLATFORM_VERSION); auto name = wGetPlatformInfoStr(platform, CL_PLATFORM_NAME); auto vendor = wGetPlatformInfoStr(platform, CL_PLATFORM_VENDOR); auto extensions = wGetPlatformInfoStr(platform, CL_PLATFORM_EXTENSIONS); auto host_timer_resolution = wGetPlatformInfo<cl_ulong>(platform, CL_PLATFORM_HOST_TIMER_RESOLUTION); println("Profile: ", profile); println("Version: ", version); println("Name: ", name); println("Vendor: ", vendor); println("Extensions: ", extensions); println("Host Timer Resolution: ", host_timer_resolution); } ```, ) #doc На компьютере установлены две платформы (у вас может быть по-другому), встроенная графика AMD процессора, и Intel'овская реализация на процессоре. ==== `clGetDeviceIDs` Наконец, мы хотим получить от платформы список доступных девайсов. Эта функция принимает id платформы и тип девайса, который мы хотим, на выбор: #align( center, )[ #box( width: 90%, )[ #tablex( columns: 2, stroke: foreground, [CL_DEVICE_TYPE_CPU], [An OpenCL device that is the host processor. The host processor runs the OpenCL implementations and is a single or multi-core CPU.], [CL_DEVICE_TYPE_GPU], [An OpenCL device that is a GPU. By this we mean that the device can also be used to accelerate a 3D API such as OpenGL or DirectX.], [CL_DEVICE_TYPE_ACCELERATOR], [Dedicated OpenCL accelerators (for example the IBM CELL Blade). These devices communicate with the host processor using a peripheral interconnect such as PCIe.], [CL_DEVICE_TYPE_DEFAULT], [The default OpenCL device in the system.], [CL_DEVICE_TYPE_ALL], [All OpenCL devices available in the system.], ) ] -- Прямиком из документации #box( width: 90%, )[ #tablex( columns: 2, stroke: foreground, [CL_DEVICE_TYPE_CPU], [Устройство OpenCL, главный процессор. Хост-процессор запускает реализации OpenCL и представляет собой одно-- или многоядерный CPU.], [CL_DEVICE_TYPE_GPU], [Устройство OpenCL, графический процессор. Под этим мы подразумеваем, что устройство также можно использовать для ускорения 3D API, такого как OpenGL или DirectX.], [CL_DEVICE_TYPE_ACCELERATOR], [Специальные ускорители OpenCL (например, IBM~CELL~Blade). Эти устройства взаимодействуют с главным процессором с помощью периферийного соединения, такого как PCIe.], [CL_DEVICE_TYPE_DEFAULT], [Устройство OpenCL по умолчанию в системе.], [CL_DEVICE_TYPE_ALL], [ Все устройства OpenCL, доступные в системе. ], ) ] -- Мне лень переводить. ] #let (doc, obtain-devices) = commit( br-info-printed, ```cpp for (auto platform : platforms) { println("For platform ", platform); println("CPU: ", wGetDeviceIDs( platform, CL_DEVICE_TYPE_CPU)); println("GPU: ", wGetDeviceIDs( platform, CL_DEVICE_TYPE_GPU)); println("ACCELERATOR: ", wGetDeviceIDs( platform, CL_DEVICE_TYPE_ACCELERATOR)); println("DEFAULT: ", wGetDeviceIDs( platform, CL_DEVICE_TYPE_DEFAULT)); println("ALL: ", wGetDeviceIDs( platform, CL_DEVICE_TYPE_ALL)); println(); } ```, ) #doc Здесь внезапно обнаруживаем, что если девайсов не найдено, то первый вызов функции не "вернёт" 0, а выдаст код ошибки -1. Учитываем это. Ну круто, у нас две платформа с одним девайсом на каждой. Выбираю реализацию на процессоре, так как драйвера amd graphics под линукс немного глючные. ==== Делаем что-то полезное Допустим, мы выбрали интересующий нас девайс. #let (doc, select-devices) = commit(br-info-printed, ```cpp auto devices = wGetDeviceIDs(platforms[1], CL_DEVICE_TYPE_ALL); ```, show-results: false) #doc ... или несколько... Кстати, конечно, выбирать явным индексом, конечно, плохая идея, но об этом мы потом подумаем. Теперь нам нужно создать контекст. ===== `clCreateContext` Контекст --- это своего рода `globalThis` от мира OpenCL. Он инкапсулирует в себе всё, что мы хотим из хост-кода делать с девайс-кодом. Функция принимает кучу всего. В частности, умеет принимать несколько девайсов, если они принадлежат одной платформе. Ну, пока обойдёмся. В качестве `user_data` передаём nullptr. `properties` --- тоже странная штука, пока обойдёмся без неё. #let (doc, context-created) = commit(select-devices, ```cpp auto context = wCreateContext(nullptr, devices, nullptr, nullptr); println(context); ```) #doc Ещё один несодержательный указатель. Теперь нужно в этом контексте создать тот код, который мы будем запускать в этом контексте: ==== `clCreateProgramWithSource` "Принимает" массив указателей на source. Обычно мы хотим не извращаться с C-style строчками, а иметь отдельный файл с исходным кодом (обычно расширение `.cl`). То есть, надо открыть файл, прочитать и скормить (компиляция девайс-кода будет уже в рантайме). Предлагается использовать обычные C'шные функции fread и прочее. Открыть в `binary`, `seek` до конца и так далее. Эта функция не делает ничего особенного. Если мы тут зафейлились, мы где-то конкретно налажали --- передали кривой буфер или ещё что-нибудь. Ошибки внутри девайс-кода будут обнаруживаться уже потом. ==== `clBuildProgram` Вот это уже серьёзно: компиляция нашего исходника. Передаём сюда `id` нашего `program`'a, который мы по'create'или, и девайс, под который надо скомпилиться. Или передать null, и тогда будет скомпилированно под все девайсы, привязанные к контексту. Компиляция может занимать продолжительное время! Имеет смысл локально закэшировать. Но так как результат сильно зависит от драйверов, девайсов, версий, погоды, фазы луны; распространять прекомпилированную версию не имеет смысла. Если в девайс-коде есть какая-нибудь синтаксическая (или ещё что-нибудь) ошибка, то она вылезет здесь. Обязательно проверять результат здесь! Можно сделать `clGetBuildInfo`, чтобы получить билд-лог (своего рода compilation error), ему нужно давать честный `id` девайса. build-options --- не должен быть null! Некоторые платформы могут его не пережить. Передайте пустую строчку. Или, лучше, используйте по назначению! Например, можно с помощью `-D` передавать дефайнами переменные. Здесь функция-обёртка поосмысленней: #extract("/typst/sources/gpu/draft-prelude.cpp", "buildmacro") ==== Наконец, девайс-код ``` kernel void add(global const int *a, global const int *b, global int *c) { *c = *a + *b; } ``` Здесь немного нового по сравнению с С. - `kernel` означает, что это точка входа в программу. Их может быть несколько --- это не совсем то же, что `main`. - `global` означает... что означает? потом поговорим. Давайте делать. #let (doc, program-built) = commit( context-created, ```cpp const char* source = "kernel void add(global const int *a, " "global const int *b, global int *c) {\n" " *c = *a + *b;\n" "}\n"; auto source_len = std::string(source).length(); cl_program program = wCreateProgramWithSource(context, 1, &source, &source_len); println(program); wBuildProgram(program, devices, "", nullptr, nullptr); ```, ) #doc ... и ещё один указатель куда-то... Зато, если у нас не удался `build`, мы получаем человекочитаемое сообщение об ошибке! Например, попытаемся вставить пробел в середину слова `void`: #let (doc, _) = commit( context-created, ```cpp const char* source = "kernel vo id add(global const int *a, " "global const int *b, global int *c) {\n" " *c = *a + *b;\n" "}\n"; auto source_len = std::string(source).length(); cl_program program = wCreateProgramWithSource(context, 1, &source, &source_len); println(program); wBuildProgram(program, devices, "", nullptr, nullptr); ```, ) #doc ===== `clCreateKernel` --- создаёт идентификатор, через который мы сможем вызывать `kernel`. Передаём туда имя. #let (doc, kernel-created) = commit(program-built, ```cpp cl_kernel add = wCreateKernel(program, "add"); ```, execute: false) #doc Теперь мы хотим передать ему аргументы и запустить его! Проблемы? Э-э-э......... Указатели на память, что вы думаете, сработает? Ха. Где память? На девайсе. Мы её выделили? Нет. Очень жаль. Давайте выделять... ==== Here we go again ===== `clCreateBuffer` Выделяем память на девайсе. Нам надо только передать размер буфера, и то, как мы хотим к нему обращаться из кернела (read only, write only, read-write). В данном случае, мы хотим три буфера: под `a` и под `b` --- read-only, под `c` --- write-only. Ну, мы можем оба подписать read-write, но лучше так --- так что-нибудь оптимизировать (не надо про протокол когерентности, кэши, всё остальное думать). Понятно, что доступ распространяется только на кернел, с хоста-то мы и так записать/прочитать сможем. `clCreateBuffer` возвращает `cl_mem`, это своего рода указатель, но не указатель. Это хендл, арифметику с ним делать нельзя. А мы написали `int`... а что это? Понятное дело, что `int` на девайсе и `int` на хосте могут отличаться. Ну так для этого может быть `cl_int`. На самом деле, они даже фиксированы, не зависят от девайса. Так что это всегда 32 бита. Лучше, чем в С! А вот `size_t` девайса мы не знаем. Точнее, можем спросить, но это будет уже в рантайме и у конкретного девайса. Так что кернелам просто запрещено принимать `size_t`. #let (doc, buffers-created) = commit(kernel-created, ```cpp cl_mem aBuffer = wCreateBuffer(context, CL_MEM_READ_ONLY, 4, nullptr); cl_mem bBuffer = wCreateBuffer(context, CL_MEM_READ_ONLY, 4, nullptr); cl_mem cBuffer = wCreateBuffer(context, CL_MEM_WRITE_ONLY, 4, nullptr); ```, execute: false) #doc ===== `clSetKernelArg` Наконец, можем накормить кернел аргументами. Указываем сюда идентификатор кернела, номер аргумента, значение аргумента (оно --- как адрес + количество байтов). Так как мы передаём "указатели", в качестве количества байтов у нас `size_of(cl_mem)` #let (doc, args-set) = commit(buffers-created, ```cpp wSetKernelArg(add, 0, sizeof(cl_mem), &aBuffer); wSetKernelArg(add, 1, sizeof(cl_mem), &bBuffer); wSetKernelArg(add, 2, sizeof(cl_mem), &cBuffer); ```, execute: false) #doc ===== `clEnqueueWriteBuffer` В наших буферах лежит какой-то мусор, надо его наполнить. Чувствуется в названии подвох. ===== `clCreateCommandQueue` --- очередь команд, чего мы хотим. Принимает контекст и девайс. А ещё принимает _флажки_. Один из них полезный --- profiling info (или как-то так), причём почти ничего не стоит. Рассказывает, сколько времени уходит на процессы. Второй --- `out of order executionary mode`. Не влезай, убьёт. #let (doc, queue-created) = commit( args-set, ```cpp auto command_queue = wCreateCommandQueue(context, devices[0], CL_QUEUE_PROFILING_ENABLE); ```, execute: false, ) #doc ===== `clEnqueueWriteBuffer` , да. Принимает `cl_mem`, указатель наш (откуда брать данные), флажок `blocking write`. Про блокирующее чтение и запись. Мы ставим _задание на постановку в очередь_. Если мы не поставим флажок, то оно вернётся мгновенно! И ничего не дождётся. Имеет смысл делать передачу данных *на* девайс не блокирующей, а *с* девайса --- блокирующей. Очередь ленивая, не будет ничего исполнять, пока мы не пнём её. Ну, или можно пнуть через "подождать выполнения всех функций". Или спросить "#strike[а не в омах ли измеряется сопротивление] а не закончилось ли исполнение". - Спойлер: В конце захотим `clEnqueueReadBuffer`. #let (doc, buffers-wrote) = commit(queue-created, ```cpp cl_int a = 2; cl_int b = 3; wEnqueueWriteBuffer(command_queue, aBuffer, false, 0, 4, &a, 0, nullptr, nullptr); wEnqueueWriteBuffer(command_queue, bBuffer, false, 0, 4, &b, 0, nullptr, nullptr); ```, execute: false) #doc ===== `clEnqueueNDRangeKernel` --- урааа! Запуск кернела. Передаём туда, очевидно, очередь и кернел. Принимает также dimensions (who? пока передаём 1); global work size, причём через указатель (пока тоже 1); local work size --- смело кормим null'ами, так же поступаем с event'ами. #let (doc, kernel-ranged) = commit( buffers-wrote, ```cpp size_t global_work_size = 1; wEnqueueNDRangeKernel(command_queue, add, 1, nullptr, &global_work_size, nullptr, 0, nullptr, nullptr); ```, execute: false, ) #doc ===== `clEnqueueReadBuffer` Наконец, читаем нашу замечательную сумму двух чисел. Будем на это, во всяком случае, надеяться. #let (doc, buffers-read) = commit( kernel-ranged, ```cpp cl_int c = 0; wEnqueueReadBuffer(command_queue, cBuffer, true, 0, 4, &c, 0, nullptr, nullptr); ```, execute: false, ) #doc - Замечание к окончанию: всё, что мы `create`, хорошо бы потом `release`. А то может быть грустно. #let (doc, all-released) = commit(buffers-read, ```cpp clReleaseMemObject(aBuffer); clReleaseMemObject(bBuffer); clReleaseMemObject(cBuffer); clReleaseProgram(program); clReleaseKernel(add); clReleaseCommandQueue(command_queue); clReleaseContext(context); println(c); ```) #doc - А если что-нибудь криво работает на девайсе... Ну, упадёт видео-драйвер. Винда его обычно поднимает через пару секунд, остальные --- ... поэкспериментируйте! === Наконец, занимаемся чем-то полезным. Хотим посчитать сумму элементов массива. - work_item --- идейно тред. Но их много. Тысячи их. - SIMT: single instruction, multiple threads. Есть вычислительные блоки, а есть понятие "ядер" видеокарты. Если проводить аналогию с процессором --- ядер не так много. Quda-псевдо-ядра это что-то в духе конвееров (умеет считать, но не имеет логики управления). Конвееры объединяются в ядра, как раз. И вот эти work-item'ы --- запускаются на конвейерах. И они исполняют одну и ту же команду одновременно. Если у насd ситуация, что есть if, то сначала все исполняют одну ветку (часть тредов ждёт), потом наоборот. Хотя если все одновременно в одну ветку зашли, то ждать не будут. Особенно интересно про циклы будет, конечно... - Соответственно, пачку тредов, исполняющихся одновременно, называем варпом. Их там 32 или 64, но это не очень важно. Где-то зашито, где-то можно выбрать. Это набор тредов, выполняющихся аппаратно синхронно. Хотя на новых видеокарточках, бывает, расходится, ну да неважно. - Сэкономили на обращении к памяти. Запускаем на ядре несколько пачек тредов, и переключаемся между ними, когда текущая обращается к памяти. Поэтому принципиально кэш видеокарточкам не нужен, но кое-где его делают. Где-то для буферизации записи, где-то для экономии энергии. - Так вот, `global_work_size` --- это то, сколько тредов мы хотим запустить _всего_. Они, конечно, не обязательно будут запущены одновременно. `local_work_size` --- гарантированно будет запущенно на одном аппаратном исполнителе. Зачем? У тредов есть оперативка девайса (global), и регистры (одного потока, их мало). А ещё! Есть локальная память (local). Она общая для тредов одного исполнителя. На размер локальной группы есть ограничения, можно спросить у девайса, какой у него лимит. По стандарту нам гарантируется, что максимальный --- ... адын! Хотя на самом деле обычно 256, а DirectX и вовсе требует 1024. Ну и соответственно, если сделать некратно размеру варпа, то просто часть тредов будет неактивна. Итак, что мы теперь делаем, чтобы запустить наше `a+b`? + Буфера размера побольше. + Global work size размером в количество элементов. + Мы не используем никакого межтредового взаимодействия, так что `local_work_size` --- `null`. То есть, драйвер, разбирайся сам. + Получить внутри кернела его номер: `get_global_id(0)` (возвращает size_t) + Наконец, поменять кернел: ``` size_t x = get_global_id(0); c[x] = a[x] + b[x]; ``` Правда, регистры здесь все 32-битные, а size_t не обязательно 32-битное. А мы хотим не выжирать много регистров (приватной памяти), а то часть ещё пойдёт в глобальную память... Так что будьте внимательны, может, лучше использовать иногда uint. Кстати, можно узнать, сколько у нас не влезло в регистры, и поправить код. А то это самая большая просадка по времени будет. Аналогично с `get_global_id`, есть `get_local_id` --- номер в группе, и `get_group_id` --- номер группы. А почему 0? А помните у нас был dimension --- 1? Это нумерация тредов. Она может быть одномерной, двумерной, трёхмерной. Соответственно, тогда у треда будет номер по х, номер по y, номер по z. Просто для удобства нумерации, чтобы не надо было в случае чего делить/умножать/и так далее. Так вот 0 --- это номер координаты. #let read-folder(dir, ..files) = { let res = (:) for f in files.pos() { res.insert(f, read(dir + "/" + f)) } res } #full-externation-log( read-folder("/typst/sources/gpu/aplusb", "CMakeLists.txt", "main.cpp", "program.cl", "utils.h", "utils.cpp", "wrappers.h", "wrappers.cpp"), eval(read("gpu/cmake-build-command.txt")), foreground: foreground, error: rgb("#770000"), hide-files: (), hide-commands: (), ) #close-exec()
https://github.com/pku-typst/ichigo
https://raw.githubusercontent.com/pku-typst/ichigo/main/test.typ
typst
MIT License
#import "src/model.typ": themes-validation #themes-validation(( course-name: "Typst 使用小练习", serial-str: "第 1 次作业", author-info: "PKU-Typst", author-names: (), ))
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap8/4_ammeter_design.typ
typst
Other
#import "../../core/core.typ" === Ammeter design A meter designed to measure electrical current is popularly called an "ammeter" because the unit of measurement is "amps." In ammeter designs, external resistors added to extend the usable range of the movement are connected in _parallel_ with the movement rather than in series as is the case for voltmeters. This is because we want to divide the measured current, not the measured voltage, going to the movement, and because current divider circuits are always formed by parallel resistances. Taking the same meter movement as the voltmeter example, we can see that it would make a very limited instrument by itself, full-scale deflection occurring at only 1 mA: As is the case with extending a meter movement's voltage-measuring ability, we would have to correspondingly re-label the movement's scale so that it read differently for an extended current range. For example, if we wanted to design an ammeter to have a full-scale range of 5 amps using the same meter movement as before (having an intrinsic full-scale range of only 1 mA), we would have to re-label the movement's scale to read 0 A on the far left and 5 A on the far right, rather than 0 mA to 1 mA as before. Whatever extended range provided by the parallel-connected resistors, we would have to represent graphically on the meter movement face. #image("static/00150.png") Using 5 amps as an extended range for our sample movement, let's determine the amount of parallel resistance necessary to "shunt," or bypass, the majority of current so that only 1 mA will go through the movement with a total current of 5 A: #image("static/00162.png") #image("static/10157.png") From our given values of movement current, movement resistance, and total circuit (measured) current, we can determine the voltage across the meter movement (Ohm's Law applied to the center column, $E = I R$): #image("static/10158.png") Knowing that the circuit formed by the movement and the shunt is of a parallel configuration, we know that the voltage across the movement, shunt, and test leads (total) must be the same: #image("static/10159.png") We also know that the current through the shunt must be the difference between the total current (5 amps) and the current through the movement (1 mA), because branch currents add in a parallel configuration: #image("static/10160.png") Then, using Ohm's Law ($R=E/I$) in the right column, we can determine the necessary shunt resistance: #image("static/10161.png") Of course, we could have calculated the same value of just over 100 milli-ohms ($100 m Omega$) for the shunt by calculating total resistance ($R=E/I$; $0.5 "volts"/5 "amps" = 100 m Omega$ exactly), then working the parallel resistance formula backwards, but the arithmetic would have been more challenging: $ R_"shunt" = 1 / (1 / (100 m) - 1/500) \ R_"shunt" = 100.02 m Omega $ In real life, the shunt resistor of an ammeter will usually be encased within the protective metal housing of the meter unit, hidden from sight. Note the construction of the ammeter in the following photograph: #image("static/50025.jpg") This particular ammeter is an automotive unit manufactured by Stewart-Warner. Although the D'Arsonval meter movement itself probably has a full scale rating in the range of milliamps, the meter as a whole has a range of $plus.minus 60 "amps"$. The shunt resistor providing this high current range is enclosed within the metal housing of the meter. Note also with this particular meter that the needle centers at zero amps and can indicate either a "positive" current or a "negative" current. Connected to the battery charging circuit of an automobile, this meter is able to indicate a charging condition (electrons flowing from generator to battery) or a discharging condition (electrons flowing from battery to the rest of the car's loads). As is the case with multiple-range voltmeters, ammeters can be given more than one usable range by incorporating several shunt resistors switched with a multi-pole switch: #image("static/00163.png") Notice that the range resistors are connected through the switch so as to be in parallel with the meter movement, rather than in series as it was in the voltmeter design. The five-position switch makes contact with only one resistor at a time, of course. Each resistor is sized accordingly for a different full-scale range, based on the particular rating of the meter movement (1 mA, 500 Ω). With such a meter design, each resistor value is determined by the same technique, using a known total current, movement full-scale deflection rating, and movement resistance. For an ammeter with ranges of 100 mA, 1 A, 10 A, and 100 A, the shunt resistances would be as such: #image("static/00164.png") Notice that these shunt resistor values are very low! 5.00005 mΩ is 5.00005 milli-ohms, or 0.00500005 ohms! To achieve these low resistances, ammeter shunt resistors often have to be custom-made from relatively large-diameter wire or solid pieces of metal. One thing to be aware of when sizing ammeter shunt resistors is the factor of power dissipation. Unlike the voltmeter, an ammeter's range resistors have to carry large amounts of current. If those shunt resistors are not sized accordingly, they may overheat and suffer damage, or at the very least lose accuracy due to overheating. For the example meter above, the power dissipations at full-scale indication are (the double-squiggly lines represent "approximately equal to" in mathematics): #image("static/10163.png") $ P_(R 1) &= E^2 / R_1 = (0.5 V)^2 / (5.00005 m Omega) approx 50 W \ P_(R 2) &= E^2 / R_2 = (0.5 V)^2 / (50.005 m Omega) approx 5 W \ P_(R 3) &= E^2 / R_3 = (0.5 V)^2 / (500.5 m Omega) approx 0.5 W \ P_(R 4) &= E^2 / R_4 = (0.5 V)^2 / (5.05 Omega) approx 49.5 m W \ $ An 1/8 watt resistor would work just fine for R#sub[4], a 1/2 watt resistor would suffice for R#sub[3] and a 5 watt for R#sub[2] (although resistors tend to maintain their long-term accuracy better if not operated near their rated power dissipation, so you might want to over-rate resistors R#sub[2] and R#sub[3]), but precision 50 watt resistors are rare and expensive components indeed. A custom resistor made from metal stock or thick wire may have to be constructed for R#sub[1] to meet both the requirements of low resistance and high power rating. Sometimes, shunt resistors are used in conjunction with voltmeters of high input resistance to measure current. In these cases, the current through the voltmeter movement is small enough to be considered negligible, and the shunt resistance can be sized according to how many volts or millivolts of drop will be produced per amp of current: #image("static/00165.png") If, for example, the shunt resistor in the above circuit were sized at precisely 1 Ω, there would be 1 volt dropped across it for every amp of current through it. The voltmeter indication could then be taken as a direct indication of current through the shunt. For measuring very small currents, higher values of shunt resistance could be used to generate more voltage drop per given unit of current, thus extending the usable range of the (volt)meter down into lower amounts of current. The use of voltmeters in conjunction with low-value shunt resistances for the measurement of current is something commonly seen in industrial applications. The use of a shunt resistor along with a voltmeter to measure current can be a useful trick for simplifying the task of frequent current measurements in a circuit. Normally, to measure current through a circuit with an ammeter, the circuit would have to be broken (interrupted) and the ammeter inserted between the separated wire ends, like this: #image("static/00166.png") If we have a circuit where current needs to be measured often, or we would just like to make the process of current measurement more convenient, a shunt resistor could be placed between those points and left there permanently, current readings taken with a voltmeter as needed without interrupting continuity in the circuit: #image("static/00167.png") Of course, care must be taken in sizing the shunt resistor low enough so that it doesn't adversely affect the circuit's normal operation, but this is generally not difficult to do. This technique might also be useful in computer circuit analysis, where we might want to have the computer display current through a circuit in terms of a voltage (with SPICE, this would allow us to avoid the idiosyncrasy of reading negative current values): #image("static/00168.png") ``` shunt resistor example circuit v1 1 0 rshunt 1 2 1 rload 2 0 15k .dc v1 12 12 1 .print dc v(1,2) .end ``` ``` v1 v(1,2) 1.200E+01 7.999E-04 ``` We would interpret the voltage reading across the shunt resistor (between circuit nodes 1 and 2 in the SPICE simulation) directly as amps, with 7.999E-04 being 0.7999 mA, or $799.9 mu A$. Ideally, 12 volts applied directly across 15 kΩ would give us exactly 0.8 mA, but the resistance of the shunt lessens that current just a tiny bit (as it would in real life). However, such a tiny error is generally well within acceptable limits of accuracy for either a simulation or a real circuit, and so shunt resistors can be used in all but the most demanding applications for accurate current measurement. #core.review[ - Ammeter ranges are created by adding parallel "shunt" resistors to the movement circuit, providing a precise current division. - Shunt resistors may have high power dissipations, so be careful when choosing parts for such meters! - Shunt resistors can be used in conjunction with high-resistance voltmeters as well as low-resistance ammeter movements, producing accurate voltage drops for given amounts of current. Shunt resistors should be selected for as low a resistance value as possible to minimize their impact upon the circuit under test. ]
https://github.com/Nerixyz/icu-typ
https://raw.githubusercontent.com/Nerixyz/icu-typ/main/README.md
markdown
MIT License
# icu-datetime <!-- markdownlint-disable-file MD033 --> <!-- markdownlint-configure-file { "no-duplicate-heading": { "siblings_only": true } } --> This library is a wrapper around [ICU4X](https://github.com/unicode-org/icu4x)' `datetime` formatting for Typst which provides internationalized formatting for dates, times, and timezones. As the WASM bundle includes all localization data, it's quite large (about 8 MiB). See [nerixyz.github.io/icu-typ](https://nerixyz.github.io/icu-typ) for a full API reference with more examples. ## Example ```typ #import "@preview/icu-datetime:0.1.2": fmt-date, fmt-time, fmt-datetime, experimental // These functions may change at any time #import experimental: fmt-timezone, fmt-zoned-datetime #let day = datetime( year: 2024, month: 5, day: 31, ) #let time = datetime( hour: 18, minute: 2, second: 23, ) #let dt = datetime( year: 2024, month: 5, day: 31, hour: 18, minute: 2, second: 23, ) #let tz = ( offset: "-07", iana: "America/Los_Angeles", zone-variant: "st", // standard ) = Dates #fmt-date(day, locale: "km", length: "full") \ #fmt-date(day, locale: "af", length: "full") \ #fmt-date(day, locale: "za", length: "full") \ = Time #fmt-time(time, locale: "id", length: "medium") \ #fmt-time(time, locale: "en", length: "medium") \ #fmt-time(time, locale: "ga", length: "medium") \ = Date and Time #fmt-datetime(dt, locale: "ru", date-length: "full") \ #fmt-datetime(dt, locale: "en-US", date-length: "full") \ #fmt-datetime(dt, locale: "zh-Hans-CN", date-length: "full") \ #fmt-datetime(dt, locale: "ar", date-length: "full") \ #fmt-datetime(dt, locale: "fi", date-length: "full") = Timezones (experimental) #fmt-timezone( ..tz, local-date: datetime.today(), format: "specific-non-location-long" ) \ #fmt-timezone( ..tz, format: ( iso8601: ( format: "utc-extended", minutes: "required", seconds: "optional", ) ) ) = Zoned Datetimes (experimental) #fmt-zoned-datetime(dt, tz) \ #fmt-zoned-datetime(dt, tz, locale: "lv") \ #fmt-zoned-datetime(dt, tz, locale: "en-CA-u-hc-h24-ca-buddhist") ``` <!-- typst c res/example.typ res/example.png --root . --> ![Example](res/example.png) Locales must be [Unicode Locale Identifier]s. Use [`locale-info(locale)`](https://nerixyz.github.io/icu-typ/locale-info/) to get information on how a locale is parsed. Unicode extensions are supported, so you can, for example, set the hour cycle with `hc-h12` or set the calendar with `ca-buddhist` (e.g. `en-CA-u-hc-h24-ca-buddhist`). ## Documentation Documentation can be found on [nerixyz.github.io/icu-typ](https://nerixyz.github.io/icu-typ). ## Using Locally Download the [latest release](https://github.com/Nerixyz/icu-typ/releases), unzip it to your [local Typst packages](https://github.com/typst/packages#local-packages), and use `#import "@local/icu-datetime:0.1.2"`. ## Building To build the library, you need to have [Rust](https://www.rust-lang.org/), [just](https://just.systems/), and [`wasm-opt`](https://github.com/WebAssembly/binaryen) installed. ```sh just build # to deploy the package locally, use `just deploy` ``` While developing, you can symlink the WASM file into the root of the repository (it's in the `.gitignore`): ```sh # Windows (PowerShell) New-Item icu-datetime.wasm -ItemType SymbolicLink -Value ./target/wasm32-unknown-unknown/debug/icu_typ.wasm # Unix ln -s ./target/wasm32-unknown-unknown/debug/icu_typ.wasm icu-datetime.wasm ``` Use `cargo b --target wasm32-unknown-unknown` to build in debug mode. [Unicode Locale Identifier]: https://unicode.org/reports/tr35/tr35.html#Unicode_locale_identifier
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-3130.typ
typst
Apache License 2.0
#let data = ( (), ("HANGUL LETTER KIYEOK", "Lo", 0), ("HANGUL LETTER SSANGKIYEOK", "Lo", 0), ("HANGUL LETTER KIYEOK-SIOS", "Lo", 0), ("HANGUL LETTER NIEUN", "Lo", 0), ("HANGUL LETTER NIEUN-CIEUC", "Lo", 0), ("HANGUL LETTER NIEUN-HIEUH", "Lo", 0), ("HANGUL LETTER TIKEUT", "Lo", 0), ("HANGUL LETTER SSANGTIKEUT", "Lo", 0), ("HANGUL LETTER RIEUL", "Lo", 0), ("HANGUL LETTER RIEUL-KIYEOK", "Lo", 0), ("HANGUL LETTER RIEUL-MIEUM", "Lo", 0), ("HANGUL LETTER RIEUL-PIEUP", "Lo", 0), ("HANGUL LETTER RIEUL-SIOS", "Lo", 0), ("HANGUL LETTER RIEUL-THIEUTH", "Lo", 0), ("HANGUL LETTER RIEUL-PHIEUPH", "Lo", 0), ("HANGUL LETTER RIEUL-HIEUH", "Lo", 0), ("HANGUL LETTER MIEUM", "Lo", 0), ("HANGUL LETTER PIEUP", "Lo", 0), ("HANGUL LETTER SSANGPIEUP", "Lo", 0), ("HANGUL LETTER PIEUP-SIOS", "Lo", 0), ("HANGUL LETTER SIOS", "Lo", 0), ("HANGUL LETTER SSANGSIOS", "Lo", 0), ("HANGUL LETTER IEUNG", "Lo", 0), ("HANGUL LETTER CIEUC", "Lo", 0), ("HANGUL LETTER SSANGCIEUC", "Lo", 0), ("HANGUL LETTER CHIEUCH", "Lo", 0), ("HANGUL LETTER KHIEUKH", "Lo", 0), ("HANGUL LETTER THIEUTH", "Lo", 0), ("HANGUL LETTER PHIEUPH", "Lo", 0), ("HANGUL LETTER HIEUH", "Lo", 0), ("HANGUL LETTER A", "Lo", 0), ("HANGUL LETTER AE", "Lo", 0), ("HANGUL LETTER YA", "Lo", 0), ("HANGUL LETTER YAE", "Lo", 0), ("HANGUL LETTER EO", "Lo", 0), ("HANGUL LETTER E", "Lo", 0), ("HANGUL LETTER YEO", "Lo", 0), ("HANGUL LETTER YE", "Lo", 0), ("HANGUL LETTER O", "Lo", 0), ("HANGUL LETTER WA", "Lo", 0), ("HANGUL LETTER WAE", "Lo", 0), ("HANGUL LETTER OE", "Lo", 0), ("HANGUL LETTER YO", "Lo", 0), ("HANGUL LETTER U", "Lo", 0), ("HANGUL LETTER WEO", "Lo", 0), ("HANGUL LETTER WE", "Lo", 0), ("HANGUL LETTER WI", "Lo", 0), ("HANGUL LETTER YU", "Lo", 0), ("HANGUL LETTER EU", "Lo", 0), ("HANGUL LETTER YI", "Lo", 0), ("HANGUL LETTER I", "Lo", 0), ("HANGUL FILLER", "Lo", 0), ("HANGUL LETTER SSANGNIEUN", "Lo", 0), ("HANGUL LETTER NIEUN-TIKEUT", "Lo", 0), ("HANGUL LETTER NIEUN-SIOS", "Lo", 0), ("HANGUL LETTER NIEUN-PANSIOS", "Lo", 0), ("HANGUL LETTER RIEUL-KIYEOK-SIOS", "Lo", 0), ("HANGUL LETTER RIEUL-TIKEUT", "Lo", 0), ("HANGUL LETTER RIEUL-PIEUP-SIOS", "Lo", 0), ("HANGUL LETTER RIEUL-PANSIOS", "Lo", 0), ("HANGUL LETTER RIEUL-YEORINHIEUH", "Lo", 0), ("HANGUL LETTER MIEUM-PIEUP", "Lo", 0), ("HANGUL LETTER MIEUM-SIOS", "Lo", 0), ("HANGUL LETTER MIEUM-PANSIOS", "Lo", 0), ("HANGUL LETTER KAPYEOUNMIEUM", "Lo", 0), ("HANGUL LETTER PIEUP-KIYEOK", "Lo", 0), ("HANGUL LETTER PIEUP-TIKEUT", "Lo", 0), ("HANGUL LETTER PIEUP-SIOS-KIYEOK", "Lo", 0), ("HANGUL LETTER PIEUP-SIOS-TIKEUT", "Lo", 0), ("HANGUL LETTER PIEUP-CIEUC", "Lo", 0), ("HANGUL LETTER PIEUP-THIEUTH", "Lo", 0), ("HANGUL LETTER KAPYEOUNPIEUP", "Lo", 0), ("HANGUL LETTER KAPYEOUNSSANGPIEUP", "Lo", 0), ("HANGUL LETTER SIOS-KIYEOK", "Lo", 0), ("HANGUL LETTER SIOS-NIEUN", "Lo", 0), ("HANGUL LETTER SIOS-TIKEUT", "Lo", 0), ("HANGUL LETTER SIOS-PIEUP", "Lo", 0), ("HANGUL LETTER SIOS-CIEUC", "Lo", 0), ("HANGUL LETTER PANSIOS", "Lo", 0), ("HANGUL LETTER SSANGIEUNG", "Lo", 0), ("HANGUL LETTER YESIEUNG", "Lo", 0), ("HANGUL LETTER YESIEUNG-SIOS", "Lo", 0), ("HANGUL LETTER YESIEUNG-PANSIOS", "Lo", 0), ("HANGUL LETTER KAPYEOUNPHIEUPH", "Lo", 0), ("HANGUL LETTER SSANGHIEUH", "Lo", 0), ("HANGUL LETTER YEORINHIEUH", "Lo", 0), ("HANGUL LETTER YO-YA", "Lo", 0), ("HANGUL LETTER YO-YAE", "Lo", 0), ("HANGUL LETTER YO-I", "Lo", 0), ("HANGUL LETTER YU-YEO", "Lo", 0), ("HANGUL LETTER YU-YE", "Lo", 0), ("HANGUL LETTER YU-I", "Lo", 0), ("HANGUL LETTER ARAEA", "Lo", 0), ("HANGUL LETTER ARAEAE", "Lo", 0), )
https://github.com/ntjess/typst-drafting
https://raw.githubusercontent.com/ntjess/typst-drafting/main/docs/utils.typ
typst
The Unlicense
#import "../drafting.typ" #let example-box = box.with(fill: white.darken(3%), inset: 0.5em, radius: 0.5em, width: 100%) #let dummy-page(width, height: auto, margin-left, margin-right, content) = { let total-width = width + margin-left + margin-right style(styles => { let content-box = box( height: height, width: width, fill: white, stroke: (left: black + 0.5pt, right: black + 0.5pt), inset: 3pt, content, ) let box-height = measure(content-box, styles).height let height = if height == auto {box-height} place(example-box(height: height, width: total-width, radius: 0pt)) pad( left: margin-left, content-box ) }) } #let _build-preamble(scope) = { let preamble = "" for module in scope.keys() { preamble = preamble + "import " + module + ": *; " } preamble } #let eval-example(source, ..scope) = [ #let preamble = _build-preamble(scope.named()) #eval( (preamble + "[" + source + "]"), scope: scope.named() ) <example-eval-result> ] #let _bidir-grid(direction, ..args) = { let grid-kwargs = (:) if direction == ltr { grid-kwargs = (columns: 2, column-gutter: 1em) } else { grid-kwargs = (rows: 2, row-gutter: 1em, columns: (100%,)) } grid(..grid-kwargs, ..args) } #let example-with-source(source, inline: false, direction: ttb, ..scope) = { let picture = eval-example(source, ..scope) let source-box = if inline {box} else {block} _bidir-grid(direction)[ #example-box(raw(lang: "typ", source)) ][ #example-box(picture) ] } #let _make-page(source, offset, w, l, r, scope) = { let props = ( "margin-right:" + repr(r) + ", margin-left:" + repr(l) + ", page-width:" + repr(w) + ", page-offset-x: " + repr(offset) ) let preamble = "#let margin-note = margin-note.with(" + props + ")\n" let content = eval-example(preamble + source.text, ..scope) dummy-page(w, l, r, content) } #let standalone-margin-note-example( source, width: 2in, margin-left: 0.8in, margin-right: 1in, scope: (drafting:drafting), direction: ltr, ) = { let (l, r) = (margin-left, margin-right) let number-args = (width, l, r) let content = _make-page(source, 0pt, ..number-args, scope) _bidir-grid(direction)[ #example-box(width: 100%, source) ][ #locate(loc => { let offset = loc.position().x set text(font: "linux libertine") layout(layout-size => { style(styles => { let minipage = content let minipage-size = measure(minipage, styles) let (width, height) = (minipage-size.width, minipage-size.height) let ratio = (layout-size.width / width) * 100% let w = width let number-args = number-args.map(n => n * ratio) minipage = _make-page(source, offset, ..number-args, scope) minipage }) }) }) ] }
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/src/util/core.typ
typst
MIT License
#import "@preview/oxifmt:0.2.0": strfmt as fmt /// Substitute `value` for the return value of `default()` if it is a sentinel value. /// /// - value (any): The value to check. /// - default (function): The function to produce the default value with. /// - check (any): The sentinel value to check for. /// -> any #let or-default(value, default, check: none) = if value == check { default() } else { value } /// An alias for `or-default` with `check: auto`. #let auto-or = or-default.with(check: auto) /// An alias for `or-default` with `check: none`. #let none-or = or-default.with(check: none) /// Returns the text direction for a given language, defaults to `ltr` for unknown languages. /// /// Source: #link("https://github.com/typst/typst/blob/9646a132a80d11b37649b82c419833003ac7f455/crates/typst/src/text/lang.rs#L50-57")[`lang.rs#L50-L57`] /// /// lang (str): The languge to get the text direction for. /// -> direction #let text-direction(lang) = if lang in ( "ar", "dv", "fa", "he", "ks", "pa", "ps", "sd", "ug", "ur", "yi", ) { rtl } else { ltr } /// Returns the page binding for a text direction. /// /// Source: #link("https://github.com/typst/typst/blob/9646a132a80d11b37649b82c419833003ac7f455/crates/typst/src/layout/page.rs#L368-L373")[`page.rs#L368-L373`] /// /// dir (direction): The direction to get the page binding for. /// -> alignement #let page-binding(dir) = (ltr: left, rtl: right).at(repr(dir)) /// A list of queryable element functions. #let queryable-functions = ( bibliography, cite, figure, footnote, heading, locate, math.equation, metadata, ref, )
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/bonus1.typ
typst
MIT License
#import "@local/evan:1.0.0":* #show: evan.with( title: [Some review problems for Midterm 1], subtitle: [18.02 Recitation MW9], author: "<NAME>", date: [16 September 2024], ) #quote(attribution: [Cynthia in Pokémon Diamond and Pearl])[ The power you learned... I can feel it emanating from you. But that's enough talk. Let's get on with why you're here. As the Pokémon League Champion, I accept your challenge! ] This handout (and any other DLC's I write) are posted at #url("https://web.evanchen.cc/1802.html"). = Problems Are you a person that plays every video game on hard mode? Yeah? I have a treat for you. More seriously, my hope is these problems help you review for Midterm 1 (in less than two weeks!), even if you don't manage to solve them yourself. My suggestion is: think about each for 15-30 minutes, then read the solution (pages 3-end of the online PDF) or come to office hours and I'll explain them. I hope this helps you digest the material; I tried to craft problems that teach deep understanding and piece together multiple ideas, rather than just using one or two isolated recipes. Solving with friends is encouraged; you'll have more fun thinking together. Still, don't worry even if you solve 0 of the 6 problems; these are way harder than what will actually appear on the midterm. The problems are sorted by the order the topics appeared in class (not by difficulty). / Problem 1.: In $RR^3$, compute the projection of the vector $vec(4,5,6)$ onto the plane $x+y+2z=0$. / Problem 2.: Suppose $A$, $B$, $C$, $D$ are points in $RR^3$. Give a geometric interpretation for this expression: $ |arrow(D A) dot (arrow(D B) times arrow(D C))|. $ / Problem 3.: Fix a plane $cal(P)$ in $RR^3$ which passes through the origin. Consider the linear transformation $f : RR^3 -> RR^3$ where $f(bf(v))$ is the projection of $bf(v)$ onto $cal(P)$. Let $M$ denote the $3 times 3$ matrix associated to $f$. Compute the determinant of $M$. / Problem 4.: Let $bf(a)$ and $bf(b)$ be two perpendicular unit vectors in $RR^3$. A third vector $bf(v)$ in $RR^3$ lies in the span of $bf(a)$ and $bf(b)$. Given that $bf(v) dot bf(a) = 2$ and $bf(v) dot bf(b) = 3$, compute the magnitudes of the cross products $bf(v) times bf(a)$ and $bf(v) times bf(b)$. / Problem 5.: Compute the trace of the $2 times 2$ matrix $M$ given the two equations $ M vec(4,7) = vec(5,9) " and " M vec(5,9) = vec(4,7). $ / Problem 6.: There are three complex numbers $z$ satisfying $z^3 = 5 + 6 i$. Suppose we plot these three numbers in the complex plane. Compute the area of the triangle they enclose. #pagebreak() _This page is intentionally blank. Solutions on next page._ #pagebreak() = Solutions == Solution to problem 1 *Answer*: $vec(1/2, 3/2, -1)$. === First approach using vector projection In recitation R02 you had to calculate the distance from a vector to a plane. This problem only requires one step on top of that: you need to then translate by the normal vector. See the cartoon below, where $bf(a)$ denotes the answer. #figure( image("figures/bonus1p1.png", width: 70%), caption: [Projection onto a plane.], ) To execute the calculation, let $bf(v) = vec(4,5,6)$ and $bf(n) = vec(1,1,2)$. The scalar projection is $ op("comp")_(bf(n)) (bf(v)) = (bf(v) dot bf(n)) / (|bf(n)|) = (21) / sqrt(6). $ The vector projection is then $ bf(a) = (op("comp")_(bf(n)) (bf(v))) (bf(n))/(|bf(n)|) = 21/sqrt(6) vec(1,1,2)/sqrt(6) = vec(7/2,7/2,7). $ Then the desired projection is $ bf(v) - op("proj")_(bf(n)) (bf(v)) = vec(1/2, 3/2, -1). $ === Second approach using normal vectors only (no projection stuff) A lot of you don't find vector projection natural (I certainly don't). So it might be easier to imagine shifting $bf(v)$ by _some_ multiple of $bf(n) = vec(1,1,2)$ and then work out which multiple it is. Specifically, we're looking for#footnote[In comparison to the first solution, the value of $t$ is exactly $ t = (op("comp")_(bf(n)) (bf(v))) /(|bf(n)|). $ But the idea behind the second solution is that you don't _need to know_ what the geometric formula of $t$ is. You can just solve for $t$ indirectly by asserting that $bf(a)$ lies on $x+y+2z=0$.] a real number $t in RR$ such that the vector $ bf(a) = bf(v) - t bf(n) = vec(4-t, 5-t, 6-2t) $ lies on the plane $x+y+2z = 0$. But we can actually solve for $t$ just by plugging this $bf(a)$ into the equation of the plane: $ (4-t) + (5-t) + 2(6-2t) = 0 ==> 21 - 6t = 0 ==> t = 7/2. $ Hence the answer $ bf(a) = vec(4-7/2, 5-7/2, 6-2(7/2)) = vec(1/2, 3/2, -1). $ #pagebreak() == Solution to problem 2 *Answer*: This equals the volume of the parallelepiped formed by $arrow(D A)$, $arrow(D B)$, $arrow(D C)$. Here are two approaches for proving it. === First approach using coordinates Let $D = (0,0,0)$, $A = (x_A, y_A, b_A)$, $B = (x_B, y_B, z_B)$, $C = (x_C, y_C, z_C)$. Then expanding the cross product gives $ (x_A bf(e)_1 + y_A bf(e)_2 + z_A bf(e_3)) dot det(mat(bf(e)_1, bf(e)_2, bf(e)_3; x_B, y_B, z_B; x_C, y_C, z_C)). $ If you think about what evaluating the determinant using the formula together with the dot product would give, you should find it's actually just $ det(mat(x_A, y_A, z_A; x_B, y_B, z_B; x_C, y_C, z_C)) $ which is the volume of the parallelepiped. === Second approach using geometric picture The cross product $arrow(D B) times arrow(D C)$ is a vector whose area is equal to the parallelogram formed by $arrow(D B)$ and $arrow(D C)$. The dot product of that cross product against $arrow(D A)$ is equal to the _height_ of $A$ to plane $B C D$ times this area, and the volume is the height times the area. See the following picture from #url("https://en.wikipedia.org/wiki/Triple_product") (in the Wikipedia figure, $bf(a)$ denotes our $arrow(D A)$, etc.). #figure( image("media/parallelepiped.png", width: 50%), caption: [Triple product image taken from Wikipedia.], ) #pagebreak() == Solution to problem 3 *Answer*: 0, no matter which plane $cal(P)$ is picked. === First approach using basis vectors Let $bf(e)_1$, $bf(e)_2$, $bf(e)_3$ be the three basis vectors. Then: - The matrix $M$ is formed by gluing $f(bf(e)_1)$, $f(bf(e)_2)$, $f(bf(e)_3)$ together. - I claim the vectors $f(bf(e)_1)$, $f(bf(e)_2)$, $f(bf(e)_3)$ are linearly dependent. After all, they are all contained in the two-dimensional plane $cal(P)$ by definition, and so three vectors in a plane can't be linearly independent. - So the determinant is equal to zero (this theorem is one of the criteria we use to check whether vectors are linearly independent or not). === Second approach using eigenvectors Let $bf(n)$ be any nonzero normal vector to $cal(P)$. Then $f(bf(n)) = bf(0)$, so $bf(n)$ is an eigenvector with eigenvalue $0$. Since the determinant is the product of the eigenvalues, the determinant must be $0$ too. === Third approach using coordinate change This approach requires you to know the fact that the determinant doesn't change if you rewrite the matrices in a new basis. Let $bf(n)$ be any nonzero normal vector to $cal(P)$. Pick two more unit vectors $bf(b)_1$ and $bf(b)_2$ perpendicular to $bf(n)$ that span $cal(P)$. Then $bf(b)_1$, $bf(b)_2$ and $bf(n)$ are linearly independent and spanning, i.e. a basis of $RR^3$. So we can change coordinates to use these instead. We know that $ M(bf(b)_1) &= bf(b)_1 \ M(bf(b)_2) &= bf(b)_2 \ M(bf(n)_2) &= bf(0). $ If we wrote $M$ as a matrix _in this new basis_ $angle.l bf(b)_1, bf(b)_2, bf(n) angle.r$ (rather than the usual basis), we would get the matrix $ M = mat(1,0,0;0,1,0;0,0,0) $ which has determinant $0$. #remark[ In fact, if you also know that the trace doesn't change when you rewrite $M$ in a different basis, this approach shows the trace $M$ is always exactly $1+1+0 = 2$ as well, no matter which plane $cal(P)$ is picked. ] #pagebreak() == Solution to problem 4 *Answer*: $|bf(a) times bf(v)| = 3$ and $|bf(b) times bf(v)| = 2$. Since $bf(v)$ is contained in the span of $bf(a)$ and $bf(b)$, we can just pay attention to the plane spanned by these two perpendicular unit vectors. So the geometric picture is that $bf(v)$ can be drawn in a rectangle with $bf(a)$ and $bf(b)$ as a basis, as shown. Because $bf(v) dot bf(a) = 2$ and $bf(v) dot bf(b) = 3$, this rectangle is $2$ by $3$. #figure( image("figures/bonus1p4.png", width: 30%), caption: [Plotting $bf(v)$ in the span of $bf(a)$ and $bf(b)$.], ) Now the magnitude of the cross product $bf(a) times bf(v)$ is supposed to be equal to the area of the parallelogram formed by $bf(a)$ and $bf(v)$, which is $3$ (because this parallelogram has base $|bf(a)|=1$ and height $|bf(v) dot bf(b)|=3$). Similarly, $bf(b) times bf(v)$ has magnitude $2$. #pagebreak() == Solution to problem 5 *Answer*: $0$. There are several approaches possible. The first two show how to find the four entries of the matrix $M$. The latter sidestep this entirely and show that the matrix is actually always trace $0$. === First approach: brute force Like in the pop quiz in my R04 notes, we will try to work out $M vec(1,0)$ and $M vec(0,1)$. We're looking for constants $c_1$ and $c_2$ such that $c_1 vec(4,7) + c_2 vec(5,9) = vec(1,0)$. - Solving the system of equations $4c_1 + 5c_2 = 1$ and $7c_1 + 9c_2 = 0$ using your favorite method gives coefficients $c_1 = 9$ and $c_2 = -7$, i.e. $ 9 vec(4,7) - 7 vec(5,9) = vec(1,0). $ This lets us get $ M( vec(1,0) ) = 9 M( vec(4,7) ) - 7 M( vec(5,9) ) = 9 vec(5,9) - 7 vec(4,7) = vec(17, 32). $ - By solving the analogous system we can find the identity $ -5 vec(4,7) + 4 vec(5,9) = vec(0,1), $ and hence: $ M( vec(0,1) ) = -5 M( vec(4,7) ) + 4 M( vec(5,9) ) = -5 vec(5,9) + 4 vec(4,7) = vec(-9, -17). $ Gluing these together $ M = mat(17,-9;32,-17). $ The trace is thus $17 + (-17) = 0$. === Second approach: inverse matrices We can collate the two given equations into saying that $ M mat(4,5;7,9) = mat(5,4;9,7). $ Hence one could also recover $M$ by multiplying by the inverse matrix: $ M = mat(5,4;9,7) mat(4,5;7,9)^(-1) = mat(5,4;9,7) 1/(4 dot 9-7 dot 5) mat(9,-5;-7,4) = mat(17,-9;32,-17). $ (Of course, we get the same entries for $M$ as the last approach.) Again the trace is $17 + (-17) = 0$. === Third approach: Guessing eigenvectors and eigenvalues Let $bf(b)_1 = vec(4,7)$ and $bf(b)_2 = vec(5,9)$. Adding and subtracting the given equations gives $ M(bf(b)_1 + bf(b)_2) &= bf(b)_1 + bf(b)_2 \ M(bf(b)_1 - bf(b)_2) &= -(bf(b)_1 - bf(b)_2). $ So $bf(b)_1 pm bf(b)_2$ are eigenvectors with eigenvalues $pm 1$. Since $M$ is a $2 times 2$ matrix there are at most two eigenvalues: we found them all! The trace of $M$ is the sum of the eigenvalues. Call in the answer $1 + (-1) = 0$. === Fourth approach: Change coordinates This approach requires you to know the fact that the trace doesn't change if you rewrite the matrices in a new basis. Since $bf(b)_1 = vec(4,7)$ and $bf(b)_2 = vec(5,9)$ are a basis of $RR^2$, we can change coordinates to use the $bf(b)_i$. In that case, $ M(bf(b)_1) = bf(b)_2 " and " M(bf(b)_2) = bf(b)_1. $ If we wrote $M$ as a matrix _in this new basis_ $angle.l bf(b)_1, bf(b)_2 angle.r$ (rather than the usual basis), we would get the matrix $ M = mat(0,1;1,0) $ which has trace $0+0=0$. #pagebreak() == Solution to problem 6 *Answer*: $(3 sqrt(3))/4 root(3, 61)$. We start by converting the complex number $5 + 6 i$ into polar form. The modulus $r$ of $5 + 6 i$ is: $ r = lr(|5 + 6 i|) = sqrt(5^2 + 6^2) = sqrt(25 + 36) = sqrt(61). $ The argument $theta$ is some random angle we won't use the exact value of: $theta = arg (5 + 6 i) = tan^(- 1) (6 / 5)$. Now to find the cube roots of $z^3 = 5 + 6 i$, we use the polar form: $ z = root(6, 61) (cos (frac(theta + 2 k pi, 3)) + i sin (frac(theta + 2 k pi, 3))) $ for $k = 0 , 1 , 2$. This gives us three roots corresponding to the different values of $k$. #figure( image("figures/bonus1p6.png", width: 60%), caption: [Three solutions to $z^3 = 5+6i$], ) This looks like an equilateral triangle centered around the origin, where each spoke coming from the origin has magnitude $s$, where $ s = root(6, 61). $ If we cut up the equilateral triangle by the three arrows above, we get three small isosceles triangles with a $120 degree$ angle at the apex. The area of each triangle is going to be $s^2/2 sin(120 degree)$. So this gives a final answer of $ 3 dot root(3,61)/2 dot sin(120 degree) = (3 sqrt(3))/4 root(3, 61). $
https://github.com/jens-hj/ds-exam-notes
https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/1.typ
typst
#import "../lib.typ": * #show link: it => underline(emph(it)) #set math.equation(numbering: "(1)") #set enum(full: true) #set math.mat(delim: "[") #set math.vec(delim: "[") #set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled)) #show heading.where(level: 1): it => text(size: 22pt, it) #show heading.where(level: 2): it => text(size: 18pt, it) #show heading.where(level: 3): it => { text(size: 14pt, mainh, pad( left: -0.4em, gridx( columns: (auto, 1fr), align: center + horizon, gap: 0em, it, rule(stroke: 1pt + mainh) ) )) } #show heading.where(level: 4): it => text(size: 12pt, secondh, it) #show heading.where(level: 5): it => text(size: 12pt, thirdh, it) #show heading.where(level: 6): it => text(thirdh, it) #show emph: it => text(accent, it) #show ref: it => { //let sup = it.supplement let el = it.element if el == none { it.citation } else { let eq = math.equation // let sup = el.supplement if el != none and el.func() == eq { // The reference is an equation let sup = if it.fields().at("supplement", default: "none") == "none" { [Equation] } else { [] } // [#it.has("supplement")] show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#sup #n] } else if it.citation.has("supplement") { if el != none and el.func() == eq { show regex("\d+"): set text(accent) let n = numbering(el.numbering, ..counter(eq).at(el.location())) [#el.supplement #n] } else { text(accent)[#it] } } } } === Data Storage ==== Basic Problem - Persistent storage - Reliable storage: no corruption, minimise loss - Cope with large amounts of data ==== Discs - Exponential growth in capacity - Linear growth in read/write speeds Thus simply getting larger discs might not helpt, and will inversely effectively slow down the overall system - especially for HDDs where random access is slow, and having to get more data from a single drive simply overburdens it. ==== Distributed System - Single machine won't be enough - Interface with multiple machine - Coordination (Interesting challenge) - Programming is more complex - Synchronise and manage - Network limitations - More points of failure - Limitation of components - Expect continuous failure NFS bad quote: _"still in use, sometimes I wonder why"_ #emoji.face.rofl #report-block[ Was I supposed to do replication with erasure codes?? ] ==== HDFS - Get data quickly - Analyse quickly #report-block[ Not expected to do low level socket programming, expected to use ZMQ or Flask or such. ] #report-block[ Definitely supposed to have done parallelism #set enum(numbering: bold-enum) 1. *Main thread to accept connections* \ #ra Make a new socket to handle each connection on a different socket. 2. *Event-based reaction* \ #ra Decent, but different \ Wouldn't do this in Python ]
https://github.com/yaoyuanArtemis/resume
https://raw.githubusercontent.com/yaoyuanArtemis/resume/main/README.md
markdown
Do What The F*ck You Want To Public License
# typst-cv-miku This is a simple, elegant, academic style CV template for [typst](https://typst.app/). Support for English and Chinese (and more). You can see the online demo [here](https://typst.app/project/rbxGsQC-tEkDq0mnNIuxkv). ## Usage 1. Read [typst](https://typst.app/docs/) documentation to know about Typst. 2. Modify these files to build your personal resume and you can edit any code to reach what you want if you have capability. 3. Modify `.typ` files to fit your needs. You may need to learn some basic typst syntax. ## By the waygit Typst currently has some [bugs](https://github.com/typst/typst/issues/144) in the emoji output, so for the time being SVG images are being used instead, which you can find at [twemoji utils](https://twemoji.godi.se/). Small icon from Material Icons (Community). ## License Licensed under [WTFPL](http://www.wtfpl.net/).
https://github.com/xkevio/parcio-typst
https://raw.githubusercontent.com/xkevio/parcio-typst/main/parcio-thesis/main.typ
typst
MIT License
#import "template/template.typ": * #import "template/parcio-bib.typ": parcio-bib // Title, Author, Abstract, // optional: thesis-type to specify "Bachelor", "Master", "PhD", etc., // optional: reviewers to specify "first-reviewer", "second-reviewer" and (if needed) "supervisor". // optional: date to specify your deadline (default: datetime.today()) // optional: lang to specify the language for text features like "" or hyphenation (specify as ISO 639-1/2/3 code, default: "en") #show: project.with( "Title", ( name: "Author", mail: "<EMAIL>" ), include "chapters/abstract.typ", thesis-type: "Bachelor/Master", reviewers: ("Prof. Dr. Musterfrau", "Prof. Dr. Mustermann", "Dr. Evil") ) // Set lower roman numbering for ToC and abstract. #set page(margin: 2.5cm, footer: none) #outline(depth: 3) #empty-page // Set arabic numbering for everything else and reset page counter. #set page(numbering: "1", footer: context { let page-count = counter(page).get().first() let page-align = if calc.odd(page-count) { right } else { left } align(page-align, counter(page).display("1")) }) #counter(page).update(1) // --- ACTUAL CONTENT OF THESIS. --- // #include "chapters/introduction/intro.typ" #include "chapters/background/background.typ" #include "chapters/eval/eval.typ" #include "chapters/conclusion/conc.typ" // --------------------------------- // #empty-page #parcio-bib("bibliography/report.bib", style: "bibliography/apalike.csl", enable-backrefs: true) #empty-page #include "appendix.typ" #empty-page #include "legal.typ"
https://github.com/yy01zz02/profile-template
https://raw.githubusercontent.com/yy01zz02/profile-template/main/readme.md
markdown
MIT License
# Typst 中文简历模板 ## 介绍 一个借助 Github Actions 实现自动部署的 Typst 简历模板。效果如下(也可参考 Release 页面中的 PDF 文件): | [中文示例](https://github.com/NorthSecond/Auto_Typst_Resume_Template/releases/download/Release-template-1.0.0/default.pdf) | [英文示例](https://github.com/NorthSecond/Auto_Typst_Resume_Template/releases/download/Release-template-1.0.0/Resume.pdf)| |:---:|:---:| | ![](https://github.com/NorthSecond/Auto_Typst_Resume_Template/blob/main/docs/Chinese.png?raw=true) | ![](https://github.com/NorthSecond/Auto_Typst_Resume_Template/blob/main/docs/English.png?raw=true)| ### 字体 中文简历使用的是 **思源宋体**,字体文件在 `fonts` 文件夹下,使用时并不需要进行安装;英文简历模板使用 Centaur 字体。 ### 证件照支持(暂无) > 目前没有解决插入证件照之后的一些小小的设计问题,所以暂时不支持插入证件照,如果将 `init` 函数中的 `pic_path` 设为非空值可能会出现一些小问题。 目前主要遇见的问题是 Typst 的元素没有找到一个像 LaTeX 一样浮动在页面之上指定位置的方法,因此如果插入图片的话可能会导致姓名不能居中等问题,目前在想办法使用指定size溢出的方式来解决这个问题。 ### Github Actions 对于本地没有安装 Typst 的使用者,可以通过 Github Actions 实现自动部署。在每一次提交后,Github Actions 会自动运行 Typst 并将生成的 PDF 文件打包提供下载。 ## 使用方式 1. 在仓库的右上角点击 "Use this template" 按钮,选择新建一个您的仓库; 2. (可选)在 `Github Actions` 控制界面打开本仓库的 Github Action 功能; 3. 修改 `src` 文件夹下的文件为你的简历内容。 ### 本地编译 在有 Typst 和 GNU Make 的本地环境中,可以通过 Typst 命令行工具进行编译。 项目提供的 Makefile 中包含了以下几个定义目标: - `make all`:清理文件夹中的所有 .pdf 文件,然后编译中文和英文版本的简历文件; - `make clean`:清理文件夹中的所有 .pdf 文件; - `make zh`:编译中文版本的简历文件; - `make en`:编译英文版本的简历文件; ### Github Actions 项目配置了自动部署的 Github Actions,可以在每次提交后自动运行 Typst (执行的命令是 `make all`)并将生成的 PDF 文件打包提供下载。可以在 `Actions` 标签页查看运行结果,并在对应运行时的 `Summary` 页面的 `Artifacts` 部分下载生成的 PDF 文件压缩包。 ![](https://github.com/NorthSecond/Auto_Typst_Resume_Template/blob/main/docs/Action.png?raw=true) ### Github Release 项目配置了 Github Release,对于正式版本的发布,使用 `git tag` 功能打上版本号标签,Github Actions 会自动将生成的 PDF 文件发布到 Github Release 页面。 > 请注意,使用 `git tag` 功能时,需要在本地使用 `git push --tags` 命令将标签推送到远程仓库。 ### Typst Web 我制作了一个 typst.app 上的在线项目,[链接](https://typst.app/project/r4XMUB3ENQUH7zWiuK7_tO)。但是由于字体不太好上传,所以暂时还不是特别推荐。 ## TBD - [x] 英文版示例与字体 - [ ] 证件照插入的解决方案
https://github.com/SeniorMars/typst-raytracer
https://raw.githubusercontent.com/SeniorMars/typst-raytracer/main/readme.md
markdown
# raytracer in typst So far, I've implemented the mandelbrot as a proof of concept. ![Mandelbrot](https://user-images.githubusercontent.com/31679231/228093331-d9e44897-11dd-4e35-aeee-0252ced9ecd4.png) This was made to test my parser. Here is the output: ```treesitter (source_file (set_expression (function_call (identifier) (arguments (asssigned_argument (identifier) (numeric (int_literal) (unit)))))) (paragraph_break) (let_declaration (identifier) (parameters) (code_block (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (int_literal)) (assignment_expression (let_declaration (identifier)) (negation (float_literal))) (assignment_expression (let_declaration (identifier)) (float_literal)) (assignment_expression (let_declaration (identifier)) (negation (float_literal))) (assignment_expression (let_declaration (identifier)) (float_literal)) (assignment_expression (let_declaration (identifier)) (parenthesized_expression (binary_operator (parenthesized_expression (binary_operator (identifier) (identifier))) (identifier)))) (assignment_expression (let_declaration (identifier)) (parenthesized_expression (binary_operator (parenthesized_expression (binary_operator (identifier) (identifier))) (identifier)))) (let_declaration (identifier)) (let_declaration (identifier)) (let_declaration (identifier)) (let_declaration (identifier)) (assignment_expression (let_declaration (identifier)) (int_literal)) (while_expression (comparison_expression (identifier) (identifier)) (code_block (assignment_expression (let_declaration (identifier)) (binary_operator (binary_operator (identifier) (identifier)) (identifier))) (assignment_expression (let_declaration (identifier)) (int_literal)) (while_expression (comparison_expression (identifier) (identifier)) (code_block (assignment_expression (let_declaration (identifier)) (binary_operator (binary_operator (identifier) (identifier)) (identifier))) (assignment_expression (identifier) (float_literal)) (assignment_expression (identifier) (float_literal)) (assignment_expression (identifier) (binary_operator (identifier) (identifier))) (assignment_expression (identifier) (binary_operator (identifier) (identifier))) (assignment_expression (let_declaration (identifier)) (int_literal)) (while_expression (comparison_expression (boolean_expression (comparison_expression (identifier) (identifier)) (parenthesized_expression (binary_operator (identifier) (identifier)))) (float_literal)) (code_block (assignment_expression (identifier) (binary_operator (binary_operator (binary_operator (float_literal) (identifier)) (identifier)) (identifier))) (assignment_expression (identifier) (binary_operator (binary_operator (identifier) (identifier)) (identifier))) (assignment_expression (identifier) (binary_operator (identifier) (identifier))) (assignment_expression (identifier) (binary_operator (identifier) (identifier))) (assignment_operators (identifier) (int_literal)))) (assignment_expression (identifier) (binary_operator (method_call (identifier) (identifier) (arguments (argument (identifier)) (argument (int_literal)))) (int_literal))) (assignment_expression (identifier) (binary_operator (method_call (identifier) (identifier) (arguments (argument (identifier)) (argument (int_literal)))) (int_literal))) (assignment_expression (identifier) (binary_operator (method_call (identifier) (identifier) (arguments (argument (identifier)) (argument (int_literal)))) (int_literal))) (content_block (function_call (identifier) (arguments (asssigned_argument (identifier) (function_call (identifier) (arguments (argument (identifier)) (argument (identifier)) (argument (identifier))))) (asssigned_argument (identifier) (numeric (float_literal) (unit))) (asssigned_argument (identifier) (numeric (float_literal) (unit)))))) (assignment_operators (identifier) (int_literal)))) (content_block (line_break)) (assignment_operators (identifier) (int_literal)))))) (paragraph_break) (function_call (identifier) (arguments))) ```
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/013_At%20Any%20Cost.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "At Any Cost", set_name: "Battle for Zendikar", story_date: datetime(day: 25, month: 11, year: 2015), author: "<NAME>", doc ) #emph[Ob Nixilis is having a bad day.] #emph[Things had been going so well. He'd seized the power of the relocated Khalni Heart, and with it forged a connection to the raw mana of Zendikar. He was finally ready to tap into Zendikar's hedron network and restore his Planeswalker spark—and then disaster struck, in the form of the elf Planeswalker Nissa Revane.] #emph[Nissa took Khalni Heart from the demon would-be Planeswalker, repaired her own connection with Zendikar, and collapsed tons of rock and soil on him.] #emph[It was a setback. But Ob Nixilis had not gotten this far by giving up.]   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Pain. A modest upgrade to the oblivion I had been expecting. It could only mean one thing. She left me alive. I laughed. Nothing else to do, really. My body was broken in a dozen places by the collapse of the cavern, and I was thoroughly pinned in place. The act of laughing sent waves of radiant agony throughout my body, and I used the pain to diagnose my injuries. They were severe, but I would heal. I was breathing. That was nice. Shallow, pained breaths, with stone and sand pressing down on me from above, but I was clearly getting enough fresh air to keep me conscious. That implied that I wasn't that far from the surface. Or perhaps I was just near enough to an air pocket that would run out soon. None of the options were terribly good. But I was alive. Defeat, if you survive it, should mean time for reflection. Unearned arrogance has been the death of countless would-be warlords. After all, how many did I cut down for their hubris over the millennia? Here, buried alive, on the heels of a crushing loss, I decided I would take the opportunity I had been given. It had been a very good plan. Synchronize a hedron network with Khalni Heart, and use it to channel enough planar energy through my body to reignite my spark. There had been a decent chance it would have killed me, yes, but I was well past that being a concern by now. And yes, I knew that as of some decades ago, being a Planeswalker didn't mean what it used to. So much the better, really. The idea that there were countless planes out there that had lost their godlike protectors and champions! Imagine the chaos that the Mending had wrought on the Multiverse! Chaos like that needs to be quelled. Chaos like that needs to be brought to heel, and I am the perfect person for the task. The plan was good, but the plan had failed. The idea that some Planeswalker other than Nahiri would actually want to save this horrible plane had really not factored highly into my thought process. I had contingencies in place for #emph[her] , but I admit I wasn't prepared for an insane Joraga who could draw upon the heart of a dying world showing up #emph[hours] before my ritual would have been complete, upending a century's worth of work, and burying me alive. #figure(image("013_At Any Cost/01.jpg", width: 100%), caption: [Nissa's Renewal | Art by Lius Lasahido], supplement: none, numbering: none) I was annoyed. There was a bigger problem, and it was that all of my troops were in one valley, so to speak. I didn't know how long Zendikar had before the Eldrazi would finish destroying the plane, and even accounting for what I had learned, I didn't #emph[have] another half-century to recreate my work. At the rate things were progressing, the plane would be irreparably broken within the year. Not to mention that there wasn't another power source like Khalni Heart left on the plane. Well, there was #emph[one] . But even I wasn't that desperate. Not yet. I ran down my options. Option one: I try to replicate my work. Complication: The Eldrazi will almost certainly destroy the plane, with me on it, long before I succeed. Maybe I'd get extraordinarily lucky, and stumble upon another power source, but only fools plan on luck, and I didn't intend to start now. Option two: I go after the elf, and take the Heart back. Complication: Taking on a Planeswalker in my current state seems like pretty poor odds, especially one who has Khalni Heart at her disposal. Especially one who already handed me a defeat when I was at full strength. There's no honor or dignity in a futile charge against a superior foe, despite what I may have told a general or two whom I needed to do the tactically expedient thing. Option three: Team up with a greater power. Oh, it's never my first choice, but sometimes it's the only way. I had studied the Eldrazi almost as thoroughly as I had studied the hedrons. While they couldn't be bargained with, they had shown themselves willing to work through allies—old Kalitas learned that the hard way—and I would certainly relish helping them bring this world to ashes and end. But then what? They have no sense of gratitude, no sense of fairness. The idea that they would reward me in any way would be impossibly alien to them. A pyrrhic victory is merely the most palatable kind of defeat. #figure(image("013_At Any Cost/02.jpg", width: 100%), caption: [Sire of Stagnation | Art by <NAME>], supplement: none, numbering: none) Time. I needed more #emph[time] ! The solution hit me, and I laughed again. Uproarious, oblivious to the pain. I laughed until I wept molten tears. After all these centuries, nothing amuses me like irony. There was exactly one way that I could buy myself enough time to recreate my work. I was going to have to save Zendikar.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) First things first. Buried alive. I wasn't sure precisely how much time had passed. I was far from healed, but when you're counting down to the end of the world, you can cut corners sometimes. I reached out to the area around me and attempted to extinguish the nearby life, drawing the energy for myself. A simple feat of magic, and somewhat of a specialty. But when I reached out... nothing. I was buried in Bala Ged, a place stripped of all life by Ulamog. There wasn't even an insect, a worm, a blade of grass to drain for strength. This time, I found the irony less amusing. I struggled for what must have been hours before I finally managed to shift the stones above me. While doing so, I imagined a thousand pleasing ways to end the elf's miserable existence. The entire process of escape took days. A handful of the ideas held promise. From there, the next step was to excavate what I could of my hedron network. Even with a bare handful of hedrons, I could effectively construct a leyline "compass"—something that would give me a sense of the distribution of energy on what was left of the plane. If there was going to be a defense of Zendikar, the Joraga would be at the center of it, drawing on the power of Khalni Heart, and that was something I could track. The work was slow, and it gave me plenty of time to think. Ulamog's spawn were an unrelenting, unthinking force, and the various monstrosities that commanded them wielded sheer power of the sort that I had rarely seen. Still, it was the unthinking aspect of their nature that provided the opportunity. All it would take would be a properly coordinated force of sufficient might and an insufficient sense of self-preservation to give me an opportunity to strike at the head. I was sure the Zendikari were busy scrounging up such a force, even if I had no intention of leading it. The titans had been trapped for a very long time, and they could be contained again; I didn't need them destroyed, or even permanently incapacitated. Quite the contrary—I was more than pleased to give the monsters the feast they deserved. I just didn't intend to be a course. I had spent quite some time deciphering exactly what Nahiri had done to me. And now I was going to do the same thing to Ulamog: use a hedron to bind an extraplanar threat, and save Zendikar. I wondered if Nahiri would be pleased or disgusted that I was the one doing her work for her now. I found both options hilarious. #linebreak I clawed through the dust for more than a day before I found what I was looking for: a hedron no larger than my head, intricately carved, and alive with power. It was the keystone in the hedron network I had created—just the thing to use to bind Ulamog and diminish its power. I looked upon it again with some amount of awe. There was room in my loathing of Nahiri to admire her genius. To create something of such power, and contain that power in an object that could survive for millennia or more! If Nahiri had not returned to help forestall Zendikar's destruction, it almost certainly meant she was dead. It made me a little sad, truly, that I would never get the chance to face her again. Well. That had been enough sentiment to last me another decade. Or, more likely, for the rest of my life. I ran a pulse of magic through two of the larger hedrons in my network, and they floated up above the sand, turning themselves slowly until they found alignment. From there, I activated the keystone and moved it slowly around the pair, feeling the push and pull of energy from the stones. Lithomancy was a subtle art, and though I knew I had only scratched the surface of it, it still offered me a versatility of magic that I had not known before. The basic function of a hedron is to redirect energy—but that simple function can be used to empower, summon, imprison, or destroy. #figure(image("013_At Any Cost/03.jpg", width: 100%), caption: [Lithomancer's Focus | Art by <NAME>], supplement: none, numbering: none) An image of weight, of gravity and distance, played out in my mind and body, and I strained to make sense of it. The location of the elf was easy enough to divine; empowered by the Heart, she stood out like the sun. But there was something else, a channeling of mana that seemed both abhorrent and familiar. They were close together; whatever it was, it was likely where the Zendikari would make their last stand. Tazeem. Sea Gate, if memory served. A lovely place for a slaughter. I unfurled my wings. Marvelous things, really, and I hadn't made much use of them. They made travel slightly more bearable, and made moving between Zendikar's continents much less of a chore. The skies offered a taste of freedom, but also served as a bitter reminder of what I had lost. The freedom of the skies is a vanishing mote of dust in the face of the freedom that the Multiverse once offered me. On the other hand, you don't see a lot of demons on boats, and it turns out there are some very good reasons for that. I flew along the coasts, preferring to avoid flying over open water, except as needed to reach Tazeem. The skies were largely devoid of life. With a keen eye, you could pick out some of Ulamog's floating spawn, but they were uninterested in me, and I in them. Birds were rare. Angels, thankfully, were all but gone. When the Eldrazi rose, the angels fought. Adorable, really. Not awful tacticians, if I'm being fair, but they labored under the misconception that it was a battle that they could win. The angels fought, and mostly, they died. Very rarely, you'd see one of Emrakul's lone spawn floating about, doing whatever her spawn do. But for the most part, the skies were mine. An open sky, a bright sun shining down on me, peaceful clouds drifting in the wind. And I felt them all as an oppressive weight, a confinement—that distant horizon was a claustrophobic nightmare. But soon that horizon would be gone. And one way or another, so would I.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) As I covered the miles on my approach to Sea Gate, it was clear that I was heading to the right place. On one side, there were endless wastes—Ulamog himself had carved a path to this place, leaving silence and dust in his wake. On the other, a ragged supply caravan wound its way through Tazeem. Refugees and fighters (though you couldn't really tell the difference between them) were swarming to the wall; the last stand of Zendikar was already underway. I could hear the roar of battle from miles away. Such a beautiful thing. But it was nothing compared to what I saw when I crested the wall. #figure(image("013_At Any Cost/04.jpg", width: 100%), caption: [Aligned Hedron Network | Art by <NAME>right], supplement: none, numbering: none) Armies clashing, spawn and Zendikari slaughtered by the thousands, and rising above it all, Ulamog. Trapped. In an enormous hedron network. I needed a moment to take it all in. I couldn't keep the grin off my face. The network was huge. The Zendikari had accomplished with brute force what had taken me decades to complete through care and subtlety. By using the gigantic, structural hedrons, they were able to tap into the energy of the entire #emph[plane] —my work with Khalni Heart was essentially a scale model of what they had done. The alignment was rough and amateurish, even by my dabbler's standards, but it was stable. Only a fool plans on luck, but it is a greater fool who fails to take advantage of it. Option one was back on the table. I found a good vantage point to study the network, gently displacing the kor sentries who had been using it as a lookout station. The network was straining to contain Ulamog, but the titan was starting to weaken as well. I was impressed. The Zendikari might have actually been able to kill it. Full marks for effort and inventiveness. But it was time to add a minor wrinkle to that plan. #figure(image("013_At Any Cost/05.jpg", width: 100%), caption: [Demon's Grasp | Art by David Gaillet], supplement: none, numbering: none) I flew up, high up above the fray. Kor on their kitesails spotted me at this point, but didn't engage—their attention was focused on holding back the spawn and relaying information to the battle below. The keystone hedron trailed behind me, and it began to react to the network's incredible energy. Its runes glowed with a violent light, overwhelmed by the leyline flow. I willed it into place, locked it into a harmonic point above the ring's precise center. It began to spin, a vortex of energy forming that sent a numbing electrical charge throughout my body. I faltered in the sky for a moment—my heart was pounding, and I could scarcely breathe. I had waited so long for this. So very long. I spoke three words. In that moment, everything began anew. The energy overwhelmed my senses: My vision flared to white, and I couldn't sense my body. The power burned through me, a rushing torrent of agony and perfection, and deep within my core, first as a glimmer, and then as a blazing flame, my spark. My spark returned. The Multiverse stretched out before me once more! I could feel the worlds, countless worlds, familiar and new, splayed out on an infinite canvas of realities. I felt them as pinpricks of light, beacons of power in the distance. The dream I'd had for millennia was finally at hand, I could leave this terrible place! I started to fade away, away to anywhere but here... No. I wasn't done here. Not yet. I tore myself out of the mana stream, power coursing through me. A snap of my fingers, and one of the structural hedrons fell out of alignment. The sheer force of the leylines held it in place for a moment longer, but then, achingly slowly, it tumbled to the world below. There were screams of terror and disbelief; Ulamog thrashed, and the rest of the network crumbled. And down, so far down below me, I caught sight of her. The little elf. She had to know what was happening, she had to have felt it in her bones. Yes. There. She looked up at me, a look composed of shock and utter, utter despair. That was a nice start. But I was far from done. One by one, I felt my connections to my old conquered worlds reappear. Not all of them, but enough. It had been so long. I let loose an enormous bolt of withering annihilation into the armies below, cutting off their retreat and forcing them back into Ulamog's path. The Zendikari were dying, hundreds each #emph[second] , and I could taste each life as it was snuffed out—crisp, juicy, and sweet. A pocket of order was forming in the ranks below. A few Planeswalkers were desperately trying to organize a retreat, not that there was anywhere meaningful for them to go. Head swimming with power, I wanted nothing more than to swoop down there and end them all—and I would—but I caught myself. Not yet. Not #emph[yet] . There was one last thing I needed to do first. Deep beneath the surface, it was already beginning to stir. I whispered to it, heedless of distance. I dared not focus my mind too directly on it—reality recoiled and splintered merely from my thoughts approaching. But the power was there, and power spoke to power. It did not have a consciousness, not in any sense I could describe, but it had a #emph[will] , and that will wanted nothing more than to be given purpose. #figure(image("013_At Any Cost/06.jpg", width: 100%), caption: [Ob Nixilis Reignited | Art by <NAME>], supplement: none, numbering: none) I laughed. I had not felt joy like this before, not ever. No triumph, no glory was greater than this. Beings of power... beings of power #emph[want to be called] ! With my spark reignited, it was the easiest thing in the world. One more word. One little word was all it took. The world shook as I said it. The doom of Zendikar was here at last. I reached out to the south and grasped it. Awakened it fully with the sheer force of my will. Mine would be the last word for this wretched plane, and I shouted it from the center of my soul. #strong["Rise!"]
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/align.typ
typst
// Test alignment. --- align-right --- // Test ragged-left. #set align(right) To the right! Where the sunlight peeks behind the mountain. --- align-in-stack --- #set page(height: 100pt) #stack(dir: ltr, align(left, square(size: 15pt, fill: eastern)), align(center, square(size: 20pt, fill: eastern)), align(right, square(size: 15pt, fill: eastern)), ) #align(center + horizon, rect(fill: eastern, height: 10pt)) #align(bottom, stack( align(center, rect(fill: conifer, height: 10pt)), rect(fill: forest, height: 10pt, width: 100%), )) --- align-center-in-flow --- // Test that multiple paragraphs in subflow also respect alignment. #align(center)[ Lorem Ipsum Dolor ] --- align-start-and-end --- // Test start and end alignment. #rotate(-30deg, origin: end + horizon)[Hello] #set text(lang: "de") #align(start)[Start] #align(end)[Ende] #set text(lang: "ar") #align(start)[يبدأ] #align(end)[نهاية] --- alignment-fields-x --- // Test 2d alignment 'horizontal' field. #test((start + top).x, start) #test((end + top).x, end) #test((left + top).x, left) #test((right + top).x, right) #test((center + top).x, center) #test((start + bottom).x, start) #test((end + bottom).x, end) #test((left + bottom).x, left) #test((right + bottom).x, right) #test((center + bottom).x, center) #test((start + horizon).x, start) #test((end + horizon).x, end) #test((left + horizon).x, left) #test((right + horizon).x, right) #test((center + horizon).x, center) #test((top + start).x, start) #test((bottom + end).x, end) #test((horizon + center).x, center) --- alignment-fields-y --- // Test 2d alignment 'vertical' field. #test((start + top).y, top) #test((end + top).y, top) #test((left + top).y, top) #test((right + top).y, top) #test((center + top).y, top) #test((start + bottom).y, bottom) #test((end + bottom).y, bottom) #test((left + bottom).y, bottom) #test((right + bottom).y, bottom) #test((center + bottom).y, bottom) #test((start + horizon).y, horizon) #test((end + horizon).y, horizon) #test((left + horizon).y, horizon) #test((right + horizon).y, horizon) #test((center + horizon).y, horizon) #test((top + start).y, top) #test((bottom + end).y, bottom) #test((horizon + center).y, horizon) --- alignment-type --- #test(type(center), alignment) #test(type(horizon), alignment) #test(type(center + horizon), alignment) --- alignment-axis --- // Test alignment methods. #test(start.axis(), "horizontal") #test(end.axis(), "horizontal") #test(left.axis(), "horizontal") #test(right.axis(), "horizontal") #test(center.axis(), "horizontal") #test(top.axis(), "vertical") #test(bottom.axis(), "vertical") #test(horizon.axis(), "vertical") --- alignment-inv --- #test(start.inv(), end) #test(end.inv(), start) #test(left.inv(), right) #test(right.inv(), left) #test(center.inv(), center) #test(top.inv(), bottom) #test(bottom.inv(), top) #test(horizon.inv(), horizon) #test((start + top).inv(), (end + bottom)) #test((end + top).inv(), (start + bottom)) #test((left + top).inv(), (right + bottom)) #test((right + top).inv(), (left + bottom)) #test((center + top).inv(), (center + bottom)) #test((start + bottom).inv(), (end + top)) #test((end + bottom).inv(), (start + top)) #test((left + bottom).inv(), (right + top)) #test((right + bottom).inv(), (left + top)) #test((center + bottom).inv(), (center + top)) #test((start + horizon).inv(), (end + horizon)) #test((end + horizon).inv(), (start + horizon)) #test((left + horizon).inv(), (right + horizon)) #test((right + horizon).inv(), (left + horizon)) #test((center + horizon).inv(), (center + horizon)) #test((top + start).inv(), (end + bottom)) #test((bottom + end).inv(), (start + top)) #test((horizon + center).inv(), (center + horizon)) --- alignment-add-two-horizontal --- // Error: 8-22 cannot add two horizontal alignments #align(center + right, [A]) --- alignment-add-two-vertical --- // Error: 8-20 cannot add two vertical alignments #align(top + bottom, [A]) --- alignment-add-vertical-and-2d --- // Error: 8-30 cannot add a vertical and a 2D alignment #align(top + (bottom + right), [A]) --- issue-1398-line-align --- // Test right-aligning a line and a rectangle. #align(right, line(length: 30%)) #align(right, rect()) --- issue-2213-align-fr --- // Test a mix of alignment and fr units (fr wins). #set page(height: 80pt) A #v(1fr) B #align(bottom + right)[C]
https://github.com/antonWetzel/Masterarbeit
https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/analyse.typ
typst
#import "setup.typ": * = Analyse von Bäumen Die charakteristischen Eigenschaften werden für jeden Baum einzeln berechnet. Für jeden Punkt im Baum wird zuerst die relative Höhe, lokale Krümmung und zugehörige horizontale Ausdehnung bestimmt. Mit diesen Daten wird dann eine Unterteilung in Boden, Stamm und Krone durchgeführt. Ein Beispiel für die Ergebnisse sind in @analyse_eigenschaften zu sehen. #figure(caption: [Baum eingefärbt mit den berechneten Eigenschaften.], grid( columns: 1 * 4, column-gutter: 1em, subfigure(image("../images/crop/prop_height.png"), caption: [Höhe]), subfigure(image("../images/crop/prop_curve_all.png"), caption: [Krümmung]), subfigure(image("../images/crop/prop_var_all.png"), caption: [Ausdehnung]), subfigure(image("../images/crop/prop_classification.png"), caption: [Klassifikation]), )) <analyse_eigenschaften> == Eingabedaten Die Punkte sind als Liste der Länge $n$ gegeben. Für den Punkt $i in NN_0^(n-1)$ ist nur die globale Position $p_i = (p_(i x), p_(i y), p_(i z))$ bekannt. Die Punkte sind dabei ungeordnet, wodurch aufeinanderfolgende Punkte in der Liste weit voneinander entfernte Positionen haben können. == Punkteigenschaften Um einen Punkt $i$ zu analysieren, wird die zugehörige Nachbarschaft $N_i$ benötigt. Die Nachbarschaft enthält dabei die nächsten Punkte nach Abstand sortiert. Dafür wird mit den Punkten ein KD-Baum erstellt. Mit diesem können effizient für eine Position $p_i$ und ein beliebiges $k in NN$ die $k$-nächsten Punkte bestimmt werden. Die Konstruktion und Verwendung vom KD-Baum wird in @kd_baum erklärt. In der Nachbarschaft ist dann $N_0$ der momentane Punkt $i$, $N_1$ der nächste Punkt und $N_(k-1)$ der $k-1$ nächste Punkt. === Relative Höhe Für jeden Punkt wird die relative Höhe im Segment bestimmt. Dafür wird zuerst mit allen Positionen die Mindesthöhe $h_min$ und Maximalhöhe $h_max$ bestimmt. $ h_min = min_(i in NN_0^(n-1))p_(i y) #h(40pt) h_max = max_(i in NN_0^(n-1))p_(i y) $ Mit der Mindest- und Maximalhöhe kann für den Punkt $i$ die relative Höhe $h_i$ bestimmt werden. $ h_i = (p_(i y) - h_min) / (h_max - h_min) $ Die relative Höhe liegt immer im Bereich $[0; 1]$ und wird größer, je höher der Punkt liegt. === Krümmung Die Krümmung der ursprünglichen abgetasteten Oberfläche wird für jeden Punkt geschätzt. Dafür wird für den Punkt $i$ die Verteilung der umliegenden Punkte $N_i$ betrachtet. Zuerst wird für die Nachbarschaft der geometrische Schwerpunkt $s_i$ bestimmt. $ s_i = 1 / k dot sum_(j in N_i) p_j $ Mit dem Schwerpunkte kann die Kovarianzmatrix $C_i$ bestimmt werden. // prettypst: disable #{ set math.mat(column-gap: 0.5cm) $ C_i = 1 / k dot sum_(j in N_i) mat( (p_(j x) - s_(i x))^2, (p_(j x) - s_(i x)) dot (p_(j y) - s_(i y)), (p_(j x) - s_(i x)) dot (p_(j z) - s_(i z)); (p_(j y) - s_(i y)) dot (p_(j x) - s_(i x)), (p_(j y) - s_(i y))^2, (p_(j y) - s_(i y)) dot (p_(j z) - s_(i z)); (p_(j z) - s_(i z)) dot (p_(j x) - s_(i x)), (p_(j z) - s_(i z)) dot (p_(j y) - s_(i y)), (p_(j z) - s_(i z))^2; ) $ } // prettypst: enable Ohne die Verschiebung um $s_i$ würde die globale Position der Punkte die Kovarianzmatrix beeinflussen. Von der Kovarianzmatrix werden die Eigenwerte und zugehörige Eigenvektoren bestimmt. Die normierten Eigenvektoren $v_(i alpha)$ mit $alpha in {0, 1, 2}$ bilden eine Orthonormalbasis und der zugehörige Eigenwert $lambda_(i alpha)$ für $v_(i alpha)$ ist die Ausdehnung der Punkte entlang des Basisvektors. Der kleinste Eigenwert gehört zur Dimension mit der geringsten Ausdehnung. Je kleiner der kleinste Eigenwert, desto näher liegen die Punkte in der Nachbarschaft an der Ebene aufgespannt durch die anderen beiden Eigenvektoren. Ein Beispiel für Eigenvektoren im zweidimensionalen ist in @analyse_eigenvektoren gegeben. Die Länge der Vektoren ist anhängig vom zugehörigen Eigenwert und die Ausdehnung der Punkte ist am geringsten Entlang des kleinsten Eigenvektors. #let numbers = ( (0.4855, -0.6487), (0.3659, -0.2336), (-0.2306, 0.4376), (0.6910, -0.3798), (0.1949, -0.8047), (-0.0356, 0.8813), (-0.1612, 0.6089), (-0.5485, -0.2536), (0.0358, -0.5869), (0.4356, 0.4279), (0.7246, 0.2678), (-0.5915, -0.7436), (0.5475, -0.7034), (-0.0222, 0.1034), (-0.4046, 0.2089), (0.3141, -0.8417), (0.7025, -0.1088), (-0.3285, 0.8300), (-0.0354, -0.0361), (0.4030, -0.0194), (0.4539, -0.0164), (0.4572, -0.7717), (-0.2935, 0.3223), (0.9009, -0.1449), (0.7847, 0.1091), (0.6713, -0.1648), (0.3486, 0.6795), (-0.1179, -0.4614), (-0.3916, -0.7057), (-0.3888, 0.1888), (-0.0683, 0.2466), (-0.5469, -0.3778), (-0.6345, 0.1398), (0.0890, -0.3881), (0.8525, -0.4541), (-0.5835, -0.0581), (-0.8216, 0.2838), (-0.0144, 0.0659), (0.2945, -0.7860), (-0.7919, -0.3148), (-0.5017, 0.6025), (-0.9352, 0.1064), (0.5355, 0.0521), (0.3187, 0.4207), (0.2212, 0.2391), (-0.5832, 0.4985), (-0.3192, -0.7679), (-0.2470, 0.0340), (0.9310, 0.3424), (-0.2747, 0.1090), ) #let test(sec_scale) = cetz.canvas(length: 2cm, { import cetz.draw: *; set-style(stroke: black) line((0, 0), (2, 0), mark: (end: ">", fill: black)) line((0, 0), (0, 2), mark: (end: ">", fill: black)) content((2, 0), anchor: "west", padding: 0.1, $x$) content((0, 2), anchor: "east", padding: 0.1, $y$) let a_0 = (0.8, 0.5) let a_1 = (-0.125 * sec_scale, 0.2 * sec_scale) for (x, y) in numbers { let c_x = 1.0 + x * a_0.at(0) + y * a_1.at(0) let c_y = 1.0 + x * a_0.at(1) + y * a_1.at(1) circle((c_x, c_y), radius: 0.03, fill: black, stroke: none) } let s = 1.5 let e_0 = (1 + a_0.at(0) * s * 0.9, 1 + a_0.at(1) * s * 0.9) let e_1 = (1 + a_1.at(0) * s * 0.9, 1 + a_1.at(1) * s * 0.9) line((1, 1), e_0, mark: (end: ">", fill: black)) line((1, 1), e_1, mark: (end: ">", fill: black)) content(e_0, anchor: "north", padding: 0.1, $v_0$) content(e_1, anchor: "south", padding: 0.1, $v_1$) }) #figure( caption: [Eigenwerte und zugehörige Eigenvektoren.], grid( columns: 2, subfigure(test(1.0), caption: $lambda_0 = 4 lambda_1$), subfigure(test(2.0), caption: $lambda_0 = 2 lambda_1$), ), ) <analyse_eigenvektoren> Mit den Eigenwerten $lambda_(i alpha)$ absteigend nach größer sortiert wird die Krümmung $c_i$ berechnet. $ c_i = (3 lambda_(i 2)) / (lambda_(i 0) + lambda_(i 1) + lambda_(i 2)) $ $c_i$ liegt dabei im abgeschlossenen Bereich $[0; 1]$, weil $0 <= lambda_(i 0) <= lambda_(i 1) <= lambda_(i 2)$ ist. === Eigenschaften für die Visualisierung <eigenschaften_visualisierung> Für die Visualisierung wird die Position, Orientierung und Größe von jedem Punkt benötigt. Die Position ist in den Eingabedaten gegeben und die anderen Eigenschaften werden mit der lokalen Umgebung vom Punkt berechnet. In @analyse_render ist ein Beispiel gegeben. Die dichteren Punkte beim Stamm sind kleiner als die umliegenden Punkte und die Orientierung ändert sich beim Übergang vom Stamm zum Boden. #figure( caption: [ Ausschnitt von einer Punktwolke. ], rect(image("../images/auto-crop/properties.png", height: 30%), inset: 0.5pt), ) <analyse_render> Für die Orientierung wird die Normale bestimmt, welche orthogonal zur geschätzten zugehörigen Oberfläche vom Punkt ist. Dafür werden wieder die Eigenvektoren der Kovarianzmatrix verwendet. Der Eigenvektor, welcher zum kleinsten Eigenwert gehört, ist dabei orthogonal zur geschätzten Ebene mit der größten Ausdehnung. Für die Punktgröße wird der durchschnittliche Abstand zu den umliegenden Punkten bestimmt. Dadurch werden die Punkte in Bereichen mit hoher Punktdichte kleiner. == Baumeigenschaften Für den Baum wird die Gesamthöhe und jeweils die Höhe und den Durchmesser vom Stamm und der Krone gesucht. Dafür werden die Punkte in Scheiben unterteilt, diese dem Boden, Stamm oder Krone zugeordnet und dann wird mit den Scheiben die gesuchten Werte berechnet. Die einstellbaren Parameter dafür sind in @analyse_klassifkation_parameter gelistet. #figure( caption: [Parameter für die Klassifikation.], table( columns: (auto, 1fr), align: (x, y) => if y == 0 { center } else { (center, left).at(x) }, [*Name*], [*Funktion*], $w$, [Breite von einer Scheibe], $h_g$, [Maximale Suchhöhe für den Boden], $s_g$, [Skalierungsfaktor für die Mindestfläche vom Boden], $h_t$, [Höhe für die Berechnung vom Stammdurchmesser], $r_t$, [Bereich für die Berechnung vom Stammdurchmesser], $d_c$, [Differenz zwischen den Stammdurchmesser und dem Mindestdurchmesser der Krone], ), ) <analyse_klassifkation_parameter> === Unterteilung in Scheiben Zuerst werden die Punkte in gleich breite Scheiben unterteilt. Dafür wird mit der Breite $w$, $h_min$ und $h_max$ die Anzahl der benötigten Scheiben $c$ und für jeden Punkt $i$ der Index $s_i$ der zugehörigen Scheibe berechnet. $ c = floor((h_max - h_min) / w) + 1 #h(40pt) s_i = floor((p_(i y) - h_min) / w) $ Für jede Scheibe wird der horizontale konvexe Bereich bestimmt, der alle Punkte in der Scheibe beinhaltet. Dafür werden die Methoden wie bei der Segmentierung in @segmentierung_bereiche_chapter verwendet. Mit den Bereichen wird die Fläche bestimmt, welche von den Punkten in der Scheibe belegt wird. In @analyse_klassifkation_slices ist ein Beispiel gegeben. #figure( caption: [Baum in Scheiben unterteilt mit der zugehörigen Fläche für jede Scheibe.], image("../images/klassifkation_slices.svg"), ) <analyse_klassifkation_slices> === Bodenhöhe Mit den Flächen wird zuerst die kleinste Fläche $a_min$ und die größte Fläche $a_max$ bestimmt. Danach wird die Bodenhöhe $g$ gesucht. Dafür werden die Suchhöhe $h_g$ und der Skalierungsfaktor $s_g$ verwendet. Von unten wird die erste Scheibe gesucht, welche eine größere Fläche als $s_g dot a_min$ hat. Ist die Scheibe höher als $h_g$, wird die Höhe der untersten Scheibe als Boden verwendet. Ist die Scheibe niedriger als $h_g$, wird die nächste Scheibe gesucht, dessen Fläche kleiner als $s_g dot a_min$ ist, und die Höhe von dieser Scheibe wird als $g$ verwendet. === Stammdurchmesser Mit der berechneten Bodenhöhe $g$, der Messhöhe $h_t$ und dem Bereich $r_t$ wird der Stammdurchmesser $d_t$ bestimmt. Zuerst werden alle Punkte bestimmt, bei denen die Höhe im Bereich $[g + h_t - r_t / 2, g + h_t + r_t / 2)$ liegt. Mit dem MSAC-Algorithmus#footnote([#strong[m]-estimator #strong[sa]mple #strong[c]onsensus]) wird der Kreis gesucht, welcher am besten die Punkte beschreibt. Beim MSAC-Algorithmus werden wiederholt genug zufällige Datenpunkte ausgewählt, dass aus diesen der gewünschte Wert eindeutig berechnet werden kann. Danach wird für jeden Datenpunkt die Abweichung zum Wert bestimmt. Die Abweichung wird auf einen Maximalwert beschränkt, um den Einfluss von weit entfernten Datenpunkten zu verringern. Die Summe von allen Abweichungen ist der Fehler für den momentanen Wert. Der Wert mit dem geringsten Fehler wird als das finale Ergebnis verwendet @msac. Am Anfang wird als Durchmesser der Standardwert #number(0.5) m und als kleinster Fehler unendlich verwendet. Dann werden wiederholt drei zufällige Punkte ausgewählt, mit denen das Zentrum und der Durchmesser vom zugehörige Kreis eindeutig berechnet werden kann. Der summierte Abstand von allen Punkten zum Kreis wird als Fehler berechnet. Um den Effekt von Datenpunkten zu verringern, welche nicht zum Stamm gehören wird die Abweichung auf #number(0.2) m beschränkt. Ist der momentane Fehler kleiner als der bisher kleinste Fehler, wird der Durchmesser als neuen besten Wert verwendet und der kleinste Fehler wird aktualisiert. Nach allen Iterationen wird der Durchmesser vom besten Kreis als der geschätzte Stammdurchmesser verwendet. === Baumhöhe Mit dem Stammdurchmesser $d_t$ und der Mindestdifferenz $d_c$ wird die Höhe vom Anfang der Krone bestimmt. Dafür wird die Scheibe gesucht, dessen Durchmesser $d_c$ größer als $d_t + d_c$ ist. Die zugehörige geschätzte Mindestfläche $a_m$ kann abhängig vom Durchmesser geschätzt werden. $ a_m = pi dot ((d_t + d_c) / 2)^2 $ Danach wird die erste Scheibe höher als der Boden gesucht, dessen Fläche größer als $a_m$ ist und die zugehörige Höhe $h_c$ als Anfang der Krone verwendet. Der Baum geht vom Boden bis zur höchsten Scheibe, der Stamm vom Boden bis $h_c$ und die Krone von $h_c$ bis zur höchsten Scheibe. === Durchmesser von der Baumkrone Für den Durchmesser von der Baumkrone wird für alle Scheiben in der Krone die Scheibe mit der größten Fläche $a_c$ gesucht. Mit der Fläche wird der zugehörige Durchmesser $d_c$ geschätzt. $ d_c = 2 dot sqrt(a_c / pi) $
https://github.com/astrale-sharp/typst-assignement-template
https://raw.githubusercontent.com/astrale-sharp/typst-assignement-template/main/libs/science.typ
typst
MIT License
#let display_float(f, digits: 4) = { let exp = calc.floor(calc.log(f)) let div = if exp < 0 {1/calc.pow(10, -exp)} else {calc.pow(10, exp)} let mant = f / div let mant = calc.round(mant, digits: digits) [$#mant times 10^#exp $] } #display_float(9000,digits : 1) #display_float(0.01, digits : 4) #display_float(10.001 ,digits : 4) #display_float(7) #display_float(450, digits : 0) #display_float(7.1234, digits : 2)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/041%20-%20Kaldheim/007_Episode%204%3A%20Into%20the%20Demons'%20Realm.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 4: Into the Demons' Realm", set_name: "Kaldheim", story_date: datetime(day: 27, month: 01, year: 2021), author: "<NAME> & <NAME>", doc ) For once in her time on Kaldheim, Kaya didn't need to worry about the cold. On the other side of Tyvar's Omenpath, a blast of hot, noxious air had greeted her. The sky was the first thing she saw: rolling dark clouds without the memory of a sun. The only light to be found came from the red thunderbolts that occasionally split the sky and the orange glow rising from somewhere below them. Kaya stood with Tyvar at the top of a ridge of black, jagged rock. Over the lip, she could see a tarry morass spiderwebbed with smoldering orange ruptures, a vast expanse of lava whose surface had partially hardened into great chunks of black pumice floating on molten rock. Now and then, a pocket of lava would burst into a molten geyser, sending glowing chunks of lava spattering into the air. It was hard to imagine somewhere less hospitable to life—and yet, Tyvar seemed to look at the apocalyptic vista with nothing short of wonder. "We made it," he said. "I wasn't sure we could." "What's that supposed to mean?" asked Kaya. "The gods sealed this place long ago, after Varragoth first escaped, with powerful runes of warding. I've never opened an Omenpath here—no elf has. But Tibalt must have somehow damaged the wards." #emph[That sword.] It hadn't been any kind of magic she'd seen before—nothing like the portal Alrund had opened. "We've got to get that sword away from him. If he can rip open the doors to this place, who knows what else he can do with it?" Tyvar pointed behind her. She turned, hand automatically reaching for her dagger—and finding, she remembered a moment later, nothing. It wasn't a threat he was pointing out, anyway. Down on the partially cooled surface of the magma lake, a few oddly straight lines were carved out of the web of volcanic ruptures. After a moment, her eyes adjusted to the low light, and she saw what had been carved into the basalt, waiting for their arrival: an orange molten arrow. "Well, among the many things Tibalt's been accused of, subtlety's not one of them," muttered Kaya. In an easy, almost practiced motion, Tyvar hopped over the lip of the ridge. He kicked off a spire of rock, then slid down a slope of glassy gravel. His momentum stopped just in front of the magma flats, where he looked back up at her. "Coming?" #figure(image("007_Episode 4: Into the Demons' Realm/01.jpg", width: 100%), caption: [Immersturm Skullcairn | Art by: <NAME>], supplement: none, numbering: none) Fun as it would have been to hop between lily pads of cooled stone, Kaya didn't feel like taking a dunk into lava if she missed a jump. Apparently, neither did Tyvar; once she'd gotten down to the edge of the lake, he'd pressed his fingertips into the blackened shore and closed his eyes. "Hang on," he said. "I want to try something." Across the magma, the basalt shore began to creep out. The stone didn't just expand or double up on itself, either—it seemed to #emph[grow] , tendrils of rock twining together, knitting themselves into a bridge. When he opened his eyes, Tyvar seemed just as surprised as she was. She stepped gingerly onto it. It was subtly ridged, latticed in places in a way she didn't think stone was naturally capable of. It was, she found herself thinking, oddly beautiful. #emph[First, he turns those trolls to stone, now this. The kid's a transmuter. ] But that wasn't all he was. Somehow, Tyvar had sparked without realizing it—gone all the way to Zendikar, just thinking it was another of Kaldheim's realms. Back in Gnottvold, when he'd opened that Omenpath, Tyvar had made it clear that he was going in whether or not she was coming with him. If he was just another headstrong hero intent on some glorious death, Kaya would have let him go—after all, Kaldheim had no shortage of those, and she had work to do. But Tyvar was a planeswalker, and one who didn't know what that really meant. Somehow, it seemed like a waste to let Tibalt kill him before he'd seen more of the Multiverse. She tried to tell him a bit about it all as they walked. "These planes are like the realms, then? And connecting them—an even vaster World Tree?" he said. "Well, without the literal branches. And no giant animals in the spaces between." At least as far as she knew. "More importantly, they're not connected in the same way. Portals don't just show up, and there aren't spells for crossing between them. The only way to move from one to the other is to be one of us." "A planeswalker," said Tyvar, kicking a hunk of blackened pumice off into the lava. "A fine offer. But I think I'll pass. There's glory aplenty for me in Kaldheim, and more realms than I could explore in one lifetime. Besides, how would people know to tell stories about me if I left the World Tree altogether? I'd have to start anew each time." #emph[Yeah] , thought Kaya. #emph[That's the tricky part. ] New friends, new enemies, new rules to every plane. Always the stranger, the newcomer. Dropped again and again into other people's squabbles, other people's wars. It was exciting, at first. Then, after a while, it got exhausting. But, like it or not, it wasn't a choice. Kaya grabbed him by the shoulder and spun him around. "You don't get to pass, kid. That's not how this works. You're a planeswalker, whether you like it or not, and next time you wind up somewhere full of magic, monsters, and people you don't understand, you'll need"—she scrambled for words—"you'll need some kind of code. A set of rules." Kaya's code was simple: do no harm~unless they had it coming and somebody's paying you for the privilege. Sure, once or twice she'd gotten mixed up in messes she should have stayed out of; now and then, if she was feeling charitable, she'd off a particularly troublesome ghost pro bono. But the code was important—it was the only thing that followed her from plane to plane, the only thing she could count on. What would Tyvar be able to count on when he moved on from Kaldheim one day? What glory or heroic tales would matter then? Tyvar pulled his arm free, his annoyance plain as day on those chiseled yet somehow boyish features. "I have a code—the same one passed down by the warriors of Skemfar for untold generations. I'm in no need of a stranger's schooling on such things." "I'm just trying to help you!" she said. Nobody had ever done that for her and look how she had ended up. Mercenary, thief, killer. Tibalt was in no position to accuse her of anything—but he'd been right. "I am not a child, and I don't need your help. As I've demonstrated, I'm more than capable of handling myself." With that, he stormed off, down the path of black rock. #emph[Stubborn fool.] Why was she even still here? She had other paying work on Kaldheim, after all. A monster she was supposed to be tracking down. She was still deciding whether to turn around when the first harpoon cracked into the blackened path, inches from Tyvar's foot. It was a crude weapon, rough iron ringed in barbs, and heavy enough to sink straight into rock. For an instant, Tyvar seemed too stunned to move—and he didn't notice the second one screaming toward him. Kaya reached him just in time, turning his torso to ghostly light just as the iron harpoon whistled through him. He stumbled back, planted one hand on the path, and turned his arms charcoal black. "On our right!" snapped Kaya. Cutting a path toward them, through the chunks of cooled magma, was—improbably—a ship. It reminded her of the longships the Omenseekers had piloted, but while those were sleek and narrow, meant to slip into narrow channels and explore remote coves, this vessel was meant for only one thing. Spikes ringed the outer edge, cruel and narrow; the prow was an iron wedge with a chipped, battering edge. In place of sails, a sheet of flame seemed to billow and catch whatever unearthly current was pushing them closer. "Demons," said Tyvar. "Ready yourself." #figure(image("007_Episode 4: Into the Demons' Realm/02.jpg", width: 100%), caption: [Demon Berserker Token | Art by: <NAME>], supplement: none, numbering: none) As the ship drew nearer, Kaya could make out three figures on board. On one, an iron helmet added rows of horns to the two that naturally curled from his forehead; a black visor concealed his eyes. Another had one hand replaced by a massive flanged mace, the ridges crusted over with blood. Near the prow, on an elevated platform, was the biggest—a thickly built brute with his right side covered in black iron plates. The membranes of his great wings were rent and torn from past skirmishes. With his left hand, he hefted another harpoon, leaning back for the throw. This one, Tyvar was prepared for. With a dancer's timing, he swiped his blackened arm across the path of the harpoon, knocking it into the magma. "We need to close the distance," he said. Kaya grimaced. "Actually, I don't think that's our problem." The ship was only picking up speed, the fiery sails stoked into furnace-hot gusts. Two of the demons, the smaller ones, spread their wings and dragged themselves into the air with great, eager flaps. They didn't mean to just pull up alongside them. "Look out!" shouted Kaya. She dodged to one side of the path Tyvar had built them; he dodged to the other. Then that ramming edge along the prow smashed into it, scattering basalt and cinders into the air. Kaya rolled to her feet in time to see the one with the mace hand swooping out of the sky toward her. He brought the weapon down in a colossal diving blow that smashed a dimple into the volcanic pack where Kaya had been standing a moment before. Before he could pull his arm back, she stamped down on the flanges and phased it partially into the stone. He bellowed and grabbed for her, but she slipped free of his grasp like smoke, hop-stepping back to the harpoon still embedded in the rock. It wasn't hard for her to wrench it free—phasing it here and there did the trick—but the weight of it nearly tipped her into the magma lake. While she struggled with both hands to heft the heavy iron pole, the demon beat his wings furiously, heaving and pulling at the volcanic rock enclosing his arm. With a little concentration, Kaya turned the harpoon entirely immaterial, then threw. When it left her hand, it went from weightless, insubstantial, to suddenly every bit as heavy and lethal as before—and traveling at a much higher speed. It punched clean through the demon's hammered breastplate and out the other side. The demon thrashed in place for a moment, the mace on his arm still melded with the ground, before collapsing. Kaya allowed herself a moment to exhale, then started forward. Planting one foot on the armor encasing the demon's back, she vaulted up onto the deck of the longship. On the other side, she could see Tyvar flanked. The demon with the horned helmet was chopping at him furiously with a pair of short cleavers lined with wicked, serrated teeth, and the big one she'd seen with his body half-encased in metal kept him penned in with great sweeps from a spiked hammer. Just one blow from that looked sufficient to take the elf's head off—but so far, Tyvar had managed to stay just ahead of every swing. His arms, she noticed, were no longer the rough black of basalt. Now they were a molten, glowing orange, as if he'd heated them in a forge. Each time he batted away a cleaver blow, embers scattered and winked out into the air. He was quick, strong, and skilled, there was no doubt about that. But he couldn't keep this up forever. She ducked under the flame sail, shielding her face from the heat with one hand, and took a running leap off the side, landing with a less-than-graceful flop across the big demon's back. He was twice her height, probably more than twice her weight, and barely leaned forward at the impact, but she managed to secure a hold around his neck. With a thought, she wreathed her hand in that eerie light and straightened her fingers into a spear. #emph[Quick jab through the heart. Flicker out of phase, and extract. Won't be comfortable, but it'll get the job done.] As the demon groped awkwardly around his back trying to reach her, Kaya jabbed her hand just to the left of the spine, rematerializing for an instant— And nearly blacked out from the pain. It was #emph[burning ] inside the demon, like sticking her hand in a furnace. She lost her grip on the demon's neck and tumbled off down onto the rough black stone beneath. The demon shuddered, fell to one knee—then pushed himself to standing using the handle of that massive war hammer as a brace. He turned toward her, tiny red eyes smoldering with rage. From his mouth poured a thick black bile that bubbled and steamed. She'd hurt him, but not enough. Her hand had only been material for a fraction of a second, yet she could still feel the pain, white-hot and absolute. But pain, like so many things, was a tool. A tool Kaya knew how to use. #emph[Focus on it. Use it.] From somewhere deep inside her, Kaya felt an icy chill welling up. The demon raised his hammer, the great muscles working to lift the massive thing, boiling blood still spilling from his mouth. That's when Kaya phased the rocky path beneath him into empty air. The demon's wings shot out on reflex, trying to rebalance, to keep himself aloft. It might have worked, if not for the holes and tears that pocked their leathery surface, or the great hammer hanging above him. He started roaring the moment his legs sunk into the lava—he fell forward, dropping the hammer, clawing for purchase on the rough black stone still making up the part of the path Kaya stood on. With a sharp kick, she sent him flailing backwards into the molten rock and allowed the path to rematerialize over him. Across the path, Tyvar's battle with the remaining demon raged on; with only one opponent, the elf was on the offensive. The brass knife affixed to his bracer had grown longer now, glowing orange with the same volcanic heat that covered his arms. With a snapping stroke that left heat shimmers through the air, he chopped straight through one of the demon's cleavers; his next slash passed through its neck. She heard a sizzling sound, smelled something worse than burning hair, and then the demon's helmed head bounced once off the basalt and into the lava while the body sagged onto the path of black rock. The fight was done. Kaya's hand still throbbed awfully despite the spell she'd used to fix the worst of it. She'd never had much of a knack for healing magic. It would likely be days before she had a full range of motion in it again. "That was amazing!" said Tyvar. "Yeah, yeah," said Kaya. "I saw what you—" "That jarl was twice your size! Do you know how many humans, in all the sagas I've known, have slain a demon? Assuming you didn't talk things through with the other one, you bested #emph[two] ! And without a weapon! The skalds #emph[must ] hear about this. I'll tell them myself, when we're finished!" "Uh, thanks," said Kaya, caught off guard. #emph[So the kid can share glory. ] "If we plan on doing this again, though, I'd prefer to be armed." Something seemed to dawn on Tyvar, then. "Of course. Allow me." He stooped over the massive hammer the demon jarl had dropped before going into the magma. Kaya was about to protest—#emph[a bit heavy for me, not really my style] —when Tyvar pushed his fingers into the black iron of the hammerhead as if it were mud. From it, he pulled two fistfuls of metal: one he dropped to the path where it clinked dully against the rock. The other nugget he held up and squinted at. "Terrible quality. But we can do something about that." He pressed both hands around it and squeezed, the muscles along his arms and shoulders going taut. When his palms came apart, he was holding a small oval, rough in parts like the pit of a fruit. He knelt over and pushed it into the basalt, which took some doing. Afterwards, he did the same with the other nugget. Kaya watched, mystified, as he scooped broken, charcoal-colored earth into a little mound over each. "What are you doing?" "Everything has the potential to grow," said Tyvar, straightening back up. "Trees, people—we expect it from them. But earth and stone, too, given time, and patience. Or, failing that, a bit of magic. I told you my abilities work differently in each realm I pass through. I figured in a place as lifeless as this, anything would be desperate to grow. Even metal. And I was right," he said, grinning. She'd never heard of transmutation like this. "What about back in Gnottvold? What you did to those trolls?" He waved his hand dismissively. "Easy. Torga trolls are creatures of the earth—they spend years at a time as little more than boulders, gathering moss. They're not far from stone as is. I only coaxed them a bit closer to that shape." Then, before her eyes, something poked up out of the ground. A sprout—the same dark iron color that the oval had been, but curling, unfurling. Then another, from the other mound. Kaya watched as they grew taller and thicker, as they sprouted tendrils that wove together into braiding latticework. When the top folded over the rest, falling in a D-shaped curve, she realized what she was looking at: a hand-axe. Two, actually. Grown from the ground, like stalks of wheat. Tyvar reached over and pulled them from the rock—twisting as he did so, as if snapping off a root. Then he handed them to her, handle first. "You like them fast and light. Is that right?" Warily, she took one. The whole thing was made of the same material—no rust, no blood, no imperfections, just cold gray metal. The head of the axe, with those ornate knotwork patterns grown into it, was a lighter color than the handle. Somehow the grip was rougher, in a way that felt like it wouldn't slip from her hands. She flipped it into the air, everything rotating around a point just below the axe head, and caught it again. Well-balanced, for something that popped out of the ground. "Thanks," she said, tucking the axe and its sister into her belt. Tyvar slapped her shoulder and grinned. "I'm certain you'll put them to good use. Now, we have a villain to catch. Shall we continue?" "Actually," said Kaya, glancing back at where the demon longship was wedged into the black stone path. "I've got a better idea." #figure(image("007_Episode 4: Into the Demons' Realm/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) As vessels went, Kaya had much preferred Cosima's longship. On top of its uncanny ability to take one wherever they needed to go, there was no chance of impaling herself along the gunwale or setting her hair on fire adjusting the boom. Luckily, Tyvar seemed to have a bit more experience sailing than she did, and once the demon ship built up speed, it smashed through the plates of cooled magma floating on the lava's surface without so much as a judder. The elf worked the sails while she kept watch from the prow. "There," she said, pointing ahead of them. Rising above an ash-gray plain was a vast, dark mountain. Where the peak should have been was a jagged, open cone that nearly brushed the roiling clouds above. At the top, Kaya could make out a strange light. It seemed to distort the air around it like shimmers of heat, occasionally sending a rippling ribbon of uncanny blue or green streaking into the sky. Where had she seen that light before? #emph[Alrund.] In Kaldheim, that was the light of the gods. But it was the same light she'd seen at the fringes of the portal Tibalt had carved open. Tyvar shifted the rudder, angling the ship toward the mountain. "That's the Bloodcrag! I never thought I'd actually get to see it." "Great. Perfect. Bloodcrag." Briefly, she considered if it wasn't too late to turn this boat around. Nobody was paying her for Tibalt's head, after all. #emph[But that horned bastard has so many enemies, I could probably find a buyer. Chandra, maybe.] They left the longship beached along the slagged shore of the lava lake. Scaling the mountain, at least, wouldn't be the hard part. Shaped into the rock were a set of ancient stairs. They were worn with age and slightly too large for Kaya or Tyvar to climb comfortably—carved into this place many millennia ago for the bloodthirsty inhabitants of Immersturm, not for elves or humans—but they were manageable. Partway up, something caught her eye. Movement below them, on the magma lake. Kaya paused, her back to one of the huge and faintly warm steps. Across the surface of the lake, between the occasional flare of erupting lava, iron ships cut through the black, each one topped with a flickering curtain of flame in the shape of a sail. It was too far for her to make out any figures—from here, even the grim vessels looked like something she might find in a toy shop—but over the lash of wind this high up, she could just make out the steady beat of drums. "By the Einir," muttered Tyvar. "There must be dozens." "Hundreds," said Kaya. "The ship we ran across must have been part of their vanguard. Scouts." "And that's the army." But why? All this—a legion of demons, a fleet of longships—just to stop them? She knew she was tough, and Tyvar wasn't half-bad for a budding planeswalker, but this seemed like overkill. Unless— Unless they weren't here for them at all. "That sword," said Kaya. "It opens portals! Rips holes in the space between realms!" Tyvar stared uncomprehendingly at her. Kaya grabbed his shoulders and shook him. "Kid, he's going to start a Doomskar!" "Correction," came a voice from above them. "I already started it." A bolt of searing flame shot down from the switchback of stairs above them; Kaya threw herself to one side just in time to feel the heat lick against her face. Grinning down at them from the ridge above was Tibalt. A curl of red, jittering flame wreathed one hand; in the other, he held that sword of shimmering, colorful glass. #figure(image("007_Episode 4: Into the Demons' Realm/04.jpg", width: 100%), caption: [Sword of the Realms | Art by: <NAME>awan], supplement: none, numbering: none) "We've got to get that sword away from him," said Kaya. Another ball of flame arced through the air, turning the rock molten where Tyvar had been standing a moment before. She went one way, and Tyvar went the other. Between the winding stairway path, wedges of black rock jutted from the mountainside, evidence of tectonic shifts as savage as any denizen of the realm. Tyvar used them as cover, keeping low, climbing the slope in athletic leaps and bounds. For Kaya, things weren't so complicated. She beat a straight path for Tibalt, phasing through rock and fire and whatever else the devil threw her way; nimble as Tyvar was, she quickly pulled ahead of him. Fifteen feet, then ten. Kaya slipped an axe from her belt and hurled it at Tibalt. It clipped his shoulder, sent him sprawling, and she drew the second axe. #emph[Don't let him get up.] She pushed herself over the ridge and lunged for Tibalt, focused entirely on reaching him, on the subtle shifts in her footing to let her bring all her weight down with the blow. She saw, too late, the deep breath that was filling his chest, the puffing up of those red cheeks. The smoke poured from his mouth in a great and sudden torrent, blanketing the oversized stairs in an instant. It rushed over Kaya in a wave, stinging her eyes, burning her throat. Blind, she swung anyway—but the axe only clanged off rock. Kaya pulled her cowl over her mouth and nose with one hand, kept the axe leveled and ready with the other, but all she could see was the smoke. Throughout, little orange cinders danced with malice. It seemed to cling to her, to seek out gaps in the cloth she breathed through, to pry at her squinting eyelids. Anywhere it touched bare skin, it burned. She did her best to shut out the pain and discomfort, to focus on her hearing. Where was Tibalt? Where was Tyvar? #emph[It's not too late to run.] The thought seemed to come from nowhere. #emph[It's done anyway. Tibalt already started the Doomskar. What are you still doing here?] Gradually, the burning across her skin, in her lungs and eyes, grew worse. An odd fatigue had settled into her limbs, too—the hand-axe she held out, once so light and balanced, seemed to drag her arm down now. #emph[This plane's problems aren't your problems. You owe these people nothing. Go on—jump through the Blind Eternities. Get out of here. Save yourself. It's what you're best at, after all.] The thoughts rolled through her mind one after another, with Kaya powerless to stop them, and in spite of herself, she felt the impulse tugging at her, the magical energies building around her, preparing to carry her away. #emph[It would be so easy. There's nothing for you here anymore but pain.] Something was wrong—beyond the burning smoke, beyond the unnatural exhaustion that now threatened to drag Kaya to her knees. There was a voice in her head. A voice that almost—but not quite—sounded like her own. There was a movement in the swirling smoke to her right; she saw the sword first, those beautiful colors trapped in glass, arcing toward her. Tibalt, swinging to kill. "You couldn't just #emph[leave] , could you?" She tried to raise her axe to block the blow, but it was so heavy—her arm, so sluggish. Kaya knew already that it would arrive too late. On an animal instinct, Kaya squeezed her eyes shut. There was a resounding clang. Not exactly the sound of metal biting into flesh. No pain, either. Funny. Kaya opened her eyes. Between her and Tibalt stood Tyvar. He'd caught that shimmering god-light sword on the dagger fixed to his bracer. Tibalt was struggling to push through, arms shaking with the effort, and getting nowhere. "Who in all the hells are #emph[you] ?" With a quick and practiced gesture, Tyvar knocked the sword from Tibalt's hands. "<NAME>. Prince of the elves. Greatest hero in Kaldheim." The fog was starting to clear from Kaya's head now; she could #emph[feel ] where Tibalt had slipped into her mind, the way he had cloaked his presence in her own doubts and fears. The more she listened, the worse the fatigue and pain grew. It was almost artful, this magic—nothing like the clumsy, slapdash work she'd seen from him so far. But then why had Tyvar been immune to it? He'd charged into the smoke, same as her. Why weren't his doubts, his insecurities, slowly sucking the life from him? Unless—unless he didn't have any? #emph[By the ancients] , she thought. #emph[He's too young—too arrogant—too ] dumb#emph[ to doubt himself. And thank all the gods of Kaldheim for that.] In front of her, Tibalt scrambled back, red fire curling around one hand, but Tyvar grabbed him by his collar and flipped him over one shoulder, crashing the planeswalker into the edge of one stone stair. The breath went out of Tibalt in a hacking cough, and with it went the smoke and the fire, dwindling to nothing around them. Tyvar pressed his brass blade to Tibalt's neck. "Now, fiend, you will tell us what you've done." At that, Tibalt managed a grin. "Go see for yourself," he croaked. Kaya felt the energy gathering around him, the magic a sharp, acrid taste in the air. She tried to shout, but then there was the sound of a fire catching on dry wood, and the back of Tibalt's eyes lit orange. Like burning paper, his body dissolved into a mass of orange cinders, and Tyvar stumbled back. "He," sputtered the elf. "He—" "Planeswalked. Yeah," said Kaya, pushing herself off the ground. "Tyvar—thanks. For helping me there." "Of course," he said, recovering. "But what if he returns?" "He can't. Not for a while, anyway, and if he does, he'll be no threat to us. It takes a lot of magic to jump planes. He'll need a while to recharge." "Ah," said Tyvar. "So we've won? It's over?" Kaya glanced up toward the peak of the mountain, where those strange lights continued to coruscate and ripple across the ash-clouded sky. "No. I don't think it is." On any other day, maybe the sight of a vast well of blood resting in the cone of the mountain below them might have been worth a moment's regard. But from the peak of the Bloodcrag, they had a clear view of the tear in the sky. It stretched, end to end, from where they stood to the middle of the lake of magma they had crossed; Kaya didn't know whether the heavy clouds of ash had blocked their view or whether it was new, a fresh wound made during their initial ascent. Along the edges of the tear, spilling out and covering the sky, radiated that shifting, multicolored light. "By all the realms," muttered Tyvar. Inside, Kaya could see a shifting, kaleidoscopic tableau of landscapes: craggy, towering mountains, fortresses of ice, plains of tall yellow grass. It felt as though she was seeing into the whole of the Multiverse, all the planes rent open in one utterly wrong stroke. "Any chance you know how to undo that? Maybe with the sword?" she said. They'd brought it up with them, tucked into Tyvar's belt. He shook his head. "My talents #emph[do ] have their limits, you know." Despite everything—the iron reek of blood, the tear in the sky—that forced a laugh from Kaya. It died in her throat, though, when she saw the first figures rising from the fiery lake far below them. With each beat of their leathery wings, they rose higher into the air, bearing swords and spears, halberds and hammers, the weight of the weapons and armor dragging at them but not keeping them from their steady, dreadful progress. There must have been thousands of them, all headed for that hole in the sky. Their invitation to pillage, to burn, to destroy not just one world but all the worlds this plane had to offer. At their center, rising from a ship with two vast masts of fire, was a demon that dwarfed all the others. In one hand he dragged a great double-bladed axe; he seemed to be beating his wings with manic fury, bowling past others in his need for escape. She knew his name, even before Tyvar whispered it, dumbstruck. She had heard it spoken enough times during her time with the Omenseekers: Varragoth. #figure(image("007_Episode 4: Into the Demons' Realm/05.jpg", width: 100%), caption: [Varragoth, Bloodsky Sire | Art by: <NAME>], supplement: none, numbering: none) Kaya turned to Tyvar, who was still staring at the unholy flock rising before them. "Tyvar, we have to go. This plane is about to go to pieces." He didn't seem to hear her. "We need to stop them. We need to warn whoever's on the other side!" "Tyvar," she said, gently. "It's over. You're a great warrior, don't get me wrong, but the greatest warrior in history couldn't change what's about to happen." Already, she could see demons crossing into the gap, their great wingbeats bringing them to new prey. "We tried. Now all we can do is stay alive. Get to the next plane, try to do better—" She tried to put a hand on his back, but he wrenched away from her. "So this is what your kind does—disappear as soon as the world pitches a direction you don't care for. Run as soon as things get hard. You and that Tibalt aren't so different in the end." The words hit her harder than she expected. By the time she'd started shaping together a reply—something about not being so hardheaded, something about going to get yourself killed—Tyvar had already opened an Omenpath. He turned to her. "If this is what it means to be a planeswalker, I want no part in it." With that, he stepped through the doorway. The energy Kaya had been gathering to planeswalk still hung in the air around her, a nameless pressure lacking a valve. She could still go. She #emph[should ] still go. It was the smart choice. It was her code. But she couldn't help thinking about those voices in her head. How she'd been hearing them, in one way or another, since long before she'd met Tibalt or Tyvar. Kaya swore, took a deep breath, and stepped in after him.
https://github.com/SillyFreak/typst-packages-old
https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/crudo/gallery/test.typ
typst
MIT License
// make the PDF reproducible to ease version control #set document(date: none) // #import "../src/lib.typ" #import "@preview/crudo:0.1.0" #import "@preview/codly:0.2.1": * #show: codly-init #codly() #let preamble = ```typ #import "@preview/crudo:0.0.1" ``` #let example = ````typ #crudo.r2l(```c int main() { return 0; } ```) ```` #let full-example = crudo.join(preamble, example) = The example #example = The example with preamble #full-example (usually you don't show this) = Evaluating the example #eval(full-example.text, mode: "markup")
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/complessità/16_richiami_matematici.typ
typst
= Richiami matematici: simboli di Landau Quello che facciamo nella teoria della complessità è chiederci _"quanto costa questo programma?"_ Per capire il costo di un dato programma valuteremo delle funzioni nella forma $f(n)$, dove $n$ indica la grandezza dell'input della DTM. Nel fare il confronto tra due algoritmi per uno stesso problema, bisogna tenere in considerazione che a fare la differenza (_in termini di prestazioni_) sono gli input di dimensione "ragionevolmente grande", dove con questa espressione intendiamo una dimensione significativa nel contesto d'applicazione del problema. Siano ad esempio $t_1$ e $t_2$ due funzioni tali che $ t_1 (n) = 2n quad bar.v quad t_2 (n) = 1/100 n^2 + 1/2 n + 1 . $ Quale delle due è migliore? La risposta è _dipende_: se considero $n$ abbastanza piccoli allora $t_2$ è migliore perché i coefficienti ammortizzano il valore di $n^2$, mentre se considero $n$ sufficientemente grandi è migliore $t_1$. Date due funzioni, non le devo valutare per precisi valori di $n$, ma devo valutare il loro *andamento asintotico*, ovvero quando $n$ tende a $+infinity$. == Simboli di Landau principali I *simboli di Landau* sono utili per stabilire degli *ordini di grandezza* fra le funzioni, in modo da poterle paragonare. I più utilizzati sono i seguenti tre: + $O$: letto _"O grande"_, date due funzioni $f,g : NN arrow.long NN$ diciamo che $ f(n) = O(g(n)) $ se e solo se $ exists c > 0 quad exists n_0 in NN bar.v forall n gt.eq n_0 quad f(n) lt.eq c dot g(n) . $ Questo simbolo dà un *upper bound* alla funzione $f$. + $Omega$: letto _"Omega grande"_, date due funzioni $f,g : NN arrow.long NN$ diciamo che $ f(n) = Omega(g(n)) $ se e solo se $ exists c > 0 quad exists n_0 in NN bar.v forall n gt.eq n_0 quad f(n) gt.eq c dot g(n). $ Questo simbolo dà un *lower bound* alla funzione $f$. + $Theta$: letto _"teta grande"_, date due funzioni $f,g : NN arrow.long NN$ diciamo che $ f(n) = Theta(g(n)) $ se e solo se $ exists c_1, c_2 > 0 quad exists n_0 in NN bar.v forall n gt.eq n_0 quad c_1 dot g(n) lt.eq f(n) lt.eq c_2 dot g(n). $ Si può notare facilmente che valgono le proprietà $ f(n) = O(g(n)) arrow.l.r.long.double g(n) = Omega(f(n)) \ f(n) = Theta(g(n)) arrow.l.r.long.double f(n) = O(g(n)) and f(n) = Omega(g(n)) . $ Noi useremo spesso $O$ perché ci permette di definire il _worst case_.
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/thesis/abstract.typ
typst
MIT License
#import "../util/style.typ":font_size,font_family,vspacer #import "../util/functions.typ":invisible_heading #let chinese_abstract(content, keywords)={ if content != none { set align(center) set text(font: font_family.heiti, size: font_size.xiao_san) set par(leading: 0.6em) [摘#h(2em)要\ \ ] invisible_heading[摘#h(2em)要] set align(left) set text(font: font_family.songti, size: font_size.xiao_si) set par(leading: 0.95em, first-line-indent: 2em, justify: true) set block(spacing: 0.95em) content + v(1.25em) + h(-2em) set text(font: font_family.heiti, size: font_size.xiao_si, weight: "bold") [关键词:#keywords.join(";")] } } #let english_abstract(title, content, keywords)={ if content != none { set align(center) set text(font: font_family.songti, size: font_size.xiao_san, weight: "regular") set par(leading: 1.3em) [*#title*\ \ ] set par(leading: 2em) [Abstract] v(16pt) invisible_heading[Abstract] set block(spacing: 0.95em) set align(left) set text(font: font_family.songti, size: font_size.xiao_si) set par(leading: 0.95em, first-line-indent: 2em, justify: true) [#content\ ] set text(font: font_family.heiti, size: font_size.xiao_si, weight: "bold") linebreak() [Key Words:#keywords.join(";")] } } #let abstract( chinese_content, chinese_keywords, english_title, english_content, english_keywords, )=[ #chinese_abstract(chinese_content, chinese_keywords) #pagebreak(weak: true) #english_abstract(english_title, english_content, english_keywords) #pagebreak(weak: true) ]
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/树/子结构判断.typ
typst
#import "../../../../lib.typ":* === #Title( title: [子结构判断], reflink: "https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/description/", level: 2, )<子结构判断> #note( title: [ 子结构判断 ], description: [ 给定两棵二叉树 tree1 和 tree2,判断 tree2 是否以 tree1 的某个节点为根的子树具有 相同的结构和节点值 。 注意,空树 不会是以 tree1 的某个节点为根的子树具有 相同的结构和节点值 。 ], examples: ( [ #image("img/example1.png", width: 50%) 输入:tree1 = [1,7,5], tree2 = [6,1] 输出:false 解释:tree2 与 tree1 的一个子树没有相同的结构和节点值。 ],[ #image("img/example2.png", width: 50%) 输入:tree1 = [3,6,7,1,8], tree2 = [6,1] 输出:true 解释:tree2 与 tree1 的一个子树拥有相同的结构和节点值。即 6 - > 1。 ] ), tips: [ 0 <= 节点个数 <= 10000 ], solutions: ( ( name:[递归遍历], text:[ 若树 B 是树 A 的子结构,则子结构的根节点可能为树 A 的任意一个节点。因此,判断树 B 是否是树 A 的子结构,需完成以下两步工作: + 先序遍历树 A 中的每个节点 node ;(对应函数 isSubStructure(A, B)) + 判断树 A 中以 node 为根节点的子树是否包含树 B 。(对应函数 recur(A, B)) #align(center,{image("img/solution1.png", width: 80%)}) 本文名词规定:树 A 的根节点记作 节点 A ,树 B 的根节点称为 节点 B 。 `recur(A, B) `函数: + 终止条件: + 当节点 B 为空:说明树 B 已匹配完成(越过叶子节点),因此返回 `true` ; + 当节点 A 为空:说明已经越过树 A 的叶节点,即匹配失败,返回 `false` ; + 当节点 A 和 B 的值不同:说明匹配失败,返回 `false` ; + 返回值: + 判断 A 和 B 的 左子节点 是否相等,即 `recur(A.left, B.left)` ; + 判断 A 和 B 的 右子节点 是否相等,即 `recur(A.right, B.right)` ; `isSubStructure(A, B) `函数: + 特例处理: 当 树 A 为空 或 树 B 为空 时,直接返回 `false` ; + 返回值: 若树 B 是树 A 的子结构,则必满足以下三种情况之一,因此用或 || 连接; + 以 节点 A 为根节点的子树 包含树 B ,对应 `recur(A, B)`; + 树 B 是 树 A 左子树 的子结构,对应 `isSubStructure(A.left, B)`; + 树 B 是 树 A 右子树 的子结构,对应 `isSubStructure(A.right, B)`; ],code:[ ```cpp class Solution { public: bool isSubStructure(TreeNode* A, TreeNode* B) { return (A != nullptr && B != nullptr) && (recur(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B)); } private: bool recur(TreeNode* A, TreeNode* B) { if(B == nullptr) return true; if(A == nullptr || A->val != B->val) return false; return recur(A->left, B->left) && recur(A->right, B->right); } }; ``` ]), ), gain:none, )
https://github.com/jamesrswift/typst-chem-par
https://raw.githubusercontent.com/jamesrswift/typst-chem-par/main/src/rules/formulae.typ
typst
MIT License
#import "../stateful.typ": * #import "../constants.typ": elements, pseudo-elements // Prepare array of elements #let all-elements = elements + pseudo-elements #all-elements = all-elements.sorted( (it) => it.len() ) #let ChemRegex = "(\(?((" + all-elements.map(it=>{"("+it+")"}).join("|") + ")+\d?)+(\)\d*)?(\d*([\+-])?)*)" #let formulae(body) = { show regex(ChemRegex): (it) => context { if-state-enabled( it , { show regex("\d"): set text(features: ("sinf", "subs")) show regex("\d*[+-]"): super it }) } body }
https://github.com/xhalo32/constructive-logic-course
https://raw.githubusercontent.com/xhalo32/constructive-logic-course/master/slides/02-todistaminen.typ
typst
#import "@preview/touying:0.4.2": * #import "slidetheme.typ" #import "@preview/note-me:0.2.1": * #import "@preview/prooftrees:0.1.0": * #let palette = ( rgb("#7287fd"), // lavender rgb("#209fb5"), // sapphire rgb("#40a02b"), // green rgb("#df8e1d"), // yellow rgb("#fe640b"), // peach rgb("#e64553"), // maroon ) #let math-palette = palette.map(c => c.darken(20%)) #show raw: slidetheme.colorize-code(palette) #show math.equation: it => slidetheme.colorize-math(math-palette, it) #set raw(syntaxes: "Lean4.sublime-syntax", theme: "Catppuccin Latte.tmTheme") #set text(font: "Fira Sans", weight: "light", size: 20pt) // #show raw: it => box( // fill: rgb("#eff1f5"), // inset: 8pt, // radius: 12pt, // text(fill: rgb("#4c4f69"), it) // ) #let s = slidetheme.register(aspect-ratio: "16-9") #let s = (s.methods.info)( self: s, title: [Konstruktiivinen logiikka ja formaali todistaminen], subtitle: [1 – Lauselogiikka], author: [<NAME> & <NAME>], date: datetime.today(), institution: [Otaniemen lukio], ) #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert #let (slide, empty-slide, title-slide, new-section-slide, focus-slide) = utils.slides(s) #show: slides == TODO #todo[ - luonnollinen päättely - todistus siitä, että $A -> A$ ja sama Leanillä - mikä on todistusassistentti? - miksi on todistusassistentti? - mitä leanillä voi tehdä? - tutkitaan $A -> A$-todistusta - mikä on A? - mikä on nuoli? - mikä on by? - mikä on intro? - mikä on exact? - implikaation sulutus, mitä eroa on $A -> (A -> B) -> B$ ja $A -> A -> B -> B$ välillä? ] == Tällä tunnilla #todo[tunnin oppimistavoitteet] - Mitä vaaditaan osoittamaan looginen väite korrektiksi - Päättelysääntöjä - Milloin looginen väite on tautologia tai todistettavissa vääräksi - Konstruktiivisen logiikan kieli - Natural deduction todistus - Klassisen logiikan ominaispiirteet == Todistukset totuustauluja käyttäen Konjunktio, disjunktio, negaatio, ekvivalenssi ja implikaatio == Luonnollinen päättely $ (()/A ()/B)/((A and B)/(B -> (A and B))/(A -> (B -> (A and B)))) $ #tree( axi[], uni[$A$], axi[], uni[$B$], bin[$A and B$], uni[$B -> (A and B)$], uni[$A -> (B -> (A and B))$] ) == Aksioomat MAA11 s.85 == Päättelysäännöt == Todistus luonnollista päättelyä käyttäen $A -> A$ (identiteettifuntio) Identiteettifuntio on funktio, joka kuvaa jokaisen lähtöjoukkonsa alkion itseensä. Tarkastellaan identiteettifuntion todistusta luonnollista päättelyä käyttäen. Mitä aksioomia ja sääntöjä? == $A -> A$, mutta Leanillä #grid(columns:(1fr, 1fr), text(size:15pt, [ Kirjoitetaan edellisen dian todistus Leaniä käyttäen: \ ```lean4 def identity : A → A := by intro a exact a ``` ]), text(size:15pt, [ `def` aloittaa määritelmän (definition) `by` aloittaa taktiikkatodistuksen `A` tyyppi `→` implikaatio, jostakin seuraa jotakin `intro` siirretään hypoteesi *maalista* oletukseksi *kontekstiin* `exact` suljetaan maali tarjoamalla *todistustermi* ]) ) == Lause, eli _teoreema_ #todo[ Esimerkkinä parilliset luvut (esitetään formaalisti 4 kappaleessa) ] == Apulause, eli _lemma_ == Kontrapositio MAA11 s.87 == Epäsuora todistus - $A -> B$ on ekvivalentti $not B -> not A$ klassisessa logiikassa - Huom: ei päde konstruktiivisessa logiikassa (kaikilla A ja B) == Epäsuora todistus esimerkki #todo[ ]
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/bootstrap.typ
typst
//! Set everything up before including the actual content /// Packages #import "@preview/codly:1.0.0": codly, codly-init #import "@preview/glossarium:0.4.2": make-glossary, register-glossary #import "@preview/hydra:0.5.1": hydra /// Local files #import "glossary.typ": entry-list /// Set rules #set heading(numbering: "1.") #set page( paper: "a4", margin: (y: 6em), header: context { let location = hydra(use-last: true) if location != none { let location = emph(location) if calc.even(here().page()) { align(left, location) } else { align(right, location) } line(length: 100%) } }, footer: context { let page_number = here().page() // no numbering in front page if page_number == 0 { return } let position = if calc.even(page_number) { left } else { right } text(8pt)[ #align(position)[ #counter(page).display( both: true, (current, total) => { let text = [Pág. #current / #total] let width = measure(text).width * current / total block[ #text #align(left)[ #line(length: width, stroke: rgb(0, 150, 200)) ] ] }, ) ] ] }, ) #set par(justify: true) #set text( font: "Open Sans", lang: "es", ligatures: true, size: 12pt, slashed-zero: true, ) /// Show rules #show bibliography: set heading(numbering: "1.") #show heading.where(level: 1): it => { pagebreak(weak: true) + it } #show: make-glossary #show: codly-init.with() /// Set up packages #register-glossary(entry-list) #codly( languages: ( bash: (name: "Bash", icon: "🐧", color: rgb("#CACACA")), diff: (name: "Diff", icon: "± ", color: rgb("#00AA00")), rust: (name: "Rust", icon: "🦀", color: rgb("#CE412B")), ), zebra-fill: none, number-format: none, stroke: 0.5pt + black, ) /// Actual content #include "content/main.typ"
https://github.com/tingerrr/subpar
https://raw.githubusercontent.com/tingerrr/subpar/main/test/supplement/test.typ
typst
MIT License
// Synopsis: // - default supplement is figure // - supplement is inferred from kind // - set supplement is used and propagated by default // - propagation works as expected #import "/test/util.typ": * #import "/src/lib.typ" as subpar // default supplement is figure #subpar.grid( figure(fake-image, caption: [Inner Caption]), <1a>, figure(fake-image, caption: [Inner Caption]), <1b>, columns: (1fr, 1fr), caption: [Super], label: <1>, ) // supplement is inferred from kind #subpar.grid( figure(fake-image, caption: [Inner Caption]), <2a>, figure(fake-image, caption: [Inner Caption]), <2b>, columns: (1fr, 1fr), caption: [Super], kind: raw, label: <2>, ) // set supplement is used and propagated #subpar.grid( figure(fake-image, caption: [Inner Caption]), <3a>, figure(fake-image, caption: [Inner Caption]), <3b>, columns: (1fr, 1fr), caption: [Super], supplement: "Image", label: <3>, ) // set supplement is used and not propagated #subpar.grid( figure(fake-image, caption: [Inner Caption]), <4a>, figure(fake-image, caption: [Inner Caption]), <4b>, columns: (1fr, 1fr), caption: [Super], supplement: "Image", propagate-supplement: false, label: <4>, ) @1, @1a, @1b @2, @2a, @2b @3, @3a, @3b @4, @4a, @4b
https://github.com/Personal-Data-Acquisition/PDA_paperwork
https://raw.githubusercontent.com/Personal-Data-Acquisition/PDA_paperwork/main/last_term/executive_summary.typ
typst
= Executive Summary (Team 6) #strong[Authors:] <NAME>, <NAME>, <NAME>, <NAME> #strong[DATE:] 2024-04-08 The Data Logger developed as part of this capstone project uses the common STM32F1 series of microcontrollers integrated with a Controller Area Network (CAN) bus and implemented using Embedded Rust. Sensor capabilities include GPS, acceleration, temperature, and more. The data gathered by this device can be viewed through a custom web UI hosted by the device.This system represents a robust solution for real-time data acquisition, processing, and storage, catering to diverse industrial and automotive applications.
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/intake-rebuild/decide.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Decide: Intake Rebuild", type: "decide", date: datetime(year: 2024, month: 2, day: 16), // TODO: fix date author: "<NAME>", witness: "Violet Ridge", ) In order to make our final decision as to which option to choose, we rated each option in the follow categories on scale of 1 to 10: - Strength integrity with a weight of 1x - Reliability with a weight of 0.8x - Ease of fabrication with a weight of 0.5x We then plotted these options on a decision matrix: #decision-matrix( // properties: ( // (name: "Structural Integrity", weight: 1), (name: "Reliability", weight: 0.8), (name: "Ease of Fabrication", weight: 0.5), ), ("No Bracing", 2, 4, 8), ("High Strength Axle Bracing", 8, 2, 7), ("3-Channel Bracing", 6, 5, 4), ) #admonition( type: "decision", )[ We ended up choosing an intake with high strength axle bracing due to its incredibly high structural integrity. While this will be very difficult to build, we think that the trade off is overall worth it. ] = CAD Breakdown After deciding on which option we wanted we designed it with CAD. The intake is driven by sprockets and chain, unlike our old intake which was directly driven. We do this to be able to change the gear ratio and protect the motor from harm. #image("./gear ratio.png", width: 50%) We opted for a 3:1 gear ratio, giving us a final RPM of 1800. This is mainly to compensate for the reduced speed of the smaller wheels. #grid( columns: (1fr, 1fr), [ Another essential part of our design is the sleds. These help the intake ride on top of the goal so we can push the triballs in with the drivetrain. They also serve the dual purpose of protecting the flex wheels inside of the intake from harm. ], image("./sled.png"), ) #image("./cad-drawing-1.svg") #image("./cad-drawing-2.svg") #image("./cad-drawing-3.svg")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/terms-06.typ
typst
Other
// Error: 8 expected colon / Hello
https://github.com/DamienFlury/summaries
https://raw.githubusercontent.com/DamienFlury/summaries/main/OOP1/main.typ
typst
#import "typst-boxes.typ": * #set page( header: align(right)[OOP Zusammenfassung – <NAME>], numbering: "– 1 –", flipped: true, margin: 20pt, ) #show: content => columns(5, content) #set text( lang: "de", size: 8pt, ) #let warn(body) = { slantedColorbox( title: "Warnung", color: "red", radius: 0pt, width: auto )[#body] } #set text( lang: "de" ) == Unäre Operatoren ```java x++``` #sym.arrow.l.r.double Gib x zurück; x = x + 1. \ ```java ++x``` #sym.arrow.l.r.double x = x + 1; Gib x zurück. == Datentypen #image("./datatypes_overview.png", width: 100%) === Double Mantisse: 52 Bit Exponent: 11 Bit Vorzeichen: 1 Bit === Float Mantisse: 23 Bit Exponent: 8 Bit Vorzeichen 1 Bit === Ordnung von Primitives Implizites Casting von unten nach oben: + double (64 Bit) + float (32 Bit) + long (64 Bit) + int (32 Bit) + short (16 Bit) + byte (8 Bit) Long ist spezifischer als float: ```java long l = 1; float f = l; // ok ``` Spezialfall char (unsigned 16 Bit): + explizites Casting von/zu byte, short. + implizites Casting zu int, float (und grösser). === Iterator ```java Iterator<String> iter = stringList.iterator(); while(it.hasNext()) { String elem = it.next(); it.remove(); } ``` === List ```java list.removeAll(List.of("Bsys1", "CN1")); ``` === Wrapper-Klassen ```java Integer boxed = Integer.valueOf(5); int unboxed = boxed.intValue(); // auch atomatisches Boxing: Integer wrapper = 123; // Integer.valueOf(123); int value = wrapper; // wrapper.intValue(); ``` === String Pooling Eine reine Compiler-Optimisation. Gleiche Strings können als einziges Objekt alloziiert werden. Beispiel: ```java String a = "Hello"; String b = "Hello"; a == b // true // aber: String a = "Hello"; String b = "H"; b += "ello"; a == b // false // oder: String a = "Hello"; String b = new String(a); a == b // false ``` Info: Compiler erkennt konstanten Ausdruck "OO" + "Prog" als "OOProg". Somit ist `"OO" + "Prog" == "OOProg"`. === Textblocks (Multiline Strings) ```java String a = """ Multiline String with "(unescaped) double quotes inside"."""; ``` == Enums ```java public enum Weekday { MONDAY(true), TUESDAY(true), WEDNESDAY(true), THURSDAY(true), FRIDAY(true), SATURDAY(false), SUNDAY(false); private boolean isWeekday; public Weekday(boolean isWeekday) { this.isWeekday = isWeekday; } } ``` Der `==`-Operator funktioniert für Enums by default. == Arrays ```java Arrays.equals(a, b); // Vergleicht die Inhalte der Arrays Arrays.deepEquals(a, b); // Vergleicht verschachtelte Arrays ``` === Mehrdimensionale Arrays ```java int[][] matrix = new int[2][3]; ``` == Methoden === Overloading _f_ spezifischer als _g_ #sym.arrow.l.r.double Alle möglichen Aufrufe von _f_ passen auch für _g_ (aber nicht umgekehrt). Bei Overlaoding gibt es *keine* Priorisierung von links nach rechts (oder umgekehrt): ```java print(int a, double b) {} print(double a, int b) {} print(1, 1) // ambiguous method call ``` === Dynamische vs Statische Bindung Alle nicht privaten Methoden verwenden Dynamic Dispatch. \ Static Dispatch wird verwendet bei: - Konstruktoren - Privaten Methoden - Statischen Methoden === Covarianz Der Rückgabe-Typ einer überschriebenen Methode kann Subtyp sein: ```java class Vehicle { Vehicle getClone() {} } class Car extends Vehicle { @Override Car getClone() {} } ``` == Wichtige Spezialfälle der Gleichheit ```java double a = Double.POSITIVE_INFINITY; a + 1 == a + 2; // true ``` ```java double a = Double.NaN; a != a; // true ``` ```java null == null; // true ``` == Hiding ```java class Vehicle { String description = "Any vehicle"; } class Car extends Vehicle { String description = "This is a car"; } ``` Statische Bindung: - Zugriff auf das Feld der eigenen Klasse mit `description` oder `this.description` - Zugriff auf das Feld der Basisklasse mit `super.description` oder `((Vehicle)this).description` - Zugriff auf das Feld irgendeiner Klasse in der Vererbungshierarchie mit `((SuperSuperClass)this).description` (Es existiert kein `super.super`). == Equals-Overriding Bei equals stets `getClass() != obj.getClass()` verwenden, anstelle `instanceof`, da `instanceof` die Vererbungshierarchie berücksichtigt. === Regeln - Reflexivität: - `x.equals(x)` #sym.arrow.r `true` - Symmetrie: - `x.equals(y) == y.equals(x)` - Transitivität: - `x.equals(y) && y.equals(z)` #sym.arrow.r `x.equals(z)` - Konsistenz: - Determinismus: Immer dasselbe Resultat für dieselben Argumente. - Null - `x.equals(null)` #sym.arrow.r `false` === Implementierung ```java @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; // Wichtig bei Vererbung Person person = (Person) o; return Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName); } ``` === Hash-Code ```java @Override public int hashCode() { return Objects.hash(firstName, lastName); } ``` == Collections #table( columns: (auto, auto), [*Methode*], [*Effizienz*], [`get()`, `set()`], [Sehr schnell], [`add()`], [Sehr schnell (amortisiert)], [`remove(int)`], [Langsam (meist umkopieren)], [`contains()`], [Langsam (durchsuchen)] ) === Performance-Übersicht #image("./performance-overview.png", width: 100%) === Feature-Übersicht #image("./feature-overview.png", width: 100%) === Amortisierung von `add()` Jedes neue Array, welches erstellt wird, wird um 1.5 grösser, muss aber nicht bei jedem `add()` vergrössert werden. *Amortisierte Kostenanalyse*: Einfügen im Worst Case langsam, im Durchschnitt aber sehr schnell. Max. Anzahl Umkopieren bei n+1 Einfügen: $$$ n + n (2/3) + n (2/3)^2 + n (2/3)^3 + ... = 3n $$$ Die amortisierte Kostenanalyse beträgt somit <= 3 pro Einfügen. == Exceptions Bei einem Rethrow in einer try-Methode, werden alle nachfolgenden catches nicht behandelt. === Übersicht #image("./exceptions-overview.png", width: 100%) ```java `Exception(String message, Throwable cause)``` (cause kann Exception sein, damit kann man den Stack Trace selbst aufbauen) === Finally Wird immer ausgeführt, auch wenn Exception nicht geprüft wurde oder nach einem Rethrow. Wird auch ausgeführt nach einem early return. Die zweite Exception im Finally-Block überschreibt erste Exception im catch Block. ```java try { // ... } catch(RuntimeException ex) { throw ex; // wird ignoriert } finally { throw new Exception(); } ``` === Multicatch ```java try { // ... } catch(NoStringException | ShortStringException ex) { System.out.println("clip error: " + ex.getMessage()); } ``` === Try-With-Resources ```java try(var scanner = new Scanner(System.in)) {} // äquivalent zu: { Scanner scanner = new Scanner(System.in); try { } finally { if (scanner != null) { scanner.close(); } } } ``` == Liskov Substitution Principle "Objekte einer Klasse soll man durch Objekte einer Subklasse ersetzen können, ohne die Programm-Korrektheit zu verletzen." == Downcasting von `null` Downcasting von `null` geschieht ohne Fehler: ```java Vehicle v = null; Car c = (Car)v; // c == null ``` == Packages ```java package p1; public class A {} package p2; import p1.A; public class C {} ``` Exakte Imports haben Priorität, Wildcards nicht: ```java package p1; public class A {} package p2; public class A {} ``` Wildcard: ```java package p1; import p2.*; class Test { A a1; p2.A a2; } ``` Exakter Import: ```java package p1; import p2.A; class Test { p1.A a1; A a2; ``` === Static Imports ```java import static java.lang.Math.*; ``` ```java import java.lang.*``` ist implizit immer vorhanden. == Interfaces Gleiche Signatur, aber unterschiedliche Rückgabetypen geht nicht: ```java interface RoadVehicle { String getModel(); } interface WaterVehicle { int getModel(); } class AmphibianMobile implements RoadVehicle, WaterVehicle { // Compilerfehler public int getModel() { return 1; } } ``` Mit Subtypen funktioniert es aber: ```java interface RoadVehicle { RoadVehicle clone(); } interface WaterVehicle { WaterVehicle clone(); } class AmphibianMobile implements RoadVehicle, WaterVehicle { @Override public AmphibianMobile clone() { // Covarianz return new AmphibianMobile(); } } ``` === Mehrere Interfaces mit spezifischerem Interface (ok) #image("./multiple-interfaces.png", width: 100%) === Mehrere Interfaces mit derselben Priorisierung (nicht ok, Klasse muss den Konflikt beheben) #image("./multiple-interfaces-conflict.png", width: 100%) == Comparable-Interface ```java class Person implements Comparable<Person> { private int age; public int compareTo(Person other) { return Integer.compare(age, other.age); } } ``` == Comparator-Interface ```java interface Comparator<T> { int compare(T a, T b); } class AgeComparator implements Comparator<Person> { public int compare(Person p1, Person p2) { return Integer.compare(p1.getAge(), p2.getAge()); } } Collections.sort(people, new MyComparator()); people.sort(this::compareByAge); // Methodenreferenz (Higher order function) ``` ```java @FunctionalInterface interface Comparable<T> { int compare(T first, T second); } ``` === Comparator-Bausteine ```java people.sort(Comparator .comparing(Person::getAge) .reversed()); // reversed ist eine default methode auf dem Comparator-Interface people.sort(Comparator .comparing(Person::getLastName) .thenComparing( Person::getFirstName)); ``` == Stream-API === Wichtige Stream-Methoden - filter - map - flatMap - mapToInt/mapToDouble/mapToLong - sorted - distinct - limit - skip === Terminaloperationen - forEach - forEachOrdered (erhält Reihenfolge, besonders wichtig bei Parallelisierung) - count - min, max - average, sum - findAny, findFirst - allMatch, anyMatch, noneMatch - reduce === Parallelisierung ```java people.parallelStream() .filter(p -> p.getAge() > 16) .forEach(System.out::println); ``` === Vordefinierte Funktionsschnittstellen ```java interface Predicate<T> { boolean test(T input); } interface Function<T, R> { R apply(T input); } interface Consumer<T> { void accept(T input); } ``` Von `java.util.function`. ```java filter(Predicate<T> p) map(Function<T, U> f) forEach(Consumer<T> c) ``` === Methodenreferenz-Syntax ```java list.forEach(System.out::println); ``` ```java var random = new Random(); Stream.generate(random::nextInt) .forEach(System.out::println); ``` ```java Map<Integer, List<Person>> peopleByAge = people.stream() .collect(Collectors .groupingBy(Person::Age)); ``` === Optional ```java OptionalDouble averageAge = people.stream() .mapToInt(Person::getAge) .average(); if (averageAge.isPresent()) { System.out.println(averageAge .getAsDouble()); } ``` Methoden: `empty()`, `of(double value)`, `ifPresent(Consumer)`, `orElse(double value)` === Groupings ```java Map<Integer, List<Person>> peopleByAge = people.stream() .collect(Collectors .groupingBy(Person::getAge)); ```
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/types/number/test.typ
typst
Other
#import "/src/lib.typ" as z #import "/tests/utility.typ": * #show: show-rule.with(); #let schema = z.any() = types/number == Input types == Custom assertions === Min #let test-min(valid: true, value, minimum: 0) = utility-expect-eq( test: value, schema: z.number(min: minimum), truth: if (valid) { value } else { none }, )([Comparing #value against minimum #minimum]) #test-min(valid: true, 5, minimum: 4) #test-min(valid: true, 5, minimum: 5) #test-min(valid: false, 5, minimum: 6) === Min #let test-max(valid: true, value, maximum: 0) = utility-expect-eq( test: value, schema: z.number(max: maximum), truth: if (valid) { value } else { none }, )([Comparing #value against maximum #maximum]) #test-max(valid: false, 5, maximum: 4) #test-max(valid: true, 5, maximum: 5) #test-max(valid: true, 5, maximum: 6)