repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/hitszosa/universal-hit-thesis | https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/utils/states.typ | typst | MIT License | #import "../config/constants.typ": current-date
#let thesis-info-state = state(
"thesis-info",
(
title-cn: "",
title-en: "",
author: "▢▢▢",
student-id: "▢▢▢▢▢▢▢▢▢▢",
supervisor: "▢▢▢ 教授",
profession: "▢▢▢ 专业",
collage: "▢▢▢ 学院",
institute: "哈尔滨工业大学",
year: current-date.year(),
month: current-date.month(),
day: current-date.day(),
),
)
#let bibliography-state = state("bibliography") |
https://github.com/KhalilAMARDJIA/booker | https://raw.githubusercontent.com/KhalilAMARDJIA/booker/master/_extensions/booker/typst-show.typ | typst | // Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: doc => book(
$if(title)$
title: [$title$],
$endif$
$if(author)$
author: [$author$],
$endif$
$if(date)$
date: [$date$],
$endif$
$if(lang)$
lang: "$lang$",
$endif$
$if(region)$
region: "$region$",
$endif$
$if(abstract)$
abstract: [$abstract$],
abstract-title: "$labels.abstract$",
$endif$
$if(margin)$
margin: ($for(margin/pairs)$$margin.key$: $margin.value$,$endfor$),
$endif$
$if(papersize)$
paper: "$papersize$",
$endif$
$if(mainfont)$
font: ("$mainfont$",),
$endif$
$if(fontsize)$
fontsize: $fontsize$,
$endif$
$if(section-numbering)$
sectionnumbering: "$section-numbering$",
$endif$
doc,
)
|
|
https://github.com/curvenote-templates/ncssm | https://raw.githubusercontent.com/curvenote-templates/ncssm/main/template.typ | typst | MIT License | #import "ncssm.typ": *
[-IMPORTS-]
#let tableStyle = (
map-cells: cell => {
if (cell.y == 0) {
return (..cell, content: strong(text(cell.content, 9pt)))
}
(..cell, content: text(cell.content, 9pt))
},
auto-vlines: false,
map-hlines: line => {
if (line.y == 0 or line.y == 1) {
line.stroke = gray + 1pt;
} else {
line.stroke = 0pt;
}
return line
},
)
#show: template.with(
frontmatter: (
title: "[-doc.title-]",
abstract: [
[-parts.abstract-]
],
[# if doc.subtitle #]
subtitle: "[-doc.subtitle-]",
[# endif #]
[# if doc.short_title #]
short-title: "[-doc.short_title-]",
[# endif #]
[# if doc.open_access !== undefined #]
open-access: [-doc.open_access-],
[# endif #]
[# if doc.github !== undefined #]
github: "[-doc.github-]",
[# endif #]
[# if doc.doi #]
doi: "[-doc.doi-]",
[# endif #]
[# if doc.date #]
date: datetime(
year: [-doc.date.year-],
month: [-doc.date.month-],
day: [-doc.date.day-],
),
[# endif #]
[# if doc.keywords #]
keywords: (
[#- for keyword in doc.keywords -#]"[-keyword-]",[#- endfor -#]
),
[# endif #]
authors: (
[# for author in doc.authors #]
(
name: "[-author.name-]",
[# if author.orcid #]
orcid: "[-author.orcid-]",
[# endif #]
[# if author.email #]
email: "[-author.email-]",
[# endif #]
[# if author.affiliations #]
affiliations: ([#- for aff in author.affiliations -#]"[-aff.index-]"[#- if not loop.last -#],[#- endif -#][#- endfor -#]),
[# endif #]
),
[# endfor #]
),
affiliations: (
[# for aff in doc.affiliations #]
(
id: "[-aff.index-]",
name: "[-aff.name-]",
[# if aff.ror #]
ror: "[-aff.ror-]",
[# endif #]
),
[# endfor #]
),
[# if doc.license.content #]
license: (id: "[-doc.license.content.id-]", name: "[-doc.license.content.name-]", url: "[-doc.license.content.url-]"),
[# endif #]
),
[# if doc.biblio.first_page #]
page-start: [-doc.biblio.first_page-]
[# endif #]
)
[# if parts.first_page #]
[-parts.first_page-]
// This may be moved below the first paragraph to start columns later
#set page(columns: 2, margin: (x: 1.5cm, y: 2cm),)
[# endif #]
[-CONTENT-]
[# if doc.bibtex #]
#bibliography("[-doc.bibtex-]", title: text(10pt, "References"), style: "ieee")
[# endif #]
|
https://github.com/saurabtharu/Internship-repo | https://raw.githubusercontent.com/saurabtharu/Internship-repo/main/Internship%20Report%20-%20typst/chapters/0-cover.typ | typst | #import "../template.typ": *
#align(center,
image("../images/TU Logo.svg",height: 19%)
)
#align(center, text(16pt)[
*Tribhuvan University \
Institute of Science and Technology \ \
Asian College of Higher Studies \
Ekantakuna, Lalitpur, Nepal* \ \
])
#align(center, text(14pt)[
*An Internship Report \
On \
"DevOps Engineer " \
At \
F1Soft International Pvt. Ltd.*
])
#align(center, text(14pt)[
#boldText[
\
*Submitted by \
#person[<NAME> (T.U. Exam Roll No. 24256/076)]* \
]
])
#align(center, text(14pt)[
\
*An Internship Report Submitted in partial fulfillment of the requirement of
Bachelor of Science in Computer Science & Information Technology \
(BSc.CSIT) 8th Semester of Tribhuvan University, Nepal*
\ \
*June, 2024*
])
#pagebreak() |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/plotst/0.1.0/README.md | markdown | Apache License 2.0 | # A plotting library for Typst
A Typst library for drawing graphs and plots.
Made by Gewi413 and Pegacraffft
## Currently supported graphs
- Scatter plots
- Graph charts
- Histograms
- Bar charts
- Pie charts
- Overlaying plots/charts
(more to come)
## How to use
To use the package you can import it through this command `import "@preview/plotst:0.1.0": *`.
The documentation is found in the [Docs.pdf](https://github.com/Pegacraft/typst-plotting/blob/master/docs/Docs.pdf) file. It contains all functions necessary to use this library. It also includes a tutorial to create every available plot under their respective render methods.
If you need some example code, check out [main.typ](https://github.com/Pegacraft/typst-plotting/blob/master/example/main.typ). It also includes a [compiled version](https://github.com/Pegacraft/typst-plotting/blob/master/example/Plotting.pdf) of the current [main.typ](https://github.com/Pegacraft/typst-plotting/blob/master/example/main.typ)
## Examples:
All these images were created using the [main.typ](https://github.com/Pegacraft/typst-plotting/blob/master/example/main.typ)
### Scatter plots
```js
// Plot 1:
// The data to be displayed
let gender_data = (
("w", 1), ("w", 3), ("w", 5), ("w", 4), ("m", 2), ("m", 2),
("m", 4), ("m", 6), ("d", 1), ("d", 9), ("d", 5), ("d", 8),
("d", 3), ("d", 1), (0, 11)
)
// Create the axes used for the chart
let y_axis = axis(min: 0, max: 11, step: 1, location: "left", helper_lines: true, invert_markings: false, title: "foo")
let x_axis = axis(values: ("", "m", "w", "d"), location: "bottom", helper_lines: true, invert_markings: false, title: "Gender")
// Combine the axes and the data and feed it to the plot render function.
let pl = plot(data: gender_data, axes: (x_axis, y_axis))
scatter_plot(pl, (100%,50%))
// Plot 2:
// Same as above
let data = (
(0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false)
let pl = plot(data: data, axes: (x_axis, y_axis))
scatter_plot(pl, (100%, 25%))
```

### Graph charts
```js
// The data to be displayed
let data = (
(0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
// Create the axes used for the chart
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false)
// 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 caption and rounding")
```

### Histograms
```js
// Plot 1:
// The data to be displayed
let data = (
18000, 18000, 18000, 18000, 18000, 18000, 18000, 18000,
18000, 18000, 28000, 28000, 28000, 28000, 28000, 28000,
28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000,
28000, 28000, 28000, 28000, 28000, 28000, 28000, 28000,
35000, 46000, 75000, 95000
)
// Classify the data
let classes = class_generator(10000, 50000, 4)
classes.push(class(50000, 100000))
classes = classify(data, classes)
// Create the axes used for the chart
let x_axis = axis(min: 0, max: 100000, step: 10000, location: "bottom")
let y_axis = axis(min: 0, max: 31, step: 5, location: "left", helper_lines: true)
// Combine the axes and the data and feed it to the plot render function.
let pl = plot(data: classes, axes: (x_axis, y_axis))
histogram(pl, (100%, 40%), stroke: black, fill: (purple, blue, red, green, yellow))
// Plot 2:
// Create the different classes
let classes = ()
classes.push(class(11, 13))
classes.push(class(13, 15))
classes.push(class(1, 6))
classes.push(class(6, 11))
classes.push(class(15, 30))
// Define the data to map
let data = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17))
// Create the axes
let x_axis = axis(min: 0, max: 31, step: 1, location: "bottom", show_markings: false)
let y_axis = axis(min: 0, max: 41, step: 5, location: "left", helper_lines: true)
// Classify the data
classes = classify(data, classes)
// Combine the axes and the data and feed it to the plot render function.
let pl = plot(axes: (x_axis, y_axis), data: classes)
histogram(pl, (100%, 40%))
```

### Bar charts
```js
// Plot 1:
// The data to be displayed
let data = ((10, "Monday"), (5, "Tuesday"), (15, "Wednesday"), (9, "Thursday"), (11, "Friday"))
// Create the necessary axes
let y_axis = axis(values: ("", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), location: "left", show_markings: true)
let x_axis = axis(min: 0, max: 20, step: 2, location: "bottom", helper_lines: true)
// Combine the axes and the data and feed it to the plot render function.
let pl = plot(axes: (x_axis, y_axis), data: data)
bar_chart(pl, (100%, 33%), fill: (purple, blue, red, green, yellow), bar_width: 70%, rotated: true)
// Plot 2:
// Same as above, but with numbers as data
let data_2 = ((20, 2), (30, 7), (16, 12), (40, 13), (5, 17))
let y_axis_2 = axis(min: 0, max: 41, step: 5, location: "left", show_markings: true, helper_lines: true)
let x_axis_2 = axis(min: 0, max: 21, step: 1, location: "bottom")
let pl_2 = plot(axes: (x_axis_2, y_axis_2), data: data_2)
bar_chart(pl_2, (100%, 60%), bar_width: 100%)
```

### Pie charts
```js
show: r => columns(2, r)
// create the sample data
let data = ((10, "Male"), (20, "Female"), (15, "Divers"), (2, "Other")
// Skip the axis step, as no axes are needed
// Put the data into a plot
let p = plot(data: data)
// Display the pie_charts in all different display ways
pie_chart(p, (100%, 20%), display_style: "legend-inside-chart")
pie_chart(p, (100%, 20%), display_style: "hor-chart-legend")
pie_chart(p, (100%, 20%), display_style: "hor-legend-chart")
pie_chart(p, (100%, 20%), display_style: "vert-chart-legend")
pie_chart(p, (100%, 20%), display_style: "vert-legend-chart")
```

**Overlayed Graphs**
```js
// Create the data for the two plots to overlay
let data_scatter = (
(0, 0), (2, 2), (3, 0), (4, 4), (5, 7), (6, 6), (7, 9), (8, 5), (9, 9), (10, 1)
)
let data_graph = (
(0, 3), (1, 5), (2, 1), (3, 7), (4, 3), (5, 5), (6, 7),(7, 4),(11, 6)
)
// Create the axes for the overlay plot
let x_axis = axis(min: 0, max: 11, step: 2, location: "bottom")
let y_axis = axis(min: 0, max: 11, step: 2, location: "left", helper_lines: false)
// create a plot for each individual plot type and save the render call
let pl_scatter = plot(data: data_scatter, axes: (x_axis, y_axis))
let scatter_display = scatter_plot(pl_scatter, (100%, 25%), stroke: red)
let pl_graph = plot(data: data_graph, axes: (x_axis, y_axis))
let graph_display = graph_plot(pl_graph, (100%, 25%), stroke: blue)
// overlay the plots using the overlay function
overlay((scatter_display, graph_display), (100%, 25%))
```

|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-00.typ | typst | Other | // Ref: true
#set page(width: 150pt)
// Empty.
#()
// Not an array, just a parenthesized expression.
#(1)
// One item and trailing comma.
#(-1,)
// No trailing comma.
#(true, false)
// Multiple lines and items and trailing comma.
#("1"
, rgb("002")
,)
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/print-unity-mantissa/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
#num(1, e: 4)
#num(1, e: 4, print-unity-mantissa: false) |
https://github.com/k0tran/cont_labs | https://raw.githubusercontent.com/k0tran/cont_labs/master/reports/lab2.typ | typst | #import "template.typ": *
#show: lab.with(n: 2)
#align(center)[#text(size: 17pt)[*Предисловие*]]
Перед началом хода лабораторной работы стоит сказать несколько слов про её предыдущую версию. Дело в том, что вся работа уже была выполнена за исключением одной небольшой детали -- использовались статичные айпишники вида `192.168.56.X` вместо `172.20.0.X`.
При попытке установить необходимый адрес выводилась следующая ошибка:
#pic(img: "lab2/vbox_error_1.png")[Ошибка использования адреса из запрещенного диапазона]
Немного погуглив, я нашел решение:
#pic(img: "lab2/vbox_error_2.png")[Модифицированный `/etc/vbox/networks.conf`]
После которого появилась новая ошибка:
#pic(img: "lab2/vbox_error_3.png")[Ошибка VBoxManage E_ACCESSDENIED]
При поиске решения для этой ошибки я нашел (ссылки встроены):
- #link("https://stackoverflow.com/questions/69728426/e-accessdenied-when-creating-a-host-only-interface-on-virtualbox-via-vagrant")[stackoverflow];
- #link("https://www.virtualbox.org/ticket/20626")[тикет на virtualbox.org]
На данных ресурсах указано два способа решения, один из которых уже был применен (модификация `/etc/vbox/networks.conf`), а другой заключался в использовании `VirtualBox 6.1.26` или более ранней версии (У меня стоял `VirtualBox 7.X`).
Однако, при установке `VirtualBox 6.1` (пакет из AUR) было обнаружено, что для его работы требуются старые модули ядра (`linuxX-virtualbox-host-modules`). При этом просто старые ядра не работали, необходимы были именно старые модули (проверял 419, 515, 61), которых в свободном доступе не было! (в отличии от того же `Arch`; Модули ядра `Arch`'a не подошли).
Соответственно из этой ситуации я вижу три выхода:
- использовать виртуалку в виртуалке (внешнаяя 7.X, внутренняя 6.1);
- использовать Windows 10, которая стоит у меня второй системой;
- установить на рабочую машину совместимую с VirtualBox 6.1 систему (третьей).
Первый вариант отметается ввиду возможных сложностей с настройкой (надо разрешить подобного рода развертывание) и сильных проблем с производительностью. Второй вариант тоже может быть проблемным из-за особенностей ОС Windows. Третий вариант выглядит труднозатратным, однако руководствуясь опытом установки различных дистрибутивов я посчитал его самым простым для меня. Поэтому был установлен xfce4 Debian 12:
#pic(img: "lab2/sysinfo_1.png")[Запуск `neofetch`]
Установленные версии VirtualBox и Vagrant:
#pic(img: "lab2/sysinfo_2.png")[Версии VirtualBox и Vagrant]
Однако позже я узнал что скачал слишком старую версию `6.1` (небходима не позднее `6.1.26`). А эта версия в свою очередь не поддерживала Debian 12, поэтому был установлен Debian 11 и установлена "правильная" версия VirtualBox:
#pic(img: "lab2/sysinfo_3.png")[Debian 11]
#pagebreak()
= Vagrant disk
== Подготовительные работы
Инициализация виртуальной машины:
#pic(img: "lab2/vagrant_init.png")[Инициализация виртуальная машины]
Включение функиции управления дисками:
#pic(img: "lab2/vagrant_disks_on.png")[Включение функции управления дисками]
Так же отключаем проверку обновлений. Для этого нужно раскомментировать следующую строку:
#pic(img: "lab2/vagrant_updates_off.png")[Настройка отключения обновлений]
== Работа с дисками
Для начала имеем следующую структуру:
#pic(img: "lab2/vagrant_disks_1.png")[Дисковое пространство виртуальной машины]
Здесь видно, что основной диск виртуальной машины (`sda1`) занимает 40 гигабайт. Для его увеличения на 20 гигабайт необходимо установить новый раздел диска 60 гигабайт. Так же добавляем подключение дополнительного жесткого диска размером 10 гигабайт (с именем `extra`):
#pic(img: "lab2/vagrant_disks_2.png")[Конфигурация дисков виртуальной машины]
Далее перезагружаем виртуальную машину и видим следующий результат:
#pic(img: "lab2/vagrant_disks_3.png")[Дисковое пространство виртуальной машины после изменений]
На рисунке выше видно, что основной диск (`sda1`) теперь занимает 60 гигабайт, а так же появился дополнительный диск на 10 гигабайт (`sdc`)
#pagebreak()
= Vagrant network
== Vagrantfile
Приватная сеть со статичным ip адресом из диапазона `172.20.0.0/24` (был выбран `172.20.0.5`):
#pic(img: "lab2/vagrant_net_1.png")[Настройка приватной сети]
Публичная сеть:
#pic(img: "lab2/vagrant_net_2.png")[Настройка публичной сети]
Сетевое имя хоста:
#pic(img: "lab2/vagrant_net_3.png")[Задание сетевого имени хоста]
Пробрасываение 22-го порта виртуальной машины на 3333 порт хоста:
#pic(img: "lab2/vagrant_net_4.png")[Пробрасывание]
== Проверка всех измененных параметров
Проверяем что имя виртуальной машины поменялось на `vm1` и была добавлена запись в `/etc/hosts`:
#pic(img: "lab2/vagrant_net_5.png")[Демонстрация настроек имени хоста]
Рассмотрим адаптеры виртуальной машины:
#pic(img: "lab2/vagrant_net_6.png")[Адаптеры виртуальной машины]
Здесь `enp0s9` имеет публичный ip `192.168.31.209`, а `enp0s8` имеет статический адрес `172.20.0.5`.
Проверка прокинутого порта при помощи сканера nmap:
#pic(img: "lab2/vagrant_net_6.png")[Результаты сканирования nmap]
#pagebreak()
= Vagrant provision
== Установка
Для начала выделим скрипт установки (из прошлой лабораторной) в отдельный скрипт:
#pic(img: "lab2/vagrant_prov_1.png")[Скрипт установки docker engine]
Затем необходимо добавить этот скрипт на этап provision:
#pic(img: "lab2/vagrant_prov_2.png")[Сам скрипт]
== Подтверждение установки
#pic(img: "lab2/vagrant_prov_3.png")[Запуск `docker run hello-world`]
#pagebreak()
= Vagrant multi-machine
В первую очередь скрипты для provision были выделены в отдельные переменные:
#pic(img: "lab2/vagrant_vm_cfg_1.png")[Скрипты]
Затем используем их при конфигурации трех виртуальных машин:
#pic(img: "lab2/vagrant_vm_cfg_2.png")[Конфигурация vm1, vm2 и vm3]
Стоит отметить, что в задании проверка функционала не заявлена обязательной. Однако для себя я запустил пару команд и, например, убедился что пользователь присутствует в системе (при помощи `id`). Так же за него можно залогинится `sudo login adam`, предварительно установив пароль `sudo passwd adam` |
|
https://github.com/tfachmann/unveiling-the-dark-arts-of-rotations | https://raw.githubusercontent.com/tfachmann/unveiling-the-dark-arts-of-rotations/main/tfachmann-theme.typ | typst | #import "@preview/polylux:0.3.1": *
#import logic
#let simple-footer = state("simple-footer", [])
#let simple-theme(
aspect-ratio: "16-9",
footer: [],
background: white,
foreground: black,
body
) = {
set page(
paper: "presentation-" + aspect-ratio,
margin: 2em,
header: none,
footer: none,
fill: background,
)
set text(fill: foreground, size: 25pt)
show footnote.entry: set text(size: .6em)
show heading.where(level: 2): set block(below: 2em)
set outline(target: heading.where(level: 1), title: none, fill: none)
show outline.entry: it => it.body
show outline: it => block(inset: (x: 1em), it)
simple-footer.update(footer)
body
}
#let centered-slide(body) = {
logic.polylux-slide(align(center + horizon, body))
}
#let title-slide(body) = {
set heading(outlined: false)
centered-slide(body)
}
#let focus-slide(background: aqua.darken(50%), foreground: white, body) = {
set page(fill: background)
set text(fill: foreground, size: 1.5em)
logic.polylux-slide(align(center + horizon, body))
}
#let slide(body) = {
let deco-format(it) = text(size: .6em, fill: gray, it)
set page(
// header: locate( loc => {
// let sections = query(heading.where(level: 1, outlined: true).before(loc), loc)
// if sections == () [] else { deco-format(sections.last().body) }
// }),
footer: deco-format({
simple-footer.display(); h(1fr); logic.logical-slide.display()
}),
footer-descent: 1em,
header-ascent: 1em,
)
logic.polylux-slide(body)
}
|
|
https://github.com/clementjumel/resume-template | https://raw.githubusercontent.com/clementjumel/resume-template/main/resume-english.typ | typst | #import "template.typ": *
#show: resume.with(
author: "<NAME>",
description: [Member of the Night's Watch, Bastard of Winterfell, King in the North],
phone: "+00 1 23 45 67 89",
location: "Westeros",
email: "<EMAIL>",
github: "https://github.com/johnsnow",
linkedin: "https://www.linkedin.com/in/johnsnow/",
image-path: "./images/icon.jpg", // Set image-path to empty to remove the image
accent-color: "#26428b", // Accent color is optional; remove this line to make the resume in black and white
)
/*
* Lines that start with == are formatted into section headings
* You can use the specific formatting functions if needed
* The following formatting functions are listed below
* #edu(dates: "", degree: "", gpa: "", institution: "", location: "")
* #work(company: "", dates: "", location: "", title: "")
* #project(dates: "", name: "", role: "", url: "")
* #extracurriculars(activity: "", dates: "")
* There are also the following generic functions that don't apply any formatting
* #generic-two-by-two(top-left: "", top-right: "", bottom-left: "", bottom-right: "")
* #generic-one-by-two(left: "", right: "")
*/
== Experience
#work(
title: "Leader of the human armies to defeat the White Walkers",
location: "Westeros",
company: "The Northern armies",
dates: dates-helper(start-date: "~12 000 years B.C.", end-date: "~12 000 years B.C."),
)
- Wields a sword made of Valyrian steel which can kill White Walkers
- Lived and fought beyon the Wall
// You can add more work items by uncommenting & filling the following lines
// #work(
// title: ...,
// location: ...,
// company: ...,
// dates: ...,
// )
// - ...
// - ...
== Education
#edu(
institution: "The Night's Watch",
location: "The Wall",
dates: dates-helper(start-date: "~12 000 years B.C.", end-date: "~12 000 years B.C."),
degree: "Watcher on the Wall",
)
- Manage to survive the Night's Watch training (barely)
- Defended the Wall against the Wildlings and the White Walkers
// You can add more education items by uncommenting & filling the following lines
// #edu(
// institution: ...,
// location: ...,
// dates: ...,
// degree: ...,
// )
// - ...
// - ...
== Skills
- *Physical*: sword wielding
// - *Other*: ...
== Hobbies
*Sports*\
- Tried dragon riding once
// - ...
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/packages.typ | typst | The Unlicense | #import "@preview/tablex:0.0.8"
#import "@preview/showybox:2.0.1"
#import "@preview/timeliney:0.0.1"
#import "@preview/cetz:0.2.0"
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/virama-pos.typ | typst | Other | #import "/lib/draw.typ": *
#import "/template/lang.typ": hind
#let start = (0, 0)
#let end = (1000, 1000)
#let _diamond = (point, offset, fill, ..args) => {
let (x, y) = point
shape(
(x, y - offset),
(x + offset, y),
(x, y + offset),
(x - offset, y),
fill: fill,
..args.named(),
)
}
#let diamond = (point, size, border: 0, border-fill: theme.bg, ..args) => {
let args = args.named()
let arg-fill = args.at("fill", default: theme.main)
let _ = args.remove("fill")
let offset = size * calc.sqrt(2) / 2
if border != 0 {
_diamond(point, offset + border, border-fill, ..args)
}
_diamond(point, offset, arg-fill)
}
#let graph = with-unit((ux, uy) => {
// mesh(start, end, (100, 100), stroke: 1 * ux + gray)
let pen = 5 * ux + theme.main;
txt(hind[#text[छ्]], (120, 900), anchor: "lt", size: 1000 * ux)
segment((130, 900), (741, 900), stroke: pen)
arrow-head((120, 900), 30, theta: 180deg)
arrow-head((751, 900), 30)
txt([631 个单位], (435.5, 890), size: 42 * ux, anchor: "cb", dy: 20)
rect((120, 865), width: 631, height: 620, stroke: pen)
diamond((382, 282), 30, fill: gray, border: 6, closed: true)
txt(text(fill: white)[`(276,57)`], (382, 282), size: 25 * ux, anchor: "cb", dy: 35)
shape(
(595, 180),
(680, 180),
(815, 15),
(718, 15),
closed: true,
fill: gray,
stroke: stroke(
paint: theme.main,
thickness: pen.thickness,
dash: "dashed",
)
)
segment((751, 860), (751, 45))
diamond((574, 243), 30, fill: gray, border: 6)
txt([`(-172,0)`], (574, 240), size: 25 * ux, anchor: "cb", dy: 30)
arrow((751, 255), (382, 255), head-scale: 3)
arrow((382, 215), (574, 215), head-scale: 3)
txt([631 - 276 = 355], (750, 255), size: 35 * ux, anchor: "lc", dx: 20)
txt([355 + -172 = 183], (750, 208), size: 35 * ux, anchor: "lc", dx: 20)
})
#canvas(end, width: 50%, graph)
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/005/005.typ | typst | #let date = datetime(
year: 2022,
month: 5,
day: 14,
)
#metadata((
"title": "angular服务端渲染",
"author": "dashuai009",
description: "",
pubDate: date.display(),
subtitle: [angular,angular_universal,ssr],
))<frontmatter>
#import "../../__template/style.typ": conf
#show: conf
#date.display();
#outline()
== Angular 统一平台简介
[Angular Universal:Angular 统一平台简介](https://angular.cn/guide/universal)
> 本指南讲的是Angular Universal(统一平台),一项在服务端运行 Angular 应用的技术。
>
> 标准的 Angular 应用会运行在浏览器中,它会在 DOM 中渲染页面,以响应用户的操作。 而Angular Universal 会在服务端运行,生成一些静态的应用页面,稍后再通过客户端进行启动。 这
意味着该应用的渲染通常会更快,让用户可以在应用变得完全可交互之前,先查看应用的布局。
== 参考文档
[Angular Universal:Angular 统一平台简介](https://angular.cn/guide/universal)
[Rendering on web](https://developers.google.com/web/updates/2019/02/rendering-on-the-web)
[Angular Universal: a Complete Practical Guide](https://blog.angular-university.io/angular-universal/)
== 示例代码
[Angular Universal: a Complete Practical Guide](https://github.com/angular-university/angular-universal-course)
[个人代码](https://github.com/dashuai009/angularUniversal)
== 为何需要服务端渲染?
有三个主要的理由来为你的应用创建一个 Universal 版本。
- 通过搜索引擎优化(SEO)来帮助网络爬虫。
- 提升在手机和低功耗设备上的性能
- 迅速显示出第一个支持首次内容绘制(FCP)的页面
== 案例
以我的博客渲染过程为例。
这里给出一个比较大的例子,为了方便展示setTitle等部分。
如果单纯在服务端向`<div></div>`插入一段`html`代码也可以。
== 如何使用
要创建服务端应用模块 app.server.module.ts,请运行以下 CLI 命令。
```text
ng add @nguniversal/express-engine
```
该命令会创建如下文件夹结构。
```text
src/
index.html app web page
main.ts bootstrapper for client app
main.server.ts * bootstrapper for server app
style.css styles for the app
app/ ... application code
app.server.module.ts * server-side application module
server.ts * express web server
tsconfig.json TypeScript base configuration
tsconfig.app.json TypeScript browser application configuration
tsconfig.server.json TypeScript server application configuration
tsconfig.spec.json TypeScript tests configuration
```

在我的package.json中有如下定义
```json
{
"script":{
"dev:ssr": "ng run blog:serve-ssr",
"serve:ssr": "node dist/blog/server/main.js",
"build:ssr": "ng build --prod && ng run blog:server:production",
"prerender": "ng run blog:prerender"
}
}
```
之后运行`npm run dev:ssr`(与运行`ng run blog:serve-ssr`等价),可以在本地测试。
生产环境下可以用`npm run build:ssr`编译项目。和 `npm run srve:ssr` 运行项目。
== 目标
打开一个article的时候
- 直接从服务器段拿到已经把md渲染为html
- 前端无需再去请求md文档
== 重复获取数据
=== 了解状态转移API
有了App Shell,现在让我们讨论另一个常见的服务器端渲染优化:客户端启动时服务器到客户端的状态转移。
首先让我们谈谈State Transfer API解决的问题。当我们的Angular Universal应用程序启动时,页面的很大一部分已经被渲染,并且从一开始就对用户可见。
但是请记住,此服务器端呈现的应用程序将从服务器中提取普通的客户端应用程序,然后该应用程序将接管页面。
然后,此Angular客户端应用程序将启动,并且它将做的第一件事是什么?它会联系服务器并再次获取所有数据!
客户端应用程序甚至会在加载数据时打开加载指示器。对于用户来说这很奇怪,因为来自服务器的页面中已经有数据,那么为什么应用程序又要加载它呢?
然后,客户端将重新呈现所有数据,并将其再次传递给页面,并将其显示给用户。
所有这一切都有一个问题:服务器刚刚检索了数据并呈现了数据,那么为什么还要在客户端上再次重复相同的过程呢?这是多余的,它查询服务器两次,并且不能提供良好的用户体验,这是我们 首先使用Universal的主要原因。
=== Transfer API如何工作?
为了解决重复数据获取的问题,我们需要的是通用应用程序将其数据存储在页面上某个位置,然后使其可用于客户端应用程序的方式,而无需再次调用服务器。
这正是State Transfer API允许我们执行的操作!State Transfer API为我们提供了一个存储容器,用于在服务器和客户端应用程序之间轻松地传输数据,从而避免了客户端应用程序必须与服务 器联系以获取数据的需求。
=== 添加transferStateModule
[Here](https://angular.cn/api/platform-browser/TransferState)
angular提供了一种在服务器和浏览器之间,进行数据传输的一个接口。数据是附加在html后边中的一个script的标签中。
> 我踩的坑:这个数据自动进行json的解码转码。不要再对数据进行JSON.parse和JSON.stringify,无法处理html的标签,"<"
分别在app.server.module.ts和app.module.ts中,分别添加`ServerTransferStateModule`和`BrowserTransferStateModule`。


=== 编写resovler
在app.module.ts中声明(provider)resoler.ts模块。
之后,就可以在该文件中利用TransferState模块处理数据。
== 服务端是否渲染
进行一些细粒度的控制,可以使用自定义结构指令来实现:appShellRender和appShellNoRender。
#table(
columns: (1fr, auto),
inset: 10pt,
align: horizon,
"appShellRender", "服务端渲染",
"appShellNoRender", "服务端不渲染",
)
请注意,appShellRender和appShellNoRender对客户端没有任何影响!在浏览器中,每次我们浏览单个页面应用程序时,整个模板都会呈现出来。
[代码示例](https://github.com/angular-university/angular-universal-course/tree/2-express-engine-finished/src/app/directives)
== 编写服务端不渲染的组件
服务端渲染的用法简单,且就这样了。
如果想写服务端不加载的组件,又不想在组件里适配,有一种hack的写法,这里简单记录一下。
```html
<my-comp *ngif = "show | sync"></my-comp>
```
show可以是上层组件中的`Observable<boolean>`,在服务端传递`of(false)`即可。这样服务端不会渲染`my-comp`组件。 |
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/8-Pipeline/pipeline-aleas.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Pipeline aléas
],
lesson: "ARO",
chapter: "8 - Pipeline",
definition: "TBD",
col: 1,
doc,
)
= Dépendances
Deux instructions ont une dépendance si elles ont besoin de la même chose pour fonctionner correctement, comme un même registre, une même unité de calcul ou une même adresse mémoire. Lorsque cela se produit, le pipeline doit attendre que l'instruction précédente termine de travailler sur cette ressource avant de pouvoir commencer à travailler sur l'instruction suivante. Cela peut entraîner des retards et réduire l'efficacité du pipeline.
Les aléas sont inhérents au parallélisme des instructions et peuvent être classés en trois catégories principales :
== Dépendances structurels
Ce type de problèmes survient lorsque deux instructions dans des étages différents du pipeline nécessitent la même ressource.
=== Exemple
Dans l'exemple ci-dessous nous voyons que l'instruction LDR nécessite l'accès à la mémoire pour charger une valeur dans un registre, tandis que l'instruction ADD nécessite l'accès à la mémoire pour stocker le résultat d'une addition. Si ces deux instructions sont exécutées en même temps, elles entreront en conflit pour accéder à la mémoire, ce qui entraînera un aléa structurel.
#image("/_src/img/docs/image copy 44.png")
== Dépendances de données
Accès simultané aux mêmes registres.
=== RAW (Read After Write)
L’instruction n+x lit une source modifiée par l’instruction n.
```shell
ADD R1, R2, R3 R1 = R2 + R3
SUB R5, R1, #2 R5 = R1 - 2
```
=== WAR (Write After Read)
L’instruction n+x écrit dans une destination que l’instruction n utilise comme source.
```shell
ADD R1, R2, R3 R1 = R2 + R3
SUB R2, R4, #2 R2 = R4 – 2
```
=== WAW (Write After Write)
L’instruction n+x écrit dans une destination et l’instruction n écrit dans cette même destination.
```shell
ADD R1, R2, R3 R1 = R2 + R3
AND R5, R1, R2
SUB R1, R4, #2 R1 = R4 – 2
```
=== Exemple
Ce type de problèmes survient lorsque deux instructions dans des étages différents du pipeline nécessitent le même registre alors que ce dernier n’a pas encore été mis à jour.
#image("/_src/img/docs/image copy 45.png")
Vu qu'il faut attendre l'opération WB (Write Back) pour que dans le registre `R1` la valeur de l'addition `R1` et 1 soit stockée, la deuxième instruction ADD ne peut pas être exécutée avant que la première instruction ADD ne soit complètement terminée.
== Dépendances de contrôle
Lors de l'exécution d'une instruction de branchement conditionnel, on dit que le branchement est pris si la condition est vérifiée et que le programme se poursuit effectivement à la nouvelle adresse.
#image("/_src/img/docs/image copy 46.png")
= Arrêt de pipeline
Pour éviter les aléas, le pipeline peut être arrêté. Cela peut se faire de différentes manières :
== Arrêt de pipeline par hardware
Lorsqu'un aléa est détecté, le pipeline peut être arrêté pour attendre que l'aléa soit résolu. Cela peut se faire en vidant le pipeline ou en insérant des bulles.
#image("/_src/img/docs/image copy 47.png")
== Arrêt de pipeline par
#image("/_src/img/docs/image copy 48.png")
= Forwarding (bypassing)
Le forwarding est une technique qui permet de résoudre les aléas de données en transmettant directement les données d'une étape du pipeline à une autre. Cela permet d'éviter les retards dus aux aléas de données en fournissant les données nécessaires à l'étape suivante du pipeline dès qu'elles sont disponibles.
- Le résultat est directement accessible à la sortie du bloc *EXECUTE* pourl'instruction suivante.
== Sans Forwarding
#image("/_src/img/docs/image copy 88.png")
== Avec Forwarding
#image("/_src/img/docs/image copy 89.png") |
|
https://github.com/linhduongtuan/DTU-typst-presentation | https://raw.githubusercontent.com/linhduongtuan/DTU-typst-presentation/main/slide_sections.typ | typst | #import "slides.typ": *
#import "slide_footnotes.typ": *
// Meine eigene Implementation für ein Inhaltsverzeichnis.
// Überschreibt die Standardfunktion "new-section" aus "slides.typ"
#let new-section(title) = {
// Und eine neue Folie wird erzeugt, zusammen mit einer Überschrift.
slide(theme-variant: "section-slide")[= #title]
state("current_slide_section").update(title)
} |
|
https://github.com/ralphmb/typst-template-stats-dissertation | https://raw.githubusercontent.com/ralphmb/typst-template-stats-dissertation/main/writeup/sections/introduction.typ | typst | Apache License 2.0 | In this project we hope to examine...\
We will first look at... \
Afterwards we will look at...\
#heading([Notes], outlined: false, numbering: none)
// No numbering - I didn't want this to show up in contents or change numbering of later sections.
#let wordcount = 10000
Word count excluding bibliography, appendices is approximately #wordcount.\
// The code in writeup/other/template.typ isn't mine, so I'm leaving attribution for it here.
This document was typeset using Typst. The code used for generating page headers was written by <NAME>, and used under the terms of the Apache open source license. Their original work and the associated license can be found at the following link.
#link("https://github.com/zagoli/simple-typst-thesis")\
This project received ethics approval from Coventry University, the certificate can be found at the end of the appendices.
Thank you to <NAME> for their practical support and guidance. |
https://github.com/SergeyGorchakov/russian-phd-thesis-template-typst | https://raw.githubusercontent.com/SergeyGorchakov/russian-phd-thesis-template-typst/main/parts/part2.typ | typst | MIT License | #import "../lib.typ": *
#part_count.step() // Обновление счетчика разделов
#show: fix-indent()
= Длинное название главы, в которой мы смотрим на примеры того, как будут верстаться изображения и списки <ch2>
== Одиночное изображение <ch2:sec1>
Вставить одиночное изображение можно следующим образом:
#figure(
image("../images/typst.png", width: 50%),
caption: [Typst]
) <fig:typst>
И сослаться на него: На рисунке @fig:typst показано ...
#lorem(100) // текст заполнителя для шаблона
#lorem(50)
== Проверка нумерации уравнений по разделам
Уравнение во втором разделе.
$ z^2 = x^2 + y^2 $
|
https://github.com/SkiFire13/master-thesis | https://raw.githubusercontent.com/SkiFire13/master-thesis/master/chapters/background/2-tuples.typ | typst | #import "../../config/common.typ": *
== Tuples
In order to define systems of fixpoint equations we will need to refer to multiple equations/variables/values together, and to do that we will use $n$-tuples. We now introduce some basic notions regarding tuples, along with some convenient notation for referring to them or their elements and constructing new ones.
#definition([set of $n$-tuples])[
Let $A$ be a set. Given $n >= 1$ the set of $n$-tuples of $A$, written $A^n$, is inductively defined as $A^0 = { () }$, $A^1 = A$ and $A^(n+1) = A times A^n$.
]
#notation([$n$-tuple])[
Let $A^n$ be a set of $n$-tuples. We will refer to its elements using boldface lowercase letters, like $tup(a)$. Given $tup(a) in A^n$ we will refer to its $i$-th element with the non-boldface $a_i$.
]
#notation("concatenation")[
Let $tup(a_1), ..., tup(a_k)$ be either $n$-tuples or single elements of $A$. The notation $(tup(a_1), ..., tup(a_k))$ represents a $n$-tuple obtained by concatenating the elements in the tuples $tup(a_1), ..., tup(a_k)$. Single elements are considered as $1$-tuples for this purpose.
]
We will also often refer to intervals over natural numbers, typically in order to index the elements of a tuple.
#notation("range")[
We will refer to the set ${ 1, ..., n }$ with the shorthand $range(n)$.
]
Given a poset $X$ we can extend its order to $X^n$ by having the $psub$ relation hold for two tuples when the $sub$ relation holds for all the pair of elements. This is called _pointwise order_, and we will use it often later on.
#definition("pointwise order")[
Let $(X, sub)$ be a poset. The pointwise order $psub$ on $X^n$ is defined, for $tup(x), tup(x') in X^n$, by $tup(x) psub tup(x')$ if $forall i in range(n). x_i sub x'_i$.
It can be proven that $(X^n, psub)$ is also a poset. Moreover if $(X, sub)$ is a (complete) lattice then $(X^n, psub)$ is also a (complete) lattice, where $join tup(X) = (join X_1, join X_2, ..., join X_n)$ and similarly for $meet tup(X)$.
]
|
|
https://github.com/MLAkainu/Network-Comuter-Report | https://raw.githubusercontent.com/MLAkainu/Network-Comuter-Report/main/metadata.typ | typst | Apache License 2.0 | #let meta = (
course-name: "Mạng máy tính",
course-id: "CO3094",
title: "DEVELOP A SIMPLE FILE-SHARING APPLICATION",
semester: 231,
date: "11/2023",
students: (
"2110527": "<NAME>",
"2112594": "<NAME>",
"2110342": "<NAME>"
),
advisor: "<NAME>",
) |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/while-04.typ | typst | Other | // Error: 2:2-2:24 loop seems to be infinite
#let i = 1
#while i > 0 { i += 1 }
|
https://github.com/grodino/uni-rennes-typst | https://raw.githubusercontent.com/grodino/uni-rennes-typst/main/src/colors.typ | typst | MIT License | #let primary = (dark: rgb("#000000"), light: rgb("#ffffff"))
#let accent-green = (dark: rgb("#007852"), light: rgb("#65b32e"))
#let accent-cyan = (dark: rgb("#004070"), light: rgb("#00abe4"))
#let accent-blue = (dark: rgb("#3a1c67"), light: rgb("#4054a1"))
#let accent-purple = (dark: rgb("#751b74"), light: rgb("#a877b2"))
#let accent-pink = (dark: rgb("#a8004d"), light: rgb("#ed6ea7"))
#let accent-red = (dark: rgb("#b51f1f"), light: rgb("#e63312"))
#let accent-orange = (dark: rgb("#cc621a"), light: rgb("#f7a600"))
|
https://github.com/adfaure/invoice-template | https://raw.githubusercontent.com/adfaure/invoice-template/main/example.typ | typst | MIT License | #import "invoice.typ" : invoice
#let my-information = (
name: [<NAME>],
// Only in france ?
siret: [00000000000000],
immatriculation: [],
mail: [#link("mailto:<EMAIL>")],
address: [
1 road Somewhere \
Anywhere
],
tel: [+00000000000],
conditions: [
]
)
// This is the client info, needs to be dynamically loaded
#let client-information = (
name: [ Client Name ],
address: [ 122 road \ Paris],
number: [0000],
)
// Bank account information
#let bank-account = (
account-owner : [<NAME>],
bank-address: [ 1 road, Elsewhere ],
iban: [AB00 0000 0000 0000 0000 0000 000],
bic: [ AAAAAAAA ]
)
// Title
#let title = "Title"
#let conditions = [ Payement due ASAP]
#let month = sys.inputs.at("month", default: datetime.today().month())
// Set the lang for localize package
#set text(lang: "en")
// Show links in blue
#show link: set text(blue.darken(30%))
// Load the invoice template
#show: body => invoice(title, my-information, bank-account, client-information, month, [ ], body)
// This part is the body of the invoice, write down what you did
Details of the operations
#v(31em)
// Simple table with the price
#table(
columns: (1fr, auto),
[ *Total* ], [ 1 000 000\$ ]
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10A00.typ | typst | Apache License 2.0 | #let data = (
("KHAROSHTHI LETTER A", "Lo", 0),
("KHAROSHTHI VOWEL SIGN I", "Mn", 0),
("KHAROSHTHI VOWEL SIGN U", "Mn", 0),
("KHAROSHTHI VOWEL SIGN VOCALIC R", "Mn", 0),
(),
("KHAROSHTHI VOWEL SIGN E", "Mn", 0),
("KHAROSHTHI VOWEL SIGN O", "Mn", 0),
(),
(),
(),
(),
(),
("KHAROSHTHI VOWEL LENGTH MARK", "Mn", 0),
("KHAROSHTHI SIGN DOUBLE RING BELOW", "Mn", 220),
("KHAROSHTHI SIGN ANUSVARA", "Mn", 0),
("KHAROSHTHI SIGN VISARGA", "Mn", 230),
("KHAROSHTHI LETTER KA", "Lo", 0),
("KHAROSHTHI LETTER KHA", "Lo", 0),
("KHAROSHTHI LETTER GA", "Lo", 0),
("KHAROSHTHI LETTER GHA", "Lo", 0),
(),
("KHAROSHTHI LETTER CA", "Lo", 0),
("KHAROSHTHI LETTER CHA", "Lo", 0),
("KHAROSHTHI LETTER JA", "Lo", 0),
(),
("KHAROSHTHI LETTER NYA", "Lo", 0),
("KHAROSHTHI LETTER TTA", "Lo", 0),
("KHAROSHTHI LETTER TTHA", "Lo", 0),
("KHAROSHTHI LETTER DDA", "Lo", 0),
("KHAROSHTHI LETTER DDHA", "Lo", 0),
("KHAROSHTHI LETTER NNA", "Lo", 0),
("KHAROSHTHI LETTER TA", "Lo", 0),
("KHAROSHTHI LETTER THA", "Lo", 0),
("KHAROSHTHI LETTER DA", "Lo", 0),
("KHAROSHTHI LETTER DHA", "Lo", 0),
("KHAROSHTHI LETTER NA", "Lo", 0),
("KHAROSHTHI LETTER PA", "Lo", 0),
("KHAROSHTHI LETTER PHA", "Lo", 0),
("KHAROSHTHI LETTER BA", "Lo", 0),
("KHAROSHTHI LETTER BHA", "Lo", 0),
("KHAROSHTHI LETTER MA", "Lo", 0),
("KHAROSHTHI LETTER YA", "Lo", 0),
("KHAROSHTHI LETTER RA", "Lo", 0),
("KHAROSHTHI LETTER LA", "Lo", 0),
("KHAROSHTHI LETTER VA", "Lo", 0),
("KHAROSHTHI LETTER SHA", "Lo", 0),
("KHAROSHTHI LETTER SSA", "Lo", 0),
("KHAROSHTHI LETTER SA", "Lo", 0),
("KHAROSHTHI LETTER ZA", "Lo", 0),
("KHAROSHTHI LETTER HA", "Lo", 0),
("KHAROSHTHI LETTER KKA", "Lo", 0),
("KHAROSHTHI LETTER TTTHA", "Lo", 0),
("KHAROSHTHI LETTER TTTA", "Lo", 0),
("KHAROSHTHI LETTER VHA", "Lo", 0),
(),
(),
("KHAROSHTHI SIGN BAR ABOVE", "Mn", 230),
("KHAROSHTHI SIGN CAUDA", "Mn", 1),
("KHAROSHTHI SIGN DOT BELOW", "Mn", 220),
(),
(),
(),
(),
("KHAROSHTHI VIRAMA", "Mn", 9),
("KHAROSHTHI DIGIT ONE", "No", 0),
("KHAROSHTHI DIGIT TWO", "No", 0),
("KHAROSHTHI DIGIT THREE", "No", 0),
("KHAROSHTHI DIGIT FOUR", "No", 0),
("KHAROSHTHI NUMBER TEN", "No", 0),
("KHAROSHTHI NUMBER TWENTY", "No", 0),
("KHAROSHTHI NUMBER ONE HUNDRED", "No", 0),
("KHAROSHTHI NUMBER ONE THOUSAND", "No", 0),
("KHAROSHTHI FRACTION ONE HALF", "No", 0),
(),
(),
(),
(),
(),
(),
(),
("KHAROSHTHI PUNCTUATION DOT", "Po", 0),
("KHAROSHTHI PUNCTUATION SMALL CIRCLE", "Po", 0),
("KHAROSHTHI PUNCTUATION CIRCLE", "Po", 0),
("KHAROSHTHI PUNCTUATION CRESCENT BAR", "Po", 0),
("KHAROSHTHI PUNCTUATION MANGALAM", "Po", 0),
("KHAROSHTHI PUNCTUATION LOTUS", "Po", 0),
("KHAROSHTHI PUNCTUATION DANDA", "Po", 0),
("KHAROSHTHI PUNCTUATION DOUBLE DANDA", "Po", 0),
("KHAROSHTHI PUNCTUATION LINES", "Po", 0),
)
|
https://github.com/r8vnhill/apunte-bibliotecas-de-software | https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit2/Extension.typ | typst | == Funciones de Extensión
Las funciones de extensión en Kotlin permiten añadir nuevas funcionalidades a una clase sin necesidad de heredar de ella o modificar su código original.
Estas funciones no modifican la clase extendida de ninguna manera y se resuelven estáticamente, lo que significa que no forman parte de la clase real.
Es importante notar que, si la clase original ya tiene un método con la misma firma que la función de extensión, el método original tendrá preferencia sobre la función de extensión.
=== Ejemplo de una Función de Extensión
```kotlin
fun String.replaceSpaces(replacement: String): String {
return this.replace(" ", replacement)
}
```
En este ejemplo, estamos extendiendo la clase `String` con una nueva función `replaceSpaces`.
La palabra clave `this` se refiere a la instancia de `String` sobre la que se llama la función.
=== Uso de la Función de Extensión
Una vez definida, la función de extensión puede ser llamada como si fuera un método miembro de la clase.
```kotlin
fun main() {
val text = "Hello World"
println(text.replaceSpaces("_"))
}
```
En este caso, la función `replaceSpaces` se llama sobre una instancia de `String`, reemplazando todos los espacios en blanco por guiones bajos.
=== Limitaciones de las Funciones de Extensión
Es importante tener en cuenta que las funciones de extensión no pueden acceder a los miembros protegidos o privados de la clase que están extendiendo.
Esto asegura que no se violen los principios de encapsulación y acceso seguro a los datos.
=== Operadores de Extensión
Al igual que con las funciones de extensión, Kotlin permite definir operadores de extensión, que son operadores personalizados añadidos a las clases existentes.
==== Definición de un Operador de Extensión
```kotlin
operator fun String.times(n: Int): String = this.repeat(n)
```
En este ejemplo, estamos extendiendo la clase `String` con el operador de multiplicación (`*`).
Este operador utiliza la función `repeat` para repetir la cadena `n` veces.
==== Uso del Operador de Extensión
Una vez definido, el operador de extensión puede ser utilizado como cualquier otro operador nativo de la clase.
```kotlin
fun main() {
val text = "Hello"
println(text * 3) // Output: HelloHelloHello
}
```
En este caso, el operador `*` se utiliza para repetir la cadena `"Hello"` tres veces.
=== Propiedades de Extensión
En Kotlin, también es posible definir propiedades de extensión, lo que permite añadir nuevas propiedades a las clases existentes sin modificar su código fuente.
Estas propiedades se implementan mediante getters y setters.
==== Definición de Propiedades de Extensión
Las propiedades de extensión permiten añadir nuevas propiedades a las clases existentes de manera similar a como se añaden nuevas funciones.
```kotlin
val String.wordCount: Int
get() = this.split("""\s+""".toRegex()).size
```
En este ejemplo, se define una propiedad de extensión `wordCount` para la clase `String`, que cuenta el número de palabras en la cadena dividiéndola por espacios en blanco.
==== Propiedades de Extensión con Getter y Setter
También es posible definir propiedades de extensión con un setter, permitiendo modificar el valor de la propiedad.
```kotlin
var MutableList<String>.firstElement: String
get() = this[0]
set(value) {
this[0] = value
}
```
En este caso, se añade una propiedad de extensión `firstElement` a la clase `MutableList<String>`, que permite acceder y modificar el primer elemento de la lista.
==== Uso de Propiedades de Extensión
Una vez definidas, las propiedades de extensión pueden ser utilizadas como cualquier otra propiedad miembro de la clase.
```kotlin
fun main() {
val text = "<NAME>"
println(text.wordCount) // Output: 2
val list = mutableListOf("Apple", "Banana", "Cherry")
println(list.firstElement) // Output: Apple
list.firstElement = "Apricot"
println(list.firstElement) // Output: Apricot
}
```
En este ejemplo, la propiedad `wordCount` se utiliza para contar las palabras en una cadena, y la propiedad `firstElement` se utiliza para acceder y modificar el primer elemento de una lista mutable.
|
|
https://github.com/azduha/typst-templates | https://raw.githubusercontent.com/azduha/typst-templates/main/dite.typ | typst | MIT License | #import "template.typ": *
#let data = json.decode("{}")
#show: duha.with(
title:"Závazná přihláška dítěte",
author: "<NAME>"
)
#title("Závazná přihláška dítěte", subtitle: "na letní dětský tábor Duha AZ")
#v(-0.3em)
#credentials(fields: (
"Organizátor:": [
Duha Alternativní Zóna (dále jen Duha AZ) \
\1. máje 325/1, 591 01 Žďár nad Sázavou \
IČO: 670 24 629, \
registrace: VSP/1 – 3086/90 R ze dne 28. 2. 1990
],
"Místo:": [
táborová základna Údolí Slunce poblíž Železných Horek
],
"Termín:": [
30. 6. 2024 - 13. 7. 2024
],
"Cena tábora:": [
4 100 Kč pro členy Duhy AZ, 4 500 Kč pro nečleny Duhy AZ
]
))
#v(0.3em)
#let imagecontent = {
if (type(optional(data, "fotka")) == str and optional(data, "fotka").len() > 0) {
// Cannot place image from online, this is for now
place(line(start: (0%, 0%), end: (100%, 100%), stroke:(thickness: lineThickness, paint: fillColor)))
place(line(start: (100%, 0%), end: (0%, 100%), stroke:(thickness: lineThickness, paint: fillColor)))
} else {
[
Fotografie dı́těte
#par(text(
[
jakákoli aktuálnı́, \
sloužı́ ke zkvalitněnı́ \
práce vedoucı́ch, \
seznámı́ se s podobou \
dı́těte již před \
začátkem tábora
],
size: 0.8em,
), leading: 0.4em)
]
}
}
#place(top + right, box(
align(center + horizon, imagecontent),
width: 105pt,
height: 140pt,
stroke: (
paint: black,
thickness: 0.8pt
),
), dy: 38%)
#form([
#heading("Základní údaje o účastníkovi")
#field("Jméno a příjmení:", to: 55%, content: optional(data, "jmeno") + " " + optional(data, "prijmeni"))
#field("Přezdívka / oslovení:", content: optional(data, "prezdivka"))
#field("Bydliště:", to: 60%, content: optional(data, "bydliste"))
#field("Škola:", content: optional(data, "skola"))
#field("Rodné číslo:", to: 35%, content: optional(data, "datum_narozeni"))
#field("Zdravotní pojišťovna:", to: 75%, content: optional(data, "zp"))
#field("Třída:", content: optional(data, "trida"))
#heading("Další důležité údaje")
#options("Je účastnı́k v současnosti členem Duhy AZ?", options: (
"ANO": 64%,
"NE": 74%
), selected: ("NE", "ANO", "").at(data.at("clen", default: 2)))
#options("Je plavec (uplave alespoň 25 m)?", options: (
"ANO": 64%,
"NE": 74%
), selected: ("NE", "ANO", "").at(data.at("plavec", default: 2)))
#field("Kolikrát byl(a) již na táboře (jakémkoliv):", to: 74%, content: str(optional(data, "tabor")) + (if str(optional(data, "tabor")).len() > 0 {" krát"}))
#field("Stan by chtěl(a) sdı́let s:", to: 74%, content: optional(data, "stan"))
#field("Je nějaké jı́dlo, jež odmı́tá jı́st:", to: 74%, content: optional(data, "jidlo"))
#field("Dalšı́ důležitá (např. zdravotnı́) sdělenı́:", to: 74%, lines: 1, content: optional(data, "oznameni"))
#heading("Kontaktní údaje")
Kontakt s rodiči pro komunikaci v obdobı́ před táborem (vyplň te alespoň jeden řádek):
#field("Jméno matky:", to: 40%, content: optional(data, "jmeno_matky"))
#field("Telefon:", to: 64%, content: format-phone(optional(data, "telefon_matky")))
#field("Email:", content: optional(data, "email_matky"))
#field("Jméno otce:", to: 40%, content: optional(data, "jmeno_otce"))
#field("Telefon:", to: 64%, content: format-phone(optional(data, "telefon_otce")))
#field("Email:", content: optional(data, "email_otce"))
#field("Zaměstnavatel (v přı́padě poskytnutı́ finančnı́ho přı́spěvku):", content: optional(data, "zamestnavatel"))
#v(0.6em)
Kontakt na zákonného zástupce dosažitelného v době konánı́ tábora:
#field("Jméno:", to: 40%, content: optional(data, "kontakt_jmeno"))
#field("Telefon:", to: 70%, content: format-phone(optional(data, "kontakt_telefon")))
#field("Poznámka:")
#heading("Ujednání")
#text([
Souhlası́m, aby se naše dı́tě zúčastnilo letnı́ho tábora organizace Duha AZ od 30. 6. do 13. 7. 2024.
Zároveň souhlası́m s převzetı́m odpovědnosti za přı́padné škody způsobené dı́tětem.
Udı́lı́m souhlas k tomu, aby vedenı́ tábora shromažďovalo, zpracovávalo a archivovalo uvedené osobnı́ údaje pro potřeby
tábora a po dobu nezbytně nutnou (stanovenou zákonem). Osobnı́ údaje budou chráněny proti zneužitı́ a nebudou poskytnuty třetı́m stranám. Souhlası́m (i dı́tě souhlası́) s fotografovánı́m a pořizovánı́m audiovizuálnı́ho záznamu dı́těte v rámci činnosti, s archivacı́
těchto materiálů a s jejich použitı́m při prezentaci a propagaci činnosti, např. v kronikách, tisku, na internetu atp.
Také potvrzuji úplnost a pravdivost výše uvedených údajů.
], size: 0.9em)
#v(0.6em)
#field("Datum:", to: 40%, content: format-datetime(optional(data, "datum")))
#field("Podpis:")
])
#pagebreak()
#title("Posudek o zdravotní způsobilosti", subtitle: "dítěte k účasti na zotavovací akci a škole v přírodě")
#v(-0.5em)
#form([
#field("Evidenční číslo posudku:")
#heading("1. Identifikační údaje")
#field("Jméno a příjmení posuzovaného dítěte:", to: 75%, content: optional(data, "jmeno") + " " + optional(data, "prijmeni"))
#field("RČ:", content: optional(data, "datum_narozeni"))
#field("Adresa mı́sta trvalého pobytu nebo jiného bydliště na územı́ ČR posuzovaného dı́těte:", newline: true, content: optional(data, "bydliste"))
#field("Název poskytovatele zdravotních služeb vydávajícího posudek:")
#field("Adresa sı́dla nebo mı́sta podnikánı́ poskytovatele:", lines: 2, lastLineTo: 70%)
#field("IČO:")
#field(heading("2. Účel vydání posudku: "))
#heading("3. Posudkový závěr")
#v(-0.5em)
#[
#set par(first-line-indent: 1em)
#heading([
A) Posuzované dítě k účasti na zotavovací akci nebo škole v přírodě
#super("1, 2")
], level: 2)
#[
#set par(first-line-indent: 2em, hanging-indent: 2.5em)
a) je zdravotně způsobilé
#h(20%)
b) nenı́ zdravotně způsobilé
#v(-0.3em)
#field("c) je zdravotně způsobilé s omezenı́m:", to: 100%)
#v(0.3em)
#par(text(size: 0.9em, [
#super("1") Nehodící se škrtněte
#v(-0.4em)
#super("2") Bylo-li zjištěno, že posuzované dı́tě je zdravotně způsobilé s omezenı́m, uvede se omezenı́ podmiňujı́cı́ zdravotní způsobilost k účasti na letnı́m táboře, zotavovacı́ akci a škole v přı́rodě
]))
]
#heading([
B) Potvrzení o tom, že dítě
], level: 2)
#[
#set par(first-line-indent: 2em, hanging-indent: 2.5em)
#options("a) se podrobilo stanoveným pravidelným očkovánı́m:", options: (
"ANO": 90%,
"NE": 100%
))
#field("b) je proti nákaze imunní (typ/druh):")
#field("c) má trvalou kontraindikaci proti očkování (typ/druh):")
#field("d) je alergické na:")
#field("e) dlouhodobě užívá léky (typ/druh, dávka):")
]
]
#heading("4. Poučení")
#text([
Proti bodu 3. části A) tohoto posudku je možné podat podle ustanovení § 46 odst. 1 zákona č. 373/2011 Sb., o specifických zdravotních službách, ve znění pozdějších předpisů, podat návrh na jeho přezkoumání do 10 pracovních dnů ode dne jeho prokazatelného předání poskytovatelem zdravotních služeb, který posudek vydal. Návrh na přezkoumání lékařského posudku nemá odkladný účinek, jestliže z jeho závěru vyplývá, že posuzovaná osoba je pro účel, pro nějž byla posuzována, zdravotně nezpůsobilá nebo zdravotně způsobilá s podmínkou.
], size: 0.8em)
#heading("5. Oprávněná osoba")
#field("Jméno a příjmení oprávněné osoby:")
#options("Vztah k posuzovanému dítěti:", options: (
"Zákonný zástupce": 54%,
"Opatrovník": 70%,
"Pěstoun": 83%,
"Jiný: ______": 100%
))
#text("")
#place(top + left, signature(length: 40%, [Datum vydání posudku]), dy: 87%)
#place(top + right, signature(length: 40%, [
Jméno, přı́jmenı́ a podpis lékaře,\
razı́tko poskytovatele zdravotnı́ch služby
]), dx: 0%, dy: 87%)
#place(top + left, signature(length: 40%, [
Oprávněná osoba převzala posudek \
do vlastních rukou dne
]), dy: 95%)
#place(top + right, signature(length: 40%, [Podpis oprávněné osoby]), dy: 95%)
]) |
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/content/summary.typ | typst | MIT License | #import "/utils/todo.typ": TODO
= Summary
#TODO[
This chapter includes the status of your thesis, a conclusion and an outlook about future work.
]
== Status
#TODO[
Describe honestly the achieved goals (e.g. the well implemented and tested use cases) and the open goals here. if you only have achieved goals, you did something wrong in your analysis.
]
=== Realized Goals
#TODO[
Summarize the achieved goals by repeating the realized requirements or use cases stating how you realized them.
]
=== Open Goals
#TODO[
Summarize the open goals by repeating the open requirements or use cases and explaining why you were not able to achieve them. Important: It might be suspicious, if you do not have open goals. This usually indicates that you did not thoroughly analyze your problems.
]
== Conclusion
#TODO[
Recap shortly which problem you solved in your thesis and discuss your *contributions* here.
]
== Future Work
#TODO[
Tell us the next steps (that you would do if you have more time). Be creative, visionary and open-minded here.
] |
https://github.com/3w36zj6/textlint-plugin-typst | https://raw.githubusercontent.com/3w36zj6/textlint-plugin-typst/main/test/fixtures/Comment/input.typ | typst | MIT License | // This is a comment.
// This is another comment.
This is a /* comment */.
Our study design is as follows:
/* Somebody write this up:
- 1000 participants.
- 2x2 data design. */
|
https://github.com/ralphmb/typst-template-stats-dissertation | https://raw.githubusercontent.com/ralphmb/typst-template-stats-dissertation/main/writeup/main.typ | typst | Apache License 2.0 | #import "./other/template.typ": getHeader
#let my_name = "<NAME>"
#let thesis_title = "Project Title"
#let thesis_domain = "Mathematics and Statistics"
#let my_institution = "Coventry University"
#set document(author: my_name, title: thesis_title)
#set text(font: "New Computer Modern", lang: "en")
#set heading(numbering: "1.1")
#set par(justify: true)
// Title Page
#v(0.25fr)
#align(center)[
#text(2em, weight: 700, thesis_title)
]
#pad(
top: 0.7em,
grid(
columns: (1fr),
gutter: 1em,
align(center)[
*#my_name* \
#thesis_domain \
#my_institution \
]
),
)
// Table of contents
#outline(depth: 3, indent: true)
#pagebreak()
// Main body
#set page(numbering: "1", number-align: center)
#set page(header: getHeader(),
margin: (x:30pt, y:50pt))
#counter(page).update(1)//
// Formatting for tables
// Highlighting top and left columns
#set table(
fill: (x, y) =>
if x == 0 or y == 0 {
gray.lighten(40%)
},
align: right,
)
// Make the highlighted text bold
#show table.cell.where(x: 0): strong
#show table.cell.where(y: 0): strong
// Center them and make the text smaller
#show table: set text(8pt)
#show table: set align(center)
// And here's where we include all the sections.
= Introduction
#include("./sections/introduction.typ")
#pagebreak(weak: true)
#set par(first-line-indent: 20pt) // Indents first line of a new paragraph
#set page(columns: 2)
= Review of Literature
#include("./sections/litreview.typ")
= Preliminary Steps
== Data Collection
#include("./sections/datacollection.typ")
== Exploratory Analysis
#include("./sections/exploratory.typ")
= Main Topic
#include("./sections/bigsection.typ")
// Bibliography section
#set page(header: [])
#set text(8pt)// Setting smaller text sizes to save paper
#bibliography("./sections/bibliography.bib")
//.bib files work here as in latex, get references in bibtex format and copy/paste them into it
#pagebreak(weak: true)
#set page(columns: 1)
#set text(7pt)
#set par(first-line-indent: 0pt)
#show table: set text(7pt)
#heading([Appendices], numbering:none)
#linebreak()
#include("./sections/appendix.typ") |
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/Math/equation.typ | typst | #set text(
size:10pt,
)
#set page(
paper:"a5",
margin:(x:1.8cm,y:1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
= 方程式
一个数学方程式。
可以与文本内嵌显示,也可以作为单独的块显示。
= 例
#image("22.png")
= 语法
此函数还具有专用语法:在美元符号内编写数学标记以创建方程式。以至少一个空格开始和结束方程会将其提升到水平居中的单独块中。有关数学语法的更多详细信息,请参阅 math 主页。
= 参数
#image("23.png")
= 块
方程式是否显示为单独的块。
默认:false
= 编号
如何对表达式进行编号。
默认:none
= 编号对齐
等式编号的对齐方式。
默认情况下,对齐方式为 end + horizon 。对于水平分量,可以使用文本方向的 right 、left 或 start 和 end ;对于垂直分量,可以使用 top 、horizon 或 bottom 。
违约:end + horizon
= 补充
数学表达式的补充内容。
添加在被引用的公式编号的前面。
如果指定了一个函数,将会传入引用的表达式,并返回其内容。
默认:auto
= 内容
等式的内容。
|
|
https://github.com/han0126/MCM-test | https://raw.githubusercontent.com/han0126/MCM-test/main/2024亚太杯typst/chapter/chapter1.typ | typst | = 问题重述
== 问题背景
洪水是世界上最严重的自然灾害之一,洪水事件对人类社会自然环境都形成了强烈的冲击。随着全球变暖,气温上升,人类活动的日益影响下,洪水的发生频率和强度都在显著上升,为此,对于洪水灾害的数据分析和预测是十分有必要的。为了有效进行分析和预测,我们需要依据各项指标,通过科学精确的方法建立洪水预测模型,从而提前采取相应措施来降低自然灾害带给人类的影响。
== 问题提出
根据以上背景,以及给出的三个附件,需要解决以下问题:
1. 分析附件'train.csv'中洪水概率与各指标的相关性,提出合理建议和措施。
2. 将洪水概率聚类成不同类别,选取合适指标,建立预警模型。
3. 基于相关性分析,选取合适指标建立概率预测模型,并简化该模型。
4. 基于预测模型,预测'test.csv'中的洪水概率,并分析结果1. 分析附件'train.csv'中洪水概率与各指标的相关性,提出合理建议和措施。
2. 将洪水概率聚类成不同类别,选取合适指标,建立预警模型。
3. 基于相关性分析,选取合适指标建立概率预测模型,并简化该模型。
4. 基于预测模型,预测`test.csv`中的洪水概率,并分析结果。
#h(2em)其中,`train.csv`中给出了$100$多万组季风强度、地形排水等$20$个指标得分与洪水概率的数据;`test.csv`中仅给出$74$万组$20$个指标得分。
\
\
|
|
https://github.com/linsyking/messenger-manual | https://raw.githubusercontent.com/linsyking/messenger-manual/main/hello%20world.typ | typst | #import "@preview/fletcher:0.4.4" as fletcher: diagram, node, edge
#pagebreak()
= Hello World in Messenger
== Installation
To create a simple game in Messenger, the first step is to install the Messenger CLI tool:
Messenger CLI is written in Python. You need to install `python>=3.7`. #link("https://pipx.pypa.io/stable/")[pipx] is a tool to manage python applications. It is recommended to use `pipx` instead of `pip` on Unix-based OS (including WSL).
```bash
pipx install -i https://pypi.python.org/simple elm-messenger>=0.3.7
# Or use pip on Windows:
pip install -i https://pypi.python.org/simple elm-messenger>=0.3.7
```
This tool assists in quickly building a project. To create a new project, use the following commands:
```bash
messenger init helloworld
# Or with custom repo:
messenger init helloworld -t <Repo URL>
# With custom branch:
messenger init helloworld -t <Repo URL> -b <Branch name>
```
Then, create a new scene and add a layer in that scene:
```bash
# Open our project directory
cd helloworld
# Create a new scene
messenger scene Home
# Create a new layer called MainLayer
messenger layer Home MainLayer
```
*Note:* If the scene name is not "Home", change the scene name in `initScene` in `MainConfig.elm` (which defines which scene to start), as it is set to "Home" by default.
*Hint:* It is fine to use lowercase letters like `home` and `mainLayer`. The Messenger CLI will automatically convert these to appropriate names.
*Note:* By default, a scene is a `LayeredScene`. To create a `RawScene` without any layers, add the `--raw` argument when creating a scene. Raw scene doesn't have `SceneBase.elm` when created. However, if users try to add a component or a layer to a raw scene, that file will automatically be created.
See @cli to learn more about Messenger CLI.
== Project Structure
```bash
./helloworld
├── assets # Store game assets in this folder
├── elm.json
├── index.html
├── Makefile
├── messenger.json
├── .messenger # Data used by Messenger, don’t modify this by hand!
├── public # JS, CSS and HTML files
└── src
├── Lib
│ ├── Base.elm # Base types for many modules
│ ├── Ports.elm
│ ├── Resources.elm # Images to load
│ └── UserData.elm # User global data
├── MainConfig.elm # Configurations for the game
├── Main.elm
└── Scenes # Scene folder
├── AllScenes.elm # Stores all the scene data
└── Home # A scene called "Home"
├── MainLayer # A layer called "MainLayer" in Home
│ ├── Model.elm # Layer definitions
│ └── Init.elm # Init message type
├── Components # Scene components
│ ├── Comp # A component called "Comp"
│ │ ├── Model.elm
│ │ └── Init.elm
│ └── ComponentBase.elm
├── SceneBase.elm
└── Model.elm
```
== Getting Started
First, determine the `UserData` and `SceneMsg`, which respectively represent the data that can be accessed or modified at any time and the message to be sent to the scene when switching scenes.
Next, prepare `userConfig` and a list containing all the scenes as inputs. The `userConfig` is a record that includes the basic configurations needed by the main function. This is automatically wrapped in `Main.elm`, so only the options in `MainConfig.elm` need to be modified.
An initial global data is also needed, but it is not necessary to provide the full global data. Instead, users only need to provide a subset that does not include any Messenger internal data.
Since this is a hello world project, only one scene is needed, so customizing `UserData` and `SceneMsg` can be skipped.
By default, Messenger does not add user layers to a scene automatically because it does not know how the layers will be initialized. It is a good practice to add layers to the scene immediately after creating them.
First, open `Scenes/Home/Model.elm` and import layer:
```elm
import Scenes.Home.MainLayer.Model as MainLayer
```
Second, add the layer to `init` function:
```elm
init env msg =
...
, layers =
[ MainLayer.layer NullLayerMsg envcd
]
```
Now open `Scenes/Home/MainLayer/Model.elm`. Change the `view` function:
```elm
import Messenger.Render.Text exposing (renderText)
...
view : LayerView SceneCommonData UserData Data
view env data =
renderText env.globalData 40 "Hello World" "Arial" ( 900, 500 )
```
`LayerView` is a type sugar to represent the `view` type of layer.
```elm
type alias LayerView cdata userdata data =
Env cdata userdata -> data -> Renderable
```
It will expands to
```elm
Env SceneCommonData UserData -> Data -> Renderable
```
`Env` is a type that represents the _environment_. Layers and components can not only update its own data, it can also view and update the environment (aka. _side effects_).
Its definition is:
```elm
type alias Env common userdata =
{ globalData : GlobalData userdata
, commonData : common
}
```
`GlobalData` is a type that Messenger keeps all the time. It has some key information Messenger needs to use like the screen size. Many Messenger library functions need global data as an argument.
`commonData` is the data shared among all the layers in a scene. It is defined in `Scenes/Home/SceneBase.elm:SceneCommonData`.
Let's take a closer look at `GlobalData`.
```elm
type alias GlobalData userdata =
{ internalData : InternalData
, sceneStartTime : Int
, globalStartTime : Int
, globalStartFrame : Int
, sceneStartFrame : Int
, currentTimeStamp : Time.Posix
, windowVisibility : Visibility
, mousePos : ( Float, Float )
, pressedMouseButtons : Set Int
, pressedKeys : Set Int
, extraHTML : Maybe (Html WorldEvent)
, canvasAttributes : List (Html.Attribute WorldEvent)
, volume : Float
, userData : userdata
, currentScene : String
}
```
Global data won't be reset if users change the scene.
- `globalStartFrame` records the past frames number since the game started
- `globalStartTime` records the past time since the game started, in milliseconds
- `sceneStartFrame` records the past frames number since this scene started
- `sceneStartTime` records the past time since this scene started, in milliseconds
- `userdata` records the data that users set to save
- `extraHTML` is used to render extra HTML tags. Be careful to use this
- `windowVisibility` records whether users stay in this tab/window
- `pressedKeys` records the keycodes that are be pressed now
- `pressedMouseButtons` records the mouse buttons that are pressed now
- `volume` records the volume of the game
- `currentScene` records the current scene name
- `mousePos` records the mouse position, in virtual coordinate
*Note.* Since the `globalStartTime` and `sceneStartTime` are discrete, please use a range rather than a specific time point when judging the time.
Now, run `make` to build the game, and use `elm reactor` or other static file hosting tools (If you use VS Code, you can try using the #link("https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer")[Live Server]), but *DO NOT* directly open the HTML file in the browser because assets won’t be loaded due to CORS.
We use coordinate `(900, 500)` to render the text instead of using HTML tags. This coordinate is not the real pixels on the screen, but the *virtual coordinate* in the game.
The virtual resolution is 1920 × 1080 by default, and the real resolution is determined by the browser window size. The virtual size is defined in `MainConfig.elm`, users may change it to whatever they like.
The `renderText` function wraps the `Canvas.text` which will transform virtual coordinate to the real coordinate. That’s why we also need to send `env.globalData` to that function.
== Order of Rendering <layers>
To understand layers and scenes better, let’s create another scene called "Game"
and add two layers called "A" and "B" in that scene.
```bash
# Create a new scene
messenger scene Game
# Create new layers
messenger layer Game A
messenger layer Game B
```
Now similarly, add these two layers to scene:
```elm
...
, layers =
[ A.layer NullLayerMsg envcd
, B.layer NullLayerMsg envcd
]
```
Then draw a red rectangle on layer A and a blue rectangle on layer B at
the same position. See the result.
Layer B will be on the top of the layer A, which means A is rendered before B.
The order is the same when using `Canvas.group`. The first element in a list will be rendered first and be at the bottom of the scene. Therefore, it is important to organize the order of layers correctly.
However, the order of updating is different from rendering. See @events.
== Message Passing
Recall the `update` function in `ConcreteGeneralModel`.
```elm
update : env -> event -> data -> bdata -> ( ( data, bdata ), List (Msg tar msg sommsg), ( env, Bool ) )
```
However, layers generally do not need `bdata`, so Messenger provides a `ConcreteLayer` type that hides `bdata` (making it a `()`):
```elm
type alias ConcreteLayer data cdata userdata tar msg scenemsg =
{ init : LayerInit cdata userdata msg data
, update : LayerUpdate cdata userdata tar msg scenemsg data
, updaterec : LayerUpdateRec cdata userdata tar msg scenemsg data
, view : LayerView cdata userdata data
, matcher : Matcher data tar
}
```
Here `LayerUpdate` is defined by:
```elm
type alias LayerUpdate cdata userdata tar msg scenemsg data =
Env cdata userdata -> WorldEvent -> data -> ( data, List (Msg tar msg (SceneOutputMsg scenemsg userdata)), ( Env cdata userdata, Bool ) )
```
`LayerUpdateRec` is defined by:
```elm
type alias LayerUpdateRec cdata userdata tar msg scenemsg data =
Env cdata userdata -> msg -> data -> ( data, List (Msg tar msg (SceneOutputMsg scenemsg userdata)), Env cdata userdata )
```
Users can provide the `tar` and `msg` type in `Scenes/Home/SceneBase.elm`.
Now let's consider implementing the example mentioned in @example1. You can either start a new project or use the hello world project.
Create a scene with three layers:
```bash
messenger scene Recursion
messenger layer Recursion A
messenger layer Recursion B
messenger layer Recursion C
```
Add them to the scene (`Scenes/Recursion/Model.elm`):
```elm
import Scenes.Recursion.A.Model as A
import Scenes.Recursion.B.Model as B
import Scenes.Recursion.C.Model as C
...
, layers =
[ A.layer NullLayerMsg envcd
, B.layer NullLayerMsg envcd
, C.layer NullLayerMsg envcd
]
```
To send integers between layers, we need a `IntMsg`. So edit `Scenes/Recursion/SceneBase.elm`:
```elm
type LayerMsg
= IntMsg Int
| NullLayerMsg
```
For layer A, edit `Scenes/Recursion/A/Model.elm`:
```elm
updaterec env msg data =
case msg of
IntMsg x ->
if 0 <= x && x < 10 then
( data, [ Other ( "B", IntMsg (3 * x) ), Other ( "B", IntMsg (10 - 3 * x) ), Other ( "C", IntMsg x ) ], env )
else
( data, [], env )
_ ->
( data, [], env )
```
For layer B, edit `Scenes/Recursion/B/Model.elm`:
```elm
update env evt data =
if env.globalData.sceneStartFrame == 10 then
( data, [ Other ( "A", IntMsg 2 ) ], ( env, False ) )
else
( data, [], ( env, False ) )
```
and
```elm
updaterec env msg data =
case msg of
IntMsg x ->
( data, [ Other ( "A", IntMsg (x - 1) ) ], env )
_ ->
( data, [], env )
```
Finally, for layer C, edit `Scenes/Recursion/C/Model.elm`:
```elm
updaterec env msg data =
case msg of
IntMsg x ->
let
_ =
Debug.log "C received" x
in
( data, [], env )
_ ->
( data, [], env )
```
Now `make` and see the result!
== Initialization <init>
Users may want to initialize the layer or the scene with special data and may even with some environment information.
The data to initialize a layer or a scene must be defined in the layer messages or the scene messages. The layer will be initialized by that message.
We can investigate the `init` function in layer:
```elm
LayerInit SceneCommonData UserData LayerMsg Data
```
which expands to:
```elm
Env SceneCommonData UserData -> LayerMsg -> Data
```
So users can initialize a layer with the environment and a layer message.
Users can create an `Init.elm` file to store the initialization type for scenes, layers and components (`Init.elm` is automatically created for scene prototype). Messenger CLI provides an argument to add that file when creating a scene, a layer, or a component:
```bash
# Use --init or -i
messenger scene ... --init
messenger layer ... --init
messenger component ... --init
```
For example, if you run:
```bash
messenger scene Home --init
```
Then `Scenes/Home/Init.elm` will be created with empty `InitData`.
Users should know the dependency relationship clearly between all the modules, especially the `Init` modules, or they may run into cyclic dependency problems.
#align(center)[
#diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
node((0, 0), [`Scenes.AllScenes`], corner-radius: 0pt),
node((1, 1), [`Scenes.Level1.Model`], corner-radius: 0pt),
node((0, 1), [`Scenes.Home.Model`], corner-radius: 0pt),
node((0, 2), [`Lib.Base`], corner-radius: 0pt),
node((1, 2), [...], corner-radius: 1pt),
node((0, 3), [`Scenes.Home.Init`], corner-radius: 0pt),
node((1, 3), [`SceneProtos.Game.Init`], corner-radius: 0pt),
node((0, 4), [`Scenes.Home.SceneBase`], corner-radius: 0pt),
node((1, 4), [...], corner-radius: 1pt),
node((0, 6), [`Scenes.Home.Components.ComponentBase`], corner-radius: 0pt),
node((0, 5), [`Scenes.Home.Layer1.Init`], corner-radius: 0pt),
node((1, 5), [`Scenes.Home.Layer2.Init`], corner-radius: 0pt),
node((-0.5, 7), [`Scenes.Home.Components.Enemy.Init`], corner-radius: 0pt),
node((0.7, 7), [`Scenes.Home.Components.Player.Init`], corner-radius: 0pt),
edge((0, 0), (0.9, 1), "->"),
edge((0, 0), (0, 1), "->"),
edge((1, 1), (1, 2), "->"),
edge((0, 1), (0, 2), "->"),
edge((0, 2), (0.9, 3), "->"),
edge((1, 3), (1, 4), "->"),
edge((0, 2), (0, 3), "->"),
edge((0, 3), (0, 4), "->"),
edge((0, 4), (0, 5), "->"),
edge((0, 4), (0.9, 5), "->"),
edge((0, 5), (0, 6), "->"),
edge((0, 6), (-0.7, 7), "->"),
edge((0, 6), (0.7, 7), "->"),
node(enclose: ((-0.5, 0), (1, 1), (1, 0)), stroke: (paint: blue, dash: "dashed"), inset: 8pt),
node((1, 0), text(fill: blue)[Models], stroke: none),
node(enclose: ((-1, 2), (3, 7.5), (0, 2)), stroke: (paint: blue, dash: "dashed"), inset: 8pt),
node((-1, 2), text(fill: blue)[Base and Init], stroke: none),
)
]
In the above diagram, A $->$ B means A _may_ depend on B, and B *must not* depend on A.
As you can see, all the models can depend on all the `Base` and `Init`. So it's quite free to import any types you defined.
However, in the "Base and Init" zone, you should carefully handle the dependency. The rule is: *upper level may depend on lower levels*. *Never* use `Lib.Base` in any `Base` or `Init`. If necessary, use a type parameter and instantiate it in models (see the @sceneproto example). |
|
https://github.com/jomaway/typst-bytefield | https://raw.githubusercontent.com/jomaway/typst-bytefield/main/lib/utils.typ | typst | MIT License | #import "asserts.typ": *
// insert a value into an dict and return the dict
#let dict-insert-and-return(dict, key, value) = {
assert.eq(type(dict), dictionary);
assert.eq(type(key), str);
dict.insert(key,value);
return dict
}
#let get-field-type(field) = {
assert-bf-field(field);
return field.at("field-type", default: none);
}
/// Check if a given field is a bf-field
#let is-bf-field(field) = {
assert.eq(type(field), dictionary)
field.at("bf-type", default: none) == "bf-field"
}
/// Check if a given field is a data-field
#let is-data-field(field) = {
assert-bf-field(field);
field.at("field-type", default: none) == "data-field"
}
/// Check if a given field is a note-field
#let is-note-field(field) = {
assert-bf-field(field);
field.at("field-type", default: none) == "note-field"
}
/// Check if a given field is a header-field
#let is-header-field(field) = {
assert-bf-field(field);
field.at("field-type", default: none) == "header-field"
}
/// Return the index of the next data-field
#let get-index-of-next-data-field(idx, fields) = {
let res = fields.sorted(key: f => f.field-index).find(f => f.field-index > idx and is-data-field(f))
if res != none { res.field-index } else { none }
}
/// Check if a field spans over multiple rows
#let is-multirow(field, bpr) = {
// if range.start is at the beginn of a new row
if (calc.rem(field.data.range.start, bpr) != 0) { return false }
// field size is multiple of bpr
if (calc.rem(field.data.size, bpr) != 0) { return false }
return true
}
/// calculates the max annotation level for both sides
#let get-max-annotation-levels(annotations) = {
let left_max_level = -1
let right_max_level = -1
for field in annotations {
assert-bf-field(field)
let (side, level, ..) = field.data;
if (side == left) {
left_max_level = calc.max(left_max_level,level)
} else {
right_max_level = calc.max(right_max_level,level)
}
}
return (
pre-levels: left_max_level +1,
post-levels: right_max_level +1,
)
}
/// Check if given dict is a bf-cell
#let is-bf-cell(cell) = {
cell.at("bf-type", default: none) == "bf-cell"
}
/// Check if bf-cell is a data cell.
#let is-data-cell(cell) = {
cell.at("cell-type", default: none) == "data-cell"
}
/// Check if bf-cell is a note cell.
#let is-note-cell(cell) = {
cell.at("cell-type", default: none) == "note-cell"
}
/// Check if bf-cell is a header cell.
#let is-header-cell(cell) = {
cell.at("cell-type", default: none) == "header-cell"
}
/// Check if a string is empty
#let is-empty(string) = {
assert.eq(type(string), str, message: "expected string, found " + type(string))
string == none or string == ""
}
/// Check if a string or content is not empty
#let is-not-empty(string) = {
// assert.eq(type(string), str, message: strfmt("expected string, found {}",type(string)))
if (type(string) == str) {
return string != none and string != ""
} else if (type(string) == content) {
return string != []
}
}
/// Return the current index of a field or cell
#let get-index(f) = {
if is-bf-field(f) {
return f.field-index
} else if is-bf-cell(f) {
return f.cell-index
} else {
none
}
}
/// Check if in a certain grid
#let is-in-main-grid(cell) = {
center == cell.position.grid
}
/// Check if in a certain grid
#let is-in-left-grid(cell) = {
left == cell.position.grid
}
/// Check if in a certain grid
#let is-in-right-grid(cell) = {
right == cell.position.grid
}
/// Check if in a certain grid
#let is-in-header-grid(cell) = {
top == cell.position.grid
}
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/user_func_pos.typ | typst | Apache License 2.0 |
#let tmpl3(font, stroke) = text(font: font, stroke: stroke)[]
#tmpl3(("Agency FB"),/* position */)
|
https://github.com/fontlos/FengruCup-template | https://raw.githubusercontent.com/fontlos/FengruCup-template/main/main.typ | typst | MIT License | #import "template.typ": *
#show: frb.with(
title: "\"冯如杯\" 竞赛主赛道项目论文 Typst 模板",
subtitle: "基于 Typst 的论文模板",
header: "北京航空航天大学“冯如杯”竞赛主赛道参赛作品论文模板",
author: "Fontlos",
abstract-CN: [
本 Typst 模板是北京航空航天大学大学第三十四届 "冯如杯" 竞赛主赛道论文模板, 相比 Word 排版更加强大, 相比 Latex 模板更加轻量方便快捷
],
keyword-CN: [
冯如杯, 模板, Typst
],
abstract-EN: [
This Typst template is made for the main track paper of the 34rd Fengru Cup Competition of Beijing University of Aeronautics and Astronautics (BUAA), which is more powerful compared to Word, and lighter and easier to use compared to the Latex template.
],
keyword-EN: [
Fengru Cup, Template, Typst
],
bibliography-file: "refs.bib",
auto-num-title: true,
)
= Typst 简介
Typst 是可用于出版的可编程标记语言, 拥有变量, 函数与包管理等现代编程语言的特性, 注重于科学写作 (science writing), 定位与 LaTeX 相似. 相比于 Latex, 有语法简洁, 编译速度快, 环境搭建简单等优势
= 使用方法
所有样式已参照北京航空航天大学大学第三十四届 "冯如杯" 竞赛主赛道论文格式要求制定, 使用者只需专注于文字编辑即可
== 环境配置
=== 编译器及必要文件准备
- 从 #link("https://github.com/typst/typst/releases/")[*Github Release*] 下载对应系统打包好的可执行文件并加入环境变量
- 确保电脑上装有宋体(SimSun), 华文中宋体(STZhongsong), 黑体(SimHei), 华文新魏(STXinwei), Times New Roman 等字体(不确定是否安装可输入 `typst fonts` 命令查看)
- `git clone` 或 下载本储存库
=== 编辑器配置
推荐使用 *Vscode* 并搭配 *Typst LSP* 和 *Typst Preview* 插件
== 模板使用
基本语法详情参照 #link("https://typst.app/docs/reference")[#bold("官方文档")], 这里仅介绍一下如何使用模板
```typ
#import "template.typ": frb
#show: frb.with(
title: "Title",
subtitle: "Subtitle",
header: "Header",
author: none,
abstract-CN: [中文摘要],
keyword-CN: [关键词1, 关键词2],
abstract-EN: [English Abstract],
keyword-EN: [Keyword1, Keyword2],
bibliography-file: "refs.bib",
bibliography-title: "参考文献",
bibliography-style: "gb-7714-2015-numeric",
auto-num-title: true,
)
= First title
== Second title
=== Third title
Your article
```
- `title`: 论文标题, 显示在封面页, 必填
- `subtitle`: 论文副标题, 可以留空, 无需手动写出破折号
- `header`: 论文页眉内容
- `author`: 虽然作者根据冯如杯规则理应留空或者填写 `none`, 但还是加上了
- `abstract-CN`: 中文摘要, 直接在中括号内填写即可, 内容要求同正文相同, 下面的 `abstract-EN`同理
- `keyword-CN`: 中文关键词, 直接在中括号内填写即可, 用逗号隔开, 下面的 `abstract-EN`同理
- `bibliography-file`: 参考文献目录文件是一个 `.bib` 文件, 具体写法可以参照下面的内容以及本储存库根目录的 `refs.bib`
- `bibliography-title`: 参考文献目录标题
- `bibliography-style`: 参考文献样式
- `auto-num-title`: 按照冯如杯的规范对标题进行自动标号, 默认启用, 如果你有需要也可以关闭此功能手动标号
=== 样式说明
对于 1, 2, 3 级标题, 模板已经适配了对应的样式
模板已经做好了段首自动缩进, 输入时仅需要空一行作为分段即可
但是 Typst 目前仅能给连续段落除第一段以外的段落进行段首缩进, 所以会打破段落连续性的元素可能导致缩进失败
在本模板中, 以下会导致段落连续性被打破的元素已经做好了段首缩进适配
- Heading
- List
- Numbered list
- Table
- Math block
- Code block
- `img` function
对于其他元素, 可以通过 `#indent` 或 `#h(2em)` 手动添加缩进
对于数学表达式和代码块, 其字体使用内建字体, 如果需要替换请直接修改模板代码
目前 Typst 对中文字体样式的支持不够完善, 因此模板内提供了一些函数进行辅助, 包括用于加粗文本的 `bold` 函数, 使文本斜体的 `italic` 函数, 以及专门针对中文字符的版本, 如果你希望可以通过原生语法实现中文字体加粗, 可以通过 `#show: bold-rule` 来开启全局规则, 斜体同理, 但可能会产生一些冲突和难以排查的错误
注: `bold` 函数可能会与数学表达式块中的同名函数冲突, 可以通过别名导入解决此问题
=== 内建函数说明
只展示最基础的用法, 详细说明见模板源码
- `img`: 添加一张带有说明的图片
- 用法: `#img(path:"path/to/image")[caption]`
- 可选参数:
- `width`: 图片宽度, 接受百分制参数
- `num`: 是否启用图片标号, 默认关闭
- 下面的函数针对于非英文字符
- `bold`: 加粗文字
- 用法: `#bold[Text]`
- 可选参数:
- `reg`: 正则表达式
- `base-weight`: 字重, 接受 `em` 单位的参数
- `bold-cn`: 针对中文的加粗, 参考 `bold`
- `bold-rule`: 启用加粗规则, 使你能够通过 `**` 加粗文字
- 用法: `#show: bold-rule`
- `bold-cn-rule`
- `italic`: 斜体文字
- 用法: `#italic[Text]`
- 可选参数:
- `reg`: 正则表达式
- `ang`: 倾斜角, 弧度制
- `spacing`: 两侧空白
- `italic-rule`: 启用斜体规则, 使你能够通过 `__` 倾斜文字
- 用法: `#show: italic-rule`
=== 参考文献目录文件
一个 `.bib` 文件通常包含若干条以下内容
```bib
@article{refa,
author = {Author},
title = {Title},
journal = {Journal},
volume = {1},
pages = {1--2},
year = {2024},
}
@book{refb,
author = {Author},
title = {Title},
edition = {Edition},
address = {Address},
publisher = {Publisher},
year = {2024},
}
@phdthesis{refp,
author = {Author},
title = {Title},
school = {School},
year = {2024},
}
```
这三种分别代表文章, 书籍, 博士论文. `refa` 等代表引用名称, 可以在正文中通过 `@refa` 在具体位置添加引用@refa @refb @refp. 其他参数很容易理解. 最后将在文章末尾添加参考文献目录. 其他参数和类型请自行参阅 LaTex BibTex标准
= 总结
无论是对比 Word 还是 Latex, Typst 都是论文编写更加高效更加现代化的方式, 值得推广让更多人学习使用 |
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/layout/abstract.typ | typst | MIT License | #let abstract(body, lang: "en") = {
let title = (en: "Abstract", de: "Zusammenfassung")
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: lang
)
set par(
leading: 1em,
justify: true
)
// --- Abstract ---
v(1fr)
align(center, text(font: body-font, 1em, weight: "semibold", title.at(lang)))
body
v(1fr)
}
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/AMT/docs/4-JDBCandJPA/java-presistence-api.typ | typst | #import "/_settings/typst/template-note.typ": conf
#show: doc => conf(
title: [
Java Persistence API (JPA)
],
lesson: "AMT",
chapter: "4. JDBC and JPA",
definition: "Definition",
col: 1,
doc,
)
= Object Relational Mapping (ORM) pour Java
L'Object Relational Mapping (ORM) est une technique permettant de faire correspondre des objets à des bases de données relationnelles. L'API Java Persistence (JPA) est l'API Java utilisée pour cela et permet aux applications Java d'interagir avec une base de données. Des runtimes JPA comme Hibernate sont des implémentations de l'API JPA, souvent basées sur JDBC. JPA est une API de haut niveau qui réduit le code répétitif.
= POJO et JavaBeans
Un POJO (Plain Old Java Object) est un objet Java classique sans conventions spécifiques. Les JavaBeans, quant à eux, respectent certaines conventions :
- Un constructeur par défaut public.
- Des champs privés.
- Des getters et setters publics.
- L'implémentation de l'interface Serializable.
Les JavaBeans sont souvent utilisés dans les frameworks pour leur facilité de manipulation via la réflexion.
= Entités JPA
Une entité JPA est une classe Java représentant une entité en base de données. Elle ressemble à une classe JavaBean et est annotée avec `@Entity`. L'implémentation de `Serializable` n'est requise que dans certains cas spécifiques. Exemple :
```java
@Entity
public class Person {
@Id
@Column(name = "id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
}
```
= Entity Manager
L'Entity Manager gère les entités JPA : création, persistance et suppression. Il est souvent injecté avec l'annotation `@Inject`. Exemple d'utilisation :
```java
@ApplicationScoped
public class PersonService {
@Inject
private EntityManager em;
@Transactional
public void create(Person person) {
em.persist(person);
}
}
```
= Annotations d'entités
Les annotations sont utilisées pour mapper les classes et champs aux tables et colonnes de la base de données :
- `@Entity` pour marquer une classe comme entité.
- `@Id` pour marquer la clé primaire.
- `@Column` pour mapper les champs aux colonnes.
- `@OneToOne`, `@OneToMany`, `@ManyToOne`, `@ManyToMany` pour les relations entre entités.
- `@JoinColumn` pour les clés étrangères.
- `@GeneratedValue` pour générer des clés primaires.
- `@Enumerated` pour mapper un enum.
- `@Embeddable` et `@Embedded` pour mapper des objets embarqués.
Les possibilités de JPA vont bien au-delà de ce cours. Il est conseillé de consulter la documentation de JPA et des runtimes comme Hibernate.
= Résumé des annotations JPA
== `@OneToOne`
L'annotation `@OneToOne` définit une relation un-à-un entre deux entités, où une instance d'une entité est associée à une seule instance d'une autre entité. Cette relation est souvent représentée par une clé étrangère dans l'une des tables, permettant une liaison directe entre les deux. Elle peut être unidirectionnelle (une seule entité connaît l'autre) ou bidirectionnelle (les deux entités se connaissent mutuellement).
== `@OneToMany`
L'annotation `@OneToMany` décrit une relation un-à-plusieurs, où une entité est associée à plusieurs instances d'une autre entité. La table correspondant à l'entité "enfant" possède généralement une clé étrangère pointant vers l'entité "parent". Ce type de relation est souvent utilisé pour modéliser des scénarios de type parent-enfants, comme un département avec plusieurs employés.
== `@ManyToOne`
L'annotation `@ManyToOne` est l'inverse de `@OneToMany`. Elle représente une relation plusieurs-à-un, où plusieurs instances d'une entité sont liées à une seule instance d'une autre entité. Une clé étrangère dans la table de l'entité "enfant" pointe vers l'entité "parent". Ce type de relation est couramment utilisé lorsque de nombreux objets partagent un élément commun, comme plusieurs employés dans un même département.
== `@ManyToMany`
L'annotation `@ManyToMany` établit une relation plusieurs-à-plusieurs entre deux entités. Chaque entité peut être liée à plusieurs instances de l'autre, ce qui crée une relation réciproque. Cette relation est souvent implémentée à l'aide d'une table de jointure qui stocke les associations entre les deux tables. Par exemple, un étudiant peut être inscrit à plusieurs cours, et chaque cours peut avoir plusieurs étudiants.
== `@JoinColumn`
L'annotation `@JoinColumn` est utilisée pour spécifier la colonne de jointure dans une relation entre deux entités. Elle indique la colonne de la base de données qui sert de clé étrangère pour lier une entité à une autre. Elle est souvent associée à des relations telles que `@ManyToOne` ou `@OneToOne`, afin de définir explicitement la colonne de référence dans la base de données.
== `@Embeddable` et `@Embedded`
L'annotation `@Embeddable` marque une classe comme étant intégrable dans une autre entité. `@Embedded` est utilisée pour indiquer que cette classe intégrée fait partie d'une autre entité. Ces annotations sont utiles pour encapsuler des groupes de champs qui sont réutilisés dans plusieurs entités, sans créer une table distincte. Elles permettent une modularisation des entités tout en évitant des relations complexes de type clé étrangère. |
|
https://github.com/TheRealKaup/Journal | https://raw.githubusercontent.com/TheRealKaup/Journal/main/draft/cosmological_argument_book_review.typ | typst | #set text(dir: rtl, font: "<NAME>", size: 12pt, hyphenate: false)
#set par(justify: true)
#set page(
paper: "a4",
numbering: "1 / 1"
)
#set heading(numbering: "1.")
#set outline(indent: auto)
#set quote(block: true)
#set smartquote(enabled: true)
// LTR footnotes in RTL document
#show footnote.entry: set text(dir: ltr)
#set footnote.entry(separator: text(dir: ltr)[#line(length: 30%, stroke: 0.5pt)])
// Default dark mode colors
#let colors = (
page: color.black,
text: color.white,
link: rgb(255, 127, 255),
line: color.white,
)
// True = switch to light mode
#if true {
colors = (
page: color.white,
text: color.black,
link: rgb(0, 0, 191),
line: color.black,
)
}
// Set colors
#set page(fill: colors.page)
#set text(fill: colors.text)
#show link: set text(colors.link)
#show ref: set text(colors.link)
#show outline.entry: set text(colors.link)
#show footnote: set text(colors.link)
#set line(stroke: colors.line)
// Better quotes
#show quote: it => block(spacing: 1.2em, stroke: (right: colors.line))[
#block(inset: (right: 1.2em, left: 1.2em))[#it.body
#if it.attribution != none [
(#it.attribution)
]
]
]
#align(center)[
#text(18pt, weight: "bold")[
"5 ראיות לקיום אלוהים", "ראיה 1: סיבת היקום" - ביקורת
#text(fill: red)[
טיוטה ב'
]
]
איתן קאופמן
(AKA Kaup) - #link("mailto:<EMAIL>")
This work is licensed under #link("https://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1")[Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International]
]
#outline(title: [תוכן העניינים])
#pagebreak()
= הקדמה
#strong[
שימו לב: זוהי גרסת טיוטה. עשויות להיות כאן טעויות רבות. במידה ונמצאה טעות, בבקשה תיידעו אותי לגביה.
]
במאמר זה אציג ביקורת על הספר "ראיות לקיום אלוהים" שנכתב על ידי שמעון מאיר (מכאן ואילך מאיר), פרק "ראיה 1: סיבת היקום" (עמודים 29 עד 59). הפרק זמין בחינם בתור ספר מוקלט
#footnote[https://www.youtube.com/watch?v=ib09WS9Mdxc]
#box[
וpdf
]
#footnote[https://drive.google.com/file/d/19dmk9dojlUlmq9Pr5sfXXJEOu8_gzyci/view].
במאמר זה לא תמצאו הוכחה שאלוהים לא קיים, אלא רק הפרכה לטיעון הקוסמולוגי שאלוהים כן קיים
#footnote[https://en.wikipedia.org/wiki/Cosmological_argument].
לצורך דיון, אנו מכירים בלוגיקה קלאסית
#footnote[https://en.wikipedia.org/wiki/Classical_logic]
וראליזם
#footnote[https://en.wikipedia.org/wiki/Philosophical_realism]
במידה שתואמת לספר המבוקר.
לאורך המאמר אתייחס לשני סוגי מודליות
#footnote[https://en.wikipedia.org/wiki/Modality_(linguistics)]\;
לוגיקה ופיזיקה. טענות לוגיות בהכרח נכונות פיזיקלית, אך טענות פיזיקליות לא בהכרח נכונות לוגית
#footnote[https://en.wikipedia.org/wiki/Metaphysical_necessity],
לדוגמה:
- פיזיקלית, בעלי חיים ששורדים ללא אנרגיה הם בלתי אפשריים, אך לוגית אפשריים.
- פיזיקלית, כדור הארץ חייב להסתובב סביב השמש, אך לוגית הוא יכול להישאר במקום.
- לוגית, דבר לא יכול להתקיים ולא להתקיים בו זמנית #footnote[https://en.wikipedia.org/wiki/Law_of_noncontradiction], ולכן גם פיזיקלית.
- לוגית, משהו יכול להתקיים או לא להתקיים #footnote[https://en.wikipedia.org/wiki/Law_of_excluded_middle], ולכן גם פיזיקלית.
פעמים רבות אשתמש במונח "מטאפיזיקה" כמעט כמו תחום נוסף שכולל מה שלוגי אך לא פיזיקלי. אך, "מטאפיזיקה" רק מרצה נוחות לשונית; היא מארחת ישויות לא פיזיקליות, עולמות אפשריים, הדברים המעצבים את התחום הפיזיקלי (כמו חוקי הפיזיקה), וכדומה. במקום להגיד "עובדה לוגית אך לא פיזיקלית", אגיד "עובדה מטאפיזיקלית". מאחר ולא גילינו מידע מטאפיזיקלי אמפירי, כלומר ידע אפוסטריורי, רוב השיחות על דברים מטאפיזיקליים (כולל האחת הזו) מתבססות על טענות אפריוריות
#footnote[https://en.wikipedia.org/wiki/A_priori_and_a_posteriori],
אולם כאלו שבאופן שגוי קובעות עובדות מטאפיזיקליות על בסיס מודליות פיזיקלית, ולכן הן לא משכנעות.
"היקום" דורש הגדרה. עצם כך שניתן לתת לו אפיונים משל עצמו, כמו נקודת התחלה וסיבה לקיומו, הופך אותו לנושא. באופן שתואם לספר, היקום:
/ מורכב: ממה שלא ניתן להסביר לפי חוקי הפיזיקה; המרחב, הזמן וחוקי הפיזיקה עצמם.
/ כולל: את מה שניתן להסביר לפי חוקי הפיזיקה; מצבם הנוכחי של הדברים הפיזיקליים.
דבר הוא פיזיקלי אם ניתן להסביר אותו לפי חוקי הפיזיקה, והוא מטאפיזיקלי אם לא ניתן כי הם נוגדים או לא מספקים. לדוגמה, חוקי הפיזיקה לא יכולים לעזור לנו להסביר את נוכחותם של חוקי הפיזיקה עצמם (בעקבות סתירה שנובעת מכללי סיבתיות פיזיקלית לפיהם דבר לא יכול להוות בעצמו את סיבתו, ומלכתחילה חוקי הפיזיקה מתייחסים לשינוי מצבם של דברים ולא יצירתם), ולכן הם מטאפיזיקליים, ההסבר להם אינו פיזיקלי, ולא ניתן להניח שהם פועלים לפי מודליות פיזיקלית.
#pagebreak()
= סקירה
== יש סיבה
=== קביעת עיקרון הסיבתיות על היקום
#quote(attribution: [עמודים 30, 31])[
[...] ההנחה הבסיסית שלכל דבר שאנו רואים סביבנו יש סיבות מדויקת לכך שהוא בדיוק כפי שהוא, נכונה בנוגע לכל מה שסביבי ובעצם לכל דבר. הנחה זו נקראת: עקרון הסיבתיות. כלומר שהמציאות פועלת באופן של סיבה ותוצאה. בעיקרון זה יש הכללה אמפירית המבוססת על הניסיון היומיומי והמדעי שלנו, וביסודו ישנה אינטואיציה חזקה שלפיה לא ייתכן ש"יש" יופיע מתוך "אין". [...] אם יש סיבה מדויקת לקיומו של כל פרט שהחל להיות בעולם, נדמה שגם היקום כולו צריך סיבה לקיומו.
]
בחלק זה נקבע על היקום עיקרון הסיבתיות
#footnote[https://en.wikipedia.org/wiki/Principle_of_sufficient_reason],
שהוא חוק פיזיקלי לפיו כל דבר בעל התחלה דורש סיבה לקיומו. קביעה זו שגויה, הרי היקום מטאפיזיקלי, לוגית דבר יכול להתקיים ללא סיבה, והכרחיות פיזיקלית לא מובילה להכרחיות לוגית. חד-הכיווניות הזו עשויה להישמע יותר אינטואיטיבית עם דוגמה שכוללת חוק פיזיקלי אחר: כוח המשיכה נקבע פיזיקלית ולא לוגית, לכן לא ניתן לטעון שהוא בהכרח פועל על היקום.
=== שלילת האינסוף מהתחום הפיזיקלי
#quote(attribution: [עמוד 37])[
התוצאה היא שאנו ניצבים בפני סתירה: מצד אחד כל החדרים מלאים, אך מצד שני תמיד יהיו חדרים פנויים לאינסוף אורחים.
]
זו למעשה סתירה שנוצרה עקב תיאור מסולף של מלון הילברט
#footnote[https://en.wikipedia.org/wiki/Hilbert%27s_paradox_of_the_Grand_Hotel]
ולא בעקבות רעיון האינסוף או יישום פיזיקלי שלו. במלון הילברט לא "כל החדרים מלאים", אלא יש "אינסוף חדרים מלאים" ו-"אינסוף חדרים פנויים", שביחד שווים לקיבולת המלון; אינסוף חדרים, ולכן אין סתירה.
#quote(attribution: [עמוד 37])[
אך גם אם במקצוע המתמטיקה אפשר לעסוק באינסוף ולהבין אותו במגוון אופנים, במציאות הממשית אנו מגיעים לאַבסוּרד, כלומר למצבים שאינם מתיישבים עם ההיגיון ועם השכל הישר.
]
האבסורד במלון הילברט נוצר בעקבות הניסיון להציב אינסוף בין שתי נקודות (הפקיד לא באמת מסוגל להגיע בעצמו לכל חדר, אחרת יש סוף לאינסוף). לכן, יישום פיזיקלי של אינסוף חסר נקודת התחלה או סוף לא נשלל.
=== קביעת המפץ הגדול כנקודת התחלת היקום
#quote(attribution: [עמודים 40, 41])[
מתברר שהיקום הוא לא אינסופי, אלא הזמן והמרחב עצמם הופיעו בנקודה בודדת בעבר. מסקנה שהפכה לקונצנזוס מדעי וקיבלה את הכינוי "המפץ הגדול". על פי תאוריית המפץ הגדול, החומר והאנרגיה ביקום כולו הופיעו מנקודה בודדת בעבר לפני כ-13.8 מיליארד שנים. [...] למיטב הידע המדעי, לזמן ולמרחב שבהם אנו חיים הייתה התחלה. היקום החל להתקיים.
]
תאוריית המפץ הגדול מסבירה את הארגון של היקום (לדוגמה, למה הגלקסיות מתרחקות אחת מהשנייה), ולא שלזמן והמרחב עצמם נקודת התחלה. לדוגמה, לפני המפץ הגדול יכל להיות ארגון אחר של היקום שהסתיים במפץ הגדול שהוביל לארגון הנוכחי. לפני הארגון הקודם היה ארגון נוסף שהוביל אליו, וכן הלאה, לנצח, רגרסיה אינסופית.
=== שלילת היקום כעובדה גסה
#quote(attribution: [עמוד 45])[
כאשר אנו מסיקים שסוקרטס הוא בן תמותה, אנו עושים זאת על בסיס ההנחות שכל בני האדם הם בני תמותה ושסוקרטס הוא אדם. היסק זה הוא רציונלי מפני שההנחות הן אמיתיות והמסקנה תקפה מבחינה לוגית. אבל אם ייתכנו עובדות גסות, איננו צריכים בכלל הנחות אמיתיות והיסקים לוגיים. אנו יכולים להניח שסוקרטס הוא בן תמותה כעובדה גסה על המציאות, או אפילו להניח שהמסקנה ההפוכה שסוקרטס אינו בן תמותה גם היא עובדה גסה על המציאות. אם ייתכנו עובדות גסות, אז ההיסקים שלנו כבר אינם תקפים, ואי אפשר לסמוך על החשיבה שלנו כשאנחנו רוצים להגיע להסברים הטובים ביותר. כלומר, הטענה שהופעת היקום היא עובדה גסה שאינה צריכה סיבה חורגת מהלוגיקה האנושית, ולכן קשה מאוד לקבלה כטענה אמיתית.
]
הטיעון פה אינו ברור במיוחד. ייתכן והאנלוגיה היא בין להניח ש"סוקרטס הוא בן תמותה" כעובדה גסה
#footnote[https://en.wikipedia.org/wiki/Brute_fact]
לבין להניח ש"היקום קיים" כעובדה גסה. קודם כל, אף אחד לא מניח שהיקום עובדה גסה, אלא רק מעלה את הרעיון כאפשרות. אני מסכים שאין לנו הוכחה עבורה ולכן אין זה רציונלי להאמין בה, אך בתור אפשרות היא רציונלית לחלוטין, מאחר והאנלוגיה המדוברת לא סימטרית; ידוע לנו שבהכרח ניתן להסביר את ההנחה "סוקרטס הוא בן תמותה" (לדוגמה, בעזרת הידע שלנו בביולוגיה), ולכן הטענה שלא ניתן להסביר אותה (כלומר, שההנחה עובדה גסה) אינה רציונלית, הרי היא מכחישה את המדע, ופונדמנטלית את עיקרון הסיבתיות. אך, לא ידוע לנו שבהכרח ניתן להסביר את ההנחה "היקום קיים", מאחר ואין לנו סיבה להאמין שיש לה הסבר (עיקרון הסיבתיות פיזיקלי, בזמן שהיקום מטאפיזיקלי).
לגבי תקופתן של עובדות גסות, לאחר קריאות רבות עדיין לא הצלחתי להבין איך הדוגמה מראה שאנו יכולים להניח את ההפוך. אנו יכולים להבחין במשהו בלי לדעת את הסברו, אך עדיין לדעת די טוב שהוא נכון, כי נכונותו מוצבת ממש לפנינו. אם היינו מניחים שקיומו של היקום עובדה גסה, איך לפיכך יכולנו להניח שהיקום לא קיים? אם לצד היתרה בחשבון הבנק שלי מופיע אפס, והייתי מניח מטיפשותי שהמספר עובדה גסה, הייתי יכול במקום להניח שמוצג שם מספר אחר?
=== שלילת יקום הכרחי וקביעתו קונטינגנטי
#quote(attribution: [עמוד 46])[
אני, וגם את ואתה, כולנו יצורים תלויים. קוֹנְטִינְגֶנְטִיִּים. יכולנו להתקיים, ובמידה רבה יכולנו לא להתקיים.
]
אינדטרמיניזם
#footnote[https://en.wikipedia.org/wiki/Indeterminism]
בתור הנחת יסוד.
#quote(attribution: [עמודים 47, 48])[
[...] מכיוון שהיקום אדיר בגודלו מעבר לכל דמיון, הרעיון שהוא הכרחי נשמע מושך, אבל מחשבה מעמיקה יותר תביא למסקנה שיש סיבות טובות לחשוב שאין זה כך. [...] גילו המופלג, גודלו ומורכבותו האדירה של היקום אינם משנים דבר בנוגע לשאלה מדוע הוא קיים. היקום כולו נותר קונטינגנטי ועדיין צריך הסבר.
]
איני רואה למה גודלו של היקום יכול להוות סיבה להכרחיותו, ולכן לא מבין למה הוחלט להתייחס לטענה הלא קוהרנטית הזו. אך, לקבוע לפיכך שהיקום קונטינגנטי
#footnote[https://en.wikipedia.org/wiki/Contingency_(philosophy)]
זו דילמה שקרית
#footnote[https://en.wikipedia.org/wiki/False_dilemma],
הרי האפשרות שהיקום הכרחי לא נשללה.
#quote(attribution: [עמוד 48])[
כל מה שהחל להתקיים דורש הסבר לקיומו, ומה שהחל להתקיים אינו יכול להיות הכרחי. ומיטב הידע המדעי מצביע על כך שהיקום אינו יוצא דופן מבחינה זו.
]
לפי דעתי, על בסיס "מה שהחל להתקיים אינו יכול להיות הכרחי", הכוונה היא להוסיף לצד עיקרון הסיבתיות מעין "עיקרון קונטינגנטיות". כבר הבהרתי מקודם שמודליות פיזיקלית אינה מספקת להסקה מטאפיזיקלית, אך בנוסף לכך, מאיר טועה לגבי היות הדברים ביקום קונטינגנטיים: מאחר וזה אפשרי שהיקום הכרחי $P_1$, ובגלל שזה אפשרי שהיקום דטרמיניסטי
#footnote[https://en.wikipedia.org/wiki/Determinism]
$P_2$, אז זה אפשרי שהדברים ביקום הכרחיים גם הם $Q$, כלומר, אנחנו אפילו לא יודעים האם הדברים ביקום קונטינגנטיים, ולכן מלכתחילה האינדוקציה חסרת ביסוס.
=== שלילת רגרסיה אינסופית
#quote(attribution: [עמוד 50])[
ההנחה שהיו גורמים פיזיקליים למפץ הגדול מניחה גם שהיו אירועים בזמן ובמרחב שקדמו למפץ הגדול. ואם לא הופיע אחד מהם מתישהו יֵש מאַיִן, אז כל שנותר לנו להניח הוא שהייתה סיבה פיזיקלית לסיבה של המפץ הגדול. וסיבה פיזיקלית לסיבה של הסיבה של המפץ הגדול, וכך הלאה לנצח. כלומר, אינסוף סיבות אחורה בזמן, שהובילו בסופו של דבר ליצירת אותו גנרטור יקומים שיצר את היקום שלנו. [...] אך כפי שעזר לנו להבין הפקיד החרוץ בקבלה של המלון האינסופי, אי אפשר לקבל את קיומו של אינסוף ממשי מכיוון שהוא מוביל אותנו לאבסורד ולמצבים שסותרים כל היגיון ושכל ישר.
]
מאיר מנסה להוכיח שרגרסיה אינסופית
#footnote[https://en.wikipedia.org/wiki/Infinite_regress]
בלתי אפשרית $Q$ כי ליקום נקודת התחלה $P$, על בסיס כך שאם ליקום נקודת התחלה $P$ אז רגרסיה אינסופית בלתי אפשרית $Q$, מבלי להוכיח שליקום נקודת התחלה $P$ (הנחת המבוקש
#footnote[https://en.wikipedia.org/wiki/Begging_the_question]);
בחלק בו מאיר שלל את האינסוף מהיקום הוא הניח נקודת התחלה וסוף, ועכשיו הוא משתמש במסקנה שיצר כדי להראות שיש נקודת התחלה ("אינסוף סיבות אחורה בזמן, שהובילו בסופו של דבר..."). "ליקום נקודת התחלה" $P$ ↔ "אין רגרסיה אינסופית" $Q$. הנקודה היא שללא נקודת התחלה אין שום כשל לוגי גלוי בהצבת אינסוף לפני נקודת הזמן הנוכחית.
בנוסף, גם אם ליקום נקודת התחלה, אפשר לצאת מהתחום הפיזיקלי ולטעון שלפני הייתה רגרסיה אינסופית של יקומים, כאשר כל יקום בסיומו התחיל את היקום הבא בדרכים מטאפיזיקליות.
=== מסקנה סופית שליקום סיבה
#quote()[
עד כה ניסינו לתת חמישה הסברים לקיומו של היקום, והסקנו שכולם הסברים חלשים מדי, שאינם מתיישבים עם השכל הישר:
1. לא ייתכן שמשהו יופיע מכלום.
2. הסבר לפרטים אינו פוטר מהסבר למכלול.
3. עובדות גסות אינן מספקות הסבר מספק.
4. היקום הוא אפשרי ולא הכרחי.
5. דמיון על שרשרת סיבות נצחית שקדמה למפץ הגדול רק מחזירה אותנו לאבסורד שבאינסוף. (עמוד 51)
]
כתגובה:
+ עיקרון הסיבתיות הינו חוק פיזיקלי שמצבו המטאפיזיקלי לא ידוע, כי לוגית אינו מוכרח.
+ מסכים (הפרטים; מצב תכולת היקום. המכלול; היקום).
+ עובדות גסות לפי הגדרה לא מספקות הסבר, שהוא מתבקש פיזיקלית, לא לוגית.
+
- דלימה שקרית בה היקום קונטינגנטי כי אין הוכחה להכרחיותו.
- הנחה חסרת בסיס שהיקום אינדטרמיניסטי, ולכן תכולתו והוא בעצמו קונטינגנטי.
+
- המפץ הגדול לא בהכרח מסמל את נקודת התחלת היקום.
- הנחת המבוקש בה היקום לא אינסופי $Q$, כי יש לו נקודת התחלה $P$, כי הוא לא אינסופי $Q$.
- גם אם ליקום נקודת התחלה, ניתן להציב רגרסיה אינסופית ומטאפיזיקלית של יקומים.
== והיא אלוהים
=== סיבה הכרחית
#quote(attribution: [עמוד 52])[
[...]אם ידוע שקיימים דברים הכרחיים כמו חוקי המתמטיקה והלוגיקה, אז ייתכנו גם דברים הכרחיים אחרים, שאינם רק מושגים מופשטים. כלומר, קיים עוד הסבר להתחלת היקום: משהו הכרחי גרם לו להתחיל. אם מיטב המדע מצביע על כך שהזמן והמרחב של היקום החלו להתקיים, ואם שרשרת של סיבות אינסופית לאחור אינה אפשרית, אז חייבת להיות סיבה ראשונה שלא החלה להתקיים אלא תמיד הייתה וממנה החלה שרשרת הסיבות; סיבה ראשונה שעצם טבעה הוא הכרחי, ולכן אינה צריכה סיבה בעצמה.
]
"הכרחיות" היא מילה מודלית
#footnote[https://en.wikipedia.org/wiki/Modal_word],
והיא תלויה במודליות כמו פיזיקה ולוגיקה. הטענה "חוקי המתמטיקה והלוגיקה הכרחיים" חסרת משמעות, כי הכוונה היא שהם הכרחיים לפי חוקי המתמטיקה והלוגיקה; הכרחיים לפי עצמם, אך כל דבר "מעצם טבעו" בלבד הכרחי, הודות לחוק הזהות
#footnote[https://en.wikipedia.org/wiki/Law_of_identity].
כאשר טוענים שמשהו הכרחי, לרוב הכוונה היא להכרחי לפי מודליות מסוימת מעליו. דרך יותר ברורה לתאר את חוקי הלוגיקה והמתמטיקה היא "אקסיומות", לחלופין "עובדות גסות", כי פשוט איננו מסוגלים לייחס להם הסבר רציונלי מבלי להכתיר אותם כעובדות גסות, הרי הסבר רציונלי עובד רק בתוך התחום הרציונלי שהם בעצמם קובעים.
בפשטות, עצם טבעה של טענה הכרחית מילולית מחייב אותה לדרוש סיבה (ולא הפוך), אחרת היא עובדה גסה, שמאיר שלל כרעיון מקודם. לכן, בצירוף להנחות של מאיר (אין עובדות גסות ועיקרון הסיבתיות לוגי):
- הסיבה ראשונית:
- התחילה ← חייבת סיבה (עיקרון הסיבתיות) ← לא ראשונית (סתירה)
- לא התחילה ← לא חייבת סיבה ← יכולה להיות ראשונית:
- קונטינגנטית ← עובדה גסה כי גם ראשונית (סתירה)
- הכרחית ← חייבת סיבה ← ראשונית (סתירה)
כלומר, הדילמה היא בין סיבה גסה וראשונית (ברמה של חוקי הלוגיקה), לבין סיבה הכרחית שתלויה בסיבות אחרות (על בסיס חוקי הלוגיקה). לפי הבנתי מאיר בחר במקרה הראשון, אולם בשני המקרים אין צורך בסיבת ביניים והיקום יכול להסתדר לבד.
יש דרך אחרת לפרש את הטיעון: "אם רגרסיה אינסופית וסיבה ראשונית קונטינגנטית (גסה) לא אפשריות, האפשרות שנותרת היא סיבה ראשונית הכרחית, והטיעון הזה בעצמו הוא ההכרחיות שהיא דורשת (אין הכרחיות נוספת ולא גלויה)". הכשל הוא כרגיל מעבר שגוי בין פיזיקה ללוגיקה; אם היקום קונטינגנטי (כפי שמאיר מאמין) הטיעון מתפצל מהמודליות הלוגית בו היקום קונטינגנטי לתוך המודליות הפיזיקלית של היקום בו הוא "הכרחי לפי עצמו", לכן הסיבה הכרחית רק פיזיקלית ולא לוגית כפי שמסקנת הטיעון עשויה להישמע. בקצרה, יקום קונטינגנטי לוגית יכל לא להתקיים, משמע גם סיבתו.
=== סיבה שחורגת מעיקרון הסיבתיות
#quote(attribution: [עמוד 54])[
[...] מכיוון שהסיבה הראשונית נמצאת מחוץ לזמן, היא גם חורגת באופן יחיד ומיוחד מעקרון הסיבתיות.
]
אני מסכים שהסיבה חורגת מהעיקרון, הרי היא לא "התחילה", אך כמובן אין סתירה בייחוס סיבה לעובדה מחוץ לזמן בכל זאת, הרי עיקרון הסיבתיות הוא חד-כיווני (\u{2190}), לא דו-כיווני (\u{2194}). לדוגמה, הנוסחה $2 + 2 = 4$ לא תלויה בזמן, ובכל זאת לתוצאתה סיבה מתמטית.
=== סיבה יחידית
#quote(attribution: [עמוד 54])[
כמו כן, ההיסק שלסיבה הראשונה אין סיבה שחוללה אותה מוביל למסקנה שקיימת אך ורק סיבה ראשונית אחת. לא ייתכן שקיימות כמה סיבות ראשונות, כי אנו זקוקים לסיבה שהיא ראשונה וחסרת סיבה לחלוטין.
]
לפי הגדרת הסיבה הראשונית אין סיבה לפניה, אולם ניתן לדמיין כמה סיבות ראשוניות מקבילות, כמו מספר ישויות נפרדות שביחד יצרו את היקום.
=== סיבה בעלת תודעה
#quote(attribution: [עמוד 56])[
אי אפשר להסביר את ההתחלה של הזמן והמרחב של היקום באמצעות הסבר טבעי. לפני שהסיבה הראשונית פעלה להתחיל את היקום לא היה שום דבר מלבדה, ובטח שלא חוקי טבע ותנאים פיזיקליים הנדרשים בשביל שנוכל להשתמש בהסבר טבעי. אי אפשר להסביר את התחלת היקום בשרשרת אירועים טבעית, כי עוד לא היו בכלל אירועים, ועוד לא היה טבע.
]
אם לחוקי הטבע (לחלופין, חוקי הפיזיקה) הסבר, הסבר זה אינו פיזיקלי, אחרת היה סותר סיבתיות פיזיקלית שלא מאפשרת לדבר ליצור את עצמו, ועל כך הסכמתי בהקדמה. אך, "אירועים" בכללי בהחלט יכולים להתקיים "מחוץ" או "לפני" היקום. לדוגמה, ייתכן שזמן "תמיד היה, לא הייתה לו התחלה ולכן אין לו סיבה" והיו אירועים לפני היקום (לא ספציפית אינסוף), יכולים להיות יקומים מקבילים עם אירועים נפרדים משלהם, ומלכתחילה אפשרי שההגדרה ל"אירוע" לא תלויה בזמן, אולם במאמר זה לא אחתור יותר לפילוסופיית המרחב והזמן
#footnote[https://en.wikipedia.org/wiki/Philosophy_of_space_and_time].
#quote(attribution: [עמוד 56])[
על כן, ההתחלה של היקום יכולה להיות מוסברת רק באמצעות הסבר אישי. בחירתך להרתיח מים לקפה יכולה להיות תוצאה של התמכרות לקפה או הרגל של שנים, כלומר קבועה מראש. אבל היא גם יכולה להיות בחירה חופשית שלך להחליט לפנק את עצמך. כך גם הסיבה הראשונית לקיומו של היקום היא ההסבר האישי להופעתו. היקום הופיע כתוצאה אישית של בחירה חופשית. ורק ישויות בעלות תודעה יכולות לרצות לבחור ולבצע פעולה מסוימת.
]
אולם בחירה חופשית תואמת למעבר בין סיבה הכרחית ליקום קונטינגנטי, היא סוג של אירוע אליו מאיר התנגד לפני רגע כדבר שניתן ליישם מחוץ לזמן. על המסקנה שיש הסבר אישי אפשר למתוח עוד ועוד ביקורות, כי הטיעון בקושי מורכב, והסבר אישי מוגדר באופן כללי מדי. לדוגמה, ייתכן ותודעה (חוויה סובייקטיבית וכדומה) הינה תופעה שיסודה פיזיקלי, או שבחירה חופשית היא עובדה גסה.
=== מסקנה סופית שיש אלוהים
#quote()[
#show terms.item: set text(weight: "thin") // Disable terms list bold weight
אז החומר ההכרחי שהוא סיבת היקום צריך להיות:
/ א.: יחידי
/ ב.: לא פיזיקלי
/ ג.: נצחי (נפרד מהזמן)
/ ד.: בעל כוחות אדירים מעל לכל דמיון
/ ה.: בעל תודעה ועצמאות להחליט ליצור את היקום ברגע מסוים בעבר (עמוד 57)
]
כתגובה:
+ (א.) אפשרי במקום שכמה דברים נפרדים יצרו את היקום במקביל.
+ (ב.) נכון לצורך הדיון, מאחר ודבר פיזיקלי לא יכול ליצור את עצמו.
+ (ג.) מרומז שימוש דו-כיווני שגוי בעיקרון הסיבתיות (למרות שמלכתחילה לא מוכרח).
+ (ד.) לא הרחבתי על נקודה זו כי לפי דעתי היא חסרת משמעות ומאוד סובייקטיבית.
+ (ה.) בחירה חופשית נוגדת את דבריו של מאיר מהיותה אירוע שגם עשוי להיחשב עובדה גסה, ויתכן שתודעה היא פיזיקלית מטבעה.
== נספח א': תכלית היקום
#quote(attribution: [עמוד 58])[
משחר ההיסטוריה בני אדם עמלו רבות במטרה להמציא מכונות וליצור אותן [...] כולן מיוצרות בשביל לתעל את כוחו של האדם. כלומר, לכולן יש תכלית שלשם השׂגתה הושקעו זמן ומשאבים רבים. [...] אם כך נכון באדם, אז קל וחומר באלוהים. אם ישות עליונה רצתה שהיקום שלנו יתקיים והתחילה מרצונה את שרשרת הסיבות שהובילה לקיומנו, אז יש לנו לא רק סיבה, אלא גם תכלית. [...] תכלית לכלל מעידה גם על תכלית של הפרט — כפי שכל בורג פשוט בחללית חיוני לתפקודה ומשרת את התכלית הכוללת שלצורכה נבנתה החללית, כך יש לעצם קיומי משמעות ותכלית כלשהי. גם אני הקטן, חלק מהיקום, ועל כן סביר שגם לי יש חלק בתכליתו.
]
אלוהים לא היה חייב ליצור את היקום עם תכלית. להאניש את אלוהים ולקבוע שנבראנו בצלמו הוא רעיון מעגלי, ומעבר לכך נוגד את האינטואיציה שאחריה מאיר עוקב: כוחו של אלוהים בלתי נתפס, אז למה שנוכל לתפוס את החלטתו ליצור את היקום? אלוהים יכל ליצור את היקום בטעות, אולי אפילו מבלי לשים לב. אפשרי שאלוהים התכוון ליצור את היקום, אבל לא את כל שרשרת הסיבות מגלקסיית שביל החלב, מערכת השמש שלנו, כדור הארץ והחיים עליו, עד בני האדם; כל אלו סתם קונטינגנטיים ולא לוקחים חלק בתכלית. כפי שציינת, אתה קונטינגנטי ולא הכרחי כמו בורג בחללית, אני ואתה יכולנו לא להתקיים בזמן שהעולם היה נשאר פחות או יותר אותו הדבר, מבלי להשפיע על תכליתו.
|
|
https://github.com/OverflowCat/typecharts | https://raw.githubusercontent.com/OverflowCat/typecharts/neko/lib.typ | typst | #import "@preview/jogs:0.2.3": *
#let echarts = read("echarts.js")
#let bytecode = compile-js(echarts)
#let render(config, option, theme: none) = {
let svg = call-js-function(bytecode, "renderChart", config, option, theme)
image.decode(svg)
}
#let evalRender(config, option, theme: none) = {
let svg = eval-js(echarts + "\n let config = {width: 400, height: 320}; let option = " + option + ";renderChart(config, option)")
image.decode(svg)
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/place-float-figure_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(height: 250pt, width: 150pt)
= Introduction
#lorem(10) #footnote[Lots of Latin]
#figure(
placement: bottom,
caption: [A glacier #footnote[Lots of Ice]],
image("/assets/files/glacier.jpg", width: 80%),
)
#lorem(40)
#figure(
placement: top,
caption: [An important],
image("/assets/files/diagram.svg", width: 80%),
)
|
https://github.com/Amelia-Mowers/typst-tabut | https://raw.githubusercontent.com/Amelia-Mowers/typst-tabut/main/doc/example-snippets/group-aggregation.typ | typst | MIT License | #import "@preview/tabut:<<VERSION>>": tabut, group
#import "usd.typ": usd
#import "example-data/titanic.typ": titanic, classes
#tabut(
group(titanic, r => r.Pclass),
(
(header: [*Class*], func: r => classes.at(r.value)),
(header: [*Total Fare*], func: r => usd(r.group.map(r => r.Fare).sum())),
(
header: [*Avg Fare*],
func: r => usd(r.group.map(r => r.Fare).sum() / r.group.len())
),
),
fill: (_, row) => if calc.odd(row) { luma(240) } else { luma(220) },
stroke: none
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-AB70.typ | typst | Apache License 2.0 | #let data = (
("CHEROKEE SMALL LETTER A", "Ll", 0),
("CHEROKEE SMALL LETTER E", "Ll", 0),
("CHEROKEE SMALL LETTER I", "Ll", 0),
("CHEROKEE SMALL LETTER O", "Ll", 0),
("CHEROKEE SMALL LETTER U", "Ll", 0),
("CHEROKEE SMALL LETTER V", "Ll", 0),
("CHEROKEE SMALL LETTER GA", "Ll", 0),
("CHEROKEE SMALL LETTER KA", "Ll", 0),
("CHEROKEE SMALL LETTER GE", "Ll", 0),
("CHEROKEE SMALL LETTER GI", "Ll", 0),
("CHEROKEE SMALL LETTER GO", "Ll", 0),
("CHEROKEE SMALL LETTER GU", "Ll", 0),
("CHEROKEE SMALL LETTER GV", "Ll", 0),
("CHEROKEE SMALL LETTER HA", "Ll", 0),
("CHEROKEE SMALL LETTER HE", "Ll", 0),
("CHEROKEE SMALL LETTER HI", "Ll", 0),
("CHEROKEE SMALL LETTER HO", "Ll", 0),
("CHEROKEE SMALL LETTER HU", "Ll", 0),
("CHEROKEE SMALL LETTER HV", "Ll", 0),
("CHEROKEE SMALL LETTER LA", "Ll", 0),
("CHEROKEE SMALL LETTER LE", "Ll", 0),
("CHEROKEE SMALL LETTER LI", "Ll", 0),
("CHEROKEE SMALL LETTER LO", "Ll", 0),
("CHEROKEE SMALL LETTER LU", "Ll", 0),
("CHEROKEE SMALL LETTER LV", "Ll", 0),
("CHEROKEE SMALL LETTER MA", "Ll", 0),
("CHEROKEE SMALL LETTER ME", "Ll", 0),
("CHEROKEE SMALL LETTER MI", "Ll", 0),
("CHEROKEE SMALL LETTER MO", "Ll", 0),
("CHEROKEE SMALL LETTER MU", "Ll", 0),
("CHEROKEE SMALL LETTER NA", "Ll", 0),
("CHEROKEE SMALL LETTER HNA", "Ll", 0),
("CHEROKEE SMALL LETTER NAH", "Ll", 0),
("CHEROKEE SMALL LETTER NE", "Ll", 0),
("CHEROKEE SMALL LETTER NI", "Ll", 0),
("CHEROKEE SMALL LETTER NO", "Ll", 0),
("CHEROKEE SMALL LETTER NU", "Ll", 0),
("CHEROKEE SMALL LETTER NV", "Ll", 0),
("CHEROKEE SMALL LETTER QUA", "Ll", 0),
("CHEROKEE SMALL LETTER QUE", "Ll", 0),
("CHEROKEE SMALL LETTER QUI", "Ll", 0),
("CHEROKEE SMALL LETTER QUO", "Ll", 0),
("CHEROKEE SMALL LETTER QUU", "Ll", 0),
("CHEROKEE SMALL LETTER QUV", "Ll", 0),
("CHEROKEE SMALL LETTER SA", "Ll", 0),
("CHEROKEE SMALL LETTER S", "Ll", 0),
("CHEROKEE SMALL LETTER SE", "Ll", 0),
("CHEROKEE SMALL LETTER SI", "Ll", 0),
("CHEROKEE SMALL LETTER SO", "Ll", 0),
("CHEROKEE SMALL LETTER SU", "Ll", 0),
("CHEROKEE SMALL LETTER SV", "Ll", 0),
("CHEROKEE SMALL LETTER DA", "Ll", 0),
("CHEROKEE SMALL LETTER TA", "Ll", 0),
("CHEROKEE SMALL LETTER DE", "Ll", 0),
("CHEROKEE SMALL LETTER TE", "Ll", 0),
("CHEROKEE SMALL LETTER DI", "Ll", 0),
("CHEROKEE SMALL LETTER TI", "Ll", 0),
("CHEROKEE SMALL LETTER DO", "Ll", 0),
("CHEROKEE SMALL LETTER DU", "Ll", 0),
("CHEROKEE SMALL LETTER DV", "Ll", 0),
("CHEROKEE SMALL LETTER DLA", "Ll", 0),
("CHEROKEE SMALL LETTER TLA", "Ll", 0),
("CHEROKEE SMALL LETTER TLE", "Ll", 0),
("CHEROKEE SMALL LETTER TLI", "Ll", 0),
("CHEROKEE SMALL LETTER TLO", "Ll", 0),
("CHEROKEE SMALL LETTER TLU", "Ll", 0),
("CHEROKEE SMALL LETTER TLV", "Ll", 0),
("CHEROKEE SMALL LETTER TSA", "Ll", 0),
("CHEROKEE SMALL LETTER TSE", "Ll", 0),
("CHEROKEE SMALL LETTER TSI", "Ll", 0),
("CHEROKEE SMALL LETTER TSO", "Ll", 0),
("CHEROKEE SMALL LETTER TSU", "Ll", 0),
("CHEROKEE SMALL LETTER TSV", "Ll", 0),
("CHEROKEE SMALL LETTER WA", "Ll", 0),
("CHEROKEE SMALL LETTER WE", "Ll", 0),
("CHEROKEE SMALL LETTER WI", "Ll", 0),
("CHEROKEE SMALL LETTER WO", "Ll", 0),
("CHEROKEE SMALL LETTER WU", "Ll", 0),
("CHEROKEE SMALL LETTER WV", "Ll", 0),
("CHEROKEE SMALL LETTER YA", "Ll", 0),
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/gentle-clues/0.4.0/gentle-clues.typ | typst | Apache License 2.0 | // gentle-clues
#let gc_header-title-lang = state("lang", "en")
#let gc_task-counter = counter("gc-task-counter")
#let gc_enable-task-counter = state("gc-task-counter", true)
#let title_dict = (
abstract: (de: "Einführung", en: "Abstract", fr: "Résumé"),
info: (de: "Info", en: "Info", fr: "Info"),
question: (de: "Frage", en: "Question", fr: "Question"),
memo: (de: "Merke", en: "Memorize", fr: "À retenir"),
task: (de: "Aufgabe", en: "Task", fr: "Tâche"),
conclusion: (de: "Zusammenfassung", en: "Conclusion", fr: "Conclusion"),
tip: (de: "Tipp", en: "Tip", fr: "Conseil"),
success: (de: "Erledigt", en: "Success", fr: "Succès"),
warning: (de: "Achtung", en: "Warning", fr: "Avertissement"),
error: (de: "Fehler", en: "Error", fr: "Erreur"),
example: (de: "Beispiel", en: "Example", fr: "Exemple"),
quote: (de: "Zitat", en: "Quote", fr: "Citation"),
)
/*
Basic gentle-clue (clue) template
*/
#let clue(
content,
title: none, // string or none
icon: emoji.magnify.l, // file or symbol
_color: navy, // color profile name
width: auto, // length
radius: 2pt, // length
inset: 1em, // length
header-inset: 0.5em, // length
) = {
// Set default color:
let stroke-color = luma(70);
let bg-color = stroke-color.lighten(85%);
let border-color = bg-color.darken(10%); // gray.lighten(20%);
let border-width = 0.5pt;
// setting bg and stroke color from color argument
if (type(_color) == color) {
stroke-color = _color;
bg-color = _color.lighten(85%);
border-color = bg-color.darken(10%);
} else if (type(_color) == dictionary) {
if (_color.keys().contains("stroke")) {
assert(type(_color.stroke) == color, message: "stroke must be of type color");
stroke-color = _color.stroke;
}
if (_color.keys().contains("bg")) {
assert(type(_color.bg) == color, message: "bg must be of type color");
bg-color = _color.bg;
border-color = bg-color.darken(10%);
}
if (_color.keys().contains("border")) {
assert(type(_color.border) == color, message: "border must be of type color");
border-color = _color.border;
}
} else if (type(_color) == gradient) {
stroke-color = _color;
bg-color = _color;
} else {
panic("No valid color type. Use a gradient, color, or specify a dict with (stroke, bg)");
}
// Disable Heading numbering for those headings
set heading(numbering: none, outlined: false, supplement: "Box")
let header = rect(
fill: bg-color,
width: 100%,
radius: (top-right: radius),
inset: header-inset,
stroke: (right: border-width + bg-color )
)[
#grid(
columns: (auto, auto),
gutter: 1em,
box(height: 1em)[
#if type(icon) == "symbol" {
text(1em,icon)
} else {
image(icon, fit: "contain")
}
],
align(left + horizon,strong(title))
)
]
let content-box(content) = box(
width: 100%,
fill: white,
inset: inset,
radius: (
top-left: 0pt,
bottom-left: 0pt,
top-right: if (title != none){0pt} else {radius},
rest: radius
),
)[#content]
box(
width: width,
inset: (left: 1pt),
radius: (right: radius, left: 0pt),
stroke: (
left: (thickness: 2pt, paint: stroke-color, cap: "butt"),
top: if (title != none){border-width + bg-color} else {border-width + border-color},
rest: border-width + border-color,
),
)[
#set align(start)
#stack(dir: ttb,
if title != none { header; },
content-box(content)
)
]
}
// Predefined gentle clues
#let get_title_for(clue) = {
assert.eq(type(clue),str);
locate(loc => {
let lang = gc_header-title-lang.at(loc)
title_dict.at(clue).at(lang)
})
}
#let increment_task_counter() = {
locate(loc => {
if (gc_enable-task-counter.at(loc) == true){
gc_task-counter.step()
}
})
}
#let get_task_number() = {
locate(loc => {
if (gc_enable-task-counter.at(loc) == true){
" " + gc_task-counter.display()
}
})
}
/* info, note */
#let info(title: auto, icon: "assets/info.svg", ..args) = clue(
_color: rgb(29, 144, 208), // blue
title: if (title != auto) { title } else { get_title_for("info") },
icon: icon,
..args
)
#let note = info
/* success, check, done */
#let success(title: auto, icon: "assets/checkbox.svg", ..args) = clue(
_color: rgb(102, 174, 62), // green
title: if (title != auto) { title } else { get_title_for("success") },
icon: icon,
..args
)
#let check = success
#let done = success
/* warning, attention, caution */
#let warning(title: auto, icon: "assets/warning.svg", ..args) = clue(
_color: rgb(255, 145, 0), // orange
title: if (title != auto) { title } else { get_title_for("warning") },
icon: icon,
..args
)
#let attention = warning
#let caution = warning
/* error, failure */
#let error(title: auto, icon: "assets/crossmark.svg", ..args) = clue(
_color: rgb(237, 32, 84), // red
title: if (title != auto) { title } else { get_title_for("error") },
icon: icon,
..args
)
#let failure = error
/* task */
#let task(title: auto, icon: "assets/task.svg", ..args) = {
increment_task_counter()
clue(
_color: maroon, // purple rgb(158, 84, 159)
title: if (title != auto) { title } else { get_title_for("task") + get_task_number()},
icon: icon,
..args
)
}
#let todo = task
/* tip, hint, important */
#let tip(title: auto, icon: "assets/tip.svg", ..args) = clue(
_color: rgb(0, 191, 165), // teal
title: if (title != auto) { title } else { get_title_for("tip") },
icon: icon,
..args
)
#let hint = tip
#let important = tip
/* abstract, summary, tldr */
#let abstract(title: auto, icon: "assets/abstract.svg", ..args) = clue(
_color: olive, // rgb(124, 77, 255), // kind of purple
title: if (title != auto) { title } else { get_title_for("abstract") },
icon: icon,
..args
)
/* conclusion, idea */
#let conclusion(title: auto, icon: "assets/lightbulb.svg", ..args) = clue(
_color: rgb(255, 201, 23), // yellow
title: if (title != auto) { title } else { get_title_for("conclusion") },
icon: icon,
..args
)
#let idea = conclusion
/* memorize, remember */
#let memo(title: auto, icon: "assets/excl.svg", ..args) = clue(
_color: rgb(255, 82, 82), // kind of red
title: if (title != auto) { title } else { get_title_for("memo") },
icon: icon,
..args
)
#let remember = memo
/* question, faq, help */
#let question(title: auto, icon: "assets/questionmark.svg", ..args) = clue(
_color: rgb("#7ba10a"), // greenish
title: if (title != auto) { title } else { get_title_for("question") },
icon: icon,
..args
)
#let faq = question
#let help = question
/* quote */
#let quote(title: auto, icon: "assets/quote.svg", ..args) = clue(
_color: eastern,
title: if (title != auto) { title } else { get_title_for("quote") },
icon: icon,
..args
)
/* example */
#let example(title: auto, icon: "assets/example.svg", ..args) = clue(
_color: orange,
title: if (title != auto) { title } else { get_title_for("example") },
icon: icon,
..args
)
|
https://github.com/GartmannPit/Praxisprojekt-II | https://raw.githubusercontent.com/GartmannPit/Praxisprojekt-II/main/Praxisprojekt%20II/PVA-Templates-typst-pva-2.0/abstract.typ | typst | #let showAbstract()=[
= Abstract
// Write your abstract under the heading and remove the edit information
Edit your abstract to the document in _abstract.typ_ \ // delete me
#lorem(150) // delete me
] |
|
https://github.com/typst-community/org | https://raw.githubusercontent.com/typst-community/org/main/GOVERNANCE.md | markdown | This document describes the governance structure of the project and how decisions are made.
## Organization Governance
The following member(s) hold ownership positions over the organization:
- [@huwaireb](https://github.com/huwaireb)
> [!NOTE]
> The numbers of owners is intentionally kept small to allow for quick decision making, and a reduced surface area for attacks. More members may be added as the organization grows through, most likely, a consensus processes, undefined currently.
This means, by default, they have administrative power over the organization, including the ability to add/remove members, create/delete repositories, and manage the organization's settings. This is a consequence of centralization, and is not ideal. However, it is a necessary evil for the time being. We welcome any suggestions on how to improve this, if you have an idea please open an [issue](https://github.com/typst-community/org/issues/new).
## Project Governance
| Project | Maintainer(s) | Team |
| --------------------------------------------------------------------- | ---------------------------------------- | ----------------------------------------------------------------------------------------- |
| [setup-typst](https://github.com/typst-community/setup-typst) | [@yusancky](https://github.com/yusancky) | [@typst-community/setup-typst](https://github.com/orgs/typst-community/teams/setup-typst) |
| [typst.js](https://github.com/typst-community/typst.js) | [@jcbhmr](https://github.com/jcbhmr) | None |
| [typst-installer](https://github.com/typst-community/typst-installer) | [@jcbhmr](https://github.com/jcbhmr) | None |
Maintainers have full control over their respective projects and teams.
If you would like to **add a new project** to the organization please see [Getting Involved](CONTRIBUTING.md#getting-involved). |
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/typst-slides-fudan/themes/polylux/book/src/themes/gallery/clean.typ | typst | #import "../../../../polylux.typ": *
#import themes.clean: *
#set text(font: "Inria Sans")
#show: clean-theme.with(
footer: [Author, institution],
short-title: [Short title],
logo: image("dummy-logo.png"),
)
#title-slide(
title: [Presentation title],
subtitle: [Presentation subtitle],
authors: ([Author A], [Author B], [Author C]),
date: [January 1, 1970],
watermark: image("dummy-watermark.png"),
)
#slide(title: [First slide title])[
#lorem(20)
]
#new-section-slide("The new section")
#slide(title: [Slide with multiple columns])[
#lorem(20)
][
#lorem(10)
][
#lorem(30)
]
#focus-slide[
_Focus!_
This is very important.
]
|
|
https://github.com/csimide/SEU-Typst-Template | https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/parts/abstract-bachelor-fn.typ | typst | MIT License | #import "../utils/fonts.typ": 字体, 字号
#let abstract-conf(
cn-abstract: none,
cn-keywords: none,
en-abstract: none,
en-keywords: none,
) = {
// 摘要使用罗马字符的页码
set page(numbering: "I", number-align: center)
counter(page).update(1)
set text(font: 字体.宋体, size: 字号.小四)
if not cn-abstract in (none, [], "") or not cn-keywords in (none, ()) {
{
set par(first-line-indent: 2em, leading: 14pt, justify: true)
show par: set block(spacing: 14pt)
// 我不理解为什么两个摘要需要不同的间距
heading(outlined: true, bookmarked: true, level: 1, numbering: none)[摘要]
v(3pt)
cn-abstract
v(18pt)
// 英文
set par(first-line-indent: 0em)
if not cn-keywords in (none, ()) {
assert(type(cn-keywords) == array)
"关键词:" + cn-keywords.join(",")
}
}
}
if not en-abstract in (none, [], "") or not en-keywords in (none, ()) {
{
pagebreak(weak: true)
set par(first-line-indent: 2em, leading: 15pt, justify: true)
show par: set block(spacing: 15pt)
// 我不理解为什么两个摘要需要不同的间距
heading(
outlined: true,
bookmarked: true,
level: 1,
numbering: none,
)[ABSTRACT]
v(3pt)
en-abstract
v(20pt)
if not en-keywords in (none, ()) {
assert(type(en-keywords) == array)
"KEY WORDS: " + en-keywords.join(",")
}
}
}
}
#abstract-conf(
cn-abstract: [示例摘要],
cn-keywords: ("关键词1", "关键词2"),
en-abstract: none,
en-keywords: ("Keywords1", "Keywords2"),
)
|
https://github.com/Origami404/kaoyan-shuxueyi | https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/扩展/01-有理分式积分.typ | typst | = 有理分式积分
有理分式是指形如 $P(x) / Q(x)$ 的式子, 其中 $P$ 和 $Q$ 都是多项式.
我们可以假定分子 $P$ 的阶数比 $Q$ 小. 若否, 我们就可以把高次的部分提出来, 从而使积分变为 $R + P'/Q$ 的积分, 其中 $P = R * Q + P'$, $P'$ 的阶数小于 $Q$.
由代数基本定理, 任何多项式 $Q(x)$ 都会有 $n$ 个复根, 所以任何多项式肯定可以表示为一堆一次项和一堆 $Delta < 0$ 二次项的积, 前者代表该多项式的所有实根, 后者代表该多项式的所有复根:
$
Q(x) = product_(i = 0)^(n - 1) (x - x_i)^(k_i) * product_(i = n)^(m - 1) ((x - x_i)^2 + r_i)^(l_i)
$ |
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/layout/pad.typ | typst | // Test the `pad` function.
--- pad-basic ---
// Use for indentation.
#pad(left: 10pt, [Indented!])
// All sides together.
#set rect(inset: 0pt)
#rect(fill: conifer,
pad(10pt, right: 20pt,
rect(width: 20pt, height: 20pt, fill: rgb("eb5278"))
)
)
Hi #box(pad(left: 10pt)[A]) there
--- pad-expanding-contents ---
// Pad can grow.
#pad(left: 10pt, right: 10pt)[PL #h(1fr) PR]
--- pad-followed-by-content ---
// Test that the pad element doesn't consume the whole region.
#set page(height: 6cm)
#align(left)[Before]
#pad(10pt, image("/assets/images/tiger.jpg"))
#align(right)[After]
--- pad-adding-to-100-percent ---
// Test that padding adding up to 100% does not panic.
#pad(50%)[]
--- issue-5044-pad-100-percent ---
#set page(width: 30pt, height: 30pt)
#pad(100%, block(width: 1cm, height: 1cm, fill: red))
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/attach-p2_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set text(size: 8pt)
// Test that the attachments are aligned horizontally.
$ x_1 p_1 frak(p)_1 2_1 dot_1 lg_1 !_1 \\_1 ]_1 "ip"_1 op("iq")_1 \
x^1 b^1 frak(b)^1 2^1 dot^1 lg^1 !^1 \\^1 ]^1 "ib"^1 op("id")^1 \
x_1 y_1 "_"_1 x^1 l^1 "`"^1 attach(I,tl:1,bl:1,tr:1,br:1)
scripts(sum)_1^1 integral_1^1 abs(1/2)_1^1 \
x^1_1, "("b y")"^1_1 != (b y)^1_1, "[∫]"_1 [integral]_1 $
|
https://github.com/Mouwrice/resume | https://raw.githubusercontent.com/Mouwrice/resume/main/letter.typ | typst | #import "brilliant-CV/template.typ": *
#show: layout
#set text(size: 12pt) //set global font size
#letterHeader(
myAddress: [Gent, Belgium],
recipientName: [IQGeo],
recipientAddress: none,
date: [10/04/2024],
subject: "Job Application: Software Engineer R&D"
)
Dear Sir/Madam,
I am writing this brief cover letter for the recent job opening of Software Engineer at your R&D department in Gent, Belgium.
While scrolling through LinkedIn job applications, this one peaked my interest. After having enrolled in numerous Algorithms and telecommunication- and networking courses during my studies, this job opening seems to be a great follow up.
Not only have I studied theory during my studies, but I have also gathered a decent amount of experience solving problems and developing software, both alone and in group. Over the years I have also had the opportunity to be part of small to medium agile teams developing software as a Student Job and Internship. Combined with the occasinal personal side-project I can say that I have become pretty comfortable in the software engineering landscape and I am always keen to learn new things and improve on my skills.
What I am now primarily looking for, as I finialize my Master's Education, is a team to join and re-enforce, starting in the period of September to October.
I hope that I hereby have been able to convince you of my interest and intent and look forward to hearing from you for an eventual exploratory conversation!
Sincerely,
#letterSignature("/src/signature.png")
#letterFooter() |
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/7e1810-algo_hw/hw7.typ | typst | #import "@preview/diagraph:0.2.1": *
#import "utils.typ": *
== HW7 (Week 8)
Due: 2024.04.28
=== Question 21.1-1
Let $(u,v)$ be a minimum-weight edge in a connected graph $G$. Show that $(u,v)$ belongs to some minimum spanning tree of $G$.
#[
#set text(fill: black)
#align(center)[
#scale(55%, reflow: true)[
#raw-render(```dot
digraph MSTModification {
layout=neato
subgraph cluster_0 {
node [shape=circle, style=filled, color=lightgrey];
style = invis;
A1 -> B1 [label="2", dir="none"];
B1 -> C1 [label="3", dir="none"];
C1 -> D1 [label="6", dir="none"];
D1 -> E1 [label="4", dir="none"];
E1 -> F1 [label="5", dir="none"];
F1 -> A1 [label="1", dir="none"]; // Minimum weight edge
}
subgraph cluster_1 {
style = invis;
node [shape=circle, style=filled, color=lightgrey];
A2 -> B2 [label="2", dir="none"];
B2 -> C2 [label="3", dir="none"];
C2 -> D2 [label="6", dir="none"];
D2 -> E2 [label="4", dir="none"];
E2 -> F2 [label="5", dir="none"];
F2 -> A2 [style=dotted, color=red, label="Removed", dir="none"];
}
subgraph cluster_2 {
style = invis;
node [shape=circle, style=filled, color=lightgrey];
A3 -> B3 [label="2", dir="none"];
B3 -> C3 [label="3", dir="none"];
D3 -> E3 [label="4", dir="none"];
E3 -> F3 [label="5", dir="none"];
F3 -> A3 [label="1", dir="none"];
C3 -> D3 [style=dotted, color=red, label="Removed", dir="none"];
}
}
```)
]
]
]
#ans[
Let $T$ be a minimum spanning tree of $G$. If $(u,v)$ is not in $T$, then $T union \{(u,v)\}$ contains a cycle $C$. Since $(u,v)$ is the minimum-weight edge in $G$ that crosses the cut $(V(T), V - V(T))$, we can replace an edge in $C$ with $(u,v)$ to get a spanning tree $T'$ with $w(T') < w(T)$, which contradicts the assumption that $T$ is a minimum spanning tree.
]
=== Question 21.2-1
Kruskal's algorithm can return different spanning trees for the same input graph $G$, depending on how it breaks ties when the edges are sorted into order. *Show that for each minimum spanning tree $T$ of $G$, there is a way to sort the edges of $G$ in Kruskal's algorithm so that the algorithm returns $T$.*
#rev1_note[
排序时引入第二关键字, 标记是否为想要的边. 令树边优先于非树边即可.
]
#ans[
Let $T$ be a minimum spanning tree of $G$. We sort the edges of $G$ in nondecreasing order of their weights. If there are ties, we break them arbitrarily. Since $T$ is a minimum spanning tree, the edges of $T$ are sorted before the edges not in $T$. Therefore, Kruskal's algorithm will add the edges of $T$ to the tree before adding any other edges, and the result will be $T$.
]
=== Question 21.2-4
Suppose that all edge weights in a grpah are integers in the range from $1$ to $abs(V)$. How fast can you make Kruskal's algorithm run? What if the edge weights are integers in the range from 1 to $W$ for some constant $W$?
#ans[
- If the edge weights are integers in the range from $1$ to $abs(V)$, we can use counting sort to sort the edges in $O(E)$ time.
- If the edge weights are integers in the range from $1$ to $W$, we can use radix sort to sort the edges in $O(E \lg W)$ time.
]
|
|
https://github.com/GZTimeWalker/GZ-Typst-Templates | https://raw.githubusercontent.com/GZTimeWalker/GZ-Typst-Templates/main/usage.typ | typst | MIT License | #import "templates/report.typ": *
#show: report.with(
title: "实验报告实验",
subtitle: "尝试使用 Typst 编写实验报告",
name: "张三",
stdid: "22223333",
classid: "实验二班",
major: "实验报告编写技术",
school: "实验报告学院",
time: "2022~2023 学年第二学期",
banner: "../images/sysu.png"
)
// write your report here
#title(content: "尝试使用 Typst 编写实验报告")
= 实验报告实验
== 什么是实验报告
#lorem(200)
#booktab(
width: 100%,
aligns: (left + horizon, center, right + bottom),
columns: (1fr, 1fr, 1fr),
caption: [`booktab` 示例],
[左对齐], [居中], [右对齐],
[4], [5], [6],
[7], [8], [9],
[10], [$ (n(n+1)) / 2 $], [11],
)
=== 公式
$ sum_(k=0)^n k
&= 1 + ... + n \
&= (n(n+1)) / 2 $
== 什么是 Typst
#lorem(20)
行内代码块: `#lorem(20)`
```c
int main() {
// 这是一句中文注释
// This is a comment in English
printf("Hello, world!");
return 0;
}
```
== 做个数学题
#set par(first-line-indent: 0pt)
3.1 设 $cal(V)$ 和 $cal(W)$ 是两 Hilbert 空间,${ket(v_j)}$ 和 ${ket(w_j)}$ 分别为 $cal(V)$ 和 $cal(W)$ 的一组正交模基。设 $display(T_A: sum_(j = 1)^n c_j ket(v_j) arrow.r sum_(j=1)^n c_j sum_(i=1)^m a_(i j) ket(w_j))$,证明 $T_A$ 是线性算子。
证明:对于 $forall k in NN, 0 < k <= n$,可以取一组 $display(c_j = cases(
1 "," j = k,
0 "," j != k
))$,由上述定义,可得到:
$ T_A (sum_(j = 1)^n c_j ket(v_j)) &= T_A (c_k ket(v_j)) = T_A (ket(v_j)) \
&= sum_(j=1)^n c_j sum_(i=1)^m a_(i j) ket(w_j) = c_k sum_(i=1)^m a_(i j) ket(w_j) = sum_(i=1)^m a_(i j) ket(w_j) $
则对于任意的一组 $c_j$,可以得到:
$ T_A (sum_(j = 1)^n c_j ket(v_j)) = sum_(j=1)^n c_j sum_(i=1)^m a_(i j) ket(w_j) = sum_(j=1)^n c_j T_A (ket(v_j)) $
即 $T_A$ 是线性算子。
|
https://github.com/dasayan05/typst-ai-conf-templates | https://raw.githubusercontent.com/dasayan05/typst-ai-conf-templates/master/neurips/neurips.typ | typst | MIT License | #let abstract_fn(doc) = [
#if type(doc) == "content" {
// only content blocks allowed as abstract
align(center)[
#box(width: 4.5in)[
#align(center)[
#text(size: 12pt)[*Abstract*]
]
#align(left)[
#doc
]
]
]
} else {
panic("Abstract requires a content block")
}
]
#let manuscript(title: [Paper Title], authors: (), abstract: [], content) = [
#set page(
paper: "us-letter",
margin: (x: 1.5in, y: 1in)
)
#set par(
justify: true,
leading: 0.45em
)
#set text(
font: "Times",
size: 10pt,
weight: "medium",
spacing: 65%
)
#show link: l => [
#set text(font: "CMU Typewriter Text", size: 10pt)
#box(stroke: 1pt + rgb(0, 255, 255))[#l]
]
#show raw: set text(font: "CMU Typewriter Text", size: 10pt)
#set heading(numbering: "1.1 ")
#show heading: h => [
#h #v(7pt)
]
#show heading.where(level: 1): set text(size: 12pt)
#show heading.where(level: 2): set text(size: 10pt)
#show heading.where(level: 3): set text(size: 10pt)
#align(center)[
#line(length: 100%, stroke: 4pt)
#v(0.125in)
#text(size: 17pt)[*#title*]\
#v(0.125in)
#line(length: 100%)
]
#v(20pt)
#align(center)[
#let c = ()
#for i in range(authors.len()) {
c.push(1fr)
}
#grid(
columns: c,
..authors
)
]
#v(20pt)
#abstract_fn(abstract)
\
// ...
#content
] |
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/5-implementation/import.typ | typst | Wie im Kapitel der Konzeption festgelegt, sollen die Modelle und Metadaten mithilfe von verschachtelten Komponenten geladen werden. Hierbei ermöglicht der zuvor definierte Web Component "ar-element-interactive" das Laden von 3D-Modellen und Metadaten. Der Component "ar-option" definiert ein Möbelstück und erhählt den Dateipfad des 3D-Modells sowie die Metadaten des Möbelstücks wie in @figure-html dargestellt. Dadurch können ohne interne Anpassungen neue Möbelstücke hinzugefügt werden oder Modelle und Metadaten verändert werden.
#let code = ```html
<ar-element-interactive>
<ar-option
model="one_one_center_scale.glb"
name="1x1" id="17"
/>
<ar-option
model="two_one_center_scale.glb"
name="2x1"
id="18"
/>
</ar-element-interactive>
```
#figure(
code,
caption: [Implementierung der "ar-element-interactive" Komponente mit zwei "ar-option" Komponenten]
) <figure-html>
Nach der Initialisierung der "ar-element-interactive" Komponente werden die "ar-option" Komponenten mithilfe der in @figure-loadOptions dargestellten Funktion geladen. Bei dieser Funktion handelt es sich um einen Auszug der vollständigen Funktion, die in @appendix-loadOptions dargestellt ist. Als Parameter wird ein Array der "ar-option" Komponenten übergeben. Anschließend werden mithilfe des von Three.js bereitgestellten GLTFLoaders die Modelle asynchron geladen. Die Modelle werden in Three.js 3D-Objekte umgewandelt und die definierten Metadaten den Objekten hinzugefügt. Hierbei kann die von Three.js bereitgestellte "userData"-Eigenschaft verwendet werden, unter der benutzerdefinierte Daten gespeichert werden können, die von Three.js ignoriert werden. Abschließend werden die Modelle in einer Variablen der Klasse namens "options" gespeichert und für die gesamte Klasse zugänglich gemacht.
#let code = ```js
export async function loadOptions(options) {
const loader = new GLTFLoader();
// Load all models asynchronously
const gltfs = Promise.all(
[...options].map((option) =>
loader.loadAsync(option.getAttribute("model")),
),
);
// Wait for all models to load
const models = await gltfs;
// Process each loaded model
models.forEach((gltf, index) => {
const model = gltf.scene.children[0];
model.userData.name = [...options][index].getAttribute("name");
this.options.push(model);
});
}
```
#figure(
code,
caption: [Auszug der "loadOptions" Funktion zum Laden von Modellen und Metadaten]
) <figure-loadOptions> |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-12.typ | typst | Other | // Error: 7-25 show is only allowed directly in code and content blocks
#(1 + show heading: none)
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/数据库系统/数据库设计理论.typ | typst | ---
order: 4
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "数据库系统",
lang: "zh",
)
#let null = math.op("null")
#let Unknown = math.op("Unknown")
#counter(heading).update(3)
= 第四部分: 数据库设计理论
== 复杂数据类型
=== 面向对象数据库 <OOP>
- 在关系数据库中融入面向对象的思想
- Build an #redt[object-oriented database(OODB)] that *natively supports* object-oriented data and direct access from programming language
- Build an #redt[object-relational database(ORDB)], adding object-oriented features to a relational database
- Automatically convert data between programming language model and relational model; data conversion specified by object-relational mapping(ORM)
- 为了让 SQL 支持复杂类型,引入的扩展
+ *Collection types*(Nested relations are an example of collection types)
+ *Structured types*(Nested record structures like composite attributes)
+ *Inheritance*
+ *Object orientation*(Including object identifiers and references)
+ *Large object types*(BLOB, CLOB)
- 我们的叙述主要基于 SQL1999,它的标准尚未被完全实现,但很多特性已经在某些商业数据库中广泛应用
- User-defined types and Table types
```sql
create type Person
(ID varchar(20) primary key,
name varchar(20),
address varchar(20))
ref from(ID);
create table people of Person;
create type interest as table (
topic varchar(20),
degree_of_interest int);
create table users (
ID varchar(20),
name varchar(20),
interests interest); -- Table 作为 type
```
- Array and Multiset Types
```sql
create type Publisher as
(name varchar(20),
branch varchar(20))
create type Book as
(title varchar(20),
author-array varchar(20) array [10],
pub-date date,
publisher Publisher,
keyword-set varchar(20) multiset)
create table books of Book
```
- Type and Table Inheritance
```sql
create type Student under Person (degree varchar(20));
create type Teacher under Person (salary integer);
```
- Reference Types
```sql
create type Person
(ID varchar(20) primary key,
name varchar(20),
address varchar(20))
ref from(ID);
create table people of Person;
create type Department (
dept_name varchar(20),
head ref(Person) scope people);
create table departments of Department
insert into departments values ('CS', '12345')
-- Using references in path expressions
select head->name, head->address from departments;
```
- Object-Relational Mapping
- Object-relational mapping(ORM) systems allow
+ Specification of mapping between programming language objects and database tuples
+ Automatic creation of database tuples upon creation of objects
+ Automatic update/delete of database tuples when objects are update/deleted
+ Interface to retrieve objects satisfying specified onditions
- Tuples in database are queried, and object created from the tuples
- 大概意思就是在高级编程语言的 objects 和数据库 tuples 之间建立一一映射(比如如果是 Java,就是在 JDBC 之上再套一层抽象)
- An example: #redt[Hibernate] ORM for Java
```java
@Entity public class Student {
@Id String ID;
String name;
String department;
int tot_cred;
}
// creates a Student object and saves it to the database
Session session = getSessionFactory().openSession();
Transaction txn = session.beginTransaction();
Student stud = new Student("12328", "<NAME>", "Comp. Sci.", 0);
session.save(stud);
txn.commit();
session.close();
```
- `@Entity` 表示映射到数据库中某一关系;默认的关系名和属性名可以用 `@Table` 和 `@Column` 覆盖;`@Id` 表示主键
=== 半结构数据 <semi-structure>
- 半结构化数据便利了数据的交换(应用之间、前后端之间)
- XML: Extensible Markup Language
- 例如
```XML
<bookstore>
<book category="COOKING" ISBN="100-10-00">
<title lang="en">Everyday Italian</title>
<author><NAME></author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN" ISBN="10000-100-199">
<title lang="en">H<NAME></title>
<author><NAME></author>
<year>2005</year>
<price>29.99</price>
<publisher>ABC</publisher>
<edition>5</edition>
</book>
<book category="WEB" ISBN="10000-10-09">
<title lang="en">XQuery Kick Start</title>
<author><NAME></author>
<author><NAME></author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
```
- XML 可以单独作为一种数据形式,用 Tree model 存储,用 DTD 定义,用 XPath 表达式查询
- JSON: JavaScript Object Notation
=== RDF & Textual Data & Spatial Data
- 略
== 物理存储系统
- 存储介质可以分为:volatile storage(易失存储), non-volatile storage(非易失存储)
- 存储的结构 storage hierarchy
- primary 主存储器
- 快而易失,常见的有主存(main memory)和 cache
- cache 的存取效率最高,但是 costly,主存访问快但是对于数据库而言空间太小
- secondary 二级存储器
- 不容易丢失,访问较快,又叫在线存储
- 常见的是闪存和磁盘(and SSD)
- tertiary 三级存储器
- 不容易丢失,访问慢,但是容量大而 cheap,离线存储
- 磁带,光存储器
- 总体的存储架构:cache--主存--闪存--磁盘--光盘--磁带
#fig("/public/assets/Courses/DB/img-2024-04-25-14-36-17.png")
=== 磁盘 Magnetic Disks
- 组成结构
#wrap-content(
fig("/public/assets/Courses/DB/img-2024-04-22-13-42-25.png"),
[
- read-write head 读写头
- 和磁盘表面靠得很近
- 用于读写磁盘中的文件信息
- tracks 磁道, 由磁盘表面划分,每个硬盘大概有 50k 到 100k 个磁道
- sectors 扇区,由磁道划分而成
- 扇区是数据读写的最小单位
- 每个扇区的大小是 512 bytes,每个磁道有 500$wave$1000 个扇区
- 磁盘控制器:计算机系统和磁盘之间的接口
- Disk subsystem 磁盘子系统:由 disk controller 操纵若干个磁盘组成的字系统
],
)
- 磁盘的性能评价标准
- access time(访问时间),包括:
- seek time(寻道时间):读写头的 arm 正确找到 track 的时间,平均的 seek time 是最坏情况的一半
- rotational latency(旋转延迟):旋转造成的延迟,平均时间是最坏的一半
- data-transfer rate(数据传输率):数据从磁盘读写的速度
- Disk block:logical unit for storage allocation and retrieval,通常在 4k$wave$16k bytes 之间
- 顺序访问模式(Sequential access pattern)与随机访问模式(Random access pattern),尽量用顺序访问替换随机访问。
- I/O operations per second(IOPS ,每秒 I/O 操作数)
- MTTF(mean time to failure,平均故障时间):出现 failure 之前的平均运行时间
- 磁盘访问的优化
- buffering:in-memory buffer to cache disk blocks
- block: 一个磁道中的若干连续扇区组成的序列
- read-ahead:数据预取
- disk-arm-scheduling:磁盘控制器层面的算法优化
- file organization:通过按照访问数据的方式来组织 block 优化访问时间
- Nonvolatile write buffers(非易失性写缓存)
- 把要写的数据先写到一个快速的非易失的缓存里,如 NVM. 这时上面的程序可以继续执行了, NVM 再择机将数据写回到磁盘。
- Log disk(日志磁盘)
=== Flash Storage
- NAND flash
- requires page-at-a-time read (page: 512 bytes to 4 KB),顺序读写和随机读写差不多
- 写了数据如果要再写需要把之前的擦掉,像黑板
- SSD(Solid State Disk)
- 使用标准的面向块的磁盘接口,但在内部将数据存储在多个*闪存*设备上
- 一个 block 在经过许多次 erase 后将会*磨损*
#tbl(
columns: 3,
fill: blue.lighten(70%),
[],
[Magnetic Disk],
[Solid State Disk],
[Retrieve a page],
[5-10 milliseconds],
[20-100 microseconds],
[Random access],
[Random 50 to 200 IOPS],
[reads: 10,000 IOPS writes: 40,000 IOPS],
[Data transfer rate],
[200M],
[500M(SATA), 3G(NVMe)],
[Power consumption],
[higher],
[lower],
[Update mode],
[in place],
[erase $->$ rewrite],
[Realiability],
[MTTF : 500,000 to 1,200,000 hours],
[erase blocks: 100,000 to 1,000,000 erases],
)
- 将 logical page *Remapping* 到 physical page addresses,避免等待 erase 的时间消耗
- 这通过 *Flash translation table*(also stored in a label field of flash pag) 来记录
- 同时负责 wear leveling(磨损均衡):跨物理块均匀分布写操作
- 比较
#tbl(
columns: 5,
fill: blue.lighten(70%),
[],
[DRAM],
[NVM],
[SSD],
[HDD],
[Read Latency],
[1x],
[2-4x],
[500x],
[105x],
[Write Latency],
[1x],
[2-8x],
[5000x],
[105x],
[Persistence],
[No],
[Yes],
[Yes],
[Yes],
[Byte-Addressable],
[Yes],
[Yes],
[No],
[No],
[Endurance],
[Yes],
[No],
[No],
[Yes],
)
=== File organization 文件组织
- 数据库存储在一系列的文件中,每个文件是一系列的 records,每条 record 包含一系列的 fields
- 每个文件被划分为固定长度的 block,block 是数据存取/存储空间分配的基本单位
- 一个 block 有多条记录,在传统的数据库中,我们作以下假设:
- 记录的长度不能超过 block
- 每条记录一定都是完整的
- Fixed-Length Records 定长记录
- Store record $i$ starting from byte $n dot (i – 1)$, where $n$ is the size of each record.
- 三种 delete 方式:
+ 顺序移动,低效
+ 用最后一条覆盖
+ Free List,用链表的形式来存储 free records
#fig("/public/assets/Courses/DB/img-2024-04-22-15-07-07.png")
- Variable-length records 变长记录
- 典型的变长记录
- 属性按照顺序存储
- 变长记录由两部分组成:用 offset+length 的形式指示变长信息以及本身就是定长属性的定长段,以及存储实际信息的变长段
- 空值用 null-value bitmap 存储
- 例如:这里位置 12 放的 65000 是定长的 salary,位置 20 放的 0000, 表示前面四个属性均是非空的, 1 表示空。(放在前面也可以,只要在一个固定位置能找到即可)前提:每一个记录都是被放在一起的。(有按列存储的方式)
#fig("/public/assets/Courses/DB/img-2024-04-22-14-54-07.png")
- 变长记录如何安置到 block 中?*slotted page* 结构
- slotted page header 包含
+ 记录的总数
+ block 中的 free space 的末尾
+ 每条记录所在的位置和大小
- 删除的两种策略:
+ 顺序移动,低效
+ 打个标记,等后面如果需要分配内存但不够用时,再一次性重整之前的空间。
#fig("/public/assets/Courses/DB/img-2024-04-22-14-54-57.png")
- 文件中记录的组织方式
- heap
- sequential
- multitable clustering file organization
- B+ tree
- hashing
- Heap File Organization
- 记录可以被放置在文件中任何 free space,通常它们一旦申请了就不会移动
- 找到空闲空间十分重要,使用 *Free-space map*
- 维护一个空闲块的地图,记录这个块的空闲程度。
- multi-level free-space map
#fig("/public/assets/Courses/DB/img-2024-04-22-15-13-09.png")
- Sequential File Organization
- 适用于需要对整个文件进行顺序处理的应用程序
- 文件中的记录按搜索键(*search-key*)排序
- Deletion – use pointer chains
- Insertion – locate the position where the record is to be inserted
- 逻辑上联系,物理上分开到新的 block 中,不然需要频繁地移动
- 一段时间后进行物理重组(*reorganize*),否则就失去了顺序性、局部性的意义
#fig("/public/assets/Courses/DB/img-2024-04-22-15-16-16.png")
- Multitable Clustering File Organization
- 把相关信息存放在一起组成 clusters
- 这样,对经常链接的两个表 $"department" join "instructor"$ 比较高效;但对单独查询某个信息就不太好
#fig("/public/assets/Courses/DB/img-2024-04-22-15-23-17.png")
- Table Partitioning
- 一个表太大,对于并行访问可能引发冲突,也不利于数据的存储,并且每个操作的开销过大,于是我们可以把表分开
- 事实上,我们可以用不同的切分方式实施多次,并且存在不同的存储介质上,比如把热点数据放在 SSD 上,把冷数据放在 magnetic disk 上
- Data Dictionary Storage
- 数据字典、或称系统目录,存储 metadata,比如
+ Information about relations
+ User and accounting information, including passwords
+ Statistical and descriptive data
+ Physical file organization information
+ Information about indices
=== 存储缓冲区的管理
- block 是存储空间申请和数据转移的基本单位
- 通过将数据放到主存中来提高访问效率
- buffer manager:用于管理缓冲区中的内存分配
- 当需要从磁盘读取 block 的时候,数据库会调用 buffer mananger 的功能
- 如果 block 已经在 buffer 中了,就直接返回这个 block 的地址
- 如果不在,则 buffer manager 会动态分配 buffer 中的内存给block,并且可能会覆盖别的 block,然后将磁盘中 block 中的内容写入 buffer 中
- 涉及到 buffer 的替换算法 LRU strategy(最近最少策略) 即替换掉最近使用频率最低的 block
- 用链表来表示访问次序
#fig("/public/assets/Courses/DB/img-2024-04-22-15-44-06.png")
- pinned block: 内存中的不允许写回磁盘的 block,表示正在处理事务或者处于恢复阶段(正在访问这一块,那么这一块不能被替换出去)
- keep a `pin_count`,buffer block 只有在 `pin_count` 为 0 时才能被替换
- Shared and exclusive locks on buffer
- 当 page 在 move/reorganize 的时候,需要防止内容读取,同时要确保同一时刻只有一个 move/reorganize 操作
- readers get *shared lock*; updating to a block requires *exclusive lock*
- Locking rules:
+ 同一时刻只有一个进程能得到排他锁
+ shared lock 和 exclusive lock 不能同时存在
+ shared lock 可以同时赋予多个进程
#wrap-content(
fig("/public/assets/Courses/DB/img-2024-04-22-18-30-34.png"),
[
- Clock
- LRU 算法的近似替代
- 当某页被访问时,设其访问位为 1。当需要淘汰一个页面时,只需检查页的访问位
- 如果是 0,就选择该页换出;如果是 1,则将它置为 0,暂不换出,继续检查下一个页面,若第一轮扫描中所有页面都是 1,则将这些页面的访问位依次置为 0 后,再进行第二轮扫描
],
)
```
When replacement necessary:
do for each block in cycle {
if (reference_bit == 1)
set reference_bit = 0;
else if (reference_bit == 0)
choose this block for replacement;
} until a page is chosen;
```
=== Column-Oriented Storage
- 列存储 (Column-Oriented Storage) 是将关系的每个属性单独存储的方式。
- 列存储的优点有:
+ 如果只有一部分属性被访问,可以减少 I/O 次数
+ 可以提高 CPU 缓存性能
+ 可以提高压缩效率
+ 可以在现代 CPU 架构上实现向量处理
- 列存储的缺点有:
+ 从列存储中重建元组的代价较高
+ 元组的删除和更新代价较高
+ 解压缩代价较高
+ 列存储在决策支持系统中比行存储更有效,而在事务处理中,传统的行存储更受欢迎。一些数据库支持同时使用两种存储方式,称为混合行列存储(Hybrid Row/Column Stores)
== 索引
- 数据库系统中引入索引机制,用于加快查询和访问需要的数据
- search key 通过一个属性值查找一系列属性值,用于文件中查询
- Index file 索引文件包含一系列的 search key 和 pointer(两者的组合被称为 index entry)
#tbl(
columns: 2,
[search key],
[pointer],
)
- 查询方式是通过 search key 在 index file 中查询 data 的地址(pointer),然后再从 data file 中查询数据
- 两种 search key 的排序方式:ordered index,hash index
- 索引的不同指标
- 查询有两种(Point query 和 Range query)
- Access time, Insertion time, Deletion time, Space overhead
- Ordered indices 顺序索引:index entry 按照 search key 的值来进行排列
- Primary index 主索引(Also called clustering index,聚集索引)
- 主索引和数据内的顺序是一样的。点查和范围查都是比较高效的。
- search key 往往是 primary key,但不一定;如果 key 不是一个主键,那可能会对应多个记录,后面辅助索引也是一样。
#fig("/public/assets/Courses/DB/img-2024-04-29-13-43-51.png")
- Secondary index 辅助索引(Also called non-clustering index)
- 不要跟多级索引搞混,仍是一级,但 search key 值的排序不同于 file 内数据的顺序
#fig("/public/assets/Courses/DB/img-2024-04-29-13-43-32.png")
- 索引的不同方式
- Dense index 密集的索引:每一条记录都有对应的索引
- Sparse index 稀疏的索引:查询时从 pointer 指向记录开始顺序查找;需要的空间和插入删除新索引的开销较小,但是比密集的索引要慢
#grid(
columns: 2,
fig("/public/assets/Courses/DB/img-2024-04-29-13-42-29.png", width: 85%),
fig("/public/assets/Courses/DB/img-2024-04-29-13-42-45.png"),
)
- Multilevel index 多级索引,如对索引文件本身再建立一次索引
- 分为 outer index 和 inner index
=== B+ 树索引
- B+ 树文件索引
- 通过 B+ 树的索引方式来寻找文件中数据的地址,B+ 树的定义和 ADS 中的 B+ 树类似,
- 树的非叶节点由指向儿子的指针和充当路标的 search-key 相间组合而成
- 两个 search-key 之间的指针指向的数据的值在这两个 search-key 之间
- note:下面这张图实际上用的是 secondary index,只是没画出来(一旦出现同名而 ID 分开的情况,这张图就寄了)
#fig("/public/assets/Courses/DB/img-2024-04-29-13-50-04.png")
- B+ 树上的查询的时间复杂度是 $log N$ 级别,$N$ 是 search key 的总个数
- 查询的路径长度:不会超过 $ceil(log_(n/2) K/2) + 1$,其中 $K$ 是 B+ 树中的索引的个数(即规模 $N$)
- B+ 树的一个节点的大小和一个磁盘区块一样大(往往是 4KB),而 $n$ 的规模一般在 $100$ 左右(矮胖)
- B+ 树的查询,支持 point query, range query 和整体的 scanning
- B+ 树的更新:插入和删除
- 插入的算法:先找到该插入的位置直接插入,如果当前的节点数量超过了阶数 $M$ 则拆成两个部分,并向上更新索引
- 删除的算法: 直接把要删除的节点删除,然后把没有索引 key 的非叶节点删除,从旁边找一个叶节点来合并出新的非叶节点
- internal node 实际上不一定要删除某一项(也就是说存在 internal 节点中的某个值不在 leaf node 中的情况)
- B+ 树的相关计算
- 高度的估计(似乎是从 $1$ 开始算):
- B+ 树高度最小的情况:所有的叶节点都满,此时的 $h = ceil(log_N M)$
- 最大的情况,所有的叶节点都半满,此时的 $h= ceil(log_[N/2] M/2)+1$
- size 大小的估计:也是两种极端情况
- 给定高度,计算能表示的 record 数量最多最少是多少
#fig("/public/assets/Courses/DB/img-2024-04-29-14-25-39.png")
- 给定 size,计算高度,或更精细地计算每层节点数
#fig("/public/assets/Courses/DB/img-2024-04-29-14-34-17.png")
=== B+ trees issues
- B+ 树文件组织
- 叶子节点不再放索引项,放记录本身。
- 可以改变半满的要求以提高空间利用率。
#fig("/public/assets/Courses/DB/img-2024-04-29-14-46-58.png")
- Record relocation and secondary indices
- 考虑记录的 *move*,所有 secondary index 都要更新
- solution: 后面讲的 non-unique search keys 或者改造 secondary B+ tree index,将“索引+pointer”变为“索引+primary key”(添加了继续从 primary key 查询到实际地址的开销)
- Variable length strings as keys
- solution: #strike[用魔法打败魔法],使用动态 fanout,即不再以指针数量作为节点切分的标准,而是以空间使用率(space utilization as criterion for splitting)
- Prefix compression
- 对 internal node,可以仅保留足够区分 entries 的前缀,以节省空间
- 对 leaf node,可以共享前缀
- Multiple-Key Access
- 对频繁出现的多个属性的查询,可以用组合属性建立 B+ 树
- B+ 树算法是一模一样的,只是比较函数发生变化
- Non-unique Search Keys
- B+ 树叶子节点不直接指向磁盘里的某个数据,而是指向一个块
- 或者,可以在索引上加上一个属性成为 multiple-key,使它对应的记录唯一
- 对原本的索引查找,可以视为加上范围查找,如 ${a_i=v} -> {(v,-infty) "to" (v,infty)}$
=== Bulk Loading and Bottom-Up Build
- 如果我们一次性插入很多数据,有两种策略
+ Efficient alternative 1: 插入前先排序
- 局部性较好,减少 I/O
+ Efficient alternative 2: 自底向上构建
- 如果是初始化 bulk load
+ 首先排序
+ 随后从最底层开始,layer by layer 地创建 B+ 树,写入磁盘的过程可以同时进行
#fig("/public/assets/Courses/DB/img-2024-04-29-15-08-06.png")
- 如果是对已有 B+ 树 bulk load
+ 遍历已有 B+ 树的叶子层,将其和新数据 merge sort,然后重新 layer by layer 地构建 B+ 树
#fig("/public/assets/Courses/DB/img-2024-04-29-15-15-22.png")
=== Indexing in Main Memory and Flash
- In Memory: 尽管快于 disk/flash,但仍慢于 cache
- 对一个拥有大 node 的 B+ tree,可能会造成许多 cache misses
- 数据结构或算法是否能够利用 cache 特性被称为 cache-aware or cache-conscious
- 考虑到 disk access,每个 node 的大小依然应该是 $4K$
- 但在 node 中查询,无论用顺序查找还是二分之类,都没有充分利用 cache,此时的解决方法是 node 内,再用一个树形结构拆散成 $64B$,也就是节点内再细分成一棵树(而不是用数组存储)
#fig("/public/assets/Courses/DB/img-2024-04-29-19-30-51.png")
- In Flash: 需要先 erase 才能 write,同时擦的次数是有限制的
- 最好的方法是从底构建,然后顺序写入
- 使用 LSM tree
=== Write Optimized Indices
- Performance of B+-trees can be poor for *write-intensive*(写密集型) workloads
==== Log Structured Merge (LSM) Tree
#grid(
columns: 2,
[
- consider only inserts/queries for now
- 原始版本(插入)
- 记录首先插入到 in-memory tree($L_0$ tree)中
- 当 $L_0$ tree 满时,将其移动到 disk,构建或合并到 $L_1$ tree(使用 bottom-up build)
- 以此类推
- 好处
- Inserts are done using only *sequential I/O* operations
- *Leaves are full*, avoiding space wastage
- Reduced number of I/O operations per record inserted as compared to normal B+ tree(up to some size)
- 坏处
- Queries have to search multiple trees
- Entire content of each level copied multiple times(一定的空间浪费)
- 变体: Stepped-merge index
- 磁盘上每层有 $k$ 棵树,当 $k$ 个索引处于同一层时,使用 $k$ 路 merge 合并它们并得到一棵层数 +1 的树
- 相比原始版本减少 write cost,但使得 query 变得 even more expensive
- point query 的优化——bloom filter(布隆过滤器)
- 每棵树对应一个 bloom filter,用于判断某个 key 是否可能在这棵树中(1 不一定在,0 一定不在)
- LSM trees 最初作为 disk-based indices 被引入,但对减少 flash-based indices 的擦除也很有帮助
],
[
#fig("/public/assets/Courses/DB/img-2024-04-29-19-35-47.png")
#v(5em)
#fig("/public/assets/Courses/DB/img-2024-04-29-19-45-44.png")
#fig("/public/assets/Courses/DB/img-2024-04-29-20-05-31.png")
],
)
==== Buffer Tree
- B+ tree 的每个 internal node 中把一定位留空作为 buffer
- 插入时先存储在 buffer 中,等到一定量后批量移动到下一个 level 的 node
- 相应地,减少了每个记录的 I/O 次数
==== bitmap indices
- Bitmap indices are a special type of index designed for efficient querying on multiple keys
- 特别适用于这种情况:记录数目固定,但想要加快查询速度的情况,并且待查询的属性的*取值数量较少*
- 对于多属性查询,使用按位*与*、*或*即可很方便地得到结果
- bitmap 的所需空间相比 original relation size 要小得多
- 在计算机中打包成 word(32 or 64) 进行计算
#fig("/public/assets/Courses/DB/img-2024-04-29-20-16-48.png")
=== 总结:存储结构和B+树的计算
- 记录的存储:
- 数据库的记录在 block 中存储,一个 block 中有大量的记录存储,有线性存储的,也有使用 B+ 树索引的
- 线性存储的记录:
- 假设一条记录的长度为 $L$,block 的大小为 $B$,那么一条记录中最多有$ floor(B/L)$ 条记录
- 如果一共有 $N$ 条记录,一个 block 中有 $M$ 条记录,那么一共需要$ceil(N/M)$ 个 block,而 $M=floor(B/L)$
- B+ 树索引 block 的计算,假设 block 的大小为 $B$,指针的大小是 $a$,被索引的属性值大小是 $b$
- 要注意指针节点比属性值多一个,所以一个块上的扇出率 $n$(fan-out rate)是$ floor((B-a)/(a+b))+1$
- $n$ 也就是这个 B+ 树的阶数,然后根据公式来估算 B+ 树的高度,其中 $M$ 应该是作为索引的值可以取到的个数
== 查询处理 QueryProcess
#quote[印象中这一部分的作业题以套公式算为主]
- 查询处理的基本步骤
- Parsing and translation 解析和翻译
- Optimization 优化
- 一种 SQL 查询可能对应了多种等价的关系代数表达式
- 估计每种方式的 cost,选择最节约的方式进行查询
#fig("/public/assets/Courses/DB/img-2024-05-06-13-39-00.png")
- Evaluation 评估
- 更细化地指定每个操作使用的算法,指定各个操作如何协调
#fig("/public/assets/Courses/DB/img-2024-05-06-13-39-43.png")
- Query cost 的计算
- 主要的 cost 来源:disk access
- seek(磁盘读写头寻道)
- block read
- block written,且 write 的 cost 要大于 read
- 为简单起见,read 和 write 合在一起作为 block transfer,并且忽略 CPU cost(为简单起见),忽略最后一次写回磁盘的开销(因为 pipeline)
- cost 计算的方式:在 $B$ 个 blocks 中查询 $S$ 次所消耗的时间$= B times t_T+S times t_S$,其中$t_T$ 表示一次 block transfer 的时间,$t_S$ 表示一次 seek 的时间
- cost依赖于主存中*缓冲区的大小*:更多的内存可以减少 disk access
- 通常考虑最坏的情况:只提供最少的内存来完成查询工作
=== select 的 cost 估计
- Algorithm1:线性搜索,查询每个 block 判断是否满足查询条件
- 只用 seek 一次(假定数据页都放在一起)
- 最坏情况:$"Cost" = b_r times t_T + t_s$,其中$b_r$ 是关系 r 中*存储了记录的block的数量*
- 如果通过键来搜索,在找到的时候就停止,则平均情况:$"Cost" = (b_r\/2) times t_T + t_s$
- Index scan--使用索引进行搜索
- Algorithm2: primary index, equality on key,使用 B+ 树搜索一条记录
- $"cost" = (h_i+1) times(t_T+t_S)$ --- $h_i$ 是索引的高度(从 $1$ 开始)
- Algorithm3: primary index, equality on non-key,使用 B+ 树搜索多条记录
- 想要的结果会存储在连续的block中(因为有主索引)
- $"cost" =h_i (t_T + t_S) + t_S + t_T * b$ 其中$ b$ 表示包含匹配记录的 block 总数
- Algorithm4:Secondary index, equality on key
- $"cost" = (h_i + 1) times (t_T + t_S)$
- Algorithm4':Secondary index, equality on non-key
- 检索了$n$ 条记录,不一定在同一个 block 上面,设共分布在 $m$ 个 block 上
- $"cost" = (h_i + m + n) times (t_T + t_S)$ 有时候会非常耗时
- Algorithm5:comparison
- `<` 直接扫描
- `>` 使用 primary index: $"cost" =h_i (t_T + t_S) + t_S + t_T * b$ 与 Algorithm3 一样
- Algorithm6 $wave$ Algorithm9,涉及比较和复杂操作,没有具体的公式(可能比较难算了)
=== sort 的 cost 估计
- Sort:*external* *sort-merge* 类似于 ads 里面的外部归并排序
- 基本步骤如下($M$ 表示 memory 能包含几个 block,$b_r$ 表示 block 的数量)
- create sorted runs,创建归并段,即对 blocks 分段排序,显然分段大小受制于 $M$
- merge the runs,将这些段进行 $k$ 路归并,可能需要进行多次
- 下图中,假设一个字母加一个数字就是一个块(每个块包含 $1$ 个记录,$b_r=12$),$M=3$,那么有 $ceil(b_r\/M)=4$ 个总的归并段,$"passes"=2$,每次 pass 处理 $M-1=2$ 个归并段,每个归并段同时处理 $1$ 个 block($b_b=1$)
#fig("/public/assets/Courses/DB/img-2024-05-06-20-12-04.png")
- 思考为什么明明看起来是相邻的块依然要 seek?
#grid(
columns: 2,
gutter: 1em,
align(horizon, fig("/public/assets/Courses/DB/img-2024-05-06-20-19-23.png")),
[
- Simple version
- runs 总数 $ceil(b_r\/M)$
- merge pass 总数 $ceil(log_(M-1)(b_r\/M))$
- 如果归并段 $N$ 小于内存页 $M$,该次 pass 能一下子处理完,使用 $N$ blocks 作 buffer 处理数据,$1$ block 作输出(满了就写回并清空)
- 否则,该次 pass 分多次处理,用 $M-1$ 个 block 作 buffer(在 simple version 下,每次处理 $M-1$ 个归并段),$1$ 个 block 作输出
- Cost of Block Transfer
- During run generation 为 $2 b_r$;每次 pass 过程中的 disk access 数量也为 $2 b_r$,因为每个块都需要被读取和写回
- 忽略最后一次写回的 $b_r$,外部排序中总的 disk access 次数 $ (2ceil(log_(M-1)(b_r\/M))+1)b_r $
- Cost of Seek
- During run generation 为 $2ceil(b_r\/M)$,也就是两倍归并段的总数;每次 pass 过程中的 disk access 数量为 $2b_r$
- 忽略最后一次写回的 $b_r$,外部排序中总的 seek 次数 $ 2 ceil(b_r\/M) + b_r (2ceil(log_(M-1)(b_r\/M))-1) $
],
align(horizon, fig("/public/assets/Courses/DB/img-2024-05-06-20-31-39.png")),
[
- Advanced version
- 每个归并段同时只处理一个 block 导致在合并的时候太多次的 seek,考虑每个归并段同时处理 $b_b$ 个 blocks,这样在 merge 阶段,每个归并段内的多个块是写在一起的,只用一次 seek 就可以查到 $b_b$ 个 block
- read/write $b_b$ blocks at a time; can merge $floor(M\/b_b) - 1$ runs at a time
- runs 总数 $ceil(b_r\/M)$; merge pass 总数 $ceil(log_(floor(M\/b_b) - 1)(b_r\/M))$
- Cost of Block Transfer
- During run generation 为 $2 b_r$;每次 pass 过程中的 disk access 数量也为 $2 b_r$
- 外部排序中总的 disk access 次数 $ (2ceil(log_(floor(M\/b_b) - 1)(b_r\/M))+1)b_r $
- Cost of Seek
- During run generation 为 $2ceil(b_r\/M)$;每次 pass 过程中的 disk access 数量为 $2ceil(b_r\/b_b)$
- 外部排序中总的 seek 次数 $ 2 ceil(b_r\/M) + floor(b_r\/b_b) (2ceil(log_(floor(M\/b_b) - 1)(b_r\/M))-1) $
]
)
=== Join 的 cost 估计
- 这里都没有考虑写出去的消耗(考试的时候可能变通),join 后给 pipeline 后的其它步骤用
- nested-loop join
- 计算theta-join表达式:$r join_theta s$ 算法的伪代码如下
- $r$ 指外层循环,$s$ 指内层循环
```
for each tuple tr in r do begin
for each tuple ts in s do begin
test pair (tr,ts) to see if they satisfy the join condition
if they do, add tr • ts to the result
end
end
```
- block transfer次数: $n_r times b_s+b_r$
- seeks的次数 $n_r+b_r$
- block nested-loop join $r join_theta s$
```
for each block Br of r do begin
for each block Bs of s do begin
for each tuple tr in Br do begin
for each tuple ts in Bs do begin
Check if (tr,ts) satisfy the join condition
if they do, add tr • ts to the result.
end
end
end
end
```
- 两个内存循环在内存中进行,忽略不计
- 最坏情况的 cost: block transfer --- $b_r times b_s+b_r$; seeks --- $2b_r$
- 从这里也可以看出,大的关系应该放在内层循环
- 最好情况的 cost: block transfers --- $b_r+b_s$; seeks --- $2$(内存空间足够大,一次全读进来,挺扯的。。。)
- 优化:使用$M-2$个 block 容纳外层($M$是内存可以容纳的block数量),此时
- block transfer次数=$ceil(b_r/(M-2)) times b_s+b_r$
- seek次数= $2ceil((b_r)/(M-2))$
- Index nested-loop join(在有索引的时候)
- 索引一定程度上可以代替 file scan,内层关系使用 index
- 在最糟情况下,内存只能容纳外关系的一个 block(其实应该至少还得容纳内关系的一个 block),对其中的每一条记录,用索引查找 $s$
- $"cost"=b_r (t_T+t_s)+c times n_r$ 其中 $c$ 表示遍历索引和找到所有匹配的 $s$ 中的 tuple 所消耗的时间,可以用*一次s上的单个selection来估计s的值*
- Merge-Join(如果两个关系是有序的,或者权衡利弊排序后再用这个方法)
- 只能在natural-join和equal-join中使用
- 也是会有微型的两重循环(两边多个可以连接的时候)
- 也可以像 merge sort 一样同时处理多个 block
- block transfer的次数=$b_r+b_s$,seek的次数=$ceil(b_r/r_b)+ceil(b_s/s_b) ~(r_b+s_b=M)$ (最值计算,柯西不等式)
- hybrid merge-join:一个关系有序,另一个关系在连接属性上拥有 secondary index(B+ 树索引)
- 先把排序关系和未排序关系 B+ 树的叶子做 merge(后者树上叶子的 key attr 是有序的,因此可以做 merge,这里可以理解为 merge 上指针)
- transfer 和 seek 的代价参照 Merge-Join
- 随后,先按照指针指向的地址排个序(而不是直接按地址寻找内容拼接,因为更小)
- 假设生成的 address 都在内存中,那么不涉及磁盘代价
- 按照地址寻找内容,替换指针,拼接成结果
- 设指针落在 $n$ 个 block 上,transfer 和 seek 的代价都是 $n$
- Hash join:使用hash函数进行join
- hash join 的想法来自于一个直觉:我们是否可以把要 join 的属性按近似程度分门别类,这样只用比较同一类的属性就可以了,大大减少了比较的次数
- 哈希函数 $bold(h())$ 把 join 属性映射到 {0, 1, ..., $n_h$},$r_i$ 只需和 $s_i$ 比较,无需考虑其它任何不在 $s_i$ 中的 partition
- 我们设小的关系为 $s$,称作 build input,大的关系为 $r$,称作 probe input(注意这里大小关系跟前面反一反)
- 流程为
+ partition build input(s),用哈希函数 $h()$,并且为每个 partition 预留一个 block 作为 buffer
+ partition probe input(r),用哈希函数 $h()$
+ 链接 $r_i$ 和 $s_i$ $(0 =< i < n_h)$,方法是为每个 $s_i$ 创建一个不同与之前的 in-memory 哈希函数 $h_i ()$,再 one by one 地从磁盘中读取 $r_i$;然后对每个 tuple $t_r$,利用 $h_i ()$ 快速确定是否有与之对应的 $t_s$,链接起来写到输出 buffer
#fig("/public/assets/Courses/DB/img-2024-06-18-14-02-59.png",width:50%)
- 需要满足 $ceil(b_s \/ M) + 1 < n_h < M - 1$
- 后者的要求来自于*分块时*需要 $n_h$ 个缓冲块,如果不够那分都分不了;前者的要求来自 $s$ 根据 $h()$ *分块后*能够放进内存($+1$ 留给 buffer)
- 如果不满足怎么办?多按照右边的限制多次哈希,直到满足左边的限制,即使用 Recursive partitioning
- 一般最后一级的哈希函数是 $n_h = ceil(b_s \/ M)*f$,$f$ 为修正因子
- 不需要递归切分时,近似来说就是 $M > sqrt(b_s)$(*重要*)
- cost of hash-join
- If recursive partitioning not needed
- block transfer: $3(b_r+b_s)+4n_h$
- partition: 读 $b_r+b_s$ blocks,写 $(b_r+b_s)+2n_h$ blocks
- join: 读 $(b_r+b_s)+2n_h$,不考虑写
- $n_h$ 是额外加的可能超出 buffer 大小的情况
- seeks: $2(ceil(b_r/b_b)+ceil(b_s/b_b)) + 2n_h$
- $b_b$ 怎么算?$b_b$ 个 input buffer 加上 $n_h times b_b$ 个 output buffer,合一起等于 $M$
- $b_b=floor(M\/(n_h+1))$(应该是这样算)
- If recursive partitioning needed
- 需要 $ceil(log_(floor(M\/b_b)-1) (b_s\/M))$ 轮 partition
- partition $=2(b_r+b_s) ceil(log_(floor(M\/b_b)-1)(b_s\/M))+b_r+b_s$
- seek $=2(ceil(b_r\/b_b)+ceil(b_s\/b_b))ceil(log_(floor(M\/b_b)-1)(b_s\/M))$
- 如果所有东西都能放进主存里,则$n_h=0$ 并且不需要 partition(只需 in-memory 的哈希操作),即 cost $=b_r+b_s$
- 其它操作:Aggregation, Set Operations, Outer Join
- Set Operation 用 hash join 的思想举一反三
- Evaluation of Expression 表达式求值
- *Materialization* 实体化
- 依次进行表达式的计算,构建前缀树递归进行
- Pipelining 流水线,同时评估多个操作
- evaluate several operations simultaneously , passing the results of one operation on to the next.
#note[
做题时的几个注意点:
+ external merge sort 的 seek 次数是两倍归并段的总数,读一次写一次,虽然我感觉读和写不用分开(磁盘头停在原地不就好了?)。。。
+ ……
]
== 查询优化 Query Optimization
- 两种查询优化的办法
- 找到等价的查询效率最高的关系代数表达式
- 指定详细的策略来处理查询
=== 等价关系代数表达式
- Equivalent Expressions 等价的关系代数表达式
- *evaluation plan*:类似于算术表达式的前缀树,表示了每步操作进行的过程
- Cost-based optimization,基于 cost 的优化
- 基本步骤
- 用运算法则找到逻辑上等价的表达式
- 注释结果表达式来获得查询计划
- 选择cost最低的表达式
- cost 的估算基于
- 统计信息量的大小,比如 tuples 的数量,一个属性不同取值的个数
- 中间结果的数量,用于复杂表达式的优化
- 算法的消耗
- 通过 `explain <query>` 可以查看到底被处理成了什么样
==== *等价表达式的规则*
+ 合取选择和选两次等价:$sigma_(theta_1 and theta_2)(E)= sigma_theta_1( sigma_theta_2(E))$
+ 选择两次的顺序可以交换;$sigma_theta_1(sigma_theta_2(E))= sigma_theta_2( sigma_theta_1(E))$
+ 嵌套的投影只需要看最外层的:$Pi_L_1(Pi_L_2(dots(E)))= Pi_L_1(E)$
+ 选择和笛卡尔积可以变成 theta join:$sigma_theta (E_1 times E_2)=E_1 join_theta E_2$
- 两步 theta join 可以合并:$sigma_theta_1(E_1 join_theta_2 E_2)=E_1 join_(theta_1 and theta_2)E_2$
+ Theta-join 和自然连接可以改变顺序:$E_1 join_theta E_2=E_2 join_theta E_1$
+ 自然连接满足结合律:$(E_1 join E_2) join E_3=E_1 join (E_2 join E_3)$
- Theta-join 的结合规则:$(E_1 join_theta_1 E_2) join_(theta_2 and theta_3) E_3=E_1 join_(theta_1 and theta_3) (E_2 join_theta_2 E_3)$,这里 $theta_2$ 只牵涉到 $E_2, E_3$ 中的属性
+ 选择操作和 Theta-join 的混合运算
- 当$ theta_1$ 中的属性都只出现在E1中的时候:$ sigma_theta_1(E_1 join_theta_2 E_2)= sigma_theta_1 (E_1) join_theta_2 E_2$
- 当$ theta_1, theta_2$ 分别只包含E1,E2中的属性时:$ sigma_(theta_1 and theta_2)(E_1 join_theta E_2)= sigma_theta_1(E_1) join sigma_theta_2(E_2)$
+ 投影操作和 Theta-join 的混合运算
- 当 $theta$ 只包含$L_1 or L_2$ 中的属性的时候:$ Pi_(L_1 or L_2)(E_1 join_theta E_2)=(Pi_L_1(E_1)) join_theta (Pi_L_2 (E_2))$
- 当 ?
9. & 10. 集合运算中的交运算和并运算满足交换律和结合律
11. 选择操作中有集合的运算时满足分配律(比如进行差运算再选择等价于分别选择再差运算)
12. 投影操作中有并运算时满足分配律
- ...... 很琐碎,应该不用掌握
- Join的顺序优化:当有若干张表需要join的时候,*先从join后数据量最小的开始*,后面还有一种基于动态规划的方法
- 可以通过共享相同的子表达式来减少表达式转化时的空间消耗,通过动态规划来减少时间消耗
=== cost 的估计
- 忽略 IO 的每个操作的估计
- 基本的变量定义
- $n_r$ 表示关系 $r$ 中元组的数量(也就是关系 $r$ 的 size)
- $b_r$ 包含 $r$ 中元组需要的 block 数量
- $l_r$ $~~r$ 中一个元组的 size
- $f_r$ block factor of $r$ 比如可以选取一个 block 能容纳的 $r$ 中元组的平均数量
- $V(A, r)$ 关系 $r$ 中属性 $A$ 可能取到的不同的值的数量,$=>$ Histograms
- 当关系 $r$ 中的元组都存储在一个文件中的时候 $b_r= ceil(n_r \/ f_r)$
- 选择的估计
- 单属性选择
- 从 $r$ 中选择 $A$ 属性 $=x$ 的$"size" = n_r / V(A,r)$
- 选择 $A$ 属性小于 $x$ 的 size
- $"size"=0$ if $x < min(A,r)$
- $"size"=n_r times (x-min(A,r)) / (max(A,r)-min(A,r))$
- 如果缺少统计信息,我们假定 $"size"= n_r/2$
- 选择 $A$ 属性大于 $x$,和上面的表达式是对称的
- complex selection 多重选择
- 假设$s_i$是满足条件$ theta_i$的元组的个数,假设*独立分布*
- conjunction $"size"=n_r times (s_1 times s_2 times … times s_n)/n_r^n$
- disjunction $"size"=n_r times (1-(1- s_1/n_r) times dots times (1- s_n /n_r))$
- negation $"size"=n_r-"size"(sigma_theta (r))$
- join 的估计
- 笛卡尔积的情况下,关系 $R,S$ 的 join 最终元组的个数为 $n_r times n_s$
- 如果 $R sect S$ 为空,则自然连接的结果和笛卡尔积的结果相同
- 如果非空,且 $R sect S$ 是 $R$ 的 key,则 $R,S$ 的自然连接结果中的元组个数不会超过 $n_s$
- 如果 $R sect S$ 的结果是 $S$ 到 $R$ 的外键,则最后的元组数为 $n_s$,反之对称
- 一般情况,$R sect S={A}$不是键,自然连接的结果 size 估计值为$(n_r times n_s)/(max(V(A,r),V(A,s)))$
- 其他操作的估计
- 投影(合并)的 $"size"=V(A,r)$
- 聚合操作的 $"size"=V(A,r)$
- 集合操作:*并*估计为相加,*交*估计为取最小,*差*估计为取前者
- 外部连接(上界估计):
- 左外连接的 $"size" = "自然连接的size" + r "的size"$
- 右外连接的 $"size" = "自然连接的size" + s "的size"$
- 全连接的 $"size" = "自然连接的size" + r "的size" + s "的size"$
- 不同值(distinct)个数的估计
- 选择,估计 $V(A, sigma_theta (r))$
- 如果 $theta$ 强制要求接受一个值或一组值……
- 如果能算出中选率:$V(A, sigma_theta (r))=V(A,r) times "中选率"$
- 否则,$V(A, sigma_theta (r))=min(V(A,r), n_(sigma_theta (r)))$
- join 的估计,$V(A, r join s)$
- 如果 $A$ 的所有取值都来自 $r$,那么 $V(A,r join s)=min(V(A,r), n_(r join s))$
- 否则,如果 $A$ 包含 $r$ 中的 $A_1$ 和 $s$ 中的 $A_2$,$ V(A, r join s) = min(V(A_1,r) * V(A_2-A_1,s), V(A_1-A_2,r) * V(A_2,s), n_(r join s)) $
- 基于 cost 的 join 顺序优化
- $n$ 个关系进行自然连接有$(2n-2)!/(n-1)!$种不同的join顺序
- 找到最合适的 join-tree 的办法:递归地尝试,动态规划+局部搜索的办法,时间复杂度 $O(n^3)$,空间复杂度 $O(2^n)$
- Left Deep Join Trees 左倾树,当结合方式只考虑左倾树的时候,找到最优解的时间复杂度是 $O(n 2^n)$,$2^n$
- *Heuristic Optimization* 启发式优化
- 尽早进行 selection
- 尽早进行 projection
- 选择最严格的 selection 和 operations 操作(选出来的比例越少越好)
- 用于查询优化的结构
- pipelined evaluation plan
- optimization cost budget
- plan catching
=== Additional Optimization Techniques\*\*
- Nested Subqueries
- Materialized Views
- 略
|
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/template/sections/lists.typ | typst | MIT License | = Lists
== Bulleted lists
- Item 1
- #lorem(20)
- #lorem(20)
- #lorem(20)
- #lorem(20)
- #lorem(20)
- #lorem(20)
- #lorem(20)
- #lorem(10)
- #lorem(10)
\ // add a line break to separate the list with a new indented paragraph
#lorem(30)
== Numbered lists
+ Item 1
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(20)
+ #lorem(30) // otherwise leave with a single line break to continue without indentation
#lorem(30)
#lorem(50)
|
https://github.com/EgorGorshen/typster-scripts | https://raw.githubusercontent.com/EgorGorshen/typster-scripts/main/README.md | markdown | MIT License | # typster-scripts
## tabler
скрипт для создания таблиц истиности (note: `<=` тоде самое что `xor` | `->` )
```sh
$ ./tabler "lambda x, y, z: x and y <= z"
```
```typ
#let fal = table.cell(
fill: red.lighten(60%)
)[False]
#let tru = table.cell(
fill: green.lighten(60%)
)[False]
#table(
columns: 4,
stroke: 0.5pt,
align: center+ horizon,
[x], [y], [z], [$x and y -> z$],
fal, fal, fal, fal, fal, fal, tru, fal, fal, tru, fal, fal, fal, tru, tru, fal, tru, fal, fal, tru, tru, fal, tru, tru, tru, tru, fal, fal, tru, tru, tru, tru
)
```
|
https://github.com/TillWege/nSim | https://raw.githubusercontent.com/TillWege/nSim/main/paper/main.typ | typst | zlib License | #import "template.typ": *
#show: project.with(
title: "Simulation von Gravitation im Sonnensystem",
subtitle: "Hochschule Rhein-Waal\nFakultät Kommunikation und Umwelt\nMethoden und Werkzeuge der modernen Astronomie",
authors: (
"<NAME> (28891)",
),
date: "9.July 2024",
)
#set heading(numbering: "1.1")
#show outline.entry.where(
level: 1
): it => {
v(10pt, weak: true)
it
}
#v(20em)
#align(center)[#heading("Abstract", numbering: none, outlined: false)]
#block([Die Bewegung der Sterne und Planeten fasziniert die Menschheit schon seit Urzeiten. In diesem Paper wird eine Methode zur Simulation der Gravitation im Sonnensystem vorgestellt, welche physikalisch akkurate Daten verwendet, um die Bewegung der Planeten zu berechnen. Die Simulation wird in C++ implementiert und visualisiert. ])
Schlagwörter: _Simulation_, _Gravitation_, _Sonnensystem_, _C++_, _Visualisierung_
#pagebreak()
#outline(indent: 5%, fill: line(length: 100%, stroke: 0.5pt + rgb("#aaa")))
#pagebreak()
#set page(numbering: "1", number-align: center, columns: 2)
= Einleitung
Die Planeten in unserem Sonnensystem folgen wie alle anderen Objekt im Universum den physikalischen Grundgesetzen. Für die Bewegungen der Planeten ist primär die Gravitationskraft verantwortlich. Durch das Verstehen dieser Kraft ist es uns möglich, die Bewegungen der Planeten zu simulieren.
#block()
Dieses Paper verwendet diese Grundgesetze, um eine Simulation zu entwickeln, welche die Bewegungen der Planeten im Sonnensystem berechnet.
= Historischer Kontext
Im Laufe der Zeit haben viele Physiker und Astronomen sich mit der Bewegung der Planeten beschäftigt. Über die Jahrhunderte wurden viele Modelle entwickelt, welche nah am heutigen Stand der Wissenschaft sind. Im folgenden werden einige dieser Modelle vorgestellt.
#block([
1. Im 16ten Jahrhundert entwickelte <NAME> mit "_Über die Umlaufbahnen der Himmelssphären_" @kopernicus das erste Modell, welches den heutigen Erkenntnissen nahe kommt. Er beschrieb die Bewegung der Planeten dadurch, dass alle Planeten aufeinander Gravitation ausüben.
])
#block([
2. Zu Beginn des 17ten Jahrhunderts entwickelte <NAME> mit _Astronomia nova_ @kepler ein Modell, welches die Bewegung der Planeten genauer beschrieb. Seine Axiome besagten, dass die Planeten sich auf Ellipsen bewegen, und Körper sich gegenseitig anziehen.
])
#block([
3. 1644 entwickelte <NAME> mit _Philosophiæ Naturalis Principia Mathematica_ @newton das Modell, welches bis heute zur Beschreibung der Gravitation verwendet wird. Seine Gravitationsgesetze beschreiben, wie sich Körper aufeinander anziehen.
])
= Mathematische Grundlagen
Wie durch Newton beschrieben, wirkt auf jeden Körper eine Gravitationskraft, welche durch die Masse der Körper und den Abstand zwischen den Körpern bestimmt wird. Die Gravitationskraft zwischen zwei Körpern kann durch die Formel
$ F_G = G * (m_1 * m_2)/r^2 $
beschrieben werden. Hierbei ist $F_G$ die resultierende Gravitationskraft, $G$ die Gravitationskonstante ($6.67*10^(-11)m^3/("kg"*s^2)$), $m_1$ und $m_2$ die Massen der Körper und $r$ der Abstand zwischen den Körpern. Die Kraft wirkt hierbei entlang der Verbindungslinie der Körper.
#linebreak()
Für ein 2-Körper-System kann die Bewegung der Körper durch diese Formel bestimmt werden. Die Gravitationskraft, welche die Körper aufeinander ausüben, kann mit der Masse dieser verwendet werden, um die Beschleunigung der Körper mit $F = m * a$ zu bestimmen.
Für 2-Körper-Systeme ist es möglich, numerische Lösungen für die Bewegung der Körper zu finden.
#linebreak()
In mehr-Körper-Systemen wird die Bewegung der Körper durch die Summe der einzelnen wirkenden Gravitationskräfte bestimmt. Für Systeme mit 3 oder mehr Körpern ist es nicht möglich, analytische Lösungen zu finden. Wenn wir hierzu Lösungen finden wollen, müssen wir numerische Methoden verwenden.
Im folgenden wird eine Methode vorgestellt, welche Eulers Methode verwendet, um die Bewegung der Planeten im Sonnensystem zu simulieren.
#linebreak()
Eulers Methode ist eine numerische Methode, welche ein Differentialgleichungssystem durch diskrete Schritte approximiert. Die Methode ist einfach zu implementieren, kann jedoch aufgrund ihrer Funktionsweise ungenau sein.
Als erstes bestimmen wir unseren diskreten Zeitschritt $Delta t$. Danach bestimmen wir die Startwerte für die Position und Geschwindigkeit der Körper im Raum.
#linebreak()
Nun können wir für alle $n$ Körper die Gravitationskräfte berechnen, welche auf die Körper wirken. In diesem Fall ist die Kraft $arrow(F_G)$ ein Vektor, welcher die Richtung und Stärke der Kraft angibt. Mit dieser Kraft können wir die Beschleunigung der Körper bestimmen. Mit $ arrow(a) = arrow(F_G) / m$ und $ arrow(v) = arrow(v) + arrow(a) * Delta t$ können wir nun die angepassten Geschwindigkeiten der Körper bestimmen. Die Geschwindigkeit ist in diesem Fall ein 3-Dimensionaler Vektor, welcher die Geschwindigkeit in $x$, $y$ und $z$ Richtung angibt. Für einen Körper kann nun die neue Position $arrow(r)$ im Raum mit $ arrow(r) = arrow(r) + arrow(v) * Delta t$ bestimmt werden.
#linebreak()
Wenn wir dieses Verfahren nun für alle Körper im System durchführen, können wir die Bewegung der Körper simulieren. Dieses Verfahren von Hand durchzuführen ist sehr aufwendig, weshalb sich die Implementation als Computerprogramm anbietet.
= Vorbereitung
== Datensätze <dataset>
Für die Simulation des Sonnensystems benötigen wir Daten über die Planeten und ihre diversen Satelliten. Die wichtigen Daten für die Simulation sind die Masse der Körper, die Position der Körper im Raum und die Geschwindigkeit der Körper. Diese Daten können aus diversen Quellen bezogen werden. Für die Planeten wurden die Daten aus dem Projekt _Nasa Data Scraper_ von _Devstronomy_ @planets auf Github verwendet. Das gleiche Projekt beinhaltet auch einen Datensatz für die Satelliten der Planeten. Dieser ist allerdings für unsere Simulation nicht geeignet, da keine Informationen zu Position und Geschwindigkeit der Satelliten enthalten sind.
#linebreak()
Die Daten der Satelliten wurden vom _Solar System Dynamics_ Projekt des _Jet Propulsion Laboratory_ der _NASA_ @ssd verwendet. Vom _SSD_ Projekt können wir sowohl die physikalischen Daten der Satelliten @satellite_phys, als auch die orbitale Parameter der Satelliten @satellite_orb beziehen. Diese Daten beinhalten die _Semi Major Axis_ und weitere Parameter, welche für die Simulation benötigt werden.
== Wahl der Programmiersprache
Da für diese Simulation eine große Anzahl an Berechnungen durchgeführt werden muss, stellte die Wahl der Programmiersprache eine wichtige Entscheidung dar. Für diese Simulation wurde deshalb C++ gewählt. C++ ist eine schnelle kompilierte Sprache.
== Wahl von Hilfsbibliotheken
Zur Visualisierung unserer Simulation benötigen wir eine Bibliothek, welche die Darstellung von 3D-Objekten ermöglicht. Hierzu wurde die Bibliothek _Raylib_ @Raylib verwendet. Raylib ist eine C-Bibliothek, welche die Erstellung von 2D und 3D Anwendungen ermöglicht. Neben der Darstellung von 3D-Objekten war es auch noch wichtig, dass wir einfache Interface-Elemente anzeigen können. Hierzu wird die Bibliothek _Dear ImGui_ @Imgui verwendet. ImGui ist eine C++ Bibliothek, welche in der Spieleentwicklung verwendet wird, um einfache Interface-Elemente anzuzeigen. Um diese beiden Bibliotheken zusammen zu verwenden, wurde das Projekt _rlImGui_ @Rlimgui verwendet.
Die Bibliotheken _ImGui_ und _rlImGui_ wurden als Submodule in das Projekt eingebunden. _Raylib_ wird während der Kompilierung des Projektes heruntergeladen und verwendet. Hierzu wurde das Programm _Cmake_ @cmake verwendet. Cmake ist ein Build-System, welches es ermöglicht, C und C++ Projekte plattformunabhängig zu kompilieren.
= Implementierung
== Grundlegendes
Die Implementierung der Simulation folgt dem zuvor beschriebenen Ablauf. In der _Main_-Funktion der Simulation werden zuerst die nötigen Bibliotheken initialisiert. Für dieses Projekt war es nötig, einen eigenen _Vektor_-Datentypen zu verwenden. Die Gründe hierzu, werden in @32bit erläutert. Dieser _SciVec3_ verwendet 64-Bit Gleitkommazahlen, um möglichst präzise Berechnungen zu ermöglichen. Der Datentyp und die dazugehörigen Funktionen zur Addition, Subtraktion, Multiplikation und Skalierung können in _SciVec3.h_ gefunden werden. Die Körper des Sonnensystems werden mithilfe eines Datentypen _Body_ abgebildet. In _Body.h_ wird das _struct_ _Body_ wie folgt definiert:
#figure([```cpp
struct Body
{
std::string name;
double radius;
double mass;
Color color{};
SciVec3 position;
SciVec3 velocity;
bool isPlanet;
int satelliteCount = 0;
std::string satelliteNames[64] = {""};
...
}
```], caption: "Definition des _Body_-Datentyps")
Die Felder _radius_, _mass_, _postion_, und _velocity_ sind für die Simulation am wichtigsten. Für jedes Objekt wird außerdem ein _Name_, eine _Farbe_, und eine Liste an Satelliten gespeichert. Die Simulation verwaltet eine dynamische Liste (_std::vector_) an _Body_-Objekten. Diese Liste stellt den aktuellen Zustand der Simulation da. Um diese Liste nun mit Daten zu füllen, müssen wir unsere Datensätze einladen.
== Laden der Datensätze
Die Datei _Loader.h_ beinhaltet die Funktionen, welche die Datensätze aus @dataset lädt. Die Funktion _loadPlanets_ lädt die _planets.csv_-Datei aus dem _Assets_-Ordner. Zuerst erstellt diese Funktion allerdings die Sonne, welche nicht im Datensatz enthalten ist. Hierfür wurden die wichtigsten Werte in _Consts.h_ definiert. Danach iteriert die Funktion über die Zeilen der CSV-Datei und erstellt für jede Zeile ein _Body_-Objekt. Hierbei ist es wichtig, die einzelnen Werte in die korrekten Einheiten umzuwandeln. Für diese Simulation wurde die Entscheidung getroffen, alle Werte in SI-Einheiten zu speichern. Insbesondere für die Datenwerte _Mass_ war es nötig, 64-Bit Gleitkommazahlen zu verwenden. Um die Visualisierung besser zu gestalten, wurden allen Planeten individuelle Farbe zugeordnet.
Neben den bereits genannten Daten, war die Bestimmung der initialen Position und Geschwindigkeit der Körper eine wichtige Entscheidung. Der Datensatz der Planeten beinhaltet sowohl Werte für den _Aphelion_, den _Perihelion_, die _Inclination_ und die _Exzentrizität_ der Planeten. Des Weiteren wurde ein Wert für die durchschnittliche _orbital_velocity_ angegeben.
// TODO Richtig implmentieren und dann beschreiben
#block()
Die Funktion _loadSatallites_ funktioniert ähnlich wie _loadPlanets_. Hierbei werden die Dateien _satellites_data.csv_ und _satellites_orbit.csv_ kombiniert, um die Satelliten der Planeten zu erstellen. Für jeden Satellit wird zuerst der _Parent_-Körper gesucht. Danach werden die weiteren planetaren Informationen bestimmt. Dieser Datensatz weist die Besonderheit auf, dass nicht die Masse der Objekte angegeben ist, sondern der _Standard Gravitational Parameter_ $mu$. Dieser Wert ist definiert als $mu = G * m$, wobei $G$ die Gravitationskonstante ist. Um die Masse der Satelliten zu bestimmen, wird der Wert $mu$ durch $G$ geteilt.
Die Bestimmung der initialen Position und Geschwindigkeit der Satelliten ist etwas komplizierter. Hierzu müssen wir nicht nur die orbitalen Parameter des Satelliten, sondern auch die des Parent-Körpers verwenden.
// TODO Richtig implmentieren und dann beschreiben
== Aufteilung von Simulation und Visualisierung
Die Simulation und Visualisierung sind zwei verschiedene Aufgaben mit unterschiedlichen Zielen. Ziel der Visualisierung ist es, in geregelten Abstände den Zustand der Simulation darstellen. Dieser Vorgang ist größtenteils abhängig von der Grafikkarte. Die Simulation hingegen ist abhängig von der CPU. Idealerweise sind die beiden Prozesse soweit wie möglich voneinander getrennt. Dies wurde in diesem Projekt so realisiert, dass die Simulation in einem getrennten _Thread_ läuft. Die Visualisierung hingegen läuft im _Main_-Thread der Anwendung. Beide Threads greifen auf die selbe Liste an Daten zu, weshalb es nötig war, die Zugriffe auf diese Liste zu synchronisieren. Um eine möglichst geringe Latenz für den Nutzer zu ermöglichen, hat die Visualisierung die primäre Kontrolle über die Liste. Sie kann angeben wann die Simulation auf die Liste zugreifen kann, indem die Simulation temporär pausiert wird.
== Implementieren der Simulation
Die Simulation ist der Kern der Anwendung. Um möglichst große Zeiträume simulieren zu können, ist es also nötig, diesen Vorgang möglichst effizient zu implementieren. Die Simulation wird in der Funktion _simulate_ in _main.cpp_ implementiert. Diese Funktion wird in einem eigenen _Thread_ ausgeführt. Dieser Thread arbeitet komplett unabhängig von der Visualisierung. Solang die Simulation nicht pausiert ist, entweder durch den Nutzer, oder durch die Visualisierung, wird die Simulation in einer Schleife ausgeführt. Im folgenden wird eine vereinfachte Version der Funktion _simulate_ gezeigt:
#figure([```cpp
void simulate()
{
if(simulationRunning)
{
for(body1 in bodies)
{
for(body2 in bodies)
{
if(body1 == body2)
continue;
Force = calculate_gravity(body1, body2);
body1.acceleration += Force / body1.mass;
body2.acceleration -= Force / body2.mass;
body1.velocity += body1.acceleration * delta_t;
body2.velocity += body2.acceleration * delta_t;
body1.position += body1.velocity * delta_t;
body2.position += body2.velocity * delta_t;
}
}
}
}
```], caption: "Vereinfachte Version der Funktion simulate")
Die Funktion folgt dem zuvor definierten Aufbau. Für jeden Körper wird die Gravitationskraft berechnet, welche auf den Körper wirkt. Mit dieser Kraft wird die Beschleunigung des Körpers bestimmt. Mit der Beschleunigung wird die Geschwindigkeit, und damit die Position des Körpers bestimmt. Dieser Vorgang wird für alle Körper in der Liste _bodies_ durchgeführt.
Wichtig ist hierbei, dass die Berechnung von der globalen variable _delta_t_ abhängig ist. Diese Variable bestimmt den Zeitschritt der Simulation. Je kleiner dieser Wert ist, desto genauer ist die Simulation, jedoch auch langsamer. Je nach verfügbarer Rechenleistung kann dieser Wert auf bis zu 1s pro Iteration gesetzt werden. Mehr hierzu in @results.
== Implementieren der Visualisierung
Mithilfe der Visualisierung können wir den momentanen Zustand der Simulation darstellen. Die primäre _draw_-loop der Simulation findet innerhalb der _main_-Funktion der Anwendung statt. Eine vereinfachte Version dieser Funktion sieht wie folgt aus:
#figure([```cpp
void draw()
{
BeginDrawing3D();
ClearBackground(BLACK);
UpdateClipPlane();
simulationRunning = false;
for(body in bodies)
{
DrawBody(body);
}
simulationRunning = true;
UpdateCamera();
DrawInterface();
EndDrawing3D();
}
```], caption: "Vereinfachte Version der Funktion draw")
Diese Funktion wird solange in einer Schleife ausgeführt, bis die Anwendung geschlossen wird. Nach dem Starten des 3-D-Renderers wird der Hintergrund gelöscht. Als nächstes wird die _ClipPlane_@clipplane angepasst. Dies ist der Abstand von Geometrie zur Kamera, ab welchem Objekte nichtmehr dargestellt werden. Aufgrund der großen Werte, welche durch die Verwendung von physikalisch akkuraten Werten auftreten, ist es nötig, diesen Wert anhand der aktuellen Kameraeinstellungen anzupassen.
Nachdem diese Vorbereitungen getroffen wurden, werden die einzelnen planetarischen Objekte gezeichnet. Die Funktion _DrawBody_ nimmt die aktuelle Position des Körpers und stellt diesen mithilfe einer gefärbten Kugel in 3D dar.
#figure([
#image("./assets/sun.jpg", width: 80%)
], caption: "Sonne in nSim")
Diese Methode kann nun verwendet werden um die Planeten und ihre Satelliten zu visualisieren. Ein Phänomen, welches aufgrund dieser Art der Visualisierung auftritt, ist, dass die relative Bewegung und Position von Körpern zueinander schwer zu erkennen ist.
#figure([
#image("./assets/no_trails.jpg", width: 80%)
], caption: "Erde und Mond") <no_trails>
Wie in @no_trails zu erkennen ist, gibt uns diese Visualisierung keine Anhaltspunkte für die Orientierung und Bewegung der Planeten. Ein weiteres Problem war es, dass aufgrund der Skalierung der Visualisierung einige Satelliten sehr klein, und damit schwer zu erkennen wurden. Um diese Problematiken zu verringern, wurden drei weitere Visualisierungen hinzugefügt.
#pagebreak()
1. Astronomisches Gitter
#figure([
#image("./assets/grid.jpg", width: 80%)
], caption: "Sonne mit astronomischem Gitter") <grid>
Um ein besseres Gefühl für die relative Position und Rotation von Punkten im Raum zu geben, wurde ein optionales Gitter zur Visualisierung hinzugefügt. Dieses Gitter weist eine Auflösung von $1/100 "AU"$, oder einem Einhundertstel der astronomischen Einheit da. Über die Einstellung kann auch die Größte des Gitters kontrolliert werden. Das Gitter wird zentriert über dem aktuell fokussierten Körper angezeigt.
2. Transparente Selektoren für Satelliten
#figure([
#image("./assets/selector.jpg")
], caption: "Mond mit transparenten Selektor") <selector>
@selector zeigt unseren Mond in Grau mit einem größeren halb-transparenten Selektor darüber. Der Selektor ermöglicht es, auch die kleinren planetarischen Objekte zu selektieren. Die Größe des Selektors ist dabei immer noch abhängig von dem Radius des Objektes, damit die Skalierung trotzdem akkurat bleibt.
#linebreak()
3. Historische Pfade
#figure([
#image("./assets/trails.jpg", width: 80%)
], caption: "Erde und Mond mit historischen Pfaden")
Um die Bewegung der Objekte besser zu visualisieren, werden die vergangenen Positionen gespeichert und in Form einer 3D-Kurve durch den Raum angezeigt. So ist es beispielsweise möglich zu sehen, wie der Mond sich relativ zur Erde bewegt.
== Implementierung des Interfaces
Um mit der Simulation zu interagieren, wurden einfache Interface-Elemente benötigt. Die Interface-Elemente wurden in Form von verschiedenen _ImGui-Fenstern_ realisiert. Die folgenden Fenster wurden für die Simulation implementiert:
+ Graphics Debugger: #linebreak() Fenster zum Einstellen der grafischen Visualisierung. Hier können Dinge wie das Gitter, die Selektoren und Wireframe-Rendering aktiviert werden
+ Camera Settings: #linebreak() Fenster, welches die aktuellen Parameter der Camera anzeigt.
+ Simulation Settings: #linebreak() Fenster, welches die Konfiguration des Zeitschrittes erlaubt. Über dieses Fenster kann auch die Simulation pausiert werden. Des Weiteren wird angezeigt, wie viele Sekunden, Minuten, Stunden und Tage bisher in der Simulation vergangen sind.
+ Focus Select: #linebreak() Fenster, welches verwendet werden kann, um den aktuell fokussierten Körper zu wechseln.
== Implementierung der Kamera
Die Kamera selbst ist mithilfe von sphärischen Koordinaten relativ zum aktuell fokussierten Körper ausgerichtet. Es ist möglich, mithilfe der Maus den horizontalen und vertikalen Winkel der Kamera relativ zum Körper anzupassen. Mithilfe des Mausrads kann der Abstand $r$ der Kamera zu diesem kontrolliert werden. Die Kamera dieser Simulation richtet sich am aktuell fokussierten Planeten aus. Dementsprechend ist es nötig, die Kamera in jedem Durchgang der Visualisierungsfunktion zu aktualisieren. Dabei übernimmt die Kamera zuerst die Position des aktuell fokussierten Objektes. Danach wird anhand der sphärischen Koordinaten $theta$ und $phi$ wie folgt die relative Position ermittelt:
$Delta_x = r * sin(theta) * cos(phi)$
$Delta_y = r * cos(theta)$
$Delta_z = r * sin(theta) * cos(phi)$
Die finalen Koordinaten der Kamera können dann mit
$x = x_"planet" + Delta_x$
$y = y_"planet" + Delta_y$
$z = z_"planet" + Delta_z$
bestimmt werden. Hierbei ist wichtig zu beachten, dass _OpenGL_, und damit auch _Raylib_, ein rechtshändiges Koordinatensystem verwenden, in welchem $y$ und nicht wie typisch $z$ die vertikale Achse ist.
= Besonderheiten und Lösungen <problems>
Die Simulation weist eine vielzahl von Besonderheiten auf, welche die Implementation beeinflussen. Der wichtigste Faktor hierbei ist die Größte der verschiedenen verwendeten Werte. Da die Werte in SI-Einheiten vorliegen, sind die Werte für die Positionen und Geschwindigkeiten sehr groß. Die Masse der Sonne beispielsweise beträgt $1.989 * 10^30"kg"$. Die Distanz zwischen der Erde und der Sonne liegt bei $1.495 * 10^11m$. Aufgrund dieser großen Werte ist es nötig, die Visualisierung zu skalieren. Hierzu wurde der Faktor 1:1000000 gewählt. Dieser Faktor wird für alle Größen innerhalb der Visualisierung verwendet. Die Berechnung der Simulation findet allerdings trotzdem mit den ungekürzten Werten statt.
== 32-Bit Gleitkommazahlen <32bit>
Die Größenordnung der Werte führt dazu, dass wir Gleitkommazahlen verwenden müssen, um diese akkurat darzustellen. Eine reguläre 64-Bit Zahl hat einen Wertebereich von $-2^63$ bis $2^63-1$ oder von $plus.minus 9.22 * 10^18$. Damit wäre es nicht möglich, die meisten Berechnungen durchzuführen. Gleitkommazahlen nach IEEE-754@ieee können größere Zahlen darstellen. 32Bit Gleitkommazahlen haben einen Wertebereich von $plus.minus 3.40*10^38$. Dieser Wertebereich ist groß genug, um unsere Berechnungen durchzuführen. Für Gleitkommazahlen ist allerdings nicht nur der Wertebereich, sondern auch die Genauigkeit wichtig. 32-Bit Gleitkommazahlen haben eine Genauigkeit von 7 Stellen. Für unsere Berechnungen ist dies nicht ausreichend. Deshalb wurde ein eigener Datentyp _SciVec3_ implementiert. Dieser Datentyp verwendet 64-Bit Gleitkommazahlen. Diese bieten eine Genauigkeit von 15 Stellen. Der Datentyp _SciVec3_ wird für alle Berechnungen innerhalb der Simulation verwendet. Nur für die Darstellung wird in den von _Raylib_ verwendeten _Vector3_-Datentypen umgewandelt.
== Floating Origin <floating_origin>
Auch nach den Anpassungen in @32bit treten allerdings noch Probleme bei der Visualisierung auf. Unsere skalierten Werte sind häufig länger als 7 Stellen. Dies führt aufgrund des Aufbaus von IEEE-754 Gleitkommazahlen dazu, dass Genauigkeitsprobleme sichtbar werden. In diesem Fall können wir nicht wie zuvor den Datentypen anpassen, da moderne Grafikschnittstellen wie _OpenGL_ nur 32-Bit Gleitkommazahlen unterstützen.
Um dieses Problem zu lösen, wurde das Konzept des _Floating Origin_ eingeführt. Hierbei werden alle Objekte relativ zum aktuell fokussierten Körper dargestellt. Dies führt dazu, dass der fokussierten Bereich der Visualisierung immer im genausten Bereich der Gleitkommazahlen dargestellt werden. Die Logik hierfür ist wie folgt:
+ Die Position des aktuell fokussierten Körpers wird als Ursprung der Welt gesetzt.
+ Beim Anzeigen der Körper wird die Position des fokussierten Körpers von der Position des Körpers abgezogen.
+ Die Kamera wird relativ zum fokussierten Körper positioniert.
Da die gesamte Positionierung und Berechnung weiterhin mithilfe des _SciVec3_ in 64-Bit ausgeführt wird, sind die Berechnungen weiterhin akkurat. Erst nachdem diese Berechnungen durchgeführt wurden, werden die Werte in 32-Bit Gleitkommazahlen umgewandelt.
= Ergebnisse <results>
Ziel unserer Simulation war es, dass wir die Bewegung der Planeten simulieren und in 3D visualisieren können. Hierzu wurde das Programm _nSim_, ein n-Body Simulator, entwickelt.
#figure(
image("./assets/nsim.png"),
caption: "nSim Simulation des inneren Sonnensystems"
) <nsim1>
@nsim1 zeigt einen weiten Blick auf das innere Sonnensystem. Hier werden die Umlaufbahnen des Merkurs, der Venus, der Erde und des Mars um die Sonne sichtbar.
#figure(
image("./assets/nsim1.png"),
caption: "nSim Simulation von Jupiter"
) <nsim2>
@nsim2 zeigt die Simulation des Jupiter und seiner vier größten Monde. Hierbei ist zu erkennen, wie die Monde um den Jupiter kreisen.
_nSim_ ermöglicht es, innerhalb kürzester Zeit die Bewegung der Planeten über Tage oder sogar Jahre hinweg zu simulieren. Hierzu werden diverse Open-Source Projekte verwendet. Der Code für dieses Projekt kann auf _Github_ @github eingesehen werden.
#pagebreak()
#set page(numbering: "1", number-align: center, columns: 1)
#bibliography("sources.yml", title: "Quellen", style: "ieee") |
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/121.%20really.html.typ | typst | really.html
What Startups Are Really Like
Want to start a startup? Get funded by
Y Combinator.
October 2009(This essay is derived from a talk at the 2009 Startup School.)I wasn't sure what to talk about at Startup School, so I decided
to ask the founders of the startups we'd funded. What hadn't I
written about yet?I'm in the unusual position of being able to test the essays I write
about startups. I hope the ones on other topics are right, but I
have no way to test them. The ones on startups get tested by about
70 people every 6 months.So I sent all the founders an email asking what surprised them about
starting a startup. This amounts to asking what I got wrong, because
if I'd explained things well enough, nothing should have surprised
them.I'm proud to report I got one response saying:
What surprised me the most is that everything was actually
fairly predictable!
The bad news is that I got over 100 other responses listing the
surprises they encountered.There were very clear patterns in the responses; it was remarkable
how often several people had been surprised by exactly the same
thing. These were the biggest:
1. Be Careful with CofoundersThis was the surprise mentioned by the most founders. There were
two types of responses: that you have to be careful who you pick
as a cofounder, and that you have to work hard to maintain your
relationship.What people wished they'd paid more attention to when choosing
cofounders was character and commitment, not ability. This was
particularly true with startups that failed. The lesson: don't
pick cofounders who will flake.Here's a typical reponse:
You haven't seen someone's true colors unless you've worked
with them on a startup.
The reason character is so important is that it's tested more
severely than in most other situations. One founder said explicitly
that the relationship between founders was more important than
ability:
I would rather cofound a startup with a friend than a stranger
with higher output. Startups are so hard and emotional that
the bonds and emotional and social support that come with
friendship outweigh the extra output lost.
We learned this lesson a long time ago. If you look at the YC
application, there are more questions about the commitment and
relationship of the founders than their ability.Founders of successful startups talked less about choosing cofounders
and more about how hard they worked to maintain their relationship.
One thing that surprised me is how the relationship of startup
founders goes from a friendship to a marriage. My relationship
with my cofounder went from just being friends to seeing each
other all the time, fretting over the finances and cleaning up
shit. And the startup was our baby. I summed it up once like
this: "It's like we're married, but we're not fucking."
Several people used that word "married." It's a far more intense
relationship than you usually see between coworkers—partly because
the stresses are so much greater, and partly because at first the
founders are the whole company. So this relationship has to be
built of top quality materials and carefully maintained. It's the
basis of everything.
2. Startups Take Over Your LifeJust as the relationship between cofounders is more intense than
it usually is between coworkers, so is the relationship between the
founders and the company. Running a startup is not like having a
job or being a student, because it never stops. This is so foreign
to most people's experience that they don't get it till it happens.
[1]
I didn't realize I would spend almost every waking moment either
working or thinking about our startup. You enter a whole
different way of life when it's your company vs. working for
someone else's company.
It's exacerbated by the fast pace of startups, which makes it seem
like time slows down:
I think the thing that's been most surprising to me is how one's
perspective on time shifts. Working on our startup, I remember
time seeming to stretch out, so that a month was a huge interval.
In the best case, total immersion can be exciting:
It's surprising how much you become consumed by your startup,
in that you think about it day and night, but never once does
it feel like "work."
Though I have to say, that quote is from someone we funded this
summer. In a couple years he may not sound so chipper.
3. It's an Emotional Roller-coasterThis was another one lots of people were surprised about. The ups
and downs were more extreme than they were prepared for.In a startup, things seem great one moment and hopeless the next.
And by next, I mean a couple hours later.
The emotional ups and downs were the biggest surprise for me.
One day, we'd think of ourselves as the next Google and dream
of buying islands; the next, we'd be pondering how to let our
loved ones know of our utter failure; and on and on.
The hard part, obviously, is the lows. For a lot of founders that
was the big surprise:
How hard it is to keep everyone motivated during rough days or
weeks, i.e. how low the lows can be.
After a while, if you don't have significant success to cheer you
up, it wears you out:
Your most basic advice to founders is "just don't die," but the
energy to keep a company going in lieu of unburdening success
isn't free; it is siphoned from the founders themselves.
There's a limit to how much you can take. If you get to the point
where you can't keep working anymore, it's not the end of the world.
Plenty of famous founders have had some failures along the way.
4. It Can Be FunThe good news is, the highs are also very high. Several founders
said what surprised them most about doing a startup was how fun it
was:
I think you've left out just how fun it is to do a startup. I
am more fulfilled in my work than pretty much any of my friends
who did not start companies.
What they like most is the freedom:
I'm surprised by how much better it feels to be working on
something that is challenging and creative, something I believe
in, as opposed to the hired-gun stuff I was doing before. I
knew it would feel better; what's surprising is how much better.
Frankly, though, if I've misled people here, I'm not eager to fix
that. I'd rather have everyone think starting a startup is grim
and hard than have founders go into it expecting it to be fun, and
a few months later saying "This is supposed to be fun? Are you
kidding?"The truth is, it wouldn't be fun for most people. A lot of what
we try to do in the application process is to weed out the people
who wouldn't like it, both for our sake and theirs.The best way to put it might be that starting a startup is fun the
way a survivalist training course would be fun, if you're into that
sort of thing. Which is to say, not at all, if you're not.
5. Persistence Is the KeyA lot of founders were surprised how important persistence was in
startups. It was both a negative and a positive surprise: they were
surprised both by the degree of persistence required
Everyone said how determined and resilient you must be, but
going through it made me realize that the determination required
was still understated.
and also by the degree to which persistence alone was able to
dissolve obstacles:
If you are persistent, even problems that seem out of your
control (i.e. immigration) seem to work themselves out.
Several founders mentioned specifically how much more important
persistence was than intelligence.
I've been surprised again and again by just how much more
important persistence is than raw intelligence.
This applies not just to intelligence but to ability in general,
and that's why so many people said character was more important in
choosing cofounders.
6. Think Long-TermYou need persistence because everything takes longer than you expect.
A lot of people were surprised by that.
I'm continually surprised by how long everything can take.
Assuming your product doesn't experience the explosive growth
that very few products do, everything from development to
dealmaking (especially dealmaking) seems to take 2-3x longer
than I always imagine.
One reason founders are surprised is that because they work fast,
they expect everyone else to. There's a shocking amount of shear
stress at every point where a startup touches a more bureaucratic
organization, like a big company or a VC fund. That's why fundraising
and the enterprise market kill and maim so many startups.
[2]But I think the reason most founders are surprised by how long it
takes is that they're overconfident. They think they're going to
be an instant success, like YouTube or Facebook. You tell them
only 1 out of 100 successful startups has a trajectory like that,
and they all think "we're going to be that 1."Maybe they'll listen to one of the more successful founders:
The top thing I didn't understand before going into it is that
persistence is the name of the game. For the vast majority of
startups that become successful, it's going to be a really
long journey, at least 3 years and probably 5+.
There is a positive side to thinking longer-term. It's not just
that you have to resign yourself to everything taking longer than
it should. If you work patiently it's less stressful, and you can
do better work:
Because we're relaxed, it's so much easier to have fun doing
what we do. Gone is the awkward nervous energy fueled by the
desperate need to not fail guiding our actions. We can concentrate
on doing what's best for our company, product, employees and
customers.
That's why things get so much better when you hit ramen profitability.
You can shift into a different mode of working.7. Lots of Little ThingsWe often emphasize how rarely startups win simply because they hit
on some magic idea. I think founders have now gotten that into
their heads. But a lot were surprised to find this also applies
within startups. You have to do lots of different things:
It's much more of a grind than glamorous. A timeslice selected
at random would more likely find me tracking down a weird DLL
loading bug on Swedish Windows, or tracking down a bug in the
financial model Excel spreadsheet the night before a board
meeting, rather than having brilliant flashes of strategic
insight.
Most hacker-founders would like to spend all their time programming.
You won't get to, unless you fail. Which can be transformed into:
If you spend all your time programming, you will fail.The principle extends even into programming. There is rarely a
single brilliant hack that ensures success:
I learnt never to bet on any one feature or deal or anything
to bring you success. It is never a single thing. Everything
is just incremental and you just have to keep doing lots of
those things until you strike something.
Even in the rare cases where a clever hack makes your fortune, you
probably won't know till later:
There is no such thing as a killer feature. Or at least you
won't know what it is.
So the best strategy is to try lots of different things. The reason
not to put all your eggs in one basket is not the usual one,
which applies even when you know which basket is best. In a startup
you don't even know that.
8. Start with Something MinimalLots of founders mentioned how important it was to launch with the
simplest possible thing. By this point everyone knows you should
release fast and iterate. It's practically a mantra at YC. But
even so a lot of people seem to have been burned by not doing it:
Build the absolute smallest thing that can be considered a
complete application and ship it.
Why do people take too long on the first version? Pride, mostly.
They hate to release something that could be better. They worry
what people will say about them. But you have to overcome this:
Doing something "simple" at first glance does not mean you
aren't doing something meaningful, defensible, or valuable.
Don't worry what people will say. If your first version is so
impressive that trolls don't make fun of it, you waited too long
to launch.
[3]One founder said this should be your approach to all programming,
not just startups, and I tend to agree.
Now, when coding, I try to think "How can I write this such
that if people saw my code, they'd be amazed at how little there
is and how little it does?"
Over-engineering is poison. It's not like doing extra work for
extra credit. It's more like telling a lie that you then have to
remember so you don't contradict it.
9. Engage UsersProduct development is a conversation with the user that doesn't
really start till you launch. Before you launch, you're like a
police artist before he's shown the first version of his sketch to
the witness.It's so important to launch fast that it may be better to think of
your initial version not as a product, but as a trick for getting
users to start talking to you.
I learned to think about the initial stages of a startup as a
giant experiment. All products should be considered experiments,
and those that have a market show promising results extremely
quickly.
Once you start talking to users, I guarantee you'll be surprised
by what they tell you.
When you let customers tell you what they're after, they will
often reveal amazing details about what they find valuable as
well what they're willing to pay for.
The surprise is generally positive as well as negative. They won't
like what you've built, but there will be other things they would
like that would be trivially easy to implement. It's not till you
start the conversation by launching the wrong thing that they can
express (or perhaps even realize) what they're looking for.
10. Change Your IdeaTo benefit from engaging with users you have to be willing to change
your idea. We've always encouraged founders to see a startup idea
as a hypothesis rather than a blueprint. And yet they're still
surprised how well it works to change the idea.
Normally if you complain about something being hard, the general
advice is to work harder. With a startup, I think you should
find a problem that's easy for you to solve. Optimizing in
solution-space is familiar and straightforward, but you can
make enormous gains playing around in problem-space.
Whereas mere determination, without flexibility, is a greedy algorithm
that may get you nothing more than a mediocre local maximum:
When someone is determined, there's still a danger that they'll
follow a long, hard path that ultimately leads nowhere.
You want to push forward, but at the same time twist and turn to
find the most promising path. One founder put it very succinctly:
Fast iteration is the key to success.
One reason this advice is so hard to follow is that people don't
realize how hard it is to judge startup ideas, particularly their
own. Experienced founders learn to keep an open mind:
Now I don't laugh at ideas anymore, because I realized how
terrible I was at knowing if they were good or not.
You can never tell what will work. You just have to do whatever
seems best at each point. We do this with YC itself. We still
don't know if it will work, but it seems like a decent hypothesis.
11. Don't Worry about CompetitorsWhen you think you've got a great idea, it's sort of like having a
guilty conscience about something. All someone has to do is look
at you funny, and you think "Oh my God, they know."These alarms are almost always false:
Companies that seemed like competitors and threats at first
glance usually never were when you really looked at it. Even
if they were operating in the same area, they had a different
goal.
One reason people overreact to competitors is that they overvalue
ideas. If ideas really were the key, a competitor with the same
idea would be a real threat. But it's usually execution that
matters:
All the scares induced by seeing a new competitor pop up are
forgotten weeks later. It always comes down to your own product
and approach to the market.
This is generally true even if competitors get lots of attention.
Competitors riding on lots of good blogger perception aren't
really the winners and can disappear from the map quickly. You
need consumers after all.
Hype doesn't make satisfied users, at least not for something as
complicated as technology.12. It's Hard to Get UsersA lot of founders complained about how hard it was to get users,
though.
I had no idea how much time and effort needed to go into attaining
users.
This is a complicated topic. When you can't get users, it's hard
to say whether the problem is lack of exposure, or whether the
product's simply bad. Even good products can be blocked by switching
or integration costs:
Getting people to use a new service is incredibly difficult.
This is especially true for a service that other companies can
use, because it requires their developers to do work. If you're
small, they don't think it is urgent.
[4]
The sharpest criticism of YC came from a founder who said we didn't
focus enough on customer acquisition:
YC preaches "make something people want" as an engineering task,
a never ending stream of feature after feature until enough
people are happy and the application takes off. There's very
little focus on the cost of customer acquisition.
This may be true; this may be something we need to fix, especially
for applications like games. If you make something where the
challenges are mostly technical, you can rely on word of mouth,
like Google did. One founder was surprised by how well that worked
for him:
There is an irrational fear that no one will buy your product.
But if you work hard and incrementally make it better, there
is no need to worry.
But with other types of startups you may win less by features and
more by deals and marketing.
13. Expect the Worst with DealsDeals fall through. That's a constant of the startup world. Startups
are powerless, and good startup ideas generally seem wrong. So
everyone is nervous about closing deals with you, and you have no
way to make them.This is particularly true with investors:
In retrospect, it would have been much better if we had operated
under the assumption that we would never get any additional
outside investment. That would have focused us on finding
revenue streams early.
My advice is generally pessimistic. Assume you won't get money,
and if someone does offer you any, assume you'll never get any more.
If someone offers you money, take it. You say it a lot, but I
think it needs even more emphasizing. We had the opportunity
to raise a lot more money than we did last year and I wish we
had.
Why do founders ignore me? Mostly because they're optimistic by
nature. The mistake is to be optimistic about things you can't
control. By all means be optimistic about your ability to make
something great. But you're asking for trouble if you're optimistic
about big companies or investors.
14. Investors Are CluelessA lot of founders mentioned how surprised they were by the cluelessness
of investors:
They don't even know about the stuff they've invested in. I
met some investors that had invested in a hardware device and
when I asked them to demo the device they had difficulty switching
it on.
Angels are a bit better than VCs, because they usually have startup
experience themselves:
VC investors don't know half the time what they are talking
about and are years behind in their thinking. A few were great,
but 95% of the investors we dealt with were unprofessional,
didn't seem to be very good at business or have any kind of
creative vision. Angels were generally much better to talk to.
Why are founders surprised that VCs are clueless? I think it's
because they seem so formidable.The reason VCs seem formidable is that it's their profession to.
You get to be a VC by convincing asset managers to trust you with
hundreds of millions of dollars. How do you do that? You have to
seem confident, and you have to seem like you understand technology.
[5]
15. You May Have to Play GamesBecause investors are so bad at judging you, you have to work harder
than you should at selling yourself. One founder said the thing
that surprised him most was
The degree to which feigning certitude impressed investors.
This is the thing that has surprised me most about YC founders'
experiences. This summer we invited some of the alumni to talk to
the new startups about fundraising, and pretty much 100% of their
advice was about investor psychology. I thought I was cynical about
VCs, but the founders were much more cynical.
A lot of what startup founders do is just posturing. It works.
VCs themselves have no idea of the extent to which the startups
they like are the ones that are best at selling themselves to VCs.
[6]
It's exactly the same phenomenon we saw a step earlier. VCs get
money by seeming confident to LPs, and founders get money by seeming
confident to VCs.
16. Luck Is a Big FactorWith two such random linkages in the path between startups and
money, it shouldn't be surprising that luck is a big factor in
deals. And yet a lot of founders are surprised by it.
I didn't realize how much of a role luck plays and how much is
outside of our control.
If you think about famous startups, it's pretty clear how big a
role luck plays. Where would Microsoft be if IBM insisted on an
exclusive license for DOS?Why are founders fooled by this? Business guys probably aren't,
but hackers are used to a world where skill is paramount, and you
get what you deserve.
When we started our startup, I had bought the hype of the startup
founder dream: that this is a game of skill. It is, in some
ways. Having skill is valuable. So is being determined as all
hell. But being lucky is the critical ingredient.
Actually the best model would be to say that the outcome is the
product of skill, determination, and luck. No matter how much
skill and determination you have, if you roll a zero for luck, the
outcome is zero.These quotes about luck are not from founders whose startups failed.
Founders who fail quickly tend to blame themselves. Founders who
succeed quickly don't usually realize how lucky they were. It's
the ones in the middle who see how important luck is.
17. The Value of CommunityA surprising number of founders said what surprised them most about
starting a startup was the value of community. Some meant the
micro-community of YC founders:
The immense value of the peer group of YC companies, and facing
similar obstacles at similar times.
which shouldn't be that surprising, because that's why it's structured
that way. Others were surprised at the value of the startup community
in the larger sense:
How advantageous it is to live in Silicon Valley, where you
can't help but hear all the cutting-edge tech and startup news,
and run into useful people constantly.
The specific thing that surprised them most was the general spirit
of benevolence:
One of the most surprising things I saw was the willingness of
people to help us. Even people who had nothing to gain went out
of their way to help our startup succeed.
and particularly how it extended all the way to the top:
The surprise for me was how accessible important and interesting
people are. It's amazing how easily you can reach out to people
and get immediate feedback.
This is one of the reasons I like being part of this world. Creating
wealth is not a zero-sum game, so you don't have to stab people in
the back to win.
18. You Get No RespectThere was one surprise founders mentioned that I'd forgotten about:
that outside the startup world, startup founders get no respect.
In social settings, I found that I got a lot more respect when
I said, "I worked on Microsoft Office" instead of "I work at a
small startup you've never heard of called x."
Partly this is because the rest of the world just doesn't get
startups, and partly it's yet another consequence of the fact that
most good startup ideas seem bad:
If you pitch your idea to a random person, 95% of the time
you'll find the person instinctively thinks the idea will be a
flop and you're wasting your time (although they probably won't
say this directly).
Unfortunately this extends even to dating:
It surprised me that being a startup founder does not get you
more admiration from women.
I did know about that, but I'd forgotten.
19. Things Change as You GrowThe last big surprise founders mentioned is how much things changed
as they grew. The biggest change was that you got to program even
less:
Your job description as technical founder/CEO is completely
rewritten every 6-12 months. Less coding, more
managing/planning/company building, hiring, cleaning up messes,
and generally getting things in place for what needs to happen
a few months from now.
In particular, you now have to deal with employees, who often have
different motivations:
I knew the founder equation and had been focused on it since I
knew I wanted to start a startup as a 19 year old. The employee
equation is quite different so it took me a while to get it
down.
Fortunately, it can become a lot less stressful once you reach
cruising altitude:
I'd say 75% of the stress is gone now from when we first started.
Running a business is so much more enjoyable now. We're more
confident. We're more patient. We fight less. We sleep more.
I wish I could say it was this way for every startup that succeeded,
but 75% is probably on the high side.
The Super-PatternThere were a few other patterns, but these were the biggest. One's
first thought when looking at them all is to ask if there's a
super-pattern, a pattern to the patterns.I saw it immediately, and so did a YC founder I read the list to.
These are supposed to be the surprises, the things I didn't tell
people. What do they all have in common? They're all things I
tell people. If I wrote a new essay with the same outline as this
that wasn't summarizing the founders' responses, everyone would say
I'd run out of ideas and was just repeating myself.What is going on here?When I look at the responses, the common theme is that
starting a startup was like I said, but way more so. People just
don't seem to get how different it is till they do it. Why? The
key to that mystery is to ask, how different from what? Once you
phrase it that way, the answer is obvious: from a job. Everyone's
model of work is a job. It's completely pervasive. Even if you've
never had a job, your parents probably did, along with practically
every other adult you've met.Unconsciously, everyone expects a startup to be like a job, and
that explains most of the surprises. It explains why people are
surprised how carefully you have to choose cofounders and how hard
you have to work to maintain your relationship. You don't have to
do that with coworkers. It explains why the ups and downs are
surprisingly extreme. In a job there is much more damping. But
it also explains why the good times are surprisingly good: most
people can't imagine such freedom. As you go down the list, almost
all the surprises are surprising in how much a startup differs from
a job.You probably can't overcome anything so pervasive as the model of
work you grew up with. So the best solution is to be consciously
aware of that. As you go into a startup, you'll be thinking "everyone
says it's really extreme." Your next thought will probably be "but
I can't believe it will be that bad." If you want to avoid being
surprised, the next thought after that should be: "and the reason
I can't believe it will be that bad is that my model of work is a
job."
Notes[1]
Graduate students might understand it. In grad school you
always feel you should be working on your thesis. It doesn't end
every semester like classes do.[2]
The best way for a startup to engage with slow-moving
organizations is to fork off separate processes to deal with them.
It's when they're on the critical path that they kill you—when
you depend on closing a deal to move forward. It's worth taking
extreme measures to avoid that.[3]
This is a variant of <NAME>man's principle that if you
aren't embarrassed by what you launch with, you waited too long to
launch.[4]
The question to ask about what you've built is not whether it's
good, but whether it's good enough to supply the activation energy
required.[5]
Some VCs seem to understand technology because they actually
do, but that's overkill; the defining test is whether you can talk
about it well enough to convince limited partners.[6]
This is the same phenomenon you see with defense contractors
or fashion brands. The dumber the customers, the more effort you
expend on the process of selling things to them rather than making
the things you sell.Thanks: to <NAME> for reading drafts of this,
and to all the founders who responded to my email.Related:Startups in 13 SentencesThe Hardest Lessons for Startups to LearnHow Not to DieThe 18 Mistakes That Kill StartupsA Fundraising Survival GuideRussian TranslationKorean TranslationHebrew Translation
|
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/1a79a4-example/main.typ | typst | #set heading(numbering: "1.")
= Fibonacci sequence
The Fibonacci sequence is defined through the
recurrence relation $F_n = F_(n-1) + F_(n-2)$.
It can also be expressed in _closed form:_
$
F_n = round(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2
$
#let count = 8
#let nums = range(1, count + 1)
#let fib(n) = (
if n <= 2 {
1
} else {
fib(n - 1) + fib(n - 2)
}
)
The first #count numbers of the sequence are:
#align(
center,
table(
columns: count,
..nums.map(n => $F_#n$),
..nums.map(n => str(fib(n))),
),
)
#pagebreak()
$
f(t x_1 + (1-t)x_2, t y_1 + (1-t)y_2) <= t f(x_1, y_1) + (1-t) f(x_2, y_2)
$
Taking the derivative of the above inequality with respect to $t$ gives
$
(d F) / (d t) = (x_1 - x_2) f'_x|_((t x_1 + (1-t)x_2, t y_1 + (1-t)y_2)) + (y_1 - y_2) f'_y|_((
t x_1 + (1-t)x_2, t y_1 + (1-t)y_2
)) - f(x_1, y_1) + f(x_2, y_2)
$
Meanwhile:
$
F(0) = f(x_2, y_2) - f(x_2, y_2) = 0 \
F(1) = f(x_1, y_1) - f(x_1, y_1) = 0 \
F(t) <=0 quad (t in [0, 1])
$
So it's clear that $F'(1) >= 0$, which means:
$
(d F) / (d t)|_(t=1) = (x_1 - x_2) f'_x|_((x_1, y_1)) + (y_1 - y_2) f'_y|_((x_1, y_1)) - f(x_1, y_1) + f(x_2, y_2) >= 0
$
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1680.typ | typst | Apache License 2.0 | #let data = (
("OGHAM SPACE MARK", "Zs", 0),
("OGHAM LETTER BEITH", "Lo", 0),
("OGHAM LETTER LUIS", "Lo", 0),
("OGHAM LETTER FEARN", "Lo", 0),
("OGHAM LETTER SAIL", "Lo", 0),
("OGHAM LETTER NION", "Lo", 0),
("OGHAM LETTER UATH", "Lo", 0),
("OGHAM LETTER DAIR", "Lo", 0),
("OGHAM LETTER TINNE", "Lo", 0),
("OGHAM LETTER COLL", "Lo", 0),
("OGHAM LETTER CEIRT", "Lo", 0),
("OGHAM LETTER MUIN", "Lo", 0),
("OGHAM LETTER GORT", "Lo", 0),
("OGHAM LETTER NGEADAL", "Lo", 0),
("OGHAM LETTER STRAIF", "Lo", 0),
("OGHAM LETTER RUIS", "Lo", 0),
("OGHAM LETTER AILM", "Lo", 0),
("OGHAM LETTER ONN", "Lo", 0),
("OGHAM LETTER UR", "Lo", 0),
("OGHAM LETTER EADHADH", "Lo", 0),
("OGHAM LETTER IODHADH", "Lo", 0),
("OGHAM LETTER EABHADH", "Lo", 0),
("OGHAM LETTER OR", "Lo", 0),
("OGHAM LETTER UILLEANN", "Lo", 0),
("OGHAM LETTER IFIN", "Lo", 0),
("OGHAM LETTER EAMHANCHOLL", "Lo", 0),
("OGHAM LETTER PEITH", "Lo", 0),
("OGHAM FEATHER MARK", "Ps", 0),
("OGHAM REVERSED FEATHER MARK", "Pe", 0),
)
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/frontend/helix.typ | typst | Apache License 2.0 | #import "/docs/tinymist/frontend/mod.typ": *
#show: book-page.with(title: "Tinymist Helix Extension")
Run and configure tinymist in helix for Typst.
== Features
<features>
See #link("https://github.com/Myriad-Dreamin/tinymist#features")[Tinymist Features] for a list of features.
#include "common-finding-executable.typ"
== Setup Server
<setup-server>
Update `.config/helix/languages.toml` to use tinymist.
```toml
[language-server.tinymist]
command = "tinymist"
[[language]]
name = "typst"
language-servers = ["tinymist"]
```
== Tips
<tips>
=== Working with Multiple-File Projects
<working-with-multiple-file-projects>
There is a way in #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/README.md#multiple-file-project-support")[Neovim];, but you cannot invoke related commands with arguments by #link("https://docs.helix-editor.com/commands.html")[:lsp-workspace-command] in helix. As a candidate solution, assuming your having following directory layout:
```plain
├── .helix
│ └── languages.toml
└── main.typ
```
You could create .helix/languages.toml in the project folder with the following contents:
```toml
[language-server.tinymist.config]
typstExtraArgs = ["main.typ"]
```
Then all diagnostics and autocompletion will be computed according to the `main.typ`.
Note: With that configuration, if you’re seeing a file that is not reachable by `main.typ`, you will not get diagnostics and autocompletion correctly in that file.
== Extra Settings
<extra-settings>
To configure LSP server, you can edit the `language-server.tinymist` section. For example, if you want to export PDF on typing and output files in `$root_dir/target` directory:
```toml
[language-server.tinymist]
command = "tinymist"
config = { exportPdf = "onType", outputPath = "$root/target/$dir/$name" }
```
See #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim/Configuration.md")[Tinymist Server Configuration]
for references.
|
https://github.com/ctenopoma/SoftwareDesignTypst | https://raw.githubusercontent.com/ctenopoma/SoftwareDesignTypst/main/031.software_function_structure_definition.typ | typst | #import ".\software_designe_templete.typ": *
#show: software_requirements.with(
title: "データベース構造定義書"
)
= 概要
本書は〇〇を対象としたソフトウェアのデータベース構造定義書である。
== 目的
本書の目的は〇〇のデータベース構造を定義することである。
== 参照
本書で参照する図書を示す。
#v(10pt)
+ 参考図書1
+ 参考図書2
== 定義
本書で使用する用語を定義する。
#v(30pt)
#tbl(table(
columns: 3,
[用語], [意味], [備考],
[], [], [],
),
caption: [本書における用語の定義],
) <tbl1>
// データベースの一覧
= データベース一覧
+ データベース1
+ データベース2
// データベース毎に定義する
= データベース1
== 概要
本データべースは、〇の用途で使用する。
// データベースにデータを追加するソフトウェアコンポーネント/モジュールを記載する
== データ入力コンポーネント
本データベースにデータを追加するソフトウェアコンポーネントを以下に示す。
// データベースのデータを取得するソフトウェアコンポーネント/モジュールを記載する
== データ取得コンポーネント
本データベースからデータを取得するソフトウェアコンポーネントを以下に示す。
== 構造
本データベースのデータ構造を @db1 に示す。
#v(30pt)
#tbl(table(
columns: 6,
[データ項目], [データ型], [説明],[下限],[上限],[同値クラス],
[日付], [float32], [日付データ(32bit)], [0], [$2^32 -1$], [-],
[フラグ], [BYTE], [分類フラグ], [0], [$1$], [0:分類1 \ 1: 分類2]
),
caption: [データベース1のデータ構造],
) <db1> |
|
https://github.com/Le-foucheur/dotfile | https://raw.githubusercontent.com/Le-foucheur/dotfile/main/.config/Code/User/History/-489ce262/3ylC.typ | typst | #import "transposition.typ": *
#import "@preview/drafting:0.2.0": *
#let question = counter("questions")
#let nonumeq = math.equation.with(block: true, numbering: none)
#let dm(x) = box[#nonumeq[#x]]
#let dfrac(x, y) = math.frac(dm(x), dm(y))
#let lbar(..args) = math.display(math.cases(delim: "|", ..args))
#let ubar(body, col: red) = rect(
inset: 0pt,
outset: (bottom: 3pt, rest: 0pt),
stroke: (bottom: (0.5pt + col), rest: 0pt),
)[#body]
#let frame(x) = rect(stroke: 1pt + red, outset: (x: -2pt, y: 2pt))[#x]
#let dframe(x) = frame(dm(x))
#let donc = "donc" + h(3pt)
#let Donc = "Donc" + h(3pt)
#let onA = "On a" + h(3pt)
#let tq = "tel que" + h(3pt)
#let et = "et" + h(3pt)
#let dt = math.dif + "t"
#let Id(n) = math.mat(..for x in range(n){
let l = ()
for y in range(n){
if y == x {
l.push(1)
} else { l.push(0) }
}
(l,)
})
#let M0(n) = math.mat(..for x in range(n){
let l = ()
for y in range(n){
l.push(0)
}
(l,)
})
#let tend(n, val) = $limits(-->)_(#n -> #val)$
#let undermath(body, col: red)= {
style(styles => {
let size = measure(dm(body), styles);
let size2 = measure(body, styles);
let offshet = ((size.height) - (size2.height)) / 1.1 + 1.3pt;
box(stroke: (bottom: col + 1pt), outset: (bottom: offshet), body);
})
}
#let th = "th"
#let t(x) = for i in range(x) {
h(1em)
}
#let cv = "converge" + h(3pt)
#let bi = math.beta.alt
#let soitn(body, ens) = [soit $#body in #ens$]
#let soietn(body, ens) = [soient $#body in #ens$]
#let Soitn(body, ens) = [Soit $#body in #ens$]
#let Soietn(body, ens) = [Soient $#body in #ens$]
#let ssi = "si et seulement si" + h(1pt)
#let vect(body) = "Vect("+ body + ")"
#let ateb = math.beta.alt
#let Ker(body) = if (body.fields().keys() == ("text",)) {[Ker #body]} else {[Ker(#body) ]}
#let Im(body) = if (body.fields().keys() == ("text",)) {[Im #body]} else {[Im(#body) ]}
#let Vect = "Vect"
#let ou = "ou" + h(3pt)
#let G = $#text(font: "LT Perfume")[G]$+ h(4pt)
#let C = $#text(font: "LT Perfume")[C]$+ h(4pt)
#let ar(body) = $arrow(#body)$
#let ve(..body) = {grid(columns: 1,row-gutter: 3pt ,grid.vline(), ..body)}
#let equi(n : $n$, k : $+oo$) = $ tilde_(#n -> #k) $
#let po(ele : $x$ , vers : $0$ ) = $ =_(#ele -> #vers) $
#let QED = align(right, text[*Q.E.D.*]) // Quod erat demonstratum
#let LAF = align(center, text(17pt)[*L.A.F.*]) //Labor ad facio
#let a = text[#h(-16pt) a.]
//tout les set rule :
#let template(doc) = [
#set heading(numbering: (..numbers) => {
let n = numbers.pos().len()
if n == 1 {
question.update(1)
} else if n == 2 {
[Partie ]
numbering("I", numbers.pos().at(1) - 1)
"."
} else if n == 3 {
question.step()
if question.get().last() < 10 {
margin-note(side: left, dy: -16.4pt, stroke: none)[#h(14pt)N=° #question.display().]
} else {
margin-note(side: left, dy: -16.4pt, stroke: none)[#h(8pt)N=° #question.display().]
}
} else if n == 4 {
margin-note(side: left, dy: -16.5pt, stroke: none)[#h(34pt)#numbering("a.", numbers.pos().at(3) + 1) ]
} else if n == 5 {
numbering("i.", numbers.pos().at(4))
}
})
#set underline(stroke: red + 1pt)
#set par(leading: 0.8em)
#set page(numbering: (..nums) => nums.pos().map(na).join("/"), number-align: right)
#set math.cancel(stroke: red)
#set text(font:"Linux Libertine")
#doc
] |
|
https://github.com/YouXam/soviet-matrix | https://raw.githubusercontent.com/YouXam/soviet-matrix/main/template/main.typ | typst | MIT License | #import "@preview/soviet-matrix:0.1.0": game
#show: game.with(seed: 0)
/*
Move Left: a
Move Right: d
Soft Drop: s
Hard Drop: f
Rotate Left: q
Rotate Right: e
180-degree Rotate: w
Enter characters below to get started.
*/
|
https://github.com/tiankaima/typst-notes | https://raw.githubusercontent.com/tiankaima/typst-notes/master/feebf7-2023_fall_TA/graphs/graph_1.typ | typst | #import "@preview/cetz:0.1.1"
#cetz.canvas({
import cetz.draw: *
// Your drawing code goes here
let chart(..values, name: none) = {
let values = values.pos()
let offset = 0
let total = values.fold(0, (s, v) => s + v.at(0))
let segment(from, to) = {
merge-path(
close: true,
{
line((0, 0), (rel: (360deg * from, 1)))
arc((), start: from * 360deg, stop: to * 360deg, radius: 1)
},
)
}
group(
name: name,
{
stroke((paint: black, join: "round"))
let i = 0
for v in values {
fill(v.at(1))
let value = v.at(0) / total
// Draw the segment
segment(offset, offset + value)
// Place an anchor for each segment
anchor(v.at(2), (offset * 360deg + value * 180deg, .75))
offset += value
}
},
)
}
// Draw the chart
chart(
(10, red, "red"),
(3, blue, "blue"),
(1, green, "green"),
name: "chart",
)
set-style(
mark: (fill: white, start: "o", stroke: black),
content: (padding: .1),
)
// Draw annotations
line("chart.red", ((), "-|", (2, 0)))
content((), [Red], anchor: "left")
line("chart.blue", (1, -1), ((), "-|", (2, 0)))
content((), [Blue], anchor: "left")
line("chart.green", ((), "-|", (2, 0)))
content((), [Green], anchor: "left")
}) |
|
https://github.com/touying-typ/touying | https://raw.githubusercontent.com/touying-typ/touying/main/themes/themes.typ | typst | MIT License | #import "default.typ"
#import "simple.typ"
#import "metropolis.typ"
#import "dewdrop.typ"
#import "university.typ"
#import "aqua.typ"
#import "stargazer.typ" |
https://github.com/Isaac-Duan/ousr_typst_templates | https://raw.githubusercontent.com/Isaac-Duan/ousr_typst_templates/main/证件照片A4复印排版.typ | typst | MIT License | #set page("a4")
// 身份证照片,一页正反面
// 长85.6mm, 高 54.0mm
#place(
dx: 20%,
dy: 10%,
image("__身份证正面照片模板.jpg", width: 85.6mm, height: 54.0mm),
)
#place(
dx: 20%,
dy: 60%,
image("__身份证反面照片模板.jpg", width: 85.6mm, height: 54.0mm),
)
#pagebreak()
// 户口本单页照片
// 单页尺寸长143毫米,宽105毫米
#place(
dx: 8%,
dy: 20%,
image("__户口本页照片模板.jpg", width: 143mm, height: 105mm),
) |
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/utility.typ | typst | Other | #import "/src/lib.typ" as z
#let show-rule(body, ..args) = {
set page(height: auto)
body
}
#let utility-expect-eq(
schema: none,
test: none,
truth: none,
) = block.with(
width: 100%,
inset: 8pt,
radius: 4pt,
fill: if (z.parse(test, schema, ctx: z.z-ctx(soft-error: true)) == truth) {
rgb("#c4e4bd")
} else {
rgb("#f5d3d6")
},
) |
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Modules/WritingAnArgument.typ | typst | #import "../../../template.typ": *
= How to Argue?
*Classical Structure*
Introduction #sym.arrow.r Presentation of writer's position #sym.arrow.r Summary of Opposing views #sym.arrow.r response to opposing views #sym.arrow.r conclusion
== Classical Appeals
#definition[
*Logos*: appear to logic, focuses attention on the quality of the message, the clarity of the argument itself and the logic of its reasons and supports
]
#definition[
*Ethos*: focuses on the writer's character of credibility. This can come through the professionalism of the paper, the expert reputation of the author, the _appeal from credibility_
]
#definition[
*Pathos*: focuses on the values of the intended audience, _appeal to their emotions_
]
== When to use which?
*Logos*
- Articles in scholarly journals
- Legal briefs and court descriptions
- Visual arguments (unbiased graphs/charts, etc)
*Ethos*
- Using speeches from well respected experts
- Newspaper editorials from experts
- First hand account from expert
*Pathos*
- Blogs/Message Boards
- Personal stories
- Visual Arguments (political cartoons, photographs)
- Public affairs advocacy advertisements
|
|
https://github.com/Wybxc/typst-nix | https://raw.githubusercontent.com/Wybxc/typst-nix/main/templates/handout/handout.typ | typst | Apache License 2.0 | #let project(title: "", authors: (), date: none, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: "1 / 1", number-align: end)
set text(
font: (
"Inria Serif",
"Source Han Serif SC"
),
weight: "medium",
lang: "zh"
)
set par(justify: true, first-line-indent: 2em)
set heading(numbering: "1 ")
show heading: it => {
set text(font: "Inria Serif")
if it.level == 1 [
#v(1em)
#align(center)[
#strong(counter(heading).display())
#strong(it.body)
#v(1em, weak: true)
]
] else [
#set par(first-line-indent: 0em)
#strong(it.body)
]
}
show emph: it => {
set text(font: "AR PL UKai")
it.body
}
show strong: it => {
set text(font: "Source Han Sans SC", weight: "medium")
it.body
}
set list(indent: 2em)
set enum(indent: 2em)
// Title row.
align(center)[
#block(text(font: "Source Han Serif SC", weight: "bold", 2em, title))
#v(1.5em, weak: true)
#text(weight: "semibold", date)
]
// Author information.
pad(
bottom: 0.25em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, author)),
),
)
// Main body.
body
}
// 处理首行缩进消失的零高假段落
#let fake-para = {
$ $
v(-1.65em)
}
#let angled(..x) = $lr(angle.l #x.pos().join(",") angle.r)$
#let QED = align(right, rect(width: 0.75em, height: 0.75em, stroke: {0.5pt + black}))
#let rank = $op("rank")$
#let argmin = math.op("argmin", limits: true)
#let argmax = math.op("argmax", limits: true)
#let varnothing = move(scale(x: -100%)[$nothing.rev$], dy: -0.12em)
|
https://github.com/touying-typ/touying | https://raw.githubusercontent.com/touying-typ/touying/main/examples/simple.typ | typst | MIT License | #import "../lib.typ": *
#import themes.simple: *
#show: simple-theme.with(
aspect-ratio: "16-9",
footer: [Simple slides],
)
#title-slide[
= Keep it simple!
#v(2em)
Alpha #footnote[Uni Augsburg] #h(1em)
Bravo #footnote[Uni Bayreuth] #h(1em)
Charlie #footnote[Uni Chemnitz] #h(1em)
July 23
]
== First slide
#lorem(20)
#focus-slide[
_Focus!_
This is very important.
]
= Let's start a new section!
== Dynamic slide
Did you know that...
#pause
...you can see the current section at the top of the slide? |
https://github.com/wenzlawski/typst-cv | https://raw.githubusercontent.com/wenzlawski/typst-cv/main/modules/skills.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Skills")
#cvSkill(
type: [Languages],
info: [German (native) #hBar() English (fluent) #hBar() French (limited)]
)
#cvSkill(
type: [Technology],
info: [Python (Pandas/Numpy) #hBar() R (tidyerse) #hBar() Julia #hBar() SQL #hBar() Rust]
)
#cvSkill(
type: [Programs],
info: [Git, Linux, Docker, Emacs]
)
#cvSkill(
type: [Personal Interests],
info: [Rock Climbing #hBar() Literature #hBar() Philosophy #hBar() FOSS #hBar() Art]
)
|
https://github.com/ntjess/typst-drafting | https://raw.githubusercontent.com/ntjess/typst-drafting/main/README.md | markdown | The Unlicense | # Margin Notes
## Setup
`drafting` exists in the official typst package repository, so the
recommended approach is to import it from the `preview` namespace:
``` typst
#import "@preview/drafting:0.2.0"
```
Margin notes cannot lay themselves out correctly until they know your
page size and margins. To this end, make sure call
`#set-page-properties()` **after** configuring your page size/margins:
``` typ
// Of course, you can set whatever margin values you prefer
#set page(
margin: (right: 2in), paper: "us-letter"
)
// This is important! Call it whenever your page is reconfigured.
#set-page-properties()
```
Note: `drafting` does not yet support `inside`/`outside` margins. Follow
<https://github.com/typst/typst/issues/3636> for updates.
## The basics
<span id="input-text"></span>
```typst
#lorem(20)
#margin-note(side: left)[Hello, world!]
#lorem(10)
#margin-note[Hello from the other side]
#margin-note[When notes are about to overlap, they're automatically shifted]
#margin-note(stroke: aqua + 3pt)[To avoid collision]
#lorem(25)
#margin-note(stroke: green, side: left)[You can provide two positional arguments if you want to highlight a phrase associated with your note.][The first is text which should be inline-noted, and the second is the standard margin note.]
#let caution-rect = rect.with(inset: 1em, radius: 0.5em, fill: orange.lighten(80%))
#inline-note(rect: caution-rect)[
Be aware that `typst` will complain when 4 notes overlap, and stop automatically avoiding collisions when 5 or more notes
overlap. This is because the compiler stops attempting to reposition notes after a few attempts
(initial layout + adjustment for each note).
You can manually adjust the position of notes with `dy` to silence the warning.
]
```

## Adjusting the default style
All function defaults are customizable through updating the module
state:
<span id="input-text"></span>
```typst
#lorem(14) #margin-note[Default style]
#lorem(10)
#set-margin-note-defaults(stroke: orange, side: left)
#margin-note[Updated style]
#lorem(10)
```

Even deeper customization is possible by overriding the default `rect`:
<span id="input-text"></span>
```typst
#import "@preview/colorful-boxes:1.1.0": stickybox
#let default-rect(stroke: none, fill: none, width: 0pt, content) = {
set text(0.9em)
stickybox(rotation: 30deg, width: width/1.5, content)
}
#set-margin-note-defaults(rect: default-rect, stroke: none, side: right)
#lorem(20)
#margin-note(dy: -5em)[Why not use sticky notes in the margin?]
// Undo changes from this example
#set-margin-note-defaults(rect: rect, stroke: red)
```

## Multiple document reviewers
<span id="input-text"></span>
```typst
#let reviewer-a = margin-note.with(stroke: blue)
#let reviewer-b = margin-note.with(stroke: purple)
#lorem(10)
#reviewer-a[Comment from reviewer A]
#lorem(5)
#reviewer-b(side: left)[Reviewer B comment]
#lorem(10)
```

## Inline Notes
<span id="input-text"></span>
```typst
#lorem(10)
#inline-note[The default inline note will split the paragraph at its location]
#lorem(10)
#inline-note(par-break: false, stroke: (paint: orange, dash: "dashed"))[
But you can specify `par-break: false` to prevent this
]
#lorem(10)
```

## Hiding notes for print preview
<span id="input-text"></span>
```typst
#set-margin-note-defaults(hidden: true)
#lorem(20)
#margin-note[This will respect the global "hidden" state]
#margin-note(hidden: false, dy: -2.5em)[This note will never be hidden]
// Undo these changes
#set-margin-note-defaults(hidden: false)
```

# Positioning
## Precise placement: rule grid
Need to measure space for fine-tuned positioning? You can use
`rule-grid` to cross-hatch the page with rule lines:
<span id="input-text"></span>
```typst
#rule-grid(width: 10cm, height: 3cm, spacing: 20pt)
#place(
dx: 180pt,
dy: 40pt,
rect(fill: white, stroke: red, width: 1in, "This will originate at (180pt, 40pt)")
)
// Optionally specify divisions of the smallest dimension to automatically calculate
// spacing
#rule-grid(dx: 10cm + 3em, width: 3cm, height: 1.2cm, divisions: 5, square: true, stroke: green)
// The rule grid doesn't take up space, so add it explicitly
#v(3cm + 1em)
```

## Absolute positioning
What about absolutely positioning something regardless of margin and
relative location? `absolute-place` is your friend. You can put content
anywhere:
<span id="input-text"></span>
```typst
#context {
let (dx, dy) = (here().position().x, here().position().y)
let content-str = (
"This absolutely-placed box will originate at (" + repr(dx) + ", " + repr(dy) + ")"
+ " in page coordinates"
)
absolute-place(
dx: dx, dy: dy,
rect(
fill: green.lighten(60%),
radius: 0.5em,
width: 2.5in,
height: 0.5in,
[#align(center + horizon, content-str)]
)
)
}
#v(0.5in)
```

The “rule-grid” also supports absolute placement at the top-left of the
page by passing `relative: false`. This is helpful for “rule“-ing the
whole page.
|
https://github.com/jomaway/typst-bytefield | https://raw.githubusercontent.com/jomaway/typst-bytefield/main/bytefield.typ | typst | MIT License | // Bytefield - generate protocol headers and more
// pull in the user facing api
#import "lib/api.typ": bytefield, bit, bits, byte, bytes, flag, group, note, bitheader, section
#import "lib/states.typ": bf-config
// import common network protocols
#import "common.typ";
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/01-leftovers/!sec.typ | typst | #import "../../config.typ"
= Остатки сладки
#include "01-cond-extremes.typ"
|
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/15_avtomatsko_odvajanje.typ | typst | = Avtomatsko odvajanje z dualnimi števili
== Naloga
- Definirajte podatkovni tip za dualna števila.
- Za podatkovni tip dualnega števila definirajte osnovne operacije in elementarne
funkcije, kot so $sin$, $cos$ in $exp$.
- Uporabite dualna števila in izračunajte hitrost nebesnega telesa, ki se giblje po
Keplerjevi orbiti. Keplerjevo orbito izrazite z rešitvijo #link("https://en.wikipedia.org/wiki/Kepler%27s_equation")[Keplerjeve enačbe], ki jo rešite z Newtonovo metodo.
- Posploši dualna števila, da je komponenta pri $epsilon$ lahko vektor. Uporabite
posplošena dualna števila za izračun gradienta funkcije več spremenljivk. |
|
https://github.com/Enter-tainer/typstyle | https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/grid/array.typ | typst | Apache License 2.0 | #grid(
columns: (60pt, 1fr, 2fr),
rows: (auto, 60pt),
gutter: 3pt,
rect[Fixed width, auto height],
rect[1/3 of the remains],
rect[2/3 of the remains],
rect(height: 100%)[Fixed height],
[image],
[image]
)
|
https://github.com/pauladam94/ENS-Rennes-Typst-Slides-Template | https://raw.githubusercontent.com/pauladam94/ENS-Rennes-Typst-Slides-Template/main/slides.typ | typst | #let slide-number = counter("slide-number")
#let sections = state("section")
#let global-title = state("title")
#let global-short-title = state("short-title")
#let global-subtitle = state("subtitle")
#let global-authors = state("authors")
#let global-short-authors = state("short-authors")
#let global-date = state("date")
#let global-color-accentuation = state("color-accentuation")
#let global-aspect-ratio = state("aspect-ratio")
#let global-logo-path = state("logo-path")
#let slides(
title: none,
short-title: none,
subtitle: none,
authors: none,
short-authors: none,
date: none,
color-accentuation : none,
aspect-ratio: "16-9",
logo-path: none,
body
) = {
set text(
font: "Fira Code",
size: 25pt,
)
set page(
paper: "presentation-" + aspect-ratio,
margin: 0pt
)
global-title.update(title)
global-short-title.update(short-title)
global-subtitle.update(subtitle)
global-authors.update(authors)
global-short-authors.update(short-authors)
global-date.update(date)
global-color-accentuation.update(color-accentuation)
global-aspect-ratio.update(aspect-ratio)
global-logo-path.update(logo-path)
body
}
// ||==========SECTION==========||
#let section(
title,
level : 1
) = {
if level < 1 {
panic("level should be positive")
}
sections.update(
arr => {
if arr == none {
((title: title, level : level),)
} else {
arr.push((title: title, level: level))
arr
}
}
)
}
// ||==========TITLE==========||
#let title-slide(
) = {
set align(center)
locate(loc => {
let body = [
#text(
size: 30pt,
weight: 900,
global-title.display()) \ \
#text(
size: 20pt,
weight: 500,
global-subtitle.display())
]
let border = 3mm + global-color-accentuation.at(loc).at(0)
block(
stroke: (top: border, bottom: border),
width: 80%,
inset: 1.5em,
above: 1fr,
text(.8em, body)
)
// let path = global-logo-path.at(loc)
let path = "logo-ENS-Rennes.png"
if path != none {
image(
width: 150pt,
path
)
}
text(global-authors.at(loc) + [ \ ])
text(14pt,global-date.at(loc))
v(1fr)
})
}
// ||==========MAXI-OUTLINE==========||
#let maxi-outline(
) = {
let marker(level) = {
if level == 1 [|>] else if level == 2 [->] else [--]
}
locate(loc => {
let sections = sections.final(loc)
list(
spacing: 50pt,
marker: [],
..sections.map(
section => {
box(
inset : (left: ((section.level - 1)* 80 + 50)*1pt),
[#marker(section.level) #section.title]
)
}
)
)
})
}
// ||==========MINI-OUTLINE==========||
#let mini-outline(
) = {
locate(loc => {
let acc = ()
let current_level = 0
let arr = sections.at(loc)
if arr != none {
for i in range(arr.len() - 1, -1, step: -1) {
let (title, level) = arr.at(i)
if i == arr.len() - 1 {
current_level = level
acc.push(title)
} else if current_level == level + 1 {
acc.push(title)
current_level = level
} else if level == 1 {
break
}
}
}
for (i,title) in acc.rev().enumerate() {
[-> #title ]
}
})
}
// ||==========HEADER==========||
#let header(
) = {
locate(loc => {
let body = [
#grid(
columns: (20fr, 6fr, 2fr, 1fr),
mini-outline(),
global-title.display(),
{
let path = global-logo-path.at(loc)
if path != none {
image(
width: 20pt,
path
)
}
},
image(width: 20pt, "logo-ENS-Rennes.png")
)
]
let border = 1mm + global-color-accentuation.at(loc).at(1)
block(
stroke: (bottom: border),
width: 100%,
inset: .2em,
align(horizon)[#text(.5em, body)]
)
})
}
// ||==========FOOTER==========||
#let footer() = {
locate(loc => {
let body = [
#grid(
columns: (8fr, 8fr, 1fr),
global-short-authors.display(),
global-short-title.display(),
[#slide-number.display() / #slide-number.final(loc).at(0)]
)
]
let border = 1mm + global-color-accentuation.at(loc).at(2)
block(
stroke: (top: border),
width: 100%,
inset: .3em,
text(.5em, body)
)
})
}
#let title_show(title) = {
block(
inset: (left: 50pt, top: 0pt, bottom: 0pt),
text(25pt, weight: "black", title)
)
}
// ||==========SLIDE==========||
#let slide(
type: none,
title: none,
.. bodies
) = {
slide-number.step()
if type == "title" and bodies.pos().len() == 0 and title == none {
// ||==========TITLE-SLIDE==========||
title-slide()
pagebreak()
} else if type == "outline" and bodies.pos().len() == 0 and title == none {
// ||==========OUTLINE-SLIDE==========||
header()
v(1fr)
maxi-outline()
v(2fr)
footer()
pagebreak()
} else if type == none {
// ||==========NORMAL-SLIDE==========||
let acc = ()
for (index, body) in bodies.pos().enumerate() {
acc.push(body)
// ||==========HEADER==========||
header()
// ||==========TITLE==========||
title_show(title)
// ||==========BODY==========||
block(
inset: (left: 20pt),
for acc-body in acc {
acc-body
}
)
v(1fr)
// ||==========FOOTER==========||
footer()
pagebreak(weak: true)
}
} else if (type == "outline" or type == "title") and title != none {
panic("outline and title slide doesn't have a title" + "")
} else if (type == "outline" or type == "title") and bodies.pos().len() != 0 {
panic("outline and title slide doesn't have a body")
}
}
|
|
https://github.com/gomazarashi/Typst_report | https://raw.githubusercontent.com/gomazarashi/Typst_report/main/typst_report.typ | typst | #set text(lang: "ja") // 言語を日本語に設定
#set text(font: ("<NAME>","New Computer Modern"),size: 10pt,) // フォントを設定
#set table(inset: 7pt) // 表の余白を設定
// 表のキャプションを上部に表示するよう設定
#show figure.where(
kind: table
): set figure.caption(position: top)
// 見出しの設定
#show heading: set text(font: ("<NAME>"),weight:500 )
#set heading(numbering: "1.1.")
#align(center)[
#v(200pt)
#text(
size: 18pt,
)[
タイトル
]
#v(10pt)
#text(
size: 12pt,
)[
氏名 \
所属1 \
所属2 \
学籍番号 0000000 \
\
#datetime.today().display("[year]年[month]月[day]日")
]
]
#pagebreak()
#set page(numbering: "1/1")
#counter(page).update(1)
= 図
#figure(
image("./apple.jpg",width: 50%),
caption: "リンゴの画像",
)<apple>
@apple はリンゴの画像です。
= 表
#figure(
table(
columns: 3,
[これは],[テーブル],[です],
[これは],[テーブル],[です],
[これは],[テーブル],[です],
),
caption: "テーブル",
)<table>
@table はテーブルです。
= リンク
\
#link("https://oucrc.net")[岡山大学電子計算機研究会: OUCRC]
#link("https://oucrc.net")
|
|
https://github.com/Error0229/- | https://raw.githubusercontent.com/Error0229/-/main/__/__%20....typ | typst | The Unlicense | #set text(font: ("Microsoft Sans Serif", "New Computer Modern"))
#align(center, text(24pt)[
*現代科技概論 期末心得報告*\
*淺談如何面對死亡*
])
#align(right, [資工三 110590004 林奕廷])
= 導言
死亡是人類共通的終極經歷,它帶來的恐懼和未知感深深影響著每個人的生活態度和決策。理解和接受死亡,不僅是個人的心理挑戰,更是文化和社會結構中的一部分。不同的文化對死亡有著不同的解讀和儀式,這些文化觀念塑造了我們對死亡的認知和應對方式。通過深入探討臨終治療、老年生活品質以及重大疾病時的安排,本文旨在探討如何幫助人們更好地準備和面對死亡,達到身心的和諧與平靜。
= 臨終治療
臨終治療是指在病人接近生命末期時提供的醫療和心理支持。其目的是減輕痛苦,提升生命最後階段的生活品質。臨終治療包括疼痛管理、心理輔導和社會支持。
== 疼痛管理
在臨終階段,許多病人會經歷嚴重的疼痛。適當的疼痛管理可以通過藥物治療、物理治療和心理支持來實現,減輕病人的痛苦,使他們能夠有尊嚴地度過生命的最後時光。疼痛管理不僅僅是緩解身體上的不適,更是關係到病人心靈上的平靜和家庭的和諧。通過使用適當的藥物,如阿片類藥物、非甾體抗炎藥物等,結合物理治療和心理支持,可以有效地緩解疼痛,提升病人和家屬的生活品質。此外,疼痛管理還包括針對病人的個體需求制定個性化的治療計劃,確保病人在臨終階段獲得全方位的照顧和支持。
== 心理輔導
面對死亡,病人和家屬往往會感到恐懼和無助。心理輔導可以幫助他們接受現實,處理悲傷,並找到內心的平靜。臨終心理輔導的目標是幫助病人和家屬在面對死亡的過程中,找到內心的力量和支持,接受和適應即將到來的變化。輔導過程中,專業的心理治療師會使用不同的技術,如認知行為療法、冥想和放鬆訓練等,幫助病人和家屬緩解焦慮和抑鬱,增強他們的心理韌性。此外,心理輔導還強調家庭成員之間的溝通和支持,幫助他們共同面對和處理因疾病和死亡帶來的挑戰。
= 健康管理
定期的體檢和健康管理是保持身體健康的重要措施。良好的飲食習慣、適量的運動和充足的睡眠可以延緩衰老,提升生活品質。健康管理不僅僅是關注身體健康,還包括心理和社會層面的健康。這需要老年人積極參與社會活動,保持心理上的健康和平衡。例如,參與社區活動、志願服務和興趣小組,可以幫助老年人建立社交聯繫,增加生活的滿足感。此外,良好的健康管理還需要與醫療專業人士保持密切聯繫,及時獲取健康資訊和醫療支持,確保老年人能夠在健康問題出現時,及時獲得有效的治療和照顧。
= 社會支持
社會支持包括家人、朋友和社區的關懷和幫助。強大的社會支持系統可以提供情感上的安慰,減少孤獨感,增加生活的滿足感。社會支持系統對於老年人的生活品質有著深遠的影響。家庭成員的支持和關愛,是老年人心理健康的重要保障。同時,社區和社會服務機構也應積極提供多樣化的支持服務,如健康講座、心理輔導和社會活動等,幫助老年人保持積極的生活態度。此外,社會支持還應包括經濟上的保障,如退休金和醫療保險,確保老年人在經濟上不會因疾病和老齡化而陷入困境。
= 參與有意義的活動
參與有意義的活動如志願服務、學習新技能或興趣愛好,不僅可以豐富生活,還可以保持心理健康,增強自我價值感。有意義的活動對於老年人來說,不僅僅是消遣和娛樂,更是保持身心健康的重要方式。例如,參加志願服務活動,可以讓老年人感受到自我價值和社會的認同;學習新技能,可以激發他們的求知欲和創造力,增強自信心;發展興趣愛好,如園藝、繪畫和音樂,則可以幫助他們放鬆心情,減少壓力。此外,參與有意義的活動還可以促進社交互動,幫助老年人建立和維持良好的人際關係,從而提升整體生活品質。
= 面臨重大疾病時的安排
當面臨重大疾病時,提前安排和溝通是關鍵。這不僅能幫助病人過上有尊嚴的生活,還能減輕家屬的負擔。
== 預立醫療指示
預立醫療指示是病人在清醒時對未來醫療決策的指示文件。它可以包括不施行心肺復甦術、不插管等具體醫療措施,確保在無法表達意願時,醫療人員能按照病人的意願進行治療。預立醫療指示的制定,需要病人與醫療專業人士進行充分的溝通和討論,確保其內容符合病人的真實意願和需求。此外,病人還應該與家屬分享這些指示,確保家屬在緊急情況下,能夠理解並支持病人的選擇。這不僅可以減少家屬在面對重大醫療決策時的壓力,還能避免因意見分歧而導致的衝突。
== 與家屬的溝通
與家屬進行坦誠的溝通是減少誤解和衝突的重要步驟。了解病人的意願和期望,並共同制定應對方案,可以減輕家屬的心理負擔,增強他們的支持力量。有效的溝通需要耐心和技巧,病人和家屬應該在平和的氛圍中進行討論,確保每個人的聲音都能被聽到和尊重。除了口頭溝通,書面的醫療指示和備忘錄也是重要的工具,可以在關鍵時刻提供清晰的指導。此外,醫療專業人士也應該積極參與到這些溝通過程中,提供專業的建議和支持,幫助病人和家屬做出明智的決策。
= 個人觀點
在探討如何面對死亡的過程中,我不禁思考,究竟什麼是我們應該追求的「好死」?死亡作為生命的終點,它的意義不僅僅在於結束,而是在於如何結束。我們生活在一個崇尚年輕和健康的社會,死亡往往被視為一種失敗或是禁忌。然而,真正的挑戰在於如何在面對不可避免的死亡時,仍然能夠保持尊嚴和意義。
死亡的意義不僅僅局限於個人,它還深刻影響著我們周圍的世界。當我們考慮如何面對自己的死亡時,我們同時也在考慮如何影響我們的親人和朋友。我們的選擇不僅是對自己負責,也是對他人負責。這需要我們在生前就開始思考和準備,這樣才能在面對死亡時不至於慌亂失措。
一個令人深思的問題是,我們是否應該將所有的資源和努力都用在延長生命上?醫學技術的進步讓我們有能力延長生命,但這是否真的意味著我們的生活品質會因此提高?我們是否應該在某個時刻接受死亡,並將重點放在如何有尊嚴地生活和離開這個世界,而不是盲目地追求生命的延續?
我認為,我們需要重新審視死亡的意義,並學會接受它作為生命的一部分。這並不是說我們不應該努力治療疾病或是延長生命,而是我們應該在這個過程中保持一種平衡和理性。接受死亡並不意味著放棄,而是意味著我們懂得何時該放手,何時該讓生命自然地走到終點。
面對死亡,我們需要更多的勇氣和智慧,去做出那些看似困難但卻必要的決定。這些決定將影響我們如何度過生命的最後階段,如何與我們的親人告別,以及我們將留下什麼樣的遺產和回憶給後人。死亡的到來雖然無法避免,但我們完全可以選擇如何面對它,並在這個過程中找到生命的最終意義。
= 結論
死亡雖然是生命的終點,但我們可以通過準備和安排,使這一過程更加平和和有尊嚴。臨終治療、有意義的老年生活,以及面臨重大疾病時的安排,都是我們可以努力的方向。提前了解並面對這些問題,不僅可以提高個人的生活品質,還能給家人帶來更多的安慰和支持。
提前準備和安排,不僅可以使個人在面對死亡時更加從容和有尊嚴,還能減輕家屬的心理負擔。通過提前制定醫療指示和進行有效的溝通,可以避免在緊急情況下出現混亂和衝突,確保病人的意願得到尊重和實現。此外,提前準備還可以幫助家屬更好地應對和處理悲傷,減少因失去親人而帶來的心理創傷和負面情緒。因此,我們每個人都應該積極面對死亡,提前做好準備,為自己和家人創造一個更好的未來。
|
https://github.com/platformer/typst-homework-template | https://raw.githubusercontent.com/platformer/typst-homework-template/main/README.md | markdown | MIT License | # typst-homework-template
Just a simple Typst template for homework assignments. To use it, add `hw-template.typ` to your project and import it:
```typst
#import "hw-template.typ": hw, problem
```
See `hw-example.typ` and `hw-example.pdf` for example usage. Look at `hw-template.typ` to see the options the different functions have (don't worry, it's short).
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-31350.typ | typst | Apache License 2.0 | #let data = (
"0": ("<CJK Ideograph Extension H, First>", "Lo", 0),
"105f": ("<CJK Ideograph Extension H, Last>", "Lo", 0),
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/supercharged-dhbw/1.3.0/template/abstract.typ | typst | Apache License 2.0 | #let abstract = [
#lorem(200)
] |
https://github.com/Hao-Yuan-He/resume_typst | https://raw.githubusercontent.com/Hao-Yuan-He/resume_typst/main/resume.typ | typst | #let resume(
author: "",
location: "",
email: "",
github: "",
linkedin: "",
phone: "",
personal-site: "",
accent-color: "#000000",
img:"",
body,
) = {
// Sets document metadata
set document(author: author, title: author)
// Document-wide formatting, including font and margins
set text(
// LaTeX style font
font: ("Calibri", "PingFang SC"),
size: 10pt,
lang: "en",
// Disable ligatures so ATS systems do not get confused when parsing fonts.
ligatures: true
)
// Reccomended to have 0.5in margin on all sides
set page(
margin: (0.5in),
"us-letter",
)
// Link styles
show link: underline
// Small caps for section titles
show heading.where(level: 2): it => [
#pad(top: 0pt, bottom: -10pt, [#smallcaps(it.body)])
#line(length: 100%, stroke: 1pt)
]
// Accent Color Styling
show heading: set text(
fill: rgb(accent-color),
)
show link: set text(
fill: rgb(accent-color),
)
// Name will be aligned left, bold and big
show heading.where(level: 1): it => [
#set align(left)
#set text(
weight: 400,
size: 20pt,
font: ( "Linux Libertine","Songti SC"),
)
#it.body
]
show image: it => block(
radius: 50pt, clip: true
)[#it]
let personal_info = (
if phone != "" {
phone
},
if location != "" {
location
},
if email != "" {
link("mailto:" + email)[#email]
},
if github != "" {
link("https://" + github)[#github]
},
if linkedin != "" {
link("https://" + linkedin)[#linkedin]
},
if personal-site != "" {
link("https://" + personal-site)[#personal-site]
},
).filter(x => x != none).join(" | ")
// Level 1 Heading
[= #(author)]
// Personal Info
pad(
top: 0.25em,
align(left)[
#(
personal_info
)
],
)
place(
image(img, width: 50pt),
dx:6.8in,dy:-0.65in,
)
// Main body.
set par(justify: true)
body
}
// Generic two by two component for resume
#let generic-two-by-two(
top-left: "",
top-right: "",
bottom-left: "",
bottom-right: "",
) = {
pad[
#top-left #h(1fr) #top-right \
#bottom-left #h(1fr) #bottom-right
]
}
// Generic one by two component for resume
#let generic-one-by-two(
left: "",
right: "",
) = {
pad[
#left #h(1fr) #right
]
}
// Cannot just use normal --- ligature becuase ligatures are disabled for good reasons
#let dates-helper(
start-date: "",
end-date: "",
) = {
start-date + " " + $dash.en$ + " " + end-date
}
// Section components below
#let edu(
institution: "",
dates: "",
degree: "",
gpa: "",
location: "",
) = {
generic-two-by-two(
top-left: strong(institution),
bottom-left: text[
#set text(
weight: 100,
size: 9pt,
font: ("Calibri","STFangsong",),
)
#degree
],
top-right: text(gray)[#dates]
)
}
#let description(
des:"",
) = {
align(left)[
#set text(
weight: 200,
size: 8pt,
font: ("Calibri","STFangsong",),
)
#des
]
}
#let work(
title: "",
dates: "",
des: "",
location: "",
) = {
generic-two-by-two(
top-left: strong(title),
top-right: dates,
bottom-left: text[
#set text(
weight: 100,
size: 9pt,
font: ("Calibri","STFangsong",),
)
#des
],
bottom-right: emph[
#set text(
weight: 100,
size: 9pt,
font: ("Calibri","STFangsong",),
)
#location
],
)
}
#let project(
role: "",
name: "",
url: "",
dates: "",
) = {
pad[
*#role*, #name (#link("https://" + url)[#url]) #h(1fr) #dates
]
}
#let extracurriculars(
activity: "",
dates: "",
) = {
generic-one-by-two(
left: strong(activity),
right: dates,
)
}
#let award(
name: "",
des:"",
dates: "",
) = {
generic-two-by-two(
top-left: strong(name),
bottom-left: text[
#set text(
weight: 100,
size: 9pt,
font: ("Calibri","STFangsong",),
)
#des
],
top-right: dates,
)
} |
|
https://github.com/Tran-Thu-Le/tybank | https://raw.githubusercontent.com/Tran-Thu-Le/tybank/main/template.typ | typst | #import "utils.typ": *
// ---------------------------------------------
// Parameters of the template
// ---------------------------------------------
// A4 size
#let page_width = 210mm
#let page_height = 297mm
#let text_percent = 0.8
#let margin_percent = calc.max(1-text_percent, 0)/2
#let margin_width = margin_percent*page_width
#let margin_height = margin_percent*page_height
#let text_width = text_percent*page_width
#let text_height = text_percent*page_height
// ---------------------------------------------
// Set project
// ---------------------------------------------
#let project(title: "",
authors: (),
watermark_content: content,
footer_left: content,
footer_right: content,
body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
let watermark = rotate(24deg, text(80pt, fill: rgb("E7DCFF"), watermark_content))
let footer = context [
#line(length: 100%, stroke: (paint: blue, thickness: 2pt, cap: "round"))
#footer_left
#h(1fr)
#footer_right
]
set page(numbering: "1",
number-align: center,
margin: (x: margin_width, y: margin_height),
width: page_width,
height: page_height,
background: watermark,
footer: footer
)
set heading(numbering: "1.1.")
set text(font: "New Computer Modern", lang: "en")
show math.equation: set text(weight: 400)
// Title row.
align(center)[
#let stroke = none
#let format_title(x) = text(weight: 700, 1.5em, x)
#grid(
columns: (1fr, 1fr),
// rows: (auto, 60pt),
gutter: 1em,
fill: none,
rect(stroke: stroke, width: 100%)[#align(center)[#format_title(title) \ \ Thời gian: 90p, Mã đề: 003]],
rect(stroke: stroke, width: 100%)[#align(left)[#format_title[*Họ tên:*] \ \ Lớp: ]]
)
]
// Main body.
set par(justify: true)
body
}
// ---------------------------------------------
// Template for displaying one question, choices and solution
// ---------------------------------------------
#let layout_a_question(order, aquestion, show_options, permutation) = [
#let (show_answer, show_solution, show_tags) = (show_options.answer, show_options.solution, show_options.tags)
// 1. Draw a line in show_answer mode
#if show_solution {[#line(length: 100%)]}
// 2. Display stem
#text(blue)[*Câu #order:*] #aquestion.stem // cau hoi in Vietnameses
// 3. Format and display choices
#let formatted_choices = format_choices(aquestion, permutation, correct: show_answer)
#display_choices(formatted_choices, text_width)
// 4. Show answer
#if show_solution [*Lời giải.* #aquestion.solution \ ]
// 4. Show answer
#if show_tags [*Nhãn.* #aquestion.tags \ ]
] // end of layout_a_question()
// ---------------------------------------------
// Template for displaying list of questions
// ---------------------------------------------
#let layout_questions(questions, show_options, permuted_questions, permuted_choices) = {
let (show_answer, show_solution, show_tags) = (show_options.answer, show_options.solution, show_options.tags)
let number_of_questions = questions.len()
v(1em)
for i in range(number_of_questions) {
let permuted_index = permuted_questions.at(i)
layout_a_question(i+1, questions.at(permuted_index), show_options, permuted_choices.at(i))
}
} // end of layout_questions()
|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/params.typ | typst | MIT License | #import "catppuccin.typ": *
#import "lib.typ": *
#import "diff.typ": diffdict
#import "dict.typ": leafmap, leafzip, leafflatten
#import "equation.typ"
#import "seq.typ": fib
#let seeds = (0, 31, 227, 252, 805)
#let na = $N "/" A$
#let syms = (
delta_t: $Delta_t$,
m_r: $M_E$,
m_i: $M_I$,
sigma_d: $sigma_d$,
sigma_p: $sigma_p$,
sigma_r: $sigma_i$,
sigma_o: $sigma_o$,
sigma_t: $sigma_t$,
radius: $C_("radius")$,
r_r: $r_R$,
speed: $abs(v_0)$,
n_r: $N_R$,
s: $s e e d$,
comms-radius: $r_("comms")$,
comms-failure-prob: $gamma$,
variable-temporal-dist: $t_(K-1)$,
lookahead-multiple: $l_m$,
interrobot-safety-distance: $d_r$,
variables: $|V|$,
max-iterations: $N_"RRT"$,
step-size: $s$,
collision-radius: $r_C$,
neighbourhood-radius: $r_N$,
)
// let params = (
#let circle = (
// sim: (
// ),
factor: (
sigma_d: $1m$,
sigma_p: $1 times 10^(-15)m$,
sigma_r: $0.005m$,
sigma_o: $0.005m$,
sigma_t: na,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $50$,
// S_r: $2.2$,
comms-failure-prob: $0%$,
// variable-temporal-dist: {let v = 2 * 50 / 15; $#v$},
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: ${5, 13.33}s^*$, // 2 * 50m / 15m/s
// variables: todo[...],
lookahead-multiple: ${1, 3}^*$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: $50m$,
speed: $15m"/"s$,
n_r: ${5, 10, ..., 50}$,
// s: $2^*$,
s: equation.as-set(seeds),
),
)
#let clear-circle = (
// sim: (
// ),
factor: (
sigma_d: $1m$,
sigma_p: $1 times 10^(-15)m$,
sigma_r: $0.005m$,
sigma_o: $0.005m$,
sigma_t: na,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $50$,
// S_r: $2.2$,
comms-failure-prob: $0%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: $5s^*$, // 2 * 50m / 15m/s
// variables: todo[...],
lookahead-multiple: $3^*$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: $50m$,
speed: $15m"/"s$,
n_r: ${5, 10, ..., 50}$,
// s: $2^*$,
s: equation.as-set(seeds),
),
)
#let varying-network-connectivity = (
factor: (
sigma_d: $1m$,
sigma_p: $1 times 10^(-15)m$,
sigma_r: $0.005m$,
sigma_o: $0.005m$,
sigma_t: na,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $50$,
// S_r: $2.2$,
comms-failure-prob: $0%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: ${5, 13.33}s^*$, // 2 * 50m / 15m/s
// variables: todo[...],
lookahead-multiple: $3^*$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: ${20, 40, ..., 80}m$,
speed: $15m"/"s$,
n_r: $30$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
#let junction = (
// sim: (
// ),
factor: (
sigma_d: $0.5m$,
sigma_p: $1 times 10^(-15)m$,
sigma_r: $0.005m$,
sigma_o: $0.005m$,
sigma_t: na,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $50$,
// S_r: $2.2$,
comms-failure-prob: $0%$,
variable-temporal-dist: $2s$,
// variables: todo[...],
lookahead-multiple: $3^*$,
),
env: (
radius: $N "/" A$,
r_r: $2m$,
comms-radius: $50m$,
speed: $15m"/"s$,
// n_r: na,
n_r: $Q_("in") times 50 s$,
// n_r: ${5, 10, ..., 50}$,
// s: $2^*$,
s: equation.as-set(seeds),
),
)
#let communications-failure = (
// sim: (
// ),
factor: (
sigma_d: $1$,
sigma_p: $1 times 10^(-15)$,
sigma_r: $0.005$,
sigma_o: $0.005$,
sigma_t: na,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $50$,
comms-failure-prob: ${0, 10, ..., 90}%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: ${5, 13.33}s^*$, // 2 * 50m / 15m/s
lookahead-multiple: $3^*$,
// variables: todo[...],
// S_r: $2.2$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: $50m$,
n_r: $21$,
speed: ${10, 15}m"/"s$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
// sigma-pose-fixed = 0.0000000000000010000000036274937
// sigma-factor-dynamics = 0.10000000149011612
// sigma-factor-interrobot = 0.009999999776482582
// sigma-factor-obstacle = 0.009999999776482582
// sigma-factor-tracking = 0.15000000596046448
// lookahead-multiple = 3
#let solo-gp = (
// sim: (
// ),
factor: (
sigma_d: $0.1$,
sigma_p: $1 times 10^(-15)$,
sigma_r: $0.005$,
sigma_o: $0.005$,
sigma_t: $0.15$,
interrobot-safety-distance: $2.2 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $10$,
comms-failure-prob: $0%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: $5s$, // 2 * 50m / 15m/s
lookahead-multiple: $3^*$,
// variables: todo[...],
// S_r: $2.2$,
),
env: (
radius: na,
r_r: $2 m$,
comms-radius: na,
n_r: $1$,
speed: $7m"/"s$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
// [gbp]
// sigma-pose-fixed = 0.0000000000000010000000036274937
// sigma-factor-dynamics = 0.10000000149011612
// sigma-factor-interrobot = 0.009999999776482582
// sigma-factor-obstacle = 0.009999999776482582
// sigma-factor-tracking = 0.5
// lookahead-multiple = 3
// variables = 10
#let collaborative-gp = (
// sim: (
// ),
factor: (
sigma_d: $0.1$,
sigma_p: $1 times 10^(-15)$,
sigma_r: $0.005$,
sigma_o: $0.005$,
sigma_t: ${0.15, 0.5}$,
interrobot-safety-distance: $4 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: $10$,
m_i: $10$,
comms-failure-prob: $0$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: $5s$, // 2 * 50m / 15m/s
lookahead-multiple: $3^*$,
// variables: todo[...],
// S_r: $2.2$,
),
env: (
radius: na,
r_r: $2m$,
comms-radius: $20m$,
n_r: $100$, // 10 * 10
speed: $7m"/"s$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
#let internals = fib(11).slice(2)
#let externals = internals
#let iteration-amount = (
// sim: (
// ),
factor: (
sigma_d: $1$,
sigma_p: $1 times 10^(-15)$,
sigma_r: $0.005$,
sigma_o: $0.005$,
sigma_t: na,
interrobot-safety-distance: $2.5 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: equation.as-set(externals),
m_i: equation.as-set(internals),
comms-failure-prob: $0%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: $5s^*$, // 2 * 50m / 15m/s
lookahead-multiple: $3^*$,
// variables: todo[...],
// S_r: $2.2$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: $50m$,
n_r: $25$,
speed: $10m"/"s$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
#let iteration-schedules = (
// sim: (
// ),
factor: (
sigma_d: $1$,
sigma_p: $1 times 10^(-15)$,
sigma_r: $0.005$,
sigma_o: $0.005$,
sigma_t: na,
interrobot-safety-distance: $2.5 times C_("radius")$,
),
gbp: (
delta_t: $0.1$,
m_r: ${5, 10, 15, 20, 25}$,
m_i: $50$,
comms-failure-prob: $0%$,
// variable-temporal-dist: todo[...],
// variable-temporal-dist: $6.67s^*$, // 2 * 50m / 15m/s
variable-temporal-dist: $7s^*$, // 2 * 50m / 15m/s
lookahead-multiple: $3^*$,
// variables: todo[...],
// S_r: $2.2$,
),
env: (
radius: $50m$,
r_r: $tilde.op cal(U)(2,3) m$,
comms-radius: $50m$,
n_r: $30$,
speed: $10m"/"s$,
// s: ${0, 32, 64, 128, 255}^*$,
s: equation.as-set(seeds),
),
)
// params.tabular(params.communications-failure.env, previous: params.circle.env, title: [Environment]),
// params.tabular(params.communications-failure.gbp, previous: params.circle.gbp, title: [GBP Algorithm], extra-rows: 0),
// params.tabular(params.communications-failure.factor, previous: params.circle.factor, title: [Factor Settings]),
#let make-rows(subdict, previous: none) = {
let diff = if previous == none {
leafmap(subdict, (k, v) => false) } else {
diffdict(previous, subdict)
}
assert(type(diff) == dictionary, message: "expected `diff` to have type 'dictionary', got " + type(diff))
let dict = leafzip(subdict, diff)
let dict_flattened = leafflatten(dict)
for (k, pair) in dict_flattened {
let v = pair.at(0)
let different = pair.at(1)
let k = syms.at(k)
if different {
(k, text(theme.peach, v))
} else {
(k, v)
}
}
// let pair-list = subdict.pairs().filter(it => {
// not type(it.at(1)) == dictionary
// }).map(it => {
// let key = it.at(0)
// let val = it.at(1)
// (syms.at(key), val)
// })
//
// pair-list.flatten()
}
#let tabular(subdict, title: none, extra-rows: 0, previous: none) = {
let header = table.header(
[Param], [Value]
)
let header-rows = (0,)
if header != none {
header-rows = (0, 1)
header = table.header(
table.cell(colspan: 2, align: center, title),
[Param], [Value]
)
}
show table.cell : it => {
if it.y in header-rows {
set text(theme.text)
strong(it)
} else if calc.even(it.y) {
set text(theme.text)
strong(it)
} else {
set text(theme.text)
it
}
}
set align(center)
cut-block(
table(
columns: (1fr, auto),
align: (x, y) => (left, right).at(x) + horizon,
stroke: none,
header,
fill: (x, y) => if y in (0, 1) {
theme.lavender.lighten(50%)
} else if calc.even(y) { theme.crust } else { theme.mantle },
gutter: -1pt,
..make-rows(subdict, previous: previous),
..rep((" ", " "), extra-rows).flatten()
)
)
}
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2018/MS-12.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [<NAME>], [CHN], [3631],
[2], [<NAME>], [CHN], [3558],
[3], [XU Xin], [CHN], [3347],
[4], [LIANG Jingkun], [CHN], [3297],
[5], [<NAME>], [GER], [3274],
[6], [<NAME>], [CHN], [3212],
[7], [<NAME>], [JPN], [3162],
[8], [JANG Woojin], [KOR], [3137],
[9], [#text(gray, "ZHANG Jike")], [CHN], [3104],
[10], [ZHOU Yu], [CHN], [3102],
[11], [KANAMITSU Koyo], [JPN], [3087],
[12], [MIZUTANI Jun], [JPN], [3065],
[13], [PITCHFORD Liam], [ENG], [3062],
[14], [YAN An], [CHN], [3051],
[15], [<NAME>], [SWE], [3025],
[16], [<NAME>], [CHN], [3019],
[17], [FANG Bo], [CHN], [3014],
[18], [SAMSONOV Vladimir], [BLR], [3014],
[19], [<NAME>hiro], [JPN], [2992],
[20], [<NAME>], [TPE], [2989],
[21], [OVTCHAROV Dimitrij], [GER], [2988],
[22], [YU Ziyang], [CHN], [2978],
[23], [<NAME>], [GER], [2977],
[24], [<NAME>], [JPN], [2975],
[25], [<NAME>], [CHN], [2968],
[26], [JEOUNG Youngsik], [KOR], [2959],
[27], [<NAME>], [CHN], [2957],
[28], [<NAME>], [POR], [2956],
[29], [<NAME>], [BRA], [2955],
[30], [LIM Jonghoon], [KOR], [2952],
[31], [UEDA Jin], [JPN], [2933],
[32], [#text(gray, "<NAME>")], [KOR], [2927],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [<NAME> Su], [KOR], [2923],
[34], [PARK Ganghyeon], [KOR], [2920],
[35], [<NAME>], [AUT], [2905],
[36], [<NAME>], [CHN], [2899],
[37], [<NAME>], [GER], [2895],
[38], [<NAME>], [SLO], [2884],
[39], [OSHIMA Yuya], [JPN], [2881],
[40], [<NAME>], [JPN], [2876],
[41], [<NAME>], [JPN], [2868],
[42], [<NAME>], [ROU], [2866],
[43], [<NAME>], [JPN], [2863],
[44], [<NAME>], [SVK], [2862],
[45], [<NAME>], [GER], [2860],
[46], [ZHU Linfeng], [CHN], [2856],
[47], [XU Chenhao], [CHN], [2853],
[48], [#text(gray, "LI Ping")], [QAT], [2840],
[49], [<NAME>], [HKG], [2839],
[50], [<NAME>], [KOR], [2838],
[51], [<NAME>], [SWE], [2835],
[52], [<NAME>], [FRA], [2833],
[53], [<NAME>], [IND], [2824],
[54], [<NAME>], [IRI], [2823],
[55], [CHUANG Chih-Yuan], [TPE], [2820],
[56], [OIKAWA Mizuki], [JPN], [2817],
[57], [<NAME>], [CRO], [2815],
[58], [WANG Yang], [SVK], [2815],
[59], [ARUNA Quadri], [NGR], [2814],
[60], [GNANASEKARAN Sathiyan], [IND], [2813],
[61], [<NAME>], [SWE], [2808],
[62], [<NAME>], [DEN], [2806],
[63], [<NAME>jan], [SLO], [2801],
[64], [<NAME>], [FRA], [2793],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [<NAME>], [GER], [2792],
[66], [<NAME>], [JPN], [2790],
[67], [TAKAKIWA Taku], [JPN], [2787],
[68], [<NAME>], [UKR], [2785],
[69], [<NAME>], [GER], [2783],
[70], [<NAME>], [USA], [2773],
[71], [<NAME>], [CHN], [2771],
[72], [<NAME>], [AUT], [2768],
[73], [SHIBAEV Alexander], [RUS], [2766],
[74], [MURAMATSU Yuto], [JPN], [2761],
[75], [<NAME>], [SWE], [2755],
[76], [TSUBOI Gustavo], [BRA], [2753],
[77], [MA Te], [CHN], [2750],
[78], [AKKUZU Can], [FRA], [2749],
[79], [LUNDQVIST Jens], [SWE], [2748],
[80], [<NAME>], [CAN], [2748],
[81], [<NAME>], [FRA], [2748],
[82], [<NAME>], [SWE], [2744],
[83], [ZHAI Yujia], [DEN], [2743],
[84], [<NAME>], [POL], [2743],
[85], [<NAME>-An], [TPE], [2737],
[86], [<NAME>], [JPN], [2737],
[87], [XUE Fei], [CHN], [2735],
[88], [<NAME>], [POL], [2731],
[89], [QIU Dang], [GER], [2728],
[90], [APOLONIA Tiago], [POR], [2725],
[91], [<NAME>], [KAZ], [2725],
[92], [KIZUKURI Yuto], [JPN], [2723],
[93], [<NAME>], [KOR], [2721],
[94], [<NAME>], [AUT], [2719],
[95], [<NAME>], [DEN], [2714],
[96], [<NAME>], [BEL], [2708],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [STOYANOV Niagol], [ITA], [2707],
[98], [<NAME>], [SWE], [2706],
[99], [CHIANG Hung-Chieh], [TPE], [2705],
[100], [HWANG Minha], [KOR], [2705],
[101], [DESAI Harmeet], [IND], [2704],
[102], [<NAME>], [FIN], [2703],
[103], [GIONIS Panagiotis], [GRE], [2701],
[104], [<NAME>], [JPN], [2700],
[105], [<NAME>], [JPN], [2696],
[106], [<NAME>], [SWE], [2695],
[107], [<NAME>], [EGY], [2691],
[108], [<NAME>], [HKG], [2689],
[109], [SKACHKOV Kirill], [RUS], [2688],
[110], [#text(gray, "<NAME>")], [PRK], [2688],
[111], [<NAME>], [POL], [2686],
[112], [HIRANO Yuki], [JPN], [2685],
[113], [#text(gray, "<NAME>")], [FRA], [2683],
[114], [KIM Minhyeok], [KOR], [2682],
[115], [<NAME>], [ESP], [2682],
[116], [<NAME>], [KOR], [2679],
[117], [<NAME>], [CRO], [2679],
[118], [TOGAMI Shunsuke], [JPN], [2678],
[119], [<NAME>], [JPN], [2676],
[120], [OUAICHE Stephane], [ALG], [2675],
[121], [JIANG Tianyi], [HKG], [2672],
[122], [ZHMUDENKO Yaroslav], [UKR], [2671],
[123], [MATSUDAIRA Kenji], [JPN], [2668],
[124], [KIM Minseok], [KOR], [2664],
[125], [#text(gray, "GAO Ning")], [SGP], [2663],
[126], [MONTEIRO Joao], [POR], [2659],
[127], [<NAME>], [CHN], [2658],
[128], [LIAO Cheng-Ting], [TPE], [2656],
)
) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-rtl_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set text(dir: rtl)
#table(columns: 2)[A][B][C][D]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1B000.typ | typst | Apache License 2.0 | #let data = (
("KATAKANA LETTER ARCHAIC E", "Lo", 0),
("HIRAGANA LETTER ARCHAIC YE", "Lo", 0),
("HENTAIGANA LETTER A-1", "Lo", 0),
("HENTAIGANA LETTER A-2", "Lo", 0),
("HENTAIGANA LETTER A-3", "Lo", 0),
("HENTAIGANA LETTER A-WO", "Lo", 0),
("HENTAIGANA LETTER I-1", "Lo", 0),
("HENTAIGANA LETTER I-2", "Lo", 0),
("HENTAIGANA LETTER I-3", "Lo", 0),
("HENTAIGANA LETTER I-4", "Lo", 0),
("HENTAIGANA LETTER U-1", "Lo", 0),
("HENTAIGANA LETTER U-2", "Lo", 0),
("HENTAIGANA LETTER U-3", "Lo", 0),
("HENTAIGANA LETTER U-4", "Lo", 0),
("HENTAIGANA LETTER U-5", "Lo", 0),
("HENTAIGANA LETTER E-2", "Lo", 0),
("HENTAIGANA LETTER E-3", "Lo", 0),
("HENTAIGANA LETTER E-4", "Lo", 0),
("HENTAIGANA LETTER E-5", "Lo", 0),
("HENTAIGANA LETTER E-6", "Lo", 0),
("HENTAIGANA LETTER O-1", "Lo", 0),
("HENTAIGANA LETTER O-2", "Lo", 0),
("HENTAIGANA LETTER O-3", "Lo", 0),
("HENTAIGANA LETTER KA-1", "Lo", 0),
("HENTAIGANA LETTER KA-2", "Lo", 0),
("HENTAIGANA LETTER KA-3", "Lo", 0),
("HENTAIGANA LETTER KA-4", "Lo", 0),
("HENTAIGANA LETTER KA-5", "Lo", 0),
("HENTAIGANA LETTER KA-6", "Lo", 0),
("HENTAIGANA LETTER KA-7", "Lo", 0),
("HENTAIGANA LETTER KA-8", "Lo", 0),
("HENTAIGANA LETTER KA-9", "Lo", 0),
("HENTAIGANA LETTER KA-10", "Lo", 0),
("HENTAIGANA LETTER KA-11", "Lo", 0),
("HENTAIGANA LETTER KA-KE", "Lo", 0),
("HENTAIGANA LETTER KI-1", "Lo", 0),
("HENTAIGANA LETTER KI-2", "Lo", 0),
("HENTAIGANA LETTER KI-3", "Lo", 0),
("HENTAIGANA LETTER KI-4", "Lo", 0),
("HENTAIGANA LETTER KI-5", "Lo", 0),
("HENTAIGANA LETTER KI-6", "Lo", 0),
("HENTAIGANA LETTER KI-7", "Lo", 0),
("HENTAIGANA LETTER KI-8", "Lo", 0),
("HENTAIGANA LETTER KU-1", "Lo", 0),
("HENTAIGANA LETTER KU-2", "Lo", 0),
("HENTAIGANA LETTER KU-3", "Lo", 0),
("HENTAIGANA LETTER KU-4", "Lo", 0),
("HENTAIGANA LETTER KU-5", "Lo", 0),
("HENTAIGANA LETTER KU-6", "Lo", 0),
("HENTAIGANA LETTER KU-7", "Lo", 0),
("HENTAIGANA LETTER KE-1", "Lo", 0),
("HENTAIGANA LETTER KE-2", "Lo", 0),
("HENTAIGANA LETTER KE-3", "Lo", 0),
("HENTAIGANA LETTER KE-4", "Lo", 0),
("HENTAIGANA LETTER KE-5", "Lo", 0),
("HENTAIGANA LETTER KE-6", "Lo", 0),
("HENTAIGANA LETTER KO-1", "Lo", 0),
("HENTAIGANA LETTER KO-2", "Lo", 0),
("HENTAIGANA LETTER KO-3", "Lo", 0),
("HENTAIGANA LETTER KO-KI", "Lo", 0),
("HENTAIGANA LETTER SA-1", "Lo", 0),
("HENTAIGANA LETTER SA-2", "Lo", 0),
("HENTAIGANA LETTER SA-3", "Lo", 0),
("HENTAIGANA LETTER SA-4", "Lo", 0),
("HENTAIGANA LETTER SA-5", "Lo", 0),
("HENTAIGANA LETTER SA-6", "Lo", 0),
("HENTAIGANA LETTER SA-7", "Lo", 0),
("HENTAIGANA LETTER SA-8", "Lo", 0),
("HENTAIGANA LETTER SI-1", "Lo", 0),
("HENTAIGANA LETTER SI-2", "Lo", 0),
("HENTAIGANA LETTER SI-3", "Lo", 0),
("HENTAIGANA LETTER SI-4", "Lo", 0),
("HENTAIGANA LETTER SI-5", "Lo", 0),
("HENTAIGANA LETTER SI-6", "Lo", 0),
("HENTAIGANA LETTER SU-1", "Lo", 0),
("HENTAIGANA LETTER SU-2", "Lo", 0),
("HENTAIGANA LETTER SU-3", "Lo", 0),
("HENTAIGANA LETTER SU-4", "Lo", 0),
("HENTAIGANA LETTER SU-5", "Lo", 0),
("HENTAIGANA LETTER SU-6", "Lo", 0),
("HENTAIGANA LETTER SU-7", "Lo", 0),
("HENTAIGANA LETTER SU-8", "Lo", 0),
("HENTAIGANA LETTER SE-1", "Lo", 0),
("HENTAIGANA LETTER SE-2", "Lo", 0),
("HENTAIGANA LETTER SE-3", "Lo", 0),
("HENTAIGANA LETTER SE-4", "Lo", 0),
("HENTAIGANA LETTER SE-5", "Lo", 0),
("HENTAIGANA LETTER SO-1", "Lo", 0),
("HENTAIGANA LETTER SO-2", "Lo", 0),
("HENTAIGANA LETTER SO-3", "Lo", 0),
("HENTAIGANA LETTER SO-4", "Lo", 0),
("HENTAIGANA LETTER SO-5", "Lo", 0),
("HENTAIGANA LETTER SO-6", "Lo", 0),
("HENTAIGANA LETTER SO-7", "Lo", 0),
("HENTAIGANA LETTER TA-1", "Lo", 0),
("HENTAIGANA LETTER TA-2", "Lo", 0),
("HENTAIGANA LETTER TA-3", "Lo", 0),
("HENTAIGANA LETTER TA-4", "Lo", 0),
("HENTAIGANA LETTER TI-1", "Lo", 0),
("HENTAIGANA LETTER TI-2", "Lo", 0),
("HENTAIGANA LETTER TI-3", "Lo", 0),
("HENTAIGANA LETTER TI-4", "Lo", 0),
("HENTAIGANA LETTER TI-5", "Lo", 0),
("HENTAIGANA LETTER TI-6", "Lo", 0),
("HENTAIGANA LETTER TI-7", "Lo", 0),
("HENTAIGANA LETTER TU-1", "Lo", 0),
("HENTAIGANA LETTER TU-2", "Lo", 0),
("HENTAIGANA LETTER TU-3", "Lo", 0),
("HENTAIGANA LETTER TU-4", "Lo", 0),
("HENTAIGANA LETTER TU-TO", "Lo", 0),
("HENTAIGANA LETTER TE-1", "Lo", 0),
("HENTAIGANA LETTER TE-2", "Lo", 0),
("HENTAIGANA LETTER TE-3", "Lo", 0),
("HENTAIGANA LETTER TE-4", "Lo", 0),
("HENTAIGANA LETTER TE-5", "Lo", 0),
("HENTAIGANA LETTER TE-6", "Lo", 0),
("HENTAIGANA LETTER TE-7", "Lo", 0),
("HENTAIGANA LETTER TE-8", "Lo", 0),
("HENTAIGANA LETTER TE-9", "Lo", 0),
("HENTAIGANA LETTER TO-1", "Lo", 0),
("HENTAIGANA LETTER TO-2", "Lo", 0),
("HENTAIGANA LETTER TO-3", "Lo", 0),
("HENTAIGANA LETTER TO-4", "Lo", 0),
("HENTAIGANA LETTER TO-5", "Lo", 0),
("HENTAIGANA LETTER TO-6", "Lo", 0),
("HENTAIGANA LETTER TO-RA", "Lo", 0),
("HENTAIGANA LETTER NA-1", "Lo", 0),
("HENTAIGANA LETTER NA-2", "Lo", 0),
("HENTAIGANA LETTER NA-3", "Lo", 0),
("HENTAIGANA LETTER NA-4", "Lo", 0),
("HENTAIGANA LETTER NA-5", "Lo", 0),
("HENTAIGANA LETTER NA-6", "Lo", 0),
("HENTAIGANA LETTER NA-7", "Lo", 0),
("HENTAIGANA LETTER NA-8", "Lo", 0),
("HENTAIGANA LETTER NA-9", "Lo", 0),
("HENTAIGANA LETTER NI-1", "Lo", 0),
("HENTAIGANA LETTER NI-2", "Lo", 0),
("HENTAIGANA LETTER NI-3", "Lo", 0),
("HENTAIGANA LETTER NI-4", "Lo", 0),
("HENTAIGANA LETTER NI-5", "Lo", 0),
("HENTAIGANA LETTER NI-6", "Lo", 0),
("HENTAIGANA LETTER NI-7", "Lo", 0),
("HENTAIGANA LETTER NI-TE", "Lo", 0),
("HENTAIGANA LETTER NU-1", "Lo", 0),
("HENTAIGANA LETTER NU-2", "Lo", 0),
("HENTAIGANA LETTER NU-3", "Lo", 0),
("HENTAIGANA LETTER NE-1", "Lo", 0),
("HENTAIGANA LETTER NE-2", "Lo", 0),
("HENTAIGANA LETTER NE-3", "Lo", 0),
("HENTAIGANA LETTER NE-4", "Lo", 0),
("HENTAIGANA LETTER NE-5", "Lo", 0),
("HENTAIGANA LETTER NE-6", "Lo", 0),
("HENTAIGANA LETTER NE-KO", "Lo", 0),
("HENTAIGANA LETTER NO-1", "Lo", 0),
("HENTAIGANA LETTER NO-2", "Lo", 0),
("HENTAIGANA LETTER NO-3", "Lo", 0),
("HENTAIGANA LETTER NO-4", "Lo", 0),
("HENTAIGANA LETTER NO-5", "Lo", 0),
("HENTAIGANA LETTER HA-1", "Lo", 0),
("HENTAIGANA LETTER HA-2", "Lo", 0),
("HENTAIGANA LETTER HA-3", "Lo", 0),
("HENTAIGANA LETTER HA-4", "Lo", 0),
("HENTAIGANA LETTER HA-5", "Lo", 0),
("HENTAIGANA LETTER HA-6", "Lo", 0),
("HENTAIGANA LETTER HA-7", "Lo", 0),
("HENTAIGANA LETTER HA-8", "Lo", 0),
("HENTAIGANA LETTER HA-9", "Lo", 0),
("HENTAIGANA LETTER HA-10", "Lo", 0),
("HENTAIGANA LETTER HA-11", "Lo", 0),
("HENTAIGANA LETTER HI-1", "Lo", 0),
("HENTAIGANA LETTER HI-2", "Lo", 0),
("HENTAIGANA LETTER HI-3", "Lo", 0),
("HENTAIGANA LETTER HI-4", "Lo", 0),
("HENTAIGANA LETTER HI-5", "Lo", 0),
("HENTAIGANA LETTER HI-6", "Lo", 0),
("HENTAIGANA LETTER HI-7", "Lo", 0),
("HENTAIGANA LETTER HU-1", "Lo", 0),
("HENTAIGANA LETTER HU-2", "Lo", 0),
("HENTAIGANA LETTER HU-3", "Lo", 0),
("HENTAIGANA LETTER HE-1", "Lo", 0),
("HENTAIGANA LETTER HE-2", "Lo", 0),
("HENTAIGANA LETTER HE-3", "Lo", 0),
("HENTAIGANA LETTER HE-4", "Lo", 0),
("HENTAIGANA LETTER HE-5", "Lo", 0),
("HENTAIGANA LETTER HE-6", "Lo", 0),
("HENTAIGANA LETTER HE-7", "Lo", 0),
("HENTAIGANA LETTER HO-1", "Lo", 0),
("HENTAIGANA LETTER HO-2", "Lo", 0),
("HENTAIGANA LETTER HO-3", "Lo", 0),
("HENTAIGANA LETTER HO-4", "Lo", 0),
("HENTAIGANA LETTER HO-5", "Lo", 0),
("HENTAIGANA LETTER HO-6", "Lo", 0),
("HENTAIGANA LETTER HO-7", "Lo", 0),
("HENTAIGANA LETTER HO-8", "Lo", 0),
("HENTAIGANA LETTER MA-1", "Lo", 0),
("HENTAIGANA LETTER MA-2", "Lo", 0),
("HENTAIGANA LETTER MA-3", "Lo", 0),
("HENTAIGANA LETTER MA-4", "Lo", 0),
("HENTAIGANA LETTER MA-5", "Lo", 0),
("HENTAIGANA LETTER MA-6", "Lo", 0),
("HENTAIGANA LETTER MA-7", "Lo", 0),
("HENTAIGANA LETTER MI-1", "Lo", 0),
("HENTAIGANA LETTER MI-2", "Lo", 0),
("HENTAIGANA LETTER MI-3", "Lo", 0),
("HENTAIGANA LETTER MI-4", "Lo", 0),
("HENTAIGANA LETTER MI-5", "Lo", 0),
("HENTAIGANA LETTER MI-6", "Lo", 0),
("HENTAIGANA LETTER MI-7", "Lo", 0),
("HENTAIGANA LETTER MU-1", "Lo", 0),
("HENTAIGANA LETTER MU-2", "Lo", 0),
("HENTAIGANA LETTER MU-3", "Lo", 0),
("HENTAIGANA LETTER MU-4", "Lo", 0),
("HENTAIGANA LETTER ME-1", "Lo", 0),
("HENTAIGANA LETTER ME-2", "Lo", 0),
("HENTAIGANA LETTER ME-MA", "Lo", 0),
("HENTAIGANA LETTER MO-1", "Lo", 0),
("HENTAIGANA LETTER MO-2", "Lo", 0),
("HENTAIGANA LETTER MO-3", "Lo", 0),
("HENTAIGANA LETTER MO-4", "Lo", 0),
("HENTAIGANA LETTER MO-5", "Lo", 0),
("HENTAIGANA LETTER MO-6", "Lo", 0),
("HENTAIGANA LETTER YA-1", "Lo", 0),
("HENTAIGANA LETTER YA-2", "Lo", 0),
("HENTAIGANA LETTER YA-3", "Lo", 0),
("HENTAIGANA LETTER YA-4", "Lo", 0),
("HENTAIGANA LETTER YA-5", "Lo", 0),
("HENTAIGANA LETTER YA-YO", "Lo", 0),
("HENTAIGANA LETTER YU-1", "Lo", 0),
("HENTAIGANA LETTER YU-2", "Lo", 0),
("HENTAIGANA LETTER YU-3", "Lo", 0),
("HENTAIGANA LETTER YU-4", "Lo", 0),
("HENTAIGANA LETTER YO-1", "Lo", 0),
("HENTAIGANA LETTER YO-2", "Lo", 0),
("HENTAIGANA LETTER YO-3", "Lo", 0),
("HENTAIGANA LETTER YO-4", "Lo", 0),
("HENTAIGANA LETTER YO-5", "Lo", 0),
("HENTAIGANA LETTER YO-6", "Lo", 0),
("HENTAIGANA LETTER RA-1", "Lo", 0),
("HENTAIGANA LETTER RA-2", "Lo", 0),
("HENTAIGANA LETTER RA-3", "Lo", 0),
("HENTAIGANA LETTER RA-4", "Lo", 0),
("HENTAIGANA LETTER RI-1", "Lo", 0),
("HENTAIGANA LETTER RI-2", "Lo", 0),
("HENTAIGANA LETTER RI-3", "Lo", 0),
("HENTAIGANA LETTER RI-4", "Lo", 0),
("HENTAIGANA LETTER RI-5", "Lo", 0),
("HENTAIGANA LETTER RI-6", "Lo", 0),
("HENTAIGANA LETTER RI-7", "Lo", 0),
("HENTAIGANA LETTER RU-1", "Lo", 0),
("HENTAIGANA LETTER RU-2", "Lo", 0),
("HENTAIGANA LETTER RU-3", "Lo", 0),
("HENTAIGANA LETTER RU-4", "Lo", 0),
("HENTAIGANA LETTER RU-5", "Lo", 0),
("HENTAIGANA LETTER RU-6", "Lo", 0),
("HENTAIGANA LETTER RE-1", "Lo", 0),
("HENTAIGANA LETTER RE-2", "Lo", 0),
)
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/dialogue.typ | typst | #import "@local/typkit:0.1.0": *
#import "meta-content-layouts/simple.typ": simple-meta-layout
// #import "meta-content-layouts/extended.typ": extended-meta-content
// TODO
#let dialogue-layout(dialogue-items, body-width: auto, row-gutter: 15pt, spacing: 0.8em) = {
set table.cell(breakable: false)
set block(breakable: false)
show par: set block(spacing: spacing )
table(
column-gutter: 10pt,
columns: (auto, body-width),
stroke: none,
row-gutter: row-gutter,
..dialogue-items,
)
}
#let dialogue(dialogue, metadata) = {
// can pass in sys.inputs (for version 0.11.0)
let inputs = sys.inputs
let margin = (top: 1in, left: 1in, right: 1in, bottom: 0.85in)
set page(footer: {
counter(page).display(number => {
let num = sm-text(number)
let mark = [— #num —]
centered(mark)
})
},
paper: "us-letter", margin: (top: 1in, left: 1in, right: 1in, bottom: 0.85in)
)
let row-gutter = resolve-pt(metadata.at("spacing", default: 15pt))
simple-meta-layout(metadata)
dialogue-layout(dialogue, row-gutter: row-gutter)
}
|
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/main/i21/tri.typ | typst | = Algos de tri
3 types d'algos de tri:
- tri par selection
- tri par propagation
- tri par insertion
tout les algorithmes reposent sur une méthode d'echange d'items basé sur leurs indice:
```python
def swap(T, i, j):
a = T[i]
T[i] = T[j]
T[j] = a
```
== tri par selection
bien que simple, l'algorithme est considere comme inefficace a cause de son temps d'execution quadratique
$ Omega(n) = n^2 \
O(n) = n^2 \
Theta(n) = n^2 \
$
il consiste a parcourir une liste, et echanger le plus petit element par le premier,
puis d'avencer l'indice du premier jusqu'a finir de parcourir la liste
```
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j], A[j-1]
j ← j - 1
end while
i ← i + 1
end while
```
== tri par propagation (Bubble sort)
il a une complexite de $n^2$, sauf pour le meilleur cas, ou $Omega(n) = n$
il consiste a echanger les elements qui sont dans le désordre ($n+1< n$), a la fin de chaque iteration, le dernier element est le plus grand, donc l'indice est soustre a chaque fois
```
tri_à_bulles(Tableau T)
pour i allant de (taille de T)-1 à 1
pour j allant de 0 à i-1
si T[j+1] < T[j]
(T[j+1], T[j]) ← (T[j], T[j+1])
```
== tri par insertion
il parcours la liste, et a chaque fois que l'algo trouve un nombre inferieur au precedent, il revient en arriere pour le placer correctement
```
procédure tri_insertion(tableau T)
pour i de 1 à taille(T) - 1
# mémoriser T[i] dans x
x ← T[i]
# décaler les éléments T[0]..T[i-1] qui sont plus grands que x, en partant de T[i-1]
j ← i
tant que j > 0 et T[j - 1] > x
T[j] ← T[j - 1]
j ← j - 1
# placer x dans le "trou" laissé par le décalage
T[j] ← x
```
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/exponent/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
#num(e: [10])[1]
#num(e: 10)[1]
#num(1, e: 10)
#num(1, e: [10])
$num(1, e: 10)$ |
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/penreport.typ | typst | MIT No Attribution | #import "@preview/chic-hdr:0.3.0": *
#import "./helper/tlp.typ": ShowTLP, TLP
#import "./helper/vuln.typ": vuln
#import "./helper/severity.typ": Severity
#import "./helper/author.typ": getAuthorString
#import "../intro.typ": intro
#let penreport(
title: "",
subtitle: "Penetration Test Report #1",
id: none,
date: datetime.today(),
versions: (),
targets: (),
client: "",
sharing: none,
authors: (),
font: "Open Sans",
numbering: "1.1",
draft: false,
body
) = [
/* General Config */
#set document(
title: title + " - " + subtitle,
author: getAuthorString(authors, false)
)
#set page(
foreground: [
#if draft [
#set align(center)
#set text(
size: 100pt,
fill: rgb(100%, 0, 0, 25%)
)
#rotate(-45deg)[
DRAFT
]
]
]
)
#set text(font: "Open Sans")
#set heading(numbering: numbering)
#set list(marker: ([•], [--]))
#show heading.where(level: 1): it => {
pagebreak(weak: true)
it
}
#show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
strong(it)
}
/* Header + Footer Config */
#show: chic.with(
chic-header(
left-side: none,
center-side: none,
right-side: ShowTLP(sharing),
),
chic-footer(
left-side: strong(
text(title)
) + text("\n" + subtitle, size: 9pt),
center-side: [Page #chic-page-number() of #locate(loc => counter(page).final(loc).at(0))],
right-side: ShowTLP(sharing),
),
chic-separator(1pt, on: "footer"),
chic-offset(7pt),
chic-height(1.75cm)
)
#intro(
title: title,
subtitle: subtitle,
date: date,
versions: versions,
targets: targets,
client: client,
authors: authors,
)
#body
]
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/计算机组成与设计/Memory.typ | typst | ---
order: 5
---
#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(4)
= Memory
#info(caption: "Contents of Chapter 5")[
+ Introduction
+ Memory Technology
+ The basics of Cache
+ Measuring and improving cache performance
+ Virtual Memory
]
== Introduction
- Locality
- 时间局部性(大概$95%$),空间局部性(大概$80%$)
- Memory Hierarchy
- 所有数据存储在 disk 上
- copy recently used data to DRAM (main memory)
- copy more recently used data to SRAM (cache)
- hit, hit time, miss, miss penalty 等指标
- 我们将讨论 cache(SRAM and DRAM) 和 virtual memory(DRAM and DISK)
#fig("/public/assets/Courses/计组/img-2024-05-13-09-20-54.png")
== Memory Technology
- SRAM technology
- DRAM technology
- DDR, QDR(根据 data rate 分类)
- Row buffer
- DRAM banking
- Flash Storage
- 种类:NAND, NOR
- 读写损耗,remap 技术
- Disk storage
- disk sectors and access
#fig("/public/assets/Courses/计组/img-2024-05-13-09-04-11.png")
== The basics of Cache
- 可以将 cache 内容分门别类(建立 map),这样,在 cache 中寻找数据的时间(hit time)就缩短了;但同时,如果这一类别的位置满了,需要替换(这又减小了 hit 的概率);最后,还需要考虑写数据的操作,如果只更改 cache 中的数据而不改 main memory,会发生 inconsistency,否则,如果两个都改,速度会变慢。
- main issues
+ 数据怎么放
+ 找数据怎么找
+ cache 满了怎么替换
+ 写操作策略
- direct mapped
- 内存的每个地址固定映射到 cache 的某个位置(可能跟其他地址共享)
#fig("/public/assets/Courses/计组/img-2024-05-13-09-29-36.png")
- 给定内存中的地址,根据映射直接可以知道它在 cache 中的位置,但还需要知道 tag 才能确定是否命中
- 把内存中地址高位作为 tag
- 还有 valid bit 来标识这个位置是否有数据
- 块内偏移量不作为 block address 寻址的一部分,block address 包含 valid bit 和 tag
- 下面的例子中,Cache 一共要存 16KB 的数据,每个块为 4 word,那么一共需要 $2^10$ 个 Cache 块,index bit 需要 10 bits
- address 一共 64 bit,块内偏移量为 4 bit(4 word per block),再减去 10 bits 的 index,剩下 50 bits 作为 tag
- 一共 $2^10$ 个 Cache block,每个需要 128 存储数据,$50+1$ 存储 valid bit 和 tag
#grid(columns: 2,
fig("/public/assets/Courses/计组/img-2024-05-15-10-09-10.png"),
fig("/public/assets/Courses/计组/img-2024-05-15-10-26-58.png")
)
- 缺失率与块大小的关系
- 块太小,一次搬过来的数据太少,会导致更多的缺失
- 块太大,搬来的数据不一定全都是有用的,可能就其中某一段有用,导致 cache 能容纳的块数就少,也会导致更多的缺失
- 因此是一个 trade-off
#fig("/public/assets/Courses/计组/img-2024-05-15-11-05-29.png")
- Handling Cache reads hit and Misses
- 对读操作,比较简单,当遇到 miss 时,需要 Control_Stall CPU
- 对写操作,更复杂,对 hit 和 miss 各有两种策略
- write hits
+ write-back: 写 cache,等到替换时再写 main memory (cause inconsistency)
- keep track of dirty bit
+ write-through: 写 cache 同时写 main memory
- 解决方法,先写到 buffer,但总归还是会慢(当然 write-back 也可以有 buffer)
- write misses
+ write-allocate: 先读 cache,再写,write-back 一般会 allocate
+ no-write-allocate: 直接写 main memory
- 是否 allocate 会影响后续的 miss rate
#fig("/public/assets/Courses/计组/img-2024-05-15-11-00-29.png")
- Intrinsity FastMATH
- 通过 address 找 cache 中数据的路线图,这里 address 细化到 byte(我们实验中 lhw, lb 就是细化到 byte)
#fig("/public/assets/Courses/计组/img-2024-05-15-11-18-28.png")
- Memory 组织方式的影响:wide memory(more words per block) and banks
#fig("/public/assets/Courses/计组/img-2024-05-15-11-25-17.png")
- 原本的方式
- $1$ 个 cycle 发送地址;$15$ 个 cycles 寻找到数据;$1$ 个 cycle 发送一个 word 数据
- $17$ 的计算可以不看,是单个 word 的情况
- $65$ 的计算,$1$ 发送地址,随后等待总线准备好 $1$ 个 block $4$ 个 word 的数据,一共 $4 times (15+1)$
- 最后带宽为 $4$ 个 clock $1$ 个 word
#fig("/public/assets/Courses/计组/img-2024-05-15-11-31-11.png")
- 使用宽 block 的方式
- $1$ 个 block $4$ 个 word 的数据只用两次或一次查找
#fig("/public/assets/Courses/计组/img-2024-05-15-11-31-25.png")
- 但是这要求 BUS 和 Cache 的宽度与之相同,实际情况总线做不到太宽,我们可以用 bank 的方式来解决
- 使用 bank 组织方式
- 最好将同一块内的数据分散到不同的 bank,提高并行度
#fig("/public/assets/Courses/计组/img-2024-05-15-11-31-52.png")
== Measuring and improving cache performance
- 涉及很多公式运算,直接看 PPT
- Summary
- 考虑 stalk 的诸多 CPU Time 计算
- 即使 CPU 实现得更好(CPI 从 2 到 1),提高的性能并不会有一倍那样大的提升
- 即使时钟频率快一倍,最后提高的性能因为 memory 而产生的 stall 也不会有一倍那样大的提升
- Can’t neglect cache behavior when evaluating system performance
=== flexible replacement of blocks
- The disadvantage of a direct-mapped cache $=>$ set-associative, fully-associative(组相连、全相连)
- 实际上三种相连方式就是一个 set 内 block 数量的极端和中间态
- 之前是一个 cache 块对应多个 memory 块,现在是多个 cache 块对应多个 memory 块
#fig("/public/assets/Courses/计组/img-2024-05-15-11-55-32.png")
- The basics of a set-associative cache
- 简单看一下它的效果
#grid(columns: 2,
fig("/public/assets/Courses/计组/img-2024-05-15-12-02-35.png"),
fig("/public/assets/Courses/计组/img-2024-05-15-12-03-22.png")
)
- 在 SPEC2000 指令数据集上测试结果显示,2 路组相连提升很多,再多下去并不明显
- set-associative 的查找方式
- 每个 index 对应一个 set,每个 set 有多个 cache block
#fig("/public/assets/Courses/计组/img-2024-05-30-15-32-28.png")
- 组相连 Cache 的计算
- PPT 66 \~ 67
- Replacement Policy
- Direct mapped,没有选择,只能替换
- Set associative,在 set 内优先选择 non-valid entry,否则根据某种策略替换
- LRU,Simple for 2-way, manageable for 4-way, too hard beyond that
- 需要加一位 reference bit
- Random,在 high-Associativity 时性能与 LRU 相当
=== Decreasing miss penalty with multilevel caches
- PPT 69 \~ 70,一个直观的增加 L-2 Cache 的效果的例子
=== Interactions with Advanced CPUs
- 使用 out-of-order CPUs,即使 miss 发生,也能继续乱序执行一些不需要 access main memory 的指令
- 其性能分析更加复杂,一般使用 simulations
=== Interactions with Software
- 程序的指令编排跟 CPU 性能也有关系
- 例子:排序算法、通用矩阵乘法
#hline()
- 总结,影响 cache 命中率的硬件因素主要有以下四点:
- Cache 的容量。
- Cache 与主存储器交换信息的单位量(cache line size)。
- Cache 的组织方式
- Cache 的替换算法
- 总结,影响总 CPI 的因素
- Cache Size
- Block Size
- Associativity
- multilevel caches
- Main memory access time(use banking)
- 指令种类、数量和顺序(软件)
== Dependable Memory Hierarchy
- Reliability: mean time to failure (MTTF)
- Service interruption: mean time to repair (MTTR)
- Mean time between failures: MTBF = MTTF + MTTR
- Availability = MTTF / (MTTF + MTTR)
== Virtual Machines
- Virtual Machine Monitor(VMM)
== Virtual Memory
- 把 main memory 当做 disk storage 的 "cache"
- 之前的 "block" 现在叫 "page"
- 之前的 "miss" 现在叫 "page fault"
- 主要有两个动机
- 不同程序之间共享主存且进行保护,每个程序得到自己的虚拟地址空间
- “扩展”主存的大小,减轻程序员为了适应主存大小分割程序的负担(现在没那么必要)
- 通过地址转换实现
#fig("/public/assets/Courses/计组/img-2024-05-20-08-55-56.png")
- Page faults
- huge miss penalty, thus pages should be fairly *large* (e.g., 4KB)
- reducing page faults is important (*LRU* is worth the price)
- can handle the faults *in software* instead of hardware
- using write-through is too expensive so we use *write back*
- Page Tables(PT,页表)
- 采用全相连策略(miss 的代价远大于在主存中查询的代价)
#fig("/public/assets/Courses/计组/img-2024-05-20-09-10-58.png")
- 每当 OS 创建一个进程,就会创建一个页表,这个页表会被存储在主存中(但由于页表非常大,朴素实现肯定是无法接受的,有一些技术来减小,比如多级页表,不作要求)
- Making Address Translation Fast(TLB,快表)
- 把页表的常用部分搬到 Cache 中,Translation Look-aside Buffer (TLB)
#fig("/public/assets/Courses/计组/img-2024-06-01-13-22-21.png")
- 有点像是为页表建立一个 cache
- 快表 miss 后去页表中查找,有两次机会
#fig("/public/assets/Courses/计组/img-2024-05-20-09-33-58.png")
- 流程图
- 发生 TLB miss exception 后,从 main memory 查找 PT 并 load 到 TLB 中,得到物理地址,之后跟 TLB hit 一样
#fig("/public/assets/Courses/计组/img-2024-05-22-10-08-20.png")
- 三种数据结构的 miss 和 hit
#tbl_white(
columns: 4,
fill: (x,y) => if y == 0 {rgb(0, 144, 227)},
[TLB],[PT],[Cache],[Possible? If so, under what circumstance?],
[hit],[hit],[miss],[Possible, although the page table is never really checked if TLB hits.],
[miss],[hit],[hit],[TLB misses, but entry found in page table;after retry, data is found in cache.],
[miss],[hit],[miss],[TLB misses, but entry found in page table;after retry, data misses in cache.],
[miss],[miss],[miss],[TLB misses and is followed by a page fault;after retry, data must miss in cache.],
[hit],[miss],[miss],[Impossible: cannot have a translation in TLB if page is not present in memory.],
[hit],[miss],[hit],[Impossible: cannot have a translation in TLB if page is not present in memory.],
[miss],[miss],[hit],[Impossible: data cannot be allowed in cache if the page is not in memory.],
)
- Memory Protection
- 不同进程可以共享它们的虚拟地址空间,但需要额外的位标记保护
- 硬件上为 OS 的保护提供支持
== The Memory Hierarchy
- There are Four Questions for Memory Hierarchy Designers
+ Q1: Where can a block be placed in the upper level? (Block placement)
- Fully Associative, Set Associative, Direct Mapped
+ Q2: How is a block found if it is in the upper level? (Block identification)
- Tag/Block
+ Q3: Which block should be replaced on a miss? (Block replacement)
- Random, LRU,FIFO
+ Q4: What happens on a write? (Write strategy)
- Hit: Write Back or Write Through (with Write Buffer)
- Miss: Write Allocate or No-Write Allocate
- 这里是做个复习
- 3C 模型(把 misses 分类)
- Compulsory Misses(强制失效,冷启动失效): 第一次访问 block 时的 miss
- Capacity Misses(容量失效): cache 太小导致把一个 block 替换后又要用到
- Conflict Misses(冲突失效,碰撞失效): non-fully mapped cache 中的 miss,多个 block 竞争同一个组导致的 miss
- 三个失效的改善方法分别是:调整 block 大小(并非越高越好)、增加 cache 大小、增加组相连度(并非越高越好)
== 使用 FSM 实现简单的 Cache
- write back & write allocate
- 略
|
|
https://github.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement | https://raw.githubusercontent.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement/main/TP/TP0-Introduction.typ | typst | #import "../TD_TP_Commons.typ": *
== R1.01 - Introduction
=== Avant de commencer chaque séance TP
+ Ouvrez un terminal et créez un dossier dans votre espace (disque H).
+ Placez vous dans le dossier et créez un dossier TP\<_num. du TP_\>.
+ Travaillez dans le dossier TP\<_num. du TP_\>.
+ Oubliez les accents dans le langage Typ.
=== Pendant chaque séance de TP
Durant votre travail, à chaque apparition d'une indication de type
#fix[_un message_]
commitez et pushez sur Github votre projet mis à jour avec comme message de commit "fix _un message_".
=== B-A BA Git
Pour utiliser Git, la configuration de votre identité Git doit être opérante.
Si ce n'est pas le cas, voici un rappel des commandes à exécuter pour effectuer
la configuration.
```bash
git config --global user.name "mon_user_name"
git config --global user.email "mon_adresse"
```
où "mon_user_name" est à remplacer par votre nom d'utilisateur GitHub et "mon_adresse" est est à remplacer par votre adresse électronique utilisée pour créer votre compte GitHub.
Ensuite, pour vérifier votre configuration, vous pouvez utiliser la commande
```bash
git config --global -l
```
Pour récupérer le projet en local :
```bash
git clone https://_adresse_du_dépôt_distant_
```
Pour effectuer un commit et un push sur le dépôt distant (sur Github ou Gitlab), placez vous en local dans le dossier qui contient le projet et exécutez les commandes suivantes :
```bash
git add .
git commit -m"fix ... ..."
git push
```
|
|
https://github.com/fiit-community/base-typst-template | https://raw.githubusercontent.com/fiit-community/base-typst-template/main/template/assets/mod.typ | typst | MIT License |
#let logo = image.with("fiit-logo.svg")
|
https://github.com/freundTech/typst-typearea | https://raw.githubusercontent.com/freundTech/typst-typearea/main/tests/basic.visual.typ | typst | MIT License | #import "../typearea.typ": *
#show: typearea.with(
header: block(width: 100%, height: 100%, above: 0pt, below: 0pt, fill: red),
footer: block(width: 100%, height: 100%, above: 0pt, below: 0pt, fill: blue),
)
#block(width: 100%, height: 100%, above: 0pt, below: 0pt, fill: green)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/014%20-%20Khans%20of%20Tarkir/003_Sorin's%20Revelation.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Sorin's Revelation",
set_name: "Khans of Tarkir",
story_date: datetime(day: 24, month: 09, year: 2014),
author: "<NAME>",
doc
)
#emph[Sarkhan Vol is not the only one who has come to Tarkir in search of something. The vampire Planeswalker Sorin Markov is here as well, for reasons of his own. Although the two Planeswalkers don't know it, they are here looking for the same thing: the spirit dragon Ugin.]
#emph[Long ago, Sorin helped Ugin and another Planeswalker, the Lithomancer, seal away the monstrous Eldrazi on Zendikar. Recently, the Eldrazi escaped, and Sorin believes that Ugin is one of the few who can stop them.]
#emph[Sorin has found his way here, to Ugin's home world, in search of his old ally. He still holds out hope, but he has not seen Ugin in a long time. And he knows that he may be much, much too late.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Tarkir.
Sorin winced at the sun's grotesque glare as if someone had stabbed him. He stood on a vast steppe. The scrub grasses made dry sounds in the hot breeze that swirled and scoured the rocks and hills.
#figure(image("003_Sorin's Revelation/01.jpg", width: 100%), caption: [Plains | Art by Noah Bradley], supplement: none, numbering: none)
Sorin instantly loathed Tarkir's relentless heat, and he could feel his flesh burning. He pulled his hood up over his head to shield his pale skin and headed for the nearest shadow under a high, irregular plateau that rose up from the steppe. His boots broke through the thin crust of dried earth as he walked. A lone buzzard wheeled high overhead, its shadow tracing silent circles on the ground as Sorin moved to cover.
In the relative shade of the high plateau, Sorin turned toward the distant, snow-capped peaks that stretched along the northern horizon and scanned the jagged ridges. There, a single peak stood out—a dragon's head looking to the east. A small smile crossed Sorin's lips. Somewhere up there was his destination.
"So the oracle was right," Sorin said. "I hope the rest of her visions prove true, dragon. I don't have much time."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Sorin waited until the agreeable cold of the night set in before he ventured out onto the moonlit landscape and headed north. The mad scatter of images from the dark oracle still burned in his mind's eye. They made some sense: a great battle of dragons, a chasm of ice, Ugin's swirling form. But the images were vague, blurred, and chaotic. He would have to work out the details on the way, but his path was known. As he walked toward the mountains, Sorin kept his senses sharp—not for danger but for blood. The journey had been a long one and the hunger had grown within him.
#figure(image("003_Sorin's Revelation/02.jpg", width: 100%), caption: [Sorin, Solemn Visitor | Art by Cynthia Sheppard], supplement: none, numbering: none)
It wasn't too long before Sorin could see the heat of a campfire from his vantage point on a ridge. The fire had burned down to cinders long before dark, but Sorin could still sense its heat and the five warriors camped nearby. They looked to be scouts—they were armored for speed—and their small horses were tethered to a strand of tough, desert shrubs. Two of the warriors were on watch, a fair distance from the camp and each other. They would be the first to go.
Sorin moved like a cat's shadow until he could see the warrior's eyes glinting in the moonlight. He reached out and caught the sentry's mind like a small, docile fish.
The man stiffened. His eye went large. Sorin moved into view and smiled.
"Tell your friend you'll take the watch alone," he whispered.
The warrior nodded and set off toward the other man.
As Sorin watched him move off into the night, he felt a customary pang of irritation. The need for food—it felt so weak, so stupid, so mortal. A repetitive, mundane task that bound him to lesser beings. He had tried to ignore it once, but the results had been dangerous and horrifying. Sorin resented the hold that it had over him.
Sorin felt a small, unsettled feeling rustle inside of him like a snake, coiled and ready to strike. Nahiri was gone and her silence disturbed him, but Ugin should have sensed the danger. Why hadn't he come to Zendikar? The Eldrazi titans were a fire that could not be quenched, and Ugin's absence was strange. Sorin knew he had to find the dragon soon and hoped the two of them could once again stop the impending catastrophe.
The warrior shuffled back and stood before Sorin, who seized him without hesitation, like a spider, and drained him to a pale husk. He looked up at the moon and lowered the man's body to the earth where it crumpled at his feet, bloodless and gaping.
Sorin regarded the dead man at his feet for a moment, then moved off and blended into the night.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Sorin followed an old animal trail that led him deep into the mountain wilderness. The granite peaks, capped in snow and ice, rose up far above his head as he traversed the crags and passes.
#figure(image("003_Sorin's Revelation/03.jpg", width: 100%), caption: [Rugged Highlands | Art by Eytan Zana], supplement: none, numbering: none)
The experience of time as a phenomenon had long since ceased for Sorin. And the long trek through Tarkir was no more than a series of moments. There was no anticipation, no sense of ennui, no unnecessary urgency. He knew what he needed to do and his mind was occupied with the action of the moment. Over the millennia, his human frailties and neurosis had grown, blossomed, and withered away. Now, all that remained was a mind unburdened by the yoke of mortality.
He drew near the snowline, the tall pines laden with thick snow that glistened in the light. He heard them before they rounded the bend in the trial: a band of five warriors and a shaman on massive, long-haired beasts. The warriors carried heavy spears and wore bear-claw necklaces. The shaman was hooded in a thick fur and masked behind a veil of bones and knotted yarn. The leader held an axe made from the jawbone of some hulking creature; a bearskin cloak wrapped his broad shoulders, and he had a weathered face that looked like tanned leather. They didn't seem afraid of him.
#emph[Good] , Sorin thought. #emph[I need a guide] .
"Is this the 'terrible traveler' that the whisperer spoke of?" one of the warriors asked the others in hushed tones, not realizing that even at thirty paces, Sorin could hear every word.
"I doubt it," the captain replied. "My guess, he's a Sultai: warped by too much rakshasa magic. What do you sense, Rushka?"
"There is no life within that creature," the shaman said. "It's dangerous."
"Wait to hear what he says, then we kill him."
Sorin approached. He could feel their lives as they pulsed before him, each heartbeat its own rhythm. He began to hum a spell under his breath as he neared the warriors, an old spell from a forgotten time—a tune of death.
"That's far enough, Sultai demon-spawn," the warrior captain said from atop his beast. "Your head will decorate a spear tonight."
Sorin smiled and closed his pale fist in front of his face as a chuckle escaped his lips. Dark smoke issued from between his fingers like ink poured into clear water. Two warriors suddenly gasped and then shrieked as they desiccated into corpses in a matter of seconds. Their mounts flew into a panic and charged off the mountain path. The leathery cadavers of their former riders fell to the ground like dried beef as the mounts crashed through the woods.
The other three warriors were shocked and struggled to calm their wild-eyed beasts. One warrior was thrown to the ground and, in a flash of speed, Sorin subdued him with a well-placed boot heel.
The shaman held out his hand and a pillar of greenish fire blazed up from the ground. In an instant, it coalesced into a hulking form that charged Sorin. Sorin reached out his hand and willed the two leathery corpses back from the dead. The former warriors writhed on the ground and jerked onto all fours. Their eyes blazed with unlife and their bodies were gripped with blood madness.
"Master," they hissed, their faces pulled into rictus grins filled with sharp fangs.
Sorin only had to look, and his vampire thralls moved with unholy speed. They leaped from the rocks to grapple with the great beast as it charged toward Sorin. Even as they were crushed beneath the beast's powerful feet, the vampiric fiends tore at the creature's flesh with terrifying power and savagery. The creature tried in vain to shake them off but it was only moments before the gluttonous feasting brought the enormous beast to its knees.
The shaman howled and charged Sorin, hurling three slashes of fire that streaked through the air. The spell tore through Sorin's leather vest, which caused Sorin's skin on his arm to blacken and peel away from his bones.
Sorin hissed and thrust his will into the shaman's mind. His eyes flashed with malevolence. "Kill that one." Sorin pointed to the captain who steadied his beast and prepared to charge.
The shaman wheeled about and swung his spear at his captain's head, but the captain reacted like a cat and struck the shaman's head off with one blow from his jawbone axe. As he turned to face Sorin, the captain failed to see a lone, leathery vampire as it crawled from the corpse of the beast and scrabbled across the rocks on a broken leg. As the captain raised his weapon, the undead husk leapt onto the warrior captain's back and caught him in an iron grip. The captain struggled but the vampire sank its fangs into the captain's spine and drained his blood.
When it was finished, Sorin dismissed the broken vampire and it fell still, its fangs streaked with blood. He walked over to the unconscious warrior and knelt down to cradle his head.
"You shall serve me," Sorin whispered in his ear.
The warrior's eyes snapped open. Sorin made sure not to dominate the warrior's will too much, lest he erase all agency from his newest thrall's mind. Sorin needed the man to find Ugin.
#figure(image("003_Sorin's Revelation/04.jpg", width: 100%), caption: [Vampire token | Art by Cynthia Sheppard], supplement: none, numbering: none)
At first mention of the name Ugin, the warrior seemed afraid. But with another mental stab from Sorin, he spoke.
"The Spirit Dragon's domain. The journey is not long from here, but it is dangerous."
Sorin extended his hand. "Lead the way."
The warrior shuffled before him and followed an ancient trail that only an experienced tracker could pick out. They moved high across a mountain face for a day and then camped under the stars. Sorin watched the warrior sleep in his furs next to the dwindling fire. Sorin had forgotten what it felt like to need warmth and tried to remember his days as a mortal, wrapped up in mortal concerns next to the large fireplace in Markov Manor. There was still a fondness for Innistrad that somehow persisted within Sorin through thousands of years.
As he sat there in the darkness, Sorin held the memory of Innistrad like a secret jewel within the dark velvet of his mind.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
They trekked along the narrow trails and icy crags in relative silence, but Ugin's presence interested Sorin.
"How long have you known about the domain of the Spirit Dragon?" Sorin asked his guide.
"Our people found the Spirit Dragon's domain long ago, before the end of all dragons."
"Dragons no longer exist here?" Sorin asked.
"They have all been killed," his guide said as he shuffled along. "Hunted to extinction. It was said that the dragons were born from great storms, but those storms ended."
"Born from storms? Interesting. Ugin never mentioned it."
The warrior paused for a second and then continued down the trail.
"The elders say that a dragon tempest was a time of celebration. We revere the memory of the dragons. Their spirit of savagery is why we Temur survive. But some say that the dragons became greedy and corrupt, so the Spirit Dragon gave us magic to fight them. Now the dragons are all dead, so we fight each other."
"A story I have heard time and time again." Sorin said. "It never seems to go smoothly, does it?"
The Temur guide said nothing.
Days passed until they crested a ridge that eventually led to a steep cliff. Far below was a flat plain of ancient, shattered rock covered in ice and snow. Sorin could see that the rock on the plain had been warped and shaped by an immense outpouring of energy. He could see a spiral of rock that looked as if it had once been molten and made to follow lines of force, then flash frozen. The strange rocks surrounded a deep canyon of blackened granite that streaked through the center of the plain.
"There lies the Spirit Dragon." The Temur guide pointed to the canyon floor.
Sorin looked.
Bones.
#figure(image("003_Sorin's Revelation/05.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The chasm stretched before him for hundreds of yards and, deep within the huge crack in the earth, Sorin could just make out places where a huge, skeletal rib cage stuck out from the ice like the bare beams of a cathedral.
"Impossible," Sorin whispered and staggered to the edge of the cliff. Sorin reached out and felt the lack of life far below him. He slammed his fist against the cold rock. "Oracle be damned! Lies and vagaries! That cannot be Ugin."
The warrior stared at Sorin.
"Take me down there. I must see for myself."
"It is dangerous," his guide said, emotionless. "All who enter the chasm have died."
"I don't care," Sorin said with a surge of ire. "Move. Now."
The warrior winced in pain, then moved along the cliff's edge. Eventually, a precarious path that led down to the canyon appeared. As they picked their way along the rocks and ice, Sorin couldn't take his eyes off the bones. Even against the white glare of the snow, they glowed and gave off a bluish mist. The magic trapped in them was still powerful.
They reached the floor of the chasm. A section of skeletal tail could be seen jutting out from the snow, the bluish mist emanating from it. The closer they got to the bones, the more Sorin could feel the forces at work—powerful magic from another age.
These were Ugin's bones.
The warrior guide began to falter as he struggled forward.
"Stop," Sorin said. The warrior wobbled on his feet. "No need for you to get ripped to pieces. Move back."
The warrior turned and took shelter in the lee of a boulder as Sorin moved toward the ghostly arc of ribs that rose overhead. The closer he came to them, the more he could feel the tidal forces of magic as they pulled at the very fibers of his being. He could feel the spark within him respond, holding him together as he moved upward through the Spirit Dragon's ribs toward the skull.
Blue mists of energy began to swirl around Sorin. He kneeled down to brush the snow from the solid ice below. There, within the darkness of the ice, gleamed Ugin's unmistakable skull. It looked at Sorin through the dead hollows of his eyes. Sorin reached out and felt for any sign of life, any shred of Ugin's spirit, but there was only a palpable void.
#figure(image("003_Sorin's Revelation/06.jpg", width: 100%), caption: [Bitter Revelation | Art by <NAME>], supplement: none, numbering: none)
Sorin gazed into Ugin's black sockets. "There's more life in me than in you, dragon."
Sorin pressed his forehead against the ice and spat a curse into the snow as the reality sank in.
On the journey down the cliff into the canyon, he had held onto the hope that Ugin's spirit had not been destroyed. He had hoped there would be something that could be resurrected, a shred of consciousness that could be pulled back from the brink of annihilation. But Sorin's hopes were snuffed out like a feeble flame.
Ugin was dead. And with him fell the hopes of countless worlds.
Sorin walked back through the archway of ribs to the warrior who waited for him. Zendikar would surely be destroyed. And what would be next? Innistrad? Whether it was now or in a thousand years, it was only a matter of time before his world would be consumed. The thought made Sorin feel both furious and helpless at the same time.
"We're all doomed," Sorin said to the warrior and the winds.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.