repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/template/template.typ | typst | Other | #import "consts.typ"
#import "util.typ"
#import "page.typ": page_setting
#import "font.typ": font-setting
#import "l10n.typ": l10n_setting
#import "heading.typ": heading-setting
#let template(doc) = [
#show: page_setting
#show: font-setting
#show: l10n_setting
#show: heading-setting
#doc
]
#let web-page-template(doc) = if util.is-web-target() [
#set document(
title: consts.title,
author: (consts.author, ..consts.translators),
)
#show: template
#doc
#context { // show footnotes if have
if counter(footnote).at(here()).sum() > 0 {
pagebreak()
} else {
v(2em)
}
}
#set text(lang: "en")
#set par(justify: false)
#bibliography("/refs.bib", title: none)
] else [
#doc
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list-attach_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test basic attached list.
Attached to:
- the bottom
- of the paragraph
Next paragraph.
|
https://github.com/MasterEvarior/typst-cv | https://raw.githubusercontent.com/MasterEvarior/typst-cv/main/cv.typ | typst | MIT License | #import "template/template.typ": template, education_entry, skill_entry, work_entry, references_entry, interests_entry, icon, languages_entry, misc_entry
#let name = "<NAME>"
#let color = black
#let photo = "photo.jpeg"
#let personal_profile = "lorem(120)"
#let personal_info = ((
(
"service": "email",
"display": "<EMAIL>"
),
(
"service": "phone",
"display": "+1 206 555 0100"
),
(
"service": "nationality",
"display": "US National"
),
(
"service": "home",
"display": " 1600 Pennsylvania Avenue, Washington D.C."
),
(
"service": "birthday",
"display": "01.01.1994"
)
))
#show: doc => template(doc, color, name, photo, personal_profile, personal_info)
= #icon("experience") Work Experience
#work_entry("Chief Hackerman", "National Security Agency", start_date: "Since August 2021", tasks: (
"Hacked at least 2 nation states, 22 US citizens and one starbucks",
"Broke international law, like 20 times",
"Created a system that randomly decides who has to pick up donuts"
), location: "Fort Meade, Maryland")
#work_entry("Software Developer ", "Example.com", start_date: "August 2016", end_date: "August 2020", tasks: (
"Implemented and maintained a system to create fantastic data, to use as examples",
"Made funny jokes during meetings"
), location: "Dallas, Texas")
= #icon("education") Education
#education_entry("Computer Science", "University of Texas",
degree_title: "BSc.", description: "Theoretical education in computer science topics mixed with practical projects in a wide range of subjects.", start_date: "August 2010", end_date: "August 2016", location: "Austin, Texas")
= #icon("skills") Skills
#skill_entry((
(
icon: "git",
name: [ Git ]
),
(
icon: "java",
raise: true,
name: [ Java ]
),
(
icon: "springboot",
name: [ Spring Boot ]
),
(
icon: "maven",
name: [ Maven ]
),
(
icon: "docker",
raise: true,
name: [ Docker ]
),
(
icon: "cicd",
name: [ CI/CD with Jenkins ]
),
(
icon: "sonarqube",
name: [ SonarQube ]
),
(
icon: "cloudfoundry",
name: [ Cloud Foundry ]
),
))
#languages_entry((
(
name: [ English ],
level: 10,
acquisition: [ Native language ],
),
(
name: [ English(British Accent) ],
level: 1,
acquisition: [ "Cool, innit?" ],
),
(
name: [ French ],
level: 1,
acquisition: [ Can say "French Fries" ],
))
)
= #icon("interests") Interests & Hobbies
#interests_entry((
(
name: [ Invisible Object Photography ],
description: [
I delight in the whimsical world of invisible object photography, capturing the hilarity of pretending with non-existent item It's a playful exploration where creativity knows no bounds, yielding laughter-filled snapshots.
]
),
(
name: [ Pet Rock Olympics ],
description: [
Participating in the Pet Rock Olympics is a riot! Almost clinching victory in absurd events like rock rolling and synchronize rock swimming made for a side-splitting, near-triumphant experience.
]
)
))
= #icon("online") Online Presence
#misc_entry(
(
(
label: [ GitHub ],
value: [ https://github.com/Example ]
),
(
label: [ Website ],
value: [ https://example.com ]
)
)
)
= #icon("references") References
#references_entry((
(
name: [ <NAME> ],
role: [ Software Architect at Example.com ],
email: "<EMAIL>",
phone: "+1 206 555 0200",
),
(
name: [ <NAME> ],
role: [ Scrum Master at Example.com ],
email: "<EMAIL>",
phone: "+1 206 555 0300",
),
)) |
https://github.com/tingerrr/anti-matter | https://raw.githubusercontent.com/tingerrr/anti-matter/main/example/front-matter.typ | typst | MIT License | #set heading(numbering: none)
#show outline: set heading(outlined: true)
#outline()
= Figures
Content
= Tables
Content
= Listings
Content
|
https://github.com/DawnEver/mcm-icm-typst-template | https://raw.githubusercontent.com/DawnEver/mcm-icm-typst-template/main/appendices.typ | typst | MIT License |
#let first-line-indent = 20pt
#let appendices(body)={
// show Appendices
body
pagebreak()
pad(
left: -first-line-indent
)[#heading("Appendices", numbering: none)]
pad(
left: -first-line-indent,
)[#heading("Appendices A First appendix", numbering: none)]
par(
hanging-indent: -first-line-indent,
)[
In addition, your report must include a letter to the Chief Financial Officer(CFO) of the Goodgrant Foundation, Mr. <NAME>, that describes the optimal investment strategy, your modeling approach and major results, and a brief discussion of your proposed concept of a return-on-investment (ROI). This letter
should be no more than two pages in length.
Here are simulation programmes we used in our model as follow.
]
pad(left: -first-line-indent)[#line(length: 100%, stroke: gray)]
```matlab
function [t,seat,aisle]=OI6Sim(n,target,seated)
pab=rand(1,n);
for i=1:n
if pab(i)<0.4
aisleTime(i)=0;
else
aisleTime(i)=trirnd(3.2,7.1,38.7);
end
end
```
pad(left: -first-line-indent)[#line(length: 100%, stroke: gray)]
pad(
left: -first-line-indent,
)[#heading("Appendices B Second appendix", numbering: none)]
} |
https://github.com/rabotaem-incorporated/algebra-conspect-1course | https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/README.md | markdown | Other | # Конспект лекций по алгебре
> Лектор: **<NAME>**.
## Гайд по использованию
### Короткая версия
[PDF тут](https://github.com/rabotaem-incorporated/algebra-conspect-1course/releases/latest), качаете и читаете
### Подробная версия
Для начала убедитесь, что знаете общие правила пользования конспектом:
1. Если до экзамена осталось больше недели, этим конспектом лучше не пользоваться.
2. Если до экзамена осталось меньше двух дней, этот конспект вам не поможет.
3. "между одной неделей и двумя днями пригодно к использованию так сказать" - @frungl
Теперь выйдите на улицу, потрогайте траву, вернитесь домой, скиньте эквивалент 30 долларов в dogecoin на мой кошелек и скачайте последний релиз [отсюда](https://github.com/rabotaem-incorporated/algebra-conspect-1course/releases/latest).
## О списке билетов
Среди релизов есть PDF с отмеченными ссылками на билеты второго семестра.
## Contributing
> Ваш вклад очень важен для нас.
Конспект написан на [Typst](https://typst.app/). Можете сделать pull request с исправлениями, добавлениями и т.д. Все изменения будут рассмотрены (скорее всего). Typst кстати написан на Rust. Ну это так, между делом. Просто примите к сведению.
Теперь используется oфициальная, последняя на момент релиза версия Typst (на момент написания README это 0.8.0). Релизы собираются через прикрепленный скрипт на Python.
## Как собрать?
Скачайте Typst [здесь](https://github.com/typst/typst/releases/latest) и
```bash
typst compile main.typ
```
Капец интуитивно, да?
Используйте `watch` вместо `compile` чтобы Typst следил за изменениями и перекомпилировался автоматически.
## Licensing
See [LICENSE](LICENSE). |
https://github.com/zyf722/typst-tabler-icons | https://raw.githubusercontent.com/zyf722/typst-tabler-icons/main/src/lib-impl.typ | typst | MIT License | /// Render a [Tabler icon](https://tabler.io/icons) by its name or unicode.
///
/// Parameters:
/// - `icon`: The name of the icon
/// - This can be name in string or unicode of the icon
/// - `tabler-icon-map`: The map of icon names to unicode
/// - Default is a map generated from Tabler metadata
/// - *Not recommended* You can provide your own map to override it
/// - `..args`: Additional arguments to pass to the `text` function
///
/// Returns: The rendered icon as a `text` element
#let tabler-icon(
icon,
tabler-icon-map: (:),
..args,
) = {
text(
font: "tabler-icons",
// If the name is in the map, use the unicode from the map
// If not, pass the name and let the ligature feature handle it
tabler-icon-map.at(icon, default: icon),
..args,
)
}
|
https://github.com/lvignoli/typst-pandoc | https://raw.githubusercontent.com/lvignoli/typst-pandoc/main/README.md | markdown | MIT License | [pandoc 3.1.2](https://github.com/jgm/pandoc/releases/tag/3.1.2) now provides a Typst writer to convert **to** Typst.
A reader is also [planned](https://github.com/jgm/pandoc/issues/8740).
Hence, because of upcoming native support for Typst, this extension will **not** be maintained.
---
# Typst custom reader and writer for Pandoc
[Typst](https://typst.app) is a modern markup-based typesetting system with powerful typesetting and scripting capabilities.
_It's really great._
[Pandoc](https://pandoc.org) is a universal document converter that handles **lots** of formats.
The custom `reader.lua` and `writer.lua` allow converting to and from Typst using Pandoc embedded Lua engine.
## Usage
```terminal
pandoc -t writer.lua input.tex -o output.typ
pandoc -f reader.lua input.typ -o output.html
```
> Hint:
> Try converting this README to Typst!
See [Pandoc User's guide](https://pandoc.org/MANUAL.html) for more advanced usage.
## TODO
Some planned improvements to be done.
- [X] Better formatting
- [X] Sort imports
- [ ] Support tight and sparse lists properly
- [ ] Improve standalone template with prettier default
- [ ] Parse the language of code blocks in Typst markup \[reader\]
- [ ] Parse Typst nested lists (that's a bit tricky here, use a recursive pattern or an LPeg dedicated grammar) \[reader\]
- [ ] Parse escaped Typst markup characters \[reader\]
- [ ] Work towards feature completeness
- [ ] Handle most informative attributes in the writer
- [ ] …
---
## Features completeness
Checked items are minimally supported.
Unchecked items are not supported.
### Writer
#### Blocks
- [X] Plain
- [X] Para
- [ ] LineBlock
- [X] CodeBlock
- [X] RawBlock
- [X] BlockQuote
- [X] OrderedList
- [X] BulletList
- [X] DefinitionList
- [X] Header
- [X] HorizontalRule
- [ ] Table
- [ ] Figure
- [X] Div
#### Inlines
- [X] Str
- [X] Emph
- [X] Underline
- [X] Strong
- [X] Strikeout
- [X] Superscript
- [X] Subscript
- [X] SmallCaps
- [X] Quoted
- [ ] Cite
- [X] Code
- [X] Space
- [X] SoftBreak
- [X] LineBreak
- [ ] Math (needs to convert TeX syntax to Typst)
- [ ] RawInline
- [X] Link
- [X] Image
- [ ] Note
- [X] Span
### Reader
Some Pandoc AST items do not have a dedicated Typst markup.
The result is usually obtained by a generic and expected function call, which could be parsed, such as `#strike[redacted]` or `#underline[important]`.
#### Blocks
- [X] Plain
- [X] Para
- [ ] LineBlock
- [X] CodeBlock
- [ ] RawBlock
- [ ] BlockQuote (no markup)
- [X] OrderedList
- [X] BulletList
- [ ] DefinitionList
- [X] Header
- [X] HorizontalRule
- [ ] Table
- [ ] Figure
- [ ] Div (probably corresponds to a content block)
#### Inlines
- [X] Str
- [X] Emph
- [ ] Underline (no markup)
- [X] Strong
- [ ] Strikeout (no markup)
- [X] Superscript
- [X] Subscript
- [X] SmallCaps
- [ ] Quoted
- [ ] Cite
- [X] Code
- [X] Space
- [X] SoftBreak
- [X] LineBreak
- [ ] Math (needs to convert TeX syntax to Typst, not planned)
- [ ] RawInline
- [X] Link
- [ ] Image
- [ ] Note
- [ ] Span
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/136.%20patentpledge.html.typ | typst | patentpledge.html
The Patent Pledge
August 2011I realized recently that we may be able to solve part of the patent
problem without waiting for the government.I've never been 100% sure whether patents help or hinder technological
progress. When I was a kid I thought they helped. I thought they
protected inventors from having their ideas stolen by big companies.
Maybe that was truer in the past, when more things were physical.
But regardless of whether patents are in general a good thing, there
do seem to be bad ways of using them. And since bad uses of patents
seem to be increasing, there is an increasing call for patent reform.The problem with patent reform is that it has to go through the
government. That tends to be slow. But recently I realized we can
also attack the problem downstream. As well as pinching off the
stream of patents at the point where they're issued, we may in some
cases be able to pinch it off at the point where they're used.One way of using patents that clearly does not encourage innovation
is when established companies with bad products use patents to
suppress small competitors with good products. This is the type
of abuse we may be able to decrease without having to go through
the government.The way to do it is to get the companies that are above pulling
this sort of trick to pledge publicly not to. Then the ones that
won't make such a pledge will be very conspicuous. Potential
employees won't want to work for them. And investors, too, will
be able to see that they're the sort of company that competes by
litigation rather than by making good products.Here's the pledge:
No first use of software patents against companies with less
than 25 people.
I've deliberately traded precision for brevity. The patent pledge
is not legally binding. It's like Google's "Don't be evil." They
don't define what evil is, but by publicly saying that, they're
saying they're willing to be held to a standard that, say, Altria
is not. And though constraining, "Don't be evil" has been good for
Google. Technology companies win by attracting the most productive
people, and the most productive people are attracted to employers
who hold themselves to a higher standard than the law requires.
[1]The patent pledge is in effect a narrower but open source "Don't
be evil." I encourage every technology company to adopt it. If
you want to help fix patents, encourage your employer to.Already most technology companies wouldn't sink to using patents
on startups. You don't see Google or Facebook suing startups for
patent infringement. They don't need to. So for the better technology
companies, the patent pledge requires no change in behavior. They're
just promising to do what they'd do anyway. And when all the
companies that won't use patents on startups have said so, the
holdouts will be very conspicuous.The patent pledge doesn't fix every problem with patents. It won't
stop patent trolls, for example; they're already pariahs. But the
problem the patent pledge does fix may be more serious than the
problem of patent trolls. Patent trolls are just parasites. A
clumsy parasite may occasionally kill the host, but that's not its
goal. Whereas companies that sue startups for patent infringement
generally do it with explicit goal of keeping their product off the
market.Companies that use patents on startups are attacking innovation at
the root. Now there's something any individual can do about this
problem, without waiting for the government: ask companies where
they stand.
Patent Pledge Site
Notes:[1]
Because the pledge is deliberately vague, we're going to need
common sense when intepreting it. And even more vice versa: the
pledge is vague in order to make people use common sense when
interpreting it.So for example I've deliberately avoided saying whether the 25
people have to be employees, or whether contractors count too. If
a company has to split hairs that fine about whether a suit would
violate the patent pledge, it's probably still a dick move.The Investment That Didn't Happen
|
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/机器视觉实践/报告/5/5.typ | typst | The Unlicense | #import "../template.typ": *
#show: project.with(
title: "5",
authors: ("absolutex",),
)
= 机器视觉实践 五
== 实验目的
图像水印添加与提取
+ 要求考虑 DCT 变换实现图像水印算法
+ 要求在对图像添加扰动(如噪声旋转、缩放)时仍能提取水印
== 实验代码
本次实验我用了两种方法进行添加水印:频域直接添加和自定义的 LSB 最低有效位。
=== 频域直接添加
频域直接添加的原理是先将图像做 fft 得到频域,然后直接对频域图像绘制信息,最后 ifft 得到隐写图像。提取信息时,只需要将携带信息的图像进行 fft 即可在频域图中看到信息。
对于彩色图像,我选择分离 RGB 通道后,使用蓝色通道进行频域信息的承载,因为人眼对蓝色通道的变化更不敏感。
#include_code("../src/watermark/myfft.py")
=== LSB 最低有效位
LSB 最低有效位是广泛使用的一种隐写技术,LSB隐写就是修改RGB颜色分量的最低二进制位,也就是最低有效位(LSB),而人类的眼睛很难注意到像素的 1 亮度变化。
这里利用 LSB 原理设计了一个比较复杂的算法:
1. 计算隐写内容长度,并将每一个 bit 较为平均地分散到图像(的蓝色通道)中。这里分散的值使用的是 jump,也就是同一行中有效 bit 的距离。
2. 对于每一张图像,随机选取 $31 times 8$ 个点(共计 31 bytes)存储 31 次 jump 数字本身,恢复时取多数。
3. 隐写内容以 64 个 0 作为结束,而恢复时只要遇到连续 8 个 0 就认为结束。
算法的目的是为了减少噪声干扰对隐写信息造成的影响。下面是代码:
#include_code("../src/watermark/LSB.py")
== 实验结果与心得
=== 频域直接添加
#figure(
image("DCT1.jpg", width: 100%),
caption: [频域直接添加 隐写前后对比],
)
在空间域,隐写前后的图像没有任何区别。第三图是频域直接添加信息后的频谱,将第三图进行 ifft 再 fft 后得到第四图。可以看到第四图中心有隐约的中心对称的 “1234” 字样,但并不是特别明显。
#figure(
image("DCT1_big.jpg", width: 20%),
caption: [加密后频域放大图],
)
放大后可以明显看到隐写信息。
我也尝试过在频域不同位置添加隐写信息,结果恢复的频谱图上根本无法看到隐写的信息,因为频域能量集中在图片中心;即使现在将字写得靠近图片中心,也很难看到隐写的信息,更不用说将字写在远离中心的地方了。
#figure(
image("DCT2.jpg", width: 70%),
caption: [椒盐噪声干扰下的信息恢复],
)
在椒盐噪声干扰下,频谱噪声也加大,信息痕迹更淡,但是依然可以观察到隐写的信息。这种情况下,可能需要对频域图像进行二次处理,提高对比度以更好地恢复信息。
#figure(
image("DCT3.jpg", width: 70%),
caption: [高斯噪声干扰下的信息恢复],
)
高斯噪声干扰下,频谱的隐写信息反而看得更加清楚。这可能是因为频谱的中心能量更加集中所导致的。
#figure(
image("DCT4.jpg", width: 70%),
caption: [色块切割干扰下的信息恢复],
)
色块切割干扰下,对频谱的信息提取没有明显影响。
=== LSB 最低有效位
#figure(
image("LSB.jpg", width: 50%),
caption: [LSB 法原图与隐写图对比],
)
LSB 法并不会对图像造成肉眼可见的影响。因此后续不再放出对比图像。
无干扰条件下:
```
请输入水印内容:1234
INFO:root:jump: 255
INFO:root:got image shape : (1440, 1080)
INFO:root:most common jump: (255, 31)
获取水印: 1234
```
可以看到所有 31 个 jump 值均未改变,成功提取出水印。
椒盐噪声:
```
请输入水印内容:1234
INFO:root:got image shape : (1440, 1080)
INFO:root:most common jump: 255, 个数为 25
获取水印: 1234 !
```
可以看到 jump 成功读取,但是在获取水印时没有正确读取结束符,导致读取长度大于实际信息长度。该算法对椒盐噪声干扰抗性一般。因为椒盐噪声本身是全图随机的,这降低了将 LSB 的信息位分散到全图的抗干扰意义。
高斯噪声:
```
请输入水印内容:1234
INFO:root:jump: 255
INFO:root:got image shape : (1440, 1080)
WARNING:root:相同的 jump 不够多,可能有干扰,jump 为 239, 个数为 2
zB{Ìe,mkRµ)@!¦áiâ¬+¯=J5¼ÚçwÊv§{Îó¥9LcÆRç9ÜÆ³ç{Þ÷û½-^ÿükÞsÞs×¹¥¦5½!)@+\B¹¥PÄCÊs3µé¾ Á.y¡[ÌB^öR&!aµ³¯g8qLd :´w¥¯
....
```
可以看到 jump 未能成功读取,信息获取错误。该算法无法抗高斯噪声的干扰:高斯噪声是全图影响,并且对于像素最后一位影响很大,几乎等于完全随机错位。
色块切割:
```
请输入水印内容:1234
INFO:root:jump: 255
INFO:root:got image shape : (1440, 1080)
INFO:root:most common jump: 255, 个数为 30
获取水印: 1234
```
对于色块切割干扰,该算法拥有非常高的抗干扰能力。不如说,算法的核心思想是将色块分散到全图,这一开始就是为了色块切割设计的。局部的色块切割只会丢失很小一部分信息,均匀分散能保证大多数信息的完整性。
=== 其他心得体会
本次实验多次将图像的 RGB 三通道分离,在处理后再将三通道合并回图片。而在 LSB 的测试中,一直出现图片 jump 和信息提取失败的情况,无论何种干扰(特别是色块切割干扰),jump 正确的个数都小于 3。将写入信息时和解码时对整个 G 通道矩阵打印并 diff,发现比信息量多得多的像素发生了漂移,也就是灰度值出现变化,幅度在 1-3 左右。这对于 LSB 是致命性的灾难,因为这意味着最低位发生了改变。
最后经过实验我发现这个现象是由于 JPG 格式图像导致的精度损失,因为 JPG 图像是有损压缩格式。将图像换为 PNG 后,观测到了期望结果。 |
https://github.com/YXalix/resume | https://raw.githubusercontent.com/YXalix/resume/main/template.typ | typst | // 字体
#let font = (
main: "IBM Plex Serif",
mono: "IBM Plex Mono",
cjk: "Noto Serif CJK SC",
size: 11pt,
)
// 图标
#let icon(path) = box(
baseline: 0.125em,
height: 1.0em,
width: 1.25em,
image(path)
)
#let faAngleRight = icon("fa-angle-right.svg")
// 主体
#let resume(
size: 10pt,
themeColor: rgb(38, 38, 125),
top: 2cm,
bottom: 2cm,
left: 2cm,
right: 2cm,
photograph: "",
photographWidth: 0em,
gutterWidth: 0em,
header,
body
) = {
// 页边距设定
set page(paper: "a4", numbering: "1", margin: (
top: top,
bottom: bottom,
left: left,
right: right,
))
// 基础字体设定
set text(font: (font.main, font.cjk), size: size, lang: "zh")
// 标题及小标题样式
show heading: set text(themeColor, 1.1em)
// 二级标题下加一条横线
show heading.where(level: 2): it => stack(
// v(0.2em),
it,
v(0.2em),
line(length: 100%, stroke: 0.05em + themeColor),
// v(0.1em),
)
// 更改 bullet list 的图标
// set list(indent: 1em, body-indent: 0.8em, marker: faAngleRight)
// 上面的语句无法精确控制图标位置, 因此改用了下列方法重写 list
show list: it => stack(spacing: 0.4em, ..it.children.map(item => {
grid(
columns: (2em, 1fr),
gutter: (0em),
box({
h(0.75em)
faAngleRight
}),
pad(top: 0.15em, item.body)
)
}))
// 链接颜色
show link: set text(fill: themeColor)
// 主体设定
set par(justify: true)
show par: set block(spacing: 0.65em)
// 首部与照片
grid(
columns: (photographWidth, 1fr, auto),
if (photograph != "") {
image(photograph, width: photographWidth)
},
gutter: (gutterWidth, 0em),
header
)
body
}
// 带竖线的侧边栏
#let sidebar(side, content, withLine: true, sideWidth: 12%) = style(styles => {
let sideSize = measure(side, styles)
let contentSize = measure(content, styles)
let height = calc.max(sideSize.height, contentSize.height) + 0.5em
grid(
columns: (sideWidth, 0%, 1fr),
gutter: (0.75em),
{
set align(right)
v(0.25em)
side
v(0.25em)
},
if (withLine) {line(end: (0em, height), stroke: 0.05em)},
{
v(0.25em)
content
v(0.25em)
},
)
})
#let infoitem(
icon: icon,
content: content,
) = {
set align(left)
set text(font: (font.mono, font.cjk), fill: black)
grid(
columns: (auto, auto),
gutter: (5pt),
icon, content
)
}
// person info
#let person(
color: black,
// ap,
home,
school,
major,
phone,
email,
github
) = {
set align(left+bottom)
v(0.3em)
set text(font: (font.mono, font.cjk), fill: color, size: 14pt)
// ap
set text(size: 10pt)
grid(
columns: (1fr, 1fr, 1fr),
gutter: (1em),
home, school, major,
phone, email, github
)
}
// 教育背景
#let education(
date,
school,
desc
) = {
set align(right)
set text(font: (font.main, font.cjk), size: 1em)
grid(
columns: (auto, 1fr),
gutter: (5pt),
date, school
)
desc
}
#let internship(
date,
position,
desc
) = {
set text(font: (font.main, font.cjk), size: 1em)
v(0.1em)
grid(
columns: (1fr, auto),
gutter: (0em),
date, position
)
v(-0.5em)
grid(
gutter: (0em),
desc
)
}
// 日期:
#let date(body) = text(
weight: "extralight",
fill: rgb(0, 0, 0),
size: 1.2em,
body
)
// 技术: 字体变细
#let tech(body) = block({
set text(weight: "extralight", size: 1em)
body
})
// 项目
#let item(
title,
desc,
endnote,
data,
) = {
set text(font: (font.main, font.cjk), size: 1em)
// v(0.1em)
grid(
columns: (30%, 1fr, auto),
gutter: (0em),
title, desc, endnote
)
v(-0.4em)
data
}
// 研究
#let researchitem(
title,
endnote,
) = {
v(0.25em)
grid(
columns: (1fr, auto),
gutter: (0em),
title, endnote
)
}
|
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/identify-drivetrain.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Identify Problem: Drivetrain",
type: "identify",
date: datetime(year: 2023, month: 5, day: 12),
author: "<NAME>",
witness: "Violet Ridge",
)
The drivetrain is the most essential component of our robot. It lets us traverse
the field, and is the base for all of our other subsystems. Ever single season
besides Nothing But Net has needed a drivetrain, so we assumed that we'd need
one for this season as well.
#align(center)[
#image("/assets/game-challenges/traversing.svg", height: 35%)
]
= Design Constraints
- The drivetrain must fit inside an 18" by 18" by 18" cube.
- The drivetrain must use no more than 66Ws of motors.
= Design Goals
- A speed faster than our drivetrain from Spin Up (4.25 f/s)
- Bracing that keeps all essential structure of the drivetrain square
- The ability to cross the barrier
|
https://github.com/liuxu89/Principles | https://raw.githubusercontent.com/liuxu89/Principles/main/templates/page.typ | typst | // This is important for shiroa to produce a responsive layout
// and multiple targets.
#import "@preview/shiroa:0.1.1": get-page-width, target, is-web-target, is-pdf-target, plain-text, templates
#import templates: *
// Metadata
#let page-width = get-page-width()
#let is-pdf-target = is-pdf-target()
#let is-web-target = is-web-target()
// first line indent
#let empty-par = par[#box()]
#let fake-par = context empty-par + v(-measure(empty-par + empty-par).height)
// Theme (Colors)
#let (
style: theme-style,
is-dark: is-dark-theme,
is-light: is-light-theme,
main-color: main-color,
dash-color: dash-color,
code-extra-colors: code-extra-colors,
) = book-theme-from(toml("theme-style.toml"), xml: it => xml(it))
// Fonts
#let main-font = (
"Charter",
"Source Han Serif SC",
"Source Han Serif TC",
// shiroa's embedded font
"Linux Libertine",
)
#let code-font = (
"BlexMono Nerd Font Mono",
// shiroa's embedded font
"DejaVu Sans Mono",
)
// Sizes
#let main-size = if is-web-target {
16pt
} else {
10.5pt
}
// #let heading-sizes = (26pt, 22pt, 14pt, 12pt, main-size)
#let heading-sizes = (30pt, 26pt, 18pt, 16pt, main-size)
#let list-indent = 0.5em
/// 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: "Typst Book", authors: (), kind: "page", body) = {
// set basic document metadata
set document(
author: authors,
title: title,
) if not is-pdf-target
// set web/pdf page properties
set page(
numbering: none,
number-align: center,
width: page-width,
)
// remove margins for web target
set page(
margin: (
// reserved beautiful top margin
top: 20pt,
// reserved for our heading style.
// If you apply a different heading style, you may remove it.
left: 20pt,
// Typst is setting the page's bottom to the baseline of the last line of text. So bad :(.
bottom: 0.5em,
// remove rest margins.
rest: 0pt,
),
height: auto,
) if is-web-target
// Set main text
set text(
font: main-font,
size: main-size,
fill: main-color,
lang: "en",
)
// Set main spacing
set enum(
indent: list-indent * 0.618,
body-indent: list-indent,
)
set list(
indent: list-indent * 0.618,
body-indent: list-indent,
)
set par(leading: 1em, first-line-indent: 2em)
set block(spacing: 1.3em)
// Set text, spacing for headings
// Render a dash to hint headings instead of bolding it as well if it's for web.
show heading: set text(weight: "regular") if is-web-target
show heading: it => {
let it = {
set text(size: heading-sizes.at(it.level))
if is-web-target {
heading-hash(it, hash-color: dash-color)
}
it
}
block(
spacing: 1.45em,
below: 1.45em,
it,
)
fake-par
}
// link setting
show link: set text(fill: dash-color)
// math setting
show math.equation: set text(weight: 400)
// code block setting
show raw: it => {
set text(font: code-font)
if "block" in it.fields() and it.block {
rect(
width: 100%,
inset: (x: 4pt, y: 5pt),
radius: 4pt,
fill: code-extra-colors.bg,
[
#set text(fill: code-extra-colors.fg) if code-extra-colors.fg != none
#set par(justify: false)
// #place(right, text(luma(110), it.lang))
#it
],
)
} else {
it
}
}
// Main body.
set par(justify: true)
body
}
#let part-style = heading
|
|
https://github.com/saYmd-moe/note-for-statistical-mechanics | https://raw.githubusercontent.com/saYmd-moe/note-for-statistical-mechanics/main/main.typ | typst | #import "template.typ": *
// 文章信息设置
#show: conf.with(
title: "热力学与统计物理笔记整理",
shortitle: "Note for Thermodynamics and Statistical Mechanics",
author: "saYmd"
)
//----------------热力学部分----------------
#include "./contents/PartI/PartI.typ"
#include "./contents/PartI/Chp01.typ"
#include "./contents/PartI/Chp02.typ"
#include "./contents/PartI/Chp03.typ"
#include "./contents/PartI/Chp04.typ"
//-----------------------------------------
#pagebreak()
//----------------统计力学部分----------------
#include "./contents/PartII/PartII.typ"
#include "./contents/PartII/Chp05.typ"
#include "./contents/PartII/Chp06.typ"
#include "./contents/PartII/Chp07.typ"
|
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-12-31/23-12-31.typ | typst | #import "/template.typ": *
#show: project.with(
date: "31/12/23",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
missingMembers: (
"<NAME>",
),
timeStart: "15:00",
timeEnd: "16:00",
);
= Ordine del giorno
- Valutazione dell'avanzamento;
- Analisi di retrospettiva;
- Pianificazione.
== Valutazione dell'avanzamento
Ogni membro del gruppo ha esposto ciò che ha svolto durante lo sprint rispetto al prodotto software o documentale che aveva in carico.
=== Piano di Qualifica
- Sono state individuate delle metriche di base riguardanti i documenti e l'andamento generale del gruppo;
- È stato creato un cruscotto di qualità su Grafana per monitorare l'andamento del gruppo tramite misurazione degli story points, i quali vengono classificati in quattro stati:
+ in corso;
+ in verifica;
+ completato;
+ da completare.
=== Norme di Progetto
Non sono stati prodotti tutti i capitoli preventivati anche a causa di un prevedibile rallentamento dei lavori discusso nella @improvements.\
Di seguito è riportata la situazione dei capitoli a fine sprint:
#figure(
table(
columns: 5,
[*Numero ticket*],[*Numero sezione*],[*Categoria*],[*Titolo*],[*Stato*],
[DOC-292\*], [6.3.4], [Technical Management processes], [Risk Management process], [Completato],
[DOC-155], [6.3.7], [Technical Management processes], [Measurement process], [Completato],
[DOC-159], [6.4.2], [Technical processes], [Stakeholder Needs and Requirements Definition process], [Completato],
[DOC-156], [6.3.8], [Technical Management processes], [Quality Assurance process], [In verifica],
[DOC-155], [6.4.1], [Technical processes], [Business or Mission Analysis process], [In verifica],
[DOC-146], [6.2.5], [Organizational\ Project-Enabling processes], [Quality Management process], [Da completare],
[DOC-160], [6.4.3], [Technical processes], [System/Software requirements definition process], [Da completare],
[DOC-161\*\*], [6.4.4], [Technical processes], [Architecture Definition process], [Da completare],
),
caption: "Stato capitoli Norme di Progetto a fine sprint 8"
)
\* Revisione ulteriore di un capitolo già completato;\
\*\* Durante la retrospettiva il capitolo è stato classificato come non indispensabile per la revisione RTB, in quanto tratta tematiche non ancora affrontate dal gruppo.
=== Analisi dei Requisiti
È stato implementato il tracciamento requisito-fonte. È necessaria una revisione generale del documento.
=== Piano di Progetto
Non sono state rilevate criticità, la stesura del documento procede senza problemi.
=== PoC
È stato realizzato un PoC finale tramite la compattazione dei PoC esplorativi realizzati finora, i quali avevano ottenuto l'approvazione del Proponente durante i meeting svolti prima del periodo delle vacanze. Dato il cambio di ruoli è stato programmato un meeting interno per spiegare nel dettaglio il PoC e il suo funzionamento ai nuovi Programmatori. Sarà inoltre necessario realizzare un video demo da mostrare al Proponente.
=== Automazioni
Non sono stati apportati importanti cambiamenti. Sono ancora presenti dei bug, in particolare il numero di versione dei documenti non viene correttamente aggiornato.
== Analisi di retrospettiva
=== Keep doing
Nonostante il periodo di feste, i membri del gruppo sono riusciti a riprendere i lavori in autonomia senza particolari problemi.
=== Improvements <improvements>
È stato notato un rallentamento dei lavori e una concentrazione degli stessi nel weekend, ovviamente causato dal periodo di feste. Questo rallentamento non viene visto, però, come un vero e proprio aspetto da migliorare dato che era già stato preso in considerazione.\
Si prevede comunque un ritorno alla normale attività per il prossimo sprint, anche in vista dell'apertura della finestra per la revisione RTB.
== Pianificazione
- Viene fissato un meeting in data martedì 2 gennaio per:
- selezionare, tra i capitoli non ancora redatti delle Norme di Progetto, quelli necessari alla revisione RTB, in modo da proseguire la stesura del documento il più rapidamente possibile;
- illustrare la struttura e il funzionamento del PoC ai nuovi Programmatori.
- Si continua la stesura delle Norme di Progetto con i capitoli selezionati durante il meeting;
- L'Analista dovrà terminare il documento Analisi dei Requisiti ed effettuarne una revisione completa;
- Si continua la stesura del Piano di Qualifica lavorando sulle metriche individuate e sull'implementazione di una dashboard per la loro visualizzazione grafica;
- L'Amministratore dovrà:
- redigere i verbali;
- modificare il documento Piano di Progetto aggiungendo il preventivo del nono sprint e il consuntivo dell'ottavo sprint;
- migliorare le GitHub Action risolvendo gli errori legati al versionamento dei file.
- Si dovrà realizzare un video demo da mostrare al Proponente per ricevere dei feedback sul PoC realizzato.
|
|
https://github.com/flechonn/interface-typst | https://raw.githubusercontent.com/flechonn/interface-typst/main/docs/Base_exercices.md | markdown | <span style="color:#7B7D7D;">[ FRENCH VERSION BELOW ]
## EXERCISE BASE
### Introduction
Documentation on the format we have chosen for the exercise sheets provided as input.
We initially started with the following exam sheet: [exam sheet](./exemple/Examen-ALGO6-2023.04.19.tex), which we then divided into several exercises and formatted according to our needs.
### Standard Exercise File
#### Metadata
##### LaTeX Exercise File
Metadata will be provided in the following format in the .tex exercise file:
```tex
% Command to define metadata
\newcommand{\setMeta}[2]{}
\setMeta{title}{Mon Title}
\setMeta{duration}{1h30}
\setMeta{difficulty}{easy}
\setMeta{solution}{0}
\setMeta{figures}{none}
\setMeta{points}{5pts}
\setMeta{bonus}{0}
\setMeta{author}{Moi}
\setMeta{references}{none}
\setMeta{language}{français}
\setMeta{material}{none}
```
##### Typst Exercise file
```.typ
#show terms: it => {
let title = label("Mon Title")
let duration = label("1h30")
let difficulty = label("easy")
let solution = label("0")
let figures = label("none")
let points = label("5pts")
let bonus = label("0")
let author = label("Moi")
let references = label("none")
let language = label("français")
let material = label("none")
}
```
#### Exercise Content
##### Fichier exercice LaTeX
The exercise content will be provided in the following format in the .tex exercise file:
```tex
\begin{document}
\section{Exercice}
% Section dedicated to the exercise
\section{Solution}
% Section dedicated to the solution if it exists
\end{document}
```
##### Typst Exercise File
```typ
TODO
```
### Choice of Database
We chose to use formatted LaTeX and Typst exercise files to build our database. This will allow us to more easily retrieve metadata and exercise content.
<br>
<br>
<span style="color:#7B7D7D;">[ FRENCH VERSION ]
## BASE D'EXERCICES
### Introduction
Documentation sur le format que nous avons choisi pour les fiches d'exercices données en entrée.
Nous sommes initialement partis de la feuille d'examen suivante : [feuille examen](./exemple/Examen-ALGO6-2023.04.19.tex), que nous avons ensuite découpé en plusieurs exercices, et formaté selon nos besoins.
### Fichier exercice type
#### Métadonnées
##### Fichier exercice LaTeX
Les métadonnées seront données selon le format suivant dans le fichier exercice .Tex :
```tex
% Commande pour définir les métadonnées
\newcommand{\setMeta}[2]{}
\setMeta{title}{Mon Title}
\setMeta{duration}{1h30}
\setMeta{difficulty}{easy}
\setMeta{solution}{0}
\setMeta{figures}{none}
\setMeta{points}{5pts}
\setMeta{bonus}{0}
\setMeta{author}{Moi}
\setMeta{references}{none}
\setMeta{language}{français}
\setMeta{material}{none}
```
##### Fichier exercice Typst
```.typ
#show terms: it => {
let title = label("Mon Title")
let duration = label("1h30")
let difficulty = label("easy")
let solution = label("0")
let figures = label("none")
let points = label("5pts")
let bonus = label("0")
let author = label("Moi")
let references = label("none")
let language = label("français")
let material = label("none")
}
```
#### Contenu de l'exercice
##### Fichier exercice LaTeX
Le contenu de l'exercice sera donné selon le format suivant dans le fichier exercice .tex :
```tex
\begin{document}
\section{Exercice}
% Partie dédiée à l'exercice
\section{Solution}
% Partie dédiée à la solution si celle-ci existe
\end{document}
```
##### Fichier exercice Typst
```.typ
A faire
```
### Choix de la base de données
Nous avons choisit de prendre des fichiers d'exercices LaTeX et Typst formatés pour constituer notre base de données. Cela nous permettra de retrouver plus facilement les métadonnées et le contenu de l'exercice.
|
|
https://github.com/Quaternijkon/Typst_ADSL | https://raw.githubusercontent.com/Quaternijkon/Typst_ADSL/main/theme.typ | typst |
#import "@preview/touying:0.4.2": *
#let ustcblue=rgb("#034ea1")
//横向导航栏
#let ustc-nav-bar(self: none) = states.touying-progress-with-sections(dict => {
let (current-sections, final-sections) = dict
current-sections = current-sections.filter(section => section.loc != none).map(section => (
section,
section.children,
)).flatten().filter(item => item.kind == "section")
final-sections = final-sections.filter(section => section.loc != none).map(section => (
section,
section.children,
)).flatten().filter(item => item.kind == "section")
let current-index = current-sections.len() - 1
set text(size: 1em)
for (i, section) in final-sections.enumerate() {
set text(fill: if i != current-index {
gray
} else {
white
})
box(inset: 1em)[#link(section.loc, utils.section-short-title(section))<touying-link>]
}
})
//章节目录页()
#let ustc-outline(self: none) = states.touying-progress-with-sections(dict => {
let (current-sections, final-sections) = dict
current-sections = current-sections.filter(section => section.loc != none).map(section => (
section,
section.children,
)).flatten().filter(item => item.kind == "section")
final-sections = final-sections.filter(section => section.loc != none).map(section => (
section,
section.children,
)).flatten().filter(item => item.kind == "section")
let current-index = current-sections.len() - 1
for (i, section) in final-sections.enumerate() {
if i == 0 {
continue
}
set text(fill: if current-index == 0 or i == current-index {
self.colors.primary
} else {
self.colors.secondary.lighten(80%)
})
block(
spacing: 1.5em,
[#link(section.loc, utils.section-short-title(section))<touying-link>],
)
if i == current-index {
block(height: 2pt, width: 100%, spacing: 0pt, utils.call-or-display(self, self.ustc-chapter-progress-bar))
}
}
// for (i, section) in final-sections.enumerate() {
// if i == 0 {
// continue
// } else if current-index == 0 {
// set text(fill: self.colors.primary)
// block(
// spacing: 1.5em,
// [#link(section.loc, utils.section-short-title(section))<touying-link>],
// )
// } else if i == current-index {
// set text(fill: self.colors.primary)
// block(
// spacing: 1.5em,
// [#link(section.loc, utils.section-short-title(section))<touying-link>],
// )
// block(height: 2pt, width: 100%, spacing: 0pt, utils.call-or-display(self, self.ustc-chapter-progress-bar))
// } else if i < current-index {
// set text(fill: self.colors.secondary)
// block(
// spacing: 1.5em,
// [#link(section.loc, utils.section-short-title(section))<touying-link>],
// )
// } else {
// set text(fill: self.colors.tertiary)
// block(
// spacing: 1.5em,
// [#link(section.loc, utils.section-short-title(section))<touying-link>],
// )
// }
// }
})
#let slide(
self: none,
title: auto,
subtitle: auto,
header: auto,
footer: auto,
display-current-section: auto,
..args,
) = {
if title != auto {
self.ustc-title = title
}
if subtitle != auto {
self.ustc-subtitle = subtitle
}
if header != auto {
self.ustc-header = header
}
if footer != auto {
self.ustc-footer = footer
}
if display-current-section != auto {
self.ustc-display-current-section = display-current-section
}
(self.methods.touying-slide)(
..args.named(),
self: self,
title: title,
setting: body => {
show: args.named().at("setting", default: body => body)
align(horizon, body)
},
..args.pos(),
)
}
#let title-slide(self: none, ..args) = {
self = utils.empty-page(self)
let info = self.info + args.named()
info.authors = {
let authors = if "authors" in info {
info.authors
} else {
info.author
}
if type(authors) == array {
authors
} else {
(authors,)
}
}
let content = {
if info.logo != none {
align(center + horizon, info.logo)
}
show: align.with(center + horizon)
block(
fill: self.colors.primary,
inset: 1.5em,
radius: 0.5em,
breakable: false,
{
text(size: 1.2em, fill: self.colors.neutral-lightest, weight: "bold", info.title)
if info.subtitle != none {
parbreak()
text(size: 1.0em, fill: self.colors.neutral-lightest, weight: "bold", info.subtitle)
}
},
)
// authors
grid(
columns: (1fr,) * calc.min(info.authors.len(), 3),
column-gutter: 1em,
row-gutter: 1em,
..info.authors.map(author => text(fill: black, author)),
)
v(0.5em)
// institution
if info.institution != none {
parbreak()
text(size: 0.7em, info.institution)
}
// date
if info.date != none {
parbreak()
text(size: 1.0em, utils.info-date(self))
}
// place(right + top, image("assets/vi/ustc_logo_side.svg",format: "svg"), dx: -1em)
}
(self.methods.touying-slide)(self: self, repeat: none, content)
}
#let outline-slide(self: none) = {
self.ustc-title = context if text.lang == "zh" [大纲] else [Outline]
let content = {
set align(horizon)
set text(weight: "bold")
hide([-])
ustc-outline(self: self)
}
(self.methods.touying-slide)(self: self, repeat: none, section: (title: context if text.lang == "zh" [大纲] else [Outline]), content)
}
#let new-section-slide(self: none, short-title: auto, title) = {
self.ustc-title = context if text.lang == "zh" [大纲] else [Outline]
let content = {
set align(horizon)
set text(weight: "bold")
hide([-]) // magic
ustc-outline(self: self)
}
(self.methods.touying-slide)(self: self, repeat: none, section: (title: title, short-title: short-title), content)
}
#let ending-slide(self: none, title: none, body) = {
let content = {
set align(center + horizon)
if title != none {
block(
fill: self.colors.tertiary,
inset: (top: 0.7em, bottom: 0.7em, left: 3em, right: 3em),
radius: 0.5em,
text(size: 1.5em, fill: self.colors.neutral-lightest, title),
)
}
body
}
(self.methods.touying-slide)(self: self, repeat: none, content)
}
#let slides(self: none, title-slide: true, slide-level: 1, ..args) = {
if title-slide {
(self.methods.title-slide)(self: self)
}
(self.methods.touying-slides)(self: self, slide-level: slide-level, ..args)
}
#let focus-slide(self: none, background-color: none, background-img: none, body) = {
let background-color = if background-img == none and background-color == none {
rgb(self.colors.primary)
} else {
background-color
}
self = utils.empty-page(self)
self.page-args += (
fill: self.colors.primary,
margin: 1em,
..(if background-color != none { (fill: background-color) }),
..(if background-img != none { (background: {
set image(fit: "stretch", width: 100%, height: 100%)
background-img
})
}),
)
set text(fill: white, weight: "bold", size: 2em)
(self.methods.touying-slide)(self: self, repeat: none, align(horizon, body))
}
#let matrix-slide(self: none, columns: none, rows: none, ..bodies) = {
self = utils.empty-page(self)
(self.methods.touying-slide)(self: self, composer: (..bodies) => {
let bodies = bodies.pos()
let columns = if type(columns) == int {
(1fr,) * columns
} else if columns == none {
(1fr,) * bodies.len()
} else {
columns
}
let num-cols = columns.len()
let rows = if type(rows) == int {
(1fr,) * rows
} else if rows == none {
let quotient = calc.quo(bodies.len(), num-cols)
let correction = if calc.rem(bodies.len(), num-cols) == 0 { 0 } else { 1 }
(1fr,) * (quotient + correction)
} else {
rows
}
let num-rows = rows.len()
if num-rows * num-cols < bodies.len() {
panic("number of rows (" + str(num-rows) + ") * number of columns (" + str(num-cols) + ") must at least be number of content arguments (" + str(bodies.len()) + ")")
}
let cart-idx(i) = (calc.quo(i, num-cols), calc.rem(i, num-cols))
let color-body(idx-body) = {
let (idx, body) = idx-body
let (row, col) = cart-idx(idx)
let color = if calc.even(row + col) { white } else { silver }
set align(center + horizon)
rect(inset: .5em, width: 100%, height: 100%, fill: color, body)
}
let content = grid(
columns: columns, rows: rows,
gutter: 0pt,
..bodies.enumerate().map(color-body)
)
content
}, ..bodies)
}
// #let register(
// self: themes.default.register(),
// aspect-ratio: "16-9",
// progress-bar: true,
// footer-columns: (25%, 25%, 1fr, 5em),
// footer-a: self => self.info.author,
// footer-b: self => utils.info-date(self),
// footer-c: self => if self.info.short-title == auto {
// self.info.title
// } else {
// self.info.short-title
// },
// footer-d: self => {
// states.slide-counter.display() + " / " + states.last-slide-number
// },
// ..args,
// ) = {
// // code implementation
// }
#let register(
self: themes.default.register(),
aspect-ratio: "16-9",
progress-bar: true,
footer-columns: (25%, 25%, 1fr, 5em),
footer-a: self => self.info.author,
footer-b: self => utils.info-date(self),
footer-c: self => if self.info.short-title == auto {
self.info.title
} else {
self.info.short-title
},
footer-d: self => {
states.slide-counter.display() + " / " + states.last-slide-number
},
footer-g: self => {
link("https://github.com/Quaternijkon/Typst_USTC_CS.git",image("assets/img/github-mark-white.svg"))
},
..args,
) = {
// color theme
self = (self.methods.colors)(
self: self,
// primary: rgb("#034ea1"),
// primary-dark: rgb("#004098"),
// secondary: rgb("#a289ca"),
// secondary-dark: rgb("#543795"),
primary-lighten: rgb("#a289ca"),
primary: rgb("#543795"),
secondary: rgb("#034ea1"),
secondary-dark: rgb("#004098"),
tertiary: rgb("#005bac"),
neutral-lightest: rgb("#ffffff"),
neutral-darkest: rgb("#000000"),
themeblue: rgb("#4285f4"),
themegreen: rgb("#34a853"),
themeyellow: rgb("#fbbc05"),
themered: rgb("#ea4335"),
)
// marker
self.ustc-knob-marker = box(
width: 0.5em,
place(
dy: 0.1em,
circle(
fill: gradient.radial(self.colors.primary.lighten(100%), self.colors.primary.darken(40%), focal-center: (30%, 30%)),
radius: 0.25em,
),
),
)
// save the variables for later use
self.ustc-enable-progress-bar = progress-bar
self.ustc-progress-bar = self => states.touying-progress(ratio => {
grid(
columns: (ratio * 100%, 1fr),
rows: 2pt,
components.cell(fill: gradient.linear(self.colors.primary.lighten(10%),self.colors.primary.darken(10%))),
components.cell(fill: self.colors.neutral-lightest),
)
})
self.ustc-chapter-progress-bar = self => states.touying-progress(ratio => {
grid(
columns: (ratio * 100%, 1fr),
rows: 2pt,
components.cell(fill: self.colors.primary),
components.cell(fill: self.colors.secondary.lighten(60%)),
)
})
self.ustc-navigation = self => {
grid(
align: center + horizon,
columns: (1fr, auto, auto),
rows: 1em,
components.cell(fill: self.colors.primary, ustc-nav-bar(self: self)),
// block(fill: self.colors.neutral-lightest, inset: 4pt, height: 100%, image("assets/vi/ustc_logo_side.svg")),
)
}
self.ustc-title = none
self.ustc-subtitle = none
self.ustc-footer = self => {
let cell(fill: none, it) = rect(
width: 100%,
height: 100%,
inset: 1mm,
outset: 0mm,
fill: fill,
stroke: none,
align(horizon, text(fill: self.colors.neutral-lightest, it)),
)
// grid(
// align: center + horizon,
// columns: (1fr, auto, auto),
// rows: 1em,
// components.cell(fill: self.colors.primary, ustc-nav-bar(self: self)),
// )
grid(
// columns: footer-columns,
columns:(24%,68%,3%,5%),
rows: (2em, auto),
// cell(fill: self.colors.primary, utils.call-or-display(self, footer-a)),
// cell(fill: self.colors.primary-dark, utils.call-or-display(self, footer-b)),
// cell(fill: self.colors.primary, utils.call-or-display(self, footer-c)),
cell(fill: self.colors.primary, utils.call-or-display(self, footer-c)),
cell(fill: self.colors.primary, ustc-nav-bar(self: self)),
// cell(fill: self.colors.primary, utils.call-or-display(self, footer-a)),
// cell(fill: self.colors.primary-dark.darken(20%), utils.call-or-display(self, footer-b)),
cell(fill: self.colors.primary, utils.call-or-display(self, footer-g)),
cell(fill: self.colors.primary, utils.call-or-display(self, footer-d)),
)
}
self.ustc-header = self => {
if self.ustc-title != none {
block(
width: 100%,
height: 2em,
fill: gradient.linear(self.colors.primary, self.colors.neutral-lightest),
)
place(left + horizon, text(fill: self.colors.neutral-lightest, weight: "bold", size: 1.3em, self.ustc-title), dx: 1.5em)
place(right + horizon, image("assets/img/adsl_notext.png",format: "png",width: 25%), dx: -1em)
}
}
// set page
let header(self) = {
set align(top)
grid(
rows: (auto, auto),
// utils.call-or-display(self, self.ustc-navigation),
utils.call-or-display(self, self.ustc-header),
)
}
let footer(self) = {
set text(size: .5em)
set align(center + bottom)
grid(
rows: (auto, auto),
utils.call-or-display(self, self.ustc-footer),
if self.ustc-enable-progress-bar {
utils.call-or-display(self, self.ustc-progress-bar)
},
)
}
self.page-args += (
paper: "presentation-" + aspect-ratio,
header: header,
footer: footer,
header-ascent: 0em,
footer-descent: 0em,
margin: (top: 4.5em, bottom: 3.5em, x: 2.5em),
)
// register methods
self.methods.slide = slide
self.methods.title-slide = title-slide
self.methods.outline-slide = outline-slide
self.methods.new-section-slide = new-section-slide
self.methods.touying-new-section-slide = new-section-slide
self.methods.ending-slide = ending-slide
self.methods.focus-slide = focus-slide
self.methods.matrix-slide = matrix-slide
self.methods.slides = slides
self.methods.touying-outline = (self: none, enum-args: (:), ..args) => {
states.touying-outline(self: self, enum-args: (tight: false) + enum-args, ..args)
}
self.methods.alert = (self: none, it) => text(fill: self.colors.primary, it)
self.methods.tblock = (self: none, title: none, it) => {
grid(
columns: 1,
row-gutter: 0pt,
block(
fill: self.colors.primary,
width: 100%,
radius: (top: 6pt),
inset: (top: 0.4em, bottom: 0.3em, left: 0.5em, right: 0.5em),
text(fill: self.colors.neutral-lightest, weight: "bold", title),
),
rect(
fill: gradient.linear(self.colors.primary, self.colors.primary.lighten(90%), angle: 90deg),
width: 100%,
height: 4pt,
),
block(
fill: self.colors.primary.lighten(90%),
width: 100%,
radius: (bottom: 6pt),
inset: (top: 0.4em, bottom: 0.5em, left: 0.5em, right: 0.5em),
it,
),
)
}
self.methods.init = (self: none, lang: "zh", font: ("Linux Libertine",), body) => {
set text(size: 19pt, font: font)
set heading(outlined: false)
set list(marker: self.ustc-knob-marker)
show strong: it => text(weight: "bold", it)
show figure.caption: set text(size: 0.6em)
show footnote.entry: set text(size: 0.6em)
show link: it => if type(it.dest) == str {
set text(fill: self.colors.primary)
it
} else {
it
}
show: if lang == "zh" {
import "@preview/cuti:0.2.1": show-cn-fakebold
show-cn-fakebold
} else {
it => it
}
set text(lang: lang)
show figure.where(kind: table): set figure.caption(position: top)
body
}
self
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/document_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 10-12 can only be used in set rules
// #document() |
https://github.com/jxpeng98/Typst-Paper-Template | https://raw.githubusercontent.com/jxpeng98/Typst-Paper-Template/main/README.md | markdown | MIT License | # Typst-Paper-Template
Following the official tutorial, I create a single-column paper template for general use. You can use it for papers published on SSRN etc.
## How to use
### Use as a template package
Typst integrated the template with their official package manager. You can use it as the other third-party packages.
You only need to enter the following command in the terminal to initialize the template.
```bash
typst init @preview/ssrn-scribe
```
If will generate a subfolder `ssrn-scribe` including the `main.typ` file in the current directory with the latest version of the template.
### Mannully use
1. Download the template or clone the repository.
2. generate your bibliography file using `.biblatex` and store the file in the same directory of the template.
3. modify the `main.typ` file in the subfolder `/template` and compile it.
***Note:* You should have `paper_template.typ` and `main.typ` in the same directory.**
In the template, you can modify the following parameters:
`maketitle` is a boolean (**compulsory**). If `maketitle=true`, the template will generate a new page for the title. Otherwise, the title will be shown on the first page.
- `maketitle=true`:
| Parameter | Default | Optional | Description |
| --- | --- | --- | --- |
| `font` | "PT Serif" | Yes | The font of the paper. You can choose "Times New Roman" or "Palatino" |
| `fontsize` | 11pt | Yes | The font size of the paper. You can choose 10pt or 12pt |
| `title` | "Title" | No | The title of the paper |
| `subtitle` | none | Yes | The subtitle of the paper, use "" or [] |
| `authors` | none | No | The authors of the paper |
| `date` | none | Yes | The date of the paper |
| `abstract` | none | Yes | The abstract of the paper |
| `keywords` | none | Yes | The keywords of the paper |
| `JEL` | none | Yes | The JEL codes of the paper |
| `acknowledgments` | none | Yes | The acknowledgment of the paper |
| `bibliography` | none | Yes | The bibliography of the paper ```bibliography: bibliography("bib.bib", title: "References", style: "apa")``` |
- `maketitle=false`:
| Parameter | Default | Optional | Description |
| --- | --- | --- | --- |
| `font` | "PT Serif" | Yes | The font of the paper. You can choose "Times New Roman" or "Palatino" |
| `fontsize` | 11pt | Yes | The font size of the paper. You can choose 10pt or 12pt |
| `title` | "Title" | No | The title of the paper |
| `subtitle` | none | Yes | The subtitle of the paper, use "" or [] |
| `authors` | none | No | The authors of the paper |
| `date` | none | Yes | The date of the paper |
| `bibliography` | none | Yes | The bibliography of the paper ```bibliography: bibliography("bib.bib", title: "References", style: "apa")``` |
**Note: You need to keep the comma at the end of the first bracket of the author's list, even if you have only one author.**
```typst
(
name: "",
affiliation: "", // optional
email: "", // optional
note: "", // optional
),
```
```typst
#import "@preview/ssrn-scribe:0.5.0": *
#show: paper.with(
font: "PT Serif", // "Times New Roman"
fontsize: 12pt, // 12pt
maketitle: true, // whether to add new page for title
title: [#lorem(5)], // title
subtitle: "A work in progress", // subtitle
authors: (
(
name: "<NAME>",
affiliation: "Artos Institute",
email: "<EMAIL>",
note: "123",
),
),
date: "July 2023",
abstract: lorem(80), // replace lorem(80) with [ Your abstract here. ]
keywords: [
Imputation,
Multiple Imputation,
Bayesian,],
JEL: [G11, G12],
acknowledgments: "This paper is a work in progress. Please do not cite without permission.",
// bibliography: bibliography("bib.bib", title: "References", style: "apa"),
)
= Introduction
#lorem(50)
```
## Preview
### Example
Here is a screenshot of the template:

### Example-brief with `maketitle=true`

### Example-brief with `maketitle=false`

|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/sweet-graduate-resume/0.1.0/template/main.typ | typst | Apache License 2.0 | #import "@preview/sweet-graduate-resume:0.1.0": *
#show: doc => preamble(doc)
#let urls = (
(
name: "Codeberg",
url: "https://codeberg.org/innocent_zero",
svg: image("svg/codeberg.svg"),
fa: false,
brand: false,
solid: false,
),
(name: "Website", url: "https://example.com", svg: "link", fa: true, brand: false, solid: false),
(name: "Website", url: "https://example.com", svg: "github", fa: true, brand: true, solid: true),
)
#header("InnocentZero", "roll", "school", urls)
#let edu = ((prog: "Bachelors", school: "college", grade: "4.0"), (prog: "grad", school: "school", grade: "4.0"))
#section-header("Education")
#education(edu)
#let achievements = ([#lorem(30)], [#lorem(20)])
#section-header("Scholastic Achievements")
#points(achievements)
#let skills = ([#lorem(30)], [#lorem(20)])
#section-header("Major Competitions and Technical Skills")
#points(skills)
#let courses = ([#lorem(4)], [#lorem(5)], [#lorem(3)], [#lorem(2)], [#lorem(4)])
#section-header("Relevant Coursework")
#dual(courses)
#section-header("Professional Experience")
#let interner = ([#lorem(25)], [#lorem(30)])
#dated-section(
"Software Intern",
"industrial",
date-start: "May 2024",
date-end: "Aug 2024",
ongoing: false,
points: interner,
)
#dated-section(
"AI Intern",
"research",
date-start: "May 2024",
ongoing: true,
points: interner,
)
#section-header("Projects")
#let interner = ([#lorem(25)], [#lorem(30)])
#dated-section(
"Cybersecurity Project Maintainer",
"self",
points: interner,
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.2/src/draw/projection.typ | typst | Apache License 2.0 | #import "grouping.typ": group, get-ctx
#import "transformations.typ": set-transform
#import "/src/process.typ"
#import "/src/matrix.typ"
#import "/src/drawable.typ"
#import "/src/util.typ"
#let ortho-projection-matrix = ((1, 0, 0, 0),
(0, 1, 0, 0),
(0, 0, 0, 0),
(0, 0, 0, 1))
// Get an orthographic view matrix for 3 angles
#let ortho-matrix(x, y, z) = matrix.mul-mat(
matrix.ident(),
matrix.transform-rotate-x(x),
matrix.transform-rotate-y(y),
matrix.transform-rotate-z(z),
)
// Pushes a view- and projection-matrix to transform
// all `body` elements. The current context transform is
// not modified.
//
// - body (element): Elements
// - view-matrix (matrix): View matrix
// - projection-matrix (matrix): Projection matrix
// - reset-transform (bool): If true, override (and thus ignore)
// the current transformation with the new matrices instead
// of multiplying them.
#let _projection(body, view-matrix, projection-matrix, reset-transform: false) = {
(ctx => {
let transform = ctx.transform
ctx.transform = matrix.mul-mat(projection-matrix, view-matrix)
if not reset-transform {
ctx.transform = matrix.mul-mat(transform, ctx.transform)
}
let (ctx, drawables, bounds) = process.many(ctx, util.resolve-body(ctx, body))
ctx.transform = transform
return (
ctx: ctx,
bounds: bounds,
drawables: drawables,
)
},)
}
// Apply function `fn` to all vertices of all
// elements in `body`.
//
// - body (element): Elements
// - fn (function): Callback of the form `vector => vector` that gets
// applied to all vertices
#let apply-transform-function(body, fn) = {
(ctx => {
let transform = ctx.transform
ctx.transform = matrix.ident()
let (ctx, drawables, bounds) = process.many(ctx, util.resolve-body(ctx, body))
ctx.transform = transform
drawables = drawables.map(d => {
d.segments = d.segments.map(s => (s.at(0), ..s.slice(1).map(fn)))
if d.type == "content" {
d.pos = fn(d.pos)
}
return d
})
return (
ctx: ctx,
drawables: drawable.apply-transform(ctx.transform, drawables),
)
},)
}
/// Set-up an orthographic projection environment.
///
/// This is a transformation matrix that rotates elements around
/// the x, the y and the z axis by the parameters given.
///
/// By default an isometric projection (x ≈ 35.264°, y = 45°) is set.
///
/// #example(```
/// ortho({
/// on-xz({
/// rect((-1,-1), (1,1))
/// })
/// })
/// ```)
///
/// - x (angle): X-axis rotation angle
/// - y (angle): Y-axis rotation angle
/// - z (angle): Z-axis rotation angle
/// - reset-transform (bool): Ignore the current transformation matrix
/// - body (element): Elements to draw
#let ortho(x: 35.264deg, y: 45deg, z: 0deg, reset-transform: false, body, name: none) = group(name: name, ctx => {
_projection(body, ortho-matrix(x, y, z),
ortho-projection-matrix, reset-transform: reset-transform)
})
/// Draw elements on the xy-plane with optional z value.
///
/// All vertices of all elements will be changed in the
/// following way: $vec(x, y, z_"argument")$, where $z_"argument"$
/// is the z-value given as argument.
///
/// #example(```
/// on-xy({
/// rect((-1, -1), (1, 1))
/// })
/// ```)
///
/// - z (number): Z coordinate for all coordinates
/// - body (element): Elements to draw
#let on-xy(z: 0, body) = get-ctx(ctx => {
let z = util.resolve-number(ctx, z)
apply-transform-function(body, pt => {
(pt.at(0), pt.at(1), z)
})
})
/// Draw elements on the xz-plane with optional y value.
///
/// All vertices of all elements will be changed in the
/// following way: $vec(x, y_"argument", y)$, where $y_"argument"$
/// is the y-value given as argument.
///
/// #example(```
/// on-xz({
/// rect((-1, -1), (1, 1))
/// })
/// ```)
///
/// - y (number): Y coordinate for all coordinates
/// - body (element): Elements to draw
#let on-xz(y: 0, body) = get-ctx(ctx => {
let y = util.resolve-number(ctx, y)
apply-transform-function(body, pt => {
(pt.at(0), y, pt.at(1))
})
})
/// Draw elements on the yz-plane with optional y value.
///
/// All vertices of all elements will be changed in the
/// following way: $vec(x_"argument", x, y)$, where $x_"argument"$
/// is the x-value given as argument.
///
/// #example(```
/// on-yz({
/// rect((-1, -1), (1, 1))
/// })
/// ```)
///
/// - x (number): X coordinate for all coordinates
/// - body (element): Elements to draw
#let on-yz(x: 0, body) = get-ctx(ctx => {
let x = util.resolve-number(ctx, x)
apply-transform-function(body, pt => {
(x, pt.at(0), pt.at(1))
})
})
|
https://github.com/vaucher-leo/template-tb-typst | https://raw.githubusercontent.com/vaucher-leo/template-tb-typst/main/template-HEIG-tb-EN.typ | typst | MIT License | // Template for Bachelor's thesis of the HEIG-VD
// Author: <NAME>
// Date: 07.03.2024
// Version: 1.0
//
// Brief:
// This template is based on the LaTex template of the HEIG-VD
// available on GitHub. It is just the styling with some modifications
// but the complex makefile with all the complicated things has not
// been done and will not be for now.
#let project(
title: "",
authors: (),
professor: "",
departement: "",
filiere: "",
orientation: "",
field: "",
date: none,
logoHeig: "images/HEIG-VD.svg",
logoHesso: "images/hes-so.svg",
signatureFile: "images/signature.png",
confidential: false,
body,
) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: none)
set par(justify: true)
set text(
font: "Source Sans Pro",
lang: "en",
size: 12pt,)
set heading(numbering: "1.1 ")
show heading.where(
level: 1
): it => [
#set text(weight: 600, size: 20pt)
#block(v(4.5cm) + it.body + v(1cm))
]
show heading.where(
level: 2
): it => [
#set text(weight: 600, size: 15pt)
#block(v(0cm) + it + v(0.5cm))
]
// Table of contents.
show outline.entry.where(
level: 1
): it => {
v(12pt, weak: true)
text(weight: 550 ,v(0.1cm) + it)
}
show outline.entry.where(
level: 2
): it => {
it
}
set outline(
fill: text(
weight: 350 ,
h(0.5em) + box(width: 1fr, repeat("." + h(0.3em))) + h(0.2em)
)
)
// Title page.
// Logo HEIG-VD
if logoHeig != none {
pad(
left: 0cm,
top: 0cm,
image(logoHeig, height: 2cm)
)
}
// Logo HES-SO
if logoHesso != none {
place(
(right + bottom),
move(
dy: 0.8cm,
image(logoHesso, height: 1cm)
)
)
}
// Title
v(3cm)
align(center, text(2em, weight: 600, title))
// Travail de Bachelor
v(-0.4cm)
align(center, text(1.1em, weight: 600, "Bachelor Thesis"))
// Confidentiel
v(4em)
if confidential {
align(center, text(1.1em, weight: 600, "CONFIDENTIAL"))
}
else {
align(center, text(1.1em, weight: 600, " "))
}
// Département
v(4em)
align(center, text(1em, weight: 370, departement + " Department"))
// Filière
align(center, text(1em, weight: 370, filiere + " Sector"))
// Orientation
align(center, text(1em, weight: 370, orientation + " Orientation"))
// Author
v(4.5em)
text(
1em,
weight: 370,
align(
center,
authors,
))
// Date
v(0.5em)
align(center, text(1em, weight: 370, date))
// Supervisor
v(3.5cm)
align(center, text(1em, weight: 370, "Supervised by :\n" + professor + " (HEIG-VD)"))
pagebreak(to: "odd")
// Preamble
set page(
numbering: "i",
number-align: center,
footer: locate(loc => {
let currentpage = loc.page()
if calc.odd(currentpage) [
#if confidential {
box(width: 1fr)
counter(page).display("i")
box(width: 1fr, align(right,text(size: 11pt, "CONFIDENTIAL")))
} else {
align(center, counter(page).display("i"))
}
] else [
#h(1fr)
]
})
)
counter(page).update(1)
heading(
numbering: none,
outlined: true,
"Preamble"
)
text("This Bachelor's thesis (hereinafter " + strong("TB") + ") is produced at the end of the course of study, with a view to obtaining the title of Bachelor of Science HES-SO in Engineering.\nAs an academic work, its content, without prejudging its value, does not engage the responsibility of the author, the Bachelor's thesis jury and the School.\nAny use, even partial, of this TB must respect copyright.")
v(4em)
move(
dx: 10cm,
text("HEIG-VD\nHead of Department")
)
v(6cm)
text("Yverdon-les-Bains, " + date)
pagebreak(to: "odd")
// Authentication
heading(
numbering: none,
outlined: true,
"Authentication"
)
text("I, " + authors + ", hereby certify that I produced this work on my own and did not use any sources other than those expressly mentioned.")
v(5cm)
move(
dx: 10cm,
text(authors)
)
move(
dx: 10cm,
dy: -0.3cm,
image("images/signature.png", height: 2cm)
)
v(4cm)
text("Yverdon-les-Bains, " + date)
// Reset Firt title margin
show heading.where(
level: 1
): it => [
#set text(weight: 600, size: 20pt)
#block(v(0cm) + it.body + v(0.5cm))
]
pagebreak(to: "odd")
// CDC
heading(
numbering: none,
outlined: true,
"Specifications"
)
include "page/Specifications.typ"
pagebreak(to: "odd")
// Resume
heading(
numbering: none,
outlined: true,
"Summary"
)
include "page/Summary.typ"
pagebreak(to: "odd")
v(1cm)
outline(depth: 3, indent: true, title: v(-1cm) + "Table of contents")
pagebreak(to: "odd")
// Rest of document
show heading.where(
level: 1
): it => [
#set text(weight: 600, size: 20pt)
#block(v(0.5cm) + it.body + v(0.5cm))
]
show heading.where(
level: 2
): it => [
#set text(weight: 600, size: 15pt)
#block(v(0cm) + it + v(0.5cm))
]
set page(
numbering: "1",
number-align: center,
footer: locate(loc => {
let currentpage = loc.page()
if confidential {
if calc.odd(currentpage) [
#box(width: 1fr)
#counter(page).display("1")
#box(width: 1fr, align(right,text(size: 11pt, "CONFIDENTIAL")))
] else [
#box(width: 1fr, align(left,text(size: 11pt, "CONFIDENTIAL")))
#counter(page).display("1")
#box(width: 1fr)
]
} else {
align(center, counter(page).display("1"))
}
})
)
counter(page).update(1)
body
} |
https://github.com/Cubik65536/VanierFLOSSDay24Talk | https://raw.githubusercontent.com/Cubik65536/VanierFLOSSDay24Talk/main/main.typ | typst | Other | // Get Polylux from the official package repository
#import "@preview/polylux:0.3.1": *
#import themes.university: *
// Make the paper dimensions fit for a presentation and the text larger
#set page(
paper: "presentation-16-9",
footer: [
#grid(
columns: (1fr, 20%),
rows: 1,
align(horizon + left)[
#text(size: 9pt)[
Content licensed under Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
]
],
align(right)[
#stack(
dir: ltr,
spacing: 5pt,
image("cc-icons-svg/cc.svg", height: 24pt),
image("cc-icons-svg/by.svg", height: 24pt),
image("cc-icons-svg/nc.svg", height: 24pt),
image("cc-icons-svg/nd.svg", height: 24pt)
)
],
)
]
)
#set text(size: 18pt)
#polylux-slide[
#align(horizon + left)[
= Free/Libre and Open Source Software\ #text(size: 48pt)[How to get started?]
]
#align(bottom + left)[
<NAME> (\@Cubik65536)
#text(size: 16pt)[
Wednesday, October 16#super[th], 2024 \
Montreal, Quebec, Canada
]
]
]
#set page(
footer: none
)
#polylux-slide[
== Why contributing to F.L.O.S.S?
- Help improving the software - that *you're using*.
- Help others.
- Gain experience:
- Coding
- Writing
- Team Working
- Designing
- Get Paid
]
#focus-slide[
#align(center)[
"How do I get started in contributing?"
based on my _own_ experience
]
]
#matrix-slide[
= “What can I do?”
]
#polylux-slide[
== What kind of contributions can you make?
- Code
]
#focus-slide[
#align(center)[
"Code is only one part of open source."
]
#align(right)[
#text(size: 12pt)[
By <NAME>, posted on _IT'S FOSS_.\
https://itsfoss.com/hacktoberfest-guide/
]
]
]
#polylux-slide[
== What kind of contributions can you make?
- Code
- Test
- Translate
- Support
- Document
- Promote
- Design
#align(right)[
#text(size: 12pt)[
Contribute - Participate - Mozilla Thunderbird Project Website\
https://www.thunderbird.net/en-US/participate/
]
]
]
#matrix-slide[
= "How do I get started?"
]
#matrix-slide[
== 1. Know the project.
]
#polylux-slide[
== Know the project
Ideally, you should be familiar with the project you want to contribute to before you start contributing. (You are using the software.)
What you can do:
- Read the *README* file.\
Usually, the README file contains information about the project, the purpose/goal of the project, and how to get started with the project.
- Join the project's *mailing list* or *chat room* (if there is one), and talk to the maintainers and other users.
- Take a look at the project's *LICENSE*.\
The license tells you what you can and cannot do with the project's code (and/or other works).
Does the license align with your values? Do you want your work to be put under that license?
]
#matrix-slide[
== 2. Get to know how to contribute.
]
#polylux-slide[
== Get to know how to contribute
Is it very _*important*_ to know the contribute guidelines of the project you want to contribute to.
What you can do:
- Read the *CONTRIBUTING* file.\
Usually, the CONTRIBUTING file contains information about how to contribute to the project.\
e.g. how to report a bug (info you need to submit, format to follow, etc.), how to configure your development environment, the project code style, how to submit a patch, who to reach out if you need help, etc.
- Read the project's *code of conduct*.\
It is sometimes included in the CONTRIBUTING file, or it may be a separate file.\
The code of conduct contains the rules you need to follow when you are being a part of the community of the project. Not following the code of conduct can lead to some serious consequences.
- Peek at _past contributions_ and source codes.
]
#matrix-slide[
== 3. Contribute.
]
#polylux-slide[
- Get the beta (testing) version of the software, and test it. If you find an issue, report it.
- Translate the software or its documentation to your language.
- Find an issue (bug report, feature request, or generally a task to work on) and work on it.
- This can be code related, or not code related (e.g. documentation, design, etc.).
- Find a small-sized issue (or tagged with `beginner`, `good-first-issue`, etc.) to start with. This will help you get familiar with the project's existing works and the contribution process.
- Talk to the maintainers and other contributors.\
They can help you get started, helping you choose something to work on.
]
#matrix-slide[
= "Where do I get started?"
]
#polylux-slide[
Like I said, ideally you should contribute to a software/library that you are using.
\
However, if you don't have a specific project in mind, here are some places you can look at:
- #text(blue)[#link("https://github.com/MunGell/awesome-for-beginners")[The `awesome-for-beginners` repository on GitHub]], which has a list of projects that are beginner-friendly.
- Events like #text(blue)[#link("https://hacktoberfest.com/")[Hacktoberfest]], which encourages people to contribute to open source projects. There will be projects that accepts `hacktoberfest` contributions, and by contributing to them, you can get some swags/merchandise.
]
#set page(
paper: "presentation-16-9",
footer: [
#grid(
columns: (1fr, 20%),
rows: 1,
align(horizon + left)[
#text(size: 9pt)[
Content licensed under Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
]
],
align(right)[
#stack(
dir: ltr,
spacing: 5pt,
image("cc-icons-svg/cc.svg", height: 24pt),
image("cc-icons-svg/by.svg", height: 24pt),
image("cc-icons-svg/nc.svg", height: 24pt),
image("cc-icons-svg/nd.svg", height: 24pt)
)
],
)
]
)
#set text(size: 32pt)
#matrix-slide[
= Good Luck, Have Fun!
]
|
https://github.com/TJ-CSCCG/tongji-slides-typst | https://raw.githubusercontent.com/TJ-CSCCG/tongji-slides-typst/main/theme/university.typ | typst | MIT License | #import "logic.typ"
#import "utils.typ"
// University theme
//
// Originally contributed by <NAME> - https://github.com/drupol
//
// Please feel free to improve this theme
// by submitting a PR in https://github.com/andreasKroepelin/typst-slides
#let uni-colors = state("uni-colors", (:))
#let uni-short-title = state("uni-short-title", none)
#let uni-short-author = state("uni-short-author", none)
#let uni-short-date = state("uni-short-date", none)
#let uni-progress-bar = state("uni-progress-bar", true)
#let university-theme(
aspect-ratio: "16-9", short-title: none, short-author: none, short-date: none, color-a: rgb("#0C6291"), color-b: rgb("#A63446"), color-c: rgb("#FBFEF9"), progress-bar: true, body,
) = {
set page(
paper: "presentation-" + aspect-ratio, margin: 0em, header: none, footer: none,
)
set text(size: 25pt)
show footnote.entry: set text(size: .6em)
uni-progress-bar.update(progress-bar)
uni-colors.update((a: color-a, b: color-b, c: color-c))
uni-short-title.update(short-title)
uni-short-author.update(short-author)
uni-short-date.update(short-date)
body
}
#let title-slide(
title: [], subtitle: none, authors: (), institution-name: "University", date: none, logo: none, footer: none,
) = {
let authors = if type(authors) == "array" { authors } else { (authors,) }
let footer = {
set text(size: 10pt)
set align(center + bottom)
let cell(fill: none, it) = rect(
width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none, align(horizon, text(fill: white, it)),
)
if footer != none {
footer
} else {
locate(
loc => {
let colors = uni-colors.at(loc)
show: block.with(width: 100%, height: auto, fill: colors.a)
grid(
columns: (90%, 10%), rows: (1.5em, auto), cell(fill: colors.b, none),
// cell(fill: colors.b,),
// cell(fill: colors.b),
// // cell(uni-short-title.display()),
// // cell(uni-short-date.display()),
cell(logic.logical-slide.display() + [~/~] + utils.last-slide-number),
)
},
)
}
}
let content = locate(
loc => {
let colors = uni-colors.at(loc)
if logo != none {
align(right, logo)
}
align(
center + horizon, {
block(inset: 0em, breakable: false, {
text(size: 2em, fill: colors.a, strong(title))
if subtitle != none {
parbreak()
text(size: 1.2em, fill: colors.a, subtitle)
}
})
set text(size: .8em)
grid(
columns: (1fr,) * calc.min(authors.len(), 3), column-gutter: 1em, row-gutter: 1em, ..authors.map(author => text(fill: black, author)),
)
v(1em)
if institution-name != none {
parbreak()
text(size: .9em, institution-name)
}
if date != none {
parbreak()
text(size: .8em, date)
}
if footer != none {
parbreak()
text(size: .8em, footer)
}
},
)
},
)
set page(
// margin: ( top: 2em, bottom: 1em, x: 0em ),
// header: header,
footer: footer, footer-descent: 0em,
// header-ascent: .6em,
)
logic.polylux-slide(content)
}
#let slide(
title: none, header: none, header-pic: none, footer: none, new-section: none, body,
) = {
let body = pad(x: 2em, y: .5em, body)
let progress-barline = locate(
loc => {
if uni-progress-bar.at(loc) {
let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false)
let colors = uni-colors.at(loc)
utils.polylux-progress(
ratio => {
grid(
rows: 2pt, columns: (ratio * 100%, 1fr), cell(fill: colors.a), cell(fill: colors.b),
)
},
)
} else { [] }
},
)
let header-text = {
if header != none {
header
} else if title != none {
if new-section != none {
utils.register-section(new-section)
}
locate(
loc => {
let colors = uni-colors.at(loc)
block(
fill: colors.c, inset: (x: .5em), grid(
columns: (60%, 40%), align(top + left, heading(level: 2, text(fill: colors.a, title))), align(top + right, text(fill: colors.a.lighten(65%), utils.current-section)),
),
)
},
)
} else { [] }
}
let header-pic = {
if header-pic != none {
figure(
image("./img/E9B78952-B8E5-49B8-9326-A0AD28C9A337_1_105_c.jpeg"), numbering: none,
)
} else {
// none
figure(
image("./img/E9B78952-B8E5-49B8-9326-A0AD28C9A337_1_105_c.jpeg", width: auto), placement: bottom, numbering: none,
)
}
}
let cell = rect.with(width: auto, height: auto, stroke: none)
let specify_cell = rect.with(width: 100%, height: 200%, stroke: none)
let header = {
// set align(top + right)
grid(
rows: (60%, 80%), cell[], cell(
grid(
columns: (89%, 10%, 1%),
// row-gutter: 3mm,
// progress-barline,
// header-text,
specify_cell(
align(
left + horizon, text(
font: "Zapfino", fill: rgb(21, 94, 169), size: 13pt, "Tongji University",
),
),
), specify_cell(header-pic), cell[],
// cell[
// #set align(right)
// #figure(image("pic/E9B78952-B8E5-49B8-9326-A0AD28C9A337_1_105_c.jpeg"))
// ],
),
),
)
}
// let footer = {
// set text(size: 10pt)
// set align(center + bottom)
// let cell(fill: none, it) = rect(
// width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none,
// align(horizon, text(fill: white, it))
// )
// if footer != none {
// footer
// } else {
// locate( loc => {
// let colors = uni-colors.at(loc)
// show: block.with(width: 100%, height: auto, fill: colors.b)
// grid(
// columns: (25%, 1fr, 15%, 10%),
// rows: (1.5em, auto),
// cell(fill: colors.a,none),
// cell(fill: colors.a,
// // uni-short-title.display()
// none),
// cell(fill: colors.a,
// // uni-short-date.display()
// none),
// cell(logic.logical-slide.display() + [~/~] + utils.last-slide-number)
// )
// })
// }
// }
let footer = {
set text(size: 10pt)
set align(center + bottom)
let cell(fill: none, it) = rect(
width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none, align(horizon, text(fill: white, it)),
)
if footer != none {
footer
} else {
locate(
loc => {
let colors = uni-colors.at(loc)
show: block.with(width: 100%, height: auto, fill: colors.a)
grid(
columns: (90%, 10%), rows: (1.5em, auto), cell(fill: colors.b, none),
// cell(fill: colors.b,),
// cell(fill: colors.b),
// // cell(uni-short-title.display()),
// // cell(uni-short-date.display()),
cell(logic.logical-slide.display() + [~/~] + utils.last-slide-number),
)
},
)
}
}
set page(
margin: (top: 3.5em, bottom: 1em, x: 0em), header: header, footer: footer, footer-descent: 0em, header-ascent: .6em,
)
logic.polylux-slide(body)
}
#let focus-slide(background-color: none, background-img: none, footer: none, body) = {
let background-color = if background-img == none and background-color == none {
rgb("#0C6291")
} else {
background-color
}
// let footer = {
// set text(size: 10pt)
// set align(center + bottom)
// let cell(fill: none, it) = rect(
// width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none,
// align(horizon, text(fill: white, it))
// )
// if footer != none {
// footer
// } else {
// locate( loc => {
// let colors = uni-colors.at(loc)
// show: block.with(width: 100%, height: auto, fill: colors.a)
// grid(
// columns: (90%, 10%),
// rows: (1.5em, auto),
// cell(fill: colors.b, none),
// // cell(fill: colors.b,),
// // cell(fill: colors.b),
// // // cell(uni-short-title.display()),
// // // cell(uni-short-date.display()),
// cell(logic.logical-slide.display() + [~/~] + utils.last-slide-number)
// )
// })
// }
// }
set page(fill: background-color, margin: 1em) if background-color != none
set page(background: {
set image(fit: "stretch", width: 100%, height: 100%)
background-img
}, margin: 1em) if background-img != none
set text(fill: white, size: 2em)
logic.polylux-slide(align(horizon, body))
}
#let matrix-slide(columns: none, rows: none, footer: none, ..bodies) = {
let bodies = bodies.pos()
let columns = if type(columns) == "integer" {
(1fr,) * columns
} else if columns == none {
(1fr,) * bodies.len()
} else {
columns
}
let num-cols = columns.len()
let rows = if type(rows) == "integer" {
(1fr,) * rows
} else if rows == none {
let quotient = calc.quo(bodies.len(), num-cols)
let correction = if calc.rem(bodies.len(), num-cols) == 0 { 0 } else { 1 }
(1fr,) * (quotient + correction)
} else {
rows
}
let num-rows = rows.len()
if num-rows * num-cols < bodies.len() {
panic(
"number of rows (" + str(num-rows) + ") * number of columns (" + str(num-cols) + ") must at least be number of content arguments (" + str(bodies.len()) + ")",
)
}
let cart-idx(i) = (calc.quo(i, num-cols), calc.rem(i, num-cols))
let color-body(idx-body) = {
let (idx, body) = idx-body
let (row, col) = cart-idx(idx)
let color = if calc.even(row + col) { white } else { white }
set align(center + horizon)
rect(inset: .5em, width: 100%, height: 90%, fill: color, body)
}
let footer = {
set text(size: 10pt)
set align(center + bottom)
let cell(fill: none, it) = rect(
width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none, align(horizon, text(fill: white, it)),
)
if footer != none {
footer
} else {
locate(
loc => {
let colors = uni-colors.at(loc)
show: block.with(width: 105%, height: auto, fill: colors.a)
grid(
columns: (90%, 10%), rows: (1.5em, auto), cell(fill: colors.b, none),
// cell(fill: colors.b,),
// cell(fill: colors.b),
// // cell(uni-short-title.display()),
// // cell(uni-short-date.display()),
cell(logic.logical-slide.display() + [~/~] + utils.last-slide-number),
)
},
)
}
}
let header-pic = {
figure(
image("./img/E9B78952-B8E5-49B8-9326-A0AD28C9A337_1_105_c.jpeg"), numbering: none,
)
}
let content = grid(
columns: columns, rows: rows, gutter: 0pt, ..bodies.enumerate().map(color-body),
)
let cell = rect.with(width: 100%, height: 100%, stroke: none)
let specify_cell = rect.with(width: 100%, height: 111%, stroke: none)
// let mainbody = rect(width: 100%,height: 90%,stroke: none,content)
let mainbody = grid(
rows: (12%, 78%, 10%), cell(
grid(
columns: (90%, 10%), cell(
align(
left + horizon, text(
font: "Zapfino", fill: rgb(21, 94, 169), size: 13pt, "Tongji University",
),
),
), cell(header-pic),
),
), cell(content), specify_cell(footer),
)
logic.polylux-slide(mainbody)
}
|
https://github.com/piepert/logik-tutorium-wise2024-2025 | https://raw.githubusercontent.com/piepert/logik-tutorium-wise2024-2025/main/src/ablaufplan.typ | typst | Creative Commons Zero v1.0 Universal | #import "/src/templates/exercise.typ": *
#show: project.with(
title: [
Ablaufplan für das Logik-Tutorium
],
document-title: [
Ablaufplan für das Logik-Tutorium
],
abstract: [
In diesem Tutorium lernen Sie die grundlagen des logischen Denkens für die Analyse philosophischer Argumente, damit sie in zukünftigen Hausarbeiten und Seminaren die Positionen philosophischer Texte kriterienbasiert analysieren und beurteilen können.
Das Tutorium ist interaktiv und soll sie dazu anleiten, selbständig zu arbeiten und sich im universitären Lernen zurechtzufinden. Es wird Material angeboten, um die Ziele im Selbststudium zu erreichen und zu festigen.#footnote[Das Skript wird zitiert mit "Skript p. 94 / S. 181." Die Abkürzung "p." meint die PDF-Seite, also "$x$ / 115" und "S." steht für die Buchseiten ab p. 16.] Jeder Abschnitt wird mit einer Lernevaluation (LEV) abgeschlossen, mit der Sie prüfen können, auf welchem Stand Sie sich befinden.
Zum erfolgreichen Aneignen der Inhalte sind zu jeder Sitzung Lernziele gegeben, die sie sich im Laufe des Semesters aneignen müssen, um das Modul zu bestehen. Es werden _nicht_ alle Lernziele in den einzelnen Sitzungen vollumfänglich behandelt. Nutzen Sie die Materialien im Selbststudium, um fehlendes Wissen zu ergänzen und die nötigen Fähigkeiten zu entwickeln.
])
#show table.cell: set text(size: 0.75em)
#include "raw-plan.typ" |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/list-02.typ | typst | Other | - Level 1
- Level #[
2 through content block
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/outrageous/0.1.0/examples/rush.typ | typst | Apache License 2.0 | //! This example replicates the outline of the paper on the rush programming language.
//! See https://paper.rush-lang.de
#import "../outrageous.typ"
#set text(font: "New Computer Modern")
#set page(numbering: "1")
// only do numbering for the first three levels, in the style `1.`
// note: we have to set the style to `1.1` so that references don't
// include the trailing dot, and then manually add the dot back
// for headings and ToC entries
#set heading(numbering: (..nums) => {
let nums = nums.pos()
if nums.len() < 4 {
numbering("1.1", ..nums)
}
})
#show heading: it => block({
// sans font for headings
set text(font: "Noto Sans")
if it.numbering != none {
numbering(it.numbering, ..counter(heading).at(it.location()))
// add the trailing dot here
if it.level < 4 { [. ] }
}
it.body
})
// level 1 headings start new pages and have some vertical spacing
#show heading.where(level: 1): it => {
set text(size: 25pt)
pagebreak(weak: true)
v(1cm)
it
v(1cm)
}
// references to level 1 headings should say 'Chapter'
#set heading(supplement: it => if it.level == 1 { [Chapter] } else { [Section] })
// outlines are indented and only show the first four levels
#set outline(indent: auto, depth: 4)
#{
// only for ToC: default outrageous-toc styling, but we have to add the trailing dot
// to the numbering, and therefore also have to add some more indent
show outline.entry: outrageous.show-entry.with(body-transform: (lvl, body) => {
// all this just to add a dot after the numbering :/
if "children" in body.fields() {
let (number, space, ..text) = body.children
style(styles => {
h(measure([.], styles).width * (lvl - 1))
if not number.at("text", default: "").starts-with(regex("\d")) {
// if `number` isn't actually a number (i.e. when there is no number),
// then `space` is part of the text
[#((space,) + text).join()]
} else {
[#number. #text.join()]
}
})
}
})
outline()
}
// figure numbering per chapter
#show heading.where(level: 1): it => {
counter(figure.where(kind: "chapfigure-" + repr(image))).update(0)
counter(figure.where(kind: "chapfigure-" + repr(table))).update(0)
counter(figure.where(kind: "chapfigure-" + repr(raw))).update(0)
it
}
#show figure: it => {
if type(it.kind) == str and it.kind.starts-with("chapfigure-") {
it
} else {
let chapter = counter(heading.where(level: 1)).at(it.location()).first()
let dic = it.fields()
let _ = if "body" in dic { dic.remove("body") }
let _ = if "label" in dic { dic.remove("label") }
let _ = if "counter" in dic { dic.remove("counter") }
let fig = figure(
it.body,
..dic,
numbering: n => numbering("1.1", chapter, n),
kind: "chapfigure-" + if type(it.kind) == str { it.kind } else { repr(it.kind) },
)
if it.has("label") {
let new-label = if it.kind == table { "tbl" } else if it.kind == raw { "lst" } else { "fig" }
new-label += ":" + str(it.label)
[#fig #label(new-label)]
} else { fig }
}
}
#show outline.entry: outrageous.show-entry.with(..outrageous.presets.outrageous-figures)
#outline(title: [List of Figures], target: figure.where(kind: "chapfigure-image"))
#{
show outline.entry: outrageous.show-entry.with(
..outrageous.presets.outrageous-figures,
body-transform: outrageous.presets.outrageous-figures.body-transform.with(
// use a different state key for each "list of x" to separately calculate alignment for each
state-key: "outline-table-numbering-max-width",
)
)
// override the show rule to not insert a page break
show heading.where(level: 1): it => {
v(1.5cm)
text(size: 25pt, font: "Noto Sans", it.body)
v(1cm)
}
outline(title: [List of Tables], target: figure.where(kind: "chapfigure-table"))
}
#show outline.entry: outrageous.show-entry.with(
..outrageous.presets.outrageous-figures,
body-transform: outrageous.presets.outrageous-figures.body-transform.with(
state-key: "outline-listing-numbering-max-width",
)
)
#outline(title: [List of Listings], target: figure.where(kind: "chapfigure-raw"))
// don't allow newlines inside "RISC-V"
#show "RISC-V": box
#counter(page).update(1)
= Introduction
#counter(page).update(1)
See @my-chapter, @my-section, @my-subsection, @fig:my-figure, @tbl:my-table, and @lst:my-listing.
== Stages of Compilation
#pagebreak()
#figure([a], caption: [Steps of compilation.])
#figure([a], caption: [Steps of compilation. (altered)])
#pagebreak()
== The rush Programming Language
#figure([```rush fn fib(n: int) -> int {}```], caption: [Generating Fibonacci numbers using rush.]) <my-listing>
=== Features
#pagebreak()
#figure(table(), caption: [Lines of code of the project's components in commit '`f8b9b9a`'.])
#pagebreak()
#figure(table(), caption: [Most important features of the rush programming language.])
#figure(table(), caption: [Data types in the rush programming language.]) <my-table>
#pagebreak()
= Analyzing the Source <my-chapter>
== Lexical and Syntactical Analysis <my-section>
=== Formal Syntactical Definition by a Grammer <my-subsection>
#figure([```rust fn main() {}```], caption: [Grammar for basic arithmetic in EBNF notation.])
=== Grouping Characters Into Tokens
#pagebreak()
#figure([```rust fn main() {}```], caption: [The rush '`Lexer`' struct definition.])
#figure(table(), caption: [Advancing window of a lexer.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Simplified '`Token`' struct definition.])
=== Constructing a Tree
#figure([a], caption: [Abstract syntax tree for '`1+2**3`'.]) <my-figure>
#pagebreak()
#figure(table(), caption: [Mapping from EBNF grammar to Rust type definitions.])
==== Operator Precedence
#figure([```rust fn main() {}```], caption: [Example language a traditional LL(1) parser cannot parse.])
#pagebreak()
==== Pratt Parsing
#figure([a], caption: [Abstract syntax tree for '`1+2**3`' using Pratt parsing.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Pratt-parser: Implementation for token precedences.])
#figure([```rust fn main() {}```], caption: [Pratt-parser: Implementation for expressions.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Pratt-parser: Implementation for grouped expressions.])
#figure([```rust fn main() {}```], caption: [Pratt-parser: Implementation for infix-expressions.])
#figure([a], caption: [Token precedences for the input '`(1+2*3)/4**5`'.])
#pagebreak()
==== Parser Generators
== Semantic Analysis
=== Defining the Semantics of a Programming Language
=== The Semantic Analyzer
#pagebreak()
#figure([```rust fn main() {}```], caption: [A rush program which adds two integers.])
==== Implementation
#pagebreak()
#figure([```rust fn main() {}```], caption: [Fields of the '`Analyzer`' struct.])
#figure([```rust fn main() {}```], caption: [Output when compiling an invalid rush program.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: Validation of the '`main`' function's signature.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: The '`let_stmt`' method.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: Analysis of expressions during semantic analysis.])
#figure([```rust fn main() {}```], caption: [Analyzer: Obtaining the type of expressions.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: Validation of argument type compatibility.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: Determining whether an expression is constant.])
==== Early Optimizations
#figure([```rust fn main() {}```], caption: [Redundant '`while`' loop inside a rush program.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Analyzer: Loop optimization.])
#figure([a], caption: [How semantic analysis affects the abstract syntax tree.])
#pagebreak()
= Interpreting the Program
== Tree-Walking Interpreters
#figure([```rust fn main() {}```], caption: [Tree-walking interpreter: Type definitions.])
#pagebreak()
=== Implementation
#figure([```rust fn main() {}```], caption: [Tree-walking interpreter: '`Value`' and '`InterruptKind`' definitions.])
=== How the Interpreter Executes a Program
#figure([a], caption: [Call stack at the point of processing the '`return`' statement.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Tree-walking interpreter: Beginning of execution.])
#figure([```rust fn main() {}```], caption: [Tree-walking interpreter: Calling of functions.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Example rush program.])
=== Supporting Pointers
#pagebreak()
== Using a Virtual Machine
=== Defining a Virtual Machine
#pagebreak()
#figure([```rust fn main() {}```], caption: [Struct definition of the VM.])
=== Register-Based and Stack-Based Machines
=== The rush Virtual Machine
#pagebreak()
#figure([```rust fn main() {}```], caption: [Minimal pointer example in rush.])
#figure([a], caption: [Linear memory of the rush VM.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [VM instructions for the minimal pointer example.])
=== How the Virtual Machine Executes a rush Program
#figure([```rust fn main() {}```], caption: [A recursive rush program.]) <recursive-rush-program>
#figure([```rust fn main() {}```], caption: [Struct definition of a '`CallFrame`'.])
#pagebreak()
#figure([a], caption: [Example call stack of the rush VM.])
#figure([```rust fn main() {}```], caption: [VM instructions matching the AST in @fig:ast-and-vm-instructions.])
#pagebreak()
=== Fetch-Decode-Execute Cycle of the VM
#figure([```rust fn main() {}```], caption: [The '`run`' method of the rush VM.])
#pagebreak()
#figure([```rust fn main() {}```], caption: [Parts of the '`run_instruction`' method of the rush VM.])
#pagebreak()
=== Comparing the VM to the Tree-Walking Interpreter
#figure([a], caption: [AST and VM instructions of the recursive rush program in @lst:recursive-rush-program.]) <ast-and-vm-instructions>
#pagebreak()
#pagebreak()
= Compiling to High-Level Targets
== How a Compiler Translates the AST
#figure([a], caption: [Abstract syntax tree for '`1 + 2 < 4`'.])
#pagebreak()
== The Compiler Targeting the rush VM
#pagebreak()
#pagebreak()
#pagebreak()
#pagebreak()
== Compilation to WebAssembly
=== WebAssembly Modules
#pagebreak()
#pagebreak()
=== The WebAssembly System Interface
#pagebreak()
=== Implementation
#pagebreak()
==== Function Calls
==== Logical Operators
#pagebreak()
=== Considering an Example rush Program
#pagebreak()
#pagebreak()
== Using LLVM for Code Generation
=== The Role of LLVM in a Compiler
#figure([a], caption: [Steps of compilation when using LLVM.])
=== The LLVM Intermediate Representation
#pagebreak()
==== Structure of a Compiled rush Program
#pagebreak()
#pagebreak()
=== The rush Compiler Using LLVM
#pagebreak()
#pagebreak()
#pagebreak()
#pagebreak()
#pagebreak()
=== Final Code Generation: The Linker
#figure([a], caption: [The linking process.])
#pagebreak()
=== Conclusions
#pagebreak()
== Transpilers
#pagebreak()
= Compiling to Low-Level Targets
== Low-Level Programming Concepts
=== Sections of an ELF File
=== Assemblers and Assembly Language
#pagebreak()
#figure([a], caption: [Level of abstraction provided by assembly.])
=== Registers
#pagebreak()
#figure([a], caption: [Relationship between registers, memory, and the CPU.])
#pagebreak()
=== Using Memory: The Stack
==== Alignment
#figure([a], caption: [Examples of memory alignment.])
#pagebreak()
=== Calling Conventions
#pagebreak()
=== Referencing Variables Using Pointers
#pagebreak()
#pagebreak()
== RISC-V: Compiling to a RISC Architecture
#figure(table(), caption: [Registers of the RISC-V architecture.])
=== Register Layout
#pagebreak()
=== Memory Access Through the Stack
#figure([a], caption: [Stack layout of the RISC-V architecture.])
=== Calling Convention
#pagebreak()
=== The Core Library
#pagebreak()
=== RISC-V Assembly
#pagebreak()
#pagebreak()
=== Supporting Pointers
=== Implementation
==== Struct Fields
#pagebreak()
#pagebreak()
==== Data Flow and Register Allocation
#pagebreak()
#figure([a], caption: [Simplified integer register pool of the RISC-V rush compiler.])
#pagebreak()
#pagebreak()
#pagebreak()
==== Functions
#pagebreak()
==== Let Statements
#pagebreak()
==== Function Calls and Returns
#pagebreak()
#pagebreak()
#pagebreak()
==== Loops
#pagebreak()
#pagebreak()
== x86_64: Compiling to a CISC Architecture
=== x64 Assembly
#pagebreak()
=== Registers
#pagebreak()
#figure(table(), caption: [General purpose registers of the x64 architecture.])
#pagebreak()
=== Stack Layout and Calling Convention
#figure([a], caption: [Stack layout of the x64 architecture.])
=== Implementation
#pagebreak()
==== Struct Fields
#pagebreak()
==== Memory Management
==== Register Allocation
#pagebreak()
==== Functions
#pagebreak()
==== Function Calls
==== Control Flow
#figure([a], caption: [Structure of if-expressions in assembly.])
#pagebreak()
#pagebreak()
==== Integer Division and Float Comparisons
#pagebreak()
#pagebreak()
==== Pointers
#pagebreak()
== Conclusion: RISC vs. CISC Architectures
#pagebreak()
= Final Thoughts and Conclusions
#pagebreak()
#pagebreak()
#set heading(numbering: none)
= List of Figures
= List of Tables
#pagebreak()
= List of Listings
#pagebreak()
#pagebreak()
#pagebreak()
= Bibliography
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/accent-03.typ | typst | Other | // Test accent bounds.
$sqrt(tilde(T)) + hat(f)/hat(g)$
|
https://github.com/dikkadev/typst-statastic | https://raw.githubusercontent.com/dikkadev/typst-statastic/main/dbg.typ | typst | The Unlicense | #import "lib.typ": *
= Statastic Package Test with Larger Dataset
This document showcases the features of the `statastic` package using a larger dataset.
= Data Preparation
We will use the following dataset:
#let data = (
(1, 2.5),
(2, 3.6),
(3, 5.1),
(4, 7.4),
(5, 11.0),
(6, 15.8),
(7, 22.5),
(8, 31.2),
(9, 41.7),
(10, 54.0),
(11, 68.0),
(12, 84.6),
(13, 103.8),
(14, 125.6),
(15, 150.0),
)
#data
The dataset contains two columns:
- Column 0: Independent variable `x`
- Column 1: Dependent variable `y`
= Statistical Measures
== Average
- Average of `x`: #avg(data, 0)
- Average of `y`: #avg(data, 1)
== Median
- Median of `x`: #median(data, 0)
- Median of `y`: #median(data, 1)
== Variance
- Variance of `x`: #var(data, 0)
- Variance of `y`: #var(data, 1)
== Standard Deviation
- Standard Deviation of `x`: #std(data, 0)
- Standard Deviation of `y`: #std(data, 1)
= Regression Analyses
We will perform different regression analyses on the dataset to find the relationship between `x` and `y`.
== Linear Regression
#let linRegResult = linearRegression(data, 0, 1)
- [*Slope*]: #linRegResult.slope
- [*Intercept*]: #linRegResult.intercept
- [*R-squared*]: #linRegResult.r_squared
== Quadratic Regression
#let quadRegResult = quadraticRegression(data, 0, 1)
The coefficients are:
- [*a*] (quadratic term): #quadRegResult.a
- [*b*] (linear term): #quadRegResult.b
- [*c*] (constant term): #quadRegResult.c
- [*R-squared*]: #quadRegResult.r_squared
== Exponential Regression
#let expRegResult = exponentialRegression(data, 0, 1)
The coefficients are:
- [*a*]: #expRegResult.a
- [*b*]: #expRegResult.b
- [*R-squared*]: #expRegResult.r_squared
== Logarithmic Regression
#let logRegResult = logarithmicRegression(data, 0, 1)
The coefficients are:
- [*a*]: #logRegResult.a
- [*b*]: #logRegResult.b
- [*R-squared*]: #logRegResult.r_squared
== Power Regression
#let powRegResult = powerRegression(data, 0, 1)
The coefficients are:
- [*a*]: #powRegResult.a
- [*b*]: #powRegResult.b
- [*R-squared*]: #powRegResult.r_squared
= Conclusion
This test demonstrates the functionalities provided by the `statastic` package for statistical analysis and various regression models in Typst.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/src/lib.typ | typst | Apache License 2.0 | #let version = version(0, 1, 0)
#import "circuit.typ": circuit
#import "element.typ"
#import "gates.typ"
#import "util.typ"
#import "wire.typ" |
https://github.com/FlorentCLMichel/quetta | https://raw.githubusercontent.com/FlorentCLMichel/quetta/main/src/quenya.typ | typst | MIT License | // Impleentation of the Quenya Mode
#import "tengwar_proto.typ": *
#let map-quenya = (
th : sule, Th : sule,
"£t" : tinco-alt, "£T" : tinco-alt,
t : tinco, T : tinco,
"£nd" : ando-alt, "£Nd" : ando-alt,
nd : ando, Nd : ando,
"£ss" : esse-alt, "£Ss" : esse-alt,
"£s" : silme-alt, "£S" : silme-alt,
ss : esse, Ss : esse,
s : silme, S : silme,
nt : anto, Nt : anto,
"£ngw" : ungwe-alt, "£Ngw" : ungwe-alt,
nqu : unque, Nqu : unque,
ngw : ungwe, Ngw : ungwe,
nkw : unque, Nkw : unque,
ñw : nwalme, Ñw : nwalme,
"£ng" : anga-alt, "£Ng" : anga-alt,
ng : anga, Ng : anga,
nc : anca, Nc : anca,
nq : anca, Nq : anca,
nk : anca, Nk : anca,
"£n" : noldo, "£N" : noldo,
ñ : noldo, Ñ : noldo,
n : numen, N : numen,
rd : arda, Rd : arda,
"£r" : romen, "£R" : romen,
r : ore, R : ore,
"£p" : parma-alt, "£P" : parma-alt,
p : parma, P : parma,
"£mb" : umbar-alt, "£Mb" : umbar-alt,
mb : umbar, Mb : umbar,
f : formen, F : formen,
mp : ampa, Mp : ampa,
m : malta, M : malta,
v : vala, V : vala,
"£qu" : quesse-alt, "£Qu" : quesse-alt,
qu : quesse, Qu : quesse,
"£kw" : quesse, "£Kw" : quesse,
kw : quesse-alt, Kw : quesse-alt,
"£k" : calma, "£K" : calma,
k : calma-alt, K : calma-alt,
"£c" : calma-alt, "£C" : calma-alt,
c : calma, C : calma,
hw : hwesta, Hw : hwesta,
"£h" : hyarmen, "£H" : hyarmen,
h : aha, H : aha,
y : anna, Y : anna,
ld : alda, Ld : alda,
"£l" : lambe-alt, "£L" : lambe-alt,
l : lambe, L : lambe,
w : wilya, W : wilya,
x : calma + silme, X : calma + silme,
ai : iglide + tehta-a, Ai : iglide + tehta-a,
ei : iglide + tehta-e, Ei : iglide + tehta-e,
oi : iglide + tehta-o, Oi : iglide + tehta-o,
ui : iglide + tehta-u, Ui : iglide + tehta-u,
au : uglide + tehta-a, Au : uglide + tehta-a,
eu : uglide + tehta-e, Eu : uglide + tehta-e,
iu : uglide + tehta-i, Iu : uglide + tehta-i,
ou : uglide + tehta-o, Ou : uglide + tehta-o,
a : tehta-a, A : tehta-a,
e : tehta-e, E : tehta-e,
i : tehta-i, I : tehta-i,
o : tehta-o, O : tehta-o,
u : tehta-u, U : tehta-u,
á : carrier-j + tehta-a, Á : carrier-j + tehta-a,
é : carrier-j + tehta-e, É : carrier-j + tehta-e,
í : carrier-j + tehta-i, Í : carrier-j + tehta-i,
ó : carrier-j + tehta-o, Ó : carrier-j + tehta-o,
ú : carrier-j + tehta-u, Ú : carrier-j + tehta-u,
ä : tehta-a, Ä : tehta-a,
ë : tehta-e, Ë : tehta-e,
ï : tehta-i, Ï : tehta-i,
ö : tehta-o, Ö : tehta-o,
ü : tehta-u, Ü : tehta-u,
ô : tehta-oo, Ô : tehta-oo,
"," : comma,
"." : period,
"--" : em-dash,
"—" : em-dash,
"-" : en-dash,
"!" : exclamationmark,
"(" : l-paren,
")" : r-paren,
"" : tilde,
"/" : slash,
"<" : "\u{ffff}«\u{fffe}",
"«" : "\u{ffff}«\u{fffe}",
">" : "\u{ffff}»\u{fffe}",
"»" : "\u{ffff}»\u{fffe}",
"|" : "\u{fffd}",
"?" : questionmark,
)
#let quenya-str(txt, style: "normal") = {
// Set the font to Tengwar Annatar
set text(font: tengwar-font, fallback: false)
// Extract numbers, convert them to quenya, and shift the glyphs to avoid conflicts
txt = txt.replace(regex("([0-9]+)"),
m => number-to-quenya(m.captures.first()))
// Map symbols from the Latin alphabet to Tengwar glyphs
txt = txt.replace(regex("(" + array-to-string-or(map-quenya.keys()) + ")"),
m => map-quenya.at(m.captures.first(), default: m.captures.first()))
// Undo the number glyph shifts
txt = txt.replace(regex("(" + array-to-string-or(numbers-unshift.keys()) + ")"),
m => numbers-unshift.at(m.captures.first()))
// Replace aha by halla if followed by ore, romen, or lambe
txt = txt.replace(regex(aha + "(" + ore + "|" + romen + "|" + lambe + "|" + lambe-alt + ")"),
m => halla + m.captures.first())
// Exchange aha and hyarmen and add two dots below anna at start of word
txt = txt.replace(regex("(\ +)(" + aha + "|" + hyarmen + ")"),
m => m.captures.at(0) + if m.captures.at(1) == aha {hyarmen} else {aha})
txt = txt.replace(regex("(\ +)" + anna), m => m.captures.first() + anna + tehta-y)
txt = txt.replace(regex("(.)"),
m => if m.captures.first() == aha {
hyarmen
} else if m.captures.first() == hyarmen {
aha
} else if m.captures.first() == anna {
anna + tehta-y
} else {
m.captures.first()
},
count: 1)
// If anna follows a consonant, replace it by two dots under the tengwa
txt = txt.replace(regex("(" + array-to-string-or(consonants) + ")" + "(\u{fffe}?)" + anna),
m => m.captures.at(0) + m.captures.at(1) + tehta-y)
// If órë is followed by a vowel or by anna and a vowel, replace it with rómen, and conversely
txt = txt.replace(regex("([" + ore + romen + "])" + "(" + array-to-string-or(vowels) + ")"),
m => {if m.captures.at(0) == ore { romen } else { ore }} + m.captures.at(1))
txt = txt.replace(regex("([" + ore + romen + "])" + anna + "(" + array-to-string-or(vowels) + ")"),
m => {if m.captures.at(0) == ore { romen } else { ore }} + anna + m.captures.first())
// Use S-hooks if possible, and move the following tehtar if needed
txt = txt.replace(regex("(" + array-to-string-or(consonants) + ")"
+ "(\u{fffe}?)" + silme
+ "([" + array-to-string-or(tehtar) + "]?)"),
m => if s-hooks.keys().contains(m.captures.at(0)) {
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + s-hooks.at(m.captures.at(0))
} else {
m.captures.at(0) + m.captures.at(1) + sule + m.captures.at(2)
}
)
// Use alternate versions of silme and esse if followed by a short vowel
txt = txt.replace(regex(silme + "(" + array-to-string-or(tehtar) + ")"),
m => silmenuquerna + m.captures.first())
txt = txt.replace(regex(esse + "(" + array-to-string-or(tehtar) + ")"),
m => essenuquerna + m.captures.first())
txt = txt.replace(regex("\\" + silme-alt + "(" + array-to-string-or(tehtar) + ")"),
m => silmenuquerna-alt + m.captures.first())
txt = txt.replace(regex(esse-alt + "(" + array-to-string-or(tehtar) + ")"),
m => essenuquerna-alt + m.captures.first())
// If a tehta is not on a consonnant nor preceded by \u{ffff}, add a carrier (exclude theta-y)
// (Run twice to deal with sequences of multiple tehtar)
txt = txt.replace(regex("(.?)(\u{fffe}?)(\u{ffff}?)(" + array-to-string-or(tehtar.slice(0,-1)) + ")"),
m => if (consonants + (carrier-i, carrier-j, tehta-y)).contains(m.captures.at(0)) {
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + m.captures.at(3)
} else {
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + carrier-i + m.captures.at(3)
})
txt = txt.replace(regex("(.?)(\u{fffe}?)(\u{ffff}?)(" + array-to-string-or(tehtar.slice(0,-1)) + ")"),
m => if (consonants + (carrier-i, carrier-j, tehta-y)).contains(m.captures.at(0)) {
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + m.captures.at(3)
} else {
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + carrier-i + m.captures.at(3)
})
// Fix the tilde width
txt = txt.replace(regex("(" + array-to-string-or(consonants) + ")([" + array-to-string-or(vowels) + "]?)" + tilde),
m => m.captures.at(0) + m.captures.at(1) + overtilde.at(letter-shapes.at(m.captures.at(0))))
// Adjust the positions of tehtars
txt = txt.replace(
regex("(" + array-to-string-or(consonants)
+ ")(\u{fffe}?)"
+ "(\u{ffff}?)("
+ tehta-y + "?)("
+ array-to-string-or(vowels) + ")"),
m => {
let shifted-a = vowels-shifted.at(
m.captures.at(3) + letter-shapes.at(m.captures.at(0)),
default: m.captures.at(3))
let shifted-b = vowels-shifted.at(
m.captures.at(4) + letter-shapes.at(m.captures.at(0)),
default: m.captures.at(4))
m.captures.at(0) + m.captures.at(1) + m.captures.at(2) + if (letter-shapes.keys().contains(m.captures.at(0))) {
if style == "italic" {
vowels-shifted-it.at(
m.captures.at(3) + letter-shapes.at(m.captures.at(0)),
default: shifted-a) + vowels-shifted-it.at(
m.captures.at(4) + letter-shapes.at(m.captures.at(0)),
default: shifted-b)
} else {
shifted-a + shifted-b
}
} else {
m.captures.at(3) + m.captures.at(4)
}
})
// Combine repeated consonants
txt = txt.replace(regex("(" + array-to-string-or(consonants) + ")(" + array-to-string-or(consonants) + ")"),
m => if (m.captures.at(0) == m.captures.at(1)) {
m.captures.first() + undertilde.at(letter-shapes.at(m.captures.at(0)))
} else {
m.captures.at(0) + m.captures.at(1)
})
// Use alt font for text between \u{ffff} and \u{fffe}
let re-alt-font = regex("\u{ffff}(.?)\u{fffe}")
show re-alt-font : it => {
let m = it.text.match(re-alt-font).captures.first()
text(font: tengwar-font-alt, fallback: false, m)
}
// Remove \u{fffd}
show "\u{fffd}": ""
txt
}
#let quenya(it, style: "normal") = {
show re-esse-adjust: adjust-esse
show re-lambe-silmenuquerna-adjust: adjust-lambe-silmenuquerna
show re-tehtar-adjust: adjust-tehtar
show re-digits-adjust: adjust-digits
if it.has("text") {
text(quenya-str(it.text, style: style), style: style)
} else if it.has("body") {
if (repr(it.func()) == "emph") {
set text(style: "italic")
quenya(it.body, style: "italic")
} else {
it.func()(quenya(it.body, style: style))
}
} else if it.has("children") {
it.children.map(it => quenya(it, style: style)).join()
} else if it.has("child") {
quenya(it.child, style: style)
} else {
it
}
}
|
https://github.com/Nrosa01/TFG-2023-2024-UCM | https://raw.githubusercontent.com/Nrosa01/TFG-2023-2024-UCM/main/Pruebas/Documento%20Entrevistado.typ | typst | #import "setup.typ": *
#show: project
= Creación de 3 partículas
== Arena
La partícula de arena se desplaza hacia abajo si el espacio está vacío o si hay agua. En caso contrario, intenta moverse hacia la derecha y luego hacia abajo; si no es posible, intenta moverse hacia la izquierda y luego hacia abajo. Adicionalmente, para mayor dinamismo, en lugar de probar siempre hacia abajo a la derecha, se sugiere hacerlo de manera aleatoria entre derecha e izquierda.
== Vapor
El vapor se comporta como la arena en su movimiento, pero en lugar de descender, asciende hacia arriba. Es posible usar el comportamiento de la arena como base.
== Agua
Similar a la arena, la partícula de agua se desplaza hacia abajo si no hay obstrucción. Si encuentra alguna, intenta moverse hacia abajo a la derecha y luego a la izquierda. Si no es posible, busca moverse primero hacia la derecha y luego hacia la izquierda.
== Lava
Al igual que la arena, la lava se desplaza en dirección descendente. Sin embargo, después de moverse, verifica si hay alguna partícula de agua adyacente; si la encuentra, la convierte en vapor.
Es decir, por un lado está el movimiento, que es igual que la arena, comprobando solo con el vacío sin el agua. Después de esto, se verifica si hay agua adyacente y, en caso afirmativo, se ha de convertir en vapor
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/default/default.typ | typst | The Unlicense | #import "./components.typ"
#import "/utils.typ"
#let rules = utils.make-rules(doc => {
doc
})
#let cover = utils.make-cover(ctx => [
#set align(center + horizon)
*Default Cover*
])
#let frontmatter-entry = utils.make-frontmatter-entry((ctx, body) => {
show: page.with(
header: [
= #ctx.title
#box(
width: 1fr,
line(length: 100%),
)
],
footer: align(
center,
context counter(page).display("i"),
),
)
body
})
#let body-entry = utils.make-body-entry((ctx, body) => {
show: page.with(
header: [
= #ctx.title
#box(
width: 1fr,
line(length: 100%),
)
],
footer: align(
center,
context counter(page).display(),
),
)
body
})
#let appendix-entry = utils.make-appendix-entry((ctx, body) => {
show: page.with(
header: [
= #ctx.title
#box(
width: 1fr,
line(length: 100%),
) ],
footer: align(
center,
context counter(page).display("i"),
),
)
body
})
}
#let default-theme = utils.make-theme(
// Global show rules
rules: rules,
cover: cover,
// Entry pages
frontmatter-entry: frontmatter-entry,
body-entry: body-entry,
appendix-entry: appendix-entry,
)
|
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/tools/test-helper/README.md | markdown | Apache License 2.0 | # Test helper
This is a small VS Code extension that helps with managing Typst's test suite.
When installed, three new buttons appear in the menubar for all `.typ` files in
the `tests` folder.
- Open: Opens the output and reference images of a test to the side.
- Refresh: Refreshes the preview.
- Rerun: Re-runs the test.
- Update: Copies the output into the reference folder and optimizes
it with `oxipng`.
For the test helper to work correctly, you also need to install `oxipng`, for
example with `cargo install oxipng`.
|
https://github.com/sofianedjerbi/ResumeOld | https://raw.githubusercontent.com/sofianedjerbi/ResumeOld/main/letter.typ | typst | Apache License 2.0 | #import "brilliant-CV/template.typ": *
#show: layout
#set text(size: 12pt) //set global font size
#letterHeader(
myAddress: [284 Avenue de Lyon \ 07500 Guilherand-Granges, France],
recipientName: [CY Cergy Paris Université],
recipientAddress: [95000 Cergy, France],
date: [10/03/2024],
subject: "Candidature au Master d'Informatique à distance"
)
Madame, Monsieur,
Passionné par l’ingénierie et l’architecture logicielle, avec quatre années d'expérience riche et diversifiée dans la création de solutions informatiques, je me permets de vous adresser ma candidature pour le Master 1 que propose votre établissement. Mon parcours m'a permis d'acquérir une maîtrise avancée dans plusieurs langages de programmation (Java, C++, Python, Kotlin, etc.) et technologies (Linux, Docker, AWS, Azure, etc.), me positionnant idéalement pour poursuivre mes études dans ce domaine.
Ce master à distance représente pour moi l'opportunité idéale de concilier travail et études. Travaillant en parallèle, je souhaite appliquer concrètement et immédiatement les connaissances acquises. Cela me permettra non seulement de continuer à monter en compétences de manière significative mais aussi d’enrichir mon expérience professionnelle par de nouvelles perspectives académiques.
Mon expérience dépasse largement le cadre académique traditionnel. Elle m'a offert une compréhension approfondie des défis techniques actuels et à venir, ainsi qu'une capacité à innover et à apporter des solutions efficaces. Je suis convaincu que mon profil unique apportera une valeur ajoutée à votre programme, tout en me permettant de bénéficier d'un enseignement de qualité pour approfondir mes connaissances et compétences.
Motivé à l'idée de rejoindre votre établissement, je suis persuadé que ce master à distance est le tremplin dont j'ai besoin pour poursuivre mon évolution professionnelle tout en consolidant mes acquis théoriques. Je suis impatient de pouvoir discuter plus amplement de ma candidature avec vous.
Je vous remercie pour l'attention que vous porterez à ma candidature et reste à votre disposition pour toute information complémentaire.
Cordialement,
<NAME>
#letterSignature("/src/signature.png")
#letterFooter()
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/opticalsize_07.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test attaching primes only
$a' = a^', a_', a_'''^''^'$ |
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/bonnes-pratiques.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#set text(font: "Roboto Serif")
= Bonnes pratiques de Programmation <bonnes-pratiques-de-programmation>
== Introduction <introduction>
Les bonnes pratiques (ou règles de codage) sont un ensemble de règles visant à uniformiser les pratiques de développement afin que "tout le monde s’entende bien". Le but est que le code soit #strong[facile à lire] pour soi-même et pour les autres, que sa #strong[logique soi évidente], qu’il soit #strong[explicite] et #strong[soigné]. Il doit également être maintenable dans le temps bien que cela ne nous concerne pas encore, de même pour la portabilité.
#quote(
block: true,
)[
Remarque : Les "bonnes pratiques" restent tout de même subjectives puisque la lisibilité est subjective. Presque tout ce qui se trouve dans ce document provient des sources citées, mais faire autrement n’est pas toujours un problème !
]
Il existe de nombreuses règles réparties en plusieurs thèmes :
+ L’organisation des fichiers
+ L’indentation
+ Les conventions de nommage
+ Les commentaires et la documentation
+ Les recommandations sur les déclérations
+ Les recommandations sur l’écriture des instructions, des structures et l’usage des parenthèses (dont accolades etc…).
Par exemple, du code redondant, 200 caractères sur une même ligne ou bien des noms de variables à une lettre constituent des crimes (parmi d’autres), que vous ne commettez évidemment plus.
#quote(
block: true,
)[
Remarque : Certaines de ces règles dépenderont également du langage, documenter son code est assez universel mais les convention de nommage sont souvent différentes, de même pour l’organisation des fichiers. Nous ferons donc (si nécessaire) la distinction entre OCaml et C.
]
Liens utiles
- Pour le C : #link("https://www.gnu.org/prep/standards/")[GNU Coding Standards]
- Pour le OCaml : #link("https://ocaml.org/docs/guidelines")[OCaml Programming Guidelines]
- Pour le Python : #link("https://peps.python.org/pep-0008/")[PEP 8]
Vous pourriez tenter d’ingérer ces textes sacrés de la programmation mais je vous propose un résumé sur ce qui est le plus important pour nous.
== I - Le nommage <i---le-nommage>
Que ce soient les noms des variables ou ceux des fichiers il est important d’avoir une organisation claire pour que même sans #link(
"https://fr.wikipedia.org/wiki/%C3%89diteur_de_texte",
)[éditeur de texte] vous puissiez identifier chaque élément du programme. Ces noms servent en quelques sortes de premiers "commentaires" pour votre code, ils doivent donner des #strong[informations utiles]. Cependant il est recommandé de ne pas le faire pour les caractères qui prêtent à confusion comme `l et O` qui se confondent facilement avec `1 et 0`.
#quote(
block: true,
)[
Remarque : Pour ce qui est temporaire ou "local" on peut se permettre des noms assez courts puisque c’est utilisé dans un seul contexte où les commentaires suffisent, il est important que le nom donne des informations si c’est pertinent.
]
Dans nos deux langages et dans bien d’autres #strong[snake\_case] pour nommer les variables. Il est explicitement interdit d’utiliser des majuscules ! En C elles sont réservées aux macros, aux énums et aux constantes. En OCaml elles sont réservées aux constructeurs et aux modules.
Pour les fonctions et les fichiers on utilisera ici cette même convention.
#quote(
block: true,
)[
Remarque : Historiquement on demandait un maximum de 14 caractères en C afin d’éviter des conflits sur les vieux systèmes, mais aujourd’hui ce n’est plus le cas (dans le cas général).
]
=== C - Particularités <c---particularités>
Les constantes sont nommées en #strong[screaming snake case], de plus elles sont généralement précédées du mot clé `const` .
```c
const int MA_CONSTANTE = 42;
```
Je vous renvoie sur #link(
"https://fr.wikiversity.org/wiki/Introduction_au_langage_C/Variables_et_constantes",
)[cette page] où vous pourrez prendre connaissance de toutes les subtilitées liées à la délcaration de variables et de constantes.
=== OCaml - Particularités <ocaml---particularités>
En OCaml il est recommandé de nommer explicitement vos #strong[exceptions], jusque là rien de nouveau.
Mais il est également recommandé d’utiliser le plus possible les exceptions données par défaut.
Si vous avez besoin d’exprimer le fait de ne pas avoir trouver un élément, plutôt que de redéfinir une nouvelle exception il est préférable d’utiliser `Not_found`.
#quote(
block: true,
)[
Remarque : On utilise du #strong[snake case] en commançant par une majuscule pour les exceptions.
]
Enfin, lorsqu’une fonction anonyme (`fun x -> foo...`) est trop grande nommez-là.
== II - Formattage <ii---formattage>
Le formattage du code est la structure visuelle que vous lui donnez, c’est l’équivalent de la présentation d’une copie, si elle est sale personne ne voudra (ou ne pourra) la lire.
Indentation (très important)
L’indentation permet d’identifier très rapidement les blocs de code, il est indispensable de la respecter.
```c
// Mal indenté
for (i = 0; i < 42; i++) {
foo();
if (i == 7) {
bar();
}
}
// Au lieu
for (i = 0; i < 42; i++) {
foo();
if (i == 7) {
bar();
}
}
```
```ocaml
(* Mal indenté *)
for i = 0 to 42 do
foo ();
if i = 7 then
bar ();
done;
(* Au lieu de *)
for i = 0 to 42 do
foo ();
if i = 7
then bar ();
done;
```
En OCaml on placera les `|` du pattern-matching sous le `let`, on ne fait pas d’alignement excessif. De même, on met les flèches directement après.
```ocaml
(* On n'écrit pas *)
let f = function
| C1 -> 1
| Long_name _ -> 2
| _ -> 3
(* Mais *)
let f = function
| C1 -> 1
| Long_name _ -> 2
| _ -> 3..
```
Utilisation des opérateurs
Il est plus lisible de séparer ses opérateurs par des espaces. Vous pouvez également vous servir de parenthèses.
```c
// Peu lisible ou difficilement
x*y
x * y+z
x*y/z+a-b
// Au lieu de
x * y
x * y + z
(x * y / z) + (a - b)
```
#quote(
block: true,
)[
On remarque bien ici la subjectivité, les parenthèses sont inutiles et nous aurions raison de ne pas les mettre, mais ce n’est pas interdit. Quand on peut contribuer à une meilleure lisibilité on a tout à fait le droit.
]
Placement des accolades & déclaration d’une fonction
En C, lors de la déclaration d’une fonction, on place les accolades sur la première colonne, c’est-à-dire qu’on revient à la ligne. C’est surtout utile pour certains outils de recherche. Dans une fonction il ne faudra pas le faire pour autre chose (`while`, `for`, `if`…) car cela perturberait ces outils. Cependant cela reste autorisé pour les `struct` et les `enums` (qui peuvent rester en une ligne s’ils tiennent).
De plus, le nom de la fonction suit la même règle, il est placé à partir de la première colonne et est donc séparé du type de retour.
```c
// Un exemple
typedef struct position {int x; int y;};
typedef struct joueur
{
int id;
char* nom;
int* items;
};
void
foo (joueur next_player, position pos)
{
bar();
};
```
On placera également des accolades lorsque l’on imbriquera des `if` & `else`.
```c
if (i == 42) {
foo();
} else {
bar();
}
```
Lorsque qu’il y en a plusieurs d’imbriqués ont hésitera pas à rassembler `else` et le `if` qui suit ensemble.
```c
if (i == 42) {
foo();
} else if (i % 2 == 0) {
bar();
}
```
Taille du code
Il existe une limite de caractères recommandée en largeur, c’est de là que vient cette ligne verticale dans vos environnements. En C un maximum de 79 caractères est recommandé pour 80 en OCaml. L’objectif est que le code soit visible sur n’importe quel environnement. Il est également recommandé de faire tenir vos fonctions sur un écran si possible, plus si vous n’avez vraiment pas le choix.
Dans certains cas, respecter la limite horizontale peut sembler impossible mais voici quelques outils qui vous seront utiles.
- Sauter des lignes entre vos arguments et vos opérateurs (avant) s’ils ne tiennent pas sur une ligne.
```c
void
foo (int longueur_matrice, int largeur_matrice, int** matrice,
int element, int* ligne_retour, int* colonne_retour)
{
if (longueur_matrice > largeur_matrice
&& element > 0
&& element < largeur_matrice) foo();
}
```
- En OCaml, mettre un `\` dans une chaîne de caractère permet d’omettre les espaces en début de ligne après un retour.
```ocaml
let universal_declaration =
"-1- Programs are born and remain free and equal under the law;\n\
distinctions can only be based on the common good." in
....
```
== III - Mauvaises Pratiques <iii---mauvaises-pratiques>
Tout comme on peut trouver des atrocités en langue, on peut trouver des crimes de guerre en programmation. On cite dans cette partie les plus courants.
Les if & else inutiles
Lorsque vous manipulez des valeurs booléennes avec des opérateurs, il ne faut pas oublier que vous manipulez des valeurs booléennes avec des opérateurs… A ce titre, vous savez que vous pouvez utiliser cette valeur sans passer par des conditions.
En effet, tout comme `1 + 4` renvoie `5`, `3 == 5` renverra généralement `false` tandis que `21 > 12 && 42 > 7` renverra `true`.
Exemple plus concret :
```c
// Mauvaise pratique
bool
f (int x, int y)
{
// "si j'aurais su j'aurais pas venu"
if (x > y || x % 2 == 0) {
return false;
} else {
return true;
}
}
// Bonne pratique
bool
g (int x, int y)
{
return !(x > y || x % 2 == 0);
}
```
#quote(
block: true,
)[
Remarque : Cette mauvaise pratique est présente partout puisqu’elle ne dépend pas du langage. Elle ne vous fera pas voir.
]
Programmer dans les fichiers d’en-tête
Puisque les extensions ne sont que des conventions pour nous, l’ordinateur accepte que l’on exécute n’importe quel fichier. Vous pourriez prendre votre cours dans un fichier `.png` mais vous ne le faites pas bien sûr. De la même manière vous ne devez pas coder d’instruction dans les fichiers d’en-tête, ils sont réservés aux déclarations (variables, prototypes de fonctions etc…). Cela est même considéré (par les humains) comme une erreur de le faire ! \
Je vous renvoie au #link(
"https://github.com/voXrey/cours-informatique/blob/main/compilation.md",
)[cours sur la compilation] pour en savoir plus sur les fichiers d’en-tête.
Affectation dans les conditions
Que ce soit par erreur ou par curiosité (en espérant pas par besoin), vous savez peut-être déjà que dans certains langages on peut affecter une variable dans une condition puisque l’affectation a une valeur de retour.
Exemple en C :
```c
void
f (int x)
{
if (x = 42) {
printf("%d", x);
} else {
printf("%d", 0);
}
}
```
On décide d’appeler `f` avec l’argument `x = 2024`, à votre avis qu’est-ce qui sera affiché par cette fonction ?
Réponse : `42`
En effet, l’affectation renvoie la valeur affectée, puisqu’elle est différente de `0` (ici `2024`), la condition est remplie puis la valeur de `x` nouvellement affectée est affichée. Ainsi l’affectation dans une condition renverra toujours `true` à moins d’affecter une valeur nulle.
Il s’agit là plus d’une erreur que d’une mauvaise pratique mais dans la situation où cela vous paraîtrait malin de la faire sachez que ce sera incompréhensible.
Ignorer les warnings
Les warnings ne sont pas là pour rien, c’est écrit dessus. Préférez les résoudre plutôt que de les bypass. De plus, un programme rempli de warnings dégage un parfum "d’amateur".
Lors de votre pattern-matching en OCaml, faites en sorte que celui-ci soit exhaustif, les développeurs le disent, abusez-en mais faites-le bien. Evitez-donc les "catch-all" (ou "fourre-tout" en français) comme `_ -->` ou `x -->`.
Lorsque vous souhaitez ignorer le résultat d’une expression, précisez-le explicitement, ne laissez pas le warning.
```ocaml
(* Ne pas faire *)
List.map f l;
print_newline ()
(* Mais *)
let _ = List.map f l in
print_newline ()
(* Ou bien avec la fonction ignore *)
ignore (List.map f l);
print_newline ()
```
Si le compilateur vous averti, c’est qu’il y a une erreur potentielle, dans cet exemple l’intention du développeur aurait dû être celle-ci :
```ocaml
List.iter f l;
print_newline ()
```
Gestion des importations
Utiliser les fonctions importés depuis `module` en écrivant `module.fonction` est certes précis mais long. Il est donc possible d’ouvrir les modules mais il faut faire attention aux collisions.
```ocaml
let f () =
Format.print_string "Hello World!"; print_newline ()
```
Ce code est pose problème car il n’appelle pas~`Format.print_newline` pour vider la file d’attente et afficher~`"Hello World!"`. Au lieu de cela,~`"Hello World!"` est coincé dans la file d’attente, tandis que~`Stdlib.print_newline` produit un retour chariot sur la sortie standard.
Si~`Format` se trouve dans un fichier et que la sortie standard est le terminal, l’utilisateur aura du mal à constater qu’il manque un retour chariot dans le fichier, tandis qu’un faux retour chariot apparaissait à l’écran !
Cependant pour une question de lisibilité il peut être parfois vivement recommandé d’ouvrir le module. De plus, ouvrir de grandes bibliothèques comme celles contenant des entiers de précision arbitraires afin de ne pas surcharger le prgramme qui lest utilise est bien.
```ocaml
open Num
let rec fib n =
if n <= 2 then Int 1 else fib (n - 1) +/ fib (n - 2)
```
Dans un programme où les définitions de types sont partagées, il est avantageux de rassembler ces définitions dans un ou plusieurs modules sans implémentations (contenant uniquement des types). Il est alors acceptable d’ouvrir systématiquement le module qui exporte les définitions de types partagées.
== IV - Commentaires & Documentation <iv---commentaires-documentation>
Lorsque vous programmez, vous avez une logique et une réflexion qui ne seront pas les mêmes que celles de quelqu’un d’autre ou même de vous dans quelques semaines. Commenter votre code est donc une nécessité pour un programme maintenable dans le temps et partageable. On recommande même souvent de toujours coder en anglais pour pouvoir demander de l’aide plus facilement.
Chaque programme fois commencer par un commentaire expliquant brièvement à quoi il sert. Au début de chaque fichier, indiquez également son utilité.
Pour chaque fonction, indiquez la spécification de la fonction en détail (ce qu’elle fait, types d’arguments, leur utilité…). Il n’est cependant pas nécessaire de répéter la déclaration de l’argument. Il est attendu de donner des informations pertinentes comme un élément inhabituel ou propre à la fonction.
En C, il est recommandé de laisser deux espaces après une phrase dans un commentaire et de les commencer par une majuscule, cela facilitera la génération automatique de la documentation. Il y a beaucoup de détails à ce propos à aller voir, il n’y a pas besoin de le détailler ici.
Les commentaires dits "inoffensifs", ceux qui apportent des informations triviales sont inutiles, et sont même une nuisance. Voici un exemple de ce que cela pourrait être :
```ocaml
(*
Function print_lambda:
print a lambda-expression given as argument.
Arguments: lam, any lambda-expression.
Returns: nothing.
Remark: print_lambda can only be used for its side effect.
*)
let rec print_lambda lam =
match lam with
| Var s -> printf "%s" s
| Abs l -> printf "\\ %a" print_lambda l
| App (l1, l2) ->
printf "(%a %a)" print_lambda l1 print_lambda l2
```
N’hésitez pas à utiliser des `assert` qui donnent une information claire tout en apportant une réelle vérification.
== Sources <sources>
- #link(
"https://fr.wikipedia.org/wiki/R%C3%A8gles_de_codage",
)[Page wikipédia sur les règles de codage]
- #link(
"https://perso.liris.cnrs.fr/pierre-antoine.champin/enseignement/algo/cours/algo/bonnes_pratiques.html",
)[Cours d’algo de Pierre-Antoine Champin]
- #link("https://www.gnu.org/prep/standards/")[GNU Coding Standards]
- #link(
"https://ocaml.org/docs/guidelines#no-beastly-alignment-of-the---symbols-in-pattern-matching-clauses",
)[OCaml Programming Guidelines]
- #link(
"https://emmanuel-delahaye.developpez.com/tutoriels/c/bonnes-pratiques-codage-c",
)[Cours de bonnes pratiques en C sur developpez.net]
- #link(
"https://github.com/ocaml-ppx/ocamlformat",
)[Github de ocamlformat autof-formatter pour ocaml]
- #link(
"https://fr.wikiversity.org/wiki/Introduction_au_langage_C/Variables_et_constantes",
)[wikiversité - constantes et variables]
|
|
https://github.com/kimushun1101/How-to-use-typst-for-paper-jp | https://raw.githubusercontent.com/kimushun1101/How-to-use-typst-for-paper-jp/main/main.typ | typst | MIT License | #import "@preview/touying:0.4.2": *
#import "@preview/ctheorems:1.1.2": thmrules, thmbox, thmplain, thmproof
#let s = themes.university.register(aspect-ratio: "16-9")
#let s = (s.methods.numbering)(self: s, section: "1.", "1.1")
// Global information configuration
#let s = (s.methods.info)(
self: s,
title: [Typst で論文を書く],
// subtitle: [Subtitle],
author: [<NAME>],
// date: datetime(year: 2024, month: 8, day: 3),
date: datetime.today(),
institution: [
#sym.XX : #link("https://x.com/kimushun1101")[$#sym.at$kimushun1101]\
GitHub : #link("https://github.com/kimushun1101")[kimushun1101]
],
)
// Extract methods
#let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s)
#show: init
#show table: set text(size: 18pt)
#show figure.where(kind: table): set figure.caption(position: top)
#show strong: alert
#let gothic = ("MS PGothic", "Hiragino Kaku Gothic Pro", "IPAexGothic", "Noto Sans CJK JP")
#let mincho = ("MS PMincho", "Hiragino Mincho Pro", "IPAexMincho", "Noto Serif CJK JP")
#set text(size: 24pt, font: gothic)
#import "@preview/sourcerer:0.2.1": code
#show link: set text(blue)
// Theorems configuration by ctheorems
#show: thmrules.with(qed-symbol: $square$)
#let thmjp = thmplain.with(base: {}, separator: [#h(0.5em)], titlefmt: strong, inset: (top: 0em, left: 0em))
#let definition = thmjp("definition", text(font: gothic)[定義])
#let lemma = thmjp("lemma",text(font: gothic)[補題])
// #let theorem = thmjp("theorem", text(font: gothic)[定理])
#let theorem = thmbox("theorem", "定理", fill: rgb("#eeffee"))
#let corollary = thmjp("corollary",text(font: gothic)[系])
#let proof = thmproof("proof", text(font: gothic)[証明], separator: [#h(0.9em)], titlefmt: strong, inset: (top: 0em, left: 0em))
// #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
// #let definition = thmplain("definition", "定理")
// // #let theorem = thmbox("theorem", "Theorem", inset: (x: 1.2em, top: 1em))
// #let lemma = thmplain("lemma", "補題")
// // #let corollary = thmbox("corollary", "Corollary", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
// #let proof = thmproof("proof", "Proof")
// Extract slide functions
#let (slide, empty-slide) = utils.slides(s)
#show: slides
// First slide
== (制御工学勉強会での)発表の背景
#columns(2)[
#image("figs/post_x.png")
#image("figs/post_discord.png")
]
制御工学の論文執筆には LaTeX を使用する人が多い.\
数式や図を多用することから好まれる傾向がある?\
一方,習得コストが高め(研究室配属時に訓練される)
= Typst の概要
== Typst
LaTeX の代替として海外で Typst が流行り始めている
Typst の特徴
- テキストファイルをコンパイルして PDF を作成
- 環境構築が簡単
- 文法やエラー文がわかりやすい
- 公式ドキュメントが整備されている #footnote[https://typst.app/docs/]
- 公式がテンプレートやパッケージを管理している #footnote[https://typst.app/universe]
- 公式のクラウド環境もある
- 公式 Discord があり活発
== Word, LaTeX, Typst の比較
#figure(
placement: top,
// caption: [Word, LaTeX, Typst の比較],
table(
columns: 5,
stroke: none,
table.header(
[],
[],
[Word],
[LaTeX],
[Typst],
),
table.hline(),
[1],[Word が LaTeX より優れている部分], [], [], [],
[],[知名度,テンプレートの多さ], [⊚], [○], [△],
[],[インストールの簡単さ], [○], [△], [⊚],
[],[習得の容易さ], [○], [△], [⊚],
table.hline(),
[2],[LaTeX が Word より優れている部分], [], [], [],
[],[マルチプラットフォーム対応], [△], [○], [⊚],
[],[ソフトウェア使用料], [有料], [無料], [無料],
[],[ファイル形式], [.docx (バイナリ)], [.tex (テキスト)], [.typ (テキスト)],
[],[体裁の整えやすさ], [△], [⊚], [⊚],
table.hline(),
[3],[Typst が LaTeX より優れている部分], [], [], [],
[],[文法のシンプルさ], [‐], [○], [⊚],
[],[エラー文のわかりやすさ], [‐], [△], [⊚],
[],[コンパイルの速さ], [‐], [△], [⊚],
)
) <tab:comparison>
∗#text(12pt)[作成時現在の状況です.書き手の独断と偏見を含みます.]
== Typst の使い方
=== 環境構築
+ #link("https://code.visualstudio.com/")[VS Code] をインストール
+ 拡張機能 #link("https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist")[Tinymist Typst] をインストール#footnote[Tinymist は VS Code 以外にも #link("https://helix-editor.com/")[Helix] や #link("https://neovim.io/")[Neovim], #link("https://zed.dev/")[Zed] などにもインストール可能 https://github.com/Myriad-Dreamin/tinymist]
=== 執筆方法
+ main.typ などの typ ファイルを作成
+ ファイルを開いたエディターの 0 行目にある `preview` で表示#footnote[エディター右上のアイコンやショートカットキーは`Ctrl + K, V` でも実行可能です.]
+ エディター窓の最上部にある `Export PDF` でファイル保存#footnote[保存したときにPDF出力する設定もあります.]
== 学会の Typst テンプレートサンプルを作ってみた
https://github.com/kimushun1101/typst-jp-conf-template
#columns(2)[
#image("figs/github.png", width: 90%)
以下の国内学会論文に似せた\ テンプレートを作成
- 日本ロボット学会学術講演会#footnote[公式で Typst フォーマットが提供されました.\ #h(10mm) https://ac.rsj-web.org/2024/manuscript.html]
- 自動制御連合講演会
- 制御部門マルチシンポジウム
]
== 個人的なこだわりポイント
=== *Abstruct や Keywords の体裁*
学会によってここらへんも微妙に変化するため細かく対応
=== *本文に Typst のコード例*
文法をコピペするために,コード例 #footnote[図,表,数式,定理など] をたくさん書きました.\
追加リクエストなどあればください.
=== *参考文献の体裁*
自動で引用順になります.
CSL ファイルで体裁も整えています.
引用の表記も [1] だったり,上付き 1) だったり.
= 文法紹介
== マークアップ
印象としては Markdown 記法に近い
/* 表示がそれっぽく見えるようにズルしています */
#figure(
// caption: [フォントの設定],
table(
columns: 3,
stroke: none,
table.header(
[名称],
[コード例],
[レンダリング例],
),
table.hline(),
[見出し1], [`= Heading 1`], [#text(20pt, [*Heading 1*])],
[見出し2], [`== Heading 2`], [#text(18pt, [Heading 2])],
[段落区切り], [空行を挟む], [ ],
[改行], [`\`], [ ],
[raw テキスト], [$prime.rev$`text`$prime.rev$], [`text`],
[箇条書きリスト], [`- item`], [ #sym.bullet item ],
[番号つきリスト], [`+ item`], [ 1. item ],
[強調(太文字)], [`*strong*`], [*strong*],
[強調(斜体)], [`_emphasis_`], [#text(font: "Times New Roman", [_emphasis_])],
[クオーテーション], [`'single'` or `"double"`], ['single' or "double"],
[コメントアウト], [`/* block */` or `// line`], [ ],
)
)
https://typst-jp.github.io/docs/reference/syntax/ を参考
== 数式のコード例
数式番号をつけるような中央揃えの数式は,最初の`$` の後ろと閉じの`$` の前にスペースを挟み
#code(
```typ
$ dot(x) &= A x + B u \
y &= C x $ <eq:system>
```
)
のように書き,文中に書く数式は,`$` の前後にスペースを挟まず
#code(
```typ
$x in RR^n$
```
)
というように書きます.
== 数式のレンダリング例
前ページの例を参考に以下のようなレンダリングができる.
以下のシステムを考える.
$ dot(x) &= A x + B u \
y &= C x $ <eq:system>
ここで $x in RR^n$ は状態,$u in RR^m$ は入力,$y in RR^l$ は出力,$A in RR^(n times n)$,$B in RR^(n times m)$,および $C in RR^(l times n)$ は定数行列である.
== 図のコード例
執筆時現在 Typst 0.11 では PNG, JPEG, GIF, SVG の形式を挿入可能
#code(
```typ
#figure(
placement: bottom,
image("figs/quadratic.svg", width: 90%),
caption: [$x^2$ のグラフ],
) <fig:quadratic>
#figure(
placement: bottom,
image("figs/sqrt-and-sin.png", width: 90%),
caption: [$sqrt(x)$ と $sin x$ のグラフ],
) <fig:sqrt-sin>
```
)
== 図のレンダリング例
#columns(2)[
#figure(
placement: bottom,
image("figs/quadratic.svg", width: 90%),
caption: [$x^2$ のグラフ],
) <fig:quadratic>
#figure(
placement: bottom,
image("figs/sqrt-and-sin.png", width: 90%),
caption: [$sqrt(x)$ と $sin x$ のグラフ],
) <fig:sqrt-sin>
]
== 表のコード例
#code(
```typ
#figure(
placement: top,
caption: [フォントの設定],
table(
columns: 3,
stroke: none,
table.header(
[項目],
[サイズ (pt)],
[フォント],
),
table.hline(),
[タイトル], [18], [ゴシック体],
[著者名], [12], [ゴシック体],
[章タイトル], [12], [ゴシック体],
[節,小節,本文], [10], [明朝体],
[参考文献], [9], [明朝体],
)
) <tab:fonts>
```
)
== 表のレンダリング例
#figure(
placement: top,
caption: [フォントの設定],
table(
columns: 3,
stroke: none,
table.header(
[項目],
[サイズ (pt)],
[フォント],
),
table.hline(),
[タイトル], [18], [ゴシック体],
[著者名], [12], [ゴシック体],
[章タイトル], [12], [ゴシック体],
[節,小節,本文], [10], [明朝体],
[参考文献], [9], [明朝体],
)
) <tab:fonts>
== 定理環境のコード例
最初に ctheorems パッケージを import して設定,本文中で使用
#code(
// このコードでは以下よりも多く設定している
```typ
#import "@preview/ctheorems:1.1.2": *
#show: thmrules.with(qed-symbol: $square$)
#let definition = thmplain("definition", "定義")
#let lemma = thmplain("lemma","補題")
#let proof = thmplain("proof", "証明", separator: [#h(0.9em)])
```
)
#code(
```typ
#definition("用語 A")[
用語 A の定義を書きます.
]<def:definition1>
#lemma[
補題を書きます.タイトルは省略することもできます.
]<lem:lemma1>
#proof([@thm:theorem1 の証明])[
証明終了として□印をつけています.
]
```
)
== 定理環境のレンダリング例
前ページのコードを少し修正すると以下のようにレンダリングできる.
#definition("用語 A")[
用語 A の定義を書きます.
]<def:definition1>
#lemma[
補題を書きます.タイトルは省略することもできます.
]<lem:lemma1>
#lemma("補題 C")[
補題を書きます.番号のカウントアップ規則も設定可能.
]<lem:lemma2>
#theorem("定理 D")[
ここに定理を書きます.Box 設定の例です.
]<thm:theorem1>
#corollary[
系を書きます.@def:definition1 のように,ラベルで参照することもできます.
]
#proof([@thm:theorem1 の証明])[
証明終了として□印をつけています.
]
== 引用
引用は "\@label" と記述する.
図のラベルとして `@fig:quadratic` とすれば@fig:quadratic,\
表のラベルとして `@tab:fonts` とすれば @tab:fonts となる.
数式や参考文献,定理環境なども同様.
= おわりに
== このスライドについて
この資料はソースコードも含めて GitHub で公開しております.\
https://github.com/kimushun1101/How-to-use-typst-for-paper-jp
不備やご助言などありましたら,GitHub の #link("https://github.com/kimushun1101/How-to-use-typst-for-paper-jp/issues")[Issues] や #link("https://github.com/kimushun1101/How-to-use-typst-for-paper-jp/pulls")[Pull requests] にいただけましたら幸いです.#footnote("正直,私に届くように言っていただければ連絡方法はなんでもよいです.私の対応も気が向いたときにやります.お互い気軽にやりましょう.")
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/multiline.typ | typst | Apache License 2.0 | // Test multiline math.
---
// Test basic alignment.
$ x &= x + y \
&= x + 2z \
&= sum x dot 2z $
---
// Test text before first alignment point.
$ x + 1 &= a^2 + b^2 \
y &= a + b^2 \
z &= alpha dot beta $
---
// Test space between inner alignment points.
$ a + b &= 2 + 3 &= 5 \
b &= c &= 3 $
---
// Test in case distinction.
$ f := cases(
1 + 2 &"iff" &x,
3 &"if" &y,
) $
---
// Test mixing lines with and some without alignment points.
$ "abc" &= c \
&= d + 1 \
= x $
---
// Test multiline subscript.
$ sum_(n in NN \ n <= 5) n = (5(5+1))/2 = 15 $
---
// Test no trailing line break.
$
"abc" &= c
$
No trailing line break.
---
// Test single trailing line break.
$
"abc" &= c \
$
One trailing line break.
---
// Test multiple trailing line breaks.
$
"abc" &= c \ \ \
$
Multiple trailing line breaks.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/030%20-%20Amonkhet/007_Judgment.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Judgment",
set_name: "Amonkhet",
story_date: datetime(day: 17, month: 05, year: 2017),
author: "<NAME> & <NAME>",
doc
)
#figure(image("007_Judgment/01.png", width: 100%), caption: [], supplement: none, numbering: none)
#emph[Samut has abandoned the Trials, her crop, and her old life. She has spent the last few days on the run and is desperate to stay alive long enough to face the trespasser who transformed her world. After discovering that her city is not the way it was only decades ago, she is determined to convince her oldest and dearest friend, Djeru, to believe her. When a direct confrontation doesn't convince him, Samut turns to the only god that could spare his life.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Samut had spent three days without casting a shadow. The light of the suns was a luxury a fugitive could not afford. She had dashed from hiding place to hiding place, pressing herself into the dark crevices of the city-state, out of sight of angels and the anointed dead.
#figure(image("007_Judgment/02.jpg", width: 100%), caption: [Trespasser's Curse | Art by David Palumbo], supplement: none, numbering: none)
Today, her shelter was a former embalming chamber. She hurried in, kicking over a table of dried-out unguents and organ vessels in her haste, and pulled the heavy stone door shut. She lit a torch in its sconce. And then she waited.
It was three days ago that viziers and the anointed dead had seized her. After her ill-advised shouts of dissent, their hands had clamped onto her arms and over her mouth and dragged her out of earshot. She had broken free of her captors at the small cost of a dislocated shoulder, fleeing into the city's dark places using all the speed she had—but how could she have been so careless? When thousands of citizens happily accepted their suffocating blanket of lies, how could she think she could sway hearts by simply yelling in the street? Well, no more. She only cared about swaying one now.
There was a scraping sound at the door. She shoved it open, squinting into the dust-dancing shafts of sunlight. A figure appeared: a guardian mummy wrapped head to toe in linen. Samut beckoned it in.
The mummy shuffled its way over the threshold, step by step. When it had made its way into the chamber, she hauled the door shut again with a crunch of sandstone on sandstone.
The mummy looked at Samut, its taut wrappings flickering in the torchlight.
Samut grinned. "So? Give me a hug already."
#figure(image("007_Judgment/03.jpg", width: 100%), caption: [Labyrinth Guardian (Emblamed) | Art by Yeong-Hao Han], supplement: none, numbering: none)
The mummy's shoulders sank. "This is blasphemy," it mumbled in a familiar male voice.
"But it got you here without getting either of us killed," Samut said.
"I can barely move," the mummy said, stretching its constricted shoulders. "Get me out of this."
She helped the mummy unwrap the linen bindings. The wholesome face of her friend Djeru emerged, and he shrugged the rest of the way out of the disguise. This was the one face she wanted to see. This was her one remaining ally in the world—her cropmate, her brother-in-arms, her friend.
She clasped her arms around him. "I'm glad you're alive," she whispered in his ear.
Djeru backed out of the embrace, holding Samut at arm's length. "How is it you are free to summon me here? I heard they had you on a tight leash after your show of . . . of dissent."
Samut scanned his eyes for judgment. "For my heresy, you mean."
"For defying the law of the gods," he said quietly.
"That's what I asked you here for," she said. "I'm free now, Djeru. You can be free, too."
"Free? From what? You want me to break the law as well?"
That stung. An arrest was tantamount to guilt in his eyes. Was he so ready to relinquish their friendship? "The law has been corrupted. And so have the gods."
Djeru was shaking his head. "You impugn the God-Pharaoh himself."
Samut clasped her hands together. "But he's the very lie that has corrupted the world! There were old customs before the God-Pharaoh, before these Trials. He made the world forget itself. He remade the world and remade the gods to suit his whims."
"Is that why you called me here? To spin stories at me?" He shook his hands in frustration. "I should be in training, Samut. The Trial of Zeal nears. Or have you forgotten what that means to an initiate?"
"I have not forgotten what it means to you." She put a hand on his arm and squeezed. "But I cannot call a lie the truth, and you shouldn't either."
"What are you saying?"
"Don't go to the final Trial."
"Samut."
"Don't throw yourself away. Don't offer up your death, just for—for #emph[sport] ."
"Sport? You call the most holy pinnacle of my life a #emph[sp] —" He walked in an exasperated circle.
That was wrong of her. Painfully wrong. "I'm sorry. I'm sorry. I just—I have seen what the viziers don't want us to see. I have seen how our society has been—twisted. The skeleton of our world removed and replaced with something else. You think you'll be proving yourself a worthy Djeru, but you'll just be destroying Djeru."
He pointed a finger at her. "You're telling me to destroy Djeru in another way instead, by throwing away everything I've worked for to get this far. You're telling me to dishonor myself and dishonor the gods."
She was losing him. She didn't know what to say. "Would the gods want you to die? Would #emph[Nakht] want you to die?" Samut said, and instantly she knew it was the exact wrong thing to say.
"Don't you bring his name into this," Djeru snapped. "Nakht died #emph[unworthy] , out there in the dunes, because of our stupidity. Because of our foolish trespass. And now he roams the sands, biting the intestines out of desiccated corpses. I'm not making that mistake with my own life."
Samut wanted to shout at him—#emph[You utter dunce! You proud and simple fool!] #emph[You'd rather die than show that you were tricked by a false pharaoh!] But she tried to keep her voice even. She knew if she yelled at him, she would just be another nameless dissenter, ranting in the street—and that she would lose him to his self-destructive beliefs.
"Djeru, my friend," she said. "Nakht died to show us what it looks like when a life is cut short. To show us the ugly futility of death."
"No," Djeru said. "He died for #emph[nothing] ."
Something snapped in her. "#emph[SO WILL YOU!] " she roared at him. Her words rang in the fire-lit chamber, reverberating off the stone walls.
#figure(image("007_Judgment/04.jpg", width: 100%), caption: [Samut, Voice of Dissent | Art by <NAME>], supplement: none, numbering: none)
Djeru tipped his chin up. He beat his chest with his fist with ritual solemnity. "I die to rise eternal," he said, in the rhythm of the initiates' chants.
Samut dropped her head, feeling suddenly heavy. She walked in a slow circle, rubbing the back of her neck, pulling at the tight coils of her hair. Every instinct in her body told her it was hopeless to try to save him from himself. Of course she couldn't make that decision for him—the more she pressed him, the further he would back away. She had to walk away, and let him decide for himself.
Except that walking away was not her strong suit.
"Don't go to that Trial," she said.
He made a bitter half-laugh. "You know I had hoped you called me here to ask for #emph[my] help?" He shook his head. "I thought you wanted me to help you get back on the path. To attest to Temmet for you. Maybe to keep you from rotting in a sarcophagus somewhere."
"Djeru."
"You think I'm throwing #emph[my] life away? You might be the greatest initiate of our time. It's a waste, Samut. You've chosen to be a waste."
"I don't care what you think of me," she whispered. "Just don't die."
"Maybe the gods can teach you to believe, dissenter," Djeru said, heading for the door. "I'll plead to Hazoret for you."
He pushed the door open. For a moment there was a dazzling light from outside. And then sandstone scraped against sandstone, and it was just a dim, quiet chamber again, shadows swaying with the torchlight.
She stood there for a long while, wallowing in a brume of failure. She found herself debating her own mood, entertaining the possibility that she had done enough to save her friend's life. Maybe just having the conversation was enough. Maybe she had planted enough of a question in his heart that Djeru would resist the lies of the God-Pharaoh, renounce the Trials, and thank her for caring enough to intervene on his behalf. Maybe he would approach her as a friend, his head bowed low in apology, and ask her forgiveness—that was possible, wasn't it?
She managed to believe that for three entire seconds.
Djeru was unwavering. He'd probably never deign to speak to her again in the precious few days before the final Trial, let alone recant. Meanwhile, the city-state still crawled with mummies and viziers who wanted her dead. If she showed her face in public again, it would be for the last time.
And yet as she replayed Djeru's words in her mind, a nagging feeling itched at her. "#emph[I'll plead to Hazoret for you] ," Djeru had said. What he intended as pity felt more like an opportunity.
She heaved the door open and ran, out from the shadows, into the glare of the two suns.
#figure(image("007_Judgment/05.jpg", width: 100%), caption: [Prepare | Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Samut was already braking as she streaked across the threshold into the monument, crumpling a ceremonial rug with her feet. She spun and looked back, blades at the ready, but the squad of mummies who pursued her had stopped at the entryway. Their blank faces fixated on her, with that vague linen smile, but they did not budge. They needed explicit permission to enter the house of a god.
#figure(image("007_Judgment/06.jpg", width: 100%), caption: [Hazoret's Monument | Art by <NAME>], supplement: none, numbering: none)
Samut caught her breath, sheathing her blades. A set of wide stairs led up into obscurity, lit by braziers carved with the shapes of jackals on each step. Samut couldn't see how far the staircase went—somewhere up into the highest interior of the monument. Into the head of a god.
Samut knelt and bowed low, her forehead touching the floor. "I request an audience, mighty Hazoret." And she only moved when she heard the voice.
"#strong[You may enter, initiate.] "
The voice sounded from every direction, thick words heavy with archaic pronunciation. Samut stood, and saw that the mummies remained outside, waiting. Samut took a ceremonial hearth candle and lit it from one of the braziers. She balanced the candle carefully in her upturned palms and put a foot on the first step. What could she say to a god, to spare her friend's life? Was she actually prepared for this?
She climbed.
The stairs narrowed with each step, with walls of darkness closing in as she ascended. She realized that figures stood in the dark places, motionless mummies stationed throughout, their bodies gowned with fabrics and hieroglyphs of Hazoret. Samut wondered if they were the past victims of Hazoret's temper, upstarts not worthy of the paradisiacal beyond.
Samut emerged onto a dais and gasped. A thirty-foot curtain of fire rose before her, framed by a towering gilded arch. Sparks spit from of the curtain of flame and sizzled in Samut's hair. Samut's face roasted, but she was careful not to spill her hearth candle.
#figure(image("007_Judgment/07.jpg", width: 100%), caption: [Trial of Zeal | Art by <NAME>], supplement: none, numbering: none)
The flame curtain parted, and Samut saw, initially, feet. She looked up to see Hazoret looking down at her. A shining ring gently revolved and undulated around the jackal god's face, a halo of living gold.
The god's mouth moved, but the sound came from everywhere. "#strong[We shall speak until your candle burns away. Would you care to sit, initiate?] "
Samut realized she was surrounded by benches, padded settees, ornate divans—all scaled to mortal dimensions and lit by sparkling tapers. Hazoret's innermost temple was arranged like a cozy traditional hearth, a place for family gatherings.
Samut cleared her throat. "Thank you, great Hazoret," she said. "But I am no initiate. Not anymore."
"#strong[Your words and your heart do not agree. Be seated.] "
Samut quickly sat, still holding her ceremonial candle.
The god gathered her legs under her in a comfortable sitting position, taking up the entire center of the hearth. "#strong[Why is it that you come to me in anguish, at a time that should be joyous?] "
Samut was unnerved by how quickly the god read her soul. She had beheld the gods before, of course, but this was the first time she had ever conversed with a divinity one-on-one. "I beg forgiveness, Fervent One. I cannot feel joyous for the Trial that is to come." Samut took a trembling breath. "My friend Djeru wishes to die. At your Trial. By your hand."
"#strong[Then you should celebrate!] " Hazoret said. "#strong[Your friend has the courage to seek the highest goal. As should you.] "
Samut's hands trembled as she cradled her candle. The tiny flame flickered, the wax melting into itself. Where was all her confidence and certainty from when she confronted Djeru? Where was her conviction that the gods had become deluded now that she had the opportunity to say it to a god's face? "I know that is what we are taught. That all must battle to win their place in the afterlife, as the viziers tell us."
"#strong[Their counsel is wise.] "
"And I—I know that Djeru would not want me to interfere in his path." She realized she was speaking more to her candle than to the god. If she was going to say this to the God of Zeal, then she would have to say it with fervor. "But I cannot abide it. He does not know the truth of the afterlife or of the Trials."
Hazoret's head tilted, and not in amusement. Her eyes were cold flames of challenge. "#strong[But you know, initiate? You know?] "
Samut bowed with shame. She opened her mouth to object, but she could not summon up the words. She was struck suddenly by how small and insolent she was, seated on a god's divan, welcomed into a god's house, present only by a god's invitation. The mighty Hazoret had shown her only supreme generosity in granting her this time, and she had brought only childish, impudent complaints. Confusing, cold tears brimmed in Samut's eyes.
The dais rumbled, as if the entire monument stirred with a low vibration. "#strong[I could strike you down for this sacrilege] ," Hazoret said. "#strong[You know this.] "
"Yes," Samut whispered.
"#strong[But it is never my wish to cage a warrior's heart. And I see that your heart yearns to fight. So fight, Initiate Samut. Fight for the truth in your heart.] "
Samut beheld the pinnacle of ferocity and grace before her. She was overcome with admiration—she longed for Hazoret to be proud of her. And by terrifying corollary, she desperately feared #emph[failing] her.
But if she did not make her request, then she would fail Djeru instead.
"I do not know the way to ask what I must ask," she said.
The ground shook. Spikes of living gold radiated from around Hazoret's face. "#strong[Does a warrior hesitate? Speak!] "
Samut bowed, and she sniffed away tears. "Great Hazoret, Keeper of the Gate," she said. "I have come to plead for Djeru's survival. I ask that when he offers you his life, that you not take it from him."
Hazoret sat back. The bright specks of her eyes wandered from Samut to the ceiling, and to some mental distance Samut could not perceive. After a time, the god looked down at Samut again. "#strong[This is a serious and woeful matter. Is this what he desires?] "
"I spoke to him, but he refused me."
"#strong[So you would alter his path, in defiance of his will? You wish to cage his heart? Would you not grant him the same favor I have granted you?] "
Every part of Samut wanted to crumple in shame. She almost tossed her dwindling candle down and fled. But the thought of Djeru bleeding on the ground flashed in her mind. She saw his life trickling out of two puncture holes—one through his head and one through his heart. Her battle-brother, fulfilling his dream of dying uselessly. The thought squeezed her heart like a fist.
"He labors under a lie."
"#strong[This initiate. Djeru. You call him a friend?] "
"I do."
"#strong[And though you see your friend's belief, that faith that inflames his heart—you would call him mistaken?] "
"I do, mighty Hazoret. But if I may . . ." Samut swallowed hard, gathering the strength to look Hazoret in the eye. "Is it possible that you are . . . also mistaken?"
Hazoret did not reply, but Samut felt the rumbling of the platform below her, and the keening of every brick in the walls around her. Shuffling sounds echoed from far down the staircase—the approaching, inexorable footfalls of summoned mummies.
Hazoret leaned in close, and suddenly the god seemed ten times larger, expanding to fill Samut's vision. Nothing existed but the jackal-face of rippling gold, hot and crackling and immediate.
Samut withered back into her cushion. But even now, even as the fervent rage of a god enveloped her, she felt consumed by an extraordinary feeling of love—Hazoret's love. In their closeness, she felt the warm generosity implicit in Hazoret's invitation, the hospitality of her hearth-like temple, the thick-walled protection of her grand home. This was Hazoret's heart. This was the Hazoret that she, perhaps, had once been. This was connection.
"Kind Hazoret," Samut whispered. "Do you remember how we once called you? The people of this world call you Gate Keeper now, and Trials' End—but also the Mother of Zeal. Nurturer of Hearts. We are your children, your family. You were not always a cruel god, poised with spear and fire at the gates of death. You were a god of compassion and inspiration, whose fiery heart inspired the people to their greatest achievements."
A glimmer of light passed across Hazoret's vast golden face, and Samut thought she saw the god momentarily withdraw by an almost imperceptible distance.
"You are zealous, yes," Samut continued. "But I fear that fervency that made you great has been twisted to make you callous. Not a celebrant of life, but an instrument of death. Is there any of that still in you? Any tiny sliver of a memory of that time before the God-Pharaoh?"
Hazoret's face hung in the air above her, roiling with majestic fire. Tears rolled down Samut's cheeks and turned to steam. She could only wait for the judgment of a god.
Then, Hazoret spoke, and the words were thunder.
"#strong[May the ammits eat the heart from your chest.] "
Hazoret stood up to her full height, sweeping away from Samut. The god's face was now remote and impassive, all intimacy shattered. Samut looked down to weep into her candle, but it had extinguished into a handful of puddled wax.
As servant mummies filled the temple, the god said her final words to Samut. The words crushed Samut's heart—not because of the promise of punishment, but from the revocation of welcome.
"#strong[Anointed] ," said the God of Zeal. "#strong[Seize the dissenter.] "
#figure(image("007_Judgment/08.jpg", width: 100%), caption: [Time to Reflect | Art by Daarken], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Samut could feel her own breath on her face. The sarcophagus was tight, its limits only a finger length from every part of her skin. Her arms had been weaved through the sleeves, leaving her hands trapped away from her body and exposed to the dry air outside. It had been hours since she had been forced in that time, and as the first sun rose in the sky, the temperature in her prison rose in tandem.
Discomfort had given its way to thirst hours ago, and she had lost her perception of time by the time thirst gave way to desperation.
Samut initially tried to force her way out. She charged a spell of speed to ram her elbows through the walls but was met only with bruises and the straining of her own bones. She wriggled and jostled, but the prison seemed to be enchanted in such a way that one could not break out from the inside.
She refused to weep. Mostly out of determination. Partly because she couldn't spare any extra water. Entirely because she knew she was exactly where she needed to be.
She realized quickly that she was not alone. To her left and right were similar sarcophagi, and inside each one was a dissenter like herself. Their heresies varied, but each had gathered enough to know that it was their duty to inform the newcomers of what would come next.
"There are no monsters in the Trial of Zeal," one to Samut's left had said, "The monsters initiates face in the final Trial are the dissenters themselves."
"Everything they tell us is a lie." Samut shook her head, temples tapping either side of her prison.
"The initiates fight dissenters and heretics to prove their faith. They'll come for us soon so we can be next."
"I think we'll be the last," says the one to Samut's right. "The second sun is hours away from its zenith."
From down the line, "May his return come quickly!"
From either side of Samut, "Shut up!"
"The God-Pharaoh is not of this world," Samut said. The others are hushed to listen. "I've seen the old temples. Our gods are true but he is not."
The others went silent. Samut's voice descended into a deadly serious tone.
"If we are to save our world when he returns I need to save the life of one acolyte."
"Why one?" said the voice to the left.
"He is strong and full of conviction," Samut replied. "If anyone could convince a god they'd been lied to, it's him. If I can convince him, he can do anything, and we can live our lives free of the trespasser's influence."
Samut knew that Djeru would hate her for this. She knew he would fight and spit and probably try to kill her for ruining his death, but it was necessary. She couldn't face this without him.
The hot day passed into frigid night, and Samut's skin chilled when she leaned against the walls of her enclosure. Sleep was a useless hope, and her muscles cramped from holding herself still and away from the cold of the sarcophagus.
They'll come in the morning. They'll take her to the arena. She'll finally convince Djeru, they'll leave alive, and the two will fight off the trespasser that ruined their world in the first place.
Her insomnia was interrupted by voices outside.
"When Nissa tried to track her it led us here—"
"Are those #emph[hands—] "
"Those weren't there before. There's people inside, hold on—"
Searing heat and a crack of light poured in through a break in the sarcophagus. The prison fell to either side, and Samut blinked away the blur. Standing in front of her were two strangers, a red-haired woman and a tall, sturdy man.
#figure(image("007_Judgment/09.jpg", width: 100%), caption: [By Force | Art by <NAME>eneuve], supplement: none, numbering: none)
These were not the people who would take her to the final Trial. This was wrong, Samut thought; she wasn't supposed to be rescued!
Samut began to run, stumbling on cramped and exhausted legs. She was stopped by the one who freed her from the cage, a man who introduced himself as Gideon. He explained that they saw her days ago evading capture and came to rescue her.
Samut wanted to laugh at his arrogance. Instead, she asked why they needed #emph[her ] of all people.
The woman alongside him introduced herself as Chandra, and asked Samut to clarify what she meant days ago when she tried to warn the public about the lies of the Hours.
Putting aside confusion over how they found her in the first place, Samut told the strangers about what she had learned. About the empty tombs, about how those who died in the Trial of Zeal were taken elsewhere, about her dance and the dead generations that came before. She watched as the two strangers shared a look, nodded, and sent for help. Eventually, three other strangers came and joined. They swapped information, took guesses at the time they needed before the God-Pharaoh's return.
Samut struggled to keep up with the names as she greeted Nissa, Liliana, and Jace in turn. She joined them to help the other dissenters out of their sarcophagi as the strangers caught each other up.
Jace focused on filling in their new acquaintance. "The God-Pharaoh is a dragon from another world, Samut. I believe he came here in a moment of desperation. Otherwise, he would have made a place himself."
Nissa told the group of what she found on the walls of Naktamun. "There used to be eight gods, now there are five. I am uncertain what happened to the other three, but the surviving gods were all tampered with to suit <NAME>'s intentions."
"They kill each other in the Trial of Ambition," Gideon said, voice heavy with confusion. "The Trials are #emph[intended ] to churn out bodies. The ones who die in the Trial of Zeal are taken to a separate place. I haven't figured out why."
Liliana took in a deep breath.
"My third demon is here."
The conversation halted at that. Samut had no idea what the woman meant, but the others had gone silent with fury.
"And you didn't #emph[tell us?] " Chandra seethed.
Nissa narrowed her eyes. "Did you #emph[ever] intend to help us with <NAME> or was this your real motivation?"
Gideon turned the group's attention to the man in blue. "Jace, did you know about this?"
The man shifted uncomfortably. ". . . It's a secondary motivation for our group. The sooner Liliana is free from her contract the sooner she can fight at full capacity—"
Nissa shook her head. "Jace, this goes against what we came here for."
Chandra cut to the point. "For someone so smart, you do an awful lot of thinking with every part of you #emph[except your brain, ] jackass—"
"Liliana, do you really expect us to drop what we came here to do and fight your battles for you?" Gideon asked looking to the woman in violet.
She tipped her chin and absent-mindedly moved her hand to her right pocket. "Yes, because you can't defeat Bolas without me!"
"Quiet!" Samut interjected. The others stared at her, fuming. She calmed her voice and looked each of the trespassers in the eye.
"I want to make one thing clear," Samut said. "We don't have time to argue. We have time to get to the Trial of Zeal and save the one person who can help me rally Naktamun. The God-Pharaoh isn't here, we won't know what he's capable of until he arrives, and every single one of you is going to help me rescue my friend because #emph[none of you have a plan to do anything otherwise] . Got it?"
Coyly, the other five each nodded.
"Good."
Gideon stepped forward. "I swear to help you save the life of your friend."
#emph[He delivers promises quickly] , Samut thought. She nodded in acceptance.
And froze.
She had felt them before she saw them.
The gods.
All of them.
In a single-file line they approached, Hazoret in the lead, the others just behind. The other four must have come to see the show, to stay together now that the God-Pharaoh was nearly here.
Samut felt compelled to still and hush. The other mortals succumbed to the same spell.
"#strong[Dissidents. Your time has come] ," Hazoret said, voice as hard as steel. "#strong[Come, and face the last initiates in the final Trial.] "
A haze overcame the group, and everything went dark.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("007_Judgment/10.jpg", width: 100%), caption: [Hazoret the Fervent (Invocation) | Art by <NAME>], supplement: none, numbering: none)
The dissidents awoke with cartouches of control hanging around their necks. They were standing, still as the dead, in the center of a great arena. Twin suns beamed down, and a sheen of sweat sat at the base of their necks.
Samut, Chandra, Jace, Gideon, Nissa, and Liliana had been forced to stand in a ring, each of them facing outward. At the far end of the arena was a great platform, and atop it stood Hazoret, God of Zeal, flanked on each side by the other four gods of Amonkhet.
The pantheon was difficult to look at. Meeting their gaze filled the dissident's hearts with shame. Only Samut locked eyes with the gods, the fire in her gut not anger at the deities, but at whoever it was that tainted them so. Her gods were good. They were #emph[good. ] What had been done to them was a sin beyond sins. Whoever the trespasser was would pay.
In the stands around them were the anointed, silent and still. The reverent quiet of the former initiates filled Samut with wary awe, their presence a reminder of the special future that awaited those who participated in the final Trial.
Standing beneath the platform of the gods were four initiates. Each tense with excitement, desperate for a victory.
While the other dissidents stood frozen by the stationary magic of the cartouches, Jace was launching a psychic assault on the cartouche around his own neck. The thing had spelled him still and mute, but his mind was free to fight against the thing.
#emph[Jace, I think I've got it.]
The white blossoms of Nissa's voice in Jace's mind caught his attention. He moved his eyes to his left and saw Nissa's hand twitch, moving willingly against the enchantment of the cartouche.
#emph[How did you do that? ] Jace asked in her mind.
She gave off the suggestion of a mental shrug. #emph[They work like leylines] , she thought. #emph[A different mana source, but the same principle.]
She didn't have time to completely dissolve the spell. Hazoret raised her spear at the end of the arena and spoke.
Her voice rung like a bell through the arena.
"#strong[Initiates. Before you are heretics, doomed souls who denied your God-Pharaoh and your way of life. Your task in this, the final Trial, is to kill each of them.] "
Samut scanned each initiate ahead of her, desperately searching for Djeru. Did he go already? Was she too late?
No. There. At the end. Djeru stood with khopesh in hand, his stance practiced and unmovable. He looked accomplished and proud and smiled with a believer's grin.
Thank the gods. He was still alive, and Samut intended to keep him that way.
Gideon spotted him at the same time she did. His stomach dropped in dread. Would he have to kill Djeru, as Djeru had mercifully murdered his crop?
Djeru, on the other hand, saw Samut and felt a rush. Of course he would face his dearest friend on this, his last day in this body. This was indeed destiny.
Hazoret brought down her spear.
"#strong[The Hours are moments away. May the final Trial begin.] "
The god held up her hand, and Hazoret's mark of battle rage appeared over their heads.
#figure(image("007_Judgment/11.jpg", width: 100%), caption: [Pursue Glory | Art by <NAME>], supplement: none, numbering: none)
Samut had studied the effects of Hazoret's magic, of course, but experiencing it was entirely different than reading about it.
She needed to fight.
She needed to win, to appease, to curb the favor of the chosen daughter of the God-Pharaoh.
Hazoret's magic was a welcome, zealous fire in their minds and a rush of strength in their limbs. All were enchanted, all were under the same spell. Each driven to maim, kill, let go of their logic and embrace Hazoret's fervor.
Conscious thought was lost.
Only the need to battle remained.
The cartouches of control vanished from the sternums of the dissenters, and with their bodies their own once more, the group of heretics surged forward.
Samut launched herself toward Djeru alongside the frenzy of dissenters also charging. The magic twisting her body and mind told her to fight and kill. Her heart reminded her of her goal.
She had to keep Djeru alive. By any means necessary.
Jace was the first to attempt to use magic. Instinctively he raised his hand, intent on crushing the mind of the initiate running toward him. When no light came, no mana rose to meet his command, his eyes went wide in surprise. The initiate rushing him bent forward, lifted, and threw Jace onto his back and knocked the air out of his lungs.
Chandra artfully leaped over Jace's body. She embraced Hazoret's magic with ease, and though fire wouldn't come to her fists, she punched and scratched at the initiate in front of her with all her might. She laughed wildly. The release felt amazing, and as the initiate fighting her grappled and kicked, Chandra dodged and volleyed. What she had in spitfire she lacked in training, however. The initiate she was facing landed a punch to her kidney and a jab to her cheek. Chandra howled in rage and tackled the initiate to the ground. Liliana joined Chandra in an instant, holding the other initiate down, her face contorted by Hazoret's fury while the two women did their best to fight without magic.
Nissa was the only one doing an adequate job of fighting without magic. She had taken a few punches from the third initiate facing her, but had lifted Jace from the ground and tossed him into her opponent. Hazoret's mark shone red and vibrant on the crown of her head as she screamed a Joragan battle cry at Jace and the initiate.
Gideon was as lost to the magic as the others. He was running, heaving, grunting with each stride toward Djeru at the other end of the arena.
Samut was faster, though. She made it to him first. Her eyes met Djeru's. Underneath the magic, she sensed his surprise.
Djeru took an instinctive swing at her with his khopesh, which Samut dodged with ease. In the span of a second, she shifted her weight and stood back-to-back with her friend.
His understanding was immediate and silent.
She would protect him. They would fight together.
Gideon, marked with magic and mad with battle lust, locked eyes with the two friends. He swung his fists with lack of practice and an abundance of muscle.
Djeru gripped his weapon tight, and his prayer began.
"Hazoret, Keeper of the Gate of the Afterlife and the favorite of the God-Pharaoh," Djeru cried.
He yelled his prayer as he moved, his practiced and masterful fighting style in perfect harmony with Samut's dynamic martial skills.
As Djeru worshiped aloud, Hazoret's eyes locked on him and Samut. The initiate's voice was full and firm, timed with the movement of battle, interspersed with breath and effort.
"Behold, mighty Hazoret, the zeal of your children!" Djeru yelled.
His khopesh ripped upward, cutting a sleek, shallow slice cut through Gideon's forearm—whites of Gideon's eyes stared at his arm like he'd never seen his own blood before—
"My final prayer in this physical form is not for myself. It is for the person who deserves your mercy the most!"
Samut's leg met the face of Gideon—she rode her momentum, followed through, easily took the man from full standing height to flat on the ground—
Djeru continued, panting with rage and effort. "Please, I beg of you, forgive Samut, my dearest friend! She is sharp in ways I am not, and her worth is proven by her talents!"
The friends locked brief eye contact—do you mean it? Yes, I do, of course, I do, Samut—two bodies moved in tandem, grappling fellow dissidents, a flawless synchronicity, khopesh and well-trained kicks dancing side by side—
"Forgive her for her trespasses! Forgive her for her doubts!" Djeru prayed through panting breath.
Gideon wiped away hot crimson and yelled, "You're throwing away your life! Why do you want to die?!" Djeru ignored it—elbowed Gideon's nose, landed a punch to his kidney, sliced his proud cheek—
"Behold Samut's faith in the old ways!" Djeru punctuates his prayer with a slice of his khopesh. "See how she has studied our past and made manifest our people's culture!"
Samut's feet cracked bones, and the caress of her hands blooms bruises—she knocks another dissident out cold as they try to stab Djeru with a spear—
"Please, grant Samut a glorified death."
The two initiates wove violence into dance. Pull, thrust, dislocate shoulder, box ears—
Djeru's earnest tears ran down the creases of fury on his face. "I could not spend my forever knowing that she no longer existed. She cannot suffer Nakht's fate."
Hazoret's spell began to wear off. Time slowed down. Color returned, senses regained, Samut stopped. Djeru was alive. How does she keep him that way?
Djeru concluded with his khopesh on the ground, a formal surrender. "Hear my prayer, Hazoret!"
"#strong[I do, Djeru.] "
The battle magic dissipates.
Djeru's prayer ended.
The god Hazoret stood tall at the end of the arena.
"#strong[Come forward, Djeru and Samut.] "
Around them was spatters of blood, the bodies of three initiates (head turned sideways, throat parted, thrown body discarded into the crowd). The strangers known as the Gatewatch were alive, blinking, confused, realizing they had access to their magic again.
Djeru took Samut's hands in his during the brief silence. "Samut, I choose this death."
Samut shook her head. "I need you to help me defeat the greatest trespasser. I need you to help me, and I cannot do it if your soul is not here."
"I will see you in paradise, my friend."
Samut's eyes closed in defeat.
Djeru turned toward Hazoret and approached.
The arena seemed to stretch on and on, time itself stopped as he walked in silence across the dust and stone. Djeru's existence had been condensed to walking this line, to willing one foot in front of the other so he could receive his gift.
Samut couldn't wait. She couldn't stand idly by. Not after everything she'd done to convince him to stay alive.
#strong[Please approach, Samut, daughter of our past. ] Hazoret's voice was a warm crackling fire in Samut's mind. She followed Djeru and found herself standing alongside her friend in front of the god.
Hazoret looked down, looked through the two initiates. She spoke to Djeru first.
"#strong[You did not kill the remaining dissenters.] "
Djeru swallowed. "A dissenter's death is not one to be found in the final Trial. They do not know our ways."
Hazoret moved her head back slightly in approval.
"#strong[Will you claim your place among the eternal, Djeru?] "
Tears rolled down Djeru's cheeks. A glorious death was all he ever wanted, all he ever desired. He nodded. He would have his place. His death would #emph[mean something.]
Samut's heart sunk further with the knowledge of what she had to do. Djeru would never forgive her. How could he?
Hazoret looked to Samut.
"#strong[Your worth is only proven if your faith is true, Samut. Will you receive my gift?] "
Without hesitation, she shook her head.
"The greatest trespasser is nearly here," she said, voice cracking, eyes locked with Hazoret's. "I have work to do."
Hazoret gave a small, disappointed sigh. Djeru only stared, eyes wide in shock and disappointment. He couldn't answer. He only swallowed and squeezed her shoulder. A silent farewell.
It was too much.
Samut let out a shaky breath. "I am sorry, my friend. Please forgive me, someday."
Her apology was met with a crease of confusion on Djeru's brow.
"#strong[Approach, Djeru.] "
Djeru stepped forward and closed his eyes in reverence. He kneeled and outstretched his arms.
Hazoret raised her spear, and Samut steeled her will.
He had to live. He #emph[had ] to live. There was no turning back. Samut wasn't losing a friend again to a meaningless death. Samut dug in her heel and loosened her stance, charging a spell of speed and timing her impending intervention as Hazoret's spear pulled back.
The god released, and Samut leaped.
#figure(image("007_Judgment/12.jpg", width: 100%), caption: [Gideon's Intervention | Art by Daarken], supplement: none, numbering: none)
It happened in a flash.
Samut kicked off and tackled Djeru from the side, knocking him to the ground at the same time a great #emph[CLANG] and a burst of gold erupted behind her.
As Samut hit the ground, she realized that the noise had come from Gideon behind her. He stood between them and Hazoret's spear, silky golden magic forming a barrier between himself and death.
#emph[He keeps his word] , Samut thought with the briefest of smiles.
That mirth was instantly crushed by the wide-eyed surprise of her friend, pinned beneath her to the stone floor of the arena.
Samut wanted desperately to look away. Couldn't look away. Her betrayal was manifest on the face of her best friend. Djeru shook with fury.
"How #emph[could you?] "
"Djeru, I know this isn't what you wanted—"
"How COULD YOU!"
He shoved her off and swung a punch, which she dodged as easily as she would a falling feather. Tears welled up in Djeru's eyes as the gods in the arena each gave a sudden gasp.
There, above them all, the second sun was beginning to pass through the horns on the horizon, its long-awaited cycle at last at its end.
Djeru took no notice. He tried to grapple with an unwilling Samut, his heaves of agony giving way to open sobs.
The gods began to walk towards the exit of the arena, their attention focused skyward.
Only Hazoret stayed behind, oddly stunned by what had just happened. She held her spear in uncertain hands.
A distracted Gideon stared at Hazoret in fright, jaw slack and eyes wide. He looked down in confusion, then turned to Djeru.
"Djeru," he said, "she was going to k—"
"I KNOW WHAT SHE WAS GOING TO DO!" Djeru spat, his face contorted in fury. He shoved Samut to the side and launched himself at the man. Gideon's invulnerability shimmered with each blow, his face twisted in pathetic confusion beneath the soft golden light of his magic. He didn't try to block the blows, and only let Djeru continue pummeling blow after blow.
"That was my chance, and now it's GONE! IT'S GONE, YOU BASTARD!"
Gideon only shook his head in disbelief behind his golden glittering shroud of protection. Samut could see that his natural resistance only made Djeru all the more furious. She could see how he wanted to crush that barrier, break it, stab through and eviscerate, rip through the trespasser's tendons and smear his enchantment with the contents of his intestines. Samut felt pity, but not regret. She knew how angry he would be. She knew that she and this stranger had ruined her best friend's life.
Gideon held up his hands at last to stop Djeru's attack. He did not touch him but instead backed off.
"Why do you want to die?!"
"Because I want to exist!" Djeru exclaimed in a sob.
He fell to his knees and wept.
The air stilled. The only sound in the arena was that of the defeated warrior. The other trespassers watched, silent, from afar. Samut's heart sank. Of course that was his fear. After what became of Nakht, how could it be anything else?
His mourning echoed off the hundreds of anointed in the stands. The world had ceased to exist, and all that was left was his failure. The pantheon of gods behind Hazoret had left. They needed to be at the Luxa River. The Hours had almost begun.
Samut's hands went to Djeru's shoulders as he lamented.
She leaned in, and in a voice quiet and small, she whispered.
"We have so much work left to do and so many people left to help. Your training was for #emph[that] , not for this."
Djeru couldn't answer. He could only weep.
Samut kept whispering, "We get to grow old together, Djeru. And someday, a long time far from now, our people will live long, full lives, and only then we will walk into the afterlife side by side. I'm sorry you did not get what you wanted, but I am thankful you are here." She kissed Djeru's forehead in gratitude.
He only grieved. Samut squeezed his shoulder.
"Please, Djeru, you need to get up now."
It took a moment, but he did.
He took a single, steeled look at Gideon, whose eyes darted to the ground.
#strong[You intervened] #emph[, ] a warm voice said in Samut's mind. She looked up and met the golden gaze of Hazoret. Samut nodded.
#strong[What do you have to say for yourself?]
#emph[I believe in you, Giver of Gifts, ] Samut prayed. #emph[I believe that you are ] not #emph[what you are forced to do. And that you will protect your children when we need you the most.]
Hazoret stood still. Uncertain. Her ears twitched and caught the light of two suns.
"The Hours have begun, Hazoret," Samut finally said aloud.
A loud droning blast, like that of an ancient horn, echoed through the city and against the stands of the arena.
Samut, the Gatewatch, Hazoret, and the utterly crushed Djeru looked to the sky as a shadow overcame them all, like a cloud passing overhead.
The shadow cast by the second sun began to wipe a slow line of darkness across the stadium. They all stood still and watched as the line passed at the speed of a gentle walk from one side . . . to the other.
The shift in light settled and their eyes adjusted. The world was now half-dark, a grim saturation of what it was before.
"#strong[It has begun. The Hours have begun!] " Hazoret stepped #emph[over ] Samut, Djeru, and Gideon, her eyes trained on the light glinting past either side of the structure on the horizon.
"Get up, Djeru, we need to go." Samut pulled Djeru to his feet.
Djeru wiped his wet face. "There is a chance. If the Hours have begun, the God-Pharaoh will still deliver us."
Samut shook her head and kept her mouth shut. The chill from the second sun's shadow raised her flesh.
She shivered from the cold.
Outside of the arena, they heard a crowd yelling and crying, stampeding as quickly as they could to the banks of the Luxa River. The Gate to the Afterlife lay at the end. According to the first prophecy in the Accounting of the Hours, the gate would open when the second sun entirely sat between the horns, revealing the promise of the God-Pharaoh.
"Djeru, we need to run. We need to make sure as many people survive the next few hours as possible."
The second sun had never set, but now that it cast a shadow on the entire city, everything was half-dark. Everything was cold. Djeru had never felt #emph[cold ] before.
"Samut, we need to go to the river. The Hours begin with the opening of the Gate to the Afterlife. He is coming. The God-Pharaoh will show me mercy!" Djeru began running toward the exit of the arena, toward the mass of reverent citizens outside.
Liliana, Jace, Chandra, and Nissa bolted for the exit.
Gideon held behind.
He looked at his forearm and watched a rivulet of his own blood run down to his thumb.
Distantly, he knew he should run and keep up with the others. But he was transfixed, staring at the wound Djeru had sliced through his arm.
The blood ran thick and dark in the gloom of the single sun. It slid easily down.
Gideon's heart beat an anxious rhythm in his chest.
Hazoret had whispered in his mind the moment he stood between her and Djeru. Her words repeated in his mind, looping over and over with the rhythm of his panicking heart.
#strong[I am neither the first nor the last immortal whom you will cross.]
#strong[Cursed is the man who forgets his own past,]
#strong[for I see your death, <NAME>.]
#strong[You are no god.]
Gideon shivered at those words and watched the blood of his arm hit the stone below.
He looked to the sun passing behind the horn of the immense monument in the distance, and the indestructible man felt only a bleak and empty horror.
|
|
https://github.com/loicreynier/sandbox | https://raw.githubusercontent.com/loicreynier/sandbox/main/typst-demo/main.typ | typst | The Unlicense | #import "template.typ": conf
#let abstract = [
Isotropic turbulence generated by dragon's fire breath
is a captivating phenomenon that has intrigued researchers for centuries.
In this study,
we delve into the intriguing world of mythical creatures by investigating
the energy spectra of two distinct dragon species
--- wyverns and traditional dragons ---
shedding light on their unique characteristics and underlying mechanisms.
Utilizing advanced mathematical formulations,
we aim to shed light on the underlying physics
and gain insights into the unique properties of their turbulent fire flows.
]
#show: doc => conf(title: "
Feeding the Flame: Exploring the Mysteries of
Isotropic Turbulence from Dragon's Fire
", authors: ((
name: "<NAME>",
affiliation: "Medmora Drake University",
email: "<EMAIL>",
),), abstract: abstract, doc)
= Introduction
Within the realms where dragons soar the skies and breathe fire,
the awe-inspiring spectacle of their fiery breath
has inspired legends and inspired scientific curiosity for generations.
Isotropic turbulence,
the mesmerizing fluid behavior characterized by energy cascades across scales,
is at the heart of this phenomenon.
This study ventures into the magical world of dragons to examine
the isotropic turbulence in the fire breath of wyverns and traditional dragons,
providing unprecedented insights through the formulation of energy spectra
= Methodology
To explore the mysteries of dragon fire breath,
a harmonious collaboration between dragon scholars and human researchers is fostered.
Wyverns and traditional dragons, hailing from diverse regions,
are closely observed in their natural habitats.
Advanced magical imaging techniques, augmented with human technology,
capture the turbulent dynamics of their fire breath.
Incorporating the essence of dragon magic,
we derive formulae for the energy spectra of their fiery exhalations.
= Energy Spectra Formulations
In the realm of wyverns,
their fire energy spectrum,
denoted $E_upright(W)$,
is expressed by the mystical formula
$ E_upright(W)(k) = A_upright(W) k^(-5/3) exp(-k/k_0), $ <wyvern_spectra>
where
$k$ is the wavenumber representing the scale of turbulence,
$A_upright(W)$ is a dragon-specific constant
and $k_0$ is the characteric wavenumber indicating the peak energy scale.
For traditional dragons, their fire energy spectrum,
denoted as $E_upright(D)(k)$,
embodies a more intricate nature and is represented by the enchanted formula
$ E_upright(D)(k)
= A_upright(D) k^(-5/3) + B_upright(D) k^(-2) exp(-k/k_0), $ <dragon_spectra>
where
- $A_upright(D)$ is a unique constant tied to the dragon's ancient lineage,
- $B_upright(D)$ represents the influence of rare dragon traits,
- $k_0$ retains its significance as the characteristic wavenumber.
= Data Collection and Analysis
Magical energy measurements,
facilitated by the harmonious blend of dragon magic and human instrumentation,
are collected during dragons' fire-breathing events.
The collected data undergo meticulous spectral analysis
using state-of-the-art methods involving dragon-enchanted Fourier Transform techniques.
= Results
The spectral analyses of wyverns' and traditional dragons' fire breath
reveal captivating distinctions.
Wyverns' fire exhibits a well-defined inertial subrange in the energy spectrum,
consistent with the classical $-5/3$ power-law scaling predicted by Kolmogorov turbulence theory.
In contrast,
traditional dragons' fire unveils a fascinating dual-cascade behavior,
characterized by $-5/3$ scaling at large scales and $-2$ scaling at small scales.
This unique dual-cascade phenomenon suggests
an intriguing interplay of elemental forces and mythical intricacies.
= Discussion
The distinct energy spectra observed
in wyverns' and traditional dragons' fire breath
lead us to contemplate the underlying magical processes
governing their fiery abilities.
Variations in dragon physiology,
elemental composition,
and ancient lineage are proposed
as factors influencing the energy transfer mechanisms,
giving rise to the contrasting turbulence behaviors.
= Conclusion
By formulating energy spectra for wyverns' and traditional dragons' fire breath,
this study provides a deeper understanding of the isotropic turbulence
at play in their awe-inspiring abilities.
The enchanting discoveries made in this study transcend the boundaries of the magical realm
and hold profound implications for scientific understanding.
The formulation of energy spectra and the revelation of dual-cascade behaviors
can inspire advancements in fluid dynamics, combustion science, and energy generation research.
Moreover,
this exploration of isotropic turbulence in dragon fire breath
may spark novel applications in sustainable energy harnessing and environmental studies.
The harmonious alliance between dragon magic and human science offers
a unique gateway to exploring the enigmatic dynamics of these mythical creatures,
enriching both realms with newfound wisdom and wonder.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/bone-resume/0.1.0/README.md | markdown | Apache License 2.0 | # bone-resume
This is a Typst template.
## Usage
You can use this template in the Typst web app by clicking "Start from template"
on the dashboard and searching for `bone-resumee`.
Alternatively, you can use the CLI to kick this project off using the command
```
typst init @preview/bone-resume
```
Typst will create a new directory with all the files needed to get you started.
## Configuration
This template exports the `resume-init` function with the following named arguments:
- `authors`: Your name.
- `title(optional)`: The resume's title as content.
- `footer(optional)`: The resume's footer as content.
The function also accepts a single, positional argument for the body of the
paper.
The template will initialize your package with a sample call to the `bone-resume`
function in a show rule. If you want to change an existing project to use this
template, you can add a show rule like this at the top of your file:
```typ
#import "@preview/bone-resume:0.1.0": bone-resume
#show: bone-resume.with(
author: "六个骨头"
)
= 个人介绍
A Student.
// Your content goes below.
```
|
https://github.com/veilkev/jvvslead | https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/1_system.typ | typst | #import "../sys/packages.typ": *
#import "../sys/sys.typ": *
#import "../sys/header.typ": *
#set align(center)
// #show raw.where(lang: "pintora"): it => pintorita.render(it.text)
= Office Functions
An overview
#let renderc(code) = render(code.text)
#renderc(
```
digraph {
"Point of Sale" -> "Office Manager Menu (F5x2)"
"Office Manager Menu (F5x2)" -> "Office Checker Menu (F5x1)"
"Office Checker Menu (F5x1)" -> "Office Manager Menu (F5x2)"
"Office Functions" -> "Office Manager Menu (F5x2)"
"Office Functions" -> "Office Checker Menu (F5x1)"
"Main Menu" -> "Office Functions"
}
```
)
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/compiler/embedded-expr.typ | typst | Apache License 2.0 | // Test embedded expressions.
// Ref: false
---
// Error: 6-8 expected identifier, found keyword `as`
// Hint: 6-8 keyword `as` is not allowed as an identifier; try `as_` instead
#let as = 1 + 2
---
#{
// Error: 7-9 expected identifier, found keyword `as`
// Hint: 7-9 keyword `as` is not allowed as an identifier; try `as_` instead
let as = 10
}
---
// Error: 2-2 expected expression
#
---
// Error: 2-2 expected expression
# hello
|
https://github.com/RanolP/resume | https://raw.githubusercontent.com/RanolP/resume/main/README.md | markdown | <picture>
<source media="(prefers-color-scheme: dark)" srcset="./cover/page-dark-1.svg">
<source media="(prefers-color-scheme: light)" srcset="./cover/page-light-1.svg">
<img src="./cover/page-light-1.svg">
</picture>
# résumé
Modern résumé built with Typst
## Dev Environment
- Use VS Code for editor (contains recommended extension and settings).
- Use mise or asdf-compatible version manager and activate here.
- Run `./scripts/src/prebuild.ts` when you need and compile it with `typst compile resume.typ`.
## Special Thanks
- [shiftpsh](https://github.com/shiftpsh) for his impressive cv design and the [solved.ac](https://solved.ac) service
- [Open Color](https://yeun.github.io/open-color/) for good palette
- [Icones](https://icones.js.org/) for easier icon search
- [Iconify](https://iconify.design/) for icon CDN
- [Typst](https://typst.app/) for awesome markup language
|
|
https://github.com/smorad/um_cisc_7026 | https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_2_linear_regression.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.university: *
#import "@preview/cetz:0.2.2": canvas, draw, plot
#import "common.typ": *
// Translate setup:
// Open slidepilot and start presentation (present on new screen)
// Make it not full screen
// Open OBS
// Right click video, full-screen projector preview
#set text(size: 25pt)
#show: university-theme.with(
aspect-ratio: "16-9",
short-title: "CISC 7026: Introduction to Deep Learning",
short-author: "<NAME>",
short-date: "Lecture 2: Linear Regression"
)
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#let side-by-side(columns: none, gutter: 1em, align: center + horizon, ..bodies) = {
let bodies = bodies.pos()
let columns = if columns == none { (1fr,) * bodies.len() } else { columns }
if columns.len() != bodies.len() {
panic("number of columns must match number of content arguments")
}
grid(columns: columns, gutter: gutter, align: align, ..bodies)
}
#let cimage(..args) = {
align(center + horizon, image(..args))
}
#let log_plot = canvas(length: 1cm, {
plot.plot(size: (8, 6),
x-tick-step: none,
y-tick-step: none,
{
plot.add(
domain: (0, 25),
x => calc.log(1 + x),
label: $ log(1 + x) $
)
})
})
#let argmin_plot = canvas(length: 1cm, {
plot.plot(size: (8, 6),
x-tick-step: 1,
y-tick-step: 2,
{
plot.add(
domain: (-2, 2),
x => calc.pow(1 + x, 2),
label: $ (x + 1)^2 $
)
})
})
#title-slide(
// Section time: 34 mins at leisurely pace
title: [Linear Regression],
subtitle: "CISC 7026: Introduction to Deep Learning",
institution-name: "University of Macau",
//logo: image("logo.jpg", width: 25%)
)
#slide(title: [Participation])[
I need the class to ask questions when they do not understand #pause
I need the class to answer my questions, so I know that you understand #pause
If you ask/answer questions I will give the class 100% participation grade #pause
Otherwise, I will have to grade students individually on participation #pause
You will make name tags, and I will count each time you participate
]
/*
#slide(title: [Participation])[
Everyone take out paper and a pen #pause
Fold the paper into thirds, and write your full name in English and your student ID #pause
I will record when you *ask good questions* or *answer questions* #pause
Participate once: ok participation grade #pause
Participate more than once: perfect participation grade
]
*/
#slide(title: [Agenda])[
+ Review #pause
+ Quiz #pause
+ Linear Regression
]
#slide(title: [Agenda])[
+ *Review*
+ Quiz
+ Linear Regression
]
#slide(title: [Review])[
We often know *what* we want, but we do not know *how* #pause
We have many pictures of either dogs or muffins $x in X$ #pause
We want to know if the picture is [dog | muffin] $y in Y$ #pause
We learn a function or mapping from $X$ to $Y$
]
#slide(title: [Review])[
#text(size: 23pt)[
Why do we call it machine *learning*? #pause
We learn the function $f$ from the *data* $x in X, y in Y$ #pause
More specifically, we learn function *parameters* $Theta$ #pause
$ f: X times Theta |-> Y $ #pause
$ f("你好吗", vec(theta_1, theta_2, dots.v)) = "You good?" $ #pause
$ x = "你好吗", quad X = "Chinese sentences" $ #pause
$ y = "You good?", quad Y = "English sentences" $
]
]
#slide(title: [Review])[
Create vectors, matrices, or tensors in `jax`
```python
import jax.numpy as jnp
a = jnp.array(1) # Scalar
b = jnp.array([1, 2]) # Vector
C = jnp.array([[1,2], [3,4]]) # 2x2 Matrix
D = jnp.ones((3,3,3)) # 3x3x3 Tensor
```
You can determine the dimensions of a variable using `shape`
```python
b.shape # Prints (2,)
C.shape # Prints (2,2)
D.shape # prints (3,3,3)
```
]
#slide(title: [Review])[
Create vectors, matrices, or tensors in `pytorch`
```python
import torch
a = torch.tensor(1) # Scalar
b = torch.tensor([1, 2]) # Vector
C = torch.tensor([[1,2], [3,4]]) # 2x2 Matrix
D = torch.ones((3,3,3)) # 3x3x3 Tensor
```
You can determine the dimensions of a variable using `shape`
```python
b.shape # Prints (2,)
C.shape # Prints (2,2)
D.shape # prints (3,3,3)
```
]
#slide(title: [Review])[
```python
import jax.numpy as jnp
s = 5 * jnp.array([1, 2])
print(s) # jnp.array(5, 10)
x = jnp.array([1, 2]) + jnp.array([3, 4])
print(x) # jnp.array([4, 6])
y = jnp.array([1, 2]) * jnp.array([3, 4]) # Careful!
print(y) # jnp.array([3, 8])
z = jnp.array([[1], [2]]) @ jnp.array([[3, 4]])
print(z) # A^t B (dot product), jnp.array([[11]])
```
]
#slide(title: [Review])[
`pytorch` is very similar to `jax`
```python
import torch
s = 5 * torch.tensor([1, 2])
print(s) # torch.tensor(5, 10)
x = torch.tensor([1, 2]) + torch.tensor([3, 4])
print(x) # torch.tensor([4, 6])
y = torch.tensor([1, 2]) * torch.tensor([3, 4]) # Careful!
print(y) # torch.tensor([3, 8])
z = torch.tensor([[1], [2]]) @ torch.tensor([[3, 4]])
print(z) # A^t B (dot product), torch.tensor([[11]])
```
]
#slide(title: [Review])[
You can also call various methods on arrays/tensors
```python
import jax.numpy as jnp
x = jnp.array([[1, 2], [3, 4]]).sum(axis=0)
print(x) # Sum across leading axis, array([4, 6])
y = jnp.array([[1, 2], [3, 4]]).mean()
print(y) # Mean across all axes, array(2.5)
z = jnp.array([[1, 2], [3, 4]]).reshape((4,))
print(z) # jnp.array([1, 2, 3, 4])
```
]
#slide(title: [Review])[
Same thing for `pytorch`
```python
import torch
x = torch.tensor([[1, 2], [3, 4]]).sum(axis=0)
print(x) # Sum across leading axis, array([4, 6])
y = torch.tensor([[1, 2], [3, 4]]).mean()
print(y) # Mean across all axes, array(2.5)
z = torch.tensor([[1, 2], [3, 4]]).reshape((4,))
print(z) # torch.tensor([1, 2, 3, 4])
```
]
// Review 8 mins
#slide(title: [Agenda])[
+ *Review*
+ Quiz
+ Linear Regression
]
#slide(title: [Agenda])[
+ Review
+ *Quiz*
+ Linear Regression
]
#slide(title: [Quiz])[
Time for a quiz! #pause
All laptops and phones away #pause
Everyone take out paper and pen, write your name and student ID #pause
I will explain the questions, then you have *15 minutes* to answer the questions #pause
You are not expected to answer all questions correctly, do not stress! #pause
]
#slide(title: [Quiz])[
*Q1:* What is the function signature for machine learning?
$ quad "___" : "_______" quad |-> quad "___" $
*Q2:* What does the following code print?
```python
jnp.array([1, 2]) * jnp.array([2, 1]) + jnp.array([5, 6])
```
*Q3:* What does the following code print?
```python
jnp.array([[1, 2], [3, 4]]).sum(axis=1)
```
*Q4:* What does the following code print?
```python
torch.arange(4)
```
]
#slide(title: [Quiz])[
*Q1:* What is the function signature for machine learning? #pause
*A1:* $f: X times Theta |-> Y$ #h(2em) $f: X, Theta |-> Y$ also ok. #pause
*Q2:* What does the following code print?
```python
jnp.array([1, 2]) * jnp.array([2, 1]) + jnp.array([5, 6])
``` #pause
`[1 * 2 + 5, 2 * 1 + 6]` #pause
*A2:* `Array([7, 8], dtype=int32)`, #h(2em) `[7, 8]` also ok
]
#slide(title: [Quiz])[
*Q3:* What does the following code print?
```python
jnp.array([[1, 2], [3, 4]]).sum(axis=1)
``` #pause
`[1 + 2, 3 + 4]` #pause
*A3:* `Array([3, 7], dtype=int32)`, #h(2em) `[3, 7]` also ok #pause
*Q4:* What does the following code print?
```python
jnp.arange(4)
``` #pause
*A4:* `Array([0, 1, 2, 3], dtype=int32)`, `[0, 1, 2, 3]` also ok
]
// 15 + 15 = 30 mins no questions
#slide(title: [Agenda])[
+ Review
+ *Quiz*
+ Linear Regression
]
#slide(title: [Agenda])[
+ Review
+ Quiz
+ *Linear Regression*
]
#slide(title: [Linear Regression])[
Today, we will learn about linear regression #pause
Probably the oldest method for machine learning (Gauss and Legendre) #pause
#cimage("figures/lecture_1/timeline.svg", height: 55%) #pause
Neural networks share many similarities with linear regression
]
#slide(title: [Linear Regression])[
Many problems in ML can be reduced to *regression* or *classification* #pause
*Regression* asks how many #pause
- Given my parents height, How tall will I be? #pause
- Given the rain today, how much rain will there be tomorrow? #pause
- Given a camera image, how far away is this object? #pause
*Classification* asks which one #pause
- Is this image of a dog or muffin? #pause
- Given the rain today, will it rain tomorrow? Yes or no? #pause
- Given a camera image, what color is this object? Yellow, blue, red, ... ? #pause
Let us start with regression
]
#slide(title: [Linear Regression])[
Today, we will come up with a regression problem and then solve it! #pause
+ Define an example problem #pause
+ Define our linear model $f$ #pause
+ Define a loss function $cal(L)$ #pause
+ Use $cal(L)$ to learn the parameters $theta$ of $f$ #pause
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ *Define an example problem*
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Example Problem])[
The World Health Organization (WHO) has collected data on life expectancy #pause
#cimage("figures/lecture_2/who.png", height: 60%)
#text(size: 14pt)[Available for free at #link("https://www.who.int/data/gho/data/themes/mortality-and-global-health-estimates/ghe-life-expectancy-and-healthy-life-expectancy")
]
]
#slide(title: [Example Problem])[
The WHO collected data from roughly 3,000 people from 193 countries #pause
For each person, they recorded: #pause
- Home country #pause
- Alcohol consumption #pause
- Education #pause
- Gross domestic product (GDP) of the country #pause
- Immunizations for Measles and Hepatitis B #pause
- How long this person lived #pause
We can use this data to make future predictions
]
#slide(title: [Example Problem])[
Since everyone here is very educated, we will focus on how education affects life expectancy #pause
There are studies showing a causal effect of education on health #pause
- _The causal effects of education on health outcomes in the UK Biobank._ Davies et al. _Nature Human Behaviour_. #pause
- By staying in school, you are likely to live longer
]
#slide(title: [Example Problem])[
*Task:* Given your education, predict your life expectancy #pause
$X in bb(R)_+:$ Years in school #pause
$Y in bb(R)_+:$ Age of death #pause
Each $x in X$ and $y in Y$ represent a single person #pause
*Approach:* Learn the parameters $theta$ such that
$ f(x, theta) = y; quad x in X, y in Y $ #pause
*Goal:* Given someone's education, predict how long they will live
]
// 40:00
#slide(title: [Linear Regression])[
+ *Define an example problem*
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ *Define our linear model $f$*
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Model])[
Soon, $f$ will be a deep neural network #pause
For now, it is easier if we make $f$ a *linear function* #pause
#align(center, grid(
columns: 2,
align: center,
column-gutter: 2em,
$ f(x, bold(theta)) = f(x, vec(theta_1, theta_0)) = theta_1 x + theta_0 $,
cimage("figures/lecture_2/example_regression_graph.png", height: 50%)
)) #pause
Now, we need to find the parameters $bold(theta) = vec(theta_1, theta_0)$ that makes $f(x, bold(theta)) = y$
// To do this, we will need to find a *loss function* $cal(L)$
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ *Define our linear model $f$*
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ *Define a loss function $cal(L)$*
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Loss Function])[
Now, we need to find the parameters $bold(theta) = vec(theta_1, theta_0)$ that make $f(x, bold(theta)) = y$ #pause
How do we find $bold(theta)$? (Hint: We want $f(x, bold(theta)) = y$) #pause
We will minimize the *loss* (error) between $f(x, bold(theta))$ and $y$, for all
$ x in X, y in Y $
]
#slide(title: [Loss Function])[
We compute the loss using the *loss function* #pause
$ cal(L): X^n times Y^n times Theta |-> bb(R) $ #pause
// $ cal(L)(x, y, bold(theta)) $ #pause
The loss function tells us how close $f(x, bold(theta))$ is to $y$ #pause
By *minimizing* the loss function, we make $f(x, bold(theta)) = y$ #pause
There are many possible loss functions, but for regression we often use the *square error* #pause
$ "error"(y, hat(y)) = (y - hat(y))^2 $
]
#slide(title: [Loss Function])[
//$ f(x, vec(theta_2, theta_1)) = W x + b $ #pause
Let's derive the error function #pause
#side-by-side[
$ f(x, bold(theta)) = y $
][
f(x) should predict y
] #pause
#side-by-side[
$ f(x, bold(theta)) - y = 0 $
][
Move y to LHS
] #pause
#side-by-side[
$ (f(x, bold(theta)) - y)^2 = 0 $
][
Square for minimization
] #pause
#side-by-side[
$ "error"(f(x, bold(theta)), y) = (f(x, bold(theta)) - y)^2 $
][
]
/*
#side-by-side[
$ 1/2 (f(x, bold(theta)) - y)^2 = 0 $
][
Scale by a constant
]
#side-by-side[
$ cal(L)(x, y, bold(theta)) = 1/2 (f(x, bold(theta)) - y)^2 $
][
This is our loss function!
] #pause
*/
]
#slide(title: [Loss Function])[
We can write the loss function for a single datapoint $x_i, y_i$ as
$ cal(L)(x_i, y_i, bold(theta)) = "error"(f(x_i, bold(theta)), y_i) = (f(x_i, bold(theta)) - y_i)^2 $ #pause
*Question:* Will this $cal(L)$ give us a good prediction for all possible $x$? #pause
*Answer:* No! We only consider a single datapoint $x_i, y_i$. We want to learn $bold(theta)$ for the entire dataset, for all $x in X, y in Y$
]
#slide(title: [Loss Function])[
For a single $x_i, y_i$:
$
cal(L)(x_i, y_i, bold(theta)) = "error"(f(x_i, bold(theta)), y_i) = (f(x_i, bold(theta)) - y_i)^2
$ #pause
For the entire dataset:
$ bold(x) = mat(x_1, x_2, dots, x_n)^top, bold(y) = mat(y_1, y_2, dots, y_n)^top $ #pause
#text(size: 22pt)[
$
cal(L)(bold(x), bold(y), bold(theta)) = sum_(i=1)^n "error"(f(x_i, bold(theta)), y_i) = sum_(i=1)^n (f(x_i, bold(theta)) - y_i)^2
$
] #pause
When $cal(L)(bold(x), bold(y), bold(theta))$ is small, then $f(x, bold(theta)) approx y$ for the whole dataset!
//Minimizing this loss function will give us the optimal parameters for the entire dataset!
]
// 50 mins
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ *Define a loss function $cal(L)$*
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ *Use $cal(L)$ to learn the parameters $theta$ of $f$*
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Optimization])[
Here is our loss function:
$ cal(L)(bold(x), bold(y), bold(theta)) = sum_(i=1)^n "error"(f(x_i, bold(theta)), y_i) = sum_(i=1)^n (f(x_i, bold(theta)) - y_i)^2 $ #pause
When $cal(L)(bold(x), bold(y), bold(theta))$ is small, then $f(x, bold(theta)) approx y$ for the whole dataset! #pause
We want to find parameters $bold(theta)$ that make the loss small #pause
Let us state this more formally
]
#slide(title: [Optimization])[
Our objective is to *minimize* the loss, using $argmin$ #pause
$argmin_x f(x)$ means find the $x$ that makes $f(x)$ smallest #pause
#side-by-side[*Question:* $ "What is " argmin_(x) (x + 1)^2 $ ][ #argmin_plot] #pause
*Answer:* $argmin_(x) (x + 1)^2 = -1$, where $f(x) = 0$
]
#slide(title: [Optimization])[
Formally, our objective is to find the $argmin$ of the loss
$
argmin_bold(theta) cal(L)(bold(x), bold(y), bold(theta)) &= argmin_bold(theta) sum_(i=1)^n "error"(f(x_i, bold(theta)), y_i) \ &= argmin_bold(theta) sum_(i=1)^n (f(x_i, bold(theta)) - y_i)^2
$
]
#slide(title: [Optimization])[
$
argmin_bold(theta) cal(L)(bold(x), bold(y), bold(theta)) &= argmin_bold(theta) sum_(i=1)^n "error"(f(x_i, bold(theta)), y_i) \ &= argmin_bold(theta) sum_(i=1)^n (f(x_i, bold(theta)) - y_i)^2
$ #pause
*Question:* How do we evaluate this expression to find $bold(theta)$? #pause
*Answer:* Deriving the solution for this objective requires taking partial derivatives of matrices #pause
We will derive the solution later. For now, trust me! #pause
We will go over the steps to find $bold(theta)$
]
#slide(title: [Optimization])[
First, we will construct a *design matrix* $bold(X)_D$ containing input data $x$ #pause
$ bold(X)_D = mat(bold(x), bold(1)) = mat(x_1, 1; x_2, 1; dots.v, dots.v; x_n, 1) $
]
#slide(title: [Optimization])[
#text(size: 22pt)[
We add the column of ones so that we can multiply $bold(X)_D$ with $bold(theta)$ to get a linear function $theta_1 x + theta_0$ evaluated at each data point
$ bold(X)_D bold(theta) = mat(x_1, 1; x_2, 1; dots.v, dots.v; x_n, 1) vec(theta_1, theta_0) = underbrace(vec(theta_1 x_1 + theta_0, theta_1 x_2 + theta_0, dots.v, theta_1 x_n + theta_0), "Predicted" y) $
We can also evaluate our model for new datapoints #pause
$ bold(X)_D bold(theta) = mat(x_"Steven", 1) vec(theta_1, theta_0) = underbrace(vec(theta_1 x_"Steven" + theta_0), "Predicted" y) $
]
]
#slide(title: [Optimization])[
#side-by-side[
With our design matrix $bold(X)_D$ and desired output $bold(y)$,
][
$ bold(X)_D = mat(x_1, 1; x_2, 1; dots.v, dots.v; x_n, 1), bold(y) = vec(y_1, y_2, dots.v, y_n) $
] #pause
#side-by-side[
and our parameters $bold(theta),$
][ $ bold(theta) = vec(theta_1, theta_0), $] #pause
#v(2em)
#side-by-side[$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $ ][(Magic!) We can find the parameters that minimize $cal(L)$]
]
#slide(title: [Optimization])[
To summarize: #pause
The $bold(theta)$ given by
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $ #pause
Provide the solution to
$
argmin_bold(theta) cal(L)(bold(x), bold(y), bold(theta)) &= argmin_bold(theta) sum_(i=1)^n "error"(f(x_i, bold(theta)), y_i) \ &= argmin_bold(theta) sum_(i=1)^n (f(x_i, bold(theta)) - y_i)^2
$
]
// 55:00, maybe 60:00 with more slides?
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ *Use $cal(L)$ to learn the parameters $theta$ of $f$*
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ *Solve the example problem*
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
Back to the example... #pause
*Task:* Given your education, predict your life expectancy #pause
$X in bb(R)_+:$ Years in school #pause
$Y in bb(R)_+:$ Age of death #pause
*Approach:* Learn the parameters $theta$ such that
$ f(x, theta) = y; quad x in X, y in Y $ #pause
*Goal:* Given someone's education, predict how long they will live #pause
#align(center)[You will be doing this in your first assignment!]
]
#slide(title: [Linear Regression])[
Plot the datapoints $(x_1, y_1), (x_2, y_2), dots $ #pause
Plot the curve $f(x, bold(theta)) = theta_1 x + theta_0; quad x in [0, 25]$ #pause
#cimage("figures/lecture_2/linear_regression.png", height: 60%) #pause
//We figured out linear regression! #pause
//But can we do better?
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ *Solve the example problem*
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
// 70:00 maybe 75:00
#focus-slide[Relax]
#slide(title: [Linear Regression])[
*Task:* Given your education, predict your life expectancy #pause
Plot the datapoints $(x_1, y_1), (x_2, y_2), dots $ #pause
Plot the curve $f(x, bold(theta)) = theta_1 x + theta_0; quad x in [0, 25]$ #pause
#cimage("figures/lecture_2/linear_regression.png", height: 60%)
]
#slide(title: [Linear Regression])[
#cimage("figures/lecture_2/linear_regression.png", height: 60%)
We figured out linear regression! #pause
But can we do better?
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ *Solve the example problem*
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ *Expand to nonlinear models*
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Nonlinear Regression])[
*Question:* #pause
#side-by-side[
Does the data look linear? #pause
#cimage("figures/lecture_2/linear_regression.png", height: 60%) #pause
][
Or maybe more logarithmic? #pause
#log_plot #pause
]
However, linear regression must be linear!
]
#slide(title: [Nonlinear Regression])[
*Question:* What does it mean when we say linear regression is linear? #pause
*Answer:* The function $f(x, theta)$ is a linear function of $x$ #pause
*Trick:* Change of variables to make $f$ nonlinear: $x_"new" = log(1 + x_"data")$ #pause
$ bold(X)_D = mat(x_1, 1; x_2, 1; dots.v, dots.v; x_n, 1) => bold(X)_D = mat(log(1 + x_1), 1; log(1 + x_2), 1; dots.v, dots.v; log(1 + x_n), 1) $
Now, $f$ is a linear function of $log(1 + x)$ -- a nonlinear function of $x$!
]
#slide(title: [Nonlinear Regression])[
New design matrix...
$ bold(X)_D = mat(log(1 + x_1), 1; log(1 + x_2), 1; dots.v, dots.v; log(1 + x_n), 1) $
#side-by-side[
New function...
$ f(x, vec(theta_1, theta_0)) = theta_1 log(1 + x) + theta_0 $#pause
][
Same solution...
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $
]
]
#slide(title: [Nonlinear Regression])[
#cimage("figures/lecture_2/log_regression.png", height: 60%) #pause
Better, but still not perfect #pause
Can we do even better?
]
#slide(title: [Nonlinear Regression])[
What about polynomials? #pause
$ f(x) = a x^m + b x^(m-1) + dots + c x + d $ #pause
Polynomials can approximate *any* function (universal function approximator) #pause
Can we extend linear regression to polynomials?
//$ f(x, bold(theta)) = theta_m x^m + theta_(m - 1) x^(m-1) + dots + theta_1 + x^1 + theta_0 $
]
#slide(title: [Nonlinear Regression])[
Expand $x$ to a multi-dimensional input space... #pause
$ bold(X)_D = mat(x_1, 1; x_2, 1; dots.v, dots.v; x_n, 1) => bold(X)_D = mat(
x_1^m, x_1^(m-1), dots, x_1, 1;
x_2^m, x_2^(m-1), dots, x_2, 1;
dots.v, dots.v, dots.down;
x_n^m, x_n^(m-1), dots, x_n, 1
) $ #pause
Remember, $n$ datapoints and $m + 1$ polynomial terms #pause
And add some new parameters...
$ bold(theta) = mat(theta_1, theta_0)^top => bold(theta) = mat(theta_m, theta_(m-1), dots, theta_1, theta_0)^top $
]
#slide(title: [Nonlinear Regression])[
#text(size:22pt)[
$ bold(X)_D bold(theta) = underbrace(mat(
x_1^m, x_1^(m-1), dots, x_1, 1;
x_2^m, x_2^(m-1), dots, x_2, 1;
dots.v, dots.v, dots.down;
x_n^m, x_n^(m-1), dots, x_n, 1
), n times (m + 1))
underbrace(vec(theta_m, theta_(m-1), dots.v, theta_0), (m + 1) times 1) =
underbrace(vec(
theta_m x_1^m + theta_(m-1) x_1^(m-1) + dots + theta_0,
theta_m x_2 + theta_(m-1) x_2^(m-1) + dots + theta_0,
dots.v,
theta_n x_n^m + theta_(m-1) x_n^(m-1) + dots + theta_0
), "Y prediction, " n times 1)
$] #pause
$ "New function... " quad f(x, bold(theta)) = theta_m x^m + theta_(m - 1) x^(m-1), dots, theta_1 + x^1 + theta_0 $ #pause
$ "Same solution... "quad bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $
//By changing the input space, we can fit a polynomial to the data!
]
#slide(title: [Nonlinear Regression])[
$ f(x, bold(theta)) = theta_m x^m + theta_(m - 1) x^(m-1), dots, theta_1 + x^1 + theta_0 $ #pause
*Summary:* By changing the input space, we can fit a polynomial to the data using a linear fit!
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ *Expand to nonlinear models*
+ Discuss overfitting
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ *Discuss overfitting*
+ Interactive discussion
+ Homework summary
]
#slide(title: [Overfitting])[
$ f(x, bold(theta)) = theta_n x^m + theta_(m - 1) x^(m - 1), dots, theta_1 + x^1 + theta_0 $ #pause
How do we choose $m$ (polynomial order) that provides the best fit? #pause
#grid(
columns: 3,
row-gutter: 1em,
image("figures/lecture_2/polynomial_regression_n2.png"),
image("figures/lecture_2/polynomial_regression_n3.png"),
image("figures/lecture_2/polynomial_regression_n5.png"),
$ m = 2 $,
$ m = 3 $,
$ m = 5 $
)
]
#slide(title: [Overfitting])[
How do we choose $n$ (polynomial order) that provides the best fit?
#grid(
columns: 3,
row-gutter: 1em,
image("figures/lecture_2/polynomial_regression_n2.png"),
image("figures/lecture_2/polynomial_regression_n3.png"),
image("figures/lecture_2/polynomial_regression_n5.png"),
$ m = 2 $,
$ m = 3 $,
$ m = 5 $
)
#side-by-side[Pick the $m$ with the smallest loss][
$ argmin_(bold(theta), m) cal(L)(bold(x), bold(y), (bold(theta), m)) $]
]
#slide(title: [Overfitting])[
#grid(
columns: 3,
row-gutter: 1em,
image("figures/lecture_2/polynomial_regression_n2.png"),
image("figures/lecture_2/polynomial_regression_n3.png"),
image("figures/lecture_2/polynomial_regression_n5.png"),
$ m = 2 $,
$ m = 3 $,
$ m = 5 $
)
*Question:* Which $m$ do you think has the smallest loss? #pause
*Answer:* $m=5$, but intuitively, $m=5$ does not seem very good...
]
#slide(title: [Overfitting])[
#grid(
columns: 3,
row-gutter: 1em,
image("figures/lecture_2/polynomial_regression_n2.png"),
image("figures/lecture_2/polynomial_regression_n3.png"),
image("figures/lecture_2/polynomial_regression_n5.png"),
$ m = 2 $,
$ m = 3 $,
$ m = 5 $
)
More specifically, $m=5$ will not generalize to new data #pause
We will only use our model for new data (we already have the $y$ for a known $x$)! #pause
]
#slide(title: [Overfitting])[
When our model has a small loss but does not generalize to new data, we call it *overfitting* #pause
The model has fit too closely to the sampled data points, rather than the trend #pause
Models that overfit are not useful for making predictions #pause
Back to the question... #pause
*Question:* How do we choose $m$ such that our polynomial model works for unseen/new data? #pause
*Answer:* Compute the loss on unseen data!
]
#slide(title: [Overfitting])[
To compute the loss on unseen data, we will need unseen data #pause
Let us create some unseen data! #pause
#cimage("figures/lecture_2/train_test_split.png", height: 60%)
]
#slide(title: [Overfitting])[
*Question:* How do we choose the training and testing datasets? #pause
$ "Option 1:" bold(x)_"train" &= vec(
x_1, x_2, x_3
) bold(y)_"train" &= vec(
y_1, y_2, y_3
); quad
bold(x)_"test" &= vec(
x_4, x_5
) bold(y)_"test" &= vec(
y_4, y_5
)
$ #pause
$ "Option 2:" bold(x)_"train" &= vec(
x_4, x_1, x_3
) bold(y)_"train" &= vec(
y_4, y_1, y_3
); quad
bold(x)_"test" &= vec(
x_2, x_5
) bold(y)_"test" &= vec(
y_2, y_5
)
$ #pause
*Answer:* Always shuffle the data #pause
*Note:* The model must never see the testing dataset during training. This is very important!
]
#slide(title: [Overfitting])[
We can now measure how the model generalizes to new data #pause
#cimage("figures/lecture_2/train_test_regression.png", height: 60%)
Learn parameters from the train dataset, evaluate on the test dataset #pause
#side-by-side[
$cal(L)(bold(X)_"train", bold(y)_"train", bold(theta))$
][
$cal(L)(bold(X)_"test", bold(y)_"test", bold(theta))$
]
]
#slide(title: [Overfitting])[
We use separate training and testing datasets on *all* machine learning models, not just linear regression #pause
]
// 55:00 + 20 break + 40 = 1h55m
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ *Discuss overfitting*
+ Interactive discussion
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ *Interactive discussion*
+ Homework summary
]
#slide(title: [Discussion])[
*Q:* When should we use test and train splits? #pause
*Q:* Are neural networks more powerful than linear regression? #pause
*Q:* Why would we want to use linear regression instead of neural networks? #pause
*Q:* What are interesting problems that we can apply linear regression to? #pause
*Q:* We use a squared error loss. What effect does this have on outliers? #pause
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ *Interactive discussion*
+ Homework summary
]
#slide(title: [Linear Regression])[
+ Define an example problem
+ Define our linear model $f$
+ Define a loss function $cal(L)$
+ Use $cal(L)$ to learn the parameters $theta$ of $f$
+ Solve the example problem
+ Expand to nonlinear models
+ Discuss overfitting
+ Interactive discussion
+ *Homework summary*
]
#slide(title: [Homework])[
Tips for assignment 1 #pause
```py
def f(theta, design):
# Linear function
return design @ theta
``` #pause
Not all matrices can be inverted! Ensure the matrices are square and the condition number is low
```py
A.shape
cond = jax.numpy.linalg.cond(A)
``` #pause
Everything you need is in the lecture notes
]
#slide(title: [Homework])[
https://colab.research.google.com/drive/1I6YgapkfaU71RdOotaTPLYdX9WflV1me
]
|
|
https://github.com/freundTech/typst-forge | https://raw.githubusercontent.com/freundTech/typst-forge/main/polylux/test.typ | typst | // see https://github.com/andreasKroepelin/polylux/blob/main/examples/minimal.typ
#import "@typst-forge/polylux:0.3.1": *
#set page(paper: "presentation-16-9")
#set text(size: 25pt)
#polylux-slide[
#align(horizon + center)[
= Very minimalist slides
A lazy author
July 23, 2023
]
]
#polylux-slide[
== First slide
Some static text on this slide.
]
#polylux-slide[
== This slide changes!
You can always see this.
#uncover(2)[But this appears later!]
]
|
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/README.md | markdown | Other | # The `Valkyrie` Package
<div align="center">Version 0.2.2</div>
This package implements type validation, and is targeted mainly at package and template developers. The desired outcome is that it becomes easier for the programmer to quickly put a package together without spending a long time on type safety, but also to make the usage of those packages by end-users less painful by generating useful error messages.
## Example Usage
```typ
#import "@preview/valkyrie:0.2.2" as z
#let my-schema = z.dictionary((
should-be-string: z.string(),
complicated-tuple: z.tuple(
z.email(),
z.ip(),
z.either(
z.string(),
z.number(),
),
),
)
)
#z.parse(
(
should-be-string: "This doesn't error",
complicated-tuple: (
"<EMAIL>",
// Error: Schema validation failed on argument.complicated-tuple.1:
// String must be a valid IP address
"NOT AN IP",
1,
),
),
my-schema,
)
```
## Community-lead
As of version 0.2.0, `valkyrie` now resides in the typst-community organisation. Typst users are encouraged to submit additional types, assertions, coercions, and schemas that they believe are already used widely, or should be widely adopted for the health of the ecosystem. |
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/24-01-21/24-01-21.typ | typst | #import "/template.typ": *
#show: project.with(
date: "21/01/24",
subTitle: "Meeting di retrospettiva e pianificazione",
docType: "verbale",
authors: (
"<NAME>",
),
timeStart: "15:00",
timeEnd: "15:45",
);
= Ordine del giorno
- Valutazione del progresso generale;
- Analisi di retrospettiva;
- RTB;
- Pianificazione.
== Valutazione del progresso generale <avanzamento>
Ogni membro del gruppo, supportato dall'evidenza della board Jira, ha esposto lo stato di avanzamento delle proprie attività assegnate.
Come già previsto durante la pianificazione i lavori risultano rallentati causa esami.
Si prevede di procedere a ritmo rallentato fino allo sprint 13.
=== Lettera di presentazione
La lettera di presentazione relativa al colloquio RTB è stata ultimata e spedita.
=== Piano di Progetto
Il documento Piano di Progetto è stato completamente revisionato e sono state effettuate modifiche minori per migliorare leggibilità e comprensione.
=== Sito Web
Il sito Web del gruppo è ora totalmente online e completo di riferimenti a tutta la documentazione prodotta.
=== Presentazione RTB
La presentazione Google Slides è stata terminata sia dal punto di vista del contenuto sia dal punto di vista del layout e del tema. Essa risulta ora pronta per il colloquio di RTB.
== Analisi di retrospettiva
=== Keep doing <keep-doing>
Le revisioni dei documenti prodotti continuano a distinguersi per celerità e precisione.
Migliorata la comunicazione tra membri del gruppo, essa è ora più precisa e tempestiva.
=== Improvements <improvements>
Continua lo sbilanciamento tra gli impegni dei singoli del gruppo. Esso è dovuto principalmente alla differenza nelle date degli esami che ciascuno deve sostenere.
== RTB
È stata fissata la presentazione RTB per il 25/01/24 alle ore 8:40.
Sono stati assegnati gli argomenti che ciascun membro del gruppo ricoprirà durante la presentazione, facendo particolare attenzione a suddividere equamente il lavoro e i minuti di presentazione a disposizione.
Il gruppo ritiene necessario fissare un meeting di "prova" della presentazione il 24/01/24 alle ore 17:30.
== Pianificazione <pianificazione>
La pianificazione dello Sprint 12 tiene conto della prossimità della sessione di esame invernale. Di seguito le task principali assegnate:
- Redigere consuntivo di periodo 11;
- Redigere preventivo di periodo 12;
- Estendere termini Glossario;
- Modifica minore su una tabella del documento Analisi dei Requisiti causa rilevamento errore.
|
|
https://github.com/RanolP/typlog | https://raw.githubusercontent.com/RanolP/typlog/main/_utils/_palette.typ | typst | // See https://yeun.github.io/open-color/
#let palette = for (k, v) in (blue-5: "#339af0") {
((k): color.rgb(v))
}
|
|
https://github.com/Dav1com/minerva-report-fcfm | https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/lib/states.typ | typst | MIT No Attribution | /// Este es un `state` que es usado por el template para
/// saber si el documento siendo compilado es `main.typ`
/// o un documento secundario.
///
/// -> state
#let is-main = state("minerva.is-main", false)
/// Esta función permite obtener ayuda sobre cualquier función
/// del template. Para saber qué funciones y variables define
/// el template simplemente deja que el autocompletado te guíe,
/// luego puedes llamar esta función para obtener más ayuda.
///
/// - nombre (string): Puede ser el nombre de una función o
/// variable, entonces la función entrega
/// ayuda general sobre esta. Si se entrega
/// algo de la forma `"help(nombre)"` entonces
/// entrega ayuda específica sobre el argumento
/// `nombre`.
/// -> content
#let help(nombre) = {
import "../meta.typ": *
return help-leaf("states")(nombre)
}
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2007/WS-12.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [3041],
[2], [LI Xiaoxia], [CHN], [2944],
[3], [GUO Yue], [CHN], [2935],
[4], [WANG Nan], [CHN], [2933],
[5], [GUO Yan], [CHN], [2821],
[6], [JIANG Huajun], [HKG], [2640],
[7], [LI Jiawei], [SGP], [2636],
[8], [WANG Yuegu], [SGP], [2631],
[9], [#text(gray, "NIU Jianfeng")], [CHN], [2603],
[10], [CAO Zhen], [CHN], [2597],
[11], [CHANG Chenchen], [CHN], [2530],
[12], [KIM Kyungah], [KOR], [2501],
[13], [PARK Miyoung], [KOR], [2489],
[14], [WU Jiaduo], [GER], [2482],
[15], [FAN Ying], [CHN], [2480],
[16], [LIN Ling], [HKG], [2477],
[17], [LI Jiao], [NED], [2471],
[18], [#text(gray, "CHEN Qing")], [CHN], [2470],
[19], [LEE Eunhee], [KOR], [2468],
[20], [LIU Shiwen], [CHN], [2463],
[21], [PENG Luyang], [CHN], [2458],
[22], [#text(gray, "KANAZAWA Saki")], [JPN], [2452],
[23], [FUKUHARA Ai], [JPN], [2441],
[24], [GAO Jun], [USA], [2439],
[25], [DING Ning], [CHN], [2435],
[26], [LI Qian], [POL], [2426],
[27], [WANG Chen], [CHN], [2423],
[28], [SHEN Yanfei], [ESP], [2421],
[29], [TOTH Krisztina], [HUN], [2418],
[30], [HIRANO Sayaka], [JPN], [2411],
[31], [LIU Jia], [AUT], [2404],
[32], [SUN Beibei], [SGP], [2394],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [MONTEIRO DODEAN Daniela], [ROU], [2393],
[34], [TIE Yana], [HKG], [2389],
[35], [LOVAS Petra], [HUN], [2354],
[36], [ZHANG Rui], [HKG], [2346],
[37], [FUJINUMA Ai], [JPN], [2337],
[38], [#text(gray, "SCHOPP Jie")], [GER], [2333],
[39], [SCHALL Elke], [GER], [2332],
[40], [LAU Sui Fei], [HKG], [2326],
[41], [FENG Tianwei], [SGP], [2322],
[42], [<NAME>], [PRK], [2310],
[43], [<NAME>], [HUN], [2307],
[44], [<NAME>], [ITA], [2300],
[45], [FUKUOKA Haruna], [JPN], [2297],
[46], [#text(gray, "UMEMURA Aya")], [JPN], [2295],
[47], [<NAME>], [KOR], [2294],
[48], [<NAME>], [CRO], [2293],
[49], [<NAME>], [TPE], [2288],
[50], [#text(gray, "<NAME>")], [CHN], [2286],
[51], [<NAME>], [SGP], [2286],
[52], [#text(gray, "<NAME>")], [HKG], [2286],
[53], [<NAME>], [CHN], [2283],
[54], [<NAME>], [DOM], [2283],
[55], [<NAME>], [RUS], [2259],
[56], [#text(gray, "<NAME>")], [ROU], [2259],
[57], [<NAME>], [ROU], [2251],
[58], [<NAME>], [CHN], [2243],
[59], [<NAME>hyung], [AUS], [2242],
[60], [FUJII Hiroko], [JPN], [2241],
[61], [<NAME>], [CRO], [2240],
[62], [PAVLOVICH Viktoria], [BLR], [2236],
[63], [PAVLOVICH Veronika], [BLR], [2235],
[64], [SHAN Xiaona], [GER], [2230],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [<NAME>], [THA], [2229],
[66], [<NAME>], [AUT], [2229],
[67], [<NAME>], [JPN], [2228],
[68], [YAO Yan], [CHN], [2223],
[69], [<NAME>], [JPN], [2206],
[70], [<NAME>], [FRA], [2199],
[71], [<NAME>], [FRA], [2197],
[72], [ODOROVA Eva], [SVK], [2196],
[73], [<NAME>], [GER], [2186],
[74], [#text(gray, "<NAME>")], [ROU], [2185],
[75], [<NAME>], [AUT], [2183],
[76], [<NAME>], [GER], [2179],
[77], [KWAK Bangbang], [KOR], [2179],
[78], [LU Yun-Feng], [TPE], [2166],
[79], [<NAME>], [FRA], [2146],
[80], [<NAME>], [GER], [2143],
[81], [<NAME>], [SRB], [2143],
[82], [<NAME>], [GER], [2135],
[83], [NEGRISOLI Laura], [ITA], [2133],
[84], [STEFANOVA Nikoleta], [ITA], [2129],
[85], [VACENOVSKA Iveta], [CZE], [2129],
[86], [<NAME>], [SGP], [2128],
[87], [STRBIKOVA Renata], [CZE], [2126],
[88], [XU Jie], [POL], [2125],
[89], [<NAME>yunjung], [KOR], [2119],
[90], [KOTIKHINA Irina], [RUS], [2118],
[91], [JIAO Yongli], [ESP], [2117],
[92], [KONISHI An], [JPN], [2116],
[93], [#text(gray, "JANG Hyon Ae")], [PRK], [2113],
[94], [ETSUZAKI Ayumi], [JPN], [2108],
[95], [EKHOLM Matilda], [SWE], [2104],
[96], [KOSTROMINA Tatyana], [BLR], [2104],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [KIM Jong], [PRK], [2102],
[98], [DVORAK Galia], [ESP], [2101],
[99], [ISHIGAKI Yuka], [JPN], [2094],
[100], [MUANGSUK Anisara], [THA], [2093],
[101], [BILENKO Tetyana], [UKR], [2091],
[102], [YU Kwok See], [HKG], [2087],
[103], [TERUI Moemi], [JPN], [2084],
[104], [LANG Kristin], [GER], [2080],
[105], [IVANCAN Irene], [GER], [2077],
[106], [LAY Jian Fang], [AUS], [2076],
[107], [RAMIREZ Sara], [ESP], [2073],
[108], [ZHU Fang], [ESP], [2068],
[109], [DOLGIKH Maria], [RUS], [2067],
[110], [MOLNAR Cornelia], [CRO], [2064],
[111], [CHENG I-Ching], [TPE], [2059],
[112], [SHIM Serom], [KOR], [2046],
[113], [PASKAUSKIENE Ruta], [LTU], [2044],
[114], [KIM Kyungha], [KOR], [2040],
[115], [PAN Chun-Chu], [TPE], [2037],
[116], [YOON Sunae], [KOR], [2031],
[117], [#text(gray, "STRUSE Nicole")], [GER], [2031],
[118], [ONO Shiho], [JPN], [2021],
[119], [KO Somi], [KOR], [2021],
[120], [TIMINA Elena], [NED], [2017],
[121], [<NAME>], [UKR], [2017],
[122], [GATINSKA Katalina], [BUL], [2017],
[123], [KIM Junghyun], [KOR], [2016],
[124], [LI Chunli], [NZL], [2015],
[125], [YAMANASHI Yuri], [JPN], [2012],
[126], [LI Bin], [HUN], [2011],
[127], [PARK Youngsook], [KOR], [2007],
[128], [KRAVCHENKO Marina], [ISR], [2007],
)
) |
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/doc/examples/book/content.typ | typst | MIT License | = Chapter A
#lorem(20)
= Chapter B
#lorem(50)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/visualize/shape-rounded.typ | typst | Apache License 2.0 | // Test rounded rectangles and squares.
---
#set square(size: 20pt, stroke: 4pt)
// no radius for non-rounded corners
#stack(
dir: ltr,
square(),
h(10pt),
square(radius: 0pt),
h(10pt),
square(radius: -10pt),
)
#stack(
dir: ltr,
square(),
h(10pt),
square(radius: 0%),
h(10pt),
square(radius: -10%),
)
// small values for small radius
#stack(
dir: ltr,
square(radius: 1pt),
h(10pt),
square(radius: 5%),
h(10pt),
square(radius: 2pt),
)
// large values for large radius or circle
#stack(
dir: ltr,
square(radius: 8pt),
h(10pt),
square(radius: 10pt),
h(10pt),
square(radius: 12pt),
)
#stack(
dir: ltr,
square(radius: 45%),
h(10pt),
square(radius: 50%),
h(10pt),
square(radius: 55%),
)
|
https://github.com/Quaternijkon/Typst_FLOW | https://raw.githubusercontent.com/Quaternijkon/Typst_FLOW/main/main.typ | typst | // #import "../lib.typ": *
#import "theme.typ": *
// #import "src/exports.typ": *
// #import themes.dewdrop: *
#import "@preview/numbly:0.1.0": numbly
#show: dewdrop-theme.with(
aspect-ratio: "16-9",
footer: self => self.info.title,
footer-alt: self => self.info.subtitle,
navigation: "mini-slides",
config-info(
title: [A strategy to improve cache performance in vector query],
subtitle: [Cache-aware design in Milvus],
author: [董若扬],
date: datetime.today(),
institution: [ADSLAB, USTC],
),
)
// #set heading(numbering: numbly("{1}.", default: "1.1"))
#let primary= rgb("#004098")
#show emph: it => {
text(primary, it.body)
}
#show outline.entry.where(
level: 1
): it => {
v(1em, weak: true)
// strong(it.body)
text(primary, it.body)
}
#title-slide()
// #outline-slide()
#include "content1.typ"
|
|
https://github.com/eliapasquali/typst-thesis-template | https://raw.githubusercontent.com/eliapasquali/typst-thesis-template/main/thesis.typ | typst | Other | #import "./config/variables.typ": *
#import "./config/thesis-config.typ": *
#show: config.with(
myAuthor: myName,
myTitle: myTitle,
myNumbering: "1.",
myLang: myLang
)
#include "structure.typ"
|
https://github.com/OverflowCat/BUAA-Data-and-Error-Analysis-Sp2024 | https://raw.githubusercontent.com/OverflowCat/BUAA-Data-and-Error-Analysis-Sp2024/neko/5-regression/straight.typ | typst | #import "helper.typ": c
#set text(lang: "zh", cjk-latin-spacing: auto)
== 5-10
#let x = (1.585, 2.512, 3.979, 6.310, 9.988, 15.85)
#let y = (0.03162, 0.02291, 0.02089, 0.01950, 0.01862, 0.01513)
#let lnx = x.map(calc.ln)
#let lny = y.map(calc.ln)
#table(
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
$ln x$, ..lnx.map(c).map(str),
$ln y$, ..lny.map(c).map(str)
)
#import "@preview/plotst:0.2.0": *
#{
let data = lnx.zip(lny)
// Create the axes used for the chart
let x_axis = axis(min: 0, max: 2.7, step: 0.5, location: "bottom", helper_lines: true)
let y_axis = axis(min: -4.3, max: -3.2, step: 0.1, location: "left", helper_lines: true)
// Combine the axes and the data and feed it to the plot render function.
let pl = plot(data: data, axes: (x_axis, y_axis))
graph_plot(pl, (100%, 25%))
graph_plot(pl, (100%, 25%), rounding: 30%, caption: "Graph Plot with rounding")
}
|
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/utierne/postnaUtierenBezKnaza.typ | typst | #import "../../../style.typ": *
#import "/SK/texts.typ": *
#import "../styleCasoslov.typ": *
= Pôstna utiereň <X>
#show: rest => columns(2, rest)
TODO: zaciatok
#lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.")
#lettrine("Amen.")
#lettrine("Sláva na výsostiach Bohu a na zemi pokoj ľuďom dobrej vôle.") #note[(3x)]
#lettrine("Pane, otvor moje pery, a moje ústa budú ohlasovať tvoju slávu.") #note[(2x)]
== Šesťžalmie <X>
#zalm(3)
#zalm(37)
#zalm(62)
#si
#lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)]
#ektenia(3)
#zalm(87)
#zalm(102)
#zalm(142)
#si
#lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)]
#ektenia(12)
== Boh je Pán <X>
#verseSoZvolanim("Aleluja, aleluja, aleluja.",
(
"Svojou dušou dychtím po tebe v noci, Bože, lebo tvoje prikázania osvecujú celú zem.",
"Učte sa spravodlivosti, obyvatelia zeme.",
"Závisť zničí ľudí nepolepšiteľných.",
"Potrestal si zlých, Pane, potrestal si mocných zeme."
))
== Trojičné piesne <X>
TODO: doplnit
== Katizmy a sedaleny <X>
#note[Berieme katizmy podľa predpisu.]
#note[Medzi katizmami berieme sedaleny.]
#zalm(50)
TODO: Spas Boze svoj lud
== Kánon <X>
#note[Berieme kánon podľa predpisu]
#note[Po ôsmej piesni, berieme Velebenie Bohorodičky]
#verseSoZvolanim("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.",
(
"Velebí moja duša Pána * a môj duch jasá v Bohu, mojom Spasiteľovi.",
"Lebo zhliadol na poníženosť svojej služobnice, * hľa, od tejto chvíle blahoslaviť ma budú všetky pokolenia.",
"Lebo veľké veci mi urobil ten, ktorý je mocný, a sväté je jeho meno. * A jeho milosrdenstvo z pokolenia na pokolenie s tými, čo sa ho boja.",
"Ukázal silu svojho ramena, * rozptýlil tých, čo v srdci pyšne zmýšľajú.",
"Mocnárov zosadil z trónov a povýšil ponížených. * Hladných nakŕmil dobrotami a bohatých prepustil naprázdno.",
"Ujal sa Izraela, svojho služobníka, lebo pamätá na svoje milosrdenstvo, * ako sľúbil našim otcom, Abrahámovi a jeho potomstvu naveky."
), prve: false)
#lettrine("Dôstojné je velebiť teba, Bohorodička, vždy blažená a nepoškvrnená Matka nášho Boha. Čestnejšia si ako cherubíni a neporovnateľne slávnejšia ako serafíni, bez porušenia si porodila Boha Slovo, opravdivá Bohorodička, velebíme ťa.")
== Svitilen <X>
TODO: postne svitileny
== Chvály <X>
#include "../../zalmy/Z_ChvalyMale.typ"
#verse((
"Aby ich súdili podľa písaného práva. * Všetkým jeho svätým to bude na slávu.",
"Chváľte Pána v jeho svätyni! * Chváľte ho na jeho vznešenej oblohe.",
"Chváľte ho za jeho činy mohutné; * chváľte ho za jeho nesmiernu velebnosť.",
"Chváľte ho zvukom poľnice, * chváľte ho harfou a citarou.",
"Chváľte ho bubnom a tancom, * chváľte ho lýrou a flautou.",
"Chváľte ho ľubozvučnými cimbalmi, chváľte ho jasavými cimbalmi; všetko, čo dýcha, nech chváli Pána.",
), start: 6)
#ektenia(3)
== Slávoslovie <X>
#slavoslovieMale
#ektenia(12)
== Veršové slohy <X>
#note[Berieme veršové slohy s veršami podľa predpisu.]
Dobré je oslavovať Pána a ospevovať meno tvoje, Najvyšší.
Za rána zvestovať tvoju dobrotu a tvoju vernosť celé noc.
#trojsvatePoOtcenas
== Tropáre <X>
#note[Berieme predpísané tropáre]
TODO: Stojime v chrame ...
#ektenia(12)
#efrem
#prepustenieBezKnaza
|
|
https://github.com/dark-flames/resume | https://raw.githubusercontent.com/dark-flames/resume/main/data/award.typ | typst | MIT License | #import "../libs.typ": *
#import "../chicv.typ": *
#let awardList = (
(
name: "National Olympiad in Informatics in Provinces",
detail: "First Prize",
intro: "Competitive programming contest held by China Computer Federation",
date: "Nov, 2015",
location: "Shandong, China",
content: []
),
)
#let award(env) = {
resume-content(env, {
multiLang(env, en: [== Honors and Awards])
let s = awardList.map(a => {
cventry(
tl: [*#a.name*, #a.detail],
tr: a.date,
bl: a.intro,
br: a.location
)[#a.content]
}).join()
[#s]
})
} |
https://github.com/SillyFreak/typst-prequery | https://raw.githubusercontent.com/SillyFreak/typst-prequery/main/docs/man-style.typ | typst | MIT License | // adapted from https://github.com/Mc-Zen/tidy/blob/v0.3.0/src/styles/minimal.typ
#import "@preview/tidy:0.3.0"
#import tidy.utilities: *
// ==== internal utilities
#let mono = text.with(font: "DejaVu Sans Mono", size: 0.85em, weight: 340)
#let name-fill = rgb("#1f2a63")
#let signature-fill = rgb("#d8dbed")
#let radius = 2pt
#let preview-radius = 0.32em
#let mono-fn(name, args: none, ret: none) = mono({
text(name-fill, name)
if args != none {
let args = args.map(box)
if args.len() <= 3 {
"("
args.join(", ")
")"
} else {
"(\n"
args.map(arg => " " + arg + ",").join("\n")
"\n)"
}
}
if ret != none {
if args != none {
box[~-> #ret]
} else {
box[: #ret]
}
}
})
#let get-type-color(type) = rgb("#eff0f3")
#let show-types(types, style-args, joiner: h(0.3em)) = {
types.map(style-args.style.show-type.with(style-args: style-args)).join(joiner)
}
#let signature-block(..args) = {
let bar-width = 1mm
set par(justify: false)
block(
width: 100%,
radius: radius,
fill: signature-fill,
stroke: (left: bar-width + name-fill),
outset: (left: -bar-width / 2),
inset: (x: 0.7em, y: 0.7em),
..args
)
}
#let preview-block(no-codly: true, ..args) = {
import "@preview/codly:1.0.0"
show: if no-codly { codly.no-codly } else { it => it }
block(
stroke: 0.5pt + luma(200),
radius: preview-radius,
..args
)
}
// ==== functions required from styles
#let show-outline(module-doc, style-args: (:)) = {
let prefix = module-doc.label-prefix
let gen-entry(name, args: none) = {
let entry = mono-fn(name, args: args)
if style-args.enable-cross-references {
let lbl = prefix + name
if args != none { lbl += "()" }
entry = link(label(lbl), entry)
}
entry
}
let entries = (
..module-doc.functions.map(fn => gen-entry(fn.name, args: ())),
..module-doc.variables.map(var => gen-entry(var.name)),
)
grid(
columns: (1fr,) * 3,
column-gutter: 0.5em,
..entries.chunks(calc.ceil(entries.len() / 3)).map(entries => {
block(
fill: gray.lighten(80%),
width: 100%,
inset: (y: 0.6em),
radius: radius,
list(..entries)
)
}),
)
}
// Create beautiful, colored type box
#let show-type(type, style-args: (:)) = {
h(2pt)
box(outset: 2pt, fill: get-type-color(type), radius: 2pt, raw(type, lang: none))
h(2pt)
}
#let show-function(
fn, style-args,
) = {
block(breakable: style-args.break-param-descriptions, {
let parameter-list = (style-args.style.show-parameter-list)(fn, style-args)
let lbl = if style-args.enable-cross-references {
label(style-args.label-prefix + fn.name + "()")
}
[#parameter-list #lbl]
})
pad(x: 0em, eval-docstring(fn.description, style-args))
let args = fn.args.pairs()
if style-args.omit-private-parameters {
args = args.filter(((arg-name, info)) => not arg-name.starts-with("_"))
}
if style-args.omit-empty-param-descriptions {
args = args.filter(((arg-name, info)) => info.at("description", default: "") != "")
}
args = args.map(((arg-name, info)) => {
let types = info.at("types", default: ())
let description = info.at("description", default: "")
(style-args.style.show-parameter-block)(
arg-name, types, eval-docstring(description, style-args),
style-args,
show-default: "default" in info,
default: info.at("default", default: none),
)
})
if args.len() != 0 {
[*#style-args.local-names.parameters:*]
args.join()
}
v(4em, weak: true)
}
#let show-parameter-list(fn, style-args) = {
signature-block(breakable: style-args.break-param-descriptions, {
mono-fn(
fn.name,
args: {
let args = fn.args.pairs()
if style-args.omit-private-parameters {
args = args.filter(((arg-name, info)) => not arg-name.starts-with("_"))
}
args = args.map(((arg-name, info)) => {
arg-name
if "types" in info [: #show-types(info.types, style-args)]
})
args
},
ret: if fn.return-types != none { show-types(fn.return-types, style-args) },
)
})
}
// Create a parameter description block, containing name, type, description and optionally the default value.
#let show-parameter-block(
name, types, content, style-args,
show-default: false,
default: none,
) = block(
breakable: style-args.break-param-descriptions,
inset: 0pt, width: 100%,
{
set par(hanging-indent: 1em, first-line-indent: 0em)
mono(name)
[ (]
show-types(types, style-args, joiner: [ #text(size: 0.6em)[or] ])
if show-default [ \= #raw(lang: "typc", default)]
[) -- ]
content
}
)
#let show-reference(label, name, style-args: none) = {
link(label, raw(name, lang: none))
}
#let show-variable(
var, style-args,
) = {
signature-block(breakable: style-args.break-param-descriptions, {
let var-signature = mono-fn(
var.name,
ret: if "type" in var { (style-args.style.show-type)(var.type, style-args: style-args) },
)
let lbl = if style-args.enable-cross-references {
label(style-args.label-prefix + var.name)
}
[#var-signature #lbl]
})
pad(x: 0em, eval-docstring(var.description, style-args))
v(4em, weak: true)
}
// Adapted from https://github.com/Mc-Zen/tidy/blob/v0.3.0/src/show-example.typ
// see discussion here: https://discord.com/channels/1054443721975922748/1296208677371379813
/// Takes given code and both shows it and previews the result of its evaluation.
///
/// The code is by default shown in the language mode `lang: typc` (typst code)
/// if no language has been specified. Code in typst markup lanugage (`lang: typ`)
/// is automatically evaluated in markup mode.
///
/// - code (raw): Raw object holding the example code.
/// - scope (dictionary): Additional definitions to make available for the evaluated
/// example code.
/// - scale-preview (auto, ratio): How much to rescale the preview. If set to auto, the the preview is scaled to fit the box.
/// - inherited-scope (dictionary): Definitions that are made available to the entire parsed
/// module. This parameter is only used internally.
#let show-example(
code,
dir: ltr,
scope: (:),
preamble: "",
ratio: 1,
scale-preview: auto,
mode: "code",
inherited-scope: (:),
code-block: block,
preview-block: preview-block,
col-spacing: 5pt,
..options
) = {
set raw(block: true)
let lang = if code.has("lang") { code.lang } else { "typc" }
if lang == "typ" {
mode = "markup"
}
if mode == "markup" and not code.has("lang") {
lang = "typ"
}
set raw(lang: lang)
if code.has("block") and code.block == false {
code = raw(code.text, lang: lang, block: true)
}
let preview = {
set heading(numbering: none, outlined: false)
[#eval(preamble + code.text, mode: mode, scope: scope + inherited-scope)]
}
let preview-outer-padding = 3pt
let preview-inner-padding = 5pt
show: if dir.axis() == "vertical" { pad.with(x: 4%) } else { it => it }
layout(size => {
let code-width
let preview-width
if dir.axis() == "vertical" {
code-width = size.width
preview-width = size.width
} else {
code-width = ratio / (ratio + 1) * size.width - 0.5 * col-spacing
preview-width = size.width - code-width - col-spacing
}
let available-preview-width = preview-width - 2 * (preview-outer-padding + preview-inner-padding)
let preview-size
let scale-preview = scale-preview
if scale-preview == auto {
preview-size = measure(preview)
assert(preview-size.width != 0pt, message: "The code example has a relative width. Please set `scale-preview` to a fixed ratio, e.g., `100%`")
scale-preview = calc.min(1, available-preview-width / preview-size.width) * 100%
} else {
preview-size = measure(block(preview, width: available-preview-width / (scale-preview / 100%)))
}
set par(hanging-indent: 0pt) // this messes up some stuff in case someone sets it
// We first measure this thing (code + preview) to find out which of the two has
// the larger height. Then we can just set the height for both boxes.
let arrangement(width: 100%, height: auto) = {
let code-block = code-block(
width: code-width,
height: height,
{
set text(size: .9em)
pad(x: -4.3%, code)
}
)
let preview-block = preview-block(
height: height,
width: preview-width,
inset: preview-outer-padding,
box(
width: 100%,
fill: white,
inset: preview-inner-padding,
scale(
scale-preview,
origin: top + left,
block(preview, height: preview-size.height, width: preview-size.width)
)
)
)
show: block.with(
width: width,
inset: 0pt,
)
grid(
..if dir.axis() == "horizontal" {
(columns: 2, rows: 1, column-gutter: col-spacing)
} else {
(columns: 1, rows: 2, row-gutter: col-spacing)
},
..if dir in (ltr, ttb) {
(code-block, preview-block)
} else {
(preview-block, code-block)
}
)
}
let height = if dir.axis() == "vertical" { auto }
else { measure(arrangement(width: size.width)).height }
arrangement(height: height)
})
}
|
https://github.com/GuTaoZi/SUSTech-thesis-typst | https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/template/references.typ | typst | MIT License | #import "../utils/style.typ": *
#let references(
bibPath: "../references.bib",
en_title: false,
) = {
pagebreak(weak: true)
align(center)[
#hide[
#heading(level: 1,numbering: none,"参考文献")
#v(-20pt)
]// 这个实现也挺难受的,自动生成目录时会自动抓取标题原本的样式,如果把下面的文字塞进heading.body,那么目录里就会出现三号黑体的“参考文献”
#text(font: FONTS.黑体,size: FSIZE.三号,weight: "bold", "参考文献")
#if en_title [
#text(font: ("Source Han Sans SC", "Source Han Sans", "Noto Sans CJK SC", "SimHei", "Heiti SC", "STHeiti"),size: FSIZE.三号,weight: "bold", "\nReferences")
]
]
set text(font: FONTS.宋体,size: FSIZE.五号)
bibliography(bibPath, title: none, style: "gb-7714-2005-numeric")
} |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/place-spacing.typ | typst | Apache License 2.0 | // Test that placed elements don't add extra block spacing.
---
#show figure: set block(spacing: 4em)
Paragraph before float.
#figure(rect(), placement: bottom)
Paragraph after float.
---
#show place: set block(spacing: 4em)
Paragraph before place.
#place(rect())
Paragraph after place.
|
https://github.com/pluttan/os | https://raw.githubusercontent.com/pluttan/os/main/lab3/lab3.typ | typst | #import "@docs/bmstu:1.0.0":*
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx, cellx
#show: student_work.with(
caf_name: "Компьютерные системы и сети",
faculty_name: "Информатика и системы управления",
work_type: "лабораторной работе",
work_num: 3,
study_field: "09.03.01 Информатика и вычислительная техника",
discipline_name: "Операционные системы",
theme: "Исследование среды управления и методов защиты",
author: (group: "ИУ6-52Б", nwa: "<NAME>"),
adviser: (nwa: "<NAME>"),
city: "Москва",
table_of_contents: true,
)
= Введение
== Цель работы
Исследование среды управления Linux и методов защиты.
== Общая информация
В данной работе на проработку выносится следующее:
- Окружения рабочего стола (DE) Linux (GNOME, KDE,Xfce,LXDE);
- Настройка Openbox;
- Установка и настройка панелей;
- Настройка autostart;
- Настройка рабочего стола;
- Отображение иконок;
- Установка и настройка conky;
- Управление с помощью консоли;
- Основные команды и утилиты;
- Основные утилиты;
- Объединение команд;
- Более сложные утилиты;
- top, ps, pstree;
- ping, netstat, ip;
- Написание скриптов на bash.
= Выполнение
== Установка X Window System и Openbox
X Window System представляет собой оконную систему, определяющую
стандартные интерфейсы и протоколы для работы с графическим
интерфейсом пользователя. В данной ЛР будет использована открытая
реализация X.Org. Для установки X.Org нужно выполнить следующую
команду:
```sh apt-get install xorg```.
#img(image("img/1.png", width:80%), [```sh apt-get install xorg```])
#img(image("img/2.png", width:80%), [```sh apt-get install xorg```])
После установки оконной системы требуется установить Openbox. Для
этого нужно выполнить команду:
```sh apt-get install openbox dbus-x11```
#img(image("img/4.png", width:80%), [```sh apt-get install openbox dbus-x11```])
#img(image("img/5.png", width:80%), [```sh apt-get install openbox dbus-x11```])
Чтобы активировать графический интерфейс, необходимо запустить xсервер: ```sh startx```.
#img(image("img/6.png", width:90%), [```sh startx```])
#img(image("img/7.png", width:90%), [Рабочий стол и меню])
== Эмулятор терминала в графическом режиме
Выберем из меню «Terminal emulator». Открывается окно `uxterm`. В
этом окне мы будем вводить команды так же, как в текстовом режиме в мы
вводили команды в `bash`.
#img(image("img/8.png", width:90%), [Окно `uxterm`])
Выполним команду: ```sh pstree```
#img(image("img/9.png", width:90%), [```sh pstree```])
Тут `bash` работает, просто вывод текста осуществляется
посредством `xterm` (`uxterm`).
Установим другой эмулятор терминала командой:
```sh apt-get install kitty```
В этом терминале есть полоса прокрутки, выделение и копирование
текста в буфер обмена.
#img(image("img/10.png", width:90%), [```sh apt-get install kitty```])
#img(image("img/11.png", width:90%), [```sh apt-get install kitty```])
#img(image("img/12.png", width:90%), [Откроем ```sh kitty```])
#img(image("img/13.png", width:90%), [Интерфейс ```sh kitty```])
== Подменю «Debian»
В меню нет пункта «Debian», это значит что отсутствуют некоторые
необходимые пакеты. Откроем терминал и дадим команды:
```sh apt-get install menu```
```sh apt-get install menu-xdg```
#img(image("img/16.png", width:90%), [```sh apt-get install menu``` ```sh apt-get install menu-xdg```])
Далее выполним следующие комманды:
#img(image("img/17.png", width:90%), [```sh mkdir ~/.config```\
```sh mkdir ~/.config/openbox```\
```sh cp /etc/xdg/openbox/rc.xml ~/.config/openbox/```\
```sh cp /etc/xdg/openbox/menu.xml ~/.config/openbox/```\
```sh cp /etc/xdg/openbox/autostart ~/.config/openbox/```])
Первые две команды создадут для пользователя `root`
папку `./config/openbox`, остальные три скопируют туда настройки из общей
папки настроек `Openbox` в папку настроек конкретного пользователя.
== Текстовый браузер w3m в Openbox.
В консоли `kitty` браузер `w3m` способен загружать изображения. Для
этого необходимо поставить пакет `w3m-img`:\
```sh apt-get install w3m-img```\
#img(image("img/19.png", width:90%), [```sh apt-get install w3m-img```])
После успешной установки запустим браузер.
#img(image("img/20.png", width:90%), [```sh w3m google.com```])
== Установка текстового редактора «mousepad»
Соберем `mousepad` из исходников. Для этого перейдем на сайт `deb.debian.org/debian`.
#img(image("img/21.png", width:90%), [```sh w3m deb.debian.org/debian```])
А затем последовательно перейдем по ссылкам пути к директории `pool/main/m/`
Далее с помошью поиска (`/`) найдем `mousepad`.
#img(image("img/27.png", width:90%), [Поиск `/mousepad`])
#img(image("img/28.png", width:90%), [Поиск `/mousepad`])
Попадаем в директорию и ищем архив с исходниками.
#img(image("img/31.png", width:90%), [Архив с исходниками])
Нажимаем Enter и скачиваем файл.
#img(image("img/32.png", width:90%), [Загрузка завершена])
После выходим из браузера. При помощи комманды ```sh ls``` видим, что файл загружен и находится в домашней директории.
#img(image("img/33.png", width:90%), [Загруженный файл])
Распакуем архив при помощи утилиты ```sh tar```.
#img(image("img/34.png", width:90%), [```sh tar -xf mousepad_0.5.10.orig.tar.bz2```])
Теперь установим компилятор и стандартные библеотеки:\ ```sh apt-get install build-essential``` ```sh apt-get install intltool libgtk2.0-dev```\ ```sh apt-get install intltool gtk```
#img(image("img/35.png", width:80%), [```sh apt-get install build-essential```])
#img(image("img/36.png", width:80%), [```sh apt-get install build-essential```])
#img(image("img/37.png", width:70%), [```sh apt-get install intltool libgtk2.0-dev```])
#img(image("img/38.png", width:70%), [```sh apt-get install intltool libgtk2.0-dev```])
#img(image("img/41.png", width:70%), [```sh apt-get install intltool gtk```])
#img(image("img/42.png", width:70%), [```sh apt-get install intltool gtk```])
#img(image("img/44.png", width:70%), [```sh apt-get install intltool gtksourceview```])
#img(image("img/45.png", width:70%), [```sh apt-get install intltool gtksourceview```])
Переходим в распакованный каталог, собираем и устанавливаем:\
```sh cd mousepad_0.5.10```\
```sh ./configure```\
```sh make```\
```sh make install-strip```
#img(image("img/46.png", width:70%), [```sh ./configure```])
#img(image("img/48.png", width:70%), [```sh make```])
#img(image("img/50.png", width:70%), [```sh make install-strip```])
#img(image("img/51.png", width:70%), [```sh make install-strip```])
Итак, мы установили `mousepad`. Теперь перезагрузим терминал и зайдем в лог `xorg`.
#img(image("img/58.png", width:70%), [Лог `xorg`])
Далее в лабораторных работах я буду использовать `neovim` так как для меня этот редактор удобнее. Установил я его коммандой ```sh apt-get install neovim```. Конфигурацию тоже написал я, ее исходники лежат по адресу `github.com/pluttan/dotfiles/nvim`.
== Установка и настройка панелей
По умолчанию Openbox предоставляет пользователю лишь рабочий стол
с контекстным меню. Для получения более привычного способа управления
нужно установить панели. Среди самых популярных панелей для Openbox
можно выделить `xfce4-panel`, `lxpanel` и `tint2`. Первые две входят в состав `Xfce`
и `LXDE` соответственно.
Для установки `xfce4-panel` необходимо выполнить команду:
```sh apt-get install dbus-x11 xfce4-panel```
#img(image("img/61.png", width:70%), [```sh apt-get install dbus-x11 xfce4-panel```])
Для запуска панели необходимо набрать в терминале:
```sh xfce4-panel```
После этого будет показан диалог первого запуска, необходимо выбрать
«Использовать настройки по умолчанию».
#img(image("img/62.png", width:70%), [```sh xfce4-panel```])
#img(image("img/63.png", width:70%), [```sh xfce4-panel```])
#img(image("img/64.png", width:70%), [```sh xfce4-panel```])
Однако при закрытии окна консоли панель пропадёт. Она пропала из-за
того, что родителем процесса панели являлся процесс окна консоли. Этот
недостаток может быть исправлен запуском параллельных процессов.
#img(image("img/65.png", width:70%), [```sh kitty||xfce4-panel```])
Настроим верхнюю панель. Для этого нужно щёлкнуть правой клавишей
мыши по панели, после чего появится меню. В этом меню нужно выбрать пункт «Параметры панели», после чего вокруг панели появится выделение и откроется окно настроек.
#img(image("img/67.png", width:70%), [Меню])
#img(image("img/68.png", width:70%), [Настройки])
Над вкладками находится переключатель панелей (раскрывающийся
список) и кнопки добавления/удаления панелей.
Вкладка «Экран» позволяет настроить такие опции, как ширину панели,
возможность перетаскивать панель, ширину панели, автоматическое скрытие
и т.д.
Вкладка «Внешний вид» содержит всего одну опцию, позволяющую
выбрать стиль панели: системный, цвет или изображение.
Вкладка «Элементы» содержит список элементов, размещённых на
панели. Их можно перемещать (клавиши с зелёными стрелками),
настраивать, удалять и добавлять.
Настроим нижнюю панель следующим образом: постоянная ширина,
возможность перетаскивания по экрану, автоскрытие.
Для настройки нижней панели нужно выбрать «Панель 2» в
переключателе панелей. На вкладке «Экран» уберем отметку с пункта
«Закрепить панель» и поставить в «Автоматически показывать и скрывать
панель», ширину установить 45пикселов и длину 25%.
#img(image("img/68.png", width:70%), [«Экран»])
На вкладке
«Элементы» убрать все элементы, кроме «Показать рабочий стол»,
разделитель и «Каталог». Разделитель настроить следующим образом: стиль
– прозрачный, установить отметку в пункте «Расширять». После закрытия
окна настройки панель скроется, при наведении на неё курсора она
развернётся. Теперь панель можно перетаскивать по всему экрану (захватив
курсором одно из мест по краю панели, отмеченных точками)
#img(image("img/69.png", width:60%), [«Элементы»])
#img(image("img/70.png", width:70%), [Результат])
== Настройка autostart
Как было отмечено, панель закрывается при закрытии окна терминала,
из которого она была вызвана. Это можно исправить с помощью настроек
автозапуска.
В этом пункте работы будет использоваться системный
скрипт autostart. Openbox может быть настроен для каждого пользователя
отдельно, тогда файлы autostart, environment, rc.xml и menu.xml должны
содержаться в домашнем каталоге каждого пользователя
(`~/.config/openbox/`). При отсутствии этих файлов Openbox обращается к
системным, хранящимся в папке `/etc/xdg/openbox/`. Эти файлы лучше
оставлять неизменными или исправлять очень аккуратно, так как ошибка в
них может вызвать негативные последствия. Особенно этот факт
должны иметь в виду системные администраторы, многие программы
работают по такому принципу.
Добавим автозапуск панели и терминала для всех пользователей.
Откроем в `neovim` файл `autostart`:
```sh nvim /etc/xdg/openbox/autostart```
#img(image("img/73.png", width:70%), [```sh nvim /etc/xdg/openbox/autostart```])
#img(image("img/74.png", width:70%), [Исправленный файл `autostart`])
#pagebreak()
== Файловый менеджер
Установим PCManFM:
```sh apt-get install pcmanfm```
#img(image("img/77.png", width:70%), [```sh apt-get install pcmanfm```])
Файловый менеджер вызывается командой ```sh pcmanfm```.
#img(image("img/99.png", width:70%), [```sh pcmanfm```])
Я буду пользоваться файловым менеджером `yazi`.
#img(image("img/81.png", width:70%), [```sh yazi```])
== Настройка рабочего стола
Для организации привычного пользователю Windows окружения не
хватает, как минимум, одного важного элемента: иконок на рабочем столе.
Для отображения иконок могут использоваться отдельные программы. В
данной ЛР предлагается использовать `idesk`. Вторым элементом, который
будет добавлен на рабочий стол, будет менеджер системных ресурсов `conky`.
Для отображения иконок рабочего стола нужно установить `idesk`:
```sh apt-get install idesk```
#img(image("img/83.png", width:70%), [```sh apt-get install idesk```])
При попытке вызова будет выдана ошибка. Она объясняется
отсутствием необходимой папки, её можно создать следующей командой:
```sh mkdir ~/.idesktop```
#img(image("img/84.png", width:70%), [```sh mkdir ~/.idesktop```])
Результат повторного запуска `idesk`:
#img(image("img/85.png", width:70%), [```sh idesk```])
Необходимо исправить скрипт `autostart`. Теперь он будет
выглядеть так:
#img(image("img/86.png", width:70%), [`autostart`])
Теперь необходимо попробовать создать ярлык на рабочем столе.
Ярлыки в idesk хранятся в виде файлов lnk. Для создания ярлыка (и открытия
его для редактирования) для mousepad нужно выполнить следующую команду:
```sh nvim ~/.idesktop/leafpad.lnk```
В данной команде используется особенность большинства редакторов в
UNIX-системах: если файл существует, он открывается, если нет – он
создаётся.
#img(image("img/87.png", width:70%), [Файл создан])
В файле необходимо набрать следующее:
```sh
table Icon
Caption: Mousepad
Command: /usr/bin/mousepad
Icon: /usr/share/icons/gnome/32x32/apps/accessories-texteditor.png
Width: 32
Height: 32
X: 100
Y: 100
end
```
#img(image("img/88.png", width:70%), [Добалена конфигурация ярлыка])
Это вызовет ошибку связанную с неустановленным `GNOME` поэтому я установил весь `GNOME`, а после отключил его функционал.
#img(image("img/91.png", width:70%), [Ошибка])
Перезагрузить `idesk` можно введя сделующие комманды: ```sh killall idesk``` ```sh idesk```
#img(image("img/89.png", width:70%), [```sh killall idesk``` ```sh idesk```])
#img(image("img/92.png", width:70%), [Иконка создана])
Преимуществом хранения ярлыков в таком формате является гибкая
настройка. Возможно настроить не только размер и положение, но и
реакцию на отдельные кнопки мыши. Так, `Command[0]` отвечает за реакцию
на двойное нажатие левой кнопки мыши, `Command[1]` – за двойное
нажатие правой. Поменяем название ярлыка на `TextEditor` и сделаем так,
чтобы при двойном щелчке левой клавишей мыши открывался `Mousepad`, при
двойном щелчке правой – `neovim` в новом окне `kitty`.
#img(image("img/94.png", width:70%), [Исправленная конфигурация])
Теперь необходимо настроить отображение иконок в `PCManFM`. Он
использует библиотеку `GTK`, следующая команда скачает и установит
иконки, которые будут использоваться всеми `GTK`-приложениями:
```sh apt-get install tango-icon-theme```
Для того, чтобы именно эти иконки использовались в GTKприложениях, необходимо создать для них конфигурационный файл:
```sh nvim ~/.gtkrc-2.0```
В этом файле необходимо прописать следующую строчку:
```sh gtk-icon-theme-name="Tango"```
#img(image("img/97.png", width:70%), [Исправленная конфигурация])
#img(image("img/118.png", width:70%), [Новые иконки])
== Установка и настройка `conky`
`conky` представляет собой монитор системных ресурсов. Это гибкая
утилита, позволяющая отслеживать такие параметры, как использование ОЗУ
и диска, нагрузку на ЦП. Однако conky может отображать даже новости и
погоду.
Для установки `conky` надо выполнить:
```sh apt-get install conky```(```sh apt-get install conky-all```)
#img(image("img/100.png", width:70%), [```sh apt-get install conky-all```])
Для настройки `conky` необходимо отредактировать его
конфигурационный файл:
```sh nvim /etc/conky/conky.conf```
#img(image("img/101.png", width:70%), [```sh nvim /etc/conky/conky.conf```])
Как и в случае с настройкой `Openbox`, это общий файл.
Пользовательские файлы настроек conky должны лежать по адресу
`~/.conkyrc`.
Необходим изменить положение `conky`. Для этого замените строку
`alignment top_left`
на
`alignment top_right`
В секции `conky.text` задается текст, выводимый на панель `conky`.
Следующая строка добавит в conky отображение имени пользователя в
системе:
```sh ${color grey} Current user: $USER```
#img(image("img/102.png", width:70%), [```sh nvim /etc/conky/conky.conf```])
Перезапустим `conky` и увидим результат:
#img(image("img/104.png", width:70%), [`conky`])
Наконец, необходимо отредактировать скрипт автозапуска, добавив в
него `conky`, теперь скрипт должен выглядеть следующим образом:
#img(image("img/105.png", width:70%), [`autostart`])
== Настройка фона рабочего стола
Скачаем большую коллекцию фонов для рабочего стола: `https://github.com/D3Ext/aesthetic-wallpapers`.
#img(image("img/106.png", width:70%), [`aesthetic-wallpapers`])
Откроем текстовым редактором файл `/root/.ideskrc`, и зададим полный
путь к файлу фоновой картинки в параметре `Backgroung.file`. Убедитесь,
что после имени файла нет пробела. Перезапустим `idesk`.
#img(image("img/107.png", width:70%), [`/root/.ideskrc`])
#img(image("img/119.png", width:70%), [`/root/.ideskrc`])
#img(image("img/108.png", width:70%), [Результат])
== Настройка расширения экрана
Отредактируем `xorg.conf` так:
#img(image("img/113.png", width:70%), [`xorg.conf`])
Перезапустим `xorg` и получим финальный результат:
#img(image("img/117.png", width:100%), [финальный результат])
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/modulize-packages.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.page.with(title: "外部库")
除此之外,可以从特殊的路径从网络导入外部模块,即外部库(external packages)。Typst的外部库机制可能不是世界上最精简的,但是我所见过当中最精简的。它可能更稍显简陋,但已经有上百个外部库通过官方渠道发布,并足以满足我们日常生活的使用。
在Typst中使用外部库极为简单,你只需要`import`特定的路径就能访问其内部的变量声明。例如你可以导入一个用于绘画自动机的外部库:
#code(```typ
#import "@preview/fletcher:0.4.0" as fletcher: node, edge
#align(center, fletcher.diagram(
node((0, 0), $S_1$),
node((1, 0), $S_2$),
edge((1, 0), (0, 0), $g$, "..}>", bend: 25deg),
edge((0, 0), (1, 0), $f$, "..}>", bend: 25deg),
))
```)
其中,以下一行代码完成了导入外部库的所有工作。我们注意到其完全为`import`语法,唯一陌生的是其中的路径格式:
```typ
#import "@preview/fletcher:0.4.0" as fletcher: node, edge
```
解读路径#text(red, `@preview`)`/`#text(eastern, `fletcher`)`:`#text(orange, `0.4.0`)的格式,它由三部分组成。
=== 「命名空间」,#text(red, `@preview`)
以`@`字符开头。目前仅允许使用两个命名空间:
- #text(red, `@preview`):Typst仅开放`beta`版本的包管理机制。所有`beta`版本的都在`preview`命名空间下。
- #text(red, `@local`):Typst建议的本地库命名空间。
=== 「库名」,#text(eastern, `fletcher`)
必须符合变量命名规范:
+ 以ASCII英文字符(`a-z`或`A-Z`)开头;
+ 跟随任意多个ASCII英文或数字字符(`a-z`或`A-Z`或`0-9`)或下划线(`_`)或中划线(`-`)。
例如`OvO`、`O_O`、`O-O`都是合法的库名。但是`0v0`不是合法库名,因为其以数字零开头。
=== 「版本号」,#text(orange, `0.4.0`)
必须符合#link("https://semver.org/")[SemVer]规范。
如果你不能很好地阅读和理解#link("https://semver.org/")[SemVer]规范,仅记住合法的版本号由三个递增的数字组成,并用「点号」(`.`)分隔;版本号之间可以相互比较,且比较版本时按顺序比较数字。例如`0.0.0`、`0.10.0`、`1.5.11`、`1.24.1`是合法且递增的版本号。
+ #text(red, `1`)`.0.11`比#text(red, `0`)`.10.0`大,因为#text(red, `1`)大于#text(red, `0`);
+ `1.`#text(red, `24`)`.1`比`1.`#text(red, `5`)`.11`大,因为#text(red, `24`)大于#text(red, `5`);
+ `1.24.0`与`1.24.0`相等。
== 下载外部库
一般来说,使用外部库与导入本地模块一样简单。当你尝试导入一个外部库时,Typst会立即启动下载线程为你从网络下载外部库代码:
```typ
#import "@preview/fletcher:0.4.0" as fletcher: node, edge
```
一般情况下,从网络下载外部库的时间不会超过十秒钟,并且不需要任何额外配置。但由于不可描述的原因,你有可能需要为下载线程配置代理。当你希望通过网络代理下载外部库时,请检查全局环境变量`HTTP_PROXY`和`HTTPS_PROXY`是否成功设置。
+ 如果你的网络代理软件包含环境变量设置,请*优先*在你的网络代理环境中配置。
+ 否则如果你是Linux用户,请检查启动`typst-cli`或`vscode`的shell中,使用`echo $HTTP_PROXY`检查是否包含该环境变量。
+ 否则如果你是Windows用户,请使用`Win + R`快捷键呼出运行窗口,执行`system`#sym.zws`properties`#sym.zws`advanced`,调出「环境变量」窗口,并检查是否包含该环境变量。
#figure(align(center, image("./systempropertiesadvanced.png", width: 50%)))
== 库文件夹
上一小节中的「命名空间」对应本地的一个或多个文件夹。
首先,Typst会感知你系统上的“数据文件夹”和“缓存文件夹”并在其中存储库代码。
Typst将会在`{cache-dir}/`#text(green, `typst/packages`)中缓存从网络下载的库代码。其中`{cache-dir}`在不同的操作系统上:
- 在Linux上对应为`$XDG_CACHE_HOME` or `~/.cache`。
- 在macOS上对应为`~/Library/Caches`。
- 在Windows上对应为`%LOCALAPPDATA%`。
Typst同时会检查`{data-dir}/`#text(green, `typst/packages`)中是否包含相应的库。其中`{data-dir}`在不同的操作系统上:
- 在Linux上对应为`$XDG_DATA_HOME` or ~/.local/share。
- 在macOS上对应为`~/Library/Application Support`。
- 在Windows上对应为`%APPDATA%`。
#let breakable-path(..contents) = contents.pos().join([#sym.zws`/`#sym.zws])
当你尝试引入`preview`命名空间中的外部库#breakable-path(
text(red, `@preview`),
[#text(eastern, `fletcher`)`:`#text(orange, `0.4.0`)],
)时,Typst会严格*按顺序*做如下事情。
+ 检查数据文件夹。
检查是否包含对应库,其应当位于#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `preview`),
text(eastern, `fletcher`),
text(orange, `0.4.0`)
)。如果有,那么解析路径为对应库路径。
+ 检查缓存文件夹。
检查是否包含对应库,其应当位于#breakable-path(
`{cache-dir}`,
text(green, `typst/packages`),
text(red, `preview`),
text(eastern, `fletcher`),
text(orange, `0.4.0`)
)。如果有,那么直接解析路径为对应库路径。否则从网络下载库代码至对应位置。并解析路径为对应库路径。
简单来说,Typst会将库路径映射到你数据文件夹或缓存文件夹,优先按顺序使用已经存在的库代码,并按需从网络下载外部库。
Typst的该规则意味着你可以拥有以下几条特性。
其一,若你已经下载了网络库到本地,再次访问将不会再产生网络请求和检查远程库代码的状态。
其二,你可以将本地库存储到数据文件夹。特别地,你可以在数据文件夹中的`preview`文件夹中存储库,以*覆盖*缓存文件夹中已经下载的库。这有利于你调试或临时使用即将发布的外部库。
其三,你可以在本地随意创建新的命名空间,对于#breakable-path(
text(red, `@my-namespace`),
[#text(eastern, `my-package`)`:`#text(orange, `version`)],
),Typst将检查并使用你位于#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `my-namespace`),
text(eastern, `my-package`),
text(orange, `version`)
)的库代码。尽管Typst对命名空间没有限制,但建议你使用#text(red, `@local`)作为所有本地库的命名空间。
== 构建和注册本地库
本小节教你如何构建和注册本地库。由于库代码与文档代码并没有什么本质区别,这一节也供你参考组织多文件结构的Typst项目。
=== 元数据文件
在库的根目录下必须有一个名称为`typst.toml`的元数据文件,这是对代码库的描述。内容示例如下:
```toml
[package]
name = "example"
version = "0.1.0"
entrypoint = "lib.typ"
```
为了满足Typst对信息描述最低限度的要求,你仅需要填入以下三个字段:
- `name`:该库的名字。
- `version`:该库的版本号。
- `entrypoint`:库的入口文件。
其中,`entrypoint`字段建议始终为`lib.typ`,所以你仅需自行填写`name`和`version`字段即可满足最低要求。
=== 入口文件
你可以在元数据文件中配置入口文件路径。一般来说,该文件对应为库的根目录下的`lib.typ`文件。
你可以使用本节提及的《变量导出的三种方式》编写该文件。当导入该库时,其中的「变量声明」将提供给文档使用。
=== 示例库的文件组织
假设你希望构建一个`@local/example:0.1.0`的外部库供本地使用。你应该将`example`库的文件夹*拷贝或链接*到#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `local`),
text(eastern, `example`),
text(orange, `0.1.0`)
)路径。
创建#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `local`),
text(eastern, `example`),
text(orange, `0.1.0`),
`typst.toml`
)文件,并包含以下内容:
```toml
[package]
name = "example"
version = "0.1.0"
entrypoint = "lib.typ"
```
创建#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `local`),
text(eastern, `example`),
text(orange, `0.1.0`),
`lib.typ`
)文件,并包含以下内容:
```typ
#import "add.typ": add
#import "sub.typ": sub
```
这样你就可以在本地的任意文档中使用库中的`add`或`sub`函数了:
```typ
#import "@local/example:0.1.0" as example: add, sub as subtract
```
== 发布库到官方源
略
== 再谈「根目录」
在Typst编译器中,任意文件都被编码为以下两个字段的组合:
+ `package`,表示该文件所属的库,将决定文件所属的「根目录」。
+ `path`,表示该文件夹相对于库「根目录」的位置。
如果`package`字段为空(```rs None```),那么表示该文件属于文档本身。这意味着文件路径的根目录为文档的根目录。
否则,表示该文件属于某个库。考虑前面小节中Typst解析库文件夹的过程,文件路径的根目录将改变为你数据文件夹或缓存文件夹中的某个子文件夹。这意味着,如果在库中使用绝对路径或相对路径,「根目录」将发生相应改变。请回忆《绝对路径与相对路径》小节内容。
例如在文件夹`@local/example:0.1.0`的内部,设使内部文件#breakable-path(
`{data-dir}`,
text(green, `typst/packages`),
text(red, `local`),
text(eastern, `example`),
text(orange, `0.1.0`),
`src/add-simd.typ`
)中包含这样的代码。
```typ
#read("/typst.toml")
#read("../typst.toml")
```
则「根目录」被解析为#breakable-path(
`{data-dir}`,
text(eastern, `{example-lib}`),
)。
绝对路径`/typst.toml`被解析为#breakable-path(
`{data-dir}`,
text(eastern, `{example-lib}`),
`typst.toml`
)
相对路径`../typst.toml`被解析为#breakable-path(
`{data-dir}`,
text(eastern, `{example-lib}`),
`src`,
`..`,
`typst.toml`
)
== 函数与闭包中的路径解析
这里有一个微妙的问题。在函数或闭包中请求解析一个绝对路径或相对路径,Typst会如何做?
答案是,任何路径解析都依附于路径解析代码所在文件。这句话有些晦涩,但例子却容易懂。这里举两个例子。
假设函数在文档相对于根目录的`/packages/m1.typ`中被声明:假设其中有这样一个函数:
```typ
#let parse-code(path) = {
let content = read(path)
return parse-text(content)
}
```
那么无论我们在哪个文件引入了`parse-code`函数,其`read(path)`的路径解析都是固定的,其绝对路径相对于文档根目录,其相对路径相对于`/packages/m1.typ`的父目录。例如:
- 调用`parse-code("/abc.typ")`时,该函数始终读取`/abc.typ`文件。
- 调用`parse-code("../def.typ")`时,始终读取`/packages/../def.typ`文件。
假设函数在某个库的`/src/m1.typ`中被声明,则其绝对路径相对于*库根目录*,其相对路径相对于`/src/m1.typ`的父目录。
这种行为在有的时候不是你期望的,但你可以同样通过传递一个来自文档的闭包绕过该限制。例如,`parse-code`改写为:
```typ
#let parse-code(path, read-file: read) = {
let content = read-file(path)
return parse-text(content)
}
```
并且在调用时传入一个读取文件的「回调函数」
```typ
#parse-code("../def.typ", read-file: (p) => read(p))
```
|
https://github.com/jens-hj/ds-exam-notes | https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/lectures/12.typ | typst | #import "../lib.typ": *
#show link: it => underline(emph(it))
#set math.equation(numbering: "(1)")
#set enum(full: true)
#set math.mat(delim: "[")
#set math.vec(delim: "[")
#set list(marker: text(catppuccin.latte.lavender, sym.diamond.filled))
#show heading.where(level: 1): it => text(size: 22pt, it)
#show heading.where(level: 2): it => text(size: 18pt, it)
#show heading.where(level: 3): it => {
text(size: 14pt, mainh, pad(
left: -0.4em,
gridx(
columns: (auto, 1fr),
align: center + horizon,
it, rule(stroke: 1pt + mainh)
)
))
}
#show heading.where(level: 4): it => text(size: 12pt, secondh, it)
#show heading.where(level: 5): it => text(size: 12pt, thirdh, it)
#show heading.where(level: 6): it => text(thirdh, it)
#show emph: it => text(accent, it)
#show ref: it => {
//let sup = it.supplement
let el = it.element
if el == none {
it.citation
}
else {
let eq = math.equation
// let sup = el.supplement
if el != none and el.func() == eq {
// The reference is an equation
let sup = if it.fields().at("supplement", default: "none") == "none" {
[Equation]
} else { [] }
// [#it.has("supplement")]
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#sup #n]
}
else if it.citation.has("supplement") {
if el != none and el.func() == eq {
show regex("\d+"): set text(accent)
let n = numbering(el.numbering, ..counter(eq).at(el.location()))
[#el.supplement #n]
}
else {
text(accent)[#it]
}
}
}
}
=== Data Deduplication
- If you already have data stored that
==== Cost of Data
- File size itself
- Cost of redundancy
*Two Questions*
- Can we reduce storage costs
- Can we reduce the cost of redundancy
==== Example
- Send and email to 100 employees with a 10MB attachment
- What is the cost of sending this email?
- $10"MB" times 100 + 100 times "rest of mail" = 1"GB" + 100 times "rest of mail"$ (without redundancy)
- $10"MB" times 3 times 100 + 100 times "rest of mail" = 3"GB" + 100 times "rest of mail"$ (with redundancy)
*Instead:*
- Store the 10MB attachment once
- $10"MB" + "overhead" + 100 times "rest of mail"$
==== Idea
- Instead of doing deduplication at file level
- Recognise bit-patterns within files and deduplicate at bit-level
- *Or at a _block level_ #sym.arrow.l This is the one used (Fixed size block, variable-sized is very uncommon and difficult)*
- Do this across all files
- Think of it as lego, going from the finished build to the list of bricks
- Store the list of bricks and _the instructions_
- The more data you store, the more opportunities for deduplication
- Instruction are typically an index to a table containing a pointer to the data
*Goal:*
- Eliminate storage of data with same content
==== Challenges
- Can we preserve performance?
- Can we support general file system operations?
- Read, write, modify, delete
- Can we deploy deduplication on low-cost commodity hardware?
- A few GB of RAM, 32/64-bit CPU, standard OS
- Maybe a small server
- Or you want each node to be part of computation
=== Practical Ideas
- *Deduplication in backup systems*
- Assume no modifications
- *Deduplication file systems*
- ZFA, OpenDedup SDFS
- Consumes significant memory
- *VM image storage?*
- VM images are large and have a lot of common data
==== Compare Blocks
- Don't compare every single block
- Cryptographic hashing
- MD5, SHA-1
- Hashing is fast
- Probability of getting different content with same hash is _very low_
- Combat by having larger hashes
*How often do I get matches?*
- Birthday paradox
- $N$ people, what is the probability that two people have the same birthday?
- Number of values to test to have a probability of at least one collision greater than 50%
is $N^(1"/"2)$ for $N$ possible values \
#ra Block size of $N = 2^n$ \
#ra Need $2^(n"/"2)$ values to have a 50% chance of a collision \
- Above is _worst case_ with equal probabilities for each block \
#ra typically there is _more correlation_ in data
==== When to Delete Blocks
- When no file references it
- This requires exploring/analysing all files to find references
*Instead:*
- Keep count of how many times a block is referenced
- This should be part of the initial processing
- Decrement count for all blocks referenced by a file when it is deleted
- This count gives a notion of _importance_ of a block
==== Where to put index structure
*RAM*
- Hadoop, ZFS
- Fast, but limited by RAM size
- Per 1TB of data, around 4GB of RAM is needed
*Disk*
- Updating each data block moves the disk head
- Impacts performance #ra Slow
*LiveDFS*
- Partial storage of fingerprints in memory
- Rest on disk
- Balance between RAM and disk
- Per 1TB of data, around 1.6GB of RAM is needed
==== Important Slides
#image("../img/12/dd-ss.png")
=== Generalised View
- Block basis + deviation
- Maximise similarities in data
- Gains start earlier
- Easier to find matches
==== Important Slides
#image("../img/12/dd-gen.png") |
|
https://github.com/matthiasGmayer/typst-math-template | https://raw.githubusercontent.com/matthiasGmayer/typst-math-template/main/template.typ | typst | #import "common_symbols.typ": *
#import "manage.typ"
// The project function defines how your document looks.
// It takes your content and some metadata and formats it.
// Go ahead and custo// Go ahead and customize it to your liking!
#let cont_to_text(cont) = {
if cont.has("text") {cont.text}
else if cont.has("children") {cont.children.map(c => c.text).join("")}
}
#let labeled(label_cont) = {
let text = cont_to_text(label_cont)
[#[]#label(text)]
}
#let styling(body) = {
set cite(style: "alphanumerical")
set par(justify: true)
set heading(numbering: "1.1 ")
set text(font: "New Computer Modern", lang: "en")
show math.equation: set text(weight: 400)
show "TODO": t => text(red)[*#t*]
body
}
#let sub_project(body, already:false) = {
// set heading(numbering: "1.")
// if not already {
// set par(justify: true)
// set heading(numbering: "1.")
// set text(font: "New Computer Modern", lang: "en")
// show math.equation: set text(weight: 400)
// show "TODO": t => text(red)[*#t*]
// bibliography("citations.yml")
// }
styling(body)
}
#let project(
title: "",
abstract: [],
authors: (),
type:"",
department: "",
institution: "",
supervisors: (),
date: none,
body,
) = {
// Set the document's basic properties.
set page(numbering: "1", number-align: center)
set document(author: authors.map(a => a.name), title: title)
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center)[
*#author.name* \
#author.email
]),
),
)
linebreak()
align(center,type)
align(center,department + "\n" + institution)
linebreak()
if supervisors.len() > 0 {align(center)[Supervisor:]}
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..supervisors.map(author => align(center)[
*#author.name* \
#author.email
]),
)
//abstract
v(3em)
set par(justify: true)
heading(outlined: false, numbering: none, text(0.85em, smallcaps[Abstract]))
abstract
// Main body.
// let sub_project = sub_project.with(already: true)
styling[
#body
]
labeled[end_end]
}
// #let theorem_block(cont) = block(width:100%, stroke: luma(250), outset: 8pt, radius: 4pt,cont)
#let theorem_block(name, cont) = {
// if name == "Example" or name == "RSmmary" [
// #block(
// width:100%, stroke: luma(240), outset: 8pt, radius: 4pt, spacing: 16pt,
// cont)
// ] else [
// #block(width:100%)[#cont]
// ]
block(width:100%)[#cont]
}
// #let theorem_block(cont) = block(width:100%, stroke: luma(250), outset: 8pt, radius: 4pt,cont)
#let count_block_name = state("count_block_name")
#let count_block_loc = state("count_block_loc","HELLO")
#let countblock(name, conts, level: 3) = {
count_block_name.update(name)
counter(heading).step(level: level)
if conts.len() == 1 [
#block(width:100%)[
*#name
#locate(loc => count_block_loc.update(loc))
#counter(heading).display("1.")*
#conts.at(0)
]
] else [
#block(width:100%)[
*#name
#locate(loc => count_block_loc.update(loc))
#counter(heading).display("1.1")* (#conts.at(0)).
#conts.at(1)
]
]
}
#let default_level = 3
#let definition(..conts, level: default_level) = countblock("Definition", conts.pos(), level: level)
#let theorem(..conts, level: default_level) = countblock("Theorem", conts.pos(), level: level)
#let example(..conts, level: default_level) = countblock("Example", conts.pos(), level: level)
#let lemma(..conts, level: default_level) = countblock("Lemma", conts.pos(), level: level)
#let corollary(..conts, level: default_level) = countblock("Corollary", conts.pos(), level: level)
#let remark(..conts, level: default_level) = countblock("Remark", conts.pos(), level: level)
#let summary(..conts, level: default_level) = countblock("Summary", conts.pos(), level: level)
#let notation(..conts, level: default_level) = countblock("Notation", conts.pos(), level: level)
#let proof(cont) = [#block[_Proof_. #cont #h(5pt)#h(1fr)$square.big$]]
#let cref(label_cont, fun:(label,location) => ref(label), allow_nonref:true) = {
let my_label_text = cont_to_text(label_cont)
let my_label = label(my_label_text)
locate(loc => {
let labels = query(my_label, loc)
let count = labels.len()
if count == 0 {
if manage.is_main_document.at(loc) and not allow_nonref {
ref(my_label) // gives error: label not found.
}
else {
text(red)[*#my_label_text*]
}
}
else {
fun(my_label, labels.at(0).location())
}
})
}
#let tref(label_cont) = {
cref(label_cont, fun:(label, location) => link(count_block_loc.at(location))[#count_block_name.at(location)~#numbering("1.1",..counter(heading).at(location))])
}
#let ccite(cite_cont) = {
let my_cite_text = cont_to_text(cite_cont)
locate(loc =>
if manage.is_main_document.at(loc) {
cite(my_cite_text)
} else {
text(red)[#my_cite_text]
}
)
}
#let graph_node(pos, radius, unit:1pt, cont, offset) = {
style(styles=>{
let size = measure(cont,styles)
let posu = ((pos.at(0)-radius) * unit, (pos.at(1)-radius) * unit)
place(dx: posu.at(0), dy: posu.at(1))[#circle(inset: 1pt
,radius:radius*unit
)[#cont]
// []
]
// place[#align(center)[hehale]]
// place(dx: posu.at(0)+size.width/2+offset.at(0)*unit, dy: posu.at(1)+size.height/2+offset.at(1)*unit, cont)
// place(cont)
})
}
#let graph_arrow(start, end, pad_start: 0, pad_end: 0, arrow_len: 8pt, unit:1pt) = {
let deg = calc.atan2(start.at(0)-end.at(0),start.at(1)-end.at(1))
let sindeg = calc.sin(deg)
let cosdeg = calc.cos(deg)
let startu = ((start.at(0)-pad_start*cosdeg) * unit, (start.at(1)-pad_start*sindeg) * unit)
let endu = ((end.at(0)+ pad_end*cosdeg) * unit, (end.at(1) + pad_end*sindeg) * unit)
place[#line(start:startu, end:endu)]
place[#line(start: endu, angle: deg+30deg, length: arrow_len)]
place[#line(start: endu, angle: deg -30deg, length: arrow_len)]
}
#let graph(nodes, arrows, radius,pad_start:0, pad_end:10, offset:(0,0)) = {
block(height: pad_start * 1pt)
let maxy = 0
for (pos, cont) in nodes {
graph_node(pos,radius,cont, offset)
maxy = calc.max(pos.at(1), maxy)
}
for (i1,i2) in arrows {
graph_arrow(nodes.at(i1).at(0),nodes.at(i2).at(0), pad_start:radius, pad_end:radius)
}
block(height: (maxy + pad_end) * 1pt)
}
#let sep = {
let space = -5pt
v(space)
line(start: (-5%,0%), length: 107.5%, stroke: 0.1pt)
v(space)
}
#let tableofcontents = [
#text(weight: "bold", size: 1.5em)[Contents] \
#locate(loc => {
let headings = query(heading, loc)
for head in headings {
if head.numbering == none {continue}
let number = counter(heading).at(head.location())
link(head.location(), {
box(width: 1.5em) * (number.len()-1)
if head.numbering != none {box(width: 1.5em + (number.len()-1) * 0.5em, numbering(head.numbering, ..number))}
if head.level == 1 {text(weight: "bold")[#head.body]}
else {head.body}
box(width: 1em)
box(repeat([.]), width: 1fr)
box(width: 2em, align(right, [#head.location().page()]))
linebreak()
})
}
let head = headings.at(-1)
link(head.location(), {
box(width: 1.5em)
text(weight: "bold")[#head.body]
box(width: 1em)
box(repeat([.]), width: 1fr)
box(width: 2em, align(right, [#head.location().page()]))
})
})
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-FE50.typ | typst | Apache License 2.0 | #let data = (
("SMALL COMMA", "Po", 0),
("SMALL IDEOGRAPHIC COMMA", "Po", 0),
("SMALL FULL STOP", "Po", 0),
(),
("SMALL SEMICOLON", "Po", 0),
("SMALL COLON", "Po", 0),
("SMALL QUESTION MARK", "Po", 0),
("SMALL EXCLAMATION MARK", "Po", 0),
("SMALL EM DASH", "Pd", 0),
("SMALL LEFT PARENTHESIS", "Ps", 0),
("SMALL RIGHT PARENTHESIS", "Pe", 0),
("SMALL LEFT CURLY BRACKET", "Ps", 0),
("SMALL RIGHT CURLY BRACKET", "Pe", 0),
("SMALL LEFT TORTOISE SHELL BRACKET", "Ps", 0),
("SMALL RIGHT TORTOISE SHELL BRACKET", "Pe", 0),
("SMALL NUMBER SIGN", "Po", 0),
("SMALL AMPERSAND", "Po", 0),
("SMALL ASTERISK", "Po", 0),
("SMALL PLUS SIGN", "Sm", 0),
("SMALL HYPHEN-MINUS", "Pd", 0),
("SMALL LESS-THAN SIGN", "Sm", 0),
("SMALL GREATER-THAN SIGN", "Sm", 0),
("SMALL EQUALS SIGN", "Sm", 0),
(),
("SMALL REVERSE SOLIDUS", "Po", 0),
("SMALL DOLLAR SIGN", "Sc", 0),
("SMALL PERCENT SIGN", "Po", 0),
("SMALL COMMERCIAL AT", "Po", 0),
)
|
https://github.com/tony-rsa/thonifho.muhali.cv | https://raw.githubusercontent.com/tony-rsa/thonifho.muhali.cv/main/src/sections/en/education.typ | typst | MIT License | #import "../../template.typ": *
#cvSection("Education")
#cvEntry(
title: [M.Sc. Informatics],
host: [#link("https://shorturl.at/cjxPZ")[#ln #hSpc() Technical University of Munich] #hDot() Full-time],
date: [October 2022 — March 2023 (6 months)],
mode: [Munich, Germany #hDot() On-site],
logo: "assets/logos/tum.png",
desc: [Courses: #hSpc() Software Engineering Patterns #hBar() Distributed Systems #hBar() Virtualization Methods],
)
#cvEntry(
title: [M.Sc. Computer Science and Applied Mathematics],
host: [#link("https://shorturl.at/qTV46")[#ln #hSpc() Moscow Aviation Institute] #hDot() Part-time],
date: [September 2021 — August 2023 (2 years)],
mode: [Moscow, Russia #hDot() Hybrid],
logo: "assets/logos/mai.png",
desc: [Courses: #hSpc() Architecture of Highload Services #hBar() Backend Development #hBar() Parallel Computing],
)
#cvEntry(
title: [B.Sc. Business and Economics],
host: [#link("https://shorturl.at/fQRX4")[#ln #hSpc() Higher School of Economics] #hDot() Full-time],
date: [September 2016 — August 2020 (4 years)],
mode: [Saint Petersburg, Russia #hDot() On-site],
logo: "assets/logos/hse.png",
desc: [Courses: #hSpc() Data Science #hBar() Statistical analysis #hBar() Economic Theory #hBar() Econometrics],
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/CHANGELOG/CHANGELOG-0.1.md | markdown | Apache License 2.0 | # v0.1.6
## Changelog since v0.1.6
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
- temporarily removed pdf exporter, which eliminates the bundle size of `typst_ts_renderer` about 6MB.
#### Feature
- implemented [proposal: Retrieve Text from Document](https://github.com/Myriad-Dreamin/typst.ts/blob/main/docs/proposals/2-retrieve-text-from-document.md)
- the used ligature glyph information are attached to the artifact.
# v0.1.5
## Changelog since v0.1.5
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
- rename `typst_renderer_ts` to `typst_ts_renderer`
#### Feature
- add `typst_ts_core::ArtifactExporter`
- canvas exporter supports rendering outline glyph, shape, and images.
- canvas exporter does not relies on rust graphics library, which eliminates the bundle size of `typst_ts_renderer` about 600KB.
#### Bugfix
- fix several unhandled cases in `typst_ts_renderer::ArtifactJsBuilder`
# v0.1.4
## Changelog since v0.1.4
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
#### Feature
- add docker image `myriaddreamin/typst.ts` to [ghcr.io](https://github.com/Myriad-Dreamin/typst.ts/pkgs/container/typst.ts).
- set visibility during rendering
- compiler add a format `rmp` ([rust message pack](https://docs.rs/rmp/latest/rmp/))
- introduce [canvas exporter](https://github.com/Myriad-Dreamin/typst.ts/blob/main/exporter/canvas/Cargo.toml)
#### Bugfix
# v0.1.3
## Changelog since v0.1.3
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
#### Feature
- introduce `@myriaddreamin/typst.angular` to provide angular component.
- reduce the size of `@myriaddreamin/typst.ts` by removing serde and serde_json from dependencies.
- using `JSON.parse` instead of serde_json.
- attach build info (compiler name and compiler version) to artifact.
#### Bugfix
# v0.1.2
## Changelog since v0.1.2
### Known Issues
- To export typst document as pdf format, enture `typst::eval::LANG_ITEMS` must be included in `[email protected]`. This can cause the overall package size to increase by approximately 6MB.
### Security Notes
No new security note.
### Changes
- The upstream `[email protected]` has been merged, which causes breaking changes of artifact format.
#### Feature
- upgrade es target of `@myriaddreamin/typst.ts` to es2020.
- publish `@myriaddreamin/typst.react` to npm.
- merge [hasher change](https://github.com/typst/typst/commit/d0afba959d18d1c2c646b99e6ddd864b1a91deb2) from upstream, which seems to significantly improves performance.
- add method `runWithSession` to `@myriaddreamin/typst.ts/TypstRenderer`.
- `@myriaddreamin/typst.ts/TypstRenderer` can now render document with multiple pages.
#### Bugfix
- fix bug that document cannot scroll.
# v0.1.1
## Changelog since v0.1.1
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
#### Feature
- add continuous integration with github actions.
#### Bugfix
- ensure that `typst-ts-fontctl` creates the directory for copying fonts on all platform.
- fix `typst-ts-cli` not working on linux.
# v0.1.0
## Changelog since v0.1.0
### Known Issues
No new known issue.
### Security Notes
No new security note.
### Changes
#### Feature
- add program `typst-ts-cli`, with [commands: compile, font:list](https://github.com/Myriad-Dreamin/typst.ts/blob/2478df888282af09dc814a481348745c4311f98f/cli/src/lib.rs).
- add program `typst-ts-fontctl` to download font assets from typst repo, [ref](https://github.com/Myriad-Dreamin/typst.ts/blob/2478df888282af09dc814a481348745c4311f98f/contrib/fontctl/src/main.rs).
- add `typst_ts_core::Artifact` to represent a precompiled document.
- add `typst_ts_core::Artifact::to_document` to convert an artifact to a `typst::doc::Document`.
- introduce `typst_ts_core::config::WorkspaceConfig` for configure workspace for compiler.
- introduce `typst_ts_core::config::CompileOpts` for control low-level behavior of compiler.
- add `@myriaddreamin/typst.ts/createTypstRenderer(pdfjsModule): TypstRenderer`.
- add method `init` and method `render` to `@myriaddreamin/typst.ts/TypstRenderer`.
- add `@myriaddreamin/typst.ts/preloadRemoteFonts: BeforeBuildFn`.
- add `@myriaddreamin/typst.ts/preloadSystemFonts: BeforeBuildFn`.
- add `@myriaddreamin/typst.react/<TypstDocument fill?='' artifact=''>`.
|
https://github.com/Tengs-Fan/Tengs-Penkwe | https://raw.githubusercontent.com/Tengs-Fan/Tengs-Penkwe/master/letter-nokia.typ | typst | #import "./template.typ": *
#show: layout
#set text(size: 12pt) //set global font size
#letterHeader(
myAddress: [1690 Western Parkway \ V6T 1V3, Vancouver, British Columbia],
recipientName: [Nokia],
recipientAddress: [Ottawa, Ontario],
date: [#datetime.today().display()],
subject: "Job Application for Service Router Platform Test Dev Student Co-op"
)
Dear Hiring Manager,
I am writing to express my keen interest in the Service Router Platform Test Dev Student position at Nokia Canada, starting in January 2024. I am currently a Computer Science student at the University of British Columbia, actively seeking opportunities to apply my skills in a real-world setting.
During my studies, I have built a strong base in programming and have gained hands-on experience with several tools that are important for this role. Here’s how my experiences make me a good fit for this position:
1. Through my coursework in the software engineering course (CPSC 310) at UBC, I learned the importance of testing in the software development cycle. I have spent considerable time testing various software components to ensure their reliability and functionality, which would be beneficial when developing automated test cases at Nokia.
2. Over the past 4 years, I have grown comfortable working with Linux, acquiring the necessary skills to work proficiently in a Linux-based regression environment, a critical component of this role.
3. I am familiar with using source control software such as Git, which will allow me to integrate well with Nokia's development environment and collaborate effectively with the team.
4. I gained valuable insights into hardware components during a personal project where I implemented a MIPS CPU using Verilog, which could be an asset in understanding and testing new hardware and software features at Nokia.
My academic experience have allowed me to hone my analytical and troubleshooting skills, enabling me to approach complex problems with innovative solutions. As a quick learner, I am eager to immerse myself in Nokia's cutting-edge technologies, adopting a hands-on approach to understand feature areas inside and out to test them thoroughly.
I am no stranger to collaborative environments, having worked closely with teams during mymany course. This experience, along with volunteering experience, has equipped me with good interpersonal skills and an understanding of diverse perspectives.
Thank you for considering my application. I am enthusiastic about the possibility of discussing how my background, skills, and motivations align with Nokia's mission and this role in particular.
Sincerely,
#letterSignature("/assets/signature.png")
#letterFooter()
|
|
https://github.com/tuto193/typst-uos-thesis | https://raw.githubusercontent.com/tuto193/typst-uos-thesis/main/glossaries.typ | typst | MIT License | #let abbreviations = (
"vip": ("VIP", "Very Important Person"),
"vcp": ("VRP", "Very Cool People"),
)
// #let symbols = (
// "rvec": ($bold(v)$, "Random vector: a location in n-dimensional Cartesian space, where each dimensional component is determined by a random process", $bold(v)$),
// )
// #let glossaries = (
// "computer": ("computer", "A programmable machine that receives input data, stores and manipulates the data, and provides formatted output", "computer")
// )
#let GLOSSARIES = (
abbreviation: abbreviations
// symbol: symbols,
// glossary: glossaries
)
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/convex-hull-working-1.typ | typst | #import "@local/typkit:0.1.0": *
#import "@local/mathematical:0.1.0": *
#let convex-hull(points) = {
let hull = algorithms.convex-hull(points)
draw.canvas({
draw.set-style(
circle: (
fill: blue
)
)
draw.shapes.points(points, fill: blue)
draw.shapes.polygon(hull, stroke: red)
let hull-points = get-adjacently-paired-points(hull)
for (i, pair) in hull-points.enumerate() {
draw.brace(..pair, i + 1)
}
})
}
#let points = (
(0, 0), (1, 1), (2, 2), (3, 1), (4, 0),
(3, 3), (2, 4), (1, 3), (2, 1), (10, 10)
)
#convex-hull(points)
// draws a simple convex-hull
// the labels are just indexes
// there is no selection of which brace to draw ...
// all the braces are drawn
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/packages/m1.typ | typst | Apache License 2.0 |
一段内容
#let add(x, y) = x + y
另一段内容
#let sub = {
let sub(x, y) = x - y
sub
}
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2007/WS-11.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [3008],
[2], [GUO Yue], [CHN], [2976],
[3], [WANG Nan], [CHN], [2934],
[4], [GUO Yan], [CHN], [2841],
[5], [LI Xiaoxia], [CHN], [2826],
[6], [NIU Jianfeng], [CHN], [2626],
[7], [JIANG Huajun], [HKG], [2620],
[8], [KIM Kyungah], [KOR], [2564],
[9], [LI Jiawei], [SGP], [2560],
[10], [CHANG Chenchen], [CHN], [2530],
[11], [WANG Yuegu], [SGP], [2515],
[12], [LEE Eunhee], [KOR], [2509],
[13], [LI Jiao], [NED], [2506],
[14], [WU Jiaduo], [GER], [2504],
[15], [KANAZAWA Saki], [JPN], [2480],
[16], [SHEN Yanfei], [ESP], [2470],
[17], [LIN Ling], [HKG], [2468],
[18], [PENG Luyang], [CHN], [2458],
[19], [TIE Yana], [HKG], [2450],
[20], [FAN Ying], [CHN], [2444],
[21], [PARK Miyoung], [KOR], [2442],
[22], [FUKUHARA Ai], [JPN], [2440],
[23], [CAO Zhen], [CHN], [2439],
[24], [WANG Chen], [CHN], [2423],
[25], [LIU Jia], [AUT], [2420],
[26], [CHEN Qing], [CHN], [2409],
[27], [LIU Shiwen], [CHN], [2406],
[28], [GAO Jun], [USA], [2403],
[29], [ZHANG Rui], [HKG], [2388],
[30], [TOTH Krisztina], [HUN], [2364],
[31], [TAN Wenling], [ITA], [2353],
[32], [FENG Tianwei], [SGP], [2353],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [HIRANO Sayaka], [JPN], [2349],
[34], [LAU Sui Fei], [HKG], [2349],
[35], [FUKUOKA Haruna], [JPN], [2339],
[36], [SUN Beibei], [SGP], [2333],
[37], [FUJINUMA Ai], [JPN], [2332],
[38], [WU Xue], [DOM], [2328],
[39], [GANINA Svetlana], [RUS], [2323],
[40], [LOVAS Petra], [HUN], [2318],
[41], [SONG Ah Sim], [HKG], [2313],
[42], [DING Ning], [CHN], [2311],
[43], [<NAME>], [PRK], [2310],
[44], [<NAME>], [HUN], [2306],
[45], [PAVLO<NAME>], [BLR], [2298],
[46], [<NAME>], [ROU], [2297],
[47], [<NAME>], [POL], [2296],
[48], [#text(gray, "<NAME>")], [CHN], [2286],
[49], [<NAME>], [CRO], [2284],
[50], [<NAME>], [CHN], [2283],
[51], [<NAME>], [JPN], [2275],
[52], [<NAME>], [ROU], [2272],
[53], [PAVLOVICH Veronika], [BLR], [2271],
[54], [<NAME>], [AUS], [2271],
[55], [#text(gray, "<NAME>")], [ROU], [2259],
[56], [<NAME>], [GER], [2233],
[57], [<NAME>], [JPN], [2227],
[58], [UMEMUR<NAME>], [JPN], [2224],
[59], [<NAME>], [GER], [2224],
[60], [<NAME>], [KOR], [2221],
[61], [<NAME>], [GER], [2216],
[62], [ODOROVA Eva], [SVK], [2213],
[63], [<NAME>], [CRO], [2209],
[64], [<NAME>], [JPN], [2206],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [YU Mengyu], [SGP], [2205],
[66], [#text(gray, "XU Yan")], [SGP], [2198],
[67], [LI Xue], [FRA], [2198],
[68], [<NAME>], [GER], [2195],
[69], [LI Qiangbing], [AUT], [2193],
[70], [KWAK Bangbang], [KOR], [2184],
[71], [XIAN Yifang], [FRA], [2174],
[72], [VACENOVSKA Iveta], [CZE], [2162],
[73], [KOMWONG Nanthana], [THA], [2160],
[74], [STEFANOVA Nikoleta], [ITA], [2159],
[75], [#text(gray, "ZHANG Xueling")], [SGP], [2157],
[76], [STRBIKOVA Renata], [CZE], [2154],
[77], [BILENKO Tetyana], [UKR], [2153],
[78], [LU Yun-Feng], [TPE], [2149],
[79], [ZAMFIR Adriana], [ROU], [2148],
[80], [ERDELJI Anamaria], [SRB], [2143],
[81], [TAN Paey Fern], [SGP], [2141],
[82], [BOLLMEIER Nadine], [GER], [2135],
[83], [NEGRISOLI Laura], [ITA], [2133],
[84], [GRUNDISCH Carole], [FRA], [2125],
[85], [DVORAK Galia], [ESP], [2122],
[86], [KONISHI An], [JPN], [2116],
[87], [#text(gray, "JANG Hyon Ae")], [PRK], [2113],
[88], [ETSUZAKI Ayumi], [JPN], [2108],
[89], [XU Jie], [POL], [2102],
[90], [KIM Jong], [PRK], [2102],
[91], [KOTIKHINA Irina], [RUS], [2097],
[92], [ISHIGAKI Yuka], [JPN], [2094],
[93], [YU Kwok See], [HKG], [2087],
[94], [SCHOPP Jie], [GER], [2084],
[95], [TERUI Moemi], [JPN], [2084],
[96], [IVANCAN Irene], [GER], [2082],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [CHENG I-Ching], [TPE], [2081],
[98], [KOSTROMINA Tatyana], [BLR], [2081],
[99], [RAMIREZ Sara], [ESP], [2079],
[100], [MOON Hyunjung], [KOR], [2079],
[101], [LAY Jian Fang], [AUS], [2076],
[102], [MOLNAR Cornelia], [CRO], [2075],
[103], [SHIM Serom], [KOR], [2069],
[104], [ZHU Fang], [ESP], [2062],
[105], [MUANGSUK Anisara], [THA], [2061],
[106], [LANG Kristin], [GER], [2058],
[107], [PAN Chun-Chu], [TPE], [2058],
[108], [STRUSE Nicole], [GER], [2052],
[109], [DOLGIKH Maria], [RUS], [2052],
[110], [<NAME>], [GER], [2052],
[111], [PASKAUSKIENE Ruta], [LTU], [2044],
[112], [KIM Kyungha], [KOR], [2040],
[113], [#text(gray, "BADESCU Otilia")], [ROU], [2039],
[114], [HUANG Yi-Hua], [TPE], [2033],
[115], [YOON Sunae], [KOR], [2031],
[116], [ONO Shiho], [JPN], [2021],
[117], [KO Somi], [KOR], [2021],
[118], [TIMINA Elena], [NED], [2020],
[119], [GATINSKA Katalina], [BUL], [2017],
[120], [GHATAK Poulomi], [IND], [2017],
[121], [KIM Junghyun], [KOR], [2016],
[122], [LI Chunli], [NZL], [2015],
[123], [YAMANASHI Yuri], [JPN], [2012],
[124], [KRAVCHENKO Marina], [ISR], [2007],
[125], [<NAME>], [SWE], [2003],
[126], [#text(gray, "<NAME>")], [KOR], [2001],
[127], [#text(gray, "<NAME>")], [RUS], [1997],
[128], [<NAME>], [ROU], [1996],
)
) |
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/docs/schule-manual.typ | typst | MIT License | #import "@local/mantys:0.1.4": *
#import "@preview/tidy:0.3.0"
#import "../src/schule.typ"
#let TeX = style(styles => {
set text(font: "New Computer Modern")
let e = measure("E", styles)
let T = "T"
let E = text(1em, baseline: e.height * 0.31, "E")
let X = "X"
box(T + h(-0.15em) + E + h(-0.125em) + X)
})
#let LaTeX = style(styles => {
set text(font: "New Computer Modern")
let a-size = 0.66em
let l = measure("L", styles)
let a = measure(text(a-size, "A"), styles)
let L = "L"
let A = box(scale(x: 110%, text(a-size, baseline: a.height - l.height, "A")))
box(L + h(-a.width * 0.67) + A + h(-a.width * 0.25) + TeX)
})
#show: mantys.with(
..toml("../typst.toml"),
date: datetime.today(),
abstract: [
SCHULE ist eine Sammlung von Typst Vorlagen zur Gestaltung von Arbeitsmaterialien (Arbeitsblätter, Klausuren, Wochenpläne ...) für die Schule. Das Paket ist eine Adaption meines #mty.footlink("https://github.com/jneug/arbeitsblatt", [#LaTeX Pakets]) für Typst.
],
examples-scope: (
schule: schule,
),
)
#let show-module(name, scope: (:)) = tidy-module(
read("../src/" + name + ".typ"),
name: name,
include-examples-scope: true,
scope: scope,
)
#let exampleout(name, cap: none) = {
figure(
mty.frame(width: 50%, image("examples/" + name + ".svg", width: 100%)),
caption: if cap != none [#cap (#mty.rawc(theme.colors.secondary, "examples/" + name + ".pdf"))] else [#mty.rawc(
theme.colors.secondary,
"examples/" + name + ".pdf",
)],
kind: image,
)
}
#let examplefile(name, cap: none) = {
let code = read("examples/" + name + ".typ")
mty.codelst.sourcefile(code.replace("../src/schule.typ", "@local/schule:0.1.1"), lang: "typ")
exampleout(name, cap: cap)
}
= About
SCHULE ist ein Typst Paket, mit dem Arbeitsblätter, Klausuren und andere Materialien für den Informatikunterricht erstellt werden können.
Das Paket ist ein Port des #LaTeX Pakets #mty.gitlink("jneug/arbeitsblatt"), welches wiederum auf dem #mty.footlink("https://ctan.org/pkg/schule", "schule Paket") basierte.
Durch die Adaption für Typst wurden mit der Zeit Funktionalitäten ergänzt, entfernt und verändert, um das Paket an die modernere Typst-Umgebung und das wachsende Ökosystem von verfügbaren Paketen anzupassen.
= Verwendung der Vorlagen
== Installation
SCHULE ist derzeit nicht im Typst-Universum als öffentliche Vorlage verfügbar. Die Installation muss lokal erfolgen.
== Vorlagen
=== Arbeitsblatt
=== Klassenarbeit
=== Klausur
== Module
=== Aufgaben
=== Layout- und Text-Elemente
// #import "../src/api/content.typ": __all__
// #show-module("api/content", scope: __all__)
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/数学模型/论文/pkuthss-typst/template.typ | typst | #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"),
)
#let lengthceil(len, unit: 字号.小四) = calc.ceil(len / unit) * unit
#let partcounter = counter("part")
#let chaptercounter = counter("chapter")
#let appendixcounter = counter("appendix")
#let footnotecounter = counter(footnote)
#let rawcounter = counter(figure.where(kind: "code"))
#let imagecounter = counter(figure.where(kind: image))
#let tablecounter = counter(figure.where(kind: table))
#let equationcounter = counter(math.equation)
#let appendix() = {
appendixcounter.update(10)
chaptercounter.update(0)
counter(heading).update(0)
}
#let skippedstate = state("skipped", false)
#let chinesenumber(num, standalone: false) = if num < 11 {
("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十").at(num)
} else if num < 100 {
if calc.rem(num, 10) == 0 {
chinesenumber(calc.floor(num / 10)) + "十"
} else if num < 20 and standalone {
"十" + chinesenumber(calc.rem(num, 10))
} else {
chinesenumber(calc.floor(num / 10)) + "十" + chinesenumber(calc.rem(num, 10))
}
} else if num < 1000 {
let left = chinesenumber(calc.floor(num / 100)) + "百"
if calc.rem(num, 100) == 0 {
left
} else if calc.rem(num, 100) < 10 {
left + "零" + chinesenumber(calc.rem(num, 100))
} else {
left + chinesenumber(calc.rem(num, 100))
}
} else {
let left = chinesenumber(calc.floor(num / 1000)) + "千"
if calc.rem(num, 1000) == 0 {
left
} else if calc.rem(num, 1000) < 10 {
left + "零" + chinesenumber(calc.rem(num, 1000))
} else if calc.rem(num, 1000) < 100 {
left + "零" + chinesenumber(calc.rem(num, 1000))
} else {
left + chinesenumber(calc.rem(num, 1000))
}
}
#let chinesenumbering(..nums, location: none, brackets: false) = locate(loc => {
let actual_loc = if location == none { loc } else { location }
if appendixcounter.at(actual_loc).first() < 10 {
if nums.pos().len() == 1 {
"第" + chinesenumber(nums.pos().first(), standalone: true) + "章"
} else {
numbering(if brackets { "(1.1)" } else { "1.1" }, ..nums)
}
} else {
if nums.pos().len() == 1 {
"附录 " + numbering("A.1", ..nums)
} else {
numbering(if brackets { "(A.1)" } else { "A.1" }, ..nums)
}
}
})
#let chineseunderline(s, width: 300pt, bold: false) = {
let chars = s.clusters()
let n = chars.len()
style(styles => {
let i = 0
let now = ""
let ret = ()
while i < n {
let c = chars.at(i)
let nxt = now + c
if measure(nxt, styles).width > width or c == "\n" {
if bold {
ret.push(strong(now))
} else {
ret.push(now)
}
ret.push(v(-1em))
ret.push(line(length: 100%))
if c == "\n" {
now = ""
} else {
now = c
}
} else {
now = nxt
}
i = i + 1
}
if now.len() > 0 {
if bold {
ret.push(strong(now))
} else {
ret.push(now)
}
ret.push(v(-0.9em))
ret.push(line(length: 100%))
}
ret.join()
})
}
#let chineseoutline(title: "目录", depth: none, indent: false) = {
heading(title, numbering: none, outlined: false)
locate(it => {
let elements = query(heading.where(outlined: true).after(it), it)
for el in elements {
// Skip list of images and list of tables
if partcounter.at(el.location()).first() < 20 and el.numbering == none { continue }
// Skip headings that are too deep
if depth != none and el.level > depth { continue }
let maybe_number = if el.numbering != none {
if el.numbering == chinesenumbering {
chinesenumbering(..counter(heading).at(el.location()), location: el.location())
} else {
numbering(el.numbering, ..counter(heading).at(el.location()))
}
h(0.5em)
}
let line = {
if indent {
h(1em * (el.level - 1 ))
}
if el.level == 1 {
v(0.5em, weak: true)
}
if maybe_number != none {
style(styles => {
let width = measure(maybe_number, styles).width
box(
width: lengthceil(width),
link(el.location(), if el.level == 1 {
strong(maybe_number)
} else {
maybe_number
})
)
})
}
link(el.location(), if el.level == 1 {
strong(el.body)
} else {
el.body
})
// Filler dots
if el.level == 1 {
box(width: 1fr, h(10pt) + box(width: 1fr) + h(10pt))
} else {
box(width: 1fr, h(10pt) + box(width: 1fr, repeat[.]) + h(10pt))
}
// Page number
let footer = query(selector(<__footer__>).after(el.location()), el.location())
let page_number = if footer == () {
0
} else {
counter(page).at(footer.first().location()).first()
}
link(el.location(), if el.level == 1 {
strong(str(page_number))
} else {
str(page_number)
})
linebreak()
v(-0.2em)
}
line
}
})
}
#let listoffigures(title: "插图", kind: image) = {
heading(title, numbering: none, outlined: false)
locate(it => {
let elements = query(figure.where(kind: kind).after(it), it)
for el in elements {
let maybe_number = {
let el_loc = el.location()
chinesenumbering(chaptercounter.at(el_loc).first(), counter(figure.where(kind: kind)).at(el_loc).first(), location: el_loc)
h(0.5em)
}
let line = {
style(styles => {
let width = measure(maybe_number, styles).width
box(
width: lengthceil(width),
link(el.location(), maybe_number)
)
})
link(el.location(), el.caption.body)
// Filler dots
box(width: 1fr, h(10pt) + box(width: 1fr, repeat[.]) + h(10pt))
// Page number
let footers = query(selector(<__footer__>).after(el.location()), el.location())
let page_number = if footers == () {
0
} else {
counter(page).at(footers.first().location()).first()
}
link(el.location(), str(page_number))
linebreak()
v(-0.2em)
}
line
}
})
}
#let codeblock(raw, caption: none, outline: false) = {
figure(
if outline {
rect(width: 100%)[
#set align(left)
#raw
]
} else {
set align(left)
raw
},
caption: caption, kind: "code", supplement: ""
)
}
#let booktab(columns: (), aligns: (), width: auto, caption: none, ..cells) = {
let headers = cells.pos().slice(0, columns.len())
let contents = cells.pos().slice(columns.len(), cells.pos().len())
set align(center)
if aligns == () {
for i in range(0, columns.len()) {
aligns.push(center)
}
}
let content_aligns = ()
for i in range(0, contents.len()) {
content_aligns.push(aligns.at(calc.rem(i, aligns.len())))
}
return figure(
block(
width: width,
grid(
columns: (auto),
row-gutter: 1em,
line(length: 100%),
[
#set align(center)
#box(
width: 100% - 1em,
grid(
columns: columns,
..headers.zip(aligns).map(it => [
#set align(it.last())
#strong(it.first())
])
)
)
],
line(length: 100%),
[
#set align(center)
#box(
width: 100% - 1em,
grid(
columns: columns,
row-gutter: 1em,
..contents.zip(content_aligns).map(it => [
#set align(it.last())
#it.first()
])
)
)
],
line(length: 100%),
),
),
caption: caption,
kind: table
)
}
#let conf(
cauthor: "张三",
eauthor: "<NAME>",
studentid: "23000xxxxx",
blindid: "L2023XXXXX",
cthesisname: "博士研究生学位论文",
cheader: "北京大学博士学位论文",
ctitle: "北京大学学位论文 Typst 模板",
etitle: "Typst Template for Peking University Dissertations",
school: "某个学院",
cfirstmajor: "某个一级学科",
cmajor: "某个专业",
emajor: "Some Major",
direction: "某个研究方向",
csupervisor: "李四",
esupervisor: "<NAME>",
date: "二零二三年六月",
cabstract: [],
ckeywords: (),
eabstract: [],
ekeywords: (),
acknowledgements: [],
linespacing: 1em,
outlinedepth: 3,
blind: false,
listofimage: true,
listoftable: true,
listofcode: true,
alwaysstartodd: true,
doc,
) = {
let smartpagebreak = () => {
if alwaysstartodd {
skippedstate.update(true)
pagebreak(to: "odd", weak: true)
skippedstate.update(false)
} else {
pagebreak(weak: true)
}
}
set page("a4",
header: locate(loc => {
if skippedstate.at(loc) and calc.even(loc.page()) { return }
[
#set text(字号.五号)
#set align(center)
#if partcounter.at(loc).at(0) < 10 {
let headings = query(selector(heading).after(loc), loc)
let next_heading = if headings == () {
()
} else {
headings.first().body.text
}
// [HARDCODED] Handle the first page of Chinese abstract specailly
if next_heading == "摘要" and loc.page() == 2 {
[
#next_heading
#v(-1em)
#line(length: 100%)
]
}
} else if partcounter.at(loc).at(0) <= 20 {
if calc.even(loc.page()) {
[
#align(center, cheader)
#v(-1em)
#line(length: 100%)
]
} else {
let footers = query(selector(<__footer__>).after(loc), loc)
if footers != () {
let elems = query(
heading.where(level: 1).before(footers.first().location()), footers.first().location()
)
// [HARDCODED] Handle the last page of Chinese abstract specailly
let el = if elems.last().body.text == "摘要" or not skippedstate.at(footers.first().location()) {
elems.last()
} else {
elems.at(-2)
}
[
#let numbering = if el.numbering == chinesenumbering {
chinesenumbering(..counter(heading).at(el.location()), location: el.location())
} else if el.numbering != none {
numbering(el.numbering, ..counter(heading).at(el.location()))
}
#if numbering != none {
numbering
h(0.5em)
}
#el.body
#v(-1em)
#line(length: 100%)
]
}
}
}]}),
footer: locate(loc => {
if skippedstate.at(loc) and calc.even(loc.page()) { return }
[
#set text(字号.五号)
#set align(center)
#if query(selector(heading).before(loc), loc).len() < 2 or query(selector(heading).after(loc), loc).len() == 0 {
// Skip cover, copyright and origin pages
} else {
let headers = query(selector(heading).before(loc), loc)
let part = partcounter.at(headers.last().location()).first()
[
#if part < 20 {
numbering("I", counter(page).at(loc).first())
} else {
str(counter(page).at(loc).first())
}
]
}
#label("__footer__")
]
}),
)
set text(字号.一号, font: 字体.宋体, lang: "zh")
set align(center + horizon)
set heading(numbering: chinesenumbering)
set figure(
numbering: (..nums) => locate(loc => {
if appendixcounter.at(loc).first() < 10 {
numbering("1.1", chaptercounter.at(loc).first(), ..nums)
} else {
numbering("A.1", chaptercounter.at(loc).first(), ..nums)
}
})
)
set math.equation(
numbering: (..nums) => locate(loc => {
set text(font: 字体.宋体)
if appendixcounter.at(loc).first() < 10 {
numbering("(1.1)", chaptercounter.at(loc).first(), ..nums)
} else {
numbering("(A.1)", chaptercounter.at(loc).first(), ..nums)
}
})
)
set list(indent: 2em)
set enum(indent: 2em)
show strong: it => text(font: 字体.黑体, weight: "semibold", it.body)
show emph: it => text(font: 字体.黑体, weight: "semibold", it.body)
show par: set block(spacing: linespacing)
show raw: set text(font: 字体.代码)
show heading: it => [
// Cancel indentation for headings
#set par(first-line-indent: 0em)
#let sizedheading(it, size) = [
#set text(size)
#v(2em)
#if it.numbering != none {
strong(counter(heading).display())
h(0.5em)
}
#strong(it.body)
#v(1em)
]
#if it.level == 1 {
if not it.body.text in ("Abstract", "学位论文使用授权说明", "版权声明") {
smartpagebreak()
}
locate(loc => {
if it.body.text == "摘要" {
partcounter.update(10)
counter(page).update(1)
} else if it.numbering != none and partcounter.at(loc).first() < 20 {
partcounter.update(20)
counter(page).update(1)
}
})
if it.numbering != none {
chaptercounter.step()
}
footnotecounter.update(())
imagecounter.update(())
tablecounter.update(())
rawcounter.update(())
equationcounter.update(())
set align(center)
sizedheading(it, 字号.三号)
} else {
if it.level == 2 {
sizedheading(it, 字号.四号)
} else if it.level == 3 {
sizedheading(it, 字号.中四)
} else {
sizedheading(it, 字号.小四)
}
}
]
show figure: it => [
#set align(center)
#if not it.has("kind") {
it
} else if it.kind == image {
it.body
[
#set text(字号.五号)
#it.caption
]
} else if it.kind == table {
[
#set text(字号.五号)
#it.caption
]
it.body
} else if it.kind == "code" {
[
#set text(字号.五号)
代码#it.caption
]
it.body
}
]
show ref: it => {
if it.element == none {
// Keep citations as is
it
} else {
// Remove prefix spacing
h(0em, weak: true)
let el = it.element
let el_loc = el.location()
if el.func() == math.equation {
// Handle equations
link(el_loc, [
式
#chinesenumbering(chaptercounter.at(el_loc).first(), equationcounter.at(el_loc).first(), location: el_loc, brackets: true)
])
} else if el.func() == figure {
// Handle figures
if el.kind == image {
link(el_loc, [
图
#chinesenumbering(chaptercounter.at(el_loc).first(), imagecounter.at(el_loc).first(), location: el_loc)
])
} else if el.kind == table {
link(el_loc, [
表
#chinesenumbering(chaptercounter.at(el_loc).first(), tablecounter.at(el_loc).first(), location: el_loc)
])
} else if el.kind == "code" {
link(el_loc, [
代码
#chinesenumbering(chaptercounter.at(el_loc).first(), rawcounter.at(el_loc).first(), location: el_loc)
])
}
} else if el.func() == heading {
// Handle headings
if el.level == 1 {
link(el_loc, chinesenumbering(..counter(heading).at(el_loc), location: el_loc))
} else {
link(el_loc, [
节
#chinesenumbering(..counter(heading).at(el_loc), location: el_loc)
])
}
}
// Remove suffix spacing
h(0em, weak: true)
}
}
let fieldname(name) = [
#set align(right + top)
#strong(name)
]
let fieldvalue(value) = [
#set align(center + horizon)
#set text(font: 字体.仿宋)
#grid(
rows: (auto, auto),
row-gutter: 0.2em,
value,
line(length: 100%)
)
]
// Cover page
if blind {
set align(center + top)
text(字号.初号)[#strong(cheader)]
linebreak()
set text(字号.三号, font: 字体.仿宋)
set par(justify: true, leading: 1em)
[(匿名评阅论文封面)]
v(2fr)
grid(
columns: (80pt, 320pt),
row-gutter: 1.5em,
align(left + top)[中文题目:],
align(left + top)[#ctitle],
align(left + top)[英文题目:],
align(left + top)[#etitle],
)
v(2em)
grid(
columns: (80pt, 320pt),
row-gutter: 1.5em,
align(left + top)[一级学科:],
align(left + top)[#cfirstmajor],
align(left + top)[二级学科:],
align(left + top)[#cmajor],
align(left + top)[论文编号:],
align(left + top)[#blindid],
)
v(4fr)
text(字号.小二, font: 字体.仿宋)[#date]
v(1fr)
} else {
box(
grid(
columns: (auto, auto),
gutter: 0.4em,
image("pkulogo.svg", height: 2.4em, fit: "contain"),
image("pkuword.svg", height: 1.6em, fit: "contain")
)
)
linebreak()
strong(cthesisname)
set text(字号.二号)
v(60pt)
grid(
columns: (80pt, 300pt),
[
#set align(right + top)
题目:
],
[
#set align(center + horizon)
#chineseunderline(ctitle, width: 300pt, bold: true)
]
)
v(60pt)
set text(字号.三号)
grid(
columns: (80pt, 280pt),
row-gutter: 1em,
fieldname(text("姓") + h(2em) + text("名:")),
fieldvalue(cauthor),
fieldname(text("学") + h(2em) + text("号:")),
fieldvalue(studentid),
fieldname(text("学") + h(2em) + text("院:")),
fieldvalue(school),
// fieldname(text("专") + h(2em) + text("业:")),
// fieldvalue(cmajor),
// fieldname("研究方向:"),
// fieldvalue(direction),
// fieldname(text("导") + h(2em) + text("师:")),
// fieldvalue(csupervisor),
)
v(60pt)
text(字号.小二)[#date]
}
smartpagebreak()
// Copyright
set align(left + top)
set text(字号.小四)
// heading(numbering: none, outlined: false, "版权声明")
// par(justify: true, first-line-indent: 2em, leading: linespacing)[
// 任何收存和保管本论文各种版本的单位和个人,未经本论文作者同意,不得将本论文转借他人,亦不得随意复制、抄录、拍照或以任何方式传播。否则,引起有碍作者著作权之问题,将可能承担法律责任。
// ]
// smartpagebreak()
// Chinese abstract
par(justify: true, first-line-indent: 2em, leading: linespacing)[
#heading(numbering: none, outlined: false, "摘要")
#cabstract
#v(1fr)
#set par(first-line-indent: 0em)
*关键词:*
#ckeywords.join(",")
#v(2em)
]
// English abstract
// par(justify: true, first-line-indent: 2em, leading: linespacing)[
// #[
// #set text(字号.小二)
// #set align(center)
// #strong(etitle)
// ]
// #if not blind {
// [
// #set align(center)
// #eauthor \(#emajor\) \
// Directed by #esupervisor
// ]
// }
// #heading(numbering: none, outlined: false, "Abstract")
// #eabstract
// #v(1fr)
// #set par(first-line-indent: 0em)
// *KEYWORDS:*
// #h(0.5em, weak: true)
// #ekeywords.join(", ")
// #v(2em)
// ]
// Table of contents
chineseoutline(
title: "目录",
depth: outlinedepth,
indent: true,
)
if listofimage {
listoffigures()
}
if listoftable {
listoffigures(title: "表格", kind: table)
}
if listofcode {
listoffigures(title: "代码", kind: "code")
}
set align(left + top)
par(justify: true, first-line-indent: 2em, leading: linespacing)[
#doc
]
// if not blind {
// par(justify: true, first-line-indent: 2em, leading: linespacing)[
// #heading(numbering: none, "致谢")
// #acknowledgements
// ]
// partcounter.update(30)
// heading(numbering: none, "北京大学学位论文原创性声明和使用授权说明")
// align(center)[#heading(level: 2, numbering: none, outlined: false, "原创性声明")]
// par(justify: true, first-line-indent: 2em, leading: linespacing)[
// 本人郑重声明:
// 所呈交的学位论文,是本人在导师的指导下,独立进行研究工作所取得的成果。
// 除文中已经注明引用的内容外,
// 本论文不含任何其他个人或集体已经发表或撰写过的作品或成果。
// 对本文的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。
// 本声明的法律结果由本人承担。
// #v(1em)
// #align(right)[
// 论文作者签名
// #h(5em)
// 日期:
// #h(2em)
// 年
// #h(2em)
// 月
// #h(2em)
// 日
// ]
// #align(center)[#heading(level: 2, numbering: none, outlined: false, "学位论文使用授权说明")]
// #v(-0.33em, weak: true)
// #align(center)[#text(字号.五号)[(必须装订在提交学校图书馆的印刷本)]]
// #v(字号.小三)
// 本人完全了解北京大学关于收集、保存、使用学位论文的规定,即:
// - 按照学校要求提交学位论文的印刷本和电子版本;
// - 学校有权保存学位论文的印刷本和电子版,并提供目录检索与阅览服务,在校园网上提供服务;
// - 学校可以采用影印、缩印、数字化或其它复制手段保存论文;
// - 因某种特殊原因须要延迟发布学位论文电子版,授权学校 #box[#rect(width: 9pt, height: 9pt)] 一年 / #box[#rect(width: 9pt, height: 9pt)] 两年 / #box[#rect(width: 9pt, height: 9pt)] 三年以后,在校园网上全文发布。
// #align(center)[(保密论文在解密后遵守此规定)]
// #v(1em)
// #align(right)[
// 论文作者签名
// #h(5em)
// 导师签名
// #h(5em)
// 日期:
// #h(2em)
// 年
// #h(2em)
// 月
// #h(2em)
// 日
// ]
// ]
// }
}
|
|
https://github.com/Lucascf11/PRE | https://raw.githubusercontent.com/Lucascf11/PRE/main/Avaliacoes/AV5/main.typ | typst | #import "@preview/klaro-ifsc-sj:0.1.0": report
#set text(lang: "pt")
#show: doc => report(
title: "Avaliação 5 de Processos Estocásticos",
subtitle: "Vetores aleatórios gaussianos",
// Se apenas um autor colocar , no final para indicar que é um array
authors: ("<NAME>",),
date: "28 de Julho de 2024",
doc,
)
#set text(18pt)
= Enunciado
#set text(14pt)
#figure(
image("images/Enunciado.png", width: 100%),
caption: "Enunciado da Avaliação",
supplement: [Figura],
)<Enunciado>
#pagebreak()
#set text(18pt)
= Resolução
#set text(14pt)
== Coletando informações do enunciado
No enunciado é dado que temos um vetor aleatório gaussiano, isso quer dizer que as variáveis aleatórias contidas nesse vetor são *conjuntamente gaussianas* e isso implica que *todas as variáveis aleatórias contidas nesse vetor são gaussianas*.
\
Outra informação dada pelo enunciado é que a média do vetor aleatório gaussiano é nula, isso nos concede o seguinte vetor média:
$ E[arrow(X)] = mu_arrow(X) = vec(0,0,0) $
Podemos evocar a representação genérica da matriz covariância 3x3, que são as dimensões da matriz covariância concedida pelo enunciado:
$ mat("var"[X_1],"cov"[X_1,X_2],"cov"[X_1,X_3];"cov"[X_2,X_1],"var"[X_2],"cov"[X_2,X_3];"cov"[X_3,X_1],"cov"[X_3,X_2],"var"[X_3]) $
Analisando a matriz covariância dada pelo enunciado, também podemos encontrar a variância de $X_1$, $X_2$ e $X_3$:
$ "var"[X_1] = sigma^2_X_1 = 9
\ "var"[X_2] = sigma^2_X_2 = 4
\ "var"[X_3] = sigma^2_X_3 = 1 $
Tendo tudo isso de informação, e como base que uma variável aleatória gaussiana se distribui do seguinte modo: $X dash.wave N(mu,sigma^2)$, podemos analisar como as variáveis aleatórias $X_1$, $X_2$ e $X_3$ se distribuem de maneira gaussiana:
$ X_1 dash.wave N(0,9)
\ X_2 dash.wave N(0,4)
\ X_3 dash.wave N(0,1) $
Ainda analisando essa mesma matriz covariância, podemos obter o valor das covariâncias e analisar como esses valores irão impactar em termos de dependência e correlação entre as variáveis aleatórias do enunciado:
$ "cov"[X_1,X_2] = "cov"[X_2,X_1] = 2
\ "cov"[X_1,X_3] = "cov"[X_3,X_1] = 0
\ "cov"[X_2,X_3] = "cov"[X_3,X_2] = 0 $
As covariâncias acima nos entregam algumas informações importantes sobre as variáveis aleatórias gaussianas do enunciado:
+ $X_1$ e $X_2$ possuem correlação entre si, portanto uma depende da outra
+ $X_1$ e $X_3$ são descorrelacionadas entre si
+ $X_2$ e $X_3$ são descorrelacionadas entre si
Tratando-se de variáveis aleatórias conjuntamente gaussianas, descorrelação implica independência, logo, chegamos à conclusão que $X_1$ e $X_2$ independem de $X_3$.
\
Tendo esses dados coletados agora de início, podemos recorrer a isso quando estivermos resolvendo os exercícios solicitados no enunciado dessa avaliação.
#pagebreak()
== Determinar $Pr[2 <= X_1 <= 3]$
Aqui, precisamos encontrar a probabilidade de $X_1$ assumir um valor entre 2 e 3. Já sabemos, através da coleta de informações do enunciado que, $X_1$ se distribui de maneira gaussiana. Dada essa constatação, para encontrarmos a probabilidade de uma variável aleatória gaussiana se situar em um intervalo qualquer, podemos utilizar uma subtração de função $Phi$, que é expressa por:
$ Pr[a <= X <= b] = Phi((b - mu_X)/sigma_X) - Phi((a - mu_X)/sigma_X) $<Funcao_Phi>
Utilizando os dados do enunciado e aplicando na @Funcao_Phi definimos que:
$ Pr[2 <= X <= 3] = Phi((3 - 0)/sqrt(9)) - Phi((2 - 0)/sqrt(9))
\ Pr[2 <= X <= 3] = Phi(3/3) - Phi(2/3) = Phi(1) - Phi(2/3)
\ Pr[2 <= X <= 3] = 0.093837 = 9,3837% $
Através dos cálculos, chegamos à conclusão que a probabilidade de $X_1$ estar no intervalo entre 2 e 3 é de 9,3837%.
\
Para calcular o resultado, utilizamos o auxílio do software *Octave*.
#pagebreak();
== Determinar $Pr[2 <= X_1 <= 3 | X_2 = 2]$
Para determinarmos a probabilidade solicitada pelo enunciado, precisamos primeiramente fazer algumas análises. Já verificamos anteriormente que $X_1$ e $X_2$ são correlacionadas, haja visto que a covariância entre ambas é diferente de 0. Sendo assim, há uma dependência entre elas. Isso faz com que tenhamos que, primeiramente encontrar a PDF condicional de $X_1|X_2=3$, para somente depois, aplicarmos a @Funcao_Phi e encontrarmos a probabilidade em questão.
\
Para descobrirmos a PDF condicional mencionada anteriormente, teremos que realizar a seguinte operação:
$ f_(X_1)(x_1|X_2 = 2) = (f_(X_1,X_2)(x_1,2))/(f_(X_2)(2)) $<X1_dadoque_X2>
Para encontrarmos o numerador dessa fração, precisaremos aplicar a fórmula da gaussiana multidimensional:
$ f_(arrow(X))(arrow(x)) = (1)/sqrt((2pi)^n"det"C)exp(-1/2(arrow(x) - arrow(mu))^T C^(-1)(arrow(x) - arrow(mu))) $<gaussiana_multidimensional>
Para encontrarmos o denominador da fração descrita na @X1_dadoque_X2 utilizaremos a mesma fórmula. porém adaptada para n = 1:
$ F_X (x) = 1/sqrt(2pi sigma^2)exp(-(x - mu)^2/(2sigma^2)) $<variavel_aletoria_gaussiana>
Assim sendo, podemos começar o cálculo da probabilidade solicitada no enunciado. Iremos começar calculando o numerador da @X1_dadoque_X2. Para isso, iremos primeiramente descobrir alguns dados importantes para aplicarmos na @gaussiana_multidimensional:
$ n = 2 " " " " " " C = mat(9,2;2,4) " " " " " " arrow(x) = vec(X_1,X_2) " " " " " " X_2 = 2 " " " " " " arrow(mu) = vec(0,0)
\ "det"C = (9 times 4) - (2 times 2) = 36 - 4 = 32
\ C^(-1) = 1/32 mat(4,-2;-2,9) $
$ f_(X_1,X_2)(x,2) = 1/sqrt((2pi)^2 32)exp(-1/2mat(X_1,2) 1/32mat(4,-2;-2,9)mat(X_1;2))
\ f_(X_1,X_2)(x,2) = 1/sqrt((2pi)^2 32)exp(-1/2 times 1/32 mat([4X_1 - 4], [-2X_1 + 18])mat(X_1;2))
\ f_(X_1,X_2)(x,2) = 1/sqrt((2pi)^2 32)exp(-1/2 times 1/32 (4X_1^2 - 4X_1 - 4X_1 + 36 ))
\ f_(X_1,X_2)(x,2) = 1/sqrt((2pi)^2 32)exp(-1/2 times (4X_1^2 - 8X_1 + 36 )/32) $
Temos o numerador da @X1_dadoque_X2, agora calculamos o seu denominador utilizando a @variavel_aletoria_gaussiana:
$ X_2 dash.wave N(0,4)
\ f_(X_2)(2) = 1/sqrt(2pi (4))exp(-1/2 times (2-0)^2/4)
\ f_(X_2)(2) = 1/sqrt(2pi (4))exp(-1/2 times 4/4)
\ f_(X_2)(2) = 1/sqrt(2pi (4))exp(-1/2 times 1)
$
Temos toda a fração da @X1_dadoque_X2, finalmente podemos encontrar a probabilidade solicitada:
$ f_X_1(x_1|X_2 =2) = (1/sqrt((2pi)^cancel(2) 32)exp(-1/2 times (4X_1^2 - 8X_1 + 36 )/32)) / (1/sqrt(cancel(2pi) (4))exp(-1/2 times 1) )
\ f_X_1(x_1|X_2 =2) = 1/sqrt((2pi) 8)exp(-1/2 times (4X_1^2 - 8X_1 + 4)/32 )
\ f_X_1(x_1|X_2 =2) = 1/sqrt((2pi) 8)exp(-1/2 times (X_1^2 - 2X_1 + 1)/8 )
\ f_X_1(x_1|X_2 =2) = 1/sqrt((2pi) 8)exp(-1/2 times (X_1 - 1)^2/8 )
$
Com esse cálculo, nós descobrimos que:
$ X_1 | X_2 = 2 " " " " dash.wave " " " "N(1,8) $
Desse modo, nós podemos finalmente calcular $Pr[2 <= X_1 <= 3 | X_2 = 2]$, pois sai pela @Funcao_Phi:
$ Pr[2 <= X_1 <= 3 | X_2 = 2] = Phi((3 - 1)/sqrt(8)) - Phi((2 - 1)/sqrt(8))
\ Pr[2 <= X_1 <= 3 | X_2 = 2] = Phi((2sqrt(8))/8) - Phi((sqrt(8))/8)
\ Pr[2 <= X_1 <= 3 | X_2 = 2] = 0,1221
\ Pr[2 <= X_1 <= 3 | X_2 = 2] = 12,21%
$
Com isso, chegamos na conclusão que, a probabilidade para que $X_1$ esteja no intervalo entre 2 e 3, dado que $X_2 = 2$, é de 12,21%.
\
Novamente, utilizamos o software *Octave* para auxiliar no cálculo da função $Phi$
#pagebreak();
== Determinar $Pr[2 <= X_1 <= 3 | X_2 = 2 and X_3 = 3]$
Novamente, assim como fizemos na questão anterior, antes de determinar a probabilidade solicitada, nós precisamos fazer algumas análises. Já se sabe que $X_1$ depende de $X_2$. Porém, quando analisamos a matriz covariância do enunciado, nós verificamos que $X_1$ e $X_3$ são descorrelacionadas entre si, pois a covariância entre essas variáveis vale 0. Como são variáveis aleatórias conjuntamente gaussianas, a descorrelação entre elas implica independência entre ambas. Dada essa constatação, não importa o valor que $X_3$ assume, em nada irá interferir em $X_1$.
\
Sendo assim então:
$ Pr[2 <= X_1 <= 3 | X_2 = 2 and X_3 = 3] = Pr[2 <= X_1 <= 3 | X_2 = 2]
\ Pr[2 <= X_1 <= 3 | X_2 = 2] = 12,21% $
Como $X_3$ em nada altera $X_1$ independente do valor que ela assuma, nós chegamos na conclusão que a probabilidade de $X_1$ estar entre o intervalo de 2 e 3 dado que $X_2 = 2$ e $X_3 = 3$ é a mesma probabilidade já calculada no exercício anterior: 12,21%
#pagebreak()
== Determinar $Pr[X_1 - X_3 > 4]$
Para descobrirmos a probabilidade solicitada pelo enunciado, primeiramente vamos definir que $Y = X_1 - X_3$. Como $X_1$ e $X_3$ se distribuem de maneira gaussiana, $Y$ se distribui de maneira gaussiana também. Podemos assumir que $Y = arrow(Y)$. Nós vamos precisar descobrir como $Y$ se distribui realizando as operações abaixo:
$ mu_arrow(Y) = A arrow(mu)_(arrow(X)) + arrow(b) $<vetor_media_Y>
$ C_arrow(Y) = A C_arrow(X)A^T $<covariancia_de_Y>
Pelas equações, logo percebemos que teremos que realizar transformações lineares afins para descobrirmos a probabilidade solicitada pelo enunciado. A @vetor_media_Y nos concede o vetor média de $arrow(Y)$ e a @covariancia_de_Y nos permite encontrar a matriz covariância de $arrow(Y)$.
\
Após compreendermos isso, podemos extrair algumas informações para aplicarmos nas equações:
$ arrow(X) = vec(X_1,X_3) " " " " " " arrow(mu)_(arrow(X)) = vec(0,0) " " " " " " C_arrow(X) = mat(9,0;0,1) " " " " " " A = mat(1,-1) " " " " " " arrow(b) = vec(0) $
Com isso, podemos partir para os cálculos, começando pelo vetor média de $arrow(Y)$:
$ mu_arrow(Y) = mat(1,-1)vec(0,0) + vec(0) = (0) $
Em seguida, calculamos a matriz covariância de $arrow(Y)$:
$ C_arrow(Y) = mat(1,-1)mat(9,0;0,1)mat(1;-1)
\ C_arrow(Y) = (10)
$
Para o cálculo da matriz covariância de $arrow(Y)$, utilizamos o software *Octave*.
\
Com os cálculos anteriores, temos que:
$ Y dash.wave N(0,10) $
Após isso, fica fácil encontrarmos a probabilidade solicitada. Assumimos que a probabilidade de $X_1 - X_3 > 4$ sai pela probabilidade máxima subtraída da função $Phi$ aplicada para o valor 4:
$ Pr[X_1 - X_3 > 4] = 1 - Phi((4 - 0)/sqrt(10) )
\ Pr[X_1 - X_3 > 4] = 1 - Phi((4sqrt(10))/10)
\ Pr[X_1 - X_3 > 4] = 1 - 0,8970 = 0,1030
\ Pr[X_1 - X_3 > 4] = 10,30%
$
Logo, chegamos na conclusão que a probabilidade de $X_1 - X_3$ ser maior que 4 vale 10,30%
\
Novamente, utilizamos o *Octave* para calcular a função $Phi$
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/docs/src/developer_documentation/theme_contribution.md | markdown | The Unlicense | # Contributing a Theme
Before you get started, we ask that you read our [contributing guide](https://github.com/The-Notebookinator/notebookinator/blob/main/.github/CONTRIBUTING.md).
Upon cloning your fork of the Notebookinator, you can find all of the existing themes in the `themes/` folder.
Each theme in the `themes/` folder follows the same file structure detailed in the [previous](./custom_themes.md) guide. If you have a theme on hand, just copy it into the `themes/` folder. For example, the foo theme's entry point should now be at `themes/foo/foo.typ`
If you refer to the Notebookinator as a local package anywhere in your theme, make sure to replace those imports with references to the files directly.
For example, if a file imports `utils` like this:
```typ
#import "@local/notebookinator:1.0.1": utils
```
Replace it with this:
```typ
#import "/utils.typ"
```
If you don't currently have a theme written, follow the [previous](./custom_themes.md) guide from the beginning, but place the theme folder in the `themes/` folder.
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/计算机组成与设计/Instructions.typ | typst | ---
order: 2
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "计算机组成与设计",
lang: "zh",
)
#let tbl_white(white_row: 1 , content_size: 9pt,..args) = align(center, block[
#show table.cell: it => if it.y <= white_row - 1 {
set text(fill: white, stroke: white)
it
} else {
set text(size: content_size)
it
}
#tbl(..args)
])
#counter(heading).update(1)
= Instructions——Language of the Computer
#info(caption: "Contents of Chapter 2")[
2.1 Introduction \
2.2 Operations of the Computer Hardware \
2.3 Operands of the Computer Hardware \
2.4 Representing Instructions in the Computer \
2.5 Logical Operation \
2.6 Instructions for Making Decisions \
2.7 Supporting Procedures in Computer Hardware \
2.8 Communicating with People \
2.9 MIPS Addressing for 32 Bit Immediates and Addresses \
2.10 Translanting and starting a Program \
2.11 \*How Compilers Optimize \
2.12 \*How Compilers Work \
2.13 A C Sort Example to Put It All together \
2.14 \*Implementing an Object-Oriented Language \
2.15 Arrays Versus Pointers \
2.16 Real Stuff: IA-32 Instructions \
2.17 Fallacies and Pitfalls \
2.18 Concluding Remarks \
2.19 Historical Perspective and Further Reading
]
== Introduction
- Instruction characteristics
- 处理器的内存类型:
- stack, accumulator, general purpose register(register-memory, register-register: load / store)
- 指令中对 memory 的操作数
- 三种类型: register-register, register-memory, memory-memory
- Operations in the instruction Set
- Type and Size of Operands
- Representation in the Computer
- Encoding
- 变量区分
- 高级语言如 C 中有 int, char, float 等区分
- 但在硬件上,直接用存储硬件的方式来区分:register, memory address(Displacement + Immediate), stack
== Operations of the Computer Hardware
- #redt[Design Principle 1]: *Simplicity favors regularity*(简单源自规整,指令包含3个操作数)
- 这里以 add 和 sub 为例
== Operands of the Computer Hardware
- Register Operands
- 寄存器的位数:32 / 64
- #redt[Design Principle 2]: *Smaller is faster*(越少越快,寄存器个数一般不超过32个,因为寄存器地址一般是定长 encode,太多会增大 encode 消耗)
#let register_tbl = tbl_white(
content_size: 10pt,
columns: 4,
fill: (x,y) => if y == 0 {rgb(153, 153, 0)},
[Name],[Register name],[Usage],[Preserved on calls],
[x0],[0],[The constant value 0],[n.a.],
[x1(ra)],[1],[Return address(link register)],[yes],
[x2(sp)],[2],[Stack pointer],[yes],
[x3(gp)],[3],[Global pointer],[yes],
[x4(tp)],[4],[Thread pointer],[yes],
[x5-x7 & x28-x31],[5-7, 28-31],[Temporary registers],[no],
[x8-x9 & x18-x27],[8-9, 18-27],[Saved registers],[yes],
[x10-x17],[10-17],[Arguments / Results],[no],
)
#register_tbl
- RISC-V operands
#fig("/public/assets/Courses/计组/img-2024-03-18-08-35-48.png", width: 60%)
- Memory Operands
- 优势:可以存更多数据、可以存更复杂更灵活的数据结构
- 需要 load / store 跟 register 交互
- Memory is byte addressed: Each address identifies an 8-bit byte
- 大端与小端(相对主流),RISC-V is Little endian
#fig("/public/assets/Courses/计组/img-2024-03-18-08-39-19.png", width: 84%)
- Memory Alignment
#fig("/public/assets/Courses/计组/img-2024-03-18-08-53-14.png", width: 80%)
- 不过 RISC-V 没有对齐的要求
- Constant or Immediate Operand
- 对于常数或立即数,如果放在 memory 中,每次都要 load,效率低,为此定义了立即数指令,如 addi
$ "addi" "x22", "x22", 4 med med \/\/ "x22"= "x22" + 4 $
- #redt[Design Principle 3]:Make the common case fast
== Signed and Unsigned Numbers
- 略
== Representing Instructions in the Computer
- 从汇编指令到机器码(machine code)
#fig("/public/assets/Courses/计组/img-2024-03-18-09-18-59.png")
- 上面这种例子是 R-format
#fig("/public/assets/Courses/计组/img-2024-03-18-09-20-46.png", width: 60%)
- #redt[Design Principle 4]: Good design demands good compromises(好的设计需要折中)
- 对于立即数,可以看到 R-format 只有 5 位来表示,范围太小了,因此定义了 I-format,范围变为 $+- 2^11$
#fig("/public/assets/Courses/计组/img-2024-03-18-09-25-07.png", width: 60%)
- 对 store 操作有 S-format,把不需要的目标寄存器 rd 空出来给立即数,这里图片有错,应为$"imm"[11:5]$, #redt[$5"bits"$]
#fig("/public/assets/Courses/计组/img-2024-03-18-09-28-18.png", width: 70%)
- 归纳:
#fig("/public/assets/Courses/计组/img-2024-03-18-09-34-46.png")
- Stored-program
#wrap-content(fig("/public/assets/Courses/计组/img-2024-03-20-10-13-14.png", width: 48%))[
- 当今计算机的两个 key principle
- Instructions are represented as numbers
- Programs can be stored in memory like numbers
- Instruction 和 program 都以数字形式存储在 memory 中,program 可以对 program 进行操作(也因此带来一定危险性)
- 二进制的兼容性允许在不同计算机上运行同一段程序
]
== Logical Operations
- 略
== Instructions for Making Decisions
- Branch instructions, 判断寄存器值是否相等,跳转到 L1 标号的指令
1. (branch equal) beq register1, register2, L1
2. (branch not equal) bne register1, register2, L1
3. (branch less than) blt rs1, rs2, L1
4. (branch greater or equal) bge rs1, rs2, L1
```c
if (i == j) f = g + h; else f = g – h;
```
```assembly
bne x22, x23, ELSE // go to ELSE if i != j
add x19, x20, x21 // f = g + h ( skipped if i not equals j )
beq x0, x0, EXIT // no-condition jump
ELSE: sub x19, x20, x21 // f = g - h ( skipped if i equals j )
EXIT:
```
- 如果没有 blt 和 bge,可以用这样的方式曲线救国
- RISC-V 是有的,不过不一定有这种分拆的方式快
#fig("/public/assets/Courses/计组/img-2024-03-20-10-42-08.png", width: 59%)
- 界限检查的小 trick
- `If (x20>=x11 | x20 < 0) goto IndexOutofBounds`
- 用 `bgeu x20, x11, IndexOutofBounds`,当做无符号数处理(当 x11 为正数)
- case, switch: jump address table(use `jalr`)
```c
switch (k) {
case 0 : f = i + j ; break ; /* k = 0 */
case 1 : f = g + h ; break ; /* k = 1 */
case 2 : f = g - h ; break ; /* k = 2 */
case 3 : f = i - j ; break ; /* k = 3 */
}
```
#fig("/public/assets/Courses/计组/img-2024-03-20-11-13-01.png", width:60%)
== Supporting Procedures in Computer Hardware
- Procedure/function --- be used to structure programs
- Six steps
1. Place Parameters where the procedure can access them(in registers x10 \~ x17)
2. Transfer control to the procedure
3. Acquire the storage resources needed for the procedure
4. Perform the desired task
5. Place the result value in a place where the calling program can access it
6. Return control to the point of origin(address in x1)
- Procedure call(*调用*): jump and link(jal)
- ```assembly jal x1, ProcedureLabel``` 跳转到某一标号,并将当前地址存入 x1
- Procedure return(*返回*): jump and link register(jalr)
- ```assembly jalr x0, 0(x1)``` 跳转到 x1 中存储的地址,并将当前地址存入 x0(弃用)
- Stack(栈):Ideal data structure for spilling registers
- stack pointer(sp): x2
- Push: sp= sp-8; Pop: sp = sp+8(因为栈是从上往下存)
- Register Usage
- x5 – x7, x28 – x31: temporary registers
- Not preserved by the callee,子程序想用这些寄存器可以直接覆盖
- x8 – x9, x18 – x27: saved registers
- If used, the callee saves and restores them,子程序需要先压栈再使用,用完恢复
- Leaf Procedures & Non-Leaf Procedures: 叶子程序不会调用其它程序
- 对 Non-Leaf Procedures,如递归函数,return address, Any arguments and temporaries needed *after the call* 需要被压栈保存,在子程序结束后恢复(函数调用栈)
- 一个误区,之前以为 temporaries 完全不用保护,实际上指的是子函数可以直接覆盖,父函数还是要保护一下它们的。设想调用子程序后还有操作(非尾递归),此时恢复 temporary 就很有必要
```c
long long fact (long long n) {
if (n < 1) return 1;
else return (n * fact(n - 1));
}
```
```assembly
fact: addi sp, sp, -16 // adjust stack for 2 items
sd x1, 8(sp) // save the return address
sd x10, 0(sp) // save the argument n
addi x5, x10, -1 // x5 = n - 1
bge x5, x0, L1 // if n >= 1, go to L1(else)
addi x10, x0, 1 // return 1 if n <1
addi sp, sp, 16 // Recover sp (Why not recover x1 and x10?)
jalr x0, 0(x1) // return to caller
L1: addi x10, x10, -1 // n >= 1: argument gets (n - 1)
jal x1, fact // call fact with (n - 1)
add x6, x10, x0 // copy the return value(这里就是为什么返回值和参数能一起存)
ld x10, 0(sp) // restore argument n
ld x1, 8(sp) // restore the return address
addi sp, sp, 16 // adjust stack pointer to pop 2 items
mul x10, x10, x6 // return n*fact (n - 1)
jalr x0, 0(x1) // return to the caller
```
- 小测的例子,更清晰(x10 为参数,x11 为返回值):
```C
int sum(int n) {
if (n == 0) return 0;
else return n + sum(n - 1);
}
```
```assembly
addi x11, x0, 0 // 初始化
sum: addi sp, sp, -8 // 保存之前的参数和返回值
sw x1, 4(sp)
sw x10, 0(sp)
beq x10, x0, Return // 如果 n = 0,直接返回,否则还要调用 sum(n-1)
addi x10, x10, -1
jal x1, sum
lw x10, 0(sp)
lw x1, 4(sp)
add x11, x11, x10
Return: add sp, sp, 8
jalr x0, 0(x1)
```
- Storage class of C variables: automatic(动态变量), static(静态变量)
- Procedure frame and frame pointer (x8 or fp)
- The importance of fp,帧指针(frame pointer)跟 sp 指向同一块地方,不同之处在于 fp 相对固定,一般以 fp 作为基地址查找动态变量
- automatic
- Global pointer (x3 or gp)
- static
- 内存布局
#fig("/public/assets/Courses/计组/img-2024-03-20-12-08-58.png")
== Communicating with People
- Byte-encoded character sets
- ASCII, Latin-1
- Unicode: 16-bit/32-bit character set
- Byte / Halfword / Word Operations
- lb, lh, lw, sb, sh, sw: 8-bit, 16-bit, 32-bit
- String 表示
- 三种方法
1. 在第一位存放长度(如 Java)
2. 变量伴随长度
3. 用特殊字符结尾(如 C)
== RISC-V Addressing for Wide Immediate and Addresses
- 大多数情况下,12-bit 的立即数是够用的,但也存在例外
- lui (load upper immediate)指令 (belong to U-format)
- lui: ```assembly lui rd, constant```,将 constant 的高 20 位放到 rd 中
- 剩下的低 12 位用 addi 补充(注意符号,可能要用 addiu 或 or)
#fig("/public/assets/Courses/计组/img-2024-03-27-10-24-35.png", width: 80%)
- Branch Addressing(分支指令跳转)
- SB-Format(B-format)
- 在相对当前指令 $+-2^12$ bits 的范围内跳转
#fig("/public/assets/Courses/计组/img-2024-03-27-10-33-24.png", width: 80%)
- branch 跳转在循环中常用,因为循环体一般不会写太大。而函数调用这种需要更大的跳转范围:
- Jump Addressing(无条件跳转)
- UJ-Format(J-format)
- 20-bit immediate, 12-bit offset
- 在相对当前指令 $+-2^20$ bits 的范围内跳转
- 如果 beq(B-format)不够,化为 bne+jal;如果还不够,用 lui+ jalr
#fig("/public/assets/Courses/计组/img-2024-03-27-10-38-41.png", width: 80%)
- 例子:```C while (save[i]==k) i=i+1;``` in c
```assembly
Loop: slli x10, x22, 3 // temp reg x10 = 8 * i
add x10, x10, x25 // x10 = address of save[i]
ld x9, 0(x10) // temp reg x9 = save[i]
bne x9, x24, Exit // go to Exit if save[i] != k
addi x22, x22, 1 // i = i + 1
beq x0, x0, Loop // go to Loop
Exit:
```
#fig("/public/assets/Courses/计组/img-2024-03-27-11-00-51.png", width: 80%)
- 反汇编,先看后 7 位确定 opcode,再 $dots$
== Parallelism and Instructions: Synchronization
- 考虑多进程之间的竞争,solutions:
- synchronization: mutual exclusion、semaphore ...
- atomic exchange or atomic swap (instructions in RISC-V: lr.d and sc.d)
- Load reserved: `lr.d rd,(rs1)`, Load from address in rs1 to rd
- Store conditional: `sc.d rd,(rs1),rs2`, Store from rs2 to address in rs1
- 当 `rs1` 自从 lr.d 之后没有被改变过时,视为成功
- 检查 rd 是 1 还是 0,来确定是否成功(成功返回0)
- 例子:atomic swap (to test/set lock variable) & lock
```assembly
// atomic swap
again: lr.d x10,(x20)
sc.d x11,(x20),x23 // X11 = status
bne x11,x0,again // branch if store failed
addi x23,x10,0 // X23 = loaded value
// lock
addi x12,x0,1 // copy locked value
again: lr.d x10,(x20) // read lock
bne x10,x0,again // check if it is 0 yet
sc.d x11,(x20),x12 // attempt to store
bne x11,x0,again // branch if fails
// unlock
sd x0,0(x20) // free lock
```
== Translating and Starting a Program
#fig("/public/assets/Courses/计组/img-2024-03-27-11-30-00.png")
- Compiling & Assembling
- Obeject File & Linking Object Modules(静态)
- Loading a Program 的步骤
- Dynamic Linking
- Lazy Linkage
- Java Applications(解释型语言,跟 C 的方式不太一样)
== A C Sort Example To Put it All Together
- 直接看 PPT
== Arrays versus Pointers
- array 对 index 操作,然后乘8加到地址上,而 pointer 直接对地址操作
- 例子(注意这里其实得在循环开始前做个判断,否则数组的第一个元素一定会被赋值)
#tbl(
columns: (.9fr, 1fr),
[```C
clear1(int array[], int size) {
int i;
for (i = 0; i < size; i += 1)
array[i] = 0;
}
```],
[
```c
clear2(int *array, int size) {
int *p;
for (p = &array[0]; p < &array[size];
p = p + 1)
*p = 0;
}
```],
[```assembly
li x5,0 // i = 0
loop1:
slli x6,x5,3 // x6 = i * 8
add x7,x10,x6 // x7 = address
// of array[i]
sd x0,0(x7) // array[i] = 0
addi x5,x5,1 // i = i + 1
blt x5,x11,loop1 // if (i<size)
// go to loop1
```],
[```assembly
mv x5,x10 // p = address of array[0]
slli x6,x11,3 // x6 = size * 8
add x7,x10,x6 // x7 = address
// of array[size]
loop2:
sd x0,0(x5) // Memory[p] = 0
addi x5,x5,8 // p = p + 8
bltu x5,x7,loop2 // if (p<&array[size])
// go to loop2
```]
)
- 比较
- Array version requires shift to be inside loop,所以用指针会更好
- 但实际上编译器会自动优化,所以程序员只需关注代码的可读性和安全性
== Real Stuff: MIPS Instructions
- MIPS: commercial predecessor to RISC-V
#fig("/public/assets/Courses/计组/img-2024-04-01-08-20-00.png", width: 89%)
- 大致相同的基本指令集,但 conditional branches 不同
- For <, <=, >, >=
- RISC-V: blt, bge, bltu, bgeu
- MIPS: slt, sltu (set less than, result is 0 or 1)
- Then use beq, bne to complete the branch
- Instruction Encoding(指令的写法类似,但编码不一样)
== Real Stuff: The Intel x86 ISA
- Evolution with backward compatibility
- Two operands per instruction
- 每条指令都是两个操作数,不区分目标和源,并且支持很多(复杂指令集)
- 指令长度也是可变的
#tbl(
columns:2,
[Source/dest operand],[Second source operand],
[Register],[Register],
[Register],[Immediate],
[Register],[Memory],
[Memory],[Register],
[Memory],[Immediate]
)
- Memory addressing modes
- $"Address"$ in $"register"$
- $"Address" = "R"_"base" + "displacement"$
- $"Address" = "R"_"base" + 2^"scale" times "R"_"index" ("scale" = 0, 1, 2, "or" 3)$
- $"Address" = "R"_"base" + 2^"scale" times "R"_"index" + "displacement"$
- 把复杂指令 translate to 微操作(microoperations)
== Other RISC-V Instructions
- 回到 RISC-V
- Base integer instructions (RV64I)
- ```assembly auipc rd, immed // rd = (imm << 12) + pc```
- slt, sltu, slti, sltui: set less than
- addw, subw, addiw: 对低32位操作
- 32-bit variant: RV32I: registers are 32-bits wide, 32-bit operations
- Instruction Set Extensions
- M: integer multiply, divide, remainder
- A: atomic memory operations
- F: single-precision floating point
- D: double-precision floating point
- C: compressed instructions
== Fallacies and Pitfalls
- Fallacies
- Powerful instruction $=>$ higher performance
- assembly code $=>$ higher performance
- Pitfalls
- Sequential words are not at sequential addresses(4! not 1)
- Keeping a pointer to an automatic variable after procedure returns
== Summary
- Two principles of stored-program computers
- Use instructions as numbers
- Use alterable memory for programs
- Four design principles
- Simplicity favors regularity
- Smaller is faster
- Good design demands good compromises
- Make the common case fast
- 寄存器归纳
#register_tbl
- 指令格式归纳
#tbl_white(
white_row: 2,
columns: 8,
fill: (x,y) => if y == 0 or y == 1 {rgb(0, 174, 239)},
[name], table.cell(colspan: 6)[Field], [Comments],
[(Field Size)],[7bits],[5bits],[5bits],[3bits],[5bits],[7bits],[],
[R-type],[funct7],[rs2],[rs1],[funct3],[rd],[opcode],[Arithmetic instruction format],
[I-type], table.cell(colspan: 2)[imm[11:0]],[rs1],[funct3],[rd],[opcode],[Loads & Immediate arithmetic],
[S-type],[imm[11:5]],[rs2],[rs1],[funct3],[imm[4:0]],[opcode],[Stores],
[SB-type],[imm[12,10:5]],[rs2],[rs1],[funct3],[imm[4:1,11]],[opcode],[Conditional branch format],
[UJ-type],table.cell(colspan: 4)[imm[20,10:1,11,19:12]],[rd],[opcode],[Unconditional jump format],
[U-type],table.cell(colspan: 4)[imm[31:12]],[rd],[opcode],[Upper immediate format]
)
- 指令集编码归纳
#tbl_white(
columns: 6,
fill: (x,y) => if y == 0 {rgb(153, 204, 0)} else if x == 0 {rgb(222, 235, 203)},
[Format],[Instruction],[Opcode],[Funct3],[Funct6/7],[Description],
table.cell(rowspan: 10)[R-type],[add],[0110011],[000],[0000000],[addition],
[sub],[0110011],[000],[0100000],[subtraction],
[sll],[0110011],[001],[0000000],[shift left logical],
[xor],[0110011],[100],[0000000],[xor],
[srl],[0110011],[101],[0000000],[shift right logical],
[sra],[0110011],[101],[0100000],[shift right arithmetic],
[or],[0110011],[110],[0000000],[or],
[and],[0110011],[111],[0000000],[and],
[lr.d],[0110011],[011],[0001000],[load reserved],
[sc.d],[0110011],[011],[0001100],[store conditional],
table.cell(rowspan: 17)[I-type],[lb],[0000011],[000],[n.a.],[load byte],
[lh],[0000011],[001],[n.a.],[load halfword],
[lw],[0000011],[010],[n.a.],[load word],
[ld],[0000011],[011],[n.a.],[load doubleword],
[lbu],[0000011],[100],[n.a.],[load byte unsigned],
[lhu],[0000011],[101],[n.a.],[load halfword unsigned],
[lwu],[0000011],[110],[n.a.],[load word unsigned],
[addi],[0010011],[000],[n.a.],[add immediate],
[slli],[0010011],[001],[000000],[shift left logical immediate],
[slti],[0010011],[010],[n.a.],[set less than immediate],
[sltiu],[0010011],[011],[n.a.],[set less than immediate unsigned],
[xori],[0010011],[100],[n.a.],[xor immediate],
[srli],[0010011],[101],[000000],[shift right logical immediate],
[srai],[0010011],[101],[010000],[shift right arithmetic immediate],
[ori],[0010011],[110],[n.a.],[or immediate],
[andi],[0010011],[111],[n.a.],[and immediate],
[jalr],[1100111],[000],[n.a.],[jump and link register],
table.cell(rowspan: 4)[S-type],[sb],[0100011],[000],[n.a.],[store byte],
[sh],[0100011],[001],[n.a.],[store halfword],
[sw],[0100011],[010],[n.a.],[store word],
[sd],[0100011],[011],[n.a.],[store doubleword],
table.cell(rowspan: 6)[SB-type],[beq],[1100011],[000],[n.a.],[branch equal],
[bne],[1100011],[001],[n.a.],[branch not equal],
[blt],[1100011],[100],[n.a.],[branch less than],
[bge],[1100011],[101],[n.a.],[branch greater or equal],
[bltu],[1100011],[110],[n.a.],[branch less than unsigned],
[bgeu],[1100011],[111],[n.a.],[branch greater or equal unsigned],
table.cell(rowspan: 2)[U-type],[lui],[0110111],[n.a.],[n.a.],[load upper immediate],
[auipc],[0010111],[n.a.],[n.a.],[Add Upper Imm to PC],
[UJ-type],[jal],[1101111],[n.a.],[n.a.],[jump and link],
)
- 指令集归纳
#tbl_white(
content_size: 8pt,
columns: 5,
fill: (x,y) => if y == 0 {rgb(0, 173, 238)},
[Category],[Instruction],[Example],[Meaning],[Comments],
table.cell(rowspan: 3)[Arithmetic],[add],[```assembly add x5,x6,x7```],[x5=x6 + x7],[Add two source register operands],
[subtract],[```assembly sub x5,x6,x7```],[x5=x6 - x7],[First source register subtracts second one],
[add immediate],[```assembly addi x5,x6,20```],[x5=x6+20],[Used to add constants],
table.cell(rowspan: 15)[Data transfer],[load doubleword],[```assembly ld x5, 40(x6)```],[x5=Memory[x6+40]],[doubleword from memory to register],
[store doubleword],[```assembly sd x5, 40(x6)```],[Memory[x6+40]=x5],[doubleword from register to memory],
[load word],[```assembly lw x5, 40(x6)```],[x5=Memory[x6+40]],[word from memory to register],
[load word, unsigned],[```assembly lwu x5, 40(x6)```],[x5=Memory[x6+40]],[Unsigned word from memory to register],
[store word],[```assembly sw x5, 40(x6)```],[Memory[x6+40]=x5],[word from register to memory],
[load halfword],[```assembly lh x5, 40(x6)```],[x5=Memory[x6+40]],[Halfword from memory to register],
[load halfword, unsigned],[```assembly lhu x5, 40(x6)```],[x5=Memory[x6+40]],[Unsigned halfword from memory to register],
[store halfword],[```assembly sh x5, 40(x6)```],[Memory[x6+40]=x5],[halfword from register to memory],
[load byte],[```assembly lb x5, 40(x6)```],[x5=Memory[x6+40]],[byte from memory to register],
[load bite, unsigned],[```assembly lbu x5, 40(x6)```],[x5=Memory[x6+40]],[Unsigned byte from memory to register],
[store byte],[```assembly sb x5, 40(x6)```],[Memory[x6+40]=x5],[byte from register to memory],
[load reserved],[```assembly lr.d x5,(x6)```],[x5=Memory[x6]],[Load;1st half of atomic swap],
[store conditional],[```assembly sc.d x7,x5,(x6)```],[Memory[x6]=x5; x7 = 0/1],[Store;2nd half of atomic swap],
[load upper immediate],[```assembly lui x5,0x12345```],[x5=0x12345000],[Loads 20-bits constant shifted left 12 bits],
[auipc],[```assembly auipc x5,0x12345```],[x5=0x12345000+PC],[Loads 20-bits constant shifted left 12 bits plus PC],
table.cell(rowspan: 6)[Logical],[and],[```assembly and x5, x6, x7```],[x5=x6 & x7],[Arithmetic shift right by register],
[inclusive or],[```assembly or x5,x6,x7```],[x5=x6 | x7],[Bit-by-bit OR],
[exclusive or],[```assembly xor x5,x6,x7```],[x5=x6 ^ x7],[Bit-by-bit XOR],
[and immediate],[```assembly andi x5,x6,20```],[x5=x6 & 20],[Bit-by-bit AND reg. with constant],
[inclusive or immediate],[```assembly ori x5,x6,20```],[x5=x6 | 20],[Bit-by-bit OR reg. with constant],
[exclusive or immediate],[```assembly xori x5,x6,20```],[X5=x6 ^ 20],[Bit-by-bit XOR reg. with constant],
table.cell(rowspan: 6)[Shift],[shift left logical],[```assembly sll x5, x6, x7```],[x5=x6 << x7],[Shift left by register],
[shift right logical],[```assembly srl x5, x6, x7```],[x5=x6 >> x7],[Shift right by register],
[shift right arithmetic],[```assembly sra x5, x6, x7```],[x5=x6 >> x7],[Arithmetic shift right by register],
[shift left logical immediate],[```assembly slli x5, x6, 3```],[x5=x6 << 3],[Shift left by immediate],
[shift right logical immediate],[```assembly srli x5,x6,3```],[x5=x6 >> 3],[Shift right by immediate],
[shift right arithmetic immediate],[```assembly srai x5,x6,3```],[x5=x6 >> 3],[Arithmetic shift right by immediate],
table.cell(rowspan: 6)[Conditional branch],[branch if equal],[```assembly beq x5, x6, 100```],[if(x5 == x6) go to PC+100],[PC-relative branch if registers equal],
[branch if not equal],[```assembly bne x5, x6, 100```],[if(x5 != x6) go to PC+100],[PC-relative branch if registers not equal],
[branch if less than],[```assembly blt x5, x6, 100```],[if(x5 < x6) go to PC+100],[PC-relative branch if registers less],
[branch if greater or equal],[```assembly bge x5, x6, 100```],[if(x5 >= x6) go to PC+100],[PC-relative branch if registers greater or equal],
[branch if less, unsigned],[```assembly bltu x5, x6, 100```],[if(x5 >= x6) go to PC+100],[PC-relative branch if registers less, unsigned],
[branch if greater or equal, unsigned],[```assembly bgeu x5, x6, 100```],[if(x5 >= x6) go to PC+100],[PC-relative branch if registers greater or equal, unsigned],
table.cell(rowspan: 2)[Unconditional branch],[jump and link],[```assembly jal x1, 100```],[x1 = PC + 4; go to PC+100],[PC-relative procedure call],
[jump and link register],[```assembly jalr x1, 100(x5)```],[x1 = PC + 4; go to x5+100],[procedure return; indirect call],
)
|
|
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/README.md | markdown | MIT License | # Typst: Templates
*A curated list of paper templates in the area of machine learning.*
## Overview
Some conferences and journals in machine learning allow submissions in PDF
without special requirement to use LaTeX. They also provides a template and an
example paper in LaTeX. With official author instructions, these materials
enable us to make our own template in Typst mark up language. We start with
template for ICML and are going to add templates for other [Core A\*][1]
conferences and journals during next calendar years. The fields of research is
below.
- Artificial intelligence (4602).
- Computer vision and multimedia computation (4603).
- Data management and data science (4605).
- Machine learning (4611).
The list of A* conferences of the fields given follows.
- ACM International Conference on Computer Graphics and Interactive Techniques
(SIGGRAPH).
- ACM International Conference on Knowledge Discovery and Data Mining (KDD).
- ACM International World Wide Web Conference (WWW).
- Association for Computational Linguistics (ACL).
- Association for the Advancement of Artificial Intelligence (AAAI).
- Conference on Learning Theory (COLT).
- Empirical Methods in Natural Language Processing (EMNLP).
- European Conference on Computer Vision (ECCV).
- [IEEE Conference on Computer Vision and Pattern Recognition (CVPR)](cvpr).
- IEEE International Conference on Computer Vision (ICCV).
- International Conference on Automated Planning and Scheduling (ICAPS).
- [International Conference on Learning Representations (ICLR)](iclr).
- International Joint Conference on Artificial Intelligence (IJCAI).
- International World Wide Web Conference (WWW).
- [International Conference on Machine Learning (ICML)](icml).
- International Conference on the Principles of Knowledge Representation and
Reasoning (KR).
- International Joint Conference on Artificial Intelligence (IJCAI).
- International Joint Conference on Autonomous Agents and Multiagent Systems
(AAMAS).
- [Neural Information Processing System (NeurIPS)](neurips).
Additionally, we are going to provide templates for popular machine learning
scientific journals as well.
- [Journal of Machine Learning Research (JMLR)](jmlr).
- [Transactions on Machine Learning Research (TMLR)](tmlr).
## Usage
You can use this template in the [Typst][2] WebApp by clicking _Start from
template_ on the dashboard and searching for a template (e.g. `lucky-icml`).
Alternatively, you can use the CLI to kick this project off using the command
```shell
typst init @preview/lucky-icml
```
## Utilities
Typst of version 0.10.0 does not produce colored annotations. In order to
mitigate the issue, we add [a simple script](colorize-annotations.py) to the
repository. The script is plain and simple. One can use it as follows.
```shell
./colorize-annotations.py \
neurips/example-paper.typst.pdf neurips/example-paper-colored.typst.pdf
```
It is written with PyMuPDF library and inserts colored annotation.
[1]: https://portal.core.edu.au/conf-ranks/?search=A*&by=rank&source=CORE2023&sort=aacronym
[2]: https://typst.app/
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/feature/preview.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book-page.with(title: "Tinymist Preview Feature")
Two ways of previewing a Typst document are provided:
- PDF Preview: let lsp export your PDF on typed, and open related PDF by your favorite PDF viewer.
- Web (SVG) Preview: use builtin preview feature.
Whenever you can get a web preview feature, it is recomended since it is much faster than PDF preview and provides bidirectional navigation feature, allowing jumping between the source code and the preview by clicking or lsp commands.
== PDF Preview
For non-vscode clients, neovim client as an example. One who uses `nvim-lspconfig` can place their configuration in the `servers.tinymist.settings` section. If you want to export PDF on typing and output files in `$root_dir/target` directory, please configure it like that:
```lua
return {
-- add tinymist to lspconfig
{
"neovim/nvim-lspconfig",
opts = {
servers = {
tinymist = {
settings = {
exportPdf = "onType",
outputPath = "$root/target/$dir/$name",
}
},
},
},
},
}
```
#pro-tip[
=== VSCode:
The corresponding configuration should be placed in the `settings.json` file. For example:
```json
{
"tinymist.exportPdf": "onType",
"tinymist.outputPath": "$root/target/$dir/$name"
}
```
]
Also see:
- #link("https://github.com/Myriad-Dreamin/tinymist/blob/main/editors/vscode/Configuration.md")[VS Cod(e,ium): Tinymist Server Configuration]
- #link("https://github.com/Myriad-Dreamin/tinymist/blob/main/editors/neovim/Configuration.md")[Neovim: Tinymist Server Configuration]
== Builtin Preview Feature
See #link("https://enter-tainer.github.io/typst-preview/arch.html")[Typst-Preview Developer Guide].
=== CLI Integration
```bash
typst-preview /abs-path/to/main.typ --partial-rendering
```
is equivalent to
```bash
tinymist preview /abs-path/to/main.typ --partial-rendering
```
=== Editor Integration
#pro-tip[
=== VSCode:
The preview feature is also integrated into the LSP server. You can use the preview feature like when you were using it in `mgt19937.typst-preview` extension.
]
#pro-tip[
=== Neovim:
You may seek #link("https://github.com/chomosuke/typst-preview.nvim")[typst-preview.nvim] for the preview feature.
]
#pro-tip[
=== Emacs:
You may seek #link("https://github.com/havarddj/typst-preview.el")[typst-preview.el] for the preview feature.
]
=== `sys.inputs`
If the document is compiled by lsp, you can use `sys.inputs` to get the preview arguments:
```typ
#let preview-args = json.decode(sys.inputs.at("x-preview", default: "{}"))
```
There is a `version` field in the `preview-args` object, which will increase when the scheme of the preview arguments is changed.
```typ
#let version = preview-args.at("version", default: 0)
#if version <= 1 {
assert(preview-args.at("theme", default: "light") in ("light", "dark"))
}
```
==== Theme-aware template
The only two abstracted theme kinds are supported: `light` and `dark`. You can use the following code to get the theme:
```typ
#let preview-theme = preview-args.at("theme", default: "light")
```
|
https://github.com/duskmoon314/thu-polylux | https://raw.githubusercontent.com/duskmoon314/thu-polylux/main/template/main.typ | typst | MIT License | #import "@preview/polylux:0.3.1": *
#import "@local/thu-polylux:0.1.0": *
#show: thu-polylux.with(
// aspect-ratio: "16-9",
)
#title-slide(
title: "THU Polylux Theme",
subtitle: "模板示例",
author: "暮月",
institute: "清华大学",
)
#tableofcontents()
#section("课题背景", show-slide: true)
#slide(title: "Test")[
#lorem(5)
]
#section("研究现状", show-slide: true)
#slide(title: "Test")[
#lorem(5)
]
#section("研究内容", show-slide: true)
#slide(title: "Test")[
#lorem(5)
]
#section("计划进度", show-slide: true)
#slide(title: "Test")[
#lorem(5)
]
#section("参考文献", show-slide: true)
#slide(title: "Test")[
#lorem(5)
] |
https://github.com/Catlordx/WUT-LAB-Report-Typst-Template | https://raw.githubusercontent.com/Catlordx/WUT-LAB-Report-Typst-Template/master/main.typ | typst | MIT License | #import "wut.typ": *
#let number = "000111222333"
#let college = "计算机与人工智能学院"
#let teacher = "你猜猜"
#let course = "Rust程序设计"
#let author = "你猜猜"
#let class = "计算机xxxx"
#show: conf.with(
number: number,
title: "实验报告",
course: course,
college: college,
teacher: teacher,
author: author,
class: class,
from: 2024,
to: 2025,
which: 1,
)
#experiment_table(
course_name: course,
project_name: "顺序结构",
)[
#section_1()
#section_1_1()
#indent 豫章故郡,洪都新府。星分翼轸,地接衡庐。襟三江而带五湖,控蛮荆而引瓯越。物华天宝,龙光射牛斗之墟;人杰地灵,徐孺下陈蕃之榻。雄州雾列,俊采星驰。台隍枕夷夏之交,宾主尽东南之美。都督阎公之雅望,棨戟遥临;宇文新州之懿范,襜帷暂驻。十旬休假,胜友如云;千里逢迎,高朋满座。腾蛟起凤,孟学士之词宗;紫电青霜,王将军之武库。家君作宰,路出名区;童子何知,躬逢胜饯。
时维九月,序属三秋。潦水尽而寒潭清,烟光凝而暮山紫。俨骖騑于上路,访风景于崇阿。临帝子之长洲,得天人之旧馆。层峦耸翠,上出重霄;飞阁流丹,下临无地。鹤汀凫渚,穷岛屿之萦回;桂殿兰宫,即冈峦之体势。
披绣闼,俯雕甍,山原旷其盈视,川泽纡其骇瞩。闾阎扑地,钟鸣鼎食之家;舸舰弥津,青雀黄龙之舳。云销雨霁,彩彻区明。落霞与孤鹜齐飞,秋水共长天一色。渔舟唱晚,响穷彭蠡之滨,雁阵惊寒,声断衡阳之浦。
遥襟甫畅,逸兴遄飞。爽籁发而清风生,纤歌凝而白云遏。睢园绿竹,气凌彭泽之樽;邺水朱华,光照临川之笔。四美具,二难并。穷睇眄于中天,极娱游于暇日。天高地迥,觉宇宙之无穷;兴尽悲来,识盈虚之有数。望长安于日下,目吴会于云间。地势极而南溟深,天柱高而北辰远。关山难越,谁悲失路之人;萍水相逢,尽是他乡之客。怀帝阍而不见,奉宣室以何年。
嗟乎!时运不齐,命途多舛。冯唐易老,李广难封。屈贾谊于长沙,非无圣主;窜梁鸿于海曲,岂乏明时?所赖君子见机,达人知命。老当益壮,宁移白首之心?穷且益坚,不坠青云之志。酌贪泉而觉爽,处涸辙以犹欢。北海虽赊,扶摇可接;东隅已逝,桑榆非晚。孟尝高洁,空余报国之情;阮籍猖狂,岂效穷途之哭
勃,三尺微命,一介书生。无路请缨,等终军之弱冠;有怀投笔,慕宗悫之长风。舍簪笏于百龄,奉晨昏于万里。非谢家之宝树,接孟氏之芳邻。他日趋庭,叨陪鲤对;今兹捧袂,喜托龙门。杨意不逢,抚凌云而自惜;钟期既遇,奏流水以何惭?
呜呼!胜地不常,盛筵难再;兰亭已矣,梓泽丘墟。临别赠言,幸承恩于伟饯;登高作赋,是所望于群公。敢竭鄙怀,恭疏短引;一言均赋,四韵俱成。请洒潘江,各倾陆海云尔。
#align(center)[
滕王高阁临江渚,佩玉鸣鸾罢歌舞。
画栋朝飞南浦云,珠帘暮卷西山雨。
闲云潭影日悠悠,物换星移几度秋。
阁中帝子今何在?槛外长江空自流。
]
#section_1_2()
#section_1_3()
]
#blank_table([
#section_2()
#section_2_1()
#text(font: "Lucida Calligraphy")[
// #set text(font: "Lucida Calligraphy")
#align(center)[
Ode to the West Wind
]
#align(center)[
O wild West Wind, thou breath1 of Autumn's2 being3,
Thou, from whose unseen presence4 the leavesdead5
Are driven, like ghosts6 from an enchanter7 fleeing,
Yellow, and black, and pale, and hectic8 red,
Pestilence-stricken9 multitudes10: O thou,
Who chariotest11 to their dark wintry bed
The winged12 seeds, where they lie cold and low,
Each like a corpse13 within its grave14, until
Thine azure15sister of the Spring shall blow
Her clarion16o'er17the dreaming earth, and fill
(Driving sweet buds like flocks18 to feed in air)
With living hues19and odours20plain21and hill:
Wild Spirit, which art moving everywhere;
Destroyer22 and preserver23; hear, oh hear!
]
]
#section_2_2()
*插入图片*:
#align(center)[
#image("assets/logo.jpg")
]
*插入超链接*#link("https://typst.app/")[#text(font: "Lucida Calligraphy")[Typst]]
#section_2_3()
#lorem(62)
]) |
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/very-base-utils.typ | typst | #let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#let alternating-white = (white.darken(5%), white.darken(10%))
#let alternating-black = (black.darken(5%), black.darken(10%))
#let _block = block
#let _frac = block
#let _blue = blue
#let _red = red
#let _green = green
#let _black = black
#let _white = white
#let _circle = circle
#let _line = line
#let _text = text
#let _table = table
#let _heading = heading
#let _lorem = lorem
#let _pad = pad
#let _text = text
#let _rect = rect
#let _image = image
#let _figure = figure
#let _h = h
#let _box = box
#let _enum = enum
#let _list = list
#let typst-line = line
#let typst-circle = circle
#let typst-rect = rect
#let is-content(x) = { type(x) == "content" }
#let is-array(x) = { type(x) == "array" }
#let is-nested-array(x) = { type(x) == "array" and type(x.at(0)) == array }
#let is-dict(x) = { type(x) == "dictionary" }
#let is-dictionary(x) = { type(x) == "dictionary" }
#let is-object(x) = { type(x) == "dictionary" }
#let is-integer(x) = { type(x) == "integer" }
#let is-number(x) = { type(x) == "integer" }
#let is-length(x) = { type(x) == "length" }
#let is-function(x) = { type(x) == "function" }
#let is-string(x) = { type(x) == "string" }
#let identity(x) = {
return x
}
// doc: retrieves the first arg of sink.pos() or fallback
#let get-sink(sink, fallback) = {
let args = sink.pos()
return if args.len() == 0 { fallback } else if args.len() == 1 { args.first() } else { args }
}
#let empty(x) = {
return x == none
}
#let exists(x) = {
return x != none and x != false
}
#let trim(x) = {
return x.trim()
}
#let has-value(x) = {
return x != none and x.len() > 0
}
#let split(s, r) = {
return s.split(regex(r)).map(trim).filter(has-value)
}
#let len(s) = {
return s.len()
}
#let colored(x, fill: none) = {
return text(fill: resolve-color(fill), resolve-content(x))
}
#let array-to-dict(aa) = {
let store = (:)
for (a,b) in aa {
store.at(a) = b
}
return store
}
#let assign-fresh(a, b) = {
for (k, v) in b {
if k not in a {
a.insert(k, v)
}
}
return a
}
#let merge-fresh(a, b) = {
let store = ()
for (k, v) in a {
let value = if k in b { b.at(k) } else { v }
store.insert(k, value)
}
return store
}
#let resolve-str(x) = {
if is-string(x) {
return x
}
return str(x)
}
#let resolve-text(x) = {
if is-string(x) {
return x
}
if is-content(x) {
return x
}
if is-object(x) {
return x.text
}
return str(x)
}
#let resolve-pt(x) = {
if is-length(x) {
return x
}
return x * 1pt
}
#let resolve-content(x) = {
if is-content(x) {
return x
}
return text(str(x))
}
#let is-even(n) = {
return calc.rem(n, 2) == 0
}
#let is-odd(n) = {
return calc.rem(n, 2) != 0
}
#let split-twice(s) = {
let len = s.len()
if len == 1 {
return (s, s)
}
else if is-odd(len) {
panic("cant be odd len")
}
else {
let halfway-point = int(len / 2)
let a = s.slice(0, halfway-point)
let b = s.slice(halfway-point)
return (a, b)
}
}
#let wrap(x, ..sink) = {
let symbol = get-sink(sink, " ")
if is-number(symbol) {
let spaces = resolve-point(symbol)
spaces
x
spaces
} else if is-content(symbol) {
symbol
x
symbol
} else {
split-twice(symbol).join(x)
}
}
#let resolve-color(color) = {
let colors = (:)
return if is-string(color) { colors.at(color, default: green) } else { color }
}
#let split-singles(s) = {
let store = ()
for letter in s {
store.push(letter)
}
return store
}
#let test(s, r) = {
return exists(s.match(regex(r)))
}
#let has(x, y) = {
return y in x
}
#let tail(file) = {
return file.split("/").last()
}
#let add-extension(file, ext) = {
if test(file, "\.\w+$") {
file
} else {
file + "." + ext
}
}
#let npath(dir, name) = {
return dir.replace(regex("/$"), "") + "/" + tail(name)
}
#let is-defined(x) = {
return x != none
}
#let coerce-content(x) = {
if not exists(x) {
return
} else if is-content(x) {
x
} else {
text(x)
}
}
#let coerce-array(x) = {
if is-array(x) {
x
} else {
(x,)
}
}
#let assert-array(body) = {
assert(
type(body) == array,
message: "Incorrect type for body: " + repr(type(body)),
)
}
#let resolve-inches(x) = {
let t = type(x)
if t == length {
return float(x.inches())
}
if t == int or t == float {
return x
}
panic("do not know how to resolve inches for", x)
}
#let assign(a, b) = {
if has-value(b) {
for (k, v) in b {
a.insert(k, v)
}
}
return a
}
#let centered(content) = {
align(center, content)
}
#let has-children(content) = {
if is-content(content) {
return "children" in content.body.fields()
}
return false
}
#let merge(..args) = {
let merge-array(..items) = {
return items.flatten()
}
let merge-dictionary(a, b, overwrite: true) = {
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, overwrite: overwrite)
}
}
return c
} else {
return if overwrite {b} else {a}
}
}
let items = args.pos()
let first = items.first()
if is-dict(first) {
return merge-dictionary(..items)
}
if is-array(first) {
return merge-array(..items)
}
}
#let str-replace(s, r, rep) = {
return s.replace(regex(r), rep)
}
#let remove-spaces(s) = {
return str-replace(s, " +", "")
}
#let templater(s, ref) = {
let callback(s) = {
let key = s.text.slice(1)
if is-string(ref) or is-number(ref) {
return str(ref)
}
return if test(key, "^\d") {
ref.at(int(key) - 1)
} else {
ref.at(key)
}
}
return str-replace(s, "\$\w+", callback)
}
#let fill(count, symbol) = {
return range(count).map((i) => symbol)
}
#let match(s, r) = {
let m = s.match(regex(r))
if m != none {
if len(m.captures) > 0 {
m.captures
} else {
m.text
}
}
}
#let get-match(x) = {
let length = x.captures.len()
if length > 1 {
return x.captures
}
else if length == 1 {
return x.captures.first()
}
else {
return x.text
}
}
#let re-wrap(ref, template) = {
let escapables = (
"*",
"(",
")",
"[",
"]",
"{",
"}",
)
let escape(s) = {
return if s in escapables {
"\\" + s
} else {
s
}
}
let s = ref.keys().map(escape).join("|")
return template.replace("$1", s)
}
#let dreplace(s, ref, template: "(?:$1)") = {
let replacer(x) = {
return ref.at(get-match(x))
}
let r = re-wrap(ref, template)
return s.replace(regex(r), replacer)
}
#let redact(text, fill: black, height: 1em) = {
box(rect(fill: fill, height: height)[#hide(text)])
}
#let bold(x) = {
return text(weight: "bold", resolve-content(x))
}
#let assert-type(body, kind: none) = {
let ref = (
array: list,
dict: dictionary,
number: int,
string: str,
str: str,
)
let a = type(body)
let b = ref.at(kind)
if a == b {
return
}
let args = (b, a)
let message = templater("require type: $1. instead got: $2.", args)
panic(message)
}
#let copy(x) = {
if is-array(x) {
return x.map(copy)
}
if is-object(x) {
let store = (:)
for (a, b) in x {
store.insert(a, copy(b))
}
}
return x
}
#let get-longest(items) = {
let highest = 0
for item in items {
let l = item.len()
if l > highest {
highest = l
}
}
return highest
}
#let get-shortest(items) = {
let lowest = 1000
for item in items {
let l = item.len()
if l < lowest {
lowest = l
}
}
return lowest
}
#let double-quote(s) = {
if s.starts-with("\"") == true {
return s
}
return "\"" + s + "\""
}
#let step(..args) = {
let a = args.pos()
let start = 1
let end = a.at(0)
let step = 1
let arg-length = a.len()
if arg-length == 2 {
start = a.at(0)
end = a.at(1)
}
else if arg-length == 3 {
start = a.at(0)
end = a.at(1)
step = a.at(2)
}
return range(start, end + 1, step: step)
}
#let reduce(iterable, fn) = {
if is-object(iterable) {
iterable = iterable.pairs()
}
assert(is-array(iterable.first()))
let store = (:)
for item in iterable {
if item != none {
let (k, v) = item
let value = fn(v, k)
if value != none {
store.insert(k, value)
}
}
}
return store
}
#let walk(o, fn) = {
let runner(o, key: none) = {
if is-array(o) {
return o.map(runner.with(key: key))
} else if is-object(o) {
let store = (:)
for (k, v) in o.pairs() {
let value = runner(v, key: k)
store.insert(k, value)
}
return store
} else {
return fn(o, key)
}
}
return runner(o)
}
#let square(size, ..sink) = {
rect(width: size, height: size, ..sink)
}
#let merge-existing(a, b) = {
let c = (:)
for (k,v) in a {
if k in b {
c.insert(k, b.at(k))
} else {
c.insert(k, v)
}
}
return c
}
#let untouchable() = {
panic("this should never be reached")
}
#let todo(..sink) = {
panic("todo", get-sink(sink, ""))
}
#let is-last(index, items) = {
return index == len(items) - 1
}
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/raw.typ | typst | Apache License 2.0 | ```typ
abc
```
```typ abc ```
#```typ abc```
#(```typ abc```)
#text(```typ https://zh.wikipedia.org```)
````typ
https://zh.wikipedia.org
````
#(
```typ
writing-markup
```,
```typ
writing-markup
```
)
#let escaped-sequences = (
``, `\[`, ```\` ```, `\"`, [\`]
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/lang-with-region_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// with unknown region configured
#set text(font: "Noto Serif CJK TC", lang: "zh", region: "XX")
#outline()
|
https://github.com/jverzani/CalculusWithJuliaNotes.jl | https://raw.githubusercontent.com/jverzani/CalculusWithJuliaNotes.jl/main/quarto/precalc/Precalculus.typ | typst | MIT License | // Some definitions presupposed by pandoc's typst output.
#let blockquote(body) = [
#set text( size: 0.92em )
#block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body]
]
#let horizontalrule = [
#line(start: (25%,0%), end: (75%,0%))
]
#let endnote(num, contents) = [
#stack(dir: ltr, spacing: 3pt, super[#num], contents)
]
#show terms: it => {
it.children
.map(child => [
#strong[#child.term]
#block(inset: (left: 1.5em, top: -0.4em))[#child.description]
])
.join()
}
// Some quarto-specific definitions.
#show raw.where(block: true): set block(
fill: luma(230),
width: 100%,
inset: 8pt,
radius: 2pt
)
#let block_with_new_content(old_block, new_content) = {
let d = (:)
let fields = old_block.fields()
fields.remove("body")
if fields.at("below", default: none) != none {
// TODO: this is a hack because below is a "synthesized element"
// according to the experts in the typst discord...
fields.below = fields.below.amount
}
return block.with(..fields)(new_content)
}
#let unescape-eval(str) = {
return eval(str.replace("\\", ""))
}
#let empty(v) = {
if type(v) == "string" {
// two dollar signs here because we're technically inside
// a Pandoc template :grimace:
v.matches(regex("^\\s*$")).at(0, default: none) != none
} else if type(v) == "content" {
if v.at("text", default: none) != none {
return empty(v.text)
}
for child in v.at("children", default: ()) {
if not empty(child) {
return false
}
}
return true
}
}
// Subfloats
// This is a technique that we adapted from https://github.com/tingerrr/subpar/
#let quartosubfloatcounter = counter("quartosubfloatcounter")
#let quarto_super(
kind: str,
caption: none,
label: none,
supplement: str,
position: none,
subrefnumbering: "1a",
subcapnumbering: "(a)",
body,
) = {
context {
let figcounter = counter(figure.where(kind: kind))
let n-super = figcounter.get().first() + 1
set figure.caption(position: position)
[#figure(
kind: kind,
supplement: supplement,
caption: caption,
{
show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1))
show figure.where(kind: kind): set figure.caption(position: position)
show figure: it => {
let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1)
show figure.caption: it => {
num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug?
[ ]
it.body
}
quartosubfloatcounter.step()
it
counter(figure.where(kind: it.kind)).update(n => n - 1)
}
quartosubfloatcounter.update(0)
body
}
)#label]
}
}
// callout rendering
// this is a figure show rule because callouts are crossreferenceable
#show figure: it => {
if type(it.kind) != "string" {
return it
}
let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none)
if kind_match == none {
return it
}
let kind = kind_match.captures.at(0, default: "other")
kind = upper(kind.first()) + kind.slice(1)
// now we pull apart the callout and reassemble it with the crossref name and counter
// when we cleanup pandoc's emitted code to avoid spaces this will have to change
let old_callout = it.body.children.at(1).body.children.at(1)
let old_title_block = old_callout.body.children.at(0)
let old_title = old_title_block.body.body.children.at(2)
// TODO use custom separator if available
let new_title = if empty(old_title) {
[#kind #it.counter.display()]
} else {
[#kind #it.counter.display(): #old_title]
}
let new_title_block = block_with_new_content(
old_title_block,
block_with_new_content(
old_title_block.body,
old_title_block.body.body.children.at(0) +
old_title_block.body.body.children.at(1) +
new_title))
block_with_new_content(old_callout,
block(below: 0pt, new_title_block) +
old_callout.body.children.at(1))
}
// 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead
#let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = {
block(
breakable: false,
fill: background_color,
stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"),
width: 100%,
radius: 2pt,
block(
inset: 1pt,
width: 100%,
below: 0pt,
block(
fill: background_color,
width: 100%,
inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) +
if(body != []){
block(
inset: 1pt,
width: 100%,
block(fill: white, width: 100%, inset: 8pt, body))
}
)
}
#let article(
title: none,
subtitle: none,
authors: none,
date: none,
abstract: none,
abstract-title: none,
cols: 1,
margin: (x: 1.25in, y: 1.25in),
paper: "us-letter",
lang: "en",
region: "US",
font: "linux libertine",
fontsize: 11pt,
title-size: 1.5em,
subtitle-size: 1.25em,
heading-family: "linux libertine",
heading-weight: "bold",
heading-style: "normal",
heading-color: black,
heading-line-height: 0.65em,
sectionnumbering: none,
toc: false,
toc_title: none,
toc_depth: none,
toc_indent: 1.5em,
doc,
) = {
set page(
paper: paper,
margin: margin,
numbering: "1",
)
set par(justify: true)
set text(lang: lang,
region: region,
font: font,
size: fontsize)
set heading(numbering: sectionnumbering)
if title != none {
align(center)[#block(inset: 2em)[
#set par(leading: heading-line-height)
#if (heading-family != none or heading-weight != "bold" or heading-style != "normal"
or heading-color != black or heading-decoration == "underline"
or heading-background-color != none) {
set text(font: heading-family, weight: heading-weight, style: heading-style, fill: heading-color)
text(size: title-size)[#title]
if subtitle != none {
parbreak()
text(size: subtitle-size)[#subtitle]
}
} else {
text(weight: "bold", size: title-size)[#title]
if subtitle != none {
parbreak()
text(weight: "bold", size: subtitle-size)[#subtitle]
}
}
]]
}
if authors != none {
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..authors.map(author =>
align(center)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
block(inset: 2em)[
#text(weight: "semibold")[#abstract-title] #h(1em) #abstract
]
}
if toc {
let title = if toc_title == none {
auto
} else {
toc_title
}
block(above: 0em, below: 2em)[
#outline(
title: toc_title,
depth: toc_depth,
indent: toc_indent
);
]
}
if cols == 1 {
doc
} else {
columns(cols, doc)
}
}
#set table(
inset: 6pt,
stroke: none
)
#show: doc => article(
title: [Precalculus topics with Julia],
date: [2024-10-13],
sectionnumbering: "1.",
toc_title: [Table of contents],
toc_depth: 3,
cols: 1,
doc,
)
Various pre-calculus topics
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%20591%20-%20Mathematical%20Logic/Assignments/Assignment%203.typ | typst | #import "/Templates/generic.typ": latex, header
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": *
#import "@preview/cetz:0.2.0"
#let head(doc) = header(doc, title: "Assignment 3")
#show: head
#show: latex
#show: NumberingAfter
#show: thmrules
#show: symbol_replacing
#set page(margin: (x: 1.6cm, top: 2.5cm, bottom: 1.9cm))
#show math.equation: it => {
if it.has("label"){
return math.equation(block: true, numbering: "(1)", it)
}
else {
it
}
}
#show ref: it => {
let el = it.element
if el != none and el.func() == math.equation {
link(el.location(),numbering(
"(1)",
counter(math.equation).at(el.location()).at(0)+1
))
} else {
it
}
}
#let lemma = lemma.with(numbering: none)
#set enum(numbering: "(a)")
= Question
<question-1>
== Statement
A model $mM$ of a theory $T$ is called existentially closed if whenever $sigma$ is an existential $L(mM)$-sentence satisfied in a model $mN sat T$ containing $mM$, then $mM sat sigma$.
Show that the following are equivalent for a theory $T$:
+ all models of $T$ are existentially closed,
+ for every formula $phi(ov(x))$ there exists a universal formula $psi(ov(x))$ such that $T proves forall ov(x) (phi(ov(x)) <-> psi(ov(x)))$
== Solution
The backwards direction is simple, let $sigma(ov(c)) = exists ov(y) (phi(ov(c), ov(y))) $ be an existential $(|mM)$-sentence for some model $mM sat T$, where $ov(c)$ are the constants coming from $mM$. Now if for some model $mN sat T$ that contains $mM$ we have $mN sat sigma$, then by assumption there exists a universal formula $psi(ov(c))$ such that $T proves forall ov(c) (exists ov(y)(phi(ov(c),ov(y))) <-> psi(ov(c)))$ and so $mN sat psi(ov(c))$. But now $phi(ov(c))$ is a universal statement so since $ov(c) in mM$ then since universal statements are closed downwards then $mM sat phi(ov(c))$ and thus by using the assumption again $mM sat exists ov(y) (phi(ov(c),ov(y))$ and thus $mM sat sigma(ov(c))$.
Now the forward direction is tricky, first we can assume that $phi(ov(c))$ being true is consistent since otherwise it is equivalent to a false statement. Now let us first prove a lemma.
#lemma[
Let $phi(ov(x))$ be a closed formula, meaning that if $mN sat T$ is a model containing $mM sat T$ then $mN sat phi(ov(a)) => mM sat phi(ov(a))$ for all $a in mM$. Then $T proves forall ov(x) (phi(ov(x)) <-> psi(ov(x)))$ for some universal formula $psi(ov(x))$.
]
#proof[
Add a constant $c$ to the language $L$ and set $T' = angle.l T, phi(ov(c)) angle.r$ to be the theory closure of $T$ and $phi(ov(c))$. Assume then that $mM sat T'_forall$, then by assignment 2 there is some model $mN sat T'$ that contains $mM$. Then $mN sat phi(ov(c))$, but now since it is a closed formula $mM sat phi(ov(c))$ and so $T'_forall proves phi(ov(c))$. Then by definition, there is a finite collection of universal sentences $psi_i (ov(c))$ with
$
T union {psi_i (ov(c)) : i <= n } proves phi(ov(c)).
$
Then since a conjunction of universal sentences is also universal and so if we set $Phi (ov(c)) = and.big_i psi_i (ov(c))$ then $Phi (ov(c))$ is universal and
$
T proves Phi(ov(c)) -> phi(ov(c)).
$
On the other hand since $Phi (ov(c))$ is in $T'$ then $T union { phi(ov(c)) } proves Phi(ov(c))$ and so
$
T proves phi(ov(c)) -> Phi(ov(c)).
$
Thus $T proves phi(ov(c)) <-> Phi(ov(c))$. But since $T$ doesn't know anything about $ov(c)$ we can use the Model Theory Eraser™️ to replace it with a variable $ov(x)$ and take a universal quantifier.
]
We now prove the statement with induction on the number of quantifiers in the normal form of the formula $phi(ov(x))$
#pagebreak(weak: true)
=== Base case
If $phi(ov(x))$ is existential, since every model of $T$ is existential closed, $phi(ov(x))$ is closed and thus by the lemma above we are done.
=== Universal Quantifier
Assume that $phi(ov(x)) = forall ov(y) (phi'(ov(x),ov(y)))$, then by inductive hypothesis applied to $phi'$,
$
T proves forall ov(y) forall ov(x) (phi'(ov(x), ov(y)) <-> psi(ov(x),ov(y)))
$
and so as a consequence of this
$
T proves forall ov(x) (forall ov(y) (phi'(ov(x), ov(y))) <-> forall ov(y) (psi(ov(x),ov(y))))
$
now $forall ov(y) (psi(ov(x),ov(y)))$ is still universal and so we are done.
=== Existential Quantifier
Assume instead that $phi(ov(x)) = exists ov(y) (phi'(ov(x), ov(y)))$, again by inductive hypothesis, now applied to $not phi'$,
$
T proves forall ov(y) forall ov(x) (not phi'(ov(x), ov(y)) <-> psi(ov(x),ov(y)))
$
for some universal formula $psi$.
Now as a consequence of this
$
T proves forall ov(x) (forall ov(y) (not phi'(ov(x),ov(y))) <-> forall ov(y) (psi(ov(x),ov(y))))
$
and so since $p <-> q$ is equivalent to $not p <-> not q$ we get
$
T proves forall ov(x) (exists ov(y) (phi'(ov(x),ov(y))) <-> exists ov(y) (not psi(ov(x),ov(y)))).
$
But now $exists ov(y) (not psi(ov(x),ov(y)))$ is an existential formula and so by base case, we have for some universal formula $phi'$
$
T proves forall ov(x) (exists ov(y) (not psi(ov(x),ov(y))) <-> phi'(ov(x)))
$
and so we also have
$
T proves forall ov(x) (phi(ov(x)) <-> phi'(ov(x)))
$
#pagebreak(weak: true)
= Question
== Statement
A theory is called Model Complete if for any two models $mM, mN sat T$, if $mM$ is a substructure of $mN$, then $mM elm mN$.
Show that a theory $T$ is model complete if and only if every model of $T$ is existentially closed.
== Solution
Assume that $T$ is model complete, let $mM sat T$ and $sigma(ov(a))$ is an existential $L(mM)$ sentence, then if for some $mN sat T$ containing $mM$ we have $mN sat sigma(ov(a))$ then by model completeness we have $mM elm mN$ and thus $mM sat sigma(ov(a))$. Thus $mM$ is existentially closed.
On the other hand assume that all models of $T$ are existentially closed, assume that $mM,mN sat T$ with $mM seq mN$ then by @question-1 we have that for any $L(mM)$-sentence $sigma(ov(c))$
$
T proves forall ov(x) (sigma(ov(x)) <-> psi(ov(x)))
$
for some universal formula $psi$. But then $mN sat sigma(ov(a))$ means that $mN sat psi(ov(a))$ and so since universal formulas are closed downwards $mM sat psi(ov(a))$ and so $mM sat sigma(ov(a))$. Thus we have
$
mN sat sigma(ov(a)) => mN sat sigma(ov(a)).
$
<eqn-1>
For the other direction, again by @question-1, now applied to $not sigma(ov(a))$, we get
$
T proves forall ov(x) (not sigma(ov(x)) <-> psi(ov(x)))
$
for some universal statement $psi$. But then by negating inside the brackets we get
$
T proves forall ov(x) (sigma(ov(x)) <-> not psi(ov(x))).
$
Now $not psi$ is an existential formula which means it is closed upwards so $mM sat sigma(ov(a))$ means that $mM sat not psi(ov(x))$ and so $mN sat not psi(ov(x))$ and finally $mN sat sigma(ov(a))$. We have thus showed that
$
mM sat sigma(ov(a)) => mN sat sigma(ov(a))
$
and so together with @eqn-1 this proves that $mM elm mN$.
#pagebreak(weak: true)
= Question
<question-3>
== Statement
Describe the complete $n$-types over the empty set for the theory of dense linear orders without endpoints.
== Solution
I will claim that this set of complete $n$-types is in correspondence with the set of finite linear orders on at most $n$ elements.
To see this we will need the following simple lemma to reframe our question.
#lemma[
For two complete $n$ types $p_1(x_1,...x_n)$ and $p_2(x_1,...x_n)$ over the empty set in a theory $T$, $p_1 = p_2$ if and only if for every two models $mM sat p_1$, $mN sat p_2$, $mM$ and $mN$ are elementarily equivalent as models over the language $L(a_1,...a_n)$.
]
<lemma-elem_equiv>
#proof[
Since the types are complete we know that
$
Th_(L(a_1,...,a_n)) (mM) = p_1
"and"
Th_(L(a_1,...,a_n))(mN) = p_2.
$
The statement then follow trivially.
]
Our plan is now to get the correspondence as in the following diagram
#block(width: 100%)[
#set align(center)
#cetz.canvas({
import cetz.draw: *
set-style(mark: (end: ">"))
content((0,0), box(inset: 3pt)[Start with type $p$ on $a_1,...,a_n$], name: "top left")
content((0,-1.5), box(inset: 3pt)[Check for each $i,j$ if $a_i < a_j$ or $a_j < a_i$ or neither], name: "middle left")
content((0,-3), box(inset: 3pt)[Get ordering on some set of size at most $n$], name: "bottom left")
content((7,0), box(inset: 3pt)[Start with order on $A$], name: "top right")
content((7,-1.5), box(inset: 3pt)[Realize $A$ as $A seq QQ$], name: "middle right")
content((7,-3), box(inset: 3pt)[Get type $tp_n^QQ (A)$], name: "bottom right")
line((name: "top left", anchor: "south"), (name: "middle left", anchor: "north"))
line((name: "middle left", anchor: "south"), (name: "bottom left", anchor: "north"))
line((name: "top right", anchor: "south"), (name: "middle right", anchor: "north"))
line((name: "middle right", anchor: "south"), (name: "bottom right", anchor: "north"))
})]
Now clearly for any finite linear order on some set $A$ with $|A| <= n$, the order is realized on some finite subset of $QQ$. Now set $a_1,...,a_n$ to be the $QQ$ elements realizing it, then $tp_n^QQ (a_1,...a_n)$ is a complete type.
Now let $p$ be some arbitrary complete $n$-type on $T$, let $a_1,...,a_n$ be the variables of the type, then since the type is complete we have for each $i,j$ either $a_i < a_j$, $a_j < a_i$ or neither. This then gives us a finite total ordering on the $a_i$'s with 'neither' corresponding to $a_i = a_j$.
Now we want to check that the two operations are inverses of each other. Clearly if we start with an ordering, get a type, then the type gives us back the ordering we started with since the type will contain sentences of the form $a_i < a_j$ characterizing the ordering.
Now assume then that we start with a type $p$, get an ordering, then realize the ordering in $QQ$, and get the type $tp_n^QQ (A)$. We want to argue that $tp_n^QQ (A) = p$, to see this we will use #link(<lemma-elem_equiv>)[the lemma above]. We will show that in fact any countable model of $p$ is isomorphic to $tp_n^QQ (A)$ and so $p$ is $omega$-categorical and thus complete, making all its models elementarily equivalent. Recall that we showed dense linear orders are $omega$-categorical by using the back and forth construction, and recall that our inductive step did not care what partial isomorphism we had in the previous step. Now since the partial map $f : mM -> QQ$ given by $f(a_i) = a_i$ is a partial isomorphism we can treat it as a step in the back and forth method thus completing $f$ to an isomorphism. Thus $p$ is $omega$-categorical and thus complete.
#pagebreak(weak: true)
= Question
== Statement
Describe the complete $n$-types over the empty set for the theory of atomless Boolean algebras.
== Solution
First I will define a 'generating' set for a Boolean algebra $A$ to be a set of elements $a_i$ such that each element of $A$ can be written of the form
$
or.big_(i in S) and.big_(j in K_i) s_(i,j)
$
where $s_(i,j)$ is of the form $a_ell$ or $not a_ell$.
Similarly to the above question I claim that the complete $n$-types are in correspondence with generating sets of size at most $n$ for finite Boolean algebras.
We will use #link(<lemma-elem_equiv>)[the lemma in question 3] as well.
In order to recreate the argument from question 3 we want a standard model of this theory to work with. We will define one implicitly, by taking an infinite sequence of elements $x_1,x_2,...$ and declaring that any finite intersection of $x_i$ or $not x_i$ using each element at most once is non zero, we will then consider the 'free' Boolean algebra generated by these elements and call it $BB$.
Now our plan will be very similar to the previous question
#block(width: 100%)[
#set align(center)
#cetz.canvas({
import cetz.draw: *
set-style(mark: (end: ">"))
content((0,0), box(inset: 3pt)[Start with type $p$ on $a_1,...,a_n$], name: "top left")
content((0,-1.5), box(inset: 3pt)[Consider all relations satisfied by these elements], name: "middle left")
content((0,-3), box(inset: 3pt)[Get some finite Boolean algebra $A$], name: "bottom left")
content((7,0), box(inset: 3pt)[Start some finite Boolean algebra $A$], name: "top right")
content((7,-1.5), box(inset: 3pt)[Realize $A$ as $A seq BB$], name: "middle right")
content((7,-3), box(inset: 3pt)[Get type $tp_n^BB (A)$], name: "bottom right")
line((name: "top left", anchor: "south"), (name: "middle left", anchor: "north"))
line((name: "middle left", anchor: "south"), (name: "bottom left", anchor: "north"))
line((name: "top right", anchor: "south"), (name: "middle right", anchor: "north"))
line((name: "middle right", anchor: "south"), (name: "bottom right", anchor: "north"))
})]
First let us construct a finite subalgebra for each type, we do this by considering elements of the form
$
and.big_(i=1)^n s_i
$
where each $s_i$ is either $a_i$ or not $a_i$. Then the type $p$ will tell us for each such element whether it is equal to $0$ or not. Then we collect all the ones that are not equal to zero and consider them as atoms and use that to generate a finite Boolean algebra. One can easily check that for this Boolean algebra the original elements $a_i$ form a generating set for this algebra.
The second thing we need to prove is that every finite Boolean algebra is realized in $BB$.
We can do this by the back and forth method we used in Assignment 1, we can construct, step by step, an isomorphism between any finite Boolean algebra $A$ to some finite subalgebra of $BB$
We now need to check that any two models of some type $p$ are elementarily equivalent. We show this also using back and forth, let $p$ be a type and $A$ the associated finite subalgebra, we need to show that for any countable model $mM sat p$ we have $(mM,a_1,...,a_n) equiv (BB,a_1,...,a_n)$, but this is simple by starting with the partial isomorphism mapping $a_i in mM$ to $a_i in BB$ and then extending it to all of $mM$ and $BB$ using back and forth.
Thus as in @question-3 we showed the correspondence.
#pagebreak(weak: true)
= Question
<question-5>
== Statement
A model $mM$ of a complete theory $T$ is a _prime model_ if for every model $mN sat T$ there exists an elementary embedding of $mM$ into $mN$.
Show that $mM$ is a prime model if and only if $mM$ is countable and every type $tp^mM (ov(a))$ for a tuple $ov(a)$ in $mM$ is isolated.
== Solution
I am going to assume the language is countable since otherwise this can't be true.
Assume that a model is prime, then by Lowenheim-Skolem downwards Theorem we get that there are countable models $mN$ of $T$ with $mN elm mM$. Now by assumption $mM elm mN$ and so they must be isomorphic and thus $mM$ must be countable. Now assume that a type $tp^mM (ov(a))$ is not isolated for some tuple $ov(a)$. This means that there is a model of $T$ that omits $tp^mM (ov(a))$ and so there is no way to elementarily embed $mM$ into $mN$ since the image of $ov(a)$ would have the same type.
On the other hand let $mM$ be a model model which is countable and in which every tuple has an isolated type. Then let $mN sat T$ be any other model, then we construct an elementary embedding by induction (or as I like to call it, the forth method), where at each step we will form a partial embedding $f_n : A_n -> B_n$ where $A_n seq mM$ and $B_n seq mN$.
At the base case we map constants to constants $f_0$ maps constants to constants, now enumerate the rest of $mM$ as $a_0,a_1,...$ and assume we have constructed $f_n$. Now let $a_j$ be the element of smallest index not in $A_n$, consider the type $tp^mM (ov(A_n), a_j)$ where $ov(A_n)$ represents the ordered tuple of elements in $A_n$. This type must be isolated so there is some formula $phi(ov(A_n),a_j)$ which implies the whole type, then we have $mM sat exists x (phi(ov(A_n),x))$. But then $exists x (phi(ov(A_n),x)) in tp^mM (ov(A_n))$ so $exists x (phi(ov(B_n), x)) in tp^mN (ov(B_n))$ since $f_n$ is a partial embedding. Hence we can pick a witness $y$ to this sentence and extend $f_n$ by setting $f_(n+1) (a_j) = y$. This continues to be a partial embedding. Then by induction we construct an embedding $f : mM -> mN$.
Note that this is injective since the formulas $a_i != a_j$ are preserved by the embedding.
#pagebreak(weak: true)
= Question
== Statement
Prove that $T$ has a prime model if and only if for every $n$, the isolated types are dense in $S_n (T)$.
== Solution
Assume that $T$ has a prime model, then let $p$ be a type in $S_n (T)$ with some model $mN sat T$ that realizes it and let $mM$ be the prime model of $T$, giving us $mM elm mN$. Now let $[phi(ov(a))]$ be some open neighborhood containing $p$, then $phi in p$. But then $mN sat exists ov(x) (phi(ov(x)))$ and so $mM sat exists ov(x) (phi(ov(x)))$. Now by @question-5 we get that the witness $ov(a)$ of this sentence in $mM$ has an isolated type $tp_n^mM (ov(a))$ and thus by construction $phi in tp_n^mM (ov(a))$ and so $tp_n^mM (ov(a)) in [phi(ov(a))]$ and so we have found an isolated type in $[phi(ov(a))]$ and so the set of isolated types is dense in $S_n (T)$.
On the other hand assume that the set of isolated types is dense, we want to show the existence of a countable model $mM$ in which every type is isolated. Notice first that we don't need to worry about countability since we can just use Lowenheim-Skolem to bring the cardinality down. Next notice that $mM$ realizing a non-isolated type for an $n$-tuple $ov(a)$ is equivalent to
$
mM sat { not phi(ov(a)) | phi(ov(x)) "isolates a complete type" } =: p_n
$
for if $mM sat phi(ov(a))$ for some isolating formula then it would have an isolated type.
Now if $p_n$ is not a type, that is not finitely consistent, then all the types of $mM$ are isolated so no issues there, so we can assume that $p_n$ is a type. Now we simply need to omit this type, in order to do that we need to show that $p_n$ is not isolated, that is, for every satisfiable formula $psi(ov(x))$ there is a formula $phi(ov(x))$ which isolates a complete type such that $T tack.not forall ov(x) (psi(ov(x)) -> not phi(ov(x)))$.
But this is true, since for every formula $psi$ we have that there exists some complete isolated type $p in [psi]$, let $phi$ be its isolated formula, then $T proves forall ov(x) (phi(ov(x)) -> psi(ov(x))$ so $T tack.not forall ov(x) (psi(ov(x)) -> not phi(ov(x)))$, and so $p_n$ are all not isolated and thus all $p_n$ can be simultaneously omitted.
|
|
https://github.com/warthog-network/whitepaper | https://raw.githubusercontent.com/warthog-network/whitepaper/master/template.typ | typst | #import "@preview/numbly:0.1.0": numbly
// main project
#let bubble(
title: "",
subtitle: "",
alt: "",
author: "",
affiliation: "",
year: none,
class: none,
date: datetime.today().display(),
logo: none,
main-color: "#FDB913", // Primary Palette color of warthog
alpha: 60%,
color-words: (),
body,
) = {
set document(author: author, title: title)
// Save heading and body font families in variables.
let body-font = "Montserrat"
let title-font = "Montserrat"
// Set colors
let primary-color = rgb(main-color) // alpha = 100%
// change alpha of primary color
let secondary-color = color.mix(color.rgb(100%, 100%, 100%, alpha), primary-color, space:rgb)
// highlight important words
show regex(if color-words.len() == 0 { "$ " } else { color-words.join("|") }): text.with(fill: primary-color)
// customize look of figure
set figure.caption(separator: [ --- ], position: top)
// customize inline raw code
show raw.where(block: false) : it => h(0.5em) + box(fill: primary-color.lighten(90%), outset: 0.2em, it) + h(0.5em)
// Set body font family.
set text(font: body-font, 12pt)
show heading: set text(font: title-font, fill: primary-color)
// heading numbering
set heading(numbering: (..nums) => {
let level = nums.pos().len()
// only level 1 and 2 are numbered
let pattern = if level == 1 {
"I."
} else if level == 2 {
"I.1."
}
if pattern != none {
numbering(pattern, ..nums)
}
})
// add space for heading
show heading.where(level:1): it => it + v(0.5em)
// Set link style
show link: it => underline(text(fill: primary-color, it))
//numbered list colored
set enum(indent: 1em, numbering: n => [#text(fill: primary-color, numbering("1.", n))])
//unordered list colored
set list(indent: 1em, marker: n => [#text(fill: primary-color, "•")])
// display of outline entries
show outline.entry: it => text(size: 12pt, weight: "regular",it)
// Title page.
// Logo at top right if given
if logo != none {
set image(width: 6cm)
place(top + right, logo)
}
// decorations at top left
place(top + left, dx: -35%, dy: -28%, circle(radius: 150pt, fill: primary-color))
place(top + left, dx: -10%, circle(radius: 75pt, fill: secondary-color))
// decorations at bottom right
place(bottom + right, dx: 30%, dy: 30%, circle(radius: 150pt, fill: secondary-color))
v(2fr)
align(center, text(font: title-font, 3em, weight: 700, title))
v(2em, weak: true)
align(center, text(font: title-font, 2em, weight: 700, subtitle))
v(2em, weak: true)
align(center, text(1.1em, date))
v(2fr)
// alt information.
align(center)[
#text(alt, 14pt, weight: "bold") \
]
pagebreak()
// Table of contents.
set page(
numbering: "1 / 1",
number-align: center,
)
// Main body.
set page(
header: [#emph()[#title #h(1fr) #alt]]
)
set par(justify: true)
body
}
//useful functions
//set block-quote
#let blockquote = rect.with(stroke: (left: 2.5pt + luma(170)), inset: (left: 1em))
#let appendix(body) = {
set heading(numbering: numbly(
"Appendix {1:A}.",
"{1:A}.{2}.",
"{1:A}.{2}.{3}",
))
counter(heading).update(0)
body
}
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/public-member_guide/member_guide.typ | typst |
#import "/meta-environments/env-templates.typ": *
#set enum(full: true, numbering: (..n) => {
let format = if n.pos().len() > 1 {"a."} else {"1."}
numbering(format, n.pos().last())
})
#show: doc => guide_document(
title: "Member Guide",
authors: ("Protohav<NAME>",),
draft: true,
// date: datetime(
// year: 2024,
// month: 4,
// day: 1,
// ),
doc
)
= Welcome
<welcome_to_protohaven>
Welcome to Protohaven!
= Community
#set heading(offset:1)
#include "/common-policy/core_values.typ"
#include "/common-policy/shop_rules.typ"
#set heading(offset:0)
== Health
#set heading(offset:2)
#include "/common-policy/personal_protective_equipment.typ"
#include "/common-policy/emergency_equipment.typ"
#include "/common-policy/covid_protocols.typ"
#set heading(offset:0)
== Safety
#set heading(offset:2)
#include "/common-policy/tool_status_tags.typ"
#include "/common-policy/filing_a_tool_report.typ"
#set heading(offset:0)
= Programs
<programs>
== Classes
<classes>
Classes are the entry point to our community. They focus on teaching
design, fabrication, and related skills. They dive into everything from
basic skills and safety to immersive projects that teach students how to
operate equipment with confidence to advanced maintenance and
troubleshooting intensives that earn members clearance to join our
maintenance crew. They range from introductory public talks and
workshops to in-depth multi-week courses. Not all classes provide
clearances. Be sure to read course descriptions carefully.
Class development and support are led by the Education Coordinator and Executive Director and taught by either staff, Teaching Fellows, or contract instructors.
=== Getting Cleared on Tools
<getting-cleared-on-tools>
Most tools in the shop require clearance before independent use as a
member. Each tool is different and most are expensive and/or delicate.
You can find our full list of equipment and the clearance associated
with each tool at:
https://www.protohaven.org/equipment/
Each new member receives a free clearance (or \$45 off a 101 Class) when
they join and complete the
#link("https://protohaven.app.neoncrm.com/np/clients/protohaven/eventList.jsp")[New Member Orientation].
#strong[There are two pathways to get cleared to use equipment as a
member:]
+ #link("https://protohaven.app.neoncrm.com/np/clients/protohaven/eventList.jsp")[#strong[Take a Class]]
— Learn through making things together!
We think the best way to gain clearance on a piece of equipment that
is new to you is through a hands-on, supportive class that may include
a clearance. They’re also a great way to advance skills that you may
already have. Our classes are open to the public.
+ Open to the public, no experience required (unless otherwise
stated). \
+ 3-6 students maximum, depending on the class. \
+ Minimum of two participants. Classes may be canceled due to low
enrollment.
+ #link("https://www.protohaven.org/product-category/basic-clearances")[#strong[Schedule a Clearance]]
— Study
#link("https://www.protohaven.org/tool-trainers/")[shop protocols] &
show us your skills!
If you have previous experience on a tool our Clearances are designed
for you. These are exclusive to members and are scheduled by request.
You’ll need to demonstrate to your instructor that you can use the
equipment safely, carefully, and cleanly to receive clearance.
Clearances are pass/fail. YOU WILL NOT RECEIVE ANY INSTRUCTION DURING
THIS SESSION.
+ Open to active members, scheduled with minimum 72hr lead time \
+ 2 students maximum \
+ 1 student minimum
=== Intensive Courses
<intensive-courses>
We’re incredibly excited to offer intensive, multi-session courses! This
is the most in-depth, supportive pathway for anyone to grow confidence
working independently, deepen their skills, and gain clearance on
equipment.
Our intensive courses are the only class offering that include
membership, homework, a private \#class-channel on
#link("https://www.protohaven.org/discord/")[our discord server], and
peer group meetups between sessions. Existing members receive a special
discount on all our multi-session courses! It is important to note that
existing members who enroll in an intensive do not receive free,
discounted, transferred, refunded, or prorated membership during this
time.
= Membership
<membership>
Membership is a long-term educational and support program for design and
fabrication enthusiasts and professionals. Protohaven members receive
discounts on public courses, gain independent access to the 12,500ft2
Wilkinsburg campus for self-guided projects, participate in member-only
learning circles, and receive individual guidance based on their
specific goals.
The space includes professional-quality tools and equipment in 15
different disciplines ranging from graphic design and laser cutting to
woodworking and welding.
Each new member also receives a free Basic Clearance (or \$45 off a
class) when they join for the first time and complete the New Member
Orientation.
== Age Requirements
<age-requirements>
Minors using the shop outside of scheduled classes must be members and
accompanied by a parent or guardian who is also a member. \
#strong[Workshop access] is limited only to those 16+ years of age. \
#strong[Studio access] is limited only to those of 12+ years of age.
== Affordability
<affordability>
At Protohaven we are dedicated to being an accessible and equitable
makerspace. Low income rates are available for those who require
financial assistance to become members through our Access to Making
Program (AMP).
You can apply for an income based rate on our website:
// FIXME the following URL is broken? -pgm
https://protohaven.app.neoncrm.com/forms/protohaven-amp
== Membership Types
Protohaven offers three membership types: general, weekend, and weeknight:
#table(
stroke: none,
columns: (auto, auto, auto, auto),
inset: 10pt,
// align: horizon + left,
align: (col, row) => (left + top,center + top,center + top,center + top).at(col),
[], [*General*], [*Weekend*], [*Weeknight*],
table.hline(start: 1),
[Pricing],
[\$115.00/mo],
[\$65.00/mo],
[\$65.00/mo],
[Hours],
[10am–10pm],
[Sa-Su: 10am–10pm],
[M-F: 5pm–10pm],
[First Clearance Free\
(or \$45 toward a class)],
[✓],
[✓],
[✓],
)
=== General Membership
<general-membership>
General members have access to the shop during all of our public hours. This is our most popular option for enthusiasts who want the flexibility to use the shop anytime it's open to the public.
=== Weekend Membership
<weekend-membership>
Weekend members have access to the shop every Saturday and Sunday from 10am – 10pm. Weekend membership is an affordable option for those just getting into making, or who need only occasional access and can come in on the weekends.
=== Weeknight Membership
<weeknight-membership>
Weekend members have access to the shop every Monday through Friday from 5pm – 10pm. Weekend membership is an affordable option for those just getting into making, or who need only occasional access and can work in the evenings.
== Managing Your Protohaven Account
=== Sign Up for a Protohaven Membership
Sign up for a Protohaven membership with the following link:
https://www.protohaven.org/membership/
=== Cancel Your Protohaven Membership
You can cancel your membership at any time by going to your Protohaven account page:
https://www.protohaven.org/my-account/
...and navigating to:
#emph[My Account \> My Subscription \> Cancel]
To switch or resume your membership, cancel your existing membership (as above), and then sign up for your desired membership from the membership page:
https://www.protohaven.org/product/membership/
== Materials & Consumables
<materials-consumables>
It is the responsibility of the maker to provide their own materials and
consumables in the workshop this includes the materials you are using to
construct your work, but also certain consumables that are required for
equipment to function (ie. sandpaper, welding nozzles, flux, contact
paper, etc.) Our store has some of these items in stock, but we cannot
guarantee that everything you need will be in stock at all times. Please
come prepared. Anyone wanting to purchase consumables, must see the Shop
Tech on duty.
== Scheduling a Clearance
<scheduling-a-clearance>
Clearances are required before members can operate equipment
independently at Protohaven. Learn more at
#link(<getting-cleared-on-tools>)["Getting Cleared on Tools"] under the
#link(<classes>)["Classes"] section of this guide.
As a member, you can schedule a Basic Clearance for equipment where you
hold previous experience. Sign into your Protohaven account and go to
our
#link("https://www.protohaven.org/product-category/basic-clearances")[Basic Clearances]
page to schedule.
As an important next step, you’ll need to study the public,
shop-specific protocols by visiting the
#link(<tool-tutorials>)[Tool Tutorial] before your clearance.
== Tool Tutorials
<tool-tutorials>
#link("https://www.protohaven.org/tool-trainers/")[Tool Tutorials] are
public guides to the basic safe, careful, and clean use of the equipment
at Protohaven. They’re the basis for receiving clearance on equipment,
and are also useful resources for ongoing use.
We’ve just started their development, but will be creating them for each
piece of equipment in the shop that requires clearance to use.
The #strong[table of contents] on the left hand menu allows you to
quickly jump to the section you need. \
The #strong[Initial Setup], #strong[Basic Operation], and
#strong[Cleanup Checklists] are what instructors use to ensure that you
can use the equipment according to community expectations. \
== Reserving Equipment
<reserving-equipment>
Members are required to reserve time slots for equipment and areas
online using their Protohaven account. Reservations are for one and two
hour blocks and can be reserved multiple times. You must be cleared in
an area or piece of equipment in order to reserve it. Most areas can
support 2 members simultaneously working, however others (like welding
and the CNCs) can only support 1 user at a time. Anyone caught using
equipment that they do not have the appropriate clearances for risks
having their membership revoked.
#block[
#set enum(numbering: "1)", start: 1)
+ From the home page navigate to the membership tab and click "Equipment
reservations".
+ Once on the reservation page choose a piece of equipment from the
dropdown and use the calendar to select your desired date. Once
selected a drop down menu with available times will appear. Select
your desired time range and add to your cart. Repeat this step to add
more reservations (Times will not be reserved until you proceed to
checkout)
+ Once you have added all of your reservations proceed to checkout by
clicking the shopping basket at the top right of the page.
Reservations are free products and must be checked out before the
reservation can be booked.
]
#block[
#set enum(numbering: "1)", start: 4)
+ Once you complete checkout you will receive an email confirming your
booking. You can always review and cancel any current and past
bookings from the "My Account" page and navigate to "Bookings" NOTE:
Bookings may only be cancelled the day BEFORE your reservation. Day of
cancellations must be submitted by email to
#link("mailto:<EMAIL>")[<EMAIL>]. Please
include your order number in your cancellation request.
]
== Maintenance
<maintenance>
Maintenance actions can only be made by the authorized maintenance crew.
All members are expected to report maintenance when it’s required. A
subset of members then perform maintenance. Anyone can see the present
state of equipment by
#link("https://www.protohaven.org/tools/")[checking its status].
Maintenance is prioritized based on high equipment usage.
=== Maintenance Requests
<maintenance-requests>
Maintenance requests inform staff and techs of issues with equipment
ranging from simple replacement parts to potential safety issues.
Members are encouraged to use this system so that the Protohaven team
can respond quickly to shop needs, reducing equipment downtime and
keeping you working effectively longer. Maintenance Requests can be
found here: #link("https://www.protohaven.org/tools/")
=== Maintenance Actions
<maintenance-actions>
Maintenance actions can only be made by authorized maintenance crew
which includes staff, techs, instructors, fellows, and authorized
members. Members can view and follow maintenance actions in real time by
joining the Protohaven Discord Server
=== Equipment Status
<equipment-status>
You can also view the current status of all equipment and areas by
reviewing our Master Equipment List. This list catalogs all equipment
and reports its most recent condition and last action taken on it.
#link("https://www.protohaven.org/tools/")[View it here.]
== Storage
Protohaven provides both overnight and monthly storage options to ensure
you can continue working on your projects without the hassle of
transporting your work to and from home. You must see the Shop Tech on
duty in order to purchase storage.
=== Overnight storage
<overnight-storage>
- #strong[Project Carts] - Movable carts with bottom shelf, ideal for
storing smaller projects and tools. #emph[All belongings must remain
inside the perimeter of the cart.] \
- #strong[Hub Tables] - Movable, large tables, ideal for medium to large
glue-ups, drying, or curing. #emph[All belongings must remain inside
the perimeter of the table.] \
- #strong[Pallet space] - Workshop floor space, ideal for storing large
builds or pieces of personal equipment. #emph[Belongings must be on
movable pallets or carts with wheels.]
=== Monthly Storage
<monthly-storage>
- #strong[Locker] - Small lockers for storing tools, small projects, and
personal belongings. Can be locked (lock not included). \
- #strong[Board & Bar] - Great for longer lengths of wood or metal \
- #strong[Cage] - Perfect for those using the shop regularly. Plenty of
room for projects, material and personal tools. Can be locked (lock
not included). \
- #strong[Sheet] - Ideal for plywood, sheet metal, large acrylic, etc \
- #strong[Rack] - Shelving offering plenty of horizontal space for
flexible storage. #emph[All belongings must remain inside the area of
the shelf.] \
- #strong[Pallet space] - Workshop floor space, ideal for storing large
builds or pieces of personal equipment. #emph[Belongings must be on
movable pallets or carts with wheels.]
== Receiving Mail and Freight
As a member you can have your mail and supply orders sent directly to
Protohaven at no additional cost. Additionally, our loading docks can
support freight pick-ups and drop-offs within regular shop hours. We
just ask that you are available on your freight delivery day to properly
store your shipment before the shop closes that day. Please be sure to
check for mail regularly, as mail that has not been picked up for over
one month may be returned to the sender. If there are any extenuating
circumstances that will prevent you from picking up your mail in a
timely manner, please let us know.
== Guest Policy
<guest-policy>
==== Who
<who>
Protohaven members are welcome to bring guests during member hours.
Members are responsible for ensuring that their guests abide by all
shop, community and COVID-19 guidelines during their visit. They will
also need to complete the following upon entering the building.
==== When
<when>
Guests are welcome during all member access hours. See the
#link(<shop-hours>)[shop hours] section for details.
==== How
<how>
Guests are _not_ cleared Protohaven members and should not be assisting or
independently operating equipment in any way. Guests may consult, view
work in progress and socialize with their host.
Guests must join as members, complete orientation, and receive clearances _before_ working or assisting in the shop (this includes the use of tools provided by the
member).
*Protohaven members will risk having their membership revoked if they admit a guest that is using tools and equipment at Protohaven without the guest first becoming a member and receiving the proper clearances.*
== Emergency Policy
<emergency-policy>
=== Fire
<fire>
In the event of a small fire, extinguishers are present throughout the
building:
- Kitchen/Hub \
- Wood Shop \
- Maintenance Room \
- Blacksmithing \
- Front Entrance
If you use a fire extinguisher for any reason, notify the appropriate
Protohaven staff member or on duty tech.
In the event of a true fire emergency OR if the fire suppression system
is triggered, evacuate the building immediately and THEN call 911 ONLY
after you have safely removed yourself from danger. After emergency
services have been contacted notify the appropriate Protohaven staff
member or and fill out an incident report.
=== Medical/Injury
<medicalinjury>
For minor injuries there are first aid kits in the kitchen located next
to the shop doors, in the forge, and in the woodshop area next to the
door leading to the studio. Please report any low supplies to a staff
member. There are also two AED machines, with one being located in the
kitchen, and the other being located in the woodshop next to the first
aid kit.
In the event of a medical emergency time is of the essence. If you can
safely and knowledgeably do so, #strong[seek consent] to stabilize the
injured person(s) and CLEARLY IDENTIFY an individual to call 911. If you
are unable to stabilize, safely attempt to locate someone who can after
calling 911. After the immediate threat has passed and emergency
services have been contacted notify the appropriate Protohaven staff
member for further instruction.
In the event of an injury, an incident report will need to be filed with
the Shop Tech on duty.
==== Mental Health/Crisis De-Escalation
<mental-healthcrisis-de-escalation>
In the event of a mental health crisis it is important that those
affected feel safe and that they have resources at their disposal. Our
neighbors at Resolve Crisis Services (333 N. Braddock Ave.) have around
the clock support for those in need and we encourage you to direct those
in crisis to those resources.
Resolve 24/7 Hotline: 1-888-7-YOU-CAN (796-8226) \
Walk-ins welcome without appointment
= Communications
== Discord
<discord>
Protohaven Members enjoy access to our Discord server to connect, share,
and learn alongside fellow members. It is designed to be a peer-to-peer
resource for all members.
As part of our community, here are some of the channels you have access
to:
- \#general to connect and generally chit-chat with one another \
- \#free to share materials that are looking for a good home \
- \#buy-and-sell to, well, buy and sell \
- \#help-wanted to seek out advice or coordinate project help from other
members \
- \#show-and-tell to see and share all the cool things you’re working on
both inside and outside the shop!
To join, please use the link below and sign-up with your Protohaven
Email:
#link("https://www.protohaven.org/discord/")
= Volunteer Opportunities
<volunteer-opportunities>
== Shop Tech
<shop-tech>
Our Shop Techs represent our primary maintenance and member support
corps. This team is responsible for fulfilling maintenance requests,
assisting and greeting members, and opening and closing the shop.
=== How to Apply
<how-to-apply>
More information can be found at
#link("https://www.protohaven.org/opportunities/").
== Teaching Fellowship
<teaching-fellowship>
Over the course of this 6 month program, Teaching Fellows
collaboratively develop core Protohaven Classes. As a team, they play a
key role in creating a rich, supportive learning environment that brings
value to students of all skill levels.
=== How to Apply
<how-to-apply-1>
More information can be found at:
#link("https://www.protohaven.org/opportunities/").
== Instructor Open Calls
<instructor-open-calls>
Instructors are contracted to use their design and fabrication
experience to inspire, mentor, and problem solve alongside students who
are discovering their skills and gaining a deeper understanding of shop
equipment.
=== How to Apply
<how-to-apply-2>
Open calls will be posted as needed here:
#link("https://www.protohaven.org/opportunities/")
= Shop Information
<shop-information>
== Contact Information
=== Shop Location
#image("/common-graphics/maps/map-protohaven_location.svg")
=== Street Address
<protohaven-address>
214 N. Trenton Ave \
Wilkinsburg, PA \
15221
#strong[Note:] 214 S. Trenton is on the other side of Penn Ave and is a
residential address and is sometimes where packages are delivered by
accident. #strong[Please note on your shipment that deliveries should be
sent to a commercial/warehouse address.]
=== Phone Number
The Protohaven main desk can be reached by phone at: 412-731-4400
=== Email Address
Send email to Protohaven at: `<EMAIL>`
== Shop Hours
<shop-hours>
For the safety and security of our community and members Protohaven
Member Hours are only open to students (during scheduled class times),
members and guests of members. Office hours are open to the public for
tours while staff are available.
=== Office Hours
Monday - Friday: 10:00am - 4:00pm
=== Member Hours
Monday - Thursday: 10am - 10pm
Friday - Sunday: 10am - 10pm
=== Scheduled Tours
7 Days/Week
Saturday-Thursday 1pm and 6pm
Friday 1pm and 6:30pm
==== New Member Orientations
New member onboarding is a scheduled, one-on-one meeting to help you get settled in the shop.
==== Holidays (Shop Closed)
- New Year’s Eve
- New Year’s Day
- Martin Luther King Day
- Easter
- Memorial Day
- Juneteenth
- Independence Day
- Labor Day
- Thanksgiving/National Day of Mourning
- Christmas Eve
- Christmas
= Appendicies
== Code of Conduct
<code-of-conduct>
#set heading(offset:2)
#include "/common-policy/code_of_conduct.typ"
#set heading(offset:0)
== Shop Usage Agreement
<shop-usage-agreement>
== Floorplan
<floorplan>
#image("/common-graphics/maps/floorplan-full.svg", width: 100%)
== Equipment List
<equipment-list>
The following equipment list is more or less complete as of the date of publication of this member's guide. For an updated list with status information, please see the following link:
https://www.protohaven.org/equipment/
#block[
#set text(size: 9pt)
#let tool_list = csv("/data-reference/general/protohaven_tool_list.csv")
#table(
columns: (auto, auto, auto),
stroke: none,
inset: 5pt,
fill: (_, y) => if calc.odd(y) { color.tablegrey },
align: horizon + left,
table.header(
[*Shop Area*], [*Tool Name*], [*Make and Model*],
),
table.hline(),
..tool_list.flatten(),
)
]
|
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/bell/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#include "/examples/bell.typ" |
https://github.com/OrangeX4/typst-cheq | https://raw.githubusercontent.com/OrangeX4/typst-cheq/main/examples/custom-styles.typ | typst | MIT License | #import "../lib.typ": checklist
#set page(width: auto, height: auto, margin: 2em)
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Solar System Exploration, 1950s – 1960s
- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [-] Jupiter
- [/] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley
#show: checklist.with(marker-map: (" ": sym.ballot, "x": sym.ballot.x, "-": sym.bar.h, "/": sym.slash.double))
= Solar System Exploration, 1950s – 1960s
- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [-] Jupiter
- [/] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley |
https://github.com/OpenCorvallis/osfc-checklists | https://raw.githubusercontent.com/OpenCorvallis/osfc-checklists/main/73146.typ | typst | Apache License 2.0 | // Copyright 2024 Oregon State Flying Club
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// General design note: The checklists are defined in variables, then the pages
// are created and formatted at the bottom of the file. This puts all the
// formatting details in one place in the file, making it easier to perform
// formatting revisions.
#import "common.typ": checklist, checklist_group
// -----------------------------------------------------------------------------
// Ground Checklists and Information page
// -----------------------------------------------------------------------------
#let ground_checklists_and_info = [
#checklist("Preflight", black,
checklist_group("Fluids"),
([Magnetos], [OFF]),
([Fuel quantity], [CHECK VISUALLY]),
([Fuel sumps], [DRAIN],
[Left wing, right wing, fuel strainer. Inspect for contamination.]),
([Fuel filler caps], [SECURE]),
([Engine oil level], [CHECK], [Minimum 6 quarts]),
checklist_group("Cabin"),
([Pitot cover], [REMOVE]),
([POH], [VERIFY PRESENT]),
([Master], [ON]),
([Flaps], [EXTEND]),
([Fuel gauges], [CHECK QUANTITY]),
([Lights], [CHECK]),
([Tach time], [RECORD]),
([Pitot heat], [TEST]),
([Master], [OFF]),
([Fire extinguisher], [SECURE]),
([Control lock], [REMOVE]),
checklist_group("Empennage"),
([Rudder gust lock], [REMOVE]),
([Control surfaces], [CHECK], [Freedom of movement and security]),
checklist_group("Right"),
([Main wheel tire], [CHECK INFLATION]),
([Aileron], [CHECK], [Freedom of movement and security]),
checklist_group("Nose"),
([Propeller, spinner], [CHECK], [For nicks and security]),
([Landing light], [CHECK CLEAR]),
([Air filter], [CHECK CLEAR]),
([Nosewheel & strut], [CHECK INFLATED]),
([Static source], [CHECK CLEAR]),
checklist_group("Left"),
([Main wheel tire], [CHECK INFLATION]),
([Fuel tank vent], [CHECK CLEAR]),
([Pitot tube], [CHECK CLEAR]),
([Stall warning], [TEST]),
([Aileron], [CHECK], [Freedom of movement and security]),
checklist_group("Final"),
([FlightCircle], [DISPATCH]),
([Baggage door], [LOCK]),
([Chocks], [REMOVE]),
([Tie-downs], [REMOVE]),
)
#checklist("Securing", black,
([Control lock], [INSTALL]),
([Tie-downs, chocks], [APPLY]),
([Vents, windows], [CLOSE]),
([Pitot cover], [APPLY]),
([Tach, Hobbs times], [RECORD]),
([FlightCircle], [CHECK IN]),
([Doors], [LOCK]),
)
]
// -----------------------------------------------------------------------------
// Operating Checklists
// -----------------------------------------------------------------------------
#let operating_checklists = [
#checklist("Start", black,
checklist_group("Before Start"),
([Preflight inspection], [COMPLETE]),
([Passenger briefing], [COMPLETE]),
([Brakes], [TEST and SET]),
([Seats, belts, harnesses], [SECURE]),
([Fuel valve], [BOTH]),
([Radios, electrical equipment], [OFF]),
([Circuit breakers], [CHECK IN]),
([Beacon switch], [ON]),
checklist_group("Engine Start"),
([Mixture], [RICH]),
([Carburetor heat], [COLD]),
([Prime], [AS REQUIRED]),
([Throttle], [OPEN 1/8 INCH]),
([Master], [ON]),
([Propeller area], [CLEAR]),
([Ignition switch], [START], [Release when engine starts]),
([Oil pressure], [CHECK], [If no pressure in 30 seconds, shutdown]),
([Mixture], [GROUND LEAN]),
checklist_group("Before Taxi"),
([Avionics], [ON]),
([Headset], [ON]),
([Flaps], [RETRACT]),
([Weather], [OBTAIN]),
([Altimeter], [SET]),
([EFB Setup], [AS DESIRED]),
([Navigation, landing lights], [ON]),
)
#checklist("Run-up", black,
([Instruments], [CHECK and SET]),
([VOR Check], [IF NEEDED]),
([Brakes], [SET]),
([Doors and windows], [CLOSED, LOCKED]),
([Flight controls], [FREE and CORRECT]),
([Fuel valve], [BOTH]),
([Mixture], [RICH], [Below 3000 feet]),
([Throttle], [1700 RPM]),
([Magnetos], [CHECK], [Max drop 125 RPM, max diff. 50 RPM]),
([Engine gauges, ammeter], [CHECK]),
([Vacuum gauge], [CHECK]),
([Carburetor heat], [TEST]),
([Idle], [TEST]),
([Mixture], [GROUND LEAN]),
([Throttle friction], [ADJUST]),
)
#checklist("Before Takeoff", black,
([Radios], [SET]),
([Instruments], [SET]),
([Takeoff briefing], [COMPLETE]),
([Beacon, navigation, landing lights], [ON]),
([Carburetor heat], [AS REQUIRED]),
([Flaps], [0-10°]),
([Trim], [TAKEOFF]),
([Fuel valve], [BOTH]),
([Fuel quantity], [CHECK]),
([Mixture], [RICH], [Below 3000 feet]),
)
]
// -----------------------------------------------------------------------------
// Emergency Checklists (left side)
// -----------------------------------------------------------------------------
#let left_emergency_checklists = [
#checklist("Engine Failure During Takeoff Run", black, emergency: true,
([Throttle], [IDLE]),
([Brakes], [APPLY]),
([Flaps], [RETRACT]),
([Mixture], [CUT-OFF]),
([Magnetos], [OFF]),
)
// The title in the POH is "ENGINE FAILURE IMMEDIATELY AFTER TAKEOFF" but
// that didn't fit on one line so immediately was replaced with shortly.
#checklist("Engine Failure Shortly After Takeoff", black, emergency: true,
([Airspeed], align(right)[Flaps up: 65 KIAS\ Flaps down: 60 KIAS]),
([Mixture], [CUT-OFF]),
([Fuel valve], [OFF]),
([Magnetos], [OFF]),
([Flaps], [AS REQUIRED]),
([Master], [OFF]),
)
#checklist("Engine Failure During Flight", black, emergency: true,
([Airspeed], [65 KIAS]),
([Carburetor heat], [ON]),
([Fuel valve], [BOTH]),
([Mixture], [RICH]),
([Magnetos], [BOTH (or START if prop stopped)]),
([Primer], [IN and LOCKED]),
)
// POH title: EMERGENCY LANDING WITHOUT ENGINE POWER, emergency replaced
// with forced to fit on one line.
#checklist("Forced Landing Without Engine Power", black, emergency: true,
([Airspeed], align(right)[Flaps up: 65 KIAS\ Flaps down: 60 KIAS]),
([Mixture], [CUT-OFF]),
([Fuel valve], [OFF]),
([Magnetos], [OFF]),
([Flaps], [AS REQUIRED], [40° recommended]),
([Master], [OFF]),
([Doors], [UNLATCH BEFORE TOUCHDOWN]), // "prior to" -> "before" for space
([Touchdown], [SLIGHTLY TAIL LOW]),
([Brakes], [APPLY HEAVILY]),
)
// POH title: PRECAUTIONARY LANDING WITH ENGINE POWER. Removed "with engine
// power" to fit on one line.
#checklist("Precautionary Landing", black, emergency: true,
([Flaps], [20°]),
([Airspeed], [60 KIAS]),
([Selected field], [FLY OVER], [Note terrain/obstructions.
Retract flaps\ upon reaching a safe altitude and airspeed.]),
([Radios, electrical switches], [OFF]),
([Flaps], [40° (on final approach)]),
([Airspeed], [60 KIAS]),
([Master], [OFF]),
([Doors], [UNLATCH BEFORE TOUCHDOWN]), // "prior to" -> "before" for space
([Touchdown], [SLIGHTLY TAIL LOW]),
([Magnetos], [OFF]),
([Brakes], [APPLY HEAVILY]),
)
#checklist("Ditching", black, emergency: true,
([Radio], [MAYDAY on 121.5 MHz], [Give location, intentions]),
([Heavy objects], [SECURE or JETTISON]),
([Flaps], [20°-40°]),
([Power], [300 FT/MIN DESCENT AT 55 KIAS],
[If no power available, approach flaps up 65 KIAS or flaps 10° 60 KIAS]),
([Strong wind, heavy seas:\ #h(1em)LAND INTO WIND\
Light wind, heavy swells:\ #h(1em)LAND PARALLEL TO SWELLS], []),
([Doors], [UNLATCH]),
([Touchdown], [LEVEL ATTITUDE], [at established rate of descent]),
([Face], [CUSHION at touchdown with coat]),
([Airplane], [EVACUATE]),
([Life vests/raft], [INFLATE]),
)
#checklist("Engine Fire During Start On Ground", black, emergency: true,
([Cranking], [CONTINUE]),
([If engine starts:], []),
([#h(1em)Power], [1700 RPM for a few minutes]),
([#h(1em)Engine], [SHUTDOWN]),
([If engine fails to start:], []),
([#h(1em)Throttle], [FULL OPEN]),
([#h(1em)Mixture], [CUT-OFF]),
([#h(1em)Cranking], [CONTINUE for 2-3 minutes]),
([#h(1em)Fire extinguisher], [OBTAIN]),
([#h(1em)Master], [OFF]),
([#h(1em)Magnetos], [OFF]),
([#h(1em)Fuel valve], [OFF]),
([#h(1em)Fire], [EXTINGUISH],
[Using fire extinguisher, seat cushion, wool blanket, or dirt.
If practical try to remove air filter if it is ablaze.)]),
([Both cases: inspect and repair damage before conducting another flight.], []),
)
#checklist("Engine Fire in Flight", black, emergency: true,
([Mixture], [CUT-OFF]),
([Fuel valve], [OFF]),
([Master], [OFF]),
([Cabin heat & air], [OFF], [(except overhead vents)]),
([Airspeed], [100 KIAS],
[If fire is not extinguished, increase glide speed to find an airspeed
which will provide an incombustible mixture]),
([Forced Landing Without Engine Power checklist], [EXECUTE]),
)
]
// -----------------------------------------------------------------------------
// Emergency Checklists (right side)
// -----------------------------------------------------------------------------
#let right_emergency_checklists = [
#checklist("Electrical Fire in Flight", black, emergency: true,
([Master], [OFF]),
([All other switches (except magnetos)], [OFF]),
([Vents/cabin air/heat], [CLOSE]),
([Fire extinguisher], [USE]),
([If fire appears out and electrical power necessary to continue flight:], []),
([#h(1em)Master], [ON]),
([#h(1em)Circuit breakers], [CHECK], [(do not reset faulty circuit)]),
([#h(1em)Radio/electrical switches], [ON],
[One at a time with delay after each until short circuit is
localized]),
([#h(1em)Vents/cabin air/heat], [OPEN],
[(when fire is completely extinguished)]),
)
#checklist("Cabin Fire", black, emergency: true,
([Master], [OFF]),
([Vents/cabin air/heat], [CLOSED], [(to avoid drafts)]),
([Fire extinguisher], [USE],
[WARNING: After discharging extinguisher within a closed cabin,
ventilate cabin]),
([Land ASAP, inspect for damage], []),
)
#checklist("Wing Fire", black, emergency: true,
([Nav lights], [OFF]),
([Pitot heat], [OFF]),
([NOTE: Sideslip to keep flames away from fuel tanks and cabin.
Land ASAP using flaps only as required.], []),
)
#checklist("Inadventent Icing Encounter", black, emergency: true,
([Pitot heat], [ON]),
([Turn back or change altitude to obtain an OAT less conducive to icing.], []),
([Cabin heat], [FULL ON]),
([Defroster], [OPEN]),
([Cabin air], [ADJUST], [Maximize defroster heat and airflow]),
([Throttle], [OPEN]),
([Carburetor and air filter icing], [MONITOR],
[Apply carb heat as required, lean mixture for maximum RPM if used continuously]),
([Land], [NEAREST AIRPORT], [With very rapid ice build-up, select suitable
off-airport landing site]),
([With ≥ 1/4 inch ice on the leading edges, prepare for significantly higher
stall speed], []),
([Flaps], [LEAVE RETRACTED]),
([Open left window and scrape ice from windshield, if necessary for visibility], []),
([Forward slip if necessary for visibility], []),
([Approach speed], [65-75 KIAS], [Depending on level of accumulation]),
([Landing], [Perform in level attitude]),
)
// POH title: STATIC SOURCE BLOCKAGE (Erroneous Instrument Reading
// Suspected). Removed "(Erroneous Instrument Reading Suspected)" to fit on
// one line.
#checklist("Static Source Blockage", black, emergency: true,
([Alternate static source valve], [PULL ON]),
([Airspeed], [Use calibration table\ in POH section 5]),
)
#checklist("Landing With a Flat Main Tire", black, emergency: true,
([Approach], [NORMAL]),
([Touchdown], [GOOD TIRE FIRST], [Hold airplane off flat tire as long as possible]),
)
#checklist("Over-Voltage Light Illuminates", black, emergency: true,
([Master], [OFF (both sides)]),
([Master], [ON]),
([If over-voltage light illuminates again:], []),
([#h(1em)Flight], [TERMINATE ASAP]),
)
#checklist("Ammeter Shows Discharge", black, emergency: true,
([Alternator], [OFF]),
([Nonessential electrical equipment], [OFF]),
([Flight], [TERMINATE as soon as practical]),
)
]
// -----------------------------------------------------------------------------
// Page definitions and formatting
// -----------------------------------------------------------------------------
// This is set to the minimum margin size that Ryan V's printer can support
// (experimentally-determined).
#let margins = 6mm
#page(flipped: true, margin: margins, paper: "us-letter")[
// page() supports multiple columns, but does not support setting the gutter
// width for multiple columns, so we call columns() ourselves instead.
#columns(2, gutter: 2*margins)[
= Ground Checklists and Information #h(1fr) N73146
#columns(2)[
#set text(9.4pt)
#ground_checklists_and_info
]
#v(1fr)
= Version 1 #h(1fr) #include "signature.typ"
#colbreak()
= Operating Checklists #h(1fr) N73146
#columns(2)[
#set text(9pt)
#operating_checklists
]
]
]
#page(flipped: true, margin: margins, paper: "us-letter")[
#columns(2, gutter: 2*margins)[
#box(fill: red, width: 100%,
align(center, box(fill: white, outset: 1em)[= Emergency Checklists]))
#v(-.5em)
#columns(2, gutter: 2mm)[
#set text(9pt)
#left_emergency_checklists
]
#colbreak()
#box(fill: red, width: 100%,
align(center, box(fill: white, outset: 1em)[= Emergency Checklists]))
#v(-.5em)
#columns(2, gutter: 2mm)[
#set text(9pt)
#right_emergency_checklists
]
]
]
|
https://github.com/fuchs-fabian/typst-template-aio-studi-and-thesis | https://raw.githubusercontent.com/fuchs-fabian/typst-template-aio-studi-and-thesis/main/src/declaration_on_the_final_thesis.typ | typst | MIT License | // Translated with: https://www.deepl.com
#let get-declaration-on-the-final-thesis(
lang: "de",
legal-reference: none,
thesis-name: none,
consent-to-publication-in-the-library: none, // true, false
genitive-of-university: none
) = [
#import "utils.typ": *
#import "dictionary.typ": txt-declaration-on-the-final-thesis, txt-declaration-on-the-final-thesis-first-part
#let get-placeholder(it) = { text(fill: red)[#todo(it)] }
#set text(size: 10pt)
#set heading(numbering: none)
#heading(outlined: false, txt-declaration-on-the-final-thesis)
#txt-declaration-on-the-final-thesis-first-part
#v(1fr)
#if lang == "de" [
Mir ist bewusst, dass Täuschungen nach der für mich gültigen Studien- und Prüfungsordnung / nach
#if is-not-none-or-empty(legal-reference) [ #legal-reference ] else [ #get-placeholder[Rechtsbezug] ]
geahndet werden.
] else if lang == "en" [
I am aware that cheating will be penalised according to the study and examination regulations applicable to me / according to
#if is-not-none-or-empty(legal-reference) [ #legal-reference. ] else [ #get-placeholder[legal reference]. ]
]
#v(1fr)
#if lang == "de" [
Die Zustimmung zur elektronischen Plagiatsprüfung wird erteilt.
] else if lang == "en" [
Consent to the electronic plagiarism check is granted.
]
#signing()
#v(2fr)
#if lang == "de" [
Der Veröffentlichung der
#if is-not-none-or-empty(thesis-name) [ #thesis-name ] else [ #get-placeholder[Art der Abschlussarbeit] ]
in der Bibliothek der
#if is-not-none-or-empty(genitive-of-university) [ #genitive-of-university ] else [ #get-placeholder[Genitiv der Universität] ]
wird
#if is-not-none-or-empty(consent-to-publication-in-the-library) {
if consent-to-publication-in-the-library [] else [nicht]
} else [ #get-placeholder[nicht] ]
zugestimmt.
] else if lang == "en" [
The publication of the
#if is-not-none-or-empty(thesis-name) [ #thesis-name ] else [ #get-placeholder[thesis name] ]
in the library of
#if is-not-none-or-empty(genitive-of-university) [ #genitive-of-university ] else [ #get-placeholder[genitive of university] ]
is
#if is-not-none-or-empty(consent-to-publication-in-the-library) {
if consent-to-publication-in-the-library [] else [nicht]
} else [ #get-placeholder[not] ]
approved.
]
#signing()
] |
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/seminars/2024-10-14.typ | typst | = Задачи
== Задача 1
$ F(x) = cases(
0.0 "," & x<=3,
0.2 "," & -3<x<=1,
0.4 "," & 1<x<=2,
1.0 "," & x>2,
) $
#figure(
caption: [Ряд распределения],
table(
columns: 4,
$x$, $-3$, $1$, $2$,
$p$, $0.2$, $0.2$, $0.2$
)
)
== Задача 2
#figure(
caption: [ряд распределения],
table(
columns: 5,
$x$, $0$, $1$, $2$, $3$,
$P$, $C^0_7 dot C^3_8 / C^3_15 = 56/455$, $... = 196/455$, $... = 168/455$, $... = 35/455$
)
)
$ E(x) = 0 dot 56/455 + 1 dot 196/455 + 2 dot 168/455 + 3 dot 35/455 = 1.4 $
$ D(x) = 3 dot 7 / 15 dot (1 - 7 / 15) dot (1 - 7-1 / 15-1) = 0.64 $
Общий вид (напоминание):
$ p = C^m_M dot C^n-m_N-m / C^n_N $
$ M(x) = n dot M / N $
$ D(x) = n dot M / N dot (1 - M / N) dot (1 - n-1/N-1) $
== Задача 3
$N = 7, M = 4, n = 4$
#figure(
caption: [ряд распределения],
table(
columns: 5,
$x$, $1$, $2$, $3$, $4$,
$P$, $4/35$, $18/35$, $12/35$, $1/35$
)
)
ВАЖНО: здесь нельзя использовать формулу гипергеометрической вероятности, тк
наше распределение начинается с 1 (не с 0)
$ M = 1 dot 4 / 35 + 2 dot 18 / 35 + 3 dot 12 / 35 + 4 dot 1 / 35 = 2.217 $
$ D = 0.49 $
== Задача 4
$ P(x > 3) = 1 / 3 $
$ F_x(3) - ? $
$ P(x<3) + P(x=3) + P(x>3) = 1 $
$ F_x (3) = P(x<3) = 1 - P(x>3) = 2/3 $
== Задача
$ p = 0.8 $
#figure(
caption: [ряд распределения],
table(
columns: 3,
$x$, $2$, $3$,
$P$, $p$, $1-p$
)
)
$ M(x) = 2 p + 3 (1 - p) = 2.2 $
TODO: complete the graph
$ M(x^2) =4 dot 0.8 + 9 dot 0.2 = 5 $
$ D(x) = M(x^2) - (M(x))^2 = 5 - 4.84 = 0.16 $
$ sigma(x) = 0.4 $
== Задача
#figure(table(
columns: 4,
[], [Вклад], [Годовых], [Вероятность банкротства],
$A$, $20$, $40%$, $0.3$,
$B$, $18$, $30%$, $0.2$
))
$X$ --- сумма вклада
Через год:
$x_1 = 0$ --- оба банкрота
$x_2 =28$ --- банкрот $B$
$x_3 = 23.4$ --- банкрот $A$
$x_4 = 51.4$ --- нет банкрота
#figure(table(
columns: 5,
$X$, $0$, $23.4$, $28$, $51.4$,
$p$, $0.05$, $0.24$, $0.14$, $0.56$
))
$ M(x) = 38.32 $
$ M(x^2) = 1720.672 $
$ D(x) = 252.2496 $
== Задача
$ N = 2000, p = 0.001 $
$ "П"(a) = "П"(1) $
$ P(x = 2) = 1/(2! e) = 0.184 $
$ P(x >= 2) = 1 - P(0) - P(1) = 1 - 1/e - 1/e = 0.264 $
== Задача
$ N = 1000 $ --- всего деталей
$ n > 2 $ --- система работает, пока
$ q = 0.998 $ --- безотказная работа одной детали
$ p = 0.002 $
$ x ~ "П"(2) $
$ E(x) = ... $
|
|
https://github.com/exusiaiwei/quarto-ilm | https://raw.githubusercontent.com/exusiaiwei/quarto-ilm/main/_extensions/ilm/typst-template.typ | typst | MIT License | // Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
#let std-smallcaps = smallcaps
#let std-upper = upper
// Overwrite the default `smallcaps` and `upper` functions with increased spacing between
// characters. Default tracking is 0pt.
#let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body))
#let upper(body) = std-upper(text(tracking: 0.6pt, body))
// Colors used across the template.
#let stroke-color = luma(200)
#let fill-color = luma(250)
#let quarto-ilm(
title: none,
subtitle: none,
short-title: none,
author: none,
authors: (),
affiliations: (),
date: none,
date-format: "[month repr:long] [day padding:zero], [year repr:full]",
abstract: none,
keywords: (),
bibliography-file: none,
bibliography-style: none,
paper-size: "a4",
preface: none,
table-of-contents: false,
chapter-pagebreak: true,
external-link-circle: true,
figure-index: (enabled: false, title: "List of Figures"),
table-index: (enabled: false, title: "List of Tables"),
listing-index: (enabled: false, title: "List of Listings"),
body,
) = {
// Set document metadata and global styles
set document(title: title, author: author)
set text(font: ("Libertinus Serif", "Linux Libertine"), size: 12pt)
set page(
paper: paper-size,
margin: (bottom: 1.75cm, top: 2.25cm),
footer: context {
let i = counter(page).at(here()).first()
let is-odd = calc.odd(i)
let aln = if is-odd { right } else { left }
let target = heading.where(level: 1)
if query(target).any(it => it.location().page() == i) {
return align(aln)[#i]
}
let before = query(target.before(here()))
if before.len() > 0 {
let current = before.last()
let gap = 1.75em
let chapter = upper(text(size: 0.68em, current.body))
if current.numbering != none {
if is-odd {
align(aln)[#chapter #h(gap) #i]
} else {
align(aln)[#i #h(gap) #chapter]
}
}
}
},
)
set par(leading: 0.7em, justify: true, linebreaks: "optimized")
set heading(numbering: "1.")
// Configure raw text display
show raw: set text(font: ("Iosevka", "Fira Mono"), size: 9pt)
// Configure paragraph properties
show par: set block(spacing: 1.35em)
// Add vertical space after headings
show heading: it => {
it
v(2%, weak: true)
}
// Do not hyphenate headings
show heading: set text(hyphenate: false)
show link: it => {
it
// Workaround for ctheorems package so that its labels keep the default link styling.
if external-link-circle and type(it.dest) != label {
sym.wj
h(1.6pt)
sym.wj
super(box(height: 3.8pt, circle(radius: 1.2pt, stroke: 0.7pt + rgb("#993333"))))
}
}
// Display preface as the second page.
if preface != none {
page(preface)
}
// Configure equation numbering
set math.equation(numbering: "(1)")
// Display inline code in a small box that retains the correct baseline.
show raw.where(block: false): box.with(
fill: fill-color.darken(2%),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code with padding
show raw.where(block: true): block.with(
inset: (x: 5pt),
)
// Table styles
show figure.where(kind: table): set block(breakable: true)
set table(
inset: 7pt,
stroke: (0.5pt + stroke-color)
)
show table.cell.where(y: 0): smallcaps
// Start document content
{
// Cover page
page(align(left + horizon, block(width: 90%)[
#let v-space = v(2em, weak: true)
#text(3em)[*#title*]
#v-space
#text(1.6em, author)
#if abstract != none {
v-space
block(width: 80%)[
#par(leading: 0.78em, justify: true, linebreaks: "optimized", abstract)
]
}
#if date != none {
v-space
text(date)
}
]))
// Preface
if preface != none {
preface
}
// Table of contents
if table-of-contents {
outline(depth: 3, indent: true)
}
// Main content
show heading.where(level: 1): it => {
if chapter-pagebreak { pagebreak(weak: true) }
it
}
body
// Bibliography
if bibliography != none {
show std-bibliography: set text(0.85em)
// Use default paragraph properties for bibliography.
show std-bibliography: set par(leading: 0.65em, justify: false, linebreaks: auto)
}
// Indices
if figure-index.enabled or table-index.enabled or listing-index.enabled {
pagebreak()
show outline: set heading(outlined: true)
if figure-index.enabled { outline(title: figure-index.title, target: figure.where(kind: image)) }
if table-index.enabled { outline(title: table-index.title, target: figure.where(kind: table)) }
if listing-index.enabled { outline(title: listing-index.title, target: figure.where(kind: raw)) }
}
}
}
// This function formats its `body` (content) into a blockquote.
#let blockquote(body) = {
block(
width: 100%,
fill: fill-color,
inset: 2em,
stroke: (y: 0.5pt + stroke-color),
body
)
} |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.node/npm/darwin-x64/README.md | markdown | Apache License 2.0 | # `@myriaddreamin/typst-ts-node-compiler-darwin-x64`
This is the **x86_64-apple-darwin** binary for `@myriaddreamin/typst-ts-node-compiler`
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11150.typ | typst | Apache License 2.0 | #let data = (
("MAHAJANI LETTER A", "Lo", 0),
("MAHAJANI LETTER I", "Lo", 0),
("MAHAJANI LETTER U", "Lo", 0),
("MAHAJANI LETTER E", "Lo", 0),
("MAHAJANI LETTER O", "Lo", 0),
("MAHAJANI LETTER KA", "Lo", 0),
("MAHAJANI LETTER KHA", "Lo", 0),
("MAHAJANI LETTER GA", "Lo", 0),
("MAHAJANI LETTER GHA", "Lo", 0),
("MAHAJANI LETTER CA", "Lo", 0),
("MAHAJANI LETTER CHA", "Lo", 0),
("MAHAJANI LETTER JA", "Lo", 0),
("MAHAJANI LETTER JHA", "Lo", 0),
("MAHAJANI LETTER NYA", "Lo", 0),
("MAHAJANI LETTER TTA", "Lo", 0),
("MAHAJANI LETTER TTHA", "Lo", 0),
("MAHAJANI LETTER DDA", "Lo", 0),
("MAHAJANI LETTER DDHA", "Lo", 0),
("MAHAJANI LETTER NNA", "Lo", 0),
("MAHAJANI LETTER TA", "Lo", 0),
("MAHAJANI LETTER THA", "Lo", 0),
("MAHAJANI LETTER DA", "Lo", 0),
("MAHAJANI LETTER DHA", "Lo", 0),
("MAHAJANI LETTER NA", "Lo", 0),
("MAHAJANI LETTER PA", "Lo", 0),
("MAHAJANI LETTER PHA", "Lo", 0),
("MAHAJANI LETTER BA", "Lo", 0),
("MAHAJANI LETTER BHA", "Lo", 0),
("MAHAJANI LETTER MA", "Lo", 0),
("MAHAJANI LETTER RA", "Lo", 0),
("MAHAJANI LETTER LA", "Lo", 0),
("MAHAJANI LETTER VA", "Lo", 0),
("MAHAJANI LETTER SA", "Lo", 0),
("MAHAJANI LETTER HA", "Lo", 0),
("MAHAJANI LETTER RRA", "Lo", 0),
("MAHAJANI SIGN NUKTA", "Mn", 7),
("MAHAJANI ABBREVIATION SIGN", "Po", 0),
("MAHAJANI SECTION MARK", "Po", 0),
("MAHAJANI LIGATURE SHRI", "Lo", 0),
)
|
https://github.com/Coyenn/thesis-template | https://raw.githubusercontent.com/Coyenn/thesis-template/main/README.md | markdown | # Thesis Template
This is a declarative thesis template based on [typst](https://typst.app) and [d2](https://d2lang.com) that compiles to a PDF file.
## Quickstart
1. Install [typst](https://typst.app), [d2](https://d2lang.com), and [entr](https://github.com/eradman/entr).
2. Clone this repository. (git clone https://github.com/Coyenn/thesis-template.git)
3. Run `./project watch` to compile the project in watch mode.
|
|
https://github.com/ParaN3xus/numblex | https://raw.githubusercontent.com/ParaN3xus/numblex/main/lib/numblex.typ | typst | MIT License | #import "./parser.typ": parser
#import "./model.typ": to_numbering
/// Numblex main function
#let numblex(s, ..options) = {
return to_numbering(..parser(s))
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.