repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/soupslurpr/BeauTyXT | https://raw.githubusercontent.com/soupslurpr/BeauTyXT/main/README.md | markdown | ISC License | # BeauTyXT
BeauTyXT is a beautiful, private, secure, and minimalistic Text, Markdown, and Typst editor.\
Now sandboxes all Rust code in separate processes for better protection against exploitation – because that's what
the cool kids do 😎
## About
Check out the official website at https://beautyxt.app/ for more info and download.
## Contributing
Check [CONTRIBUTING.md](https://github.com/soupslurpr/BeauTyXT/blob/master/CONTRIBUTING.md) for things to know
if you want to contribute. Also points to build instructions.
## Donation
Like BeauTyXT? You can donate to [soupslurpr](https://github.com/soupslurpr), the lead developer of BeauTyXT to support their work on BeauTyXT and their other open source projects. Thank you!
[Monero](https://www.getmonero.org/) address:\
`<KEY>`
The [Monero](https://www.getmonero.org/) address can also be found in the app's settings.
## Branding
You may not use the name "BeauTyXT", a name that includes "BeauTyXT", and the app icon in a derivative work that has published builds.\
This is to prevent confusion of which is the official BeauTyXT.
|
https://github.com/ufodauge/master_thesis | https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/components/intro-section/toc-figure.typ | typst | MIT License | #import "@preview/oxifmt:0.2.0": strfmt
#import "../common/page.typ" : Page
#let TocFigurePage(title: "図目次", target: image) = locate(loc => [
#let images = query(figure.where(outlined: true, kind: target), loc)
#let lines = images.fold((
lines : (),
options: ( latest_chapter: none )
), (( lines, options ), image) => [
#let img_loc = image.location()
#let chapter = counter(heading).at(img_loc).first()
#let index = image.counter.at(img_loc).first()
#let page_index = counter(page).at(image.location()).first()
#if (options.latest_chapter == none) {
options.latest_chapter = chapter
}
#if (options.latest_chapter != chapter) {
lines.push(v(10pt))
}
#lines.push(
grid(
columns: (18pt, 28pt, 1fr, 10pt, 18pt),
none,
[
#strfmt("{}.{}", chapter, index)
],
[
#image.caption.body
#h(1em)
#box(width: 1fr, repeat(box(inset: (x: 0.25em), ".")))
],
none,
align(right)[
#page_index
]
)
)
#return (lines, options)
]).first()
#Page[
= #title
#for line in lines [
#line
]
]
])
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/bibliography-00.typ | typst | Other | // Test ambiguous reference.
= Introduction <arrgh>
// Error: 1-7 label occurs in the document and its bibliography
@arrgh
#bibliography("/works.bib")
|
https://github.com/a-mhamdi/graduation-report | https://raw.githubusercontent.com/a-mhamdi/graduation-report/main/Typst/en-Report/CP-Report.typ | typst | MIT License | // CAPSTONE PROJECT
#import "Class.typ": *
#import "Title-page.typ": *
#set document(author: author, title: title, keywords: keywords, date: auto)
// The project function is called with the content of the document.
#show: report.with(
title: title,
titre: titre,
diploma: diploma,
program: program,
supervisor: supervisor,
author: author,
date: date,
bibFile: "Biblio.bib",
isAbstract: true,
)
#titlepage(
title: title,
titre: titre,
diploma: diploma,
program: program,
supervisor: supervisor,
author: author,
date: date
)
#pagebreak()
#place(bottom + right, box(width: 256pt, text(emph(dedication))))
#set page(header: none)
#chap("Acknowledgements", notAck: false)
#pagebreak()
#ack
/* ### Capstone Project Report ### */
// TOC
#set page(numbering: "i")
#counter(page).update(1)
#{
show heading: none
heading(outlined: false, bookmarked: true)[Contents]
}
#outline(depth: 3, indent: auto)
// LOF
#pagebreak()
#{
show heading: none
heading(outlined: false, bookmarked: true)[List of Figures]
}
#outline(
title: [List of Figures],
target: figure.where(kind: image),
)
// LOT
#pagebreak()
#{
show heading: none
heading(outlined: false, bookmarked: true)[List of Tables]
}
#outline(
title: [List of Tables],
target: figure.where(kind: table),
)
#set page(numbering: "1")
#counter(page).update(1)
// --- GI + Chaps + GC ---
#include "chaps/intro.typ"
#include "chaps/chpt1.typ"
#include "chaps/chpt2.typ"
#include "chaps/chpt3.typ"
#include "chaps/outro.typ"
// --- END OF DOCUMENT ---
|
https://github.com/dark-flames/resume | https://raw.githubusercontent.com/dark-flames/resume/main/data/interest.typ | typst | MIT License | #import "../libs.typ": *
#let interest(env) = {
cv-content(env, {
multiLang(env, en: [== Research Interests])
[
- _Implementation of dependently typed programming languages_ , focusing on features such as pattern matching.
- _Semantic models of type theories_, especially categorical semantics, leveraging categorical perspectives to grasp the essence of new language features quickly.
- _Semantics-based approaches for programming languages_, such as normalization-by-evaluation and logical relations.
- _Dependent version of practical type systems_, such as gradual typing and effect systems.
]
})
}
|
https://github.com/buxx/cv | https://raw.githubusercontent.com/buxx/cv/master/README.md | markdown | To build the cv, install [typst](https://typst.app/) then :
typst compile cv.typ
|
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/ads/meta.typ | typst | // 'de' or 'en'
#let language = "de"
#let author_first_name = "Maxim"
#let author_last_name = "Mustermann"
#let author_matrikel_number = "123456"
#let author_course = "course_id"
#let thesis_supervisor_first = "Prof. Dr. <NAME>"
#let thesis_supervisor_second = "Dr. <NAME>"
#let thesis_supervisor_third = "<NAME>"
#let thesis_type = "Bachelor"
#let thesis_subject_type = (
"de": "Seminararbeit",
"en": "Term paper"
)
#let thesis_title = (
"de": "Titel der Arbeit",
"en": "Title of the thesis"
)
#let thesis_sub_title = (
"de": "Optionaler Untertitel der Arbeit", // <-- "" for ignoring subtitle
"en": "optional subtitle of the thesis", // <-- "" for ignoring subtitle
)
#let thesis_study_course = (
"de": "Informatik",
"en": "Conputer Science",
)
#let bib_file = "../main.bib" |
|
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/可视化/线条/xiantiao.typ | typst | = 线条
定义如何绘制线条。
描边具有油漆(纯色或渐变)、粗细、线帽、线连接、斜接限制和虚线图案。所有这些值都是可选的,并且具有合理的默认值。
#image("1.png")
= 简单的笔画
您可以从颜色、粗细或两者的组合创建简单的实心描边。具体来说,无论在哪里需要笔画,您都可以传递以下任何值:
指定描边粗细的长度。颜色是继承的,默认为黑色。
用于描边的颜色。厚度是继承的,默认为 。1pt
使用运算符从颜色和粗细组合而成的描边,如 中所示。+2pt + red
为了实现完全控制,您还可以为任何需要笔画的函数提供字典或对象。字典的键可以包含构造函数的任何参数,如下所示。stroke
= 领域
在描边对象上,您可以访问构造函数中列出的任何字段。例如,是 。同时,是因为它未指定。设置为的字段将被继承。(2pt + blue).thickness2ptstroke(red).capautoauto
= 构造 函数
将值转换为笔画或使用给定参数构造笔画。
请注意,在大多数情况下,您不需要将值转换为笔画即可使用它们,因为它们将自动转换。但是,此构造函数可用于确保值具有笔画的所有字段。
#image("2.png")
#image("3.png")
#image("4.png") |
|
https://github.com/SSSayon/analytical-mechanics | https://raw.githubusercontent.com/SSSayon/analytical-mechanics/main/note.typ | typst | #import "conf/conf.typ": *
#show: conf
#set math.vec(gap: 0.8em)
#set math.mat(gap: 0.6em)
#align(center, text("Notes on Analytical Mechanics", size: 15pt))
#align(center, "Sayon")
#align(center, "2024 spring")
教材: <NAME>, _Mathematical methods of classical mechanics_
1. Newtonian mechanics
2. Lagrangian mechanics
- variational principle 变分法
3. Hamiltonian mechanics
- symplectic structure 辛结构
4. Integrable systems
5. Nonintegrability
6. Relativity
#line(length: 100%)
Kepler's 3 laws
1. Each planet moves on an elliptical orbit with the sun at one focus.
2. The area swept by the planet within unit time is a constant. (angular momentum conservation)
3. The ratio of the cube of the semimajor and the square of the period is a constant. ($a^3/T^2$ = const)
\
The principles of relativity and determinacy:
A. space($RR^3$) and time($RR$)
B. Galileo's principle of relativity
#pad(left: 1em)[
There exist coordinate systems (called inertial 惯性的) with the following properties:
- All the laws of nature at all moments of time are the same in all inertial coordinate systems
- All coordinate systems in uniform rectilinear motion w.r.t. an inertial one are themselves inertial 相对于惯性坐标系作匀速直线运动的坐标系是惯性的
]
C. Newton's principle of determinacy
#pad(left: 1em)[
The initial state of a mechanical system (the totality of positions and velocities of its points of some moment) uniquely determines all its motion.
]
\
_Galileo structure_
1. The universe - a four-dim affine space (仿射空间) $A^4$. The points of $A^4$ are called world points or events. The parallel displacements of $A^4$ constitute a vector space $RR^4$.
2. Time - a linear map $t: RR^4 -> RR$. If $t(a-b) = 0, a, b in A^4$, we say $a$ and $b$ are simultaneous events.
3. The distance between simultaneous events $a$ and $b$: $quad rho(a,b) = sqrt(angle.l a-b\, a-b angle.r)$
\
The _Galileo group_ is the group of all transformations preserving the Galileo structure.
The elements of Galileo group are called _Galilean transformations_. \ Thus, Galilean transformations are #underline("affine transformations") of $A^4$ which preserve #underline("intervals of time") and #underline("the distance between simultaneous events"). (保持时间间隔和同时事件距离)
Three types of elements of Galileo group: (在伽利略坐标空间 $(t,arrow(x)) in (RR, RR^3)$ 下)
1. uniform motion: $g_1(t, arrow(x)) = (t, arrow(x)+arrow(v) t)$, $arrow(v) in RR^3$ velocity
2. translation: $g_2(t, arrow(x)) = (t+s, arrow(x) + arrow(s))$, $forall t in RR, arrow(x) in RR^3$
3. rotation: $g_3(t, arrow(x)) = (t, G arrow(x))$, $G: RR^3 -> RR^3$ orthogonal transformation
\
Newton mechanics
$ m dot.double(x) = arrow(F) (x, dot(x), t) $
1. By the time translation, we get that the equation $(dif^2 x(t+s))/(dif (t+s)^2)$ does not depend on $t$ explicitly
2. By the space translation, we get that the equation depends only on relative positions
3. By the rotation, we get $F(G x, G dot(x)) = G dot.c F(x, dot(x))$, $G$ orthogonal transformation of $RR^3$
$ m_1 dot.double(x)_1 = (G m_1 m_2 (x_1 - x_2))/(||x_1 - x_2||^3) $
$ m_2 dot.double(x)_2 = (G m_1 m_2 (x_2 - x_1))/(||x_1 - x_2||^3) $
#pagebreak()
#line(length: 100%)
Chapter 02
#line(length: 100%)
#set math.equation(numbering: "(1)")
*Systems of 1 degree of freedom:* discribe by
$ dot.double(x) = f(x), x in RR $ <1_deg_of_freedom>
Kinetic energy: $T = 1/2 dot(x)^2$
Potential energy: $U(x) = - display(integral_(x_0)^x f(t) dif t)$
Total energy: $E = T + U$
\
*Thm.* For a system evolving according to @1_deg_of_freedom, its total energy is conserved.
_Proof._ $dot(E) = dot(T) + dot(U) = dot(x) dot.double(x) + (-f(x)) dot(x) = 0$
\
Setting $y=dot(x)$, we convert @1_deg_of_freedom into
$ cases(dot(x) = y, dot(y) = f(x)) $
Phase space (plane): the space $RR^2$ of $x$ and $y$
\ Phase point: a point in the phase plane
\ Phase curve: the image of a solution in the plane space
\
_Example: Harmonic oscillator_ 谐振子
#align(center, $dot.double(x) = -x$)
$display(==> cases(dot(x)=y, dot(y)=-x) quad ==> vec(x, y)' = mat(0,1;-1,0) vec(x, y) )$
#v(0.4em)
$K = 1/2 dot(x)^2 = 1/2 y^2, U = -integral (-x) dif x = 1/2 x^2 ==> E = 1/2(x^2 + y^2)$
#figure(
image("img/harmonic_oscillator.svg", width: 30%)
)
\
More generally, we consider
#align(center, $display(E = 1/2 y^2 + U(x))$)
$==> y = plus.minus sqrt(2(E-U(x)))$
_从 $U$ 画相图的方法:_
\ Rules: (1) $y = - sqrt(2(E-U(x)))$ has the same monotonicity as $U$.
\ #h(29.5pt) (2) In the upper half plane $y>0$, $y =dot(x)$, this means, points move to the right.
\ #h(29.5pt) (3) If the $E$-level set ${1/2 y^2 + U(x) = E}$ does not contains any critial point of $E$, then the level set is an entire periodic orbit.
\ #h(29.5pt) (4) If the $E$-level set contains a critial point $x_t$ of $E$ and if the critial point is nondegenerate, then depending on the sign of $U''(x_t)$, it gives a _saddle_ if $U''(x_t)<0$ and a _center_ if $U''(x_t)>0$.
#figure(
image("img/phase_curve.svg", width: 40%)
)
如图所示, $E_2$-level set 包含了一个 saddle, $E_4$-level set 包含了两个 center.
#v(0.5em)
$display(cases(dot(x) = y, dot(y) = -U'(x)))$ , suppose $x^*$ is a critical point.
The linearized equation
$display(cases(delta dot(x) = delta y, delta dot(y) = -U''(x^*)) quad i.e. vec(delta dot(x), delta dot(y)) = mat(0,1;-U''(x^*),0) vec(delta x, delta y))$
// 局部极大值, 则两个特征值 加起来等于 0, 乘起来小于 0, 则是两个纯虚数
\
#line(length: 100%)
*Systems of 2 degree of freedom:*
*N$dot.double(upright(bold(o)))$ther's law:* _symmetry (invariance under a continuous group)_ implies conservation law.
We say s system has _2 degrees of freedom_ if it satisfies the equation
$ dot.double(bold(x)) = bold(f)(bold(x)), bold(x) in RR^2 $
A system is called _conservative_ (保守系统) if there exists a function $U: RR^2 -> RR$ s.t.
$ bold(F) = -nabla U $
The equation is
$ dot.double(bold(x)) = -nabla U(bold(x)) $
We define the total energy as $E = 1/2||bold(y)||^2+U(bold(x)), bold(y) = dot(bold(x))$.
*Thm.* A conservative system has the law of energy conservation.
\
*Def.* The motion of a point in a _central field_ (中心力场) on a plane is defined by
$ dot.double(bold(r)) = Phi(r) bold(hat(e)_r) $
*Def.* We define the _angular momentum_ by
$ bold(M) = bold(r) times dot(bold(r)) $
*Thm.* For a point moving in a central field, the angular momentum is conserved.
\
$bold(r) = r bold(hat(e)_r)$
#figure(
image("img/polar_coordinate.svg", width: 35%)
)
#line()
*Lemma.* $dot(bold(r)) = dot(r) bold(hat(e)_r) + r dot(phi) bold(hat(e))_phi, quad bold(dot.double(r)) = (dot.double(r)-r dot(phi)^2)bold(hat(e)_r) + (2 dot(r) dot(phi)+r dot.double(phi))bold(hat(e))_phi.$
_Proof._ $bold(r) = r bold(hat(e)_r)$,
$display(dot(bold(r)) = dot(r) bold(hat(e)_r) + r (dif hat(bold(r)))/(dif t) = dot(r) bold(hat(e)_r) + r (dif bold(hat(r)))/(dif phi) dot(phi) = dot(r) bold(hat(e)_r) + r dot(phi) bold(hat(e))_phi)$
$dot.double(bold(r)) = ...$
可以用复数证, $(r e^(i phi))' = dot(r) e^(i phi) + r dot(phi) i e^(i phi), quad (r e^(i phi))'' = (dot.double(r) - r dot(phi)^2)e^(i phi) + (2 dot(r) dot(phi) + r dot.double(phi)) i e^(i phi)$ 即为该引理.
#line()
$bold(M) = bold(r) times bold(dot(r)) &= bold(r) times (dot(r) bold(hat(e)_r) + r dot(phi) bold(hat(e))_phi) \
&= r bold(hat(e)_r) times r dot(phi) bold(hat(e))_phi = r^2 dot(phi) bold(hat(e)_r) times bold(hat(e))_phi = r^2 dot(phi)$
Kepler's second law is exactly the angular momentum conservation.
\
*Thm.* Consider a point moving in a central field with the equation $bold(dot.double(r)) = -nabla U(bold(r)), bold(r) in RR^2$ where $U = U(||bold(r)||) = U(r)$. Then the radius $r$ satisfies a system of 1 degree of freedom with effective potential
$ V(r) = U(r) + M^2/(2r^2) $
_(Reducing a motion in a central field to a system of 1 degree of freedom)_
_Proof._ By the equation of motion, we have $bold(dot.double(r)) = -(partial U)/(partial r)hat(bold(e))_r$.
由引理 $display(==> cases(dot.double(r) - r dot(phi)^2 = -(partial U)/(partial r), 2 dot(r) dot(phi)+r dot.double(phi)=0 &==>dif/(dif t)(r^2 dot(phi))=0))$
According to the angular momentum conservation (上面一行又再次给出了),
$r^2 dot(phi) = M ==> dot(phi) = display(M/r^2)$
$==> display(dot.double(r) = -(partial U)/(partial r) + r (M/r^2)^2 = - partial/(partial r)(U+M^2/(2r^2)) = -partial/(partial r) V)$, where $display(V = U+M^2/(2r^2))$.
注. The total energy in the derived 1-dim problem $display(E_1 = dot(r)^2/2+V(r))$ is _the same_ as the total energy in the original problem $display(E = (||bold(dot(r))||^2)/2 + U(bold(r)))$, since
#align(center, $display((||bold(dot(r))||^2)/2 = (dot(r)^2)/2 + (r^2 dot(phi)^2)/2 = (dot(r)^2)/2 + M^2/(2 r^2))$)
\
#line(length: 100%)
*Kepler problem:* $U = -k/r ==>$
$ V(r) = U(r) + M^2/(2 r^2) = -k/r + M^2/(2 r^2) $
#figure(
image("img/V-r.svg", width: 35%)
)
\
$display(E = 1/2 dot(r)^2 + V(r) ==> (dif r)/(dif t) = plus.minus sqrt(2 (E-V(r))))$
又由 angular momentum 守恒 $==> display((dif phi)/(dif t) = M/r^2)$
$display(==> (dif phi)/(dif r) = (M\/r^2)/(sqrt(2(E-(-k/r+M^2/(2 r^2))))))$
$display(==> phi &= integral dif phi = integral (M\/r^2)/(sqrt(2(E+k/r-M^2/(2 r^2)))) dif r = dots.c \
&= arccos((M/r-k/M)/(sqrt(2E+k^2/M^2))) = arccos((M^2/(k r)-1)/sqrt(1+(2 E M^2)/k^2)))$
记 $p := M^2/k, quad e := sqrt(1+(2 E M^2)/k^2)$ (eccentricity, 离心率)
$display(==> (p/r-1)/e = cos phi ==> r = p/(1+e cos phi))$
$ r = p/(1+e cos phi) $
- when $0<e<1$ i.e. $E<0$, the orbit is an ellipse
- when $e=1$ i.e. $E=0$, the orbit is a parabola
- when $e>1$ i.e. $E>0$, the orbit is a hyperbola
$a$: semi-major, $b$: semi-minor
$==> 2a = p/(1+e)+p/(1-e) = (2p)/(1-e^2)$
$==> a = p/(1-e^2) = k/(2|E|), b = a sqrt(1-e^2) = M/sqrt(2|E|)$
\
Kepler's third law: $display(a^3/T^2) = "const"$
$pi a b = integral_0^T M/2 dif t = 1/2 M T ==> T = dots.c = 2 pi a^(3/2) k^(-1/2)$.
\
#line(length: 100%)
*Axially symmetric field* 轴对称场
*Def.* A vector field in $RR^3$ is said to be _axially symmetric_ if it is invariant under the group of rotations which fixes every point in the axis.
We choose the $z$-axis to be the axis fixed by the group of rotations.
*Lemma.* If a field is conservative and axially symmetric, then its potential energy $U$ has the form $U(r,z)$, independent of $phi$.
_证明. 见作业_
*Thm.* For a particle moving in a conservative and axially symmetric field, then $ M_z = angle.l hat(bold(e))_z, bold(r) times dot(bold(r)) angle.r $ is conserved (角动量 $bold(M)$ 在 $z$ 方向的分量守恒).
_Proof._ $dot(M_z) = angle.l hat(bold(e))_z, bold(r) times dot.double(bold(r)) angle.r = angle.l hat(bold(e))_z, bold(r) times bold(F) angle.r = 0$
(_由引理, $bold(F) = - nabla U(r,z)$ lies in the plane spanned by $hat(bold(e))_z$ and $bold(r)$._)
#line(length: 100%)
*The two-body problem*
$ m_1 dot.double(bold(r_1)) = - (partial U)/(partial bold(r_1)) \
m_2 dot.double(bold(r_2)) = - (partial U)/(partial bold(r_2)) $
where $U = U(|bold(r_1)-bold(r_2)|)$.
*Thm.* The time variation of the relative distance $bold(r) = bold(r_1) - bold(r_2)$ in the two body problem is the same as the motion of a point mass $m = (m_1 m_2)/(m_1+m_2)$ in a field with potential $U(|bold(r|))$.
_Proof._ $m_1 m_2 dot.double(bold(r)) = m_1 m_2 bold(dot.double(r)_1) - m_1 m_2 bold(dot.double(r)_2) = -m_2 (partial U)/(partial bold(r_1)) + m_1 (partial U)/(partial bold(r_2)) = -(m_1+m_2) (partial U)/(partial bold(r))$.
#pagebreak()
#line(length: 100%)
*Lagrangian mechanics*
Chapter 03 - Calculus of variations 变分法
#line(length: 100%)
Lagrangian mechanics: variational principle
$quad arrow.t.b quad$ Legendre transformation
Hamiltonian mechanics: symplectic structure
\
Functional 泛函: A function on the space of curves.
$ Phi(gamma) = integral_a^b L(x(t), dot(x)(t), t) dif t $
where $gamma:[a,b] -> RR^n$ is a $C^1$ curve.
Lagrangian $L: underbrace(RR^n times RR^n, "phase space") times RR -> RR$ is a $C^2$ function.
$Phi: E -> RR$ functional, $E$ is the space of $C^1$ curves in $RR^n$ .
\
*Def.* A functional $Phi: E -> RR$ is said to be _differentiable_ at $gamma_0$, if there exist a linear functional $F: E -> RR$ s.t.
$ Phi(gamma_0+h) -Phi(gamma_0) = F dot.c h + o(h) $
F is called the _differential_ of $Phi$ at $gamma_0$.
*Thm.* Assume $L$ is $C^2$, then $Phi(gamma) = display(integral_a^b L(x(t), dot(x)(t), t) dif t)$ is differentiable. Its differential is given by
$ F dot.c h = integral_a^b ((partial L)/(partial x) - dif/(dif t) (partial L)/(partial dot(x)))_(gamma_0) h(t) dif t + lr((partial L)/(partial dot(x)) h mid(|))_a^b $
_Proof._ 用分部积分公式.
$display( Phi(gamma+h)-Phi(gamma)
&= integral_a^b L(x+h, dot(x)+dot(h),t) dif t - integral_a^b L(x, dot(x),t) dif t \
&= integral_a^b (cancel(L(x,dot(x),t)) + lr((partial L)/(partial x)mid(|))_gamma h + lr((partial L)/(partial dot(x))mid(|))_gamma dot(h) + o(h) - cancel(L(x, dot(x),t))) dif t \
&= integral_a^b (lr((partial L)/(partial x)mid(|))_gamma h + lr((partial L)/(partial dot(x))mid(|))_gamma dot(h)) dif t + o(h) \
&= integral_a^b (lr((partial L)/(partial x)mid(|))_gamma h - lr(dif/(dif t)(partial L)/(partial dot(x))mid(|))_gamma h) dif t + lr(lr((partial L)/(partial dot(x))mid(|))_gamma h mid(|))_a^b + o(h). \
)$
\
*Def.* A curve $gamma$ is called an extremal (极点) of $Phi$ if $F|_gamma dot.c h = 0, forall h in E$.
*Thm.* Let $E_0$ be the space of curves. $gamma:[a,b] -> RR^n, gamma(a) = x_0, gamma(b) = x_1$ with fixed points. Then $gamma$ is an extremal of $Phi$ if and only if
$ (partial L)/(partial x) - dif/(dif t) (partial L)/(partial dot(x)) = 0 "along" gamma $ <E-L>
We call @E-L _the Euler-Lagrange equation_.
_Proof._ Since we consider only curves with fixed endpoints in $E_0$ i.e. $gamma_1=gamma_0+h$ has the same points as $gamma_0$, this implies $h=0$ at $t=a,b$.
Thus the differential of $Phi$ reads
#align(center, $display(F_gamma dot.c h = integral_a^b lr(((partial L)/(partial x) - dif/(dif t) (partial L)/(partial dot(x)))mid(|))_(gamma(t)) h(t) dif t)$)
#line()
*Lemma.* If a continuous function $f:[a,b] -> RR$ satisfies $display(integral_a^b f(t)h(t) dif t = 0)$, $forall h$ continuous with $h(a)=h(b)=0$, then $f(t) equiv 0$.
#line()
which finishes the proof.
\
*Thm.* A curve is an extremal of $Phi$ iff the Euler-Lagrangian equation is satisfied along $gamma$.
\
_Example. a free mass (不受力的质点静止或匀速直线运动)_
$U=0, quad L = T = 1/2 m (dot(x)_1^2+dot(x)_2^2+dot(x)_3^2)$
$==> 0 = dif/(dif t) (partial L)/(partial x_i) = m dot.double(x)_i ==> x_i = A_i t + B_i$.
\
#line(length: 100%)
*Hamilton's principle of least action:*
$ underbrace(m dot.double(x) = -nabla U(x)\, quad x in RR^3 " Newton eqn", "Mechanical systems") $
*Thm.* Motions of the mechanical system _coincide with_ extremals of the functional
$ Phi(gamma) = integral_a^b L(gamma(t), dot(gamma)(t), t) dif t $
where $L(x, dot(x)) = 1/2 m dot(x)^2 - U(x). quad$ (Kinetic energy - potential energy)
_证明. 显然_
\
*Def.* Given Lagrangian $L(x, dot(x), t), x in RR^n$, we call
$x$ the generalized coordinates/positions,
$dot(x)$ the generalized velocities,
$(partial L)/(partial dot(x)) = p$ the generalized momentum,
$(partial L)/(partial x)$ the generalized forces
#line()
_Example: central field_
#align(center, $dot(bold(r)) = dot(r)bold(hat(e)_r) + r dot(phi) bold(hat(e))_phi$)
Kinetic energy $T = 1/2 m||dot(bold(r))||^2 = 1/2 m (dot(r)^2 + r^2 dot(phi)^2)$
Potential energy $U(r)$
Lagrangian $L(r, phi, dot(r), dot(phi)) = T - U = 1/2 m (dot(r)^2 + r^2 dot(phi)^2) - U(r)$
$attach(==>, t: "E-L" ) display(cases(
m dot.double(r) = m r dot(phi)^2 - (partial U)/(partial r) & ==> m dot.double(r) = M^2/(m r^3) - (partial U)/(partial r),
dif/(dif t) (m r^2 dot(phi))= 0 & ==> m r^2 dot(phi)=M "angular momentum conservation"))$
#line()
\
*Def.* If the Lagrangian does not depend on a generalized coordinate $x_1$ i.e. $(partial L)/(partial x_1) = 0$, we say $x_1$ is a _cyclic coordinate_.
*Thm.* The existence of a cyclic generalized coordinate $x_1$ implies the corresponding generalized momentum $(partial L)/(partial dot(x)_1)$ is a conserved quantity.
\
#line(length: 100%)
*Legendre transformation:*
Let $f: RR-> RR$ be a convex function (额外假设 $C^2$, $f''>0$), the _Legendre transformation_ of $f$ is
$ f^*(y) = sup_x (x y - f(x)) $
#figure(
image("img/legendre.svg", width: 28%)
)
Suppose the $sup$ is attained at $x_0$, we have $lr(dif/(dif x) (x y - f(x))mid(|))_x_0 = 0 ==> y = f'(x_0)$
\
*Prop.* Let $f$ be a convex function, then its Legendre transformation is still convex.
_Proof._
#align($display(f^*(lambda y_1 + (1-lambda) y_2 ) &= sup_x ((lambda y_1 + (1-lambda)y_2)x-f(x))
\ &= sup_x lr([lambda(y_1 x -f(x))+(1-lambda)(y_2 x -f(x))])
\ &<= lambda sup_x (y_1 x -f(x)) +(1-lambda) sup_x (y_2 x- f(x))
\ &= lambda f^*(y_1) + (1-lambda) f^*(y_2).
)$, center)
\
*Prop.* Suppose $f:RR -> RR$ is $C^2$, strictly convex. Suppose the $sup$ in the definition of $f^*(x)$ is attained at $x_0$ satisfying $y_0 = f'(x_0)$. Then we have
$ x_0 = (f^*)'(y_0), quad f''(x_0) dot.c (f^*)''(y_0) = 1 $
_Proof._ By assumption, we have $f^*(y_0) = x_0 y_0 -f(x_0)$, where $x_0 = (f')^(-1)(y_0)$
$==> (f^*)'(y_0) = (partial f^*)/(partial x_0) (partial x_0)/(partial y_0) + (partial f^*)/(partial y_0) = (partial x_0)/(partial y_0) (y_0-f'(x_0)) + x_0 = x_0$
_注. 说明 $f'$ 与 $(f^*)'$ 互为反函数._
\
*Prop.* The Legendre transformation is involutive, i.e. $(f^*)^* = f$.
_Proof._ 若假设 $f in C^2$, 则由上一命题容易证明 (_略_).
#line()
#italic([$display(h(t) = sup_p (p t - sup_x (p x - f(x))))$, 对每个 $t$,\
对每个 $p$, $display(p t - sup_x (p x - f(x)))$ 的几何意义为 $f(x)$ 的斜率为 $p$ 的切线在 $t$ 处的函数值 (如下图), 再结合 $f(x)$ 是凸函数, 故这些切线都在 $f(x)$ 图像下方, 这些点的 $sup$ 正是 $f(t)$.])
#figure(
image("img/legendre_involutive.svg", width: 80%)
)
#line()
For a convex function multi variables $f: RR^n -> RR$, we define its Legendre transformation
$ f^*(y) = sup_x (angle.l x, y angle.r - f(x)) $
\
#line(length: 100%)
*Hamiltonian mechanics:*
Given a Lagrangian $L(x, dot(x)): RR^n times RR^n -> RR$, suppose $L$ is (strictly) convex in $dot(x)$. Let the _Hamiltonian_
$ H(x, y) = sup_(dot(x)) (angle.l y, dot(x) angle.r - L(x, dot(x))) $
be the Legendre transformation of $L$ w.r.t $dot(x)$.
By the involutivity, we have
#align(center, $L(x, dot(x)) = display(sup_y) (angle.l dot(x),y angle.r - H(x, y))$)
When the $sup$ is attained, we have
$ cases(y &= (partial L)/(partial dot(x)) &quad "generalized momentum"\
dot(x) &= (partial H)/(partial y)) $
#align(
$display(attach(==>, t: "E-L") cases(
dot(y) = dif/(dif t) (partial L)/(partial dot(x)) = (partial L)/(partial x) = - (partial H)/(partial x) &quad("why?"),
dot(x) = (partial H)/(partial y)
))$, center)
We get _the Hamiltonian canonical equations_
$ cases(dot(x) = (partial H)/(partial y), dot(y) = -(partial H)/(partial x)) $
\
#line()
_Example._ $L(x, dot(x)) = 1/2 m angle.l A dot(x), dot(x) angle.r - U(x)$
$y = (partial L)/(partial dot(x)) = m A dot(x) ==> dot(x) = 1/m A^(-1) y$
$H(x,y) = angle.l y, dot(x) angle.r-L(x, dot(x)) = ... = underbrace(1/(2 m) angle.l y\, A^(-1) y angle.r, "Kinetic energy") + underbrace(U(x), "Potential energy")$
#line()
( Lagrangian: 动能 $-$ 势能 $==>$ 有变分法 \
Hamiltonian: 动能 $+$ 势能 $==>$ 有辛结构 )
\
*Thm.* For mechanical systems (where kinetic energy $K= 1/2 m angle.l A dot(x), dot(x) angle.r$ is a quadratic form w.r.t. $dot(x)$ ), the Hamiltonian is the total energy.
*Thm.* (energy conservation) If $H$ does not depend on $t$ explicitly, then along any orbit $(x(t), y(t))$, we have $H(x(t),y(t)) equiv$ const.
_Proof._ $dif/(dif t) H(x(t),y(t)) = (partial H)/(partial x) dot(x) + (partial H)/(partial y) dot(y) = (partial H)/(partial x) (partial H)/(partial y) + (partial H)/(partial y) (-(partial H)/(partial x)) = 0$.
\
#line(length: 100%)
*Cyclic coordinates:*
*Def.* If a generalized coordinate $x_1$ does not enter $H$ i.e. $(partial H)/(partial x_1) = 0$, we call $x_1$ a _cyclic coordinate_. \ ( We also have $(partial L)/(partial x_1) = 0$ )
*Prop.* Suppose $x_1$ is a cyclic coordinate of $H$. Then the corresponding $y_1$ is a conserved quantity.
_Proof._ $dot(y)_1 = -(partial H)/(partial x_1) = 0$
#italic([于是每一个 cyclic coordinate 都能将 $n$ 个坐标减少到 $n-1$ 个 ( $2n$ 个一阶方程 $==> 2(n-1)$ 个 ), 最后由 $dot(x)_1 = (partial H)/(partial y_1) (y_1, tilde(x), tilde(y),t)$ 积分出 $x_1$ 即可.])
\
#line(length: 100%)
*Liouville theorem*
*Thm.* The Hamiltonian flow _preserves volume_ of the phase space.
#line()
phase space: $RR^n times RR^n$ \
phase flow: the one-parameter group of transformations of the phase space
$ g^t: RR^n times RR^n &-> RR^n times RR^n \
(x(0), y(0)) &|-> (x(t),y(t)) $
where $(x(t), y(t))$ solves the Hamiltonian equation.
For any given $t_0$, $g^(t_0)$ is a diffeomorphism (微分同胚) on $RR^n times RR^n$
#figure(
image("img/liouville.svg", width: 30%)
)
$"Vol"(D) = "Vol"(g^t (D))$
#line()
_Proof of Liouville theorem._ Let $D(t) := g^t (D(0))$, $v(t) := "Vol"(D(t))$.
Suppose we are given a system of $dot(x) = f(x)$. Then $g^t (x) = x + f(x) t + O(t^2) quad (t -> 0)$
$v(t) = integral_D(t) dif x = integral_D(0) det (partial g^t)/(partial x) dif x = integral_D(0) det(I + (partial f)/(partial x) t + O(t^2)) dif x quad (t -> 0)$
#line()
*Lemma1.* For any matrix $A$, we have
#align(center, [$det(I+t A) = 1 + t tr(A) + O(t^2) quad (t -> 0)$])
#line()
$==> v(t) = integral_D(0) (1 + t tr((partial f)/(partial x)) + O(t^2)) dif x = integral_D(0) (1 + t nabla dot.c f + O(t^2)) dif x$
$==> display(lr((dif v)/(dif t)mid(|))_(t=0) = integral_D(0) nabla dot.c f dif x)$
#line()
*Lemma2.* If $nabla dot.c f equiv 0$ (divergence free), then $g^t$ preserves volume.
_Proof._ Since $t=t_0$ is no worse than $t=0$, we have
#align(center, $display(lr((dif v)/(dif t)mid(|))_(t=t_0) = integral_D(t_0) nabla dot.c f dif x)$)
$==> (dif v)/(dif t) equiv 0 ==> v(t) equiv$ const.
#line()
For our Hamiltonian flow, we have $display(cases(dot(x) = (partial H)/(partial y), dot(y) = -(partial H)/(partial x)))$
$==> nabla dot.c f = nabla dot.c (dot(x), dot(y)) = nabla dot.c ((partial H)/(partial y), -(partial H)/(partial x)) = sum (partial)/(partial x_i)(partial H)/(partial y_i)-(partial)/(partial y_i)(partial H)/(partial x_i) = 0$,
which finishes the proof.
\
#line(length: 100%)
*Thm.* (Poincar$acute(upright(e))$ recurrence, _加强版本_) Let $f: X -> X$ be a diffeomorphism #underline("preserving the volume") where $X$ is a domain with $"Vol"(X)<oo$. Then for any $A subset X$ with $"Vol"(A)>0$, we have a.e. $x in A$, $exists {n_k}_(k=0)^oo$ s.t. $f^(n_k) (x) in A$.
_Proof._ We first prove that there is one point $x in A$ and $n in NN$ s.t. $f^n (x) in A$.
Consider $A, f(A), f^2 (A), ...$, since $f$ preserves volume, we have $"Vol"(A) = "Vol"(f(A)) = ...$
Since $"Vol"(A)>0$, let $N = floor(("Vol"(X))/("Vol"(A))) + 1$, $exists n_1<n_2 in NN$ s.t. $f^(n_1) (A) sect f^(n_2) (A) eq.not emptyset$
$==> A sect f^(n_2-n_1) (A) eq.not emptyset$ (_这一步需要单射_).
_修改以上证明 (考虑 $A, f^(-1) (A), ...$) , 就不需要单射条件了._
余下证明见作业.
\
#line(length: 100%)
*holonomic constraints*
_Example._ $L_N: RR^2 times RR^2 -> RR$
$T = 1/2 (dot(q)_1^2+dot(q)_2^2), quad U_N = 1/2 N dot(q)_2^2 + U_0(q_1, q_2)$
$L_N = T - U_N$
$H_N = 1/2 (dot(q)_1^2+dot(q)_2^2) + U_N (bold(q)) = E "(total energy) fixed as" N -> oo$
$==> q_2 -> 0$ as $N -> oo$ ( 不然 $1/2 N dot(q)_2^2$ 项趋于无穷 )
Consider initial condition $(*)$:
#align(center, $q_1(0) &= q_1^0, quad &dot(q)_1(0) &= dot(q)_1^0, \ q_2(0) &= 0, quad &dot(q)_2 (0) &= 0$)
*Thm.* Let $q_1 = phi_N (t)$ be the evolution of $q_1$ under the initial condition $(*)$, then the limit
#align(center, $display(lim_(N->oo) phi_N (t)-> psi(t))$)
exists, where $q_1 = psi(t)$ satisfies the E-L equation
$ (partial L_*)/(partial q_1) = dif/(dif t) (partial L_*)/(partial dot(q)_1), $
where
$ L_*(q_1, dot(q)_1) = T mid(|)_(q_2=dot(q)_2=0) - U_0 mid(|)_(q_2=0) $
_即: 被很大的势场限制住的运动, 其 Lagrangian 相当于不考虑这个势场的势能以及限制曲面法向的动能._
\
*Def.* (holonomic constraints) Let $Gamma$ be an $m$-dim surface in $RR^(3n)$ of points $bold(r_1), ..., bold(r_n) in RR^3$ with masses $m_1, ..., m_n$ respectively. Let $bold(q) = (q_1, ..., q_m)$ be coordinates on $Gamma$, $bold(r_i) = bold(r_i) (bold(q))$. The system discribed by
$ dif/(dif t) (partial L)/(partial dot(bold(q))) = (partial L)/(partial bold(q)), quad L = 1/2 sum m_i bold(r)_i^2 - U(bold(q)) $
is called _a system of $n$ points with $3n-m$ ideal holonomic coordinates_.
_Example._ $bold(r)_i in SS^2 subset RR^3, quad q = (theta, phi)$ is the spherical coordinates, \
$bold(r)_i = (cos theta_i cos phi_i, cos theta_i sin phi_i, sin theta_i)$
\
#line(length: 100%)
*Differentiable manifold*
*Def.* A set $M$ is called a _manifold_ if $M$ is given a finite or countable collection of charts such that each point lies in at least one chart.
chart (坐标卡): $(U, phi)$, where $U subset RR^n$ is an open set, $phi$ is an one-to-one map from $U$ to some subset of $M$.
In the overlaping region of two charts, $phi_j^(-1) circle.tiny phi_i [phi_i^(-1) (V_i sect V_j)] subset U_j$
$==> phi_j^(-1) circle.tiny phi_i$ is a map from an open subset of $RR^n$ to another open subset of $RR^n$.
We say $M$ is a _differentiable manifold_ if $phi_j^(-1) circle.tiny phi_i$ is differentiable for all $i,j$
\
#line()
注. *Projective space*
$ RR PP^n = {"all lines going through" O "in" RR^(n+1)} $
_作业题._ $S O(3)$ homeomorphic to $RR PP^3$.
#line()
\
*Tangent space*
We say two curves $phi(t), psi(t)$ are equivalent at $x$ if $phi(0) =psi(0) =x$ and $display(lim_(t->0) (phi(t)-psi(t))/t = 0)$ in some chart.
*Def.* A tangent vector to a manifold $M$ at $x$ is an equivalent class of curves $phi(t)$ with $phi(0)=x$.
tangent space (切空间) $T_x M$: the set of tangent vectors to $M$ at $x$.
tangent bundle (切丛) $T M = display(union.big_(x in M) T_x M)$
\
*Riemannian manifold*: a manifold endowed with a Riemannian metric (_各点 metric 要是同一个_).
A _Riemannian metric_ on a manifold $M$ is given by a positive definite quadratic form on $T_x M$ at each point $x in M$:
$ T_x M × T_x M &&-> RR \ (u &, v) &&|-> angle.l u,v angle.r_x = angle.l A_x u, v angle.r $
$||v||_x = sqrt(angle.l u\,v angle.r_x), quad v in T_x M$
For a curve $gamma: [0, 1] -> M$, its length is given by $display(ell(gamma)=integral_0^1 sqrt(angle.l dot(gamma)(t)\, dot(gamma)(t) angle.r_gamma(t)) dif t)$
*Derivative map*:
Let $f: M -> N$ be a map between two manifolds. The derivative of $f$ at point $x in M$ is the linear map of the tangent spaces
$ D f_x = f_(*x): T_x M -> T_(f(x)) N, $
which is given in the following way:
$forall v in T_x M$, consider a curve $phi: RR->M$ with $phi(0)=x,dot(phi)(0)=v$, then $ display(f_(*x) (v) = lr(dif/(dif t)f(phi(t))mid(|))_(t=0))$.
_注. $f_(*x)(v)$ 的值与 $phi$ 的选取无关._
_注. $f_(*x)$ 是线性的._
\
#line(length: 100%)
*How to solve a system with holonomic constraints:*
1. Find $Gamma subset RR^(3n)$, $bold(r)_1, ..., bold(r)_n in RR^3$, $bold(r)_i = bold(r)_i (bold(q))in Gamma$, $bold(q) = (q_1, ..., q_m) in RR^m$
2. Kinetic energy
#align(center, $display(T = 1/2 sum m_i bold(dot(r))_i^2 = 1/2 sum m_i lr(|(D bold(r)_i)/(D bold(q)) dot.c bold(dot(q))|)^2 = 1/2 sum a_(i j) (bold(q)) dot(q)_i dot(q)_j)$)
3. Solve E-L equation $L = T - U(bold(q))$
\
_Example._ motion of a particle of mass $1$ on a surface of revolution in $RR^3$
Introduce polar coordinates $(r, phi)$ on $RR^2$
$Gamma$ is given by $(r(z), phi, z), z in [a, b], phi in [0, 2 pi]$.
$x &= r(z) cos phi &==> dot(x) &= r_z dot(z) cos phi &- r sin phi space dot(phi) \
y &= r(z) sin phi &==> dot(y) &= r_z dot(z) sin phi &+ r cos phi space dot(phi)$
$==> T = 1/2 (dot(x)^2 + dot(y)^2 + dot(z)^2) = ... = 1/2 ((1 + r_z^2) dot(z)^2 + r^2(z) dot(phi)^2)$
$L (= T) = L(phi,z,dot(phi),dot(z)): T Gamma -> RR$ does not depend on $phi$ explicitly ( $phi$ is a cyclic coordinate)
$==> dif/(dif t) (partial L)/(partial dot(phi)) = (partial L)/(partial phi) = 0 ==> (partial L)/(partial dot(phi)) = r^2 dot(phi) = "const"$
Let $alpha$ be the angle formed by $bold(v)$ with $z$-axis, then the horizontal component of the velocity is \ $r dot(phi) = |bold(v)| sin alpha$ (_看下图理解_)
#figure(
grid(
columns: (1fr, 1fr),
align: bottom,
image("img/clairaut-1.png", width: 75%),
image("img/clairaut-2.png", width: 100%)
)
)
By energy conservation, $|bold(v)|$ is a constant $==> underbrace(r sin alpha= r^2 dot(phi) |bold(v)|^(-1) = "const", "Clairaut's theorem")$
\
_Example._ bead on a rotating circle
a bead with mass $1$ moves along a vertical circle of radius $1$ which rotates with angular velocity $omega$.
$Gamma: bold(r) = (sin(theta) cos(omega t), sin(theta) sin(omega t), cos(theta))$ ( $theta in [-pi, pi]$ measured from the highest point )
$T = 1/2 |dot(bold(r))|^2 = 1/2 (omega^2 sin^2 theta + dot(theta)^2), quad U = g cos theta$
$==> L = T - U = underbrace(1/2 dot(theta)^2) + underbrace(1/2 omega^2 sin^2 theta - g cos theta)$
与一个 $1$-dim system 相同: $T' = 1/2 dot(q)^2, U' = A cos q - B sin^2 q$, where $A = g, B= 1/2 omega^2$
- 当 $2B < A$ 即 $omega^2 r < g$ 时 ($r=1$), $q = plus.minus pi$ (最低点) 是一个稳定点. (此时大圈转的很慢, 符合生活常识.)
- 当 $2B > A$ 时, $q = plus.minus pi$ 将不再是稳定点, 但在 $(-pi, pi)$ 中新出现了两个稳定点, 分别对应 $cos q = - A/(2B) = - g/(omega^2 r)$, 如下图所示.
#figure(
image("/img/bead_on_circle.png", width: 65%)
)
\
#line(length: 100%)
*N$dot.double(upright(bold(o)))$ther's law*
_以下考虑的是$underbrace("自治系统", L(q,dot(q)) : T M -> RR)$. $underbrace("非自治系统", L(q,dot(q),t) : T M times RR-> RR)$也存在类似定理, 见作业._
$M$ manifold, $L: T M -> RR$ a smooth function, $h: M -> M$ a smooth map
*Def.* A Lagrangian system $L: T M -> RR$ _admits_ the map $h$ if for any $v in T_x M$ we have
$ L(x, v) = L(h(x), D h(x) v) $
*Thm.*(N$dot.double(upright(o))$ther) If the system $L: T M -> RR$ admits the $1$-parameter group of diffeomorphism \ $h^s: M -> M, s in RR$, then the Lagrangian system _admits a first integral_ $I: T M -> RR$
$ I(q, dot(q)) = lr((partial L)/(partial dot(q)) (dif h^s (q))/(dif s) mid(|))_(s=0) $
_注. $I$ 的表达式中两部分应该是行向量乘列向量,得到个数量 (或写成向量点积)._
_Proof._ Let $phi(t)$ be a solution to the E-L equation, $Phi(t,s):=h^s (phi(t))$
By assumption, $L(Phi(t,s), dif/(dif t) Phi(t,s)) = L(phi(t), dot(phi)(t))$
Take $dif/(dif s)$ on both sides, $0 = (partial L)/(partial q) (dif Phi)/(dif s) + (partial L)/(partial dot(q)) dif/(dif s) dif/(dif t) Phi$
By the E-L equation $dif/(dif t) (partial L)/(partial dot(q)) (Phi(t,s), dif/(dif t) Phi(t,s)) = (partial L)/(partial q) (Phi(t,s), dif/(dif t) Phi(t,s))$
$==> 0 = dif/(dif t) (partial L)/(partial dot(q)) (dif Phi)/(dif s) + (partial L)/(partial dot(q)) dif/(dif t) dif/(dif s) Phi = dif/(dif t) ((partial L)/(partial dot(q)) (dif Phi)/(dif s)) $
$==> display((partial L)/(partial dot(q)) (dif h^s)/(dif s))$ is a conserved quantity.
(_抄自教材, 其实没懂_) In fact, the first integral $I = (partial L)/(partial dot(q))q'$ is _the rate of change of $L(v)$_ when the vector $v in T_x M$ varies inside $T_x M$ with velocity $(dif h^s (x))/(dif s)|_(s=0)$
\
_Example._ points with masses $m_i$, $L = 1/2 sum m_i bold(dot(x))_i^2 - U(bold(x))$
1. Suppose the system admits the translation along $bold(e)_1$: $h^s (bold(x)_i) = bold(x)_i + bold(e)_1 s$
#h(12.5pt) By Nother's thm, $I = sum (partial L)/(partial dot(bold(x))_i) (dif h^s)/(dif s) = sum m_i angle.l dot(bold(x))_i, bold(e)_1 angle.r = underbrace(sum m_i dot(x)_(i 1), "动量" bold(e)_1"分量") quad$ is conserved
#h(12.5pt) i.e. translation invariance $==>$ momentum conservation
2. Suppose $L$ admits rotations around $bold(e)_1$
#h(12.5pt) Let $h^s$ be the rotation around $bold(e)_1$-axis by angle $s$, then $(dif h^s)/(dif s) (bold(x)_i) = bold(e)_1 times bold(x)_i$ (_思考_)
#h(12.5pt) $==> I = sum (partial L)/(partial dot(bold(x))_i) (dif h^s)/(dif s) (bold(x)_i) = sum m_i angle.l bold(dot(x))_i, bold(e)_1 times bold(x)_i angle.r = underbrace(sum m_i angle.l bold(x)_i times bold(dot(x))_i\, bold(e)_1 angle.r, "角动量在" bold(e)_1 "的投影") space$ conserved
#h(12.5pt) i.e. rotation invariance $==>$ angular momentum conservation
#pagebreak()
#line(length: 100%)
Chapter 05 Oscillations
#line(length: 100%)
*Linearization*
$ (dif bold(x))/(dif t) = bold(f) (bold(x)), bold(x) in RR^n $
A point $bold(x)_0$ is called an equilibrium (平衡点) or fixed point if $bold(x)(t) equiv bold(x)_0$ is a solution. In other words, $bold(f) (bold(x)_0) =0$.
Consider $L = T - U(bold(q)), quad T = 1/2 sum a_(i j) (bold(q)) dot(q)_i dot(q)_j$
The point $bold(q)_0, dot(bold(q))_0$ is an equilibrium iff $dot(bold(q))_0 = 0$ and $bold(q)_0$ is a critical point of $U$ i.e. $lr((partial U)/(partial bold(q)) mid(|))_(bold(q)_0) = 0$
#figure(
image("/img/oscil-linear-tmp.jpg")
)
#figure(
image("/img/handwritten/handwritten_1.jpg")
)
#figure(
image("/img/handwritten/handwritten_2.jpg")
)
#figure(
image("/img/handwritten/handwritten_3.jpg")
)
#figure(
image("/img/handwritten/handwritten_4.jpg")
)
#pagebreak()
#line(length: 100%)
Chapter 07 Differential forms
#line(length: 100%)
*Forms on $RR^n$*
- $1$-form: linear functional on $RR^n$
#h(1em) The space of 1-forms is denoted by $(RR^n)^* tilde.equiv RR^n$
- $2$-form: $omega^2: RR^n times RR^n -> RR$ bilinear, anti-symmetric
#h(1em) $omega^2: (u,v) = angle.l A u , v angle.r, quad A$ anti-symmetric
- $k$-form: k-linear, skew-symmetric
#line()
*Exterior product*
1. The exterior product of 2 $1$-forms $omega_1, omega_2 in Lambda^1 RR^n$:
$ (omega_1 and omega_2) (xi_1, xi_2) = mat(delim: "|", omega_1(xi_1), omega_1(xi_2); omega_2(xi_1), omega_2(xi_2)) $
2. The exterior product of k $1$-forms $omega_1, ..., omega_k in Lambda^1 RR^n$
$ (omega_1 and ... and omega_k)(xi_1, ..., xi_k) = mat(delim: "|", omega_1(xi_1), ..., omega_1(xi_k); dots.v, dots.down, dots.v; omega_k (xi_1), ..., omega_k (xi_k)) = det(omega_i (xi_j)) $
Next, given $k$-form $omega^k$ and $l$-form $omega^l$, we define their exterior product
$ (omega^k and omega^l)(xi_1, ..., xi_(k+l)) = display(sum_("all permutations")) (-1)^nu omega^k (xi_(i_1), ..., xi_(i_k)) omega^l (xi_(i_(k+1)), ..., xi_(i_(k+l))) $
properties of exterior product
- skew-symmetry: $omega^k and omega^l = (-1)^(k l) space omega^l and omega^k$
- distributivity
- associativity
We shall prove the equivalence of the definition of $omega^k and omega^l$ and the exterior product of $1$-forms. (omitted)
Remark. $omega^1 and omega^1 = 0$, but $omega^2 and omega^2$ is in general not. Actually, $omega^(2k+1) and omega^(2k+1)=0$.
#line()
*pull-back* 拉回 (behavior under mappings)
Let $f: RR^n -> RR^m$ be a linear map, $omega^k$ be a $k$-form on $RR^m$. Then
$ (f^* omega^k) (xi_1, ..., xi_k) := omega^k (f(xi_1), ..., f(xi_k)) $
is a $k$-form on $RR^n$
#line()
*Differential forms*
We generalize the notion of forms from $RR^n$ to a manifold $M$
Let $f: M -> RR$ be a differentiable function, recall the differential $dif f(x)$ is a linear functional $T_x M -> RR$ given by:
#h(1em) Given $xi in T_x M$, let a smooth curve $gamma: (-epsilon, epsilon) -> M$ s.t. $gamma(0)=x, gamma'(0) = xi$, then
#align(center, $dif_x f(xi) = lr(dif/(dif t) mid(|))_(t=0) f(gamma(t)) = angle.l dif_x f, gamma'(0) angle.r = angle.l dif_x f, xi angle.r$)
*Def.* A differential $1$-form on $M$ is a smooth map $omega: T M -> RR$ linear on each $T_x M$.
*Thm.* Give $RR^n$ coordinates $x_1, ..., x_n$. Then _every_ differential $1$-form $omega: T RR^n -> RR$ can be written as
$ omega = a_1(x_1, ..., x_n) dif x_1 + ... + a_n (x_1, ..., x_n) dif x_n, $
where $dif x_i (xi) = xi_i, space xi=(xi_1,...,xi_n) in RR^n$, and $a_i (x)$ are smooth functions.
*Def.* A differential $k$-form $omega^k|_x$ at a point $x in M$ is a $k$-form on the tangent space $T_x M$, i.e. a $k$-linear, skew-symmetric function of $k$ vectors $xi_1,...,xi_k in T_x M$.
*Thm.* Give $RR^n$ coordinates $x_1, ..., x_n$. Then _every_ differential $k$-form $omega^k$ on $T RR^n$ has the form
$ omega^k = sum_(i_1<...<i_k) a_(i_1,...,i_k) (x_1, ..., x_n) dif x_(i_1) and ... and dif x_(i_k) $
#line(length: 100%)
*Integration of differential forms*
We shall prove a general Stokes formula
$ integral_(partial Omega) omega = integral_Omega dif omega $
or written as $angle.l omega, partial Omega angle.r = angle.l dif omega, Omega angle.r$, i.e. $partial$ and $dif$ are dual.
#line()
1. The integration of a differential $1$-form along a curve
#h(14pt) Let $gamma: [0, 1] -> M$ be a smooth curve and $omega^1$ a $1$-form. We define
$ integral_gamma omega^1 = lim_(Delta->0) sum_i omega^1 (xi_i) $
#h(14pt) There, we partition $[0,1]$ into intervals $Delta_i=[t_i,t_(i+1)]$, $xi_i = dif gamma|_(t_i)(Delta_i) in T_gamma(t_i) M$, 这里把 $Delta_i$ 看成向量. 见下图.
#figure(
grid(
columns: (1fr, 1fr),
align: bottom,
image("img/integral_of_form-1.png", width: 75%),
image("img/integral_of_form-2.png", width: 75%)
)
)
2. The integration of a differential $k$-form along a $k$-dim surface
#h(14pt) 定义与 $1$-form 类似, 将曲面划分为小块, 每块用平行多面体代替. 见上图.
3. (_special case_) The integration of a differential $k$-form on oriented $RR^k$
#h(14pt) Let $x_1,...,x_k$ be a oriented coordinate system of $RR^k$. \
#h(13pt) Then every $k$-form has the form $omega^k = a(x_1, ..., x_k) dif x_1 and ... and dif x_k$ \
#h(14pt) Let $D$ be a bounded convex polyhedron in $RR^k$. We define
$ integral_D omega^k = integral_D a(x_1,...,x_k) dif x_1 ... dif x_k $
#h(14pt) 其中右式理解为通常的 Riemann 积分.
#h(14pt) 注. 这一定义与上面的一般定义相容, 因为此时 $D$ 的 tangent space 仍是 $D$ 本身.
#line()
上面只能定义 $k$-form 在 $k$-dim 曲面上的积分. 为定义一般的 $k$-form on $n$-dim space 的积分, 自然地, 通过_拉回_来定义.
*The behavior of differential forms under mappings*
Let $f: M -> N$ be a differentiable map between manifolds. Let $omega$ be a differential $k$-form on $N$. Then there is a well-defined differential $k$-form on $M$:
$ (f^* omega) (xi_1, ..., xi_k) := omega (f_*(xi_1), ..., f_*(xi_k)), quad forall xi_1,...,xi_k in T_x M $
其中 $f_*$ 是 $f$ 的微分.
*Integration of a $k$-form on $n$-dim manifolds*
*Def.* A $k$-dim _cell_ $sigma$ on $M$ is a triple $sigma = (D, f, O r)$, where
- $D$: a convex polyhedron in $RR^k$
- $f: D -> M$ a differentiable map
- $O r$: an orientation on $RR^k$
*Def.* The integration of a $k$-form $omega^k$ on a cell $sigma$ is defined as
$ integral_sigma omega^k = integral_D f^* omega^k $
*Def.* A _chain_ (链) of dim $k$ on a manifold $M$ consists of a finite collection of $k$-dim cells $sigma_1,...,sigma_r$ and integers $m_1,...,m_r$ called _multiplicities_. Denote it by $C_k = m_1 sigma_1 + ... + m_r sigma_r$.
$ integral_C_k = sum m_i integral_sigma_i omega $
*Def.* Let $sigma = (D, f, O r)$ be a cell of dim $k$, we define its _boundary_ $partial sigma$ to be a collection of cells of dim $k-1$,
$ partial sigma = sum sigma_i, quad sigma_i = (D_i, f_i, O r_i), $
where $D_i$ are faces of $D$, $f_i = f|_D_i$.
Let $e_1,...,e_k$ be a basis of $RR^k$. At each point of $D_i$, we choose an outer normal (外法向). An orientation on $D_i$ is a choice of basis $f_1,...,f_(k-1)$, we require $(n, f_1,...,f_(k-1))$ to have the same orientation as $(e_1,...,e_k)$.
#line(length: 100%)
*Exterior differentiation*
To see the divergence we assume the domain $Omega$ is very small.
Suppose $Omega$ is the parallelepiped (平行六面体) spanned by $epsilon xi_1, epsilon xi_2, epsilon xi_3$
The _divergence_ is obtained as the limit
$ lim (integral_(partial Omega_epsilon) omega^2)/(epsilon^3 V), quad V = det(xi_1,xi_2,xi_3) $
*Def. (exterior derivative)* (_omitted, see page 189 _)
*Thm.* Let $omega^k$ be a $k$-form, then there exists a unique $(k+1)$-form $Omega$ on $T M$, given as
$ F(epsilon xi_1,...,epsilon xi_(k+1)) = epsilon^(k+1) Omega(xi_1,...,xi_(k+1)) + o(epsilon^(k+1)) quad (epsilon -> 0) $
where $F=integral_sigma omega^k$, $sigma$ be the boundary of the parallelepiped spanned by $(epsilon xi_1,...,epsilon xi_(k+1))$.
Moreover, if $omega^k = sum a_(i_1,...,i_k) dif x_i_1 and ... and dif x_i_k$, then $ Omega = dif omega^k = sum dif a_(i_1,...,i_k) and dif x_i_1 and ... and dif x_i_k $
_注. 这基本给出了 stokes 公式._
_Example._ $omega^2 = A dif y and dif z + B dif z and dif x + C dif x and dif y$, then $Omega = dif omega^2 = "div"(A,B,C) dif x and dif y and dif z$.
_Proof._ 只证最简单的 $1$-form $omega^1 = a(x_1,x_2) dif x_1$.
Given $xi,eta$ (small enough) shown as below, we calculate $F(xi,eta) = integral_sigma omega^1$, where $sigma$ is the boundary of the parallelogram spanned by $eta,xi$.
#figure(
image("img/stokes.png", width: 35%)
)
$display(
integral_sigma omega^1
&= integral_0^1 (a(xi t) - a(xi t + eta))xi_1 - (a(eta t) - a(eta t + xi))eta_1 dif t & (xi_i = dif x_i (xi), eta_i = dif x_i (eta))& \
&= integral_0^1 -(cancel((partial a)/(partial x_1)eta_1)+(partial a)/(partial x_2)eta_2)xi_1 + (cancel((partial a)/(partial x_1)xi_1)+(partial a)/(partial x_2)xi_2)eta_1 dif t &+ o(||xi||^2 + ||eta||^2) \
&&("derivative taken at" x_1=x_2=0) \
&= (partial a)/(partial x_2) (eta_2 xi_1 - xi_1 eta_2) + o(||xi||^2 + ||eta||^2)
)$
$==> Omega(xi, eta) = (partial a)/(partial x_2) (eta_2 xi_1 - xi_1 eta_2) ==> Omega = (partial a)/(partial x_2) dif x_2 and dif x_1 = dif omega^1$.
*Thm. (Stokes formula)* Let $omega$ be a $k$-form, $Omega$ be a chain of dim $k+1$. Then $ integral_(partial Omega) omega= integral_Omega dif omega $
_Proof. See page 192, using the thm above._
#line()
*Def.* We say a differential form $omega$ is _closed_ if $dif omega = 0$.
A closed form, when integrated on a boundary, is always 0.
*Def.* A differential $k$-form $omega$ is called _exact_ if there exists a $(k-1)$-form $alpha$ s.t. $dif alpha = omega$.
For any differential form, we have $dif^2 omega = 0 ==>$ an exact form is closed.
Dually, for any chain $Omega$, $partial^2 Omega = 0$.
#pagebreak()
#line(length: 100%)
Chapter 08 Symplectic manifolds
#line(length: 100%)
A _symplectic manifold_ $(M^(2n),omega^2)$ is an even dimensional manifold $M^(2n)$ endowed with a closed nondegenerate differential $2$-form $omega^2$.
nondegenerate: $forall xi,eta in T_x M, omega^2|_x (xi,eta) = angle.l A xi, eta angle.r$, where $A$ is nondegenerate and anti-symmetric.
_Example._ $RR^(2n), quad x_1,...,x_n,y_1,...,y_n, quad omega^2 = dif y_1 and dif x_1 + ... + dif y_n and dif x_n$
The most important symplectic manifold for us is $T^* M$ (_cotangent bundle_, 余切丛), $ T^* M = union.big_(x in M) T_x^* M $
where $T_x^* M$ is the _cotangent space_ of $M$ at $x$, i.e. the space of $1$-forms on $T_x M$.
#line()
The Lagrangian mechanics happens on $T M$, $ L: T M -> RR $
The Hamiltonian mechanics happens on $T^* M$, $ H: T^* M -> RR $
$H(p, q) = display(sup_(dot(q))) (angle.l p, dot(q) angle.r - L(dot(q), q)), quad p in T_q M$
The generalized momentum $p$ is a linear functional on $T_q M$.
#line()
On $T^* M$, there is _a natual symplectic form_
$ omega^2 = dif p and dif q = sum dif p_i and dif q_i $
$omega^2 = dif omega^1$, where $omega = p dif q$ is a $1$-form on $T^* M$.
Let $q$ be coordinates on $M$, $p$ be coordinates on $T_q^* M$.
Let $N = T^* M$, $omega = p dif q$ is a 1-form on $N$. At point $x=(p,q) in N$,
$
omega|_x: &T_x N &&-> RR \
&(p dif q) xi &&= p dot.c xi_q
$
#line()
We next introduce the Hamiltonian vector field.
*Def.* To every vector $xi in T_x M$, where $(M,omega^2)$ is a symplectic manifold. We can associate a $1$-form $ omega_xi^1 (eta) = omega^2 (eta,xi), forall eta in T_x M $
This induces an isomorphism between $T_x M$ and $T_x^* M$, $xi |-> omega_xi^1$
We denote this isomorphism as $I$:
$ I: &T_x^*M &-> &T_x M \
&omega_xi^1 = omega^2 (dot.c, xi) &|-> &xi $
By the nondegeneracy, $omega^2 (eta,xi) = angle.l A eta, xi angle.r = angle.l eta, A^T xi angle.r$, thus $omega_xi^1$ is exactly the vector $A^T xi$.
Let $H: M -> RR$ be a function, then $dif H$ is a $1$-form on $T^* M$. By the isomorphism, there exists a vector field on $M$ denoted by $X_H = I dif H$, called the Hamiltonian vector field.
_但反过来, 每个 $M$ 上的 vector field 不一定是一个函数的微分. 如果是, 我们定义_:
*Def.* We say a vector field $X_H$ a _Hamiltonian vector field_, if there exists $H$ s.t. $omega(dot.c, X_H) = dif H$.
_Example._ $RR^2, quad (y,x), quad omega = dif y and dif x, quad H:RR^2->RR$ a Hamiltonian function
设 $H$ 对应的 Hamiltonian vector field 为 $X$, 则由定义有 $omega(xi, X) = dif H(xi)$
$==> mat(delim: "|", xi_y, X_y; xi_x, X_x) = (partial H)/(partial y) xi_y + (partial H)/(partial x) xi_x ==> X = (X_y, X_x) = (-(partial H)/(partial x), (partial H)/(partial y))$
#line()
Given Hamiltonian vector field $X_H$, we define the _Hamiltonian flow_ by solving the ODE
$ dot(x) = X_H (x), quad x in N = T^*M $
denoted by
$ g^t: N &-> N \
x &|-> g^t x $
_Example._ 上面那个例题中, $H$ 导出的 Hamiltonian flow 便由
#align(center, $(dot(y), dot(x)) = (-(partial H)/(partial x), (partial H)/(partial y))$)
给出, 这即是 Hamiltonian canonical equation.
*Thm.* A Hamiltonian flow preserves the symplectic structure
$ (g^t)^* omega = omega $
_Proof. See page 204._
// TODO
#line()
*Law of energy conservation*
*Thm.* Let $H: M -> RR$ be a Hamiltonian function, then it is constant under the corresponding Hamiltonian flow (with Hamiltonian function $H$).
_Proof._ $space dif/(dif t) H(g^t x) = dif H (X_H) = omega(X_H, X_H) =0$.
\
#line(length: 100%)
*The algebraic structure of Hamiltonian mechanics*
#line()
*The commutator of vector fields*
Let $A(z)$ be a vector field on $RR^n$, we have the ODE $dot(z) = A(z)$.
Let $a^t$ be the flow of the ODE.
*Def.* Given a smooth function $phi: RR^n -> RR$, the Lie derivative of $phi$ along the vector field $A$ is defined as
$ (cal(L)_A phi) (z) = lr(dif/(dif t)mid(|))_(t=0) phi(a^t z) = dif phi dot.c A = sum A_i partial/(partial z_i) phi $
We denote
$ cal(L)(A) := A_1 (z) partial/(partial z_1) + ... + A_n (z) partial/(partial z_n) $
*Lemma.* The operator $cal(L)_B cal(L)_A - cal(L)_A cal(L)_B$ is a #underline("first order") linear operator.
_Proof._
#align(center, $display(
cases(cal(L)_B cal(L)_A phi = sum_i B_i partial/(partial z_i) (sum_j A_j partial/(partial z_j) phi) = sum_(i,j) lr((B_i (partial A_j)/(partial z_i) (partial phi)/(partial z_j) + cancel(B_i A_j (partial^2 phi)/(partial z_i partial z_j) phi))),
cal(L)_A cal(L)_B phi = sum_i A_i partial/(partial z_i) (sum_j B_j partial/(partial z_j) phi) = sum_(i,j) lr((A_i (partial B_j)/(partial z_i) (partial phi)/(partial z_j) + cancel(A_i B_j (partial^2 phi)/(partial z_i partial z_j) phi))))
) "(指相减时消掉)"$)
$==> (cal(L)_B cal(L)_A - cal(L)_A cal(L)_B) phi = sum_(i,j) (B_i (partial A_j)/(partial z_i) - A_i (partial B_j)/(partial z_i)) partial/(partial z_j) phi =: sum_(i,j) [A,B]_j space partial/(partial z_j) phi = [A,B] dot.c dot(phi)$
We denote $ [A,B]_j := sum_i (B_i (partial A_j)/(partial z_i) - A_i (partial B_j)/(partial z_i)) $
*Def.* The _commutator_ of two vector field $A$ and $B$ is the vector field $C$ for which
$ cal(L)_C = cal(L)_B cal(L)_A - cal(L)_A cal(L)_B $
denoted by $ C = [A, B] $
*Prop.* For all smooth vector fields $A,B,C$, we have
(1) linearity: $[a A + b B, C] = a[A,C] + b[B,C]$\
(2) anti-symmetry: $[A,B] = -[B,A]$\
(3) _Jacobi identity:_ $[[A,B],C] + [[B,C],A] + [[C,A],B] = 0$
These implies the space of $C^oo$ vector fields forms a _Lie algebra_.
*Thm.* Let $a^t, b^t$ be the flows generated by vector fields $A,B$ respectively. Then the flows _commute_ iff the commutator of the vector field vanish, i.e.
$ a^t circle.tiny b^s = b^s circle.tiny a^t <==> [A,B]=0 $
_Proof._ We first have
$display(lr(partial^2/(partial s partial t)mid(|))_(t=s=0) (phi(a^t b^s z) - phi(b^s a^t z)) = (cal(L)_B cal(L)_A - cal(L)_A cal(L)_B) phi) = [A,B] dot.c dot(phi)$
This proves "$==>$".
For the "$<==$" part, if $[A,B]=0$, then $phi(a^t b^s z) - phi(b^s a^t z) = o(s^2 + t^2) quad (s,t-> 0)$
We partition the ractangle $[0,t) times [0,s)$ into $N^2$ equal small ractangles.
We deform the path of $b^s a^t$ into $a^t b^s$ by $N^2$ steps. The total error is $o(1)$.
Letting $N -> oo$, we get $phi(a^t b^s z) = phi(b^s a^t z), forall phi$.
#line()
*Poisson bracket*
*Def.* Let $F, H$ be two functions on a symplectic manifold $(M, omega)$, the _Poisson bracket_ ${F, H}$ is defined as the derivative of $F$ along the Hamiltonian flow of $H$,
$ {F,H}(z) = lr(dif/(dif t)mid(|))_(t=0) F(g_H^t z) = dif F (X_H) = underbrace(omega(X_H,X_F), "注意"F"和"H"的位置是反的") $
Since $omega$ is anti-symmetric, ${F,H} = -{H,F}$.
_Example._ $RR_((x,y))^2, quad omega = dif y and dif x$
$quad quad quad quad cases(dot(x) = (partial F)/(partial y), dot(y) = -(partial F)/(partial x)) quad cases(dot(x) = (partial H)/(partial y), dot(y) = -(partial H)/(partial x))$
$==> {F,H}(z) = lr(dif/(dif t)mid(|))_(t=0) F(g_H^t z) = (partial F)/(partial x) dot(x) + (partial F)/(partial y) dot(y) = (partial F)/(partial x) (partial H)/(partial y) - (partial F)/(partial y) (partial H)/(partial x)$.
*Prop.* The Poisson bracket has the following properties: $forall H_1,H_2,H_3 in C^oo (M)$, we have
(1) linearity \
(2) anti-symmetry \
(3) _Jacobi identity:_ ${{H_1, H_2}, H_3} + {{H_2, H_3}, H_1} + {{H_3, H_1}, H_2} = 0$
Thus, the space of $C^oo (M)$ also forms a Lie algebra under the Poisson bracket.
*Thm.* Let $Beta,Gamma$ be two Hamiltonian vector field with Hamiltonians $beta, gamma$. Then $[Beta,Gamma]$ is a Hamiltonian vector field whose Hamiltonian is exactly ${beta,gamma}$.
_Proof._ Let ${beta, gamma} = delta$.
$forall alpha$, by Jacobi identity, we have
${alpha,delta} = {alpha, {beta, gamma}} = {{alpha, beta}, gamma} - {{alpha,gamma}, beta}$.
${{alpha, beta}, gamma} = cal(L)_Gamma {alpha,beta} = cal(L)_Gamma cal(L)_Beta alpha, space {{alpha,gamma}, beta} = cal(L)_Beta {alpha,gamma} = cal(L)_Beta cal(L)_Gamma alpha$
Let $Delta$ be the Hamiltonian vector field of $delta$, then ${alpha, delta} = cal(L)_Delta alpha$
$==> cal(L)_Delta = cal(L)_Gamma cal(L)_Beta - cal(L)_Beta cal(L)_Gamma = cal(L)_[Beta,Gamma]$
\
#line()
*Symplectic transformation*
_Example._ $H: RR^2-> RR, H(y,x) = 1/2 (y^2 + x^2)$, Hamiltonian equation $cases(dot(y) = -x, dot(x) = y)$
Let $cases(x= r sin theta, y= r cos theta) space$ be the polar coordinates.
$==> cases(dot(r) = ... = 0, dot(theta) = ... = 1)$
$H(r,theta) = 1/2 r^2$, if Hamiltonian equation holds, $cases(dot(r) = -(partial H)/(partial theta) = 0, dot(theta) = (partial H)/(partial r) = r)$, contradicts! \
_问题在于这一变换并不是辛变换!_ \
Instead of $(r, theta)$, we use $(I, theta)$, where $I = r^2/2$. Then $H=I, cases(dot(I) = -(partial H)/(partial theta) = 0, dot(theta) = (partial H)/(partial I) = 1) space$ agrees.
#figure(
image("/img/handwritten/handwritten_5.jpg")
)
#figure(
image("/img/handwritten/handwritten_6.jpg")
)
#figure(
image("/img/handwritten/handwritten_7.jpg")
)
#figure(
image("/img/handwritten/handwritten_8.jpg")
)
#figure(
image("/img/handwritten/handwritten_9.jpg")
)
#figure(
image("/img/handwritten/handwritten_10.jpg")
)
#figure(
image("/img/handwritten/handwritten_11.jpg")
)
#figure(
image("/img/handwritten/handwritten_12.jpg")
)
#figure(
image("/img/handwritten/handwritten_13.jpg")
)
#figure(
image("/img/handwritten/handwritten_14.jpg")
)
#figure(
image("/img/handwritten/handwritten_15.jpg")
)
#figure(
image("/img/handwritten/handwritten_16.jpg")
)
#figure(
image("/img/handwritten/handwritten_17.jpg")
)
#figure(
image("/img/handwritten/handwritten_18.jpg")
)
#figure(
image("/img/handwritten/handwritten_19.jpg")
)
#pagebreak()
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/tracking-spacing-02.typ | typst | Other | // Test that tracking doesn't disrupt mark placement.
#set text(font: ("PT Sans", "Noto Serif Hebrew"))
#set text(tracking: 0.3em)
טֶקסט
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Interi/Divisione.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
Dati due numeri interi $n$ e $m$, con $n > m > 0$, l'operazione di
*divisione euclidea* (o *divisione intera*) induce due numeri interi
$q$ e $r$, chiamati rispettivamente _quoziente_ e _resto_, tali che
il prodotto fra $m$ e $q$ é il multiplo di $m$ che piú si avvicina
ad $n$ per difetto ed il resto $r = n - m q$ misura lo scarto.
#theorem[
Siano $n$ e $m$ due numeri interi, con $m != 0$. Esiste una ed
una sola coppia di interi $q$ ed $r$ tali per cui $n = m q + r$
e $0 lt.eq r < |m|$
]
/* #proof[
Si supponga che $n gt.eq 0$. Fissato arbitrariamente $m$, si proceda per
induzione su $n$:
- Se $n = 0$, si ha $0 = m q + r$, ovvero $m q = -r$. In effetti, esiste
una ed una sola coppia di numeri interi $q$ ed $r$ per i quali tale
uguaglianza é verificata, ovvero $0, 0$. Infatti, $m dot 0 = -0 = 0$
e $0 lt.eq 0 < |m|$;
- Assumendo che esista una ed una sola coppia di numeri interi $q$ ed $r$
tali per cui $n = m q + r$ e $0 lt.eq r < |m|$, si dimostri che esista
una ed una sola coppia di numeri interi $q'$ ed $r'$ tali per cui
$(n + 1) = m q' + r'$ e $0 lt.eq r' < |m|$
Se $n gt.eq |m|$, ovvero se $n > n − |m| gt.eq 0$, per l'ipotesi di
induzione esistono $q'$ e $r'$ in $ZZ$ tali che $n − |m| = m q' + r'$
con $0 lt.eq r' < |m|$.
Allora $n = m q' + |m| + r'$ e, essendo $|m| = plus.minus m$, si ha
$n = m(q' plus.minus 1) + r'$ con $0 lt.eq r < |m|$.
Per quanto riguarda l'unicitá
] */
Siano $a$ e $b$ due numeri interi. Se esiste $c in ZZ$ tale che $a = b c$,
si dice che $b$ _divide_ $a$, oppure analogamente che $a$ é _divisibile_
per $b$. Per indicare che $b$ divide $a$ viene usata la notazione $b | a$;
se invece $b$ non divide $a$, si usa la notazione $b divides.not a$. Se $b$
divide $a$, si dice anche che $b$ é _multiplo_ di $a$.
#lemma[
Per qualsiasi $a in ZZ$, sia $plus.minus 1$ che $plus.minus a$
sono divisori di $a$.
]
// #proof[
// Dimostrabile, da aggiungere
// ]
Siano $a, b in ZZ$ non entrambi nulli; si dice che $d in ZZ$ é un *Massimo
Comun Divisore* tra $a$ e $b$ se sono verificate entrambe le seguenti due
condizioni:
+ $d | a$ e $d | b$. Ovvero, $d$ é divisore sia di $a$ che di $b$;
+ Se $c in ZZ$ é tale che $c | a$ e $c | b$, allora $c | d$. Ovvero,
tutti i divisori di $a$ che sono anche divisori di $b$ sono anche
divisori di $d$.
#theorem[
Dati due numeri $a, b in ZZ$ non entrambi nulli, se $d$ e $tilde(d)$
sono due Massimi Comun Divisori fra $a$ e $b$ allora devono essere
uguali in modulo, ovvero deve aversi $d = plus.minus tilde(d)$.
]
#proof[
Essendo $d$ un Massimo Comun Divisore per $a$ e $b$, deve valere
$d | a$ e $d | b$. Inoltre, deve valere anche che se $c in ZZ$
é tale che $c | a$ e $c | b$, allora $c | d$.
Essendo peró anche $tilde(d)$ un Massimo Comun Divisore per $a$ e
$b$, deve valere $tilde(d) | a$ e $tilde(d) | b$. Allora é possibile
sostituire $c$ con $tilde(d)$ nella seconda espressione ed ottenere
che $tilde(d) | d$.
É peró possibile operare anche in senso contrario: essendo $tilde(d)$
un Massimo Comun Divisore per $a$ e $b$, deve valere anche che se $c
in ZZ$ é tale che $c | a$ e $c | b$, allora $c | tilde(d)$, e valendo
$d | a$ e $d | b$ deve aversi che $d | tilde(d)$.
Esistono allora due numeri $h, k in ZZ$ tali per cui $tilde(d) = h d$
e $d = tilde(d)$. Ne segue $tilde(d) = (h k) tilde(d)$, e quindi $h
k = 1$. Deve allora aversi $h = k = 1$ e quindi $d = tilde(d)$ oppure
$h = k = -1$ e quindi $d = -tilde(d)$.
]
Dal teorema si evince immediatamente che se $d$ é un Massimo Comun Divisore
positivo di due numeri interi $a$ e $b$, allora $d$ é univoco. Tale valore
viene indicato con $"MCD"(a, b)$.
#theorem("Esistenza ed unicitá del Massimo Comun Divisore")[
Per una qualsiasi coppia di numeri interi $a$ e $b$ non entrambi nulli
esiste sempre ed é univoco $d = "MCD"(a, b)$
] <MCD-exists-and-unique>
#proof[
Innanzitutto, é immediato riconoscere che se $d = "MCD"(a, b)$, allora é
vero anche $d = "MCD"(-a, -b)$. É altrettanto immediato riconoscere che
$"MCD"(a, b) = "MCD"(b, a)$ per qualsiasi $a, b$. Pertanto, senza perdita
di generalitá, é possibile assumere che $a$ e $b$ siano numeri naturali
con $a gt.eq b$.
Se $a = 0$ e $b != 0$ si verifica facilmente che $"MCD"(a, b) = a$; allo
stesso modo, se $b = 0$ e $a != 0$ si ha $"MCD"(a, b) = b$. Si consideri
pertanto il caso piú generale in cui $a != 0$ e $b != 0$. Devono allora
esistere un quoziente $q_(1)$ ed un resto $r_(1)$ tali per cui é possibile
eseguire la divisione:
$ a = b q_(1) + r_(1) , 0 lt.eq r_(1) < b $
Se $r_(1) = 0$, allora $"MCD"(a, b) = b$, perché $a = b q_(1)$ é la
definizione stessa di $b | a$ e $q_(1)$ é arbitrario. Se cosí non é,
é possibile ripetere l'operazione e risvolgere i calcoli con un nuovo
resto ed un nuovo quoziente. Piú in generale:
#set math.mat(column-gap: 2.5em, delim: none)
$ mat(
& (1), & a = b q_(1) + r_(1), & r_(1) != 0;
& (2), & b = r_(1) q_(2) + r_(2), & r_(2) != 0;
& (3), & r_(1) = r_(2) q_(3) + r_(3), & r_(3) != 0;
& dots.v, &, &;
& (k - 1), & r_(k - 3) = r_(k - 2) q_(k - 1) + r_(k - 1),
& r_(k - 1) != 0;
& (k), & r_(k - 2) = r_(k - 1) q_(k), &;
) $
Il fatto che prima o poi si giunga ad una $k$-esima iterazione
in cui $r_(k) = 0$ é garantito dal fatto che tale successione
é una successione strettamente crescente di numeri non negativi.
L'ultimo resto non nullo, ovvero $r_(k - 1)$, é precisamente
$"MCD"(a, b)$. Per verificarlo, é sufficiente osservare come
questo possegga entrambe le proprietá enunciate nella definizione
di Massimo Comun Divisore:
- Alla riga $(k)$ si ha $r_(k - 2) = r_(k - 1) q_(k)$,
ovvero $r_(k - 1) | r_(k - 2)$. Sostituendo la riga $(k)$
nella riga $(k - 1)$ si ha:
$ r_(k - 3) = r_(k - 2) q_(k - 1) + r_(k - 1) =
r_(k - 1) q_(k) q_(k - 1) + r_(k - 1) =
r_(k - 1) (q_(k) q_(k - 1) + 1) $
Ovvero, $r_(k - 1) | r_(k - 3)$ (Si noti come il raccoglimento
é ammesso dato che $r_(k - 1)$ é definito come non nullo).
Risalendo di riga in riga, é facile convincersi che dalla
riga $(2)$ si ottiene $r_(k - 1) | r_(1)$ e $r_(k - 1) | b$.
Dalla riga $(1)$ segue $r_(k - 1) | a$. Avendo dimostrato che
$r_(k - 1) | a$ e $r_(k - 1) | b$, si ha che $r_(k - 1)$ possiede
la prima proprietá dell'MCD.
- Sia $c in ZZ - {0}$. Siano poi $a = c overline(a)$ e $b = c
overline(b)$. Sostituendo nella riga $(1)$ si ottiene:
$ a = b q_(1) + r_(1) =>
c overline(a) = c overline(b) q_(1) + r_(1) =>
r_(1) = c overline(a) - c overline(b) q_(1) =>
r_(1) = c (overline(a) - overline(b) q_(1)) $
Da cui si ha $c | r_(1)$. Ponendo $r_(1) = c overline(r_(1))$ e
sostituendo nella riga $(2)$, si ha:
$ b = r_(1) q_(2) + r_(2) =>
c overline(b) = c overline(r_(1)) q_(2) + r_(2) =>
r_(2) = c overline(b) - c overline(r_(1)) q_(2) =>
r_(2) = c (overline(b) - overline(r_(1)) q_(2)) $
Da cui si ha $c | r_(2)$. Discendendo di riga in riga ed applicando
lo stesso procedimento, si arriva fino a $c | r_(k - 1)$. Ma questo
equivale a dire che, per un $c$ numero intero generico, se $c | a$
e $c | b$, allora $c | r_(k - 1)$, e quindi $r_(k - 1)$ possiede
anche la seconda proprietá dell'MCD.
]
La dimostrazione del @MCD-exists-and-unique fornisce implicitamente anche
un algoritmo per calcolare, a partire da due numeri interi $a$ e $b$ non
entrambi nulli, il loro MCD. Tale algoritmo é strutturato come segue:
+ Si calcola qual'é il piú grande intero $q$ tale per cui é possibile
moltiplicarlo per $b$ ottenendo un valore inferiore ad $a$;
+ Si calcola $r$ come differenza fra $q b$ ed $a$. Se tale valore é
nullo, allora $q$ é MCD per $a$ e $b$, e l'algoritmo termina;
+ $b$ diventa il nuovo $a$, mentre $r$ diventa il nuovo $b$. Dopodiché,
si torna al punto 1.
#example[
L'MCD dei numeri $a = 110143$ e $b = 665$ é 19. Infatti:
#set math.mat(delim: none)
$ mat(
110143 & = 665 dot 165 + 418 &;
665 & = 418 dot 1 + 247 &;
418 & = 247 dot 1 + 171 &;
247 & = 171 dot 1 + 76 &;
171 & = 76 dot 2 + 19 &;
76 & = 19 dot 4 &;
) $
]
#theorem("Identitá di Bézout")[
Se $a$ e $b$ sono due numeri interi non entrambi nulli, allora
esistono due numeri interi $x$ e $y$ tali per cui vale:
$ a x + b y = "MCD"(a, b) $
] <Bezout>
#proof[
Facendo riferimento al @MCD-exists-and-unique, si consideri
la successione di operazioni. In particolare, la riga $(1)$,
ovvero $a = b q_(1) + r_(1)$, puó anche essere riscritta come
$r_(1) = a (1) + b (-q_(1))$. Sostituendo nella riga $(2)$, si ha:
$ b = r_(1) q_(2) + r_(2) =>
b = (a - b q_(1)) q_(2) + r_(2) =>
r_(2) = b - a q_(2) + b q_(1) q_(2) =>
r_(2) = a (-q_(2)) + b (q_(1) q_(2) + 1) $
In questo modo, é possibile ciascun resto come combinazione
lineare intera di $a$ e di $b$:
#set math.mat(column-gap: 1.5em, delim: none)
$ mat(
& (1), & a = b q_(1) + r_(1), r_(1) &= a - b q_(1);
& (2), & b = r_(1) q_(2) + r_(2), r_(2) &= b - r_(1) q_(2) =
a (-q_(2)) + b (q_(1) q_(2) + 1);
& (3), & r_(1) = r_(2) q_(3) + r_(3), r_(3) &= r_(1) - r_(2) q_(3) =
a(q_(2) q_(3) + 1) + b(-q_(1) - q_(3) - q_(1) q_(2) q_(3));
& dots.v, & ;
) $
In particolare per il resto $r_(k - 1)$, che é anche il massimo comun
divisore di $a$ e di $b$, esisteranno due valori $x$ e $y$ tali per
cui é possibile esprimerlo come combinazione lineare intera di $a$ e
$b$, e quindi $r_(k - 1) = "MCD"(a, b) = a x + b y$.
]
La dimostrazione del @Bezout fornisce implicitamente anche un algoritmo
per calcolare, a partire da due numeri interi $a$ e $b$ non entrambi nulli,
una possibile coppia $x, y$ di interi tali da soddisfare l'identitá per $a$
e $b$, fintanto che il loro MCD é noto. Tale algoritmo é strutturato come
segue:
+ Si esprime $r$ in funzione di $a$ e di $b$, spostando ques'ultimo a primo
membro ed isolando $r$ a secondo membro;
+ Se $r$ é l'MCD di $a$ e di $b$, l'algoritmo termina, perché le soluzioni
particolari cercate sono i coefficienti di $a$ e di $b$;
+ Si passa alla riga successiva e si ripete il procedimento, esprimendo i
due nuovi $a$ e $b$ in funzione dei precedenti. Si osservi come questi,
ad ogni iterazione, cambiano di segno.
#example[
L'MCD dei numeri $a = 110143$ e $b = 665$ é 19. Una soluzione
particolare che soddisfa l'identitá di Bézout per questa coppia
é ricavata di seguito:
#set math.mat(delim: none)
$ mat(
110143 & = 665 dot 165 + 418 & =>
& a & = & 165 b + 418 & =>
& a - 165 b & = & 418 &;
665 & = 418 dot 1 + 247 & =>
& b & = & a - 165 b + 247 & =>
& 166 b - a & = & 247;
418 & = 247 dot 1 + 171 & =>
& a - 165 b & = & 166 b - a + 171 & =>
& 2 a - 331 b & = & 171;
247 & = 171 dot 1 + 76 & =>
& 166 b - a & = & 2 a - 331 b + 76 & =>
& 497 b - 3 a & = & 76;
171 & = 76 dot 2 + 19 & =>
& 2 a - 331 b & = & 2(497 b - 3 a) + 19 & =>
& 8 a - 1325 b & = & 19;
) $
]
Se due numeri interi hanno 1 come Massimo Comun Divisore, allora si
dice che tali numeri sono *coprimi* o *primi fra di loro*.
#lemma[
Due numeri interi $a$ e $b$ sono primi fra di loro se e soltanto
se esistono due numeri interi $x$ e $y$ tali per cui vale $a x +
b y = 1$.
] <Coprime-as-Bézout>
#proof[
Il primo verso dell'implicazione deriva direttamente dalla definizione
di numeri coprimi. Infatti, due numeri interi $a$, e $b$ si dicono
coprimi se il loro MCD é 1; sostituendolo nell'identitá di Bézout,
si ha precisamente $a x + b y = 1$.
Ció che manca da dimostrare é il secondo verso, ovvero che se per due
numeri interi $a$ e $b$ esistono due numeri interi $x$ e $y$ tali per
cui $a x + b y = 1$, allora $a$ e $b$ sono coprimi. Si supponga per
assurdo che, se esistono $x$ e $y$, tali per cui $a x + b y = 1$,
allora $a$ e $b$ non siano coprimi. Questo significa che il loro MCD
non é 1, ovvero che $a x + b y != 1$, ma questo é in contraddizione
con l'ipotesi assunta per assurdo.
]
Siano $a, b in ZZ$ non entrambi nulli; si dice che $m in ZZ$ é un *Minimo
Comune Multiplo* tra $a$ e $b$ se sono verificate entrambe le seguenti due
condizioni:
+ $a | m$ e $b | m$. Ovvero, sia $a$ che $b$ sono divisori di $m$;
+ Se $c in ZZ$ é tale che $a | c$ e $b | c$, allora $m | c$. Ovvero,
se sia $a$ che $b$ sono divisori di un generico $c$, allora anche $m$
é divisore di $c$.
#theorem[
Dati due numeri $a, b in ZZ$ non entrambi nulli, se $m$ e $tilde(m)$
sono due Minimi Comuni Multipli fra $a$ e $b$ allora devono essere
uguali in modulo, ovvero deve aversi $m = plus.minus tilde(m)$.
]
Dal teorema si evince immediatamente che se $m$ é un Minimo Comune Multiplo
positivo di due numeri interi $a$ e $b$, allora $m$ é univoco. Tale valore
viene indicato con $"mcm"(a, b)$.
#theorem("Esistenza ed unicitá del Minimo Comune Multiplo")[
Per una qualsiasi coppia di numeri interi $a$ e $b$ non entrambi
nulli esiste sempre ed é univoco $m = "mcm"(a, b)$. In particolare,
$"mcm"(a, b) = frac(a b, "MCD"(a, b))$.
]
#proof[
Sia $d = "MCD"(a, b)$. Siano poi $a = tilde(a)d$, $b = tilde(b)d$ e
$m = frac(a b, d)$. Sostituendo le espressioni di $a$ e $b$ in $m$,
si ha $m = frac(tilde(a) d tilde(b) cancel(d), cancel(d)) = tilde(a)
tilde(b) d = a tilde(b) = b tilde(a)$, da cui si evince $a | m$ e
$b | m$, provando il primo requisito della definizione di Minimo
Comune Multiplo.
Preso un $c in ZZ$ tale per cui $a | c$ e $b | c$, ossia tale
per cui $c = a s = b t$ per certi $s, t in ZZ$, si ha $c =
tilde(a) s d = tilde(b) t d$, ovvero $tilde(a) s = tilde(b) t$.
Poiché $"MCD"(tilde(a), tilde(b)) = 1$, deve aversi $tilde(a) |
t$ e $tilde(b) | s$, ovvero deve valere $t = h tilde(a)$ e $s =
k tilde(b)$ per certi $h, k in ZZ$. Sostituendo $t = h tilde(a)$
nell'espressione per $c$, si ha $c = b tilde(a) h = m h$, da cui si
deduce $m | c$, provando il secondo requisito della definizione di
Minimo Comune Multiplo.
]
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/charts.typ | typst | #import "@preview/cetz:0.2.2": canvas, chart, draw, palette, plot
#let data = ((19, 0, 1, 0), (22, 1, 0, 0), (23, 10, 0, 0), (24, 1, 0, 0), (25, 1, 0, 0), (28, 2, 0, 0), (31, 1, 0, 0), (54, 0, 1, 0), (55, 1, 0, 0), (56, 0, 1, 0), (60, 1, 0, 0))
#let age_gender = canvas({
draw.set-style(legend: (fill: white))
chart.columnchart(
size: (12, 5),
mode: "stacked",
value-key: (1,2,3),
data,
x-label: "Alter",
y-label: "Anzahl",
bar-style: palette.new(colors: (rgb(217, 48, 29), rgb(0, 176, 240), rgb(210, 246, 138))),
labels: ([Männlich], [Weiblich], [Divers]),
legend: "legend.inner-north-east",
)
}) |
|
https://github.com/liuguangxi/fractusist | https://raw.githubusercontent.com/liuguangxi/fractusist/main/tests/test-sierpinski-triangle.typ | typst | MIT License | #set document(date: none)
#import "/src/lib.typ": *
#set page(margin: 1cm)
= n = 1
#align(center)[
#sierpinski-triangle(1, step-size: 40)
]
= n = 2
#align(center)[
#sierpinski-triangle(2, step-size: 30, fill-style: gray, stroke-style: none)
]
= n = 3
#align(center)[
#sierpinski-triangle(3, step-size: 20, fill-style: none, stroke-style: stroke(paint: gradient.linear(..color.map.crest, angle: 45deg), thickness: 4pt, join: "bevel"))
]
= n = 4
#align(center)[
#sierpinski-triangle(4, step-size: 20, fill-style: gradient.radial((orange, 0%), (silver, 100%), focal-center: (30%, 30%)), stroke-style: stroke(paint: gradient.linear(..color.map.crest, angle: 45deg), thickness: 2pt, join: "bevel"))
]
#pagebreak(weak: true)
= n = 5
#align(center)[
#sierpinski-triangle(5, step-size: 10, fill-style: none, stroke-style: stroke(paint: purple, thickness: 2pt, join: "bevel"))
]
= n = 6
#align(center)[
#sierpinski-triangle(6, step-size: 6, fill-style: gradient.linear(..color.map.crest, angle: 45deg), stroke-style: none)
]
#pagebreak(weak: true)
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/loading/toml.typ | typst | --- toml ---
// Test reading TOML data.
#let data = toml("/assets/data/toml-types.toml")
#test(data.string, "wonderful")
#test(data.integer, 42)
#test(data.float, 3.14)
#test(data.boolean, true)
#test(data.array, (1, "string", 3.0, false))
#test(data.inline_table, ("first": "amazing", "second": "greater") )
#test(data.table.element, 5)
#test(data.table.others, (false, "indeed", 7))
#test(data.date_time, datetime(
year: 2023,
month: 2,
day: 1,
hour: 15,
minute: 38,
second: 57,
))
#test(data.date_time2, datetime(
year: 2023,
month: 2,
day: 1,
hour: 15,
minute: 38,
second: 57,
))
#test(data.date, datetime(
year: 2023,
month: 2,
day: 1,
))
#test(data.time, datetime(
hour: 15,
minute: 38,
second: 57,
))
--- toml-invalid ---
// Error: 7-30 failed to parse TOML (expected `.`, `=` at line 1 column 16)
#toml("/assets/data/bad.toml")
|
|
https://github.com/magic3007/cv-typst | https://raw.githubusercontent.com/magic3007/cv-typst/master/doc/interests.typ | typst | Modeling and Optimization in VLSI CAD, Machine Learning Applications, HPC, MLSys, Probabilistic Modeling |
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/common/font-paths.md | markdown | MIT License | <!-- markdownlint-disable-file first-line-h1 -->
List of sources specifying paths to font files that will be made available to
your Typst project. With this, you can compile Typst projects even when the
fonts it uses are not available on your system.
Used for setting `TYPST_FONT_PATHS` (see [`text#font`][typst-ref-text--font]).
[typst-ref-text--font]: https://typst.app/docs/reference/text/text/#parameters-font
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/-2-dedication.typ | typst | Other | #align(
horizon,
)[
#show emph: set text(size: 1.4em)
#set par(first-line-indent: 0pt)
#show par: it => block(spacing: 1.6em, it)
_To my family and the htmx discord._ --- <NAME>
_To my wife Tarunya, for her support through the ups and downs of this project._ --- <NAME>
_<NAME> ve babam Özgür Akşimşek’e._ --- <NAME>ek
]
|
https://github.com/lkndl/typst-bioinfo-thesis | https://raw.githubusercontent.com/lkndl/typst-bioinfo-thesis/main/modules/info-covers.typ | typst | #import "styles.typ": *
#let info-front-style(body) = {
set align(center)
set block(spacing: 1em)
align(top, [
#image("logos/tum_logo.svg", width: 25%)
#par(leading: .5em, text(
weight: "extralight", size: 26pt,
upper([School of Computation, \ Information and Technology -- \ Informatics])))
#text(weight: "light", size: 18pt, upper([Technische Universität München]))
])
set block(spacing: 2.5em)
set par(justify: false)
set text(size: 18pt, hyphenate: false)
body
}
#let cover-page(args) = {
show: info-front-style
[
#v(1em)
#{args.Degree + if args.lang == "en" ['s Thesis in Informatics] else [arbeit in Informatik]} \
#par(leading: .5em, text(weight: "medium", size: 26pt, args.title))
#args.author
#align(bottom, image("logos/tum_in_logo.svg", width: 20%))
]
// the scope of show: info-front-style i.e. it's body ends here because cover-page is not passed a body - just args
}
#let title-page(args, submission-info-content) = {
show: info-front-style
[
#v(0em)
#{args.Degree + if args.lang == "en" ['s Thesis in Informatics] else [arbeit in Informatik]} \
#par(leading: .5em, text(weight: "medium", size: 22pt, args.title))
#v(-1em)
#par(leading: .5em, text(weight: "medium", size: 22pt, args.translated-title))
]
submission-info-content
} |
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/lezer.typ | typst | #import "/components/glossary.typ": gls
== The Lezer Parser System
<sec-lezer>
Manually crafting a robust parser for a programming language is a complex and time-consuming endeavor. To efficiently construct a parser capable of providing syntax analysis for any language, while also supporting #gls("lsp") integration, several key requirements must be met @bib-php-parser:
- *Error Tolerance*: The parser should gracefully handle incomplete or invalid
code, producing a partial parse tree and relevant diagnostics.
- *Performance*: To ensure responsiveness, the parser must be able to parse
several megabytes of source code per second, leaving ample room for other
language server operations. The parser should exhibit low latency, allowing
for real-time feedback and responsiveness.
- *Memory Efficiency*: Optimized data structures are essential for handling
large codebases without excessive memory consumption.
- *Incremental Parsing*: The ability to update the parse tree incrementally
based on code changes is crucial for providing real-time feedback.
- *Rich CST*: The generated CST (@sec-cst) should accurately represent the
source code, including whitespace and comments, to facilitate semantic and
transformational operations.
- *Testability*: A well-defined test suite is essential to ensure parser
correctness and reliability.
- *Maintainability*: The parser's codebase should be clear, well-structured,
and easy to understand and modify.
- *Extensibility*: The parser should provide a flexible #gls("api") for
integration with other tools and components.
To expedite the parser development process while meeting these stringent requirements, we have chosen to leverage a parser generator, specifically Lezer. The following subsections will delve into the details of Lezer and its suitability for our project.
=== Overview
The challenge of parsing structured text has persisted for decades, with various solutions offering varying degrees of efficiency, flexibility, and ease of use. Lezer, a JavaScript-based parser generator, represents a contemporary approach to this problem.
Unlike traditional parser generators, Lezer produces compact parse tables that can be efficiently loaded and executed in the browser. This design choice prioritizes performance and memory efficiency, making it well-suited for web-based applications.
Lezer's core functionality revolves around generating parsers from grammar specifications. These grammars define the syntax rules of a language, and the generator produces the necessary code to parse text according to those rules. The resulting parser constructs a #gls("nast"), which represents the structure of the parsed text. This #gls("nast") can then be used for various language-aware operations, including syntax highlighting, code folding, and code completion @bib-lezer.
By focusing on performance, flexibility, and ease of use, Lezer offers a compelling solution for developers building language-aware applications.
=== Core Features
==== Grammar-Driven Parsing
Lezer adopts a grammar-driven approach, allowing developers to define language syntax declaratively. This high-level specification is then transformed into an efficient parser through the use of a parser generator. This approach promotes code readability, maintainability, and the ability to rapidly iterate on language definitions.
==== Incremental Parsing
Lezer is optimized for incremental parsing, enabling efficient updates to the parse tree when the underlying text is modified. By reusing existing parse tree nodes, Lezer minimizes the computational overhead associated with re-parsing entire documents. This feature is essential for providing real-time feedback to users as they edit code.
==== Error Tolerance
Lezer is designed to handle syntax errors gracefully. Rather than halting parsing upon encountering an error, it attempts to recover and produce a partial parse tree. This error-tolerant approach ensures that users can continue editing their code even in the presence of syntax mistakes.
==== Fast
By leveraging the #gls("lr", mode: "short") parsing algorithm, an efficient tokenizer, and carefully optimized data structures, Lezer achieves exceptional parsing speed. This enables real-time feedback and responsiveness, crucial for a seamless user experience.
==== Lightweight
Lezer's parser generator produces compact parse tables that are optimized for efficient execution. These parse tables, combined with a relatively small runtime library, can be easily included in web applications or other software distributions without incurring significant overhead. This lightweight nature is crucial for applications with limited resources, such as mobile devices or embedded systems.
By minimizing the size of the shipped code, Lezer helps to reduce load times and improve overall application performance.
==== Memory-Friendly
Lezer places a strong emphasis on memory efficiency by employing a compact syntax tree representation. To minimize memory footprint, the parser packs groups of related nodes together into 64-bit units. This approach allows for efficient storage and retrieval of syntactic information.
By adopting this memory-efficient design, Lezer enables the parsing of large codebases without compromising performance. This is particularly important for web-based applications where memory resources can be constrained.
=== Challenges of Using Lezer for LSP Integration
While Lezer offers a robust foundation for parsing and syntax highlighting, integrating it into a full-fledged #gls("lsp") implementation presents specific challenges.
==== NAST Limitations for Semantic Analysis
Lezer's #gls("nast", mode: "long") is optimized for efficient parsing and syntax highlighting. However, it may not be sufficiently expressive to support complex semantic analysis tasks required by #gls("lsp"). Features like "go to definition" or "find references" often demand a deeper understanding of the code's structure and meaning than what a #gls("nast") can provide.
==== Focus on Syntax Highlighting
Lezer's core strength lies in its ability to rapidly parse and highlight code syntax. While this is crucial for basic code editing, advanced language features like semantic analysis, type checking, and code refactoring necessitate additional tooling or extensions to the #gls("nast").
==== Parser Customization
Lezer's #gls("lr") parsing approach might require custom tokenization logic for certain languages. This can introduce complexity and increase development effort. Additionally, handling language-specific grammar nuances might necessitate modifications to the Lezer grammar specification.
|
|
https://github.com/DaAlbrecht/thesis-TEKO | https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Configuration_management.typ | typst | #import "@preview/tablex:0.0.5": tablex, cellx
The microservice uses environment variables to configure the behavior. The following variables are supported:
#figure(
table(
columns: (1fr, 1fr,auto),
rows: (auto),
align: (left,left, center + horizon),
[*Variable*],
[*Description*],
[*Default*],
[AMQP_CONNECTION_POOL_SIZE],
[The number of connections to the AMQP server.],
[5],
[AMQP_USERNAME],
[The username to use when connecting to the AMQP server.],
[guest],
[AMQP_PASSWORD],
[The password to use when connecting to the AMQP server.],
[guest],
[AMQP_HOST],
[The hostname of the AMQP server.],
[localhost],
[AMQP_PORT],
[The port of the AMQP server.],
[5672],
[AMQP_MANAGEMENT_PORT],
[The port of the AMQP management server.],
[15672],
[AMQP_TRANSACTION_HEADER],
[The name of the header that contains the transaction ID.],
[None],
[AMQP_ENABLE_TIMESTAMP],
[Whether the amqp messages have timestamps or not.],
[true],
[ENABLE_METRICS],
[Whether to enable metrics or not.],
[false],
),
kind: table,
caption: "Environment variables"
)
#pagebreak()
|
|
https://github.com/EgorGorshen/scripts-for-typst | https://raw.githubusercontent.com/EgorGorshen/scripts-for-typst/main/README.md | markdown | MIT License | # Scripts typst
Скрипты и настройки для ускорения работы на семинарах и лекциях
## Функционал
> `((numeric))` — матрица
- Работа с матрицами:
- `M(matrix)` — функция для отображения матриц в формате `math`
- `matT(matrix)` — транспанирование матрицы
- `rmatrix(n, m, mn: -20, mx: 20, rn: 122, tp: "int", fround: 2)` — генерация рандомной матрицы:
- `n:int`x`m:int` — размеры матрицы
- `mn:float` & `mx:float` — минимальное и максимально возможные значения
- `rn:int` — число для генирации рандомных чисел
- `tp:string` — `int` / `float`
- `fround:int` — до какого сисла округлять значения при `tp=float`
- `rmatI(n, m, rn)` — генерация рандомной матрицы размерами `n:int`x`m:int`
- `rmatF(n, m, rn, fr: 2)` — генерация `float` матрицы размерами `n:int`x`m:int`
- `matE(n)` — генерируеь единичную матрицу `n x n`
- `matMultAlpha(A, alpha)` — умножение матрицы `A` на число `alpha`
- `matSum(A, B)` — сумма матрицы `A` и `B`
- `matMinus(A, B)` — A - b
- `matMult(A, B)` — A * B
- `matDet(A)` — определитель матрицы
- `matT(A)` — транспанирование матрицы
- `matMinor(A)` — вычисление миинора матрицы
- `matMinus1Pow(A)` — вычисление -1 степени матрицы A
- `matPrintAsCases(matrix)` — выводит матрицу к виду системы урвнений
- `matTr(matrix)` — вычисляет след матрицы
- `matPow(matrix, pow)` — вычисляет степень матрицы (`pow >= -1`)
- Работа с таблицами истиности:
- `truthTable(fnStr)` — построение таблицы истиности в по функции записаный в виде строки(`#truthTable("(x, y, z) => {x and y = z}")`)
- Алгоритм Гауса:
- `gaussian_method_print(matrix, name:"A")` — расписывает алгоритм Гауса по этапно
- `gaussian_method_result(matrix, name:"A")` — возвращает результирующую матрицу
## TODO
- [ ] Написать документации для функций в коде
- [x] Написать функцию для красивого вывода матрицы в виде системы линейных уравнений
- [ ] Написать блоки для оформления:
- [ ] Домашних заданий
- [ ] Теорем
- [ ] Лем
- [ ] Доказательств
|
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/notebook.typ | typst | Creative Commons Attribution Share Alike 4.0 International | //Cover
#include "cover.typ"
//Table of Contents
#include "toc.typ"
//Intro Section
#include "entries/intro/about.typ"
#include "entries/intro/introductions.typ"
//Pre-building Entires
#include "entries/pre_building/spin_up_reflections.typ"
#include "entries/pre_building/name_reveal.typ"
#include "entries/pre_building/game_reaveal.typ"
#include "entries/pre_building/rules.typ"
//Summer Break
#include "entries/summer/cad.typ"
//Early Season
#include "entries/early_season/intro_meta.typ"
#include "entries/early_season/building_drive.typ"
#include "entries/early_season/trouble_shoot_drive.typ"
#include "entries/early_season/intake.typ"
#include "entries/early_season/drive_loctite.typ"
#include "entries/early_season/scrim.typ"
#include "entries/competitions/dulaney.typ"
// Mid Season
#include "entries/mid_season/cata_fix.typ"
#include "entries/mid_season/driver.typ"
#include "entries/competitions/hereford.typ" |
https://github.com/YDX-2147483647/typst-pointless-size | https://raw.githubusercontent.com/YDX-2147483647/typst-pointless-size/main/README.md | markdown | MIT License | # Typst Pointless Size——字号 zìhào
中文字号的号数制及字体度量单位。
Chinese size system (hào-system) and type-related measurements units.
```typst
#import "@preview/pointless-size:0.1.0": zh, zihao
#set text(size: zh(5)) // 五号(10.5pt)
// or
#set text(zh(5))
#show: zihao(5)
// 小号用负数表示 use negative numbers for small sizes
#zh(-4) // 小四(12pt)
#zh(1) // 一号(26pt)
#zh(-1) // 小一(24pt)
#zh("-0") // 小初(36pt)
#zh(0) // 初号(42pt)
```

<!--
#import "@preview/pointless-size:0.1.0": zh
#set page(width: auto, height: auto, margin: 1em)
#table(
columns: 3,
align: left + horizon,
stroke: none,
table.hline(),
[号数], [点数], [意义],
table.hline(stroke: 0.5pt),
..(
(0, "初号"),
("-0", "小初"),
..range(1, 9).map(n => (
(n, numbering("一号", n)),
..if n < 7 {
(-n, numbering("小一", n))
},
)),
).flatten().chunks(2).map(((n, t)) => (
raw("zh(" + repr(n) + ")", lang: "typst"),
[#zh(n)],
text(zh(n), t),
)).flatten(),
table.hline(),
)
-->
字号没有统一规定,本包默认与 CTeX、MS Word、WPS、Adobe 的中文规则一致。
Chinese size systems were not standardized. By default, this package is consistent with Chinese rules of CTeX, MS Word, WPS, Adobe.
如想覆盖定义:If you want to override:
```typst
#import "@preview/pointless-size:0.1.0": zh as _zh
#let zh = _zh.with(overrides: ((7, 5.25pt),))
#assert.eq(_zh(7), 5.5pt)
#assert.eq(zh(7), 5.25pt)
```
## 相关链接 Relevant links
> [!TIP]
>
> - ✅ = 一致 consistent
> - 👪 = 与描述的规则之一一致 consistent with one of the described rules
> - 🚸 = 不完全一致 not fully consistent
- 🚸[§2.3.5 基本版式设计的注意事项 - 中文排版需求 | W3C 编辑草稿](https://www.w3.org/International/clreq/#considerations_in_designing_type_area)(中/英)\[2024-09-13\]
> “号”由于当年金属活字各地厂家的规范不一而不尽相同……不作为规范性规定。
§2.3.5 Considerations when Designing the Type Area - Requirements for Chinese Text Layout | W3C Editor's Draft (Chinese & English)
> These hào-systems were not standardized by the various foundries in the past. …It is not normative information.
- ✅表25 中文字号 - [CTeX v2.5.0 (2022-07-14) 宏集手册 | CTAN](http://mirrors.ctan.org/language/chinese/ctex/ctex.pdf)(中文)
Table 25 Chinese text size - Documentation of the package CTeX v2.5.10 (2022-07-14) (Chinese)
https://github.com/CTeX-org/ctex-kit/blob/0fb196c42c56287403fecca6eb6b137c00167f40/ctex/ctex.dtx#L9974-L9993
- 👪[字体度量单位 - CJK Type Blog | Adobe](https://ccjktype.fonts.adobe.com/2009/04/post_1.html)(中/英)\[2009-04-02\] ([archive.today](https://archive.today/QxXuk))
Type-related Measurements Units (Chinese & English)
- ✅[如何转换字号、磅、px?- 技巧问答 | WPS学堂](https://www.wps.cn/learning/question/detail/id/2940)(中文)\[2020-05-07\]
How to convert between hào, point, and pixel? - Tech Q&A | WPS learning (Chinese)
- [#135 显明解行号号珍 - 字谈字畅 | The Type](https://www.thetype.com/typechat/ep-135/)(中文,带文字说明的播客)\[2020-09-09\] ([archive.today](https://archive.today/qaG8D))
(Chinese, podcast with show notes)
- [#543 ctexsize: 重设各级字号大小 - CTeX-org/ctex-kit | GitHub](https://github.com/CTeX-org/ctex-kit/issues/543)(中文)\[2020-10-13\]
#543 ctextsize: Redesign the font size system (Chinese)
- ✅[CY/T 154—2017 中文出版物夹用英文的编辑规范 - 行业标准 | 全国标准信息公共服务平台](https://std.samr.gov.cn/hb/search/stdHBDetailed?id=8B1827F23645BB19E05397BE0A0AB44A)(中文)\[2017-04-17\]
> 11.2.1 中文文本中夹用英文时,英文字号应与中文字号匹配。常用的为:中文“小五号”与英文“9P”相对应,中文“五号”与“10.5P”相对应。
- ✅[GB 40070–2021 儿童青少年学习用品近视防控卫生要求 - 国家标准 | 全国标准信息公共服务平台](https://std.samr.gov.cn/gb/search/gbDetailed?id=BBE32B661B7E8FC8E05397BE0A0AB906)(中文)\[2021-02-20\]
其中用到了号数制,例如4.3.1“小学一、二年级用字应不小于16P(3号)字”。总结下来是三号 16pt、四号 14pt、小四 12pt、五号 10.5pt、小五 9pt。
GB 40070–2021 Hygienic requirements of study products for myopia prevention and control in children and adolescents - National standards | National public service platform for standards information (Chinese)
The standard uses hào-system, e.g. 4.3.1 “texts for grade 1/2 of primary school should not be less than 16P (size 3)”. To summarize, size 3 = 16pt, size 4 = 14pt, size small 4 = 12pt, size 5 = 10.5pt, size small 5 = 9pt.
- 👪[字号(印刷)| 维基百科](https://zh.wikipedia.org/wiki/%E5%AD%97%E5%8F%B7_(%E5%8D%B0%E5%88%B7))(中文)
Hào (typography) | Wikipedia (Chinese)
|
https://github.com/Meisenheimer/Notes | https://raw.githubusercontent.com/Meisenheimer/Notes/main/main.typ | typst | MIT License | #import "@local/doc:1.0.0": *
#show: doc.with(
documentclass: "book",
title: "Handbook of Applied Mathematics",
language: "en",
show_outline: true,
subtitle: none,
authors: (
(
name: "<NAME>",
email: "<EMAIL>",
institude: none,
corresponding: true,
),
),
)
#part("Mathematical Foundation")
#include "src/Analysis.typ"
#include "src/Algebra.typ"
#include "src/ODE.typ"
#include "src/PDE.typ"
#include "src/Probability.typ"
#include "src/StochasticProcess.typ"
#include "src/Statistics.typ"
#include "src/Graph.typ"
#include "src/Combinatorics.typ"
#part("Scientific Computing")
#include "src/Interpolation.typ"
#include "src/Integration.typ"
#include "src/Optimization.typ"
#include "src/IVP.typ"
#include "src/NumberTheory.typ"
#part("Machine Learning")
#include "src/Regression.typ"
#include "src/DecisionTree.typ"
#include "src/SVM.typ"
#include "src/Cluster.typ"
#include "src/NeuralNetworks.typ"
|
https://github.com/Dav1com/minerva-report-fcfm | https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/lib/front.typ | typst | MIT No Attribution | #import "header.typ" as header
#import "footer.typ" as footer
#import "states.typ" as states
/// Crea un página y settea variables de estado requeridas
/// por otras funciones del template. Si buscas extender
/// el template con tu propia portada, es recomendado
/// pasarlo por esta función.
///
/// - it (content): Contenido de la portada.
/// - ..args (arguments): Argumentos a pasar a la función `page`
/// -> content
#let base(it, ..args) = {
return page(..args, {
states.is-main.update(true)
it
counter(page).update(0)
})
}
/// Diseño de portada básico, perfecto para informes y tareas.
///
/// - meta (dictionary): Contenidos del archivo **meta.typ**
/// - titulo-centrado (bool): Si es que el título debería ir centrado respecto
/// a la página. Por defecto `false`.
/// -> content
#let portada1(
meta,
titulo-centrado: false,
) = {
let miembros = (:)
if type(meta.autores) == "string" {
miembros.insert("Integrante", meta.autores)
} else if meta.autores.len() > 0 {
miembros.insert(
if meta.autores.len() == 1 {
"Integrante"
} else {
"Integrantes"
},
meta.autores
)
}
miembros = miembros + meta.equipo-docente
let header = header.base[
#grid(columns: (auto, 1fr), rows: auto)[
#set align(left + bottom)
#for nombre in meta.departamento.nombre [#nombre \ ]
][
#set align(right + bottom)
#if meta.departamento.logo != none {
let logo_raw = if type(meta.departamento.logo) == function {
meta.departamento.at("logo")()
} else {
meta.depatamento.logo
}
image.decode(logo_raw, height: 50pt)
}
]
#v(8pt)
#line(length: 100%, stroke: 0.4pt)
]
let member-table-args = ()
for (categoria, nombres) in miembros {
member-table-args.push[#categoria:]
member-table-args.push[
#if type(nombres) == array {
for nombre in nombres [#nombre \ ]
} else {
nombres
}
]
}
let titulo = align(center, {
set text(size: 25pt)
if meta.titulo != none {
meta.titulo
linebreak()
}
if meta.subtitulo != none {
meta.subtitulo
linebreak()
}
if meta.tema != none {
meta.tema
}
})
let member-table = grid(columns: (1fr, auto), rows: auto)[][
#grid(columns: 2, rows: auto, row-gutter: 10pt, column-gutter: 5pt, ..member-table-args)
#for (nombre, fecha) in meta.fechas [
Fecha de #nombre: #fecha \
]
#meta.lugar
];
let member-table-wrapper = {
if titulo-centrado {
(it) => place(bottom+right, align(top+left, it))
} else {
(it) => it
}
}
return base(header: header)[
#v(1fr)
#titulo
#v(1fr)
#member-table-wrapper(grid(columns: (1fr, auto), rows: auto, [], member-table))
]
}
/// Portada que contiene en una página el resumen y el outline.
///
/// - meta (dictionary, module): Contenidos del archivo **meta.typ**.
/// - espaciado (length): Espaciado entre los elementos principales de la portada.
/// - indice (boolean): Decide si incluir un índice.
/// -> content
#let portada-simple(
meta,
espaciado: 4cm,
indice: false
) = {
let meta = dictionary(meta)
let autores = if type(meta.autores) == array {
meta.autores.join(", ")
} else {
meta.autores
}
return base(margin: (x: 4cm), align(center + horizon)[
#set heading(numbering: none, outlined: false)
#set text(size: 13pt)
#let page-content(main-spacing) = stack(dir: ttb, spacing: main-spacing,
stack(dir: ttb, spacing: 2cm,
[
#text(size: 20pt)[*#meta.titulo*]
#set text(tracking: 1pt)
#meta.subtitulo
],
[
#stack(dir: ltr, spacing: 2cm, meta.tema, autores)
#if meta.at("url", default: none) != none {
link(meta.url)
}
]
),
..if meta.at("resumen", default: none) != none {
([
= Resumen
#meta.resumen],)
} else {
()
},
outline(depth: 2)
)
#layout(size => {
let desired = measure(page-content(espaciado))
if desired.height > size.height {
page-content(1fr)
} else {
page-content(espaciado)
}
})
])
}
/// Esta función permite obtener ayuda sobre cualquier función
/// del template. Para saber qué funciones y variables define
/// el template simplemente deja que el autocompletado te guíe,
/// luego puedes llamar esta función para obtener más ayuda.
///
/// - nombre (string): Puede ser el nombre de una función o
/// variable, entonces la función entrega
/// ayuda general sobre esta. Si se entrega
/// algo de la forma `"help(nombre)"` entonces
/// entrega ayuda específica sobre el argumento
/// `nombre`.
/// -> content
#let help(nombre) = {
import "../meta.typ": *
return help-leaf("front")(nombre)
}
|
https://github.com/augustebaum/tenrose | https://raw.githubusercontent.com/augustebaum/tenrose/main/examples/simplegraph.typ | typst | MIT License | #import "@preview/diagraph:0.2.2": *
#set heading(numbering: (..nums) => [Graph #numbering("1", ..nums):])
#let render-example(dot, ..args) = style(styles => {
let code = raw(dot.text, lang: "dot")
let graph = render(dot.text, ..args)
let side-by-side = measure(code, styles).width + measure(graph, styles).width < 20cm
let columns = if side-by-side { (auto, auto) } else { (auto,) }
grid(
columns: columns,
gutter: 1cm,
raw(dot.text, lang: "dot"),
render(dot.text, ..args),
)
})
= Test
#render-example(
```
digraph {
rankdir=LR;
f -> B
B -> f
C -> D
D -> B
E -> F
f -> E
B -> F
}
```
)
= Eating
#render-example(
```
digraph {
orange -> fruit
apple -> fruit
fruit -> food
carrot -> vegetable
vegetable -> food
food -> eat
eat -> survive
}
```
)
= FFT
Labels are overridden manually.
#render-example(
```
digraph {
node [shape=none]
1
2
3
r1
r2
r3
1->2
1->3
2->r1 [color=red]
3->r2 [color=red]
r1->r3 [color=red]
r2->r3 [color=red]
}
```,
labels: (
"1": $(1,0,0,0), i$,
"2": $(1,0), -1$,
"3": $(0,0), -1$,
r1: $(1,1)$,
r2: $(0,0)$,
r3: $(1,1,1,1)$,
)
)
= State Machine
#render-example(
```
digraph finite_state_machine {
rankdir=LR
size="8,5"
node [shape=doublecircle]
LR_0
LR_3
LR_4
LR_8
node [shape=circle]
LR_0 -> LR_2 [label="SS(B)"]
LR_0 -> LR_1 [label="SS(S)"]
LR_1 -> LR_3 [label="S($end)"]
LR_2 -> LR_6 [label="SS(b)"]
LR_2 -> LR_5 [label="SS(a)"]
LR_2 -> LR_4 [label="S(A)"]
LR_5 -> LR_7 [label="S(b)"]
LR_5 -> LR_5 [label="S(a)"]
LR_6 -> LR_6 [label="S(b)"]
LR_6 -> LR_5 [label="S(a)"]
LR_7 -> LR_8 [label="S(b)"]
LR_7 -> LR_5 [label="S(a)"]
LR_8 -> LR_6 [label="S(b)"]
LR_8 -> LR_5 [label="S(a)"]
}
```, labels: (
"LR_0": $"LR"_0$,
"LR_1": $"LR"_1$,
"LR_2": $"LR"_2$,
"LR_3": $"LR"_3$,
"LR_4": $"LR"_4$,
"LR_5": $"LR"_5$,
"LR_6": $"LR"_6$,
"LR_7": $"LR"_7$,
"LR_8": $"LR"_8$
)
)
= Clustering
See http://www.graphviz.org/content/cluster.
#render-example(
```
digraph G {
subgraph cluster_0 {
style=filled;
color=lightgrey;
node [style=filled,color=white];
a0 -> a1 -> a2 -> a3;
label = "process #1";
}
subgraph cluster_1 {
node [style=filled];
b0 -> b1 -> b2 -> b3;
label = "process #2";
color=blue
}
start -> a0;
start -> b0;
a1 -> b3;
b2 -> a3;
a3 -> a0;
a3 -> end;
b3 -> end;
start [shape=Mdiamond];
end [shape=Msquare];
}
```
)
= HTML
#render-example(
```
digraph structs {
node [shape=plaintext]
struct1 [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
<TR><TD>left</TD><TD PORT="f1">mid dle</TD><TD PORT="f2">right</TD></TR>
</TABLE>>];
struct2 [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
<TR><TD PORT="f0">one</TD><TD>two</TD></TR>
</TABLE>>];
struct3 [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4">
<TR>
<TD ROWSPAN="3">hello<BR/>world</TD>
<TD COLSPAN="3">b</TD>
<TD ROWSPAN="3">g</TD>
<TD ROWSPAN="3">h</TD>
</TR>
<TR>
<TD>c</TD><TD PORT="here">d</TD><TD>e</TD>
</TR>
<TR>
<TD COLSPAN="3">f</TD>
</TR>
</TABLE>>];
struct1:f1 -> struct2:f0;
struct1:f2 -> struct3:here;
}
```
)
= Overridden labels
Labels for nodes `big` and `sum` are overridden.
```dot
digraph {
rankdir=LR
node[shape=circle]
Hmm -> a_0
Hmm -> big
a_0 -> "a'" -> big [style="dashed"]
big -> sum
}
```
#raw-render(
```
digraph {
rankdir=LR
node[shape=circle]
Hmm -> a_0
Hmm -> big
a_0 -> "a'" -> big [style="dashed"]
big -> sum
}
```,
labels: (:
big: [_some_#text(2em)[ big ]*text*],
sum: $ sum_(i=0)^n 1/i $,
),
)
= Automatic math labels
#render-example(
```
digraph {
a -> alpha
phi -> rho
rho -> a
tau -> omega
phi -> a_8
a_8 -> alpha
a_8 -> omega
alpha_8 -> omega
}
```
) |
https://github.com/dogeystamp/typst-templates | https://raw.githubusercontent.com/dogeystamp/typst-templates/master/legacy/sfd.typ | typst | The Unlicense | // templates for online lecture notes
#import "../main.typ": gen_preamble, doc_template, mono_font, lref
#let template(
title: none,
authors: none,
lecture_url: none,
class: [Lecture notes],
body
) = {
doc_template(title: title, {
gen_preamble(
title: title,
authors: authors,
prefix: [_#{class}_],
suffix: link(lecture_url)
)
body
})
}
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/05-complex-functions/05-laurent-series.typ | typst | #import "../../utils/core.typ": *
== Ряды Лорана
#ticket[Ряд Лорана. Кольцо сходимости. Единственность.]
#def[
_Ряд Лорана_ --- ряд вида
$
sum_(n = -oo)^(oo) c_n (z - z_0)^n.
$
_Правильной частью_ ряда Лорана называется $sum_(n = 0)^oo c_n (z - z_0)^n$.
_Главной частью_ ряда Лорана называется $sum_(n = -oo)^(-1) c_n (z - z_0)^n = sum_(m = 1)^oo c_(-m) (z - z_0)^(-m)$.
Ряд _сходится_, если сходится его правильная и главная части.
Далее мы будем писать все ряды при $z_0 = 0$.
]
#props[
1. Существуют $0 <= r <= R <= +oo$ такие, что ряд Лорана $sum_(n = -oo)^oo c_n z^n$ сходится при $r < abs(z) < R$ и расходится при $abs(z) < r$ или $abs(z) > R$.
]
#proof[
1. $R$ --- радиус сходимости правильной части. Что с главной частью?
$ sum_(m = 1)^oo c_(-m) (1/z)^m = sum_(m = 1)^oo c_(-m) w^m. $
Это ряд, у которого есть радиус сходимости $tilde(R)$. Если $abs(w) < tilde(R)$, то ряд расходится, то есть если $abs(1/z) < tilde(R)$, или $abs(z) > 1/tilde(R)$. Аналогично, при $abs(w) > tilde(R)$ --- ряд расходится. $r = 1/tilde(R)$.
Возможно, $r$ получилось больше $R$. Тогда положим $r = R$, чтобы было верно неравенство из свойства.
]
#def[
Кольцо $r < abs(z) < R$ называется _кольцом сходимости_.
]
#props[
2. В кольце строго внутри кольца сходимости $tilde(r) < abs(z) < tilde(R)$ сходимость равномерная.
3. В кольце сходимости ряд можно дифференцировать сколь угодно много раз.
]
#proof[
2. Из свойств степенных рядов, если уменьшить круг сходимости немного, сходимость будет равномерной. Сделаем это с кругами из доказательства свойства 1.
3. Каждая точка строго внутри кольца лежит в каком-то уменьшенном кольце, а там есть бесконечная дифференцируемость.
]
#th(label: "loran-coefficient-formula")[
Если $f(z) = sum_(n = -oo)^oo c_n z^n$ при $r < abs(z) < R$, то коэффициенты определены однозначно. Замечу, что кольцо не пустое, так как какое-то значение $z$ в нем лежит.
Более того, есть формула для коэффициентов:
$
c_n = 1/(2pi i) integral_(abs(z) = rho) (f(z))/(z^(n + 1)) dif z,
$
где $rho$ --- любое значение $r < rho < R$: по всем окружностям значения интегралов будут совпадать как интегралы по гомотопным путям.
]
#proof[
Считаем интеграл.
$
integral_(abs(z) = rho) (f(z))/(z^(n + 1)) dif z.
$
Параметризуем $z = rho e^(i t)$, $dif z = rho e^(i t) dot i dif t$:
$
integral_0^(2pi) sum_(k = -oo)^oo overbrace(c_k rho^k e^(i k t), f(z)) 1/underbrace(rho^(n + 1) e^(i (n + 1) t), z^(n + 1)) i rho e^(i t) dif t =
i integral_0^(2pi) sum_(k = -oo)^(oo) c_k rho^(k - n) e^((k - n) i t) dif t newline(=^*) i sum_(k = -oo)^oo c_k rho^(k - n) integral_0^(2pi) e^(i (k - n) t) dif t.
$
Так как мы выбрали $rho$ строго внутри кольца, для любого $rho$ и у главной, и у правильной части есть равномерная сходимость, а значит в $*$ можно менять местами интеграл и сумму.
Чему равен здесь интеграл?
$
integral_0^(2pi) e^(i m t) dif t = cases(
2pi\, "при" m = 0,
lr(e^(i m t)/(i m) bar)_(t = 0)^(t = 2pi) = 0\, "при" m != 0.
)
$
Значит,
$
integral_(abs(z) = rho) (f(z))/(z^(n + 1)) dif z =
2pi i c_n.
$
То есть если коэффициенты есть, то любые коэффициенты выражаются через наш интеграл. Значит, они определены однозначно.
]
#ticket[Ряд Лорана. Существование. Разложение голоморфной в кольце функции в сумму голоморфных функций.]
#th(name: "Лорана")[
$f$ голоморфна в кольце $r < abs(z) < R$. Тогда она в этом кольце раскладывается в ряд Лорана, то есть
$
f(z) = sum_(n = -oo)^oo a_n z^n, "где"
a_n = 1/(2pi i) integral_(abs(z) = rho) f(z) / z^(n + 1) dif z.
$
]
#proof[
Возьмем $r < r_1 < r_2 < R_2 < R_1 < R$. Возьмем множество $r_1 <= abs(z) <= R_1$ --- компакт $K$, и точку в его внутренности, $r_2 < abs(z) < R_2$. Напишем по границе множества интегральную формулу Коши:
$
f(z) = 1/(2 pi i) integral_(diff K) f(zeta) / (zeta - z) dif zeta = 1/(2 pi i) integral_(abs(zeta) = R_1) f(zeta) / (zeta - z) dif zeta - 1/(2pi i) integral_(abs(zeta) = r_1) f(zeta) / (zeta - z) dif zeta.
$
Считаем по отдельности интегралы, начнем с первого. Распишем знаменатель как ряд:
$
1/(zeta - z) = 1/zeta dot 1/(1 - z/zeta) = 1/zeta sum_(n = 0)^oo (z/zeta)^n = sum_(n = 0)^oo z^n / (zeta^(n + 1)).
$
Тогда
$
integral_(abs(zeta) = R_1) f(zeta) / (zeta - z) dif zeta =
integral_(abs(zeta) = R_1) f(zeta) dot (sum_(n = 0)^oo z^n/(zeta^(n + 1))) dif z =^*
sum_(n = 0)^oo z^n underbrace(integral_(abs(zeta) = R_1) f(zeta)/(zeta^(n + 1)) dif z, := c_n) =
sum_(n = 0)^oo c_n z^n.
$
Как обычно, надо объяснить, почему можно переставлять в $*$ сумму с интегралом. Докажем равномерную сходимость. $f in H(r < abs(z) < R)$, значит $f in C(r_1 <= abs(z) <= R_1)$, то есть $f$ ограничена в кольце. $r_1 < r_2 < abs(z) < R_2 < R_1$, значит $abs(f(zeta)) <= M$ для каждого $zeta$. Тогда
$
abs(f(zeta)) abs(z)^n / (abs(zeta)^(n + 1)) <= M 1/R_1 (R_2 / R_1)^n,
$
а это сходящая геометрическая прогрессия. По признаку Вейерштрасса, сходится.
Теперь другой интеграл. Здесь, чтобы была сходимость, уже нужно писать ряд по $zeta/z$:
$
1/(zeta - z) = -1/z dot 1/(1 - zeta/z) = - 1/z sum_(n = 0)^oo zeta^n / z^n = -sum_(n = 1)^oo zeta^(n - 1)/z^n.
$
Аналогично считаем интеграл, меняем его местами с суммой по аналогичным причинам.
$
integral_(abs(zeta) = r_1) f(zeta)/(zeta - z) dif zeta = integral_(abs(zeta) = r_1) -f(zeta) sum_(n = 1)^oo zeta^(n - 1)/z^n dif zeta = sum_(n = 1)^oo 1/(z^n) underbrace(integral_(abs(zeta) = r_1) -f(zeta) zeta^(n - 1) dif zeta, -c_(-n)).
$
Получаем разложение в ряд.
]
#notice[
Неравенство Коши верно для $n in ZZ$:
$
abs(a_n) <= M_rho / rho^n, "где" M_rho = max_(abs(zeta) = rho)abs(f(zeta)).
$
]
#follow[
Если $f$ голоморфна в кольце $r < abs(z) < R$, то существует $g in H(abs(z) < R)$ и $h in H(abs(z) > r)$ такие, что $f = g + h$. Если $lim_(z -> oo) h(z) = 0$, то разложение единственно.
]
#proof[
Пусть
$
g(z) = sum_(n = 0)^oo a_n z^n, \
h(z) = sum_(n = 1)^oo a_(-n) z^(-n).
$
Тогда $g$ сходится в кольце $r < abs(z) < R$, а значит и в $abs(z) < R$ (нет проблем со сходимостью около нуля), а значит $g in H(abs(z) < R)$. Тоже самое для $h$: она сходится при $abs(z) > r$, а значит голоморфна при $abs(z) > r$.
Проверим единственность.
Пусть $f = g + h = g_1 + h_1$, и $g, g_1 in H(abs(z) < R)$, и $h, h_1 in H(abs(z) > r)$. Тогда рассмотрим
$
F(z) := cases(
g(z) - g_1 (z) "при" abs(z) < R,
h(z) - h_1 (z) "при" abs(z) > r
) in H(CC).
$
Голоморфность следует из того, что голоморфны обе части в своих областях, и они совпадают в кольце. Значит $F$ является аналитическим продолжением каждой из функций. Кроме того, по условию, $F(z) --> 0$ при $z -> oo$. Значит эта функция меньше $1$ для всякого $abs(z) > A$, и ограничена при $abs(z) <= A$. Значит она ограничена везде, и по теореме Лиувилля, $F$ --- константа. Но $F$ стремится к нулю при $z -> oo$, значит $F = 0$.
]
#ticket[Особые точки голоморфных функций. Равносильные определения устранимой особой точки.]
#def[
Если $f in H(0 < abs(z - a) < R)$, то $a$ называется _изолированной особой точкой_ функции $f$. Иными словами, функция не определена в точке $a$, но определена и голоморфна в некоторой окрестности этой точки.
]
#def[
Определим бесконечные пределы: $ lim_(z -> a) f(z) = oo $ означает, что $abs(f(z)) -->_(z -> a) +oo$.
]
#notice[
$ lim_(z -> a) f(z) = oo <==> lim_(z -> a) 1/(f(z)) = 0 $
]
#def[
Пусть $a$ --- изолированная особая точка.
- Если существует $lim_(z -> a) f(z) in CC$, то такая точка называется _устранимой особой точкой_.
- Если $lim_(z -> a) f(z) = oo$, то такая точка называется _полюсом_.
- Если не существует $lim_(z -> a) f(z)$, то такая точка называется _существенной особой точкой_.
]
#examples[
+ $f(z) = (sin z)/z$ имеет устранимую особую точку в нуле, так как при $z = 0$ предел равен $1$.
+ $f(z) = (e^z - 1)/z$ то же самое.
+ $f(z) = (cos z)/z$ имеет полюс в нуле.
+ $f(z) = tg(z)$ имеет полюсы в точках $pi/2 + pi n$.
+ $f(z) = e^(1/z)$ имеет существенную особую точку в нуле, так как если $z_n = 1/(2pi i n)$, то $f(z_n) = e^(2pi i n) = 1$, а если $z_n = 1/(2pi i n + pi i)$, то $f(z_n) = e^(2pi i n + pi i) = -1$.
]
#th(name: "характеристика устранимой особой точки")[
$f = H(0 < abs(z - a) < R)$. Следующие условия равносильны:
1. $a$ --- устранимая особая точка.
2. $f$ ограничена в проколотой окрестности $a$.
3. Существует $g in H(abs(z - a) < R)$ такая, что $f(z) = g(z)$ при $0 < abs(z - a) < R$.
4. В главной части разложения Лорана $f$ в окрестности $a$ все коэффициенты равны нулю.
]
#proof[
- "$1 ==> 2$": если существует предел, то есть локальная ограниченность.
- "$4 ==> 3$": если в главной части ряда Лорана все коэффициенты нулевые, то возьмем все остальное в качестве $g$. Такая $g$ подходит.
- "$3 ==> 1$": $lim_(z -> a) f(z) = lim_(z -> a) g(z) = g(a)$.
- "$2 ==> 4$": Пусть $abs(f(z)) <= M$ при $0 < abs(z - a) < r$. Тогда для коэффициентов главной части ряда Лорана: $|c_n| <= M_rho / rho^n <= M/rho^n --> 0$ при $rho -> 0$, где $M_rho = max abs(f(z)) < M$ при $abs(z - a) = rho$ (по формуле коэффициентов#rf("loran-coefficient-formula")).
]
#ticket[Характеристика полюса. Связь между нулями и полюсами.]
#th(name: "характеристика полюса")[
$f in H(0 < abs(z - a) < R)$. Следующие условия равносильны:
1. $a$ --- полюс.
2. Существует $m in NN$ и $g in H(abs(z - a) < R)$, такая, что $g(a) != 0$ и $f(z) = g(z) / (z - a)^m$ при $0 < abs(z - a) < R$.
3. В главной части ряда Лорана (в кольце $0 < abs(z - a) < R$) $f$ есть только конечное *ненулевое* (иначе устранимо) число ненулевых коэффициентов.
]
#proof[
- "$1 ==> 2$": Заведем $h(z) = 1/(f(z))$. Тогда $lim_(z -> a) f(z) = oo$, а значит $abs(f(z)) > 1$ в некоторой окрестности $a$, и для $h(z)$ это устранимая особая точка (в ней предел $0$). Доопределим эту функцию в точке $a$. Такая $h$ голоморфна в окрестности $a$, и равна нулю в точке. Можем вынести из нее множитель $(z - a)^m$, тогда
$
h(z) = (z - a)^m dot tilde(h) (z), " где" tilde(h) in H(abs(z - a) < r) "и " tilde(h)(a) != 0.
$
Ну а $f$, соответственно, равна $1/h$:
$
f(z) = 1/(z - a)^m dot 1/(tilde(h)(z)).
$
Берем $g(z) = 1/(tilde(h) (z))$ в окрестности $a$. Правда, эта функция пока определена при $abs(z - a) < r$. Давайте доопределим:
$
g(z) = cases(
1/(tilde(h) (a)) "при" z = a,
(z - a)^m f(z) "при" z != a
).
$
Она голоморфна, так как точка $a$ --- устранимая особая точка $(z - a)^m f(z)$.
- "$2 ==> 3$": Возьмем ряд Тейлора голоморфной в круге функции $g$ в точке $a$:
$
g(z) = sum_(n = 0)^oo c_n (z - a)^n.
$
Тогда
$
f(z) = g(z) / (z - a)^m = sum_(n = -m)^oo c_(n + m) (z - a)^n.
$
В этом ряду действительно конечное ненулевое число ненулевых коэффициентов в главной части.
- "$3 ==> 1$": $f(z) = sum_(n = -m)^oo c_n (z - a)^n$ и $c_(-m) != 0$. Значит $f(z) sim c_(-m)/(z - a)^m$.
]
#def[
$m$ из этой теоремы называется _порядком полюса_.
]
#notice[
В процессе доказательства поняли равносильность:
1. $a$ --- полюс $f$ порядка $m$.
2. $a$ --- нуль $1/f$ кратности $m$.
3. $f(z) = sum_(n = -m)^oo c_n (z - a)^n$ и $c_m != 0$.
]
#ticket[Мероморфные функции. Свойства. Производные мероморфных функций. Характеристика существенной особой точки.]
#def[
$f$ --- _мероморфная_ в $Omega$ функция, если $f in H(Omega without E)$, а $E$ --- множество всех полюсов $f$. Устранимые особые точки тоже годятся: их можно сразу устранить.
]
#notice[
Рассмотрим ситуацию, когда у множества $E$ нет предельных точек в $Omega$. Пусть $a_n$ --- полюсы $a_n in E$, и $lim a_n = a in Omega$. Тогда ни в каком кольце $0 < abs(z - a) < R$ не может быть голоморфности. Значит $a$ --- не изолированная особая точка, и тем более не полюс: иначе в окрестности $a$ не могло бы быть полюсов. С другой стороны, в точке $a$ и голоморфности быть не может, так как
$
lim_(z -> a_n) f(z) = oo ==> exists z_n in U_(a_n): abs(f(z_n)) > n ==> z_n --> a "и " abs(f(z_n)) --> +oo.
$
Получается предел --- не полюс, и не точка голоморфности. Значит эта точка не лежит в $Omega$, и не является предельной.
]
#example[
$ctg 1/z$ мероморфная в $CC without {0}$, но не мероморфная в $CC$.
]
#th[
$f$, $g$ мероморфны в $Omega$. Тогда
1. $f plus.minus g$ мероморфна в $Omega$.
2. $f g$ мероморфна в $Omega$.
3. $f/g$ мероморфна в $Omega$, если $g equiv.not 0$.
4. $f'$ мероморфна в $Omega$.
]
#proof[
1.
$
f(z) + g(z) = sum_(n = -m_1)^oo c_n (z - a)^n + sum_(n = -m_2)^oo d_n (z - a)^n.
$
Это ряд такого же вида, поэтому $f + g$ мероморфна.
2. Если $f$ и $g$ голоморфны в $a$, то $f g$ голоморфна в $a$. Только в таких точках $f(a) = 0$ или $g(a) = 0$. В остальных точках распишем (такое представление существует)
$
f(z) = (z - a)^(-m) phi(z),\
g(z) = (z - a)^(-l) psi(z).
$
Тогда
$
f(z) g(z) = (z - a)^(-(m + l)) phi(z) psi(z).
$
3. Аналогично,
$
f(z) / g(z) = (z - a)^(-(m - l)) phi(z)/(psi(z)).
$
Если нули $g$ имеют предельную точку, то $g equiv 0$ по теореме о единственности, а такие функции не рассматриваются.
4. Если $f$ голоморфна в окрестности $a$, то $f'$ тоже голоморфна в окрестности $a$. Если $a$ --- полюс, то
$
f'(z) = (-m phi(z) + phi'(z) (z - a))/(z - a)^(-m + 1).
$
Полюс не исчезает.
]
#th(name: "характеристика существенной особой точки")[
$f in H(0 < abs(z - a) < R)$. Следующие условия равносильны:
1. $a$ --- существенная особая точка.
2. В главной части ряда Лорана $f$ в окрестности $a$ бесконечно много ненулевых коэффициентов.
]
#proof[
Получается по принципу исключения: по двум предыдущим теоремам ничего больше не остается.
]
#ticket[Теорема Сохоцкого. Формулировка теоремы Пикара.]
#th(name: "Сохоцкого")[
Пусть $a$ --- существенная особая точка $f$ и $eps > 0$. Тогда $ Cl {f(z): 0 < abs(z - a) < eps} = CC union {oo}. $
Более того, для любого $A in CC union {oo}$ найдется такая последовательность $z_a -> a$, что $f(z_n) -> A$.
]
#proof[
1. Случай $A = oo$.
Если $f$ ограничена в окрестности $a$, то по характеристике устранимой особой точки, $a$ --- устранимая. А это не так. Значит в любой окрестности $a$, $f$ не ограничена, и найдется $z_n: abs(z_n - a) < 1/n$ такая, что $abs(f(z_n)) > n$.
2. Случай $A in CC$.
Если в каждой окрестности $0 < abs(z - a) < 1/n$ функция $f$ принимает значение $A$, то возьмем последовательность таких точек.
Если в некоторой окрестности $0 < abs(z - a) < eps$ значение $A$ не достигается, то рассмотрим $g(z) = 1/(f(z) - A)$. В такой проколотой окрестности эта функция голоморфна --- в ней не обнуляется знаменатель. Значит $a$ --- изолированная особая точка $g$. Рассмотрим случаи:
- $a$ --- устранимая. Тогда существует $lim_(z -> a) g(z) = b in CC$ и $lim_(z -> a) f(z) = lim_(z -> a) 1/(g(z)) + A$. Это либо бесконечность (если $b = 0$), либо комплексное число (если $b != 0$). Но такого быть не может: тогда $a$ --- либо устранимая особая точка, либо полюс $f$, но она должна быть существенной.
- $a$ --- полюс $g$. Тогда $lim_(z -> a) g(z) = oo$ и $lim_(z -> a) f(z) = 1/oo + A = 0 + A = A$. Значит это устранимая особая точка, а не существенная. Снова противоречие.
- $a$ --- существенная особая точка $g$. Тогда существует последовательность $g(z_n) -> oo$ по предыдущему пункту. А значит $f(z_n) = 1/(g(z_n)) + A --> A$.
]
#th(name: "Пикара")[
Если $a$ --- существенная особая точка и $eps > 0$, то множество ${f(z): 0 < abs(z - a) < eps}$ это либо $CC$, либо $CC$ без одной точки.
]
#proof[
Храбров сказал, что на доказательство уйдет пара или две, и мы доказывать ее не будем. Еще он сказал, что эту теорему иногда называют "большой теоремой Пикара", так как у нее есть ослабленный аналог, на доказательство которого уйдет всего лишь одна пара. Оно вам надо?
]
#example[
Одно значение может отсутствовать. Например, при $f(z) = e^(1/z)$, $z = 0$ --- существенная особая точка, но экспонента не принимает значение $0$ никогда.
]
#ticket[Бесконечный предел и бесконечно удаленная точка. Особенность в бесконечно удаленной точке. Теорема Лиувилля в $overline(CC)$.]
#def[
Предел в точке $oo$:
$ lim_(z -> oo) f(z) = b $
если
$
forall eps > 0 space exists R space forall abs(z) > R space abs(f(z) - b) < eps
$
или
$
forall z_n -> oo space f(z_n) -> b.
$
]
#denote[
$overline(CC) = CC union {oo}$.
]
#def[
Пусть $f: Omega --> CC$, где $Omega subset overline(CC)$. Тогда если $lim_(z -> oo) f(z) = f(oo)$, то $f$ непрерывна в $oo$.
]
#def[
Пусть $f in H(abs(z) > R)$ ($f$ голоморфна в проколотой окрестности бесконечности).
1. Если существует $lim_(z -> oo) f(z) in CC$, то $oo$ --- устранимая особая точка.
2. Если $lim_(z -> oo) f(z) = oo$, то $oo$ --- полюс.
3. Если не существует $lim_(z -> oo) f(z)$, то $oo$ --- существенная особая точка.
]
#notice[
Можно смотреть на это в терминах функции от обратного аргумента.
1. $oo$ --- устранимая особая точка $f$ тогда и только тогда, когда $0$ --- устранимая особая точка $f(1/z)$, что равносильно тому, что $f(z)$ ограничена в окрестности $oo$, что равносильно тому, что в разложении $f$ в ряд Лорана по степеням $z$ при положительных степенях все коэффициенты равны нулю.
2. $oo$ --- полюс $f$ тогда и только тогда, когда $0$ --- полюс $f(1/z)$, что равносильно тому, что в разложении $f$ в ряд Лорана по степеням $z$ при положительных степенях есть конечное ненулевое число ненулевых коэффициентов.
3. $oo$ --- существенная особая точка $f$ тогда и только тогда, когда $0$ --- существенная особая точка $f(1/z)$, что равносильно тому, что в разложении $f$ в ряд Лорана по степеням $z$ при положительных степенях бесконечно много ненулевых коэффициентов.
]
#def[
$f$ --- голоморфная в $oo$, если $oo$ --- устранимая особая точка $f$.
]
#th(name: "Лиувилля")[
Если $f in H(overline(CC))$, то $f = const$.
]
#proof[
$f$ --- голоморфна в $oo$, значит существует $lim_(z -> oo) f(z) =: b$. Тогда существует $R$ такое, что $abs(f(z) - b) < 1$ при $abs(z) > R$, в частности $abs(f(z)) < abs(b) + 1$ при $abs(z) > R$. В круге $abs(z) <= R$ функция ограничена как непрерывная на компакте. Значит, она ограничена везде, и по теореме Лиувилля, $f = const$.
]
#ticket[<NAME>. Стереографическая проекция. Связь между расстояниями образов и прообразов.]
#def[
_Стереографическая проекция_ --- отображение точек на плоскости точкам на сфере. Точке бесконечности соответствует северный полюс сферы.
Северный полюс расположен в $N = (0, 0, 1)$, и рассматривается точка на плоскости $(x, y, 0)$. Южный полюс сферы лежит на плоскости в точке $(0, 0, 0)$.
#figure[
#image("../../images/riemann-sphere.svg", width: 10cm)
]
Такая сфера называется _сферой Римана_.
]
#th[
При стереографической проекции точке плоскости $z = x + i y$ соответствует точка на сфере с координатами
$
u = x/(1 + abs(z)^2), space
v = y/(1 + abs(z)^2), space
w = (abs(z)^2)/(1 + abs(z)^2).
$
Обратное отображение:
$
x = u/(1 - w), space
y = v/(1 - w).
$
]
#proof[
Параметризуем прямую $N z$: $(t x, t y, 1 - t)$. Уравнение сферы $u^2 + v^2 + (w - 1/2)^2 = 1/4$, то есть $u^2 + v^2 + w^2 = w$. Подставляем параметризацию прямой:
$
t^2 x^2 + t^2 y^2 + (1 - t)^2 = (1 - t) <==>
t^2 abs(z)^2 + cancel(1) - cancel(2)t + t^2 = cancel(1) - cancel(t) newline(<==>)
t dot abs(z)^2 - 1 + t = 0 ==> t = 1/(1 + abs(z)^2).
$
Подставляем $t$ в параметризацию, получаем что требовалось. Обратное отображение выводится.
]
#follow(plural: true)[
1. Расстояние между образами точек $z$ и $tilde(z)$ равно
$
abs(z - tilde(z))/(sqrt(1 + abs(z)^2) sqrt(1 + abs(tilde(z))^2)).
$
2. Расстояние между образом $z$ и $oo$ равно
$
1/(sqrt(1 + abs(z)^2)).
$
]
#proof[
1. $
(u - tilde(u))^2 + (v - tilde(v))^2 + (w - tilde(w))^2 =
underbrace(u^2 + v^2 + w^2, =w) +
underbrace(tilde(u)^2 + tilde(v)^2 + tilde(w)^2, =tilde(w)) -
2(u tilde(u) + v tilde(v) + w tilde(w)) newline(=)
abs(z)^2/(1 + abs(z)^2) +
abs(tilde(z))^2/(1 + abs(tilde(z))^2)
-
2 dot (x tilde(x) + y tilde(y) + abs(z)^2 abs(tilde(z))^2)/((1 + abs(z)^2)(1 + abs(tilde(z))^2))
=
(abs(z)^2 + abs(tilde(z))^2 + 2abs(z)^2 abs(tilde(z))^2)/((1 + abs(z)^2)(1 + abs(tilde(z))^2))
-
2 dot (x tilde(x) + y tilde(y) + abs(z)^2 abs(tilde(z))^2)/((1 + abs(z)^2)(1 + abs(tilde(z))^2))
newline(=)
(abs(z)^2 + abs(tilde(z))^2 - 2x tilde(x) - 2 y tilde(y))/((1 + abs(z)^2)(1 + abs(tilde(z))^2)) =
((x - tilde(x))^2 + (y - tilde(y))^2)/((1 + abs(z)^2) (1 + abs(tilde(z))^2)) =
abs(z - tilde(z))^2/((1 + abs(z)^2) (1 + abs(tilde(z))^2)).
$
2. Упражнение.
]
#follow(plural: true)[
3. Предел в $overline(CC)$ и предел на сфере Римана --- одно и тоже, то есть $z_n --> z_*$ в $overline(CC)$ тогда и только тогда, когда образы $z_n$ сходятся к образу $z_*$ в $RR^3$ (не обязательно считать расстояния по дуге на сфере).
]
#proof[
- "$==>$", $z_n --> z_* in CC$: Тогда $abs(z_n - z_*) --> 0$, а значит
$
abs(z_n - z_*)/(sqrt(1 + abs(z_n)^2) sqrt(1 + abs(z_*)^2)) < abs(z_n - z_*) --> 0.
$
- "$<==$":
$
(z_n - z_*)/(sqrt(1 + abs(z_n)^2) sqrt(1 + abs(z_*)^2)) --> 0 ==> abs(z_n - z_*)/sqrt(1 + abs(z_n)^2) --> 0.
$
Если $z_n$ --- ограничена, то $abs(z_n - z_*) --> 0$, и все доказано. Если $z_n$ не ограничена, то найдется $z_(n_k) --> oo$, и дробь
$
abs(z_(n_k) - z_*)/sqrt(1 + abs(z_(n_k))^2) --> 1,
$
что противоречит предположению: она должна стремиться к нулю.
- $z_n --> oo$: сразу получается в обе стороны, так как
$
1/(sqrt(1 + abs(z_n)^2)) --> 0.
$
]
#follow(plural: true)[
4. $overline(CC)$ --- компакт (!). Надо только быть осторожным с тем, где именно. Метрики в $overline(CC)$ у нас нет (они не захватывают бесконечность), поэтому говорить надо о топологических пространствах. Короче, забейте, компакт и компакт. Вопросы?
]
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10500.typ | typst | Apache License 2.0 | #let data = (
("ELBASAN LETTER A", "Lo", 0),
("ELBASAN LETTER BE", "Lo", 0),
("ELBASAN LETTER CE", "Lo", 0),
("ELBASAN LETTER CHE", "Lo", 0),
("ELBASAN LETTER DE", "Lo", 0),
("ELBASAN LETTER NDE", "Lo", 0),
("ELBASAN LETTER DHE", "Lo", 0),
("ELBASAN LETTER EI", "Lo", 0),
("ELBASAN LETTER E", "Lo", 0),
("ELBASAN LETTER FE", "Lo", 0),
("ELBASAN LETTER GE", "Lo", 0),
("ELBASAN LETTER GJE", "Lo", 0),
("ELBASAN LETTER HE", "Lo", 0),
("ELBASAN LETTER I", "Lo", 0),
("ELBASAN LETTER JE", "Lo", 0),
("ELBASAN LETTER KE", "Lo", 0),
("ELBASAN LETTER LE", "Lo", 0),
("ELBASAN LETTER LLE", "Lo", 0),
("ELBASAN LETTER ME", "Lo", 0),
("ELBASAN LETTER NE", "Lo", 0),
("ELBASAN LETTER NA", "Lo", 0),
("ELBASAN LETTER NJE", "Lo", 0),
("ELBASAN LETTER O", "Lo", 0),
("ELBASAN LETTER PE", "Lo", 0),
("ELBASAN LETTER QE", "Lo", 0),
("ELBASAN LETTER RE", "Lo", 0),
("ELBASAN LETTER RRE", "Lo", 0),
("ELBASAN LETTER SE", "Lo", 0),
("ELBASAN LETTER SHE", "Lo", 0),
("ELBASAN LETTER TE", "Lo", 0),
("ELBASAN LETTER THE", "Lo", 0),
("ELBASAN LETTER U", "Lo", 0),
("ELBASAN LETTER VE", "Lo", 0),
("ELBASAN LETTER XE", "Lo", 0),
("ELBASAN LETTER Y", "Lo", 0),
("ELBASAN LETTER ZE", "Lo", 0),
("ELBASAN LETTER ZHE", "Lo", 0),
("ELBASAN LETTER GHE", "Lo", 0),
("ELBASAN LETTER GHAMMA", "Lo", 0),
("ELBASAN LETTER KHE", "Lo", 0),
)
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/rules.typ | typst | The Unlicense | #import "./format.typ"
#import "./colors.typ": *
#import "/utils.typ"
#let rules = utils.make-rules(doc => {
set text(font: ("Calibri", "Carlito"), size: 11pt)
set page("us-letter")
set footnote.entry(separator: none)
// Enforce the correct font on Excalidraw drawings
show image: it => [
#align(center)[
#set text(font: "Virgil 3 YOFF")
#it
]
]
show link: it => [
#text(
fill: blue,
[ _ #it _ ],
)
]
show figure: it => align(center)[
#it.body
#if it.caption != none [
_ #it.caption.body _
]
]
set raw(theme: "./radial.tmTheme")
show raw.where(block: false): format.raw-not-block
show raw.where(block: true): it => format.raw-block(it)
show heading: format.heading
//show table: format.table
// Display the whole document
doc
})
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/tracking-spacing_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test tracking.
#set text(tracking: -0.01em)
I saw Zoe yӛsterday, on the tram.
|
https://github.com/CaldeCrack/Typst-Templates | https://raw.githubusercontent.com/CaldeCrack/Typst-Templates/main/template.typ | typst | // Generic Typst template for university projects
/* Usage
#import "<path>/template.typ": *
#show: project.with(
title: "title",
subtitle: "subtitle",
author: ("First Member", "Second Member"),
prof: ("Professor", ),
aux: ("Auxiliar", ),
signature: "Course",
numbering: "a.1."
*/
// Generic Typst template for university projects
#let project(title: "", subtitle: "", author: (), prof: (), aux: (), signature: "", numbering: "1.1.", font: "Linux Libertine", body) = {
// Document's basic properties
set document(author: author, title: title)
set page(
margin: (left: 25mm, right: 25mm, top: 20mm, bottom: 15mm),
numbering: "- 1 -",
number-align: center,
header-ascent: 30%,
header: align(left)[
Facultad de Ciencias Físicas y Matemáticas #h(1fr) Universidad de Chile #line(start: (0pt, -8pt), end: (454pt, -8pt))
],
)
set text(font: font, lang: "es")
v(8mm)
// Singular | plural
let prof_text = "Profesor"
let aux_text = "Auxiliar"
let student_text = "Estudiante"
if prof.len() > 1 {prof_text += "es"}
if aux.len() > 1 {aux_text += "es"}
if author.len() > 1 {student_text += "s"}
// Sub header
align(left)[
#v(-2.4em)
*#signature* \
*#prof_text:* #prof.join(", ", last: " y ") \
#if aux.len() > 0 [*#aux_text:* #aux.join(", ", last: " y ") #linebreak()]
*#student_text:* #author.join(", ", last: " y ")
]
// Logo
place(
top + right,
image("dcc.png", width: 22%),
dy: -0.9%
)
// Title row
align(center)[
#v(0.8em)
#block(text(weight: 700, 1.75em, title))
#v(0.75em, weak: true)
#subtitle
]
// Main body
set heading(numbering: "P1.1.")
set enum(numbering: numbering)
set par(justify: true)
body
}
|
|
https://github.com/htlwienwest/da-vorlage-typst | https://raw.githubusercontent.com/htlwienwest/da-vorlage-typst/main/lib/pages/dokumentation.typ | typst | MIT License | #import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx, cellx
#import table: cell
#let dokumentation(persons: ()) = [
= Dokumentation der Diplomarbeit
#set text(11pt)
#set par(leading: 7pt)
#let std_space = 7mm
#let left_col = 6cm
#table(
columns: (left_col, 1fr),
[Verfasser], v(std_space),
[Jahrgang], v(std_space),
[Thema], v(std_space),
[Kooperationspartner], v(std_space),
)
#let nested_table(right) = {
cell(
inset: 0pt,
table(
columns: (3cm, 1fr),
[Datum: #v(std_space+5mm)], right
),
)
}
#table(
columns: (left_col, 1fr),
[Aufgabenstellung], v(std_space),
[Realisierung], v(std_space),
[Ergebnisse], v(std_space+5cm),
[Teilname an Wettbewerben], v(std_space),
[Möglichkeiten der Einsichtnahme\ der Arbeit], v(std_space+6mm),
[Abgabevermerk], nested_table[Übernommen von:],
[Approbation], nested_table[Prüfer:],
[], nested_table[Abteiluntsvorstand:]
)
]
|
https://github.com/lsacienne/UTBM-Internship-Report-Typst | https://raw.githubusercontent.com/lsacienne/UTBM-Internship-Report-Typst/main/example/test.typ | typst | MIT License | #import "../utbm.typ": cover, fourth-cover
#cover()
#fourth-cover()[#lorem(248)] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.8.0/lib/lib.typ | typst | Apache License 2.0 | #import "clues.typ": *
#import "predefined.typ": * |
https://github.com/adeshkadambi/ut-thesis-typst | https://raw.githubusercontent.com/adeshkadambi/ut-thesis-typst/main/0-abbrev.typ | typst | MIT License | #set terms(spacing: 2em, separator: h(1em, weak: true))
/ ADLs: Activities of Daily Living
/ SCI: Spinal Cord Injury |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cuti/0.1.0/demo-and-doc/demo-and-doc-cn.typ | typst | Apache License 2.0 | #import "../lib.typ": *
#import "@preview/sourcerer:0.2.1": code
#set par(justify: true)
#show heading: show-cn-fakebold
= Cuti Demo & 中文文档
== 简介
Cuti 是利用 `text` 的 `stroke` 属性生成伪粗体的工具。该工具通常可用于为宋体、黑体、楷体等字体提供“粗体”。
Cuti 使用 0.02857em 作为 `stroke` 的参数。在 Microsoft Office 中,使用伪粗体会给字符添加一个 0.02857em 的描边。(实际上,精确值可能是 $1/35$。)
#line(length: 100%)
== 光速上手
在文档顶端加入
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
#import "@preview/cuti:0.1.0": show-cn-fakebold
#show text: show-cn-fakebold
#show strong: show-cn-fakebold
```
)
宋体、黑体、楷体的加粗就工作了。
#line(length: 100%)
== fakebold
不带其他参数的 `#fakebold[]` 会为字符添加#fakebold[伪粗体]效果。
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
Fakebold: #fakebold[#lorem(5)] \
Bold: #text(weight: "bold", lorem(5)) \
Bold + Fakebold: #fakebold[#text(weight: "bold", lorem(5))] \
```
)
#block(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
inset: 10pt,
)[
Fakebold: #fakebold[#lorem(5)] \
Bold: #text(weight: "bold", lorem(5)) \
Bold + Fakebold: #fakebold[#text(weight: "bold", lorem(5))]
]
`#fakebold[]` 有一个 `base-weight` 参数,可以用于指定基于什么字重描边。 默认情况或 `base-weight: none` 时,基准字重会从上文继承。
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
Bold + Fakebold: #fakebold(base-weight: "bold")[#lorem(5)] \
#set text(weight: "bold")
Bold + Fakebold: #fakebold[#lorem(5)]
```
)
#block(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
inset: 10pt,
)[
Bold + Fakebold: #fakebold(base-weight: "bold")[#lorem(5)] \
#set text(weight: "bold")
Bold + Fakebold: #fakebold[#lorem(5)]
]
#line(length: 100%)
== #regex-fakebold
`#regex-fakebold` 设计上是用于多语言、多字体情境的,可以根据参数 `reg-exp` 内的正则表达式只将匹配到的字符应用伪粗体格式。它也可以接受 `base-weight` 参数。
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
+ RegExp `[a-o]`: #regex-fakebold(reg-exp: "[a-o]")[#lorem(5)]
+ RegExp `\p{script=Han}`: #regex-fakebold(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。] \
#set text(weight: "bold")
+ RegExp `\p{script=Han}`: #regex-fakebold(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。]
```
)
#block(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
inset: 10pt,
)[
+ RegExp `[a-o]`: #regex-fakebold(reg-exp: "[a-o]")[#lorem(5)] \
+ RegExp `\p{script=Han}`: #regex-fakebold(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。] \
#set text(weight: "bold")
+ RegExp `\p{script=Han}`: #regex-fakebold(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。]
]
在上面的例子 \#3 中, `9` 和 `15` 是由字体提供的“真”粗体,而其他字符是用 `regular` 字重描边得到的伪粗体。
#line(length: 100%)
== show-fakebold
在多语言、多字体的场景中,不同的语言通常使用不同的字体,但是不是所有的字体都自带 `bold` 字重。需要 `strong` 或者 `bold` 效果时,每次都使用 `#fakebold` `#regex-fakebold` 并不方便。所以,我们提供了用于设置 `show` 规则 `#show-fakebold` 函数。
`show-fakebold` 和 `regex-fakebold` 有着相同的参数。默认情况下 `show-fakebold` 使用 `"."` 作为正则表达式,也就是说所有字符带加粗或`strong`属性都会被伪粗体加粗(如果配置了相应的 `show` 规则)。
请注意:`show text` 规则和 `show strong` 规则需要分别配置。
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
#show text: show-fakebold
Regular: #lorem(10) \
#text(weight: "bold")[Bold: #lorem(10)]
```
)
#block(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
inset: 10pt,
)[
#show text: show-fakebold
Regular: #lorem(10) \
#text(weight: "bold")[Bold: #lorem(10)]
]
正常情况下字体提供的加粗与伪粗体叠加的效果不是我们想要的。一般需要指定正则表达式、指定伪粗体的生效范围。
#code(
numbering: true,
radius: 0pt,
text-style: (font: ("Courier New", "SimHei")),
```typst
#show strong: it => show-fakebold(reg-exp: "\p{script=Han}", it)
Regular: 我正在使用 Typst 排版。 \
Strong: *我正在使用 Typst 排版。*
```
)
#block(
stroke: (paint: blue, thickness: 1pt, dash: "dashed"),
inset: 10pt,
)[
#show strong: it => show-fakebold(reg-exp: "\p{script=Han}", it)
Regular: 我正在使用 Typst 排版。 \
Strong: *我正在使用 Typst 排版。*
]
`show-fakebold` 也接受 `base-weight` 参数。
#line(length: 100%)
== cn-fakebold & show-cn-fakebold
这两个都是为中文排版封装的。
- `cn-fakebold` 是 `regex-fakebold` 的封装,默认的正则范围是中文字符与常见标点符号。
- `show-cn-fakebold` 是 `show-fakebold` 的封装,默认的正则范围是中文字符与常见标点符号,使用方法见“光速上手”小节。
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/import-17.typ | typst | Other | // Error: 8 expected expression
#import
|
https://github.com/pluttan/asmlearning | https://raw.githubusercontent.com/pluttan/asmlearning/master/lab1/lab1.typ | typst | #import "@docs/bmstu:1.0.0":*
#show: student_work.with(
caf_name: "Компьютерные системы и сети",
faculty_name: "Информатика и системы управления",
work_type: "лабораторной работе",
work_num: "1",
discipline_name: "Машинно-зависимые языки и основы компиляции",
theme: "Изучение среды и отладчика ассемблера",
author: (group: "ИУ6-42Б", nwa: "<NAME>"),
adviser: (nwa: "<NAME>"),
city: "Москва",
table_of_contents: true,
)
= Цель работы
Изучение процессов создания, запуска и отладки программ
на ассемблере Nasm под управлением операционной системы Linux, а также
особенностей описания и внутреннего представления данных.
= Создание папок и файлов
При работе с операционной системой `linux` удобно использовать для большинства действий терминал, поэтому я буду использовать только его. Редактор кода `neovim`, деббагер `gdb`.
Создадим папку и файлы для 1 лабораторной работы. Для этого воспользуемся утилитами ```sh mkdir```, ```sh cd```, ```sh touch``` и выведем все файлы в папке на экран с помощью ```sh ls```.\
#code("mkdir -r ~/labs/lab1
cd ~/labs/lab1
touch lab1.{1..6}.asm
ls", "zsh", "Создаем папки и файлы")
#img(
image("01-ls.png", width: 80%),
[Вывод команды ```sh ls```]
)
= Заготовка программы
Возьмем заготовку программы для 32 битной архитектуры.
#code(read("lab1.1.asm"), "asm", "Заготовка программы")
Программу скомпилируем и скомпануем при помощи компилятора ```sh nasm``` и копоновщика ```sh ld```.
Так как процессор у меня 64-ех разрядный, а программа написана для 32-ух разрядного процессора укажем компановщику, что нужно использовать режим эмуляции: ```sh ld -m elf_i386```.\
#pagebreak()
И так вся команда для собрания бинарного файла будет выглядеть так:
#code("mod=lab1.1 # Название ассемблерного файла без расширения
nasm -f elf -o $mod.o $mod.asm
ld -m elf_i386 -o $mod $mod.o
", "sh", "Команда для создания бинарного файла")\
После этого программу можно запустить при помощи команды ```sh ./$mod```.
#img(
image("02-lab1.1.png", width: 80%),
[Вывод программы 1]
)\
Разберем основные идеи в программе.
Она разделена на 3 подпрограммы: вывод, ввод, выход. Между подпрограммами используется механизм прерываний, который выполняет системные функции указанные в регистре ```asm eax```. Следует отметить, что сейчас все прерывания обрабатываются программно и доступ к действительным аппаратным прерываниям современные операционные системы не предоставляют.
Для вывода используем системную функцию 4. Для этого помещаем значение 4 в ```asm eax```. В регистр ```asm ebx``` помещаем декриптор файла `stdout`. Дескрипторы файлов `stdin`, `stdout` и `stderr` -- 0, 1 и 2, соответственно. В ```asm ecx``` указываем ссылку на первый элемент массива с нашей строкой (которая в памяти представлена как набор чисел). В ```asm edx``` помещаем размер строки.
Тут следует немного подробнее остановиться на том как мы получаем этот размер строки, объявленный в ```asm section .data```. Знак `$` воспринимается в диалекте `nasm` как адрес текущей ячейки памяти, т.е. если использовать знак `$` после объявления массива то мы получим адрес, который на единицу превосходит адрес последнего элемента массива. Вычитая из полученного адреса адрес начала массива мы получаем длину массива, а так как эти операции были проделаны не с литералами, а с адресами мы используем ```asm equ```. По такому же принципу мы получаем и ```asm lenIn```.
Для чтения выделим отдельно неинициализированную память для 10 букв(после ввода 11 ввод перенаправится в командную строку по завершении программы). Используем системную функцию 3, файл stdin, выделенную память и ее длину для регистров ```asm eax```, ```asm ebx```, ```asm ecx```и ```asm edx``` соответственно.
Для выхода используем системную функцию 0, возвращаем код 0, чтобы показать, что программа успешно завершилась.
Посмотрим как выглядит машинное представление программы, ее дизассемблированный код, содержимое регистров в отладчике. Для этого запустим отладку с помощью команды ```sh gdb $mod```.
#img(
image("03-interfgdb.png", width: 80%),
[Интерфейс `gbd`]
)\
Создадим новый "слой" в котором сверху будут регистры, а снизу ассемблерный код, созданный на основе полученного бинарного кода. Сам машинный код это набор чисел, так что он совершенно не нагляден для отладки.
```sh
tui new-layout ra regs 1 asm 1 cmd 1
```
После создания слоя перейдем в него с помощью команды ```sh lay ra```.
Тут создадим точку останова на метке начала нашей программы ```sh br start```.
Перед запуском убедимся что в память загрузилось все, что мы объявили в ```asm section .data```.
#img(
image("04-mem.png", width: 80%),
[Занятая память]
)
Как мы видим в начале памяти идет `"Press Enter to Exit"`. Попробую представить это более наглядно:
#text(size: 12pt)[
```math
50 72 65 73 73 20 45 6e 74 65 72 20 74 6f 20 45 78 69 74
P r e s s E n t e r t o E x i t
```]
10 байт после этой записи зарезервированы под ввод, а константы просто заменяются самим компилятором nasm, поэтому памяти они не используют (аналогично ```c #define```).
Итак теперь все готово к запуску, вводим команду ```sh run```.
#img(
image("05-deb.png", width: 60%),
[Запуск программы]
)\
Как мы видим регистры ```asm eax```, ```asm ebx```, ```asm ecx```и ```asm edx``` пусты, а курсор на первой ассемблерной инструкции. Выполним первую часть кода и посмотрим как изменится содержимое регистров.
#img(
image("06-deb1.png", width: 60%),
[Первая часть кода]
)\
Переместили все значения в регистры, и результатом стало, что все значения просто лежат в регистрах, но после системного прерывания значение в регистре ```asm eax``` поменяется на коды, возвращенные системой после печати.
#img(
image("07-deb2.png", width: 60%),
[Вызываем прерывание и видим как меняется значение регистра]
)\
После выполнения первой части кода уже понятно, как ведут себя регистры при операциях перемещения и вызове системы, поэтому просто для наглядности приведу еще один скриншот программы с перемещением в регистры второй части программы.
#img(
image("08-deb3.png", width: 60%),
[Готовим регистры для вызова ввода]
)\
Итак, мы нажали на enter, программа завершилась с кодом $0$. Осталось только проверить флаги. Они хранятся в регистре ```asm eflags```. Вот, что находится в этом регистре после завершения программы:
#img(
image("09-deb4.png", width: 100%),
[Флаги после завершения программы]
)\
Приведу таблицу флагов.
#img(
image("10-eflags.svgz", width: 80%),
[Таблица флагов]
)\
Из таблицы видно, что так как программа завершилась нулем, она подняла флаг четности `PF` и флаг нуля `CF`. `IF` по умолчанию всегда поднят, если у программы есть возможность вызвать прерывание.
= Отладка арифмитических операций
Приведем другой ассемблерный код с арифмитическими операциями:
#code(read("lab1.2.asm"), "asm", "Код для отладки")
Скомпилируем, соберем и запустим файл. Он просто завершит работу. Все операции мы можем посмотреть опять обратившись к отладке. Тут я построчно приведу всю отладку начиная с ```asm _start```.
Но для начала снова проверим память:
#img(
image("11-mem2.png", width: 50%),
[Память]
)\
Тут $-30$ это `0xffe2` (правило получения числа -а: переводим а в двоичную форму (прямой код), заменяем все 0 на 1, а 1 на 0 (обратный код), прибавляем 1 к записи (дополнительный код)). Убедимся в правильности записи `30 = 0x1e`, преобразуем в обратный `0x1e = 00011110b`#sym.arrow`11100001b = 0xe1` тут стоит заметить что на самом деле в памяти мы выделяем слово, получается 30 это не `0x1e`, а `0x001e`, тогда обратный код `0xffe1`, добавим 1, чтобы получить дополнительный и получится как раз `0xffe2`.
А `b` положительно, поэтому представляется в памяти в виде простой формы `21 = 16+5 = 0x15`.
Теперь запускаем программу и смотрим на результат.
#grid(
columns:2,
gutter:10pt,
img(image("12-deb5.png", width: 90%),"Запуск"),
img(image("13-deb6.png", width: 90%),```asm mov eax, [a]```)
)
#grid(
columns:2,
gutter:10pt,
img(image("14-deb7.png", width: 90%),```asm add eax, 5```),
img(image("15-deb8.png", width: 90%),```asm sub eax, [b]```)
)
#grid(
columns:2,
gutter:10pt,
img(image("16-deb9.png", width: 90%),```asm mov [x], eax```),
img(image("17-deb10.png", width: 90%),```asm mov eax, 1```)
)
Так как числа записываются в память друг за другом, и по шине данных проходит ровно 32 бита, то в регистр ```asm eax``` попала не только ```asm a```, но и ```asm b```. Но операции не изменили знак числа, поэтому в конечном итоге мы получили правильный ответ, который записали в память:
#img(image("18-mem3.png", width: 60%),[Память программы после завершения], f:(i)=>{i.display()})
Как мы видим в память записывается весь регистр ```asm eax```, но так как память выделена только для 1 байта, то неициализированные переменные могут перезаписать код, например если в ```asm section .bss``` добавить ```asm nw resb 2```, а в ```asm _start``` добавить перед выходом ```asm mov [nw], 0```, то `15ff` затрется.
Но есть и другие способы решения этой проблемы.
Сначала разберем, что нам необходимо с потерей данных, но все же записать в оперативную память некоторые данные размер которых превышает размер выделенной памяти. Тогда необходимо объявить сколько именно байт мы хотим записать в память, т.е. заменить ```asm mov [x], eax``` #sym.arrow ```asm mov byte[x], eax```.
Но в идеале изначально отсечь все, что не относится к нашему числу, для этого можно заменить ```asm mov eax, [a]``` #sym.arrow ```asm mov ax, [a]```, а дальше продолжить работать с ```asm eax```. Еще есть более сложный способ -- применение маски: дело в том, что если нам необходимо из числа `0xff271369` сделать `0x00000369`, то можно просто воспользоваться логической операцией ```asm and``` с литералом `0x00000fff`, тогда все "ненужные" числа логически умножатся на ноль и останутся только те, что логически умножились на 1. Для данного случая маску можно применить после ```asm mov eax, [a]``` так:```asm and eax, 0x0000ffff```.
Так же стоит отметить, что изначально мы выделяем памяти на 1 байт меньше для ответа, так что использовать ключевое слово ```asm byte``` все равно придется.
= Работа с памятью
В отличии от высокоуровневых языков со строгой типизацией в ассемблере, при выделении памяти в нее можно положить любое значение, оно будет транслированно компилятором в численное значение.
#code(read("lab1.3.asm"), "asm", [Код для работы с памятью])
Скомпилируем, соберем и откроем в отладчике код.
В коде нас интересуют только данные в памяти:
#img(image("19-mem4.png", width: 100%),[Память программы], f:(i)=>{i.display()})
jdlkaslkdja jadklkjdla dajklj kkakjd djjdj
Разбирать данные будем снизу вверх, справа налево, каждые 32 бита, слева направо каждый. Для удобства напишу таблицу, в которой показано какой байт к чему относится, адресация идет на каждый байт, в строке 4 байта поэтому адрес меняется на 4, уменьшается адрес потому что мы читаем снизу вверх (адрес полностью не вместился так что к написанному смещению необходимо прибавить `0x804a000`):\
\
#table(
columns: (auto, auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[Смещение], [Значение 32 бит], [1 байт], [2 байт], [3 байт], [4 байт],
[30], [`00 00 00 00`], [`f1`], [`f1`], [`f1`], [`f1`],
[2c], [`00 00 00 00`], [`f1`], [`alu`], [`alu`], [`alu`],
[28], [`00 00 00 00`], [`alu`], [`alu`], [`alu`], [`alu`],
[24], [`00 00 00 00`], [`alu`], [`alu`], [`alu`], [`alu`],
[20], [`00 00 00 00`], [`alu`], [`alu`], [`alu`], [`alu`],
[1c], [`00 00 00 00`], [`alu`], [`alu`], [`alu`], [`alu`],
[18], [`00 08 08 08`], [`alu`], [`valar`], [`valar`], [`valar`],
[14], [`08 08 12 34`], [`valar`], [`valar`], [`ar`], [`ar`],
[10], [`56 78 80 01`], [`ar`], [`ar`], [`min`], [`min`],
[0c], [`0a 6f 6с 6c`], [`sdk`\\n], [`sdk`o], [`sdk`l], [`sdk`l],
[08], [`65 48 0c 23`], [`sdk`e], [`sdk`H], [`beta`], [`beta`],
[04], [`17 25 10 ff`], [`beta`], [``], [`v5`], [`lue3`],
[00], [`80 01 00 ff`], [`lue3`], [`chart`], [`chart`], [`val1`],
)
= Определение данных
*Задание*:
Определите в памяти следующие данные:
+ целое число 25 размером 2 байта со знаком;
+ двойное слово, содержащее число -35;
+ символьную строку, содержащую ваше имя (русскими буквами и латинскими буквами).
Вот получившийся по данному заданию код:
#code(read("lab1.4.asm"), "asm", [Определение данных])
Скомпилируем, соберем и откроем в отладчике код.
В коде нас снова интересуют только данные в памяти:
#img(image("20-mem5.png", width: 100%),[Память программы], f:(i)=>{i.display()})
Составим такую же таблицу, что и в предыдущем задании.
#pagebreak()
#table(
columns: (auto, auto, auto, auto, auto, auto),
inset: 10pt,
align: horizon,
[Смещение], [Значение 32 бит], [1 байт], [2 байт], [3 байт], [4 байт],
[18], [`00 00 00 b9`], [], [],[],[`n`й],
[14], [`d0 b5 d0 80`], [`n`й], [`n`е],[`n`е],[`n`р],
[10], [`d1 b4 d0 bd`], [`n`р], [`n`д],[`n`д],[`n`н],
[0c], [`d0 90 d0 20`], [`n`н], [`n`А],[`n`А],[`n` ],
[08], [`79 65 72 64`], [`n`y], [`n`e],[`n`r],[`n`d],
[04], [`6e 41 ff ff`], [`n`n], [`n`A],[`b`],[`b`],
[00], [`ff dd 00 19`], [`b`], [`b`],[`a`],[`a`],
)
Так как буквы кириллицы не входят в ASCII, то для их записи необходимо 2 байта, для латиницы используется только 1 байт. Тут пример из начала с получением длины не сможет сработать, ведь у нас каждая буква кодируется разным количеством байт.
= Работа с данными
*Задание*: Определите несколькими способами в программе числа, которые
во внутреннем представлении (в отладчике) будут выглядеть как 25 00 и 00 25. Проверьте правильность ваших предположений, введя соответствующие
строки в программу.
Вот получившийся по данному заданию код:
#code(read("lab1.5.asm"), "asm", [Работа с данными])
В данном задании требуется несколькими способами вывести числа. В отладчике все числа выводятся в 16-ричном формате, так что буду работать с ним. Первым способом я выбрал простой ввод в память двух чисел. Чтобы они не "слиплись" используем двойное слово -- 32 бита.
#img(image("21-mem6.png", width: 60%),[Первый способ], f:(i)=>{i.display()})
Вторым способом я выбрал использование регистров, ведь 16-тибитные ```asm ax```,```asm bx```,```asm cx```,```asm dx``` разделяются на верхние ```asm ah```,```asm bh```,```asm ch```,```asm dh``` и нижние ```asm al```,```asm bl```,```asm cl```,```asm dl```. Таким образом если `0x25` внести в нижний регистр то в отладчике он так и будет, а если в верхний, то он автоматически умножится на 256, т.е. станет `0x2500`.
#img(image("22-deb11.png", width: 50%),[Второй способ], f:(i)=>{i.display()})
= Переполнение
Добавьте в программу переменную ```py F1 = 65535``` размером слово и переменную ```py F2 = 65535``` размером двойное слово. Вставьте в программу команды сложения этих чисел с 1:
```asm
add [F1],1
add [F2],1
```
Проанализируйте и прокомментируйте в отчете полученный результат (обратите внимание на флаги).
Вот получившийся код:
#code(read("lab1.6.asm"), "asm", [Переполнение])
Заходим в отладчик и запускаем программу:
#img(image("23-deb12.png", width: 60%),[Запуск], f:(i)=>{i.display()})
Добавляем значения в регистры:
#img(image("24-deb13.png", width: 60%),[Значения в регистрах], f:(i)=>{i.display()})
Устраиваем переполнение для регистра ```asm ax```:
#img(image("25-deb14.png", width: 60%),[Переполнение], f:(i)=>{i.display()})
Так как мы прибавили 1, то при переполнении ax перешагнул на 1 и стал 0, поэтому поднялся нулевой флаг `ZF` и флаг четности `PF`. `AF` и `CF` как флаги переноса свидетельствуют о переполнении регистра.
```asm ebx``` имеет размер в 2 раза больше, поэтому при прибавлении единицы значение в этом регистре станет просто `0x10000`:
#img(image("26-deb15.png", width: 60%),[```asm ebx``` не переполняется], f:(i)=>{i.display()})
= Вывод
В процессе работы были изучены процессы создания, запуска и отладки программ на ассемблере NASM под управлением Linux. Были освоены специфики описания и внутреннего представления данных, а также изучены операции ввода-вывода через прерывания, арифметические операции, работа с памятью и отслеживание переполнения. Этот опыт позволил более глубоко понять внутреннее устройство компьютера, архитектуру и специфику работы операционной системы на низком уровне.
= Контрольные вопросы
1. *Дайте определение ассемблеру. К какой группе языков он относится?*
Ассемблер - низкоуровневый язык программирования, посылающий команды процессору. Язык ассемблера относится к машинно-зависимым языкам программирования.
2. *Из каких частей состоит заготовка программы на ассемблере?*
Заготовка программы на языке ассемблера состоит из трех частей:
- ```asm section .text``` (сегмент кода)
- ```asm section .data``` (сегмент инициализированных данных)
- ```asm section .bss``` (сегмент неинициализированных данных)
3. *Как запустить программу на ассемблере на выполнение? Что происходит с программой на каждом этапе обработки?*
Для подготовки программы к выполнению сперва вызывают транслятор
`nasm` и компоновщик `ld` следующей командой:
```sh nasm -f elf64 lab1.asm -l lab1.lst```
В результате работы транслятор создает объектный файл, которые затем подается на вход компоновщика:
```sh ld -o lab1 lab1.o```
Компоновщик формирует исполняемую программу.
4. *Назовите основные режимы работы отладчика. Как осуществить пошаговое выполнение программы и просмотреть результаты
выполнения машинных команд.*
- `si` – выполнить шаг с заходом в тело процедуры;
- `s` – выполнить шаг, не заходя в тело процедуры.
- `r` - запуск программы
- `br` - установить точку останова
- `lay` - переключиться между слоями
5. *В каком виде отладчик показывает положительные и
отрицательные целые числа? Как будут представлены в памяти
числа: A dw 5,-5 ? Как те же числа будут выглядеть после загрузки в регистр AX?*
5 в шестнадцатеричной системе счисления равно `00000005`, а -5 будет выглядеть как `fffffffb`. В регистре ```asm AX``` число 5 будет выглядеть как `0005`, а число -5 будет выглядеть как `fffb`.
6. *Каким образом в ассемблере программируются выражения?
Составьте фрагмент программы для вычисления С=A+B, где A, В и С – целые числа формата BYTE.*
#code("section .data
A db 1
B db 2
section .bss
C resb 1
section .text
global _start
_start:
mov al, [A]
mov ah, [B]
add al, ah
mov byte[C], al
", "asm", "C = A+B")
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/006_The%20Chensal%20Twins.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Chensal Twins",
set_name: "Khans of Tarkir",
story_date: datetime(day: 15, month: 10, year: 2014),
author: "<NAME>",
doc
)
#emph[A thief stands accused. A Jeskai village is ready to mete out justice. But true justice has only one source.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"They're here! They're here!"
"The twins!"
"Hurry!"
The sing-song voices and pattering footfalls drew Kela's attention. She shifted her gaze, all the while keeping her neck faultlessly straight and walking step for step at Dar's side.
A handful of Jigme Village children were racing toward them along the far bank of the babbling river.
"Do you think they'll say he's guilty?" the boy in front called back to the others.
"He is guilty!" said a slightly chubby boy with flushed cheeks. He ran past the other boy.
"How do you know?" a girl with a fringe of straight, black bangs panted.
"I know because—" Abruptly, the chubby boy slowed to a stop. "Wow." He pointed at Kela and Dar's foreheads in awe. "Look."
#figure(image("006_The Chensal Twins/01.jpg", width: 100%), caption: [Dragon-Style Twins | Art by Wesley Burt], supplement: none, numbering: none)
The others fell in behind him, staring unabashedly.
"The dragon's eye," the first boy said reverently.
"The marks are so bright," said the girl with the fringe.
"They hurt my eyes." The chubby boy shielded his face.
"That's ridiculous." This voice, an annoyed mutter, came from Kela's other side.
Kela looked without moving her head. She wouldn't have seen the girl in the tree had it not been for the child's glistening eyes. They were sharp and bright and they followed Kela and Dar's every move.
"It's a symbol of strategy," one of the children on the other side of the river said.
The girl in the tree rolled her eyes. "Cunning. The dragon's eye is a symbol of cunning." She spoke in a whisper, barely loud enough even for Kela to hear.
"It means they're really good at combat," one of the other children said.
"Incorrect," the girl in the tree said. "It means they are on a path to enlightenment." She touched her own forehead, an act that looked familiar and practiced. "A path that led them here. A path that will lead us all to the places and times we are most needed." She closed her eyes and dipped her head in a bow.
How Kela wished that those words were true; she did not feel she was on a path, rather that she was wandering aimlessly, following Dar.
Suddenly, the branch beneath the girl gave way with a sharp snap.
Kela gasped.
The girl reacted before Kela could, flipping and somersaulting as though the whole stunt had been planned. She landed soundlessly in a crouch like a cat on the side of the path. Her piercing eyes flashed to Kela's. Caught, she stood and smiled shyly.
Kela stretched her lips into a configuration they weren't much used to, returning the gesture.
"What are you doing?" Dar's voice startled Kela out of her grin.
Her eyes shot forward. "Nothing. I was just—"
"Don't. Speak."
"We're not even to the village yet."
"There are villagers here, are there not?"
"They're only children, Dar."
"And they can see you talking."
"They can see #emph[you] talking. You spoke fir—"
"Enough. You shall not show emotion. What we do, it's all about perception, Kela. When will you understand that?"
"What we do is about justice, brother."
"A justice that the Jeskai only accept because of the way we are perceived. If that perception is tarnished, so too will be our decrees. Is that what you want?"
The question felt like a trap; Kela didn't dare shake her head, nor speak a response, for that was a trap too. Luckily, she was saved from doing either as they arrived at the village gates.
Jigme villagers lined the bridge on the other side of the entrance. Eyes and mouths hung agape as Kela and Dar approached.
It was a narrow bridge, and with villagers on both sides it was only wide enough for one of them to cross at a time. Dar went first. He always went first. He had done everything first since the day they were born. Although they were twins, he had been born first—first by a day. He in the evening, and Kela in the morning of the next day.
Being born in the morning light was the reason she was #emph[innocence] . And Dar's birth in the darkness of night was the reason he was #emph[guilt] . At least that was as it should be, that and nothing else.
A gong sounded from the village center. Kela could feel the reverberations in her chest. She followed her brother through the corridor of chattering villagers into Jigme Square. As she walked she caught snippets of gossip, slander, and suspicion.
"...guilty as water runs south..."
"...don't need arbiter twins to tell us..."
"...he never even climbed the Initiate's Stair."
"What kind of man..."
Together, Kela and Dar ascended three shallow steps and came to stand on a low wooden platform in the village center.
The village elder, a woman with a tight, white braid running down to her ankles, bowed to them. A breathless quiet settled over the villagers.
#figure(image("006_The Chensal Twins/02.jpg", width: 100%), caption: [Jeskai Elder | Art by <NAME>], supplement: none, numbering: none)
"Welcome to Jigme." The elder's voice was crisp. "I am <NAME>. You honor us with your presence, <NAME>." She bowed long and low. "May justice be served today."
"So say the #emph[Rules of the Reeds] ." Dar and Kela returned the bow, Dar dipping slightly lower than Kela.
Kela bristled silently.
They were supposed to be equals; they were supposed to be balanced. That was how justice was ensured, by innocence equaling guilt in every measure. But with Dar being born the day before her, with the way he held himself over Kela, it was a wonder that they could serve justice at all. Kela often thought they should not, that she should not.
"Come," <NAME> said as she stood. "It is time."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Like all courts in all small Jeskai villages, the Jigme Village Court was carefully maintained. The floors had the look of just recently having been swept and the matching pillows that had been laid out for Kela and Dar looked as though they had been freshly embroidered. Kela had heard that Jigme was known for its exquisitely crafted fabrics.
As she settled into the soft cushion, Kela glanced around the courtroom. It was small; there was only enough room for a dozen villagers to watch the proceedings. That was fine with her; the scrutiny of too many eyes made her feel like a fraud.
"This court has been called to session under the Dragon Eyes of the Chensal Twins." <NAME> spoke before the small crowd. "Today, we hear the case of <NAME> against the Jigme Village." She extended her arm, gesturing at a raw, rangy man who stood near the wall with his head bowed. "May justice be served today."
"So say the #emph[Rules of the Reeds] ," the villagers intoned.
With that the room fell silent, and Kela and Dar began the Ritual of Arbiter Twins. Through a series of slow, controlled movements and a low, sonorous chant, they fell into a state of deep meditation. They would hear the trial from that state, connected as they were to truth, justice, and the way of the dragons.
The trial proceeded around them; <NAME> was persecuted and he made his defense. The case was straightforward. The man was accused of thievery. Nine baskets of apples had been stolen from the Village reserve. Three baskets had been found in Lotse's shelter, less than a half day's journey from Jigme. Six more baskets were found empty not far off, and many wandering Jeskai who often went hungry had littered cores along the nearby trails in the days that followed.
Lotse admitted to feeding the hungry, but he also claimed the fruit was his to give.
The voices washed over Kela, rocking her gently as she slipped ever deeper into her meditation.
Lotse's tearful voice swirled around her.
Kela fell deeper still.
<NAME>'s words danced on Kela's eyelids.
She drifted.
The villagers rumbled.
And Kela was transported to the place where justice dwelled.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When she surfaced from her meditation, Kela slowly became aware of her surroundings. She was in the Jigme Tower of Innocence. The trial had ended. She had been carried up to the top of the tower while still in her meditative state, as was the tradition.
She faced the moment of judgment.
That moment was supposed to be one of purest clarity, a moment only Arbiter Twins could experience. She was supposed to open her eyes knowing the verdict, feeling Lotse's innocence or guilt in her soul.
But the only thing she felt in her soul was the weight of deception. Her deception. It was what she always felt in every Tower of Innocence in every Jeskai village she and Dar had visited. She was a fraud.
#figure(image("006_The Chensal Twins/03.jpg", width: 100%), caption: [Jeskai Banner | Art by <NAME>], supplement: none, numbering: none)
As she looked to the oil lamp in the center of the tower her stomach tightened. It was for her to decide if she should light, or not light, the wick. No, it was for her to know. But she did not know.
She stood and paced the small circumference of the room. There was not much time. Soon the gong would sound, and at that moment she would have to act. Dar would act too; he would light or not light the lamp in the Tower of Guilt. But unlike her he would know unquestionably what he should do. Dar always knew.
Kela tried to think back on the trial, tried to sort through the details that swam in her mind. Was Lotse innocent? It seemed like he might be. Perhaps. She should light her lamp, she thought. Yes she would light it.
She tried to feel confident about her decision. That was the trick to it, or so her mentor at the Cori Mountain Stronghold had told her, time and again. "You must believe in yourself, in what you feel inside, that is where the truth lies."
She tried to believe. She had to believe, for if she was wrong...
Only one flame could burn. Arbiter Twins, for as long as there had been Arbiter Twins, only lit one flame at every trial. Twins did not speak to each other, they were not allowed to see each other, their towers were separate, yet somehow only one flame was ever lit. Never two, never none. That was how the villagers knew it was justice.
The gong rang out.
Kela picked up the flint and moved to strike it, but then she stopped.
No, she should not light it. No. He was guilty.
Wasn't he?
"Oh, I don't know." She held her breath, clenching the flint in her fist. "Please, please, please."
"Guilty! He is guilty!" The cries rose up from the villagers below.
"Give us back the apples!"
Kela breathed.
Lotse was guilty. Dar had lit his lamp.
She had been right to leave hers cold.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The celebration that followed was as much for the Jigme villagers as it was for their guests. Music was played on hand-carved flutes, magical dancing lights filled the sky, and villagers sang, hands clasped, around fires.
At the edge of the crowd, Kela picked out the girl from the tree. She was observing the festivities intently, but was unwilling to join in. When she noticed Kela watching her she offered the same shy smile she had earlier. Her admiration for Kela was obvious in her wide eyes and Kela was thankful that she and Dar had been able to live up to the girl's expectations that day.
It was one more trial that they had arbitrated successfully, one more time that they had, despite their imbalance, despite #emph[her] fraudulent birth, executed justice. She glanced at Dar. Was it possible that was their path after all? Was there a chance that she belonged?
Dinner was served to the village elder first, as was tradition. It was flatbread and, fittingly, if not appropriately, a thick apple soup.
"Thank you." <NAME> nodded to the young man who had served her. All eyes were on the old woman sitting atop the wooden platform as she tucked a wisp of her white hair behind her ear. She wafted the aroma of the soup to her nose and nodded. "Smells good."
There was a smattering of polite laughter. Kela could sense the hunger behind the sound; they would not be served until the elder ate.
<NAME> finally lifted the bowl to her lips and drank the soup. She swallowed once, twice, and then she lowered the bowl, a smile on her face. "It is del—" Her voice caught in her throat. She cocked her head to the side as though puzzled, and then her eyes shot wide. She raised her hands to her neck, clawing wildly, her face turning gray.
The music stopped.
The dancing lights fell from the sky.
"She's choking!" someone shouted.
"Help her!" another cried.
Villagers crowded up the shallow steps, running to the elder's aid, healers and mystics.
The commotion escalated to a frenzy...and then, just as quickly, it diminished into silence.
A Jigme healer stepped back, shaking his head.
"What happened?" a stray voice wondered.
"I don't know," came an answer. "She just—she just—"
"She was poisoned!" This voice was loud and sure. "It was the apples!"
Kela was not the only one to gasp.
"It was Lotse!"
The Jigme villagers mobilized, and before Kela's mind could catch up with their feet they were at the doors of the prison, pounding them down.
"Murderer!" they cried.
"Kill him!"
They broke into Lotse's cell and dragged him out. A mob, thirsting for blood.
"Stop!" Lotse begged. "Stop, please!"
"We will have your head for what you have done!" A Jeskai warrior drew his blade.
"No!" Kela jumped in front of the sword. She didn't realize she had leapt until she was there, staring at the sharp tip, her breath coming in quick, short gasps.
"Get out of the way!" the warrior shouted.
"What are you doing?"
Kela recognized the second voice as Dar's. He was standing back from the crowd glaring at her. She knew what he was thinking without his need to speak. That was not the way he wished for the villagers to perceive them. He was telling her with his eyes to get up, to get out of the way, and to let them kill the man.
But she could not move. Something bound her to that place, that moment. It was as though she had been walking a long road and only then had she realized this had been her destination all along.
"Get out of the way, so help me!" The warrior pressed his blade to Kela's throat.
"He should have a trial," she whispered.
"What did she say?" The question came from further back in the crowd.
"What did you say?" the warrior asked.
"He should have a trial," Kela said, slightly louder this time.
"But he is a murderer!" a villager cried.
"Murderer!" The voices of the other villagers echoed.
"Can you say he is not?" the warrior asked Kela.
Kela looked to Lotse. There was fear in his eyes, fear and pleading. She tried to see more, but there was no more to see. She did not know if he was guilty or innocent. She could not tell.
"Well?" the warrior pressed. "Say it, arbiter. If you can. Say he is innocent."
She could not.
Kela saw Dar behind the warrior, his lips curled up into a sneer. And around him it seemed that all the villagers mimicked his expression.
The sneers made Kela feel foolish. What had she done? What was she thinking? She looked away, down to the muddy ground, for there was nowhere else for her to look. And that's when she saw the girl from the tree.
The girl was staring up at Kela, wide-eyed, from under the shelter of an upturned wagon. Their eyes locked, and in that moment Kela understood something she had never fully understood before. There was more at stake here than the guilt or innocence of one man. Jeskai justice was at stake. And the girl from the tree was holding Kela to her part in that moment.
"See! She cannot say it!" a voice from the crowd called. "She cannot say he is innocent!"
"He is guilty then!"
"Murderer!"
"Kill him!"
"Enough!" Kela found her voice, shaking though it was. Fear didn't matter. She nodded to the girl from the tree and pushed aside the warrior's blade. She got to her feet and faced Dar and the wild Jigme villagers.
"I will not stand for this!" She had never felt that way before. Flame was coursing through her veins and lapping at her soul. Rather than holding it in, she let it flow, to flow out of her in the name of justice. "The #emph[Rules of the Reeds] dictate that any Jeskai accused of murder will have a trial. So this man shall. I will not make a judgment until I am in my tower!"
"Blasphemy!"
"He is guilty!"
"Can't you see it?"
"Is this what you would have too, twin?" The warrior turned to Dar.
Kela felt slightly sorry for her brother then. He had no choice but to agree with her, both for perception's sake and for the sake of the #emph[Rules of the Reeds] .
Dar nodded slowly. "Yes."
The crowd gasped.
"But—" Dar held up his hands before they could launch into their cries. "But we will be quick. Let us go to our towers now and make our judgments as my sister wants. Let us do that before you have his head, let us do that and your village will not be guilty of breaking the #emph[Rules of the Reeds] ."
"So be it!" the warrior cried. "Light your flame if you must. It will do well to cast a light on the murderer's beheading!"
The Jigme villagers cheered and moved toward Kela and Dar as one.
Kela shouted, but her voice was not heard above theirs. She was hurried toward the tower and shouldered up the stairs. That was not how an Arbiter was to be treated. That was not how a trial was to be run.
She caught Dar's eye.
He shook his head once, sharp and pointed. She knew what he was telling her: "Do not light your flame."
He would be lighting his, affirming the villager's beliefs, upholding the perception of justice.
But justice was not a perception.
Kela was thrown into the room at the top of tower and the door slammed behind her.
She barely had time to push herself to her feet before the gong sounded.
Driven still by the flame inside, she ran for the flint and struck it. Then she lit wick. The lamp of innocence ignited.
"What is this?" The cry from below came mere seconds later.
Kela ran to the window. All of Jigme was staring up at her and Dar.
"Two flames!"
"This is not justice!"
"We will have justice!"
The mob turned on the towers and so too did their thirst for blood.
Kela's tower shook as they climbed, and they were at her door the next moment beating it down.
Kela sprang out through the window. She sprinted down toward the ground on the currents of the air. She would not fall to those hands, not that night.
"What have you done?" Dar stormed onto the current of air that supported her weight. It shifted under them as he followed her. "You are ruining us, sister. They will never trust us again."
"I am not ruining us, I am saving us. We do not know the judgment. This was the only way."
"I know the judgment."
Kela hesitated, slowing. The current trembled beneath her feet. Dar had spoken so surely. She looked back at him over her shoulder. His face was a mask she could not read.
"I know the judgment," he said again. "That should be enough for you, sister. Come now, you never knew anyway, did you? I could always tell. It was all blind luck. A guessing game. 'Will Dar light his flame?' How many times did you ask yourself that?"
Kela faltered and the current of air dipped. She lost her footing and her control and she plummeted to the ground.
For a moment all was black. When she blinked the world back into focus, Dar was standing above her, his sword drawn. "Do not make me do this, sister. Concede to me. The thief is guilty of murder. I know."
But Dar did not know. Kela was sure. She was certain. The feeling welled inside her, and she recognized it then. She had felt it before, so many times before, in all of the villages, in all of the Towers of Innocence, in that very village earlier that day when it had told her not to light her flame. It had only been a whisper previously because she had not given credence to its voice. But then, when she was listening, it was screaming. So she screamed too. "No!" She rolled out of reach of Dar's blade and jumped to her feet. "You cannot know if I do not know."
She drew her sword.
"Don't be foolish, Kela. If you attempt to fight me, I will kill you. Put down your blade."
"Only one justice will force my blade from my hand." Kela swung her sword. Dar parried. "We will fight, brother. For the judgment of this moment, we will fight."
Their blades met in mid-air with a great clang.
And so began their Combat of Clarity. It was an old, unused tradition of the Arbiter Twins. If ever they disagreed on a verdict they were to be set to single combat. It was said on the scrolls that so evenly matched as they were, the only thing that would set the twins apart would be the clarity of their judgment. The twin who was fighting for justice, defending truth, would have the edge, as slight as it was, and would therefore be victorious.
#figure(image("006_The Chensal Twins/04.jpg", width: 100%), caption: [Dragon's Eye Savants | Art by <NAME>ainville], supplement: none, numbering: none)
Kela possessed the clarity in that combat and she knew it. She could see everything. It was as though she was looking at the world from four different vantage points at once, and two more in the future. She saw her brother roll and she saw him get up at the same time. But when she moved to stop him she saw him stumble back, never reaching the place where he would have stood if he had rolled.
Every move was like that. She knew where to place her blade and when. She knew how hard to strike and when to turn.
She felt the eyes of the entire village upon them as the twins circled each other. And with each blow she felt the shift in the villagers' gazes. Their moods were turning from shock to disbelief, and then to awe. Those around her were understanding what she understood. They saw, perhaps with less clarity, but they saw what she saw. They saw her reasons, they saw her truth, they saw her justice.
When the moment was right, Kela leapt into a spinning strike and landed in a crouch on the ground with her knee on Dar's chest and her blade at his throat.
He looked up into her eyes. He saw then, too. He saw it all.
"What will you do, Kela?" he whispered. "What judgment will you pass? I am guilty."
Kela realized that for the first time in their lives she had the power. And she realized she did not want it. Power over Dar was not what she had sought. Balance was what they needed.
She smiled down at her brother. "Just as there cannot be light without darkness, day without night, there cannot be innocence without guilt." She removed the blade from Dar's throat and she stood. "Alone I am only one side of a blade. Together we are the sword of Justice." She extended her hand, offering it to Dar. "Will you join me?"
His eyes locked on hers. He took her hand and allowed her to help him up.
For the first time, they stood together before the villagers as equals.
"The man will have a fair trial," Dar said. "Justice will be served here today."
"So say the #emph[Rules of the Reeds] !" the villagers intoned.
The gong sounded.
Kela turned toward the tone. The young girl from the tree stood by the metal plate, holding the hammer. She smiled at Kela.
Kela returned the grin.
|
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/seminars/2024-09-23.typ | typst | Пусть $A_1, A_2, ..., A_k$ --- полная группа событий.
Делаем $n$ испытаний, хотим $m_i$ событий $A_i$, где $m_1 + m_2 + ... + m_k = n$:
$ P = n! dot (p_1^(m_1) p_2^(m_2) ... p_k^(m_k)) / (m_1! m_2! ... m_k!) $
= Задачи
== Задача 10
$ P(A) = P_3(2) + P_3(3) = 3 dot 0.7^2 dot 0.3 + 0.7^3 = 0.784 $
== Задача 11
8-ой выстрел --- обязательно промах
В первых семи --- два промаха
$ P = P_7(5) dot 0.2 = C^5_7 dot 0.8^5 dot 0.2^2 dot 0.2 = 0.058 $
== Задача 18
См. 11
$ P_20(9) dot p = C^9_19 p_9 q_10 dot p = 0.001 $
== Задача 25
$ n = 3 $
$ p = 0.05 $
$ p(n + 1) = 0.05 (3 + 1) = 0.2 $
$ floor(0.2) = 0 $
== Задача 2
$ P(A) = p + (1 - p)^2 p + (1 - p)^4 p $
$ P(B) = (1 - p) p + (1 - p)^3 p + (1 - p)^5 p $
$ P(C) = (1 - p)^6 $
$ P(D) = (1 - p)^6 + (1 - p)^5 p $
== Задача 4
$ P(A-B-A) = P(A) P(B) + (1 - P(A))P(B)P(A) $
$ P(B-A-B) = P(A) P(B) + (1 - P(B))P(A)P(B) $
== Задача
20 мячей:
- 12 новых
- 8 игранных
- извлекают 2, играют, потом возвращают
- потом снова извлекают 2 --- они новые
- с какой вероятностью первые два тоже были новые?
$H_1$ --- первые два оба новые
$H_2$ --- новый -- старый
$H_3$ --- оба старые
$ P(H_1) = C^2_12 / C^2_20 = 33 / 95 $
$ P(H_2) = (C^1_12 C^1_8) / C^2_20 = 48/95 $
$ P(H_3) = C^2_8 / C^2_20 = 14/95 $
$A$ --- вторые два мяча новые
$ P(A | H_1) = C^2_10 / C^2_20 = 9/38 $
$ P(A | H_2) = (C^1_10 C^1_20) / C^2_10 = 11/38 $
$ P(A | H_3) = C^2_12 / C^2_20 = 11/38 $
$ P(H_1 | A) = (P(H_1) P(A | H_1)) / (sum^3_(i = 1) P(H_i)P(A | H)i) $
== Задача
4 кубика:
- 3 правильных
- 1 фальшивый $P(6) = 1/2; P(i) = 0.1$
$H_1$ --- выбрали правильный
$H_2$ --- выбрали фальшивый
$A$ --- выпала шестерка
$ P(A | H_1) = 1/6 $
$ P(A | H_2) = 1/2 $
$ P(H_2 | A) = (P(A | H_2)P(H_2)) / (P(A | H_2)P(H_2) + P(A | H_1)P(H_1)) $
|
|
https://github.com/wyatt-feng/sustech-ug-thesis-typst | https://raw.githubusercontent.com/wyatt-feng/sustech-ug-thesis-typst/main/README.md | markdown | Other | # Typst Template for SUSTech UG Thesis<br/>南科大本科生毕业设计Typst模版

The full PDF file is available [here](./resources/sample.pdf), which includes the basic syntax of Typst.
## Usage
The templates in both languages are crafted based on the
[official template](https://tao.sustech.edu.cn/studentService/graduation_project.html), but discrepancies exist between
this template and the formal guideline. (I myself used this template in my ug thesis and there weren't any problems for
me though.) If you come across a problem, please raise an issue or consider fixing it and raising a pull request.
- Install the latest version of [Typst](https://github.com/typst/typst). It's way easier and faster than Latex!
- Download and extract the entire project
- Modify `metadata.typ` and `thesis.typ`
- Run `typst compile thesis.typ --font-path resources/fonts` to compile the thesis
- Alternatively, you can run `typst watch thesis.typ --font-path resources/fonts` to preview the result as you type
Do **NOT** use it in the official Typst web app because it will take forever to load every time you open the document.
## TODO
- ~Tables and images, including captions~
- ~Footnotes~
- ~Bibliography~
- ~English version~
- Upload to the official template repo
## Acknowledgement
This template is based on lucifer1004's *excellent* project [pkuthss-typst](https://github.com/lucifer1004/pkuthss-typst). It did most of the dirty job and helped me understand Typst and templates.
|
https://github.com/Joelius300/hslu-typst-template | https://raw.githubusercontent.com/Joelius300/hslu-typst-template/main/README.md | markdown | MIT License | # HSLU Typst Template
Simple [Typst](https://typst.app/) template for HSLU theses ([demo](main.pdf)). It's built from scratch, but I took some valuable inspiration from [DarkDampSquib/hslu_template_typst](https://github.com/DarkDampSquib/hslu_template_typst) for external packages.
Since the template is in German anyway, I'll switch language now. If you want to port it to another language, I'll gladly add a link to your repo.
Ganz grundsätzlich: Es muss vor allem für die Betreuungsperson stimmen; sprecht euch also gut mit ihr ab bezüglich Deckblatt, Schrift, Kapitel, Überschriften, Referenzierung, etc. also eigentlich allem!
## Eigenschaften
- Automatisches Deckblatt (Port von "Seiten 1-3 Bachelorarbeit.tex")
- Schriftgrösse, Zeilenabstand, etc. sind von dem häufig referenzierten Buch "Wissenschaftliches Arbeiten" von <NAME> übernommen (und mit Betreuuer abgesprochen).
- Aufgeteilt in mehrere Dateien nach Hauptkapitel (von "Aufbau Bericht.pdf" vorgegeben) und mit Anforderungen vorgefüllt
- Automatische Seitenzahlen mit unterschiedlicher Nummerierung in Front- und Back-matter vs Hauptteil (mithilfe von [tingerrr/anti-matter](https://github.com/tingerrr/anti-matter))
- Automatische Titel-, Bild-, Formel- und Tabellennummerierung mit Kapitelunterteilung (mithilfe von [RubixDev/typst-i-figured](https://github.com/RubixDev/typst-i-figured))
- Automatische Inhaltsverzeichnisse inkl. Abkürzungs-, Bild-, Formel- und Tabellenverzeichnis
- Automatische TODO-Liste mit Seitenzahlen
- Helferfunktionen wie `eq` (Formel) und `img` (Bild) mit Beispielen
- Referenzen und Bibliografie mit BibTeX (beispielsweise). Ich empfehle aus [Zotero](https://www.zotero.org/) zu exportieren.
Da Typst PDF/A noch nicht unterstützt, muss das nachträglich konvertiert werden, z.B. mit Adobe Acrobat.
## Lizenz
MIT
Entsprechend bitte ich um eine kurze Referenz, wenn das Template in einer Arbeit verwendet wird.
Gerne könnt ihr das Template forken, verbessern und erweitern damit alle profitieren können.
## Dev Setup
Neben der [Web-App](https://typst.app/) kann auch lokal mit Typst gearbeitet werden.
Ich verwende dazu:
- [Neovim](https://neovim.io/) with [AstroNvim](https://astronvim.com/)
- [nvarner/typst-lsp](https://github.com/nvarner/typst-lsp) (installed with [mason-lspconfig.nvim](https://github.com/williamboman/mason-lspconfig.nvim))
- [kaarmu/typst.vim](https://github.com/kaarmu/typst.vim)
- [chomosuke/typst-preview.nvim](https://github.com/chomosuke/typst-preview.nvim)
- [LanguageTool](https://languagetool.org/) and [ltex-ls](https://github.com/valentjn/ltex-ls) (again with mason-lspconfig) as writing aid
Ich habe auch gutes gehört von der [VSCode(ium) Extension](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp) von [typst-lsp](https://github.com/nvarner/typst-lsp) zusammen mit der [VSCode(ium) Extension](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) von [typst-preview](https://github.com/Enter-tainer/typst-preview).
|
https://github.com/piepert/grape-suite | https://raw.githubusercontent.com/piepert/grape-suite/main/src/template/main.typ | typst | MIT License | #import "@preview/grape-suite:1.0.0": seminar-paper, german-dates
#set text(lang: "de")
#show: seminar-paper.project.with(
title: "Die Intensionalität von dass-Sätzen",
subtitle: "Intensionale Kontexte in philosophischen Argumenten",
university: [Universität Musterstadt],
faculty: [Exemplarische Fakultät],
institute: [Institut für Philosophie],
docent: [Dr. <NAME> Beispielprüferin],
seminar: [Beispielseminar],
submit-to: [Eingereicht bei],
submit-by: [Eingereicht durch],
semester: german-dates.semester(datetime.today()),
author: "<NAME>",
email: "<EMAIL>",
address: [
12345 Musterstadt \
Musterstraße 67
]
)
= Einleitung
#lorem(100)
#lorem(100)
= Hauptteil
#lorem(100)
#lorem(100)
== These
#lorem(200)
== Antithese
#lorem(100)
#lorem(200)
== Synthese
#lorem(100)
#lorem(200)
= Fazit
#lorem(100)
#lorem(100) |
https://github.com/timetraveler314/Note | https://raw.githubusercontent.com/timetraveler314/Note/main/24/FPAA.typ | typst | #import "@local/MetaNote:0.0.1" : *
#let detm = math.mat.with(delim: "|")
#show: doc => MetaNote(
title: [
Functional Programming with Abstract Algebra,
],
authors: (
(
name: "timetraveler314",
affiliation: "University of Genshin",
email: "<EMAIL>",
),
),
doc,
)
#let opl = math.plus.circle
#let ip(x,y) = $lr(angle.l #x, #y angle.r)$
#let ip3(x,y,z) = $lr(angle.l #x, #y, #z angle.r)$
#let comp = math.circle.small
=
== Basic Structures
#definition("(Left) Semigroup Action")[
Let $angle.l M, opl angle.r $ be a semigroup and $S$ be a set. A (left) semigroup action of $M$ on $S$ is a function $dot : M times S -> S$ such that for all $m, n in M$ and $s in S$,
$
(m opl n) dot s = m dot (n dot s)
$
#example[
Consider the semigroup $ip(RR, +)$ and the vector set $RR^2$. The function $arrow.ccw : RR times RR^2 -> RR^2$ defined by a counter-clockwise rotation of $s$ by angle $m$ is a semigroup action.
$
(alpha + beta) arrow.ccw s = alpha arrow.ccw (beta arrow.ccw s)
$
]
]
Extending actions to monoids is straightforward by adding the requirement that $
epsilon dot s = s.
$
== Monoid Constructions
How to construct a monoid out of a given monoid, a type and the arrow constructor?
#definition("Pointwise Monoid")[
Let $M$ be a monoid and $S$ be a set. The pointwise monoid of $M$ and $S$ is the set of all functions $S -> M$ with the operation of pointwise multiplication.
$
(f opl g)(s) = f(s) opl g(s), \
epsilon(s) = epsilon
$
]
How to upgrade a semigroup to a monoid?
#example("Free Monoid from Semigroup")[
Use ```hs Maybe```. ```hs Maybe M``` is a monoid with ```hs Nothing``` as the identity element and ```hs Just m``` as the non-identity element.
]
==== Cayley Representation
```hs
rep :: [a] -> ([a] -> [a])
rep xs = (xs ++)
abs :: ([a] -> [a]) -> [a]
abs f = f []
```
$
ip3([A], ++, []) <->
ip3([A]->[A], comp, id)
$
The idea works for any monoid.
#definition("Cayley Representation")[
Let $M$ be a monoid. The Cayley representation of $M$ is the set of all functions $M -> M$ with the operation of function composition.
$
(f comp g)(m) = f(g(m)), \
id(m) = m
$
]
#definition("Free Monoid")[
Let $S$ be a set. The free monoid generated by $S$ is the set of all finite sequences of elements of $S$ with the operation of concatenation.
]
= Day 2 : Automatic Differentiation
== Structures
=== Semiring Module ("Scalar Product")
```hs
class (Semiring d, Monoid e)
=> Module d e | e -> d where
(.*.) :: d -> e -> e
```
= Day 3 : PLP/Graded Monoids
= Day 4 : |
|
https://github.com/eduardz1/Bachelor-Thesis | https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/chapters/software-components.typ | typst | #import "../utils/common.typ": *
= Software Components <software-components>
The following is an overview of the software components it was necessary to
write to achieve our goals. The codebase is encompassed in different modules
with each being responsible for a distinct task, in particular, we have:
- A scheduler and controller module that is responsible for scheduling the
execution of the SMOL program and remotely controlling the actuators that we'll
treat in @smol-scheduler.
- A data collector module that is responsible for the collection of data collected
by the different sensors that we'll treat in @data-collector-program.
- A module that contains the actuators scripts and is remotely called by the
scheduler module, we'll treat it in @actuators-script.
- The asset model used to formally describe the greenhouse and that we'll treat in
@asset-model.
- The SMOL program serves as a proof of concept for the language and will be
treated in @smol-twinning-program.
#_content(
[
== SMOL Scheduler <smol-scheduler>
The SMOL scheduler is the main program that controls the execution of the SMOL
code and, in doing so, schedules the actuators. It's also responsible for
starting the data collectors. All of these operations are done remotely via the
SSH protocol on a local network.
More precisely, the scheduler is a Java program that interfaces with the #link(<smol-twinning-program>)[SMOL Twinning Program] and
extracts the data from a knowledge graph generated by SMOL via semantical
lifting of the program state.
For example, when searching for the plants that need to be watered, the
scheduler will query the lifted state and save the results in a `ResulSet`
object. The `ResultSet` object contains the IDs of the plants that need to be
watered.
```Java
var repl = new REPL(settings);
var query =
"PREFIX prog: <https://github.com/Edkamb/SemanticObjects/Program#>\n" +
"SELECT ?plantID " +
"WHERE { ?plantsToWater prog:Plant_plantId ?plantID}";
var plantsToWater = repl
.getInterpreter()
.query(query);
```
where `Plant` is a class defined in the SMOL program that has a `plantId`
property.
At this point, the ResultSet can be passed to a method `waterControl` that will
start the actuators responsible for the plants listed.
```java
waterControl(plantsToWater);
private static void waterControl(
ResultSet plantsToWater
) {
var reader = new GreenhouseModelReader(
greenhouseAssetModelFile,
ModelTypeEnum.ASSET_MODEL
);
// list of pump pins to activate
var pumpPins = new ArrayList<Integer>();
while (plantsToWater.hasNext()) {
var plantToWater = plantsToWater.next();
var plantId = plantToWater
.get("?plantId")
.asLiteral()
.toString();
pumpPins
.add(reader.getPumpPinForPlant(plantId));
}
startWaterActuator(pumpPins);
}
```
`startWaterActuator` will simply iterate over the pins and via SSH send the
command:
```bash
cd /home/pi/greenhouse_actuator && python3 -m actuator water <pin>
```
In the SMOL program, the check for the plants that need to be watered is done
with a simple while loop that compares the current moisture of the plant by
querying the Influx database for the ideal moisture that is associated with the
individual in the asset model and deciding based on the difference whether the
plant should be watered or not. The next step would be to automate the process
by running a simulation (by designing an FMU) of the greenhouse and using the
results of the simulation to decide when to water the plants and update the
simulation accordingly when the predicted values diverge from the real ones.
== Greenhouse Asset Model <asset-model>
The asset model serves as an interface between the physical system - the
greenhouse - and the digital system - the digital twin -. It contains an
organized description of the physical system, including its components, their
properties, and their relationships. To describe the greenhouse we used the
`OWL` language, a semantic web language that follows the `RDF` specification.
We can see how the data is organized by comparing the graph of the relationships
between the `Basilicum`, the `Plant`, and the `HealthState` classes.
#figure(
image("../img/basilicum-plant-healthstate.svg"),
caption: "Relationships between the Basilicum, Plant, and HealthState classes",
)
In our asset model, we would formalize the relationships as follows:
```turtle
@prefix : <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#> .
@prefix ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@base <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse> .
<http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse> rdf:type owl:Ontology .
###############################################
# Object Properties
###############################################
ast:hasHealthState
rdf:type owl:ObjectProperty ;
rdfs:subPropertyOf owl:topObjectProperty ;
rdfs:domain ast:Plant ;
rdfs:range ast:HealthState .
###############################################
# Classes
###############################################
ast:Basilicum rdf:type owl:Class ;
rdfs:subClassOf ast:Plant .
ast:Plant rdf:type owl:Class ;
owl:hasKey ( ast:hasPlantId ) .
ast:HealthState rdf:type owl:Class .
###############################################
# Data Properties
###############################################
ast:hasMaxNdvi rdf:type owl:DatatypeProperty ;
rdfs:domain ast:HealthState ;
rdfs:range xsd:double .
ast:hasMinNdvi rdf:type owl:DatatypeProperty ;
rdfs:domain ast:HealthState ;
rdfs:range xsd:double .
ast:hasIdealMoisture rdf:type owl:DatatypeProperty ;
rdfs:domain ast:Plant ;
rdfs:range xsd:double .
ast:hasIdealTemperature
rdf:type owl:DatatypeProperty ;
rdfs:domain ast:Plant ;
rdfs:range xsd:double .
ast:hasPlantId rdf:type owl:DatatypeProperty ;
rdfs:domain ast:Plant ;
rdfs:range xsd:string .
```
We can see that we define the namespaces at the top of the document to make the
rest of the definition more readable, the namespaces enable us to use standard
definitions, for example when we use the `owl:ObjectProperty` class what we are
using is the
```
http://www.w3.org/2002/07/owl#ObjectProperty
```
class that is defined as
```turtle
owl:ObjectProperty a rdfs:Class ;
rdfs:label "ObjectProperty" ;
rdfs:comment "The class of object properties." ;
rdfs:isDefinedBy <http://www.w3.org/2002/07/owl#> ;
rdfs:subClassOf rdf:Property .
```
We have also defined the `ast` namespace that we use to define the classes and
properties that are specific to our asset model.
== SMOL Twinning program <smol-twinning-program>
The `SMOL` program is run by the host computer and is responsible for the
creation of the digital twin of the greenhouse.
It achieves this in the following steps:
+ It reads the #link(<asset-model>)[`asset model`] from the `OWL` file
+ It generates `SMOL` objects from the asset model individuals
+ For each asset object it retrieves the sensor data associated with that specific
asset from the database (i.e. the moisture of a pot)
+ After retrieving the data it performs the semantic lifting of the program state,
creating a knowledge graph that represents the state of the assets in the
greenhouse
To interface with the Asset Model we created a SMOL class with methods that
retrieve the instances of the classes in the asset model. The class is called
`AssetModel` and is defined as follows:
```smol
/**
* Retrieves data from the asset model and
* converts it to SMOL objects
*/
class AssetModel()
// get pot instances from the asset model
List<Pot> getPots()
List<Pot> pots = construct("
PREFIX ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#>
SELECT ?shelfFloor ?groupPosition ?potPosition
WHERE {
?pot rdf:type ast:Pot ;
ast:hasShelfFloor ?shelfFloor ;
ast:hasGroupPosition ?groupPosition ;
ast:hasPotPosition ?potPosition .
}");
return pots;
// edit query to get new pots
end
// get shelf instances from the asset model
List<Shelf> getShelves()
List<Shelf> shelves = construct("
PREFIX ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#>
SELECT ?shelfFloor
WHERE {
?shelf rdf:type ast:Shelf ;
ast:hasShelfFloor ?shelfFloor .
}
");
return shelves;
end
// get pump instances from the asset model
List<Pump> getPumps()
List<Pump> pumps = construct("
PREFIX ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#>
SELECT ?shelfFloor ?groupPosition
WHERE {
?pump rdf:type ast:Pump ;
ast:hasShelfFloor ?shelfFloor ;
ast:hasGroupPosition ?groupPosition.
}
");
return pumps;
end
// get plant instances from the asset model
List<Plant> getPlants()
List<Plant> plants = construct("
PREFIX ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#>
SELECT ?plantId ?idealMoisture
WHERE {
?plant rdf:type ast:Plant ;
ast:hasPlantId ?plantId ;
ast:hasIdealMoisture ?idealMoisture .
}
");
return plants;
end
// get health state instances from the asset model
List<HealthState> getHealthStates()
List<HealthState> healthStates = construct("
PREFIX ast: <http://www.semanticweb.org/gianl/ontologies/2023/1/sirius-greenhouse#>
SELECT ?name ?minNdvi ?maxNdvi
WHERE {
?healthState rdf:type ast:HealthState ;
ast:hasName ?name ;
ast:hasMinNdvi ?minNdvi ;
ast:hasMaxNdvi ?maxNdvi .
}
");
return healthStates;
end
Unit printAssetModelData()
...
end
end
```
Here we see that the syntax of `SMOL` is very intuitive, with the `end` keyword
used to delineate code blocks.
We see that each class has a method that retrieves the instances of that class
from the asset model. The `construct` top-level expression constructs a list of
new objects from a `SPARQL` query @smol. An example of how the classes are
defined in `SMOL` is the following:
```smol
/**
* Represents a physical Plant. Should be
* retrieved from the asset model via
* AssetModel.getPlants() Each plant is
* contained in a Pot. The Pot contains
* the information about which plant
* it contains.
*/
class Plant(String plantId, Double idealMoisture, String healthState)
Double getNdvi()
Double healthState = 0.0;
List<Double> influxReturn = null;
influxReturn = access(
"from(bucket: \"greenhouse_test\")
|> range(start: -30d)
|> filter(fn: (r) => r[\"_measurement\"] == \"ast:plant\")
|> filter(fn: (r) => r[\"_field\"] == \"ndvi\")
|> filter(fn: (r) => r[\"plant_id\"] == %1)
|> keep(columns: [\"_value\"])
|> last()",
INFLUXDB("config_local.yml"),
this.plantId);
healthState = influxReturn.get(0);
return healthState;
end
Double getPotMoisture()
Double moisture = 0.0;
List<Double> influxReturn = null;
influxReturn = access(
"from(bucket: \"greenhouse_test\")
|> range(start: -30d)
|> filter(fn: (r) => r[\"_measurement\"] == \"ast:pot\")
|> filter(fn: (r) => r[\"_field\"] == \"moisture\")
|> filter(fn: (r) => r[\"plant_id\"] == %1)
|> keep(columns: [\"_value\"])
|> last()",
INFLUXDB("config_local.yml"),
this.plantId);
moisture = influxReturn.get(0);
return moisture;
end
end
```
Here we see a second top-level expression, the `access expression`, also called
`query expression`, used to retrieve a list of literals or lifted objects using
a query mode `SPARQL` to access the semantically lifted state or `INFLUXDB` to
access an external InfluxDB database @smol. In our case, we use the `INFLUXDB`
query mode to retrieve the values of the sensors from the database.
What is loaded into the program state is a digital twin of the physical
greenhouse, with objects that mirror the physical objects and their properties.
== Data Collector Program <data-collector-program>
To collect data from the sensors connected to the greenhouse we wrote a Python
program that retrieves the data and uploads them to InfluxDB.
The repository is located at the address
https://github.com/N-essuno/greenhouse-data-collector.
The project directory structure is organized as follows:
```
.
├── .github
│ └── workflows
│ └── black.yml
├── collector
│ ├── __init__.py
│ ├── __main__.py
│ ├── assets
│ │ ├── __init__.py
│ │ ├── asset.py
│ │ ├── greenhouse_asset.py
│ │ ├── measurement_type.py
│ │ ├── plant_asset.py
│ │ ├── pot_asset.py
│ │ ├── pump_asset.py
│ │ ├── shelf_asset.py
│ │ └── utils.py
│ ├── config.ini.example
│ ├── config.py
│ ├── demo
│ │ ├── __init__.py
│ │ └── demo_influx.py
│ ├── influx
│ │ ├── __init__.py
│ │ └── influx_controller.py
│ ├── sensors
│ │ ├── __init__.py
│ │ ├── humidity.py
│ │ ├── interpreter.py
│ │ ├── light_level.py
│ │ ├── mcp3008.py
│ │ ├── moisture.py
│ │ ├── ndvi.py
│ │ ├── temperature.py
│ │ └── water_level.py
│ └── tests
│ ├── __init__.py
│ ├── config_test.ini
│ ├── random_measurements.py
│ ├── test_config_eval.py
│ └── test_influx_controller.py
├── .gitignore
├── .pre-commit-config.yaml
├── README.md
├── requirements.txt
└── scripts
└── load_random_data.py
```
The project features a `requirements.txt` file that lists all the dependencies
needed to run the program.
There is a script `load_random_data.py` that can be used to load random data
into the database. It can be used to test the program without having to connect
the sensors to the Raspberry Pi.
The `pre-commit-config.yaml` file is used to configure the pre-commit hooks that
are run before every commit by leveraging the #link("https://pre-commit.com/")[pre-commit] Python
framework. The hooks are used to format the code, reorder imports, and
statically check for errors.
The `.github` folder contains the CI configuration file that is used to check
that the code is formatted correctly and can be extended to run the tests in the
future.
In the `test` folder there are some tests that verify the correct functionality
of the program.
=== The Collector Module <collector-module>
The program is structured as a Python module. The main module is the `collector`
module. It contains the `__main__.py` file which is the entry point of the
program. It also contains the `config.py` file that is responsible for reading
the configuration file and making it available to the rest of the program. The
configuration file is in a `.ini` format, in the main module we include an
example file that can be used as a template. The configuration file enables the
user to configure the following parameters:
```ini
[influx2]
url=
org=
token=
[pots]
# moisture_adc_channel refers to the channel in the Analog to Digital Converter
pot_1={"shelf_floor":"1", "group_position":"left", "pot_position":"left", "moisture_adc_channel":1, "plant_id":"1"}
pot_2={"shelf_floor":"1", "group_position":"left", "pot_position":"right", "moisture_adc_channel":2, "plant_id":"2"}
[shelves]
shelf_1={"shelf_floor":"1", "humidity_gpio_pin":4, "temperature_gpio_pin":4}
[plants]
plant_1={"plant_id":"1"}
plant_2={"plant_id":"2"}
[sensor_switches]
use_infrared_sensor=false
use_light_sensor=false
[moisture_values]
XP=[2.45, 1.2]
[water_level_values]
XP=[1.1, 2.0]
[light_level_values]
XP=[80, 180]
```
The numbers in the configuration file are what we used for our sensors after
calibrating them, `pots`, `shelves`, and `plants` are read as dictionaries that
represent the asset model of the greenhouse, and `sensor_switches` is used to
enable or disable the readout of some of the sensors, `moisture_values`,
`water_level_values` and `light_level_values` are the values used to calibrate
the sensors, we'll talk more about this later on in @sensors.
The collector module is composed of the following submodules:
- `assets`
- `demo`
- `influx`
- `sensors`
- `tests`
=== Assets
Used to represent the various assets in our database as classes, having used the
Python `ABC` module to help us with better class inheritance, we can get an idea
of how each of them works just by looking at an excerpt of the `Asset` class.
```python
import logging
import sys
import threading
import time
import traceback
from abc import ABC, abstractmethod
from influxdb_client import Point
from collector.influx.influx_controller import InfluxController
class Asset(ABC):
stop_flag = threading.Event()
influx_controller = InfluxController()
sensor_read_interval = 5
def set_sensor_read_interval(
self, sensor_read_interval: int
) -> None:
"""
Sets the sensor read interval in seconds
"""
self.sensor_read_interval = sensor_read_interval
@abstractmethod
def to_point(self) -> Point:
"""
Convert the asset to a point. Returns a
point with the fields and tags of the asset
"""
pass
@abstractmethod
def stop_sensor(self):
pass
def read_sensor_data(self) -> None:
"""
Read sensor data and write a point to
influxdb. The point is created by the
to_point() method. Repeat every
sensor_read_interval seconds.
"""
try:
bucket = self.influx_controller.get_bucket("greenhouse")
while not self.stop_flag.is_set():
point = self.to_point()
self.influx_controller.write_point(
point, bucket
)
time.sleep(self.sensor_read_interval)
except Exception as e:
self.stop_sensor()
sys.exit(1)
self.stop_sensor()
sys.exit(0)
def stop_thread(self):
self.stop_flag.set()
def reset_stop_flag(self):
self.stop_flag.clear()
```
We can see the way that the `to_point` and `stop_sensor` methods are implemented
by looking, as an example, at an excerpt of the `ShelfAsset` class.
```python
from dataclasses import dataclass...
@dataclass
class ShelfAsset(Asset):
"""
Class representing The Shelf Asset
Attributes:
sh_floor (str): floor of the shelf, 1 or 2
humidity_sensor (Humidity)
temp_sensor (Temperature)
"""
sh_floor: str
hum_sensor: Humidity
temp_sensor: Temperature
_typ = MeasurementType.SHELF.get_measurement_name()
def __post_init__(self):
if self.sh_floor != "1" and
self.sh_floor != "2":
raise ValueError(
"sh_floor must be 1 or 2"
)
def to_point(self) -> Point:
return (
Point(self._typ)
.tag("shelf_floor", self.sh_floor)
.field(
"temperature",
self.temp_sensor.read()
)
.field(
"humidity",
self.hum_sensor.read()
)
)
def stop_sensor(self):
self.temperature_sensor.stop()
```
In general with each asset, we initialize some class variables and verify that
the value they are initialized with is valid (using the `__post_init__` method).
Here `_typ` turns out to be equivalent to the string `ast:shelf` which is the
asset type prefixed by the namespace `ast`, required in InfluxDB. The point is
then decorated with the tags and fields that are specific to the asset.
This way of structuring the Asset classes makes it very easy to extend the
program to support new assets.
=== Influx <influx-python>
The `influx` module is a wrapper around the `influxdb_client` library. It
contains a class `InfluxController` that is responsible for creating the client
and the bucket and for writing points to the database.
The class is treated as a singleton so that only one instance of it can be
created. This is done by using the `__new__` method, executed at the object's
allocation in memory.
```python
from typing import Iterable, Optional, Union...
class InfluxController:
"""
Singleton, handles the connection to InfluxDB
Attributes:
_instance: the singleton instance
_client: the InfluxDB client used to interact with the database
"""
_instance = None
_client = InfluxDBClient
.from_config_file(CONFIG_PATH)
def __new__(cls):
"""
Create a new instance of the class if it
does not exist, otherwise, return the
existing one
"""
if cls._instance is None:
cls._instance = super(
InfluxController, cls
).__new__(cls)
return cls._instance
def delete_bucket(
self,
bucket_name: str
) -> bool:
...
def get_bucket(
self, bucket_name: str
) -> Optional[Bucket]:
...
def create_bucket(
self,
bucket_name: str
) -> Bucket:
...
def write_point(
self,
point: Union[Point, Iterable[Point]],
bucket: Bucket
) -> bool:
...
def close(self):
self._client.close()
```
=== Sensors <sensors>
The `sensors` module contains the classes that represent the sensors connected
to the Raspberry Pi. Each sensor class has a method `read` that returns the
value measured, in cases such as the moisture sensor, the value needs to be
converted to a number that makes sense as a measurement, in this case a
percentage. When such a conversion is needed, the class feeds the value to an
interpreter as we can see below.
```python
from collector.sensors.interpreter import Interpreter
from collector.sensors.mcp3008 import MCP3008
class Moisture:
def __init__(
self, adc: MCP3008, channel: int
) -> None:
"""Initializes the Moisture sensor.
Args:
adc (MCP3008): the analog to digital converter
channel (int): the channel of the ADC to which the sensor is connected to
"""
self.interpret = Interpreter("moisture")
.interpret
self.adc = adc
self.channel = channel
def read(self) -> float:
return self.interpret(
self.adc.read(self.channel)
)
def stop(self):
self.adc.close()
```
The `Interpreter` is a class that utilizes the #link("https://numpy.org/")[NumPy] `interp` function
that performs one-dimensional linear interpolation of monotonically increasing
points. Here we can see how the values in the configuration file are used to
convert the raw values.
Having the function cached as a class variable enables us to reuse it for every
value that needs to be converted, leading to a noticeable performance
improvement.
```python
import json
import numpy as np
from collector.config import CONFIG_PATH
try:
# >3.2
from configparser import ConfigParser
except ImportError:
# python27
# Refer to the older SafeConfigParser as ConfigParser
from configparser import SafeConfigParser as ConfigParser
class Interpreter:
"""
Class that interprets raw values from sensors
to meaningful values. Uses linear inter-
polation, a variable number of points can
be used to define the interpolation function
"""
def __init__(
self, sensor: str, range: tuple = (0, 100)
):
conf = ConfigParser()
conf.read(CONFIG_PATH)
self.XP = json.loads(
conf[sensor + "_values"]["XP"]
)
self.FP = np.linspace(
range[0], range[1], len(self.XP)
)
# If the first value is greater than the
# last one, reverse the arrays
if self.XP[0] > self.XP[-1]:
self.XP = self.XP[::-1]
self.FP = self.FP[::-1]
def interpret(self, value: float) -> float:
return np.interp(value, self.XP, self.FP)
```
Instead of reading the values from the configuration file as standard single
values, we read them as a #link("https://www.json.org/json-en.html")[JSON], this
enables us to submit multiple values and calculate the interpolation function
even for sensors that don't change voltage linearly.
The NumPy `linspace` function is used to create an array of values that are
linearly spaced between the first and the last value of the `range` tuple with a
length equal to the number of values in the `XP` array. #v(600pt) /* FIXME: remove once issue #466 is implemented */The
arrays `XP` and `FP`, respectively the x-coordinates of the data points and the
y-coordinates of the data points are reversed if the values are not in
ascending order, this way it's possible to use the `interp` function even for
sensors like the moisture sensor that decreases in voltage as the moisture
increases.
=== \_\_main\_\_
The main class serves to start the data collection, it operates in a
multithreaded fashion, starting a thread for each asset. It also handles the
stopping of the threads when the program is interrupted.
== Actuators Script <actuators-script>
As a separate project, we have created a Python module that serves to run the
various scripts for the actuators. Actuators can be pumps (for watering or
fertilization), can be electronic switches for the lights, can be fans for air
circulation, etc...
Being separated into a separate module makes it so that the actuators can be run
remotely from the server running the SMOL scheduler. For instance, to activate
the pump it's sufficient to call the
```python
GPIO.output(pump_pin, GPIO.HIGH)
```
function from the #link("https://pypi.org/project/RPi.GPIO/")[RPi.GPIO] package
and let the voltage be on `HIGH` for a set amount of time before resetting it to
`LOW`.
],
) |
|
https://github.com/xiongyaohua/typst-template-swjtu-thesis | https://raw.githubusercontent.com/xiongyaohua/typst-template-swjtu-thesis/main/test.typ | typst | #set heading(numbering: "1. 1")
= Heading 1
== Heading 2
#set math.equation(numbering: "(1)")
$ a + b $
$ a + b $
$ a + b $
#{
show heading: set align(center)
show heading: set block(above: 5em)
set heading(numbering: "A. 1 ")
[
= Heading 1
== Heading 2
]
}
#{
show heading.where(level: 1): it => {
pagebreak()
it
}
[
= Heading 1
== Heading 2
]
}
#set heading(numbering: none)
= Heading 3 |
|
https://github.com/The1Azreen/Visualization-of-Choropleth-Map-of-Resident-Population-Density-in-Singapore-Archived- | https://raw.githubusercontent.com/The1Azreen/Visualization-of-Choropleth-Map-of-Resident-Population-Density-in-Singapore-Archived-/main/Team_3_Poster.typ | typst | // Some definitions presupposed by pandoc's typst output.
#let blockquote(body) = [
#set text( size: 0.92em )
#block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body]
]
#let horizontalrule = [
#line(start: (25%,0%), end: (75%,0%))
]
#let endnote(num, contents) = [
#stack(dir: ltr, spacing: 3pt, super[#num], contents)
]
#show terms: it => {
it.children
.map(child => [
#strong[#child.term]
#block(inset: (left: 1.5em, top: -0.4em))[#child.description]
])
.join()
}
// Some quarto-specific definitions.
#show raw.where(block: true): block.with(
fill: luma(230),
width: 100%,
inset: 8pt,
radius: 2pt
)
#let block_with_new_content(old_block, new_content) = {
let d = (:)
let fields = old_block.fields()
fields.remove("body")
if fields.at("below", default: none) != none {
// TODO: this is a hack because below is a "synthesized element"
// according to the experts in the typst discord...
fields.below = fields.below.amount
}
return block.with(..fields)(new_content)
}
#let empty(v) = {
if type(v) == "string" {
// two dollar signs here because we're technically inside
// a Pandoc template :grimace:
v.matches(regex("^\\s*$")).at(0, default: none) != none
} else if type(v) == "content" {
if v.at("text", default: none) != none {
return empty(v.text)
}
for child in v.at("children", default: ()) {
if not empty(child) {
return false
}
}
return true
}
}
#show figure: it => {
if type(it.kind) != "string" {
return it
}
let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none)
if kind_match == none {
return it
}
let kind = kind_match.captures.at(0, default: "other")
kind = upper(kind.first()) + kind.slice(1)
// now we pull apart the callout and reassemble it with the crossref name and counter
// when we cleanup pandoc's emitted code to avoid spaces this will have to change
let old_callout = it.body.children.at(1).body.children.at(1)
let old_title_block = old_callout.body.children.at(0)
let old_title = old_title_block.body.body.children.at(2)
// TODO use custom separator if available
let new_title = if empty(old_title) {
[#kind #it.counter.display()]
} else {
[#kind #it.counter.display(): #old_title]
}
let new_title_block = block_with_new_content(
old_title_block,
block_with_new_content(
old_title_block.body,
old_title_block.body.body.children.at(0) +
old_title_block.body.body.children.at(1) +
new_title))
block_with_new_content(old_callout,
new_title_block +
old_callout.body.children.at(1))
}
#show ref: it => locate(loc => {
let target = query(it.target, loc).first()
if it.at("supplement", default: none) == none {
it
return
}
let sup = it.supplement.text.matches(regex("^45127368-afa1-446a-820f-fc64c546b2c5%(.*)")).at(0, default: none)
if sup != none {
let parent_id = sup.captures.first()
let parent_figure = query(label(parent_id), loc).first()
let parent_location = parent_figure.location()
let counters = numbering(
parent_figure.at("numbering"),
..parent_figure.at("counter").at(parent_location))
let subcounter = numbering(
target.at("numbering"),
..target.at("counter").at(target.location()))
// NOTE there's a nonbreaking space in the block below
link(target.location(), [#parent_figure.at("supplement") #counters#subcounter])
} else {
it
}
})
// 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead
#let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = {
block(
breakable: false,
fill: background_color,
stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"),
width: 100%,
radius: 2pt,
block(
inset: 1pt,
width: 100%,
below: 0pt,
block(
fill: background_color,
width: 100%,
inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) +
block(
inset: 1pt,
width: 100%,
block(fill: white, width: 100%, inset: 8pt, body)))
}
#let poster(
// The poster's size.
size: "'36x24' or '48x36''",
// The poster's title.
title: "Paper Title",
// A string of author names.
authors: "Author Names (separated by commas)",
// Department name.
departments: "Department Name",
// University logo.
univ_logo: "Logo Path",
// Footer text.
// For instance, Name of Conference, Date, Location.
// or Course Name, Date, Instructor.
footer_text: "Footer Text",
// Any URL, like a link to the conference website.
footer_url: "Footer URL",
// Email IDs of the authors.
footer_email_ids: "Email IDs (separated by commas)",
// Color of the footer.
footer_color: "Hex Color Code",
// DEFAULTS
// ========
// For 3-column posters, these are generally good defaults.
// Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters.
// For 2-column posters, you may need to tweak these values.
// See ./examples/example_2_column_18_24.typ for an example.
// Any keywords or index terms that you want to highlight at the beginning.
keywords: (),
// Number of columns in the poster.
num_columns: "3",
// University logo's scale (in %).
univ_logo_scale: "70",
// University logo's column size (in in).
univ_logo_column_size: "10",
// Title and authors' column size (in in).
title_column_size: "20",
// Poster title's font size (in pt).
title_font_size: "48",
// Authors' font size (in pt).
authors_font_size: "36",
// Footer's URL and email font size (in pt).
footer_url_font_size: "30",
// Footer's text font size (in pt).
footer_text_font_size: "24",
// The poster's content.
body
) = {
// Set the body font.
set text(font: "STIX Two Text", size: 18pt)
let sizes = size.split("x")
let width = int(sizes.at(0)) * 1in
let height = int(sizes.at(1)) * 1in
univ_logo_scale = int(univ_logo_scale) * 1%
title_font_size = int(title_font_size) * 1pt
authors_font_size = int(authors_font_size) * 1pt
num_columns = int(num_columns)
univ_logo_column_size = int(univ_logo_column_size) * 1in
title_column_size = int(title_column_size) * 1in
footer_url_font_size = int(footer_url_font_size) * 1pt
footer_text_font_size = int(footer_text_font_size) * 1pt
// Configure the page.
// This poster defaults to 36in x 24in.
set page(
width: width,
height: height,
margin:
(top: 1in, left: 2in, right: 2in, bottom: 2in),
footer: [
#set align(center)
#set text(32pt)
#block(
fill: rgb(footer_color),
width: 100%,
inset: 20pt,
radius: 10pt,
[
#text(font: "Courier", size: footer_url_font_size, footer_url)
#h(1fr)
#text(size: footer_text_font_size, smallcaps(footer_text))
#h(1fr)
#text(font: "Courier", size: footer_url_font_size, footer_email_ids)
]
)
]
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 0.65em)
// Configure lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// 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(24pt, weight: 400)
if it.level == 1 [
// First-level headings are centered smallcaps.
#set align(center)
#set text({ 32pt })
#show: smallcaps
#v(50pt, weak: true)
#if it.numbering != none {
numbering("I.", deepest)
h(7pt, weak: true)
}
#it.body
#v(35.75pt, weak: true)
#line(length: 100%)
] else if it.level == 2 [
// Second-level headings are run-ins.
#set text(style: "italic")
#v(32pt, weak: true)
#if it.numbering != none {
numbering("i.", deepest)
h(7pt, weak: true)
}
#it.body
#v(10pt, weak: true)
] else [
// Third level headings are run-ins too, but different.
#if it.level == 3 {
numbering("1)", deepest)
[ ]
}
_#(it.body):_
]
})
// Arranging the logo, title, authors, and department in the header.
align(center,
grid(
rows: 2,
columns: (univ_logo_column_size, title_column_size),
column-gutter: 10pt,
row-gutter: 20pt,
image(univ_logo, width: univ_logo_scale),
text(title_font_size, title + "\n\n") +
text(authors_font_size, emph(authors) + departments),
)
)
// Start three column mode and configure paragraph properties.
show: columns.with(num_columns, gutter: 64pt)
set par(justify: true, first-line-indent: 0em)
show par: set block(spacing: 0.65em)
// Display the keywords.
if keywords != () [
#set text(24pt, weight: 400)
#show "Keywords": smallcaps
*Keywords* --- #keywords.join(", ")
]
// Display the poster's contents.
body
}
// Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: doc => poster(
title: [Visualization of Choropleth Map of Resident Population Density in Singapore],
// TODO: use Quarto's normalized metadata.
authors: [Azreen, <NAME>, Aloysius, <NAME>],
departments: [~],
size: "36x24",
// Institution logo.
univ_logo: "./images/sit.png",
// Footer text.
// For instance, Name of Conference, Date, Location.
// or Course Name, Date, Instructor.
footer_text: [AAI1001 AY23/24 Tri 3 Team Project],
// Any URL, like a link to the conference website.
footer_url: [~],
// Emails of the authors.
footer_email_ids: [Team 03],
// Color of the footer.
footer_color: "ebcfb2",
// DEFAULTS
// ========
// For 3-column posters, these are generally good defaults.
// Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters.
// For 2-column posters, you may need to tweak these values.
// See ./examples/example_2_column_18_24.typ for an example.
// Any keywords or index terms that you want to highlight at the beginning.
// Number of columns in the poster.
// University logo's scale (in %).
// University logo's column size (in in).
// Title and authors' column size (in in).
// Poster title's font size (in pt).
// Authors' font size (in pt).
// Footer's URL and email font size (in pt).
// Footer's text font size (in pt).
doc,
)
= Introduction
<introduction>
The geographical distribution of Singapore’s population is crucial in urban studies and public policy. Our project examines how demographic characteristics relate to urban planning policies, as illustrated in Figure 1. This visualization, based on data from the Singapore Department of Statistics \(2023), highlights significant demographic changes. Commended for its clarity, our work can be enhanced with interactive elements, expanded temporal ranges, and detailed geospatial mappings. These improvements will offer a more comprehensive view of how urban planning impacts population distribution and housing patterns in Singapore.
= Previous Visualisation
<previous-visualisation>
#figure([
#box(width: 70%,image("images/Figure1.PNG"))
], caption: figure.caption(
position: bottom,
[
Visualization of Choropleth Map of Resident Population Density by the Department of Statistics Singapore \(Singstat 2023)
]),
kind: "quarto-float-fig",
supplement: "Figure",
numbering: "1",
)
<fig-label>
= Strengths
<strengths>
The Choropleth map contains several variables: population distribution \(quantitative) and planning areas \(categorical). Additionally, the visualization includes a heatmap that allow users to delve into subzones to see pattern in land development and population over time.
= Suggested Improvements
<suggested-improvements>
+ Better contrast: Utilize high-contrast colors to improve accessibility for users with visual impairments, ensuring clarity and ease of interpretation for all users. One such example is the use of Color Universal Design \(CUD) colors which are designed to be distinguishable by all users, including those with color vision deficiencies. \(#link("https://jfly.uni-koeln.de/color/")[Okabe and Ito 2008];)
+ Reduced Data Density: Simplify the presentation by reducing the number of data points displayed simultaneously, thus preventing overcrowding and making the visualization more comprehensible.
+ Interactive Elements: Hovering over a country will display a tooltip with detailed information on the population size of a certain region of Singapore as well as the age profile.
+ Expanded Temporal Ranges: Introduce options for users to select specific time periods for analysis, facilitating a deeper exploration of trends over time.
= Implementation
<implementation>
== Data Sources
<data-sources>
- Weekly counts of population data by planning area were obtained from the Singapore Department of Statistics. The data includes the total population, age groups, and planning areas for each year. Data Source from \(#link("https://www.singstat.gov.sg/find-data/search-by-theme/population/geographic-distribution/latest-data")[Singapore Department of Statistics];)
- The geospatial data for the planning areas was obtained from the Master Plan 2019 Planning Area Boundary KML file. Data Source from \(#link("https://www.ura.gov.sg/maps/#master-plan")[Urban Redevelopment Authority \(URA)];)
== Software
<software>
- #emph[dplyr] package is used for data manipulation
- #emph[leaflet] package is used for creating interactive maps
- #emph[sf] package is used for handling spatial data
- #emph[shiny] package is used for building interactive web applications
= Improved Visualisation
<improved-visualisation>
#figure([
#box(width: 75%,image("images/DataVisualization.png"))
], caption: figure.caption(
position: bottom,
[
Visualization of improved Choropleth Map of Resident Population Density by the Department of Statistics Singapore \(Singstat 2023)
]),
kind: "quarto-float-fig",
supplement: "Figure",
)
= Insight
<insight>
We can see how certain regions like Punggol, Jurong West, and Tampines have experienced significant population growth over the years due to new housing development plans in the early 2000s. This visualization allows users to explore the population density of different planning areas in Singapore and observe changes over time.
= Further Suggestions for Interactivity
<further-suggestions-for-interactivity>
We propose implementing dynamic UI updates, such as changing the map title or legend based on selected criteria, and using 'shinycssloaders' for loading animations. Additionally, offering options to download filtered data and visualizations would enhance user experience.
Conditional highlighting based on user-defined criteria, such as population growth or elderly density, and integrating a time slider with play/pause controls for automatic changes over time would provide a more interactive and informative experience
= Conclusion
<conclusion>
The plot can effectively communicate the relationship between the population density in each region of Singapore over time, and additionally allow curious readers to explore the data even further using interactivity.
= References
<references>
+ <NAME>., <NAME>., & <NAME>. \(2023, June 21). Dealing with information overload: A comprehensive review. Frontiers in psychology. https:\/\/www.ncbi.nlm.nih.gov/pmc/articles/PMC10322198/
+ Department of Statistics Singapore. \(2000 - 2023). Singapore Residents by Planning Area / Subzone, Single Year of Age and Sex \(June 2000-2010, June 2011-2020, June 2021, June 2022, June 2023) \[Data set\]. https:\/\/www.singstat.gov.sg/find-data/search-by-theme/population/geographic-distribution/latest-data
+ <NAME>., & <NAME>. \(2008). Color Universal Design \(CUD): How to make figures and presentations that are friendly to Colorblind people. https:\/\/jfly.uni-koeln.de/color/
+ Singapore Department of Statistics. \(2023). Population Trends 2023. https:\/\/www.singstat.gov.sg/-/media/files/publications/population/population2023.ashx
+ Urban Redevelopment Authority \(URA). \(2019). Master Plan 2019 Planning Area Boundary KML. https:\/\/www.ura.gov.sg/maps/\#master-plan
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/plot.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": util, draw, matrix, vector, styles, palette
#import util: bezier
#import "/src/axes.typ"
#import "/src/plot/sample.typ": sample-fn, sample-fn2
#import "/src/plot/line.typ": add, add-hline, add-vline, add-fill-between
#import "/src/plot/contour.typ": add-contour
#import "/src/plot/boxwhisker.typ": add-boxwhisker
#import "/src/plot/util.typ" as plot-util
#import "/src/plot/legend.typ" as plot-legend
#import "/src/plot/annotation.typ": annotate, calc-annotation-domain
#import "/src/plot/bar.typ": add-bar
#import "/src/plot/errorbar.typ": add-errorbar
#import "/src/plot/mark.typ"
#import "/src/plot/violin.typ": add-violin
#import "/src/plot/formats.typ"
#import plot-legend: add-legend
#let default-colors = (blue, red, green, yellow, black)
#let default-plot-style(i) = {
let color = default-colors.at(calc.rem(i, default-colors.len()))
return (stroke: color,
fill: color.lighten(75%))
}
#let default-mark-style(i) = {
return default-plot-style(i)
}
/// Create a plot environment. Data to be plotted is given by passing it to the
/// `plot.add` or other plotting functions. The plot environment supports different
/// axis styles to draw, see its parameter `axis-style:`.
///
/// #example(```
/// plot.plot(size: (2,2), x-tick-step: none, y-tick-step: none, {
/// plot.add(((0,0), (1,1), (2,.5), (4,3)))
/// })
/// ```)
///
/// To draw elements insides a plot, using the plots coordinate system, use
/// the `plot.annotate(..)` function.
///
/// = parameters
///
/// = Options
///
/// You can use the following options to customize each axis of the plot. You must pass them as named arguments prefixed by the axis name followed by a dash (`-`) they should target. Example: `x-min: 0`, `y-ticks: (..)` or `x2-label: [..]`.
///
/// #show-parameter-block("label", ("none", "content"), default: "none", [
/// The axis' label. If and where the label is drawn depends on the `axis-style`.])
/// #show-parameter-block("min", ("auto", "float"), default: "auto", [
/// Axis lower domain value. If this is set greater than than `max`, the axis' direction is swapped])
/// #show-parameter-block("max", ("auto", "float"), default: "auto", [
/// Axis upper domain value. If this is set to a lower value than `min`, the axis' direction is swapped])
/// #show-parameter-block("equal", ("string"), default: "none", [
/// Set the axis domain to keep a fixed aspect ratio by multiplying the other axis domain by the plots aspect ratio,
/// depending on the other axis orientation (see `horizontal`).
/// This can be useful to force one axis to grow or shrink with another one.
/// You can only "lock" two axes of different orientations.
/// #example(```
/// plot.plot(size: (2,1), x-tick-step: 1, y-tick-step: 1,
/// x-equal: "y",
/// {
/// plot.add(domain: (0, 2 * calc.pi),
/// t => (calc.cos(t), calc.sin(t)))
/// })
/// ```)
/// ])
/// #show-parameter-block("horizontal", ("bool"), default: "axis name dependant", [
/// If true, the axis is considered an axis that gets drawn horizontally, vertically otherwise.
/// The default value depends on the axis name on axis creation. Axes which name start with `x` have this
/// set to `true`, all others have it set to `false`. Each plot has to use one horizontal and one
/// vertical axis for plotting, a combination of two y-axes will panic: ("y", "y2").
/// ])
/// #show-parameter-block("tick-step", ("none", "auto", "float"), default: "auto", [
/// The increment between tick marks on the axis. If set to `auto`, an
/// increment is determined. When set to `none`, incrementing tick marks are disabled.])
/// #show-parameter-block("minor-tick-step", ("none", "float"), default: "none", [
/// Like `tick-step`, but for minor tick marks. In contrast to ticks, minor ticks do not have labels.])
/// #show-parameter-block("ticks", ("none", "array"), default: "none", [
/// A List of custom tick marks to additionally draw along the axis. They can be passed as
/// an array of `<float>` values or an array of `(<float>, <content>)` tuples for
/// setting custom tick mark labels per mark.
///
/// #example(```
/// plot.plot(x-tick-step: none, y-tick-step: none,
/// x-min: 0, x-max: 4,
/// x-ticks: (1, 2, 3),
/// y-min: 1, y-max: 2,
/// y-ticks: ((1, [One]), (2, [Two])),
/// {
/// plot.add(((0,0),))
/// })
/// ```)
///
/// Examples: `(1, 2, 3)` or `((1, [One]), (2, [Two]), (3, [Three]))`])
/// #show-parameter-block("format", ("none", "string", "function"), default: "float", [
/// How to format the tick label: You can give a function that takes a `<float>` and return
/// `<content>` to use as the tick label. You can also give one of the predefined options:
/// / float: Floating point formatting rounded to two digits after the point (see `decimals`)
/// / sci: Scientific formatting with $times 10^n$ used as exponet syntax
///
/// #example(```
/// let formatter(v) = if v != 0 {$ #{v/calc.pi} pi $} else {$ 0 $}
/// plot.plot(x-tick-step: calc.pi, y-tick-step: none,
/// x-min: 0, x-max: 2 * calc.pi,
/// x-format: formatter,
/// {
/// plot.add(((0,0),))
/// })
/// ```)
/// ])
/// #show-parameter-block("decimals", ("int"), default: "2", [
/// Number of decimals digits to display for tick labels, if the format is set
/// to `"float"`.
/// ])
/// #show-parameter-block("mode", ("none", "string"), default: "none", [
/// The scaling function of the axis. Takes `lin` (default) for linear scaling,
/// and `log` for logarithmic scaling.])
/// #show-parameter-block("base", ("none", "number"), default: "none", [
/// The base to be used when labeling axis ticks in logarithmic scaling])
/// #show-parameter-block("grid", ("bool", "string"), default: "false", [
/// If `true` or `"major"`, show grid lines for all major ticks. If set
/// to `"minor"`, show grid lines for minor ticks only.
/// The value `"both"` enables grid lines for both, major- and minor ticks.
///
/// #example(```
/// plot.plot(x-tick-step: 1, y-tick-step: 1,
/// y-minor-tick-step: .2,
/// x-min: 0, x-max: 2, x-grid: true,
/// y-min: 0, y-max: 2, y-grid: "both", {
/// plot.add(((0,0),))
/// })
/// ```)
/// ])
/// #show-parameter-block("break", ("bool"), default: "false", [
/// If true, add a "sawtooth" at the start or end of the axis line, depending
/// on the axis bounds. If the axis min. value is > 0, a sawtooth is added
/// to the start of the axes, if the axis max. value is < 0, a sawtooth is added
/// to its end.])
///
/// - body (body): Calls of `plot.add` or `plot.add-*` commands. Note that normal drawing
/// commands like `line` or `rect` are not allowed inside the plots body, instead wrap
/// them in `plot.annotate`, which lets you select the axes used for drawing.
/// - size (array): Plot size tuple of `(<width>, <height>)` in canvas units.
/// This is the plots inner plotting size without axes and labels.
/// - axis-style (none, string): How the axes should be styled:
/// / scientific: Frames plot area using a rectangle and draw axes `x` (bottom), `y` (left), `x2` (top), and `y2` (right) around it.
/// If `x2` or `y2` are unset, they mirror their opposing axis.
/// / scientific-auto: Draw set (used) axes `x` (bottom), `y` (left), `x2` (top) and `y2` (right) around
/// the plotting area, forming a rect if all axes are in use or a L-shape if only `x` and `y` are in use.
/// / school-book: Draw axes `x` (horizontal) and `y` (vertical) as arrows pointing to the right/top with both crossing at $(0, 0)$
/// / left: Draw axes `x` and `y` as arrows, while the y axis stays on the left (at `x.min`)
/// and the x axis at the bottom (at `y.min`)
/// / `none`: Draw no axes (and no ticks).
///
/// #example(```
/// let opts = (x-tick-step: none, y-tick-step: none, size: (2,1))
/// let data = plot.add(((-1,-1), (1,1),), mark: "o")
///
/// for name in (none, "school-book", "left", "scientific") {
/// plot.plot(axis-style: name, ..opts, data, name: "plot")
/// content(((0,-1), "-|", "plot.south"), repr(name))
/// set-origin((3.5,0))
/// }
/// ```, vertical: true)
/// - plot-style (style,function): Styling to use for drawing plot graphs.
/// This style gets inherited by all plots and supports `palette` functions.
/// The following style keys are supported:
/// #show-parameter-block("stroke", ("none", "stroke"), default: 1pt, [
/// Stroke style to use for stroking the graph.
/// ])
/// #show-parameter-block("fill", ("none", "paint"), default: none, [
/// Paint to use for filled graphs. Note that not all graphs may support filling and
/// that you may have to enable filling per graph, see `plot.add(fill: ..)`.
/// ])
/// - mark-style (style,function): Styling to use for drawing plot marks.
/// This style gets inherited by all plots and supports `palette` functions.
/// The following style keys are supported:
/// #show-parameter-block("stroke", ("none", "stroke"), default: 1pt, [
/// Stroke style to use for stroking the mark.
/// ])
/// #show-parameter-block("fill", ("none", "paint"), default: none, [
/// Paint to use for filling marks.
/// ])
/// - fill-below (bool): If true, the filled shape of plots is drawn _below_ axes.
/// - name (string): The plots element name to be used when referring to anchors
/// - legend (none, auto, coordinate): The position the legend will be drawn at. See plot-legends for information about legends. If set to `<auto>`, the legend's "default-placement" styling will be used. If set to a `<coordinate>`, it will be taken as relative to the plot's origin.
/// - legend-anchor (auto, string): Anchor of the legend group to use as its origin.
/// If set to `auto` and `lengend` is one of the predefined legend anchors, the
/// opposite anchor to `legend` gets used.
/// - legend-style (style): Style key-value overwrites for the legend style with style root `legend`.
/// - ..options (any): Axis options, see _options_ below.
#let plot(body,
size: (1, 1),
axis-style: "scientific",
name: none,
plot-style: default-plot-style,
mark-style: default-mark-style,
fill-below: true,
legend: auto,
legend-anchor: auto,
legend-style: (:),
..options
) = draw.group(name: name, ctx => {
draw.assert-version(version(0, 3, 1))
// Create plot context object
let make-ctx(x, y, size) = {
assert(x != none, message: "X axis does not exist")
assert(y != none, message: "Y axis does not exist")
assert(size.at(0) > 0 and size.at(1) > 0, message: "Plot size must be > 0")
let x-scale = ((x.max - x.min) / size.at(0))
let y-scale = ((y.max - y.min) / size.at(1))
if y.horizontal {
(x-scale, y-scale) = (y-scale, x-scale)
}
return (x: x, y: y, size: size, x-scale: x-scale, y-scale: y-scale)
}
// Setup data viewport
let data-viewport(data, x, y, size, body, name: none) = {
if body == none or body == () { return }
assert.ne(x.horizontal, y.horizontal,
message: "Data must use one horizontal and one vertical axis!")
// If y is the horizontal axis, swap x and y
// coordinates by swapping the transformation
// matrix columns.
if y.horizontal {
(x, y) = (y, x)
body = draw.set-ctx(ctx => {
ctx.transform = matrix.swap-cols(ctx.transform, 0, 1)
return ctx
}) + body
}
// Setup the viewport
axes.axis-viewport(size, x, y, none, body, name: name)
}
let data = ()
let anchors = ()
let annotations = ()
let body = if body != none { body } else { () }
for cmd in body {
assert(type(cmd) == dictionary and "type" in cmd,
message: "Expected plot sub-command in plot body")
if cmd.type == "anchor" {
anchors.push(cmd)
} else if cmd.type == "annotation" {
annotations.push(cmd)
} else { data.push(cmd) }
}
assert(axis-style in (none, "scientific", "scientific-auto", "school-book", "left"),
message: "Invalid plot style")
// Create axes for data & annotations
let axis-dict = (:)
for d in data + annotations {
if "axes" not in d { continue }
for (i, name) in d.axes.enumerate() {
if not name in axis-dict {
axis-dict.insert(name, axes.axis(
min: none, max: none))
}
let axis = axis-dict.at(name)
let domain = if i == 0 {
d.at("x-domain", default: (0, 0))
} else {
d.at("y-domain", default: (0, 0))
}
if domain != (none, none) {
axis.min = util.min(axis.min, ..domain)
axis.max = util.max(axis.max, ..domain)
}
axis-dict.at(name) = axis
}
}
// Create axes for anchors
for a in anchors {
for (i, name) in a.axes.enumerate() {
if not name in axis-dict {
axis-dict.insert(name, axes.axis(min: none, max: none))
}
}
}
// Adjust axis bounds for annotations
for a in annotations {
let (x, y) = a.axes.map(name => axis-dict.at(name))
(x, y) = calc-annotation-domain(ctx, x, y, a)
axis-dict.at(a.axes.at(0)) = x
axis-dict.at(a.axes.at(1)) = y
}
// Set axis options
axis-dict = plot-util.setup-axes(ctx, axis-dict, options.named(), size)
// Prepare styles
for i in range(data.len()) {
if "style" not in data.at(i) { continue }
let style-base = plot-style
if type(style-base) == function {
style-base = (style-base)(i)
}
assert.eq(type(style-base), dictionary,
message: "plot-style must be of type dictionary")
if type(data.at(i).style) == function {
data.at(i).style = (data.at(i).style)(i)
}
assert.eq(type(style-base), dictionary,
message: "data plot-style must be of type dictionary")
data.at(i).style = util.merge-dictionary(
style-base, data.at(i).style)
if "mark-style" in data.at(i) {
let mark-style-base = mark-style
if type(mark-style-base) == function {
mark-style-base = (mark-style-base)(i)
}
assert.eq(type(mark-style-base), dictionary,
message: "mark-style must be of type dictionary")
if type(data.at(i).mark-style) == function {
data.at(i).mark-style = (data.at(i).mark-style)(i)
}
if type(data.at(i).mark-style) == dictionary {
data.at(i).mark-style = util.merge-dictionary(
mark-style-base,
data.at(i).mark-style
)
}
}
}
draw.group(name: "plot", {
draw.anchor("origin", (0, 0))
// Prepare
for i in range(data.len()) {
if "axes" not in data.at(i) { continue }
let (x, y) = data.at(i).axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
if "plot-prepare" in data.at(i) {
data.at(i) = (data.at(i).plot-prepare)(data.at(i), plot-ctx)
assert(data.at(i) != none,
message: "Plot prepare(self, cxt) returned none!")
}
}
// Background Annotations
for a in annotations.filter(a => a.background) {
let (x, y) = a.axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
data-viewport(a, x, y, size, {
draw.anchor("default", (0, 0))
a.body
})
}
// Fill
if fill-below {
for d in data {
if "axes" not in d { continue }
let (x, y) = d.axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
data-viewport(d, x, y, size, {
draw.anchor("default", (0, 0))
draw.set-style(..d.style)
if "plot-fill" in d {
(d.plot-fill)(d, plot-ctx)
}
})
}
}
if axis-style in ("scientific", "scientific-auto") {
let draw-unset = if axis-style == "scientific" {
true
} else {
false
}
let mirror = if axis-style == "scientific" {
auto
} else {
none
}
axes.scientific(
size: size,
draw-unset: draw-unset,
bottom: axis-dict.at("x", default: none),
top: axis-dict.at("x2", default: mirror),
left: axis-dict.at("y", default: none),
right: axis-dict.at("y2", default: mirror),)
} else if axis-style == "left" {
axes.school-book(
size: size,
axis-dict.x,
axis-dict.y,
x-position: axis-dict.y.min,
y-position: axis-dict.x.min)
} else if axis-style == "school-book" {
axes.school-book(
size: size,
axis-dict.x,
axis-dict.y,)
}
// Stroke + Mark data
for d in data {
if "axes" not in d { continue }
let (x, y) = d.axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
data-viewport(d, x, y, size, {
draw.anchor("default", (0, 0))
draw.set-style(..d.style)
if not fill-below and "plot-fill" in d {
(d.plot-fill)(d, plot-ctx)
}
if "plot-stroke" in d {
(d.plot-stroke)(d, plot-ctx)
}
})
if "mark" in d and d.mark != none {
draw.scope({
if y.horizontal {
draw.set-ctx(ctx => {
ctx.transform = matrix.swap-cols(ctx.transform, 0, 1)
return ctx
})
}
draw.set-style(..d.style, ..d.mark-style)
mark.draw-mark(d.data, x, y, d.mark, d.mark-size, size)
})
}
}
// Foreground Annotations
for a in annotations.filter(a => not a.background) {
let (x, y) = a.axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
data-viewport(a, x, y, size, {
draw.anchor("default", (0, 0))
a.body
})
}
// Place anchors
for a in anchors {
let (x, y) = a.axes.map(name => axis-dict.at(name))
let plot-ctx = make-ctx(x, y, size)
let pt = a.position.enumerate().map(((i, v)) => {
if v == "min" { return axis-dict.at(a.axes.at(i)).min }
if v == "max" { return axis-dict.at(a.axes.at(i)).max }
return v
})
pt = axes.transform-vec(size, x, y, none, pt)
if pt != none {
draw.anchor(a.name, pt)
}
}
})
// Draw the legend
if legend != none {
let items = data.filter(d => "label" in d and d.label != none)
if items.len() > 0 {
let legend-style = styles.resolve(ctx.style,
base: plot-legend.default-style, merge: legend-style, root: "legend")
plot-legend.add-legend-anchors(legend-style, "plot", size)
plot-legend.legend(legend, anchor: legend-anchor, {
for item in items {
let preview = if "plot-legend-preview" in item {
_ => {(item.plot-legend-preview)(item) }
} else {
auto
}
plot-legend.item(item.label, preview,
mark: item.at("mark", default: none),
mark-size: item.at("mark-size", default: none),
mark-style: item.at("mark-style", default: none),
..item.at("style", default: (:)))
}
}, ..legend-style)
}
}
draw.copy-anchors("plot")
})
/// Add an anchor to a plot environment
///
/// This function is similar to `draw.anchor` but it takes an additional
/// axis tuple to specify which axis coordinate system to use.
///
/// #example(```
/// plot.plot(size: (2,2), name: "plot",
/// x-tick-step: none, y-tick-step: none, {
/// plot.add(((0,0), (1,1), (2,.5), (4,3)))
/// plot.add-anchor("pt", (1,1))
/// })
///
/// line("plot.pt", ((), "|-", (0,1.5)), mark: (start: ">"), name: "line")
/// content("line.end", [Here], anchor: "south", padding: .1)
/// ```)
///
/// - name (string): Anchor name
/// - position (tuple): Tuple of x and y values.
/// Both values can have the special values "min" and
/// "max", which resolve to the axis min/max value.
/// Position is in axis space defined by the axes passed to `axes`.
/// - axes (tuple): Name of the axes to use `("x", "y")` as coordinate
/// system for `position`. Note that both axes must be used,
/// as `add-anchors` does not create them on demand.
#let add-anchor(name, position, axes: ("x", "y")) = {
((
type: "anchor",
name: name,
position: position,
axes: axes,
),)
}
|
https://github.com/Mufanc/hnuthss-template | https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/pages/cover.typ | typst | #import "/configs.typ": font, fontsize
#let basic_info(..info) = [
#let info = info.named()
#set align(center)
#show table.cell.where(x: 0): set text(font: font.sans, size: fontsize.L4)
#show table.cell.where(x: 1): set text(size: fontsize.L3s)
#show table.cell.where(x: 0, y: 0): content => [
#set text(size: fontsize.L2s, weight: 600)
#set par(justify: true)
#content
]
#show table.cell.where(x: 1, y: 0): content => [
#set par(leading: 1.4em, justify: true)
#content
]
#table(
columns: (5.1cm, 7.5cm),
rows: 1.07cm,
// 自动换行的 dirty fix
inset: (x, y) => if x == 1 and y == 0 { (x: 5pt, y: 12pt) } else { 5pt },
align: (x, y) =>
if x == 1 and y == 0 { left + top } // 自动换行的 dirty fix
else if x == 0 { right + bottom }
else if x == 1 { left + bottom },
stroke: (x, y) => if x == 1 { (bottom: 0.1pt) } else { none },
column-gutter: 3pt,
"论文(设计)题目:", info.project,
"", "",
"学 生 姓 名:", info.name,
"学 生 学 号:", info.id,
"专 业 班 级:", info.class,
"学 院 名 称:", info.college,
"指 导 老 师:", info.supervisor
)
]
#let cover(..info) = [
#page(
background: align(center + top)[
#v(3cm)
#image("/assets/logos/logo-grayscale.svg", width: 12cm)
]
)[
#align(center, image("/assets/logos/logo-text-grayscale.svg", width: 7cm))
#v(1.5cm)
#text(size: 45pt, " 本科生毕业论文(设计)")
#v(2.5cm)
#basic_info(..info)
#let date = info.named().date
#align(center + bottom, text(size: fontsize.L4)[
#date.year() 年 #date.month() 月 #date.day() 日
])
]
]
|
|
https://github.com/duskmoon314/THU_AMA | https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch2/3-外部联系.typ | typst | Creative Commons Attribution 4.0 International | #import "/book.typ": *
#show: thmrules
#show: book-page.with(title: "外部联系")
= 外部联系
== 群同态与群同构
回顾:$angle.l a angle.r tilde.equiv lr((bb(Z) , +))$或$lr((bb(Z) \/ n bb(Z) , +))$,其中同构\=双射+保运算
#definition()[
设$lr((G , dot.op)) , lr((G prime , circle.stroked.tiny))$为群,若存在映射$f : G arrow.r G prime$使得$forall a , b in G$均有$f lr((a dot.op b)) = f lr((a)) circle.stroked.tiny f lr((b))$,则称$f$是$G$到$G prime$的一个#strong[同态(homomorphism)]
进一步:
- 单射(injective) + 同态 = #strong[单同态] or #strong[嵌入(monomorphism)] $G arrow.r.hook^f G prime$
- 满射(surjective) + 同态 = #strong[满同态] or #strong[映上(epimorphism)] $G arrow.r.twohead^f G prime$
- 双射(bijective) + 同态 = #strong[同构(isomorphism)] $G arrow.r^tilde_f G'$
]
Imf 像集 $I m f = f lr((G)) = { f lr((g)) \| g in G } subset.eq G prime$,$f$满$arrow.l.r.double f lr((G)) = G prime$
Kerf 核 $K e r f = f^(- 1) lr((e prime)) = { g in G \| f lr((g)) = e prime } subset.eq G$,$K e r f = { e } arrow.l.r.double f$单
#property()[
设$f : G arrow.r G prime$为群同态,则
+ $f lr((e)) = e prime$(保幺元)$f lr((a^(- 1))) = f lr((a))^(- 1)$(保逆元)$f lr((a^n)) = f lr((a))^n$(保方幂)
$f lr((e)) = f lr((e^2)) = f lr((e)) f lr((e)) arrow.r.double f lr((e)) = e prime$
$e prime = f lr((e)) = f lr((a dot.op a^(- 1))) = f lr((a)) f lr((a^(- 1))) arrow.r.double f lr((a^(- 1))) = f lr((a))^(- 1)$ (左逆同理)
+ $H lt.eq G arrow.r.double f lr((H)) lt.eq G prime$(保子群)特别有$I m f = f lr((G)) lt.eq G prime$
$forall f lr((a)) f lr((b)) in f lr((H))$,其中$a , b in H$,$f lr((a)) f lr((b))^(- 1) = f lr((a b^(- 1))) in f lr((H)) arrow.r.double f lr((H)) lt.eq G$
+ $H lt.tri.eq G arrow.r.double f lr((H)) lt.tri.eq f lr((G))$
$forall f lr((h)) in f lr((H)) , forall f lr((g)) in f lr((G)) , f lr((g)) f lr((h)) f lr((g))^(- 1) = f lr((g h g^(- 1))) in f lr((H))$
+ $N lt.eq f lr((G)) = I m f arrow.r.double f^(- 1) lr((N)) lt.eq G$(反向局部保子群)
$forall a , b in f^(- 1) lr((N)) , exists n_1 , n_2 in N$使得$a = f lr((n_1)) , b = f lr((n_2))$
$f lr((a b^(- 1))) = f lr((a)) f lr((b))^(- 1) = n_1 n_2^(- 1) in N arrow.r.double a b^(- 1) in f^(- 1) lr((N)) arrow.r.double f^(- 1) lr((N)) lt.eq G$
+ $N lt.tri.eq f lr((G)) = I m f arrow.r.double f^(- 1) lr((N)) lt.tri.eq G$(反向局部保正规子群),特别当$N = { e }$时,$f^(- 1) lr((N)) = K e r f lt.tri.eq G$
$forall a in f^(- 1) lr((N)) , forall g in G$,设$f lr((a)) = n_1 in N$,
则$f lr((g a g^(- 1))) = f lr((g)) n_1 f lr((g))^(- 1) in N arrow.r.double g a g^(- 1) in f^(- 1) lr((N)) arrow.r.double f^(- 1) lr((N)) lt.tri.eq G$
+ 若$o lr((a)) < oo arrow.r.double o lr((f lr((a)))) \| o lr((a))$(保持阶为因子)
$f lr((a))^(o lr((a))) = f lr((a^(o lr((a))))) = f lr((e)) = e prime arrow.r.double o lr((f lr((a)))) \| o lr((a))$
+ #theorem()[
设$K = K e r f$则
+ $forall a prime in I m f$,若$f lr((a)) = a prime$,则$f^(- 1) lr((a prime)) = a K$
+ $f$为单同态$arrow.l.r.double lr(|K|) = 1$
]
#proof()[
+ $forall k in K , f lr((a k)) = f lr((a)) f lr((k)) = a prime e prime = a prime arrow.r.double a k in f^(- 1) lr((a prime))$
反之,$forall x in f^(- 1) lr((a prime))$
有$f lr((x)) = a prime = f lr((a)) arrow.r.double f lr((a^(- 1) x)) = f lr((a))^(- 1) f lr((x)) = e prime arrow.r.double a^(- 1) x in K = f^(- 1) lr((e prime)) arrow.r.double x in a K arrow.r.double f^(- 1) lr((a prime)) subset.eq a K$
综上,$f^(- 1) lr((a prime)) = a K$
+ f单 $arrow.l.r.double forall a prime in f lr((G)) , a prime$的原像唯一$arrow.l.r.double lr(|a K|) = 1 arrow.l.r.double lr(|K|) = 1 arrow.l.r.double K = { e }$
]
+ 保陪集
]
#theorem("同态基本定理")[
设$f : G arrow.r G prime$为群同态,$K = K e r f$,则
+ $G \/ K tilde.equiv f lr((G))$,特别,若$f$为满同态,则$G \/ K tilde.equiv G prime$
+ 设$pi : G arrow.r.twohead G \/ K$为自然同态,$j : f lr((G)) arrow.r.hook G prime$为嵌入同态,则$f$可分解为$f = j circle.stroked.tiny f^(‾) circle.stroked.tiny pi$,其中$f^(‾) : G \/ K arrow.r f lr((G)) , a^(‾) arrow.r.bar f lr((a))$
]
#proof()[
+ 作对应$f^(‾) : G \/ K arrow.r f lr((G)) = I m f , g K arrow.r.bar f lr((g))$
$g K = g_1 K arrow.l.r.double g^(- 1) g_1 in K arrow.l.r.double f lr((g^(- 1) g_1)) = e prime arrow.l.r.double f lr((g_1)) = f lr((g)) arrow.l.r.double f^(‾) lr((g_1 K)) = f^(‾) lr((g K))$
故$f^(‾)$为映射,且为单射。另一方面,显然满射。下验证其保运算
$f^(‾) lr((g_1 K dot.op g_2 K)) = f^(‾) lr((g_1 g_2 K)) = f lr((g_1 g_2)) = f lr((g_1)) f lr((g_2)) = f^(‾) lr((g_1 K)) dot.op f^(‾) lr((g_2 K))$
故$f^(‾)$为同构
+ $forall g in G , j circle.stroked.tiny f^(‾) circle.stroked.tiny pi lr((g)) = j circle.stroked.tiny f^(‾) lr((g K)) = j lr((f lr((g)))) = f lr((g)) arrow.r.double f = j circle.stroked.tiny f^(‾) circle.stroked.tiny pi$
]
#theorem("子群对应定理")[
设$f : G arrow.r G prime$为满同态,$K = ker f , S = { H |H lt.eq G , K lt.eq H }, S prime = { N| N lt.eq G prime }$,则$S$与$S prime$之间有一一对应。
]
#proof()[
作映射$sigma : S arrow.r S prime , H arrow.r.bar f lr((H))$
验证$sigma$为单射:若$sigma lr((H)) = sigma lr((H_1))$,有$f lr((H)) = f lr((H_1)) arrow.r.double forall h in H , exists h_1 in H_1 , f lr((h)) = f lr((h_1)) arrow.r.double f lr((h_1^(- 1) h)) = e prime arrow.r.double h_1^(- 1) h in K arrow.r.double h in h_1 K subset.eq H_1 arrow.r.double H subset.eq H_1$。同理$H_1 subset.eq H arrow.r.double H = H_1 arrow.r.double sigma$单射
验证$sigma$满射:$forall N in S prime$,令$H = f^(- 1) lr((N))$,由局部反向保子群知$H lt.eq G$。又$K = f^(- 1) lr((e prime)) subset.eq f^(- 1) lr((N)) = H$,故$H subset.eq S$,且$sigma lr((H)) = f lr((H)) = N$,故$sigma$满射
综上,$sigma$为单射且满射,故为双射,即为一一对应
]
#theorem("商群同构定理(第一同构定理)")[
设$f : G arrow.r.twohead G prime$为满同态,$K = ker f , H lt.tri.eq G , K lt.eq H$,则 $ G \/ H tilde.equiv G prime \/ f lr((H)) tilde.equiv frac(G \/ K, H \/ K) $
]
#proof()[
令$H prime = f lr((H))$,故$H prime lt.tri.eq G prime , G prime \/ H prime = f lr((G)) \/ f lr((H)) = { f lr((g)) H prime \| f lr((g)) in G prime }$
作映射$sigma : G arrow.r G prime \/ H prime , g arrow.r.bar f lr((g)) H prime$
验证$sigma$满:由$f$满可证。
验证$sigma$保运算:$sigma lr((g_1 g_2)) = f lr((g_1 g_2)) H prime = f lr((g_1)) f lr((g_2)) H prime = lr((f lr((g_1)) H prime)) lr((f lr((g_2)) H prime)) = sigma lr((g_1)) sigma lr((g_2))$
$ker sigma = { g in G | sigma lr((g)) = f lr((g)) H prime = H prime = e prime H } = { g in G| f lr((g)) in H prime = f lr((H)) } = f^(- 1) lr((H prime))$。由$H prime = f lr((H)) , K lt.eq H$与子群对应定理知$ker sigma = H$。
对$sigma$用同态基本定理有$G \/ ker sigma = G \/ H tilde.equiv G prime \/ H prime = G prime \/ f lr((H))$
由$f : G arrow.r.twohead G prime$知$G \/ K tilde.equiv G prime$。
考虑限制映射(只考虑$H$内的元素,其外的不关心)$f \|_H : H arrow.r f lr((H)) = H prime , h arrow.r.bar f lr((h))$,显然为满同态。
$ker f |_H = {h in H | f lr((h)) = e prime} = {h in H \| h in K} = H sect K = K$
对$f \|_H$用同态基本定理有$H \/ K tilde.equiv f lr((H)) = H prime$,则有$G prime \/ H prime tilde.equiv frac(G \/ K, H \/ K)$
]
#corollary()[
设$N lt.tri.eq H , N lt.tri.eq G , H lt.tri.eq G$,则 $ G \/ H tilde.equiv frac(G \/ N, H \/ N) $
]
#theorem("子群乘积同构定理(第二同构定理)")[
设$N lt.tri.eq G , H lt.eq G$,则$H N \/ N tilde.equiv H \/ lr((H sect N))$
]
#proof()[
仍用基本定理,作映射$phi : H arrow.r H N \/ N , h arrow.r.bar lr((h n)) N = h N$,显然$phi$为满射。
验证保运算:$phi lr((h_1 h_2)) = lr((h_1 h_2)) N = lr((h_1 N)) lr((h_2 N)) = phi lr((h_1)) phi lr((h_2)) arrow.r.double phi$为满同态
$ker phi = {h in H |phi lr((h)) = h N = N} = {h in H| h in N} = H sect N$
对$phi$用同态基本定理有$H \/ ker phi = H \/ lr((H sect N)) tilde.equiv H N \/ N$
]
#example()[
证明:$S_4 \/ K_4 tilde.equiv S_3$
]
#proof()[
$S_3 lt.eq S_4 , K_4 lt.tri.eq S_4 arrow.r.double S_3 K_4 lt.eq S_4$,且$lr(|S_3 K_4|) = frac(lr(|S_3|) lr(|K_4|), lr(|S_3 sect K_4|)) = frac(6 times 4, 1) = 24$,故$S_3 K_4 = S_4 , S_3 sect K_4 = { lr((1)) }$
由子群乘积同构定理,$S_4 \/ K_4 = S_3 K_4 \/ K_4 tilde.equiv S_3 \/ S_3 sect K_4 = S_3$
] |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/009_Mercy.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Mercy",
set_name: "<NAME>",
story_date: datetime(day: 19, month: 11, year: 2014),
author: "<NAME>",
doc
)
The goblin. The stinking goblin. The fat, stinking goblin. Sidisi sat, slumped in her throne, head bare, crown gone—taken right off her head by the accursed goblin. There was little else she had been able to think about in the past few months except for the goblin and what she would do to him and his clan when she got a hold of them. It had become an obsession. One by one, her most trusted advisors had warned her against the course of blind revenge, and one by one they had met their fate at the maw of the Mother Crocodile at the center of the Kheru Temple pit.
#figure(image("009_Mercy/01.jpg", width: 100%), caption: [Jeering Instigator | Art by Willian Murai], supplement: none, numbering: none)
"Jhinu," Sidisi hissed. "I am hungry. Bring me my food."
The crown had once been taken by Sidisi herself, off of the freshly severed head of the previous khan. Like all Sultai khans, she had proven her abilities of trickery and ruthlessness, and created her own destiny. When she dropped his lifeless body into the pits, it was the sign to all other comers at the throne that a similar fate would befall them. The purge of her potential rivals in her first years as khan had left all other challengers afraid to do anything but bow to her, leading to a golden age of calm in Sultai politics. Now, however, the courts at Kheru Temple were uncharacteristically quiet, and it was unclear if the nobles and merchants who usually made up its halls were afraid of Sidisi's famous temper, raising armies of their own to take the throne from her, or simply dead. She had fed so many to the pits. Oh so many.
"My queen," a gaunt, balding man said, bowing as he led an armless Sibsig with a bowl of fruit attached to its head. "I hope this is of your pleasing."
Jhinu had been part of the merchant class, from one of the wealthiest families in the entire Sultai Empire. In an attempt to curry favor, and to get a monopoly on the Niraj River tax collection duties, he delivered to Sidisi the heads of three goblins he claimed to have been the culprits of the sinister act. The ape knew nothing of the Rakshasa magic or that, to the Queen of the Sultai, the dead's lips are as easily moved as those of the living. The three goblins knew nothing of her crown—they were deserters who drowned in an attempt to cross the Niraj, looking to scavenge food from the farms on the far side. Trickery and deception was expected in politics, but there was a high price to getting caught. She kept him alive as a reminder to all that there were fates worse than death.
"Tell me, Jhinu," Sidisi said, putting a grape in her mouth and swallowing it whole. "It has been some time since one of your relatives has come to bargain for your life. Do they no longer care about you, or are there none left?"
"They…they are afraid, my queen." Jhinu said. "They do not wish to displease you with offers not worthy of your magnificence"
Sidisi picked through the fruit, throwing the pieces she had no desire to eat onto the floor. "And what happened to the last relative who brought gold and jewels?"
#figure(image("009_Mercy/02.jpg", width: 100%), caption: [Dutiful Return | Art by <NAME>], supplement: none, numbering: none)
Jhinu looked toward a Sibsig chained to a pillar on the left of the room, holding up a Sultai banner."
"Do you have no more brothers?" Sidisi asked. "I could've sworn you had at least two brothers."
Jhinu looked at the Sibsig that he had brought into the room.
"Oh yes," Sidisi said. "I thought I had put him near the mandrill cages."
"My cousin," Jhinu said. "My cousin was the one you had guarding the cages."
"Well," Sidisi said, picking up a grape and putting it in her mouth, "If nobody is left who would barter for your life, maybe you are worthless. Perhaps I should be done with you then. Give you to the pits."
"No, no, my queen!" Jhinu said, prostrating himself on the floor in front of her. "I am sorry. I have other family. I will send more messages. I am sure someone else will come to barter for me."
"See that they do," Sidisi said. "With the raising of my army, we have been sending so many fewer people to the pits. A worm like you is not fit for a second skin."
"I…I am sorry," Jhinu said again, backing away from the khan. "Please…please. I have recruits for you to inspect."
Sidisi motioned for him to bring them to her. In raising her army, she had requested that all of the Sultai provinces provide five percent of their population to be enlisted into Sidisi's army. The provinces sent first their unwanted, criminals, and destitute, many of which were hardly fit to feed to the crocodile pits, let alone be the front line in the greatest Sulati army in a millennium. To show her displeasure at the level tribute, Sidisi had sent out a second request—this time for the eldest born of each family. While this request had been unpopular, Rakshasa emissaries sent to the provinces who were not compliant quickly quelled any risk of an uprising. From this crop, Sidisi had requested that the strongest be sent in for her personal inspection. The best of these would be her personal guard—undead warriors strong enough to guard her from incursions like the one she had suffered at the hands of those wretched goblins.
"Allow me to present the contingent from the Niraj province," Jhinu said.
Sidisi inspected the recruits from her throne. They were strong warriors, in the prime of their lives. Their second skins would be free of the defects that the lesser Sibsig were born with—weak knees, weak shoulders, teeth unable to rip the flesh from bones.
"Hold. What is this morsel?" Sidisi said, pausing as she made it halfway through the recruits. In the back was a youth, no more than thirteen years old. "This is a joke of yours, Jhinu? I thought you inspected this crop yourself."
"I assure you, my queen," Jhinu said, "these are all strong warriors. They will serve you well."
Sidisi whipped her tail angrily, knocking the bowl of fruit, along with the Sibsig's head, onto the palace floor. "Do not toy with me, ape. I know this is your home province, and I will not show them leniency by allowing them to send me such children."
"My queen," Jhinu said, kneeling to the floor. If you inspect the youth yourself, I assure you, you will find he is as strong as any other man here."
Sidisi left her throne and approached Jhinu. "I know you have relatives left, and if not them, then friends and business associates. Disobey me again, and I will scour the empire clean of not just you, but everyone you have ever known, and your name will never be spoken again."
Jhinu lifted his head and nodded once. From the corner of her eye, Sidisi saw the youth hesitate for half a second, then bounded at the queen. He was unfettered—his shackles attached to nothing at all, just a ruse. His speed was rarely seen in these apes, almost snakelike. Likely the boy had come from the Jeskai, either by force or as a willing participant in the plot. The pause had given Sidisi a moment to react, and with preternatural speed, her tail grabbed Jhinu by the leg and threw him into the youth. He screamed as they tumbled across the marble floor of the palace. The youth attempted to regain his footing, but found the queen's tail around his neck. He reached for the dagger but found it out of his grasp.
#figure(image("009_Mercy/03.jpg", width: 100%), caption: [Throttle | Art by <NAME>], supplement: none, numbering: none)
On the floor, Jhinu gasped for air, black streaks quickly moving across his skin from where the dagger had scraped him in the tumble. Sidisi recognized the poison. It was known as Silumgar's Breath, made from the distilled essence of hundreds of orchid stems that bloomed only once a decade in the heart of the Objung Swamps. The poison was as rare and expensive as it was potent. Painful, slow, and totally incurable. A single scratch would have been more than enough to kill her over the course of several days or weeks as she rotted away from the inside. This was a personal attack.
"You were right, Jhinu," Sidisi said, cracking the neck of the youth and tossing him to the ground. "That one was strong. He will make a worthy addition to my guard."
"I…" Jhinu said, writhing in pain. "I won't let you beat me. I will make you pay for what you've done to me and my family."
"I gave you too little credit," she said, running her tail across Jhinu's sweaty, convulsing brow. "I thought you a helpless fool, but I was only partly right. Still, you reminded me of something—I have become too lax." Sidisi picked up the dagger and thrust it squarely into Jhinu's chest. "As much pleasure I would get from watching you writhe in agony for the next few days, it is a mistake I won't make again."
Sidisi returned to her throne, her head held high now, reminded again of her purpose. Reminded again of the greatness of the dragons, and the ruthlessness that had for so long made them the rulers of this world. Allowing Jhinu to live just to watch him suffer was a form of mercy in disguise. Mercy, the greatest sin of all sins, had almost cost Sidisi her life. It was an emotion that even in its barest form, she would never show again.
#figure(image("009_Mercy/04.jpg", width: 100%), caption: [Sidisi, <NAME> | Art by <NAME>], supplement: none, numbering: none)
If the goblin had been armed with spear or arrow, it's possible that it could've struck a mortal blow. Fortunately for Sidisi, the Mardu love war more than they love victory. Sidisi knew that her army was not yet close to being complete. She needed to raise an army the likes of which had not been seen since the time of Tasigur. An army of Sibsig that would cover the entire steppe and march tirelessly on the Mardu until their horses died of exhaustion. And one by one, she would kill every encampment she could find, raising the dead by herself if need be, so that they could join the unyielding march on their brethren. Soon, the great orc Zurgo himself would adorn her palace as her greatest prize. Perhaps she would turn him into a serving tray, or maybe a chair.
|
|
https://github.com/BrainTmp/MetaNote | https://raw.githubusercontent.com/BrainTmp/MetaNote/main/Typst/metanote.typ | typst | #import "metatheorem.typ": *
#let theorem = metamathbox("theorem", "Theorem", rgb(13, 71, 161)) // Material Blue 900
#let example = metamathbox("example", "Example", rgb(51, 105, 30)) // Material Light Green 900
#let corollary = metamathbox("corollary", "Corollary", rgb(26, 35, 126)) // Material Indigo 900
#let note = metamathbox("note", "Note", rgb(0, 77, 64)) // Material Teal 900
#let definition = metamathbox("definition", "Definition", rgb(38, 50, 56)) // Material Blue Grey 900
#let proposition = metamathbox("proposition", "Proposition", rgb(230, 81, 0)) // Material Orange 900
#let question = metamathbox("question", "Question", rgb(26, 35, 126))
#let exercise = metamathbox("exercise", "Exercise", rgb(26, 35, 126))
#let exerciseb = metamathbox("exercise", "Exercise", rgb(26, 35, 126)).with(numbering: none)
#let hint = metamathbox("hint", "Hint", rgb(26, 35, 126))
#let lemma = metamathbox("lemma", "Lemma", rgb(51, 105, 30))
#let proof = thmplain(
"proof",
"Proof",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
#let proofsk = thmplain(
"proofsk",
"Proof Sketch",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
#let solution = thmplain(
"solution",
"Solution",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
#let MetaNote(
title: none,
authors: (),
doc,
head_numbering: "1.1.",
head_mode: "note",
print: false
) = {
let head_mode_func = (mode) => {
if head_mode == "note" {
return head_numbering
} else if head_mode == "book" {
return (..nums) => {
if nums.pos().len() == 1 {
return "Chapter " + nums.pos().map(str).join(".") + "" + math.quad
} else if nums.pos().len() == 2 {
return "Section " + nums.pos().map(str).join(".") + "" + math.quad
} else {
return nums.pos().map(str).join(".")
}
}
}
}
set heading(numbering: head_mode_func(head_mode))
// set par(first-line-indent: 1em, justify: true)
set align(center)
text(17pt, title)
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 24pt,
..authors.map(author => [
#author.name \
#author.affiliation \
#link("mailto:" + author.email)
]),
)
set align(left)
show: thmrules
doc
} |
|
https://github.com/MasterTemple/typst-bible-plugin | https://raw.githubusercontent.com/MasterTemple/typst-bible-plugin/main/bible.typ | typst | #let bible = plugin("bible.wasm")
// currently only ESV is supported
#let translation = "ESV";
#let verse_number(n) = {
[#text(baseline: -0.4em, weight: "bold", size: 7pt, str(n))]
}
#let get_verse_content(book, chapter, verse) = {
let content = str(bible.get_verse(bytes(book), bytes(str(chapter)), bytes(str(verse)), bytes(translation)));
content.trim("\"")
}
#let get_verse_content_range(book, chapter, start_verse, end_verse) = {
let arr = ();
for verse in range(int(start_verse), int( end_verse)+1) {
let content = get_verse_content(book, chapter, verse);
// arr.push([*#super(typographic: false, size: 0.8em, str(verse))* #content]);
arr.push([#verse_number(verse) #content]);
}
arr.join(" ")
}
#let set_verse_footnote(book, chapter, start_verse, end_verse) = {
let content = get_verse_content_range(book, chapter, start_verse, end_verse);
let verse = start_verse;
if start_verse != end_verse {
verse = [#start_verse\-#end_verse]
}
[#footnote[#content - #book #chapter:#verse #translation]]
}
#let parse_ref(ref) = {
let book = ref.find(regex("(\d )?\D+")).trim();
let chapter = ref.find(regex("\d+:")).replace(":", "");
let start_verse = ref.find(regex(":\d+")).replace(":", "");
let end_verse = ref.find(regex("\d+$"));
(book, chapter, start_verse, end_verse)
}
#let parse_verse_and_get_content(ref) = {
let (book, chapter, start_verse, end_verse) = parse_ref(ref)
let content = get_verse_content_range(book, chapter, start_verse, end_verse);
content
}
// #let verse(ref) = {
// let book = ref.find(regex("(\d )?\D+")).trim();
// let chapter = ref.find(regex("\d+:")).replace(":", "");
// let start_verse = ref.find(regex(":\d+")).replace(":", "");
// let end_verse = ref.find(regex("\d+$"));
// set_verse_footnote(book, chapter, start_verse, end_verse)
// }
#let block_quote(content, attribution) = {
let this_quote = block(width: 100%,
pad(x: 0.5em, y: 0.5em, right: 4em,
quote(block: true, attribution: [#attribution])[
#par(justify: true, content)
])
)
[
#layout(size => [
#let (height,) = measure(
block(width: size.width, this_quote),
)
#let height = height
#let indent = 2em
#h(indent)
#box(
width: 2pt,
height: height,
fill: black,
)
#place(
dy: -height,
dx: indent,
[#this_quote]
)
])
]
}
#let hstack_quote(content, attribution) = {
let this_quote = block(width: 100%,
pad(x: 0.5em, y: 0.5em, right: 0.5em,
quote(block: true, attribution: [#attribution])[
#par(justify: true, content)
])
)
pad(x: 2em, [
#layout(size => [
#let (height,) = measure(
block(width: size.width, this_quote),
)
#let height = height
#stack(dir: ltr,
box(
width: 2pt,
height: height,
fill: black,
),
[#this_quote]
)
])
])
}
#let merge_every_other(arr1, arr2) = {
let arr = ();
let toggle = false;
let i1 = 0;
let i2 = 0;
while i1 < arr1.len() or i2 < arr2.len() {
toggle = not toggle;
if toggle {
if i1 == arr1.len() {
continue
}
arr.push(arr1.at(i1));
i1 += 1;
} else {
if i2 == arr2.len() {
continue
}
arr.push(arr2.at(i2).text);
i2 += 1;
}
}
arr
}
#let fmt_match(content, pattern, formatter) = {
let parts = content.split(regex(pattern))
let matches = content.matches(regex(pattern))
let alternating_parts = merge_every_other(parts, matches);
let result = ()
for (i, part) in alternating_parts.enumerate() {
if calc.rem(i, 2) == 0 {
result.push(part)
}
else {
result.push([#formatter(part)])
}
}
result.join()
}
#let bible_footnote(..refs) = {
[#footnote[
#for ref in refs.pos() {
[#h(0.5em) #parse_verse_and_get_content(ref) - #ref #translation\ ]
[#h(1.5em)]
}
]]
}
#let bible_quote(..refs) = {
for ref in refs.pos() {
let content = parse_verse_and_get_content(ref)
[
#hstack_quote(content, [#ref #translation] )
]
}
}
// ref = verse reference
// hl = highlight match pattern
// ul = underline match pattern
// it = italics match pattern
// b = bold match pattern
#let bible_quote_fmt1(ref, hl: "", b: "", ul: "", it: "") = {
let content = parse_verse_and_get_content(ref)
let new_fields = ()
for child in content.fields().children {
if child.has("text") {
// [#type(child)\ ]
if hl.len() > 0 {
child = [#fmt_match(child.text, hl, highlight.with(fill: yellow))]
// [#child\ ]
// [#type(child)\ ]
// [#child.has("text")\ ]
// [#child.text\ ]
}
if b.len() > 0 {
child = [#fmt_match(child.text, b, text.with(weight: "bold"))]
}
if ul.len() > 0 {
child = [#fmt_match(child.text, ul, underline)]
}
if it.len() > 0 {
child = [#fmt_match(child.text, it, text.with(style: "italic"))]
}
}
new_fields.push(child)
}
let content = new_fields.join("")
[
#hstack_quote(content, [#ref #translation] )
]
}
#let apply_function_to_content(content, pattern, fn) = {
let new_fields = ()
for child in content.fields().children {
if child.has("text") {
if pattern.len() > 0 {
child = [#fmt_match(child.text, pattern, fn)]
}
}
new_fields.push(child)
}
return new_fields.join("")
}
#let apply_fmt_to_content(content, pattern, formatter) = {
let new_fields = ()
for child in content.fields().children {
if child.has("text") {
if pattern.len() > 0 {
child = [#fmt_match(child.text, pattern, formatter)]
}
}
new_fields.push(child)
}
return new_fields.join("")
}
// `ref` = verse reference
// `hl` = highlight match pattern
// `ul` = underline match pattern
// `it` = italics match pattern
// `b` = bold match pattern
// `c` = custom match pattern to apply `fmt` filter
// `fmt` = custom formatting pattern
// `omit` = omit content by replacing with elipse ...
#let bible_quote_fmt(ref,
hl: "", b: "", ul: "", it: "", c: "", fmt: text.with(), omit: ""
) = {
let content = parse_verse_and_get_content(ref)
// `hl` = highlight match pattern
let content = apply_fmt_to_content(content, hl, highlight.with(fill: yellow))
// `b` = bold match pattern
let content = apply_fmt_to_content(content, b, text.with(weight: "bold"))
// `ul` = underline match pattern
let content = apply_fmt_to_content(content, ul, underline)
// `it` = italics match pattern
let content = apply_fmt_to_content(content, it, text.with(style: "italic"))
// `c` = custom match pattern to apply `fmt` filter
// `fmt` = custom formatting pattern
let content = apply_fmt_to_content(content, c, fmt)
// `omit` = omit content by replacing with elipse ...
let content = apply_function_to_content(content, omit, (text) => text.replace(regex(omit), "..."))
[
#hstack_quote(content, [#ref #translation] )
]
}
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/017%20-%20Dragons%20of%20Tarkir/006_The%20Call.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Call",
set_name: "Dragons of Tarkir",
story_date: datetime(day: 15, month: 04, year: 2015),
author: "<NAME>",
doc
)
#emph[On another Tarkir, with a different destiny, the man called Surrak was khan of his clan. Savage, swift, and ] attuned with nature#emph[, he ruled the Temur by example.]
#emph[Times have changed, however—time itself has changed—and Surrak never lived that life. Now he is the Hunt Caller of the Atarka clan, who hunt to feed their dragonlord. If Surrak knew of this other fate, his original destiny as khan, he might prefer that life.]
#emph[But then again, he might not.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Birds burst from the pines, scattering snow to the steep slopes below, as the hours of long silence are broken by the sound of the horn. The hunting horn. The call to the most sacred of tasks.]
#emph[The mountains are vast, trackless, and pristine. A dragon's gaze stretches far, but none can see every slope, every cave, every hollow. Deep in the mountains is a place of peace. A human or ainok can escape for days, weeks; a clever one, maybe even a year. But the quiet has a price. The empty mountains are yet ruled, and when the horn sounds, you answer.]
#figure(image("006_The Call/01.jpg", width: 100%), caption: [Mountain | Art by Titus Lunter], supplement: none, numbering: none)
#emph[Four ainok rise from their hidden camp. They do not serve Atarka, but these are her lands. Their peace is her peace. They bundle up as best they can, and shuffle off in the direction of the sound. It is the better of the two options. Neither the mother nor the father is much of a hunter. The eldest daughter is fit, the younger son scrawny. There is no debate, no discussion. The horn sounds, and they walk. Some of them will last the week.]
#emph[The great sledge rumbles over the snowdrifts, pulled by fur-covered men and women that look not that dissimilar from the beasts heaped atop it. Nobody speaks. There are noises, noises of effort and exertion, noises of nervousness and frustration, but no words. There will be time for words later, once the hunt is done.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Surrak stood atop the sledge and relished the small pain of the icy air in his lungs. They had been on the trail of a mountain krushok for almost a day now and, by the size of the tracks, it was enormous. An offering like that could keep the dragonlord satisfied for almost a week. Once a krushok reached this size, they no longer bred, they no longer traveled with their herds. A perfect quarry. Along the way, they had taken a dozen elk, three saberclaws, a handful of yeti, and a hermit who refused the call. Surrak was particularly pleased with the saberclaws. Atarka seemed to enjoy them, and by thinning out the area's predators, that left more game animals for the hunt.
Out in the wild places, Surrak felt completely at home. There was a fierce joy to this—he could put from his mind the reason that he hunted and focus everything on the instincts that would lead to a successful conclusion. Every bit of movement caught his eye, every sound turned his head. He had never come this way before, but he knew this place. The power deep within the land resonated with him, gave him strength, drove him onward. There was no time for anything else.
#figure(image("006_The Call/02.jpg", width: 100%), caption: [Surrak, the Hunt Caller | Art by <NAME>], supplement: none, numbering: none)
The tracks were fresh as the sledge moved through the treeline and across a mountain spring. The beast stopped for water here, and its tracks in the stream bed had not yet washed away. They were close now. Surrak gestured to his scouts, sending two of them off parallel to the tracks, while he dismounted from the sledge and breathed in the scent of his quarry. Close. Very close. Energy from the land welled up on him, and he could feel it tingling in his fists. He carried no weapon. He had never needed one.
Just as he was about to start his chase, a shadow passed over the sledge. His eyes searched the skies and saw the silhouette of a dragon, flying lazily above. One of Atarka's brood, by its size and mass. Something seemed off in the way it flew, and he hissed to his scouts and hunters to hold still. They hunkered down into the snow, and to a dragon above, they must have seemed to disappear entirely. But there was no hiding the sledge. The dragon circled again, and now Surrak saw what had caught his eye to begin with: its wingbeats were uneven and its flight unsteady. He was silent and still for several moments.
"What do you see?" Surrak's second broke the stillness. He was an enormous man, and he kept his voice low.
"It's one of Atarka's brood, but it's circling us. It's seen the sledge, and it's thinking about it. It should know better, but it's thinking about it." Surrak let out a long, slow breath, which turned to frost in the air. "Look at the wingbeats. That's not a healthy dragon. Injured, perhaps. Maybe sick. Either way, it's thinking about coming for us."
"And what do we do if that happens?"
Surrak took another few breaths.
"This meat is for Atarka. We bring her the meat, or we become the meal. That's not so complicated, is it?"
His second shook his head. The wingbeats grew more distant, and then the dragon faded from sight. Surrak whistled a command and, as one, the hunters rose from the snow. The pursuit began.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The krushok must have caught the smell on the wind. #emph[They don't get old without being clever] , Surrak thought, and the krushok had done everything it could to throw the hunters off of its trail. It crossed a river, then crossed back. But the ainok could track its scent in the dark, if they needed to. It stayed to rocky terrain in order to leave less obvious tracks, but there was no hiding its passage from the hunters' keen eyes. Finally, it used its size and speed to try to outpace them, but Surrak's scouts had already reached it. With spears and slings, they harried it, driving it back, turning its course back toward the hunters' ambush. When the krushok burst into the clearing, the hunters let loose a volley of spears and hooks. It was trapped.
It let out a bellow that shook the stones, and the hunters, moving as one, began to rein it in with hooks and ropes. Hunters crept forward with long-bladed spears, looking to deliver the mortal blow. The beast bucked and strained, but the hunters were strong and skilled. It let out a low sound, and its head sagged as it showed its exhaustion. The ropes went taut, and the spear-bearers lunged in.
#figure(image("006_The Call/03.jpg", width: 100%), caption: [Feral Krushok | Art by <NAME>], supplement: none, numbering: none)
But the beast had been hiding its strength, just as the hunters had. With a burst of might, it leapt up, snapping ropes, and swinging its great horn. Two of the spear-bearers were swatted aside, bones snapping, bodies flung against trees and stone. With a mighty kick, it crushed several of the hunters holding the ropes and hooks. Surrak's second grabbed one of the fallen hunters' spears and charged in with a shout. With a powerful thrust, he drove the spear upwards under the beast's great jaw. It shuddered, stumbled, and knelt down—defeated—blood pooling red against white, steam rising from the snow.
There was little celebration among the hunters. A quick check on the fallen to see whether they were wounded or dead. There was an unspoken calculus at work here. With this kill in hand, they needed to load the sledge and turn around. Those that could walk, would walk. Those that could pull, would pull. But there was only one way to ride back to Atarka on the sledge, and nobody volunteered for it.
The sledge was pulled up as close to the enormous corpse as the hunters could manage, and planks were cut from the surrounding pines, so that the enormous krushok could be hoisted atop it. Surrak let his second direct the effort while he watched the clouds—they were starting to pool around the nearby peaks. A storm was coming. Not a dragon tempest, but the regular kind that brought wind, snow, cold, and death to anyone caught in it. The clouds darkened as he watched, and if the winds prevailed….
A shape burst from the clouds, dropping into a thunderous dive.
"Get clear of the sledge! NOW!" Surrak shouted a warning, but it was too late, as the dragon dropped down from the skies, a meteor of wings, scales, and antlers. It crashed to the earth, smashing a crater into the snow and ice, and it slid twenty yards down the slope after it hit. It scored the trees and the hunting party with a gout of flame, and blinding smoke wreathed its form. Surrak squinted through the flames to see it. He saw its eyes and he saw a feral madness in them. It stomped over to the krushok, and took a gluttonous bite while the surviving hunters scattered into the treeline.
#figure(image("006_The Call/04.jpg", width: 100%), caption: [Herdchaser Dragon | Art by <NAME>], supplement: none, numbering: none)
The dragon was stout, thirty feet in length, with a rack of jagged antlers that marked it as one of Atarka's brood. But her dragons were intelligent, and they knew that the Hunt was not to be interfered with. For one of her brood to attack, it had to be mad or desperate.
"Everyone get back. I'm going to secure the sledge." Surrak wrapped his bearskin tight around his shoulders and slowly walked through the smoke. He growled guttural syllables and punctuated the sound by scraping and striking a stone against a scale that he wore against his coat for that purpose. No human had the capacity to speak draconic, but Surrak had managed to improvise a close approximation of several of those impossible sounds. #emph["I am the <NAME>,"] he tried to say.
The dragon did not react, save to glare at him as it chewed its stolen meal.
Surrak continued. #emph["You are stealing Atarka's meat. Stop now."]
Again, nothing. If the dragon understood him, it gave no sign. He sighed.
"Fine, we'll do this the other way."
Surrak crouched down, growled, and bared his teeth. There was no man nor beast that could have possibly misunderstood this. The dragon gulped down a mawful of meat, and returned the glare.
The dragon roared and snapped at him, but it was posturing. Surrak circled, crouched low, palms down toward the ground. This was a good place. Lots of energy to be drawn. An old place. The magic started to well up in him, and his blood felt hot. The dragon let loose a burst of flame, but Surrak dashed forward, ducking most of it. He was burnt, but didn't feel it. The dragon wheeled around on him, bringing a thick, clawed arm down toward his face. But before it could land, he planted his back fist and threw a punch.
#figure(image("006_The Call/05.jpg", width: 100%), caption: [Epic Confrontation | Art by <NAME>s], supplement: none, numbering: none)
One was all it took.
The dragon fell to the earth, neck broken. The hunters that survived re-emerged from their hiding places. They took stock of the damage, but they didn't have long. The winds had picked up, and the snow began to fall. The storm was upon them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Two days passed, and the storm did not let up in the slightest. Keeping a fire lit was almost impossible, and the trees only provided so much shelter. The sledge was full of food, but it was frozen solid. It would keep for Atarka, but unless they found a way to do something about their immediate predicament, it would never reach her. And if that happened, Surrak knew what would follow. His people would pay the price.
"I'll be back shortly."
His hunters were huddled together for warmth, using the sledge as a windbreak. They gave him quizzical looks, but said nothing. Surrak trudged straight on into the wind, toward where the dragon had fallen. Despite its bulk, he needed to dig the dragon out of the snow before he could get to work. He cut into the creature, digging out chunks of flesh and an organ from the beast's torso. Once he reached the camp, he sliced the organ open and poured a thick, foul liquid on the wood. A few sparks later, and it burst into a roaring flame. Dragonfire. The hunters eyed Surrak suspiciously, but were grateful enough for the warmth. Then he skewered a chunk of meat, and began roasting it.
"Is that…?" Surrak's second stared, disbelieving. "That's not allowed. We have all this meat…"
#figure(image("006_The Call/06.jpg", width: 100%), caption: [Atarka Beastbreaker | Art by Joh<NAME>oss], supplement: none, numbering: none)
Surrak cut him off. "Allowed? We eat what we kill. I killed it, and I was right to do so. It had lost its reason. It was a beast, and I was stronger. Now #emph[that] ," he said, pointing toward the sledge, "is not allowed. That is #emph[hers] . We're going to be late getting back to her as it is. We barely have enough to pull the sledge, so we'll be moving slow. We're days delayed by the storm. So we're going to eat our kill, we're going to regain our strength, and then we're going to do our job. Understood?"
Surrak's second opened his mouth to reply, then saw Surrak's clenched fist and thought better of it.
Surrak had never eaten dragon before. It was delicious.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The ascent to the Ayagor was assisted as the sledge approached. Atarka lounged atop the peak, the largest thing that lived on Tarkir. Despite her massive bulk, Surrak had seen her enraged to action. Nothing that large should move that fast, and yet she could when she needed to. For now, she was content to watch as the enormous sledge of meat was tipped into the bowl of stone before her. She gave a snort, charring the bowl with dragonfire, and then began to eat. Surrak was on hand to deliver the traditional message.
"Great Atarka, dragonlord and protector. This is a gift. Spare us, and there will be more."
#figure(image("006_The Call/07.jpg", width: 100%), caption: [Dragonlord Atarka | Art by <NAME>], supplement: none, numbering: none)
Atarka growled her acceptance and her mighty jaws crushed up bone, fur, hide, and meat alike.
Surrak smiled to himself. It had been another successful hunt, and his people would live. He turned and began to walk back down the mountain, when he heard a panicked voice. His second.
"Dragonlord Atarka! Please forgive us! We had no choice."
Surrak turned back and hissed, "Idiot, stop this at once."
But his second continued. "Surrak killed one of your brood to defend your offering. He violated the natural order! Please forgive us and limit your vengeance only to him!"
Surrak smiled, and he waited.
Atarka looked up from her meal, obviously annoyed. She growled four words in draconic. #emph["Take care of it."]
#figure(image("006_The Call/08.jpg", width: 100%), caption: [Atarka's Command | Art by <NAME>], supplement: none, numbering: none)
Surrak rounded on his second, who had already turned toward him with a knife.
"I will make sure she is fed, Surrak."
Surrak shook his head.
"She wasn't talking to you."
With a burst of speed, Surrak slammed his fist into his second's ribs, cracking several, and sending the knife clattering along the stone. He caught the huge man before he hit the ground and held him close, whispering into his ear. "I don't blame you for trying. But she knows I did nothing wrong. Why are dragons above humans? They're stronger. Simple as that. But the dragon we found was weak. Sick. So what reverence did we owe it? She understands. And now you do."
Surrak tossed the larger man to the ground, and began to walk away. "We leave for the next hunt in two days. It'll be hard for you to keep up with those ribs."
He turned back and smiled.
"But we bring her the meat, or we become the meal. So you'll serve either way."
|
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/8形态学处理.typ | typst | #import "../template.typ": *
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge
#import fletcher.shapes: house, hexagon, ellipse
#import "@preview/pinit:0.1.4": *
#import "@preview/cetz:0.2.2"
#import "/book.typ": book-page
#show: book-page.with(title: "数字图像处理基础 | DIP")
= 形态学处理 Morphological Processing
== 形态学操作
=== 腐蚀和膨胀
- 腐蚀:将结构元素放在图像上,只有结构元素完全覆盖图像时,输出为 1,否则为 0。即:$
A minus.circle B = {z | (B)_z subset.eq A}
$
- 可以被理解为形态学滤波:把小物体过滤掉
- 膨胀:将结构元素放在图像上,只要结构元素和图像有交集,输出为 1,否则为 0。即:$
A plus.circle B = {z | (B)_z sect A eq.not diameter}
$
=== 开操作和闭操作
- 开操作:平滑边缘,断开窄的连接,去除细的突出
- 先腐蚀再膨胀 $
A circle.stroked.tiny B = (A minus.circle B) plus.circle B
$
- 闭操作:连接物体,填充小的空洞,平滑物体边缘
- 先膨胀再腐蚀 $
A circle.filled.tiny B = (A plus.circle B) minus.circle B
$
先开后闭可以去除小的物体,先闭后开可以去除小的空洞。
== 邻接性
=== $m$-邻接
#grid(
columns: (1fr, 1fr, 1fr),
)[
#figure(
table(
columns: (2em, 2em, 2em),
rows: (2em, 2em, 2em),
align: center + horizon,
[], table.cell(fill: yellow)[], [],
table.cell(fill: yellow)[], [A], table.cell(fill: yellow)[],
[], table.cell(fill: yellow)[], [],
),
caption: "4-邻接",
kind: {
image
},
)
][
#figure(
table(
columns: (2em, 2em, 2em),
rows: (2em, 2em, 2em),
align: center + horizon,
table.cell(fill: yellow)[], table.cell(fill: yellow)[], table.cell(fill: yellow)[],
table.cell(fill: yellow)[], [A], table.cell(fill: yellow)[],
table.cell(fill: yellow)[], table.cell(fill: yellow)[], table.cell(fill: yellow)[],
),
caption: "8-邻接",
kind: {
image
},
)
][
#figure(
table(
columns: (2em, 2em, 2em),
rows: (2em, 2em, 2em),
align: center + horizon,
[B], [], [],
[C], [A], [],
[], [], [D],
),
caption: "",
kind: {
image
},
)<adjacency_example>
]
@adjacency_example 中,AB 为 8-邻接,AC、BC 均为 4-邻接。由于 C 的存在,AB*不*为 $m$-邻接。但是 AD 是 $m$ 邻接的。
#note_block[
4-邻接必有 $m$-邻接和 8-邻接;8-邻接需要判断一下 $m$-邻接。
]
$m$-邻接是为了消除歧义。
#note_block[
尝试使用形态学操作的方法提取图片morphology.jpg中的国旗图案。
```py
#task2.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('imgs/morphology.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 158, 255, cv2.THRESH_BINARY_INV)
# show binary image
cv2.imwrite('outputs/exp5_2_binary.jpg', binary)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 17))
morph = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)
cv2.imwrite('outputs/exp5_2_morph.jpg', morph)
# 寻找轮廓
contours, _ = cv2.findContours(morph, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contoured_image = cv2.drawContours(np.zeros_like(image), contours, -1, (0, 255, 0), 2)
cv2.imwrite('outputs/exp5_2_contours.jpg', contoured_image)
upper = 1.1
lower = 0.9
contour_image = np.zeros_like(image)
i = 1
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if ((lower * 48 / 32 <= w / h <= upper * 48 / 32)
and (lower * 48 * 32 <= w * h <= upper * 48 * 32)):
# 保存框内的图像
cv2.imwrite(f'outputs/exp5_2_{i}.jpg', image[y:y + h, x:x + w])
i += 1
# 将框内的图像 crop 出来,放到新的图像上
contour_image[y:y + h, x:x + w] \
= image[y:y + h, x:x + w]
print(i)
cv2.imwrite('outputs/exp5_2_0.jpg', contour_image)
```
]
|
|
https://github.com/loreanvictor/master-thesis | https://raw.githubusercontent.com/loreanvictor/master-thesis/main/proposal.typ | typst | MIT License | #import "proposal_template.typ": *
#import "common/titlepage.typ": *
#import "common/metadata.typ": *
#titlepage(
title: titleEnglish,
titleGerman: titleGerman,
degree: degree,
program: program,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate
)
#show: project.with(
title: titleEnglish,
titleGerman: titleGerman,
degree: degree,
program: program,
supervisor: supervisor,
advisors: advisors,
author: author,
startDate: startDate,
submissionDate: submissionDate
)
#set heading(numbering: none)
= Abstract
// - Provide a brief summary of the proposed work
// - What is the main content, the main contribution?
// - What is your methodology? How do you proceed?
Proposed thesis investigates a simplified approach for enhancing realtime collaboration on structured diagrams, implementing the solution in Apollon, an open-source UML modeling editor. Inspired by methodologies like $delta$-CRDTs, this work aims to utilise insights from these approaches for the specific case of structured diagrams in general and UML diagrams in particular. This work also aims to provide a pluggable solution for scalability of realtime collaboration in Apollon, which can be viewed as a schematic solution for any such distributed system. Throughout this exploration, this thesis briefly touches on other known methods, such as CRDTs, shedding light on the chosen approach for structured diagrams.
#set heading(numbering: "1.1")
= Introduction
// - Introduce the reader to the general setting
// - What is the environment?
// - What are the tools in use?
Diagrams hold a central position in software development and design. Among the various types, UML diagrams in particular are considered 'the de-facto standard' for representing software architectures and workflows @uml-empirical. UML, however, has proven diffcult to adopt both by professionals in the industry @uml-in-practice and by students and instructors in academia @uml-learning. This diffuclty underscores the need for easy-to-use and learning-focused UML modeling tools such as Apollon #footnote("https://github.com/ls1intum/Apollon"), which have shown to be effective in improving learning outcomes in modelling @uml-learning.
A key feature of such tools is realtime collaboration. Collaborative settings are shown to have a positive impact on contribution amongst participants specifically during modeling using UML @collab-on-table. Combined with a rising trend in remote work and study, realtime collaboration is becoming a necessity for making the gains of a collaborative working/learning environments for modeling readily available to a wider audience, while further shortening assessment, evaluation and feedback cycles, hence further increasing engagement of such tools.
= Problem
// - What is/are the problem(s)?
// - Identify the actors and use these to describe how the problem negatively influences them.
// - Do not present solutions or alternatives yet!
// - Present the negative consequences in detail
A key challenge for implementing realtime collaboration for UML modeling tools such as Apollon (or any other realtime collaboration program), is ensuring that every user is working with the same data. When network is prone to disconnection or delay, it is impossible to guarantee a strong consistency and constant availability @cap. Practically, for example in an educational setting, this would either mean constant interuption for the students while tutors attempt to provide feedback, or tutors providing feedback on diagrams that the students have already changed.
A common-place solution to this is adopting a weaker consistency model, _eventual consistency_, allowing for more optimistic systems that would apply user changes immediately to their local replica and then synchronise with other clients @eventually-consistent. Such solutions however require complex and error-prone reconcilliation mechanisms @crdt-list. Even newer refinements such as conflict-free data types (CRDTs) have unnecessary complexity and inefficient consumption of bandwidth and memory, even for cases as simple as a one-way counter @crdt-list, @delta-crdt, as shown in #link(<figure-1>)[Figure 1].
#figure(
image("figures/g-counter-cvrdt.png", width: 80%),
caption: [
A G-Counter CRDT, where each replica must maintain a separate counter for each other replica, and sync the whole array periodically.
]
) <figure-1>
Scaling realtime collaboration systems proposes another key challenge for implementation. A non-scaling system will have lower availability under unexpected load, hindering larger work / educational settings, or settings with participants from across different geographical regions.
= Motivation
// - Outline why it is important to solve the problem
// - Again use the actors to present your solution, but don’t be to specific
// - Be visionary!
// - If applicable, motivate with existing research, previous work
Solving the challenges of implementing realtime collaboration for diagrams in general and UML diagrams in particular, can not only further help alleviate the diffculties of adopting UML, but also act as a recipe for other similarly structured replicated data, without the need for complex reconcilliation mechanisms or inefficient data types. In practice, such a solution has the potential to act as a theoretical framework for conflict free replicated documents in suitable industrial domains, including distributed and highly structured NoSQL data.
Additional implementation of a pluggable scalability layer then can not only future-proof projects such as Apollon, but also provide a schematic solution for any such distributed system or application, with architectural design that is simple to start with while capable at higher usage volumes.
= Objective
// - What are the main goals of your thesis?
The objectives of the proposed thesis are as follows (in order of priority):
- Restructure Apollon data model to enable use of standard-compliant patching mechanisms producing commutative patches on independent changes and idempotent patches on overlapping changes.
- Implement a realtime collaboration solution for Apollon, using the proposed data model and patching standards.
- Evaluate the proposed solution for correctness.
- Implement a pluggable scalability layer for Apollon, using a simple and scalable architecture.
- Explore theoretically sufficient conditions for applicability of the proposed solutions for the general case.
#figure(
image("figures/client-server-uml.png", width: 60%),
caption: [
Schematic overview of how the realtime collaboration that is to be implemented.
]
) <figure-2>
= Schedule
// - When will the thesis Start (Always 15th of Month)
// - Create a rough plan for your thesis (separate the time in sprints with a length of 2-4 Weeks)
// - Each sprint should contain several work items - Again keep it high-level and make to keep your plan realistic
// - Make sure the work-items are measurable and deliverable
// - No writing related tasks! (e.g. ”Write Analysis Chapter”)
*Start Date*: 15.10.2023 \
*End Date*: 15.04.2024
#table(
columns: (auto, 1fr, auto, auto),
[\#], [goals], [date], [duration],
[1], [Literature review, initial impl. of realtime collab.], [15.10 - 28.10], [2 weeks],
[2], [Final impl. of realtime collaboration], [29.10 - 18.11], [3 weeks],
[3], [Coverage and Documentation], [19.11 - 02.12], [2 weeks],
[4], [Theoretical analysis & evaluation], [03.12 - 17.12], [2 weeks],
[5], [Initial impl. of pluggable scalability layer], [02.01 - 15.01], [2 weeks],
[6], [Impl. prototype of scalable broadcast / storage], [16.01 - 5.02], [3 weeks],
[7], [Literature review for scalability], [06.02 - 19.02], [2 weeks],
[8], [Final impl. of scalability layer / coverage & docs], [20.02 - 04.03], [2 weeks],
[9], [Thesis finalisation], [05.03 - 01.04], [4 weeks]
)
|
https://github.com/MaharshiAJ/Resume-Template | https://raw.githubusercontent.com/MaharshiAJ/Resume-Template/main/template.typ | typst | #set text(font: "Arial", lang: "en")
#set page(paper: "us-letter")
#let header(
name: str,
email: str,
linkedinUrl: str
) = {
set align(center)
text(20pt, weight: "bold", name)
linebreak()
text(12pt, {
email + " | " + linkedinUrl
})
}
#let sectionHeader(title: str) = {
[
#set align(left)
#text(16pt, weight: "bold", title)
#v(-12pt)
#line(length: 100%)
]
}
#let education(
schools: (str: (
degree: str,
major: str,
graduation: str,
gpa: str,
location: str
))
) = {
sectionHeader(title: "Education")
for (key, value) in schools {
text(12pt, weight: "bold", {
value.degree + ", " + value.major + ", " + value.graduation + h(1fr) + "GPA: " + value.gpa
})
linebreak()
text(12pt, {
key + ", " + value.location
})
linebreak()
linebreak()
}
}
#let experience(
roles: (
str: (
title: str,
start: str,
end: str,
location: str,
description: ()
)
)
) = {
sectionHeader(title: "Experience")
for (key, value) in roles {
text(12pt, {
[*#value.title*] + h(1fr) + value.start + " - " + value.end
})
linebreak()
text(12pt, {
key + ", " + value.location
})
linebreak()
for bullet in value.description {
list(text(12pt, bullet))
}
}
}
#let skills(skills: (str: ())) = {
sectionHeader(title: "Skills")
for (key, value) in skills {
list(
text(12pt, {
key + ": " + for i in value.enumerate() {
if i.at(0) < value.len() - 1 {
i.at(1) + ", "
} else {
i.at(1)
}
}
})
)
}
} |
|
https://github.com/matryt/modules-typst | https://raw.githubusercontent.com/matryt/modules-typst/main/img-aside-text/1.0.0/lib.typ | typst | #let main(image,..blocks) = {
stack(
dir:ltr,
spacing:lem,
image,
block(
blocks.pos().join(linebreak())
)
)
}
|
|
https://github.com/FkHiroki/ex-E5 | https://raw.githubusercontent.com/FkHiroki/ex-E5/main/sections/section3.typ | typst | MIT No Attribution | = 3. 考察
== 課題(1)
=== 乱数の平均値が0.5になる理由、分散の値が1/12になる理由
まず、一様乱数の確率密度関数を考える。一般に、一様乱数の確率密度関数は次のように表される。
$
f(x) =
cases(
1 / (b-a) space ( a <= x <= b ),
0 space ( "otherwise" )
)
$ <eq:uniform>
これを用いて、平均値$E(X)$と分散$V(X)$を求めると、次のようになる。
$
E(X) &= integral_(-infinity)^infinity x f(x) d x = integral_(a)^b x f(x) d x \
&= integral_(a)^b x / (b-a) d x \
&= 1 / (b-a) [x^2 / 2]_(a)^b \
&= (b + a) / 2
$
$
E(X^2) &= integral_(-infinity)^infinity x^2 f(x) d x = integral_(a)^b x^2 f(x) d x \
&= integral_(a)^b x^2 / (b-a) d x \
&= 1 / (b-a) [x^3 / 3]_(a)^b \
&= (b^2 + a b + a^2) / 3
$
$
V(X) &= E(X^2) - E(X)^2 \
&= (b^2 + a b + a^2) / 3 - (b + a)^2 / 4 \
&= (b^2 - 2 a b + a^2) / 12 = (b - a)^2 / 12
$
よって、今回の場合、$a = 0$、$b = 1$ であるため、平均値$E(X)$、分散$V(X)$はそれぞれ$0.5$、$1/(12)$になることがわかる。
== 課題(2)
=== buffonの針で、何故$pi$の値が求められるのか
まず、buffonの針問題とは、床の上に等間隔に引かれた平行線群があり、その距離を$2a$として,この床に長さ$2l( l < a)$の針をデタラメに落とすと,その針が平行線と交わる確率はいくらかという問題である。
buffonの針で何故$pi$の値が求められるかについて以下の図を基に考える。
#figure(
image("../figs/buffon _fig.png", width: 60%),
caption: [buffonの針問題],
) <fig:buffon_fig>
針の中点を$y$、針と平行線のなす角を$theta$、針の長さを$2l$とする。対称性より、$y$の区間を$[0, a]$、$theta$の区間を$[0, pi/2]$とする。この時、針が平行線と交差する条件は、
$ y <= l sin theta $
と表される。ここで針をデタラメに落とすということは、$y$と$theta$は一様分布に従うと解釈できる。$(y, theta)$平面を考えると、針が平行線と交差する確率は、$y = l sin theta$を$theta$の領域で積分した面積を、全体の面積で割ったものになる。全体の面積は、$y$の区間が$[0, a]$、$theta$の区間が$[0, pi/2]$であるため、$(a pi)/2$になる。また、針が平行線と交差する領域は、
$ integral_(0)^(pi/2) l sin theta d theta = l $
となる。よって、針が平行線と交差する確率$P$は、
$ P = l / ((a pi)/2) = (2l) / (a pi) $ <eq:prob>
と求めることができる。
今回の実験では、$y$の区間を$[a, 3a]$、$theta$の区間を$[0, pi]$とし、針の下端$y_1$、上端$y_2$を
$
cases(
y_1 = y - l sin theta,
y_2 = y + l sin theta
)
$ <eq:y>
として、$y_1$と$y_2$の積が負になるとき、針が平行線と交差すると判定している。交わった回数を$n$、全試行回数を$N$とすると、@eq:prob より、
$ pi = (2l) / (a P) = (2l N) / (a n) $
と$pi$を求めることができる。[参考:@text2024e5]
=== フローチャート
今回buffonの針問題を解くためのプログラムのフローチャートを以下に示す。ここで、$a = 1.0$、$l = 0.8$に設定した。そして、@eq:prob、@eq:y を用いて、$pi$の計算を行った。
#figure(
image("../figs/flowchart.png", width: 60%),
caption: [buffonの針問題のフローチャート],
) <fig:buffon_flowchart>
== 課題(3)
=== 乱数から$pi$を求める⽅法とその精度
$pi$を求めるのに用いられる方法として、入門的モンテカルロ法と当たり外れのモンテカルロ法がある。これら2つの方法について述べる前に、大数の法則について説明する。大数の法則とは、試行回数(一般的には標本すう)を十分大きくすると、確率変数の平均値が基の分布(母集団)の平均値に収束するという法則である。ここで、$[a, b]$で定義された関数$f(x)$と$[a, b]$に一様分布する確率変数$r$を考える。この時、$r$の確率密度関数$rho(r)$は、@eq:uniform と同様の式で表される。この時、$f(x)$の平均値$E(f(x))$は、
$ E(f(x)) = integral_(a)^b f(x) rho(r) d r = I / (b - a) $ <eq:mean>
となる。ここで、$I$は$f(x)$の区間$[a, b]$での積分値である。また、大数の法則より、十分大きい$N$に対して、$N$個の一様乱数$r_i$を発生させたとすると、$f(x)$の平均値は、
$ E(f(r)) tilde.eq 1 / N sum_(i=1)^(N) f(r_i) $ <eq:mean2>
となる。そして、@eq:mean と@eq:mean2 より、$I$は、
$ I tilde.eq (b - a) / N sum_(i=1)^(N) f(r_i) $ <eq:mean3>
と近似できる。これが入門的モンテカルロ法による求積である。
次に、$0 <= f(x) <= c $として、$0 <= y <= c$、$a <= x <= b$の領域を考える。この領域に、$N$個の一様乱数$(x_i, y_i)$を発生させ、$f(x_i) >= y_i$の時の数を$n$とする。この時、領域と$f(x)$より下の領域の面積比は、
$ 1 /(c (b - a)) integral_(a)^b f(x) d x tilde.eq n / N $ <eq:monte>
となる。この式より、$I$は、
$ I tilde.eq c (b - a) n / N $ <eq:monte2>
となる。このように、$f(x_i) >= y_i$に当てはまるかどうかで積分値を求める方法を当たり外れのモンテカルロ法という。
ここで、$f(x) = sqrt(1 - x^2)$、$a = 0$、$b = 1$とすることで、
$ pi = 4 I $
と求めることができる。
次に、これら2つの方法の制度について考える。@fig:monte_hit_comp で見たように、どちらの手法も初めは回数が増えるにつれて精度が向上しているが、試行回数が$10^5$を超えてからは、精度の向上が$0$付近で緩やかになっている。大数の法則を考えると、初めは、試行回数が少ないため、平均値が母集団の平均値に収束していく様子がはっきりと見られるが、そこから試行回数が増えていくと、乱数の分布が理想的なものに近づくため誤差が$0$付近で一定になると考えられ、シミュレーション結果もそれを裏付けている。また、@fig:buffon_result、@fig:monte_result、@fig:hit_result を比べると、$30000$回の時に、$pi$の値の誤差が、入門的モンテカルロ法、当たり外れのモンテカルロ法の方がbuffonの針よりも小さく、精度が良いことがわかる。よって、小さい$N$($10^5$以下)なら、入門的モンテカルロ法を使い、大きい$N$($10^5$以上)なら、入門的モンテカルロ法、当たり外れのモンテカルロ法のどちらかを使うことで、精度良く$pi$の値を求めることができると考えられる。
== 課題(4)
=== ランダムウォークの理論値と実験値の比較
@fig:randomwalk_comp を見ると、ランダムウォークの理論値と実験値は酷似していることがわかる。さらに、各$X$の値における理論値と実験値の相対誤差を計算した結果を@tab:randomwalk_error に示す。
#figure(
caption: [ランダムウォークの理論値と実験値の比較],
table(
columns: 2,
stroke: (none),
table.header(
[$X$], [相対誤差 "/%"]
),
table.hline(),
[-10], [3.02],
[-8], [0.362],
[-6], [0.363],
[-4], [0.0192],
[-2], [0.145],
[0], [0.143],
[2], [0.226],
[4], [0.00469],
[6], [0.367],
[8], [1.01],
[10], [2.41],
table.hline(),
)
) <tab:randomwalk_error>
この表から、$X$の絶対値が大きくなるにつれ、相対誤差が大きくなるという傾向があることがわかる。これは、大数の法則を考えると、試行回数が多くなるにつれて平均値が理論値に収束していくため、平均値付近の値は理論値に近づくが、平均値から離れるにつれて、誤差が大きくなると考えられる。また、実際に平均値付近の$X$での誤差を確認してみると、$X$の絶対値が$4$の場所が誤差が最も小さくなっている。これは、発生させた乱数が、確率$1/2$で右、左に移動する様子を完全に再現できていないためであると考えられる。何故なら、確率が$1/2$からズレると、平均値も同時にずれてしまう。そのため、$X$の絶対値が$4$の場所付近が平均値となり、大数の法則により、誤差が最も小さくなっていると考えられる。
=== 二項分布に従う確率分布の理論値と実験値の比較
@fig:binomial_comp だけを見ると、理論値と実験値は酷似しているように見える。より精度を確認するために、各患者数における理論値と実験値の相対誤差を計算した結果を@fig:binomial に重ねて表示させた。その結果を@fig:binomial_error に示す。この図から横軸の値が$0, 1, 2$の時は、相対誤差が$1$になっていることがわかる。しかし、この結果は妥当であると言える。なぜなら、患者数が$0, 1, 2$の時は、理論値が$0$に近く、オーダーが$10^(-9)$よりも小さいため、試行回数が$10^8$の時に実験値が$1$を超えることがないため、実験値が$0$として観測され、相対誤差が$1$になっていると考えられる。これを踏まえて、患者数が$0, 1, 2$の時の相対誤差を除いた結果を@fig:binomial_error2 に示す。この図から、期待値に近い患者数の時は、相対誤差が小さく、患者数が多くなるにつれて、相対誤差が大きくなるという傾向があることがわかる。しかし、患者数が$3$の時は、誤差が小さくなっている様子が見られる。これは、患者数が$0, 1, 2$の時と同様にオーダーの問題で、理論値が$10^(-8)$なため、試行回数が$10^8$の時に実験値が1の位になるため、ずれによる変動を受けにくいと考えられ、それに対し、患者数が$4,5$などの場所では、オーダーが$10^(-7)$なため、桁数が2桁になるため、1の位がずれの影響を受けやすいと考えられる。その結果、患者数が$3$の時の相対誤差が小さくなっていると考えられる。
#figure(
image("../figs/patients_error1.png", width: 90%),
caption: [二項分布の理論値と相対誤差],
) <fig:binomial_error>
#figure(
image("../figs/patients_error2.png", width: 90%),
caption: [二項分布の理論値と相対誤差(患者数が0, 1, 2の時を除く)],
) <fig:binomial_error2>
= 結論
今回の実験では、乱数を用いて$pi$を求める方法、buffonの針問題、ランダムウォーク、二項分布に従う確率分布をシミュレーションするプログラムを実行し、その結果を比較した。その結果、$pi$を求める方法として、入門的モンテカルロ法、当たり外れのモンテカルロ法があることがわかった。また、これら2つの方法の精度について考察した結果、試行回数が$10^5$を超えると、精度の向上が緩やかになることがわかった。また、$30000$回の時に、$pi$の値の誤差が、入門的モンテカルロ法、当たり外れのモンテカルロ法の方がbuffonの針よりも小さく、精度が良いことがわかった。そして、ランダムウォーク、二項分布に従う確率分布の理論値と実験値の比較を行った結果、理論値と実験値は酷似していることがわかった。また、理論値と実験値の相対誤差を計算した結果、平均値から離れるにつれて、誤差が大きくなるという傾向があることがわかった。しかし、平均値付近の値は理論値に近づくため、誤差が小さくなることがわかった。 |
https://github.com/LDemetrios/Conspects-4sem | https://raw.githubusercontent.com/LDemetrios/Conspects-4sem/master/typst/styles/themes/dark.typ | typst | #let background = rgb("#212121")
#let foreground =rgb("#f0f0f0")
#let red-ish = rgb("#ff7777")
#let green-ish = rgb("#77ff77")
#let blue-ish = rgb("#7777ff")
#let yellow-ish = rgb("#ffff77")
#let pagewidth = none
#let pageheight = auto
|
|
https://github.com/LucaCiucci/custom-typst | https://raw.githubusercontent.com/LucaCiucci/custom-typst/main/README.md | markdown | # custom-typst
Custom typst
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/meta-environments/env-posters.typ | typst |
#import "/meta-environments/env-features.typ": *
#import "/meta-environments/env-branding.typ": *
/*
* TEXT STYLES
*
* Renders `content` with the module's text styling. This is useful for content
* that is outside of the `template` container but which should be visually consistent.
*/
#let apply-text-styles(content) = {
set text(
font: font.sans
)
set par(
leading: 0.8em,
)
show heading.where(level: 1): it => [
#pagebreak(weak: true)
#set text(size: 24pt, font: font.sans, number-type: "lining", weight: "bold",)
#block(it.body)
]
show heading.where(level: 2): it => text(
size: 18pt,
font: font.sans,
number-type: "lining",
weight: "semibold",
{
v(0.6em)
it.body
}
)
show heading.where(level: 3): it => text(
size: 14pt,
font: font.sans,
number-type: "lining",
weight: "semibold",
it.body
)
show heading.where(level: 4): it => text(
size: 12pt,
font: font.sans,
number-type: "lining",
weight: "semibold",
it.body
)
show figure: it => align(center)[
#set text(size: 9pt, font: font.sans)
#it.body
/*#it.supplement*/ #it.caption
]
// Link support
show link: it => {
if type(it.dest) == str and it.dest.contains("http"){
set text(font: font.link, size: 9pt)
it
} else if type(it.dest) != str {
set text(color.link)
it
} else {
set text(color.link)
it
}
}
// Reference support
show ref: it => {
if it.element.numbering == none {
// Use your custom scheme
link(it.target, it.element.body)
} else {
// Default `ref`
it
}
}
// Enums
set enum(numbering: "1.a.")
content
}
#let large_poster(
title: "Poster Title",
category: "Shop Area",
authors: ("Someone","Some<NAME>"),
date: datetime.today(),
wrapper: apply-text-styles,
doc,
) = {
set page(
margin: (top: 0.5in, left: 0.5in, bottom: 0.5in, right: 0.5in),
width: 26in,
height: 40in,
)
set document(title: title,
author: authors,
keywords: ("protohaven", "poster"),
date: date,
)
set text(
font: font.sans,
)
// Poster Heading
grid(
columns: (8in, 1fr),
gutter: 0.5in,
image("/common-graphics/branding/logo-protohaven-p.svg"),
align(bottom,text(size: 72pt, baseline: -6pt, category))
)
align(center,text(weight: "bold", size: 144pt, title))
// The rest of the content
wrapper(doc)
}
#let small_poster(
title: "Poster Title",
category: "Shop Area",
authors: ("Someone","<NAME>"),
date: datetime.today(),
wrapper: apply-text-styles,
doc,
) = {
set page(
margin: (top: 0.5in, left: 0.5in, bottom: 0.5in, right: 0.5in),
width: 8.5in,
height: 11in,
)
set document(title: title,
author: authors,
keywords: ("protohaven", "poster"),
date: date,
)
set text(
font: font.sans,
)
// Poster Heading
grid(
columns: (0.32in, 1fr),
gutter: 0.2in,
image("/common-graphics/branding/logo-protohaven-p.svg"),
align(bottom,text(size: 32pt, baseline: -2pt, category))
)
align(center,text(weight: "bold", size: 48pt, title))
// The rest of the content
wrapper(doc)
} |
|
https://github.com/paylanon/godot-typst | https://raw.githubusercontent.com/paylanon/godot-typst/main/README.md | markdown | MIT License | <p align="center">
<img src="https://github.com/paylhorse/godot-typst/assets/74363924/61433620-8126-46a4-8deb-39c7eac1c5f1" alt="logo" width="200"/>
</p>
<p align="center">
<b>Render Typst expressions in <a href="https://github.com/godotengine/godot">Godot 4</a></b>
</p>
<p align="center">
<b>Requires <a href="https://github.com/godot-rust/gdext">godot-rust</a> and <a href="https://github.com/typst/typst">Typst</a></b>
</p>
## ABOUT
A robust $\TeX$ alternative, directly in your Godot application.
Inspired by [GodoTeX](https://github.com/file-acomplaint/GodoTeX). Works similarly by providing custom ```TextureRect``` and ```Sprite2D``` nodes that renders Typst expressions, continually updated at runtime.

## INSTALLATION
#### (1) Ensure Typst is installed to system.
```bash
$ typst --version
```
#### (2) Add this crate as a dependency to your godot-rust project. In ``Cargo.toml``:
```toml
[dependencies]
godot-typst = { git = "https://github.com/paylanon/godot-typst" }
```
#### (3) Import the TypstTextureRect and TypstSprite classes to automatically add them to Godot. Ignore warning.
In ``lib.rs``:
```rs
use godot_typst::TypstTextureRect;
use godot_typst::TypstSprite;
```
**Done!**
Find the example project at example/typst_project in this repo.
|
https://github.com/exusiaiwei/My-brilliant-CV | https://raw.githubusercontent.com/exusiaiwei/My-brilliant-CV/main/modules/education.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Education")
#cvEntry(
title: [Bachelor of Arts in Literature],
society: [Wuhan University],
date: [2019.9 - 2023.6],
location: [China],
logo: "../src/logos/whu.png",
description: list(
[GPA: 3.69/4.0],
[Thesis: Research on Network Language Classification Features Based on Multidimensional Model],
[Course: Introduction of language technologies #hBar() Computer Fundamentals #hBar() Cognitive Linguistics #hBar() Technology of Digital Communication ]
)
) |
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/_settings/typst/template-qk.typ | typst | #let conf(
title: none,
lesson: none,
author: "<NAME>.",
col: 1,
doc,
) = {
set text(font: "Times New Roman")
set page("a4",
header: [
#columns(2)[
#set align(left)
#set text(size: 12pt)
#author
#colbreak()
#set align(right)
#datetime.today().display("[month]-[year]")
]
#v(13pt)
],
header-ascent: 0%,
footer-descent: 20%,
margin: (x: 14mm, top: 14mm, bottom: 14mm),
numbering: "1/1"
)
doc
}
|
|
https://github.com/wdmhswj/myTypsts | https://raw.githubusercontent.com/wdmhswj/myTypsts/main/test/test.typ | typst | = _Introduction_
== title_level2
In this report, we will explore the
various factors that influence fluid
dynamics in glaciers and how they
contribute to the formation and
behaviour of these natural structures.
+ list1
- sublist1
- sublist2
+ list2
- Glaciers as the one shown in @glaciers will cease to exist if we don't take action soon!
#figure(
image("test.png", width: 70%),
caption: [
_Glaciers_ form an important part
of the earth's climate system.
],
)<glaciers>
= Methods
We follow the MER models
established in @van2019capsulenet.
#bibliography("test.bib")
The equation $Q = rho A v + C$ defines the glacier flow rate.
The flow rate of a glacier is
defined by the following equation:
$ Q = rho A v + C $
The flow rate of a glacier is given
by the following equation:
$ Q = rho A v + "time offset" $
Total displaced soil by glacial flow:
$ 7.32 beta +
sum_(i=0)^nabla Q_i / 2 $
Total displaced soil by glacial flow:
$ 7.32 beta +
sum_(i=0)^nabla
(Q_i (a_i - epsilon)) / 2 $
$ v := vec(x_1, x_2, x_3) $
$ a arrow.squiggly b $
|
|
https://github.com/PorterLu/Typst | https://raw.githubusercontent.com/PorterLu/Typst/main/README.md | markdown | # Typst
Typst is a new markup-based typesetting system for the sciences. The purpose of this repository is recording my learning process. Let's get started!
|
|
https://github.com/EricWay1024/Homological-Algebra-Notes | https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/b-ext1.typ | typst | #import "../libs/template.typ": *
= $Ext$ and Extensions
<ext-extension>
== Extensions
#definition[
Let $A$ and $B$ be $R$-modules. An *extension* of $A$ by $B$ is a #sest
$
ses(B, X, A).
$
Two extensions are *equivalent* if there is a commutative diagram
// #align(center,image("../imgs/2023-11-25-13-22-33.png",width:50%))
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwE<KEY>T<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$0$]),
node((0, 1), [$B$]),
node((0, 2), [$X$]),
node((0, 3), [$A$]),
node((0, 4), [$0$]),
node((1, 0), [$0$]),
node((1, 1), [$B$]),
node((1, 2), [$X'$]),
node((1, 3), [$A$]),
node((1, 4), [$0$]),
arr((0, 0), (0, 1), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 3), (0, 4), []),
arr((0, 1), (1, 1), [$=$]),
arr((0, 2), (1, 2), [$iso$]),
arr((0, 3), (1, 3), [$=$]),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), []),
arr((1, 2), (1, 3), []),
arr((1, 3), (1, 4), []),
))
This is an equivalence relation. We denote $e(A, B)$ as the equivalence classes of extensions of $A$ by $B$.
An extension is *split* if it is equivalent to
$
ses(B, A xor B, A).
$
]
#lemma[
If $Ext^1 (A, B) = 0$, then every extension of $A$ by $B$ is split.
]
#proof[
We look at the #lest of $Ext^ast (A, -)$:
$
hom (A, X) -> hom (A, A) ->^diff Ext^1 (A, B) = 0.
$
The first arrow is a surjection, so
$id_A in hom (A, A)$ can always lift to a splitting $sigma: A -> X$. (It is helpful to recall the proof of @projective-split.)
]
From the above proof, we also see that $diff(id_A) in Ext^1 (A, B)$ is the obstruction to the extension of $A$ by $B$ being split: the extension is split if and only if $id_A$ lifts to some element in $hom (A, X)$, if and only if $0 = diff (id_A)$.
#endlec(14)
#lemma[
Let $ses(B, X, A)$ be an extension of $A$ by $B$, and let $k : C -> A$. Then there exists an extension $ses(B, Y, C)$ of $C$ by $B$, unique up to extension equivalence, such that the following diagram commutes:
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBpiBdUkANwEMAbAVxiRACEQBf<KEY>clVqMWbABrdeIDNjwEi<KEY>BOX<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((1, 1), [$B$]),
node((1, 2), [$X$]),
node((1, 3), [$A$]),
node((1, 0), [$0$]),
node((1, 4), [$0$]),
node((0, 1), [$B$]),
node((0, 3), [$C$]),
node((0, 2), [$Y$]),
node((0, 0), [$0$]),
node((0, 4), [$0$]),
arr((0, 3), (1, 3), [$k$]),
arr((0, 1), (1, 1), [$id_B$]),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), []),
arr((1, 2), (1, 3), []),
arr((1, 3), (1, 4), []),
arr((0, 2), (1, 2), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 0), (0, 1), []),
arr((0, 3), (0, 4), []),
))
]
<rotman729>
#proof[
@rotman[Lemma 7.29].
]
#theorem[
Given $R$-modules $A$ and $B$, the map
$
Theta: e(A, B) &-> Ext_R^1 (A, B) \
[ses(B, X, A)] &mapsto diff(id_A)
$
is a bijection, and split extensions correspond to $0 in Ext_R^1 (A, B)$.
]
#proof(title: "Proof sketch")[
We first show that $Theta$ is surjective. Let $x in Ext^1_R (A, B)$, and we want to construct some extension $xi = (ses(B, X, A))$ such that $Theta(xi) = x$.
Since $RMod$ has enough injectives, we can find a #sest
$
ses(B, I, N, f:j, g: pi),
$
where $I$ is injective and $pi = coker(j)$. Since $I$ is injective, we have $Ext^1_R (A, I) = 0$ by @ext-injective, so the #lest of $Ext$ gives an exact sequence
$
0 -> homr (A, B) -> homr (A, I) -> homr (A, N) ->^(delta') Ext^1_R (A, B) -> 0.
$
Now $delta'$ is surjective, so $x in Ext^1_R (A, B)$ can be lifted to some $beta in homr (A, N)$ such that $delta' (beta) = x$. Now we have the following:
// https://t.yw.je/#N4Igdg9gJgpgzi<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((1, 1), [$B$]),
node((1, 2), [$I$]),
node((1, 3), [$N$]),
node((1, 0), [$0$]),
node((1, 4), [$0$]),
node((0, 1), [$B$]),
node((0, 3), [$A$]),
arr((0, 3), (1, 3), [$beta$]),
arr((0, 1), (1, 1), [$id_B$]),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), [$j$]),
arr((1, 2), (1, 3), [$pi$]),
arr((1, 3), (1, 4), []),
))
We now apply @rotman729 to find a commutative diagram with exact rows that completes the above diagram:
// https://t.yw.je/#N4Igdg9gJg<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((1, 1), [$B$]),
node((1, 2), [$I$]),
node((1, 3), [$N$]),
node((1, 0), [$0$]),
node((1, 4), [$0$]),
node((0, 1), [$B$]),
node((0, 3), [$A$]),
node((0, 2), [$X$]),
node((0, 0), [$0$]),
node((0, 4), [$0$]),
arr((0, 3), (1, 3), [$beta$]),
arr((0, 1), (1, 1), [$id_B$]),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), [$j$]),
arr((1, 2), (1, 3), [$pi$]),
arr((1, 3), (1, 4), []),
arr((0, 2), (1, 2), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 0), (0, 1), []),
arr((0, 3), (0, 4), []),
))
where the top row is the extension $xi$ we claim to have $Theta(xi) = x$. To prove that it is indeed the case, notice by naturality of the #lest of $Ext$, there is a commutative diagram
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZ<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$homr(A, A)$]),
node((0, 1), [$Ext^1_R (A, B)$]),
node((1, 0), [$homr(A, N)$]),
node((1, 1), [$Ext^1_R (A, B)$]),
arr((0, 1), (1, 1), [$id$]),
arr((0, 0), (0, 1), [$delta$]),
arr((0, 0), (1, 0), [$beta oo -$]),
arr((1, 0), (1, 1), [$delta'$]),
))
from which we see
$
Theta(xi) = delta(id_A) = delta'((beta oo -)(id_A)) = delta'(beta) = x.
$
Thus we have shown $Theta$ is surjective.
Now again by @rotman729, the extension $xi$ we have constructed is unique up to equivalence, so we have effectively constructed a well-defined map
$
Phi : Ext^1_R (A, B) -> e(A, B)
$
with $Theta(Phi(x)) = x$ (if we can show that $Phi$ is independent of the choices of $I$ and $beta$).
The rest of the proof is to show that $Phi(Theta([xi])) = [xi]$ for any extension class $[xi] in e(A, B)$.
]
== Baer Sum
When a set $X$ has a bijection with the underlying map of a group $G$, then in general $X$ can be also equipped with a group structure. We are therefore interested in characterising the group structure on $e(A, B)$, in view of its bijection with the group $Ext^1(A, B)$. The natural addition operation on $e(A, B)$ was first explicitly ascertained by <NAME>.
#definition[
Let
$ xi_1 colon 0 arrow.r B arrow.r^(i_1) X_1 arrow.r^(pi_1) A arrow.r 0 comma quad xi_2 colon 0 arrow.r B arrow.r^(i_2) X_2 arrow.r^(pi_2) A arrow.r 0 $
be extensions of $A$ by $B$. Let
$ X^(prime prime) eq X_1 times_A X_2 eq lr({lr((x_1 comma x_2)) in X_1 times X_2 colon pi_1 lr((x_1)) eq pi_2 lr((x_2))}) $
and let
$ Y eq X^(prime prime) / lr({lr((i_1 lr((b)) comma minus i_2 lr((b)))) colon b in B}). $ Then the sequence $ 0 arrow.r B arrow.r^i Y arrow.r^pi A arrow.r 0 $ is
called the *Baer sum* of $xi$ and $xi^prime$, where we have maps
$ i colon B &arrow.r Y \ b &arrow.r.bar lr((i_1 lr((b)) comma 0)) $
and
$ pi colon Y &arrow.r A \ lr((x_1 comma x_2)) &arrow.r.bar pi_1 lr((x_1)) plus pi_2 lr((x_2)). $
]
#lemma[
The Baer sum is
a well-defined extension of $A$ by $B$.
]
#lemma[
The set of
equivalence classes of extensions of $A$ by $B$ is an abelian group
under the Baer sum, and the map $Theta$ is an isomorphism of abelian
groups.
]
== Yoneda $Ext$ Groups
Using extensions of $A$ by $B$, we can define $"Ext"^n lr((A comma B))$
in any abelian category, not necessarily with enough projectives or injectives.
We call this the Yoneda $Ext$ group.
#definition[
We define the Yoneda $"Ext"^n lr((A comma B))$ to be the
equivalence classes of exact sequences
$ xi colon 0 arrow.r B arrow.r X_n arrow.r dots.h arrow.r X_1 arrow.r A arrow.r 0 $
under the equivalence relation generated by $xi tilde.op xi^prime$ if
there is a diagram
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRGJAF9T1Nd9CKAIzkqtRizYAhLjxAZseAkQBMo6vWatEIABoB9Qt16KBRAMzrxWtgDp7sk-2UoALFc2SdBoY-l8lQWQAVg8JbRAAQT8FZyCANjCbHQ5jf1MXElIhMU8I1LlYwKIRHI1w6RiAsxQ1MusvPQByQyqMoMt6vLsHNKKa5Hcuiu8W3z7qzNDh5Ki2uKJEmcbUsRgoAHN4IlAAMwAnCABbJDIQHAgkITSD46vqC6QVG8OTxDVzy8RzF7vvh6+rl+b3cnyQwWB4IBSHikMQAHZoYgABxw5FIgCccIxSKExDheNx1zktzeQhEYMQQmeJNeVw+jypP1pfwpjPRDQiAF4-KSnpi4aDGeS4aFKdTyrMeZwKJwgA
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$0$]),
node((0, 1), [$B$]),
node((0, 2), [$X_n$]),
node((0, 3), [$...$]),
node((0, 4), [$X_1$]),
node((0, 5), [$A$]),
node((0, 6), [$0$]),
node((1, 0), [$0$]),
node((1, 1), [$B$]),
node((1, 2), [$X'_n$]),
node((1, 3), [$...$]),
node((1, 4), [$X'_1$]),
node((1, 5), [$A$]),
node((1, 6), [$0$]),
arr((0, 0), (0, 1), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 3), (0, 4), []),
arr((0, 4), (0, 5), []),
arr((0, 5), (0, 6), []),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), []),
arr((1, 2), (1, 3), []),
arr((1, 3), (1, 4), []),
arr((1, 4), (1, 5), []),
arr((1, 5), (1, 6), []),
arr((0, 1), (1, 1), [$=$]),
arr((0, 2), (1, 2), []),
arr((0, 4), (1, 4), []),
arr((0, 5), (1, 5), [$=$]),
))
// #align(center, img("2023_10_29_1d9afce33fbce6757ca2g-099(1)", width: 80%))
]
Note that the arrows $X_i arrow.r X_i^prime$ do not have to be
isomorphisms. At first glance, this seems different to our previous definition of
equivalence for extensions of $A$ by $B$. However, by the Five Lemma, when $n = 1$, the morphism $X_1 -> X'_1$ is necessarily an isomorphism.
#definition[
We again define a notion of a Baer sum. Let $xi$ and $xi^prime$ be
representatives of elements of $"Ext"^n lr((A comma B))$. Let
$X_1^(prime prime)$ be the pullback of
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZARgBoAGAXVJADcBDAGwFcYkQANAfWJAF9S6TLnyEUZYtTpNW7AIL9BIDNjwEi5UpJoMWbRJx4ByflJhQA5vCKgAZgCcIAWySaQOCEmIC7jl4gAmGg8vPko+IA
#align(center, commutative-diagram(
node-padding: (40pt, 40pt),
node((0, 1), [$X_1$]),
node((1, 1), [$A$]),
node((1, 0), [$X'_1$]),
arr((0, 1), (1, 1), []),
arr((1, 0), (1, 1), []),
))
// #block[
// #box(width: textwidth, img("2023_10_29_1d9afce33fbce6757ca2g-099(2)", width: 15%))
// ]
and let $X_n^(prime prime)$ be the pushout of
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRACEQBfU9TXfIRQBGclVqMWbABoB9Qjz7Y8BImWHj6zVohDSA5PO7iYUAObwioAGYAnCAFskZEDghJhikHcfPqbpAAmLgouIA
#align(center, commutative-diagram(
node-padding: (40pt, 40pt),
node((0, 0), [$B$]),
node((0, 1), [$X_n$]),
node((1, 0), [$X'_n$]),
arr((0, 0), (0, 1), []),
arr((0, 0), (1, 0), []),
))
// #block[
// #box(width: textwidth, img("2023_10_29_1d9afce33fbce6757ca2g-099", width: 15%))
// ]
Let $Y_n$ be the quotient of $X_n^(prime prime)$ by the antidiagonal.
Then the Baer sum is
$ 0 arrow.r B arrow.r Y_n arrow.r X_(n minus 1) xor X_(n minus 1)^prime arrow.r dots.h arrow.r X_2 xor X_2^prime arrow.r X_1^(prime prime) arrow.r A arrow.r 0. $
]
Suppose that $cal(A)$ has enough projectives and $P_bullet arrow.r A$ is
a projective resolution. Consider the diagram
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZANgBoAGAXVJADcBDAGwFcYkQBBEAX1PU1z5CKMgEZqdJq3Zde-bHgJEA7BQkMWbRCHI8+IDAqErS4mhunbdcgwMXDkAVlPqpWkAA0A+tf2HBSigALC7mbuwAdFF68gEOAMyhkprs3oQ2-vZEAExJFu4AQjG2RoFOamEp2gAKPsWZxsEVyZYgURH1do3IiVSVrbUAFGAAtKIAlJ2lDrl9Le616X5dZaLN+exDYADUE1NxROTr4drt+<KEY>
#align(center, commutative-diagram(
node-padding: (40pt, 40pt),
node((0, 6), [$A$]),
node((1, 6), [$A$]),
node((0, 7), [$0$]),
node((1, 7), [$0$]),
node((1, 5), [$X_0$]),
node((1, 4), [$...$]),
node((1, 3), [$X_n$]),
node((1, 2), [$B$]),
node((0, 5), [$P_0$]),
node((0, 4), [$...$]),
node((0, 3), [$P_(n-1)$]),
node((0, 2), [$P_n$]),
node((0, 1), [$P_(n+1)$]),
node((0, 0), [$...$]),
node((1, 1), [$0$]),
arr((0, 0), (0, 1), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 3), (0, 4), []),
arr((0, 4), (0, 5), []),
arr((0, 5), (0, 6), []),
arr((0, 6), (0, 7), []),
arr((0, 6), (1, 6), [$=$]),
arr((1, 4), (1, 5), []),
arr((1, 3), (1, 4), []),
arr((1, 2), (1, 3), []),
arr((1, 1), (1, 2), []),
arr((1, 5), (1, 6), []),
arr((1, 6), (1, 7), []),
))
By @comparison, there is a chain map from the top row to the
bottom row lifting id : $A arrow.r A$. Setting
$M eq Ker d_n^(lr((P)))$ gives a diagram
// https://t.yw.je/#N4Igdg9gJgpgzi<KEY>
#align(center, commutative-diagram(
node-padding: (40pt, 40pt),
node((0, 5), [$A$]),
node((1, 5), [$A$]),
node((0, 6), [$0$]),
node((1, 6), [$0$]),
node((1, 4), [$X_0$]),
node((1, 3), [$...$]),
node((1, 2), [$X_n$]),
node((1, 1), [$B$]),
node((0, 4), [$P_0$]),
node((0, 3), [$...$]),
node((0, 2), [$P_(n-1)$]),
node((0, 1), [$M$]),
node((0, 0), [$0$]),
node((1, 0), [$0$]),
arr((0, 0), (0, 1), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 3), (0, 4), []),
arr((0, 4), (0, 5), []),
arr((0, 5), (0, 6), []),
arr((0, 5), (1, 5), [$=$]),
arr((1, 3), (1, 4), []),
arr((1, 2), (1, 3), []),
arr((1, 1), (1, 2), []),
arr((1, 0), (1, 1), []),
arr((1, 4), (1, 5), []),
arr((1, 5), (1, 6), []),
arr((0, 1), (1, 1), [$beta$]),
arr((0, 2), (1, 2), []),
arr((0, 4), (1, 4), []),
))
// #block[
// #box(width: textwidth, img("2023_10_29_1d9afce33fbce6757ca2g-100", width: 80%))
// ]
with exact rows.
#proposition[There is a natural isomorphism between Yoneda
$Ext ^n$ and the standard $"Ext"^n$.]
|
|
https://github.com/mdnls/typst-template | https://raw.githubusercontent.com/mdnls/typst-template/main/README.md | markdown | = Typst Template
Here is my personal template for the [Typst](typst.app).
|
|
https://github.com/RemiSaurel/miage-rapide-tp | https://raw.githubusercontent.com/RemiSaurel/miage-rapide-tp/main/0.1.2/README.md | markdown | # miage-rapide-tp
Typst template to generate a practical work report for students of the MIAGE (Méthodes Informatiques Appliquées à la Gestion des Entreprises).
## 🧑💻 Usage
- Directly from [Typst web app](https://typst.app/) by clicking "Start from template" on the dashboard and searching for `miage-rapide-tp`.
- With CLI:
```
typst init @preview/miage-rapide-tp:{version}
```
## 🚀 Features
- Cover page
- Table of contents (optionnal)
- `question` = automatically generates a question number (optionnal) with the content of the question
- `code-block` = code block with syntax highlighting. You can pass a filepath or code directly to display in the block
- `remarque` = a remark block with content and color
### Cover page
The conf looks like this:
```typ
#let conf(
subtitle: none,
authors: (),
toc: true,
lang: "fr",
font: "Satoshi",
date: none,
years: (2024, 2025),
years-label: "Année universitaire",
title,
doc,
)
```
### Question
A question can be added like this:
```typ
#question("Une question avec numéro ?")
#question("Une question sans numéro ?", counter: false)
```
The first argument is the question content, and the second (OPTIONAL) is the counter. If `counter` is set to `false`, the question will not be numbered.
### Code-block
To use a `code-block`, you can do as follows :
```typ
#code-block(read("code/main.py"), "py")
#code-block(read("code/example.sql"), "sql", title: "Classic SQL")
```
The first argument is the code to display, the second is the language of the code, and the third is the title of the code block.
### Remarque
To use a `remarque`, you can do as follows :
```typ
#remarque("Ceci est une remarque")
#remarque("Remarque personnalisée", bg-color: olive, text-color: white)
```
You can change the bg-color and text-color of the remark block to match your needs.
## 📝 License
This is MIT licensed.
> Rapide means fast in French. tp is the abbreviation of "travaux pratiques" which means practical work. MIAGE is a French degree in computer science applied to management.
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/komplexitaet/master_tree.typ | typst | #import "@preview/cetz:0.2.2"
#let a = 2
#let max_depth = 4
#let rec_tree(root, depth: 0) = {
if depth == max_depth {return root}
let children = if depth == max_depth - 2 {
([...], ) * a
} else if depth == max_depth - 1 {
($1$, ) * a
} else {
($n/b^(#(depth+1))$, ) * a
}
children = children.map(c => rec_tree(c, depth: depth + 1))
return (root, ..children)
}
#cetz.canvas({
import cetz.draw: *
import cetz.tree
set-style(content: (padding: 6pt))
tree.tree(
//($n$, $n/b$, $n/b$, $n dot b ^(-1)$)
rec_tree($n$),
spread: .35,
grow: 1.2,
name: "tree",
)
set-style(content: (padding: 0pt))
cetz.decorations.flat-brace(
(rel: (-4pt, 0), to: "tree.south-west"),
(rel: (-4pt, 0), to: "tree.north-west"),
name: "height"
)
content("height.content", anchor: "south", angle: 90deg)[$log_b n$]
cetz.decorations.flat-brace(
(rel: (0, -4pt), to: "tree.south-east"),
(rel: (0, -4pt), to: "tree.south-west"),
name: "width"
)
content("width.content", anchor: "north")[$a^(log_b n)$]
}) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/subelement-panic_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Outline entry (pre-emptive)
// // Error: 2-48 cannot outline text
// #outline.entry(1, [Hello], [World!], none, [1]) |
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/hide.typ | typst | // Test the `hide` function.
--- hide-text ---
AB #h(1fr) CD \
#hide[A]B #h(1fr) C#hide[D]
--- hide-line ---
Hidden:
#hide[#line(length: 100%)]
#line(length: 100%)
--- hide-table ---
Hidden:
#hide(table(rows: 2, columns: 2)[a][b][c][d])
#table(rows: 2, columns: 2)[a][b][c][d]
--- hide-polygon ---
Hidden:
#hide[
#polygon((20%, 0pt),
(60%, 0pt),
(80%, 2cm),
(0%, 2cm),)
]
#polygon((20%, 0pt),
(60%, 0pt),
(80%, 2cm),
(0%, 2cm),)
--- hide-rect ---
#set rect(
inset: 8pt,
fill: rgb("e4e5ea"),
width: 100%,
)
Hidden:
#hide[
#grid(
columns: (1fr, 1fr, 2fr),
rows: (auto, 40pt),
gutter: 3pt,
rect[A],
rect[B],
rect[C],
rect(height: 100%)[D],
)
]
#grid(
columns: (1fr, 1fr, 2fr),
rows: (auto, 40pt),
gutter: 3pt,
rect[A],
rect[B],
rect[C],
rect(height: 100%)[D],
)
--- hide-list ---
Hidden:
#hide[
- 1
- 2
1. A
2. B
- 3
]
- 1
- 2
1. A
2. B
- 3
--- hide-image ---
Hidden:
#hide(image("/assets/images/tiger.jpg", width: 5cm, height: 1cm,))
#image("/assets/images/tiger.jpg", width: 5cm, height: 1cm,)
--- issue-622-hide-meta-cite ---
// Test that metadata of hidden stuff stays available.
#set cite(style: "chicago-notes")
A pirate. @arrgh \
#set text(2pt)
#hide[
A @arrgh pirate.
#bibliography("/assets/bib/works.bib")
]
--- issue-622-hide-meta-outline ---
#set text(8pt)
#outline()
#set text(2pt)
#hide(block(grid(
[= A],
[= B],
block(grid(
[= C],
[= D],
))
)))
|
|
https://github.com/typst-community/mantodea | https://raw.githubusercontent.com/typst-community/mantodea/main/src/_pkg.typ | typst | MIT License | #import "@preview/codelst:2.0.0"
#import "@preview/hydra:0.4.0"
#import "@preview/showybox:2.0.1"
#import "@preview/t4t:0.3.2"
#import "@local/valkyrie:0.2.0" as z
|
https://github.com/naotiki/documents | https://raw.githubusercontent.com/naotiki/documents/main/emacs-cheetsheet/document.typ | typst | #import "@preview/tablex:0.0.5": *
#let mainfont = "UDEV Gothic 35"
#let color1 = rgb("#6e7b8b") // LightSteelBlue4
#set text (font: mainfont, size: 10pt, lang: "ja" )
#set page( paper: "a4",
//flipped: true,
columns: 1,
margin: (left: 1cm, right: 1cm, top: 0.5cm, bottom: 0.2cm)
)
#show heading: it => [
#set align(center)
#set text(12pt, weight: "bold", font: mainfont)
#block(it.body)
#v(5pt)
]
#let mytab(header, e, color1, color2) = {
tablex(
columns: (13.2fr, 6.8fr),
rows: (18pt, 15pt), // first, repeat for rest
align: left + horizon,
row-gutter: 0pt,
stroke: none,
auto-lines: false,
fill: (col, row) => if calc.even(row) { color2 } else { white },
colspanx(2, fill: color1)[#text(9pt, white)[*#header*]],
..e.map(
row => (
if row.keys().at(0) == "$twocolumn" {
colspanx(2, align: center + horizon)[ #row.values().at(0) ] }
else
{ (row.keys().at(0), row.values().at(0)) } )
).flatten(),
//colspanx(2)[],
hlinex(stroke: color1 + 2pt) //gutter-restrict: top
)
}
#let k = yaml("keyboard.yaml")
= Emacs チートシート
#place(
top + right,
[
#datetime.today().display()
],
)
#for j in k.Kbd {
let chap = j.keys().at(0)
let entries = j.values().at(0)
mytab(chap, entries, color1, color1.lighten(65%))
v(8pt)
v(1fr)
}
//#line(length: 100%,stroke:rgb("#000000").lighten(65%))
|
|
https://github.com/rabarbra/cv | https://raw.githubusercontent.com/rabarbra/cv/main/cv_de.typ | typst | #import "render.typ": render
#render(
yaml("cv.de.yml")
) |
|
https://github.com/mintjesba/JIE-Typst-Template | https://raw.githubusercontent.com/mintjesba/JIE-Typst-Template/main/jie-subm/main.typ | typst | #import "jie-subm.typ": *
#show: doc => jie-subm(
show-as-article: false, // Change to true to get article-like output
article-type: [
[Article Type]
],
title: [
[Article Title]
],
subtitle: [
[Article Subtitle (optional)]
],
authors: (
[Author A], [Author B], [Author C], [Author D], [Author E]
),
institutions: (
[Department Name, Institution I, City, Country],
[Department Name, Institution II, City, Country],
[Department Name, Institution III, City, Country],
[Department Name, Institution IV, City, Country],
[Department Name, Institution V, City, Country],
),
corresponding-author: [
[Insert Corresponding Author information here. Include mailing address, email address and, if desired, website address.]
],
conflict-of-interest-statement: [
[Insert Conflict of Interest Statement here. If no conflict of interest exists, please use the wording, "The authors declare no conflict of interest."]
],
data-availability-statement: [
[Insert the relevant Data Availability Statement here. For sample statements, see http://jie.click/data-statements.]
],
keywords: (
[industrial ecology], [keyword 2], [keyword 3], [keyword 4], [keyword 5], [keyword 6 (max.)]
),
abstract: [
[Insert Abstract here, no more than 250 words. Summarize research question, methods, findings and implications. Do not use the abstract as an introduction.]
],
doc,
)
= Introduction <sec:introduction>
[Insert Introduction text here]
= Methods <sec:methods>
[Insert Methods here. Please do not title this section “Materials and Methods” unless use of physical materials are part of the methodology.]
= Results <sec:results>
[Insert Results here. Please be sure to follow the JIE data accessibility requirements (#link("http://jie.click/dataacessibility")). Please insert tables formatted as Typst tables, not as embedded images.]
= Discussion <sec:discussion>
[Insert Discussion text here.]
= Acknowledgements <sec:acknowledgements>
[Insert Acknowledgments here.]
= Funding Information <sec:funding-information>
[Insert Funding Information here.]
= References <sec:references>
// Insert references in "refs.bib" file.
#bibliography("refs.bib", title: none, style: "apa")
= Supporting Information <sec:supporting-information>
#show-supp-inf(
(
[This supporting information describes ...], // S1
[This supporting information describes ...], // S2
// [Extra supporting information ...], // Add more if needed.
)
)
// Figure legends are auto-generated from content above. |
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/utils/template.typ | typst | #import "datestamp.typ": datestamped_outline
#let _heading_builder(
is_bold: true,
is_smallcapsed: false,
is_underlined: false,
font_size: 16pt,
line_len: 2cm,
vspace: 0.5cm,
body
) = {
if is_smallcapsed {
body = smallcaps(body)
}
if is_underlined {
body = underline(body)
}
let body = text(
size: font_size,
weight: if is_bold { "bold" } else { "regular" },
body
)
let line = line(
length: line_len,
stroke: if is_bold { 1pt } else { 0.5pt },
)
v(vspace, weak: true)
grid(
columns: (1fr, auto, 1fr),
align: (horizon + right, horizon + center, horizon + left),
column-gutter: 5pt,
line,
body,
line,
)
v(vspace, weak: true)
}
#let conf(
title: none,
subtitle: none,
author: none,
year: none,
outline_opts: none,
body
) = {
// Set metadata
set document(
title: [#title. #subtitle],
author: author,
)
[
#metadata((
title: title,
subtitle: subtitle,
)) <document_info>
]
// Set language and font size
set text(lang: "ru", size: 11pt)
set par(justify: true)
// Title page
align(center + horizon, [
#text(30pt, weight: "bold")[
#title
#subtitle
]
#text(25pt, author)
#text(20pt, year)
])
// Outline
datestamped_outline(..outline_opts)
pagebreak(weak: true)
// Page style
set page(
header: align(center)[
#title. #subtitle
#line(length: 100%, stroke: 0.5pt)
],
footer: align(center, {
line(length: 100%, stroke: 0.5pt)
counter(page).display("1")
}),
)
// Headings style
show heading.where(level: 1): h => _heading_builder(
is_bold: true,
font_size: 16pt,
line_len: 2cm,
h.body
)
show heading.where(level: 2): h => _heading_builder(
is_bold: false,
is_smallcapsed: true,
font_size: 14pt,
line_len: 1cm,
h.body
)
show heading.where(level: 3): h => _heading_builder(
is_bold: false,
is_smallcapsed: true,
is_underlined: true,
font_size: 12pt,
line_len: 0cm,
h.body
)
// Terms style
show terms.item: it => [
*Опр. *
#text(weight: "bold", it.term): #it.description
]
// Table style
set table(align: left)
// Figure style
set figure.caption(position: top)
// Body
body
}
|
|
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/Control-for-Integrator-Systems/template.typ | typst | #let template(title:"title",part:"part",body) = [
#set page(paper:"presentation-16-9",margin: 1cm)
#align(center+horizon)[
#text(rgb("#005826"),size: 1cm,title)
#text(black,size: 0.8cm,part)
]
#pagebreak()
#set page(
footer:
text(gray,size:0.4cm)[
#part
#h(1fr)
#counter(page).display(
"1/1",
both: true,
)
],
header: link("https://xsro.github.io/print/Control-for-Integrator-Systems.pdf",text(gray,size:0.2cm)[xsro.github.io (#datetime.today().display())])
)
#set text(size:0.5cm)
#set figure.caption(position: top)
#set heading(numbering: "1.1")
#set math.equation(
numbering: "(1)",
supplement: none,
)
#show ref: it => {
// provide custom reference for equations
if it.element != none and it.element.func() == math.equation {
// optional: wrap inside link, so whole label is linked
link(it.target)[(#it)]
} else {
it
}
}
#outline(indent: 1cm)
#bibliography("ref.bib",style: "gb-7714-2015-author-date")
#pagebreak()
#body
#align(center+horizon,text(blue,size:3cm)[THANKS])
]
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/introspection/locate.typ | typst | --- locate-position ---
// Test `locate`.
#v(10pt)
= Introduction <intro>
#context test(locate(<intro>).position().y, 20pt)
--- locate-position-trailing-tag ---
// Test locating the position of a tag with no following content.
#context test(here().position().y, 10pt)
#box[]
#v(10pt)
#context test(here().position().y, 20pt)
--- locate-missing-label ---
// Error: 10-25 label `<intro>` does not exist in the document
#context locate(<intro>)
--- locate-duplicate-label ---
= Introduction <intro>
= Introduction <intro>
// Error: 10-25 label `<intro>` occurs multiple times in the document
#context locate(<intro>)
--- locate-element-selector ---
#v(10pt)
= Introduction <intro>
#context test(locate(heading).position().y, 20pt)
--- locate-element-selector-no-match ---
// Error: 10-25 selector does not match any element
#context locate(heading)
--- locate-element-selector-multiple-matches ---
= Introduction <intro>
= Introduction <intro>
// Error: 10-25 selector matches multiple elements
#context locate(heading)
--- locate-between-pages ---
// Test locating tags that are before or between pages.
#set page(height: 30pt)
#context [
// Before the first page.
// (= at the very start of the first page, before the header)
#test(locate(<a>).position(), (page: 1, x: 0pt, y: 0pt))
// On the first page.
#test(locate(<b>).position(), (page: 1, x: 10pt, y: 10pt))
// Between the two pages.
// (= at the very start of the first page, before the header)
#test(locate(<c>).position(), (page: 2, x: 0pt, y: 0pt))
// After the last page.
// (= at the very end of the last page, after the footer)
#test(locate(<d>).position(), (page: 2, x: 0pt, y: 30pt))
#test(locate(<e>).position(), (page: 2, x: 0pt, y: 30pt))
]
#metadata(none) <a>
#pagebreak(weak: true)
#metadata(none) <b>
A
#pagebreak()
#metadata(none) <c>
#pagebreak(weak: true)
B
#pagebreak(weak: true)
#metadata(none) <d>
#pagebreak(weak: true)
#metadata(none) <e>
--- issue-4029-locate-after-spacing ---
#set page(margin: 10pt)
#show heading: it => v(40pt) + it
= Introduction
#context test(
locate(heading).position(),
(page: 1, x: 10pt, y: 50pt),
)
--- issue-4029-locate-after-pagebreak ---
#set page(margin: 10pt)
#show heading: it => pagebreak() + it
= Introduction
#context test(
locate(heading).position(),
(page: 2, x: 10pt, y: 10pt),
)
--- issue-4029-locate-after-par-and-pagebreak ---
// Ensure that the heading's tag isn't stuck at the end of the paragraph.
#set page(margin: 10pt)
Par
#show heading: it => pagebreak() + it
= Introduction
#context test(locate(heading).page(), 2)
--- issue-1886-locate-after-metadata ---
#show heading: it => {
metadata(it.label)
pagebreak(weak: true, to: "odd")
it
}
Hi
= Hello <hello>
= World <world>
// The metadata's position does not migrate to the next page, but the heading's
// does.
#context {
test(locate(metadata.where(value: <hello>)).page(), 1)
test(locate(<hello>).page(), 3)
test(locate(metadata.where(value: <world>)).page(), 3)
test(locate(<world>).page(), 5)
}
--- issue-1833-locate-place ---
#set page(height: 60pt)
#context {
place(right + bottom, rect())
test(here().position(), (page: 1, x: 10pt, y: 10pt))
}
|
|
https://github.com/chubetho/Bachelor_Thesis | https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/templates/cover.typ | typst | #set page(
paper: "a4",
margin: (right: 3cm, left: 3.5cm, top: 2cm, bottom: 3.5cm),
)
#set align(center)
#par[
#set text(lang: "de")
Technische Hochschule Würzburg-Schweinfurt\ Fakultät Informatik und Wirtschaftsinformatik
]
#v(7em)
#text(1.5em, "Bachelorarbeit")
#v(2em)
#text(2em, weight: 700, [A Study on Micro Frontend Architecture and Its Impact])
#v(2em)
#[
#set text(lang: "de")
vorgelegt an der Technischen Hochschule Würzburg-Schweinfurt in der Fakultät Informatik und Wirtschaftsinformatik zum Abschluss eines Studiums im Studiengang Informatik
]
#v(2em)
#text(2em)[<NAME>]
#text(1.1em)[
#set text(lang: "de")
Eingereicht am: 13. September 2024
]
#v(1fr)
#[
#set text(lang: "de")
Erstsprüfer: Prof. Dr. <NAME>\
Zweitprüfer: Prof. Dr. <NAME>
]
#pagebreak(weak: true) |
|
https://github.com/imkochelorov/ITMO | https://raw.githubusercontent.com/imkochelorov/ITMO/main/src/algorithms/s2/l7/main.typ | typst | #import "template.typ": *
#set page(margin: 0.4in)
#set par(leading: 0.55em, first-line-indent: 0em)
#set text(font: "New Computer Modern")
#show par: set block(spacing: 0.55em)
#show heading: set block(above: 1.4em, below: 1em)
#show heading.where(level: 1): set align(center)
#show heading.where(level: 1): set text(1.44em)
#set page(height: auto)
#set page(numbering: none)
#set raw(tab-size: 4)
#set raw(lang: "py")
#show: project.with(
title: "Алгоритмы и Структуры Данных. Лекция 7",
authors: (
//"_scarleteagle",
"imkochelorov",
//"AberKadaber"
),
date: "03.04.2024",
)
#let make = $supset.sq$
= Хэш-таблицы
*Что нам нужно от хэш-таблиц?:*
+ Структура данных `set` --- множество уникальных элементов
- `insert(x)` --- добавить элемент в множество, если ранее в нём его не было
- `remove(x)` --- удалить элемент из множества, если он в нём присутствует
- `contains(x)` --- проверить, есть ли элемент в множестве
+ Структура данных `map` --- отображение $k -> v$ по уникальному ключу $k$
- `put(k, v)` --- присвоить ключ соответствующее значение
- `remove(k)` --- удалить ключ
- `get(k)` --- получить значение, соответствующее ключу
\
Пусть ключ (значение, в случае `set`) `x` $in$ `[0, u-1]`\ \
*Различные подходы к написанию:*\ #v(0.2cm)
*1.* `u` --- маленькое\ #v(0.2cm)
Например, хотим хранить ключи до 5. Создадим массив из 5 элементов:\ #v(0.2cm)
#align(center)[`a = [null] * 5`]
#columns(3)[
`put(k, v):
a[k] = v`
#colbreak()
`get(k):
return a[k]`
#colbreak()
`remove(k):
a[k] = null`
]
Если известно, что все ключи не превосходят, например, миллион, то это очень хорошая реализация, каждая операция в которой работает за честную $O(1)$\
Но, к сожалению, в жизни всё часто устроено иначе: не всегда $u$ маленькая, а иногда хочется хранить элементы сложнее чисел, например, строки, которые уже непонятно как индексировать
\ \
*2.* `u` --- большое\ #v(0.2cm)
Предположим, что мы не можем позволить себе создать массив на $u$ элементов. Например, `u` = $10^18$\
Всё ещё хочется хранить все наши элементы в массиве, но необходимо _пожать_ наши числа, чтобы мы могли индексироваться по не очень большому массиву и хранить их\ #v(0.15cm)
Создадим массив на $m$ элементов\ Придумаем функцию `h(x): [0, u-1]` $->$ `[0, m-1]` --- _называется хэш-функцией_\
Первое что приходит в голову для функции `h(x) = x % m`
#v(0.2cm)
#columns(4)[
#colbreak()
```py m #some const
a = [null] * m```
#colbreak()
`h(x):
return x % m`
]
#columns(3)[
`put(k, v):
a[h(k)] = v`
#colbreak()
`get(k):
return a[h(k)]`
#colbreak()
`remove(k):
a[h(k)] = null`
]
#v(0.2cm)
К сожалению, у этой реализации есть проблемы:\ #v(0.2cm)
*Пример:*\
#columns(2)[
```py m = 5
a = [null] * 5
h(x):
return x % 5
put(12, 8) #a[2] = 8
put(17, 5) #перезаписываем a[2], затирая старое значение
get(12) #получим 5, хотя должны были получить 8
```
#colbreak()
#v(0.0cm)
#align(center)[*Коллизия*:\
`x` $eq.not$ `y` $ quad "и" quad$ `h(x) = h(y)`] #v(0.2cm)
Довольно мерзкая ситуация, с которой нужно как-то бороться. Но по принципу Дирихле следует, что полностью побороться с коллизиями не получится и необходимо как-то научиться жить с этим
]
*3.* `u` --- большое, но теперь уживаемся с коллизиями (или почему хэш-_таблица_ называется таблицей)\ #v(0.2cm)
*Пример:*
#table(columns: (2.2fr, 10fr),
inset: 0pt,
stroke: none,
//align: horizon,
align(left)[
```py m = 5
a = [null] * m
put(12, 8)
#a[2] = [(12, 8)]
put(17, 5)
#a[2] = [(12, 8),
# (17, 5)]
get(12) #8
```],
[
Массив `a` после инициализации состоит из `m` `null` значений\
После добавления по ключу `12` значения `8`, `a[2] = 8` \
Перед добавлением значения по ключу `17`, видим, что в `a[2]` уже лежит значение `5`\
Исправим алгоритм и вместо хранения одного элемента в ячейке `a[2]`, будем хранить в ней список - _цепочку_ ключ-значение `[(12, 8), (17, 5)]`\
Выполняя `get(12)` получим не одно значение, а _цепочку_ вида ключ-значение, пробежавшись по которому найдём искомое по ключу значение
]
)
#v(0.2cm)
#align(center)[Реализация:]
#columns(3)[
`put(k, v):
h = h(k)
for i in range(len(a[h])):
if (a[i][0] == k):
a[i][1] = y
a.add((x, y))`\ #v(0.1cm)
#colbreak()
`get(k):
for (x, y) in a[h(k)]:
if (x == k):
return y
return null`\ #v(0.1cm)
#colbreak()
`remove(k):
for i in range(len(a[h])):
if (a[i][0] == k):
a.remove(i)`\
]
Однако такая реализация будет плохо работать с серией значений `0, m, 2 * m, 3 * m, ...`\
Теперь ассимптотика стала $O(n)$, что ничем не лучше обыкновенного массива\
#v(0.4cm)
Добавим случайность в работу программы\ #v(0.1cm)
`h(x)` --- случайная функция`: [0, u-1]` $->$ `[0, m-1]`. Существует $m^u$ таких
функций\ #v(0.1cm)
Предположим, мы выбрали одну из них. Посчитаем теперь время математическое ожидание времени работы `get()`. Оно будет равно математическому ожиданию количества элементов во входных данных с одинаковым хэшом:\ #v(0.3cm)
#align(center)[$E(T($`get()`$)) = E($количества элементов `x: h(x) = h(k)`$)$]#v(0.3cm)
_Важный момент:_ случайность берётся только из выбора хэш-функции. Мы не считыаем, что входные данные случайны\ #v(0.3cm)
Посчитаем вероятность того, что неравные элементы имеют одинаковый хэш (вероятность коллизий): #v(0.3cm)
#align(center)[$ p($`h(x) = h(k)`$) = 1/m $]#v(0.3cm)
По линейности математического ожидания посчитаем:#v(0.3cm)
#align(center)[$E(T($`get()`$)) = E($количества элементов `x: h(x) = h(k)`$) = n dot p($`h(x) = h(k)`$) = n/m $] #v(0.3cm)
Теперь, если мы будем выбирать случайную хэш-функцию в начале работы программы, то вне зависимости от входных данных математическое ожиидание времени работы `get()` будет равно $n/m$. \ То есть, все $n$ входных значений в среднем разбиваются поровну между $m$ нашими ячейками\ #v(0.3cm)
#align(center)[$m tilde n: quad E(T($`get()`$)) = O(1)$] #v(0.3cm)
Отличная структура данных, которая хорошо работает, однако есть один нюанс. Всё это время мы опирались на то, что можем выбрать сдучайную хэш-функцию. Но на самом деле не очень понятно, как мы можем это сделать. Даже непонятно, как сохранить информацию об этой функции, когда она уже будет создана. Так как возможных функций $m^k$, число бит, необходимое, чтобы сохранить информацию об одной конкретной слишком велико: #v(0.3cm)
#align(center)[_необходимое число бит_ $= log_2(m^u) = u dot log_2(m)$] #v(0.3cm)
Сохранить информацию о нашей функции уже проблема, не говоря о том, чтобы как-то её выбрать#v(0.3cm)
Попробуем выбирать функцию не всех возможных существующих, а из множества поменьше. \ Нам необходимо иметь возможность случайно её выбирать и хранить, но оставляя вероятность коллизии хэшей двух различных элементов неизменной #v(0.3cm)
Наша хэш-функция будет выглядеть так (часто называется _Универсальное множество хэш-функций_): #v(0.3cm)
#align(center)[`h(x) = ((a * x + b) % p) % m`\ #v(0.1cm) `a, b, p` --- параметры, выбираемые случайно\ #v(0.1cm)`0` < `a` $<$ `p` $quad$ `0` $<=$ `b` < `p` $quad$ `p` -- большое простое число (большее $m$)] #v(0.3cm)
Теперь нашу функцию легко генерировать, рандомя 3 числа и также легко хранить. Осталось проверить, что она продолжает удовлетворять нашему свойству о вероятности коллизий: #v(0.3cm)
#align(center)[`x` $eq.not$ `y` $quad p($`h(x) = h(y)`$)$]#v(0.3cm) $p($`h(x) = h(y)`$) space <=> space$`((a * x + b) % p) % m = ((a * y + b) % p) % m`$quad =>$\ #v(0.1cm) `((a * x + b) % p - (a * y + b) % p)` $dots.v$ `m`$quad =>$#v(0.1cm) `(a * x + b - a * y - b) % p` $dots.v$ `m`$quad =>$\ #v(0.1cm) `(a * (x - y)) % p` $dots.v$ `m`$quad =>$\ #v(0.1cm) `(a * (x - y)) % p = t * m`, $quad 0 <= $ `t` $<= floor(p/m)$\ #v(0.1cm) `a = t * m * (x - y)`$attach(, tr:-1)$ `(mod p)` --- относительно `a` это уравнение имеет ровно 1 решение, если `a` $eq.not$ `0`\ #v(0.1cm) $forall $ `t` $in [0, floor(p/m)] space exists!$ `a`, для которого равенство верно$quad =>$ \ #v(0.3cm) Для каждого `t` равенство верно с вероятностью $1/p$\ Существует порядка $p/m$ значений `t`\ #v(0.3cm)
#align(center)[ $p/m dot 1/p = 1/m$]#v(0.3cm)
#align(center)[$ p($`h(x) = h(y)`$) = 1/m, quad$для$quad$`x` $eq.not$ `y`]#v(0.3cm)
Теперь мы умеем выбирать случайную хэш-функцию, которая удовлетворяет необходимым свойствам.\
Вне зависимости от дальнейших входных данных, наша таблица будет работать хорошо.\
Более того, даже если вдруг вышло, что злоумышленник угадал нашу хэш-функцию и пытается этим пользоваться, мы можем это обнаружить.\ #v(0.1cm) Для этого в процессе работы хэш-таблицы будем поддерживать размер цепочек внутри ячеек. Если он станет сильно больше $n/m$, значит всё пошло совсем плохо, и мы можем сгенерировать новую\ хэш-функцию и перестроить таблицу\ #v(0.3cm)
*Преимущества* данного подхода:\
- Максимально простая реализация
*Недостатки* данного подхода:\
- Всё плохо с точки зрения кэш-памяти: все наши цепочки случайно разбросаны в реальной памяти
\ \
*4.* _Хэш-таблица с открытой адресацией_\ #v(0.2cm)
В прошлой реализации мы придумали цепочки для того, чтобы уживаться с коллизиями. Побробуем обойтись без них и с хорошим процентом кэш-хитов\ #v(0.1cm)
*Пример:*
#table(columns: (2.2fr, 10fr),
inset: 0pt,
stroke: none,
//align: horizon,
align(left)[
```py m = 5
a = [null] * m
put(12, 8)
#a[2] = (12, 8)
put(17, 5)
#a[2] = (12, 8)
#a[3] = (17, 5)
get(12) #8
```],
[
Массив `a` после инициализации состоит из `m` `null` значений\
После добавления по ключу `12` значения `8`, `a[2] = 8` \
Перед добавлением значения по ключу `17`, видим, что в `a[2]` уже лежит значение `5`\
Изменим предыдущий алгоритм и вместо составления _цепочки_ ключ-значение в одной ячейке нашего массива, положим элемент в первую свободную ячейку справа
])
#v(0.2cm)
#align(center)[Реализация:]
#columns(2)[
#align(center)[
```py put(k, v):
i = h(k)
while (a[i] != null):
i = (i + 1) % m
a[i] = (k, v)```]\ #v(0.1cm)
#colbreak()
#align(center)[
```py get(k):
i = h(k)
while (a[i] != null):
if (a[i].first == k):
return a[i].second
i = (i + 1) % m
return null```]
] #v(0.2cm)
Функция `get()` работает, так как в ней мы проходим тот же самый путь, который проходили при добавлении конкретного элемента (если добавляли его), или чуть дальше, до первого `null` значения. Но если мы добавляли элемент, то `get()` его обязательно найдёт\ #v(0.1cm)
Однако `remove()` реализуется не так легко, как кажется. Если создать его похожим на `get()`, то наша таблица сломается после удаления `12` в указанном примере, так как на попытку найти `17`, наша таблица скажет, что такого ключа не сущесвтует, когда он есть\ #v(0.3cm)
*Помашем руками:*\ #v(0.1cm)
Скажем, что мы знаем, сколько будет добавлений в таблицу и создадим её в 2 раза большую\
Предположим, что элементы по нашей хэш-таблице расположены равномерно: после заполнения #v(0.3cm)
#align(center)[`p(a[i] == null) =` $1/2$]#v(0.1cm)
Если это так, то с вероятностью $1/2$ `while` совершит одну итерацию, с вероятнотью $1/4$ две итерации и тд. #v(0.3cm)
#align(center)[$E(T($`while`$)) = limits(sum)_(i = 1)^(infinity) i/2^i = 2$]#v(0.3cm)
Однако наше предположение, на самом деле редко выполняется на практике, что ломает нашу оценку\
Но не смотря на это, таблица работает достаточно быстро\ #v(0.3cm)
Хотя даже для решения этой проблемы существует модификация: будем переходить вправо не на 1\
#columns(3)[
#align(center)[
```py put(k, v):
i = h(k)
while (a[i] != null):
i = (i + f(i)) % m
a[i] = (k, v)```]\ #v(0.1cm)
#colbreak()
#align(center)[
```py get(k):
i = h(k)
while (a[i] != null):
if (a[i].first == k):
return a[i].second
i = (i + f(i)) % m
return null```]
#colbreak()
#align(center)[
```py
f(x):
return a * x + b```
]
] #v(0.3cm)
Однако и здесь не без проблем. Всю эту реализацию мы придумали, чтобы табличка хорошо укладывалась в кэш, но данная модификация с _прыжками_ по массиву вместо последовательного прохода усложняет хранение таблички в кэше\
Если нам не нужно часто удалять, то это вполне хороший подход к созданию хэш-таблицы, который легко реализовывать. Но если от таблицы также нужны удаления, то, конечно, подход с цепочками является предпочтительным
|
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/template/sections/figures.typ | typst | MIT License | = Sample figures
// Sample figures taken from https://apastyle.apa.org/style-grammar-guidelines/tables-figures/sample-figures
== Sample bar graph
Referencing @fig:sample-bar-graph.
#figure(
[
#image("../assets/images/sample-bar-graph.png")
#set align(left)
_Note._
Framing scores of adolescents and young adults are shown for low and high risks and for small, medium, and large rewards (error bars show standard errors).
],
caption: [Framing Scores for Different Reward Sizes],
placement: none,
) <fig:sample-bar-graph>
== Sample line graph
Referencing @fig:sample-line-graph.
#figure(
[
#image("../assets/images/sample.line-graph.png")
#set align(left)
_Note._
Mean regression slopes in Experiment 1 are shown for the stereo motion, biocularly viewed monocular motion, combined, and monocularly viewed monocular motion conditions, plotted by rotation amount. Error bars represent standard errors. From “Large Continuous Perspective Change With Noncoplanar Points Enables Accurate Slant Perception,” by <NAME>, <NAME>, and <NAME>, 2018, Journal of Experimental Psychology: Human Perception and Performance, 44(10), p. 1513 (https://doi.org/10.1037/xhp0000553). Copyright 2018 by the American Psychological Association.
],
caption: [Mean Regression Slopes in Experiment 1],
) <fig:sample-line-graph>
== Sample CONSORT flowchart
Referencing @fig:sample-consort-flowchart.
#figure(
caption: [CONSORT Flowchart of Participants],
image("../assets/images/sample-consort-flowchart.png"),
) <fig:sample-consort-flowchart>
== Sample path model
Referencing @fig:sample-path-model.
#figure(
caption: [Path Analysis Model of Associations Between ASMC and Body-Related Constructs],
[
#image("../assets/images/sample-path-model.png")
#set align(left)
_Note._
The path analysis shows associations between ASMC and endogenous body-related variables (body esteem, body comparison, and body surveillance), controlling for time spent on social media. Coefficients presented are standardized linear regression coefficients.\
#super[\*\*\*]$p < .001$.
],
) <fig:sample-path-model>
== Sample qualitative research figure
Referencing @fig:sample-qualitative-research-figure.
#figure(
caption: [Organizational Framework for Racial Microaggressions in the Workplace],
image("../assets/images/sample-qualitative-research-figure.png"),
) <fig:sample-qualitative-research-figure>
== Sample mixed methods research figure
Referencing @fig:sample-mixed-methods-research-figure.
#figure(
caption: [A Multistage Paradigm for Integrative Mixed Methods Research],
image("../assets/images/sample-mixed-methods-research-figure.png"),
) <fig:sample-mixed-methods-research-figure>
== Sample illustration of experimental stimuli
Referencing @fig:sample-stimuli.
#figure(
caption: [Examples of Stimuli Used in Experiment 1],
[
#image(
"../assets/images/sample-illustration-experimental-stimuli.png",
alt: "Two computer-generated cartoon bees, one with two legs, a striped body, single wings, and antennae, and the other with six legs, a spotted body, double wings, and no antennae."
)
#set align(left)
_Note._
Stimuli were computer-generated cartoon bees that varied on four binary dimensions, for a total of 16 unique stimuli. They had two or six legs, a striped or spotted body, single or double wings, and antennae or no antennae. The two stimuli shown here demonstrate the use of opposite values on all four binary dimensions.
],
) <fig:sample-stimuli>
== Sample map
Referencing @fig:sample-map
#figure(
caption: [Poverty Rate in the United States, 2017],
[
#image("../assets/images/sample-map.png",
alt: "Map of the United States, with color gradients indicating percentage of people living in poverty."
)
#set align(left)
_Note._
The map does not include data for Puerto Rico. Adapted from 2017 Poverty Rate in the United States, by U.S. Census Bureau, 2017 (https://www.census.gov/library/visualizations/2018/comm/acs-poverty-map.html). In the public domain.
]
) <fig:sample-map>
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/shorthand.typ | typst | Apache License 2.0 | // Test shorthands for unicode codepoints.
---
The non-breaking~space does work.
---
// Make sure non-breaking and normal space always
// have the same width. Even if the font decided
// differently.
#set text(font: "New Computer Modern")
a b \
a~b
---
- En dash: --
- Em dash: ---
---
#set text(font: "Roboto")
A... vs #"A..."
|
https://github.com/yan-aint-nickname/uni | https://raw.githubusercontent.com/yan-aint-nickname/uni/main/oop-matrix-cli/diagrams/user_input.typ | typst | MIT License | // https://xkcd.com/1195/
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import fletcher.shapes: diamond, parallelogram
#set text(font: "Comic Neue", weight: 600)
#let user_input = diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
node((0,0), [Получить пользовательский ввод], extrude: (-2, 0)),
edge("--"),
node((0,1), [Начало], corner-radius: 10pt),
edge("-|>"),
node((0,2), [Ввод `maxValue`], shape: parallelogram.with(angle: 30deg)),
edge("-|>"),
node((0,3), align(center)[
Ошибка\ ввода
], shape: diamond),
edge("-|>", [Нет]),
node((0,4), [Ввод `D`], shape: parallelogram.with(angle: 30deg)),
edge("-|>"),
node((0,5), align(center)[
Ошибка\ ввода
], shape: diamond),
edge("-|>", [Нет]),
node((0,6), [Ввод `Q`], shape: parallelogram.with(angle: 30deg)),
edge("-|>"),
node((0,7), align(center)[
Ошибка\ ввода
], shape: diamond),
edge("-|>", [Нет]),
node((0,8), [Вернуть `0`], shape: parallelogram.with(angle: 30deg)),
edge("-|>"),
node((0,9), [Конец], corner-radius: 10pt),
edge((0,5), (-1,5), (-1,8), "-|>", [Да], label-pos: 0.1),
edge((0,3), (-1,3), (-1,8), "-|>", [Да], label-pos: 0.1),
node((-1,8), [Вернуть `1`], shape: parallelogram.with(angle: 30deg)),
edge((-1,8), (-1,8.5), (0,8.5), (0,9), "-|>"),
edge((0,7), (-1,7), (-1,8), "-|>", [Да], label-pos: 0.1),
) |
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/call.typ | typst | // Test function calls.
--- call-basic ---
// Omitted space.
#let f() = {}
#[#f()*Bold*]
// Call return value of function with body.
#let f(x, body) = (y) => [#x] + body + [#y]
#f(1)[2](3)
// Don't parse this as a function.
#test (it)
#let f(body) = body
#f[A]
#f()[A]
#f([A])
#let g(a, b) = a + b
#g[A][B]
#g([A], [B])
#g()[A][B]
--- call-aliased-function ---
// Call function assigned to variable.
#let alias = type
#test(alias(alias), type)
--- call-complex-callee-expression ---
// Callee expressions.
#{
// Wrapped in parens.
test((type)("hi"), str)
// Call the return value of a function.
let adder(dx) = x => x + dx
test(adder(2)(5), 7)
}
--- call-bad-type-bool-literal ---
// Error: 2-6 expected function, found boolean
#true()
--- call-bad-type-string-var ---
#let x = "x"
// Error: 2-3 expected function, found string
#x()
--- call-shadowed-builtin-function ---
#let image = "image"
// Error: 2-7 expected function, found string
// Hint: 2-7 use `std.image` to access the shadowed standard library function
#image("image")
--- call-bad-type-int-expr ---
#let f(x) = x
// Error: 2-6 expected function, found integer
#f(1)(2)
--- call-bad-type-content-expr ---
#let f(x) = x
// Error: 2-6 expected function, found content
#f[1](2)
--- call-args-trailing-comma ---
// Trailing comma.
#test(1 + 1, 2,)
--- call-args-duplicate ---
// Error: 26-30 duplicate argument: font
#set text(font: "Arial", font: "Helvetica")
--- call-args-bad-positional-as-named ---
// Error: 4-15 the argument `amount` is positional
// Hint: 4-15 try removing `amount:`
#h(amount: 0.5)
--- call-args-bad-colon ---
// Error: 7-8 unexpected colon
#func(:)
--- call-args-bad-token ---
// Error: 10-12 unexpected end of block comment
// Hint: 10-12 consider escaping the `*` with a backslash or opening the block comment with `/*`
#func(a:1*/)
--- call-args-missing-comma ---
// Error: 8 expected comma
#func(1 2)
--- call-args-bad-name-and-incomplete-pair ---
// Error: 7-8 expected identifier, found integer
// Error: 9 expected expression
#func(1:)
--- call-args-bad-name-int ---
// Error: 7-8 expected identifier, found integer
#func(1:2)
--- call-args-bad-name-string ---
// Error: 7-12 expected identifier, found string
#func("abc": 2)
--- call-args-bad-name-group ---
// Error: 7-10 expected identifier, found group
#func((x):1)
--- call-args-lone-underscore ---
// Test that lone underscore works.
#test((1, 2, 3).map(_ => {}).len(), 3)
--- call-args-spread-override ---
// Test standard argument overriding.
#{
let f(style: "normal", weight: "regular") = {
"(style: " + style + ", weight: " + weight + ")"
}
let myf(..args) = f(weight: "bold", ..args)
test(myf(), "(style: normal, weight: bold)")
test(myf(weight: "black"), "(style: normal, weight: black)")
test(myf(style: "italic"), "(style: italic, weight: bold)")
}
--- call-args-spread-forward ---
// Test multiple calls.
#{
let f(b, c: "!") = b + c
let g(a, ..sink) = a + f(..sink)
test(g("a", "b", c: "c"), "abc")
}
--- call-args-spread-type-repr ---
// Test doing things with arguments.
#{
let save(..args) = {
test(type(args), arguments)
test(repr(args), "(three: true, 1, 2)")
}
save(1, 2, three: true)
}
--- call-args-spread-array-and-dict ---
// Test spreading array and dictionary.
#{
let more = (3, -3, 6, 10)
test(calc.min(1, 2, ..more), -3)
test(calc.max(..more, 9), 10)
test(calc.max(..more, 11), 11)
}
#{
let more = (c: 3, d: 4)
let tostr(..args) = repr(args)
test(tostr(a: 1, ..more, b: 2), "(a: 1, c: 3, d: 4, b: 2)")
}
--- call-args-spread-none ---
// None is spreadable.
#let f() = none
#f(..none)
#f(..if false {})
#f(..for x in () [])
--- call-args-spread-string-invalid ---
// Error: 11-19 cannot spread string
#calc.min(.."nope")
--- call-args-content-block-unclosed ---
// Error: 6-7 unclosed delimiter
#func[`a]`
--- issue-886-args-sink ---
// Test bugs with argument sinks.
#let foo(..body) = repr(body.pos())
#foo(a: "1", b: "2", 1, 2, 3, 4, 5, 6)
--- issue-3144-unexpected-arrow ---
#let f(a: 10) = a(1) + 1
#test(f(a: _ => 5), 6)
--- issue-3502-space-and-comments-around-destructuring-colon ---
#let ( key : /* hi */ binding ) = ( key: "ok" )
#test(binding, "ok")
--- issue-3502-space-around-dict-colon ---
#test(( key : "value" ).key, "value")
--- issue-3502-space-around-param-colon ---
// Test that a space after a named parameter is permissible.
#let f( param : v ) = param
#test(f( param /* ok */ : 2 ), 2)
--- call-args-unclosed ---
// Error: 7-8 unclosed delimiter
#{func(}
--- call-args-unclosed-string ---
// Error: 6-7 unclosed delimiter
// Error: 1:7-2:1 unclosed string
#func("]
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/dynamic/rule-interval.typ | typst | #import "../../../polylux.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 30pt)
#polylux-slide[
#only((beginning: 1, until: 5))[Content displayed on subslides 1, 2, 3, 4, and 5 \ ]
#only((beginning: 2))[Content displayed on subslide 2 and every following one \ ]
#only((until: 3))[Content displayed on subslides 1, 2, and 3 \ ]
#only((:))[Content that is always displayed]
]
|
|
https://github.com/danbalarin/vse-typst-template | https://raw.githubusercontent.com/danbalarin/vse-typst-template/main/lib/outline.typ | typst | #import "@preview/outrageous:0.2.0"
#import "macros.typ": heading-like
#let custom-outline() = {
show outline.entry: outrageous.show-entry.with(
..outrageous.presets.outrageous-toc,
vspace: (none, none),
body-transform: (lvl, body, state-key: "outline-figure-numbering-max-width") => {
let number
let text
if(body.has("children")) {
(number, _, text) = body.children
} else {
// number = " "
text = body.text
}
if(lvl == 1 and number != [1]) {
v(0.1em)
}
outrageous.align-helper(
state-key,
[#number],
(max-width, this-width) => box[#v(.4em)#h(calc.max(this-width - 6pt, 0pt))#number #text],
)
},
)
outline(indent: 0em)
pagebreak()
}
|
|
https://github.com/Fwxzxh/MyResume | https://raw.githubusercontent.com/Fwxzxh/MyResume/main/cv.typ | typst | #set document(
title: "Resume",
author: "<NAME>",
date: auto,
keywords: ("Resume", "<NAME>", "Technology")
)
#set page(
paper: "us-letter"
)
#set par(justify: true)
#set text(
font: "Times New Roman",
size: 12pt,
)
#let Header1 = 18pt
#let Header2 = 16pt
#let Header3 = 14pt
#let EducationItem(Institution: "", Date: "", Title: "", BulletPoints: ()) = {
text(Header1, weight: "bold")[#Institution]
linebreak()
text(Header2)[#Date]
linebreak()
text(Header3, style: "italic")[#Title]
linebreak()
if BulletPoints == () {
for value in BulletPoints [
- value
]
}
}
// A Function to generate a resume item
#let WorkItem(Company: "", Title: "", Date: "", Keywords: "", Experiences: ()) = {
text[
#text(Header1, weight: "bold")[#Company]
#h(1fr)
#text(Header1)[#Date]
]
linebreak()
if Title != "" {
text(Header2, weight: "semibold", style: "italic")[#Title]
linebreak()
}
if Keywords != "" {
text(Header3, style: "italic")[#Keywords]
linebreak()
}
if Experiences != () {
for value in Experiences [
- #value
]
}
}
// A function to Generate a styled header
#let NewSectionHeader(Title) = {
text(22pt, weight: "bold")[
#underline(extent: 2pt, stroke: blue)[
#Title
]
]
}
// Header of my document
#par(justify: false)[
#align(left)[
#text(28pt, weight: "black")[
*<NAME>*
]
#text(16pt, weight: "light")[
#link("mailto:<EMAIL>")
#sym.emptyset
(442) 189 7740
#sym.emptyset
México, <NAME>
#sym.emptyset
#show link: underline
#link("https://github.com/Fwxzxh")[github.com/Fwxzxh]
#sym.emptyset
#link("https://www.linkedin.com/in/jdemeca")[linkedin.com/jdemeca]
]
]
]
#line(length: 100%, end: none)
// Keywords
// #par()[
// #text(size: 14pt)[
// Hi! I’m Jorge, a developer with a strong problem-solving mindset and an unwavering passion for lifelong learning.
// My journey in software development has allowed me to cultivate a deep understanding of emerging technologies and expertise in crafting innovative solutions.
// ]
// ]
// Items
#NewSectionHeader("Work Experience")
#WorkItem(
Company:"Visteon Corporation",
Title: "Software Engineer",
Date:"Ago. 2022 - Present",
Keywords:"HMI Developer & Internal Tools Architect",
Experiences: (
"Key role in the development of v363, v710, v769 & p758 ford programs HMI.",
"Led code reviews and static analysis to uphold quality standards.",
"Proactively reviewed and analyzed requirements to deliver solid solutions.",
"Participated in CES concepts, representing the company's solutions.",
"Led the upgrade of existing legacy frameworks to enhance efficiency and alleviate workflow pain points.",
"Led the creation of new tools and frameworks to enhance developer productivity.",
"Skills in Unix, IPC, CAN, Networking, reverse engineering data analysis and data engineering for internal projects.",
)
)
#WorkItem(
Company: "Freelance Developer",
Title: "Team Lead",
Date: "Ene. 2021 - Feb 2023",
// Keywords: "Team Lead",
Experiences: (
"Coordinated a team of 4 developers to create software solutions for small and medium-sized businesses.",
"Developed custom applications that helped clients to improve internal processes and increase revenue.",
"Implemented Agile workflows in the team.",
"Focus on fulfill customer needs & delivering a reliable solution.",
"Designed a management platform for a retail store that increased sales by 15%",
)
)
#WorkItem(
Company: "CIDESI",
Title: "Intern",
Date: "Ago. 2021 - March 2022",
Keywords: "Social Service",
Experiences: (
"Computer vision algorithms implementation and theory in Python and Matlab",
"Search & Cleaning of free flowers images for the validation of a flower-counting algorithm",
"Creation of a open Dataset of flower images.",
"Said Dataset allowed researchers to improve the accuracy of the flower-counting algorithm by 20%",
"Cleaning, segmentation & counting of flowers via Computer vision algorithms and frameworks.",
)
)
#NewSectionHeader("Education")
#EducationItem(
Institution: "Tecnológico Nacional de México Campus Querétaro",
Date:"2017-2023",
Title:"Computer engineering, with specialization in distributed systems.",
BulletPoints:()
)
#NewSectionHeader("Skills")
#terms.item(
"Programming Languages",
"C#/F#, C/C++, Python, Go, Rust, Swift, Java, Kotlin, SQL, Bash, Powershell.",
)
#terms.item(
"Developer Tools",
"CANalizer, Git, GitHub, Jira, GDB, RenderDoc, Unity, Godot, Blender."
)
#terms.item(
"Operating Systems",
"Windows, MacOs, Linux, QNX."
)
#terms.item(
"Frameworks",
"WPF, AvaloniaUI, QT, Robot Framework, OpenCV, TensorFlow, FastApi."
)
#terms.item(
"Languages",
"Spanish, English."
)
#terms.item(
"Soft Technical Skills",
text()[
Data Analysis (Collecting, Processing & interpreting)
#linebreak()
Project Management (Planning, Organizing & Executing)
#linebreak()
Technical Writing (Writing clear & concise technical documentation)
#linebreak()
Presentation Skills (Communicating technical information effectively to to all audiences)
]
)
#terms.item(
"Technical Interests",
"Compilers, Operating Systems, Artificial Intelligence, Game Engines, Functional Programming."
) |
|
https://github.com/enseignantePC/2023-24 | https://raw.githubusercontent.com/enseignantePC/2023-24/master/Chapitre1/tp1/tp1.typ | typst | #import "../../act_template.typ": *
#show : it => activité(
title: [ Détermination de masse volumique ],
chapter_name: [Identification des espèces chimiques.],
number: 1,
kind : [TP],
it,
)
#v(-5pt)
#introduction[ Au cours de l'histoire, la monnaie a été faite de différents métaux.
Pour éviter les fraudes et les arnaques, il faut une méthode pour distinguer deux métaux.
En chimie, on aura besoin de distinguer les espèces chimiques.
*_Peut-on différencier des espèces chimiques à l'aide de leur masse volumique. _* ]
// question, pate à crêpe.
// #doc(
// width: 50%,
// // shadow : false
// )[]
#v(-5pt)
#stack(
dir: ltr,
spacing: 14pt,
doc(width: 42%, shadow: false, title: [Matériel à disposition])[
- Lunettes de protection ;
- Une balance ;
- Une spatule ;
- Une coupelle ;
- Une éprouvette graduée de 25mL ;
- Une pipette graduée de 10mL ;
- Une pipette simple ;
- Une pissette d'eau distillée ;
- Votre règle ;
],
doc(
width: 50%,
title: [Masse volumique d'un échantillon de matière],
)[
La masse volumique $rho$ d'un échantillon de matière est la grandeur égale au
rapport de sa masse $m$ par son volume $V$.
Elle est définie par la relation :#h(5pt) #box(scale(130%, $rho = m / V$))
avec :
- la masse en gramme (g) ;
- le volume en centimètre cube (cm3) ;
- la masse volumique en gramme par centimètre cube (g·cm-3).
La masse volumique est une grandeur qui caractérise une espèce chimique. Elle
dépend de l'état de l'espèce chimique (solide, liquide ou gaz) et de la
température ambiante.
],
)
#v(-3pt)
#question[ *Rédiger (sur une feuille à part à rendre.)* un _protocol expérimental_ permettant de déterminer la
masse volumique d'un liquide, même travail pour un solide.
Pour rédiger un protocol experimental, il faut :
- *Décrire très brièvement* ce qu'on doit faire, par étape.
- *Indiquer* ce qu'on va conclure de l'experience.
#set text(style : "italic")
#underline[Exemple avec un objectif différent:]
#v(-5pt)
Objectif: la réaction entre la soude et l'acide citrique crée t-elle de la chaleur?
+ *Prélever* trois grammes de soude dans une coupelle.
+ *Diluer* dans une fiole jaugée de 15mL.
+ *Prélever* 15mL d'acide à l'aide d'une pipette jaugée et mettre l'échantillon dans un bécher.
+ Mesurer la température la solution d'acide et de la solution de soude.
+ Verser le contenu de la fiole jaugée dans le bécher, on mesurera la température finale pour la comparer aux températures initiales.
]
#question[
En classe entière, *Discuter* puis *Choisir* le protocol expérimental.
]
#question[
Pour chacun des échantillons, *Réaliser* le protocol et *noter* sa masse volumique. (Les calculs devront être détaillés.)
#let letters = "ABCDEF"
#let len = letters.clusters().len()
#let line1 = letters.clusters().map(x => box(x, inset: 18pt))
#let line2 = line1.map(hide)
#set align(center)
#table(
align: center + horizon,
columns: len + 1 ,
[échantillon: ], ..line1,
[$rho " " (g \/ "cm"^3)$], ..line2
)
]
#question[
Les mesures permettent-elles d'identifier chacun des échantillons?
]
#question[
La mesure de la masse volumique d'un échantillon permet-elle de déterminer sa nature avec certitude ? *Trouver un example ou un contre-example.*.
]
// #minititle[Ouverture : Qu'avez vous appris sur la précision]
#let tab1 = "Espèce chimique Masse volumique (g·cm -3 ) Aspect à température ambiante (20 °C)
Eau 1,00 Liquide incolore
Fer 7,86 Solide gris
Zinc 7,13 Solide gris clair
Éthanol 0,789 Liquide incolore
Acétone 0,784 Liquide incolore
Étain 7,29 Solide blanc, mou"
#figure(
placement: bottom,
caption: [Masses volumiques de diverses espèces chimiques],
table(
columns: 3,
align: center + horizon,
..tab1.split(regex("\t|\n"))
)
) <fig1> |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-01.typ | typst | Other | // Test the `len` method.
#test(().len(), 0)
#test(("A", "B", "C").len(), 3)
|
https://github.com/ofurtumi/typst-packages | https://raw.githubusercontent.com/ofurtumi/typst-packages/main/README.md | markdown | # typst-packages
Collection of personal typst packages and templates
## location
to use these packages, this repo needs to be cloned into `{cache-dir}/typst/packages/` where `{cache-dir}` is
- `$XDG_DATA_HOME` or `~/.local/share` on Linux
- `~/Library/Application` Support on macOS
- `%APPDATA%` on Windows
## importing
to use a package or template import them using
`#import "@{namespace}/{package}:{version}": *`
for example `#import "@templates/ass:0.1.0": *`
## usage
```typst
#import "@templates/ass:0.1.0": *
#show: doc => template(
author: "<NAME>"
project: "Project Name",
class: "Class Name",
doc
)
```
|
|
https://github.com/Xiaole-An/personalResume | https://raw.githubusercontent.com/Xiaole-An/personalResume/main/resume_noHardware.typ | typst | #import "template.typ": *
// 设置图标, 来源: https://fontawesome.com/icons/
// 如果要修改图标颜色, 请手动修改 svg 文件中的 fill="rgb(38, 38, 125)" 属性
#let faAward = icon("icons/fa-award.svg")
#let faBuildingColumns = icon("icons/fa-building-columns.svg")
#let faCode = icon("icons/fa-code.svg")
#let faEnvelope = icon("icons/fa-envelope.svg")
#let faGithub = icon("icons/fa-github.svg")
#let faGraduationCap = icon("icons/fa-graduation-cap.svg")
#let faLinux = icon("icons/fa-linux.svg")
#let faPhone = icon("icons/fa-phone.svg")
#let faWindows = icon("icons/fa-windows.svg")
#let faWrench = icon("icons/fa-wrench.svg")
// 主题颜色
#let themeColor = rgb("#080a23")
// 设置简历选项与头部
#show: resume.with(
// 字体基准大小
size: 10pt,
// 标题颜色
themeColor: themeColor,
// 控制纸张的边距
top: 1.5cm,
bottom: 2cm,
left: 2cm,
right: 2cm,
// 如果不需要头像,则将下面的参数注释或删除
photograph: "images/acx.jpg",
photographWidth: 6.42em,
gutterWidth: 10em,
)[
#figure(
// placement: auto,
image("images/top_half_eng.png", width: 40%),
)
= 安尘汐
*联系电话*:13002460562 *邮箱*:<EMAIL> *出生年月*:2000.05
*政治面貌*:共青团员 *籍贯*:辽宁
#h(2em) // 手动顶行, 2em 代表两个字的宽度
]
== 教育背景
#sidebar(withLine: true, sideWidth: 5%)[
硕士
本科
][
*东北大学* · 机械工程与自动化学院 · 机械工程专业(推荐免试)机器视觉与机器人实验室 (前15%)
*东北大学* · 机械工程与自动化学院 · 机械工程专业(前20%)
]
== 项目经历
#item(
[ *基于多任务和高层特征的曝光轮廓不清叶片的边缘检测* (课题项目,独立完成)],
[],
date[ 2023 年 04 月 – 2024 年 06 月 ],
)
- *项目背景:* 强光导致图像的采集效果变差,引起了叶片图像边缘的模糊,影响了对叶片的基于视觉的检测/测量效果。
- *个人工作:* 为了解决边缘模糊问题,*1.)* 提取图像极高层信息作为图像中物体的轮廓表示并添加监督;*2.)* 强制模型进行参数共享,限制模型大小来增强多任务学习效果;*3.)* 根据叶片数据集的正负样本量和自然场景边缘数据集的正负样本量加权BCE损失,实现良好的背景负样本抑制效果。
- *项目结果:* 提出了BedNet-IR网络,利用高层特征和显著性检测、边缘检测多任务学习方法实现叶片由于曝光轮廓被隐去的良好边缘预测,ODS-F和OIS-F在极端光照叶片数据集上分别达到0.815和0.926;同时泛化性能良好。
#xiangmu_item(
[ *相似航空机加件细粒度分类 * (项目负责人)],
[东北大学 / 沈阳飞机工业集团],
date[ 2023 年 07 月 – 2024 年 05 月 ]
)
- *项目背景:* 本项目是和沈飞的合作项目,目的是自动识别战斗机上的74种相似工件,缩短生产流程,提高生产稳定性。
- *个人工作:* #sym.circle.filled *硬件设计*: 根据工件尺寸对相机,镜头进行选型,设计图像采集平台并加工、安装。#sym.circle.filled *算法设计*: 设计基于ViT的双输入孪生网络,接收机加件的双视角视图。*1.)* 提出Token Selected Self-Attention,选择与图像更相关的tokens互相做自注意力计算,并只更新这些tokens的值;*2.)* 使用选择分数对各tokens进行加权求和,使用MLP分类;*3.)* 针对机加件极为相似的特点,惩罚过于自信的输出概率分布,将输出概率分布的负熵添加到损失中。
- *项目结果:* 最终实现极相似机加件99.8%(无限位,视角偏差±10°),100%(有限位)的分类准确率,为企业撰写总结报告和说明书。
== 实习经历
#shixi_item(
[ *沈阳新松机器人自动化股份有限公司* ],
[算法实习生],
date[ 2024 年 07 月 – 至今 ]
)
- *负责项目: *基于accelerated features (CVPR24)的兴趣点检测和匹配,用于实时SLAM系统。
- *个人工作: *为了适应企业AGV的室内工作场景,*1.) *改进accelerated features网络的关键点检测头和描述子生成并进行微调,丰富特征点的描述;*2.) *使用MegaDepth和扭曲的COCO-20k数据集进行预训练,调整COCO-20k的扭曲方式进行模型微调,把模型应用场景向室内转移。
- *项目结果: *将室内场景匹配的旋转鲁棒性从原方法45°提高到现在的150°,并保持检测和匹配的实时性,在$720#sym.times 1280$分辨率的图像上推理速度达到200 frames/min,并且能够实时处理快速移动的分辨率为$240#sym.times 240$的图像。
== 专业技能
- 熟悉Python编程语言,Pytorch深度学习框架,linux操作系统,了解git常见操作。熟练使用Solidworks,AutoCad等三维、二维建模软件。
- 熟悉常见的边缘检测传统算子和深度学习边缘检测算法,如Sobel, Canny, RCF, PidiNet等;了解常见的特征点提取与匹配方法,如xfeature, Loftr, LightGlue等;熟悉深度学习基本理论及经典网络模型,如ResNet,RepVGG,ViT等。
== 获奖情况
- 一等学业奖学金两次;二等学业奖学金一次,三等学业奖学金两次(本科期间),神州高铁命名奖学金三次(硕士期间);
- 辽宁省人工智能大赛三等奖;互联网+大学生创新创业大赛辽宁省三等奖;挑战杯大学生创业计划竞赛辽宁省二等奖。
- 大学生创新创业大赛省级良好(新型扭转-弯曲软体机器人的研制),发表一篇会议论文;
== 发表论文
A Novel Edge Detection Method of Blade with Multi-Supervision for Fore-Background Confusion Caused by Extreme Illumination.
(IEEE Sensors Journal Q1, *第一作者*)
== 自我评价
本人品行端正、乐于助人;坚持运动,个性积极乐观;具有强烈进取心、责任心,具有较好沟通与合作能力。
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/hover/pagebreak.typ | typst | Apache License 2.0 |
#(/* ident after */ pagebreak);
|
https://github.com/OCamlPro/ppaqse-lang | https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/links.typ | typst |
#let absint = link("https://www.absint.com/index.html", "AbsInt")
#let aiT = link("https://www.absint.com/ait/", "aiT")
#let altergo = link("https://alt-ergo.ocamlpro.com/", "Alt-Ergo")
#let aocc = link("https://www.amd.com/en/developer/aocc.html", "AOCC")
#let api_sanity_checker = link(
"https://lvc.github.io/api-sanity-checker/",
"API Sanity Checker"
)
#let apple = link("https://www.apple.com", "Apple")
#let armlink = {
link("https://developer.arm.com/tools-and-software/embedded/arm-compiler",
"Arm Linker")
}
#let astree = link("https://www.absint.com/astree/", "Astree")
#let boost = link("https://live.boost.org/", "Boost")
#let bound-T = link("https://www.bound-t.com", "Bound-T")
#let cadna = link("https://cadna.lip6.fr/index.php", "CADNA")
#let cantata = link("https://www.qa-systems.com/products/cantata", "Cantata")
#let chronos = link("https://www.comp.nus.edu.sg/~rpembed/chronos/", "Chronos")
#let clang = link("https://clang.llvm.org", "Clang")
#let compcert = link("https://compcert.org", "CompCert")
#let coq = link("https://coq.inria.fr", "Coq")
#let criterion = link("https://criterion.readthedocs.io", "Criterion")
#let cvc5 = link("https://cvc5.github.io/", "CVC5")
#let fluctuat = {
link("https://www.lix.polytechnique.fr/~putot/fluctuat.html", "Fluctuat")
}
#let framac = link("https://frama-c.com", "Frama-C")
#let gappa = link(
"https://gappa.gitlabpages.inria.fr/gappa/index.html",
"Gappa"
)
#let gcc = link("https://gcc.gnu.org", "GCC")
#let gliwa = link("https://www.gliwa.com/", "Gliwa")
#let gmp = link("https://gmplib.org", "GMP")
#let haskell = link("https://www.haskell.org", "Haskell")
#let icx = link(
"https://www.intel.com/content/www/us/en/developer/tools/oneapi/dpc-compiler.html",
"ICX"
)
#let intel = link("https://www.intel.com", "Intel")
#let iris = link("https://iris-project.org/", "Iris")
#let isabelle = link("https://isabelle.in.tum.de", "Isabelle/HOL")
#let lean = link("https://lean-lang.org", "Lean")
#let libcester = link(
"https://exoticlibraries.github.io/libcester/index.html",
"LibCester"
)
#let mpfi = link("https://gitlab.inria.fr/mpfi/mpfi", "MPFI")
#let mpfr = link("https://www.mpfr.org", "MPFR")
#let msvc = link("https://docs.microsoft.com/en-us/cpp/", "MSVC")
#let novaprova = link("https://novaprova.org/", "NovaProva")
#let OCaml = link("https://ocaml.org", "OCaml")
#let opmock = link("https://opmock.com", "Opmock")
#let otawa = link("https://www.tracesgroup.net/otawa/?page_id=361", "Otawa")
#let parasoft = link(
"https://www.parasoft.com/products/parasoft-c-ctest/",
"Parasoft"
)
#let polyspace = {
link("https://www.mathworks.com/products/polyspace.html", "Polyspace")
}
#let pvs = link("https://pvs.csl.sri.com", "PVS")
#let rapidtime = {
link("https://www.rapitasystems.com/products/rapitime", "RapiTime")
}
#let redefinedc = link("https://gitlab.mpi-sws.org/iris/refinedc", "RefinedC")
#let stackanalyser = {
link("https://www.absint.com/stackanalyzer/", "StackAnalyzer")
}
#let sweet = link("http://www.mrtc.mdh.se/projects/wcet/sweet.html", "SWEET")
#let t1stack = link("https://www.gliwa.com/products/t1stack/", "T1.stack")
#let TPT = link("https://piketec.com/tpt/", "TPT")
#let vercors = link("https://vercors.ewi.utwente.nl/", "VerCors")
#let vectorcast = link(
"https://www.vector.com/int/en/products/products-a-z/software/vectorcast/vectorcast-c/",
"VectorCAST/C++"
)
#let viper = link("https://viper.ethz.ch", "Viper")
#let xsc = link(
"https://www2.math.uni-wuppertal.de/wrswt/xsc/cxsc/apidoc/html/index.html",
"XSC"
)
#let z3 = link("https://github.com/Z3Prover/z3", "Z3")
#let llvm = link("https://llvm.org/", "LLVM")
#let microsoft = link("https://www.microsoft.com", "Microsoft")
#let inria = link("https://www.inria.fr", "INRIA")
#let linaro = link("https://www.linaroforge.com/linaro-ddt", "Linaro DDT")
#let gdb = link("https://www.gnu.org/software/gdb/", "GDB")
#let lldb = link("https://lldb.llvm.org/", "LLDB")
#let totalview = link("https://totalview.io/", "TotalView")
#let undo = link("https://undo.io/", "Undo")
#let valgrind = link("https://www.valgrind.org/", "Valgrind")
#let vsd = link("https://www.visualstudio.com/", "Visual Studio Debugger")
#let visualstudio = link(
"https://visualstudio.microsoft.com/fr/vs/",
"Visual Studio"
)
#let antlr = link("https://www.antlr.org/", "ANTLR")
#let byacc = link("https://invisible-island.net/byacc/", "Byacc")
#let hyacc = link("https://hyacc.sourceforge.net/", "Hyacc")
#let lemon = link("https://www.hwaci.com/sw/lemon/", "Lemon")
#let llgen = link("https://github.com/theovosse/llgen", "LLgen")
#let llnextgen = link("https://os.ghalkes.nl/LLnextgen/", "LLnextgen")
#let yacc = link(
"https://www.tuhs.org/cgi-bin/utree.pl?file=V6/usr/source/yacc",
"Yacc"
)
#let treesitter = link(
"https://tree-sitter.github.io/tree-sitter/",
"Tree-sitter"
)
#let styx = link("http://speculate.de/", "Styx")
#let cocor = link("http://ssw.jku.at/Research/Projects/Coco/", "Coco/R")
#let sablecc = link("https://sablecc.org/", "SableCC")
#let bison = link("https://www.gnu.org/software/bison/", "Bison")
#let unicc = link("https://sourceforge.net/projects/unicc/", "Unicc")
#let kmyacc = link("https://github.com/Kray-G/kmyacc", "Kmyacc")
#let apg = link("https://sabnf.com/", "APG")
#let gold = link("http://goldparser.org/", "GOLD")
#let dparser = link("https://dparser.sourceforge.io/", "DParser")
#let yaep = link("https://github.com/vnmakarov/yaep", "YAEP")
#let gdk = link("https://gdk.sourceforge.net/", "GDK")
#let buckaroo = link("https://buckaroo.pm/", "Buckaroo")
#let clib = link("https://github.com/clibs/clib", "Clib")
#let conan = link("https://conan.io/", "Conan")
#let vcpkg = link("https://vcpkg.io/en/", "vcpkg")
#let janestreet = link("https://janestreet.com", "Jane Street")
#let cameleer = link("https://github.com/ocaml-gospel/cameleer", "Cameleer")
#let alcotest = link("https://github.com/mirage/alcotest", "Alcotest")
#let ounit = link("https://github.com/gildor478/ounit", "OUnit")
#let qcheck = link("https://github.com/c-cube/qcheck", "QCheck")
#let crowbar = link("https://github.com/stedolan/crowbar", "Crowbar")
#let bun = link("https://github.com/ocurrent/bun", "Bun")
#let ppx_inline_test = link(
"https://github.com/janestreet/ppx_inline_test",
"ppx_inline_test",
)
#let ppx_expect = link(
"https://github.com/janestreet/ppx_expect",
"ppx_expect",
)
#let crates_io = link("https://crates.io")[`crates.io`]
#let lib_rs = link("https://lib.rs")[`lib.rs`]
#let dypgen = link("http://dypgen.free.fr/index.html", "Dypgen")
#let sedlex = link("https://github.com/ocaml-community/sedlex", "sedlex")
#let ulex = link("https://github.com/ocaml-community/ulex", "ulex")
#let menhir = link("https://gitlab.inria.fr/fpottier/menhir", "Menhir")
#let camlp5 = link("https://camlp5.github.io", "Camlp5")
#let opam = link("https://opam.ocaml.org/", "opam")
#let C = link("https://www.iso.org/standard/74528.html", "C")
#let Cpp = link("https://isocpp.org/", "C++")
#let Ada = link("https://www.adaic.org/", "Ada")
#let Scade = link("https://www.ansys.com/products/systems/ansys-scade-suite", "SCADE")
#let Rust = link("https://www.rust-lang.org", "Rust")
#let CNES = link("https://cnes.fr", "CNES")
#let ocaml = OCaml
#let nix = link("https://nixos.org/#", "Nix")
#let flex = link("https://github.com/westes/flex", "Flex")
#let quex = link("https://quex.sourceforge.io/", "Quex")
#let re2c = link("https://re2c.org/", "Re2c")
#let ragel = link("https://www.colm.net/open-source/ragel/", "Ragel")
#let eclair = link("https://www.bugseng.com/eclair", "ECLAIR")
#let tisanalyser = link(
"https://www.trust-in-soft.com/trustinsoft-analyzer",
"TrustInSoft Analyzer"
)
#let gnat = link("https://www.gnu.org/software/gnat/", "GNAT")
#let codepeer = link(
"https://www.adacore.com/static-analysis-suite/defects-and-vulnerability",
"CodePeer"
)
#let spark = link("https://www.adacore.com/about-spark", "SPARK")
#let cvc4 = link("https://cvc4.github.io/", "CVC4")
#let windbg = link("https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools")[WinDBG]
#let rr = link("https://rr-project.org/")[rr]
#let boost_test = link(
"https://www.boost.org/doc/libs/1_85_0/libs/test/doc/html/index.html",
[Boost Test Library]
)
#let catch2 = link("https://github.com/catchorg/Catch2", "Catch2")
#let gtest = link("https://github.com/google/googletest", "Google Test")
#let google = link("https://about.google", "Google")
#let safetynet = link(
"https://bitbucket.org/rajinder_yadav/safetynet/src/master/",
"Safetynet"
)
#let testwell_ctc = link(
"https://www.verifysoft.com/fr_ctcpp.html",
"Testwell CTC++"
)
#let aunit = link("https://github.com/AdaCore/aunit", "AUnit")
#let adatest95 = link(
"https://www.qa-systems.fr/tools/adatest-95/",
"Ada Test 95"
)
#let avhen = link("http://ahven.stronglytyped.org/", "Avhen")
#let ldra = link("https://ldra.com/products/ldra-tool-suite/", "LDRA")
#let vectorcastAda = link(
"https://www.vector.com/int/en/products/products-a-z/software/vectorcast/vectorcast-ada/",
"VectorCAST/Ada"
)
#let rtrt = link(
"https://www.ibm.com/products/rational-test-realtime",
"Rational Test RealTime"
)
#let ptcdobjada = link(
"https://www.ptc.com/en/products/developer-tools/objectada",
"PTC ObjectAda"
)
#let ptcapexada = link(
"https://www.ptc.com/en/products/developer-tools/apexada",
"PTC ApexAda"
)
#let gnatpro = link("https://www.adacore.com/gnatpro", "GNAT Pro")
#let gnatllvm = link("https://github.com/AdaCore/gnat-llvm", "GNAT LLVM")
#let gaoc = link(
"https://www.ghs.com/products/ada_optimizing_compilers.html",
"GreenHills Ada Optimizing Compiler")
#let janusada = link(
"http://www.rrsoftware.com/html/blog/ja-312-rel.html",
"Janus/Ada"
)
#let gnatstack = link(
"https://www.adacore.com/gnatpro/toolsuite/gnatstack",
"GNATstack"
)
|
|
https://github.com/layandreas/typst-resume | https://raw.githubusercontent.com/layandreas/typst-resume/main/README.md | markdown | # Resume
My resume using [Typst](https://github.com/typst/typst). This resume is based on the [Alta Typst](https://github.com/GeorgeHoneywood/alta-typst) template.
|
|
https://github.com/sevehub/minimalbc | https://raw.githubusercontent.com/sevehub/minimalbc/main/README.md | markdown | MIT License | # minimalbc
This repository provides a Typst template for creating sleek and minimalist professional business cards.
The function, **minimalbc**, allows you to customize the majority of the business card's elements.
By default, the layout is horizontal. However, it can be easily switched to a vertical layout by passing the value true to the flip argument in the minimalbc function.
Here’s an example of how to use the minimalbc function:
```Typst
#import "lib.typ":minimalbc
#show: minimalbc.with(
// possible geo_size options: eu, us, jp , cn
geo_size: "eu",
flip:true,
company_name: "Company Name",
name: "<NAME>",
role: "Role",
telephone_number: "+000 00 000000",
email_address: "<EMAIL>",
website: "example.com",
company_logo: "company_logo.png",
bg_color: "ffffff",
)
```
When compiled, this will produce a PDF file named businesscard.pdf located in this repository. Feel free to download and use this as a starting point for your own business cards.
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/utils/datestamp.typ | typst | #let _parse_date(date_str) = {
let date_match = date_str.match(regex("^(\d{4})[-](\d{2})[-](\d{2})$"))
if date_match == none {
panic("failed to parse date (YYYY-MM-DD): " + date_str)
}
let (year, month, day) = date_match.captures
datetime(
year: int(year),
month: int(month),
day: int(day),
)
}
#let datestamp(date) = {
// Parse date
if type(date) == str {
date = _parse_date(date)
}
assert(type(date) == datetime)
// Set mark (label)
[#metadata(date) <datestamp>]
// Print stamp
let stroke = red + 0.5pt;
block(
breakable: false,
grid(
columns: (1fr, auto, 1fr),
align: horizon + center,
line(length: 100%, stroke: stroke),
block(
inset: 5pt,
radius: 5pt,
stroke: stroke,
date.display()
),
line(length: 100%, stroke: stroke),
)
)
}
#let datestamped_outline(
title: "Содержание",
depth: none,
indent: 1cm,
fill: repeat([.]),
) = context {
let items = query(selector(label("datestamp")).or(selector(heading)))
for item in items {
if item.func() == heading {
let level = item.level
if depth == none or level <= depth {
let ind = h((level - 1) * indent)
let name = item.body
let dots = box(width: 1fr, fill)
let loc = item.location()
let page = loc.page()
link(loc)[#ind#name #dots #page\ ]
}
} else if item.func() == metadata {
let date = item.value
let loc = item.location()
let data = grid(
columns: (auto, 1fr),
align: horizon + center,
column-gutter: 5pt,
text(fill: red, date.display()),
line(length: 100%, stroke: 0.5pt + red)
)
link(loc, data)
} else {
panic("unreachable")
}
}
}
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/sig_dict.typ | typst | Apache License 2.0 | // contains: paint,cap
#text(stroke: (/* range after 1..2 */ ))[]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.