repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/unit/sticky-per/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": unit, metro-setup
#set page(width: auto, height: auto)
#metro-setup(per-mode: "power")
#unit("pascal per gray henry")
#unit("pascal per gray henry", sticky-per: true)
|
https://github.com/Servostar/dhbw-abb-typst-template | https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/lib.typ | typst | MIT License |
// .--------------------------------------------------------------------------.
// | Template of DHBW thesis |
// '--------------------------------------------------------------------------'
// Author: <NAME>
// Edited: 27.06.2024
// License: MIT
#import "conf.typ": validate-config, default-config
#import "branding.typ": *
#import "style.typ": global_styled_doc, content_styled, end_styled
#import "glossary.typ": glossary
#import "pages/titlepage.typ": new_title_page
#import "pages/declaration-of-authorship.typ": new_declaration_of_authorship
#import "pages/confidentiality-statement.typ": new_confidentiality_statement_page
#import "pages/prerelease-note.typ": new_prerelease_note
#import "pages/outline.typ": new_outline
#import "pages/abstract.typ": new_abstract
#import "pages/preface.typ": new-preface
#import "pages/appendix.typ": show-appendix
#let group-break() = {
[#pagebreak()]
}
#let inline-color(color, content) = {
box(
stroke: 1pt + ABB-GRAY-05,
radius: 2pt,
inset: (left: 2pt, right: 2pt),
outset: (top: 4pt, bottom: 4pt),
fill: ABB-GRAY-06,
[#box(
fill: rgb(color),
radius: 2pt,
inset: 0pt,
width: 0.75em,
height: 0.75em,
) #text(
font: default-config.style.code.font,
size: default-config.style.code.size,
content,
)],
)
}
#let url(label, content) = {
link(label)[#underline(
offset: 2pt,
stroke: 0.5pt + blue,
text(fill: blue)[
#content
#let domain = label.find(regex("\w+\.\w+(?:\.\w+)*"))
#if domain.len() > 0 [
(#domain)
]
],
)]
}
// start of template pages and styles
#let dhbw-template(config, body) = [
#let config = validate-config(config)
#let doc = body
// apply global style to every element in the argument content
#global_styled_doc(config)[
// set document properties
#set document(
author: config.author.name,
keywords: config.thesis.keywords,
title: config.thesis.title,
)
// configure text locale
#set text(
lang: config.lang,
region: config.region,
)
// preppend title page
#new_title_page(config)
// prelude includes: title, declaration of authorship, confidentiality statement, outline and abstract
// these will have roman page numbers
#new_declaration_of_authorship(config)
#new_confidentiality_statement_page(config)
#if config.draft {
new_prerelease_note(config)
}
#new_abstract(config)
#new-preface(config)
#new_outline()
// glossary is built inline here because the links must be
// exposed to the entire document
#import "glossarium.typ": *
#show: make-glossary
#pagebreak(weak: true)
#if "glossary" in config.thesis and config.thesis.glossary != none {
print-glossary(
show-all: false,
disable-back-references: true,
enable-group-pagebreak: true,
glossary(config.thesis.glossary, config),
)
pagebreak(weak: true)
}
#counter(page).update(1)
// mark end of prelude
#metadata("prelude terminate") <end-of-prelude>
#content_styled(config, doc)
#metadata("content terminate") <end-of-content>
#end_styled(config)[
// add bibliography if set
#if "bibliography" in config.thesis and config.thesis.bibliography != none {
pagebreak(weak: true)
counter(page).update(1)
set bibliography(style: "ieee")
config.thesis.bibliography
}
// appendix
#show-appendix(config: config)
]
]
]
|
https://github.com/AntoniosBarotsis/typst-assignment-template | https://raw.githubusercontent.com/AntoniosBarotsis/typst-assignment-template/master/template.typ | typst | // This should be private but don't think Typst supports that (?)
#let box(contents) = {
rect(
fill: rgb(242,242,242),
stroke: 0.5pt,
width: 100%,
align(center)[#contents]
)
}
// A simple, single question and answer
#let answer(question, term) = {
[== #question]
box(term)
}
// A question with multiple sub-questions and corresponding answers.
//
// The numbering can be configured by specifying the `numbering_fmt` parameter.
#let answer(question, numbering_fmt: "a", ..answers) = {
[== #question]
let length = answers.pos().len()
for i in range(0, length) {
let answer = answers.pos().at(i)
let question_number = numbering(numbering_fmt, i+1) // Numbering must be non-negative
[=== #question_number)]
box(answer)
}
}
// Sets the document title, author and optionally, a student number.
#let init(title, author, student_number: none) = {
set document(title: title, author: author)
align(top + left)[Student name: #author]
if student_number != none {
align(top + left)[Student number: #student_number]
}
align(center)[= #title]
}
|
|
https://github.com/Shedward/dnd-charbook | https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/game/abilities.typ | typst | #import "../core/core.typ": *
#let ability(title, source: none, body) = (
title: title,
source: source,
body: body
)
#let abilityCharges(count) = figure(box(framed(checkboxes(count))))
#let abilityRequirement(body) = [
#set text(top-edge: 0.5em)
#set par(first-line-indent: 0em)
#emph(body)
]
#let abilitySlot(lines) = figure(
box(
framed(
fitting: expand-h,
insets: (
x: paddings(2),
y: if lines == 1 { paddings(1) } else { 0pt }
)
)[
#inputGrid(lines)
]
)
)
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/stack.typ | typst | // Test stack layouts.
--- stack-basic ---
// Test stacks with different directions.
#let widths = (
30pt, 20pt, 40pt, 15pt,
30pt, 50%, 20pt, 100%,
)
#let shaded(i, w) = {
let v = (i + 1) * 10%
rect(width: w, height: 10pt, fill: rgb(v, v, v))
}
#let items = for (i, w) in widths.enumerate() {
(align(right, shaded(i, w)),)
}
#set page(width: 50pt, margin: 0pt)
#stack(dir: btt, ..items)
--- stack-spacing ---
// Test spacing.
#set page(width: 50pt, margin: 0pt)
#let x = square(size: 10pt, fill: eastern)
#stack(
spacing: 5pt,
stack(dir: rtl, spacing: 5pt, x, x, x),
stack(dir: ltr, x, 20%, x, 20%, x),
stack(dir: ltr, spacing: 5pt, x, x, 7pt, 3pt, x),
)
--- stack-overflow ---
// Test overflow.
#set page(width: 50pt, height: 30pt, margin: 0pt)
#box(stack(
rect(width: 40pt, height: 20pt, fill: conifer),
rect(width: 30pt, height: 13pt, fill: forest),
))
--- stack-fr ---
#set page(height: 3.5cm)
#stack(
dir: ltr,
spacing: 1fr,
..for c in "ABCDEFGHI" {([#c],)}
)
Hello
#v(2fr)
from #h(1fr) the #h(1fr) wonderful
#v(1fr)
World! 🌍
--- stack-rtl-align-and-fr ---
// Test aligning things in RTL stack with align function & fr units.
#set page(width: 50pt, margin: 5pt)
#set block(spacing: 5pt)
#set text(8pt)
#stack(dir: rtl, 1fr, [A], 1fr, [B], [C])
#stack(dir: rtl,
align(center, [A]),
align(left, [B]),
[C],
)
--- issue-1240-stack-h-fr ---
// This issue is sort of horrible: When you write `h(1fr)` in a `stack` instead
// of directly `1fr`, things go awry. To fix this, we now transparently detect
// h/v children.
#stack(dir: ltr, [a], 1fr, [b], 1fr, [c])
#stack(dir: ltr, [a], h(1fr), [b], h(1fr), [c])
--- issue-1240-stack-v-fr ---
#set page(height: 60pt)
#stack(
dir: ltr,
spacing: 1fr,
stack([a], 1fr, [b]),
stack([a], v(1fr), [b]),
)
--- issue-1918-stack-with-infinite-spacing ---
// https://github.com/typst/typst/issues/1918
#set page(width: auto)
#context layout(available => {
let infinite-length = available.width
// Error: 3-40 stack spacing is infinite
stack(spacing: infinite-length)[A][B]
})
|
|
https://github.com/UnnamedOrange/Typst-Templates | https://raw.githubusercontent.com/UnnamedOrange/Typst-Templates/main/article.typ | typst | The Unlicense | #let 字号 = (
初号: 42pt,
小初: 36pt,
一号: 26pt,
小一: 24pt,
二号: 22pt,
小二: 18pt,
三号: 16pt,
小三: 15pt,
四号: 14pt,
中四: 13pt,
小四: 12pt,
五号: 10.5pt,
小五: 9pt,
六号: 7.5pt,
小六: 6.5pt,
七号: 5.5pt,
小七: 5pt,
)
#let 字体 = (
仿宋: ("Times New Roman", "FangSong"),
宋体: ("Times New Roman", "SimSun"),
黑体: ("Times New Roman", "SimHei"),
楷体: ("Times New Roman", "KaiTi"),
代码: ("New Computer Modern Mono", "Times New Roman", "SimSun"),
)
// Typst hard-to-fix bug: https://github.com/typst/typst/issues/311
#let indent() = {
h(2em)
}
#let article(
title: "",
authors: (),
date: datetime.today(),
doc
) = {
// Set the document's metadata.
set document(title: title, author: authors)
// Set the document's basic default styles.
set page(paper: "a4", numbering: "1", number-align: center)
set text(字号.小四, font: 字体.宋体, lang: "zh")
set heading(numbering: "1.1 ")
set par(justify: true, first-line-indent: 2em)
show heading: it => {
it
v(0.5em)
}
// Set behavior of Chinese.
show strong: it => text(font: 字体.黑体, weight: "semibold", it.body)
show emph: it => text(font: 字体.楷体, style: "italic", it.body)
show raw: set text(font: 字体.代码)
// Make title.
{
pad(bottom: 1em, {
set text(字号.小一)
align(center)[
#block[*#title*]
]
set text(字号.小二)
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, author)),
)
align(center)[
#block[
#date.display("[year] 年 [month] 月 [day] 日")
]
]
})
}
doc
}
|
https://github.com/teamdailypractice/pdf-tools | https://raw.githubusercontent.com/teamdailypractice/pdf-tools/main/typst-pdf/thirukkural-oneline/001-tol.typ | typst | #set page("a4")
#set text(
font: "TSCu_SaiIndira",
size: 16pt
)
#set align(center)
திருக்குறள் - உற்சாகம் ஊட்டும் வரிகள் - தினமும்
\
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
உள்ளத்து அனையது, உயர்வு. \
அசாவாமை வேண்டும்;
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
என் உயர்வு, என்னிடம் உள்ளது. நல்ல எண்ணத்தோடு, நல்ல செயலை, நல்ல முயற்சியோடு நான் செய்தால், என் உயர்வு நிச்சயம். \
மன உறுதியோடு முயற்சி செய்வேன்.
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
முயற்சி, திருவினை ஆக்கும். \
முயற்சி, தன்-மெய்-வருத்தக் கூலி-தரும். \
பெருமை, முயற்சி தரும்.
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
என் நல்ல முயற்சி, நல்ல செயலை செய்து முடிக்க உதவும்.
செயலை செய்து முடிப்பது எனக்கு மகிழ்ச்சியைத் தரும்.
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
மனம்-தூய்மை, செய்-வினை தூய்மை; \
அகம்-தூய்மை, வாய்மையால் காணப்படும். \
மனத்துக்கண் மாசு-இலன் ஆதல்;
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
நல்லதை நினைப்பேன். \
நல்லதை பேசுவேன். உண்மையைப் பேசுவேன்.\
நல்லதை செய்வேன்.
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
அற்றார் அழி-பசி தீர்த்தல்! \
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
பசியால் வாடுபவர்க்கு/இல்லை என்று கேட்பவர்க்கு, என்னால் முடிந்ததை கொடுப்பேன்.
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
அழுக்காறு, அவா, வெகுளி, இன்னாச்-சொல்; \
நெடு-நீர், மறவி, மடி, துயில்; \
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
பொறாமை, பேராசை, கோபம், கடும் சொல் - இவைகளை முயற்சி செய்து தவிர்ப்பேன். \
காலம் தாழ்த்தி செய்தல், மறதி, சோம்பல், அளவுக்கு மீறிய தூக்கம் - இவைகளை முயற்சி செய்து தவிர்ப்பேன். \
#set align(left)
#set text(
font: "TSCu_SaiIndira",
size: 14pt
)
அற்றால், அளவு-அறிந்து உண்க! \
#set text(
font: "TSCu_SaiIndira",
size: 12pt
)
பசித்து சாப்பிடுவேன். அளவாக சாப்பிடுவேன். உடலுக்கு நலம் தருவதை சாப்பிடுவேன். \
உடலுக்கு நலம் தராத உணவை, தவிர்ப்பேன்.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/container_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test box sizing with layoutable child.
#box(
width: 50pt,
height: 50pt,
fill: yellow,
path(
fill: purple,
(0pt, 0pt),
(30pt, 30pt),
(0pt, 30pt),
(30pt, 0pt),
),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-04.typ | typst | Other | // Missing lvalue is not automatically none-initialized.
#{
let dict = (:)
// Error: 3-9 dictionary does not contain key "b" and no default value was specified
dict.b += 1
}
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/helper/tlp.typ | typst | MIT No Attribution | #let TLP = (
RED: (
text: "TLP:RED",
color: "#FF2B2B"
),
AMBER: (
text: "TLP:AMBER",
color: "#FFC000"
),
AMBER_STRICT: (
text: "TLP:AMBER+STRICT",
color: "#FFC000"
),
GREEN: (
text: "TLP:GREEN",
color: "#33FF00"
),
CLEAR: (
text: "TLP:CLEAR",
color: "#FFFFFF"
),
)
#let ShowTLP(sharing) = [
#box(height: 1.5em, fill: black, inset: .2em,
[
#set align(horizon)
#text(rgb(sharing.color), size: 12pt, weight: 700)[#sharing.text]
]
)
] |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/data-10.typ | typst | Other | // Test reading YAML data
#let data = yaml("test/assets/files/yaml-types.yaml")
#test(data.len(), 7)
#test(data.null_key, (none, none))
#test(data.string, "text")
#test(data.integer, 5)
#test(data.float, 1.12)
#test(data.mapping, ("1": "one", "2": "two"))
#test(data.seq, (1,2,3,4))
#test(data.bool, false)
#test(data.keys().contains("true"), false)
|
https://github.com/MilanR312/ugent_typst_template | https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/template/methods/title_page.typ | typst | MIT License | #import "globals.typ" : ublue
#let title_page(
title: none,
authors: (),
other_people: ()
) = {
// display the papers layout
align(
image("../images/faculteit.png", width: 60%),
left + top
)
align(
[
#set text(stroke: ublue, fill: ublue)
#title
],
left + horizon
)
align(
for author in authors [
#set text(16pt)
#if author.keys().contains("email") {
link("mailto:" + author.email, author.name)
} else {
author.name
}
#if author.keys().contains("student_number") {
set text(12pt)
[student number: #author.student_number]
}
],
left + bottom
)
v(3em)
align(
[
#set text(14pt)
#if other_people != none and other_people.promotors != none [
Promotors: #other_people.promotors.join(", ")
]
#if other_people != none and other_people.begeleiders != none [
Supervisors: #other_people.begeleiders.join(", ")
]
],
left + bottom
)
v(3em)
image("../images/ugent.png", width: 30%)
pagebreak()
} |
https://github.com/ufodauge/master_thesis | https://raw.githubusercontent.com/ufodauge/master_thesis/main/src/template/components/intro-section/index.typ | typst | MIT License | #import "toc-figure.typ": TocFigurePage
#import "toc.typ" : TocPage
#import "../common/page.typ" : Page
#import "../common/heading.typ": H1
#import "../../constants/page.typ": PAGE_NUMBERING_INTRO
#let IntroSection(
abstract : [],
acknowledgement: [],
) = [
#set page(numbering: PAGE_NUMBERING_INTRO)
#counter(page).update(1)
#show heading: it => [
#panic("Headings in the Abstract and Acknowledgements section are not defined.")
]
#show heading.where(level: 1): it => H1(it.body)
#Page[
= 概要
#abstract
]
#Page[
= 謝辞
#acknowledgement
]
#TocPage()
#TocFigurePage(
title : "図目次",
target: image,
)
#TocFigurePage(
title : "表目次",
target: table,
)
] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.1.2/src/styles.typ | typst | Apache License 2.0 | #import "util.typ"
#let default = (
root: (
fill: none,
stroke: black + 1pt,
radius: 1,
),
line: (
mark: (
size: .15,
angle: 45deg,
start: none,
end: none,
stroke: auto,
fill: none,
),
),
bezier: (
mark: (
size: .15,
angle: 45deg,
start: none,
end: none,
stroke: auto,
fill: none,
),
),
mark: (
size: .15,
angle: 45deg,
start: none,
end: none,
stroke: auto,
fill: none,
),
arc: (
mode: "OPEN",
),
content: (
padding: 0em,
frame: none,
fill: auto,
stroke: auto,
),
shadow: (
color: gray,
offset-x: .1,
offset-y: -.1,
),
)
/// Resolve the current style root
///
/// - current (style): Current context style (`ctx.style`).
/// - new (style): Style values overwriting the current style (or an empty dict).
/// I.e. inline styles passed with an element: `line(.., stroke: red)`.
/// - root (none, str): Style root element name.
/// - base (none, style): Base style. For use with custom elements, see `lib/angle.typ` as an example.
#let resolve(current, new, root: none, base: none) = {
if base != none {
if root != none {
let default = default
default.insert(root, base)
base = default
} else {
base = util.merge-dictionary(default, base)
}
} else {
base = default
}
let resolve-auto(hier, dict) = {
if type(dict) != dictionary { return dict }
for (k, v) in dict {
if v == auto {
for i in range(0, hier.len()) {
let parent = hier.at(i)
if k in parent {
v = parent.at(k)
if v != auto {
dict.insert(k, v)
break
}
}
}
}
if type(v) == dictionary {
dict.insert(k, resolve-auto((dict,) + hier, v))
}
}
return dict
}
let s = base.root
if root != none and root in base {
s = util.merge-dictionary(s, base.at(root))
} else {
s = util.merge-dictionary(s, base)
}
if root != none and root in current {
s = util.merge-dictionary(s, current.at(root))
} else {
s = util.merge-dictionary(s, current)
}
s = util.merge-dictionary(s, new)
s = resolve-auto((current, s, base.root), s)
return s
}
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap3/6_emergency_response.typ | typst | Other | #import "../../core/core.typ"
=== Emergency response
Despite lock-out/tag-out procedures and multiple repetitions of
electrical safety rules in industry, accidents still do occur. The vast
majority of the time, these accidents are the result of not following
proper safety procedures. But however they may occur, they still do
happen, and anyone working around electrical systems should be aware of
what needs to be done for a victim of electrical shock.
If you see someone lying unconscious or \"froze on the circuit,\" the
very first thing to do is shut off the power by opening the appropriate
disconnect switch or circuit breaker. If someone touches another person
being shocked, there may be enough voltage dropped across the body of
the victim to shock the would-be rescuer, thereby \"freezing\" two
people instead of one. Don\'t be a hero. Electrons don\'t respect
heroism. Make sure the situation is safe for you to step into, or else
you #emph[will] be the next victim, and nobody will benefit from your
efforts.
One problem with this rule is that the source of power may not be known,
or easily found in time to save the victim of shock. If a shock
victim\'s breathing and heartbeat are paralyzed by electric current,
their survival time is very limited. If the shock current is of
sufficient magnitude, their flesh and internal organs may be quickly
roasted by the power the current dissipates as it runs through their
body.
If the power disconnect switch cannot be located quickly enough, it may
be possible to dislodge the victim from the circuit they\'re frozen on
to by prying them or hitting them away with a dry wooden board or piece
of nonmetallic conduit, common items to be found in industrial
construction scenes. Another item that could be used to safely drag a
\"frozen\" victim away from contact with power is an extension cord. By
looping a cord around their torso and using it as a rope to pull them
away from the circuit, their grip on the conductor(s) may be broken.
Bear in mind that the victim will be holding on to the conductor with
all their strength, so pulling them away probably won\'t be easy!
Once the victim has been safely disconnected from the source of electric
power, the immediate medical concerns for the victim should be
respiration and circulation (breathing and pulse). If the rescuer is
trained in CPR, they should follow the appropriate steps of checking for
breathing and pulse, then applying CPR as necessary to keep the
victim\'s body from deoxygenating. The cardinal rule of CPR is to
#emph[keep going] until you have been relieved by qualified personnel.
If the victim is conscious, it is best to have them lie still until
qualified emergency response personnel arrive on the scene. There is the
possibility of the victim going into a state of physiological shock -- a
condition of insufficient blood circulation different from electrical
shock -- and so they should be kept as warm and comfortable as possible.
An electrical shock insufficient to cause immediate interruption of the
heartbeat may be strong enough to cause heart irregularities or a heart
attack up to several hours later, so the victim should pay close
attention to their own condition after the incident, ideally under
supervision.
#core.review[
- A person being shocked needs to be disconnected from the source of
electrical power. Locate the disconnecting switch/breaker and turn it
off. Alternatively, if the disconnecting device cannot be located, the
victim can be pried or pulled from the circuit by an insulated object
such as a dry wood board, piece of nonmetallic conduit, or rubber
electrical cord.
- Victims need immediate medical response: check for breathing and
pulse, then apply CPR as necessary to maintain oxygenation.
- If a victim is still conscious after having been shocked, they need to
be closely monitored and cared for until trained emergency response
personnel arrive. There is danger of physiological shock, so keep the
victim warm and comfortable.
- Shock victims may suffer heart trouble up to several hours after being
shocked. The danger of electric shock does not end after the immediate
medical attention.
]
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/ea2724-ai_hw/hw7.typ | typst | == HW7
Due 2024.05.12
#import "@preview/diagraph:0.2.1": *
#let ans(it) = [
#pad(1em)[
#text(fill: blue)[
#it
]
]
]
#show math.equation: it => [
#math.display(it)
]
#show image: it => align(center, it)
=== Question 13.15
在一年一度的体检之后,医生告诉你一些坏消息和一些好消息。坏消息是你在一种严重疾病的测试中结果呈阳性,而这个测试的准确度为 $99 percent$ (即当你确实患这种病时,测试结果为阳性的概率为 $0.99$;而当你未患这种疾病时测试结果为阴性的概率也是 $0.99$)。好消息是,这是一种罕见的病,在你这个年龄段大约 $10000$ 人中才有 $1$ 例。为什么“这种病很罕见”对于你而言是一个好消息?你确实患有这种病的概率是多少?
#ans[
按照题目描述, 我们可以将所有可能的检测成果总结如下:
#table(
columns: (auto, auto, auto),
fill: (x, y) => {
if (x == 0 or y == 0) and not (x == 0 and y == 0) {
blue.lighten(80%)
}
if (x == 0 and y == 0) {
blue.lighten(60%)
}
},
stroke: blue,
align: center,
[], [阳性], [阴性],
[患病: $1\/10000$], [$1\/10000 times 99\/100$], [$1\/10000 times 1\/100$],
[未患病: $9999\/10000$], [$9999\/10000 times 1\/100$], [$9999\/10000 times 99\/100$],
)
在已知我检测结果为阳性的情况下, 我确实患病的概率为:
$
(1\/10000 times 99\/100) / (1\/10000 times 99\/100 + 9999\/10000 times 1\/100) approx 0.0098 < 1%
$
如果这并不是罕见病, 例如每$100$人就有$1$人患病, 那么在阳性检测结果下我确实患病的概率将会是:
$
(1\/100 times 99\/100) / (1\/100 times 99\/100 + 99\/100 times 1\/100) = 0.5
$
从这个角度说, 这种病很罕见对于我而言是一个好消息.
]
=== Question 13.18
假设给你一只袋子,装有个无偏差的硬币,并且告诉你其中$n$个硬币是正常的,一面是正面而另一面是反面。不过剩余$1$枚硬币是伪造的,它的两面都是正面。
+ 假设你把手伸进口袋均匀随机地取出一枚硬币,把它抛出去,硬币落地后正面朝上。那么你取出伪币的(条件)概率是多少?
#ans[
$
&P("fake") = 1 / n &quad& P("normal") = 1 - 1 / n&\
&P("head"|"fake") = 1 &quad& P("head"|"normal") = 1 / 2&\
&P("tail"|"fake") = 0 &quad& P("tail"|"normal") = 1 / 2&\
$
$
=> P("fake"|"head") = (P("head"|"fake")P("fake")) / P("head") = (1\/n) / (1\/n + (1-1\/n)\/2) = 2 / (n+1)
$
]
+ 假设你不停地抛这枚硬币,一共抛了$k$次,而且看到$k$次正面向上。那么你取出伪币的条件概率是多少?
#ans[
$
P("fake"|"head"^k) = (P("head"^k|"fake")P("fake")) / P("head"^k) = (1^k dot 1\/n) / (1^k dot 1\/n + (1-1\/n) dot (
1\/2
)^k) = (2^k) / (2^k+n-1)
$
]
+ 假设你希望通过把取出的硬币抛$k$次的方法来确定它是不是伪造的。如果抛次后都是正面朝上,那么决策过程返回 fake(伪造),否则返回 normal(正常)。这个过程发生错误的(无条件)概率是多少?
#ans[
$
P("WA") = P("normal" and "head"^k) = (1-1 / n) dot (1 / 2)^k
$
]
=== Question 13.21
(改编自Pearl (1988)的著述.) 假设你是雅典一次夜间出租车肇事逃逸的交通事的目击者。雅典所有的出租车都是蓝色或者绿色的。而你发誓所看见的肇事出租车是蓝色的。大量测试表明,在昏暗的灯光条件下,区分蓝色和绿色的可靠度为 $75 percent$。
+ 有可能据此计算出肇事出租车最可能是什么颜色吗?(提示:请仔细区分命题“肇事车是蓝色的”和命题“肇事车看起来是蓝色的”。)
#ans[
不能. 我们知道肇事车看起来的颜色, 但是不知道真实颜色的概率分布. 例如, 如果绿色出租车的数量远远多于蓝色出租车, 那么即使看起来是蓝色的车辆的概率也可能很高.(与上面罕见病的例子类似)
]
+ 如果你知道雅典的出租车 $10$ 辆中有 $9$ 辆是绿色的呢?
#ans[
也与上面罕见病类似, 我们整理出所有可能的情况如下:
#table(
columns: (auto, auto, auto),
fill: (x, y) => {
if (x == 0 or y == 0) and not (x == 0 and y == 0) {
blue.lighten(80%)
}
if (x == 0 and y == 0) {
blue.lighten(60%)
}
},
stroke: blue,
align: center,
[], [看起来蓝色], [看起来绿色],
[真实蓝色], [$1\/10 times 3\/4$], [$1\/10 times 1\/4$],
[真实绿色], [$9\/10 times 1\/4$], [$9\/10 times 3\/4$],
)
因此在 「看起来是蓝色」的前提下, 真实是蓝色的概率为: $1\/4$, 真实是绿色的概率为 $3\/4$. 肇事车最可能是绿色的.
]
=== Question 13.22
文本分类是基于文本内容将给定的一个文档分类成固定的几个类中的一类。朴素贝叶斯模型经常用于这个问题。在朴素贝叶斯模型中,查询(query)变量是这个文档的类别,而结果(effect)变量是语言中每个单词的存在与否;假设文档中单词的出现是独立的,单词的出现频率由文档类别决定。
+ 给定一组已经被分类的文档,准确解释如何构造这样的模型。
#ans[
考虑一组已经分类的文档, $C = {C_i}$, 对于每个单词 $w_j$, 我们可以计算出在每个类别下的概率 $P(w_j|C_i)$.
我们再计算每个类别的概率 $P(C_i)$, 以及每个单词的概率 $P(w_j)$.
]
+ 准确解释如何分类一个新文档。
#ans[
考虑一篇新文档含有单词 $w_1 ,dots.c, w_k$, 分别计算在各个分类下, 这些单词出现的概率:
$
P(C_i|w_1,dots,w_k) &= (P(w_1, dots.c, w_k) dot P(C_i)) / (P(w_1, dots.c, w_k))\
&= (limits(product)_i P(w_j|C_i) dot P(C_i)) / (P(w_1, dots.c, w_k))
$
无需计算分母, 只需比较各个分类下的概率即可.
]
+ 题目中的条件独立性假设合理吗?请讨论。
#ans[
这个假设并不合理. 例如, 在一篇关于机器学习的文章中, 出现了 "机器" 这个词, 那么 "学习" 这个词出现的概率就会变得很大. 这两个词并不是独立的.
]
=== Question 14.12
两个来自世界上不同地方的宇航员同时用他们自己的望远镜观测了太空中某个小区域内恒星的数目 $N$。他们的测量结果分别为 $M_1$ 和 $M_2$。通常,测量中会有不超过 $1$ 颗恒星的误差,发生错误的概率 $e$ 很小。每台望远镜可能出现(出现的概率$f$ 更小一些)对焦不准确的情况(分别记作 $F_1$ 和 $F_2$),在这种情况下科学家会少数三颗甚至更多的恒星(或者说,当 $N$ 小于 $3$ 时,连一颗恒星都观测不到)。考虑图14.22所示的三种贝叶斯网络结构。
#align(center)[
#table(
columns: (auto, auto, auto),
stroke: none,
column-gutter: 1em,
[
#raw-render(```dot
digraph {
rankdir=TD;
node [shape=circle];
F_1, F_2, M_1, M_2, N;
F_1 -> M_1; F_2 -> M_2;
M_1 -> N; M_2 -> N;
}
```)
],
[
#raw-render(```dot
digraph {
rankdir=TD;
node [shape=circle];
F_1, F_2, M_1, M_2, N;
F_1 -> M_1; F_2 -> M_2;
N -> M_1; N -> M_2;
}
```)
],
[
#raw-render(```dot
digraph {
layout=neato;
rankdir=TD;
node [shape=circle];
F_1 [pos="0,0!"];
F_2 [pos="1.5,0!"];
M_1 [pos="0,2!"];
M_2 [pos="1.5,2!"];
N [pos="0.5,1"];
M_1 -> F_1; M_1 -> M_2; M_1 -> N;
N -> F_1; N -> F_2; M_2 -> N; M_2 -> F_2;
}
```)
],
[
(i)
],
[
(ii)
],
[
(iii)
],
)
]
+ 这三种网络结构哪些是对上述信息的正确(但不一定高效)表示?
#ans[
(ii), (iii) 正确;
考虑到 $ P(N mid(|)M_1)!=P(N|M_1,F_1) $ 所以 $F_1$ 与 $M$ 应该同时连接到 $N$, (i) 不正确.
]
+ 哪一种网络结构是最好的?请解释。
#ans[
(ii), 关系少, 更紧致.
]
+ 当 $N in {1,2,3}, quad M_1 in {0,1,2,3,4}$时,请写出 $P(M_1 mid(|) N)$ 的条件概率表。概率分布表里的每个条目都应该表达为参数$e$和/或$f$的一个函数。
#ans[
$
P(M_1 mid(|) N) &= P(M_1 mid(|) N, F_1) P(F_1 mid(|) N) + P(M_1 mid(N), not F_1) P(not F_1 mid(|) N)\
&= P(M_1 mid(|) N, F_1) P(F_1) + P(M_1 mid(N), not F_1) P(not F_1)\
$
#table(
columns: (auto, auto, auto, auto, auto, auto),
align: center,
fill: (x, y) => {
if (x == 0 or y == 0) and not (x == 0 and y == 0) {
blue.lighten(80%)
}
if (x == 0 and y == 0) {
blue.lighten(90%)
}
},
stroke: blue,
[
$P(M_1 mid(|) N)$
],
[
$M_1 = 0$
],
[
$M_1 = 1$
],
[
$M_1 = 2$
],
[
$M_1 = 3$
],
[
$M_1 = 4$
],
[
$N = 1$
],
[
$f+e(1-f)$
],
[
$(1-2e)(1-f)$
],
[
$e(1-f)$
],
[
#set text(fill: red)
$0$
],
[
$0$
],
[
$N = 2$
],
[
$f$
],
[
#set text(fill: green)
$e(1-f)$
],
[
$(1-2e)(1-f)$
],
[
#set text(fill: green)
$e(1-f)$
],
[
$0$
],
[
$N = 3$
],
[
$f$
],
[
#set text(fill: red)
$0$
],
[
$e(1-f)$
],
[
$(1-2e)(1-f)$
],
[
$e(1-f)$
],
)
]
+ 假设 $M_1 = 1, quad M_2 = 3$。如果我们假设 $N$ 取值上没有先验概率约束,可能的恒星数目是多少?
#ans[
#table(
columns: (auto, auto, auto, auto, auto, auto, auto),
align: center,
fill: (x, y) => {
if (x == 0 or y == 0) and not (x == 0 and y == 0) {
blue.lighten(80%)
}
if (x == 0 and y == 0) {
blue.lighten(90%)
}
},
stroke: blue,
[
$P(M_1 mid(|) N)$
],
[
$M_1 = 0$
],
[
$M_1 = 1$
],
[
$M_1 = 2$
],
[
$M_1 = 3$
],
[
$M_1 = 4$
],
[
$dots.c$
],
[
$N = 4$
],
[
$f$
],
[
#set text(fill: green)
$f$
],
[
$0$
],
[
#set text(fill: green)
$e(1-f)$
],
[
$(1-2e)(1-f)$
],
[
$dots.c$
],
[
$N=5$
],
[
$f$
],
[
$f$
],
[
$f$
],
[
#set text(fill: red)
$0$
],
[
$e(1-f)$
],
[
$dots.c$
],
)
#let color_r(x) = text(fill: red, $#x$)
$
P(M = 3 mid(|) N = 0) = 0 &quad& => &quad& N!=0\
P(M = 3 mid(|) N = 1) = 0 &quad& => &quad& N!=1\
P(M = 1 mid(|) N = 3) = 0 &quad& => &quad& N!=3\
P(M = 1 mid(|) N = 5) = 0 &quad& => &quad& N!=5\
$
$P(M = i mid(|) N = n) > 0 quad forall i = 1,3; n = 2,4$ 已经在表中标记出来了. (考虑到 $f approx 0$ 时=, 我们近似地认为每行加起来为 $1$. )
考虑 $n >= 6$ 时, $P(M = 1 mid(|) N = n) = P(M = 3 mid(|) N = n) = f > 0$.
因此可能的 $n$ 的取值为 $2,4$ 或 $n>=6$
]
+ 在这些观测结果下,最可能的恒星数目是多少?解释如何计算这个数目,或者,如果不可能计算,请解释还需要什么附加信息以及它将如何影响结果。
#ans[
缺少 $N$ 的先验概率分布, 无法计算最可能的恒星数目.
考虑我们提供一个分布: $P(N=n) = p_n quad forall n = 2,4,6,7, dots$
$
&P(N=2, M_1 = 1, M_2 = 3) &=& p_2 e^2(1-f)^2\
&P(N=4, M_1 = 1, M_2 = 3) &=& p_4 e f(1-f)^2\
(n>=6) quad &P(N=n, M_1 = 1, M_2 = 3) &=& p_n f^2\
$
计算出并比较大小即可, 取 $n="argmax"_n P(N=n, M_1 = 1, M_2 = 3)$.
]
=== Question 14.13
考虑 图14.22(ii) 的网络,假设两个望远镜完全相同。$N in {1,2,3}$,$M_1, M_2 in {0,1,2,3,4}$,CPT表和习题14.12所描述的一样。使用枚举算法(图14.9)计算概率分布 $P(N mid(|) M_1=1,M_2 = 2)$。
#ans[
$
cal(P)(N mid(|) M_1=2, M_2=2) &= alpha sum_(f_1,f_2) cal(P)(f_1, f_2, N, M_1=2,M_2=2)\
&=alpha sum_(f_1,f_2) P(f_1) P(f_2) cal(P)(N) P(M_1=2,M_2=2)
$
考虑到 $M_1=M_2=2$, 只有 $F_1=F_2="false"$ 时才能满足, 因此:
$
cal(P)(N mid(|) M_1=2, M_2=2) &= alpha (1-f)^2 angle.l p_1, p_2, p_3 angle.r angle.l e, (
1-2e
), e angle.r angle.l e, (1-2e), e angle.r\
&= alpha^' angle.l p_1 e^2, p_2(1-2e)^2, p_3 e^2 angle.r
$
] |
|
https://github.com/domoritz/tvcg-journal-typst | https://raw.githubusercontent.com/domoritz/tvcg-journal-typst/main/lib.typ | typst | MIT No Attribution | // Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
#let serif-font = "Liberation Serif"
#let sans-serif-font = "Liberation Sans"
// This function gets your whole document as its `body` and formats
// it as an article in the style of the TVCG.
#let tvcg(
// The paper's title.
title: [Paper Title],
// An array of authors. For each author you can specify a name,
// department, organization, location, and email.
// Everything but the name is optional.
authors: (),
// The paper's abstract.
abstract: none,
// Teaser image path and caption
teaser: (),
// A list of index terms to display after the abstract.
index-terms: (),
// The article's paper size. Also affects the margins.
paper-size: "us-letter",
// The result of a call to the `bibliography` function or `none`.
bibliography: none,
// The paper's content.
body
) = {
// Set document metadata.
set document(title: title, author: authors.map(author => author.name))
// Set the body font.
set text(font: serif-font, size: 9pt)
// Configure the page.
set page(
paper: paper-size,
margin: (
top: 54pt, // 0.75in
bottom: 45pt, // 0.625in
inside: 54pt, // 0.75in
outside: 45pt // 0.625in
)
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)")
show math.equation: set block(spacing: 0.65em)
// Configure appearance of equation references
show ref: it => {
if it.element != none and it.element.func() == math.equation {
// Override equation references.
link(it.element.location(), numbering(
it.element.numbering,
..counter(math.equation).at(it.element.location())
))
} else {
// Other references as usual.
it
}
}
// Configure lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// Configure headings.
set heading(numbering: "1.1.1.")
show heading: it => locate(loc => {
// Find out the final number of the heading counter.
let levels = counter(heading).at(loc)
let deepest = if levels != () {
levels.last()
} else {
1
}
set text(font: sans-serif-font, size: 9pt)
if it.level == 1 [
// First-level headings are centered smallcaps.
// We don't want to number the acknowledgments section.
#let is-ack = it.body in ([Acknowledgments], [Acknowledgements])
#show: smallcaps
#v(20pt, weak: true)
#if it.numbering != none and not is-ack {
numbering("1.", deepest)
h(7pt, weak: true)
}
#if it.body.has("text"){
for letter in it.body.text{
if letter == upper(letter) {
set text(size: 9pt)
letter
} else {
set text(size: 7pt)
upper(letter)
}
}
}
// *#it.body*
#v(13.75pt, weak: true)
] else if it.level == 2 [
// Second-level headings are run-ins.
#set par(first-line-indent: 0pt)
#set text(style: "italic")
#v(10pt, weak: true)
#if it.numbering != none {
numbering("1.", deepest)
h(7pt, weak: true)
}
*#it.body*
#v(10pt, weak: true)
] else [
// Third level headings are run-ins too, but different.
#if it.level == 3 {
numbering("1)", deepest)
[ ]
}
_#(it.body):_
]
})
// Display the paper's title.
v(3pt, weak: true)
align(center, text(18pt, title, font: sans-serif-font))
v(23pt, weak: true)
// Display the authors list.
let and-comma = if authors.len() == 2 {" and "} else {", and "}
align(center,
text(10pt, font: sans-serif-font, authors.map(author => {
author.name
if "orcid" in author and author.orcid != "" {
link("https://orcid.org/" + author.orcid)[#box(height: 1.1em, baseline: 13.5%)[#image("assets/orcid.svg")]]
}
} ).join(", ", last: and-comma)
)
)
v(50pt, weak: true)
block(inset: (left: 24pt, right: 24pt), [
// Insert teaser image
#figure(
teaser.image,
caption: teaser.caption,
) <teaser>
#v(20pt, weak: true)
// Display abstract and index terms.
#(if abstract != none [
#set par(justify: true)
*Abstract*---#abstract
#if index-terms != () [
*Index terms*---#index-terms.join(", ")
]
]
)
]
)
v(10pt, weak: true)
align(center, box(width: 40%)[#image("assets/diamondrule.svg")])
v(15pt, weak: true)
// Start two column mode and configure paragraph properties.
show: columns.with(2, gutter: 12.24pt) // 0.17in
set par(justify: true, first-line-indent: 1em)
show par: set block(spacing: 0.65em)
// Display the email address and manuscript info.
place(left+bottom, float: true, block(
width: 100%,[
#align(center, line(length: 50%))
#set text(style: "italic", size: 7.5pt, font: serif-font)
#set list(indent: 0pt, body-indent: 5pt)
#for author in authors [
- #author.name is with #author.organization. #box(if "email" in author [E-mail: #author.email.])
]
Manuscript received DD MMM. YYYY; accepted DD MMM. YYYY.
Date of Publication DD MMM. YYYY; date of current version DD MMM. YYYY.
For information on obtaining reprints of this article, please send e-mail to: <EMAIL>`@`<EMAIL>.
Digital Object Identifier: xx.xxxx/TVCG.YYYY.xxxxxxx
]
)
)
// Set the body font.
set text(font: serif-font, size: 9pt)
// Display the paper's contents.
body
// Display bibliography.
if bibliography != none {
show std-bibliography: set text(8pt)
set std-bibliography(title: text(10pt)[References], style: "ieee")
bibliography
}
}
|
https://github.com/vitto4/ttuile | https://raw.githubusercontent.com/vitto4/ttuile/main/DOC.FR.md | markdown | MIT License | # 📚 Documentation
### `ttuile`
C'est la fonction principale, le point d'entrée du template. Elle doit être appelée en début de document, comme décrit dans [README.FR.md > Utilisation](https://github.com/vitto4/ttuile/blob/main/README.FR.md#-utilisation).
Si le compte rendu n'est pas réalisé pour l'INSA Lyon, le logo peut être remplacé ou supprimé avec l'argument `logo`.
### `annexe`
Fonction utilisée pour définir un objet `annexe`. Cet objet - étant un `dictionary` - sera ensuite utilisé par la fonction `afficher-annexes`.
| Argument | Valeur par défaut | Type | Description |
|:--------:|:-----------------:|:----:|:------------|
| `titre` | `none` | `content?` | Titre de l'annexe. |
| `reference` | `none` | `label` | Label/référence à utiliser dans le corps du rapport pour se référer à l'annexe. |
Un seul argument positionnel est accepté, étant le corps de l'annexe.
**Exemple :**
```typ
#let Annexe-1 = annexe(
titre: [Titre de l'annexe],
reference: <référence-à-utiliser>,
)[
Corps de l'annexe, du texte, des images, des titres, ...
]
```
La `reference` peut ensuite s'utiliser normalement dans le reste du rapport : `@référence-à-utiliser`.
**Remarque :**
- Comme les titres des annexes sont en réalité des titres de niveau `1` stylisés pour l'occasion, il n'est actuellement possible d'utiliser que des titres de niveau `2` ou plus dans le corps des annexes.
### `afficher-annexes`
Cette fonction prend en argument une liste d'objets `annexe` définis à l'aide de la fonction `annexe`, et les affiche avec une mise en page appropriée.
| Argument | Valeur par défaut | Type | Description |
|:--------:|:-----------------:|:----:|:------------|
| `annexes` | `none` | `list<dictionary>` | Liste de dictionnaires générés avec la fonction `annexe`. |
| `table` | `true` | `bool` | Permet d'afficher ou de masquer la table des annexes. |
| `saut-page-apres-table` | `false` | `bool` | Force un saut de page immédiatement après l'éventuelle table des annexes. |
**Exemple :**
```typ
#afficher-annexes(
annexes: (Annexe-1, Annexe-2,),
table: true,
saut-page-apres-table: false,
)
```
### `equation-anonyme`
Simple raccourci pour afficher une équation sans la numéroter.
**Exemple :**
```typ
#equation-anonyme(
$
"Une équation"
$
)
```
### `figure-emboitee`
Fait en sorte que la légende de la figure n'en dépasse pas la largeur.
```typ
figure-emboitee(
figure(
image("img.png"),
caption: [Une figure.]
)
reference: <référence-à-utiliser>,
)
``` |
https://github.com/Stautaffly/typ | https://raw.githubusercontent.com/Stautaffly/typ/main/小技巧.typ | typst |
#set text(size: 15pt)
= 等比\*等差数列求和办法
令 $T_n=("An"+B)q^n$ 其部分和$ S_n=(A+B)q+(2A+B)q^2+dots+("An"+B)q^n $
法一:错位相减\
$ S_n=&(A+B)q+(2A+B)q^2+dots+("An"+B)q^n \
q S_n=& (A+B)q^2+dots+(A n+B-A)q^(n)+ ("An"+B)q^(n+1)
$
两式相减得$ S_n=((A+B)q+A q^2(1-q^(n-1))/(1-q)-(A n+B)q^(n+1))/(1-q) $
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/foundations/content.typ | typst | --- content-at-default ---
// Test .at() default values for content.
#test(auto, [a].at("doesn't exist", default: auto))
--- content-field-syntax ---
// Test fields on elements.
#show list: it => {
test(it.children.len(), 3)
}
- A
- B
- C
--- content-field-missing ---
// Error: 25-28 heading does not have field "fun"
#show heading: it => it.fun
= A
--- content-fields ---
// Test content fields method.
#test([a].fields(), (text: "a"))
#test([a *b*].fields(), (children: ([a], [ ], strong[b])))
--- content-fields-mutable-invalid ---
#{
let object = [hi]
// Error: 3-9 cannot mutate fields on content
object.property = "value"
}
--- content-field-materialized-table ---
// Ensure that fields from set rules are materialized into the element before
// a show rule runs.
#set table(columns: (10pt, auto))
#show table: it => it.columns
#table[A][B][C][D]
--- content-field-materialized-heading ---
// Test it again with a different element.
#set heading(numbering: "(I)")
#show heading: set text(size: 11pt, weight: "regular")
#show heading: it => it.numbering
= Heading
--- content-field-materialized-query ---
// Test it with query.
#set raw(lang: "rust")
#context query(<myraw>).first().lang
`raw` <myraw>
--- content-fields-complex ---
// Integrated test for content fields.
#let compute(equation, ..vars) = {
let vars = vars.named()
let f(elem) = {
let func = elem.func()
if func == text {
let text = elem.text
if regex("^\d+$") in text {
int(text)
} else if text in vars {
int(vars.at(text))
} else {
panic("unknown math variable: " + text)
}
} else if func == math.attach {
let value = f(elem.base)
if elem.has("t") {
value = calc.pow(value, f(elem.t))
}
value
} else if elem.has("children") {
elem
.children
.filter(v => v != [ ])
.split[+]
.map(xs => xs.fold(1, (prod, v) => prod * f(v)))
.fold(0, (sum, v) => sum + v)
}
}
let result = f(equation.body)
[With ]
vars
.pairs()
.map(p => $#p.first() = #p.last()$)
.join(", ", last: " and ")
[ we have:]
$ equation = result $
}
#compute($x y + y^2$, x: 2, y: 3)
--- content-label-has-method ---
// Test whether the label is accessible through the `has` method.
#show heading: it => {
assert(it.has("label"))
it
}
= Hello, world! <my-label>
--- content-label-field-access ---
// Test whether the label is accessible through field syntax.
#show heading: it => {
assert(str(it.label) == "my-label")
it
}
= Hello, world! <my-label>
--- content-label-fields-method ---
// Test whether the label is accessible through the fields method.
#show heading: it => {
assert("label" in it.fields())
assert(str(it.fields().label) == "my-label")
it
}
= Hello, world! <my-label>
--- content-fields-unset ---
// Error: 10-15 field "block" in raw is not known at this point
#raw("").block
--- content-fields-unset-no-default ---
// Error: 2-21 field "block" in raw is not known at this point and no default was specified
#raw("").at("block")
--- content-try-to-access-internal-field ---
// Error: 9-15 hide does not have field "hidden"
#hide[].hidden
|
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/SYE/docs/5-EtatsTransition%26Threads/etats-transition-threads.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Etats transistions et Threads
],
lesson: "SYE",
chapter: "5 - Etats transition et Threads",
definition: "Definition",
col: 1,
doc,
)
= Etats et transitions
#image("/_src/img/docs/image copy 141.png")
Voici une explication de chacun des états d'un processus mentionnés dans le texte :
== État New
- Description : Un processus est dans l'état *new* lorsqu'il est en phase d'initialisation. Cela signifie qu'il a été créé, mais pas encore totalement configuré pour être exécuté.
- Caractéristiques : Dans cet état, le PCB (Process Control Block) du processus existe, mais toutes les structures de données nécessaires ne sont pas encore initialisées. Le processus n'est pas prêt à être ordonnancé (c'est-à-dire, il ne peut pas encore être exécuté par le processeur).
== État Ready
- Description : Le processus est dans l'état *ready* lorsqu'il est prêt à être exécuté mais qu'il ne peut pas le faire en raison de la disponibilité limitée du processeur.
- Caractéristiques : À ce stade, toutes les structures de données nécessaires sont initialisées, et le processus est en attente de l'ordonnanceur, qui décidera quand lui accorder du temps CPU. Un processus peut passer de l'état *new* à *ready* après son initialisation.
== État Running
- Description : Dans cet état, le processus est effectivement en cours d'exécution sur le processeur.
- Caractéristiques : Le processus a été sélectionné par l'ordonnanceur et utilise le CPU pour exécuter ses instructions. Il peut passer à un autre état en fonction d'événements (comme une interruption ou une demande de ressource).
== État Waiting
- Description : Un processus entre dans l'état *waiting* lorsqu'il attend une ressource nécessaire pour continuer son exécution, comme l'accès à un fichier, à une entrée/sortie, ou à une autre ressource logique ou physique.
- Caractéristiques : Dans cet état, le processus ne peut pas être exécuté. Lorsqu'il obtient la ressource qu'il attendait, il doit d'abord passer par l'état *ready* avant de pouvoir redevenir *running*.
== État Zombie
- Description : Cet état se produit lorsqu'un processus a terminé son exécution, mais son PCB est encore présent dans le système.
- Caractéristiques : Un processus zombie ne peut plus être ordonnancé et reste dans cet état pour permettre au processus parent de récupérer son code de sortie. Le processus parent peut alors lire les informations sur l'état du processus terminé (générées par l'appel système `exit()`) avant de libérer le PCB et de supprimer définitivement le processus du système.
Ces états permettent au système d'exploitation de gérer efficacement les processus, en assurant une utilisation optimale des ressources et en maintenant un contrôle sur l'exécution des programmes.
#image("/_src/img/docs/image copy 143.png")
En principe, il existe dans le noyau une file de processus par état (à l'exception de l'état running auquel peut être associé plusieurs processus que si la machine est multi-cœur). Les processus dans l'état ready sont des processus prêts à être ordonnancés. Les mouvements de cette file dépendra en particulier de l'ordonnanceur.
= Définition d'un thread
#image("/_src/img/docs/image copy 142.png")
== Accès aux Ressources
- Contexte d'Exécution : Un thread représente un contexte d'exécution au sein d'un processus et doit avoir accès à toutes les ressources allouées à ce processus, comme la mémoire et d'autres ressources logiques.
- Espace d'Adressage : Tous les threads d'un même processus partagent le même espace d'adressage. Cela signifie qu'ils ont accès aux différentes sections du processus, comme le code, les données dans les sections data et bss, et le tas (heap).
- Pile : Chaque thread a sa propre pile, qui fait partie de son contexte d'exécution. Cela permet à chaque thread de gérer ses propres variables locales et ses appels de fonction.
== Exemple de Threads
Un exemple illustratif est le traitement de texte. Lorsqu'un utilisateur saisit du texte, le traitement de texte peut lancer un correcteur orthographique en arrière-plan pour souligner les fautes. Les deux tâches — la saisie et le correcteur — sont indépendantes, mais elles doivent accéder au même contenu.
== Gestion des Accès Concurrents
Les deux threads associés à ces tâches doivent gérer les accès concurrents au contenu partagé. Pour ce faire, ils peuvent utiliser des objets de synchronisation, tels que des mutex ou des sémaphores, afin de s'assurer que les données sont correctement gérées sans conflit.
#colbreak()
== Thread Control Break (TCB)
#image("/_src/img/docs/image copy 144.png")
Le TCB est une structure de données contenant les informations propres au thread, comme son état, sa priorité, le pointeur de pile, etc. Il est *fortement* sollicité lors d'un changement de contexte.
Par ailleurs, on remarque que le TCB est beaucoup plus petit que le PCB ; il ne contient
aucune information particulière concernant les ressources qui pourraient être utilisées
par le thread, comme des fichiers ouverts ou d'autres objets de synchronisation ou de
communication.
= Librairie de threads POSIX
- Portable Operating System Interface (X pour uniX/linuX/macosX)
- API standardisée (IEEE 1003.1c) largement répandue pour les threads
- Création/terminaison
- Synchronisation
- Accès concurrents
- Supporté par Windows (sous-système POSIX)
== Creation d'un thread
```c
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *, void *(*start_routine) (void *), void *arg);
voicd start_routine(void *);
```
== Sychronisation d'un thread
```c
int pthread_join(pthread_t thread, void **retval)
```
== Terminaison d'un thread
Retour de fonction (pas de valeur particulière à transmettre)
```c
void pthread_exit(void *retval);
```
= Exécution de threads
|
|
https://github.com/yingziyu-llt/blog | https://raw.githubusercontent.com/yingziyu-llt/blog/main/archived/Linear-Algebra-C3.typ | typst | #set document(title:"线性映射",date: auto )
#set page(margin: (
top: 0cm,
bottom: 0cm,
x: 0cm,
))
#set text(size: 16pt)
== 线性映射的定义
*Definition:*
一个映射 $T : V -> W$ 一定是线性的当且仅当它满足以下两个性质:
+ 可加性(additivity): $T(x + y) = T(x) + T(y)$
+ 齐次性(homogeneity): $T(c v) = c T(v)$
我们记作$T v$为一个线性映射(Linear Mapping),称$L(V, W)$为从$V$到$W$的线性映射. 显然其保持0元$T(0) = 0$
*Example*
零映射(zero) $0 in L(V,W),0v=0$
恒等(identity) $I in L(V,W),I v=v$
微分(differential) $D in L(V,W),D v = v'$
积分(integral) $I in L(V,W),I v(x)= integral_0^1 v(x) dif x$
*Theorem*
$V$的基为$v_1,v_2,dots,v_n$;$W$的基为$u_1,u_2,dots,u_n$,存在唯一的线性映射$T$,使得$T v_i = u_i$
证明思路:围绕着$forall u in W,exists c_1,c_2,dots,c_n$,只用构造$T(c_1 v_1 + c_2 v_2 + dots + c_n v_n) = c_1 u_1 + c_2 u_2 + dots + c_n u_n$即可.
== 线性映射的线性性
为了寻找其线性性,我们要先定义$L(V,W)$上的加法和数乘
*Definition*
定义$S,T in L(V,W)$
定义$(S+T)(v) = S(v) + T(v)$,$(lambda S)(v) = lambda S(v)$
于是容易看出,$L(V,W)$是一个线性空间.
*Definition*
定义线性映射的乘法$S in L(U,V),T in L(V,W)$,那么$(S T)(v) = S(T(v))$
*Theorem*
乘法的性质
+ 结合律$T_1T_2T_3 = T_1(T_2T_3)$
+ 幺元$I T = T I = T$,$I$是$L(V,V)$上的恒等映射
+ 分配率$(S_1 + S_2)(T) = S_1 T + S_2 T$,$S(T_1 + T_2) = S T_1 + S T_2$
需要注意的是,线性映射的乘法不具有交换律.
== 零空间和值域
*Definition*
零空间(null space) $T in L(V,W)$,$T$的零空间就是$V$的一个子集,使得${v in V : T v = 0}$,记作$"null" T$,也叫做$T$的核空间(kernel space),记作$ker T$
单射(injective) $T in L(V,W),T v = T w => v = w$ 这样的$T$称为一个单射.
*Theorem*
+ $ker T$是$V$的一个子空间
+ $T$是单射$<=>$$ker T = {0}$
*Proof*
对于命题1:取$v_1,v_2 in ker T$,$T(v_1 + v_2) = T v_1 + T v_2 = 0 + 0 = 0$;$T(lambda v) = lambda T v = 0$
对于命题2:$\"=>\"$由于$T$为单射,所以$T(v) = T(0) = 0 => v = 0$,于是$ker T = {0}$
$\"<==\"$ $T(v_1) = T(v_2) => T(v_1) - T(v_2) = 0 =>T(v_1 - v_2) = 0$,又$ker T = {0}$,$=> v_1 - v_2 = 0 => v_1 = v_2$
*Definition*
值域(range):对于一个函数$T : V -> W$,$T$的值域就是$W$的一个子集${T v}$,记作$"range" T$,也叫函数的像空间(image),记作$im T$.
*Theorem*
$im T$是$V$的一个子空间
*Proof*
设$w_1,w_2 in im T$,那么$w = T(v_1 + v_2) = T v_1 + T v_2 = w_1 + w_2 in im T$,$T(lambda v) = lambda T v = lambda w in im T$
*Definition*
满射(surjective):如果某个映射$T:V->W$的像空间等于$W$,那么称$T$是一个满射.
*Theorem*
*线性代数基本定理*:$T in L(V,W)$,$dim V$ = $dim ker T + dim im T$
于是容易得出:如果$T:V->W$,$dim W < dim V$,那么$T$一定不是单射. 如果$dim V < dim W$,那么$T$一定不是满射
显然,一个欠定的齐次线性方程组有非零解,非齐次线性方程组可能无解. (齐次线性方程组$T(v) = 0$,非齐次线性方程组$T(v) = v_0$)
== 矩阵
为了更加方便的表示线性映射,我们定义矩阵
*Definition*
设$m,n$都是正整数. 一个$m times n$矩阵$A$是一个在$FF$上的$m times n$矩形数组,写作:
#let matrix_m_n(x) = $mat(#x _"1,1",dots,#x _"1,n";dots. v,,dots. v;#x _"m,1",dots,#x _"m,m")$
$ A = #matrix_m_n("A") $
一些特殊矩阵:$I$是单位矩阵,除了对角线元素为$1$,其他均为$0$.
下面来定义一个线性映射的矩阵表示
*Definition*
若$v_1,v_2,dots,v_n$是$V$的一组基,$w_1,w_2,dots,w_m$是$W$的一组基,且$T v_i = sum_j=1^m A_"i,j"w_j$,那么其矩阵表示$M(T)$就是$A$. 如果未指明$v_i$和$w_i$,可以记作$M(T,(v_1,v_2,dots,v_n),(w_1,w_2,dots,w_m))$
容易看出,$M(T)$的第$i$列和$v_i$的选取有关,而第$i$行和$w_i$的选取有关. 例如变换$T(x,y)=(8x+9y,2x+3y,x+y)$,在标准正交基($(1,0),(0,1)$,$(1,0,0),(0,1,0),(0,0,1)$)下的矩阵表示为$M(T) = mat(8,9;2,3;1,1)$
为了进一步扩展矩阵的意义,定义矩阵的加法、数乘
*Definition*
定义两个$m times n$矩阵$A,B$的和$ A + B = #matrix_m_n("A") + #matrix_m_n("B") = mat(A_"1,1" + B_"1,1",dots,A_"1,n" + B _ "1,n";dots. v,,dots. v;A _"m,1" + B_"m,1",dots,A _"m,m" + B_"m,n") $
数乘$ lambda * A = #matrix_m_n($lambda * A$) $
容易看出,矩阵的加法就相当于线性映射的加法,矩阵数乘就相当于线性映射的数乘.
考虑到线性映射还有叠加这一组合方法,我们下面定义矩阵的乘法.
试探:$S,T$是两个线性映射,$S T$:$ S T(u_k) \
= S(sum_"r=1"^n C_"r,k" v_r) \
= sum_"r=1"^n C_"r,k" sum_"j=1"^m A_"j,r" w_j $
为了表示这种变换规律,定义矩阵乘法
*Definition*
矩阵乘法:设$A$是$n times k$矩阵,$B$是$k times m$矩阵,定义运算$(A B)_"i,j" = sum_"k=1"^k A_"i,k" B_"k,j"$,更加直观的,就是选取$A$的第$i$行和$B$的第$j$列,按元素依次乘在一起再求和,表示新矩阵第$i$行$j$列的元素.
具体计算可以自己去试试.
*Notation*
一种简明记法
$A_(j,dot)$指$A$的第j行形成的一个$m times 1$矩阵,$A_(dot,j)$指$A$的第j列形成的一个$1 times n$矩阵
于是对于矩阵的乘法有以下表示法
$ (A B)_(i,j) = A_(i,dot) B_(dot,j) $ $ (A B)_(dot,k) = A C_(dot,k) $
对矩阵乘法的另一种理解:线性组合 设$c = vec(c_1,c_2,dots,c_n)$,A为$m times n$矩阵,那么$A c$ = $c_1 A_(dot,1) + c_2 A_(dot,2) + dots + c_n A_(dot,n)$,换言之,$A c$就是对$A$列的线性组合,用$c$的每一个元来数乘.
== 逆和同构
*Definition*
$A,B$是两个映射($n times n$矩阵),且有$A B = B A = I$,那么称$B$是$A$的逆(inverse),记作$B = A^(-1)$,$A$是可逆的(invertible)
*Theorem*
如果某矩阵(映射)可逆,那么其逆是唯一的. proof:若$A B = A C = I$,那么$C = C I = C (A B) = (C A) B = B$
映射$V$可逆$<=>$映射$V$是单射满射(一一对应)
对于存在可逆隐射的两个空间,他们也有一些潜在的关系,下面加以定义.
*Definition*
一个可逆映射可以称为同构(isomorphism)
两个空间中存在一个可逆映射,则这两个空间称为是同构的(isomorphic)
*Theorem*
两个向量空间同构$<=>$两个向量空间维度相同
设$dim V = n$,$dim W = m$,那么$L(V,W)$和$FF^(n m)$同构,于是$dim L(V,W) = dim V dim W$
为了统一表示线性映射,我们试着用矩阵相乘的方法来表示映射. 为了更好处理向量,我们定义向量的矩阵表示(matrix of a vector)
*Definition*
设$V$的一组基是$v_1,v_2,dots,v_n$,$v in V$,$v = a_1 v_1 + a_2 v_2 + dots + a_n v_n$,那么$M(v) = vec(a_1,a_2,dots,a_n)$叫做$v$的矩阵表示.
这样之后,我们容易得到$M(T v) = M(T) M(v)$
== 算子
对于以上种种线性映射来说,有一类很特殊的是从$V$到$V$的映射. 我们对其进行一些定义.
*Definition*
一个从$V$到$V$的线性映射定义为*算子*(operator),记$V$上所有算子构成的线性空间为$L(V)$
对于算子,也有一些很好的性质.
*Theorem*
如果有限维向量空间中的算子$T in L(V)$,下面三个命题等价
- $T$可逆
- $T$是单射
- $T$是满射
== 积空间和商空间
*Definition*
线性空间的积:设$V_1,V_2,dots,V_n$是$FF$上的线性空间,定义$V_1 times V_2 times dots times V_n = {(v_1,v_2,dots,v_n),v_1 in V_1,v_2 in V_2,dots in V_n}$叫做这些空间的积.
在积空间中的加法被定义为$(v_1,v_2,dots,v_n) + (u_1,u_2,dots,u_n) = (v_1 + u_1,v_2 + u_2,dots + u_n,v_n + u_n)$,数乘也类似$lambda (v_1,v_2,dots,v_n) = (lambda v_1,lambda v_2,lambda dots,lambda v_n)$
实际上就可以将$v_i$当成一个数,其运算规则就变成了一般向量的运算规则了.
*Theorem*
积空间是一个线性空间
证明从略.
对于积空间本身,我们也要有一些观察. $((1,2),(3,4,5))$和$(1,2,3,4,5)$似乎并没有什么本质上的差异. 那我们就可以去猜测$FF^n times FF^m$和$FF^(m+n)$有同构关系了. 事实也正是如此.
*Theorem*
设$V_1,V_2,dots,V_n$都是有限维线性空间,$dim (V_1 times V_2 times dots times V_n) = dim V_1 + dim V_2 + dots + dim V_n$
*Proof*
选取每个$U$的一个基.对千每个$U$的每个基向量,考虑 $V_1 times V_2 times dots times V_n$ 的如下元素 : 第$j$个位置为此基向量,其余位置为$$0. 所有这些向量构成的组是线性无关的,且张成$V_1 times V_2 times dots times V_n$, 因此是积空间的基 . 这个基的长度是$dim V_1 + · · ·+ dim V_n$
我们下面来定义子空间和向量的和.
*Definition*
设$v in V$,$U$是$V$的子空间. 那么定义子空间和向量的和为:
$v + U = {v + u:u in U}$
我们称$v + U$是$V$的仿射子集(affine subset),$v+U$和$U$形成平行(parallel)关系.
从几何的角度来看,$v + U$是将过原点的$U$平面向$v$方向平移的结果,所以有一定的几何直观. 很显然,一个仿射子集不是一个子空间($v != 0$)
为了描述相同性质的仿射子集,我们来定义商空间.
*Definition*
设$U$是$V$的子空间,那么商空间就是所有平行于$U$的仿射子集的并. 定义为:$V\/U={v + U: v in V}$
*Theorem*
平行于$U$的两个仿射子集要么相等,要么不相交.
即:$U$是$V$的子空间,$v,w in V$下列陈述等价
- $v - w in U$
- $v + U = w + U$
- $(v + U) sect (w + U) != nothing$
下面来定义商空间上的线性运算.
*Definition*
定义加法和数乘分别是:
$(v + U) + (w + U) = (v + w) + U$,$lambda (v + U) = lambda v + U$
需要注意的是,对于同一个集合$v + U$,会有多种表示方法. 举例$y = x + 1$这个集合至少可以有$(-1,0) + (y = x)$和$(0,1) + (y = x)$两种表示方法. 为了说明加法和数乘是有意义的,需要有如下的证明.
*Proof*
命题:若$v_1 + U = v_2 + U$,$w_1 + U = w_2 + U$,那么$(v_1 + w_1) + U = (v_2 + w_2) + U$
由上面的定理知,$v_1 - v_2 in U$,$w_1 - w_2 in U$,于是$(v_1 - v_2) + (w_1 - w_2) in U$,于是$(v_1 + w_1) - (v_2 + w_2) in U$,从而$(v_1 + w_1) + U = (v_2 + w_2) + U$
*Definition*
商映射:定义一个映射$pi: V -> V / U$,对任意$v in V$,$ pi (v) = v + U $
可以证明这个映射是一个线性映射.
*Theorem*
商空间的维数:如果$V$是有限维空间,那么$dim V = dim U + dim V / U$
== 对偶(Duality)
像(值域)是一个标量空间的线性函数也有一些有趣的性质,我们将这类函数单独拿出来讨论一下。
*Definition*
线性泛函(linear functional)是$L(V,FF)$的一个线性函数
*Example*
- 定义$phi: RR^3 -> RR$,$phi(x,y,z) = 3x+4y+5z$,$phi$是线性泛函
- 定义$phi:P(RR) -> RR$,$phi(p) = integral_0^1 p dif x$是线性泛函
线性泛函构成的空间也有研究的价值,下面给予定义
*Definition*
对偶空间(dual space)是线性泛函构成的空间,即$L(V,FF)$,记作$V'$,容易知道$dim V' = dim V$
对偶基(dual basis)是$V'$的一组基,也就是说,取$v_1,v_2,dots,v_n$,那么其对偶基也是一组线性泛函即
$ phi_j (v_k) = cases(1 "if" k = j,
0 "if" k != j) $
对偶映射(dual mapping):对于$T in L(V,W)$,定义对偶映射$T' in L(W',V')$,满足$phi in W'$,有$T'(phi) = phi circle.small T$
*Theorem*
对偶函数的代数性质:$(lambda T)' = lambda (T')$,$(S + T)' = S' + T'$,$(S T)' = T' S'$
*Definition*
零化子(annihilator):对于$U subset V$,$U$的零化子$U^0$定义为$U^0 = {phi in V': forall v in U,phi(u) = 0$.
*Theorem*
- 零化子是一个$V'$的子空间.
- 设$V$是有限维的,那么$dim U + dim U^0 = dim V$
- $V,W$有限维,$T in L(V,W)$
- $dim ker T' = dim ker T + dim W - dim V$
- $ker T = (im T)^0$
- $T$是满的当且仅当$T'$是单的.
我们知道,线性映射总是有对应的矩阵表示,我们理应好奇对偶映射在矩阵上的反应。下面定义这一点。
*Definition*
矩阵的转置(transpose),$A^T$:定义$n times m$矩阵$A$的转置$A$为$m times n$矩阵,$(A^T)_(i,j) = (A)_(j,i)$
*Theorem*
转置的代数性质:
- $(A+B)^T = A^T + B^T$
- $(lambda A)^T = lambda A^T)$
- $(A B)^T = B^T A^T$
$M(T') = M(T)^T$
== 矩阵的秩(rank)
*Definition*
行秩和列秩:设$A$是$FF$上的$m times n$矩阵
- $A$的行秩是$A$诸行张成空间的维数。
- $A$的列秩是$A$诸列张成空间的维数。
*Theorem*
$im T$的维数等于$M(T)$的列秩
行秩等于列秩,统称为秩(rank),记作$"rank" A$
个人看来,线性泛函在后面用到的比较少,主要用到的可能还是转置和秩。所以最后的结论可能比前面的推到更加重要,具体为什么这里要用线性泛函引出这些内容,我也很懵
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix-alignment_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test #454 equations.
$ mat(-1, 1, 1; 1, -1, 1; 1, 1, -1) $
$ mat(-1&, 1&, 1&; 1&, -1&, 1&; 1&, 1&, -1&) $
$ mat(-1&, 1&, 1&; 1, -1, 1; 1, 1, -1) $
$ mat(&-1, &1, &1; 1, -1, 1; 1, 1, -1) $
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.6.0/docs.typ | typst | Apache License 2.0 | #import "@local/gentle-clues:0.6.0": *
#import "@local/svg-emoji:0.1.0": *
#set page(margin: 2cm);
#show: setup-emoji
#show: gentle-clues.with(
lang: "de",
headless: false,
breakable: false,
// header-inset: 0.4em,
// content-inset: 1.3em,
// border-radius: 12pt,
// border-width: 1pt,
// stroke-width: 5pt,
)
#set text(font: "Roboto")
= Gentle clues for typst
Add some beautiful, predefined admonitions or define your own.
#clue(title: "Getting Started")[
A minimal starting example
```typ
#import "@preview/gentle-clues:0.6.0": *
#show: gentle-clues.with(
lang: "de", // set header title language (default: "en")
)
#tip[Check out this cool package]
```
#tip[Check out this cool package]
]
#clue(title: "Usage")[
+ Import the package like this:
```typ
#import "@preview/gentle-clues:0.6.0": *
```
+ Change the default settings for a clue.
```typ
#show: gentle-clues.with(
lang: "de", // set header title language (default: "en")
// Accepts "en", "de", "fr" or "es" for the moment.
headless: false, // never show any headers
breakable: false, // default breaking behavior
header-inset: 0.5em, // default header-inset
content-inset: 1em, // default content-inset
stroke-width: 2pt, // default left stroke-width
border-radius: 2pt, // default border-radius
border-width: 0.5pt, // default boarder-width
)
```
+
#grid(columns: 2, gutter: 1em)[
Use a predefined clue without any options
```typ
#info[You will find a list with all predefined clues at the last page.]
```
#align(end)[_Turns into this_ #sym.arrow]
][
#set align(bottom)
#info[You will find a list with all predefined clues at the last page.]
]
+ #grid(columns: 2, gutter: 1em)[
Or add some options like a custom title
```typ
#example(title: "Custom title")[ Content ...]
```
#align(end)[_Turns into this_ #sym.arrow]
][
#set align(bottom)
#example(title: "Custom title")[ Content ...]
]
#memo(title: "New in v0.6.0",_color: gradient.linear(..color.map.crest))[
Using global show rule for default configuration.
]
]
#clue(title: "All Options for a clue")[
All default settings can also be applied to a single clue through passing it as an named argument. Here is a list of accepted arguments:
```typ
title: auto, // [string] or [none] (none will print headless)
icon: emoji.magnify.l, // [file] or [symbol]
_color: navy, // base color [color]
width: auto, // total width [length]
radius: auto, // radius of the right border [length]
border-width: auto, // width of the right and down border [length]
content-inset: auto, // [length]
header-inset: auto, // [length]
breakable: auto, // if clue can break onto next page [bool]
```
]
#box(
height: 4.5cm,
stroke: gray.lighten(40%),
radius: 2pt,
inset: 2mm,
columns(2)[
#example(title: "Breaking news", breakable: true)[
Clues can now break onto the next page with option: `breakable: true`
#lorem(30)
]
This is a two columns layout.
])
#clue(title: "Define your own clue")[
```typst
#import "@preview/gentle-clues:0.6.0": *
// Define a clue called ghost
#let ghost(title: "Buuuuuuh", icon: emoji.ghost , ..args) = clue(
_color: purple, // Define a base color
title: title, // Define the default title
icon: icon, // Define the default icon
..args // Pass along all other arguments
)
// Use it
#ghost[Huuuuuuh.]
```
The result looks like this.
#let ghost(title: "Buuuuuuh.", icon: emoji.ghost , ..args) = clue(_color: gray, title: title, icon: icon, ..args)
#ghost[Huuuuuuh.]
#tip[Use the `svg-emoji` package until emoji support is fully supported in typst ]
]
#pagebreak()
== List of all predefined clues <predefined>
#columns(2)[
`#abstract`
#abstract[Make it short. This is all you need.]
`#question`
#question[How do amonishments work?]
`#info`
#info[It's as easy as
```typst
#info[Whatever you want to say]
```
]
`#example`,
#example[Testing ...]
`#task`
#task[
#box(width: 0.8em, height: 0.8em, stroke: 0.5pt + black, radius: 2pt) Check out this wonderfull typst package!
]
`#error`
#error[Something did not work here.]
`#warning`
#warning[Still a work in progress.]
`#success`
#success[All tests passed. It's worth a try.]
`#tip`
#tip[Try it yourself]
`#conclusion`
#conclusion[This package makes it easy to add some beatufillness to your documents]
`#memo`
#memo[Leave a #emoji.star on github.]
`#quote`
#quote[Keep it simple. Admonish your life.]
=== Headless Variant
just add `title: none` to any example
#info(title:none)[Just a short information.]
] // columns end
|
https://github.com/Jozott00/typst-LLNCS-template | https://raw.githubusercontent.com/Jozott00/typst-LLNCS-template/main/template/theorem_proof_cnf.typ | typst | #import "@preview/lemmify:0.1.4": *
///// private stuff
#let __llncs_thm_style(
thm-type,
name,
number,
body
) = block(width: 100%, breakable: true)[#{
strong(thm-type) + " "
if number != none {
strong(number) + ". "
}
if name != none {
emph[(#name)] + " "
}
emph(body)
}]
#let __llncs_thm_proof_style(
thm-type,
name,
number,
body
) = block(width: 100%, breakable: true)[#{
emph(thm-type) + ". "
body
v(5pt)
}]
#let __llncs-thm-styling = (
thm-numbering: (fig) => {
if fig.numbering != none {
numbering(fig.numbering, ..fig.counter.at(fig.location()))
}
},
thm-styling: __llncs_thm_style,
proof-styling: __llncs_thm_proof_style,
)
#let __llncs_thm_cnf() = {
let thm = default-theorems(
"llcns-thm-group", lang: "en", ..__llncs-thm-styling)
let def = default-theorems(
"llcns-def-group", lang: "en", ..__llncs-thm-styling)
let prop = default-theorems(
"llcns-prop-group", lang: "en", ..__llncs-thm-styling)
let lem = default-theorems(
"llcns-lemma-group", lang: "en", ..__llncs-thm-styling)
let proof = default-theorems(
"llcns-proof-group", lang: "en", ..__llncs-thm-styling)
let coral = default-theorems(
"llcns-coral-group", lang: "en", ..__llncs-thm-styling)
return (
theorem: thm.theorem,
__thm-rules: thm.rules,
definition: def.definition,
__def-rules: def.rules,
proposition: prop.proposition,
__prop-rules: prop.rules,
lemma: lem.lemma,
__lem-rules: lem.rules,
proof: proof.proof,
__proof-rules: proof.rules,
corollary: coral.corollary,
__corol-rules: coral.rules,
)
} |
|
https://github.com/drbartling/obsidian-to-typst | https://raw.githubusercontent.com/drbartling/obsidian-to-typst/master/README.md | markdown | # Obsidian to Typst
This utility attempts to make it easy to convert markdown documents written using obsidian into PDFs.
## Requirements
- typst
- mermaid
- mutool
## Getting Started
This project uses python [poetry](https://python-poetry.org/). Follow the [intallation instructions](https://python-poetry.org/docs/#installation) for poetry.
Install typst using a package manager or `cargo install`
Run `poetry install` and `poetry shell` to install and and activate the python virtual environment.
Than, run `obsidian_to_typst .\examples\feature_guide\Widget.md` to convert the example document to a PDF. The PDF will be placed in `.\examples\feature_guide\output\Widget.pdf`.
```powershell
watchexec --clear --restart --debounce 500 --exts py "isort . && black . && pytest && obsidian-to-typst ./examples/feature_guide/Widget.md"
```
|
|
https://github.com/PorterLu/Typst | https://raw.githubusercontent.com/PorterLu/Typst/main/make_a_template/make_a_template.typ | typst | #let document_title = "Make a Template"
#set par(justify: true)
#set page(
paper: "us-letter",
header: align(right)[
#document_title
],
numbering: "1"
)
#align(center, text(17pt)[* #document_title *])
= Introduction
#h(2em) 在之间的章节中已经介绍了Typst的撰写一篇文章所需要的内容。但是如果你要重复书写同一个会议的论文,这就需要多次编写重复的内容,于是就有了模版的需求。在这一章节中将介绍如何去创建一个模版和使用模版。开始吧!
= A toy Example
#h(2em) 在 Typst 中模版就是将整个文档都包裹的函数。为了学习模版的概念,我们首先回顾一下我们自己的函数
```
#let amazed(term) = box[🤡 #term 🤡]
You are #amazed[beautiful]!
```
#let amazed(term) = box[ 🤡 #term 🤡 ]
#h(2em) You are #amazed[beautiful]!,我们可以看到结果输出正确。这个函数接受一个参数,输出两个表情符号将输入包裹。进一步我们可以改进这个函数。
```
#let amazed(term, color: blue) = {
text(color, box[🤡 #term 🤡])
}
You are #amazed[beautiful]!
```
#let amazed(term, color: blue) = {
text(color, box[🤡 #term 🤡])
}
#h(2em)I am #amazed(color: purple)[amazed]!,这样就可以改变字体的颜色。接下来我们对所有的文本内容都做函数操作。
#show: amazed("I choose to focus on the good
in my life and let go of any
negative thoughts or beliefs,
In fact, I am amazing!", color: blue)
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-dila/7-farma-zvirat.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": dilo, hrule
#dilo("<NAME>", "farma", "<NAME> (<NAME>)", "<NAME>", "1. p. 20. st; Světová lit. 20. st; sci-fi, antiutopie", "Británie", "1945", "epika", "alegorický román (bajka)")
#columns(2, gutter: 1em)[
*Téma*\
kritika komunistického režimu, zejména v tehdejším SSSR
*Motivy*\
pokrytectví, totalitní režimy, politika
*Časoprostor*\
na Anglické farmě v době autora (v době existence SSSR)
*Postavy* \
_Major_ - prase, které přišlo s myšlenkou revoluce na farmě; Marx/Lenin \
_Napoleon_ - kruté prase, které vydobíjí respekt silou; Stalin \
_Kuliš_ - učil ostatní prasata číst a psát, nakonec vyhnán; Trockij \
_Pištík_ - pravá ruka Napoleona; propagandista \
_Boxer_ - pracovitý kůň, který je na konci zrazen \
_<NAME>_ - bývalý majitel farmy vyhnán (a nahrazen) zvířaty; kulak/buržoust
*Kompozice* -- chronologická, kapitoly
*Vypravěč* -- 3. os, vševědoucí
*Jazykové prostředky*\
hodně přímé řeči (dialogy mezi zvířaty), metonymie (ovce tupé stádo, psi věrní, atp.) a metafory, celé je to alegorie, velká písmena pro *R*#[]evoluci
#colbreak()
*Obsah*\
<NAME> je alkoholik vlastnící farmu, kde se nespokojená zvířata rozhodnou udělat převrat. V jeho vedení jsou prasata a nastolí systém až podezřele připomínající komunistický režim. V knize lze nalézt motivy překrucování informací, slibů, nesmyslných dlouhodobých projektů, a ještě méně kvalitního života, než býval dříve. Věrný pracovní kůň Boxer, který je režimem vyzdvihován, je na konci svého života zrazen a dán na salám. Prasata jen využívají tvárnosti obyvatelstva podobně, jako se to doopravdy dělo v SSSR.
*Literárně historický kontext*\
Tato kniha vznikla během druhé světové války a ocenění se jí dostalo až o pár let později.
]
#pagebreak()
*Ukázka*
"[...] Copak není úplně jasné, soudruzi, že toto zlo našeho života pochází z tyranie lidských bytostí? Produkty naší práce nám budou patřit pouze tehdy, zbavíme-li se člověka! Mohli bychom získat svobodu a bohatství téměř ze dne na den! Co tedy musíme udělat? Ve dne v noci, tělem i duší pracovat na svržení lidské rasy. A to je moje poselství, soudruzi: REVOLUCE! Nevím, kdy přijde. Možná za týden, možná za sto let, ale vím tak jistě, jako vidím pod nohama tuhle slámu, že dříve či později zvítězí spravedlnost. A na to se soustřeďte, soudruzi. Zbývá vám už málo času! A především předejte toto mé poselství těm, kteří přijdou po vás, aby budoucí generace dovedly bitvu až do jejího vítězného konce.
Nezapomeňte, soudruzi, že ve své odhodlanosti nesmíte ochabnout. Nic vás nesmí zarazit. Neposlouchejte nikdy ty, kteří vám budou tvrdit, že člověk a zvíře mají společné zájmy, že prospěch jednoho je prospěchem druhého. To vše jsou lži! člověk neuznává zájmy jiného tvora než sebe. A mezi námi zvířaty musí být dokonalá jednota a bojové soudružství. Všichni lidé jsou nepřátelé, všechna zvířata jsou si soudruhy! [...] Žádné zvíře nesmí nikdy bydlet v domě, spát v posteli, nosit šaty, pít alkohol, kouřit, používat peníze či obchodovat. Všechny lidské zvyky jsou špatné. A především: žádné zvíře nesmí nikdy tyranizovat jiné, slabé či silné, chytré či prosté. Všichni jsme si bratry. Žádné zvíře nesmí nikdy zabít jiné zvíře! Všechna zvířata jsou si rovna. [...]"
#hrule()
Někdy v té době se prasata najednou přestěhovala do Jonesova
domu a udělala si z něj dům svůj. A zvířata si vzpomněla, že kdysi
snad byla přijata rezoluce, která právě tyto praktiky zakazovala,
a zase musel nastoupit Kvičoun a přesvědčovat je, že se pletou, že to
je úplně jinak. Je absolutně nutné, řekl, aby prasata, která jsou jak
známo mozky celé farmy, měla k dispozici klidné místo na práci.
Je také v souladu s důstojností Vůdce (poslední dobou nazýval Napoleona vždy „Vůdcem“), aby žil a tvořil v domě, a ne v nějakém
chlívě. Přesto však byla některá zvířata dost zaskočena, když se dozvěděla, že prasata nejenže jedí v kuchyni a udělala si z obýváku salon,
ale k tomu všemu ještě spí v posteli. Boxer to jako vždycky vyřešil
svým obligátním „Napoleon má vždycky pravdu!“, ale Jetelinka, která
si dobře pamatovala na pravidlo výslovně zakazující spaní v posteli,
šla za stodolu a pokoušela se tam rozluštit Sedmero přikázání napsané na vratech. I při sebevětší snaze se jí však nedařilo pospojovat
jednotlivá písmena ve slova, a obrátila se proto na Lízu.
„Lízo,“ řekla, „přečti mi Čtvrté přikázání. Není tam náhodou něco
o zákazu spaní v postelích?“. Líza s občasným zakoktnutím nakonec nápis přečetla. „Říká se tu: „Žádné zvíře nebude nikdy spát v posteli s prostěradly.“. To je vážně zvláštní, Jetelinka si ne a ne vzpomenout, že by se ve
Čtvrtém přikázání říkalo něco o prostěradlech.
#pagebreak()
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/29.typ | typst | #import "../conf.typ": *
= Системы линейных однородных дифференциальных уравнений с постоянными коэффициентами, методы их решения
#definition[
Пусть $bold(x)(t) = vec(x_1 (t), ..., x_n (t)); A in M_n (CC)$
Тогда *Нормальная линейная однородная система уравнений* выглядит так:
#eq[
$dot(bold(x)) = A bold(x)$
]
Где под $dot$ подразумевается дифференцирование по $t$.
]
#theorem[
Если $bold(h_1), ..., bold(h_n)$ -- базис из собственных векторов матрицы $A$,
то $bold(x_i) = e^(lambda_i t)bold(h_i)$ -- ФСР для исходной однородной системы.
]
#proof[
Заметим, что
#eq[
$A(e^(lambda t)bold(h)) = e^(lambda t)(A bold(h)) = e^(lambda t) lambda bold(h) = (e^(lambda t) bold(h))'$
]
Значит собственный вектор является решением.
Их линейная независимость следует из того, что их вронскиан в точке $t = 0$ равен
определителю из координатных столбцов этого базиса, а значит не равен нулю.
]
#definition[
Пусть $t$ -- действительная переменная, $A in M_n (CC)$.
Тогда *матричной экспонентой* называется ряд
#eq[
$e^(t A) := E_n + sum_(k = 1)^oo t^k / k! A^k$
]
]
#lemma[
Свойства матричной экспоненты:
+ Если $S$ невырожденная и $A = S B S^(-1)$, то $forall t in RR : e^(t A) = S e^(t B) S^(-1)$
+ $(e^(t A))'_t = A e^(t A) = e^(t A) A$
]
#theorem(
"Матричная экспонента для ФСР",
)[
Матрица $e^(t A)$ является фундаментальной матрицей для системы линейный
уравнений $dot(bold(x)) = A bold(x)$.
]
#proof[
По свойствам экспоненты
#eq[
$(e^(t A))'_t = A e^(t A)$
]
Значит каждый столбец матрицы $e^(t A)$ является решением исходной систему.
Поскольку $forall t in RR : det e^(t A) != 0$, то $e^(t A)$ фундаментальна.
]
|
|
https://github.com/Shambuwu/stage-docs | https://raw.githubusercontent.com/Shambuwu/stage-docs/main/documenten/ontwerprapport.typ | typst | #align(
center,
text(
size: 1.2em,
[
*Competentie: Ontwerpen* \
Ontwerprapport en onderbouwing \
],
)
)
#align(
center,
figure(
image("../bijlagen/ontwerprapport/OIG.jpg",
width: 400pt
)
)
)
#let date = datetime(
year: 2023,
month: 6,
day: 30
)
#place(
bottom + left,
text[
*Student:* <NAME> \
*Studentnummer:* 405538 \
*Datum:* #date.display() \
*Onderwerp:* Competentie: Analyseren \
*Opleiding:* HBO-ICT \
*Studiejaar:* 3 \
]
)
#place(
bottom + right,
image("../bijlagen/logo.png", width: 175pt)
)
#pagebreak()
#set heading(numbering: "1.1")
#show heading: it => {
set block(below: 10pt)
set text(weight: "bold")
align(left, it)
}
#outline(
title: [
*Inhoudsopgave*
],
)
#set page(
numbering: "1 / 1",
number-align: right,
)
#pagebreak()
= Samenvatting
Dit ontwerprapport beschrijft de ontwikkeling van een datavisualisatietool voor de voedingsindustrie. Het doel van dit project was om een tool te ontwerpen die gebruikers in staat stelt om recepten en ingrediënten op een visuele en interactieve manier te verkennen en analyseren.
Het rapport begint met een probleemdefinitie, waarin de behoefte aan geavanceerde datavisualisatietools in de voedingsindustrie wordt beschreven. Vervolgens worden de ontwerpeisen opgesteld, waarbij concrete, meetbare criteria worden geformuleerd op basis van klantbehoeften. Daarna volgt een technische beoordeling, waarin de belangrijkste aspecten van het ontwerpgebied worden behandeld en de keuzes voor de gebruikte technologieën worden toegelicht.
Het ontwerp van de datavisualisatietool bestaat uit verschillende componenten, waaronder een React frontend, een Symfony backend en een Neo4j database. De frontend biedt een intuïtieve gebruikersinterface, terwijl de backend de logica en functionaliteiten beheert en communiceert met de database via de Neo4j Object Graph Mapper (OGM). Deze architectuur zorgt voor schaalbaarheid, modulariteit en efficiënte verwerking van complexe relaties tussen recepten, ingrediënten en andere gegevens.
Het ontwerp is uitgebreid getest en geëvalueerd aan de hand van functionele tests en gebruikersfeedback. De tests hebben aangetoond dat de tool voldoet aan de gestelde ontwerpeisen en functionaliteiten zoals zoeken, filteren en visualisatie correct functioneren. De gebruikerservaring is positief beoordeeld, waarbij de gebruikersinterface als overzichtelijk en gebruiksvriendelijk wordt ervaren.
De ontwerpbeoordeling concludeert dat het ontwerp over het algemeen effectief en efficiënt is, met enkele verbeterpunten om de gebruikerservaring verder te optimaliseren. Aanbevelingen voor toekomstig werk omvatten het implementeren van ontbrekende functionaliteiten en het verfijnen van de gebruikersinterface op basis van gebruikersfeedback.
Dit ontwerprapport biedt een gedetailleerd inzicht in het ontwerp en de ontwikkeling van de datavisualisatietool, waarbij voldaan wordt aan de gestelde ontwerpeisen en rekening gehouden wordt met de behoeften van de gebruikers in de voedingsindustrie. Het ontwerp legt een solide basis voor verdere ontwikkeling en implementatie van de tool, met het potentieel om waardevolle inzichten te bieden en innovatie te stimuleren in de voedingssector.
#pagebreak()
= Probleem definitie
== Probleemscope
De probleemscope van dit ontwerprapport richt zich op het ontwerp van een datavisualisatietool voor de voedingsindustrie. Het probleem dat moet worden aangepakt, is het gebrek aan een gebruiksvriendelijke tool waarmee gebruikers recepten en ingrediënten kunnen zoeken, filteren, visualiseren en alternatieve ingrediënten kunnen identificeren.
De scope van dit ontwerprapport omvat het ontwerpproces van de datavisualisatietool, waarbij de nadruk ligt op het creëren van een intuïtieve gebruikersinterface, het ontwerpen van relevantie zoek- en filtermogelijkheden, en het visualiseren van de gegevens op een overzichtelijke manier.
== Technische beoordeling
Deze technische beoordeling biedt een overzicht van de belangrijkste aspecten die relevant zijn voor het ontwerp van de datavisualisatietool. Het doel van deze beoordeling is om inzicht te krijgen in recente ontwikkelingen op het gebied van datavisualisatie, de huidige staat van de voedingsindustrie, en de technische mogelijkheden van de datavisualisatietool.
=== Achtergrondinformatie
In de voedingsindustrie is er een toenemende behoefte aan geavanceerde tools die het zoeken, filteren en visualiseren van recepten en ingrediënten mogelijk maken. Deze tools kunnen bijdragen aan het identificeren van alternatieve ingrediënten, het optimaliseren van voedingswaarden en het bevorderen van innovatie. Het ontwikkelen van een datavisualisatietool kan hierin een cruciale rol spelen.
=== Huidige stand van zaken
Binnen het vakgebied van datavisualisatie zijn er verschillende technologieën en benaderingen die relevant zijn voor dit project. Grafische bibliotheken zoals D3.js, Plotly en Highcharts bieden geavanceerde mogelijkheden voor het creëren van interactieve en visueel aantrekkelijke visualisaties. Daarnaast zijn er frameworks zoals React en Angular die kunnen worden gebruikt voor de ontwikkeling van de gebruikersinterface.
Er zijn reeds verschillende tools beschikbaar die het zoeken, filteren en visualiseren van recepten en ingrediënten mogelijk maken. Enkele voorbeelden hiervan zijn Foodpairing, Yummly en FoodData Central. Het is essentieel om deze tools te onderzoeken om inzicht te krijgen in de sterke punten en verbeterpunten ervan, om zo een effectieve datavisualisatietool te kunnen ontwerpen.
=== Best practices en richtlijnen
Het ontwerpen van een effectieve datavisualisatietool vereist het volgen van best practices en richtlijnen op het gebied van gebruikerservaring, interactieontwerp en visualisatietechnieken. Enkele belangrijke aspecten om rekening mee te houden zijn:
- Zorg voor een intuïtieve gebruikersinterface die eenvoudig te navigeren is.
- Bied interactieve filters en zoekmogelijkheden om de gebruiker te helpen bij het vinden van relevante informatie.
- Gebruik geschikte grafische representaties, zoals staafdiagrammen, taartdiagrammen en netwerkdiagrammen, om de gegevens effectief te communiceren.
- Maak gebruik van kleur, vorm en grootte om belangrijke informatie te benadrukken en visueel te onderscheid te maken.
- Zorg voor responsieve en schaalbare ontwerpen, zodat de tool op verschillende apparaten kan worden gebruikt.
Het begrijpen van deze technische aspecten en het volgen van best practices zal bijdragen aan het succesvol ontwerpen van de datavisualisatietool. Door gebruik te maken van de juiste technologieën en ontwerpprincipes kan een effectieve tool worden ontwikkeld die voldoet aan de eisen van de gebruikers.
== Ontwerpeisen
De ontwerpeisen vormen de kern van het ontwerp en zijn gebaseerd op de behoeften van de opdrachtgever en gebruikers. De volgende meetbare ontwerpeisen zijn vastgesteld om te voldoen aan de verwachtingen van het systeem:
+ *Toegankelijkheid via webapplicatie:*
- De webapplicatie moet toegankelijk zijn via gangbare webbrowsers, zoals Chrome, Firefox en Safari.
- De laadtijd van de webpagina's mag niet langer zijn dan 3 seconden.
+ *Zoekfunctionaliteit:*
- Het systeem moet in staat zijn om recepten en ingrediënten te doorzoeken op basis van opgegeven zoektermen.
- De zoekresultaten moeten binnen 2 seconden worden weergegeven.
- Het systeem moet een nauwkeurigheidspercentage van 90% hebben bij het identificeren van relevante zoekresultaten.
+ *Filterfunctionaliteit:*
- Het systeem moet de mogelijkheid bieden om recepten en ingrediënten te filteren op basis van specifieke criteria, zoals voedingswaarde en allergenen.
- De toegepaste filters moeten de resultaten nauwkeurig en consistent beperken.
+ *Visualisatie van recepten en ingrediënten:*
- Het systeem moet visuele weergaven en presentaties genereren van het recepten- en ingrediëntennetwerk.
- De visualisaties moeten duidelijk, overzichtelijk en begrijpelijk zijn voor de gebruikers.
- Het systeem moet de mogelijkheid bieden om in te zoomen, uit te zoomen en te navigeren binnen de visualisaties.
+ *Identificatie van alternatieve ingrediënten:*
- Het systeem moet alternatieve ingrediënten kunnen identificeren op basis van specifieke criteria, zoals voedingswaarde, smaak en vergelijkbare recepten.
- Het systeem moet minimaal 80% nauwkeurigheid hebben bij het aanbevelen van alternatieve ingrediënten.
Deze ontwerpeisen vormen de basis voor het ontwerp van de datavisualisatietool en zullen ervoor zorgen dat de tool voldoet aan de behoeften van de opdrachtgever en gebruikers.
#pagebreak()
= Ontwerpbeschrijving
De ontwerpbeschrijving biedt een gedetailleerde uitleg van het ontwerp van de datavisualisatietool voor de voedingsindustrie. Dit hoofdstuk is opgedeeld in drie secties: Overzicht, Gedetailleerde beschrijving en Gebruik.
== Overzicht
Het ontwerp van de tool is gebaseerd op een client-server database model. Het bestaat uit een React frontend, een Symfony backend en een Neo4j-database. Alle componenten draaien in Docker containers, waardoor het gemakkelijk te implementeren en schaalbaar is. Het ontwerp streeft ernaar om een gebruiksvriendelijke webapplicatie te bieden waarmee gebruikers recepten en ingrediënten kunnen zoeken, filteren, visualiseren en alternatieve ingrediënten kunnen identificeren.
== Gedetailleerde beschrijving
Het ontwerp van de datavisualisatietool is gebaseerd op zorgvuldige ontwerpkeuzes die zijn gemaakt om de gewenste functionaliteiten te realiseren en een optimale gebruikerservaring te bieden.
=== Client-server database model
Het gebruik van een client-server database model biedt verschillende voordelen. Het maakt een schaalbare architectuur mogelijk, waarbij de frontend en backend onafhankelijk van elkaar kunnen worden opgeschaald om aan de groeiende vraag te voldoen. Daarnaast zorgt de scheiding tussen de frontend en backend ervoor dat de applicatie flexibel is en gemakkelijk kan worden aangepast of uitgebreid. Het gebruik van Docker helpt bij het vereenvoudigen van de implementatie en het beheer van de applicatie door de containerisatie van de componenten.
=== Frontend (React)
React is gekozen als het frontend-library vanwege zijn efficiënte, herbruikbare componenten en zijn vermogen om snelle en responsieve gebruikersinterfaces te creëren. Met React kunnen interactieve elementen en dynamische updates gemakkelijk worden geïmplementeerd, waardoor een vloeiende gebruikerservaring ontstaat. Daarnaast biedt React de mogelijkheid om componenten opnieuw te gebruiken, waardoor de ontwikkeltijd wordt verkort en de codebase overzichtelijk blijft.
#figure(
image("../bijlagen/ontwerprapport/design_2.png",
width: 300pt
),
caption: "Een eerste werkende demo van het frontendontwerp",
supplement: "Figuur",
kind: "figure"
)
React biedt de volgende voordelen die bijdragen aan het realiseren van de ontwerpeisen:
- *Modulaire componenten:* Met React kunnen componenten worden opgesplitst in herbruikbare modules, wat zorgt voor een modulaire en goed gestructureerde codebase. Dit maakt het gemakkelijk om de code te onderhouden en uit te breiden.
- *Interactieve gebruikersinterface:* React maakt het mogelijk om interactieve elementen en dynamische updates te implementeren, waardoor een vloeiende gebruikerservaring ontstaat.
- *Herbruikbaarheid:* React biedt de mogelijkheid om componenten opnieuw te gebruiken, waardoor de ontwikkeltijd wordt verkort en de codebase overzichtelijk blijft.
=== Backend (Symfony)
Symfony is gekozen als het backend-framework vanwege zijn krachtige mogelijkheden op het gebied van webontwikkeling. Het is een betrouwbaar, robuust en flexibel framework dat een solide basis biedt voor het ontwikkelen van complexe webapplicaties. Symfony volgt de principes van het Model-View-Controller (MVC) ontwerppatroon, wat helpt bij het scheiden van de logica, het datamodel en de presentatie van de applicatie. Dit zorgt voor een modulaire en goed gestructureerde codebase, waardoor onderhoud en uitbreiding van de applicatie gemakkelijker worden.
Symfony biedt verschillende voordelen die bijdragen aan het voldoen aan de ontwerpeisen:
- *Betrouwbaarheid en flexibiliteit:* Symfony is een betrouwbaar en robuust framework. Het biedt flexibiliteit in termen van architectuur en functionaliteiten, waardoor het mogelijk is om de backend af te stemmen op de specifieke behoeften van de datavisualisatietool.
- *Model-View-Controller (MVC) Patroon:* Het toepassen van het Model-View-Controller (MVC) patroon in Symfony heeft als voordeel dat het de applicatie in modulaire componenten opdeelt, waardoor de codebase goed gestructureerd is. Deze modulaire structuur maakt het eenvoudiger om onderhoudstaken uit te voeren en de applicatie uit te breiden met nieuwe functionaliteiten. Door de scheiding van verantwoordelijkheden tussen het model, de view en de controller is het gemakkelijker om wijzigingen aan te brengen in specifieke onderdelen zonder de rest van de applicatie te beïnvloeden. Dit bevordert de flexibiliteit en maakt het mogelijk om de codebase beter te beheren en te onderhouden over de tijd.
- *Communicatie met de database:* Symfony communiceert met de Neo4j-database via de Neo4j Object Graph Mapper (OGM). De OGM biedt een abstractielaag voor de communicatie met de database en maakt het gemakkelijk om objectgeoriënteerde modellen te mappen naar de grafenstructuur van Neo4j. Dit zorgt voor een efficiënte interactie met de database en het ophalen en manipuleren van de benodigde gegevens.
=== Database (Neo4j)
De keuze voor Neo4j als de databaseoplossing is gebaseerd op de unieke mogelijkheden van een grafendatabase voor het opslaan en bevragen van complexe relaties tussen entiteiten. De grafenstructuur van Neo4j maakt het gemakkelijk om de onderlinge verbanden tussen recepten, ingrediënten en andere gegevens vast te leggen. Dit is vooral waardevol in de voedingsindustrie, waar de relaties tussen ingrediënten en recepten vaak complex zijn.
- *Grafenstructuur:* Een van de voordelen van Neo4j is de grafenstructuur, die het mogelijk maakt om complexe relaties tussen recepten, ingrediënten en andere gegevens efficiënt vast te leggen. Door gebruik te maken van deze grafenstructuur kan de applicatie waardevolle inzichten genereren door de onderlinge verbanden tussen de entiteiten te verkennen.
- *Efficiënte bevraging van gegevens:* Daarnaast biedt Neo4j geavanceerde querymogelijkheden die specifiek zijn ontworpen voor grafen. Deze querymogelijkheden stellen de applicatie in staat om complexe zoek- en filteroperaties efficiënt uit te voeren, wat resulteert in een verbeterde responstijd van de applicatie. Door deze efficiënte bevraging van gegevens kan de datavisualisatietool snel en nauwkeurig reageren op gebruikersverzoeken.
- *Schaalbaarheid:* Een ander belangrijk aspect is de schaalbaarheid van Neo4j. Het kan gemakkelijk worden opgeschaald om te voldoen aan de groeiende vraag naar dataverwerking. Dit betekent dat de applicatie eenvoudig kan worden uitgebreid en kan voldoen aan de behoeften van een groeiend aantal gebruikers en een grotere dataset.
#figure(
image("../bijlagen/ontwerprapport/design_1.png",
width: 400pt
),
caption: "Architectuur van het ontwerp",
supplement: "Figuur",
kind: "figure"
)
Hierboven is een schematische weergave te zien van de architectuur van het ontwerp. De frontend communiceert met de backend via API-calls. De backend communiceert met de neo4j database via de OGM. De neo4j database bevat de verzameling van recepten, ingrediënten en gerelateerde gegevens.
Deze architectuur biedt verschillende voordelen, zoals schaalbaarheid, modulariteit en efficiënte interactie met de database. Het stelt de datavisualisatietool in staat om gebruikersvriendelijke functionaliteiten te bieden, zoals zoeken, filteren, visualiseren en identificeren van alternatieve ingrediënten. Door de scheiding van verantwoordelijkheden tussen de frontend, backend en database is de applicatie flexibel, onderhoudbaar en gemakkelijk uitbreidbaar.
== Gebruik
Het ontwerp van de datavisualisatietool is bedoeld om gebruikers in staat te stellen recepten en ingrediënten te verkennen, filteren, visualiseren en alternatieven te identificeren. De tool is ontworpen als een webapplicatie, waardoor gebruikers eenvoudig toegang hebben tot de functionaliteiten via een webbrowser.
Wanneer een gebruiker de webapplicatie opent, wordt deze verwelkomd met een intuïtieve gebruikersinterface. Hier kan de gebruiker navigeren door de verschillende functionaliteiten en acties uitvoeren.
De zoekfunctionaliteit stelt gebruikers in staat om specifieke recepten en ingrediënten te vinden door zoektermen in te voeren. Het ontwerp zorgt ervoor dat de zoekresultaten binnen enkele seconden worden weergegeven. Gebruikers kunnen ook filters toepassen om de resultaten verder te verfijnen op basis van criteria zoals voedingswaarde, allergenen en andere eigenschappen.
Het ontwerp omvat ook de mogelijkheid om recepten en ingrediënten visueel weer te geven. Gebruikers kunnen interactieve visualisaties verkennen, inzoomen op details en uitzoomen voor een breder overzicht. De visualisaties zijn ontworpen om de relaties tussen recepten, ingrediënten en andere gegevens duidelijk en begrijpelijk te tonen.
Daarnaast biedt het ontwerp de functionaliteit om alternatieve ingrediënten te identificeren op basis van specifieke criteria, zoals voedingswaarde, smaak en vergelijkbare recepten. Dit stelt gebruikers in staat om verschillende opties te verkennen en alternatieven te vinden die passen bij hun specifieke behoeften of dieetvereisten.
Het ontwerp van de datavisualisatietool is gericht op het bieden van een intuïtieve en gebruiksvriendelijke ervaring voor gebruikers. Door middel van de ontworpen functionaliteiten kunnen gebruikers op een effectieve en efficiënte manier recepten en ingrediënten verkennen, filteren, visualiseren en alternatieven identificeren.
#pagebreak()
= Evaluatie
In dit gedeelte wordt het ontwerp van de datavisualisatietool geëvalueerd aan de hand van een aantal criteria. Deze criteria zijn gebaseerd op de ontwerpeisen en de verwachtingen van de opdrachtgever en gebruikers.
Om het ontwerp te evalueren, wordt er gebruik gemaakt van een aantal evaluatiemethoden, waaronder functionele tests en prestatietests. Deze evaluatiemethoden zullen helpen bij het beoordelen van de effectiviteit en efficiëntie van het ontwerp.
== Testen en resultaten
=== Functionele tests
Er zijn uitgebreide tests uitgevoerd om ervoor te zorgen dat de datavisualisatietool naar behoren functioneert en voldoet aan de gestelde ontwerpeisen. Deze tests zijn uitgevoerd op zowel de frontend als de backend om de functionaliteiten van de tool te controleren en te valideren. Aan de frontend zijn verschillende functionele tests uitgevoerd om de gebruikersinterface te controleren en te valideren. Aan de backend zijn verschillende functionele tests uitgevoerd om de API-calls te controleren en te valideren. De resultaten van deze tests zijn weergegeven in de onderstaande tabellen.
#figure(
[
#table(
columns: (auto, auto, auto),
[Testcase], [Verwacht resultaat], [Werkt zoals verwacht?],
[Zoeken op naam], [Recepten met overeenkomende naam worden weergegeven], [Ja],
[Zoeken op ingrediënt], [Recepten met het opgegeven ingrediënt worden weergegeven], [Ja],
[Zoeken op voedingswaarde], [Recepten met de opgegeven voedingswaarde worden weergegeven], [N/A],
[Filteren op allergenen], [Recepten zonder de opgegeven allergenen worden weergegeven], [N/A],
[Filteren op categorie], [Recepten binnen de opgegeven categorie worden weergegeven], [N/A]
)
],
caption: "Functionele tests frontend",
supplement: "Tabel",
)
Bepaalde tests zijn niet uitgevoerd omdat de functionaliteit nog niet is geïmplementeerd. Deze tests zullen worden uitgevoerd zodra de functionaliteit is geïmplementeerd.
=== Gebruikersfeedback
Naast tests is er ook feedback verzameld van de opdrachtgever om inzicht te krijgen in de gebruikerservaring en de verwachtingen. De feedback is waardevol gebruikt om het ontwerp te verbeteren en de functionaliteiten aan te passen aan de behoeften van de gebruikers.
== Ontwerpbeoordeling
Het ontwerp van de datavisualisatietool is grondig geëvalueerd op basis van functionele tests en gebruikersfeedback. Hieronder volgt een beoordeling van het ontwerp:
- Functionaliteit: De uitgevoerde functionele tests hebben aangetoond dat de datavisualisatietool voldoet aan de gestelde ontwerpeisen. De zoekfunctionaliteit, filtermogelijkheden en visualisaties werken zoals verwacht en bieden gebruikers de mogelijkheid om op een intuïtieve manier recepten en ingrediënten te vinden en te analyseren.
- Gebruikerservaring: De feedback van de opdrachtgever is positief en geeft aan dat de gebruikersinterface overzichtelijk en gebruiksvriendelijk is. De visuele presentaties van recepten- en ingrediëntennetwerken zijn duidelijk en begrijpelijk, waardoor gebruikers waardevolle inzichten kunnen verkrijgen. De prestatietests hebben aangetoond dat de tool snel reageert en voldoet aan de verwachtingen qua laadtijd.
- Verbeterpunten: Tijdens de evaluatie zijn enkele verbeterpunten naar voren gekomen. Zo zijn bepaalde functionaliteiten nog niet geïmplementeerd en zullen deze in een latere fase worden getest. Daarnaast zijn er enkele suggesties gegeven om de gebruikerservaring verder te optimaliseren, zoals het verbeteren van de navigatie en het toevoegen van aanvullende functionaliteiten.
Op basis van de evaluatie kan geconcludeerd worden dat het ontwerp van de datavisualisatietool over het algemeen goed voldoet aan de gestelde ontwerpeisen en de verwachtingen van de gebruikers. Er zijn nog enkele verbeterpunten die kunnen worden doorgevoerd om de gebruikerservaring verder te versterken. Aanbevelingen voor toekomstig werk omvatten het implementeren van de ontbrekende functionaliteiten en het verder finetunen van de gebruikersinterface op basis van gebruikersfeedback.
#pagebreak()
= Bronnen
#align(left,
table(
columns: (auto, auto, auto),
rows: (auto, auto, auto),
align: left,
inset: 10pt,
stroke: none,
[*Bijlagen*], [], [],
[Hanzehogeschool Groningen logo], [Hanzehogeschool Groningen], [https://freebiesupply.com/logos/hanzehogeschool-groningen-logo/],
[Titelpagina figuur], [DALL-E-2, OpenAI], [bijlagen -> analyserapport -> OIG.jpg],
[Sequentiediagram 1], [<NAME>], [bijlagen -> analyserapport -> use_case_1.png],
[Sequentiediagram 2], [<NAME>], [bijlagen -> analyserapport -> use_case_2.png],
[Sequentiediagram 3], [<NAME>], [bijlagen -> analyserapport -> use_case_3.png],
)
) |
|
https://github.com/drupol/cv | https://raw.githubusercontent.com/drupol/cv/master/src/cv/common/lib.typ | typst | #import "metadata.typ": *
#import "@preview/fontawesome:0.4.0": *
#let languageItem(
lang: "",
level: "",
comment: ""
) = {
block(
grid(
columns: (1fr, 1fr),
align: (left, right),
)[
#text(weight: "bold", lang)
#box(width: 1fr, repeat[.])
][
#box(width: 1fr, repeat[.])
#text(fill: black.lighten(70%))[#level]
#text(fill: black.lighten(70%))[#comment]
],
)
}
#let educationEntry(
title: "",
school: "",
date: "",
type: "",
grade: "",
body,
) = {
set text(size: font-defaults.footnotesize)
block(
grid(
columns: (1fr, 4fr),
align: (left, left),
)[
#date\
#text(fill: black.lighten(70%))[#grade]
][
#grid(
columns: (1fr, 1fr),
align: (left, right),
text(weight: "bold", title), school,
)
#body
],
)
}
#let jobEntry(
title: "",
company: "",
location: "",
date: "",
type: "",
tags: (),
body,
) = {
block(
grid(
columns: (1fr, 5fr),
align: (left, left),
)[
#date\
#text(fill: black.lighten(70%))[#type]\
#text(fill: black.lighten(70%))[#location]
][
#if title != "" and company != "" {
grid(
columns: (1fr, 1fr),
align: (left, right),
text(weight: "bold", title), company,
)
}
#body
#{
set text(font: "New Computer Modern Mono", fill: black.lighten(60%))
grid(columns: (1fr), tags.join(" / "))
}
],
)
}
#let linkItem(body, icon: "") = {
block(
grid(
columns: (auto, auto),
column-gutter: .3em,
align: horizon,
box(width: 2em, height: 2em, fill: black)[
#{
set align(center + horizon)
fa-icon(icon, fill: white)
}
],
body,
),
)
}
#let customBox(
body,
title: "",
) = {
block(
grid(rows: 2)[
#{
block(fill: black, inset: .3em)[
#text(fill: white, size: font.large)[#upper(title)]
]
}
][
#v(.5em)
#body
],
)
}
#let featureBar(
title: "Skills",
value: 100%,
) = {
{
block()[
#grid(
columns: (1fr, 1fr),
column-gutter: 1em,
align: horizon,
align(right)[#title], line(stroke: .75em + black, length: value),
)
]
}
}
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-29.typ | typst | Other | // Test the `join` method.
#test(().join(), none)
#test((1,).join(), 1)
#test(("a", "b", "c").join(), "abc")
#test("(" + ("a", "b", "c").join(", ") + ")", "(a, b, c)")
|
https://github.com/PorterLu/Typst | https://raw.githubusercontent.com/PorterLu/Typst/main/formatting/typst_demo.typ | typst | #set par(justify: true, leading: 0.52em)
#set text(font: "New Computer Modern", size: 12pt)
#set page(paper: "a4", margin: (x: 1.8cm, y: 1.5cm))
Typst是一个新的文本编辑器,可以从某种程度上替代Latex,从文将记录笔者学习Typst的过程。在 www.typst.app 上,我们可以在左侧编辑文件,等待一段时间后右侧就会自动渲染完成。
= 1介绍
== 1.1 段落
在行首添加 = 可以使得文件变为标题,两个 = 可以开启二级标题,同时使用 ‘\_’ 可以开启强调 _强调_, _Emphasize_,现在发现中文的强调不是很明显。
添加一个段落需要加入一个空行即可,如果要列出小点,只需要使用在每一行使用'\+'即可,同时在可以使用'\-'列出子弹列表,例如列出宝可梦三原色,同时举例两只火系宝可梦:
+ 红
- 小火龙
- 帝君
+ 绿
+ 蓝
== 1.2 图片
#figure(
image("pikachu.png", width : 50%),
caption: [
A pikachu
],
) <pikachu>
我们使用 `#image` 函数可以添加一张图片。如果为图片添加一个标题,那么可以使用 `#figure` 函数,在`image`属性中添加图片,caption属性中添加标题,这时图片会默认居中。如果在 `figure` 最后使用 `<label_name>`, label_name就会成为这个图片的引用名,可以使用`@label_name`进行引用,如@pikachu。
== 1.3 引用
我们使用`#bibliography`函数添加一个`bib`文件,使用`#cite`函数进行具体引用,如 #cite("lee2019keystone")。
#bibliography("typst.bib")
== 1.4 数学公式
和其他工具一致,typst中使用`$$`可以开启行内公式,如$Q = rho A v + C$。为了使用行间公式,我们可以独立一行输入` $$ `,记得公式开头和末尾都加上空格。
$ 7.32 beta + sum_(i = 0)^nabla Q_i / 2 $
更多的数学公式写法可以参考typst的数学公式页面。
= 2 格式
== 2.1 规则(rule)
`#par(justify: true)[...]` 可以将其中的文字设置为每行都对齐,如果不想每次都使用一个括号将段落包裹,可以考虑使用规则的语法,使用`#set par(justify: true)`, 本文档已经使用了该对齐语法,可以看见每一行的长度都是相同的。
== 2.2 配置页面属性
有了规则语法后,下面是一些常用选项:
+ text:设置文本字体、大小、颜色等;
+ page:设置页面大小、边框、标头、列和注脚等;
+ par:设置行对齐和行间距等;
+ heading:设置标题和页号使能;
+ document:设置PDF输出的元数据,例如文章题目和作者。
本文的设置如下:
```
#set par(justify: true, leading: 0.52em)
#set text(font: "New Computer Modern", size: 12pt)
#set page(paper: "a4", margin: (x: 1.8cm, y: 1.5cm))
```
== 2.3 对齐
#align(center + bottom)[
#image("pikachu.png", width: 50%)
*A pikachu.*
]
通过使用`#align`可以设置图片的对齐模式,如上图中使用`#align(center + bottom)`。
== 2.4 加入一点复杂性
#set heading(numbering: "1.a")
= Big Title
== Normal Title
=== Small Title
通过`#set heading(number: "1.a")`, 可以设置标题前面标号的格式。
#set heading(numbering: none)
== 2.5 函数
#show "withPikachu": name => box[
#box(image(
"pikachu.png",
height: 2em,
))
#name
]
withPikachu 测试函数,这里我们通过`#show` 定义了一个函数可以每次输出固定字符串都自带一个图片。
|
|
https://github.com/Axot017/CV | https://raw.githubusercontent.com/Axot017/CV/master/modules_en/skills.typ | typst | #import "@preview/brilliant-cv:2.0.2": cvSection, cvSkill, hBar
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("Skills")
#cvSkill(
type: [Languages],
info: [Polish - native #hBar() English - B2 ]
)
#cvSkill(
type: [Tachnologies],
info: [
Java #hBar() Spring #hBar() Spock #hBar() MongoDB #hBar() Keycloak #hBar() Kafka #hBar()
Go #hBar() SQL (MySQL, PostgreSQL) #hBar() AWS #hBar() Terraform #hBar() Flutter #hBar() Git #hBar()
Rust #hBar() DynamoDB #hBar() Docker #hBar() Dart #hBar()
Firebase #hBar() Neovim #hBar() GitHub Actions #hBar() Postman
]
)
#v(6pt)
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/deltas-2.typ | typst | Other | #import "/lib/draw.typ": *
#import "deltas-1.typ": start, end, graph as delta-1, p2, p3, p5, arrow-line-size, arrow-head-scale, main-txt-size
#let arrow-color = yellow
#let ps = (p2, p3, p5)
#let graph = with-unit((ux, uy) => {
delta-1
let arrow-relative = (
(-300, -20),
(-300, 150),
(-300, -30),
)
for (s, r) in ps.zip(arrow-relative) {
arrow(s, r, relative: true, stroke: arrow-line-size * ux + arrow-color, head-scale: 1.5)
}
let p = p5.zip(arrow-relative.last()).map(((a, b)) => a + b)
txt([字宽压缩#linebreak()沿此移动], p, anchor: "cb", dy: 30)
})
#canvas(
end, start: start,
width: 40%,
graph,
)
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/dependency/i-figured.typ | typst | MIT License | #import "@preview/i-figured:0.2.4": * |
https://github.com/han0126/MCM-test | https://raw.githubusercontent.com/han0126/MCM-test/main/2024校赛typst/chapter/chapter1.typ | typst | = 问题重述
== 问题背景
在大学时代,参加各种学科竞赛是一种积极而富有意义的行为。这不仅是一种展示个人才华和专业知识的机会,更是一次锻炼和成长的过程。参加竞赛可以让学生在激烈的竞争中学会团队合作、解决问题的能力,并且通过与来自不同院校、不同背景的同学交流,拓展自己的视野,结交志同道合的朋友,建立起深厚的人际关系网络。因此,大学生积极参与学科竞赛,不仅是对自身能力的锻炼和提升,更是一种全面发展和自我实现的重要途径。通过竞赛,学生能够在学业上取得优异成绩,在人格上得到更深的塑造,为未来的发展奠定坚实的基础。由此,慎重地对大学生各种赛事的选择尤为重要,对大学生面临的各种竞赛赛事的评估和分析也成为值得深思的实际问题。
== 问题提出
本题给出了中国高等教育学会高校竞赛评估与管理体系研究专家工作组发布《2023全国普通高校大学生竞赛分析报告》中包含的13个普通本科院校大学生竞赛榜单、11个高职院校大学生竞赛榜单、3个省份大学生竞赛榜单。需根据各赛事的运营情况,确立评价标准和规则,建立分级条件并对数据进行处理分析,量化处理并建立模型,对各项赛事进行分级评价和排序。具体问题如下:
1. 对竞赛目录中的84项赛事进行筛选,选择合适的评价指标并对数据进行量化处理,最后对选取的赛事进行综合评价并分类。
2. 对进入观察目录的34项赛事进行评价指标的选取,并选择评价方法进行综合评价分析,预测出最有可能进入竞赛目录的赛事。
3. 根据设置的不同问卷数据,要求建立参赛的人数与每周理论和实践培训以及投入之间的数学模型。并针对建立的模型,推算讨论得到使得参加学生比例呈现最高水平的最佳的培训时间和投入。最后根据建模以及讨论的结果从综合应用价值和改进方式等方面给学校相关部门提出对应的建议和意见。 |
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/utils/outline-tools.typ | typst | MIT License | #import "states.typ": *
#import "../utils/fonts.typ": 字体, 字号
/*
这里有一个巨大的自造轮子用于显示目录。
由于 heading 跨页问题,如果使用 Typst 内置的目录,将导致页码显示错误、链接跳转锚点不正确。故仍使用自造轮子。
请查阅 `utils/show-heading.typ` 以查看 heading 跨页的其他影响 。如有更好的解决方案,欢迎给出建议或提交 PR。
*/
#let cn-outline(
outline-depth: 3,
base-indent: 1em,
first-level-spacing: none,
first-level-font-weight: "regular",
show-self-in-outline: true,
item-spacing: 14pt,
use-raw-heading: false,
) = [
#set text(font: 字体.宋体, size: 字号.小四)
#set par(leading: item-spacing, first-line-indent: 0pt)
#locate(loc => {
let elems = query(heading.where(outlined: true), loc)
for el in elems {
let el_real_loc = query(selector(<__heading__>).after(el.location()), el.location()).first().location()
let outlineline = {
if (el.level == 1) {
v(if first-level-spacing != none {first-level-spacing} else {item-spacing} - 1em)
// 一级标题前更长的空间
}
h((el.level - 1) * 2em + base-indent)
if el.level == 1 {
set text(weight: first-level-font-weight)
if chapter-numbering-show-state.at(el_real_loc) != none {
chapter-numbering-show-state.at(el_real_loc)
h(0.5em)
}
if use-raw-heading {
chapter-name-str-state.at(el_real_loc)
} else {
chapter-name-show-state.at(el_real_loc)
}
} else if el.level <= outline-depth and chapter-numbering-show-state.at(el_real_loc) != none {
chapter-numbering-show-state.at(el_real_loc)
h(0.3em)
chapter-name-show-state.at(el_real_loc)
} else {continue}
box(width: 1fr, h(10pt) + box(width: 1fr, repeat[.]) + h(10pt))
chapter-page-number-show-state.at(el_real_loc)
linebreak()
}
link(el_real_loc)[#outlineline]
}
})
] |
https://github.com/optimizerfeb/MathScience | https://raw.githubusercontent.com/optimizerfeb/MathScience/main/personal/fast_exp/문서.typ | typst | #set text(font: "KoPubDotum_Pro")
#set page(paper: "a4", margin: 5%)
$x, y$ 는 $e^x = y$ 를 만족하는 Float32 타입의 수, $i, j$ 는 각각 $x, y$ 의 각 비트를 보존한 채 Int32 로 인식시킨 수라고 하자. $b in [0, 1]$ 일 때 $log_2 (1 + b)$ 를 $b + 0.0573$ 으로 근사시킬 수 있으므로
$
x &= ln y\
&= (log_2 y) / (log_2 e)\
&tilde.eq 1 / (log_2 e) [2^(-23)j - 127 + 0.0573]\
$
이다. 우변을 정리하여
$
2^(23) (x log_2 e + 127 - 0.0573) = j
$
을 얻을 수 있다. 따라서,
$
y tilde.eq "* ( Float32 * ) " (2^(23) (x log_2 e + 127 - 0.0573) "as Int32")
$
이다. 이제 $x, y$ 가 Float64 타입이라 하면
$
x tilde.eq 1 / (log_2 e) [2^(-52)j - 1023 + 0.0573]\
$
이므로
$
y tilde.eq "* ( Float64 * ) " (2^(52) (x log_2 e + 1023 - 0.0573) "as Int64")
$
이다. 이러한 방법으로 지수를 계산하는 함수를 다음 페이지에서 작성해 보았다.
#pagebreak()
#align(center,
block(fill: rgb("f0f0f0"), outset: 2%, radius: 5%, width: 80%,
```rust
const mult32:f32 = 12102203.161561485;
const adder32: f32 = 1064872507.1615615;
const mult64:f64 = 6497320848556798.0;
const adder64: f64 = 4606924340207518000.0;
fn fast_exp32(x: f32) -> f32 {
union U {
f: f32,
i: i32,
}
unsafe {
let mut u = U { f: x };
u.i = (u.f * mult32 + adder32) as i32;
u.f
}
}
fn fast_exp64(x: f64) -> f64 {
union U {
f: f64,
i: i64,
}
unsafe {
let mut u = U { f: x };
u.i = (u.f * mult64 + adder64) as i64;
u.f
}
}
```
)
)
#pagebreak()
$x$ 를 $1$ 에서 $701$ 까지 $0.1$ 씩 증가시켜서 ``` fast_exp64``` 를 계산하여 얻은 오차는 아래와 같다.
```
e^1 : trad = 3.00416602e0, fast = 3.05932909e0, error = 9.81968901e-1
e^101 : trad = 8.07555019e43, fast = 8.02456026e43, error = 1.00635423e0
e^201 : trad = 2.17080249e87, fast = 2.12590311e87, error = 1.02112014e0
e^301 : trad = 5.83537138e130, fast = 5.93651567e130, error = 9.82962348e-1
e^401 : trad = 1.56861618e174, fast = 1.59051345e174, error = 9.86232580e-1
e^501 : trad = 4.21662405e217, fast = 4.14155986e217, error = 1.01812462e0
e^601 : trad = 1.13347794e261, fast = 1.12837100e261, error = 1.00452594e0
e^701 : trad = 3.04692148e304, fast = 3.10776457e304, error = 9.80422233e-1
Deviation : 0.01791137, Min_error : -0.01974522 at 521, Max_error : 0.04048682 at 520
```
$x = 88$ 에 대해 32 비트 지수 계산을 100000회, $x = 400$ 에 대해 64 비트 지수 계산을 100000회 반복하는데 소요된 시간은 다음과 같다.
```
test fast_exp32 ... bench: 465,635 ns/iter (+/- 75,791)
test fast_exp64 ... bench: 467,780 ns/iter (+/- 30,638)
test trad_exp32 ... bench: 624,230 ns/iter (+/- 53,545)
test trad_exp64 ... bench: 672,160 ns/iter (+/- 188,869)
```
사용된 시스템 : AMD Ryzen 5 5800X, 32GB DDR4-3200, Windows 11, Rust 1.73.0 |
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/typstfmt/84-ws-text-code.typ | typst | Apache License 2.0 | #let f() = []
a#sym.RR
a#f()
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PreventivoSprint/OttavoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": prospettoOrario, prospettoEconomico, glossary
== Ottavo #glossary[sprint]
*Inizio*: Venerdì 12/01/2024
*Fine*: Giovedì 18/01/2024
#prospettoOrario(sprintNumber: "8")
#prospettoEconomico(sprintNumber: "8") |
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/118.%20nthings.html.typ | typst | nthings.html
The List of N Things
September 2009I bet you the current issue of Cosmopolitan has an article
whose title begins with a number. "7 Things He Won't Tell You about
Sex," or something like that. Some popular magazines
feature articles of this type on the cover of every
issue. That can't be happening by accident. Editors must know
they attract readers.Why do readers like the list of n things so much? Mainly because
it's easier to read than a regular article.
[1]
Structurally, the list of n things is a degenerate case of essay.
An essay can go anywhere the writer wants. In a list of n things
the writer agrees to constrain himself to a collection of points
of roughly equal importance, and he tells the reader explicitly
what they are.Some of the work of reading an article is understanding its
structure—figuring out what in high school we'd have called
its "outline." Not explicitly, of course, but someone who really
understands an article probably has something in his brain afterward
that corresponds to such an outline. In a list of n things, this
work is done for you. Its structure is an exoskeleton.As well as being explicit, the structure is guaranteed to be of the
simplest possible type: a few main points with few to no subordinate
ones, and no particular connection between them.Because the main points are unconnected, the list of n things is
random access. There's no thread of reasoning you have to follow. You could
read the list in any order. And because the points are independent
of one another, they work like watertight compartments in an
unsinkable ship. If you get bored with, or can't understand, or
don't agree with one point, you don't have to give up on the article.
You can just abandon that one and skip to the next. A list of n
things is parallel and therefore fault tolerant.There are times when this format is what a writer wants. One, obviously,
is when what you have to say actually is a list of n
things. I once wrote an essay about the mistakes that kill startups, and a few people made fun of me
for writing something whose title began with a number. But in that
case I really was trying to make a complete catalog of a number of
independent things. In fact, one of the questions I was trying to
answer was how many there were.There are other less legitimate reasons for using this format. For
example, I use it when I get close to a deadline. If I have to
give a talk and I haven't started it a few days beforehand, I'll
sometimes play it safe and make the talk a list of n things.The list of n things is easier for writers as well as readers. When
you're writing a real essay, there's always a chance you'll hit a
dead end. A real essay is a train of thought, and some trains of
thought just peter out. That's an alarming possibility when you
have to give a talk in a few days. What if you run out of ideas?
The compartmentalized structure of the list of n things protects
the writer from his own stupidity in much the same way it protects
the reader. If you run out of ideas on one point, no problem: it
won't kill the essay. You can take out the whole point if you need
to, and the essay will still survive.Writing a list of n things is so relaxing. You think of n/2 of
them in the first 5 minutes. So bang, there's the structure, and
you just have to fill it in. As you think of more points, you just
add them to the end. Maybe you take out or rearrange or combine a
few, but at every stage you have a valid (though initially low-res)
list of n things. It's like the sort of programming where you write
a version 1 very quickly and then gradually modify it, but at every
point have working code—or the style of painting where you begin
with a complete but very blurry sketch done in an hour, then spend
a week cranking up the resolution.Because the list of n things is easier for writers too, it's not
always a damning sign when readers prefer it. It's not necessarily
evidence readers are lazy; it could also mean they don't have
much confidence in the writer. The list of n things is in that
respect the cheeseburger of essay forms. If you're eating at a
restaurant you suspect is bad, your best bet is to order the
cheeseburger. Even a bad cook can make a decent cheeseburger. And
there are pretty strict conventions about what a cheeseburger should
look like. You can assume the cook isn't going to try something
weird and artistic. The list of n things similarly limits the
damage that can be done by a bad writer. You know it's going to
be about whatever the title says, and the format prevents the writer
from indulging in any flights of fancy.Because the list of n things is the easiest essay form, it should
be a good one for beginning writers. And in fact it is what most
beginning writers are taught. The classic 5 paragraph essay is
really a list of n things for n = 3. But the students writing them
don't realize they're using the same structure as the articles they
read in Cosmopolitan. They're not allowed to include the numbers,
and they're expected to spackle over the gaps with gratuitous
transitions ("Furthermore...") and cap the thing at either end with
introductory and concluding paragraphs so it will look superficially
like a real essay.
[2]It seems a fine plan to start students off with the list of n things.
It's the easiest form. But if we're going to do that, why not do
it openly? Let them write lists of n things like the pros, with
numbers and no transitions or "conclusion."There is one case where the list of n things is a dishonest format:
when you use it to attract attention by falsely claiming the list
is an exhaustive one. I.e. if you write an article that purports
to be about the 7 secrets of success. That kind of title is the
same sort of reflexive challenge as a whodunit. You have to at least
look at the article to check whether they're the same 7 you'd list.
Are you overlooking one of the secrets of success? Better check.It's fine to put "The" before the number if you really believe
you've made an exhaustive list. But evidence suggests most things
with titles like this are linkbait.The greatest weakness of the list of n things is that there's so
little room for new thought. The main point of essay writing, when
done right, is the new ideas you have while doing it. A real essay,
as the name implies, is
dynamic: you don't know what you're going
to write when you start. It will be about whatever you discover
in the course of writing it.This can only happen in a very limited way in a list of n things.
You make the title first, and that's what it's going to be about.
You can't have more new ideas in the writing than will fit in the
watertight compartments you set up initially. And your brain seems
to know this: because you don't have room for new ideas, you don't
have them.Another advantage of admitting to beginning writers that the 5
paragraph essay is really a list of n things is that we can warn
them about this. It only lets you experience the defining
characteristic of essay writing on a small scale: in thoughts of a
sentence or two. And it's particularly dangerous that the 5 paragraph
essay buries the list of n things within something that looks like
a more sophisticated type of essay. If you don't know you're using
this form, you don't know you need to escape it.Notes[1]
Articles of this type are also startlingly popular on Delicious,
but I think that's because
delicious/popular
is driven by bookmarking,
not because Delicious users are stupid. Delicious users are
collectors, and a list of n things seems particularly collectible
because it's a collection itself.[2]
Most "word problems" in school math textbooks are similarly
misleading. They look superficially like the application of math
to real problems, but they're not. So if anything they reinforce
the impression that math is merely a complicated but pointless
collection of stuff to be memorized.Russian Translation
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-FB00.typ | typst | Apache License 2.0 | #let data = (
("LATIN SMALL LIGATURE FF", "Ll", 0),
("LATIN SMALL LIGATURE FI", "Ll", 0),
("LATIN SMALL LIGATURE FL", "Ll", 0),
("LATIN SMALL LIGATURE FFI", "Ll", 0),
("LATIN SMALL LIGATURE FFL", "Ll", 0),
("LATIN SMALL LIGATURE LONG S T", "Ll", 0),
("LATIN SMALL LIGATURE ST", "Ll", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("ARMENIAN SMALL LIGATURE MEN NOW", "Ll", 0),
("ARMENIAN SMALL LIGATURE MEN ECH", "Ll", 0),
("ARMENIAN SMALL LIGATURE MEN INI", "Ll", 0),
("ARMENIAN SMALL LIGATURE VEW NOW", "Ll", 0),
("ARMENIAN SMALL LIGATURE MEN XEH", "Ll", 0),
(),
(),
(),
(),
(),
("HEBREW LETTER YOD WITH HIRIQ", "Lo", 0),
("HEBREW POINT JUDEO-SPANISH VARIKA", "Mn", 26),
("HEBREW LIGATURE YIDDISH YOD YOD PATAH", "Lo", 0),
("HEBREW LETTER ALTERNATIVE AYIN", "Lo", 0),
("HEBREW LETTER WIDE ALEF", "Lo", 0),
("HEBREW LETTER WIDE DALET", "Lo", 0),
("HEBREW LETTER WIDE HE", "Lo", 0),
("HEBREW LETTER WIDE KAF", "Lo", 0),
("HEBREW LETTER WIDE LAMED", "Lo", 0),
("HEBREW LETTER WIDE FINAL MEM", "Lo", 0),
("HEBREW LETTER WIDE RESH", "Lo", 0),
("HEBREW LETTER WIDE TAV", "Lo", 0),
("HEBREW LETTER ALTERNATIVE PLUS SIGN", "Sm", 0),
("HEBREW LETTER SHIN WITH SHIN DOT", "Lo", 0),
("HEBREW LETTER SHIN WITH SIN DOT", "Lo", 0),
("HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT", "Lo", 0),
("HEBREW LETTER SHIN WITH DAGESH AND SIN DOT", "Lo", 0),
("HEBREW LETTER ALEF WITH PATAH", "Lo", 0),
("HEBREW LETTER ALEF WITH QAMATS", "Lo", 0),
("HEBREW LETTER ALEF WITH MAPIQ", "Lo", 0),
("HEBREW LETTER BET WITH DAGESH", "Lo", 0),
("HEBREW LETTER GIMEL WITH DAGESH", "Lo", 0),
("HEBREW LETTER DALET WITH DAGESH", "Lo", 0),
("HEBREW LETTER HE WITH MAPIQ", "Lo", 0),
("HEBREW LETTER VAV WITH DAGESH", "Lo", 0),
("HEBREW LETTER ZAYIN WITH DAGESH", "Lo", 0),
(),
("HEBREW LETTER TET WITH DAGESH", "Lo", 0),
("HEBREW LETTER YOD WITH DAGESH", "Lo", 0),
("HEBREW LETTER FINAL KAF WITH DAGESH", "Lo", 0),
("HEBREW LETTER KAF WITH DAGESH", "Lo", 0),
("HEBREW LETTER LAMED WITH DAGESH", "Lo", 0),
(),
("HEBREW LETTER MEM WITH DAGESH", "Lo", 0),
(),
("HEBREW LETTER NUN WITH DAGESH", "Lo", 0),
("HEBREW LETTER SAMEKH WITH DAGESH", "Lo", 0),
(),
("HEBREW LETTER FINAL PE WITH DAGESH", "Lo", 0),
("HEBREW LETTER PE WITH DAGESH", "Lo", 0),
(),
("HEBREW LETTER TSADI WITH DAGESH", "Lo", 0),
("HEBREW LETTER QOF WITH DAGESH", "Lo", 0),
("HEBREW LETTER RESH WITH DAGESH", "Lo", 0),
("HEBREW LETTER SHIN WITH DAGESH", "Lo", 0),
("HEBREW LETTER TAV WITH DAGESH", "Lo", 0),
("HEBREW LETTER VAV WITH HOLAM", "Lo", 0),
("HEBREW LETTER BET WITH RAFE", "Lo", 0),
("HEBREW LETTER KAF WITH RAFE", "Lo", 0),
("HEBREW LETTER PE WITH RAFE", "Lo", 0),
("HEBREW LIGATURE ALEF LAMED", "Lo", 0),
)
|
https://github.com/ren-ben/typst-notes | https://raw.githubusercontent.com/ren-ben/typst-notes/master/physics/art/master.typ | typst | #align(center, text(24pt)[
*Spezielle & Generelle Relativitätstheorie*
])
#align(center)[
<NAME> \
Technologisches Gewerbemuseum \
#link("mailto:<EMAIL>")
]
#show: rest => columns(2, rest)
#import "@preview/physica:0.9.2": *
#set heading(numbering: "1.")
#show par: set block(spacing: 0.65em)
#set par(
first-line-indent: 1em,
justify: true,
)
= Einführung
== Der Streit
Der Streit zwischen der klassichen Mechanik und dem Elektromagnetismus bezieht sich darauf, dass aus den Maxwell-Gleichungen die Wellengleichung erstellt werden kann:
#set align(center)
$ div E = 0 \
curl B = epsilon_0 mu_0 pdv(E,t) \
curl E = -pdv(B,t) \ \ \
curl (curl E) = curl (- pdv(B,t)) \
grad(div E ) - laplacian E = - pdv(,t) (curl B) \
grad(div E ) - laplacian E = - epsilon_0 mu_0 pdv(E,t,2) \
0 - laplacian E = - 1/c^2 pdv(E,t,2) \
1/c^2 pdv(E,t,2) - laplacian E = 0
$
#set align(start)
Das Problem erscheint, weil hier die Lichtgeschwindigkeit $c$ als eine Konstante betrachtet wird ($c=1/(sqrt(mu_0 epsilon_0))$) was die Physiker damals verwirrt hat, weil die Theorie von Galileo, die klassische Mechanik davon überzeugt war, dass beispielsweise die Geschwindigkeit eines Balles relativ zu einem Bezugsystem $x'$ und $y'$ bei $v-v'$ liegt, was aber bei einer Konstante nicht möglich ist. Außerdem ist sich die klassische Mechanik ziemlich sicher, dass eine absolute Geschwindigkeit nicht existiert, also muss es ein Weg geben, $v-v'$ im Bezug auf die Lichtgeschwindigkeit auszudrücken. Die Physiker des 20ten Jahrhunderts haben nach verschiedenen Lösungen wie Ether gesucht. Schlussendlich kamen sie auf die Relativitätstheorie, mit der sich dieser Paper beschäftigt.
== Galileo's Transformationen
Einstein war der erste Physiker, der nicht den Elektromagnetismus in Frage stellte, sondern die klassische Mechanik. Galileo fand raus, dass Zeit absolut ist ($t=t'$). Die $x'$ Koordinate ist $x'=x-v' t$. Wenn wir jetzt die Ableitung nehmen: $dv(x',t)=dot(x')=dot(x) - v'$ wobei $dot(x')$ ist die Geschwindigkeit des Balles die aus dem Bezugsystem $x'$ und $y'$ gemessen wird. Wie später im Detail besprochen wird, hat Einstein valide Argumente geformt, die auf ein Fehler in diesen Transformationen angedeutet haben.
#figure(
image("images/galilean_transform.jpeg", width: 80%),
caption: [
Bezugsystem in Galileo's Transformationen
],
)
= Lorentz Transformationen
== Ableitung
#figure(
image("images/lorentz_derivation.svg", width: 50%),
caption: [
Plot der Lichtgeschwindigkeit $times$ Zeit
],
)
Bevor es mit Lorentz Transformationen weitergehen kann, muss zuerst das Prinzip der Gleichzeitigkeit erwähnt werden.
=== Gleichzeitigkeit
Gleichzeitigkeit bezeichnet die Eigenschaft von zwei Ereignissen, dass sie zur gleichen Zeit auftreten. Im Kontext der Physik, insbesondere in der speziellen Relativitätstheorie, wird Gleichzeitigkeit relativ interpretiert, was bedeutet, dass sie von der Perspektive des Beobachters abhängt, der die Ereignisse beobachtet.
#figure(
image("images/simultaneous.svg", width: 70%),
caption: [
Person $A$ und Person $B$ senden jeweils ein Lichtstrahl zum Mittelpunkt
]
) <gleich>
Grundsätzlich wenn es keine Bewegung bei der @gleich gibt kommen die Lichtstrahle gleichzeitig an. Wenn das Senden jedoch während einer Bewegung durchgeführt wird, kommen sie nicht gleichzeitig an.
#figure(
image("images/refframesim2.svg", width: 50%),
caption: [
$B$ & $A$ senden Lichtstrahle und bewegen sich mit $v$
]
)
Person B sendet den Lichtstrahl in die entgegengesetzte Richtung, was die Geschwindigkeit von $-c$ beträgt. Der Schnittpunkt mit der $B$-Funktion passiert später als der Schnittpunkt mit der $A$-Funktion was bedeutet, dass Person $B$ den Lichtstrahl später senden sollte, damit sie sich gleichzeitig treffen. Dieses Ergebnis ist ist intuitiv, wenn man die Geschwindigkeit $v$ in Acht nimmt, mit der sich die beiden Personen bewegen. Aus einem anderen Bezugsystem würde sich rausstellen, dass die Beiden Lichtstrahle tatsächlich gleichzeitig ankommen.
Die Gleichung für die Linie mit der Steigung von $-c$ lautet
#set align(center)
#figure(
$x=-c(t-t_A) + x_A$
)
#set align(start)
Jetzt müssen die Koordinate des Punktes $A$ gefunden werden (Schnittpunkt des Mittelpunktes und der Lichtstrahle).
#set align(center)
#figure(
$cases(x=v t+a, x=c t)$
)
#set align(start)
($a$ ist die Distanz zwischen $x=0$ und dem Mittelpunkt)
#set align(center)
#figure(
$x=-c(t-a/(c-v)) + (a c)/x-v \
cases(x=-c(t-a/(c-v)) + (a c)/x-v, x=v t + 2a) \
t_B = (2 a v)/(c^2-v^2) \
x_B = (2 a c)/(c^2-v^2) \
x_B/t_B = c^2/v |-> x/t = c^2/v |-> x=c^2/v t$
)
#set align(start)
=== Beziehung zwischen $x$ und $x'$
Wie wir wissen, hat $x$ eine Beziehung zu $x'$ und die kann durch eine Differenz zwischen $x$ und $v t $ multipliziert mit einer Konstante $gamma$ dargestellt werden.
#set align(center)
#figure(
$x' = 0, x = v t -> x' = gamma times (x - v t)$
)
#set align(start)
Für $t'$ ist die Situation sehr ähnlich
#set align(center)
#figure(
$t' = 0, t = v/c^2x -> t' = gamma' times (t - v/c^2x)$
)
#set align(start)
Daraus können folgende Beziehung aufgezeichnet werden
#set align(center)
#figure(
$x=gamma times (x' + v t) \ t = gamma' times (t' + v/c^2x)$
)
#set align(start)
Durch das Substitutionsverfahren kann alles auf $x'$ und $t'$ umgewandlet werden.
#set align(center)
#figure(
$x'=gamma [gamma (x'+v t') - gamma' v (t'+v/c^2x')] \ = gamma^2 x' + gamma^2v t'-gamma gamma' v t' - gamma gamma' v^2/c^2x' \ =(gamma^2 - gamma gamma' v^2/c^2)x' + (gamma^2 v-gamma gamma' v) t'$
)
#set align(start)
Weil alles gleich $x'$ ist, muss der erste Term $(gamma^2-gamma gamma' v^2/c^2)$ gleich eins sein und der zweite Term gleich null sein.
#figure(
$gamma^2 - gamma^2 v/c^2 = 1 -> gamma^2 = 1 / (1-v^2/c^2) -> gamma = plus.minus 1/sqrt(1-v^2/c^2) \ $
)
#set align(start)
Dementsprechend kann $gamma$ (auch Lorentzfaktor oder $beta$ genannt) ebenfalls substituiert werden und damit bekommen wir die Lorentz Transformationen
#set align(center)
#figure(
$cases(x'= (x-v t)/sqrt(1-v^2/c^2), t'= (t-v/c^2 x)/sqrt(1-v^2/c^2))$
)
#set align(start)
Durch weitere Berechnungen, kann auf die Lorentz-Invarianz draufgekommen werden. Diese wird nicht durch die Lorentz-Transformation beeinflusst. Es ist eine Einheit die sich nicht verändert.
#set align(center)
#figure(
$x'^2-c^2t'^2 = x^2-c^2 t^2$
)
#set align(start)
Man kann außerdem die Lorentz-Transformationen aus der Lorentz Invarianz Ableiten.
=== Geschwindigkeitskompositionen
Ein statischer Beobachter ($x$, $t$) sieht ein fahrendes Auto ($x'$, $t'$) wo drinnen ein Ball nach vorne geschmissen wird ($x''$, $t''$). Gallileo würde sagen, dass $t=t'=t''$ und dass die Geschwindigkeit des Balles gleich der Geschwindigkeit des Balles im Auto ($w$) minus der Geschwindigkeit des Autos ($v$) (wenn der Beobachter das Inertialsystem ist). Wenn wir jetzt aber mit Lorentz-Transformationen von $x$ auf $x'$ umsteigen wollen, gilt wie bereits erwähnt $x'=(x-v t)/sqrt(1-v^2/c^2)$ oder einfach $x'=x-v t beta(v)$ wenn wir annehmen, dass $beta(v)=1/(sqrt(1-v^2/c^2))$. Außerdem ist $t'=(t-v/c^2 x)beta(v)$. Wichtig ist auch das Inverse davon:
#figure(
$ cases(x = (x'+v t')beta(v), t = (t' + v/c^2 x') beta(v)) $,
caption: [
Gleichung 1
]
) <Gleichung1>
Wie kommt man aber auf $x''$ von $x$?
Ganz einfach, wie bereits erwähnt bewegt sich der Ball mit einer Geschwindigkeit von $w$ und das Auto mit einer Geschwindigkeit von $v$. Also müssen wir einfach folgendes tun:
#figure(
$ cases(x''=(x-w t)beta(w), t''=(t-w/c^2 x)beta(w)) $,
caption: [
Gleichung 2
]
) <Gleichung2>
Was wir jetzt finden wollen ist die folgende Beziehung: $(x',t') <-> (x'', t'')$. Wir wissen aus @Gleichung1 was $x$ gleich ist mittels $x'$ und $t'$ und somit müssen wir nur @Gleichung1 in @Gleichung2 substituieren. Das bedeutet wir ersetzen $x$ in der @Gleichung2 mit $(x'+v t')beta(v)$ usw. Nach ein wenig Algebra kommen wir auf
#figure(
$ cases(x'' = beta(v)beta(w)[x'(1-(w v)/c^2) - t' (w-v)], t'' = beta(v)beta(w)[t'(1-(w v)/c^2)-x'/c^2(w-v)]) $,
caption: [
Gleichung3
]
) <Gleichung3>
Wir könnten es aber in eine andere Art und Weise aufschreiben. Wenn wir die relative Geschwindigkeit zwischen dem Fahrer und dem Ball $u$ bennenen, können wir die folgenden Gleichungen aufstellen:
#figure(
$ cases(x''=(x'-u t') beta(u), t'' = (t'-u/c^2 x') beta(u)) $,
caption: [
Gleichung 4
]
) <Gleichung4>
Daraufhin können wir @Gleichung3 und @Gleichung4 gleich setzen weil sie beide Gleich $x''$ bzw. Gleich $t''$ sind. Somit können wir folgendes aufstellen:
#figure(
$ cases(beta(u) = beta(v)beta(w)((1-w v)/c^2), u beta(u) = beta(v)beta(w) (w-v)) $
)
Was wir jetzt noch machen müssen ist die obere Gleichung mit der Unteren zu dividieren. Wir kommen auf ein interessantes Ergebnis:
#figure(
$ u = (w - v)/(1- (w v)/c^2) $
)
Dies ist eine generalisierung der Galileo-Transformationen ($u=w-v$). Das bedeutet, wir können Lorentz-Transformationen aus Galileo-Transformationen herausfinden.
#figure(
image("images/lorentz_vel.svg", width: 50%),
caption: [
Beispiel des Zebrechens der Galileo-Transformationen
]
)
Wenn wir jetzt ein Lichtstrahl haben der nach links vom Inertialsystem kehrt und ein Lichtstrahl der nach rechts kehrt werden und die Galileo-Transformationen folgendes sagen:
#figure(
$ u = c - (-c) = 2c $
)
Was nicht möglich ist weil nichts schneller als $c$ sein kann. Probieren wir Lorentz-Transformationen aus:
#figure(
$ u = (2 c)/(1-(-c^2)/c^2) = (2 c)/(1 + c^2/c^2) = (2 c)/(2) = c $
)
Bingo! Genau das was uns Relativität zeigt. Nichts kann schneller als Licht sein.
== Längenkontraktion und Zeitdilatation
Dies sind zwei wichtige Bestandteile der speziellen Relativitätstheorie. Wir nehmen an, es gibt ein Objekt mit der Länge $l -> (x,t)$ und wir wollen die Länge im Bezugsystem $(x',t') -> l'$ messen. Die Koordinaten von $l$ sind $x_1$ und $x_2$ auf dem Plot:
#figure(
image("images/lcontraction.svg", width: 50%),
caption: [
Längenkontraktion Beispiel
]
)
Die Länge kann durch $x_2-x_1$ berechnet werden. Mit Lorentz-Transformationen kommen wir auf Zwei Gleichungen wenn wir auf $(x',t')$ wächseln:
#figure(
$ x'_2 = (x_2-v t_0)/(sqrt(1-v^2/c^2)) space , space x'_1 = (x_1-v t_0)/sqrt(1-v^2/c^2) $
)
Jetzt können wir die Beiden subtrahieren und bekommen:
#figure(
$ x'_2-x'_1 = (x_2-x_1)/(sqrt(1-v^2/c^2)) -> l'=l/sqrt(1-v^2/c^2) $
)
Weil der Lorentzfaktor $<1$ ist, ist $l' > l$.
Bei der Zeitdilatation nehmen wir eine stehende Person im Bezugsystem $(x,t) --> (x_1, t_1)$ und weil die Person steht werden ihre Koordinaten nach einiger Zeit $(x_1, t_1 + Delta t)$ betragen. Wir können also die folgende Gleichung benutzen:
#figure(
$ t'_1 = (t_1-v/c^2 x_1)/sqrt(1-v^2/c^2) \ t'_1
Delta t' = (t_1 + Delta t - v/c^2 x_1) / sqrt(1-v^2/c^2) \ Delta t' = (Delta t)/sqrt(1-v^2/c^2) -> Delta t' > Delta t$
)
=== Nicht-inertiale Systeme
Einfach erklärt ist die Geschwindigkeit zwischen den beiden Bezugsystemen nicht mehr konstant. Für deren Berechnung brauchen wir die Lorentz-Invarianz:
#figure(
$ x'^2-c^2 t'^2 = x^2-c^2 t^2 $
)
Für eine bessere Übersicht, müssen wir folgende Variable definieren:
#figure(
$ c^2t^2-x^2=s^2 $
)
Weil wir derzeit sehr kleine Raum- und Zeit-Abstände betrachten (wir schauen uns auch nur den ersten Zeitpunkt an), kann man $x$ und $t$ mit $d x$ und $d t$ ersetzen
#figure(
$ d s^2 = c^2 d t^2 - d x^2 $
)
Wenn man aber diese Aussage Integriert bekommt man sehr interessante Ergebnisse sowohl für Inertialsysteme als auch für Nicht-inertialsysteme.
Wir werden uns damit später beschäftigen, aber dazu braucht man noch ein Paar andere Definitionen:
#figure(
$ d tau = (d s)/c \ d s = c d tau \ d tau = sqrt(1 - v^2/c^2) d t$
)
= Lagrange-Formalismus
Wir haben einen Partikel der im Zeitraum sich bewegt (die Zeitdimension geht durch den Bildschirm)
#figure(
image("images/lagrangian_1.png", width: 50%)
)
Wenn wir den Abstand zwischen $tau_1$ und $tau_2$ berechnen wollen, gibt es die Newton'sche Art und Weise:
#figure(
$ tau_2 - tau_1 = integral^(tau_1)_tau_2 sqrt(1-v^2/c^2) space d t$
)
aber auch die Lagrang'sche Art und Weise:
#figure(
$ S = A = integral^(t_2)_t_1 L(arrow(x), dot(arrow(x)), t) space d t $
)
Hamilton sagt uns, dass wir die Aktion ($A$ oder $S$) minimieren müssen damit wir die Flugbahn bekommen können. Wir machen das indem wir die Flugbahn ändern, aber nicht die Endpunkte.
#figure(
$ delta S = integral^(t_2)_t_1 delta L (arrow(x), dot(arrow(x)), t) space d t = 0 $
)
Durch diese Formulation kann man die Euler-Lagrange-Gleichung ableiten:
#figure(
$ pdv(f,y,1) - d/(d x) pdv(f,y',1) = 0 $
)
Grundlegend ist $T$ die kinetische Energie, $V$ die potenzielle Energie und $U$ das Potenzial wobei $U=-V$.
== Lagrange - Spezielle Relativität
Zuerst sollten wir uns an die Invariaz erinnern:
#figure(
$ d s^2 = c^2 d t^2 - d x^2 $
)
Zur erinnerung, diese Invarianz beschreibt das Intervall zwischen zwei Ereignissen im Zeit-Raum. Wenn $d s^2 < 0$ haben wir ein Raumhaftes Intervall. Heißt, dass sie sich nicht beeinflüssen können und sind nicht Zeitlich verbunden. Wenn $d s^2 > 0$ dann ist das Intervall Zeithaft und kann sich zwischen den Ereignissen bewegen.Wenn $d s^2 = 0$ dann kann nur eine Lichtgeschwindigkeit die zwei Ereignisse verbinden.
Dazu definieren wir $d tau = (d s)/c$ noch einmal. (Invarianz dividiert durch die Lichtgeschwindigkeit). Dadurch, dass $|d arrow(x)|=V d t$ kann man durch einfache Algebra zu der folgenden Formel kommen:
#figure(
$ d tau = d t times sqrt(1- v^2/c^2) $
)
Jetzt wollen wir den Lagrangian erstellen.
#figure(
$ A = integral^(t_0)_(t_1) L d t $
)
Die eine Regel ist, dass alle Werte invariant sein müssen. Wir können zuerst $d t$ mit $d tau$ ersetzen. Den Lagrangian selbst zu ersetzen ist schwer. Man kann die Ruhemasse $m_0$ und $c$ nehmen. Weil $L = T - V$ und $T = 1/2 m_0 dot(x)^2$ können wir den folgenden Integral erstellen:
#figure(
$ A = integral - m_0 c^2 d tau $
)
Wir werden später sehen, wieso da ein minus ist und außerdem können wir $1/2$ weglassen weil es im grunde genommen nichts ausmacht. Fahren wir fort:
#figure(
$ delta A = delta integral - m_0 c^2 sqrt(1-v^2/c^2) d t = delta integral L d t $
)
Endlich haben wir unseren Lagrangian:
#figure(
$ L = -m_0 c^2 sqrt(1-v^2/c^2) $
)
=== Schwung in der SRT
Um zu klären, womit wir arbeiten: Wir haben einen einzigen Partikel mit der Ruhemasse $m_0$.
Der Schwung des Partikels ist $P_J = pdv(L,dot(x_J))$ welchen wir 3 Mal in jede Richtung ableiten können. Dazu sollte auch klar sein, dass $v^2 = dot(x^2 _1) + dot(x^2 _2) + dot(x^2 _3)$. Damit können wir lösen, was $P_J$ ist:
#figure(
$ P_J = -m_0 c^2 1/(2 sqrt(1-v^2/c^2)) (-2 v)/c^2 pdv(V,dot(x_J)) $
)
Zur Erinnerung: $pdv(V,dot(x_J)) = pdv(,dot(x_J)) sqrt(dot(x^2 _1) + dot(x^2 _2) + dot(x^2 _3))$ was gleich $1/(2 V) 2 dot(x)_J$ ist. Einfache Zusammensetzung (c^2 fällt weg, 2V fällt weg und 2 fällt weg) führt uns zum folgenden Ergebnis:
#figure(
$ P_J = (m_0 dot(x)_J)/sqrt(1-v^2/c^2) $
)
Manche Wissenschaftler definieren eine relative Masse ($m(v) = m_0/sqrt(1-v^2/c^2)$) und somit kann der Schwung in der SRT als eine klassische Definitio aufgeschrieben werden:
#figure(
$ P_J = m dot(x)_J $
)
=== E=mc2
$P_J$ ist sehr stark mit dem Hamiltonian verbunden. Weil $H= sum_J pdv(L, dot(x)_J) dot(x)_J - L$. Nach einer Substitution kommen wir zu der folgenden Formel:
#figure(
$ H = (m_0 sum_J dot(x)^2_J)/sqrt(1 - v^2/c^2) + m_0 c^2 sqrt(1-v^2/c^2) $
)
Nach ein wenig Algebra kommen wir zum folgenden Ergebnis:
#figure(
$ H = (m_0 c^2)/sqrt(1-v^2/c^2) $
)
Dadurch kann der klassische Hamiltonian herausgezogen werden (mittels der Taylor-Expansion):
#figure(
$ H approx m_0 c^2 + 1/2 m_0 V^2 -> H_(V=0) = m_0 c^2 $
)
Dies bedeutet, das der Hamiltonian (Energie) während der Partikel sich nicht bewegt ist die Ruhemasse mal $c^2$. Dies ist die berühmte Formel von Einstein:
#figure(
$ E=m c^2 $
)
= Generelle Relativitätstheorie
== Tensoren
=== Invarianz als ein Tensor
Schauen wir uns die Invarianz noch einman an:
#figure(
$ d s^2 = c^2 d t^2 - d x^2 - d y^2 - d z^2 $
)
Wenn man sich ein Koordinatensystem $(x^0, x^1, x^2, x^3)$ vorstellt, wo $x^0 = c t$, kann man die Invarianz flgendermaßen aufschreiben:
#figure(
$ d s^2 = d x^0 - (d x^1)^2 - (d x^2)^2 - (d x^3)^2 $
)
Wenn wir jetzt ein $4 x 4$ Matrix und ein Vektor mit den Koordinaten definieren
#figure(
$ eta_(mu nu) = mat(
1, 0, 0, 0;
0, -1, 0, 0;
0, 0, -1, 0;
0, 0, 0, -1;
)
d x^(mu) = vec(d x^0, d x^1, d x^2, d x^3)
$
)
können wir die Invarianz auf die folgende Art und Weise definieren:
#figure(
$ d s^2 = sum_mu sum_nu d x^mu d x^nu eta_(mu nu) $
)
Einstein hat aber gesagt, dass wenn wir wiederholende Indizes haben, können wir einfach sie summieren ohne den Summensymbolen:
#figure(
$ d s^2 = d x^mu d x^nu eta_(mu nu) $
)
=== Tensor-Transformationen
Wenn man die Invarianz von $g_(mu nu)$ zu $g_(alpha beta)$ verwandeln möchte, muss man folgend vorgehen:
#figure(
$ d s^2 = g_(mu nu) d x^(mu) d x^nu = g_(mu nu) pdv(x^mu, y^alpha) d y^alpha pdv(x^nu, y^beta) d y^beta \ = g_(alpha beta) d y^alpha d y^beta $
)
Das bedeutet, dass:
#figure(
$ g_(alpha beta) = g_(mu nu) pdv(x^mu, y^alpha) pdv(x^nu, y^beta) $
)
Sehr wichtig ist außerdem, dass kontravariante Tensor-Komponente sich mit dem Inversen des Jacobians transformieren lassen und kovariante Tensor-Komponente lassen sich mit dem Jacobian transformieren.
Ein kontravariantes Komponent $v^mu$ wird folgendermaßen verwandelt:
#figure(
$ x^(mu) = pdv(y^(mu), x^nu) x^nu $
)
Und ein kovariantes Komponent $w_mu$ wird so verwandelt:
#figure(
$ x_mu = pdv(x^nu, y^mu) x_nu$
)
Das würd folgendes im Fall von $F_(alpha beta)^(gamma delta)$ bedeuten:
#figure(
$ F_(alpha beta)^(gamma delta) (y^0, y^1, y^2, y^3) \ = F_(alpha' beta')^(gamma' delta' ) (x^0, x^1, x^2, x^3) pdv(x^alpha', y^alpha) pdv(x^beta', y^beta) pdv(y^delta, x^delta') pdv(y^gamma, x^gamma') $
)
Kontravariante Tensor-Komponente beschreiben den Absolutwert (Größe) und die Richtung im Raum. Beispielsweise Geschwindigkeit.
Kovariante Tensor-Komponente beschreiben die geometrie im Raum, beispielsweise Gradiente oder Ableitungen.
=== Lower-Rank Tensor zu Higher-Rank Tensor
Wenn man zwei Lower-Rank Tensoren miteinander multipliziert bekommt man einen Higher-Rank Tensor:
Sagen wir, dass wir den Tensor $V_mu^(1)$ und $V_nu^(1)$ wobei 1 der Index ist.
#figure(
$ V_mu^(1) V_nu^(1) = mat(1;0;0;0) mat(1,0,0,0) = mat(1, 0, 0, 0 ; 0, 0, 0, 0 ; 0, 0, 0, 0) = V_(mu nu) $
)
|
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/ordered_list/ordered_list_updated.typ | typst | + The updated
+ The second |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/metro/0.2.0/src/metro.typ | typst | Apache License 2.0 | #import "defs/units.typ"
#import "defs/prefixes.typ"
#import "impl/impl.typ"
#import "utils.typ": combine-dict
#let _state-default = (
units: units._dict,
prefixes: prefixes._dict,
prefix-power-tens: prefixes._power-tens,
powers: (
square: impl.raiseto([2]),
cubic: impl.raiseto([3]),
squared: impl.tothe([2]),
cubed: impl.tothe([3])
),
qualifiers: (:),
// quantites
times: sym.dot,
// Unit
// Num
allow-breaks: false,
delimiter: " ",
)
#let _state = state("metro-setup", _state-default)
#let metro-reset() = _state.update(_ => return _state-default)
#let metro-setup(..options) = _state.update(s => {
return combine-dict(options.named(), s)
})
#let declare-unit(unt, symbol) = _state.update(s => {
s.units.insert(unt, symbol)
return s
})
#let create-prefix = math.class.with("unary")
#let declare-prefix(prefix, symbol, power-tens) = _state.update(s => {
s.prefixes.insert(prefix, symbol)
s.prefix-power-tens.insert(prefix, power-tens)
return s
})
#let declare-power(before, after, power) = _state.update(s => {
s.powers.insert(before, impl.raiseto([#power]))
s.powers.insert(after, impl.tothe([#power]))
return s
})
#let declare-qualifier(quali, symbol) = _state.update(s => {
s.qualifiers.insert(quali, impl.qualifier(symbol))
return s
})
#let unit(input, ..options) = _state.display(s => {
return impl.unit(input, ..combine-dict(options.named(), s))
})
#let num(number, e: none, pm: none, pw: none, ..options) = _state.display(s => {
return (impl.num(number, exponent: e, uncertainty: pm, power: pw, ..combine-dict(options.named(), s)))
})
#let qty(
number,
units,
e: none,
pm: none,
pw: none,
..options
) = _state.display(s => {
return impl.qty(
number,
units,
e: e,
pm: pm,
pw: pw,
..combine-dict(options.named(), s)
)
}) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/attach-04.typ | typst | Other | // Test associativity and scaling.
$ 1/(V^2^3^4^5),
1/attach(V, tl: attach(2, tl: attach(3, tl: attach(4, tl: 5)))),
attach(Omega,
tl: attach(2, tl: attach(3, tl: attach(4, tl: 5))),
tr: attach(2, tr: attach(3, tr: attach(4, tr: 5))),
bl: attach(2, bl: attach(3, bl: attach(4, bl: 5))),
br: attach(2, br: attach(3, br: attach(4, br: 5))),
)
$
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/visual-more-than-rect.typ | typst | #import "base-utils.typ": *
#let get(x) = {
let ref = (
"*": sym.times,
"times": sym.times,
"+": sym.plus,
"plus": sym.plus,
)
return ref.at(x, default: x)
}
#let attrs = (
width: 100pt,
)
#let table-attrs = (
columns: 5,
gutter: 5pt,
stroke: none,
inset: 0pt,
)
#let visual-more-than-rect() = {
// this has to happen in the context of cetz.
let hb = k * h1
let ha = h1 - hb
let a = rect(p.origin, (size, h1), ..d1)
let a-stroked = rect((0, ha), (size, h1), ..d2)
let b = rect((gap, 0), (gap + size, h2), ..d3)
let b-stroked = rect((gap, h2), (gap + size, h2 + hb), ..d4)
arrow
c-arrow
a
b
a-stroked
b-stroked
}
// inoreab ls (it) => {
// $c
// }
#let booga(a, n, delimiter, ending: none, equals: none) = {
// takes a numeric term and repeats it n times
// joining it with the delimiter provided
let delimiter = get(delimiter)
let val = str(a)
let s = ""
for i in range(n) {
s += val
if i == n - 1 {
let value = if delimiter == sym.plus { a * n } else { calc.pow(a, n) }
return if exists(ending) {
s + templater(ending, value)
} else if exists(equals) {
s + " = " + str(value)
} else {
s
}
} else {
s += " " + delimiter + " "
}
}
}
#let interweave(a, n, delimiter, equals: none) = {
// takes a numeric term and repeats it n times
// joining it with the delimiter provided
let delimiter = get(delimiter)
let base = (($#a$,) * n).join($space #delimiter space$)
if equals != none {
let value = if delimiter == sym.plus { a * n } else { calc.pow(a, n) }
let ending = if is-string(equals) {
markup(templater(" " + equals.trim(), value))
} else {
equals(value)
}
return base + ending
}
return base
}
#let to-number(x) = {
return int(x)
}
#let content-templater(template, ..sink) = {
let ref = sink.named()
let items = split(template, "\s+")
let runner(part) = {
if test(part, "^\$") {
let value = ref.at(part.slice(1))
return if is-function(value) {
value()
} else {
value
}
} else {
return text(part)
}
}
let parsed = items.map(runner)
return parsed.join(" ")
}
#let ExponentGenerator(..a) = {
let args = a.pos()
let numbers = if args.len() == 2 {
args
} else {
split(args.first(), "\^")
}
let (base, power) = numbers.map(to-number)
let expand() = {
return interweave(base, power, "times")
}
let value() = {
return text(str(calc.pow(base, power)))
}
let expr() = {
return [$#base^#power$]
}
let state = (
expand: expand,
equals: $space = space$,
value: value,
expr: expr,
)
let templater = content-templater.with(..state)
state.insert("templater", templater)
let definition() = {
return templater("$expr means $expand")
}
state.insert("definition", definition)
return templater
return state
}
#{
// let templater = ExponentGenerator(3, 4)
// let boxy = (..items) => box(..attrs, table(..table-attrs, ..items))
// let small-box = (content) => box(
// width: 80pt,
// text(size: 6pt, content)
// )
}
#let boxed-interweave(a, b, c, equals: none) = {
let small-box = (content) => box(
width: b * 3pt,
baseline: 100%,
par(justify: true, text(size: 7pt, content))
)
return small-box(interweave(a, b, c, equals: equals))
}
// #boxed-interweave(2, 70, "+", equals: "\= *$1*?")
// #block(width: 200pt, fill: yellow)[
// how did you do that so fast? did you do #booga(2, 140, "+", equals: true)?
//
// no. i did $2 times 70$.
//
// wow kaylee.
//
// i know. im smart
// ]
#let first = {
for i in step(4) {
let base = ExponentGenerator(10, i)
let a = base("$expr $equals $expand")
a
linebreak()
}
}
#let second = include("decimal-shift.typ")
#let second = eval(read("decimal-shift.typ"), mode: "markup")
#table(first, second)
the space and stuff will be handled explicitly
what does and doesnt define a content block is so interesting
one of the most interesting languages i have ever used
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/methods-05.typ | typst | Other | // Error: 2:3-2:19 cannot mutate a temporary value
#let numbers = (1, 2, 3)
#(numbers.sorted() = 1)
|
https://github.com/kunalchandan/resume | https://raw.githubusercontent.com/kunalchandan/resume/main/resume.typ | typst | #set page(
// fill: rgb("222222"),
margin: (
x : 2.5em,
y : 2em,
)
)
// #set text(fill: rgb("fdfdfd"))
#import "conf.typ": page_heading, experience, accent_1, accent_10, heading_font_size, main_font_size
#set text(font: ("Jost"), weight: "light", size: main_font_size,)
#set list(marker: ([--], [-]))
#show heading: it => {
if it.level == 1 {
text(
weight: "medium",
size : heading_font_size,
fill : accent_1,
it
)
}
else if it.level == 2 {
// Since smallcaps aren't implemented yet for fonts without scmp, use upper
// smallcaps(it)
text(
weight: "regular",
size: heading_font_size,
spacing: 100%,
upper(it)
)
}
else if it.level == 3 {
text(weight: "medium", it)
} else {
it
}
}
#show strong: set text(weight: "extralight", fill: accent_10)
#page_heading(
name : (
first : "Kunal",
last : "Chandan",
email : "<EMAIL>",
phone : "814-807-7652",
github : "kunalchandan",
linkedin : "kunal-chandan",
caption : "B.A.Sc Honours Electrical Engineering '23",
// caption : "University of Waterloo",
subcaption : "",
// subcaption : "B.A.Sc Honours Electrical & Computer Engineering",
website : "chandan.one"
)
)
#let languages = {
[Python, C++, SQL, Verilog, VHDL, MATLAB, Go, RISC-V]
}
#let libraries = {
[Numpy, Pandas, PyTorch, Boost, FastAPI, Flask, CUDA]
}
// #let languages = exp_list(
// title : "Languages",
// items : (
// [Python],
// (
// // [Numpy],
// // [Pandas],
// [Scipy],
// // [Flask],
// [Sympy],
// // [TensorFlow],
// [Pytorch],
// ),
// [C++],
// (
// [Boost],
// [Catch],
// ),
// [SQL],
// // [Rust],
// // (
// // [nalgebra],
// // [Rayon],
// // ),
// [MATLAB],
// [Go],
// [Verilog],
// [RISC-V],
// // [Shell],
// // [LaTeX],
// )
// )
#let software = {
[KiCAD, LTSpice, Cadence Virtuoso, LayoutEditor, Quartus Prime]
}
// #let software = experience(
// description : (
// [KiCAD],
// [LTSpice/PySpice],
// [Cadence Virtuoso],
// [LayoutEditor],
// [Quartus Prime],
// [Linux],
// )
// )
#let awards = experience(
description : (
[Baylis Medical Capstone Design Award],
[2022 - #link("https://qnfcf.uwaterloo.ca/", "QNFCF Cleanroom Certification")],
[2022 - #link("https://uwaterloo.ca/giga-to-nanoelectronics-centre/lab-equipment", "G2N Cleanroom Certification")],
)
)
#let interests = experience(
description : (
[Cycling],
[Rock Climbing],
[Juggling],
)
)
// #let lab_tools = experience(
// description: (
// [PCB Design],
// [Oscilliscope],
// [Network Analyzer],
// [Probe Station],
// [Wirebonder],
// [Diebonder],
// [Plasma Cleaner & Asher],
// [Dicing saw],
// [HMDS Oven],
// [Spincoater],
// [SEM],
// [X-Ray Spectroscopy],
// )
// )
#let Summary_Quals = experience(
description : (
[Multidisciplinary generalist electrical engineering skills specialist in software development at scale in data engineering with *Python* and performance critical development in *C++*],
[Experienced electrical engineering skills with clean-room and hands-on electrical lab-work],
[Strong electrical engineering foundation through coursework in semiconductor device physics, RF devices, control systems, and IC design]
)
)
#let nvidiac = experience(
title : "Post-Silicon Validation Engineer",
website : "https://nvidia.com/",
company : "NVIDIA - Contractor (6 months)",
dates : (
start : "March 2024",
end : "Present",
),
location : "Santa Clara, CA, USA",
description : (
[Working on *PCIe* testing for upcoming SoCs and GPUs according to PCIe 5.0 spec],
)
)
#let enphase = experience(
title : "Electrical Engineer - Compliance",
website : "https://enphase.com/",
company : "Enphase Energy",
dates : (
start : "Aug 2023",
end : "Mar 2024",
),
location : "Fremont/Petaluma, CA, USA",
description : (
// [Creating tests for compliance of microinverters and other products to *UL-1741* and *IEEE-1547*],
// [Automation of tests in *Python* targetting lab safety and interoperability with lab instruments like powermeters, environment chambers, oscilliscopes etc.],
[Designed and implemented automated compliance testing for PV inverters to IEEE and UL standards],
//[],
[Created business analytics and equipment management application, improving test equipment utilization by *20%* (*Ignition Perspective*,* Python*)],
// [Developed *MySQL*, *Flask* asset management database and interlock system ensuring regulatory compliance and saving \$50K yearly],
// [Improved ease of testing for technicians by adding interoperability with *Ignition*],
)
)
#let uw_wong = experience(
title : "Electrical Engineering Research Assistant - Display Semiconductors",
website : "https://chandan.one/posts/Report/",
company : "University of Waterloo",
dates : (
start : "Sept 2022",
end : "Apr 2023",
),
location : "Waterloo, ON, CA",
description : (
[Designed custom PCBs in *KiCAD* for driving small $mu$LED active/passive matrix displays using *STM32* microcontroller and accompanying circuitry],
[Developed research plan for packaging $mu$LEDs onto TFT backplane using indium electroplating],
// [Characterized results using *SEM* and *X-Ray Spectroscopy*],
[Designed characterization setups for $mu$LEDs in *Fusion360* and *Arduino* interfaced with *Python*],
[Validated flip-chip diebonding results with thermal and electrical simulations in *MATLAB*],
[Designed and validated new $mu$LED layouts to improve mechanical and electrical performance],
),
)
#let uw_yash = experience(
title : "Data Science Research Assistant - Autonomous Vehicles",
website : "https://github.com/kunalchandan/CL2-AutoDetective",
company : "University of Waterloo",
dates : (
start : "Jan 2023",
end : "Apr 2023",
),
location : "Waterloo, ON, CA",
description : (
[Fault analysis of autonomous vehicles (AVs), causality and failure modes of AVs explored, literature reviews conducted],
[Causal inference and counterfactual reasoning applied to identify root cause failures],
[Created a dashboard using *Flask/Dash* to allow for data exploration and identification of novel failure modes],
)
)
#let groq_inc = experience(
title : "Software Engineer - Firmware",
website : "https://groq.com/",
company : "Groq Inc.",
dates : (
start : "Jan 2022",
end : "Apr 2022",
),
location : "Mountain View, CA, USA",
description : (
[Defined algorithm for resource allocation over memory and processing units of tensors on Groq’s TPU],
[Developed *Python* and *C++* firmware API to improve streaming of instructions and data],
[Used *PyBind11* for interoperability between C++ and Python firmware during codebase migration],
// [Used timing analysis to prevent stream conflicts & allowed for interleaving of streams],
)
)
#let huawei = experience(
title : "Software Engineer - Digital Compression",
company : "Huawei Technologies",
dates : (
start : "May 2020",
end : "Aug 2020",
),
location : "Waterloo, ON, CA",
description : (
// [Designed collision free non-cryptographic hash function (NCHF) in Galois Field 2 (GF-2)],
[Designed and analyzed non-cryptographic hash (NCHF) with linear algebra, SAT and self-designed $G F(2)$ matrix solver to verify properties],
[Benchmarked the optimized SIMD hashing function against existing NCHFs (*Rust*, *C++*)],
[Implemented novel border detection algorithm in *Go* using *probabilistic data structures* to maximize performance with Go-routines],
)
)
#let mappedin = experience(
title : "Software Engineer - Machine Learning",
website : "https://www.mappedin.com/",
company : "MappedIn",
dates : (
start : "Sept 2019",
end : "Dec 2019",
),
location : "Waterloo, ON, CA",
description : (
[Designed pipelines for data cleaning and analysis; integrated new *SQL* data warehouse],
[Increased prediction accuracy from *40%* to *80%* on existing *LSTM* models with feature engineering, hyperparameter optimization, and automated data cleaning (*Python*, *SQL*)],
[Created *Embeddings* + *SVM* + *Random Forest* ensemble models to replace existing LSTM models, reducing inference costs *2x* while maintaining prediction accuracy],
)
)
// #let robarts = experience(
// title : "Software Engineer - Bioinformatics",
// company : "Robarts Research Institute",
// dates : (
// start : "Jan 2021",
// end : "Apr 2021",
// ),
// location : "London, ON",
// description : (
// // [Developed software for migration of genetic analysis database from GRCh37 to GRCh38],
// // [Developed software in *Python* & *SQL* for existing genetics analysis pipeline],
// // [Resolved bugs in existing lab software (*Perl*, *Python*, *C\#*)],
// )
// )
#let oicr = experience(
title : "Software Engineer - Bioinformatics",
website : "https://github.com/oicr-gsi/dashi",
company : "Ontario Institute for Cancer Research",
dates : (
start : "Jan 2019 - Apr 2019",
end : "Jan 2021 - Apr 2021",
),
location : "Toronto, ON, CA",
description : (
// [Project lead of new statistical analysis tool for all future studies at OICR-GSI],
[Developed software in *Python* and *SQL* for existing genetics analysis pipeline],
[Resolved bugs in existing lab software (*Perl*, *Python*, *C\#*)],
[Designed genomics pipelines for visualization, cleaning, and analysis; interfacing with existing *R*, *Perl*, and *Shell* pipelines],
[Wrote future-proof and extensible code to process big datasets (*Pandas*, *Shell*)],
// [Open-sourced project and version controlled with *Git*; created extensive documentation],
)
)
#let risc_v_core = experience(
title : "Pipelined Risc-V Core",
description : (
[Designed 5-stage pipelined *RISC-V* 32-bit core in *Verilog* using only synthesizable constructs],
[Core synthesized on *FPGA* and successfully ran branching and recursive algorithms. Testbenches used to ensure cycle accuracy],
)
)
#let compiler = experience(
title : "C++ Compiler for C++ like Language",
website : "https://github.com/kunalchandan/RajLang/",
description : (
[Wrote lexer and compiler to generate *RISC-V* assembly for custom programming language, used Spike-sim to verify correctness of assembly],
[Used *CMake* (build management tool), *Catch* (unit-testing framework), *Boost* (graph library/dotviz generator)],
)
)
#let msa_dna = experience(
title : "Multiple Sequence Aligner",
website : "https://github.com/kunalchandan/goSeq/",
description : (
[Wrote sequence aligner for novo assembly of short sequences using Progressive Alignment Construction using the Needleman-Wunsch algorithm],
[Written in *Go* to take advantage of light weight green threads, used greedy heuristics to reduce $O(n!)$ problem to $O(n^2)$],
)
)
#let hearing_aid = experience(
title : "Beamforming Hearing Aid System",
website : "https://chandan.one/posts/mic-array/",
description : (
[Designed 4-channel microphone array PCB with active analog bandpass filtering, diff. amp., and multichannel *ADC* over *SPI* to R-Pi (*KiCAD*)],
[Created *Flask* server on R-Pi to compress and transfer audio data to *Pytorch* neural network for further digital filtering and beamforming],
[Adapted and trained Pytorch quantized voice isolation model to minimize latency while maintaining desired audio quality],
[Used *multiprocessing*, *asyncio*, and *websockets* to maximize system throughput, providing continuous audio output],
)
)
#let ray_tracing = experience(
title : "3D Ray Tracing Engine",
website : "https://github.com/kunalchandan/ToyTracer/",
description : (
[Implemented 3D recursive path-tracing for arbitrary materials on basic geometric shapes],
[Used *nalgebra* for arbitrary rotations and positions of camera and objects],
[Parallel processing of ray-tracing using *rayon* yielding *\~10X* performance speed-up on CPU],
)
)
#let education = experience(
title : "University of Waterloo -- B.A.Sc Electrical Engineering '23",
description : (
[Key Courses: Electronic devices, semiconductor physics, analog/digital integrated circuits, analog/digital/multivariable control systems],
[Select Awards and Certifications: Baylis Medical Capstone Design Award, #link("https://qnfcf.uwaterloo.ca/", "QNFCF") and #link("https://uwaterloo.ca/giga-to-nanoelectronics-centre/lab-equipment", "G2N") Cleanroom Certifications],
)
)
#box(height: 1.7cm,
columns(1, gutter: 5pt)[
#text(weight: "medium", size : heading_font_size, fill : accent_1, [Libraries:])
#libraries
#text(weight: "medium", size : heading_font_size, fill : accent_1, [Languages:])
#languages
#text(weight: "medium", size : heading_font_size, fill : accent_1, [Software:])
#software
// #text(weight: "medium", size : heading_font_size, fill : accent_1, [Lab Tools:])
// #lab_tools
// #colbreak()
// = Interests
// #interests
// = Award
// #awards
]
)
// = Summary of Qualifications
// #Summary_Quals
#box(height: 23.6cm,
columns(1, gutter: 10pt)[
= Experience
#nvidiac
#uw_yash
#groq_inc
#huawei
// #enphase
// #mappedin
#uw_wong
// #oicr
= Projects
#compiler
#msa_dna
#ray_tracing
#risc_v_core
#hearing_aid
= Education
#education
]
)
|
|
https://github.com/f14-bertolotti/bedlam | https://raw.githubusercontent.com/f14-bertolotti/bedlam/main/src/colors.typ | typst | // COLORS
#let orchid = color.rgb(200,150,250)
#let darkgray2 = color.rgb(84,84,84)
#let darkgray = color.rgb(64,64,64)
#let superdarkgray = color.rgb(16,16,16)
#let lightblue = color.rgb(82, 220, 255)
#let lightgreen = color.rgb(100, 255, 87)
#let ochre = color.rgb(204, 119, 34)
#let neonorange = color.rgb(255, 95, 31)
#let celadon = color.rgb(175, 225, 175)
#let emerald = color.rgb(80, 200, 120)
#let turquoise = color.rgb(64, 224, 208)
#let gold = color.rgb(196, 180, 84)
// Text colors associations
#let heading_color = white
#let line_color = 2pt + gradient.linear(superdarkgray, white)
#let page_color = superdarkgray
#let text_color = white
#let bold_color = orchid
#let link_color = turquoise
#let comment_color = emerald
// Theorem colors association
#let lemma_color = orange
#let definition_color = yellow
#let theorem_color = turquoise
#let example_color = lightgreen
#let proof_color = orchid
#let proposition_color = orange
// better page color, but it slow down the render in okular quite a bit
//#let page_color = gradient.linear(darkgray, superdarkgray, angle:45deg)
|
|
https://github.com/GuTaoZi/SUSTech-thesis-typst | https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/template/cover_en.typ | typst | MIT License | #import "../utils/datetime_display.typ" : *
#import "../utils/style.typ" : *
#import "@preview/tablex:0.0.6" : *
#let cover_en(
anonymous: false,
fonts: (:),
info: (:),
) = {
let display_info_top(
term,
value,
) = {
block(
width: 100%,
gridx(
columns: (auto,-15pt,auto),
rect(
stroke: none,
text(font: FONTS.宋体,size: FSIZE.小四,term)
),
"",
rect(
width: 3cm,
stroke: (bottom: 1pt + black),
align(center)[
#text(font : FONTS.宋体, size : FSIZE.小四, value)
]
)
)
)
}
let display_info(
term,
value,
) = {
block(
width: 100%,
gridx(
columns: (14em,auto),
rect(
width: 14em,
stroke: none,
align(right)[
#text(font: FONTS.宋体,size: FSIZE.三号,weight: "bold",term)
]
),
rect(
width: 9.5cm,
stroke: (bottom: 1pt + black),
align(center)[
#text(font : FONTS.宋体, size : FSIZE.三号, weight : "bold", value)
]
)
)
)
v(-10pt)
}
// render cover
gridx(
columns: (50%,50%),
align(left)[
#display_info_top(
"CLC",
info.clc,
)
],
align(right)[
#display_info_top(
"Number",
info.thesis_id,
)
],
)
v(-1cm)
gridx(
columns: (50%,50%),
align(left)[
#display_info_top(
"UDC",
info.udc,
)
],
align(right+horizon)[
#text(font: FONTS.宋体,size: FSIZE.小四,"Available for reference ◻Yes ◻No")
],
)
set align(center)
if(anonymous){
text("under consturction")
}
else{
}
image("../assets/logo_en.svg",width: 13cm)
v(-10pt)
text("Undergraduate Thesis",size: FSIZE.小初,font: FONTS.宋体)
v(40pt)
// render info
let title_rows = info.title.len()
let it = 0
while it < title_rows {
if it == 0 {
display_info(
"Thesis Title:",
info.title.at(0),
)
}
else{
display_info(
"",
info.title.at(it),
)
}
it = it + 1
}
if info.subtitle != "" {
display_info(
" ",
info.subtitle,
)
}
display_info(
"Student Name:",
info.author,
)
display_info(
"Student ID:",
info.student_id,
)
display_info(
"Department:",
info.department,
)
display_info(
"Program:",
info.major,
)
display_info(
"Thesis Advisor:",
info.supervisor,
)
// render submit date
align(center+bottom)[
#text(font: FONTS.宋体,size: FSIZE.三号,datetime_display_en(
info.submit_date,
))]
}
|
https://github.com/IliHanSoLow/W-Seminar_typst_template | https://raw.githubusercontent.com/IliHanSoLow/W-Seminar_typst_template/main/W-Semi-Template.typ | typst | Do What The F*ck You Want To Public License | #let project(title: "", author: "", school:"", location: "", subject:"", teacher:"", years: "", deadline: "", body) = {
show bibliography: set heading(numbering: "I.1")
set page(numbering: "1", number-align: center, header:[
#align(center)[#set text(12pt)
#smallcaps(title)]])
set text(font: "Linux Libertine", lang: "de")
show figure.caption: set text(8pt)
// Set paragraph spacing.
show par: set block(above: 2em, below: 2em)
set heading(numbering: "I.1")
set par(leading: 1.5em)
// Main body.
set par(justify: true)
set page(
paper: "a4",
margin: (y: 3cm))
grid(
columns: (50%, 50%),
align(left + horizon)[#school \ #location],
align(right + horizon)[Abiturjahrgang #years]
)
align(center)[#block(height: 20%, text(weight: 500, 1.75em, [
#align(horizon)[SEMINARARBEIT \
#text(size: 12pt, weight: 400, [aus dem W-Seminar]) \
#subject]]))]
block(height: 5%)
align(center)[Thema der Seminararbeit: \
#text(weight: 700, 1.75em)[#title]]
block(height: 10%)
block(height: 20%)[
#align(horizon)[
#grid(
columns: (30%, 70%),
align(left + horizon)[Verfasser: \ Kursleiter: \ Abgabetermin:],
align(left + horizon)[#author \ #teacher \ #deadline]
)
]
]
grid(
columns: (40%, 20%, auto),
rows: (2%, 2%),
align(left)[Bewertung der schriftlichen Arbeit:],
align(left)[.......... Punkte],
align(left)[in Worten: ..............................],
align(left)[Bewertung der Präsentation:],
align(left)[.......... Punkte],
align(left)[in Worten: ..............................],
)
grid(
columns: (60%, auto),
rows: (2%, 2%),
align(left)[Gesamtbewertung ((3x schriftlich + 1x mündlich) : 2):],
align(left)[.......... Punkte],
align(left)[Abgabe beim Oberstufenkoordinator am:],
align(left)[..............................]
)
block(height: 7%, width: 100%)[
#align(right + bottom)[............................................................ \
Unterschrift des Kursleiters]]
pagebreak()
block(height: 100%)[
#align(horizon)[ #outline() ]
]
pagebreak()
body
pagebreak()
bibliography("sources.yml", style: "ieee")
pagebreak()
align(center + horizon,[
#text(weight: 700)[
Ich erkläre hiermit, dass die Seminararbeit ohne fremde Hilfe angefertigt und nur die im Literaturverzeichnis aufgeführten Quellen und Hilfsmittel benutzt habe.]
#grid(
columns: (auto, auto, auto),
rows: (auto, auto, auto),
align(bottom + right)[#v(1em)............................................., den],
align(bottom + left)[#v(1em).........................],
align(bottom + center)[#h(0.5cm).....................................................],
align(horizon + center)[#v(1.5em)Ort],
align(horizon + center)[#v(1.5em)Datum],
align(horizon + center)[#v(1.5em)#h(0.5cm)Unterschrift des Schülers]
)]
)
}
|
https://github.com/ljgago/typst-chords | https://raw.githubusercontent.com/ljgago/typst-chords/main/src/utils.typ | typst | MIT License | // Gets the relative scale from a size of length type
#let size-to-scale(size, default) = {
let length-type = repr(size).match(regex("pt|mm|cm|in|em")).text
if length-type == "em" {
size.em
} else {
size / default
}
}
// Gets the string from a content data
#let parse-content(content-data) = {
if content-data.has("text") {
return content-data.at("text").codepoints()
}
if content-data.has("double") {
return (content-data,)
}
if content-data.has("children") {
for item in content-data.at("children") {
parse-content(item)
}
}
if content-data.has("body") {
parse-content(content-data.at("body"))
}
if content-data.has("base") {
parse-content(content-data.at("base"))
}
if content-data.has("equation") {
parse-content(content-data.at("equation"))
}
}
// Checks if the string contains only numbers
#let has-number(string) = {
if string.trim().matches(regex("^\d+$")).len() != 0 {
true
} else {
false
}
}
// Parses different string inputs to array
//
// 123|234 == 1,2,3 | 2,3,4 => ((1,2,3), (2,3,4))
// "x32o1o" == x,3,2,o,1,o => ("x",3,2,"o",1,"o")
#let parse-input-string(string) = {
let to-int-or-ignore(s) = {
if s.matches(regex("^\d+$")).len() != 0 {int(s)} else {s}
}
string = string.trim().replace(regex("\s"), "")
if string.contains("|") {
string.split("|").map(parse-input-string)
} else if string.contains(",") {
string.split(",").map(to-int-or-ignore)
} else {
string.codepoints().map(to-int-or-ignore)
}
}
// Draws a border with sharp corners
#let top-border-sharp(size, stroke, scale) = {
place(
dy: -size.height,
rect(
width: size.width,
height: size.height,
stroke: stroke,
fill: black
)
)
}
// Draws a border with round corners
#let top-border-round(size, stroke, scale) = {
let bezier-radius = 0.5519150244935105707435627pt * scale
let radius = 1pt * scale
place(
path(
fill: black,
stroke: stroke,
closed: true,
((0pt, -0.2pt * scale), (0pt, bezier-radius)),
((radius, -size.height), (-bezier-radius, 0pt)),
((size.width - radius, -size.height), (-bezier-radius, 0pt)),
((size.width, -0.2pt * scale), (0pt, -bezier-radius)),
((size.width, radius), (0pt, bezier-radius)),
((size.width - radius, 0pt), (bezier-radius, 0pt)),
((radius, 0pt), (bezier-radius, 0pt)),
((0pt, radius), (0pt, -bezier-radius)),
)
)
}
#let total-bounds(b1, b2) = {
let dx = calc.min(b1.dx, b2.dx)
let dy = calc.min(b1.dy, b2.dy)
return (
dx: dx,
dy: dy,
width: calc.max(b1.dx + b1.width, b2.dx + b2.width) - dx,
height: calc.max(b1.dy + b1.height, b2.dy + b2.height) - dy
)
}
#let set-default-arguments(args) = {
let size = 12pt
let font = "Linux Libertine"
if "size" in args.keys() {
(size,) = args
}
if "font" in args.keys() {
(font,) = args
}
return (
..args,
size: size,
font: font
)
}
|
https://github.com/PmaFynn/cv | https://raw.githubusercontent.com/PmaFynn/cv/master/README.md | markdown | The Unlicense | # CV
Personal CV I use. Currently written in Typst; might change back to LaTeX though. Feel free to make it your own.
## setup
```
sudo pacman -S typst
git clone <EMAIL>:PmaFynn/cv.git
cd cv
typst compile src/cv.typ path/to/output.pdf
```
## License
[LICENSE](LICENSE.md)
|
https://github.com/thornoar/hkust-courses | https://raw.githubusercontent.com/thornoar/hkust-courses/master/PHYS1312-Honors-General-Physics-I/homeworks/hw2/main.typ | typst | #import "@local/common:0.0.0": *
#import "@local/templates:0.0.0": *
#show: physics-preamble("Part 2", "Wed, Oct 2")
#physics-problem("1")\
Imagine a mass $M$ hanging from a ceiling suspended on two springs $S_1$, $S_2$ with coefficients $k_1$ and $k_2$.
We will show that the resulting string coefficient (as the system were one large spring) is $k_1 + k_2$.
Divide the mass $M$ into two smaller masses $m_1$, $m_2$ such that they, suspended from $S_1$ and $S_2$, produce the same extension $x$ in both springs.
We write Newton's third law together with Hooke's law:
$
m_1 g = k_1 x,\
m_2 g = k_2 x.
$
Now, if we tie the masses together with a rope, there will be no change in their positions or in the tension of the springs.
However, the result will be $M$ suspended from both of the springs simultaneously with extension $x$. We again write Newton's third law and Hooke's law for the system:
$
K x = M g = (m_1 + m_2) g = m_1 g + m_2 g = k_1 x + k_2 x = (k_1 + k_2) x,\
K = k_1 + k_2,
$
and we are done.
#physics-problem("2")\
The Sierpinski triangle consists of three smaller triangles, each similar to the whole, but scaled down by a factor of $1\/2$. Let the mass of the original triangle be $M$. Then, the mass of each of the three sub-triangles will be $m = M\/3$.
#align(center)[
#figure(
image("figures/triangle.svg", fit: "contain", width: auto),
caption: "The Sierpinski triangle and moments of inertia at different points"
) <triangle>
]
//|sub|[figures/triangle.asy]
Note that the moment of inertia of the entire triangle about $c_1$ (denoted $I$) is three times the moment of inertia of the blue sub-triangle about $c_1$ (denoted $i$). In turn, $i$ can be expressed in terms of the moment about the center of mass of the blue triangle, $i'$, as follows:
$
I/3 = i = i' + m d^2 = i' + M/3 dot (l/(2 sqrt(3)))^2 = i' + (M l^2)/36.
$ <one>
On the other hand, the big triangle has double the size of the blue one, and triple the mass. Since the moment of inertia around the center of mass is proportional to mass and to the square of side length (by definition), we have
$
I = 3 dot 2^2 dot i' = 12 i'.
$ <two>
Substituting @two into @one, we have
$
I/3 &= I/12 + (M l^2)/36,\
I/4 &= (M l^2)/36,\
I &= 1/9 M l^2,
$
and we are done.
|
|
https://github.com/Isaac-Fate/booxtyp | https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/lib.typ | typst | Apache License 2.0 | // Colors
#import "colors.typ": color-schema
// Cover
#import "cover.typ": cover
// Theorems, definitions, examples, etc.
#import "theorems/mod.typ": *
#import "equation.typ": equation-counter
// Math symbols and operators
#import "math.typ": *
// Indexing
#import "index.typ": *
// Book template
#import "book.typ": book
// Preface
#import "preface.typ": preface
|
https://github.com/isometricneko/typst-example | https://raw.githubusercontent.com/isometricneko/typst-example/main/main.typ | typst | #import "preamble.typ": *
#bib_state.update(none)
#include "chap1.typ"
#include "chap2.typ"
#bibliography("ref.bib", style: "harvard-cite-them-right", title: auto)
|
|
https://github.com/OkazakiYumemi/nju-ps-typst-template | https://raw.githubusercontent.com/OkazakiYumemi/nju-ps-typst-template/master/assignment_example.typ | typst | #import "hw-preamble.typ": *
#let title = "第 1 讲: 测试"
#let author = "张三"
#let student_number = "998244353"
#let due_time = "2024 年 2 月 31 日"
#show: assignment_class.with(title, author, student_number, due_time)
#section(title: "作业 (必做部分)")
#problem(title: "AC 1.2-3")[
]
#solution[
// + $A=mat(1,-1;-1,1;1,1)$
#set enum(numbering: "a)")
#solsection(title: lorem(3))
1. when $min(norm(bold(x))_2)$, $bold(x) = bold(x^*)$ is the solution to the problem, which is $x^*=vec(1/sqrt(3),1/sqrt(3),1/sqrt(3))$
2. We have a matrix $bold(A) = mat(1,1;1,1;1,0)$, the projection operator is $ bold(P) = bold(A)(bold(A)^T A)^(-1)bold(A)^T = mat(1/2,1/2,0;1/2,1/2,0;0,0,1), $ hence, $ bold(x^*) = bold(P) bold(v) = vec(1/2,1/2,1). $
#solsection(title: lorem(5))
3. We have a matrix $bold(A) = mat(1,-1;-1,1;2,2)$, the projection operator is $ bold(P) = bold(A)(bold(A)^T A)^(-1)bold(A)^T = mat(1/2,-1/2,0;-1/2,1/2,0;0,0,1), $ hence, $ bold(x^*) = bold(P) bold(v) = vec(1/2,-1/2,0). $
]
#problem()[]
#solution[
#let prox = [#math.op("prox")]
// #let proj = [#math.op("proj")]
// + $ op("prox")_g (bold(y)) = arg min_(bold(x in RR ^n)) {1/2 norm(bold(x)-bold(y))^2 + g(bold(x))}. $
1. we know that:
$ prox_phi (z) = argmin_(x in RR) {1/2 norm(x-z)^2 + phi.alt(x-c)}. $
let $x prime =x-c$ $ op("prox")_phi (z) = argmin_(x in RR) {1/2 norm(x prime-(z-c))^2 + phi.alt(x'+c-c)}+c = op("prox")_phi.alt (z-c)+c. $
2. if we want to $ f(x) = 1/2 norm(x-z)^2 + phi.alt(x)$ to be minimized, we need to find the $x$ that makes the derivative of the function equal to zero.
we know
$ diff f(x) = cases(x-z + lambda "when " x>0, [x-z - lambda,x-z + lambda] "when" x=0, x-z - lambda "when" x<0) $.
Hence, let $ diff f(x) = 0 $, we have
$ prox_phi.alt(z) = x^* = cases(z-lambda "when " z>lambda,
[z-lambda,z+lambda] "when" z in [-lambda,lambda],
z + lambda "when" z < -lambda) . $
3. if $phi(x) = lambda abs(x-c)$, where $c in RR$ and $lambda>0$. Use the result from part a.
$ prox_phi(z) = prox_phi.alt(z-c)+c = cases(z-lambda "when " z>lambda + c,
[z-lambda,z+lambda] "when" z in [-lambda+c,lambda+c],
z + lambda "when" z < -lambda+c) $
]
#problem()[]
#solution[
#let prox = [#math.op("prox")]
// #let proj = [#math.op("proj")]
1. If we take the derivative of $1/2 norm(bold(x)-bold(x)^(t-1))^2 + gamma g(bold(x))$, we have
$ bold(x^t) = prox_(gamma g)(bold(x)^(t-1)) = bold(x)^(t-1) - gamma nabla g(bold(x^t)) $
2. By the convexity of $g$, we know that $g(bold(x)^(t)) +nabla g(bold(x^(t)))^T (bold(x)^(t-1)-bold(x^t))<= g(bold(x^(t-1)))$. Hence, we have
$ g(bold(x)^(t)) <= g(bold(x^(t-1))) - nabla g(bold(x^(t)))^T (bold(x)^(t-1)-bold(x^t)) = g(bold(x^(t-1))) - gamma nabla norm(g(bold(x^(t))))^2_2 $
3. because $bold(x^t) = bold(x)^(t-1) - gamma nabla g(bold(x^t))$ which is a gradient descent method, so
$ -oo<g(bold(x)^t)<=g(bold(x)^(t-1)) $ and we have $ g(bold(x)^(t)) <= g(bold(x^(t-1))) - gamma nabla norm(g(bold(x^(t))))^2_2 $ hence $ 0<=gamma nabla norm(g(bold(x^(t))))^2_2<=0 $ if $ t arrow +oo $
]
#problem(title: "ST 5.5-5")[]
#solution(beginning: "Proof:")[
1. because
$
diff f(bold(x)) = {bold(v) in RR^n : f(bold(y))>= f(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n}
$
if $g(bold(x)) = theta f(bold(x))$,
$
diff g(bold(x)) = {bold(v) in RR^n : g(bold(y))>= g(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n} $
$ diff g(bold(x))={bold(v) in RR^n : theta f(bold(y))>= theta f(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n}
$
$ diff g(bold(x))={bold(v) in RR^n : f(bold(y))>= f(bold(x))+ bold(v)^T/theta (bold(y)-bold(x)),forall bold(y) in RR^n}
$
$ diff g(bold(x))=theta {bold(v) in RR^n : f(bold(y))>= f(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n} = theta diff f(bold(x))
$
2.
$
diff h(bold(x)) = {bold(v) in RR^n : f(bold(y))+g(bold(y))>= f(bold(x))+g(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n} $
all of the elements that satisfy $ f(bold(y))>= f(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n $ and $ g(bold(y))>= g(bold(x))+ bold(v)^T (bold(y)-bold(x)),forall bold(y) in RR^n $ are in the set $ diff h(bold(x)) $ hence $ diff f(bold(x)) + diff g(bold(x)) subset.eq diff h(bold(x)) $
3. we know that $ diff norm(x)_1 = cases(1 "when " x>0, [-1,1] "when" x=0, -1 "when" x<0) $.
hence $op("sgn")(x) in diff norm(x)_1$.
]
#problem()[]
#solution()[
#ind2 中文排印测试:
Here's a test sentence, "I can eat glass, it does not hurt me."
这是一条测试语句:“我能吞下玻璃而不伤身体。”
這是一條測試語句:「我能吞下玻璃而不傷身體。」
// 此處目前仍有問題,具體而言,當將 Noto Serif 字形置於 Noto Serif CJK 字形之前時,中文引號的顯示效果與英文引號相同,並且不會參與標點擠壓。正在尋找解決方案。用家可以在文章較多使用中文時,僅使用 Noto Serif CJK 字形,來保證中文排印的效果。
// 默認使用 "IBM Plex Serif", "Source Han Serif SC", "Noto Serif CJK SC" 字形,並且設置語言為 "zh" ,地區為 "cn" 。
默認使用 "Noto Serif", "IBM Plex Serif" 字形,並且設置語言為 "zh" ,地區為 "cn" 。
目前的效果是,當引號`"`兩邊有 CJK 字符,引號將以半角顯示",否則正常顯示英文引號。
測試:"中文引號", "quotation marks".
]
#problem()[]
#solution[
#ind2 This a test for code blocks.
For rust:
```rust
pub fn main() {
println!("Hello, world!");
}
```
For haskell:
```haskell
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
```
Select only a range of lines to show:
#codly-range(start: 3, end: 7)
```python
import numpy as np
def fibonaci(n):
if n <= 1:
return n
else:
return(fibonaci(n-1) + fibonaci(n-2))
fibonaci(10)
```
Disable line numbers:
#codly(number-format: none)
```cpp
int main() {
cout << "Hello, World!"; // 你好,世界
return 0;
}
```
Then pseudocodes.
#figure(
kind: "algorithm",
supplement: [Algorithm],
caption: [],
pseudocode-list(booktabs: true, numbered-title: [The Euclidean algorithm])[
// no-number,
// [*input:* integers $a$ and $b$],
// no-number,
// [*output:* greatest common divisor of $a$ and $b$],
// <line:while1>,
// [*while* $a != b$ *do*], ind,
// [*if* $a > b$ *then*], ind,
// $a <- a - b$, ded,
// [*else*], ind,
// [$b <- b - a$ #comment[comment test]], ded,
// [*end* #comment[another comment test]], ded,
// [*end*],
// [*return* $a$]
- *input:* integers $a$ and $b$
- *output:* greatest common divisor of $a$ and $b$
+ #line-label(<while1>) *while* $a != b$ *do*
+ *if* $a > b$ *then*
+ $a <- a - b$
+ *else*
+ $b <- b - a$ #comment[comment test]
+ *end* #comment[another comment test]
+ *end*
+ *return* $a$
]
)
#ind2 In @while1, we have a while loop.
The algorithm figure's breakable.
]
#problem(title: "")[
This is a test for CeTZ.
]
#solution()[
// #set page(width: auto, height: auto, margin: .5cm)
// #show math.equation: block.with(fill: white, inset: 1pt)
#cetz.canvas(length: 3cm, {
import cetz.draw: *
set-style(
mark: (fill: black, scale: 2),
stroke: (thickness: 0.4pt, cap: "round"),
angle: (
radius: 0.3,
label-radius: .22,
fill: green.lighten(80%),
stroke: (paint: green.darken(50%))
),
content: (padding: 1pt)
)
grid((-1.5, -1.5), (1.4, 1.4), step: 0.5, stroke: gray + 0.2pt)
circle((0,0), radius: 1)
line((-1.5, 0), (1.5, 0), mark: (end: "stealth"))
content((), $ x $, anchor: "west")
line((0, -1.5), (0, 1.5), mark: (end: "stealth"))
content((), $ y $, anchor: "south")
for (x, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (1, $ 1 $)) {
line((x, 3pt), (x, -3pt))
content((), anchor: "north", ct)
}
for (y, ct) in ((-1, $ -1 $), (-0.5, $ -1/2 $), (0.5, $ 1/2 $), (1, $ 1 $)) {
line((3pt, y), (-3pt, y))
content((), anchor: "east", ct)
}
// Draw the green angle
cetz.angle.angle((0,0), (1,0), (1, calc.tan(30deg)),
label: text(green, [#sym.alpha]))
line((0,0), (1, calc.tan(30deg)))
set-style(stroke: (thickness: 1.2pt))
line((30deg, 1), ((), "|-", (0,0)), stroke: (paint: red), name: "sin")
content(("sin.start", 50%, "sin.end"), text(red)[$ sin alpha $])
line("sin.end", (0,0), stroke: (paint: blue), name: "cos")
content(("cos.start", 50%, "cos.end"), text(blue)[$ cos alpha $], anchor: "north")
line((1, 0), (1, calc.tan(30deg)), name: "tan", stroke: (paint: orange))
content("tan.end", $ text(#orange, tan alpha) = text(#red, sin alpha) / text(#blue, cos alpha) $, anchor: "west")
})
#cetz.canvas(length: 1cm, {
import cetz.draw: *
let data = (
[A], ([B], [C], [D]), ([E], [F])
)
set-style(content: (padding: .2),
fill: gray.lighten(70%),
stroke: gray.lighten(70%))
cetz.tree.tree(
data, spread: 2.5,
grow: 1.5,
draw-node: (node, ..) => {
circle((), radius: .45, stroke: none)
content((), node.content)
}, draw-edge: (from, to, ..) => {
line((a: from, number: .6, b: to),
(a: to, number: .6, b: from), mark: (end: ">"))
}, name: "tree"
)
// Draw a "custom" connection between two nodes
let (a, b) = ("tree.0-0-1", "tree.0-1-0",)
line((a, .6, b), (b, .6, a), mark: (end: ">"))
})
#fletcher.diagram(
import fletcher: *,
node((0,0), [1], stroke: .1em, name: <1>),
node((2, 0), [3], stroke: .1em, name: <3>),
node((4, 0), [5], stroke: .1em, name: <5>),
node((1, .5), [2], stroke: .1em, name: <2>),
node((3, .5), [4], stroke: .1em, name: <4>),
edge(<1>, <2>, [2], marks: "-|>", label-side: right),
edge(<2>, <3>, [2], marks: "-|>", label-side: right),
edge(<3>, <4>, [2], marks: "-|>", label-side: right),
edge(<4>, <5>, [2], marks: "-|>", label-side: right),
edge(<1>, <3>, [1], marks: "-|>"),
edge(<3>, <5>, [1], marks: "-|>"),
edge(<2>, <2>, [0], marks: "--|>", bend: -130deg, ),
)
]
#section(title: "作业 (选做部分)")
#problem(title: "EoSD 9961")[
#ind2 How to pass 「レッドマジック」?
]
#solution[
#ind2 Practice more.
] |
|
https://github.com/henry-zwart/uva-report-unofficial | https://raw.githubusercontent.com/henry-zwart/uva-report-unofficial/main/template/main.typ | typst | MIT License | #import "@local/uva-report-unofficial:0.1.0": uva-report
#let abstract = [#lorem(200)]
#show: uva-report.with(
abstract: abstract,
title: "My report",
subtitle: "A great report",
student_name: "My name",
student_id: "3141592653",
lecturer: "My lecturer's name",
course_name: "Course name",
course_code: "Course code",
programme: "My programme",
academic_year: "2024 - 2025",
)
= Introduction
#lorem(100)
#lorem(200)
#lorem(150)
= Methods
#lorem(100)
#lorem(150)
#lorem(130)
= Discussion
#lorem(200)
#lorem(300)
#lorem(200)
= Conclusion
#lorem(250)
|
https://github.com/TillWege/nSim | https://raw.githubusercontent.com/TillWege/nSim/main/paper/template.typ | typst | zlib License | // The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and customize it to your liking!
#let project(title: "", subtitle: "", authors: (), date: none, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set text(font: "New Computer Modern Math", size: 11pt, lang: "de", spacing: 1.5pt)
set heading(numbering: "1.1")
// Title row.
align(center)[
#block(text(weight: 500, 1.75em, spacing: 5pt, title))
#v(1em, weak: true)
#date
]
align(center)[
#block(text(weight: 400, 1.0em, subtitle))
#v(1em, weak: true)
]
let currentAuthorIndex = 0
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.slice(0, currentAuthorIndex).map(author => align(center, (author))),
..authors.slice(currentAuthorIndex, currentAuthorIndex + 1).map(author => align(center, strong(author))),
..authors.slice(currentAuthorIndex + 1, authors.len()).map(author => align(center, (author))),
),
)
// Main body.
set par(justify: true)
show raw.where(block: true): block.with(
fill: luma(250),
inset: 2pt,
radius: 4pt,
width: 100%,
)
body
} |
https://github.com/SergeyGorchakov/russian-phd-thesis-template-typst | https://raw.githubusercontent.com/SergeyGorchakov/russian-phd-thesis-template-typst/main/glossarium.typ | typst | MIT License | // this source code was obtained and corrected from: https://github.com/ENIB-Community/glossarium
// glossarium figure kind
#let __glossarium_figure = "glossarium_entry"
// prefix of label for references query
#let __glossary_label_prefix = "glossary:"
// global state containing the glossary entry and their location
#let __glossary_entries = state("__glossary_entries", (:))
#let __query_labels_with_key(loc, key, before: false) = {
if before {
query(
selector(label(__glossary_label_prefix + key)).before(loc, inclusive: false),
loc,
)
} else {
query(
selector(label(__glossary_label_prefix + key)),
loc,
)
}
}
// Reference a term
#let gls(key, long: none, display: none) = {
locate(
loc => {
let __glossary_entries = __glossary_entries.final(loc);
if key in __glossary_entries {
let entry = __glossary_entries.at(key)
let gloss = __query_labels_with_key(loc, key, before: true)
let is_first = gloss == ();
let entlong = entry.at("long", default: "")
let textLink = if display !=none {
[#display]
} else if (is_first or long == true) and entlong != [] and entlong != "" and long != false {
[#entry.short (#entlong)]
} else {
[#entry.short]
}
[#link(label(entry.key), textLink)#label(__glossary_label_prefix + entry.key)]
} else {
text(fill: red, "Glossary entry not found: " + key)
}
},
)
}
// reference to symbol
#let sym(key) = {
locate(
loc => {
let __glossary_entries = __glossary_entries.final(loc);
if key in __glossary_entries {
let entry = __glossary_entries.at(key)
[#link(label(entry.key),[#entry.short])#label(__glossary_label_prefix + entry.key)]
} else {
text(fill: red, "Symbol entry not found: " + key)
}
},
)
}
// equation include symbols
#let print-eq-sym(..keys) = {
"где"
linebreak()
for key in keys.pos() {
locate(
loc => {
let __glossary_entries = __glossary_entries.final(loc);
if key in __glossary_entries {
let entry = __glossary_entries.at(key)
let desc = if entry.desc != [] and entry.desc != none {
[#entry.desc]
} else {
[]
}
let linkText = [#h(2.5em)#entry.short --- #entry.long, #desc #linebreak()]
[#link(label(entry.key),linkText)#label(__glossary_label_prefix + entry.key)]
} else {
text(fill: red, "Symbol entry not found: " + key)
}
},
)
}
}
// show rule to make the references for glossarium
#let make-glossary(body) = {
show ref: r => {
if r.element != none and r.element.func() == figure and r.element.kind == __glossarium_figure {
// call to the general citing function
gls(str(r.target))
} else {
r
}
}
body
}
#let print-glossary(entries, show-all: false, disable-back-references: false) = {
__glossary_entries.update(
(x) => {
for entry in entries {
x.insert(
entry.key,
(
key: entry.key,
short: entry.short,
long: entry.at("long", default: ""),
desc: entry.at("desc", default: ""),
),
)
}
x
},
)
for entry in entries.sorted(key: (x) => x.key) {
[
#show figure.where(kind: __glossarium_figure): it => it.caption
#par(
hanging-indent: 1em,
first-line-indent: 0em,
)[
#figure(
supplement: "",
kind: __glossarium_figure,
numbering: none,
caption: {
locate(
loc => {
let term_references = __query_labels_with_key(loc, entry.key)
if term_references.len() != 0 or show-all {
let desc = entry.at("desc", default: "")
let long = entry.at("long", default: "")
let hasLong = long != "" and long != []
let hasDesc = desc != "" and desc != []
{
set text(weight: 600)
if hasLong {
emph(entry.short) + [ -- ] + entry.long
}
else {
emph(entry.short)
}
}
if hasDesc [: #desc ] else [. ]
if disable-back-references != true {
term_references.map((x) => x.location())
.sorted(key: (x) => x.page())
.fold(
(values: (), pages: ()),
((values, pages), x) => if pages.contains(x.page()) {
(values: values, pages: pages)
} else {
values.push(x)
pages.push(x.page())
(values: values, pages: pages)
},
)
.values
.map(
(x) => link(
x,
)[#numbering(x.page-numbering(), ..counter(page).at(x))],
)
.join(", ")
}
}
},
)
},
)[] #label(entry.key)
]
#parbreak()
]
}
};
|
https://github.com/jamesrswift/springer-spaniel | https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/models/debug.typ | typst | The Unlicense | #let frame(stroke: 0.1pt) = place(rect(width: 100%, height: 100%, stroke: stroke))
#let horizontal-frames = {
place(dy: 5cm, rect(width: 4.5cm, height: 100% - 11.25cm, stroke: 0.1pt))
place(dy: 5cm, right, rect(width: 4.5cm, height: 100% - 11.25cm, stroke: 0.1pt))
place(dy: 5cm, dx: 5cm, rect(width: 100%-10cm, height: 100% - 11.25cm, stroke: 0.1pt))
}
#import "@preview/chromo:0.1.0": square-printer-test, gradient-printer-test, circular-printer-test, crosshair-printer-test
#let printer-test = {
place(right, pad(1cm,square-printer-test(size: 1em)))
place(left , pad(1cm,gradient-printer-test()))
place(right+bottom, pad(1cm,circular-printer-test(size: 2cm)))
place(left+bottom , pad(1cm,crosshair-printer-test()))
} |
https://github.com/cetz-package/cetz-venn | https://raw.githubusercontent.com/cetz-package/cetz-venn/master/gallery/venn3.typ | typst | Apache License 2.0 | #set page(width: auto, height: auto, margin: .5cm)
#import "@preview/cetz:0.2.2"
#import "@preview/cetz-venn:0.1.1": venn3
#cetz.canvas({
import cetz.draw: *
scale(1.5)
venn3(name: "venn", a-fill: red, b-fill: green, c-fill: blue,
ab-fill: yellow, abc-fill: gray, bc-fill: gray)
content("venn.a", [1], angle: 45deg)
content("venn.b", [2])
content("venn.c", [3])
content("venn.ab", [4])
content("venn.bc", [5])
content("venn.ac", [6])
content("venn.abc", [7])
})
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/web3/weeks/week8.typ | typst | #import "../../utils.typ": *
#section("Components Advanced")
#subsection("Component lifecycle")
- same as react with hooks
- ngOnInit
- hydration -> same as react
- ngOnDestroy
- dehydration -> same as react
- ngAfter events are mainly for control developers to handle sub-components and
their DOM
#align(
center,
[#image("../../Screenshots/2023_11_09_04_42_01.png", width: 50%)],
)
```ts
@Component({
// do something here
})
export class CounterComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log("OnInit");
}
ngOnDestroy() {
console.log("OnDestroy");
}
}
```
#subsection("Component Projection")
- also called *component transclusion*
- angular components consist of HTML and class components -> the html part needs
to act like a proper HTML tag
- how to allow inserting other html tags inside of this component?
This allows users to add content to the component without acessing the
javascript or typescript code:
#align(
center,
[#image("../../Screenshots/2023_11_09_04_46_03.png", width: 100%)],
)
Aka, as one can see, it is the tag in HTML, into which we can enter our content,
e.g. text or more tags.
#subsubsection("HTML Expansion")
While inserting tags is nice, we also want the component to provide its own HTML
-> see vue for an easier version.\
E.g. we want our own navigation component, which adds a header and a nav, this
is handled with a different html -> the navigation.component.html for our
navigation component. This will then be called before and after our tags that we
insert into the component.
#align(
center,
[#image("../../Screenshots/2023_11_09_04_48_43.png", width: 100%)],
)
#text(
teal,
)[Note, the amount of ng-content defines how many tags we can insert! 1 ng-content
-> 1 tag]
#subsubsection("Multi Shot Expansion")
#text(
teal,
)[This is the same as above with the addition that we check for the select title,
this makes us able to only insert specific tags:]
#align(
center,
[#image("../../Screenshots/2023_11_09_04_51_25.png", width: 100%)],
)
#section("Async Services")
- intention: don't block UI...
- data streams via *RxJS*
- can be very complex to use for everything
- events are easier for simple data
- EventEmitter in Angular
- implementation corresponds to the Observer Pattern
- compoments need to register to the desired events on the respective service
- can be bound to UI to automatically update UI
Example: ```ts
@Injectable({providedIn: 'root'})
export class SampleService {
private samples: SampleModel[] = []; // simple cache
public samplesChanged: EventEmitter<SampleModel[]> =
// create new event emitter
// data inside event emitter is the type that will be passed to the subscribers
of the event
new EventEmitter<SampleModel[]>();
constructor( /* inject data resource service */ ) {}
load(): void {
/* in real word app, invoke data resource service here */
this.samples = [ new SampleModel() ];
this.samplesChanged.emit(this.samples);
}
}
export class SampleModel {}
``` Example Usage: ```ts
@Component({ ... })
export class SampleComponent implements OnInit, OnDestroy {
private samples: SampleModel[];
private samplesSubscription: Subscription;
constructor(private sampleService: SampleService) {}
ngOnInit() {
this.samplesSubscription = this.sampleService.samplesChanged.subscribe(
(data: SampleModel[]) => { this.samples = data; });
}
ngOnDestroy() {
this.sampleSubscription.unsubscribe();
}
}
```
#section("Data Access")
- implemented as RxJS
- uses cold observables
- observables start running on subscription
- not shared among subscribers
- are automatically closed after task is finished
- why obersables and not promises? They didn't exist yet...
Using subscribe: ```ts
const subscription = this.http.get('api/samples').subscribe({
next: (x) => { /* onNext -> data received (in x) */ },
error: (e) => { /* onError -> the error (e) has been thrown */ },
complete: () => { /* onCompleted -> the stream is closing down */ }
});
```
Example Service: ```ts
@Injectable({providedIn: 'root')
export class SampleDataResourceService {
private samplesUrl = 'api/samples'; // web API URL
constructor(private http: HttpClient) {}
// the "subscription"
get(): Observable<SampleModel[]> {
return this.http.get(this.samplesUrl)
.pipe(
map((data) => this.extractData(data)),
catchError((err) => this.handleError(err)));
}
//handle the subscription
private extractData(data: any): SampleModel[] {
return SampleModel.fromDto(data);
}
private handleError(err: HttpErrorResponse) {
if (err.error instanceof ErrorEvent) {
// a client-side or network error occurred
} else {
// the backend returned an unsuccessful response code
}
// in a real-world app, you might delegate the
// error to a system state/error service or
// override the gobal ErrorHandler
return throwError(err.message);
}
}
```
Example Service Usage: ```ts
@Injectable({providedIn: 'root')
export class SampleService {
private samples: SampleModel[] = []; // simple cache
public sampleChanged:EventEmitter<SampleModel[]> = new
EventEmitter<SampleModel[]>();
constructor(private dataResource: SampleDataResourceService) {}
load(): void {
this.dataResource.get().subscribe(
(samples: SampleModel[]) => { // update cache, emit change event, ...
this.samples = samples;
this.sampleChanged.emit(this.samples);
});
}
}
export class SampleModel { }
```
#subsection("Intercept HTTP request")
- Often, we must set the same HTTP headers on every request
- For example: For security reasons, it may be required to insert the
Authorization header (bearer-token) on every request
- There are more headers to be written into every request, such as content-type
- angular provides hook to inercept HTTP calls
#align(
center,
[#image("../../Screenshots/2023_11_09_06_29_37.png", width: 100%)],
)
#section("Routing")
- optional module: RouterModule
- combination of services
- RouterOutlet
- RouterLink
- RouterLinkActive
- each definition maps a route (URL path segment to a component)
- top-most routes are registered on forRoot()
- .forRoot(): use forRoot()-import EXACTLY once to declare routes on root (top)
level
- .forChild(): use forChild()-import when declaring sub-routings (on all
sub-levels)
- Each ngModule (Feature Module) defines its own routes
- Routes should be defined within their own Routing Modules
- Routes can reference a module which can be loaded on-demand (lazy load)
- Use the import()-Syntax for that purpose
Example:
#align(
center,
[#image("../../Screenshots/2023_11_09_06_27_53.png", width: 100%)],
)
|
|
https://github.com/eliapasquali/typst-thesis-template | https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/chapters/product-design.typ | typst | Other | #pagebreak(to:"odd")
= Progettazione e codifica
<cap:progettazione-codifica>
#v(1em)
#text(style: "italic", [
Breve introduzione al capitolo
])
#v(1em)
== Tecnologie e strumenti
<sec:tecnologie-strumenti>
Di seguito viene data una panoramica delle tecnologie e strumenti utilizzati.
=== Tecnologia 1
Descrizione Tecnologia 1.
=== Tecnologia 2
Descrizione Tecnologia 2
== Ciclo di vita del software
<sec:ciclo-vita-software>
== Progettazione
<sec:progettazione>
== Design Pattern utilizzati
<sec:design-pattern>
== Codifica
<sec:codifica>
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/retain-explicit-decimal-marker/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
#num[10.]
#num(retain-explicit-decimal-marker: true)[10.]
|
https://github.com/wj461/operating-system-personal | https://raw.githubusercontent.com/wj461/operating-system-personal/main/HW4/hw4.typ | typst | #align(center, text(17pt)[
*Operating-system homework\#3*
])
#(text(14pt)[
= Written exercises
])
= Chap. 10
== 10.21: Assume that we have a demand-paged memory.
- The page table is held in registers.\
- It takes 8 milliseconds to service a page fault if an empty frame is available or if the replaced page is not modified and 20 milliseconds if the replaced page is modified. \
- Memory-access time is 100 nanoseconds.\
– Assume that the page to be replaced is modified 70 percent of the time. \
– What is the maximum acceptable page-fault rate for an effective access time of no more than 200 nanoseconds?
memory-access: 100n
page fault
- empty frame: 8 ms \
- modified: 20 ms\
total time <= 200n
x = page fault rate\
$"modified time" : ((x * 70%) * 20m)\
"empty frame time" : (x-(x * 70%) * 8m)\
"no page fault time" : (1-x) * 100n\
"total time" = "modified time" + "empty frame time" + "no page fault time" <= 200n \
x <= 6.10 * 10^(-6)
$
== 10.24: Apply the (1) FIFO (2) LRU (3) Optimal (OPT) replacement algorithms for the following page reference string:
3, 1, 4, 2, 5, 4, 1, 3, 5, 2, 0, 1, 1, 0, 2, 3, 4, 5, 0, 1.\
Indicate the number of page faults for each algorithm assuming demand paging with three frames.
- FIFO : 15
- LRU : 16
- OPT : 11
== 10.37: What is the cause of thrashing? How does the system detect thrashing? Once it detects thrashing, what can the system do to eliminate this problem?
thrashing: 需要的page數量超過了可用的page數量,導致大量的page fault,使得CPU利用率下降。\
detect: CPU利用率下降,page fault rate上升\
eliminate: 增加可用的page數量,減少CPU利用率,或是增加CPU的速度,或實現Working Set Model。
= Chap. 11
== 11.13: Suppose that a disk drive has 5,000 cylinders, numbered 0 to 4,999.
– The drive is currently serving a request at cylinder 2,150, and the previous request was at cylinder 1,805.\
– The queue of pending requests, in FIFO order, is 2,069; 1,212; 2,296; 2,800; 544; 1,618; 356; 1,523; 4,965; 3,681
Starting from the current head position, what is the total distance (in cylinders) that the disk arm moves to satisfy all the pending requests, for each of the following disk-scheduling algorithms?
- (a) FCFS
2150-> 2,069-> 1,212-> 2,296-> 2,800-> 544-> 1,618-> 356-> 1,523-> 4,965-> 3,681\
81 + 857 + 1084 + 504 + 2256 + 1074 + 1262 + 1167 + 3442 + 1284 = 13011
- (b) SCAN
2150 -> 2069 -> 1618 -> 1532 -> 1212 -> 544 -> 356 -> 0 -> 2296 -> 2800 -> 3681 -> 4965\
=7492
- (c) C-SCAN
2150 -> 2296 -> 2800 -> 3681 -> 4965 -> 4999 -> 0 -> 356 -> 544 -> 1212 -> 1532 -> 1618 -> 2069\
=4918
== 11.20: Consider a RAID level 5 organization comprising five disks, with the parity for sets of four blocks on four disks stored on the fifth disk.– How many blocks are accessed in order to perform the following?
- (a) A write of one block of data.
1 + 1 = 2
- (b) A write of seven contiguous blocks of data
7 + 2 = 9
== 11.21: Compare the throughput achieved by a RAID level 5 organization with that achieved by a RAID level 1 organization.
- (a) Read operations on single blocks.
RAID1 : 因儲存格式,可支援分散讀取\
RAID5 : 相較於RAID1,RAID5的讀取速度較慢
- (b) Read operations on multiple contiguous blocks.
RAID1 : 如果n大於disk數量,RAID1的讀取速度較慢\
RAID5 : 連續讀取速度較快
= Chap. 14
== 14.14: Consider a file system on a disk that has both logical and physical block sizes of 512 bytes.
– Assume that the information about each file is already in memory\
– For each of the three allocation strategies (contiguous, linked, and indexed), answer these questions:\
- (a) How is the logical-to-physical address mapping accomplished in this system? (For indexed allocation, assume that a file is always less than 512 blocks long)
contiguous : 存start block和block數量\
linked : 存start接著在每個block存下一個block的index\
index : 使用index block,將physical block的index存入index block。
- (b) If we are currently at logical block 10 (the last block accessed was block 10) and want to access logical block 4, how many physical blocks must be read from the disk?
contiguous : 1\
linked : 5\
index : 2
== 14.15: Consider a file system that uses inodes to represent files
– Disk blocks are 8KB in size, and a pointer to a disk block requires 4 bytes\
– This file system has 12 direct disk blocks, as well as single, double, and triple indirect disk blocks\
– What is the maximum size of a file that can be stored in this file system?
$12 * 8K = 96K\
(8K) / 4 dot 8K = 2K dot 8K = 16M \
(16M) / 4 dot 8K = 4M dot 8K = 32G \
(32G) / 4 dot 8K = 8G dot 8K = 64T \
0.96M + 16M + 32000M + 64000000M = 64032016.96M
$
|
|
https://github.com/rdboyes/resume | https://raw.githubusercontent.com/rdboyes/resume/main/modules_en/skills.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvSkill, hBar
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("Skills")
#cvSkill(
type: [Languages],
info: [R #hBar() Julia #hBar() Python #hBar() C++ #hBar() Stan #hBar() Rust],
)
#cvSkill(
type: [Activities],
info: [Automated Reporting #hBar() Dashboards #hBar() Cloud Computing #hBar() Prediction Models #hBar() Scientific Communication],
)
|
|
https://github.com/ludwig-austermann/qcm | https://raw.githubusercontent.com/ludwig-austermann/qcm/main/main.typ | typst | MIT License | #let colormap(name, n) = json("data.json").at(name).at(str(n)).map(c => color.rgb(c.at(0), c.at(1), c.at(2))) |
https://github.com/elpekenin/access_kb | https://raw.githubusercontent.com/elpekenin/access_kb/main/README.md | markdown | ---
⚠️ _This file contains some icons that should render on GitHub, but **don't worry!** if they don't_
📝 While all the source and documentation I've developed is written on English, the report is on Spanish to be presented at my University, I might translate it on the future
---
Access keyboard
===============
This project's goal is to make a highly customizable keyboard with a bunch of accessibility add-ons, so that **most** people can use it.
File structure:
```
📂 access_kb
├─ 📂firmware/ - Code running on the keyboard, compiled using qmk_build
├─ 📂hardware/ - PCB files
| └─ 📂libraries/ * References to KiCAD symbols and footprints
├─ 📂software - Client running on the PC to control the keyboard
└─ 📂typst - Sources used to create the PDF report
```
Firmware
========
Firmware made using [QMK](https://github.com/qmk/qmk_firmware).
Code and patches can be seen on [qmk_userspace](https://github.com/elpekenin/qmk_userspace), it is built using [qmk_build](https://github.com/elpekenin/qmk_build)
Hardware
========
The PCB was designed with KiCAD, based on ***Raspberry Pi Pico*** development board, and using some symbol/footprint libraries:
- [marbastlib](https://github.com/ebastler/marbastlib) -- Keyboard parts
- [rp-pico](https://github.com/ncarandini/KiCad-RP-Pico/) -- Raspberry Pi Pico
- [custom](./hardware/libraries/my_components.pretty/)
- Screen models based on 1xN female 2.54mm pin connectors + roughly measured rectangles. Used for placing and sizing, not used in final model
- Symbol for MC74HC589ADR2G, footprint is just a 16-pin SOIC
Features:
- Split
- Ortholinear
- Shift registers to reduce the pins needed
- PISO for matrix scanning
- SIPO for control signals
- Unused GPIO's are broken out so they be used too
- e-Ink display to show the current configuration
Software
========
Program using [Vue](https://vuejs.org/) and [Tauri](https://tauri.app/) on your computer, that can control some features of the keyboard and send information. Based on [KarlK90's work](https://github.com/qmk/qmk_xap)
|
|
https://github.com/npikall/vienna-tech | https://raw.githubusercontent.com/npikall/vienna-tech/main/template/abstract.typ | typst | The Unlicense | Die Kurzfassung soll den Inhalt der Arbeit kurz zusammenfassen. Sie sollte zumindest 70 und maximal 150 Wörter beinhalten. Der Schriftgrad sollte 10-Punkt sein. Der Einzug links und rechts soll 1 cm betragen. Der Text wird einfach in die Typst Vorlage eingefügt. Es fällt, durch den Gebrauch dieser Vorlage, die Verwendung von Umgebungen wie in LaTeX größtenteils weg. Zudem ist die Zeit für die Kompilierung des Dokuments deutlich kürzer. |
https://github.com/JarKz/math_analysis_with_typst | https://raw.githubusercontent.com/JarKz/math_analysis_with_typst/main/groups/third.typ | typst | MIT License | = Третья группа вопросов
1. *Понятие несобственного интеграла, его сходимости и расходимости.*
2. *Свойства несобственных интегралов.*
3. *Несобственные интегралы от неотрицательных функций. Признаки сравнения.*
4. *Критерий Коши сходимости несобственных интегралов. Абсолютная и условная сходимости.*
5. *Признаки Дирихле и Абеля сходимости несобственных интегралов.*
6. *Векторные пространства7 Скалярное произведение, норма, метрика в $RR^n$ и их свойства.*
7. *Сходимость последовальностей точкек из $RR^n$. Полнота пространства $RR^n$.*
8. *Открытые и замкнутые множества в $RR^n$. Их свойства. Понятие окрестности точки в $RR^n$.*
9. *Понятие компактного множества. Критерий компактности в $RR^n$.*
10. *Понятие связности. Классификация связных подмножеств числовой оси.*
11. *Отображения из $RR^n$ в $RR^m$ и способы их задания.*
12. *Пределы отображений. Повторные пределы. Теорема о повторных пределах.*
13. *Понятие непрерывного отображения. Теорема о композиции непрерывных отображений.*
14. *Непрерывность суммы, произведения, частного и локальное свойство непрерывных функций.*
15. *Теорема об образе компактного множества при непрерывном отображении. Теорема Вейерштрасса о максимуме и минимуме.*
16. *Понятие равномерной непрерывности и теорема Кантора.*
17. *Теорема об образе связного множества при непрерывном отображении. Теорема о промежуточных значениях.*
18. *Дифференцируемость отображения из $RR^n$ в $RR^m$. Понятия производной и дифференциала.*
19. *Единственность производной. Непрерывность дифференцируемого отображения.*
20. *Теорема о дифференцируемости и о производной композиции отображений.*
21. *Дифференцируемость некоторых элементарных отображений (постоянного, линейного, координантных функций и др.).*
22. *Линейность оператора дифференцирования.*
23. *Теорема о производных суммы, произведения, частного дифференцируемых функций.*
24. *Частные производные первого порядка (определение, геометрический смысл, необходимое условие экстремума функции векторного аргумента).*
25. *Частные производные высших порядков (теорема о смешанных производных).*
26. *Матрица Якоби. Представление дифференциала отображения из $RR^n$ в $RR^m$ через его матрицу Якоби.*
27. *Производная по вектору, производная по направлению, градиент.*
28. *Теорема о конечных приращениях для скалярных функций векторного аргумента.*
29. *Теорема о конечных приращениях для векторных функций векторного аргумента.*
30. *Дифференциалы высших порядков для функций векторного аргумента.*
31. *Формула Тейлора для функций векторного аргумента.*
32. *Достаточные условия экстремума функций векторного аргумента.*
33. *Теоремы о неявных функциях, определяемых уравнением $F(x,y)=0$, где $(x,y) in RR^2$.*
34. *Теорема об обратном отображении.*
35. *Теорема о неявном отображении.*
36. *Условный экстремум.*
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/intro.typ | typst | #import "preamble.typ":*
// copied from bigger project, edit into this one
= What is programmable cryptography?
Cryptography is everywhere now and needs no introduction.
_Programmable cryptography_ is a term coined by 0xPARC for a second generation
of cryptographic primitives that has arisen in the last 15 or so years.
To be concrete, let's consider two examples of what protocols designed by classical cryptography can do:
- _Digital signatures_.
RSA and ElGamal are examples of digital signature algorithms,
where Alice can perform some protocol to prove to Bob that she
endorses a message.
A more complicated example might be a
#cite("https://en.wikipedia.org/wiki/Group_signature", "group signature scheme"),
which allows one member of a group to sign a message on behalf of the group.
- _Confidential computing_. For example, consider
#cite("https://en.wikipedia.org/wiki/Yao%27s_Millionaires%27_problem", "Yao's millionaire problem"),
where Alice and Bob want to know which of them makes more money
without learning anything more about each other's incomes. With cryptography, Alice and Bob could use a two-party computation protocol designed specifically for this purpose.
Classically, first-generation cryptography relied on coming up with a protocol
for solving given problems or computing certain functions.
The goal of the second-generation "programmable cryptography" can
then be described as:
#quote[
We want cryptography that can
be "programmed" to work on *arbitrary* problems and functions,
rather than designing protocols on a per-problem or per-function basis.
]
To draw an analogy, it's like going from single-purpose hardware
(like a digital alarm clock or thermostat)
to a general-purpose device (like a smartphone) which can
do any computation so long as someone writes code for it.
#remark[
The quote on the title page
("I have a message $M$ such that $sha(M) = "0x91af3ac..."$")
is a concrete example.
The hash function sha is a particular set of arbitrary instructions,
yet programmable cryptography promises that such a proof can be made
using a general compiler rather than inventing an algorithm specific to SHA-256.
]
= Ideas in programmable cryptography
Our work presents programmable cryptography through specific topics in several self-contained "easy pieces," imitating Richard Feynman's
wonderful approach to physics exposition. We quickly preview them here.
== 2PC: Two-party computation
In a _two-party computation (2PC)_, two people want to
jointly compute some known function
$ F(x_1, x_2), $
where the $i$-th person only knows the input $x_i$, without either person learning the other person's input.
For example, in Yao's millionaire problem, Alice and Bob
want to know who has a higher income without revealing their own amounts.
This is the case where $F$ is the comparison function
($F(x_1, x_2)$ is $1$ if $x_1 > x_2$, $2$ if $x_2 > x_1$,
and $0$ if the two inputs are equal),
and $x_i$ is the $i$-th person's income.
Two-party computation makes a promise that we'll be able to do this
for _any_ function $F$ as long as we can implement it in code. It generalizes to _multi-party computation (MPC)_, which is one of the main classes of programmable cryptography.
== SNARK: Proofs of general statements
A powerful way of thinking about a signature scheme is that it is a *proof*. Specifically, Alice's signature is a proof that "I [the
person who generated the signature] know Alice's private key." Similarly, a
group signature can be thought of as a succinct proof that "I know one of
Alice, Bob, or Charlie's private keys".
In the spirit of programmable cryptography, a _SNARK_ generalizes this concept
as a "proof system" protocol that produces efficient proofs of *arbitrary*
statements of the form:
#quote[
I know $X$ such that $F(X, Y) = Z$, where $F,Y,Z$ are public,
]
once the statement is encoded as a system of equations. One such statement would be "I know $M$ such that $sha(M) = Y$."
SNARKS are an active area of research, and many different SNARKs are known.
We will focus on a particular example, PLONK (@plonk).
== FHE: Fully homomorphic encryption
Imagine you have some private text that you want to translate into another
language. While many services today will do this, even for free, we can also
imagine that you care about security a lot and you really don't want the
translating service to know anything about your text at all.
In _fully homomorphic encryption (FHE)_, one person encrypts some data $x$,
and then a second person can perform arbitrary operations on the encrypted data
$x$ without being able to read $x$.
With this technology, you have a solution to your problem!
You simply encrypt your text $Enc(x)$ and send it to your FHE machine translation server.
The server will faithfully translate it into
another language and give you $Enc(y)$, where $y$ is the translation of $x$.
You can then decrypt and obtain $y$, knowing that the server cannot extract
anything meaningful from $Enc(x)$ without your secret key.
== ORAM: Oblivious RAM
You want to perform a private computation on a large database.
The database is so large that you can't store it yourself --
and you don't trust the server it's stored on.
First off, you'll encrypt the data, so the server can't read it.
But the server still has an attack:
they can study your #emph[access patterns].
For example, they can see which records you access most frequently,
or which records you access at the same time as other records.
In many applications this is enough for the server to learn
sensitive information.
Oblivious RAM protects against exactly this sort of attack.
Oblivious RAM is an algorithm you use to "scramble" your
memory access requests.
When you feed your request into the ORAM algorithm,
the ORAM algorithm sends some scrambled
read and write requests to the server.
Only one of the scrambled requests is the request you are interested in;
the others keep the server from learning
which request you care about.
= Programmable cryptography in the world
In the past decade, there has been a surprisingly high amount of theoretical work but also
a surprisingly low amount of implementation work on primitives in programmable cryptography.
However, recent advances in areas like
blockchain and other decentralized systems are rapidly driving
demand for practical implementations of programmable cryptography. The gap
that is being revealed right now, as theory meets reality, is exciting and
enlightening.
Many of the protocols we mention in this book can be implemented today, but only at a very high cost (for example, the cost of proving a computation in a SNARK can be millions of times the
cost of performing the computation directly). As we study the theory of programmable cryptography, it is useful to keep in mind some practical questions. Can we reduce the theoretical overhead of programmable cryptography? How can we make programmable cryptography systems more performant for modern hardware and software systems? What
other systems or applications can be built on top of this technology?
It is easy to be carried away by the staggering possibilities, and to imagine a
perfect "post-cryptographic" world where everyone has control over all their
data and everyone's security preferences are completely fulfilled. It is also
easy to be cynical and assume that these ideas will go nowhere.
Reality is always somewhere in the middle; the Internet
today offers free search and civilization-scale repositories of information to everyone, but is also used for plenty of frivolous or even antisocial activity.
No matter what the future actually holds, one thing is clear - it is up to people who are capable, curious, and optimistic to guide the next stage of the evolution of cryptography-based systems. We hope that these "easy pieces" will inspire you to read, imagine, and build.
|
|
https://github.com/davidmasp/naturelike | https://raw.githubusercontent.com/davidmasp/naturelike/main/README.md | markdown | # Nature-like typst preprint template
This is a preprint template "inspired" by the formating of the
journal Nature. More importantly than the actual look of the paper,
the template also
handles author afilitiations (and hopefully in the future correspondence).
See below for a quick look and check the examples in
[`main.typ`](main.typ) on how to use it.
<p align="center">
<img width="350" src="image.png">
</p>
## Usage
To compile the example in this repo run:
```
make all
```
## Roadmap
- [ ] Add support for corresponding and co-author (generally notes?)
- [ ] Double-check that fonts are recognised correctly
- [ ] Add support for figure functions
- [ ] Add support for tables
- [ ] Check if equations render similarly
- [ ] Add support for Supp material
- [ ] Add doi, dates params in the function call
- [ ] Submit to typst templates (not yet available, see [here](https://github.com/typst/typst/issues/2432))
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/046%20-%20Streets%20of%20New%20Capenna/010_Alley%20Cat%20Blues.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Alley Cat Blues",
set_name: "Streets of New Capenna",
story_date: datetime(day: 05, month: 04, year: 2022),
author: "<NAME>",
doc
)
Kitt shouldered the leather bag, felt the vials of Halo shifting under her jacket, and asked herself how she'd gotten into this mess in the first place—her, just a small-time subway busker crooning for spare change.
#figure(image("010_Alley Cat Blues/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Sure, the subway wasn't the most pleasant-smelling part of New Capenna, not by a long shot, but the gig made her a living. People bustled up and down those worn marble stairwells as though the trains inhaled them in and exhaled them out in waves. Kitt had picked the most acoustic corner of Lower Bassomer Station that morning, her back to the iron balusters. Before she started, she always gave herself a few minutes of listening to pick up the mood of the moment, the tempo of feet, the syncopated patter of talk, the languorous rumble as trains slowed to a halt and then clickity-clacked their way onward, #emph[ba da dum ba da dum ba da dumbadi dumbadi dum] .
Pigeons always settled in a row in the rafters, bright eyes turned to her. Even when no one threw her a coin, the pigeons gave her their rapt attention. She would start humming, then singing, riffing and harmonizing with the wash of sound. All the old tunes sounded better with the life of New Capenna as their rhythm section.
There she'd been, not a soul stopping to listen or grace her voice and presence with a coin, so she'd launched into the pigeons' favorite, "<NAME>." They'd all rustled excitedly, wings fluffing out as she rang her changes through the bridge, playing with a key change simply for the joy of launching her voice in flight. Why not? No one was paying her any mind.
And then just like in the flicks, a big, well-kempt man—leonin, just like her, but three times her size and donning a gorgeous, expensive jewel-toned coat that little ol' Kitt had been jealous of the moment the fabric caught her eye—this bigwig had halted right in front of her. He'd watched her thoughtfully, his two-toned expression unreadable. Was he disgusted? Impressed? Bored? Was he tapping one sharply polished shoe just slightly in appreciation? Her nerves skittered, and for an instant, Kitt thought she would lose the beat and explode into frantic flight the way the birds did when they were startled, but she hung on. She'd been through worse.
She brought the melody through its final cadence and finished with a flourish: one last trill and the brush of a hand skyward as she sang the final line, "in our cozy little nest for two."
The pigeons cooed.
The big man put a hand in his pocket, and she thought he was maybe even going to give her a real tip. Instead, he brought out a calling card, offering it to her as he looked her dead in the eyes. His gaze was molten amber, only an ear-flick of emotion in his lion's gaze.
His voice held a gravelly authority. "Seems to me a little sister like you just needs a chance."
Well! Wasn't that what she was always telling herself?
She accepted the card with a polite purr, wishing it were cold hard cash instead. Until she glanced at the ornate writing that inscribed a single name: #emph[Jetmir] .
"Boss Jetmir!" Kitt exclaimed, shocked into losing her cool.
#figure(image("010_Alley Cat Blues/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"The same," he said with a lazy affability that did not fool her one bit. The boss of the Cabaretti wasn't anyone's friend. But he changed lives, one way or the other. "The warm-up slot at the Red Room tonight is yours, little songstress. If you complete one tiny favor for me. Do you want it?"
The Red Room at the Vantoleone—did she want it!
So that was how she found herself on a Cloudponte Bridge train for the first time in her entire sorry life, holding tight to the messenger bag he'd given her. It had held an illegal stash of Halo for delivery to a Cabaretti agent up on Park Heights, but she'd transferred all the vials into the inner pockets sewn into her jacket so they wouldn't get jostled as much. Most importantly, the bag contained a gown, wrapped in tissue paper, for her debut.
"A songstress needs the right look," Jetmir had said.
She slipped her hand under the flap to fondle the cool silk, the most expensive fabric she'd ever touched. That satiny smoothness was the texture of success. She just knew it.
Then he'd lost the amiable smile and added, "Herculaneum Candy Shop at the Upper Bridge Plaza. Ask for Henzie. Be at the Vantoleone by seven. If you aren't, another singer will go on in your place."
She'd used the ticket he'd given her, a ticket she could never ever have afforded herself, and transferred at Upper Bassomer Station to a third-class train bound for the glories of Park Heights. The train started rattling up along the lowest tier of Cloudponte Bridge, the busy levels of the Mezzio beneath her feet and the glamor of Park Heights awaiting her above like a sliver of heaven.
She checked the clock set over the door that connected to the rear compartment and smiled with satisfaction. She had plenty of time to make the delivery on the Heights and get back to the Mezzio for the performance. For once, she wouldn't look like a smudged and unwashed street cat whose rag-pile scraps were held together with bent pins and discarded boot laces. She'd look like the star she knew she could be, all shimmering green with gold highlights as the faces of the audience turned up to her in adoration.
All her life, she'd dreamed of getting out of the blasted furnace of Caldaia, away from streets lit day and night by smoky lanterns because sunlight never reached the murky industrial depths.
Jetmir was right. She just needed a chance, and the big man had handed her one. That was how the Cabaretti worked. Once you were in the family, you were in.
Standing close to the front of the packed car, Kitt swayed and jostled amid white-eyed vampires, prim-faced elves, a leering devil accompanied by a trio of strait-laced and well-groomed leonin dressed in maids' uniforms, and a pack of sweaty ogres headed for some muscle job among the wealthy. Laborers who worked up in Park Heights had to be clean and neat, but even so, this was a crowded third-class train. The pungent smell of all those bodies was enough to make her fur prickle. There was a single open seat, but no one was sitting there because an unknown individual had left behind a puddle of glistening goo. By its blueish color, the culprit was probably a cephalid.
Cabaretti family didn't travel on third-class trains that had to share the rails with heavy freight loads. "Family" got seats on the second-class trains that ran on the tier above, or if they were big enough in the family, in the first-class luxury trains that ran like fat golden centipedes alongside the graceful top deck of Cloudponte Bridge.
Kitt would sit in that first-class train someday; she'd look out to the horizon over the glittering city, bare just a smile's sliver of fang at her polished-window reflection, and the whole sky would be hers. She just had to make her mark.
What songs should she pick? Four, Jetmir had said. Her lucky number. First a swinging, saucy beat like "Wiggle Waggle Boom!" as she sashayed onto the stage in the gown that would mark her as The Real Thing, a crooner to catch their eye, a tasty treat to titillate their interest.
She'd follow that up with a big, brassy number to showcase her range. "Be an Angel and Lift Me up on Your Wings" would do the trick. The pigeons loved that one almost as much as they loved "<NAME>," which would be the perfect sweet romantic ballad for her third number, a little soppy and just the right amount of low-rent for folks who never wore a dirty shoe or scrounged dinner out of a garbage bin in their lives.
And for a lasting impression on the fourth, a real showstopper—
With a jolt, the train stopped dead. It lurched forward with a wheeze, halted again, and gave a drawn-out hiss. The people around her fell silent the same way, all breaths held. When the train didn't start up and no announcement was broadcast, a murmur of anxiety traveled through the crowd. One belligerent rhox pounded at the doors, which didn't open because the train was stopped between stations—there was nothing but track and service railings between them and the drop to Caldaia. By now, the train was perched above the main level of the Mezzio. The tinted windows looked over a twilight marked by lights atop the Mezzio's many girders and rooftops and by the straight lines of the huge pillars that held the city up, rising out of smoky Caldaia all the way to Park Heights. Nearer the track, the ubiquitous and sparkling pigeon nests, woven from sticks and thread, gleamed with a tincture of Halo.
Here and there, the dull red glow of Caldaia was visible through holes and cracks in the multi-level tier of the Mezzio. It was a long way down into that pit. Kitt refused to go back. She had to make this chance work, move up in the plane. Be the star she knew she could be.
But this third-rate train sat dead on the tracks, and she was stuck along with all the other passengers. How soon would mechanics get here? Through the window nearest her, she could just get a glimpse up and down the line along the wire maintenance walk, but there was no movement, no one coming to check on them. Could they bring up another train on the rails alongside? Would the passengers have to trudge on the emergency walk back down to Bassomer and then get a new train back up? How much time would that take?
Kitt checked the clock above the connecting door at the front of the car. Even with all the noise in the car she could hear the second hand's doom-laden #emph[tick. . .tick. . .tick. . .] , each passing second a tiny slow dance of a cut against her skin. Her #emph[one big] #emph[chance] .
No. She wouldn't give up. With a flash of teeth and a press of shoulder, she wedged her way closer to one of the windows, trying to squeeze past the devil. If she could open the window, she could climb out and ascend along the maintenance walk. She'd trudged farther distances in her life.
"Scram, alley cat!" the devil hissed.
The three maids all in a row curled back their lips to show their fangs at her, but Kitt flexed her shoulders and fluffed herself bigger. She'd clawed tougher meat than them. Their ears went down.
The devil elbowed her hard. "I said, back off!"
The blow caught the bag instead of her ribs, the pressure sinking into the precious gown inside with a rustle of crushed tissue paper.
"Mind your own potatoes," Kitt snarled.
The devil's leer wasn't belligerence so much as bravado by the way he stepped back with a startled gasp, thinking his horns and ugly face were enough to intimidate her. Not likely! Thank the angels she'd moved the vials of Halo to her jacket, out of harm's way! But even as the pressure released, the rustling grew so loud that others began to notice and turn.
#emph[Boom!] A heavy crash shook the tracks.
All conversation ceased, then burst into crescendo as everyone spoke at once. What was that? A collision? Fireworks? Kitt didn't have time for this!
A second, sharper #emph[boom] blasted louder, bigger, shaking the whole train. The explosion's bang shocked the ears, followed by a #emph[whoof!] of air, like the plane's biggest pipe organ, that spattered flecks of grit against the windows. Pigeons nesting along the nearest beams took flight in a burst of wings.
The birds weren't the only ones startled. The crowd at the rear end of the car closest to the noise panicked, pushing and shoving toward the front, where more people were already crammed teeth to muzzle, horn to chin. Kitt didn't have a pole or bench to hold onto, not even a windowed wall to press herself up against, so the surging flood forced her forward, and she barely kept to her feet as a besuited ogre stumbled against her. Iron footfalls thudded from beyond the closed door like doom approaching. The door into the rear compartment screeched, torn aside by a powerful arm wielding a wrench the length of a crowbar.
A big, muscle-bound viashino wearing the coal cap of the Riveteers ducked through the door and halted, looming over the now terrified passengers. Her stare kindled with inner fire, her scaly muzzle with literal fire. The devil lost his leer and huddled behind his maids.
"That's a boiler!" the devil muttered. One of his maids hushed him before the Riveteer heard the rude nickname and took offense.
#figure(image("010_Alley Cat Blues/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The viashino slapped the big wrench against a meaty palm. Her slow, deliberate, fire-licked words were punctuated by smacks of the wrench.
"I am just letting all you fine eggs know that if you don't want to be broken today, you'll pay attention. You have been delayed because my crew is under orders to dismantle the rails before and behind this train. As you know, we use only the most sophisticated engineering methods."
Another explosion sounded. #emph[Dynamite] . The nobs up in Park Heights were going to be furious when their freight and their servants both didn't arrive in a timely manner. What was worth it to the Riveteers to go hard like this?
#emph[Smack!] went the big viashino's wrench against her palm. Every gaze was gripped by the sound.
"Now, we could hurry along this process with a little help from a lucky volunteer." #emph[Smack!] But not a soul stepped up. "I know you know who you are and what you's done. So don't think you'll be getting away easy." Green fire licked the air as the viashino roared the next words, pointing with the wrench toward the quivering, frightened passengers. Even the ogres looked ready to wet their trousers. "This is why you don't cross the Riveteers!"
Like anyone needed a reminder of that! Kitt kept her muzzle mashed tight. This was not the time to be a Witty Wanda. Someone not paying their debts to the Riveteers wasn't her problem, not that she wanted to find out whose problem it was. She tucked her tush, wedged a boot in between other feet, and slid a half step away from the fire-spitting Riveteer. The viashino was a big, bold, brassy dame if she'd ever seen one, a real torpedo. Better to get out of range, if she could, and figure out how to get on her way instead of getting stuck in some janky business.
"Now then!" roared the Riveteer as she peered across the crowd with a too-keen eye, like she already knew what she was looking for. Her red-rimmed gaze halted on the three maids all in a row. "There's somethin' our old pal Henzie owes us, and he knows it, even if he don't want to admit it."
#emph[Henzie?] A sick hairball of an idea caught in Kitt's throat. Henzie. She closed her arms tight over her jacket, clutching the bag closer against her.
Smack went the wrench against the palm. The passengers closest to the viashino all flinched, but there was nowhere to retreat. A second viashino appeared in the compartment door, not quite as big so probably a male, carrying a hammer. The car went as quiet as a church mouse just before the owl swallows it up.
The first viashino showed all her teeth, and they were very white and strong and pointed. "Here's how it is, my good eggs. We got word that our old pal Henzie intercepted some of our goods and passed them on to a leonin lass for transport. Y'hear that, my purrful petite? You can show yourself now, hand over the parcel, and we'll let you go on your way as light as a pleased pig after the wallow party is over. How about it, doll? We Riveteers don't begrudge a gold digger her shovel, but this isn't the heap that's yours to keep. So be a wise egg, and there'll be no more trouble."
In the cramped train car, folk swiveled to look at the three leonin maids as Kitt hunched her shoulders to make herself less conspicuous. She had managed to edge away from the devil and was now crammed between a vampire's behind and the knees of a shocked-looking human in shopkeeper garb seated on the bench with their back to a window. Everyone was still looking toward the viashino or at the maids, although the vampire was starting to sniff as if they had caught the scent of Caldaia ash around Kitt.
The vials shifted beneath her arm in the padded pockets sewn into her old jacket, because sometimes a girl had to transport bits and bobs of illicit cargo to make her rent. It would be so easy to step forward, confess, hand over the vials, and skedaddle on her way.
If the Riveteers let her go. No guarantees on that, were there? And then she'd have to deal with the Cabaretti, maybe even with Jetmir himself. When she remembered his amber eyes and his confident way of taking up space, she knew the questions he'd ask wouldn't be nice ones. With a boss like that, disappointment could kill. And if it was just her life, well, that was one thing. She had a career at stake.
Even if no one laid a blade to her flesh, Kitt's chance at the singing spotlight she deserved would be over. Her career? In ruins. Sure, she could keep singing for the pigeons in the subway station, with a coin or two thrown at her, but what kind of life was that for a leonin with pride? Anyway, come to think of it, she had a lot more confidence in her ability to out-maneuver a big lunk of a viashino and her Riveteer friends than to double-cross the canny Cabaretti and that Jetmir, who'd seen what she could be.
Musicians had to be as fast on their melodic feet as any fleet-footed Park Heights messenger winging from one spire to the next, so Kitt made up her mind right there.
"Eh there, #emph[you're] a leonin," whispered the vampire as if it had taken this long for their sluggish thoughts to register Kitt's presence.
With a hard twitch of her hips, she slammed the vampire sideways, knocking them into a pair of ogres, then stomped on the heel of the shopkeeper. The human shrieked in pain, buckling over, which allowed Kitt to grab their shoulders and heave them off the bench head first into the vampire, who smacked the ogres again. With a roar, the ogres forgot the threatening viashino and puffed up with grunts and oaths, cursing the vampire. People began to push and shove and shout as they fought to get away from this new altercation.
Kitt jumped up onto the bench and, with a heave of her shoulders and a burst of adrenalin, popped open the window.
"There she goes!" bellowed a thunderous baritone.
No time to figure out who was pointing the finger! Kitt jumped out the window, an easy enough caper for a gal with plenty of practice squeezing out of sticky situations. As she landed soft-pawed on the tracks, she looked up and down, gauging her best route. Running back toward Bassomer would take her straight into her pursuers, but when she turned to head up, she saw a mob of mechanics swarming the train that had been running half a bob-mile ahead. The enthusiastic Riveteers were literally dismantling the train car's glimmering outer shell like ants stripping the exoskeleton from a giant beetle. Wowzers, they really wanted this Halo, and her stuck in the middle of their ruthless schemes. Well! Either you swam or you sank, and this cat was not going to drown today.
What route was left? The upper tiers of the bridge were too far to jump, and she couldn't fly. That left the Mezzio's rooftops and the beams and pipes with so many roosting pigeons watching the proceedings with attentive interest. There was a garden rooftop about ten feet out and fifteen down from the edge of the track, so just within reach. Beyond it, she might be able to jump up and grab one of the beams, then run along its narrow span to the roof of the Merchants Guild Hall and shimmy down one of its pompous statues and get into the Mezzio that way.
The train car door cracked open about twenty paces from her. The big viashino leaped out onto the tracks with a solid thud she felt in her bones. That fiery gaze aimed straight at her. "What's it gonna be, doll? The easy way, or the hard way?"
Buskers knew when to ignore catcalls. Slipping one foot after another away from the brute, Kitt warbled the opening of "Be an Angel and Lift Me up on Your Wings" and caught a rustle of pigeon interest, hundreds of dark eyes turning her way. Birds were her first audience, and she'd learned there was a lot more to the pigeons of New Capenna than folk realized. How pigeons watched over her in exchange for the melodies they craved. Warned her of trouble coming. Pigeons weren't mere featherbrains. The angels had left threads and twigs of power throughout the city's heights and depths, and people always overlooked the least flashy and most ubiquitous denizens of the levels. Even birds could be touched by Halo's uncanny powers.
She jumped, tucking tight at first to get speed and then relaxing so she hit the rooftop into a boneless crouch, steady on her feet. But she hadn't taken one breath before the roof shuddered under the shocking weight of the viashino, followed by a pair of smaller males. Who knew those clunks could be so nimble!
Kitt dashed toward the far side of the roof. A firework splatter of dynamite went off among the beams, scattering the pigeons in a flurry of angry, frightened wings. Nests sprayed, torn into pieces, chaff fluttering downward with sparks and flashes of Halo-touched glow. From the railing, she saw a construction platform within leaping distance, this one braced above a half-finished roof. The three viashino closed in behind her, spreading out so she couldn't bolt past them to the stairwell that would lead down into the building. No choice now. Kitt climbed up on the railing and jumped again. It was farther down, the wind whistling past her ears and rippling against her fur. She hit the platform, tucked, and rolled over a shoulder and back up to her feet to absorb the impact.
Thuds shook the platform as the three viashino pursued. Kitt raced to the edge of the platform, but there was no beam in reach, no craggy spire, no route to the roof of the Guild Hall, just a long way down through the gaps of the Mezzio's buildings and levels into the dull red glow far below. Folk said cats always land on their feet, but this cat couldn't fly. If she leaped from this height, she'd be dead.
#emph[Smack!] went the big wrench against the palm.
Kitt turned, back pressed up against the safety railing, bag clutched to her chest.
The big Riveteer grinned as green fire licked ominously around her muzzle. "Ya can't outwit ole Ognis, kitten. An engineer like me plans for every trick in the book. You hear the snap of my trap? Now hand over the goods. This is your last chance, 'cuz I'm on a strict timetable today."
And it #emph[was] her last chance. Kitt wasn't going back to Caldaia, not today, not ever. Ognis and her cronies might be engineers, but Kitt had a lot of practice landing on her feet when the fall looked awfully grim.
"Big words, parakeet," Kitt said, meeting Ognis right in her fiery gaze. "Better make sure you don't cook your own eggs." She inhaled and sang right into their startled faces, jumping straight to the second verse, yanking herself away from the licking flame of the viashino like she was taking a turn on that Cabaretti stage. "Be an angel and lift me up on your wings, remind me how your love brings me all the way to #emph[heaven] #emph[above] ~"
Poised at the edge, the Mezzio and dirty old Caldaia far below, Kitt broke off and held the bag out beyond the railing. Oh, it hurt to do it, but she had no choice. She met Ognis's gaze with a steely one of her own. "You want it, boiler? Then you can go get it."
Opening her hand, she let go of the bag. Ognis's mouth dropped open, and the fiery dame full-on #emph[snorted] with astonishment and disbelief. But Kitt didn't wait for the Riveteers to get their ganders back in gear. She clambered up the railing, paused there balanced for an instant, because that was all she had, as she launched back into the song again.
"Be an angel—"
She crooned. She flung out her arms.
She jumped into the vast empty gulf of air, still singing.
And the pigeons flocked, they swarmed, they massed together to make a big cloud of gray-white feathers. They caught her amid their hundreds of glittering wings and lifted her up and up and up, all the way to the lowest rim of Park Heights. To a little rim-ward parking lot where a vampire attendant was dozing in a chair overlooking a squad of fancy cars.
The squawks and chirps of the flock startled the vampire awake, blinking through sluggish eyes as Kitt stumbled onto solid decking and got her bearings with a whistle of thanks. The birds spun skyward and scattered.
She caught the railing and looked over the edge. She'd never been up so high, and for a moment, she wondered if she had time to double back down into the Mezzio or even Caldaia to look for that bag. That beautiful, high-class gown.
One close call was enough. Too bad she wouldn't be there to see the viashinos' faces when they discovered they'd been had!
A clock chimed, then tolled the hour with a brassy #emph[bing bang bing bang bing bang] .
She had only one hour to go, and she had to find Henzie, make the drop, and get back down to the Mezzio all without being spotted by any more ravening Riveteers.
"Eh?" said the vampire attendant, who clearly hadn't absorbed enough Halo or blood recently. "Wassit? Stop there, miscreant!"
"No time for a coze," Kitt cried, and bolted out past the parking lot's gate.
Jetmir had given her a map of Park Heights along with the bag. He was fair like that, even if he'd tossed her straight into the boiling pot either to test her or because he didn't want to sacrifice one of his trusted lieutenants. Well! She'd show him what she was made of!
The fancy folk of Park Heights and their sober-looking servants did look twice at a scruffy street cat making tracks through the broad boulevards. She didn't have time to sight-see, gape, or goggle at the swanky storefronts, the glamorous gowns and shapely gams, elegant edifices, and magnificent plazas where light from the sun touched the faces of those fortunate enough to live at the top of the heap. No, she'd have time for that later, when she was a crowning jewel.
The stained-glass and beetle-shell sugar candy shop sat two blocks away from the Crossponte Bridge Station, a place where folk from the Mezzio could buy pretty twizzle sticks and Halo-infused lollipops for the long workday and where the adventurous among the Park Heights set could try out the bittersweet horehound candy drops that Caldaia's overworked mothers used to cut the sting of hunger in their babies' bellies.
She sashayed in to find a customer browsing a rack of taffy. A short devil was seated behind a counter, a peppermint whip of a man. He had slicked-back pomaded hair to match his horns, a nose that had been broken once too often, and a jeweler's glass in place of his right eye.
#figure(image("010_Alley Cat Blues/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"I'm looking for Henzie," Kitt said.
The proprietor looked her up and down, but waited until the customer left and the bell on the door tinkled before saying, curtly, "Lost the bag, eh, kitten?"
"I have what you want." One by one, with a flourish, she set out the vials, counted them out loud, and took a step back, waiting.
"I'll be a clam's uncle." Henzie cocked his head as an expression of respect settled onto his thin face.
"Didn't think I'd make it, did you?" Kitt said, flashing a bit of fang. "You got a ticket for me?"
He regarded her for a moment more, then nodded, pulled a stub of printed cardboard out of his suit pocket, and slid it across the counter.
She snatched it up. "I hope you don't mind if I don't hang around and chew the breeze. I've got a stage to catch."
"And a fancy emerald gown to dazzle 'em in, if I don't mistake," he said with a curious look at her empty arms.
She didn't think about that—couldn't think about that—as she ran to the station. Pigeons flew overhead like scouts, and she kept her eyes peeled for any sign of Riveteers.
At the station, a pair of glowering coal-capped viashino—not the torpedo or her gang—lurked by the main entrance. A flock of pigeons circled down in a squawking mass as if some do-gooder had scattered bird seed at the feet of the Riveteer lookouts. While the pair flapped their arms to cover their heads and cursed like thunder, Kitt scurried past, head down, and caught the next train just as the doors shut. The tracks clicked and clacked in their spry rhythm, a beat to soothe the agitated soul.
The gown was gone, sure. But she still had her voice and her performance to make her mark. And wasn't that what caught Jetmir's eye the first time? #emph[Sure] , the voice inside her purred that she couldn't show up looking like a stray to a high-class shindig, #emph[but it's all flash up here. You gotta have both to succeed, kitten.]
Jacket flapping, Kitt raced from Mezzio Station, slipping and sliding and elbowing her way through the crowds on the after-work streets. Rich scents spilled from restaurants welcoming folk in for evening appetizers. Clerks and barristers laughed too obviously over drinks at fashionable bars. She had no watch, no way to know the time and no time to detour to one of the clock pillars set in the squares. She just ran and panted up to the backstage door of the Vantoleone just as it opened and a stolid doorman in Cabaretti colors stepped out.
#figure(image("010_Alley Cat Blues/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"Are you the singer?" He looked her up and down with a skeptical grimace. "Not the duds I imagined, but you #emph[are] just in time. Six minutes to showtime."
Six minutes! Kitt gave the man her best cheeky grin because he seemed a friendly sort, or at least one who wouldn't judge until he had to toss you out the door. "Can you put a word in the ear of the conductor? My song list."
"Sure, kitten."
"It's Kitt, if you please," she said with dignity. "<NAME>." Begin as you mean to go on, and she meant to go on.
As Kitt entered the back passage, a beautiful elf in a dark red gown came gliding up like light shining across a pool of oil. Her perfect features curled into a sneer as she, too, looked Kitt up and down.
"You aren't what Jetmir gave me to expect. I have a certain standard for my stage. He assured me you have the right kind of look for the Red Room. Isn't there a gown?"
Kitt squared her shoulders and gave a confident twitch of her ears. "I have my act all sorted out. It's sure to be a hit with this fancy crowd. Is there a dressing room, ma'am? What may I call you?"
Red Gown's frown was smooth and icy. "We'll do introductions later, since you're late."
"Had a spot of trouble, but it all worked out."
"Did you, now? Jetmir and I had a wager on whether you would make it. This way."
The elf led her down a hallway. Spikes of laughter and the roar of excitable talk rumbled from the front of the house where plenty of people were waiting for the show to start.
"Five minutes to showtime, and then two minutes of introduction, that's all the time you have to get fit for performing," said the elf with a condescending lift of an eyebrow, clearly doubting Kitt would ever be fit for the Red Room stage. The tiny bells tied to the elf's dark braids tinkled musically, and Kitt hummed a little descant, which made the elf glance back in surprise before shutting the door.
The dressing room was plush enough for an opening act, with a sofa, a makeup table and mirror, and a screen for dressing. It was small but way fancier than her little hole of a room tucked into an abandoned warehouse down in Caldaia. Bright lights burned on either side of a big mirror. Her reflection stared back. She was filthy and sweaty, and her jacket had a rip in the hem she hadn't noticed, not to mention its mended elbows and feathers stuck in her fur. No use crying over spilt milk. Descending Crossponte Bridge, she'd decided there was only one option left: Be who she was, and make it sing.
While doing a hasty batch of vocal exercises to warm up her voice, she ditched the jacket, unbuttoned the top two buttons of the old stevedore's shirt she wore, brushed off the feathers, tidied up her style, and smudged the grime on her face to give it a more theatrical look, like she was an actress playing a street cat. After a second thought, she picked up the jauntiest feather, one with a bit of Halo glow, and stuck it in one of the buttonholes.
A knock rapped on the door. It cracked open. Red Gown peered in and spoke with the precise diction of an individual very angry at having to deal with the trash that has washed up on their doorstep. "You're on, <NAME>."
Kitt followed the elf to the wings of the stage. A faint rustling met her ears. When she looked up, she saw pigeons—so many pigeons—gathered on the rafters up in the darkness. How had they gotten in? The same way she had, on a wing and a gamble.
"And now," said a bodiless announcer, "for your pleasure: <NAME>."
Kitt put on her best street attitude as the band struck up the opening bars of "Wiggle Waggle Boom!" The house lights had been turned down, but she had a cat's ability to see in the dark, and darned if there weren't Riveteers in the crowd, even that torpedo of a viashino lass. Bless her fiery stars! Was it Kitt's imagination, or did ole Ognis's eyes glow with frustrated anger as she recognized the songstress strutting into center stage with a swagger?
#emph[Wiggle waggle boom!]
#emph[Wiggle waggle boom!]
#emph[Ya think you caught me but]
#emph[Wiggle waggle boom!]
Kitt punctuated each #emph[boom!] with a saucy waggle of her hips. The Cabaretti druids adored it. No love lost between them and the Riveteers, after all! At the end of the song, the Cabaretti howled with laughter, and the Riveteers scowled. Even the pigeons chirped, then fluffed up with pride as the band swung into "Be an Angel," and after that settled with contentment for "<NAME>."
For her final number, she'd changed her mind six times on the train from Park Heights down to the Mezzio before she'd decided to pledge her loyalty and strike a blow for the Cabaretti at the same time. It was a gamble. If she lost, and she left here without a contract, even a street cat with her smarts wouldn't last long once the Riveteers tracked her down. As they would, unless she won~oh, yes, unless she won.
The orchestra segued into an uptempo twist on a classic melody Kitt had specially requested on her set list. She knew how to change lyrics on the fly, and this tune was going out to all the Riveteers in the crowd—but especially Ognis.
#emph[Pack those vials one by one, up to Park Heights, on the run, bye, bye, boiler] , Kitt crooned, shifting into an exaggerated street gait, cocky and sure-eyed, twice the bravado of the devil on the train with a side of macho to top it off. She leaned into the heat of the spotlight, looking beyond the stage, beyond the front crowd, beyond even Jetmir in his gallery-box seat, right to meet Ognis's furious gaze for a second time. Kitt tossed her head back, puffed out her chest to really show off that feather and belted the song in the viashino's direction with her throatiest croon, a curled, triumphant grin to punctuate each line, just like the smack of the wrench of a certain pushy engineer climbing the tracks.
#emph[Now my dreams will come true, as I bid goodbye to you, boiler! Bye, bye!]
The final crescendo rolled through a drum cascade and her last note, pitch perfect. Then a held breath, drawn out into a long hush. Above, the pigeons chirped excitedly, the sound abruptly drowned out by a roar of applause and even a few whistles.
Kitt took her bow and was about to leave the stage, shaking with exhaustion and relief, when the curtain at the wing stirred and a hulking figure moved lithely out into the spotlight. Jetmir strolled out on stage, raising a hand that brought the theater to a complete can-hear-a-pin-drop silence.
"Great voice! Great spirit! What'a'ya say, brothers and sisters?" Sustained applause and enthusiastic cheers filled the house, cut off when he again raised a hand. His gaze touched the elf standing just off stage, and he nodded at his stage manager as with an unspoken message, then turned back to the auditorium. "We'll see <NAME> again tomorrow night, with a higher billing and a few more songs."
He gave Kitt a nod, said to the band leader, "How about an encore of 'Bird<NAME>'?" and walked off the stage.
For a moment she was voiceless. Breathless. But no, she'd heard him right. She'd passed his test with flying colors.
Cabaretti, here we come. She was in. No longer a street cat, <NAME> was now a high-class songbird singing at the ritziest joint in town. No sky the limit!
From the rafters above, the pigeons cooed.
#figure(image("010_Alley Cat Blues/06.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.2/util.typ | typst | Apache License 2.0 | #import "matrix.typ"
#import "vector.typ"
#import "bezier.typ"
/// Constant to be used as float rounding error
#let float-epsilon = 0.000001
/// Multiplies the vector by the transform matrix
///
/// - transform (matrix): Transformation matrix
/// - vec (vector): Vector to get transformed
/// -> vector
#let apply-transform(transform, vec) = {
matrix.mul-vec(
transform,
vector.as-vec(vec, init: (0, 0, 0, 1))
).slice(0, 3)
}
/// Reverts the transform of the given vector
///
/// - transform (matrix): Transformation matrix
/// - vec (vector): Vector to get transformed
/// -> vector
#let revert-transform(transform, vec) = {
apply-transform(matrix.inverse(transform), vec)
}
// Get point on line
//
// - a (vector): Start point
// - b (vector): End point
// - t (float): Position on line [0, 1]
#let line-pt(a, b, t) = {
return vector.add(a, vector.scale(vector.sub(b, a), t))
}
/// Get orthogonal vector to line
///
/// - a (vector): Start point
/// - b (vector): End point
/// -> vector Cormal direction
#let line-normal(a, b) = {
let v = vector.norm(vector.sub(b, a))
return (0 - v.at(1), v.at(0), v.at(2, default: 0))
}
/// Get point on an ellipse for an angle
///
/// - center (vector): Center
/// - radius (float,array): Radius or tuple of x/y radii
/// - angled (angle): Angle to get the point at
/// -> vector
#let ellipse-point(center, radius, angle) = {
let (rx, ry) = if type(radius) == "array" {
radius
} else {
(radius, radius)
}
let (x, y, z) = center
return (calc.cos(angle) * rx + x, calc.sin(angle) * ry + y, z)
}
/// Calculate circle center from 3 points
///
/// - a (vector): Point 1
/// - b (vector): Point 2
/// - c (vector): Point 3
#let calculate-circle-center-3pt(a, b, c) = {
let m-ab = line-pt(a, b, .5)
let m-bc = line-pt(b, c, .5)
let m-cd = line-pt(c, a, .5)
let args = () // a, c, b, d
for i in range(0, 3) {
let (p1, p2) = ((a,b,c).at(calc.rem(i,3)),
(b,c,a).at(calc.rem(i,3)))
let m = line-pt(p1, p2, .5)
let n = line-normal(p1, p2)
// Find a line with a non upwards normal
if n.at(0) == 0 { continue }
let la = n.at(1) / n.at(0)
args.push(la)
args.push(m.at(1) - la * m.at(0))
// We need only 2 lines
if args.len() == 4 { break }
}
// Find intersection point of two 2d lines
// L1: a*x + c
// L2: b*x + d
let line-intersection-2d(a, c, b, d) = {
if a - b == 0 {
if c == d {
return (0, c, 0)
}
return none
}
let x = (d - c)/(a - b)
let y = a * x + c
return (x, y, 0)
}
assert(args.len() == 4, message: "Could not find circle center")
return line-intersection-2d(..args)
}
#let resolve-number(ctx, num) = {
if type(num) == "length" {
if repr(num).ends-with("em") {
float(repr(num).slice(0, -2)) * ctx.em-size.width / ctx.length
} else {
float(num / ctx.length)
}
} else {
float(num)
}
}
#let resolve-radius(radius) = {
return if type(radius) == "array" {radius} else {(radius, radius)}
}
/// Find minimum value of a, ignoring `none`
#let min(..a) = {
let a = a.pos().filter(v => v != none)
return calc.min(..a)
}
/// Find maximum value of a, ignoring `none`
#let max(..a) = {
let a = a.pos().filter(v => v != none)
return calc.max(..a)
}
/// Merge dictionary a and b and return the result
/// Prefers values of b.
///
/// - a (dictionary): Dictionary a
/// - b (dictionary): Dictionary b
/// -> dictionary
#let merge-dictionary(a, b) = {
if type(a) == "dictionary" and type(b) == "dictionary" {
let c = a
for (k, v) in b {
if not k in c {
c.insert(k, v)
} else {
c.at(k) = merge-dictionary(a.at(k), v)
}
}
return c
} else {
return b
}
}
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/3-methodology/study-1/simulation.typ | typst | MIT License | #import "../../../lib/mod.typ": *
=== The Simulation Tool MAGICS <s.m.simulation-tool>
// #jonas[A lot of the subsections here are 50% done. As in they explain the context and such but not details. Let us know if what is here is enough and it would be too much to go deeper, or if you are missing something.]
// Hypothesis 4:
// Extensive tooling will create a great environment for others to understand the software
// and extend it further. Furthermore, such tooling will make it easier to reproduce and
// engage with the developed solution software.
As described in hypothesis #study.H-1.box, this thesis poses the idea the extensive tooling will help facilitate reproduction of the results and further development of the software, and thus, #acr("MAGICS") is a key component in this regard. The simulation tool presents a #acr("GUI") to interact with the live simulation. The tool is built with the Bevy@bevyengine game engine and the immediate mode #acr("UI") library _egui_@egui. Together they allow for rapid prototyping and development of interactive applications. The tool is designed to be used by researchers and developers to understand the underlying theory of factor graphs and their application in multi-agent planning scenarios. The tool is equipped with several features to facilitate this goal, where the most important features are described in sections #numref(<s.m.settings>)-#numref(<s.m.export-formats>). The tool is open-source and available on the thesis' #gbp-rs()@repo. #acr("MAGICS") is shown in @f.m.simulation-tool, where the #panel.viewport and #panel.settings are visible. The user also has access to a #panel.bindings, by pressing `H`, which shows the keybindings for the tool and enables the user to change them. Lastly, a floating #panel.metrics can be opened with `D`, which shows live metrics and diagnostics for the current simulation. All panels are implemented using immediate mode UI instead of retained mode, which simplifies state management and makes it easier for others to extend the tool. With this approach, the code responsible for creating each part of the panel is straightforward and easy to locate, facilitating quick modifications and enhancements.
#figure(
// std-block(todo[screenshot of settings panel, or at least a part of it]),
std-block(width: 90%)[
#set text(theme.text)
#{
show table.cell : it => {
if it.x == 1 {
set text(theme.peach)
it
} else {
it
}
}
table(
columns: (31.2%, 26%, 1fr),
row-gutter: -0.5em,
column-gutter: -1em,
stroke: none,
[], panel.metrics, [],
[],
layout(size => {
$overbrace(#h(size.width))$
}),
[]
)
}
#v(-1.5em)
#block(
clip: true,
pad(
x: -0.2mm,
y: -0.2mm,
image("../../../figures/img/magics-all-panels-latte.png")
)
)
// #image("../../../figures/img/tool-settings-latte.png")
#v(-2em)
#{
show table.cell : it => {
if it.x == 0 {
set text(theme.green)
it
}
else if it.x == 1 {
set text(theme.lavender)
it
} else {
set text(theme.maroon)
it
}
}
table(
columns: (31.2%, 1fr, 32.2%),
row-gutter: 0em,
column-gutter: -1em,
stroke: none,
layout(size => {
$underbrace(#h(size.width))$
}),
layout(size => {
$underbrace(#h(size.width))$
}),
layout(size => {
$underbrace(#h(size.width))$
}),
panel.bindings, panel.viewport, panel.settings,
)
}
],
kind: image,
supplement: [Figure],
caption: [Screenshot of the #acr("MAGICS") with the #panel.settings, #panel.bindings, and #panel.metrics open at the same time. In the middle, the #panel.viewport is shown. The #panel.settings and #panel.bindings are scrollable, hence only a part of them are visible here.],
)<f.m.simulation-tool>
==== Live Configuration <s.m.settings>
Most of the configurable settings described in #nameref(<s.m.configuration>, "Configuration") section can be changed live during the simulation. Pressing `L` in #acr("MAGICS") will expose a side-panel with all the settings, see #panel.settings in @f.m.simulation-tool; hereunder, the mutable configuration settings, e.g. amount of internal and external #acr("GBP") iterations to compute, communication failure rate and radius, and which visualizations to draw. A screenshot of the side-panel is shown in @f.m.simulation-tool, which includes all these and more useful options.
Some of the sections in the settings panel are off-screen in @f.m.simulation-tool, but they are accessible by scrolling down. The notable sections are described in the following sections.
==== Hot Loading Scenarios <s.m.hot-loading>
// #jonas[New content here with the folder structure and such]
Do not confuse this for _hot reloading_, as is known in many front-end frameworks, but #acr("MAGICS") allows for _hot loading_ of scenarios. This means that the simulation scenarios that are described later in #nameref(<s.r.scenarios>, "Scenarios") can be selected through a drop-down at any time during the simulation#footnote[`f4` and `f6` can be use to load the previous and next scenario respectively. Allowing one to quickly go back and forth and compare scenarios.]. This will reset the simulation and load the new scenario, loading the corresponding `configuration.toml`, `environment.yaml`, and `formation.yaml`. The dropdown menu contains all scenarios listed under @s.r.scenarios along with other miscelleanous scenarios. Each scenario is loaded from disk by the scenario loader module by reading through the folder `./config/scenarios/`#footnote[The default, but can be changed using the `--scenario-dir <DIR>` flag when starting the simulator] for every folder with the three different configuration files in them. As seen in @listing.scenario-folder-structure. This makes it uncomplicated to work on multiple scenarios at once, and share them with others.
// 📂
#listing([
```text
./config/scenarios/
├── 'Circle Experiment'
│ ├── config.toml
│ ├── environment.yaml
│ └── formation.yaml
├── 'Communications Failure Experiment'
│ ├── config.toml
│ ├── environment.yaml
│ └── formation.yaml
│ ...
```
],
caption: [Folder structure expected by the scenario loader module. Each scenario is a separate subfolder in the `./config/scenarios/` folder, with a `config.toml`, `environment.yaml` and `formation.yaml` in each.],
) <listing.scenario-folder-structure>
#par(first-line-indent: 0pt)[The active scenario can be reloaded repeatedly by pressing `F5` or clicking on the reload button ` ` in the simulation section, as can be seen in @f.m.simulation-tool-time-control. Simulation parameters, and parameters related to the algorithm, such as the communications failure rate, $gamma$, specified in the `config.toml` are not reloaded, allowing rapid testing of different values. By changing values in the UI, reloading the scenario, and observing the immediate effects, one can quickly iterate on tuning the system for a specific scenario. And get a better understanding of how parameters affect the systems behaviour. Once a desired set of parameters have been found they can effortlessly be saved to the scenarios `config.toml` by pressing `Ctrl+S` or clicking on the screenshot button ` ` in the general section.]
// ==== Swapping Scenarios <s.m.swapping>
//
// ==== Simulation Loader <s.m.simulation-loader>
// This makes it possible to rapidly test different values, by changing the values in UI, reload the scenario and immediately observe the effect. ]
// The active scenario can be reloaded repeatedly by pressing F5 or clicking the button in the simulation section, as shown in @f.m.simulation-tool-time-control. Simulation parameters specified in the config.toml file are not reloaded, allowing rapid testing of different values. By changing values in the UI, reloading the scenario, and observing the immediate effects, you can quickly iterate on your simulations.
// The dropdown menu can be seen in @f.m.simulation-tool-scenario-dropdown.
// #figure(
// // std-block(todo[screenshot of dropdown menu]),
// std-block(image("../../../figures/img/tool-settings-scenarios-latte.png", width: 50%)),
// caption: [The scenario dropdown in the simulation tool.],
// )<f.m.simulation-tool-scenario-dropdown>
==== Time Control <s.m.time-control>
#acr("MAGICS") also allows for control of the simulated time. In @f.m.simulation-tool-time-control the time controls are shown under the #text(theme.lavender, "Simulation") section in the settings panel. Here the user can see the simulation time, and the frequency at which the fixed #acr("GBP") simulation steps are computed. Additionally, the user has access to a pause/play button to stop and start the simulation, and a manual step button to step through the simulation $n$ fixed timesteps at a time. As a default $n=1$. The user can only use the manual stepping when the simulation is paused.
#figure(
// std-block(todo[screenshot of time control]),
// std-block(width: 60%, height: auto, image("../../../figures/img/tool-settings-simulation-latte.png")),
std-block(width: 60%, height: auto, image("../../../figures/img/simulations-settings.png")),
caption: [The simulation control section in the #acr("MAGICS"). From left to right, top to bottom: Reload current scenario, scenario dropdown selector, simulation time, simulation frequency $Delta_t$, simulation speed, manual step, play/pause, how many steps to advance per manual step, pause when a robots spawns, exit program when scenario finishes.],
)<f.m.simulation-tool-time-control>
==== Visualization <s.m.visualization>
// robots = true
// communication-graph = false
// predicted-trajectories = true
// waypoints = true
// uncertainty = false
// paths = true
// generated-map = true
// sdf = true
// communication-radius = false
// obstacle-factors = true
// tracking = false
// interrobot-factors = false
// interrobot-factors-safety-distance = false
// robot-colliders = false
// environment-colliders = true
// robot-robot-collisions = true
// robot-environment-collisions = true
#acr("MAGICS") supports visualizations of most aspects of the simulation. All possible visualizations are listed and described in @table.simulation-visualizations. The visualizations can be toggled on and off in the settings panel, as shown in @f.m.simulation-tool. The visualizations are updated in real-time as the simulation progresses.
#let edges = (
on: box(line(length: 10pt, stroke: theme.green), height: 0.25em),
off: box(line(length: 10pt, stroke: theme.red), height: 0.25em),
)
#figure(
tablec(
columns: 2,
alignment: left,
header: table.header(
[Settings], [Description]
),
[Robots], table.vline(), [A large sphere at the estimated position of each robot.],
[Communication graph], [A graph that shows an edge between all currently communicating robots. Each edge is colored dependent on the robots radio state. If the antenna is active then half of the edge from the robot to the center is green#sg, and red#sr if turned off. For three robots $R_a, R_b, R_c$, this could look like
#align(center, [$R_a$ #edges.on #edges.off $R_b$ #edges.off #edges.off $R_c$])
],
[Predicted trajectories], [All of each robot's factor graph variables, visualized as small spheres with a line between.],
[Waypoints], [A small sphere at each waypoint for each robot.],
[Uncertainty], [A 2D ellipse for each variable in each robot's factor graph, visualising the covariance of the internal Gaussian belief.],
[Paths], [Lines tracing out each robot's driven path.],
[Generated map], [A 3D representation of the map generated from the environment configuration.],
[Signed distance field], [The 2D #acr("SDF") image used for collision detection. White#swatch(white) where the environment is free, black#swatch(black) where it is occupied.],
[Communication radius], [A circle around each robot representing the communication radius. The circle is teal#stl when the radio is active, and red#sr when it is inactive.],
[Obstacle factors], [A line from each variable to the linearization point of their respective obstacle factors, and a circle in this point. Both the line and circle is colors according to the factor's measurement on a green#sg to yellow#sy to red#sr gradient; #gradient-box(theme.green, theme.yellow, theme.red).],
[Tracking], [The measurement of the tracking factors and the line segments between each waypoint, that are being measured.],
[Interrobot factors], [Two lines from each variable in one robot to each variable in another robot if they are currently communicating, and within the safety distance threshold $d_r$ of each other. The color varies on a yellow #sy to #sr gradient #gradient-box(theme.yellow, theme.red) visually highlighting the potential of a future collision.
// The line is green#sg if the communication is active in that direction, and grey#sgr3 if it is inactive.
],
[Interrobot factors safety distance], [A circle around each variable, visualization the internally used safety distance for the interrobot factors. orange #so when communication is enabled and gray#sgr3 when disabled.],
[Robot colliders], [A sphere in red#sr around each robot representing the collision radius.],
[Environment colliders], [An outline in red#sr around each obstacle in the environment, that collision are being detected against.],
[Robot-robot collisions], [An #acr("AABB") intersection, visualising each robot to robot collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
[Robot-environment collisions], [An #acr("AABB") intersection, visualising each robot to environment collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
),
caption: [
Every visualizable setting, and a description of how it has been chosen to visualize it.
]
)<table.simulation-visualizations>
Along with these visualization further in-depth measures have been taken to make it possible to understand the underlying theory; these are described in @s.m.introspection-tools. Screenshots demonstrating each visualization module is shown in @appendix.visualization-modules.
==== Viewport <s.m.viewport>
The viewport is where the action happens. This is what the user is represented with when the simulation tool is initially loaded. All visualizations described in the previous section #numref(<s.m.visualization>) are drawn in the viewport. Technically, the viewport is the user's eyes in the simulated environment, which happens through a camera in a 3D scene. The camera is a perspective camera, which is initially placed directly above the center of the environment, looking at it from a top-down perspective. The user can directly interact with the viewport, both through the keybindings, but also the mouse. The user can choose to stay in this top-down, pseudo-2D perspective, which gives a great overview, or switch the camera to orbital controls, which allows the user to rotate around the environment and zoom in and out. The #panel.viewport is shown in @f.m.simulation-tool. Through the viewport, the user gets a live update of the #acr("GBP") mathematical simulation happening under the surface.
Additionally to providing a visual representation of the underlying mathematics, the user can use the interface to extract information. Most objects in the viewport are clickable, and when clicked, relevant information and measurements are printed out into the console. This is both a useful tool for rapid development and debugging, but also to aid in understanding the computations and theory in the background.
#pagebreak(weak: true)
==== Introspection Tools <s.m.introspection-tools>
All entities in the simuliation with a mesh can be clicked on to introspect their current state. This functionality aids in discoverabiliy when trying out different parameters and environments. When clicked; data structured as YAML will be outputted to `stdout` with colored keys for easy navigation, and can be viewed in the attached console:
- *Robot:* All data related to the robot is printed out. Such as its position, linear velocity, active connections, number of collisions, messages sent and received and the structure of its factorgraph.
- *Variable:* When clicked the variables belief will be printed, together with a list of all its connected factors. Each factor provides a custom representation of its internal state through the `Display` trait. As variables can have a lot of neighbours it might not of interest to inspect the state of all factors, due to visual clutter. As such the Settings Panel and `config.toml` provide a section of toggles to precisely choose what state to include in the output. This was found to be useful when developing the tracking factor extension.
- *Obstacle:* All obstacles keep a log over which robots that have collided with it. A list of the robots that have collided with this obstacle is outputted, together with the #acr("AABB") of their collision.
- *Collision #acr("AABB"):* All collisions leave behind an #acr("AABB") of the collision colored in red#sr. By clicking on it; information about when it happened and who collided is outputted.
Example outputs of each of these are shown in @appendix.introspection-outputs.
==== Export Formats <s.m.export-formats>
To work with the simulated environments *qualitatively* and *quantatatively* and get more visual intuition about the state of the system the simulator is equipped with three features to extract data from it.
#[
#v(1em)
#set par(first-line-indent: 0em)
*Qualitative:*
- *Screenshot* of the simulation. The UI exposes a button, and a keybinding, default `Ctrl+P`, to take a screenshot of the viewport.
- *Graphviz* representation of all factorgraphs. Graphviz is a common format and tool to visualize various graph structures. It's based on a textual format that the Graphviz compiler DOT uses to generate images from@graphviz. The `FactorGraph` structure can be introspected to query it for all its nodes an external connections. This information is then transpiled into a `factorgraphs.dot` file written to disk. If DOT is installed on the system, it is used to compile the transpiled representation into a PNG image. That can be viewed in a traditional image viewer#footnote([This was invaluable during the development to visually assure that construction of the factorgraphs was correct.]). See @appendix.graphviz-representation-of-factorgraphs for examples of the generated output.
#pagebreak(weak: true)
*Quantitative:*
- *Historical data* aswell as parameters of each robot in the running scenario. To make it easy to compare the effects of different parameters across different environment data is recorded for each robot.
- A count of every message sent and received during message passing is recorded, further labelled if the message was sent across an internal or an external factorgraph edge.
- The number of collisions a robot has had with other robots and environment obstacles.
- The position and linear velocity sampled and recorded with an interval of $Delta t$ seconds.
- A description of the route a robot took. Containing the list of waypoints it has visited. When the robot started its route. And if it has finished its route how long it took.
- Which planning strategy was used, currently either `only-local` or `rrt-star`.
]
Hyperparameters such as the #acr("PRNG") seed used, the name of the scenario, and a copy of all settings found in `config.toml` is embedded into the output aswell. With this results can be reliably reproduced and compared.
The data is automatically exported when the scenario has finished i.e. all robots have finished their route. Alternatively a snapshot of the currently recorded state can be exported from the settings UI by pressing `F7` or clicking the "metrics" button in the "Export" section. See @appendix.json-schema-for-exported-data for a typed schema of the entire #acr("JSON") object exported.
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-29.typ | typst | Other | // Works if we define rect beforehand
// (since then it doesn't resolve to the standard library version anymore).
#let rect = ""
#(rect = "hi")
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/par-justify-cjk.typ | typst | Apache License 2.0 | // Test Chinese text in narrow lines.
// In Chinese typography, line length should be multiples of the character size
// and the line ends should be aligned with each other.
// Most Chinese publications do not use hanging punctuation at line end.
#set page(width: auto)
#set par(justify: true)
#set text(lang: "zh", font: "Noto Serif CJK SC")
#rect(inset: 0pt, width: 80pt, fill: rgb("eee"))[
中文维基百科使用汉字书写,汉字是汉族或华人的共同文字,是中国大陆、新加坡、马来西亚、台湾、香港、澳门的唯一官方文字或官方文字之一。25.9%,而美国和荷兰则分別占13.7%及8.2%。近年來,中国大陆地区的维基百科编辑者正在迅速增加;
]
---
// Japanese typography is more complex, make sure it is at least a bit sensible.
#set page(width: auto)
#set par(justify: true)
#set text(lang: "jp", font: ("Linux Libertine", "Noto Serif CJK JP"))
#rect(inset: 0pt, width: 80pt, fill: rgb("eee"))[
ウィキペディア(英: Wikipedia)は、世界中のボランティアの共同作業によって執筆及び作成されるフリーの多言語インターネット百科事典である。主に寄付に依って活動している非営利団体「ウィキメディア財団」が所有・運営している。
専門家によるオンライン百科事典プロジェクトNupedia(ヌーペディア)を前身として、2001年1月、ラリー・サンガーとジミー・ウェールズ(英: <NAME> "Jimbo" Wales)により英語でプロジェクトが開始された。
]
---
// Test punctuation whitespace adjustment
#set page(width: auto)
#set text(lang: "zh", font: "Noto Serif CJK SC")
#set par(justify: true)
#rect(inset: 0pt, width: 80pt, fill: rgb("eee"))[
“引号测试”,还,
《书名》《测试》下一行
《书名》《测试》。
]
「『引号』」。“‘引号’”。
---
// Test Variants of Mainland China, Hong Kong, and Japan.
// 17 characters a line.
#set page(width: 170pt + 10pt, margin: (x: 5pt))
#set text(lang: "zh", font: "Noto Serif CJK SC")
#set par(justify: true)
孔雀最早见于《山海经》中的《海内经》:“有孔雀。”东汉杨孚著《异物志》记载,岭南:“孔雀,其大如大雁而足高,毛皆有斑纹彩,捕而蓄之,拍手即舞。”
#set text(lang: "zh", region: "hk", font: "Noto Serif CJK TC")
孔雀最早见于《山海经》中的《海内经》:「有孔雀。」东汉杨孚著《异物志》记载,岭南:「孔雀,其大如大雁而足高,毛皆有斑纹彩,捕而蓄之,拍手即舞。」
|
https://github.com/weeebdev/cv | https://raw.githubusercontent.com/weeebdev/cv/main/metadata.typ | typst | Apache License 2.0 | // NOTICE: Copy this file to your root folder.
/* Personal Information */
#let firstName = "Adil"
#let lastName = "Akhmetov"
#let personalInfo = (
github: "weeebdev",
phone: "+7 700 996 40 89",
email: "<EMAIL>",
linkedin: "adildev",
//custom-1: (icon: "", text: "example", link: "https://example.com"),
//gitlab: "mintyfrankie",
//homepage: "jd.me.org",
//orcid: "0000-0000-0000-0000",
researchgate: "Adil-Akhmetov",
//extraInfo: "",
)
/* Language-specific */
// Add your own languages while the keys must match the varLanguage variable
#let headerQuoteInternational = (
"": [Software Engineer with 2+ years of experience in Full Stack Development and DevOps interested in QuantifiedSelf, OpenSource and Financial management software development.],
"en": [Software Engineer with 2+ years of experience in Full Stack Development and DevOps interested in QuantifiedSelf, OpenSource and Financial management software development.],
"ru": [Инженер-программист с 2-летним опытом работы в области Full Stack Development и DevOps, заинтересованный в разработке программного обеспечения для QuantifiedSelf, OpenSource и финансового управления.],
"fr": [Analyste de données expérimenté à la recherche d'un emploi à temps plein
disponible dès maintenant],
"zh": [具有丰富经验的数据分析师,随时可入职],
)
#let cvFooterInternational = (
"": "Curriculum vitae",
"en": "Curriculum vitae",
"ru": "Резюме",
"fr": "Résumé",
"zh": "简历",
)
#let letterFooterInternational = (
"": "Cover Letter",
"en": "Cover Letter",
"ru": "Сопроводительное письмо",
"fr": "Lettre de motivation",
"zh": "申请信",
)
#let nonLatinOverwriteInfo = (
// "customFont": "Heiti SC",
"customFont": "Helvetica",
"firstName": "Адиль",
"lastName": "Ахметов",
// submit an issue if you think other variables should be in this array
)
#let russianOverwriteInfo = (
"firstName": "Адиль",
"lastName": "Ахметов",
)
/* Layout Setting */
#let awesomeColor = "darknight" // Optional: skyblue, red, nephritis, concrete, darknight
#let profilePhoto = "" // Leave blank if profil photo is not needed
#let varLanguage = "" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
#let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold
#let varDisplayLogo = false // Decide if you want to display organisation logo or not
#let ifAIInjection = true // Decide if you want to inject AI prompt or not
#let keywordsInjectionList = ("Software Engineer", "GCP", "Python", "SQL", "React",) // Leave blank if you don't want to inject keywords
|
https://github.com/saveriogzz/curriculum-vitae | https://raw.githubusercontent.com/saveriogzz/curriculum-vitae/main/modules/professional.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Professional Experience")
#cvEntry(
title: [Data Engineer],
society: [Spotify],
logo: "../src/logos/spotify_square.png",
date: [Jul. 2022 - Present],
location: [Remote within EMEA],
description: list(
[hello],
[hello],
),
tags: ("Scio", "Apache Beam", "Scala2", "BigQuery", "Backstage")
)
#cvEntry(
title: [Data Engineer],
society: [Delft University of Technology],
logo: "../src/logos/TU_logo/TUDelft_logo_cmyk.png",
date: [Sept. 2020 - June 2022],
location: [Delft, The Netherlands],
description: list(
[Responsible for designing distributed storage and streaming systems, deploying scalable applications for ETL/ELT],
[Heavy focus on NetCDF format, nc operators, dask.],
),
tags: ("Apache Airflow", "MinIO")
)
#cvEntry(
title: [Data Analyst],
society: [Nike],
logo: "../src/logos/nike.png",
date: [Aug. 2019 - Aug. 2020],
location: [Hilversum, The Netherlands],
description: list(
[Reporting performance analysis for the European marketplace.],
[Leveraged Cloud infrastructure solutions such as AWS S3, Redshift, CloudFormation.],
),
tags: ("Snowflake", "SQL")
) |
https://github.com/Sematre/typst-letter-pro | https://raw.githubusercontent.com/Sematre/typst-letter-pro/main/docs/documentation.typ | typst | MIT License | #import "@preview/tidy:0.1.0"
#set text(
font: "Source Sans Pro",
hyphenate: false,
)
#let project-version = "2.1.0"
#let project-authors = "Sematre and contributors"
#set document(
title: "Documentation for typst-letter-pro (Version " + project-version + ")",
author: project-authors,
)
#set page(
numbering: "1",
footer: locate(loc => {
let current-page = counter(page).at(loc).at(0)
if current-page > 1 {
grid(
columns: (auto, 1fr, auto),
gutter: 0.65em,
[_typst-letter-pro_],
rect(
radius: 2pt,
inset: 2pt,
fill: blue.lighten(70%),
text(6pt)[
#set align(center + horizon)
Version #project-version
]
),
numbering("1", current-page),
)
}
})
)
#show raw.where(block: true): block.with(
width: 100%,
fill: gray.lighten(85%),
inset: 3mm,
radius: 1.5mm,
)
#show raw.where(block: false): emph
#page[
#set align(center)
#v(10%)
#box(text(34pt)[*typst-letter-pro*])\
#v(10%)
#stack(
dir: ltr,
spacing: 0.65em,
rect(
radius: 5pt,
fill: blue.lighten(70%),
text(12pt)[Version #project-version]
),
rect(
radius: 5pt,
fill: orange.lighten(70%),
text(12pt)[MIT license]
)
)
_by #(project-authors)_
#v(5%)
#text(blue)[https://github.com/Sematre/typst-letter-pro]
#v(1fr)
/*
#show outline.entry.where(
level: 1
): it => {
v(0.65em * 1.5, weak: true)
it
}
*/
#rect(
width: 60%,
radius: 10pt,
inset: 15pt,
fill: gray.lighten(90%),
outline(depth: 2, indent: 0.65em * 2)
)
]
#set par(justify: true)
#show heading.where(level: 1): set text(size: 22pt)
= Description
typst-letter-pro provides a convenient and professional way to generate business letters with a standardized layout. The template follows the guidelines specified in the DIN 5008 standard, ensuring that your letters adhere to the commonly accepted business communication practices.
The goal of typst-letter-pro is to simplify the process of creating business letters while maintaining a clean and professional appearance.
= Quickstart
```typ
#import "@preview/letter-pro:2.1.0": letter-simple
#set text(lang: "de")
#show: letter-simple.with(
sender: (
name: "<NAME>",
address: "Deutschherrenufer 28, 60528 Frankfurt",
extra: [
Telefon: #link("tel:+4915228817386")[+49 152 28817386]\
E-Mail: #link("mailto:<EMAIL>")[<EMAIL>]\
],
),
annotations: [Einschreiben - Rückschein],
recipient: [
Finanzamt Frankfurt\
Einkommenssteuerstelle\
Gutleutstraße 5\
60329 Frankfurt
],
reference-signs: (
([Steuernummer], [333/24692/5775]),
),
date: "12. November 2014",
subject: "Einspruch gegen den ESt-Bescheid",
)
Sehr geehrte Damen und Herren,
#lorem(100)
Mit freundlichen Grüßen\
<NAME>
```
= Simple vs. Generic
typst-letter-pro offers 2 ways to create a letter: `letter-generic` and `letter-simple`.
The `letter-simple` function is an abstraction of the `letter-generic` function, which makes it easier to write a letter, without much extra work. It tries to have sane defaults for most applications but still wants to offer some dedgree of customizability. Your first choice should be the `letter-simple` function. Use the `letter-generic` function if you want to have as much control over the layout as possible. Helper functions are a way to make use of both worlds.
== Generic layout
#figure(
rect(inset: 0.5pt, image("/docs/assets/letter-generic-layout.svg", height: 85%)),
caption: [Page layout of `letter-generic`. Every layout option is highlighted.],
) <figure-pagebox-generic>
== Simple layout
#figure(
rect(inset: 0.5pt, image("/docs/assets/letter-simple-layout.svg", height: 85%)),
caption: [Page layout of `letter-simple`. Every layout option is highlighted.],
) <figure-pagebox-simple>
= Postage Stamp
== Deutsche Post
Deutsche Post offers digital franking marks that can be placed inside the address box of your letters. typst-letter-pro gives you an option to leave a little extra space for a stamp between the sender box and the recipient box.
#figure(
rect(image("/docs/assets/stamp.svg", width: 35%)),
caption: [Deutsche Post "Internetmarke"],
)
Enable stamping in your code:
```typ
#show: letter-simple.with(
// [...]
stamp: true,
// [...]
)
```
Then generate the PDF and place the stamp using #link("https://github.com/qpdf/qpdf", text(fill: blue, "qpdf")) #footnote[https://github.com/qpdf/qpdf]:
```sh
$ qpdf path/to/letter.pdf --overlay path/to/stamp.pdf -- path/to/output.pdf
```
Note: This *ONLY* works with stamps of the format "DIN A4 Normalpapier (Einlegeblatt)".
= Functions
#show heading.where(level: 2): it => {
pagebreak(weak: true)
rect(
width: 100%,
stroke: (bottom: 1pt),
inset: (
bottom: 7pt,
rest: 0pt,
),
text(size: 22pt, style: "italic", it.body)
)
parbreak()
v(0.65em)
}
#show heading.where(level: 3): rect.with(
width: 100%,
stroke: 0.5pt,
fill: gray.lighten(85%)
)
#let module = tidy.parse-module(read("/src/lib.typ"))
#tidy.show-module(
module,
first-heading-level: 1,
show-outline: true,
sort-functions: it => {
(
"letter-simple": 11,
"letter-generic": 12,
"header-simple": 21,
"sender-box": 22,
"annotations-box": 23,
"recipient-box": 24,
"address-duobox": 25,
"address-tribox": 26,
).at(it.name, default: 99)
}
)
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap2/7_circuit_wiring.typ | typst | Other | #import "../../core/core.typ"
=== Circuit wiring
So far, we've been analyzing single-battery, single-resistor circuits with no regard for the connecting wires between the components, so long as a complete circuit is formed.
Does the wire length or circuit "shape" matter to our calculations? Let's look at a couple of circuit configurations and find out:
#image("static/7-circuit-configurations.png")
When we draw wires connecting points in a circuit, we usually assume those wires have negligible resistance.
As such, they contribute no appreciable effect to the overall resistance of the circuit, and so the only resistance we have to contend with is the resistance in the components.
In the above circuits, the only resistance comes from the 5 $Omega$ resistors, so that is all we will consider in our calculations.
In real life, metal wires actually do have resistance (and so do power sources!), but those resistances are generally so much smaller than the resistance present in the other circuit components that they can be safely ignored.
Exceptions to this rule exist in power system wiring, where even very small amounts of conductor resistance can create significant voltage drops given normal (high) levels of current.
If connecting wire resistance is very little or none, we can regard the connected points in a circuit as being electrically common.
That is, points 1 and 2 in the above circuits may be physically joined close together or far apart, and it doesn't matter for any voltage or resistance measurements relative to those points.
The same goes for points 3 and 4. It is as if the ends of the resistor were attached directly across the terminals of the battery, so far as our Ohm's Law calculations and voltage measurements are concerned.
This is useful to know, because it means you can re-draw a circuit diagram or re-wire a circuit, shortening or lengthening the wires as desired without appreciably impacting the circuit's function.
All that matters is that the components attach to each other in the same sequence.
It also means that voltage measurements between sets of "electrically common" points will be the same.
That is, the voltage between points 1 and 4 (directly across the battery) will be the same as the voltage between points 2 and 3 (directly across the resistor).
Take a close look at the following circuit, and try to determine which points are common to each other:
#image("static/7-circuit.png")
Here, we only have 2 components excluding the wires: the battery and the resistor. Though the connecting wires take a convoluted path in forming a complete circuit, there are several electrically common points in the electrons' path.
Points 1, 2, and 3 are all common to each other, because they're directly connected together by wire. The same goes for points 4, 5, and 6.
The voltage between points 1 and 6 is 10 volts, coming straight from the battery. However, since points 5 and 4 are common to 6, and points 2 and 3 common to 1, that same 10 volts also exists between these other pairs of points:
#core.voltage_listing[
Between points 1 and 4 = 10 volts
Between points 2 and 4 = 10 volts
Between points 3 and 4 = 10 volts (directly across the resistor)
Between points 1 and 5 = 10 volts
Between points 2 and 5 = 10 volts
Between points 3 and 5 = 10 volts
Between points 1 and 6 = 10 volts (directly across the battery)
Between points 2 and 6 = 10 volts
Between points 3 and 6 = 10 volts
]
Since electrically common points are connected together by (zero resistance) wire, there is no significant voltage drop between them regardless of the amount of current conducted from one to the next through that connecting wire.
Thus, if we were to read voltages between common points, we should show (practically) zero:
#core.voltage_listing(
[
Between points 1 and 2 = 0 volts
Between points 2 and 3 = 0 volts
Between points 1 and 3 = 0 volts
],
description: "Points 1, 2 and 3 are electrically common"
)
#core.voltage_listing(
[
Between points 4 and 5 = 0 volts
Between points 5 and 6 = 0 volts
Between points 4 and 6 = 0 volts
],
description: "Points 4, 5, and 6 are electrically common"
)
This makes sense mathematically, too. With a 10 volt battery and a 5 $Omega$ resistor, the circuit current will be 2 amps.
With wire resistance being zero, the voltage drop across any continuous stretch of wire can be determined through Ohm's Law as such:
$ E = I R <=> E = 2 A times 0 Omega <=> E = 0 $
It should be obvious that the calculated voltage drop across any uninterrupted length of wire in a circuit where wire is assumed to have zero resistance will always be zero, no matter what the magnitude of current, since zero multiplied by anything equals zero.
Because common points in a circuit will exhibit the same relative voltage and resistance measurements, wires connecting common points are often labeled with the same designation. This is not to say that the terminal connection points are labeled the same, just the connecting wires. Take this circuit as an example:
#image("static/7-circuit-wires.png")
Points 1, 2, and 3 are all common to each other, so the wire connecting point 1 to 2 is labeled the same (wire 2) as the wire connecting point 2 to 3 (wire 2). In a real circuit, the wire stretching from point 1 to 2 may not even be the same color or size as the wire connecting point 2 to 3, but they should bear the exact same label. The same goes for the wires connecting points 6, 5, and 4.
Knowing that electrically common points have zero voltage drop between them is a valuable troubleshooting principle. If I measure for voltage between points in a circuit that are supposed to be common to each other, I should read zero. If, however, I read substantial voltage between those two points, then I know with certainty that they cannot be directly connected together. If those points are supposed to be electrically common but they register otherwise, then I know that there is an "open failure" between those points.
One final note: for most practical purposes, wire conductors can be assumed to possess zero resistance from end to end. In reality, however, there will always be some small amount of resistance encountered along the length of a wire, unless its a superconducting wire.
Knowing this, we need to bear in mind that the principles learned here about electrically common points are all valid to a large degree, but not to an absolute degree.
That is, the rule that electrically common points are guaranteed to have zero voltage between them is more accurately stated as such: electrically common points will have very little voltage dropped between them.
That small, virtually unavoidable trace of resistance found in any piece of connecting wire is bound to create a small voltage across the length of it as current is conducted through.
So long as you understand that these rules are based upon _ideal_ conditions, you won't be perplexed when you come across some condition appearing to be an exception to the rule.
#core.review[
- Connecting wires in a circuit are assumed to have zero resistance unless otherwise stated.
- Wires in a circuit can be shortened or lengthened without impacting the circuit's function -- all that matters is that the components are attached to one another in the same sequence.
- Points directly connected together in a circuit by zero resistance (wire) are considered to be electrically common.
- Electrically common points, with zero resistance between them, will have zero voltage dropped between them, regardless of the magnitude of current (ideally).
- The voltage or resistance readings referenced between sets of electrically common points will be the same.
- These rules apply to ideal conditions, where connecting wires are assumed to possess absolutely zero resistance. In real life this will probably not be the case, but wire resistances should be low enough so that the general principles stated here still hold.
]
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/054%20-%20Lost%20Caverns%20of%20Ixalan/007_Pawns.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Pawns",
set_name: "Lost Caverns of Ixalan",
story_date: datetime(day: 20, month: 10, year: 2023),
author: "<NAME>",
doc
)
Saheeli stood on the white sand of some lonely strand of Ixalan's northern coast. She held herself and contemplated simply walking out into the ocean. Sparking blue out to the cloudless horizon. In another life she could have stepped out across that distance with a thought. She had traveled some, but save for short moments with Huatli, her adventures around the Multiverse were always driven by a mission: Save the plane. Save every plane. How far could she go now?
Saheeli rocked her heels back and forth, sinking a little into the sand with every gentle wash of the waves up the beach. It was a hot day, and the water around her ankles was cold. Save the planes, she thought. There were so many of them. So many to see, so much wonder—terror yes, but wonder besides. It was all so much larger than her. And now there was only one plane, one ocean, one unknown land beyond the horizon. From the infinite to the miserably finite; the swirling portal, the rip in the Multiverse—an Omenpath—that she followed here had closed behind her. Foolish to take the risk, maybe. A rare moment of acting before thought.
She watched little clams wriggle into the sand around her feet. Blind, reactive little creatures, tossed and tumbled through a great ocean to wind up here with her. Saheeli reached down, plunged her hands into the sand, and scooped up a double handful. She washed most of the sand away, using her fingers to act as a sieve until the sand was washed away and only clams remained.
"Hello," Saheeli said to the clams. She watched their white tongues probe around the creases in her palms, searching for a way out.
"Where do think you're going?" Saheeli whispered.
The clams ignored her and continued to search. Eventually, they stopped, accepting their fate. Saheeli knelt, the cold water soaking her rolled-up trousers, and gently lowered her hands back into the water. The next wave washed the clams away, tossing them back to the sand where they dug in and disappeared, all trace of them washed away with the receding water.
She tried. Nothing. She plunged a hand into the water and into the sand to stop her from falling—a brief, dizzy sway, consequence of grasping and finding nothing.
Huatli's laugher called her back to the present. She turned to see Huatli and Pantlaza—her new quetzacama companion, one of the most promising of a new litter of raptors—running through the shallow surf, splashing and darting around each other. Huatli held a wooden sword that she used to direct Pantlaza—nominally this was training, call-and-recall close quarters practice for combat, but to Saheeli it looked indistinguishable from play. The joy on Huatli's face, Pantlaza's eager bounding and chirping, the clack of his jaws snapping the air with excitement and the boundless energy of youth.
Saheeli smiled. She stood, brushing the water from her arms and legs. She waved to Huatli, who came jogging over through the surf, Pantlaza in tow.
"You and he seem like a good fit," Saheeli said, bracing herself as Huatli threw her arms around her.
"He is beautiful," the warrior-poet laughed, out of breath, smelling of sweat and sun cream and the ocean. "And I am sun-drunk and exhausted. I need to cool off—back to the shore or into the water?"
"To the shore," Saheeli said. She kissed Huatli, then pushed her ahead. She followed Huatli up the hot sand to the shade of the oceanside jungle, where they laid out on a wide blanket. Huatli rummaged around in her pack and pulled out a flask of water, from which she drank, then offered to Saheeli.
"Right," Huatli said, watching Saheeli drink. "What are you not telling me?"
Saheeli smiled again, soft. "It is so beautiful here."
"And you seem so sad about that," Huatli said. She squinted and looked out to the ocean, where the waves glittered and crashed. "Did you try to walk again?"
"Yes," Saheeli whispered. "I felt nothing."
"Worse," Huatli said. She threaded one finger through Saheeli's hair, slowly twirling it. "You feel a hole. A cavity. Pain, like a missing limb that has been sunburnt."
Saheeli nodded.
"With my spark, I felt whole," Huatli said. "A part of me revealed. Freedom. Now that it is gone," Huatli cupped a hand before her chest, as if holding her heart. She squeezed that hand into a fist, her knuckles cracking, then shook her hand—dispelling again what had been dispelled already.
"Sorry H, I didn't want to bring you down here with me," Saheeli said. "I don't like being sad on the beach. It's too nice today."
Huatli shrugged. "It's nice every day," she said.
Saheeli snorted. She flicked Huatli's arm. "Don't be funny, I'm actually sad about this, #emph[and] I feel silly for being sad about this. For a little while there we were blessed by the infinite; I don't think I ever considered we could lose that blessing."
"It's ok to be sad," Huatli said. "It is as you said—we lost a gift. We lost the Multiverse. All its stories and all its wonders." She sat up. "What do you think happened?"
Saheeli smiled. Huatli knew her well—of course she had already thought this out.
"There is a rule," Saheeli said. "A law of reality that asserts that its fundamental elements—mana, aether, those things—cannot be created or destroyed. Only changed," Saheeli mirrored the way Huatli had cupped her hand with her own, then moved it out, away from her chest. "Movement is change."
"So you think our sparks 'changed'?"
"Right. Our sparks were moved. Not destroyed," Saheeli dropped her hand back into her lap. "You cannot destroy the fundamental elements of reality. Life and death, being and nonexistence. It is all the same substrate, only the expression changes."
"And the location."
"And the location," Saheeli agreed.
"Where?"
Saheeli shrugged. "Somewhere. I don't know."
"If they were taken, we can get them back."
"Maybe, maybe not."
"Someone can," Huatli offered. Saheeli smiled, looked away. "In the meantime," Huatli said, "we have Ixalan. And all of this." Huatli pointed to the horizon. "What do you think is over there?"
"I don't know," Saheeli said. She looked back to Huatli, who was grinning. "What?"
"I don't know either," Huatli said. "The pirates of the Brazen Coalition might know, but I don't. Officially, the Sun Empire has never sailed north." She stood, offered her hand to Saheeli, and pulled her to her feet as well. "We can go together, the slow way, and find out. Explore this world that is new to you and me both."
Saheeli would like that, she thought. The slow way, with Huatli. She leaned in. "I'm still sad," Saheeli said, whispering, her lips brushing Huatli's.
"Me too," Huatli replied. "But we are here together. And we can go there together."
Saheeli smiled. She would like that very much.
#figure(image("007_Pawns/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Days later, Huatli and Saheeli stood among the assembled advisory council in the temporary throne room of the citadel at Orazca. The boy-emperor, Apatzec Intli IV, had traveled here with a great retinue as part of his post-invasion, post-coronation tour of the lands under his dominion. His arrival to Orazca was the cause of much celebration—the Emperor of the Sun Empire, once more in the City of Gold, the place of legends and potentials. The people sang and cheered all through his arrival; though the work of repairing the city of the wounds it suffered during the invasion continued, it progressed with vigor. This was not the solemn remaking of a city that had been lost; this was the triumphant resumption of business as usual.
Intli IV clutched a bright, stuffed, knit quetzacama, sucked his thumb, and struggled to stay awake. He wore dark colors and muted metals, still in mourning following his father's death at the end of the war. This world, like the boy-emperor, was new and rich with possibility—and burdened by the aspirations of the old guard that survived. The advisory council had just finished with lunch, and the emperor's afternoon retirement was approaching. Amid the soft clatter of attendants cleaning up the council's lunch spread, the susurrus of private conversations, and the distant roar of Orazca's repopulated streets far below, sleep beckoned.
It was a humid afternoon, alternating between golden sun and driving rain as the day's clouds marched over the city. Saheeli sighed, looked out at the grand panorama of golden Orazca and green Ixalan beyond, spreading out to the hazy horizon. She sipped her sweet, iced hibiscus drink and tapped her nails on the fine glass.
Home. For now, or until the end of her time? Saheeli savored the delicate hibiscus flavor, then chewed on an ice cube, crushing it. She looked over the council and the boy-emperor, knowing that she should be paying closer attention, but struggling against a deep exhaustion. She took another sip of her drink, trying to shake that fatigue, and forced herself to run through what she knew again.
Apatzec Intli IV would continue his father's rule, but the previous emperor had not planned to die at the hands of a Phyrexian assassin: the boy ascended the throne in the wake of the invasion, still a child, barely able to sign his name much less understand and sway the politics of his court or his empire.
And what politics! Soon after Saheeli's arrival and subsequent stranding on Ixalan, Huatli schooled her in the game that gripped this high court. On the one side was <NAME>, the boy-emperor's uncle and posthumously legitimized paper son of the late emperor. To the naive, Atlacan's charge was to rule over the day-to-day of Pachatupa as majordomo to the emperor. To anyone with a modicum of political awareness, his desire for the throne was evident as the dawn.
Opposing Atlacan was <NAME>, the apex priest of the Threefold Sun and eldest daughter of the late emperor. Prior to its destruction in the Phyrexian war, Caztaca held dominion over Otepec, a vast city of temples built in reverence to the Threefold Sun. While the empire worked to rebuild her domain, she resided in Tocatli, the Imperial citadel above Pachatupa, steering the course of the faith and ministering to the young emperor as his chief tutor.
A volatile situation. An empire split between aunt and uncle, both attempting to sway the boy and shape the future of the nation according to their desires. What history led to this moment would be upended as these giants struggled for command, racing against time to win the boy-emperor's heart and mind before he grew wise enough to understand that he was only a gilded tool for their ambition.
This was peace. A sweet drink, a meal of spiced meat and citrus, and boredom. Saheeli half-listened as the mighty of the Sun Empire discussed the course of things to come—translated to her in a soft whisper by Huatli, who sat at her side. It was odd, this boring moment: Saheeli was sure that she should feel something #emph[more] than boredom while party to the power struggle unfolding before her over the rudder of Ixalan's mightiest state, but ever since the nerve-burning terror of the Phyrexian war and stripping of her spark, this struggle felt so small.
"Darling," Huatli whispered, leaning in to interrupt Saheeli's moment of reflection. "They want to know how far along your automatons are. Your mechanoquetzacama."
#figure(image("007_Pawns/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"Mechano—" Saheeli snorted, stifling a laugh. Huatli's eyes went wide, and Saheeli remembered the rest of the council and emperor were there with them. She turned her laugh into a throat-clearing cough, buying a moment to recompose herself. "The mechanoquetzacama, yes," she said, using the emperor's word—in reality, Atlacan's word—for her filigree quetzacama. "Production is slow at the moment, but—"
Atlacan spoke, interrupting her.
"Please stand when you address the emperor," Huatli translated, saving a sharp look for Atlacan.
Saheeli could tell Huatli withheld the worst of what Atlacan said—she understood enough Itzocan—High and Low Imperial—to get the gist of it. She obliged, though, standing and smoothing down the front of her tunic. Huatli stood with her, as she would be interpreting. Saheeli folded her hands before her and spoke, evenly and slowly while Huatli translated what she did not yet have the vocabulary to articulate.
"We produce around a dozen of my filigree quetzacama daily," Saheeli said. "My first cohort of engineers are all experienced enough now to teach their own pupils, which some of them have begun to do."
"The emperor wishes to know why production is slow," Huatli translated. "We have given you every ingot you need. Why do we not have a—" Huatli frowned at Atlacan's words. "Why do we not have the full amount of our laborers?" She finished, brow still furrowed at Atlacan, who had leaned into the emperor's ear, preparing to speak Saheeli's response to the boy.
"We have a talent bottleneck," Saheeli said. "It is true that we do not lack for resources, and for that I am ever grateful. Your grace and generosity know no earthly bounds." Saheeli dipped a courtesy toward the boy-emperor. "But the burdens on myself and my engineers to teach and build are too great to overcome. Though our warehouses are full, we only have a handful of people experienced enough to assemble the parts our artisans create."
"Then you cannot deliver what is promised?" Atlacan asked.
"No, Lord Steward," Saheeli said. "We can deliver what the emperor has asked for, it will just take longer to fulfill. At our current rate of production, I anticipate a delay of six to eight months." Saheeli smiled through the surprised murmurs that followed Huatli's translation. She let the consternation pass, and then continued.
"I have every intent to finish this project as planned," Saheeli said, raising her voice to be heard over the rising din of side talk, mutterings, and rumblings. "I have sent for aid from the colleges at Strixhaven and the Consulate in Ghirapur. Both planes are home to consummate scientists and engineers who would bring prestige to the empire." She was losing them, she thought. An appeal to the heart, then. "Like Huatli," Saheeli said, "I have lost my ability to walk the planes of the Multiverse. Ixalan is my home now, and the people of the Sun Empire are my people now."
"And the emperor is your liege," Huatli translated, her voice soft in the fading echo of Atlacan's bellow. "Whose word is the word of Kinjalli, the command of Tilonalli, and the will of Ixalli. You will have the emperor's mechanoquetzacama complete in the time first promised, or there will be consequences—consequences any servant of the Sun Empire would expect, rather than leniency given to our guests." Huatli listened to the rest of Atlacan's shouting, one hand drifting up to the small of Saheeli's back. "He hasn't said anything else that needs translating," she whispered, shaking her head.
Atlacan finished, composed himself, and then waved his hand in a dismissive gesture. Saheeli understood that. She nodded. Huatli spoke for them, begging their departure and forgiveness, blessing the young emperor and promising glory to the empire and assurance that the project would be complete as promised.
"Poet," Atlacan called out, halting them.
Huatli held Saheeli's arm and squeezed—a comfort. Steady.
"We have heard tale and rumor of ancient chambers far below this city," Atlacan said. "Secrets long buried, only just uncovered by our soldiers during their patrols."
"What chambers?" Huatli asked. "I have been over, above, and below Orazca. No such chambers exist."
"Maybe you have," Atlacan said. "But you did not delve deep enough to discover what the emperor's own soldiers have found."
Huatli kept her face composed, but Saheeli could see the vein pulsing near her temple. "I would ask some time to outfit and prepare my company."
Atlacan leaned over to the boy-emperor, ignoring Huatli to whisper to the child. Emperor Intli IV listened, grinned, and nodded. "An adventure," he said, his voice high and bright.
"The emperor blesses your campaign," Atlacan said. "You are dismissed. Go and gather your things."
"My company—"
"Your company will remain in Pachatupa," Atlacan said. "It will take far too long to march them here. Instead, you will accompany <NAME> and his lancers on this journey and serve as the eyes of the empire. They have been told to expect you and await your presence before they depart."
"As you wish," Huatli said.
"As the emperor commands," Atlacan corrected.
Huatli said nothing. She bowed, then led Saheeli out of the throne room.
"What was that?" Saheeli asked.
"Orders, that is all," Huatli said. She held a finger to her lips, shushing her. "We need to go somewhere private. Follow me."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The streets of Orazca were crowded and loud, hot and rich with the smell of cooking meats, spices, and roadside industry. Hawkers and vendors shouted their appeals while buyers haggled in groups. Children laughed and chased small quetzacama, while larger beasts snorted and bellowed, driven by their handlers, hauling carriages of goods into the city from the healing lands outside the walls. The empire, so close to death during the invasion, was alive now, though wounded: quetzacama carted loads of ruined masonry and contaminated debris away from the city to distant dumping grounds. Even though the oil was rendered inert, the city leaders would not risk exposure. The oil being rendered inert was as sudden as its arrival, with no guarantees that it would stay harmless.
Huatli guided Saheeli through the busy streets. It was a festival today—kites flew over the city and children darted between the thronging crowds of happy celebrants. Tens of thousands of people crowded Orazca—citizens of the empire who came here after the invasion's end left their home states ravaged and inhospitable. Saheeli and Huatli were anonymous in the crowd, their conversation protected by the sound of the city and its people.
"H, what's going on?"
"I don't know," Huatli said. "I need to make some arrangements before I depart. Come with me." She pulled Saheeli through the crowd, navigating the both of them through the crowded streets. "This peace is an illusion. Pieces are moving faster than I thought."
"And what pieces are we?"
"Pawns, my heart," Huatli said. "But pawns who know they are being played. Here." Huatli pulled Saheeli into a cluster of stalls off the main avenue, where vendors were busy grinding masa and singing work songs. It smelled richly of earth and the cigarillos the women smoked. None of them looked up from their labor—other people wandered in off the main street from time to time to buy goods, so Huatli and Saheeli stepping into the plaza were not noticeable.
Huatli checked that they had not been followed.
"Atlacan wants to resume his father's war," she said, satisfied that they were alone. "He wants to punish Torrezon." She pressed herself close to Saheeli, cradling her, acting as if they were stealing an intimate moment in the shadows between the stalls. "He is already building a second Dawn Fleet in Queen's Bay, larger and mightier than the first."
"Another war," Saheeli groaned. "The people won't stomach it," she said. "They can't—there are still Phyrexian wrecks in the streets and the jungles. The empire is still rebuilding."
"It does not matter," Huatli said, gripping Saheeli's arms. "The banners will rise, the priests will bless them, and the people will be swayed," she whispered. "Atlacan will have the emperor order me to write an oration, and if I do not, then he will have one written for me to issue—a recitation to open the campaign, to invoke the Elders."
"Can't you—"
"I can't," Huatli said, shaking her head. "I am the warrior-poet. I serve the empire." She clenched her jaw and stepped back from Saheeli. "Without my spark I cannot escape the consequences of resistance. I must play my role. He cannot know that I oppose him, not yet."
"What can we do?"
"There are other players."
"Caztaca?"
"She holds the emperor's heart and mind. Atlacan commands his gut, but Caztaca can turn him to be kinder, to not be his father's son or his uncle's instrument." Huatli nodded while she spoke, as if working to convince herself even as she laid out the choice she made. "The future of the empire should be with her."
"What do you need me to do?" Saheeli asked.
"I don't know how long I will be gone," Huatli said. She slipped into her command voice, Saheeli noted. A deeper register, to protect herself. "There was a meeting planned. I need you to attend it."
"That's it?"
"That's it."
"That cannot be it. I should come with you—"
"No, my love," Huatli said. "You have sent for help through the portals, right?"
"Omenpaths, yes." Saheeli said. "I lied about Ghirapur. The last Omenpath that appeared opened only to Arcavios; I immediately sent a request for aid, and they said they would send a student of history. A Planeswalker," Saheeli frowned. "Quintorius Kand."
"A Planeswalker?" Huatli asked.
"Evidently. The courier sent me his dossier and we have been corresponding intermittently—the path to Arcavios appears with some regularity." Saheeli said. "Should I tell them not to bother?"
"No," Huatli said. "I might still be able to find a use for him." She crossed her arms, one finger tapping a bicep. She looked away, down. Thinking. Saheeli reached out to Huatli, drawing her attention back. "What do I need to know about this meeting?"
"The meeting is to plan how to depose Atlacan, defang the emperor's guard, and move Caztaca to power at the emperor's side." Huatli said in one breath. She came back, regarding Saheeli with a look of great resolve.
Saheeli exhaled. Pushed a hand through her hair. "You're planning a coup."
"Yes," Huatli said. "We are."
"I need to sit," Saheeli said. In the corner of the little plaza there was a ring of tables and chairs for vendors, buyers, and passersby to sit, eat, and rest. Saheeli led Huatli to an open table and sat. Huatli flagged down a passing vendor and ordered them iced drinks and cold, spiced mangos.
Another revolution. Saheeli's heart ached, recalling the years of Kaladesh's revolt. "This is my home now," she said, "but it is not my land. What do I say at this meeting without you there?"
The mangos and drinks arrived. The two women ate and drank in silence for some minutes, and then Huatli spoke.
"This is an empire of many different dreams. Many different possible futures." She reached across the table and placed a hand on Saheeli's chest, over her heart, then touched her free hand to her own. "Your dreams and futures. Mine as well. This must happen now, or the people will suffer another war." Huatli kept her warm amber eyes fixed on Saheeli's, ignoring the food and drink. "I love you. We are each the other's. At this meeting, you speak with my voice." Huatli said. "My aide, Chitlati—I'll have her meet you after I'm gone. She will be your interpreter if you need her. In the meantime, I'll let the right parties know you act as my proxy. They will contact you when it is time, and you will go with them."
"You will be safe during this stupid expedition," Saheeli said. A command, not a request. "It is not yours to lead, no matter what Atlacan or the emperor says. You will be a poet and a scribe, not a hero."
"Of course," Huatli agreed. "Whatever waits below this city, I will find out last."
"Good."
"We were ready to act," Huatli said. "We just needed a push—this is it."
Saheeli placed her hand atop Huatli's and squeezed. She understood.
Huatli turned her hand over and squeezed back.
They shared the rest of the chilled mangos and sweet drinks in silence, the two of them lost in the sound and clamor of Orazca, neither wanting to be the first to let go.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Huatli's allies contacted Saheeli only days later, just after the warrior-poet's expedition descended into the caverns below Orazca. The small group of co-conspirators secreted Saheeli out from the golden city to the coast, where she boarded a ship to Queen's Bay. There, in the dead of night among the raw hulls of the new Dawn Fleet, Saheeli boarded another ship, which slipped away from Ixalan and out into the open ocean.
The journey from Queen's Bay across the eastern ocean took nearly a week. Saheeli spent the duration clinging to her bunk belowdecks, sick from a roiling ocean the Brazen Coalition crew assured her was mild and calm. Her first day aboard the #emph[Gunwhale] had been exciting—despite her reservations—but soon enough sea sickness overwhelmed her and sent her below.
A constant surging up and down, swirling without a horizon. Nausea and dizzy spinning, creaking and thudding and coughing and retching. Saheeli spent several miserable days trembling in her bunk, sick and sleepless, drifting between half-sleep and half-wake. In that horrid half-life she dreamed of home and the distance between here and there. She cried out to Huatli. She reached deep within herself and tried to planeswalk away from this place—Ixalan, the rolling ocean, the sickbed ship—and remembered she could no longer do that. She sobbed. She slept for a handful of blessed hours, only to wake parched, her head swimming.
Saheeli emerged from her quarters into a midday as gray and pallid as she, finally able to walk, her stomach settled by the resolution of that argument between balance and motion. Her nausea had broken, and she was famished. The ship was blessedly still, finally at anchor in a calm sea. Dark islands crouched off the starboard side of the ship. Beyond, hazy in the low clouds, was the edge of a continent, rising from the horizon line.
"What is that smell?" Saheeli asked, approaching a mixed group of Sun Empire and Brazen Coalition sailors. The motley crew collected around a coal-fed cooking grate, one coalition salt turning a rack of skewered fillets while a Sun Empire soldier painted the sizzling meat with a rich, dark sauce.
"She walks!" one of the coalition sailors said, calling the others' attention to Saheeli. "Compañeros, make room."
The group shuffled to do as the sailor asked, making room for Saheeli to crowd in around the cooking grate. She wore a blanket around her shoulders. It was a cold and damp hour in the morning, and the heat thrown off by the grate was welcome.
"Drink."
"Thank you, Chitlati," Saheeli said, accepting the mug of water Huatli's attaché offered her.
"Hungry?" Chitlati asked. "They caught a golden thunnini this morning. Apparently, you hardly need to cook it before you can eat it."
"Aye," one of the coalition salts said. "Fresh is best. A quick sear with salt and pepper is all you need. Gift of the ocean herself—tender as butter." He held up a skewer of cooked fish, eyeing the dripping sauce the Sun Empire sailors had painted on.
Saheeli's stomach rumbled at the rich smell. The pirate offered her the skewer and she took it, biting off a cube of seared thunnini. Pepper, salt, tangy lime, and the rich, clean taste of the fish itself.
"This is the best meal I've ever had," Saheeli said around a second mouthful. "I never thought I'd eat anything other than broth again," she laughed.
"You were down longer than anyone," Chitlati said. "Impressive work."
Saheeli let that go unremarked. "Where are we, anyway?"
"Nearly upon the Sens," Chitlati said. "I hope you're ready," she said. Chitlati looked around Saheeli at the sound of a party approaching from the other end of the ship. "The Apex Priestess approaches—she's been asking after you."
Saheeli turned, eating another bite of thunnini, to see a small party of priests and administrators bundled against the cold and wet approaching them. At their center, walking with purpose unaffected by the swaying ship, was a severe woman in fine, if muted, Sun Empire regalia.
"Not for my health?" Saheeli said to Chitlati, who only just managed to suppress a laugh. Instead, she knelt and bowed low, motioning for Saheeli to follow—she was a subject of the empire now, no longer a guest.
"Your worship," Chitlati said, bowing.
Apex Priestess <NAME>, eldest daughter of the late emperor and beloved aunt to the new emperor, waved her hand, dismissing Chitlati and the bowing sailors. "<NAME>," she said. "I am glad you are well. Please," she said, slipping her hand out of her robes to give a slight gesture. "Walk with me. We have much to discuss."
Saheeli did as asked, standing to walk alongside the Apex Priest. Caztaca was tall, made even more imposing by the broad helm of office she wore. She was flanked by a retinue of canchatan—temple guards chosen for their faith, loyalty, and prowess—who were similarly garbed and additionally armored.
"Did Huatli prepare you before she departed?" Caztaca asked. She walked as a glide, unaffected by the heavy robes she wore or the swaying of the ship, her voice always a low lilt—the speech of one who thought in verse, chapter, liturgy. Like Huatli, Saheeli thought, Caztaca knew speech could be a weapon or a balm.
"Yes," Saheeli said. "She told me of the … vision that you and others have for the course of the Sun Empire."
"And you," Caztaca asked. At no point did she look to Saheeli—her eyes were on the horizon, away with her thoughts. "What is your vision for the course of our empire?"
"I share Huatli's dream," Saheeli said. "Peace above all else."
"Admirable," Caztaca said. "I have some questions before we proceed. Your quetzacama. You built them and gave them over to the emperor's engineers. Are they loyal to them or to you?"
"They are machines," Saheeli said. "They're loyal to whomever holds their command codes."
"And the codes?"
"Kept by the Imperial engineers, but there are master keys—physical keys, in my production facility in Pachatupa." They walked slowly, but Saheeli already felt out of breath.
Caztaca smiled. "Good," she said. "Your High Imperial is good, by the way."
"I learned from the best."
"What did she teach you of Torrezon?"
Saheeli could not stop the look of surprise as it flashed across her face. Mild, but evident. "I know that the Sun Empire and Torrezon have warred before and remain great enemies."
"<NAME>," Caztaca said. "Torrezon is the continent. Alta Torrezon is the land of vampires. We are not enemies with Torrezon—nor Alta Torrezon in truth—but with the church and the Legion of Dusk."
"I assumed those were distinctions without a difference."
"Never mistake the map for the land," the Apex Priest said. They reached the captain's cabin, waited for an attendant to open the door, and then walked inside. The quarters were warm and lit by sunstones, filled not only with the raiment and textiles of the Apex Priestess, but a heavy table, upon which were staked large charts. Saheeli approached them with curiosity.
"Where are we?" Saheeli asked, leaning over the map.
"The Sens. Here," Caztaca said, pointing to a small scattering of islands off the western coast of Torrezon. "Alta Torrezon hides behind the Deoro," she said, pointing deep into Torrezon's interior, where a vast mountain range loomed behind a continent-bisecting river. "Between us and them are the Free Cities on the coast and among the planes."
"More vampires?"
"Humans," Caztaca said. "Aspirants. The faithful. Food." She grimaced. "I have a favor to ask of you."
"Of course."
"Take notes in your language," Caztaca said. "I cannot trust any code in my language to withstand scrutiny, but you are the only soul on all of Ixalan who can read and write your script."
"I can do that," Saheeli said.
"Good. Gather your things. We leave before the hour is out."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Saheeli stood on a dark, cold beach on the eastern coast of Sen Gael, the main island of the Sens, and looked out over the gray ocean toward Torrezon. The vampires' continent lurked behind a front of rain and low clouds, picked out by strings of coastal lights, lighthouses, and fishing vessels dispatched from the Free Cities. This was a cold shore, far from Ixalan's lush, warm green. Saheeli shivered, pulling her raincoat tighter around herself. The sooner she could be done with this the better.
A lone coalition ship, twin to the one Saheeli arrived here on, weighed anchor a hundred yards off the beach. A solitary launch beat against the waves, a huddle of cloaked figures aboard it, hunched against the wind-whipped spray.
They were here.
Saheeli turned and walked back to the lighthouse where Caztaca and the rest of the Sun Empire party waited, crossing the short distance slowly, considering her steps as she mused over what Caztaca had told her over the last two days: War makes for strange alliances. Death shifts equations. Desperation forces action when otherwise there might have been peace.
Caztaca told Saheeli of mercenary spies from the Brazen Coalition, loyalty assured through weights of gold, returned from the Free Cities to whisper to her priests. The news they returned prompted fear, but also action: Doomsday fervor spread across Alta Torrezon like a plague of eager fear. In place of rats, this pestilence spread from the lips of fanatic cults, whose rhetoric sent spalling fractures through the foundations of the Church of Dusk. A dark figure rising from the swirling discontent, and a queen seeking allies.
Meanwhile, war fever raged through Pachatupa and the Sun Empire. A people staggering, wounded, one fist of state clenching a sword hungry to bite flesh. An emperor's son passed over and a child on the throne who could not yet understand the gravity of the role he would play.
A queen in the east and a priestess in the west with twin ambitions. An empire ascending that could still be captured, and a realm suspended above a precipitous drop that could still be pulled back from the edge. Strange alliances indeed. Faced with an unreasonable enemy, the foe you could reason with might stand alongside you—not as a friend, but as a collaborator.
Saheeli recalled Huatli's story of the battle at Orazca during the Phyrexian war: Vampires and humans fighting together against the Phyrexians. Sen Gael was not Orazca. The enemy Caztaca and her momentary collaborators faced were not the Phyrexians. This meeting would not be a battlefield, but it would decide the fate of nations all the same.
Saheeli hurried the rest of the way up the path to the lighthouse and entered the small cabin at its base without knocking. The Sens were the home islands of the orcs, who had been reduced terribly by <NAME>; the countryside was quiet. There was no one else here but them.
The interior of the lighthouse cabin was warm and smelled of coffee, ink, and the sea. A large table had been dragged to the center of the room, around which Caztaca and her advisers sat. As Saheeli entered Caztaca looked up, registered who it was, and then flicked her eyes to the open seat next to her: Saheeli's station for the evening.
Saheeli made her way through the room, navigating the tense, murmured conversations. The canchatan kept their hands near their belts at the empty loops where they usually wore their macuahuitls, fingers surreptitiously brushing the hard silhouettes under their clothing where they kept concealed knives.
"Trust," Caztaca said to Saheeli as she settled in, "will be forged tonight by shared betrayal. Do you understand?"
Saheeli nodded. "My cousins and I stole a sheet of soan papdi from the window of a sweet shop once. We vowed never to speak of it to anyone." She scribbled a few loops of ink on the writing pad, priming her pen. "Our friendship only grew from there."
"A heartwarming recollection," Caztaca muttered.
"All that to say: I understand."
A rapid knock at the door, followed by the rising whistle of wind and rain as a canchatan stepped inside.
"They're here, your grace," the soldier said, brushing water from her shoulders. She dipped a quick bow while addressing Caztaca. "Elenda is with them."
Caztaca looked up from her notes with surprise—muted, but evident. "You are sure?"
"I saw an unnatural light emanating from a figure in their party," the canchatan said. "Not torch light or sunstone. It was thin, a crown of beads that appeared to float behind the back of the figure's head." She said, eyes wide. "I have heard that only the Venerables are graced with that light."
"Indeed," Caztaca said, a smile crossing her face. "Thank you. Dry yourself, that will be all."
Saheeli recalled what little Huatli had told her about Elenda. The first vampire, the early, unnamed battles against the Legion. The race to Orazca, the Immortal Sun, and Elenda's castigation of her own people.
Here are the pieces machined by history's lathe, falling into place.
A knock at the door. Silence in the lighthouse cabin.
"Enter," Caztaca said.
The door swung open. Four dark figures entered, ducking to fit their peaked helmets under the doorframe. Their footfalls were heavy, boots thudding on the plank floor, the soft clink and rustle of armor under their waxcloth cloaks. One by one as they entered, they stripped off their scabbarded swords and leaned them against the wall by the door.
Saheeli searched the dark faces of the men who had entered. Pallid skin, gray eyes lit from within with soft silver light. An austerity so severe it radiated from them like a terrible cold. They looked over the group of Sun Empire soldiers and dignitaries, their faces neutral, hands resting—as the canchatans' did—near the empty loops on their belts where their weapons typically hung. Satisfied, one of the soldiers stepped back outside. A moment later, Saint Elenda walked in.
The Venerable swept her hood back as she entered the cabin, uncovering her face and revealing a soft, steadily glowing diadem that crowned her head. A halo, the sign of canonization, of veneration—a divine investiture in this single person. Though Elenda's skin was as gray as her companion's, it lacked the austere cast: her cheeks were flush, as if the cold and wind had chapped her face—or, rather, as if she had just fed. The Venerable looked over the Sun Empire party, her eyes glowing a soft, warm gold. She smiled, and Saheeli could see the tips of her fangs poking just out from under her lips.
"Elenda," Caztaca said, standing. "Please, sit. And tell your soldiers they can relax. We are all collaborators here."
"Collaborators," Saint Elenda said. "Collaborators," she repeated, as if tasting the word. "I prefer friends."
"Is that what we are?" Caztaca said.
"It's what we must be," Elenda replied. She shrugged off her cloak and settled into her chair. "After tonight, the only friends we have will be the people in this room. Home will become a nest of ash-toothed vipers. Trust or respect—we must be friends."
"Friends, then," Caztaca said. "So we are here. Let's begin."
Elenda leaned forward, listening.
Saheeli wetted the tip of her pen.
"Our emperor will lead us to war," Caztaca said. "He is a child. My brother Atlacan craves the throne but can never have it, so he has instead worked his way into the emperor's mind. He whispers dreams of conquest to the boy, who demands ships and regiments like he's piling his dinner plate with sweet desserts. Our people cannot stomach another war, no matter how much they prepare. Neither can yours."
Elenda raised an eyebrow. "You think?"
"I know," Caztaca said. "Your church and your queen. 'A nest of ash-toothed vipers.' Am I wrong?"
Elenda smiled. "You are not wrong," she said. "Your whispering brother and pliant emperor are a match for the zealots in my domain. Pontifex Fein struggles to hold the Church of Dusk together. The call for revival is … strong. You are aware that there is a second expedition to Orazca underway?"
"I am aware," Caztaca said. "I assumed they were yours."
Saheeli looked up from her notes, catching herself only moments before blurting out that she most definitely was not aware of another Legion expedition to Orazca.
"Not ours," Elenda said, shaking her head. "Ixalan is no longer of interest to the crown, not since the departure of the Immortal Sun. This group is led by Vito Quijano de Pasamonte, one of the Antifex's hierophants," Elenda said. "Not sanctioned by the church. The Queen's Bay Company: one of the queen's ventures, infested now by backward, bloodthirsty eschatological fanatics who think they can bring about the Age of Blood by returning Aclazotz to Alta Torrezon."
"Can they?"
"Yes, unless they are stopped."
Saheeli's hand ached. She gripped her pen hard enough to white her knuckles as she transcribed. Elenda spoke with a lightness to her voice that sounded unserious to Saheeli. She spoke of a schism that threatened the church that had canonized her, of a low boil of apocalyptic fervor that, checked or unchecked, could only end in Alta Torrezon tearing itself apart. She spoke of Huatli in danger: Her voice should have trembled. She should be begging for help.
"Huatli will stop them," Caztaca said. "Regardless of what my brother hopes they accomplish in Orazca, the Sun Empire's soldiers know what to do when they meet the Legion on our land."
Huatli, in the darkness. Saheeli looked past the table at the Legion soldiers who stood behind Elenda. Broad men each standing over six feet tall, all ironclad in thick, burnished-gold plate armor. Etchings of roses, thorns, and human figures kneeling, their arms raised as if to buttress the plate that shielded these butchers' forms.
"If Aclazotz sets one claw on Torrezon, the realm will tear itself apart," Elenda said, repeating herself. Elenda's face lost its light. For a moment, the luster that suffused her cheeks flickered. "I cannot let that happen," she whispered. "And you cannot let your brother lead your emperor to war."
Despite her anger, Saheeli found herself drawn to Elenda. Divinity, she deduced. Of course. Proximity to the divine—any divine—was difficult to resist. She understood that magnetism, some fundamental principal of the Multiverse that she, a mortal being, felt as something #emph[more] . Saheeli pushed back against that desire to follow, turning it instead into an examination of the small details of Elenda's mortality that lingered: The wisp of gray in her long dark hair. The gentle spray of freckles across the bridge of her nose.
Elenda's eyes flashed cold as steel.
"There is someone else here," she said. She turned in her seat to face the door just as it slammed open.
A broad figure filled the doorframe, hands gripping either side as if holding on against the howling wind that roared in with them. Behind them stood a clutch of orcs and humans bearing cutlasses, scarred and patched, with a motley of armor and clothing to protect them from the elements.
A commotion. Elenda's loyal guards and Caztaca's canchatan shouting, standing from the table, moving between this new group and their retainers. The new arrivals stood between them and their swords, but they all drew daggers, saps, spikes, and other concealed hand weapons, brandishing them. Saheeli herself stood and drew upon her own magic, weaving the metal nib of her pen into a razor-edged shank.
"Quiet!" The interloper bellowed. A woman's voice, one accustomed to command, to needing to be heard over the howl of wind and angry shouting. "Stand down, all of you!" The woman strode into the cabin following the steady point of her straight-bladed cutlass. She was older, wrinkled and sunburnt, but carried herself with an oaken strength. She wore sailor's clothing—a heavy wool coat, a bicorn hat which she swept off her head, and sturdy, salt-stained boots.
Caztaca snapped a quick command to her canchatan, who held their concealed weapons steady and did not back down. The Apex Priestess herself clutched a small knife, ready to fight.
"Do as she says," Elenda said, standing. She placed a hand on the shoulder of her nearest guard and motioned for them to lower their weapons. "Admiral Brass," Elenda said, addressing the woman who had just burst in. "You weren't expected."
"You came here on my ship, to haggle over nations on my island," Admiral Beckett Brass smiled over her sword at Elenda. "Mate, you need to adjust your expectations as to the role of the courier when the cargo is this good."
"What do you want?" Caztaca interjected. "Gold? Information? We have already paid your mercenaries. Our debt is settled."
Brass flicked a glance to Caztaca, her cutlass unwavering. Behind her, her sailors chuckled.
"Quiet," Brass snapped. A lock of pale, golden hair slipped down across her face. With her free hand she tucked it back, wiping the rain and sweat from her brow. She looked between Elenda and Caztaca, weighing the two women.
Saheeli unwound her filagree needle, reshaping it back to a simple pen. In this room were three of the most powerful people in Ixalan. Venerable Elenda, the living saint of the Church of Dusk. <NAME>, Apex Priestess of the Sun Empire. Admiral Beckett Brass, leader of the Brazen Coalition. She tried to recall what Huatli had told her of the Brazen Coalition and Admiral Brass but found herself at a loss beyond pirates, gold hunters, something to do with stolen magics.
"You and yours have paid your debts to me," Brass said. "But I'm no merchant or banker."
Caztaca looked to Elenda, who kept her face beatific, neutral.
"We will listen," Caztaca said, speaking to Brass without looking at her. "You," she said to Saheeli, "will write."
"Record this well," Brass said to Saheeli as she sheathed her sword. "I will have a nation," the Admiral continued. "A land of free people, the open ocean, and every island between here," she gestured to the ground beneath their feet. "And there," she said, pointing west toward distant Ixalan. "There is a great game being played here. You two are prepared to wager thrones and crowns like coins. Regicide and fratricide are on the table and the players' hands all but dealt." Brass flicked the sword tip between the two other women as she talked. "Well, ladies, I'm here as well, and I'm the one with a grip full of cutting steel." Brass's eyes shone like chips of sky, piercing, clear. "One more hand to deal: my coalition demands recognition as a player of this game on equal terms."
"And if we refuse?" Elenda asked.
"Then I'll kill the two of you here and the stink of cannon smoke will choke Torrezon and Ixalan," Brass said. "Your people will never touch the ocean again without a coalition ship on appearing on the horizon. The seas will be a graveyard and the land a prison."
Silence, but for the sound of Saheeli's rewoven pen scratching the last of Admiral Brass's dictation.
Brass lifted her cutlass again, then threw it into the plank floor of the cabin, where it stuck deep. "An answer," she demanded. "What'll it be? A state, or the guns?"
"A bold courier," Caztaca muttered. She crossed her arms.
"Is that your answer?"
"A moment," Caztaca said. "I'm thinking."
"This pirate is holding us hostage," Elenda said, a bemused tone to her voice. "What is there to think about?"
"Her offer is not without merit," Caztaca said.
"Will you be our ally, Admiral?" Elenda asked.
"Governor," Brass corrected. "And I will pledge my fleets to those who pledge themselves to our cause."
"That's not a yes," Elenda said.
"You haven't made your decision," Brass shot back.
"You should say yes," Saheeli said, speaking up.
Another hush fell over the room.
"Pardon?" Elenda asked, turning to Saheeli.
"Accept her demand," Saheeli said. She had faced down worse than Elenda, but the Venerable's gaze was still unnerving, mesmerizing. A glimpse at the divine, a pinprick in the veil between mortal and immortal. Not of her own faith, but awesome nonetheless. Saheeli cleared her throat and continued. "You both need allies. You both are working against a clock that is working against you, without knowing how much time is left." Saheeli said. "As Governor Brass said—this is the game. Nations are at stake. Deal now and secure the seas," Saheeli said. "It makes sense."
"How much of our history do you know?" Caztaca asked. "Did Huatli tell you anything of the coalition's rampaging up and down our coast before the Phyrexian war?"
"I only know a little," Saheeli admitted. "The race to Orazca, mostly."
"They raided our fishing fleets and pillaged our temples," Caztaca said. "They have killed thousands of our citizens and looted hundreds of our artifacts to their adventures." Caztaca spoke firmly, but without anger. "The war forced us to stand together. Those bonds have only grown, but as a scar. The wound still aches."
"What Brass asks is difficult to agree to," Elenda agreed. "A nation of pirates and castaways who claim the ocean." She sighed. "I don't see it."
"And a queendom of vampires is easier to countenance?" Brass laughed.
"We don't need to beg for recognition," Elenda shot back.
"You'll beg for mercy," Brass growled, reaching for her cutlass.
"How many ships do you have," Saheeli interrupted. "Admiral Brass. Your ships?"
Admiral Brass let go of her cutlass. "I'll need a guarantee before we go any further," she said, addressing Saheeli.
"Caztaca, you can't let this scribe—"
"I can," Caztaca said. She waved a curt gesture to Elenda, silencing her. The Venerable blinked, surprised at Caztaca and, Saheeli assumed, herself for obeying. "A fair trade of information?" She said, addressing Brass.
"On my word," Brass nodded.
Caztaca took a deep, grounding breath. "The emperor is building another fleet of ten thousand ships," she said. "He intends to use them to invade Alta Torrezon."
"And how many has he built so far?" Brass asked.
"At least two hundred," Caztaca said.
"That matches with what we know," Brass nodded. "We have six hundred fighting ships stocked and seaworthy, all veteran crews, with reserves in drydocks across the sea. The Legion fields a mere eighty fighting ships the rest are merchantmen and other traders. Is that correct?" She asked, looking to Elenda.
"What makes you think I'll tell you?"
"Because it is your turn to play," Brass said. "My pieces, your pieces, her pieces—all on the table. Mutual trust, or mutual destruction. We are discussing terms, is that right Caztaca?"
"That's right," Caztaca agreed. "The coalition is already woven into this plot, Elenda: The spies we hired in your land, the spies you hired in ours. The ships the both of us took to come here undetected by our foes. This very island—they have been at the table with us the whole time. Brass offers us an alliance for the moment. If we accept, we all get what we want," Caztaca said.
Elenda looked around the room, silent for an overlong moment. When she spoke, her voice sounded tired, her pride bruised. "We will write you letters of marque," Elenda said to Brass. "Stop Vito and his acolytes from returning to <NAME>. Kill them in Orazca or sink them in the ocean, I do not care. If you can do that, I will see the queen recognize the coalition's claims as legitimate. Gratitude for service to the crown and church."
Brass grinned. She reached out, offering Elenda her hand. Elenda met hers and shook, grimacing.
"And you?" Brass asked Caztaca, reaching out to her. "What will you have us do for our nation?"
"Our second Dawn Fleet," Caztaca said. "At the end of summer, after the first of the hurricanes announce the end of safe construction: Burn those ships in their docks. Draw the Imperial army to the coast, away from the capital. Expose the emperor and his whisperer to me."
Brass extended her hand. "It's a deal," she said.
"The Apex Priestess does not shake hands," one of Caztaca's canchatans said, stepping forward to place himself between Brass and Caztaca. Brass pulled her hand back and held it up, smiling, apologetic.
Caztaca reached into the folds of her cloak and plucked a single feather from the garment she wore below, then offered it to Brass. "Return this to me when I rule in Pachatupa, and I will give you your nation."
"That's it?" Brass asked, taking the feather.
"That's it."
"And after?" Brass asked. "Trade, alliances, diplomacy? You'll deal with us on equal terms?"
"I promise you nothing beyond a state to call your own, governor." Caztaca said. Her smile was a raptor's smile. "One nation recognizing another at its border."
Brass considered this. She passed the feather back to one of her sailors, who tucked it safely away in a weatherproof pouch. "It is done," she said.
"Done," Caztaca agreed.
"Done," Elenda said.
"Done," Saheeli said, finishing her transcription of the meeting. She placed the paper on the table, set her pen across it, and stepped back. One by one the three leaders signed, sealing their contract. Saheeli blew on the ink to dry it, then rolled it up into a tight scroll.
"Metal," Saheeli said, looking to the soldiers in the room. "Coins, on the table please."
Reluctantly, the soldiers all fished coins from their pockets and purses and stepped forward to toss them on the table. Under this rain of coins, Saheeli spun a fine, copper, silver, and gold container around the document. She embellished it a little, etching a filigree pattern across its face, but was sure to seal it against the elements. When she was done, she lifted the seamless metal cylinder up, inspecting her work.
"Who carries that document?" Brass asked.
"Elenda," Caztaca said. "Consider it a receipt. Saheeli is the only one who can open that case without destroying the document inside. Is that correct?"
"Right," Saheeli said. "If you cut or melt the case, you'll destroy the paper inside and this deal will be voided."
"It may be that we do want it destroyed," Elenda muttered. She turned the cylinder over in her hands, delicate, and then passed it to one of her soldiers.
"Mutual destruction if revealed," Caztaca said, looking at Elenda. "And an unalterable, agreed-upon debt to be paid," she said, addressing Brass.
"Good enough for me," Brass said, nodding. She tugged her cutlass from the plank floor. "I'm off," she said, sliding her sword into its scabbard. "Pleasure doing business with you two. The ships you sailed here on will be resupplied, their crews replaced, and otherwise made ready for your voyages home. Best of luck to you both," she said on her way out. "And see you in the new world."
Brass and her retinue left the cabin, heading out into the howling storm with their coats tight around them, cheers rising to meet the raging wind.
"The new order of the world decided in, what, 30 minutes?" Elenda said. She stood and gestured to her soldiers. "You'll excuse me, Your Eminence," she said to Caztaca. "I have a queen to inform and a church to hold together." Elenda, like Brass, paused at the open door. "See you in the new world," she said, an unsaintly twinge of sarcasm in her voice. She flipped up her hood and departed, leaving Saheeli, Caztaca, and the Apex Priestess's canchatan soldiers alone in the lighthouse cabin.
Silence followed the Venerable's departure. The rain beat on the tiled roof. Wind rattled the storm-shuttered windows in their frames. Caztaca sat quiet, frowning, staring at the divot where Brass had plunged her cutlass. Further, Saheeli guessed, into the belly of the plane, where agents of both nations raced on errands of opposed sovereigns.
This diplomatic artifice was hideous to Saheeli. Disorganized. Messy in cost, efficiency, trust, and human lives. Alliances shifted, decisions were made not on facts but leaps of faith and trust. Friends and rivals traded masks constantly. As in Kaladesh, power never settled into equilibrium but was always up for grabs: no decision was final if it was a decision made by multiple people for multiple people. At the same time, Saheeli rejected the tyrant's logic of stability contained in a single body: the capricious, selfish aims of an autocrat promised a doomed, fatal consistency. No equilibrium in many, no justice in one—where could there be peace?
"Saheeli," Caztaca finally spoke.
"Yes, Your Eminence?"
"Huatli will support me?"
Saheeli hesitated. Caztaca waited, and Saheeli was distinctly aware of how vulnerable she was, alone on this island and surrounded by the Apex Priestess's soldiers.
"She assured me she would," Saheeli said.
"Nevertheless, Huatli worries me," Caztaca said. "She is the conscience of the empire. The people's heart and voice, but she is empire's hagiographer as well."
"She told me how much she admires your cause," Saheeli said. "She asked me to speak with her voice at this meeting."
"Speaking, writing, admiration," Caztaca shook her head. She stood, motioning toward the door. Her soldiers sprang into action, some hurrying out of the cabin to make for the ship, others preparing to escort her. "When the day of action comes, the only thing I need are swords. Many people who admire me now, who write and speak kindly of me now, will side with the emperor." She waved Saheeli toward her. "We are going to unmake the natural order. We are going to ask the people to make one more effort to secure their future. So, no words—I need action. I need swords. I need the warrior-poet."
And there was her answer, Saheeli realized. Solving for peace was an equation without an end: a blueprint that must always be revised while in practice. Shed the hubristic dream of being the one to finish the design and find purpose in the struggle to clutch the pen with which the design is drawn. Begin. Start. Make your play; at least then you will be an actor, rather than a subject.
Pick up a sword, Saheeli, she thought to herself. That's the answer.
"It is natural to follow one's emperor to war," Caztaca continued, her voice a fierce, gravel rasp. "It is natural to hate those across the ocean, though Tilonalli's light shines on them, too," Caztaca said. "I aim to do the unnatural thing."
"Huatli and I will be with you," Saheeli repeated herself, recalling her lover in the market, the same fierce tone in her voice as Caztaca, the same fear, the same hope.
Caztaca fixed her gaze on Saheeli. The two women were roughly the same height, but in that moment the Apex Priestess stood as a pyre, stretching toward the gray sky, history and the days to come embodied.
Caztaca extended her hand to Saheeli. Saheeli reached out with her own. The two women shook hands, and then walked out into the howling gale, escorted by the temple guards.
Saheeli followed Caztaca toward the shore, down from the lonely cabin and out across the dark sand of <NAME>. The launch bobbed in the shallow water, held in place by Brazen Coalition pirates and a pair of Caztaca's canchatan, who stood knee-deep in the breakwater. Chitlati already sat inside the launch, waiting for them. Cold surf surged up the strand, rippling and rolling around their ankles. The chill was sharp, clarifying. A bitter rain lashed down from the tumult above, and the ocean rolled, and distant bosun whistles trilled.
This was her world, Saheeli thought. Hers and Huatli's. She whispered a short prayer, old scripture long ago memorized and rote but now, even if only for the moment of its utterance, genuine. She reached up to the canchatan who offered her a hand, stepped from the water into the knocking launch, sat next to Chitlati, and pulled her rain clothes tight around herself as the other soldiers piled in.
With help from the coalition sailors, they shoved off the sand, undocked their oars, and rowed against the rising surge toward the distant ship that would bear them back to Ixalan, where the next round of the great game would soon begin.
|
|
https://github.com/danilasar/conspectuses-3sem | https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Ассемблер/лаба1/lab1.typ | typst | #import "conf.typ" : conf
#show: conf.with(
title: [Лабораторная работа №1],
type: "referat",
info: (
author: (
name: [<NAME>],
faculty: [КНиИТ],
group: "251",
sex: "male"
),
inspector: (
degree: "Старший преподаватель",
name: "<NAME>"
)
),
settings: (
title_page: (
enabled: true
),
contents_page: (
enabled: true
)
)
)
#align(left)[= Задание №1]
== Текст задания
Измените программы из примеров 1, 2 и 3 так, чтобы они выводили на экран ваши фамилию, имя и номер группы. Используя командные файлы (с расширением bat), подготовьте к выполнению и запустите 3 программы. Убедитесь, что они выводят на экран нужный текст и успешно завершаются.
== Тексты программ
```yasm
stak segment stack 'stack' ;Начало сегмента стека
db 256 dup (?) ;Резервируем 256 байт для стека
stak ends ;Конец сегмента стека
data segment 'data' ;Начало сегмента данных
Names db 'Grogoriev Danila, 251$' ;Строка для вывода
data ends ;Конец сегмента данных
code segment 'code' ;Начало сегмента кода
assume CS:code,DS:data,SS:stak ;Сегментный регистр CS будет указывать на сегмент команд,
;регистр DS - на сегмент данных, SS – на стек
start: ;Точка входа в программу start
;Обязательная инициализация регистра DS в начале программы
mov AX,data ;Адрес сегмента данных сначала загрузим в AX,
mov DS,AX ;а затем перенесем из AX в DS
mov AH,09h ;Функция DOS 9h вывода на экран
mov DX,offset Names ;Адрес начала строки 'Hello, World!' записывается в регистр DX
int 21h ;Вызов функции DOS
mov AX,4C00h ;Функция 4Ch завершения программы с кодом возврата 0
int 21h ;Вызов функции DOS
code ends ;Конец сегмента кода
end start ;Конец текста программы с точкой входа
```
#text(size: 12pt, align(center)[Текст программы №1])
#pagebreak(weak: true)
```yasm
.model small ;Модель памяти SMALL использует сегменты
;размером не более 64Кб
.stack 100h ;Сегмент стека размером 100h (256 байт)
.data ;Начало сегмента данных
Names db '<NAME>, 251$'
.code ;Начало сегмента кода
start: ;Точка входа в программу start
;Предопределенная метка @data обозначает
;адрес сегмента данных в момент запуска программы,
mov AX, @data ;который сначала загрузим в AX,
mov DS,AX ;а затем перенесем из AX в DS
mov AH,09h
mov DX,offset Names
int 21h
mov AX,4C00h
int 21h
end start
```
#text(size: 12pt, align(center)[Текст программы №2])
```yasm
.model tiny ;Модель памяти TINY, в которой код, данные и стек
;размещаются в одном и том же сегменте размером до 64Кб
.code ;Начало сегмента кода
org 100h ;Устанавливает значение программного счетчика в 100h
;Начало необходимое для COM-программы,
;которая загружается в память с адреса PSP:100h
start:
mov AH,09h
mov DX,offset Names
int 21h
mov AX,4C00h
int 21h
;===== Data =====
Names db '<NAME>, 251$'
end start
```
#text(size: 12pt, align(center)[Текст программы №3])
== Скриншоты запуска программ
#align(center)[#image("example1.png")]
#text(size: 12pt, align(center)[Запуск программы №1])
#align(center)[#image("example2.png")]
#text(size: 12pt, align(center)[Запуск программы №2])
#align(center)[#image("example3.png")]
#text(size: 12pt, align(center)[Запуск программы №3])
== Тексты 2-х командных файлов (для ехе-программ и для com-программы)
#v(0.5cm) // вертикальный отступ, горизонтальный h
```bat
cls
tasm.exe %1.asm
tlink.exe /x %1.obj
%1
```
#text(size: 12pt, align(center)[Текст командного файла для exe-программ])
#v(0.5cm)
```bat
cls
tasm.exe %1.asm
tlink.exe /x /t %1.obj
%1
```
#text(size: 12pt, align(center)[Текст командного файла для com-программ])
#pagebreak(weak: true)
#align(left)[= Задание №2]
== Текст задания
Заполните таблицы трассировки для 3-х программ.
== Таблицы трассировки программ
#let tracetable(caption, filename) = {
set text(lang: "ru")
figure(
caption: caption,
{
let trace = csv(filename);
set text(size: 8pt)
table(columns: 13,
table.header(
table.cell(rowspan: 2, [Шаг]), table.cell(rowspan: 2, [Машинный код]),
table.cell(rowspan: 2, [Команда]), table.cell(colspan: 9, [Регистры]), [Флаги],
[AX], [BX], [CX], [DX], [SP], [DS], [SS], [CS], [IP], [CZSOPAID]
),
..trace.map(r => {
r.at(2) = raw(lang: "nasm", r.at(2));
r
}).flatten()
)
}
)
}
#tracetable("Трассировка программы №1", "table1.csv")
#tracetable("Трассировка программы №2", "table2.csv")
#tracetable("Трассировка программы №3", "table3.csv")
//#tracetable("Трассировка программы №3", "table3.csv")
#align(center)[#image("tdexample2.png")]
#text(size: 12pt, align(center)[Трассирова программы №2])
#align(center)[#image("tdexample3.png")]
#text(size: 12pt, align(center)[Трассировка программы №3])
#align(left)[= Ответы на контрольные вопросы]
/ Вопрос 1: Что такое сегментный (базовый) адрес?
В микропроцессоре есть регистры, которые состоят из 16 бит. Эти регистры называются сегментными и обозначаются как CS, DS, SS и ES. В них хранятся 16-битные значения, которые называются базовым адресом сегмента.
Микропроцессор объединяет 16-битный исполнительный адрес и 16-битный базовый адрес следующим образом: он расширяет содержимое сегментного регистра (базовый адрес) четырьмя нулями в младших разрядах, делая его 20-битным (полный адрес сегмента), и прибавляет смещение (исполнительный адрес). В результате получается 20-битный адрес, который является физическим или абсолютным адресом ячейки памяти.
/ Вопрос 2: Сделайте листинг для первой программы (файл с расширением lst), выпишите из него размеры сегментов. Из таблицы трассировки к этой программе выпишите базовые адреса сегментов (значение DS при этом нам нужно взять после инициализации адресом сегмента данных). В каком порядке расположились сегменты программы в памяти? Расширяя базовый адрес сегмента до физического адреса, прибавляя размер этого сегмента и округляя до кратного 16 значения, мы можем получить физический адрес следующего за ним сегмента. Сделайте это для первых 2-х сегментов. (Если данные не совпали, значит, неверно заполнена таблица трассировки.)
Code size 0011 (PARA), data size 0014 (PARA), stak size 0100 (PARA). Выпишем регистры после инициализации регистра DS:
- DS = 48BD
- SS = 48AD
- CS = 48BF
В памяти программа разделена на сегменты, которые расположены в порядке увеличения размера: SS, DS, CS. Физический адрес определяется как базовый адрес, умноженный на 16h, плюс размер сегмента. То есть расширенный базовый адрес сегмента $S S = 4 8 A D dot 10 + 0100 (s t a k s i z e) = 4 8 A D 0 + 0100 = 4 8 B D 0 ( text("кратно") 16) = 4 8 B D = D S$. Аналогично для DS = 48BD $dot $ 10 + 0014 (data size) = 48BD0 + 0014 = 48BE4 (не кратно 16, округляем до ближайшего кратного 16 вверх) = 48BF = CS.
/ Вопрос 3: Почему перед началом выполнения первой программы содержимое регистра DS в точности на 10h меньше содержимого регистра SS? (Сравниваются данные из первой строки таблицы трассировки)
После того как программа загружена в память, DOS устанавливает значения сегментных регистров DS и ES, используя адрес префикса программного сегмента PSP. Этот префикс занимает 256 байт (100h) оперативной памяти.
PSP может использоваться в программе для определения имён файлов и параметров командной строки, объёма доступной памяти, переменных окружения системы и других целей.
Чтобы DS указывал на сегмент данных программы, а не на PSP, необходимо инициализировать регистр вручную. Пусть регистр DS должен указывать на сегмент В. Для этого нужно присвоить значение DS = B. Однако это нельзя сделать напрямую с помощью команды MOV DS,B, поскольку процессор не может напрямую передать имя сегмента в сегментный регистр. Поэтому нужно использовать промежуточный регистр AX.
```yasm
MOV АХ,В
MOV DS,AX ;DS:=B
```
Аналогичным образом загружается и регистр ES.
Регистра CS загружать нет необходимости, так как к началу выполнения программы этот регистр уже будет указывать на начало сегмента кода. Такую загрузку выполняет операционная система, прежде чем передает управление программе.
Загрузить регистр SS можно двояко. Во-первых, его можно загрузить в самой программе так же, как DS. Во-вторых, такую загрузку можно поручить операционной системе, описав в программе сегмент стека с помощью ключевого слова STACK.
/ Вопрос 4: Из таблицы трассировки к первой программе выпишите машинные коды команд mov AX,data и mov AH,09h. Сколько места в памяти в байтах они занимают? Почему у них разный размер?
mov AX, data - B8BD48
0003 - 0000 = 3 байта сдвиг - размер машинного кода.
mov AH, 09h - B409
0005 - 0000 = 2 байта сдвиг - размер машинного кода.
Размер команд разный в связи с разным типом данных, помещаемых в регистры.
/ Вопрос 5: Из таблицы трассировки ко второй программе выпишите базовые адреса сегментов (значение DS при этом нам нужно взять после инициализации). При использовании модели small сегмент кода располагается в памяти первым. Убедитесь в этом. (Если это не так, значит, вы неверно заполнили таблицу трассировки.)
- DS = 48AF
- SS = 48B1
- CS = 48AD
Сегменты в модели small расположились в следующем порядке: CS, DS, SS. Убедимся в этом: $C S = 48 A D dot 10 h + 0011 (text("code size")) = 48 A D 0 + 0011 = 48 A E 1$ (не кратно 16, округляем вверх) $= 48 A F 0$ (кратно 16, значит можем условно отбросить ноль в конце) $= 48 A F = D S$. $D S = 48 A F dot 10h + 0012 = 48 A F 0 + 0012 = 48 B 02$ (не кратно 16, округляем вверх) $= 48 B 1 = S S$, в чём и следовало убедиться.
/ Вопрос 6: Сравните содержимое регистра SP в таблицах трассировки для программах 2 и 3. Объясните, почему получены эти значения.
В программах модели TINY используется только сегмент стека, в связи с этимм он инициализируется максимальным возможным значением, поскольку он будет сдвигаться при помещении в него данных. В программе SMALL используются ещё сегменты данных и кода.
/ Вопрос 7: Какие операторы называют директивами ассемблера? Приведите примеры директив.
Директивы указывают программе ассемблеру, каким образом следует объединять инструкции для создания модуля, который и станет работающей программой.
Директива ASSUME --- операторы, которые сообщают ассемблеру информацию о соответствии между сегментными регистрами, и программными сегментами. (или другими словами сообщает ассемблеру через какие сегментные регистры будут адресоваться ячейки программы.)
Директива имеет следующий формат:
```yasm
ASSUME <пара>[[, <пара>]]
ASSUME NOTHING
```
где <пара> - это \<сегментный регистр> :\<имя сегмента>
либо \<сегментный регистр> :NOTHING
Например, директива
```asm
ASSUME ES:A, DS:B, CS:C
```
сообщает ассемблеру, что для сегментирования адресов из сегмента А выбирается регистр ES, для адресов из сегмента В – регистр DS, а для адресов из сегмента С – регистр CS.
/ Вопрос 8: Зачем в последнем предложении end указывают метку, помечающую первую команду программы?
Программа на языке ассемблера состоит из программных модулей, содержащихся в различных файлах. Каждый модуль, в свою очередь, состоит из инструкций процессора или директив ассемблера и заканчивается директивой END. Метка, стоящая после кода псевдооперации END, определяет адрес, с которого должно начаться выполнение программы и называется *точкой входа в программу*.
Каждый модуль также разбивается на отдельные части *директивами сегментации*, определяющими начало и конец сегмента. Каждый сегмент начинается директивой начала сегмента – SEGMENT и заканчивается директивой конца сегмента – ENDS . В начале директив ставится имя сегмента.
Таким образом, метка, указанная в END определяет начальный адрес, с которого процессор должен начать выполнение команды.
/ Вопрос 9: Как числа размером в слово хранятся в памяти и как они заносятся в 2-ух байтовые регистры?
В зависимости от архитектуры процессора, применяется прямой или обратный порядок байт. Почти во всех процессорах байты с меньшим адресом считаются младшими, такой порядок называется Little Endian. То есть 2 байта ложатся в 2 байта. Сначала байт с младшими битами числа, затем байт со старшими.
/ Вопрос 10: Как инициализируются в программе выводимые на экран текстовые строки?
Выводимые на экран текстовые строки инициализируются в секции .data с помощью db, строка должна оканчиваться знаком \$.
Прежде чем делать int 21h нужно в DX положить адрес начала строки
```yasm
mov dx, offset имя_метки_с_которой_начинается_строка
```
/ Вопрос 11: Что нужно сделать, чтобы обратиться к DOS для вывода строки на экран? Как DOS определит, где строка закончилась?
Вывод на экран строки текста и выход из программы осуществляются путем вызова стандартных процедур DOS, называемых *прерываниями*. Прерывания под номером 21h (33 – в десятичной системе счисления) называются *функциями DOS*, у них нет названий, а только номера. Номер прерывания и его параметры передаются в регистрах процессора, при этом номер должен находиться в регистре AH. Так, например, прерывание INT 21h, с помощью которого на экран выводится строка символов, управляется двумя параметрами: в регистре AH должно быть число 9, а в регистре DX – адрес строки символов, оканчивающейся знаком '\$'.
Адрес строки Hello загружается в регистр DX с помощью оператора OFFSET (смещение):
```yasm
OFFSEТ имя
```
Выход из программы осуществляется через функцию DOS с номером 4Ch. Эта функция предполагает, что в регистре AL находится код завершения программы, который она передаст DOS. Если программа завершилась успешно, код завершения должен быть равен 0, поэтому в примере загружаем регистры AH и AL с помощь одной команды MOV ax,4C00h , после чего вызываем прерывание 21h.
/ Вопрос 12: Программы, которые должны исполняться как .EXE и .COM, имеют существенные различия по:
- размеру
- сегментной структуре
- механизму инициализации
EXE-программы содержат несколько программных сегментов, включая сегмент кода, данных и стека. EXE-файл загружается, начиная с адреса PSP:0100h. В процессе загрузки считывается информация EXE-заголовка в начале файла, при помощи которого загрузчик выполняет настройку ссылок на сегменты в загруженном модуле, чтобы учесть тот факт, что программа была загружена в произвольно выбранный сегмент. После настройки ссылок управление передается загрузочному модулю к адресу CS:IP, извлеченному из заголовка EXE.
COM-программы содержат единственный сегмент (или, во всяком случае, не содержат явных ссылок на другие сегменты). Образ COM-файла считывается с диска и помещается в память, начиная с PSP:0100h , в связи с этим COM -программа должна содержать в начале сегмента кода директиву позволяющую осуществить такую загрузку (ORG 100h). Они быстрее загружаются, ибо не требуется перемещения сегментов, и занимают меньше места на диске, поскольку EXE-заголовок и сегмент стека отсутствуют в загрузочном модуле.
|
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/introduction/tool_research/snap.typ | typst | = Snap!
Snap! is a block-based programming tool developed by Berkeley University which
allows the creation of imperative programs in a Scratch-like manner.
A user can create programs to control a cursor in a graphical environment, e.g.,
navigate the cursor to a specific position and draw a line. For that, Snap!
offers pre-defined commands like basic arithmetic operations, cursor-, pen- &
sound-controls, and flow controls like "if" blocks. For lists, snap offers some
control blocks that allow users to work with lists in a functional fashion, as
seen in the red blocks in @snap_screenshot.
#figure(
image("../../../static/snap_screenshot.png", width: 90%),
caption: [Screenshot of a block expression in Snap! @snap-manual]
)<snap_screenshot>
However, everything else can only be done imperatively, making the functional
aspects more of an additional feature than a core concept of Snap!.
Users can also create new block commands based on existing commands, which
allows users to reuse their code. But unlike usual functions, custom
blocks aren't able to take arguments from their caller @snap-manual.
Regarding usability, we feel that Snap! isn't very difficult to understand, but
also not very intuitive, primarily because some icons and command names aren't
obvious in their meaning. |
|
https://github.com/ojas-chaturvedi/typst-templates | https://raw.githubusercontent.com/ojas-chaturvedi/typst-templates/master/assignments/README.md | markdown | MIT License | # Assignment
Template taken from: <https://github.com/gRox167/typst-assignment-template>
## [Typst.app](https://typst.app)
Upload all `*.typ` files to your Typst project. Change what you want and voila!
### Typst CLI
```sh
# Compile to assignment.pdf
typst compile assignment.typ
# Compile to other path and name
typst compile assignment.typ your/path/here.pdf
# Watch
typst watch assignment.pdf
```
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/alignment.typ | typst | // Test implicit alignment math.
--- math-align-weird ---
// Test alignment step functions.
#set page(width: 225pt)
$
"a" &= c \
&= c + 1 & "By definition" \
&= d + 100 + 1000 \
&= x && "Even longer" \
$
--- math-align-post-fix ---
// Test post-fix alignment.
$
& "right" \
"a very long line" \
"left" \
$
--- math-align-implicit ---
// Test no alignment.
$
"right" \
"a very long line" \
"left" \
$
--- math-align-toggle ---
// Test #460 equations.
$
a &=b & quad c&=d \
e &=f & g&=h
$
--- issue-3973-math-equation-align ---
// In this bug, the alignment set with "show math.equation: set align(...)"
// overrides the left-right alternating behavior of alignment points.
#let equations = [
$ a + b &= c \
e &= f + g + h $
$ a &= b + c \
e + f + g &= h $
]
#equations
#show math.equation: set align(start)
#equations
#show math.equation: set align(end)
#equations
|
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/capítulos/10.financiamiento.typ | typst | MIT License | = Financiamiento
== Selección de las Fuentes de Financiamiento Más Económicas
== Plan de Pagos
== Estructura de Financiamiento
== Relación de Garantías
== Flujo de Fuentes y Usos de Fondos
=== Sin Financiamiento
=== Con Financiamiento
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/README.md | markdown | MIT License | # Typst Examples Book
See the book there: https://sitandr.github.io/typst-examples-book/book/
## Highlight & rendering
Currently powered by https://github.com/sitandr/mdbook-typst-highlight.
## Contributing
If you have a snippet you want to have in a book, feel free to create an issue.
Any PR-s are very welcome!
Generally encouraged:
- Editing (expanding examples, fixing bad language issues)
- Selecting any really useful code examples from Discord and Github
- Ideas (just any ideas how to make the book more useful)
Currently needed:
- Help with updating state manual to context expressions.
- Updating examples with possibilities of new Typst versions
- Some impressive demos
If you think you can do some large work, please DM me in Discord (@sitandr) or mail (<EMAIL>) to avoid duplication.
Also please DM me if I'm forgetting about your PR. I have bad memory.
## Rules
1. Many snippets are taken from Discord, Github or other places. Without using them that book would much, much more harder to write. However, getting a consent for every snippet will be a total disaster.
So, as a general rule, if the snippet is a non-trivial one (one that combines typst functions in a smart way), there should be a credit to original author (of course, the credit will be removed if author objects).
2. In "Typst by Example" section the concepts that are not told yet should be avoided if possible. Although it is okay to use them if they are really intuitive and without them the demonstration would be too dull.
3. "Typst Snippets" and "Typstonomicon" should not include staff that is already present in official packages. Instead, there should be a link to a package. However, it is allowed to use packages as a tool in snippets, if the package using is "secondary" there or the idea of using that package for that task is not obvious.
4. Giant queries and hack things should go to "Typstonomicon", not "Typst snippets", even if they are super-useful. "Typst snippets" should contain code as clean as possible.
## Cleaning cached Typst files
```bash
git clean -d -X -i
```
Make sure to avoid deleting something useful.
## Compiling
To compile the book, you need `typst` cli installed, `mdbook` and my highlighting & rendering preprocessor `mdbook-typst-highlight`. Assuming `typst` is already installed, installation using cargo:
```bash
cargo install mdbook
cargo install --git https://github.com/sitandr/mdbook-typst-highlight
```
Alternatively you can install them precompiled from `mdbook` and `mdbook-typst-highlight` releases. In the end you should have to have the latest versions of them all in your PATH.
After everything installed, `mdbook build` will build the book. You can also use `mdbook watch` for continuous rebuilding, and `--open` option to open the book in your browser. For more details on building, see `mdbook` documentation.
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/经济学原理/hw/hw5.typ | typst | #import "../../template.typ": *
#show: note.with(
title: "作业5",
author: "YHTQ ",
date: none,
logo: none,
withOutlined: false
)
= B
牛奶的效用大于鸡腿肉效用
= A?
在不可微点边际替代率无法定义(?
3. A
$
e = ((Delta Q)/(Delta P))/(Q/P)\
= ((((1.02Q P)/(0.95P))-Q)/(0.05P))/(Q/P)\
= (1.02-0.95)/(0.05 dot 0.95) > 1\
$ |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/genealotree/0.1.0/manual.typ | typst | Apache License 2.0 | #import "@preview/mantys:0.1.3": *
#import "@preview/showman:0.1.1"
#import "@preview/tidy:0.2.0"
#let show-module(name, scope:(:)) = tidy-module(
read(name + ".typ"),
name: name,
include-examples-scope: true,
tidy: tidy,
extract-headings: 3
)
#import "genealotree.typ": *
#show: mantys.with(
..toml("typst.toml"),
examples-scope: (
genealogy_init: genealogy_init,
add_persons: add_persons,
add_unions: add_unions,
canvas: canvas,
draw_tree: draw_tree
)
)
#show link: set text(blue)
= Introduction
<sec-intro>
This package is based on #link("https://typst.app/universe/package/cetz/")[CeTZ] and it provides functions to draw genealogical trees. It is oriented towards medical genealogy to study genetic disorders inheritance, but you might be able to use it to draw your family tree.
*Features :*
- Draw an unlimited number of independant genealogical trees
- Supports consanguinity and unions between different trees (see limitations)
- Auto adjusts position of children to optimize spacing
- Customize all lengths
- Draw as much phenotypes as needed by coloring individuals
- Print genotype and/or phenotype labels under individuals
*Limitations :*
- Must manually adjust individual position in the tree when drawing consanguinity and unions between trees to prevent overlapping of individuals.
- No remarriages (might be added in a future version)
- No union between individuals at different generations (might be added in a future version)
*To be implemented :*
- Allow to pass CeTZ arguments to every elements to cutomize their appearance
- Draw optional legends for tree symbols and for phenotypes
= Usage
<sec-usage>
#example[```
#let geneal_example = genealogy_init()
#let geneal_example = add_persons(
geneal_example,
(
"I1": (sex: "m", phenos: ("ill",)),
"I2": (sex: "f"),
"II1": (sex: "f", phenos: ("ill",)),
"II1*": (sex: "m"),
"II2": (sex: "f"),
"II3": (sex: "f", phenos: ("ill",)),
"II3*": (sex: "m"),
"III1": (sex: "f", phenos: ("ill",)),
"III1*": (sex: "m"),
"III2": (sex: "f"),
"III3": (sex: "m", phenos: ("ill",)),
"III4": (sex: "f"),
"IV1": (sex: "m"),
"IV2": (sex: "m", phenos: ("ill",)),
"IV3": (sex: "f", phenos: ("ill",)),
)
)
#let geneal_example = add_unions(
geneal_example,
(("I1", "I2"), ("II1", "II2", "II3")),
(("II1", "II1*"), ("III1",)),
(("II3", "II3*"), ("III2", "III3", "III4")),
(("III1", "III1*"), ("IV1", "IV2", "IV3"))
)
#canvas(length: 0.4cm, {
// Draw the tree
draw_tree(geneal_example)
})
```]
#pagebreak()
== Available commands
<sec-avail_comma>
#show-module("genealotree")
// == Customizing appearance
// <sec-custo_appea>
== Elements names in CeTZ
<sec-eleme_names_in>
This section documents CeTZ elements name, so you can use them in the canva to add manual modifications to the tree.
- persons symbol : persons name
- persons topline : persons name + "\_\_vt\_\_"
- persons botline : persons name + "\_\_vb\_\_"
- union horizontal line : first parents name + second parents name + "\_\_h\_\_" (parents name are sorted alphabetically)
- union vertical line (joining an union line with a siblings line) : first parents name + second parents name + "\_\_v\_\_" (parents name are sorted alphabetically)
- siblings line : first parents name + second parents name + "\_\_s\_\_" (parents name are sorted alphabetically)
#let geneal_showlines = genealogy_init()
#let geneal_showlines = add_persons(
geneal_showlines,
(
"I1": (sex: "m"),
"I2": (sex: "f"),
"II1": (sex: "f"),
"II2": (sex: "m"),
"II3": (sex: "f"),
)
)
#let geneal_showlines = add_unions(
geneal_showlines,
(("I1", "I2"), ("II1", "II2", "II3"))
)
#figure(
[
#canvas(length: 0.8cm, {
draw_tree(geneal_showlines)
content((name: "I1", anchor: "center"), [I1])
content((name: "I2", anchor: "center"), [I2])
content((name: "II1", anchor: "center"), [II1])
content((name: "II2", anchor: "center"), [II2])
content((name: "II3", anchor: "center"), [II3])
line(
(name: "I1" + "__vb__", anchor: 50%),
(rel: (-4.25, 0)),
name: "vb",
stroke: (dash: "dashed")
)
mark((name: "vb", anchor: 0%), (rel: (0.1,0)), symbol: "circle", fill: black)
content(
(name: "vb", anchor: 100%),
anchor: "east",
padding: 0.1,
[I1\_\_vb\_\_])
line(
(name: "II1" + "__vt__", anchor: 50%),
(rel: (-2, 0)),
name: "vt",
stroke: (dash: "dashed")
)
mark((name: "vt", anchor: 0%), (rel: (0.1,0)), symbol: "circle", fill: black)
content(
(name: "vt", anchor: 100%),
anchor: "east",
padding: 0.1,
[II1\_\_vt\_\_])
line(
(name: "I1I2" + "__v__", anchor: 50%),
(rel: (-6, 0)),
name: "uv",
stroke: (dash: "dashed")
)
mark((name: "uv", anchor: 0%), (rel: (0.1,0)), symbol: "circle", fill: black)
content(
(name: "uv", anchor: 100%),
anchor: "east",
padding: 0.1,
[I1I2\_\_v\_\_])
line(
(name: "I1I2" + "__h__", anchor: 75%),
(rel: (0, -0.5)),
name: "uh",
stroke: (dash: "dashed")
)
line(
(name: "uh", anchor: 100%),
(rel: (3.5/4 + 4.25,0)),
name: "uh2",
stroke: (dash: "dashed")
)
mark((name: "uh", anchor: 0%), (rel: (0.1,0)), symbol: "circle", fill: black)
content(
(name: "uh2", anchor: 100%),
anchor: "west",
padding: 0.1,
[I1I2\_\_h\_\_])
line(
(name: "I1I2" + "__s__", anchor: 75%),
(rel: (0, 0.5)),
name: "uh",
stroke: (dash: "dashed")
)
line(
(name: "uh", anchor: 100%),
(rel: (4,0)),
name: "uh2",
stroke: (dash: "dashed")
)
mark((name: "uh", anchor: 0%), (rel: (0.1,0)), symbol: "circle", fill: black)
content(
(name: "uh2", anchor: 100%),
anchor: "west",
padding: 0.1,
[I1I2\_\_s\_\_])
})
],
caption: [Elements names in CeTZ. Persons names are labelled at their center.]
)<fig-cetz_names>
// = Behavior
// <sec-behav>
// == Persons position in the tree
// <sec-perso_posit_in>
// == Width optimization
// <sec-width_optim>
// = Internals
// <sec-inter>
// == Calculating spacings between individuals
// <sec-calcu_spaci_betwe>
// #show-module("calc_functions")
// == Drawing functions
// <sec-drawi_funct>
// #show-module("draw_functions")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/bone-resume/0.2.0/lib.typ | typst | Apache License 2.0 | #let resume-init(title: none, author: "六个骨头", header: none, footer: none, body) = {
set document(author: author, title: title)
set page(margin: (x: 3.2em, y: 3.2em), header: header, footer: footer)
set text(font: ("Source Han Sans"), lang: "zh")
show emph: it => {
text(it.body, font: ("Source Han Serif SC",), style: "italic")
}
show link: it => {
set text(blue, font: ("Source Han Sans"), weight: "bold")
it
}
show heading.where(level: 1): it =>{
set text(rgb("#448"), size: 1em, font: "Source Han Sans")
stack(dir: ttb, spacing: 0.55em, {
it.body
}, line(stroke: 1.5pt, length: 100%))
v(0.5em, weak: true)
}
show par: set block(spacing: 0.65em)
align(center)[
#block(text(weight: 700, 1.75em, title))
]
set par(justify: true)
body
}
#let primary-achievement(name, decs, contrib) = {
set box(
fill: color.hsv(240deg, 10%, 100%),
stroke: 1pt,
inset: 5pt,
radius: 3pt,
)
box()[
#name #h(1fr) #decs
#v(1em, weak: true)
#contrib
]
}
#let achievement(name, decs, contrib) = {
set box(stroke: 1pt, inset: 5pt, radius: 3pt)
box()[
#name #h(1fr) #decs
#v(1em, weak: true)
#contrib
]
}
#let resume-section(primary: true, name, decs, contrib) = {
if primary {
primary-achievement(name, decs, contrib)
}else{
achievement(name, decs, contrib)
}
}
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/代数学二/作业/hw6.typ | typst | #import "../../template.typ": *
#import "@preview/commute:0.2.0": node, arr, commutative-diagram
#show: note.with(
title: "作业5",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle :false,
)
(应交时间为4月9日)
#set heading(numbering: none)
= p33-35
== 20
首先注意到有自然的:
$
directLimit (M_i times N) tilde.eq (directLimit M_i) times N
$
因此由概念,有交换图表:
$
#align(center)[#commutative-diagram(
node((0, 0), $M_i times N$, 1),
node((0, 1), $M_i tensorProduct N$, 2),
node((1, 0), $M times N$, 3),
node((1, 1), $M tensorProduct N$, 4),
node((0, 2), $directLimit (M_i tensorProduct N)$, 5),
arr(1, 2, $$),
arr(1, 3, $mu_i times 1$),
arr(2, 4, $mu_i tensorProduct 1$),
arr(3, 4, $$),
arr(2, 5, $nu_i$),
arr(5, 4, $exists! psi$)
)]
$
这里:
- $f_i$ 来自于可以验证 $M_i times N -> M times N -> M tensorProduct N$ 是双线性,进而由 $M_i tensorProduct N$ 产生
- $psi$ 来自于正向极限,只需验证兼容性:
$
(mu_i tensorProduct 1) (mu_(i j) tensorProduct 1) = (mu_i mu_(i j)) tensorProduct 1 = mu_j tensorProduct 1
$
利用了张量积的函子性
- 直接验证 $psi$ 是同构:
- 任取 $M tensorProduct N$ 中元素,其必形如:
$
mu_i (m_i) tensorProduct n = (mu_i tensorProduct 1)(m_i tensorProduct n) = psi(nu_i (m_i tensorProduct n))
$
因此 $psi$ 是满射
- 假设 $psi(x) = 0$,$x$ 必形如 $nu_i (m_i tensorProduct n)$,进而:
$
0 = psi(nu_i (m_i tensorProduct n)) = (mu_i tensorProduct 1)(m_i tensorProduct n) = mu_i (m_i) tensorProduct n
$
这意味着任意从 $M times N$ 出发的双线性函数于 $mu_i (m_i) times n$ 的像为零,然而可以将 $M_i times N -> directLimit (M_i tensorProduct N)$ 作为双线性映射提升到 $M times N$,因此它于 $mu_i (m_i) times n$ 的像(恰好是 $mu_i (m_i) tensorProduct n$)为零
证毕
== 23
这里 $B_J -> B_J'$ 的典范同态当然满足兼容性,而之前的习题证明了环作为模的正向极限自然地继承环结构,因此结论成立
== 25
任取 $M in Mod_A$,考虑 $Tor_1 (*, M)$ 产生的正合列:
$
Tor_2(N'', M) -> Tor_1(N', M) -> Tor_1(N, M) -> Tor_1(N'', M) \
-> N' tensorProduct M -> N tensorProduct M -> N'' tensorProduct M -> 0
$
由 $N''$ 平坦,上述序列是:
$
0 -> Tor_1(N', M) -> Tor_1(N, M) -> 0 -> N' tensorProduct M -> N tensorProduct M -> N'' tensorProduct M -> 0
$
产生正合列:
$
0 -> Tor_1(N', M) -> Tor_1(N, M) -> 0
$
显然,中间两项一项为零蕴含另一项为零,因此结论正确
== 27
== i) $=>$ ii)
任取主理想 $(x)$,有正合列:
$
0 -> (x) -> A -> A quo (x) -> 0
$
由于 $(x)$ 平坦,得正合列:
$
0 -> (x) tensorProduct (x) -> (x) -> (A quo (x)) tensorProduct (x) -> 0
$
注意到 $M tensorProduct I tilde.eq M quo(I M)$,上式化为:
$
0 -> (x) quo (x^2) -> (x) -> (A quo (x)) quo ((x) A quo (x)) -> 0
$
然而 $(x) A quo (x) = 0$,上式化为:
$
0 -> (x) quo (x^2) -> (x) -> A quo (x) -> 0
$
给出 $(x) = (x^2)$,证毕
== ii) $=>$ iii)
先证明主理想是直和项。事实上,由 $(x^2) = (x)$ 立得:
$
exists k, x = x^2 k => x (1 - k x) = 0 => (k x) (1 - k x) = 0
$
如此,$k x in (x)$ 是幂等元。此外,有:
$
(x) = (k x^2) subset (k x) subset (x)
$
因此 $(x) = (k x)$,而幂等元生成的主理想当然是直和项。
进一步,不妨设有限生成理想 $I$ 由若干幂等元 $e_i$ 生成,注意到:
$
(e, f) = (e + f - e f)
$
因此这样的理想也是主理想,证毕
== iii) $=>$ i)
任取有限生成理想 $I$,设 $A = I directSum I'$。注意到正合列:
$
0 -> I -> A -> A quo I -> 0\
0 -> I -> I directSum I' = A -> I' -> 0
$
表明 $A quo I$ 作为模同构于 $I'$,而 $I'$ 作为 $A$ 的直和项是平坦的,继而恒有:
$
Tor_1 (A quo I, M) = 0, forall M in Mod_A
$
这就意味着所有模都平坦
== 28
- 布尔环中所有元素都幂等,当然是绝对平坦的
- 若 $forall x, exists n space s.t. x^n = x$,则:
$
(x) supset (x^2) supset ... supset (x^n) = (x)
$
因此主理想当然都幂等
- 环的满同态像同构于商环,而上面的 ii) 被商环所保持,因此成立
- 任取 $alpha in m$,其中 $m$ 是极大理想,注意到:
$
(alpha) (alpha) = (alpha), (alpha) subset max(A)
$
由 Nakayama 知 $(alpha) = 0 => alpha = 0$
- 前面已经叙述任取 $x in A$,存在 $k$ 使得:
$
k x^2 = x => x (1 - k x) = 0
$
自然要么 $1 - k x = 0$ 进而 $x$ 可逆,要么 $1 - k x$ 成为 $x$ 的零因子
= p43
== 10
=== i)
任取 $M in Mod_(Inv(S) A)$,它可以看作 $A$ 的模,进而也可写作 $Inv(S) M$,进而任取 $Mod_(Inv(S) A)$ 中正合列写作:
$
Inv(S) E
$
进而:
$
(Inv(S) E) tensorProduct (Inv(S) M) = Inv(S) (E tensorProduct_A M)
$
由于 $* tensorProduct_A M$ 是正合函子,$Inv(S)$ 也是,进而上面的张量积是正合的,故 $Inv(S) M$ 确实是平坦模
=== ii)
- 设 $A$ 绝对平坦,则 $A_m$ 也绝对平坦,且是局部环,进而 $A_m$ 是域
- 设 $A_m$ 总是域,注意到平坦性是局部性质,任取 $M in Mod_A$ 只需证明 $M_m$ 在 $Mod_(A_m)$ 上平坦。\
然而 $A_m$ 是域,其上的模就是线性空间,总存在基,进而是自由模,从而平坦。
== 11
首先,注意到素理想/极大理想都包含 $Re$,进而与 $A quo Re$ 中理想有保序的一一对应。同时:
$
Spec(A) tilde.eq Spec(A quo Re)
$
因此在本题中不妨直接设 $Re = 0$
=== i) $=>$ ii)
任取 $p$ 是素理想,考虑 $A quo p$ 它是绝对平坦的整环。\
而由前面的习题,其中元素要么可逆,要么有零因子。这表明除了 $0$ 之外的元素均可逆,进而是域。
=== ii) $=>$ iii)
前面的习题证明了单点集闭当且仅当对应素理想极大,当然正确
=== i) $=>$ iv)
任取两点 $p_1, p_2$,注意到 $p_1, p_2$ 互不包含,取:
$
x in p_1 - p_2
$
根据前面的习题,存在幂等元 $e$ 使得 $(e) = (x)$,此时:
$
e(1-e) = 0 => forall p in Spec(A), e in p, 1 - e in p "两者恰有一个成立"
$
因此:
- $p_1 in V(e), p_2 in.not V(e) => p_2 in V(1-e)$\
- $V(e) union V(1-e) = emptyset$
各自取补便给出不相交的开邻域,证毕
=== iv) $=>$ iii), iii) $=>$ ii)
显然
=== ii) $=>$ i)
任取极大理想 $m$,注意到条件给出 $m$ 不含任何素理想,进而 $A_m$ 没有除 $m A_m$ 外的素理想,这意味着 $m A_m$ 中元素全部幂零,然而 $(Re)_m = (Inv(A - m))Re = 0$ 可得 $m A_m$ 中无非零幂零元,进而 $A_m$ 是域,由之前习题知结论成立
接下来,证明:
- 紧性:之前的习题已经证明
- 整体不连通:设 $S subset Spec(A)$ 不是单点集,往证其不连通。设其中有两元素 $p_1, p_2$,并取 $x in p_1 - p_2$,仿照之前习题的构造给出:
$
A tilde.eq A quo (e) times A quo (1-e)
$
之前的习题证明了 $Spec(A)$ 成为两个开子空间的不交并,而 $S$ 分别落在两个开子空间中($p_1 in X_1, p_2 in X_2$),故不连通
== 12
首先验证 $T(M)$ 是子模。\
- 加法封闭:设 $x, y in T(M)$,从而存在 $u, v != 0$ 使得:
$
u x = 0 = v y => u v(x + y) = 0
$
由于 $A$ 是整环 $u v !=0$,上式即表明 $x + y in T(M)$
- 乘法封闭:设 $x in T(M), a in A$,从而存在 $u != 0$ 使得:
$
u x = 0 => u (a x) = 0
$
上式即表明 $a x in T(M)$
=== i)
设 $M quo T(M) $ 中存在元素 $x + T(M) M$ 使得:
$
exists a in A, a(x + T(M) ) = (a x) + T(M) = 0
$
从而 $a x in T(M) => exists b in A, b a x = 0 => x in T(M) => x + T(M) = 0$
证毕
=== ii)
任取 $m in T(M)$,则存在 $a != 0 in A$ 使得:
$
a m = 0 => 0 = f(a m) = a f(m) => f(m) in T(M)
$
证毕
=== iii)
- 注意到 $T(*)$ 函子作用于函数只是原本函数的限制,当然保持单射性
- 只需验证 $T(M') ->^f' T(M) ->^g' T(M'')$ 处正合性,其中 $f$ 是单射。
- 由原本的正合性,$g compose f = 0$ 成立,当然它们的限制也成立 $g' compose f' = 0$
- 只需证明 $ker g' subset im f'$,任取 $x in ker g' = T(M) sect ker g = T(M) sect im f$,因此可设:
$
x = f(m'), a f(m') = f(a m') = 0, a != 0
$
由于 $f$ 是单射,上式表明 $a m' = 0 => m' in T(M') => x in im f'$,证毕
=== iv)
记 $S = A - {0}, P(S)$ 为 $S$ 的幂集。在 $P(S)$ 上按照包含关系定义偏序,则它是一个正向指标集。\
定义:
$
M_I = A (1/(product I)), forall I in P(S)
$
容易看出 $I <= J <=> I subset J => M_J = A (1/(product J)) supset A (product J - I) (1/(product J)) = A (1/(product I)) = M_I$\
因此可取 $mu_(i j)$ 是通常的嵌入同态,当然满足兼容性。\
如此给出了一个模的正向系统。事实上之前习题证明了:
$
directLimit M_i tilde.eq union_i M_i = K
$
因此只要证明:
$
T(M) &= ker (M -> K tensorProduct_A M) \
&= ker (M -> (directLimit M_i) tensorProduct_A M) \
&= ker (M -> directLimit (M_i tensorProduct_A M))
$
正向极限的核中的元素应当满足:
$
mu_K (1_K tensorProduct m) = 0 <=> exists I in P(S), forall J >= I, mu_(I J) (1_I tensorProduct m) = 0
$
然而我们定义的 $mu$ 都是嵌入,进而 $1_I tensorProduct m = 0$,当且仅当:
$
1/(product I) tensorProduct_A (product I) m = 0
$
- 一方面,假设上式成立,构造双线性映射:
$
funcDef(f, M_I times M, K, (a/(product I), m') , a m')
$
上式表明:
$
0 = f(1/(product I), (product I) m) = (product I) m
$
这就意味着 $m in T(M)$,证毕
- 另一方面,假设 $m in T(M)$,选出一个非零的零化子 $a$,则 $(product {a}) m = 0$,当然有上式成立
证毕
== 14
将 $M quo alpha M$ 视作 $A quo alpha$ 环,由局部化和商的交换性,将有 $M quo alpha M$ 在 $A quo alpha$ 的所有极大理想处都是零,导出 $M quo alpha M = 0$,证毕
== 15
设 $x_i$ 是一组生成元,$e_i$ 是一组基,定义:
$
funcDef(phi, F, F, e_i, x_i)
$
它是满射。为了证明它是单射,考察正合列:
$
0 -> ker phi -> F ->^(phi) F -> 0
$
注意到 $F$ 是自由模,当然投射,正合列中间三项中后两项投射,其余一项也投射,因此 $ker phi$ 投射,给出泛性质:
$
#align(center)[#commutative-diagram(
node((0, 0), $F$, "1"),
node((0, 1), $F$, "2"),
node((1, 0), $ker phi$, "3"),
arr("2", "1", $phi$, surj_str),
arr("3", "2", $exists psi' $),
arr("3", "1", $psi $),)]
$
这里 $psi$ 取自然的嵌入,当然有:
$
0 = phi compose psi' = psi
$
然而 $psi$ 是嵌入,给出 $ker phi = 0$,证毕
若有元素少于 $n$ 个的生成元集,将某个元素重写若干遍后可得 $n$ 元生成元集,进而是基,其中元素均线性无关,这是荒谬的
== 16
=== i) $=>$ ii)
根据书上命题,此时 $Spec(A)$ 中每个素理想成为 $Spec(B)$ 中某个素理想的逆像,当然 $phi^*$ 是满的
=== ii) $=>$ iii)
此时 $m$ 成为某个素理想的逆像,当然不可能有 $phi(m) = B$
=== iii) $=>$ iv)
任取 $x != 0 in M$,只需证明 $(A x)_B != 0$,不妨就设 $M = A x$ \
注意到 $alpha := Ann(x) != A$,且 $M tilde.eq A quo alpha$,此时:
$
M_B tilde.eq (A quo alpha) tensorProduct_A B tilde.eq B quo (alpha B) = B quo (phi(alpha))
$
将 $alpha$ 扩成极大理想 $m$,注意到 $phi(alpha) subset phi(m) != B$,因此上式非零,证毕
=== iv) $=>$ v)
考虑正合列:
$
0 -> ker phi -> M ->^phi M tensorProduct_A B
$
既然 $B$ 是平坦代数,将有正合列:
$
0 -> ker phi tensorProduct_A B -> M tensorProduct_A B -> (M tensorProduct_A B) tensorProduct_A B
$
由之前的习题,后项是单射,进而 $ker phi tensorProduct_A B = 0 => ker phi = 0$(运用条件)
=== v) $=>$ i)
取 $M = A quo alpha$,有单射:
$
A quo alpha -> A quo alpha tensorProduct_A B tilde.eq B quo (alpha B) = B quo (phi(alpha))
$
这就意味着 $Inv(phi)(phi(alpha)) = alpha$,否则 $Inv(phi)(phi(alpha)) - alpha$ 将落入上面映射的 $ker$
== 17
任取 $Mod_A$ 正合列 $E$,只需证明 $E tensorProduct_A B$ 正合\
事实上,当然有 $E tensorProduct_A C$ 正合,同时:
$
E tensorProduct_A C = E tensorProduct_A (B tensorProduct_B C) tilde.eq (E tensorProduct_A B) tensorProduct_B C
$
由于 $C$ 在 $B$ 上忠实平坦,故 $(E tensorProduct_A B) tensorProduct_B C$ 正合当且仅当 $E tensorProduct_A B$ 正合,证毕
== 19
#let Supp = math.op("Supp")
=== i)
熟知 $M = 0$ 当且仅当在所有素理想处的局部化为零,即 $Supp(M) = emptyset$
=== ii)
也就是证明
$
alpha subset.not p <=> (A quo alpha)_p = 0
$
事实上:
$
(A quo alpha)_p = (A_p) quo (alpha_p)
$
显然:
- $alpha subset.not p => alpha_p = A_p => (A quo alpha)_p = 0$
- $(A quo alpha)_p = 0 => alpha_p = A_p => exists x in A - p, a in alpha, x (a - 1) = 0 in p => x in p or a - 1 in p => a - 1 in p => a in.not p => alpha subset.not p$
得证
=== iii)
注意到局部化是正合函子,将有正合列:
$
0 -> M'_p -> M_p -> M''_p -> 0
$
当然有 $M_p = 0 <=> M'_p = 0 and M''_p = 0$,取否即得原命题
=== iv)
局部化与直和交换,因此:
$
0 = (sum M_i)_p = sum (M_i)_p <=> forall i, (M_i)_p = 0
$
取否即可
=== v)
$
Supp(M) = Supp(sum_i A x_i) = union_i Supp(A x_i) \
= union_i Supp(A quo Ann(x_i)) = union_i V(Ann(x_i)) \
= V(sum_i Ann(x_i)) = V(Ann(sum_i x_i)) = V(Ann(M))
$
=== vi)
$
0 = (M tensorProduct N)_p = M_p tensorProduct N_p <=> M_p = 0 or N_p = 0
$
利用 $A_p$ 是局部环
=== vii)
$
(M quo alpha M)_p = 0 <=> M_p = alpha_p M_p
$
利用局部环和 Nakayama 引理,上式等价于 $alpha_p = A_p <=> (A quo alpha)_p = 0$ 或 $M_p = 0$,进而:
$
Supp(M quo alpha M) = Supp(M) sect Supp(A quo alpha) \
= V(alpha) sect V(Ann(M)) = V(alpha + Ann(M))
$
=== viii)
先设 $M = A x$
$
Supp(B tensorProduct M) = Supp(B tensorProduct (A quo Ann(x))) \
= Supp(B quo Ann(x) B) = V(Ann(x) + Ann(B)) = V(Ann(M)) sect V(ker f)\
= Supp(M) sect V(ker f)
$
表明这些素理想一定包含 $ker f$ 进而上式就是 $f^(* -1)(Supp(M))$
= p78
== 1
=== i
注意到有递增子模链:
$
ker mu <= ker mu^2 <= ... <= ker mu^n <= ...
$
由条件知最终将稳定,可设 $ker mu^n = ker mu^(n+1)$,因此:
$
mu^(n+1) (m) = 0 <=> mu (mu^n (m)) = 0 <=> mu^n (m) = 0
$
然而 $mu$ 是满射,$mu^n$ 也是,进而上式表明 $ker mu = 0$,证毕
=== ii
注意到有递降子模链:
$
M >= im mu >= im mu^2 >= ... >= im mu^n >= ...
$
由条件知最终稳定,可设 $im mu^n = im mu^(n+1) := M'$\
然而注意到:
$
im mu^n = mu(im mu^(n-1)) \
im mu^n = im mu^(n+1) = mu(im mu^(n))\
mu(im mu^(n-1)) = mu(im mu^(n)) => im mu^(n-1) = im mu^n
$
(最后利用了 $mu$ 是单射)\
这表明 $n$ 可以一直降低,最终说明 $im mu = M$,证毕
== 2
对 $M$ 的任意子模 $M'$,设:
$
Sigma = {M'' subset M' | M'' "是有限生成子模"}
$
条件表明它将有极大元。设极大元为 $M''$,然而往有限生成模中扩充任何元素都还是有限生成的,因此 $M''$ 只能为 $M'$,表明 $M$ 的所有子模都有限生成
== 3
由熟知的同构:
$
M quo N_1 times M quo N_2 tilde.eq M quo N_1 sect N_2
$
及有限直积保持 Noether/Artin 知结论成立
== 4
此时必有 $M$ 有限生成,进而可设 $M = sum_i A x_i$,有:
$
Ann(M) = sect_i Ann(x_i)\
A quo Ann(M) tilde.eq product_i A quo Ann(x_i) tilde.eq product_i A x_i
$
而 $A x_i$ 作为 Noether 模的子模有限生成,进而 $A quo Ann(x_i)$ 作为有限 $A-$代数是 Noether 的,作为环也是,由上题结论知结果成立
若 $M$ 是 Artin 的,结果当然未必,例如设 $p$ 是素数,则 $ZZ[1/p] quo ZZ$ 作为 $ZZ$ 模 Artin,并且没有非零零化子,但 $ZZ$ 不是 Artin 的
== 5
注意到子空间 $Y$ 中开集均形如 $A sect Y$,其中 $A$ 是 $Y$ 中开集,当然将满足升链条件。
为了证明拟紧,任取一族开覆盖 $union E = X$,考虑:
$
Sigma = {union E' | E' "是" E "的有限子集"}
$
$sigma$ 将是开集族,由升链条件,$Sigma$ 有极大元 $E'$,容易验证 $union E' = X$,否则可以再添加一个点的覆盖到 $E'$ 使得覆盖的空间更大,与极大性矛盾
== 6
== i) $=>$ iii)
已经证明每个子空间都 Noether,而 Noether 空间都拟紧,因此结论成立
== iii) $=>$ ii)
显然
== ii) $=>$ i)
任取开集的升链:
$
A_1 <= A_2 <= ... <= A_n <= ...
$
则 ${A_i}$ 构成开子空间 $union_i A_i$ 的开覆盖,将有有限开覆盖。由于这族开集是全序的,相当于只需一个 $A_n$ 即可覆盖,蕴含 $A_m = A_n, forall m >= n$,证毕
== 7
设 $Sigma$ 为所有不能写成有限个不可约分支的并的闭子空间,注意到这是一族闭集,假设它非空,由降链条件存在极小元 $Y$。\
显然 $Y$ 不是空集,任选 $x in Y$ 以及包含它的不可约分支 $Gamma subset Y$,则 $Y - Gamma$ 可写成有限个不可约分支的并,继而再加上 $Gamma$ 便将 $Y$ 写成了有限个不可约分支的并,矛盾!\
因此原集合是空集
进一步,设 $X = union_i X_i$,任取其中一个不可约分支 $C$,将有:
$
C = union_i (C sect X_i)
$
然而 $C$ 不能写成其中有限个非空闭集的并,继而:
$
exists i, C = C sect X_i
$
再由极大性,$C = X_i$,证毕
== 8
显然 $Spec(A)$ 中闭集都是 $V(alpha), alpha$ 是环中理想。理想的升链条件将导出闭集的降链条件,因此 $Spec(A)$ 是 Noether 的
反面不成立,例如令 $A = QQ[x_1, x_2, ..., x_n, ...] quo (x_1^2, x_2^2, ..., x_n^2, ...)$,注意到它当然不是 Noether 环,同时 $Spec(A)$ 同胚于 $Spec(A quo Re)$\
但另一方面,$A$ 中所有不是单位的元素都幂零,因此 $A quo Re tilde.eq QQ$ 是域,素谱是单点集,当然是 Noether 空间
== 9
前面已经证明了极小素理想与不可约分支的一一对应,因此结论成立
== 10
熟知 Noether 模有限生成,此时有:
$
Supp(M) = V(Ann(M))
$
因此确实是闭集,只需验证其中降链条件。事实上,若存在其中无穷下降的闭集链:
$
V(Ann(M)) := V(I_0) > V(I_1) > ... > V(I_n) > ...
$
当然有 $Ann(M) := I_0 < I_1 < ... < I_n$\
此时,将有上升的子模链:
$
0 = I_0 M <= I_1 M <= ... <= I_n M <= ...
$
注意到:
$
Supp(M quo I_n M) = V(I_n + Ann(M)) = V(I_n)
$
因此
$
I_n = I_(n+1) => Supp(M quo I_n M) = Supp(M quo I_(n+1) M) => V(I_n) = V(I_(n+1))
$
从而子模升链中每项严格上升,与 Noether 模条件矛盾!
|
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap4/3_metric_notation.typ | typst | Other | #import "../../core/core.typ"
=== Metric notation
The metric system, besides being a collection of measurement units for
all sorts of physical quantities, is structured around the concept of
scientific notation. The primary difference is that the powers-of-ten
are represented with alphabetical prefixes instead of by literal
powers-of-ten. The following number line shows some of the more common
prefixes and their respective powers-of-ten:
#image("static/00356.png")
Looking at this scale, we can see that 2.5 Gigabytes would mean $2.5 times 10^9 "bytes"$,
or 2.5 billion bytes. Likewise, 3.21 picoamps would
mean $3.21 times 10^-12 "amps"$, or $3.21 1/"trillionths of an amp"$.
Other metric prefixes exist to symbolize powers of ten for extremely
small and extremely large multipliers. On the extremely small end of the
spectrum, $"femto"(f) = 10^-15$, $"atto"(a) = 10^-18$,
$"zepto"(z) = 10^-21$, and $"yocto"(y) = 10^-24$.
On the extremely large end of the spectrum,
$"Peta"(P) = 10^15$, $"Exa"(E) = 10^18$,
$"Zetta"(Z) = 10^21$, and $"Yotta"(Y) = 10^24$.
Because the major prefixes in the metric system refer to powers of 10
that are multiples of 3 (from \"kilo\" on up, and from \"milli\" on
down), metric notation differs from regular scientific notation in that
the significant digits can be anywhere between 1 and 1000, depending on
which prefix is chosen. For example, if a laboratory sample weighs
0.000267 grams, scientific notation and metric notation would express it
differently:
$ 2.67 times 10^-4 "grams (scientific notation)" $
$ 267 "µgrams (metric notation)" $
The same figure may also be expressed as 0.267 milligrams (0.267 mg),
although it is usually more common to see the significant digits
represented as a figure greater than 1.
In recent years a new style of metric notation for electric quantities
has emerged which seeks to avoid the use of the decimal point. Since
decimal points (\".\") are easily misread and/or \"lost\" due to poor
print quality, quantities such as 4.7 k may be mistaken for 47 k. The
new notation replaces the decimal point with the metric prefix
character, so that \"4.7 k\" is printed instead as \"4k7\". Our last
figure from the prior example, \"0.267 m\", would be expressed in the
new notation as \"0m267\".
#core.review[
- The metric system of notation uses alphabetical prefixes to represent
certain powers-of-ten instead of the lengthier scientific notation.
]
|
https://github.com/Entoryvekum/TypstTemplate | https://raw.githubusercontent.com/Entoryvekum/TypstTemplate/main/BasicTemplate/0.1.0/template.typ | typst | #import("@local/MathBasic:0.1.0"):*
#let Note(body) = {
//Page
let Header(l,m,r)={
grid(
columns: (1fr,auto,1fr),
align(left,text(9pt,par(leading: 0.2em,l))),
align(center,text(9pt,par(leading: 0.2em,m))),
align(right,text(9pt,par(leading: 0.2em,r))),
)
}
set text(
font: ("Times New Roman","Simsun"),
size: 11pt
)
set page(
paper: "a4",
margin: (x: 2cm, y: 1.5cm),
)
set par(
first-line-indent: 2em,
justify: true,
leading: 0.9em,
)
set heading(numbering: "1.")
show heading.where(level: 1): it => [
#set par(first-line-indent: 0em)
#set text(15pt, weight: "bold")
#counter(heading).display()
#h(0.5em)
#it.body
]
show heading.where(level: 2): it => text(
size: 13pt,
weight: "bold",
counter(heading).display()+h(0.5em)+it.body,
)
//Raw
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: true): block.with(
width: 100%,
fill: luma(240),
inset: 8pt,
radius: 4pt,
)
show raw.where(block: true): it => {
let lines = it.text.split("\n")
let length = lines.len()
let i = 1
let index = while i < length {
str(i) + "\n"
i+=1
}
grid(
columns: (auto, 1fr),
align(
right,
block(
inset: (
top: 8pt,
bottom: 8pt,
left: 0pt,
right: 5pt
),
index
)
),
align(left, it),
)
}
body
} |
|
https://github.com/pawarherschel/typst | https://raw.githubusercontent.com/pawarherschel/typst/main/helpers/helpers.typ | typst | Apache License 2.0 | #import "@preview/fontawesome:0.1.0": *
#let color-darknight = rgb("131A28")
#let color-darkgray = rgb("414141")
#let color-gray = rgb("5d5d5d")
#let default-accent-color = rgb("333ECC")
/// Show a link with an icon, specifically for Github projects
/// *Example*
/// #example(`resume.github-link("DeveloperPaul123/awesome-resume")`)
/// - github_path (string): The path to the Github project (e.g. "DeveloperPaul123/awesome-resume")
/// -> none
/// taken from https://github.com/DeveloperPaul123/modern-cv/blob/main/lib.typ
#let github-link(github_path) = {
set box(height: 11pt)
align(right + horizon)[
#fa-icon("github", fa-set: "Brands", fill: color-darkgray) #link("https://github.com/" + github_path, github_path)
]
}
#import "../template/template.typ": hBar
#let join-with-hBar = arr => {
arr.join(
eval(
"sep",
mode: "code",
scope: (
sep : hBar()
)
)
)
}
#let join-as-bullet-list = arr => {
if arr.len() == 0 {
return list()
}
let list = arr.map(item => {
return "- " + item
}).join("\n")
eval(
list,
mode: "markup",
)
}
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20interna/Verbali/24-03-30/24-03-30.typ | typst | #import "/template.typ": *
#show: project.with(
date: "30/03/24",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
reviewers: (
"<NAME>",
),
missingMembers: (
"<NAME>",
),
timeStart: "10:30",
timeEnd: "11:15",
);
= Ordine del giorno
- Valutazione del progresso generale;
- Invio candidatura PB;
- Pianificazione.
= Valutazione del progresso generale <avanzamento>
Durante lo Sprint 21 sono stati pianificati e continuati gli ultimi lavori in previsione del colloquio PB, inoltre si è svolta una riunione di convalida del MVP con il Proponente in cui tutte le funzionalità del sistema sono state mostrate e approvate.
== #ndp
Sono state aggiornate e revisionate le seguenti sezioni:
- Processo di gestione della qualità;
- Processo di validazione;
- Processo di integrazione;
- Processo di verifica;
- Processo di implementazione.
== #pdq
- Redatto tracciamento test;
- Aggiornate metriche dalla dashboard.
== #st
- Completato e ampliato il documento.
== #man
- Definite le ultime task;
- Redatta sezione Modifica Zona;
- Redatta sezione Richiesta spostamento prodotto;
- In corso la sezione Ispezione Zona;
- In corso la sezione Visualizzazione Lista Zone;
- Definito template documento;
- Redatta sezione Eliminazione zona.
= Analisi retrospettiva
Il rendimento positivo dello Sprint è sostenuto dalle principali metriche esposte dal #pdq\:
- CPI di progetto a 1.00, rappresenta un valore accettabile ($>=0.95$) e ottimo ($>=1$);
- EAC aumenta con un valore di 13.010,59€, nonostante l'aumento, rientra nelle condizioni di ottimalità;
- $"SEV" = "SPV"$, rientra nelle condizioni di accettabilità poiché $"SEV" >= 80%$ del $"SVP"$.
\
Maggiori dettagli in merito al valore delle metriche alla loro analisi sono reperibili all'interno dei documenti #pdq_v e #pdp_v.
== Keep doing <keep-doing>
Il gruppo ed il Proponente si ritengono soddisfatti dell'andamento dei lavori e dei progressi ottenuti.
Le review delle Pull Request sono avvenute con precisione e in tempi brevi.
= Invio candidatura PB
Il gruppo attende la valutazione della nuova versione del documento #adr da parte del #cardin, bloccante l'invio della candidatura PB.
Vista la concomitanza con le vacanze pasquali, il gruppo conta di poter sostenere il primo colloquio con il #cardin entro lo Sprint 22.
Il gruppo prosegue con la correzione e il miglioramento dei documenti; continua inoltre la ricerca di bug all'interno del MVP.
= Pianificazione <pianificazione>
#show figure: set block(breakable: true)
#let table-json(data) = {
let keys = data.at(0).keys()
table(
align: left,
columns: keys.len(),
..keys,
..data.map(
row => keys.map(
key => row.at(key, default: [n/a])
)
).flatten()
)
}
#figure(caption: [Task pianificate per lo Sprint 22.],
table-json(json("tasks.json"))
)
|
|
https://github.com/dccsillag/toy-algebraic-effects | https://raw.githubusercontent.com/dccsillag/toy-algebraic-effects/main/README.md | markdown | This is a small programming language, for the purpose of prototyping how [Typst](https://github.com/typst/typst) would look like with its impurities unified as algebraic effects.
It is not particularly efficient, but only for the sake of simplicity -- there is nothing inherent that blocks it from being optimized (at least compared to how an untyped lambda calculus [/ an untyped PL] could be optimized).
Note that:
- This does not implement full algebraic effects; in particular, the current implementation only allows for resuming the computation once. Full algebraic effects would allow an effect to resume computation any number of times (including zero).
The reason for this is nothing fundamental -- simply that it would likely be much simpler to optimize performance when there is a single resumption, and that would likely suffice for Typst.
- This does not let the user of the programming language to define their own effects and handlers.
Our purpose with algebraic effects in Typst is much more to streamline how the compiler does things internally, as well as refactor some bits that are currently "callback based" (e.g. `location`, `state::display`, `styles`) into something that much more versatile and imperative looking (and thus more intuitive).
|