repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-02.typ
typst
Other
// Test automatic numbering in summed content. #for i in range(5) { [+ #numbering("I", 1 + i)] }
https://github.com/mrcinv/nummat-typst
https://raw.githubusercontent.com/mrcinv/nummat-typst/master/16_nde.typ
typst
= Reševanje začetnega problema za NDE Navadna diferencialna enačba $ u'(t) = f(t, u, p) $ ima enolično rešitev za vsak začetni pogoj $u(t_0) = u_0$. Iskanje rešitve NDE z danim začetnim pogojem imenujemo #link("https://en.wikipedia.org/wiki/Initial_value_problem")[začetni problem]. V naslednji vaji bomo napisali knjižnico za reševanje začetnega problema za NDE. Napisali bomo naslednje: 1. Podatkovno strukturo, ki hrani podatke o začetnemu problemu. 2. Podatkovno strukturo, ki hrani podatke o rešitvi začetnega problema. 3. Različne metode za funkcijo `resi`, ki poiščejo približek za rešitev začetnega problema z različnimi metodami: - Eulerjevo metodo, - Runge-Kutta reda 2, - prediktor korektor z Eulerjevo in implicitno trapezno metodo in kontrolo koraka. 4. Funkcijo `vrednost`, ki za dano rešitev začetnega problema izračuna vrednost rešitve v vmesnih točkah s #link("https://en.wikipedia.org/wiki/Cubic_Hermite_spline")[Hermitovim kubičnim zlepkom]. Uporabite Hermitovo bazo kubičnih polinomov, ki zadoščajo pogojem v tabeli #figure( table( columns: 5, [], [$p(0)$], [$p(1)$], [$p'(0)$], [$p'(1)$], [$h_(00)$], [$1$], [$0$], [$0$], [$0$], [$h_(01)$], [$0$], [$1$], [$0$], [$0$], [$h_(10)$], [$0$], [$0$], [$1$], [$0$], [$h_(11)$], [$0$], [$0$], [$0$], [$1$] ), caption: [Vrednosti baznih polinomov $h_(i j)(t)$ in njihovih odvodov v točkah $t=0$ in $t=1$.] ) 5. Napisane funkcije uporabite, da poiščete rešitev začetnega problema za poševni met z zračnim uporom. Kako daleč leti telo preden pade na tla? Koliko časa leti? 6. Ocenite napako, tako da rezultat izračunajte z dvakrat manjšim korakom. == Hermitova interpolacija Približne metode za začetni problem NDE izračunajo približke za rešitev zgolj v nekaterih vrednostih spremenljivke $t$. Vrednosti rešitve diferencialne enačbe lahko interpoliramo s #link("https://en.wikipedia.org/wiki/Cubic_Hermite_spline")[kubičnim Hermitovim zlepkom]. Hermitov zlepek je na intervalu $(x_i, x_(i+1))$ enak kubičnemu polinomu, ki se z rešitvijo ujema v vrednostih in odvodih v krajiščih intervala $x_i$ in $x_(i+1)$. == Poševni met z zračnim uporom
https://github.com/jrihon/multi-bibs
https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/01_chapter/methods.typ
typst
MIT License
#import "../../lib/multi-bib.typ": * #import "bib_01_chapter.typ": biblio == Methods #lorem(50) This software package is the absolute best #mcite(("Neese2021orca"), biblio) !
https://github.com/jamesrswift/chemicoms-paper
https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/tests/open-access/test.typ
typst
#import "/src/lib.typ": template, elements; #import "@preview/scienceicons:0.0.6": open-access-icon #set page(paper: "us-letter", margin: (left: 10mm, right: 10mm, top: 12mm, bottom: 15mm), height: auto) #show: template.with( title: [A typesetting system to untangle the scientific writing process], abstract: ([The process of scientific writing is often tangled up with the intricacies of typesetting, leading to frustration and wasted time for researchers. In this paper, we introduce Typst, a new typesetting system designed specifically for scientific writing. Typst untangles the typesetting process, allowing researchers to compose papers faster. In a series of experiments we demonstrate that Typst offers several advantages, including faster document creation, simplified syntax, and increased ease-of-use.], (title: "Plain Language Summary", content: lorem(20))), header: ( article-color: rgb("#7a9371"), article-type: [Open Access] + open-access-icon(color: white, height: auto, baseline: 15%), //article-meta: [Not Peer-Reviewed], ), venue: [_Ars Bibliologia_], authors: ( ( name: "<NAME>", ), ( name: "<NAME>", corresponding: true, orcid: "" ), ), dates: ( (type: "Received Date", date: datetime.today()), (type: "Revised Date", date: datetime.today()), (type: "Accepted Date", date: datetime.today()) ), doi: "00.0000/XXXXXXXXXX", citation: [<NAME>. and Mädje, _Ars Bibliologia_, 2024, *3*, 1---2], )
https://github.com/Slyde-R/not-jku-thesis-template
https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/template/content/Introduction.typ
typst
MIT No Attribution
#import "../utils.typ": todo, silentheading, flex-caption = Introduction <chapter_introduction> <intro> #todo[replace this chapter with your introduction] @intro == Background and Motivation Cats have been companions to humans for thousands of years, yet their unique behavior and the subtle art of their interaction with humans remain only partially understood. Unlike dogs, whose domestication has long been associated with clear roles in human societies, cats have carved out a distinct niche within domestic settings. Their autonomy, coupled with an apparent mastery of human psychology, positions them as enigmatic figures in the world of pets @Bradshaw2012[p.20] . This peculiar relationship motivates the current study, which seeks to explore how cats manage to manipulate and train their human companions to cater to their needs and desires. Feline behavior is often characterized by an apparent nonchalance and independence, yet this exterior masks a sophisticated interplay of manipulation and affection @Turner2017[pp. 90-110]. Observations indicate that cats use a variety of subtle and overt strategies to influence human behavior, from purring and meowing to more nuanced actions like "kneading" and selective attention-seeking @McComb2009. This complex interaction raises questions about the cognitive and emotional dynamics at play and how these influence both the cats' and their human caregivers' daily lives. == Research Gap While substantial research exists on domestic animals and their roles in human lives, the focus has predominantly been on dogs, often highlighting their roles as companions, workers, or service animals. In contrast, the behavioral intricacies of cats and their impact on human behavior are less thoroughly explored @Serpell2017. Most studies in feline behavior have concentrated on health-related issues or general behavioral patterns, leaving a significant gap in understanding the specific ways in which cats manipulate their human counterparts. Current literature does not fully address how cats employ particular behaviors to influence human actions or how these interactions affect human psychology and household dynamics @Horwitz2010. The existing research often lacks a detailed analysis of the behavioral strategies employed by cats to achieve their goals, such as gaining attention, securing food, or ensuring comfort @Odendaal2000. This thesis aims to address these gaps by providing a comprehensive examination of feline manipulation tactics and their consequences for human behavior. == Research Objectives and Questions The primary aim of this thesis is to delve into the ways cats influence and manipulate their human companions. This exploration involves identifying and categorizing the specific behaviors that cats use to affect human actions, understanding the psychological mechanisms that underlie these behaviors, and assessing the broader impact on human routines and emotional well-being. To achieve these objectives, the research will address several key questions. First, it will investigate the precise behaviors employed by cats to manipulate their human caregivers. This includes examining how various tactics, such as vocalizations, body language, and other interactions, are strategically used to achieve specific goals. Secondly, the study will explore the cognitive and emotional processes involved in these manipulation tactics, seeking to understand the underlying psychological mechanisms that enable cats to exert influence over humans. Finally, the research will evaluate the effects of feline behaviors on human behavior, including changes in daily routines, emotional responses, and overall household dynamics. By addressing these questions, the thesis aims to provide a comprehensive understanding of feline manipulation and its implications for both cats and their human companions.
https://github.com/valentinvogt/npde-summary
https://raw.githubusercontent.com/valentinvogt/npde-summary/main/src/chapters/03.typ
typst
#import "../setup.typ": * #import "../theorems.typ": * #show: thmrules = FEM: Convergence and Accuracy <ch:convergence-and-accuracy> == Abstract Galerkin Error Estimates <sub:abstract-galerkin-error-estimates> The main takeaway here is that the solution given by the Galerkin method is the best one (with respect to the energy norm) in the chosen discrete subspace. This is formalized by the following lemma: #theorem( number: "3.1.3.7", "Cea's Lemma", )[ Under some assumptions that guarantee the existence of a unique solution we have #neq($ norm(u - u_h)_a = inf_(v_h in V_(0 , h)) norm(u - v_h)_a, $) where $u$ is the exact solution and $u_h$ is the Galerkin solution. ]<thm:ceas-lemma> Next we want to discuss the types of refinement, i.e., the steps we can take to increase the accuracy of our method. #mybox( "h-Refinement", )[ Replace the mesh $msh$ (underlying $V_(0 , h)$) with a finer mesh $msh prime$ (underlying larger discrete trial space $V prime_(0 , N prime)$). ] <concept:refinement> #v(-1cm) #mybox( "p-Refinement", )[ Replace $V_(0 , h) := S_p^0 (msh) , p in bb(N)$, with $V'_(0 , h) := S_(p + 1)^0 (msh)$, yielding a larger space: $V_(0 , h) subset V'_(0 , h)$ ] So h-refinement refines the mesh (smaller and smaller triangles) and p-refinement chooses more powerful basis functions (start with linear, then quadratic, etc.). The h in h-refinement refers to the mesh width: #definition( number: "3.2.1.4", "Mesh width", )[ Given a mesh $msh = { K }$, the *mesh width* $h_(msh)$ is defined as $ h_(msh) & := max { upright("diam") K : K in msh }\ upright("diam") K & := max { lr(|p - q|) : p , q in K } $ ] == Empirical (Asymptotic) Convergence of Lagrangian FEM <sub:empirical-asymptotic-convergence> As in NumCSE, there are two types of convergence, algebraic and exponential. We refer to the number of basis functions (dimension of the trial space) as $N$ and we study the behavior of errors as $N arrow.r oo$. Note that both exercises and theorems are often posed in terms of $h_(msh)$ as $h arrow.r 0$, which is equivalent if we have a fixed polynomial degree $p$ and only do h-refinement. #definition( number: "3.2.2.1", "Types of convergence", )[ $ norm(u - u_N)_a = Order(N^(- alpha)) , alpha > 0$ is called *algebraic* convergence with rate $alpha$. \ $ norm(u - u_N)_a = Order(exp (- gamma N^delta)) , gamma , delta > 0$ is called *exponential* convergence. ] #tip-box( [Determining convergence rates], [ - *algebraic* $ alpha approx (log eps_(i-1) - log eps_i)/(log N_i - log N_(i-1)) = log(eps_i\/eps_(i-1))/log(h_i\/h_(i-1)) $ - *exponential* In general: complicated (see §3.2.2.5 Lecture Notes) If $delta=1$ (plain exponential convergence) and we let $N$ increase linearly (e.g., $N_i = i$), $ eps_(i+1)/eps_i approx exp(-gamma) $ ], ) Note that in the case of h-refinement we get the relation between $N$ and $h$ given by #equation( number: "3.2.2.1", )[ #neq( $ N = dim S_p^0 (msh) approx p^d h_(msh)^(- d) thick arrow.r.double.long h_(msh) / p approx N^(- 1 / d) $, ) <eq:h-n-relation> where $p$ are the dimensions of the local basis functions, e.g., $p = 1$ for linear basis functions, and $d$ is the dimension of the underlying space $Omega$. ] E.g., in the case where we have $Omega subset bb(R)^2$ and piecewise linear basis functions, we get $h_(msh)^(- 2) approx N$. == A Priori (Asymptotic) Finite Element Error Estimates <sub:a-priori-asymptotic-error> Since FEM is similar to polynomial interpolation, we can use interpolation error estimates to get error bounds. Here are some results for linear interpolation: #mybox( "Linear interpolation error 1D", )[ Using the linear interpolant $I_1$ we want to study the interpolation error $u - I_1 u$. The following interpolation error estimates can be used for sufficiently smooth functions $u$: #neq( $ norm(u - I_1 u)_(L^oo (openint(a, b))) <= 1 / 4 h_(msh)^2 norm(u'')_(L^oo (openint(a, b))) $, ) #neq( $ norm(u - I_1 u)_(L^2 (openint(a, b))) <= h_(msh)^2 norm(u'')_(L^2 (openint(a, b))) $, ) #neq( $ lr(|u - I_1 u|)_(H^1 (openint(a, b))) <= h_(msh) norm(u'')_(L^2 (openint(a, b))) $, ) ] #mybox( "Linear interpolation error 2D", )[ In 2D, linear interpolation corresponds to using tent functions: $I_1 u = sum_(p in cal(V) (msh)) u (p) b^p$, where $b^p$ is the tent function associated with point $p$. #neq( $ norm(u - I_1 u)_(L^2 (Omega)) &<= C h_(msh)^2 norm(norm(D^2 u)_F)_(L^2 (Omega)) \ norm(grad (u - I_1 u))_(L^2 (Omega)) &<= C rho_(msh) h_(msh) norm(norm(D^2 u)_F)_(L^2 (Omega)) $, ) <eq:lin_interpolate_2d> Here, $D^2 u$ is the Hessian of $u$, $norm(dot)_F$ is the Frobenius norm, and $rho_(msh)$ is the shape regularity measure of the mesh $msh$, defined as $rho_(msh) = max_(K in msh) h_(msh)^2 / lr(|K|)$ for a triangular mesh. ] To get rid of this cumbersome notation, we can introduce more Sobolev spaces. #definition( number: "3.3.3.1", "Higher order Sobolev spaces/norms", ..unimportant, )[ The $m$-th order Sobolev norm is defined as #neq( $ norm(u)_(H^m (Omega))^2 = sum_(k = 0)^m sum_(balpha in bb(N)^d , lr(|balpha|) = k) integral_Omega lr(|D^balpha u|)^2 dif bx, wide "where" D^balpha u = frac( partial^(lr(|balpha|)) u, partial x_1^(alpha_1) dots.h.c thin partial x_d^(alpha_d), ) $, ) Hence we can define the $m$-th Sobolev space as #neq( $ H^m (Omega) = {v : Omega arrow.r bb(R) : norm(v)_(H^m (Omega)) < oo} $, ) ] #definition( number: "3.3.3.3", "Higher order Sobolev semi-norms", ..unimportant, )[ The $m$-th order Sobolev semi-norm is defined as #neq( $ lr(|u|)_(H^m (Omega))^2 = sum_(bold(alpha) in bb(N)^d , lr(|bold(alpha)|) = m) integral_Omega lr(|D^bold(alpha) u|)^2 dif bx $, ) ] Remember the multi-index $balpha$ already seen in @concept:multi-index. Using this new notation, we can rewrite the error bounds from @eq:lin_interpolate_2d as $ norm(u - I_1 u)_(L^2 (Omega)) &<= C h_(msh)^2 lr(|u|)_(H^2 (Omega)) \ norm(grad (u - I_1 u))_(L^2 (Omega)) &<= C rho_(msh) h_(msh) lr(|u|)_(H^2 (Omega)) $ It turns out that these bounds are not sharp. There is a very useful result for Lagrangian finite elements: #theorem( number: "3.3.5.6", "Best approximation error estimates for Lagrangian finite elements", )[ Given a triangular mesh $msh$, if the true solution $u$ is in $H^k (Omega)$, the best approximation error is bounded by #neq( $ inf_(v_h in cal(S)_p^0 (msh)) norm(u - v_h)_(H^1 (Omega)) <= C (h_(msh) / p)^(min { p , k - 1 }) norm(u)_(H^k (Omega)) $, ) ] <thm:best-approximation-error> We might not know the constant $C$ and/or $norm(u)_(H^k (Omega))$, but we know $p$ and $h_(msh)$ as they are imposed by the choice of function space and mesh. Remember the concept of refinement: we can adjust these values. And from Eq. @eq:h-n-relation we know that $h_(msh) \/ p approx N^(- 1 / d)$. Hence the error displays *algebraic* convergence with rate $min{ p , k - 1 }\/ d$. What still remains a question is $k$, the smoothness of the solution $u$. Another useful result hidden in the lecture notes is #equation( number: "3.6.3.10", [$L^2$ estimate], )[ Under some assumptions (convex domain, smooth coefficient functions), we have #neq( $ norm(u - u_h)_(L^2 (Omega)) <= C h_(msh) / p norm(u - u_h)_(H^1 (Omega)) $, ) ]<eq:l2-estimate> So we gain one order of convergence in the $L^2$ norm compared to the $H^1$ norm. #tip-box( [Rules of thumb for converge], [ If we are using $cal(S)_p^0 (msh)$ and $u$ is sufficiently smooth (e.g., $u in C^oo (Omega)$), we have $ norm(u - u_h)_(H^1 (Omega)) &= Order(h^p) \ |u - u_h|_(H^1 (Omega)) &= Order(h^p) \ norm(u - u_h)_(L^2 (Omega)) &= Order(h^(p + 1)) $ ], ) == Elliptic regularity <sub:elliptic-regularity> #theorem( number: "3.4.0.2", "Smooth elliptic lifting theorem", )[ For domains $Omega$ with smooth boundaries $partial Omega$, i.e. no corners and sufficiently smooth $sigma$, if $ u in H_0^1 (Omega) quad upright("and") quad - div (sigma grad u) in H^k (Omega) $ or $ u in H^1 (Omega) , - div (sigma grad u) in H^k (Omega) quad upright("and") quad grad u dot.op bold(n) = 0 quad upright("on") thin partial Omega $ holds, then $u in H^(k + 2) (Omega)$ and $ norm(u)_(H^(k + 2) (Omega)) <= C norm(div (sigma grad u))_(H^k (Omega)) $ ] This tells us that when solving the typical PDE $-div (sigma grad u) = f$ and the source term $f$ is in $H^k (Omega)$, the solution $u$ will be in $H^(k + 2) (Omega)$ (of course under the right assumptions). The theorem requires smooth domains, but our meshes will have corners, so what can be done there? As long as the domain and all cells are convex, something similar still holds: #theorem( number: "3.4.0.10", "Elliptic lifting on convex domains", )[ If $Omega subset RR^d$ is convex, $u in H_0^1 (Omega)$ and $Delta u in L^2 (Omega)$, then $u in H^2 (Omega)$. ]<thm:elliptic-lifting-convex-domains> If we are solving the Laplace equation on a convex domain, we just need to check if $f in L^2 (Omega)$, since $-Delta u = f$. #tip-box( [Finding $k$ in @thm:best-approximation-error], [ - Often, the exercise gives you $u$ which is in $C^oo (Omega)$, which means $u$ is infinitely smooth. In this case, $k = oo$. - Sometimes, you may use elliptic regularity results like @thm:elliptic-lifting-convex-domains to find $k=2$, for example. ], ) == Variational Crimes <sub:variational-crimes> What are variational crimes? A variational crime is committed when instead of the true variational problem $ u_h in V_(0 , h) : thin a (u_h , v_h) = ell (v_h) , thin forall v_h in V_(0 , h), $ we solve a different, "perturbed" variational problem $ tilde(u)_h in V_(0 , h) : thin a_h (tilde(u)_h , v_h) = ell_h (v_h) , thin forall v_h in V_(0 , h) $ with modified (bi-)linear forms $a_h , ell_h$. With computers, the use of quadrature and approximation of boundaries result in such a crime and are unavoidable. As Hiptmair likes to say, "we are all sinners". So the only distinction we can make is between acceptable and unacceptable "crimes". Crimes which do not affect the type and rate of convergence are acceptable. So how to not temper with the convergence? #subtle-box[ - if $norm(u - u_h)_1 in Order(h_(msh)^p)$, use a quadrature rule of order at least $2 p - 1$ - if $V_(0 , h) = cal(S)_p^0 (msh)$ then approximate the boundary with polynomials of degree $p$ ] #pagebreak() == FEM: Duality Techniques for Error Estimation <sub:duality> #theorem( number: "3.6.1.7", "Duality estimate for linear functional output", )[ Given a functional $F : V_0 arrow.r bb(R)$ the dual solution $g_F$ solves $ g_F in V_0 : thin a (g_F , v) = F (v) , thin forall v in V_0 $ and we get the estimate $ lr(|F (u) - F (u_h)|) <= C norm(u - u_h)_a inf_(v_h in V_(0 , h)) norm(g_F - v_h)_a $ ] Why is this useful? If $g_F$ can be approximated well in $V_(0 , h)$, then the output error $lr(|F (u) - F (u_h)|)$ can converge to 0 much faster than $norm(u - u_h)_a$.
https://github.com/chubetho/Bachelor_Thesis
https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/figures.typ
typst
#heading("List of Figures", outlined: true, numbering: none) #outline( title: none, target: figure.where(kind: image), ) #pagebreak(weak: true)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/showybox/0.2.1/README.md
markdown
Apache License 2.0
# Showybox (v0.2.1) **Showybox** is a Typst package for creating colorful and customizable boxes. ## Usage To use this library through the Typst package manager (for Typst 0.6.0 or greater), write `#import "@preview/showybox:0.2.1": showybox` at the beginning of your Typst file. Once imported, you can create an empty showybox by using the function `showybox()` and giving a default body content inside the parenthesis or outside them using squared brackets `[]`. By default a `showybox` with these properties will be created: - No title - No shadow - Not breakable - Black borders - White background - `5pt` of border radius - `1pt` of border thickness ```java #import "@preview/showybox:0.2.1": showybox #showybox( [Hello world!] ) ``` <h3 align="center"> <img alt="Hello world! example" src="assets/hello-world-example.png" style="max-width: 100%; background-color: #FFFFFF; padding: 10px 10px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt"> </h3> Looks quite simple, but the "magic" starts when adding a title, color and shadows. The following code creates two "unique" boxes with defined colors and custom borders: ```java // First showybox #showybox( frame: ( upper-color: red.darken(40%), lower-color: red.lighten(90%), border-color: black, width: 2pt ), title: "Hello world! - An example", [ Hello world! ] ) // Second showybox #showybox( frame: ( dash: "dotted", border-color: red.darken(40%) ), body-style: ( align: center ), sep: ( dash: "dashed" ), shadow: ( offset: 3pt ), [This is an important message!], [Be careful outside. There are dangerous bananas!] ) ``` <h3 align="center"> <img alt="Further examples" src="assets/further-examples.png" style="max-width: 100%; background-color: #FFFFFF; padding: 10px 10px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt"> </h3> ## Reference The `showybox()` function can receive the following parameters: - `frame`: A dictionary containing the frame's properties - `title-style`: A dictionary containing the title's styles - `body-styles`: A dictionary containing the body's styles - `title`: A string used as the title of the showybox - `body`: The content of the showybox - `sep`: A dictionary containing the separator's properties - `shadow`: A dictionary containing the shadow's properties - `breakable`: A boolean indicating whether a showybox can break if it reached an end of page ### Frame properties - `upper-color`: Color used as background color where the title goes (default is `black`) - `lower-color`: Color used as background color where the body goes (default is `white`) - `border-color`: Color used for the showybox's border (default is `black`) - `radius`: Showybox's radius (default is `5pt`) - `width`: Border width of the showybox (default is `2pt`) - `dash`: Showybox's border style (default is `solid`) ### Title styles - `color`: Text color (default is `white`) - `weight`: Text weight (default is `bold`) - `align`: Text align (default is `left`) ### Body styles - `color`: Text color (default is `black`) - `align`: Text align (default is `left`) ### Separator properties - `width`: Separator's width - `dash`: Separator's style (as a `line` dash style) ### Shadow properties - `color`: Shadow color (default is `black`) - `offset`: How much to offset the shadow in x and y direction either as a length or a dictionary with keys `x` and `y` (default is `4pt`) ## Gallery ### Encapsulation May have some bugs <h3 align="center"> <img alt="Encapsulation" src="assets/encapsulation.png" style="max-width: 100%; background-color: #FFFFFF; padding: 10px 10px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt"> </h3> ### Enabling breaking <h3 align="center"> <img alt="Enabling breakable" src="assets/enabling-breakable.png" style="max-width: 100%; padding: 10px 10px; background-color: #E4E5EA; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt"> </h3> ### Custom radius <h3 align="center"> <img alt="Custom radius" src="assets/custom-radius.png" style="max-width: 100%; background: #FFFFFF; padding: 10px 10px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 4pt"> </h3> ## Changelog ### Version 0.1.0 - Initial release ### Version 0.1.1 - Changed package name from colorbox to showybox - Fixed a spacing bug in encapsulated showyboxes - **Details:** When a showybox was encapsulated inside another, the spacing after that showybox was `0pt`, probably due to some "fixes" improved to manage default spacing between `rect` elements. The issue was solved by avoiding `#set` statements and adding a `#v(-1.1em)` to correct extra spacing between the title `rect` and the body `rect`. ### Version 0.2.0 - Improved code documentation - Enabled an auto-break functionality for non-titled showyboxes - Created a separator functionality to separate content inside a showybox with a horizontal line ### Version 0.2.1 _All changes listed here were performed by <NAME> (<https://github.com/jneug>)_ - Added the `shadow` option - Enabled auto-break (`breakable`) functionality for titled showyboxes - Removed a thin line that appears in showyboxes with no borders or dashed borders
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/anti-matter/0.0.1/README.md
markdown
Apache License 2.0
# anti-matter This typst packages allows you to simply mark the end and start of your front matter and back matter to change style and value of your page number without manually setting and keeping track of inner and outer page counters. ## Example ```typst #import "@preview/anti-matter:0.0.1": anti-matter, anti-front-end, anti-back-start #set page("a4", height: auto) #show heading.where(level: 1): it => pagebreak(weak: true) + it // add a title page and reset the counter #[ #set page(numbering: none) #counter(page).update(0) ] #show: anti-matter #include "front-matter.typ" #anti-front-end #include "chapters.typ" #anti-back-start #include "back-matter.typ" ``` ![An example outline showing the outer roman numbering interrupted by temporary inner arabic numbering](example.png) ## Features - Marking the start and end of front/end matter. - Specifying the numbering styles for each matter and regular content ## FAQ 1. Why are the pages not correctly counted? - If you are setting your own page header, you must use `anti-header`, see section II in the [manual]. 2. Why is my outline not displaying the correct numbering? - If you configure your own `outline.entry`, you must use `anti-page-at`, See section II in the [manual]. 3. Why does my front/inner/back matter numbering start on the wrong page? - This is likely a bug, please open an issue with a minimal reproducible example. ## Etymology The package name `anti-matter` was choosen as a word play on front/back matter. ## Glossary - [front matter](https://en.wikipedia.org/wiki/Book_design#Front_matter) - The first part of a thesis or book (intro, outline, etc.) - [back or end matter](https://en.wikipedia.org/wiki/Book_design#Back_matter_(end_matter)) - The last part of a thesis or book (bobliography, listings, acknowledgements, etc.) [manual]: https://github.com/tingerrr/typst-anti-matter/tree/87eb0108bdd79c16e996372013d8223647c9a64a/docs/manual.pdf
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/extras/callout-aside.typ
typst
MIT License
#import "@preview/cetz:0.1.2" #let _prepare(self, ctx) = { if (self.mz <= ctx.prototype.range.at(0) or self.mz >= ctx.prototype.range.at(1) ){ return (:) } let data = (if ( ctx.reflected ){ ctx.prototype.data2 } else { ctx.prototype.data1 }) let y = (ctx.prototype.get-intensity-at-mz)(self.mz, input: data) if self.height == auto {self.height = 100%} if type(self.height) == ratio { self.height = y * (self.height / 100%) } self.coordinates = ( mass-peak: (self.mz, self.height), content: self.position, ) return self } #let _stroke(self, ctx) = { cetz.draw.line( self.coordinates.mass-peak, self.coordinates.content, ..ctx.prototype.style.callouts.line ) cetz.draw.content( anchor: self.anchors.at(0), self.coordinates.content, //(72, 80), box(inset: self.inset, [#self.content]), ..ctx.prototype.style.callouts ) } #let callout-aside( mz, position, height: auto, content: none, anchor: "bottom", inset: 0.1em) = { if ( content == none ) { content = mz } return (( type: "callout-aside", mz: mz, content: content, height: height, position: position, anchors: (anchor,), inset: inset, plot-prepare: _prepare, plot-stroke: _stroke, ),) }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/124.%20selfindulgence.html.typ
typst
selfindulgence.html How to Lose Time and Money July 2010When we sold our startup in 1998 I suddenly got a lot of money. I now had to think about something I hadn't had to think about before: how not to lose it. I knew it was possible to go from rich to poor, just as it was possible to go from poor to rich. But while I'd spent a lot of the past several years studying the paths from poor to rich, I knew practically nothing about the paths from rich to poor. Now, in order to avoid them, I had to learn where they were.So I started to pay attention to how fortunes are lost. If you'd asked me as a kid how rich people became poor, I'd have said by spending all their money. That's how it happens in books and movies, because that's the colorful way to do it. But in fact the way most fortunes are lost is not through excessive expenditure, but through bad investments.It's hard to spend a fortune without noticing. Someone with ordinary tastes would find it hard to blow through more than a few tens of thousands of dollars without thinking "wow, I'm spending a lot of money." Whereas if you start trading derivatives, you can lose a million dollars (as much as you want, really) in the blink of an eye.In most people's minds, spending money on luxuries sets off alarms that making investments doesn't. Luxuries seem self-indulgent. And unless you got the money by inheriting it or winning a lottery, you've already been thoroughly trained that self-indulgence leads to trouble. Investing bypasses those alarms. You're not spending the money; you're just moving it from one asset to another. Which is why people trying to sell you expensive things say "it's an investment."The solution is to develop new alarms. This can be a tricky business, because while the alarms that prevent you from overspending are so basic that they may even be in our DNA, the ones that prevent you from making bad investments have to be learned, and are sometimes fairly counterintuitive.A few days ago I realized something surprising: the situation with time is much the same as with money. The most dangerous way to lose time is not to spend it having fun, but to spend it doing fake work. When you spend time having fun, you know you're being self-indulgent. Alarms start to go off fairly quickly. If I woke up one morning and sat down on the sofa and watched TV all day, I'd feel like something was terribly wrong. Just thinking about it makes me wince. I'd start to feel uncomfortable after sitting on a sofa watching TV for 2 hours, let alone a whole day.And yet I've definitely had days when I might as well have sat in front of a TV all day — days at the end of which, if I asked myself what I got done that day, the answer would have been: basically, nothing. I feel bad after these days too, but nothing like as bad as I'd feel if I spent the whole day on the sofa watching TV. If I spent a whole day watching TV I'd feel like I was descending into perdition. But the same alarms don't go off on the days when I get nothing done, because I'm doing stuff that seems, superficially, like real work. Dealing with email, for example. You do it sitting at a desk. It's not fun. So it must be work.With time, as with money, avoiding pleasure is no longer enough to protect you. It probably was enough to protect hunter-gatherers, and perhaps all pre-industrial societies. So nature and nurture combine to make us avoid self-indulgence. But the world has gotten more complicated: the most dangerous traps now are new behaviors that bypass our alarms about self-indulgence by mimicking more virtuous types. And the worst thing is, they're not even fun. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.
https://github.com/jangala-dev/product-docs
https://raw.githubusercontent.com/jangala-dev/product-docs/main/pdf/getbox.typ
typst
#import "template.typ": * #show: doc => manual( title: [Get Box V1 - User Guide], author: "Jangala", paper: "a5", publishing-info: [ Jangala. \ 4-6a Hookers Road \ London, E17 6DP #link("https://janga.la/") ], doc )
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/examples/dewdrop.typ
typst
#import "../lib.typ": * #let s = themes.dewdrop.register( s, aspect-ratio: "16-9", footer: [Dewdrop], navigation: "mini-slides", // navigation: none, ) #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let (init, slides, touying-outline, alert) = utils.methods(s) #show: init #show strong: alert #let (slide, title-slide, new-section-slide, focus-slide) = utils.slides(s) #show: slides = Section A == Subsection A.1 #slide[ A slide with equation: $ x_(n+1) = (x_n + a/x_n) / 2 $ ] == Subsection A.2 #slide[ A slide without a title but with *important* infos ] = Section B == Subsection B.1 #slide[ #lorem(80) ] #focus-slide[ Wake up! ] == Subsection B.2 #slide[ We can use `#pause` to #pause display something later. #pause Just like this. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously. ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.slides(s) = Appendix === Appendix #slide[ Please pay attention to the current slide number. ]
https://github.com/sergiodrd/analisis_real
https://raw.githubusercontent.com/sergiodrd/analisis_real/main/tarea4/main.typ
typst
#import "template.typ": * #let title = "Tarea 4" #let author = "<NAME>" #let course_id = "MATE 5201" #let instructor = "<NAME>" #let semester = "C41" #let due_time = "8 de octubre" #set enum(numbering: "a)") #set math.equation(numbering: "(1)", supplement: "la ecuación") #show: assignment_class.with(title, author, course_id, instructor, semester, due_time) #let contradiction = text($refmark$, size: 1.75em) // problema 1 #prob[ ] // problema 2 #prob[ ] // problema 3 #prob[ ] // problema 4 #prob[ ] // problema 5 #prob[ ] // problema 6 #prob[ ] // problema 7 #prob[ ] // problema 8 #prob[ ] // problema 9 #prob[ ] // problema 10 #prob[ ] // problema 11 #prob[ ]
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/grad.typ
typst
MIT License
#import "@local/evan:1.0.0":* = The gradient <sec-gradient> The gradient of $f : RR^n -> RR$, denoted $nabla f$, is the single most important concept in the entire "Multivariable differentiation" part. Although its definition is actually quite easy to compute, I want to give a proper explanation for where it comes from. Throughout this section, remember two important ideas: - The goal of the derivative is to approximate a function by a linear one. - Everything you used slopes for before, you should use normal vectors instead. If you want spoilers for what's to come, see the following table. #figure( table( columns: 3, align: left, table.header([Thing], [18.01], [18.02]), [Input], [$f: RR -> RR$], [$f: RR^n -> RR$], [Output], [$f': RR -> RR$], [$nabla f: RR^n -> RR^n$], [Think of as], [Slope (rise/run)], [Measures change in _each_ of $n$ directions], [Approximation], [Multiply by small run], [Dot product with small displacement], [Picture], [Slope of tangent in $x y$-graph], [Normal vector to tangent of level curve] ), kind: table, caption: [How to think of $nabla f$ for multivariable functions, compared to the derivative in 18.01.] ) == [TEXT] The gradient rewrites linear approximation into a dot product <text-gradient> In 18.01, when $f : RR -> RR$ was a function and $p in RR$ was an input, we thought of the single number $f'(p)$ as the slope to interpret it geometrically. Now that we're in 18.02, we have $n$ different rates of change, but we haven't talked about how to think of it geometrically yet. It turns out the correct definition is to take the $n$ numbers and make them into a vector. Bear with me for just one second: #definition[ If $f(x,y)$ is a two-variable function (so $f : RR^2 -> RR$), the *gradient* of $f$, denoted $nabla f$, is the function $RR^2 -> RR^2$ obtained by taking the two partial derivatives as the coordinates: $ nabla f(x,y) = vec(f_x (x,y), f_y (x,y)). $ The case of $n$ variables is analogous; for example if $f(x,y,z)$ is a three-variable function, then $ nabla f(x,y,z) = vec(f_x (x,y,z), f_y (x,y,z), f_z (x,y,z)). $ ] #typesig[ The types are confusing here. To continue harping on type safety: - Suppose $f : RR^2 -> RR$ accepts *points* in $RR^2$ and outputs *scalars* in $RR$. - Then $nabla f : RR^2 -> RR^2$ accepts *points* in $RR^2$ and outputs *vectors* in $RR^2$. Keep the distinction between points and vectors in mind when drawing pictures. We'll always draw points as dots, and vectors as arrows. ] The reason for defining this gradient is that it lets us do linear approximation with a *dot product*, and consequently dot products are going to be super important throughout this section. Let me show you how. Let's go back to our protagonist $ f(x,y) = x^2+y^2 $ at the point $P = (3,4)$. Way back in @example-circle-3-4 (on #pageref(<example-circle-3-4>)), we computed $f_x (P) = 2 dot 3 = 6$ and $f_y (P) = 2 dot 4 = 8$ and used it to get the approximation $ f(P + angle.l epsilon_x, epsilon_y angle.r) &= f(angle.l 3,4 angle.r + angle.l epsilon_x, epsilon_y angle.r) \ &= (3 + epsilon_x)^2 + (4 + epsilon_y)^2 approx 25 + 6 epsilon_x + 8 epsilon_y. $ Now the idea that will let us do geometry is to replace the pair of numbers $epsilon_x$ and $epsilon_y$ with a single "small displacement" vector $bf(v) = vec(epsilon_x, epsilon_y)$, and the pair of numbers $6$ and $6$ with the vector $vec(6,8)$ instead, so that *the approximation part just becomes a dot product*: $ f(vec(3,4) + bf(v)) approx f(vec(3,4)) + vec(6,8) dot bf(v). $ #warning(title: [Warning: the directional derivative sucks])[ In some places you see the abbreviation $D_bf(v) f (P) := nabla f (P) dot bf(v)$ and the name "directional derivative" for it. I hate this term, because some people have different notations and definitions (according to Wikipedia, some authors require $bf(v)$ to be a unit vector, etc.). So I will always just write the dot product $nabla f (P) dot bf(v)$ instead, which is unambiguous and means you have one less symbol to remember. The gradient does everything directional derivative can do, and does it better. ] In full abstraction, we can rewrite linear approximation as: #memo(title: [Memorize: Linear approximation])[ Suppose $f$ is differentiable at a point $P$. Then for small displacement vectors $bf(v)$, *linear approximation* promises that $ f(P + bf(v)) approx f(P) + nabla f(P) dot bf(v). $ In other words the net change from $f(P)$ to $f(P + bf(v))$ is approximated by the dot product $nabla f(P) dot bf(v)$. ] Up until now, all we've done is rewrite the earlier equation with a different notation; so far, nothing new has been introduced. Why did we do all this work to use different symbols to say the same thing? The important idea is what I told you a long time ago: *anything you used to think of in terms of slopes, you should rethink in terms of normal vectors*. It turns out that to complete the analogy to differentiation, the normal vector is going to be that gradient $nabla f(P)$, and we'll see why in just a moment (spoiler: it's because of the dot product). For now, you should just know that $nabla f(P)$ is _going to be_ the right way to draw pictures of all $n$ rates of change at once, although I haven't explained why yet. Before going on, let's write down the recipes and some examples just to make sure the _definition_ of the gradient makes sense, then I'll explain why the gradient is the normal vector we need to complete our analogy. == [RECIPE] Calculating the gradient #recipe(title: [Recipe for calculating the gradient])[ 1. Compute every partial derivative of the given function. 2. Output the vector whose components are those partial derivatives. ] #sample[ Consider the six functions $ f_1(x,y) = x^3 y^2 + cos(y), &#h(2em) f_2(x,y,z) = e^(x y z) \ f_3(x,y) = x^2 + y^2, &#h(2em) f_4(x,y,z) = x+y+z \ f_5(x,y,z) = x y + y z + z x &#h(2em) f_6(x,y) = x^y $ from back in @text-compute-partial and @recipe-compute-partial. Compute their gradients. ] #soln[ Take the partial derivatives we already computed and make them the components: $ nabla f_1 (x,y) = vec(3x^2 y^2, 2 x^3 y - sin(y)), &#h(2em) nabla f_2 (x,y) = vec( y z e^(x y z), x z e^(x y z), x y e^(x y z) ), \ nabla f_3 (x,y) = vec(2 x, 2 y), &#h(2em) nabla f_4 (x,y,z) = vec(1,1,1), \ nabla f_5 (x,y,z) = vec(y+z, x+z, x+y), &#h(2em) nabla f_6 (x,y) = vec(y x^(y-1), ln(y) dot x^y). #qedhere $ ] == [RECIPE] Linear approximation We actually could have stated an equivalent recipe right after we defined partial derivatives, but conceptually I think it's better to think of everything in terms of the gradient, so I waited until after I had defined the gradient to write the recipe. #recipe(title: [Recipe for linear approximation])[ To do linear approximation of $f(P + bf(v))$ for a small displacement vector $bf(v)$: 1. Compute $nabla f (P)$, the gradient of $f$ at the point $P$. 2. Take the dot product $nabla f(P) dot bf(v)$ to get a number, the approximate change. 3. Output $f(P)$ plus the change from the previous step. ] #sample[ Let $f(x, y) = x^2 + y^2$. Approximate the value of $f(3.01, 4.01)$ by using linear approximation from $(3,4)$. ] #soln[ Compute the gradient by taking both partial derivatives: $ nabla f(x, y) = vec(2x, 2y). $ So the gradient vector at the starting point is given by $ nabla f(3, 4) = vec(2 dot 3, 2 dot 4) = vec(6, 8). $ The target point $(3.01, 4.01)$ differs from the starting point $(3,4)$ by the displacement $bf(v) = (0.01, 0.01)$. So the approximate change in $f$ is given by $ underbrace(vec(6,8), = nabla f(3,4)) dot underbrace(vec(0.01, 0.01), =bf(v)) = (6 dot 0.01 + 8 dot 0.01) = 0.14. $ Therefore, $ f(3.01, 4.01) approx underbrace(f(3,4), = 25) + 0.14 = 25.14. #qedhere $ ] #sample[ Let $f(x, y) = x^3 - y^3$. Approximate the value of $f(2.01, -1.01)$ by using linear approximation from $(2,-1)$. ] #soln[ Compute the gradient by taking both partial derivatives: $ nabla f(x, y) = vec(3x^2, -3y^2). $ So the gradient vector at the starting point $(2,-1)$ is given by $ nabla f(2, -1) = vec(3(2)^2, -3(-1)^2) = vec(12, -3). $ The target point $(2.01, -1.01)$ differs from the starting point $(2,-1)$ by the displacement $bf(v) = (0.01, -0.01)$. So the approximate change in $f$ is given by $ underbrace(vec(12,-3), = nabla f(2,-1)) dot underbrace(vec(0.01, -0.01), =bf(v)) = (12 dot 0.01 + (-3) dot (-0.01)) = 0.15. $ Therefore, $ f(2.01, -1.01) approx underbrace(f(2,-1), = 9) + 0.15 = 9.14. #qedhere $ ] #sample[ Let $f(x, y) = e^x sin(y) + 777$. Approximate the value of $f(0.04, 0.03)$ by using linear approximation from the point $(0,0)$. ] #soln[ Compute the gradient by taking both partial derivatives: $ nabla f(x,y) = vec(e^x sin y, e^x cos y). $ So the gradient vector at the starting point $(0,0)$ is given by $ nabla f(0,0) = vec(e^0 sin 0, e^0 cos 0) = vec(0,1). $ The target point $(0.04, 0.03)$ differs from the starting point $(0,0)$ by $(0.04, 0.03)$. So the approximate change in $f$ is given by $ underbrace(vec(1,0), = nabla f(0,0)) dot underbrace(vec(0.04, 0.03), =bf(v)) = 0 dot 0.04 + 1 dot 0.03 = 0.04. $ Therefore, $ f(0.04, 0.03) approx underbrace(f(0,0), =777) + 0.03 = 777.03. #qedhere $ ] == [TEXT] Gradient descent At the end of @text-gradient, we promised the geometric definition of the dot product would pay dividends. We now make good on that promise. The motivating question here is: #question[ Let $f(x,y) = x^2 + y^2$. Imagine we're standing at the point $P = (3,4)$. We'd like to take a step $0.01$ away in some direction of our choice. For example, we could go to $(2.99, 4)$, or $(3, 4.01)$ or $(2.992, 4.006)$, or any other point on the circle we've marked in the figure below. (For the third point, note that $sqrt((3-2.992)^2-(4.006)^2) = 0.01$, so that point is indeed $0.01$ away.) - Which way should we step if we want to maximize the $f$-value at the new point? - Which way should we step if we want to the $f$-value to stay about the same? - Which way should we step if we want to minimize the $f$-value at the new point? ] You can see a cartoon of the situation in @fig-grad-descent. Note that this figure is not to scale, because $0.01$ is too small to be legibly drawn, so the black circle is drawn much larger than it actually is. #figure( image("figures/grad-gdescent.png", width: auto), caption: [Starting from $P = (3,4)$, we make a step $bf(v)$ away, where $|bf(v)|=0.01$. Not to scale.], ) <fig-grad-descent> To answer the question, we use the geometric interpretation of the dot product now. Remember that the change in $f$ is approximated by $ f(P + bf(v)) - f(P) approx nabla f (P) dot bf(v). $ The geometric definition of the dot product is that it equals $ nabla f (P) dot bf(v) = |nabla f(P)| |bf(v)| cos theta $ where $theta$ is the included angle. But $|nabla f(P)|$ is fixed (in this example, it's $sqrt(6^2+8^2)=10$) and $|bf(v)|$ is fixed as well (in this example we chose it to be the small number $0.01$). So actually all we care about is the angle $theta$! Think about that for a moment. Then remember how the cosine function works: - $cos(0 degree) = 1$ is the most positive value of the cosine, and that occurs when $bf(v)$ and $nabla f(P)$ point the same direction. - $cos(180 degree) = -1$ is the most negative value of the cosine, and that occurs when $bf(v)$ and $nabla f(P)$ point opposite directions. - If $nabla f (P)$ and $bf(v)$ are perpendicular (so $theta = 90 degree$ or $theta = 270 degree$), then the dot product is zero. Translation: #memo[ - Move *along* the gradient to increase $f$ as quickly as possible. - Move *against* the gradient to decrease $f$ as quickly as possible. - Move *perpendicular to* the gradient to avoid changing $f$ by much either direction. ] == [TEXT] Normal vectors to the tangent line/plane We only need to add one more idea: _keeping $f$ about the same should correspond to moving along the tangent line or plane_. Indeed, in the 2D case, the tangent line is the line that "hugs" the level curve the closest, so we think of it as the direction causing $f$ to avoid much change. The same is true for a tangent plane to a level surface in the 3D case; the plane hugs the curve near the point $P$. So that means the last bullet could be rewritten as #memo[ The gradient $nabla f (P)$ is normal to the tangent line/plane at $P$. It points towards the direction that increases $f$. ] #example[ In the previous example with a level curve, the gradient pointed away from the interior. This is not true in general. For example, imagine instead the function $ f(x,y) = 1 / (x^2 + y^2). $ The point $(3,4)$ lies on the level curve of $f(3,4) = 1/25$. The level curve of $f(x,y)$ with value $1/25$ is _also_ a circle of radius $5$, because it corresponds to the equation $1/(x^2+y^2) = 1/25$. However, the gradient looks quite different: with enough calculation one gets $ nabla f(x,y) = vec((-2x) / ((x^2+y^2)^2), (-2y) / ((x^2+y^2)^2)). $ Evaluating at $(3,4)$, we get $ nabla f(3,4) = vec(-6/625, -8/625). $ Hence, for the function $f(x,y) = 1/(x^2+y^2)$, drawing the figure analogous to @fig-grad-descent gives something that looks quite similar, except the green arrow points the _other_ way and is way smaller. This makes sense: as you move _towards_ the origin, you expect $1/(x^2+y^2)$ to get larger. See @fig-grad-descent-2. ] #figure( image("figures/grad-gdescent2.png", width: auto), caption: [Similar picture but for $f(x,y) = 1/(x^2+y^2)$. It looks very similar to @fig-grad-descent, but now the gradient points the other way and has much smaller absolute value, indicating that the value of $f$ increases as we go _towards_ the center (but only slightly). Not to scale.] ) <fig-grad-descent-2> #remark[ Back in the 3D geometry in the linear algebra part of the course, we usually neither knew nor cared what the sign and magnitude of the normal vector was. That is, when asked "what is a normal vector to the plane $x-y+2z=8$?", you could answer $vec(1,-1,2)$ or $vec(-1,1,-2)$ or even $vec(-100, 100, -200)$. But this doesn't apply to the gradient anymore: while it is a normal vector to the tangent line/plane, the magnitude carries additional information we shouldn't just throw away. ] == [RECIPE] Computing tangent lines/planes to level curves/surfaces At this point, we can compute tangent lines and planes easily. We apply the old recipe in @recipe-plane-known-dir (finding a plane given a point with a known normal vector) with $nabla f (P)$ as the normal vector. To spell it out: #recipe(title: [Recipe: Tangent line/plane to level curve/surface])[ To find the tangent line/plane to a level curve/surface of a function $f$ at point $P$: 1. Compute the gradient $nabla f$. This is a normal vector, so it tells you the left-hand side for the equation of the line/plane. 2. Adjust the right-hand side so it passes through $P$, like in @recipe-plane-known-dir. ] #sample[ Find the tangent line to $x^2 + y^2 = 25$ at the point $(3, 4)$. ] #soln[ Let $f(x,y) = x^2 + y^2$, so we are looking at the level curve for $25$ of $f$. We have seen already that $ nabla f = vec(6, 8). $ Hence, the tangent line should take the form $ 6x + 8y = d $ for some $d$. To pass through $P = (3,4)$, we need $d = 6 dot 3 + 8 dot 4$, so the answer is $ 6 x + 8 y = 50. #qedhere $ ] #todo[A couple more examples here would be nice...] == [RECAP] A recap of Part Echo on Multivariable Differentation Let's summarize the last few sections. - We replaced the old graphs we used in 18.01 with level curve and level surface pictures in @sec-level-curve. These new pictures differed from 18.01 pictures because all the variables on the axes are inputs now, and we treat them all with equal respect. - We explained in @sec-partial-derivative how to take a partial derivative of $f(x,y)$ or $f(x,y,z)$, which measures the change in just one of the variables. - We used these partial derivatives to define the gradient $nabla f$ in @sec-gradient. This made linear approximation into a dot product, where $f(P + bf(v)) approx f(P) + nabla f(P) dot bf(v)$ for a small displacement $bf(v)$. - Using the geometric interpretation of a dot product, $nabla f (P)$ was a normal vector to the level curve of $f$ passing through $P$, and: - Going along the gradient increases $f$ most rapidly - Going against the gradient decreases $f$ most rapidly - Going perpendicular to the gradient puts you along the tangent line or plane at $P$. == [EXER] Exercises #exer[ Find the tangent plane to the sphere $x^2 + y^2 + z^2 = 14$ at the point $(1,2,3)$. ] #exer[ The level curve of a certain differentiable function $f(x,y)$ for the value $-7$ turns out to be a circle of radius $2$ centered at $(0,0)$. - Give an example of one such function $f$. - What are all possible vectors that $nabla f(1.2, -1.6)$ could be? - Do linear approximation to estimate $f(1.208, -1.594)$ starting from the point $(1.2, -1.6)$. ] #exer[ For each part, either give an example of $f$ or show that none exist. - Can you find a function $f : RR^2 -> RR^2$ such that $nabla f (x,y) = vec(x,y)$? - Can you find a function $f : RR^2 -> RR^2$ such that $nabla f (x,y) = vec(100 x,y)$? - Can you find a function $f : RR^2 -> RR^2$ such that $nabla f (x,y) = vec(y,x)$? - Can you find a function $f : RR^2 -> RR^2$ such that $nabla f (x,y) = vec(100 y,x)$? ] #exer[ Let $cal(S)$ be the level surface of $f(x,y,z) = e^x + e^(2y) + e^(3z)$ that passes through the origin. Find all real numbers $t$ such that the vector $vec(t+4, t+5, t+6)$ is tangent to $cal(S)$ at the origin. ] #exer[ Let $f(x,y,z)$ be a differentiable function, and let $g(x,y,z) = e^(f(x,y,z))$. Let $P$ be any point in $RR^3$. Suppose $f(P) = 2$, and $nabla f(P)$ is a unit vector. Find the magnitude of $nabla g(P)$. ] #exer[ Let $a$, $b$, $c$ be real numbers and consider the function $ f(x,y) = a e^(x+y) + b e^(x-y). $ It turns out that the level curve of $f$ for the value $c$ passes through $(log 6, log 3)$ is tangent to the line $y = 5x$ at the origin. Find $a$, $b$, and $c$. ]
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/README.md
markdown
# Khawarizmiyyaat Visuelle Erklärungen von Algorithmen, welche einfach zu verstehen sind. Erstellt mit Typst. PDF-Download: [github.com/noahjutz/ad/releases/latest](https://github.com/noahjutz/ad/releases/latest) ## Compiling ``` git clone https://github.com/noahjutz/AD-assets.git typst c --font-path . main.typ ``` ## Lizenz Khawarizmiyyaat by <NAME> is marked with CC0 1.0. To view a copy of this license, visit https://creativecommons.org/publicdomain/zero/1.0/
https://github.com/SkytAsul/trombinoscope
https://raw.githubusercontent.com/SkytAsul/trombinoscope/main/README.md
markdown
MIT License
# Trombinoscope / Face Book This is a Typst/Python/Bash project that makes creation of a face book fast and easy. It was originally created for the French engineering school INSA Rennes, but can easily be adapted to every school in the world. ## Instructions 1. Place in the `/raw` directory all the raw image files, following the `Department/Year/Group` hierarchy. They must be in the format `.JPG`. 1. Also place the `.xlsx` files in the same hierarchy. 1. Put the wanted background image in the `trombinoclean` directory, under the name `bg_big.jpg`. 1. Launch the `/convert-raw.sh` script. This will : 1. Read pictures in `/raw` *that have not already been converted* 1. Convert the green screen to the background image 1. Detect the faces in those pictures 1. Crop around those faces, or around a center point if the face detection has failed 1. Resize the pictures to a much lower size (270 in width and keeping the same ratio, customizable) 1. Save the edited picture in `/data` in the `.JPG` format 1. Remove all previously existing `.csv` files in `/data` 1. Convert all `.xlsx` files (Google Sheets export / Excel files) from `/raw` to `.csv` ones in `/data` - yes, this step will take a long time and will burn your computer 1. Put the `GroupsData.csv` file in `/data`. 1. Do `typst compile trombi.typ`. 1. Ta-dam! ## Image dimensions - Images should have the *same* dimensions as the background image (in 2024, 4000x6000). - They can be rotated *if and only if* the file contains the necessary EXIF attributes to make the scripts understand their orientation (i.e., if you open the file with an image viewer, it is automatically in the right orientation). - Images should have the `.JPG` format (case-sensitive). - They are automatically cropped around detected face with customizable percentages. They are also resized to a smaller size (in 2024, 270x303). - Those peculiarities can be changed in the `replacehsv.py` Python script.
https://github.com/isaacew/aiaa-typst
https://raw.githubusercontent.com/isaacew/aiaa-typst/master/template.typ
typst
//*************************************************************** // AIAA TYPST TEMPLATE // // The author of this work hereby waives all claim of copyright // (economic and moral) in this work and immediately places it // in the public domain; it may be used, distorted or // in any manner whatsoever without further attribution or notice // to the creator. The author is not responsible for any liability // from the usage or dissemination of this code. // // Author: <NAME>, <NAME> // Date: 06 NOV 2023 // BAMDONE! //*************************************************************** // This function gets your whole document as its `body` and formats // it as an article in the style of the AIAA. #let aiaa( // The paper's title. 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-and-affiliations: (), // The paper's abstract. Can be omitted if you don't have one. abstract: none, // A list of index terms to display after the abstract. index-terms: (), // The article's paper size. Also affects the margins. paper-size: "us-letter", // The path to a bibliography file if you want to cite some external // works. bibliography-file: none, // The paper's content. body, ) = { // Set document metdata. set document( title: title, author: authors-and-affiliations.filter(a => "name" in a).map(a => a.name) ) // Set the body font. set text( font: "Times New Roman", top-edge: 5pt, ) // Configure the page. set page( paper: paper-size, // The margins depend on the paper size. margin: if paper-size == "a4" { (x: 41.5pt, top: 80.51pt, bottom: 89.51pt) } else { ( x: (72pt / 216mm) * 100%, top: (72pt / 279mm) * 100%, bottom: (72pt / 279mm) * 100%, ) } ) // Configure equation numbering and spacing. set math.equation(numbering: "(1)", supplement: [Eq.]) show math.equation: set block(spacing: 0.65em) // Configure appearance of equation references show ref: it => { let eq = math.equation let el = it.element if el != none and el.func() == eq { // Override equation references. link( el.label, [#el.supplement #numbering( el.numbering, ..counter(eq).at(el.location()) )] ) } else { // Other references as usual. it } } // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Configure headings. set heading( numbering: "I.A.1." ) show heading: it => locate(loc => { // Find out the final number of the heading counter. let levels = counter(heading).at(loc) let deepest = if levels != () { levels.last() } else { 1 } set text(11pt, weight: "bold", font: "Times New Roman") 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]) #v(1.65em, weak: true) #set align(center) #set text(size: 11pt, weight: "bold", font: "Times New Roman") // #show: smallcaps // #v(20pt, weak: true) #if it.numbering != none and not is-ack { numbering("I.", deepest) // h(7pt, weak: true) } #it.body #v(0.65em, weak: true) ] else if it.level == 2 [ // Second-level headings are run-ins. #v(1.65em, weak: true) #set par(first-line-indent: 0pt) // #v(16pt, weak: true) #set text(weight: "bold", size: 10pt) // #v(11pt, weak: true) #if it.numbering != none { numbering("A.", deepest) h(7pt, weak: true) } #it.body ] else [ // Third level headings are run-ins too, but different. #if it.level == 3 { numbering( "1)" , deepest) [ ] } _#(it.body):_ ] }) // Display the paper's title. v(3pt, weak: true) align(center, text(weight: "bold", 24pt, font: "Times New Roman", title)) v(8.35mm, weak: true) // Display the authors and affiliations list. { set align(center) for author-or-affil in authors-and-affiliations { // entry is an author if "name" in author-or-affil { set text(16pt, top-edge:16pt) let author-footer = { if "job" in author-or-affil [#author-or-affil.job] if "department" in author-or-affil [, #author-or-affil.department] if "aiaa" in author-or-affil [, #author-or-affil.aiaa] [.] } [#author-or-affil.name #footnote[#author-footer] ] // the entry is an affiliation } else { set text(12pt, top-edge: 10pt, style:"italic") [\ #author-or-affil.institution] if "city" in author-or-affil [, #author-or-affil.city] if "state" in author-or-affil [, #author-or-affil.state] if "zip" in author-or-affil [, #author-or-affil.zip] if "country" in author-or-affil [, #author-or-affil.country] [\ ] } } } // Configure Figures show figure.caption: strong set figure.caption(separator:" ") set figure(numbering: "1", supplement: [Fig.]) // Configure Tables show figure.where(kind: table): set figure.caption(position: top) show figure.where(kind: table): set figure(supplement: [Table]) // Configure paragraph properties. show: columns.with(1, gutter: 0pt) set par(justify: true, first-line-indent: 1.5em) show par: set block(spacing: 0.65em) // Display abstract and index terms. if abstract != none [ #text(10pt, weight: "bold", table( stroke: none, align: left, gutter: 0pt, columns: (36pt, auto, 36pt), [],[ #h(1.5em) #abstract], [] ) ) ] // Display the paper's contents. body // Display bibliography. if bibliography-file != none { show bibliography: set text(9pt) bibliography(bibliography-file, title: text(10pt)[References], style: "american-institute-of-aeronautics-and-astronautics") } } #let bEquation = it => { [#set math.equation(numbering: "(1)", supplement: "Equation") #show math.equation: set block(spacing: 0.65em) // Configure appearance of equation references #show ref: it => { let eq = math.equation let el = it.element if el != none and el.func() == eq { // Override equation references. link( el.label, [Equation #numbering( el.numbering, ..counter(eq).at(el.location()) )] ) } else { // Other references as usual. it } } #it ] } #let nomenclature(..quantities) = { let q = quantities.pos() [= Nomenclature #table( stroke: none, row-gutter: -3pt, columns: (auto, auto, auto), align: left, ..q.map( ((k,v)) => ([#k], [$=$], v) ).flatten() ) ] } // DROPCAP TOOL // Element function for space. #let space = [ ].func() // Elements that can be split and have a 'body' field. #let splittable = (strong, emph, underline, stroke, overline, highlight) // Sets the font size so the resulting text height matches the given height. // // If not specified otherwise in "text-args", the top and bottom edge of the // resulting text element will be set to "bounds". // // Parameters: // - height: The target height of the resulting text. // - threshold: The maximum difference between target and actual height. // - text-args: Arguments to be passed to the underlying text element. // - body: The content of the text element. // // Returns: The text with the set font size. #let sized(height, ..text-args, threshold: 0.1pt, body) = style(styles => { let text = text.with( top-edge: "bounds", bottom-edge: "bounds", ..text-args.named(), body ) let size = height let font-height = measure(text(size: size), styles).height // This should only take one iteration, but just in case... while calc.abs(font-height - height) > threshold { size *= 1 + (height - font-height) / font-height font-height = measure(text(size: size), styles).height } return text(size: size) }) // Attaches a label after the split elements. // // The label is only attached to one of the elements, preferring the second // one. If both elements are empty, the label is discarded. If the label is // empty, the elements remain unchanged. #let attach-label((first, second), label) = { if label == none { (first, second) } else if second != none { (first, [#second#label]) } else if first != none { ([#first#label], second) } else { (none, none) } } // Tries to extract the first letter of the given content. // // If the first letter cannot be extracted, the whole body is returned as rest. // // Returns: A tuple of the first letter and the rest. #let extract-first-letter(body) = { if type(body) == str { let letter = body.clusters().at(0, default: none) if letter == none { return (none, body) } let rest = body.clusters().slice(1).join() return (letter, rest) } if body.has("text") { let (text, ..fields) = body.fields() let label = if "label" in fields { fields.remove("label") } let func(it) = if it != none { body.func()(..fields, it) } let (letter, rest) = extract-first-letter(body.text) return attach-label((letter, func(rest)), label) } if body.func() in splittable { let (body: text, ..fields) = body.fields() let label = if "label" in fields { fields.remove("label") } let func(it) = if it != none { body.func()(..fields, it) } let (letter, rest) = extract-first-letter(text) return attach-label((letter, func(rest)), label) } if body.has("child") { // We cannot create a 'styled' element, so set/show rules are lost. let (letter, rest) = extract-first-letter(body.child) return (letter, rest) } if body.has("children") { let child-pos = body.children.position(c => { c.func() not in (space, parbreak) }) if child-pos == none { return (none, body) } let child = body.children.at(child-pos) let (letter, rest) = extract-first-letter(child) if body.children.len() > child-pos { rest = (rest, ..body.children.slice(child-pos+1)).join() } return (letter, rest) } } // Gets the number of words in the given content. #let size(body) = { if type(body) == str { body.split(" ").len() } else if body.has("text") { size(body.text) } else if body.has("child") { size(body.child) } else if body.has("children") { body.children.map(size).sum() } else if body.func() in splittable { size(body.body) } else { 1 } } // Tries to split the given content at a given index. // // Content is split at word boundaries. A sequence can be split at any of its // childrens' word boundaries. // // Returns: A tuple of the first and second part. #let split(body, index) = { if type(body) == str { let words = body.split(" ") if index >= words.len() { return (body, none) } let first = words.slice(0, index).join(" ") let second = words.slice(index).join(" ") return (first, second) } if body.has("text") { let (text, ..fields) = body.fields() let label = if "label" in fields { fields.remove("label") } let func(it) = if it != none { body.func()(..fields, it) } let (first, second) = split(text, index) return attach-label((func(first), func(second)), label) } if body.func() in splittable { let (body: text, ..fields) = body.fields() let label = if "label" in fields { fields.remove("label") } let func(it) = if it != none { body.func()(..fields, it) } let (first, second) = split(text, index) return attach-label((func(first), func(second)), label) } if body.has("child") { // We cannot create a 'styled' element, so set/show rules are lost. let (first, second) = split(body.child, index) return (first, second) } if body.has("children") { let first = () let second = () // Find child containing the splitting point and split it. for (i, child) in body.children.enumerate() { let child-size = size(child) index -= child-size if index <= 0 { // Current child contains splitting point. let sub-index = child-size + index let (child-first, child-second) = split(child, sub-index) first.push(child-first) second.push(child-second) second += body.children.slice(i + 1) // Add remaining children break } else { first.push(child) } } return (first.join[], second.join[]) } // Element cannot be split, so put everything in second part. return (none, body) } // Shows the first letter of the given content in a larger font. // // The first letter is extracted from the content, and the content is split, so // that the content is wrapped around the first letter. // // Parameters: // - height: The height of the first letter. Can be given as the number of // lines (integer) or as a length. // - justify: Whether to justify the text next to the first letter. // - hanging-indent: The indent of lines after the first line. // - gutter: The space between the first letter and the text. // - transform: A function to be applied to the first letter. // - text-args: Arguments to be passed to the underlying text element. // - body: The content to be shown. // // Returns: The content with the first letter shown in a larger font. #let dropcap( height: 2, justify: false, hanging-indent: 8pt, gutter: 0pt, transform: none, ..text-args, body ) = layout(bounds => style(styles => { // Split body into first letter and rest of string let (letter, rest) = extract-first-letter(body) if transform != none { letter = transform(letter) } // Sample content for height of given amount of lines let letter-height = if type(height) == int { let sample-lines = range(height).map(_ => [x]).join(linebreak()) measure(sample-lines, styles).height } else { measure(v(height), styles).height } // Create dropcap with the height of sample content let letter = sized(letter-height, letter, ..text-args) let letter-width = measure(letter, styles).width // Try to justify as many words as possible next to dropcap let bounded = box.with(width: bounds.width - letter-width - gutter) let index = 1 let (first, second) = while true { let (first, second) = split(rest, index) let first = { set par(hanging-indent: hanging-indent, justify: justify) first } if second == none { // All content fits next to dropcap. (first, none) break } // Allow a bit more space to accommodate for larger elements. let max-height = letter-height + measure([x], styles).height / 2 let height = measure(bounded(first), styles).height if height > max-height { split(rest, index - 1) break } index += 1 } // Layout dropcap and aside text as grid set par(justify: justify) box(grid( column-gutter: gutter, columns: (letter-width, 1fr), letter, { set par(hanging-indent: hanging-indent) first if second != none { linebreak(justify: justify) } } )) second }))
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-bare-01.typ
typst
Other
// Test bare show in content block. A #[_B #show: c => [*#c*]; C_] D
https://github.com/Amirhosein-GPR/university_notes
https://raw.githubusercontent.com/Amirhosein-GPR/university_notes/main/assets/typst/templates/note.typ
typst
#let note(doc, paper: str, flipped: bool, first_page_font_size: relative, font_size: relative, image_path: str, image_width: relative, topic: str, problem_topic: str, black_and_white: bool, version: str, authors_name: (), professors_name: (), date: str, faculty: str, phase: str, info_color: luma(50), no_responsibility: false, should_fill: true) = { let red_color = rgb(200, 0, 0) let orange_color = rgb(220, 100, 0) let yellow_color = rgb(130, 130, 0) let green_color = rgb(0, 120, 0) let blue_color = rgb(0, 100, 200) let dark_blue_color = rgb(0, 0, 200) let purple_color = rgb(150, 0, 150) let gold_color = rgb(255, 215, 0) let brown_color = rgb(125, 50, 0) if black_and_white { red_color = rgb(0, 0, 0, 255) orange_color = rgb(0, 0, 0, 255) yellow_color = rgb(0, 0, 0, 255) green_color = rgb(0, 0, 0, 255) blue_color = rgb(0, 0, 0, 255) dark_blue_color = rgb(0, 0, 0, 255) purple_color = rgb(0, 0, 0, 255) } set page( header: locate(loc => { set text( fill: black ) if counter(page).at(loc).first() > 1 { block()[ #grid( columns: (1fr, 1fr, 1fr), row-gutter: 0.5em, align(right + horizon)[ #topic ], align(center + horizon)[ #let previous_heading = query( selector(heading.where(level: 2)).before(here()) ) #if previous_heading.len() > 0 { previous_heading.last().body } ], align(left + horizon)[ #image(image_path, height: 2em) ], line(length: 300%) ) ] } }), numbering: (..nums) => { locate(loc => { if counter(page).at(loc).first() > 1 { text(stylistic-set: 1)[ #nums.pos().at(0) ] } }) }, paper: paper, flipped: flipped, margin: (x: 1cm, y: 2cm) ) set heading( numbering: (..nums) => { nums.pos().map(num => { box[#num] }).rev().join(".") } ) show heading: arg => { set par(justify: false) arg } show heading.where(level: 1): arg => { counter(figure.where(kind: image)).update(0) counter(figure.where(kind: table)).update(0) counter(figure.where(kind: raw)).update(0) let fill_color if should_fill { fill_color = red_color } else { fill_color = rgb(0, 0, 0, 0) } block(above: 0.8em)[ #grid( columns: (16%, 82%), gutter: 2%, align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: red_color, thickness: 0.15em))[ #text(stylistic-set: 1, dir: ltr, fill: red_color)[ #counter(heading).display() ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: red_color), fill: fill_color.lighten(97%))[ #text(stylistic-set: 1, dir: ltr)[ #counter(heading).display() ] ] } ], align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: red_color, thickness: 0.15em))[ #text(fill: red_color)[ #arg.body ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: red_color), fill: fill_color.lighten(97%))[ #text()[ #arg.body ] ] } ] ) ] } show heading.where(level: 2): arg => { let fill_color if should_fill { fill_color = blue_color } else { fill_color = rgb(0, 0, 0, 0) } block(above: 0.8em)[ #grid( columns: (16%, 82%), gutter: 2%, align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: blue_color, thickness: 0.15em))[ #text(stylistic-set: 1, fill: blue_color)[ #counter(heading).display() ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: blue_color), fill: fill_color.lighten(97%))[ #text(stylistic-set: 1)[ #counter(heading).display() ] ] } ], align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: blue_color, thickness: 0.15em))[ #text(fill: blue_color)[ #arg.body ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: blue_color), fill: fill_color.lighten(97%))[ #text()[ #arg.body ] ] } ] ) ] } show heading.where(level: 3): arg => { let fill_color if should_fill { fill_color = green_color } else { fill_color = rgb(0, 0, 0, 0) } block(above: 0.8em)[ #grid( columns: (16%, 82%), gutter: 2%, align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: green_color, thickness: 0.15em))[ #text(stylistic-set: 1, fill: green_color)[ #counter(heading).display() ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: green_color), fill: fill_color.lighten(97%))[ #text(stylistic-set: 1)[ #counter(heading).display() ] ] } ], align(center)[ #if black_and_white { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (paint: green_color, thickness: 0.15em))[ #text(fill: green_color)[ #arg.body ] ] } else { block(inset: 1em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: green_color), fill: fill_color.lighten(97%))[ #text()[ #arg.body ] ] } ] ) ] } show heading.where(level: 4): arg => { let fill_color if should_fill { fill_color = purple_color } else { fill_color = rgb(0, 0, 0, 0) } block(above: 0.8em)[ #grid( columns: (16%, 82%), gutter: 2%, align(center)[ #if black_and_white { block(inset: 0.9em, radius: 0.2em, width: 100%, stroke: (paint: purple_color, thickness: 0.15em))[ #text(stylistic-set: 1, fill: purple_color, size: 0.9em)[ #counter(heading).display() ] ] } else { block(inset: 0.9em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: purple_color), fill: fill_color.lighten(97%))[ #text(stylistic-set: 1, size: 0.9em)[ #counter(heading).display() ] ] } ], align(center)[ #if black_and_white { block(inset: 0.9em, radius: 0.2em, width: 100%, stroke: (paint: purple_color, thickness: 0.15em))[ #text(fill: purple_color, size: 0.9em)[ #arg.body ] ] } else { block(inset: 0.9em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: purple_color), fill: fill_color.lighten(97%))[ #text()[ #arg.body ] ] } ] ) ] } show heading.where(level: 5): arg => { let fill_color if should_fill { fill_color = orange_color } else { fill_color = rgb(0, 0, 0, 0) } block(above: 0.8em)[ #grid( columns: (16%, 82%), gutter: 2%, align(center)[ #if black_and_white { block(inset: 0.8em, radius: 0.2em, width: 100%, stroke: (paint: orange_color, thickness: 0.15em))[ #text(stylistic-set: 1, fill: orange_color, size: 0.8em)[ #counter(heading).display() ] ] } else { block(inset: 0.8em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: orange_color), fill: fill_color.lighten(97%))[ #text(stylistic-set: 1, size: 0.8em)[ #counter(heading).display() ] ] } ], align(center)[ #if black_and_white { block(inset: 0.8em, radius: 0.2em, width: 100%, stroke: (paint: orange_color, thickness: 0.15em))[ #text(fill: orange_color, size: 0.8em)[ #arg.body ] ] } else { block(inset: 0.8em, radius: 0.2em, width: 100%, stroke: (thickness: 0.15em, paint: orange_color), fill: fill_color.lighten(97%))[ #text(size: 0.8em)[ #arg.body ] ] } ] ) ] } set text( font: "Vazirmatn", dir: rtl ) set par( justify: true, leading: 0.8em ) set enum( full: true, numbering: "1.1)" ) show enum: arg => { text(stylistic-set: 1, number-width: "tabular")[ #arg ] } show outline.entry: it => { set text(stylistic-set: 1, number-width: "tabular", dir: rtl) it.body h(1em) box(width: 1fr)[#repeat([.])] h(1em) box()[#it.page] } set text(size: first_page_font_size) set figure( supplement: "شکل", numbering: arg => box()[ #text(dir: ltr)[ #counter(heading.where(level: 1)).display().#arg ] ] ) show figure: arg => { show par: set block(above: 0em) set text(stylistic-set: 1) align(center)[ #block(stroke: black, width: 100%, inset: 1em, radius: (top-left: 0.2em, top-right: 0.2em), clip: true)[ #arg.body ] #box(stroke: black, inset: 1em, width: 100%, radius: (bottom-left: 0.2em, bottom-right: 0.2em))[ #text(baseline: 0em)[ #arg.caption ] ] ] } block(width: 100%, height: 100%)[ #align(center + horizon)[ #image(image_path, width: image_width) #text(size: 1.2em)[ دانشکده #faculty ] #v(2em) #text(size: 1.6em)[ *#topic* ] #v(2em) #text(size: 1.2em)[ استاد درس: #professors_name ] #text(size: 1.2em)[ نویسنده: #authors_name ] #v(4em) #if authors_name != none { block(width: 80%)[ #set block(below: 0pt) #grid( columns: (1fr, 1fr), align(right)[ #date ], align(left)[ #version ] ) #v(1em) #line(length: 100%) ] } #align(bottom)[ #text(size: 1.4em)[ #phase ] ] ] ] if no_responsibility { align(center + horizon)[ #text(weight: "bold")[ #text(fill: blue_color)[ درود بر تو دوست عزیزی که میخوای از این جزوه استفاده کنی D: ] #text(fill: green_color)[ این جزوه، جزوه شخصیم هست و طبیعیه \ که احتمال داره مشکلاتی داشته باشه. ] #text(fill: brown_color)[ بنابراین اگه میخوای ازش استفاده \ کنی، با کمال احترام بدون که ] #v(2em) #block(stroke: (paint: red_color, thickness: 0.2em), inset: 1em, radius: 0.2em)[ #text(fill: red_color)[ هیچ مسئولیتی بابت این جزوه بر عهده \ من نخواهد بود. از جمله موارد زیر: ] #block()[ #align(right)[ #text(fill: red_color, weight: "bold")[ + ناقص بودن جزوه به هر شکلی + وجود هر گونه و هر تعداد اشتباه نگارشی یا علمی ] ] ] ] #v(2em) #text(fill: purple_color)[ بنابراین اگه خواستی از این جزوه استفاده کنی، بهتره \ فقط به این منبع اکتفا نکنی و از کتاب یا جزوه های \ دیگه ای که وجود دارن، استفاده کنی. \ \ \ ] موفق باشی (: ] ] } pagebreak() set text(size: font_size) columns(2)[ #doc ] }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/plotst/0.1.0/lib.typ
typst
Apache License 2.0
#import "/plotst/plotting.typ": * #import "/plotst/axis.typ": axis #import "/plotst/util/classify.typ": class, class_generator, classify
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/06_Jira/00_index.typ
typst
== Jira Issues Die nachfolgenden Kapitel enthalten die noch offenen Jira Issues. #include "01_bugs.typ" #pagebreak() #include "02_stories.typ" #pagebreak() #include "03_dev_stories.typ"
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/hover/builtin.typ
typst
Apache License 2.0
#(/* ident after */ table());
https://github.com/KNnut/neoplot
https://raw.githubusercontent.com/KNnut/neoplot/main/pkg/examples/readme.typ
typst
BSD 3-Clause "New" or "Revised" License
#import "../lib.typ" as gp #let title = [Examples in README] #align(center, text(17pt)[ *#title* ] ) Neoplot is a Typst package to use #link("http://www.gnuplot.info/")[gnuplot] in Typst. #gp.exec("set term svg size 420,160") Execute gnuplot commands: ````typ #gp.exec( kind: "command", ```gnuplot reset; set samples 1000; plot sin(x), cos(x) ``` ) ```` #gp.exec( kind: "command", ```gnuplot reset; set samples 1000; plot sin(x), cos(x) ``` ) Execute a gnuplot script: ````typ #gp.exec( ```gnuplot reset # Can add comments since it is a script set samples 1000 # Use a backslash to extend commands plot sin(x), \ cos(x) ``` ) ```` #gp.exec( ```gnuplot reset # Can add comments since it is a script set samples 1000 # Use a backslash to extend commands plot sin(x), \ cos(x) ``` ) To read a data file: #raw( block: true, read("data/datafile.dat") ) ````typ #gp.exec( ```gnuplot $data <<EOD 0 0 2 4 4 0 EOD plot $data with linespoints ``` ) ```` #gp.exec( ```gnuplot $data <<EOD 0 0 2 4 4 0 EOD plot $data with linespoints ``` ) or ```typ #gp.exec( // Use a datablock since Typst doesn't support WASI "$data <<EOD\n" + // Load "data/datafile.dat" using Typst read("data/datafile.dat") + "EOD\n" + "plot $data with linespoints" ) ``` #gp.exec( // Use a datablock since Typst doesn't support WASI "$data <<EOD\n" + // Load "data/datafile.dat" using Typst read("data/datafile.dat") + "EOD\n" + "plot $data with linespoints" ) To print ```gnuplot $data```: ```typ #gp.exec("print $data") ``` #gp.exec("print $data")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue25.typ
typst
Other
#let x = (a: 5) #let key = "a" #{ x.at(key) = 6 } #x
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheda-seu-thesis/0.2.0/seu-thesis/pages/cover-degree-fn.typ
typst
Apache License 2.0
#import "../utils/packages.typ": fakebold #import "../utils/fonts.typ": 字体, 字号, chineseunderline, justify-words #let degree-cover-conf( author: (CN: "王东南", EN: "<NAME>", ID: "012345"), thesisname: ( CN: "硕士学位论文", EN: [ A Thesis submitted to \ Southeast University \ For the Academic Degree of Master of Touching Fish ], heading: "东南大学硕士学位论文" ), title: ( CN: "摸鱼背景下的Typst模板使用研究", EN: "A Study of the Use of the Typst Template During Touching Fish" ), advisors: ( (CN: "湖牌桥", EN:"<NAME>", CNTitle: "教授", ENTitle: "Prof."), (CN: "苏锡浦", EN:"<NAME>", CNTitle: "副教授", ENTitle: "Associate Prof.") ), school: ( CN: "摸鱼学院", EN: "School of Touchingfish" ), major: ( main: "摸鱼科学", submajor: "计算机摸鱼" ), degree: "摸鱼学硕士", categorynumber: "N94", secretlevel: "公开", UDC: "303", schoolnumber: "10286", committeechair: "张三 教授", readers: ( "李四 副教授", "王五 副教授" ), date: ( CN: ( defenddate: "2099年01月02日", authorizedate: "2099年01月03日", finishdate: "2024年01月15日" ), EN: ( finishdate: "Jan 15, 2024" ) ), degreeform: none, cnabstract: [示例摘要], cnkeywords: ("关键词1", "关键词2"), enabstract: [#lorem(100)], enkeywords: ("Keywords1", "Keywords2"), terminology: none, anonymous: false, ) = page(margin: (top: 2cm, bottom: 2cm, left:2cm, right: 2cm), numbering: none, header: none, footer: none, { set text(font: 字体.宋体, size: 字号.小四, weight: "regular", lang: "zh") set align(center + top) set par(first-line-indent: 0pt) place(top + center, { image("../assets/cover_school.png", height: 11cm) }) place(top + left, dy: 0.5cm, { // 原始模板左侧列和右侧校徽不等高 set text(font: 字体.宋体, size: 字号.小五, weight: "regular", lang: "zh", region: "cn") set align(center) let justify-4em(s) = justify-words(s, width: 4em) grid( columns: (4em, 1em, 8em), row-gutter: 0.4em, justify-4em("学校代码"), ":", chineseunderline(schoolnumber), justify-4em("分类号"), ":", chineseunderline(categorynumber), justify-4em("密级"), ":", chineseunderline(secretlevel), justify-4em("UDC"), ":", chineseunderline(UDC), justify-4em("学号"), ":", chineseunderline(author.ID), ) }) place( top + right, image("../assets/vi/seu_logo.png", width: 1.97cm) ) v(277.3pt) block( height: 100% - 277.3pt, grid( rows: (auto, 1fr, auto, 1fr, auto, 1fr, auto, 1fr, auto), // 大标题,如“硕士学位论文” block(fakebold(text( font: 字体.标题宋体, size: 字号.小初, thesisname.CN ))), // 空间 [], // 标题 + 学位论文形式 { block(text( font: 字体.黑体, size: 字号.一号, title.CN )) if not degreeform in (none, [], [ ], "") { block(text( font: 字体.标题宋体, size: 字号.三号, "(学位论文形式:" + degreeform + ")" ), below: 2em) } }, // 空间 [], // 研究生姓名和导师姓名 { set text(font: 字体.黑体, size: 字号.小二) set par(leading: 1em) grid( columns: (5em, 1em, 10em), row-gutter: 1em, text(font: 字体.宋体)[研究生姓名], [:], {chineseunderline(author.CN)}, text(font: 字体.宋体, justify-words("导师姓名", width: 5em)), [:], chineseunderline( advisors.map(it => it.CN + " " + it.CNTitle).join("\n") ) ) }, // 空间 [], // 下方内容 { let justify-7em(s) = justify-words(s, width: 7em) let justify-6em(s) = justify-words(s, width: 6em) set text(font: 字体.黑体, size: 字号.小四) grid( columns: (17em, 16em), column-gutter: 1em, grid( columns: (7em, 10em), row-gutter: 1em, text(font: 字体.宋体, justify-7em("申请学位类别")), chineseunderline(degree), text(font: 字体.宋体, justify-7em("一级学科名称")), chineseunderline(major.main), text(font: 字体.宋体, justify-7em("二级学科名称")), chineseunderline(major.submajor), text(font: 字体.宋体, "答辩委员会主席"), chineseunderline(committeechair), ), grid( columns: (6em, 10em), row-gutter: 1em, text(font: 字体.宋体, "学位授予单位"), chineseunderline("东 南 大 学"), text(font: 字体.宋体, "论文答辩日期"), chineseunderline(date.CN.defenddate), text(font: 字体.宋体, "学位授予日期"), chineseunderline(date.CN.authorizedate), text(font: 字体.宋体, justify-6em("评阅人")), chineseunderline(readers.join("\n")), ) ) }, // 空间 [], // 日期 text(font: 字体.宋体, size: 字号.四号, date.CN.finishdate) ) ) }) #degree-cover-conf( author: (CN: "王东南", EN: "<NAME>", ID: "012345"), thesisname: ( CN: "硕士学位论文", EN: [ A Thesis submitted to \ Southeast University \ For the Academic Degree of Master of Touching Fish ], heading: "东南大学硕士学位论文" ), title: ( CN: "摸鱼背景下的Typst模板使用研究", EN: "A Study of the Use of the Typst Template During Touching Fish" ), advisors: ( (CN: "湖牌桥", EN:"HU Pai-qiao", CNTitle: "教授", ENTitle: "Prof."), (CN: "苏锡浦", EN:"SU Xi-pu", CNTitle: "副教授", ENTitle: "Associate Prof.") ), school: ( CN: "摸鱼学院", EN: "School of Touchingfish" ), major: ( main: "摸鱼科学", submajor: "计算机摸鱼" ), degree: "摸鱼学硕士", categorynumber: "N94", secretlevel: "公开", UDC: "303", schoolnumber: "10286", committeechair: "<NAME>", readers: ( "李四 副教授", "王五 副教授" ), date: ( CN: ( defenddate: "2099年01月02日", authorizedate: "2099年01月03日", finishdate: "2024年01月15日" ), EN: ( finishdate: "Jan 15, 2024" ) ), degreeform: "应用研究", cnabstract: [示例摘要], cnkeywords: ("关键词1", "关键词2"), enabstract: [#lorem(100)], enkeywords: ("Keywords1", "Keywords2"), terminology: none, anonymous: false, )
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/并行与分布式计算/main.typ
typst
#import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../template.typ": * #show: note.with( title: "并行与分布式计算基础", author: "YHTQ", date: datetime.today().display(), logo: none, ) = 前言 + 教师:杨超 <EMAIL> 智华楼 333 + 给分:作业 50% + 期末(闭卷考试) 50% + 主要内容:MPI(分布式体系), OpenMP(共享内存体系), CUDA(GPU众核) - 计算能力的度量: 通常使用 FLOPS(floating point operations per second,每秒浮点运算次数)来度量计算能力 - 并行计算的原因: 性能 = 主频 #math.times 核数 \ 功耗 = 性能 #math.times $"电压"^2$\ 电压 = 主频 提升主频导致功耗爆炸,只能提升核数 - 异构设计的原因:达成高性能和多功能的平衡 并行计算往往需要设计专门的算法,例如 FFT 对于通常的串行机器是很好的算法,但在分布式计算中不够理想 == 课程内容 - 硬件架构 - 并行算法 - 并行编程 == 并行计算的关注点 - 到解时间 Time to Solution - 伸缩性 Scalability - 效率/功耗 Efficiency - 并发度/数据局部性 Concurrency/Data Locality - 容错性 Resiliency - 可编程性 Programmability - 加速比:当处理器个数增多时,完成任务所需时间的减少比例 - 理想加速比:处理器个数增加比例(假设处理器是同构的) - 并行效率:加速比与处理器个数的比值 == 并行计算的三大定律 #proposition[阿姆达尔][ 记 $alpha in [0, 1]$ 是某任务无法并行计算的部分,假设其工作量固定,则该问题的加速比满足 $S(n) < 1/ alpha$ ] #proof[ 假设串行执行时间为 $1$,则不难验证 $n$ 核并行执行时间不小于 $alpha + (1-alpha)/n > alpha$,故 $S(n) = 1/(alpha + (1-alpha)/n) < 1/alpha$ ] #remark[][ 这个定律表明并行计算对于速度的提升是有上限的,因此早期人们对并行加速十分悲观。1985 年 Karp 打赌没人在十年内为三个实际应用做到 200 倍的并行加速。两年之内确实没有人做到,而两年之后几人就实现了 400-600 倍加速。 ] #proposition[古斯塔法森][ 记 $alpha in [0, 1]$ 是某任务无法并行计算的部分,保持处理时间恒定,令工作量随着处理器个数增加,此时加速比 $S'(n)$ 不存在上界 ] #proof[ 假设单处理器单位时间工作量为 $W$,则 $n$ 个处理器时工作量为: $ W' = alpha W + (1 - alpha) n W $ 加速比为: $ W' / W = alpha + (1 - alpha) n $ ] #proposition[孙-倪][ 记 $alpha in [0, 1]$ 是某任务无法并行计算的部分,假设该任务可并行部分随着处理器个数 $n$ 按照因子 $G(n)$ 缩放,则加速比 $S''(n) = (alpha + (1 - alpha) G(n))/(alpha + (1 - alpha)G(n)/ n)$,这里 $G(n)$ 往往用于描述内存受限的因素。 ] #example[][ 设矩阵乘法的计算复杂度是 $2 N^3$,存储复杂度为 $3 N^2$,假设内存规模为 $x$,对应的最大数据规模为 $(x/3)^(1/2)$,因此: $ G(n) = 3 (((n x)/3)^(1/2))^3 / (3 (((x)/3)^(1/2))^3) = n^(3/2) $ (也就是假设内存和处理器都扩大 $n$ 倍,能够达成的数据规模对应的运行时间比) ] #definition[计算密度][ 计算密度是指单位时间内的计算量与数据量的比值。通常情况下,有: $ "flip"/"second" = min{"peak_flops", "带宽" * "计算密度"} $ ] #definition[单层 AMAT 模型][ 假设只有一级缓存,其中 $T_s$ 是缓存访问时间,$T_m$ 是主存访问时间,$r$ 是缓存失效率,则: $ "AMAT(Average Memory Access Time)" = T_s + r T_m $ ] #definition[多层 AMAT 模型][ 假设有 $n$ 级缓存,其中 $T_s$ 是最后一级缓存访问时间,$T_m$ 是主存访问时间,$r_i$ 是第 $i$ 级缓存整体失效率(也即改层即之前的缓存全部失效的概率),则: $ "AMAT(Average Memory Access Time)" = T_s + r_1 T_1 + r_2 T_2 + ... + r_n T_n $ ] == 共享内存模型 #definition[PRAM 模型][ 并行随机访问机(Parallel Random Access Machine)是一种抽象的计算模型,其中有 $p$ 个处理器,且: - 所有处理器共享一个连续的内存空间 - 每个处理器执行互相独立的命令 - 处理器执行任何一种访存操作的时间是常数 ] 显然共享内存会产生访存冲突,往往会产生如下策略: - EREW(Exclusive Read Exclusive Write):进行读写时,只有一个处理器能够访问 - CREW(Concurrent Read Exclusive Write):多个处理器可以同时读,但只有一个处理器能够写 - ERCW(Exclusive Read Concurrent Write):只有一个处理器能够读,但多个处理器可以写 - CRCW(Concurrent Read Concurrent Write):多个处理器可以同时读写 其中并发写往往会产生冲突,因此又有如下策略: - Common:多个处理器写入相同的值,不需要处理 - Arbitrary:多个处理器随机写入,只有一个写入成功 - Priority:多个处理器写入,按照优先级决定 - Reduction:多个处理器写入,结果是所有写入的值的某种函数 == 分布式计算模型 将计算节点(compute node)通过网络连接起来,每个节点有自己的内存和处理器,节点之间通过消息传递进行通信,往往需要经过某种路由设备。节点之间往往构成一个拓扑结构。 - 跳(hop):拓扑网络上一点到另一点的最短路径 - 网络直径(diameter):拓扑网络上最长的跳数 - 二分宽度(bisection width):将网络分成两半的最小切割数 #definition[$alpha-beta$ 通信模型][ 网络通信时间由时延 $alpha$,带宽 $1/beta$,消息长度 $L$ 决定,通常有: $ T = alpha + L * beta $ ] #definition[BSP 模型][ BSP (Bulk Synchronous Parallel) 模型是一种并行计算模型,其中有 $p$ 个处理器。计算过程分为多个超步,每个超步之内处理器单独计算,超步结束时处理器之间进行通信,同步所有状态。 ] = MPI(Message Passing Interface) MPI 是一种消息传递接口,是一种标准。 == 进程定位 在 MPI 中,每个进程处在一个通信域(communicator)中,每个通信域有一个唯一的标识符,可以通过这个标识符来定位进程。通信域中每个进程有一个标识符,称为 rank == 阻塞/非阻塞通信 == 点对点通信 == 集合通信 == 程序的并行性 #definition[][ 对于两个程序(进程)$P_1, P_2$,记 $I(P), O(P)$ 分别为 $P$ 程序需要读取/写入的数据集合 ] #theorem[Bernstein][ 两个程序 $P_1, P_2$ 可以并行执行,记作 $P_1 || P_2$,如果 $O(P_1) sect I(P_2) = emptyset$ 且 $O(P_2) sect I(P_1) = emptyset$ 且 $O(P_1) sect O(P_2) = emptyset$ ] #definition[][ 不满足 Bernstein 条件的程序会产生竞争条件和数据依赖,也就是两个进程同时访问了相同数据,且至少有一个进程写入了数据。这样的并行程序如果直接执行,其结果将不能确定。具体而言,数据依赖常常分为: - 流依赖:read after write,RAW - 反依赖:write after read,WAR - 输出依赖:write after write,WAW ] #definition[][ 当且仅当所有不可消除(有些数据依赖是可消除的,例如多个数求和即使产生输出依赖也不影响结果)的程序依赖得以满足后,并行程序满足串行一致性。 ] = OpenMP 仅仅依靠消息传递进行并行编程是不足的。OpenMP 是基于线程的共享存储的并行编程模型。OpenMP 基于 PRAGMA 指导语句进行,常用的包括: - ```#pragma omp parallel [clause*]``` 开启并行区,其中常见的从句包括: - if 从句,指定是否开启并行区 - num_threads 从句,指定线程数 - private 从句,指定私有变量列表(并行区内部,for 循环内的变量都会被认为是私有变量) - shared 从句,指定共享变量列表 - default 从句,指定默认共享/私有变量,安全期间可以设为 none,强制指定所有变量 - firstprivate 从句,其中的变量是私有变量,但会自动初始化为主线性中的值 - reduction 从句,指定归约变量,是指私有变量,但最终将以某个操作符进行归约 - ```#pragma omp for [clause*]``` 开启 for 循环并行化,需要在并行区内进行 - ```#pragma omp parallel for [clause*]``` 开启并行区并行化 for 循环 == for 循环限制 为了 OpenMP 可以实现,for 循环的格式有严格限制,包括: - 开始语句:必须是 ```c i = 0``` 这种变量 $=$ 初值 - 终止语句:必须是变量与边界值的大小关系 - 计数语句:必须是等步的加或减 - 不能使用 break, goto, return 等跳转 - 循环变量必须是整数,初值、边界和增量在循环中固定
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A640.typ
typst
Apache License 2.0
#let data = ( ("CYRILLIC CAPITAL LETTER ZEMLYA", "Lu", 0), ("CYRILLIC SMALL LETTER ZEMLYA", "Ll", 0), ("CYRILLIC CAPITAL LETTER DZELO", "Lu", 0), ("CYRILLIC SMALL LETTER DZELO", "Ll", 0), ("CYRILLIC CAPITAL LETTER REVERSED DZE", "Lu", 0), ("CYRILLIC SMALL LETTER REVERSED DZE", "Ll", 0), ("CYRILLIC CAPITAL LETTER IOTA", "Lu", 0), ("CYRILLIC SMALL LETTER IOTA", "Ll", 0), ("CYRILLIC CAPITAL LETTER DJERV", "Lu", 0), ("CYRILLIC SMALL LETTER DJERV", "Ll", 0), ("CYRILLIC CAPITAL LETTER MONOGRAPH UK", "Lu", 0), ("CYRILLIC SMALL LETTER MONOGRAPH UK", "Ll", 0), ("CYRILLIC CAPITAL LETTER BROAD OMEGA", "Lu", 0), ("CYRILLIC SMALL LETTER BROAD OMEGA", "Ll", 0), ("CYRILLIC CAPITAL LETTER NEUTRAL YER", "Lu", 0), ("CYRILLIC SMALL LETTER NEUTRAL YER", "Ll", 0), ("CYRILLIC CAPITAL LETTER YERU WITH BACK YER", "Lu", 0), ("CYRILLIC SMALL LETTER YERU WITH BACK YER", "Ll", 0), ("CYRILLIC CAPITAL LETTER IOTIFIED YAT", "Lu", 0), ("CYRILLIC SMALL LETTER IOTIFIED YAT", "Ll", 0), ("CYRILLIC CAPITAL LETTER REVERSED YU", "Lu", 0), ("CYRILLIC SMALL LETTER REVERSED YU", "Ll", 0), ("CYRILLIC CAPITAL LETTER IOTIFIED A", "Lu", 0), ("CYRILLIC SMALL LETTER IOTIFIED A", "Ll", 0), ("CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS", "Lu", 0), ("CYRILLIC SMALL LETTER CLOSED LITTLE YUS", "Ll", 0), ("CYRILLIC CAPITAL LETTER BLENDED YUS", "Lu", 0), ("CYRILLIC SMALL LETTER BLENDED YUS", "Ll", 0), ("CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS", "Lu", 0), ("CYRILLIC SMALL LETTER IOTIFIED CLOSED LITTLE YUS", "Ll", 0), ("CYRILLIC CAPITAL LETTER YN", "Lu", 0), ("CYRILLIC SMALL LETTER YN", "Ll", 0), ("CYRILLIC CAPITAL LETTER REVERSED TSE", "Lu", 0), ("CYRILLIC SMALL LETTER REVERSED TSE", "Ll", 0), ("CYRILLIC CAPITAL LETTER SOFT DE", "Lu", 0), ("CYRILLIC SMALL LETTER SOFT DE", "Ll", 0), ("CYRILLIC CAPITAL LETTER SOFT EL", "Lu", 0), ("CYRILLIC SMALL LETTER SOFT EL", "Ll", 0), ("CYRILLIC CAPITAL LETTER SOFT EM", "Lu", 0), ("CYRILLIC SMALL LETTER SOFT EM", "Ll", 0), ("CYRILLIC CAPITAL LETTER MONOCULAR O", "Lu", 0), ("CYRILLIC SMALL LETTER MONOCULAR O", "Ll", 0), ("CYRILLIC CAPITAL LETTER BINOCULAR O", "Lu", 0), ("CYRILLIC SMALL LETTER BINOCULAR O", "Ll", 0), ("CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O", "Lu", 0), ("CYRILLIC SMALL LETTER DOUBLE MONOCULAR O", "Ll", 0), ("CYRILLIC LETTER MULTIOCULAR O", "Lo", 0), ("COMBINING CYRILLIC VZMET", "Mn", 230), ("COMBINING CYRILLIC TEN MILLIONS SIGN", "Me", 0), ("COMBINING CYRILLIC HUNDRED MILLIONS SIGN", "Me", 0), ("COMBINING CYRILLIC THOUSAND MILLIONS SIGN", "Me", 0), ("SLAVONIC ASTERISK", "Po", 0), ("COMBINING CYRILLIC LETTER UKRAINIAN IE", "Mn", 230), ("COMBINING CYRILLIC LETTER I", "Mn", 230), ("COMBINING CYRILLIC LETTER YI", "Mn", 230), ("COMBINING CYRILLIC LETTER U", "Mn", 230), ("COMBINING CYRILLIC LETTER HARD SIGN", "Mn", 230), ("COMBINING CYRILLIC LETTER YERU", "Mn", 230), ("COMBINING CYRILLIC LETTER SOFT SIGN", "Mn", 230), ("COMBINING CYRILLIC LETTER OMEGA", "Mn", 230), ("COMBINING CYRILLIC KAVYKA", "Mn", 230), ("COMBINING CYRILLIC PAYEROK", "Mn", 230), ("CYRILLIC KAVYKA", "Po", 0), ("CYRILLIC PAYEROK", "Lm", 0), ("CYRILLIC CAPITAL LETTER DWE", "Lu", 0), ("CYRILLIC SMALL LETTER DWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER DZWE", "Lu", 0), ("CYRILLIC SMALL LETTER DZWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER ZHWE", "Lu", 0), ("CYRILLIC SMALL LETTER ZHWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER CCHE", "Lu", 0), ("CYRILLIC SMALL LETTER CCHE", "Ll", 0), ("CYRILLIC CAPITAL LETTER DZZE", "Lu", 0), ("CYRILLIC SMALL LETTER DZZE", "Ll", 0), ("CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK", "Lu", 0), ("CYRILLIC SMALL LETTER TE WITH MIDDLE HOOK", "Ll", 0), ("CYRILLIC CAPITAL LETTER TWE", "Lu", 0), ("CYRILLIC SMALL LETTER TWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER TSWE", "Lu", 0), ("CYRILLIC SMALL LETTER TSWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER TSSE", "Lu", 0), ("CYRILLIC SMALL LETTER TSSE", "Ll", 0), ("CYRILLIC CAPITAL LETTER TCHE", "Lu", 0), ("CYRILLIC SMALL LETTER TCHE", "Ll", 0), ("CYRILLIC CAPITAL LETTER HWE", "Lu", 0), ("CYRILLIC SMALL LETTER HWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER SHWE", "Lu", 0), ("CYRILLIC SMALL LETTER SHWE", "Ll", 0), ("CYRILLIC CAPITAL LETTER DOUBLE O", "Lu", 0), ("CYRILLIC SMALL LETTER DOUBLE O", "Ll", 0), ("CYRILLIC CAPITAL LETTER CROSSED O", "Lu", 0), ("CYRILLIC SMALL LETTER CROSSED O", "Ll", 0), ("MODIFIER LETTER CYRILLIC HARD SIGN", "Lm", 0), ("MODIFIER LETTER CYRILLIC SOFT SIGN", "Lm", 0), ("COMBINING CYRILLIC LETTER EF", "Mn", 230), ("COMBINING CYRILLIC LETTER IOTIFIED E", "Mn", 230), )
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/todo.typ
typst
//Function to insert TODO #let todo(body, inline: false, big_text: 40pt, small_text: 15pt, gap: 2mm) = { // set text(fill: red) box([#rect(fill: black)[ #text(fill:white)[TODO:#body] ] // #rect(fill: blue) #place()[ #set text(size: 0pt) #figure(kind: "todo", supplement: "", caption: body, []) ]]) } //Function to insert TODOs outline // #let todo_outline = outline( // title: [TODOs], // target: figure.where(kind: "todo"), // )
https://github.com/jbro/supernote-templates
https://raw.githubusercontent.com/jbro/supernote-templates/main/include/a5x-template.typ
typst
The Unlicense
#let template(doc) = { set page(paper: "a5", margin: (top: 5mm, rest: 2mm)) set text(font: "ProFont IIx Nerd Font", size: 12pt) block(doc) place(bottom+center, text(size: 6pt, fill: gray, "unreleased")) }
https://github.com/vonhyou/typst-resume-template
https://raw.githubusercontent.com/vonhyou/typst-resume-template/master/README.md
markdown
# typst-resume-template > WIP A [Typst](https://typst.app/) version of my resume. Basically usable as a template. ## Usage - Create a typst project directly using the read-only [share link](https://typst.app/project/rdRZ87-0u5tyg-Z9c6o8uu) (recommended) - Fork/ download this repo. ## Demo ![Progress](./screenshots/progress.png) A demo pdf: [preview](./output/Résumé.pdf) ## TODO - [x] Header - [x] Sections - [x] Social Links in Header - [ ] *Reformat*
https://github.com/pride7/Typst-callout
https://raw.githubusercontent.com/pride7/Typst-callout/main/README.md
markdown
# Typst-callout This is a simple implementation for "callout" in Typst. ## Configure There are 7 types for callout: - note (default) - warning - check - summary - question - example - quote You can see the results in the `example.pdf`. The configuration of each type is saved in `configure.typ` by using a dictionary `configure`. So you can insert other type by yourself. For example, ```typst #configure.insert( "note", ( logo: "images/note.svg", box-color: rgb(240, 245, 248), title-color: rgb(88,123,207) ) ) ``` ## Usage ```typst #import "callout.typ": callout #callout( title:[Your title], type:"warning" )[ #lorem(20) ] ``` > You can use the `#grid()` to control the layout to achieve multi-callout group. <img src="example/example.png" alt="exmaple" /> <img src="example/example2.png" alt="exmaple2" />
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-26.typ
typst
Other
// Test the `product` method. #test(().product(default: 0), 0) #test(().product(default: []), []) #test(([ab], 3).product(), [ab]*3) #test((1, 2, 3).product(), 6)
https://github.com/Tiggax/zakljucna_naloga
https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/sec/uvod/4.%20bioreactor%20modeling.typ
typst
#set heading(offset: 1) #import "/src/additional.typ": todo #import "@preview/cetz:0.2.2": canvas, plot, draw, vector == Mass balance Mass balance is a fundamental principle in bioreactor modeling. It is used to describe flow of mass into, within and out of a bioreactor. This ensures that all mass entering the system is accounted for in either the product, waste or within the reactor itself. _Accumulation_ is a measure of To measure a compound or an element $i$, the balance of that $i$ in a system can be written as _Accumulation_ of _i_ where the system can be written as $ (d(i))/(d t) = E_i - S_i + sum^n_(k=1)R_(k(i)) $ while the Accumulation of elements is a simpler $ (d(e))/(d t) = E_e - S_e $ == Cell metabolism Cell division is a process in which a single mother cell multiplies its own genetic material, and then splits into two or more daughter cells @martin_2015[p. 143]. There are two kinds of divisions: / Mitosis: produces two identical daughter cells that contain identical to the mother nucleus. / Meiosis: produces four daughter cells, each with half the number of mother cells genetic material. The process of mitosis happens in all eukaryotic cells, in is the central part of cell multiplication in a bioreactor. Cell metabolism can sometimes be complex and sometimes hard to describe, but in general follows a simple principle of exponential growth. $ (d X(t))/(d t) = mu X(t) $ == Monod kinetics<monod_sec> This relation is commonly named the _Monod function_, although it was initially proposed by Michaelis–Menten and later extended by Monod to describe the growth of microorganisms. Many different mathematical formulas could be used to similarly fit the data, but it is convenient to adopt hyperbolic @monod_eq @monod_2012[p. 383]. The function follows a principal that low amount of substrate concentration gives low growth rate and if the substrate concentration increases, the growth rate also increases. For higher substrate levels, the growth rate increases diminishingly as it can be seen in @monod_f @carlsson_1998. $ mu(S) = mu_"max" S / (K_S + S) $<monod_eq> where - $K_S$ is the half saturation constant - $mu_"max"$ is the maximum specific growth rate - $S$ is the concentration of growth limiting substrate - $mu(S)$ is the growth rate at the specific concentration. #import "/src/figures/mod.typ": monod_plot, monod_function #figure( caption: [Illustration of the changing curve of the Monod function, depending on the half saturation constant at $mu_"max" = 1$], monod_plot )<monod_f> If the value of $S$ equals the value of $K_S$, it can be noted that the @monod_eq becomes $ mu(K_S) = mu_"max" dot K_S / (K_S + K_S) \ mu(K_S) = mu_"max" dot cancel(K_S) / (2 dot cancel(K_S) ) \ mu(K_S) = mu_"max" / 2 $ This can graphically be seen in @monod_half. #let k = 1 #let mu_max = 1 #figure( caption: [Monod function at $K_S$ = #k and $mu_"max"$ = #mu_max], monod_function(k: k, mu_max: mu_max) )<monod_half> == Process control<pid_sec> Process control of the bioreactor is achieved using many systems that utilize the feedback loop to achieve system stability. === PID controller @PID controller or a _proportional integral and derivative controller_ is normally used to achieve this stability. This control structure is the most dominating form of feedback in use today, with more than 90% of all control loops being @PID controllers @astrom_2001[p. 1163]. While @PID controller has a long and diverse history in the domain of automatic control, the contribution of Minorsky created support for the subsequent emergence of modern @PID controllers @borase_2021[p. 1]. Minorsky provided a theoretical analysis for the derivative of the error; that is its current rate of change @medaglia_2019. Industrial PID control tuning formulas proposed by Ziegler and Nicholas in 1942 @ziegler_1942, represented the state of the art of PID control by the early 1980s @aastrom_2006. In 1984 <NAME> @aastrom_1984 proposed a relay-tuning method built upon the classical method of Ziegler and Nichols @aastrom_2006. The simple structure and easy implementation of the @PID controller has made it the most widely used controller in various application domains @borase_2021[p. 7]. It was the first controller for the high-volume market to be mass produced in the process industries @johnson_2005[p. 1]. The workings of @PID controller can be seen in @pid_figure. #import "/src/figures/mod.typ": pid_figure, pid_graph #figure( caption: [Scheme of a PID control system as seen in @Hymel_2023[Fig. 4]], pid_graph )<pid_graph> Reference signal ($r(t)$) takes in a function of setpoints, meaning that at different times, different setpoints can be set. An error value ($e(t)$) is then calculated from the difference between the setpoint and the current measured value. This error is then used in the control algorithm. PID control uses the three mode algorithm, the proportional, integral and the derivative. The proportional term incorporates proportional changes of the error to the output and is denoted by the P in @pid_graph. The integral term, denoted by I in @pid_graph; corrects the output by reducing the offset from the process variable. Finally the derivative controls the rate of change of the process. It is denoted by D in @pid_graph, and changes the output when there are unusual variations. Each of the parameters is scaled with their respective constant, to give the user control of the performance of the controller @borase_2021[p. 2]. It could be said that the integral, proportional and derivative feedback is based on the past (I), present (P) and future (D) control error of the system @astrom_2001[p. 1163]. Visualization of the workings of @PID control can be seen in @pid_figure Function $u(t)$ in @pid_graph can also be represented as a Parallel type or _ideal representation_ $ u(t) = K_c ( e(t) + 1 / T_i integral e(t) d t + T_d (d e(t))/ (d t) ) $<pid_eq> where $K_p = K_c$, $K_i = K_c / T_i$ and $K_d = K_c dot T_d$. #figure( caption: [Visualization of the PID control response of the process variable ($y$) to the step change of setpoint (SP) in reference to time], pid_figure )<pid_figure>
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661101-%5BCalculus%201A%5D/src/lectures/03661101_lecture_7.typ
typst
#import "/template.typ": * #show: project.with( title: "חדו״א 1א׳ - שיעור 7", authors: ("<NAME>",), date: "18 בינואר, 2024", ) #set enum(numbering: "(1.א)") = תתי-סדרות == דוגמה תהא סדרה $a_n$: $[a_n: 1, 1/2, 1/3, dots]$ ותת-סדרה $b_k$: $[b_k: underbracket(b_1=1/3, (a_3)), underbracket(b_2= 1/7, (a_7)), underbracket(b_3=1/101, (a_101)), dots]$. == הגדרה תהי $(an)_(n=1)^oo$ סדרה. נאמר שסדרה $(b_k)_(k=1)^oo$ הינה *תת-סדרה* (תת״ס) שלה אם קיימת סדרה ${n_k}_(k=1)^oo$ עולה ממש של מספרים טבעיים (אינדקסים) כך ש-$b_k=a_(n_k)$. === דוגמאות נוספות נתונה סדרה $(an)_(n=1)^oo$. + הסדרה היא תת״ס של עצמה: $n_k=k$ $arrl$ $b_k=a_k$. + $b_k = a_(2k)$ היא תת״ס של $(an)$: $n_k = 2k$. + $b_k = a_(k+1)$ היא תת״ס של $(an)$: $n_k = k+1$. + $(2a_k)_(k=1)^oo$ לא תת״ס של $(an)$ כי $2a k$ לא בהכרח שווה ל-$a_n_k$: $ an &: 1,3,5,7, dots \ 2a_k &: 2,6,10,14, dots $ === שאלה אם $(a_n_k)_(k=1)^oo$ היא תת״ס של $(an)_(n=1)^oo$ וכן $(b_m_k)_(k=1)^oo$ היא תת״ס של $(b_n)_(n=1)^oo$. האם $(a_n_k + b_m_k)_(k=1)^oo$ היא תת״ס של $(an + b_n)_(n=1)^oo$? *לא*: $ a_n &: bold(2),4,bold(6),8, dots => n_k = 2k - 1 \ b_n &: 1,bold(3),5,bold(7), dots => m_k = 2k \ a_n + b_n &: 3, 7, 11, dots $ אך $a_n_1 + b_m_1 = 5$ ולא שייך ל-$(a_n + b_n)$. == משפטים === (משפט) תהי $(an)_(n=1)^oo$ סדרה ותהי $(a_n_k)_(k=1)^oo$ תת״ס שלה. אזי: + אם הסדרה $(an)$ חסומה אז גם כל תת״ס שלה ($a_n_k$) חסומה. + אם הסדרה $(an)$ מתכנסת (כולל במובן הרחב) אז גם כל תת״ס שלה ($a_n_k$) מתכנסת (ולאותו הגבול). + אם הסדרה $(an)$ מונוטונית עולה (או יורדת) אז גם כל תת״ס שלה ($a_n_k$) מונוטונית עולה (או יורדת). #pagebreak() === (משפט) לכל סדרה יש תת״ס מונוטונית === (למה) אם לסדרה $(an)$ אין איבר מקסימלי (למשל, $a_n = n^2$, או $a_n = 1-1/n$), אזי יש לה תת״ס עולה ממש ==== הוכחת הלמה נסמן $(an) in.rev M_n = max{a_1, a_2, dots, a_n}$. נבנה תת״ס עולה ממש בצורה אינדוקטיבית באופן הבא: נגדיר $n_1 = 1$. מכיוון שלסדרה $(an)$ אין איבר מקסימלי, נובע ש-$exists n_2 > n_1$ כך ש-$a_n_2>M_n_1 = a_1$ (אחרת, $M_n_1$ איבר מקסימלי בסדרה וזוהי סתירה). באופן דומה, $exists n_3 >n_2$ כך ש-$a_n_3 > M_n_2 >= a_n_2$ (אחרת $M_n_2$ איבר מקסימלי בסדרה וזוהי סתירה) - וכך הלאה. נקבל סדרת אינדקסים $n_1 < n_2 < n_3 < dots$ כך ש-$a_n_1 < a_n_2 < a_n_3 < dots$. #QED ==== הוכחת המשפט תהי $(an)$ סדרה. אם ל-$(an)$ יש תת״ס מונוטונית עולה ממש - סיימנו. נניח כי ל-$(an)$ אין תת״ס עולה ממש. נבנה כעת באופן אינדוקטיבי תת״ס יורדת. מהלמה הקודמת, נובע שלסדרה $(an)$ יש איבר מקסימלי. נסמן איבר זה באופן הבא: $a_n_1 = max{an}$. נתבונן כעת בתת״ס הבאה: $a_(n_1+1), a_(n_1+2), a_(n_1+3), dots$, שגם לה אין תת״ס עולה ממש (הרי שלסדרה המקורית אין תת״ס עולה ממש). מהלמה הקודמת, נובע שלתת״ס זו יש איבר מקסימלי. נסמן אותו $a_n_2 = max{a_(n_1+1), a_(n_1+2), dots}$. לכן $n_2 > n_1$! ברור כי $n_2 >= n_1 + 1 > n_1$. לבסוף, נראה כי מתקיים $a_n_2 <= a_n_1$. כעת ממשיכים בצורה אינדוקטיבית ומקבלים $n_1 < n_2 < n_3 < dots$ כש-$a_n_1 >= a_n_2 >= a_n_3 >= dots$. #QED == משפט בולצנו-ויירשטראס === (משפט בולצנו-ויירשטראס) לכל סדרה חסומה יש תת״ס מתכנסת ==== הוכחה תהי $(an)$ סדרה חסומה. לפי המשפט הקודם, יש ל-$(an)$ תת״ס $(a_n_k)$ מונוטונית עולה או יורדת. מהמשפט הראשון בהרצאה, נובע כי $(a_n_k)$ חסומה גם כן. אז, $(a_n_k)$ סדרה מונוטונית וחסומה, ולכן מתכנסת. #QED === (מסקנה: משפט בולצנו-ויירשראטס המוכלל) לכל סדרה יש תת״ס מתכנסת, כולל במובן הרחב #pagebreak() == הלמה של קנטור על קטעים מקוננים === (למה) נתונות שתי סדרות $(an)$ ו-$(b_n)$ המקיימות $a_n < b_n forall n in NN$ ונסמן $I_n = [a_n, b_n]$. נניח כי מתקיים: + הקטעים $I_n$ הינם קטעים מקוננים: $I_1 suq I_2 suq I_3 suq dots suq I_n supset I_(n+1) suq dots $. + $lim (b_n - a_n) = 0$. אזי קיימת נקודה יחידה המשותפת לכל הקטעים: $sect.big_(n=1)^oo I_n = {c}$. ==== הוכחה נתון: $ a_1<=a_2<= dots <= a_(n-1) <= a_n < b_n <= b_(n-1) <= dots <= b_2 <= b_1, forall n in NN $ מכאן, $(a_n)$ עולה וחסומה מלמעלה, למשל, ע״י $b_1$. לכן $exists lim an = sup an =: a$. בדומה, $(b_n)$ יורדת וחסומה מלמטה, למשל, ע״י $a_1$. לכן $exists lim b_n = inf b_n =: b$. נקבל $0 = lim (b_n - a_n) = b-a$ $arrl$ $a=b$. נראה כעת שהנקודה $a=b$ הינה הנקודה המבוקשת $c$. ברור כי $ forall m in NN, a_m <= sup a_n = a = b = inf b_n <= b_m $ כלומר, $a=b in I_m, forall m in NN$. מכאן, $exists a=b in sect.big_(n=1)^oo I_n$. כדי להוכיח את יחידות הנקודה הנ״ל, נניח בשלילה כי: $exists a' != a$, כך ש-$forall m in NN, a_m <= a' <= b_m$. נשים לב כי $a_m$ ו-$b_m$ שואפות ל-$a$, ומכלל הסנדוויץ׳ מתקיים כי $a' = lim a' = a$ - בסתירה. #QED === הוכחה נוספת למשפט בולצנו-ויירשטראס ("אריה במדבר") תהי $(c_n)$ סדרה חסומה בקטע $[a,b]$. צ״ל שקיימת תת״ס $(c_n_k)$ מתכנסת. נגדיר את $(a_k)_(k=0)^oo$ ו-$(b_k)_(k=0)^oo$ באופן הבא: $ a_0 = a and b_0 = b \ forall k in NN, a_k < b_k \ b_k - a_k = frac(1, 2^k) (b-a) \ (a_k) arrow.t and (b_k) arrow.b $ ואינסוף מאיברי הסדרה ($c_n$) מוכלים בקטע $[a_k, b_k]$ לכל $k$ טבעי. #align(center, image("/attachments/image.png", height: 4.9cm)) ואז לפי הלמה של קנטור $exists c in sect.big_(k=0)^oo [a_k, b_k]$ יחיד. נוכיח כעת ש-$c$ הינו הגבול של איזושהי תת״ס של $(c_n)$. נבנה תת״ס המתכנסת ל-$c$: נבחר $c_n_1 in [a_1, b_1]$ ו-$n_2> n_1$, $c_n_2 in [a_2, b_2]$ וכו׳ $n_k > n_(k-1)$ ומתקיים $c_n_k in [a_k, b_k]$ לכל $k>=3$ באופן אינדוקטיבי. נראה כי $a_k <= c_n_k <= b_k$, ומכלל הסנדוויץ׳ $c_n_k -> c$. #QED
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/038_War%20of%20the%20Spark.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("War of the Spark", doc) #include "./038 - War of the Spark/001_Old Friends and New.typ" #include "./038 - War of the Spark/002_The Path to Opulent.typ" #include "./038 - War of the Spark/003_Rallying the Reluctant.typ" #include "./038 - War of the Spark/004_Desperate Operatives.typ" #include "./038 - War of the Spark/005_Operation Desperation.typ" #include "./038 - War of the Spark/006_Ashes.typ"
https://github.com/ns-shop/ns-shop-typst
https://raw.githubusercontent.com/ns-shop/ns-shop-typst/main/chapter1.typ
typst
#import "template.typ": * #h1("Khảo sát và phân tích các yêu cầu của một website thương mại điện tử (TMĐT)") #h2("Tổng quan về thương mại điện tử") Thương mại điện tử (TMĐT) hiểu một cách đơn giản là hoạt động mua bán sản phẩm hay dịch vụ thông qua Internet và các phương tiện điện tử khác. Các giao dịch này gồm tất cả hoạt động như: mua bán, thanh toán, đặt hàng, quảng cáo và giao hàng ... Có nhiều tổ chức lớn trên thế giới đưa ra các định nghĩa khác nhau cho khái niệm của TMĐT. Theo Ủy ban Kinh tế Liên Hiệp Quốc châu Âu (UNECE): "TMĐT nội địa bao gồm các giao dịch trong nước qua Internet hoặc các mạng máy tính trung gian, trong khi đó, TMĐT quốc tế liên quan đến các giao dịch xuyên biên giới. Các giao dịch này là giao dịch mua/bán hàng hóa hoặc dịch vụ, sau đó, quá trình chuyển giao hàng hóa có thể được thực hiện trực tuyến hoặc thủ công”. Theo Tổ chức Thương mại Thế giới (WTO): "TMĐT bao gồm việc sản xuất, quảng cáo, bán hàng và phân phối sản phẩm được mua bán và thanh toán trên mạng Internet, nhưng được giao nhận một cách hữu hình, cả các sản phẩm giao nhận cũng như những thông tin số hoá thông qua mạng Internet". Ngày nay ngươì ta còn hiểu khái niệm TMĐT thông thường là tất cả các phương pháp tiến hánh kinh doanh và các quy trình quản trị thông qua các kêng điện tử mà trong đó internet đóng vai trò cơ bản và trong công nghệ thông tin được gọi là điều kiện tiên quyết. Tuy nhiên, TMĐT không chỉ là kinh doanh sử dụng công nghệ. TMĐT là toàn bộ quá trình kinh doanh được thực hiện bằng điện tử và được thiết kế để giúp hoàn thành mục tiêu kinh doanh. Hai công nghệ chủ chốt để xây dựng và phát triển TMĐT là trao đổi dữ liệu điện tử (EDI) và chuyển tiền điện tử (EFT). Ngày nay, công nghệ chuyển tiền điện tử được ứng dụng để xây dựng các hệ thống thanh toán điện tử. Website TMĐT là một nền tảng trực tuyến cho phép các doanh nghiệp bán hàng hoặc dịch vụ của mình cho khách hàng thông qua internet. TMĐT cung cấp một kênh bán hàng trực tuyến, mở rộng phạm vi tiếp cận của doanh nghiệp đến toàn bộ thị trường và giúp tăng thu nhập. #h3("Các đặc trưng cơ bản của TMĐT") So với các hoạt động thương mại truyền thống, TMĐT có một số các đặc trưng cơ bản sau: - Truy cập từ xa. - Thanh toán trực tuyến. - Mở cửa 24/7. - Phạm vi rộng. - Tiết kiệm chi phí. - Đa dạng sản phẩm. - Trải nghiệm người dùng tốt. #h3("Lợi ích của một trang TMĐT") Website TMĐT mang lại nhiều lợi ích cho các doanh nghiệp và khách hàng, bao gồm: - Mở rộng phạm vi tiếp cận khách hàng. - Tiết kiệm chi phí. - Tăng doanh số bán hàng. - Tăng tính minh bạch trong quản lý kinh doanh. - Đáp ứng nhu cầu của khách hàng. - Tăng tính tiện lợi cho khách hàng. - Tiết kiệm thời gian. - Hỗ trợ quản lý đơn hàng dễ dàng. #h3("Các hệ thống thanh toán trong TMĐT") Một số hình thức thanh toán điện tử được sử dụng rộng rãi trong các hệ thống thanh toán điện tử được trình bày dưới đây: - Thanh toán bằng thẻ: Đây là hình thức thanh toán đặc trưng nhất, chiếm tới 90% trong tổng số các giao dịch thanh toán điện tử. Thẻ thanh toán (thẻ chi trả) là một loại thẻ có khả năng thanh toán tiền mua hàng hóa, dịch vụ tại một vài địa điểm, kể cả website mua hàng trực tuyến nếu chấp nhận tiêu dùng bằng thẻ đó. Thẻ có thể dùng để rút tiền mặt trực tiếp từ các ngân hàng hay các máy rút tiền tự động. - Thanh toán qua cổng thanh toán điện tử: Cổng thanh toán điện tử về bản chất là dịch vụ cho phép khách hàng giao dịch tại các website TMĐT. Cổng thanh toán cung cấp hệ thống kết nối an toàn giữa tài khoản (thẻ, ví điện tử,…) của khách hàng với tài khoản của website bán hàng. Cổng thanh toán điện tử giúp người tiêu dùng và doanh nghiệp thanh toán, nhận tiền trên internet đơn giản, nhanh chóng và an toàn. - Thanh toán bằng ví điện tử: Ví điện tử là một tài khoản online có thể dùng nhận, chuyển tiền, mua thẻ điện thoại, vé xem phim, thanh toán trực tuyến các loại phí trên internet như tiền điện nước, cước viễn thông, cũng có thể mua hàng online từ các trang TMĐT. Người dùng phải sở hữu thiết bị di động thông minh tích hợp ví điện tử và liên kết với ngân hàng thì mới có thể thanh toán trực tuyến bằng hình thức này. - Thanh toán qua Mobile Banking: Hình thức này đang dần trở nên phổ biến bởi hầu hết người dùng đều sử hữu một chiếc điện thoại thông minh. Chính vì vậy, khi đi mua sắm, khách hàng không cần phải mang theo tiền mặt, thay vào đó là thanh toán qua điện thoại với dịch vụ Mobile Banking. Hệ thống thanh toán qua điện thoại được xây dựng trên mô hình liên kết giữa ngân hàng, các nhà cung cấp viễn thông, và người dùng. - Thanh toán qua QR Code: Tiến bộ công nghệ cũng là lý do khiến thanh toán bằng QR Code ngày càng được ưa chuộng. Phương thức thanh toán này khá đơn giản, gọn nhẹ, dễ sử dụng và thân thiện cho người dùng. Tính năng QR Code hiện đang được tích hợp sẵn trên ứng dụng di động của các ngân hàng, các sản phẩm và dịch vụ của Google như Google Chart hay Google Map, trên bảng hiệu, xe buýt, danh thiếp, tạp chí, website, hàng hóa tại siêu thị, cửa hàng tiện lợi,… Thậm chí là trên một số siêu ứng dụng như VinID của Tập đoàn Vingroup. Người dùng sử dụng camera điện thoại quét mã QR để thực hiện nhanh các giao dịch chuyển khoản, thanh toán hóa đơn, mua hàng. Chỉ với một lần quét, sau vài giây, người dùng đã thanh toán thành công tại các nhà hàng, siêu thị, cửa hàng tiện lợi, taxi, thậm chí là các website TMĐT hay trên bất cứ sản phẩm nào có gắn mã QR mà không cần sử dụng tiền mặt, thẻ, không lo lộ thông tin cá nhân tại các điểm thanh toán. #h3("Quy trình thanh toán điện tử") Các hệ thống thanh toán điện tử triển khai trong thực tế rất đa dạng về hình thức và công nghệ sử dụng. #img("1image.png", cap: "Quy trình thanh toán điện tử")<imgxxx1> Trong mô hình ở @imgxxx1, hệ thống thanh toán điện tử là trung gian kết nối giữa người mua, người bán, thực hiện thanh toán cho các giao dịch dựa trên kết nối với ngân hàng của người mua và người bán: - Bước 1 - Thẻ tín dụng: Các khách hàng có thẻ tín dụng do ngân hàng phát hành với hạn mức tín dụng và số dư có sẵn. - Bước 2 - Đặt hàng: Các khách hàng đến thăm một trang web hoặc cửa hàng trực tuyến sử dụng trình duyệt web tiêu chuẩn và bắt đầu mua sắm và thêm (các) sản phẩm vào giỏ hàng của mình. Sau khi kiểm tra, người mua được yêu cầu để gửi thông tin thẻ tín dụng của mình, ngày hết hạn, địa chỉ thanh toán. Sau đó, người mua cũng chọn phương thức vận chuyển cho ví dụ và sau đó nhấn vào nút gửi để bắt đầu giao dịch. Các thông tin này sau đó được chuyển đến cửa hàng trực tuyến của thương gia nơi mà các dịch vụ thanh toán bên ngoài được thiết lập. Các dịch vụ thanh toán bên ngoài nhận được thông tin được mã hóa từ các cửa hàng trực tuyến, thực hiện một kiểm tra gian lận, và sau đó bắt đầu quá trình giao tiếp thông tin thanh toán và số tiền mua hàng cho các bộ xử lý của bên thứ ba. - Bước 3 - Yêu cầu xác nhận: Dịch vụ dịch thanh toán mã hóa thông tin mua hàng hoặc dữ liệu và truyền nó cho các bộ xử lý của bên thứ ba, người sẽ chuyển thông tin hoặc dữ liệu hơn nữa để các hiệp hội thẻ hoặc thẻ phát hành cho phép và xác minh - Bước 4 - Đáp trả xác thực: Các tổ chức tài chính phát hành xác minh thông tin thẻ tín dụng và xác định xem khách hàng có đủ tín dụng để thanh toán tiền mua. Một số quyền được tạo ra và tín dụng là giảm lượng có thẩm quyền. Nếu nó để xảy ra rằng các thông tin thẻ tín dụng là không đúng hoặc nếu không có đủ tín dụng có sẵn, sau đó nhắn giảm giao dịch được tạo ra. Trong khoảng thời gian ngắn này của thời gian, các ngân hàng phát hành cũng thực hiện các hoạt động khác như dịch vụ xác minh địa chỉ, nơi các thông tin thanh toán đã nhập trực tuyến được so sánh với các mục trong cơ sở dữ liệu của ngân hàng phát hành - đây là phần xác thực. Sau đó, một thông báo uỷ quyền được trả lại cho các hiệp hội thẻ và chuyển tiếp đến các bộ xử lý của bên thứ ba. - Bước 5 - Thông báo cho bên bán: Bộ xử lý của bên thứ ba nhận được tin nhắn uỷ quyền và các thông tin cần thiết khác từ các hiệp hội thẻ hoặc tổ chức phát hành và khởi tạo quá trình truyền đạt thông điệp uỷ quyền cho các thương gia. Các bộ vi xử lý của bên thứ ba mã hóa thông điệp uỷ quyền và truyền các thông tin mã hóa cho máy chủ thương mại an toàn của bên bán. - Bước 6 - Thông báo từ bên bán: máy chủ của bên bán thu được các thông tin và được lập trình để gửi ngay cho chính người mua hoặc tin nhắn cho chủ thẻ/khách hàng. Thông thường khi thẻ tín dụng bị từ chối, một số thông tin cần thiết như một gợi ý để kiểm tra tính chính xác của các thông tin được cung cấp hoặc sử dụng một thẻ tín dụng khác để gửi lên. Ngay sau khi khách hàng nhận được thông tin này sẽ đồng ý chấp thuận một giao dịch, cùng một lúc nhận được một số xác nhận. Nó chỉ mất một vài giây từ thời điểm khách hàng nhấn vào nút mua cho đến khi khách hàng nhận được tin nhắn phản hồi trở lại. Các quá trình cấp phép thường mất một vài giây, tùy thuộc vào ứng dụng của bên bán thanh toán và thủ tục cũng như lưu lượng Internet và các yếu tố khác. - Bước 7 - Hoàn thành: Bên bán bắt đầu quá trình thực hiện lệnh của khách hàng với các sản phẩm/dịch vụ thích hợp. - Bước 8 - Yêu cầu giải quyết: Các bên bán biên soạn một loạt các đơn đặt hàng đã được hoàn thành và bắt đầu quá trình truyền tải hàng loạt các bộ xử lý của bên thứ ba để giải quyết. Bên bán đầu tiên truyền hàng loạt dịch vụ thanh toán của mình để mã hoá thông tin mua hàng và truyền các thông tin mã hóa cho các bộ vi xử lý của bên thứ ba. Các bộ xử lý của bên thứ ba nhận được thông tin này và sẽ gửi các hướng dẫn giải quyết cho tổ chức tài chính của mình để chuyển số tiền từ tài khoản của chủ thẻ vào tài khoản của thương gia. - Bước 9 - Giải quyết: Đối với mỗi giao dịch thẻ tín dụng trong hàng loạt, các tổ chức tài chính thích hợp được ghi nợ và thẻ tín dụng của chủ thẻ được cập nhật. Các ngân hàng bên mua nhận tiền và tiền được gửi vào tài khoản ngân hàng của bên bán. - Bước 10 - Đáp ứng giải quyết: Bên bán nhận được thông báo rằng tiền đã được gửi vào tài khoản ngân hàng của mình. Trên cơ sở đó, các thương gia nhận được báo cáo rằng ông có thể sử dụng để hòa giải với yêu cầu giải quyết hàng loạt của mình với hoạt động tiền gửi của mình. - Bước 11 - Quỹ có sẵn: Khoảng cách giữa các cấp của thương gia được yêu cầu thanh toán, chuyển tiền và các quỹ sẵn có thể mất đến vài ngày, tùy thuộc vào các ngân hàng phát hành, các ngân hàng mua lại và các bộ xử lý của bên thứ ba. Chu kỳ thời gian giải quyết là thực sự bị ảnh hưởng bởi thời gian nắm giữ ngân hàng mua lại tiền gửi, cũng như các thủ tục khác và chính sách được thiết lập bởi các ngân hàng mua lại và xử lý của bên thứ ba. #h2("Mô tả bài toán xây dựng website TMĐT") Công ty ABC kinh doanh về lĩnh vực may mặc muốn xây dựng hệ thống website TMĐT với các yêu cầu: - Đăng ký và đăng nhập: Người dùng có thể đăng ký tài khoản mới và đăng nhập vào hệ thống. Đăng ký tài khoản dễ dàng. - Xem sản phẩm: Người dùng có thể xem thông tin chi tiết về các sản phẩm đang được bán trên website. - Thêm sản phẩm vào giỏ hàng: Người dùng có thể thêm sản phẩm vào giỏ hàng của mình. - Quản lý giỏ hàng: Người dùng có thể chỉnh sửa số lượng sản phẩm trong giỏ hàng, xóa sản phẩm khỏi giỏ hàng, hoặc xem tổng giá trị đơn hàng. - Đặt hàng: Người dùng có thể đặt hàng bằng cách cung cấp thông tin về địa chỉ giao hàng, phương thức thanh toán và các chi tiết khác liên quan đến đơn hàng. - Theo dõi đơn hàng: Người dùng có thể theo dõi trạng thái và thông tin liên quan đến đơn hàng đã đặt. - Thanh toán: Người dùng có thể chọn phương thức thanh toán và thực hiện thanh toán cho đơn hàng. Tích hợp nhiều dịch vụ thanh toán. - Giao hàng: Website hỗ trợ các nhà cung cấp dịch vụ giao hàng để vận chuyển các đơn hàng đến địa chỉ giao hàng của người dùng. - Quản lý người dùng: Website cho phép quản lý thông tin người dùng, bao gồm cập nhật thông tin cá nhân và quản lý địa chỉ giao hàng. - Quản lý sản phẩm: Website cho phép quản lý thông tin về sản phẩm, bao gồm thêm, sửa, xóa và hiển thị sản phẩm. - Quản lý đơn hàng: Website cho phép quản lý thông tin về các đơn hàng, bao gồm xem danh sách đơn hàng, cập nhật trạng thái và xem chi tiết từng đơn hàng. - Giao diện quản lý đơn giản dễ sử dụng, giao diện người dùng dễ nhìn, đặt hàng nhanh chóng. - Đảm bảo an toàn và bảo mật cho dữ liệu. - Đảm bảo an toàn cho tính năng thanh toán đơn hàng. #h2("Khảo sát các nghiệp vụ của một website TMĐT") Một website thương mại điện tử có thể có nhiều nghiệp vụ khác nhau, nhưng dưới đây là một số nghiệp vụ quan trọng và phổ biến mà một website thương mại điện tử thường thực hiện: - Quản lý sản phẩm: Nghiệp vụ này liên quan đến việc quản lý thông tin về các sản phẩm được bán trên website. Bao gồm việc thêm, sửa, xóa sản phẩm, cập nhật thông tin sản phẩm, quản lý danh mục sản phẩm, hình ảnh, mô tả, giá cả và số lượng hàng tồn kho. - Quản lý đơn hàng: Nghiệp vụ này bao gồm quản lý quá trình đặt hàng từ khách hàng, xử lý đơn hàng, lưu trữ thông tin đơn hàng, cập nhật trạng thái đơn hàng (đã xác nhận, đang vận chuyển, đã giao hàng, hủy đơn hàng, v.v.), cung cấp thông tin vận chuyển và theo dõi đơn hàng. - Thanh toán và giao dịch: Nghiệp vụ này liên quan đến việc xử lý thanh toán trực tuyến và giao dịch với khách hàng. Bao gồm tích hợp các cổng thanh toán, cung cấp các phương thức thanh toán an toàn và tiện lợi (thẻ tín dụng, chuyển khoản ngân hàng, ví điện tử, v.v.), xử lý giao dịch thành công và cung cấp thông tin về giao dịch cho khách hàng và nhà cung cấp. - Quản lý tài khoản khách hàng: Nghiệp vụ này liên quan đến quản lý thông tin cá nhân của khách hàng, bao gồm việc đăng ký tài khoản, đăng nhập, cập nhật thông tin cá nhân, quản lý địa chỉ giao hàng và thông tin thanh toán, theo dõi lịch sử mua hàng và đánh giá sản phẩm. - Quảng cáo và khuyến mãi: Nghiệp vụ này liên quan đến việc quảng bá sản phẩm và dịch vụ của website, thiết kế và triển khai các chiến dịch quảng cáo, cung cấp mã giảm giá, khuyến mãi và chương trình thưởng cho khách hàng, theo dõi hiệu quả quảng cáo và khuyến mãi. - Tương tác khách hàng: Nghiệp vụ này liên quan đến việc tương tác với khách hàng qua các kênh như email, chat trực tuyến, điện thoại hoặc mạng xã hội. Bao gồm hỗ trợ khách hàng, giải đáp thắc mắc, xử lý khiếu nại và cung cấp hỗ trợ sau bán hàng. - Quản lý kho hàng: Nghiệp vụ này liên quan đến việc quản lý và kiểm soát hàng tồn kho, cập nhật số lượng hàng hóa có sẵn, quản lý nhập xuất kho, tổ chức vận chuyển và lưu trữ thông tin về kho hàng. - Phân tích dữ liệu và báo cáo: Nghiệp vụ này liên quan đến việc thu thập, phân tích và báo cáo dữ liệu về hoạt động kinh doanh của website thương mại điện tử. Bao gồm thông tin về lượt truy cập, doanh số bán hàng, hành vi khách hàng, hiệu quả quảng cáo và khuyến mãi, v.v. để đưa ra quyết định kinh doanh và cải thiện hiệu suất. Những nghiệp vụ trên chỉ là một phần trong tổng thể của một website thương mại điện tử, và còn nhiều nghiệp vụ khác như quản lý đánh giá và nhận xét sản phẩm, tích hợp công cụ tìm kiếm, xây dựng cộng đồng khách hàng, v.v. Tùy thuộc vào quy mô và phạm vi của website, các nghiệp vụ có thể được điều chỉnh và mở rộng để phù hợp với yêu cầu và mục tiêu kinh doanh của doanh nghiệp. #h2("Các yêu cầu chức năng của một website TMĐT") Một website thương mại điện tử cần phải đáp ứng một số yêu cầu chức năng để cung cấp trải nghiệm mua sắm trực tuyến thuận tiện, hiệu quả cho người dùng và cung cấp công cụ quản lý và phát triển hiệu quả cho người bán. Dưới đây là một số yêu cầu chức năng quan trọng của một website TMĐT: - Đăng ký và đăng nhập: Cho phép người dùng đăng ký tài khoản mới, cung cấp thông tin cá nhân cần thiết và đăng nhập vào tài khoản đã đăng ký để tiếp tục quá trình mua sắm. - Tìm kiếm và duyệt sản phẩm: Cung cấp chức năng tìm kiếm để người dùng có thể tìm kiếm sản phẩm theo từ khóa, danh mục, giá cả, thương hiệu, v.v. Đồng thời, cung cấp khả năng duyệt sản phẩm theo danh mục, thương hiệu, sản phẩm mới nhất, sản phẩm bán chạy, v.v. - Chi tiết sản phẩm: Cung cấp thông tin chi tiết về sản phẩm bao gồm hình ảnh, mô tả, thông số kỹ thuật, giá cả, đánh giá và nhận xét từ người dùng khác. - Giỏ hàng và thanh toán: Cho phép người dùng thêm sản phẩm vào giỏ hàng, cập nhật số lượng sản phẩm, tính tổng giá trị đơn hàng, chọn phương thức thanh toán và cung cấp thông tin thanh toán cần thiết để hoàn tất quá trình mua hàng. - Quản lý đơn hàng: Cung cấp chức năng cho người dùng theo dõi và quản lý đơn hàng, bao gồm xem trạng thái đơn hàng, lịch sử đơn hàng, in hóa đơn và yêu cầu hỗ trợ sau bán hàng. - Quản lý tài khoản: Cho phép người dùng cập nhật thông tin cá nhân, địa chỉ giao hàng, thông tin thanh toán và thay đổi mật khẩu. - Đánh giá và nhận xét: Cho phép người dùng đánh giá và viết nhận xét về sản phẩm đã mua để chia sẻ kinh nghiệm và đánh giá với người dùng khác. - Quản lý khuyến mãi và mã giảm giá: Cung cấp chức năng quản lý các chương trình khuyến mãi, mã giảm giá và ưu đãi đặc biệt, cho phép người dùng áp dụng mã giảm giá khi thanh toán. - Giao hàng và vận chuyển: Cung cấp thông tin về phương thức giao hàng, thời gian giao hàng dự kiến và tính phí vận chuyển. Cho phép người dùng chọn phương thức giao hàng và cập nhật địa chỉ giao hàng. - Hỗ trợ khách hàng: Cung cấp kênh liên hệ và hỗ trợ khách hàng trực tuyến để giải đáp thắc mắc, xử lý khiếu nại và cung cấp hỗ trợ sau bán hàng. - Tích hợp thanh toán trực tuyến: Hỗ trợ các phương thức thanh toán trực tuyến an toàn và thuận tiện như thẻ tín dụng, chuyển khoản ngân hàng, ví điện tử, v.v. - Quản lý báo cáo và thống kê: Cung cấp chức năng phân tích dữ liệu và báo cáo về doanh số bán hàng, lượt truy cập, đánh giá sản phẩm, v.v. để giúp doanh nghiệp đánh giá hiệu suất kinh doanh và đưa ra quyết định phát triển. Những yêu cầu chức năng này sẽ tùy thuộc vào quy mô và mục tiêu kinh doanh của mỗi website thương mại điện tử. Việc phân tích và đáp ứng đúng các yêu cầu chức năng sẽ giúp đảm bảo trải nghiệm mua sắm tốt nhất cho người dùng và nâng cao hiệu quả kinh doanh của doanh nghiệp. #h2("Khảo sát, phân tích các yêu cầu an toàn của một website TMĐT") #h3("Các lỗ hổng an toàn phổ biến trong website TMĐT") OWASP (Open Web Application Security Project) là một tổ chức phi lợi nhuận quốc tế tập trung vào việc nghiên cứu và phân tích các vấn đề về bảo mật ứng dụng web. OWASP cung cấp nhiều tài liệu, công cụ và khóa học để giúp các nhà phát triển phát hiện và khắc phục các lỗ hổng bảo mật trong ứng dụng web. OWASP cũng tạo ra danh sách "OWASP Top 10" để tập trung vào 10 lỗ hổng bảo mật phổ biến nhất trong ứng dụng web. Danh sách này được cập nhật định kỳ và dùng làm hướng dẫn cho việc phát triển ứng dụng an toàn. Các phiên bản của OWASP Top 10 từng được phát hành vào các năm khác nhau và được điều chỉnh để phản ánh các mối đe dọa bảo mật mới nhất. Theo tổ chức OWASP, 10 lỗ hổng ứng dụng web phổ biến nhất hiện nay bao gồm: @owasp-top-10 - Broken Access Control - Cryptographic Failures - Injection - Insecure Design (Lỗ hổng mới cập nhật) - Security Misconfiguration - Vulnerable and Outdated Components - Identification and Authentication Failures - Software and Data Integrity Failures (Lỗ hổng mới cập nhật) - Security Logging and Monitoring Failures - Server-Side Request Forgery (SSRF) (Lỗ hổng mới cập nhật) #img("2image.png", cap: "Danh sách lỗ hổng Top 10 OWASP 2021", width: 80%) OWASP Top 10 được cập nhật lại sau một khoảng thời gian tương đối, tùy thuộc vào sự phát triển và xu hướng của các lỗ hổng bảo mật trong ứng dụng web. Thông thường, OWASP Top 10 được cập nhật mỗi 3 - 4 năm. Danh sách OWASP Top 10 trước đây đã có các phiên bản cho các năm 2003, 2004, 2007, 2010, 2013 và 2017. #h4("Lỗ hổng Broken Access Control") Kiểm soát truy cập là sự kiểm soát người dùng không cho phép họ thực thi những hành động bên ngoài quyền hạn. Các lỗi thường dẫn đến tiết lộ thông tin trái phép, sửa đổi hoặc phá hủy tất cả dữ liệu hoặc thực hiện chức năng ngoài giới hạn của người dùng. Các phương pháp phổ biến: - Sửa đổi URL. - Sửa đổi thông tin nhận dạng để truy cập tài khoản người khác (IDOR). - Leo thang đặc quyền. Biện pháp phòng chống: - Ngoại trừ tài nguyên công cộng, còn lại từ chối theo mặc định. - Xác thực người dùng khi học quay lại ứng dụng. - Kiểm tra quyền tại thời điểm người dùng cố gắng thực hiện hành động. Ví dụ: Kẻ tấn công chỉ cần buộc các trình duyệt đến các URL mục tiêu. Quyền quản trị được yêu cầu để truy cập vào trang quản trị: `https://example.com/app/getappInfo` => `https://example.com/app/admin`. #h4("Lỗ hổng Cryptographic Failures") Bảo mật thông tin nhạy cảm bằng cách mã hóa thông tin theo các cách khác nhau, nhưng nếu cách mã hóa đó kẻ tấn công có thể giải mã được hay là cách thức giải mã không đảm bảo an toàn bản rõ thì những thông tin nhạy cảm đó sẽ bị rò rỉ ra ngoài. Các phương pháp phổ biến: - Sử dụng những giao thức truyền dữ liệu dạng rõ như HTTP, FTP,... - Sử dụng những mã hóa đã cũ hoặc yếu. - Sử dụng những hàm băm không dùng nữa như MD5, SHA1. - Khóa bí mật dễ đoán. - Chuỗi mã hóa không được xác thực. Biện pháp phòng chống: - Không sử dụng những giao thức đã cũ như FTP, SMTP,... để vận chuyển dữ liệu nhạy cảm. - Đảm bảo các thuật toán mã hóa đạt tiêu chuẩn mạnh mẽ. - Mã hóa dữ liệu trên đường truyền bằng TLS, HTTPS. - Lưu trữ password bằng các hàm băm mạnh như Argon2, scrypt, bcrypt,... - Luôn sử dụng mã hóa được xác thực thay vì chỉ mã hóa. Ví dụ: Một trang web không sử dụng TLS cho tất cả các trang hoặc hỗ trợ mã hóa yếu. Kẻ tấn công giám sát lưu lượng mạng (như tại một mạng không dây không an toàn), hạ cấp các kết nối từ HTTPS xuống HTTP, chặn các yêu cầu và đánh cắp cookie phiên của người dùng. Sau đó, kẻ tấn công phát lại cookie này và chiếm quyền điều khiển phiên của người dùng, truy cập hoặc sửa đổi dữ liệu cá nhân của người dùng. Thay vì những điều trên, họ có thể thay đổi tất cả dữ liệu được vận chuyển, ví dụ như người nhận chuyển tiền. #h4("Lỗ hổng SQL Injection") Lỗi bảo mật SQL Injection là một trong những lỗi phổ biến nhất trong các website TMĐT. Đây là lỗi bảo mật cho phép kẻ tấn công thực hiện các cuộc tấn công vào cơ sở dữ liệu của trang web bằng cách chèn các câu lệnh SQL độc hại vào các trường đầu vào trên trang web. Khi khai thác lỗi SQL Injection, kẻ tấn công có thể truy xuất và thay đổi dữ liệu trong cơ sở dữ liệu của trang web, thực hiện các hoạt động xóa hoặc thêm mới dữ liệu, và thậm chí kiểm soát toàn bộ trang web. Với những biện pháp trên, trang web TMĐT sẽ giảm thiểu được rủi ro bị tấn công SQL Injection và đảm bảo an toàn cho khách hàng trong quá trình giao dịch mua bán sản phẩm trên trang web. Ví dụ, trong một hệ thống với 1000 đầu vào, lọc thành công 999 đầu vào là không đủ vì điều này vẫn để lại một phần giống như "gót chân Asin", có thể phá hoại hệ thống bất cứ lúc nào. Ta có thể cho rằng đưa kết quả truy vấn SQL vào truy vấn khác là một ý tưởng hay vì cơ sở dữ liệu là đáng tin cậy. Nhưng thật không may vì đầu vào có thể gián tiếp đến từ những kẻ có ý đồ xấu. Đây được gọi là lỗi Second Order SQL Injection. Việc lọc dữ liệu khá khó vì thế nên sử dụng các chức năng lọc có sẵn trong framework. Các tính năng này đã được chứng minh sẽ thực hiện việc kiểm tra một cách kỹ lưỡng. Vì thế ta nên cân nhắc sử dụng các framework vì đây là một trong các cách hiệu quả để bảo vệ máy chủ. #h4("Lỗ hổng Insecure Design (Thiết Kế Không An Toàn)") Thiết kế an toàn là phân tích các giả định và điều kiện cho các dòng dự kiến đảm bảo chính xác, tránh trường hợp không mong muốn và có hành vi phù hợp với từng trường hợp. Đảm bảo kết quả được ghi lại trong nhật kí của người dùng. Học hỏi từ những sai lầm và đưa ra những cải tiến thích hợp. Biện pháp phòng chống: - Thiết lập sử dụng những thư viện mẫu thiết kế an toàn. - Kiểm tra tính hợp lí ở mỗi cấp ứng dụng. - Tách các lớp phần trên hệ thống và các lớp mạng. - Hạn chế tiêu thụ tài nguyên người dùng hoặc dịch vụ. Ví dụ: Một rạp chiếu phim cho phép đặt chỗ theo nhóm tối đa 15 người trước khi đặt tiền cọc, một kẻ tấn công có thể chạy lệnh để đặt tất cả các chỗ trong rạp sau đó dừng lại ở bước đặt cọc, gây tổn thất lớn về kinh tế. #h4("Lỗ hổng Security Misconfiguration") Nếu Insecure Design thuộc về phần thiết kế thì Security Misconfiguration thuộc về phần triển khai. Những lỗi phổ biến thường xảy ra: - Các tính năng không cần thiết được bật như các port, service, account,... - Thiếu việc tăng cường bảo mật cho từng phần của ứng dụng. - Các tài khoản và mật khẩu vẫn để mặc định không thay đổi. - Phần mềm đã lỗi thời. Trong thực tế, máy chủ website và các ứng dụng đa số bị cấu hình sai. Có lẽ do một vài sai sót như: - Chạy ứng dụng khi chế độ debug được bật. - Directory listing. - Sử dụng phần mềm lỗi thời (WordPress plugin, PhpMyAdmin cũ). - Cài đặt các dịch vụ không cần thiết. - Không thay đổi default key hoặc mật khẩu. - Trả về lỗi xử lý thông tin cho kẻ tấn công lợi dụng để tấn công, chẳng hạn như stack traces. Biện pháp phòng chống: - Loại bỏ những tài nguyên, tính năng không cần thiết. - Cung cấp sự hiệu quả và an toàn giữa các thành phần. - Liên tục cập nhật những phiên bản mới nhất. Ví dụ: Danh sách thư mục không bị tắt trên máy chủ. Kẻ tấn công phát hiện ra chúng có thể liệt kê các thư mục một cách đơn giản. Điều này có thể dẫn đến kẻ tấn công dịch ngược lại đoạn code và là tiềm ẩn rất lớn cho nhiều mối nguy hiểm khác. #h3("Các yêu cầu an toàn của một website TMĐT") Một website thương mại điện tử cần đáp ứng nhiều yêu cầu an toàn để bảo vệ thông tin cá nhân của người dùng và người bán, đảm bảo giao dịch an toàn và tránh các rủi ro liên quan đến bảo mật. Dưới đây là một số yêu cầu an toàn quan trọng của một website TMĐT: @buildwebapp - Xác thực và quản lý truy cập: Cung cấp hệ thống xác thực đáng tin cậy để đảm bảo rằng chỉ người dùng hợp lệ mới có thể truy cập vào tài khoản và thông tin cá nhân. Đồng thời, quản lý quyền truy cập để giới hạn quyền truy cập chỉ cho những người được ủy quyền. - Bảo vệ thông tin cá nhân: Đảm bảo rằng thông tin cá nhân của người dùng được bảo vệ an toàn và không bị truy cập, sử dụng hoặc tiết lộ trái phép. Áp dụng các biện pháp bảo mật như mã hóa dữ liệu, sử dụng giao thức an toàn (SSL/TLS) cho việc truyền tải thông tin và tuân thủ quy định về bảo vệ dữ liệu cá nhân. - Bảo mật giao dịch: Đảm bảo rằng quá trình thanh toán và giao dịch trên website được bảo mật. Sử dụng giao thức mã hóa SSL/TLS để bảo vệ thông tin thanh toán, hạn chế lưu trữ thông tin thẻ tín dụng và áp dụng các biện pháp kiểm tra giao dịch an toàn như xác thực hai yếu tố (2FA). - Quản lý mã độc và tấn công: Đảm bảo hệ thống website không bị tấn công bởi các loại mã độc, phần mềm độc hại và các cuộc tấn công mạng khác. Áp dụng các biện pháp bảo vệ bảo mật cơ bản như cập nhật hệ điều hành và phần mềm định kỳ, kiểm tra lỗ hổng bảo mật, sử dụng tường lửa (firewall), và các biện pháp phòng ngừa tấn công. - Quản lý rủi ro liên quan đến dữ liệu: Đảm bảo rằng dữ liệu người dùng và dữ liệu liên quan đến giao dịch được lưu trữ, sao lưu và phục hồi một cách an toàn. Thực hiện các biện pháp bảo vệ dữ liệu như mã hóa dữ liệu, sao lưu định kỳ và đảm bảo tính toàn vẹn của dữ liệu. - Quản lý lỗ hổng bảo mật: Thực hiện việc theo dõi, phát hiện và xử lý lỗ hổng bảo mật trong hệ thống website. Cập nhật và vá lỗi phần mềm định kỳ, thực hiện quản lý rủi ro bảo mật để ngăn chặn và giảm thiểu các mối đe dọa tiềm năng. - Tuân thủ quy định pháp luật: Đảm bảo rằng website tuân thủ các quy định và quyền riêng tư liên quan đến bảo vệ thông tin cá nhân, bảo mật giao dịch và quyền lợi của người dùng. Điều này bao gồm việc tuân thủ các quy định như GDPR (Quy định chung về bảo vệ dữ liệu) và các quy định pháp luật liên quan đến thương mại điện tử. - Giám sát và phản ứng sự cố: Thiết lập hệ thống giám sát liên tục để theo dõi các hoạt động bất thường và phản ứng kịp thời đối với các sự cố bảo mật. Đưa ra các biện pháp phòng ngừa và ứng phó sự cố để đảm bảo rằng website được bảo vệ một cách liên tục. Những yêu cầu an toàn này đặc biệt quan trọng trong lĩnh vực thương mại điện tử, vì thông tin cá nhân và giao dịch của khách hàng là tài sản quý giá và phải được bảo vệ một cách tốt nhất. Sự tuân thủ và triển khai hiệu quả các yêu cầu an toàn này sẽ giúp xây dựng niềm tin và tăng cường sự thụ động của người dùng trong việc sử dụng website thương mại điện tử. #h2("Kết chương") Trong chương 1 đã tìm hiểu về TMĐT và website TMĐT, tìm hiểu các lỗi bảo mật phổ biến mới nhất hiện nay. Từ những phần tìm hiểu này cho thấy việc xây dựng 1 trang website TMĐT an toàn với doanh nghiệp cũng như khách hàng sử dụng là vô cùng quan trọng. Phần tiếp theo của đồ án sẽ nói về phân tích và thiết kế website TMĐT xây dựng dưa trên việc khảo sát và xác định yêu cầu ở Chương 1.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/X_typik/typik.typ
typst
#import "../CU_json/all.typ": * #show: book #set page ( margin: 4em ) == ЧА́СТИ СОСТА́ВНЫѦ ТѴПЇКА̀. Тѵпи́къ се́й составлѧ́етсѧ и҆зъ пѧтѝ ча́стей, ѿ нн́хжє І-ѧ содєржи́тъ ви́дъ о҆́бщїй Богослꙋже́нїѧ; ІІ-ѧ Оу҆ста́вы о҆́бщїѧ разли́чнымъ Слꙋ́жбамъ О҆ктїѡиховымъ, та́кождє и҆ Мине́ниымъ; ІІІ-ѧ Оу҆ста́вы со́вствєнныѧ нѣ́кїимъ Слꙋ́жвамъ Мние́ниымъ; IV-ѧ Оу҆ста́вы со́вствєнныѧ Слꙋ́жвамъ Трїѡ́дьнымъ; V-ѧ Оу҆ста́вы со́вствєнныѧ Пра́здникѡмъ Храмовы́мъ. = Часть І. == ВИ́ДЪ Ѻ҆́БЩЇЙ БОГОСЛꙊЖЕ́НЇѦ #sText([по Оу҆ста́вꙋ Собо́ра Льво́вскагѡ провїнцїа́льнагѡ.]) Сє̀ те́ѯтъ Собо́ра #footnote([И҆звлєченъ ѿ прибавле́нїѧ XXXI.]) съ примѣча́ньми на́шими на сподѣ. #footnote([Бѡкето взѧл, ѡ҆къ Сѵборъ подлѣжїтъ Ѡ҆ѵставѡ тѡлькѡ елъ І-ѧ Частѣй, Ѡ҆ѵставѡ же прѵчихъ чєтѵрєхъ Частей подлѣжїтъ и҆ли Ѡ҆ разлїчныхъ Книгъ Богослѵжебныхъ славѧнскихъ и҆ Грѵческихъ, въ Ѡбыкновеннѣѧ Церковї.]) === Ѡ РАЗЛЇЧНЫХЪ ЧѲСТЕХЪ БОГОСЛѴЖЕНЇѦ. Частѣй Богослѵженїѧ ѥстѧ дѣвѣть: Вечєрнѧ, Повєчєрїѧ, Полѡѵночница, Ѡ҆трєѵ, чєтѵре Часѡ, сїрѵчь: Часъ а҆., г҃., д҃., и҆ ѕ҃. и҆ Лїтѵргїѧ, ѵли въ мѣсто ѥл Ѡбѵдница, рѣкше Изобразителнѧ. #footnote([Ѡбѡстѣѧ ѵ Лїтѵргїѧ не подлѣжїмъ, зѧнъ сей въ новоначалнѣхъ Бѫдѝеамъ Ѡктїохъ҇икѡ тѵхъ подлѣжїтъ.]) „Разлїч четы́рехъ Часо́въ, ѵѥже нѝжє сєи ѵпѡктъ єди́нъ и҆ тѡѧже кѵѥ, проѥхѵй какъ чѣсти Богослѵжѥнїѧ ѵмѡкѡтъ болѣе видѣнъж. Ѡще: Вечѣрнѧ єсть велїкаѧ, послѣдѣннѧѧ, и҆ малаѧ; пакѝ же велїкаѧ єсть нѵи съ Всенощнымъ, нѵи безъ Всенощнѵг. Повечєрїѧ єсть велїкое и҆ малое; и҆ пакѝ велїкое єсть нѵи безъ Всенощнѵг и҆ съ Всенощнымъ. Полѡѵночница єсть послѣдѣннѧѧ, Свѧтїчнѧѧ, и҆ Недѣльнѧѧ. Ѡ҆трєѵ єсть велїкаѧ и҆ малаѧ, сїрѵчь: послѣдѣннѧѧ; и҆ пакѝ велїкаѧ єсть нѵи безъ, и҆ли съ Всенощнымъ. — Лїтѵргїѧ єсть свѣршеннѧѧ, сїрѵчь Златѡѵстѣвѧѧ, и҆ Василїѧ, пакѝ несовѣршеннѧѧ, сїрѵчь Преждеосвѧщеннѧѧ.“ == Ѡ Вечѣрни. чѣтѝ вечѣрни велїкаѧ нѵ Всенощнѵг. 1. Кѡспрїатїѧ склѵпѣнныхъ ѡдѣждъ, и҆ каждѣнїѧ. „Кѡзвѣннымъ съвѣннѵцъ съвѣннѵс ѡгтѡѫ на велїкихъ Ѡлтарѧхъ, и҆ ѡѹтѡтѡканнѧмъ дѣкахъ кѡдѵлнѵницѣмъ, ѡще бъѧть длѧ Дїакѡнїи, ѡще же нѝ, то тѡлькѡ єди́нѵѧ, Ѡрѣѝ полѡгасѵѫ въско́, на кѡѫ Благослѡвѧнїѧ Лїтѵргїйнѧго сложєнїѧ, (ѡтпѡгрѵчѧнїѧ, и҆ полѡжѧкѡ бѧть та́мѡ и҆на́къ малѡ крѣстъ, кѡзлѡгѧєтъ єгѡ на себѣ #footnote([Ѡсловлѵ Грѣчесїи и҆ Мѵнеѧ Блав. (ѡѯ. Дѣк. на Всенощнѵг сѵ Повечєрїѧ велїкїѧ, принадлѣжить бъѧ и҆ ѹсѡбѵ, Ѡвѣтѡкъ же нашѧтѵ Свѧнѵчнамъ, въ Гринѧ Россїйски примѡжеть то́лькѡ ѡбтѡрѵй. Также: Книгъ Грѣчесїи примѡѥть должнѡ имѧхъ та́мъ же Ѡсвѣдѣнѵѧмъ: Каї ѵсѣлѡвѵсъ (Ѡрѣи и҆ Дїакѡнъ) благословѧю тѵн ѥсѡстѡлѵмъ ѵпѡлѣнъ тѡ диѡконїѧ. (Кавр. в.).])), Дїакѡнъ же Далматїѧскъ ѡрѡрѵѫ, полѡкловѧкѡ же прѡѥѧ, и҆ неслѡдѣтъ кѡ триѧ, єди́нѧ за Ѡрѣѝмъ, нѵго Дїакѡнъ къ-нѝ, пакѝ а҆-и҆, слѣжѧ же Ѡрѣѝ, нѧж Госпѡдѡрѵхѵниннѧ предъ стѣннѧѧ Ѡлтарѧмъ, и҆ ставѝшъ Дїакѡнъ къ-мс пѡ ѵкѡмъ, ҆-мс пѡ
https://github.com/thornoar/lambda-calculus-course
https://raw.githubusercontent.com/thornoar/lambda-calculus-course/master/main-lectures/exam-problems.typ
typst
#import "template.lib.typ": * #show: formatting #set page(background: image("pictures/troubles-faded.jpg", width: 100%, height: 100%, fit: "stretch")) #set heading(numbering: none) #head([ Экзаменационные задачи ]) == На 5:
https://github.com/Slyde-R/not-jku-thesis-template
https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/titlepage.typ
typst
MIT No Attribution
#let titlepage( thesis-type: "", degree: "", program: "", supervisor: "", advisors: (), department: "", author: "", date: none, title: "" ) ={ set par(leading: 0.65em, first-line-indent: 0em, justify: false) show par: set block(spacing: 1.2em) // spacing after a paragraph place(bottom+left,float: false, dx: 0cm, dy:-10%)[#box(width: 74%)[ // Title in upper case #text(size: 28pt, weight: "black", font: "Arial")[#upper[#title]] // JKU big-K Logo #image("big_K.png", width: 125pt) //#v(-1cm) // Additional Information #set text(weight: "regular", font: "Arial") #text(size: 14pt)[#thesis-type's Thesis\ ] #text(size: 11pt)[to confer the academic degree of\ ] #text(size: 14pt)[#degree\ ] #text(size: 11pt)[in the #thesis-type's program\ ] #text(size: 14pt)[#program ] ] ] // JKU logo in the header place(top+right ,float: false, dx: 1cm, dy: -1.6cm)[#box(width: 26%)[ // Title #align(right)[#image("JKU.png", width: 150pt)] ] ] place(top+right ,float: false, dx: 1.2cm, dy: 3cm)[#box(width: 28%)[ // Title #align(left)[ #text(size: 9pt)[ Author\ *#author* \ \ Submission\ *#department*\ \ Thesis Supervisor\ *#supervisor*\ \ #if advisors != () and advisors != "" [ #if advisors.len()>=2 [ Assistant Thesis Supervisors\ ] else [ Assistant Thesis Supervisor\ ] *#advisors.join(", \n")*\ \ ] #date.display("[month repr:long] [year]") ] ] ] ] place(bottom+right ,float: false, dx: 1cm, dy:1cm)[#box(width: 25%)[ // Title #align(left)[ #text(size: 8pt)[ #text(size: 8pt, weight: "black", font: "Arial")[<NAME> UNIVERSITY LINZ]\ Altenberger Straße 69\ 4040 Linz, Austria\ jku.at\ ] ] ] ] pagebreak() }
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/grid/colspan.typ
typst
Apache License 2.0
#let ofi = [Office] #let rem = [_Remote_] #let lea = [*On leave*] #show table.cell.where(y: 0): set text( fill: white, weight: "bold", ) #table( columns: 6 * (1fr,), align: (x, y) => if x == 0 or y == 0 { left } else { center }, stroke: (x, y) => ( // Separate black cells with white strokes. left: if y == 0 and x > 0 { white } else { black }, rest: black, ), fill: (_, y) => if y == 0 { black }, table.header( [Team member], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday] ), [<NAME>], table.cell(colspan: 2, ofi), table.cell(colspan: 2, rem), ofi, [<NAME>], table.cell(colspan: 5, lea), [<NAME>], rem, table.cell(colspan: 2, ofi), rem, ofi, ) #table( columns: 4 * (1fr,), [a], [b], [c], [d], fill: (_, y) => if y == 0 { black }, table.cell(rowspan: 2)[aa], table.cell(colspan: 2)[bc], [d], [b], table.cell(colspan: 2)[cd], )
https://github.com/smallscientist1/ustcthss-typst
https://raw.githubusercontent.com/smallscientist1/ustcthss-typst/main/README.md
markdown
MIT License
# ustcthss-typst 中国科学技术大学本科生毕业论文typst模版 中国科学技术大学本科生毕业论文的typst模版, 能够一键生成论文pdf文件。 按照[2024年中国科学技术大学教务处毕业论文格式要求](https://www.teach.ustc.edu.cn/notice/notice-teaching/17071.html) 编写。 **欢迎提出任何 Issue 和 PR 帮助完善这个模板。** ![ustcthss-typst](./images/cover_ustc.png) ## 使用方式 ### 方式一: 本地编译 - 下载安装最新版本的[Typst](https://github.com/typst/typst) - 克隆本仓库。 - 修改`thesis.typ`完成你的论文写作,`thesis.typ`是论文模版,其中包含了标题、段落、图片、公式、表格、引用、参考文献等的几乎所有毕业论文可能用到的特性。 - 在命令行中,执行`typst compile thesis.typ --font-path fonts`进行编译,生成同名的`thesis.pdf`文件。 ### 方式二: 在线编译 进入 [Typst](https://typst.app/) 官网 ,并将本模板的文件导入进去,包括`typ`文件、`fonts/`下的字体、图片文件。然后修改`thesis.typ`完成你的论文写作。 ## 致谢 - 本仓库基于[PKUTHSS-Typst](https://github.com/pku-typst/pkuthss-typst)修改得到,感谢开发者的贡献。 - 本仓库双语参考文献的实现参考了[SEU-Typst-Template](https://github.com/csimide/SEU-Typst-Template/tree/master?tab=readme-ov-file#%E5%8F%82%E8%80%83%E6%96%87%E7%8C%AE),感谢开发者的贡献。
https://github.com/r8vnhill/apunte-bibliotecas-de-software
https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit3/Tasks.typ
typst
== Tareas Una tarea es una unidad de trabajo que Gradle puede ejecutar. Puede representar cualquier cosa, desde compilar código, ejecutar pruebas, generar documentación, hasta desplegar una aplicación. Las tareas se definen en algún archivo `build.gradle.kts` y pueden ser muy simples o bastante complejas dependiendo de lo que necesiten hacer. === Tareas Predefinidas Gradle proporciona un conjunto de tareas predefinidas que son comunes en la mayoría de los proyectos. Algunos ejemplos de tareas predefinidas son: ==== Ejemplo de Tarea de Prueba ```kotlin tasks.test { useJUnitPlatform() } ``` Esta tarea configura Gradle para utilizar el motor de JUnit para correr los tests. ==== Ejemplo de Tarea de Copiado ```kotlin tasks.create<Copy>("copy") { // Es buena práctica añadir esto a nuestras tareas description = "Copies sources to the destination directory" group = "Custom" from("src") into("dst") } ``` Esta tarea de copiado mueve archivos desde el directorio `src` al directorio `dst`. - *description*: - Proporciona una descripción de la tarea. Es una buena práctica para hacer nuestras tareas más comprensibles. - *group*: - Asigna la tarea a un grupo. En este caso, se asigna al grupo "Custom". ==== Ejecución de Tareas Predefinidas ```powershell # Windows .\gradlew.bat test .\gradlew.bat copy ``` ```bash # Unix ./gradlew test ./gradlew copy ``` Para ejecutar las tareas predefinidas, utiliza el comando `gradlew` seguido del nombre de la tarea. En Windows, usa `.\gradlew.bat`, y en Unix, usa `./gradlew`. ==== Tareas Predefinidas Comunes - *assemble*: - Ensambla el proyecto completo. - *build*: - Construye el proyecto. - *clean*: - Elimina los archivos generados por la construcción previa. - *check*: - Ejecuta todas las verificaciones, incluyendo pruebas. Estas tareas predefinidas facilitan la configuración y ejecución de las operaciones comunes en los proyectos Gradle. === Acciones - `doFirst`: - Agrega una acción que se ejecutará al inicio de la tarea, antes de cualquier otra acción configurada en la tarea. - Se usa cuando necesitas realizar alguna preparación o configuración previa antes de la ejecución principal de la tarea. - `doLast`: - Agrega una acción que se ejecutará al final de la tarea, después de todas las demás acciones configuradas en la tarea. - Se usa cuando necesitas realizar alguna operación de limpieza, validación final o cualquier acción que debe ejecutarse después de la ejecución principal de la tarea. ==== Ejemplo de Uso de `doFirst` y `doLast` ```kotlin tasks.register("Fib") { var first = 0 var second = 1 doFirst { println("What's going on?") for (i in 1..11) { second += first first = second - first } } doLast { println("The 12th Fibonacci number is $second") } } ``` En este ejemplo: - *doFirst*: - Imprime un mensaje antes de iniciar el cálculo de la serie de Fibonacci y calcula los primeros 12 números de la serie. - *doLast*: - Imprime el 12.º número de Fibonacci después de que se ha completado el cálculo. Para ejecutar esta tarea, utiliza el comando: ```powershell # Windows .\gradlew.bat Fib ``` ```bash # Unix ./gradlew Fib ``` Aquí tienes la versión mejorada y desarrollada usando la sintaxis de Typst: ==== Orden de ejecución de acciones Las acciones agregadas con `doFirst` se ejecutan en el orden inverso en que se definen (las últimas se ejecutan primero). Las acciones agregadas con `doLast` se ejecutan en el orden en que se definen (las primeras se ejecutan primero). #line(length: 100%) *Ejercicio: Orden de Ejecución de Acciones* ¿Qué se imprimirá al ejecutar la siguiente tarea? ``` tasks.register("advancedTask") { doFirst { println("First action - Preparation Step 1") } doFirst { println("First action - Preparation Step 2") } doLast { println("Last action - Cleanup Step 1") } doLast { println("Last action - Cleanup Step 2") } } ``` #line(length: 100%) === Dependencia de Tareas Las tareas pueden depender de otras tareas. Esto asegura que las tareas se ejecuten en un orden específico. ```kotlin tasks.register("cleanAll") { // Define una tarea que limpia todos los subproyectos dependsOn(":subproject1:clean", ":subproject2:clean", ":subproject3:clean") } ``` En este ejemplo, la tarea `cleanAll` depende de las tareas `clean` de los subproyectos `subproject1`, `subproject2`, y `subproject3`. Esto significa que cuando se ejecuta `cleanAll`, Gradle primero ejecutará las tareas `clean` de cada uno de los subproyectos especificados. #line(length: 100%) *Ejercicio: Tamaño del Proyecto* Crea una tarea de Gradle que calcule el tamaño de su proyecto luego de compilarse. Para esto, considera que puedes acceder a los archivos compilados haciendo `project.fileTree("build/classes/kotlin/main").files`. Luego, puedes acceder al tamaño del archivo con el método `length()`. Incluye un grupo y descripción para tu tarea. Tu tarea debe depender de `compileKotlin`. #line(length: 100%) Aquí tienes la versión mejorada y desarrollada usando la sintaxis de Typst: === Tareas como clases Supongamos que tenemos que calcular el número de Fibonacci de forma repetida. Podemos definir una clase (abstracta)#footnote[ Podemos usar una clase abierta, pero tiene más sentido que sea abstracta ya que es abierta por definición y sólo será ocupada para ser extendida. ] para representar familias de tareas. ==== Caso de estudio: Tarea de Fibonacci ```kotlin abstract class FibonacciTask : DefaultTask() { // 1 @get:Input abstract val number: Property<Int> // 2 @TaskAction // 3 fun calculateFibonacci() { val n = number.get() if (n < 0) { throw StopExecutionException("The number must be positive") } var first = 0 var second = 1 repeat(n) { second += first first = second - first } println("The $n-th Fibonacci number is $first") } } ``` 1. *Todas las tareas deben extender de DefaultTask*: - Esto asegura que nuestra clase personalizada se comporte como una tarea de Gradle. 2. *Podemos definir inputs para nuestra tarea*: - Utilizamos propiedades anotadas con `@Input` para definir los parámetros que nuestra tarea necesitará. 3. *`@TaskAction` marca el código principal que ejecutará la tarea*: - Este método contiene la lógica principal que se ejecutará cuando la tarea se ejecute. ==== Registro de Tareas ```kotlin tasks.register<FibonacciTask>("Fib_10") { number.set(10) } tasks.register<FibonacciTask>("Fib_20") { number.set(20) } ``` En este ejemplo, registramos dos instancias de la tarea `FibonacciTask`, una para calcular el 10.º número de Fibonacci y otra para el 20.º. ==== Ejecución de Tareas ```powershell # Windows .\gradlew.bat Fib_10 .\gradlew.bat Fib_20 ``` ```bash # Unix ./gradlew Fib_10 ./gradlew Fib_20 ``` Para ejecutar las tareas `Fib_10` y `Fib_20`, utiliza el comando `gradlew` seguido del nombre de la tarea correspondiente. En Windows, usa `.\gradlew.bat`, y en Unix, usa `./gradlew`. #line(length: 100%) *Ejercicio: Tarea de Fibonacci* ¿Qué imprime el siguiente código? ```kotlin tasks.register<FibonacciTask>("Fib_10") { number.set(10) doFirst { println("Preparing to calculate the 10th Fibonacci number") } doLast { println("Finished calculating the 10th Fibonacci number") } } ``` #line(length: 100%) ==== Caso de estudio: Procesar archivos de texto Implementaremos una tarea para procesar archivos de texto. Tendremos archivos de entrada y salida. El texto debe ser tomado de un archivo de texto (input), transformado en mayúsculas y ser guardado en otro archivo de texto (output). ```kotlin abstract class TextProcessingTask : DefaultTask() { @get:InputFile abstract val inputFile: RegularFileProperty @get:OutputFile abstract val outputFile: RegularFileProperty @TaskAction fun processText() { val inputText = inputFile.get().asFile.readText() val processedText = inputText.uppercase(Locale.getDefault()) outputFile.get().asFile.writeText(processedText) println( "Text has been processed and written to " + outputFile.get().asFile.absolutePath ) } } ``` ===== Registro de la Tarea ```kotlin tasks.register<TextProcessingTask>("processText") { inputFile.set(file("src/main/resources/input.txt")) outputFile.set(file("build/output.txt")) // Acción que se ejecuta antes de la acción principal doFirst { println( "Preparing to process text from ${inputFile.get().asFile.absolutePath}" ) } // Acción que se ejecuta después de la acción principal doLast { println( "Finished processing text. Output written to " + outputFile.get().asFile.absolutePath ) } } ``` ===== Ejecución de la Tarea ```powershell # Windows .\gradlew.bat processText ``` ```bash # Unix ./gradlew processText ``` Para ejecutar la tarea `processText`, utiliza el comando `gradlew` seguido del nombre de la tarea correspondiente. En Windows, usa `.\gradlew.bat`, y en Unix, usa `./gradlew`. ===== Explicación del Código - *TextProcessingTask*: - *`@InputFile` y `@OutputFile`*: - Define los archivos de entrada y salida usando las propiedades `RegularFileProperty`. - *`@TaskAction`*: - Marca el método `processText` como la acción principal de la tarea. - Lee el texto del archivo de entrada, lo transforma a mayúsculas y lo escribe en el archivo de salida. - *Registro de la tarea*: - Configura los archivos de entrada y salida. - Usa `doFirst` para realizar acciones antes de la tarea principal y `doLast` para acciones después de la tarea principal.
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/sol-charlie.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Solutions to Part Charlie == Solution to @exer-teacup We are tasked with parametrizing the motion of a toddler sitting in a teacup on an amusement park ride. The teacup ride rotates clockwise around a fixed center, while each individual teacup rotates counterclockwise. We also want to compute the distance traveled by the toddler after one full revolution of the teacup ride. We will first parametrize the motion of the toddler and then compute the distance traveled after one full revolution of the ride. 1. The teacup center rotates clockwise with angular velocity $omega_(upright("ride"))$ in a circular path of radius $R$ around a fixed center. The position of the teacup center as a function of time $t$ is: $ bf(C) (t) = vec(R cos (omega_(upright("ride")) t) , - R sin (omega_(upright("ride")) t)) . $ This describes the circular motion of the teacup center around the fixed center of the ride, with the negative sign on the sine term indicating clockwise rotation. 2. The toddler is sitting on the edge of the teacup, which rotates counterclockwise with angular velocity $omega_(upright("cup"))$ and radius $r$. Initially, at $t = 0$, the toddler is positioned at $(r , 0)$ relative to the center of the teacup. The position of the toddler relative to the center of the teacup is: $ bf(T)_(upright("relative")) (t) = vec(r cos (omega_(upright("cup")) t) , r sin (omega_(upright("cup")) t)) . $ This describes the counterclockwise circular motion of the toddler relative to the center of the teacup. 3. To find the total position of the toddler as a function of time, we sum the position of the teacup center $bf(C) (t)$ and the position of the toddler relative to the teacup $bf(T)_(upright("relative")) (t)$. The total position of the toddler is: $ bf(T) (t) = bf(C) (t) + bf(T)_(upright("relative")) (t) . $ Substituting the expressions for $bf(C) (t)$ and $bf(T)_(upright("relative")) (t)$, we get: $ bf(T) (t) = vec(R cos (omega_(upright("ride")) t) , - R sin (omega_(upright("ride")) t)) + vec(r cos (omega_(upright("cup")) t) , r sin (omega_(upright("cup")) t)) . $ Simplifying, we have: $ bf(T) (t) = vec(R cos (omega_(upright("ride")) t) + r cos (omega_(upright("cup")) t) , - R sin (omega_(upright("ride")) t) + r sin (omega_(upright("cup")) t)) . $ This gives the parametrization of the toddler’s position as a function of time. The velocity vector $bf(T)' (t)$ is the derivative of the position vector $bf(T) (t)$ with respect to time: $ bf(T)' (t) = vec(- R omega_(upright("ride")) sin (omega_(upright("ride")) t) - r omega_(upright("cup")) sin (omega_(upright("cup")) t) , - R omega_(upright("ride")) cos (omega_(upright("ride")) t) + r omega_(upright("cup")) cos (omega_(upright("cup")) t)) . $ == Solution to @exer-helicopter Let's first parametrize $bf(P)(t)$: 1. Since the helicopter is moving upward with constant speed $v = 5$, the height of the helicopter at time $t$ is given by: $ z (t) = v t = 5 t . $ 2. The point $P$ is on the tip of the rotor blade, which is spinning clockwise with angular velocity $omega = pi / 3$. In the horizontal plane, the position of $P$ relative to the center of the rotor can be parametrized as: $ bf(v) (t) = vec(r cos (omega t) , - r sin (omega t)) , $ where $r = 2$ is the radius of the blade, and the negative sign in the $y$-coordinate reflects the clockwise rotation. Thus, the position of $P$ in the $x y$-plane is: $ bf(v) (t) = vec(2 cos (pi / 3 t) , - 2 sin (pi / 3 t)) . $ 3. The total position of the point $P$ as a function of time is the combination of the upward motion in the $z$-direction and the rotational motion in the $x y$-plane. Thus, the position of $P$ is: $ bf(P) (t) = vec(2 cos (pi / 3 t) , - 2 sin (pi / 3 t) , 5 t) . $ This gives the full parametrization of the motion of the point $P$ on the tip of the blade as a function of time. As for the distance, we first compute the velocity vector by differentiating: $ bf(P)' (t) &= (d) / (dif t) vec(2 cos (pi / 3 t) , - 2 sin (pi / 3 t) , 5 t) = vec(- (2 pi) / (3) sin (pi / 3 t) , - (2 pi) / (3) cos (pi / 3 t) , 5) . $ The speed is the magnitude of the velocity vector: $ lr(|bf(P)' (t)|) = sqrt((- (2 pi) / (3) sin (pi / 3 t))^2 + (- (2 pi) / (3) cos (pi / 3 t))^2 + 5^2) . $ Using the trigonometric identity $sin^2 (theta) + cos^2 (theta) = 1$, this simplifies to: $ lr(|bf(P)' (t)|) &= sqrt(((2 pi) / (3))^2 + 5^2) = sqrt((4 pi^2) / (9) + 25) \ &= sqrt((4 pi^2) / (9) + 225 / 9) = sqrt((4 pi^2 + 225) / (9)) = sqrt(4 pi^2 + 225) / 3 $ which is a constant! Hence the total distance traveled is simply $ upright("Distance") = int_0^(18) sqrt(4 pi^2 + 225) / 3 dif t = 18 dot sqrt(4 pi^2 + 225) / 3 = 6 sqrt(4 pi^2 + 225). $ == Solution to @exer-clockblock To be written. Answer to part (b) is 4 o'clock.
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/complex.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Complex numbers I actually don't know why this subject is part of 18.02. #todo[To be written]
https://github.com/FrederikRichter/typwiki
https://raw.githubusercontent.com/FrederikRichter/typwiki/main/README.md
markdown
# About This is a wiki implementation in Typst. It is still experimental at best and should be seen as inspiration only. I am to recreate a knowledge database similar to wikipedia (in structure of course) for my undergrad studies.
https://github.com/typst-jp/typst-jp.github.io
https://raw.githubusercontent.com/typst-jp/typst-jp.github.io/main/docs/reference/welcome.md
markdown
Apache License 2.0
--- description: | Typst リファレンスは、Typst 言語の体系的かつ包括的なガイドです。 --- # リファレンス このリファレンスは Typst の文法、コンセプト、型、そして関数すべてについての包括的なガイドです。 Typst を使うのが初めてであればまず[チュートリアル]($tutorial)から始め、 必要に応じてリファレンスに戻って Typst のより詳しい機能を学ぶことをおすすめします。 ## 言語 { #language } 本リファレンスは[Typst の構文]($syntax)の概要を与える「言語」の章から始まり、 そこには[Typst のスクリプト機能]($scripting)を用いた[ドキュメントの整形]($styling)に関するコンセプトが含まれています。 ## 関数 { #functions } 2番目の章には、Typst ドキュメントにおけるコンテンツの挿入、整形、変形、 そしてレイアウトを行うのに用いられるすべての関数についての節が含まれます。 それぞれの関数にはその役割の説明、引数の一覧、そして使い方の例が記載されています。 最後の章には、データを操作・変形するためにTypst のコードモード内で用いられる すべての関数の説明があります。前の章と同様に、それぞれの関数にはその役割の説明、 引数の一覧、そして使い方の例が記載されています。
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/026%20-%20Eldritch%20Moon/005_Campaign%20of%20Vengeance.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Campaign of Vengeance", set_name: "Eldritch Moon", story_date: datetime(day: 06, month: 07, year: 2016), author: "<NAME>", doc ) #emph[A grudge a thousand years in the making is coming to a head.] #emph[For Sorin, it is for the warping of his ancestral home. It is the unmaking of Avacyn. It is the coming of Emrakul.] #emph[For Nahiri, it is the betrayal of a friend. It is the millennium spent trapped in the Helvault. It is the ruin of Zendikar in her absence.] #emph[When two ancient Planeswalkers duel, entire planes feel it.] #grid( columns: (1fr, 1fr), gutter: 2em, figure(image("005_Campaign of Vengeance/01.png", height: 40%), caption: [], supplement: none, numbering: none), figure(image("005_Campaign of Vengeance/02.png", height: 40%), caption: [], supplement: none, numbering: none), ) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("005_Campaign of Vengeance/03.jpg", width: 100%), caption: [Clue Token | Art by Cliff Childs], supplement: none, numbering: none) They called her the Harbinger. They weren't wrong, these fanatics and cultists, and they had followed her here, growing in number as she set about her work on Innistrad. They were devoted to her, and they reminded Nahiri that the only thing worth saving in this whole damned world was her revenge. The droning gibberish chorus of hundreds of cultists echoed through halls as she stared into the vampire's face. He was an ugly thing, with lips curled back to reveal hideous teeth, sharp and merciless. Two eyes, chips of amber swimming in inky pools, stared back at her, or rather past her. From what Nahiri could tell, this bloodsucker was dressed for luxury, and he, like the dozens of his kin around him, was embedded in the wall. All of them dead. On her account. She hated this place, <NAME>. Like so much of this plane, it reeked of Sorin. Even shattered, twisted, and reshaped, as she had done, it was not enough to purge the feel of him from it. But here she was. Preparations had been made, and work had to be checked. It's an intricate business, revenge, but then, Nahiri had had a thousand years to consider it. One. Thousand. Years. It was enough time to consider her revenge from all its angles and levels of depth, to play it out, tune it, and play it out again until everything was in its place—until it was a plan. And now, as Nahiri passed through the gnarled bones of Markov Manor, she allowed herself a slight smile. Everything was indeed in its place, where she'd put it—everything but Sorin. And he would be here soon. She'd brought something special with her this time, too, a collection she'd gathered when word reached her that Sorin was bringing an army to face her. Sure, she had her cultists, but revenge was no time to be sloppy. The first of Sorin's forces to arrive were the banners, ancient cloths that hung from black wooden poles, carried by vampire knights encased in polished plate armor. Hundreds of vampires fell in behind them, spreading out across the low hill opposite the manor. Nahiri watched the procession from the manor's massive arched entryway. When Sorin at last emerged at the front of his gathered force, Nahiri's jaw was clenched. Sorin was saying something to the vampires nearest him, though she couldn't make out what it was. #figure(image("005_Campaign of Vengeance/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) It didn't matter what he was saying though. All of this would end now. Sword in hand, Nahiri stepped out into the dull light of the day, out onto the broken causeway, and welcomed Sorin. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) A metallic screech cut through the clangor of battle as Nahiri dragged her sword's blade from the ornate breastplate of a dead vampire. The corpse was one of several that lay around her in a loose semicircle. Lungs pumping, she flung herself over the lifeless heap to meet a knot of new attackers. So many of them. But she just needed the one. An axe swung into view, crimson vapor trailing behind its black blade. Nahiri ducked out of range and thrust the point of her sword into the throat of another attacker who pressed in on her right. At a downward push of her free hand, the floor before her suddenly sank, so that when the axe arced in a second attack, it bit into the rim of the depression. Splinters of stone flew from the impact, and Nahiri caught them with her magic and drove them into the unprotected face of the axe wielder. Others closed in around her. One of them, a woman all in white-enameled plate armor, stepped out from among them. She held her sword low, and Nahiri noticed the weapon had a pair of blades that twisted in a helix until they met to form a nasty tip. The vampire spoke, never taking her eyes off Nahiri, "You're not going to escape." Nahiri cocked her head and raised an eyebrow. "Escape?" "When this is over," the vampire in white continued, "I'll drink your blood from—" But the vampire fell silent when a marble corbel smashed into her mouth, pulverizing those grotesque teeth. Nahiri had plucked it from the debris that hung suspended overhead. She'd heard enough. As the vampire in white crumpled to the floor, Nahiri sent the heavy hewn stone caroming off the handful of bloodsuckers nearest her until skulls and chests collapsed from the pummeling. When the bodies were still, the bloodied chunk of masonry spun in the air so that red droplets flung out in every direction. Nahiri wiped a smear of it from her check. If Sorin's plan was to tire her before they met, then he was a fool. A thousand years in the Helvault was rest enough for several lifetimes. If it meant ending every other bloodsucker in here to get to him, then she was already off to a good start. He was here somewhere, she knew. Around her, the melee was unfolding in what she remembered had once been the manor's great hall. The chamber was choked now with vampires and cultists, all at the grisly work of slaughtering each other. Her eyes darted over the chaos, hoping to pick out that flowing white hair, or... Those cruel yellow eyes. And for a heartbeat, they were staring back at her before being swallowed up in the roiling tumult. Nahiri's throat was suddenly dry. Her heart hammered against the inside of her chest, and all the rage of the last thousand years welled up in her until all she could do was force out the name, "Sorin!" Nahiri thrust her will into the sloping stone floor, and reaching into each of the enormous flagstones, she tugged at them sharply. Her hands jerked upward, and on either side of her, two parallel walls rose up a dozen feet from the floor. Stone ground against stone, and when they stopped, they ran the length of the hall to create a sort of passage, cut off from the main fray. She was at one end, Sorin at the other. Between them stretched a thin slice of the battle—a score of vampires and at least twice that many cultists, all still tangled in their fighting. One of the vampires lunged for Nahiri, but her vengeance was too near now for such distractions. A twitch of her finger, and a lance of stone emerged suddenly from the floor. It caught the armored bloodsucker under the breastplate through the abdomen, rising until it punched through the polished red steel at the shoulder with a shrill whine. The vampire just slumped in place, and Nahiri stepped past him as he slowly sank down the length of the stone quill. "Sorin," she called out again, her voice strong and cool as the stone she wielded. And then she was striding forward, her path direct and steady, as more quills sprang up before her to impale vampires and cultists alike. It was just the two of them, then. The last time Nahiri had seen Sorin, he had been the last thing she saw in the world before the solitude of the Helvault consumed her. Now, as she looked at him, standing a dozen or so paces away, he was much as she remembered him, though with none of the frailty from their previous meeting. He wore the same armor, but it was speckled with blood, which added a cruel sheen to the red stone that adorned his breastplate. His sword also bore evidence of his butchery. His face, so accustomed to displaying that sarcastic smirk that she knew so well, instead was creased with stern lines that she had never seen. It pleased her to see him so grim. "You brought so many friends," Nahiri said, stepping out from between two grisly spikes. "But then, not everyone could make it." She knew the mention of Avacyn would sting, but there was no sarcastic retort. Sorin just raised a pale hand, and jets of black, smoky energy streaked out. Death was in those trails of shadow, death meant for Nahiri. It appeared that he desired none of the pretense or poetry of a proper duel. Her end would be enough, and she watched Sorin, unmoving, as the sinister fingers reached for her. But the fingers never touched her. They suddenly broke apart, and flew in several directions, tracing contours in the air that were otherwise invisible. Sorin unleashed a second torrent of death magic just as the first errant bolts completed their tortuous paths back to their source, crashing into the vampire in a rapid sequence of high hisses. Sorin fell to one knee, biting his lip in anguish, and from between the plates of his armor, dark vapor rose from unseen wounds. "You must think very little of me if you thought that would work," Nahiri said as the second cluster of magic struck home just as the first had. "Magic flows through leylines. Leylines pass through stone. And, well, we both know what I can do with that. So by all means, Sorin, try that garbage again." She was circling him now. "I brought Emrakul to your doorstep, and you still think I'm a child." For a moment, neither spoke. More than six thousand years of history had led them both here. Staring into Sorin's eyes, Nahiri wondered if he was thinking the same thing. They had been friends, she once believed. And now...now she would have her vengeance. At last, Nahiri said, "A thousand years, Sorin. You locked me away for a thousand years." "And yet, you're still here." Sorin coughed, sending a billow of black mist into the air. "You should have left." "I did. I returned to Zendikar to see it being gutted by the Eldrazi. You let that happen." She raised her sword so that it was level with Sorin's throat. "You condemned me and my world." "You knew the risks when you agreed to trap the titans on Zendikar. You knew that their escape was a possibility." "I also knew that we had a deal." Nahiri felt her skin get hot. "If they did escape, you and Ugin were supposed to come. When they did, you were nowhere to be found. The way I saw it, the three of us were in it together. But it was only me. All that time, it was only ever me." "So you've decided to condemn this plane." "I'm done being a warden, and Zendikar will never again be a prison. Emrakul had to go somewhere. You just made the decision a simple one." "Sorin, I'm inclined to watch this play out," came a woman's voice, melodic and biting, from above. Nahiri's head tilted to find a vampire, clad all in elegant black plate armor, floating in the air overhead at the head of a dozen or more similarly adorned vampires. She wore no helmet, and her pale face and shock of brilliant red hair stood out against the dark metal. There was an air of grace that seemed to radiate from her, and Nahiri recognized a power that was akin to Sorin's. This woman was a bloodsucker of an ancient variety. "No doubt, Olivia," Sorin said from his kneeling position. Olivia motioned to Nahiri with a delicate sword wrought of black steel. "This is her, I take it." Without waiting for a confirmation, she simply addressed Nahiri. "Whatever Sorin's done to incur your ire, I'm sure he's earned it. But he's also earned my help, so I can't allow you your revenge." "Another guardian angel, Sorin? This one was bit rushed, I think," said Nahiri. She swept a hand out, and the stone slabs before her began to turn red with heat. Olivia smiled. "I like her Sorin, I must say. But nevertheless..." At her signal, her vampires descended on Nahiri. The stones in front of the lithomancer had become white-hot, and before the bloodsuckers could reach her, she willed the contents from the molten stones—four blades, identical to the one she wielded, each one pulsing with energy of their stone forge. She grabbed one so that she had a blade in either hand. The others fanned out above her like the plumage of a phoenix. #figure(image("005_Campaign of Vengeance/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "My revenge isn't yours to hand out. I earned this. Sorin is mine." "Never forget," Sorin hissed, "I spared you. The Helvault was a courtesy." "A courtesy," Nahiri repeated, her fingers twitching. She could rend him to pieces. "The horrors you locked me away with for so long—they became my world." On that last word, Nahiri sunk the points of her swords into one of the stone tiles. She clenched her fists, and the weapons began to vibrate. The trembling resonated through the floor, growing in strength as it spread out. What began as a low buzz swelled into a rumble that shook the surrounding structure. Bright ribbons of energy bloomed from her hands in rapid pulses, winding down the blades, until they radiated out along the masonry to reach into every stone in the manor. A handful of ley stones sprouted around her, all pointing outward so that they formed a kind of star. Then, the manor lurched. The walls she created to isolate her and Sorin fell away, and the entire hall began to rotate independently of the rest of the architecture. As it swung around, the foundation creaked like the joints of some ancient god rising for the first time in an age. It was a deafening sound, and it teetered on the edge of endurable. Soon another sound crept into her hearing. With every inch of the hall's rotation, the sound grew. It was a course, grating sound, not entirely unlike the chorus of the cultists, but this was not meant for, nor made by, people. The hall's arched entryway moved with the massive chamber so that it no longer led to the broken causeway beyond the manor's gate. When the circular motion stopped, the entryway settled before a featureless stone wall. The otherworldly sound swelled. Without the grinding of stone, there was no softening it, and she felt it in the roots of her teeth. But it was time. Nahiri reached out with her magic, and layers of that wall slid away in alternating directions. Even before she coaxed the last layer aside, it exploded in a shower of rubble, and out they came. Scores of monsters, bulbous and contorted, with only vague hints at the people and animals they had once been. They were Emrakul's now, touched by the Eldrazi titan so that their flesh stretched over their mutated forms in sinewy, tangled mesh. #figure(image("005_Campaign of Vengeance/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Nahiri had been gathering them here since Emrakul's arrival, locked away in her own vault, a gift meant for her old friend. Nahiri watched them stream from their black chamber, swarming into the hall toward her. She didn't flinch, though. Nightmares were nothing new to her. They closed in, and just as the terrible horde would have crashed into her, they broke around her. These monsters were blind to her within her ring of ley stones. Cryptoliths, she'd heard them described by the cultists, though they were far from cryptic. Eldrazi followed leylines, the network of mana that all worlds have. Just as she had done on Zendikar six thousand years ago, Nahiri shaped these stones to bend Innistrad's leylines to her will. To these horrors, she occupied a blank spot in reality. She didn't exist. Such was not the case for the vampires. The Eldrazi rushed toward them, and the red-haired vampire, along with her lackeys, wasted no time wading into the monstrosities with all the fury of their kind. #figure(image("005_Campaign of Vengeance/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Nahiri backed away from the chaos, and chunks of masonry slid into place with each backward step to create an impromptu stairway that spiraled into the heights of the manor. Her ascent carried her above the hacking of vampire blades and the lashing of latticed limbs. Sorin had hoped to beat her with allies, but Nahiri was ready. Sorin had tried to beat her with his death magic, but Nahiri was ready for that too. Was he ready for her, though? She felt his eyes on her, and when she found Sorin in the turmoil below her, he was staring up at her. Blood ran down his chin, and a cultist hung limply from the vampire's fists. It wasn't the first time she'd seen him feed, but he'd never looked quite so monstrous as he did at that moment. And that's what he was, a monster. Sorin's eyes never left her, even as he began his climb. He moved like lightning, the limp cultist in his hand lolling violently as he scrambled up the twisted walls, and over to the chunks of masonry held frozen in the air. He was a cat on the hunt, swift and sure-footed. By the time Nahiri was among the unmoored, broken remnants of the manor's vaulted ceiling, Sorin was on her heels. Nahiri was a kor from Zendikar, after all. Leaping from precarious place to precarious place was second nature to her. She was also the lithomancer, and here, in a field of scattered buttresses, spires, and entire wings of the manor that were strewn about in countless bits, she was in her element. She was perched on the sill of a tall, narrow window set into a bit of wall that hung in the air in defiance of gravity. Her swords orbited above her head, a crown of blades that marked this as her domain. It was time to see if Sorin could keep up. "Now we can finish what we started, uninterrupted," Nahiri called down to Sorin, who rose after landing gracefully on a landing that still towed part of a wide staircase with it. A long red runner still clung to the remaining steps before dropping out over empty space like the tongue of some dead animal. "Are you so eager to die?" Sorin said. "When last we met, my strength was greatly diminished. You're not so fortunate this time, I'm afraid." He tossed the corpse of the cultist at Nahiri like it was a damp cloth, and she heard something crunch inside the body as it slammed into the stone beside her. "And I have every intention of killing you." "You think you scare me?" "If not yet, I will." His eyes were all cruelty, pure and ancient. "I'm not leaving until this is done, Sorin." "On that we agree, young one." Young one. Without another word, Nahiri let her swords fly, all but the one she gripped. Sorin scrambled out of the way as each blade bit deep in the stone beneath his feet, and before he could secure his footing once again, Nahiri grabbed hold of the landing with her will and upended it. For a moment, Nahiri thought he would hang on, but his fingers failed to find purchase, and he fell. But the heavy red runner swung around with the motion, and Nahiri watched as Sorin's fingers closed around the fabric, and suddenly, he was swinging instead of falling. Nahiri yanked at the landing's component flagstones, unraveling the whole structure. As it tumbled away, Sorin let go, and his momentum carried him to a wayward beam. From there he pounced to a shattered wall, and then to another beam that leaned diagonally in the air. It seemed all in the span of a heartbeat, and Nahiri could scarcely keep track of him. Then she couldn't. He was so quick, and by the time she shifted her position in her window to follow his movements beneath her, she'd lost sight of him. For several moments her eyes darted around furiously, scanning for any hint of movement. Then, a flash of silver, and all Nahiri could do was slide into the wall itself so that Sorin's blade bounced away with a deafening knell that rang for several moments through the stone. Swaddled in masonry, Nahiri heard Sorin's words muffled, but venomous. "Nahiri, Nahiri, all this trouble over a turn in the Helvault. And yet you seem so at home in stone." Then there was a loud crack, and agony shot through her side like a hot poker. The stone had been breached. She felt it, and she felt the steel in her flesh. With a scrape, the blade receded, and before it could strike again, Nahiri let herself fall from the wall's grasp, and suddenly, she was tumbling through open air. Her hand went to the burning at her side, and it was wet. Some bit of balustrade came up to meet her. She tried to grab hold of it, but her hand, slick with blood, slipped, and she bounced past it. Her eyes fluttered, and the world spun around her until it stopped all at once when she slammed hard against the surface of a massive spire that lay horizontally across the length of the open ceiling. When she was able to find enough strength, Nahiri gathered her feet beneath her and rose slowly. She leaned hard against some stonework that protruded from the surface of the spire. She was out of breath, and her mouth felt dry despite the taste of blood in her mouth. At the sound of boots on the spire in front of her, she raised her eyes to find Sorin straightening himself from his landing. He stepped forward so that he stood over her, his sword raised and threatening, just as it was a thousand years ago when he condemned her to the Helvault. But there was no Helvault this time. "You had the chance to kill me, young one. You should have taken that chance while it was there." There was no gloating in Sorin's words. It was a mentor addressing a protégé, a final lesson to impart. "Maybe," Nahiri said, though more to herself. Her sword hung limply in her hand so that the point rested on the ground. Pain radiated from the gash in her side. Her free hand had been cradling the wound, and it trembled as she took a moment to glance at it. So much blood. So what was a little more. She took a deep breath, and spoke. "Regardless of what happens here, whether I make it out of here or not, I won, Sorin. Look around you." Nahiri swept her hand weakly out to indicate the manor. "Look carefully at what I've done to everything you claim as yours." She pointed to her left. Out in the distance, over the city of Thraben, Emrakul. "No pet angel of yours will come to the rescue this time." Sorin's sword flicked out, knocking Nahiri's out into nothing. "What you took from me in Avacyn, I will take from your blood." Before a muscle could even twitch, she felt Sorin's teeth tear into her neck. All the blood in her body shifted course. Sorin was calling it to him, and it burned in her veins. He drank deeply, and Nahiri found her moment. She leaned into the masonry at her back, and it responded to her coaxing by unfurling to either side of her. Each heart beat was torment, but she pushed through it to whisper, "I can bite back, Sorin, and I've got bigger teeth than you." The stone crashed in around them, and rows of jagged stone tusks tore into Sorin from his legs to his ribs. His sword flew from his hand, and a yelp of agony exploded from his lips. Nahiri shoved herself free of him, passing through the solid stone so that only Sorin remained. The stone tightened in on him until it had him in its grasp. By the time Nahiri was finished with her work, Sorin hung in air, gripped in Nahiri's magic. There was no planeswalking from this. The stone teeth that held him chewed at his insides, keeping him in a perpetual anguish that would sap the focus he would need to leave this place. Then Nahiri spun Sorin and his stone around so that they faced the rolling plains below Markov Manor. Sorin tried to speak, an unintelligible gurgle, as Nahiri climbed onto the cocoon she'd crafted. Whatever he had to say didn't matter. She wanted him to hear her words. With one hand clinging to the pinnacle of the stone, Nahiri lowered herself so that she could whisper those words into Sorin's ear. "I spared you," Nahiri said. "A courtesy returned." #figure(image("005_Campaign of Vengeance/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) In the distance beneath a ceiling of brooding clouds, Emrakul. And the next moment, Nahiri planeswalked away from Innistrad, leaving Sorin to the fate of his world. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The horizon was Emrakul. There was nothing Sorin could do but watch as the end of Innistrad drifted slowly across Gavony toward Thraben. The people down there were of little consequence now, but Innistrad was his, and Thraben was where he had created Avacyn to protect it. Seeing it now, on brink of its ruin, sent a pang through him that hurt worse than the lithomancer's stone teeth that ground their way through his insides. Sorin felt it a moment before he heard it—metal against stone, a long, slow scrape that moved across the back of his sarcophagus from bottom to top. "I think I like this one better," came a voice rich with mockery. And then Olivia descended into view to block out the chaos beyond. She was holding his sword. "Olivia," Sorin said through gritted teeth, "release me." "Even if I could, why? Avacyn is dead. Nahiri has been driven off. Our bargain is fulfilled." She chuckled cruelly. "I call this a victory. Do try to enjoy it. Markov Manor is yours, after all. As for me," she held up Sorin's sword to inspect its edge, "I rather like the sound of 'Olivia, Lord of Innistrad.'" Any shred of patience he possessed was suddenly cast aside by a surge of desperation. This world was done. Olivia was his only way out. "Look!" he said, straining against the unyielding stone. Olivia peered over her shoulder, but said nothing. "You see," he continued, "that's what's coming! You've seen what she does, what she's capable of." He was speaking faster now, and his voice cracked. "You're going to need my help to deal with it!" Sorin didn't like the way Olivia looked at him as he spoke. She was a spider, and he was a fly. "Listen to me!" he tried again. "What good is any of this if it will be gone tomorrow?" "Avacyn is dead. And you," she said, pressing the point of his own sword against his cheek, "you're where you are. I think it's quite good." And all Sorin could do was watch as Olivia floated from view, so that Emrakul and the end she promised filled his vision once again.
https://github.com/yasemitee/Teoria-Informazione-Trasmissione
https://raw.githubusercontent.com/yasemitee/Teoria-Informazione-Trasmissione/main/2023-11-24.typ
typst
#import "@preview/lemmify:0.1.4": * #let ( theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules ) = default-theorems("thm-group", lang: "it") #show: thm-rules #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true ) = Codici per il rilevamento degli errori Quando trasmettiamo dei dati su un canale reale è inevitabile riscontrare degli errori (dovuti soprattutto al rumore applicato sul canale). Nel messaggio l'errore può presentarsi in diversi punti e con omogeneità diverse, ad esempio #v(12pt) #figure( image("assets/2023-11-24 esempio-errore.svg", width: 75%) ) #v(12pt) Oppure può presentarsi il rumore bianco, ovvero un errore costante che ha la stessa influenza su tutti i bit della stringa (in altre parole ha la stessa probabilità $p$ di errore in ogni posizione). == Probabilità di errore - Probabilità di mandare $n$ simboli senza errore $ (1 - p)^n $ - Probabilità di avere esattamente 1 errore $ n dot p(1-p)^(n-1) $ - Probabilità di avere $l$ errori $ binom(n,l) dot p^l (1 - p)^(n-l) $ - Probabilità di avere fino a $max$ errori (dove $max$ indica un numero massimo prefissato di errori) $ sum_(l = 1)^max binom(n,l) dot p^l (1 - p)^(n-l) $ - Probabilità di avere un numero pari di errori $ sum_(l = 0)^(n/2) binom(n,2l) dot p^(2l) (1 - p)^(n-2l) $ == Single parity check code Il modo più semplice per codificare un messaggio binario al fine di renderlo rilevabile agli errori è contare il numero di 1 nel messaggio e quindi aggiungere un ultimo bit binario scelto in modo che l'intero messaggio abbia un numero pari di 1. L'intero messaggio è quindi di parità pari. Pertanto, alle $(n - 1)$ posizioni del messaggio, aggiungiamo una posizione di controllo di parità $n$. Alla fine del processo di ricezione, si conta il numero di 1 nel messaggio ricevuto, e un numero dispari di 1 in tutte le n posizioni indica che si è verificato almeno un errore. Formalmente: Rilevare il bit di parità: $ sum_(i = 1)^n x_i mod 2 "(se vogliamo è lo XOR)" $ Rilevare l'errore $ sum_(i=1)^n y_i = 0 $ === Esempio Supponiamo di avere una sequenza di bit, ad esempio 101101. Per aggiungere il bit di parità, calcoliamo la somma (modulo 2) di tutti i bit della sequenza. Se il risultato è pari, il bit di parità aggiunto sarà 0; se è dispari, il bit di parità sarà 1. Quindi, nel nostro esempio: 1 ⊕ 0 ⊕ 1 ⊕ 1 ⊕ 0 ⊕ 1 ≡ 0 Poiché il risultato è pari, il bit di parità sarà 0. La sequenza con il bit di parità aggiunto sarà quindi 1011010. Quando i dati vengono trasmessi o memorizzati, il ricevitore o il sistema di memorizzazione può calcolare nuovamente la somma (modulo 2) di tutti i bit, incluso il bit di parità. Se la somma è pari, il sistema assume che non ci siano errori. Se la somma è dispari, il sistema sa che si è verificato un errore durante la trasmissione. Evidentemente, in questo codice non è possibile rilevare un doppio errore. Inoltre, non è possibile rilevare alcun numero pari di errori. Tuttavia, è possibile rilevare qualsiasi numero dispari di errori. notiamo come abbiamo $n-1$ bit di informazione e 1 bit di parità, quindi sul canale vengono spediti $n$. == Ridondanza È pratica comune suddividere un lungo messaggio nell'alfabeto binario in sequenze (blocchi) di (n - 1) cifre ciascuna e aggiungere una cifra binaria a ciascuna sequenza, rendendo così il blocco trasmesso lungo n cifre. Il blocco finale potrebbe richiedere un padding con zeri. Ciò produce la ridondanza di $ n/(n-1) = 1 + underbrace(1/(n-1),"ridondanza \n aggiunta") $ Dove $n$ è il numero di bit spediti sul canale mentre $n-1$ è il numero di bit di informazione trasmessi. == Codice ASCII Inizialmente è stato pensato con 7 bit, quindi con $2^7$ caratteri, con il bit di parità diventano 8 $ [x_1, x_2, x_3, x_4, x_5, x_6, x_7 | "parity"] $ Supponiamo di trasmettere la parola "hello$b$nctun" dove $b$ è il carattere blank/spazio e l'n finale è il bit di parità $110_8 = $ h $=01001000$ $145_8 = $ e $=01100101$ $154_8 = $ l $=01101100$ $154_8 = $ l $=01101100$ $157_8 = $ o $=01101111$ $" "40_8 = $ $b$ $=00100000$ $116_8 = $ n $=01001110$ $103_8 = $ c $=01000011$ $124_8 = $ t $=01010100$ $125_8 = $ u $=underbracket(01010101,10010110)$ Quindi il messaggio spedito è 1001011|1 In questo codice è facile riconoscere gli errori burst, ma lo svantaggio è che non riconosce gli errori pari == Codici pesati I codici che di cui abbiamo discusso finora hanno generalmente assunto una forma di rumore bianco semplice. Questo è molto adatto per molti tipi di macchine, anche se nella trasmissione seriale la perdita di un simbolo (o l'inserimento di uno in più) è un errore comune in alcuni sistemi e non viene rilevato da tali codici, causando così una perdita di sincronizzazione. Quando si tratta di interagire con gli esseri umani, un altro tipo di rumore è più appropriato. Le persone hanno la tendenza a scambiare le cifre adiacenti dei numeri; ad esempio, 67 diventa 76. Un secondo errore comune è raddoppiare la cifra sbagliata di un triplo di cifre, due delle quali adiacenti sono uguali; ad esempio, 667 diventa 677, semplicemente cambiando una cifra. Questi sono i due errori umani più comuni nell'aritmetica. In un sistema combinato di alfabeto/numeri, la confusione tra "o" e "zero" è molto comune. Una situazione piuttosto frequente è avere un alfabeto, uno spazio e i 10 decimali come l'insieme completo di simboli da utilizzare. Ciò equivale a $26 + 1 + 10 = 37$ simboli nell'alfabeto di trasmissione. Fortunatamente, 37 è un numero primo e possiamo utilizzare il seguente metodo per il controllo degli errori. Assegniamo pesi ai simboli con valori $1, 2, 3, dots$ a partire dal simbolo di controllo del messaggio. Riduciamo la somma modulo 37 (dividiamo per 37 e prendiamo il resto) in modo che sia possibile selezionare un simbolo di controllo che renda la somma 0 modulo 37. Nota che uno "spazio vuoto" alla fine, come simbolo di controllo, non è la stessa cosa di nulla. === Esempio Vogliamo codificare il messaggio 3B 82, dove 2 è il bit di controllo e lo spazio va codificato #table( columns: (1fr, 2fr, 2fr), inset: 10pt, align: horizon, [msg], [$sum$], [$sum sum$], [ $w$\ $x$\ $y$\ $z$ ], [ $w$\ $w + x$\ $w + x + y$\ $w+ x+ y+ z$ ], [ $w$\ $2w + x$\ $3w + 2x + y$\ $4w+ 3x+ 2y+ z$ ] ) Procediamo a codificare il messaggio #table( columns: (1fr, 1fr, 1fr, 1fr), inset: 10pt, align: horizon, [da codificare],[msg], [$sum$], [$sum sum$], [ $3$\ B\ blank\ $8$ ], [ $3$\ $11$\ $36$\ $8$ ], [ $3$\ $14$\ $50$\ $58$ ], [ $3$\ $17$\ $67$\ $125$ ] ) Adesso mi controllo se ho degli errori 3 x 5 = 15, 11 x 4 = 44, 36 x 3 = 108, 8 x 2 = 16, 2 x 1 = 2 15 + 44 + 108 + 16 + 2 = 185 *185 mod 37 = 0, quindi non ho errori* = Secondo Teorema di shannon == Estensione _n-esima_ Come nel caso della codifica sorgente, anche nel caso della codifica canale utilizziamo più simboli di ingresso per codificare un messaggio da trasmettere. Per far ciò, estendiamo il modello di canale in modo da considerare la trasmissione di sequenze di simboli. Dato il canale $angle.l Chi, Y, p(y|x) angle.r$ definiamo l'estensione _n-esima_ $angle.l Chi^n, Y^n, p(y^n|x^n) angle.r$ dove la quantità $ p(y^n|x^n)$ indica la probabilità di ottenere in uscita la sequenza $y^n in Y^n$ quando è stata trasmessa la sequenza $x^n in X^n$. Ricordiamo che essendo il canale senza memoria vale $product_(t=1)^n (y_t | x_t)$. Ora dobbiamo costruire un codice per il nostra canale, che sarà di tipo $(M,n)$, dove: - M = è il numero di messaggi che voglio trasmettere (ovvero il numero di simboli che voglio codificare), quindi ${1, dots, M}$ è l'insieme dei messaggi - n = numumero di volte che utilizzo il canale Definiamo anche due funzioni: - Funzione di codifica $x^n: {1, dots, M} -> Chi^n$ che prende un messaggio e lo codifica in una stringa da immmettere nel canale. - Funzione di decodifica $g: Y^n -> {1, dots, M}$ che prende una stringa ricevuta dal canale e la decodifica in un messaggio. == Probabilità di errore di decodifica Dato un codice canale, la probabilità di errore di decodifica del messaggio $i$ è definita come $ lambda_i = P(g(YY^n) != i | XX^n = x^n (i)) $ In sostanza ci chiediamo qual'è la probabilità che la stringa ricevuta sia diversa da $i$ sapendo che la codifica della stringa $i$ dove $XX^n$ e $YY^n$ sono variabili casuali che indicano i simboli trasmessi e quelli ricevuti. Possiamo aggregare le probabilità di errore di singoli messaggi in due modi: $ lambda^((n)) = max_(i = 1, dots, M) lambda_i -> "probabilità massima di errore" $ $ P_e^((n)) = 1/M sum_(i=1)^M lambda_i -> "probabilità media di errore" $ Dove ovviamente $P_e^((n)) <= lambda^((n))$ == Tasso di trasmissione (di un cod. (M,n)) Il tasso di trasmissione $R$ di un codice (M,n) è dato dal rapporto $ R = (log_2 M)/n $ Su un canale senza errore ho un tasso di trasmissione massimo, quindi $ M= 2^n \ R=(log_2 2^n)/n = 1 $ #pagebreak() == Teorema #theorem(numbering: none, name: "Secondo teorema di shannon")[ Sia $angle.l Chi, Y, p(y|x) angle.r$ un canale di capacità $C$. $forall R < C, "esiste una sequenza" k_1, dots k_2 $ di codici dove $k_n$ è di tipo $(2^(n R n),n)$ tale che: $ lim_(n -> infinity) R_n = R \ e \ lim_(n-> infinity) lambda^((n)) (k_n) = 0 $ ] Possiamo interpretare il teorema nel modo seguente. Per codificare $M$ messaggi (senza assumere nulla circa la loro distribuzione) ci servono $n = ceil(log_2 M)$ bit. Quindi, se il canale non avesse rumore, trasmetteremmo al tasso massimo di $R = 1/n log_2 M = 1$ bit per uso di canale. In altritermini, senza rumore riusciamo a trasmettere senza errori fino a $2n$ messaggi diversi usando $n$ volte il canale per ogni messaggio. Se c'è rumore, il teorema ci dice che, per ogni $δ > 0$ e per ogni n abbastanza grande, usando n volte il canale riusciamo a trasmettere uno qualunque fra $2^(n(C−δ))$ messaggi con probabilità di errore che tende a zero al crescere di $n$. In sostanza, anche se hai rumore nel canale, puoi ancora trasmettere un gran numero di messaggi con una bassa probabilità di errore, purché la velocità di trasmissione sia inferiore alla capacità del canale. La quantità δ rappresenta una piccola deviazione dalla capacità massima del canale.
https://github.com/kiwiyou/algorithm-lecture
https://raw.githubusercontent.com/kiwiyou/algorithm-lecture/main/advanced/04-advanced-dp.typ
typst
#import "@preview/cetz:0.1.2" #import "@preview/algorithmic:0.1.0" #import "../slide.typ" #show: slide.style #show link: slide.link #show footnote.entry: slide.footnote #let algorithm(..args) = text( font: ("linux libertine", "Pretendard"), size: 17pt, )[#algorithmic.algorithm(..args)] #let func(body) = text(font: ("linux libertine", "Pretendard"))[#smallcaps[#body]] #align(horizon + center)[ = 알고리즘 중급 세미나 04: 고급 다이나믹 프로그래밍 #text(size: 0.8em)[ 연세대학교 전우제#super[kiwiyou] \ 2023.01.04.r1 ] ] #slide.slide[배낭 문제][ - $N$개의 물건에 무게 $w_i$와 가치 $v_i$가 있을 때, 무게 합이 $W$를 넘지 않도록 물건을 몇 개 골라 가치 합을 최대화 - 여기서는 $w_i$가 모두 정수인 경우만 고려 - *입력 크기*\에 대한 다항 시간에 푸는 알고리즘은 발견되지 않음 - 탐욕적인 접근이 통하기 어려워 보이므로 DP로 접근 #pagebreak() - $f(i, w) =$ $i$번째 물건까지 고려했을 때, 정확히 무게 $w$를 사용하여 얻을 수 있는 최대 가치 - $f(i + 1, w) = max(f(i, w), f(i, w - w_(i + 1)) + v_i)$ - 시간 $cal(O)(N W)$, 공간 $cal(O)(N W)$ - 배열을 왼쪽부터 덮어씌우면서 공간 $cal(O)(W)$에 가능 #pagebreak() - $N$가지의 물건에 무게 $w_i$, 가치 $v_i$, 개수 $c_i$가 있을 때, 무게 합이 $W$를 넘지 않도록 물건을 몇 개 골라 가치 합을 최대화 - $C = sum_(i=1)^N c_i$개의 물건이 하나씩 있다고 생각하고 풀기 - $O(C W)$ #pagebreak() - $N$가지 물건에 무게 $w_i$와 가치 $v_i$가 있을 때, 무게 합이 $W$를 넘지 않도록 물건을 몇 가지 골라 원하는 개수만큼 선택해 가치 합을 최대화 - $f(i + 1, w) = max( & \ & f(i, w), \ & f(i, w - w_(i + 1)) + v_i, \ & f(i + 1, w + w_(i + 1)) + v_i \ )&$ - $cal(O)(N W)$ #pagebreak() - 그 외 최적화 기법은 https://infossm.github.io/blog/2023/03/18/Knapsack/ 참고 ] #slide.slide[과제][ - #slide.problem("17845", "수강 과목") - #slide.problem("23257", "비트코인은 신이고 나는 무적이다") - #slide.problem("27163", "벚꽃 내리는 시대에 결투를") ] #slide.slide[LIS][ - 부분 수열#super([Subsequence]): 수열 $A$에서 몇 개의 원소를 지워 만든 수열 - 가장 긴 증가하는 부분 수열#super([Longest Increasing Subsequence]) - 마찬가지로 탐욕법 적용이 어려움 #pagebreak() - $f(i)$: $i$번째 원소를 끝으로 하는 가장 긴 증가하는 부분 수열의 길이 - $ f(i) = max_(j<i \ A_j < A_i) f(j) + 1 $ - 시간 $cal(O)(N^2)$ 공간 $cal(O)(N)$ #pagebreak() - $g(i, L)$: $i$번째 원소까지 봤을 때, 길이가 $L$인 LIS의 끝 값 중 가장 작은 값 - $f(i) = max_(g(i - 1, L) < A_i) L + 1$ - $g(i, L)$은 $L$이 길어질수록 증가하므로, 이분 탐색을 이용 - $g(i, L)$을 담을 리스트 $M$을 만들고, $f(i)$가 $M$의 길이보다 커질 때마다 $M$의 뒤쪽에 $i$를 추가 - 그렇지 않으면 $M[f(i)]$를 $i$로 업데이트 ($A_j$가 더 작은 쪽을 남김) ] #slide.slide[과제][ - #slide.problem("12015", "가장 긴 증가하는 부분 수열 2") - #slide.problem("12014", "주식") ] #slide.slide[해답의 역추적][ - DP 문제에서 최적해 혹은 경우의 수를 찾고, *그 예를 하나 찾아야 할 때* - 이전 상태를 저장 - DP 테이블의 값을 업데이트할 때마다, 그 값의 이전 상태도 업데이트 - 전이 과정을 거꾸로 따라가기 - 모든 가능한 상태를 훑으며 전이 후 값이 나오도록 하는 상태를 선택 ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/suiji/0.1.0/lib.typ
typst
Apache License 2.0
//============================================================================== // Random number generator //============================================================================== //---------------------------------------------------------- // Internal parameters and functions //---------------------------------------------------------- // Maximally equidistributed combined Tausworthe generator // The period of this generator is about 2^88. // Part of algorithm implementations reference to GSL (https://www.gnu.org/software/gsl) #let _rand-max = 0xFFFFFFFF #let _rand-min = 0 #let _mask = 0xFFFFFFFF #let _tausworthe(s, a, b, c, d) = { let s1 = s.bit-and(c).bit-lshift(d).bit-and(_mask) let s2 = s.bit-lshift(a).bit-and(_mask).bit-xor(s).bit-rshift(b) return s1.bit-xor(s2) } #let _lcg(n) = { return (69069 * n).bit-and(_mask) } #let _get(state) = { let s1 = _tausworthe(state.at(0), 13, 19, 4294967294, 12) let s2 = _tausworthe(state.at(1), 2, 25, 4294967288, 4) let s3 = _tausworthe(state.at(2), 3, 11, 4294967280, 17) let val = s1.bit-xor(s2).bit-xor(s3) return ((s1, s2, s3), val) } #let _uniform(state) = { let (state-new, val) = _get(state) return (state-new, val / 4294967296.0) } #let _uniform-int(state, n) = { let gap = _rand-max - _rand-min let scale = calc.quo(gap, n) while true { let (state-new, val) = _get(state) let k = calc.quo(val, scale) if k < n {return (state-new, k)} } } //---------------------------------------------------------- // Public functions //---------------------------------------------------------- // Initialized the random number generator (Tausworthe) // Arguments: // seed: value of seed (integer) // Returns: // rng: generated object of random number generator #let gen-rng(seed) = { let s = int(seed).bit-and(_mask) if s == 0 {s = 1} let s1 = _lcg(s) if (s1 < 2) {s1 = s1 + 2} let s2 = _lcg(s1) if (s2 < 8) {s2 = s2 + 8} let s3 = _lcg(s2) if (s3 < 16) {s3 = s3 + 16} let state = (s1, s2, s3) // Warm it up (state, _) = _get(state) (state, _) = _get(state) (state, _) = _get(state) (state, _) = _get(state) (state, _) = _get(state) (state, _) = _get(state) return state } // Return random integers from low (inclusive) to high (exclusive). // Arguments: // rng: object of random number generator // low: lowest (signed) integers to be drawn from the distribution, optional // high: one above the largest (signed) integer to be drawn from the distribution, optional // size: returned array size, optional // Returns: // array of (rng, arr) // rng: updated object of random number generator // arr: returned array of random number(s) #let integers(rng, low: 0, high: 100, size: 1) = { assert(type(size) == int and size >= 1, message: "`size` should be positive") assert(high - low >= 1 and high - low <= 0xFFFFFFFF, message: "invalid range between `low` and `high`") let gap = high - low let state = rng let val = 0 let a = () for i in range(size) { (state, val) = _uniform-int(state, gap) a.push(val + low) } if size == 1 { return (state, a.at(0)) } else { return (state, a) } } // Return random floats in the half-open interval [0.0, 1.0). // Arguments: // rng: object of random number generator // size: returned array size, optional // Returns: // array of (rng, arr) // rng: updated object of random number generator // arr: array of random number(s) #let random(rng, size: 1) = { assert(type(size) == int and size >= 1, message: "`size` should be positive") let state = rng let val = 0 let a = () for i in range(size) { (state, val) = _uniform(state) a.push(val) } if size == 1 { return (state, a.at(0)) } else { return (state, a) } } // Draw samples from a uniform distribution. // Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). // Arguments: // rng: object of random number generator // low: lower boundary of the output interval, optional // high: upper boundary of the output interval, optional // size: returned array size, optional // Returns: // array of (rng, arr) // rng: updated object of random number generator // arr: array of random number(s) #let uniform(rng, low: 0.0, high: 1.0, size: 1) = { assert(type(size) == int and size >= 1, message: "`size` should be positive") let state = rng let val = 0 let a = () for i in range(size) { (state, val) = _uniform(state) a.push(low * (1 - val) + high * val) } if size == 1 { return (state, a.at(0)) } else { return (state, a) } } // Draw random samples from a normal (Gaussian) distribution. // Arguments: // rng: object of random number generator // loc: float, mean (centre) of the distribution, optional // scale: float, standard deviation (spread or width) of the distribution, must be non-negative, optional // size: returned array size, optional // Returns: // array of (rng, arr) // rng: updated object of random number generator // arr: array of random number(s) #let normal(rng, loc: 0.0, scale: 1.0, size: 1) = { assert(type(size) == int and size >= 1, message: "`size` should be positive") assert(scale >= 0, message: "`scale` must be non-negative") let x = 0 let y = 0 let r2 = 0 let state = rng let val = 0 let a = () for i in range(size) { while true { // Choose x and y in uniform square (-1,-1) to (+1,+1) (state, val) = _uniform(state) x = -1 + 2 * val (state, val) = _uniform(state) y = -1 + 2 * val // See if it is in the unit circle r2 = x * x + y * y if r2 <= 1.0 and r2 != 0 {break} } // Box-Muller transform a.push(loc + scale * y * calc.sqrt(-2.0 * calc.ln(r2) / r2)); } if size == 1 { return (state, a.at(0)) } else { return (state, a) } } // Return a new sequence by shuffling its contents. // Arguments: // rng: object of random number generator // arr: the array to be shuffled // Returns: // array of (rng, arr) // rng: updated object of random number generator // arr: shuffled array #let shuffle(rng, arr) = { assert(type(arr) == array, message: "`arr` should be arrry type") let size = arr.len() if size <= 1 {return (rng, arr)} let state = rng let j = 0 for i in range(size - 1, 0, step: -1) { (state, j) = _uniform-int(state, i + 1) (arr.at(i), arr.at(j)) = (arr.at(j), arr.at(i)) } return (state, arr) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/chuli-cv/0.1.0/lib.typ
typst
Apache License 2.0
#import "@preview/fontawesome:0.1.0": * #import "modules/styles.typ": * #import "modules/header.typ": * #import "modules/section.typ": * #import "modules/skills.typ": * #import "modules/languages.typ": * #import "modules/piechart.typ": * #import "modules/education.typ": * #import "modules/entry.typ": * // Cover letter Components //-------------------------------------------- #let letter-header( name: "<NAME>", address: "Your Address Here", recipientName: "<NAME>", recipientAddress: "Company Address Here", date: "Today's Date", subject: "Subject: Hey!" ) = { accent-subtopic-style(name) v(1pt) inactive-ligth-style(address) v(1pt) align(right, accent-subtopic-style(recipientName)) v(1pt) align(right, inactive-ligth-style(recipientAddress)) v(1pt) italic-text-style(date) v(1pt) underline-accent-style(subject) linebreak(); linebreak() } #let letter-signature(path) = { linebreak() place( letter-signature-style.position, dx:letter-signature-style.dx, dy:letter-signature-style.dy, path, ) } #let letter-footer(name: "<NAME>") = { place( letter-footer-style.position, table( columns: letter-footer-style.table.columns, inset: letter-footer-style.table.inset, stroke: none, footer-style(name), ) ) } // Cover letter layout //-------------------------------------------- #let cover-letter(content) = { set text( font: body-style.fonts, weight: body-style.weight, size: body-style.size, ) set align(page-style.text.align) set page( paper: page-style.paper, margin: ( left: page-style.margin.left, right: page-style.margin.right, top: page-style.margin.top, bottom: page-style.margin.bottom, ), ) content } // CV Components //-------------------------------------------- #let cv( content ) = { set text( font: body-style.fonts, weight: body-style.weight, size: body-style.size, ) set list( indent: list-style.indent ) set align(left) set page( paper: page-style.paper, margin: page-style.margin, ) content } #let header( full-name: [], job-title: [], // Each array item must have a property link, text and icon to be displayed. socials: (), profile-picture: "" ) = { table( columns: header-style.table.columns, inset: header-style.table.inset, stroke: none, column-gutter: header-style.table.column-gutter, align: left + horizon, { create-header-info( full-name: full-name, job-title: job-title, socials: socials ) }, { create-header-avatar( profile-photo: profile-picture ) } ) v(header-style.margins.bottom) } #let body(content) = { set text( font: body-style.fonts, weight: body-style.weight, size: body-style.size, ) set list( indent: list-style.indent ) set align(left) content } #let section(title) = { v(section-style.margins.top) create-section-title(title) } #let entry( title: "", company-or-university: "", date: "", location: "", logo: "", description: () ) = { v(entry-style.margins.top) table( columns: entry-style.table.columns, inset: entry-style.table.inset, stroke: none, align: entry-style.table.align, column-gutter: entry-style.margins.between-logo-and-title, {logo}, render-entry-header(title, company-or-university, date, location) ) text()[ #v(3pt) #description ] } #let skill( skills: () ) = { v(skills-style.margins.between-categories) render-skills(skills: skills) } #let language( name: "", label: "", nivel: 2 ) = { table( columns: language-style.columns, inset: 0pt, row-gutter: language-style.row-gutter, stroke: none, align: language-style.align, accent-subtopic-style(name), render-language(nivel: nivel), table.hline( stroke: ( paint: colors.inactive, thickness: 1pt, dash: "dashed" ), ), { v(4pt) inactive-ligth-style(label) } ) } #let freetime(name: "",icon:"") = { table( columns: freetime-style.columns, inset: 0pt, column-gutter: freetime-style.column-gutter, stroke: none, align: freetime-style.align, {icon}, regular-text-style(name), ) dashed-line() } #let education-entry( title: "", company-or-university: "", date: "", location: "", logo: "", gpa: "", gpa-total: "" ) = { table( columns: 2, stroke: none, inset: 0pt, row-gutter: education-entry-style.row-gutter, column-gutter: education-entry-style.column-gutter, render-education-header(title, logo, company-or-university), table.vline(), table.cell( accent-subtopic-style("GPA"), align: center, ), table.cell( render-education-icon-info(date: date, location: location), align: center, ), table.cell( { accent-subtopic-style(gpa) regular-text-style("/ " + gpa-total) }, inset: 4pt, ) ) } #let piechart(activities: ()) = { figure(render-activities(slices: activities)) }
https://github.com/NaviHX/bupt-master-dissertation.typ
https://raw.githubusercontent.com/NaviHX/bupt-master-dissertation.typ/main/sample.typ
typst
#import "bupt-master-dissertation.typ": bupt-template, bupt-table-figure, bupt-image-figure, defense-committee, declaration, chinese-cover, english-cover #chinese-cover( [基于 Typst 的论文排版研究], [20xxxxxxxx], [张三], [网络安全], [方xx], [网络安全学院], datetime.today(), ) #english-cover( [Research on paper formatting based on Typst], [20xxxxxxxx], [张三], [网络安全], [方xx], [网络安全学院], datetime.today(), ) #defense-committee( ( ([主席], lorem(1), lorem(1), lorem(3)), ([委员], lorem(1), lorem(1), lorem(3)), ([委员], lorem(1), lorem(1), lorem(3)), ([委员], lorem(1), lorem(1), lorem(3)), ([秘书], lorem(1), lorem(1), lorem(3)), ), [1989.06.04], ) #pagebreak() #declaration() #show: rest => bupt-template( // 中文摘要 ([ 本文旨在探讨[章节名称]的相关问题,并通过深入研究和分析,提出了一系列有针对性的解决方案。在这一研究中,我们首先回顾了相关领域的文献,深入了解了当前问题的研究现状和存在的挑战。随后,我们通过实证研究和数据分析,对[章节名称]的影响因素进行了详尽的探讨。 通过对实验结果的分析,我们发现[章节名称]在特定条件下呈现出明显的趋势和规律。基于这些发现,本文提出了一系列可行的解决方案,旨在优化[章节名称]的相关问题,提高其效率和性能。同时,我们也探讨了这些解决方案可能面临的挑战和局限性,为未来的研究方向提供了一些建议。 综上所述,本文通过对[章节名称]的全面研究,为相关领域的研究提供了有价值的参考和启示。希望本研究能够为解决[章节名称]相关问题提供新的思路,并为未来相关研究提供有益的参考。 ], [关键词1], [关键词2], [关键词3], [关键词4], [关键词5]), // 英文摘要 ([ In this paper, we aim to explore the issues related to [Chapter Title] and propose a series of targeted solutions through in-depth research and analysis. In this study, we first review the literature in the relevant field to understand the current research status and challenges of the existing problems. Subsequently, through empirical research and data analysis, we discuss the influencing factors of [Chapter Title] in detail. Through the analysis of experimental results, we find that [Chapter Title] exhibits clear trends and patterns under specific conditions. Based on these findings, this paper proposes a series of feasible solutions to optimize the relevant issues of [Chapter Title] and improve its efficiency and performance. At the same time, we also explore the challenges and limitations that these solutions may face, providing suggestions for future research directions. In conclusion, this paper provides valuable reference and inspiration for research in related fields through a comprehensive study of [Chapter Title]. It is hoped that this research will offer new insights for solving the issues related to [Chapter Title] and provide useful references for future related studies. ], [Keyword1], [Keyword2], [Keyword3], [Keyword4], [Keyword5]), // 符号说明 (([$A$], [截面积], [$m^2$]), ([$F$], [力], [$N$]), ([$e$], [电子电荷], [$V$]),), // 参考文献 "ref.bib", // 附录 none, // 致谢 [ 在完成本篇论文的过程中,我要衷心感谢所有支持和帮助过我的人们。首先,我要感谢我的导师[导师姓名]教授,感谢他/她在整个研究过程中的悉心指导和专业建议。他/她的深厚学识和耐心指导为我提供了巨大的帮助,使我能够克服研究中的困难,不断进步。 此外,我要感谢实验室的同仁们,感谢他们在实验设计、数据收集和分析方面的合作。他们的支持使得我的研究更加全面和可靠。 在此,我还要感谢我的家人和朋友们,感谢他们在我学业和研究中一直以来的理解、支持和鼓励。他们是我前行路上的坚强后盾。 最后,感谢所有在学术和生活中给予过我帮助的人们,你们的支持是我前进的动力。 衷心感谢你们所有! ], // 创新成果 none, // 正文 rest, ) = 绪论 本文的引言部分将介绍研究的背景、目的以及相关领域的研究现状。首先,我们将对[章节名称]的重要性和研究意义进行概述,为读者提供对本研究主题的整体认识。随后,我们将详细阐述本研究的目标和研究问题,明确研究的范围和方向。 在介绍研究现状时,我们将回顾相关领域的先前研究,分析已有文献中的主要观点和研究成果。通过对前人工作的综合总结,我们将揭示当前研究领域存在的挑战和未解之谜,为本文后续的研究工作奠定基础。 最后,我们将概述本文的结构和组织安排,为读者提供一个清晰的框架,使其能够更好地理解和把握本研究的内容。通过引言,我们旨在引发读者的兴趣,明确研究的价值,并为后续章节的详细讨论打下基础。 = 文献综述 第二章将对与[章节名称]相关的文献进行综合分析和总结。首先,我们将系统回顾先前的研究,探讨在[章节名称]领域内的关键概念、理论和方法。通过对现有文献的深入剖析,我们将识别已有研究的主要发现、趋势和不足之处。 #bupt-image-figure([校徽], lorem(3), image("./image/logo.png", width: 30%)) 此外,本章将突出先前研究中的争论点和未解决问题,为本文后续的研究提供理论基础。我们还将比较不同研究方法的优缺点,并明确本研究的创新点和独特之处。 @Kimmel2004Rumors 通过对文献的全面综述,第二章旨在为读者提供一个对[章节名称]领域的全面理解,并为本研究的深入探讨奠定基础。 #bupt-table-figure([一张表], lorem(3), table(columns: 2, [1], [2], [3], [4])) == 二级标题 随便写点。 $ a ^ 2 + b ^ 2 = c ^ 2 $ == 二级标题 编不出来了。 === 三级标题 真的一个字也编不出来了。 $ sum_(k=1)^n k = (n(n+1)) / 2 $ = 研究方法 第三章将详细描述本研究所采用的研究方法和设计。首先,我们将明确研究的整体目标,并解释为什么选择特定的研究方法来回答研究问题。在方法论的选择上,我们会考虑到其适应性、可行性和有效性。 $ F_n = floor(1 / sqrt(5) phi.alt^n) $ 接着,本章将详细介绍数据收集的过程,包括样本的选择、实验设计和数据获取方法。我们还将讨论数据分析的具体步骤和使用的工具,以确保研究的科学性和可靠性。 此外,本章还将探讨可能的局限性和方法选择的合理性,以及如何在研究设计中处理潜在的偏见或误差。通过透彻的研究方法描述,第三章旨在为读者提供对本研究设计的清晰理解,为后续章节的研究结果分析打下基础。 #lorem(5000) = 结论 第四章将总结本研究的主要发现,对研究问题进行回顾,并提出对这些发现的深层次解释。本章旨在回应研究目标,验证或修正研究假设,并将研究结果与先前的文献进行对比和讨论。 首先,我们将概述研究的主要发现和结果,强调它们对[章节名称]领域的理论贡献和实际应用的意义。然后,我们会探讨研究中的局限性和不足之处,并提出未来研究的建议和方向。 在结论部分,我们将回顾研究的整个过程,强调研究的创新之处,并总结对解决研究问题的贡献。最后,我们将就本研究的意义和影响进行讨论,展望未来相关领域的发展方向。 通过第四章的结论与讨论,读者将对本研究的重要性和贡献有一个清晰的认识,并能够更好地理解研究结果的意义。
https://github.com/JWangL5/CAU-ThesisTemplate-Typst
https://raw.githubusercontent.com/JWangL5/CAU-ThesisTemplate-Typst/master/ref/helpers.typ
typst
MIT License
#let zip(..lists) = { let lists = lists.pos() if lists == () { () } else { let ret = () let len = lists.fold( lists.first().len(), (a, b) => if a > b.len() { b.len() } else { a } ) for i in range(0, len) { let curr = () for list in lists { curr.push(list.at(i)) } ret.push(curr) } ret } } #let strspacing(s,sz,fontsz) = { let chars = s.split("") chars = chars.slice(1,chars.len()-1) chars.join(h(fontsz)) } #let strjustify(s,len,fontsz) = { let chars = s.split("") chars = chars.slice(1,chars.len()-1) let n = len - chars.len() let sz = n /(chars.len()-1) chars.join(h(sz*fontsz)) }
https://github.com/Enter-tainer/natrix
https://raw.githubusercontent.com/Enter-tainer/natrix/main/README.md
markdown
Apache License 2.0
# [Natrix](https://github.com/Enter-tainer/Natrix) ![](natrix.svg) `natrix.nat` is a drop-in replacement for `mat` with some additional features. `nat` ensures that each row in your matrix should have the similar height, unless one of them becomes too tall. At this moment, it is recommended to use `nat` only in display equations, but not in inline equations. This is because `nat` looks a little bit off when used in inline equations. ## Documentation ### `nat` Every thing is the same as `mat` in typst. This package also provides `bnat`, `Bnat`, `vnat`, `Vnat`,
https://github.com/exdevutem/taller-git
https://raw.githubusercontent.com/exdevutem/taller-git/main/README.md
markdown
# Documento de referencia - Taller de Git y Github Este documento fue creado como referencia para el taller de Git y Github del ExDev. Fue creado con el fin de ser un "torpedo" para los compañeros, que puedan referenciarlo rápidamente al momento de necesitarlo en sus proyectos, y con el fin de explicar el proceso y lógica de todos los comandos que se ejecutan al momento de modificar un proyecto y versionarlo con estas herramientas. ## Obtener Una versión ya compilada puede ser encontrada en la sección de "releases" de este repositorio. ## Cómo compilar Este proyecto fue creado en Typst, una herramienta similar a Latex, pero muchísimo más moderna. Para compilarlo, requieres el binario instalado en tu sistema, y ejecutar el comando ```bash $ typst compile main.typ ``` Esto te generará un archivo main.pdf como resultado de la compilación. ## Créditos - <NAME>, 2023.
https://github.com/liuxu89/liuxu89.github.io
https://raw.githubusercontent.com/liuxu89/liuxu89.github.io/main/src/daijinhua1.typ
typst
#import "/book.typ": book-page #show: book-page.with(title: "大众文化的隐形政治学") = 广场-市场 在九十年代中国的文化风景线上,一个有趣的译名,或许可以成为解读这一时代的索引之一。随着诸多现代、后现代风格的摩天大楼于中国都市拔地而起,不断突破和改写着城市的天际线;诸多的大型商城、购物中心、专卖店、连锁店、仓储式商场,以及这些新的建筑群所终日吞吐的人流,无疑成了这一风景线上最引人注目的段落。此间,Plaza--这类集商城、超级市场、餐厅、连锁快餐店、健身馆、办公楼(今日之所谓“写字楼”)、宾馆、商务中心于一体的巨型建筑,或许提供了中国大都市国际化、或曰全球化的最佳例证。如何以自己民族的语言命名这类新的空间,或许是每一个后发现代化国家诸多问题背后的细枝末节之一。于是,在1995-1996年前后,这类空间在借用人们熟悉的称谓“大厦”、“中心”之后,获得了一个“新”的译名:Plaza(广场)。一时间,烟尘四起的建筑工地围墙上,“广场”的字样随处可见。作为一种中国特色,一如你会在一个偏远的县城中遇到一个被称为“中国大饭店”的小餐馆;继Plaza之为“广场”之后,形形色色的大型或中型专卖店,亦开始称“广场”:诸如“电器广场”或“时装广场”。而在1993年前后,爆炸式地出现的数量浩繁的报纸周末版和消闲、娱乐型报刊,则同样以“广场”来命名种种时尚栏目。 来自西班牙语的Plaza,意为被重要建筑所环绕的圆形广场。在资本主义文明兴起的欧洲现代都市中,Plaza从一开始,便不仅有着政治、文化中心的功能,而且充当着城市的商业中心。而将巨型商城称为Plaza(广场),却有着欧洲-美国-亚洲发达国家、地区(对我们说来,最重要的是香港)的语词旅行脉络。将类似建筑直译为广场,就所谓规范汉语而言,并非一个恰当的意译。但一如当代中国、乃至整个现代中国的文化史上的诸多例证,一个新的名称总是携带着新的希望,新的兴奋甚或狂喜。于是“丰联广场”便成了一个远比“燕莎购物中心”更诱人的称谓。 “广场”在现代中国史上,始终不是一个普通的名词。我们或许可以说,作为中国知识分子记忆清单的必然组成部分,“广场”不仅指涉着一个现代空间。爆发于天安门广场的五四运动成了中国现代史(当然更是中国现代文化史)的开端。伴随着社会主义中国的建立,天安门广场成了开国大典、阅兵式之所在,因而成了新中国及社会主义政权的象征,亦指称着人民:消融了阶级和个体差异的巨大的群体。而1966-1967年间,毛泽东八次接见红卫兵,则在广场--天安门广场这一特定的空间上,添加了集权与革命、膜拜与狂欢、极端权力与秩序的坍塌、青年学生的激情与对过剩权力的分享的冲突意义。爆发于1976年的天安门广场上的“四•五运动”--事实上成了结束“文革”及“四人帮”政权的先导,但仍在搬演社会主义的经典样式:群众运动(以及不无荒诞的“诗歌运动”)恢复了现代社会的广场和平示威的形式。 如果说,法国大革命为现代法国提供了自己的革命模式:城市起义、街垒战、人民临时政权;那么,五四运动则提供了现代中国的革命方式:以青年学生为先导,以广场运动为高潮,并以最终引发全社会、尤其是上海工人的参与而改写并载入历史。因此,广场,作为中国文化语境中特定的能指,联系着不同历史阶段中的“革命”与政治的记忆;其自身便是“中国版”的现代性话语的重要组成部分,并且记录着中国现代化进程的特殊实践。广场,在中国几乎是一个专有名词,特指着具有神圣感的天安门广场,当代中国的政治中心;于是,当Plaza被称之为“广场”的时候,便不仅是某种时髦的称谓,而且在有意无意间显现了九十年代中国一种特定的意识形态症候与其实践内容。 = 挪用与遮蔽 或许可以说,在当代中国文化,尤其是新时期文化中,存在着某种“广场情结”。因此针对着这一多重编码的形象,类似的僭越与亵渎在八十年代后期已悄然开始。在1987-1988年间,广场与社会主义革命时代神圣的禁忌便开始成为游戏和调侃的对象。1987年著名的第五代导演田壮壮成功的商业电影《摇滚青年》中,出现了天安门红墙下的摇滚场景。在1988年(所谓“电影王朔年”)四部改编自王朔小说的影片便有两部出现了主人公在天安门广场上恶作剧的插曲。1989年中央电视台的元旦联欢晚会上,相声演员姜昆用一个关于“天安门广场改成农贸市场”的“谣言”,令观众大为开心;在一段时间之内这一说法几乎被视为有趣的社会和政治预言。 如果说,八、九十年代之交的毛泽东热、“文革”热、政治怀旧潮,在对昔日禁忌、神圣、意识形态的消费中,构成了复杂的政治情绪的发露(1);那么,在九十年代前半期,它在消费和消解昔日意识形态的同时,成功地充当着一架特殊的文化浮桥,将政治禁忌与创伤记忆转换为一种新的文化时尚。因此,Plaza--商城被名之为“广场”,便不仅是一种政治性的僭越,而且更接近于一次置换与挪用。我们知道,一次不“恰当”的挪用,固然包含着对被挪用者的冒犯与僭越;但它同时可能成为对挪用对象的借重与仿同。如果说,在社会主义中国的历史上,天安门广场曾在新的“中国中心”想象里,被指认为“世界革命的中心”,“红色的心脏”;那么,高速公路、连锁店、摩天大楼、大型商城、奢华消费的人流则以一幅典型的世界无名大都市的图画,成就着全球一体化的景观,成就着所谓“后工业社会”特有的“高速公路两侧的快餐店风景”。七、八十年代之交,中国经历着再一次的“遭遇世界”。这一悲喜剧式的遭遇,一度有力地碎裂了很多人心目中中国作为世界革命中心的想象。于是,作为一次新的合法化论证,在对毛泽东“第三世界/发展中国家”的论述的有效挪用中,中国似乎开始接受自己在(西方中心的)世界历史中“滞后的现实”,开始承认置身于(西方中心的)世界边缘位置。整个八十年代,最为有效而有力的主流意识形态表述,是官方与精英知识分子达成的深刻共识,即“改革开放”,“走向世界”,“历史进步战胜历史循环”,“现代文明战胜东方愚昧”,“朝向蔚蓝色文明”,“地球村与中国的球籍问题”。类似的主流意识形态话语,无疑将中国对自身边缘位置的接受,定义为朝向世界中心、突破中心并终有一天取而代之的伟大进军。尽管此间经历了八十年代终结处的风波,但以1992年邓小平南巡讲话为转折,社会主义市场经济或曰全球化、商业化的过程,陡然由潜流奔涌而出。中国社会一夜间再度由沉寂而市声鼎沸,似乎成为“历史规律”不可抗拒的明证。于是,以Plaza作为昔日之广场的替代物,于是似乎成了一个“恰如其分”的逻辑结果。 从某种意义上说,对“广场”这一特定能指的挪用,是一次遮蔽中的暴露;它似乎在明确地告知一个革命时代的过去,一个消费时代的降临。这里有两个颇为有趣的例证。1996年,作为一次经典的政治教育活动,举办了大型图片和实物展览:《红岩》。展览所呈现的本是现代中国史上黑暗而酷烈的一幕:它揭露了在“中美合作所”--美国CIA与国民党当局的情报机构辖下的两所监禁政治犯的秘密监狱--“白公馆”和“渣滓洞”中的暴行,即共产党人及形形色色政治异见者,当年被施以酷刑,最终在1949年前被集体灭绝。六十年代,亲历者的回忆录《在烈火中永生》、借此创作的著名长篇小说《红岩》以及根据小说改编的电影《烈火中永生》,不仅成为六十年代中国文化的代表,而且无疑是革命文化的经典之作。它指称着伟大而圣洁的共产主义精神,指称着共产党人不可摧毁、永难毁灭的信仰与意志。对于中年以上的中国人说来,它赫然端居于人们的记忆清单之中,至少在二十年乃至更长的岁月中成为最感人且迷人的英雄范式。然而,这同一主题的展览,到了1996年却成了出资承办这一展览的企业“富贵花开公司”的商业广告行为。比“红岩”更为响亮的,是“富贵花开公司”的广告词:“让烈士的鲜血浇灌富贵花开”。在此,笔者毋需赘言“富贵花开”作为典型的“旧中国”阶级社会与市民文化的向往,与革命烈士为之献身的共产主义图景间存在着怎样巨大的裂痕;但与政治波普的有意识戏仿不同,它与其说是对立的意识形态话语之不谐的展示,不如说是一次(尽管不一定成功的)置换与缝合。共产主义前景、社会主义实践被全球化景观、小康社会的未来、更为富有且舒适的“现世”(不如说是消费主义的)生活所取代。一如可口可乐公司的驻中国机构,以中国五六十年代劳动模范奖状为范本,设计了对自己公司职员的奖励标志。 另一个例子或许更为直观而清晰。那是1996-1997年间矗立在北京老城的主干道长安街中心地段的巨幅广告,三棱柱形的活动翻板不间断地依次变换、展示着三幅画面。其中之一是一幅政治性的公益广告:红色衬底上白色的等线体字样书写着:“深化改革,建设有中国特色的社会主义”;继而出现的则是连续两幅画面华丽、色调迷人的“轩尼诗(Hennessy)X.O”的广告(2)。我们间或可以将其视为一处呈现九十年代文化冲突的空间:公益广告所采取的经典社会主义宣传品的形式,及其内容所昭示的当代中国作为最后一个社会主义堡垒的意义;与之共处的是轩尼诗广告所负载的跨国资本形象、消费主义所感召的奢靡、豪华的西方“现代”生活范本。这里无疑存在着某种“冷战”时代形同水火的意识形态对立,存在着F.杰姆逊所谓第三世界的民族国家文化与帝国主义文化的“生死搏斗”(3)。但事实上,这正是一处颇为典型的九十年代文化的共用空间:它所展现的与其说是一种冲突,不如说是一次合谋。其1:2的时空比,则暗示着一次中心偏移与中心再置的过程。 经济拯救取代(经典社会主义的或政治民主的)政治拯救,成为别无选择的中国未来之路;作为全球化过程必然的伴生物,消费主义便成了九十年代中国很多地方社会、文化景观最强有力的构造者。然而,这里发生着的并非一个线性过程。如果说,在上海--中国第一工业都市,昔日的东方第一港,“十里洋场”、西方“冒险家的乐园”--人民广场确已连缀在消费风景之中;那么,在北京--中国的政治文化中心,“广场”仍并置在两种乃至多种意识形态的社会运作之中。当众多的商城、商厦、购物中心、连锁店、专卖店吞吐并分割着都市的人流,天安门广场仍是国庆盛典及1997年6月30日为庆祝“对香港恢复行使主权”而组织彻夜联欢的场所。而在南中国的第一都市广州,一种更为“和谐”的组合是“青年文化广场”:大商城间的空间成了“社会主义精神文明建设”项目--青年联欢及组织“文艺演出”的场所。因此,“广场”称谓的挪用,是一份繁复而深刻的暴露与遮蔽,它暴露并遮蔽着转型期中国极度复杂的意识形态现实,暴露并遮蔽着经济起飞的繁荣背后跨国资本的大规模渗透。但对于九十年代很多中国人来说,远为重要的,是迷人的消费主义风景线,遮蔽了急剧的市场化过程中中国社会所经历的社会再度分化的沉重现实。 = “无名”的阶级现实 九十年代,围绕着Plaza,在中国都市铺展开去的全球化风景,不仅是商城、商厦,也不仅是星罗棋布于中国主要都市的麦当劳、必胜客;而且还有充满“欧陆风情”的“布艺商店”(家居、室内装饰店)、“花艺教室”(花店)、“饼屋”(面包房,这一次是台湾译名)、咖啡馆、酒吧和迪厅(舞厅),还有拔地而起的“高尚住宅”区,以及以“一方世外桃源,欧式私家别墅”、“时代经典,现代传奇”或“艺术大地”为广告或为名称的别墅群。曾作为八十年代精英知识分子话语核心的“走向世界”、“球籍”、“落后挨打”、“撞击世纪之门”,在这新的都市风景间也成为可望并可及的“景点”:商业国际电脑网络的节点站的广告云:“中国人离信息高速公路到底有多远?——向北1500米”;长安街上的咖啡馆取名为“五月花”,地质科学院办的对外营业餐厅名曰“地球村”。命名为“世纪”、“新世纪”、“现代”或“当代”的商城、饭店,名目各异的公司多如牛毛,不胜枚举。一时间,中国人作为“快乐的消费者”取代了“幸福的人民”或“愤怒的公民”的形象。似乎是一次“逻辑”的延伸,“在消费上消灭阶级”的“后现代”社会图景,取代了无阶级、无差异、各取所需、物质产品极大丰富的共产主义远景,成了人们所向往、追逐的现世天堂。 与此同时,于1994年以后再度急剧膨胀和爆炸的大众传媒系统(电视台、有线电视台、报纸周末版及周报、大型豪华型休闲刊物),以及成功市场化的出版业,不仅丰满并装点着全球化进程中的中国生活,而且也常常屏壁式地遮挡社会现实。比如新富(NewRich)群体的崭露头角引人注目;与此相关的文化呈现是呼唤、构造中国的中产阶级社群。作为八十年代知识分子话语构造成功的一例,九十年代的社会文化“常识”之一,是精英文化与流行文化共享的对“中产阶级”的情有独钟。因为在八十年代的文化讨论中,尤其是在对战后实现经济起飞的亚洲国家之例证的援引中,一个庞大的、成为社会主体的中产阶级群体的形成,标识着经济起飞的实现,指称着对第三世界国家地位的逃离,意味着社会民主将伴随不可抗拒的“自然”进程(以非革命的方式)来临。此间,为八十年代有关讨论所忽略、为九十年代的类似表述有意遗忘的,是无人问及十三亿人口之众的中国,面对着瓜分完毕、极度成熟的全球化市场,背负着难于记数的历史重负,有没有可能成为一个以中产阶级为主体的国度;更没有关心那些无法跻身于中产阶级的人群(“大众”或“小众”)将面临着怎样的生存。 一个更为有趣的事实,于九十年代陡然繁荣之至的大众文化与大众传媒,至少在1993—1995年间,不约而同地将自己定位在所谓中产阶级的趣味与消费之上。这与其说是一种现实的文化需求,不如说是基于某种有效的文化想象;作为一个倒置的过程,它以自身的强大攻势,在尝试“喂养”、构造中国的中产阶级社群。除却法国时装杂志ELLE的中国大陆版《世界时装之苑》外,大型豪华休闲刊物《时尚》、《新现代》、《How》等纷纷创刊。如果参照1996年国家公布的各城市贫困线收入,类似杂志定价高达中国“最低生活保障”收入的1/10或1/20(在国家公布的《全国部分城市最低生活标准》中,北京、上海、广州分别为170、185、200元人民币)(4)。相对价格低廉、因而更为成功的是形形色色商业型小报。后者索性名之为《精品购物指南》、《购物导报》、《为您服务报》。类似出版物不仅以其自身充当着“高尚趣味”的标识,而且确乎体贴入微地教化着人们,如何做一个“合格”的中产阶级成员,如何使自己的“包装”吻合于自己的阶级身份。1995年的《精品购物指南》上索性刊载文章,具体告之,收入达五千元者应穿戴某一/某些品牌的时装、搭配何种品牌的皮带、皮鞋、皮包、手表;并依次类推出四千元、三千元、两千元者又当如何如何。某些售房广告引人注目地标明:“为名流编写身份的建筑”(5)。于是,商品的品牌文化便作为最安全、又最赤裸的阶级文化登堂入室。与此同时,以所谓“中国第一部百集大型室内剧(准肥皂剧)”《京都纪事》为标识,名曰《儒商》、《东方商人》、《公关小姐》、《白领丽人》、《总统套房》等等的电视连续剧,充斥在全国不同电视台的黄金时段之中;所谓“商战”故事,显然在以不甚娴熟得法的方式,展示着中产阶级或曰新富阶级的日常生活情境与魅力。如果说,在九十年代初,类似电视剧尚且是由Plaza风景、五星级饭店、总统套房式的豪华公寓、一夜骤富的泡沫经济奇迹、红男绿女、时装品牌组成的“视觉冰淇淋”;那么,到九十年代中期,颇为风行的电视连续剧《过把瘾》、《东边日出西边雨》等等,已不仅准确地把握着一份温馨忧伤的中产阶级情调,而且开始以曲折动人的故事,娓娓诉说着中产阶级的道德、价值规范。恰是在1994-1996年间,曾被目为具有政治颠覆性的、以王朔为代表的通俗文化,开始有效地参与构造中产阶级文化,或曰大众文化,至少其颠覆性因素已获得了有效的吸纳与改写(6);倡导后现代主义的文学批评者亦开始明确倡议“为中产阶级写作”。于是,在九十年代,尤其是1993年以降的中国文化风景线上,种种话语实践凸现着一个形成之中的阶级文化;但除却优雅宜人的中产阶级趣味与生活方式,确乎处在阶级急剧分化中的中国社会状况,却成了一个“不可见”的事实。 “让一部分人首先富起来”的国家政策,当然是推动市场经济的现实必须,但如何“富”,却有诸多选择殊异。与其说九十年代中国出现了一个稳定、富足的中产阶级社群,倒不如说,在所有制转换过程中(将计划经济的国家资产转化为企业、乃至个人资本),在泡沫经济的奇观内,很多地方出现了一个不无怪诞而洋洋自得的新富群体;与此相伴生的,不仅是在有限的资源分配中必然出现的另一部分人绝对生活水准的下降;而且是在国营大、中型企业中所经历的体制转轨中,数量颇巨的失业、下岗工人,以及在中国都市化、非农化过程中,涌入城市的“打工族”已形成弱势群体。尽管相对于六七十年代,中国社会消费水准的平均值大大提高是一个不争的事实;但从某种意义上说,触目惊心的贫富两极分化正在被热闹非凡的消费风景遮蔽。1996年11月,登载在《北京青年报》上的一则消息堪为一例。有趣的是,这是一则讨论广告方式是否得当的文章,题为《浙江一条广告惹众怒》。文章报道浙江一家服装公司为“树立企业形象”打出了一条广告,曰:“50万元能买几套海德绅西服?”答案是10套。因为这是用进口高档面料,嵌宝石的纯金纽扣制作而成的豪华服装,定价分别为6.8万、4.8万及2万。报道云,这则广告大犯众怒,并特别引证了一则钢铁厂青年工人的来信:“我在炼钢炉边已战斗了五个春秋,流了多少汗水,留了多少伤疤,你是无法想象的。这本是我的骄傲和自豪,但我现在感到很可悲,因为我五年的劳动所得,还不够买你公司的一套西服……”因众怒难犯,该公司“向消费者致歉”:“我们忽视了它带来的负面影响,这容易误导消费者,助长高消费,不利于社会主义精神文明建设。”但同一篇报道提及:“据悉,这10套豪华西服目前已有9套被人买走或订购。据称这9个买主绝大部分是生意人和建筑业主。”这篇关于一则“失败”(?)的广告报道,固然涉及了商品社会游戏规则的讨论;但它显然在有意无意间展露了无差异的消费图景背后日渐尖锐的阶级现实;而且于不期然处,触及了并置在中国的社会现实中彼此冲突的意识形态话语系统,触及了转型期中国的身份政治与身份危机。 在这种不期然的,或曰“化装”形式之下,贫富分化的现实绝少被提及,即使不得不涉及,也决不使用“阶级”字样。事实上,这或许是九十年代中国最为典型的、葛兰西所谓的意识形态“合法化”与“文化霸权”的实践。历经八十年代的文化实践及其非意识形态化的意识形态构造,“告别革命”成为九十年代很多人的一种社会共识。与“革命”同时遭到放逐的,是有关阶级、平等的观念及其讨论。革命、社会平等的理想及其实践,被简单地等同于谎言、灾难,甚至等同于“文化大革命”的记忆;作为九十年代中国的社会奇观之一,是除却少数有名无实的官样文章,马克思主义的理论、社会批判的立场,不仅事实上成了文化的缺席者,而且公开或半公开地成了中国知识界的文化“公敌”。取而代之的,是所谓“经济规律”、“公平竞争”、“呼唤强者”、“社会进步”。因此,在1993—1995年间,陡然迸发、释放出的物欲与拜金狂热,不仅必然携带着社会性生存与身份焦虑,而且在对激增的欲望指数、生存压力的表达中混杂着无名的敌意与仇恨。似乎指认阶级、探讨平等,便意味着拒绝改革开放,要求历史“倒退”;便意味着拒绝“民主”,侵犯“自由”。甚至最朴素的社会平等理想亦被拒绝或改写——售房广告云:“东环广厦千万间,大庇天下人杰俱欢颜”;对照一下杜甫的名句“安得广厦千万间,大庇天下寒士俱欢颜”便一切尽在不言之中(7)。于是,尽管不可见的社会分化现实触目可观,比比皆是;但它作为一个匿名的事实,却隐身于社会生活之中。如果说,那份巨大而无名的敌意必须得到发露;那么,人们宁肯赋予它别一指认与称谓,人们宁愿接受它来自某个外在的敌人,而非内在威胁。因此,1996年,中国文化舞台上引人注目的演出:民族主义的快速升温(以《中国可以说不》为肇始),尽管无疑有着极为复杂的政治、经济、历史、文化的成因,但成功地命名并转移了充塞着中国社会的“无名仇恨”——这显然是其深刻而内在的动因之一。1996年以后,极为有限的出现在传媒之中的关于资方残酷剥削、虐待工人的报道,也都无例外地涉及“外商”的恶行,社会内部阶级矛盾便被成功地转换为民族(至少是地域)冲突。 = 对现实的“修辞” 1997年夏,袭击北京的百年未遇的酷暑,最初以持续摄氏40度以上的高温,似乎使消费景观颇为热烈:各类品牌的空调机销售一空;但继而是不堪重负的城市供电系统频频断电;显露而出的,并非“后现代”的逍遥惬意,相反是一份第三世界的生存处境。更为有趣的,“国际接轨”的“广场”上出现了异样风景:每晚“七点一过”,商场内便水泄不通,附近居民“穿着拖鞋、睡衣,摇着扇子,拿着板凳”,“一家子一家子”地来到商场。来者不仅并非奢华的购物者,甚至不是来“逛商场”;他们仅仅是来“分享”商场内充足的冷气——那无疑是消费不起空调的下层市民。事实上,如果说消费主义成了九十年代中国最有力的书写之手;那么也正是消费的可能与方式清晰地划定了不同阶级、阶层的活动空间。比“广场”更为普遍而火爆的,是建筑在居民区之内的“仓储式商店”和形形色色的小商品批发市场;如果说在发达国家,所谓“仓储式商店”原本与郊区别墅、高速公路、私人轿车相伴生;那么,在这里,它却是廉价便民商店的代名词。于是,提着沉重的购物袋步行或搭乘公共汽车的购物者便成为中国都市人流中的别一点缀。而尽管人人皆知所谓“小商品批发市场”是种种假冒乃至伪劣产品的集散地,但它极为低廉的价格仍吸引着络绎不绝的人群。在“正常”情况下,市内“仓储式商店”与小商品批发市场的消费者并不光顾“广场”一类的“购物天堂”,至少绝非那里的常客。只是不期而至的酷暑颠覆了这井然有序的社会层次。 不仅如此。伴随着“大、中型企业的转轨”,企业破产、兼并及其它重大经济问题使得失业、下岗人数持续增长,而社会保障体系极不健全,确乎使部分失业、下岗工人面临着生存困境;而在社会主义“单位制”(生老病死有依靠,而绝无失业之虞)下成长起来的一代人,确乎完全缺乏应对类似变迁的心理机制。于是,这庞大的、并且在继续增长着的无业大军,不仅成为九十年代中国巨大的社会问题,而且在多方面成了难于彻底消除的隐患。犹如被撕裂的迷人景象,这一严酷的社会事实开始不“和谐”地出现在豪华生活、优雅趣味所充满的大众传媒之上。在不无“忧虑”的“中国大学生高消费”的讨论之畔,是关于呼吁救助衣食不全的高校“特困生”的报道;在关于“富裕的生活环境下长大的亚洲新一代”(他们青春期反抗的语言是:“他们老以为我还是吃麦当劳的年龄!我已经该吃必胜客了!”)的写真近旁,是“希望工程”失学儿童令人心碎的故事。甚至在同一版面,平行的位置,刊载着《最新调查结果显示,中国大都市居民消费信心在上升》和《再就业为何这样难——来自北京市下岗女工的调查报告》(8)。 然而,这凸现而出的阶级事实,并未真正使中国知识界动容。迄今为止,除极少数人文、社会学者之外,中国知识界始终鲜有人真正面对现实发言。这与其说是出自某种政治的禁忌和文化的误区,不如说它确乎出自某种拒绝反思、“告别革命”的立场选择。如果说,八十年代对类似现实的修辞,即改革的“阵痛”、历史的“代价”与进步的“过程”等等,已不足以有效地阐释/遮蔽这突出的社会困境;那么,九十年代新的修辞方式则是更加冷漠而脆弱的。1996年以降,开始频频出现在传媒之上的、关于失业/下岗工人的报导、讨论,连篇累牍地将再就业的困境解释为失业者自身的“观念转变”问题、“素质”问题、“缺乏专业技能”问题。类似讨论,全然无视原有体制的问题(首先是社会保障制度的缺席),无视很多劳动者作为社会主人公朝向经济与文化的社会底层的坠落,无视在失业/再就业过程中,公然而赤裸的年龄歧视和性别歧视。或许可以说,正是类似讨论实践着意识形态合法化的过程,它不仅潜在地将失业工人指认为“公平竞争”中“合理的劣汰者”;而且将他们无法成功地再就业的事实,不作具体分析地完全归之于他们自身的原因。更为重要的是,如果说,失业/下岗工人确实在城市内部为迅速进入的跨国资本和中国的“新富群”提供了新的廉价劳动力资源;那么他们可能面临的低廉工资、高强度劳动,及权益与福利难获保障的现实也正在遭到很多知识精英的忽视。更为荒诞的是,普通工人,一经下岗并“转变观念”,便抓住了“机遇”,陡然“劳动”致富——在众多这些夸张的故事里,失业/下岗竟然成了天赐良机。 如果说,类似“修辞”尚不能完全成功地遮蔽社会现实;那么,迅速改观了的电视剧与部分文学作品的趋向——“现实主义骑马归来”,则是作为另一种相对有效的社会“修辞”方式。1995年底,似乎是一个不期然的转变,在电视连续剧的舞台上,白领、商战故事的狂潮悄然隐去;取而代之的,是家庭情节剧,而且是颇具中国通俗文化传统的“苦情戏”。换言之,是穷人的故事取代了新富的传奇;已在八十年代退出了时代底景的大杂院、新工房(老式公寓楼)再度出场,替换了“广场”风景。其中收视率最高,并且再度成为街谈巷议之资的,是两部家庭苦情戏《咱爸咱妈》(1996年)和《儿女情长》(1997年)。不约而同地,两部电视连续剧都以老工人的父亲突然患不治之症病倒,他们原来服务的工厂无力提供医疗所必需的费用为核心情节,结构起一幕温馨苦涩的父/母慈子孝、手足情深的多子女家庭情节剧。在底层家庭或医院病床的场景中,不再为无所不包的社会主义体制所庇护的底层生活场景显影而出:这里有老人,尤其是工人的境遇问题、高昂的医疗费用问题、下岗女工问题、公开或隐晦的阶级歧视问题……然而,这与其说是现实主义的触摸,不如说是情节剧式的遮蔽。因为,在这两部连续剧中,尖锐的现实以及下层社会的苦难,被转移为传统中国的血缘亲情、家庭伦理命题;原国营大中型企业工人所面临的生存问题不再呈现为当代中国的社会问题,相反成了一个特殊的“机遇”,用以展现“血比水浓”的亲情;成了验证和复活中国传统孝悌之道的极好舞台。于是,中国式的三代、四代同“堂”的血缘(而非核心)家庭再度浮现,充当着涉渡“苦海”的一叶小舟。其中更为有趣的是《儿女情长》。该电视连续剧的核心情节,是严重脑溢血的父亲和身患癌症的母亲,顽强地延续着自己的生命,为了保持人口数,以便在城市改建、旧房搬迁的机会中,为孩子们赢得更多的住房。于是,下层社会的获救愿望仍有待于“现代化”的全面实现。但如果说,底层老人的舐犊之情,终于使孩子们赢得了宽敞的新居;那么真正使这个家庭面临的复杂困境获得解决、将这个家庭救离苦海的,却是出自一位新富的“善行”:这位“大款”爱上了家中身为单亲母亲的长女。在历经商海沉浮、人情冷暖、两性游戏之后,“大款”懂得了自己所需要的是一个善良、朴素、年龄相仿、宜家宜室的女人;于是,他昔日的学校“同桌”、今日的中年下岗女工幸运“入选”。“大款”小小的慷慨相助,便使这个家庭的问题烟消云散:开出租车的幼子得以另结良缘;次子惨淡经营的小小书摊有了资金保障;工厂下岗的长女和幼子的新妇——地位低微的街道清扫女工成了豪华街道上的花店女主人。 以另一角度触动并消解这一现实的,是被称之为“文学的现实主义冲击波”的系列小说的出现。以刘醒龙的中篇小说《分享艰难》为开端,以谈歌的《大厂》、关仁山的《大雪无乡》、何申的《年前年后》、周梅森的《人间正道》为代表。正是这类作品,为正统宣传与大众文化的再度携手,提供了一种新的空间。所谓“现实主义”之说,显然得自于这些小说大胆触及了此前完全无名、不予揭示的“社会阴暗面”:国营大中型企业的举步艰难,工人面临的生存困境,官僚阶层的贪污腐败,农民遭到的层层勒索。然而,颇为有趣的是,类似小说同时确乎是社会主义工农兵文艺的再现,只不过是经过了商业化的改写。在这些作品里,苦难的主题是直接而具体的;但拯救的给出则含混和暧昧得多。社会结构分化的现实转化为“好人”和“坏人”的修辞方式,其中阶级字样只由两种类型人物“特权”地使用:其一,是最终会在故事的结局中被指认为“经济犯罪分子”,并终被绳之以法的“坏人”;因此他口中赤裸的资本主义“宣言”与洋洋自得的阶级压迫性的语词,便无疑是一种谬误;其二,则是一些王朔或准王朔式的角色,他们把政治性的“套话”移置在不恰当的语境之中,于是关于“资本家”、“剥削”、“老板”、“穷工人”、“受苦人”、“资本家的走狗”等,竟然成了毫无意义的玩笑和套话。在这里,王朔式的语言风格,有效地颠覆了这些话语自身所携带的颠覆性,重要的社会现实在凸现中被重新遮蔽,使其仍为一个未获命名的现实。 类似小说中的第一主角通常并非社会苦难的直接背负者:普通的工人或农民;而大多是中层或基层干部、行政或企业的管理者:厂长、市长、乡长、车间主任。于是,这个桥梁式的人物便连接起社会的不同层面:政府、新富阶级、跨国资本之代理与下层民众。从某种意义上说,他/她似乎是苦难的承担者,也应该是拯救的给出者;但事实上,在小说情境中,他/她更像无助的替罪羊与无奈、无辜的帮凶者。他/她无疑充满良知,深切地同情着下层民众的苦难,但只能因此而倍受折磨、 无能为力,甚至“不得已”加入压榨者的行列,至少是默认或首肯他们的行为。但就阅读、接受而言,显然是这些主角,而并非真正无助的工人、农民,获得了读者的满腔同情。我们在对他/她的认同与同情间,认可了现实的残忍与无奈,认可了这不尽如人意的一切毕竟是我们唯一“合法”的现实。 文学并不等于社会学,有偏见或缺陷的作品也有艺术上的高下优劣之分,但这并不意味着文学作品中的意识形态无须解读与清理。九十年代,大众文化无疑成了中国文化舞台上的主角。在流光溢彩、盛世繁华的表象下,是远为深刻的隐形书写。在似乎相互对抗的意识形态话语的并置与合谋之中,在种种非/超意识形态的表述之中,大众文化的政治学有效地完成着新的意识形态实践。从某种意义上说,这一新的合法化过程,很少遭遇真正的文化抵抗。在很多人那里,社会主义时代的精神遗产或被废弃,或被应用于相反的目的。我们正经历一个社会批判立场缺席的年代。 = 注释: + 参见笔者的《救赎与消费:九十年代文化描述之一》,《钟山》1995年3期。英译文见Positions,1996年春季号。 + 这幅广告的有趣形式显然引起了王朔一族的兴趣,于是,它成了王朔自编自导的电影《爸爸》(改编自王朔的长篇小说《我是你爸爸》)一个场景中始终如一的背景。这无疑是一种王朔式的调侃。广告于1997年10月被更换,“轩尼诗XO"的两幅依旧,公益广告的一幅换成了毛泽东语录:“发展体育运动,增强人民体质。” + [美]F.杰姆逊《处于跨国资本主义时代的第三世界文学》。张京媛译。《当代电影》1989年6期。 + 参见《全国部分城市最低生活保障标准》,《资产新闻报》,1997年2月28日,总第76期,三版。 + 此为1995年九鼎轩文化策划公司为北京法政实业总公司(司法部下属公司)所做的房地产广告用语。 + 笔者所谓的“王朔一族”,指九十年代围绕在王朔周围,并逐渐成为大众传媒制作系统中颇为出色、活跃的一批创作者。以1990年在中国大部分地区构成轰动效应的中国第一部大型电视室内剧《渴望》(王朔作为主要策划者之一)为契机,王朔、冯小刚、李晓明等成为影视通俗作品制作业的主力。从1990—1995年,诸多重要的影视作品都与这一一度名之为“海马创作中心”的群体有关。 + 这块广告牌树立在北京主干线之一的三环路上。类似的广告还有“冠盖满京华,名人独潇洒”(原古诗句为“冠盖满京华,斯人独憔悴”)。 + 参见《北京青年报》1996年11月20日,第八版。
https://github.com/Dioprz/Notes
https://raw.githubusercontent.com/Dioprz/Notes/main/Scala/Functional_Programming_in_Scala/Chapter_1.typ
typst
#set page(margin: 1.75in) // #set par(leading: 0.55em, first-line-indent: 1.8em, justify: true) #set par(leading: 0.55em, justify: true) #set text(font: "New Computer Modern") #show raw: set text(font: "New Computer Modern Mono") #show par: set block(spacing: 1.4em) #show heading: set block(above: 1.4em, below: 1em) = Capítulo 1: Qué es programación funcional? == Conceptos y observaciones / Expresión transparente referencialmente: Decimos que una expresión $e$ tiene, cumple o satisface _transparencia referencial (RT)_ si, para todo programa $p$, todas las ocurrencias de $e$ en $p$ pueden ser reemplazadas por el resultado de evaluar $e$ sin afectar el significado de $p$. / Función pura : Una función $f$ es pura si la expresión $f(x)$ es RT para toda expresión $x$ RT. == Conclusiones El diseño funcional permite que los programas sean pensados y diseñados de una forma mucho más modular y local gracias a la transparencia referencial. Cuando una función debe ser modificada o símplemente comprendida, no es necesario simular mentalmente secuencias de actualizaciones de estado. El entendimiento se limita a un _razonamiento local_ en donde todo lo que importa es la entrada y salida de la función. Además de esto, y gracias a que el código no tiene efectos laterales, el código se limita a ser una serie de composiciones. Garantizar tales cosas hacen que las labores de testeo, revisión y modificación del código se vuelvan radicalmente más sencillas, aumentando la mantenibilidad y vida del código.
https://github.com/teshu0/CLIT-report-typst
https://raw.githubusercontent.com/teshu0/CLIT-report-typst/main/README.md
markdown
Creative Commons Zero v1.0 Universal
# CLIT-report-typst コンリテのアクティビティ・アサインメントレポートのTypst版テンプレート。LaTeXしたくない人向け。 - [`/activity.typ`](./activity.typ) はアクティビティレポート(授業中の方)のテンプレート - [`/assignment.typ`](./assignment.typ) はアサインメントレポート(課題の方)のテンプレート - [`/template`](./template) はテンプレのためのユーリティティなど - [`/class`](./class) は授業ごとのテンプレだけど全部をカバーしてるわけじゃない テンプレートリポジトリなので、クラスごとにレポ作ってやるといいかも
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/jurz/0.1.0/README.md
markdown
Apache License 2.0
# jurz – *Randziffern* in Typst [*Randziffern*](https://de.wikipedia.org/w/index.php?title=Randnummer&oldid=231943223) (also called *Randnummern*) are a way to reference text passages in a document, independent of the page number or the section number. They are used in many German legal texts, for example. This package provides a way to create *Randziffern* in Typst. ## Demo <table> <tr> <td> <img src="demo-2.svg" alt="left page with Randziffern on the left of the text"> </td> <td> <img src="demo-3.svg" alt="right page with Randziffern on the right of the text"> </td> </tr> </table> <details> <summary>View source</summary> ```typst #show: init-jurz.with( gap: 1em, two-sided: true ) #rz #lorem(50) #lorem(20) #rz<abc> #lorem(30) #rz #lorem(40) #rz #lorem(50) #lorem(20) #rz #lorem(24) Fur further information, look at @abc. ``` </details> ## Reference ### `init-jurz` A show rule that initializes the *Randziffern* for the document. This rule should be placed at the beginning of the document. It also allows customizing the behavior of the *Randziffern*. #### Usage ```typst #show: init-jurz.with( // parameters // two-sided: true, // gap: 1em, // supplement: "Rz.", // reset-level: 0, ) ``` #### Parameters - `two-sided` (optional): If `true`, the *Randziffern* are placed on the outer margin of the page. If `false`, they are placed on the left margin. Default is `true`. - `gap` (optional): The distance between the *Randziffer* and the text. Default is `1em`. - `supplement` (optional): The text that is placed before the *Randziffer* when referencing it. Default is `"Rz."`. - `reset-level` (optional): The heading level at which the *Randziffern* are reset. If set to `3`, for example, the numbering of the *Randziffern* restarts after every heading of levels `1`, `2`, or `3`. Default is `0`. ### `rz` Adds a *Randziffer* to the text. The *Randziffer* is a unique identifier that can be referenced in the text. You can add references the same way you can with headings. In fact, the *Randziffer* is treated as a heading of level `99` under the hood. #### Usage ```typst #rz #lorem(100) #rz<abc> #lorem(100) See also @abc. ``` ## License This package is licensed under the MIT License.
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/AnalisiDeiRequisiti/changelog.typ
typst
MIT License
#let changelog = csv("changelog.csv") #table( columns: (1fr, 2fr, 4fr, 2fr, 2fr), [*Versione*], [*Data*], [*Descrizione*], [*Autore*], [*Ruolo*], ..changelog.rev().flatten() )
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-2/homework10.typ
typst
#import "../template.typ": * #show: project.with( course: "Calculus II", course_fullname: "Calculus (A) II", course_code: "821T0160", title: "Homework #10: 多重积分", authors: ( ( name: "<NAME>", email: "<EMAIL>", id: "#198", ), ), semester: "Spring-Summer 2024", date: "May 7th, 2024", ) #let iintd = iintb($D$) #let iints = iintb($S$) #let iintsg = iintb($sigma$) #let iiintv = iiintb($V$) #let iiintog = iiintb($Omega$) #let probx(x) = [#prob(x);#v(2em)#v(1fr)] = 习题9-1 == P136 4(1) #prob[ 比较二重积分的大小: $ iintd x y dx dy " 与 " iintd (x^2 + y^2) dx dy $ ] 由均值不等式得 $ x^2 + y^2 >= sqrt(x^2 y^2) = abs(x y) >= x y $ 故 $ iintd x y dx dy < iintd (x^2 + y^2) dx dy $ == P136 4(2) #prob[ 比较二重积分的大小: $ iintb(1<=x^2+y^2<=2) x^2 y^4 sin 1 / y^2 dx " 与 " iintb(1<=x^2+y^2<=2) 2 x^2 dx dy $ ] 由于 $display(1/y^2)>=0$,故 $display(sin 1/y^2 <= 1/y^2)$,可得 $ y^4 sin 1 / y^2 <= y^4 dot 1 / y^2 = y^2 <= 2 $ 两边同乘 $x^2$,不变号,可得 $ x^2 y^4 sin 1 / y^2 <= 2 x^2 $ 故 $ iintb(1<=x^2+y^2<=2) x^2 y^4 sin 1 / y^2 dx dy < iintb(1<=x^2+y^2<=2) 2 x^2 dx dy $ = 习题9-2 == P151 2(1) #prob[ 设 $f(x)$ 在闭区间 $[a,b]$ 上连续,试证明: $ int_a^b dy int_y^b f(x) dx = int_a^b (x-a) f(x) dx $ ] $ int_a^b dy int_y^b f(x) dx = int_a^b (int_a^x dy) f(x) dx = int_a^b (x-a) f(x) dx $ == P151 2(5) #prob[ $ int_a^b dy int_y^b f(x) f(y) dx = 1 / 2 (int_a^b f(x) dx)^2 $ ] $ int_a^b dy int_y^b f(x) f(y) dx = 1 / 2 (int_a^b dy int_a^b f(x) f(y) dx) = 1 / 2 (int_a^b f(x) dx)^2 $ == P151 3(1) #prob[ 在下列积分中改变积分的顺序: $ int_0^2 dx int_x^(2x) f(x,y) dy $ ] 画图分析可得: $ I = int_0^2 dy int_(y / 2)^y f(x,y) dx + int_2^4 dy int_(y / 2)^2 f(x,y) dx $ == P151 3(3) #prob[ 在下列积分中改变积分的顺序 $ int_0^(2a) dx int_sqrt(2a x-x^2)^sqrt(2a x) f(x,y) dy space (a>0) $ ] 分析: $ & 0 <= x <= 2a; quad sqrt(2 a x - x^2) <= y <= sqrt(2a x) \ ==> & 0 <= x <= 2a; quad y^2 <= 2 a x <= x^2 + y^2 $ $D={(x,y) : 0 <= x <= 2a,space y^2 <= 2 a x <= x^2 + y^2 }$ 可以看做 $y^2=2a x,space (x-a)^2 + y^2 = a^2,space x=2a$ 所围成的区域。故 $ int_0^(2a) dx int_sqrt(2a x-x^2)^sqrt(2a x) f(x,y) dy = int_0^(2a) int_(y^2 / (2a))^(2a) f(x, y) dx dy - int_0^a int_(a-sqrt(a^2-y^2))^(a+sqrt(a^2-y^2)) f(x,y) dx dy $ == P151 4(1) #prob[ 计算二重积分:$iintd x^2 y dx dy$,其中 $D$ 是由双曲线 $x^2-y^2=1$ 及直线 $y=0,y=1$ 所围成的平面区域。 ] $ & iintd x^2 y dx dy = int_0^1 int_(-sqrt(y^2+1))^(sqrt(y^2+1)) x^2 dx y dy = int_0^1 2 / 3 y (y^2+1)^(3 / 2) dy = 1 / 3 int_0^1 (y^2+1)^(3 / 2) dif (y^2)\ = & 1 / 3 int_0^1 (u+1)^(3 / 2) du = atpos((2 u^(5/2))/15, 1, 2) = (8 sqrt(2) - 2) / 15 $ == P151 4(3) #prob[ 计算二重积分:$iintd y dx dy$,其中 $D$ 是由 $x$ 轴、$y$ 轴及曲线 $display(sqrt(x/a) + sqrt(y/b) = 1)$ 所围成的区域 $(a>0,b>0)$。 ] $ & iintd y dx dy = int_0^a dx int_0^(b (1-sqrt(x/a))^2) y dy = int_0^a 1 / 2 (b(1-sqrt(x/a)))^2 dx = int_0^1 (a b^2) / 2 (1-sqrt(u))^4 dif u\ = & (a b^2) / 2 int_1^0 t^4 (-2 (1-t) dt) = (a b^2) int_0^1 (t^4 - t^5) dt = (a b^2) / 30 $ == P151 5 #prob[ 计算: $ display(int_0^(pi/6) dy int_y^(pi/6) (cos x)/x dx) $ ] $ int_0^(pi / 6) dy int_y^(pi / 6) (cos x) / x dx = int_0^(pi / 6) (int_0^x dy) (cos x) / x dx = int_0^(pi / 6) x dot (cos x) / x dx = int_0^(pi / 6) cos x dx = atpos(sin x, 0, pi/6) = 1 / 2 $ == P151 6 #prob[ 计算: $ display(int_1^2 dx int_(sqrt(x))^x sin (pi x)/(2 y) dy + int_2^4 dx int_(sqrt(x))^2 sin (pi x)/(2 y) dy) $ ] $D$ 相当于 $x=1,x=4,y=2,y=x,y=sqrt(x)$ 所围成的图形。那么: $ & int_1^2 dx int_(sqrt(x))^x sin (pi x) / (2 y) dy + int_2^4 dx int_(sqrt(x))^2 sin (pi x) / (2 y) dy = iintd sin (pi x) / (2y) dx dy = int_1^2 int_y^(y^2) sin (pi x) / (2y) dx dy\ = & int_1^2 (2y) / pi atpos((-cos (pi x)/(2y)), y, y^2) dy = -2 / pi int_1^2 y cos (y pi) / 2 dy = (4(2+pi)) / (pi^3) $ == P151 7(1) #prob[ 利用极坐标计算积分: $ iintd sqrt(1-x^2 -y^2) dx dy quad D={(x,y):x^2+y^2<=x} $ ] 代入 $x=r cos theta;space y=r sin theta$ 得 $ x^2 + y^2 <= x ==> r^2 cos^2 theta + r^2 sin^2 theta <= r cos theta ==> r^2 <= r cos theta ==> r <= cos theta $ 故 $ & iintd sqrt(1-x^2 -y^2) dx dy = int_(-pi / 2)^(pi / 2) dif theta int_0^(cos theta) sqrt(1-r^2) r dif r = int_(-pi / 2)^(pi / 2) dif theta 1 / 2 int_0^(cos^2 theta) sqrt(1-t) dif t\ = & - 1 / 3 int_(-pi / 2)^(pi / 2) (abs(sin^3 theta) - 1) dif theta = -2 / 3 int_0^(pi / 2) (sin^3 theta - 1) dif theta = pi / 3 - 4 / 9 $ == P151 7(3) #prob[ 利用极坐标计算积分: $ iintd (x+y) dx dy quad D={(x,y):x^2+y^2<=x+y+1} $ ] $ x^2 + y^2 <= x + y + 1 ==> (x-1 / 2)^2 + (y-1 / 2)^2 <= 3 / 2 $ 取 $display(x=1/2 + r cos theta\,space y=1/2 + r sin theta)$ 得 $ r^2 <= 3 / 2 ==> r <= sqrt(3/2) $ 故 $ &iintd (x+y) dx dy = int_0^(2 pi) int_0^sqrt(3/2) (1 / 2 + r cos theta + 1 / 2 + r sin theta) r dif r dif theta\ =& int_0^sqrt(3/2) int_0^(2 pi) (1+r (cos theta + sin theta)) dif theta r dif r = int_0^sqrt(3/2) atpos((theta + r sin theta - r cos theta), 0, 2 pi) r dif r\ =& 2 pi int_0^sqrt(3/2) r dif r = 3 / 2 pi $ == P151 7(5) #prob[ 利用极坐标计算积分: $ iintd (1-x^2-y^2) / (1+x^2+y^2) dx dy $ 其中 $D$ 是 $x^2+y^2=1$,$x=0$ 及 $y=0$ 所围区域在第一象限的部分。 ] $ &iintd (1-x^2-y^2) / (1+x^2+y^2) dx dy = int_0^(pi / 2) int_0^1 (1-r^2) / (1+r^2) dot r dif r dif theta = pi / 2 int_0^1 (r-r^3) / (1+r^2) dif r = pi / 2 int_0^1 ((2r) / (1+r^2) - r) dif r\ =& pi / 2 int_0^1 atpos((ln(1+r^2)-1/2 r^2),0,1) = pi / 2 (ln 2 - 1 / 2) $ == P151 8(1) #prob[ 用适当方法计算积分: $ iintb(0<=x\,y<=1) abs(y-x^2) max{x,y} dx dy $ ] $ & iintb(0<=x\,y<=1) abs(y-x^2) max{x,y} dx dy\ =& int_0^1 int_x^1 (y-x^2) y dif y dif x + int_0^1 int_(x^2)^x (y-x^2) x dif y dif x + int_0^1 int_0^(x^2) (x^2 - y) x dif y dif x\ =& int_0^1 (1 / 3 - x^2 / 2 + x^3 / 6 - x^4 / 2 + x^5) dx = 11 / 40 $ == P152 8(3) #prob[ 用适当方法计算积分: $ iintd(x^2/a^2 + y^2/b^2) dx dy quad D:x^2+y^2<=R^2 $ ] $ & iintd(x^2/a^2 + y^2/b^2) dx dy quad D:x^2+y^2<=R^2 = int_0^(2pi) int_0^R ((r cos theta)^2 / a^2 + (r sin theta)^2 / b^2) r dif r dif theta\ =& int_0^(2 pi) int_0^R ((cos^2 theta) / a^2 + (sin^2 theta) / b^2) r^3 dif r dif theta = int_0^R (pi / a^2 + pi / b^2) r^3 dif r = pi / 4 R^4 (1 / a^2 + 1 / b^2) $ == P152 10 #prob[ 求抛物线 $y=x^2$ 与直线 $y=x+2$ 所围的平面图形的面积。 ] 联立 $display(cases(y=x^2,y=x+2))$ 得 $display(cases(x=-1,y=1))$ 或 $display(cases(x=2,y=4))$。故 $ S = int_(-1)^2 int_(x^2)^(x+2) dy dx = int_(-1)^2 (x+2-x^2) dx = 9 / 2 $ == P152 14(1) #prob[ 求曲面所围成立体的体积: $ z = 1+x+y,z=0,x+y=1,x=0,y=0 $ ] $ V &= int_0^1 int_0^(1-x) (1+x+y) dy dx = int_0^1 ((1+x)(1-x) + (1-x)^2 / 2) dx\ &= int_0^1 (-x^2 / 2 + x + 3 / 2) dx = 5 / 6 $ == P152 14(3) #prob[ 求曲面所围成立体的体积: $ z=x^2+y^2, x^2+y^2=x, x^2+y^2=2x, z=0 $ ] $ V &= iintd (x^2+y^2) dx dy quad D={(x,y) : x<=x^2+y^2<=2x} $ 令 $display(cases(x = r cos theta, y = r sin theta))$,得 $ x <= x^2 + y^2 <= 2x ==> r cos theta <= r^2 <= 2 r cos theta ==> cos theta <= r <= 2 cos theta $ 故 $ V &= int_(-pi / 2)^(pi / 2) int_(cos theta)^(2 cos theta) r^3 dif r dif theta = 2 int_0^(pi / 2) int_(cos theta)^(2 cos theta) r^3 dif r dif theta = 2 int_0^(pi / 2) atpos(r^4/4, cos theta, 2 cos theta) dif theta\ = & 15 / 2 int_0^(pi / 2) cos^4 theta dif theta = 15 / 2 dot 3 / 4 dot 1 / 2 dot pi / 2 = 45 / 32 pi $ = 习题9-3 == P171 1(2) #prob[ 计算下列三重积分 $ iiintv (dx dy dz) / ((1+x+y+z)^3) $ 其中 $V$ 是由曲面 $x+y+z=1,z=0,y=0,x=0$ 所围成的立体。 ] $ & iiintv (dx dy dz) / ((1+x+y+z)^3) = int_0^1 dx int_0^(1-x) dy int_0^(1-x-y) (1+x+y+z)^(-3) dz\ =& int_0^1 dx int_0^(1-x) dy int_(1+x+y)^2 (dt) / t^3 = int_0^1 dx int_0^(1-x) dy atpos((1/(-2 t^2)), 1+x+y, 2) \ =& int_0^1 dx int_0^(1-x) (-1 / 8 + 1 / (2 (1+x+y)^2)) dy\ =& int_0^1 (-3 / 8 + x / 8 + 1 / (2(1+x))) dx = 1 / 2 ln 2 - 5 / 16 $ == P171 1(4) #prob[ 计算下列三重积分 $ iiintv sqrt(x^2+y^2) dx dy dz $ 其中 $V$ 是由曲面 $z^2=x^2+y^2$,$z=1$ 所围成的立体。 ] $ & iiintv sqrt(x^2+y^2) dx dy dz = 4 iiintb(V') sqrt(x^2 + y^2) dx dy dz = 4 iintb(D') sqrt(x^2 + y^2) dx dy int_sqrt(x^2+y^2)^1 dz\ =& 4 iintb(D') sqrt(x^2 + y^2) (1-sqrt(x^2+y^2)) dx dy = 4 int_0^(2 pi) int_0^1 r(1-r) r dif r dif theta = 4 int_0^(2 pi) 1 / 12 dif theta\ =& 4 dot (pi) / 6 = (2 pi) / 3 $ // = 习题9-4 // == P189 2 // #prob[ // 计算曲线 $x=3t, y=3t^2, z=2 t^3$ 从 $O(0,0,0)$ 到 $A(3,3,2)$ 一段弧长。 // ] // == P189 3(1) // #prob[ // 计算第一类曲面积分: // $ // iints (x+y+z) dif S // $ // 其中 $S$ 为曲面 $x^2+y^2+z^2=a^2,space z>=0$。 // ] // == P189 3(2) // #prob[ // 计算第一类曲面积分: // $ // iints (dif S)/((1+x+y)^2) // $ // 其中 $S$ 为四面体 $x+y+z<=1,x>=0,y>=0,z>=0$ 的边界。 // ] // == P189 3(3) // #prob[ // 计算第一类曲面积分: // $ // iints abs(x y z) dif S // $ // 其中 $S$ 为曲面 $z=x^2+y^2$ 被平面 $z=1$ 所割下的部分。 // ] // == P189 3(4) // #prob[ // 计算第一类曲面积分: // $ // iints (a x + b y + c z + d)^2 dif S // $ // 其中 $S$ 是球面 $x^2+y^2+z^2=R^2$。 // ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/035%20-%20Core%202019/003_Chronicle%20of%20Bolas%3A%20Things%20Unseen.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Chronicle of Bolas: Things Unseen", set_name: "Core 2019", story_date: datetime(day: 27, month: 06, year: 2018), author: "<NAME>", doc ) Naiva had grown up under the rule of Dragonlord Atarka. Her entire life she had watched her grandmother, Yasova, once known as Dragonclaw of the Temur clan, dutifully deliver meat to the gathering place at Ayagor so Atarka could feast. "To keep the people alive, we will feed the dragon," Grandmother said every year when a few of the elder hunters grumbled about losing the old ways. Yet every year, fewer recalled the days before the fall of the khans, and thus fewer complained, and of course to the young ones like Naiva, the rule of Atarka was all they had ever known. So when she stood trapped in a ring of boulders with Grandmother and Baishya on one side and on the other a handsome young wanderer who had brought a dragon's wrath down on them, she knew what Grandmother would do. The once-mighty Yasova Dragonclaw would give way to the Ojutai dragon broodling that loomed above them, demanding to kill the renegade warrior. It shouldn't be this way! As she sucked in a harsh breath, she wished she had fire as dragons had fire so she could scald the great beast and turn it to ash. She wished she could strike even if it meant her own death. Wasn't it better to fight than to give way again and again until your soul was crushed and you denied your own name? The dragon opened its maw as a warning to drive the rest of them back. Cold radiated from deep within its massive body, ready to freeze any creature that stood in its path. Grandmother caught Naiva's eye. Here it came: she would give the hand gesture to retreat; she would leave the stranger to meet his destiny, in death. Keeping her hand hidden from the aven on the rock, Grandmother gestured #emph[Kill] . As the dragon reared back its head to strike at Tae Jin, Baishya stretched out her arms toward the earth, a warm greenish light gathering in her hands and flowing into the soil. The dragon's stinging breath blasted toward Tae Jin. Impossibly, a boulder rolled sideways into the path of its breath. A thick crust made of the dragon's icy breath crackled around the rock, solidifying before it reached Tae Jin. An arrow flashed overhead to cut through one of the wings of the aven. As the aven staggered, croaking in pain, Naiva threw her spear. The obsidian point cut through the aven's handsome garment and straight into its feathered breast. Grandmother cast her own spear, and the weapon struck the aven's head for the death blow. The dragon roared, neck whipping from side to side as it raged. Tae Jin dodged between the boulders. A second stream of its icy breath blasted into the open ground where he'd just been standing. #figure(image("003_Chronicle of Bolas: Things Unseen/01.jpg", width: 100%), caption: [Icefall Regent | Art by: David Gaillet], supplement: none, numbering: none) Naiva leaped sideways to push Grandmother into a narrow gap between two boulders. Blades of grass froze and shattered at her heels. The backs of her legs went numb, but her felted trousers gave her some protection. Looking back, she saw Baishya on her knees, doubled over, exhausted and almost fainting from the effort of moving the rock. Fec shot a useless arrow toward the dragon that bounced off its scaly hide, but it didn't even look his way. It snaked its head down to smack into the boulder Baishya had moved and which she was now sheltered behind. Naiva plucked her skinning knife from its sheath and raced back to her twin, reaching her just as the dragon used a massive claw to shove the boulder aside as if it were the merest pebble. Its body looming above them filled all of her vision. She clasped Baishya to her. At least they would die as they had been born: together. A rumbling howl split the air. The Ojutai broodling reared back, twisting around as a red dragon crowned with antlers—the very same broodling who had been following them—swooped out of the sky and slammed into it. The two beasts went tumbling over the grass, grappling and clawing. The weight of their battle shook the ground. Fire met ice in a flurry of embers and glittering snowflakes. Naiva heaved Baishya to her feet. "Can you walk?" Baishya nodded, too breathless to speak. She leaned on Naiva, trembling, face pale. "I didn't know you could do that!" Naiva exclaimed. "I didn't either," Baishya whispered. Grandmother appeared. "Retreat to the trees. Tae Jin!" They raced toward the line of trees as the dragons rolled farther away. Naiva was grateful for the tall grass now since it hid them. The roars and screeches of the battling dragons covered the noise of their footsteps and their passage through the rustling grass. She had so many questions but no time to ask. With Baishya still leaning heavily on her, she stumbled in under the trees. Baishya let go and dropped to the ground, leaning against a trunk as she worked to catch her breath. By the pool, the hunters who'd stayed behind to fish had already thrown on their packs and made ready to move, having heard the commotion. A sentry crouched up in a tree called down: "It's flying off." Naiva halted to look back. The Ojutai dragon slipped out of the claws of the Atarka broodling and broke for the sky, but the broodling leaped up and caught one of its back legs with a powerful swipe of a foreclaw, dragging the other dragon back down to earth. She felt the impact of their conjoined bodies through the soles of her boots. Their shrieks and howls thundered, and yet the titanic nature of the battle invigorated her. What would it be like to have so much power surging through you? Was that what magic felt like for Baishya? Yet the power had drained her sister too, and her very life was endangered just because she possessed the shaman's gift. Naiva left her to hurry over to where the others waited in a tight group. The hunters stared at the young man, at the blood on his tunic and the shining tattoo on his exposed shoulder. Fec said, "We must turn back. Ojutai's broodling won't dare follow us deep into Dragonlord Atarka's territory." "Their battle is not yet over," said Grandmother. "Either way, we are exposed and vulnerable now that dragons are stalking us." "Dragons are always stalking us. I must consider the circumstances that brought us here. The vision of the windfolk. This young man's mission." She cast a look back toward the edge of the trees where Baishya sat cross-legged on the ground, back to them, both hands pressed into the dirt. "Give me silence to consider." <NAME> stood in repose, waiting for the elder to address him. Naiva sidled up beside him. "You almost died," she said in an undertone. Her own pulse was still racing as a hammering in her ears. "How can you be so calm?" He turned his dark gaze on her. "I will die one way or the other, whether now or later. Discipline teaches us to accept what cannot be escaped." "You would be dead if not for my grandmother's healing." "That is true. I have heard of the healing powers of your people, and I am thankful for her skill. But healing magic is known to all of the tribes." He paused, then said almost shyly, "The rock saved me. I have not seen such a display of earth magic before. May I know your name?" "That wasn't me. That was my twin, Baishya." Even among the tribe, people often mistook Naiva and her sister for each other. They'd played tricks with it when they were younger, pretending to be the other one. Yet under his scrutiny, it annoyed her that he thought she was someone else, someone whose power and skill he admired. But then he smiled. "Ah. You are the one who threw the spear with such accuracy and brought down the aven. May I know your name?" Heat burned in her cheeks, but she did not look away. She wanted him to acknowledge her, not just her twin. "I'm called Naiva." "Enough!" Grandmother thumped the butt of her spear on the dirt. "When a vision offered by the windfolk intersects with a wanderer bringing knowledge from the Jeskai, I cannot refuse such portents. We will go on to Ugin's grave." Naiva thought Fec would argue, but he merely bowed his head in acquiescence, as did the other hunters. The First Mother had spoken, so it was settled. By now the dragons had vanished from sight, although now and again a faint thunder marked the direction of their battle. The party moved at a brisk pace, keeping under the leafy cover. Should Atarka's broodling prove victorious and come to check on them, they still had the excuse that they were hunting, but they ignored all signs of game: a trampled area where a herd of wild krushok had come to drink; a broken mammoth tusk; saiga droppings. As always, the hunters walked without speaking; Mattak, Oiyan, Darka, Rakhan, Sorya, and Fec were Grandmother's most dependable companions, disciplined and skilled. Naiva fell into step beside Tae Jin. She wanted to ask him about himself, but it seemed so awkward to blurt out personal questions. Instead, hunting for a better opening, she recalled the most puzzling aspect of the story he'd been telling. "How can there be other worlds, as the old wise-woman in the story claims?" "The planes, do you mean? I asked my master the same question. He did not know." She looked back and saw Grandmother coming up behind them, closing the gap with her confident stride. "Grandmother, do you believe there are other worlds?" Grandmother gave her a thoughtful look. "Has your sister said nothing to you about planes? I thought she told you everything." Naiva's chest grew tight. "You've talked about such matters with Baishya and never with me?" she asked indignantly. "There is a great deal of secret knowledge a shaman must know that other people never learn." Without waiting for Naiva to reply, she turned to Tae Jin. "You did not finish Ugin's story. We have quite a distance to walk, and no dragons in sight for the moment. Tell me more about Ugin. And about Bolas." As she spoke the name #emph[Bolas] , her mouth settled into a grim line. She gave him an expectant look. The young man nodded obediently. By the pressure of his lips and the tightening of his eyes, Naiva could tell he was re-ordering his thoughts, retreating from the ordinary conversation he'd just had with her into his rote memorization of an ancient story. #figure(image("003_Chronicle of Bolas: Things Unseen/02.jpg", width: 100%), caption: [Student of Ojutai | Art by: <NAME>], supplement: none, numbering: none) They walked in silence beneath the whispering trees. Finally, he began to speak. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I didn't want to leave, but I had to follow. Something momentous had happened. It made me think of standing in a dry stream bed in a desert when a cloudburst darkens the distant hills. The floodwaters are coming even if you can't see them yet. Over the years of our wandering, Nicol and I had crossed much of the continent as we hunted and explored. The expanding realm of our brother Arcades dwelt far away from the mountain of our birth. I had to retrace our path, and yet the strangest and most challenging part was flying alone. There was no Nicol beside me to talk to, to hunt with, to nap beside during long drowsy afternoons when the sun heated the itch off our scales. Solitude is all very well as a discipline for enlightenment, but even in an Arcades' settlement, I had meditated in the company of the wise elder Te Ju Ki. Throughout all those days and weeks of silence I was still able to hear the sound of another living creature's breathing alongside mine. Not now. Now I trembled each night, hearing only my own mutters, my scuffling as I scratched a hollow for myself to sleep, the whisper of my heart's beating, the passage of air in and out of my lungs. But slowly as I flew and hunted my way back across the wide, wild land, I began to hear how all things breathe. Even plants breathe. Enfolded by the respiration of the world, no life is ever alone; each of us is embedded in a vast web, one entity among myriad myriads. Sometimes the denseness of this living web comforted me. Sometimes the sheer weight of living things crowded about me like an incessant thunder that never ceases. At those times, life's jangling and roaring troubled my spirit. Sometimes its clamor humbled me, for among these teeming multitudes, I was but a single creature whose existence could be rubbed out and forgotten in an instant. A sapling oak may be crushed by the steps of passing aurochs, and no one would be the wiser. A hatchling chick may fall from the nest and be lost in the grass as if it had never existed. Not that a dragon is so insignificant as an oak or a sparrow, or so I thought, not understanding then that even the smallest, briefest life has its place. That even a dragon's name may be swallowed by the passage of time and vanish into the abyss of oblivion. The world is wide, so I did not expect to catch up to my twin, much less run across him by happenstance as I tried to follow the route we had taken to get here. Because that route had ambled and meandered over so many years, while I must fly straight and fast in pursuit, I hoped only to discover him once I reached our birth mountain, for I was certain he was headed there. Thus, one day a rumbling noise startled me as I glided through a rugged patch of hills. Sad little outposts of humanity huddled behind log palisades. Fur-clad farmers labored with digging sticks and bronze-bladed machetes to clear ground for crops. A howl of laughter echoed down a long valley patched with rectilinear fields, framed by drystone walls to keep livestock away from growing grain. But low stone walls could not keep away the depredations of marauding dragons intent on amusing themselves with destruction. Although I had not seen them for years I recognized <NAME> and his siblings at once by their fierce red crests and their aggressive behavior. At first, I thought they were burning longhouses and thatched-roof granaries for cheap pleasure, but the destruction visited upon the hapless settlements was tangential to their main purpose. They were chasing a dragon. Their quarry dove and dipped into any crevice and valley offered by the rolling hills as he fled, trying to escape them. Of course, I knew his shape and coloring at once. "Nicol!" I cried. If he heard me, he gave no sign, merely disappeared over the rise of a hill and down behind the treeline. But my shout drew their attention to me. With a roar, the biggest one, <NAME>, came hurtling toward me. His outspread wings blotted out half the sky. His claws dripped with the blood of torn livestock. I could not outrace him. In that instant of realization I froze. An updraft curled under my wings, keeping me hovering aloft, otherwise I would have crashed to the ground as my vision hazed and my fire dwindled. Death frightened me after all; I had failed Te Ju Ki. The shame of my failure was a rock in my heart, a leaden lump dragging me to the dirt. Yet Nicol needed me. Whatever happened to me, I could not allow him to die. So, I reached into my tiny arsenal of magical tricks and spun a pair of transparent, feather-light globes out of the nexus of colors and into the air. With a huff, I blew them in the direction of Vaevictis. The shining orbs startled him so deeply that he tumbled, tail over head, trying to come to a halt. Frantically he called for his siblings, who were heedlessly burning up and down the valley as humans screamed and ran. #figure(image("003_Chronicle of Bolas: Things Unseen/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Of course, I sped after Nicol, although I chanced one glance over my shoulder just before the valley dropped out of sight. Spun on the wind, the globes wafted up against the dread dragon's gleaming scales and gently popped. His startled bellow of fear shattered the air. Then I flew behind a hill and could no longer see him. Relief shuddered through me. I had survived after all. Out of nowhere a large body brushed up against mine. My claws came out as I readied myself to swipe at the attacker. "That was a fine trick to play!" chortled Nicol. It took me a moment to recover my voice, stuck as it was like a bone in my throat. "Where did you come from?" I rasped out. "I saw you. Did you think I'd abandon you to be torn apart by our cousins? They're hateful creatures who haven't one brain to rub between the four of them. I hope that snarling bag of hot wind chokes on his rage." He laughed softly as we flew on. After a long time, once my heart had ceased its galloping measure, I laughed too, thinking of how ridiculous Vaevictis had looked as the shimmering globes harmlessly dissolved against the heat of his impervious scales. "What were those globes?" Nicol asked that night. We had halted to rest on a stony hilltop overlooking a forested plain. "They are a magic that <NAME> has been teaching me." I paused, trying to think of a way to explain what she had been teaching me about planes and worlds, but he merely snorted and talked over me. "Oh. That old human creature. Aren't you done with her yet?" "Why would I be done with her?" "She's human." "She's lived longer than we have. I think." "No human, however old, can ever be as wise as the youngest dragon, for we are born with the greatest dignity, intelligence, and power of all creatures." He leaned closer, his eyes gleaming with a disquieting light whose like I had never before seen in him. His tone teased me. "I learned something special. Do you want to know what it is?" I refused to say yes because I really did not care for his prideful, taunting manner. "Don't you want to know?" he demanded with a huff of flame directed at a blameless tree whose upper branches promptly caught fire and burned like one of the torches used to light human settlements at night. "I don't think I like the way you talk about humans. Some of them are foolish, it's true, and some are angry or greedy or selfish, but others are intelligent, wise, caring creatures. Although I grant you they are small and weak as individuals. Easily broken." "Yes, indeed, they are easily broken," he said with a rumble of derisive laughter. "What do you mean by that?" "You shall see. And I will reveal to you my special learning regardless, because we are twins and we should share everything. Do you know the great ocean whose waves break upon the land?" He leaned closer with a smug quirk of his fierce snout. "There are other lands that lie beyond it, and even more creatures who live in those other lands." "Yes, I know." A flash of ire lit in his eyes that I hadn't been amazed by his revelation. I had my pride, too. Maybe I hadn't been following around Arcades all this time, as he had, studying behavior and customs and laws and weapons, but everything that existed intrigued me. Thus, when I was not meditating and studying magic with Te Ju Ki, I observed all the details of life around the central town and the nearby settlements that had fallen under its sway, including two seaside ports. #figure(image("003_Chronicle of Bolas: Things Unseen/04.jpg", width: 100%), caption: [Hinterland Harbor | Art by: <NAME>], supplement: none, numbering: none) So, I said, "Some have built boats with sails for wings and have crossed the waters and returned to tell the tale. The idea of sails for wings is quite ingenious, don't you think?" "I am sure dragons have taught them everything they know, since there are dragons on those other lands too. Although I am sure those dragons are not really like us and our siblings. We are the first, after all, and thus the most powerful." "How do you know we are first? We've never seen those other lands and those other dragons. They might have fallen from our progenitor's wings before we did." "No, absolutely not." By which I understood him to mean: he didn't want to consider that might be true. Sometimes it just wasn't worth arguing with Nicol. Anyway, I was sleepy. The next day as we flew in fine weather and great spirits side by side with each other, I did not want to disturb our amity. Perhaps if I had delved more deeply, I would have had warning of what was to come. Even fast as we flew, intent on our goal, it took us days and days to retrace our journey. Our first hint that we had indeed reached our destination came in the presence of boulders cut with the rake of claws in a double-curved quarter circle. These were set within dragon-sight of each other at the edge of a wide plain on which grazed tumultuous herds of bison, antelope, water buffalo, horses, and red deer. "These are markers too big for humans to have made," I said. "I'm hungry," he answered. Working together, we easily killed four plump specimens and sent the rest speeding away. We had barely settled down to tear into our still-warm feast when a dragon's roar shattered our peaceful idyll. Palladia-Mors dove out of the sky, and we leaped back as she landed with a ground-shaking thump. "I thought you two were gone for good! This is my hunting territory now. All of it." Nicol watched her warily while I attempted to calm her. "We are just passing through on our way to the birth mountain." "You don't want to go there," she said as she clawed the four corpses out of our reach. "Why not?" "Too much trouble. Those humans have gotten above themselves and think they are dragon hunters." She sniffed carefully around the dead animals, blood smearing her muzzle, then gulped down an antelope with a crunch of teeth and a convulsive swallow. Swinging her gaze back to us, she growled with a rumble that shook my horns. She had a gift for puffing herself up to seem twice as large and ten times as fierce as she already was. I had to struggle not to back away from her, but I knew better than to give any sign of fear in front of a violent predator. "I'll kill their leaders when I feel like it, but not now. Now I'm going to eat this delicious banquet you've so conveniently hunted for me." Nicol looked ready to lunge at her and fight, but with a lash of my tail, I got his attention and lured him aside. "The two of us can take her together," he said. "We're bigger now, almost as big as she is." "Maybe, but is it worth the chance she'll injure or kill one of us? I thought we were going to the birth mountain." He blinked once and then a second time, more slowly, and for an instant, I thought his eyes turned in lazy circles that spun my thoughts around and around. Maybe it was time to confront one of our siblings directly~I shook myself free of the irritating distraction, clawing a gouge into the soil with impatience. Nothing fruitful would be served by clashing with the other dragons. The world was wide enough that we could easily live in harmony, even if it meant staying out of the way of those who guarded their territory with jealous fervor. "What did she mean by dragon hunters?" I asked. "Why is she avoiding the birth mountain?" "We'll soon find out." We flew on, getting hungrier because Palladia-Mors abandoned the three plump carcasses to follow us. There was absolutely no point in hunting as long as she stayed close enough to grab any new catch away from us as soon as we brought it down. But when the mountain appeared in the distance with its long smooth slopes and symmetrical shape, she turned back. Nicol kept an eye on her as she retreated, but I could not keep my gaze off the mountain. A thrill of sentiment agitated me. We had no parents as humans measured family. We had only a progenitor, unseen, never spoken to, from whose wing beats we had fallen like chaff shaken out of a sheaf of wheat. The mountain was just the unforeseen place where we had woken, a chance, a coincidence. Nevertheless, the peak called to me as if it had a voice made of invisible threads that drew me ever closer to its secret, molten heart. #figure(image("003_Chronicle of Bolas: Things Unseen/05.jpg", width: 100%), caption: [Mountain | Art by: <NAME>], supplement: none, numbering: none) The mountain had not changed, or so I thought as we drew closer. But the landscape around it had changed. In the time of our falling birth, a dense forest had stretched out in every direction around the mountain, cut here and there with random clearings made by an eruption of stony ground or the fall of a giant tree. Of course, the harsh memory of our sister's death in one such clearing remained as fresh as the hot blood of the beasts we'd killed earlier, whose meat had been stolen from us by our living sister. But now. Now, what a change met our astonished eyes! The forest was hacked through with crude roadways linking fortified settlements, each cluster of buildings ringed with a high palisade. Outside the walls, huts crowded up against the palisade like so many beggars reaching out their hands toward a bowl heaped with food. Inside the walls stood longhouses of a grander construction, each ringed by a fence decorated with strips of elaborately woven textiles and strings of small brass bells. With every gust of wind the air chimed. The gates of the settlement were twice the height of a man. They were carved with a stark, violent scene of human hunters stabbing their spears into the prone body of a dying dragon. But there was worse even than this. The largest longhouse rose at the center, elevated on an artificial mound of earth and ringed by a stone wall that, to my eye, seemed to protect it from the other longhouses. Atop its gate, bound to a massive pillar, leered the skull of a dragon. The pathway leading from the gate to the entrance into the great longhouse ran beneath arches made by a dragon's ribs lashed to poles. Nicol hissed with a long, low, furious sound. "They have turned our sister into an ornament!" I was too shocked to speak. Although we flew high overhead, horns greeted our arrival. Armed people ran to the wall walk. More raced to place huge iron bolts in the belly of bolt throwers that looked like massive, grounded crossbows. Faster than I realized was possible, several of these bolts were launched on a deadly arc toward us. Although Nicol twisted out of their way, my left rear claw was cut by a glancing blow. The scratch was not much, but some nasty substance had been smeared on the point and its venom scalded my flesh. My bellow of pain shook the heavens. Five drops of my blood fell from the shallow cut, plummeting earthward, each drop as big as a human fist. People pushed and shoved, tearing and hitting as they fought to get beneath the falling blood. Two people tilted back their heads and were hit square on the face with a splash of my blood. One sank to the ground as in prayer, hands clasped at her chest, and those who had not reached the blood in time prostrated themselves around her. The other howled with glee, arms raised triumphantly as he shook spear and knife toward the sky in defiance, or as thanks for a heavenly portent. The scuffle had so roiled the crowd that the last three drops splatted on the soil. People dropped to their knees to shove blood-stained dirt into their mouths. It was an appalling scene, but we could not tarry. "Ugin!" Nicol shouted. "Come. Come!" A second round of bolts thumped out of the ballistae, headed for us. I flew as fast as ever I could to get out of reach. My claw throbbed with a malicious agony. Numbness crept up my leg. "I have to land, Nicol." "No! Keep flying." I didn't have the strength to argue. Through my haze of pain, I spied more settlements hacked out of the forest. Even the smallest settlement had at least one ballista to guard it. Those who lived inside the palisades bore iron-bladed weapons, while those who lived in the huts outside toiled in rocky fields with stone tools under the lash of cruel overseers. The gates of most of the palisades were adorned with the skulls of bears and giant wolves, while some bore sculptures meant to look like dragons which had been wired together out of human skulls in a ghastly mockery of a dragon's noble lineaments. In four other settlements, a true dragon's skull ornamented the chief's house. Notably, these settlements lay most distant from the first one, like the points of a pentagram. Even in pain, I noticed such details. At length, Nicol took pity on my wretched state and circled back to the peak of the birth mountain. There, flagging, spent, and weary beyond measure, I landed on the bare rock of the crater's high rim. If dragons could weep I would have wept. "Over here." Nicol led me to the north-facing shadow where last year's snowpack still lingered. I stuck my foot into the snow, breaking through its crust into the icy pack beneath. The relief of its biting cold soothed my stinging flesh. I dropped my head to the ground, panting softly as the pain eased. Nicol perched at the highest point of the crater, surveying the landscape. "They'll climb up after us," he said as if welcoming the confrontation. "Is this peak not too high to be climbed by frail humans?" It seemed impossible to fly just yet. I wanted to close my eyes and sleep, but I dared not. After so long living amid the order and peace of Arcades' rule, I could not quite grasp how different this place was. "They are not as frail as you think them," said Nicol. "Greed is not frail. Ambition is not frail. Their weapons can kill us because they are clever. Because they work together, as they did when they killed our sister. They will come after us because we are dragons. They want to seize our power for themselves." "Then we should go away at once. If that bolt had cut deeper, its poison might have killed me! No wonder Palladia-Mors avoids this terrible place." "Oh no, Ugin. You're not afraid of these people, are you?" Rather than reply, I licked my wounded foot, sucking out sour-tasting blood and spitting it onto the ground. He spread his wings as if in challenge to any humans staring up at the mountain from far below our exalted height. "We have come here to avenge our sister, and avenge her we will." "I won't act like Vaevictis and his siblings, slaughtering innocent creatures with indiscriminate lust!" "You won't have to kill anyone at all, brother. That I promise you. I have a plan, a very cunning plan, because I have taught myself to do something no one else can do." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "That's enough for now, <NAME>." Grandmother called a halt as the late afternoon shadows pulled long across the land. Her own face fell into shadow; something he'd said in his story troubled her, Naiva could tell, but she didn't know how to ask or if Grandmother would reveal her concerns. He bowed his head obediently. They had reached Grandmother's chosen destination: a jumble of boulders where hunting parties patrolling the borders of Atarka territory often camped. Overhangs in the rocks had been deepened to offer shelter from wind and rain and cover from the gaze of flying creatures. There was even a hearth cunningly crafted into a hollow stone-built chamber disguised amid the other boulders; many small cracks and holes channeled the smoke slowly and invisibly into the air. Beyond the boulders, the river broke over a series of descending shelf-like terraces in a churning foam whose constant chatter also provided a form of concealment. "We'll light no fire, lest the dragons find us by its heat and smell," Grandmother added. Of course, the lack of a fire was no hardship for hunters. Their gear protected them from the cold, and they carried provisions. Assigned to sentry duty, Naiva took a strip of dried meat and made her way to the edge of the trees, still brooding over the revelation about worlds. But really it was more about Baishya receiving secret training. Of course whisperers lived in constant danger from Atarka. Of course it made sense that shamans shared their knowledge only with others like themselves. But that sense of being left behind still rankled. #figure(image("003_Chronicle of Bolas: Things Unseen/06.jpg", width: 100%), caption: [Whisperer of the Wilds | Art by: <NAME>], supplement: none, numbering: none) She climbed up on one of the outermost rocks, tucking herself against it to become part of the boulder. At least she had this world and its beauty and challenges. The vantage gave her an excellent view to the northwest across a flat expanse of tundra sweeping toward the eastern range of the Qal Sisma. Where the tundra broke against the foothills, a vast chasm split the land. The deep canyon and its shattered rock was too far away to see clearly, drowned by the shadows of encroaching twilight, but a faint blueish haze drifted above the chasm as a person's breath on a cold morning clouds the icy air. Footfalls scuffed the rock. Tae Jin climbed up beside her and settled into a crouch. "That's where we are going," Naiva said. "Ugin's grave. A few days' walk away." "Have you been there before?" "Yes. Once. When we were twelve." "We?" "Hey!" Baishya called softly from below, then scrambled up. The sun caught on her face just as she reached the top, giving her features a glow that Naiva envied. She smiled winningly at Tae Jin, which annoyed Naiva even more because of how simple such exchanges seemed for Baishya while Naiva struggled with her own surging, complicated desires. "Me and Baishya, I mean, and some other children Grandmother had her eye on." "What did the wise Yasova have her eye on?" He hadn't looked at either of them, only toward the chasm and the way the light changed above it as the sun set. It almost seemed someone had lit a blue fire far down below, visible as shifting traceries of gleaming mist drifting at the rim of the chasm. Baishya tapped her on the arm in warning. "That's tribe business, Nai." Annoyed by the rebuke, still indignant over what Grandmother had mentioned, Naiva went on recklessly. "Atarka hates magic. She fears it. Grandmother thought if she could learn early which children are likely to become whisperers, she could better hide them from Atarka's wrath. She thought maybe if they slept close to Ugin's grave, the Spirit Dragon's ancestral presence might awaken their magic early. Then she could prepare them to conceal their power from Atarka or to go away into the mountains to hide." "Nai! It's not for outsiders to know our secrets." "So I am given to understand!" she said curtly before turning her attention to <NAME>, who watched the exchange with cautious interest. "Ugin is dead. There've been no dreams or portents." "Not until now," broke in Baishya. "The windfolk brought me a vision. And it sounds as if your master had a vision from Ugin too. Is that right?" He nodded with the greatest seriousness. "That is what my master believes. The tempests that birth dragons have increased in strength since Ugin's death. He believes this means some essence of the Spirit Dragon still endures, and has found the strength to reach out. That's why he sent me—" Naiva elbowed him to silence. Being close to him was almost overwhelming—his lips, his eyes, the common youthful feelings of interest and desire—but that didn't mean she stopped scanning the sky and the land for threat. The clouds to the west had started to pile up as with an incoming storm. "There," she said just as a whistle sounded from Mattak, who was on sentry duty. A strange, disjointed shadow approached through the dusk, headed straight for them. Its flight was weirdly slow and clumsy. They had time to scramble down from the boulder before the shape loomed close, resolving into its true nature: the Atarka broodling was carrying the limp body of the Ojutai dragon in its claws. It skimmed down toward their hiding place and dropped the carcass just beyond the boulders. The impact shuddered through the ground, doubled as the broodling hit hard beside it, and with a fiery blast, set flame burning along the dry grass. Blood dripped from claw marks sunk deep into its flanks from the battle. It was already badly injured, engorged with pain. "Come out! My cousin tells me truth before she dies. Traitor! Dragon killer!" Smelling them, it leaped in among the boulders. Baishya shouted a warning meant to carry back to the other hunters, but they couldn't possibly reach them in time. "Down!" <NAME> lunged past her, dodging around the dragon's massive forelegs as they slammed down onto the dirt. Naiva shoved Baishya hard behind one rock, then dropped and rolled into the cover of the adjacent boulder. The broodling's fire breath scalded the grass on which they'd been standing. Flames licked at Naiva's feet as she flipped her spear around and peered out. Tae Jin had leaped away from its lashing tail. The trailing slash of one of its rear legs caught him on the shoulder, and he reeled backward. Its howl fell like a clap of thunder. "I kill you!" Naiva jumped out into the open and shouted gibberish to draw its gaze. As the dragon hissed in surprise at her sudden appearance, Tae Jin clapped his forearms together. A glimmer of misty-like frost shuddered in his palms. With a hiss of powerful magic, the white sparks elongated to become a long ghostly blade that shimmered, bright yet without physical substance, its glowing hilt held in his hands. He darted under its head and, incredibly, slashed open its scaled belly with a powerful stroke of the insubstantial blade. His quickness in ducking aside saved him from the gush of innards that spilled onto the ground in a slimy, stinking mess. The creature crashed forward, hissing as its head slapped down onto the earth. Tae Jin spun backward to avoid being crushed, stumbled, and fell hard. Yet the dragon still had life in it. It lurched forward, snapping at him. Both Grandmother and Fec shouted at it, charging in from either side to stab at its neck, trying to draw it off. Baishya called up her magic again, sliding a huge rock sideways until it wedged up against the broodling's shoulder, trapping it. Uninjured, it could have shaken off the burden, but its struggles were weakening. #figure(image("003_Chronicle of Bolas: Things Unseen/07.jpg", width: 100%), caption: [Herdchaser Dragon | Art by: <NAME>], supplement: none, numbering: none) Naiva thrust the obsidian point of her spear into the dragon's unblinking eye, the sharp stone slicing the hard outer surface and sliding deep through the silvery orb into the soft brain beneath. The beast shuddered and with a last gasp coughed up glowing embers. She yanked her spear free. The embers faded, settled to earth, and died. Wind spilled across her face, pouring the hot, honey smell of dragon's blood into her nostrils. To kill a dragon was a crime. Yet she exalted, for she hadn't hesitated. Like a true hunter, she hadn't quailed before the attack. Dragons were more powerful than humans, but they could be killed. Yet what was the ghostly sword that had torn its belly open? Was <NAME> dead? She cautiously walked around the bulk of the corpse with its whiff of sulphur and honey. Tae Jin lay on his back, face slack, eyes closed, but still breathing. Fresh blood was splashed across his tunic. The fabric had been sliced at the right shoulder, a flap hanging down. The ripped cloth exposed the honed musculature and, cut across it, a shining mark like the rake of a twinned dragon claw that had slashed across his shoulder and down his chest. She'd never seen such a mark before, so striking and beautiful. Kneeling, she touched his face lightly. His eyes opened. Seeing her, he blinked once, and then twice as if making sure she wasn't doubled. "You are very brave," he said. She flushed, so pleased by the praise she couldn't answer. But when he smiled, she found her voice after all. "It's dead. We killed it. What was that weapon you used?" "You've lied to us, <NAME>." Grandmother's harsh voice interrupted as the rest of the party crowded up in a bristling of spears to stare at the dead dragons and the young wanderer. "You wear the dragon mark of a ghostfire warrior. <NAME> made a bargain that all the ghostfire warriors would die in exchange for the rest of the Jeskai people being allowed to live. So tell me: how is it that you even exist?"
https://github.com/chubetho/Bachelor_Thesis
https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/chapters/background.typ
typst
= Background This chapter establishes the foundational concepts by first exploring monolithic architecture, the traditional approach to software design. The discussion then moves to the rise of microservices architecture, a significant paradigm shift in backend development that has significantly influenced modern software design. This exploration is extended to the frontend, where similar principles have been adopted. Finally, the chapter introduces the concept of Domain-Driven Design, with a particular focus on its application within the micro frontend architecture. == Monolithic Architecture <NAME> defines a monolith as a deployment unit in which all system functionalities are deployed together. The most common forms of monolithic architectures are the single-process monolith, the modular monolith, and the distributed monolith @newman_BuildingMicroservices2nd_2021. The single-process monolith represents the most traditional form of monolithic architecture, where all code and functionalities are encapsulated within a single process. In contrast, a modular monolith introduces a level of separation within this single process by dividing it into distinct modules. These modules can be developed independently, thus enabling parallel development efforts. However, they must ultimately be integrated for deployment, which retains the monolithic nature of the application. The distributed monolith, while involving multiple services that can be developed and distributed independently, still requires these services to be deployed together as a unified whole. This need for simultaneous deployment ties the architecture back to monolithic principles, despite the distributed nature of the services. <NAME> further underscores the simplicity of monolithic architectures @james_Microservices_2014. Because everything runs in a single process, the development, testing, and deployment processes are more straightforward. Developers can run the entire application on their local machines, allowing for thorough testing and ensuring seamless functioning of all components. Additionally, the deployment process itself is simplified, as the entire application is packaged and deployed as a single unit. However, as applications grow in size and complexity, the limitations of a monolithic architecture become more clear. Even small changes require the entire application to be rebuilt and redeployed, which introduces inefficiencies. The close coupling of components not only slows down the development process but also complicates the updating of individual modules. Over time, maintaining a well-organized and clean codebase becomes increasingly challenging, leading to a structure that is difficult to manage. This growing complexity negatively impacts the system's reliability and maintainability. Moreover, scaling a monolithic application poses significant challenges. Because the entire application exists as a single unit, scaling necessitates replicating the entire system, even when only a small part of it is needed to scale (illustrated in @figure_scale_monolith_microservice). This approach results in resource inefficiencies and increased costs. In contrast, transitioning to a microservices architecture provides a more flexible and scalable solution for developing complex applications, enabling the scaling of individual components rather than the entire system. Monolithic architecture can still be a practical and viable option, particularly for smaller organizations or those that do not encounter significant scalability challenges @james_Microservices_2014 @newman_BuildingMicroservices2nd_2021. #figure( image("/assets/scale_monolith_microservice.png"), caption: [Comparison between the scalability in monolithic and microservices architecture @james_Microservices_2014.], ) <figure_scale_monolith_microservice> == Microservices Architecture <section_microservices> Microservices architecture is an advanced design approach where independent services are developed around specific business requirements. Each microservice is responsible for a particular functionality, enabling the creation of complex systems through the integration of modular components @newman_BuildingMicroservices2nd_2021. From an external viewpoint, microservices operate as black boxes, delivering business functionality via network endpoints, such as REST APIs. The internal workings of these services are minimally exposed, ensuring that upstream consumers, whether other microservices or external programs remain unaffected as long as the interfaces remain consistent. The concept of microservices has been an important subject of research and development for over a decade. <NAME> identified five key principles that are crucial for understanding the effectiveness of this architectural approach. These principles include independent deployability, designing services around business domains, each service owning its state, and ensuring that the architecture aligns with the organizational structure. Independent deployability is a core principle of microservices architecture, allowing developers to modify, deploy, and release changes to a microservice without affecting others. Achieving this requires that microservices be loosely coupled, guaranteeing that updates to one service do not necessitate changes in others. This is accomplished by establishing explicit, well-defined, and stable contracts between services. Building on the idea of independent deployability, modeling microservices around business domains rather than technical layers can further enhance these benefits. @ddd provides a framework for structuring services to mirror real-world domains, thereby simplifying the introduction of new features and functionalities. When services are aligned with business domains, changes usually involve fewer services, which reduces the complexity and cost of updates. The principles of @ddd encourage designing systems that remain flexible and adaptable as business needs change over time. Another key concept is that each microservice should maintain ownership of its state, interacting with other services only when necessary to obtain data. This separation allows services to manage what data is shared and what remains hidden. By maintaining clear boundaries between internal implementation details and external contracts, this approach minimizes backward-incompatible changes and reduces the potential ripple effects of updates across the system. Furthermore, aligning the architecture with the organizational structure is essential for the success of microservices. While traditional architectures often mirror the communication patterns within an organization @conway_HOWCOMMITTEESINVENT_1968, a microservices architecture benefits from structuring teams around business domains. This promotes end-to-end ownership of specific functionalities. With this alignment, teams take full responsibility for their services, from development to production, leading to faster and more efficient development processes. == Micro Frontend Architecture The concept of micro frontends was first introduced in the ThoughtWorks Technology Radar at the end of 2016, demonstrating how the benefits achieved from microservices in backend development can also be applied to the frontend @_MicroFrontendsTechnology_. #figure( image("/assets/mono_ms_mfe.png"), caption: [A monolithic application is transformed into one composed of microservices and micro frontends.], ) <figure_mono_ms_mfe> The five key concepts of microservices, as they relate to micro frontends, will also be explored in this discussion. An online shop with different sections, each developed by separate teams, will serve as a practical example to provide greater clarity. Independent deployability allows each section of the frontend to be developed, tested, and deployed independently of other sections. For example, if the team managing the product detail section needs to introduce a new feature or resolve a bug, they can deploy their changes without affecting the checkout or product recommendation sections. Micro frontends should also mirror the structure of business domains. Building on concepts of @ddd, each micro frontend corresponds to a specific business function, such as a shopping cart, product catalog, or user authentication. This alignment ensures that changes to business logic are contained within a single micro frontend, simplifying updates and making the system more adaptable to evolving business requirements. Managing its own state within a micro frontend offers several benefits. It helps maintain loose coupling between different parts of the application. For instance, the shopping cart micro frontend exclusively manages what customers add to their cart, while the product catalog micro frontend controls the display of products. This approach simplifies data flow and makes debugging and testing more straightforward, as each micro frontend has clear boundaries for managing its data. The final key concept is that teams in a micro frontend architecture are organized around business domains, with each team taking full responsibility for the development of their respective micro frontend. This organizational structure minimizes the need for inter-team coordination and enhances the speed of decision-making processes without waiting for input or approval from other teams. // However, it is important to note that microservices and micro frontend architectures may not be suitable for all types of backend and frontend applications due to the additional complexity they introduce at both technical and organizational levels. However, these approaches are particularly beneficial in scenarios where multiple teams must collaborate on the same application or when there is a need to gradually replace an existing legacy system. == Domain-Driven Design <section_ddd> Domain-Driven Design (DDD) focuses on the division of a large system into smaller, more manageable services. Introduced by <NAME> in 2003, @ddd provides a structured approach to software development that closely aligns with business goals @eric_DomainDrivenDesignTackling_2003. Although @ddd introduces a wide range of concepts, this summary will concentrate on a few key elements: domain, subdomain, bounded context, and context mapping. These concepts are illustrated through the example of an online shopping application, as shown in @figure_ddd. The application is structured around four main domains, each containing its subdomains and two bounded contexts. The domain represents the specific area of knowledge or activity that a software application is designed to address, including all relevant business logic and rules. In the given example, the domains are order, product, user, and payment. A subdomain is a smaller, specific part within a domain, categorized into three types: core subdomain, supporting subdomain, and generic subdomain. The core subdomain, which is supported by necessary supporting domains, represents the most important part of the business, delivering its unique value and therefore demanding the highest level of attention and custom development. The generic subdomain, on the other hand, is applicable across multiple domains. In the given example, the product detail subdomain supports order processing, which functions as the core subdomain. Additionally, the user authentication subdomain serves as a generic component, designed to be universally used across the application to identify customers. A bounded context is a defined boundary that separates subdomains within a specific portion of the domain. Within each bounded context, a unique ubiquitous language is used, which may differ from the languages employed in other contexts. In the example, there are two bounded contexts, both containing a subdomain named "detail," but with distinct purposes: one is used for displaying order details, while the other is for displaying product details. Despite these distinctions, relationships can exist between bounded contexts, such as when the order domain requires information from the product domain to process an order. These relationships and interactions between different bounded contexts are referred to as context mapping. Understanding these concepts is essential for applying @ddd to micro frontends. Further details on how these concepts are implemented in micro frontends will be discussed in @section_decision_framework. #figure( image("/assets/ddd.png", width: 90%), caption: [Domain-Driven Design structure of an online shopping application.], ) <figure_ddd> #pagebreak(weak: true)
https://github.com/MobtgZhang/sues-thesis-typst-bachelor
https://raw.githubusercontent.com/MobtgZhang/sues-thesis-typst-bachelor/main/paper.typ
typst
MIT License
#import "thesis.typ" as thesis #show: doc => thesis.sues_thesis_bachelor( blind: false, doc ) // 封面 #include "chapters/cover.typ" // 插入目录 #locate(loc => { thesis.chineseoutline( title: "目录", depth: 3, indent: true, ) }) #pagebreak() // 文章章节内容 #include "chapters/ch01.typ" #include "chapters/ch02.typ" #include "chapters/ch03.typ" #include "chapters/ch04.typ" #include "chapters/ch05.typ" // 附录部分 #include "chapters/appendix.typ" // 致谢部分 #include "chapters/thanks.typ"
https://github.com/Area-53-Robotics/Unofficial-Old-53E-NB
https://raw.githubusercontent.com/Area-53-Robotics/Unofficial-Old-53E-NB/main/entries/entries.typ
typst
#include "../frontmatter.typ" #include "../appendix.typ" #include "./post_reveal_entry.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rubber-article/0.1.0/README.md
markdown
Apache License 2.0
# The `rubber-article` Package <div align="center">Version 0.1.0</div> This template is a intended as a starting point for creating documents, which should have the classic LaTeX Article look. ## Getting Started These instructions will get you a copy of the project up and running on the typst web app. Perhaps a short code example on importing the package and a very simple teaser usage. ```typ #import "@preview/rubber-article:0.1.0": * #show: article.with() #maketitle( title: "The Title of the Paper", authors: ( "<NAME>", ), date: "September 1970", ) ``` ## Further Functionality The template provides a few more functions to customize the document. ```typ #show article.with( lang:"de", eq-numbering:none, text-size:10pt, page-numbering: "1", page-numbering-align: center, heading-numbering: "1.1 ", ) ```
https://github.com/metamuffin/typst
https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/text/baseline.typ
typst
Apache License 2.0
// Test baseline handling. --- Hi #text(1.5em)[You], #text(0.75em)[how are you?] Our cockatoo was one of the #text(baseline: -0.2em)[#box(circle(radius: 2pt)) first] #text(baseline: 0.2em)[birds #box(circle(radius: 2pt))] that ever learned to mimic a human voice. --- Hey #box(baseline: 40%, image("/tiger.jpg", width: 1.5cm)) there!
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/examples/exam-sugar-notation.typ
typst
MIT License
#import "../src/lib.typ": * #show: g-exam.with() #g-question(points:.2)[Question] #g-subquestion(points:.2)[sub 3] = Title =? Question 1 =? 2.2 Question 2 =? 2 Question 6 ==? Subquestion 3 ==? 1.3 Subquestion 3 =% Clarification of question ==? 1 Subquestion 4 =! Solution is this. =? .2 Question 33 =? Solve this ecuation $x^2 -4x +4 = 0$ #g-question(points:.2)[ Solve this equation $x^2 -4x +4 = 0$ ] =! Solution of the question. =? 2.4 $x^2 -4x +4 = 0$ ==? 2.4 $x^2 -4x +4 = 0$
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying/0.1.0/examples/example.typ
typst
Apache License 2.0
#import "../lib.typ": s, pause, utils, states, pdfpc, themes #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: [Custom footer]) #let s = (s.methods.enable-transparent-cover)(self: s) #let s = (s.methods.append-preamble)(self: s, pdfpc.config( duration-minutes: 30, start-time: datetime(hour: 14, minute: 10, second: 0), end-time: datetime(hour: 14, minute: 40, second: 0), last-minutes: 5, note-font-size: 12, disable-markdown: false, default-transition: ( type: "push", duration-seconds: 2, angle: ltr, alignment: "vertical", direction: "inward", ), )) // #let s = (s.methods.enable-handout-mode)(self: s) #let (init, slide, touying-outline) = utils.methods(s) #show: init // simple animations #slide[ a simple #pause dynamic #pause slide. ][ second #pause pause. ] // complex animations #slide(setting: body => { set text(fill: blue) body }, repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) in subslide #self.subslide test #uncover("2-")[uncover] function test #only("2-")[only] function #pause and paused text. ]) // multiple pages for one slide #slide[ #lorem(200) test multiple pages ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.methods(s) #slide[ appendix ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-07C0.typ
typst
Apache License 2.0
#let data = ( ("NKO DIGIT ZERO", "Nd", 0), ("NKO DIGIT ONE", "Nd", 0), ("NKO DIGIT TWO", "Nd", 0), ("NKO DIGIT THREE", "Nd", 0), ("NKO DIGIT FOUR", "Nd", 0), ("NKO DIGIT FIVE", "Nd", 0), ("NKO DIGIT SIX", "Nd", 0), ("NKO DIGIT SEVEN", "Nd", 0), ("NKO DIGIT EIGHT", "Nd", 0), ("NKO DIGIT NINE", "Nd", 0), ("NKO LETTER A", "Lo", 0), ("NKO LETTER EE", "Lo", 0), ("NKO LETTER I", "Lo", 0), ("NKO LETTER E", "Lo", 0), ("NKO LETTER U", "Lo", 0), ("NKO LETTER OO", "Lo", 0), ("NKO LETTER O", "Lo", 0), ("NKO LETTER DAGBASINNA", "Lo", 0), ("NKO LETTER N", "Lo", 0), ("NKO LETTER BA", "Lo", 0), ("NKO LETTER PA", "Lo", 0), ("NKO LETTER TA", "Lo", 0), ("NKO LETTER JA", "Lo", 0), ("NKO LETTER CHA", "Lo", 0), ("NKO LETTER DA", "Lo", 0), ("NKO LETTER RA", "Lo", 0), ("NKO LETTER RRA", "Lo", 0), ("NKO LETTER SA", "Lo", 0), ("NKO LETTER GBA", "Lo", 0), ("NKO LETTER FA", "Lo", 0), ("NKO LETTER KA", "Lo", 0), ("NKO LETTER LA", "Lo", 0), ("NKO LETTER NA WOLOSO", "Lo", 0), ("NKO LETTER MA", "Lo", 0), ("NKO LETTER NYA", "Lo", 0), ("NKO LETTER NA", "Lo", 0), ("NKO LETTER HA", "Lo", 0), ("NKO LETTER WA", "Lo", 0), ("NKO LETTER YA", "Lo", 0), ("NKO LETTER NYA WOLOSO", "Lo", 0), ("NKO LETTER JONA JA", "Lo", 0), ("NKO LETTER JONA CHA", "Lo", 0), ("NKO LETTER JONA RA", "Lo", 0), ("NKO COMBINING SHORT HIGH TONE", "Mn", 230), ("NKO COMBINING SHORT LOW TONE", "Mn", 230), ("NKO COMBINING SHORT RISING TONE", "Mn", 230), ("NKO COMBINING LONG DESCENDING TONE", "Mn", 230), ("NKO COMBINING LONG HIGH TONE", "Mn", 230), ("NKO COMBINING LONG LOW TONE", "Mn", 230), ("NKO COMBINING LONG RISING TONE", "Mn", 230), ("NKO COMBINING NASALIZATION MARK", "Mn", 220), ("NKO COMBINING DOUBLE DOT ABOVE", "Mn", 230), ("NKO HIGH TONE APOSTROPHE", "Lm", 0), ("NKO LOW TONE APOSTROPHE", "Lm", 0), ("NKO SYMBOL OO DENNEN", "So", 0), ("NKO SYMBOL GBAKURUNEN", "Po", 0), ("NKO COMMA", "Po", 0), ("NKO EXCLAMATION MARK", "Po", 0), ("NKO LAJANYALAN", "Lm", 0), (), (), ("NKO DANTAYALAN", "Mn", 220), ("NKO DOROME SIGN", "Sc", 0), ("NKO TAMAN SIGN", "Sc", 0), )
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas7/2_Utorok.typ
typst
#let V = ( "HV": ( ("","<NAME> Júda","Vladýko i Bóže vseščédryj, ímiže vísi suďbámi, dážď mí v sérdci tvój strách imíti, dážď mí hnušátisja ďijánij lukávaho, dážď mí ľubíti ťá ot vsejá duší mojejá, i tvoríti vóľu tvojú spasíteľnuju. tý bo jesí Bóh náš, rekíj: prosíte, i priímete."), ("","","Bých úbo bisóm smích, čelovíkom že uničižénije, právednym rydánije, i ánhelom pláč, skvérna vozdúchu, i zemlí i vodám: ťílo bo okaľách, dúšu i úm oskverních bezčíslennymi ďijáňmi, i vráh Bóžij bých. uvý mňí Hóspodi! Sohriších tí, sohriších, prostí mja."), ("","","Moľúsja tí, o mňí neplódňim dolhoterpí Vladýko: i ne posicý mené jáko neplódnoje drévo posičénijem smértnym, vo óhň otsylája, no plodonósna mjá sotvoríti umolén búdi, vrémja pokajánija mí dajá jáko čelovikoľúbec: jáko da otmýju Spáse mój Christé, mojá mnóhi hrichí."), ("","","V pustýni živýj neporóčno žitijé, hrichámi opusťívšij úm mój obnoví, predtéče."), ("","","Hórlicu ťá proróče, krasňíjšuju razumívše slávim, provozviščájušču súščym v míri božéstvennuju vésnu."), ("","","Predstáteľu životá mojehó, dúši mojejá chraníteľu, božéstvennyj predtéče, ot čelovíčeska jazýka ľstíva izbávi mjá rabá tvojehó."), ("Bohoródičen","","V mjatéži oburevájema mjá ľínosti, v pristánišče blahoutíšnoje spasénija naprávi Vladýčice."), ), "S": ( ("","","Jáko blúdnyj sýn prijidóch áz ščédre, prijimí mja pripádajuščaho, jáko jedínaho ot najémnik tvojích Bóže, i pomíluj mjá čelovikoľúbče."), ("","","Jáko vpadýj v razbójniki i ujázvlen, táko i áz vpadóch ot mnóhich hrichóv, i ujázvlena mí jésť dušá: k komú pribíhnu povínnyj áz, tókmo k tebí blahoutróbnomu dušám vračú? Izléj na mjá Bóže, velíkuju tvojú mílosť."), ("Múčeničen","","Svjatíji múčenicy íže dóbri stradávše i vinčávšesja, molítesja ko Hóspodu, spastísja dušám nášym."), ("Bohoródičen","","Rádujsja sólnca óblače mýslennaho i neizrečénnaho Vladýčice: rádujsja vsesvítlaja sviščé: rádujsja svíščniče vsezlatýj: tobóju presvjatája, Jéva izbávisja ot kľátvy. no jáko imúšči derznovénije ko blahopremínnomu Sýnu tvojemú i Bóhu, máterneju tvojéju molítvoju, ne oskuďíj molítisja prečístaja."), ), ) #let P = ( "1": ( ("","","Sokrušívšemu bráni mýšceju svojéju, i vsádniki tristáty pohruzívšemu, pojím jemú, jáko izbáviteľu nášemu Bóhu, jáko proslávisja."), ("","","Ťá vinóvnu nášeho spasénija, i božéstvennaho izbavlénija mólim prečístaja: molísja jéže spastísja nám."), ("","","Vés jésm v ľútych napástech, v bidách i prehrišénijich, vopijú ti prečístaja: spasí mja rabá tvojehó."), ("","","Ťá Ďívu čístuju mólim, i Máter ziždíteľa: ot vsjákaho ozloblénija bisóv izbávi nás."), ("","","Jáže Slóvo plótiju róždši páče slóva, načáľnika žízni Christá Bóha nášeho, molí spastísja nám."), ), "3": ( ("","","Utverdísja víroju Christóva cérkov, íbo neprestánno písňmi vopijét pojúšči: svját jesí Hóspodi, i ťá pojét dúch mój."), ("","","Vsepáhubnyja zlóby šéstvovav stezjú, ne obritóch putí spasénija mojehó: k nemúže mjá tý nastávi preneporóčnaja Vladýčice."), ("","","Kríposť, i utverždénije, i pómošč, i nadéždu ťá jedínu napisúju vseneporóčnaja: tý mi búdi zastúpnica v déň ischóda."), ("","","Vsehdá ťa preneporóčnaja, moľú: v čás smérti mojejá predstáni, i múki izbávi rabá tvojehó."), ("","","Rodílsja jesí ot Ďívy neskazánno, javílsja jesí, jákože izvólil jesí Spáse náš, i mír obnovíl jesí Hóspodi."), ), "4": ( ("","","Uslýšach slúch tvój, i ubojáchsja, razumích ďilá tvojá i užasóchsja Hóspodi."), ("","","Poveľínija mojehó Vladýki prestúpľ, vrahóm javíchsja udób oderžím: tý mja izbávi Vladýčice."), ("","","V čás smérti izbávi prečístaja, i spasí dúšu mojú strástnuju ot bisóv."), ("","","Razriší prečístaja Vladýčice, soúzy prehrišénij mojích, i k životú víčnomu búdi mí chodátaica molítvami tvojími."), ("","","Vospivájem ťá po roždeství páki Ďívu, i proslavľájem ťá prečístaja, jáko Máter Bóha nášeho."), ), "5": ( ("","","Útreňujušče Slóve, v slávu tvojú i chvalú, voschvaľájem neprestánno óbraz krestá tvojehó, jehóže dál jesí nám orúžije v pómošč."), ("","","Pristánišče v búri ľúťi smuščájemym, spasénija dvéri víroju spasájemym, Ďívo blahája, spasí mja rabá tvojehó."), ("","","Mnóhija ščedróty tvojá Ďívo Bohoródice, na mňí rabí tvojém javí bohátno, izbavľájušči mjá strášnaho i búduščaho sudá."), ("","","Nóšč strastéj nepostojánna soderžít dúšu mojú, i k páhubňij própasti otsylájet: svítom molítvy tvojejá Bohoródice, spasí mja rabá tvojehó."), ("","","Presvjatája Ďívo obrádovannaja, róždšaja Slóvo v ľíto páče slóva, molí jehó spastí dúšy náša."), ), "6": ( ("","","Jóna iz čréva ádova vopijáše: vozvedí ot tlí živót mój. mý že tebí vopijém: vsesíľne Spáse: pomíluj nás."), ("","","V napástech zastúpnicu ťá ímamy tvérdu, v skórbech krípkoje spasénije, pokój v pečáľich, v bidách pómošč prisnoďívo."), ("","","Tý mi chraníteľnica žízni vséj javísja prečístaja: tý mja izbávi ot bisóv v čás smérti, tý i po smérti upokój."), ("","","Dobróta čestných svjatých ánhel, rádovanije čelovíkov vsích, tý jesí Bohoródice Ďívo: tý mja k životú nastávi."), ("","","Iscilí preneporóčnaja okajánnuju dúšu mojú, neiscíľno boľáščuju žitéjskimi prélesťmi, i mnóhich dveréj zatvoréňmi."), ), "S": ( ("","","Za milosérdije mílosti tvojejá Christé Bóže, ot Ďívy svjatýja voplotítisja izvólil jesí: jejáže rádi sobľudí žízň nášu, jáko čelovikoľúbec."), ), "7": ( ("","","Péšč horjáščuju orosíl jesí Spáse, ótroki spásl jesí pojúščyja i hlahóľuščyja: blahoslovén jesí vo víki Hóspodi Bóže otéc nášich."), ("","","Mnóžestvo prehrišénij mojích prijémľa vo úm, vo otčájaniji byváju, Ďívo preneporóčnaja. ťímže tí zovú: pomozí mi, da ne do koncá pohíbnu."), ("","","Žízni súščuju Máter ťá čístaja, vídyj, zovú ti: smérti dušévnyja izbávi mjá, i víčnyja žízni spodóbi."), ("","","Izbávi preneporóčnaja ot bíd, i strastéj, i boľíznej, i ozloblénija, i žitijá sohrišénij, i ot víčnaho ohňá nehasímaho, vírno čtúščyja ťá písňmi."), ("","","Vsják jazýk slávit ťá čístaja, slávu súščuju i pochvalú róda nášeho, i nastávnicu zablúždšich, Bohoródice prepítaja."), ), "8": ( ("","","Strášnaho Cheruvímom, i čúdnaho Serafímom, i míru tvorcá, svjaščénnicy i rabí, i dúsi právednych pójte, blahoslovíte i prevoznosíte jehó vo víki."), ("","","Vsé žitijé mojé iždích v ľínosti áz preokajánnyj, i nýňi nedoumíjusja, i k koncú priblížichsja, pomozí mi, Vladýčice."), ("","","Hríšnikov pribížišče, nizvéržennych ispravlénije, tý jesí Vladýčice: sehó rádi pritekáju k pokróvu tvojemú, spasí mja."), ("","","Neusýpnu molítvu jáko imúšči, vseneporóčnaja Vladýčice míra, sudá izbávi búduščaho, víroju čtúščyja óbraz tvój."), ("","","Pojét ťá vsják jazýk slávjaj, Bóha bo prepítaho rodilá jesí Ďívo Bohonevísto: jehóže molí neprestánno spastí dúšy pojúščich ťá."), ), "9": ( ("","","Páče jestestvá Máter, i jestestvú Ďívu, jedínu v ženách blahoslovénnuju, písňmi vírniji Bohoródicu veličájem."), ("","","Pod tvojé milosérdije pribihájuščiji víroju izbavľájutsja skórbnych bíd žitijá. Ťímže i áz k tvojemú pokróvu pribihóch Bohoródice."), ("","","Krípkaja zastúpnice, nepobidímaja sťinó pečáľnych čístaja, spasí mja ot strastéj hrichóv, i ohňá víčnujuščaho."), ("","","Svítlymi sijáňmi vozsijávšaho Slóva ot tebé, Ďívo čístaja, ozarí mja, i spasí jáko blahája, i ot múk ischití."), ("","","Nósiši nosjáščaho vsjáčeskaja svjatými rukámi tvojími: jehóže molí čístaja, čuždáho zloďíjstva neoderžímych nás spastí ."), ), ) #let U = ( "S1": ( ("","","Imúšči, dušé mojá, vračevstvó pokajánija, pristupí pripádajušči i vozdychánijem vopijúšči: vračú dúš že i ťilés, svobodí mja čelovikoľúbče, ot mnóhich mojích sohrišénij, sopričtí mja bludníci i razbójniku, i mytarjú: i dáruj mí Bóže, bezzakónij mojích proščénije i spasí mja."), ("","","Íže Petróvo otveržénije slezámi očístiv, i mytaréva sohrišénija vozdychánijem prostív, čelovikoľúbče Hóspodi pomíluj mjá."), ("Bohoródičen","","Rádujsja nevmistímaho v nebesích, vmistívšaja vo utróbi tvojéj: rádujsja Ďívo, prorókov propovídanije, jéjuže vozsijá Jemmanúil: rádujsja Máti Christá Bóha."), ), "S2": ( ("","","Mytarévu pokajániju ne porevnovách, i bludnícy sléz ne sťažách: otčajavájusja bo ot nedoumínija takováho ispravlénija. No tvojím blahoutróbijem spasí mja Bóže, jáko čelovikoľúbec."), ("","","Íže bludnícy slézy, i Petrá prijémyj, i mytarjá opravdávyj iz hlubiný vozdochnúvša: i mené otčájannaho ot ďíl uščédri Spáse, i spasí mja."), ("Múčeničen","","Svjatíji tvojí Hóspodi, na zemlí podvíhšesja, vrahá popráša, i lésť ídoľskuju uprazdníša: ťímže i vincý ot tebé prijáša čelovikoľúbca Vladýki i mílostivaho Bóha, podajúščaho mírovi véliju mílosť."), ("Bohoródičen","","Prevozšlá jesí síly nebésnyja, zané chrám pokazálasja jesí božéstvennyj, blahoslovénnaja Bohoródice, jáko róždšaja Christá Spása dúš nášich."), ), "S3": ( ("","Plód čréva tvojehó","Jáko bludníca pripádaju tí čelovikoľúbče, ášče i slezámi vés nedoumíjusja ko umiléniju: molítvami Predtéči jáko ónu umilí mílostive, i spasí mja."), ("","","Hóspodi skvérnu dúši mojejá, mílosti tvojejá issópom, umílostivlsja jáko bláh omýj Spáse, i očístiv ot skvérny timínija strastéj, pomíluj mjá Vladýko, spasí sozdánije tvojé moľbámi Predtéči tvojehó, jedíne mnohomílostive."), ("Bohoródičen","","Predstáteľnice téplaja i zastúpnice christiján jesí, Bohoródice vsepítaja: ťímže s Predtéčeju, Sýna tvojehó molí obristí nám mílosť."), ), "K": ( "P1": ( "1": ( ("","","Sokrušívšemu bráni mýšceju svojéju, i vsádniki tristáty pohruzívšemu, pojím jemú, jáko izbáviteľu nášemu Bóhu, jáko proslávisja."), ("","","Vsehdá sohrišáju, i ne bojúsja tebé Christé, dolhoterpínijem íščuščaho mojehó pokajánija: dážď mí pómysl obraščénija jáko bláh, i ne prézri mené."), ("","","Hrichí ko hrichóm prilahájaj Christé, prísno nikákože prestajú áz okajánnyj, jedíne bláže bezhríšne, uščédri i spasí mja."), ("Múčeničen","","Dérzostňi dóbliji prihlašáchu stradáľcy: sijé tríznišče ispólneno pódvihov: tecém, predsidít Christós podvihopolóžnik, vinčavája pobidíteli vrahá."), ("Múčeničen","","Sovlekóstesja ťíla mnohoobráznymi ránami, i netľínija rízoju oďíjastesja múčenicy múdriji i Otcá ščedrót sýnove býste."), ("Bohoródičen","","Mnóhimi hrichí ozlóblennuju dúšu mojú, Bohorodíteľnice Ďívo, iscilí: jáko da vo hlásich blahodarénija, priľížno vsehdá slávľu ťá."), ), "2": ( ("","","Mánijem tvojím na zemnýj óbraz preložísja, préžde udoborazlivájemoje vodnóje jestestvó Hóspodi: ťímže nemókrenno pišešéstvovav Izráiľ, pojét tebí písň pobídnuju ."), ("","","Krasotá cerkóvnaja, ukrášen javílsja jesí blažénne Predtéče: júže vsehdá molítvami tvojími spasáj ot vsjákija búri jeretíčestvujuščich, krípku i nepokolebímu."), ("","","Neporóčnaja svjaščénnaja žértva tvorcú prinéslsja jesí, zaklán býl jesí božéstvennyj Predtéče, jáko áhnec nezlóbiv. Ťímže víroju ťá moľú: vsjákija mjá zlóby vrážija izbávi."), ("","","Iscilí ťilésnyja i dušévnyja náša boľízni, prisnoslávnyj predtéče, moľá vsehdá Slóva, vsích nedúhi i boľízni blahoutróbňi vzémšaho."), ("Bohoródičen","","Rodilá jesí vsesvjatája nepostižímoje Slóvo, plótiju po ipostási nám priobščívšahosja: tohó vsehdá molí, spastí víroju tebé prísno blažáščija."), ), ), "P3": ( "1": ( ("","","Nebesá utverdívyj slóvom, i zemnóje osnovánije ukripívyj na vodách mnóhich, utverdí mój úm, v vóľu tvojú čelovikoľúbče."), ("","","Íže prezirájaj čelovíkov hrichí, mnóhaho rádi Christé, čelovikoľúbija, prézri jedíne Spáse, mnóhaja mojá zlája: da ťá slávľu preblaháho."), ("","","Da plotskája choťínija sotvorjú, tvojá choťínija Christé, prezrív bezsóvistnyj, i bojúsja plámennaho tomlénija Slóve, ot nehóže mjá izbávi."), ("Múčeničen","","Ťilésnym boľíznem priobščájuščesja stradáľcy, na neboľíznennuju vziráchu žízň i oslábu: júže ulučívše v rádosti, vírnym boľízni prísno oblehčájut."), ("Múčeničen","","Zarjámi pódvihov strástonóscy prélesti ľútuju nóšč razrušíste, i k nevečérnemu svítu preidóste, nášich boľíznej ťmú prísno otjémľušče."), ("Bohoródičen","","Dvér Bóžiju províďi ťá prorók, jéjuže sám prójde jedín, jákože vísť, Ďívo prečístaja. Ťímže moľúsja tí, pokajánija dvéri samá mi otvérzi."), ), "2": ( ("","","V načáľi nebesá, vsesíľnym slóvom tvojím utverždéj Hóspodi Spáse, i vseďíteľnym i Bóžijim Dúchom, vsjú sílu ích, na nedvížimim mjá kámeni ispovídanija tvojehó utverdí."), ("","","Solncelúčnymi mólnijami vsjú prosviščáješi tvár: sólnca bo úmnaho zvizdá svítlaja javílsja jesí Predtéče. Jehóže molí priľížno strastéj ťmú othnáti ot vseboľíznennych serdéc nášich."), ("","","Zakóna i blahodáti posreďí stojá božéstvennyj Proróče, objavľáješi vsím jávi, óvomu úbo prestátije, óvij že prosijánije byvájuščeje čísto: obnovlénije soveršénno obetšávšym hrichí."), ("","","Bisóvskaho našéstvija, ot soblázn žitéjskich, i ot vsjákija skórbi nás izbávi, vopijém, Christóv Krestíteľu, moľá preblaháho, i v déň súdnyj mučénij svobodí."), ("Bohoródičen","","Blahoslovénnaja jáže Bóha neskázanno róždši, s božéstvennym jehó Krestítelem, molí čístaja neprestánno Vladýčice, o nás, v napásti vpádajuščich žitéjskija, i soderžímych hrichí."), ), ), "P4": ( "1": ( ("","","Plotskóje prišéstvije tvojé Christé, uvirjája prorók Avvakúm vzyváše: sláva síľi tvojéj Hóspodi."), ("","","Ustraníchsja ot putí, k žízni vedúščaho mjá, i v róv zlých vpadóch: Spáse, ne prézri mené."), ("","","Sléznyja mí tóki nizposlí Vladýko Slóve Bóžij: da otmýju mnóhich sohrišénij mojích timínija."), ("Múčeničen","","Privodími jáko áhncy k zakoléniju múčenicy, boríteľa vrahá zakaláchu, slávy spodobľájemi."), ("Múčeničen","","Izlivájemyja krovéj tóki prechváľniji, potóki sládostnyja uhotóvaša vsím vosprijátije, božéstvenniji múčenicy."), ("Bohoródičen","","Voplotísja ot krovéj tvojích čístych Hospóď, pokajánije čelovíkom dáruja vsím, otrokovíce chodátajstvom tvojím."), ), "2": ( ("","","Ótča ňídra ne ostávľ, i sošéd na zémľu Christé Bóže, tájnu uslýšach smotrénija tvojehó, i proslávich ťá jedíne čelovikoľúbče."), ("","","Nizložív pólk vraždébnych, i dóblestvovav na ních svítlostiju Krestíteľu, vo mňí cárstvujuščij hrích nizloží, moľúsja tí, molítvami tvojími."), ("","","Svitíľnik jávľsja blažénne mýslennyj, pokazál jesí čelovíkom Iisúsa, právednoje velíkoje Sólnce, ímže ozarítisja serdcám vsích, molísja."), ("","","V bezzakónijich začénsja i rodívsja, žívu v ľínosti, i bojúsja támošnich mučénij: ot níchže mjá ischití Krestíteľu, Bóha umolív."), ("","","Molénija o nás tebé čtúščich Krestíteľu, Bóhu prinesí: jáko da izbávit nás vsjákaho ľútaho obstojánija, i bisóvskaho vréda, mólimsja."), ("Bohoródičen","","Zakóna síni, tebé mnohovídno projavíša róždšuju Bóha: jehóže molí vseneporóčnaja, vsjákaho mjá bezzakónija i strastéj ťilésnych izbáviti."), ), ), "P5": ( "1": ( ("","","Razhnávyj nóšč strástnuju, vozsijáj mí svít úmnyj, načaloródnuju ťmú othnáv bézdny, i pervozdánnyj svít vozsijávyj míru, soďíteľu vsích."), ("","","Izbávi mjá Slóve, právednaho tvojehó hňíva, jehdá súdiši zemlí: i ot mnóhich sohrišénij pokajánijem očíšč, chrám mjá pokaží tvojejá bláhosti, jedíne soďíteľu vsích."), ("","","Ot zíľnyja mhlý strastéj osľipíchsja umóm, i ne vím, čtó ďílaju, onečúvstvivsja sérdcem: obratí mja Christé, i pokajánije mí dáruj čistíteľnoje skvérn."), ("Múčeničen","","Tríznišče ispólneno pótov, stradáľcy tékše júnošeski, k nebésňij svítlosti dostihóste, pobídnyja póčesti ot živonačálnyja rukí prijémše: ťímže rádujetesja nýňi."), ("Múčeničen","","Krípkimi žílami svjaščénnych boľíznej vášich stradáľcy, udavíste voístinnu načalozlóbnaho zmíja, i rájskija sládosti spodóbistesja: ťímže voschvaľájem vás."), ("Bohoródičen","","Jáže sólnca óblače svítlyj, vozsijáj mí svít mýslennyj ístinnaho pokajánija, i otžení ťmú lukávych pomyšlénij: da víroju pojú ťa, jáko spasénije vírnych."), ), "2": ( ("","","Hóspodi Bóže mój, ot nóšči útrenevav tebí moľúsja: podážď mí ostavlénije prehrišénij mojích, i k svítu tvojích poveľínij putí mojá naprávi, moľúsja."), ("","","Prozjábl jesí hlás vopijúščaho v pustých, premúdre, pómyslech Bóžija poznánija. Ťímže moľú ťá: dúšu mojú opusťívšuju vsjákimi prestupléňmi, obnoví."), ("","","Čestnýj Vladýki sosúd pokazálsja jesí božéstvennyj proróče, nečístych ďijánij izbávi mjá molítvami tvojími: i čésti polučíti víčnyja blahoďíteľa umolí."), ("","","Priblížišasja bezzakónija na mjá vchódom ľínosti: óbrazy pokajánija mjá blažénne Predtéče, lúčša sotvorí, jáko da usérdno putí Hospódni šéstvuju."), ("Bohoródičen","","Umertví plóti mojejá zemnája mudrovánija, Bohoródice, žízň róždšaja, smértiju smérť do koncá božéstvennoju síloju, presvjatája čístaja, potrébľšuju."), ), ), "P6": ( "1": ( ("","","Vo hlubinú hrichóvnuju vpádsja bláže, jáko Jóna ot kíta vopijú ti: vozvedí ot tlí živót mój, i spasí mja čelovikoľúbče."), ("","","Nóv bludník javíchsja, skvérno žív na zemlí, i slastným stremlénijem podkloníchsja: obratí mja Christé Bóže mój, i spasí mja jáko čelovikoľúbec."), ("","","Vozstení, o dušé mojá, da izbávišisja stenánija: proslezísja, jáko da sléz neprestánnych ne priímeši iskúsa támo v boľízni, ni jedínyja že imúščich póľzy."), ("Múčeničen","","Javístesja jákože kámenije, vo vincí jávi Christóvy cérkve vodružény: i ukrašénije tojá ľípotnoje býste, čestníji velikomúčency."), ("Múčeničen","","Končíny v Bózi dostójnyja ulučívše premúdriji, bezkonéčnaja nasľídstvujete mzdovozdajánija. Ťímže končínam nášym v pokajániji býti, múčenicy molítesja."), ("Bohoródičen","","Iz hlubiný mja ľínosti bezmírnych zól vozvedí blahája, jáže bézdnu blahoutróbija róždši, istóčnik mí sléz prisnoďívo dáruj."), ), "2": ( ("","","Jóna iz čréva ádova vopijáše: vozvedí ot tlí živót mój. Mý že tebí vopijém: vsesíľne Spáse, pomíluj nás."), ("","","Lučámi dobroďítelej jávi oblistája, i svitozárnym mučénijem sijája, prosviščáješi vsjú tvár, úmnaho vostóka drúže blížnij."), ("","","Prozjábl jesí ot stáricy neplódnyja blažénne: ťímže vopijú ti: hrichámi mnóhimi mjá sostarívšahosja, pokajánija dobrótami obnoví, molítvami tvojími."), ("","","Svitíľniče svíta nevečérňaho božéstvennyj proróče, svitíľnik sérdca mojehó uhásšij vozžzí molítvami tvojími, i svíta pričástnika mjá božéstvennaho sotvorí."), ("Bohoródičen","","Jáko dóžď vo črévo tvojé Slóvo sníde: jehóže molí prečístaja Ďívo, tečénija izsušíti bezmírnych mojích zól, moľúsja tí."), ), ), "P7": ( "1": ( ("","","Súščym v peščí otrokóm tvojím Spásé, ne prikosnúsja, nižé stuží óhň. Tohdá trijé jáko jedíňimi ustý pojáchu, i blahoslovľáchu hlahóľušče: blahoslovén jesí Bóže otéc nášich."), ("","","V strásti bezčéstija vpadóch, skotóm, Spáse, upodóbichsja, i omračívsja ne víždu ždánija tvojehó Slóve, dolhoterpilívnaho: obraščénijami vrémja dáruj. i spasí mja."), ("","","V ľínosti žitijé mojé skončách, ďíja jáže ne ľíť jésť tvoríti, i sé nýňi próčeje ko vratóm približájusja ádovym, ne prijémľa čúvstva: ne prézri mjá Christé, íže jedín sýj bláh."), ("Múčeničen","","Voždeľívše žízni víčnyja mírovi umertvístesja premúdriji: i vrahá umertvívše konéčňi, k nebesém vozleťíste, o nás stradáľcy prísno moľáščesja."), ("Múčeničen","","Razrišívšesja ot núžd ťilésnych, razrišíste prélesti úzy, i ko Christú krípkoju ľubóviju múčenicy dúšy privjazáste, svjazávšemusja plótiju, i razrušívšemu kľátvu."), ("Bohoródičen","","Svítok nóv prorók tebé predvíďiv, v némže napisásja Slóvo Ótčeje. Ťímže čístaja, moľúsja: v knízi mňí živých napisátisja molí, mnóhich mojích zól razorjájušči napisánije."), ), "2": ( ("","","Péšč ótrocy ohnepáľnu drévle rosotočášču pokazáša, jedínaho Bóha vospivájušče i hlahóľušče: prevoznosímyj otcév Bóh i preproslávlen."), ("","","Dáruj mí túči sléz molítvami tvojími: íže blahoutróbija bézdnu ríčnymi strujámi izmývyj predtéče, i vsehó mja očísti skvérny, plóti že i dúcha."), ("","","Moľbú prinesí blažénne, nad vsími Bóhu nášemu, jáko da i mené pomílujet jáko blahoutróben, mnóho sohrišájuščaho, i vozniknovénija nýňi ne imúščaho."), ("","","Neplódnaja dušé, potščísja pokájatisja, da ne jáko smokóvnicu ťá neplódnuju božéstvennyj súd posečét iz kórene, Vladýci vozopíj: Bóže, očístiv spasí mja."), ("Bohoródičen","","Umerščvlénu dúšu mojú imíjaj zlými prestupléňmi, ťá umertvívšuju ád roždestvóm tvojím, moľú Vladýčice, pokajánija mjá óbrazy oživí."), ), ), "P8": ( "1": ( ("","","Ánhelmi nemólčno v výšnich slávimaho Bóha, nebesá nebés, zemľá i hóry i chólmi, i hlubiná, i vés ród čelovíčeskij, písňmi tohó jáko sozdáteľa i izbáviteľa blahoslovíte ."), ("","","Preizobíľno nasladívsja vreďáščich slastéj, umovrédno nesmýslennyj áz, preidóch vsjákaho hríšnika: imíjaj blahoutróbija premnóžestvo, podážď mí očiščénije prehrišénij."), ("","","Nýňi pri dvérech ženích, sviščú ukrasí dušé, jeléjem napojájušči sijú milosérdija, i vsjákimi dóbrymi ďíly: préžde dáže ne zatvorítsja dvér, potščísja so Christóm vníti k rádosti neizrečénňij."), ("Múčeničen","","Ne bojáščesja múk, dóbliji vopijáchu stradáľcy: sé blahoprijátno vrémja, stánem vsí tvérdym umóm: sťážim málymi boľízňmi žízň neboľíznennuju, i sládosť nestaríjuščujusja."), ("Múčeničen","","Vodámi božéstvennymi strastotérpcy spáovy navodňájemi prísno, napojájete vsjú zémľu podražánijem pódvihov vášich: i plodonósnu sijú dobroďíteľmi soďílovajete o Chrisťí vo víki."), ("Bohoródičen","","Bohoródice, izvístnoje predstáteľstvo, i nadéžda christiján, v déň strášnyj predstáni mí prehrišívšemu mnóho: i izbávi hejénny strášnyja, ovcám mjá desným sočetavájušči."), ), "2": ( ("","","Jedínaho beznačáľnaho carjá slávy, jehóže blahoslovját nebésnyja síly, i trepéščut číni ánheľstiji, pójte svjaščénnicy, ľúdije prevoznosíte jehó vo víki."), ("","","Úz razrišíti mi sja mnóhich mojích prehrišénij, svjázana bývša, i svjázannym razrišénije podávšaho, moľá proróče jedínaho izbáviteľa, da ne prestajéši vo víki, prísno ťá slávjaščaho."), ("","","Ujazvíchsja predtéče, slastéj orúžijem, i v boľízni sérdca tebí vzyváju: uvračúj duší mojejá boľízni, Christá moľá, jedínaho vračá dúš že i ťilés."), ("","","Rukóju tvojéju predtéče, jehóže krestíl jesí Slóva, ne oskuďíj molíti neprestánno, izbáviti mjá ot rukí hrichóvnyja, sohrišívšaho mnóho, i smirénnaho i osuždénnaho."), ("","","Jáko pohrebóch v zemlí bezúmno talánt, íže mí ot Bóha vvíren býsť, ožidáju hórkaho tomlénija: ot nehóže Krestíteľu, ischití mja molítvami tvojími, vírno moľú ťá."), ("Bohoródičen","","Prebylá jesí neopalíma, prijémši vo utróbi óhň nesterpímyj Ďívo: ťímže ischití mja ot ohňá nehasímaho, orošájušči mjá nýňi, prísnaho pokajánija predóbrymi óbrazy."), ), ), "P9": ( "1": ( ("","","Bezsímennaho roždestvá začátije któ skážet ot čelovík? Netľínnaho roždestvá roždéniju któ ne počudítsja ot zemnoródnych? Ťím ťá plemená zemnája Bohoródice veličájem."), ("","","Da nasľídim búduščaja blahája, vospláčem, vozdochném, umólim Christá, dóndeže vrémja ímamy vírniji, pokajánija i molénija."), ("","","Jáko chananéja zovú ti: pomíluj mjá Christé, jákože drévle ničáščuju isprávi mjá Iisúse: i spasí mja Spáse, jáko Petrá, hrichí pohružájemaho."), ("Múčeničen","","Sťisňájemi skorbmí, temnícami že i mučéňmi, strástonóscy múčenicy, k prostránstvu uťišénija preidóša, ot ťisnotý i ot prehrišénij nás izbavľájut."), ("Múčeničen","","Zemľá úbo pokrý váša ťilesá nýňi, nébo že deržít svjatýja dúchi: prísno prestólu predstojášče slávy, so ánhely rádujutsja."), ("Bohoródičen","","Obléksja v mjá Hospóď, iz tebé prójde prečístaja: tohó úbo molí, odéždeju mjá prosvitíti svíta Ďívo, sovlékšaho mjá nýňi strastéj vrétišča ťažčájšaho."), ), "2": ( ("","","Netľínija iskušénijem róždšaja, i vsechitrecú slóvu plóť vzaimodávšaja, Máti neiskusomúžnaja Ďívo Bohoródice: prijátelišče nesterpímaho. Seló nevmestímaho ziždíteľa tvojehó, ťá veličájem."), ("","","Ot svjaščénnaho kórene proróče, prozjábl jesí, i zlóbnoje korénije vsé istórhl jesí, ímiže spodavľájema i nepotrébna byvájema posití mja blažénne, i božéstvennaho pokajánija prozjabáti plodý uprávi mjá."), ("","","Krasňíjšuju hórlicu, i slávija ťá cérkov poznavájet, velíkij predtéče: pokajánija bo provozhlasíl jesí písň dušám zapusťívšym, i zlými oľadeňívšim. ťímže víroju ťá ublážájem."), ("","","Tý putí vedúščyja ko spasíteľnym vchódom vsím pokazál jesí, slávnyj Predtéče: ímiže chodíti mjá ukripí, vsími žitijá bezpútiji bluďáščaho, prélestiju že zlóbu soďílavšaho."), ("","","Strášnyj pri dvérech déň priblížisja, i osuždénija ďilá imýj, rydáju: Hóspodi, Hóspodi, jedíne mílostive, molítvami tvojehó predtéči, i vsích svjatých, neosuždénna tohdá pokaží mja."), ("Bohoródičen","","Svít róždšaja božéstvennyj Bohoblahodátnaja, omračénnuju prestupléňmi dúšu mojú prosvití, moľúsja, i ťmý víčnyja svobódna mjá pokaží: jáko da veličáju ťá i slávľu prisnoblážénnuju."), ), ), ), "CH": ( ("","","Jáko neplódnuju smokóvnicu ne posicý mené Spáse, hríšnaho: no na mnóha ľíta proščénije mí dáruj, napajája dúšu mojú slezámi pokajánija, da plód prinesú ti mílostyni."), ("","","Jáko sólnce sýj právednoje, prosvití serdcá pojúščich ťá: Hóspodi, sláva tebí."), ("Múčeničen","","Posreďí sudíšča zakonoprestúpnych rádujuščesja vopijáchu strástonóscy tvoí: Hóspodi, sláva tebí."), ("Bohoródičen","","Svít Christé prozjábl jesí ot Ďívy, i prosvitíl jesí ród čelovíčeskij: Hóspodi, sláva tebí."), ), ) #let L = ( "B": ( ("","","Krasén bí i dóbr v sňíď, íže mené umertvívyj plód: Christós jésť drévo živótnoje, ot nehóže jadýj ne umiráju, no vopijú s razbójnikom: pomjaní mja Hóspodi, vo cárstviji tvojém."), ("","","Strúpy mojehó sérdca neiscíľnyja, Hóspodi, uvračúj, jáko jedín vráč dúš že i ťilés: i stupáti mí právo vsehdá pospíj vo spasíteľnyja putí."), ("","","Predtekíj právednomu Sólncu Christóv Krestíteľu, svitíľnik duší mojejá uhašényj mnóhoju zlóboju, vozžzí božéstvennymi molítvami tvojími, jáko da ublažáju ťá vsehdá spasájem."), ("Múčeničen","","Stradávše i vinčáni bývše, vrahá posramíli jesté, i nýňi žíteľstvujete na nebesích, svíta nepristúpnaho ispolňájemi premúdriji múčenicy, moľáščesja o dušách nášich."), ("","","Uvračúj duší mojejá strásti neiscíľnyja, božéstvennaja Tróice: i ischití mja hejénny, i iskušénij, jáže vo jedínom božestvé slávimaja blahočéstno: i víčnujuščeje mí cárstvo dáruj."), ("","","Vmistíla jesí netesnomístno vo črévi nevmistímaho: jehóže vsehdá molí Máti čístaja, ťisnotý vsjákija i strastéj naviďínija izbáviti rabý tvojá, ľubóviju ťá slávjaščyja."), ), )
https://github.com/sabitov-kirill/os-low-level-render-report
https://raw.githubusercontent.com/sabitov-kirill/os-low-level-render-report/master/main.typ
typst
#import "template.typ": * #show: ams-article.with( title: [Render: от DRM до Высокоуровневых API и Display Server'ов в Linux], authors: ( ( name: "<NAME>", department: [CT M3235], organization: [Itmo University], location: [Russia, St. Petersburg], email: "<EMAIL>", url: "t.me/ne1mnn" ), ), abstract: [ В современном мире 2D/3D графика и вычисления на выдеокарте занимают центральное место в различных сферах -- от игровой индустрии и пользовательских интерфейсов до моделирования физических процессов и машинного обучения. Однако, эффективный рендеринг и работа на видеокарте в Linux (в т.ч. Android), особенно в условиях постоянно развивающихся технологий, представляет собой сложную задачу, требующую глубокого понимания различных уровней абстракции – от драйверов и DRM (Direct Render Manager) до Display Server'ов и высокоуровневых API. В рамках моего доклада, я собираюсь обсудить ключевые проблемы и решения, связанные с рендерингом 2D и 3D графики в Linux. Основное внимание будет уделено изучению работы DRM как фундаментального элемента для эффективного взаимодействия между аппаратной и программной частями системы. Рассмотрим архитектуру и интерфейсы Display Server'ы, таких как X11, Wayland, Surface Flinger, в контексте современных графических требований, и какие возможности они открывают для разработчиков и пользователей. Кроме того, будет подробно рассмотренно взаимодействие этих компонентов с высокоуровневыми графическими API, такими как OpenGL и Vulkan, и как они способствуют повышению производительности и качества визуализации на различных уровнях абстракции. В моем докладе представлен комплексный анализ архитектуры и компонентов, с акцентом на их взаимосвязь и важность для создания эффективной графической экосистемы. Это позволит слушателям не только глубже понять технические аспекты рендеринга в Linux, но и оценить потенциал и перспективы данной области, а так же важность понимания ее устройства. ], ) #outline(title: [Содержание], depth: 2, indent: true) #pagebreak() = Общие понятия, уровень аппаратного обеспечения Графический процессор (GPU) является ключевым компонентом современных вычислительных систем, отвечая за обработку графической информации. Он выделяется своей способностью к параллельной обработке данных, благодаря чему находит применение не только в графических вычислениях, но и в области высокопроизводительных вычислений. == Архитектура паралельных вычислений SIMD (GPU - SIMD) *SIMD (Single Instruction, Multiple Data)* – это модель параллельных вычислений, используемая в компьютерной архитектуре. В этой модели одна и та же операция (инструкция) применяется параллельно к множеству элементов данных. Это позволяет достигать значительного ускорения вычислений за счет одновременной обработки нескольких данных одной инструкцией. Основная идея SIMD состоит в том, что множество операций, выполняемых над различными данными, могут быть инициированы одной командой, вместо того чтобы выполнять каждую операцию отдельно. Это особенно эффективно в задачах, где одинаковые операции нужно повторить для большого массива данных, например, при обработке изображений, звука или при выполнении научных расчетов. *GPU как реализация SIMD*: Графические процессоры (GPU) представляют собой яркий пример архитектуры SIMD в действии. #align(center)[#image("images/fermi.png", width: 280pt)] В контексте GPU, SIMD позволяет одновременно выполнять одну и ту же инструкцию на большом количестве пикселей или вершин, что является стандартной задачей в графическом рендеринге. На примере архитектуры, представленной выше, у нас есть множество мультипроцессоров, у каждого есть кэш второго уровня. Видеокарта может одновременно использовать все имеющиеся мультироцессоры, выполняя на каждом разные инструкции. Непосредственно подход SIMD реализуется внутри данных потоковых мультипроцессоров. Смотря на картинку выше, нетрудно описать реализацию, которая состоит в том, что на одном столбце можно выполнить какую-то одну операцию над различными данными, как и было сказано ранее. == Общая архитектура современных видеокарт Современные видеокарты обладают сложной структурой, которая включает следующие компоненты: + Память: Видеокарты оснащены собственной памятью (чаще всего типа GDDR), которая используется для хранения текстур, буферов кадров и других графических данных. Быстродействие и объем памяти играют ключевую роль в производительности GPU. + Вычислительные Блоки: Состоят из множества маленьких, но мощных процессоров, обрабатывающих данные параллельно. Они способны выполнять различные операции, от простых математических вычислений до сложной обработки текстур. + Кеши: Как и в CPU, в GPU присутствуют кеши для ускорения доступа к данным. Они уменьшают задержку при доступе к часто используемым данным и повышают общую производительность. == Связь GPU и CPU Все приложения исполняются на центральных процессорах, но для некоторых вычислений и отображения изображений на физические устройства они использую видеокарты, таким образом необходим механизм для связи CPU и GPU. Для этого на физическом уровне существует системная шина шину, пример современной шины - PCI Express (PCIe). PCIe обеспечивает высокоскоростной канал для передачи данных между процессором и видеокартой, что критично для высокопроизводительных графических и вычислительных приложений. Современные стандарты PCIe позволяют передавать данные с очень высокой скоростью, что важно для задач, требующих интенсивного обмена данными между CPU и GPU. == Программирование видеокарт В конкретных приложениях видеокарты выполняют самые различные задачи и вычисления, например - физический просчет траектории полета огромного количества частиц, машинное обучение, вычисление реалистичного освещения больших 3D сцен, растеризация изображений. Для каждой задачи необходимы различные программы для видеокарт. Программирование GPU включает в себя несколько ключевых аспектов: + MMIO (Memory-Mapped I/O): Техника, позволяющая программам обращаться к устройствам, таким как GPU, используя стандартные операции чтения и записи в память. Это упрощает коммуникацию между CPU и GPU. + DMA (Direct Memory Access): Механизм, позволяющий переносить данные между памятью и GPU без непосредственного участия CPU, что существенно увеличивает скорость передачи данных и снижает нагрузку на процессор. + Шейдерные Программы: Программы, запускаемые непосредственно на GPU для обработки графики. Шейдеры могут быть написаны на специализированных языках, таких как GLSL (для OpenGL) или HLSL (для DirectX и Vulkan), и позволяют детально контролировать процесс рендеринга, создавая сложные визуальные эффекты и реалистичные изображения. #pagebreak() = Низкий уровень == Прошлый взгляд на работу с видеокартой В классических Unix-системах, таких как X Window System, используемая ранее в Linux, процесс рендеринга был организован через сервер X (например, XFree86). Это был привилегированный пользовательский процесс, который отображал видеопамять в виртуальное адресное пространство пользователя. Сервер X действовал как посредник между приложениями и аппаратным обеспечением, обрабатывая графические запросы от клиентов и направляя их к видеоадаптеру. *Архитектура и Рендеринг*: В этой архитектуре, сервер X взаимодействовал напрямую с аппаратным обеспечением для рендеринга изображений. Он управлял видеопамятью и обеспечивал основные графические операции, такие как рисование окон и управление вводом. Такой подход имел значительные недостатки: он был неэффективен с точки зрения производительности, особенно в условиях современных графических требований, и представлял ограничения в масштабируемости и безопасности. #align(center)[#image("./images/Access_to_video_card_without_DRM.svg", width: 300pt)] == KMS и DRI - DRM Linux Kernel Module Современные требования к графической обработке и неэффективность старой архитектуры привели к разработке нового подхода, в основе которого лежит модуль ядра Linux - DRM (Direct Rendering Manager). *DRM: Ключевые Компоненты и Архитектура* + KMS (Kernel Mode Setting): Эта функция DRM позволяет ядру управлять настройками видеоадаптера, такими как разрешение экрана и глубина цвета, обеспечивая повышенную производительность и безопасность. + DRI (Direct Rendering Infrastructure): DRI обеспечивает прямое взаимодействие между приложениями и аппаратным обеспечением графики, минуя сервер X. Это позволяет приложениям напрямую использовать ресурсы GPU, улучшая производительность и уменьшая задержки. #align(center)[#image("./images/Access_to_video_card_with_DRM.svg")] *Архитектура DRM*: DRM состоит из ядра и драйверов устройств, обеспечивающих интерфейс между аппаратным обеспечением и высокоуровневыми графическими стеками. Он управляет доступом к графическим ресурсам, обеспечивая эффективное распределение и изоляцию ресурсов между различными приложениями. Модуль ядра Linux DRM включает в себя бесплатные драйверы с открытым исходным кодом для поддержки оборудования трех основных производителей графических процессоров для настольных компьютеров (AMD, NVIDIA и IntelЫ), а также растущего числа мобильных графических процессоров и систем на кристалле (SoC). Качество каждого драйвера сильно варьируется в зависимости от степени сотрудничества со стороны производителя и других факторов. #pagebreak() = Кроссплатформенная Абстрактные API для работы с видеокартой Кроссплатформенные графические API, такие как OpenGL, Vulkan и CUDA, представляют собой абстрактные интерфейсы, позволяющие разработчикам создавать графические приложения, которые могут работать на различных устройствах и операционных системах. Эти API служат мостом между программным обеспечением и аппаратным обеспечением, облегчая разработку графических приложений, игр, и систем виртуализации. == Задачи Кроссплатформенных Графических API + Унификация Разработки: Предоставление единого интерфейса для работы с графикой на разных платформах и устройствах, уменьшая необходимость в платформоспецифическом коде. + Абстракция от Аппаратного Обеспечения: Разработчики могут фокусироваться на создании графики, не беспокоясь о деталях конкретного графического оборудования. + Эффективность и Производительность: Эти API оптимизированы для максимальной производительности, позволяя приложениям лучше использовать возможности современных GPU. == Связь DRM с OpenGL/Vulkan Взаимодействие подобных абстрактных графических API с драйверами на Linux происходит через DRM. DRM обеспечивает эффективное взаимодействие между аппаратным и программным обеспечением, управляя такими вещами, как доступ к видеопамяти и устройствам вывода. В своб очередь, Графические драйверы, которые обеспечивают совместимость с конкретными видеокартами, играют важную роль в процессе. Они переводят инструкции от API в команды, которые может обработать GPU. На разных платформах эти драйверы могут взаимодействовать с аппаратным обеспечением по-разному, но API, как правило, предоставляют единый интерфейс для разработчиков. == Пример использования OpenGL и DRM на низком уровне Рассмотрим простейшее пользовательское приложение, которое демонстрирует процесс инициализации и настройка контекста через DRM и использование OpenGL для рендеринга (использованы пользовательская библиотеки для работы с DRM - libdrm, OpenGL в современной модульной реализации Mesa 3D): #import "@preview/codelst:1.0.0": sourcecode *CMake проекта* #sourcecode(```c cmake_minimum_required(VERSION 3.16) project(drm-example) set(CMAKE_C_STANDARD 11) add_executable(drm-example main.c) find_package (PkgConfig REQUIRED) pkg_check_modules(DRM REQUIRED libdrm) target_link_libraries(drm-example ${DRM_LIBRARIES} gbm EGL GLESv2) target_include_directories(drm-example PUBLIC ${DRM_INCLUDE_DIRS}) target_compile_options(drm-example PUBLIC ${DRM_CFLAGS_OTHER}) ```) *Структуры для хранение низкоуровневых примитивов* #sourcecode(```c static struct { int fd; drmModeModeInfo *mode; uint32_t crtc_id; uint32_t connector_id; } drm; static struct { struct gbm_device *dev; struct gbm_surface *surface; } gbm; static struct { EGLDisplay display; EGLConfig config; EGLContext context; EGLSurface surface; GLuint program; GLint modelviewmatrix, modelviewprojectionmatrix, normalmatrix; GLuint vbo; GLuint positionsoffset, colorsoffset, normalsoffset; } gl; struct drm_fb { struct gbm_bo *bo; uint32_t fb_id; }; ```) *Инициализация* + Получим коннектор DRM, по средствам которого будет создано соединением с модулем DRM, установка разрешения выводимого изображения, вывод буффера с зарендереным изображением (`Framebuffer`) на экран: #sourcecode(```c drmModeRes *resources; drmModeConnector *connector = NULL; drmModeEncoder *encoder = NULL; int i, area; drm.fd = open("/dev/dri/card0", O_RDWR); if (drm.fd < 0) { printf("could not open drm device\n"); return -1; } resources = drmModeGetResources(drm.fd); if (!resources) { printf("drmModeGetResources failed: %s\n", strerror(errno)); return -1; } /* find a connected connector: */ for (i = 0; i < resources->count_connectors; i++) { connector = drmModeGetConnector(drm.fd, resources->connectors[i]); if (connector->connection == DRM_MODE_CONNECTED) { /* it's connected, let's use this! */ break; } drmModeFreeConnector(connector); connector = NULL; } if (!connector) { /* we could be fancy and listen for hotplug events and wait for * a connector.. */ printf("no connected connector!\n"); return -1; } /* find prefered mode or the highest resolution mode: */ for (i = 0, area = 0; i < connector->count_modes; i++) { drmModeModeInfo *current_mode = &connector->modes[i]; if (current_mode->type & DRM_MODE_TYPE_PREFERRED) { drm.mode = current_mode; } int current_area = current_mode->hdisplay * current_mode->vdisplay; if (current_area > area) { drm.mode = current_mode; area = current_area; } } if (!drm.mode) { printf("could not find mode!\n"); return -1; } /* find encoder: */ for (i = 0; i < resources->count_encoders; i++) { encoder = drmModeGetEncoder(drm.fd, resources->encoders[i]); if (encoder->encoder_id == connector->encoder_id) break; drmModeFreeEncoder(encoder); encoder = NULL; } if (encoder) { drm.crtc_id = encoder->crtc_id; } else { uint32_t crtc_id = find_crtc_for_connector(resources, connector); if (crtc_id == 0) { printf("no crtc found!\n"); return -1; } drm.crtc_id = crtc_id; } drm.connector_id = connector->connector_id; return 0; ```) + Инициализация поверхности, на которую будет выводиться изображение: #sourcecode(```c gbm.dev = gbm_create_device(drm.fd); gbm.surface = gbm_surface_create(gbm.dev, drm.mode->hdisplay, drm.mode->vdisplay, GBM_FORMAT_XRGB8888, GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); if (!gbm.surface) { printf("failed to create gbm surface\n"); return -1; } return 0; ```) + Инициализация контекста OpenGL, привязанная к поверхности, созданной раннее #sourcecode(```c EGLint major, minor, n; GLuint vertex_shader, fragment_shader; GLint ret; static const EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; static const EGLint config_attribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 8, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE }; PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = (void *)eglGetProcAddress("eglGetPlatformDisplayEXT"); assert(eglGetPlatformDisplayEXT != NULL); gl.display = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_KHR, gbm.dev, NULL); if (!eglInitialize(gl.display, &major, &minor)) { printf("failed to initialize\n"); return -1; } printf("Using display %p with EGL version %d.%d\n", gl.display, major, minor); printf("EGL Version \"%s\"\n", eglQueryString(gl.display, EGL_VERSION)); printf("EGL Vendor \"%s\"\n", eglQueryString(gl.display, EGL_VENDOR)); printf("EGL Extensions \"%s\"\n", eglQueryString(gl.display, EGL_EXTENSIONS)); if (!eglBindAPI(EGL_OPENGL_ES_API)) { printf("failed to bind api EGL_OPENGL_ES_API\n"); return -1; } if (!eglChooseConfig(gl.display, config_attribs, &gl.config, 1, &n) || n != 1) { printf("failed to choose config: %d\n", n); return -1; } gl.context = eglCreateContext(gl.display, gl.config, EGL_NO_CONTEXT, context_attribs); if (gl.context == NULL) { printf("failed to create context\n"); return -1; } gl.surface = eglCreateWindowSurface(gl.display, gl.config, gbm.surface, NULL); if (gl.surface == EGL_NO_SURFACE) { printf("failed to create egl surface\n"); return -1; } /* connect the context to the surface */ eglMakeCurrent(gl.display, gl.surface, gl.surface, gl.context); printf("GL Extensions: \"%s\"\n", glGetString(GL_EXTENSIONS)); return 0; ```) + Создаем буффер для рендера изображения: #sourcecode(```c static struct drm_fb *drm_fb_get_from_bo(struct gbm_bo *bo) { struct drm_fb *fb = gbm_bo_get_user_data(bo); uint32_t width, height, stride, handle; int ret; if (fb) return fb; fb = calloc(1, sizeof *fb); fb->bo = bo; width = gbm_bo_get_width(bo); height = gbm_bo_get_height(bo); stride = gbm_bo_get_stride(bo); handle = gbm_bo_get_handle(bo).u32; ret = drmModeAddFB(drm.fd, width, height, 24, 32, stride, handle, &fb->fb_id); if (ret) { printf("failed to create fb: %s\n", strerror(errno)); free(fb); return NULL; } gbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback); return fb; } bo = gbm_surface_lock_front_buffer(gbm.surface); fb = drm_fb_get_from_bo(bo); ```) + Изменяем размер созданного буффера, на размер соответсвующий поверхности полученного ранее коннектора: #sourcecode(```c /* set mode: */ ret = drmModeSetCrtc(drm.fd, drm.crtc_id, fb->fb_id, 0, 0, &drm.connector_id, 1, drm.mode); if (ret) { printf("failed to set mode: %s\n", strerror(errno)); return ret; } ```) *Ц<NAME>* Цикл рендера -- основной цикл приложения, в котором происходит вызов системных функций, шейдерных программ и тд. В цикле мы: + Инициируем рендер изображения в текущий буффер: #sourcecode(```c static void draw(uint32_t i) { /* clear current buffer with blue color */ glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.2f, 0.3f, 0.5f, 1.0f); /* other render stuff */ } draw(i++); ```) + Выводим отрендеренный буффер на экран: #sourcecode(```c eglSwapBuffers(gl.display, gl.surface); ```) + Ставим активируем второй буффер для следующей итерации рендера (используется простейшая двойная буфферизация): #sourcecode(```c /* get new active buffer */ next_bo = gbm_surface_lock_front_buffer(gbm.surface); fb = drm_fb_get_from_bo(next_bo); /* release last buffer to render on again: */ gbm_surface_release_buffer(gbm.surface, bo); bo = next_bo; ```) + Инициируем физическое отображение активного буффера через коннектор: #sourcecode(```c static void page_flip_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data) { int *waiting_for_flip = data; *waiting_for_flip = 0; } ret = drmModePageFlip(drm.fd, drm.crtc_id, fb->fb_id, DRM_MODE_PAGE_FLIP_EVENT, &waiting_for_flip); if (ret) { printf("failed to queue page flip: %s\n", strerror(errno)); return -1; } while (waiting_for_flip) { ret = select(drm.fd + 1, &fds, NULL, NULL, NULL); if (ret < 0) { printf("select err: %s\n", strerror(errno)); return ret; } else if (ret == 0) { printf("select timeout!\n"); return -1; } else if (FD_ISSET(0, &fds)) { printf("user interrupted!\n"); break; } drmEventContext evctx = { .version = DRM_EVENT_CONTEXT_VERSION, .page_flip_handler = page_flip_handler, }; drmHandleEvent(drm.fd, &evctx); } ```) Таким образом мы ознакомились с базовым процессом рендера на Linux, используя для инициализации системы низкоуровневое API (`drm`), а для рендера высокооуровневое (`OpenGL`). Так же важно заметить, что наше приложение работает без дополнительных тяжеловесных абстракций в виде `Display Server`'а (о которых речь пойдет далее). == Real world пример Для более подробного ознакомления с процессом работы и возможностями выскооуровневых графических API можно ознакомится с еще одним примером -- созданная мной #link("https://github.com/sabitov-kirill/sculpto")[кросс-платформенная система рендера реалистичных 3D сцен], #link("https://github.com/sabitov-kirill/sculpto/blob/main/docs/images/sculpto_images.pdf")[архитектура проекта и примеры работы]. #align(center)[ #image("./images/pathtracer_spheres.png", width: 300pt) #image("./images/normal_mapping_and_bloom_on.png", width: 300pt) #image("./images/render_pass_funal.png", width: 250pt) ] #pagebreak() = Абстракция в виде Display Server'а *Display Server* — это компонент программного обеспечения, который управляет выводом графики на экран и взаимодействует с устройствами ввода, такими как клавиатура и мышь. Он играет роль посредника между приложениями и аппаратным обеспечением компьютера, обрабатывая графические запросы от приложений и преобразуя их в изображения на экране. Основным отличием Display Server'ов от высокоуровневых графических API (OpenGL, Vulkan) явялется то, что они имеют разные аспекты графической архитектуры в компьютерных системах, каждый из которых выполняет уникальные функции. *Функциональное Назначение*: + Display Server'ы: Они управляют выводом графики на экран и взаимодействием с устройствами ввода. Display Server'ы отвечают за управление окнами, обработку событий ввода от клавиатуры и мыши, а также за отрисовку графического интерфейса пользователя. + Графические API (OpenGL, Vulkan): Эти API предоставляют набор инструментов для непосредственного рендеринга графики, включая создание трехмерных сцен, обработку текстур, освещения и теней. Они не занимаются управлением оконами или вводом от пользователей, а сконцентрированы на рендеринге. *Задачи, решение которых предоставляют Display Server'ы*: + Управление Окнами: Display Server'ы упрощают процесс создания и управления окнами, которые служат поверхностями для рендеринга. Они обрабатывают создание, перемещение, изменение размера и рендеринг окон, а также управление фокусом и стеком окон. + Обработка Ввода: Они получают и обрабатывают события ввода от клавиатуры, мыши и других устройств ввода, передавая эти события соответствующим приложениям. + Композитинг: Некоторые Display Server'ы, особенно в современных системах, выполняют композитинг окон, что позволяет создавать эффекты прозрачности, анимации и другие визуальные эффекты на уровне пользовательского интерфейса. + Интеграция с Системой: Display Server'ы обеспечивают важную интеграцию с другими частями системы, такими как системы безопасности, сетевые протоколы (для удаленного доступа к графическому интерфейсу) и многое другое. + Мультипользовательская Среда: В некоторых случаях, Display Server'ы позволяют поддерживать мультипользовательские сессии и удаленный доступ к графическим интерфейсам. Так же стоит упомянуть, что Display Server'ы так же используют низкоуровневый API DRM, для выполнения приведеных выше задач. При использовании высокоуровневых API (OpenGL, Vulkan) с Display Server'ом второй является лишь прослойкой для организации процессы рендера, как и было сказано выше. == Desktop X11 и Wayland === Архитектура и Особенности X Window System (X) *Архитектура* - Центральная Роль X Server: В традиционной архитектуре X Window System, X Server играет центральную роль, управляя всеми операциями отображения и ввода. - Комплексность и Модульность: X охватывает широкий спектр функций, от управления ресурсами PCI до управления отображением и прямого рендеринга. Со временем, множество функций было вынесено из X Server в клиентские библиотеки и драйверы ядра. *Особенности* - Отсутствие Стандартизации: В X есть некоторые ограничения, такие как сложность реализации современных функций, например, композиции и управления вводом. - Модульность. Со временем, функции X Windows System, такие как рендеринг шрифтов (Freetype и Fontconfig), управление памятью и непостредственный рендеринг (Direct Rendering Infrastructure), Display Management (XRandR), были перенесены из X Server в отдельные библиотеки и модули ядра, что привело к более модульной и гибкой архитектуре. === Архитектура и Особенности Wayland *Архитектура* - Сервер и Протокол Wayland является как новым протоколом дисплейного сервера, так и его реализацией. Wayland построен на компонентах, уже существующих в экосистеме Linux, может использовать графические приложения (клиенты), созданные для X Windows System. - Упрощенная Архитектура: В отличие от X, Wayland упрощает многие процессы, предоставляя клиентам возможность управления своими окнами и содержимым. *Особенности* - Прямой Контроль и Рендеринг: Приложения в Wayland могут выделять собственные буферы и напрямую рендерить содержимое окон, используя аппаратное ускорение или качественные программные реализации. - Упрощение Управления Окнами и Композиции: Управление окнами и композиция полностью осуществляются сервером, что снижает сложность и улучшает производительность за счет уменьшения переключений контекста. - Фокус на Клиентских Приложениях: Wayland оставляет процесс рендеринга на стороне клиента, в то время как управление памятью и буферами осуществляется через системные интерфейсы. #align(center)[ #stack(dir: ltr, image("./images/x-architecture.png", height: 200pt), image("./images/wayland-architecture.png", height: 200pt) ) _Сравнение пайплайна обработки событий X Windows System и Wayland. Видно, что X Window System использует более сложную и многоуровневую архитектуру для обработки событий ввода, что может привести к большей задержке и увеличению сложности в обработке событий._ ] Таким образом *X Window System* является более старой и сложной системой с высокой степенью модульности и интеграции различных компонентов. Подходит для более сложных и многофункциональных систем. *Wayland* в свою очередь является более современный и упрощенный подход, сосредоточенный на улучшении производительности и упрощении архитектуры. Предоставляет клиентам больше контроля над рендерингом и управлением окнами. Wayland предлагает более современное и упрощенное решение для современных графических систем. == Mobile Android Surface Flinger Для мобильных устройств на системе Android (основанной на Linux) средствами компании Google разработан собственный Display Server -- Surface Flinger, оптимизированных для карманных устройств. = Заключение Мы рассмотрели ключевые аспекты и эволюцию системы рендеринга в Linux, начиная от низкоуровневых компонентов, таких как Direct Rendering Manager (DRM), до высокоуровневых графических API и Display Server'ов. Повторение ключевых особенностей: 1. *DRM и Его Роль*: DRM оказался важным звеном в цепочке рендеринга, обеспечивая эффективное взаимодействие между аппаратным обеспечением и программными компонентами системы. Эволюция DRM и его интеграция с графическими API, такими как OpenGL и Vulkan, позволила повысить производительность и эффективность графических операций в Linux. 2. *Высокоуровневые API*: OpenGL и Vulkan представляют собой ключевые инструменты для создания сложной графики и игр. Их развитие и адаптация к современным требованиям позволили разработчикам максимально использовать возможности современных GPU. 3. *Развитие Display Server'ов*: Мы обсудили эволюцию от X Window System к Wayland, подчеркнув, как изменения в архитектуре Display Server'ов отражают потребности современных графических систем. Wayland, предлагая более прямой и эффективный способ обработки графических данных и ввода пользователя, демонстрирует тенденции к упрощению и повышению производительности. 4. *Изменения в X Window System*: Вынесение различных модулей из X Server в отдельные библиотеки и компоненты способствовало упрощению системы, повышению ее модульности и улучшению взаимодействия с другими компонентами Linux-экосистемы. В заключение, рассмотрение архитектуры и компонентов системы рендеринга в Linux демонстрирует ее динамичное развитие и адаптацию к меняющимся требованиям в области графических вычислений. Эти изменения не только повысили эффективность и производительность, но и открыли новые горизонты для разработчиков и пользователей системы. #pagebreak() = Ссылки + #link("https://dri.freedesktop.org/docs/drm/gpu/")[freedesctop.org]: GPU Driver Developer's Guide + <NAME>.: Linux Graphics Drivers: an Introduction + #link("https://en.wikipedia.org/wiki/Direct_Rendering_Manager")[wikipedia.org]: Direct Rendering Manager + #link("freedesctop.org")[freedesctop.org]: Direct Rendering Manager (DRM) + #link("https://wiki.archlinux.org/title/kernel_mode_setting")[ArchLinux Wiki]: Kernel mode setting + #link("https://unix.stackexchange.com/questions/733336/what-is-opengls-relationship-with-the-drm", "Informal topic about relationship between OpenGL and DRM")
https://github.com/abd0-omar/cv-resume
https://raw.githubusercontent.com/abd0-omar/cv-resume/main/resume.typ
typst
#import "@preview/modern-cv:0.3.0": * #show: resume.with( author: ( firstname: "Abdelrahman", lastname: "Omar", email: "<EMAIL>", phone: "(+20) 1271803332", github: "abd0-omar", linkedin: "abdelrahman-omar-739126248", address: "Alexandria Egypt", positions: ( "Software Engineer", "Backend Developer", ), ), date: datetime.today().display(), language: "en", colored-headers: true, ) = Education #resume-entry( title: "Alexandria University", location: "Alex, EG", date: "Aug. 2021 - Aug. 2025", description: "B.S. in Computer Science", ) #resume-item[ - Majoring in Computer Science SIM (Software and Industrial Multimedia) 3rd year. ] = Experience #resume-entry( title: "Software Engineering Experience", location: "Alex, EG", date: "2021 - Present", description: "College Student", ) #resume-item[ - Participated in ECPC and got 4th place out of 40 teams. - Volunteered in HackerRank Club as a member of the Academic Committee where taught different people of different ages programming. - #resume-entry( title: text(weight: "light", size: 10pt)[Solved about 300 problems on LeetCode using Rust], location: github-link("abd0-omar/leet-him-code"), ) ] = Projects #resume-entry( title: "Newsletter Email API ", location: [#github-link("abd0-omar/zero2sixty")], date: "Jan. 2024 - Present", description: "Solo Designer/Developer", ) #resume-item[ - Implemented a Newsletter's api in Rust using axum framework and PostgreSQL with Docker and Github Actions. - Wrote extensive unit/integration tests for the api and added logging and metrics. ] #resume-entry( title: "URL-Shortener", location: github-link("abd0-omar/url-shortener"), date: "May 2024 - May 2024", description: "Solo Designer/Developer", ) #resume-item[ - Designed a URL-Shortener using Rust with the framework axum and PostgreSQL along with loggings, metrics and statistics. - Wrote Frontend using HTMX, Tailwind CSS and Askama template engine. ] #resume-entry( title: text("Flutter Mobile Application", baseline: -18pt), location: github-link("halaheltorgoman/Travel-Guide") + text( github-link("abd0-omar/egyptian-arabic-vocab")), date: "Apr. 2024 - present", description: "Designer/Developer of 6 Members", ) #resume-item[ - An all in one travel guide app that includes everything you need in your next travel! - Parsed json apis for translation feature in the app using dart/flutter and scraped the content of a web page to be displayed in the app using rust with unit tests. ] #resume-entry( title: "Slender Man", location: github-link("Jana-Khaled/Slender-Man-Game"), date: "May 2024 - May 2024", description: "Designer/Developer of 2 Members", ) #resume-item[ - A Slender Man clone in unity/c\#. - Implemented A\* algorithm to search for the shortest path of the closest target. ] #resume-entry( title: "Sliding Puzzle Solver", location: github-link("abd0-omar/slidin-puzzle"), date: "Dec. 2023 - Feb. 2024", description: "Solo Designer/Developer", ) #resume-item[ - A Sliding puzzle Solver using A\*, BFS, DFS, Merge sort, Manhattan and hamming distance algorithms. - Backend with Rust Axum with SQLite db, and HTMX, Tailwind and Askama template engine on the frontend. ] = Skills #resume-skill-item( "Languages", (strong("Rust"), "C++", "Java", "C#", "Flutter", "Python", "Zig"), ) #resume-skill-item("Spoken Languages", (strong("English"), strong("Arabic"))) #resume-skill-item( //"Development Tools", text("Development Tools", size: 11.94pt), (strong("Neovim"), strong("Linux"), "Docker", "Git/Github", "VSCode"), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying/0.1.0/README.md
markdown
Apache License 2.0
# [Touying](https://github.com/touying-typ/touying) ![logo](https://github.com/touying-typ/touying/assets/34951714/2aa394d3-2319-4572-aef7-ed3c14b09846) [Touying](https://github.com/touying-typ/touying) (投影 in chinese, /tóuyǐng/, meaning projection) is an object-oriented and efficient package for creating presentation slides in Typst. Touying is a package derived from [Polylux](https://github.com/andreasKroepelin/polylux). Therefore, most concepts and APIs remain consistent with Polylux. You can refer to the [Polylux documentation](https://polylux.dev/book/) for a better understanding of Touying. Compared to Polylux, Touying employs a more object-oriented writing style, capable of simulating **a mutable global singleton**. So, Touying can conveniently access and update "global variables", such as the 'handout-mode' boolean variable. At the same time, you can easily retrieve and modify page parameters by `self.page-args`, avoiding the side effects of creating a new page caused by `#set page(..)`. Additionally, Touying does not rely on `locate` and `counter` for implementing `#pause`, thus offering better performance, albeit with certain limitations. The advantage is that you can use `#pause` inline. The drawback is that `#pause` after set-show rule won't take effect (you must use set-show rule in the `setting` parameter). Currently, `#pause` only works at the outermost level, and it won't work inside layout functions like grid, but you can use the `composer` parameter to add yourself layout function like `utils.side-by-side`. **Warning: It is under development, and the API may change at any time.** ## Implemented Features - [x] **Object-oriented programming:** Singleton `s`, binding methods `utils.methods(s)` and `(self: obj, ..) => {..}` methods. - [x] **Page arguments management:** Instead of using `#set page(..)`, you should use `self.page-args` to retrieve or set page parameters, thereby avoiding unnecessary creation of new pages. - [x] **`#pause` for sequence content:** You can use #pause at the outermost level of a slide, including inline and list. - [x] **`#pause` for layout functions:** You can use the `composer` parameter to add yourself layout function like `utils.side-by-side`, and simply use multiple pos parameters like `#slide[..][..]`. - [x] **Callback-style `uncover`, `only` and `alternatives`:** Based on the concise syntax provided by Polylux, allow precise control of the timing for displaying content. - You should manually control the number of subslides using the `repeat` parameter. - [x] **Transparent cover:** Enable transparent cover using oop syntax like `#let s = (s.methods.enable-transparent-cover)(self: s)`. - [x] **Handout mode:** enable handout mode by `#let s = (s.methods.enable-handout-mode)(self: s)`. - [x] **Fit-to-width and fit-to-height:** Fit-to-width for title in header and fit-to-height for image. - `utils.fit-to-width(grow: true, shrink: true, width, body)` - `utils.fit-to-height(width: none, prescale-width: none, grow: true, shrink: true, height, body)` - [x] **Slides counter:** `states.slide-counter.display() + " / " + states.last-slide-number` and `states.touying-progress(ratio => ..)`. - [x] **Appendix:** Freeze the `last-slide-number` to prevent the slide number from increasing further. - [x] **Sections:** Touying's built-in section support can be used to display the current section title and show progress. - [x] `states.new-section(section)` to register a new section. - [x] `states.current-section` to get the current section. - [x] `states.touying-outline` or `s.methods.touying-outline` to display a outline of sections. - [x] `states.touying-final-sections(sections => ..)` for custom outline display. - [x] `states.touying-progress-with-sections((current-sections: .., final-sections: .., current-slide-number: .., last-slide-number: ..) => ..)` for powerful progress display. - [x] **Pdfpc:** pdfpc support and export `.pdfpc` file without external tool by `typst query` command simply. ## Features to Implement - [ ] **More themes:** Add more themes. - [ ] **Combinable components**: Combinable components for header, footer and sidebar, . - [ ] **Navigation bar**: Navigation bar like [here](https://tex.stackexchange.com/questions/350508/adding-outline-bar-to-the-beamer-for-section-mentioning) by `states.touying-progress-with-sections(..)`. - [ ] **Document:** Add a more detailed document. - [ ] **External viewers:** Integration with external viewers like impress.js and typst-preview. Feel free to suggest any ideas and contribute. ## Dynamic slides We can export `example.pdfpc` file by command `typst query --root . ./examples/example.typ --field value --one "<pdfpc-file>" > ./examples/example.pdfpc` ```typst #import "@preview/touying:0.1.0": s, pause, utils, states, pdfpc, themes #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: [Custom footer]) #let s = (s.methods.enable-transparent-cover)(self: s) #let s = (s.methods.append-preamble)(self: s, pdfpc.config( duration-minutes: 30, start-time: datetime(hour: 14, minute: 10, second: 0), end-time: datetime(hour: 14, minute: 40, second: 0), last-minutes: 5, note-font-size: 12, disable-markdown: false, default-transition: ( type: "push", duration-seconds: 2, angle: ltr, alignment: "vertical", direction: "inward", ), )) // #let s = (s.methods.enable-handout-mode)(self: s) #let (init, slide, touying-outline) = utils.methods(s) #show: init // simple animations #slide[ a simple #pause dynamic #pause slide. ][ second #pause pause. ] // complex animations #slide(setting: body => { set text(fill: blue) body }, repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) in subslide #self.subslide test #uncover("2-")[uncover] function test #only("2-")[only] function #pause and paused text. ]) // multiple pages for one slide #slide[ #lorem(200) test multiple pages ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.methods(s) #slide[ appendix ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/9365bbc4-9e9c-4a78-a1ab-1716d1bf22f2) ## Themes ```typst #import "@preview/touying:0.1.0": s, pause, utils, states, pdfpc, themes #let s = themes.metropolis.register(s, aspect-ratio: "16-9", footer: [Custom footer]) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, title-slide, new-section-slide, focus-slide, touying-outline, alert) = utils.methods(s) #show: init #set text(font: "Fira Sans", weight: "light", size: 20pt) #show math.equation: set text(font: "Fira Math") #set strong(delta: 100) #set par(justify: true) #title-slide( author: [Authors], title: [Title], subtitle: [Subtitle], date: [Date], extra: [Extra], ) #slide(title: [Table of contents])[ #touying-outline() ] #slide(title: [A long long long long long long long long long long long long long long long long long long long long long long long long Title])[ A slide with some maths: $ x_(n+1) = (x_n + a/x_n) / 2 $ #lorem(200) ] #new-section-slide[First section] #slide[ A slide without a title but with #alert[important] infos ] #new-section-slide[Second section] #focus-slide[ Wake up! ] // simple animations #slide[ a simple #pause dynamic slide with #alert[alert] #pause text. ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide, new-section-slide) = utils.methods(s) #new-section-slide[Appendix] #slide[ appendix ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/f08dc948-68b4-45d6-8e87-53ca3fc9912c) ## Acknowledgements Thanks to... - [@andreasKroepelin](https://github.com/andreasKroepelin) for the `polylux` package - [@Enivex](https://github.com/Enivex) for the `metropolis` theme - [@ntjess](https://github.com/ntjess) for contributing to `fit-to-height`, `fit-to-width` and `cover-with-rect`
https://github.com/teoet6/mehatronen-payak
https://raw.githubusercontent.com/teoet6/mehatronen-payak/master/dokumentaciya/dokumentaciya.typ
typst
#set par(first-line-indent: 0cm, leading: 0.50em, justify: true) #set text(lang: "bg", font: "New Computer Modern", hyphenate: false, size: 14pt) #show raw: set text(font: "New Computer Modern Mono") #show math.equation: set text(style: "italic") #show par: set block(spacing: 1.5em) #show heading: set block(above: 1.4em, below: 1em) #set heading(supplement: "Глава") #set figure(supplement: "Фигура") #let печатно = math.upright #let атан2 = math.op(печатно("атан2")) #let корен = math.sqrt #let пи = math.pi #let син = math.op(печатно("син")) #let кос = math.op(печатно("кос")) #let частно = math.frac #let съкращаваме = math.cancel #set heading(numbering: (..nums) => { let heading_funcs = ( (num) => str(num), (num) => "абвгдежзийклмнопрстуфхцчшщъьюя".clusters().at(num - 1), ) nums .pos() .enumerate() .map(((depth, num)) => heading_funcs.at(calc.rem-euclid(depth, heading_funcs.len()))(num)) .join(".") }) #let todo(content) = text(red, content) #let ai(content) = text(blue, content) #page[#grid(rows: (1fr, 1fr, 1fr, 1fr, 1fr), [ #set text(14pt) #set align(center + top) #set par(justify: false) #smallcaps[Технологично училище „Електронни системи“ към Технически университет - София] ], [ #set align(center + horizon) #set text(24pt) #smallcaps[Дипломна работа] #set text(11pt) по професия код 481020 „Системен програмист“ \ специалност код 4810201 „Системно програмиране“ ], align(center + horizon)[#set text(14pt); Тема: Мехатронен паяк], align(bottom)[#grid( columns: (1fr, 1fr), align(left)[Дипломант: \ #text(11pt)[<NAME>]], align(right)[Дипломен ръководител: \ #text(11pt)[<NAME>]], )], align(center + bottom)[#set text(14pt); #smallcaps[София \ 2024]], )] #page[#todo[Задание]] // #page[Отзив на научния ръководител и предложение за рецензент] #page[] #heading(numbering: none)[Увод] #todo[Кратко въведение в областта ( максимум 1 -2 стр.). В края на увода да бъдат поставени целите и задачите на ДР;] #ai[ През последните години в областта на роботиката се наблюдава значителен напредък, като роботите стават все по-сложни и гъвкави. Тъй като роботите продължават да се интегрират все повече в различни индустрии и приложения, нараства необходимостта от роботи, които могат да се ориентират в сложни среди и да изпълняват задачи, които са трудни или опасни за хората. Една от обещаващите области на изследване е разработването на роботи на крака, които могат да преминават през неравен терен и да се ориентират в препятствия с по-голяма лекота, отколкото роботите на колела или гъсенични машини. Настоящата дипломна работа се фокусира върху създаването на четирикрак робот-паяк, който съчетава предимствата на крачната локомоция с гъвкавостта и адаптивността на структурата на краката на паяка. Роботът паяк е проектиран да бъде високо маневрен и способен да се движи в широк спектър от среди - от индустриални условия до сценарии за реакция при бедствия. Разработването на робота-паяк включва няколко ключови предизвикателства, включително проектирането на краката и системата за придвижване на робота, разработването на алгоритми за управление за стабилно и ефективно движение и интегрирането на сензори за възприемане на околната среда и навигация. В настоящата дисертация ще бъдат разгледани тези предизвикателства и ще бъде представен нов подход към проектирането и управлението на четирикрак робот-паяк. Предложеният робот-паяк се основава на предишни изследвания в областта на движението на краката и роботиката, вдъхновена от паяци, но с акцент върху създаването на високо адаптивна и универсална платформа за широк спектър от приложения. Краката на робота са проектирани така, че да осигуряват стабилност и мобилност, а алгоритмите за управление са оптимизирани за енергийна ефективност и маневреност. Освен това роботът-паяк е оборудван с набор от сензори за възприемане на околната среда и навигация, включително камери, лидар и ултразвукови сензори. Потенциалните приложения на робота-паяк са многобройни - от индустриални инспекции и поддръжка до операции по търсене и спасяване в райони, засегнати от бедствия. Съчетавайки предимствата на локомоцията на краката с гъвкавостта на структурата на краката на паяка, роботът паяк представлява значителна стъпка напред в областта на роботиката и има потенциала да революционизира начина, по който подхождаме към сложните задачи в различни индустрии. В следващите глави ще разгледаме подробно проектирането и разработването на робота паяк, включително механичната конструкция на краката, алгоритмите за управление за стабилно и ефективно движение и интегрирането на сензори за възприемане на околната среда и навигация. Ще представим и експериментални резултати, демонстриращи възможностите на робота и потенциалните му приложения. ] = Проучване #todo[Представлява проучвателната част на ДР. Прави се преглед на съществуващи хардуерни разработки, на използваната елементна база, основни принципи и методи за обработка на сигнали и информация ( максимум 8-10 страници) ;] #todo[esp32] == Свобода <свобода> #ai[ Свободният софтуер, известен също като libre software, се отнася до компютърен софтуер, който се разпространява при условия, позволяващи на потребителите да имат достъп до изходния код на софтуера, да го променят и разпространяват. Терминът "свободен" в свободния софтуер се отнася до свободата, а не до цената, което означава, че потребителите имат свободата да използват, изучават, променят и разпространяват софтуера, без да е необходимо да плащат лицензионни такси или възнаграждения. Концепцията за свободен софтуер се основава на четири основни свободи, както са определени от Фондацията за свободен софтуер: - *Свобода 0:* Свободата да се използва програмата за всякакви цели. - *Свобода 1:* Свободата да изучавате как работи програмата и да я променяте, за да я накарате да прави това, което желаете. - *Свобода 2:* Свободата да разпространявате копия на програмата, за да можете да помагате на други хора. - *Свобода 3:* Свободата да разпространявате копия на променените от вас версии на други хора. Свободният софтуер често се разработва и поддържа от общности от доброволци и организации, които допринасят за развитието и подобряването на софтуера. Тези общности често използват модели за съвместна разработка, като например разработване на софтуер с отворен код, за да създават висококачествен софтуер, който е свободно достъпен за всички. Свободният софтуер има няколко предимства пред несвободния софтуер. От една страна, той позволява на потребителите да персонализират и променят софтуера, за да отговаря на техните специфични нужди. Той също така насърчава прозрачността, тъй като потребителите имат достъп до изходния код на софтуера и могат да го проверяват за потенциални уязвимости в сигурността или други проблеми. Освен това свободният софтуер може да спомогне за намаляване на разходите на организациите и физическите лица, тъй като от тях не се изисква да плащат лицензионни такси или възнаграждения. Примери за популярен свободен софтуер са операционната система Linux, уеб сървърът Apache, софтуерът за редактиране на изображения GIMP и пакетът за производителност LibreOffice. Като насърчава сътрудничеството, прозрачността и свободата, свободният софтуер се е превърнал в съществена част от съвременния софтуерен пейзаж. ] == Микроконтролер _Микроконтролерът_ е компактна интегрална схема, предназначена за управление на определена дейност или набор от дейности в дадена вградена система. Фактически, микроконтролерът представлява малък компютър под формата на чип, снабден с процесор, памет и периферни интерфейси. Той може да изпълнява инструкции, да обработва данни и да комуникира с други устройства. Микроконтролерите са неизменна част от модерният свят. Срещат се в автомобилистиката, индустрията, медицинските уреди, авиацията, потребителските уреди, земеделието и почти всички други отрасли. Проектирани са по такъв начин, че да имат много възможности, но и да бъдат сравнително евтини. Поради широкият обхват на термина, микроконтролерите се срещат в множество разновидности и се различават помежду си по много начини. Въпреки това повечето микроконтролери имат следните части: - *Централeн процесор* Централният процесор представлява _мозъкът_ на микроконтролера. Той отговаря за изпълнението на инструкциите и управлява цялостната работа на устройството. Обикновено той включва аритметично-логическо устройство за извършване на математически и логически операции. Централният процесор е способен условно да изпълнява една или друга част на програмата. Това негово свойство му позволява да изпълнява сложни алгоритми, а не само да пресмята математически формули. - *Памет* Микроконтролерите имат вградена в чипа памет за съхранение на инструкции и данни. Тази памет може да бъде разделена на няколко категории, включително: - *Постоянна памет* #footnote[В англоезичната литература се среща като _ROM (read only memory)_] Този вид памет се използва за съхранение на фърмуера на микроконтролера. Обикновено постоянната памет е енергонезависима, което означава, че съдържанието ѝ се пази независимо от наличието на захранване. - *Памет с произволен достъп* Още наречена _оперативна памет_ или _работна памет_. Използва се за съхранение на данни които трябва да се достъпват и променят по време на работата на микроконтролера. Често тази памет е енергозависима, което означава, че нейното съдържание се изтрива при загуба на захранване. - *Електрически изтриваема програмируема постоянна памет* #footnote[В англоезичната литература се среща като _EEPROM (electrically erasable programmable ROM)_] Вид енергонезависима памет, която може да се изтрива и препрограмира по електронен път. В нея се съхранява кода на потребителя по време на програмиране на микроконтролера, както и конфигурационни данни. - *Периферни интерфейси* Микроконтролерите обикновено включват различни периферни интерфейси за комуникация с други устройства или сензори. Примери за такива интерфейси са: - *Аналогово-цифрови преобразуватели (АЦП)* Позволяват на микроконтролера да преобразува входни аналогови сигнали в цифрови стойностти, и съответно да може да ги обработва. Повечето АЦП-та преобразуват напрежение, но съществуват и такива, които преобразуват ток. Всяко АЦП има характеристики, като резолюция, точност, скорост и т.н. - *Цифрово-аналогови преобразуватели (ЦАП)* Позволяват на микроконтролера да създава аналогови сигнали. Фактически ЦАП представлява реципрочният интерфейс на АЦП и като такъв споделя много от неговите характеристики (резолюция, точност, скорост и т.н.). Тези интерфейси са по-скъпи за производство и заради това се срещат по рядко в микроконтролерите. На тяхно място често се използва шим (@шим). - *Серийни комуникационни интерфейси* Позволяват на микроконтролера да комуникира с други устройства, използвайки серийни комуникационни протоколи. Примери за такива протоколи са _UART_ _SPI_ и _I²C_ - *Таймери и броячи* Таймерите и броячите позволяват на микроконтролера да измерва времеви интервали и реагира на времеви интервали. Тези части могат да се използват за разнообразни цели, като например генериране на сигнали за широчинно-импулсна модулация (ШИМ) или за насрочване на здачачи във времето. - *Входно-изходни щифтове с общо предназначение (ВИЩОП #footnote[Терминът _ВИЩОП_ не е общоприет. В англоезичната литература това понятие се среща като _GPIO_.])* Чрез тези щифтове, микроконтролерът взаимодейства със сензори и други компютри. Отделните ВИЩОП-и на един микроконтролер могат да имат различаващи се възможностти. Някои от възможностите включват: - *Цифров вход/изход:* тези щифтове могат да се използват за връзка цифрови компоненти, като копчета и светодиоди. - *Аналогов вход/изход:* тези щифтове са свързани с АЦП/ЦАП и могат да се използват за връзка с аналогови компоненти. Поради високата цена на ЦАП-овете, микроконтролерите с аналогов изход за по-малобройни. - *Шим изход:* тези щифтове поддържат шим (@шим). Често се използват като алтернатива на аналогови изходи. Използват се при управление на серводвигателя SG90 (@серво). - *Комуникационни интерфейси:* това са щифтове които поддържат даден вид серийна комуникация, например _UART_ _SPI_ и _I²C_. Често се случва щифтовете да имат комбинирани възможностти (например шим и I²C). В такъв случай потребителят няма как да използва и двете. Това явление трябва да се взима предвид при проектирането на система и избирането на микроконтролер. Фактически микроконтролерите се явяват неизменна част от всеки проект в областта на вградените системи. Вградените в тях комуникации и ниските им цени им позволяват да бъдат използвани за голям набор от задачи. https://bg.wikipedia.org/wiki/%D0%90%D1%80%D0%B8%D1%82%D0%BC%D0%B5%D1%82%D0%B8%D1%87%D0%BD%D0%BE-%D0%BB%D0%BE%D0%B3%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%BE_%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2%D0%BE https://bg.wikipedia.org/wiki/ROM https://bg.wikipedia.org/wiki/%D0%9F%D0%B0%D0%BC%D0%B5%D1%82_%D1%81_%D0%BF%D1%80%D0%BE%D0%B8%D0%B7%D0%B2%D0%BE%D0%BB%D0%B5%D0%BD_%D0%B4%D0%BE%D1%81%D1%82%D1%8A%D0%BF https://bg.glosbe.com/en/bg/read-only%20memory === Ардуйно <ардуйно> _Ардуйно_ е свободна (@свобода) платформа за електроника, целяща да предостави лесен за използване хардуер и софтуер. Създадена е, за да направи електрониката по-достъпна за хората без професионално минало в нея. Платформата _Ардуйно_ се състои от две основни части - множество модели платки с микроконтролер и среда за разработка. Средата за разработка на Ардуйно е софтуерно приложение, работещо на Уиндоус, Мак, Линукс и в облака. Основана е на средата за разработване на компютърно изкуство _Processing_. Тя позволява на потребителя да извършва ключови действия при разработката на проект: / Инсталиране на библиотеки: Средата позволява лесно да се добавят библиотеки, писани от други. Тези библиотеки често абстрахират определен хардуер и предоставят прост начин за взаимодействие с него. Споделянето на код в общността е насърчено чрез тази възможност на средата. / Писане на код: Ардуйно има собствен език за програмиране, основан на езиците _Wiring_ и _Ц++_. Средата предлага на потребителя автоматично довършване по време на писане, оцветяване на различните синтактични части на кода и автоматично форматиране. / Качване върху платката: #todo[] / Отстраняване на бъгове: #todo[] Платките на Ардуйно се предлагат в множество модели разделени в няколко главни семейства: - *Нано* e набор от малки платки с разнообразни функции. В зависимост от нуждата, платките могат да бъдат както по-основни, като _Nano Every_, така и по-разширени, като _Nano 33 BLE Sense_ и _Nano RP2040 Connect_. По-разширените модели разполагат с радиомодули за Bluetooth и Wi-Fi и с вградени сензори за измерване на температура, влажност, налягане, жестове, микрофон и други. Съвместими са с MicroPython и поддържат машинно обучение. - *Мкр* представлява група от платки, щитове и носители, които могат да се комбинират, за да създадат разнообразни проекти без нужда от допълнителни схеми. Всяка платка, изключае _MKR Zero_, е снабдена с радиомодул позволяващ Wi-Fi, Bluetooth®, LoRa®, Sigfox и NB-IoT комуникации. Всички платки в тази серия използват енергийно ефективния 32-битов процесор _Cortex-M0 SAMD21_. Обурудвани са и с криптографски чип за осигурена комуникация. \ Щитовете и носителите на Мкр се използват за разширяване на възможностите на платката. Например, те позволяват добавянето на сензори за околната среда, GPS, Ethernet, управление на двигатели и RGB матрица. - *Класическото семейство* вклучва платки като прословутото _Ардуйно Уно_. В него са и моделите _Леонардо_ и _Микро_. Тези платки играят ключова роля в Ардуйно проекта и се ползват с голям успех през годините, като тяхното влияние не спира да расте. - *Мега* e семейство от платки, предоставящи голяма изчислителна способност и голям брой вищопи. Ардуйно има голяма и активна общност от потребители. В нея те допринасят за развитието на платформата, като споделят своите проекти и знания чрез форуми, блогове и други онлайн ресурси. С времето е създадена огромна библиотека от код и уроци. Това улеснява начинаещите потребители да създадат първите си проекти, а опитните - да изследват нови идеи. Гореописаните качества правят Ардуйно платформа, която съчетава свободен и лесен за използване хардуер и софтуер, за да направи електрониката достъпна за широк кръг потребители. Гъвкавостта, достъпността и подкрепата на общността я правят идеална платформа за създаване на прототипи, обучение и експериментиране с електрониката и програмирането. https://www.arduino.cc/en/Guide/Introduction https://docs.arduino.cc/software/ide/#ide-v2 https://docs.arduino.cc/arduino-cloud/guides/cloud-editor/ https://www.arduino.cc/en/hardware https://processing.org/ http://wiring.org.co/ === Есп32 _Есп32_ е серия евтини микроконтролери с ниска консумация на енергия, вградени в чип. Всички издания от серията имат вградени Wi-Fi и Bluetooth с два режима. Микроконтролерите са разработени и продавани от китайската компания _Espressif Systems_. Серията _Есп32_ съдържа няколко микроконтролера, различаващи се по тактова честота (от 160МХц до 240МХц) и оперативна памет (от 128кБ до 520кБ). Микроконтролерите Есп32 са високоинтегрирани, като съдържат широк набор от периферни интерфейси, включително SPI, I²S, I²C, UART, SD/SDIO, CSI-2, DMA и шим и др. Те разполагат и с няколко функции за сигурност, като защитено зареждане, криптиране на флаш памет и защитен JTAG, което ги прави подходящи за широк спектър от приложения за IoT. Едно от най-значимите предимства на микроконтролерите ESP32 са техните интегрирани Wi-Fi и Bluetooth възможности, които им позволяват да участват в безжични комуникационни мрежи и да се свързват лесно с други устройства. Wi-Fi модулът поддържа протоколи IEEE 802.11 b/g/n/e/k, а Bluetooth модулът поддържа протоколи Bluetooth Classic и BLE (Bluetooth Low Energy). Микроконтролерите Есп32 могат да се програмират с помощта на различни среди за разработка. Някои от тях са: - *Арудийно* Както е споменато в @ардуйно, платформата предоставя среда за разработка. Тази среда може да се използва за да се програмират микроконтролери, които не са пряко свързани с Ардуйно. Използвайки нея, потребителя получава удобен и познат за него интерфейс, който улеснява начинаещите потребители в програмирането на Есп32. Интерфейсът е и портативен, тъй като е достъпен на Ундоус, Мак и Линукс. Ардуйно средата дава и достъп до голямата общност на платформата, което означава голям брой ресурси и примери. Освен ресурси и примери, общността е произвела и голям набор от библиотеки, които в някои случаи могат да спестят много време и усилия при изпълнението на проект. Използването на Ардуйно средата носи своите недостатъци. Такива например са не толкова добрата инфраструктура за отстраняване на грешки, което може значително да забави изпълнението на проекта. Използвнето на Ардуйно платформата ограничава достъпа до функции предоставени от по-силният Есп32. Най-сериозните такива функции са възможността за няколко нишки и използването на Bluetooth. Ограничен е и достъпа до по-силни функции на програмният език, като шаблони и пространства от имена. - *Ръст* #ai[ 1. Безопасност на паметта: Rust е език, безопасен за паметта, което означава, че предотвратява често срещани грешки в паметта, като например препращане към нулев указател, препълване на буфера и състезания с данни. Това е особено важно за вградени системи като ESP32, където паметта е ограничена и грешките могат да имат тежки последици. 2. Производителност: Rust има производителност, подобна на тази на C и C++, което го прави отличен избор за системно програмиране. Ограничените ресурси на ESP32 изискват ефективно използване на паметта и изчислителната мощ, което прави производителността на Rust значително предимство. 3. Съвместимост: Моделът на собственост на Rust и вградената поддръжка на паралелност го правят отличен избор за разработване на паралелни системи. Възможностите на WiFi и Bluetooth на ESP32 изискват ефективна обработка на множество връзки и потоци от данни, което прави ценна функцията за едновременност на Rust. 4. Оперативна съвместимост: Rust има добра оперативна съвместимост с езика C, което позволява използването на съществуващи библиотеки и драйвери на C за ESP32. Това може да спести време и усилия при разработването на приложения за ESP32. 5. Общност: Rust има разрастваща се и активна общност, което означава, че има много налични ресурси за обучение и отстраняване на проблеми. Това е особено важно за начинаещите, които не са запознати с Rust или с разработването на вградени системи. 1. Крива на обучение: Rust има стръмна крива на усвояване, особено за тези, които са нови в системното програмиране. Синтаксисът и концепциите могат да бъдат предизвикателство за усвояване, а документацията може да бъде оскъдна в някои области. 2. Инструменти: Въпреки че инструментариумът на Rust се подобрява, той все още не е толкова зрял, колкото други езици. Ограничените ресурси на ESP32 могат да направят дебъгването и профилирането по-трудни, а липсата на зрели инструменти може да задълбочи тези проблеми. 3. Размер: Размерът на двоичните файлове на Rust може да бъде по-голям от този на C или C++, което може да бъде проблем за вградените системи с ограничена памет. Това може да се намали чрез използване на техники като оптимизация по време на свързване и премахване на кода. 4. Екосистема: Въпреки че екосистемата на Rust се разраства, тя все още не е толкова обширна, колкото при други езици. Това може да направи намирането на библиотеки и драйвери по-трудно и да изисква повече време и усилия за разработване на персонализирани решения. 5. Хардуерна поддръжка: Поддръжката на хардуер в Rust се подобрява, но все още не е толкова обширна, колкото при други езици. Това може да направи по-трудно свързването с хардуерната периферия на ESP32 и може да изисква повече програмиране на ниско ниво. ] - *esp-idf* #ai[ 1. Изчерпателно: ESP-IDF предоставя изчерпателен набор от софтуерни компоненти, драйвери и API за чиповете от сериите ESP32 и ESP32-S. Той включва широк набор от функции, като WiFi, Bluetooth и BLE, които могат да се използват за разработване на IoT устройства. 2. Кросплатформеност: ESP-IDF поддържа междуплатформена разработка, което означава, че разработчиците могат да използват Windows, Linux или macOS, за да разработват приложения за ESP32. Това може да спести време и усилия, тъй като разработчиците могат да използват една и съща среда за разработка и инструменти за различни платформи. 3. Документация: ESP-IDF има обширна документация, която включва ръководства за започване на работа, ръководства за програмиране и референции за API. Това може да помогне на разработчиците бързо да научат как да използват ESP-IDF и да разработват приложения за ESP32. 4. Примери: ESP-IDF предоставя широк набор от примери, които демонстрират как да се използват различни функции на ESP32. Тези примери могат да помогнат на разработчиците бързо да научат как да използват ESP-IDF и да разработват приложения за ESP32. 5. Общност: ESP-IDF разполага с голяма и активна общност от разработчици, които могат да осигурят поддръжка и да помогнат за отстраняване на проблеми. Това може да бъде особено полезно за новите разработчици, които се учат как да използват ESP-IDF и да разработват приложения за ESP32. 1. Сложност: ESP-IDF може да бъде сложен и непосилен за новите разработчици. Тя включва широк набор от функции и API, които могат да бъдат предизвикателство за научаване и използване. 2. Крива на обучение: ESP-IDF има стръмна крива на обучение, особено за разработчици, които са нови в разработването на вградени системи. Тя изисква добро разбиране на програмирането на C и на концепциите за вградени системи. 3. Отстраняване на грешки: Отстраняването на грешки в ESP-IDF приложенията може да бъде предизвикателство, особено за новите разработчици. Ограничените ресурси на ESP32 и липсата на инструменти за отстраняване на грешки могат да затруднят идентифицирането и отстраняването на проблеми. 4. Размер: ESP-IDF приложенията могат да бъдат големи и да консумират значително количество памет. Това може да е проблем за разработчиците, които разработват приложения за устройства с ограничени ресурси. 5. Грешки: ESP-IDF все още е в процес на активна разработка и е възможно да има грешки и проблеми, които не са идентифицирани или отстранени. Това може да бъде разочароващо за разработчиците, които се сблъскват с проблеми и трябва да чакат за поправки или заобиколни решения. ] == Електродвигател _Електродвигателят_ (още известен като _електромотор_ или просто _мотор_) е машина преобразуваща електрическата енергия в кинетична такава, най-често чрез електромагнетизъм. Всеки двигател има подвижна и неподвижна част, наречени съответно _ротор_ и _статор_. Основната цел на проекта е движението на паяка, следователно трябва да се избере подходящ двигател. Разглеждат се няколко възможности: #todo[https://bg.wikipedia.org/wiki/%D0%A1%D0%B5%D1%80%D0%B2%D0%BE%D0%BC%D0%BE%D1%82%D0%BE%D1%80] === Постояннотоков двигател Подвижната част от постояннотоковият двигател представлява електромагнит, а неподвижната - магнит. Електромагнитът е захранен по такъв начин, че полюсите му съвпадат с тези на магнита. Поради действащите сили ротора се завърта, а с неговото завъртане полюсите се променят, започвайки процесът наново. Употребата на двигателят е много лесна: захранва се с определено напрежение. Посоката на въртене зависи от поляритета на подаденото напрежение. Не може пряко да се управлява скоростта на движение, което прави този двигател неподходящ за проекта. #ai[ Постоянно токовите мотори са изключително разпространени в различни приложения, включително в индустрията, транспорта, домакинствата и др. Техните предимства включват висока ефективност, лесно управление на скоростта и възможност за работа в широк диапазон от скорости и натоварвания. Те са особено подходящи за приложения, които изискват висока мощност и прецизно контролиране, като например в електрическите превозни средства, фабрики за производство и машини за обработка на материали. ] #todo[фигура] #todo[https://bg.wikipedia.org/wiki/%D0%9F%D0%BE%D1%81%D1%82%D0%BE%D1%8F%D0%BD%D0%BD%D0%BE%D1%82%D0%BE%D0%BA%D0%BE%D0%B2_%D0%B5%D0%BB%D0%B5%D0%BA%D1%82%D1%80%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8_%D0%B4%D0%B2%D0%B8%D0%B3%D0%B0%D1%82%D0%B5%D0%BB] === Стъпков двигател #todo[] #ai[ Стъпковият мотор е вид двигател, който работи чрез последователно движение на стъпките или чековете, които се придвижват в определен ред. Тези стъпки се движат под контрола на електроника и се използват в различни промишлени и научни приложения, както и в различни видове машини. Един от основните компоненти на стъпковия мотор е роторът, който се състои от редица стъпки или чекове, които са аранжирани по специфичен начин. Тези чекове се движат по определен ред и това движение се осигурява от електрически сигнали, които се подават на мотора. В зависимост от конструкцията и приложението, стъпковият мотор може да има различен брой стъпки и конфигурации на чековете. Една от ключовите предимства на стъпковите мотори е тяхната прецизност и контролируемост. Те могат да се придвижват с много малки стъпки, което позволява изключително висока точност при позициониране. Това ги прави идеални за приложения, където се изисква висока прецизност, като например в принтери, CNC машини, медицинска техника и роботика. Освен това, стъпковите мотори са изключително надеждни и издръжливи. Те обикновено не изискват поддръжка и имат дълъг експлоатационен живот. Техните компактни размери и лека конструкция ги правят подходящи за вграждане в различни устройства и системи. В заключение, стъпковите мотори са важен компонент във множество съвременни технологии и приложения, където се изисква висока прецизност, контрол и надежност. Техните уникални характеристики ги правят незаменими в различни индустрии и сектори. ] === Серводвигател <серво> _Серводвигателят_ #footnote[Още известен като _сервомотор_ или просто _серво_. Произлиза от латинското #smallcaps[servus] _слуга_. Пълен български превод би бил _служещ двигател_ или _служедвигател_. Такъв превод не е използван в труда, за да не затрудни читателя.] позволява завъртъне в желано от потребителя положение. Подвижната част е свързана към неподвижната чрез потенциометър, който измерва действителното положение. След като сравни желаното с действителното положение, сервото задвижва постояннотоков двигател в нужната посока. Този принцип на действие кара двигателя да оказва съпротивление, когато се оказва сила върху ротора (напр. тази на гравитацията). #ai[Основните компоненти на серво мотора включват самия двигател, енкодер (често оптичен), усилвател (за управление на електромотора), и контролер (който получава команди и генерира сигнали за управление на мотора). Енкодерът играе ключова роля за определяне на текущата позиция и скорост на мотора, като предоставя обратна връзка към контролера.] Единствен недостатък на серводвигателя е ограниченият му размах, причинен от потенциометъра в него. Докато повечето двигатели се въртят безкрайно, сервото има определен ъгъл на завъртане, рядко по-голям от 180°. Този недостатък не оказва влияние на проекта. За всички стави на крака е избран серводвигател sg90. Той има следните свойства: - захранва се на 5В постоянно напрежение - управлява се чрез широчинно-импулсна модулация (@шим), - тежи 9г, - прилага 1,4кгсм тяга, == Потенциометър #ai[ Потенциометърът е електронен компонент, който играе важна роля в регулирането на съпротивлението в електрическите вериги. Той се използва за промяна на съпротивлението чрез промяна на позицията на подвижния контакт върху проводниковата пътека. Потенциометрите се предлагат в различни размери и типове, като най-общо срещаните са линеен и обратен (логаритмичен) тип. Линейните потенциометри имат постоянно увеличаващо се съпротивление в целия ход на подвижния контакт, докато обратните потенциометри имат съпротивление, което се увеличава нелинеарно с преместването на контакта. Обратните потенциометри се използват по-често в аудиоапаратурата, тъй като човешкото ухо е по-чувствително към логаритмични промени в силата на звука. Потенциометрите се използват в широк спектър от приложения, включително усилватели, регулатори на осветление, силови източници, аудиоапаратура, инструменти за измерване и много други. Техните малки размери и удобството за интеграция ги правят незаменими компоненти в много електронни устройства и системи. ] #todo[фигура] #todo[https://www.ardboard.com/index.php?route=product/product&product_id=61&search=sg90] = Изисквания #todo[Да съдържа функционалните и електрическите изисквания към проектираното устройство (точка 2.1.), блокова схема на устройството, описание на предназначението и функциите на отделните блокове ( максимум 6-8 страници );] #todo[брой крака] #todo[ААА срещу гейската литиево-ьонна батерия] #todo[Комуникация] = Електроника #todo[Същинската част на ДР с най - голям обем. Да включва описание на принципните електрически схеми на отделните блокове или на цялото устройство, информация за използваната елементна база, изчислителна записка, симулации на цялото устройство или на отделни блокове, графики, характеристики, анализи ( максимум 10-15 страници );] #figure(image("blok-shema.png", width: 100%), caption: [Блок схема на проекта]) == Широчинно-импулсна модулация <шим> #todo[източници] #todo[фигура] Широчинно-импулсната модулация (шим #footnote[Правилно е да се пише _ШИМ_. Тъй като терминът се среща често в труда, е написан с малки букви, за да не натоварва читателя.]) е популярен и ефективен подход, използван за управление на мощността, подавана към електрически товар, който може да бъде двигател, лампа или друго електрическо устройство, както и за комуникация. Това е вид техника за модулация, която се състои в бързо превключване на сигнал между две нива, обикновено високо и ниско, с променлив работен цикъл. Терминът _широчина на импулса_ се отнася до продължителността или дължината на високия сигнал. Терминът _коефициент на запълване_ се отнася до съотношението между широчината на импулса и неговия период. С други думи, шим е техника, при която се създава поредица от импулси с фиксирана честота, но с променлива ширина. Шим сигналите могат да се генерират по различни начини, включително чрез цифрово-сигнални процесори (DSP), микроконтролери и специализирани интегрални схеми (ИС). Изборът на подход зависи от конкретното приложение и изискваната производителност. Избраният за проекта микроконтролерът Есп32, включва хардуерна поддръжка на шим. Есп32 разполага с 16 шим канала, като всеки от тях има собствен набор от конфигурационни регистри. Това позволява независимо управление достатъчно шим сигнали за повечето проекти. 16-те канала на Есп32 са разделени на две групи от по 8 канала. Едната група канали работи в режим на висока скорост. Този режим е реализиран хардуерно и предлага автоматична и безпроблемна промяна на коефициента на запълване. Другата група канали работи в режим на ниска скорост, като коефициентът на запълване трябва да се променя софтуерно. Всяка група канали може да използва различни източници на тактова честота. Поради ниската честота, изисквана при работата със серводвигателите, разликата между бързите и бавните канали не оказва влияние. https://docs.espressif.com/projects/esp-idf/en/v4.3/esp32/api-reference/peripherals/ledc.html?highlight=ledc_timer_config_t#_CPPv419ledc_timer_config_t Избраният за проекта серводвигател (@серво) се управлява с шим сигнал с честота 50Хц, което е еквивалентно на период от 20мс. При този подход завъртането на двигателя зависи от широчината на импулса на шим сигнала. Според документацията #todo[коя] ъглите между 0° и 180° съответстват на широчини на импулса между 1мс и 2мс. Въпреки това, експериментите с мотора, както и обратната връзка от други клиенти #todo[източник], показват, че действителните широчини на импулса са между 0.5мс и 2.5мс, като документираните 1мс до 2мс позволяват само 90° размах. Точното преобразуване от желан ъгъл към шим сигнал е детайлно обяснено в @серво-контролер. В нея се взима предвид експериментално доказания обхват от 0.5мс до 2.5мс. = Механика #todo[Да съдържа описание на особеностите при проектирането на печатните платки с конструктивна CAD система, графичните оригинали на страна елементи и страна спойки, вътрешни и захранващи слоеве на печатните платки, ситопечат, спецификация на елементите и използваните корпуси ( максимум 5-8 страници) ;] #todo[кад] = Логика #todo[Да съдържа описание на алгоритъма и сорс кода на управляващия софтуер със съответна коментарна част и обяснения ( максимум 5-10 страници). ] == Серво контролер <серво-контролер> Както пише в @шим, завъртанията между 0° и 180° отговарят на широчина на импулса между 0.5мс и 2.5мс: $ "широчина на импулса" &= частно("завъртане", 180°)2"мс" + 0.5"мс" \ &= частно("завъртане" + 45°, 90°)"мс" $ При есп32 микроконтролера, шим сигнала се управлява чрез параметър `duty_cycle`, който спазва следната закономерност: $ частно(печатно("duty_cycle"), 2^"резолюция") = частно("широчина на импулса", "период") $ Знаейки, че $"период" = 20"мс"$, и че за 50Хц $"резолюция" = 20$ можем да изчислим `duty_cycle`: $ частно(печатно("duty_cycle"), 2^20) &= частно(частно("завъртане" + 45°, 90°)съкращаваме("мс"), 20съкращаваме("мс")) \ печатно("duty_cycle") &= частно("завъртане" + 45°, 1800°) 2^20 &&печатно(#[ако _завъртане_ е в градуси]) \ печатно("duty_cycle") &= частно("завъртане" + частно(пи, 4), 10пи) 2^20 &&печатно(#[ако _завъртане_ е в радиани]) $ https://gist.github.com/benpeoples/3aa57bffc0f26ede6623ca520f26628c https://raspberrypi.stackexchange.com/questions/106858/what-is-the-proper-calculation-of-duty-cycle-range-for-the-sg90-servo https://www.friendlywire.com/projects/ne555-servo-safe/SG90-datasheet.pdf == Обратна кинематика #ai[ Обратната кинематика е ключов концепт в областта на роботиката и машиностроенето. Тя се отнася до методите и алгоритмите, използвани за определяне на позицията, ориентацията и движението на механични системи, като например роботи или манипулатори. Във връзка с това обратната кинематика се фокусира върху преобразуването на желаното пространствено движение (например координатите на крайната точка на робота) в съответните степени на свобода или параметри на системата (например ъгли на съчлененията). За разлика от пряката кинематика, където се изчисляват пространствените параметри на механичната система, като се имат предвид параметрите на съчлененията, обратната кинематика прави обратното: от познатите параметри на пространството се определят параметрите на съчлененията. Това е особено полезно при програмирането на роботи, където операторът желае да дефинира пътя или позицията, която трябва да бъде достигната от робота, и роботът трябва автоматично да изчисли как да промени позицията на своите съчленения, за да постигне желаната позиция. Обратната кинематика играе ключова роля във виртуалната реалност, компютърната анимация и медицинските приложения, като например симулацията на движението на човешкия скелет или операции с роботи в медицината. Тя предоставя мощни инструменти за управление и контрол на механични системи, които се използват в широка гама от области, включително производството, автоматизацията и изследователската дейност. ] Подвижните части на всеки един крак са два кокъла $к_1$ и $к_2$ и три серво мотора $с_0$, $с_1$ и $с_2$. Задачата е имайки желани кординати $ъ$, $ю$ и $в$ и дължините на костите, да разберем стойностите на трите серво мотора които ще закарат стъпалото в тези кординати. #figure(image("goren.png", width: 50%), caption: [Горен изглед]) $ с_0 &= атан2(ъ, ю) &печатно("по определение") \ р &= корен(ъ^2 + ю^2) &печатно("по питагоровата теорема") \ $ #figure(image("straniqen.png", width: 50%), caption: [Страничен изглед]) $ &к = корен(р^2 + в^2) &печатно("по питагоровата теорема") \ $ $ &к^2 = к_1^2 + к_2^2 - 2к_1к_2кос(с_2 - пи) &печатно("по косинусовата теорема") \ &с_2 = пи + кос^(-1)частно(к^2 - к_1^2 - к_2^2, -2к_1к_2) \ &с_2 = пи + кос^(-1)частно(к_1^2 + к_2^2 - р^2 - в^2, 2к_1к_2) \ $ $ &theta = атан2(в, р) $ $ &angle.spheric к_1к_2 = с_1 - theta \ &к_2^2 = к^2 + к_2^2 - 2к к_2кос(с_1 - theta) &печатно("по косинусовата теорема") \ &с_1 = theta + кос^(-1)частно(к_2^2 - к^2 - к_1^2, -2к к_1) \ &с_1 = атан2(в, р) + кос^(-1)частно(р^2 + в^2 + к_1^2 - к_2^2, 2к_1 корен(р^2 + в^2)) \ $ #todo[свържи уравненията] == Походка #todo[разсъждения върху един следващ крак] = Изпълнение #todo[Да съдържа описание и особеностите при създаването на работоспособен модел на проектираното устройство, както и фигури със снимки на външния вид на макета или монтираната печатна платка ( максимум 5-6 страници). Може и да липсва, ако няма разработен макет на устройството;] файлът `export.sh` е почти като този даден от espresiff освен че задава IDF_PATH и PS1 #ai[ To use PWM on the ESP32, you first need to configure the desired PWM channel by setting the appropriate registers. This includes selecting the PWM signal's frequency, duty cycle, and output mode (i.e., whether the signal is active-high or active-low). Once configured, the PWM signal can be started and stopped as needed.Here's a high-level overview of the steps required to configure and use PWM on the ESP32:1.Configure the clock system: The ESP32's PWM peripheral uses a clock source to generate the PWM signal. You can configure the clock source and divider to achieve the desired PWM frequency.2.Select a PWM channel: The ESP32 has multiple PWM channels, each with its own set of configuration registers. Choose the appropriate channel for your application.3.Configure the PWM signal: Set the desired frequency, duty cycle, and output mode for the PWM signal.4.Enable the PWM channel: Once configured, enable the PWM channel to start generating the PWM signal.5.Control the PWM signal: You can adjust the duty cycle or stop the PWM signal as needed. ] #heading(numbering: none)[Заключение] #todo[включва обобщение на постиженията в дипломната работа и виждане за усъвършенстване и обогатяване на разработката – 1 страница;] #heading(numbering: none)[Литература] #todo[] // #bilbliography("") = Приложения #todo[] #outline(title: [Съдържание]) _Изкуственият интелект ще замени ли паяците?_
https://github.com/Sparrow1488/Typstio
https://raw.githubusercontent.com/Sparrow1488/Typstio/master/README.md
markdown
# Typstio Откуда брать идеи: https://github.com/FastReports/FastReport/ ### Внешний вид Хочется, чтобы все было предельно визуально понятно и КРАСИВО (функционально). Можно посмотреть на `Miro` пример того, как это можно будет реализовать в `WPF` (со стрелочками, подсказками при вводе привязок данных и прочее). Но при этом **важно** сохранить простоту в коде. ![](./static/Plan.jpg) ### Отрисовка Основную логику построения компонентов я реализую в `WPF`. Перечислю преварительный алгоритм отрисовки: 1. Создание по определенной структуре шаблонов в отчете. 2. Конвертация `WPF` компонентов в `Typst` реалии (`TextBlock` -> текст, `DataGrid` -> таблица и тд). 3. Бла бла бла ## ContentWriter Sample 1 `C#`: ```C# var document = new ContentWriter(); var image = new Image("profile.jpg", width: "20%"); document.Write(new Figure(image, "About me")); document.WriteEmptyBlock(); document.Write(CreateUserTable()); document.WriteEmptyBlock(); document.Write(new Box(c => c.WriteString("Hello from Box"), new Rgb("#ff4136"))); Table CreateUserTable() { var items = new Content[] { _ => { }, c => c.Write(new Strong("Name")), c => c.Write(new Strong("Phone")), c => c.WriteString("1"), c => c.WriteString("Sparrow"), c => c.WriteString("+79531345309").Linebreak() .WriteString("+89231365311") }; return new Table(("auto", "1fr", "1fr"), items, inset: "10pt", align: "horizon"); } ``` Sample 1 `Pdf`: ![Sample-1](./static/sample1.png)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/020_Prologue%20to%20Battle%20for%20Zendikar.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Prologue to Battle for Zendikar", doc) #include "./020 - Prologue to Battle for Zendikar/001_Stirring from Slumber.typ" #include "./020 - Prologue to Battle for Zendikar/002_Drop for Drop.typ" #include "./020 - Prologue to Battle for Zendikar/003_Limits.typ" #include "./020 - Prologue to Battle for Zendikar/004_Catching Up.typ" #include "./020 - Prologue to Battle for Zendikar/005_Unkindness of Ravens.typ" #include "./020 - Prologue to Battle for Zendikar/006_Offers to the Fire.typ" #include "./020 - Prologue to Battle for Zendikar/007_For Zendikar.typ"
https://github.com/AliasQli/Chants-of-Sennaar.typst
https://raw.githubusercontent.com/AliasQli/Chants-of-Sennaar.typst/master/doc.typ
typst
#import "@preview/tidy:0.2.0" #import "index.typ": * #let docs = tidy.parse-module( name: "Chants-of-Sennaar.typst", read("index.typ"), scope: (english: english, say: say, baseDir: baseDir, glyphs: glyphs) ) #tidy.show-module(docs, style: tidy.styles.default)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11280.typ
typst
Apache License 2.0
#let data = ( ("MULTANI LETTER A", "Lo", 0), ("MULTANI LETTER I", "Lo", 0), ("MULTANI LETTER U", "Lo", 0), ("MULTANI LETTER E", "Lo", 0), ("MULTANI LETTER KA", "Lo", 0), ("MULTANI LETTER KHA", "Lo", 0), ("MULTANI LETTER GA", "Lo", 0), (), ("MULTANI LETTER GHA", "Lo", 0), (), ("MULTANI LETTER CA", "Lo", 0), ("MULTANI LETTER CHA", "Lo", 0), ("MULTANI LETTER JA", "Lo", 0), ("MULTANI LETTER JJA", "Lo", 0), (), ("MULTANI LETTER NYA", "Lo", 0), ("MULTANI LETTER TTA", "Lo", 0), ("MULTANI LETTER TTHA", "Lo", 0), ("MULTANI LETTER DDA", "Lo", 0), ("MULTANI LETTER DDDA", "Lo", 0), ("MULTANI LETTER DDHA", "Lo", 0), ("MULTANI LETTER NNA", "Lo", 0), ("MULTANI LETTER TA", "Lo", 0), ("MULTANI LETTER THA", "Lo", 0), ("MULTANI LETTER DA", "Lo", 0), ("MULTANI LETTER DHA", "Lo", 0), ("MULTANI LETTER NA", "Lo", 0), ("MULTANI LETTER PA", "Lo", 0), ("MULTANI LETTER PHA", "Lo", 0), ("MULTANI LETTER BA", "Lo", 0), (), ("MULTANI LETTER BHA", "Lo", 0), ("MULTANI LETTER MA", "Lo", 0), ("MULTANI LETTER YA", "Lo", 0), ("MULTANI LETTER RA", "Lo", 0), ("MULTANI LETTER LA", "Lo", 0), ("MULTANI LETTER VA", "Lo", 0), ("MULTANI LETTER SA", "Lo", 0), ("MULTANI LETTER HA", "Lo", 0), ("MULTANI LETTER RRA", "Lo", 0), ("MULTANI LETTER RHA", "Lo", 0), ("MULTANI SECTION MARK", "Po", 0), )
https://github.com/Zuttergutao/Typstdocs-Zh-CN-
https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/Classified/Cover.typ
typst
// 封面 #[ #set page(header:none,numbering:none) #set align(right) #set terms(separator:[: ]) #place( right, dy:20%, text(weight:700,size:28pt)[一份(不太)简短的Typst介绍], ) #line(start:(0%,25%),end:(100%,25%),length:100%,stroke: 5pt) #place( right, dy:2%, text(weight:400,style:"italic",size:16pt)[Typst官方文档中文翻译版], ) #place( right, dy:36%, text(weight:400,style:"italic",size:16pt)[中文翻译: Casea] ) #place( right, dy:40%, text(weight:400,style:"italic",size:16pt)[版本: May 20, 2023] ) #place( right, dy:44%, text(weight:400,style:"italic",size:16pt)[日期: May 28, 2023] ) ] #pagebreak()
https://github.com/LDemetrios/Svart
https://raw.githubusercontent.com/LDemetrios/Svart/main/coloring.typ
typst
// #let escape = rgb("#cc7700") // #let comment = gray // #let string = rgb("#007700") // #let string-inlay = rgb("#cc7700") // #let keyword = rgb("#770000") // #let typed = rgb("#77aaff") // #let literal = rgb("#cc0000") #let escape = rgb("#ff7700") #let comment = gray #let string = rgb("#33ff33") #let string-inlay = rgb("#cc7700") #let keyword = rgb("#ff0077") #let typed = rgb("#77aaff") #let literal = rgb("#ff7744") #let rainbow = ( rgb("#3F9101"), rgb("#0E4A8E"), rgb("#B4960A"), rgb("#BC0BA2"), rgb("#61AA0D"), rgb("#3D017A"), rgb("#D6A60A"), rgb("#7710A3"), rgb("#A502CE"), rgb("#eb5a00"), ) #let shine(what, key) = strong(text(fill: rainbow.at(calc.rem(key, rainbow.len())), what)) #let colorize-svr(code) = { show regex("impl|enum|where|static|override|match|abstract|break|cast|class|override|continue|do\s|else|false|\sfor|fun\s|if|\sin\s|!in|interface|is\s|!is|null|object|package|return|super|this|throw|true|\stry|type|val\s|var\s|when|while|operator"): it => text( fill: keyword, strong(it), ) show regex("\s[0-9.]+[uUlL]*"): set text(fill: literal) show regex("<[a-zA-Z, :]*>"): set text(fill: typed) code } #let show-rule(body) = { let code = body.text let stack = () let part = "" let mode = "code" // another option is string or comment let i = 0 let color-key = 0 while i < code.len() { let char = code.at(i) let prev-char = code.at(i - 1, default: "") let next-char = code.at(i + 1, default: "") if mode == "code" { if char == "(" { color-key += 1 stack.push(colorize-svr(part)) stack.push(shine("(", color-key)) part = "" } else if char == ")" { stack.push(colorize-svr(part)) stack.push(shine(")", color-key)) color-key -= 1 part = "" } else if char == "[" { color-key += 2 stack.push(colorize-svr(part)) stack.push(shine("[", color-key)) part = "" } else if char == "]" { stack.push(colorize-svr(part)) stack.push(shine("]", color-key)) color-key -= 2 part = "" } else if char == "{" { color-key += 3 stack.push(colorize-svr(part)) stack.push(shine("{", color-key)) part = "" } else if char == "}" { stack.push(colorize-svr(part)) stack.push(shine("}", color-key)) color-key -= 3 part = "" } else if char == "\"" { stack.push(colorize-svr(part)) mode = "string" part = char } else if char == "/" { if next-char == "/" { stack.push(colorize-svr(part)) mode = "line-comment" part = "//" i += 1 } else if next-char == "*" { stack.push(colorize-svr(part)) mode = "multiline-comment" part = "/*" i += 1 } else { part += char } } else { part += char } } else if mode == "string" { if char == "\\" { stack.push(text(fill: string, part)) stack.push(text(fill: escape, char + next-char)) part = "" i += 1 } else if char == "$" { stack.push(text(fill: string, part)) part = "$" while (code.at(i + 1).match(regex("[a-zA-Z0-9]")) != none) { part += code.at(i + 1) i += 1 } stack.push(text(fill: string-inlay, part)) part = "" } else if char == "\"" { stack.push(text(fill: string, part + char)) part = "" mode = "code" } else { part += char } } else if mode == "line-comment" { if char == "\r" or char == "\n" { stack.push(text(fill: comment, part + char)) part = "" mode = "code" } else { part += char } } else if mode == "multiline-comment" { if char == "*" and next-char == "/" { stack.push(text(fill: comment, part + char + next-char)) part = "" mode = "code" i += 1 } else { part += char } } else { assert(false, message: mode) } i += 1 } stack.push(colorize-svr(part)) for el in stack { el } }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-rect_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 17.8cm) #lorem(100) #rect(lorem(100)) #set par(justify: true) #lorem(100) #rect(lorem(100))
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/array.typ
typst
Apache License 2.0
// Test arrays. // Ref: false --- // Ref: true #set page(width: 150pt) // Empty. #() // Not an array, just a parenthesized expression. #(1) // One item and trailing comma. #(-1,) // No trailing comma. #(true, false) // Multiple lines and items and trailing comma. #("1" , rgb("002") ,) --- // Test the `len` method. #test(().len(), 0) #test(("A", "B", "C").len(), 3) --- // Test lvalue and rvalue access. #{ let array = (1, 2) array.at(1) += 5 + array.at(0) test(array, (1, 8)) } --- // Test different lvalue method. #{ let array = (1, 2, 3) array.first() = 7 array.at(1) *= 8 test(array, (7, 16, 3)) } --- // Test rvalue out of bounds. // Error: 2-17 array index out of bounds (index: 5, len: 3) and no default value was specified #(1, 2, 3).at(5) --- // Test lvalue out of bounds. #{ let array = (1, 2, 3) // Error: 3-14 array index out of bounds (index: 3, len: 3) and no default value was specified array.at(3) = 5 } --- // Test default value. #test((1, 2, 3).at(2, default: 5), 3) #test((1, 2, 3).at(3, default: 5), 5) --- // Test remove with default value. #{ let array = (1, 2, 3) test(array.remove(2, default: 5), 3) } #{ let array = (1, 2, 3) test(array.remove(3, default: 5), 5) } --- // Test bad lvalue. // Error: 2:3-2:14 cannot mutate a temporary value #let array = (1, 2, 3) #(array.len() = 4) --- // Test bad lvalue. // Error: 2:9-2:13 type array has no method `yolo` #let array = (1, 2, 3) #(array.yolo() = 4) --- // Test negative indices. #{ let array = (1, 2, 3, 4) test(array.at(0), 1) test(array.at(-1), 4) test(array.at(-2), 3) test(array.at(-3), 2) test(array.at(-4), 1) } --- // The the `first` and `last` methods. #test((1,).first(), 1) #test((2,).last(), 2) #test((1, 2, 3).first(), 1) #test((1, 2, 3).last(), 3) --- // Error: 2-12 array is empty #().first() --- // Error: 2-11 array is empty #().last() --- // Test the `push` and `pop` methods. #{ let tasks = (a: (1, 2, 3), b: (4, 5, 6)) test(tasks.at("a").pop(), 3) tasks.b.push(7) test(tasks.a, (1, 2)) test(tasks.at("b"), (4, 5, 6, 7)) } --- // Test the `insert` and `remove` methods. #{ let array = (0, 1, 2, 4, 5) array.insert(3, 3) test(array, range(6)) array.remove(1) test(array, (0, 2, 3, 4, 5)) } --- // Error: 2:2-2:18 missing argument: index #let numbers = () #numbers.insert() --- // Test the `slice` method. #test((1, 2, 3, 4).slice(2), (3, 4)) #test(range(10).slice(2, 6), (2, 3, 4, 5)) #test(range(10).slice(4, count: 3), (4, 5, 6)) #test(range(10).slice(-5, count: 2), (5, 6)) #test((1, 2, 3).slice(2, -2), ()) #test((1, 2, 3).slice(-2, 2), (2,)) #test((1, 2, 3).slice(-3, 2), (1, 2)) #test("ABCD".split("").slice(1, -1).join("-"), "A-B-C-D") --- // Error: 2-30 array index out of bounds (index: 12, len: 10) #range(10).slice(9, count: 3) --- // Error: 2-24 array index out of bounds (index: -4, len: 3) #(1, 2, 3).slice(0, -4) --- // Test the `position` method. #test(("Hi", "❤️", "Love").position(s => s == "❤️"), 1) #test(("Bye", "💘", "Apart").position(s => s == "❤️"), none) #test(("A", "B", "CDEF", "G").position(v => v.len() > 2), 2) --- // Test the `filter` method. #test(().filter(calc.even), ()) #test((1, 2, 3, 4).filter(calc.even), (2, 4)) #test((7, 3, 2, 5, 1).filter(x => x < 5), (3, 2, 1)) --- // Test the `map` method. #test(().map(x => x * 2), ()) #test((2, 3).map(x => x * 2), (4, 6)) --- // Test the `fold` method. #test(().fold("hi", grid), "hi") #test((1, 2, 3, 4).fold(0, (s, x) => s + x), 10) --- // Error: 20-22 unexpected argument #(1, 2, 3).fold(0, () => none) --- // Test the `sum` method. #test(().sum(default: 0), 0) #test(().sum(default: []), []) #test((1, 2, 3).sum(), 6) --- // Error: 2-10 cannot calculate sum of empty array with no default #().sum() --- // Test the `product` method. #test(().product(default: 0), 0) #test(().product(default: []), []) #test(([ab], 3).product(), [ab]*3) #test((1, 2, 3).product(), 6) --- // Error: 2-14 cannot calculate product of empty array with no default #().product() --- // Test the `rev` method. #test(range(3).rev(), (2, 1, 0)) --- // Test the `join` method. #test(().join(), none) #test((1,).join(), 1) #test(("a", "b", "c").join(), "abc") #test("(" + ("a", "b", "c").join(", ") + ")", "(a, b, c)") --- // Error: 2-22 cannot join boolean with boolean #(true, false).join() --- // Error: 2-20 cannot join string with integer #("a", "b").join(1) --- // Test joining content. // Ref: true #([One], [Two], [Three]).join([, ], last: [ and ]). --- // Test the `intersperse` method #test(().intersperse("a"), ()) #test((1,).intersperse("a"), (1,)) #test((1, 2).intersperse("a"), (1, "a", 2)) #test((1, 2, "b").intersperse("a"), (1, "a", 2, "a", "b")) --- // Test the `sorted` method. #test(().sorted(), ()) #test(().sorted(key: x => x), ()) #test(((true, false) * 10).sorted(), (false,) * 10 + (true,) * 10) #test(("it", "the", "hi", "text").sorted(), ("hi", "it", "text", "the")) #test(("I", "the", "hi", "text").sorted(key: x => x), ("I", "hi", "text", "the")) #test(("I", "the", "hi", "text").sorted(key: x => x.len()), ("I", "hi", "the", "text")) #test((2, 1, 3, 10, 5, 8, 6, -7, 2).sorted(), (-7, 1, 2, 2, 3, 5, 6, 8, 10)) #test((2, 1, 3, -10, -5, 8, 6, -7, 2).sorted(key: x => x), (-10, -7, -5, 1, 2, 2, 3, 6, 8)) #test((2, 1, 3, -10, -5, 8, 6, -7, 2).sorted(key: x => x * x), (1, 2, 2, 3, -5, 6, -7, 8, -10)) --- // Error: 12-18 unexpected argument #().sorted(x => x) --- // Test the `zip` method. #test(().zip(()), ()) #test((1,).zip(()), ()) #test((1,).zip((2,)), ((1, 2),)) #test((1, 2).zip((3, 4)), ((1, 3), (2, 4))) #test((1, 2, 3, 4).zip((5, 6)), ((1, 5), (2, 6))) #test(((1, 2), 3).zip((4, 5)), (((1, 2), 4), (3, 5))) #test((1, "hi").zip((true, false)), ((1, true), ("hi", false))) #test((1, 2, 3).zip((3, 4, 5), (6, 7, 8)), ((1, 3, 6), (2, 4, 7), (3, 5, 8))) #test(().zip((), ()), ()) #test((1,).zip((2,), (3,)), ((1, 2, 3),)) #test((1, 2, 3).zip(), ((1,), (2,), (3,))) #test(array.zip(()), ()) --- // Test the `enumerate` method. #test(().enumerate(), ()) #test(().enumerate(start: 5), ()) #test(("a", "b", "c").enumerate(), ((0, "a"), (1, "b"), (2, "c"))) #test(("a", "b", "c").enumerate(start: 1), ((1, "a"), (2, "b"), (3, "c"))) #test(("a", "b", "c").enumerate(start: 42), ((42, "a"), (43, "b"), (44, "c"))) #test(("a", "b", "c").enumerate(start: -7), ((-7, "a"), (-6, "b"), (-5, "c"))) --- // Test the `dedup` method. #test(().dedup(), ()) #test((1,).dedup(), (1,)) #test((1, 1).dedup(), (1,)) #test((1, 2, 1).dedup(), (1, 2)) #test(("Jane", "John", "Eric").dedup(), ("Jane", "John", "Eric")) #test(("Jane", "John", "Eric", "John").dedup(), ("Jane", "John", "Eric")) --- // Test the `dedup` with the `key` argument. #test((1, 2, 3, 4, 5, 6).dedup(key: x => calc.rem(x, 2)), (1, 2)) #test((1, 2, 3, 4, 5, 6).dedup(key: x => calc.rem(x, 3)), (1, 2, 3)) #test(("Hello", "World", "Hi", "There").dedup(key: x => x.len()), ("Hello", "Hi")) #test(("Hello", "World", "Hi", "There").dedup(key: x => x.at(0)), ("Hello", "World", "There")) --- // Error: 9-26 unexpected argument: val #().zip(val: "applicable") --- // Error: 13-30 unexpected argument: val #().zip((), val: "applicable") --- // Error: 32-37 cannot divide by zero #(1, 2, 0, 3).sorted(key: x => 5 / x) --- // Error: 2-26 cannot compare content and content #([Hi], [There]).sorted() --- // Error: 2-26 cannot compare 3em with 2pt #(1pt, 2pt, 3em).sorted() --- // Error: 42-52 unexpected argument #((k: "a", v: 2), (k: "b", v: 1)).sorted(it => it.v) --- // Error: 2-18 array index out of bounds (index: -4, len: 3) and no default value was specified #(1, 2, 3).at(-4) --- // Error: 3-4 unclosed delimiter #{(} // Error: 2-3 unclosed delimiter #{)} // Error: 4-6 unexpected end of block comment #(1*/2) // Error: 6-8 invalid number suffix: u #(1, 1u 2) // Error: 3-4 unexpected comma #(,1) // Missing expression makes named pair incomplete, making this an empty array. // Error: 5 expected expression #(a:) // Named pair after this is already identified as an array. // Error: 6-10 expected expression, found named pair #(1, b: 2) // Keyed pair after this is already identified as an array. // Error: 6-14 expected expression, found keyed pair #(1, "key": 2)
https://github.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides
https://raw.githubusercontent.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides/main/README.md
markdown
MIT License
# UniPD-Swiss-Knife-Notes-Slides In this repo, you will find notes/projects templates for the following notes: - _Microsoft Word_ (based on my Master Degree files, the "Simple (for real)" and a generic UniPD project) - _LaTeX_ (based on existing templates minimalized) - Typst (based on Alberto Lazari notes and edited accordingly) - _Markdown_ (easy and simple, like I would do) You will also find the following slides templates: - _Beamer_ (LaTeX) slides, based on a minimal working example (Generic) and Francesco De Faveri Beamer Template (Beamer Slides) - _Powerpoint_, based on the existing UniPD template of DM Math and edited accordingly - _Typst_, based on existing templates, mainly of Augusto Zanellato inspiration
https://github.com/atareao/typst-templates
https://raw.githubusercontent.com/atareao/typst-templates/main/presentacion/lib.typ
typst
MIT License
#let default-color = white.darken(10%) #let header-color = default-color.lighten(75%) #let body-color = white.darken(10%) #let code_font = "Ubuntu Mono" #let code_theme = "halcyon.tmTheme" #let layouts = ( "small": ("height": 9cm, "space": 1.4cm), "medium": ("height": 10.5cm, "space": 1.6cm), "large": ("height": 12cm, "space": 1.8cm), ) #let slides( content, title: none, subtitle: none, comment: none, date: none, authors: (), layout: "medium", ratio: 4/3, title-color: none, background: none, ) = { // Parsing if layout not in layouts { panic("Unknown layout " + layout) } let (height, space) = layouts.at(layout) let width = ratio * height // Colors if title-color == none { title-color = default-color } // Setup set document( title: title, author: authors, ) // set text( font: "Ubuntu", fill: white, size: 14pt, ) set page( width: width, height: height, margin: (x: 0.5 * space, top: 1.5 * space, bottom: 0.6 * space), background: image("../images/" + background), header: context { let page = here().page() let headings = query(selector(heading.where(level: 2))) let heading = headings.rev().find(x => x.location().page() <= page) if heading != none { set align(top + center) set text(1.0em, weight: "bold", fill: title-color) v(space * 0.2) upper(title) v(space * 0.05) text(size: 0.6em, upper(heading.body)) } }, header-ascent: 0%, footer: [ #set text(0.6em) #set align(left) #counter(page).display("1/1", both: true) ], footer-descent: 0.8em, ) set outline( target: heading.where(level: 1), title: none, ) set bibliography( title: none ) // Rules show heading.where(level: 1): x => { set page(header: none, footer: none) set align(center + horizon) set text(1.2em, weight: "bold", fill: title-color) v(- space / 2) x.body } show heading.where(level: 2): pagebreak(weak: true) show heading: set text(1.1em, fill: title-color) // Title if (title == none) { panic("A title is required") } else { if (type(authors) != array) { authors = (authors,) } set page(footer: none) set align(horizon + center) v(- space / 2) block( text(2.0em, weight: "bold", fill: title-color, title) + v(1.0em, weak: true) + if subtitle != none { text(1.4em, weight: "bold", fill: title-color, subtitle) } + v(1.0em, weak: true) + if comment != none { text(1.0em, weight: "bold", fill: title-color, comment) } + if subtitle != none and date != none { text(1.1em)[ \- ] } + if date != none {text(1.1em, date)} + v(1.6em, weak: true) + align(center,text(fill: title-color, authors.join(", ", last: " and "))) ) } // Raw set raw( theme: code_theme, tab-size: 4, ) show raw.where(block: true): (item) => { set block(fill: rgb("#1d2433")) box( fill: rgb("#1d2433"), inset: 8pt, radius: 8pt, text(fill: rgb("#a2aabc"), font: code_font, size: 10pt, item) ) } show raw.where(block: false): (item) => box( fill: rgb("#1d2433"), inset: 2pt, radius: 2pt, text(fill: rgb("#a2aabc"), font: code_font, size: 10pt, item) ) // Content content }
https://github.com/cs-24-sw-3-01/typst-documents
https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/implementation.typ
typst
#import "../custom.typ": * = Implementation
https://github.com/valentinvogt/npde-summary
https://raw.githubusercontent.com/valentinvogt/npde-summary/main/src/chapters/11.typ
typst
#import "../setup.typ": * #show: thmrules = Numerical Methods for Conservation Laws <ch:conservation-laws> #counter(heading).update((11, 1)) == Scalar Conservation Laws in 1D <sub:scalar-conservation-laws-in-1d> The goal of this chapter is to solve general conservation laws which are of the form #neq( $ frac(partial u, partial t) (x , t) + frac(partial, partial x) (f (u (x , t) , x)) = s (u (x , t) , x , t) . $, ) <eq:general-cons-law> The flux $f : bb(R) times Omega arrow.r bb(R)$ can be a general function, which can depend non-linearly on the solution $u$. Everything in this chapter will be one-dimensional in space and time, so we have $Omega subset.eq bb(R)$. We usually consider the special case $s = 0$ and $f=f(u)$, known as the *Cauchy problem*: #neq( $ frac(partial u, partial t) + frac(partial, partial x) f (u) &= 0 \ u(x,0) &= u_0 (x) $, ) <eq:cauchy-problem> #mybox( "Example: Particle Model", ..unimportant, )[ We model cars as particles with position $x_i (t)$. Traffic speed is modeled by $ dot(x)_i (t) = v_"max" dot.op (1 - frac(Delta_0, Delta x_i (t))) , quad Delta x_i (t) = x_(i + 1) (t) - x_i (t) , $ where $v_"max"$ is the maximum velocity and $Delta_0$ is the minimal distance between cars (i.e., the car length). Using some basic assumptions, we get a PDE: $ frac(partial u, partial t) (x , t) = frac(partial, partial x) u (1 - u) . $ We define the car density $u(x)$ as the number of cars in an infinitesimal interval around $x$. ] #counter(heading).step(level: 3) === Characteristics <sub:characteristics> We consider the Cauchy problem @eq:cauchy-problem. Then a characteristic curve is defined as #definition( number: "172.16.31.10", "Characteristic curve for 1D scalar conservation law", )[ $Gamma : [0 , T] arrow.r bb(R) times [0 , T]$ with $Gamma (tau) := (gamma (tau) , tau)$, such that $gamma$ satisfies $ frac(dif, dif t) gamma (tau) = f prime (u (gamma (tau) , tau)) $ for $0 <= tau <= T$. ] Generally, characteristic curves are lines along which information propagates. This means $u (x , t)$ will only depend on the initial condition at $x_0$, namely $u_0 (x_0)$, if there is a characteristic curve that starts in the point $x_0$ and travels to the spacetime point $(x , t)$. One property of characteristic curves is the following: #lemma( number: "172.16.58.3", "Classical solution and characteristic curves", )[ Smooth solutions of @eq:cauchy-problem are constant along characteristic curves. ] For example in the case of linear advection ($partial_t u + v partial_x u = 0$) we can use this to solve the equation because $gamma (tau) = (x_0 + tau v)$, which implies $u (x , t) = u_0 (x - t v)$. But this does not work if the solution is not smooth. For example, in the traffic flow model above, the solution has a jump after a certain time and hence this approach breaks down. #counter(heading).step(level: 3) === Jump conditions and Riemann Problem <sub:jump-conditions-and-riemann-problem> The method of characteristics usually only works up to a certain point in time. To get the solution for times after that, we first note that the solution will usually have a discontinuity after the time where the method of characteristics breaks down. So we study how the solution behaves at these jumps (discontinuities). The setting is as follows: We still study the Cauchy problem @eq:cauchy-problem. We can derive that along jumps, the normal components must be continuous, which leads to the #definition( number: "11.2.4.2", [Rankine--Hugoniot (jump) condition], )[ $ dot(s) (u_l - u_r) = f (u_l) - f (u_r) $ where $dot(s) = frac(d gamma, d t)$ is the time derivative of the discontinuity curve $Gamma (t) = (gamma (t) , t) in bb(R) times [0 , T]$. ] Note that this is useful because it allows us to compute the jump if we know $u_l$ and $u_r$. The Riemann problem is given as #definition( number: "11.2.5.1", "Riemann problem", )[ $ frac(partial u, partial t) + frac(partial f (u), partial x) = 0 $ and $ u_0 (x) = cases( delim: "{", u_l in bb(R) & upright("if ") x < 0, u_r in bb(R) & upright("if ") x > 0, ) $ Note that $f$ can still be chosen to be any sufficiently smooth flux function. ] Using the Rankine--Hugoniot jump condition we then get the following solution for Riemann problems with a shock: #lemma( number: "11.2.5.4", "Shock solution for Riemann problem", )[ For any two states $u_r , u_l in bb(R)$ the piecewise constant function $ u (x , t) := cases( delim: "{", u_l & upright("for ") x < dot(s) t, u_r & upright("for ") x > dot(s) t, ) & & quad quad dot(s) := frac(f (u_l) - f (u_r), u_l - u_r) , & & x in bb(R) , 0 < t < T $ is a weak solution to the Riemann problem. ] Note that the solution only holds if the equation implies a shock (jump). This is the case if $f$ is convex and $u_l > u_r$ or if $f$ is concave and $u_r > u_l$. If the jump only exists in the beginning we have a different solution #lemma( number: "11.2.5.4", "Rarefaction solution for Riemann problem", )[ If $f in C^2 (bb(R))$ is strictly $cases( delim: "{", upright("convex and ") u_l < u_r, upright("concave and ") u_r < u_l, )$, then $ u (x , t) := cases( delim: "{", u_l & upright("for ") x < min { f prime (u_l) , f prime (u_r) } dot.op t, g (x / t) & upright("for ") min { f prime (u_l) , f prime (u_r) } < x / t < max { f prime (u_l) , f prime (u_r) }, u_r & upright("for ") x > max { f prime (u_l) , f prime (u_r) } dot.op t, ) $ is a weak solution to the Riemann problem with $g := (f prime)^(- 1)$. ] The question when to choose which of the two solution is answered by #definition( number: "11.2.6.1", "Lax entropy condition", )[ Let $u$ be a weak solution of @eq:cauchy-problem, and a piecewise classical solution in neighborhood of $C^2$-curve $Gamma := (gamma (tau) , tau) , 0 <= tau <= T$, discontinuous across $Gamma$. $u$ satisfies the #emph[Lax entropy condition] in $(x_0 , t_0) in Gamma$ iff. $ f prime (u_l) > underbrace(frac(f (u_l) - f (u_r), u_l - u_r), dot(s)) > f prime (u_r) $ ] Now if $u$ satisfies the Lax entropy condition, then we have to pick the shock solution. Otherwise we pick the rarefaction solution. #counter(heading).update((11, 2, 6)) === Properties of Entropy Solutions <sub:properties-of-entropy-solutions> The essential properties here are that with the propagation speed $f prime (u)$, we find the #strong[domain of dependence] and the #strong[domain of influence];, which is best illustrated by a picture and hence we encourage the reader to look at the lecture document and the illustrations below Theorem 11.2.7.3. Moreover the second result is that the number of extrema of the solution is non-increasing in time. == Conservative Finite Volume (FV) Discretization <sub:conservative-finite-volume> === Finite Difference Methods <sub:finite-difference-methods> Finite difference methods are probably the simplest methods for solving PDEs. We just replace the spacial derivatives by some finite difference quotient for example one of the following #subtle-box[ $ "Symmetric difference quotient" quad frac(partial f, partial x) &approx frac(f (x_0 + h) - f (x_0 - h), 2 h) \ "Backward difference quotient" quad frac(partial f, partial x) &approx frac(f (x_0) - f (x_0 - h), h) \ "Forward difference quotient" quad frac(partial f, partial x) &approx frac(f (x_0 + h) - f (x_0), h) $ ] Then we construct a solution by time-stepping: given $u (x , t_k)$ we compute $u (x , t_(k + 1))$ by using some Runge--Kutta integrator. With the example of finite difference methods, we observe that by the nature of the problems we are studying in this chapter, the solutions have to be constructed under consideration of the flux direction. That is, in the spirit of characteristic curves we know that information propagates along curves in space time. And if this curve advances, for example, from left to right in space, then we need to use the forward difference quotient, because the backward difference quotient will not contain the information of the flow direction.// TODO === Spatially Semi-Discrete Conservation Form <sub:spatially-semi-discrete-conservation-form> The method we will use in this section of the course is the Finite Volume Method. We use a uniform 1D mesh with $N$ cells and search a piecewise constant solution. The coefficients are the values of $u$ at the cell centers: $ mu_i approx u(x_i, t) $ we build a mesh by taking intervals around the spatial points in which we approximate the solution $u$. Now we derive an ODE for $bmu$ by starting from the problem definition and integrating over cell $j$: $ frac(partial u, partial t) = - frac(partial, partial x) f (u) $ #neq( $ frac(partial, partial t) underbrace( integral_(x_(j - 1 \/ 2))^(x_(j + 1 \/ 2)) u (x , t) dif x, approx med h dot.op mu_j, )= -(f(u(x_(j + 1 \/ 2), t)) - f(u(x_(j - 1 \/ 2), t)) ) $, )<eq:fv-derivation> Because $u$ is piecewise constant, $u(x_(j + 1/2), t)$ is undefined. An approximation for $f_(j+1/2) :=f(u(x_(j + 1/2), t))$ is given by the *numerical flux function* $F$: #mybox("General Numerical Flux Function")[ $ f_(j+1/2) approx F(mu_(j-m_l + 1), dots, mu_(j+m_r)) $ $F$ is called a $(m_l + m_r)$--point numerical flux function. ] A *2-point flux*, which is all we need in this section, is defined as $f_(j+1/2) approx F(mu_j, mu_(j+1))$. With this, @eq:fv-derivation becomes (omitting the time argument of $mu_j$) #neq( $ frac(dif mu_j, dif t) (t) = - 1 / h (F (mu_j, mu_(j+1)) - F (mu_(j-1), mu_j)) $, )<eq:two-points-flux-discrete> We can simply plug the RHS of @eq:two-points-flux-discrete into a Runge--Kutta method, so the only thing left to do is to find a suitable flux function $F$, which should satisfy the following condition: #definition(number: "172.16.17.32", "Consistent numerical flux function")[ A numerical function $F : bb(R)^(m_l + m_r) arrow.r bb(R)$ is #emph[consistent] with the flux $f : bb(R) arrow.r bb(R)$ if $ F (u , u , dots.h , u) = f (u) , #h(2em) forall u in bb(R) $ ] Theory tells us that a consistent numerical flux will produce a solution with the correct shock speed. #counter(heading).step(level: 3) === Numerical Flux Functions <sub:numerical-flux-functions> This section now treats how to find suitable flux functions. There are several options: the simplest one just averages the inputs of $F (u , w)$, but suffers from the same problem as finite difference methods. One remedy for this is the #emph[Lax--Friedrichs / Rusanov] Flux which is useful but flattens the edges of jumps (which is due to its construction with additional diffusion). #equation( number: "192.168.127.12", [Lax--Friedrichs / Rusanov Flux], )[ $ F_(L F) (v , w) = 1 / 2 (f (v) + f (w)) - 1 / 2 (w - v) max_(min { v, w } <= u <= max { v, w }) f prime (u) $ The third term is the artificial diffusion term. ] As pointed out before, the direction in which the information flows is crucial, so an important idea to choose the right flux is to respect that. Moreover the flux has to reproduce physical solution in the sense explained above when studying two possible solutions for the Riemann problem. The final flux we look at, which solves these problems, is the Godunov Flux. #definition( number: "11.3.4.33", "Godunov Flux", )[ $ F_(G D) (v , w) = cases( delim: "{", min_(v lt.eq u lt.eq w) f (u) quad upright("if ") v < w, max_(w lt.eq u lt.eq v) f (u) quad upright("if ") v gt.eq w, ) $ ] #pagebreak(weak: true) === Monotone Schemes <sub:monotone-schemes> First, we define what it means for a flux to be monotone: #definition( number: "11.3.5.5", "Monotonicity of flux functions", )[ A 2-point numerical flux function $F = F(v, w)$ is #emph[monotone] if $ - thick F "is increasing in its first argument, i.e." &F(v, w) <= F(v+Delta v, w) quad &forall w &in bb(R) \ - thick F "is decreasing in its second argument, i.e." &F(v, w) <= F(v, w+Delta w) quad &forall v &in bb(R)$ ]<def:monotone-flux> In @sub:properties-of-entropy-solutions, we mentioned that the number of extrema of an analytical solution does not increase over time. Here, we show that the two main fluxes (LF and Godunov) we derived in the previous chapter are monotone and therefore both have this property. This is established by the following two lemmas: #lemma( number: "11.3.5.8", [Monotonicity of Lax--Friedrichs and Godunov flux], )[ For any continuously differentiable flux function $f$ the associated Lax--Friedrichs flux and Godunov flux are monotone. ] #v(-1cm) #lemma( number: "11.3.5.13", "Non-oscillatory monotone semi-discrete evolutions", )[ If $bmu = bmu (t)$ solves the two-point flux equation @eq:two-points-flux-discrete with a monotone numerical flux and $bmu (0)$ has finitely many local extrema, then the number of local extrema of $bmu (t)$ cannot be larger than that of $bmu (0)$. ] == Time-stepping for Finite-Volume Methods <sub:time-stepping-for-fv> As explained before, once we have chosen the numerical Flux, we just need to apply Runge--Kutta integration. This subsection studies some conditions that have to be considered when applying Runge--Kutta -- in particular, constraints on choosing the time-step size $tau$. #definition( number: "192.168.3.11", "Numerical domain of dependence", )[ Consider the explicit fully discrete evolution $bmu^((k + 1)) := fvH (bmu^((k)))$ on a uniform spatio-temporal mesh ($x_j = h j , j in bb(Z) , t_k = k tau , k in bb(N)_0$) with #neq( $ exists m in bb(N)_0 : (fvH (bmu))_j = fvH (mu_(j - m) , dots.h , mu_(j + m)) , j in bb(Z) . $, ) <eq:fv-stencil-width> Then the *numerical domain of dependence* is given by $ D_h^(-) (x_j , t_k) := { (x_n , t_l) in bb(R) times [0 , t_k] : j - m (k - l) lt.eq n lt.eq j + m (k - l) } $ ] $fvH$ is an operator which gives $bmu$ at the next time-step. It incorporates both the numerical flux and the Runge--Kutta method. If we have a first-order time integrator and the numerical flux function is $F=F(mu_(j-m), dots.h, mu_(j+m))$, then $fvH = fvH(mu_(j-m), dots.h, mu_(j+m))$. #subtle-box[ *Example:* Let's say we are solving @eq:two-points-flux-discrete and call the RHS $R(mu_j)$ $ frac(dif mu_j, dif t) (t) = - 1 / h (F (mu_j, mu_(j+1)) - F (mu_(j-1), mu_j)) = R(mu_j) $ and we apply explicit Euler: $ (fvH (bmu))_j &= mu_j + tau R(mu_j)\ &= mu_j - tau / h (F (mu_j, mu_(j+1)) - F (mu_(j-1), mu_j)) $ If we compare this to @eq:fv-stencil-width, we see that $m = 1$ in this case. ] // TODO Elaborate The following kind of condition appears over and over in numerical integration and gives an upper bound for the time-step size $tau$: If this upper bound is respected, the numerical solution is stable. #definition( number: "172.16.58.3", [Courant--Friedrichs--Lewy (CFL) condition], )[ An explicit local fully discrete evolution $bmu^((t + 1)) := fvH (bmu)$ on uniform spatio-temporal mesh ($x_j = h j , j in bb(Z) , t_k = k tau , k in bb(N)$) satisfies the CFL condition, if the convex hull of its numerical domain of dependence contains the maximal analytical domain of dependence $ D^(-) (x_j , t_k) subset "convex"thin (D_h^(-) (x_j , t_k)) quad forall j , k . $ ] Applied to our problem, this means #equation( number: "11.4.2.12", "CFL condition for explicit fully discrete evolution", )[ $ tau / h lt.eq frac(m, max { lr(|dot(s)_min|) , lr(|dot(s)_max|) }) . $ ] #counter(heading).update((11, 4, 3)) === Convergence of Fully Discrete FV Method <sub:convergence-of-fully-discrete-fv> The *consistency error* is defined as follows: $ eps := max_j {F(u(x_j, t), u(x_(j+1), t)) - f(u(x_(j+1/2), t))}, $ if we assume $u$ to be an exact solution of the Cauchy Problem @eq:cauchy-problem. If $eps = Order(h^q)$, the flux is called _q-th order consistent_. $q$ is then the order of convergence of the FV method. We get at most order one convergence in both $L^1$ and maximum norm due to the following fact: #mybox("Order barrier for monotone numerical fluxes")[ Monotone numerical fluxes (@def:monotone-flux) are at most first order consistent. ] #pagebreak(weak: true) == Higher-Order FV Schemes <sub:higher-order-fv-schemes> For the FV Method to achieve a convergence of order $ > 1$, we need fluxes which are consistent of order $ > 1$. Instead of coming up with completely new fluxes, we use the ones from @sub:numerical-flux-functions and only modify the arguments given to them. We choose the approach to go from piecewise-constant to *discontinuous piecewise-linear* solutions. Instead of approximating $f(u(x_(j+1/2)))$ by $F(mu_(j), mu_(j+1))$, we use $F(nu^+_(j),nu^-_(j+1))$. #grid( columns: (0.75fr, 0.2fr), column-gutter: 1em, [ $nu^+_j,nu^-_j$ are the values of the linear approximation of $u$ at the boundaries of cell $j$ (see image). The discrete evolution equation becomes #neq( $ frac(d mu_j, d t) (t) = - 1 / h (F (nu_j^+ (t), nu_(j+1)^- (t)) - F (nu_(j-1)^+ (t), nu_j^- (t)) ) $, )<eq:linear-reconstruction-evolution> ], [ #image("../../images/linear_reconstruction.png", width: 80%) ], ) where $nu_j^+,nu_j^-$ are the values of the linear approximation of $u$ at the cell boundaries. The linear approximation on cell $j$ is defined by the slope $sigma_j$. So this method boils down to finding formulas for the slopes: $ sigma_j = "slope"(mu_(j-1), mu_j, mu_(j+1)) $ #counter(heading).step(level: 3) === Slope limiting Finding a linear approximation is formally expressed as a *reconstruction operator*: $ recop = "discontinuous pw. linear approximation of " u $ Note that this operator as a mapping between vector spaces is not linear. However, we call it a *linear reconstruction* because the result is a (piecewise) linear function. We get the following formulas which we can plug into @eq:linear-reconstruction-evolution: $ v^+_(j) = recop (x^-_(j+1/2)) " and " v^-_j = recop (x^+_(j-1/2)) $ where $x^+$ denotes the limit from the right and $x^-$ from the left. Note that we always assume $recop (x_j) = mu_j$, i.e., the linear reconstruction has the same values as the piecewise constant function at the cell centers. Given slopes $sigma_j$, we can now define the linear reconstruction operator: #v(0.2cm) #subtle-box( width: 70%, )[ #v(-0.2cm) $ recop (x) = mu_j + sigma_j (x - x_j) upright(" for ") x in openint(x_(j-1/2), x_(j+1/2)) $ #v(-0.2cm) ] We introduce an important property of the reconstruction operator: #definition( number: "11.5.2.1", "Monotonicity-preserving linear reconstruction", )[ A linear reconstruction operator $upright(R)_M$ is called #emph[monotonicity-preserving] if $ mu_j <= mu_(j+1) &==> recop upright("is non-decreasing") in openint(x_j, x_(j+1)) \ mu_j >= mu_(j+1) &==> recop upright("is non-increasing") in openint(x_j, x_(j+1)) $ ] This ensures that no new extrema are introduced by the numerical scheme. Finally, we present a reconstruction operator which is monotonicity-preserving: #definition( number: "11.5.2.9", "Minmod reconstruction", )[ $ sigma_j (mu_(j-1), mu_j, mu_(j+1)) = "minmod" (frac(mu_(j+1) - mu_j, x_(j+1) - x_j), frac(mu_j - mu_(j-1), x_j - x_(j-1))) $ where $"minmod"$ is defined as $ "minmod" (a, b) = cases( delim: "{", a \, quad & upright("if ") quad a b > 0\, abs(a) &< abs(b) \ b \, & upright("if ") quad a b < 0\, abs(b) &< abs(a) \ 0 \, & upright("otherwise"), ) $ ] The argument to minmod are simply the slopes of lines connecting $mu_j$ with its left and right neighbors. If they have the same sign, we take the smaller one (in absolute value). If they have different signs ($=> mu_j$ extremum) or one is zero (plateau), we return zero. == Systems of Conservation Laws <sub:systems-of-conservation-laws> #definition( number: "192.168.3.11", "Linear system of conservation laws", )[ Let $bold(A)(x) : RR -> RR^m times RR^m$ be a matrix-valued function and $D subset RR times RR^+$. Then #neq( $ frac(partial bu, partial t) (x,t)+ frac(partial, partial x) lr((bold(A)(x) med bu(x, t)), size: #17pt) = 0 quad upright("on") D $, )<eq:linear-system-cons-laws> is a linear system of conservation laws for $bu : D arrow.r RR^m$. ] By diagonalizing $bold(A)$, we can get a general solution formula. Let $bold(r)_i$ be an eigenvector of $bold(A)$ with eigenvalue $lambda_i$: $bold(A) bold(r)_i = lambda_i bold(r)_i$. We collect the eigenvectors in a matrix $bold(R)$. Note that both $lambda_i$ and $bold(r)_i$ depend on $x$. #mybox( [Solution of @eq:linear-system-cons-laws], )[ $ bu (x,t) = sum_(i=1)^(m) (bold(R)^(-1) bu_0)_i (x - lambda_i t) bold(r)_i $ We have a superposition of states $bold(r)_i$ propagating with speed $lambda_i$ scaled by $w_i := (bold(R)^(-1) bu_0)_i$ ] #counter(heading).update((11, 6, 1,2)) ==== Riemann problem We want to solve the Riemann problem #neq( $ bu (x,0) = cases(delim: "{", bu_l & upright("if ") x < 0, bu_r & upright("if ") x > 0) $, ) <eq:riemann-problem-system> for which we can find an explicit solution. Let's illustrate it for the case $m=3$: #let gr(x) = colMath(x, rgb(255,150,0)) #let bl(x) = colMath(x, rgb(0,0,200)) $ bu (x,t) = cases( delim: "{", gr(w^l_1) bold(r)_1 + gr(w^l_2) bold(r)_2 + gr(w^l_3) bold(r)_3 = gr(bu_l) & wide upright("if ") x < lambda_1 t, bl(w^r_1) bold(r)_1 + gr(w^r_2) bold(r)_2 + gr(w^r_3) bold(r)_3 & wide upright("if ") lambda_1 t < x < lambda_2 t, bl(w^r_1) bold(r)_1 + bl(w^r_2) bold(r)_2 + gr(w^r_3) bold(r)_3 & wide upright("if ") lambda_2 t < x < lambda_3 t, bl(w^r_1) bold(r)_1 + bl(w^r_2) bold(r)_2 + bl(w^r_3) bold(r)_3 = bl(bu_r) & wide upright("if ") x > lambda_3 t, ) $ where $w^l_i = (bold(R)^(-1) bu_l)_i$ and $w^r_i = (bold(R)^(-1) bu_r)_i$ as defined above. We define $bu_0=bu_l$, $bu_m = bu_r$ and $bu_k = u upright(" where ") lambda_k t < x < lambda_(k+1) t$. For the jumps we get a formula similar to the Rankine--Hugoniot condition: $ bold(A) (x) (bu_k - bu_(k-1)) = lambda_k (bu_k - bu_(k-1)), quad k in {1, dots, m} $ where $lambda_k$ takes the role of $dot(s)$ in the scalar case. #definition( number: "172.16.17.32", "Non-linear system of conservation laws", )[ Given $U subset RR^m$, $D subset RR times RR^+$ and a continuously differentiable flux function $bold(F) : U arrow.r RR^m$, #neq( $ frac(partial bu, partial t) + frac(partial bold(F) (bu), partial x) (x, t) = 0 quad upright("on") D $, ) <eq:non-linear-system-cons-laws> is a system of conservation laws for $bu : D arrow.r U$. ] This system is called _constant-coefficient_ because $bold(F)$ does not depend on time and _translation-invariant_ because it does not take $x$ as an argument. We apply diagonalization again, this time to the Jacobian $D bold(F) (bu)$. Note that here, eigenvectors and eigenvalues do not depend on $x$ anymore, but instead on $bu$: #neq( $ D bold(F) (bu) med bold(r)_i (bu) = lambda_i (bu) med bold(r)_i $, )<eq:jacobian-eigenvalues> Here, we also get a Rankine--Hugoniot condition: #theorem( number: "192.168.3.11", [Rankine--Hugoniot condition for systems], )[ If a curve $Gamma = (gamma(t), t)$ separates two domains $ Omega_l = { (x,t) in D : x < gamma(t)} quad upright("and") quad Omega_r = { (x,t) in D : x > gamma(t) } $ and $bu_l, bu_r = eval(bu)_Omega_l, eval(bu)_Omega_r in C^1$ are strong solutions of @eq:non-linear-system-cons-laws, then $bu$ is a weak solution of @eq:non-linear-system-cons-laws if and only if $ frac(d gamma, d t) (t) dot.op (bu_l (gamma(t),t) - bu_r (gamma(t),t)) = bold(F) (bu_l (gamma(t),t)) - bold(F) (bu_r (gamma(t),t)) $ ] For the Riemann problem @eq:riemann-problem-system, this simplifies to $ dot(s) (bu_l - bu_r) = bold(F) (bu_l) - bold(F) (bu_r), quad dot(s) = frac(d gamma, d t) $ There is also an entropy condition for systems: #definition( number: "192.168.3.11", "Lax entropy condition for systems", )[ + $ exists k in {1, dots, m} : lambda_k #h(-0.5pt) (bu_l) > dot(s) > lambda_k #h(-0.5pt) (bu_r) $ + $ forall j > k: quad lambda_j (bu_l), lambda_j (bu_r) < dot(s) $ + $ forall j < k: quad lambda_j (bu_l), lambda_j (bu_r) > dot(s) $ ] #counter(heading).update((11, 6, 2)) === FV Methods for Systems of Conservation Laws The FV semi-discrete evolution equation for systems of conservation laws is completely analogous to the scalar case. For example, with a 2-point flux #neq( $ frac(d bmu_j, d t) = - 1 / h (bold(F) (bmu_j, bmu_(j+1)) - bold(F) (bmu_(j-1), bmu_j)) $, ) <eq:two-points-flux-discrete-systems> where $bold(F): RR^m times RR^m -> RR^m$ is the vector-valued numerical flux. #counter(heading).update((11, 6, 3, 1)) ==== Fluxes for linear systems As before, we use the eigenvalues of $bA$: $ bA bold(R) &= bold(D) bold(R) \ bold(D) &= "diag"(lambda_1,...,lambda_m) $ where $bold(R)$ contains the eigenvectors $bold(r)_i$ of $bA$ and $bold(D)$ contains the eigenvalues. We split $bold(D)$ into positive and negative parts: $ bold(D)^+ &= "diag"(max { 0, lambda_i })\ bold(D)^- &= "diag"(min { 0, lambda_i }) $ and define $bold(A)^(plus.minus) = bold(R) bold(D)^(plus.minus) bold(R)^(-1)$. #mybox( [Numerical fluxes for linear systems], )[ $ "Upwind flux:" quad &bold(F)_"uw" (bv, bw) = bold(A)^+ bv + bold(A)^- bw \ "Lax-Friedrichs: " quad &bold(F)_"LF" (bv, bw) = 1 / 2 bold(A) (bv + bw) - 1 / 2 abs(bold(A)) (bw - bv) $ where $ abs(bold(A)) = bold(A)^+ - bold(A)^- $ ] Intuition for the upwind flux: Information from the left ($bv$) is carried by the eigenvectors with positive eigenvalues, which propagate to the right. ==== Fluxes for non-linear systems We want to reuse the fluxes we just found for the linear case. To do this, we approximate the nonlinear equation @eq:non-linear-system-cons-laws: $ &frac(partial bu, partial t) + &&frac(partial bold(F) (bu), partial x) (x, t) &= 0 \ approx & frac(partial bu, partial t) + &&bA_R med frac(partial bu, partial x) (x, t) $ $&bA_R (bu,bw)$ is the _Roe matrix_, an approximation of the Jacobian $D bold(F) (bu)$, and must satisfy the following properties: #definition( number: "11.6.3.30", "Roe matrix", )[ + $ bA_R (bu,bu) = D bold(F)(bu)$ for all $bu in U$ + $ bA_R (bu,bw) (bu - bw) = bold(F) (bu) - bold(F) (bw)$ for all $bu, bw in U$ + $ bA_R (bu,bw)$ has $m$ distinct real eigenvalues ] There is no general formula for the Roe matrix, but once we have it, we can plug it into e.g. the Lax-Friedrichs flux.
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/truth-table-legacy.typ
typst
#import "@preview/truthfy:0.4.0" #let bit-count(n) = { let res = 0 while n > 0 { res += 1 n = n.bit-rshift(1) } return res } #let reverse-bits(n, max: none) = { if max == none { max = bit-count(n) } let rev = 0 for _ in range(max) { rev = rev.bit-lshift(1) if n.bit-and(1) == 1 { rev = rev.bit-xor(1) } n = n.bit-rshift(1) } return rev } #let comb-n(n) = 1.bit-lshift(n) #let gen-truth-order(n) = range(n).sorted(key: i => reverse-bits(i, max: bit-count(n))) #let _always-0(a) = a + " and not " + a #let var-comb-truth-cells(vars) = { let n = vars.len() let prefix = eval("$" + vars.map(_always-0).join(" and ") + "$") gen-truth-order(comb-n(n)).map(i => i + 1).map(i => truthfy.truth-table(prefix).children.slice(i * (n + 1)).slice( 0, n, )) } #let truth-cells(vars, ..values) = { let n = vars.len() let prefix = eval("$" + vars.map(_always-0).join(" and ") + "$") let var-comb-cells = var-comb-truth-cells(vars) range(comb-n(n)) .map(i => ( ..var-comb-cells.at(i), ..values.pos().map(v => v.at(i)).map(v => [#v]), ), ) .flatten() } #let truth-cells-equations(vars, ..equations) = { let n = vars.len() let prefix = eval("$" + vars.map(_always-0).join(" and ") + "$") truth-cells( vars, ..equations.pos().map(v => gen-truth-order(comb-n(n)).map(i => i + 1).map(i => ( truthfy.truth-table($(#prefix) or (#v)$).children.slice(i * (n + 1)).at(n) ))), ) } #let truth-table-manual(table-args: (), vars, ..values) = { let headers = vars + values.pos().map(v => v.at(0)) table( columns: headers.len(), inset: .4em, ..table-args, table.header(..headers.map(v => [*$#v$*])), ..truth-cells( vars, ..values.pos().map(v => v.at(1)), ) ) } #let truth-table-fn(table-args: (), vars, ..values-fn) = { let headers = vars + values-fn.pos().map(v => v.at(0)) table( columns: headers.len(), inset: .4em, ..table-args, table.header(..headers.map(v => [*$#v$*])), ..truth-cells( vars, ..values-fn.pos().map(v => range(comb-n(vars.len())).map(i => v.at(1)(i))), ) ) } #let truth-table(table-args: (), vars, ..equation-pairs) = { let headers = vars + equation-pairs.pos().map(v => v.at(0)) table( columns: headers.len(), inset: .4em, ..table-args, table.header(..headers.map(v => [*$#v$*])), ..truth-cells-equations( vars, ..equation-pairs.pos().map(v => v.at(1)), ) ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/font_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 18-24 expected "normal", "italic", or "oblique" // #set text(style: "bold", weight: "thin")
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/kzg-takeaways.typ
typst
#import "preamble.typ":* #takeaway[KZG takeaways][ 1. _Elliptic curves_ are very useful in cryptography. Roughly speaking, they are sets of points (usually in $FF_p^2$) that satisfy some group law / "addition." The BN254 curve is a good "typical curve" to keep in mind. 2. The _discrete logarithm_ assumption is a common "hard problem assumption" used in cryptography with different groups. Specifically, since elliptic curves are groups, discrete logarithm over elliptic curves is very often used. 3. _Commitment schemes_ are ways for one party to commit values to another. Elliptic curves enable _Pedersen commitments_, a very useful example of a commitment scheme. 4. Specifically, _polynomial commitment schemes_ are commitments of polynomials that are small and easy to "open" (evaluate at different points). KZG is one of the main polynomial commitment schemes being used in cryptography, such as in PLONK (coming up). ]
https://github.com/noahjutz/CV
https://raw.githubusercontent.com/noahjutz/CV/main/main.typ
typst
#import "/theme.typ": theme #set page(margin: 0pt) #set text( font: "Noto Sans", size: 14pt, hyphenate: true, ) #block( inset: (right: 60pt, left: 40pt, y: 40pt), grid( columns: (170pt, auto), column-gutter: 32pt, block( include "sidebar/main.typ" ), block( include "body/main.typ" ) ) )
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/stack-1.typ
typst
Apache License 2.0
// Test stack layouts. --- // Test stacks with different directions. #let widths = ( 30pt, 20pt, 40pt, 15pt, 30pt, 50%, 20pt, 100%, ) #let shaded(i, w) = { let v = (i + 1) * 10% rect(width: w, height: 10pt, fill: rgb(v, v, v)) } #let items = for (i, w) in widths.enumerate() { (align(right, shaded(i, w)),) } #set page(width: 50pt, margin: 0pt) #stack(dir: btt, ..items) --- // Test spacing. #set page(width: 50pt, margin: 0pt) #let x = square(size: 10pt, fill: eastern) #stack( spacing: 5pt, stack(dir: rtl, spacing: 5pt, x, x, x), stack(dir: ltr, x, 20%, x, 20%, x), stack(dir: ltr, spacing: 5pt, x, x, 7pt, 3pt, x), ) --- // Test overflow. #set page(width: 50pt, height: 30pt, margin: 0pt) #box(stack( rect(width: 40pt, height: 20pt, fill: conifer), rect(width: 30pt, height: 13pt, fill: forest), )) --- // Test aligning things in RTL stack with align function & fr units. #set page(width: 50pt, margin: 5pt) #set block(spacing: 5pt) #set text(8pt) #stack(dir: rtl, 1fr, [A], 1fr, [B], [C]) #stack(dir: rtl, align(center, [A]), align(left, [B]), [C], )
https://github.com/gbrivady/typst-templates
https://raw.githubusercontent.com/gbrivady/typst-templates/main/readme.md
markdown
# typst-templates Set of typst example templates to write reports, articles, ... Examples can be found in the `example` folder. It is strongly advised to hack the templates to fit ones need. ## List of templates - Long report with title page (with room for logos), table of content, pre-prepared appendix section with letter headings, and other stuff: `report-long.typ`. - Two columns short article: `to come` - One page article/report: `to come` ## Compiling examples ```sh typst compile --root . examples/<example to compile> <output file> ```
https://github.com/kdog3682/typkit
https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/strokes.typ
typst
#let soft = (dash: "densely-dotted", thickness: 0.5pt) #let dense = (dash: "densely-dotted", thickness: 0.5pt) #let gentle = (thickness: 0.5pt, dash: "loosely-dotted") #let verysoft = (thickness: 0.35pt, dash: "densely-dotted") #let thin = black + 0.5pt #let solid = black + 0.5pt
https://github.com/dead-summer/math-notes
https://raw.githubusercontent.com/dead-summer/math-notes/main/notes/Analysis/ch1-measures/measures.typ
typst
#import "/book.typ": book-page #import "../../../templates/conf.typ": * #show: thmrules.with(qed-symbol: $square$) #show: book-page.with(title: "Measures") = Measures Ref/Nomenclature: 1. A pair $(X, cal(F)) = ("set", sigma-"algebra")$ is a measurable space. 2. A measure on $(X, cal(F))$ is a function $mu: f -> [0, +infinity]$ , s.t. $mu(diameter) = 0$ , $mu(union.sq.big_(j=1)^infinity E_j) = sum_(j=1)^infinity mu(E_j)$ for ${E_j}_(j=1)^infinity subset cal(F)$ disjoint. 3. $(X, cal(F), mu)$ is a measure space. 4. $(X, cal(F), mu)$ is finite iff $mu(X) < infinity$ . 5. $(X, cal(F), mu)$ is $sigma$-finite iff $exists {E_j}_(j=1)^infinity subset.eq cal(F)$ , s.t. $X = union.big_(j=1)^infinity E_j$ and $mu(E_j) < infinity, forall j >=1$ . 6. $mu$ is semifinite if $forall E in cal(F), mu(E) < infinity$ , there exists a set $F subset E, F in cal(F)$ , s.t. $0 < mu(F) < infinity$ . #exr[ (5) $=>$ (6). ] #exm[ Counting measure $cal(H)^0$ on $(X, cal(P)(X))$ : $ cal(H)^0 = cases( #math.op("card") (E) & "if" E "is finite", \ infinity & "otherwise" ) $ ] #rmk[ $cal(H)^k, k >= 0$ is the Hausdroff measures. $k=0$ , $cal(H)^0$ is the counting measure, $k in NN$ , $cal(H)^k = cal(L)^k$ on $RR^k$ . ] #exm[ Dirac measure on $(X, cal(P)(X))$: fix any $x_0 in X$ , define $delta_x: cal(P)(X) -> {0, 1}$ , s.t. $ bb(1)_E(x_0) := delta_x_0(E) = cases( 1 & "if" x_0 in E, 0 & "if" x_0 in.not E, ) $ $bb(1)_E(x_0)$ is called indicator function. ] #exm[ Let $(X, cal(F), mu)$ be a measure space, let $E in cal(F)$ . Then $(X, cal(F), mu|_E)$ is a measure spcae where $mu|_E(F) := mu(E sect F)$ . ] #prp[ #set par(leading: 5pt) 1. $E subset.eq F in cal(F) => mu(E) <= mu(F)$, 2. ${E_j} subset cal(F) => mu(union.big_(j=1)^(infinity)E_j) <= sum_(j=1)^(infinity)mu(E_j)$, 3. $E_1 subset E_2 subset ... in cal(F), mu(union.big_(j=1)^(infinity)E_j) = lim_(j -> oo) E_j$, 4. $E_1 supset E_2 supset ... in cal(F)$ and $mu(E_1) < infinity$ , then $ mu(sect.big_(j=1)^(infinity)E_j) = lim_(j -> oo) E_j $ ] It's easy to see that if $mu = cal(L)^1, E_n = [n, +infinity)$ , then $mu(E_n) = infinity$ but $sect.big_(j=1)^(infinity) E_n = diameter$ . #def[ $(X, cal(F), mu)$ is a measure space, $E in cal(F)$ is $mu$-null if $mu(E) = 0$ . ] #def[ $(X, cal(F), mu)$ is a complete measure space, if $forall E in cal(F)$ is $mu$-null, s.t. $forall tilde(E) subset E$ , it holds that $tilde(E) in cal(F)$ . ] Idea: $cal(F)$ contains all $mu$-null sets. #prp[ Let $(X, cal(F), mu)$ be a measure space, set $cal(Z) = {E in cal(F): mu(E) = 0}$ . Then $ macron(cal(F)) := {A union B : A in cal(F), B subset N "for some" N in cal(Z)} $ is a $sigma$-algebra, and $exists!$ measure $macron(mu)$ on $cal(F)$ that extends $mu$ s.t. $(X, macron(cal(F)), macron(mu))$ is complete. ] #prf[ *Step 1: prove that $macron(cal(F))$ is a $sigma$-algebra.* Clearly, $macron(cal(F))$ is closed under countable unions. Now let $A union B in cal(F)$ with $A in cal(F), B subset N in cal(Z)$ and $mu(N) = 0$. Then $ X without (A union B) &= (X \\ A) sect (X \\ B) \ &= (X \\ A) sect [(X \\ N) union.sq (N \\ B )] \ &= underbrace([(X \\ A) sect (X \\ N)], in cal(F)) union.sq underbrace([(X \\ A) sect (N \\ B)], subset N in cal(Z)). $ Hence $X \\ (A union B) in macron(cal(F))$ . *Step 2: show the existence of $macron(mu)$.* Set $macron(mu)(A union B) := mu(A)$ for any $A union B in cal(F)$ where $A in cal(F)$ and $B subset N in cal(Z)$ for some $N$ . *Step 2.1: check that $macron(mu)$ is a measure.* If $A_1 union B_1 = A_2 union B_2$ where $A_i in cal(F)$ and $B_i subset N_i in cal(Z)$, then $A_1 subset A_2 union B_2$ and so $mu(A_1) <= mu(A_2) + mu(N_2) = mu(A_2)$ and likewise $mu(A_2) <= mu(A_1)$ . *Step 2.2: check that $macron(mu)$ is a measure.* Since $diameter in cal(F)$ and $diameter in cal(Z)$ , then $diameter = diameter union diameter in macron(cal(F))$ and $macron(mu)(diameter) = mu(diameter) = 0$ . $forall A_n in cal(F), B_n subset N_n in cal(Z), n>= 1$ are disjoint, then $ union.big_(n=1)^(infinity) A_n in cal(F), quad union.big_(n=1)^(infinity) B_n subset union.big_(n=1)^(infinity) N_n in cal(Z). $ Then $ macron(mu)(union.big_(n=1)^(infinity)(A_n union B_n)) &= macron(mu)((union.big_(n=1)^(infinity) A_n) union (union.big_(n=1)^(infinity) B_n)) \ &= mu(union.big_(n=1)^(infinity) A_n) = sum_(n=1)^(infinity) mu(A_n) \ &= sum_(n=1)^(infinity) macron(mu)(A_n union B_n). $ *Step 3: prove the uniqueness of $macron(mu)$.* For $A in cal(F), B subset N in cal(Z)$, $ macron(mu)(A union B) &<= macron(mu)(A) + macron(mu)(B) &<= macron(mu)(A) + macron(mu)(N) &= mu(A) + mu(N) &= mu(A). $ ] #def[ $(X, macron(cal(F)), macron(mu))$ is the completion of $(X, cal(F), mu)$ . ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/block-09.typ
typst
Other
// Error: 3 expected closing brace #{
https://github.com/alerque/polytype
https://raw.githubusercontent.com/alerque/polytype/master/data/integral-alignment/typst.typ
typst
#show math.equation: set text(font: "Libertinus Math",fallback: false) $ sum_(k=0)^oo integral_0^oo e^(-k x^2) dif x $
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw5.typ
typst
#import "../../template.typ": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #show: note.with( title: "作业5", author: "YHTQ", date: none, logo: none, withOutlined : false, withTitle :false, ) (应交时间为4月2日) = 也就是证明任意双线性映射 $f: (ZZ_m times ZZ_n) -> C$,均有 $f = 0$\ 事实上: $ 0 = f(m, 1) = m f(1, 1)\ 0 = f(1, n) = n f(1, 1) $ 设 $u m + v n = 1$,则: $ 0 = u m f(1, 1) + v n f(1, 1) = f(1, 1)\ 0 = i j f(1, 1) = f(i, j) $ 证毕 = 考虑正合列: $ 0 -> alpha -> A -> A quo alpha -> 0 $ 由张量积的右正合性,下面的序列也正合: $ alpha tensorProduct M -> A tensorProduct M -> A quo alpha tensorProduct M -> 0 $ 这给出: $ A quo alpha tensorProduct M tilde.eq (A tensorProduct M) quo (alpha tensorProduct M) tilde.eq M quo alpha M $ = 设 $m$ 是唯一极大理想,$k = A quo m$ 是留域,则: $ k tensorProduct M tilde.eq (A quo m) tensorProduct M tilde.eq M quo (m M) $ 同时: $ 0 = (M tensorProduct N)_m = M_m tensorProduct N_m $ 注意到 $k$ 是域,$M_m, N_m$ 是其上的线性空间,也即某个集合上的自由模,除非其中一个为零否则很容易构造出非零的双线性映射。因此上式即表明 $M_m = 0$ 或 $N_m = 0$\ 注意到 $M, N$ 是有限生成模,$m$ 是唯一极大理想,由 Nakayama 引理当然有 $M = 0$ 或 $N = 0$\ = 只需验证保持单射,断言以下的交换图表 #align(center)[#commutative-diagram( node((0, 0), $A$, 1), node((0, 1), $A times M_i$, 2), node((0, 2), $A tensorProduct M_i$, 3), node((1, 0), $B$, 4), node((1, 1), $ B times M_i$, 5), node((1, 2), $ B tensorProduct M_i$, 6), node((0, 2 + 1), $A tensorProduct M = plus.circle_(i in I) (A tensorProduct M_i) $, 7), node((1, 2 + 1), $B tensorProduct M = plus.circle_(i in I) (B tensorProduct M_i)$, 8), node((2, 2), $A times M = plus.circle_(i in I) (A times M_i) $, 9), node((3, 2), $B times M = plus.circle_(i in I) (B times M_i)$, 10), arr(2, 1, $$), arr(2, 3, $$), arr(5, 4, $$), arr(5, 6, $$), arr(1, 4, $f$, inj_str), arr(2, 5, $f times id_i$, inj_str), arr(3, 6, $f tensorProduct id_i$), arr(3, 7, $$, inj_str), arr(6, 8, $$, inj_str), arr(7, 8, $f''$), arr(2, 9, $$), arr(5, 10, $$), arr(9, 10, $f times id$, inj_str), arr(9, 1, $$), arr(10, 4, $$), arr(9, 7, $$), arr(10, 8, $$), )] 这里 $f'_i = (* tensorProduct M_i) f$,$f''$ 既可以由直和给出,也可以由 $(* tensorProduct M)(f)$ 给出,由唯一性可以看出它们是一致的\ 此时,每个 $M_i$ 平坦等价于 $f tensorProduct id$ 是单射,而 $M$ 平坦等价于 $f''$ 是单射 - 若每个 $M_i$ 都平坦,注意到直和是正合函子,$f''$ 作为 $f tensorProduct id$ 的直和提升当然是单射 - 若 $M$ 平坦,观察交换图表可得每个 $f tensorProduct id_i$ 都是单射 = 注意到: $ A[x] = plus.circle_(i in NN^+) A x^i $ 其中 $A x_i$ 作为模同构于 $A$,当然平坦,进而由上题结论知 $A[x]$ 平坦 = 利用泛性质,取: $ funcDef(phi, A[x] times M, M[x], (directSum_i a_i x_i, m), directSum_i (a_i m) x_i) $ 任取双线性函数 $f': A[x] times M -> C$,定义: $ funcDef(f', M[x], C, directSum_i m_i x_i, directSum_i f(1 dot x_i, m_i) ) $ 容易验证 $f' compose phi = f$,且这样的 $f'$ 是唯一的 = 断言: $ (A quo p)[x] tilde.eq (A[x]) quo (p[x]) $ 事实上,容易给出满射 $pi: A[x] -> (A quo p)[x]$ 作为系数同态的提升,且: $ ker pi = p[x] $ 因此结论显然\ 故,当然有 $p$ 是素理想时,上式左右都是整环,继而 $p[x]$ 是素理想\ 极大理想的性质未必成立,例如取 $A = ZZ, p = (3)$,在上面的同构中显然 $(A quo p)[x]$ 不是域,进而 $p[x]$ 不是极大理想 = == 任取 $f: B -> C$ 是单射,往证: $ f tensorProduct id_(M tensorProduct N) $ 也是单射。事实上: $ f tensorProduct id_(M tensorProduct N) = f tensorProduct (id_M tensorProduct id_N) = (f tensorProduct id_M) tensorProduct id_N $ 而: $ f 单 => f tensorProduct id_M 单 => (f tensorProduct id_M) tensorProduct id_N 单 $ 证毕 == 任取 $f: R -> R'$ 是单射,则 $f tensorProduct_A id_B$ 也是单射,进而: $ (f tensorProduct_A id_B) tensorProduct_B id_N = f tensorProduct_A (id_B tensorProduct_B id_N) $ 也是单射,然而注意到 $B tensorProduct N tilde.eq N$,上式表明 $f tensorProduct_A id_N$ 是单射,证毕 = 设正合列: $ 0 -> M' ->^f M ->^g M'' -> 0 $,有: $ M quo ker g = M quo im f tilde.eq M'' $ 而 $im f, M''$ 都是有限生成模。利用选择公理(?)选定一个符合条件的集合上的映射: $ funcDef(phi, M quo ker g, M, m + ker g, m) $ 进一步定义集合上映射: $ funcDef(phi, (M quo ker g) times ker g, M, (x, y), phi(x) + y) $ 显然它是满射\ 由于 $(M quo ker g) times ker g$ 是有限生成模,因此 $M$ 作为有限生成模的满射像显然也是有限生成的 // #align(center)[#commutative-diagram( // node((0, 0), $X$, 1), // node((0, 1), $M quo ker g times N$, 2), // node((1, 0), $C$, 3), // node((1, 1), $M$, 4), // arr(1, 2, $$), // arr(1, 3, $$), // arr(2, 4, $phi$, surj_str), // arr(3, 2, $$, surj_str) // )] // 其中 $X$ 是有限集而 $C$ 是其上的自由模,图上给出了 $phi compose (C -> M quo ker g times N)$ 是满射,进而 $M$ 是有限生成模 = 注意到以下序列正合: $ M ->^mu N -> N quo im mu -> 0 \ M tensorProduct (A quo alpha) ->^(mu') N tensorProduct (A quo alpha) -> (N quo im mu) tensorProduct (A quo alpha) -> 0 \ $ 然而题设表明以下序列正合(利用习题 2): $ M quo alpha M ->^(mu'') N quo alpha N -> 0\ M tensorProduct (A quo alpha) ->^(mu') N tensorProduct (A quo alpha) -> 0\ $ 换言之,有: $ (N quo im mu) tensorProduct (A quo alpha) = 0 => (N quo im mu) quo alpha (N quo im mu) = 0\ => N quo im mu = alpha (N quo im mu) $ 注意到 $N$ 有限生成,$N quo im mu$ 当然也是,且 $alpha$ 含于 Jacobson 根,因此由 Nakayama 知 $N quo im mu = 0$,证毕 = == 任取 $A$ 的极大理想 $m$,注意到以下的交换图表: #align(center)[#commutative-diagram( node((0, 0), $X$, 1), node((0, 1), $A^m$, 2), node((0, 2), $A^m quo (m A^m)$, 3), node((1, 0), $Y$, 4), node((1, 1), $A^n$, 5), node((1, 2), $A^n quo (m A^n)$, 6), arr(1, 2, $$), arr(2, 3, $$), arr(4, 5, $$), arr(5, 6, $$), arr(2, 5, $$, bij_str), arr(3, 6, $$, bij_str),)] 同时,$A^m quo (m A^m), A^n quo (m A^n)$ 是 $A quo m$ 上的线性空间。因此,只需验证 $X, Y$ 也是它们的基即可保证 $abs(X) = abs(Y)$\ 事实上,任意 $A quo m-$模均形如 $C quo m C$,其中 $C$ 是 $AModule(A)$($G$ 当然也是 $AModule(A)$,直接取 $C$ 是 $G$ 对应 $AModule(A)$ 即可),证明其中一个即可,只需验证泛性质: #align(center)[#commutative-diagram( node((0, 0), $X$, 1), node((0, 1), $A^m$, 2), node((0, 2), $A^m quo m A^m$, 3), node((1, 1), $C$, 4), node((1, 2), $C quo m C$, 5), arr(1, 5, $forall f$), arr(1, 2, $$), arr(2, 3, $$), arr(4, 5, $$), arr(2, 4, $exists !f_2$, label-pos:right), arr(1, 4, $exists !f_1$), arr(3, 5, $exists !f_3$) )] 依次给出: - 注意到在我们的取法中,$C = C quo m C$,因此 $f_1$ 就是 $f$,当然取法也是唯一的\ - $f_2$ 利用 $A^m$ 的泛性质作用于 $f_1$ 唯一给出 - $f_3$ 就是函子 $* quo m * = m tensorProduct *$ 作用于 $f_2$ 的像,自然也被唯一给出,同时这是右正合函子,保持满射性 - 至于最终的唯一性,若存在 $g, h$ 使得: $ f = g compose (X -> A^m -> A^m quo m A^m) = h compose (X -> A^m -> A^m quo m A^m) $ 由 $A^m$ 作为自由模的唯一性,应当有 $A^m -> C quo m C$ 的映射唯一,进而: $ g compose (A^m -> A^m quo m A^m) = h compose (A^m -> A^m quo m A^m) $ 然而注意到 $A^m -> A^m quo m A^m$ 是满射,因此 $g = h$,证毕 证毕 == 在交换图表: #align(center)[#commutative-diagram( node((0, 0), $X$, 1), node((0, 1), $A^m$, 2), node((0, 2), $A^m quo (m A^m)$, 3), node((1, 0), $Y$, 4), node((1, 1), $A^n$, 5), node((1, 2), $A^n quo (m A^n)$, 6), arr(1, 2, $$), arr(2, 3, $$), arr(4, 5, $$), arr(5, 6, $$), arr(2, 5, $$, surj_str), arr(3, 6, $$, surj_str),)] 中,第一个满射是条件,第二个满射由函子 $* quo m * = m tensorProduct *$ 保持,因此类似可得 $m >= n$ == 上述函子不保持单射,例如取 $A = product_(i in NN) ZZ$ $ funcDef(phi_1, A, A, (a_k)_(k in NN), (a_(2k))_(k in NN))\ funcDef(phi_2, A, A, (a_k)_(k in NN), (a_(2k + 1))_(k in NN)) $ 它们都是单同态,且 $A = phi_1(A) directSum phi_2(A)$\ 此时取 $X = {x, y}, Y = {z}$, $ funcDef(phi, A^m, A^n, s x + t y, (phi_1(s) + phi_2(y)) z) $ 容易验证它是单射,但不符合结论 = 不妨设 $A^n = M quo ker phi.alt := M'$,$X$ 是其一个基。\ 由于 $pi: M -> M'$ 是满射,它将存在右逆 $sigma$ 使得: $ pi compose sigma = id $ 此处 $sigma$ 是集合间映射,因此 $sigma compose (X -> M')$ 是从基出发的集合映射,由自由模的性质,存在唯一模同态 $sigma': M' -> M$ 使得: $ sigma compose (X -> M') = sigma' compose (X -> M') $ 注意到: $ id compose (X -> M') = pi compose sigma compose (X -> M') = pi compose sigma' compose (X -> M') $ 而 $pi compose sigma', id$ 都是模自同态,自由模的唯一性将给出 $pi compose sigma' = id$\ #lemmaLinear[][ 设 $g: M' -> M, f : M -> M'$,则有: $ f compose g = id => M tilde.eq ker f directSum im g $ ] #proof[ 任取 $a in M$,将有: $ a = a - g(f(a)) + g(f(a)) = (a - g(f(a))) + g(f(a)) $ 显然有 $(a - g(f(a))) in ker f, g(f(a)) in im g$\ 为了证明直和,只需验证分解是唯一的。事实上: $ forall x in ker f, y in M', x + g(y) = 0 => y = 0 => x = 0 $ 证毕 ] 定义模同态: $ funcDef(phi, ker phi.alt directSum M', M, x + y, sigma'(y) + x) $ 利用引理它是同构\ $ker phi.alt directSum M'$ 当然是有限生成模,因此 $M$ 也是,证毕 = 构造双线性映射: $ funcDef(p, B times N, B, (b, n), b n) $ 它当然也是 $AModule(A)$意义的双线性映射,因此可以唯一提升到 $N_B = B tensorProduct N$ 上,仍记作 $p$,并满足: $ p(b tensorProduct n) = b n $ 从而 $1 tensorProduct y = 0 => p(1 tensorProduct y) = 0 => y = 0$,因此 $g$ 是单射\ 注意到 $p compose g = id$,$p$ 当然是满射,利用引理即得同构
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/056%20-%20Outlaws%20of%20Thunder%20Junction/002_No%20Tells.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "No Tells", set_name: "Outlaws of Thunder Junction", story_date: datetime(day: 12, month: 03, year: 2024), author: "<NAME>", doc ) New beginnings, huh. Brutal stuff—you have my sympathies. Never saw a new beginning that didn't involve burning something down, and if that metaphor sounds cute to you, I invite you to smell the wet ashes of a day-old fire, and know that it's #emph[changed] everything you loved, better than magic ever could. This particular new beginning, this particular bright and shiny sunrise, involved a dame walking into my bar with literal fire in her hands. You can guess how it went from there, and the place wasn't even open yet. I knew her, of course. We were friends once, Elnor and me. But it was complicated, and I wasn't up to thinking about complications when she showed up in that gorgeous burgundy New Capennan tailor-made, a snake demon as thick as a sailor's rope twined around her arm, and aimed her hand at me. The snake was gorgeous, a bright, new-shed green. Set off the suit like a treat. The thing shot a jet of flame from its mouth, hot as a cremation in winter. With me caught unawares, she couldn't miss—it was a warning shot. "Lady!" I said. I talk better when I'm telling a story. Best I could say about that line is that I accurately identified her as a lady. The flame hadn't caught, just hit some glasses hanging behind the bar and melted them. I had my thunder bow in front of me, but I'd been tinkering with it. It was in no condition to draw on anything. Fortunately, Elnor wanted to talk, although the only sweet memory she wanted to jaw over was, "Where did the money go, Yuma?" "It went where money goes," I snapped at her. "#emph[Where's the money?] Where are the old kings and the dead gods? What are you #emph[doing] here?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Elnor and I were broke when we met. The two of us teamed up with some friends—her girlfriend Shadress and some other nice folks now dead or in jail—because we had dreams, gods help us. Seven different dreams, maybe, but we pooled them and averaged them out, and what we came up with was this. We would leave the Riveteers, where we'd all spent our youth. Then we would #emph[build] something. The Riveteers are supposed to be builders, blacksmiths, carpenters, right? That used to mean something, before this gang of laborers that banded together against the bosses became just another set of bosses. So me and my friends, we would start over, do it right. We found an empty warehouse to squat in and wrote a manifesto. We had all the skills we needed. I was a weaponsmith, Shadress was a tailor, Elnor looked cute. The money we earned would be shared. We'd recruit other people and so on, and so on, and so on to utopia. But every family has drama, and this one also had rent. The owner of the squat showed up with thugs and impounded all our gear, so we couldn't make a living. He said he'd give it back if we paid the back rent, but we didn't have that kind of money. So, obviously, it would have to be crime, the main industry in New Capenna. Top import, top export. We knew how to steal, too, and the equipment for #emph[that] was cheaper. If you do it right, you don't even need weapons, although I'll be honest: we did it wrong. Elnor was amazing back then. It was cheap of me to say she just looked cute. She had charm, and if you think that's nothing, you've never been charmless. I'm charmless myself. They like me here in Thunder Junction because I introduced cocktails to the desert. They don't like me for my class. She could drink. She could gamble. She could flirt. She was a perfect distraction, and since she could do makeup and dress with style, she was good at disguising herself, too. You don't need to glam yourself up with magic, or even use the normal boring tricks of disguise—cotton in your cheeks, change your glasses, ill-fitting clothes. You can do it all with acting and makeup. They expect one kind of girl, but here comes another. Trust me, I tried hard to be a girl for a certain number of years. It takes skill. You have to function through the pressure of all that being looked at—the way people look at women, assessing, selecting, all without regard to whether you're selecting back. It's not why I had to remake myself as a man, but I have to admit, I was also bad at it. Elnor was a genius, a natural. Function through being looked at? Put her in a room full of crime bosses, and she could win a poker game naked. So, while Elnor chatted up guards and croupiers and bank clerks, we blew safes and teased open vaults, we muscled our way through trains on rickety bridges. Those were the days! I remember them in lights and sights. The sawdust on our workshop floor, how the sunlight made it sparkle. The stained velvets in a maestro's darkened parlor, as my hand learned how heavy gold is. New Capenna was a ruined town. Even new things were ruined there. I know because we were new, and ruined. This went on for a couple of years. Oh, we got the rent money pretty quick, but then we decided it would be safer and cheaper to own a building. That was Shadress's idea—Shadress who was the exact opposite of Elnor, and the exact opposite of me. Figure #emph[that] out, if you can, but you'd need more advanced math than the Riveteers ever taught me. She only wore rusty black, with two crossed pins in her collar. She had a tailor's trick of talking with her mouth closed, because they keep pins in there, too, and when she talked, it was never direct. It wasn't, "We'll be stronger if we stick together." It was, "The two sides of an arch are always falling toward each other. That's why it's strong. If we can be like that, we'll be all right." See what I mean? We were all disasters; we couldn't have stuck together if we tried. But we could try to fall toward each other, and we did. For a bit. Anyway, that building was the worst call Shadress ever made. We borrowed the money to buy it. You can guess what happened next. Debt comes down on you in layers. And funding your debts with theft, you make twice the enemies. I won't trouble you with the whole boring story, except that I took off eventually. Just ran off down the Omenpaths, not knowing where I was going. Everyone who stayed was going to die, go to jail, or go back to being a foot soldier in one of the gangs. Back to being the lowest iron-chewer in the Riveteers? No. I wanted a #emph[new] life. Justifying myself? Of course I'm justifying myself. But I'm right, too. I could die with my friends or live alone. What I took wouldn't have paid a month's interest, and I kept it out of the hands of our enemies, didn't I? #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I threw a bottle. My virtue in a fight is that I'm fast. And I had another worry, too, besides Elnor and the disassembled crossbow. Kirri was there on the bar, in the basket where he likes to curl up. He can stay as still as a rock, so it just looked like I had an ordinary potted cactus, a bit of décor—but she was pointing that snake uncomfortably close to him, and even if I didn't make it out of here, I had to give him a shot at escape. That little guy has saved my life twice. You'll hear about both, in five minutes and ten. I'm fast, like I said. And though Elnor's fast, too, boy, I can surprise you. It's about keeping your muscles relaxed until the last-possible moment. No twitches, no tells. She hadn't told me to keep my hands where she could see them, but I kept them there anyway, right on the cool stone top of the bar. I could feel the shallow places in the stone where the mason didn't scrape it all the way clean. Then I threw myself to the side, grabbed the bottle, hurled it end over end. She shot and ducked at the same time, but I'd anticipated that, and the bottle shattered against the creature, making its jet of fire blue for a second. It melted a hole in the stone wall behind the bar, and her velvet arm was glittering with fragments of glass. Now the snake was stunned—hate to do that to a demon who didn't ask to be summoned, but better that than Kirri. He was still in his basket, still not moving. I never know what he's thinking. He's smart, but he's not what you'd call emotive. I had a couple of seconds. I used them to get my thunder bow back together and in my hand. It's a heavy, well-balanced crossbow with a stock polished bright, and it can channel lightning, hard, crackling bolts of it. Besides hunting, I mostly use it to kick people out of the bar, so it's bigger and more complicated looking than it needs to be. "I don't get it, Yuma," said Elnor. She was cool for a woman with thunder pointed at her; I could smell the power, like the smell of rain coming to the desert. "Weren't we good to you? Didn't we accept you when nobody else did? Didn't we hook you up with the best body-man in the city to change your humors, to make you a fella?" I said, "I didn't think I had to pay for your acceptance." "You don't think you have to pay for #emph[anything] of mine." "I take your point. I—" "I just told you, you've taken enough." "Walked into that," I told her. "Listen. The money's gone. I spent it. There's nothing here to get back, and I don't believe you even want to. How long have you been looking for me? A year? That's plenty of time to forget why you're doing something." Her hand flexed. The snake was looking better; as I watched, it coiled tighter around her arm, digging into the fabric, and its head reared higher. It breathed red flame, not at me, but just into the air, warming it. It's cold in the desert in the morning, and this creature was far from home. "Don't patronize me," Elnor said. "Don't try to talk me down. You always thought you could talk your way out of trouble, but all you can do is tell a story. And that's not a story about me." "Sure. Well, what is, then?" "I know a story about me," she said slowly, "and it's very painful, but I'll tell if you'd like. In honor of our old friendship." "Yeah?" "It's called #emph[Where's the Money?] " #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I had all the money sewn up into the lining of my suit when I came to Thunder Junction a year ago. It was heavy, all in tens and fives, lead and bronze coins, and it really ruined the drape. Omenport is the first city you see here, a friendly place, all wooden spires and sheltering cliffs, but it was the first place anyone who came after me would see. I knew I had to beat tracks out of there. What I didn't know was how to beat tracks, if you follow me. No idea how to survive in the desert. What passes for wilderness in New Capenna is just ruined suburbs. And it had to be on foot. I didn't trust the trains—obvious New Capennan creation, people from home would use them. And what did I know about riding? I'm a city boy. I hadn't even ridden a bicycle. So, I set off walking on the Thunder Junction road. The suit was new. Clothes matter back in New Capenna, even more than here, and I had it all custom-made by Shadress. Black wool, black velvet, pinstripes dripping from hip to hem, and I must've looked like a million bucks as I was dying. Heat exhaustion comes up on you unawares is what I've learned since then. First sign of it: you don't think clearly. Call me what you want, maybe I should've known better, but I grew up in a city where everyone always looks fantastic—not just because of the tailoring, but because the clouds and smog and the shadows of the buildings make everything dim and glamorous. I wasn't used to that big, full sun. Anyway, there I was, sitting on a rock with my sleeves rolled up and my jacket draped over my arm and making it sweat-slick, and there was this little. I mean. There was this little #emph[guy] . A sturdy little cactus, a toddler in shape and size, with six stumpy arms. Not much of a face, but I somehow knew he was well disposed to me. I put my jacket around him to keep from being hurt by the spines and picked him up. #figure(image("002_No Tells/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) I've seen a lot of things in my time. Humans, demons, great machines, revolutions, tragedies. A plane coming to an end, like New Capenna—it has a lot of things happening. Like how a broken bottle shatters into tiny pieces. The more shattered it is, the more pieces there are to catch the light. Thunder Junction's a new plane, one that's still beginning. It's still whole. So, when I say I hadn't seen anything like a baby cactusfolk, I mean it. There wasn't #emph[room] for something like him back home. He didn't lead me to water or anything like that. He'd just awakened a few minutes before. Didn't know how to do anything. But he took this shine to me, and being looked at in a friendly way made me see myself from the outside, and asked what I needed. I figured water flowed down, so I looked for low ground. Low ground turned out to be a dry riverbed, cool water under the sand. So, I lived. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "I told you, the money's gone," I said. Kirri'd had plenty of opportunities to run during that first little fracas, but he didn't run, of course; he doesn't do what he doesn't care to do, even if it was making me sweat with nerves. "Still don't believe you." "Fine. I lied. It's not gone. You're standing in it." "This is your bar?" "It's our bar," I said. "Me and the other bartenders, the piano player and the dancers. The cleaner, the cook. We run it together. We divvy the proceeds. It's just like we dreamed of back home." "But you own it." "Sure I do." "So you're not just a thief. You're a boss." "If you want to put it like that, yes, I am." She shrugged. "I don't know which one I hate more." "I'm guessing thief, but you're a thief, too." She snapped her fingers; the snake came to attention. I dove behind the bar, heard her running over to me. Cover is a trap if you're not nimble. I jumped up, hurled blurry lightning at her, and she drenched the air with flame back at me: both missed. She hit some more bottles behind the bar, though, vaporized what was inside. I was diving out of the way on a floor covered in glass and slag, hollering, "Do you have any idea what those bottles cost?" She'd taken cover behind some of the gaming tables. My bar's got two levels, floor and mezzanine. There are some bedrooms up there, empty now. Card and dice tables in back. I introduced those to Thunder Junction, too, made a fortune on 'em. I cringed at the thought of burned holes in those acres of felt, so I stayed down, didn't shoot till I heard her move. We traded shots. All of mine went high because of the damn tables. She was creeping around fast and silent, trying to come at me from unexpected places, mostly succeeding. I knew the longer this went on, the worse my odds were—she had the whole room to maneuver in, and she didn't care what state she left it in—so I crawled the length of the bar and leaped over it suddenly, feeling the freedom of the room opening up, bolting for the staircase—and away from Kirri, who still wasn't moving. Away, away, up, up! There goes Yuma, certified genius, heading for the high ground. I caught a look at her stunned face, pointed my bow as I ran, and then, just as I came to the top step, she aimed calm as you please and set the stairs on fire behind me. I had carpet on the stairs, another of my classy ideas, and now yet another one that's backfired on me because the fire fed on it like a starving beast. It was blue-hot, fast, and dangerous, surging up toward the mezzanine and cutting off my escape. I saw everything from above: the bar with the melted bottles, the hole letting in a round shaft of morning sun, Kirri in his basket, his snappy little movement as he looked up at me; Elnor, pale, standing still with the snake twining around and around her arm. I realized then that she #emph[probably] didn't really want to kill me. Her aim's not that bad. But if I were waving a stack of soft paper money at one of our craps tables, I wouldn't have bet on that number, so I darted back into one of the bedrooms. A roar of fire punched a hole right through the door, the angle sending it through the ceiling, too. "Stop setting fire to my bar!" I hollered through the hole. "Step toward the light, and I won't have to!" So here, again, is Yuma, certified and celebrated genius, the man on the cover of all the papers. The rooms on the second floor are all connected, right? That way you can make them into suites. Since they were all vacant, the doors were open for airing, meaning I could run soundlessly to another room and burst out the door, getting one good shot in. I ran, threw the door open, and there she was, standing on the bar in her filthy boots, aiming right at me. I raised my forearm instinctively against the jet of flame, felt the fire hit it, and screamed in pain. It was an ugly burn, and it left an ugly scar, but it was nothing like it should have been. It should have gone straight through me. She still didn't want to kill me—but she sure was psyching herself up to. Behind her, I could see Kirri perched in the new hole in the wall. I tried to signal with my eyes, then with my face, then with my head, that he should go, hop out, get away, but he wouldn't move, just stood there watching me. Like he was trying to convey something I wasn't cactus-like enough to understand. I'd been worried about drawing Elnor's attention to him, but she was just looking at me, puzzled. Flames were all around her now—the furniture was going up, the stairs were charcoal, and the tumbleweed thatch of the roof was half-gone. In another few minutes, the place would be one big chimney. And still there was Kirri, sitting in that hole in the wall like it was a window seat I'd just built for him. "I'm not going to turn around," she told me patiently. "I know you're trying to fake me out. If someone's back there, they can't save you." Remember how I told you that it's funny, the thoughts that come to you in a fight? With my flesh singed, the little hairs burned away, my new friend patiently waiting for me to understand something, my old friend with her hair singed and wild, the snake rearing back from her arm—all I could think about was that train heist, back home in New Capenna. It was the beginning of the end for us, but it was a proud hour while it lasted. We were surrounded on all sides by Brokers muscle—they were flooding in from the car ahead and the car behind. All we had was speed and unpredictability, but that was Elnor's forte. She was dancing around them, using every part of that grimy third-class car. Seats were cover; the bars of the luggage shelves were for pulling herself up into the air; light fixtures were for rebounding bolts of magic like trick shots in pool. Nobody knew what she'd do next, and that was how we beat the odds for one more day. Real fights are all about rhythm. You try to anticipate your opponent's rhythm. You try not to fall into one yourself. It's that simple. The thing was, she could read my mind, because I had the same rhythm I always had. She #emph[knew] me. Oh, we'd never been that close. In our old group, I was always better friends with other people—Elnor was too good a time for me. But intimacy doesn't take love, it just takes practice. I wasn't familiar with her anymore, though. She was fighting like someone else. She was fighting like #emph[Shadress] . Calm, careful, waiting, and thinking. And that meant that Shadress was dead, because you don't calm down that much, that fast, unless by way of honoring someone's memory. Shadress was the best of us. I never believed in moral authority until I met her. Well, I never believed in either one—morals or authority. She got depressed after the train job, and kind of faded away, and we all started squabbling then. Fell in separate directions. I think she knew that we'd all lost sight of the goal, when the goal was far away and the money was right there. But she really was the best person I ever knew. All this went through my head in thirty seconds, which is a long time. Elnor was just watching me figure it all out. She was giving me the time for that, because revenge isn't any good if the person doesn't know why it's happening. But she #emph[was] here for revenge, and I knew she wouldn't hold the next shot back. So, I did something she couldn't predict. I fired my thunder bow at the long mirror behind the bar. It shattered into a shower of lost money, raining down a curtain of shattered glass. Kirri was watching me through it, and I could tell that, in his quiet little way, he approved of whatever I was doing. Elnor really did turn and look at that; she couldn't believe I'd wreck my own place, even after she'd already wrecked it so thoroughly herself. Then, among the brightness and the noise, and the choking thick smoke of my investment, I leaped down and went after her hand to hand, attacking not with thunder or any kind of magic, but with my burned fist and my undamaged one. We rolled around on the floor, grappling. With both hands I wrestled the snake demon off her and hurled it across the room; it was muscular and strong, but no more than any other animal. Same trick as with the bottle. Funny how these magical creatures sometimes only have defenses against magic. They're shocked by simple force, and Elnor was the same. Well, yes, of course I could have just killed her. I didn't want to, that's all. And I was sure of that. It's the only way to #emph[guarantee] you'll lose a fight: go into it without knowing what you want out of it. I knew what I wanted, and Elnor didn't, and that's not why I won, but it's why she lost. The room was almost silent suddenly, no more big dramatic moves, just two people, tired, breathing heavy among the crackle of sparks. Elnor knows how to fight with her hands, too, but it was my specialty when I was a kid. When other kids were training in summoning and lockpicking and all the different kinds of magic, I was out on the street with my fists. A little rebellion against my dad. So there we were, going at it, me slowly winning but both of us about to choke on the smoke, when suddenly the rain hit. In Thunder Junction, the desert rain is hard and sudden. It comes clap out of a blue sky; the clouds rush up on you like a train, and then you're soaked to the pores, with impossible little flowers coming out all around you. It was winter then, thunderstorm season, but still I didn't expect it. In an instant, the fires were out, and the whole place was black and acrid like a candle wick that's just been snuffed. With the water and all that char, you could have dipped a pen in the puddles on the floor and written a poem, if you had a mind to write a poem, which just then I did not. I was still coughing out the smoke from a fire that no longer existed. She was coughing, too. And then I knelt on her sternum, grabbed her wrists, and it was done. I told her what I'm telling you now, what I tell every stranger who wanders into my bar in clean tight clothes and new boots. You say you're here for a new beginning? Fine—but that means giving up on the past. On pretending that you can still change it. "The past is dead," I said. "It's over. You're in a new place, and that means starting from nothing." "You're so wise, Yuma." Her face was slick with rain; she kept having to blink it out of her eyes, shaking her head around. "And it sure is convenient—how your wisdom means I have to forgive you." "I don't expect you to forgive me," I said. "I'm ashamed of what I did. I'd do it again, and I'd be ashamed of it again. But this is Thunder Junction—people are #emph[different] here. They're here to invent themselves." "Reinvent, you mean." "#emph[Invent] . Like a piece of machinery. Riveteers are good at tinkering, but it's all ready-made parts, ideas someone else built and broke. Here, you can forge yourself in a new fire." "Haven't you had enough of fire?" She coughed one final time. "You want me to be your friend? Team up with you? Maybe you'll give me some more life lessons like this one?" "Nope. That door's closed. I don't want to see you again. You don't want to see me. But you can start a new life. Or I guess I can kill you, if you insist, or you can kill me—and what? Take over the bar? Take over the mortgage? Pay to repair all the damage we just did? Look, either you're gonna be in the red or I am." She smiled a little, and for a moment, it was just like old times, in the way your reflection in a mirror is just like you—you can't hear it or smell it, it's got no warmth, but you feel something anyway. I knew I'd gotten through to her, and it's not because I had my lines straight, but just because she'd lapsed back into seeing me as a person. It's easy to stay mad at a phantom, or to flee one, too, but a person has got to be reckoned with. And that's when Kirri had his say. The rain all around us was gone all of a sudden, and there was a different feeling to the air. We both noticed it, and I finally let go of her wrists—my burned hand was in agony, a sharp, hot, smooth pain—and we looked around to see what had happened. Well, you've seen what the place is like now, but imagine what it was like to watch it happen. The whole inside of the room was alive with vines. They were running up the walls like water runs down—quick and flowing, massive red flowers dropping open like bells, filling up the massive holes in the ceiling. Weaving themselves together, fanciful patterns, knots, curlicues. And there was Kirri floating an inch in the air above the bar, hardly moving, just floating there serenely as the room filled up with life. I've had all sorts of great minds come in here, try to make sense of it. Apparently these vines are like no species seen anywhere, on any plane, or any plane that people've come back from. Kirri just invented them. They make the air so humid, even with the desert outside, that people stand there in the doorway and suck it in like a cool drink. The vines stopped moving finally, and Kirri dropped back down to the surface of the bar, sat down on it, and went cactus-still again. Elnor didn't do anything much. She just got up, shook out her arms, gazed up around her. Finally, she said, "Where'd he come from?" "He's been here the whole time." She kind of snorted. "Well. Let's call it. Because you're not wrong." "No." "I still hate that you spent our money on this place. Congratulations. You turned something into nothing." "We all turned a lot of something into nothing, back on New Capenna. The love was real, though." "All right," she said and whistled softly. The little snake was draped over a vine nearby; it slid down to the floor—maybe a little reluctantly—she picked it up and draped it around her shoulders. She walked out without looking back.