repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/TheRiceCold/resume | https://raw.githubusercontent.com/TheRiceCold/resume/main/modules/education.typ | typst | #import "../src/template.typ": *
#cvSection("Education")
#cvEntry(
title: [Software Engineering (Bootcamp)],
logo: "../src/logos/avion.png",
society: [Avion School],
location: [Philippines],
date: [2021 - 2022],
description: list(),
)
#cvEntry(
title: [Bachelor's degree in Entertainment and Multimedia Computing],
society: [University of Caloocan City],
location: [Caloocan City, Philippines],
logo: "../src/logos/ucc.png",
date: [2016 - 2020],
description: list(),
)
|
|
https://github.com/xsro/xsro.github.io | https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/nlct/math/space.typ | typst | #import "common.typ": definition,theorem,proposition,proposition
#pagebreak(weak: true)
= Topological Space
- 拓扑学 http://staff.ustc.edu.cn/~wangzuoq/Courses/22S-Topology/
== Metic Space
#definition[
A *metric space* $(M,d)$ consists of a set $M$ and a mapping,
called distance, $d: M times M arrow RR$,
which satisfies the following:
+ $0<=d(x,y)<infinity, forall x,y in M$
+ $d(x,y)=0$, if and only if $x=y$
+ $d(x,y)=d(y,x)$
+ Triangle Inequality: $d(x,z)<=d(x,y)+d(x,z),x,y,z in M$
]
#definition[
Let $V$ be a vector space,
if there exists a mapping $norm(dot): V arrow RR$,
satisfying
+ $norm(dot) >=0$, $forall x in V$ and $norm(x)=0$, if and only if $x=0$
+ $norm(r x)=abs(r)norm(x)$, $r in RR$, $x in V$
+ Triangle Inequality: $norm(x+y)<=norm(x)+norm(y),quad x,y in V$
Then $(M,norm(dot))$ is called a *normed space*,
and $norm(x)$ is called the norm of $x$
]
#let product(x,y)={
[$angle.l #x,#y angle.r$]
}
#definition[
Given a vector space $V$.
If there exists a mapping $product(dot,dot):V times V arrow CC$,
satisfies the following requirements:
+ $product(x,x)>=0,forall x in V$. Moreover, $product(x,x)=0$, if and only if $x=0$
+ $product(x,y)=overline(product(y,x)), x,y in V$
+ $product(a x+b y,z)=a product(x,z)+b product(y,z),x,y,z in V, a,b in CC$
Then $(V,product(dot,dot))$ is called an *inner product space*,
and $product(x,y)$ is called the inner product of $x,y$
]
#proposition[
+ Let $V$ be an inner product space.
Define a norm on $V$ as
$norm(x)=sqrt(product(x,x))$
Then $V$ becomes a normed space. Such a norm is called the norm induced by the inner product
+ Let $M$ be a normed space.
Define a distance $d$ as
$d(x,y)=norm(x-y)$,
Then $M$ becomes a metric space.
]
#definition[
A metric space $M$ is complete if each Cauchy sequence ${x_n}$ converges to a point $x in M$.
]
== Topological Spaces
#definition[
Given a set $X$ and a set of its subsets $cal(T)$.
+ $(X,cal(T))$ is called a topological space,
if $cal(T)$ satisfies the following
+ $X in cal(T), emptyset in cal(T)$;
+ If $U_lambda in cal(T),forall lambda in Lambda subset RR$, then $union_(lambda in Lambda) U_lambda in cal(T)$;
+ If $U_i in cal(T), i=1,dots,n$, then $sect_(i=1)^n U_i in cal(T)$
+ An element in $U in cal(T)$ is called an open set.
Its complement,denoted by $U^c$ is called a closed set.
+ For a point $x in X$, a subset $N$ is called a neighborhood of $x$ if there exists an open set $U$ such that $x in U subset N$
+ Let $cal(B) subset cal(T)$. $cal(B)$ is a topological basis if any element $U in cal(T)$ can be expressed as a union of some elements in $cal(B)$
+ A set of neighborhoods $cal(N) subset cal(T)$ is called a neighborhood basis of $x$ if for any neighborhood $N$ of $x$, there is an $N_0 in cal(N)$, such that $N_0 subset N$
]
== Continuous Mapping
#definition[
Let $M$, $N$ be two topological spaces.
A mapping $pi:M arrow N$ is continuous,
if one of the following two equivalent conditions holds:
- For any $U subset N$ open, its inverse image
$
pi^(-1)(U):={x in M | pi(x) in U}
$
is open
- For any $C subset N$ closed, its inverse image $pi^(-1)(C)$ is closed
]
*Note*: the two conditions are equivalent.
#definition[
Let $M$,$N$ be two topological spaces.
$M$ and $N$ are said to be homeomorphic(同胚 pei 胚胎)
if there exists a mapping $pi:M arrow N$, which is
+ one-to-one( 单射 injective),
+ onto(满射 surjective)
+ and continuous (both $pi$ and $pi^(-1)$ are continuous).
$pi$ is called a homeomorphism.
]
*Note*: If a mapping is both injective and surjective it is said to bijective(满射).
#definition[
Given a topological space $M$.
+ A set $U subset M$ is said to be clopen if it is both closed and open.
A topological space(度量空间), $M$, is said to be *connected* if the only two clopen sets are $M$ and $emptyset$
+ A continuous mapping $pi: I=[0,1] arrow M$ is called a path on $M$.
$M$ is said to be *pathwise(or arcwise) connected* if for any two points $x,y in M$ there exists a path,
$pi$, such that $pi(0)=x$ and $pi(1)=y$
]
*Tip on open and closed set*: As described by topologist <NAME>, unlike a door, "a set can be open, or closed, or both, or neither!"
#link("https://en.wikipedia.org/wiki/Clopen_set")
A set is closed if its complement is open.
But A set can be closed or open if its complement is closed.\
#link("https://en.wikipedia.org/wiki/Open_set")\
A subset $U$ of a metric space $(M,d)$ is called open if,
for any point $x$ in $U$,
there exists a real number $epsilon$
such that any point $y in M$ satisfying $d(x,y)<epsilon$ belongs to $U$.
Equivalently, $U$ is open if every point in $U$ has a neighborhood contained in $U$.
*Note*: $RR$ is connected and A pathwise connected space $M$ is connected while the converse is incorrect.
#definition[
A topological space $M$ is said to be _locally connected_ at $x in M$ if every neighborhood $N_x$ of $x$ contains a connected neighborhood $U_x$, i.e., $x in U_x subset N_x$.
$M$ is said to be locally connected if it is locally connected at each $x in M$
]
local connectedness does not imply connectedness
(hence no pathwise connectedness);
conversely, pathwise connectedness (connectedness) does not imply local connectedness.
#definition[
Let ${U_lambda|lambda in Lambda}$ be a set of open sets in $M$.
The set is called an open covering of $M$ if
$
union.big_(lambda in Lambda) U_lambda supset M.
$
$M$ is said to be a compact space if every open covering has a finite sub-covering,
i.e., there exists a finite subset ${U_lambda_i| i=1,2,dots,k}$ such that
$
union.big_(i=1)^k U_(lambda_i) supset M
$
]
From Calculus we know that with the conventional topology,
a set, $U subset RR^n$ is compact, if and only if it is bounded and closed.
Unfortunately, it is not true for general metric spaces.
#definition[
In a topological space,
$M$, a sequence ${x_k}$ is said to converge to $x$,
if for any neighborhood $U in.rev x$ there exists a positive integer
$N>0$ such that when $n>N$, $x_n in U$.
]
+ Impose the discrete topology on $RR^1$. i.e., each point is an open set.
Then $x_k$ converges to nowhere.
Because it can never get into any ${r}$, which is a neighborood of $r$
// commented if
// + Impose the co-finite topology on $RR^1$.
// Recall that in this topology $U != emptyset$ is open,
// if and only if $U^c$ is finite.
// Then $x_k$ converges to every point.
// Let $r in RR$ be any point, and $U in.rev r$ be a co-finite neighborhood.
// Since $U^c$ is finite at most finite $x_k in U^c$.
#proposition[
Let $M$, $N$ be two topological spaces.
$M$ is first countable.
$f: M arrow N$ is continuous,
if and only if for each $x_k arrow x$, $f(x_k) arrow f(x)$
]
#definition[
A topological space is called sequentially compact if
every sequence contains a convergent subsequence.
]
#definition[
(*Bolzano-Weierstrass*) Let $M$ be a first countable topological space.
if $M$ is compact, it is sequentially compact.
]
== Quotient Spaces
#definition[
Let $S$ be any set and $tilde$ be a relation between two elements of $S$.
$tilde$ is said to be an equivalent relation if
1. $x tilde x$
2. If $x tilde y$, then $y tilde x$
3. If $x tilde y$, and $y tilde z$, then $x tilde z$
]
#definition[
Let M be a topological space,
"$tilde$" an equivalent relation on $M$
] |
|
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs | https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task1/1.1.typ | typst | Apache License 2.0 | = Requirement elicitation
== Giới thiệu về bối cảnh miền của hệ thống phát triển dịch vụ in ấn thông minh. Những bên liên quan, nhu cầu hiện tại và lợi ích SPSS mang lại cho từng bên liên quan
=== _Giới thiệu về bối cảnh miền của dịch vụ in ấn thông minh cho sinh viên đại học Bách Khoa thành phố Hồ Chí Minh_
Bối cảnh miền của một hệ thống bao gồm miền vấn đề (problem domain) và miền ứng dụng (application domain) . Dịch vụ in ấn thông minh (SPSS) là một hệ thống được phát triển bởi trường Đại học Bách Khoa Thành phố Hồ Chí Minh nhằm cung cấp cho sinh viên một dịch vụ in ấn tiện lợi, an toàn và nhanh chóng nhất với số lượng nhỏ. Dịch vụ có thể sẽ được cung cấp dưới hai dạng: tự phục vụ và truyền thống. Mọi sinh viên đều được khuyến khích sử dụng dịch vụ này nếu bản thân sinh viên gặp phải những vấn đề khó khăn khi sử dụng dịch vụ in truyền thống tại trường như sau (problem domain):
#block(inset:(left:1cm))[
- Không chủ động thời gian vì phụ thuộc vào các tiệm in.
- Không tận dụng được thời gian di chuyển đến tiệm in.
- Vấn đề bảo mật thông tin khi sử dụng dịch vụ truyền thống như virus.
- Không bảo đảm về phương thức thanh toán phù hợp.
- Giá thành cao hơn so với dịch vụ in ấn truyền thông ngoài trường.
]
Miền ứng dụng (application domain) dùng để chỉ phạm vi chức năng hoặc lĩnh vực cụ thể mà hệ thống được thiết kế để yêu cầu phục vụ. Đối với SSPS, chúng ta có phạm vi chức năng và lĩnh vực như sau:
#block(inset:(left:1cm))[
- Phạm vi lĩnh vực
#block(inset:(left:1.2cm))[
\u{2218} Giáo dục: Hỗ trợ in ấn tài liệu cho sinh viên, giảng viên.
#linebreak()
\u{2218} Kinh doanh: Những người phát triển hệ thống kiếm lợi từ việc cung cấp dịch vụ.
]
- Phạm vi chức năng
#block(inset:(left:1.2cm))[
\u{2218} In ấn tài liệu của sinh viên giảng viên đa dạng từ tài liệu học tập, giáo trình, đề thi, nghiêm cứu khoa học, bảng điểm, chứng chỉ,...
#linebreak()
\u{2218} Đóng gói và bao bì an toàn, bảo mật tài liệu.
#linebreak()
\u{2218} Giao hàng và chuyển phát với tốc độ nhanh (không băt buộc).
]
]
=== _Những bên liên quan và nhu cầu hiện tại_
Stakeholder - một thuật ngữ dùng để chỉ bất kỳ người hay tổ chức mà bị ảnh hưởng bởi hệ thống và có lợi ích chính đáng. Hệ thống dịch vụ in ấn thông minh của trường (SSPS) gồm các bên liên quan sau:
#block(inset:(left:1cm))[
- Sinh viên, giảng viên trường đại học Bách Khoa: sử dụng SSPS để phục vụ việc in ấn tài liệu theo nhu cầu một cách thuận tiện và nhanh chóng.
- SPSO - Quản lý dịch vụ in ấn sinh viên: có nhu cầu nhằm nắm rõ được hoạt động in ấn của sinh viên như thói quen, sở thích, tần suất và quản lý cơ sở vật chất, trang thiết bị.
- Trường đại học bách khoa TPHCM (HCMUT): tích hợp SSPS vào hệ thống của trường để theo dõi và nắm bắt hoạt động in ấn của sinh viên và kiếm thêm lợi nhuận.
- Người giám sát máy in và thực hiện in ấn (trong trường hợp triển khai theo kiểu truyền thống): nhu cầu kiếm thêm thu nhập (nhân viên hỗ trợ của trường) hoặc ngày CTXH/điểm rèn luyện (sinh viên của trường).
- Nhân viên IT: nguyện vọng phát triển một phần mềm phù hợp để giải quyết vấn đề in ấn của sinh viên.
- Đại lý cung cấp giấy, mực in và kỹ thuật viên bảo trì: nhu cầu tìm kiếm một nơi tiêu thụ sản phẩm/dịch vụ, một đối tác ổn định và lâu dài.
- Các hệ thống thanh toán online: có nhu cầu thu hút thêm người sử dụng và thu được hoa hồng thông qua các kênh thanh toán.
]
=== _Lợi ích SPSS mang lại cho những bên liên quan_
Các bên liên quan (stakeholder) khi tham gia vào một hệ thống bên cạnh việc đáp ứng nhu cầu cấp thiết của khách hàng thì họ đều cần một lợi ích chính đáng. Lợi ích của các bên liên quan trong SSPS:
#block(inset:(left:1cm))[
- Sinh viên sử dụng dịch vụ: in ấn tài liệu thuận tiện, chủ động về thời gian và tiết kiệm chi phí in với các chương trình giảm giá và trợ giá từ trường.
- Trường đại học Bách Khoa: cải thiện chất lượng cơ sở vật chất cho sinh viên, thu lợi nhuận thông qua việc quản lý và cung cấp dịch vụ in ấn.
- Người quản lý máy in và thực hiện in ấn: Kiếm thêm thu nhập hoặc ngày CTXH/ĐRL ngoài giờ.
- Nhân viên IT: phát triển và duy trì hệ thống giúp họ có cơ hội phát triển lớn hơn về nghề nghiệp trong tương lai.
- Đại lý cung cấp giấy, mực in và kỹ thuật viên bảo trì: Kiếm thêm lợi nhuận và có được khách hàng lâu dài thông qua sự hợp tác của đại lý và nhà trường.
- Các hệ thống thanh toán online: cung cấp thêm dịch vụ để thu hút thêm người sử dụng, tạo ra hoa hồng thông qua các giao dịch.
]
|
https://github.com/YouXam/bupt-network-resources-guide | https://raw.githubusercontent.com/YouXam/bupt-network-resources-guide/main/template.typ | typst | MIT License | #let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let skippedstate = state("skipped", false)
#let forewordcounter = counter("foreword")
#let partcounter = counter("part")
#let lengthceil(len, unit: 字号.小四) = calc.ceil(len / unit) * unit
#let chinese-outline = counter("chinese-outline")
#let chinesenumbering(..nums, location: none, brackets: false) = locate(loc => {
let actual_loc = if location == none { loc } else { location }
if forewordcounter.at(actual_loc).first() >= 10 {
if nums.pos().len() == 1 {
chinese-outline.step()
context chinese-outline.display("第一章")
} else {
numbering(if brackets { "(1.1)" } else { "1.1" }, ..nums)
}
} else {
if nums.pos().len() == 1 {
none
} else {
numbering(if brackets { "(A.1)" } else { "A.1" }, ..nums)
}
}
})
#let chineseoutline(title: "目录", depth: none, indent: true) = {
forewordcounter.update(10)
heading(title, numbering: none, outlined: false)
locate(it => {
let elements = query(heading.where(outlined: true).after(it), it)
for el in elements {
// Skip list of images and list of tables
if partcounter.at(el.location()).first() < 20 and el.numbering == none { continue }
// Skip headings that are too deep
if depth != none and el.level > depth { continue }
let maybe_number = if el.numbering != none {
if el.numbering == chinesenumbering {
chinesenumbering(..counter(heading).at(el.location()), location: el.location())
} else {
numbering(el.numbering, ..counter(heading).at(el.location()))
}
h(0.5em)
}
let line = {
h(1em * (el.level - 1))
if el.level == 1 {
v(1em, weak: true)
}
if maybe_number != none {
style(styles => {
let width = measure(maybe_number, styles).width
box(
width: lengthceil(width),
link(el.location(), if el.level == 1 {
strong(maybe_number)
} else {
maybe_number
})
)
})
}
link(el.location(), if el.level == 1 {
strong(el.body)
} else {
el.body
})
// Filler dots
if el.level == 1 {
box(width: 1fr, h(10pt) + box(width: 1fr) + h(10pt))
} else {
box(width: 1fr, h(10pt) + box(width: 1fr, repeat[.]) + h(10pt))
}
// Page number
let footer = query(selector(<__footer__>).after(el.location()), el.location())
let page_number = if footer == () {
0
} else {
counter(page).at(footer.first().location()).first()
}
link(el.location(), if el.level == 1 {
strong(str(page_number))
} else {
str(page_number)
})
linebreak()
v(-0.2em)
}
line
}
})
chinese-outline.update(0)
}
#let project(author: "", title: "", class: "", body) = {
set document(author: author, title: title, date: datetime.today())
set page(footer: locate(loc => {
[
#set text(字号.五号)
#set align(center)
#if query(selector(heading).before(loc), loc).len() < 2 {
// Skip cover, copyright and origin pages
} else {
let headers = query(selector(heading).before(loc), loc)
let part = partcounter.at(headers.last().location()).first()
[
#str(counter(page).at(loc).first())
]
}
#label("__footer__")
]
}))
set heading(numbering: chinesenumbering)
show heading: it => {
if it.level == 1 {
set align(center)
it
} else {
it
v(0.4em)
}
}
set page(numbering: "1 / 1", header: context {
h(1fr)
if counter(page).get().first() != 1 {
[_ #title _]
}
})
set par(first-line-indent: 2em)
set text(font: ("Linux Libertine", "FZShuSong-Z01"), lang: "zh")
show emph: text.with(font: ("Linux Libertine", "FZKai-Z03"))
show strong: text.with(font: ("Linux Libertine", "FZXiaoBiaoSong-B05"))
show heading: it => {
if it.level == 1 {
strong(it)
v(1em)
} else {
strong(it)
}
}
show link: it => {
set text(fill: rgb("#3488f6"), weight: "thin")
underline(it, offset: 2pt)
}
let get-text = it => {
if it.func() == link {
it.body.text
} else {
it.text
}
}
show ref: it => {
if it.element.func() == heading {
let tmp = counter(get-text(it.element.body))
tmp.update(counter(heading).at(it.target))
let at = context tmp.display(it.element.fields().numbering)
link(locate(it.element.location()), [#at #it.element.body])
} else {
it
}
}
align(center)[
#v(10em)
#text([*#title*], size: 4em) \
#v(5em)
#text([*#author*], size: 2em) \
#v(1em)
#let today = datetime.today()
#text([
#today.year() 年 #today.month() 月 #today.day() 日 修订
], size: 1.5em)
]
pagebreak()
body
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.0/src/types/string.typ | typst | Apache License 2.0 | #import "../base-type.typ": base-type, assert-base-type
#import "../context.typ": context
/// Valkyrie schema generator for integer- and floating-point numbers
///
/// - name (internal):
/// - default (string): Default value to set if none is provided. *MUST* respect all other validation requirements.
/// - min (integer, none): If not none, the minimum string length that satisfies the validation. *MUST* be a positive integer. The program is *ILL-FORMED* if `min` is greater than `max`.
/// - max (integer, none): If not none, the maximum string length that satisfies the validation. *MUST* be a positive integer. The program is *ILL-FORMED* if `max` is less than `min`.
/// - length (integer, auto): If not auto, the exact string length that satisfies validation. *MUST* be a positiive integer. The program *MAY* be *ILL-FORMED* is concurrently set with either `min` or `max`.
/// - includes (array, string, none): If set, a coerced array of required strings that are required to pass validation.
/// - starts-with (string, regex, none): If set, a string or regex requirement that the string *SHOULD* start with in order to pass validation.
/// - ends-with (string, regex, none): If set, a string or regex requirement that the string *SHOULD* end with in order to pass validation.
/// - pattern (string, regex, none): If set, a string or regex requirment over the entire string that *SHOULD* be matched in order to pass validation.
/// - pattern-error (string, auto): If set, the error thrown if `pattern` is not satisfied.
/// - transform (function): A transformation applied after successful validation.
/// -> schema
#let string(
name: "string",
default: none,
min: none,
max: none,
length: auto,
includes: (),
starts-with: none,
ends-with: none,
pattern: none,
pattern-error: auto,
transform: it=>it,
) = {
// Program is ill-formed if length is set at the same time as min or max
// Type safety
assert( type(default) in (str, type(none)),
message: "Default of string must be of type string or none")
assert( type(min) in (int, type(none)), message: "Minimum length must be an integer")
if ( min != none){ assert( min >= 0, message: "Minimum length must be a positive integer")}
assert( type(max) in (int, type(none)), message: "Maximum length must be an integer")
if ( max != none){assert( max >= 0, message: "Maximum length must be a positive integer")}
assert( type(length) in (int, type(auto)), message: "Length must be an integer")
if ( length != auto){assert( length >= 0, message: "Maximum length must be a positive integer")}
if ( type(includes) == str) { includes = (includes,)}
assert( type(includes) == array, message: "Includes must be an array of string or regex primitives" )
for each in includes{
assert( type(each) in (str, regex), message: "Includes must be an array of string or regex primitives" )
}
assert( type(starts-with) in (str, regex, type(none)), message: "Starts-with must be of type string or regex")
assert( type(ends-with) in (str, regex, type(none)), message: "Ends-with must be of type string or regex")
assert( type(pattern) in (regex, type(none)), message: "Pattern must be of type regex")
assert( type(pattern-error) in (str, type(auto)), message: "Pattern-error must be a string")
assert( type(transform) == function, message: "Transform must be a function that takes a single string and return a string")
return (:..base-type(),
name: name,
default: default,
min: min,
max: max,
length: length,
includes: includes,
starts-with: starts-with,
ends-with: ends-with,
pattern: pattern,
pattern-error: pattern-error,
transform: transform,
validate: (self, it, ctx: context(), scope: ()) => {
// Default value
if (it == none){ it = self.default }
// String must be a string
if not (self.assert-type)(self, it, scope: scope, ctx: ctx, types: (str,)){
return none
}
// Minimum length
if (self.min != none) and (it.len() < self.min) {
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String length less than specified minimum of " + str(self.min))
}
// Minimum length
if (self.max != none) and (it.len() > self.max) {
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String length greater than specified maximum of " + str(self.max))
}
// Exact length
if (self.length != auto) and (it.len() != self.length) {
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String length must exactly equal " + str(self.length))
}
// Includes
for required-include in self.includes {
if not it.contains(required-include){
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String must include " + str(required-include))
}
}
// startswith
if (self.starts-with != none) and not it.starts-with(self.starts-with) {
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String must start with " + str(self.starts-with))
}
// ends with
if (self.ends-with != none) and not it.ends-with(self.ends-with) {
return (self.fail-validation)(self, it, ctx: ctx, scope: scope,
message: "String must end with " + str(self.ends-with))
}
// regex, possibly extend to custom like other types?
if ( self.pattern != none ) and (it.match(self.pattern) == none){
let message = "String failed to match following pattern: " + repr(self.pattern)
if ( self.pattern-error != auto ){ message = self.pattern-error }
return (self.fail-validation)(self, it, ctx: ctx, scope: scope, message: message)
}
return (self.transform)(it)
}
)
}
/// A specialization of string that is satisfied only by email addresses. *Note*: The testing is not rigourous to save on complexity.
#let email = string.with(
name: "email",
pattern: regex("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{2,3}){1,2}$"),
pattern-error: "String must be an email address"
)
// TO DO: url
// TO DO: emoji
// TO DO: uuid
/// A specialization of string that is satisfied only by valid IP addresses. *Note*: The testing *IS* strict.
#let ip = string.with(
name: "ip",
pattern: regex("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"),
pattern-error: "String must be a valid IP address"
)
// Transformations:
#let transform-trim = string.with(transform: str.trim)
#let transform-lowercase = string.with(transform: lower)
#let transform-uppercase = string.with(transform: upper) |
https://github.com/ivaquero/book-control | https://raw.githubusercontent.com/ivaquero/book-control/main/05-比例积分控制.typ | typst | #import "@local/scibook:0.1.0": *
#show: doc => conf(
title: "比例积分控制",
author: ("ivaquero"),
header-cap: "现代控制理论",
footer-cap: "github@ivaquero",
outline-on: false,
doc,
)
= 比例控制
<比例控制>
== 体重变化
<体重变化>
已知,7000 kcal ∼ 1 kg
于是,有
$ dv(m, t) = frac(E_i - E_e, 7000) $
其中,$m$为体重,$E_i$为饮食摄入热量,$E_e$为消耗(expenditure)热量,$E_e$的计算方法为
$ E_e = E_a + α P $
其中,$E_a$为客观运动消耗热量,$α$为正常消耗系数,$P$为基础代谢率(base metabolic rate,BMR)。
对$α$有
- 轻体力劳动:$α = 1.3$
- 中体力劳动:$α = 1.5$
- 重体力劳动:$α = 1.9$
对 BMR,有 Mifflin Jeor 公式
$ P = 10 m + 6.25 h - 5 a + s $
其中,$h$为身高,$a$为年龄,s 为代谢常数(男:5,女:-161)。
== 控制器与稳定性
<控制器与稳定性>
上,不难得出
$
dot(m) &= frac(E_i - E_a - α (10 m + 6.25 h - 5 a + s), 7000)\
&= frac(E_i - E_a - 10 α m - α C, 7000)
$
其中,$C = 6.25 h - 5 a + s$
令
- 输入:$u = E_i - E_a$
- 扰动:$d = -α C$
- 输出:$m$
于是,有
$ 7000 dot(m) + 10 m = u + d $
等号两边同时进行 Laplace 变换,得
$ frac(M(s), U(s) + D(s)) = frac(1, 7000 s + 100) $
#figure(
image("./images/block/prop.drawio.png", width: 40%),
caption: [比例控制],
supplement: "图",
)
对控制器
$ u = k_p e $
其中,$e = r - m$,即参考值与实际体重的误差。
== 引入比例
<引入比例>
这里,有
$ [k_p(R - M) + D] frac(1, 7000 s + 10 α) = M $
整理,得
$ M = frac(k_p R + D, 7000 s + 10 α + k_p) $
当$M$的极点小于$0$,系统稳定。一种常见情况是,$R$和$D$是稳定的,即
- $R = ℒ[r] = r / s$
- $D = ℒ[d] = d / s$
此时
$ M = frac(k_p r/s + d/s, 7000 s + 10 α + k_p) $
令分子为$0$,求出$P_1$和$P_2$
$ m(t) = C_1 e^(0 t) + C_2 e^(frac(-10 α - k_p, 1000)t) $
由于第一项为常数,系统稳定性由$k_p + 10 α$确定。
= 稳态误差
<稳态误差>
== 终值定理
<终值定理>
稳态误差,指系统稳定时的输出值和参考值之间的差值,即
$ e_(s s) = r - lim_(t → ∞) x(t) $
要对稳态误差实现有效控制,需要终值定理(final value theorem,FVT),即
当$∃ lim_(t → ∞) x(t)$ 时
$ lim_(t → ∞) x(t) = lim_(s → 0) s X(s) $
#tip[
终值定理可以省去 Laplace 逆变换,得到时域上的最终结果,常用于系统稳态判断。
]
== 弹簧阻尼系统
<弹簧阻尼系统>
#figure(
image("./images/model/vibration.drawio.png", width: 40%),
caption: [弹簧阻尼系统],
supplement: "图",
)
对弹簧阻尼系统
$ m dot.double(x) + k x + B dot(x) = F $
使输出$u = F$,两边同时进行 Laplace 变换,整理得
$ frac(X(s), U(s)) = frac(1, m s^2 + B s + k) $
这里仅讨论欠阻尼状态,考虑
- 对冲击响应$δ(t)$
$u(s) = ℒ[δ(t)] = 1$,于是
$ X(s) = frac(1, m s^2 + B s + k) $
使用 FVT,有
$ lim_(t → ∞) x(t) = lim_(s → 0) frac(s, m s^2 + B s + k) = 0 $
- 对阶跃响应$c$
$u(s) = ℒ[c] = c/s$,于是
$ X(s) = c / s frac(1, m s^2 + B s + k) $
使用 FVT,有
$ lim_(t → ∞) x(t) = lim_(s → 0) c / s frac(s, m s^2 + B s + k) = c / k $
#tip[
无阻尼状态,即$B = 0$时,$lim_(t → ∞) x(t)$ 不存在,无法使用 FVT。
]
= 积分控制
<积分控制>
== 比例控制器
<比例控制器>
#figure(
image("./images/block/prop-simple.drawio.png", width: 40%),
caption: [弹簧阻尼系统框图],
supplement: "图",
)
对上图系统,有
$ k_p(R(s) - X(s)) frac(1, "as" + 1) = X(s) $
整理得
$ X(s) = frac(k_p R(s), "as" + 1 + k_p) $
为使$X(s)$稳定,则其极点$s$需要小于$0$,即
$ s = frac(-1 - k_p, a) < 0 $
可知$k_p$应大于$-1$。此时,可使用 FVT。
当$r(t) = r$,有
$ X(s) = frac(k_p r/s, "as" + 1 + k_p) $
使用 FVT,有
$
lim_(t → ∞) x(t) = lim_(s → 0) s frac(k_p r/s, "as" + 1 + k_p) = frac(k_p, 1 + k_p) r
$
此时
$ e_(s s) = r - frac(k_p, 1 + k_p) r = frac(1, 1 + k_p) r $
由上,要消除稳态误差,需要$k_p → ∞$,这显然不可能,所以比例控制的效果有限。
== 比例积分控制
<比例积分控制>
将上述系统中的$k_p$替换为$c(s)$,使
$ lim_(s → 0) c(s) → ∞ $
则可消除$e_(s s)$。由 Laplace 变换,只需要因子$1/s$即可达到目的,显然此处需要引入积分运算。
令$c(s) = k_I/s$,有
$ X(s) = frac(r/s⋅k_I/s, "as" + 1 + k_I/s) = r / s frac(k_I, a s^2 + s + k_I) $
整理并进行 Laplace 逆变换,得
$ a x ̈(t) + x ̇(t) + k_I = r k_I $
这即是二阶系统的阶跃响应。即,通过引入积分,系统被升阶为了一个二阶系统。
|
|
https://github.com/levinion/typst-dlut-templates | https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/templates/thesis/introduction.typ | typst | MIT License | #import "../util/style.typ":font_family,font_size
#import "../util/functions.typ":invisible_heading
#let introduction(content)={
if content != none {
set align(center)
set text(font: font_family.heiti, size: font_size.xiao_san)
set par(leading: 0.7em)
[引#h(2em)言 \
\
]
invisible_heading()[引#h(2em)言]
set align(left)
set text(font: font_family.songti, size: font_size.xiao_si)
set par(leading: 0.9em, justify: true, first-line-indent: 2em)
set block(spacing: 1em)
content
pagebreak(weak: true)
}
}
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/042_Strixhaven%3A%20School%20of%20Mages.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Strixhaven: School of Mages", doc)
#include "./042 - Strixhaven: School of Mages/001_Episode 1: Class Is in Session.typ"
#include "./042 - Strixhaven: School of Mages/002_A Cry of Magic.typ"
#include "./042 - Strixhaven: School of Mages/003_Episode 2: Lessons.typ"
#include "./042 - Strixhaven: School of Mages/004_Episode 3: Extracurriculars.typ"
#include "./042 - Strixhaven: School of Mages/005_The Chains That Bind.typ"
#include "./042 - Strixhaven: School of Mages/006_Episode 4: Put to the Test.typ"
#include "./042 - Strixhaven: School of Mages/007_The Mentor.typ"
#include "./042 - Strixhaven: School of Mages/008_Episode 5: Final Exam.typ"
#include "./042 - Strixhaven: School of Mages/009_Blue-Green Ribbons.typ"
#include "./042 - Strixhaven: School of Mages/010_A Silent Voice Calls.typ"
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/par-bidi-05.typ | typst | Other | // Test spacing.
L #h(1cm) ריווחR \
Lריווח #h(1cm) R
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/def_use/import_star.typ | typst | Apache License 2.0 | // path: base.typ
#let x = 1;
#x
-----
#import "base.typ"
#base
#import "base.typ": *
#base, #x |
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/figures/multi-robot-path-planning-classification.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
// #set page(width: 140pt, height: 140pt, margin: 1em)
#import "@preview/cetz:0.2.2"
#import "@preview/funarray:0.4.0": windows
#import "../lib/vec2.typ"
#import "../lib/catppuccin.typ": catppuccin
#let theme = catppuccin.theme
// #import "common.typ": *
#set align(center)
#let robot(pos) = {
import cetz.draw: *
let c = theme.blue
circle(pos, radius: 0.1, fill: c.lighten(70%), stroke: c.lighten(20%))
}
#let coordinator(pos) = {
import cetz.draw: *
let c = theme.peach
circle(pos, radius: 0.125, fill: c.lighten(70%), stroke: c.lighten(20%))
}
#let connection(from, to) = {
import cetz.draw: *
line(from, to, stroke: (dash: "dashed", paint: theme.overlay2))
// circle(pos, radius: 0.15, fill: c.lighten(50%), stroke: c)
}
#let velocity(pos, dir) = {
import cetz.draw: *
// line(from, to, stroke: (dash: "dashed", paint: gray))
// let c = olive.lighten(50%)
let c = theme.maroon.lighten(30%)
line(pos, vec2.add(pos, dir), stroke: (dash: "dotted", paint: c), mark: (end: "stealth", fill: c))
}
#let title(t) = text(size: 10pt, weight: "semibold", black.lighten(30%), t)
// = Centralized
// #title[Centralized]
#let centralized = cetz.canvas({
import cetz.draw: *
// coordinate-grid(10, 10)
let robot-positions = (
(1, 1),
(-1, 1),
(-0.5, -0.8),
(0, 1.5),
(0.2, -1.1),
(0.5, -0.5),
(1.2, 0.1),
(-1.3, -0.1)
)
let coordinator-pos = (0, 0)
velocity(robot-positions.at(0), (0.0 ,0.5))
velocity(robot-positions.at(1), (0, 0.5))
velocity(robot-positions.at(2), (0, 0.56))
velocity(robot-positions.at(3), (0, 0.7))
velocity(robot-positions.at(4), (-0.1, 0.5))
velocity(robot-positions.at(5), (0.1, 0.55))
velocity(robot-positions.at(6), (0, 0.5))
velocity(robot-positions.at(7), (0, 0.55))
// velocity(robot-positions.at(8), (0, 0.8))
for pos in robot-positions {
let pos = vec2.add(coordinator-pos, pos)
connection(coordinator-pos, pos)
robot(pos)
// line(coordinator-pos, pos, stroke: (dash: "dashed", paint: gray))
}
coordinator(coordinator-pos)
})
// #pagebreak()
// = Decentralized
// #title[Decentralized]
// In the decentralized control strategy, each robot makes its own decisions based on its measurements.
#let decentralized = cetz.canvas({
import cetz.draw: *
// coordinate-grid(10, 10)
let robot-positions = (
(1, 1),
(-1, 1),
(-0.5, -0.8),
(0, 1.5),
(0.2, -1.1),
(0.5, -0.5),
(1.2, 0.1),
(-1.3, -0.1),
(0, 0)
)
let robot-velocities = (
(0, 0.5),
(0, 1),
(0, 1),
(0, 1),
(0, 1),
(0, 1),
(0, 1),
(0, 1),
(0, 1),
)
velocity(robot-positions.at(0), (0.25, 0.5))
velocity(robot-positions.at(1), (0, 0.5))
velocity(robot-positions.at(2), (-0.15, 0.56))
velocity(robot-positions.at(3), (0, 0.7))
velocity(robot-positions.at(4), (0, 0.5))
velocity(robot-positions.at(5), (0, 0.5))
velocity(robot-positions.at(6), (-0.1, 0.5))
velocity(robot-positions.at(7), (0.1, 0.55))
velocity(robot-positions.at(8), (0, 0.8))
for (pos, vel) in robot-positions.zip(robot-velocities) {
// line(pos, vec2.add(pos, vel), stroke: (dash: "dotted", paint: aqua), mark: (end: ">", fill: aqua))
}
// let coordinator-pos = (0, 0)
for pos in robot-positions {
// let pos = vec2.add(coordinator-pos, pos)
coordinator(pos)
// line(coordinator-pos, pos, stroke: (dash: "dashed", paint: gray))
}
// catmull((0,0), (1,1), (2,-1), (3,0), tension: .4, stroke: purple.lighten(80%))
// coordinator(coordinator-pos)
})
// #pagebreak()
// = `Distributed`
// #title[Distributed]
#let distributed = cetz.canvas({
import cetz.draw: *
// coordinate-grid(10, 10)
let robot-positions = (
(1, 1),
(-1, 1),
(-0.5, -0.8),
(0, 1.5),
(0.2, -1.1),
(0.5, -0.5),
(1.2, 0.1),
(-1.3, -0.1),
(0, 0)
)
let coordinator-pos = (0, 0)
// for i in range(robot-positions.len()) {
// for j in range(robot-positions.len()) {
// if i == j {
// continue
// }
// let from = robot-positions.at(i)
// let to = robot-positions.at(j)
// line(from, to, stroke: (dash: "dashed", paint: gray))
// }
// }
velocity(robot-positions.at(0), (0.05, 0.6))
velocity(robot-positions.at(1), (0, 0.5))
velocity(robot-positions.at(2), (-0.15, 0.56))
velocity(robot-positions.at(3), (0, 0.7))
velocity(robot-positions.at(4), (0, 0.5))
velocity(robot-positions.at(5), (0.6, -0.1))
velocity(robot-positions.at(6), (-0.1, 0.5))
velocity(robot-positions.at(7), (-0.1, 0.55))
velocity(robot-positions.at(8), (0, 0.8))
let connection-between(i, j) = {
connection(
robot-positions.at(i),
robot-positions.at(j)
)
}
connection-between(0, 3)
connection-between(0, 5)
connection-between(0, 6)
connection-between(1, 3)
connection-between(1, 7)
connection-between(2, 5)
connection-between(2, 7)
connection-between(2, 4)
connection-between(4, 5)
connection-between(5, 6)
connection-between(5, 8)
connection-between(6, 8)
connection-between(8, 2)
for pos in robot-positions {
// let pos = vec2.add(coordinator-pos, pos)
coordinator(pos)
}
})
// #pagebreak()
#figure(
grid(
columns: 3,
column-gutter: 4em,
row-gutter: 1em,
rows: 2,
title[Centralized],
title[Decentralized],
title[Distributed],
centralized,
decentralized,
distributed
)
)
|
https://github.com/RandomcodeDev/FalseKing-Design | https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/game/input.typ | typst | = Input
Keyboard/mouse and controllers will both be supported. Haptics for better immersion when using supported controllers should be possible as well. There will be inputs for attacking, jumping, dashing, changing elements, interacting, pausing, and accessing the different screens. |
|
https://github.com/MultisampledNight/interpretation | https://raw.githubusercontent.com/MultisampledNight/interpretation/main/interpretation.typ | typst | Other | #import "util/graphics.typ"
#let version = "0.1.2"
#set page(
numbering: "1 / 1",
)
#set par(
justify: true,
)
#set text(
size: 14pt,
font: "IBM Plex Serif",
lang: "de",
)
#set heading(
numbering: "1.1",
)
#align(
right,
)[
#text(2em)[hilfe Interpretation wie] \
Von MultisampledNight \
Version #version
]
#let note(body) = block(
fill: luma(92.5%),
inset: 0.5em,
radius: 0.5em,
width: 100%,
[
Anmerkung \
#v(-0.5em)
#line(
length: 100%,
stroke: luma(70%),
)
#v(-0.5em)
#body
]
)
#let todo(body) = align(
right,
box(
fill: purple.transparentize(80%),
inset: 0.5em,
radius: 0.5em,
[TODO: #body],
),
)
#outline(
fill: align(right, repeat[.]),
indent: auto,
)
= Ziel
Finde eine tiefere Bedeutung im Text.
= Anleitung
+ Lese den Text ein paar mal durch.
- Idealerweise gleich mit Stift in der Hand,
um einzelne Sinnabschnitte zu finden und markieren.
+ Überlege dir eine initiale Hypothese
über eine mögliche Interpretation
des Textes,
welche du über deine Arbeit hinweg
bestätigen,
ablehnen oder
irgendetwas dazwischen damit machen
wirst.
+ Finde Elemente,
mithilfe sich der Text
zunächst oberflächlich beschreiben lässt.
- Wenn ein Dialog vorhanden ist,
sammle
Argumentationspunkte,
Strategie und
Motivationen
der teilnehmenden Entitäten.
- Falls Motive zu finden sind,
schreibe diese auf.
Vielleicht
korrelieren,
interagieren oder
entgegenstehen
diese auch.
+ Lege dir einen Schreibplan/eine Gliederung zurecht.
- Die Skelettstruktur
für die meisten Fälle
ist ungefähr:
+ Einleitung
- Basissatz
- Epochenbezug
+ Hauptteil
#set enum(numbering: "a)")
+ Initiale Hypothese
+ Inhaltszusammenfassung
+ Dialoganalyse (falls nötig)
+ Sprachlich-stilistische Analyse
+ ...
+ Überprüfung der Hypothese
+ Fazit
+ Schluss
- Rückbezug auf Einleitung
- Bedeutung der Epoche oder Autor:in
- Das sollte man so weit ausfüllen,
dass man davon ausgehend
den eigentlichen Text schreiben kann,
ohne viel nachzudenken.
- Wie das aber genau aussehen soll,
hängt von der Textart ab.
- Man kann auch von der kanonischen Gliederung für die jeweilige Textart abweichen.
Das sollte man aber nur mit gutem Grund machen.
+ Führe diesen Schreibplan aus,
um den eigentlichen Text zu erhalten.
- Es ist okay,
wenn man während dem Schreiben des Textes neue Dinge herausfindet,
die nicht im Schreibplan standen,
oder doch etwas ganz anders ist.
- Meist bietet es sich an,
den Schreibplan entsprechend anzupassen,
damit sowohl Korrektor:in als auch du selber
den Überblick behalten.
Das ist aber nicht unbedingt nötig.
= Wie?
Baue nach und nach Modelle auf,
die bei der Abstraktion helfen.
== Sinnabschnitte
Texte behandeln oft mehrere
Szenen,
Situationen,
Perspektiven und
Geschehnisse.
Dementsprechend lassen sich oft
Abschnitte finden,
wo die gerade genannten Elemente
mehr oder weniger zusammenhängend sind.
Diese Abschnitte werden Sinnabschnitte genannt,
weil sie den Text brillianterweise sinnmäßig unterteilen.
Sie helfen sowohl
bei der Orientierung
für das Finden
von relevanten Textelementen,
als auch
bei der Referenz
auf diese Textelemente
dann in der Interpretation.
Effektiv sind diese
nur eine Abstraktion
über die reine Zeilenangabe
(die man sowieso immer bei Zitaten machen sollte)
hinweg,
und erlauben
eine gröbere Einordung
des Textes.
Pro Sinnabschnitt
sollte man
mindestens ein Stilmittel
und
eine Überschrift für den gesamten Abschnitt
finden.
Das ist aber auch nicht universell:
Kafka beispielsweise verwendet kaum Stilmittel,
bei Gedichten sind die Stilmittel
weitaus wichtiger als anderswo,
und auch hier gibt es große Epochenunterschiede.
== Interpretationsebenen
Ein Text hat mehrere sogenannte
Interpretationsebenen.
Eine Ebene ist
ein zusammenhängendes Verständnis
vom gesamten Text.
Bei Gedichten und Parabeln
müssen _beinahe alle_ Elemente des Textes
zu einer Ebene passen,
damit diese zutrifft,
bei anderen Texten ist es auch okay,
wenn mehrere Elemente nicht passen.
Je tiefer eine Ebene,
desto _abstrakter_ ist diese.
Die erste Ebene ist konzeptuell das,
was in der Geschichte tatsächlich passiert.
Mit höherem Abstraktionsgrad
sind auch immer weniger Elemente
im Text selber zu finden.
Stattdessen bietet sich immer wieder
die Referenz auf vorherige Ebenen an.
- Die Ebenen muss man nicht in der Interpretation selber erwähnen.
- Stattdessen macht es meist mehr Sinn,
von möglichen Interpretationen direkt zu sprechen.
- Es kann mehrere Ebenen mit dem gleichen Abstraktionsgrad geben.
- Zu beschreiben,
warum eine mögliche Ebene _nicht_ zum Text passt,
ist auch ein sehr hilfreicher Teil der Erschließung.
== Epochenbezug
Eine Epoche ist
eine zeitlich begrenzte Strömung
(aber trotzdem selten genau einordbare)
von ähnlichen Ideen
mit meist ähnlichem Stil.
Auch wenn etwas
in der Zeit einer Epoche
geschrieben ist,
muss das nicht heißen,
dass das auch Teil der Epoche ist.
Beispielsweise schreibt
Franz Kafka bis 1924
und liegt damit zeitlich im Expressionismus,
aber die Art,
wie Kafka schreibt,
ist eigentlich eher dem Realismus zuzuordnen.
Ob man speziell die Epoche zuordnen muss,
sollte man zuvor
mit der Lehrkraft absprechen.
Wenn man das muss,
sollte das eine eigene Sektion sein.
Aber selbst wenn man nicht _muss_,
ist es trotzdem sehr hilfreich,
das in die Interpretation
dort einzubetten,
wo es hilft oder
Textelemente erklären kann.
= Anhang
== Stilmittel
#todo[Die häufigsten Stilmittel auflisten]
#pagebreak()
== Epochen der Literatur
#graphics.literature-epochs
|
https://github.com/darkMatter781x/OverUnderNotebook | https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/util.typ | typst | #import "/packages.typ": codetastic
#import codetastic: qrcode
#let qrlink(
url,
quiet-zone: 4,
min-version: 1,
ecl: "l",
mask: auto,
size: auto,
width: auto,
colors: (white, black),
debug: false,
) = link(url)[#qrcode(
url,
quiet-zone: quiet-zone,
min-version: min-version,
ecl: ecl,
mask: mask,
size: size,
width: width,
colors: colors,
debug: debug,
)]
|
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/attrs.typ | typst | #import "very-base-utils.typ": *
#import "strokes.typ"
#let known = (
fill: color,
color: color,
paint: color,
stroke: stroke,
width: length,
length: length,
thickness: length,
size: length,
height: length,
align: alignment,
)
#let fills = (
black: black,
gray: gray,
silver: silver,
white: white,
navy: navy,
blue: blue,
aqua: aqua,
teal: teal,
eastern: eastern,
purple: purple,
fuchsia: fuchsia,
maroon: maroon,
red: red,
orange: orange,
yellow: yellow,
olive: olive,
green: green,
lime: lime,
)
#let alignments = (
center: center,
left: left,
right: right,
horizon: horizon,
)
#let units = (
"pt": 1pt,
"cm": 1cm,
"in": 1in,
"em": 1em,
"%": 1%,
)
#let transformer(v, k) = {
if k not in known {
return v
}
let ref-type = known.at(k)
if ref-type == color {
return fills.at(v)
}
else if ref-type == alignment {
return alignments.at(v)
}
else if ref-type == stroke {
unreachable()
}
else if ref-type == alignment {
return alignments.at(v)
}
else if ref-type == length {
if is-number(v) {
return v * 1pt
} else {
let m = match(v, "(.*?)(pt|%|cm|in|em)")
if m != none {
return float(m.first()) * units.at(m.last())
}
}
}
}
#let transform(kwargs) = {
return walk(kwargs, transformer)
}
#let sample = (
color: (
fill: "green",
align: "center",
color: "green",
)
)
// #panic(transform(sample))
// each of the items is appropriately transformed into the typst version
// transform() takes regular json input and converts to typst types
#let fulfill(key) = {
let schema = (
canvas: (
canvas-attrs:(
length: "1cm"
),
)
)
}
#let get(key) = {
let ref = (
double-sided-arrow-mark: (
width: 0.2,
length: 0.3,
stroke: strokes.soft,
start: ">",
end: ">",
fill: black,
),
arrow-mark: (
width: 3,
length: 3,
end: ">",
fill: black,
),
inline-canvas: (
// stroke: black,
// inset: 3pt,
radius: 0pt,
fill: none,
outset: 0pt,
baseline: baseline,
),
)
return ref.at(key)
}
|
|
https://github.com/Big-Ouden/ensiie_rapport | https://raw.githubusercontent.com/Big-Ouden/ensiie_rapport/main/0.1.5/ensiie_rapport.typ | typst | // Template for reports ENSIIE
// v0.1.5 - mui 2024
//
// Missing features :
// - page and locations (above, under) references for figures not available yet
// Fancy pretty print with line numbers and stuff
// found on typst.app : codelst is a Typst package for rendering sourcecode with line numbers and some other additions.
#import "@preview/codelst:2.0.1": sourcecode
// Nice color boxes
// found on typst.app : Showybox is a Typst package for creating colorful and customizable boxes.
#import "@preview/showybox:2.0.1": showybox
// Define our own functions
#let todo(body, fill-color: yellow.lighten(50%)) = {
set text(black)
box(
baseline:25%,
fill: fill-color,
inset: 3pt,
[*TODO* #body],
)
}
//
// Multiple languages support
//
// Thanks @LordBaryhobal for the original idea
#let langs = (
fr: (
toc-title: "Table des matières",
bib-title: "Bibliographie",
chapter-title: "Chapitre",
figure-name: "Figure",
table-name: "Table",
listing-name: "Listing",
appendix-title: "Annexes",
appendix-code-name: "Code annexé",
acronym-table-title: "Table des acronymes",
figure-table-title: "Table des figures",
listing-table-title: "Table des listings",
table-table-title: "Table des tableaux",
),
en: (
toc-title: "Table of contents",
bib-title: "Bibliography",
chapter-title: "Chapter",
figure-name: "Figure",
table-name: "Table",
listing-name: "Listing",
appendix-code-name: "Code appendix",
appendix-title: "Appendix",
acronym-table-title: "Table of acronyms",
figure-table-title: "List of figures",
listing-table-title: "List of listings",
table-table-title: "List of tables",
),
de: (
toc-title: "Inhaltsverzeichnis",
bib-title: "Literatur",
chapter-title: "Kapitel",
figure-name: "Abb.",
table-name: "Tabelle",
listing-name: "Listing",
appendix-code-name: "<NAME>",
appendix-title: "Anhang",
acronym-table-title: "Akronymtabelle",
figure-table-title: "Abbildungen",
listing-table-title: "Quelltexte",
table-table-title: "Tabellen",
),
)
#let i18n(lang, key) = {
if not lang in langs {
lang = "fr"
}
let keys = langs.at(lang)
if not key in keys {
panic("I18n key " + key + "doesn't exist")
}
return keys.at(key)
}
//
// Source code inclusion
//
#let _luma-background = luma(250)
// Replace the original function by ours
#let codelst-sourcecode = sourcecode
#let code = codelst-sourcecode.with(
frame: block.with(
fill: _luma-background,
stroke: 0.5pt + luma(80%),
radius: 3pt,
inset: (x: 6pt, y: 7pt)
),
numbering: "1",
numbers-style: (lno) => text(luma(210), size:7pt, lno),
numbers-step: 1,
numbers-width: -1em,
gutter:1.2em
)
// The template itself
#let project(
title: [Report title],
sub-title: [Report sub-title],
course-name: [Course name],
course-supervisor: [Course supervisor],
semester: [Semester],
academic-year: [2023-2024],
cover-image: none,
cover-image-height: 10cm,
cover-image-caption: none,
cover-image-kind: auto,
cover-image-supplement: auto,
// A list of authors, separated by commas
authors: (),
date: none,
logo: none,
version : "1.0.0",
language : "fr",
body,
) = {
// Set the document's basic properties.
set document(author: authors, title: title)
// Document language for hyphenation and other things
let internal-language = language
//
// Fonts
//
let body-font = ("Source Sans Pro", "Source Sans 3", "Linux Libertine")
let sans-font = ("Source Sans Pro", "Source Sans 3", "Inria Sans")
let raw-font = "Jetbrains Mono"
let math-font = ("Asana Math", "Fira Math")
// Default body font
set text(font: body-font, lang: internal-language)
// Set other fonts
// show math.equation: set text(font: math-font) // For math equations
show raw: set text(font: raw-font) // For code
show heading: set text(font: sans-font) // For sections, sub-sections etc..
/////////////////////////////////////////////////
// Citation style
/////////////////////////////////////////////////
set cite(style: auto, form: "normal")
/////////////////////////////////////////////////
// Basic pagination and typesetting
/////////////////////////////////////////////////
set page(
margin: (inside: 2.5cm, outside: 2cm, y: 2.1cm), // Binding inside
paper: "a4"
)
let space-after-heading = 0.5em
show heading: it => {it; v(space-after-heading)} // Space after heading
let authors-str = ()
if (authors.len() > 1){
authors-str = authors.join(", ")
}
else{
authors-str = authors.at(0)
}
let header-content = text(0.75em)[
#emph(authors-str)
#h(1fr)
#emph(eval(version, mode: "markup"))
]
let footer-content = text(0.75em)[
#emph(eval(title, mode: "markup"))
#h(1fr)
#counter(page).display(
"1/1",
both: true
)
]
// Set header and footers
set page(
header: locate(loc => {
// For pages other than the first one
if counter(page).at(loc).first() > 1 {
header-content
}
}),
header-ascent: 40%,
footer: locate(loc => {
// For pages other than the first one
if counter(page).at(loc).first() > 1 [
#move(dy:5pt, line(length: 100%, stroke: 0.5pt))
#footer-content
]
})
)
// Links coloring
show link: set text(ligatures: true, fill: blue)
// Sections numbers
set heading(numbering: "1.1.1 -")
/////////////////////////////////////////////////
// Handle specific captions styling
/////////////////////////////////////////////////
// TODO : Make this suitable for different languages
// Compute a suitable supplement as they are not to my liking
let getSupplement(it) = {
if(it.func() == image){
i18n(internal-language, "figure-name")
} else if (it.func() == table){
i18n(internal-language, "table-name")
} else if (it.func() == raw){
i18n(internal-language, "listing-name")
} else{
auto
}
}
set figure(numbering: "1", supplement: getSupplement)
// Make the caption like I like them
show figure.caption: set text(9pt) // Smaller font size
show figure.caption: emph // Use italics
set figure.caption(separator: " - ") // With a nice separator
show figure.caption: it => {it.counter.display()} // Used for debugging
// Make the caption like I like them
show figure.caption: it => {
if it.numbering == none {
eval(mode:"markup", it.body.text)
} else {
it.supplement + " " + it.counter.display() + it.separator + eval(mode:"markup", it.body.text)
}
}
/////////////////////////////////////////////////
// Code related, only for inline as the
// code block is handled by function at the top of the file
/////////////////////////////////////////////////
// Inline code display,
// In a small box that retains the correct baseline.
show raw.where(block: false): box.with(
fill: _luma-background,
inset: (x: 2pt, y: 0pt),
outset: (y: 2pt),
radius: 1pt,
)
// Allow page breaks for raw figures
show figure.where(kind:raw): set block(breakable: true)
/////////////////////////////////////////////////
// Our own specific commands
/////////////////////////////////////////////////
let insertLogo(logo) = {
if logo != none {
place(top + right,
dx: 6mm,
dy: -12mm,
clearance: 0em,
// Put it in a box to be resized
box(height:2.0cm, logo)
)
}
}
/////////////////////////////////////////////////
// Let's make the template now
/////////////////////////////////////////////////
// Title page.
insertLogo(logo)
let title-block = course-supervisor + "\n" + semester + " " + academic-year + line(length: 100%)
let title-block-content = title-block
place(top + left,
dy: -2em,
text(1em,
text(weight: 700, course-name) + "\n" + text(title-block-content),
),
)
v(10fr, weak: true)
// Puts a default cover image
if cover-image != none {
show figure.caption: emph
figure(
box(cover-image, height: cover-image-height),
caption: cover-image-caption,
numbering: none,
kind: cover-image-kind,
supplement: cover-image-supplement
)
}
v(10fr, weak: true)
// Main title
set par(leading: 0.2em)
text(font: sans-font, 2em, weight: 700, smallcaps(eval(title, mode:"markup")))
set par(leading: 0.65em)
// Subtitle
v(1em, weak: true)
text(font: sans-font, 1.2em, eval(sub-title, mode:"markup"))
line(length: 100%)
v(4em)
// Author information on the title page
pad(
top: 1em,
right: 20%,
grid(
columns: 3,
column-gutter: 3em,
gutter: 2em,
..authors.map(author => align(start, text(1.1em, strong(author)))),
),
)
// The date
text(1.1em, date)
v(2.4fr)
pagebreak()
// --- Table of Contents ---
outline(
title: {
v(5em)
text(font: body-font, 1.5em, weight: 700, i18n(internal-language, "toc-title"))
v(3em)
},
indent: 2em,
depth: 2
)
pagebreak()
// Main body.
set par(justify: true)
body
}
|
|
https://github.com/vsheg/intermediate-ml | https://raw.githubusercontent.com/vsheg/intermediate-ml/main/01-formalism/07-information.typ | typst | #import "@preview/physica:0.9.3": *
#import "../defs.typ": *
#import "../template.typ": *
#show: template
= Information Theory
== Messages
=== Communication.
Information theory was originally developed to provide a theoretical framework for
addressing an engineering problem of communication. Formally, consider a scenario where a
sender wants to transmit a message, denoted as $omega$, to a receiver. In information
theory, the semantic content of messages is irrelevant; the focus is solely on the
engineering aspects of transmission. Here, the message is treated as a sequence of _symbols_.
=== Symbols.
Symbols are distinct, identifiable entities that form the alphabet used to represent a
message. For instance, the digits from 0 to 9 can be used to represent any integer number
(the message). Similarly, nodding or shaking one's head can be considered symbols
representing the messages "yes" and "no." For hearing-impaired individuals, hand gestures
are used as symbols to communicate, with each gesture representing a specific symbol.
=== Encoding.
The simplest symbolic system capable of transmitting information must have at least two
distinct symbols, such as "0" and "1." Using this simple formal language, we can encode
basic messages.
#example[A message about whether it will rain tomorrow can be encoded with just two symbols:
$ 0 = ["It will not rain tomorrow"], quad 1 = ["It will rain tomorrow"]. $
]
#example[The outcome of a coin flip can be encoded similarly:
$ 0 = ["The coin landed on tails"], quad 1 = ["The coin landed on heads"]. $
]
Messages can be represented by the codes used for their encoding. More complex messages
can be encoded as sequences of symbols.
#example[For four possible messages:
$
Omega = { quad \
& omega_1 = ["It will not rain tomorrow, and the coin landed on heads"], \
& omega_2 = ["It will not rain tomorrow, and the coin landed on tails"], \
& omega_3 = ["It will rain tomorrow, and the coin landed on tails"], \
& omega_4 = ["It will rain tomorrow, and the coin landed on heads"] \
}, quad &
$
The following encoding can be used:
$
00 = omega_1, quad 01 = omega_2, quad 10 = omega_3, quad 11 = omega_4.
$
]
These binary sequences carry _information_. Importantly, there is no way to transmit this
information in a more compact form; we need at least a sequence of length 2 binary symbols
to encode the weather and coin states. Thus, this code is _optimal_ and cannot be further
compressed.
=== Uncertainty.
A particular message $omega^*$ can be considered successfully transmitted if and only if
the receiver can identify this specific message $omega^*$ from the set of all possible
messages $omega \in Omega$. The larger the set $Omega$ is, the harder it is to select $omega^*$ from
the set of all possible messages. Therefore, the larger $Omega$, the greater the _uncertainty_ associated
with determining the transmitted message. Uncertainty is directly related to the number of
possible messages.
=== Bits.
Various encoding schemes can be used to transmit the same message. To abstract away from
the details of specific encodings and focus on the information content itself, we
introduce the concept of _bits_. A bit is the minimum amount of information required to
eliminate uncertainty between two possibilities. The sender must transmit at least 1 bit
so that the receiver can distinguish the sent message $omega^*$ from a set of two possible
messages $Omega = \{ omega_0, omega_1 \}$.
If the set of all possible messages contains $N > 2$ messages, each bit of information can
be used to eliminate half of the remaining possibilities.
$ Omega = \{ omega_1, omega_2, omega_3, omega_4 \} $
$ 0 = [omega^* "is in the first half of" Omega], quad 1 = [omega^* "is in the second half of" Omega]. $
- The first bit divides the set into two halves:
$ Omega = \{ wide ob(omega_1\, omega_2, 0), wide ob(omega_3\, omega_4, 1) wide \} $
- The second bit further divides the set:
$ Omega = \{ wide ob(ub(omega_1, 00)\, ub(omega_2, 01), 0), wide ob(ub(omega_3, 10)\, ub(omega_4, 11), 1) wide \} $
=== Information.
The amount of bits required to identify a specific message $omega$ is called the _information content_ $I(omega)$.
The sender sends $I(omega)$ bits of information by transmitting the message $omega$, and
the receiver receives $I(omega)$ bits of information when decoding the message to identify $omega$ from
the set $Omega$.
== Hartley function
=== Bits.
When there are multiple possible outcomes, we can distinguish between them if we have the
necessary information. The minimal amount of information is 1 bit. *By definition*, each
bit of information distinguishes between 2 possibilities. For example, 1 bit of
information is required to unambiguously identify the sex of a child. The event:
$ B = {"Masha gave birth to a boy"} $
corresponds to exactly 1 bit of information, and the inverse event similarly corresponds
to 1 bit of information:
$ macron(B) = {"Masha gave birth to a girl"} $
=== Additivity.
For two *independent and equally probable* events:
$ B = {"Masha gave birth to a boy"}, quad G = {"Lena gave birth to a girl"} $
we expect the total amount of information received when both events have occurred to be
additive:
$ I(A B) = I(A) + I(B) $
Since the logarithm satisfies this property, the possible choice is:
$ log f(A B) = log f(A) + log f(B) $
=== Probability.
The probability $p$ characterizes the frequency of an event. An event with a high
probability provides a small amount of information. For instance, the probability of the
sunrise is nearly one, so the information that there will be a sunrise tomorrow carries
little value. In contrast, the information that there will be no sunrise tomorrow conveys
a significant amount of information. Thus, *the lower the probability, the more
information is conveyed*:
$ I(A) = I(Pr[A]) wide "and" wide p arrow.t <=> I arrow.b. $
The appropriate formula that satisfies these conditions is:
$
I(f(A)) = log 1/Pr[A], quad f(A) = Pr(A).
$
$ I(A B) = log 1 / Pr[A] + log 1 / Pr[B] $
=== Inverse probability.
The inverse probability $1/p$ represents the *expected number of trials* needed to achieve
*one occurrence* of an event with probability $p$. For example, if $p = 0.01$, the event
occurs, on average, once every 100 trials.
=== Information content.
#note[
In $k$-valued logic, each $k$-valued digit (0, 1, ..., $k-1$) represents information:
- In binary logic, each digit is a bit (0 or 1).
- In ternary logic, each digit is a trit (0, 1, or 2).
]
Information is the *capacity to distinguish* between possibilities. Each bit of
information distinguishes 2 possibilities, and it can assume 2 different values, 0 and 1. $n$ bits
of information distinguish $2^n$ possibilities. Hence, the amount of information required
to distinguish between $2^n$ possibilities is $n$ bits.
If there are $N$ outcomes, each time you assign a bit value to an outcome, you divide all
outcomes into 2 sets corresponding to the bit values:
$ Omega = ub({ omega in Omega | omega"'s bit value" = 0 }, Omega_0)
union ub({ omega in Omega | omega"'s bit value" = 1 }, Omega_1) $
Now, for any $omega$, knowing the corresponding bit value allows you to determine whether $omega in Omega_0$ or $omega in Omega_1$,
thereby halving the uncertainty.
Repeating this $I$ times, you partition $Omega$ into $2^I$ disjoint sets, or more
precisely, $min(2^I, N)$, as $Omega$ contains only $N$ elements:
$ Omega = { omega_1 } union { omega_2 } dots union { omega_N } $
Once the sets contain only one element, further bits do not provide additional meaningful
information. Therefore, the amount of information is proportional to the size of $Omega$.
Each bit splits $Omega$ into 2 parts, and each subsequent bit continues dividing the sets
into 2 parts. However, it is only meaningful to repeat these binary divisions up to $log_2 N$ times.
Thus, the exact number of bits needed to distinguish all outcomes is:
$
I = log_2 N = log_2 1 / p.
$
== Shannon self-information
Self-information, introduced by <NAME>, quantifies the amount of information or "surprise"
associated with the occurrence of an event. The key properties of Shannon's
self-information are:
- An event with a probability of 100% is unsurprising and thus carries no information.
- Events that are less probable yield more information when they occur.
- For two independent events, the total information is the sum of their individual
self-informations.
The self-information for an event $A$ is defined as:
$ I(A) := lg_2 1 / Pr[A]. $
For a random variable $X$ taking a specific value $x$ with probability $Pr[X = x]$, the
self-information is:
$ I_X (x) := lg_2 1 / Pr[X = x]. $
== Odds ratio
The *odds* of an event $A$ is defined as the difference in self-information (also known as
surprisal) between the event $A$ and its complement $macron(A)$:
$
"Odds" A :&= I(A) - I(macron(A)) \
&= log Pr[A] / (1 - Pr[A]).
$
== Shannon entropy
#note(
title: [Boltzmann distribution],
)[
maximizes thermodynamic probability $W$ and provides the *probability for each state*, so
the Boltzmann formula defines a *probability distribution*:
$ n_i / N = e^(-beta E_i) / (sum_i e^(-beta E_i)). $
Shannon's information entropy can be applied to this probability distribution:
$ p_i := e^(-beta E_i) / Z, quad Z := sum_i e^(-beta E_i), $
$ H &= sum_i p_i dot ln p_i \
&= sum_i e^(-beta E_i) / Z dot (-beta E_i - ln Z) \
&= - beta sum_i ub(e^(-beta E_i) / Z, p_i) dot E_i - ln Z dot ub(sum_i e^(-beta E_i)/Z, =1) \
&= - beta bra E ket - ln Z $
As a result, we get statistical entropy expressed via the partition function:
$ S_"stat" = k_B dot H $
The amount of information needed to encode the probability distribution by energy levels
can be calculated via Shannon's formula. This amount of information directly corresponds
to the statistical thermodynamic entropy with $k_B$ units, which translates bits into
energy per temperature units.
]
=== Information associated with a probability distribution.
Information corresponds to the amount of uncertainty: the more uncertain (less probable)
an outcome is, the more information it carries.
As for a single outcome $omega in Omega$, we can define the information associated with
the probability distribution ${ Pr[omega] | omega in Omega }$. Let it be the expected
value of the self-information:
$
H[Pr, Omega] :&= sum_(omega in Omega) Pr[omega] dot I(omega) \
&= sum_(omega in Omega) Pr[omega] dot log_2 1 / Pr[omega].
$
This quantity is known as the Shannon entropy, it can be interpreted as the average amount
of information produced by the probability distribution.
As a random variable $X$ induces its own probability distribution ${ Pr[X = x] | x in supp(X) }$,
the entropy can be defined specifically for the random variable:
$
H(X) :&= sum_(x in supp(X)) Pr[X = x] dot I(X = x) \
&= sum_(x in supp(X)) Pr[X = x] dot log_2 1 / Pr[X = x],
$
which is equivalent to the distribution of the events ${ [X = x] | x in supp(X)}$.
=== Practical interpretation.
#note(
title: [Fair dice],
)[
induces the uniform distribution over the set of possible outcomes $p_1 = ... = p_6 = 1/6$.
We need exactly $I = log_2 6 approx 2.58$ bits to encode each outcome. All outcomes are
equally probable, so we need the same $I$ bits of information to encode any outcome on
average.
On the other hand, when we roll a fair dice, we receive $log_2 6$ bits of information from
any outcome, and on average we receive the _entropy_ $H$ amount of information:
$ H = sum_(i = 1)^6 1/6 dot log_2 1/6 = log_2 1/6 approx 2.58 "bits". $
]
== Conditional entropy
Entropy $H$ can be generalized to the conditional case. Suppose that we have random
variables $X$ and $Y$, with their (marginal) distributions $Pr[X = x]$ and $Pr[Y = y]$ and
their joint distribution
$Pr[X = x, Y = y]$.
=== Specific conditional entropy
can be trivially defined by replacing the probability $Pr[X = x]$ with the conditional
probability $Pr[X = x|Y = y]$:
$
H(X|Y = y) :&= sum_(x in supp X) Pr[X = x|Y = y] dot log 1 / Pr[X = x|Y = y].
$
=== Conditional entropy
(non specific) is can be defined as the expected value of the specific conditional entropy
over all possible values of $y in supp Y$:
$
H(X|Y) :&= Ex_Y [H(X|Y = y)] \
&= sum_(y in supp Y) Pr[Y = y] dot H(X|Y = y)
$
|
|
https://github.com/Walfisch115/thb-typst-template | https://raw.githubusercontent.com/Walfisch115/thb-typst-template/main/thesis/conf.typ | typst | #let conf(
title: none,
author: none,
matrikelNumber: none,
supervisor: none,
secondReviewer: none,
place: none,
date: datetime.today().display(),
abstract: [],
doc
) = {
// GENERAL SETTINGS
set page(paper: "a4", numbering: "1", number-align: right)
set text(lang: "de")
set text(size: 12pt)
set par(justify: true)
// show outlines in table of contents
show outline: set heading(outlined: true)
// STYLING
// increase font size for headings
show heading.where(level: 1): set text(size: 18pt)
show heading.where(level: 2): set text(size: 16pt)
show heading.where(level: 3): set text(size: 14pt)
// insert pagebreak before level 1 heading
show heading.where(level: 1): it => {
pagebreak(weak: true)
it
}
// increase spacing between headings
show heading: it => {
v(2.5em, weak: true)
it
v(1.5em, weak: true)
}
// increase padding after figure
show figure: it => {
v(1.5em, weak: true)
it
v(1.5em, weak: true)
}
// style outline
set outline(indent: auto, fill: repeat(" ."))
// only apply styling if we are in the table of contents
// (not list of figures or list of tables, etc.)
show outline.entry: it => {
if it.element.func() == heading {
if it.level == 1 {
v(1.5em, weak: true)
strong(it)
} else {
it
}
} else {
it
}
}
// COVER PAGE
{
// remove page number
set page(numbering: none)
image("THB_Logo.svg", width: 7cm)
v(5em)
align(center)[
#text(size: 16pt)[
*#title*
]
#v(3em)
*Master-/Bachelorarbeit*
zur Erlangung des Grades Master/Bachelor of XXX \
des Fachbereichs Informatik und Medien der \
Technischen Hochschule Brandenburg
#v(3em)
vorgelegt von: \
#author
#v(1em)
Matrikelnummer: \
#matrikelNumber
#v(5em)
Betreuer: #supervisor \
Zweitgutachter: #secondReviewer
#v(3em)
#place, #date
]
}
// STATEMENT OF AUTHORSHIP
{
// remove page number
set page(numbering: none)
heading("Selbstständigkeitserklärung", outlined: false)
[
Hiermit versichere ich, dass ich die vorliegende Arbeit selbstständig verfasst und keine anderen als die angegebenen Quellen oder Hilfsmittel benutzt habe und dass die Arbeit in gleicher oder ähnlicher Form noch keiner anderen Prüfungsbehörde vorgelegt wurde.
]
v(3em)
grid(
columns: (1fr, 1fr),
// maybe replace the signature with an image
[#place, #date],[#author]
)
}
// TABLE OF CONTENTS AND ABSTRACT
{
set page(numbering: "I")
// dont show outline in table of contents
show outline: set heading(outlined: false)
// update page number
counter(page).update(1)
// ABSTRACT
// show abstract if not empty
if abstract != [] {
heading("Abstract")
abstract
}
// TABLE OF CONTENTS
outline()
}
// DOCUMENT CONTENT
{
set heading(numbering: "1.")
// update page number
counter(page).update(1)
doc
}
// TABLE OF FIGURES
let minEntries = 0
// show if more than x entries
context if query(figure.where(kind: image)).filter(f => f.caption != none).len() > minEntries {
outline(
title: [Abbildungsverzeichnis],
target: figure.where(kind: image)
)
}
// TABLE OF TABLES
// show if more than x entries
context if query(figure.where(kind: table)).filter(f => f.caption != none).len() > minEntries {
outline(
title: [Tabellenverzeichnis],
target: figure.where(kind: table),
)
}
// BIBLIOGRAPHY
// include, if existing
// bibliography()
} |
|
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/06-field-theory/04-decomposition-field.typ | typst | Other | #import "../../utils/core.typ": *
== Поля разложения
#ticket[Поле разложения многочлена. Примеры]
#def[
Пусть $f in K[x]$. Расширение $L fg K$ называется полем разложения $f$ над $K$, если
+ $f$ раскладывается в $L[x]$ на линейные множители
+ $L = K(a_1, ..., a_n)$, где $a_1, ..., a_n$ --- корни $f$ в $L$.
]
#example[
+ $CC fg RR$ --- поле разложения $x^2 + 1$
+ $QQ(root(4, 2))$ --- *не* поле разложения $x^4 - 2$ над $QQ$
+ $QQ(root(4, 2), i)$ --- поле разложения $x^4 - 2$
]
#pr[
Пусть $f in K[x]$. Тогда существует поле разложения $f$ над $K$.
]
#proof[
Индукция по $d = deg f$
"База": $d = 1 ==> K$ --- поле разложения $f$
"Переход": $d > 1 ==> exists g divides f, space g$ --- неприводим. $L = K(a), space Irr a = g$. В $L$ $g(a) = 0 ==> f(a) = 0 ==> f = (f - a)f_1$. \
Степень $f_1 = d-1 ==> exists M fg L$, где $M$ --- поле разложения $f_1$. Тогда заметим, что $M fg K$ --- поле разложения $f$.
Пусть $a_2, ..., a_c$ --- все корни $f_1$ в $M$
$
cases(M = L(a_2, ..., a_c), L = K(a)) ==> M = K(a_1, a_2, ..., a_c)
$
]
#notice[
Поле разложения единственно с точностью до изоморфизма.
]
#proof[
Без доказательства.
]
#pr[
Пусть $L fg K$ --- расширение. Тогда два условия эквивалентны:
+ $L fg K$ --- конечно.
+ $L = K(a_1, ..., a_n)$, $a_1, ..., a_n$ --- алгебраичны над $K$
]
#proof[
- "$1 ==> 2$": $a_1, ..., a_n$ --- базис $L$ над $K$. Тогда $K(a_1, ..., a_n) = L$.
- "$2 ==> 1$": Индукция по $n$:
Пусть мы знаем, что $[L' : K] < oo$, где $L' = K(a_1, ..., a_(n-1))$. Заметим, что $L = L'(a_n)$, $a_n$ --- алгебраичен над $K ==> a_n$ алгебраичен над $L'$. Поэтому $[L : K] = [L : L'] dot [L' : K] < oo$.
]
#follow[
Пусть $L fg K$ --- любое расширение, $a, b in L$, $a, b$ --- алгебраичны над $K$. Тогда
$ a+b, a b $ --- алгебраичны над $K$.
]
#proof[
Присоединим и $a$, и $b$. Это расширение конечно, значит алгебраично. И $a + b$, и $a b$ там лежат, поэтому они алгебраичны.
]
|
https://github.com/GartmannPit/Praxisprojekt-II | https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/README.typ | typst | #set text(
font: "Linux Libertine",
size: 12pt
)
#set par(justify: true, leading: 1em)
#set heading(numbering: none)
#show figure: set text(size: 0.85em)
= README for Typst Template following the BHH style guide
\
This readme is about the technical specifications and information about the project and less about its intentions. The last part in short firstly: If you have a compile error: check if you commented the table and/ or images list in _paper.typ_ in case you have no image and/ or table.
\
=== General folder structure of the template: \
\- bib\
#h(1cm) \- example.yml\
#h(1cm) \- bib.yml\
\- figures\
#h(1cm) \- test.png\
\- README\
#h(1cm) \- README.md\
#h(1cm) \- README.typ\
\- template\
#h(1cm) \- acronymsList.typ\
#h(1cm) \- bib.typ\
#h(1cm) \- conf.typ\
#h(1cm) \- contents.typ\
#h(1cm) \- cover.typ\
#h(1cm) \- figuresList.typ\
#h(1cm) \- tablesList.typ\
\- abstract.typ\
\- acronyms.typ\
\- appendix.typ\
\- main.typ\
\- paper.typ\
\
=== The most important folders
==== Bibliography <bib>
The *bib* folder stores the _.yml_ and _.bib_ files, where books and other sources are stored. They follow either the LaTeX bib style or the #link("https://github.com/typst/hayagriva", )[#underline[#text(fill: blue)[Typst own yml-format]]]. To reduce confusion use this, though of course you can add paths to any file you want. The empty _bib.yml_ file is already added to the document and is ready to take your sources in the style of the _example.yml_ file. When you don't refer to a source it's normally not shown so you could even leave the _example.yml_ file there and don't need to touch the _bib.typ_ file.
==== Figures
The *figures* folder stores the images and figures you want to add to reduce confusion about paths. Valid file types are _.jpg_, _.png_, _.gif_, and _.svg_.
==== Template data
The *template* folder stores all the _.typ_ files you need to setup an essay. You only need to touch those files if any default configuration doesn't work for you. The files in there auto-generate your list of acronyms with data you provide (in the _acronyms.typ_-file at root level), your bibliography, your table of contents, your cover page (with data you submit in the _paper.typ_), your list of figures, and your list of tables. Furthermore, the basic configuration of the page and text design is stored there.
=== The files on root level and their meaning
==== _abstract.typ_
The abstract is stored and edited in _abstract.typ_ to do so, follow the example in the file and stay within the function. Everything outside of the function will not be shown.
==== _acronyms.typ_
All the acronyms you want to have in the list of acronyms are created in _acronyms.typ_. To make the design nearly following the style guide, you need to add ```typ
#h(1fr)
``` to every explanation as shown in the examples. Might get updated soon though.
==== _appendix.typ_
As the name indicates, in _appendix.typ_ is all your text and data for the appendix stored. You can add text within the function, excatly like the abtsract in _abstract.typ_
==== _main.typ_
Your main part will be written in _main.typ_. If you wish you could also write the chapters in chapter files and add them together either in _main.typ_ or directly in _paper.typ_. Within _main.typ_ you do NOT need to set any design specific properties including headline or page definitions. Here it's solely about the content of your work. Below will be some tips about how to include figures/ pictures, tables, and cites as well as some inormation about what to do when a typst compile fails and what known errors are regarding problems of templates. Please read the chapter *#link(<TypstBasics>)[Typst Basics]* carefully.
==== _paper.typ_
_paper.typ_ is the "main" file of the document: if you want to see the whole document, you need to compile _paper.typ_ to a _.pdf_. Additionally, you set some personal properties in _paper.typ_, including:
- metadata for the _.pdf_-document:
- author: your name as string
- title: title as string
- data for the cover page:
- title: title as content or string
- univerity: university as content or string
- additionalInfo: as content or string, default: "Ausarbeitung im Rahmen des Seminars"
- seminar: seminar as content or string
- study: your study as content or string
- semester: the current semester as content or string
- examiner: your examiner as content or string
- author: author as content or string
- dateofBirth: your date of birth as content or string
- semesterCount: your total amount of semesters as content or string
- matriculationNumber: your matriculation number as content or string
- address: your address as content in the form [_street_ \\ _city_]
- email: your email as string
- date: date of submission as string
- cooperation: company of cooperation as content or string
\
Furthermore, you can remove some list/ indices here, in case you don't need them, refer to *#link(<TypstBasics>)[Typst Basics]* for more information.
\
\
#align(center)[*Basically: do NOT touch the files within the TEMPLATE folder, do NOT touch any fields starting with an _\#_ unless you only provide data while being asked via comments to do so within the _paper.typ_ file. Try to avoid using _\#_ unless you use it with _figures_, _par_ or _align_ if you are not sure about what you're doing. In all cases of lacking knowledge, see the chapter below* \ If you are an expirienced user, feel free to adjust the document to your liking, maybe open a branch for it, to allow other users the access to your version of this template? ]
\
\
= Typst Basics <TypstBasics>
== General Help
See the #link("https://typst.app/docs/reference/", )[#underline[#text(fill: blue)[official documentation of typst]]] for any guidiance regarding Typst itself. The following guide will provide some basic information with detailed code examples to make the life easier.
== Writing some text
Since the style setup is already done with this template, you don't need to worry anything design related. Something you might have to do is alignment in case you need something special. The normal text is (if nothing special is stated) written using the _Times New Roman_ font in the size _12pt_ and _justified_ with a leading of _1.5em_.
To structure your text, you can add headlines with *=* in front of the line (similiar to typical mark-down), where ```typ
= heading
== subheading
=== 3rd heading
``` and so on.\
Now you have some organized plain text...\
Just like in markdown you can make text *bold* or _italics_ or #underline()[underlined]:
```typ
*bold*
_italics_
#underline()[underlined]
```\
Just to have it noted here, the alignment is setup via the _\#align_ command:
```typ
#align(center)[centered text]
```\
To use the *\#* as text character and not as an command prefix, you can escape it, like any other functional key, with an backslash *\\*.
To add a line break either write '\#linebreak()' or just use the backslash.
Another nice function is the easy nesting: everything written within Typst Content (the squared bracktes []) is another "pure Typst instance": there you can call functions with the hashtag like before:
```typ
#par[
Let's create a paragraph with an
#underline()[
underlined part and a
#text(fill: red)[
red word
]
]
]
``` The outcome looks like this:
#par[Let's create a paragraph with an #underline()[underlined part and a #text(fill: red)[red word]]]
Maybe center it additionally?
```typ
#align(center)[
#par[
Let's create a paragraph with an
#underline()[
underlined part and a
#text(fill: red)[
red word
]
]
]
]
```
#align(center)[#par[Let's create a paragraph with an #underline()[underlined part and a #text(fill: red)[red word]]]]
But the red part shouldn't be underlined...
```typ
#align(center)[
#par[
Let's create a paragraph with an
#underline()[
underlined part and a
]
#text(fill: red)[
red word
]
]
]
```
#align(center)[#par[Let's create a paragraph with an #underline()[underlined part and a] #text(fill: red)[red word]]]
\
== Adding images
Since pure text is most of the time a little boring to read, you can add some images easily. Just have them in a normal image file type (jpg, png, gif or svg) and for easy use, place them with a nice file name in the _figures_ folder.
If you reach the point in (for exmaple _main.typ_) where you want to add the image, setup a figure and then add the image like this:
```typ
#figure(
image("figures/yourImage.png", width: 70%, alt: "give your image a nice alt text"),
caption: "and a nice caption"
)<AddANiceTag>
```
About the used parameters:
- image: image initialization
- path: mandatory, string path to file starting at document (not necessarily root!)
- width: optional, sets the width of the image (relational to page), height possible too, for more option refer to the Typst documentation
- alt: alternative text, string describing the image
- caption: figure caption, only "titling" here, numbering is added automatically with it being a figure!
- <>: a tag allows you to place a reference within the text towards a specific item. For figures they're shown as the auto-generated part of the caption (in a German text'd be "Abbildung X") where X is automatically assigned with the upcoming number in the document. They're auto-counted in order of appearance. References will be looked at a little later.
Please refrain from using '\#image(...)' without figure, since only figures - images are added to the list of figures, additionally captions are only easily available for figures.\ \
Maybe nest the figure into centering to make it look cleaner depening on your taste:
```typ
#align(center)[
#figure(
image("figures/yourImage.png", width: 70%, alt: "give your image a nice alt text"),
caption: "and a nice caption"
)<AddANiceTag>
]
```That would create (with usage of the _/figures/test.png_ image) following output:
#align(center)[
#figure(
image("figures/test.png", width: 70%, alt: "give your image a nice alt text"),
caption: "and a nice caption"
)<AddANiceTag>
]
\
=== Text wrapping around images (or any other figure)
Text wrapping isn't implemented yet though it's in planning according to the development team of Typst.
To wrap text manually, you can use the grid function: just be aware, you need to classify, which words are belonging into the grid and which not, manually. In case of adding some more lines above the image/ grid may break the whole design. But after the warning: here a code example on how to do it:
```typ
#grid(columns: 2, gutter: 1em,
[
#figure(
image("figures/test.png", width: 25%, alt: "test-image: line-drawn human"),
caption: [Demonstration of wrapping]
)<WrappedImage>
],
[
#lorem(40)
]
#lorem(50) // some after grid text to demonstrate the wrapping effect
)
``` The result with the test image (note this part will break after deleting the _test.png_ in the _figures_ folder):
#grid(columns: 2, gutter: 1em,
[
#figure(
image("figures/test.png", width: 25%, alt: "test-image: line-drawn human"),
caption: [Demonstration of wrapping]
)<WrappedImage>
],
[
#lorem(40)
]
)
#lorem(50)
\
== Tables
Sometimes you need some tables to show (scientific) data: to do so you can create a table within a figure. Here again, like with the images, don't forget to nest it within a figure to get an auto created entry in the list of tables as well as the caption feature:
```typ
#figure(
table(columns: 2, [1], [2], [3], [4]),
caption: "Demonstration"
)<TableWithTag>
``` This will return following table:
#figure(
table(columns: 2, [1], [2], [3], [4]),
caption: "Demonstration"
)<TableWithTag>
Let's add some funny designs:
```typ
#figure(
table(columns: (1fr, 2fr), inset: 10pt,
align: horizon,
[*Header 1*], [*Header 2*],
[1], [2],
[3], [4],
[5]),
caption: "Some more Design"
)<DesignATable>
``` And the outcome:
#figure(
table(columns: (1fr, 2fr), inset: 10pt,
align: horizon,
[*Header 1*], [*Header 2*],
[1], [2],
[3], [4],
[5]),
caption: "Some more Design"
)<DesignATable>
== Citing and other references
To cite something, you need to add the books/ articles/ websites/ whatever you want to cite, to the bibliography... easiest way is to put them in the according format into the bib.yml file or create a new one and integrate it in the bib.typ file in the template folder. See #link(<bib>)[Bibliography] for more information.
After having all your sources present you can cite them with an *\@* and then the tag (name of the entry of an _.yml_ element). Furthermore, you can add some more supplements, e.g. supplying a page number:
```typ
some smart statement @SmartBook[p. 6]
```
This would automatically insert the reference data according to the chosen cite style (e.g. "apa" or "ieee") and add the supplement provided.
Examples can be found in the _main.typ_ where the bibliography is embedded.
Additionally, you can reference towards a figure having a tag. Let's link an image and a table from a few chapters above:
```typ
Some text, see @WrappedImage \
And some more text, see @DesignATable
```
That's the output:\
Some text, see @WrappedImage \
And some more text, see @DesignATable
= An important note
PLEASE CHECK YOUR STYLE GUIDE, there might be some mistakes, feel free to open an issue, so we can fix that.
And last but definitly not least: you'll run into a compile error when you leave outlines of figures in, even though you haven't a figure of that respective kind in:\
when you don't have any table in, you need delete or comment the part about list of tables in the _paper.typ_
same goes for the list of images
==== Some outlines
#outline()
\
#outline(
target: figure.where(kind: image)
)
\
#outline(
target: figure.where(kind: table)
) |
|
https://github.com/0x6e66/hbrs-typst | https://raw.githubusercontent.com/0x6e66/hbrs-typst/main/ads/abstract.typ | typst | #import "../template/utils.typ": *
#let abstract = {
let abstract_de = {
lorem(200)
}
let abstract_en = {
lorem(200)
}
abstract("de", abstract_de)
abstract("en", abstract_en)
} |
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/16_Linux操作系统.typ | typst | #import "../template.typ": *
#pagebreak()
= Linux 操作系统
== Linux 操作系统
_25 Aug 1991, The Birthday of Linux > Hello, everybody out there using minix – I’m doing a (free) operating system (just a hobby, won’t be big and professional like gnu) for 386(486) AT clones. This has been brewing since April, and is starting to get ready. > —— <NAME> (时年 21 岁)_
类似于 “我写了一个加强版的操作系统实验, 现在与大家分享”
- 发布在 comp.os.minix
- 因为还依赖 Minix 的工具链 (从零开始做东西是不现实的)
- 跑的都是 GNU 的程序: gcc, bash, ...
- 从此改变世界
- “Just for fun: the story of an accidental revolutionary”
=== Minix?
- Minix: 完全用于教学的真实操作系统
- by <NAME>
年轻人的第一个 “全功能” 操作系统
- Minix1 (1987): UNIXv7 兼容
- Linus 实现 Linux 的起点
- #link("http://download.minix3.org/previous-versions/Intel-2.0.4/")[ Minix2 ] (1997):
POSIX 兼容
- 更加完备的系统, 书后附全部内核代码
- #link("http://minix3.org/")[ Minix3 ] (2006): POSIX/NetBSD 兼容
- 一度是世界上应用最广的操作系统
- Intel ME 人手一个
=== Tanenbaum/Linus "Linux is Obsolete" Debate
在 comp.os.minix 上关于 Linux 的讨论越来越多了
- <NAME> 做出了 “官方回应”
- 觉得 “太落后”
- Linus 完全不服气
- #link("https://www.oreilly.com/openbook/opensources/book/appa.html")[ 全文 ]
- <NAME> 也参与了讨论
- 他已经在 ~10 年前获得了图灵奖……
=== 后来大家知道的故事
#image("images/2023-11-26-09-12-18.png")
- Linux 2.0 引入多处理器 (Big Kernel Lock, 内核不能并行)
- Linux 2.4 内核并行
- 2002 年才引入 Read-Copy-Update (RCU) 无锁同步
- 2003 年 Linux 2.6 发布, 随云计算开始起飞
=== Linux 的 “两面”
Kernel(一个可执行的二进制序列, 由硬件厂商加载到内存)
- 加载第一个进程
- 相当于在操作系统中 “放置一个位于初始状态的状态机”
- Single user model (高权限)
- 包含一些进程可操纵的操作系统对象
- 例如`/dev/console`, 然后调试信息就会打印到控制台上 > linux 启动的时候,
某一个时刻, 字体变了. 实际上就是在启动过程中, 对终端做了一些配置.
- 除此之外 “什么也没有”
- Linux 变为一个中断 (系统调用) 处理程序
Linux Kernel 系统调用上的发行版和应用生态
- 系统工具 #link("https://www.gnu.org/software/coreutils/coreutils.html")[ coreutils ], [
binutils ](https://www.gnu.org/software/binutils/), [ systemd
](https://systemd.io/), ... > systemd 才是进程树的根, 但是实际上系统的第一个进程`init`,
并不是`systemd`, 为啥? 后面解答.
- 桌面系统 Gnome, xfce, Android
- 应用程序 file manager, vscode, ...
== 构建最小 Linux 系统
#image("images/2023-12-05-20-10-11.png")
=== 一个想法
我们能不能控制 Linux Kernel 加载的 “第一个状态机”?
- 计算机系统没有魔法
- 你能想到的事就能实现
挑战 ChatGPT:
- 我希望用 QEMU 在给定的 Linux 内核完成初始化后, 直接执行我自己编写的、静态链接的
init 二进制文件. 我应该怎么做?
我们的真正壁垒
- 怎样问出好问题
- 怎样回答问出的问题
完全可以构建一个 “只有一个文件” 的 Linux 系统——Linux 系统会首先加载一个 “init
RAM Disk” 或 “init RAM FS”,在作系统最小初始化完成后,将控制权移交给
“第一个进程”。借助互联网或人工智能,你能够找到正确的文档,例如 The kernel’s
command-line parameters 描述了所有能传递给 Linux Kernel 的命令行选项。
恰恰是 UNIX “干净” 的设计 (完成初始化后将控制权移交给第一个进程) 使得 Linus
可以在可控的工程代价下实现 (相当完善的) POSIX
兼容,从而掀起一场操作系统的革命。时至今日,实现接口级的兼容已经是一件极为困难的工程问题,典型的例子是微软的工程师最终抛弃了
API 行为兼容的 Windows Subsystem for Linux 1.0,进而转向了虚拟机上运行的 Linux
内核。
> wsl1 的实现是使用 windows 自己的 api, 将 linux 内核的 api
解释执行(转义式的模拟). 行不通的, 操作系统的对象很复杂, 有很多历史包袱例如`man proc`可以看到很多很多的
specification, 只有完全实现这些, 才能正确地模拟.
为什么现在要做一个操作系统很难? 要么兼容 linux(但是很复杂),
不兼容的话生态又跟不上.
=== 启动 Linux
熟悉的 QEMU, 稍稍有些不熟悉的命令行选项
```makefile
= Requires statically linked busybox
INIT := /init
initramfs:
= Copy kernel and busybox from the host system
@mkdir -p build/initramfs/bin
sudo bash -c "cp /boot/vmlinuz build/ && chmod 666 build/vmlinuz"
cp init build/initramfs/
cp $(shell which busybox) build/initramfs/bin/
= Pack build/initramfs as gzipped cpio archive
cd build/initramfs && \
find . -print0 \
| cpio --null -ov --format=newc \
| gzip -9 > ../initramfs.cpio.gz
run:
= Run QEMU with the installed kernel and generated initramfs
qemu-system-x86_64 \
-serial mon:stdio \
-kernel build/vmlinuz \
-initrd build/initramfs.cpio.gz \
-machine accel=kvm:tcg \
-append "console=ttyS0 quiet rdinit=$(INIT)"
clean:
rm -rf build
.PHONY: initramfs run clean
```
1. `qemu-system-x86_64`: 这是 QEMU 的可执行程序,针对 x86_64(即 64 位 Intel 和 AMD
处理器)架构的系统。
2. `-serial mon:stdio`:
这个选项将虚拟机的串行端口输出重定向到当前的标准输入输出设备。`mon:stdio` 表示监控器(QEMU
的交互式命令行界面)通过标准 I/O 设备进行交互。
3. `-kernel build/vmlinuz`: 指定虚拟机使用的内核映像文件。在这里,`build/vmlinuz` 是内核映像文件的路径。
4. `-initrd build/initramfs.cpio.gz`: 指定初始化 RAM 磁盘的文件,即 initrd。`build/initramfs.cpio.gz` 是
initrd
文件的路径,它通常包含了启动操作系统所需的最小系统,并在根文件系统挂载之前被加载。
5. `-machine accel=kvm:tcg`: 这个选项指定虚拟机使用的加速技术。`accel=kvm` 表示如果可用,应使用基于内核的虚拟机(KVM)进行硬件加速。如果
KVM 不可用,将回退到 TCG(Tiny Code Generator),后者是 QEMU 的纯软件模拟。
6. `-append "console=ttyS0 quiet rdinit=$(INIT)"`:
这个选项用于向内核传递命令行参数。`console=ttyS0` 告诉内核将控制台输出重定向到第一个串行端口(ttyS0)。`quiet` 参数减少了启动时的日志输出,使得输出更加简洁。`rdinit=$(INIT)` 设置了
init 程序的路径,这里使用了 shell 变量 `$(INIT)`,它需要在执行 QEMU
命令之前定义。
==== minimal 作为 init
```sh
❯ gcc -c minimal.S && ld minimal.o
❯ mv a.out minimal
❯ ls
build init Makefile minimal minimal.o minimal.S
❯ ./minimal
Hello, OS World
❯ mv minimal build/initramfs
```
然后我们可以把上面 Makefile 里面的 init 换成 minimal
`INIT := /minimal`
`minimal`运行之后销毁, 就没有进程了, 会发生什么?
```
[ 0.884772] Run /minimal as init process
Hello, OS World
[ 0.900809] Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000100
[ 0.901147] CPU: 0 PID: 1 Comm: minimal Not tainted 5.17.3 #1
[ 0.901463] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014
[ 0.901753] Call Trace:
[ 0.902268] <TASK>
[ 0.903735] dump_stack_lvl+0x34/0x44
[ 0.904016] panic+0xef/0x2a6
[ 0.904106] do_exit.cold+0x15/0x45
[ 0.904217] __x64_sys_exit+0x12/0x20
[ 0.904312] do_syscall_64+0x3b/0x90
[ 0.904396] entry_SYSCALL_64_after_hwframe+0x44/0xae
[ 0.904767] RIP: 0033:0x40102e
[ 0.905134] Code: 00 00 00 48 c7 c7 01 00 00 00 48 c7 c6 2e 10 40 00 48 c7 c2 1c 00 00 00 0f 05 4
8 c7 c0 3c 00 00 00 48 c7 c7 01 00 00 00 0f 05 <1b> 5b 30 31 3b 33 31 6d 48 65 6c 6c 6f 2c 20 4f 53
20 57 6f 72 6c
[ 0.905637] RSP: 002b:00007ffd1dff82b0 EFLAGS: 00000202 ORIG_RAX: 000000000000003c
[ 0.905999] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 000000000040102e
[ 0.906218] RDX: 000000000000001c RSI: 000000000040102e RDI: 0000000000000001
[ 0.906446] RBP: 0000000000000000 R08: 0000000000000000 R09: 0000000000000000
[ 0.906599] R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000000
[ 0.906870] R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
[ 0.907165] </TASK>
[ 0.907618] Kernel Offset: 0x2a400000 from 0xffffffff81000000 (relocation range: 0xffffffff800000
00-0xffffffffbfffffff)
[ 0.908150] ---[ end Kernel panic - not syncing: Attempted to kill init! exitcode=0x00000100 ]---
```
给出 panic, 并且打印调用栈以及寄存器信息.
==== busybox
本质上和 minimal 没啥区别, 就是一个静态链接的二进制文件.
```sh
❯ file $(which busybox)
/usr/bin/busybox: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=36c64fc4707a00db11657009501f026401385933, for GNU/Linux 3.2.0, stripped
```
用法:
```sh
❯ busybox ls
Makefile build init minimal minimal.S minimal.o vmlinuz
❯ busybox sh
BusyBox v1.30.1 (Ubuntu 1:1.30.1-7ubuntu3) built-in shell (ash)
Enter 'help' for a list of built-in commands.
~/cs_learning/nju_os/demo/16_demo/linux $ exit
```
busybox 就是一个 unix 常用工具的打包.
> toybox 比 busybox 更小.
可以看看 busybox 的代码, 可以看到一些系统工具的简化实现. 从中能学到不少技巧.
多读源码!
==== `init`
```sh
#!/bin/busybox sh
= initrd, only busybox and /init
BB=/bin/busybox
= (1) Print something and exit
= $BB echo -e "\033[31mHello, OS World\033[0m"
= $BB poweroff -f
= (2) Run a shell on the init console
$BB sh
= (3) Rock'n Roll!
for cmd in $($BB --list); do
$BB ln -s $BB /bin/$cmd
done
mkdir -p /tmp
mkdir -p /proc && mount -t proc none /proc
mkdir -p /sys && mount -t sysfs none /sys
mknod /dev/tty c 4 1
setsid /bin/sh /dev/tty 2>&1
```
`make && make run`之后得到一个就可以运行 busybox 里的 shell.
```
/ = /bin/busybox find /
/
/init
/bin
/bin/busybox
/root
/dev
/dev/console
```
如何把终端移动到真正的 qemu 的机器里面呢? 先终止原终端里面 busybox 的 sh.
接着就会执行后面的"Rock'n Roll"...最后的 setsid 就可以在机器上启动终端.
==== `cpio`
`cpio` 是一个标准的 Unix
工具,用于创建、提取和管理归档文件。归档文件是将多个文件或目录合并成单个文件的一种方式,这在备份和分发文件时非常有用。`cpio` 支持多种归档格式,包括它自己的格式以及
tar 格式。
`cpio` 的名称来源于“copy in and copy
out”的缩写,其设计用于将文件从一个位置复制到另一个位置,可以通过管道与其他命令结合使用,特别是与`find`命令一起用来选择要归档的文件。
在 Makefile 上下文中,`cpio` 用于创建一个新的 initramfs 映像。initramfs(初始
RAM
文件系统)是一个临时的根文件系统,由内核在引导过程中挂载,用于预加载必要的驱动程序和其他资源,直到实际的根文件系统被挂载。
以下是`cpio` 命令的一个例子,该命令通常与 `find` 命令一起用于创建 initramfs:
```bash
find . -print0 | cpio --null -ov --format=newc | gzip -9 > initramfs.cpio.gz
```
这个命令执行的操作如下:
- `find . -print0`:查找当前目录(`.`)下的所有文件和目录,并以空字符(null)终止每个条目,这样即使文件名中包含空格或换行符,`cpio` 也能正确处理。
- `cpio --null -ov --format=newc`:`cpio` 读取来自 `find` 命令的输入,`--null` 表示输入的文件名以空字符终止,`-o` 表示创建归档(copy
out),`-v` 表示详细模式,`--format=newc` 指定了新的 SVR4(System V Release
4)cpio 格式。
- `gzip -9`:将 `cpio` 创建的归档压缩为 gzip 格式,`-9` 表示最大压缩率。
- `> initramfs.cpio.gz`:将压缩后的数据重定向到文件 `initramfs.cpio.gz`。
创建完成后,`initramfs.cpio.gz` 就可以被内核在启动时作为 initramfs 使用。
==== initramfs
Initramfs(initial RAM filesystem)是一个在 Linux
系统启动时由内核加载的临时根文件系统。它被存储在内存中,并在系统启动过程的早期阶段被用来准备真正的根文件系统,比如执行硬件检测、加载必要的驱动程序和其他预启动任务。一旦这些任务完成,内核就会切换到真正的根文件系统上,通常是位于硬盘或者其他永久存储设备上。
===== 为什么需要 Initramfs?
在现代 Linux
系统中,许多硬件驱动和文件系统支持都是以模块的形式存在的,这意味着它们不是内核的一部分,而是在需要时加载。在某些情况下,根文件系统可能位于需要这些模块才能访问的设备上。因此,系统启动时需要一个预先加载这些模块的机制,以便内核能够访问并挂载真正的根文件系统。
===== Initramfs 的内容
Initramfs 通常包含以下内容:
- *必要的可执行程序和库*:这些通常包括用于挂载真正的根文件系统的工具,比如`mount`命令。
- *模块*:如果内核需要额外的模块来访问根文件系统(例如,特定的文件系统或 RAID
控制器驱动),这些模块可以包含在 initramfs 中。
- *初始化脚本*:一个名为`init`的脚本负责协调启动流程,包括加载驱动程序、挂载真正的根文件系统等。
=== 创建和使用 Initramfs
在 Linux 系统中,initramfs 通常是使用`cpio`归档格式创建的,然后被 gzip
压缩。内核在启动时会解压缩并加载 initramfs 到内存中。
创建 initramfs
的过程通常由发行版的构建脚本自动完成,但也可以手动创建。一旦创建了
initramfs,它可以通过引导加载器(如 GRUB)的配置传递给内核。例如,GRUB
配置文件中的一个条目可能包含以下行:
```plaintext
linux /boot/vmlinuz-linux root=/dev/sda1
initrd /boot/initramfs-linux.img
```
这里的`initrd`指令告诉 GRUB 加载`/boot/initramfs-linux.img`作为 initramfs。
===== 切换到真正的根文件系统
启动过程中,initramfs 的`init`脚本会执行必要的步骤来准备真正的根文件系统。这包括加载任何必要的驱动程序、设置网络(如果需要)以及挂载根文件系统。一旦根文件系统被挂载,initramfs
中的 init 脚本会用`exec`命令替换自己为根文件系统上的`/sbin/init`程序(或者任何指定的
init 系统),这个程序接下来将接管系统的其余启动过程。
在切换到真正的根文件系统之后,initramfs
所占用的内存通常会被释放,因为它在系统运行时不再需要。这个过程称为“切换根”(switch_root)。
== initrd 之后
=== initrd: 并不是我们实际看到的 Linux
只是一个内存里的小文件系统
- 我们 “看到” 的都是被 init 创造出来的
- 加载剩余必要的驱动程序, 例如网卡
- 根据 fstab 中的信息挂载文件系统, 例如网络驱动器
- 将根文件系统和控制权移交给另一个程序, 例如 systemd
==== Questions
1. 为什么 systemd 是 pstree 的根?
2. 在系统刚开始启动的时候, 只有一个`initramfs`在内存, 很小,
仅供系统的初始化使用.这个实话系统里面还没有磁盘, 那磁盘里的那么多工具都去哪儿了?
=== 构建一个 “真正” 的应用世界
系统的启动分为两个阶段, 在`initramfs`之后(系统的一级启动), 必须有一个应用调用`pivot_root`(系统的二级启动)
```c
int pivot_root(const char *new_root, const char *put_old);
```
`pivot_root()` changes the root mount in the mount namespace of the calling
process. More precisely, it moves the root mount to the directory put_old and
makes new_root the new root mount. The calling process must have the
CAP_SYS_ADMIN capability in the user namespace that owns the caller's mount
namespace.
- 执行 /usr/sbin (Kernel 的 init 选项)
- 看一看系统里的文件是什么吧
- 计算机系统没有魔法 (一切都有合适的解释)
#image("images/2023-12-05-20-09-17.png")
> 为啥在安装更新软件的时候, 在 initramfs 的时候会卡很久,
因为里面包含了很多系统的对象, 更新的时候要重新打包.
```sh
❯ ls -l /usr/sbin/init
lrwxrwxrwx 1 root root 20 Sep 20 00:57 /usr/sbin/init -> /lib/systemd/systemd
```
这个时候`systemd`就接管了.
=== 例子: #link("https://zhuanlan.zhihu.com/p/619237809")[ NOILinux Lite ]
在 init 时多做一些事
```sh
export PATH=/bin
busybox mknod /dev/sda b 8 0
busybox mkdir -p /newroot
busybox mount -t ext2 /dev/sda /newroot
exec busybox switch_root /newroot/ /etc/init
```
- pivot_root 之后才加载网卡驱动、配置 IP
- 这些都是 systemd 的工作
- (你会留意到 tty 字体变了)
- 之后 initramfs 就功成身退, 资源释放
|
|
https://github.com/timon-schelling/uni-phi111-essay-2023-12-01 | https://raw.githubusercontent.com/timon-schelling/uni-phi111-essay-2023-12-01/main/src/template/template.typ | typst | #let project(
title: "",
authors: (),
date: datetime.today().display(),
title-page-infos: [],
bib: "../refs.yml",
bib-urls: false,
lang: "de",
font: "Calibri",
font-size: 1.2em,
leading: 0.85em,
heading-padding: 0.4em,
numbering-skip-outline: true,
body,
) = {
// Set general document settings
set document(author: authors, title: title)
// Set text settings
set text(font: font, lang: lang, size: font-size)
set par(leading: leading)
// Set heading style
set heading(numbering: "1.1")
show heading: it => {
it
v(heading-padding)
}
// Set citation style for refs
import "cite.typ": *
show ref: it => show_custom_ref(it)
show cite.where(style: auto): it => show_custom_cite(it)
// Title pager
{
text(1.1em, date)
v(1.2em, weak: true)
text(2em, weight: 700, title)
// Authors
pad(
top: 0.7em,
right: 20%,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(start, strong(author))),
),
)
align(bottom)[#title-page-infos]
pagebreak()
}
// Enable page numbering
set page(numbering: if numbering-skip-outline { none } else { "1" })
// Table of contents
{
outline(depth: 5, indent: true)
pagebreak()
}
// Reset page numbering if necessary
set page(numbering: "1")
if numbering-skip-outline {
counter(page).update(1)
}
// Main body
{
set par(justify: true)
body
}
// Display the bibliography if any is given
if bib != none {
pagebreak()
let title = if lang == "de" { "Literatur" } else { none }
show bibliography: it => {
set heading(numbering: "1.1")
it
}
let style = if bib-urls {
"cite_styles/main.csl"
} else {
"cite_styles/main-no-urls.csl"
}
bibliography(bib, title: title, style: style)
}
}
|
|
https://github.com/HarryLuoo/sp24 | https://raw.githubusercontent.com/HarryLuoo/sp24/main/Physics311/reviewNotes/briefMechanics.typ | typst | #set page("us-letter")
#set heading(numbering: "1.1")
#show heading: text.with(size: 11pt, weight: 1000, font: "Libre Baskerville")
#set text(11pt)
#set page(margin: (x: 3cm, y: 3cm),numbering: "1/1", columns: 1, flipped: false)
#set math.equation(numbering:"1")
#show math.equation: set text(11pt)
#set math.cases(gap: 0.2em)
#text(font: "Cambria",size: 12pt,weight: "black")[Brief Mechanics\ Notes from Physics 311]\
<NAME>\
finalized on 5/7/2024
It's been a wild ride...
#line(length: 100%, stroke: (thickness: 2pt))
#outline(indent: auto)
#line(length: 100%)
//Exam notecard layout:
// #show heading: text.with(size: 6pt, weight: 990, font: "Libre Baskerville")
// #set text(5pt)
// #set page(margin: (x: 0.5cm, y: 0.5cm), columns: 4, flipped: true)
// #set math.equation(numbering:"[1")
// #show math.equation: set text(5pt)
//part1: covers lec 1 - 13, i.e. exam 1 content
#include "part1.typ"
//part2: exam 2 content
#include "part2.typ"
//part3: final content
#include "part3.typ"
//Appendix
//#pagebreak()
#include "apnd.typ" |
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/reference-grammar.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.page.with(title: [参考:语法示例检索表])
#let table-lnk(name, ref, it, scope: (:), res: none, ..args) = (
align(center + horizon, ref(name)),
it,
align(
horizon,
{
set heading(
bookmarked: false,
outlined: false,
)
eval(it.text, mode: "markup", scope: scope)
},
),
)
#let ref-table(items) = table(
columns: (120pt, 6fr, 5fr),
align(center)[「名称/术语」],
align(center)[语法],
align(center)[渲染结果],
..items.map(args => table-lnk(..args)).flatten(),
)
点击下面每行名称都可以跳转到对应章节的对应小节。
== 分类:基本元素 <grammar-table:base-elements>
#ref-table((
(
[段落],
refs.writing-markup.with(reference: <grammar-paragraph>),
```typ
writing-markup
```,
),
(
[标题],
refs.writing-markup.with(reference: <grammar-heading>),
```typ
= Heading
```,
),
(
[二级标题],
refs.writing-markup.with(reference: <grammar-heading>),
```typ
== Heading
```,
),
(
[着重标记],
refs.writing-markup.with(reference: <grammar-strong>),
```typ
*Strong*
```,
),
(
[强调标记],
refs.writing-markup.with(reference: <grammar-emph>),
```typ
_emphasis_
```,
),
(
[着重且强调标记],
refs.writing-markup.with(reference: <grammar-emph>),
```typ
*_emphasis_*
```,
),
(
[有序列表],
refs.writing-markup.with(reference: <grammar-list>),
```typ
+ List 1
+ List 2
```,
),
(
[有序列表(重新开始标号)],
refs.writing-markup.with(reference: <grammar-continue-list>),
```typ
4. List 1
+ List 2
```,
),
(
[无序列表],
refs.writing-markup.with(reference: <grammar-emum>),
```typ
- Enum 1
- Enum 2
```,
),
(
[交替有序与无序列表],
refs.writing-markup.with(reference: <grammar-mix-list-emum>),
```typ
- Enum 1
+ Item 1
- Enum 2
```,
),
(
[短代码片段],
refs.writing-markup.with(reference: <grammar-raw>),
// @typstyle off
````typ
`code`
````,
),
(
[长代码片段],
refs.writing-markup.with(reference: <grammar-long-raw>),
// @typstyle off
````typ
``` code```
````,
),
(
[语法高亮],
refs.writing-markup.with(reference: <grammar-lang-raw>),
// @typstyle off
````typ
```rs trait World```
````,
),
(
[块代码片段],
refs.writing-markup.with(reference: <grammar-blocky-raw>),
// @typstyle off
````typ
```typ
= Heading
```
````,
),
(
[图像],
refs.writing-markup.with(reference: <grammar-image>),
````typ
#image("/assets/files/香風とうふ店.jpg", width: 50pt)
````,
),
(
[拉伸图像],
refs.writing-markup.with(reference: <grammar-image-stretch>),
````typ
#image("/assets/files/香風とうふ店.jpg", width: 50pt, height: 50pt, fit: "stretch")
````,
),
(
[内联图像(盒子法)],
refs.writing-markup.with(reference: <grammar-image-inline>),
````typ
在一段话中插入一个#box(baseline: 0.15em, image("/assets/files/info-icon.svg", width: 1em))图片。
````,
),
(
[图像标题],
refs.writing-markup.with(reference: <grammar-figure>),
````typ
#figure(```typ
#image("/assets/files/香風とうふ店.jpg")
```, caption: [用于加载香風とうふ店送外卖的宝贵影像的代码])
````,
),
(
[链接],
refs.writing-markup.with(reference: <grammar-link>),
````typ
#link("https://zh.wikipedia.org")[维基百科]
````,
),
(
[HTTP(S)链接],
refs.writing-markup.with(reference: <grammar-http-link>),
````typ
https://zh.wikipedia.org
````,
),
(
[内部链接],
refs.writing-markup.with(reference: <grammar-internal-link>),
````typ
== 某个标题 <ref-internal-link>
#link(<ref-internal-link>)[链接到某个标题]
````,
),
(
[表格],
refs.writing-markup.with(reference: <grammar-table>),
````typ
#table(columns: 2, [111], [2], [3])
````,
),
(
[对齐表格],
refs.writing-markup.with(reference: <grammar-table-align>),
````typ
#table(columns: 2, align: center, [111], [2], [3])
````,
),
(
[行内数学公式],
refs.writing-markup.with(reference: <grammar-inline-math>),
````typ
$sum_x$
````,
),
(
[行间数学公式],
refs.writing-markup.with(reference: <grammar-display-math>),
````typ
$ sum_x $
````,
),
(
[标记转义序列],
refs.writing-markup.with(reference: <grammar-escape-sequences>),
````typ
>\_<
````,
),
(
[标记的Unicode转义序列],
refs.writing-markup.with(reference: <grammar-unicode-escape-sequences>),
````typ
\u{9999}
````,
),
(
[换行符(转义序列)],
refs.writing-markup.with(reference: <grammar-newline-by-space>),
````typ
A \ B
````,
),
(
[换行符情形二],
refs.writing-markup.with(reference: <grammar-newline>),
````typ
A \
B
````,
),
(
[速记符],
refs.writing-markup.with(reference: <grammar-shorthand>),
````typ
北京--上海
````,
),
(
[空格(速记符)],
refs.writing-markup.with(reference: <grammar-shorthand-space>),
````typ
A~B
````,
),
(
[行内注释],
refs.writing-markup.with(reference: <grammar-inline-comment>),
````typ
// 行内注释
````,
),
(
[行间注释],
refs.writing-markup.with(reference: <grammar-cross-line-comment>),
````typ
/* 行间注释
*/
````,
),
(
[行内盒子],
refs.writing-markup.with(reference: <grammar-box>),
````typ
在一段话中插入一个#box(baseline: 0.15em, image("/assets/files/info-icon.svg", width: 1em))图片。
````,
),
))
== 分类:修饰文本 <grammar-table:text>
#ref-table((
(
[背景高亮],
refs.writing-markup.with(reference: <grammar-highlight>),
````typ
#highlight[高亮一段内容]
````,
),
(
[下划线],
refs.writing-markup.with(reference: <grammar-underline>),
````typ
#underline[Language]
````,
),
(
[无驱逐效果的下划线],
refs.writing-markup.with(reference: <grammar-underline-evade>),
````typ
#underline(
evade: false)[ጿኈቼዽ]
````,
),
(
[上划线],
refs.writing-markup.with(reference: <grammar-overline>),
````typ
#overline[ጿኈቼዽ]
````,
),
(
[中划线(删除线)],
refs.writing-markup.with(reference: <grammar-strike>),
````typ
#strike[ጿኈቼዽ]
````,
),
(
[下标],
refs.writing-markup.with(reference: <grammar-subscript>),
````typ
威严满满#sub[抱头蹲防]
````,
),
(
[上标],
refs.writing-markup.with(reference: <grammar-superscript>),
````typ
香風とうふ店#super[TM]
````,
),
(
[设置文本大小],
refs.writing-markup.with(reference: <grammar-text-size>),
````typ
#text(size: 24pt)[一斤鸭梨]
````,
),
(
[设置文本颜色],
refs.writing-markup.with(reference: <grammar-text-fill>),
````typ
#text(fill: blue)[蓝色鸭梨]
````,
),
(
[设置字体],
refs.writing-markup.with(reference: <grammar-text-font>),
````typ
#text(font: "Microsoft YaHei")[板正鸭梨]
````,
),
))
== 分类:脚本声明 <grammar-table:decl>
#ref-table((
(
[进入脚本模式],
refs.writing-markup.with(reference: <grammar-enter-script>),
````typ
#1
````,
),
(
[代码块],
refs.writing-markup.with(reference: <grammar-code-block>),
````typ
#{"a"; "b"}
````,
),
(
[内容块],
refs.writing-markup.with(reference: <grammar-content-block>),
````typ
#[内容块]
````,
),
(
[空字面量],
refs.content-scope-style.with(reference: <grammar-none-literal>),
````typ
#none
````,
),
(
[假(布尔值)],
refs.content-scope-style.with(reference: <grammar-false-literal>),
````typ
#false
````,
),
(
[真(布尔值)],
refs.content-scope-style.with(reference: <grammar-true-literal>),
````typ
#true
````,
),
(
[整数字面量],
refs.content-scope-style.with(reference: <grammar-integer-literal>),
````typ
#(-1), #(0), #(1)
````,
),
(
[进制数字面量],
refs.content-scope-style.with(reference: <grammar-n-adecimal-literal>),
````typ
#(-0xdeadbeef), #(-0o644), #(-0b1001)
````,
),
(
[浮点数字面量],
refs.content-scope-style.with(reference: <grammar-float-literal>),
````typ
#(0.001), #(.1), #(2.)
````,
),
(
[指数表示法],
refs.content-scope-style.with(reference: <grammar-exp-repr-float>),
````typ
#(1e2), #(1.926e3), #(-1e-3)
````,
),
(
[字符串字面量],
refs.content-scope-style.with(reference: <grammar-string-literal>),
````typ
#"Hello world!!"
````,
),
(
[字符串转义序列],
refs.scripting-base.with(reference: <grammar-str-escape-sequences>),
````typ
#"\""
````,
),
(
[字符串的Unicode转义序列],
refs.scripting-base.with(reference: <grammar-str-unicode-escape-sequences>),
````typ
#"\u{9999}"
````,
),
(
[数组字面量],
refs.content-scope-style.with(reference: <grammar-array-literal>),
````typ
#(1, "OvO", [一段内容])
````,
),
(
[字典字面量],
refs.content-scope-style.with(reference: <grammar-dict-literal>),
````typ
#(neko-mimi: 2, "utterance": "喵喵喵")
````,
),
(
[空数组],
refs.content-scope-style.with(reference: <grammar-empty-array>),
````typ
#()
````,
),
(
[空字典],
refs.content-scope-style.with(reference: <grammar-empty-dict>),
````typ
#(:)
````,
),
(
[被括号包裹的空数组],
refs.content-scope-style.with(reference: <grammar-paren-empty-array>),
````typ
#(())
````,
),
(
[含有一个元素的数组],
refs.content-scope-style.with(reference: <grammar-single-member-array>),
````typ
#(1,)
````,
),
(
[变量声明],
refs.content-scope-style.with(reference: <grammar-var-decl>),
````typ
#let x = 1
````,
),
(
[函数声明],
refs.content-scope-style.with(reference: <grammar-func-decl>),
````typ
#let f(x) = x * 2
````,
),
(
[函数闭包],
refs.content-scope-style.with(reference: <grammar-closure>),
````typ
#let f = (x, y) => x + y
````,
),
(
[具名参数声明],
refs.content-scope-style.with(reference: <grammar-named-param>),
````typ
#let g(named: none) = named
````,
),
(
[含变参函数],
refs.content-scope-style.with(reference: <grammar-variadic-param>),
````typ
#let g(..args) = args.pos().join([、])
````,
),
(
[数组解构赋值],
refs.content-scope-style.with(reference: <grammar-destruct-array>),
````typ
#let (one, hello-world) = (1, "Hello, World")
````,
),
(
[数组解构赋值情形二],
refs.content-scope-style.with(reference: <grammar-destruct-array-eliminate>),
````typ
#let (_, second, ..) = (1, "Hello, World", []); #second
````,
),
(
[字典解构赋值],
refs.content-scope-style.with(reference: <grammar-destruct-dict>),
````typ
#let (neko-mimi: mimi) = (neko-mimi: 2); #mimi
````,
),
(
[数组内容重映射],
refs.content-scope-style.with(reference: <grammar-array-remapping>),
````typ
#let (a, b, c) = (1, 2, 3)
#let (b, c, a) = (a, b, c)
#a, #b, #c
````,
),
(
[数组内容交换],
refs.content-scope-style.with(reference: <grammar-array-swap>),
````typ
#let (a, b) = (1, 2)
#((a, b) = (b, a))
#a, #b
````,
),
(
[占位符(`let _ = ..`)],
refs.content-scope-style.with(reference: <grammar-placeholder>),
````typ
#let last-two(t) = {
let _ = t.pop()
t.pop()
}
#last-two((1, 2, 3, 4))
````,
),
))
== 分类:脚本语句
#ref-table((
(
[`if`语句],
refs.content-scope-style.with(reference: <grammar-if>),
````typ
#if true { 1 },
#if false { 1 } else { 0 }
````,
),
(
[串联`if`语句],
refs.content-scope-style.with(reference: <grammar-if-if>),
````typ
#if false { 0 } else if true { 1 },
#if false { 2 } else if false { 1 } else { 0 }
````,
),
(
[`while`语句],
refs.content-scope-style.with(reference: <grammar-while>),
````typ
#{
let i = 0;
while i < 10 {
(i * 2, )
i += 1;
}
}
````,
),
(
[`for`语句],
refs.content-scope-style.with(reference: <grammar-for>),
````typ
#for i in range(10) {
(i * 2, )
}
````,
),
(
[`for`语句解构赋值],
refs.content-scope-style.with(reference: <grammar-for-destruct>),
````typ
#for (特色, 这个) in (neko-mimi: 2) [猫猫的 #特色 是 #这个\ ]
````,
),
(
[`break`语句],
refs.content-scope-style.with(reference: <grammar-break>),
````typ
#for i in range(10) { (i, ); (i + 1926, ); break }
````,
),
(
[`continue`语句],
refs.content-scope-style.with(reference: <grammar-continue>),
````typ
#for i in range(10) {
if calc.even(i) { continue }
(i, )
}
````,
),
(
[`return`语句],
refs.content-scope-style.with(reference: <grammar-return>),
````typ
#let never(..args) = return
#type(never(1, 2))
````,
),
(
[`include`语句],
refs.content-scope-style.with(reference: <grammar-include>),
````typ
#include "other-file.typ"
````,
),
))
== 分类:脚本样式
#ref-table((
(
[`set`语句],
refs.content-scope-style.with(reference: <grammar-set>),
````typ
#set text(size: 24pt)
四斤鸭梨
````,
),
(
[作用域],
refs.content-scope-style.with(reference: <grammar-scope>),
````typ
两只#[兔#set text(fill: rgb("#ffd1dc").darken(15%))
#[兔白#set text(fill: orange)
又白],真可爱
]
````,
),
(
[`set if`语句],
refs.content-scope-style.with(reference: <grammar-set-if>),
````typ
#let is-dark-theme = true
#set rect(fill: black) if is-dark-theme
#set text(fill: white) if is-dark-theme
#rect([wink!])
````,
),
(
[`show set`语句],
refs.content-scope-style.with(reference: <grammar-show-set>),
````typ
#show: set text(fill: blue)
wink!
````,
),
(
[`show`语句],
refs.content-scope-style.with(reference: <grammar-show>),
// @typstyle off
````typ
#show raw: it => it.lines.at(1)
获取代码片段第二行内容:```typ
#{
set text(fill: true)
}
```
````,
),
(
[文本选择器],
refs.content-scope-style.with(reference: <grammar-text-selector>),
````typ
#show "cpp": strong(emph(box("C++")))
在古代,cpp是一门常用语言。
````,
),
(
[正则文本选择器],
refs.content-scope-style.with(reference: <grammar-regex-selector>),
````typ
#show regex("[”。]+"): it => {
set text(font: "KaiTi")
highlight(it, fill: yellow)
}
“无名,万物之始也;有名,万物之母也。”
````,
),
(
[标签选择器],
refs.content-scope-style.with(reference: <grammar-label-selector>),
````typ
#show <一整段话>: set text(fill: blue)
#[$lambda$语言是世界上最好的语言。] <一整段话>
另一段话。
````,
),
(
[选择器表达式],
refs.content-scope-style.with(reference: <grammar-selector-exp>),
````typ
#show heading.where(level: 2): set text(fill: blue)
= 一级标题
== 二级标题
````,
),
(
[获取位置],
refs.content-scope-style.with(reference: <grammar-locate>),
````typ
#locate(loc =>
loc.position())
````,
),
(
[检测当前页面是否为偶数页(位置相关计算)],
refs.content-scope-style.with(reference: <grammar-locate-calc>),
````typ
#locate(loc => [ 页码是偶数:#calc.even(loc.page()) ])
````,
),
(
[查询文档内容],
refs.content-scope-style.with(reference: <grammar-query>),
````typ
#locate(loc => query(<ref-internal-link>, loc).at(0).body)
````,
),
(
[声明全局状态],
refs.content-scope-style.with(reference: <grammar-state>),
````typ
#state("my-state", 1)
````,
),
))
== 分类:脚本表达式
#ref-table((
(
[函数调用],
refs.writing-markup.with(reference: <grammar-func-call>),
````typ
#calc.pow(4, 3)
````,
),
(
[函数调用传递内容参数],
refs.writing-markup.with(reference: <grammar-content-param>),
````typ
#emph[emphasis]
````,
),
(
[成员访问],
refs.content-scope-style.with(reference: <grammar-member-exp>),
````typ
#`OvO`.text
````,
),
(
[方法调用],
refs.content-scope-style.with(reference: <grammar-method-exp>),
````typ
#"Hello World".split(" ")
````,
),
(
[字典成员访问],
refs.content-scope-style.with(reference: <grammar-dict-member-exp>),
````typ
#let cat = (neko-mimi: 2)
#cat.neko-mimi
````,
),
(
[内容成员访问],
refs.content-scope-style.with(reference: <grammar-content-member-exp>),
````typ
#`OvO`.text
````,
),
(
[代码表示的自省函数],
refs.content-scope-style.with(reference: <grammar-repr>),
````typ
#repr[ 一段文本 ]
````,
),
(
[类型的自省函数],
refs.content-scope-style.with(reference: <grammar-type>),
````typ
#type[一段文本]
````,
),
(
[求值函数],
refs.content-scope-style.with(reference: <grammar-eval>),
````typ
#type(eval("1"))
````,
),
(
[求值函数(标记模式)],
refs.content-scope-style.with(reference: <grammar-eval-markup-mode>),
````typ
#eval("== 一个标题", mode: "markup")
````,
),
(
[判断数组内容],
refs.content-scope-style.with(reference: <grammar-array-in>),
````typ
#let pol = (1, "OvO", [])
#(1 in pol)
````,
),
(
[判断数组内容不在],
refs.content-scope-style.with(reference: <grammar-array-not-in>),
````typ
#let pol = (1, "OvO", [])
#([另一段内容] not in pol)
````,
),
(
[判断字典内容],
refs.content-scope-style.with(reference: <grammar-dict-in>),
````typ
#let cat = (neko-mimi: 2)
#("neko-mimi" in cat)
````,
),
(
[逻辑比较表达式],
refs.content-scope-style.with(reference: <grammar-logical-cmp-exp>),
````typ
#(1 < 0), #(1 >= 2),
#(1 == 2), #(1 != 2)
````,
),
(
[逻辑运算表达式],
refs.content-scope-style.with(reference: <grammar-logical-calc-exp>),
````typ
#(not false), #(false or true), #(true and false)
````,
),
(
[取正运算],
refs.content-scope-style.with(reference: <grammar-plus-exp>),
````typ
#(+1), #(+0), #(1), #(++1)
````,
),
(
[取负运算],
refs.content-scope-style.with(reference: <grammar-minus-exp>),
````typ
#(-1), #(-0), #(--1),
#(-+-1)
````,
),
(
[算术运算表达式],
refs.content-scope-style.with(reference: <grammar-arith-exp>),
````typ
#(1 + 1), #(1 + -1),
#(1 - 1), #(1 - -1)
````,
),
(
[赋值表达式],
refs.content-scope-style.with(reference: <grammar-assign-exp>),
````typ
#let a = 1; #repr(a = 10), #a, #repr(a += 2), #a
````,
),
(
[字符串连接],
refs.content-scope-style.with(reference: <grammar-string-concat-exp>),
````typ
#("a" + "b")
````,
),
(
[重复连接字符串],
refs.content-scope-style.with(reference: <grammar-string-mul-exp>),
````typ
#("a" * 4), #(4 * "ab")
````,
),
(
[字符串比较],
refs.content-scope-style.with(reference: <grammar-string-cmp-exp>),
````typ
#("a" == "b"), #("a" != "b"), #("a" < "ab"), #("a" >= "a")
````,
),
(
[整数转浮点数],
refs.content-scope-style.with(reference: <grammar-int-to-float>),
````typ
#float(1), #(type(float(1)))
````,
),
(
[布尔值转整数],
refs.content-scope-style.with(reference: <grammar-bool-to-int>),
````typ
#int(true), #(type(int(true)))
````,
),
(
[浮点数转整数],
refs.content-scope-style.with(reference: <grammar-float-to-int>),
````typ
#int(1), #(type(int(1)))
````,
),
(
[十进制字符串转整数],
refs.content-scope-style.with(reference: <grammar-dec-str-to-int>),
````typ
#int("1"), #(type(int("1")))
````,
),
(
[十六进制/八进制/二进制字符串转整数],
refs.content-scope-style.with(reference: <grammar-nadec-str-to-int>),
````typ
#let safe-to-int(x) = {
let res = eval(x)
assert(type(res) == int, message: "should be integer")
res
}
#safe-to-int("0xf"), #(type(safe-to-int("0xf"))) \
#safe-to-int("0o755"), #(type(safe-to-int("0o755"))) \
#safe-to-int("0b1011"), #(type(safe-to-int("0b1011"))) \
````,
),
(
[数字转字符串],
refs.content-scope-style.with(reference: <grammar-num-to-str>),
````typ
#repr(str(1)),
#repr(str(.5))
````,
),
(
[整数转十六进制字符串],
refs.content-scope-style.with(reference: <grammar-int-to-nadec-str>),
````typ
#str(501, base:16), #str(0xdeadbeef, base:36)
````,
),
(
[布尔值转字符串],
refs.content-scope-style.with(reference: <grammar-bool-to-str>),
````typ
#repr(false)
````,
),
(
[数字转布尔值],
refs.content-scope-style.with(reference: <grammar-int-to-bool>),
````typ
#let to-bool(x) = x != 0
#repr(to-bool(0)),
#repr(to-bool(1))
````,
),
))
|
https://github.com/GreyCorbel/docs | https://raw.githubusercontent.com/GreyCorbel/docs/main/main.typ | typst | MIT License | #import "gcdocs.typ": *
#show: doc => gc-docs(
title: lorem(3),
version: "v0.1.0",
logo: "./img/gc.png",
doc,
)
= Kapitola
#lorem(50)
@gc-config-Schedule
#gc-config("Schedule", "ServiceSchedule", "1 * * * *", lorem(50))
== Kapitola
#lorem(20)
== Kapitola
#lorem(20)
= Kapitola
#lorem(50)
|
https://github.com/luiswirth/diff-form-pres | https://raw.githubusercontent.com/luiswirth/diff-form-pres/main/src/main.typ | typst | #import "setup.typ": *
#import "math.typ": *
#show: my-config
#show: slides-config
#show: math-config
#align(center, text(size: 40pt, weight: "bold")[
Discrete Differential Forms\ for Computational Modeling
])
#text(size: 20pt, grid(
columns: (1fr, 1fr, 1fr),
align(center)[
<NAME>\
Applied Geometry Lab\
Caltech\
#link("mailto:<EMAIL>")
],
align(center)[
<NAME>\
Applied Geometry Lab\
Caltech\
#link("mailto:<EMAIL>")
],
align(center)[
<NAME>\
Applied Geometry Lab\
Caltech\
#link("mailto:<EMAIL>")
]
))
#pagebreak()
General idea of Differential Forms and Discrete Differential Forms
#pagebreak()
#grid(
columns: (1fr, 1fr),
[
= Idea of a Bivector
Take two vectors $avec(u), avec(v) in RR^2$
and form their *wedge* / *exterior* product
#text(50pt)[$ avec(u) and avec(v) $]
The result is called a *bivector* or *2-vector*.
It represents an oriented plane segment.
],
image("../res/bivector.svg"),
)
#pagebreak()
Exterior product
Wedge product
Given a basis of $RR^3$
$
nvec(e)_1
, quad
nvec(e)_2
, quad
nvec(e)_3
$
This is the basis of the vectors.
Using it we can build a basis for bivectors,
by considering all the linear independent
exterior product combinations of these basis vectors.
$
nvec(e)_12
= nvec(e)_1 and nvec(e)_2
quad
nvec(e)_13
= nvec(e)_1 and nvec(e)_3
quad
nvec(e)_23
= nvec(e)_2 and nvec(e)_3
$
The cross product induces this ordering of the bivector basis.
$
nvec(e)_23
quad
nvec(e)_31
quad
nvec(e)_12
$
$
nvec(e)_1 and nvec(e)_2
, quad
nvec(e)_2 and nvec(e)_3
, quad
nvec(e)_3 and nvec(e)_1
$
#pagebreak()
#[
$
dif f =
[(diff f)/(diff x_1)
quad dots.c quad
(diff f)/(diff x_n)]
=
(diff f)/(diff x_1) dif x^1
+
dots
+
(diff f)/(diff x_n) dif x^n
$
]
differential form $omega$
#pagebreak()
#text(size: 50pt)[
Exterior Derivative
$
dif^k: and^k (Omega) -> and^(k+1) (Omega)
$
]
#pagebreak()
#text(size: 50pt)[
#align(center)[Stokes' Theorem]
$
integral_M dif omega = integral_(diff M) omega
$
]
|
|
https://github.com/DashieTM/nix-introduction | https://raw.githubusercontent.com/DashieTM/nix-introduction/main/topics/nix-lang.typ | typst | #import "../utils.typ": *
#polylux-slide[
== What is Nix?
#v(15pt)
- just a programming language
- functional
- lazy
- everything is an expression
- turing complete
- made to configure environments
- native paths
- tooling for environments -> nixos etc
#pdfpc.speaker-note(```md
```)
]
#polylux-slide[
== Basics
#v(15pt)
#columns(2,[
- haskell interactive shell
- nix repl
- evaluate code in file
- nix-instantiate
- comments: \-\-
- function: argument:body
- x: 5 + x
- one argument only
- more arguments == currying
#colbreak()
- native types
- lists
- attribute set
- functions
- numbers, strings, *paths*, etc
- inbuilt functionality
- import
- lib.toString
- std.mkDerivation
])
#pdfpc.speaker-note(```md
```)
]
#polylux-slide[
== Tricks
#v(15pt)
#columns(3, [
=== let in
#sourcecode(```nix
let
func = x: x * 2;
in {
func 24
}
-- 48
```)
- *only in this scope*
#colbreak()
=== With
#sourcecode(```nix
let
attrs = {
x = 10;
b = 55;
c = 34;
};
in with attrs; [
x
b
c
];
```)
#colbreak()
=== inherit
#sourcecode(```nix
let
x = 1;
y = 2;
in
{
inherit x y;
}
```)
- copies the values in let to the scope in the curly brackets
])
#pdfpc.speaker-note(```md
```)
]
#polylux-slide[
== Packages
#v(15pt)
#sourcecode(```nix
{ stdenv
, lib
, pkgs
, fetchFromGitLab
}:
pkgs.python3.pkgs.buildPythonApplication rec {
pname = "pingpang";
version = "0.0.1";
src = fetchFromGitLab {
domain = "gitlab.globi.org";
owner = "globi";
repo = pname;
rev = version;
sha256 = "sha.something";
};
nativeBuildInputs = with pkgs; [
cargo
];
buildInputs = with pkgs; [
gtk
];
meta = with lib; {
-- homepage, architecture support, help page etc
};
}
```)
#pdfpc.speaker-note(```md
```)
]
// https://nix.dev/tutorials/nix-language
|
|
https://github.com/kristoferssolo/Mafia-the-Game-Description | https://raw.githubusercontent.com/kristoferssolo/Mafia-the-Game-Description/main/abstract.typ | typst | #import "layout.typ": indent-par
#pagebreak()
#heading(
level: 1,
outlined: false,
numbering: none,
"Anotācija",
)
#indent-par([
Sociālā lomu spēle "Mafija" ir plaši pazīstama. Tā ir pieejama vairākos
paveidos un formātos, kā arī piedāvā neierobežotu konfigurāciju un lomu skaitu.
Spēlētāju ērtībai tiek nodrošināts tīmekļa vietnes formāts, kas ietver
norādījumus, informējot lietotāju par pieejamajām iespējām, un skaidrojumus,
aprakstot spēles elementus un saskarni, ar mērķi atvieglot tās lietošanu.
Tirgus izpēte apliecina, ka ir pieejami vairāki, nepilnvērtīgi risinājumi.
Programmatūras prasību specifikācija apraksta sistēmas pamatprasības un
papildus funkcionalitāti, tostarp lomu klāsta papildināšanu, spēles
konfigurāciju izveidi, kā arī priviliģētu lietotāju (maksas lietotāju) izveidošanu,
pielietojot abonementa paveida maksājumu sistēmu.
])
#par(
first-line-indent: 0cm,
[*Atslēgvārdi:*],
)
Mafijas spēle, sistēmas prasības, specifikācijas dokuments, programmatūras
uzlabošana, lomu spēle, vienkāršota spēlēšana, organizatoriski risinājumi,
programmatūras prasību specifikācija, lietotāju veidots saturs, abonements,
maksas lietotājs, maksājumu apstrādātāja lietojumprogrammas saskarni (API).
#text(
hyphenate: auto,
lang: "en",
[
#pagebreak()
#heading(
level: 1,
outlined: false,
numbering: none,
"Abstract",
)
#indent-par([
The social role-playing game "Mafia" is widely known. It is available in
various versions and formats, offering an unlimited number of configurations
and roles. For the convenience of players, the game is made as a web
application that includes instructions, informing the user about available
options, and explanations describing the game's elements and interface, to
improve user experience.
Market research confirms that several mediocre solutions are
available. The software requirements specification describes the system's basic
requirements with additional functionality, including expanding the range of
roles, creating game configurations, and a privileged user (premium user) using
a subscription-based payment system.
])
#par(
first-line-indent: 0cm,
[*Keywords:*],
)
Mafia game, system requirements, specification document, software improvement,
role-playing, simplified gameplay, organizational solutions, software
requirements specification, user-generated content, subscription, premium user,
payment processor application program interface (API).
],
)
|
|
https://github.com/PhilChodrow/cv | https://raw.githubusercontent.com/PhilChodrow/cv/main/src/content/pd.typ | typst | #import "../template.typ": *
#cvSection("Professional Development")
#pad(left: 0.5cm,
table(
columns: 2,
stroke: none,
align: (left, left),
[2024 -- present], [Cultural Competency in Computing (3C) Fellowship],
[2023], [Middlebury College Engaged Listening Project],
[2021], [MAA Project NeXT],
[2020], [UCLA CEILS Introduction to Evidence-Based Pedagogy]
)
) |
|
https://github.com/akrantz01/resume | https://raw.githubusercontent.com/akrantz01/resume/main/template/heading.typ | typst | MIT License | #import "common.typ": icon
#let format_phone_number(phone) = {
if phone.starts-with("+") == false {
panic("Phone number must start with a country code")
}
"+" + phone.split(regex("[^0-9]+")).filter(part => part.len() > 0).join("-")
}
#let account_link(base, identifier, full: false) = {
let base = "https://" + base.trim("/", at: end) + "/" + identifier
let text = if full {
base
} else {
identifier
}
link(base, text)
}
#let header_items = (
"email": (email: "<EMAIL>", ..) => box[
#icon("email")
#link("mailto:" + email, email)
],
"phone": (phone: "+1 555 555 5555", ..) => box[
#icon("phone")
#link("tel:" + format_phone_number(phone), phone)
],
"website": (settings, url: "https://example.com", ..) => {
let text = if settings.full-links {
url
} else {
url.trim("https://", at: start)
}
box[
#icon("website")
#link(url, text)
]
},
"github": (settings, username: "john-doe", ..) => box[
#icon("github")
#account_link("github.com", username, full: settings.full-links)
],
"linkedin": (settings, username: "john-doe", ..) => box[
#icon("linkedin")
#account_link("linkedin.com/in/", username, full: settings.full-links)
],
)
#let header_item((type, ..item), settings) = box(
header_items.at(type)(..item, settings),
)
#let header(name, settings: (:), links: ()) = {
align(
center,
block[
#text(size: 2.25em, font: "Fira Code Retina", name) \
#{
set text(size: 8.25pt)
links.map(args => header_item(args, settings)).join(h(1.25em))
}
],
)
v(5pt)
}
|
https://github.com/felsenhower/kbs-typst | https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/01.typ | typst | MIT License | = Einführung
Mein erster Text mit Typst!
#lorem(20)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/grotesk-cv/0.1.0/content/other_experience.typ | typst | Apache License 2.0 | #import "../lib.typ": *
#import "@preview/fontawesome:0.2.1": *
== #fa-icon("wrench") #h(5pt) #get-header-by-language("Other experience", "Otra experiencia")
#v(5pt)
#if is-english() [
#experience-entry(
title: [Combat Training],
date: [2029],
company: [Resistance],
location: [Los Angeles, CA],
)
] else if is-spanish() [
#experience-entry(
title: [Entrenamiento de combate],
date: [2029],
company: [Resistencia],
location: [Los Ángeles, CA],
)
]
|
https://github.com/RodolpheThienard/typst-template | https://raw.githubusercontent.com/RodolpheThienard/typst-template/main/README.md | markdown | MIT License | # Typst template
## Beamer
### Use template
```typ
#import "beamer.typ" : beamer
#show: beamer.with(
title: "Title page",
author: "author",
date: [#datetime.today().display(" [Month repr:numerical], [day] [year]")],
end: "End Slide",
)
```
### Render
<details>
<summary>Outline</summary>
<img title="a title" alt="Alt text" src=".picture/outline.jpg">
</details>
<details>
<summary>Section</summary>
<img title="a title" alt="Alt text" src=".picture/section.jpg">
</details>
<details>
<summary>Slide</summary>
<img title="a title" alt="Alt text" src=".picture/slide.jpg">
</details>
|
https://github.com/F-actorio/vedtaegter | https://raw.githubusercontent.com/F-actorio/vedtaegter/main/main.typ | typst | #import "template.typ": *
#show: project.with(
title: "F-actorio Vedtægter",
authors: (
(name: "<NAME>", email: "<EMAIL>"),
(name: "<NAME>", email: ""),
),
)
#set enum(numbering: "§1", tight: false)
= Formål
+ Foreningens navn er F-actorio, udtales ...
+ Foreningens sprog er først og fremmest dansk, dernæst engelsk.
+ Klubben har sin egen skabbelsesvise, @appendix:factorio-prayer i bilagene.
= Bilag
#figure(align(left, [
Vor Factorio, du som er i automatiseringens rige,\
Helliget være dine samlebånd således.\
Komme dit teknologiske imperium,\
Ske din vilje, som i produktion, så også på kortet.\
Giv os i dag vores daglige ressourcepatches,\
Og forlad os vores spaghetti, som også vi forlader dem,\
Der spaghettier imod os.\
Led os ikke ind i Ressourceknaphed,\
Men fri os fra manuel håndtering.\
For dit er fabrikken, effekten og forskningen i evighed.\
Automatisering.]),
caption: "Factorio Vor"
) <appendix:factorio-prayer> |
|
https://github.com/donghoony/typst_editorial | https://raw.githubusercontent.com/donghoony/typst_editorial/main/result.typ | typst | MIT License | #import "colors.typ": *
#let result_page() = {
let page_title = text.with(
weight: "black",
size: 30pt
)
let score_title = text.with(
weight: "bold",
size: 20pt
)
let name_handle(name, handle) = {
let name_style = text.with(
weight: "light",
size: 15pt
)
let handle_style = text.with(
weight: "light",
size: 10pt,
font: "Consolas",
fill: rgb("BFBFBF")
)
pad(left: 30pt)[
#align(left)[#name_style[#name] #handle_style[#handle]]
]
}
let solved(div, s) = {
let color = none
if div == 3 {color = AC_BRONZE}
if div == 2 {color = AC_SILVER}
if div == 1 {color = AC_GOLD}
let text_style = text.with(
fill: color,
weight: "bold",
size: 15pt
)
let t = ""
if s == 0 {
t = grid(
columns: 2,
align(horizon)[All Solved #h(5pt)],
align(horizon)[#image("images/crown.png", width:20pt)]
)
}
else {t = [Solved #s]}
pad(top: 10pt)[#text_style[#t]]
}
align(center)[
#page_title([연습대회 결과])
#grid(
columns: (25%, 25%, 25%),
gutter: 10pt,
grid(
columns: (100%),
row-gutter: 15pt,
score_title([Div. 3]),
solved(3, 0),
name_handle("이동훈", "donghoony"),
solved(3, 3),
name_handle("이동훈", "donghoony"),
solved(3, 2),
name_handle("이동훈", "donghoony"),
solved(3, 1),
name_handle("이동훈", "donghoony")
),
grid(
columns: (100%),
row-gutter: 15pt,
score_title([Div. 2]),
solved(2, 0),
name_handle("이동훈", "donghoony"),
solved(2, 3),
name_handle("이동훈", "donghoony"),
solved(2, 2),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
),
grid(
columns: (100%),
row-gutter: 15pt,
score_title([Div. 1]),
solved(1, 0),
name_handle("이동훈", "donghoony"),
solved(1, 4),
name_handle("이동훈", "donghoony"),
solved(1, 2),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
name_handle("이동훈", "donghoony"),
)
)
]
pagebreak(weak: true)
}
|
https://github.com/DrGo/typst-tips | https://raw.githubusercontent.com/DrGo/typst-tips/main/refs/samples/tufte-handout/README.md | markdown | Provides a template for Tufte-style handouts modeled on the [Tufte-LaTeX](https://github.com/Tufte-LaTeX/tufte-latex) project.
The key feature of this template is the `margin-note` function whichs renders content in the right margin area.
## Preview
### Portrait

### Landscape

## Usage
* No images or other assets required, just grab the `tufte-handout.typ` file
* The template will attempt to use the "TeX Gyre Pagella" font if installed but the default font looks pretty good as well.
```typst
// Assumes you've cloned tufte-handout in this directory
#import "tufte-handout/tufte-handout.typ": template, margin-note
#show: doc => template(title: "A sample handout", doc)
= Part 1
#lorem(20)
#margin-note[A note!]
#lorem(30)
#margin-note[#lorem(20)]
#lorem(20)
```
|
|
https://github.com/iyno-org/Holistic-Clinical-Neurosurgery | https://raw.githubusercontent.com/iyno-org/Holistic-Clinical-Neurosurgery/main/old/example.typ | typst | = Introduction
<NAME> is an American statistician, professor, and pioneer in the field of data visualization, known for his work on the visual presentation of data and information. He is the author of influential books such as "The Visual Display of Quantitative Information" and is renowned for his principles on clarity, precision, and efficiency in data graphics. His books have inspired a unique design and typography, created by <NAME>.
This Typst template adopts many of the conventions used by Gralla and Tufte and allows the interested author to obtain a similar appearance to style of Tufte's publications. However, the design adapts the book-format to work as an article (i.e., not having multiple parts and chapters and so forth, but instead something more akin to a memo or academic journal article).
This document is a skeuomorphnote[This document is not only a skeuomorph, but also tests the template itself.] of the template; it intends to demonstrate the template's functionality across various frontmatter styles, citations, figures, and importantly, sidenotes.
= Using this template
Largely, this template is used by importing and calling the `#template()` function, understanding the quirks of its formatting, and making use of its features such as wideblocks and sidenotes.
The template is called just like any other Typst template, such as with: ```typst
#import "tufte-memo.typ": *
#show: template.with(...)[...]
```
The template can be configured with 13 arguments, which comprise:
- `title` (`content`, required).
- `shorttitle` (`content`, optional) displayed in the header if not `none`, otherwise the `title` is displayed instead.
- `subtitle` (`content`, optional).
- `authors` (`array`<, required) takes the form as in the charged-ieee template #notecite(<Typst2024>) except instead of "department" there is "role" and "location" is ommitted.
- `date` (`datetime`, optional) displays the date on the title page if not `none`.
- `document-number` (`content`, optional) reference number for document's version or some other serialization. Displayed in the header if present.
#wideblock[
- `draft` (`bool`, optional) displays a note in the footer and also places a watermark across every page if `true`.
- `distribution` (`content`, optional) places a note in the footer if present.
- `abstract` (`content`, optional) displays the abstract below the author block if present.
- `publisher` (`content`, optional) displays below the title in the header if present.
- `toc` (`bool`, optional) displays an `outline` below the abstract if `true`.
- `bib` (`bibliography`, optional) displays a bibliography at the end of the document if not `none`. Must be a filepath reference if not `none`.
- `footer-content` (`content` or `array`, optional) if `content` then displays in the footer; if `array`, then displays first element in first page footer and second element in all other pages; or `none` and no content is displayed in footer.
== Title Page Configuration
The title page is configurable based on the combination and types of arguments supplied to the template. By default, the template produces a bare bones, simple title page: calling the template with no arguments produces a blank document with only three lines of text: "Paper Title", "First Last", and the date. The template requires an entry for the `title` and `authors` hence why there are placeholders for these values. Otherwise, the other 11 arguments optionally augment the title page to include additional information.
For instance, adding an `abstract` displays an indented block of text below the author block as you might expect, setting `toc` to `true` displays the table of contents, and so forth. Experiment with the optional arguments and see for yourself how they affect the document's setting.
== Wideblocks
You may have noticed that this text spans the entire width of the page whereas the preceeding two pages were compressed to a four-inch-wide column in the typical manner of Tufte books. The template makes permissible the ability to break the narrow column format when desired by using the `#wideblock()` function, which takes a single required argument representing the content to be displayed. The simplest way to use the wideblock is by entering `#wideblock[...]`.
The wideblock simply is a `block` but with the width parameter adjusted to make the block 6.5 inches wide. This can be useful when a full page does not contain any sidenotes and otherwise the text would look somewhat awkward being unnecessarily compressed into a narrow column.
]
== Sidenotes
In Tufte books, sidenotes#note[This is a sidenote; perhaps you have already noticed them in this document.] are a distinctive feature: sidenotes are used for a variety of purposes, but mainly to provide non-critical but related information. In a basic sense, they are simply footnotes but put on the side. Sidenotes, arguably, are more elegant than footnotes since they appear closer to the text being referenced, but still with enough of a breathe around them to not feel cluttered.
This template implements sidenotes with the `note()` function. The simplest sidenote is created with `#note[enter your content here]` which yields: #note[enter your content here]. Notice how the sidenote is automatically numbered like a footnote. This can be disabled with the `numbered: false` keyword argument.#note(numbered:false)[This sidenote is not numbered.]
On the backend, the `note()` function uses the #emph[drafting] #notecite(<Jessurun2023>) package, pre-configured with some defaults. Importantly, though, the `dy` argument can still be passed to `note()` in order to adjust the vertical offset as it appears. This is helpful when many notes are included in close vicinity. Though, #emph[drafting] package will attempt to automagically adjust vertical positions in such cases, sometimes a manual touch is necessary.
Strictly speaking, the `note()` function can be used with content of any kind, including figures. More will be discussed on the side figure topic, so it will be left for now.
There is one other type of sidenote: the citation-sidenote, which is called with the `notecite()` function. The `notecite()` function extends the simple `note()` function by placing an in-text citation at the location the function was called and by placing a simplified margin citation as well. The `notecite()` function must take a `label` key, and optionally a `supplement` for the in-text citation. E.g., this: #notecite(<Tufte2001>,supplement:[p.~47]) is produced by `#notecite(<Tufte2001>,supplement:[p.~47])`. Optionally, a `dy` argument can be passed as well.
== Figures
In this template, there are three different styles to display figures: plain, sidenote, and wideblock. A plain figure called in the body text (i.e., not in a `wideblock` or in a `note`) can be used as normal with the label applied as expected. This is demonstrated with @fig:plain-figure, below. These figures only occupy the four-inch-wide space making up the width of the document.
#figure(
rect(
width:100%,
height:3in,
fill: gradient.linear(..color.map.crest)
),
caption:[This is just a plain figure.]
)<fig:plain-figure>
Alternatively, a `wideblock()` can be used to display a larger (or, at least wider) figure in the text, which spans 6.5 inches rather than four. This is demonstrated with @fig:wide.
#wideblock([#figure(
rect(width:100%,height:3in),
caption:[The widest figure you've ever seen!])
<fig:wide>]
)
When a figure is used inside a `wideblock()`, it will display across the full page width. However, the figure must be wrapped in `[ ]` in order to allow for a label to be applied. E.g., see @code:figure-label.
#figure(
```typst
#wideblock[
#figure(
rect(width:100%,height:3in),
caption:[Blah blah blah])
<fig:label>
]
```,
caption:[Example wide figure which has a label.]
)<code:figure-label>
But wait, there is yet one more option for displaying figures; in sidenotes! Here, the content of a `#note()` call is a `#figure()`. By convention, sidenote figures are not numbered, meaning the figure is produced like `#note(figure(...),numbered:false)`. Similar to wideblock figures, when a figure is used inside a note, it must be wrapped inside content brackets \[ \] in order to apply a label. See @code:figure-label for an example. fig:side-figure demonstrates this.
#note([
#figure(
rect(width:100%,height:2in),
caption:[This is a little figure in the sidenotes.]
) <fig:side-figure1>
],
dy:-3in,
numbered:false)
== Other Formatting
This template supports headings up to and including the third level. It is an opinionated choice of the template's designer to not include headings level four and beyond, and even reluctantly#note[Third level headings are not included in the table of contents.] to include level three. Consider that if a fourth level heading is required (possibly a third level, for that matter), one should considering redesigning the content of the document:
#quote(block:true)[\[It is\] notable that the Feynman lectures (3 volumes) write about all of physics in 1800 pages, using only 2 levels of hierarchical headings: chapters and A-level heads in the text. It also uses the methodology of sentences which then cumulate sequentially into paragraphs, rather than the grunts of bullet points. #notecite(<Tufte>,dy:-0.25in)]
Conveniently this discussion on headings has allowed the demonstration of the block quote in this template. No adjustments have been made to the default styling of the block quote.
And finally, a few other things to note: text is displayed with a modest lightness (`luma(30)`) to reduce the harshness of the contrast between the type and the paper; links are displayed underline like #link("www.example.com"); if the `bib` argument in the template is left to `none` than no bibliography will be displayed and citations (normal in-text citations and citation-sidenotes alike) will not work.#note[Sometimes it is desirable to have the bibliography start at the top of a blank page. In which case, leave a pagebreak as the last line of your document.]
= Epilogue
Thank you to <NAME> for inspiring this template, and to other Typst contributes, particularly <NAME> for #emph[drafting]. |
|
https://github.com/csimide/cuti | https://raw.githubusercontent.com/csimide/cuti/master/demo-and-doc/demo-and-doc-cn.typ | typst | MIT License | #import "../lib.typ": *
#import "./otr/utils.typ": *
#set page(margin: 2cm)
#set par(justify: true)
#show heading: show-cn-fakebold
#show raw.where(block: false): set text(font: "Fira Code")
#show heading.where(level: 1): it => {pagebreak(weak: true); it}
#show heading.where(level: 2): it => {line(length: 100%); it}
= Cuti Demo & 中文文档
== 简介
Cuti #footnote[读作 `/kjuːti/`,或许可以读作 `/tsʰu˥ tʰi˥/`。] 是一个为了方便用户使用伪粗体和伪斜体而设计的包。
== 光速上手
#example(
```typst
#import "@preview/cuti:0.2.1": show-cn-fakebold
#show: show-cn-fakebold
```,
sd: false
)
在文档顶端加入如上代码,宋体、黑体、楷体的加粗就工作了。
#fakebold[请注意: ]如果您使用 Source Han Sans / Source Han Serif 等包含 `bold` 字重的中文字体,不建议您对整个文档使用 `show: show-cn-fakebold` ——对整个文档使用 `show: show-cn-fakebold` 将导致支持中文粗体的字体也会使用“伪粗体”版的粗体。如下所示:
#example(
```typst
#set text(font: "Source Han Serif SC")
+ Regular: 春江潮水连海平,海上明月共潮生。
+ Bold: #text(weight: "bold")[春江潮水连海平,海上明月共潮生。]
#show: show-cn-fakebold
+ Fakebold: #text(weight: "bold")[春江潮水连海平,海上明月共潮生。]
```
)
第2行中,使用的是 Source Han Serif SC 的 Bold 字重。但设置 `show: show-cn-fakebold` 后,第3行使用的是伪粗体描边生成 Bold 字重。
== Demo
=== Part 1: `font: ("Times New Roman", "SimSun")`
#block(
fill: rgb("dcedc8"),
stroke: 0.5pt + luma(180),
inset: 10pt,
width: 100%,
)[
#set text(font: ("Times New Roman", "SimSun"))
#grid(
columns: 2,
column-gutter: 0.2em,
row-gutter: 0.6em,
[Regular:], [你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。],
[Bold(Font Only):], text(weight: "bold")[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。],
[Bold(Fake Only):], fakebold[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。],
[Bold(Fake+Font):], show-cn-fakebold(text(weight: "bold")[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。]),
[Italic(Font Only):], text(style: "italic")[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。],
[Italic(Fake Only):], fakeitalic[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。],
[Italic(Fake+Font):], regex-fakeitalic(reg-exp: "[\p{script=Han} !-・〇-〰—]", text(style: "italic")[你说得对,但是《Cuti》是一个用于伪粗体和伪斜体的包。]),
)
]
=== Part 2: `font: "Source Han Serif SC"`
#block(
fill: rgb("dcedc8"),
stroke: 0.5pt + luma(180),
inset: 10pt,
width: 100%,
)[
#set text(font: "Source Han Serif SC")
#grid(
columns: 2,
column-gutter: 0.2em,
row-gutter: 0.6em,
[Regular:], [前面忘了。同时,逐步发掘「Typst」的奥妙。],
[Bold(Font Only):], text(weight: "bold")[前面忘了。同时,逐步发掘「Typst」的奥妙。],
[Bold(Fake Only):], fakebold[前面忘了。同时,逐步发掘「Typst」的奥妙。],
[Bold(Fake+Font):], show-cn-fakebold(text(weight: "bold")[前面忘了。同时,逐步发掘「Typst」的奥妙。])
)
]
= Fakebold 部分
Cuti 利用 `text` 的 `stroke` 属性生成伪粗体。该工具通常可用于为宋体、黑体、楷体等字体提供“粗体”。Cuti 使用 0.02857em 作为 `stroke` 的参数。在 Microsoft Office 中,使用伪粗体会给字符添加一个 0.02857em 的描边。(实际上,精确值可能是 $1/35$。)
== fakebold
不带其他参数的 `#fakebold[]` 会为字符添加#fakebold[伪粗体]效果。
#example(
```typst
- Fakebold: #fakebold[#lorem(5)]
- Bold: #text(weight: "bold", lorem(5))
- Bold + Fakebold: #fakebold[#text(weight: "bold", lorem(5))]
```
)
`#fakebold[]` 可以接受与 `#text` 相同的参数。特别地,若指定 `weight` 参数,可以用于指定基于某种字重进行描边。如果不指定 `weight`,基准字重会从上文继承。指定 `stroke` 参数会被忽略。
#example(
```typst
- Bold + Fakebold: #fakebold(weight: "bold")[#lorem(5)]
- Bold + Fakebold: #set text(weight: "bold"); #fakebold[#lorem(5)]
```
)
#fakebold[注:] `cuti:0.2.0` 使用的 `base-weight` 参数仍保留以保证兼容性。
如果将文字设置为彩色,伪粗体描边也将变成相应的颜色。
#example(
```typst
- Blue + Fakebold: #fakebold(fill: blue)[花生瓜子八宝粥,啤酒饮料矿泉水。#lorem(5)]
- Gradient + Fakebold: #set text(fill: gradient.conic(..color.map.rainbow)); #fakebold[花生瓜子八宝粥,啤酒饮料矿泉水。#lorem(5)]
```
)
== #regex-fakebold
`#regex-fakebold` 设计上是用于多语言、多字体情境的,可以根据参数 `reg-exp` 内的正则表达式只将匹配到的字符应用伪粗体格式。它也可以接受 `#font` 相同的参数。
#example(
```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便士。]
+ RegExp `\p{script=Han}`: #set text(weight: "bold"); #regex-fakebold(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。]
```
)
在上面的例子 \#3 中, `9` 和 `15` 是字体提供的“真”粗体,而其他字符是用 `regular` 字重描边得到的伪粗体。
== show-fakebold
在多语言、多字体的场景中,不同的语言通常使用不同的字体,但是不是所有的字体都自带 `bold` 字重。需要 `strong` 或者 `bold` 效果时,每次都使用 `#fakebold` `#regex-fakebold` 并不方便。所以,我们提供了用于设置 `show` 规则 `#show-fakebold` 函数。
`show-fakebold` 和 `regex-fakebold` 有着相同的参数。默认情况下 `show-fakebold` 使用 `"."` 作为正则表达式,也就是说,所有字符带加粗或`strong`属性都会被伪粗体加粗。
#example(
```typst
#show: show-fakebold
- Regular: #lorem(10)
- Bold: #text(weight: "bold")[#lorem(10)]
```
)
正常情况下字体提供的加粗与伪粗体叠加的效果不是我们想要的。一般需要指定正则表达式、指定伪粗体的生效范围。
#example(
```typst
#show: show-fakebold.with(reg-exp: "\p{script=Han}")
- Regular: 我正在使用 Typst 排版。
- Strong: *我正在使用 Typst 排版。*
```
)
`show-fakebold` 也接受 `#font` 相同的参数。
== cn-fakebold & show-cn-fakebold
这两个都是为中文排版封装的。
`cn-fakebold` 是 `regex-fakebold` 的封装。`cn-fakebold` 会将中文和常见符号进行伪粗体处理,基准字重为 `regular` 字重。请注意,在混排中英文时,需要另行指定 `weight: "bold"`。
#example(
```typst
#set text(font: ("Linux Libertine", "SimSun"))
- Regular: 有时,我们点击链接,打开的却是《Never Gonna Give You Up》这首歌。
- `cn-fakebold`: #cn-fakebold[《Never Gonna Give You Up》是英国歌手 <NAME> 演唱的歌曲,于 1987 年发行。]
#set text(weight: "bold")
- Bold:《Never Gonna Give You Up》已经成为了一种网络迷因。
- Bold + `cn-fakebold`: #cn-fakebold[在 2024 年的今天,《Never Gonna Give You Up》仍有独特的魅力。]
```
)
`show-cn-fakebold` 是 `show-fakebold` 的封装,默认的正则范围是中文字符与常见标点符号。
#example(
```typst
#show: show-cn-fakebold
- Regular: 滚滚长江东逝水,浪花淘尽英雄。 #lorem(5)
- Bold: #text(weight: "bold")[滚滚长江东逝水,浪花淘尽英雄。 #lorem(5)]
- Strong: *滚滚长江东逝水,浪花淘尽英雄。 #lorem(5)*
```
)
也可以这样使用:
#example(
```typst
#show-cn-fakebold[
- Regular: 滚滚长江东逝水,浪花淘尽英雄。 #lorem(5)
- Strong: *滚滚长江东逝水,浪花淘尽英雄。 #lorem(5)*
]
```
)
这两个函数也可以接受 `#font` 相同的参数,以指定中文字符加粗的效果。
// ----------------------------------------------------
= Fakeitalic 部分
Cuti 使用的 `skew` 函数来自 typst issue \#2749 (https://github.com/typst/typst/issues/2749) by Enivex.
`skew` 利用 `rotate` 和 `scale` 的组合生成伪斜体。Cuti 使用 $-0.32175$ 作为默认的倾斜角度。在 Microsoft Office 中,使用伪粗体会给字符添加一个 $arctan(1/3)$ 的倾斜效果。请注意,由于不同的英文字体拥有不同的倾斜角度,需要自行寻找一个合适的角度。如果使用 Times New Roman 与中易宋体,则默认的角度是比较合适的。
== fakeitalic
`fakeitalic(` \
#h(2em) `ang:` #typebox[angle] 默认值 `-0.32175,` \
#h(2em) #typebox[content] \
`)`
`#fakeitalic[]` 会为字符添加#fakeitalic[伪斜体]#h(1pt)效果。
#example(
```typst
- Regular: #lorem(5)
- Italic: #text(style: "italic", lorem(5))
- Fakeitalic: #fakeitalic[#lorem(5)]
- Fakeitalic + Fakebold: #fakeitalic[#fakebold[#lorem(5)]]
```
)
可以通过调整 `ang` 参数调整倾斜的角度。
#example(
```typst
- -10deg: #fakeitalic(ang: -10deg)[#lorem(5)]
- -20deg: #fakeitalic(ang: -20deg)[#lorem(5)]
- +20deg: #fakeitalic(ang: 20deg)[#lorem(5)]
```
)
== #regex-fakeitalic
`regex-fakeitalic(` \
#h(2em) `reg-exp:` #typebox[str] 默认值: `"[^ ]",` \
#h(2em) `ang:` #typebox[angle] `,` \
#h(2em) `spacing:` #typebox[relative] #typebox[none] 默认值: #typebox[none] `,` \
#h(2em) #typebox[content] \
`)`
`#regex-fakeitalic` 设计上是用于多语言、多字体情境的,可以根据参数 `reg-exp` 内的正则表达式只将匹配到的字符应用伪斜体格式。它也可以接受 `ang` 参数。
#example(
```typst
+ RegExp `[a-o]`: #regex-fakeitalic(reg-exp: "[a-o]")[#lorem(5)]
+ RegExp `\p{script=Han}`: #regex-fakeitalic(reg-exp: "\p{script=Han}")[衬衫的价格是9磅15便士。]
+ RegExp `\p{script=Han}`: #set text(style: "italic"); #regex-fakeitalic(reg-exp: "\p{script=Han}", ang: -10deg)[衬衫的价格是9磅15便士。]
```
)
在上面的例子 \#3 中, `9` 和 `15` 是字体提供的“真”斜体,而其他字符是用 `skew` 变换得到的伪斜体。
== 为什么没有 `show-fakeitalic` 与 `show-cn-fakeitalic`
因为斜体远比我想象中要复杂。斜体与直体、伪斜体与真斜体之间需要留间隔,而我没有找到合适的间隔;不同字体要写不同的角度,很难即开即用。
并且,在 Demo 部分也可以发现:伪粗体的符号间距会出现问题。 |
https://github.com/noamzaks/Barvazim | https://raw.githubusercontent.com/noamzaks/Barvazim/main/writeups/template.typ | typst | #let MONTHS = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
#let writeup(ctf: "", exercise: "", date: datetime.today(), body) = {
set document(author: "<NAME>", title: exercise, date: date)
set page(margin: 1.2cm, footer: [
#set align(center)
#sym.copyright _Team Barvazim #text(blue)[at] #ctf #h(1fr) #MONTHS.at(date.month() - 1) #date.day(), #date.year()_
])
[
= #box(height: 12pt, image("../resources/duck.svg")) #exercise
]
body
} |
|
https://github.com/isaacholt100/isaacholt100.github.io | https://raw.githubusercontent.com/isaacholt100/isaacholt100.github.io/master/maths-notes/2-durham%3A-year-2/ent/ent.typ | typst | #import "../../template.typ": template
#show: template
= Introduction, the natural numbers
- $NN = {1, 2, 3, ...}$
- $NN_0 = {0, 1, 2, 3, ...} = NN union {0}$
- *Peano's axioms*: three primitive terms: $NN_0$, $0$ and *successor function*, $S$.
- $0 in NN_0$.
- $forall a in NN_0, S(a) != 0$.
- $S(a) = S(b) => a = b$.
- If $X subset.eq NN_0$ and
- $0 in X$ and
- $forall a in X, S(a) in X$
then $X = NN_0$.
- Last axiom applied to $X = {n in NN_0: P(n) "true"}$ gives *Principle of Mathematical Induction (PMI)*: for statement $P(n)$, if $P(0)$ true and $forall n in NN_0, P(n) => P(n + 1)$ then $P(n)$ true for every $n in NN_0$.
- *PMI variants*:
- If $P(0)$ true and if for every $n in NN_0$, $P(x)$ for every $x < n$ implies $P(n)$, then $P(n)$ true for every $n in NN_0$.
- Same as two variants above but with base case $P(1)$ true leading to $P(n)$ true for every $n in NN$.
- *Addition of natural numbers*: let $a in NN_0$.
- $a + 0 = a$.
- $a + S(b) = S(a + b)$
- *Well ordering principle (WOP)*: let $S subset.eq NN_0$, $S != nothing$, then $S$ has a smallest element.
= Divisibility
- $a$ *divides* $b$, $a | b$ if $exists d in ZZ, b = a d$. If not, write $a divides.not b$.
- *Properties of divisibility*:
- $a | 0$.
- If $a != 0$, $0 divides.not a$.
- $1 | a$ and $a | a$.
- $a divides b ==> a divides b c$.
- $a divides b$ and $b divides c ==> a divides c$.
- $a divides b$ and $a divides c ==> a divides (b x + c y)$ for any $x, y in ZZ$.
- $a divides b$ and $b divides a ==> a = plus.minus b$.
- $a | b, a > 0, b > 0 ==> a <= b$.
- $a divides b ==> a c divides b c$.
- *Division algorithm*: let $a in ZZ$, $b in NN$. Then exist unique $q$ and $r$ such that $ a = q b + r, quad 0 <= r < b $
- *Common divisor* $d$ of $a$ and $b$ is such that $d | a$ and $d | b$.
- *Greatest common divisor ($gcd$)* of $a$ and $b$ is maximal common divisor.
- *Properties of $gcd$*:
- $gcd(a, b) = gcd(b, a)$.
- If $a > 0$, $gcd(a, 0) = a$.
- $gcd(a, b) = gcd(-a, b)$.
- If $a > 0, b > 0$, $gcd(a, b) <= min{a, b}$.
- For every $a, b, q in ZZ$, $ gcd(a, b) = gcd(a, b - a) = dots.h.c = gcd(a, b - q a) $
- *Euclidean algorithm*: let $a, b in NN$. Repeating the division algorithm: $ a & = q_1 b + r_1 \ b & = q_2 r_1 + r_2 \ r_1 & = q_3 r_2 + r_3 \ & dots.v \ r_(n - 2) & = q_n r_(n - 1) + r_n $ Then exists smallest $n$ such that $r_n = 0$. Then if $n = 1$, $gcd(a, b) = b$, else $gcd(a, b) = r_(n - 1)$. Also, exists $x, y in ZZ$ such that $ gcd(a, b) = a x + b y $
= Primes, composite numbers, and the FTA
- $n in NN$ *prime* if $n > 1$ and if $d | n$ then $d = n$ or $d = 1$. If $n > 1$ not prime, $n$ *composite*.
- There are infinitely many primes.
- There are infinitely many primes of form $4n - 1$.
- *Dirichlet's theorem*: Let $a, b$ coprime. Then exist infinitely many primes of form $a n + b$.
- *Euclid's lemma*: Let $p > 1$. $p$ prime iff for every $a, b in ZZ$, $p divides a b ==> p divides a "or" p divides b$.
- Let $p$ prime. If $p | a_1 dots.h.c a_n$ then $p | a_i$ for some $i$.
- *Fundamental theorem of arithmetic (FTA)*: let $n > 1$, then $n$ can be written as product of primes, unique up to reordering. So exist distinct primes $p_1, ..., p_r$ and $e_1, ..., e_r in NN$ such that $ n = p_1^(e_1) dots.h.c p_r^(e_r) $ and if $n = q_1^(f_1) dots.h.c q_s^(f_s)$ for distinct primes $q_i$, then $r = s$ and up to reordering, $p_i = q_i$ and $e_i = f_i$ for every $i$.
= Classical equations and integer solutions
- *Pythagorean triple* $(x, y, z) in NN^3$: solution to $x^2 + y^2 = z^2$. *Primitive* if $gcd(x, y, z) = 1$.
- Every primitive Pythagorean triple $(x, y, z)$, with $2 divides x$, given by $ cases(
x = 2 s t,
y = s^2 - t^2,
z = s^2 + t^2
) $ with $s > t >= 1$, $gcd(s, t) = 1$ and $s ident.not t quad (mod 2)$.
- *Fermat's theorem*: no integer solutions exist to $x^4 + y^4 = z^2$.
- *Diophantine equation*: equation where integer or rational solutions are sought.
= Modular arithmetic and congruences
- $a$ *congruent to* $b$ *modulo $n$*, $a ident b quad (mod n)$ if $n divides (a - b)$.
- *Residue (congruence) class*: set of integers congruent $mod n$.
- If $a ident b quad (mod n)$ and $a' ident b' quad (mod n)$ then:
- $a + a' ident b + b' quad (mod n)$ and
- $a a' ident b b' quad (mod n)$.
- There are $n$ residue classes $mod n$: $overline(0), overline(1), ..., overline(n - 1)$.
- If $gcd(c, n) = 1$, then $a c ident b c quad (mod n)$ implies $a ident b quad (mod n)$.
- *Complete set of residues mod $n$*: subset $R subset ZZ$ of size $n$ whose remainders $mod n$ are distinct.
- Let $R$ be complete set of residues mod $n$ and let $gcd(a, n) = 1$, then $ a R := {a x: x in RR} $ is also complete set of residues mod $n$.
- *Linear congruence*: $a x ident b quad (mod n)$.
- If $gcd(a, n) = 1$, linear congruence has solution, unique up to adding multiples of $n$ (solutions lie in same congruence class).
- *Method for solving linear congruence* (if $gcd(a, n) = 1$):
- Use Euclidean algorithm to find $u, v$ such that $1 = a u + n v$.
- $a u ident 1 quad (mod n)$ so $a (u b) ident b quad (mod n)$ so solutions are $ x ident u b quad (mod n) $
- Linear congruence solvable iff $gcd(a, n) divides b$.
- *Chinese remainder theorem (CRT)*: let $m, n in NN$ coprime, $a, b in ZZ$. Then exists solution to $ x & ident a quad (mod m) \ x & ident b quad (mod n) $ Any solutions are congruent $mod m n$ and exists unique solution $x$ with $0 <= x < m n$.
- *Method to solve CRT problem*:
- Use Euclidean algorithm to find $r, s$ such that $1 = r m + s n$, so $r m ident 1 quad (mod n)$ and $s n ident 1 quad (mod m)$.
- So $b r m ident b quad (mod n)$ and $a s n ident a quad (mod m)$.
- So $a s n + b r m ident b quad (mod n)$ and $a s n + b r m ident a quad (mod m)$.
- So $x = b r m + a s n$ is solution.
- *Euler $phi$-function*: $phi: NN -> NN$: $ phi(n) := |{r in NN: r <= n "and" gcd(r, n) = 1}| $
- $phi(p) = p - 1$ for prime $p$.
- For prime $p$, $phi(p^n) = p^n - p^(n - 1) = p^(n - 1) (p - 1)$.
- If $gcd(m, n) = 1$, then $phi(m n) = phi(m) phi(n)$.
- Let $n$ have prime factorisation $n = product_(i = 1)^r p_i^(e_i)$. Then $ phi(n) = n product_(i = 1)^r (1 - 1/p_i) $
- Let $n in NN$, then $ sum_(d divides n) phi(d) = n $ where sum is over positive divisors of $n$.
- *Euler's theorem*: For $a in ZZ$, $n in NN$, $gcd(a, n) = 1$, $ a^(phi(n)) ident 1 quad (mod n) $
- *Fermat's little theorem*: let $p$ prime, $a in ZZ$, $p divides.not a$. Then $ a^(p - 1) ident 1 quad (mod p) $
= Primitive roots
- Let $n in NN$, $a in ZZ$, $gcd(a, n) = 1$. *(Multiplicative) order* of $a mod n$, $"ord"_n(a) = "ord"(a)$, is smallest $d in NN$ such that $ a^d ident 1 quad (mod n) $
- If $a^d ident 1 quad (mod n)$ for some $d$, then $"ord"(a) divides d$. So $"ord"(a) divides phi(n)$.
- Let $gcd(a, n) = 1$, $a$ is *primitive root $mod n$* if $"ord"_n(a) = phi(n)$.
- Let $p$ prime, $f(x)$ polynomial with integer coefficients of degree $n$. Then $f$ has at most $n$ roots $mod p$, so $f(x) ident 0 quad (mod p)$ has at most $n$ solutions $mod p$.
- Let $p$ prime, $d divides p - 1$. Then $x^d - 1 ident 0 quad (mod p)$ has exactly $d$ solutions $mod p$.
- Let $p$ prime, then there are $phi(p - 1)$ primitive roots $mod p$.
- Let $g$ primitive root $mod p$, $gcd(a, p) = 1$. Then for some $r in NN$, $ a ident g^r quad (mod p) $ ($g, g^2, ..., g^(p - 1)$ are distinct and form complete set of residues $mod p$).
- Primitive roots $mod n$ exist iff $n = 2, 4, p^k$ or $2 p^k$ for odd prime $p$, $k in NN$.
= Quadratic residues
- Let $p$ prime, $a in ZZ$, $gcd(a, p) = 1$. $a$ is *quadratic residue (QR) $mod p$* if for some $x in ZZ$, $x^2 ident a quad (mod p)$. If not, $a$ is *quadratic non-residue (NQR) $mod p$*.
- For $p$ odd prime, there are $(p - 1)/2$ QR's and $(p - 1)/2$ QNR's $mod p$.
- Products of QR's and NQR's satisfy: $ Q R times Q R = Q R \ Q R times N R = N R \ N R times N R = Q R $
- Let $p$ prime, $a in ZZ$, *Legendre symbol* is $ (a / p) := cases(
1 & "if" a "QR",
-1 & "if" a "NQR",
0 & "if" p divides a
) $
- $ ((a b) / p) = (a / p) (b / p) $
- $(a / p) = (b / p)$ if $a ident b quad (mod p)$.
- *Euler's criterion*: Let $p$ odd prime, $a in ZZ$, $gcd(a, p) = 1$, then $ a^((p - 1)\/2) ident (a / p) quad (mod p) $
- $-1$ is QR if $p ident 1 quad (mod 4)$ and is NQR if $p ident 3 quad (mod 4)$.
- *Quadratic reciprocity law (QRL)*: let $p != q$ odd primes, then $ (p / q) (q / p) = (-1)^((p - 1) / 2 (q - 1) / 2) $ If $p = 2$, $ (2 / q) = (-1)^((q^2 - 1) / 8) $
- *Algorithm for computing Legendre symbol* $(a / p)$:
- Divide $a$ by $p$ to get $a = t p + r$ so $(a / p) = (r / p)$.
- If $r = 0$, $(r / p) = 0$ so stop.
- If $r = 1$, $(r / p) = 1$ so stop.
- If $r != 0, 1$ factorise into primes $r = q_1^(e_1) dots.h.c q_k^(e_k)$ so $(r / p) = product_(i = 1)^k (q_i / p)^(e_i)$.
- $r < p$ so $q_i < p$, so calculate $(q_i / p)$ for each $i$.
- If $q_i = 2$, use $(2 / p) = (-1)^((p^2 - 1)/8)$.
- If $q_i > 2$, use $(q_i / p) = (-1)^(((q_i - 1)(p - 1))/4) (p / q_i)$ and go to step $1$ to calculate $(p / q_i)$.
- *Note*: to evaluate $((-1) / p)$, easier to use Euler's criterion.
- There are infinitely many primes of form $4n + 1$.
= Sums of two squares
- If $m$ and $n$ are sums of two squares, then so is $m n$ since $(a^2 + b^2) (c^2 + d^2) = (a c + b d)^2 + (a d - b c)^2$.
- Let $p$ odd prime. Then $p$ sum of two squares iff $p ident 1 quad (mod 4)$ (and if $p ident 1 quad (mod 4)$, this sum of two squares is unique).
- Let $n > 1$, $n = p_1 p_2 dots.h.c p_k N^2$, $p_i$ distinct primes, $N in NN$. Then $n$ sum of two squares iff $p_i = 2$ or $p_i ident 1 quad (mod 4)$ for all $i$.
= Continued fractions
- *Finite continued fraction (CF)*: $ [a_0; a_1, ..., a_n] = a_0 + 1/(a_1 + 1/(dots.down + 1/a_n)) $
- *Simple* CF: $a_0 in ZZ$, $a_1, ..., a_n in NN$.
- Any rational number can be written as finite simple continued fraction.
- *$k$th convergent* of CF $[a_0; a_1, ..., a_n]$: $ C_k := [a_0; a_1, ..., a_k] $
- $C_n = p_n \/ q_n$, where $ mat(p_k, p_(k - 1); q_k, q_(k - 1)) = mat(a_0, 1; 1, 0) mat(a_1, 1; 1, 0) dots.h.c mat(a_k, 1; 1, 0) $ so $p_1 = a_0 a_1 + 1$, $p_0 = a_0$, $q_1 = a_1$, $q_0 = 1$ and $p_k = a_k p_(k - 1) + p_(k - 2)$, $q_k = a_k q_(k - 1) + q_(k - 2)$
- If $[a_0; a_1, ..., a_n]$ is simple CF, then $q_(k - 1) <= q_k$ and $q_(k - 1) < q_k$ if $k > 1$.
- $ p_k q_(k - 1) - q_k p_(k - 1) = (-1)^(k + 1) $
- $gcd(p_k, q_k) = 1$.
- Let $alpha = [a_0; a_1, ..., a_n]$, $k = 0, ..., n - 1$, then even numbered convergents increasing: $ C_0 < C_2 < dots.h.c < C_(2m)$, odd numbered convergents decreasing $C_(2m + 1) < dots.h.c < C_3 < C_1$ and for every $k$ with $2k + 1 <= n$, $ p_(2k) / q_(2k) < alpha <= p_(2k + 1) / q_(2k + 1) $ and $ |alpha - p_k / q_k| <= 1/(q_k q_(k + 1)) $
- *Infinite CF* $[a_0; a_1, ...]$ is limit of convergents $C_n = [a_0; a_1, ..., a_n]$.
- For simple infinite CF, limit always exists.
- *Pell's equation*: $x^2 - d y^2 = 1$, $d in NN$ not square.
- *Negative Pell's equation*: $x^2 - d y^2 = -1$.
- Infinite CF *periodic* if of form $ [a_0; a_1, ..., a_m, a_(m + 1), ..., a_(m + n), a_(m + 1), ..., a_(m + n), ...] $ $a_0; a_1, ..., a_m$ is initial part, $a_(m + 1), ..., a_(m + n), a_(m + 1), ..., a_(m + n), ...$ is periodic part. In periodic part, $a_i = a_j$ if $i ident j quad (mod n)$. Write as $ [a_0; a_1, ..., a_m, overline(a_(m + 1)\, ...\, a_(m + n))] $ $n$ is *period*.
- If $d$ not square, CF of $sqrt(d)$ is periodic with initial part only $a_0$.
- Let $p_k \/ q_k$ be convergents of simple CF expansion of $sqrt(d)$ with period $n$, then for all $k >= 1$, $ p_(k n - 1)^2 - d q_(k n - 1)^2 = (-1)^(k n) $
- So if $n$ even or $k$ even, $(x, y) = (p_(k n - 1), q_(k n - 1))$ are solution to Pell's equation. Else $(x, y) = (p_(k n - 1), q_(k n - 1))$ are solution to negative Pell's equation. *All* positive solutions to (negative) Pell equation given by above. |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/184.%20fh.html.typ | typst | fh.html
Haters
January 2020(I originally intended this for startup founders, who are often
surprised by the attention they get as their companies grow, but
it applies equally to anyone who becomes famous.)If you become sufficiently famous, you'll acquire some fans who
like you too much. These people are sometimes called "fanboys," and
though I dislike that term, I'm going to have to use it here. We
need some word for them, because this is a distinct phenomenon from
someone simply liking your work.A fanboy is obsessive and uncritical. Liking you becomes part of
their identity, and they create an image of you in their own head
that is much better than reality. Everything you do is good, because
you do it. If you do something bad, they find a way to see it as
good. And their love for you is not, usually, a quiet, private one.
They want everyone to know how great you are.Well, you may be thinking, I could do without this kind of obsessive
fan, but I know there are all kinds of people in the world, and if
this is the worst consequence of fame, that's not so bad.Unfortunately this is not the worst consequence of fame. As well
as fanboys, you'll have haters.A hater is obsessive and uncritical. Disliking you becomes part of
their identity, and they create an image of you in their own head
that is much worse than reality. Everything you do is bad, because
you do it. If you do something good, they find a way to see it as
bad. And their dislike for you is not, usually, a quiet, private
one. They want everyone to know how awful you are.If you're thinking of checking, I'll save you the trouble. The
second and fifth paragraphs are identical except for "good" being
switched to "bad" and so on.I spent years puzzling about haters. What are they, and where do
they come from? Then one day it dawned on me. Haters are just fanboys
with the sign switched.Note that by haters, I don't simply mean trolls. I'm not talking about
people who say bad things about you and then move on. I'm talking
about the much smaller group of people for whom this becomes a
kind of obsession and who do it repeatedly over a long period.Like fans, haters seem to be an automatic consequence of fame.
Anyone sufficiently famous will have them. And like fans, haters
are energized by the fame of whoever they hate. They hear a song
by some pop singer. They don't like it much. If the singer were an
obscure one, they'd just forget about it. But instead they keep
hearing her name, and this seems to drive some people crazy.
Everyone's always going on about this singer, but she's no good!
She's a fraud!That word "fraud" is an important one. It's the spectral signature
of a hater to regard the object of their hatred as a
fraud. They
can't deny their fame. Indeed, their fame is if anything exaggerated
in the hater's mind. They notice every mention of the singer's name,
because every mention makes them angrier. In their own minds they
exaggerate both the singer's fame and her lack of talent, and the
only way to reconcile those two ideas is to conclude that she has
tricked everyone.What sort of people become haters? Can anyone become one? I'm not
sure about this, but I've noticed some patterns. Haters are generally
losers in a very specific sense: although they are occasionally
talented, they have never achieved much. And indeed, anyone
successful enough to have achieved significant fame would be unlikely
to regard another famous person as a fraud on that account, because
anyone famous knows how random fame is.But haters are not always complete losers. They are not always the
proverbial guy living in his mom's basement. Many are, but some
have some amount of talent. In fact I suspect that a sense of
frustrated talent is what drives some people to become haters.
They're not just saying "It's unfair that so-and-so is famous," but
"It's unfair that so-and-so is famous, and not me."Could a hater be cured if they achieved something impressive? My
guess is that's a moot point, because they
never will. I've been
able to observe for long enough that I'm fairly confident the pattern
works both ways: not only do people who do great work never become
haters, haters never do great work. Although I dislike the word
"fanboy," it's evocative of something important about both haters
and fanboys. It implies that the fanboy is so slavishly predictable in his admiration
that he's diminished as a result, that he's less than a man.Haters seem even more diminished. I can imagine being a fanboy.
I can think of people whose work I admire so much that I could abase
myself before them out of sheer gratitude. If <NAME> were
still alive, I could see myself being a Wodehouse fanboy. But I
could not imagine being a hater.Knowing that haters are just fanboys with the sign bit flipped makes
it much easier to deal with them. We don't need a separate theory
of haters. We can just use existing techniques for dealing with
obsessive fans.The most important of which is simply not to think much about them.
If you're like most people who become famous enough to acquire
haters, your initial reaction will be one of mystification. Why
does this guy seem to have it in for me? Where does his obsessive
energy come from, and what makes him so appallingly nasty? What did
I do to set him off? Is it something I can fix?The mistake here is to think of the hater as someone you have a
dispute with. When you have a dispute with someone, it's usually a
good idea to try to understand why they're upset and then fix things
if you can. Disputes are distracting. But it's a false analogy to
think of a hater as someone you have a dispute with. It's an
understandable mistake, if you've never encountered haters before.
But when you realize that you're dealing with a hater, and what a
hater is, it's clear that it's a waste of time even to think about
them. If you have obsessive fans, do you spend any time wondering
what makes them love you so much? No, you just think "some
people are kind of crazy," and that's the end of it.Since haters are equivalent to fanboys, that's the way to deal with
them too. There may have been something that set them off. But it's
not something that would have set off a normal person, so there's
no reason to spend any time thinking about it. It's not you, it's
them.Notes[1] There are of course some people who are genuine frauds. How can
you distinguish between x calling y a fraud because x is a hater,
and because y is a fraud? Look at neutral opinion. Actual frauds
are usually pretty conspicuous. Thoughtful people are rarely taken
in by them. So if there are some thoughtful people who like y, you
can usually assume y is not a fraud.[2] I would make an exception for teenagers, who sometimes act in
such extreme ways that they are literally not themselves. I can
imagine a teenage kid being a hater and then growing out of it. But
not anyone over 25.[3] I have a much worse memory for misdeeds than my wife Jessica,
who is a connoisseur of character, but I don't wish it were better.
Most disputes are a waste of time even if you're in the right, and
it's easy to bury the hatchet with someone if you can't remember
why you were mad at them.[4] A competent hater will not merely attack you individually but
will try to get mobs after you. In some cases you may want to refute
whatever bogus claim they made in order to do so. But err on the
side of not, because ultimately it probably won't matter.Thanks to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME> for reading drafts of this.Japanese TranslationArabic TranslationPolish Translation
|
|
https://github.com/J3m3/poolc-fp | https://raw.githubusercontent.com/J3m3/poolc-fp/main/HFPDWE-02.typ | typst | MIT License | #import "@preview/fletcher:0.3.0" as fletcher: node, edge
#import "@preview/pinit:0.1.3": *
#import "@preview/sourcerer:0.2.1": code
#import "@preview/xarrow:0.3.0": xarrow
#import "lib/index.typ": *
#show: conf
// 1
#title-slide(title: "How FP Deals With Effects")[
#line(length: 65%, stroke: 2pt + color_medium)
#poolc_badge #h(.3em) 양제성
#v(.5em)
#set text(size: fontsize_small)
#let date = datetime(year: date.year(), month: date.month() + 1, day: 7).display(
"[year]/[month]/[day] ([weekday repr:short])"
)
Source: #github_hypericon #h(1em) #date
]
// 2
#slide(title: "목차")[
#set enum(number-align: start)
#let left = {
set text(fill: rgb(0, 0, 0, 50%))
tbc(title: "1st Session", (
(
"함수형 프로그래밍 Intro",
"Overall Structure", "Historical Review (CS + Math)"
),
(
"함수형 패러다임",
"Core of Functional Thinking", "FP Fact-Checking"
),
(
"FP는 정말 순수한가?",
"Optimizing with Purity", "Effect Handling Basics"
)
))
}
#let right = {
tbc(title: "2nd Session", (
(
"Lazy Evaluation",
"How Lazy Evaluation Works", "Infinite Data Structure", "Laziness & Purity"
),
(
"From Functor to Monad",
"Functor in PL", "Monad in PL"
),
(
"Impurity in Pure World?",
"Side Effect in Pure World", "Uniqueness Typing", "IO Monad"
)
))
}
#align(center)[#grid(
columns: (1fr, 1em, 1fr),
left,
[],
right
)]
]
// 3 ~ 4
#absolute-center-slide(title: "How Lazy Evaluation Works", header: "Lazy Evaluation")[
#{[
#set text(size: fontsize_big)
_"Evaluation on demand"_
]}
#only(2)[#text(font: "MesloLGS NF", size: 45pt)[_\<Let's code!\>_]]
]
// 5
#absolute-center-slide( title: "How Lazy Evaluation Works", header: "Lazy Evaluation")[
#{[
#set text(size: fontsize_big)
_Thunk_: "A delayed computation"
]}
]
// 6
#relative-center-slide(title: "How Lazy Evaluation Works", header: "Lazy Evaluation")[
#box(width: 90%)[#code(lang: "Haskell", line-spacing: 9pt, ```hs
xs = [1 .. 10] ++ undefined -- Thunk
ys = take 3 xs -- Thunk
main = print ys -- Force evaluation lazily
{-
print (take 3 xs)
print (take 3 ([1 .. 10] ++ undefined))
print (1 : take 2 ([2 .. 10] ++ undefined))
print (1 : 2 : take 1 ([3 .. 10] ++ undefined))
print (1 : 2 : 3 : take 0 ([4 .. 10] ++ undefined))
print (1 : 2 : 3 : [])
print [1, 2, 3]
-}
```)]
]
// 7 ~ 8
#absolute-center-slide(title: "Infinite Data Structure", header: "Lazy Evaluation")[
#set text(size: 45pt)
```hs
ones :: [Int]
ones = 1 : ones
```
#only(2)[#set text(size: fontsize_big)
```hs
ones = 1 : ones
ones = 1 : 1 : ones
ones = 1 : 1 : 1 : ones
```]
]
// 9
#relative-center-slide(title: "Infinite Data Structure", header: "Lazy Evaluation")[
#box(width: 90%)[#code(lang: "Haskell", line-spacing: 9pt, ```hs
ones = 1 : ones -- Infinite list
main = print (take 3 ones)
{-
print (take 3 ones)
print (1 : take 2 ones)
print (1 : 1 : take 1 ones)
print (1 : 1 : 1 : take 0 ones)
print (1 : 1 : 1 : [])
print [1, 1, 1]
-}
```)]
]
// 10
#absolute-center-slide(title: "Infinite Data Structure", header: "Lazy Evaluation")[
#text(font: "MesloLGS NF", size: 45pt)[_\<Let's code!\>_]
#v(-1em)
#{[
#set text(size: fontsize_big)
Let's see more interesting examples...
]}
]
// 11
#absolute-center-slide(title: "Laziness & Purity", header: "Lazy Evaluation")[
#{[
#set text(size: fontsize_big)
_"Laziness (generally) needs purity"_
]}
]
// 12
#absolute-center-slide(title: "Laziness & Purity", header: "Lazy Evaluation")[
_Scenario: file pointer-based sequential read_ \
Assume that we are reading a config file structured like below.
#box(stroke: 1pt)[
#set text(font: "MesloLGS NF")
#let header = box(fill: rgb(255, 0, 0, 30), inset: .5em)[header]
#let basic = box(fill: rgb(0, 255, 0, 30), width: 45%, inset: .5em)[basic]
#let extended = box(fill: rgb(0, 0, 255, 30), inset: .5em)[extended]
#header#basic#extended
]
]
// 12 ~ 18
#absolute-center-slide(title: "Laziness & Purity", header: "Lazy Evaluation")[
#only("1-3")[#align(left)[
Expected:
#set text(size: fontsize_small, baseline: -2.5pt)
`readHeader` -> `readBasicConfig` -> `readExtendedConfig`
]]
#only("4-6")[#align(left)[
Lazy case:
#set text(size: fontsize_small, baseline: -2.5pt)
`readBasicConfig` -> `readHeader` -> `readExtendedConfig`
]]
#v(1em)
#box(stroke: 1pt)[
#set text(font: "MesloLGS NF")
#let header = box(fill: rgb(255, 0, 0, 30), inset: .5em)[header#pin("1")]
#let basic = box(fill: rgb(0, 255, 0, 30), width: 45%, inset: .5em)[basic#pin("2")]
#let extended = box(fill: rgb(0, 0, 255, 30), inset: .5em)[extended#pin("3")]
#header#basic#extended
#set text(size: fontsize_small)
#only(1)[#pinit-point-from(
pin-dx: 13pt,
body-dx: -45pt,
offset-dx: -45pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"1"
)[ptr]]
#only(2)[#pinit-point-from(
pin-dx: 139pt,
body-dx: -45pt,
offset-dx: 81pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"2"
)[ptr]]
#only(3)[#pinit-point-from(
pin-dx: 13pt,
body-dx: -45pt,
offset-dx: -45pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"3"
)[ptr]]
#only(4)[#pinit-point-from(
pin-dx: 238pt,
body-dx: -45pt,
offset-dx: 180pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"1"
)[ptr]]
#only(5)[#pinit-point-from(
pin-dx: 139pt,
body-dx: -45pt,
offset-dx: 81pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"2"
)[ptr]]
#only(6)[#pinit-point-from(
pin-dx: 13pt,
body-dx: -45pt,
offset-dx: -45pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
"3"
)[ptr]]
]
#box(width: 95%)[#code(line-spacing: 9pt, ```hs
getConfig :: File -> Config
getConfig f =
let
header = readHeader f
basic = readBasicConfig f
extended = readExtendedConfig (headerVersion header) f
in Config basic extended
```)]
]
// 19
#absolute-center-slide(title: "Functor in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
#let F = text(fill: blue)[F]
A #text(fill: color_dark)[type #pin("1")constructor] #F is a Functor if
#pinit-point-from(
pin-dx: 35pt,
body-dx: 10pt,
offset-dx: 65pt,
pin-dy: -30pt,
body-dy: -10pt,
offset-dy: -50pt,
thickness: 2pt,
"1"
)[
#set text(size: fontsize_small)
`i.e. List, Maybe(Optional, Option)`
]
#text(font: "MesloLGS NF", size: fontsize_medium)[
fmap :: (T -> U) -> (#F\<T\> -> #F\<U\>) #text(fill: gray)[(= lift)]
]
is given. (for arbitrary types T, U)
]
// 20
#absolute-center-slide(title: "Functor in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
#set enum(number-align: start + top)
#text(size: 35pt)[_Functor laws_]
+ #align(left)[`fmap (id) ≡ id (where id x = x)`]
+ #align(left)[
`fmap (f ∘ g) ≡ (fmap f) ∘ (fmap g)` \
#set text(size: fontsize_small)
Haskell ver. ` fmap (f . g) ≡ (fmap f) . (fmap g)`
]
]
// 21
#absolute-center-slide(title: "Functor in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
How can we implement `fmap` for _`Maybe`_?
]
// 22 ~ 28
#relative-center-slide(title: "Functor in PL", header: "From Functor to Monad")[
#v(1em)
#set text(size: fontsize_big)
#let Maybe = text(fill: blue)[Maybe]
#only("1-4")[#text(font: "MesloLGS NF", size: fontsize_medium)[
fmap :: #box(fill: color_light, outset: 7pt, radius: .2em)[(T -> U)]#pin("1")
-> #box(fill: color_light, outset: 7pt, radius: .2em)[
(#Maybe\<T\> -> #Maybe\<U\>)
]#pin("2")
#pinit-place(
dx: -67pt,
dy: -55pt,
"1"
)[f]
#pinit-place(
dx: -210pt,
dy: -55pt,
"2"
)[fmap f]
]]
#only(2)[#code(line-spacing: 12pt, ```rs
fn fmap_f<T, U>(opt_t: Maybe<T>) -> Maybe<U> {
if (opt_t.is_nothing())
return Maybe<U>();
else
return Maybe<U>(f(opt_t.value()));
}
```)]
#only(3)[
#set text(size: fontsize_medium - 1pt)
#code(line-spacing: 12pt, ```rs
fn fmap<T, U>(f: T -> U) -> (Maybe<T> -> Maybe<U>) {
fn fmap_f<T, U>(opt_t: Maybe<T>) -> Maybe<U> {
if (opt_t.is_nothing())
return Maybe<U>();
else
return Maybe<U>(f(opt_t.value()));
}
return fmap_f;
}
```)
]
#only(4)[
#text(font: "MesloLGS NF", size: fontsize_medium, fill: haskell_color)[
fmap :: (a -> b) -> Maybe a -> Maybe b
]
]
#only("5-6")[
#v(-1em)
```hs data Maybe a = Nothing | Just a```
]
#only(6)[
#block[
#align(left)[#text[
```hs fmap :: (a -> b) -> Maybe a -> Maybe b``` \
```hs fmap f (Just x) = Just (f x)``` \
```hs fmap _ Nothing = Nothing```
]]
]
]
#only(7)[
```hs
type Functor :: (* -> *) -> Constraint
class Functor f where
fmap :: (a -> b) -> f a -> f b
(<$) :: a -> f b -> f a
{-# MINIMAL fmap #-}
```
]
]
// 29 ~ 30
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
#let M = text(fill: blue)[M]
#block[
A Functor #M is a Monad if
#align(left)[
#text(font: "MesloLGS NF", size: fontsize_medium)[
#only(1)[
#text(fill: gray)[fmap :: (T -> U) -> #M\<T\> -> #M\<U\> (= lift)] \
return :: T -> #M\<T\> #text(fill: gray)[
#text(size: 25pt)[` `] (= unit)
] \
join :: #M\<#M\<T\>\> -> #M\<T\> #text(fill: gray)[
#text(size: 25pt)[` `] (= flat)
]
]
#only(2)[
#text(fill: gray)[
fmap :: (T -> U) -> #M\<T\> -> #M\<U\>
#text(size: 20pt)[` `] (= lift)
] \
return :: T -> #M\<T\> #text(fill: gray)[
#text(size: 26pt)[` `] (= unit)
] \
bind :: #M\<T\> -> ((T -> #M\<U\>) -> #M\<U\>) #text(fill: gray)[
(≡ flatMap)
]
#set text(size: fontsize_small)
#text(font: "Pretendard")[Haskell ver.]` ` (>>=) :: #M a -> (a -> #M b) -> #M b
]
]
]
is given. (for arbitrary types T, U)
]
]
// 31
#relative-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
#set enum(number-align: start + top)
#text(size: 35pt)[_Monad laws_]
+ #align(left)[
`bind m return ≡ m` \
#set text(size: fontsize_small)
Haskell ver. ` m >>= return ≡ m`
]
+ #align(left)[
`bind (return x) f ≡ f x` \
#set text(size: fontsize_small)
Haskell ver. ` return x >>= f ≡ f x`
]
+ #align(left)[
`bind (bind m f) g ≡ bind m (\x -> f x >>= g)` \
#set text(size: fontsize_small)
Haskell ver. ` (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g)`
]
]
// 32 ~ 36
#relative-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
#set enum(number-align: start + top)
#text(size: 35pt)[_Semantic of Monad_]
#let moand_in_math = "A monoid in the category of endofunctors"
#block[#align(left)[
#only(1)["#moand_in_math"]
#only(2)[#strike["#moand_in_math"]]
#only(3)[
#set text(size: fontsize_medium)
#set list(marker: ("•", "∘"), indent: .5em)
If M is a Monad, M\u{003C}T\u{003E} is an _extension of T_, where
- operations on T can also be extended
- the same extension on itself(i.e. M\<M\<T\>\>) is
- meaningless, or
- logically equial to the original, or
- can be seen as the original in some aspect
]
#only(4)[
#set text(size: fontsize_medium)
- Maybe \<T\>: T or Nothing
- Maybe \<Maybe \<T\>\>: T or Nothing or Nothing
\ ` `= Maybe \<T\>
_Meaning is preserved!_ (but type changed)
- return :: T -> Maybe \<T\>
- join :: Maybe \<Maybe \<T\>\> -> Maybe \<T\>
]
#only(5)[
#set text(size: fontsize_medium)
- List \<T\>: bunch of Ts
- List \<List \<T\>\>: bunch of bunches of Ts
\ ` `≃ List \<T\>
_Meaning is preserved!_ (but type changed)
- return :: T -> List \<T\>
- join :: List \<List \<T\>\> -> List \<T\>
]
]]
]
// 37
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
How can we implement `return` for _`Maybe`_?
]
// 38 ~ 39
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(1em)
#set text(size: fontsize_big)
#set enum(number-align: start + top)
#let Maybe = text(fill: blue)[Maybe]
#only("1-")[#text(font: "MesloLGS NF", size: fontsize_medium)[
return :: T -> #Maybe\<T\>
]]
#only(2)[#code(line-spacing: 12pt, ```rs
fn returnM<T>(t: T) -> Maybe<T> {
return Maybe<T>(t);
}
```)]
]
// 40
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(-1em)
#set text(size: fontsize_big)
How can we implement `bind` for _`Maybe`_?
]
// 41 ~ 44
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#v(1em)
#set text(size: fontsize_big)
#set enum(number-align: start + top)
#let Maybe = text(fill: blue)[Maybe]
#only(("1", "4-"))[#text(font: "MesloLGS NF", size: fontsize_medium)[
bind :: #Maybe\<T\> -> ((T -> #Maybe\<U\>) -> #Maybe\<U\>)
]]
#only("2-3")[#text(font: "MesloLGS NF", size: fontsize_medium)[
bind :: (#Maybe\<T\>, (T -> #Maybe\<U\>)) -> #Maybe\<U\>
]]
#only(3)[
#set text(size: fontsize_medium)
#code(line-spacing: 12pt, ```rs
fn bind<T, U>(m: Maybe<T>, f: T -> Maybe<U>) -> Maybe<U> {
if (m.is_nothing())
return Maybe<U>();
else
return f(m.value());
}
```)
]
#only(4)[
#set text(size: fontsize_medium)
#code(line-spacing: 12pt, ```rs
fn bind<T, U>(m: Maybe<T>) -> ((T -> Maybe<U>) -> Maybe<U>) {
fn bind_f(f: T -> Maybe<U>) {
if (m.is_nothing())
return Maybe<U>();
else
return f(m.value());
}
return bind_f;
}
```)
]
]
// 45
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
#let Maybe = text(fill: blue)[Maybe]
#block[#align(left)[
#set text(font: "MesloLGS NF", size: fontsize_medium)
return :: T -> #Maybe\<T\> \
#text(font: "MesloLGS NF", size: fontsize_medium, fill: haskell_color)[
return :: a -> #Maybe a
]
bind :: #Maybe\<T\> -> ((T -> #Maybe\<U\>) -> #Maybe\<U\>) \
#text(font: "MesloLGS NF", size: fontsize_medium, fill: haskell_color)[
(>>=) :: #Maybe a -> (a -> #Maybe b) -> #Maybe b
]
]]
]
// 46 ~ 47
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
```hs data Maybe a = Nothing | Just a```
#only(1)[#block[
#align(left)[#text[
```hs return :: a -> Maybe a``` \
```hs return x = Just x```
]]
]]
#only(2)[#block[
#align(left)[#text[
```hs
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
(Just x) >>= f = f x
Nothing >>= _ = Nothing
```
]]
]]
]
// 48
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
```hs
type Monad :: (* -> *) -> Constraint
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
{-# MINIMAL (>>=) #-}
```
]
// 49 ~ 51
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(size: fontsize_big)
Any use cases of _Monad_ and _`bind`_? \
#set text(size: fontsize_medium)
#only("2-")[Scenario: Multiple HTTP requests dependent on each other]
#only(3)[#text(font: "MesloLGS NF", size: 45pt)[_\<Let's code!\>_]]
]
// 52
#absolute-center-slide(title: "Monad in PL", header: "From Functor to Monad")[
#set text(font: "MesloLGS NF")
f :: a -> #box(outset: .3em, radius: .2em, fill: color_light)[Maybe b] \
g :: #box(outset: .3em, radius: .2em, fill: color_light)[b] -> Maybe c \
#block[
#align(left)[#text[
(>>=) :: Maybe b -> (b -> Maybe c) -> Maybe c \
f x >>= g :: Maybe c
]]
]
]
// 53
#absolute-center-slide(title: "Side Effect in Pure World", header: "Impurity in Pure World?")[
#block(width: 90%)[
#code(lang: "Haskell", line-spacing: 12pt, ```hs
whatIsYourName :: IO ()
whatIsYourName = do
putStr "What is your name? "
firstName <- getLine -- same input!
lastName <- getLine -- same input!
putStrLn ("Hello, " ++ firstName ++ " " ++ lastName)
```)
]
]
// 54
#absolute-center-slide(title: "Side Effect in Pure World", header: "Impurity in Pure World?")[
#set enum(number-align: start + top)
#block(width: 70%)[
+ #align(start)[What is IO in the type signature?]
+ #align(start)[How can we perform side effects in a language where side effects are not allowed?]
]
]
// 55
#absolute-center-slide(title: "Uniqueness Typing", header: "Impurity in Pure World?")[
#block(width: 80%)[#align(left)[
"A value with a _unique type_ is _guaranteed to have at most one reference to it at run-time_, which means that it can safely be updated in-place, reducing the need for memory allocation and garbage collection."
]]
$italic("The Idris Tutorial")$
]
// 56
#absolute-center-slide(title: "Uniqueness Typing", header: "Impurity in Pure World?")[
#block(width: 90%)[
#code(lang: "Clean", line-spacing: 12pt, ```ocaml
module hello
import StdEnv
Start :: *World -> *World
Start world
# (console, world) = stdio world
# console = fwrites "Hello, World!\n" console
# (ok, world) = fclose console world
| not ok = abort "ERROR: cannot close console\n"
| otherwise = world
```)
]
]
// 57
#absolute-center-slide(title: "IO Monad", header: "Impurity in Pure World?")[
#set text(size: fontsize_big)
Let's _hide "World"_ from users!
]
// 58 ~ 59
#absolute-center-slide(title: "IO Monad", header: "Impurity in Pure World?")[
#v(1.5em)
#set text(size: fontsize_medium - 1pt)
#block(width: 90%)[
#code(lang: "Haskell", line-spacing: 13pt, ```hs
type WorldT a = World -> (a, World)
readStrT :: WorldT String
readStrT = readStr
printStrT :: String -> WorldT ()
printStrT str world = ((), printStr str world)
(>>>=) :: WorldT a -- World -> (a, World)
-> (a -> WorldT b) -- a -> World -> (b, World)
-> WorldT b -- World -> (b, World)
m >>>= f = uncurry f . m
whatIsYourPureNameT :: WorldT ()
whatIsYourPureNameT =
printStrT "What is your name?" >>>= \_ ->
readStrT >>>= \firstName ->
readStrT >>>= \lastName ->
printStrT ("Hello, " ++ firstName ++ " " ++ lastName)
```)
]
] |
https://github.com/Complex2-Liu/macmo | https://raw.githubusercontent.com/Complex2-Liu/macmo/main/contests/2023/content/problem-05.typ | typst | #import "../lib/math.typ": problem, solution, note, ans
#problem[
求 $(b c) / (2a^2 + b c) + (a b) / (2c^2 + a b) + (a c) / (2b^2 + a c)$ 的最小值,
其中 $a, b, c$ 为任意正实数.
]
#solution[
作换元 $x = sqrt(b c), y = sqrt(a b), z = sqrt(a c)$, 问题归结于求
$ S := x^4 / (2y^2 z^2 + x^4) + y^4 / (2z^2 x^2 + y^4) + z^4 / (2x^2 y^2 + z^4) $
的最小值, 利用 Cauchy 不等式便有 $ S >= (x^2 + y^2 + z^2)^2 /
(x^4 + y^4 + z^4 + 2x^2 y^2 + 2y^2 z^2 + 2z^2 x^2) = ans(1.) $
]
/* vim: set ft=typst: */
|
|
https://github.com/darkMatter781x/OverUnderNotebook | https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/pros/pros.typ | typst | #import "/packages.typ": notebookinator, gentle-clues
#import notebookinator: *
#import themes.radial.components: *
#import gentle-clues: *
#import "/util.typ": qrlink
#show: create-body-entry.with(
title: "Decide: PROS",
type: "decide",
date: datetime(year: 2024, month: 1, day: 15),
author: "<NAME>",
)
= PROS
PROS is an open source operating system for the v5 brain.
== Benefits
- Allows us to utilize modern development tools like Visual Studio Code (VSCode)
- Builtin integration with git and github
- VSCode permits our team to use extensions that enhance our workflow. These
include:
- #link(
"https://marketplace.visualstudio.com/items?itemName=sigbots.pros",
)[PROS]: automatically installs the pros toolchain and provides a gui and
commands to use it
- #link(
"https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.vscode-clangd",
)[clangd]: advanced intellisense engine for c++ using the open source clang
compiler
- #link(
"https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker",
)[Code Spell Checker]: prevents spelling mistakes
- #link(
"https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph",
)[Git Graph]: provides a visualization of the git commit history
- #link(
"https://marketplace.visualstudio.com/items?itemName=cschlosser.doxdocgen",
)[Doxygen Documentation Generator]: aides in documenting code
- #link(
"https://marketplace.visualstudio.com/items?itemName=GitHub.copilot",
)[Github Copilot]: provides ai autocomplete and aides in documenting code
- and many others
#info[
VEX does have an vexcode extension for vscode, but it is still in beta and it is
not yet as sophisticated as PROS.
]
- Enables the use of libraries like:
- #link("https://github.com/LemLib/LemLib")[LemLib] - an open source library with
a focus on odometry and motion algorithms.
- Odometry: enables tracking the robot's location local to the field
- Boomerang: efficient algorithm to a move robot to a point and a heading
- Pure Pursuit: algorithm to follow a complex path
- Move to Point: algorithm to move the robot to a point
- Hot / Cold linking: Pros downloads two different binaries to the brain which are
then linked on the brain.
- Cold package: Includes pros's builtin library and other libraries like LemLib
that will be infrequently modified
- Hot package: contains frequently modified code like user code.
-
By segmenting these binaries, it makes uploading an updated hot package code
significantly quicker and saves valuable time when performing iterative testing.
|
|
https://github.com/j10ccc/zjut-social-practice-report-typst | https://raw.githubusercontent.com/j10ccc/zjut-social-practice-report-typst/main/example.typ | typst | #import "/layout/project.typ": project
#let meta = (
"学 院": "我的学院",
"专 业": "我的专业",
"实践报告": "一个响亮的报告名",
"姓 名": "我的名字",
"学 号": "我的学号",
"指导老师": "项目的指导老师",
"完成日期": "项目的完成时间"
)
#show: project.with(..meta)
#rect()[
#text("为了展示目录和正文排版效果,下面的内容是 AI 生成的,不要当作模板来参考。")
]
= 实践目的和背景
本次社会实践的目的是为了增强学生的社会实践能力,提高他们的社会责任感和团队合作能力。背景是在当前社会发展的背景下,学生需要更多地了解社会现实,培养实践能力,为将来的职业发展做好准备。
= 实践内容和方法
== 实践内容
本次实践的内容是参与社区义工活动。我们选择了一个当地的社区,与社区居民一起开展各种活动,包括清洁环境、植树造林、为老人提供帮助等。
== 实践方法
我们采用了多种实践方法,包括实地调研、参与活动、与社区居民交流等。通过实地调研,我们了解到社区存在的问题和需求,然后根据需求选择相应的活动参与。在活动中,我们与社区居民一起工作,共同完成任务,并与他们交流,了解他们的生活情况和需求。
= 实践过程和经验
== 实践过程
在实践过程中,我们首先进行了社区调研,了解到社区居民对环境卫生和社区建设的需求。然后,我们与社区居民一起参与了清洁环境的活动,清理了社区周边的垃圾,并进行了环境整治。接着,我们参与了植树造林的活动,为社区增添了绿色。最后,我们为社区的老人提供了帮助,包括购物、打扫卫生等。
== 实践经验
通过这次实践,我们深刻体会到了团队合作的重要性。只有团结一致,共同努力,才能完成任务。同时,我们也学会了倾听和关心他人的需求,提供帮助。这次实践还增强了我们的社会责任感,让我们更加关注社会问题,并积极参与解决。
= 实践成果和影响
== 实践成果
通过我们的努力,社区的环境得到了改善,居民的生活质量得到了提高。我们的参与和帮助得到了社区居民的认可和赞赏。
== 实践影响
这次实践不仅对我们个人有着积极的影响,提高了我们的实践能力和社会责任感,还对社区产生了积极的影响。我们的参与让社区居民感受到了社会的温暖和关爱,激发了他们对社区建设的热情。
= 实践总结和展望
== 实践总结
通过这次社会实践,我们深刻认识到了社会的复杂性和多样性,增强了我们的社会实践能力和团队合作能力。我们也更加明确了自己的职业发展方向,希望将来能够继续参与社会实践,为社会做出更多的贡献。
== 实践展望
未来,我们希望能够继续参与社会实践,扩大实践的范围和影响力。我们将继续关注社会问题,积极参与解决,为社会的发展做出自己的贡献。同时,我们也希望能够将实践经验和成果分享给更多的人,激发更多人的社会责任感和参与意识。 |
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/markup/strong.typ | typst | Apache License 2.0 | This is *strong.* \
This is #strong[too.] \
#show strong: set text(red)
And this is *evermore.*
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/super_script/super_script.typ | typst | First#super[super text]
Normal text
Second#super[super text] |
|
https://github.com/wenjia03/JSU-Typst-Template | https://raw.githubusercontent.com/wenjia03/JSU-Typst-Template/main/Templates/实验报告(无框)/template/cover.typ | typst | MIT License | #import "../utils/style.typ":*
#import "../utils/utils.typ":*
#import "../config/thesisInfo.typ":*
#set page(footer: none)
#counter(page).update(0)
#let info_value(body) = {
rect(
width: 100%,
inset: 2pt,
stroke: (
bottom: 1pt + black
),
text(
font: 字体.宋体,
size: 字号.小二,
weight: "medium",
bottom-edge: "descender"
)[
#body
]
)
}
#let info_key(body) = {
rect(width: 100%, inset: 2pt,
stroke: none,
text(
font: 字体.黑体,
size: 字号.小二,
weight: "bold",
overhang: false,
body
))
}
#align(center)[
#v(40pt)
#image("../imgs/jishoulogo_black.png",width:70%)
#v(20pt)
#table(
columns: (auto),
rows: (auto, auto ,auto),
stroke: none,
gutter: 9pt,
text(
font: 字体.宋体,
size: 1.7cm,
weight: "bold",
tracking: 5pt
)[Java Web 开发],
text(
font: 字体.宋体,
size: 1.7cm,
weight: "bold",
tracking: 5pt
)[实验报告]
),
#grid(
columns: (80pt, 250pt),
rows : (35pt, 35pt),
//gutter: 3pt,
// row : (auto ,auto, auto, auto, auto, auto),
info_key("题 目"),
info_value("实验"+zhnumbers(experimentId) +" "+experimentName),
info_key("姓 名"),
info_value(name),
info_key("学 号"),
info_value(stuId),
info_key("专业年级"),
info_value(majorGrade),
info_key("指导老师"),
info_value(guideTeacher),
info_key("完成时间"),
info_value(finishTime),
)
] |
https://github.com/crystalsolenoid/typst-resume-template | https://raw.githubusercontent.com/crystalsolenoid/typst-resume-template/main/src/main.typ | typst | #import "items.typ"
#import "sections.typ"
#import "resume.typ": resume
#import "resume.typ" as res
#let name = "<NAME>"
#show: doc => resume(
name: name,
doc
)
= #name
#res.header-links(sections.links)
== Selected Projects
#for a in sections.projects [
#res.project(..a)
]
== Work Experience
#for a in sections.experience [
#res.position(..a)
]
== Education
#for a in sections.education [
#res.education(..a)
]
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-05.typ | typst | Other | // Test that scoping works as expected.
#{
let world = [ World ]
show "W": strong
world
{
set text(blue)
show: it => {
show "o": "Ø"
it
}
world
}
world
}
|
https://github.com/typst-community/mantodea | https://raw.githubusercontent.com/typst-community/mantodea/main/src/util.typ | typst | MIT License | #import "/src/_pkg.typ"
/// Draw an alert box.
///
/// - color (color): The color to use for the box and text color.
/// - size (size): The text size to use.
/// - ..args (any): Additional arguments to pass to `showybox`.
/// - body (content): The box body.
/// -> content
#let alert(
color: purple,
size: 0.8em,
_validate: true,
..args,
body,
) = {
if _validate {
import _pkg: z
// NOTE: intentionally left empty, we only validte our own inputs
}
_pkg.showybox.showybox(
width: 100%,
frame: (
border-color: color,
title-color: color,
body-color: color.lighten(88%),
thickness: (left: 2pt, rest: 0pt),
radius: 0pt,
inset: 8pt,
),
..args,
text(size: size, fill: color.darken(60%), body),
)
}
/// Draw a blue alert box. See `alert`.
#let hint = alert.with(color: blue)
/// Draw a green alert box. See `alert`.
#let info = alert.with(color: green)
/// Draw a yellow alert box. See `alert`.
#let warn = alert.with(color: yellow)
/// Draw a red alert box. See `alert`.
#let error = alert.with(color: red)
|
https://github.com/cs-24-sw-3-01/typst-documents | https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/README.md | markdown | # typst-report
#### TO COMPILE LOCALLY RUN $ `typst watch main.typ`
#### TO VIEW PDF LOCALLY RUN $ `tinymist preview main.typ --partial-rendering`
### typst
[typst](https://github.com/typst/typst) \
macOS: `brew install typst` \
Windows: `winget install --id Typst.Typst`
### tinymist
[tinymist](https://github.com/Myriad-Dreamin/tinymist) \
macOS: `brew install tinymist`
|
|
https://github.com/Lancern/resume-template | https://raw.githubusercontent.com/Lancern/resume-template/master/README.md | markdown | Creative Commons Zero v1.0 Universal | # resume
This repository contains a simple resume template written in [typst].
<div style="display:flex;">
<img src="figures/cn-example.png" height="300px" style="margin-right:4px;" />
<img src="figures/en-example.png" height="300px" />
</div>
## Usage and Build
You need to install [typst] before you start.
The file `resume.typ` contains the template definition, which defines the resume's layout and provides some useful utility functions to help typeset your resume.
You can import this file into your own typst file to use the template:
```typst
#import "resume.typ": *
#show: resume.with(
"Your name",
"Your phone number",
"Your email",
webpage: "https://your.home.page",
github-id: "YourGithubId",
lang: "en",
)
= Education
// Your education experiences
= Professional Skills
// Your professional skills
= Work Experiences
// Your work experiences
// And more
```
This repository provides two examples that you can directly modify and refer:
- `main-en.typ`: A resume example written in English;
- `main-cn.typ`: A resume example written in simplified Chinese.
To build the resume, execute:
```bash
typst compile main.typ
```
Where `main.typ` is the file name of your typst source file.
## Reference
This section lists all the public functions and their usages as defined in `resume.typ`.
This section may require basic knowledge about the [typst language](https://typst.app/docs/reference/).
> TODO: This section is still incomplete.
### `resume.typ: resume` Function
This function defines the resume template.
Synopsis:
```typst
#let resume(
name,
phone,
email,
webpage: none,
github-id: none,
twitter-id: none,
photo: none,
lang: "en",
body,
) = { /* ... */ }
```
Parameters:
- `name`: `string`. Your name.
- `phone`: `string`. Your phone number.
- `email`: `string`. Your email number.
- `webpage`: `string`, optional. URL to your home page.
- `github-id`: `string`, optional. Your GitHub ID. A link to your github profile page will be automatically generated.
- `twitter-id`: `string`, optional. Your Twitter ID. A link to your twitter profile page will be automatically generated.
- `lang`: `string`, optional, default: `en`. The resume's language.
- `body`: `content`, required. The main content of the resume.
Returns: `content`, the content to be displayed in the output.
### `resume-item` Function
> TODO: documentation is incomplete
### `edu-item` Function
> TODO: documentation is incomplete
### `award-item` Function
> TODO: documentation is incomplete
### `work-item` Function
> TODO: documentation is incomplete
### `develop-item` Function
> TODO: documentation is incomplete
## Contribution
Any kinds of contributions are welcomed, including bug reports, bug fixes, features requests, feature implementations, documentation improvements, etc.
Feel free to open a new issue or PR!
If you have any questions on the usage of this template, feel free to open a new issue.
## License
This repository is open-source under the [Creative Commons Zero v1.0 Universal (CC0-1.0)](./LICENSE) license.
[typst]: (https://typst.app/)
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/advanced-topics-pl/presentation/presentation.typ | typst | #import "common.typ": *
#show: slides.with(
authors: [<NAME> -- 2089120],
short-authors: "<NAME>",
title: "The Typst language",
subtitle: "Advanced Topics in Programming languages presentation",
short-title: [#v(.5em) The Typst language],
date: "September 14, 2023",
theme: bristol-theme(
color: unipd-red,
logo: "/images/unipd-logo.png",
// Don't use watermarks, by using a blank image (`none` can't be used)
watermark: "/images/blank.png",
secondlogo: "/images/blank.png",
)
)
#set text(font: "Arial")
#show raw: itself => {
set text(font: "Menlo")
itself
}
// Add background to monospace text
#show raw.where(block: false): box.with(
fill: luma(220),
inset: (x: 3pt, y: 0pt),
outset: (y: 8pt),
radius: 4pt,
)
#show raw.where(block: true): block.with(
fill: luma(220),
inset: 10pt,
radius: 10pt,
)
#show figure: itself => {
set text(size: 16pt)
itself
}
// Properly display case-insensitive matches
#show regex("(?i)\btex\b"): tex
#show regex("(?i)\blatex\b"): latex
#slide(theme-variant: "title slide")
#include("sections/markup-languages.typ")
#include("sections/typst.typ")
#include("sections/markup-mode.typ")
#include("sections/code-mode.typ")
#include("sections/compiler.typ")
#include("sections/improvements.typ")
#slide(title: "GitHub support")[
#set text(size: .8em)
#grid(columns: (2fr, 3fr), gutter: 1em,
[
- Pull request to add Typst support in GitHub repos
- Needs more popularity
],
figure(image("/images/popularity/comment.png"))
)
]
#slide(title: "Popularity")[
#figure(image(width: 60%, "/images/popularity/merged.png"))
#uncover(2, figure(image(width: 60%, "/images/popularity/search.png")))
]
#slide(title: "Latest news")[
#grid(columns: (auto, auto), gutter: 2em,
figure(image("/images/popularity/syntax-highlighting.png")),
align(center + horizon, figure(image(width: 70%, "/images/popularity/languages.png"))),
)
]
#slide(title: "Sources")[
- *<NAME> (typst co-creator) Master's thesis*: \
#underline("https://www.user.tu-berlin.de/laurmaedje/programmable-markup-language-for-typesetting.pdf")
- *Typst official documentation*: #underline("https://typst.app/docs/")
]
#wake-up[
Thanks for the attention
]
|
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/compiler/weeks/week5.typ | typst | #import "../../utils.typ": *
#section("Semantic Checker")
Checks language rules -> LSP
- each identifier is unique within its scope
- typerules are fulfilled
- method calls are compatible with parameters and return types
- no cyclic inheritance
#subsection("Tables and Scopes")
Per scope, we create a symbol table in order to quickly check later on whether
or not something already exists, and what type etc. it has.
#columns(2, [
#align(
center,
[#image("../../Screenshots/2023_10_16_08_21_07.png", width: 100%)],
)
#colbreak()
#align(
center,
[#image("../../Screenshots/2023_10_16_08_21_33.png", width: 100%)],
)
])
#text(
teal,
)[Note that inner scopes can have the same symbol as the outer scope -> in this
case the inner scope shadows the outer scope symbol.]
#subsection("Type Hierarchy")
This hierarchy is defined for the abstract syntax tree (AST) that the semantic
checker is going to use.
#align(
center,
[#image("../../Screenshots/2023_10_16_08_23_24.png", width: 70%)],
)
inbuilt types:
- value types
- int
- boolean
- Null-Type
- reference types
- string
#subsubsection("Type Hierarchy for Classes")
#align(
center,
[#image("../../Screenshots/2023_10_16_08_25_07.png", width: 70%)],
)
Further inheritances of VariableSymbol:
#align(
center,
[#image("../../Screenshots/2023_10_16_08_28_49.png", width: 70%)],
)
#subsubsection("More builtin types for smallj")
- types
- int, boolean, string
- constants
- true, false
- null
- this
- built-in methods
- writeString
- fields
- length -> readonly and only for arrays
#subsubsection("Arrays")
Arrays don't have a special class in the semantic checker for smallj, instead we
have to add the [] on the fly -> type [].
#subsection("Procedure")
+ create a symboltable with all declarations
- you might need multiple ones -> multiple scopes
+ resolve types of declarations
+ resolve usage of declarations to abstract syntax tree (AST)
+ check types in AST
#subsubsection("Symbol Table Creation")
write each type in a table...
#subsubsection("Type Resolution")
Each declaration needs some sort of type, this means we now have to go back to
the previously created table and traverse through it. Each entry needs to have a
resolved type at the end of the table. Resolved type means that the declaration
is now represented with 2 symbol entries in the AST -> variable AND class symbol
instead of only variable symbol.
#align(
center,
[#image("../../Screenshots/2023_10_16_08_39_22.png", width: 70%)],
)
#subsubsubsection("Method for searching")
#align(
center,
[#image("../../Screenshots/2023_10_16_08_44_32.png", width: 70%)],
)
//typstfmt::off
```cs
bool TryFind<T>(string identifier, out T? declaration) where T : Symbol {
Symbol? scope = this;
do {
foreach (var member in scope.Declarations) {
if (member.Identifier == identifier) {
declaration = member as T;
return declaration != null;
}
}
scope = scope.Scope;
} while (scope != null);
declaration = default;
return false;
}
```
//typstfmt::on
#subsubsection("Type Usage")
Each usage of a declaration needs to be referenced to an entry in the symbol table.
#align(center, [#image("../../Screenshots/2023_10_16_08_46_44.png", width: 70%)])
#subsubsection("AST Check")
Check types of each node from bottom to top.
//typstfmt::off
```cs
TypeSymbol? ExpressionType { get; private set; }
override void Visit(BinaryExpressionNode node) {
var left = node.Left;
var right = node.Right;
left.Accept(this);
var leftType = ExpressionType;
right.Accept(this);
var rightType = ExpressionType;
switch (node.Operator) {
// case ...
case Operator.DIVIDE or Operator.MINUS: // more ommitted
CheckType(leftLocation, leftType, _intType);
CheckType(rightLocation, rightType, _intType);
ExpressionType = _intType;
break;
default: throw new ArgumentOutOfRangeException(nameof(node.Operator));
}
}
```
//typstfmt::on
#subsection("Semantic Checks")
- all designators are connecte to a variable
- variables used with operators have the correct type
- types are compatible on assignments
- expression inside if statements are booleans
- return expression fits return type
- no multiple declarations within one scope
- no user defined identifier matches a built-in one
- one main method defined
- array length is read only
#subsubsection("More Checks")
These checks can't be generally be checked in one place -> might need multiple types of checks
- no exit without return other than in void methods
- reading of uninitialized variables
- null-dereferencing
- out-of-bounds array index
- division by 0
- out of memory on new
|
|
https://github.com/remggo/cookbook-typst | https://raw.githubusercontent.com/remggo/cookbook-typst/main/example.typ | typst | MIT License | #import "cookbook.typ": recipe_yaml, recipe
#set text(lang: "de", region: "DE")
#recipe_yaml("recipe.yaml")
#recipe(
title: "Suppe",
prep-time: [2h],
servings: [3 Personen],
ingredients: [
/ 100g: Käse
/ 100g: Butter
/ 100g: Milch
/ 100g: Mehl
],
instructions: (
[
First step
#lorem(20)
],
[
Second step
#lorem(20)
],
[
#lorem(30)
]
),
images: (
small: "images/small.jpg",
big: "images/big.jpg"
),
hint: [#lorem(30)]
)
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/src/styles/help.typ | typst | MIT License | #import "../utilities.typ": *
#import "default.typ"
// Color to highlight function names in
#let fn-color = rgb("#1f2a63")
#let fn-color = blue.darken(30%)
#let default-type-color = rgb("#eff0f3")
#let show-outline(module-doc, style-args: (:)) = {
let prefix = module-doc.label-prefix
let items = ()
for fn in module-doc.functions {
items.push(link(label(prefix + fn.name + "()"), fn.name + "()"))
}
list(..items)
}
#let show-type(type-name, style-args: (:)) = {
h(2pt)
let clr = style-args.colors.at(type-name, default: style-args.colors.at("default", default: default-type-color))
if type(clr) == color {
let components = clr.components()
clr = rgb(..components.slice(0, -1), 60%)
}
box(outset: 2pt, fill: clr, radius: 2pt, raw(type-name, lang: none))
h(2pt)
}
#let show-parameter-list(fn, style-args) = {
block(fill: rgb("#d8dbed44"), width: 100%, inset: (x: 0.5em, y: 0.7em), {
set text(font: "Cascadia Mono", size: 0.85em, weight: 340)
text(fn.name)
"("
let inline-args = fn.args.len() < 5
if not inline-args { "\n " }
let items = ()
for (arg-name, info) in fn.args {
let types
if "types" in info {
types = ": " + info.types.map(x => show-type(x, style-args: style-args)).join(" ")
}
items.push(box(arg-name + types))
}
items.join( if inline-args {", "} else { ",\n "})
if not inline-args { "\n" } + ")"
if fn.return-types != none {
box[~-> #fn.return-types.map(x => show-type(x, style-args: style-args)).join(" ")]
}
})
}
// Create a parameter description block, containing name, type, description and optionally the default value.
#let show-parameter-block(
name, types, content, style-args,
show-default: false,
default: none,
) = block(
inset: 0pt, width: 100%,
breakable: style-args.break-param-descriptions,
[
#[
#raw(name, lang: none)
]
#if types != () [
(#h(-.2em)
#types.map(x => (style-args.style.show-type)(x, style-args: style-args)).join([ #text("or",size:.6em) ])
#if show-default [\= #raw(lang: "typc", default) ]
#h(-.2em))
]
--
#content
]
)
#let show-function(
fn, style-args,
) = {
if style-args.colors == auto { style-args.colors = default.colors }
set par(justify: false, hanging-indent: 1em, first-line-indent: 0em)
block(breakable: style-args.break-param-descriptions, fill: rgb("#d8dbed44"),
if style-args.enable-cross-references [
#(style-args.style.show-parameter-list)(fn, style-args)
#label(style-args.label-prefix + fn.name + "()")
] else [
#(style-args.style.show-parameter-list)(fn, style-args)
])
pad(x: 0em, eval-docstring(fn.description, style-args))
let parameter-block
for (name, info) in fn.args {
let types = info.at("types", default: ())
let description = info.at("description", default: "")
if description == "" and style-args.omit-empty-param-descriptions { continue }
parameter-block += (style-args.style.show-parameter-block)(
name, types, eval-docstring(description, style-args),
style-args,
show-default: "default" in info,
default: info.at("default", default: none),
)
}
if parameter-block != none {
[*Parameters:*]
parameter-block
}
v(2em, weak: true)
}
#let show-variable(
var, style-args,
) = {
if style-args.colors == auto { style-args.colors = default.colors }
set par(justify: false, hanging-indent: 1em, first-line-indent: 0em)
let type = if "type" not in var { none }
else { show-type(var.type, style-args: style-args) }
block(breakable: style-args.break-param-descriptions, fill: rgb("#d8dbed44"), width: 100%, inset: (x: 0.5em, y: 0.7em),
stack(dir: ltr, spacing: 1.2em,
if style-args.enable-cross-references [
#set text(font: "Cascadia Mono", size: 0.85em, weight: 340)
#text(var.name)
#label(style-args.label-prefix + var.name)
] else [
#set text(font: "Cascadia Mono", size: 0.85em, weight: 340)
#text(var.name)
],
type
)
)
pad(x: 0em, eval-docstring(var.description, style-args))
v(2em, weak: true)
}
#let show-reference(label, name, style-args: none) = {
link(label, raw(name, lang: none))
}
#import "../show-example.typ": show-example as show-ex
#let show-example(
..args
) = {
show-ex(
..args,
code-block: block.with(stroke: .5pt + fn-color),
preview-block: block.with(stroke: .5pt + fn-color),
col-spacing: 0pt
)
} |
https://github.com/j10ccc/algorithm-analysis-homework-template-typst | https://raw.githubusercontent.com/j10ccc/algorithm-analysis-homework-template-typst/main/layout/headers/index.typ | typst | #import "introduction.typ": introduction
#import "title.typ": title
#import "identification.typ": identification
#import "../divider.typ": divider
#let headers(
homework_id: [0],
date: [2023.09.04],
deadline: [2023.9.24],
time_consume: [],
intro: [请用 LATEX 编辑所有解答。所有问题请给出简洁的回答,任何冗余的回答可能会得低分。提交文件格式为 PDF]
) = [
#introduction(date, homework_id)
#divider
#title(homework_id: homework_id, deadline: deadline)[
#intro
]
#divider
#identification(time_consume)
#divider
]
|
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/comment/block-comment.typ | typst | Apache License 2.0 | Our study design is as follows:
/* Somebody write this up:
- 1000 participants.
- 2x2 data design. */
#if draw-edge == auto {
draw-edge = (source-name, target-name, target-node) => {
let (a, b) = (source-name + "." + direction,
target-name + "." + opposite-dir.at(direction))
/* see this */
draw.line(a, b)
/*
if direction == "bottom" {
draw.line(a, (rel: (0, -grow/3)), ((), "-|", b), b)
} else if direction == "up" {
draw.line(a, (rel: (0, grow/3)), ((), "-|", b), b)
} else if direction == "left" {
draw.line(a, (rel: (-grow/3, 0)), ((), "|-", b), b)
} else if direction == "right" {
draw.line(a, (rel: (grow/3, 0)), ((), "|-", b), b)
}
*/
}
}
|
https://github.com/Amelia-Mowers/typst-tabut | https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/README.typ | typst | MIT License | #let ex(input) = {
set align(center);
block(
fill: luma(97%),
inset: 8pt,
radius: 4pt,
breakable: false,
[
#set align(left);
#input
])
}
#let snippet(filename) = {[
#let version = toml("typst.toml").package.version;
#let snippet-code-path = "doc/example-snippets/" + filename + ".typ"
#let snippet-image-path = "doc/compiled-snippets/" + filename + ".svg"
#let data = xml(snippet-image-path).first();
#let size = (
height: float(data.attrs.height) * 1pt ,
width: float(data.attrs.width) * 1pt,
);
#let content = read(snippet-code-path).replace("\r", "").replace("<<VERSION>>", version)
#ex(raw(content, block: true, lang: "typ"))
#ex(image(snippet-image-path, ..size))
]}
#let snippet-quiet(filename) = {[
#let version = toml("typst.toml").package.version;
#let snippet-code-path = "doc/example-snippets/" + filename + ".typ"
#let content = read(snippet-code-path).replace("\r", "").replace("<<VERSION>>", version)
#ex(raw(content, block: true, lang: "typ"))
]}
#let no-break(content) = {
block(breakable: false, width:100%, content)
}
#let subsection(name) = {
[== #name ]
}
#let label-text(content) = {
label(lower(content.text.replace(" ", "-")))
}
#let section(name) = {
[= #name #label-text(name)]
}
#let subsection(name) = {
[== #name #label-text(name)]
}
#no-break([
= Tabut
_Powerful, Simple, Concise_
A Typst plugin for turning data into tables.
== Outline
#set list(marker: ([•], [◦]))
#let sections = (
(name: [Examples], subs: (
[Input Format and Creation],
[Basic Table],
[Table Styling],
[Header Formatting],
[Remove Headers],
[Cell Expressions and Formatting],
[Index],
[Transpose],
[Alignment],
[Column Width],
[Get Cells Only],
[Use with Tablex],
)),
(name: [Data Operation Examples], subs: (
[CSV Data],
[Slice],
[Sorting and Reversing],
[Filter],
[Aggregation using Map and Sum],
[Grouping]
)),
(name: [Function Definitions], subs: (
[`tabut`],
[`tabut-cells`],
[`rows-to-records`],
[`records-from-csv`],
[`group`],
)),
)
#{
let items = ();
for s in sections {
let s-items = ();
for ss in s.subs {
s-items.push(link(label-text(ss), ss));
}
items.push([
#link(label-text(s.name), s.name)
#list(..s-items)
])
}
list(..items, tight: true)
}
])
#pagebreak(weak: true)
#no-break([
#section([Examples])
]) #no-break([
#subsection([Input Format and Creation])
The `tabut` function takes input in "record" format, an array of dictionaries, with each dictionary representing a single "object" or "record".
In the example below, each record is a listing for an office supply product.
#snippet-quiet("example-data/supplies")
]) #no-break([
#subsection([Basic Table])
Now create a basic table from the data.
#snippet("basic")
`funct` takes a function which generates content for a given cell corrosponding to the defined column for each record.
`r` is the record, so `r => r.name` returns the `name` property of each record in the input data if it has one.
]) #no-break([
The philosphy of `tabut` is that the display of data should be simple and clearly defined,
therefore each column and it's content and formatting should be defined within a single clear column defintion.
One consequence is you can comment out, remove or move, any column easily, for example:
#snippet("rearrange")
]) #no-break([
#subsection([Table Styling])
Any default Table style options can be tacked on and are passed to the final table function.
#snippet("styling")
]) #no-break([
#subsection([Header Formatting])
You can pass any content or expression into the header property.
#snippet("title")
]) #no-break([
#subsection([Remove Headers])
You can prevent from being generated with the `headers` paramater. This is useful with the `tabut-cells` function as demonstrated in it's section.
#snippet("no-headers")
]) #no-break([
#subsection([Cell Expressions and Formatting])
Just like the headers, cell contents can be modified and formatted like any content in Typst.
#snippet("format")
]) #no-break([
You can have the cell content function do calculations on a record property.
#snippet("calculation")
]) #no-break([
Or even combine multiple record properties, go wild.
#snippet("combine")
]) #no-break([
#subsection([Index])
`tabut` automatically adds an `_index` property to each record.
#snippet("index")
You can also prevent the `index` property being generated by setting it to `none`,
or you can also set an alternate name of the index property as shown below.
#snippet("index-alternate")
]) #no-break([
#subsection([Transpose])
This was annoying to implement, and I don't know when you'd actually use this, but here.
#snippet("transpose")
]) #no-break([
#subsection([Alignment])
#snippet("align")
You can also define Alignment manually as in the the standard Table Function.
#snippet("align-manual")
]) #no-break([
#subsection([Column Width])
#snippet("width")
You can also define Columns manually as in the the standard Table Function.
#snippet("width-manual")
]) #no-break([
#subsection([Get Cells Only])
#snippet("only-cells")
]) #no-break([
#subsection([Use with Tablex])
#snippet("tablex")
])
#pagebreak(weak: true)
#no-break([
#section([Data Operation Examples])
While technically seperate from table display, the following are examples of how to perform operations on data before it is displayed with `tabut`.
Since `tabut` assumes an "array of dictionaries" format, then most data operations can be performed easily with Typst's native array functions. `tabut` also provides several functions to provide additional functionality.
]) #no-break([
#subsection([CSV Data])
By default, imported CSV gives a "rows" or "array of arrays" data format, which can not be directly used by `tabut`.
To convert, `tabut` includes a function `rows-to-records` demonstrated below.
#snippet-quiet("import-csv-raw")
Imported CSV data are all strings, so it's usefull to convert them to `int` or `float` when possible.
#snippet-quiet("import-csv")
`tabut` includes a function, `records-from-csv`, to automatically perform this process.
#snippet-quiet("import-csv-easy")
]) #no-break([
#subsection([Slice])
#snippet("slice")
]) #no-break([
#subsection([Sorting and Reversing])
#snippet("sort")
]) #no-break([
#subsection([Filter])
#snippet("filter")
]) #no-break([
#subsection([Aggregation using Map and Sum])
#snippet("aggregation")
]) #no-break([
#subsection([Grouping])
#snippet("group")
#snippet("group-aggregation")
])
#pagebreak(weak: true)
#no-break([
#section([Function Definitions])
]) #no-break([
#subsection([`tabut`])
Takes data and column definitions and outputs a table.
#ex(```typc
tabut(
data-raw,
colDefs,
columns: auto,
align: auto,
index: "_index",
transpose: false,
headers: true,
..tableArgs
) -> content
```)
=== Parameters
/ `data-raw`: This is the raw data that will be used to generate the table. The data is expected to be in an array of dictionaries, where each dictionary represents a single record or object.
/ `colDefs`: These are the column definitions. An array of dictionaries, each representing column definition. Must include the properties `header` and a `func`. `header` expects content, and specifies the label of the column. `func` expects a function, the function takes a record dictionary as input and returns the value to be displayed in the cell corresponding to that record and column. There are also two optional properties; `align` sets the alignment of the content within the cells of the column, `width` sets the width of the column.
/ `columns`: (optional, default: `auto`) Specifies the column widths. If set to `auto`, the function automatically generates column widths by each column's column definition. Otherwise functions exactly the `columns` paramater of the standard Typst `table` function. Unlike the `tabut-cells` setting this to `none` will break.
/ `align`: (optional, default: `auto`) Specifies the column alignment. If set to `auto`, the function automatically generates column alignment by each column's column definition. If set to `none` no `align` property is added to the output arg. Otherwise functions exactly the `align` paramater of the standard Typst `table` function.
/ `index`: (optional, default: `"_index"`) Specifies the property name for the index of each record. By default, an `_index` property is automatically added to each record. If set to `none`, no index property is added.
/ `transpose`: (optional, default: `false`) If set to `true`, transposes the table, swapping rows and columns.
/ `headers`: (optional, default: `true`) Determines whether headers should be included in the output. If set to `false`, headers are not generated.
/ `tableArgs`: (optional) Any additional arguments are passed to the `table` function, can be used for styling or anything else.
]) #no-break([
#subsection([`tabut-cells`])
The `tabut-cells` function functions as `tabut`, but returns `arguments` for use in either the standard `table` function or other tools such as `tablex`. If you just want the array of cells, use the `pos` function on the returned value, ex `tabut-cells(...).pos`.
`tabut-cells` is particularly useful when you need to generate only the cell contents of a table or when these cells need to be passed to another function for further processing or customization.
=== Function Signature
#ex(```typc
tabut-cells(
data-raw,
colDefs,
columns: auto,
align: auto,
index: "_index",
transpose: false,
headers: true,
) -> arguments
```)
=== Parameters
/ `data-raw`: This is the raw data that will be used to generate the table. The data is expected to be in an array of dictionaries, where each dictionary represents a single record or object.
/ `colDefs`: These are the column definitions. An array of dictionaries, each representing column definition. Must include the properties `header` and a `func`. `header` expects content, and specifies the label of the column. `func` expects a function, the function takes a record dictionary as input and returns the value to be displayed in the cell corresponding to that record and column. There are also two optional properties; `align` sets the alignment of the content within the cells of the column, `width` sets the width of the column.
/ `columns`: (optional, default: `auto`) Specifies the column widths. If set to `auto`, the function automatically generates column widths by each column's column definition. If set to `none` no `column` property is added to the output arg. Otherwise functions exactly the `columns` paramater of the standard typst `table` function.
/ `align`: (optional, default: `auto`) Specifies the column alignment. If set to `auto`, the function automatically generates column alignment by each column's column definition. If set to `none` no `align` property is added to the output arg. Otherwise functions exactly the `align` paramater of the standard typst `table` function.
/ `index`: (optional, default: `"_index"`) Specifies the property name for the index of each record. By default, an `_index` property is automatically added to each record. If set to `none`, no index property is added.
/ `transpose`: (optional, default: `false`) If set to `true`, transposes the table, swapping rows and columns.
/ `headers`: (optional, default: `true`) Determines whether headers should be included in the output. If set to `false`, headers are not generated.
]) #no-break([
#subsection([`records-from-csv`])
Automatically converts a CSV data into an array of records.
#ex(```typc
records-from-csv(
data
) -> array
```)
=== Parameters
/ `data`: The CSV data that needs to be converted, this can be obtained using the native `csv` function, like `records-from-csv(csv(file-path))`.
This function simplifies the process of converting CSV data into a format compatible with `tabut`. It reads the CSV data, extracts the headers, and converts each row into a dictionary, using the headers as keys.
It also automatically converts data into floats or integers when possible.
]) #no-break([
#subsection([`rows-to-records`])
Converts rows of data into an array of records based on specified headers.
This function is useful for converting data in a "rows" format (commonly found in CSV files) into an array of dictionaries format, which is required for `tabut` and allows easy data processing using the built in array functions.
#ex(```typc
rows-to-records(
headers,
rows,
default: none
) -> array
```)
=== Parameters
/ `headers`: An array representing the headers of the table. Each item in this array corresponds to a column header.
/ `rows`: An array of arrays, each representing a row of data. Each sub-array contains the cell data for a corresponding row.
/ `default`: (optional, default: `none`) A default value to use when a cell is empty or there is an error.
]) #no-break([
#subsection([`group`])
Groups data based on a specified function and returns an array of grouped records.
#ex(```typc
group(
data,
function
) -> array
```)
=== Parameters
/ `data`: An array of dictionaries. Each dictionary represents a single record or object.
/ `function`: A function that takes a record as input and returns a value based on which the grouping is to be performed.
This function iterates over each record in the `data`, applies the `function` to determine the grouping value, and organizes the records into groups based on this value. Each group record is represented as a dictionary with two properties: `value` (the result of the grouping function) and `group` (an array of records belonging to this group).
In the context of `tabut`, the `group` function is particularly useful for creating summary tables where records need to be categorized and aggregated based on certain criteria, such as calculating total or average values for each group.
])
|
https://github.com/typst-community/typst-install | https://raw.githubusercontent.com/typst-community/typst-install/main/README.md | markdown | MIT License | # Typst installer
🤖 `curl | sh` installer script for Typst \
💡 Inspired by [denoland/deno_install]
<table align=center><td>
```sh
# ✨🚀
curl -fsSL https://typst.community/typst-install/install.sh | sh
typst compile paper.typ
```
</table>
🚀 Easy to get started; just one shell command! \
🟦 Works on Windows too
👀 Don't want to use `curl | sh`? Follow the [official Typst installation
instructions] and download a binary from [typst/typst releases].
## Usage



Linux, macOS, WSL
```sh
curl -fsSL https://typst.community/typst-install/install.sh | sh
```
Windows
```ps1
irm https://typst.community/typst-install/install.ps1 | iex
```
<details><summary>Change install location</summary>
Linux, macOS, WSL
```sh
export TYPST_INSTALL="/usr/local"
curl -fsSL https://typst.community/typst-install/install.sh | sh
```
Windows
```ps1
$Env:TYPST_INSTALL = "C:\Program Files\typst"
irm https://typst.community/typst-install/install.ps1 | iex
```
</details>
<details><summary>Install specific version</summary>
Linux, macOS, WSL
```sh
curl -fsSL https://typst.community/typst-install/install.sh | sh -s 0.10.0
```
Windows
```ps1
v="0.10.0"; irm https://typst.community/typst-install/install.ps1 | iex
```
</details>
Now you can use `typst`! It's installed to `~/.typst/*` by default.
```sh
The Typst compiler
Usage: typst [OPTIONS] <COMMAND>
Commands:
compile Compiles an input file into a supported output format [aliases: c]
watch Watches an input file and recompiles on changes [aliases: w]
query Processes an input file to extract provided metadata
fonts Lists all discovered fonts in system and custom font paths
update Self update the Typst CLI
help Print this message or the help of the given subcommand(s)
Options:
-v, --verbosity... Sets the level of logging verbosity: -v = warning & error, -vv = info, -vvv = debug, -vvvv = trace
--cert <CERT> Path to a custom CA certificate to use when making network requests [env: TYPST_CERT=]
-h, --help Print help
-V, --version Print version
```
## Development


GitHub Pages is enabled and pulls straight from the `main` branch's root folder.
That's how the `https://typst.community/typst-install/install.sh` script is
published. That means it's a good idea to **make sure that the `main` branch
always works!** 😉
<!-- prettier-ignore-start -->
[official Typst installation instructions]: https://github.com/typst/typst#installation
[typst/typst releases]: https://github.com/typst/typst/releases
[denoland/deno_install]: https://github.com/denoland/deno_install
<!-- prettier-ignore-end -->
|
https://github.com/TheLukeGuy/backtrack | https://raw.githubusercontent.com/TheLukeGuy/backtrack/main/DOCS.md | markdown | Apache License 2.0 | # Backtrack Documentation
This document specifies and explains the Backtrack API in detail. See the
[README file](README.md) for installation instructions and a basic description
and example.
## Top-Level Items
There are only two top-level items in the library: `current-version` and
`versions`.
### Current Version
`current-version` is a [version object](#version-objects) constant for the
current compiler version.
### Versions
`versions` is a module containing version object constants for each compiler
version up until 0.9.0, plus functions for creating version objects for newer
compiler versions.
The `versions` module contains the following items:
- Version object constants for Typst 0.1.0–0.8.0, named
`v[major]-[minor]-[patch]`
- Version object constants for Typst 2023-01-30–2023-03-28, named
`v[YYYY]-[MM]-[DD]`
- A `post-v0-8-0(..components)` function that takes in the `int` components for
a compiler version above 0.8.0 and returns a corresponding version object;
`array` arguments are flattened
- A `from-v0-9-0-version(v0-9-0-version)` function that takes in a `version`
value and returns a corresponding version object
## Version Objects
The API is centered around _version objects_, which are dictionaries that have
exactly these keys:
- `cmpable` is used for comparing version objects.
- `displayable` is used for displaying version objects.
- `observable` is used for observing version objects.
> [!NOTE]
> In this document, "version object" refers to this type of Backtrack version
> object, while `version` (mind the inline code block) refers to the built-in
> `version` type added in Typst 0.9.0.
### Comparable
`cmpable` is a value that supports `<`, `<=`, `==`, `!=`, `>`, and `>=`
operations. Identical compiler versions have equal `cmpable` values, a compiler
version released before another should have a lesser `cmpable` value, etc. Its
specific value is unstable and shouldn't be relied on.
On compiler versions prior to 0.9.0, this is an `int` in all version objects;
otherwise, this is a `version` in all version objects.
> [!WARNING]
> Comparison operations are only valid when at least one of their operands is
> the current version. For instance, comparing `current-version` and a version
> object for 0.9.0 is valid, while comparing a version object for 0.9.0 and
> another for 1.0.0 is undefined and **will** produce counterintuitive results
> when compiled on specific Typst versions.
>
> This is a case of prioritizing simplicity over versatility.
### Displayable
`displayable` is a `str` with a human-friendly name for the version. It should
look natural in phrases like "Typst [displayable]" and "Typst v[displayable]".
Its specific value is unstable and shouldn't be relied on.
### Observable
`observable` is a collection containing the `int` components of the version.
For example:
- `v0-2-0.observable` = `(0, 2, 0)`
- `v2023-03-21.observable` = `(0, 0, 0, 2023, 3, 21)`
This value is guaranteed to be iterable and to have an `at` method that gets the
component at the given index. While its specific value is unstable and shouldn't
be relied on, the values produced by iterating over it or by its `at` method
_are_ stable. No other guarantees are made—do not assume other methods work
reliably even if they appear to.
On compiler versions prior to 0.9.0, this is an `array` in all version objects;
otherwise, this is a `version` in all version objects.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/conchord/0.1.1/tabs.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.1.1": canvas, draw
#let new(
tabs,
extra: none,
eval-scope: none,
scale: 0.3cm,
s-num: 6,
one-beat-length: 8,
line-spacing: 2,
) = {
let sign(x) = if x > 0 { 1 } else if x == 0 { 0 } else { -1 }
layout(
size => {
let width = size.width / scale * 0.95
canvas(
length: scale,
{
import draw: *
let draw-lines(y, x: width) = {
// TODO: use on-layer
{
for i in range(s-num) {
line((0, -(y + i)), (x, -(y + i)), stroke: rgb(1, 1, 1, 20%))
}
}
}
let draw-bar(x, y, width: 1.0) = {
line((x, -y), (x, -y - s-num + 1), stroke: width * 1.2pt + gray)
}
let x = 0
let y = 0
draw-bar(0, 0)
let last-string-x = (-1.5,) * 6
let last-tab-x = (0,) * 6
let last-sign = none
for bar in tabs {
if bar.len() > 0 {
if (last-sign == "\\" or last-sign == none) {
if bar.at(0) != "||" { x += 1. } else { x -= 0.5 }
}
}
for n in bar {
let frets = n.at(0)
if x >= width {
draw-lines(y)
draw-bar(x, y)
last-string-x = (-1.5,) * 6
x = 1.0
y += s-num + line-spacing
last-sign = "\\"
}
if n == "\\" {
if last-sign != "||" and last-sign != "|" {
draw-bar(x, y)
x += 0.5
}
else {
x -= 0.5
}
draw-lines(y, x: x - 0.5)
last-string-x = (-1.5,) * 6
y += s-num + line-spacing
x = 0.0
draw-bar(x, y)
x -= 0.5
last-sign = "\\"
continue
}
if n == "<" {
x -= 0.5
continue
}
if n == ">" {
x += 0.5
continue
}
if n == ":" {
if last-sign == none { x -= 1 / 1 }
circle((x, -y - 1.5), radius: 0.2, fill: gray, stroke: gray)
circle((x, -y - 3.5), radius: 0.2, fill: gray, stroke: gray)
last-sign = ":"
x += 0.5
continue
}
if n == "||" {
x += 0.5
draw-bar(x, y, width: 4)
x += 0.5
last-sign = "||"
continue
}
if n == "|" {
if last-sign == "|" {x -= 0.5}
draw-bar(x, y)
x += 0.5
last-sign = "|"
continue
}
if n.at(0) == "##" {
content((x, -y + 1), eval(n.at(1), scope: eval-scope))
continue
}
let last-x = x
if n.len() == 1 {
panic(n)
}
x += one-beat-length * calc.pow(2, -n.at(1))
// pause
if frets.len() == 0 {
continue
}
for fret in frets {
let n-y = fret.at(1)
if fret.len() == 3 {
if fret.at(2) == "^" {
let y = - (y + n-y - 1)
bezier-through(
(last-string-x.at(n-y - 1), y - 0.5),
((last-x + last-string-x.at(n-y - 1)) / 2, y - 1.0),
(last-x, y - 0.5),
stroke: rgb(1, 1, 1, 50%),
)
} else if fret.at(2) == "`" {
let y = - (y + n-y - 1)
let dy = fret.at(0) - last-tab-x.at(n-y - 1)
dy = sign(dy) * 0.2
line(
(last-string-x.at(n-y - 1) + 0.3, y - dy),
(last-x, y + dy),
stroke: rgb(1, 1, 1, 50%),
)
}
}
content(
(last-x, - (y + n-y - 1)),
highlight(fill: white, bottom-edge: "bounds", raw(str(fret.at(0)))),
)
last-string-x.at(n-y - 1) = last-x
last-tab-x.at(n-y - 1) = fret.at(0)
last-sign = "n"
}
}
x += 0.5
}
if last-sign == "||" {x -= 1.0}
else if last-sign == "|" {x -= 0.5}
draw-lines(y, x: x)
draw-bar(x, y)
extra
},
)
},
)
}
#let to-int(s) = {
if s.matches(regex("^\d+$")).len() != 0 { int(s) } else { panic("Bad number: " + s) }
}
#let parse-note(n, s-num: 6) = {
if n == "p" {
return ()
}
return n.split("+").map(
n => {
let cont = if n.starts-with("^") { "^" } else if n.starts-with("`") { "`" } else { none }
if cont != none { n = n.slice(1) }
let coords = n.split("/").map(to-int)
if coords.len() != 2 {
panic("Specify fret and string numbers separated by `/`: " + n)
}
if coords.at(1) > s-num {
panic("Too large string number: " + n.at(1))
}
if cont != none { coords.push(cont) }
return coords
},
)
}
#let gen(s, s-num: 6) = {
if type(s) == "content" {
s = s.text
}
let bars = ()
let cur-bar = ()
let cur-dur = 2
let code-mode = false
let code = ()
for (n, s,) in s.split(regex("\s+")).zip(s.matches(regex("\s+")) + ("",)) {
if n == "##" and not code-mode {
code-mode = true
continue
}
if code-mode {
if n == "##" {
code-mode = false
cur-bar.push(("##", code.join()))
code = ()
continue
}
code.push(n)
code.push(s.text)
continue
}
if n == "<" {
cur-bar.push(n)
continue
}
if n == ":|" {
cur-bar.push(":")
cur-bar.push("|")
cur-bar.push("<")
cur-bar.push("||")
bars.push(cur-bar)
cur-bar = ()
n = n.slice(2)
continue
}
if n == "|:" {
cur-bar.push("||")
cur-bar.push("|")
cur-bar.push(":")
bars.push(cur-bar)
cur-bar = ()
n = n.slice(2)
continue
}
if n == "||" {
cur-bar.push("|")
cur-bar.push("<")
cur-bar.push("||")
bars.push(cur-bar)
cur-bar = ()
continue
}
if n == "|" {
cur-bar.push("|")
bars.push(cur-bar)
cur-bar = ()
continue
}
if n == "\\" {
//cur-bar.push("|")
cur-bar.push("\\")
bars.push(cur-bar)
cur-bar = ()
continue
}
if n == "" {
continue
}
let note-and-dur = n.split("-")
if note-and-dur.len() > 2 or note-and-dur == 0 {
panic("Specify one duration per note")
}
if note-and-dur.len() == 2 {
let dur = note-and-dur.at(1)
let mul = 1.0
while dur.ends-with(".") {
mul += calc.log(1.5) / calc.log(2)
dur = dur.slice(0, -1)
}
cur-dur = to-int(dur) / mul
}
cur-bar.push((parse-note(note-and-dur.at(0), s-num: s-num), cur-dur))
}
if cur-bar.len() > 0 {bars.push(cur-bar)}
return bars
}
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas3/4_Stvrtok.typ | typst | #let V = (
"HV": (
("", "<NAME>", "Molítvami čestných i božéstvennych apóstol tvojích, čelovikoľúbče ščédryj, jedíne mílostive, smirénije tvojé podážď rabóm tvojím, i spasí ot bíd vospivájuščich ťá, i víroju poklaňájuščichsja."),
("", "", "Jehdá na prestóľich obojunádesjatich sjádete so vsích Sudijéju, sudíti vsjákoj tvári: ne osuždéna mjá pokažíte, i ťmý i vsjákaho tomlénija izbávite blahodáteli mojí, božéstvenniji apóstoli."),
("", "", "Ot stríl nečestívaho izbávite mjá, jáko Bóžiji samovídcy, uhašájušče jehó kovárstva: i orosíte mjá duchóvnoju rosóju, vás moľú múdriji blahodáteli mojí, božéstvenniji apóstoli."),
("", "<NAME>", "Ujázven bých okajánnyj zmijínym uhryzénijem, i ležú povéržen mértv bez dychánija: bódrennoju tvojéju moľbóju vozstávi mjá vskóri, vseblažénne svjatíteľu, da slávľu tvojú skoroposlušlívuju blahodáť."),
("", "", "Umá mojehó pomračívšasja zlými pomyšléňmi, i ležášča predvíďa, nikákože prestajét lovléňmi na mjá ľstivomúdryj: no jáko Bóh uščédri i spasí mja, Nikolája molítvami."),
("", "", "Velíkoje spasénije vsím nám javílsja jesí, Nikólaje preblažénne: izbavľáješi bo vsjáčeskich bíd i napástej rabý tvojá, i iskušénij i nedúhov i obstojánija, i vrahóv nevídimych."),
("Bohoródičen", "", "Vélija čudés tvojích čístaja, síla: izbavľáješi bo ot bíd, i spasáješi ot smérti, i voschiščáješi ot napástej nenačájemych, i skórbi razrišáješi, i sohrišénija čelovíkov otémleši."),
),
"S": (
("", "", "Vo vsjú zémľu izýde viščánije váše svjatíji apóstoli, ídoľskuju prélesť razrušíste, Bohorazúmije propovídavše: sé dóbryj pódvih váš jésť blažénniji. Sehó rádi pojém, i slavoslóvim pámjati váša."),
("", "", "Živonósnaho vinohráda súšče lózije, slávniji apóstoli, plód blahočéstija sámi sja Bóhu prinesóste. Ťímže derznovénije imúšče k nemú, prosíte darováti mír, i véliju mílosť dušám nášym."),
("", "", "Múčenicy tvojí Hóspodi, víroju utvérždšesja, i nadéždeju ukrípľšesja, ľubóviju krestá tvojehó dušévno sojedinívšesja, vrážije mučíteľstvo razrušíša: i ulučívše vincý, so bezplótnymi móľatsja o dušách nášich."),
("Bohoródičen", "", "Veľmí sohrišájušča mjá otrokovíce, ischití velíkoju tvojéju molítvoju plámene núždnaho: i isprávi čístaja tvojími moľbámi, ko spasíteľnym stezjám nastavľájušči mjá, Máternimi tvojími molítvami."),
),
)
#let P = (
"1": (
("", "", "Vódy drévle mánijem božéstvennym vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem, séj Bóh náš, preproslávlen jésť: tomú jedínomu pojím, jáko proslávisja."),
("", "", "Stenánije mí úbo podážď Bohoródice sokrušénnoje, i slézu dušévnuju, jáko da mojích mnóhich prehrišénij pláčusja, i sóvisti neispravlénija otrokovíce, i umoľú milosérdije tvojé."),
("", "", "Pómysly popolzájasja, i vpádaja v bézdnu pohíbeli, tvojé Ďívo nýňi moľú zastuplénije: utverdí nepokolebímo nemožénije umá mojehó na kámeni tvérďim Bóžijich zápovidej."),
("", "", "Smokóvnicu nošú bezplódija, i bojúsja posičénija i prí, da ne vo óhň póslet mjá ziždíteľ mój Bóh. Vladýčice predvarívši, pokajánija mjá ďíly plodonósna sotvorí, da slávľu ťá."),
("", "", "Jáko neporóčen chrám carév, strasťmí bezmístnymi oskvérnšejesja sérdce mojé, moľúsja, očísti prečístaja, cilomúdrijem že i čístym žitijém, i ďíly obohatí Bohoblahodátnaja."),
),
"3": (
("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."),
("", "", "Borjúščiji i oskorbľájuščiji mjá mnózi súť, i ňísť osláby obristí izbavlénija ot obyšédšich mjá: no ne prézri čístaja molénija mojehó."),
("", "", "Oťahčén mnóžestvom zlých, i mnóhimi prehrišéniji mojími, k vysoťí nebésňij vozzríti ne mohú: no tý ostavlénije mí podážď, prečístaja."),
("", "", "Rastórhnuti smirénnuju mojú dúšu zmíj lukávyj po vsjá dní pokušájetsja: no semú sokruší Bohoródice dušetľínnyja zúby."),
("", "", "Izbávi mjá Bohoródice vsjákija oderžáščija bidý, i hrichóvnyja búri rabá tvojehó: i k spasíteľnomu mjá pristánišču naprávi tvojími molítvami."),
),
"4": (
("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi, jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."),
("", "", "Trepéšču pomyšľája hrichóv mojích pučínu, i soprotívnych pomyšlénij ľútoje i velíkoje volnénije: no tý okormí, i k tišiňí naprávi mjá prečístaja."),
("", "", "Nedovíďinije ťážkoje dúšu mojú nýňi postíže, nerazúmije i zabvénije zlých, jáže v žitií soďíjach: no tý úbo prečístaja, na pokajánije soďíjannych mnóju navedí mja."),
("", "", "Óhň strastéj sléznymi strujámi uhasí, i udavľájuščeje mój úm žitéjskoje trevolnénije, i térnije popalí ohném Dúcha Bohorodíteľnice: tý bo pokróv mí jesí i pochvalá."),
("", "", "Molvóju napástej i trevolnénij vés potopľájem jésm lukávymi pómysly, i vo hlubinú otčájanija prísno nizvlekóm, vopijú ti: Vladýčice spasí mja rabá tvojehó."),
),
"5": (
("", "", "Jáko víďi Isáia obrázno na prestóľi prevozneséna Bóha, ot ánhel slávy dorinosíma, o okajánnyj, vopijáše, áz: províďich bo voploščájema Bóha, svíta nevečérňa, i mírom vladýčestvujušča."),
("", "", "Duší mojejá boľízni, i plóti nemožénije vísi Vladýčice, i umá mojehó hnílosť i nepostojáteľnoje. Ťímže spodóbi mjá mílosti i blahodáti tvojejá, da ťá slávľu spasájem króvom tvojím."),
("", "", "Ne zatvorí mi milosérdija ščedrót tvojích, Vladýčice vseneporóčnaja: no vo umiléniji prichoďáščemu k tebí podážď tvojá mílosti, i ľútych preminénije i proščénije, jáko da blahodárno pojú velíčija tvojá."),
("", "", "Umnóžišasja Ďívo nenavíďaščiji mjá vsúje, i oskorbľájuščiji nýňi, páče vlás hlavý mojejá čístaja, íščušče rastórhnuti, i sňíď sotvoríti sebí: sích úbo studá ispólnši vozvratí."),
("", "", "Jáže mírovi mír, i spasénije vsém podávšaja, jáko božéstvennyj mír poróždši Ďívo, bráň strastéj duší mojejá i ťíla, čístaja, umirí stráchom i ľubóviju Spása Christá."),
),
"6": (
("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."),
("", "", "V ďíľi i slóvi i ďijániji, ňísť zľí požívša na zemlí, jákože áz: ťímže tvojehó prošú Vladýčice čelovikoľúbija, ulučíti mílosti."),
("", "", "Ďijánija zlých prehrišénij, pečáli raždájut vsím ťímže hórkimi napásťmi oderžími jesmý nýňi: pomozí nám, jáže jedína christijánom spasénije."),
("", "", "I raždáješi, i čistá po roždeství javílasja jesí Bohoródice Ďívo. ťímže molí tvojé roždestvó prísno, da izbávimsja ot vsjákaho vréda vrážija tvojí rabí."),
("", "", "Molítvami prečístyja Mátere tvojejá, i vsích prorók i múčenik, i svjaščénnych učeník, Slóve Bóžij podážď nám mír, i očiščénije prehrišénij."),
),
"S": (
("", "", "Vsé žitijé mojé v ľínosti mnózi preidóch prečístaja, i nýňi priblížichsja ko ischódu mojehó vrémene, i ustrašíchsja ot vrahóv mojích, da ne rastórhnut dúšu mojú vseneporóčnaja, i v pohíbeli mjá hlubinú otpúsťat: no uščédri rabá tvojehó Ďívo, i izbávi mjá sích ozloblénija."),
),
"7": (
("", "", "Jákože drévle blahočestívyja trí ótroki orosíl jesí v plámeni chaldéjsťim, svítlym Božestvá ohném i nás ozarí, blahoslovén jesí, vzyvájuščyja, Bóže otéc nášich."),
("", "", "Tebé <NAME> čístuju i neporóčnuju, oskvernénnyj ťílom i dušéju, i okaľánnyj ďijáňmi nečístymi, moľú Vladýčice, naďíjasja na mílosť tvojú uščédri mjá prečístaja."),
("", "", "Prehrišénij mojích mnóžestvo, i zlých ispytánije, nedoumínijem mjá prepirájet ziló, i vo otčájanija vlečét mjá hlubinú: no tý prečístaja Vladýčice, spasí mja pohibájuščaho, i ľúťi potopľájema."),
("", "", "Mnóžestvom ščedrót tvojejá bláhosti, hrichóv nášich mnóžestvo prézri bláže, i blahopremínen búdi nemólčno zovúščym: blahoslovén jesí Hóspodi Bóže otéc nášich."),
("", "", "Ot brénija strastéj, i hlubiný skorbéj, i napástej žitéjskich, privlecý nás k bezstrástiju čístaja, i rádostnomu veséliju, blahoslovénnaja, zovúščich: tý jesí jedína Bohoblahodátnaja."),
),
"8": (
("", "", "Veščéstvennaho ohňá plámeň neveščéstvennym uvjadíša, Bohozrímiji ótrocy, i pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda."),
("", "", "Slastéj hóresť čúvstva vsjá ťilésnaja prošédši, dúšu mojú bezmístno okaľájet, i v smérť vlečét: Vladýčice míra, búdi mí spasénije."),
("", "", "Na ťá dúšu, i sérdce, i ťílo vozložích: ne ímam bo inýja nadéždy rázvi tebé Vladýčice, jéjuže polučú mílosti. Ťímže mí podážď bohátuju tvojú mílosť i blahodáť."),
("", "", "Zmíj mjá jádom pripolznúv, plotskóju slástiju okajánnuju dúšu mojú ľúťi umorí: no oživí sijú soprotívnymi ľičbámi, čístaja, tvojími molítvami."),
("", "", "Jáže Bóha i Spása róždšaja, mironačáľnika, tohó molí, mír mírovi posláti vskóri, jáko da v míri tohó slavoslóvim."),
),
"9": (
("", "", "Tebé neopalímuju kupinú, i svjatúju Ďívu, Máter svíta, i Bohoródicu, nadéždu vsích nás veličájem."),
("", "", "Skvérnu strástnych pomyšlénij mojehó umá očísti čístaja, v bezstrástija rízu svítluju oďivájušči mjá."),
("", "", "Otvérzi mí Ďívo božéstvennyja vchódy pokajánija, vchódy strastéj i slastéj mojích zahraždájušči, i vozbraňájušči síloju tvojéju."),
("", "", "Uslýši hlás stenánija mojehó, i hlás pláča mojehó, i podážď očiščénije i spasénije okajánňij mojéj duší, Ďívo vseneporóčnaja."),
("", "", "Víďi Danijíl prorók tvojé roždestvó Ďívo, víďi risnotívno voístinnu, íže na prestóľi víďi, jehóže déňmi vétchaho vozhlasí."),
),
)
#let U = (
"S1": (
("", "", "Prijidíte vsí, apóstoly voschválim jáko kórmčyja: ídoľskuju bo prélesť uprazdníša, i k svítu žízni vozvedóša, i v Tróicu vírovati naučíša. Ťímže dnés pámjať ích čestnúju soveršájušče vírniji, slávim Christá Bóha nášeho."),
("", "", "Apóstol tvojích pámjať ujasníl jesí Hóspodi, jáko vsesílen, jáko ukripíl jesí ích, strastém tvojím podóbitisja, i pobidíša múžeski vrážiju sílu. Ťímže i prijáša iscilénij blahodáti: ťích molítvami čelovikoľúbče, mír podážď ľúdem tvojím."),
("Bohoródičen", "", "Nepostižímaho i neopísannaho, jedinosúščnaho beznačáľnomu Otcú, vo črévo tvojé tájno vmistíla jesí Bohoródice. Jedíno i nesmísno ot Tróicy Božestvó razumíchom, roždestvó tvojé v míri slávjašče. Ťímže i blahodárno vopijém tí: rádujsja obrádovannaja."),
),
"S2": (
("", "", "Vsjú napoíša zémľu strujámi apóstoli, Bóžija Slóva, i vozrasté klás víry, i koncý vselénnyja napólni: plévely bo vsjá posikóša. Ťímže vsích Christú Bóhu privedóša, kreščájušče ťích v Tróicu nesozdánnuju."),
("", "", "Vsjú napoíša zémľu strujámi apóstoli, Bóžija Slóva, i vozrasté klás víry, i koncý vselénnyja napólni: plévely bo vsjá posikóša. Ťímže vsích Christú Bóhu privedóša, kreščájušče ťích v Tróicu nesozdánnuju."),
("", "", "Strastotérpcy svjatíji, molíte mílostivaho Bóha, da prehrišénij ostavlénije podást dušám nášym."),
("Bohoródičen", "", "Prorócy propovídaša, apóstoli naučíša, múčenicy ispovídaša, i mý vírovachom Bohoródicu ťá voístinnu súščuju: ťímže i veličájem roždestvó tvojé, prečístaja."),
),
"S3": (
("", "", "Apóstoly tvojá Christé, v koncý zemnýja poslál jesí, jáko milosérd, jáko izoščrényja síľňi stríly, zakalájuščja vsjákoje nečéstije i zlosújetstvije, i nasaždájuščja spasítelnaja učénija: ťích moľbámi ščédre, mír podážď dušám nášym."),
("", "", "Tebé propovídnika ístiny, i presvítlaho svitílnika míru, chváľašče vospivájem Nikólaje, i vopijém víroju moľáščesja: jákože nepovínnyja ot smérti ischítil jesí: táko svjáte, i nás ot bíd i skorbéj i vsjákaho izbávi ľútaho ozloblénija."),
("Bohoródičen", "", "Umertvívšujusja dúšu mojú sohrišéňmi mnóhimi, vseneporóčnaja Vladýčice: oživí, jáko derznovénije máterneje k Sýnu tvojemú imúšči: tý bo jedína rodilá jesí páče umá i smýsla Slóvo sobeznačálnoje Otcú i Dúchu, živót i netľínije míru dárujušča prísno, i véliju mílosť."),
),
"K": (
"P1": (
"1": (
("", "", "Vódy drévle, mánijem božéstvennym, vo jedíno sónmišče sovokupívyj, i razďilívyj móre Izráiľteskim ľúdem: séj Bóh náš, preproslávlen jésť: tomú jedínomu poím, jáko proslávisja."),
("", "", "Cerkóvnyja stolpý, osnovánija víry, blahočéstnaja utverždénija, i vírnyja vsjá utverždájuščaja, prijidíte ublažím svjaščénnyja apóstoly, jáko da moľbámi ích spasémsja."),
("", "", "Cerkóvnyja stolpý, osnovánija víry, blahočéstnaja utverždénija, i vírnyja vsjá utverždájuščaja, prijidíte ublažím svjaščénnyja apóstoly, jáko da moľbámi ích spasémsja."),
("", "", "Sám sebé préžde sudá blúdnyj ubojávsja osuždáju, zlája bo ďilá bezčíslennaja sťažách. Ťímže moľúsja tí právednyj Sudijé: otčájannaho mjá spasí božéstvennymi moľbámi apóstol tvojích."),
("", "", "Neprevrátniji stolpý blahočéstija, preľščénijem mjá vrážijim prepjátaho, i na zemlí ležáščaho i bídstvujuščaho, i nedoumivájuščahosja isprávite, jáko da obrjášču ostavlénije, o níchže sohriších."),
("Bohoródičen", "", "So svjatými proróki, so apóstoly, i múčeniki, iz tebé voplóščšahosja Hóspoda, priľížno čístaja molí, jáko da plotskíja náša vsjá strásti umertvít, i živót víčnyj nám dárujet."),
),
"2": (
("", "", "Pojím Hóspodevi, sotvóršemu dívnaja čudesá v čermňím móri: póntom bo pokrý protívnyja, i spasé Izráiľa. Tomú jedínomu poím, jáko proslávisja."),
("", "", "Presvítlaho svitíľnika neuhasímaho, na zemlí súščaho stolpá, i k pristánišču božéstvennomu prizyvájušča, íže volnámi žitéjskimi prísno potopľájemiji, Nikolája vsí počtím, i ľubóviju ublažím."),
("", "", "Síloju Bóžijeju vseblažénne ukripľájem, révnosť blahočéstija po rázumu sťažál jesí: ťímže choťáščyja neprávedno umréti izbávil jesí. Sehó rádi ťá mólim: vsjákaho neprávednaho ozloblénija izbávi nás Nikólaje."),
("", "", "Molénija Hóspodevi ótče neoskúdno prinosí tý: jáko da hrichóv i plámene mučénija víčnujuščaho, i napástej, i skorbéj izbávit nás, jáko jedín blahíj."),
("Bohoródičen", "", "Kovčéh božéstvennyj íže vmistívšij zakonodávca náša bezzakónija vsjá otjémľuščaho, rádi milosérdija božéstvennaho neskazánnyja pučíny, Maríju prečístuju sohlásno vospojím."),
),
),
"P3": (
"1": (
("", "", "Íže ot ne súščich vsjá privedýj, slóvom sozidájemaja, soveršájemaja Dúchom, vsederžíteľu výšnij, v ľubví tvojéj utverdí mené."),
("", "", "Íže míra koncý učénija božéstvennaho ispólnivše, dúšu mojú ispólnite dobroďítelnych ďijánij, i pomyšlénij blahích, Christóvy samovídcy."),
("", "", "Íže míra koncý učénija božéstvennaho ispólnivše, dúšu mojú ispólnite dobroďítelnych ďijánij, i pomyšlénij blahích, Christóvy samovídcy."),
("", "", "Ot soblázn mnóhich lukávaho, i ot vsjákija skórbi, i ot vsjákija ťisnotý, ot vsjákaho obstojánija, učenicý Christóvy izbávite mjá."),
("", "", "Uvý dušé mojá okajánnaja i smirénnaja, částo sohrišájušči, i Bóha prohňívajušči, káko isprósiši proščénije zlých, íchže ne prestajéši tvorjášči?"),
("Bohoródičen", "", "Božéstvennaja ľístvice, júže víďi Jákov, po néjže sníde Bóh, voznosjá nás, priľížno molí so apóstoly, uščédriti nás."),
),
"2": (
("", "", "Neplódnaja dušé i bezčádnaja, sťaží plód blahoslávnyj, veseľáščisja vozopíj: utverdíchsja tobóju Bóže, ňísť svját, ňísť práveden, páče tebé Hóspodi."),
("", "", "Izoščrén méč duchóvnyj javílsja jesí múdre: lukávyja plévely jeretíčestvujuščich posicája, i dobroďítelej stezí spasíteľnyja vírnym uhlaždája, ótče Nikólaje."),
("", "", "Tebí istóčniku istočájušču iscilénij potóki, mólimsja svjáte: skvérny strastéj vsích nás molítvami tvojími omýj, bíd i skorbéj izbavľája."),
("", "", "Krípkimi tvojími molítvami nizlahája vrahá, i nýňi náň ukripí nemoščstvújuščaja pomyšlénija náša strástnymi prilóhi, prizyvánijem svjatých tvojích molítv, ótče Nikólaje."),
("Bohoródičen", "", "Úm razumíti ne móžet, jéže páče umá roždénije, čudésnaho roždestvá tvojehó, Bohorodíteľnice vseneporóčnaja, ťímže moľú ťa: úm mój oblahodatí prísno sláviti ťá."),
),
),
"P4": (
"1": (
("", "", "Položíl jesí k nám tvérduju ľubóv Hóspodi: jedinoródnaho bo tvojehó Sýna za ný na smérť dál jesí. Ťímže tí zovém blahodarjášče: sláva síľi tvojéj Hóspodi."),
("", "", "Jákože mólniji, i jáko lučí nezachodímaho sólnca, apóstoly prostirája Slóve, v mirskíja koncý, vsích prosvitív, i bezbóžija mrák othnál jesí."),
("", "", "Jákože mólniji, i jáko lučí nezachodímaho sólnca, apóstoly prostirája Slóve, v mirskíja koncý, vsích prosvitív, i bezbóžija mrák othnál jesí."),
("", "", "Móre ľútaho hrichá Slóve oburevájet mjá, i volnénija bezčínnych pomyšlénij smirénnuju dúšu mojú smuščájut: okormíteľu Hóspodi, učenik tvojích moľbámi spasí mja."),
("", "", "Užasájusja pomyšľája strášnoje tvojé Vladýko prišéstvije: ímam bo préžde sudá, mojú osuždájuščuju mjá vnútr sóvisť, i préžde múčaščija múki, nečúvstvije mojé."),
("Bohoródičen", "", "Slóve Bóžij, íže roždéjsja ot Ďívy Bohootrokovícy tojá chodátajstvy svjaščénnymi, i premúdrych apóstol tvojích Spáse, vsjákaho obstojánija i vsjákija núždy izbávi dúšy náša."),
),
"2": (
("", "", "Priosinénnuju hóru Avvakúm prozrjáše prečístuju tvojú utróbu čístaja. Ťím vzyváše: ot júha priídet Bóh, i svjatýj ot horý priosinénnyja čášči."),
("", "", "K Bóhu chodátaja vsják vírnyj vsehdá Nikólaje predlahájet ťá. Ťímže ťá mólim, ot napástej ľútych, i padénij hrichóvnych nás izbávi ótče."),
("", "", "Vódu žívu v sérdci imýj blahodáť Hospódňu, orošáješi prísno múdre, znójem skorbéj, i suchotóju hrichóv bídstvujuščich, okajánňi pohíbnuti imúščich, vseblažénne."),
("", "", "Íže izbávil jesí inohdá vedómyja na smérť neprávedno, vseblažénne: nýňi i nás spásáj ot čelovík tletvórnych stužénija, i ot vsjákija bisóvskija lésti."),
("Bohoródičen", "", "Voplóščšesja Slóvo premnóžestvom blahoutróbija neizrečénno rodilá jesí: tohó molí prečístaja, plotskíja strásti i skvérny vsích izbáviti, i vsích núždnych žitijá."),
),
),
"P5": (
"1": (
("", "", "Na zemlí nevídimyj javílsja jesí, i čelovíkom vóleju sožíl jesí nepostižímyj: i k tebí útreňujušče, vospivájem ťá čelovikoľúbče."),
("", "", "Na zemlí voplóščsja, soďílal jesí učenikí, nebesá viščájušča Christé slávu tvojú: ťích rádi úbo Hóspodi, dúšy náša pomíluj."),
("", "", "Na zemlí voplóščsja, soďílal jesí učenikí, nebesá viščájušča Christé slávu tvojú: ťích rádi úbo Hóspodi, dúšy náša pomíluj."),
("", "", "Ot strastéj i ot vsjákija núždy, ot ľútaho obstojánija, Slóve izbávi rabý tvojá, apóstol tvojích blahoprijátnymi molítvami."),
("", "", "Uvý mňí dušé vsestrástnaja, káko chóščeši strášnomu sudú predstáti bezplódna súšči? Potščísja, pokájsja, dobroďítelej plodý vozraščájušči."),
("Bohoródičen", "", "Íže na zemlí jávľšahosja neizrečénno s plótiju, ot čístych krovéj tvojích čístaja, molí jáko Sýna tvojehó vsehdá, očiščénije nám darováti."),
),
"2": (
("", "", "Svítom tvojím nevečérnim Christé, ozarí Bóže smirénnuju mojú dúšu, i nastávi na strách tvój, zané svít poveľínija tvojá."),
("", "", "Svítu čístomu predstojá, i ottúdu prísno ischoďáščimi zarjámi prosviščájem ótče, isprosí vsím očiščénije i mír."),
("", "", "Mené páče vsích čelovík tebé prohňívavša umóm nerazúmnym, preblahíj uščédri, Nikoláa téplymi molítvami."),
("", "", "Vo unýniji iždívša mojú žízň, moľúsja tí ótče Nikólaje, vozdvíhni k pokajániju mýsľ mojú oskvernénuju."),
("Bohoródičen", "", "Jáko jedína ánhelov rádosť Bohorádovannaja, rádosti ispólni mojú mýsl sítujuščuju, i ľínostiju pohružájemuju."),
),
),
"P6": (
"1": (
("", "", "Bézdna posľídňaja hrichóv obýde mjá, i isčezájet dúch mój: no prostrýj Vladýko vysókuju tvojú mýšcu, jáko Petrá mja upráviteľu spasí."),
("", "", "Bézdnu premúdrosti duchóvnyja istočívše, apóstoľskoje soslóvije, mirskáho izsuší mudrovánija tečénije, i napój blahočestívych sobránija."),
("", "", "Bézdnu premúdrosti duchóvnyja istočívše, apóstoľskoje soslóvije, mirskáho izsuší mudrovánija tečénije, i napój blahočestívych sobránija."),
("", "", "Vozdochní i proslezísja smirénnaja dušé mojá, i vozopíj ko Hóspodu, hlahóľušči: sohriších tí Vladýko, očísti mjá blahoutróbne, moľbámi premúdrych apóstol tvojích."),
("", "", "Potekóša potócy strastéj, i potopíša mojú dušévnuju chráminu: ríki duchóvnyja bývše apóstoli, sokrušénnaho mjá k životú obnovíte."),
("Bohoródičen", "", "Sobór ťá apóstolov Christé, mólit s róždšeju ťá: očiščénije nizposláti i mír rabóm tvojím, jáko čelovikoľúbec i Bóh bláhopreminíteľ."),
),
"2": (
("", "", "Hlubiná strastéj vostá na mjá, i búrja protívnych vítrov: no predvarív mjá tý spasí Spáse, i izbávi ot tlí, jáko spásl jesí ot zvírja proróka."),
("", "", "Umertvív vozderžánijem údy, sťažál jesí žízň nestaríjemuju: jéjže i nás óbščniki tvojími molítvami soďílaj múdre, izbižánijem zláho hrichá."),
("", "", "Vítrilom svjaščénnych tvojích molítv, pučínu napástej mnohoobráznych, i hrichóvnyja hlubiný izbávi nás, ko pristánišču že životá privoďá múdre svjatíteľu."),
("", "", "Ukrasív mirlikíjskij prestól, javílsja jesí krasotá pervosvjaščénnikom: no molítvami tvojími ot mirskích napástej spasáj ný nevredímy, svjatíteľu."),
("Bohoródičen", "", "Vselívšejesja vo utróbu tvojú Slóvo, Máti čístaja, drévle v čelovícich vselívšujusja ot prestuplénija tľú, jáko Bóh jedín, vňí izhnál jésť, za milosérdije mílosti."),
),
),
"P7": (
"1": (
("", "", "Préžde óbrazu zlatómu, persídskomu čtílišču, ótroki ne pokloníšasja, trijé pojúšče posreďí péšči: otcév Bóže blahoslovén jesí."),
("", "", "Íže svít míru Christós, svít vás pokazá, svitonósniji apóstoli, razhoňájuščich ťmú preľščénija, i prosviščájuščich vírnych mýsli."),
("", "", "Íže svít míru Christós, svít vás pokazá, svitonósniji apóstoli, razhoňájuščich ťmú preľščénija, i prosviščájuščich vírnych mýsli."),
("", "", "Jáže na nás vrážija síti sokrušíte, Bohohlásniji apóstoli, i stezí nám pokajánija uhládite, k vám pribihájuščym."),
("", "", "Objuroďívšuju dúšu mojú plotskími strasťmí sóľ božéstvennaja súšče Bohohlahóliviji Hospódni apóstoli, očístite vírno oživľájušče."),
("Bohoródičen", "", "Dobróto Jákovľa, dóbrymi mjá zráki prosvití, moľúsja, moľáščisja nýňi so apóstoly, róždšemusja ot tvojích čístych krovéj."),
),
"2": (
("", "", "Trijé ótrocy v peščí Tróicu proobrazívše, preščénije óhnennoje popráša, i pojúšče vopijáchu: blahoslovén jesí Bóže otéc nášich."),
("", "", "Hubjáščaho drévle Hospódni ľúdi, bezúmnaho Ária udavíl jesí žílami slovés tvojích, jáko pástyr načáľnyj ístinen, ótče Nikólaje."),
("", "", "Svjáto prešéd presvjatóe žitijé tvojé, so svjatými živéši ótče Nikólaje, svjaščénije posylája i prosviščénije blahočéstno ťá blažáščym."),
("", "", "Jáko hotóva ťá izbáviteľa, jáko tépla zastúpnika prizyvájem prísno ótče Nikólaje, ot strastéj nás izbávi i nečájemych napástej, nachoďáščich na ný."),
("Bohoródičen", "", "Mené nebrežénijem dúšu omračívšaho, prosvití čístaja, jáže svít róždšaja, sérdca mojehó vozžizájušči svitíľnik, jáko da usérdijem blahím slávľu ťá."),
),
),
"P8": (
"1": (
("", "", "Nesterpímomu ohňú sojedinívšesja, Bohočéstija predstojášče júnoši, plámenem že nevreždéni, božéstvennuju písň pojáchu: blahoslovíte vsjá ďilá Hospódňa Hóspoda, i prevoznosíte vo vsjá víki."),
("", "", "Ujazvíchsja strastéj orúžijem, i ostrupích sérdce bezúmijem, zlóby soďíteľem: apóstoli slávniji iscilíte mjá vsehó nedoumíjuščasja, dúš i ťilés vráčeve súšče."),
("", "", "Ujazvíchsja strastéj orúžijem, i ostrupích sérdce bezúmijem, zlóby soďíteľem: apóstoli slávniji iscilíte mjá vsehó nedoumíjuščasja, dúš i ťilés vráčeve súšče."),
("", "", "Vo vsjú zémľu propovídnikov viščánije izýde božéstvennoje, učáščeje pravoslávno o jedínstvennom suščeství, jedíno jestestvó počitáti svjatýja Tróicy, i jedíno voístinnu Hospóďstvo, i jedíno cárstvo vo vsjá víki."),
("", "", "Mené mnohosohrišívšaho, i dolhoterpínije tvojé božéstvennoje iždívšaho. V prebyvániji prehrišénij, vozvratí Vladýko, vídyj mojú némošč Slóve, i ľínosť, i zlomúdrije."),
("Bohoródičen", "", "Božéstvennaja kleščé, jáže božéstvennaho úhľa neizrečénno prijémši Bohoródice, strastéj mojích razžžénnoje úhlije uhasí prečístaja, rosóju tvojích molítv, i vseslávnych i božéstvennych apóstol."),
),
"2": (
("", "", "Ánhelmi nemólčno vo výšnich slávimaho Bóha, nebesá nebés, zemľá, i hóry, i chólmi, i hlubiná, i vés ród čelovíčeskij, písňmi tohó jáko sozdáteľa, i izbáviteľa blahoslovíte , i prevoznosíte vo vsjá víki."),
("", "", "Zémľu krótkich nasľídoval jesí, krótok prepodóbne býv. Ťímže moľúsja tí vírno: ukrotí molítvami tvojími, podvizájuščajasja na mjá prísno lukávaho trevolnénija."),
("", "", "Jákože izbávil jesí vojevódy, íže neprávedno umréti choťáščyja: táko ot čelovík lukávych ozloblénija nás izbávi, i ot vsjákaho bisóvskaho navíta, Nikólaje, moľá Spása."),
("", "", "Púť pokazál jesí čelovíkom právyj i spasíteľnyj: na nehóže nastávi nás v žitijí prechoďáščich Nikólaje, molítvami tvojími, jáko da kúpno vnídem v živótnaja vratá."),
("Bohoródičen", "", "Kríposť i pínije mojé jésť, íže iz tebé roždéjsja prečístaja, jehóže priľížno molí Ďívo, razsláblennaho mjá strasťmí ukripíti, i tvoríti spasíteľnaja jehó poveľínija."),
),
),
"P9": (
"1": (
("", "", "V zakóňi síni i pisánij óbraz vídim vírniji, vsják múžeskij pól ložesná razverzája, svját Bóhu: ťím pervoroždénnoje Slóvo, Otcá beznačáľna, Sýna pervoroďáščasja Máteriju neiskusomúžno, veličájem."),
("", "", "Íže slovesý tvojích učenik, utverdíl jesí zemnýja koncý Otcá beznačáľnaho Slóve: ťích moľbámi, i mené, k strastém bezslovésnym popólzšasja, i bisóvskim preľščénijem potopľájema uščédri."),
("", "", "Íže slovesý tvojích učenik, utverdíl jesí zemnýja koncý Otcá beznačáľnaho Slóve: ťích moľbámi, i mené, k strastém bezslovésnym popólzšasja, i bisóvskim preľščénijem potopľájema uščédri."),
("", "", "Dušé mojá, strastéj rabótajuščaja ustremlénijem, postradávšemu nás rádi prinesí moľbý, jáko da izbávit ťá ľútych, moľáščymsja projavlénne svjaščénnym učenikóm, i upodóbľšymsja tohó plotskím stradánijem."),
("", "", "Christóvy učenicý, jehdá s ním sudíti sjádete sudú povínnych, neosuždénnu mojú dúšu sobľudíte, oskvernénnuju bezmístnymi ďíly, jáko blazíji mojí predstátelije, i jáko míra zastúpnicy."),
("Bohoródičen", "", "Ďívo čístaja, Ďívo prečístaja, Christóva paláto, Ďívo presvjatája, svjatáho svjatých Bóha, páče viný i slóva róždšaja, so apóstoly svjatými, o vsích molísja."),
),
"2": (
("", "", "Na sinájsťij horí víďi ťá v kupiňí Moiséj, neopáľno óhň Božestvá začénšuju vo črévi, Danijíl že ťá víďi hóru nesikómuju, žézl prozjábšij, Isáia vzyváše, ot kórene Davídova."),
("", "", "Jáko ohraždénije božéstvennoje i utverždénije, i dóbroje pribížišče, zemnýj mír sťažá ťá: chodátajstvy bo tvojími prísno izbavľájemsja ot vsjákaho iskušénija i ťisnotý, ótče Nikólaje. Ťímže vo chvaléniji vírno ublažájem ťá."),
("", "", "Uťisňájem býv mnóhimi obstojániji, k prostránstvu pribiháju vseblažénne, téplych molítv tvojích, pretvorí duší mojejá boľízni, vopijú ti: vólny ukrotí otčájanija, i umirí mojehó umá smuščénije."),
("", "", "Tvorcá nastoít prišéstvije sudíti vséj zemlí, i nehotóv sýj okajánnyj, vés ustrašájusja, pomyšľája zól mojích mnóžestvo: Hóspodi dolhoterpilíve, uščédri, i spasí mja božéstvennymi Nikolája molítvami prepodóbnaho tvojehó."),
("Bohoródičen", "", "Prosviščénije mojé spasíteľnoje javílasja jesí, róždšaja svít, duší mojejá óblaki razhoňájušči mráčnyja i ľútyja: jáko da Sýn dné molítvami tvojími búdu soďivája prepodóbnaja, jáko da v pisnoslovléniji prepodóbne ublažáju ťá."),
),
),
),
"ST": (
("", "", "Vo vsjú zémľu izýde viščánije váše svjatíji apóstoli: ídoľskuju prélesť razrušíste, Bohorazúmije propovídavše. Sé dóbryj pódvih váš jésť blažénniji, ťímže pojém i slavoslóvim váša pámjati."),
("", "", "Christóvy zápovidi neporóčno sochráňše, svjatíji apóstoli, túne prijáste, túne podavájete, isciľájušče strásti dúš i ťilés nášich. Ťímže imúšče derznovénije, tohó molíte, pomílovatisja dušám nášym."),
("", "", "Jáko svitíla v míri sijájete, i po smérti svjatíji múčenicy, pódvihom dóbrym podvíhšesja. Imúšče derznovénije, Christá molíte, pomílovatisja dušám nášym."),
("Bohoródičen", "", "Bez símene začalá jesí ot Dúcha svjatáho, i slavoslóvjašče vospivájem ťá: rádujsja presvjatája Ďívo."),
)
)
#let L = (
"B": (
("", "", "Otvérhša Christé, zápoviď tvojú, práotca Adáma iz rajá izhnál jesí: razbójnika že ščédre, ispovídaša ťá na kresťí, vóň vselíl jesí, zovúšča: pomjaní mja Spáse, vo cárstviji tvojém."),
("", "", "Íže tróstiju krestnoju iz hlubiný nevíďinija ľúdi izvédše apóstoli, i jéllinskuju prélesť othnáste ot zemlí, neléstniji spasítelije býste vírnym voístinnu. Ťímže blažími jesté."),
("", "", "Jáko lučí tájnyja, i svitíla právednaho sólnca bývše, slávniji apóstoli, zločéstija ťmú othnáli jesté, i k svítu Bohorazúmija nastáviste vsjá ľúdi: ťímže vý počitájem."),
("", "", "Múk razžžénija preterpíste, svýše stradáľcy blahodáti rósu prijáli jesté: i čelovíčeskija strásti, jáko Christóvy uhódnicy, prísno blahočéstno múdriji isciľájete. Ťímže vírno vás svjatíji počitájem."),
("", "", "Tróicy svjaščénniji propovídnicy, Pétre, i Pávle, Márko, i Lukó, Matféje, Símone, Jákove, Andréje, Joánne, Thomó, Vartholomée i Filíppe múdre, priľížno vsehdá sijú molíte, izbávitisja nám ot vsjákaho obstojánija."),
("", "", "Apóstolov dobróto, i svjatých strastotérpec rádovanije, Bohoblahodátňijšaja Vladýčice, o nás molí vsích Spása i Bóha: jáko da prehrišénij priímem ostavlénije, i božéstvennyja žízni vsí pričástnicy búdem."),
)
) |
|
https://github.com/danilasar/conspectuses-3sem | https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Ассемблер/240927.typ | typst | = Элементы архитектуры ПК и ассемблер для IBM PC
Ассемблер может обрабатывать целые десятичные, шестнадцатеричные, действительные с плавающей точкой, строковые и символьные константы.
- Двоичные целые --- последовательность нулей и единиц, заканчивающихся символом b
- Десятичные --- обычные положительные и отрицательные или заканчивающиеся символом d числа
- Шестнадцатеричные заканчиваются символом h или, если константа начинается с цифр ABCDEF, перед ней можно записать нолик.
- Действительные с плавающей точкой представляются в виде мантиссы и порядка, где буква e --- основание системы, умноженное в соответствующую степень (0.547e-2, 34.751e+02)
- Символьные данные
/ Строки: --- последовательности символов, заключённые в апострофы или кавычки
В ассемблере есть именованные константы, определяемые директивой equ:
```nasm
m equ 27
```
Переменные в ассемблере определяются с помощью директив определения данных и памяти или с помощью директивы равенства
```nasm
v1 db ?
v2 dw 34
v3 = 100
v3 = v3 + 1
```
Константы в основном используются как операнды в выражениях или в директивах определения данных и памяти.
Выражения строятся из операндов, операторов и скобок. Операнды --- это константы и переменные, операторы --- это знаки операций (арифметические, логические, операции отношений, специальные _военные_ операции).
- Арифметические операции: `+`, `-`, `\*`, /, mod
- Логические операции: and, or, xor
- Операции отношений записываются с помощью символов `lt` ($<$), `le` ($<=$), `ne` ($eq.not$), `eq` ($=$), `gt` ($>$), `ge` ($>=$)
- Спецоперации: `offset`, `ptr`
- `offset имя`, где `имя` --- имя переменной или метка, --- смещение относительно начала сегмента
- `[размер] ptr имя`
- `near` --- ближний тип вызова
- `far` --- дальний тип вызова
== Директива определения
Директива определения данных и памяти имеет вид, соответствующий общему виду директив.
Вот они, слева направо: `db, dw, dd, de, dq, dt`.
Операнды --- это одна или несколько констант, разделённых запятыми. Директива выделяет в памяти определённое количество полей памяти, присваивая имени адрес первого байта в выделенной области памяти.
Если операндом в этой директиве является символическое имя, которому уже поставлен в соответствие какой-то адрес, а это мы могли делать с помощью другой такой же директивы (например)
Если мы хотим выделить 100 полей определённого размера и заполнить их одним и тем же значением, то для этого можно использовать специальный повторитель `dup`.
С помощью этой же директивы мы можем определить одномерный массив, прописав элементы через запятую.
```nasm
m dd im1 ; двойное слово --- адрес im1
d db 100 dup(1) ; 100 байт 0x01
mas dw 1, 7, 35, 75, 84 ; одномерный массив слов
```
Определим двумерный массив:
```nasm
arr db 7, 14, 11, -5
db 5, 0, 1, 2
db -5, 0, 15, 24
```
Строковые константы можно определить с длиной вплоть до 255 символов. Команда определения слова определит широкосимвольную строку.
Команда `int` прерывает работу процессора.
Чтобы вывести на экран '!', необходимо:
```nasm
mov ah, 6
mov di, '!'
int 21h
```
== Команды работы со стеком
Адрес начала сегмента стека загружается в регистр `ss` операционной системой автоматически. На вершину стека указывает регистр `sp` (`esp`, `rsp`). Добавить элемент в стек --- команда `push операнд`, где операнд --- регистр или переменная. Для взятия из стека используется `pop операнд`.
Чтобы работать со всеми регистрами, существуют команды `push a` и `pop a`. Они позволяют положить в стек и считать из стека регистры общего назначения в следующей последовательности: `ax`, `bx`, `cx`, `as`, `bs`, `cs`, `si`, `di`.
Для 32-разрядных регистров существуют `push ad` и `pop ad`, работающие с `eax, ebx, ecx, edx, esp, ebp, esi, edi`.
Чтобы не удалять данные из стека, используют регистр `bp`:
```nasm
mov bp, sp ; (sp) -> bp
mov ax, [bp+6] ; (ss:(bp - 6)) -> ax
```
Пересылаем 4 байта из одной области памяти в другую в обратной последовательности и выводим их на экран:
```nasm
title print.asm ; определяет заголовок листинга программы, там может быть до 60 символов
page ,120 ; определяет количество строк на странице листинга и количество символов в строке (количество строк по умолчанию, символов до 120, в теории максимум 132), может использоваться без параметров, тогда она осуществляет переход на следующую страницу листинга
Sseg Segment Para stack 'stack'
db 100h dup (?)
sseg ends
DSeg Segment Para Public 'data'
dan db '1', '3', '5', '7'
rez db 4 dup (?)
dseg ends
CSeg Segment Para Public 'code'
assume ss:SSeg, ds:DSeg, cs:CSeg
Start proc far
push ds
xor ax, ax
push ax ; положили пустое слово
mov ax, dsex
mov ds, ax
mov ah, 6
mov dl, dan + 3
mov rez, dl
int 21h
mov dl, dan + 2
mov rez + 1, dl
int 21h
mov dl, dan + 1
mov rez + 2, dl
int 21h
mov dl, dan
mov rez, dl
int 21h
Start endp
CSeg ends
end Start
```
== Директива сегмента
```nasm
<имя> Segment <ReadOnly> <выравнивание> <тип> <размер> <'класс'>
```
== Точечные директивы
```nasm
.model small
.data
st1 db 'Line1', '$'
st2 db 'Line2', '$'
st3 db 'Line3', '$'
.code
begin: mov ax, @data ; заносим в сегментный регистр ds
mov ds, ax ; физический адрес сегмента данных
mov ah, 9 ; номер функции вывода строки на экран
mov dx, offset st1 ; адрес st1 должен содержаться в регистре dx
int 21h
mov dx, offset st2
int 21h
...........
mov ax, 4c00h
int 21h
end begin
```
`$` --- конец строки, которую необходимо вывести на экран.
В результате выполнения программы:
```
Line1 Line2 Line3
```
Если необходимо построчно, нельзя забывать про байты 13, 10 (они же 0dh, 0ah).
|
|
https://github.com/GartmannPit/Praxisprojekt-II | https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/README.md | markdown | # PVA-Templates
This template is a typst template with an in detail guide to use it. You can find all the information in the README.typ file.
Please note: the standard language of the tempate outcome is German, although the guide and files are written in English/ with English comment.
The places to change the language are highlighted with comments.
To compile a pdf document just run
````console
typst c paper.typ
````
in the terminal after installing the Typst Compiler. |
|
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/layout/titlepage.typ | typst | MIT License | #let titlepage(
title: "",
titleGerman: "",
degree: "",
program: "",
supervisor: "",
advisors: (),
author: "",
startDate: datetime,
submissionDate: datetime,
) = {
// Quality checks
assert(degree in ("Bachelor", "Master"), message: "The degree must be either 'Bachelor' or 'Master'")
set page(
margin: (left: 20mm, right: 20mm, top: 30mm, bottom: 30mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(leading: 0.5em)
// --- Title Page ---
v(1cm)
align(center, image("/figures/logo.png", width: 26%))
v(5mm)
align(center, text(font: sans-font, 2em, weight: 700, "Technical University of Munich"))
v(5mm)
align(center, text(font: sans-font, 1.5em, weight: 100, "School of Computation, Information and Technology \n -- Informatics --"))
v(15mm)
align(center, text(font: sans-font, 1.3em, weight: 100, degree + "’s Thesis in " + program))
v(8mm)
align(center, text(font: sans-font, 2em, weight: 700, title))
align(center, text(font: sans-font, 2em, weight: 500, titleGerman))
let entries = ()
entries.push(("Author: ", author))
entries.push(("Supervisor: ", supervisor))
// Only show advisors if there are any
if advisors.len() > 0 {
entries.push(("Advisors: ", advisors.join(", ")))
}
entries.push(("Start Date: ", startDate.display("[day].[month].[year]")))
entries.push(("Submission Date: ", submissionDate.display("[day].[month].[year]")))
v(1cm)
align(
center,
grid(
columns: 2,
gutter: 1em,
align: left,
..for (term, desc) in entries {
(strong(term), desc)
}
)
)
}
|
https://github.com/lrmrct/CADMO-Template | https://raw.githubusercontent.com/lrmrct/CADMO-Template/main/thesis.typ | typst | #set document(title: [CADMO Template],
author: "<NAME>",
keywords: ("Template", "CADMO", "ETH Zurich"),
date: auto)
#import "template/layout.typ": layout
#import "template/cover.typ": cover
#import "template/abstract.typ": abstract
#import "template/theorems.typ": theorem, proof, counter_reset
#show: layout
#show: cover.with(
title: [
Title of Thesis
],
thesis_type: [
Bachelor Thesis
],
authors: (
(
name: "<NAME>",
email: "<EMAIL>",
),
),
date: [January 19, 2038],
advisors: [Prof. Dr. <NAME>, Dr. P. Ostdoc],
department: [Department of Computer Science, ETH Zürich]
)
#show: abstract.with(
abstract: [This example thesis briefly shows the main features of our thesis style, and how to use it for your purposes.]
)
#outline(title: none, indent: 1.8em)
#set page(numbering: "1")
#counter(page).update(1)
= Introduction
This is version `v1.0` of the template.
I assume that you found this template on my #link("https://github.com/lrmrct/CADMO-Template")[Github], it is a quick and dirty translation of the CADMO thesis template into Typst which was originally written in LaTeX.
In this chapter I'll give a brief overview of the files and functions you are looking at. Please consult the Typst documentation for more details.
TODOs:
- Add missing text.
- Exact margins and font sizes.
- Section headers.
- Insert Q.E.D. into math body
- Showcase visualizations.
== Features <features>
The rest of this document shows off a few features of the template files. Look
at the source code to see which functions we used!
The template is divided into Typst files as follows:
+ `thesis.typ` is the main file.
+ `layout.typ` defines the style used in this document.
+ `theorems.typ` declares the theorem-like environments.
+ `cover.typ` creates the cover page.
+ `abstract.typ` creates the abstract page.
+ `refs.yml` is an example bibliography file. For example, read the book from Bringhurst @bringhurst1996ets if you can get a hold of it.
If you need to refer to multiple authors without wanting to name them, you can refer to an article by Einstein et al. @einstein1935can.
=== Extra package includes
There are currently no extra 3rd-party packages included.
One doesn't need an extra package to reference section in Typst.
As a small example, here is a reference to the Section #emph("Features").
#quote()[
See @features
]
=== Layout setup
This defines the overall look of the document -- for example, it
changes the chapter and section heading appearance. We consider this
a 'do not touch' area. It tries to replicate the look of the excellent #emph("Memoir") package.
=== Theorem setup
This file defines a bunch of theorem-like environments.
#theorem[An example theorem.]
#proof[Proof text goes here.]
Note that the q.e.d. symbol moves to the correct place automatically if you
end a proof. You do not need to use `square`.
#theorem(author: "<NAME>")[Another example theorem.]
#proof[This proof
1. ends in an enumerate.]
#theorem(name: "Proposition")[
Note that all theorem-like environments are by default numbered on the same counter.
]
#proof[This proof ends in a display like so:
$ f(x) = x^2. $]
#pagebreak()
=== Macro setup
There is no need for a macro setup in Typst, just look how simple it is:
$ abs(a), space.quad abs(a/b), space.quad abs(size:#75%, a/b). $
= Writing scientific texts in English
This chapter was originally a separate document written by <NAME>. It is reprinted here so that the template can serve as a quick guide to thesis
writing, and to provide some more example material to give you a feeling for good typesetting.
== Basic writing rules
The following rules need little further explanation; they are best understood by looking at the example in the booklet by Knuth et al., §2–§3.
#theorem(name: "Rule")[Write texts, not chains of formulas.]
More specifically, write full sentences that are logically interconnected by phrases like 'Therefore', 'However', 'On the other hand', etc. where appropriate.
#theorem(name: "Rule")[Displayed formulas should be embedded in your text and punctuated with it.]
In other words, your writing should not be divided into 'text parts' and 'formula parts'; instead the formulas should be tied together by your prose such that there is a natural flow to your writing.
== Being nice to the reader
Try to write your text in such a way that a reader enjoys reading it. That's of course a lofty goal, but nevertheless one you should aspire to!
#pagebreak()
#theorem(name: "Rule")[Be nice to the reader.]
Give some intuition or easy example for definitions and theorems which might be hard to digest. Remind the reader of notations you introduced many pages ago – chances are he has forgotten them. Illustrate your writing with diagrams and pictures where this helps the reader. Etc
#theorem(name: "Rule")[Organize your writing.]
Think carefully about how you subdivide your thesis into chapters, sections,
and possibly subsections. Give overviews at the beginning of your thesis and
of each chapter, so the reader knows what to expect. In proofs, outline the
main ideas before going into technical details. Give the reader the opportunity
to 'catch up with you' by summing up your findings periodically.
_Useful phrases:_ 'So far we have shown that . . .', 'It remains to show that . . .' , 'Recall that we want to prove inequality (7), as this will allow us to deduce
that . . .', 'Thus we can conclude that . . . . Next, we would like to find out whether . . .', etc.
#theorem(name: "Rule")[Don't say the same thing twice without telling the reader that you are saying it twice.]
Repetition of key ideas is important and helpful. However, if you present the
same idea, definition or observation twice (in the same or different words)
without telling the reader, he will be looking for something new where there
is nothing new.
_Useful phrases:_ 'Recall that [we have seen in Chapter 5 that] . . .', 'As argued before / in the proof of Lemma 3, . . . ', 'As mentioned in the introduction, . . .', 'In other words, . . . ', etc.
#theorem(name: "Rule")[Don't make statements that you will justify later without telling the reader that you will justify them later.]
This rule also applies when the justification is coming right in the next sentence! The reasoning should be clear: if you violate it, the reader will lose valuable time trying to figure out on his own what you were going to explain to him anyway.
_Useful phrases:_ 'Next we argue that . . .', 'As we shall see, . . .', 'We will see in the next section that . . ., etc.
== A few important grammar rules
= Typography
== Punctuation
= Example Chapter
Dummy text.
== Example Section
Dummy text.
=== Example Subsection
Dummy text.
==== Example Subsubsection
Dummy text.
#show outline: set heading(outlined: true)
#bibliography("refs.yml")
#heading(numbering: none)[A Dummy Appendix]
You can defer lengthy calculations that would otherwise only interrupt the flow of your thesis to an appendix.
|
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/Hashmaps.typ | typst | #import "../../../template.typ": *
= Hashmaps
#definition[
*Hashmaps*: array backed data structure that allows us to use "custom" or flexible keys instead of using only indices. It uses a _hashing_ function to dictate which indexes corresponds to what data in the backing array.
]
No 2 entries cannot have the same key, and you cannot go into a map entry and change the key (_immutable_).
Hashmaps generics are denoted as \<K, V> for the type for Key, and the type for Value.
Hashmaps are backed by arrays, and we put data into a certain index based on its key value. In order to calculate an index for a certain key, we use a *hashing function*.
#theorem[
*Hash Function*: represents our key object as an integer value(hashcode)
Maps the hashcode to an integer in the backing array.
`if A.equals(B)` #sym.arrow.r `A.hashcode == B.haskcode`
If hashcodes are the same, we CANNOT assume that A.equals(B)
]
We use a compression function by using % on the hashcode in order to get a smaller index. This is useful when hash functions output very large numbers even when there are only a few entries. However, this can cause collisions!
#note[
*Where to put Key?*
```java index = abs (key.hashCode() & arr.length)```
]
_How do we avoid collisions?_
We do this by controlling the size of the backing array. *For hashmaps, it is very bad to let the backing array get full*, because this causes collisions (from the `%` operator). In order to solve this, we resize while there is still space left in the array.
#theorem[
$"load factor" = "size" / "capacity"$
We usually set a maximum allowed load factor in order to avoid collisions. This factor is typically between 0.6 to 0.8, and Java's default is 0.75. After this loadfactor, we resize.
]
#note[
*Small Load Factors* has more resizes and fewer collisions, while *Large Load Factors* are more efficient with memory but cause more collisions.
]
Another way to avoid collisions is to have a _good hashing function_, where different items have different hashes, and a harder goal: similar items have way different hashcodes.
== Collission Handling
*External Chaining *
Chaining together all the entries that end up at the same index and keeping them in a small linked list. This is a _closed addressing strategy_, because entries are put where they actually belong. Here, array element points to the head of the linked list
#note[
We still want to resize periodically so that the chains don't get too long and impact run times. So we need to see each value in each linked list to find the size of the array
]
*Resizing*
For each entry in the old backing array:
For each entry in that index: calculate where to put the entry in the resized array: ```java key.hashCode() % newBackingArray.length```
== Linear Probing
Linear proving is considered *open addressing*, because the index we compute will change. Unlike external chaining, only one key value pair can occupy an index.
To identify a new index for an entry, we use a technique called *probing*, which are open addressing strategies, because the first index we calculate is not necessarily where we might end up putting it.
#definition[
*Linear Probing*: If a collision occurs at a given index, increment the index by one and check again. Do this until a null spot is found.
```java index = (h + origIndex) % backingArray.length```
h = . number of times probed (0, 1, 2, N).
At first, assume h is zero. If they key value pair isn't found, then add to the index.
] |
|
https://github.com/nafkhanzam/typst-common | https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/gray.typ | typst | #let binary-to-gray(digits) = {
let str-res = str(digits.at(0))
for i in range(digits.len() - 1) {
let l = int(digits.at(i))
let r = int(digits.at(i + 1))
let xorr = if l == r {
0
} else {
1
}
str-res += str(xorr)
}
return str-res
}
#let gray-to-binary(digits) = {
let str-res = str(digits.at(0))
let bef = int(digits.at(0))
for i in range(1, digits.len()) {
let l = int(digits.at(i))
let xorr = if l == bef {
0
} else {
1
}
str-res += str(xorr)
bef = xorr
}
return str-res
}
#let decimal-to-gray(v) = v.bit-xor(v.bit-rshift(1))
#let gray-to-decimal(v) = {
let res = 0
while v {
res = res.bit-xor(v)
v = v.bit-rshift(1)
}
return res
}
|
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/typstonomicon/index.md | markdown | MIT License | # Typstonomicon, or The Code You Should Not Write
Totally cursed examples with lots of quires, measure and other things to hack around current Typst limitations.
Generally you should use this code only if you really need it.
<div class="warning">
Code in this chapter may break in lots of circumstances and debugging it will be very painful. You are warned.
</div>
I think that this chapter will slowly die as Typst matures.
|
https://github.com/d-mironov/typst-slides-uni-freiburg | https://raw.githubusercontent.com/d-mironov/typst-slides-uni-freiburg/main/slides.typ | typst | MIT License | #import "template.typ": slides, transition
#show: slides.with(
paper: "TensorFlow Lite Micro: Embedded Machine Learning",
title: "Related Work",
author: "",
date: "2023-11-13",
// display-lastpage: false,
// short-title: "The mechanical energy",
)
#outline(title: "Agenda")
= Why Machine Learning on Embedded Systems?
// Why is it important to run ML on embedded systems?
= Examples
// Images of projects that use ML on embedded systems
= Problems
// Problems associated with ML on embedded systems
= Related Work
// Related work in the field of ML on embedded systems
#bibliography("bibliography.bib")
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/document-00.typ | typst | Other | // This is okay.
#set document(title: "Hello")
What's up?
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2019/MS-08.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[1], [马龙], [CHN], [3546],
[2], [樊振东], [CHN], [3422],
[3], [许昕], [CHN], [3374],
[4], [林高远], [CHN], [3328],
[5], [王楚钦], [CHN], [3249],
[6], [林昀儒], [TPE], [3245],
[7], [蒂姆 波尔], [GER], [3225],
[8], [梁靖崑], [CHN], [3207],
[9], [周雨], [CHN], [3120],
[10], [雨果 卡尔德拉诺], [BRA], [3118],
[11], [张本智和], [JPN], [3104],
[12], [乔纳森 格罗斯], [DEN], [3054],
[13], [于子洋], [CHN], [3052],
[14], [金光宏畅], [JPN], [3045],
[15], [郑荣植], [KOR], [3031],
[16], [方博], [CHN], [3027],
[17], [闫安], [CHN], [3025],
[18], [张禹珍], [KOR], [3023],
[19], [马蒂亚斯 法尔克], [SWE], [3018],
[20], [迪米特里 奥恰洛夫], [GER], [3002],
[21], [弗拉基米尔 萨姆索诺夫], [BLR], [3001],
[22], [孙闻], [CHN], [2975],
[23], [水谷隼], [JPN], [2972],
[24], [帕特里克 弗朗西斯卡], [GER], [2967],
[25], [安宰贤], [KOR], [2967],
[26], [赵胜敏], [KOR], [2956],
[27], [吉村和弘], [JPN], [2955],
[28], [刘丁硕], [CHN], [2952],
[29], [丹羽孝希], [JPN], [2948],
[30], [周启豪], [CHN], [2946],
[31], [克里斯坦 卡尔松], [SWE], [2929],
[32], [#text(gray, "丁祥恩")], [KOR], [2927],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[33], [郑培峰], [CHN], [2926],
[34], [徐晨皓], [CHN], [2925],
[35], [马克斯 弗雷塔斯], [POR], [2923],
[36], [吉村真晴], [JPN], [2914],
[37], [西蒙 高兹], [FRA], [2909],
[38], [托米斯拉夫 普卡], [CRO], [2906],
[39], [夸德里 阿鲁纳], [NGR], [2894],
[40], [林钟勋], [KOR], [2890],
[41], [艾曼纽 莱贝松], [FRA], [2889],
[42], [黄镇廷], [HKG], [2888],
[43], [卢文 菲鲁斯], [GER], [2885],
[44], [李尚洙], [KOR], [2882],
[45], [达科 约奇克], [SLO], [2869],
[46], [利亚姆 皮切福德], [ENG], [2867],
[47], [#text(gray, "大岛祐哉")], [JPN], [2865],
[48], [贝内迪克特 杜达], [GER], [2862],
[49], [及川瑞基], [JPN], [2854],
[50], [<NAME>], [SVK], [2853],
[51], [朱霖峰], [CHN], [2850],
[52], [赵子豪], [CHN], [2848],
[53], [薛飞], [CHN], [2846],
[54], [庄智渊], [TPE], [2837],
[55], [神巧也], [JPN], [2835],
[56], [WALTHER Ricardo], [GER], [2832],
[57], [<NAME>], [SWE], [2827],
[58], [吉田雅己], [JPN], [2826],
[59], [上田仁], [JPN], [2825],
[60], [塞德里克 纽廷克], [BEL], [2824],
[61], [GNANASEKARAN Sathiyan], [IND], [2819],
[62], [HIRANO Yuki], [JPN], [2815],
[63], [安东 卡尔伯格], [SWE], [2815],
[64], [汪洋], [SVK], [2811],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[65], [PARK Ganghyeon], [KOR], [2804],
[66], [ZHAI Yujia], [DEN], [2801],
[67], [KOU Lei], [UKR], [2799],
[68], [雅克布 迪亚斯], [POL], [2797],
[69], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2796],
[70], [TAKAKIWA Taku], [JPN], [2787],
[71], [马特], [CHN], [2785],
[72], [GERELL Par], [SWE], [2782],
[73], [WEI Shihao], [CHN], [2779],
[74], [森园政崇], [JPN], [2772],
[75], [特鲁斯 莫雷加德], [SWE], [2769],
[76], [安德烈 加奇尼], [CRO], [2766],
[77], [周恺], [CHN], [2762],
[78], [村松雄斗], [JPN], [2761],
[79], [卡纳克 贾哈], [USA], [2761],
[80], [王臻], [CAN], [2760],
[81], [SKACHKOV Kirill], [RUS], [2758],
[82], [松平健太], [JPN], [2752],
[83], [巴斯蒂安 斯蒂格], [GER], [2750],
[84], [沙拉特 卡马尔 阿昌塔], [IND], [2749],
[85], [詹斯 伦德奎斯特], [SWE], [2748],
[86], [<NAME>], [POL], [2743],
[87], [HWANG Minha], [KOR], [2741],
[88], [MONTEIRO Joao], [POR], [2740],
[89], [SHIBAEV Alexander], [RUS], [2740],
[90], [诺沙迪 阿拉米扬], [IRI], [2738],
[91], [赵大成], [KOR], [2733],
[92], [<NAME>], [ESP], [2733],
[93], [宇田幸矢], [JPN], [2727],
[94], [LANDRIEU Andrea], [FRA], [2726],
[95], [特里斯坦 弗洛雷], [FRA], [2725],
[96], [HABESOHN Daniel], [AUT], [2724],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[排名], [运动员], [国家/地区], [积分],
[97], [户上隼辅], [JPN], [2723],
[98], [徐瑛彬], [CHN], [2722],
[99], [邱党], [GER], [2722],
[100], [蒂亚戈 阿波罗尼亚], [POR], [2717],
[101], [#text(gray, "金珉锡")], [KOR], [2708],
[102], [廖振珽], [TPE], [2708],
[103], [<NAME>], [SWE], [2706],
[104], [博扬 托基奇], [SLO], [2705],
[105], [牛冠凯], [CHN], [2705],
[106], [<NAME>], [TPE], [2704],
[107], [<NAME>], [SLO], [2702],
[108], [BADOWSKI Marek], [POL], [2699],
[109], [<NAME>], [ALG], [2698],
[110], [#text(gray, "朴申赫")], [PRK], [2688],
[111], [<NAME>], [POR], [2687],
[112], [KATSMAN Lev], [RUS], [2686],
[113], [SALIFOU Abdel-Kader], [FRA], [2685],
[114], [尼马 阿拉米安], [IRI], [2685],
[115], [田中佑汰], [JPN], [2685],
[116], [<NAME>], [ENG], [2683],
[117], [安德斯 林德], [DEN], [2677],
[118], [斯特凡 菲格尔], [AUT], [2675],
[119], [SIPOS Rares], [ROU], [2672],
[120], [<NAME>], [JPN], [2670],
[121], [陈建安], [TPE], [2668],
[122], [木造勇人], [JPN], [2666],
[123], [LIU Yebo], [CHN], [2666],
[124], [奥维迪乌 伊奥内斯库], [ROU], [2664],
[125], [#text(gray, "SEO Hyundeok")], [KOR], [2664],
[126], [#text(gray, "高宁")], [SGP], [2663],
[127], [罗伯特 加尔多斯], [AUT], [2661],
[128], [CHIANG Hung-Chieh], [TPE], [2661],
)
) |
|
https://github.com/csimide/SEU-Typst-Template | https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/lib.typ | typst | MIT License | #import "templates/bachelor.typ": bachelor-conf, bachelor-utils
#import "templates/degree.typ": degree-conf, degree-utils |
https://github.com/ntjess/typst-tada | https://raw.githubusercontent.com/ntjess/typst-tada/main/docs/manual.typ | typst | The Unlicense | #import "@preview/tidy:0.1.0"
#import "../lib.typ" as tada
#import "_doc-style.typ"
// https://github.com/ntjess/showman.git
#import "@local/showman:0.1.0": formatter
#let _HEADING-LEVEL = 1
#show raw.where(lang: "example"): it => {
heading(level: _HEADING-LEVEL + 2)[Example]
it
}
#outline(indent: 1em, depth: _HEADING-LEVEL + 1)
#include("./overview.typ")
// overview applies its own template show, so scope this only to the module docs
#show: formatter.template.with(
// theme: "dark",
eval-kwargs: (
direction: ltr,
scope: (tada: tada, display: tada.display),
unpack-modules: true,
),
)
#for file in ("tabledata", "ops", "display") {
let module = tidy.parse-module(read("../src/" + file + ".typ"), scope: (tada: tada))
heading[Functions in #raw(file + ".typ", block: false)]
tidy.show-module(module, first-heading-level: _HEADING-LEVEL, show-outline: false, style: _doc-style)
} |
https://github.com/sthenic/technogram | https://raw.githubusercontent.com/sthenic/technogram/main/src/common.typ | typst | MIT License | /* A function to get text color (white/black) that's appropriate for the background. */
/* See https://stackoverflow.com/a/3943023 */
#let get-text-color(col) = {
let (red, green, blue) = rgb(col).components(alpha: false)
if red * 29.9% + green * 58.7% + blue * 11.4% > 73% {
black
} else {
white
}
}
|
https://github.com/JeyRunner/tuda-typst-templates | https://raw.githubusercontent.com/JeyRunner/tuda-typst-templates/main/templates/tudapub/common/outline.typ | typst | MIT License |
#let tudapub-make-outline-table-of-contents(
// How the table of contents outline is displayed.
// Either "adapted": use the default typst outline and adapt the style
// or "rewritten": use own custom outline implementation which better reproduces the look of the original latex template.
// Note that this may be less stable than "adapted", thus when you notice visual problems with the outline switch to "adapted".
outline_table_of_contents_style: "rewritten",
// style/layout parameters
fill_dot_space: 3pt,
heading_numbering_intent: 1em,
heading_numbering_width_per_level: 0.65em,
heading_first_level_v_space: 15pt,
heading_page_number_width: 1.5em,
// all headings with a level larger than this number will be excluded from the outline
heading_numbering_max_level: none
) = {
// check args
if not (outline_table_of_contents_style == "adapted" or outline_table_of_contents_style == "rewritten") {
panic("outline_table_of_contents_style has to be either 'adapted' or 'rewritten'")
}
// alternative (simpler than next solution)
if outline_table_of_contents_style == "adapted" {
show outline.entry.where(
level: 1
): it => {
// prevent recursion
if it.fill != none {
// new outline entry without fill
let params = it.fields()
params.fill = none
//params.page = [#params.page]
strong[
#set text(
font: "Roboto",
fallback: false,
)
#v(14pt, weak: true)
#outline.entry(..params.values())
]
} else {
it
}
}
outline(
target: heading.where(outlined: true),
depth: heading_numbering_max_level,
indent: 1em,
fill: block(width: 100% - 1em)[
#repeat[ #h(fill_dot_space) . #h(fill_dot_space) ]
]
)
}
//*/
// own outline elements
// @deprecated
/*
let mem-lengths = state("mem-lengths", ())
let space = 1em
show outline.entry: it => style(styles => {
locate(loc => {
let el = it.element
let c-heading = numbering(el.numbering, ..counter(heading).at(el.location()))
let indent = if it.level > 1 {
mem-lengths.at(loc).at(it.level - 2)
} else {0pt}
let preamb = [#h(indent)#c-heading#h(space)]
let size = measure(preamb, styles)
mem-lengths.update(array => {
if array.len() > it.level - 1 {
array.at(it.level - 1) = size.width
} else {
array.push(size.width)
}
array
})
/*
let text_params = ()
if it.level == 1 {
text_params = (
font: "Roboto",
fallback: false,
weight: "bold"
)
}
set text(
..text_params
)*/
[
#preamb#el.body
#box(width: 1fr, repeat[ #h(fill_dot_space) . #h(fill_dot_space)])
#box(width: 1.5em)[
#align(right)[#it.page]
]
//#it.page
]
})
})
*/
// own rewritten outline
if outline_table_of_contents_style == "rewritten" {
heading(
level: 1, outlined: false
)[Contents]
locate(loc => {
let headings = query(
selector(heading.where(outlined: true)).after(loc),
loc,
)
// outline params
let heading_numbering_intent = 1em
let heading_numbering_width_per_level = 0.65em
let heading_first_level_v_space = 15pt
let heading_page_number_width = 1.5em
// go over all headings
for it in headings {
if it.level > heading_numbering_max_level {
continue
}
// save location and page of current heading
let it_loc = it.location()
//let it_page = numbering(it_loc.page-numbering(), ..counter(page).at(it_loc))
let page = counter(page).at(it.location())
let it_counter_arr = counter(heading).at(it_loc)
let numbering_width = heading_numbering_width_per_level*it.level
let sum_prev_levels = range(it.level).sum()
let padd = ( (it.level - 1) * heading_numbering_intent
+ (sum_prev_levels) * heading_numbering_width_per_level*1
)
// box[#pad(left: padd)
let preamb = box(fill: none)[#pad(left: padd)[
#box(width: numbering_width + heading_numbering_intent, fill: none, {
// if heading has numbering
if it.numbering != none {
numbering(it.numbering, ..it_counter_arr) //.display(it.numbering)
}
else {
//numbering("1.1", ..it_counter_arr) + "?"
}
})
//#h(1em)
]]
//let t = 0
//t = measure(preamb, styles).width
//[#t]
// only count, if the heading is numbered!
let text_params = ()
let fill_dots = box(width: 1fr, repeat[ #h(fill_dot_space) . #h(fill_dot_space)])
// heading with level 1 has different styling
if it.level == 1 {
text_params = (
font: "Roboto",
fallback: false,
weight: "bold"
)
fill_dots = box(width: 1fr)//, repeat(str.from-unicode(32)))
v(heading_first_level_v_space, weak: true)
}
set text(
..text_params
)
link(it_loc)[
#preamb#it.body
#fill_dots
#box(width: heading_page_number_width)[
#align(right)[#page.join()]
]
//#it.page
//\
//#it.fields()
//#outline.entry(it.level, it, [Test], [], [])
\
]
}
})
}
} |
https://github.com/Tiggax/zakljucna_naloga | https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/sec/uvod/3.%20num%20metode.typ | typst | #set heading(offset: 1)
#import "/src/additional.typ": todo
#import "@preview/cetz:0.2.2": canvas, plot, draw, vector
#set math.equation(numbering: "(1.1)")
Ordinary differential equations or shorter @ODE[s], are equations that for a unknown function $y(x)$ have a form
$
F(x, y(x),y'(x), dots, y^((n))(x)) = 0
$<general_ode>
where $F$ is the given function.
@ODE can be expressed in implicitly like in @general_ode or in explicitly form like
$
F(x, y(x),y'(x), dots, y^((n-1))(x)) = y^((n))
$
They differ from Partial differential equations in the number of variables. @ODE[s] derivatives are taken only in respect to one variable, where as partial differential equations depend on several independent variables.
== First order differential equations
The _order_ of a @ODE is the order of the highest derivative, that takes place in the equation. Therefore first-order @ODE solved for the derivative has a form of
$
y'(x) = F(x,y(x))
$ <general_first_ode>
When working with more complex systems, $y(x)$ can be a vector-valued function.
Therefore when working in $RR^N$, and $x$ can take on any real value, then
$
&F&: &RR times RR^N &arrow &RR^N,
\
&y&: &RR &arrow &RR^N
$
give the domain and range of the function $F$, which defines the @ODE and the solution to this equation @butcher_2016[p.1-2].
We can find a function $phi$ such that
$
phi : D subset.eq RR arrow RR^N
$
is a solution of @general_first_ode in a set of $D$, if it is derivable the said set, and equation
$
phi'(x) = F(x,phi(x))
$
holds for each $x in D$.
Sometimes @general_first_ode is represented in terms of differentials as $d y = F(x,y)d x$.
In this, a solution of @ODE is a function $y(x)$ which when substituted into the equation, turns the equation into an identity.
_The general solution of a @ODE _ is the set of all its solutions @Polyanin_2017[p. 3].
The general solution can also be called the general integral of an equation.
Geometrically this solution is a family of curves in the $x y$-plane.
These curves are called _integral curves_ of the @ODE.
To each particular solution of the general solution, there corresponds a single curve that passes through a given point in the plane.
For each point $(x,y)$, the @general_first_ode defines a value of $y'(x)$ that can be seen in @ode_example.
That value represents the so-called slope of the integral curve that passes through that point @Polyanin_2017[p.3-4].
That is to say the @ODE generates a field of directions in the $x y$-plane.
#figure(
caption: [The vector field for the equation $y'(x) = x - y$ and an integral curve for a point $(x_0, y_0)$ in the said curve.],
image("/figures/ode-example.png", width: 90%)
)<ode_example>
=== Cauchy problem <cauchy>
The _Cauchy problem_ also known as the initial value problem asks to find a solution of @general_first_ode that satisfies the initial condition of
$
y(x_0) = y_0
$
where $y_0$ and $x_0$ are some numbers.
This means geometrically, that the solution is an integral curve of the @general_first_ode that passes through the point $(x_0,y_0)$ as seen in @ode_example.
=== Solving First order differential equations
The simplest @ODE follows the form of
$
y'(x) = f(x)
$
The solution for these equations at $y(x_0) =y_0$ is
$
phi(x) = y_0 + integral_(x_0)^x f(t) d t
$
Most of the time the equations like @general_first_ode come in some form of
$
y'(x) = f(x)g(y(x))
$<product_ode>
where the $x$ and $y(x)$ parts can be separated in some form of product.
For @ODE[s],like @product_ode, their form can be reformatted into
$
integral 1 / (g(y(x))) d y= integral f(x)d x + C
$
where $C$ is an arbitrary constant.
The general solution is one-parametric family of curves.
If the initial value is given, the constant $C$ can be determined.
if $g(y(x)) = y(x)$, we talk about _linear differential equations_.
$
F(x,y) = p(x) dot y(x) + q(x)
$
where $p$ and $q$ are functions of $x$ only, then the @ODE @general_first_ode[] is called linear, otherwise it is nonlinear @dreyer_2017[p. 23].
@LDE is _homogeneous_ if $q(x) = 0$, otherwise it is _non-homogeneous_.
In many cases the independent variable $x$ is denoted as $t$, as to imply the _time_.
and so @general_first_ode can also be denoted as
$
y'(t) = F(t, y(t))
$
or in cases when talking about systems of @ODE[s]
$
X'(t) = F(t, X(t))
$
The classes of differential equations that can be solved exactly (in closed form) using current exact methods are quite limited, covering only a small portion of practical problems.
For this reason, numerical methods are widely used today.
These methods are applicable to a broad range of equations and allow for obtaining specific solutions to particular problems @Polyanin_2017[p. 61-62].
== Single-step methods
Let us say that we have an interval of $[x_0, x_*]$.
The interval splits into $n$ equal segments of length $h = (x_* - x_0) / n$.
$y_1, dots, y_n$ then denote the approximate values of the function $y(x)$ at the points $x_1, dots, x_n = x_*$.
This discrete set of points $X_h = {x_0, x_1, dots, x_n}$ is called a mesh, where $h$ is _mesh increment_ or _step size_ and the individual points $x_k$ are called _mesh nodes_.
Collection of values is called a _mesh function_ and written as $y^((h)) = {y_k, k = 0,1,dots,n}$@Polyanin_2017[p. 62].
A single-step method is generally a numerical method that provides successively an approximation of the exact solution, $y_(k+1)$ , at the point $x_(k+1)$ based on the known approximation $y_k$ at the point $x_k$ @Polyanin_2017[p. 63].
== Euler Method <euler_sec>
#let ni = $i+1$
The Euler Method follows a very simple principle.
Suppose there is a particle.
It is moving in such a way, that at time $x_0$ its position is equal to $y_0$, and velocity is known to be $v_0$.
Over a short period of time, such that there has not been time for the velocity to change significantly from $v_0$, the change in position will be approximately equal to the change in time multiplied by $v_0$.
If the motion of the particle can be expressed as a differential equation, then the value of $v_0$ is known as a function of $x_0$ and $y_0$.
Therefore if given $x_0$ and $y_0$, the solution at $x_1$, assuming that it is close to $x_1$, can be written as
$
y_1 = y_0 + (x_1 - x_0) dot v_0
$
A step can of $y_1$ can then be calculated from known values of $x_0, x_1, y_0$ and $v_0$.
Assuming that $v_1$ can be found using the differential equation from values of $x_1$ and $y_1$, a second step can be taken using
$
y_2 = y_1 + (x_2 - x_1) dot v_1
$
to find an approximate solution of $y_2$ at $x_2$.
This step can then be repeated to get an approximation of a solution.
This solution for approximation at $y_ni$ can then be written as
$
y_ni = y_i + (x_ni - x_i) dot v_i
$<general_euler>
Sometimes @general_euler is written as
$
y^*_ni = y^*_i + h f(x_i, y^*_i)
$<general_euler_h>
where the
- $y^*_i$ is short for the approximation of $y(x)$ at $x_i$
- $h = (x_ni - x_i)$
- $f$ represents the function of velocity or the derivative of change at the previous point.
It is important that the step taken is over a short period of time, as having bigger steps can create a different result.
@euler shows how a difference in step size can affect the result of the solution.
By using larger steps, each value down the line can be less accurate.
#figure(
caption: [Example of an Euler method, where each color represents a different step size and the black line represents the theoretical solution],
image(
"/figures/euler.png",
width: 90%
)
)<euler>
=== Similarities between Euler and the Taylor series<euler_v_taylor>
Let us assume that the solution $y(x)$ exists to the Cauchy problem talked about in @cauchy, and it can be written as a Taylor series at the point $x = x_i+1$.
Then taking the Taylor series
$
f(x) = f(a)
+ (f^((1)) (a))/1!(x - a)
+ (f^((2)) (a))/2!(x - a)^2
+ dots
+ (f^((n)) (a))/n!(x - a)^n
$
Substituting $x$ with $x_ni$, $a$ with $x_i$, and then changing $(x_ni - x_i)$ with $h$ to represent the change of independent variable.
Then knowing that $f(x_i, y(x_i)) = y^((1))(x_i)$ we can write out Taylor series as
$
y(x_ni) = y(x_i)
+ h f(x_i, y(x_i))
+ h^2 / 2 y^((2))(x_i)
+ h^3 / 6 y^((3))(x_i)
+ dots
$<euler_taylor>
Taking the first two terms from the Taylor series results in @general_euler_h.
Upon examining @euler_taylor, a question arises: what if the approximation incorporated more than just the initial two terms of the Taylor series?
Given the understanding of the Taylor series, this should ideally result in an improvement in accuracy.
== Runge-Kutta method
Runge-Kutta is not one method, but a family of implicit and explicit iterative methods, of which Euler method (talked about in @euler_sec) is one of.
They are used to find approximate solutions of simultaneous nonlinear equations.
The most known method from this family is known as simply "the Runge-Kutta", "classic Runge-Kutta" or simply as "RK4".
This algorithm is named after the research of <NAME> and <NAME>, originally created in the period of 1895 - 1901.
Afterwards <NAME> made further improvements to the algorithm @dreyer_2017[p. 112].
Looking back in @euler_v_taylor, the question of using more than just the first two terms of the Taylor series arose.
The expectation is that using more terms would result in better accuracy, as it would result in better approximations.
But this is at a cost of the calculation of second, third and higher derivatives of $y(x)$ at each step.
Calculations of these derivatives can cost a lot of time and work to calculate @dreyer_2017[p. 112].
This is where Runge-Kutta algorithm is useful.
The algorithm produces the same accuracy as when using the first three terms of @euler_taylor, but without necessity of second derivative calculation.
Let there be an initial value problem as specified in @cauchy.
$
(d y) / (d t) = f(t, y),#h(2em) y(t_0) = y_0
$
The algorithm works in steps similarly the Euler method in @euler_sec.
#let ni = $n+1$
$
&t_ni = t_n + h,\
&y_ni = y^*_n + 1/6 (k_1 + 2k_2 + 2k_3 + k_4)
$
where
$
&k_1 = h f(t_n , y^*_n ),\
&k_2 = h f(t_n + h/2, y^*_n + k_1/2 ),\
&k_3 = h f(t_n + h/2, y^*_n + k_2/2 ),\
&k_4 = h f(t_n + h , y^*_n + k_3 )
$
The Runge-Kutta algorithm is called a _fourth order algorithm_ as the function $f$ needs to be calculated four times, once for each of the $k_n$ values.
Each step of the function calculates approximations for each of the increments of $k_1, ..., k_4$, and then take the mean of those values as the approximation for the next step @dreyer_2017[p. 115].
The algorithm works by calculating each of the increments of $k$.
The first $k_1$ increment calculates the approximation the same as the Euler method talked about in @euler_sec.
Second increment $k_2$ then uses the same method as $k_1$, but this time calculates it at the half-point of the step, at a point where the linear function of $k_1 dot t + y_0$ value would approximate to.
The third increment $k_3$ does the same as the second increment, but uses the linear function with a gradient of $k_2$ to calculate the point.
Finally fourth increment then uses the value of the linear function with a gradient of $k_3$ to calculate the approximate value at the end of the step.
The algorithm then takes the mean of all four increments, but using values of $k_2$ and $k_3$ twice, to calculate the approximate value at the end of the step.
#import "/src/figures/mod.typ": rk4_plot
#figure(
caption: [Visualization of RK4 algorithm, calculating the next step approximation],
rk4_plot
)<rk4>
Graphical representation of the algorithm can be seen in @rk4.
Red points represent each of the increments and their values as a vector, while the green point is the step value approximation.
Blue line represents the $y$ function; the solution to the problem.
#import "/src/figures/mod.typ": compare_e_v_rk,compare_e_v_rk_table
#let number_of_steps = 10
#figure(
caption: [Comparison of Runge-Kutta and Euler method in preportion to a known solution],
compare_e_v_rk(number_of_steps)
)<compare>
The power of the Runge-Kutta method comes is its improved accuracy over the Euler method.
@compare shows that for big steps, Runge-Kutta algorithm gives better function approximations in comparison to using the Euler method.
@error_table shows that for step size of 2, Runge-Kutta algorithm keeps up with the function managing to stay under 20% error @error_foot rate, while the Euler method starts to fall of at the second step with almost 40% error
#footnote[error rate was calculated by $"error" = x_o/ x_t - 1$, where $x_o$ is the observed value, and $x_t$ is the true value.]<error_foot>.
In practice the Runge-Kutta algorithm is used if only a few points are needed, that need high accuracy. This can happen in cases where a few $y$-values are needed to start the process in more sophisticated algorithms @dreyer_2017[p. 116].
#figure(
caption: [Table of Runge-Kutta approximation in comparison to Euler approximations and their errors relative to the solution to the problem $(d y)/(d x) = y - x$],
compare_e_v_rk_table(number_of_steps)
)<error_table>
== Nelder-Mead method
The Nelder-Mead method also known as simplex search algorithm is an algorithm originally published in 1965 by Nelder and Mead.
It is one of the best known algorithms for multidimensional unconstrained optimization without derivatives @singer_2009.
The basic algorithm is popular in many fields of science, for his simplicity and ease of use.
In the 1970s the algorithm was being included in many major software libraries, and by the 1980s its popularity branded it under many names such as the "amoeba algorithm" @press_1992 and MATLAB's "fminsearch" @schreiber_2007.
The popularity of the algorithm prevails till this day, despite the recent advances in direct search method and the age of the algorithm @singer_2009.
The Algorithm was created by modifying the original simplex-based direct search method created by Spendley @spendley_1962.
The original algorithm used two types of transformations to form a new simplex in each step.
In both of the transformations, the angles between edges in every simplex remained _constant_ throughout iteration, meaning the working simplex changed in size but _not_ shape.
The Nelder-Mead algorithm included two additional transformations - expansion and contraction, which allowed the simplex to additionally change its _shape_ @singer_2009.
=== Workings of the algorithm
#let points = $x_0, ...x_n in RR^n$
The method described in @nelder_1965 is a _simplex-based_ search method.
This means that the algorithm uses a simplex $S$ defined in $RR^n$ as the convex hull of $n + 1$ vertices #points (Examples seen in @simplex).
It is important that the initial working simplex S is _nondegenerate_, meaning that the the points #points must not lie on the same hyperplane @singer_2009.
#import "/src/figures/mod.typ": simplex_table
#figure(
caption: [Examples of convex hull in different real n-dimensional spaces],
simplex_table
)<simplex>
Given a nonlinear function $f : RR^n arrow RR$ and a simplex $$ the method calculates $f$ values at some points of $RR^n$
We define
- $p_i$ as a point in $RR^n$ of a given simplex $S$
- $y_i$ as the function value at $f(p_i)$
- $h$ as the suffix such that $y_h = max(y_i)$
- $l$ as the suffix such that $y_l = min(y_i)$
- $overline(p)$ is the centroid of the points with $i eq.not h$
- $[p_i p_j]$ as the distance from $p_i$ to $p_j$
At each stage in the process $p_h$ is replaced by a new point.
This is achieved by using one of the three operations;
_reflection_, _contraction_ and _expansion_.
Reflection of $p_h$ is denoted by $p^*$, and its coordinates are defined by the relation
$
p^* = (1 + alpha)overline(p) - alpha p_h
$
where $alpha$ is a positive constant, named the _reflection coefficient_ @nelder_1965.
Similarly we define _expansion_ of $p^*$ as
$
p^(**) = gamma p^* + (1 - gamma )overline(p)
$
where $gamma$ becomes the _expansion coefficient_.
If $gamma$ is replaced by $beta$ then _expansion_ becomes _contraction_ and $beta$ becomes the _contraction coefficient_, where its value lies between 0 and 1.
The Nelder-Mead method uses these operations in its algorithm following the graph in @nedelmead-alg.
#import "/src/figures/mod.typ": nedel_graph
#figure(
caption: [visualization of the algorithm as described in @nelder_1965[Fig. 1]],
scale(nedel_graph,x: 80%, y: 80%)
)<nedelmead-alg> |
|
https://github.com/MaxAtoms/T-705-ASDS | https://raw.githubusercontent.com/MaxAtoms/T-705-ASDS/main/content/week7.typ | typst | #import "../template.typ": example, exercise
#import "../boxes.typ": definition
#import "../tags.typ": week, barron
=== Method of Maximum Likelihood
#week("7") #barron("9.1.2")
Assume we have observed a sample $(X_1, X_2, dots, X_n)$.
Find parameters of the distribution that maximize the probability that this sample occurs.
#definition[
A maximum likelihood estimator is the parameter that maximizes the likelihood of the observed sample.
*Discrete Random Variables:* Maximize the joint pmf of $P(X_1,dots,X_n)$.
*Continous Random Variables:* Maximize the joint density $f(X_1,dots,X_n)$.
]
==== Discrete random variables
We have a sample $(X_1,dots,X_n)$ then the joint pmf is:
$
P(accent(X, arrow) = (X_1,dots,X_n)) = P(accent(X, arrow)) = P(X_1,dots,X_n) = P(X_1) dot.op dots dot.op P(X_n)
$
Because $accent(X, arrow)$ is a simple random sample the $X_i$ are independent.
Find critical values by taking the derivative w.r.t. all parameters of the distribution and equating them to $0$.
First we take the log of the joint pmf (Because log is a non-decreasing function):
$
ln(P(accent(X, arrow)))
&= ln(P(X_1) dot.op dots dot.op P(X_n)) \
&= ln P(X_1)+dots+ln P(X_n) \
&= sum_(i=1)^n ln P(X_i)
$
#example[
Poission Distribution
The possion distribution has pmf $P(x) = e^(-lambda) (lambda^x/x!)$.
We want to estimate $lambda$.
The logarithm of the pmf is
$
ln P(x) &= ln(e^(-lambda) (lambda^x/x!)) \
&= -lambda + x ln(lambda) - ln(x!)
$
So we have to maximize:
$
ln P(accent(X, arrow))
&= sum_(i=1)^n ln P(x) \
&= sum_(i=1)^n (-lambda + X_i ln(lambda) - lambda(x!)) \
&= -n lambda + ln lambda sum_(i=1)^n X_i + C
$
Next we find the derivative with respect to $lambda$:
$
diff/(diff lambda) ln(P(accent(X, arrow)))
&= diff/(diff lambda) (-n lambda + ln(lambda) sum_(i=1)^n X_i + C) \
&= -n + 1/lambda sum_(i=1)^n X_i + 0 = 0
$
Solve for $lambda$:
$
-n + 1/lambda sum_(i=1)^n x_i = 0 <=> 1/lambda sum_(i=1)^n x_i = n
<=> lambda = 1/n (sum_(i=1)^n x_i) = accent(X, macron)
$
The Maximum Likelihood estimator of $lambda$ is $accent(lambda,hat) = accent(X, macron)$.
]
==== Continous random variables
ML method maximizes the probability of $X=x$.
We know that for continous distributions
$ P(x-h < X < x+h) = integral_(x-h)^(x+h) f(y) dif y approx 2h dot.op f(x) $
Probability of observing a value close to $x$ is proportional to $f(x)$.
We can use #underline("the same method").
#example[
Exponential Distribution
The exponential distribution has pdf $f(x) = lambda e^(-lambda x)$.
We want to find the ML estimator of $lambda$.
First we find the log-likelihood:
$ ln f(accent(X, arrow)) &= sum_(i=1)^n ln (lambda e^(-lambda x_i)) \
&= sum_(i=1)^n (ln lambda - lambda x_i) \
&= n ln lambda - lambda sum_(i=1)^n x_i $
]
Find the derivative w.r.t. $lambda$.
$
dif / (dif lambda) ln f(accent(X, arrow)) = dif / (dif lambda) n ln lambda - lambda sum_(i=1)^n X_i = n / lambda - sum_(i=1)^n X_i
$
Solve:
$
0 = n/lambda - sum_(i=1)^n X_i <=> lambda = n / (sum_(i=1)^n) = 1/accent(X, macron)
$
#exercise("9.2")[
Estimate $p$ in Geometrical distribution given a sample of 3,7,5,3,2.
a) MoM: One parameter $p$ so we only need one moment.
The first population moment:
$mu_1 = E(X) = 1/p$
The first sample moment:
$m_1 = accent(X, macron)$
We need to solve:
$ mu_1 = m_1 <=> 1/p = accent(X, macron) <=> accent(p, hat) = 1/accent(X, macron) = 1/4 $
b) ML:
The pmf is $P(X) = p (1-p)^(X-1)$.
The log-likelihood function is:
$
ln P(accent(X, arrow)) &= ln (product_(i=1)^n p(1-p)^(x-1)) \
&= sum_(i=1)^n ln (p (1-p)^(x-1)) \
&= sum_(i=1)^n ln(p) + (x-1) ln (1-p) \
&= n ln(p) + ln(1-p) sum_(i=1)^n (x_i - 1)
$
Find derivative w.r.t. $p$ (note that $dif / (dif x) ln(x) = 1/x$:
$
0 &= d / (d p) n ln(p) + ln(1-p) sum_(i=1)^n x_i - 1 \
&= n / p - (sum_(i=1)^n (x_i - 1)) / (1 - p)
$
Solve for p:
$
0 &= n / p - (sum (x_i - 1)) / (1 - p) \
&<=> n (1 - p) = p (sum (X_i - 1)) \
&<=> p = 1/accent(X, macron), accent(p, hat) = 1/accent(X, macron) = 1/4
$
]
#exercise("9.5 a)")[
Find MoM of $theta$:
$1/2 (1/theta e^(-x / theta) + 1/10 e^(-x/10))$, $0 < x < oo$
$
mu_1 &= E(accent(X, macron)) = integral_theta^oo x f(x) dif x
&= integral_theta^oo x/2 (1/theta e^(-x/theta) + 1/10 e^(-x/10)) dif x = dots = theta + 5
$
$
mu_1 = m_1 <=> theta + 5 = accent(X, macron) <=> accent(theta, hat) = accent(X, macron) - 5 = 150/10 - 5 = 10
$
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/container_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test fr box.
Hello #box(width: 1fr, rect(height: 0.7em, width: 100%)) World
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/040%20-%20Zendikar%20Rising/005_Episode%203%3A%20The%20Dangerous%20Climb%2C%20the%20Long%20Fall.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 3: The Dangerous Climb, the Long Fall",
set_name: "Zendikar Rising",
story_date: datetime(day: 16, month: 09, year: 2020),
author: "<NAME>",
doc
)
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/01.jpg", width: 100%), caption: [Sea of Clouds | Art by: Sam Burley], supplement: none, numbering: none)
As Nahiri climbed, she smiled. The Murasa Skyclave loomed above her, growing closer with each step. Soon, all the hurts of this plane would be healed. With the Lithoform Core, she would erase the Roil and make Zendikar as beautiful and tranquil as it was millennia ago.
Like she remembered it.
She noticed the labored breathing of Akiri, Zareth, Orah, and Kaza behind her, but she didn't slow her breakneck pace. Not when she was so close to her goal.
Instead, she stonecrafted more and more stairs, which clicked and slid into place as she took them two at a time.
They climbed above the harabaz trees and soaring cliffs of Sunder Bay, to where air smelled clean and cold. They climbed to where droplets from the ruins' waterfalls met their sweat-soaked clothes and made the footing precarious. They climbed until Nahiri could almost touch the intricate carving on the lowest reaches of the Skyclave.
It was only then that Nahiri needed her companions. Zareth's sharp eyes, Orah's quiet steadfastness, Kaza's quick thinking, and Akiri's masterful line-slinging skills. Because around them, the Skyclave floated in pieces and chunks. Some areas were large enough for waterfalls, trees, and landings. Some were only as wide as Nahiri. Stray hedrons dotted the spaces in between the ruins, glinting in the sunlight.
Nahiri scowled.
She made those hedrons. Centuries ago, when she thought trapping the Eldrazi on Zendikar was the best course of action. Back when Sorin and Ugin were at her side whispering reassurances that they would always be there when she needed them.
Now, the hedrons were scattered and tilted at unnatural angles, and Zendikar carried deep scars of the Eldrazi's wrath.
#emph[It will all be rectified soon] , Nahiri thought, gritting her teeth. She pressed on.
The higher they climbed, the more treacherous the landscape became. Sun glare struck in unexpected moments, the ruins rumbled and moaned under their feet, and the handholds were slick with water and algae. Eventually, not even Nahiri could tell which stones would hold them and which were like temperamental allies, looking solid and trustworthy until you put some pressure on them. More than once, someone in the party lost their footing and Akiri would snag them with her ropes or Nahiri with her lithomancy. It required instant reflexes, and by the time they reached the largest of the ruins, everyone's nerves were frayed.
"Which way now?" Akiri asked, coming up beside Nahiri.
Before them, the Murasa Skyclave was a maze of towering channels of carved limestone, where moss grew in the crevices and slender, dangerous bridges spanned bottomless drops.
It was here that Nahiri understood that this Skyclave was a death trap.
"Let's find out," she said, grinning. The ancient kor set a deadly challenge before her, and Akiri accepted it gladly.
Nahiri removed the key from her pocket. It softly glowed and pulsed in her hand. She held it up to the ancient ruins.
And the ancient ruins responded.
The stones at their feet began to shine and thrum in a syncopated rhythm with the key, and stones around the party lit up. Then the glowing stones stretched out in a single line deep into the ruins. Behind her, Nahiri heard Orah gasp.
"A path," said Akiri, with admiration.
"Yes," replied Nahiri, "but watch your step. This Skyclave is old. And it doesn't like visitors." She saw Zareth give Akiri's shoulder a squeeze, and Akiri put a hand on his. Orah exchanged looks with Kaza.
"Noted," Kaza said, cheerfully.
Nahiri smiled. Proper adventurers.
They followed the lit stone path in silence, their instincts telling them that they were being led by ancient and powerful magic. Zareth, being the quickest and quietest of the party, often scouted ahead. He found traps full of poison and archways waiting to collapse and guided them around such threats safely.
These were only a fraction of the dangers in the timeworn Skyclave.
In the distance, there was always the sound of crumbling stone as hedrons crashed into the spaces around them. In the shadows of columns and crevices, they heard the scratching of unseen claws. But whenever the shadows got too close, Nahiri would make a hedron crackle with blue energy, and the shadows would retreat.
Aside from that one exception, though, Nahiri and her adventuring party passed through unmolested.
#emph[As if the Core ] wants #emph[to be found.]
The thought made Nahiri smile.
The path ended at a massive wall, covered in tiles that formed a dizzying pattern of geometric shapes and lines. At the base of the wall, the glowing stone path flashed once more and then went out. There were no other entrances or routes in sight.
"What now?" Zareth asked, folding his arms.
"Maybe we can blow it up," Kaza suggested, not hiding the hope in her voice.
"No," said Nahiri. With one hand, she clutched the key to her chest. With the other, she placed her palm on the wall. She closed her eyes, feeling the miniscule vibrations under her fingers. In the speech of stone—that beautiful, silent language—she asked, "How do I get past you?"
The wall's answer came in shifting vibrations, leading her down to where the tiles met the floor. She followed the stone's invisible movement to a recessed and tileless spot at the very bottom.
A spot the exact size of the key in her hand.
Nahiri grinned as she slipped the key into the empty slot.
There, it pulsed and brightly glowed, lighting up the tiles in a chain reaction until the entire wall was aglow. Behind her, she heard the adventurers let out a soft gasp.
"Open," Nahiri commanded in ancient kor.
And the entrance did. Folding up from the bottom tile by tile, as if a waterfall in reverse, echoing like rain in the empty ruins.
Moments later, the party found themselves standing before a grand cavern.
"That's it?" Kaza asked, unimpressed. "Anyone could have done that."
"Very few can read the runes," replied Nahiri, "or speak the forgotten language."
"Besides, no one is as insane as us to make this climb," said Akiri. The kor woman was grinning, something Nahiri hadn't seen her do before. She headed into the cavern. "Come on. Let's claim this treasure."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/02.jpg", width: 100%), caption: [Lithoform Engine | Art by: <NAME>], supplement: none, numbering: none)
Akiri had Orah and Kaza stand guard at the back of the cavern, near the exit. She knew they had been extremely lucky so far during this venture. But Akiri was too much of a seasoned climber and adventurer to expect that luck to last.
She'd lost her first traveling party to the Eldrazi years ago. She refused to lose her second one, too.
Be prepared, but quick on her feet. That was all she could do.
Together, she, Zareth, and Nahiri crossed the chamber to the center of the room, to the object that commanded all their attention.
The object that was impossible to ignore.
On a raised dais in front of them was a monolith of dark, polished granite, tapered to a point and split in the middle. Shafts of light streamed in through the ceiling, angling toward the monolith, and hedrons danced around it. Sharp crackles of dark lightning, flashing between the hedrons and the monolith, punctuated the silence of the room.
As they approached, the top of the monolith lifted away, and between the two halves of the granite, shining like a dark beacon, was the Lithoform Core.
If Akiri was honest, the Core didn't seem like much. It was small, something that could fit into her hand, though large enough that she wouldn't be able completely close her fingers around it. It shone like a small star, but it was unadorned, almost plain.
But Akiri learned long ago that sometimes the most powerful artifacts—or people—were the most unassuming.
Akiri stopped a few feet from the dais, tense and ready. She reached for Zareth's hand beside her, taking comfort in its warmth. Nothing about the Skyclave felt stable.
Nahiri kept moving forward.
Closer and closer she walked, until Akiri saw Nahiri's visage reflected in the monolith. Nahiri's expression was one of pure determination.
"This is it," Nahiri breathed. "This will change Zendikar forever."
Beside her, Akiri felt Zareth flinch. All his worries and his fears about the Core conveyed in one involuntary motion.
On an impulse, Akiri moved toward the dais, intending to take the Core, knowing that it was probably trapped. Zareth put a concerned hand on her shoulder, but she gave him a reassuring nod and kept going. She suspected that if she was quick enough, subtle enough, she could avoid setting off whatever deadfall laid in wait.
The Core flashed bright and sharp as she neared, as if in warning. She thought she detected the barest of whispers coming from it, like hushed prayers. Or threats.
#emph[For Zendikar] , she thought, and swallowing her nerves, Akiri reached out.
"Careful." Nahiri's hand clamped over her wrist in an instant. Akiri turned to look at Nahiri. The crackling lightning overhead illuminated her face, and there was a new and dangerous glint in her eye. Something that Akiri hadn't seen before, not even when Nahiri faced down a stomper in Sunder Bay.
Years of line-slinging had taught Akiri when to push forward. And when to hold back.
#emph[Wait. Watch] , she thought, and stepped down to stand beside Zareth again. She found his hand and squeezed it. He squeezed back.
#emph[Better to leave the ancient artifact to the ancient stranger] , she thought. And a small part of her was relieved that it wasn't her on the dais.
With her breath caught in her throat, Akiri watched as Nahiri raised a palm under the Lithoform Core, curled her fingers around it, and slowly pulled it toward her.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/03.jpg", width: 100%), caption: [], supplement: none, numbering: none)
For a moment, there was only silence. Just long enough for Akiri to release her breath. Just long enough for her to hope.
Then, there was a deafening #emph[crack] , and the surrounding chamber was disintegrating, falling, tearing itself apart.
#emph[Good luck's run out] , Akiri thought. She turned and shouted, "Nahiri, we need to leave—#emph[now] !"
Before her, Orah and Kaza were already running. Behind her, she saw Nahiri sprinting down the steps of the dais, shoving the Core into a satchel on her hip. Beside her, Zareth kept pace with Akiri's long strides.
But even as she ran, Akiri could feel the floor trembling under her feet, and she realized that this was not only the Murasa Skyclave's trap at work.
The Roil was shaking the earth and the sky as the Skyclave tore itself apart. Perhaps it was reacting to the magic unleashed. Perhaps it was just bad luck. Akiri didn't know.
Ahead of her, the floor beneath Orah and Kaza shifted and rolled like a wave.
"Look out!" she shouted, but another thunderous #emph[crack] drowned out her warning.
The stone floor shifted and splintered, and Kaza and Orah were hurled back. The ground they stood on tilted to sharper and sharper angles until the wizard and the cleric were scrambling to hang on by their fingers.
Then the floor shuddered. Kaza and Orah cried out, losing their tentative grip. They fell, disappearing from view.
"No!" Akiri shouted. She skidded to the edge, too slow, too late to help.
One agonizing moment later, far below, Kaza appeared, hovering on her magic staff, with Orah clinging to her waist.
Akiri exhaled, relief flooding through her.
"Keep going!" Zareth shouted. But she wasn't sure if he was talking to the separated members of their party or her.
#emph[Both] , she thought, and ran.
Fear twisted Akiri's stomach as she sprinted and the structures around her shattered and gave way to empty sky. Would Kaza and Orah make it out alive? Did she lead her party to their deaths?
No, they were good, talented people. This wouldn't be like her first adventuring party. They would be safe.
She had to believe that.
Now, she had to focus on making sure Zareth and Nahiri reached safety, too.
Because all they could do now was try to get out of the Skyclave alive.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/04.jpg", width: 100%), caption: [Akiri, Fearless Voyager | Art by: <NAME>], supplement: none, numbering: none)
Nahiri ran, fighting to hold together the ruins with her lithomancy just long enough for them to cross the precarious stone bridges. The temptation to planeswalk away to safety flashed through her mind. But no, she was done with abandoning Zendikar in its time of need. The Murasa Skyclave offered her a challenge, and she would rise to meet it.
In her satchel on her side, she thought she sensed the Core whispering, but Nahiri didn't have time to listen.
Because the Skyclave was tearing itself apart without the Core. And the Roil, the damn Roil, was whipping up winds around them and making a dangerous situation a thousand times more chaotic.
She couldn't hold together the Murasa Skyclave and hold back the Roil at the same time.
At least, not yet.
So, she ran behind Akiri and Zareth, anger coiling inside her.
They hit a dead end. Before them, islands of tree-covered ruins floated with nothing between but empty sky and a few hedrons. With a masterful throw, Akiri flung her rope and latched onto a drifting ledge.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/05.jpg", width: 100%), caption: [], supplement: none, numbering: none)
"Quick!" she said, before swinging over to the massive tilted platform below them. Zareth threw another rope, and Nahiri readied hers, but a huge swirling vortex of winds in the distance caught her attention.
Her momentary delay was too long. Before either she or Zareth made the jump, the Skyclave shuddered and shifted again.
Nahiri struggled not to fall as she watched the platform on which Akiri stood sail away from them.
"Hurry," said Zareth, holding out his arm to her. And Nahiri realized they were going to have to swing over together.
Nahiri considered refusing. This trickster, who has no love for her, might let her fall. But despite his tricks, she knew Zareth had enough honor not to murder in cold blood.
Nahiri grabbed the rope beside Zareth, and as he prepared to swing, she whispered in his ear, "I know you want the Core for yourself."
Surprise crossed the merfolk's face, but before he could respond, Nahiri commanded the stone underneath them to give them a push.
For one gravity-defying, heart-pounding moment, all Nahiri saw was sky. Wide and unforgiving.
Then they dropped to the platform. Nahiri rolled to a graceful stop. Zareth's expression melted into pure relief when he saw Akiri. She pulled him to his feet and gave Nahiri a small nod.
They were running again.
The noise was relentless as the gust of stiff wind that tore at their faces and their clothes and the Skyclave crumbled around them. The delicate stone bridges broke and fell, and the hedrons spun out of control, missing them by inches.
This was Zendikar in its most ruined, dangerous, and nightmarish form, and Nahiri #emph[hated] it.
Still, she kept running, kept dodging, kept escaping.
Until the vortex appeared.
It sprang up without warning in a space through the floor of the floating ruin. Like a tornado, it ripped into everything and everyone around it. Seconds before, Zareth had swung down to a landing on the other side of the chasm. Nahiri no longer saw him. Akiri stood, paused with the rope in her hand as the whirlwind of stone and dust whipped to a frenzy around them.
"Go!" Nahiri shouted. With a small nod, Akiri slid down the rope.
Nahiri turned, and with legs braced, arms outstretched, she grimaced and faced the vortex.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/06.jpg", width: 100%), caption: [], supplement: none, numbering: none)
#emph[I will bend you to my will] , she thought. Like she did to the Roil in Akoum, like she did with Sorin and so many other enemies in the past. She stretched out her fingers and let her rage and her guilt pour out of her with her magic.
Piece by piece, the vortex slowed and then stopped, becoming a frozen, harmless thing.
Nahiri smiled, victorious.
But it was a short-lived triumph. The vortex swelled again. Like a dam on the edge of bursting, it contained so much anger and force it pushed Nahiri back, until she could contain it no longer.
And Nahiri went flying off the ruin's ledge.
There was only sky around her, blue and cold. Nahiri twisted midair and saw Akiri's rope inches away. She reached out her hand.
And missed.
She was free falling.
Nahiri's heart seized in her throat as she summoned every shred of power she had left to stop her plunge. Until something caught her arm.
"Got you!" Akiri gasped and grinned. She hoisted Nahiri to the platform with Zareth's help.
Nahiri's cheeks burned with shame. "Let's go," she said, and shifted the floating ruins around them into a bridge. She dashed across it. Behind her, the raging rush of chaos and destruction grew louder, grew closer.
Nahiri bared her teeth. Now she knew for certain she couldn't heal Zendikar with her lithomancy alone.
The Core in her satchel was whispering again, but Nahiri wasn't listening. She was sprinting, and she was planning.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/07.jpg", width: 100%), caption: [Cinderclasm | Art by: <NAME>], supplement: none, numbering: none)
Nahiri landed on a wide stretch of the Murasa Skyclave that was still unbroken, followed closely by Zareth and Akiri. It was the first place they reached that wasn't crumbling or shaking. It took a moment for Nahiri to realize what was wrong.
#emph[Why is there lava here?] she thought, perplexed, studying the area before her. Then realization struck her—the Roil had changed the landscape of the Skyclave, like it had done to so many other areas on this plane. Nissa said that the Roil had begun as a reaction to the Eldrazi, Zendikar's way of fighting the sickness within it. Now, it seemed, it was trying to fight her.
#emph[Is this what it calls a fight? ] Nahiri smirked.
The floor before her exploded in jets of fire and ash. It knocked Nahiri back, and an immense, furious elemental emerged from the ground, as if it was born from the lava itself. Its massive chest and fists radiated heat, crackling fire as its coal-red eyes turned and glared at Nahiri. The look was full of hate.
Nahiri stretched a hand behind her, and a moment later, a glowing stone sword emerged fully formed in her grasp. If this #emph[thing ] wanted a fight, she would give it one. Gladly.
Zareth was quicker, though. With unflagging courage, he charged the elemental, trident in hand. An arc of energy shot out from the weapon and surrounded the creature, striking it full in the chest.
The elemental didn't even flinch. It cast its calm stare upon Zareth, raised both of its fiery fists, and brought them down on the merfolk.
But as quick as lightning, Akiri was there in front of Zareth, arm raised, the gauntlet on her wrist flashing, a bright disc appearing as a shield between her and the monster. The elemental slammed both fists down on the magical shield. Akiri groaned and crumpled. The creature growled in frustration and raised its hands again.
Nahiri saw Akiri and Zareth bracing for another blow and knew they would not survive the next one.
Lifting one hand in an arc while grasping her sword in the other, Nahiri raised the earth and rode it up into the sky. She barely heard the whispering as she pulled the Core from her satchel.
The motion made the elemental pause, look away from the prone figures before it, and stare straight at her. Or rather, at the Core in her hand.
"Is this what you want?" Nahiri shouted.
The elemental growled and stalked toward Nahiri, fists balled, looming closer.
Nahiri raised her sword, but she knew it wouldn't be enough. She alone wouldn't be enough against this abomination created by the Roil. She lowered her sword. Looked at the Lithoform Core in her hand.
#emph[Should I? ] she wondered.
The Core continued its whispers, but she wasn't able to make out the words.
But words were not important. Actions were.
She heard Akiri cry out from a distance, and Nahiri shifted her glance toward the sound. Zareth was running toward the monster. No, she realized, he was racing toward her, trident pulled back, energy dancing between its prongs. His face was set in grim determination.
In the same instant, the elemental growled at Nahiri and lunged.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/08.jpg", width: 100%), caption: [], supplement: none, numbering: none)
That was when Nahiri decided.
She raised the Core and easily, so easily, channeled the power in her hand.
The world cracked with dark energy. Then turned white. Color washed away in the brightness, sound became lost in the roar, and for a moment, there was nothing. Nahiri saw nothing. Heard nothing.
Felt nothing.
Her world was clean.
When the light from the Core dimmed, everything around Nahiri had turned to ashen gray. There was nothing but silence, and the elemental was completely gone.
Nahiri smiled, victorious. She had won.
Akiri's agonized voice broke the silence. "Zareth!"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/09.jpg", width: 100%), caption: [Wasteland | Art by: <NAME>], supplement: none, numbering: none)
Akiri was on her knees, holding the cold, stiff body of the person she loved. She blinked, blinked again, wanting this to be a mistake, a cruel trick. It had to be.
Zareth's hand was curled up into a claw, grasping for something. His mouth was wide in a silent scream. But it was his eyes that would haunt Akiri's dreams for months to come.
Zareth's eyes, which were always bright and full of emotion, had no light in them at all.
"Zareth~" Akiri gasped, holding the body of her friend, her love, close. This couldn't be. It couldn't~
She felt Nahiri's shadow fall over her. She glanced over and saw that the Lithoform Core was on the ground, a few feet away from where Akiri knelt in the ashes.
Nahiri moved to pick it up, but Akiri was faster. Within moments, Akiri was on her feet and stumbling back from the strange, ancient kor woman.
"What is this~#emph[thing] , Nahiri?" she demanded. The Core was warm, glowing softly in her hand, like a clear sky on a perfect line-slinging day.
"No more storms or disasters," Nahiri said, sounding so calm, so reasonable. She moved closer, "No more hellish monsters. This is our chance."
Akiri took in the surrounding devastation, the corpse on the ground. "Our #emph[chance] ?"
Nahiri didn't reply. Just took another step forward. Then another.
Akiri stumbled back, aware that there was a ledge behind her, dropping into empty sky.
"Zareth's chance?" she shouted, pointing to the corpse. "No. This ends here." She couldn't let Nahiri reach her. She couldn't let her get the Core.
Zareth was right about Nahiri. He was right.
Nahiri kept advancing. Fear clamped around Akiri's broken heart, and when the ledge was almost at her heels, she stopped.
"No," said Akiri and held the Core over the edge, ready to drop it, ready to be free of this terrible, deadly prize.
But Nahiri's gaze fixed on something past her. Akiri turned and spotted a hedron rising behind her, just within rope's reach. She'd only have to sling a line~
The hedron sparked and dark energy reached out from it, coursing through her, and Akiri found herself unable to move. She watched, frozen, as Nahiri came closer.
And closer.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/10.jpg", width: 100%), caption: [], supplement: none, numbering: none)
Calmly, Nahiri took the Lithoform Core from her nerveless hand.
Nahiri reached up and touched Akiri's cheek. It was only then that Akiri realized her cheeks were covered in tears.
"I'm sorry, Akiri, I really am," said Nahiri, and she sounded truly regretful. But what Akiri saw in Nahiri's face was only determination and ruthlessness.
She wanted to scream, but her voice was lost. She wanted to reach for her ropes, but her muscles wouldn't respond. Akiri could do nothing as Nahiri planted a hand on her shoulder. And pushed.
Akiri toppled back.
And fell.
The last thing Akiri saw was Nahiri standing, with a cold, calculated look in her eye, and the Core hovering over her outstretched palm.
Then there was only sky. Endless and cruel.
#figure(image("005_Episode 3: The Dangerous Climb, the Long Fall/11.jpg", width: 100%), caption: [], supplement: none, numbering: none)
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/concepts.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/heading.typ": chapter
#import "/template/components.typ": note
#import "/template/lang.typ": arabic
#import "/lib/glossary.typ": tr
#show: web-page-template
#chapter(label: <chapter:font-concepts>)[
// Font Concepts
字体中的术语和概念
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-radial_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#grid(
columns: 2,
square(
size: 50pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl, center: (0%, 0%)),
),
square(
size: 50pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl, center: (0%, 100%)),
),
square(
size: 50pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl, center: (100%, 0%)),
),
square(
size: 50pt,
fill: gradient.radial(..color.map.rainbow, space: color.hsl, center: (100%, 100%)),
),
)
|
https://github.com/alerque/polytype | https://raw.githubusercontent.com/alerque/polytype/master/content/hieroglyphs.md | markdown | +++
title = "Hieroglyphs"
description = "Language of the Pharaohs"
extra.typesetters = [ "sile", "typst" ]
+++
In ancient times pictographs –wielded in the hands of the Pharaohs– ruled the world .
|
|
https://github.com/duskmoon314/typst-fontawesome | https://raw.githubusercontent.com/duskmoon314/typst-fontawesome/main/example.typ | typst | MIT License | #import "lib.typ": *
#set heading(numbering: (..nums) => nums.pos().slice(1).map(str).join("."))
= typst-fontawesome
duskmoon314
https://github.com/duskmoon314/typst-fontawesome
A Typst library for Font Awesome 6.6.0 icons through the desktop fonts.
#outline()
#pagebreak()
== Usage
=== Install the fonts
You can download the fonts from the official website: https://fontawesome.com/download
After downloading the zip file, you can install the fonts depending on your OS.
==== Typst web app
You can simply upload the `otf` files to the web app and use them with this package.
==== Mac
You can double click the `otf` files to install them.
==== Windows
You can right click the `otf` files and select `Install`.
==== Some notes
This library is tested with the otf files of the Font Awesome Free set. TrueType fonts may not work as expected. (Though I am not sure whether Font Awesome provides TrueType fonts, some issue is reported with TrueType fonts.)
=== Import the library
==== Using the typst packages
You can install the library using the typst packages:
`#import "@preview/fontawesome:0.5.0": *`
==== Manually install
Copy all files start with `lib` to your project and import the library:
`#import "lib.typ": *`
There are three files:
- `lib.typ`: The main entrypoint of the library.
- `lib-impl.typ`: The implementation of `fa-icon`.
- `lib-gen.typ`: The generated icons.
I recommend renaming these files to avoid conflicts with other libraries.
=== Use the icons
You can use the `fa-icon` function to create an icon with its name:
```typst #fa-icon("chess-queen")``` #fa-icon("chess-queen")
Or you can use the `fa-` prefix to create an icon with its name:
```typst #fa-chess-queen()``` #fa-chess-queen() (This is equivalent to ```typst fa-icon().with("chess-queen")```)
You can also set `solid` to `true` to use the solid version of the icon:
```typst #fa-icon("chess-queen", solid: true)``` #fa-icon("chess-queen", solid: true)
Some icons only have the solid version in the Free set, so you need to set `solid` to `true` to use them if you are using the Free set.
Otherwise, you may not get the expected glyph.
==== Full list of icons
You can find all icons on the #link("https://fontawesome.com/search")[official website].
==== Different sets
By default, the library supports `Free`, `Brands`, `Pro`, `Duotone` and `Sharp` sets.
(See #ref(<enable_pro_sets>) for enabling Pro sets.)
But only `Free` and `Brands` are tested by me.
That is, three font files are used to test:
- Font Awesome 6 Free (Also named as _Font Awesome 6 Free Regular_)
- Font Awesome 6 Free Solid
- Font Awesome 6 Brands
Due to some limitations of typst 0.12.0, the regular and solid versions are treated as different fonts.
In this library, `solid` is used to switch between the regular and solid versions.
To use other sets or specify one set, you can pass the `font` parameter to the inner `text` function: \
```typst #fa-icon("github", font: "Font Awesome 6 Pro Solid")```
If you have Font Awesome Pro, please help me test the library with the Pro set.
Any feedback is appreciated.
===== Enable Pro sets <enable_pro_sets>
Typst 0.12.0 raise a warning when the font is not found.
To use the Pro set, ```typst #fa-use-pro()``` should be called before any `fa-*` functions.
#block(stroke: 1pt, width: 100%, inset: 1em)[
```typst
#fa-use-pro() // Enable Pro sets
#fa-icon("chess-queen-piece") // Use icons from Pro sets
```
]
==== Customization
The `fa-icon` function passes args to `text`, so you can customize the icon by passing parameters to it:
```typst #fa-icon("chess-queen", fill: blue)``` #fa-icon("chess-queen", fill: blue)
```typst #fa-chess-queen(size: 15pt)``` #fa-chess-queen(size: 15pt)
==== Stacking icons
The `fa-stack` function can be used to create stacked icons:
```typst #fa-stack(fa-icon-args: (solid: true), "square", ("chess-queen", (fill: white, size: 5.5pt)))``` #fa-stack(fa-icon-args: (solid: true), "square", ("chess-queen", (fill: white, size: 5.5pt)))
Declaration is `fa-stack(box-args: (:), grid-args: (:), fa-icon-args: (:), ..icons)`
- The order of the icons is from the bottom to the top.
- `fa-icon-args` is used to set the default args for all icons.
- You can also control the internal `box` and `grid` by passing the `box-args` and `grid-args` to the `fa-stack` function.
- Currently, four types of icons are supported. The first three types leverage the `fa-icon` function, and the last type is just a content you want to put in the stack.
- `str`, e.g., `"square"`
- `array`, e.g., `("chess-queen", (fill: white, size: 5.5pt))`
- `arguments`, e.g. `arguments("chess-queen", solid: true, fill: white)`
- `content`, e.g. `fa-chess-queen(solid: true, fill: white)`
==== Known Issues
- #link("https://github.com/typst/typst/issues/2578")[typst\#2578] #link("https://github.com/duskmoon314/typst-fontawesome/issues/2")[typst-fontawesome\#2]
This is a known issue that the ligatures may not work in headings, list items, grid items, and other elements. You can use the Unicode from the #link("https://fontawesome.com")[official website] to avoid this issue when using Pro sets.
For most icons, Unicode is used implicitly. So I assume we usually don't need to worry about this.
Any help on this issue is appreciated.
== Gallery
Here are all the icons in the library. The first column is the icon function you can use, and the second and third columns are the icon in regular and solid versions. The fourth column is what you get when you use `fa-icon` with the icon name.
Since I only use the Free set, some icons may render as a square in the following table. Please turn to the official website for the correct glyph.
#include "gallery.typ" |
https://github.com/mroberts1/nocturnal-cinema | https://raw.githubusercontent.com/mroberts1/nocturnal-cinema/main/index.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
}
}
// Subfloats
// This is a technique that we adapted from https://github.com/tingerrr/subpar/
#let quartosubfloatcounter = counter("quartosubfloatcounter")
#let quarto_super(
kind: str,
caption: none,
label: none,
supplement: str,
position: none,
subrefnumbering: "1a",
subcapnumbering: "(a)",
body,
) = {
context {
let figcounter = counter(figure.where(kind: kind))
let n-super = figcounter.get().first() + 1
set figure.caption(position: position)
[#figure(
kind: kind,
supplement: supplement,
caption: caption,
{
show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1))
show figure.where(kind: kind): set figure.caption(position: position)
show figure: it => {
let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1)
show figure.caption: it => {
num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug?
[ ]
it.body
}
quartosubfloatcounter.step()
it
counter(figure.where(kind: it.kind)).update(n => n - 1)
}
quartosubfloatcounter.update(0)
body
}
)#label]
}
}
// callout rendering
// this is a figure show rule because callouts are crossreferenceable
#show figure: it => {
if type(it.kind) != "string" {
return it
}
let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none)
if kind_match == none {
return it
}
let kind = kind_match.captures.at(0, default: "other")
kind = upper(kind.first()) + kind.slice(1)
// now we pull apart the callout and reassemble it with the crossref name and counter
// when we cleanup pandoc's emitted code to avoid spaces this will have to change
let old_callout = it.body.children.at(1).body.children.at(1)
let old_title_block = old_callout.body.children.at(0)
let old_title = old_title_block.body.body.children.at(2)
// TODO use custom separator if available
let new_title = if empty(old_title) {
[#kind #it.counter.display()]
} else {
[#kind #it.counter.display(): #old_title]
}
let new_title_block = block_with_new_content(
old_title_block,
block_with_new_content(
old_title_block.body,
old_title_block.body.body.children.at(0) +
old_title_block.body.body.children.at(1) +
new_title))
block_with_new_content(old_callout,
new_title_block +
old_callout.body.children.at(1))
}
// 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead
#let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = {
block(
breakable: false,
fill: background_color,
stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"),
width: 100%,
radius: 2pt,
block(
inset: 1pt,
width: 100%,
below: 0pt,
block(
fill: background_color,
width: 100%,
inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) +
if(body != []){
block(
inset: 1pt,
width: 100%,
block(fill: white, width: 100%, inset: 8pt, body))
}
)
}
#let PrettyPDF(
// The document title.
title: "PrettyPDF",
// Logo in top right corner.
typst-logo: none,
// The document content.
body
) = {
// Set document metadata.
set document(title: title)
// Configure pages.
set page(
margin: (left: 2cm, right: 1.5cm, top: 2cm, bottom: 2cm),
numbering: "1",
number-align: right,
background: place(right + top, rect(
fill: rgb("#E6E6FA"),
height: 100%,
width: 3cm,
))
)
// Set the body font.
set text(10pt, font: "Ubuntu")
// Configure headings.
show heading.where(level: 1): set block(below: 0.8em)
show heading.where(level: 1): underline
show heading.where(level: 2): set block(above: 0.5cm, below: 0.5cm)
// Links should be purple.
show link: set text(rgb("#800080"))
// Configure light purple border.
show figure: it => block({
move(dx: -3%, dy: 1.5%, rect(
fill: rgb("FF7D79"),
inset: 0pt,
move(dx: 3%, dy: -1.5%, it.body)
))
})
// Purple border column
grid(
columns: (1fr, 0.75cm),
column-gutter: 2.5cm,
// Title.
text(font: "Ubuntu", 20pt, weight: 800, upper(title)),
// The logo in the sidebar.
locate(loc => {
set align(right)
// Logo.
style(styles => {
if typst-logo == none {
return
}
let img = image(typst-logo.path, width: 1.5cm)
let img-size = measure(img, styles)
grid(
columns: (img-size.width, 1cm),
column-gutter: 16pt,
rows: img-size.height,
img,
)
})
}),
// The main body text.
{
set par(justify: true)
body
v(1fr)
},
)
}
#show: PrettyPDF.with(
title: "Nocturnal Cinema",
typst-logo: (
path: "\_extensions/nrennie/PrettyPDF/logo.png",
caption: []
),
)
#figure([
#box(image("img/ascenseur.jpg"))
], caption: figure.caption(
position: bottom,
[
#emph[Ascenseur pour l’échafaud] (Louis Malle, 1958)
]),
kind: "quarto-float-fig",
supplement: "Figure",
)
#block[
#link("https://mroberts.emerson.build/")[<NAME>] #link("mailto:<EMAIL>")[] \
#link("https://emerson.edu/academics/academic-departments/visual-media-arts")[Department of Visual & Media Arts] \
#link("https://emerson.edu")[Emerson College] \
#link("https://theurbannight.files.wordpress.com/2022/03/book-of-abstracts.pdf")[Media & The Night Conference] \
McGill University \
18-19 March 2022
]
#horizontalrule
#quote(block: true)[
Le cinéma s’est approprié la nuit pour la réinventer et, depuis, notre perception n’est plus la même. Difficile de contempler Shanghai ou New York sans penser à #emph[Blade Runner];. Plaisirs de noctambules, nuit des truands, des dealers et des paumés, nuit de rêve ou quotidien des travailleurs nocturnes… , par sa magie, le septième art s’est emparé de la nuit pour en faire un personnage à part entière.
]
#block[
Cinema has appropriated night in order to reinvent it, and since then our perception of it has not been the same. It’s hard to look at Shanghai or New York without thinking about #emph[Blade Runner];. The pleasures of nocturnal flâneurs; the night of crooks, dealers, and down-and-outs; the night of dreams or the everyday night of workers… By its magic, the seventh art has taken hold of the night in order to turn it into a character in its own right.
]
#quote(block: true)[
– @gwiazdzinski2016[: 63];.
]
#quote(block: true)[
\[L\]a nuit suggère, elle ne montre pas. La nuit nous trouble et nous surprend par son étrangeté; elle libère des forces en nous qui, le jour, sont dominées par la raison. . . . J’aimais les prodiges de la nuit que la lumière contraignait à se manifester; il n’existe pas une nuit absolue.
]
#block[
The night doesn’t show, it suggests. It disturbs and surprises us by its strangeness; it triggers impulses in us that, during the day, are dominated by reason. . . . I loved the wonders of the night that light forced to manifest themselves; absolute night does not exist.
]
#quote(block: true)[
– Brassaï, feuillet inédit, archives Gilberte Brassaï, no date (Exposition «Brassaï», Centre Georges Pompidou, 2000).
]
#quote(block: true)[
Black and white are, for me, cinema’s most beautiful colours.
– <NAME> @misek2010[: 83];.
]
#horizontalrule
== Avant-Propos / Preamble
<avant-propos-preamble>
I’d like to start with a brief disclaimer about what I am trying to do in this paper, and—just as importantly—what I am #emph[not] trying to do. As many people here will no doubt be already aware, there has existed for some time now a voluminous and highly specialized body of literature on the genre of #emph[film noir];, and on the postwar movement in French film known as the #emph[nouvelle vague] or New Wave. While I have no pretensions to adding to that literature, its existence does not mean that everything there is to say on these subjects has already been said. Maybe I’ve just been watching too many heist movies lately, but what I am interested in doing is to try—under cover of darkness, obviously—to break open the constrictive generic and auteurist #emph[coffres-forts] in which cinema has been locked away for decades by introducing a different paradigm that I call #emph[nocturnal cinema];. While the night has figured prominently in cinema from its earliest origins, by nocturnal cinema I am referring to a more specific corpus of films in which night is not just a temporal backdrop for narrative realism but is foregrounded as an aesthetic, thematic, stylistic, and symbolic element in the films in question. The paradigm of nocturnal cinema, I want to suggest, opens up the possibility of conceptualizing alternative histories of cinema that treat it not as a discrete object of study but position it within a broader cultural spectrum of media and artistic practices. As such, it may serve as a prototype for other new ways of thinking about the history of cinema.
With that said, let us begin, as one must, with Melville.
== Pigalle
<pigalle>
This sequence from #emph[Bob le flambeur] provides a succinct example of a particular kind of cinematic cultural mythology that was already in place when Melville’s film was released in 1956: a set of associations involving criminal activity, music, and the urban night, originating in the cinematic appropriation of popular crime fiction, that in the late 1940s came to be known as #emph[film noir];. The emergence of this mythology in the late-1930s films of <NAME>, and over subsequent decades in the films of <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>, followed by the #emph[nouvelle vague] films of Godard, Truffaut, Chabrol, and others, is the subject both of the present paper and a related project I am currently working on, a cinematic compilation album titled #emph[Ciné-Jazz];.
#block[
]
For reasons of time, I will limit myself here to the work of <NAME>, which has been overshadowed by the better-known examples of Louis Malle’s celebrated collaboration with <NAME> on #emph[Ascenseur pour l’échafaud] (1958), Godard’s #emph[À bout de souffle] (1960), and others. The series of films released by Molinaro in the late 1950s that includes #emph[Le dos au mur] (1958), #emph[Des femmes disparaissent] (1959, and #emph[Un témoin dans la ville] (1959), embody the cinematic chronotope of urban crime, jazz, and the night. Collectively, they provide a case study in a larger genre that I would like to call #emph[nocturnal cinema];. I want to explore here some of the key characteristics of this nocturnal cinema, as manifested in French #emph[film noir] and its legacy in the #emph[nouvelle vague] or New Wave.
== Nuits Monochromes
<nuits-monochromes>
As a quintessentially nocturnal experience of urban modernity, cinema is almost organically related to the night; as <NAME> has observed,
#quote(block: true)[
Du noir de la pellicule à l’obscurité de ses salles, le cinéma entretient un rapport quasi physique avec la nuit. Rien ne semble pouvoir échapper à l’emprise de la nuit. Il est souvent plus difficile d’apprécier un film en journée: même projeté dans une salle obscure, le film perd de son intensité et à la sortie, le mystère et la magie s’estompent trop vite (2016: 62).
]
But if the urban experience of watching movies has historically taken place in nocturnal darkness, the nocturnal city itself has been a subject of predilection for cinema since its inception; consider, for example, the early movies of Edison cameraman <NAME>, of the dazzling lights of the #link("https://youtu.be/Q5m6joTlnqA")[Pan-American exhibition] or #link("https://www.youtube.com/watch?v=NqDtG3dcxPs")[Coney Island] at night. There is a residual sense of wonder, what <NAME> calls the electrical sublime, in the nocturnal cityscapes of Molinaro and other filmmakers of his time, the "magie" of the night alluded to by Gwiadzdinski; but I would argue that by the 1950s this had been displaced by a deep ambivalence about the night as a space both of temptation, of opportunity for financial and erotic gain unavailable in the mundane light of day, but also a space of danger, or more accurately dangerous liaisons that lead to the downfall of those who embrace them.
The urban night is also the privileged chronotope of #emph[film noir];, whether in its American, French, or British incarnations, and that night, with its deserted streets, its neon-drenched demi-monde of bars and cabarets, is the pre-eminent setting for shady goings-on of all kinds, from jewel heists to prostitution to drug deals to the disposal of bodies. But while the night provides the backdrop to such activities in #emph[film noir];, from <NAME>’s #emph[The Woman in the Window] (1944) to <NAME>’s #emph[Night and the City] (1950), it takes on a particularly luminous resonance in the French cinema of the 1950s, from the films of Melville, as we have seen, to Louis Malle’s #emph[Ascenseur pour l’échafaud] (1958), with its famous sequence of Jean Moreau prowling the Parisian streets in search of her missing lover, accompanied by <NAME>’s muted trumpet.
Although less common in #emph[film noir] than is often assumed, jazz soundtracks are a key component of nocturnal cinema, in part because of the music’s own associations with nocturnal entertainment. Not only <NAME>, but many other American jazz musicians performed in Paris in the late 1950s, including <NAME>, Thelonious Monk, and Art Blakey, in addition to musicians already based there such as <NAME>, Franco-American <NAME>, and Algerian-born Martial Solal. Various permutations of these musicians were tapped to write soundtracks for French films: Art Blakey’s Jazz Messengers for Molinaro’s #emph[Des Femmes disparaissent] and <NAME>’s #emph[Les Liaisons dangereuses];; Monk also for #emph[Les Liaisons dangereuses];; <NAME> and <NAME> for #emph[Un témoin dans la ville];; Martial Solal for Godard’s #emph[À bout de souffle];.
#block[
]
It is, however, in the nocturnal cinema of Édouard Molinaro that the aesthetic resonance of the urban night reaches its fullest expression; so tangible does its presence become that one would be hard put to find a better example of Gwiazdzinski’s point that cinema has transformed the night into a character in its own right. While not all the action of #emph[Le dos au mur] and #emph[Un témoin dans la ville] takes place at night, so rare are the glimpses of daylight that one could easily assume that both films take place entirely after dark. In #emph[Des femmes disparaissent];, even those fleeting glimpses of daylight disappear in a film whose setting is exclusively nocturnal.
#emph[Le dos au mur] opens with a staple noir motif: the disposal of a body. Late at night, somewhere on the outskirts of Paris, a man wearing the signature trenchcoat and fedora exits a mansion and drives in to the city and enters a first-floor apartment, where to our surprise the murder has already taken place. Turning off a still-running shaver in the bathroom, the man wraps up the body of the dead man lying on the floor in a large rug and carries it to his car. He then drives to a nearby construction site and laboriously disposes of the body by mixing concrete, hoisting the carpet-wrapped body up onto scaffolding, and entombing it in a large wall that, it later emerges, happens to be adjacent to his office building. The rest of the film is an extended flashback that explains the circumstances that led up to this bizarre opening over the preceding three months.
In #emph[Des femmes disparaissent];, a man stumbles upon a human-trafficking network run by an organization of businessmen that enshares young women with promises of jet-set lifestyles, after his fiancée becomes one of its latest would-be recruits. Captured by one of the organization’s henchmen, he manages to escape with his fiancée only for the couple to be recaptured after being betrayed by one of the organization’s accomplices. The film culminates in an extended shootout at the organization’s country mansion, the liberation of the abducted women, and our hero delivering a richly-earned beating to the organization’s leader.
#emph[Un témoin dans la ville] starts out with not one but two staged suicides: a man who murders his mistress by pushing her off a train escapes prosecution by claiming she committed suicide, only to become himself the victim of a staged suicide when he is murdered one night soon afterwards by the woman’s ex-husband, Ancelin. As Ancelin slips out of the first’s house, however, he runs into a driver for a fleet of radio taxis waiting outside, whom the man he has just murdered had ordered earlier. The rest of the film depicts Ancelin’s constantly frustrated efforts to eliminate the witness, and ultimately his own pursuit by the fleet of taxi drivers and the police. The pursuit culminates at the Jardin d’Acclimatation in the Bois de Boulogne and includes eerie cutaways of startled birds and animals.
The three films share many of the signature elements of #emph[film noir];: perfect crime gone wrong; trench-coated, fedora-wearing male protagonists; alluring female protagonists; expressionistic lighting with unmotivated shadows; deep focus; and in two of the films, a jazz soundtrack. All three films make extensive use of musical cues to underscore their nocturnal sequences: #emph[Le dos au mur] opens with Richard Cornu’s conventionally melodramatic orchestral score, although the rest of the sequence unfolds in a tense silence. In #emph[Un témoin dans la ville];, after the initial trauma of the train sequence, the relaxed down-tempo of <NAME>’s saxophone suggests a return to some semblance of normality as the murderer arrives at the public prosecutor’s office to confirm the dismissal of his case as a #emph[non-lieu];. By contrast, <NAME>’s heartbeat-like drum figure at the opening of #emph[Des femmes disparaisent] creates a sense of ominous suspense from the outset.
But it is their characterization of the urban night that accounts for much of the films’ aesthetic appeal. In each, the night is a space not of total darkness but partial illumination, lit by the myriad light sources of the nocturnal city: the glow of street lights and the neon signs of bars, cafes, and advertisements; floodlit buildings and monuments; the dazzling displays of movie theater marquees; the mesmerizing patterns of automobile headlamps; even (in #emph[Le dos au mur];) portable flashlights. The term #emph[incandescent] refers to the emission of light by an object as a result of being heated, derived from the Latin verb #emph[incandescere];, to glow white. From this standpoint, Molinaro’s film can be described not just as a nocturnal but an incandescent cinema, its darkness illuminated by lights that burn with white-hot intensity.
#block[
]
This aesthetics of incandescence is not unique to Molinaro’s films, and is in fact one of the historical particularities of the city of Paris itself. Popularly known as the City of Light, or #emph[ville lumière];, since the late seventeenth century, Paris was one of the first European cities to install a system of street lighting, but not for aesthetic or commercial purposes. As is well known, the measure was made at the instigation of the police in response to a rising nocturnal crime wave:
#quote(block: true)[
<NAME>, alors nommé tout premier lieutenant général de police de Paris, en mars 1667, décida d’enrayer la criminalité grandissante dans la ville en mettant en place un éclairage public dans les rues, ruelles et impasses afin de dissuader les rôdeurs et criminels d’agir en tout impunité. Les premières lanternes d’éclairage public sont ainsi installées dans la ville de Paris et quelques mois après l’ordonnance, 2,736 lanternes à mèche charbonnée sont posées et 912 rues éclairées dans Paris (#link("https://breves-histoire.fr/thematique/ville-lumiere/")["Ville-lumière: vestiges insolites"];, #emph[Brèves d’Histoire];, no date).
]
Two and a half centuries later, a young Transylvanian journalist named <NAME> who had moved to Paris in 1924 became entranced by the nocturnal incandescence of the #emph[ville lumière] and its nightlife, and began documenting them in photography and writing. The collection of sixty black-and-white photographs of the city assembled in his 1932 book #emph[Paris de nuit] (1932), under the pseudonym of Brassaï (derived from the town of his birth, Brassó, in what was then Hungary), have since become an inseparable part of the city’s visual iconography, available from the postcard stands of countless newspaper kiosks and museum gift shops. The impact of Brassaï’s luminous images of nocturnal Paris on the stylization of the night in French #emph[film noir] several decades later is readily apparent, nowhere more so than in the films of Édouard Molinaro. Their most obvious element in common is their monochromatic nature, at a time when black and white cinematography was coded either as a signifier of neorealism or a stylistic element of #emph[film noir] and horror movies, in opposition to the garish Technicolor of Hollywood musicals. While in Brassaï’s photography the interplay of shadows and light serve a primarily aesthetic purpose, however, in Molinaro’s films it takes on a more specifically symbolic dimension, as a metaphor for the equally high-contrast moral world that the characters inhabit. #emph["Quelle nuit!"];, the characters repeatedly exclaim in #emph[Le dos au mur];, referring not just to the fact that it’s dark out but to the disturbing events taking place within it. In this world, light represents the ontological security of the social order and its institutions, literally shining the light on criminal activity and driving back the forces of darkness.
In the climactic sequence of #emph[Un témoin dans la ville];, the criminal is pursued into the Jardin d’Acclimatation by a a driver, by whom he is shot but then manages to overpower. Climbing over a gate, he appears to have eluded his pursuers yet again, only to be suddenly dazzled by the headlights of a fleet of encircling police cars. Finally exposed, he collapses under a hail of police bullets, and the film’s closing long shot shows his prone body spotlighted by the vehicles’ headlights as the police close in. No longer concealed by nocturnal shadows, the criminal has finally been brought into the light of justice. FIN.
#block[
]
While the monochromatic nocturnal cityscapes of Molinaro’s films are indebted to Brassaï’s mythologization of nocturnal Paris, however, they also add two crucial cinematic elements to it: motion and music. Other than murder, double-crossing, and abduction, one of the most prominent activities in Molinaro’s nocturnal films is driving: more specifically, night driving. Molinaro’s characters spend considerable time driving back and forth around the city, frequently in pursuit of one another. Collisions are common: cars are as much weapons as revolvers, and can be used to take down fleeing witnesses, or simply crashed into the vehicles of escaping criminals. The entire narrative of #emph[Un témoin dans la ville] revolves around a fleet of radio taxis, a historical novelty in the late 1950s that motivates the film’s extended car-chase sequences when the entire fleet is mobilized in pursuit of the murderer of the taxi driver. These taxis and other cars all carry unseen cameras, of course, and as such they become vehicles for the films’ extended tracking shots of the illuminated cityscape, of which they themselves are an integral part. Close-ups of headlights being switched on before cars speed away are ubiquitous; driver POV and rear-window shots show drifting bokeh patterns of blurred light, heightened during chase sequences.
The centrality of the automobile as a vehicle for exploring the night is far from limited to Molinaro’s films, of course; even in scenes of noctambulation, such as <NAME>’s celebrated #emph[ballade] in #emph[Ascenseur pour l’échafaud];, she spends most of her time staring at cars in the hope of spotting her missing lover.
The jazz soundtracks of Molinaro’s films can be seen as homologous (in Paul Willis’s sense) with their visual elements. For all its experimentation with chromatic scales, in its visual representations jazz has always been a monochromatic music: the entire iconography of bebop prior to the 1970s consists of black-and-white photographs of Bird, Billie Holiday, Monk, Miles, Coltrane, and many more; the titles of jazz tunes are littered with references to shadows and light; while the black/white opposition even extends to the dynamics of race in the history of the music itself, in the systemic harassment of and often violence against black musicians by white law enforcement; and on the other hand the embrace of Harlem jazz by <NAME>’s hipster "white negro".
The nocturnal cityscape takes on a very different look in the extended chase sequence from Louis Malle’s comedy #emph[Zazie dans le métro] (1961), which as one critic has noted is a far cry from the dark mood and themes of #emph[Ascenseur pour l’échafaud] two years earlier. By now the #emph[film noir] car chase sequence has already become an object of parody, and in contrast to the monochrome of Malle’s earlier film, his use of Kodak’s Eastmancolor stock for #emph[Zazie] looks suddenly garish and enhances its cartoonlike look. Much the same can be said of <NAME>’s hectic jazz score. Yet even in the mode of pastiche, the sequence again provides an animated portrait of #emph[Paris nocturne];.
#block[
]
== Night Driving
<night-driving>
Over the decade from the mid-1950s to the mid-1960s, the stylistic elements of a nocturnal cinema gradually come into view in French #emph[film noir] and the #emph[nouvelle vague] like a developing Brassaï photograph. By the time we get to #emph[Le départ] (1967), the photograph is complete. Directed by Polish auteur <NAME> and shot in Brussels rather than Paris in this case, the film stars #emph[nouvelle vague] icon <NAME> as a car-obsessed hairdresser and a score by Polish jazz musician <NAME>. As early as the opening credits, the picture is in place: the black-and-white cinematography, even in 1967; the jazz; and the car, shot from the rear of a preceding vehicle and transformed from a mundane taxi into a flashy white Porsche, plunging towards us through the incandescent swirl of streetlights. From Melville to Skolimowski, then, the cinematic romance of the nocturnal city as a space of temptation and danger.
#block[
]
== Nocturnal Panoramas
<nocturnal-panoramas>
In the tradition of Baudelaire and <NAME>’s archetypal painter of modern life, the #emph[flâneur];, numerous books have been written about the experience of exploring the city after dark by walking around it. From Surrealist #emph[flâneurs] to Situationist psychogeographers and their post-millennial descendants, there remains a pedestrian insistence (in every sense of the term) that the city is most profoundly experienced #emph[on foot];. The psychogeographic literature on the urban night reproduces this ideology in its romanticization of #emph[noctambulation];, or wandering the city at night. Cinema, for its part, is densely populated both by diurnal and nocturnal #emph[flâneurs/-euses];, from <NAME> in #emph[Ascenseur à l’échafaud] and Antonioni’s #emph[La Notte] to David Hemmings in #emph[Blow Up];. Yet the nocturnal cinema of <NAME> shows that the cinematic experience of the urban night has taken place as much from behind the wheel as on sidewalks, and typically involves more goal-oriented activities than psychogeographic research. I have come across only one psychogeographic film that involves driving rather than walking, <NAME> and <NAME>’s Ballardian homage to the M25 motorway, #emph[London Orbital] (2002), but a growing number of recent films involve exploring the city by night from a moving vehicle (<NAME>’s science-fiction film #emph[Under the Skin] (2012) comes to mind). In the postmodern megacities of the twenty-first century, it is more often from the freeway, as passengers or drivers, that we experience, and marvel at, the nocturnal panoramas of Los Angeles, Tokyo, Montréal, and the Ville Lumière itself. While the automobile arguably offers a more practical way of navigating such extended urban spaces, however, it also does more than this: viewing the panoramic nocturnal cityscape scrolling past through the frame of a car windshield or window transforms it into a cinematic experience; it feels like watching a movie. Films such as the aptly-titled #emph[Drive] (2011) explicitly play on this cinematic dimension of night driving, but it is equally ubiquitous in contemporary videogames and music videos. Collectively, they attest to the continuing ambivalence about the nocturnal city as a space of libidinal excess and dangerous liaisons.
#horizontalrule
#bibliography("https:\/\/api.citedrive.com/bib/aa54ee25-d1a4-4838-8eb0-848e54d75b38/references.bib?x=<KEY>")
|
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/分治/逆序对.typ | typst | #import "../../../../lib.typ":*
=== #Title(
title: [逆序对],
reflink: "https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/description/",
level: 2,
)<逆序对>
#note(
title: [
交易逆序对的总数
],
description: [
在股票交易中,如果前一天的股价高于后一天的股价,则可以认为存在一个「交易逆序对」。请设计一个程序,输入一段时间内的股票交易记录 record,返回其中存在的「交易逆序对」总数。
],
examples: ([
输入:record = [9, 7, 5, 4, 6]
输出:8
解释:交易中的逆序对为 (9, 7), (9, 5), (9, 4), (9, 6), (7, 5), (7, 4), (7, 6), (5, 4)。
],
),
tips: [
$0 <= "record.length" <= 50000$
],
solutions: (
( name:[分治],
text:[
「归并排序」与「逆序对」是息息相关的。归并排序体现了 “分而治之” 的算法思想,具体为:
- 分: 不断将数组从中点位置划分开(即二分法),将整个数组的排序问题转化为子数组的排序问题;
- 治: 划分到子数组长度为 1 时,开始向上合并,不断将 较短排序数组 合并为 较长排序数组,直至合并至原数组时完成排序;
合并阶段 本质上是 合并两个排序数组 的过程,而每当遇到 左子数组当前元素 > 右子数组当前元素 时,意味着 「左子数组当前元素 至 末尾元素」 与 「右子数组当前元素」 构成了若干 「逆序对」 。
因此,考虑在归并排序的合并阶段统计「逆序对」数量,完成归并排序时,也随之完成所有逆序对的统计。
`merge_sort() `归并排序与逆序对统计:
1. 终止条件: 当 $l!=r$ 时,代表子数组长度为 1 ,此时终止划分;
2. 递归划分: 计算数组中点 m ,递归划分左子数组 merge_sort(l, m) 和右子数组 merge_sort(m + 1, r) ;
3. 合并与逆序对统计:
1. 暂存数组 record 闭区间 $[l,r]$ 内的元素至辅助数组 tmp ;
2. 循环合并: 设置双指针 i , j 分别指向左 / 右子数组的首元素;
- 当 i = m + 1 时: 代表左子数组已合并完,因此添加右子数组当前元素 `tmp[j]` ,并执行j = j + 1 ;
- 否则,当 j=r+1 时: 代表右子数组已合并完,因此添加左子数组当前元素 `tmp[i]` ,并执行 i=i+1 ;
- 否则,当 $"tmp"[i] != "tmp"[j]$ 时: 添加左子数组当前元素 `tmp[i]` ,并执行 i=i+1;
- 否则(即 $"tmp"[i] > "tmp"[j]$)时: 添加右子数组当前元素 `tmp[j]` ,并执行 j=j+1 ;此时构成 m−i+1 个「逆序对」,统计添加至 res ;
4. 返回值: 返回直至目前的逆序对总数 res ;
`reversePairs() `主函数:
1. 初始化: 辅助数组 tmp ,用于合并阶段暂存元素;
2. 返回值: 执行归并排序 merge_sort() ,并返回逆序对总数即可;
为简化代码,可将“当 j=r+1 时”与“当 $"tmp"[i] != "tmp"[j]$时”两判断项合并。
],code:[
```cpp
class Solution {
public:
int reversePairs(vector<int>& record) {
vector<int> tmp(record.size());
return mergeSort(0, record.size() - 1, record, tmp);
}
private:
int mergeSort(int l, int r, vector<int>& record, vector<int>& tmp) {
// 终止条件
if (l >= r) return 0;
// 递归划分
int m = (l + r) / 2;
int res = mergeSort(l, m, record, tmp) + mergeSort(m + 1, r, record, tmp);
// 合并阶段
int i = l, j = m + 1;
for (int k = l; k <= r; k++)
tmp[k] = record[k];
for (int k = l; k <= r; k++) {
if (i == m + 1)
record[k] = tmp[j++];
else if (j == r + 1 || tmp[i] <= tmp[j])
record[k] = tmp[i++];
else {
record[k] = tmp[j++];
res += m - i + 1; // 统计逆序对
}
}
return res;
}
};
```
]),
),
gain:none,
) |
|
https://github.com/3w36zj6/typst-template | https://raw.githubusercontent.com/3w36zj6/typst-template/main/docs/example-article/main.typ | typst | #import "../../templates/article.typ": article
#show: article.with(
title: "タイトル",
subtitle: "サブタイトル",
author: "著者",
date: datetime(year: 2020, month: 10, day: 4).display("[year]/[month]/[day]"),
paginate: true,
bib: bibliography("references.bib", title: "参考文献", style: "ieee"),
)
= Writing in Typst
このレポートでは、氷河の_流体力学_に影響を与えるさまざまな要素と、これらが自然構造物の形成と振る舞いにどのように寄与するかを探求します。
+ 気候
- 温度
- 降水量
+ 地形
+ 地質学
== Adding a figure
=== Image
@glaciers で示されるような氷河は、私たちがすぐに対策を講じないと、近い将来には存在しなくなる可能性があります。
#figure(image("glacier.png", width: 70%), caption: "氷河の様子")<glaciers>
=== Table
@critical-temperatures に示されるように、さまざまな物質は異なる臨界温度を持ちます。
#figure(
table(
columns: 3,
table.header([Substance], [Subcritical °C], [Supercritical °C]),
[Hydrochloric Acid],
[12.0],
[92.1],
[Sodium Myreth Sulfate],
[16.6],
[104],
[Potassium Hydroxide],
table.cell(colspan: 2)[24.7],
),
caption: "さまざまな物質の臨界温度",
) <critical-temperatures>
=== Code
@fibonacci-code は、Fibonacci数列の最初の8項を計算するためのコードを示しています。
#figure(
[
```typst
#set page(width: 10cm, height: auto)
#set heading(numbering: "1.")
= Fibonacci sequence
The Fibonacci sequence is defined through the recurrence relation $F_n = F_(n-1) + F_(n-2)$.
It can also be expressed in _closed form:_
$ F_n = round(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2 $
#let count = 8
#let nums = range(1, count + 1)
#let fib(n) = (if n <= 2 { 1 } else { fib(n - 1) + fib(n - 2) })
The first #count numbers of the sequence are:
#align(
center,
table(columns: count, ..nums.map(n => $F_#n$), ..nums.map(n => str(fib(n)))),
)
```
],
caption: "Fibonacci数列を計算するコード",
) <fibonacci-code>
== Adding a bibliography
氷河の融解は、@glacier-melt に示されたモデルに従っています。
== Adding a formula
方程式 $Q = rho A v + C$ は氷河の流速を定義します。
氷河の流れによって移動した土壌の総量は @total-displaced-soil のように計算されます。
$
7.32 beta +
sum_(i=0)^nabla
(Q_i (a_i - epsilon)) / 2
$ <total-displaced-soil>
== Adding a footnote
詳細はドキュメンテーションをご覧ください。
#footnote[https://typst.app/docs]
#pagebreak()
= 吾輩は猫である
吾輩は猫である。名前はまだ無い。どこで生れたかとんと見当がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。吾輩はここで始めて人間というものを見た。しかもあとで聞くとそれは書生という人間中で一番獰悪な種族であったそうだ。この書生というのは時々我々を捕えて煮て食うという話である。しかしその当時は何という考もなかったから別段恐しいとも思わなかった。ただ彼の掌に載せられてスーと持ち上げられた時何だかフワフワした感じがあったばかりである。掌の上で少し落ちついて書生の顔を見たのがいわゆる人間というものの見始であろう。この時妙なものだと思った感じが今でも残っている。第一毛をもって装飾されべきはずの顔がつるつるしてまるで薬缶だ。その後猫にもだいぶ逢ったがこんな片輪には一度も出会わした事がない。のみならず顔の真中があまりに突起している。そうしてその穴の中から時々ぷうぷうと煙を吹く。どうも咽せぽくて実に弱った。これが人間の飲む煙草というものである事はようやくこの頃知った。この書生の掌の裏でしばらくはよい心持に坐っておったが、しばらくすると非常な速力で運転し始めた。書生が動くのか自分だけが動くのか分らないが無暗に眼が廻る。胸が悪くなる。到底助からないと思っていると、どさりと音がして眼から火が出た。それまでは記憶しているがあとは何の事やらいくら考え出そうとしても分らない。ふと気が付いて見ると書生はいない。たくさんおった兄弟が一疋も見えぬ。肝心の母親さえ姿を隠してしまった。その上今までの所とは違って無暗に明るい。眼を明いていられぬくらいだ。はてな何でも容子がおかしいと、のそのそ這い出して見ると非常に痛い。吾輩は藁の上から急に笹原の中へ棄てられたのである。ようやくの思いで笹原を這い出すと向うに大きな池がある。吾輩は池の前に坐ってどうしたらよかろうと考えて見た。別にこれという分別も出ない。しばらくして泣いたら書生がまた迎に来てくれるかと考え付いた。ニャー、ニャーと試みにやって見たが誰も来ない。そのうち池の上をさらさらと風が渡って日が暮れかかる。腹が非常に減って来た。泣きたくても声が出ない。仕方がない、何でもよいから食物のある所まであるこうと決心をしてそろりそろりと池を左りに廻り始めた。どうも非常に苦しい。そこを我慢して無理やりに這って行くとようやくの事で何となく人間臭い所へ出た。ここへ這入ったら、どうにかなると思って竹垣の崩れた穴から、とある邸内にもぐり込んだ。縁は不思議なもので、もしこの竹垣が破れていなかったなら、吾輩はついに路傍に餓死したかも知れんのである。一樹の蔭とはよく云ったものだ。この垣根の穴は今日に至るまで吾輩が隣家の三毛を訪問する時の通路になっている。さて邸へは忍び込んだもののこれから先どうして善いか分らない。そのうちに暗くなる、腹は減る、寒さは寒し、雨が降って来るという始末でもう一刻の猶予が出来なくなった。仕方がないからとにかく明るくて暖かそうな方へ方へとあるいて行く。今から考えるとその時はすでに家の内に這入っておったのだ。ここで吾輩は彼の書生以外の人間を再び見るべき機会に遭遇したのである。第一に逢ったのがおさんである。これは前の書生より一層乱暴な方で吾輩を見るや否やいきなり頸筋をつかんで表へ抛り出した。いやこれは駄目だと思ったから眼をねぶって運を天に任せていた。しかしひもじいのと寒いのにはどうしても我慢が出来ん。吾輩は再びおさんの隙を見て台所へ這い上った。すると間もなくまた投げ出された。吾輩は投げ出されては這い上り、這い上っては投げ出され、何でも同じ事を四五遍繰り返したのを記憶している。その時におさんと云う者はつくづくいやになった。この間おさんの三馬を偸んでこの返報をしてやってから、やっと胸の痞が下りた。吾輩が最後につまみ出されようとしたときに、この家の主人が騒々しい何だといいながら出て来た。下女は吾輩をぶら下げて主人の方へ向けてこの宿なしの小猫がいくら出しても出しても御台所へ上って来て困りますという。主人は鼻の下の黒い毛を撚りながら吾輩の顔をしばらく眺めておったが、やがてそんなら内へ置いてやれといったまま奥へ這入ってしまった。主人はあまり口を聞かぬ人と見えた。下女は口惜しそうに吾輩を台所へ抛り出した。かくして吾輩はついにこの家を自分の住家と極める事にしたのである。吾輩の主人は滅多に吾輩と顔を合せる事がない。職業は教師だそうだ。学校から帰ると終日書斎に這入ったぎりほとんど出て来る事がない。家のものは大変な勉強家だと思っている。当人も勉強家であるかのごとく見せている。しかし実際はうちのものがいうような勤勉家ではない。吾輩は時々忍び足に彼の書斎を覗いて見るが、彼はよく昼寝をしている事がある。時々読みかけてある本の上に涎をたらしている。彼は胃弱で皮膚の色が淡黄色を帯びて弾力のない不活溌な徴候をあらわしている。その癖に大飯を食う。大飯を食った後でタカジヤスターゼを飲む。飲んだ後で書物をひろげる。二三ページ読むと眠くなる。涎を本の上へ垂らす。これが彼の毎夜繰り返す日課である。吾輩は猫ながら時々考える事がある。教師というものは実に楽なものだ。人間と生れたら教師となるに限る。こんなに寝ていて勤まるものなら猫にでも出来ぬ事はないと。それでも主人に云わせると教師ほどつらいものはないそうで彼は友達が来る度に何とかかんとか不平を鳴らしている。吾輩がこの家へ住み込んだ当時は、主人以外のものにははなはだ不人望であった。どこへ行っても跳ね付けられて相手にしてくれ手がなかった。いかに珍重されなかったかは、今日に至るまで名前さえつけてくれないのでも分る。吾輩は仕方がないから、出来得る限り吾輩を入れてくれた主人の傍にいる事をつとめた。朝主人が新聞を読むときは必ず彼の膝の上に乗る。彼が昼寝をするときは必ずその背中に乗る。これはあながち主人が好きという訳ではないが別に構い手がなかったからやむを得んのである。その後いろいろ経験の上、朝は飯櫃の上、夜は炬燵の上、天気のよい昼は椽側へ寝る事とした。しかし一番心持の好いのは夜に入ってここのうちの小供の寝床へもぐり込んでいっしょにねる事である。この小供というのは五つと三つで夜になると二人が一つ床へ入って一間へ寝る。吾輩はいつでも彼等の中間に己れを容るべき余地を見出してどうにか、こうにか割り込むのであるが、運悪く小供の一人が眼を醒ますが最後大変な事になる。小供は――ことに小さい方が質がわるい――猫が来た猫が来たといって夜中でも何でも大きな声で泣き出すのである。すると例の神経胃弱性の主人は必ず眼をさまして次の部屋から飛び出してくる。現にせんだってなどは物指で尻ぺたをひどく叩かれた。吾輩は人間と同居して彼等を観察すればするほど、彼等は我儘なものだと断言せざるを得ないようになった。ことに吾輩が時々同衾する小供のごときに至っては言語同断である。自分の勝手な時は人を逆さにしたり、頭へ袋をかぶせたり、抛り出したり、へっついの中へ押し込んだりする。しかも吾輩の方で少しでも手出しをしようものなら家内総がかりで追い廻して迫害を加える。この間もちょっと畳で爪を磨いだら細君が非常に怒ってそれから容易に座敷へ入れない。台所の板の間で他が顫えていても一向平気なものである。吾輩の尊敬する筋向の白君などは逢う度毎に人間ほど不人情なものはないと言っておらるる。白君は先日玉のような子猫を四疋産まれたのである。ところがそこの家の書生が三日目にそいつを裏の池へ持って行って四疋ながら棄てて来たそうだ。白君は涙を流してその一部始終を話した上、どうしても我等猫族が親子の愛を完くして美しい家族的生活をするには人間と戦ってこれを剿滅せねばならぬといわれた。一々もっともの議論と思う。また隣りの三毛君などは人間が所有権という事を解していないといって大に憤慨している。元来我々同族間では目刺の頭でも鰡の臍でも一番先に見付けたものがこれを食う権利があるものとなっている。もし相手がこの規約を守らなければ腕力に訴えて善いくらいのものだ。しかるに彼等人間は毫もこの観念がないと見えて我等が見付けた御馳走は必ず彼等のために掠奪せらるるのである。彼等はその強力を頼んで正当に吾人が食い得べきものを奪ってすましている。白君は軍人の家におり三毛君は代言の主人を持っている。吾輩は教師の家に住んでいるだけ、こんな事に関すると両君よりもむしろ楽天である。ただその日その日がどうにかこうにか送られればよい。いくら人間だって、そういつまでも栄える事もあるまい。まあ気を永く猫の時節を待つがよかろう。我儘で思い出したからちょっと吾輩の家の主人がこの我儘で失敗した話をしよう。元来この主人は何といって人に勝れて出来る事もないが、何にでもよく手を出したがる。俳句をやってほととぎすへ投書をしたり、新体詩を明星へ出したり、間違いだらけの英文をかいたり、時によると弓に凝ったり、謡を習ったり、またあるときはヴァイオリンなどをブーブー鳴らしたりするが、気の毒な事には、どれもこれも物になっておらん。その癖やり出すと胃弱の癖にいやに熱心だ。後架の中で謡をうたって、近所で後架先生と渾名をつけられているにも関せず一向平気なもので、やはりこれは平の宗盛にて候を繰返している。みんながそら宗盛だと吹き出すくらいである。この主人がどういう考になったものか吾輩の住み込んでから一月ばかり後のある月の月給日に、大きな包みを提げてあわただしく帰って来た。何を買って来たのかと思うと水彩絵具と毛筆とワットマンという紙で今日から謡や俳句をやめて絵をかく決心と見えた。果して翌日から当分の間というものは毎日毎日書斎で昼寝もしないで絵ばかりかいている。しかしそのかき上げたものを見ると何をかいたものやら誰にも鑑定がつかない。当人もあまり甘くないと思ったものか、ある日その友人で美学とかをやっている人が来た時に下のような話をしているのを聞いた。「どうも甘くかけないものだね。人のを見ると何でもないようだが自ら筆をとって見ると今更のようにむずかしく感ずる」これは主人の述懐である。なるほど詐りのない処だ。彼の友は金縁の眼鏡越に主人の顔を見ながら、「そう初めから上手にはかけないさ、第一室内の想像ばかりで画がかける訳のものではない。昔し以太利の大家アンドレア・デル・サルトが言った事がある。画をかくなら何でも自然その物を写せ。天に星辰あり。地に露華あり。飛ぶに禽あり。走るに獣あり。池に金魚あり。枯木に寒鴉あり。自然はこれ一幅の大活画なりと。どうだ君も画らしい画をかこうと思うならちと写生をしたら」「へえアンドレア・デル・サルトがそんな事をいった事があるかい。ちっとも知らなかった。なるほどこりゃもっともだ。実にその通りだ」と主人は無暗に感心している。金縁の裏には嘲けるような笑が見えた。 |
|
https://github.com/SillyFreak/typst-packages-old | https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/template/gallery/test.typ | typst | MIT License | // make the PDF reproducible to ease version control
#set document(date: none)
#import "../src/lib.typ": add
// #import "@preview/template:0.0.1": add
= Test
#add(2, 7)
|
https://github.com/KuangjuX/typst-resume | https://raw.githubusercontent.com/KuangjuX/typst-resume/main/resume.typ | typst | MIT License | #import "chicv.typ": *
#show: chicv
= <NAME>
#fa[#envelope] <EMAIL> |
#fa[#github] #link("https://github.com/KuangjuX")[github.com/KuangjuX] |
#fa[#globe] #link("https://kuangjux.top")[kuangjux.top] |
#fa[#linkedin] #link("https://www.linkedin.com/in/kuangjux/")[KungjuX]
== Education
#cventry(
tl: "University of Chinese Academy of Sciences",
tr: "2023/08 - ",
bl: "Master of Computer Architecture",
br: "Hangzhou, Zhejiang, China"
)[]
#cventry(
tl: "TianJin University",
tr: "2019/09 - 2023/06(Expected)",
bl: "B. Eng in Computer Science and Technology",
br: "TianJin, China"
)[
- Teaching Assistant for ICS(Introduction to Computer System) in Fall 2021
- 4.0 Courses: ICS, Computer Architecture, Advanced Computer Architecture, Operating System and so on.
]
== Skills
- *Programmimg Languages:* Rust, C, Go, Python, JavaScript, Assembly
- *Tools:* Linux, Git, GDB, QEMU, Makefile, Docker
- *System:* Familiar with the concepts and design of operating system kernels, and have experience designing and implementing operating system kernels using the Rust language. Passionate and knowledgeable about the RISC-V instruction set architecture, with multiple projects designed based on the RISC-V instruction set.
- *Arch:* I have previously designed and implemented a MIPS 32-bit processor core, have read some of CAAQA, and have implemented a out-of-order simulator of tomasulo algorithm in Rust.
- *Storage/DB:* Self-taught CMU 15-445, TiKV talent-plan, and some of MIT 6.824 and completed the corresponding labs.
- *Open Source Contributions:* I have contributed code to multiple open source projects such as \@rCore-Tutorial-v3, \@cs-self-learning, and \@rustyvisor, and my personal open source projects have a total of over 400 stars.
== Selected Awards
- NSCSCC Team Competition Third Prize in 2022
- OSCOMP Team Competition Thrid Prize in 2021
- Summer OSPP The Best Quality Award in 2021
== Selected Projects
#cventry(
tl: "ko-ok-OS/xv6-rust" + "(" + fa(star)+"169)" + " " + iconlink("https://github.com/Ko-oK-OS/xv6-rust", icon: github),
tr: "2021/02 - 2021/08"
)[
- A Unix-like operating system implemented pure rust.
- Optimize memory module using Buddy Sytem.
- Redesign Spinlock/Sleeplock as smart pointer.
- Optimize file system, making it support Rust features.
]
#cventry(
tl: "hypocaust-2" + "(" + fa(star)+"17)" + " " + iconlink("https://github.com/hypocaust-2", icon: github),
tr: "2023/02 - Now"
)[
- A hardware-assisted RISC-V type-1 hypervisor written in Rust.
- Implement SBI call process, two stage page table translation, PLIC emulation(interrupt inject), exception delegation, passthrough or emulate devices.
- Capable of booting rCore-Tutorial-v3, RT-Thread, Linux mainline.
]
#cventry(
tl: "hypocaust" + "(" + fa(star)+"29)" + " " + iconlink("https://github.com/hypocaust-2", icon: github),
tr: "2023/01 - 2023/02"
)[
- A S mode trap & emulate RISC-V type-1 hypervisor written in Rust.
- Implement SBI call process, shadow page table construction, synchronization between shadow page table and guest page table, PLIC emulation(interrupt inject), exception delegation, passthrough or emulate devices.
- Capable of booting minikernel(a small os kernel with filesystem).
]
#cventry(
tl: "rCore-fat" + " " + iconlink("https://github.com/rCore-fat", icon: github),
tr: "2021/07 - 2021/08"
)[
- Design fat32 file system for rCore-Tutorial-v3, it is a alternative topic of rCore OS community in Summer OSPP 2021.
- It can run successfully on qemu and k210 development boards.
]
== Talks & Presentations
#cventry(
tl: "Hypocaust, a Type-1 RISC-V hypervisor",
tr: "2023/03/26",
bl: "Invited talk in OS2ATC 2022",
br: "Beijing, China"
)[
- slide: http://kuangjux.top/file/talks/hypocaust.pdf
- vedio: https://live.csdn.net/room/csdnlive5/VKfSCOiR
]
== Experience
#cventry(
tl: "Summer OSPP 2021",
tr: "2021/07 - 2021/09"
)[
- Participated in the work of the rcore-os community and supported the FAT32 file system for rCore-Tutorial-v3, successfully running it on QEMU and K210. My work won the Best Quality Award for the Summer of Open Source in 2021.
]
#cventry(
tl: "TWT Studio",
tr: "2019/09 - 2021/02",
bl: "Software Enginer",
br: "TianJin, China"
)[
- Developed a management system for the school management system in Vue.js and it can run stably on the server.
- Maintained the school's party building system in PHP and participated in part of the system's reconstruction work.
]
|
https://github.com/maantjemol/Aantekeningen-Jaar-2 | https://raw.githubusercontent.com/maantjemol/Aantekeningen-Jaar-2/main/IBIA/aantekeningen.typ | typst | // Update this import to where you put the `lapreprint.typ` file
// It should probably be in the same folder
#import "../template/lapreprint.typ": template
#import "../template/frontmatter.typ": loadFrontmatter
#import "@preview/drafting:0.2.0": *
#let defaultColor = rgb("#f2542d")
#show: template.with(
title: "IBIA",
subtitle: "Samenvatting + aantekeningen",
short-title: "IBIA Samenvatting",
venue: [ar#text(fill: red.darken(20%))[X]iv],
// This is relative to the template file
// When importing normally, you should be able to use it relative to this file.
theme: defaultColor,
authors: (
(
name: "<NAME> . ",
),
),
kind: "Samenvatting",
abstract: (
(title: "Samenvatting", content: lorem(100)),
),
open-access: true,
margin: (
(
title: "Key Points",
content: [
- #lorem(10)
- #lorem(5)
- #lorem(7)
],
),
),
font-face: "Open Sans"
)
#set page(
margin: (left: 2in, right: 0.8in), paper: "us-letter"
)
#let marginRatio = 0.8
#let default-rect(stroke: none, fill: none, width: 0pt, content) = {
pad(left:width*(1 - marginRatio), rect(width: width*marginRatio, stroke: stroke)[
#content
])
}
#set-page-properties()
#show terms: it => [
#margin-note(rect: default-rect, side: left, stroke: 0pt)[#text(defaultColor, weight: 600, size: 10pt)[#it.children.first().term:]\ #it.children.first().description]
]
#set heading(numbering: none)
#show heading: set text(defaultColor, weight: "medium")
= Presentatie geven deel 3 <presentatie>
Je wilt dat mensen je presentatie onthouden, maar ook je naam onthouden. Dit kan je doen door je naam wat langzamer uit te spreken.
/ <NAME>: start with the most important information and then build your case with supporting details
== Verhaal $->$ Vorm $->$ Inhoud:
- *<NAME>*
- Als je weet hoe het verhaal gaat lopen kan je de vorm bepalen en wordt de inhoud makkelijker.
- Maak bvb van te voren een template voor je presentatie.
== Presentatie $!=$ rapport:
- Probeer niet 50 slides in 10 minuten te proppen.
== Backup:
Heb een backup plan voor als er iemand ziek is of als de techniek niet werkt. Zorg dat je op tijd bent. Laat je niet afleiden als er iets fout gaat, hou er gewoon rekening mee dat er iets mis kan gaan.
== Wees op tijd & test:
- Zorg dat je op tijd bent en dat je alles getest hebt.
== Online presentaties:
Niet iedereen heeft een goede internetverbinding. Je hoort het ook niet allemaal tegelijkertijd. Let nog meer op je stiltes en geef ruimte voor vragen.
== Advies rapport:
- Expliciet zeggen dat mensen de *vragen aan het eind* moeten stellen!
- Stuur een uitnodiging voor de presentatie. Zet belangrijke punten in de uitnodiging. Zet het doel van de presentatie erin.
- Wees expliciet over wat het doel van je rapport is.
- Vertel wat je gaat doen (*vlak voor de key points*).
- Er worden vragen gesteld, dus notuleren is belangrijk (*iemand neerzetten die meeschrijft*)
- Vaak heb je ook nog een management samenvatting nodig. Die moet 100% op zichzelf staan. Max 1 slide. (*hoeft niet voor opdracht*).
- Zorg voor focus
- Zet scenario's neer. Geef 3 varianten.
#pagebreak()
= AI voor organisaties:
Hoe werken die modellen, wat kan je ermee en wat heb je eraan als organisatie?
== Large language models (LLMs):
- LLMs worden bijvoorbeeld gebruikt in de zorg.
= Vergelijken van software:
- Kan je systeem in de toekomst goed werken, is het relevant voer 2 jaar
- Leg evt het process uit waar je doorheen bent gegaan als groep
- Business, capability to fit your needs
- Architecture, ability to integrate
- Delivery, meet out of the box configuration capabilities
- Company Viability, financial viability, is it big enough to support you
- TCO (total cost of ownership)
- Retail Execution
- Detailing
- Analytics and reports
- Experience
- Other
- Procurement
- Relations |
|
https://github.com/Lucas-Wye/tech-note | https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/openmp.typ | typst | = OpenMP
#label("openmp")
- OpenMP是由OpenMP Architecture Review Board牵头提出的,并已被广泛接受的,用于共享内存并行系统的多线程程序设计的一套编译指令
(Compiler Directive)。
== Introduction
#label("introduction")
See detail at #link("https://en.wikipedia.org/wiki/OpenMP")[wiki].
== OpenMP Programming Example
#label("openmp-programming-example")
Here is a C program using OpenMP.
```c
#include<stdio.h>
#include<omp.h>
int main(void) {
const int n = 10;
int arr[n];
#pragma omp parallel for
for(int i = 0;i < n;i++) {
arr[i] = i;
printf("%d\n",i);
}
for(int j = 0;j < n;j++){
printf("%d\n",arr[j]);
}
return 0;
}
```
== More Example
#label("more-example")
#link("https://zhuanlan.zhihu.com/p/51173703")[OpenMP并行开发(C++)] \
#link("https://blog.csdn.net/drzhouweiming/article/details/1175848")[OpenMP并行程序设计(二)]
|
|
https://github.com/Mc-Zen/tidy | https://raw.githubusercontent.com/Mc-Zen/tidy/main/examples/funny-math/funny-math-docs.typ | typst | MIT License | #import "template.typ": *
// #import "@preview/tidy:0.1.0"
#import "../../src/tidy.typ"
#import "custom-style.typ"
#show: project.with(
title: "funny-math",
subtitle: "Because math should be fun",
authors: ("Euklid",),
abstract: [*funny-math* is a funny math package for #link("https://typst.app/", [Typst]). ],
date: "361 B.C.",
)
// We can apply global styling here to affect the looks
// of the documentation.
#set text(font: "Calibri", size: 9pt)
// #show heading: set text(size: 11pt)
// Module name
#show heading.where(level: 1): set text(size: 1.3em, font: "Cascadia Mono")
// Function name
#show heading.where(level: 2): set text(size: 1.2em, font: "Cascadia Mono")
#show heading.where(level: 2): block.with(above: 3em, below: 2em)
// "Parameters", "Example"
#show heading.where(level: 3): set text(size: 1.1em, weight: "semibold")
// #show heading.where(level: 3): block.with(spacing: 2em)
#show heading.where(level: 4): set text(size: 1.1em, font: "Cascadia Mono")
#pagebreak()
#{
import "funny-math.typ"
import "funny-math-complex.typ"
let image-polar = image("polar.svg", width: 150pt)
let show-module = tidy.show-module.with(
first-heading-level: 1,
style: custom-style
)
let funny-module = tidy.parse-module(
read("funny-math.typ"),
name: "funny-math",
label-prefix: "funny-math",
scope: (funny-math: funny-math)
)
show-module(funny-module)
let funny-module-ext = tidy.parse-module(
read("funny-math-complex.typ"),
name: "funny-math.complex",
label-prefix: "funny-math",
scope: (funny-math-comples: funny-math-complex, image-polar: image-polar)
)
pagebreak()
// Also show the "complex" sub-module which belongs to the main module (funny-math.typ) since it is imported by it.
show-module(funny-module-ext)
}
|
https://github.com/kznr02/neet-cv | https://raw.githubusercontent.com/kznr02/neet-cv/main/template.typ | typst | MIT License | #let project(body) = {
set page(paper: "a4", margin: (x: 1.2cm, y: 1cm))
set text(font: "Noto Sans", lang: "zh", size:9pt)
// Main body.
set par(justify: true)
body
}
#let info(name, phone, email, age, grade, github, zhihu, bilibili, photo) = {
box(
width: 100%,
height: auto,
[
#set align(left)
#set box(baseline: 5pt)
#place(right, [
#image(photo, width: 16%)
])
#set text(size: 9pt)
= #name
#box(height: 15pt, image("./assets/电话.svg"))
#h(1pt) #phone
#v(1pt, weak: true)
#box(height: 15pt, image("./assets/邮箱.svg"))
#h(1pt) #email
#v(1pt, weak: true)
#box(height: 15pt, image("./assets/年龄.svg"))
#h(1pt) #age 岁
#h(4pt)
#box(height: 15pt, image("./assets/学历.svg"))
#h(1pt) #grade
#h(4pt)
#if github != none {
box(height: 14pt, image("./assets/github.svg"))
[#h(1pt)#link(github)]
}
]
)
}
#let ctx(title) = {
v(10pt, weak: true)
box(
width: auto,
height: auto,
[
= #title
#line(length: 100%, stroke: 2pt + blue)
]
)
}
#let education(school, pro, grade, ins, lesson, time_s, time_e) = {
ctx([教育经历])
set par(justify: true)
[
#v(8pt, weak: true)
#place(right, [#time_s - #time_e])
*#school* - #pro #grade #ins
主修课程:
#for value in lesson {
[#value, ]
} 等。
]
}
#let job(c: ()) = {
ctx([实习经历])
set par(justify: true)
for value in c {
v(8pt, weak: true)
place(right, [
#value.at(2) - #value.at(3)
])
[
*#value.at(0)* - #value.at(1)
#v(9pt, weak: true)
#if value.at(4) != none {
[工作内容:#value.at(4)]
}
]
}
}
#let glory(c: ()) = {
ctx([荣誉奖项])
set par(justify: true)
for i in c {
v(8pt, weak: true)
place(right, [#i.at(1)])
[
#i.at(0)
]
}
}
#let proj(c: ()) = {
ctx([项目经历])
set par(justify: true)
for i in c {
v(8pt, weak: true)
place(right, [
#i.at(2) - #i.at(3)
])
[
*#i.at(0)* - #i.at(1)
#v(9pt, weak: true)
#i.at(4)
]
if i.at(5) != none {
v(9pt, weak: true)
[*项目地址*:#link(i.at(5))]
}
}
}
#let activity(c: ()) = {
ctx([社团和组织经历])
set par(justify: true)
for i in c {
v(8pt, weak: true)
place(right, [
#i.at(2) - #i.at(3)
])
[
*#i.at(0)* - #i.at(1)
#v(9pt, weak: true)
#if i.at(4) != none {
[负责工作:#i.at(4)]
}
]
}
}
#let skill(c) = {
ctx([个人技能])
set par(justify: true)
v(8pt, weak: true)
[#c]
}
#let certification(c: ()) = {
ctx([技能/语言证书])
v(8pt, weak: true)
[*技能:*]
for i in c.at(0) {
[#i]
}
v(8pt, weak: true)
[*语言:*]
for i in c.at(1) {
[#i]
}
}
#let commit(c) = {
ctx([个人评价])
v(8pt, weak: true)
[#c]
} |
https://github.com/gigu003/typst-templates | https://raw.githubusercontent.com/gigu003/typst-templates/main/qcreport/README.md | markdown | MIT License | # Typst Qcreport Format
## Installing
```bash
quarto use template gigu003/typst-templates/qcreport
```
This will install the format extension and create an example qmd file
that you can use as a starting place for your document.
## Using
```bash
---
title: This is a report title
subtitle: "第一季度"
date: today
authors:
- name: 陈 琼
email: <EMAIL>
affiliation: "河南省肿瘤医院"
format:
qcreport-typst:
registry: "河南省肿瘤登记处"
header: "质控报告"
footer: "https://chenq.site"
section-numbering: "1."
mainfont: "song"
toc: true
---
```
This is what a poster with the options specified above might look like:

|
https://github.com/swablab/documents | https://raw.githubusercontent.com/swablab/documents/main/beitragsordnung.typ | typst | Creative Commons Zero v1.0 Universal | #import "templates/tmpl_doc.typ": tmpl_doc
#show: doc => tmpl_doc(
title: "Beitragsordnung",
changes: (
[v1.0], [19.10.2020], [erste Fassung],
[v1.1], [01.04.2023], [
- Anpassung Beitragshöhe Födermitglieder \ (@beitrag[§], Absatz 5)
- Hinzufügen neue Familienklausel (@beitrag[§], Absatz 2)
]),
doc,
)
= Allgemeines
+ Diese Beitragsordnung ist nicht Bestandteil der Satzung. Sie kann nur von der Mitgliederversammlung des Vereins geändert werden.
+ Beim Ausscheiden aus dem Verein erfolgt keine Rückerstattung bereits geleisteter Beiträge.
= Beschlüsse
Beschlüsse über die Änderung der Beitragsordnung gelten ab dem 1. des auf die Beschlussfassung folgenden Monats. Durch Beschluss der Mitgliederversammlung kann auch ein anderer Termin festgelegt werden.
= Beitragshöhe <beitrag>
+ Die Beitragshöhe für ordentliche Mitglieder beträgt mindestens 16 € monatlich. Der Mitgliedsbeitrag einer natürlichen Person ohne oder mit geringem Einkommen kann auf einen reduzierten Betrag von mindestens 8 € je Monat gewährt werden. Dies gilt unter anderem für Schüler, Stundenten und Auszubildende. Fördermitglieder entrichten einen Mitgliedsbeitrag von mindestens 2 € monatlich.
+ Für Familien, bestehend aus zwei ordentlichen Mitgliedern und deren Kindern zwischen 12 und 18 Jahren, wird ein Mindestbeitrag von 32 € monatlich erhoben. Dies gilt nur soweit die Kinder in einem unentgeltlichen Ausbildungsverhältnis stehen.
+ Ermäßigte Beitragsformen müssen beantragt werden. Der Anspruch auf die Ermäßigung ist mit entsprechenden Unterlagen nachzuweisen.
+ Änderungen der persönlichen Angaben sind dem Verein schnellstmöglich mitzuteilen.
+ Die Zahlung der Beiträge erfolgt in der Regel im Bankeinzugsverfahren monatlich, kann aber auch als Jahresbeitrag im Voraus geleistet werden. Eine Ermäßigung des Beitrages bei jährlicher Zahlweise im Voraus ist nicht möglich.
+ Bei Mahnungen werden Mahngebühren von 3 € pro Mahnung erhoben.
+ Die Gebühren von Lastschriftrückgaben sind vollständig vom Mitglied zu tragen.
+ Für den Eintrittsmonat ist bei Eintritt vor dem 15. des Monats die volle Beitragshöhe zu entrichten. Bei einem späteren Eintritt wird für den Eintrittsmonat ein um 50% reduzierter Beitrag erhoben.
= Säumnis
Im Säumnisfall wird das Mitglied nach einmonatigem Ausbleiben des Beitrags gemahnt. Zahlt ein Mitglied trotz zweifacher Mahnung (in Textform) oder länger als drei Monate den Beitrag nicht, so gilt nach Ablauf eines Monates nach der zweiten Mahnung die Nichtzahlung als Austritt. In der zweiten Mahnung ist auf die Folgen der Nichtzahlung hinzuweisen.
= Stundung
Auf Antrag kann der Vorstand die Stundung - im Falle sozialer Härten auch den Erlass der Beiträge für höchstens ein Jahr beschließen.
|
https://github.com/qjcg/typstry | https://raw.githubusercontent.com/qjcg/typstry/main/templates/professional-formal-letter/letter.typ | typst | MIT License | #let name = [Dr. <NAME>, PhD]
#show link: set text(blue)
#set text(13pt)
#grid(
columns: (20%, 80%),
rows: (14%),
gutter: 3.5%,
[#image("logo.jpg",width: 100%)],
[
#align(bottom)[
#grid(
columns: (50%,50%),
rows: (80%),
[#text(size: 18pt)[UNIVERSITY\ OF CALIFORNIA]],
[#align(right)[#text(weight: "bold")[#name]]],
)
]
#v(-8%)
#line(length: 100%, stroke: 1.5pt)
#v(22.5%)
]
)
#text()[
#grid(
columns: (50%,50%),
rows: (17.5%),
[
#align(bottom)[
Prof. Jones\
Mathematics Search Committee\
Department of Mathematics\
University of California\
Berkeley, California 12345\
]
],
[
#align(right)[
#v(-20%)
#box(width: auto)[
#align(left)[
Dr. <NAME>\
Department of Mathematics\
123 Broadway\
Berkeley CA 12345\
Email: #link("mailto:<EMAIL>")[<EMAIL>]\
Phone: #link("tel:000-111-1111")[(000) 111-1111]\
URL: #link("https://typst.app/")[typst.app]
]
]
]
]
)
]
#v(5%)
Dear Sir or Madam\
#set par(first-line-indent: 30pt)
#lorem(60)\
#lorem(75)\
#lorem(55)\
#align(center)[Sincerely,]
#v(2%)
#align(center)[#name]
|
https://github.com/Thumuss/truthfy | https://raw.githubusercontent.com/Thumuss/truthfy/main/main.typ | typst | MIT License | #let (
generate-empty,
generate-table,
truth-table,
truth-table-empty,
NAND,
NOR,
nand,
nor,
karnaugh-empty,
//karnaugh,
) = {
let symboles-conv(a) = {
if (a) {
"1"
} else { "0" }
}
/// Transform a simple math equation to a string
let _strstack(obj) = if obj.body.has("b") {
obj.body.base.text + "_" + obj.body.b.text;
} else if not obj.body.has("children") {
" "
} else {
obj.body.children.map(subobj => {
if subobj.has("text") {
subobj.text
} else {
if subobj.fields().len() == 0 {
" "
} else {
if (subobj.has("b")) {
subobj.base.text + "_" + subobj.b.text;
} else {
_strstack(subobj.fields())
}
}
}
}).flatten().join("")
}
/// Replaces names with their values (true or false)
let _replaces(names, vals, obj) = {
// Replace names by their values
let text = obj
for e in range(names.len()) {
let reg = regex("\b(?:\(?\s?)(" + names.at(e) + ")(?:\s?\W?\)?)?\b");
for f in text.matches(reg) {
text = text.replace(reg, vals.at(e))
}
}
// Basic operations, they doesn't need a particular approach
text = str(text.replace("∧", "and").replace("∨", "or")).replace("¬", "not")
// => Approach
// Please implement the do while :pray:
while true {
let pos = text.match(
regex("([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*⇒[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+"),
) // regex hell
if (pos != none) {
text = text.replace(pos.text, "not " + pos.text.replace("⇒", "or", count: 1))
} else { break }
}
// ↑ Approach
while true {
let pos = text.match(
regex("([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*↑[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+"),
)
if (pos != none) {
text = text.replace(pos.text, "not(" + pos.text.replace("↑", "and", count: 1) + ")")
} else { break }
}
// ↓ Approach
while true {
let pos = text.match(
regex("([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*↓[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+"),
)
if (pos != none) {
text = text.replace(pos.text, "not(" + pos.text.replace("↓", "or", count: 1) + ")")
} else { break }
}
// <=> Approach
while true {
let pos = text.match(
regex("([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*⇔[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+"),
)
if (pos != none) {
text = text.replace(pos.text, "(" + pos.text.replace("⇔", "==", count: 1) + ")")
} else { break }
}
// a ? b : c Approach
while true {
let pos = text.match(
regex(
"([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*\?[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*\:[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+",
),
)
if (pos != none) {
text = text.replace(
pos.text,
" if (" + pos.text.replace("?", "){ ").replace(":", " } else { ") + " }",
)
} else { break }
}
// ⊕ Approach
while true {
let pos = text.match(
regex("([(]+.*[)]|[a-zA-Z](_\d+)?)+[ ]*⊕[ ]*([(]+.*[)]|[a-zA-Z](_\d+)?)+"),
)
if (pos != none) {
text = text.replace(pos.text, "not (" + pos.text.replace("⊕", "==", count: 1) + ")")
} else { break }
}
return text
}
/// Extract all propositions
let _extract(..obj) = {
let single_letters = ();
for operation in obj.pos(){
let string_operation = _strstack(operation).split(" ");
for substring in string_operation {
let match = substring.match(regex("[a-zA-Z](_\d+)?"));
if match != none and (match.text not in single_letters) {
single_letters.push(match.text)
}
}
}
return single_letters
}
let _gen-nb-left-empty-truth(reverse: false, sc: symboles-conv, bL, row) = {
let rng = range(1, bL + 1)
for col in if reverse { rng } else { rng.rev() } {
let raised = calc.pow(2, col - 1);
let vl = if reverse { (L - 1) - row } else { row }
let value = not calc.even(calc.floor(vl / raised))
([#sc(value)],)
}
}
let _mathed(obj) = eval(obj, mode: "math")
let truth-table-empty(reverse: false, sc: symboles-conv, info, data) = {
let base = _extract(..info)
let bL = base.len()
let L = calc.pow(2, bL);
let iL = info.len()
let nbBox = (iL + bL) * calc.pow(2, bL)
if data.len() < nbBox {
for _ in range(nbBox - data.len()) {
data.push([])
}
}
table(
columns: iL + bL,
..base.map(_mathed),
..info,
..(
for row in range(L) {
(.._gen-nb-left-empty-truth(reverse: reverse, sc: sc, bL, row))
(
..data.slice(row * iL, count: iL).map((a) => [#if type(a) != "content" { sc(a) } else { a }]),
)
}
),
)
}
let _first-elem-karnaugh = (0, 0, 1, 1);
let _second-elem-karnaugh = (0, 1, 1, 0);
let _nb-cols-karnaugh = (0, 3, 3, 5, 5)
let _concat-name-karnaugh(list: ()) = {
let bL = list.len();
let name = list.at(0);
if (bL == 2) { return name + "/" + list.at(1) } else if (bL == 3) { return name + "/" + list.at(1) + list.at(2) } else { return name + list.at(1) + "/" + list.at(2) + list.at(3) }
}
let _concat-object-karnaugh(reverse: false, sc: symboles-conv, i: 0, nb: false) = {
let m = [#sc(_first-elem-karnaugh.at(if reverse { 3 - i } else { i }) == 1)]
let n = [#sc(_second-elem-karnaugh.at(if reverse { 3 - i } else { i }) == 1)]
n
if nb {
m
}
}
let karnaugh-empty(reverse: false, sc: symboles-conv, info, data) = {
let base = _extract(..info)
let bL = base.len()
assert(
bL >= 2,
message: "You need more than 1 variable and less or equal 4 variables to use a karnaugh table.",
);
let L = int(calc.pow(2, bL - 1) / 2);
if L == 1 { L = 2 } // hack for now
let nbBox = calc.pow(2, bL)
let columns = _nb-cols-karnaugh.at(bL)
let name = _concat-name-karnaugh(list: base);
if data.len() < nbBox {
for _ in range(nbBox - data.len()) {
data.push([ ])
}
}
table(
columns: columns,
name,
..for col in range(columns - 1) {
let m = _concat-object-karnaugh(reverse: reverse, sc: sc, i: col, nb: bL >= 3)
(m,)
},
..for row in range(L) {
(
..(
[#_concat-object-karnaugh(reverse: reverse, sc: sc, i: row, nb: bL >= 4)],
),
)
(
..data.slice(row * (columns - 1), count: columns - 1).map((a) => [#if type(a) != "content" { sc(a) } else { a }]),
)
},
)
}
/*let karnaugh(sc: symboles-conv, ..info) = {
let objInfo = info.pos()
let base = _extract(..objInfo)
let data = ()
let bL = base.len()
assert(
bL >= 2,
message: "You need more than 1 variable and max 4 variables to use a karnaugh table.",
);
let L = int(calc.pow(2, bL - 1) / 2);
if L == 1 { L = 2 } // hack for now
let nbBox = calc.pow(2, bL)
let columns = _nb-cols-karnaugh.at(bL)
let transform = objInfo.map(_strstack).map(a => "(" + a + ")")
let joined = if transform.at(0).contains("∧") {
transform.join("∨")
} else {
transform.join("∧")
}
let elems2 = ((false, false), (false, true), (true, false), (true, true)).map(a => a.map(repr))
let elem3 = {
let o = elems2
(o.map(a => ("false", ..a)) + o.map(a => ("true", ..a)))
}
let zeros = if (base.len() == 2) { elem2 } else if (base.len() == 3) { elem3 } else {}
for i in range(nbBox) {
let x = zeros.at(i)
repr(x)
/*let repp = _replaces(base, x, joined)
data.push(eval(repp))*/
//data.push(false)
}
//karnaugh-empty(sc: sc, objInfo, data)
}*/
let truth-table(reverse: false, sc: symboles-conv, ..inf) = {
let info = inf.pos()
let base = _extract(..info)
let bL = base.len()
let L = calc.pow(2, bL);
let iL = info.len()
let nbBox = (iL + bL) * calc.pow(2, bL)
let transform = info.map(_strstack)
table(columns: iL + bL, ..base.map(_mathed), ..info, ..(for row in range(L) {
let list = ();
let rng = range(1, bL + 1)
(..for col in rng { // The left side
let raised = calc.pow(2, col - 1);
let vl = if reverse { (L - 1) - row } else { row }
let value = not calc.even(calc.floor(vl / raised))
list.push(value)
([#sc(value)],)
})
let x = list.map(repr)
if x != none and x.len() != 0 {
(..for col in range(iL) { // The right side
let m = _replaces(base, x, transform.at(col));
//([#m],) // Debug
let k = eval(m);
([#sc(k)],)
})
}
}))
}
let generate-table = truth-table; // DEPRECATED
let generate-empty = truth-table-empty ; // DEPRECATED
// For simplified writing
let NAND = "↑";
let NOR = "↓"
let nand = "↑"
let nor = "↓"
(
generate-empty,
generate-table,
truth-table,
truth-table-empty,
NAND,
NOR,
nand,
nor,
karnaugh-empty,
//karnaugh,
)
}
/*#karnaugh-empty(($A B C$,), ())
#karnaugh-empty(($A B C D$,), ())
#karnaugh-empty(($A B$,), ())
//#karnaugh($A and B$, $ C and B and D$)
#truth-table($A and B$, reverse: true)
//#karnaugh($A and B and C$)
//#karnaugh($A and B and C$)
//#karnaugh($A and B and C and D$)*/
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.