repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/copyzied/infodev | https://raw.githubusercontent.com/copyzied/infodev/main/Lab-3.typ | typst | #import "Class.typ": *
#show: ieee.with(
title: [#text(smallcaps("Lab #3: Web Application with Genie"))],
/*
abstract: [
#lorem(10).
],
*/
authors:
(
(
name: "<NAME>",
department: [Student],
organization: [ISET Bizerte --- Tunisia],
profile: "copyzied",
),
)
// index-terms: (""),
// bibliography-file: "Biblio.bib",
)
In this lab, we will create a basic web application using *Genie* framework in Julia. The application will allow us to control the behaviour of a sine wave, given some adjustble parameters. we are required to carry out this lab using the REPL .
#figure(
image("Images/REPL.png", width: 100%, fit: "contain"),
caption: "Julia REPL"
) <fig:repl>
#exo[codes of Sine Wave Control][]
#let code=read("../Codes/web-app/app.jl")
#raw(code, lang: "julia")
#let code=read("../Codes/web-app/app.jl.html")
#raw(code, lang: "html")
```zsh
julia --project
```
```julia
julia> using GenieFramework
julia> Genie.loadapp() # Load app
julia> up() # Start server
```
We can now open the browser and navigate to the link #highlight[#link("localhost:8000")[localhost:8000]]. We will get the graphical interface as in @fig:genie-webapp.
#figure(
image("Images/Capture d’écran 2024-05-13 213447.png", width: 100%),
caption: "Genie -> Sine Wave",
) <fig:genie-webapp>
|
|
https://github.com/dead-summer/math-notes | https://raw.githubusercontent.com/dead-summer/math-notes/main/notes/ScientificComputing/ch1-intro-to-scicomp/efficiency.typ | typst | #import "/book.typ": book-page
#import "../../../templates/conf.typ": *
#import "@preview/mitex:0.2.4": *
#show: book-page.with(title: "Efficiency")
#show: codly-init.with()
#show: thmrules.with(qed-symbol: $square$)
#codly_init()
= 5 Efficiency
The rule to improve efficiency is (obviously) to minimize the number of arithmetic operations.
#exm[
Evaluate the polynomial
$
p_n(x) = a_n + a_(n-1) x + a_(n-1) x^2 + dots.c + a_1 x^(n-1) + a_0 x^n.
$
Straightforward evaluation of the polynomial may involve $cal(O)(n^2)$ multiplications.
Let
$
p_(n-1)(x) = a_(n-1) + a_(n-1) x + dots.c + a_1 x^(n-2) + a_0 x^(n-1)
$
and
$
p_k(x) = a_k + a_(k-1)x + a_(k-2)x^2 + dots.c + a_1x^(k-1) + a_0x^k
$
for $k = n, n - 1, dots.c ,2,1,0$ . Note that two consecutive polynomials have the relation
$
p_k(x) = a_k + x p_(k-1)(x).
$
We can start with $p_0(x) = a_0$ and use the recursion above for $k = 1,2, dots.c , n$ to get $p_n(x)$ . The procedure only involves $cal(O)(n)$ multiplications. It called Horner’s rule.
]
#exm[
Evaluate $ln(2)$ with the Taylor series expansion
$
ln(1+x) = x - x^2/2 + x^3/3 - x^4/4 +x^5 + dots.c
$
]
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
int n = 100;
for (int i = 0; i <= 4; i++) {
float sum = 0.0;
float x = 1.0;
float z = x;
for (int k = 1; k <= n; k++) {
if ((k%2) == 0) {
sum −= z / k;
} else {
sum += z / k;
}
z *= x;
}
float error = fabs(sum − log(2.0));
std::cout << "n = " << n << ", sum = " << sum
<< ", error = " << error << std::endl;
n *= 10;
}
return EXIT SUCCESS;
}
```
One may alternatively use the formula
$
ln((1+x)/(1-x)) &= ln(1+x) - ln(1-x)\
&=2(x + x^3/3 + x^5/5 + x^7/7 + dots.c )
$
for $x=1\/3$.
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
int n = 1;
for (int i = 0; i < 8; i++) {
float sum = 0.0;
float x = 1.0 / 3.0;
float x2 = x * x;
float z = x;
for (int k = 1, m = 1; k <= n; k++) {
sum += z / m;
z *= x2;
m += 2;
}
sum *= 2;
float error = fabs(sum − log(2.0));
std::cout << ′′n = ′′ << n << ′′, sum = ′′ << sum
<< ′′, error = ′′ << error << std::endl;
n++;
}
return EXIT SUCCESS;
}
```
|
|
https://github.com/rice8y/cetzuron | https://raw.githubusercontent.com/rice8y/cetzuron/main/src/lib.typ | typst | #import "requirements.typ"
#import "fcnn.typ": fcnn
#import "rnn.typ": rnn
#import "ae.typ": ae |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/data-11.typ | typst | Other | // Error: 7-18 failed to parse yaml file: while parsing a flow sequence, expected ',' or ']' at line 2 column 1
#yaml("test/assets/files/bad.yaml")
|
https://github.com/Caellian/UNIRI_voxels_doc | https://raw.githubusercontent.com/Caellian/UNIRI_voxels_doc/trunk/content/usporedba.typ | typst | = Usporedba s poligonima
Zbog prethodnih ograničenja u računalnoj memoriji, uporaba voksela je značajno slabije istražena metoda pohrane modela i prikaza. Postojeći harver je optimiran za prikaz tradicionalnih
== Problemi
- Kako zaobliti svijet
- Je li vrijedno spomena, vrlo specifično za računalne igre...
- Postoji negdje efekt sa shaderima; ne rješava probleme topologije
- https://www.youtube.com/watch?v=bJr4QlDxEME
=== Izgled
- Sampliranje uvijek narušava kvalitetu modela, ili zauzima previše memorije
- Artisti su naviknuti raditi s trokutima
- Nije bitno za proceduralan sadržaj
- Marching cubes i djeca
- Vrlo teško modelirati nepravilne oblike
== Interaktivnost
- "Svijet nije maketa od papira nego ima volumen".
- Postoje metode lažiranja nekih vrsta interakcija.
- Dodavanje svake zahtjeva zaseban trud dok je voxel engine uniforman (veliki upfront cost, lakše dodavanje sadržaja)
== Košta
- Kako bi vokseli bili praktični u real time aplikacijama potrebno je jako puno rada u optimizaciji njihove strukture u GPU memoriji, rendering kodu, LOD sustavu, ...
- Nvidia paper je dobar početak ali ne zadovoljava mnogo zahtjeva modernih računalnih igara
- Mislim da nema transparentnost?
#pagebreak()
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/spread-04.typ | typst | Other | // None is spreadable.
#let f() = none
#f(..none)
#f(..if false {})
#f(..for x in () [])
|
https://github.com/OrangeX4/typst-cheq | https://raw.githubusercontent.com/OrangeX4/typst-cheq/main/examples/example.typ | typst | MIT License | #import "../lib.typ": checklist
#set page(width: auto, height: auto, margin: 2em)
#show: checklist
= Solar System Exploration, 1950s – 1960s
- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [-] Jupiter
- [/] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley
= Extras
- [>] Forwarded
- [<] Scheduling
- [?] question
- [!] important
- [\*] star
- ["] quote
- [l] location
- [b] bookmark
- [i] information
- [S] savings
- [I] idea
- [p] pros
- [c] cons
- [f] fire
- [k] key
- [w] win
- [u] up
- [d] down |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_13.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 14-83 failed to decode image (Format error decoding Png: Invalid PNG signature.)
// #image.decode(read("/assets/files/tiger.jpg", encoding: none), format: "png", width: 80%) |
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/mediapipe_pose.typ | typst | #import "lib.typ": *
= MediaPipe Pose Landmarker <mediapipe-pose>
The following section describes the MediaPipe Pose Landmarker solution @mediapipe-pose-landmarker. It first provides some context about the broader MediaPipe Framework before going into more detail on the MediaPipe Pose Landmarker solution. The features of the solution are discussed, as well as the motivation behind the choice of this solution for the air drumming application. The inference models used in the solution are also briefly discussed, including BlazePose and GHUM.
MediaPipe is a collection of on-device machine learning tools and solutions by Google @mediapipe. It consists of two main categories. There are the MediaPipe solutions, which have predefined "Tasks" that are ready to be used in your application @mediapipe-solutions. There are tasks on vision such as the detection and categorisation of objects or the detection of hand gestures @mediapipe-gesture-recognition @mediapipe-object-detection. One of these vision solutions is the MediaPipe Pose Landmarker. Other solutions such as text classification and audio classification are also present @mediapipe-text-classification @mediapipe-audio-classification. On the other hand, exists the MediaPipe Framework. It is the low-level component used to build efficient on-device machine learning pipelines, similar to the premade MediaPipe Solutions @mediapipe-framework. The remainder of this thesis solely addresses the MediaPipe Pose Landmarker Solution from this point forward, and will frequently be referred to as simply "MediaPipe" or "MediaPipe Pose" for the sake of conciseness.
MediaPipe Pose is available on three different platforms. One can use it in Python, on Android and on the web. However, these are only just API's to interact with the actual detection task. The application presented in this thesis is completely written in Python, but all the concepts that are discussed are applicable to any platform.
== Features
The main feature of MediaPipe Pose is of course, just as all body pose estimation tools, to extract the body pose from a given image or video frame. Unlike many other body pose estimation tools, MediaPipe delivers a 3D estimation instead of the more common 2D estimation, by introducing depth. However, in the measurement results, this added depth dimensionality is shown to be less than ideal.
The MediaPipe Pose Landmarker solution matches all the requirements set at the beginning of the project. It can run on-device in real-time and provides 3D pose estimation. It only requires a single camera to operate and can run on consumer-grade hardware. A laptop with a webcam is sufficient to run the application. The hands and feet are properly detected and tracked, which is essential for the drumming application. The MediaPipe Pose Landmarker solution is also quite fast and can run in real-time. The MediaPipe Pose Landmarker solution is a perfect fit for the air drumming application. Not only does it meet all the requirements, it is one of the few tools currently available that is ready to be used in a production environment. MediaPipe is not just a research tool; it is a tool that is actively maintained and updated by Google. This is a big advantage over many other tools that are often abandoned once the research paper has been published.
#footnote[
Following the announcement at Google I/O 2024, MediaPipe is now part of the larger Google AI Edge collection of tools and solutions. This once again confirms that MediaPipe is ready to be used in a professional and commercial setting. #link("https://ai.google.dev/edge#mediapipe")[https://ai.google.dev/edge#mediapipe #link-icon]
]
All of these reasons are why MediaPipe has been chosen for this project.
MediaPipe has three modes of operation, called the `RunningMode`. MediaPipe can work on still images (`IMAGE`), decoded video frames (`VIDEO`) and a live video feed (`LIVE_STREAM`) @mediapipe-pose-landmarker. Using the live video feed mode has some implications. When running MediaPipe in a real-time setting, the inference time of the model is constraint by this real-time application. When frame inference takes too long to be in the time window the frame gets dropped. Another major aspect of real-time applications is that the inference should not block the main thread and halt the program. This is why the inference in the `LIVE_STREAM` mode is performed asynchronously and results are propagated back using a callback function.
One other feature other than returning the body pose is the creation of an image segmentation mask.
#footnote[A segmentation mask is a grayscale image, sometimes just pure black and white, with the goal of partitioning the image into segments. For example, the MediaPipe segmentation mask colours all pixels white where the human silhouette is visible.]
MediaPipe has the ability to output a segmentation mask of the detected body pose. This mask could be used for e.g. applying some visual effects and post-processing, but it is not of much use in this implementation.
== Inference models
MediaPipe Pose is based on two computer vision models for the inference of the body pose. The first one is BlazePose which is only designed to return two-dimensional data in the given frame @blazepose. A second is the GHUM model, a model that captures 3D meshes given human body scans. A synthetic depth is obtained via the GHUM model fitted to the 2D points @ghum.
The Pose task consists of 3 `.task` files that contain the actual detection task and models. Three models are available: Lite (3 MB size), Full (6 MB size) and Heavy (26 MB size).
The measurement results will prove that the larger models can provide a more accurate and correct result but at reduced inference speeds. There is a trade-off to be made between accuracy and real-time processing. Although the Heavy model is almost 9 times larger than the Lite model, the improvement in accuracy is a lot smaller. The Lite model is not considerably worse and produces fine results for the drumming application.
=== BlazePose
BlazePose provides human pose tracking by employing machine learning (ML) to infer 33, 2D landmarks of a body from a single frame @blazepose. A standard for body pose originating from 2020 is the COCO topology @coco. The COCO 2020 Keypoint Detection Task is a challenge to develop a solution to accurately detect and locate the keypoints from the COCO dataset. The original COCO topology only consists of 17 landmarks. With little to no landmarks on the hands and feet. BlazePose extends this topology to a total of 33 landmarks by providing landmarks for the hands and feet as well. These added landmarks are crucial for the drumming application and is part of the reason MediaPipe was chosen.
#figure(caption: [BlazePose 33 landmark topology with the original COCO landmarks in green.])[
#image(width: 100%, "images/blazepose_landmarks.jpg")
]
Next some parts of the BlazePose design and tracking model are discussed. It is important to understand some underlying methods discussed here as it helps to interpret the measurement results. A complete and detailed overview is provided in the original paper @blazepose.
The pipeline of MediaPipe is displayed in @mediapipe-pipeline. Before predicting the exact location of all keypoints the pose region-of-interest (ROI) is located within the frame using the _Pose detector_. The _Pose tracker_ then subsequently infers all 33 landmarks from this ROI. When in `VIDEO` or `LIVE_STREAM` mode, the pose detection step is only run on the first frame to reduce the inference time. For any subsequent frames, the ROI is then derived from the previous points.
#figure(caption: [MediaPipe Pose estimation pipeline])[
#image(width: 100%, "images/mediapipe_pipeline.jpg")
] <mediapipe-pipeline>
As this solution is intended to be used in a real-time setting, the inference needs to be within milliseconds. The MediaPipe team have observed that the position of the torso is most easily and efficiently found by detecting the position of the face. The face has the most high-contrast features of the entire body and thus results in a fast and lightweight inference compared to the rest of the body @mediapipe-blazepose. This, of course, has the logical consequence that the face should be visible within the frame. This means that the "drummer" has to face the camera head on for the best result.
After detecting the face the construction of the pose region-of-interest begins. The human body centre, scale, and rotation are described using a circle. This circle is constructed by predicting two virtual points. One point being the centre of the hips, the other lies on the circle as the extension of the hip midpoint to face bounding box vector. These two points should now describe a circle as shown in @vitruvian-man.
#figure(caption: [MediaPipe Pose detection and alignment using virtual keypoints.])[
#image("images/mediapipe_vitruvian.jpg")
] <vitruvian-man>
Lastly, we very briefly describe the actual network architecture for the tracking of keypoints.
The model takes an image as input with a fixed size of 256 by 256 pixels and 3 values for each pixel providing RGB values, @mediapipe-network. The model uses "a regression approach that is supervised by a combined heat map/offset prediction of all keypoints" @blazepose, @cnn-pose. The left-hand side outputs the heat maps and offset maps. Both the centre and left-hand side of the network are trained using the provided heatmap and offset loss. Afterwards, the heatmaps and output maps output layers are removed and the regression encoder on the right-hand side is trained. The fixed input layer size indicates that there is no use in increasing the resolution to get an increase in the prediction accuracy. The measurements also confirm this hypothesis.
#figure(caption: [MediaPipe Pose network architecture.])[
#image("images/mediapipe_network.jpg")
] <mediapipe-network>
=== GHUM (Generative 3D Human Shape and Articulated Pose Models)
As mentioned, MediaPipe Pose offers an extra dimension unlike many other purely 2D pose estimation tools. This third dimension is, of course, depth. It does so by utilising an entirely different model, being the GHUM model @ghum. The GHUM model can construct a full 3D body mesh given image scans of a person. The outputs form an actual 3D mesh of 10,168 vertices for the regular model and 3,194 vertices for the lite model. MediaPipe is quite vague on the exact usage of this model in the pose solution. The only mention of GHUM is in the following sentence: _"Keypoint Z-value estimate is provided using synthetic data, obtained via the GHUM model (articulated 3D human shape model) fitted to 2D point projections."_ @mediapipe-model-card. Nonetheless, in the measurements it is shown that there is some notion of depth, but it is far from accurate. Especially when compared to the other 2D values provided by the BlazePose model.
|
|
https://github.com/PA055/5839B-Notebook | https://raw.githubusercontent.com/PA055/5839B-Notebook/main/Entries/First-Steps/3d-design-software.typ | typst | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "3d design software",
type: "decide",
date: datetime(year: 2024, month: 3, day: 10),
author: "<NAME>",
witness: "<NAME>"
)
Before any models for possible drive trains or new odometry sensors can be made a decision on what software to use is necessary. In the previous season we adpoted Autodesk inventor. There exists 3 main options other then inventor for vex which include Solid Works, Fusion 360, and Onshape. Each has a variety of favorable aspects to be considered when choosing.
The best way to comapre these is through a decision matrix of various aspects of each
#decision-matrix(
properties: (
(name: "Familiarty", weight: 30),
(name: "Acessability", weight: 20),
(name: "Availble Part Libraries", weight: 5),
(name: "Availble Help Recoruces", weight: 5),
(name: "Vex Compatability", weight: 2),
(name: "Ease of Use", weight: 2),
),
("Inventor", 5, 5, 4, 5, 4, 3),
("Fusion 360", 3, 3, 5, 3, 5, 4),
("Solid Works", 2, 4, 3, 2, 3, 3),
("Onshape", 1, 5, 4, 3, 4, 4),
)
#admonition(type: "note")[
Inventor scored far higher in some categories compared to other teams due to Eastern Tech's Engineering Program. This program which the majority of the team is in teaches Inventor and provides us with a browser version of it. This ngeates Onshapes main advantage and gives us 3 teachers who can help fix any problems we run into.
]
#admonition(type: "decision")[
Due to a variety of reasons the main one being a lack of time to learn a new software and familiarty with Inventor it will continue to be our primary design software.
]
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/book/src/dynamic/pause.md | markdown | # `pause` to reveal content piece by piece
Consider some code like the following:
```typ
#uncover("1-")[first]
#uncover("2-")[second]
#uncover("3-")[third]
```
The goal here is to uncover parts of the slide one by one, so that an increasing
amount of content is shown, but we don't want to specify all subslide indices
manually, ideally.
If you have used the LaTeX beamer package before, you might be familiar with the
`\pause` command.
It makes everything after it on that slide appear on the next subslide.
In Polylux, this works very similar with `#pause`, so we can equivalently write
the above code as:
```typ
{{#include pause.typ:6:10}}
```
This results in

`#pause` should mainly be used when you want to distribute a lot of code onto
different subslides.
Note that it does not affect content in the same paragraph as itself, for example.
For smaller pieces of code, consider one of the functions described next.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test alternative delimiter with set rule.
#set math.mat(delim: "[")
$ mat(1, 2; 3, 4) $
$ a + mat(delim: #none, 1, 2; 3, 4) + b $
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/substitution/ligature.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
// ### Ligature substitution
=== #tr[ligature]#tr[substitution]
// We've done one to one, and we've done one to many - *ligature substitution* is a many-to-one substitution. You substitute multiple glyphs on the left `by` the one on the right.
我们介绍完了一换一和一换多,现在该来介绍#tr[ligature]这种多换一#tr[substitution]了。它可以将`by`左边的多个#tr[glyph]#tr[substitution]为右边的一个#tr[glyph]。
// The classic example for Latin script is how the two glyphs "f" and "i" become the single glyph "fi", but we've done that one already. In the Khmer script, when two consonants appear without a vowel between them, the second consonant is written below the first and in a special form. This consonant stack is called a "coeng", and the convention in Unicode is to encode the stack as CONSONANT 1, U+17D2 KHMER SIGN COENG, CONSONANT 2. (You need the explicit coeng because Khmer is written without word boundaries, and a word-ending consonant followed by a word-beginning consonant shouldn't trigger a stack.)
这里最经典的例子就是拉丁文中将f和i转换成单个#tr[glyph]fi,但这个例子我们已经讲过了。我们这里换一个高棉文的例子:当高棉文的两个辅音中间没有元音时,第二个辅音需要被写成比第一个略低的特殊形式。这种特殊的堆叠形式称为 “coeng”,Unicode编码这一行为的方式是 `CONSONANT 1, U+17D2 KHMER SIGN COENG, CONSONANT 2`。(因为高棉文是没有分词的,而一个词末尾的辅音和下一个词开头的辅音并不触发coeng堆叠形式,所以我们需要显式的写出这个符号。)
// So, whenever we see U+17D2 KHMER SIGN COENG followed by a consonant, we should transform this into the special form of the consonant and tuck it below the base consonant.
所以当看见 `U+17D2 KHMER SIGN COENG`后面跟着一个辅音时,就需要把这个辅音改成特殊形式,然后把它放在基本辅音的下方。
#figure(
placement: none,
)[#include "khmer.typ"]
// As you can see from the diagram above, the first consonant doesn't change; we just need to transform the coeng sign plus the second consonant into the coeng form of that consonant, and then position it appropriately under the first consonant. We know how to muck about with positioning, but for now we need to turn those two glyphs into one glyph. We can use a ligature substitution lookup to do this. We create a `rlig` (required ligature) feature, which is a ligature that is "required to be used in normal conditions" and "important for some scripts to insure correct glyph formation", and replace the two glyphs U+17D2 KHMER SIGN COENG plus a consonant, with the coeng forms:
从上述流程图可以看出,第一个辅音没有改变。我们只需要将coeng符号和在其后的第二个辅音变成对应的coeng形式,然后放到第一个辅音下方的合适位置。我们知道如何调整位置,但首先我们得将后两个#tr[glyph]变成一个,这就需要用到#tr[ligature]#tr[substitution]#tr[lookup]。我们创建 `rlig`(必要#tr[ligature])特性,这个特性中的#tr[ligature]是“必须在通常情况下开启”和“用于确保某些#tr[scripts]中的#tr[glyph]被正确处理”的。在这个特性中我们编写规则将 `U+17D2 KHMER SIGN COENG` 和其后的一个辅音一起转换成coeng形式:
```fea
feature rlig {
sub uni17D2 uni1780 by uni1780.coeng;
sub uni17D2 uni1781 by uni1781.coeng;
#...
}
```
// In the next chapter, we'll explore in the next chapter why, instead of ligatures for Arabic rules, you might want to use the following lookup type instead: contextual substitutions.
在下一章中我们会研究阿拉伯文,并介绍为什么它的#tr[ligature]需要使用另一种#tr[substitution]类型,#tr[contextual]#tr[substitution]。
|
https://github.com/OJII3/tuat-typst | https://raw.githubusercontent.com/OJII3/tuat-typst/main/template.typ | typst | #import "@local/tuat-typst:0.1.0": tuatTemplate
#show: doc => tuatTemplate( // title: "実験報告書
date1: "2021-01-01", // 日付1
date2: "2021-01-02", // 日付2
date3: "2021-01-03", // 日付3
date4: "2021-01-04", // 日付4
// date5: "2021-01-05", // 日付5
collaborator1: "<NAME>", // 共同作業者1
collaborator2: "<NAME>", // 共同作業者2
collaborator3: "<NAME>", // 共同作業者3
collaborator4: "<NAME>", // 共同作業者4
// collaborator5: "<NAME>", // 共同作業者5
submitDate: "2021-01-06", // 提出日
resubmitDate: "2021-01-08", // 再提出日
deadline: "2021-01-07", // 期限日
redeadline: "2021-01-09", // 再提出期限日
subject: "情報工学実験", // 科目
teacher: "<NAME>", // テーマ指導教員
grade: "2", // 学年
semester: "後期", // 学期
credit: "2", // 単位
theme: "テーマ", // テーマ
studentId: "学籍番号", // 学籍番号
author: "<NAME>", // 著者
doc,
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11EE0.typ | typst | Apache License 2.0 | #let data = (
("MAKASAR LETTER KA", "Lo", 0),
("MAKASAR LETTER GA", "Lo", 0),
("MAKASAR LETTER NGA", "Lo", 0),
("MAKASAR LETTER PA", "Lo", 0),
("MAKASAR LETTER BA", "Lo", 0),
("MAKASAR LETTER MA", "Lo", 0),
("MAKASAR LETTER TA", "Lo", 0),
("MAKASAR LETTER DA", "Lo", 0),
("MAKASAR LETTER NA", "Lo", 0),
("MAKASAR LETTER CA", "Lo", 0),
("MAKASAR LETTER JA", "Lo", 0),
("MAKASAR LETTER NYA", "Lo", 0),
("MAKASAR LETTER YA", "Lo", 0),
("MAKASAR LETTER RA", "Lo", 0),
("MAKASAR LETTER LA", "Lo", 0),
("MAKASAR LETTER VA", "Lo", 0),
("MAKASAR LETTER SA", "Lo", 0),
("MAKASAR LETTER A", "Lo", 0),
("MAKASAR ANGKA", "Lo", 0),
("MAKASAR VOWEL SIGN I", "Mn", 0),
("MAKASAR VOWEL SIGN U", "Mn", 0),
("MAKASAR VOWEL SIGN E", "Mc", 0),
("MAKASAR VOWEL SIGN O", "Mc", 0),
("MAKASAR PASSIMBANG", "Po", 0),
("MAKASAR END OF SECTION", "Po", 0),
)
|
https://github.com/noahjutz/CV | https://raw.githubusercontent.com/noahjutz/CV/main/body/main.typ | typst | #import "section.typ": section
#import "timeline.typ": entry, arrow
#import "project.typ": project
#import "/chip.typ": chips
#set block(below: 16pt, above: 0pt)
#include "title.typ"
#section("Akademischer Werdegang")
#entry(
[2010 #sym.dash 2012],
"Regensburg International School",
none
)
#entry(
[2012 #sym.dash 2021],
"Privat-Gymnasium PINDL",
none
)
#entry(
[2022 #sym.dash],
"OTH Regensburg",
)[
Aktuell mit 103 ECTS und einer Durchschnittsnote von 2.3 im 6. Semester meines Informatikstudiums (B. Sc.).
]
#arrow
#section("Praktika")
#entry(
[2018],
"ZMT Automotive"
)[
Praktikum als Feinwerkmechaniker
]
#arrow
#section("Projekte")
#project(
"GymRoutines",
icon: "/assets/logos/GymRoutines.svg",
url: "codeberg.org/noahjutz/GymRoutines"
)[
Workout-Tracker für Android.
#chips("Android", "Kotlin", "Jetpack")
]
#project(
"Algorithmen & Datenstrukturen",
icon: "/assets/logos/AD.svg",
url: "github.com/noahjutz/AD"
)[
Darstellungen von Algorithmen.
#chips("Typst", "Python", "CI/CD")
]
#project(
"Endict",
icon: "/assets/logos/Endict.svg",
url: "codeberg.org/noahjutz/Endict"
)[
Englisches Wörterbuch für Android.
#chips("SQLite", "JSON", "XML")
] |
|
https://github.com/Dherse/typst-brrr | https://raw.githubusercontent.com/Dherse/typst-brrr/master/samples/masterproef/elems/code_blocks.typ | typst | #let code_width_state = state("code_width", 100%)
#let set-code-width(width) = {
code_width_state.update(width)
}
#let code-blocks(body) = {
let languages = (
"rust": ("Rust", "\u{fa53}", rgb("#CE412B")),
"c": ("C", none, rgb("#283593")),
"python": ("Python", "\u{ed01}", rgb("#FFD43B")),
"verilog-ams": ("Verilog-AMS", none, rgb(30,100,200)),
"vhdl": ("VHDL", text(font: "UGent Panno Text")[</>], gray),
"spice": ("SPICE", none, rgb("#283593")),
"phos": ("PHÔS", "\u{ed8a}", rgb("#de8f6e")),
"js": ("Tokens", "\u{ecd7}", rgb("#656255")),
"typ": ("Bytecode", "\u{f7ff}", rgb("#6f006f")),
"typc": ("Bytecode", "\u{f7ff}", rgb("#6f006f")),
)
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: true): it => {
// Get the info of the language
let lang = if it.lang == none {
(it.lang, none, black)
} else {
languages.at(it.lang, default: (it.lang, none, black))
}
let lang_icon = if lang == none or lang.at(1) == none {
none
} else {
text(
font: "tabler-icons",
fallback: false,
weight: "regular",
size: 1em,
)[#lang.at(1)]
}
let lang_box = if lang_icon == none { none } else {
style(styles => {
let content = [#lang_icon#lang.at(0)]
let height = measure(content, styles).height
box(
radius: 2pt,
fill: lang.at(2).lighten(60%),
inset: 0.32em,
height: height + 0.32em * 2,
stroke: 1.5pt + lang.at(2),
)[#content]
})
}
// Build the content
let contents = ()
let lines = it.text.split("\n").enumerate()
for (i, line) in lines {
let line = if line == "" { " " } else { line }
let content = if i == 0 {
raw(line, lang: it.lang)
} else {
raw(line, lang: it.lang)
}
contents.push((
index: str(i + 1),
content: content,
))
}
// Compute the width of the largest number, add the gap
let width_numbers = 10pt + 0.64em
let border_color = luma(200) + 1.5pt;
let cell(i, len, body, ..args) = {
let radius = (:)
let stroke = (left: border_color, right: border_color)
if i == 0 {
radius.insert("top-left", 0.32em)
radius.insert("top-right", 0.32em)
stroke.insert("top", border_color)
}
if i == len - 1 {
radius.insert("bottom-left", 0.32em)
radius.insert("bottom-right", 0.32em)
stroke.insert("bottom", border_color)
}
radius.insert("rest", 0pt)
rect(
inset: (left: width_numbers + 0.48em, rest: 0.64em),
fill: if calc.rem(i, 2) == 0 {
luma(240)
} else {
white
},
radius: radius,
stroke: stroke,
width: 100%,
..args
)[ #body ]
}
align(left, stack(
dir: ttb,
..contents.enumerate().map(((i, x)) => {
cell(i, contents.len())[
#if i == 0 {
place(
top + right,
lang_box,
dy: -0.42em,
dx: 0.24em,
)
}
#set par(justify: false)
#place(x.index, dx: -width_numbers)
#x.content
]
})
))
}
body
} |
|
https://github.com/maxi0604/typst-builder | https://raw.githubusercontent.com/maxi0604/typst-builder/main/directory/content.typ | typst | MIT License | It also works if the files are in directories.
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/tdd.typ | typst | #import "/components/glossary.typ": gls
== Test-Driven Development (TDD) <sec-tdd>
#gls("tdd", mode:"full") is a software development methodology that emphasizes
writing tests before writing production code. This approach promotes a focus on
quality, maintainability, and testability. We will explore the key principles,
benefits, and challenges of #gls("bdd") (@sec-bdd).
#gls("tdd") is a valuable methodology that can significantly improve the
quality and maintainability of software projects. By writing tests before code,
developers can ensure that their systems meet the desired requirements and are
well-tested. While there may be initial challenges, the long-term benefits of
#gls("tdd") often outweigh the costs @bib-tdd.
=== Key Principles of TDD
- *Red-Green-Refactor Cycle*: #gls("tdd", mode:"full") follows a cyclical
process:
- *Red*: Write a failing test that defines the desired behavior.
- *Green*: Write the minimum amount of production code to make the test pass.
- *Refactor*: Refactor the code to improve its design and maintainability while
ensuring the tests continue to pass.
- *Small, Focused Tests*: #gls("tdd") encourages writing small, focused tests that
verify specific units of code.
- *Continuous Testing*: #gls("tdd") promotes a culture of continuous testing,
ensuring that code changes are validated throughout the development process.
=== Benefits of Using TDD
- *Improved Code Quality*: #gls("tdd") can lead to cleaner, more maintainable
code by encouraging modular design and early detection of bugs.
- *Increased Test Coverage*: Writing tests before code ensures that the system
is thoroughly tested, improving its reliability.
- *Faster Development*: #gls("tdd") can accelerate development by providing a
clear direction and preventing the accumulation of technical debt.
- *Enhanced Collaboration*: #gls("tdd") can foster collaboration among team
members by providing a shared understanding of the system's requirements and
behavior.
=== TDD and BDD
#gls("tdd") and #gls("bdd") are often used together to complement each other.
#gls("bdd") provides a high-level specification of the system's behavior, while
#gls("tdd") ensures that the implementation meets those specifications.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/pinit/0.1.0/simple-arrow.typ | typst | Apache License 2.0 | #let simple-arrow(
fill: black,
stroke: 0pt,
start: (0pt, 0pt),
end: (30pt, 0pt),
thickness: 2pt,
arrow-width: 4,
arrow-height: 4,
inset: 0.5,
tail: (),
) = {
let _arrow-width = arrow-width * thickness
let _arrow-height = arrow-height * thickness
let _inset = inset * thickness
let start-x = start.at(0)
let start-y = start.at(1)
let end-x = end.at(0)
let end-y = end.at(1)
let _dx = end-x - start-x
let _dy = end-y - start-y
let _angle = calc.atan2(_dx.pt(), _dy.pt())
let _ht = 0.5 * thickness
let _hw = 0.5 * _arrow-width
let _c = calc.cos(_angle)
let _s = calc.sin(_angle)
polygon(
fill: fill,
stroke: stroke,
..tail,
(start-x - _s * _ht, start-y + _c * _ht),
(start-x + _dx - _s * _ht - _c * (_arrow-height - _inset), start-y + _dy + _c * _ht - _s * (_arrow-height - _inset)),
(start-x + _dx - _s * _hw - _c * _arrow-height, start-y + _dy + _c * _hw - _s * _arrow-height),
(end-x, end-y),
(start-x + _dx + _s * _hw - _c * _arrow-height, start-y + _dy - _c * _hw - _s * _arrow-height),
(start-x + _dx + _s * _ht - _c * (_arrow-height - _inset), start-y + _dy - _c * _ht - _s * (_arrow-height - _inset)),
(start-x + _s * _ht, start-y - _c * _ht),
)
} |
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/design/design_iteration_1.typ | typst | #import "../../../style.typ": *
= First Design Iteration <design-iteration-1>
For the first iteration, multiple design directions were created and evaluated.
The following process was chosen to gain as much insight as possible:
1. @design-evaluation-criteria defines a set of evaluation criteria to compare
the designs in the form of a questionnaire.
2. Then, three proposals are presented: A Flo-based design in
@flo-inspired-design, a Scratch-based design in @scratch-inspired-design, and
a design inspired by the Haskell function notation in
@haskell-function-notation-inspired-design.
3. The three designs are filled into a questionnaire and handed to a selected survey group.
The feedback is then further discussed in @iteration-1-conclusion.
#include_section("design_concept/content/design/design_iteration_1_criteria.typ", heading_increase: 1)
#include_section("design_concept/content/design/design_iteration_1_scratch_inspired.typ", heading_increase: 1)
#include_section("design_concept/content/design/design_iteration_1_flo_inspired.typ", heading_increase: 1)
#include_section("design_concept/content/design/design_iteration_1_haskell_function_notation_inspired.typ", heading_increase: 1)
#include_section("design_concept/content/design/design_iteration_1_results.typ", heading_increase: 1) |
|
https://github.com/AHaliq/DependentTypeTheoryReport | https://raw.githubusercontent.com/AHaliq/DependentTypeTheoryReport/main/preamble/lemmas.typ | typst | #import "@preview/lemmify:0.1.6": *
#import "@preview/showybox:2.0.1": showybox
// Define default theorem environments.
#let (
theorem, lemma, corollary,
remark, proposition, example,
proof, definition, rules: thm-rules
) = default-theorems(
"thm-group",
lang: "en",
thm-numbering: thm-numbering-heading.with(max-heading-level: 1)
)
#let exercise(name, body) = showybox(
frame: (
border-color: silver,
)
)[
#underline(smallcaps([Exercise #name:])) #body
] |
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/dyk.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1877", "1931 (54 let)", "politik, básník, dramatik, novinář, kritik divadelní i literární, šachista", "gymnázium a práva na UK", "buřič, později nacionalista", "/cj-autori/media/dyk.jpg")
<NAME> byl významný český spisovatel, básník a dramatik, aktivní především na přelomu 19. a 20. Narodil se v #underline[Pšovce u Mělníka]. Jeho tvorba reflektovala dynamické a komplikované období před první světovou válkou a meziválečnou érou, během níž se česká společnost intenzivně potýkala s otázkami identity, politiky a sociálních nerovností.
Dyk se stal hlasem své doby, jehož názory se prolínaly s mnoha společenskými debatami. Byl liberálně a demokraticky orientovaný, což se odráželo jak v jeho literatuře, tak i ve veřejném životě. Své obdivuhodné nadání využíval ke kritice sociální nespravedlnosti a korupce, což ho často stavělo do opozice vůči tehdejší politické a společenské situaci.
Umělecky <NAME> zastupoval zejména romantismus a symbolismus, přičemž propojoval jejich prvky s realistickým zobrazováním lidských osudů a společenských problémů. Jeho díla jsou důkazem hlubokého porozumění lidské psychologie.
Mezi jeho nejvýznamnější díla patří:
1. *Satiry a sarkasmy* -- Politická satira a poezie. V prvním oddíle této sbírky se nachází řada epitafů, jimiž básník charakterizoval své literární přátele, nepřátele i sebe.
2. *Zmoudření <NAME>* -- Divadelní hra. Drží se děje i smyslu původního románu, ale liší se hlavně závěrem; Dykův don Quijot skutečně zmoudří, ale zaplatí za to smrtelnou sklíčeností a bezútěšným zoufalstvím.
*Současníci*\
_<NAME>_ -- Povídání o pejskovi a kočičce, 1929\
_<NAME>_ -- Květy intimních nálad, 1891\
#pagebreak() |
https://github.com/cs-24-sw-3-01/typst-documents | https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/chapters/testing.typ | typst | #import "../custom.typ": *
= Testing
== Unit and Integration
== User Tests |
|
https://github.com/Wh4rp/Presentacion-Typst | https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/ejemplos/11_set_scope.typ | typst | Esto se ve afectado #[
#set list(marker: [--])
- Dash
]
Pero esto no:
- Bullet |
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/029%20-%20Aether%20Revolt/006_The%20Skies%20over%20Ghirapur.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Skies over Ghirapur",
set_name: "<NAME>",
story_date: datetime(day: 11, month: 01, year: 2017),
author: "<NAME>",
doc
)
#emph[When renegades prepared to storm the Aether Hub, sky pirate Kari Zev had a different plan—find aether the best way she knows how by taking directly from Consulate ships. Always one in favor of a contingency plan, Jace accompanied the young captain on her mission.]
#emph[When the Consulate retakes the Aether Hub from the renegades, they lock down air traffic and threaten to stamp out the renegades' plan to assault Tezzeret himself. It will fall to Kari and Jace to create the opening the renegades need.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("006_The Skies over Ghirapur/01.jpg", width: 100%), caption: [Kari Zev's Expertise |Art by Jason Rainville], supplement: none, numbering: none)
Though she was only fifteen, Kari Zev had been at the pirating trade long enough to have seen her share of strange things. Sometimes she'd go to strange places and meet strange people, while at other times strangeness came to her. Perhaps that's just what it was to be pirate. Kari couldn't say for sure, but whatever it was, Kari had always been quick to recognize the strange as a wonderful source of opportunity.
And that's how the notorious young pirate captain found herself aboard a Consulate aether-collecting skyship, smuggling canisters of their inventory onto her ship under the approving gaze of Consulate stooges, all the while consulting the voice in her head.
Of course, the Consulate saw none of that, at least not in that way. What they observed was an allied Consulate vessel, with a loyal Consulate crew, who'd come to them on official Consulate business to requisition aether for the Consulate cause.
#figure(image("006_The Skies over Ghirapur/02.jpg", width: 100%), caption: [Aethersphere Harvester | Art by Christine Choi], supplement: none, numbering: none)
"#emph[It's quite a trick, Jace. I can't believe it's working. This is the last crate] ," she thought, though it still felt odd to think #emph[at] someone. But then, what was typical about this job?
She bent her knees, pressed her cheek against the filigreed side panel of the crate, and lifted her end of it. Through gritted teeth, she let out a sharp abbreviated breath as the load rose off the deck's polished surface, and as the weight of the crate was bit into her fingers, Jace's voice bloomed in her head.
"#emph[Let's just get this done. I'd advise against any more theatrics, though.] "
"#emph[Theatrics?] " She was shuffling backward as she conversed in her mind, trusting in her crate-partner to guide their way across the gangplank that spanned the open space between this ship and hers. "#emph[What theatrics? As a loyal Consulate captain, I simply shared my feelings about the filthy renegades.] "
"#emph[The illusions that mask you, your crew, and your ship are only visual. All I'm saying is don't give them reason to be suspicious. There's a guard to your left. He's not pleased about this exchange.] "
Kari didn't have to look to know that the guard was watching her, but of course she did anyway. He was a lanky officer of some rank, with rounded shoulders and gray at his temples. Kari nodded at him as they stepped onto the gangplank.
"#emph[He's following you across] ," came Jace's thoughts once more.
"#emph[Excellent] ," she thought, "#emph[I have a lot more to say.] "
"#emph[I can tell that you're joking, you know.] "
"#emph[You're still sweating about it, though, aren't you?] " Kari teased.
At last they were back aboard her ship, #emph[Dragon's Smile] , though it looked more like a Consulate-commissioned cloud cutter, and even she couldn't see through Jace's illusion. Hopefully, neither could this officer, who came around to her as she and her partner lowered the crate to the deck.
Kari rubbed her sore fingers, and turned to the officer, who stood a full head taller than her. "Can I help you with something?" He was looking around the ship, and he was doing so in a way that seemed like he wanted her to know that he was looking for something.
"#emph[He's a lieutenant] ," Jace telepathically fed her.
"Lieutenant," she said, and again, "can I help you with something?"
The officer tilted his head down and met her gaze. He started to say something, but his words were lost as a screech from above cut across them, and he leapt back as though to avoid an attack. "A monkey!" he said, looking up. A second screech sounded.
#figure(image("006_The Skies over Ghirapur/03.jpg", width: 100%), caption: [Art by Daniel Ljunggren], supplement: none, numbering: none)
"Yep," confirmed Kari. "Someone's got to run this ship."
Clearly relieved, the sailor let out a nervous chuckle, and Kari couldn't resist. "What's funny?" she said in all seriousness. A long moment followed where the officer's smile slowly faded until he was standing there shifting his gaze awkwardly from the monkey to Kari, and back again. Kari's face remained humorless, and she was savoring every bit of this.
"I'm just having fun with you, Lieutenant," she said, hooking a thumb beneath the sash of rank that hung across her torso, and giving it a good flick. "This here's my ship."
His head cocked to one side, and his brow furrowed. "I'm sorry, you seem quite young to be a captain."
Kari put on her best no-nonsense expression. "Son, there are two possible realities here. Either I #emph[am] too young, and therefore not a captain. Or," she flicked the sash of rank again, "I am, in fact, a captain, and you are questioning my authority. Now then, which reality do you suppose is a safer one for you to believe in? Perhaps there's a reason you're still a lieutenant. Think on that."
"Apologies, Captain. I meant no offense."
Kari reached up and brushed off the officer's shoulder. It took everything she had not to laugh. "I know. If you meant to offend me, well, then you'd discover a whole other kind of reality. Now go on." She turned her back to them, and barked an order at no one in particular, " Make ready to shove off! The renegade filth must pay!"
When the lieutenant departed, Kari had the gangplank hauled in. Soon, the space between the ships began to widen as Kari's pulled away. When she deemed the distance to be sufficient, she thought at Jace, "#emph[You can drop the trick now. We're well enough away.] " And before she could finish articulating her thoughts into words, her Consulate uniform dissipated, along with the Consulate trappings on her ship. She was no long Kari Zev, Consulate blah, but instead, she was back to being Kari Zev, pirate captain. "#emph[Impressive, Jace. Truly. Now meet me on deck if you want to see our score.] "
As she waited for the hooded man, she paced the deck of her ship. Even though it was never truly gone, she was glad to have it back. While it wasn't her first ship, it was beautiful, with its up-swept bow that had earned it its name. She loved it. More than that, she loved it up here. It was fresher, and freer, and it was hers.
Off to starboard, Kari spotted a pod of skywhales that swam through a swirling aether current no more than a couple leagues away. There were perhaps a dozen of the magnificent creatures following the flow of aether across the sky. Young were among them, darting between their mammoth elders with a heedlessness that made Kari smile.
"You shouldn't have done that back there," said Jace when he joined Kari at the crates, and it took her a moment to adjust to the sound of his voice being spoken aloud. "It was an unnecessary risk to tear into that officer. You knew that to be true."
"A risk? Yeah, I suppose. But I'd never be able to forgive myself otherwise." Her hand swept from the direction from which they had flown toward the pile of lifted cargo behind her. "You understand that, right?"
"I'm not entirely sure I do," Jace replied, but Kari already wasn't listening. The begoggled monkey, Ragavan, was watching this exchange from atop the heap of crates, and Kari whistled him over.
"Come, Ragavan, prince of mine, let's have a look inside, shall we?" Kari worked at the latch, and when it slid away it was the white-furred monkey who hoisted the lid. With a smile, Kari welcomed the familiar blue glow that washed over them.
#figure(image("006_The Skies over Ghirapur/04.jpg", width: 100%), caption: [Art by Sara Winters], supplement: none, numbering: none)
She reached inside and extracted the cylindrical form of an aether canister. The light it emitted came from a glass window set into the middle of its metal casing, and Kari gazed at the swirling gaseous contents within. Then, from over her shoulder, Jace's face appeared.
"Were you expecting something other than aether?"
"Nope. Just appreciating the moment. You should too. After all, your illusion won us all this," she said, passing the canister over to Jace, who took it with obvious curiosity. Then she boomed the command, "Let's get this cargo secured! Bring it below."
After a moment, the platform in the center of the deck began to sink into the cargo hold in the belly of #emph[Dragon's Smile] . As it moved, Kari lifted herself onto one of the other crates, and sat at its edge so that her legs dangled.
#figure(image("006_The Skies over Ghirapur/05.jpg", width: 100%), caption: [<NAME>, Skyship Raider | Art by <NAME>], supplement: none, numbering: none)
Addressing Jace, who didn't even seem to notice to descent, she said, "You know, when I was aboard my first ship, #emph[Sun Chaser] , my captain used to tell me all the time that the main thing that makes a great pirate is instinct for finding and seizing opportunity. If you can't do that, my captain said, you're just a thief with a boat." She paused. "What I mean is, when all this business with the Consulate and the Grand Consul is over, you could come with us. A person of your talents could be pretty useful."
No response. Perhaps he hadn't heard her. The platform shuddered into place in the narrow hold below deck.
Kari was about to repeat the question, but stopped. Instead, she just watched him turn the cylinder over in hands, as though he was inspecting it for some hidden meaning that was sealed away within. It was just aether, but he was utterly engrossed.
Then at last, Jace said, "I'm sorry, did you say something?"
Never mind, she thought. Instead, she said, "You're not the pirating type, are you?"
The canister stopped moving in Jace's hands. He smiled. "No? What type do I strike you as?"
"Well," Kari leaned forward, elbows on her knees, and gave Jace a squinting look. "Not the pirating type, anyway."
"I suppose not. But what does that entail, the pirating type? How did you come to enjoy this lifestyle?"
"How does anyone come to do anything?" Kari shrugged. "All I know is that I couldn't imagine doing anything else. Whatever it takes to keep this ship flying, I'll do it. And all this aether," she pounded a fist on the lid of the crate she was using as a chair, "is going to fetch enough to see that skies remain open to me for at least a little while."
Jace set the canister back in its place like it was suddenly contaminated. "You intend to #emph[sell] this aether to the renegades? Let's be clear, I went with you because I thought you could help turn the tide in all this. I can lend a hand with your errands; just know that I'm here for Tezzeret.
It was little too accusatory for Kari's liking. Especially aboard her own ship. "Look, Jace, Pia and I are pretty close. She's like a second mom to me. But she knows me well enough to understand that I don't fight for freedom, and I certainly don't fight for free. I'll raid for the renegade cause because it's the right thing to do, but the truth of it is this ship, let alone a fleet, doesn't stay in the sky all by itself." She pounded her fist again. "That's the pirating type!"
Her face was growing hot, and she was aware that the volume of her voice had risen sharply over last few seconds. She took a breath. "Look, just before dawn tomorrow, I'll be arranging the drop with one of Pia's associates. You should come."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
They were called the aviaries. Kari had explained to Jace it was the collective term for the cluster of hangars perched on the rooftops of some of the tallest buildings in Ghirapur. It's where she used to visit as a small child to watch skyships come and go all day. The whole thing was a tangle of catwalks and stairways that connected a host of storage facilities and workshops that ranged in size from meager to cavernous. It reminded Jace of an inverted anthill.
It was dark in the predawn light but for a wisp of aether, miles long, bent close to the city. Jace was thankful for its pale blue light, which was enough for him to pick out the edges and contours of their circuitous path.
Then, Jace saw a vertical yellow-orange light appear in space ahead of Kari. In an instant, he snatched the same illusion spell from his mind that he'd used back on the Consulate ship, ready to mask the two of them if the need arose. He waited. Then, above the nagging wind he heard Kari's muted voice, "Ukti, is that you?"
"Kari," came an unfamiliar voice, raspy and hard. It wasn't entirely unfriendly, a fact that Jace was quick to confirm with cursory telepathic feelers. "I'm surprised to see you here," the voice continued.
"Why? What happened?" Kari asked.
"Pia's group lost the Aether Hub. They're all scattered now. Some people started showing up here, but not the ones you're waiting to see."
"Show me," said Kari. The door swung open to reveal an old dwarven woman, wrinkled with age, but upright and strong-looking.
Jace followed Kari into a wide, low-ceilinged room arranged like a restaurant, with round, bare-topped, metal tables. From what Jace could see, broad windows encircled the place, though the curtains had been drawn across them all.
"This is First Launch," Kari informed Jace. "It's a restaurant and club for aeronauts. My parents brought me here a few times when I was kid."
"You're still a kid, Kari." Ukti rounded on the youth. "What kind of life is piracy for a fifteen-year-old?"
"Mine," answered Kari, her voice cool, as though she'd given that exact response, with just as much explanation, a dozen times or more. For several breaths, an invisible, unbendable rod seemed to extend between Kari's eyes and those of the elderly dwarf, as they stared coldly at one another.
Finally, Ukti snorted, and turned to lead the two of them through dining area, pushing in chairs as she went. Soon, they entered a pantry. The shelves were only half full, but Jace wouldn't have known from the collection of smells that met them. At the pantry's far side, Ukti reached behind a spice rack and found something there along the wall, and there came a sequence of low clicks that seemed to originate inside the wall. She then tugged at the corner of the shelf, which pivoted inward silently on rollers to reveal a dimly lit, narrow chamber. Within, a slightly narrower stairway with steep, shallow steps led upward to the sound of muffled voices. Five minds according Jace's mental sweep.
"Through here," Ukti said with a tired wave.
"Thank you, Ukti," said Kari. She placed her foot atop the first step, but before she could begin ascending, Ukti seized her wrist and shot a glance around to each of the three of them.
"Listen," Ukti said, "you are two out of a handful of people who know about this place. It's my sanctum. You treat it with respect."
Jace navigated the steps after Kari. Below him, Ukti closed the secret door, and the only light came from a circular hole in the ceiling where the stairs terminated. As his feet found each progressive rung, Jace thought of his own sanctum on Ravnica. It was his retreat from the pressures of his Guildpact responsibilities, and he'd grown to rely on it. He knew well the importance of a person's sanctum.
His head rose through the round portal into a room that was far too small for its current inhabitants. A quick count confirmed his initial assessment, and with Kari that meant six people crammed into a room not much larger than the pantry they had just passed through. Everyone was talking at once, and each person appeared to be carrying on several conversations. In the middle of it all was his own companion. The noise was a little overwhelming, and Jace decided to focus on navigating the final, awkward step into the room. He was contemplating his approach when a thick gauntleted hand reached out from the huddle. Behind it, a voice: "It's a tricky one. Take my hand."
Jace complied. A strong grip closed around his hand, and he was hoisted into the room.
Then Jace heard Kari's familiar voice. "Come on in, Jace." She was pushing her way over to him, and his eyes moved from her to take in the cramped space. Every inch of every wall was covered in what Jace discerned to be aviator equipment and tools. Some of it looked very old. To his left, a metal shelf extended from the wall to form a work bench, and it too was covered in all manner of tiny metal bits and instruments. In the far corner, someone sat in an old, worn chair. A second chair in the other corner filled the remaining space.
"I'm not sure I can be any more 'in' than I am now."
"No?" Kari smirked, and hung an arm over his shoulder. "Crows!" The conversation in the room quieted as the all eyes turned toward Kari. "This here is Jace. He's a friend of Renegade Prime's, which means he's one of my friends. He's a talented young man and a promising smuggler."
When the conversations resumed, Jace suddenly found himself in the middle of them. Kari recounted their heist from earlier, and after that came the introductions. They were called the Derby Crows. They had been an aeronaut society that raced skyships in the city, but as things with the Consulate took a turn, they decided as a group to take a more active role in politics. They were at the Aether Hub with Pia when everything fell apart yesterday.
"Look," Kari said, "I'm supposed to make a drop today, but it appears things are a bit more complicated than I was hoping. How bad is it?"
A dwarf rose to her feet. Around her neck hung a red scarf embroidered with purple scrollwork, and a white tattoo ran down across her right eye from forehead to cheek. Depala was how she'd introduced herself. "Consulate's spread out from Weldfast to the Spire. They've formed up around #emph[Skysovereign] ."
"#emph[Skysovereign] ," Kari repeated after a moment.
"Yeah," said Depala with a nod. "Have a look. Laksha, show them what you showed us."
The woman Depala had addressed turned around and slid a small gear-shaped door to one side. Jace had missed it on his initial read of the room, but it was very small door with an opening that was no higher than the woman's chest. She had to duck to pass through it. "Come on," she said, but Jace, Kari, and Depala were only able to crowd around the doorway and look out at the woman, who huddled over an apparatus that was perched on a modest platform clinging to the attic's exterior. She didn't seem to mind.
#figure(image("006_The Skies over Ghirapur/06.jpg", width: 100%), caption: [Quicksmith Spy | Art by <NAME>], supplement: none, numbering: none)
"There," she said. "Have a look for yourselves." And then she pushed her way back into the attic. The apparatus was a collection of lenses fixed in a brass frame, and when it was Jace's turn to peer through them, his entire field of vision was filled with the enormity of what could only be the promised #emph[Skysovereign] , a massive warship that hung heavy in the air like a storm cloud. In the growing light of dawn, Jace could make out scores of smaller escort ships that orbited the flagship.
#figure(image("006_The Skies over Ghirapur/07.jpg", width: 100%), caption: [Skysovereign, Consul Flagship | Art by Jung Park], supplement: none, numbering: none)
When he rejoined the group inside, Depala was shaking her head. "There's no way #emph[Heart of Kiran] 's getting through that monster," she said, spinning the replica's tiny propeller as she spoke.
After that, no one said anything for a while, and the only sound was Laksha moving the gear door back into place.
"Kari," the dwarf said, "we're trying to find a way to buy the #emph[Heart of Kiran] some time to take flight. It's our best shot at the Spire, but this blockade has completely grounded the renegades. We can't even get to our racing crafts," she said.
"So you have no plan," Jace said.
Depala threw her hands up. "That's what we've been trying figure out. We need ships, plain and simple."
Admittedly Jace felt a bit out of his element with all the talk of skyships, though he seized on something the young captain had mentioned after their heist. "What about your fleet, Kari? You mentioned your fleet earlier."
"Is that true?" asked the large man who'd lifted Jace into the room, a note of optimism rising in his voice.
Kari shot Jace a look. He got the feeling that he'd said something wrong, but he was already following that question up with another. "Can you send word to them? Kari?"
"Wouldn't do much good." She leaned against the work bench shelf, and looked at her boots while everyone was looked at her. "They're near Lathnu," Kari said without looking up, "but they're not exactly sky-worthy these days. That #emph[Skysovereign] 's exactly as you described it, Depala: a monster. It was designed to be a pirate hunter, and it was that and more. When it was done with my fleet, #emph[Dragon's Smile] was the only ship to make it out. You can find the rest of them scattered in a million pieces in the streets of the village that it destroyed to get to us."
Then Kari pointed in #emph[Skysovereign] 's direction, as though she could sense it through the wall. "All I could do was watch as that thing just floated away like it was out for a pleasure cruise."
Silence once again filled the room. Then Jace stepped toward Kari. "Was it a lot of ships?" he asked.
"Fourteen, including #emph[Dragon's Smile] ."
"And how well did you know them?"
"Very." She raised an eyebrow. "Why?"
Jace allowed himself a smile. "Then we have no time to waste. I have an idea."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
During the night, the aether current had swept in close to the city, bringing with it the same pod of whales that Kari had seen yesterday during the heist. Kari, knuckles on the starboard gunwale, leaned out from the deck to peer down over the side of her ship at these gathered behemoths. With mouths agape, the whales took turns gulping huge curls of aether, and all along their hides countless speckles lit up with the aether's warm glow.
From there, Kari's gaze tracked along the sprawl of the city. An updraft sent her asymmetrically longer hair whipping along her right shoulder with such suddenness that Ragavan scurried over to her unassailed shoulder with a litany of annoyed noises. Below the ship's keel, a veil of gauzy clouds spread out over most of the sky below, and the parts of the city seen through it took on an ethereal quality.
Even from this altitude, she could see the double-pylon tower that loomed as the tallest structure in the city. It was haloed in multiple tiers of circling enforcer skyships, and as much as she attempted to count and assess their various makes and armaments, her eyes were again and again drawn to the floating mass that dominated the airspace between the spire and Weldfast—#emph[Skysovereign] .
All they had to do was dislodge it from its aerial perch long enough to create enough of a gap for the renegades' own #emph[Heart of Kiran] to mount an assault on the grand consul in the spire. So the plan was to draw the Consulate flagship out of position. Toward them. To Kari, it was as though the ship was following her across the world, and she was now supposed to welcome it with open arms. She was suddenly aware of how thin and cold the air up here was, though part of her found more comfort in it than in the prospect of facing the #emph[Skysovereign] again.
But then there was the other part of her, the pirate captain part, which demanded satisfaction for the destruction of her fleet. It was that part of her that sent an angry heat up her neck until it boiled over in sharp, hissed words that pushed their way through clenched teeth. "Sovereign of the sky, huh?" Her eyes shifted back to the whales in flight. "I'm not sure they'd agree."
Kari found her raiders in the cargo hold, seated in two rows facing each other. It was more cramped than usual, with their haul of aether taking up most of the space.
Seven of the raiders crewed #emph[Dragon's Smile] , and five were Derby Crows. Each one of them had a flight pack secured to their backs, though the packs varied from raider to raider. Kari took the moment to captain a bit; she strode up and down the narrow space between the two rows, doling out encouraging nods before she drew her sword and addressed them all.
"Listen up! Your job is to get some attention. Cause enough of a stink for their flagship to take notice. Think you can do that?" An enthusiastic affirmation rose up. "Good. Now remember, this is #emph[Dragon's Smile] ," she said, spreading her arms out to either side. "Today, each one of you is one of its brilliant pointed teeth! And the time has come to show the Consulate just how sharp these teeth can be."
The cheers of her raiders followed her from the cargo hold, and she let them linger in her thoughts as she made her way to the cockpit.
When they'd left the Aviaries that morning, Depala had made it quite clear that she'd like to pilot #emph[Dragon's Smile] during this operation. When Kari asked why she should allow it, Depala had simply said, "Because you know that's where I belong." That much was probably true. Kari had seen her race before, and there was no doubt that the dwarf was one of the best pilots in Ghirapur.
Kari was going to ask Depala to take the helm, anyway, but she never said so, so when the captain entered the cockpit, it made her smile to see the dwarf already seated at the controls. Behind her, Jace was strapping into his seat.
Kari secured Ragavan in his spot in an alcove above the pilot. After she had strapped herself in, she asked, "Are you two all set?"
"Just give the word," said Depala.
"Jace?" Kari said, shifting in her seat toward him.
"If I had to choose yes or no, then I suppose yes. But if it's a spectrum—"
"Depala," Kari called out as she slid her goggles over her eyes, "make like a meteor!"
"Right away, Captain," said the dwarf, before addressing the crew through the conical end of a communication tube that extended from the ceiling of the cockpit. "Here we go." Then the engines halted with a low sigh, and even before the quad propellers had stopped rotating, the ship was falling. Air rushed around the vessel, and in seconds its mounting whoosh drowned out all other noise. Her straps kept her secured to her seat, but Kari's stomach felt unmoored in her abdomen. It was a discomfort she was used to, and one even Jace, who sat with eyes closed, seemed to be handling like it was nothing.
Not much time now, Kari intuited. At any moment, Depala would reengage the engines. Through the rounded glass of the cockpit, all Kari could see were flits of white racing up along a backdrop of blue sky. Wisps of cloud, she guessed, but they were moving too fast. Any time now, Depala.
Then the skyship's nose dipped, and the cockpit was suddenly leading the descent. All at once, the fast-approaching city swung into view, and so did the tops of dozens of Consulate ships arranged in a multi-layered formation that were impossible to count from their vantage. The abrupt shift in gravity pinned Kari and her insides back, and all she could do was watch the panic that was spreading among the formation as they frantically dispersed at their advance. "Look at 'em scatter!" came Depala's voice through her manic laughter.
"How about those engines, Depala?" Kari said in way that barely resembled a question.
"Another second." She was enjoying this perhaps a bit too much. "And..." The dwarf's hand shot forward and cranked the lever to engage the engines. The ship obeyed, as Kari knew it would, and she felt the hum of its four rotors working in harmony.
#emph[Dragon's Smile] soared between the first of the Consulate ships and through the gap in the blockade. "Here we go!" Depala bellowed. She pulled on the control stick, and the ship went into a tight swoop that brought it out of its vertical dive. Then #emph[Dragon's Smile] was among the Consulate fleet, and the pilot had to weave between the hostile vessels. There was no time for them to catch their breath, though the same was true for the Consulate ships, which were still tangled in their collective scramble.
Now the real work could begin. "Stay between them until we deploy," Kari said. "They're less likely to open fire if they might hit their own ships."
"I don't have much choice. They're everywhere!" Depala growled. "If you're going to deploy the crew, do it soon."
Kari unfastened her straps. "It won't do much good if #emph[Skysovereign] doesn't take any notice. Just get as close as you can." The young captain rose from her seat and leaned into the communication tube, her words echoing as they made their way through the narrow tube that reached out through her ship and down to her crew in the cargo hold. "Get ready down there! When the hatch opens, deploy! Be as bees—swarm them!"
For a heartbeat, there was silence. Then, "Bees?" came a tinny voice from the tube. "A moment ago, we were teeth. Sharp teeth. Which is it, if I may be so bold, Captain?"
That was good. Spirits were up. "What about bees #emph[with] teeth? How does that sound?"
"Absolutely terrifying."
"Wonderful!" Kari meant to say, but the word came out as a gulp as the skyship juked to one side. She caught herself on the back of the captain's chair. "No chance of a warning next time, I take it," Kari said leaning over Depala's shoulder.
"Afraid not, Captain." Depala sent the ship into a sharp climb that was punctuated by a hard bank. "Have a look." There was no need for her to point, for when they came out of their turn, Kari's field of vision was consumed by #emph[Skysovereign's] great bulk. It hung there in the air, almost motionless, between two buildings like a predatory bird perched on an invisible branch.
"There it is," the captain said flatly as her eyes narrowed.
She turned to the illusionist, who was still motionless, with eyes shut tight, though now pale as a marble statue. She had to admit, he was handling the drop better than she thought. "Jace! Jace!" When his eyelids slid open, Kari barked, "You still with us?"
He nodded. "I'll be ready when you need me."
"I truly hope so. In the meantime, I need you to open the cargo bay door to unleash the crew. Turn that crank until it doesn't crank anymore." She pointed to a metallic disk that hung from the low ceiling above Jace's head. "Ragavan, to me!" The monkey scurried to her along the netting on the wall, and by the time he was on her shoulder, Jace was at his task.
"Where are you going?" he yelled over the screech of the obstinate crank.
She pulled on a flight pack, and Ragavan had to do some gymnastics to avoid the harness's straps. "I'm going topside to see about keeping my deck clear!" Kari said, clasping the contraption's final strap at her waist. Then she was off at a run, her booted footfalls clanging along the metal floor panels of the central corridor and up a steep set of stairs. At the top, she pushed her way through a low, arched passage that opened onto the chaotic scene that played out all around them—because of them.
Ships were streaking past from every direction, and Kari felt as though she were moving in slow motion against such a frenetic backdrop. Or rather, the whole thing seemed like the inner workings of an elaborate clockwork toy that had been wound too tight. Fast flying was nothing new to Kari, but she had to admit, Depala was coaxing something out of #emph[Dragon's Smile] that even she hadn't seen before.
#emph[She better not break my ship.]
Once at the ship's stern, she was thankful to have the cabin at her back, which protected her from the wind's most insistent clutches. She anchored herself to railing with the cable and winch that was fixed to the bottom of her flight pack. Then, she peered down just as the first of her raiders launched from the yawning cargo bay. They emerged as blurs in twos and threes until all twelve were airborne, carried along on flight packs much like her own.
#emph[Well done, Jace] , she thought.
"#emph[Thank you] ," Jace said, his words startling her with their closeness. Like before, they manifested directly in her mind, but it was as though he'd been walking right behind her this whole time. "#emph[That crank wasn't easy work.] "
"#emph[Dammit, Jace!] " she thought back at him, "#emph[How long have you been lurking in my head?] "
"#emph[I don't lurk. I was about to let you know that the task was done.] "
Kari's eyes flitted from one group of raiders to the next as they wove through the Consulate line like a bunch of angry...bees. Then back to Jace, "#emph[Now I need you to close the bay door. Then stay where I can reach you. When I give the command, you know what to do.] "
"#emph[Of course.] "
"#emph[You remember everything I showed you?] "
"#emph[Every detail.] "
"#emph[Well, let's hope we won't need it.] " Kari watched a Consulate ship suddenly spin out of control when a neighboring vessel struck it with an errant harpoon that was meant for a pair of her raiders. To starboard-low, three Consulate ships collided while in pursuit of a single raider—one of Depala's by the look of her.
#figure(image("006_The Skies over Ghirapur/08.jpg", width: 100%), caption: [<NAME> | Art by <NAME>], supplement: none, numbering: none)
"Things are going well so far, wouldn't you say, my prince?" Kari nudged the monkey with her head. Ragavan chittered his agreement, while Kari made a quick mental tally.
#emph[Run the blockade? Check.]
#emph[Disrupt the Consulate formation? Check.]
But her list was interrupted by a blast that rang out from above. It sent her and Ragavan tumbling to the deck, and with an arm held up to shield her face, Kari looked up to see an aetherborn raider leaping from an expanding cloud of what was once a Consulate ship.
#figure(image("006_The Skies over Ghirapur/09.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The aetherborn gave Kari a casual salute in their descent, before they landed hard on another Consulate ship.
"Cause a ton of mayhem? That's right, Ragavan, check," Kari said as #emph[Dragon's Smile] continued on its winding course through the blockade. "But not enough. The flagship—the only ship that matters—hasn't budged. And none of this'll mean a damn thing if that sky slug doesn't give chase. Hey!" Kari's hand went to head where Ragavan had tugged at a chunk of hair. The monkey was screeching and pointing toward the streets below.
"All right, you have my attention." Dozens of Consulate enforcers, equipped with flight packs or mounted on single-seater skimmers, were joining the fight. Most were deploying to screen the ships. But not all of them.
"#emph[Are you seeing this, Kari?] " said Jace. "#emph[Depala spotted a group of enforcers moving in to intercept.] "
"#emph[Six of them, yep] ," Kari responded. She tested her anchor cable with a quick tug. "#emph[Can we shake them?] "
"#emph[Depala says she'll do what she can.] "
Kari drew her sword. "My prince—#emph[not you, Jace] —battle station." Ragavan flicked his goggles into place and scurried into a pouch that was nestled between Kari's shoulder blades where her flight pack curved away from her back. "It's time we got into this fight."
By the time the first three enforcers rose up along #emph[Dragon's Smile] 's port side, Kari had already taken flight. Her pack's mechanical wings buzzed furiously as they carried her across the deck, and as she flew, her anchor cable unspooled behind her with a high zipping sound.
The trio of enforcers were held aloft on identical quad-prop flight packs and were armed with Consulate-issue net-casters, which they clutched close to their chests. There was no sense in waiting to get mobbed by these mooks, so she welcomed them to her ship with all the hospitality of a pirate captain. She raced right at them.
Or rather, right past them.
As expected, the enforcers dispersed at Kari's direct approach, and she hurtled straight through them. The cable seemed to draw a line in the air as she flew, separating two of them from the third. Kari saw this and leaned into a tight a turn to sweep around the two. Before the cable could go slack, Kari engaged the winch's break and raced back toward the ship.
"Ragavan, hang on!" Kari yelled, and her cable caught one of the enforcers in the chest with a loud snap, sending Kari catapulting into the second enforcer, a startled dwarf who couldn't raise his weapon in time. With the first enforcer in tow, Kari and the dwarf tumbled to the deck of #emph[Dragon's Smile] . Weapons skidded away and they grappled there in a heap of wings and propellers as the ship tilted this way and that.
There was dull thud when Kari's elbow connected with the dwarf's cheek, and for half a second, the fight seemed to abandon him. Kari shoved him away, and in the next moment, she was in the air again.
The first enforcer had just untangled herself from Kari's cable with the help of the third one, and Kari wasted no time bowling them both over.
The victory was fleeting, however, for the three other enforcers joined their comrades. One of them, an officer of some rank, descended to hover before Kari.
#figure(image("006_The Skies over Ghirapur/10.jpg", width: 100%), caption: [Spire Patrol | Art by <NAME>], supplement: none, numbering: none)
Kari sent her thoughts at Jace, "#emph[Any progress?] "
And in response came, "Skysovereign#emph[ hasn't moved. How are things topside?] "
"Surrender your vessel," the officer commanded.
To Jace, "#emph[Not great. Any chance of deploying your part of the plan?] "
From Jace, "#emph[Just give me a moment.] "
Kari stepped toward the officer. "Let your Consuls know," she called out, "that I, <NAME>, captain of #emph[Dragon's Smile] , have brought my fleet to claim this city." #emph[Any second, now.]
Then there was a flash of blue, and whatever the officer was about to say was lost to the great spectacle that unfolded over the next few moments. Suddenly, ships were drifting out from behind buildings. Not Consulate ships, but pirate ships.
#figure(image("006_The Skies over Ghirapur/11.jpg", width: 100%), caption: [Illusionist's Stratagem | Art by <NAME>], supplement: none, numbering: none)
They moved in twos and threes, and like the enforcers, Kari could only watch, utterly transfixed, because she knew each one of them. #emph[Brass Hammer] and #emph[The Demon of Vahd] . #emph[Cold Wind] and #emph[Kite] . And more. They kept coming. Even the #emph[Sun Chaser] —of course the #emph[Sun Chaser] . Her fleet had returned to her, and they were assembling to fill the space above a plaza so that buildings protected their flanks to either side. One moment, #emph[Dragon's Smile] was alone, and the next, it was one among dozens. This was Jace, she knew, or rather, the memories she'd shared with Jace. But nevertheless, she couldn't help but be consumed by the feeling that the Consulate was severely outmatched now. The enforcers seemed to share her assessment because all around her, they were taking flight to retreat from the pirate fleet.
The officer looked from Kari to the wall of ships, then back to Kari. And before the next snide comment could leave Kari's lips, the officer's net-caster fired. Its suddenness caught Kari off guard, and for a moment, Kari just stood there as the net expanded on its path to entangle her.
But it never got to her. From his pouch on her shoulders, Ragavan pounced. He vaulted off Kari's head, and threw himself into the incoming net. He was entangled instantly, and in the net's clutches, the monkey fell to the deck without any of his usual grace.
In the next heartbeat, the officer was off—and with her, the net containing Kari's prince.
"Ragavan!" Kari shrieked. She was already in motion. In the span of four steps, she scooped her sword up from the deck and was leaping over the side of her ship. As the wings of her flight pack flitted into life, a downward swing from her blade severed her anchor cable against the gunwale.
Kari raced after the officer, and the distance between them closed rapidly. She came in low, and saw that Ragavan was still bundled in the net, which now hung from the officer's waist. "Hang on, prince of mine. I'm coming for you," she said under her breath, and she wished that the monkey shared Jace's mind-reading tricks.
When Kari caught the officer, it was from below, and before the officer could bank, Kari had grabbed hold of her so that they were hurtling through the air, face to face. The officer tried to shake Kari off, but Kari just wrapped her legs around the officer's.
"Get off me!" the officer spat.
"Not while you have my monkey!"
"You'll kill us both!"
Kari just winked at the officer, and shoved her sword into the spinning action of one of the four propellers that kept the officer aloft. There was a series of staccato pops and streams of sparks as the propeller tore itself to pieces buffeting against Kari's blade. Immediately, their flight path became erratic, a development exacerbated by the punches the officer rained down on Kari.
But Kari held on, and she drove her head into the officer's jaw. Pain engulfed her skull but the blows ceased, and she managed to wrest control of their entwined path, if only to influence it. The undamaged propellers tugged the flight pack to one side, and though Kari compensated with her own pack, the tangled group flew ended up in wide semi-circle that took them back toward the projection of the pirate ship, through the #emph[Sun Chaser's] illusory hull, and beyond the fleet.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Kari's not responding," said Jace, his eyes closed against the madness he knew was playing out beyond the cockpit. "She's moving too fast for me to reach into her mind."
"Just focus on that projection of yours!" Depala snapped.
And of course, that's exactly what Jace was doing. Though he was physically strapped in his seat behind the dwarven pilot, his mind was at work maintaining the enormous and complex illusion that he'd constructed solely out of memories pulled from Kari's mind—plus a few duplicates here and there to really sell the spectacle. It was a lot of work that required tremendous focus and most of his attention.
"The #emph[Skysovereign] will never commit if they see through..." Depala began, but trailed off.
Jace didn't want to risk opening his eyes, especially not right now. "What's happening?"
"Bet you could guess."
He could, but Depala said it anyway. "#emph[Skysovereign] inbound with escort, moving to engage the fleet. If Renegade Prime's people don't recognize their opening, she and I will have words after this."
"How should our fleet respond?" Jace asked.
"Keep them steady. We should be just one of its numbers."
Jace was suddenly aware of the light strobing beyond his eyelids. He tried to push the visual sensory input from his mind, but then the whole world seemed to turn white and a sound like the sky tearing open boomed in his ears. He pulled his awareness into his illusion to keep it from failing, though he couldn't ignore the metallic taste that had filled his mouth.
From some distant place, Jace heard his name. There was panic in the sound, which came again and again. He willed his consciousness back into the cockpit, where the world was turned sideways, and where Depala was calling for him.
"I'm here, Depala," Jace said, which was partly true. Part of him was still keeping the fleet intact. "Were we hit?"
"Jace! I'm blind!" the pilot yelled.
"WHAT?!"
"Take the controls!"
Even as the ship banked and juked, Jace didn't like the prospect of him at the helm. There simply wasn't adequate time to pull the necessary expertise from Depala's mind. So instead, he returned a favor. During their freefall descent into the Consulate blockade, Jace had staved off panic by reaching out to the absolute confidence in Depala's thoughts. Now, he pulled her into his mind.
"I can see!" Depala said, and without missing a beat, she pulled #emph[Dragon's Smile] into a graceful climb.
"What blinded you?"
"The lightning cannon on that thing!" And as if to demonstrate, the strobe went off again. This time Depala banked hard to dodge the arc of electricity. All the while, #emph[Skysovereign] drifted closer. Jace, meanwhile, felt that his hold on his grand illusion could falter at any moment.
"It certainly seems to like us, despite your illusions," Depala said.
"This is still Captain Zev's ship."
"Don't much look forward to facing her if we break it."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When Kari, Ragavan, and the Consulate officer emerged on the other side of Jace's illusion, they were still locked in their savage airborne brawl. The officer kicked furiously at Kari, and Kari tried to swipe at the net containing Ragavan. The monkey, for his part, reached through his net to occupied himself with riffling the officer's pockets.
Kari was almost dislodged when the officer caught the young captain below the knee with the sole of her heavy boot, and jerked it downward so that it raked along Kari's shin. Wincing, she bit her lip.
The pain broke her concentration, and Kari noticed that their path had carried them into an eddy of aether. And in that eddy, colossal shapes were moving. Swimming.
Skywhales.
They were creatures without malice or predatory urges, though that did little to assuage the feeling of absolute insignificance that gripped Kari at that moment. Her throat had suddenly become dry, and she realized her mouth was hanging open.
The officer must have also been struggling with a crisis based on how wide her eyes had grown. It was in that instant that Kari remembered her prince. She wrenched the gathered net from the officer's waist, pushed away from her stubborn adversary.
Once away, she held Ragavan close. One of the whales bent through the air toward them, and for a moment, Kari was face to face to it. Its mouth seemed to go on forever, and the throat grooves that creased its lower jaw were like canyons. She could have been a mote of dust for all the notice the whale reciprocated.
Then in Kari's mind, Jace's voice bloomed. It sounded somehow distant, but he was calling her name.
"#emph[Jace!] " she replied.
"Skysovereign's#emph[ right on top of us. ] Heart of Kiran#emph[ is still grounded. We can't last much longer here.] " He sounded drained and haggard.
"#emph[No!] " She refused to allow #emph[Dragon's Smile] , the last of her fleet, to meet the same fate. She gave the whale one last look, wheeled around, and sped toward her ship.
But then she stopped. And all at once, she saw it. Opportunity.
"#emph[Jace, open the cargo door. And when I give the word, have Depala jettison my cargo and climb sharply.] "
"#emph[Jettison the aether? Do I understand that correctly?] " asked Jace, his words barely registering in her mind.
"#emph[This is for my fleet.] "
She came streaking out from the illusory fleet, and she was met by #emph[Skysovereign] 's great bulk looming before her. It filled the sky, a metallic reflection of the skywhale behind her.
"#emph[We're right below you, Kari] ," Jace said, and Kari saw her ship climbing to meet her.
"#emph[Drop the cargo!] " Kari thought as loud as she could, while she worked the fastenings of her flight pack. The crates fell from the ship's hold, flipping end over end so that the canisters themselves tumbled out.
This was it. Kari whipped her flight pack from her shoulders and hurled it down so that it crashed into the glass canisters. Puffs of blue erupted, and as more canisters shattered, the cloud swelled and began to reach out in spiraling wisps. It'd have to be enough to get their attention.
Meanwhile, Kari cradled Ragavan to her chest and slid onto the #emph[Dragon's Smile] 's deck as it climbed. Her aching shin screamed at her as they skidded and bounced along the deck's metal surface. Finally, she and Ragavan came to a hard stop when they slammed into the aft railing.
"#emph[Keep clear] ," Kari thought at Jace, thankful that she didn't have to speak aloud.
A few moments passed. Then Kari watched Jace's illusory fleet—her fleet—flicker and burst, as one of the skywhales came hurtling through it toward the aether. And directly ahead of the great creature, #emph[Skysovereign] .
#figure(image("006_The Skies over Ghirapur/12.jpg", width: 100%), caption: [Aethertide Whale | Art by <NAME>], supplement: none, numbering: none)
While smaller Consulate vessels careened out of its path, the #emph[Skysovereign] was left to prove its name as the whale met it with full force. It was no contest. Metal squealed and crumpled, and everywhere smoke billowed into the sky. The whale moved off unfazed, while the Consulate flagship coasted in the air for a moment like an errant balloon, before the whole thing listed to one side and drifted slowly to the ground.
"Prince of mine," she said, "come watch this with me." She helped him find his way out of the net, and she placed him on her shoulder. Then, utterly exhausted, Kari draped her arms over the rail and watched the dying gasps of the metal monster.
They should probably get out of here, she thought. She was about to give the command when Jace's voice found her mind once again, only this time his words were more animated than she'd come to expect. "#emph[Was that your doing?] "
"#emph[That was the whale, Jace. I don't hit that hard.] "
|
|
https://github.com/An-314/Notes_of_Electrodynamics | https://raw.githubusercontent.com/An-314/Notes_of_Electrodynamics/master/appendix.typ | typst | #import"@preview/physica:0.9.2":*
#import "@preview/mitex:0.2.4":*
#import "template.typ": *
= 附录
== 外微分与张量代数
<附录A>
以下内容由GPT-o1生成:
#mitext(
`
\subsubsection{引言}
微分形式是微分几何和拓扑中的核心工具,提供了在任意维度空间中处理积分和微分运算的统一框架。传统的向量分析中的梯度、散度和旋度可以通过微分形式重新表述。这种表述不仅深化了对这些算子的理解,而且方便了在高维空间中的推广。
\subsubsection{向量场与微分形式的对应}
在三维欧几里得空间中,向量场和微分形式之间存在以下对应关系:
- \textbf{标量函数 \( f \)}:对应 \textbf{0-形式}。
- \textbf{向量场 \( \vec{F} = P\vec{i} + Q\vec{j} + R\vec{k} \)}:对应 \textbf{1-形式} \( \omega = Pdx + Qdy + Rdz \)。
- \textbf{面密度}:对应 \textbf{2-形式} \( \alpha = U\, dy \wedge dz + V\, dz \wedge dx + W\, dx \wedge dy \)。
- \textbf{体积形式}:对应 \textbf{3-形式} \( \beta = T\, dx \wedge dy \wedge dz \)。
\subsubsection{外微分算子}
外微分 \( \mathrm{d} \) 是作用于微分形式的基本算子,具有以下性质:
- \textbf{线性性}:
\[
d(a\omega + b\eta) = a\,d\omega + b\,d\eta
\]
- \textbf{Leibniz 法则}:
\[
d(\omega \wedge \eta) = d\omega \wedge \eta + (-1)^k \omega \wedge d\eta
\]
其中 \( \omega \) 是 \( k \)-形式。
- \textbf{幂零性}:
\[
d^2 = 0
\]
\subsubsection{Hodge 对偶算子 \( * \)}
Hodge 对偶算子 \( * \) 将一个 \( k \)-形式映射为一个 \( (n - k) \)-形式(\( n \) 为空间维数)。在三维空间中:
- \textbf{1-形式与 2-形式}:互为 Hodge 对偶。
- \textbf{0-形式与 3-形式}:互为 Hodge 对偶。
\subsubsection{梯度与微分形式}
- \textbf{标量函数 \( f \)}:
- 对应 \textbf{0-形式}。
- \textbf{梯度运算}:
- 对 \( f \) 取外微分 \( df \),得到对应的 \textbf{1-形式}:
\[
df = \frac{\partial f}{\partial x}\,dx + \frac{\partial f}{\partial y}\,dy + \frac{\partial f}{\partial z}\,dz
\]
- \textbf{对应的向量场}:
- 梯度向量场 \( \nabla f \) 与 \( df \) 有一一对应关系。
\subsubsection{散度与微分形式}
- \textbf{向量场对应的 1-形式}:
\[
\omega = P\,dx + Q\,dy + R\,dz
\]
- \textbf{步骤}:
\begin{enumerate}
\item \textbf{应用 Hodge 对偶}:
\[
*\omega = P\,(*dx) + Q\,(*dy) + R\,(*dz)
\]
得到一个 \textbf{2-形式}。
\item \textbf{对 \( *\omega \) 取外微分}:
\[
d(*\omega)
\]
得到一个 \textbf{3-形式}。
\item \textbf{再次应用 Hodge 对偶}:
\[
*d(*\omega)
\]
得到一个 \textbf{0-形式}(标量)。
\end{enumerate}
- \textbf{结果}:
\[
*d(*\omega) = \frac{\partial P}{\partial x} + \frac{\partial Q}{\partial y} + \frac{\partial R}{\partial z} = \operatorname{div} \vec{F}
\]
- \textbf{总结}:\textbf{散度运算}对应于对 1-形式应用组合算子 \( *d* \)。
\subsubsection{旋度与微分形式}
- \textbf{向量场对应的 1-形式}:
\[
\omega = P\,dx + Q\,dy + R\,dz
\]
- \textbf{步骤}:
\begin{enumerate}
\item \textbf{对 \( \omega \) 取外微分}:
\begin{align*}
d\omega &= \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) dx \wedge dy \\
&\quad + \left( \frac{\partial R}{\partial y} - \frac{\partial Q}{\partial z} \right) dy \wedge dz \\
&\quad + \left( \frac{\partial P}{\partial z} - \frac{\partial R}{\partial x} \right) dz \wedge dx
\end{align*}
得到一个 \textbf{2-形式}。
\item \textbf{应用 Hodge 对偶}:
\[
*d\omega = \left( \frac{\partial R}{\partial y} - \frac{\partial Q}{\partial z} \right) dx + \left( \frac{\partial P}{\partial z} - \frac{\partial R}{\partial x} \right) dy + \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) dz
\]
得到一个 \textbf{1-形式}。
\end{enumerate}
- \textbf{对应的向量场}:
\[
\operatorname{curl} \vec{F} = \left( \frac{\partial R}{\partial y} - \frac{\partial Q}{\partial z} \right) \vec{i} + \left( \frac{\partial P}{\partial z} - \frac{\partial R}{\partial x} \right) \vec{j} + \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) \vec{k}
\]
- \textbf{总结}:\textbf{旋度运算}对应于对 1-形式取外微分并应用 Hodge 对偶,即:
\[
\operatorname{curl} \vec{F} = (*d\omega)^\sharp
\]
其中 \( \sharp \) 表示将 1-形式转换为向量场。
\subsubsection{总结}
- \textbf{梯度}:
- 对标量函数(0-形式)取外微分 \( df \),对应梯度向量场 \( \nabla f \)。
- \textbf{散度}:
- 对 1-形式应用组合算子 \( *d* \),得到散度 \( \operatorname{div} \vec{F} \)。
- \textbf{旋度}:
- 对 1-形式取外微分 \( d\omega \) 并应用 Hodge 对偶 \( * \),得到旋度 \( \operatorname{curl} \vec{F} \)。
- \textbf{统一框架}:
- 微分形式和外微分提供了统一的数学框架,方便在高维空间中推广和应用。
\subsubsection{附录:重要公式汇总}
\begin{enumerate}
\item \textbf{梯度}:
\[
\nabla f = (df)^\sharp
\]
\item \textbf{散度}:
\[
\operatorname{div} \vec{F} = *d(*\omega)
\]
\item \textbf{旋度}:
\[
\operatorname{curl} \vec{F} = (*d\omega)^\sharp
\]
\item \textbf{拉普拉斯算子}(对于标量函数):
\[
\Delta f = \operatorname{div}(\nabla f) = *d*d f
\]
\end{enumerate}
`
)
_以下内容是2023年春王晓峰老师微积分A2的课程内容:_
=== 王晓峰如是说
对于微分形式$omega$
$
integral_(partial Omega) omega = integral_Omega dd(omega)\
$
==== 向量场与一阶微分形式、梯度
$
vb(e_i) "基底向量", dd(x^i) "对偶基", dd(x^i)(vb(e_j)) = delta^i_j\
$
$vb(X)=sum X^i vb(e_j)$和$omega=sum A_i dd(x^i)$对应,有
$
omega_(vb(X)) = vb(X) dot vb(v) ,forall vb(v)\
A_j = omega(vb(e_j)) = sum_i X^i vb(e_i) dot vb(e_j) = X^j g_(i j)\
$
从而
$
omega_(vb(X)) = sum_j A_j dd(x^j) = sum_(i,j) X^i g_(i j) dd(x^j)\
vb(X)_omega = sum_i X^i vb(e_i) = sum_(i,j) A_j g^(i j) vb(e_i)\
$
有微分和梯度
$
dd(f) = sum_i partialderivative(f,x^i) dd(x^i)\
grad f = sum_(i,j) partialderivative(f,x^i) g^(i j) vb(e_j)\
$
函数的微分与坐标和度量无关、梯度有关。正交坐标系下
$
grad f = sum_i 1/norm(vb(e_i)) partialderivative(f,x^i) vu(e_i) = sum_i 1/sqrt(g_(i i)) partialderivative(f,x^i) vu(e_i)\
$
由此可以得到球、柱、直角坐标系下的梯度。
==== 向量场与二阶微分形式、旋度
$
vb(e_1), vb(e_2), vb(e_3) "基底向量", dd(x^1), dd(x^2), dd(x^3) "对偶基"
$
向量场$vb(X)=X^1 vb(e_1) + X^2 vb(e_2) + X^3 vb(e_3)$对应二阶微分形式
$
omega = A_1 dd(x^2) and dd(x^3) + A_2 dd(x^3) and dd(x^1) + A_3 dd(x^1) and dd(x^2)\
$
即
$
omega(vb(u), vb(v)) = vb(X) dot (vb(u) times vb(v))
$
从而*向量场和二阶微分形式的对应*
$
A_1 = omega(vb(e_2), vb(e_3)) = X^1 vb(e_1) dot (vb(e_2) times vb(e_3))
$
对于一阶微分形式$eta = sum B_i dd(x^i)$,有
$
dd(eta) = sum dd(B_i) and dd(x^i) = sum_"cyc" (partialderivative(B_i,x^j) - partialderivative(B_j,x^i)) dd(x^i) and dd(x^j)\
$
对应的
$
curl vb(X) = sum_"cyc" (partialderivative(sum_(k=1)^3 X^k g_(k i),x^j) - partialderivative(sum_(k=1)^3 X^k g_(k j),x^i)) vb(e_i)\
$
正交坐标系下
$
curl vb(X) = 1/(norm(vb(e_1)) norm(vb(e_2)) norm(vb(e_3))) mat(
vb(e_1), vb(e_2), vb(e_3);
partialderivative(,x^1), partialderivative(,x^2), partialderivative(,x^3);
X^1 norm(vb(e_1))^2, X^2 norm(vb(e_2))^2, X^3 norm(vb(e_3))^2;delim: "|"
)\
$
可以得到球、柱、直角坐标系下的旋度。
==== 向量场与三阶微分形式、散度
向量场$vb(X)=X^1 vb(e_1) + X^2 vb(e_2) + X^3 vb(e_3)$对应二阶微分形式
$
omega = A_1 dd(x^2) and dd(x^3) + A_2 dd(x^3) and dd(x^1) + A_3 dd(x^1) and dd(x^2)\
$
有三阶微分形式
$
dd(omega) = sum_i partialderivative(A_i,x^i) dd(x^1) and dd(x^2) and dd(x^3)\
$
从而散度
$
dd(omega) (vb(e_1), vb(e_2), vb(e_3)) = div vb(X) vb(e_1) dot (vb(e_2) times vb(e_3))\
$
从而
$
div vb(X) = 1/(vb(e_1) dot (vb(e_2) times vb(e_3))) sum_(i=1)^3 partialderivative(X^i vb(e_1)dot (vb(e_2)times vb(e_3)),x^i) = 1/sqrt(det G) sum_(i=1)^3 partialderivative(X^i sqrt(det G),x^i)\
$
在正交坐标系下
$
div vb(X) = 1/(norm(vb(e_1)) norm(vb(e_2)) norm(vb(e_3))) sum_(i=1)^3 partialderivative(X^i norm(vb(e_1)) norm(vb(e_2)) norm(vb(e_3)),x^i)\
$
可以得到球、柱、直角坐标系下的散度。 |
|
https://github.com/feiyangyy/Learning | https://raw.githubusercontent.com/feiyangyy/Learning/main/linear_algebra/n维向量空间及子空间.typ | typst | #set text(
font: "New Computer Modern",
size: 6pt
)
#set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
#set heading(numbering: "1.")
= 向量空间
行列式只能判别n个未知量,n个方程的线性方程组的解的情况,并且,当行列式为0时,n维向量空间就是从另外一个角度,来研究解的情况。
取数域K上任意n个数组成的有序数组:
$
K^n ={(a_1, a_2, ... ,a_n) | a_i in K }
$
如果$K^n$中的两个元素有$a_i = b_i$. 则称这两个元素相等。
加法定义:
$
(a_1, a_2, ..., a_n) + (b_1, b_2, ..., b_n) = ((a_1+b_1),(a_2+b_2),..., ((a_n+b_n)))
$
标量乘法:
$
k(a_1,a_2, ...,a_n) = (k a_1, k a_2, ..., k a_n)
$
#let a = math.bold($alpha$);
#let b = math.bold($beta$);
#let c = math.bold($gamma$)
对于#a、#b、#c $in K^n$,容易验证以下8条规则:
加法的4条法则:
1. 加法交换律 $#a + #b = #b + #a$
2. 加法结合率 $#a + #b + #c = (#a + #b) + #c$
3. $bold(0) + #a = #a + bold(0) = #a$, 我们把$bold(0)$称为0元,也是加法的单位元
4. 对于$#a$, 定义$-#a = (-a_1,-a_2, ..., -a_n) -> #a + (-#a) = bold(0)$, $-#a$ 称作$#a$的负元
乘法的4条法则:
5. $1 #a = #a$,注意这里的1是标量
6. $(k l)#a = k(l#a)$
7. $(k+l)#a = k#a + l#a$
8. $k(#a + #b) = k#a + k#b$
以上定义及其规律,我们可以从平面或者立体向量联想得出,同样的后续的向量空间,在1维时,对应的就是一条直线,在2维时,对应的就是一个平面空间,在3维时就是一个立体空间,在4维时就是一个时空空间,更高维则不能从物理角度出发去联想了。
我们也可以把系数矩阵的每一行当做一个行向量,那么矩阵的初等行变换(不包括行交换),就对应于上面的加法、标量乘法运算。
以上8条法则,实际上是被定义出来的(参考邱维声 高等代数下册 第8章),这里不做介绍了
== 向量空间定义
数域K上所有的n元有序数组组成的集合$K^n$, 连同上述定义的运算规则一起,称作数域K上的一个#highlight()[n维向量空间x,$K^n$中的元素称为n维向量]。对于$#a = (a_1,a_2, ...,a_i, ..., a_n)$, $a_i$ 叫做$#a$的第i个分量
上述线性空间中的n元有序数组可以写成行或者写成列的形式,写成行时,是行向量;写成列时,是列向量,列向量可以看成行向量的转置。
给定一个系数数组$(k_1,k_2, ...,k_n)$,将其与n个向量分别乘加$k_1 (#a _1) +k_2 (#a _2) + ... + k_n (#a _n) = bold(b)$, 则称$bold(b)$ 是向量组$(#a _1,#a _2, ..., #a _n) $的一个线性组合。 在$K^n$中,如果$#b in K^n$, 并且存在一组系数$(k_1,k_2, ...,k_n)$, 能满足:$k_1 (#a _1) +k_2 (#a _2) + ... + k_n (#a _n) = #b $, 则就称$#b$ 可以被向量组$(#a _1,#a _2, ..., #a _n) $线性表示
现在我们再看线性方程组:
$
cases(
a_11 x_1 + a_12 x_2 + ... + a_(1 n)x_n = b_1,
a_21 x_1 + a_22 x_2 + ... + a_(2 n)x_n = b_2,
dots.v,
a_(m 1) x_1 + a_(m 2) x_2 + ... + a_(m n)x_n = b_m,
)
$
注意,这里可能$m!=n$,我们将系数矩阵的每1列都看做一个列向量,把$x_1,x_2, ..., x_n$,则方程组就可以表达为:
$x_1 bold(a_1) + x_2 bold(a_2) + ... + x_n bold(a_n) = bold(b)
$
#highlight()[即常数项组成的向量$bold(b)$ 能否被列向量组$bold(a_1), bold(a_2), ... bold(a_n)$线性表示。]
(此处的线性表示,不限定系数是否全为0,当系数全为0时,则表示的向量一定是一个0向量)
== 向量空间的子空间 (imortant)
对于任意$#a, #b in U$, U是$K^n$的一个非空子集,如果满足:
1. 加法封闭 $#a + #b in U$
2. 标量乘法封闭 $l #a in U$
则就称U是$K^n$的一个线性子空间,或者子空间,向量组$bold(a_1), bold(a_2), ... bold(a_n)$ 的所有线性组合组成了$K^n$的一个子空间,称其为$bold(a_1), bold(a_2), ... bold(a_n)$#highlight()[张成的一个子空间],记作$<bold(a_1), bold(a_2), ... bold(a_n)>$
所以就有以下推论:
$x_1 bold(a_1) + x_2 bold(a_2) + ... + x_n bold(a_n) = bold(b)
$ 有解 $<->$ $bold(b)$ 可以由$bold(a_1), bold(a_2), ... bold(a_n)$线性表示 $<->$$ bold(b) in <bold(a_1), bold(a_2), ... bold(a_n)>$ 此处解可能不唯一,注意这里无穷多解的情况被合并到有解中;在前面的行列式章节内,无穷多解的情况被合并到无解中。
向量空间和线性空间的关系:
1. 向量空间只封闭了空间内的加法和标量乘法,而线性空间则封闭了更多运算。对于子空间同理。向量空间可以认为是线性空间的子集或者特例
2. 向量空间,通常是有限维的
3. 向量空间中的元素都是向量, 线性空间中的元素可以是向量、矩阵、或者其他东西
= 线性相关的向量组和线性无关的向量组(important)
== 向量组线性无关和相关的定义
#let inr_express=$k_1 bold(a_1) + k_2 bold(a_2) + ... + k_n bold(a_n)$
#let parameters=$(k_1,k_2, ..., k_n)$
#let vectors=$(bold(a_1) , bold(a_2), ..., bold(a_n) )$
#let zv = $bold(0)$
#let ceq = $<->$
类似于我们前面提到的齐次线性方程组,对于公式:$#inr_express = bold(0)$, 如果有不全为0的系数$#parameters$,使得此公式成立,则称$#vectors$是#highlight()[线性相关]的;否则,即只有$k_1=k_2 = ... = k_n = 0$ 使得此公式成立,则称#vectors 是#highlight()[线性无关]的
#highlight(fill:red)[线性无关时,如果我们尝试用$(bold(a_k))\\ bold(a_i)$ 表示$bold(a_i)$, 则需要除0,因此不存在任何系数能使得$(bold(a_k))\\ bold(a_i)$ 表示$bold(a_i)$, 这就是无关的内涵]
=== 从其他角度理解向量组无关和相关
线性相关和线性无关是线性代数中最为重要的概念之一,有以下几个方面的内涵(以下的向量组表示中,向量数$>1$)
1. 从线性组合来看:
- 线性相关:#vectors 可以通过不全为0的系数序列,组合成$bold(0)$向量
- 线性无关:#vectors 只有全为0的系数序列,才能组合成$bold(0)$向量
2. 线性表示
- 线性相关,#vectors 中至少某一个向量可以表示为其他向量的线性组合(考虑将被表示的向量移动到等式右侧即可得证)
- 线性无关,#highlight()[每一个向量都不能被其他向量线性表示]
- 如果向量$bold(b)$可以被#vectors 线性表示,那么
- #vectors 线性相关 #ceq $bold(b)$ 被表示的方式不唯一
- 。。。。。 线性无关 #ceq $bold(b)$ 被表示的方式唯一
- 即线性方程组$#vectors=bold(b)$ 在有解时,解的区分情况
3. 齐次线性方程组
- 齐次线性方程组的列向量组是线性相关的$<->$齐次线性方程组有非0解
- ......................线性无关的..$<->$ ...... 只有0解
4. 行列式(行列式限定矩阵为方阵),#vectors 中每个向量需要是n维向量
- 以#vectors 构成的矩阵的行列式等于0 $<->$ #vectors 线性相关,这个可以由行列式与齐次线性方程组解的关系得出,同时结合3
- 。。。。。。。。。。。。不等于0 $<->$ #vectors 线性无关
5. 如果#vectors 中的一部分$(bold(a_i), ..., bold(a_s))$ 线性相关,则整体线性相关
- 如果 #vectors 整体线性无关,则 其任意一部分也线性无关 (考虑通过反证法),其实就是命题5. 的#highlight()[逆否命题]
6. 如果#vectors 整体线性无关,则在每个向量上扩充其维度(相当于增加方程组个数),则扩充后的延伸组依然线性无关,这个证明很自然,因为使得扩充后的向量组的每个向量前$n$个分量,使得#inr_express = $bold(0)$ 的条件只有#parameters 全为0(这是定义),所以扩充后的向量组 使得该公式成立的条件依然只有#parameters 全为0
- 如果#vectors 线性相关,则对于其中每个向量减去m个分量,得到的缩短向量组,也是线性相关的(6.的逆否命题)
==== 6 的证明
下面 证一下6.
#let cvectors=$(bold(c_1), bold(c_2), ..., bold(c_n))$
对于#vectors $in K^n$, 设其线性无关,那么设#cvectors $in K^(n+m)$ 是扩充后的向量组,根据线性无关定义:$
cases(k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
dots.v,
k_1 a_(n 1) + k_2 a_(n 2) + ... + k_n a_(n n) = 0,
) <->^(扩 充 后) cases(
k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
dots.v,
k_1 a_(n 1) + k_2 a_(n 2) + ... + k_n a_(n n) = 0,
k_1 a_(n+1, 1) + k_2 a_(n+1, 2) + ... + k_n a_(n+1, n) = 0,
dots.v,
k_1 a_(n+m, 1) + k_2 a_(n+m, 2) + ... + k_n a_(n+m, n) = 0,
)
$
根据线性无关定义,使得扩充后的前n个等式成立的条件,只有#parameters 全为0,从而扩充后的向量组依然是线性无关的
对于其逆否命题,我们设#vectors 是线性相关的,即
$
cases(k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
dots.v,
k_1 a_(n 1) + k_2 a_(n 2) + ... + k_n a_(n n) = 0,
) <->^(缩 短 m)
cases(k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
k_1 a_(11) + k_2 a_(12) + ... + k_n a_(1n) = 0,
dots.v,
k_1 a_(n-m, 1) + k_2 a_(n-m, 2) + ... + k_n a_(n-m, n) = 0,
)
$
根据线性相关定义,存在不全为0的#parameters 使得上述任意一项等式成立,从而对于缩短后的等式组也成立,从而得出缩短后的向量组,依然线性相关
==== 2. 的证明
这里再给一下 2. 的第三部分的证明
1. 假设$bold(b)$ 可以被#vectors 线性表出,并且#vectors 线性相关,那么就有$t_1 bold(a_1) + t_2 bold(a_2) + ... t_n bold(a_n) = bold(b)$,同理,因为#vectors 线性相关,则$#inr_express = 0$ 中的系数$(k_1,k_2, ..., k_n)$ 不全为0, 那么令$m_i=(t_i + k_i)$, 则$m_i bold(a_1) + ... + m_i bold(a_n) = k_1 bold(a_1) + ... + k_n bold(a_n) + t_1 bold(a_1) + ... + t_n bold(a_n) = bold(0) + bold(b) = bold(b)$, 又因为$(k_i)$ 不全为0,那么$(m_i) != (t_i)$. 从而$bold(b)$ 表出方式不唯一
2. 假设$bold(b)$ 可以被#vectors 线性表出,并且#vectors 线性无关,我们假设b 有两个不同的表出方式,其系数$(s_i)$ 和$(t_i)$, 令$(m_i) = (s_i - t_i)$, 那么就有$sum_i m_i bold(a_i) = sum_i s_i bold(a_i) - sum_i t_i bold(a_i) = bold(b) - bold(b) = bold(0)$,又因为#vectors 线性无关,则#inr_express 中的系数$0 = (k_i) = (m_i) = (s_i - t_i) => s_i = t_i$,与假设矛盾,从而$bold(b)$的表出方式唯一
补充2.的正面的主要目的是这个正面过程和后面的线性方程组的解联系比较紧密,同时我们可以看到,在代数领域,我们主要通过抽象化的各种解而不是具某个数值的解做逻辑推理。
=== 命题 1 设向量组#vectors 线性无关,则$bold(beta)$ 可以被#vectors 表示的充要条件是$[bold(beta), #vectors]$ 线性相关。下面只证明充分性
证,设#vectors 线性无关,且$[bold(beta), #vectors]$线性相关,则根据定义有:$#inr_express + l bold(beta) = bold(0)$,如果$l = 0$,则$#inr_express = bold(0) -> 与 已 知 条 件 矛 盾$,因此$l!=0$,从而有:$bold(beta) = -(#inr_express)/l$
== 极大线性无关组
=== 1. 极大线性无关组定义
假设$bold(beta)$可以被#vectors 线性表示,如果#vectors 是线性无关组,则表示方式唯一(见前述推论2), 如果#vectors 线性相关,则表示方式不唯一。如果我们能在#vectors 找到一个部分组是线性无关的,当从其余向量中往该组中再添加一个向量时,则该组变成线性相关的。这个部分组就称为#vectors 的一个极大无关组。#highlight()[极大无关组可能不唯一]
=== 2. 向量组等价
#let bvectors=($(bold(b_1), bold(b_2), ..., bold(b_r))$)
#let cvectors=($(bold(c_1), bold(c_2), ..., bold(c_s))$)
如果向量组#vectors 中的每一个向量$bold(a_i)$ 都可以被#bvectors 线性表示,同时#bvectors 中的每个向量都可以被#vectors 线性表示。#highlight()[则称两个向量组等价, 记作$#vectors =^(~) #bvectors$], 注意定义中,#highlight()[是每一个向量都可以被另外一者线性表示]
等价关系是$K^n$中的向量组之间的一种关系,这种关系有以下性质:
1. 反身性: 任何一个向量组都与自身等价
2. 对称性: $#vectors =^(~) #bvectors <-> #bvectors =^(~) #vectors$
3. 传递性: $#vectors =^(~) #bvectors, #bvectors =^(~) #cvectors => #vectors =^(~) #cvectors$
下面对第3点证明:
$
#vectors =^(~) #bvectors => bold(a_i) = sum_(j = 1)^(r)b_(i j)bold(b_j);\
#bvectors =^(~) #cvectors => bold(b_j) = sum_(k = 1)^(s) c_(j k) bold(c_k);\
=> bold(a_i) = sum_(j = 1)^(r)b_(i j)[sum_(k = 1)^(s) c_(j k) bold(c_k)]
$
我们对这个式子做一些展开
$
bold(a_i) = sum_(j = 1)^(r)b_(i j)[sum_(k = 1)^(s) c_(j k) bold(c_k)] = sum_j b_(i j) [c_(j 1)bold(c_1) + c_(j 2) bold(c_2) + ... + c_(j_s) bold(c_s)] =sum_j b_(i j)(c_(j 1)) bold(c_1) + sum_j b_(i j)(c_(j 2)) bold(c_2) + ... + sum_j b_(i j) (c_(j s)) bold(c_s) = (k_1 bold(c_1) + k_2 bold(c_2) + ... + k_s bold(c_s))
$
反之亦然
=== 命题1. 向量组与其极大线性无关组等价
#let inr_group = $(bold(a_1), bold(a_2), ..., bold(a_m))$
1. 根据极大线性无关组定义, 该向量组可以被原向量组直接线性表示
2. 根据极大线性无关组定义,设线性无关组为#inr_group, 对于$m<j<=n, bold(a_j)$一定可以被该无关组线性表示,那么其整体都可以被该无关组线性表示
- 综上所述,该命题成立
=== 推论1. 向量组的任意两个极大线性无关组等价:
- #highlight()[由性质3.(传递性) + 命题1. 可得证]
=== 推论2. $bold(beta)$ 可以由#vectors 线性标出 当且仅当 $bold(beta)$ 可以被#vectors 的一个极大线性无关组线性表出
- #vectors 等价于其一个极大线性无关组,根据传递性可知$bold(beta)$ 可由该无关组线性表出;同理,当$bold(beta)$可被一个极大无关组标出时,根据 推论1, 其一定可以被#vectors 线性表出
=== 引理1. 若#bvectors 可以被 #vectors 线性表示,且 $r>n$,则#bvectors 线性相关
证明(important)
如果 #bvectors 可被#vectors 线性表出,那么:
$bold(b_1) = a_(11)bold(a)_1 + a_(12)bold(a)_2 + ... + a_(1 n) bold(a)_n \
bold(b_2) = a_(2 1)bold(a)_1 + a_(2 2)bold(a)_2 + ... + a_(2 n) bold(a)_n\
dots.v\
bold(b_r) = a_(r 1)bold(a)_1 + a_(r 2)bold(a)_2 + ... + a_(r n) bold(a)_n => x_1 bold(b_1) + x_2 bold(b_2) + ... + x_r bold(b_r) = \
x_1(a_(11)bold(a)_1 + a_(12)bold(a)_2 + ... + a_(1 n) bold(a)_n ) + x_2(a_(2 1)bold(a)_1 + a_(2 2)bold(a)_2 + ... + a_(2 n) bold(a)_n) + ... + x_r (a_(r 1)bold(a)_1 + a_(r 2)bold(a)_2 + ... + a_(r n) bold(a)_n) = \
(a_11 x_1 + a_21x_2 + ... + a_(r 1)x_r)bold(a)_1 + (a_12 x_1 + a_22 x_2 + ... + a_(r 2) x_r)bold(a)_2 + ...+ (a_(1 n) x_1 + a_(2 n) x_2 + ... + a_(r n)x_r) bold(a_n) <- 共 n 项
$
若$bvectors$ 线性相关,那么存在一组不全为0的数$(x_1, x_2, ..., x_r)$,使得$ x_1 bold(b_1) + x_2 bold(b_2) + ... + x_r bold(b_r) = bold(0)$. 对应于展开式中,我们将设每一项的系数的结果都为0,这样整体就是一个$bold(0)$, 按照这个思路,我们构造这样的方程:
$
cases(
a_11 x_1 + a_21 x_2 + ...+a_(r 1) x_r = 0,
a_12 x_1 + a_22 x_2 + ...+a_(r 2) x_r = 0,
dots.v,
a_(1 n) x_1 + a_(2 n) x_2 + ...+a_(r n) x_r = 0,
)
$ 我们得到了一个有r个未知量,有n个方程的齐次线性方程组,(观察系数a的指标,从1到n,故而有n个方程),因为$r>n$ 所以,该方程组必有非0解。取任意一个非0解$(k_1, k_2, ..., k_r)$, 代入 $ x_1 bold(b_1) + x_2 bold(b_2) + ... + x_r bold(b_r)$的展开式中, 有:
$
(a_11 k_1 + a_21 k_2 + ... + a_(r 1)k_r)bold(a)_1 ...+ (a_(1 n) k_1 + a_(2 n) k_2 + ... + a_(r n)k_r) bold(a_n) = 0bold(a)_1 + 0bold(a)_2 + ... + 0bold(a)_n = bold(0)
$
得证。这里要注意的是#vectors 并不要求是线性无关的
从引理1 可以推出(逆否命题)
=== 推论3 设#bvectors 可由 #vectors 线性表出,若 #bvectors 线性无关,则 $r <= n$
除了逆否命题外,可以考虑引理1.中得到的系数方程组 只有0解的条件必须满足$n >= r$(必要条件,但不充分), 从而得证
=== 推论4. 两个等价的线性无关的向量组,向量个数相等
从推论3可以得出, 即$#bvectors$ 线性无关且可以被#vectors 表示,则$r <= n$,又$#vectors$ 线性无关且可被#bvectors 表出,则$n <= r$,则$n=r$
=== 推论5. 向量组的任意两个极大无关组的向量个数相等
结合 推论4. + 推论1. 可得证。 推论1. 说明了两个极大无关组可以互相标出,推论4.结合了极大无关组得线性无关定义,限定了两者个数相等
== 定义 #highlight(fill: green)[向量组的极大线性无关组所含向量个数成为该向量组的秩,全为0向量的向量组的秩规定为0,记作$r a n k(#vectors)$]
=== #highlight(fill:red)[命题2. #vectors 线性无关的充要条件是它的秩等于向量个数]
证:
因为#vectors 线性无关,因此其极大线性无关组是其自身$=>$ $r a n k #vectors = n$
命题2 表明了秩的重要性,通过一个自然数就可以分析出一个向量组是否线性无关,在结合线性无关的概念及含义,可以直接得到很多结论。
== 秩的比较
=== 命题3. 如果(1)可以被(2) 线性表出,则前者的秩小于或等于后者的秩 即$r a n k{(1)} <= r a n k {(2)}$
1. 设#bvectors 是(1)的一个极大线性无关组,#vectors 是(2)的一个极大线性无关组,由命题1,可知#bvectors 等价于(1),而(1) 又可以被 (2) 线性表出,(2) 等价于 #vectors, 则可知#bvectors 可以被 #vectors 线性表出,根据推论3. #bvectors 向量个数小于 #vectors 向量个数,即$r a n k{(1)} <= r a n k {(2)}$
=== 命题4. 等价的向量组有相等的秩(必要但不充分)
证明:若两个向量组等价,则可以互相表出,则其设其极大无关组分别为$a$和$b$, 那么a被b表示时,则$r a n k(a) <= r a n k(b)$,同理,b 被a 表出时$r a n k(b) <= r a n k(a)$ 从而$r a n k(a) = r a n k(b)$,从而得证。
但反过来不一定。秩可以理解为向量组降维的特征,不能直接代表向量组本身,并且上面的向量组讨论秩时,也没有限定向量的维度
== #highlight(fill:red)[向量空间的基、标准基以及维数(最重要概念)]
原书这部分内容有点循环引用的意思,即为了说明A,需要引入B,而B的定义又依赖A。所以有点生涩
定义1. 向量空间的基
设U是$K^n$的一个子空间, 并且$#vectors in U$, #vectors 同时能满足以下性质:
1. #vectors 线性无关
2. U 中任意向量都可以被#vectors 线性表出
此时,我们称#vectors 是 U的一个#highlight(fill: red)[基]
(注:如果#vectors 每个向量的模长都是1,那么这个基就称为U的一个标准基,如果#vectors 是标准基,并且满足$bold(a_i)dot bold(a_j) = 0$ 这样的基称为标准正交基)
#let KSpace =$K^n$
=== 定理1. $K^n$的任意非零子空间都有一个基
这里补充一个命题, $K^n$ 中的线性无关组所含向量个数至多为$n$
证,利用反证法,不仿设$(bold(a_1),bold(a_2), ..., bold(a_n), bold(a_(n+1)))$ 是$K^n$的一个线性无关组,那么对于方程组:
$cases(
x_1a_(11) + x_2a_(21) + ... + x_n(a_(n 1)) + x_(n+1)(a_(n+1, 1)) = 0,
x_1a_(12) + x_2a_(22) + ... + x_n(a_(n 2)) + x_(n+1)(a_(n+1, 2)) = 0,
dots.v,
x_1a_(1n) + x_2a_(2n) + ... + x_n(a_(n n)) + x_(n+1)(a_(n+1, n)) = 0,
)
$
应当只有0解,但是上面的方程组未知量个数(n+1)多于方程个数(n), 因此必有非0解,取任意非0解$(k_1, k_2, ..., k_(n+1))$ 均能使得$k_1(bold(a_1)) + ... + k_(n+1)(bold(a_(n+1))) = bold(0)$ 成立,则其该向量组线性相关,与假设矛盾,因此命题得证
接下来证定理1.
从U中取一个非0向量$bold(a_1)$, 若$<bold(a_1)> != U$, 那么必然可以从U中再取一个$bold(a_2)$; 若$<bold(a_1)> = U$, 那么$(a_1)$ 就是U的一个基。其不可以被$bold(a_1)$线性表出。若$<bold(a_1), bold(a_2)> !=U$, 那么可以取到$bold_(a_3)$ 不可以被$(bold(a_1), bold(a_2))$ 线性表出,如果$<bold(a_1), bold(a_2)> =U$,那么$(bold(a_1), bold(a_2))$ 就是U的一个基,依次类推。又根据上面的命题($K^n$的线性无关组所含向量数至多为n),这个步骤至多可以重复到n次,不妨设为s次,那么$(bold(a_1), bold(a_2), ..., bold(a_s))$ 就是U的一个基。从而得证。
=== 定理2. $K^n$的非零子空间U的任意两个基所含向量个数相等
根据基的定义,设U的两个基分别为$#vectors$ 和#bvectors, 那么$#vectors =^(~) #bvectors$, 又两者线性无关,根据(极大线性无关组/推论4. 两个等价的线性无关组所含向量个数相同),定理得证
=== 定义2. $K^n$ 非0子空间U的一个基所含向量个数称为U的维数,记作$dim_K U$ 或者$dim U$
#highlight()[零子空间的维数定义为0]
#highlight(fill: green)[这里特别要注意,U的维数是基所含向量个数决定的,而不是向量的维数]
举例来说,三维向量空间中的一个平面上的两个不共线向量所构成的子空间就是一个平面空间,其维数为2,而其中的向量维数都是3(或者说是3维向量)
$K^n$ 是其自身的子集,我们回顾$K^n$的定义:$[(a_1,a_2, ...,a_n) | a_i in K]$ 所构成的所有集合,所以,其一个标准基是:$
[mat(1;0;...;0;), mat(0;1;...;0), ..., mat(0;0;...;1)] <->共 n 项
$,因此$dim(K^n) = n$
=== 基和坐标(important)
设$vectors$ 是U的一个基,那么U下的任意向量$bold(alpha)$ 都可以表示为:$bold(alpha) = a_1 bold(a_1) + a_2 bold(a_2) + ... a_n bold(a_n)$. 我们把有序数组$(a_1, a_2, ..., a_n)$ 称为在基$vectors$ 下的#highlight(fill: red)[坐标]
#let bases=$(bold(a_1), bold(a_2), ..., bold(a_r))$
=== 命题1. 设$dim U = r$,则U中任意$r+1$个向量(组成的向量组)线性相关
由维数的定义$->$ U的一个基的向量组个数为$r$ $->$ 由极大无关组/引理1 即可得证
=== 命题2. 设$dim U = r$,则U中任意r个线性无关的向量构成一个基
在定理1.的证明过程中,我们逐步推导,证明了U中至少有一个基。我们任取线性无关向量组$(bold(a_1), bold(a_2), ..., bold(a_r))$,该向量组扩充一个U中的向量$bold(beta)$, 根据命题1,则$(bold(a_1), bold(a_2), ..., bold(a_r), bold(beta))$ 线性相关($dim U = r->$ (r+1)个向量线性相关)
=== 命题3. 设$dim U = r$, 如果U中任意向量可被#bases 线性表出,则#bases 是U的一个基
#let o_bases=$(bold(b_1), bold(b_2), ..., bold(b_n))$
证:
取U中的一个基 #o_bases, 那么任意$bold(b_i)$可以被#bases 线性表出, 根据(秩的比较/推论3,向量组A可被向量组B线性表出$->$ rank(A)$<=$ rank(B)),从而有 $ r = r a n k(#o_bases) <= r a n k (#bases) <= r -> r a n k (#bases) = r$, 因此#bases 是线性无关的(根据秩的定义直接可得),进而是U的一个基
=== 命题4. 设U W都是#KSpace 的子空间,并且$U subset.eq W$,那么 $dim U <= dim W$
#let bases=($bold(a_1), bold(a_2), ..., bold(a_r)$)
#let w_bases=($bold(w_1), bold(w_2), ..., bold(w_t)$)
#let rb = $r a n k (#bases)$
#let rw = $r a n k (#w_bases)$
证: 取 U 的一个基 #bases, 取W的一个基#w_bases, 因为$U subset.eq W$, 所以U中的向量都可以被W的基表示,进而 #bases 可以被#w_bases 表示,根据秩的定义及相关推论可得$r = #rb <= rw = t -> r<=t <-> dim U <= dim W$
=== 命题5. 设U W都是#KSpace 的子空间,并且$U subset.eq W$,如果$dim U = dim W$,则$U = W$
根据命题4. 证明过程,当$dim U = dim W$时,即$r = t$,即$bases$是W中的一个向量个数为$r=t$线性无关组,再根据本节命题2,#bases 就是W的一个基
=== 定理3. 向量组#vectors 的一个极大线性无关组是#vectors 生成向量空间的一个基
#let space = $<bold(a_1), bold(a_2), ..., bold(a_n)>$
#let expr_a = $p_j bold(a_j)$
#let expr_b = $k_i bold(a_i)$
#let rank = $r a n k $
证:
根据极大线性无关组的定义,#vectors 中任意向量都可以被其极大无关组#bases 表出,那么空间#space 表示的任意向量$#b = sum_i #expr_b = sum_i k_i sum_j #expr_a =>^(交 换 求 和 顺 序) sum_(j=1)^(r) sum_i k_i #expr_a = sum_j t_j bold(a_j)$, 即#space 中的任意向量,都可以被#bases 线性表示,从而#bases 是 #space 的一个基
由定理3,我们有一些推论:
$dim #space = #rank #vectors$, 这个是数值上相等,含义上不同,前者指空间的维数,后者指向量组的秩
|
|
https://github.com/spidersouris/touying-unistra-pristine | https://raw.githubusercontent.com/spidersouris/touying-unistra-pristine/main/template/template.typ | typst | MIT License | #import "@preview/touying:0.5.3": *
#import "@preview/touying-unistra-pristine:1.1.0": *
#show: unistra-theme.with(
aspect-ratio: "16-9",
config-info(
title: [Title],
subtitle: [_Subtitle_],
author: [Author],
date: datetime.today().display("[month repr:long] [day], [year repr:full]"),
logo: image("unistra.svg"),
),
)
#title-slide(logo: image("unistra.svg"))
= Example Section Title
== Example Slide
A slide with *important information*.
#focus-slide(
theme: "neon",
[
This is a focus slide \ with theme "neon"
],
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/g-exam/0.1.0/examples/exam-minimal.typ | typst | Apache License 2.0 | #import "../g-exam.typ": g-exam, g-question, g-subquestion
#show: g-exam.with()
#g-question(point: 2)[Question 1]
#g-question(point: 1)[Question 2]
#g-question(point: 1.5)[Question 3] |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/accent_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test high base.
$ tilde(integral), tilde(integral)_a^b, tilde(integral_a^b) $
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/anchor/ligature-mark.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/template/lang.typ": thai
#import "/lib/glossary.typ": tr
#show: web-page-template
// ### Mark-to-ligature
=== #tr[ligature]上的符号
// This next positioning lookup type deals with how ligature substitutions and marks inter-relate. Suppose we have ligated two Thai characters: NO NU (น) and TO TAO (ต) using a ligature substitution rule:
下一个#tr[positioning]#tr[lookup]类型用于处理#tr[ligature]和符号之间的关系。假设我们在制作泰语#tr[character] `NO NU`(#thai[น]) 和 `TO TAO`(#thai[ต]) 的#tr[ligature]#tr[substitution]:
```fea
lookupflag IgnoreMarks;
sub uni0E19' uni0E15' by uni0E190E15.liga;
```
// We've ignored any marks here to make the ligature work - but what if there *were* marks? If the input text had a tone mark over the NO NU (น้), how should that be positioned relative to the ligature? We've taken the NO NU away, so now we have `uni0E190E15.liga` and a tone mark that needs positioning. How do we even know which *side* of the ligature to attach the mark to - does it go on the NO NU part of the TO TAO part?
在#tr[substitution]流程中我们为了让#tr[ligature]正常形成而忽略了所有符号,但如果真的有符号出现会怎么样呢?如果输入文本在 `NO NU` 上加了一个音调(#thai[น้]),在形成#tr[ligature]后这个音调会被放在哪呢?在这个过程中,原本的两个字母都消失了,只剩下了`uni0E190E15.liga`和一个需要被#tr[positioning]的音调符号。我们甚至都无法知道这个音调原本是加在哪个字母上的。
// Mark-to-ligature positioning helps to solve this problem. It allows us to define anchors on the ligature which represent where to put anchors for each component part. Here is how we do it:
#tr[ligature]上的符号#tr[positioning]可以帮助解决这个问题。它允许我们在#tr[ligature]#tr[glyph]上定义多个锚点,分别表示各个组成部件上的符号位置。写法如下:
```fea
feature mark {
position ligature uni0E190E15.liga # 声明连字中的定位规则
# 第一个部件: NO NU
<anchor 325 1400> mark @TOP_MARKS # 第一个部件的锚点
ligcomponent # 分隔不同部件
# 第二个部件: TO TAO
<anchor 825 1450> mark @TOP_MARKS # 第二个部件的锚点
;
} mark;
```
// So we write `position ligature` and the name of the ligated glyph or glyph class, and then, for each component which made up the ligature substitution, we give one or more mark-to-base positioning rules; then we separate each component by the keyword `ligcomponent`.
语法是先写 `position ligature` 加上#tr[ligature]#tr[glyph]的名字或#tr[glyph]类,然后为每个参与#tr[ligature]#tr[substitution]的部件添加一个或多个锚点衔接#tr[positioning]规则。这些部件之间使用关键字 `ligcomponent`隔开。
// The result is a set of anchors that can be used to attach marks to the appropriate part of ligated glyphs:
它的效果就是在#tr[ligature]#tr[glyph]产生了一系列可以为每个部件添加符号的锚点:
#figure(
caption: [#tr[ligature]上的符号#tr[positioning]],
placement: none,
)[#include "mark-to-lig.typ"]
|
https://github.com/markcda/unitech-infosec-basics-practice-2nd-gr | https://raw.githubusercontent.com/markcda/unitech-infosec-basics-practice-2nd-gr/master/report-titov.typ | typst | MIT License | #import "00-university-template.typ": *
#show: student_work.with(
title: "Отчёт по практике - <NAME>.",
header: "unitech-2023-header.png",
department_name: "Кафедра информационной безопасности",
institute_name: "Институт инфокоммуникационных систем и технологий",
work_type: "отчёт по учебно-лабораторной практике",
author: (name: "<NAME>", sex: "male", degree: "студент", group: "ИБО-ТС-22", nwa: "<NAME>."),
adviser: (name: "<NAME>", sex: "male", degree: "заведующий кафедрой ИБ", nwa: "<NAME>."),
city: "Королёв",
year: "2024",
table_of_contents: true,
links: (
//(type: "doc", title: "Доктрина информационной безопасности Российской Федерации (от 5 декабря 2016 г.)"),
//(type: "book", author: "<NAME>", title: "Севейна", publisher: "Литрес.Самиздат", year: "2019"),
//(type: "web", title: "Форум о технике прямого преобразования на «Сайте Кубанских Радиолюбителей»", link: "http://forum.cqham.ru/viewforum.php?f=28", access_date: "10.01.2024"),
//(type: "web", title: "Радиоприёмник прямого преобразования", link: "https://ru.wikipedia.org/wiki/Радиоприёмник_прямого_преобразования", access_date: "10.01.2024"),
//(type: "web", title: "Приёмник прямого преобразования частоты", link: "https://digteh.ru/WLL/PrmPrjamPreobr.php", access_date: "10.01.2024"),
),
)
#set heading(numbering: "1.")
= Лабораторная работа №1. КРИПТОАНАЛИЗ ШИФРА ПРОСТОЙ ЗАМЕНЫ
_Цель работы:_ Выполнить криптоанализ текста, зашифрованного шифром простой замены с применением непереборного метода вскрытия шифротекста.
*Ход работы:*
== Исходный код программы
Ниже приведён код программы по шифрованию и дешифрованию на основе шифра простой замены на языке программирования Python 3.10 (#lower([@lab-01])). Программа позволяет вводить данные с клавиатуры и файлов (тестовые данные - #lower([@lab-01-encrypt])).
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Файл lab_01.py],
[
```python
import random
import sys
from typing import Optional, Tuple, Union
RU_ALPHABET = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
ENCRYPT_ACTION = "--enc"
DECRYPT_ACTION = "--dec"
# Считывает текст из файла
def read_from_file_enc(filename: str) -> Optional[str]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')[0].lower()
return buf
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
def read_from_file_dec(filename: str) -> Optional[Tuple[str, str]]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')
s, k = buf[0], buf[1]
return (s, k)
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
# Считывает текст из терминала
def read_from_console_enc() -> str:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
return input().lower()
def read_from_console_dec() -> Tuple[str, str]:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
s = input().lower()
k = input("Введите ключ шифрования: ")
return (s, k)
# Шифрует текст предоставленным ключом
def encrypt(text: str) -> Union[str, str]:
key = []
ru_sample = list(RU_ALPHABET)
while len(ru_sample) != 0:
letter = random.choice(ru_sample)
key.append(letter)
ru_sample.remove(letter)
key = ''.join(key)
encrypted = []
for symbol in text:
pos = RU_ALPHABET.find(symbol)
if pos == -1:
encrypted.append(symbol)
continue
new_sym = key[pos]
encrypted.append(new_sym)
return ''.join(encrypted), key
# Расшифровывает текст предоставленным ключом
def decrypt(encrypted: str, key: str) -> str:
decrypted = []
for symbol in encrypted:
pos = key.find(symbol)
if pos == -1:
decrypted.append(symbol)
continue
old_sym = RU_ALPHABET[pos]
decrypted.append(old_sym)
return ''.join(decrypted)
# Уточняет, что нужно сделать
def decide_action() -> str:
def print_prompt() -> None:
print('Выберите действие: ')
print('1. Зашифровать текст с помощью ключа')
print('2. Расшифровать текст с помощью ключа')
def read_opt(allowed: list) -> Optional[int]:
try:
opt = int(input("Введите номер [1-2]: "))
if opt not in allowed:
print(f'Ошибка: опция #{opt} недоступна!')
return None
return opt
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
print_prompt()
opt = read_opt([1, 2])
while opt is None:
print_prompt()
opt = read_opt([1, 2])
match opt:
case 1:
return ENCRYPT_ACTION
case 2:
return DECRYPT_ACTION
case _:
return None
# Читает в программу текст и ключ
def read(filename: Optional[str], action: str) -> Optional[Union[Tuple[str, str], str]]:
if filename is None:
if action == ENCRYPT_ACTION:
return read_from_console_enc()
else:
return read_from_console_dec()
else:
if action == ENCRYPT_ACTION:
return read_from_file_enc(filename)
else:
return read_from_file_dec(filename)
# Начало программы
if __name__ == '__main__':
# Если программу запустить с аргументами (именем файла с текстом и ключом), ввод будет считан из файла
filename = None
action = None
for arg in sys.argv[1:]:
if arg == ENCRYPT_ACTION:
action = ENCRYPT_ACTION
elif arg == DECRYPT_ACTION:
action = DECRYPT_ACTION
else:
filename = arg
if action is None:
action = decide_action()
if action == ENCRYPT_ACTION:
s = read(filename, action)
encrypted, key = encrypt(s)
print(f'Результат: "{encrypted}"')
print(f'Ключ: "{key}"')
elif action == DECRYPT_ACTION:
s, k = read(filename, action)
decrypted = decrypt(s, k)
print(f'Результат: "{decrypted}"')
```
]
) <lab-01>
#show figure: set block(breakable: false)
#figure(
caption: [Файл lab_01_encrypt.txt],
[
```
Безумие - это когда ты делаешь одно и то же, ожидая совсем другого результата.
```
]
) <lab-01-encrypt>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
== Частотный анализ шифрованного текста
Для проведения работы был зашифрован следующий текст:
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Файл lab_01_text.txt],
[
```
Князь Багратион, выехав на самый высокий пункт нашего правого фланга, стал спускаться книзу, где слышалась перекатная стрельба и ничего не видно было от порохового дыма. Чем ближе они спускались к лощине, тем менее им становилось видно, но тем чувствительнее становилась близость самого настоящего поля сражения. Им стали встречаться раненые. Одного, с окровавленною головой, без шапки, тащили двое солдат под руки. Он хрипел и плевал. Пуля попала, видно, в рот или в горло. Другой, встретившийся им, бодро шел один, без ружья, громко охая и махая от свежей боли рукою, из которой кровь лилась, как из склянки, на его шинель. Лицо его казалось больше испуганным, чем страдающим. Он минуту тому назад был ранен. Переехав дорогу, они стали круто спускаться и на спуске увидели несколько человек, которые лежали; им встретилась толпа солдат, в числе которых были и раненые. Солдаты шли в гору, тяжело дыша, и, несмотря на вид генерала, громко разговаривали и махали руками. Впереди, в дыму, уже были видны ряды серых шинелей, и офицер, увидав Багратиона, с криком побежал за солдатами, шедшими толпой, требуя, чтоб они воротились. Багратион подъехал к рядам, по которым то там, то здесь быстро щелкали выстрелы, заглушая говор и командные крики. Весь воздух пропитан был пороховым дымом. Лица солдат все были закопчены порохом и оживлены. Иные забивали шомполами, другие подсыпали на полки, доставали заряды из сумок, третьи стреляли. Но в кого они стреляли, этого не было видно от порохового дыма, не уносимого ветром. Довольно часто слышались приятные звуки жужжанья и свистения. Что это такое? - думал князь Андрей, подъезжая к этой толпе солдат. - Это не может быть цепь, потому что они в куче! Не может быть атака, потому что они не двигаются; не может быть каре: они не так стоят.
```
]
) <lab-01-text>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
Получен был следующий результат:
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Зашифрованный текст],
[
```
хйлят ымъгмрдвй, фжэзмф йм пмчжо фжпвхдо ацйхр ймеэъв агмфвъв нимйъм, прми пацпхмртпл хйдяц, ъсэ пижемимпт аэгэхмрймл пргэитым д йдьэъв йэ фдсйв ыжив вр авгвзвфвъв сжчм. ьэч ыидёэ вйд пацпхмидпт х ивудйэ, рэч чэйээ дч прмйвфдивпт фдсйв, йв рэч ьцфпрфдрэитйээ прмйвфдимпт ыидявпрт пмчвъв ймпрвлуэъв авил пгмёэйдл. дч прмид фпргэьмртпл гмйэйжэ. всйвъв, п вхгвфмфиэййвш ъвивфво, ыэя емахд, рмудид сфвэ пвисмр авс гцхд. вй згдаэи д аиэфми. ацил авамим, фдсйв, ф гвр дид ф ъвгив. сгцъво, фпргэрдфедопл дч, ывсгв еэи всдй, ыэя гцётл, ъгвчхв взмл д чмзмл вр пфэёэо ывид гцхвш, дя хврвгво хгвфт идимпт, хмх дя пхилйхд, йм эъв едйэит. идбв эъв хмямивпт ывитеэ дпацъмййжч, ьэч пргмсмшудч. вй чдйцрц рвчц ймямс ыжи гмйэй. аэгээзмф свгвъц, вйд прмид хгцрв пацпхмртпл д йм пацпхэ цфдсэид йэпхвитхв ьэивфэх, хврвгжэ иэёмид; дч фпргэрдимпт рвиам пвисмр, ф ьдпиэ хврвгжз ыжид д гмйэйжэ. пвисмрж еид ф ъвгц, рлёэив сжем, д, йэпчвргл йм фдс ъэйэгмим, ъгвчхв гмяъвфмгдфмид д чмзмид гцхмчд. фаэгэсд, ф сжчц, цёэ ыжид фдсйж глсж пэгжз едйэиэо, д вндбэг, цфдсмф ымъгмрдвйм, п хгдхвч авыэёми ям пвисмрмчд, еэседчд рвиаво, ргэыцл, ьрвы вйд фвгврдидпт. ымъгмрдвй авсюэзми х глсмч, ав хврвгжч рв рмч, рв ясэпт ыжпргв уэихмид фжпргэиж, ямъицемл ъвфвг д хвчмйсйжэ хгдхд. фэпт фвясцз агвадрмй ыжи авгвзвфжч сжчвч. идбм пвисмр фпэ ыжид ямхваьэйж авгвзвч д вёдфиэйж. дйжэ ямыдфмид евчавимчд, сгцъдэ авспжамид йм авихд, свпрмфмид ямглсж дя пцчвх, ргэртд пргэилид. йв ф хвъв вйд пргэилид, крвъв йэ ыжив фдсйв вр авгвзвфвъв сжчм, йэ цйвпдчвъв фэргвч. свфвитйв ьмпрв пижемидпт агдлрйжэ яфцхд ёцёёмйтл д пфдпрэйдл. ьрв крв рмхвэ? - сцчми хйлят мйсгэо, авсюэяёмл х крво рвиаэ пвисмр. - крв йэ чвёэр ыжрт бэат, аврвчц ьрв вйд ф хцьэ! йэ чвёэр ыжрт мрмхм, аврвчц ьрв вйд йэ сфдъмшрпл; йэ чвёэр ыжрт хмгэ: вйд йэ рмх првлр.
```
]
) <lab-01-encrypted-text>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
Проведём частотный анализ при помощи следующей программы:
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Программа криптоанализа lab_01_freq_analysis.py],
[
```python
from collections import Counter
import lab_01
s = lab_01.read_from_file_enc('lab_01_text.txt')
encrypted, key = lab_01.encrypt(s)
print(f'Результат: "{encrypted}"')
print(f'Ключ: "{key}"')
ru_letters = ""
for symbol in encrypted:
if symbol in lab_01.RU_ALPHABET:
ru_letters += symbol
cntr = Counter(ru_letters)
size = len(ru_letters)
print('Частотный анализ:')
for ch, freq in cntr.most_common():
p = freq / size
print(f'"{ch}":\t{p}')
```
]
) <lab-01-freq-analysis>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
Результаты:
#box(height: 256pt,
columns(2, gutter: 11pt)[
#set par(justify: true)
```
"в": 0.11818181818181818
"м": 0.07832167832167833
"д": 0.07832167832167833
"э": 0.07132867132867132
"р": 0.06153846153846154
"и": 0.05944055944055944
"й": 0.05524475524475524
"п": 0.04965034965034965
"г": 0.045454545454545456
"ф": 0.03986013986013986
"х": 0.03496503496503497
"ч": 0.032167832167832165
"с": 0.032167832167832165
"ж": 0.028671328671328673
"а": 0.027972027972027972
"ц": 0.025174825174825177
"ъ": 0.022377622377622378
"т": 0.021678321678321677
"л": 0.02097902097902098
"ы": 0.01818181818181818
"я": 0.014685314685314685
"ё": 0.011188811188811189
"е": 0.01048951048951049
"з": 0.009790209790209791
"ь": 0.009790209790209791
"о": 0.007692307692307693
"у": 0.0034965034965034965
"ш": 0.002797202797202797
"б": 0.002797202797202797
"к": 0.002797202797202797
"н": 0.0013986013986013986
"ю": 0.0013986013986013986
```
]
)
Видно, что букве "в" шифротекста соответствует наивысшая частота, что похоже на букву "о". У букв "м", "д", "э" также похожи частоты на буквы "е", "ф" и "и". Также вероятно, что одна из них - это буква "а".
Приступим к подбору мелких частиц и предлогов. Буква "д" достаточно часто встречается в качестве предлога или союза, поэтому резонно предположить, что это буква "и" оригинального текста.
Часто встречается словесная единица "дч", причём $ p('ч') ≈ p('л' | 'к' | 'м') $ Предположим, что это местоимение "им".
Частоты букв "рэч" позволяют предположить, что это слово "там". Однако это не проходит проверку словом "чэйээ", поэтому делаем вывод, что "э" соответствует "е". Отсюда "чэйээ" - это "менее", тогда "й" - это "н".
Достаточно часто встречается слово "крв", и поскольку "в" предположительно равно "о", "крв" - это "это".
Расшифруем первое большое слово: "йэпхвитхв" ("не\_\_о\_\_\_о" ≈ "несколько").
На второе - "ымъгмрдвй" ("\_\_\_\_\_\_ион") - пока не хватает смысла. Как насчёт "пмчжо"? "с\_м\_\_". "всйвъв" - "о\_но\_о", причём "с" (`p ≈ 0.032`) похоже на "д" (`p ≈ 0.025`) и ещё не встречалось. Тогда "всйвъв" - это "одного".
Отсюда "ымъгмрдвй" - это "\_\_г\_\_\_ион". Всё ещё не хватает.
Берём словосочетание "дч фпргэрдимпт рвиам пвисмр": "им \_ст\_е\_ил\_сь тол\_\_ солд\_т". Отсюда "м" - это "а", "а" - "п", и словосочетание расшифровывается как "им встретилась толпа солдат".
"ымъгмрдвй" - "\_агратион", т.е. - Багратион; "ы" - это "б".
Возьмём достаточно большой кусок текста: "фаэгэсд, ф сжчц, цёэ ыжид фдсйж глсж пэгжз едйэиэо, д вндбэг" - "впереди, в дыму, уже были видны ряды серых шинелей".
Итоговый ключ дешифровки: "мыфъсэщёядохичйвагпрцнзбьеуюжткшл".
Таким образом, благодаря частотному анализу была значительно ускорена дешифровка текста без необходимости полного перебора.
== Контрольный вопрос
*Что понимается под избыточностью сообщения?*
_Ответ:_ Избыточность сообщения — это наличие в сообщении дополнительной информации, которая не является необходимой для передачи его основного смысла. Она часто используется для повышения надежности передачи данных, для предотвращения потери информации из-за шума или ошибок, а также для обеспечения ясности и понимания.
= Лабораторная работа №2. ШИФРЫ ПЕРЕСТАНОВКИ НА ПРИМЕРЕ ШИФРА КАРДАНО
_Цель работы:_ Разработать алгоритмы шифрования и дешифрования сообщений с применением решётки Кардано.
*Ход работы:*
== Исходный код программы
Ниже приведён код программы по шифрованию и дешифрованию на основе шифра Кардано на языке программирования Python 3.10 (#lower([@lab-02])). Программа позволяет вводить данные с клавиатуры и файлов (тестовые данные - #lower([@lab-02-encrypt]), #lower([@lab-02-decrypt])).
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Файл lab_02.py],
[
```python
import random
import sys
from typing import Optional, Tuple, Union
ENCRYPT_ACTION = "--enc"
DECRYPT_ACTION = "--dec"
# Считывает текст из файла
def read_from_file_enc(filename: str) -> Optional[str]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')[0]
return buf
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
def read_from_file_dec(filename: str) -> Optional[Tuple[str, str]]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')
s, k = buf[0], buf[1]
return (s, k)
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
# Считывает текст из терминала
def read_from_console_enc() -> str:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
return input().lower()
def read_from_console_dec() -> Tuple[str, str]:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
s = input().lower()
k = input("Введите ключ шифрования: ")
return (s, k)
# Создаёт ключ и шифрует текст с его помощью
def encrypt(text: str) -> Tuple[str, str]:
square_len = find_nearest_bigger_square(len(text))
padded_text = text.ljust(square_len ** 2)
key = make_cardano_lattice_key(square_len)
encrypted = []
for si in key:
encrypted.append(padded_text[si])
for si in rotate_key_90(key, square_len):
encrypted.append(padded_text[si])
for si in rotate_key_180(key, square_len):
encrypted.append(padded_text[si])
for si in rotate_key_270(key, square_len):
encrypted.append(padded_text[si])
return ''.join(encrypted), encode_key(key)
# Расшифровывает текст с помощью ключа
def decrypt(encrypted: str, key: str) -> str:
size = int(len(encrypted) ** 0.5)
key = decode_key(key)
decrypted = [' '] * (size ** 2)
quarter = len(encrypted) // 4
rotations = [
key,
rotate_key_90(key, size),
rotate_key_180(key, size),
rotate_key_270(key, size)
]
for i, rotation in enumerate(rotations):
for j, pos in enumerate(rotation):
decrypted[pos] = encrypted[i * quarter + j]
return ''.join(decrypted)
# Ищет ближайший больший квадрат
def find_nearest_bigger_square(text_size: int) -> int:
i = 1
while i ** 2 < text_size:
i += 1
return i
# Кодирует ключ
def encode_key(key: list[int]) -> str:
return '-'.join(map(str, key))
# Декодирует ключ
def decode_key(key: str) -> list[int]:
return list(map(int, key.split('-')))
# Поворот на 90 градусов
def rotate_90(row: int, col: int, n: int) -> Tuple[int, int]:
return col, n - 1 - row
# Поворот на 180 градусов
def rotate_180(row: int, col: int, n: int) -> Tuple[int, int]:
return n - 1 - row, n - 1 - col
# Поворот на 270 градусов
def rotate_270(row: int, col: int, n: int) -> Tuple[int, int]:
return n - 1 - col, row
# Вычисление позиции ячейки матрицы в решётке
def calc_pos(row: int, col: int, n: int) -> int:
return row * n + col
# Вычисление позиций ячейки из решётки
def calc_pos2(pos: int, n: int) -> Tuple[int, int]:
return pos // n, pos % n
# Вращение ключа
def rotate_key_90(key: list[int], side_len: int) -> list[int]:
return [calc_pos(*rotate_90(*calc_pos2(i, side_len), side_len), side_len) for i in key]
def rotate_key_180(key: list[int], side_len: int) -> list[int]:
return [calc_pos(*rotate_180(*calc_pos2(i, side_len), side_len), side_len) for i in key]
def rotate_key_270(key: list[int], side_len: int) -> list[int]:
return [calc_pos(*rotate_270(*calc_pos2(i, side_len), side_len), side_len) for i in key]
# Ищет перемещения окна при поворотах решётки
def find_opposites(side_len: int, window: int) -> list[int]:
opposites = [window]
row, col = calc_pos2(window, side_len)
# Ищем три дополнительных поворота
w1 = calc_pos(*rotate_90(row, col, side_len), side_len)
w2 = calc_pos(*rotate_180(row, col, side_len), side_len)
w3 = calc_pos(*rotate_270(row, col, side_len), side_len)
# Если повороты одинаковые, нет смысла их добавлять.
# Это случается, когда размер квадрата нечётный, и выбранное окно - центр квадрата.
if window != w1:
opposites += [w1, w2, w3]
return opposites
# Создаёт решётку Кардано
def make_cardano_lattice_key(side_len: int) -> list[int]:
lattice = [i for i in range(side_len ** 2)]
key = []
while len(lattice) != 0:
window = random.choice(lattice)
key.append(window)
windows = find_opposites(side_len, window)
for w in windows:
lattice.remove(w)
return key
# Уточняет, что нужно сделать
def decide_action() -> str:
def print_prompt() -> None:
print('Выберите действие: ')
print('1. Зашифровать текст с помощью ключа')
print('2. Расшифровать текст с помощью ключа')
def read_opt(allowed: list) -> Optional[int]:
try:
opt = int(input("Введите номер [1-2]: "))
if opt not in allowed:
print(f'Ошибка: опция #{opt} недоступна!')
return None
return opt
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
print_prompt()
opt = read_opt([1, 2])
while opt is None:
print_prompt()
opt = read_opt([1, 2])
match opt:
case 1:
return ENCRYPT_ACTION
case 2:
return DECRYPT_ACTION
case _:
return None
# Читает в программу текст и ключ
def read(filename: Optional[str], action: str) -> Optional[Union[Tuple[str, str], str]]:
if filename is None:
if action == ENCRYPT_ACTION:
return read_from_console_enc()
else:
return read_from_console_dec()
else:
if action == ENCRYPT_ACTION:
return read_from_file_enc(filename)
else:
return read_from_file_dec(filename)
# Начало программы
if __name__ == '__main__':
# Если программу запустить с аргументами (именем файла с текстом и ключом), ввод будет считан из файла
filename = None
action = None
for arg in sys.argv[1:]:
if arg == ENCRYPT_ACTION:
action = ENCRYPT_ACTION
elif arg == DECRYPT_ACTION:
action = DECRYPT_ACTION
else:
filename = arg
if action is None:
action = decide_action()
if action == ENCRYPT_ACTION:
s = read(filename, action)
encrypted, key = encrypt(s)
print(f'Результат: "{encrypted}"')
print(f'Ключ: "{key}"')
elif action == DECRYPT_ACTION:
s, k = read(filename, action)
decrypted = decrypt(s, k)
print(f'Результат: "{decrypted}"')
```
]
) <lab-02>
#show figure: set block(breakable: false)
#figure(
caption: [Файл lab_02_encrypt.txt],
[
```
Безумие - это когда ты делаешь одно и то же, ожидая совсем другого результата.
```
]
) <lab-02-encrypt>
#figure(
caption: [Файл lab_02_decrypt.txt],
[
```
аб. игети зьикзоо е а-о оэт мдесдысажуож е у,тге я т н аоео гь реурладтлмдшво до
74-0-77-37-5-64-56-73-36-30-22-69-29-47-14-2-31-15-79-68-40
```
]
) <lab-02-decrypt>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
== Шифрование и дешифрование текста
Выберем достаточно большой кусок текста: "Уже близко становились французы; уже князь Андрей, шедший рядом с Багратионом, ясно различал перевязи, красные эполеты, даже лица французов. (Он ясно видел одного старого французского офицера, который вывернутыми ногами в штиблетах, придерживаясь за кусты, с трудом шел в гору.) Князь Багратион не давал нового приказания и все так же молча шел перед рядами. Вдруг между французами треснул один выстрел, другой, третий... и по всем расстроившимся неприятельским рядам разнесся дым и затрещала пальба. Несколько человек наших упало, в том числе и круглолицый офицер, шедший так весело и старательно. Но в то же мгновение, как раздался первый выстрел, Багратион оглянулся и закричал: Ура!"
Зашифруем его с помощью команды:
```
$ ./lab_02.py --enc lab-02-text.txt
Результат: ".н аажрг а,фсьрти еиваянраинс Взее тсрд ц врпраннср ггясе рб ов уваиоатрА слрл рглр м нмиешзык о и да:ло йО веаш,.туитН Бваьгатрняуго го имт ушд гбаелокя рулитла, овя авр ааасф иыйэ аосос вкелякжзгз л;ууалть йен,мре тнк.п ияр ыниаицсоонпеч ыгасйецьуасыь очоитквдкетлкелУы тыевзечи амбигКыецо и румйнктлрнжпит ниадарндвт ея,унпурцор фздр оирндпн во асрялррсак ллн еанлие хуаарщн,ьуирк о лм Ннди й ап р.д а дх и а дсиро я ! аа шео жл Уад,мсчгвутси нфз й й,иулосол трсф е (ено ензме,длнлрсита ла уж д осе цао арввнеермоед рткио жвсл ск чияетоанр оывБдвы ь,см шл. ор тыд. озрмшоеф пои га )ьезекляшяжаш, ио оов язеа оглро о еом няяпоае,оези ,омпа иц.р аиБзс од а ртктви цз еииеес ле н и шзсс ыевкт и мее кт мл."
Ключ: "276-81-323-494-622-239-625-407-710-574-410-171-434-496-432-208-522-
426-348-186-16-498-352-658-563-329-240-595-473-707-359-247-454-153-431-
290-163-238-262-42-129-554-492-306-104-311-24-339-374-616-444-197-92-
308-160-463-244-516-576-205-4-722-425-427-3-251-300-673-291-214-317-253-
645-43-609-50-703-325-506-166-455-706-361-215-5-46-140-264-537-249-293-
217-560-487-521-316-254-517-36-702-169-699-17-358-157-626-680-679-
336-700-340-199-142-423-614-618-469-266-648-357-573-362-19-587-501-
690-421-650-395-433-245-363-299-164-675-147-281-176-181-61-510-716-661-
509-327-442-536-453-606-665-566-368-246-68-225-491-204-541-596-193-
59-715-260-525-87-570-382-226-242-118-719-148-324-39-381-500-
105-602-653-364-121-527-85".
```
Ключ представляет из себя номера прорезей в решётке, пронумерованной справа налево сверху вниз, со стороной, равной в длину ближайшему квадрату, большему длины текста (длина текста - 686 символов). Для данного текста в решётке 729 клеток, т.е. размеры решётки - 27 на 27.
Расшифруем текст обратно:
```
$ ./lab_02.py
Выберите действие:
1. Зашифровать текст с помощью ключа
2. Расшифровать текст с помощью ключа
Введите номер [1-2]: 2
Введите текст (на русском языке), который требуется зашифровать/расшифровать:
.н аажрг а,фсьрти еиваянраинс Взее тсрд ц врпраннср ггясе рб ов уваиоатрА слрл рглр м нмиешзык о и да:ло йО веаш,.туитН Бваьгатрняуго го имт ушд гбаелокя рулитла, овя авр ааасф иыйэ аосос вкелякжзгз л;ууалть йен,мре тнк.п ияр ыниаицсоонпеч ыгасйецьуасыь очоитквдкетлкелУы тыевзечи амбигКыецо и румйнктлрнжпит ниадарндвт ея,унпурцор фздр оирндпн во асрялррсак ллн еанлие хуаарщн,ьуирк о лм Ннди й ап р.д а дх и а дсиро я ! аа шео жл Уад,мсчгвутси нфз й й,иулосол трсф е (ено ензме,длнлрсита ла уж д осе цао арввнеермоед рткио жвсл ск чияетоанр оывБдвы ь,см шл. ор тыд. озрмшоеф пои га )ьезекляшяжаш, ио оов язеа оглро о еом няяпоае,оези ,омпа иц.р аиБзс од а ртктви цз еииеес ле н и шзсс ыевкт и мее кт мл.
Введите ключ шифрования: 276-81-323-494-622-239-625-407-...
Результат: "уже близко становились французы; уже князь андрей, шедший рядом с багратионом, ясно различал перевязи, красные эполеты, даже лица французов. (он ясно видел одного старого французского офицера, который вывернутыми ногами в штиблетах, придерживаясь за кусты, с трудом шел в гору.) князь багратион не давал нового приказания и все так же молча шел перед рядами. вдруг между французами треснул один выстрел, другой, третий... и по всем расстроившимся неприятельским рядам разнесся дым и затрещала пальба. несколько человек наших упало, в том числе и круглолицый офицер, шедший так весело и старательно. но в то же мгновение, как раздался первый выстрел, багратион оглянулся и закричал: ура! "
```
Таким образом, мы убедились, что программа работает корректно.
== Контрольный вопрос
*Какие ещё шифры перестановки вам известны?*
_Ответ:_ Шифр железнодорожной изгороди, шифр двойной перестановки, шифр карточной колоды, анаграммный шифр, шифр Энигма.
= Лабораторная работа №3. ПОТОЧНЫЕ ШИФРЫ
_Цель работы:_ Разработать генератор гаммы на базе линейного рекуррентного регистра сдвига и выполнить шифрование путём наложения гаммы на открытый текст.
*Ход работы:*
== Исходный код программы
Ниже приведён код программы по шифрованию и дешифрованию на основе наложения гаммы на языке программирования Python 3.10 (#lower([@lab-03])). Программа позволяет вводить данные с клавиатуры и файлов (тестовые данные - #lower([@lab-03-encrypt]), #lower([@lab-03-decrypt])).
#show figure: set block(breakable: true)
#set par(justify: false)
#figure(
caption: [Файл lab_03.py],
[
```python
import random
import sys
from typing import List, Optional, Tuple, Union
RU_ALPHABET = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
ENCRYPT_ACTION = "--enc"
DECRYPT_ACTION = "--dec"
# Считывает текст из файла
def read_from_file_enc(filename: str) -> Optional[str]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')[0]
return buf
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
def read_from_file_dec(filename: str) -> Optional[Tuple[str, str]]:
try:
with open(filename, "r") as f:
buf = f.read().split('\n')
s, k = buf[0], buf[1]
return (s, k)
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
# Считывает текст из терминала
def read_from_console_enc() -> str:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
return input().lower()
def read_from_console_dec() -> Tuple[str, str]:
print("Введите текст (на русском языке), который требуется зашифровать/расшифровать:")
s = input().lower()
k = input("Введите ключ шифрования: ")
return (s, k)
# Создаёт ключ
def generate_key(length: int, a: int, c: int, m: int, seed: int) -> List[int]:
key = [seed]
for _ in range(1, length):
next_value = (a * key[-1] + c) % m
key.append(next_value)
return key
# Конвертация индексов в символы и наоборот
def char_to_index(char: str) -> int:
return RU_ALPHABET.index(char.lower())
def index_to_char(index: int, is_upper: bool) -> str:
char = RU_ALPHABET[index]
return char.upper() if is_upper else char
# Создаёт ключ и шифрует текст с его помощью
def encrypt(text: str, key: List[int]) -> Tuple[str, str]:
encrypted = []
for char, k in zip(text, key):
if char.lower() in RU_ALPHABET:
index = (char_to_index(char) + k) % 33
encrypted_char = index_to_char(index, char.isupper())
encrypted.append(encrypted_char)
else:
encrypted.append(char)
return ''.join(encrypted), encode_key(key)
# Расшифровывает текст с помощью ключа
def decrypt(encrypted: str, key: str) -> str:
key = decode_key(key)
decrypted = []
for char, k in zip(encrypted, key):
if char.lower() in RU_ALPHABET:
index = (char_to_index(char) - k) % 33
decrypted_char = index_to_char(index, char.isupper())
decrypted.append(decrypted_char)
else:
decrypted.append(char)
return ''.join(decrypted)
# Кодирует ключ
def encode_key(key: list[int]) -> str:
return '-'.join(map(str, key))
# Декодирует ключ
def decode_key(key: str) -> list[int]:
return list(map(int, key.split('-')))
# Уточняет, что нужно сделать
def decide_action() -> str:
def print_prompt() -> None:
print('Выберите действие: ')
print('1. Зашифровать текст с помощью ключа')
print('2. Расшифровать текст с помощью ключа')
def read_opt(allowed: list) -> Optional[int]:
try:
opt = int(input("Введите номер [1-2]: "))
if opt not in allowed:
print(f'Ошибка: опция #{opt} недоступна!')
return None
return opt
except Exception as e:
print(f'Ошибка: {str(e)}')
return None
print_prompt()
opt = read_opt([1, 2])
while opt is None:
print_prompt()
opt = read_opt([1, 2])
match opt:
case 1:
return ENCRYPT_ACTION
case 2:
return DECRYPT_ACTION
case _:
return None
# Читает в программу текст и ключ
def read(filename: Optional[str], action: str) -> Optional[Union[Tuple[str, str], str]]:
if filename is None:
if action == ENCRYPT_ACTION:
return read_from_console_enc()
else:
return read_from_console_dec()
else:
if action == ENCRYPT_ACTION:
return read_from_file_enc(filename)
else:
return read_from_file_dec(filename)
# Начало программы
if __name__ == '__main__':
# Если программу запустить с аргументами (именем файла с текстом и ключом), ввод будет считан из файла
filename = None
action = None
for arg in sys.argv[1:]:
if arg == ENCRYPT_ACTION:
action = ENCRYPT_ACTION
elif arg == DECRYPT_ACTION:
action = DECRYPT_ACTION
else:
filename = arg
if action is None:
action = decide_action()
if action == ENCRYPT_ACTION:
# Параметры генерации ключа
a = random.randint(1, 1000)
c = random.randint(0, 1000)
m = 33
seed = random.randint(0, 32)
s = read(filename, action)
key = generate_key(len(s), a, c, m, seed)
encrypted, key_str = encrypt(s, key)
print(f'Результат: "{encrypted}"')
print(f'Ключ: "{key_str}"')
elif action == DECRYPT_ACTION:
s, k = read(filename, action)
decrypted = decrypt(s, k)
print(f'Результат: "{decrypted}"')
```
]
) <lab-03>
#show figure: set block(breakable: false)
#figure(
caption: [Файл lab_03_encrypt.txt],
[
```
Безумие - это когда ты делаешь одно и то же, ожидая совсем другого результата.
```
]
) <lab-03-encrypt>
#figure(
caption: [Файл lab_03_decrypt.txt],
[
```
пхвюйвк - лги ззииа бл овеёйшд яюшл о тц чя, змндзн лщяккс лядэщаз хепвьцээлё.
15-17-27-11-30-26-6-5-0-8-15-17-27-11-30-26-6-5-0-8-15-17-27-11-30-
26-6-5-0-8-15-17-27-11-30-26-6-5-0-8-15-17-27-11-30-26-6-5-0-8-15-
17-27-11-30-26-6-5-0-8-15-17-27-11-30-26-6-5-0-8-15-17-27-11-
30-26-6-5
```
]
) <lab-03-decrypt>
#set par(justify: true, first-line-indent: 1.25cm, linebreaks: "optimized")
#par("")
== Шифрование и дешифрование текста
В процессе выполнения программы ключ гаммирования (шифрующая последовательность ЛРС) генерируется автоматически и представляет из себя набор регистров. Сымитируем генерацию ЛРС и шифротекста и расшифровку текста:
```
$ ./lab_03.py
Выберите действие:
1. Зашифровать текст с помощью ключа
2. Расшифровать текст с помощью ключа
Введите номер [1-2]: 1
Введите текст (на русском языке), который требуется зашифровать/расшифровать:
Невероятно, но очень интересно!
Результат: "тэетисмкрь, ыж ьпзыф цёхтизяёс!"
Ключ: "5-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14"
```
Передаём другому адресату данные, и он проводит дешифровку текста:
```
$ ./lab_03.py
Выберите действие:
1. Зашифровать текст с помощью ключа
2. Расшифровать текст с помощью ключа
Введите номер [1-2]: 2
Введите текст (на русском языке), который требуется зашифровать/расшифровать:
тэетисмкрь, ыж ьпзыф цёхтизяёс!
Введите ключ шифрования: 5-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14-25-3-14
Результат: "невероятно, но очень интересно!"
```
Таким образом, мы убедились, что программа работает корректно.
== Контрольный вопрос
*Перечислите разновидности поточных шифров и их особенности.*
_Ответ:_
Поточные шифры делятся на два основных типа: синхронные и самосинхронизирующиеся. Синхронные поточные шифры генерируют ключевой поток независимо от открытого текста и зависят только от ключа шифрования и начального значения. Ключевой поток в этом случае комбинируется с открытым текстом обычно с использованием операции сложения по модулю два (XOR). Примеры таких шифров включают RC4 и A5/1. Их особенности заключаются в высокой скорости шифрования и дешифрования, что делает их идеальными для потоковых данных, таких как аудио- и видеопередача. Однако они уязвимы к атаке на повторный ключ, если тот же ключ используется дважды.
Самосинхронизирующиеся поточные шифры зависят не только от ключа и начального значения, но и от определенного числа предыдущих символов шифртекста. Это позволяет восстанавливать синхронизацию при потере части данных, что является их ключевым преимуществом в условиях ненадежных каналов связи. Примеры таких шифров включают шифр CFB (Cipher Feedback Mode) и OFB (Output Feedback Mode). Их использование позволяет достичь устойчивости к ошибкам передачи, однако скорость шифрования может быть ниже по сравнению с синхронными поточными шифрами из-за необходимости учитывать предыдущие данные.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/titleize/0.1.1/README.md | markdown | Apache License 2.0 | # titleize
Small wrapper around the [titlecase](https://crates.io/crates/titlecase) library to convert text to title case.
It follows the [rules defined by <NAME>](https://daringfireball.net/2008/05/title_case).
For more details, refer to the library.
`titlecase` applies a show rule, that by default transforms every string of at least four characters.
This limit can be changed with the `limit` parameter.
Especially with equations, the results can be a bit unpredictable, so proceed with care.
```typst
#import "@preview/titleize:0.1.1": titlecase
#for s in (
"Being productive on linux",
"Finding an alternative to Mac OS X — part 2",
[an example with small words and sub-phrases: "the example"],
) [
#s => #titlecase(s) \
]
#let debug-print(x) = {
if type(x) == content {
let fields = x.fields()
let func = x.func()
[
#repr(func)
#for (k, v) in fields [
- #k: #debug-print(v)
]
]
} else {
if type(x) == array [
array
#for y in x [
- #debug-print(y)
]
] else [
#repr(type(x)) (#repr(x))
]
}
}
#show: titlecase
= This is a test, even with math $a = b + c$
In math, text can appear in various places:
$
a_"for example in a subscript" &= "or in a longer text" \
f(x) &= sin(x)
$
```
 |
https://github.com/Vortezz/fiches-mp2i-maths | https://raw.githubusercontent.com/Vortezz/fiches-mp2i-maths/main/chapter_2.typ | typst | #set page(header: box(width: 100%, grid(
columns: (100%),
rows: (20pt, 8pt),
align(right, text("CHAPITRE 1. ENSEMBLES ET APPLICATIONS")),
line(length: 100%),
)), footer: box(width: 100%, grid(
columns: (50%, 50%),
rows: (8pt, 20pt),
line(length: 100%),
line(length: 100%),
align(left, text("<NAME> - MP2I")),
align(right, text("<NAME> - 2023/2024")),
)))
#set heading(numbering: "I.1")
#let titleBox(title) = align(center, block(below: 50pt, box(height: auto, fill: rgb("#eeeeee"), width: auto, inset: 40pt, text(title, size: 20pt, weight: "bold"))))
#titleBox("Ensembles et applications")
= Théorie intuitive des ensembles
== Définition intuitive
Un *ensemble* $E$ est une collection d'objets appelés *éléments* de $E$.
On dit que $x$ _appartient_ à $E$ et on note $x in E$ si $x$ est un élément de $E$.
Il existe plusieurs manières de définir un ensemble :
- Par *énumération* : $E = {x_1, ..., x_n}$
- Par *compréhension* : $E = {x in A | P(x)}$ (Tous les éléments de $A$ vérifiant la propriété $P$)
- Par *induction structurelle* :
- On prend des _éléments initiaux_
- On prend une _manière de construire de nouveaux éléments_ à partir des éléments initiaux
- Par *construction* : On utilise $union$ et $sect$ pour construire de nouveaux ensembles à partir d'ensembles existants
A noter qu'il est possible de construire des ensembles par induction structurelle de deux manières différentes :
- Par le bas : On prend des éléments initiaux et on construit de nouveaux éléments à partir de ceux-ci
- Par le haut : On prend un ensemble $E$ le "plus petit ensemble" contenant $A_1,...,A_n$ et stable pour les constructions $P_1,...,P_k$. C'est souvent l'intersection de tous les ensembles possédant une propriété de stabilité.
== Inclusion
On note $F subset E$ si $forall x in F ==> x in E$, et on dit que $F$ est *inclus* dans $E$.
Si $F = G$ si et seulement si $F subset G$ et $G subset F$, on dit que $F$ et $G$ sont *égaux*.
Si $F subset G$ et $G subset H$, alors $F subset H$ (transitivité de l'inclusion).
#emoji.warning Ne pas confondre $subset$ et $in$ !
== Petits ensembles, cardinal d'un ensemble
L'*ensemble vide* est sous ensemble de tous ensemble $E$. On le note $emptyset$.
On appelle *singleton* un ensemble contenant un seul élément ${a}$. \
On appelle *paire* un ensemble contenant deux éléments distincts ${a, b}$.
On appelle intuitivement *cardinal* d'un ensemble $E$ le nombre d'éléments de $E$. On le note $|E|$.
== Ensemble des parties d'un ensemble
On note $P(E)$ l'ensemble des parties de $E$, c'est-à-dire l'ensemble dont les éléments sont les sous-ensembles de $E$.
Puisque $emptyset in P(E)$ et $E in P(E)$, on a $P(E) != emptyset$.
On note $P_k (E)$ l'ensemble des parties de $E$ à $k$ éléments.
Notation troeschienne :
- $P(n) = P([|1,n|])$
- $P_k (n) = P_k ([|1,n|])$
== Opérations sur les parties d'un ensemble
- *Intersection* : L'intersection de deux ensembles $E$ et $F$ est l'ensemble des éléments appartenant à $E$ et à $F$. On la note $E sect F$.
- *Union* : L'union de deux ensembles $E$ et $F$ est l'ensemble des éléments appartenant à $E$ ou à $F$. On la note $E union F$.
- *Différence ensembliste* : La différence ensembliste de deux ensembles $E$ et $F$ est l'ensemble des éléments appartenant à $E$ mais pas à $F$. On la note $E \\ F$.
- *Complémentaire* : On a $F subset E$, Le complémentaire d'un ensemble $F$ dans un ensemble $E$ est la différence ensembliste $E \\ F$. On le note $E \\ F = E - F = C_E F = F^c = F_c = overline(F)$
- *Différence symétrique* : La différence symétrique de deux ensembles $E$ et $F$ est l'ensemble des éléments appartenant à $E$ ou à $F$ mais pas aux deux. On la note $E Delta F$.
Il est important de noter que $union$ et $sect$ sont des opérations *associatives*, *commutatives* et *distribuables* l'une par rapport à l'autre.
Deux ensembles $E$ et $F$ sont *disjoints* si $E sect F = emptyset$. On peut alors noter $E union F$ sous la forme $E union.plus F$ ou $E union.sq F$.
On peut appliquer les lois de De Morgan aux opérations sur les ensembles :
$ (E union F)^c = E^c sect F^c "et" (E sect F)^c = E^c union F^c $
Le complémentaire est décroissant, ainsi $forall A,B in P(E), A subset B ==> B^c subset A^c$
$overline(A)$ est l'unique sous ensemble $B$ tel que $A union B = E$ et $A sect B = emptyset$.
On en déduit que :
- $C_E E = emptyset$
- $C_E emptyset = E$
- $C_E C_E F = F$
== Union et intersection d'une famille d'ensembles
Une *famille* d'éléments d'un ensemble $E$, $a_i in E$ est une fonction $a_i : I -> E$, notée $(a_i)_(i in I)$
On définit l'union et l'intersection d'une famille d'ensembles $(A_i)_(i in I)$ par :
- $ union.big_(i in I) A_i = {x in E | exists i in I, x in A_i} $
- $ sect.big_(i in I) A_i = {x in E | forall i in I, x in A_i} $
Si les $A_i$ sont deux à deux disjoints, on peut écrire $union.big.plus_(i in I) A_i $ ou $union.big.sq_(i in I) A_i $
== Partitions
Une *partition* d'un ensemble $E$ est un sous ensemble $F$ de $P(E)$ tel que :
- $forall A in F, A != emptyset$
- $forall A,B in F, A != B ==> A sect B = emptyset$
- $union.big_(A in F) A = E$
Il est possible de faire une *partition ordonnée* avec un $n$-uplet, un *recouvrement* soit une famille d'ensembles dont l'union est $E$ et un *recouvrement disjoint* soit une famille d'ensembles dont l'union est $E$ et deux à deux disjoints.
== Produit cartésien
On appelle $A times V$ le *produit cartésien* de $A$ et $V$, soit l'ensemble des couples $(a, v)$ avec $a in A$ et $v in V$ vérifiant :
$ (a,v) = (a',v') <==> (a = a' and v = v') $
Si $A times V = emptyset <==> (A = emptyset or V = emptyset)$
Il est possible de construire des $n$-uplets, en effet $(a,b,c)=(a,(b,c))$, c'est ainsi généralisable. |
|
https://github.com/OthoDeng/typst_cv_template | https://raw.githubusercontent.com/OthoDeng/typst_cv_template/main/src/CV_template_en.typ | typst | #let conf(
name: none,
address: none,
phone: none,
email: none,
blog: none,
doc
) = {
set page(margin: (x: 40pt, y: 40pt))
set text(font: "New Computer Modern", size: 12pt)
set block(spacing: 8pt)
set document(
title: "CV",
author: name,
)
show link: underline
set align(center)
par(text(size: 18pt, weight: "bold", name))
v(8pt)
par(address)
par(stack(
dir: ltr,
spacing: 4pt,
text(phone),
text("·"),
link("mailto:" + email)
))
v(4pt)
set align(start)
set line(stroke: 0.38pt + luma(20%))
show heading.where(
level: 1
): it => {
set text(size: 14pt, weight: "bold")
v(4pt)
align(left, smallcaps(it))
v(-10pt)
stack(
dir: ltr,
spacing: 4pt,
line(length: 100%),
line(length: 4pt),
line(length: 4pt),
line(length: 4pt),
line(length: 4pt),
line(length: 4pt),
)
v(4pt)
}
show heading.where(//Heading style
level: 2
): it => {
box(text(size: 12pt, weight: "semibold", it, rgb("#1A237E")))
}
doc
}
#let cv_block(//CV Content style
name: none,
date: none,
entity: none,
description: none,
) = par({
heading(level: 2, name)
if entity != none {
", "
text(fill: luma(20%),style: "italic", entity)
}
h(1fr)
text(style: "italic", date)
v(1pt)
text(fill: luma(12%),description)
})
#let cv_link(
url,
) = link("https://" + url, text(fill: rgb(20%, 20%, 40%), url))
//// Preview ////
#show: doc => conf(
name: "<NAME>",
address: "No.114, Apple Road, Banan(Postcode: 12345)",
phone: "(+21) 123-4567-8900",
email: "<EMAIL>",
doc,
)
= Education
#cv_block(
name: "Caliton University",
date: "Sep. 2023 ~ Jul. 2027",
entity: "Atlantic",
description: [
- B.S with Honors in Fish Touching
- Ranking: 1/183 | GPA:4.00/4
],
)
= Project Experience/ Internship
#cv_block(
name: "Research Assistant",
entity: [Key Laboratory of Fishing],
description: [
- Assist with data collection and analysis for fish research project]
)
#v(5pt)
#cv_block(
name: "Member",
entity: [
Innovation Center on Fish Touching
],
description:[
- Contributed to development of fish catching model using machine learning
]
)
= Area of Interest
*Fish Touching* | *Cat Feeding* | *Dog jogging*
= Publications
#cv_block(
name: "Rei,*Rin, et al.",
entity: [Empirical Study of Paper Style Text Generation Technology Based on Large-scale Language Models [#cv_link("openai.com/114.514")]],
description: [
- Examined how Current students use Large-scale Language Module(ChatGPT) to cheat.
]
)
= Selected Awards and Honors
#cv_block(
name: "Fish Catching Assessment Project",
entity: "Supervised by Professor Miku",
description: [
- Analyzed 30 years of fish data to assess risk factors .
- Developed an interactive data visualization dashboard using Python.
]
)
= Additional Information
#cv_block(
name:"Extracurricular Activities",
entity: [
- Member, University Fish Association
- Volunteer, Local Fish Service Office
- User, #link("https://openai,com")[Open Ai]
]
)
#cv_block(
name: "Laboratory Skills",
description:[
- Maintenance and operation of the clean laboratory
- Pipetting, weighing, filtrating, titrating, etc.
]
)
#cv_block(
name: "Computer and Language Skills",
description: [
- Programming: Python(Average)
- Software: Meh
- Language: Alienese(Native)
]
)
|
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-02-29/24-02-29.typ | typst | #import "/template.typ": *
#show: project.with(
date: "29/02/24",
subTitle: "Aggiornamento sullo stato dei lavori",
docType: "verbale",
authors: (
"<NAME>",
),
externalParticipants : (
(name: "<NAME>", role: "Referente aziendale"),
),
timeStart: "16:15",
timeEnd: "17:10",
location: "Zoom",
);
= Ordine del giorno
- ER;
- Mock-up;
- Architettura e design;
- Meeting futuri.
== ER
È stato mostrato lo schema ER del database di supporto, modificato secondo le considerazioni fatte nell'ultimo meeting (22/02/2024).
Gli attributi di dettaglio dell'entità `Prodotto`, quali `peso`, `larghezza`, `profondità` e `altezza`, sono stati ritenuti dal Proponente come non necessari per richiedere lo spostamento di un prodotto, e quindi da non inviare alle API.
È stata confermata dal Proponente l'idea di avere un'entità `Zona` per permettere una gestione univoca del bin sullo scaffale e a terra: quest'ultimo sarà considerato come appartenente a uno scaffale avente un solo ripiano a livello zero.
== Mock-up
È stato mostrato al Proponente il mock-up realizzato, il quale è servito per illustrare e discutere alcune proprietà del MVP, in particolare:
- è stata discussa la scelta di poter inserire la lunghezza in metri del lato maggiore del magazzino per lo scaling dell'ambiente a partire da un SVG. Questa scelta è stata approvata dal proponente, evidenziando comunque la necessità di poter ridimensionare l'ambiente e scalare tutti gli elementi del piano di conseguenza;
- è stata confermata l'idea di notificare l'utente della presa in carico dell'operazione di spostamento da parte del sistema con una notifica toast;
- è stata confermata l'idea di introdurre la possibilità di visualizzare tutti gli spostamenti effettuati dall'utente nella sessione corrente;
- è stata rielaborata la condizione per cui uno scaffale si possa eliminare solo se vuoto. Viene avanzata dal Proponente la possibilità che uno scaffale sia sempre eliminabile anche quando non vuoto. I prodotti contenuti nello scaffale vengono quindi visualizzati come "non assegnati" nell'apposita lista. L'utente ha quindi la possibilità di assegnarli ad altri bin vuoti;
- con il Proponente è stata concordata la possibilità di modificare gli scaffali anche quando non vuoti nei seguenti casi:
- l'utente vuole aumentare le dimensioni di uno scaffale;
- l'utente vuole diminuire le dimensioni di uno scaffale e le modifiche apportate non comportano l'eliminazione di bin pieni (requisito desiderabile).
- è stata rifiutata l'idea di avere dimensioni e numero di bin diversi per ogni ripiano dello scaffale in quanto non corrispondente a una situazione realistica. Lo scaffale deve seguire una logica colonnare, di conseguenza devo avere un numero di colonne uguale in ogni ripiano, ognuna con larghezza omogenea. Non è possibile quindi avere in due ripiani dello stesso scaffale lo stesso numero di colonne ma con dimensioni che variano da piano a piano.
== Architettura e design
Vengono esposti alcuni dei principali dubbi nati durante il meeting interno di design thinking tenutosi il 29/02/2024:
- *layer di architettura dedicato al database*: non è essenziale in quanto la presenza del database non è richiesta nel capitolato, e si tratta solamente di un supporto. Di conseguenza viene data libertà al gruppo nel considerarlo un vero e proprio layer;
- *definizione di classi e design pattern*: dato che ogni entità del progetto risulta essere solamente un aggregato di informazioni privo di comportamento, l'utilizzo di classi e design pattern non è ritenuto essenziale dal Proponente;
- *business logic*: le verifiche di fattibilità del posizionamento degli scaffali sono effettuate da Three.js, come visibile nel PoC; l'unica business logic individuabile è rappresentata dalle API, che nel contesto del capitolato sono simulate. Di conseguenza, anche dal Proponente non è stata individuata una vera e propria business logic da implementare nel prodotto.
== Meeting futuri
Il Proponente ha confermato la sua disponibilità per proseguire gli incontri a cadenza settimanale.
Il prossimo appuntamento è fissato per giovedì 07/03/2024 alle ore 16:00.
|
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20esterna/Verbali/24-02-22/24-02-22.typ | typst | #import "/template.typ": *
#show: project.with(
date: "22/02/24",
subTitle: "Aggiornamento sullo stato dei lavori",
docType: "verbale",
authors: (
"<NAME>",
),
externalParticipants : (
(name: "<NAME>", role: "Referente aziendale"),
),
timeStart: "15:20",
timeEnd: "16:10",
location: "Zoom",
);
= Ordine del giorno
- Aggiornamento sullo stato dei lavori;
- Feedback su modalità e strumenti per il testing;
- Feedback sul deploy dell'applicazione;
- Presentazione bozza diagramma ER;
- Meeting futuri.
== Aggiornamento sullo stato dei lavori
Il Proponente è stato aggiornato sull'esito del duplice colloquio di RTB sostenuto dal gruppo.
Il gruppo ha evidenziato i punti di forza del lavoro svolto finora e presentato le soluzioni che si intendono adottare relative alle criticità emerse.
== Feedback su modalità e strumenti per il testing
Il gruppo ha esposto al Proponente le proprie considerazioni riguardanti il testing dell'applicazione. Le tipologie di testing considerate sono:
- unit testing;
- integration testing;
- end-to-end testing.
=== Unit testing
Il Proponente, seppur indicando che in azienda viene utilizzato JUnit per il processo di unit testing, non ha posto vincoli riguardo al software da adottare ed ha apprezzato la proposta del gruppo di utilizzare Jest.
Il Proponente ha poi consigliato di rendere questa modalità di testing il focus principale del gruppo, poiché ritenuta di importanza maggiore rispetto alle altre.
=== Integration testing
Il Proponente ha manifestato la visione che lo sviluppo di integration testing non sia considerato un requisito obbligatorio, ribadendo che la logica di business non costituisce il fulcro principale del capitolato proposto.
Il gruppo, a seguito di questa indicazione, si impegna a prendere una decisione finale in merito durante lo svolgimento dei lavori. Si prevede un'approfondita valutazione della necessità e dei potenziali benefici legati allo sviluppo di integration testing. La decisione definitiva sarà presa considerando l'orientamento del Proponente e valutando attentamente come questa scelta possa influire sulle fasi successive del progetto.
=== End-to-end testing
Il Proponente ha espresso interesse nei confronti della proposta, ritenendo tuttavia che lo sviluppo di questo tipo di testing non sia attualmente una priorità. Ha sottolineato l'elevato costo in termini di tempi e risorse di cui tali test possono necessitare che possono risultare critici e non adatti al contesto di un progetto didattico.
In seguito a questa valutazione da parte del Proponente, il gruppo considererà l'implementazione di questa tipologia di testing solo tempi e risorse permettendo.
== Feedback sul deploy dell'applicazione
Il Proponente ha ritenuto interessante la proposta del gruppo di implementare il processo di deploy dell'applicazione utilizzando AzureVM (insieme a Docker).
Il feedback generale ha evidenziato l'approvazione dei meccanismi di Continuous Integration e Continuous Deployment (CI/CD) implementati
== Presentazione bozza diagramma ER
Durante la presentazione della bozza del diagramma ER relativo al database di supporto all'applicazione, il Proponente ha valutato positivamente il lavoro svolto dal gruppo e ha suggerito alcune modifiche per migliorare la struttura del database, prendendo in esame le seguenti considerazioni:
+ schema ER:
- codice identificativo dei bin completo (non numerati semplicemente da 1 a n ma completi di tutte le informazioni necessarie). Il Proponente ha inoltre fornito questo esempio:
#align(center, `PLK-100-MGP0101A10`)
dove:
+ PLK = Stabilimento
+ 100 = Magazzino
+ MGP = Area
+ 01 = Corsia
+ 01 = Scaffale
+ A = Colonna
+ 10 = Piano
- ogni ripiano può avere un numero di bin diverso;
- l'altezza dello scaffale è la somma delle altezze dei ripiani che lo compongono.
+ bin:
- profondità fissa dipendente dalla profondità dello scaffale;
- larghezza deve essere personalizzabile;
- altezza fissa dipendente dal ripiano.
+ posizionamento
- il database contiene le coordinate (x,y) di posizionamento dello scaffale all'interno dell'ambiente.
Lo schema ER verrà quindi modificato e ripresentato nel meeting successivo.
== Meeting futuri
Il Proponente ha confermato la sua disponibilità per proseguire gli incontri a cadenza settimanale.
Il prossimo appuntamento è fissato per giovedì 29/02/2024 alle ore 16:00. |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/112.%20revolution.html.typ | typst | revolution.html
A Local Revolution?
April 2009Recently I realized I'd been holding two ideas in my head that would explode if combined.The first is that startups may represent a new economic phase, on the scale of the Industrial Revolution. I'm not sure of this, but there seems a decent chance it's true. People are dramatically more
productive as founders or early employees of startups—imagine how much less Larry and Sergey would have achieved if they'd gone to work for a big company—and that scale of improvement can change social customs.The second idea is that startups are a type of business that flourishes in certain places that specialize in it—that Silicon Valley specializes in startups in the same way Los Angeles specializes in movies, or New York in finance. [1]What if both are true? What if startups are both a new economic phase and also a type of business that only flourishes in certain centers?If so, this revolution is going to be particularly revolutionary. All previous revolutions have spread. Agriculture, cities, and industrialization all spread widely. If startups end up being like the movie business, with just a handful of centers and one dominant one, that's going to have novel consequences.There are already signs that startups may not spread particularly well. The spread of startups seems to be proceeding slower than the spread of the Industrial Revolution, despite the fact that communication is so much faster now.Within a few decades of the founding of Boulton & Watt there were steam engines scattered over northern Europe and North America. Industrialization didn't spread much beyond those regions for a while. It only spread to places where there was a strong middle class—countries where a private citizen could make a fortune without having it confiscated. Otherwise it wasn't worth investing in factories. But in a country with a strong middle class it was easy for industrial techniques to take root. An individual mine or factory owner could decide to install a steam engine, and within a few years he could probably find someone local to make him one. So steam engines spread fast. And they spread widely, because the locations of mines and factories were determined by features like rivers, harbors, and sources of raw materials.
[2]Startups don't seem to spread so well, partly because they're more a social than a technical phenomenon, and partly because they're not tied to geography. An individual European manufacturer could import industrial techniques and they'd work fine. This doesn't seem to work so well with startups: you need a community of expertise, as you do in the movie business. [3]
Plus there aren't the same forces driving startups to spread. Once railroads or electric power grids were invented, every region had to have them. An area without railroads or power was a rich potential market. But this isn't true with startups. There's no need for a Microsoft of France or Google of Germany.Governments may decide they want to encourage startups locally, but government policy can't call them into being the way a genuine need could.How will this all play out? If I had to predict now, I'd say that startups will spread, but very slowly, because their spread will be driven not by government policies (which won't work) or by market need (which doesn't exist) but, to the extent that it happens at all, by the same random factors that have caused startup culture to spread thus far. And such random factors will increasingly be outweighed by the pull of existing startup hubs.Silicon Valley is where it is because <NAME> wanted to move back to Palo Alto, where he grew up, and the experts he lured west to work with him liked it so much they stayed. Seattle owes much of its position as a tech center to the same cause: Gates and Allen wanted to move home. Otherwise Albuquerque might have Seattle's place in the rankings. Boston is a tech center because it's the intellectual capital of the US and probably the world. And if Battery Ventures hadn't turned down Facebook, Boston would be significantly bigger now on the startup radar screen.But of course it's not a coincidence that Facebook got funded in the Valley and not Boston. There are more and bolder investors in Silicon Valley than in Boston, and even undergrads know it.Boston's case illustrates the difficulty you'd have establishing a new startup hub this late in the game. If you wanted to create a startup hub by reproducing the way existing ones happened, the
way to do it would be to establish a first-rate research university in a place so nice that rich people wanted to live there. Then the town would be hospitable to both groups you need: both founders and investors. That's the combination that yielded Silicon Valley. But Silicon Valley didn't have Silicon Valley to compete with. If you tried now to create a startup hub by planting a great university in a nice place, it would have a harder time getting started, because many of the best startups it produced would be sucked away to existing startup hubs.Recently I suggested a potential shortcut:
pay startups to move. Once you had enough good startups in one place, it would create a self-sustaining chain reaction. Founders would start to move there without being paid, because that was where their peers were, and investors would appear too, because that was where the deals were.In practice I doubt any government would have the balls to try this, or the brains to do it right. I didn't mean it as a practical suggestion, but more as an exploration of the lower bound of what it would take to create a startup hub deliberately.The most likely scenario is (1) that no government will successfully establish a startup hub, and (2) that the spread of startup culture will thus be driven by the random factors that have driven it so far, but (3) that these factors will be increasingly outweighed by the pull of existing startup hubs. Result: this revolution, if it is one, will be unusually localized.
Notes[1]
There are two very different types of startup: one kind that evolves naturally, and one kind that's called into being to "commercialize" a scientific discovery. Most computer/software startups are now the first type, and most pharmaceutical startups the second. When I talk about startups in this essay, I mean type I startups. There is no difficulty making type II startups spread: all you have to do is fund medical research labs; commercializing whatever new discoveries the boffins throw off is as straightforward as building a new airport. Type II startups neither require nor produce startup culture. But that means having type II startups won't get you type I startups. Philadelphia is a case in point: lots of type II startups, but hardly any type I.Incidentally, Google may appear to be an instance of a type II startup, but it wasn't. Google is not pagerank commercialized. They could have used another algorithm and everything would have turned out the same. What made Google Google is that they cared about doing search well at a critical point in the evolution of the web.[2]
Watt didn't invent the steam engine. His critical invention was a refinement that made steam engines dramatically more efficient: the separate condenser. But that oversimplifies his role. He had such a different attitude to the problem and approached it with such energy that he transformed the field. Perhaps the most accurate way to put it would be to say that Watt reinvented the steam engine.[3]
The biggest counterexample here is Skype. If you're doing
something that would get shut down in the US, it becomes an
advantage to be located elsewhere. That's why Kazaa took
the place of Napster. And the expertise and connections the
founders gained from running Kazaa helped ensure the success
of Skype.Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this.
|
|
https://github.com/Meisenheimer/Notes | https://raw.githubusercontent.com/Meisenheimer/Notes/main/src/Regression.typ | typst | MIT License | #import "@local/math:1.0.0": *
= Regression
== Linear Regression
#env("Definition")[
Given a data set ${(mathbf(x)_i, y_i), i in {1, dots, m}}$ where $mathbf(x)_i in RR^n$, the linear regression seeks $tilde(mathbf(w)) in RR^n$ and $tilde(b) in RR$ such that
$ f(mathbf(x)_i) = tilde(mathbf(w))^T mathbf(x)_i + tilde(b) approx y_i. $
In general, we choose mean square error to estimate the error between $f(mathbf(x)_i)$ and $y_i$, which implies
$ (tilde(mathbf(w)), tilde(b)) = limits(arg min)_(mathbf(w) in RR^n, b in RR) sum_(i=1)^m (f(mathbf(x)_i) - y_i)^2 = limits(arg min)_(mathbf(w) in RR^n, b in RR) sum_(i=1)^m (mathbf(w)^T x + b - y_i)^2. $
]
#env("Theorem")[
Given a data set ${(mathbf(x)_i, y_i), i in {1, dots, m}}$ where $mathbf(x)_i in RR^n$, let
$ X = mat(mathbf(x)_1^T, 1; dots.v, 1; mathbf(x)_m^T, 1; ), mathbf(y) = mat(y_1; dots.v; y_m), $
if $X^T X$ is invertible, the solution of linear regression can be written as
$ mat(mathbf(w); b) = (X^T X)^(-1) X^T mathbf(y). $
] |
https://github.com/typst-community/setup-typst | https://raw.githubusercontent.com/typst-community/setup-typst/main/README_zh-Hans-CN.md | markdown | MIT License | <p align=center>
<a href="https://github.com/typst-community/setup-typst/blob/main/README.md" hreflang="en" lang="en">English</a> | <b>简体中文</b>
</p>
# Setup Typst
此操作为 GitHub Actions 用户提供以下功能:
- 安装给定版本的 Typst 并将其加入 PATH
- 可选地将 [第三方包](https://github.com/typst/packages) 依赖缓存
<table align=center><td>
```yaml
- uses: typst-community/setup-typst@v3
- run: typst compile paper.typ paper.pdf
```
</table>
## 用法


### 基本用法
```yaml
name: Render paper.pdf
on: push
jobs:
render-paper:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
# Typst 被安装,且第三方包将被缓存!
- run: typst compile paper.typ paper.pdf
```
### 输入
- **`typst-token`:** 当从 [typst/typst] 拉取版本时使用的 GitHub 令牌。默认情况下,这应
该涵盖全部情况。你通常无需修改此项。
- **`typst-version`:** 需要安装的 Typst 的版本。它可以是一个确定的版本号如 `0.10.0` 或
语义化版本号如 `0.10` 和 `0.x`。你也可以使用 `latest` 使用最新版本的 Typst。默认值为
`latest`。
- **`cache-dependency-path`:** 第三方包依赖列表文件的文件名。该文件应该是一个含有
`import` 关键字的 Typst 文件。
### 输出
- **`typst-version`:** 安装的 Typst 的版本。它的格式应该类似 `0.10.0`。
- **`cache-hit`:** Typst 是否存缓存下载。
### 自定义组合
#### 上传工作流构件
```yaml
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
- run: typst compile paper.typ paper.pdf
- uses: actions/upload-artifact@v4
with:
name: paper
path: paper.pdf
```
#### 使用 Fontist 拓展字体支持
如需为 GitHub Actions 运行器拓展字体库,可使用 Fontist 进行自定义字体安装。以下是使用
[fontist/setup-fontist] 添加新字体的范例:
```yaml
- uses: fontist/setup-fontist@v2
- run: fontist install "Fira Code"
- uses: typst-community/setup-typst@v3
with:
cache-dependency-path: requirements.typ
- run: typst compile paper.typ paper.pdf --font-path ~/.fontist/fonts
```
## 开发

**我应该如何测试我的贡献?**
开启一个草稿拉取请求,GitHub Actions 测试项将在被管理员的许可后运行。
[Typst]: https://typst.app/
[typst/typst]: https://github.com/typst/typst
|
https://github.com/liuxu89/Principles | https://raw.githubusercontent.com/liuxu89/Principles/main/sample-page.typ | typst | #import "/book.typ": book-page
#show: book-page.with(title: "Hello, typst")
= Hello, typst
Sample page
|
|
https://github.com/enseignantePC/2023-24 | https://raw.githubusercontent.com/enseignantePC/2023-24/master/style.typ | typst | #import "@preview/showybox:1.1.0": showybox
#let doc_counter = counter("doc")
#let doc(
..body,
width: 1fr,
title: none,
title-size: 15pt,
boxed: false,
shadow : true,
show_doc: true,
) = box(
width: width,
{
doc_counter.step()
showybox(
title: text(size: title-size)[
#if show_doc [Doc. #doc_counter.display()]
#if show_doc and title != none [:]
#if title != none [#title]
],
frame: (
title-color: red.lighten(70%),
body-color: gray.lighten(60%),
),
border-style: (color: black),
title-style: (
color: red.darken(60%),
weight: "bold",
boxed: boxed,
boxed-align: left,
align: center,
breakable: false,
),
shadow: if shadow {(color: black)},
breakable: true,
..body,
)
}) |
|
https://github.com/YonniGashu/resume | https://raw.githubusercontent.com/YonniGashu/resume/main/README.md | markdown | # My Resume
My resume!
Whatever is in this repository is what [my website](https://ygashu.dev) links to.
Built using [Typst!](https://typst.app/)
|
|
https://github.com/Tetragramm/flying-circus-typst-template | https://raw.githubusercontent.com/Tetragramm/flying-circus-typst-template/main/CHANGELOG.md | markdown | MIT License | # (https://github.com/Tetragramm/flying-circus-typst-template/releases/tag/v3.0.0)
## Added
Functions available:
- FlyingCircus (The document style)
- FCPlane
- FCVehicleSimple
- FCVehicleFancy
- FCShip
- FCWeapon
- HiddenHeader
- KochFont
## Removed
---
## Changed
N/A
## Migration Guide from v0.1.X
N/A
---
# [v3.0.0](https://github.com/Tetragramm/flying-circus-typst-template/releases/tag/v3.0.0)
Initial Release is compatible with the latex v3.0.0, so versioning will start there. |
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/template/sections/tables.typ | typst | MIT License | = Sample Tables
// Sample tables taken from https://apastyle.apa.org/style-grammar-guidelines/tables-figures/sample-tables
== Sample Demographic Characteristics Table
Referencing @table:sample-demographic-characteristics.
#figure(
[
#table(
align: (x, y) =>
if (y == 0 or y == 1) and x >= 0 { center }
else if x == 0 and y > 0 { left }
else { center },
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
table.header(
table.hline(),
table.cell(rowspan: 2)[Baseline characteristic],
table.cell(colspan: 2)[Guided self-help],
table.cell(colspan: 2)[Unguided self-help],
table.cell(colspan: 2)[Wait-list control],
table.cell(colspan: 2)[Full sample],
table.hline(),
[n], [%], [n], [%], [n], [%], [n], [%],
),
table.hline(),
[Gender],
table.cell(colspan: 8)[],
[~Female],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[~Male],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[Marital status],
table.cell(colspan: 8)[],
[~Single],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[~Married/partnered],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[~Divorced/widowed],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[~Other],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[Children #super([a])],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[Cohabitating],
[25], [50], [20], [40], [23], [46], [68], [45.3],
[Highest educational level], table.cell(colspan: 8)[],
[~Middle school], [25], [50], [20], [40], [23], [46], [68], [45.3],
[~High school/some college], [25], [50], [20], [40], [23], [46], [68], [45.3],
[~University or postgraduate degree], [25], [50], [20], [40], [23], [46], [68], [45.3],
[Employment], table.cell(colspan: 8)[],
[~Unemployed], [25], [50], [20], [40], [23], [46], [68], [45.3],
[~Student], [25], [50], [20], [40], [23], [46], [68], [45.3],
[~Self-employed], [25], [50], [20], [40], [23], [46], [68], [45.3],
[~Retired], [25], [50], [20], [40], [23], [46], [68], [45.3],
[Previous psychological treatment#super[a]], [25], [50], [20], [40], [23], [46], [68], [45.3],
[Previous psychotropic medication#super[a]], [25], [50], [20], [40], [23], [46], [68], [45.3],
table.hline(),
)
#set align(left)
_Note._
N = 150 (n = 50 for each condition). Participants were on average 39.5 years old (SD = 10.1), and participant age did not differ by condition.\
#super[a] Reflects the number and percentage of participants answering “yes” to this question.
],
caption: [Sociodemographic Characteristics of Participants at Baseline],
) <table:sample-demographic-characteristics>
== Sample Results of Several $t$ Tests Table
Referencing @table:sample-results-of-several-t-tests.
#figure(
[
#table(
align: (x, y) =>
if (y == 0 or y == 1) and x >= 0 { center }
else if x == 0 and y > 0 { left }
else { center },
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
table.header(
table.hline(),
table.cell(rowspan: 2)[Logistic parameter],
table.cell(colspan: 2)[9-year-olds],
table.cell(colspan: 2)[16-year-olds],
table.cell(rowspan: 2)[$t(40)$],
table.cell(rowspan: 2)[$p$],
table.cell(rowspan: 2)[Cohen's $d$],
table.hline(),
[M], [SD], [M], [SD]
),
table.hline(),
[Maximum asymptote, proportion],
[0.85], [0.05], [0.90], [0.04], [2.56], [.014], [.63],
[Crossover, in ms],
[500], [50], [450], [40], [2.34], [.024], [.56],
[Slope, as change in proportion per ms],
[.002], [.0005], [.0025], [.0004], [2.56], [.014], [.63],
table.hline(),
)
#set align(left)
_Note._
For each subject, the logistic function was fit to target fixations separately. The maximum asymptote is the asymptotic degree of looking at the end of the time course of fixations. The crossover point is the point in time the function crosses the midway point between peak and baseline. The slope represents the rate of change in the function measured at the crossover. Mean parameter values for each of the analyses are shown for the 9-year-olds (n = 24) and 16-year-olds (n = 18), as well as the results of t tests (assuming unequal variance) comparing the parameter estimates between the two ages.
],
caption: [Results of Curve-Fitting Analysis Examining the Time Course of Fixations to the Target],
) <table:sample-results-of-several-t-tests>
== Sample Correlation Table
Referencing @table:sample-correlation.
#figure(
[
#table(
align: (x, y) =>
if y == 0 and x >= 0 { center }
else if x == 0 and y > 0 { left }
else { center },
columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr),
table.hline(),
table.header(
[Variable], [_n_], [_M_], [_SD_], [1], [2], [3], [4], [5], [6], [7],
),
[1. Internal-external status#super[a]], [3,697], [0.43], [0.49], [-], [-], [-], [-], [-], [-], [-],
[2. Manager job performance], [2,134], [3.14], [0.62], [-.08\*\*], [-], [-], [-], [-], [-], [-],
[3. Starting salary#super[b]], [3,697], [1.01], [0.27], [.45\*\*], [-.01], [-], [-], [-], [-], [-],
[4. Subsequent promotion], [3,697], [0.33], [0.47], [.08\*\*], [-.07\*\*], [.04\*], [-], [-], [-], [-],
[5. Organizational tenure], [3,697], [6.45], [6.62], [-.29\*\*], [.09\*\*], [.01], [.09\*\*], [-], [-], [-],
[6. Unit service performance#super[c]], [3,505], [85.00], [6.98], [-.25\*\*], [-.39\*\*], [.24\*\*], [.08\*\*], [.01], [-], [-],
[7. Unit financial performance#super[c]], [694], [42.61], [5.86], [.00], [-.03], [.12\*], [-.07], [-.02], [.16\*\*], [-],
table.hline(),
)
#set align(left)
#super[a] 0 = internal hires and 1 = external hires.\
#super[b] A linear transformation was performed on the starting salary values to maintain pay practice confidentiality. The standard deviation (0.27) can be interpreted as 27% of the average starting salary for all managers. Thus, ±1 SD includes a range of starting salaries from 73% (i.e., 1.00 – 0.27) to 127% (i.e., 1.00 + 0.27) of the average starting salaries for all managers.\
#super[c] Values reflect the average across 3 years of data.\
#super[\*]$p < .05$. #super[\*\*]$p < .01$.
],
caption: [Descriptive Statistics and Correlations for Study Variables],
) <table:sample-correlation>
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/tests/topdown/footer/test.typ | typst | The Unlicense | #import "../ledger.typ": *
#set text(size: 11pt)
#set page(height: 5cm, margin: 1em)
#dining-table.make(columns: example,
footer: none,
data: data,
notes: dining-table.note.display-list
)
#v(0.5cm)
#dining-table.make(columns: example,
footer: (
table.cell(
colspan: 3, fill: none,
align(right, strong(smallcaps[total])),
),
[#{7*100}],[00],
[#{7*99}],[00]
),
data: data,
notes: dining-table.note.display-list
) |
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/utierne/utierenBezKnaza.typ | typst | #import "../../../style.typ": *
#import "/SK/texts.typ": *
#import "../styleCasoslov.typ": *
= Každodenná utiereň <X>
#show: rest => columns(2, rest)
TODO: zaciatok
#lettrine("Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami.")
#lettrine("Amen.")
#lettrine("Sláva na výsostiach Bohu a na zemi pokoj ľuďom dobrej vôle.") #note[(3x)]
#lettrine("Pane, otvor moje pery, a moje ústa budú ohlasovať tvoju slávu.") #note[(2x)]
== Šesťžalmie <X>
#zalm(3)
#zalm(37)
#zalm(62)
#si
#lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)]
#ektenia(3)
#zalm(87)
#zalm(102)
#zalm(142)
#si
#lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)]
#ektenia(12)
== Boh je Pán <X>
#verseSoZvolanim("Boh je Pán a zjavil sa nám, * požehnaný, ktorý prichádza v mene Pánovom.",
(
"Oslavujte Pána, lebo je dobrý, * lebo jeho milosrdenstvo trvá naveky.",
"Obkľúčili ma nepriatelia zovšadiaľ, * ale v mene Pánovom som ich porazil.",
"Ja nezomriem, budem žiť * a vyrozprávam skutky Pánove.",
"Kameň, čo stavitelia zavrhli, sa stal kameňom uholným. * To sa stalo na pokyn Pána; vec v našich očiach obdivuhodná."
))
== Tropár <X>
#note[Berieme tropáre podľa predpisu]
== Katizmy a sedaleny <X>
#note[Berieme katizmy podľa predpisu.]
#note[Medzi katizmami berieme sedaleny.]
#zalm(50)
== Kánon <X>
#note[Berieme kánon podľa predpisu]
#note[Po ôsmej piesni, berieme Velebenie Bohorodičky]
#verseSoZvolanim("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.",
(
"Velebí moja duša Pána * a môj duch jasá v Bohu, mojom Spasiteľovi.",
"Lebo zhliadol na poníženosť svojej služobnice, * hľa, od tejto chvíle blahoslaviť ma budú všetky pokolenia.",
"Lebo veľké veci mi urobil ten, ktorý je mocný, a sväté je jeho meno. * A jeho milosrdenstvo z pokolenia na pokolenie s tými, čo sa ho boja.",
"Ukázal silu svojho ramena, * rozptýlil tých, čo v srdci pyšne zmýšľajú.",
"Mocnárov zosadil z trónov a povýšil ponížených. * Hladných nakŕmil dobrotami a bohatých prepustil naprázdno.",
"Ujal sa Izraela, svojho služobníka, lebo pamätá na svoje milosrdenstvo, * ako sľúbil našim otcom, Abrahámovi a jeho potomstvu naveky."
), prve: false)
#lettrine("Dôstojné je velebiť teba, Bohorodička, vždy blažená a nepoškvrnená Matka nášho Boha. Čestnejšia si ako cherubíni a neporovnateľne slávnejšia ako serafíni, bez porušenia si porodila Boha Slovo, opravdivá Bohorodička, velebíme ťa.")
== Svitilen <X>
#svitileny
== Chvály <X>
#include "../../zalmy/Z_ChvalyMale.typ"
#verse((
"Aby ich súdili podľa písaného práva. * Všetkým jeho svätým to bude na slávu.",
"Chváľte Pána v jeho svätyni! * Chváľte ho na jeho vznešenej oblohe.",
"Chváľte ho za jeho činy mohutné; * chváľte ho za jeho nesmiernu velebnosť.",
"Chváľte ho zvukom poľnice, * chváľte ho harfou a citarou.",
"Chváľte ho bubnom a tancom, * chváľte ho lýrou a flautou.",
"Chváľte ho ľubozvučnými cimbalmi, chváľte ho jasavými cimbalmi; všetko, čo dýcha, nech chváli Pána.",
), start: 6)
#ektenia(3)
== Slávoslovie <X>
#slavoslovieMale
#ektenia(12)
== Veršové slohy <X>
#note[Berieme veršové slohy s veršami podľa predpisu.]
Dobré je oslavovať Pána a ospevovať meno tvoje, Najvyšší.
Za rána zvestovať tvoju dobrotu a tvoju vernosť celé noc.
#trojsvatePoOtcenas
== Tropáre <X>
#note[Berieme predpísané tropáre]
#ektenia(12)
#prepustenieBezKnaza
|
|
https://github.com/OtaNix-ry/typst-packages | https://raw.githubusercontent.com/OtaNix-ry/typst-packages/main/README.md | markdown | MIT License | # OtaNix ry typst-packages
Typst packages providing various OtaNix related document templates and styles.
## Templates
### Board-meeting
The OtaNix board-meeting document template (w/logo)

This template is mostly adapted from
- https://github.com/DVDTSB/dvdtyp/
Copyright (c) 2024 DVDTSB
- https://github.com/piepert/grape-suite/blob/main/src/exercise.typ
Copyright (c) 2024 <NAME>
## Getting Started
To create a new typst project which uses these typst packages you can use the provided flake template:
```shell
nix flake init -t github:OtaNix-ry/typst-packages
```
This creates a new flake with the following sample typst document
```typst
#import "@otanix/board-meeting:0.1.0": *
#show: meeting.with(
title: "OtaNix ry hallituksen kokous",
subtitle: "Mallidokumentti"
)
```
### Without flakes
TODO npins
## Adding to an existing typix project
Check the [`examples/quick-start/flake.nix`](./examples/quick-start/flake.nix) flake and adapt it to your needs.
## License
MIT License. [See the full license.](./LICENSE) |
https://github.com/Clay438/3Bao_of_HBUT_workflow | https://raw.githubusercontent.com/Clay438/3Bao_of_HBUT_workflow/master/README.md | markdown | # 3BAO_OF_HBUT_WORKFLOW

3BAO_OF_HBUT_WORKFLOW是一个旨在积极重构[思维导图](/templates/mindmap/),[文献阅读](/templates/文献阅读/),[每科三问](/templates/每科三问/)完成方式的项目,以便:
- 在ddl之前(通常位于期末周),以较短时间完成三宝,提高学习效率。
- 利用typst排版以便减少在word中遇到的排版问题
- 采用markdown格式编写mindmap,操作方便快速,利于扩展。
- 减少重复劳动,提高效率。
## Dependence
- [Typst](https://typst.app/docs/)
- [Markdown](https://markdown.com.cn/basic-syntax/)
- Xmind
- [pandoc](https://pandoc.org)
## Usage
---
### mindmap:
- 思维导图可以被以markdown格式写出,下面是一个示例:
```markdown
- Python基础
- 语法
- 变量
- 数据类型
- 运算符
- 控制流
- 条件语句
- 循环
- 函数
- 定义和调用
- 参数和返回值
- 递归
- 数据结构
- 列表
- 元组
- 字典
- 集合
```
- 一旦完成markdown格式的mindmap,将该文件以markdown格式导入Xmind,导出为png


- 利用pandoc将png转换为pdf
### 文献阅读:
[利用typ模版](/templates/文献阅读/文献阅读表.typ)//(!!!未完成的模版!!!)
### 每科三问:
[利用typ模版](/templates/每科三问/每科三问.typ)//(!!!未完成的模版!!!)
|
|
https://github.com/jamesrswift/typst_templates | https://raw.githubusercontent.com/jamesrswift/typst_templates/main/rsc-template/0.1.0/rsc-template.typ | typst | #let LARGE = text.with(size: 15pt)
#let Large = text.with(size: 12pt)
#let large = text.with(size: 10pt)
#let normalSize = text.with(size: 9pt)
#let footnoteSize = text.with(size: 7pt)
#let create_dates(article_dates) = {
return table(
inset: 0pt,
row-gutter: 0.15cm,
stroke: none,
columns: (1fr, 1fr),
..article_dates.map( entry =>{
return (
footnoteSize[#entry.type:],
footnoteSize[#entry.date]
)
}).flatten()
)
}
#let create_manuscript_information_left(article_dates, doi) = {
return align(bottom)[
#create_dates(article_dates)
#footnoteSize[DOI: #doi]
]
}
#let create_manuscript_information_right(title, authors, abstract) = {
return [
#block(LARGE(weight:500, title))
#v(0.6cm, weak: true)#authors.map(author=>author.name).join(", ")
#v(1.618em, weak: true)
#par(justify: true)[#abstract]
]
}
#let pageCount() = locate( loc => [#counter(page).final(loc).at(0)] )
#let project(
title: [],
title_string: "",
authors: (),
abstract: [],
journal: "Journal Name",
article_type: "Article Type",
article_dates: (),
doi: "",
keywords: [],
year: 2023,
volume: 3,
body,
) = {
// Set the document's basic properties.
set document(author: authors.map(a => a.name), title: title_string)
set page(
paper: "us-letter",
margin: (left: 10mm, right: 10mm, top: 12mm, bottom: 15mm),
numbering: "1",
number-align: end,
footer: locate( loc => [
#if calc.even(loc.page()) [
#align(left)[
#counter(page).display()#h(0.75em)| #h(1em) _ #journal _, #year, *#volume*, 1---#pageCount()
]
] else [
#align(right)[
_ #journal _, #year, *#volume*, 1---#pageCount() #h(1em)|#h(0.75em)#counter(page).display()
]
]
])
)
set text(font: "Droid Sans", lang: "en", size:9pt)
show math.equation: set text(weight: 400)
// Set paragraph spacing.
//show par: set block(above: 0.75cm, below: 0.8cm)
show heading: set block(above: 1.4em, below: 0.8em)
show heading: set text(size: 12pt)
set heading(numbering: "1.1")
//set par(leading: 0.58em)
v(1.2em)
// Journal Name
block( inset: 0.2cm,text(weight: 200, 28pt, journal))
// Article type
block(fill: rgb(167,195,212), text(weight: 200, 24pt, article_type ,fill: white), width: 100% , inset: 10pt, radius: 2pt)
// Manuscript Information
pad(
top: 0.3em, bottom: 0.3cm,
x: 0em,
grid(
columns: (1.4fr,5fr),
gutter: 0em,
create_manuscript_information_left(article_dates, doi),
create_manuscript_information_right(title, authors, abstract)
)
)
line(length: 100%, stroke:0.5pt)
v(0.8em)
// Main body.
set par(justify: true, first-line-indent: 0.45cm);
show par: set block(above: 0pt, below: 0.7em,)
show: columns.with(2, gutter: 1.618em)
body
} |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chordx/0.2.0/README.md | markdown | Apache License 2.0 | # chordx
A package to write song lyrics with chord diagrams in Typst.
**Table of Contents**
- [Introduction](#introduction)
- [Usage](#usage)
- [Typst Packages](#typst-packages)
- [Local Packages](#local-packages)
- [Documentation](#documentation)
- [Examples](#examples)
- [Chart Chords](#chart-chords)
- [Piano Chords](#piano-chords)
- [Single Chords](#single-chords)
- [License](#license)
## Introduction
With `chordx` you can easily generate song lyrics with chords for writing songbooks.
`chordx` generates chord charts for stringed instruments (e.g. guitar, ukulele, etc.), piano chords (with diferent piano layouts) and single chords that are chords without charts used to write the chords over a word to write songbooks.
## Usage
`chordx` exports 3 functions that return others with default settings:
- `new-chart-chords`: used to generate chart chords for stringed instruments.
- `new-piano-chords`: used to generate piano chords.
- `new-single-chords`: used to show the chord name over a word.
### Typst Packages
Typst added an experimental package repository and you can import `chordx` as follows:
```js
#import "@preview/chordx:0.2.0": *
```
### Local Packages
If the package hasn't been released yet, or if you just want to use it from this repository, you can use _*local-packages*_.
You can read the documentation about typst [local-packages](https://github.com/typst/packages#local-packages) and learn about the path folders used in differents operating systems (Linux / MacOS / Windows).
In Linux you can do:
```sh
git clone https://github.com/ljgago/typst-chords ~/.local/share/typst/packages/local/chordx/0.2.0
```
And import the package in your file:
```typ
#import "@local/chordx:0.2.0": *
```
## Documentation
Here [chordx-docs](https://github.com/ljgago/typst-chords/blob/main/docs/chordx-docs.pdf) you have the reference documentation that describes the functions and parameters used in this package. (_Generated with [tidy](https://github.com/Mc-Zen/tidy)_)
## Examples:
### Chart Chords
```typ
#import "@preview/chordx:0.2.0": *
#let chart-chord = new-chart-chords(scale: 1.5)
#let chart-chord-round = new-chart-chords(style: "round", scale: 1.5)
// Style "normal"
#chart-chord(tabs: "x32o1o", fingers: "n32n1n")[C]
#chart-chord(tabs: "ooo3", fingers: "ooo3")[C]
// Style "round"
#chart-chord-round(tabs: "xn332n", fingers: "o13421", fret-number: 3, capos: "115")[Cm]
#chart-chord-round(tabs: "onnn", fingers: "n111", capos: "313")[Cm]
```
<h3 align="center">
<a href="https://github.com/ljgago/typst-chords/blob/main/examples/chart-chords.typ">
<img
alt="Graph Chord"
src="https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/chart-chords.svg"
style="max-width: 100%; width: 450pt; padding: 10px 20px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 8pt; box-sizing: border-box; background: white"
>
</a>
</h3>
### Piano Chords
```typ
#import "@preview/chordx:0.2.0": *
#let piano-chord = new-piano-chords(scale: 1.5)
#let piano-chord-round = new-piano-chords(scale: 1.5, style: "round")
#piano-chord(layout: "F", keys: "<KEY>", color: blue)[B]
#piano-chord-round(layout: "F", keys: "<KEY>", color: red)[B]
```
<h3 align="center">
<a href="https://github.com/ljgago/typst-chords/blob/main/examples/piano-chords.typ">
<img
alt="Graph Chord"
src="https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/piano-chords.svg"
style="max-width: 100%; width: 450pt; padding: 10px 20px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 8pt; box-sizing: border-box; background: white"
>
</a>
</h3>
### Single Chords
```typ
#import "@preview/chordx:0.2.0": *
#let chord = new-single-chords(style: "italic", weight: "semibold")
#chord[Jingle][G][2] bells, jingle bells, jingle #chord[all][C][2] the #chord[way!][G][2] \
#chord[Oh][C][] what fun it #chord[is][G][] to ride \
In a #chord[one-horse][A7][2] open #chord[sleigh,][D7][3] hey!
```
<h2 align="center">
<a href="https://github.com/ljgago/typst-chords/blob/main/examples/single-chords.typ">
<img
alt="Single Chord"
src="https://raw.githubusercontent.com/ljgago/typst-chords/main/examples/single-chords.svg"
style="max-width: 100%; width: 450pt; padding: 10px 20px; box-shadow: 1pt 1pt 10pt 0pt #AAAAAA; border-radius: 8pt; box-sizing: border-box; background: white"
>
</a>
</h2>
## License
[MIT License](./LICENSE)
|
https://github.com/kotatsuyaki/canonical-nthu-thesis | https://raw.githubusercontent.com/kotatsuyaki/canonical-nthu-thesis/main/layouts/preface.typ | typst | MIT License | #let preface-impl(
margin: (:),
it,
) = {
set page(
margin: margin,
numbering: "i",
)
set par(
leading: 1.5em,
first-line-indent: 2em,
)
// Disable heading numbering.
set heading(numbering: none)
show heading.where(
level: 1,
): it => {
// Show the body of the heading with some vertical spacing surrounding.
// Headings in the preface are not numbered.
block(width: 100%, {
set text(size: 24pt)
v(3em)
it.body
v(2em)
})
}
// Show level-1 outline entries in bold text and without the dots.
show outline.entry.where(
level: 1,
): it => {
strong(it.body)
h(1fr)
// strong(repr(it))
strong(it.page)
}
// Reset the page counter to start the abstract at page i.
counter(page).update(1)
it
}
|
https://github.com/grnin/Zusammenfassungen | https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/07_Mutexe_Semaphore.typ | typst | // Compiled with Typst 0.11.1
#import "../template_zusammenf.typ": *
#import "@preview/wrap-it:0.1.0": wrap-content
/*#show: project.with(
authors: ("<NAME>", "<NAME>"),
fach: "BSys2",
fach-long: "Betriebssysteme 2",
semester: "FS24",
tableofcontents: (enabled: true),
language: "de"
)*/
= Mutexe und Semaphore
Jeder Thread hat seinen _eigenen_ Instruction-Pointer und Stack-Pointer.
Die IPs aller Threads werden _unabhängig_ voneinander bewegt. Bei parallelen Threads
völlig unabhängig und _nicht synchron_, selbst bei identischem Code. Bei nebenläufigen
Threads auf dem selben Prozessor immer in Bursts bis zum nächsten Thread-Wechsel.
== Synchronisations-Mechanismen Grundlagen
Ein Thread erzeugt Items: _der Producer_.
Ein anderer Thread verarbeitet diese: _der Consumer_.
Beide Threads arbeiten _unterschiedlich schnell_. Items werden über einen _begrenzt
grossen Ring-Puffer_ übermittelt.
Falls der Puffer voll ist, muss der Producer warten, bevor er wieder etwas auf den Puffer
legen kann. Gleichermassen muss der Consumer warten, falls der Puffer leer ist.
Da C für _keine noch so kleine Operation garantiert_, dass sie in eine
_einzige Instruktion_ übersetzt wird #hinweis[(non-atomic)], wird dieses Problem eine
_Race-Condition_ auslösen.
=== Race-Condition
Wenn Ergebnisse von der _Ausführungsreihenfolge_ einzelner Instruktionen abhängen, spricht
man von einer _Race Condition_. Register werden beim Kontext-Wechsel gesichert,
der Counter aber nicht. Greifen _nebenläufige Threads_ schreibend und lesend auf den
_gleichen Hauptspeicherbereich_ zu, gibt es _keine Garantien_, was passieren wird.
Wenn die Änderung nicht schnell genug erfolgt, bekommt sie der andere Thread nicht mit,
während er selbst Änderungen vornimmt. Ein Thread muss andere Threads vom Zugriff
ausschliessen können - _Threads müssen synchronisiert werden_.
=== Critical Sections
Jeder kooperierende Thread hat einen Code-Bereich, in dem er Daten mit anderen Threads
teilt, die _Critical Section_. Es wird ein _Protokoll_ benötigt, anhand dessen Threads den
Zugang zu ihren Critical Sections _synchronisieren_ können.
=== Atomare Instruktionen
Eine atomare Instruktion kann vom Prozessor _unterbrechungsfrei_ ausgeführt werden.\
#hinweis[*Achtung:* Selbst einzelne Assembly-Instruktionen können unter Umständen nicht
atomar durchgeführt werden, z.B. non-aligned Memory Access]
=== Anforderungen an Synchronisations-Mechanismen
- _Gegenseitiger Ausschluss:_ Wenn ein Thread in seiner Critical Section ist, dürfen alle
anderen Threads ihre Critical Section nicht betreten. #hinweis[(mutual exclusion, mutex)]
- _Fortschritt:_ Wenn kein Thread in seiner Critical Section ist und irgendein Thread in
seine Critical Section möchte, muss in endlicher Zeit eine Entscheidung getroffen
werden, wer als nächstes in die Critical Section darf.
- _Begrenztes Warten:_ Es gibt eine feste Zahl $n$, sodass gilt: Wenn ein Thread seine
Critical Section betreten will, wird er nur $n$-mal übergangen.
=== Implementierung von Synchronisations-Mechanismen
Moderne Computer-Architekturen geben _kaum Garantien_ bezüglich der Ausführung von
Instruktionen. Instruktionen müssen _nicht atomar_ sein, Sequenzen können äquivalent
_umgeordnet_ werden. Synchronisations-Mechanismen können auf modernen Computern
_nur mit Hardwareunterstützung_ implementiert werden.
==== Konzept: Abschaltung von Interrupts
Alle Interrupts werden abgeschaltet, wenn eine _Critical Section betreten_ werden soll.
Auf Systemen mit _einem Prozessor effektiv_, weil es zu keinem Kontext-Wechsel kommen kann.
Für Systeme mit _mehreren Prozessoren_ jedoch _nicht praktikabel_, da Interrupts für alle
Threads ausgeschaltet werden müssten.
_Generell gefährlich:_ Solange die Interrupts ausgeschaltet sind, kann das OS den Thread
nicht unterbrechen.
==== Verwendung spezieller Instruktionen
Moderne Prozessoren stellen eine von zwei _atomaren_ Instruktionen zur Verfügung, mit
denen _Locks_ implementiert werden können:
- _Test-And-Set:_ Setzt einen `int` auf 1 und returnt den vorherigen Wert
- _Compare-And-Swap:_ Das gleiche, aber in Fancy: überschreibt einen `int` mit einem
spezifizierten Wert, wenn dieser dem erwarteten Wert entspricht.
*Test-And-Set:*
Liest den Wert von einer Adresse (0 oder 1) und setzt ihn dann auf 1.
```c
test_and_set (int * target) { int value = *target; *target = 1; return value; }
int lock = 0;
// T1: sets lock = 1 & reads 0, T2 sets lock = 1, but reads 1
while (tas (&lock) == 1) { /* busy loop */ }
// critical section
lock = 0;
```
*Compare-And-Swap*:
_Liest_ einen Wert aus dem Hauptspeicher und _überschreibt_ ihn im Hauptspeicher,
falls er einem _erwarteten Wert_ entspricht.
```c
compare_and_swap (int *a, int expected, int new_a) {
int value = *a;
if (value == expected) { *a = new_a; }
return value;
}
while (cas (&lock, 0, 1) == 1) { /* busy loop */ }
// critical section
lock = 0;
```
Kommen zwei Threads $T_1$ und $T_2$ genau gleichzeitig an die while-Schleife, garantiert
die HW, dass _nur $bold(T_1)$ `test_and_set`_ bzw. _`compare_and_swap`_ ausführt.
$T_1$ setzt `lock` auf 1, liest aber 0 und _verlässt_ die Schleife sofort.
$T_2$ sieht `lock` auf jeden Fall als 1 und _bleibt_ in der Schleife.
#pagebreak()
== Semaphore
Ein Semaphore enthält einen _Zähler $bold(z >= 0)$_. Auf den Semaphor wird nur über
spezielle Funktionen zugegriffen:
- _Post (v):_ Erhöht $z$ um 1
- _Wait (p):_ Wenn $z > 0$, verringert $z$ um $1$ und setzt Ausführung fort.
Wenn $z=0$, versetzt den Thread in waiting, bis ein anderer Thread $z$ erhöht.
=== Producer-Consumer-Problem mit Semaphoren
Der _Producer_ wartet darauf, dass mindestens ein Element _frei_ ist.
Der _Consumer_ wartet darauf, dass mindestens ein Element _gefüllt_ ist.
Dafür verwenden wir _zwei Semaphore_.
Die Consumer und Producer geben sich diese gegenseitig frei.
```c
semaphore free = n;
semaphore used = 0;
```
#columns(2)[
```c
// Producer
while (1) {
// Warte, falls Customer zu langsam
WAIT (free); // Hat es Platz in Queue?
produce_item (&buffer[w], ...);
POST (used); // 1 Element mehr in Queue
w = (w+1) % BUFFER_SIZE;
}
```
#colbreak()
```c
// Consumer
while (1) {
// Warte, falls Producer zu langsam
WAIT (used); // Hat es Elemente in Queue?
consume (&buffer[r]);
POST (free); // 1 Element weniger in Q
r = (r+1) % BUFFER_SIZE;
}
```
]
=== ```c int sem_init (sem_t *sem, int pshared, unsigned int value);```
_Initialisiert den Semaphor `sem`_, sodass er `value` Marken enthält
#hinweis[(max. Grösse der Queue)]. Ist `pshared = 0`, kann `sem` nur innerhalb eines
Prozesses verwendet werden, ansonsten über mehrere.
==== Anwendung als globale Variable
Typischerweise legt man im Programm eine _globale Variable_ `sem` vom Typ `sem_t` an.
_Bevor_ der erste Thread gestartet wird, der `sem` verwenden soll, wird _`sem_init`_
aufgerufen, z.B. im `main()`.
```c
sem_t sem;
int main ( int argc, char ** argv ) { sem_init (&sem, 0, 4); }
```
==== Anwendung als Parameter für den Thread
Alternativ definiert man im Struct, das dem Thread übergeben wird, einen Member `sem` vom
Typ `sem_t *`.\
Der Speicher für den Semaphor wird dann entweder auf dem Stack oder auf dem Heap alloziert.
```c
struct T { sem_t *sem; ... };
int main ( int argc, char ** argv ) {
sem_t sem;
sem_init (&sem, 0, 4);
struct T t = { &sem, ... };
}
```
=== `sem_wait` und `sem_post`
```c int sem_wait (sem_t *sem); int sem_post (sem_t *sem);```
implementieren _Post_ und _Wait_. Geben 0 zurück, wenn Aufruf OK, sonst -1 und Fehlercode
in `errno`. Im _Fehlerfall_ wird der Semaphor _nicht verändert_.
=== `sem_trywait` und `sem_timedwait`
```c
int sem_trywait (sem_t *sem);
int sem_timedwait (sem_t *sem, const struct timespec *abs_timeout);
```
Sind wie `sem_wait`, aber _brechen ab_, falls Dekrement _nicht_ durchgeführt werden kann.
`sem_trywait` bricht sofort ab, `sem_timedwait` nach der angegebenen Zeitdauer.
Es gibt kein `sem_trypost`.
=== ```c int sem_destroy (sem_t *sem);```
_Entfernt_ möglichen zusätzlichen _Speicher_, den das OS mit `sem` _assoziiert_ hat.
#pagebreak()
== Mutexe
Ein Mutex hat einen _binären Zustand $bold(z)$_, der nur durch zwei Funktionen verändert werden kann:
- _Acquire:_ Wenn $z = 0$, setze $z$ auf 1 und fahre fort.
Wenn $z = 1$, blockiere den Thread , bis $z = 0$
- _Release:_ Setzt $z = 0$
Kann durch einen Semaphor mit _Beschränkung_ von $z$ auf 1 realisiert werden.
Acquire und Release heissen auch _Lock_ bzw. _Unlock_.
Ein Mutex ist die _einfachste Form_ der Synchronisierung.
Acquire und Release müssen immer paarweise durchgeführt werden.
```c ACQUIRE(mutex); ++counter; RELEASE(mutex);```
=== POSIX Thread Mutex API
==== ```c int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);```
_Initialisiert_ die opake Daten-Struktur _`pthread_mutex_t`_.
Attribute sind _optional_, Verwendung analog zu `pthread`-Attributen mit
`pthread_mutexattr_init, ..._destroy`.
_Attribute:_
`protocol`: z.B. `PTHREAD_PRIO_INHERIT`: Mutex verwendet Priority-Inheritance,
`pshared`: Mutex kann von anderen Prozessen verwendet werden,
`type`: Mutex kann beliebig oft vom selben Thread aquiriert werden,
`prioceiling`: Minimale Priorität der Threads, die den Mutex halten.
```c
int pthread_mutex_lock (pthread_mutex_t *mutex); // acquire (blocking)
int pthread_mutex_trylock (pthread_mutex_t *mutex); // attempt to acquire (non-blocking)
int pthread_mutex_unlock (pthread_mutex_t *mutex); // release
int pthread_mutex_destroy (pthread_mutex_t *mutex) // cleanup
```
```c
// Beispiel Initialisierung
pthread_mutex_t mutex; // global variable
int main() {
pthread_mutex_init (&mutex, 0); // 0 = default Attribute
// run threads and wait for them to finish
pthread_mutex_destroy (&mutex);
}
// Beispiel Verwendung in Threads
void * thread_function (void * args) {
while (running) {
...
pthread_mutex_lock (&mutex); // Enter critical section
// Perform critical section, e.g. ++counter
pthread_mutex_unlock (&mutex); // Leave critical section
...
}
}
```
#wrap-content(
image("img/bsys_35.png"),
align: top + right,
columns: (75%, 25%),
)[
=== Priority Inversion und Priority Inheritance
- Thread $A$ hat _niedrige Priorität_ und hält einen Mutex $M$
- Thread $B$ hat _mittlere Priorität_
- Thread $C$ hat _hohe Priorität_ und läuft gerade.
Nach 10ms benötigt Thread $C$ den Mutex $M$.
Ein _hoch-priorisierter_ Thread wartet auf eine Ressource, die von einem _niedriger
priorisierten_ Thread _gehalten_ wird. Ein Thread mit Prioriät zwischen diesen beiden
Threads erhält den Prozessor. Die effektiven Prioritäten des hoch-priorisierten und des
mittel-priorisierten Threads sind _invertiert_ gegenüber den zugewiesenen Prioritäten.
_Gemeinsam verwendete Ressourcen werden bei Prioritiy Inversion im schlimmsten Fall mit
der niedrigsten Priorität aller beteiligten Threads gehalten._
]
#wrap-content(
image("img/bsys_36.png"),
align: top + right,
columns: (75%, 25%),
)[
Um dieses Problem zu lösen, wird bei Priority Inheritance die _Priorität von $bold(A)$
temporär auf die Priorität von $bold(C)$ gesetzt_, damit der Mutex schnell wieder
freigegeben wird. $A$ läuft, bis er den Mutex $M$ freigibt, danach erhält $A$ wieder die
vorherige Priorität und $C$ läuft weiter.
] |
|
https://github.com/mem-courses/discrete-mathmatics | https://raw.githubusercontent.com/mem-courses/discrete-mathmatics/main/template.typ | typst | MIT License | #import "@preview/tablex:0.0.8": tablex, colspanx, rowspanx, hlinex, vlinex, cellx
#let font_song = ("New Computer Modern", "Source Han Serif SC", "Simsun", "STSong")
#let font_fangsong = ("FangSong", "STFangSong")
#let font_hei = ("Calibri", "Source Han Sans SC", "Source Han Sans HW SC", "SimHei", "Microsoft YaHei", "STHeiti")
#let font_kai = ("KaiTi_GB2312", "KaiTi", "STKaiti")
#let definition_counter = state("definition_counter", 0)
#let theorem_counter = state("theorem_counter", 0)
#let problem_counter = state("problem_counter", 0)
#let indent = 0em
#let force-indent = 2em
#let par-margin = 0.8em
#let fake_par = [#text()[#v(0pt, weak: true)];#text()[#h(0em)]]
#let project(
course: "",
title: "",
authors: (),
date: none,
body,
course_fullname: "",
semester: "",
course_code: "",
) = {
if (course_fullname == "") {
course_fullname = course
}
if (course_code != "") {
course_fullname = course_fullname + " (" + course_code + ")"
}
// 文档基本信息
set document(author: authors.map(a => a.name), title: title)
set page(
paper: "a4",
margin: (left: 12mm, right: 12mm, top: 20mm, bottom: 20mm),
numbering: "1",
number-align: center,
)
// 页眉
set page(header: {
locate(loc => {
if (counter(page).at(loc).at(0) == 1) {
return none
}
set text(font: font_song, 10pt, baseline: 8pt, spacing: 3pt)
grid(
columns: (1fr, 1fr, 1fr),
align(left, course),
[]/* align(center, title)*/,
align(right, date),
)
line(length: 100%, stroke: 0.5pt)
})
})
// 页脚
set page(footer: {
set text(font: font_song, 10pt, baseline: 8pt, spacing: 3pt)
set align(center)
grid(
columns: (1fr, 1fr),
align(left, authors.map(a => a.name).join(", ")),
align(right, counter(page).display("1/1", both: true)),
)
})
set text(font: font_song, lang: "en", size: 12pt)
show math.equation: set text(weight: 400)
// Set paragraph spacing.
show par: set block(above: par-margin, below: par-margin)
// set heading(numbering: "1.1)")
set par(leading: 0.75em)
block(
below: 4em,
stroke: 0.5pt + black,
radius: 2pt,
width: 100%,
inset: 1em,
outset: -0.2em,
)[
#text(size: 0.84em)[#grid(
columns: (auto, 1fr, auto),
align(left, strong(course_fullname)),
[],
align(right, strong(semester)),
)]
#v(0.75em)
#align(center)[#text(size: 1.5em)[#title]]
#v(0.75em)
#block(
..authors.map(author => align(center)[
#text(size: 0.84em)[#grid(
columns: (auto, 1fr, auto),
align(left, author.name + " (" + author.id + ")"),
[],
align(right, author.email),
)]
]),
)
]
// Main body.
set par(justify: true)
show "。": "."
show heading.where(level: 1): it => [
#definition_counter.update(x => 0)
#theorem_counter.update(x => 0)
#set text(size: 1.2em)
#it
#v(0.15em)
]
show heading.where(level: 2): it => [
#theorem_counter.update(x => 0)
#it
]
set par(first-line-indent: indent)
set table(inset: 5pt, stroke: 0.5pt, align: horizon + center)
body
}
#let song(it) = text(it, font: font_song)
#let fangsong(it) = text(it, font: font_fangsong)
#let hei(it) = text(it, font: font_hei)
#let kai(it) = text(it, font: font_kai)
#let bb = it => [#strong[#it]]
#let hw(name, it, jt) = {
block(width: 100%)[
#let hl(x) = strong(text(x, font: ("Cambria", ..font_hei), number-type: "old-style"))
#v(0.4em)
#problem_counter.update(x => (x + 1))
#hl[Exercise #name:]
#it#fake_par#fake_par
#v(0.2em)
#h(-indent)#hl[Solution:]
#jt
#v(0.8em)
]
}
#let named_block(it, name: "", color: red, inset: 11pt) = block(
below: 1em,
stroke: 0.5pt + color,
radius: 3pt,
width: 100%,
inset: inset,
)[
#place(
top + left,
dy: -6pt - inset, // Account for inset of block
dx: 8pt - inset,
block(fill: white, inset: 2pt)[
#set text(font: "Noto Sans", fill: color)
#strong[#name]
]
)
#let fontcolor = color.darken(20%)
#set text(fill: fontcolor)
#set par(first-line-indent_width: 0em)
#it
]
#let example(it) = named_block(it, name: "Example", color: gray.darken(60%))
#let proof(it) = named_block(it, name: "Proof", color: rgb(120, 120, 120))
#let abstract(it) = named_block(it, name: "Abstract", color: rgb(0, 133, 143))
#let summary(it) = named_block(it, name: "Summary", color: rgb(0, 133, 143))
#let info(it) = named_block(it, name: "Info", color: rgb(68, 115, 218))
#let note(it) = named_block(it, name: "Note", color: rgb(68, 115, 218))
#let tip(it) = named_block(it, name: "Tip", color: rgb(0, 133, 91))
#let hint(it) = named_block(it, name: "Hint", color: rgb(0, 133, 91))
#let success(it) = named_block(it, name: "Success", color: rgb(62, 138, 0))
#let help(it) = named_block(it, name: "Help", color: rgb(153, 110, 36))
#let warning(it) = named_block(it, name: "Warning", color: rgb(184, 95, 0))
#let attention(it) = named_block(it, name: "Attention", color: rgb(216, 58, 49))
#let caution(it) = named_block(it, name: "Caution", color: rgb(216, 58, 49))
#let failure(it) = named_block(it, name: "Failure", color: rgb(216, 58, 49))
#let danger(it) = named_block(it, name: "Danger", color: rgb(216, 58, 49))
#let error(it) = named_block(it, name: "Error", color: rgb(216, 58, 49))
#let bug(it) = named_block(it, name: "Bug", color: rgb(204, 51, 153))
#let quote(it) = named_block(it, name: "Quote", color: rgb(132, 90, 231))
#let cite(it) = named_block(it, name: "Cite", color: rgb(132, 90, 231))
#let table3-global-align = align
#let table3(
..args,
inset: 0.5em,
stroke: 0.5pt,
width: 100%,
align: center + horizon,
columns: 1,
) = {
set table3-global-align(center)
if type(columns) == int {
let new_columns = ()
for i in range(columns) {
new_columns.push(1fr)
}
columns = new_columns
}
box(
width: width,
clip: true,
stack(
tablex(
..args,
inset: inset,
stroke: stroke,
align: align,
columns: columns,
map-hlines: h => {
if (h.y == 0) {
(..h, stroke: (stroke * 2) + black)
} else if (h.y == 1) {
(..h, stroke: stroke + black)
} else {
(..h, stroke: 0pt)
}
},
auto-vlines: false,
),
line(stroke: (stroke * 2) + black, length: 100%),
),
)
}
#let parts(columns: 1, ..it) = {
let buffer = ()
for (id, sol) in it.named() {
buffer.push([#h(force-indent / 2);*#id)*])
buffer.push(box(width: 100%, sol))
}
grid(
columns: 2 * columns,
column-gutter: 0.25em,
row-gutter: 1em,
..buffer,
)
}
#let indent-box(it, radio: 1) = grid(
columns: (force-indent * radio, 1fr),
column-gutter: 0pt,
[],
it,
)
#let idt = indent-box
#let named_block(it, name: "", color: red, inset: 11pt) = {
block(
below: 1em,
stroke: 0.5pt + color,
radius: 3pt,
width: 100%,
inset: inset,
)[
#place(
top + left,
dy: -6pt - inset, // Account for inset of block
dx: 8pt - inset,
block(fill: white, inset: 2pt)[
#set text(font: "Noto Sans", fill: color)
#strong[#name]
]
)
#let fontcolor = color.darken(0%)
#set text(fill: fontcolor)
#set par(first-line-indent: 0em)
#it
]
fake_par
}
#let correction(it) = named_block(it, name: "Correction", color: rgb(216, 58, 49))
|
https://github.com/j-mueller/typst-vegalite | https://raw.githubusercontent.com/j-mueller/typst-vegalite/main/README.md | markdown | MIT License | # typst-vegalite
Run vegalite in typst. The package is published as [nulite](https://typst.app/universe/package/nulite/). See [typst-package/README.md](typst-package/README.md) for usage instructions.
## Building the project
1. Enter the nix shell with `nix develop`
2. Run `build.sh`. This compiles `js/dist/index.js` to quickjs bytecode and places it in the `typst-package` folder.
|
https://github.com/dainbow/MatGos | https://raw.githubusercontent.com/dainbow/MatGos/master/themes/12.typ | typst | #import "../conf.typ": *
= Равномерная сходимость функциональных последовательностей и рядов. Непрерывность, интегрируемость и дифференцируемость суммы функционального ряда.
== Непрерывность суммы функционального ряда
#definition[
*Функциональная последовательность* $seq(f)$ *сходится равномерно* на $E$ к
функции $f(x)$ ($f_n arrows f$), если
#eq[
$forall epsilon > 0 : exists N in NN : forall n > N : forall x in E : space abs(f_n (x) - f(x)) < epsilon$
]
]
#definition[
Функциональная последовательность $seq(f)$ *сходится поточечно* на $E$ к функции $f(x)$,
если
#eq[
$forall x in E : forall epsilon > 0 : exists N in NN : forall n > N : space abs(f_n (x) - f(x)) < epsilon$
]
]
#theorem(
"Критерий Коши равномерной сходимости функциональной последовательности",
)[
#eq[
$f_n arrows_E f <=> forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : forall x in E : space abs(f_(n + p) (x) - f_n (x)) < epsilon$
]
]
#definition[
*Фукнциональный ряд* $sum_(n = 1)^oo f_n (x)$ *равномерно сходится* на $E$, если
равномерно сходится на $E$ функциональная последовательность $S_n (x) = sum_(k = 1)^n f_k (x)$
]
#theorem(
"Критерий Коши равномерной сходимости функциональных рядов",
)[
#eq[
$sum_(n = 1)^oo f_n "равномерно сходится на " E <=> \
forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : forall x in E : space abs(sum_(k = n)^(n + p) f_k (x)) < epsilon$
]
]
#theorem("Предельный переход в равномерно сходящихся последовательностях")[
Если $seq(f)$ равномерно сходится к $f$ на множестве $E$ метрического
пространства, $x_0$ -- предельная точка $E$, причём
#eq[
$forall n in NN : lim_(x -> x_0, x in E) f_n (x) = a_n$
]
Тогда
#eq[
$lim_(x -> x_0, x in E) f(x) = lim_(n -> oo) a_n$
]
То есть оба предела существуют и равны.
]
#proof[
Воспользуемся критерием Коши равномерной сходимости:
#eq[
$forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : forall x in E : space abs(f_(n + p) (x) - f_n (x)) < epsilon$
]
Совершим предельный переход $x -> x_0$:
#eq[
$forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : space abs(a_(n + p) - a_n) <= epsilon$
]
То есть числовая последовательность $seq(a)$ имеет какой-то предел $a$, теперь
нужно установить, что он равен пределу предельной функции:
#eq[
$abs(f(x) - a) = abs(f(x) - f_n (x)) + abs(f_n (x) - a_n) + abs(a_n - a)$
]
Стоит упомянуть про кванторы:
- Берём номер $N$ больший $N_1$ для равномерного предела функций и $N_2$ для
числового предела $a_n ->_(n -> oo) a$
- $delta$-окрестность $x_0$ меньшую требуемой для фиксированного $f_N (x) ->_(x -> x_0) a_N$
]
#corollary[
Если $f_n (x)$ непрерывна на $E$, $f_n arrows f$ на $E$, то $f$ непрерывна на $E$.
]
#theorem(
"Предельный переход в функциональных рядах",
)[
Если $sum_(n = 1)^oo f_n (x)$ сходится равномерно на $E$, $x_0$ -- предельная
точка $E$, $forall n in NN : space lim_(x -> x_0, x in E) f_n (x) = a_n$, то
#eq[
$sum_(n = 1)^oo a_n = lim_(x -> x_0, x in E) sum_(n = 1)^oo f_n (x)$
]
]
#proof[
Доказывается очевидно применением предыдущей теоремы для последовательности
частичных сумм.
]
== Интегрируемость суммы функционального ряда
#theorem(
"Интегрирование равномерно сходящейся функциональной последовательности",
)[
Если $forall n in NN : space f_n$ интегрируемы по Риману на $[a, b]$ и $f_n arrows f$ на $[a, b]$,
то $f$ интегрируема по Риману на $[a, b]$ и
#eq[
$integral_a^b f(x) dif x = lim_(n -> oo) integral_a^b f_n (x) dif x$
]
]
#proof[
Воспользуемся тем, что каждый элемент функциональной последовательности
интегрируем:
#eq[
$forall n in NN : forall epsilon > 0 : exists P : space U(P, f_n) - L(P, f_n) < epsilon / (3 (b - a))$
]
Далее определение равномерной сходимости:
#eq[
$forall epsilon > 0 : exists N in NN : forall x in [a, b] : space abs(f_n (x) - f(x)) < epsilon / (3 (b - a))$
]
Итак, оценим верхнюю сумму Дарбу предела:
#eq[
$U(P, f) = sum_(k = 1)^n sup_(x in [x_(k - 1), x_k]) f(x) Delta x_k <= \ sum_(k = 1)^n (sup_(x in [x_(k - 1), x_k]) f_n (x) + epsilon / (3 (b - a)))Delta x_k = U(P, f_n) + epsilon / 3$
]
Аналогично для нижней:
#eq[
$L(P, f) >= L(P, f_n) - epsilon / 3$
]
Таким образом,
#eq[
$U(P, f) - L(P, f) <= U(P, f_n) - L(P, f_n) + (2 epsilon) / 3 < epsilon$
]
Мы доказали интегрируемость $f$, осталось доказать, что интеграл равен тому, что
надо:
#eq[
$abs(integral_a^b f_n (x) dif x - integral_a^b f(x) dif x) <= integral_a^b abs(f_n (x) - f(x)) dif x <= epsilon / (3 (b - a)) dot (b - a) < epsilon$
]
]
#theorem(
"Интегрирование функциональных рядов",
)[
Если $f_n in cal(R)[a, b], sum_(n = 1)^oo f_n (x)$ равномерно сходится на $[a, b]$,
то $sum_(n = 1)^oo f_n (x) in cal(R)[a, b]$ и
#eq[
$integral_a^b sum_(n = 1)^oo f_n (x) dif x = sum_(n = 1)^oo integral_a^b f_n (x) dif x $
]
]
#proof[
Доказывается очевидно применением предыдущей теоремы для последовательности
частичных сумм.
]
== Дифференцируемость суммы функционального ряда
#theorem("Дифференцирование функциональных последовательностей")[
Если
+ $f_n$ дифференцируемы на $(a, b)$
+ $f'_n arrows$ на $(a, b)$
+ $exists x_0 in (a, b) : space f_n (x_0) ->_(n -> oo)$
То
+ $f_n arrows f$ на $(a, b)$
+ $f$ дифференцируема на $(a, b)$
+ $f'_n -> f'$ на $(a, b)$
]
#proof[
Используем равномерную сходимость производных:
#eq[
$forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : forall x in (a, b) : space abs(f'_(n + p) (x) - f'_n (x)) < epsilon / (2 (b - a)) $
]
А также сходимость самих функций в точке $x_0$:
#eq[
$forall epsilon > 0 : exists N in NN : forall n > N : forall p in NN : space abs(f_(n + p) (x_0) - f_n (x_0)) < epsilon / 2$
]
Применим теорему Лагранжа для непрерывных $f_n$ между произвольной точкой $x$ и
фиксированной $x_0$:
#eq[
$exists xi in {x, x_0} : space abs((f_(n + p) (x) - f_n (x)) - (f_(n + p) (x_0) - f_n (x_0))) = \ abs(f'_(n + p) (xi) - f'_n (xi))abs(x - x_0) $
]
Тогда мы можем доказать фундаментальность самой последовательнсоти:
#eq[
$abs(f_(n + p) (x) - f_n (x)) <= abs(f_(n + p) (x_0) - f_n (x_0)) + abs(f'_(n + p) (xi) - f'_n (xi))abs(x - x_0) < \
epsilon / 2 + epsilon / (2 (b - a)) abs(x - x_0) < epsilon$
]
Значит по критерию Коши $f_n arrows f$ на $(a, b)$.
Остаётся доказать дифференцируемость $f$ в произвольной точке $x in (a, b)$, для
этого введём вспомогательные функции:
#eq[
$phi_n (t) := (f_n (t) - f_n (x)) / (t - x) ; quad phi(t) := (f(t) - f(x)) / (t - x)$
]
Докажем фундаментальность $seq(phi)$:
#eq[
$\
abs(phi_(n + p) (t) - phi_n (t)) = abs((f_(n + p) (t) - f_n (t)) - (f_(n + p) (x) - f_n (x))) / (t - x) attach(=, t: "<NAME>") \
abs(f'_(n + p) (xi) - f'_n (xi)) < epsilon / (2 (b - a )) $
]
Получили, что $phi_n arrows phi$ на $A := (a, b) without {x}$.
Заметим, что $x$ -- предельная точка $A$, тогда применим теорему о непрерывном
поточечном пределе:
#eq[
$lim_(n -> oo) f'_n (x) = lim_(n -> oo) lim_(t -> x, t in A) phi_n (t) = lim_(t -> x, t in A) phi(t) = f'(x)$
]
Заметим, что этими равенствами мы доказываем как существование, так и равенство
пределов.
]
|
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_745%20-%20Lie%20Groups%20and%20Lie%20Algebras/Assignments/Assignment%201.typ | typst | #import "/Templates/generic.typ": latex, header
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": *
#show: doc => header(title: "Assignment 1", name: "<NAME>", doc)
#let lecture = counter("lecture")
#lecture.step()
#let update_lecture = () => {
lecture.step()
counter(heading).update(0)
}
#let bonus_problem = {
pagebreak()
block(text([*Bonus Exercise*], size: 17pt))
}
#show: latex
#let NumberingAfter(doc) = {
let level = 1
set heading(
numbering: (..numbers) => if numbers.pos().len() <= level {
return context numbering(
"1.1",
lecture.get().first(),
..numbers,
)
},
supplement: "Exercise",
)
show heading: it => {
if (it.numbering == none) {
return it
}
if (it.level > 1) {
return text(it, size: 14pt)
}
let numbers = counter(heading).at(it.location())
let display-number = numbering(it.numbering, ..numbers)
let body = it.body
// if (numbers.last() > 1) {
pagebreak(weak: true)
// }
block(text([*#body #display-number*], size: 17pt))
}
doc
};
#show: thmrules
#let col(x, clr) = text(fill: clr)[$#x$]
#let bar(el) = $overline(#el)$
#show: NumberingAfter
#set enum(numbering: "(a)")
*Sources consulted* \
Classmates: <NAME>. \
Texts: Class Notes.
= Exercise
== Statement
Let $A$ be an algebra, and $A\_$ be the algebra with the commutator bracket $[a,b] = a b - b a$. For each of the following conditions on $A$ prove that $A\_$ carries the structure of a Lie Algebra.
+ $A$ satisfies $a(b c) = (a b) c$ for all $a,b,c in A$.
+ $A$ satisfies $a(b c) + b(c a) + c(a b) = (a b)c + (b c)a + (c a)b = 0$ for all $a,b,c in A$.
+ $A$ satisfies $a(b c) - (a b) c = b (a c) - (b a) c = a (c b) - (a c)b$ for all $a,b,c in A$.
+ $A$ satisfies $[a, b c] + [b, c a] + [c, a b] = 0$ for all $a,b,c in A$.
== Solution
First it is clear that $[a,a] = a a - a a = 0$ and thus the bracket is always alternating, it is also easy to see that it is bilinear, it is thus enough to check that it satisfies the Jacobi condition in each case. We can start by simplifying
$
&[a,[b,c]] + [b,[c,a]] + [c,[a,b]] \
&= a(b c) - a(c b) - (b c) a + (c b) a + b (c a) - b (a c)
\ &- (c a) b + (a c) b + c (a b) - c (b a) - (a b) c + (b a) c,
$
We need to prove that this expression is always zero for any $a,b,c in A$ in each of the required cases.
+ In this case we throw away the brackets and pair up the terms as is colored
$
& col(a b c, #red) - col(a c b,#green) - col(b c a, #blue) + col(c b a, #yellow) + col(b c a, #blue) - col(b a c, #purple)
\ &- col(c a b, #orange) + col(a c b, #green) + col(c a b, #orange)
- col(c b a, #yellow) - col(a b c, #red) + col(b a c, #purple).
$
Since each color has a pair of positive and negative terms they cancel out giving us zero.
+ In this case we can group up the terms like so
$
& col(a (b c), #red) - col(a (c b),#green) - col((b c) a, #blue) + col((c b) a, #purple) + col(b (c a), #red) - col(b (a c), #green)
\ &- col((c a) b, #blue) + col((a c) b, #purple) + col(c (a b), #red)
- col(c (b a), #green) - col((a b) c, #blue) + col((b a) c, #purple).
$
The #text(fill: red)[red] terms give us
$
a(b c) + b(c a) + c(b a)
$
which cancel out according to our rule. Similarly the #text(fill: green)[green] terms give us
$
-a (c b) - b(a c) - c (b a)
$
which also cancel out. The blue terms give
$
-(a b) c - (b c) a - (c a) b.
$
And the purple terms give
$
(a c) b + (c b) a + (b a) c.
$
Each color cancels out due to our identity and thus the whole expression is equal to zero.
+ In this case we group up the terms like
$
& col(a (b c), #red) - col(a (c b),#purple) - col((b c) a, #green) + col((c b) a, #green) + col(b (c a), #green) - col(b (a c), #red)
\ &- col((c a) b, #purple) + col((a c) b, #purple) + col(c (a b), #purple)
- col(c (b a), #green) - col((a b) c, #red) + col((b a) c, #red).
$
The #text(fill: red)[red] terms give us
$
(a(b c) - (a b) c) - (b(a c) - (b a) c)
$
which vanishes because of our identity. Similarly the #text(fill: green)[green] terms give
$
(b(c a) - (b c) a) - (c (b a) - (c b) a)
$
which similarly vanishes. Finally the #text(fill: purple)[purple] terms give us
$
(c(a b) - (c a)b) - (a(c b) - (a c)b)
$
which also vanishes.
+ In the last case we rewrite the identity a bit differently,
$
&[a,[b,c]] + [b,[c,a]] + [c,[a,b]] \
= & [a,b c - c b] + [b, c a - a c] + [c, a b - b a] \
= & [a,b c] - [a, c b] + [b, c a] - [b, a c] + [c, a b] - [c, b a] \
= & col([a,b c],#red) - col([a, c b],#green) + col([b, c a],#red) - col([b, a c],#green) + col([c, a b], #red) - col([c, b a],#green) \
$
and again due to the identity we have the #text(fill: red)[red] and #text(fill: green)[green] terms group up together and vanish.
= Exercise
== Statement
Prove that $sl_n$, the subspace of $gl_n$ consisting of matrices with zero trace, is a Lie subalgebra.
== Solution
It is enough to show that for any two matrices $a,b in gl_n$ we have $tr([a,b]) = 0$. To see this we recall the formulas for matrix multiplication and trace.
$
(a b)_(i j) = sum_(k=1)^n a_(i k) b_(k j) wide wide tr(a) = sum_(i=1)^n a_(i i).
$
Combining the two we get
$
tr(a b - b a) = sum_(i = 1)^n (a b - b a)_(i i)
= sum_(i = 1)^n (a b)_(i i) - sum_(i=1)^n (b a)_(i i)
= sum_(i = 1)^n sum_(k=1)^n a_(i k) b_(k i) - sum_(i=1)^n sum_(k=1)^n b_(i k) a_(k i)
$
and since the two sums are the same up to renaming of indices, this expression must be equal to zero.
= Exercise
== Statement
Let $B$ be any bilinear form, show that,
$
o_(V,B) = {a in gl_V | B(a(v), w) + B(v, a(w)) = 0, forall v,w in V},
$
is a Lie subalgebra of $gl_V$.
== Solution
Let us take two matrices $a,b in o_(V,B)$ and consider their commutator $[a,b]$. We can compute
$
B([a,b]v, w) + B(v,[a,b]w)
=
B(a b v, w) - B(b a v, w) + B(v, a b w) - B(v, b a w)
$
since both $a$ and $b$ are in $o_(V,B)$ we can move them around to get the following
$
-B(b v, a w) + B(a v, b w) - B(a v, b w) + B(b v, a w).
$
Now the inner and outer terms cancel as pairs and we get $0$. Thus we have
$
B([a,b]v,w) + B(v,[a,b]w) = 0
$
and so $[a,b] in o_(V,B)$ and so $o_(V,B)$ is closed under the Lie bracket.
= Exercise
== Statement
Consider some bilinear form on $FF^n$ represented in the standard basis by the matrix $B$. Show that
$
o_(FF^n, B) = {a in gl_n | a^T B + B a = 0},
$
where $a^T$ is the transpose of the matrix $a$.
== Solution
First recall that in the standard basis the matrix $B$ is defined by
$
B_(i j) = B(e_i, e_j)
$
where $e_i,e_j$ are any basis vectors. Similarly any matrix $a in gl_n$ is defined by
$
a(e_i) = sum_(k=1)^n a_(k i) e_k
$
We compute
$
(a^T B + B a)_(i j) &= sum_(k=1)^n a_(k i) B_(k j) + B_(i k) a_(k j)
= sum_(k=1)^n a_(k i) B(e_k, e_j) + B(e_i, e_k) a_(k j)
\ &= sum_(k=1)^n B(a_(k i) e_k, e_j) + B(e_i, a_(k j) e_k)
\ &= B(a (e_i), e_j) + B(e_i, a(e_j)).
$
We thus know that the expression $a^T B + B a = 0$ is equivalent to $B(a(e_i), e_j) + B(e_i, a(e_j)) = 0$ for all basis vectors, which is then equivalent to $B(a(v), w) + B(v,a(w)) = 0$ for all vectors in $FF^n$.
= Exercise
== Statement
Let $f : Mat_n (FF) -> FF$ be a linear function satisfying $f([a,b]) = 0$ for all $a,b in Mat_n (FF)$. Show that $f = lambda tr$ for some constant $lambda in FF$.
== Solution
Consider a linear basis for $Mat_n (FF)$ consisting of single entry matrices
$
e^((ell k))_(i j) = cases(1 : i = ell \, j = k, 0 : "otherwise")
$
We note here that $e^((i j)) e^((k ell))$ is non-zero only if $j = k$ in which case we have $e^((i k)) e^((k ell)) = e^((i ell))$.
Since $f$ is linear we can write for each matrix $a$
$
f(a) = f(sum_(i,j) a_(i j) e^((i j)))
= sum_(i,j) a_(i j) f(e^((i j))),
$
from this we get that it is enough to show that
$
f(e^((i j))) = cases(lambda : i = j, 0 : "otherwise")
$
for some $lambda$.
Now we compute for $i != j$,
$
[e^((i i)), e^((i j))]
=
e^((i i)) e^((i j)) - e^((i j)) e^((i i))
=
e^((i j)) - 0
= e^((i j))
$
so $f(e^((i j))) = 0$ for $i != j$. Next, also for $i != j$ we have
$
[e^((i j)), e^((j i))]
=
e^((i j)) e^((j i))
-
e^((j i)) e^((i j))
= e^((i i)) - e^((j j))
$
and thus $f(e^((i i)) - e^((j j))) = 0$ and $f(e^((i i))) = f(e^((j j)))$. Now we fix $lambda = f(e^((1 1)))$ and immediately get $lambda = f(e^((i i)))$ for all $i$ as well as $0 = f(e^((i j)))$ for $i != j$, which finishes the proof.
#update_lecture()
= Exercise
== Statement
For any algebra $A$ over a field $FF$, a derivation of $A$ is an $FF$-vector space endomorphism $D$ of $A$ satisfying $D(a b) = D(a) b + a D(b)$. Prove that the space of derivations $op("Der") A$ is a Lie subalgebra of $gl_A$.
== Solution
Let $D,F$ be two derivations of $A$, we want to show that $[D,F]$ is also a derivation. There is really only one way to do that, we compute
$
[D,F](a b)
&= D F (a b) - F D (a b)
= D(F (a) b + a F(b))
+ F(D (a) b + a D(b))
\ &= D F (a) b + col(F(a) D(b), #red) + col(D (a) F(b), #green) + a D F (b)
\ &- F D (a) b - col(D(a) F(b), #green) - col(F(a) D(b), #red) - a F D (b)
\ &= D F (a) b + a D F (b)
- F D (a) b - a F D (b)
\ &= (D F - F D) (a) b + a (D F - F D) (b)
\ [D,F] (a b) &= [D, F] (a) b + a [D, F](b).
$
And so we exactly get the definition of a derivation. Hence $op("Der") A$ is closed under the Lie bracket and thus a Lie subalgebra.
#bonus_problem
== Statement
Consider the vector space $V$ with basis ${ L_m : m in ZZ } union {C}$ with product given by
$
[L_m, L_n] = (m-n) L_(m+n) + (m^3 - m) / 12 delta_(m, -n) C\
[C,L_m] = 0, m in ZZ.
$
Show that the bracket gives a Lie Algebra structure on $V$.
== Solution
First let us check anti-commutativity
$
[L_m,L_n]
&= (m - n) L_(m+n) + (m^3 - m) / 12 delta_(m,-n) C
\ &= -(n - m) L_(m+n) + ((-n)^3 - (-n)) / 12 delta_(-m,n) C
\ &= -(n - m) L_(m+n) - (n^3 - n) / 12 delta_(-m,n) C
\ &= [L_n,L_m]
$
and anti-commutativity with $C$ is clear. We now have to check the Jacobi identity, if any of the arguments is $C$ then the whole expression vanishes so we can ignore that case and assume that all the arguments are $L_n$ for some $n$.
$
& [L_n,[L_m, L_p]] + [L_m, [L_p, L_n]] + [L_p, [L_n, L_m]]
\ = & [L_n,(m-p)L_(m+p) + (m^3-m) / 12 delta_(m,-p) C]
\ + & [L_m,(p-n)L_(p+n) + (p^3-p) / 12 delta_(p,-n) C]
\ + & [L_p,(n-m)L_(n+m) + (n^3-n) / 12 delta_(n,-m) C]
$
Now since $C$ is central we can cancel it from every bracket
$
&[L_n,(m-p)L_(m+p)] + [L_m,(p-n) L_(p+n)] + [L_p,(n-m) L_(n+m)]
\ = &(m-p) [L_n,L_(m+p)] + (p-n)[L_m,L_(p+n)] + (n-m)[L_p,L_(n+m)]
\ = &(m-p) (n - m - p) L_(n+m+p) + (m-p)(n^3-n) / 12 delta_(n,-m-p) C
\ + &(p-n) (m - p - n) L_(n+m+p) + (p-n)(m^3-m) / 12 delta_(m,-p-n) C
\ + &(n-m) (p - n - m) L_(n+m+p) + (n-m)(p^3-p) / 12 delta_(p,-n-m) C
$
Collecting like terms we get
$
((m-p)(n-m-p)+(p-n)(m-p-n)+(n-m)(p-n-m)) L_(n+m+p)
\ +(((m-p)(n^3-n)+(p-n) (m^3-m)+(n-m)(p^3-p)) / 12) delta_(n+m+p,0) C.
$
Now we first deal with the first coefficient
$
&col(m n, #red) - col(m^2, #green) - col(m p, #blue) - col(p n, #yellow) + col(p m, #blue) + col(p^2, #purple)
\ + &col(p m, #blue) - col(p^2, #purple) - col(p n, #yellow) - col(n m, #red) + col(n p, #yellow) + col(n^2, #orange)
\ + &col(n p, #yellow) - col(n^2, #orange) - col(n m, #red) - col(m p,#blue) + col(m n, #red) + col(m^2, #green)
$
As we can see by the highlighted groups everything cancels out and we get exactly $0$.
For the second coefficient it can only possibly be non-zero if $delta_(n+m+p,0) = 1$ that is if $n + m + p = 0$. With that in mind we compute
$
((m-p)(n^3-n)+(p-n) (m^3-m)+(n-m)(p^3-p))
\ = m n^3 - col(m n, #red) - p n^3 + col(p n, #green) + p m^3 - col(p m, #blue) - n m^3 + col(n m, #red) + n p^3 - col(n p, #green) - m p^3 + col(m p, #blue)
\ = m n^3 - p n^3 + p m^3 - n m^3 + n p^3 - m p^3
$
we can now replace $n$ with $- m - p$ and we get
$
&m (-m-n)^3 - p (-m - p)^3 + p m^3 - (-m-p) m^3 + (-m-p)p^3 - m p^3
\ = &- m (col(m^3,#red)+3m^2p+3m p^2+p^3)
+ p (m^3 + 3m^2p+3m p^2 +col(p^3,#green))
\ + & p m^3 + col(m^4,#red) + p m^3 - m p^3 - col(p^4,#green) - m p^3
\ = &- col(3m^3 p,#green) - col(3m^2 p^2,#red) - col(m p^3, #blue) + col(p m^3,#green) + col(3m^2p^2,#red) + col(3m p^3, #blue) + col(p m^3,#green) + col(p m^3, #green) - col(m p^3, #blue) - col(m p^3, #blue)
\ =&0
$
So all together our final result is $0$ so the Jacobi identity holds and thus this is indeed a Lie algebra.
= Exercise
== Statement
Let ${x_i, x_j} in A$ be choices of elements of $A$, the algebra of smooth functions in the variables $x_1,...,x_n.$ Now define the bracket operation
$
{f,g} = sum_(i,j=1)^n (diff f) / (diff x_i) (diff g) / (diff x_j) {x_i, x_j}.
$
Show that this bracket gives $A$ the structure of a Lie algebra if and only it is anti-commutative and satisfies the Jacobi identity for any triplet $x_i,x_j,x_k$.
== Solution
// We compute
// $
// {f,g} + {g,f}
// &= sum_(i,j=1)^n (diff f) / (diff x_i) (diff g) / (diff x_j) {x_i,x_j}
// + sum_(i,j=1)^n (diff g) / (diff x_i) (diff f) / (diff x_j) {x_i,x_j}
// $
// then after swapping indices in the second sum we get
// $
// sum_(i,j=1)^n (diff f) / (diff x_i) (diff g) / (diff x_j) {x_i,x_j}
// + sum_(j,i=1)^n (diff g) / (diff x_j) (diff f) / (diff x_i) {x_j,x_i}
// = sum_(i,j=1)^n (diff f) / (diff x_i) (diff g) / (diff x_j) (
// {x_i,x_j} + {x_j,x_i}
// ).
// $
// So ${dot,dot}$ is anti-symmetric iff it is anti-symmetric on $x_i,x_j$ for all $i,j$.
//
// Next we check the Jacobi identities, for brevity we will denote $(diff f)/(diff x_i)$ as $f_i$
// $
// {f,{g,h}} + {g,{f,h}} + {h,{f,g}}
// \ = sum_(i,j=1)^n (
// {f, g_i h_j {x_i,x_j}}
// + {g, h_i f_j {x_i,x_j}}
// + {h, f_i g_j {x_i,x_j}}
// )
// \ = sum_(i,j=1)^n sum_(k,ell=1)^n (
// f_k (
// g_(i ell) h_j {x_i,x_j}
// + g_i h_(j ell) {x_i,x_j}
// + g_i h_j {x_i,x_j}_ell
// ){x_k,x_ell}
// \ + g_k (
// h_(i ell) f_j {x_i,x_j}
// + h_i f_(j ell) {x_i,x_j}
// + h_i f_j {x_i,x_j}_ell
// ){x_k,x_ell}
// \ + h_k (
// f_(i ell) g_j {x_i,x_j}
// + f_i g_(j ell) {x_i,x_j}
// + f_i g_j {x_i,x_j}_ell
// ){x_k,x_ell}
// )
// $
If the Poisson bracket defines a Lie algebra structure for some choice of values $lr({x_i , x_j})$, then in particular, the axioms of a Lie algebra must be satisfied for brackets of terms $x_i$. The interesting question is whether the converse holds. We suppose then that the $lr({x_i , x_j})$ are chosen so that $lr({x_i , x_j}) = - lr({x_j , x_i})$, and so that the Jacobi identity is satisfied for triples $x_i , x_j , x_k$.
The bilinearity of the bracket follows from the linearity of differentiation, and the skew-symmetry follows from the assumption of the skew symmetry on the $x_i$.
At this point we introduce some shorthands to simplify what follows. If $f$ is any function, we write $f_i$ for the derivative of $f$ with respect to $x_i$. When we are discussing an expression $e$ in terms of three functions $f , g$, h, we will write $op("CS") lr((e))$ for the ’cyclic summation’ of $e$, the expression formed by summing those obtained from $e$ by permuting the $f , g , h$ cyclically. In particular, the Jacobi identity will be $op("CS") lr(({ f , { g , h } })) = 0$.
First we calculate the iterated bracket of monomials $x_i$ :
$
lr({x_i , lr({x_j , x_k})}) = sum_l lr({x_j , x_k})_l lr({x_i , x_l}) upright(" (an example of the shorthands described). ")
$
Now the iterated bracket of any three polynomials (or functions) $f , g$ and $h$ is:
$
{
h , {f , g}
} = sum_(i , j , k , l) lr([f_(i l) g_j h_k + g_(j l) f_i h_k]) lr({x_i , x_j}) lr({x_k , x_l}) + sum_(i , j , k , l) f_i g_j h_k lr({x_i , x_j})_l lr({x_k , x_l})
$
By the assumption that the Jacobi identity holds on the $x_i$, we have (for any $i , j , k$):
$ sum_l op("CS") lr((f_i g_j h_k)) lr({x_i , x_j})_l lr({x_k , x_l}) = 0 $
for cyclicly permuting the $f , g , h$ corresponds to cyclicly permuting the $i , j , k$ (in the opposite order). Thus we have:
$
op("CS") lr(({ h , { f , g } })) = sum_(i , j , k , l) op("CS") lr((f_(i l) g_j h_k + g_(j l) f_i h_k)) lr({x_i , x_j}) lr({x_k , x_l})
$
The remaining task can be viewed as finding the $lr({x_alpha , x_beta}) lr({x_gamma , x_delta})$ coefficient in this expression, where we substitute all appearances of $lr({x_beta , x_alpha})$ for $- lr({x_alpha , x_beta})$, and so on. To do so, we tabulate all the appearances of terms which are multiples of $lr({x_alpha , x_beta}) lr({x_gamma , x_delta})$. We may as well assume here that $alpha < beta$ and $gamma < delta$.
#figure(
align(center)[#table(
columns: 7,
align: (col, row) => (
center,
center,
center,
center,
center,
center,
center,
center,
center,
center,
).at(col),
stroke: none,
inset: 6pt,
[order],
[$i$],
[$j$],
[$k$],
[$l$],
table.vline(),
[multiple of $lr({x_alpha , x_beta}) lr({x_gamma , x_delta})$],
table.vline(),
[group],
table.hline(),
table.cell(rowspan: 8)[$f,g,h$],
[$alpha$],
[$beta$],
[$gamma$],
[$delta$],
[$+ f_(alpha delta) g_beta h_gamma + g_(beta delta) f_alpha h_gamma$],
[#col(1, green)],
[$gamma$],
[$delta$],
[$alpha$],
[$beta$],
[$+ f_(gamma beta) g_delta h_alpha + g_(delta beta) f_gamma h_alpha$],
[#col(1, red)],
[$beta$],
[$alpha$],
[$gamma$],
[$delta$],
[$- f_(beta delta) g_alpha h_gamma - g_(alpha delta) f_beta h_gamma$],
[#col(10, red)],
[$delta$],
[$gamma$],
[$alpha$],
[$beta$],
[$- f_(delta beta) g_gamma h_alpha - g_(gamma beta) f_delta h_alpha$],
[#col(10, green)],
[$alpha$],
[$beta$],
[$delta$],
[$gamma$],
[$- f_(alpha gamma) g_beta h_delta - g_(beta gamma) f_alpha h_delta$],
[#col(4, red)],
[$gamma$],
[$delta$],
[$beta$],
[$alpha$],
[$- f_(gamma alpha) g_delta h_beta - g_(delta alpha) f_gamma h_beta$],
[#col(4, green)],
[$beta$],
[$alpha$],
[$delta$],
[$gamma$],
[$+ f_(beta gamma) g_alpha h_delta + g_(alpha gamma) f_beta h_delta$],
[#col(7, green)],
[$delta$],
[$gamma$],
[$beta$],
[$alpha$],
[$+ f_(delta alpha) g_gamma h_beta + g_(gamma alpha) f_delta h_beta$],
[#col(7, red)],
table.hline(),
table.cell(rowspan: 8)[$g,h,f$],
[$alpha$],
[$beta$],
[$gamma$],
[$delta$],
[$+ g_(alpha delta) h_beta f_gamma + h_(beta delta) g_alpha f_gamma$],
[#col(5, green)],
[$gamma$],
[$delta$],
[$alpha$],
[$beta$],
[$+ g_(gamma beta) h_delta f_alpha + h_(delta beta) g_gamma f_alpha$],
[#col(5, red)],
[$beta$],
[$alpha$],
[$gamma$],
[$delta$],
[$- g_(beta delta) h_alpha f_gamma - h_(alpha delta) g_beta f_gamma$],
[#col(2, red)],
[$delta$],
[$gamma$],
[$alpha$],
[$beta$],
[$- g_(delta beta) h_gamma f_alpha - h_(gamma beta) g_delta f_alpha$],
[#col(2, green)],
[$alpha$],
[$beta$],
[$delta$],
[$gamma$],
[$- g_(alpha gamma) h_beta f_delta - h_(beta gamma) g_alpha f_delta$],
[#col(8, red)],
[$gamma$],
[$delta$],
[$beta$],
[$alpha$],
[$- g_(gamma alpha) h_delta f_beta - h_(delta alpha) g_gamma f_beta$],
[#col(8, green)],
[$beta$],
[$alpha$],
[$delta$],
[$gamma$],
[$+ g_(beta gamma) h_alpha f_delta + h_(alpha gamma) g_beta f_delta$],
[#col(11, green)],
[$delta$],
[$gamma$],
[$beta$],
[$alpha$],
[$+ g_(delta alpha) h_gamma f_beta + h_(gamma alpha) g_delta f_beta$],
[#col(11, red)],
table.hline(),
table.cell(rowspan: 8)[$h,f,g$],
[$alpha$],
[$beta$],
[$gamma$],
[$delta$],
[$+ h_(alpha delta) f_beta g_gamma + f_(beta delta) h_alpha g_gamma$],
[#col(9, green)],
[$gamma$],
[$delta$],
[$alpha$],
[$beta$],
[$+ h_(gamma beta) f_delta g_alpha + f_(delta beta) h_gamma g_alpha$],
[#col(9, red)],
[$beta$],
[$alpha$],
[$gamma$],
[$delta$],
[$- h_(beta delta) f_alpha g_gamma - f_(alpha delta) h_beta g_gamma$],
[#col(6, red)],
[$delta$],
[$gamma$],
[$alpha$],
[$beta$],
[$- h_(delta beta) f_gamma g_alpha - f_(gamma beta) h_delta g_alpha$],
[#col(6, green)],
[$alpha$],
[$beta$],
[$delta$],
[$gamma$],
[$- h_(alpha gamma) f_beta g_delta - f_(beta gamma) h_alpha g_delta$],
[#col(12, red)],
[$gamma$],
[$delta$],
[$beta$],
[$alpha$],
[$- h_(gamma alpha) f_delta g_beta - f_(delta alpha) h_gamma g_beta$],
[#col(12, green)],
[$beta$],
[$alpha$],
[$delta$],
[$gamma$],
[$+ h_(beta gamma) f_alpha g_delta + f_(alpha gamma) h_beta g_delta$],
[#col(3, green)],
[$delta$],
[$gamma$],
[$beta$],
[$alpha$],
[$+ h_(delta alpha) f_gamma g_beta + f_(gamma alpha) h_delta g_beta$],
[#col(3, red)],
)],
)
The table describes how to cancel out these terms, we group them into to groups, as dictated by the color, then the number dictate an ordering on the groups such that for two adjacent number they cancel out exactly two terms.
= Exercise
== Statement
Let $phi : frak(g)_1 -> frak(g)_2$ be a homomorphism. Then:
+ $ker phi$ is an ideal of $frak(g)_1$.
+ $im phi$ is a subalgebra of $frak(g)_2$.
+ $im phi iso frak(g)_1 quo ker phi$.
== Solution
+ Clearly $ker phi$ is a subspace, then for any $x in frak(g)_1, y in ker phi$ we have
$
phi([x,y]) = [phi(x),phi(y)] = [phi(x), 0] = 0.
$
so $[x,y] in ker phi$.
+ Let $phi(x), phi(y) in im phi$, then we have
$
[phi(x), phi(y)] = phi([x,y])
$
which is also in the image of $phi$
+ We define an isomorphism $psi : frak(g)_1 quo ker phi -> im phi$ by $psi([x]) = phi(x)$, this is well defined because for any $z_1,z_2 in ker phi$
$
phi([x+z_1,y+z_2])
=
phi([x,y]+[x,z_2]+[z_1,y]+[z_1,z_2])
=
phi([x,y])
$
because the kernel is an ideal.
This is by definition surjective, and it is injective since if $psi([x]) = 0$ then $phi(x) = 0$ so $x in ker phi$.
= Exercise
== Statement
Given $B in Mat_n (FF)$, let $O_(n,B) (A) = { g in Gl_n (A) : g^T B g = B }$. Show that this family of groups is a family of algebraic groups.
== Solution
For $g,h in O_(n,B) (A)$ we have
$
(g h)^T B (g h) = h^T g^T B g h = h^T (g^T B g) h = h^T B h = B,
$
so $g h in O_(n, B) (A)$ and thus $O_(n, B) (A)$ is a group.
Now note the fact that
$
g^T B g
$
is a matrix with polynomial entries with the variables being the entries of $g$. Hence $g^T B g = B$ is a polynomial equation in the entries of $g$. Thus $O_(n, B) (A)$ is an algebraic group.
= Exercise
== Statement
Prove that $Lie Sl_n = sl_n (FF)$ and $Lie O_(n,B) = o_(FF^n, B)$.
== Solution
We check first for $Sl_n$, it is defined by $det(g) = 1$ so we have
$
det(I+epsilon X)
= sum_(sigma in S_n) product_(i=1)^n (I+epsilon X)_(i sigma(i))
= sum_(sigma in S_n) product_(i=1)^n
(delta_(i sigma(i)) + epsilon X_(i sigma(i)))
$
now if $sigma$ is any non-trivial permutation then it has at least two non-fixed points. Thus the product at least two factors of $epsilon$, so it vanishes in the sum. Thus we are left with
$
det(I+epsilon X) = product_(i=1)^n (delta_(i i) + epsilon X_(i i))
$
now expanding this, since only terms with one or less $epsilon$'s survive we get
$
det(I + epsilon X) = 1 + epsilon sum_(i=1)^n X_(i i)
$
so we must have $sum_i^n X_(i i) = tr(X) = 0$ which is precisely the definition for $sl_n (FF)$.
Next for $O_(n, B)$, it is defined by $g^T B g = B$ so we have
$
(I + epsilon X)^T B (I + epsilon X) =
B + epsilon X^T B + B epsilon X + epsilon X^T B epsilon X =
B + epsilon (X^T B + B X)
$
we thus have $I + epsilon X in O_(n, B)$ if and only if $X^T B + B X = 0$ which is also precisely the definition of $o_(FF^n, B)$.
#update_lecture()
= Exercise
== Statement
Show that $Z(gl_n (FF)) = FF I_n$ where $Z$ is the center of a Lie algebra.
Show that $Z(sl_n (FF)) = 0$ if $op("char") FF divides.not n$ and $FF I_n$ otherwise.
== Solution
Let $A$ be a matrix in $Z(gl_n (FF))$ then $A$ commutes with all other matrices in $gl_n (FF)$. Now using the Jordan normal theorem, since conjugation does not change commutativity, we may assume that $A$ is in its Jordan normal form. Further more, assume that $A$ is not in $FF I_n$, then it either has a Jordan block of size 2 or more, two Jordan blocks with different eigenvalues.
Thus we have that $A = mat(B, 0; 0, *)$ where we either have $B = mat(lambda, 0; 0, rho)$ or $B = mat(lambda, 1;0,lambda)$. In the first case we set
$
C := mat(0, 1;1,0)
$
making
$
[B,C]
= mat(0, lambda;rho, 0) - mat(0, rho;lambda,0)
= mat(0, lambda - rho;rho-lambda, 0)
$
which is non-zero. In the second case we get
$
[B,C] = mat(1, lambda;lambda, 0) - mat(0, lambda;lambda, 1) = mat(1,0;0,-1)
$
Then we have
$
[mat(B,0;0,*),mat(C,0;0,0)] != 0
$
in either case so if $A$ is not in $FF I_n$ it cannot commute with everything. On the other hand if $A$ is in $FF I_n$ then it clearly commutes with everything so we are done.
Since the matrix $mat(C,0;0,0)$ we constructed is in $sl_n (FF)$ the argument in $sl_n$ is identical, the only difference is that we replace $FF I_n$ with $FF I_n sect sl_n (FF)$ which is empty if $I in.not sl_n (FF)$, which happens precisely when $tr(I) = n != 0$ in $FF$, i.e. when $op("char") F divides.not n$.
= Exercise
== Statement
Let $n = dim frak(g)$, show that $dim Z(frak(g)) != n-1$.
== Solution
Assume this is the case, then let $e_1, ..., e_(n-1)$ be a basis of $Z(frak(g))$ and $e_n$ be any vector not in $Z (frak(g))$ making $e_1,...,e_n$ a basis for $frak(g)$. We know that $[e_n, e_i] = 0$ for all $i <= n-1$ and we also know that $[e_n, e_n] = 0$ so we get that $e_n in Z(frak(g))$, contradicting the choice of $e_n$.
= Exercise
== Statement
Prove that any $n$-dimensional Lie algebra with $dim Z(frak(g)) = n - 2$ is isomorphic to either $op("ab")_(n-3) plus.circle op("heis")_3$ or $op("ab")_(n-2) plus.circle eta$ where $eta$ is the canonical non-abelian Lie algebra of dimension 2.
== Solution
Write $frak(g) = Z(frak(g)) plus.circle V$ where this is a vector space direct sum, let $v_1,v_2$ be a basis of $V$. Now we consider $[v_1,v_2]$, first assume that $[v_1,v_2] in Z(frak(g))$, then find a basis $e_1,...,e_(n-2)$ for $Z(frak(g))$ that includes $[v_1,v_2]$ as a basic vector, we then have
$
v_1,v_2,[v_1,v_2]=e_1,e_2,e_3,...,e_(n-2)
$
is a basis for $frak(g)$ so since clearly $span(v_1,v_2,[v_1,v_2]) iso op("heis")_3$ then we get exactly the decomposition as Lie algebras $frak(g) = op("heis")_3 plus.circle op("ab")_(n-3)$.
On the other hand if $[v_1,v_2] in.not Z(frak(g))$ then
$
[v_1,v_2] = a v_1 + b v_2 + z
$
for some vector $z in Z(frak(g))$. Now either $a$ or $b$ are non-zero, assume WLOG that $a != 0$, we then have
$
[v_1 + b / a v_2 + 1 / a z, 1 / a v_2] = 1 / a [v_1, v_2] + b / a^2 [
v_2,v_2
] + 1 / a [z,v_2] = v_1 + b / a v_2 + 1 / a z
$
so if we define $v'_1 := v_1 + b/a v_2 + 1/a z, v'_2 = 1/a v_2$ then $[v'_1,v'_2] = v'_1$ and so $span(v'_1,v'_2) iso eta$ as a Lie algebra and thus we get the decomposition $frak(g) = eta plus.circle op("ab")_(n-2)$.
= Exercise
== Statement
Show that if $dim V <= infinity$, then $A$ is a nilpotent operator on $V$ if and only if all its eigenvalues are $0$.
== Solution
Clearly if $A$ is nilpotent then the minimal polynomial for $A$ is of the form $p(x) = x^n$ for some $n$, so since the eigenvalues of $A$ are roots of the minimal polynomial in $FF$ then they must all be zero.
On the other hand if the eigenvalues of $A$ are all 0, then the minimal polynomial only has $0$ as a root, so it is of the form $x^n$ for some $n$ so we know that $A^n = 0$ and so it is nilpotent.
= Exercise
== Statement
Construct in $sl_3 (FF)$ a 2-dimensional subspace, consisting of nilpotent matrices, which do not share a common eigenvector.
== Solution
Consider the matrices
$
A = mat(0,1,0;0,0,1;0,0,0),
quad
B = mat(0,0,0;-1,0,0;0,1,0)
$
they span a $2$ dimensional subspace, and we have
$
mat(0,a,0;-b,0,a;0,b,0)^3
&=
mat(0,a,0;-b,0,a;0,b,0)
mat(0,a,0;-b,0,a;0,b,0)
mat(0,a,0;-b,0,a;0,b,0)
=
mat(-a b,0,a^2;0,0,0;-b^2,0,a b)
mat(0,a,0;-b,0,a;0,b,0)
\ &=
mat(0,0,0;0,0,0;0,0,0)
$
so all the matrices in this subspace are nilpotent. However, they do not all share a common eigenvector, for assume this is the case for a vector $v = vec(a,b,c)$ then we have
$
0 = A vec(a,b,c) = vec(b,c,0)
$
so $b= c = 0$. But then
$
0 = B vec(a,0,0) = vec(0,-a,0)
$
so $a = 0$ and thus $v = 0$.
|
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/004.%20avg.html.typ | typst | #set page(
paper: "a5",
margin: (x: 1.8cm, y: 1.5cm),
)
#set text(
font: "Liberation Serif",
size: 10pt,
hyphenate: false
)
#set par(justify: true)
#set quote(block: true)
#v(10pt)
= Beating the Averages
#v(10pt)
_April 2001, rev. April 2003_
_(This article is derived from a talk given at the 2001 Franz Developer Symposium.)_
In the summer of 1995, my friend <NAME> and I started a startup called *Viaweb*. Our plan was to write software that would let end users build online stores. What was novel about this software, at the time, was that it ran on our server, using ordinary Web pages as the interface.
A lot of people could have been having this idea at the same time, of course, but as far as I know, Viaweb was the first Web-based application. It seemed such a novel idea to us that we named the company after it: Viaweb, because our software worked via the Web, instead of running on your desktop computer.
Another unusual thing about this software was that it was written primarily in a programming language called Lisp. It was one of the first big end-user applications to be written in Lisp, which up till then had been used mostly in universities and research labs. #footnote[
Viaweb at first had two parts: the editor, written in Lisp, which people used to build their sites, and the ordering system, written in C, which handled orders. The first version was mostly Lisp, because the ordering system was small. Later we added two more modules, an image generator written in C, and a back-office manager written mostly in Perl. In January 2003, Yahoo released a new version of the editor written in C++ and Perl.
It's hard to say whether the program is no longer written in Lisp, though, because to translate this program into C++ they literally had to write a Lisp interpreter: the source files of all the page-generating templates are still, as far as I know, Lisp code. (See Greenspun's Tenth Rule.)
]
== The Secret Weapon
<NAME> has written an essay called "How to Become a Hacker," and in it, among other things, he tells would-be hackers what languages they should learn. He suggests starting with Python and Java, because they are easy to learn. The serious hacker will also want to learn C, in order to hack Unix, and Perl for system administration and cgi scripts. Finally, the truly serious hacker should consider learning Lisp:
#quote(attribution: [<NAME>])[Lisp is worth learning for the profound enlightenment experience you will have when you finally get it; that experience will make you a better programmer for the rest of your days, even if you never actually use Lisp itself a lot.]
This is the same argument you tend to hear for learning Latin. It won't get you a job, except perhaps as a classics professor, but it will improve your mind, and make you a better writer in languages
you do want to use, like English.
But wait a minute. This metaphor doesn't stretch that far. The reason Latin won't get you a job is that no one speaks it. If you write in Latin, no one can understand you. But Lisp is a computer language, and computers speak whatever language you, the programmer, tell them to.
So if Lisp makes you a better programmer, like he says, why wouldn't you want to use it? If a painter were offered a brush that would make him a better painter, it seems to me that he would want to use it in all his paintings, wouldn't he? I'm not trying to make fun of <NAME> here. On the whole, his advice is good. What he says about Lisp is pretty much the conventional wisdom. But there is a contradiction in the conventional wisdom: Lisp will make you a better programmer, and yet you won't use it.
Why not? Programming languages are just tools, after all. If Lisp really does yield better programs, you should use it. And if it doesn't, then who needs it?
This is not just a theoretical question. Software is a very competitive business, prone to natural monopolies. A company that gets software written faster and better will, all other things being equal, put its competitors out of business. And when you're starting a startup, you feel this very keenly. Startups tend to be an all or nothing proposition. You either get rich, or you get nothing. In a startup, if you bet on the wrong technology, your competitors will crush you.
Robert and I both knew Lisp well, and we couldn't see any reason not to trust our instincts and go with Lisp. We knew that everyone else was writing their software in C++ or Perl. But we also knew that that didn't mean anything. If you chose technology that way, you'd be running Windows. When you choose technology, you have to ignore what other people are doing, and consider only what will work the best.
This is especially true in a startup. In a big company, you can do what all the other big companies are doing. But a startup can't do what all the other startups do. I don't think a lot of people realize this, even in startups.
The average big company grows at about ten percent a year. So if you're running a big company and you do everything the way the average big company does it, you can expect to do as well as the average big company -- that is, to grow about ten percent a year.
The same thing will happen if you're running a startup, of course. If you do everything the way the average startup does it, you should expect average performance. The problem here is, average performance means that you'll go out of business. The survival rate for startups is way less than fifty percent. So if you're running a startup, you had better be doing something odd. If not, you're in trouble.
Back in 1995, we knew something that I don't think our competitors understood, and few understand even now: when you're writing software that only has to run on your own servers, you can use any language you want. When you're writing desktop software, there's a strong bias toward writing applications in the same language as the operating system. Ten years ago, writing applications meant writing applications in C. But with Web-based software, especially when you have the source code of both the language and the operating system, you can use whatever language you want.
This new freedom is a double-edged sword, however. Now that you can use any language, you have to think about which one to use. Companies that try to pretend nothing has changed risk finding that their competitors do not.
If you can use any language, which do you use? We chose Lisp. For one thing, it was obvious that rapid development would be important in this market. We were all starting from scratch, so a company that could get new features done before its competitors would have a big advantage. We knew Lisp was a really good language for writing software quickly, and server-based applications magnify the effect of rapid development, because you can release software the minute it's done.
If other companies didn't want to use Lisp, so much the better. It might give us a technological edge, and we needed all the help we could get. When we started Viaweb, we had no experience in business. We didn't know anything about marketing, or hiring people, or raising money, or getting customers. Neither of us had ever even had what you would call a real job. The only thing we were good at was writing software. We hoped that would save us. Any advantage we could get in the software department, we would take.
So you could say that using Lisp was an experiment. Our hypothesis was that if we wrote our software in Lisp, we'd be able to get features done faster than our competitors, and also to do things in our software that they couldn't do. And because Lisp was so high-level, we wouldn't need a big development team, so our costs would be lower. If this were so, we could offer a better product for less money, and still make a profit. We would end up getting all the users, and our competitors would get none, and eventually go out of business. That was what we hoped would happen, anyway.
What were the results of this experiment? Somewhat surprisingly, it worked. We eventually had many competitors, on the order of twenty to thirty of them, but none of their software could compete with ours. We had a wysiwyg online store builder that ran on the server and yet felt like a desktop application. Our competitors had cgi scripts. And we were always far ahead of them in features. Sometimes, in desperation, competitors would try to introduce features that we didn't have. But with Lisp our development cycle was so fast that we could sometimes duplicate a new feature within a day or two of a competitor announcing it in a press release. By the time journalists covering the press release got round to calling us, we would have the new feature too.
It must have seemed to our competitors that we had some kind of secret weapon -- that we were decoding their Enigma traffic or something. In fact we did have a secret weapon, but it was simpler than they realized. No one was leaking news of their features to us. We were just able to develop software faster than anyone thought possible.
When I was about nine I happened to get hold of a copy of The Day of the Jackal, by <NAME>. The main character is an assassin who is hired to kill the president of France. The assassin has to get past the police to get up to an apartment that overlooks the president's route. He walks right by them, dressed up as an old man on crutches, and they never suspect him.
Our secret weapon was similar. We wrote our software in a weird AI language, with a bizarre syntax full of parentheses. For years it had annoyed me to hear Lisp described that way. But now it worked to our advantage. In business, there is nothing more valuable than a technical advantage your competitors don't understand. In business, as in war, surprise is worth as much as force.
And so, I'm a little embarrassed to say, I never said anything publicly about Lisp while we were working on Viaweb. We never mentioned it to the press, and if you searched for Lisp on our Web site, all you'd find were the titles of two books in my bio. This was no accident. A startup should give its competitors as little information as possible. If they didn't know what language our software was written in, or didn't care, I wanted to keep it that way. #footnote[<NAME> says that I didn't need to be secretive, because even if our competitors had known we were using Lisp, they wouldn't have understood why: _"If they were that smart they'd already be programming in Lisp."_]
The people who understood our technology best were the customers. They didn't care what language Viaweb was written in either, but they noticed that it worked really well. It let them build great looking online stores literally in minutes. And so, by word of mouth mostly, we got more and more users. By the end of 1996 we had about 70 stores online. At the end of 1997 we had 500. Six months later, when Yahoo bought us, we had 1070 users. Today, as Yahoo Store, this software continues to dominate its market. It's one of the more profitable pieces of Yahoo, and the stores built with it are the foundation of Yahoo Shopping. I left Yahoo in 1999, so I don't know exactly how many users they have now, but the last I heard there were about 20,000.
== The Blub Paradox
What's so great about Lisp? And if Lisp is so great, why doesn't everyone use it? These sound like rhetorical questions, but actually they have straightforward answers. Lisp is so great not because of some magic quality visible only to devotees, but because it is simply the most powerful language available. And the reason everyone doesn't use it is that programming languages are not merely technologies, but habits of mind as well, and nothing changes slower. Of course, both these answers need explaining.
I'll begin with a shockingly controversial statement: programming languages vary in power.
Few would dispute, at least, that high level languages are more powerful than machine language. Most programmers today would agree that you do not, ordinarily, want to program in machine language. Instead, you should program in a high-level language, and have a compiler translate it into machine language for you. This idea is even built into the hardware now: since the 1980s, instruction sets have been designed for compilers rather than human programmers.
Everyone knows it's a mistake to write your whole program by hand in machine language. What's less often understood is that there is a more general principle here: that if you have a choice of several languages, it is, all other things being equal, a mistake to program in anything but the most powerful one. #footnote[All languages are equally powerful in the sense of being Turing equivalent, but that's not the sense of the word programmers care about. (No one wants to program a Turing machine.) The kind of power programmers care about may not be formally definable, but one way to explain it would be to say that it refers to features you could only get in the less powerful language by writing an interpreter for the more powerful language in it. If language A has an operator for removing spaces from strings and language B doesn't, that probably doesn't make A more powerful, because you can probably write a subroutine to do it in B. But if A supports, say, recursion, and B doesn't, that's not likely to be something you can fix by writing library functions.]
There are many exceptions to this rule. If you're writing a program that has to work very closely with a program written in a certain language, it might be a good idea to write the new program in the same language. If you're writing a program that only has to do something very simple, like number crunching or bit manipulation, you may as well use a less abstract language, especially since it may be slightly faster. And if you're writing a short, throwaway program, you may be better off just using whatever language has the best library functions for the task. But in general, for application software, you want to be using the most powerful (reasonably efficient) language you can get, and using anything else is a mistake, of exactly the same kind, though possibly in a lesser degree, as programming in machine language.
You can see that machine language is very low level. But, at least as a kind of social convention, high-level languages are often all treated as equivalent. They're not. Technically the term _"high-level language"_ doesn't mean anything very definite. There's no dividing line with machine languages on one side and all the high-level languages on the other. Languages fall along a continuum #footnote[Note to nerds: or possibly a lattice, narrowing toward the top; it's not the shape that matters here but the idea that there is at least a partial order.] of abstractness, from the most powerful all the way down to machine languages, which themselves vary in power.
Consider _Cobol_. Cobol is a high-level language, in the sense that it gets compiled into machine language. Would anyone seriously argue that Cobol is equivalent in power to, say, Python? It's probably closer to machine language than Python.
Or how about Perl 4? Between Perl 4 and Perl 5, lexical closures got added to the language. Most Perl hackers would agree that Perl 5 is more powerful than Perl 4. But once you've admitted that, you've admitted that one high level language can be more powerful than another. And it follows inexorably that, except in special cases, you ought to use the most powerful you can get.
This idea is rarely followed to its conclusion, though. After a certain age, programmers rarely switch languages voluntarily. Whatever language people happen to be used to, they tend to consider
just good enough.
Programmers get very attached to their favorite languages, and I don't want to hurt anyone's feelings, so to explain this point I'm going to use a hypothetical language called Blub. Blub falls right in the middle of the abstractness continuum. It is not the most powerful language, but it is more powerful than Cobol or machine language.
And in fact, our hypothetical Blub programmer wouldn't use either of them. Of course he wouldn't program in machine language. That's what compilers are for. And as for Cobol, he doesn't know how
anyone can get anything done with it. It doesn't even have x (Blub feature of your choice).
As long as our hypothetical Blub programmer is looking down the power continuum, he knows he's looking down. Languages less powerful than Blub are obviously less powerful, because they're missing some feature he's used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn't realize he's looking up. What he sees are merely weird languages. He probably considers them about equivalent in power to Blub, but with all this other hairy stuff thrown in as well. Blub is good enough for him, because _he thinks in Blub_.
When we switch to the point of view of a programmer using any of the languages higher up the power continuum, however, we find that he in turn looks down upon Blub. How can you get anything done in Blub? It doesn't even have y.
By induction, the only programmers in a position to see all the differences in power between the various languages are those who understand the most powerful one. (This is probably what <NAME> meant about Lisp making you a better programmer.) You can't trust the opinions of the others, because of the Blub paradox: they're satisfied with whatever language they happen to use, because it dictates the way they think about programs.
I know this from my own experience, as a high school kid writing programs in Basic. That language didn't even support recursion. It's hard to imagine writing programs without using recursion, but I didn't miss it at the time. I thought in Basic. And I was a whiz at it. Master of all I surveyed.
The five languages that <NAME> recommends to hackers fall at various points on the power continuum. Where they fall relative to one another is a sensitive topic. What I will say is that I think Lisp is at the top. And to support this claim I'll tell you about one of the things I find missing when I look at the other four languages. How can you get anything done in them, I think, without macros? #footnote[It is a bit misleading to treat macros as a separate feature. In practice their usefulness is greatly enhanced by other Lisp features like lexical closures and rest parameters.]
Many languages have something called a macro. But Lisp macros are unique. And believe it or not, what they do is related to the parentheses. The designers of Lisp didn't put all those parentheses in the language just to be different. To the Blub programmer, Lisp code looks weird. But those parentheses are there for a reason. They are the outward evidence of a fundamental difference between Lisp and other languages.
Lisp code is made out of Lisp data objects. And not in the trivial sense that the source files contain characters, and strings are one of the data types supported by the language. Lisp code, after it's read by the parser, is made of data structures that you can traverse.
If you understand how compilers work, what's really going on is not so much that Lisp has a strange syntax as that Lisp has no syntax. You write programs in the parse trees that get generated within the compiler when other languages are parsed. But these parse trees are fully accessible to your programs. You can write programs that manipulate them. In Lisp, these programs are called macros. They are programs that write programs.
Programs that write programs? When would you ever want to do that? Not very often, if you think in Cobol. All the time, if you think in Lisp. It would be convenient here if I could give an example of a powerful macro, and say there! how about that? But if I did, it would just look like gibberish to someone who didn't know Lisp; there isn't room here to explain everything you'd need to know to understand what it meant. In Ansi Common Lisp I tried to move things along as fast as I could, and even so I didn't get to macros until page 160.
But I think I can give a kind of argument that might be convincing. The source code of the Viaweb editor was probably about 20-25% macros. Macros are harder to write than ordinary Lisp functions, and it's considered to be bad style to use them when they're not necessary. So every macro in that code is there because it has to be. What that means is that at least 20-25% of the code in this program is doing things that you can't easily do in any other language. However skeptical the Blub programmer might be about my claims for the mysterious powers of Lisp, this ought to make him curious. We weren't writing this code for our own amusement. We were a tiny startup, programming as hard as we could in order to put technical barriers between us and our competitors.
A suspicious person might begin to wonder if there was some correlation here. A big chunk of our code was doing things that are very hard to do in other languages. The resulting software did things our competitors' software couldn't do. Maybe there was some kind of connection. I encourage you to follow that thread. There may be more to that old man hobbling along on his crutches than meets the eye.
== Aikido for Startups
But I don't expect to convince anyone (over 25) to go out and learn Lisp. The purpose of this article is not to change anyone's mind, but to reassure people already interested in using Lisp -- people who know that Lisp is a powerful language, but worry because it isn't widely used. In a competitive situation, that's an advantage. Lisp's power is multiplied by the fact that your competitors don't get it.
If you think of using Lisp in a startup, you shouldn't worry that it isn't widely understood. You should hope that it stays that way. And it's likely to. It's the nature of programming languages to make most people satisfied with whatever they currently use. Computer hardware changes so much faster than personal habits that programming practice is usually ten to twenty years behind the processor. At places like MIT they were writing programs in high-level languages in the early 1960s, but many companies continued to write code in machine language well into the 1980s. I bet a lot of people continued to write machine language until the processor, like a bartender eager to close up and go home, finally kicked them out by switching to a risc instruction set.
Ordinarily technology changes fast. But programming languages are different: programming languages are not just technology, but what programmers think in. They're half technology and half religion. #footnote[As a result, comparisons of programming languages either take the form of religious wars or undergraduate textbooks so determinedly neutral that they're really works of anthropology. People who value their peace, or want tenure, avoid the topic. But the question is only half a religious one; there is something there worth studying, especially if you want to design new languages.] And so the median language, meaning whatever language the median programmer uses, moves as slow as an iceberg. Garbage collection, introduced by Lisp in about 1960, is now widely considered to be a good thing. Runtime typing, ditto, is growing in popularity. Lexical closures, introduced by Lisp in the early 1970s, are now, just barely, on the radar screen. Macros, introduced by Lisp in the mid 1960s, are still terra incognita.
Obviously, the median language has enormous momentum. I'm not proposing that you can fight this powerful force. What I'm proposing is exactly the opposite: that, like a practitioner of Aikido, you can use it against your opponents.
If you work for a big company, this may not be easy. You will have a hard time convincing the pointy-haired boss to let you build things in Lisp, when he has just read in the paper that some other language is poised, like Ada was twenty years ago, to take over the world. But if you work for a startup that doesn't have pointy-haired bosses yet, you can, like we did, turn the Blub paradox to your advantage: _you can use technology that your competitors, glued immovably to the median language, will never be able to match_.
If you ever do find yourself working for a startup, here's a handy tip for evaluating competitors. Read their job listings. Everything else on their site may be stock photos or the prose equivalent, but the job listings have to be specific about what they want, or they'll get the wrong candidates.
During the years we worked on Viaweb I read a lot of job descriptions. A new competitor seemed to emerge out of the woodwork every month or so. The first thing I would do, after checking to see if they had a live online demo, was look at their job listings. After a couple years of this I could tell which companies to worry about and which not to. The more of an IT flavor the job descriptions had, the less dangerous the company was. The safest kind were the ones that wanted Oracle experience. You never had to worry about those. You were also safe if they said they wanted C++ or Java developers. If they wanted Perl or Python programmers, that would be a bit frightening -- that's starting to sound like a company where the technical side, at least, is run by real hackers. If I had ever seen a job posting looking for Lisp hackers, I would have been really worried.
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/03-unicode/property.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/template/lang.typ": mandingo
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## Character properties
== #tr[character]属性
// The Unicode Standard isn't merely a collection of characters and their code points. The standard also contains the Unicode Character Database, a number of core data files containing the information that computers need in order to correctly process those characters. For example, the main database file, `UnicodeData.txt` contains a `General_Category` property which tells you if a codepoint represents a letter, number, mark, punctuation character and so on.
Unicode标准不仅只是收集所有#tr[character]并为他们分配#tr[codepoint]而已,它还建立了Unicode#tr[character]数据库。这个数据库中包含了许多核心数据文件,计算机依赖这些文件中的信息来正确处理#tr[character]。例如,主数据文件`UnicodeData.txt`中定义了#tr[general category]属性,它能告诉你某个#tr[character]是字母、数字、标点还是符号等等。
// Let's pick a few characters and see what Unicode says about them. We'll begin with codepoint U+0041, the letter `A`. First, looking in `UnicodeData.txt` we see
我们挑一些字符来看看Unicode能提供关于它们的哪些信息吧。从#tr[codepoint]`U+0041`字母`A`开始。首先,在`UnicodeData.txt`文件中有如下数据:
```
0041;LATIN CAPITAL LETTER A;Lu;0;L;;;;;N;;;;0061;
```
// After the codepoint and official name, we get the general category, which is `Lu`, or "Letter, uppercase." The next field, 0, is useful when you're combining and decomposing characters, which we'll look at later. The `L` tells us this is a strong left-to-right character, which is of critical importance when we look at bidirectionality in later chapters. Otherwise, `UnicodeData.txt` doesn't tell us much about this letter - it's not a character composed of multiple characters stuck together and it's not a number, so the next three fields are blank. The `N` means it's not a character that mirrors when the script flips from left to right (like parentheses do between English and Arabic. The next two fields are no longer used. The final fields are to do with upper and lower case versions: Latin has upper and lower cases, and this character is simple enough to have a single unambiguous lower case version, codepoint U+0061. It doesn't have upper or title case versions, because it already is upper case, duh.
在开头的#tr[codepoint]和官方#tr[character]名称之后就是#tr[general category]属性,其值为 `Lu`,含义为“字母(Letter)的大写(uppercase)形式”。下一个属性的值是 `0`,这个属性是用于指导如何进行#tr[character]的#tr[combine]和#tr[decompose]的,这方面的内容我们在后面会介绍,暂时先跳过。下一个属性值是`L`,它告诉我们`A`是一个强烈倾向于从左往右书写的#tr[character],这一属性对于后续会介绍的文本#tr[bidi]性至关重要。除此之外`UnicodeData.txt`中的关于`A`就没有太多有用的信息了:它不是一个由多个#tr[character]组合而成的#tr[character],也不是数字,所以后面的几个属性都是空的。下一个有值的是`N`,它表示当文本的书写方向翻转时,这个字符不需要进行镜像。可以想象一下,圆括号在阿拉伯文环境中,相对于在英文中就是需要镜像的,但`A`不需要。接下来的两个属性已经不再使用了,直接跳过它们。最后一个属性则是有关大小写转换的。拉丁字母有大小写形式,而`A`#tr[character]比较简单,它拥有一个明确的小写版本,码位为`U+0061`。它没有大写或标题形式,呃,因为它本身已经是大写了嘛。
// What else do we know about this character? Looking in `Blocks.txt` we can discover that it is part of the range, `0000..007F; Basic Latin`. `LineBreak.txt` is used by the line breaking algorithm, something we'll also look at in the chapter on layout.
关于这个#tr[character]我们还能知道些什么呢?打开 `Blocks.txt` 文件,我们能知道它处于 `0000..007F; Basic Latin` 这个范围区间。
`LineBreak.txt`中则提供了一些在断行算法中需要用到的信息,我们会在关于#tr[layout]的章节中详细介绍,现在先简单看看:
#[
#set text(0.8em)
```
0041..005A;AL # Lu [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
```
]
// This tells us that the upper case A is an alphabetic character for the purposes of line breaking. `PropList.txt` is a rag-tag collection of Unicode property information, and we will find two entries for our character there:
这一行告诉我们,对于断行来说,大写字母 A 属于 `AL` 类别,含义为字母和常规符号。
`PropList.txt` 是一个混杂了各种Unicode属性信息的集合,在其中和我们的`A`#tr[character]有关的有两条:
#[
#set text(0.7em)
```
0041..0046 ; Hex_Digit # L& [6] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER F
0041..0046 ; ASCII_Hex_Digit # L& [6] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER F
```
]
// These tell us that it is able to be used as a hexadecimal digit, both in a more relaxed sense and strictly as a subset of ASCII. (U+FF21, a full-width version of `A` used occasionally when writing Latin characters in Japanese text, is a hex digit, but it's not an ASCII hex digit.) `CaseFolding.txt` tells us:
这些信息告诉我们,`A` 能够用在十六进制数字中,在宽松环境和严格的ASCII环境中均可。作为对比,`U+FF21` 全宽的 `A` 在日文文本中作为拉丁#tr[character]使用。它也属于十六进制数字,但不属于 ASCII 十六进制数字。
`CaseFolding.txt` 中的信息如下:
```
0041; C; 0061; # LATIN CAPITAL LETTER A
```
// When you want to case-fold a string containing `A`, you should replace it with codepoint `0061`, which as we've already seen, is LATIN SMALL LETTER A. Finally, in `Scripts.txt`, we discover...
这表示当你希望对一个含有`A`的字符串进行#tr[case-fold]时,需要把它替换为#tr[codepoint]`0061`,也就是`LATIN SMALL LETTER A`。
最后,在`Scripts.txt`文件中,可以发现:
#[
#set text(0.8em)
```
0041..005A ; Latin # L& [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
```
]
// ..that this codepoint is part of the Latin script. You knew that, but now a computer does too.
这一条表示这个#tr[codepoint]属于拉丁文。当然,这个信息你早就知道了,但计算机有了这个文件才能知道。
// Now let's look at a more interesting example. N'ko is a script used to write the Mandinka and Bambara languages of West Africa. But if we knew nothing about it, what could the Unicode Character Database teach us? Let's look at a sample letter, U+07DE NKO LETTER KA (ߞ).
现在我们换一个更有趣的例子吧。N'ko(也被称为西非书面字母或恩科字母)是一种用于书写西非地区的曼丁戈语和班巴拉语的#tr[script]。如果我们对这种#tr[script]一无所知的话,Unicode#tr[character]数据库能够提供给我们一些什么信息呢?我们用`U+07DE NKO Letter KA`(#mandingo[ߞ])这个字母来试试吧。
// First, from `UnicodeData.txt`:
首先,`UnicodeData.txt`中的信息有:
```
07DE;NKO LETTER KA;Lo;0;R;;;;;N;;;;;
```
// This tells me that the character is a Letter-other - neither upper nor lower case - and the lack of case conversion information at the end confirms that N'ko is a unicase script. The `R` tells me that N'ko is written from right to left, like Hebrew and Arabic. It's an alphabetic character for line breaking purposes, according to `LineBreak.txt`, and there's no reference to it in `PropList.txt`. But when we look in `ArabicShaping.txt` we find something very interesting:
这行告诉我们,这个#tr[character]属于`Lo`#tr[general category],表示它是一个“字母(Letter)的其他(other)形式”。这里的其他形式表示既不是大写也不是小写。这行最后缺少的大小写转换信息也告诉我们,N'ko 是一种不分大小写的#tr[script]。中间的`R`则表示N'ko#tr[script]是从右往左书写的,就像希伯来文和阿拉伯文那样。
根据 `LineBreak.txt` 中的信息,对于断行来说它和`A`的类别一样,也属于普通字母这一类。在 `PropList.txt` 中没有关于它的信息。但当我们打开 `ArabicShaping.txt` 这个文件时,会发现一些有趣的信息:
```
07DE; NKO KA; D; No_Joining_Group
```
// The letter ߞ is a double-joining character, meaning that N'ko is a connected script like Arabic, and the letter Ka connects on both sides. That is, in the middle of a word like "n'ko" ("I say"), the letter looks like this: ߒߞߏ.
这个字母#mandingo[ߞ]是一个双向互连#tr[character],这意味着N'ko是一种和阿拉伯文类似的连写#tr[script],并且 Ka 字母和左右两边都互相连接。也就是说,在表示“我说”的单词“n'ko”里,这个字母看上去是这样的:#mandingo[ߒߞߏ]。
// This is the kind of data that text processing systems can derive programmatically from the Unicode Character Database. Of course, if you really want to know about how to handle N'ko text and the N'ko writing system in general, the Unicode Standard itself is a good reference point: its section on N'ko (section 19.4) tells you about the origins of the script, the structure, diacritical system, punctuation, number systems and so on.
这就是文字处理系统能用程序从Unicode#tr[character]数据库中获取到的信息。当然,如果你真的想学习N'ko#tr[writing system]的通用知识和如何处理它们,Unicode标准本身就是一个很好的参考资料。它的 N'ko 部分(在 19.4 小节)会告诉你这种#tr[script]的起源、结构、#tr[diacritic]、标点、数字系统等方面的信息。
#note[
// > When dealing with computer processing of an unfamiliar writing system, the Unicode Standard is often a good place to start. It's actually pretty readable and contains a wealth of information about script issues. Indeed, if you're doing any kind of heavy cross-script work, you would almost certainly benefit from getting hold of a (printed) copy of the latest Unicode Standard as a desk reference.
当使用计算机处理一种不熟悉的#tr[writing system]时,Unicode标准通常是一个很好的起点。它的易读性其实非常强,而且包含在处理#tr[script]时会遇到的各种问题的关键信息。事实上,在进行任何繁重的跨#tr[scripts]工作时,如果在手边能有一本(纸质版的)最新版Unicode标准文档作为参考手册,必然会大有裨益。
]
|
https://github.com/yonatanmgr/university-notes | https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661111-%5BLinear%20Algebra%201A%5D/src/lectures/03661111_lecture_10.typ | typst | #import "/template.typ": *
#import "@preview/colorful-boxes:1.2.0": *
#show: project.with(
title: "אלגברה לינארית 1א׳ - שיעור 10",
authors: ("<NAME>",),
date: "6 בפברואר, 2024",
)
// #include "/utils/toc.typ"
// #pagebreak()
#set enum(numbering: "(1.א)")
= העתקות לינאריות - המשך
== תזכורת
יהיו $U,V$ זוג מ״ו מעל אותו שדה $F$, ותהי $T: U->V$ העתקה. נאמר ש-$T$ ה״ל אם:
$ forall u_1, u_2 in U, forall alpha, beta in F: T(alpha u_1 + beta u_2) = alpha T u_1 + beta T u_2 $
ובהכללה:
$ forall u_1, dots, u_n in U, lambda_1, dots, lambda_n in F: T(sum_(k=1)^n lambda_k u_k) = sum_(k=1)^n lambda_k T u_k $
=== גרעין ותמונה
אם $T: U->V$ ה״ל, הגרעין $ker T = {u in U : T u = 0}$ הוא ת״מ של $U$ והתמונה $im T = {T u : u in U}$ היא ת״מ של $V$.
- ה״ל $T: U->V$ היא *חח״ע* אם $forall u_1, u_2 in U: T u_1 = T u_2 iff u_1 = u_2$.
- הוכחנו ש-$T$ חח״ע אם״ם $ker T = {0_U}$.
- ה״ל $T: U->V$ היא *על* אם $im T = V$.
- הוכחנו גם שאם $T$ לינארית אז $T(0_U) = 0_V$.
- ה״ל $T: U->V$ נקראת *איזומורפיזם* אם $T$ חח״ע ועל.
- הוכחנו שאם $T$ איזומורפיזם קיימת $T: U->V$ שהיא גם כן לינארית וגם כן איזומורפיזם.
// #figure(image("/image.png", width: 20%), caption: [איזומופריזם])
נסמן ב-$hom(U, V)$ את אוסף כל הה״ל מ-$U$ ל-$V$, ונסמן ב-$hom(V)$ את אוסף כל הה״ל מ-$V$ לעצמו.
=== (טענה) יהיו $U,V$ זוג מ״ו מעל אותו שדה $F$. אזי, $hom(U,V)$ הוא בעצמו מ״ו מעל $F$ עם הפעולות:
+ $forall T,S in hom(U,V) forall u in U: (T+S) (u) = T u + S u$
+ $forall T in hom(U,V) forall lambda in F forall u in U: (lambda T)(u) = lambda T u$
==== הוכחה
$hom (U,V)$ הינו תת-קב׳ של מרחב הפונק׳ מ-$U$ ל-$V$ ($V^U$). בכדי להסיק שזהו ת״מ מספיק להראות שהעתקת האפס היא לינארית (ראינו בשיעור הקודם) וגם שיש סגירות לצ״ל של ה״ל.
$ forall T, S in hom(U,V), forall alpha, beta in F, forall u_1, u_2 in U, forall lambda, mu in F : \ (alpha T + beta S) (lambda u_1 + mu u_2) = lambda(alpha T + beta S) (u_1) + mu(alpha T + beta S) (u_2)
$
נרצה להראות ש-$alpha T+beta T$ לינארית:
$ (alpha T + beta S)(lambda u_1 + mu u_2) &= alpha T (lambda u_1 + mu u_2) + beta S (lambda u_1 + mu u_2) \ &= lambda (alpha T u_1 + beta S u_1) + mu (alpha T u_2 + beta S u_2) \ &= lambda (alpha T + beta S)(u_1) + mu(alpha T + beta S) (u_2) $
#QED
=== (טענה) תהי $T: U->V$ ה״ל ותהי $S: V->W$ גם ה״ל כאשר $U,V,W$ מ״ו מעל אותו שדה $F$. אז ההרכבה $S of T: U->W$ היא גם לינארית.
==== הוכחה
$ forall u_1, u_2 in U, forall alpha, beta in F: S of T(alpha u_1 + beta u_2) = S(T(alpha u_1+beta u_2)) \ = S (alpha T u_1 + beta T u_2) = alpha S(T u_1) + beta S (T u_2) = alpha dot S of T (u_1) + beta dot S of T (u_2) $
#QED
נתבונן ב-$hom(V)$. ההרכבה מתנהגת כפעולת כפל, ומקיימת:
+ קיום איבר נייטרלי - העתקת הזהות.
+ חוק הקיבוץ: לכל שלישייה של ה״ל $T, S, R: V->V$ מתקיים $(T of S) of R = T of (S of R)$.
+ חוקי הפילוג: לכל שלישייה של ה״ל $T, S, R: V->V$ מתקיים:
$ T of (S+R) = T of S + T of R or (T+S) of R = T of R + S of R $
+ $T of (lambda S) = lambda (T of S)$:
$ T of (lambda S) u = T (lambda S u) = lambda T (S u) = lambda dot T of S (u) $
#outlinebox(
title: "🚸 זהירות!",
color: "red", centering: true
)[
אין חוק חילוף בהרכבת ה״ל:
$ S(x,y) = (x,0), T(x,y) = (y,x), S, T: RR^2->RR^2
\ T of S (x,y) = T(x,0) = (0,x)
\ S of T (x,y) = S(y,x) = (y,0)
$
]
=== (משפט) ה״ל מוגדרת היטב לפי פעולתה על איברי בסיס.
==== הוכחה
יהי $V$ מ״ו מעל השדה $F$ ויהי $B$ בסיס סדור של $V$.
כל וקטור ב-$B$ ניתן להביע בצורה יחידה כצ״ל של איברי $B$.
$ forall v in V exists n in NN_0, exists b_1, dots, b_n in B, exists lambda_1, dots, lambda_n in F: v = sum_(k=1)^n lambda_k b_k $
כעת, $T v = T (sum_(k=1)^n lambda_k b_k) = sum_(k=1)^n lambda_k T b_k $. מהיחידות אנו מסיקים גם שההעתקה מוגדרת היטב (ח״ע). #QED
=== (דוגמה) מעגל היחידה
נגדיר ה״ל נחמדה $T: RR^2->RR^2$:
$ &T vec(1,0) = vec(cos phi, sin phi) \
&T vec(0,1) = vec(cos (phi + R/2), sin (phi + R/2)) = vec(-&&sin phi, &&cos phi)
$
בהצגה פולארית:
$ T vec(R cos theta, R sin theta) = T (R cos theta vec(1,0) + R sin theta vec(0,1)) = R cos theta dot T vec(1,0) + R sin theta dot T vec(0,1) = \ R cos theta dot vec(cos phi, sin phi) + R sin theta dot vec(-&&sin phi, &&cos phi) = R dot vec(cos theta cos phi - sin theta sin phi, cos theta sin phi+ sin theta cos phi) = R dot vec(cos(theta+phi), sin (theta+phi)) $
=== (משפט) משפט המימד
תהי $T: U->V$ ה״ל כאשר $dim U < oo$. אזי: $dim U = dim ker T + dim im T$.
==== הוכחה
הגרעין הינו ת״מ של $U$, ויהי $B = (b_1, dots, b_n)$ בסיס של $ker T$. נשלים את $B$ לבסיס של $U$ ע״י הוספה של $C=(c_1, dots, c_m)$. כלומר, $dim U = n+m$.
אם נראה ש-$(T c_1, dots, T c_m)$ בסיס של $im T$ נוכל להסיק את המשפט.
יהי $v in im T$. מכאן שקיים $u in U$ כך ש-$T u = v$. $B uu U$ בסיס של $U$, כלומר: $u = sum_(k=1)^n alpha_k b_k + sum_(k=1)^m beta_k c_k$. כעת:
$ v= T u = T (sum_(k=1)^n alpha_k b_k + sum_(k=1)^m beta_k c_k) overbrace(=, "T ה״ל") sum_(k=1)^n T b_k + sum_(k=1)^m beta k T c_k in span{T c_1, dots, T c_n} $
ואכן $span{T c_1, dots, T c_m} = im T $, ואז נותר להראות ש-${T c_1, dots, T c_m}$ בת״ל:
$ 0 = sum_(k=1)^m alpha_k T c_k = T (underbrace(sum_(k=1)^m alpha_k c_k, in ker T)) $
#QED
|
|
https://github.com/Vanille-N/mpri2-edt | https://raw.githubusercontent.com/Vanille-N/mpri2-edt/master/ext.typ | typst | #import "typtyp.typ"
#let tt = typtyp
#import "time.typ"
#import "classes.typ"
// This file is where you would declare an external class (not from the MPRI)
// that you take.
//
//
// You are encouraged to MAKE A PULL REQUEST with whatever you add to this file.
//
// 1. For others
// People might be interested in this class and one person adding it can benefit many.
//
// 2. For yourself
// The internal representation is not stable and any changes to this file are
// *not* considered breaking changes. By not including your changes upstream
// you implicitly sign up for having to solve merge conflicts, resolve error
// messages, and update the internal representation yourself.
//
// Please DO NOT REMOVE CLASSES FROM THIS FILE, as it may break other people's setup.
// Here are provided the color codes for MPRI classes. If you want your new
// class to fit into one of these categories, use that color. Otherwise you should
// define a new color.
#import "mpri.typ": verif, prog, logic, algos, data
#tt.is(tt.array(tt.color), (verif, prog, logic, algos, data))
// Otherwise you can also define a new color
#let other = rgb("cf12de").lighten(50%)
// Below is a class formatter.
// It takes up to 4 parameters:
// - `name`: the full name of the class
// - `room`: the location of the class
// - `teacher`: the person teaching that class
// - `uid` (optional): some identifier of the class
// Below is just an example formatter, feel free to define your own with the same signature.
#let fmt(name, uid, teacher, room) = [
#text(size: 11pt, weight: "bold")[#name] \
#text(size: 11pt)[#room]
#text(size: 8pt)[(#teacher)]
#if uid != none [ #text(size: 8pt, weight: "bold")[[#uid]] ]
]
// The next step is to declare the class in the form
// #let my_new_class = classes.new(color, formatter, [Full Name], [Class ID], [Teacher])
// ID may be `none`.
//
// For example, below is the declaration of the class "Introduction to Bullshit",
// from the category "other" (which defines its color), given by professor Whatever.
//
// IMPORTANT: if you use external classes you will need to modify `my.typ` to
// - import them using `#import "ext.typ"` at the top
// - also add `#import "classes.typ"` for the merge function below
// - add them to your `chosen` list by appending e.g. `ext.intro_to_bullshit`
// - replace `mpri.week` with `classes.merge(mpri.week, ext.week)` to register the classes
// see `demo/ext.typ` for details
#let intro_to_bullshit = classes.new(other, fmt, [Introduction to Bullshit], none, [Whatever])
// Then create a new slot in the correct day.
// This is done through the function
// `classes.slot(my_new_class, Room, start: starting-time, len: length, sem: semester, etcs: credits)`
// where
// - `my_new_class` is whatever name you defined just above
// - `Room` should be what Typst calls "content", the easiest way is to just write the text between `[...]`
// - `starting-time` and `length` can be built from the function `time.from-hm(hours, minutes)`
// - `semester` is one of `(1,)` for the first semester only, `(2,)` for the second semester only, or `(1,2)` for both
// Caution: do not forget the trailing comma.
// - `credits` (integer) is however may ECTS credits this class will grant
#let week = tt.ret(classes.Week, (
mon: (
classes.slot(intro_to_bullshit, [in Hell], start: time.from-hm(9,42), len: time.from-hm(3,14), sem:(2,), ects: 1000),
),
tue: (
),
wed: (
),
thu: (
),
fri: (
),
))
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/maupassant.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1850", "1893 (43 let)", "spisovatel", "<NAME>.", "realismus, naturalismus", "/cj-autori/media/maupassant.jpg")
Francouzský spisovatel 2. poloviny 19. století, spolu s Émilem Zolou a Gustavem Flaubertem představitel literárního realismu a naturalismu. Jeho šest románů a několik povídkových sbírek si zaslouží pozornost díky síle realismu, fantaskním prvkům a pesimismu, ale také díky stylistickému umění. Skutečná literární dráha Maupassanta je přitom vymezena pouhým desetiletím -- tvořil mezi lety 1880 a 1890. Uznání se dočkal již za svého života a i dnes je vnímán jako velikán francouzské literatury, jehož dílo se stále interpretuje a adaptuje.
Jeho dílo je inspirováno tvorbou _Honoré de Balsaca_ (zakladatele kriticko-realistického románu) a #underline[_Émila Zoly_] (zakladatele naturalismu).
Naturalismus vychází z realismu, zaměřuje se často na "nechutné detaily", je morbidnější.
Mezi jeho známá díla patří:
1. *Miláček* -- společensko-kritický román, v němž si mladý novinář za pomoci své přitažlivosti buduje kariéru využíváním žen. Nakonec se cílevědomý mladík dostává až do pařížských šlechtických kruhů.
2. *<NAME>* -- také z prostředí prusko-francouzské války; zobrazuje barbarské chování pruských vojáků.
*Současníci*\
_<NAME>_ -- Revizor, 1836\
bratři _Mrštíkovi_ -- Maryša, 1894\
_<NAME>_ -- Zločin a trest, 1866 \
_<NAME>_ -- Zabiják, 1877
#pagebreak() |
https://github.com/Wh4rp/Presentacion-Typst | https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/ejemplos/9_import-fabuloso.typ | typst | #import "8_modulo-fabuloso.typ": faboloso
Tú eres #faboloso[guapisimo]!
Yo soy #faboloso(color: purple)[faboloso]! |
|
https://github.com/lynn/typst-syntree | https://raw.githubusercontent.com/lynn/typst-syntree/main/README.md | markdown | MIT License | # typst-syntree
**syntree** is a typst package for rendering syntax trees / parse trees (the kind linguists use).
The name and syntax are inspired by <NAME>'s [syntree](https://github.com/mshang/syntree). Here's an example to get started:
<table>
<tr>
<td>
```typ
#import "@preview/syntree:0.2.0": syntree
#syntree(
nonterminal: (font: "Linux Biolinum"),
terminal: (fill: blue),
child-spacing: 3em, // default 1em
layer-spacing: 2em, // default 2.3em
"[S [NP This] [VP [V is] [^NP a wug]]]"
)
```
</td>
<td>

</td>
</tr>
</table>
There's limited support for formulas inside nodes; try `#syntree("[DP$zws_i$ this]")` or `#syntree("[C $diameter$]")`.
For more flexible tree-drawing, use `tree`:
<table>
<tr>
<td>
```typ
#import "@preview/syntree:0.2.0": tree
#let bx(col) = box(fill: col, width: 1em, height: 1em)
#tree("colors",
tree("warm", bx(red), bx(orange)),
tree("cool", bx(blue), bx(teal)))
```
</td>
<td>

</td>
</tr>
</table>
|
https://github.com/dankelley/typst_templates | https://raw.githubusercontent.com/dankelley/typst_templates/main/qe/0.0.1/qe.typ | typst | MIT License | // https://typst.app/docs/tutorial/making-a-template/
// https://github.com/typst/packages/?tab=readme-ov-file#local-packages
#let conf(
student: none,
date: none,
doc,
) = {
set text(font: "Times Roman", size: 14pt)
set page("us-letter",
header: [
_Qualifying Examination_
#h(1fr)
*#student*
#h(1fr)
#date
])
doc
}
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/raw-02.typ | typst | Other | // Multiline block splits paragraphs.
Text
```rust
fn code() {}
```
Text
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/bamdone-aiaa/0.1.0/lib.typ | typst | Apache License 2.0 | //***************************************************************
// AIAA TYPST TEMPLATE
//
// The author of this work hereby waives all claim of copyright
// (economic and moral) in this work and immediately places it
// in the public domain; it may be used, distorted or
// in any manner whatsoever without further attribution or notice
// to the creator. The author is not responsible for any liability
// from the usage or dissemination of this code.
//
// Author: <NAME>, <NAME>
// Date: 06 NOV 2023
// BAMDONE!
//***************************************************************
// Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
// This function gets your whole document as its `body` and formats
// it as an article in the style of the AIAA.
#let aiaa(
// The paper's title.
title: (),
// An array of authors. For each author you can specify a name,
// department, organization, location, and email. Everything but
// but the name is optional.
authors-and-affiliations: (),
// The paper's abstract. Can be omitted if you don't have one.
abstract: none,
// The article's paper size. Also affects the margins.
paper-size: "us-letter",
// The result of a call to the `bibliography` function or `none`.
bibliography: none,
// The paper's content.
body,
) = {
// Set document metdata.
set document(
title: title,
author: authors-and-affiliations.filter(a => "name" in a).map(a => a.name)
)
// Set the body font.
set text(
font: "Times New Roman",
top-edge: 5pt,
)
// Configure the page.
set page(
paper: paper-size,
// The margins depend on the paper size.
margin: if paper-size == "a4" {
(x: 41.5pt, top: 80.51pt, bottom: 89.51pt)
} else {
(
x: (72pt / 216mm) * 100%,
top: (72pt / 279mm) * 100%,
bottom: (72pt / 279mm) * 100%,
)
}
)
// Configure equation numbering and spacing.
set math.equation(numbering: "(1)", supplement: [Eq.])
show math.equation: set block(spacing: 0.65em)
// Configure appearance of equation references
show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
// Override equation references.
link(
el.label,
[#el.supplement #numbering(
el.numbering,
..counter(eq).at(el.location())
)]
)
} else {
// Other references as usual.
it
}
}
// Configure lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// Configure headings.
set heading(
numbering: "I.A.1."
)
show heading: it => locate(loc => {
// Find out the final number of the heading counter.
let levels = counter(heading).at(loc)
let deepest = if levels != () {
levels.last()
} else {
1
}
set text(11pt, weight: "bold", font: "Times New Roman")
if it.level == 1 [
// First-level headings are centered smallcaps.
// We don't want to number of the acknowledgment section.
#let is-ack = it.body in ([Acknowledgment], [Acknowledgement])
#v(1.65em, weak: true)
#set align(center)
#set text(size: 11pt, weight: "bold", font: "Times New Roman")
// #show: smallcaps
// #v(20pt, weak: true)
#if it.numbering != none and not is-ack {
numbering("I.", deepest)
// h(7pt, weak: true)
}
#it.body
#v(0.65em, weak: true)
] else if it.level == 2 [
// Second-level headings are run-ins.
#v(1.65em, weak: true)
#set par(first-line-indent: 0pt)
// #v(16pt, weak: true)
#set text(weight: "bold", size: 10pt)
// #v(11pt, weak: true)
#if it.numbering != none {
numbering("A.", deepest)
h(7pt, weak: true)
}
#it.body
] else [
// Third level headings are run-ins too, but different.
#if it.level == 3 {
numbering( "1)" , deepest)
[ ]
}
_#(it.body):_
]
})
// Display the paper's title.
v(3pt, weak: true)
align(center, text(weight: "bold", 24pt, font: "Times New Roman", title))
v(8.35mm, weak: true)
// Display the authors and affiliations list.
{
set align(center)
for author-or-affil in authors-and-affiliations {
// entry is an author
if "name" in author-or-affil {
set text(16pt, top-edge:16pt)
let author-footer = {
if "job" in author-or-affil [#author-or-affil.job]
if "department" in author-or-affil [, #author-or-affil.department]
if "aiaa" in author-or-affil [, #author-or-affil.aiaa]
[.]
}
[#author-or-affil.name #footnote[#author-footer] ]
// the entry is an affiliation
} else {
set text(12pt, top-edge: 10pt, style:"italic")
[\ #author-or-affil.institution]
if "city" in author-or-affil [, #author-or-affil.city]
if "state" in author-or-affil [, #author-or-affil.state]
if "zip" in author-or-affil [, #author-or-affil.zip]
if "country" in author-or-affil [, #author-or-affil.country]
[\ ]
}
}
}
// Configure Figures
show figure.caption: strong
set figure.caption(separator:" ")
set figure(numbering: "1", supplement: [Fig.])
// Configure Tables
show figure.where(kind: table): {
set figure.caption(position: top)
set figure(supplement: [Table])
}
// Configure paragraph properties.
show: columns.with(1, gutter: 0pt)
set par(justify: true, first-line-indent: 1.5em)
show par: set block(spacing: 0.65em)
// Display abstract and index terms.
if abstract != none [
#text(10pt, weight: "bold",
table(
stroke: none,
align: left,
gutter: 0pt,
columns: (36pt, auto, 36pt),
[],[ #h(1.5em) #abstract], []
)
)
]
// Display the paper's contents.
body
// Display bibliography.
if bibliography != none {
show std-bibliography: set text(8pt)
set std-bibliography(title: text(10pt)[References], style: "american-institute-of-aeronautics-and-astronautics")
bibliography
}
}
#let b-equation = it => {
[#set math.equation(numbering: "(1)", supplement: "Equation")
#show math.equation: set block(spacing: 0.65em)
// Configure appearance of equation references
#show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
// Override equation references.
link(
el.label,
[Equation #numbering(
el.numbering,
..counter(eq).at(el.location())
)]
)
} else {
// Other references as usual.
it
}
}
#it ]
}
#let nomenclature(..quantities) = {
let q = quantities.pos()
[= Nomenclature
#table(
stroke: none,
row-gutter: -3pt,
columns: (auto, auto, auto),
align: left,
..q.map(
((k,v)) => ([#k], [$=$], v)
).flatten()
)
]
}
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unofficial-fhict-document-template/0.10.0/README.md | markdown | Apache License 2.0 | <!-- markdownlint-disable MD033 -->
# FHICT Document Template




This is a document template for creating professional-looking documents with Typst, tailored for FHICT (Fontys Hogeschool ICT).
## Introduction
Creating well-structured and visually appealing documents is crucial in academic and professional settings. This template is designed to help FHICT students and faculty produce professional looking documents.
<img src="./thumbnail.png" alt="Showcase" width="100%">
## Requirements
- Roboto font installed on your system (is optional but without it the style is not whole)
- Typst builder installed on your system (Explained in `Getting Started`).
## Features
- Consistent formatting for titles, headings, subheadings, and paragraphs.
- Clean and professional document layout.
- FHICT Style.
- Configurable document options.
- Helper functions.
## Getting Started
To get started with this Typst document template, follow these steps:
1. **Check for the roboto font**: Check if you have the roboto font installed on your system. If you don't, you can download it from [Google Fonts](https://fonts.google.com/specimen/Roboto).
2. **Install Typst**: I recommend to use VSCode with the [Typst LSP Extension](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp). You will also need a PDF viewer in VSCode if you want to view the document live.
3. **Import the template**: Import the template into your own typst document. `#import "@preview/unofficial-fhict-document-template:0.10.0": *`
4. **Set the available options**: Set the available options in the template file to your liking.
5. **Start writing**: Start writing your document.
## Helpful Links / Resources
- The manual contains a list of all available options and helper functions. It can be found [here](https://github.com/TomVer99/FHICT-typst-template/blob/main/documentation/manual.pdf) or attached to the latest release.
- The [Typst Documentation](https://typst.app/docs/) is a great resource for learning how to use Typst.
- The bibliography file is written in [BibTeX](http://www.bibtex.org/Format/). You can use [BibTeX Editor](https://truben.no/latex/bibtex/) to easily create and edit your bibliography.
- You can use sub files to split your document into multiple files. This is especially useful for large documents.
## Contributing
I welcome contributions to improve and expand this document template. If you have ideas, suggestions, or encounter issues, please consider contributing by creating a pull request or issue.
## Disclaimer
This template / repository is not endorsed by, directly affiliated with, maintained, authorized or sponsored by Fontys Hogeschool ICT. It is provided as-is, without any warranty or guarantee of any kind. Use at your own risk.
The author was/is a student at Fontys Hogeschool ICT and created this template for personal use. It is shared publicly in the hope that it will be useful to others.
The use of the Fontys logo is done according to the Fontys guidelines, see [NOTICE](https://github.com/TomVer99/FHICT-typst-template/blob/main/template/assets/NOTICE).
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/src/element.typ | typst | Apache License 2.0 | #import "elements/ports.typ": add-ports, add-port
#import "elements/element.typ": elmt
#import "elements/alu.typ": alu
#import "elements/block.typ": block
#import "elements/extender.typ": extender
#import "elements/multiplexer.typ": multiplexer
#import "elements/logic/gate.typ": gate
#import "elements/logic/and.typ": gate-and, gate-nand
#import "elements/logic/or.typ": gate-or, gate-nor
#import "elements/logic/xor.typ": gate-xor, gate-xnor
#import "elements/logic/buf.typ": gate-buf, gate-not
#import "elements/group.typ": group |
https://github.com/JohnMeyerhoff/typst_utils | https://raw.githubusercontent.com/JohnMeyerhoff/typst_utils/master/listing.typ | typst | #let labeled_frame(label: none, content) = {
let font = (font: "Fira Code", size: 10pt)
set text(..font)
show raw: set text(..font)
box(stroke: black + 2pt, radius: 1em)[
#if label != none {
block(
stroke: black + 2pt,
inset: 0.8em,
below: 0.1em,
radius: (top-left: 1em, bottom-right: 1.5mm),
label,
)
}
#block(
width: 100%,
inset: (rest: 0.5em),
content,
)
]
}
#let include_code_full(file_path, lang) = {
labeled_frame(label: file_path)[
#raw(read(file_path), lang: lang)
]
}
#let include_code_snippet(file_path, lang, start_line, end_line) = {
let all = read(file_path)
let selection = ""
let counter = 1
for x in all.split("\n") {
if((start_line <= counter) and (counter <= end_line)){
selection = selection+ x + "\n"
}
counter+=1
}
labeled_frame(label: file_path)[
#raw(selection, lang: lang)
]
} |
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/meeting_minutes/week_05.typ | typst | = Project Meeting 17.10.2023 08:15 - 09:00 (MS Teams)
== Participants
- Prof. Dr. <NAME>
- <NAME>
- <NAME>
== Agenda
- Presentation of 3 design concept drafts & the survey questionnaire to make a decision
- Input from Advisor:
- Send questionnaire to <NAME>, <NAME>, <NAME> and <NAME>
- Think about what to do if the survey doesn't have a conclusive result
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tiaoma/0.1.0/manual.typ | typst | Apache License 2.0 | #import "./lib.typ": *
#show link: underline
#{
set align(center)
text(17pt)[tiaoma]
par(justify: false)[
A barcode generator for typst. Using #link("https://github.com/zint/zint")[zint] as backend.
]
}
#let barcode-height = 5em
#let left-right(..args) = grid(columns: (1fr, auto), gutter: 1%, ..args)
This package provides shortcut for commonly used barcode types. It also supports all barcode types supported by zint. All additional arguments will be passed to `image.decode` function. Therefore you may customize the barcode image by passing additional arguments.
#left-right[
```typ
#ean("6975004310001", width: 10em)
```
][
#align(right)[#ean("6975004310001", width: 10em)]
]
For more examples, please refer to the following sections.
#line(length: 100%)
#show: doc => columns(2, doc)
= EAN
== EAN-13
#left-right[
```typ
#ean("6975004310001")
```
][
#align(right)[#ean("6975004310001", height: barcode-height)]
]
== EAN-8
#left-right[
```typ
#ean("12345564")
```
][
#align(right)[#ean("12345564", height: barcode-height)]
]
== EAN-5
#left-right[
```typ
#ean("12345")
```
][
#align(right)[#ean("12345", height: barcode-height)]
]
== EAN-2
#left-right[
```typ
#ean("12")
```
][
#align(right)[#ean("12", height: barcode-height)]
]
= Code 128
#left-right[
```typ
#code128("1234567890")
```
][
#align(right)[#code128("1234567890", height: barcode-height)]
]
= Code 39
#left-right[
```typ
#code39("ABCD")
```
][
#align(right)[#code39("ABCD", height: barcode-height)]
]
= UPCA
#left-right[
```typ
#upca("123456789012")
```
][
#align(right)[#upca("123456789012", height: barcode-height)]
]
= Data Matrix
#left-right[
```typ
#data-matrix("1234567890")
```
][
#align(right)[#data-matrix("1234567890", height: barcode-height)]
]
= QR Code
#left-right[
```typ
#qrcode("1234567890")
```
][
#align(right)[#qrcode("1234567890", height: barcode-height)]
]
= Channel Code
#left-right[
```typ
#channel("1234567")
```
][
#align(right)[#channel("1234567", height: barcode-height)]
]
= MSI Plessey
#left-right[
```typ
#msi-plessey("1234567")
```
][
#align(right)[#msi-plessey("1234567", width: 7em)]
]
= Micro PDF417
#left-right[
```typ
#micro-pdf417("1234")
```
][
#align(right)[#micro-pdf417("1234", height: barcode-height)]
]
= Aztec Code
#left-right[
```typ
#aztec("1234567890")
```
][
#align(right)[#aztec("1234567890", height: barcode-height)]
]
= Code 16k
#left-right[
```typ
#code16k("1234567890")
```
][
#align(right)[#code16k("1234567890", width: 7em)]
]
= MaxiCode
#left-right[
```typ
#maxicode("1234567890")
```
][
#align(right)[#maxicode("1234567890", height: barcode-height)]
]
= Planet Code
#left-right[
```typ
#planet("1234567890")
```
][
#align(right)[#planet("1234567890", width: 9em)]
]
= Others
This package supports many other barcode types thanks to zint. You can find the full list in here:
+ Code11
+ C25Standard
+ C25Matrix
+ C25Inter
+ C25IATA
+ C25Logic
+ C25Ind
+ Code39
+ ExCode39
+ EANX
+ EANXChk
+ GS1128
+ EAN128
+ Codabar
+ Code128
+ DPLEIT
+ DPIDENT
+ Code16k
+ Code49
+ Code93
+ Flat
+ DBarOmn
+ RSS14
+ DBarLtd
+ RSSLtd
+ DBarExp
+ RSSExp
+ Telepen
+ UPCA
+ UPCAChk
+ UPCE
+ UPCEChk
+ Postnet
+ MSIPlessey
+ FIM
+ Logmars
+ Pharma
+ PZN
+ PharmaTwo
+ CEPNet
+ PDF417
+ PDF417Comp
+ PDF417Trunc
+ MaxiCode
+ QRCode
+ Code128AB
+ Code128B
+ AusPost
+ AusReply
+ AusRoute
+ AusRedirect
+ ISBNX
+ RM4SCC
+ DataMatrix
+ EAN14
+ VIN
+ CodablockF
+ NVE18
+ JapanPost
+ KoreaPost
+ DBarStk
+ RSS14Stack
+ DBarOmnStk
+ RSS14StackOmni
+ DBarExpStk
+ RSSExpStack
+ Planet
+ MicroPDF417
+ USPSIMail
+ OneCode
+ Plessey
+ TelepenNum
+ ITF14
+ KIX
+ Aztec
+ DAFT
+ DPD
+ MicroQR
+ HIBC128
+ HIBC39
+ HIBCDM
+ HIBCQR
+ HIBCPDF
+ HIBCMicPDF
+ HIBCCodablockF
+ HIBCAztec
+ DotCode
+ HanXin
+ Mailmark2D
+ UPUS10
+ Mailmark4S
+ Mailmark
+ AzRune
+ Code32
+ EANXCC
+ GS1128CC
+ EAN128CC
+ DBarOmnCC
+ RSS14CC
+ DBarLtdCC
+ RSSLtdCC
+ DBarExpCC
+ RSSExpCC
+ UPCACC
+ UPCECC
+ DBarStkCC
+ RSS14StackCC
+ DBarOmnStkCC
+ RSS14OmniCC
+ DBarExpStkCC
+ RSSExpStackCC
+ Channel
+ CodeOne
+ GridMatrix
+ UPNQR
+ Ultra
+ RMQR
+ BC412
There are some examples:
== C25Standard
#left-right[
```typ
#barcode("123", "C25Standard")
```
][
#align(right)[#barcode("123", "C25Standard", height: barcode-height)]
]
== UPCE
#left-right[
```typ
#barcode("1234567", "UPCEChk")
```
][
#align(right)[#barcode("1234567", "UPCEChk", width: barcode-height)]
]
== MicroQR
#left-right[
```typ
#barcode("1234567890", "MicroQR")
```
][
#align(right)[#barcode("1234567890", "MicroQR", width: 3em)]
]
== Aztec Runes
#left-right[
```typ
#barcode("1234567890", "AzRune")
```
][
#align(right)[#barcode("122", "AzRune", height: 3em)]
]
== Australia Post
#left-right[
```typ
#barcode("1234567890", "AusPost")
```
][
#align(right)[#barcode("12345678", "AusPost", width: 9em)]
]
== DotCode
#left-right[
```typ
#barcode("1234567890", "DotCode")
```
][
#align(right)[#barcode("1234567890", "DotCode", width: 3em)]
]
== CodeOne
#left-right[
```typ
#barcode("1234567890", "CodeOne")
```
][
#align(right)[#barcode("1234567890", "CodeOne", height: 3em)]
]
== Grid Matrix
#left-right[
```typ
#barcode("1234567890", "GridMatrix")
```
][
#align(right)[#barcode("1234567890", "GridMatrix", width: 2em)]
]
== Han Xin Code
#left-right[
```typ
#barcode("1234567890", "HanXin")
```
][
#align(right)[#barcode("1234567890", "HanXin", width: 3em)]
]
== Code128B
#left-right[
```typ
#barcode("1234567890", "Code128B")
```
][
#align(right)[#barcode("1234567890", "Code128B", height: 3em)]
]
== ISBN
#left-right[
```typ
#barcode("9789861817286", "ISBNX")
```
][
#align(right)[#barcode("9789861817286", "ISBNX", height: 4em)]
]
== PharmaTwo
#left-right[
```typ
#barcode("1234567890", "PharmaTwo")
```
][
#align(right)[#barcode("12345678", "PharmaTwo", width: 3em)]
]
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/bradbury.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1920", "2012 (91 let)", "spisovatel", "Los Angeles High School", "fantasy, sci-fi", "/cj-autori/media/bradbury.jpg")
<NAME> byl americký spisovatel. Jeho literární kariéra se odehrála převážně v období 20. století, které bylo poznamenáno technologickým pokrokem, studenou válkou a rostoucím vlivem masových médií.
Bradburyho názory se často obracely k otázkám lidského pokroku a technologického rozvoje. Byl skeptický vůči nadměrné závislosti na technologiích a varoval před možnými negativními dopady, které by mohly mít na lidskou společnost. Zároveň byl fascinován lidskou touhou po objevování a pochopení vesmíru.
Umělecky Bradbury zastupoval zejména literární směr známý jako sci-fi a fantastika, ve kterých se zaměřoval na dystopické a futuristické prvky. Jeho díla často kombinují sci-fi s hororem, mysteriem a sociální kritikou.
Mezi další známá díla <NAME>ho patří:
1. *Marťanská kronika (The Martian Chronicles)* - Sbírka sci-fi povídek, které popisují kolonizaci Marsu lidmi. Autor prostřednictvím těchto příběhů zkoumá lidské touhy, ambice a deziluze, a zároveň předkládá otázky o budoucnosti lidstva. Psáno formou datovaného deníku.
2. *Tudy přijde něco zlého (Something Wicked This Way Comes)* - Román, který kombinuje temné prvky fantasy s coming-of-age#footnote("přechod mladého člověka do dospělosti") příběhem. Bradbury v tomto díle zkoumá téma dobra a zla prostřednictvím příběhu o dvou chlapcích, kteří se potýkají se záhadnými událostmi v jejich malém městě.
*Současníci*\
_<NAME>_ -- Já, robot, 1950 \
_<NAME>_ -- Vesmírná Odysea, 1968 \
_<NAME>_ -- <NAME> (@farma[]), 1945 \
_<NAME>_ -- <NAME>. (@rur[]), 1920 \
#pagebreak() |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045%20-%20Kamigawa%3A%20Neon%20Dynasty/006_Episode%205%3A%20Threads%20of%20War.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 5: Threads of War",
set_name: "Kamigawa: Neon Dynasty",
story_date: datetime(day: 27, month: 01, year: 2022),
author: "<NAME>",
doc
)
The compound was a chaos of metal and blood, but the Wanderer didn't stop moving. She was a part of the dance—a figure in the ever-moving battle.
Nearby, Kaito's sword clashed again and again, fighting the onslaught of Jin-Gitaxias's hired henchmen. Tamiyo hovered in the distance, scroll unbound as she held Tezzeret in a temporary state of paralysis.
Deep claw marks were streaked across the floor where Jin-Gitaxias's half-severed body lay. A sign that he'd tried—and failed—to stand back up.
Now, he was unmoving.
The Wanderer didn't bother checking to see if there was still life in him. Fighting felt like being in a trance. It consumed every one of her thoughts, and it wouldn't end until the danger passed.
One by one, their enemies fell. The Wanderer and Kaito made sure of it.
When the chaos faded, only the ring of silence filled the Wanderer's ears. She turned, breathing controlled despite the adrenaline coursing through her, and saw a flicker of relief in Kaito's grin.
"We make a good team," he said, twisting the handle of his sword until the jagged edge flattened and the blade was once again smooth. "It's a shame there's no one left for round two."
"I didn't realize you'd developed such a taste for war," the Wanderer replied, straightening her hat. "The boy I remember would've much preferred the spoils of the palace kitchen."
Kaito's laugh was loose. In one smooth motion, he sheathed his sword at his back. "You've been gone a long time if you think palace food is still the best on Kamigawa. I'll introduce you to this vendor in Towashi—they make these smoked crab rolls that practically melt in your mouth and—"
Tamiyo cleared her throat, motioning to a magically bound Tezzeret. Though his body didn't move, his pink eyes raged with life.
Kaito ran a hand over his shaved head, sheepish. "Right. Business first, food later."
Tamiyo looked at him briefly before focusing her attention on the Wanderer. "It is clear this man poses a threat to Kamigawa, but perhaps it would benefit us all to learn the truth of his plans before we lock him away?"
The Wanderer swept a strand of white hair from her brow. "Whatever his plans, it's the kami he hurt—and perhaps it's the kami he should answer to."
Kaito frowned. "You want to take him to Kyodai?"
Her voice was as unyielding as stone. "Yes. We will decide his fate together."
The emperor was taught to control her emotions, even during battle. But she was still a child when her spark sent her to another plane. For a long time, she was all alone. #emph[Grieving] alone.
So, she did the only thing she could—she tightened the lock on her heart and turned her controlled demeanor into a means of survival.
Now that she was home, she could feel her emotions thundering against her chest, longing to be set free. But she wouldn't let her guard down. Not until she knew for sure that she could stay on Kamigawa.
Because if she opened the gates to her heart and allowed herself to feel the joy of seeing her people again—seeing #emph[Kaito] again—only to have it ripped away from her once more?
It might take an entire lifetime to recover from that kind of heartbreak.
The Wanderer stepped toward Tezzeret and sheathed her own sword. Whatever he'd done to Kyodai ten years ago had inadvertently set off the Wanderer's spark. Perhaps that meant he was also the key to reversing whatever damage his prototype chip had done.
She'd get answers from him. But she'd do it with Kyodai at her side.
"We leave for Eiganjo at once," the Wanderer ordered.
Tamiyo gave a slight bow in acknowledgement. Kaito merely nodded.
But Tezzeret watched them with a newfound energy. The veins in his neck strained against Tamiyo's story magic, gaze drifting down to where the Reality Chip was embedded on the back of the Wanderer's hand. He couldn't move his body, but his mind?
Maybe his mind was all he needed.
An icy shudder ran through the Wanderer. There was no time to say anything—no time to shout a warning before Tezzeret took control of the Reality Chip.
The Wanderer screamed, hands shooting to her temples as the device pulsed with energy. The metal wires dug themselves deeper into her flesh, throbbing with power. There was a flash of white, and she felt her mind jump from the compound to the Imperial Palace, where Kyodai wailed in her chamber. It was as if their minds had been united—and the connection meant that Kyodai was in agony, too.
#figure(image("006_Episode 5: Threads of War/01.jpg", width: 100%), caption: [Art by: Wylie Beckert], supplement: none, numbering: none)
The Wanderer felt like her soul was flickering between the doorway of one plane and the next. The Reality Chip was disrupting her spark, forcing her on the verge of planeswalking. But it also sharpened the Wanderer's bond with Kyodai, and through it, the Wanderer could hear Kyodai's thoughts as clearly as if they'd been standing in the same room.
#emph[Eiganjo is under attack] , Kyodai called out. #emph[Risona has brought an army. You must not planeswalk again—the palace needs you.]
The Wanderer tried to respond—to tell Kyodai about Tezzeret and the Reality Chip—but it was no use. Pain radiated through every nerve. Her spark was destabilizing.
The Wanderer's mind fluttered.
"No!" Kaito shouted, voice hoarse. He threw his hand out, reaching for a large crate in the distance, and tugged with his mind. With a desperate growl, Kaito sent the object flying across the room, where it landed with a heavy#emph[ crack] against Tezzeret's spine.
He slumped to his knees, dazed, but Kaito didn't give him time to recover. A second crate crashed into the back of Tezzeret's head, louder and faster than the first.
The impact knocked Tezzeret out cold.
Tamiyo flattened her mouth and reread the paralysis spell. "His power over technology allows him to manipulate the Reality Chip." Her gaze drifted to the Wanderer. "Whatever he's done—it is making your spark volatile."
Kaito knelt beside the Wanderer, face crumpling with concern. "I thought you said the chip would keep her on Kamigawa?"
Tamiyo floated closer. With an ethereal grace, she leaned down and lifted the Wanderer's hand to get a closer look at the device. "I believe Tezzeret has activated something inside the device. But this technology is beyond my understanding. I do not see a way to undo it."
"I can feel it. It's like I'm splitting apart from inside," the Wanderer said with a pained nod. "Please—help me remove it."
"You will risk planeswalking if I do," Tamiyo noted.
"The chip won't keep me here. Not anymore. And if I planeswalk #emph[with ] it, I'll be lost in the Multiverse with an unstable Reality Chip. Who knows what could happen?" The Wanderer clutched her chest, fighting for a way to tether herself to this plane. "The chip opened a path to Kyodai. I can concentrate my energy on her and use our bond to try and control my spark."
"Will it be enough?" Kaito asked, voice raw with hope.
The Wanderer didn't dare look him in the eyes. She was too afraid he'd see the cracks. "It will have to be," was all she said.
Tamiyo gave a nod of understanding and pressed a finger to the Reality Chip, waiting as the strange wires writhed and shook free of the Wanderer's skin.
#figure(image("006_Episode 5: Threads of War/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The Wanderer bit the edge of her lip, trying not to gasp from the pain. "There's something else," she added, watching the way Tamiyo was studying the chip like it wasn't a weapon at all but a book in an ancient library. Something that needed time to be understood. "Kyodai said Eiganjo is already under attack. If there's any hope of stopping the Uprisers, we need to get there before Risona reaches Kyodai."
Kaito frowned. "She wouldn't hurt a kami, would she?" And not just any kami—Kyodai was the spirit guardian of all Kamigawa.
The Wanderer's face paled. "Risona wants to abolish the empire and bring an end to Imperial rule. Perhaps she believes taking the throne by force will be enough to destroy it. But if she realizes Kamigawa will never accept a radicalized republic without Kyodai's blessing, she may seek to remove Kyodai altogether. Either way, I must protect the temple."
"It will take us hours to reach Eiganjo." Kaito motioned to a still unconscious Tezzeret. "And unless one of Tamiyo's scrolls happens to be a levitation spell, we're going to have to carry our prisoner all the way there. Who, may I point out, is almost #emph[exclusively ] muscle and metal." He lifted his shoulders. "I'm just saying, this may not be the best time for a back injury."
"I was able to planeswalk from Eiganjo to this compound," the Wanderer said. "I can return to the palace the same way."
"But you'd be alone." Kaito shook his head. "Not to mention you don't have the chip this time. What if it didn't work?"
"Then we need transportation." The Wanderer's voice was level. Serious. "Something faster than the sky ferry, with room to carry all four of us."
Kaito twisted his mouth. "There are surveillance mechs all over Otawara. But they're unpilotable. Someone would have to hack into the controls and route a course for Eiganjo manually."
Tamiyo hummed, pensive. "Perhaps there is an alternative. The Reality Chip seems to augment power that is already there, such as the Wanderer's spark." She looked at Kaito. "Like you, I am telekinetic."
Kaito was still kneeling beside the Wanderer, the concern forming a pinch in his brow. "Please tell me you're not suggesting what I think you're suggesting."
Tamiyo lifted the Reality Chip to the back of her own hand and pressed the panel to her flesh. The wires nestled into her skin, making her suck in a quick breath before the edges of the device began to glow.
She motioned to Tezzeret. "Help me carry him to the nearest mech. I will get us to Eiganjo."
The group moved quickly, carrying the weight of their enemy on their shoulders. They made their way to the edge of Otawara, where a surveillance mech shaped like an enormous origami reptile was perched on a high platform. Its sights were glued to the sky ferry below.
Kaito tilted his head toward the armored machine, where a pair of projectiles rested on its shoulders. "Anyone else see the problem here?"
"Allow me," the Wanderer said as if accepting a friendly challenge.
She moved swiftly across the pavement, staying clear of the mech's cameras. Sword in hand, the Wanderer raised the handle over her shoulder, blade pointed skyward, and heaved the weapon straight for the metallic beast's neck—right between two plates of armor at the top of its spine.
The sword struck hard, and sparks flew from its neck like a display of faulty wires. The mech let out a ragged groan before lowering its body to the ground and settling into a state of hibernation.
The Wanderer climbed up its back, using the fan-like armor as steps, and retrieved her sword before twisting to look at the others. "We should hurry—it's only a matter of time before someone notices the surveillance feed is no longer working. And we don't exactly have time to be answering questions."
Kaito and Tamiyo helped to drag Tezzeret's body onto the mech's back, doing their best to secure themselves to the array of metal disks layered along the spine.
With Tezzeret wedged beneath one of his arms, Kaito glanced warily at the Wanderer, and then back at Tamiyo. "Right, so do we count to three or—"
Tamiyo didn't wait for him to finish; she shut her eyes, took a breath, and let the Reality Chip's power course through her veins.
Beneath them, the reptilian mech shook. The Wanderer threw a hand forward, bracing herself against one of the shoulder blades. It sounded as if the sky was being ripped in half—and then the mech lifted into the air.
The Wanderer's heart lurched as Tamiyo sent the machine sailing over the edge of Otawara. They flew through the clouds, wind hammering against their faces. Kaito grinned wildly, enjoying every moment, while Tamiyo's brow was furrowed with deep concentration.
The mech shuddered beneath them—it was a great deal of metal to control, and the Wanderer wasn't sure how the Reality Chip could be affecting Tamiyo. The Wanderer used it to help her planeswalk, but that only took a few seconds. It would take significantly more time to reach Eiganjo.
She tightened her grip around Tezzeret and hoped the breeze would carry them faster.
When they finally broke through the clouds, the Wanderer could hear the faint sound of war in the distance. The clash of metal. The screams of the wounded.
On the surface below, the Wanderer watched as the walls outside the Imperial Palace turned to rubble.
Risona and the Asari Uprisers had indeed come to Eiganjo—and they'd already breached the gates.
When Tezzeret stirred, the Wanderer wasn't fast enough to draw her sword.
With a ferocious wave of his hand, he yanked every smoke device from Kaito's belt, sending them scattering across the mech's back. They exploded in bursts of white and gray smoke, leaving Kaito, Tamiyo, and the Wanderer coughing violently and straining for clean air. The mech rumbled, teetering from side to side, and the Wanderer felt her hand start to slip.
Kaito reached out, fingers latching desperately around her forearm. "I got you!"
But the Wanderer's eyes were pinned to Tezzeret's glowing pink ones. He sneered before launching himself from the mech. At the same time, Tamiyo let out a strained cry.
She couldn't control the mech alone—and they were seconds away from impact, too close to the surface to avoid smashing into the earth.
The Wanderer looked at Kaito with a desperate urgency. "We need to jump," she ordered.
Kaito didn't want to let go—she could see it in his horrified gaze. But the Wanderer wasn't going to give him a choice.
She yanked her arm from his grip and leapt for the surface.
The last thing the Wanderer saw before twisting her body to soften her own landing was the mech exploding against the side of an Imperial apartment.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When the smokey haze finally cleared, Kaito stood, strength returning to his limbs, and searched near the remains of the mech for any sign of the emperor.
He couldn't find her.
Maybe it was a good thing not to find a body. Maybe it meant she survived the fall.
Moth riders swept overhead before diving into the nearby battlefield. They weren't interested in the wreckage. Not when the war continued to rage on the other side of the wall.
And Tezzeret—where had he gone?
When Tamiyo appeared in the clearing, Kaito stared wide-eyed. "What just happened? I thought he was paralyzed!"
Tamiyo lifted her hand, displaying the flickering Reality Chip that remained there. "Using the chip must've interfered with my magic. I could not maintain the spell and fly the mech at the same time."
Kaito laced his fingers together and rested them against his head. "He's a planeswalker—he could be anywhere."
"Tezzeret will not leave this plane without the Reality Chip," Tamiyo pointed out. "And he still believes it's in the emperor's possession."
Kaito's stomach dropped, but the grating sound of metal on metal pulled his attention away. He ran to the other side of the debris, skidding to a halt before he reached the railing, and peered below at the chaos flooding through the Imperial courtyard.
An enormous mech folded itself into the shape of a lion, energy blazing from its outstretched jaws toward the Uprisers charging through the broken wall. Kyodai's temple was still protected, but with the first wall breached and a slew of bodies crowding the gardens, Kaito couldn't say for certain which side was winning.
In the distance, he saw the emperor. Round hat shielding most of her white hair, she was making her way toward Kyodai's chamber. She moved like a gust of wind, determined and focused, and when Kaito's gaze drifted higher, he saw why.
Risona was there, a few buildings ahead, with several Uprisers scaling the wall beside her. She must've used the battle as a diversion and slipped past the most heavily guarded areas.
But the emperor was moving quickly. If her path remained clear, she'd be able to cut Risona off before the Uprisers reached the temple.
#emph[Unless Tezzeret found her first.]
Tamiyo reached the edge of Otawara, slender finger pointing toward the rooftop below. "There." Her voice was sharp. "He's going after the emperor."
Kaito's brows knotted as he scanned the black roof tiles. With his black clothes and dark hair, Tezzeret wasn't easy to find. But when the sunlight glinted off his metal arm, Kaito hissed through his teeth.
"I'll get us closer," Tamiyo said. With one step, she wrapped her arms around Kaito, lifted him into the air, and soared toward Eiganjo's inner wall.
They slammed against one of the roofs with an unpleasant #emph[thud] . Kaito rocked back on his heels to keep from sliding, sending several tiles toppling to the ground.
"I apologize for the rough landing." Tamiyo stood, regaining her composure. "Flying is much easier as a solo venture."
Kaito removed his mask. Himoto folded and refolded like metal paper before shifting into her familiar tanuki shape. Launching her forward with one hand, the drone flew down into the chaos below.
"What are you doing?" Tamiyo asked, puzzled.
He blinked, watching the drone vanish in the crowd. "Making sure we have a backup plan." There was no time to explain—not when the emperor was in danger.
#figure(image("006_Episode 5: Threads of War/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Kaito charged across the roof, scaling wall after wall, trying to close the gap between him and his enemy. Tezzeret was too focused on the emperor to notice Tamiyo flying above, scroll already beginning to unroll.
But Kaito was anxious, and too hungry for a fight. He took one look at the stone lantern perched in the nearby garden and used his mind to send it flying toward Tezzeret. The object smashed against Tezzeret's shoulder, sending him wobbling over the roof tiles. He spun, livid, and spotted Tamiyo first.
The recognition in his eyes when he spotted the Reality Chip on her exposed hand was unmistakable.
Tamiyo didn't get a chance to read her scroll; Tezzeret used his power to summon a bladed electric fan from a sand garden on the other side of the wall and hurled it toward her. When it was only an arm's length away, Tezzeret made a fist with his hand, and the ornament exploded.
Sand hit Tamiyo's eyes, and when she recoiled, her scroll fell.
Kaito leapt to meet them on the roof, not bothering to reach for his sword. His weapons would not help him now; not when every one of them was enhanced with Futurist technology.
With both hands in front of him, Kaito pulled several tiles from the roof and sent them toward Tezzeret like an onslaught of arrows. Tamiyo floated back, squinting as she searched the garden for the scroll that had fallen.
Kaito charged before Tezzeret had time to recover, swinging his leg around until his foot collided against Tezzeret's chin. Again, Tezzeret stumbled, jaw clenched and hands becoming fists.
Kaito could feel the thrum of Tezzeret's power pulling at every scrap of tech on his body—every weapon and piece of armor~all of it made Kaito vulnerable.
But this was Kamigawa. Kaito's home. And he'd spend most of his life scaling the rooftops, making sure the next time he met the man in front of him, he'd be ready.
There was nothing vulnerable about retribution. If anything, it made Kaito stronger. His heart was in this fight, far more than Tezzeret's could ever be.
Kaito shook off the bulk of his enhanced gear, letting his knives and pocket-sized devices trickle down the roof like heavy rain. He didn't need them. Not for this fight.
Kaito's fist met Tezzeret's cheek. He swung with unrelenting force, pushing Tezzeret back across the roof, throwing punch after punch.
Tezzeret brought his metal arm up in defense. This time when Kaito swung, Tezzeret snatched his shirt, pulling him close. Only a fist of metal remained between them.
"You and I were here once before," Tezzeret seethed. "And it didn't end well for you."
"Well, you know what they say—if at first you don't succeed~" Kaito braced himself, "then next time, bring a friend."
Tezzeret paused, confusion taking over, when his mouth tore open and he let out a pain-stricken howl. He released Kaito, stumbling back on the ridgeline. In his thigh was a gleaming dagger, the gold handle carved with the symbol of the Imperials.
Kaito looked down into the courtyard, where samurai and Uprisers had destroyed any semblance of order in the moss garden, and found Eiko. Beside her, Kaito's drone hovered in the air, and a matching blade was in one of her fists.
He gave his sister a mock salute before turning back to Tezzeret, who had only just managed to remove the blade from his wounded leg.
Tamiyo floated down, paralysis scroll stretched in front of her. In an instant, Tezzeret stiffened as if turned to stone.
Tamiyo didn't take her eyes off of him, and when she spoke, her voice was like iron. "Tell the Imperials to prepare an appropriate holding cell. Somewhere #emph[without] tech."
Kaito gave a curt nod. "I'll tell Light-Paws." He turned, getting ready to clamber down the nearest trellis, when Tezzeret's cold voice snapped like the crackle of a last ember.
"There's no need to keep me in Eiganjo," he drawled silkily. "I already have what Phyrexia wants."
Kaito turned, brow furrowed, and watched in horror as Tamiyo's hand flashed and the Reality Chip came to life.
Tamiyo wasn't prepared for the hold Tezzeret would have over her, or how it would sever her connection to her story magic. She reeled, face ashen, and clutched her hand to her chest.
Kaito barely had time to process her distress before Tezzeret lunged, grabbing Tamiyo's trembling body by her shoulders. Snarling, Tezzeret lashed at the air with his metal arm, and a violent, jagged line split through the sky. The crack of electricity pierced Kaito's ears as he watched the portal grow to Tezzeret's full height.
Tezzeret yanked Tamiyo through the snapping light, and they both vanished from the rooftop.
Kaito took a step forward, blinking like he was trying to will everything back to how it was. But it was no use. The portal gave a metallic hiss and snapped shut.
Tamiyo—and Tezzeret—were gone.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Risona moved in circles, footsteps calculated and hair sticking to the sweat on her face. "I will not yield."
The Wanderer matched her pace. "Surrender is not a requirement," she said, voice echoing throughout the chamber.
The fallen bodies of Risona's Uprisers were slumped on the floor. They'd entered the temple only to find the Wanderer waiting. Most of them were easy enough to take down, but Risona was stubborn, and her style of sword fighting was brutal and relentless. It would've made most Imperials sweat.
But the Wanderer was not just any Imperial. And unlike Risona, she had trained on more than one plane. Adapting was second nature to the Wanderer now.
#figure(image("006_Episode 5: Threads of War/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Risona rotated her sword through the air, building momentum for her next strike.
It would do her no good. The Wanderer could've ended the fight ages ago with a blade straight through her heart, but she was holding back. She wasn't after needless bloodshed—she was merely waiting for Risona to accept the inevitable and avoid an execution.
Except the fire in Risona's eyes burned too strong for surrender.
Kyodai's layered voice carried across the mist on the far side of the room. #emph[Your mercy would not be returned if the situation were reversed] , she said into the Wanderer's mind. #emph[She has no interest in peace with the Imperials.]
Risona swung hard, and the Wanderer twirled out of the way with ease, exchanging positions on the opposite end of their imagined battleground. Huffing with exhaustion, Risona only gripped her hilt tighter.
The Wanderer's mouth twitched. She was focused on Risona's faltering steps and the way her shoulders sagged with the weight of her sword.
Risona was tired. And the Wanderer did not wish to humiliate her any further.
The Wanderer raised her sword high. "Drop your blade. There is no need for you to die this way."
"You abandoned your people for over a decade," Risona seethed. "You know #emph[nothing ] of what any of us need."
Her words were like an icicle straight to the Wanderer's chest, even as she tried not to show it. "Leaving was never my choice."
"It doesn't matter," Risona bit back. "You were gone, leaving a weakened kami to oversee the merging of the mortal and spirit realms, and a bickering, power-hungry court to rule in your stead. The Imperials have always had too much control, but your disappearance caused instability to ripple through Kamigawa. You may have Kyodai, but it is the #emph[people's] faith that makes a true leader. And the people lost faith in your return long ago—they will not see you the same way they once did."
"You stormed the palace and murdered dozens." The Wanderer's voice was like steel. "There is no amount of faith that could be recovered after what you've done."
"Perhaps not," Risona said, breaths uneven. "But it is far better to have no Emperor at all than one who cannot be depended on to stay." She raised her sword to the Wanderer's. "We will finish what we started."
Risona lunged—just as something flew across the room and cracked against the side of her skull, knocking her unconscious.
The Wanderer blinked at the stone lying near Risona's body and turned to find Kaito standing several yards away. "Did you—did you just throw a #emph[rock] at the leader of the Asari Uprisers?"
Kaito shrugged, cheeks pink. "I found it in the garden on my way in. I'm out of smoke bombs. And to be honest, after the day I've had, I'm not all that comfortable using metal."
The Wanderer went from aghast horror to something much more like amusement. And when she laughed, the lilting sound poured out of her like it had been locked away for far too many years.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Once Risona was bound in restraints and marched outside as proof the Uprisers had lost, the battle met a swift end. Between those who fled and those who surrendered, there were only a handful of defectors left for the Imperial samurai to deal with.
Kaito stood in the temple window, peering down at the grounds below. He could see Eiko giving orders in the distance. She was suited to Imperial life, even in times of crisis.
"Looks like they have everything under control out there," Kaito mused. "You'll be pleased to know that order is once again restored." He turned toward the emperor, expecting to find her still basking in the relief of victory.
But the emperor was hunched at the waist, grimacing in pain.
Her spark was destabilizing. And without the Reality Chip~
Kaito hurried to the center of the chamber, sliding to his knees. "Tamiyo has the chip." His stomach felt like it was ready to evaporate. "I—I don't know where Tezzeret took her." #emph[I don't know what to do to help] , he wanted to scream.
The emperor pressed a hand to his forearm, shaking her head. "I don't have much time."
Kaito's eyes burned. "There must be something left—some kind of research in the lab that could help keep you here."
When she didn't respond, he felt a familiar ache tighten in his throat.
Guilt flooded back to him, pounding like tidal waves, refusing to ease.
Kaito rubbed his forehead, jaw clenched. For the second time in his life, he'd failed to protect her. "I'm so sorry."
She looked up, expression soft. "This is not your fault, Kaito. It never was. And you have #emph[nothing ] to be sorry for. You have been the most loyal friend I have ever known—and I am grateful to you."
Kyodai's voice was layered with confusion and sadness. She swayed, shadows dancing below her, and lowered her head just above the floor. The black sphere in her forehead flickered like a light beginning to fade.
The emperor watched the kami, conversing with thoughts Kaito couldn't begin to guess. But whatever was said, the emperor did not balk, even when she was met with Kyodai's wails of protestations.
Kaito could see it in the emperor's body language—the finality.
Whatever she was asking~it was the only way to help Kamigawa with the time she had left.
Finally, the kami bent her head.
The emperor forced herself back to her feet and looked at Kaito, still clutching her ribs. "Find Light-Paws. And please—hurry."
Kaito didn't have to run far. Light-Paws and Eiko were already making their way up the temple stairs in search of the emperor. In clipped sentences, he told them what had happened. What was #emph[going ] to happen.
He told them that the Emperor of Kamigawa was running out of time.
They burst back into the chamber, where Kyodai towered above the emperor like a mystical guardian. The bond between the great kami and the emperor had always been strong. The same bond was probably the only thing keeping the emperor in Eiganjo for a few final moments.
"Light-Paws," the emperor said, lifting a hand like she was calling her advisor closer.
Light-Paws moved quickly, bowing at the waist. "Please—tell me how I can help you."
The emperor lifted her chin. "Kamigawa needs someone to rule while I'm away. Someone Kyodai and my people can look to as a true and rightful authority. It is the only thing that will stabilize our lands." She paused. "Kamigawa needs an emperor."
Light-Paws didn't blink, or breathe, or move. She stood the way the stone relics of the ancient forests had stood for thousands of years.
Light-Paws's eyes fluttered. "You can't mean that I~?" She couldn't find the words to finish.
"Kyodai gives her blessing, as do I." The emperor nodded. "You will be my proxy, and rule Kamigawa for as long as I am unable."
#figure(image("006_Episode 5: Threads of War/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Light-Paws knelt then, forehead pressed to the ground. A sign of great respect. "I will do what you ask and honor your legacy every day until you return."
The emperor winced, lips parted as if her tether to Kamigawa had finally snapped.
Kaito felt a panic rush through him. This was happening too fast. Too suddenly.
#emph[He wasn't ready to say goodbye.]
The emperor looked at him. There was no joy in her eyes, but she smiled at him anyway, to offer what little comfort she could. "Kaito—" she started.
But Kaito didn't hear the rest. The spark took hold of her, and the emperor once again vanished from Kamigawa.
Kaito felt his heart shatter in a thousand places. Eiko gasped nearby, hand covering her mouth. Kyodai howled with the ache of a farewell.
Light-Paws continued to bow to the empty space the emperor left behind, her seven tails draped against the floor. Finally, she stood, turning to face Kaito and Eiko.
Behind her, a brand-new tail formed.
And with the sunlight framing her kitsune-like shape, Kaito and his sister bowed to the new Regent of Kamigawa.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
There was no trace of Jin-Gitaxias in the compound, or anywhere else on Otawara or Eiganjo. Kaito's best guess was that Tezzeret took him through the portal after Tamiyo.
There'd have been no reason to return for just a body—which meant Jin-Gitaxias must have survived.
And somewhere in the Multiverse, Kaito felt certain that Tamiyo was alive, too.
"I thought you'd have left already." Eiko's voice sounded nearby.
Kaito released his grip on the railing and looked toward the rest of the balcony where his sister stood in her traditional garb. "I wanted to congratulate my sister on her big promotion. #emph[Senior ] advisor, was it?"
Eiko rolled her eyes. "I know you think it's ridiculous, but you don't need to mock—"
"I'm not," Kaito said, earnestly. He pressed a hand to his chest. "I'm proud of you, Eiko. Truly."
"Oh." She hesitated. "Well—thank you."
Kaito pointed a thumb over his shoulder. "Looks like the outer wall is almost back together."
Eiko's disposition shifted from sister to royal advisor, and her voice rose to match it. "There is still a lot to clean up. The Uprisers are not happy we've taken Risona prisoner. And the power shift within the court has been an adjustment."
"If you're worried about a coup, I have some experience with intervening—and a pretty good throwing arm," Kaito offered with a smirk.
"Kaito," Eiko said slowly. "As much as I look forward to having you closer to home, I am not giving you permission to throw stones at members of the Imperial court."
Kaito said nothing.
Eiko took a place beside her brother, staring into the clouds. "You're not staying, are you." It wasn't a question.
"I made you a promise." Kaito took her hand and squeezed. "I said I wouldn't leave without saying goodbye."
She shut her eyes and took a slow breath. "Are you going to search for the emperor again?"
Kaito followed her gaze into the clouds like he was imagining another plane. "Yes—but there's someone else I need to find first."
He'd already been to Tamiyo's home. He needed to be the one to tell her family what happened. To look them in the eyes and tell them he would search every plane to find her again.
He owed Tamiyo that much. And if she still had the Reality Chip, perhaps he could use it to track down the emperor, too.
Before Kaito left the house, Nashi had promised, as soon as he was old enough, he'd help look for Tamiyo, too.
Kaito knew what such a promise felt like, so he didn't point out how dangerous it would be, or how impossible it would be for Nashi to travel to other planes. Instead, Kaito told him he was looking forward to seeing him again someday, if only to leave the child with hope.
"I know you can't send a drone where you're going, but~" Eiko shook her head, smiling slightly. "Just don't wait too long to let me know you're still alive, okay?"
Kaito nodded, wrapping his arms around her. "Okay," he whispered against her hair. "But the next time we meet, it had better be in Towashi. I'm not coming all the way back to Kamigawa without first filling up on curry and noodles. Priorities and all that."
Eiko laughed, shoving his arm lightly when he pulled away. When she spoke again, her smile faded. "You should see her before you go."
Kaito's throat knotted. He knew who she meant; he'd been avoiding Light-Paws's path for days. "Things were awkward enough when she was an advisor. And now she's the Regent of Kamigawa." Kaito lifted his shoulders. "Maybe we're not meant for a reconciliation."
"Promise me you'll try, someday," Eiko urged.
Kaito stilled, running a hand behind his neck. "For you? I can promise someday." And then he lifted a hand. "See you around, sis."
She nodded, mouth flat as tears filled her eyes. It was all the goodbye she could give him.
For the second time in his life, Kaito left the palace with no plans to return. He would master his planeswalking. He would search the Multiverse for Tamiyo.
He would find a way to finish what he started and bring the emperor home.
= EPILOGUE
"Arise, first of the Phyrexian planeswalkers. You will not be the last."
Tamiyo's eyes fluttered at the sound of Jin-Gitaxias's voice. She sat up, processing the shapes around her. It wasn't the first time she'd been awake in the laboratory, but it was the first time it felt~familiar.
Frowning, Tamiyo reached for her satchel and pulled out one of her story scrolls. She stared at the parchment, watching as the words flashed with a metallic sheen and morphed into another language entirely. She read the Phyrexian text as if she'd been doing it all her life and felt a strange contentment wash over her.
#figure(image("006_Episode 5: Threads of War/06.jpg", width: 100%), caption: [Tamiyo's Compleation | Art by: <NAME>], supplement: none, numbering: none)
Phyrexia was her new home. She was a part of it—mind, body, and soul.
Tamiyo looked down at the chrome flickering across her arms like strange patchwork. It was as freshly polished as the rebuilt portion of Jin-Gitaxias's chest.
The monster shifted nearby, teeth clicking together as he studied the cable-like wires flowing with bright liquid. They trailed from Tamiyo's flesh to a nearby machine.
Tamiyo felt only gratitude to the monster. She had always loved her family and would do anything to protect them. Now, she would protect Phyrexia with the same unfailing loyalty.
When Tezzeret's reflection appeared on one of the surgical glass beakers, Jin-Gitaxias turned, snapping his sharp jaws in greeting.
"Your presence has been scarce in recent days," the monster noted. There was a hint of sharpness in his voice.
Tezzeret brushed off the veiled accusation and lifted his metal arm. It glowed with a faint pink energy. "Using the Planar Bridge takes a toll. I was recovering." He glanced at Tamiyo with distaste.
She tilted her head. Something was rattling him. Something he was attempting to conceal with irritation. "You do not like me. I can feel your truth." If he was not loyal to Phyrexia, she would discover the reason why.
There was a vulnerability in the way he watched her. Perhaps it was not solely to do with his damaged body.
Tezzeret bit down on his unease, replacing it with indifference. "You and your friends tried to interfere with Phyrexia's plans. I have no reason to like you, and even less reason to trust you."
Tamiyo could find only truth in his words, so she settled back in her seat, glancing briefly at the three iron-bound scrolls she swore never to use. She'd always believed they were far too powerful and risked causing great destruction.
But she also promised to intervene if there was ever an immediate threat to the place—and people—she considered home.
Phyrexia was her family now. And there was nothing she wouldn't do for her family.
Jin-Gitaxias snarled. "Your doubt for the previous fleshling is understandable. But the test subject has proven a worthy candidate. To trust the planeswalker now is to trust Phyrexia."
Tezzeret blinked, solemn. "It sounds like things are going well. Does <NAME> know you've succeeded in creating the first Phyrexianized planeswalker?"
"She has been informed and has been suitably chastised for underestimating my intelligence." Jin-Gitaxias moved aside, metal body gleaming. "The work continues to progress, but there is still much to be done."
Research. Further data. #emph[Progress.]
Tamiyo had traveled the Multiverse for knowledge. And if that's what would protect Phyrexia, then she would help in any way she could.
Her family would always come first.
|
|
https://github.com/pimm-dev/agreement-about-religion | https://raw.githubusercontent.com/pimm-dev/agreement-about-religion/main/typst/main.typ | typst | #let lead_manager = "박종현"
#let color = (
title: rgb("#000"),
body: rgb("#333")
)
#let midline = path(
stroke: .5pt + color.body,
closed: false,
(0pt, 0pt),
(0pt, 30%)
)
#let doc_layout(body) = {
text(fill: color.body)[
#body
]
linebreak()
align(center)[
#text(size: 7pt)[
#grid(
columns: 3,
inset: (x: 4pt),
[20#underline[ㅤㅤㅤ] 년], [#underline[ㅤㅤㅤㅤ] 월], [#underline[ㅤㅤㅤㅤ] 일]
)
]
#grid(
columns: (1fr, 1fr, 1fr),
rows: 2em,
align: center + horizon,
[전남대학교 게임개발동아리 PIMM], [대표자ㅤ#lead_manager], [(인)],
[전남대학교 게임개발동아리 PIMM], [서명자ㅤ#underline[ㅤㅤㅤ]], [(인)]
)
]
}
#let doc(body) = {
set page("a4",
flipped: true,
margin: (x: 40pt, top: 35pt, bottom: 25pt),
header: [
#text(size: 5pt)[
#columns(2)[
#align(left)[종교에 관한 서약서, r1.1, 좌측]
#colbreak()
#align(right)[종교에 관한 서약서, r1.1, 우측]
]
]
]
)
set text(size: 6pt, font: ("Noto Serif KR"))
show heading.where(level: 1): it => [
#set align(center)
#set text(size: 12pt, weight: "medium", fill: color.title)
#it
#set text(size: .5em)
#linebreak()
]
show heading.where(level: 2): it => [
#set align(center)
#set text(size: 8pt, weight: "regular", fill: color.title)
#it
#set text(size: .4em)
#linebreak()
]
grid(
columns: (1fr, 70pt, 1fr),
align(horizon)[
#doc_layout(body)
],
align(center + horizon)[
#text(fill: color.body)[
#midline
(인)
#midline
(인)
#midline
]
],
align(horizon)[
#doc_layout(body)
]
)
}
#show: body => doc(body)
#include "README.typ"
|
|
https://github.com/fsr/rust-lessons | https://raw.githubusercontent.com/fsr/rust-lessons/master/src/lesson3.1_c-problems.typ | typst | #import "slides.typ": *
#show: slides.with(
authors: ("<NAME>", "<NAME>"), short-authors: "H&A",
title: "Wer rastet, der rostet", short-title: "Rust-Kurs Lesson 3", subtitle: "Ein Rust-Kurs für Anfänger",
date: "Sommersemester 2023",
)
#show "theref": $arrow.double$
#show link: underline
#new-section("C/++-Probleme")
#slide(title: "basic memory layout")[
#table(
columns: (1fr, 2.3fr, auto),
inset: 7pt,
//align: right,
[*Bsp.-Start-Adresse*], [*name*], [*Wofür*],
`0`, ``, "bleibt frei",
`2000`, "Text/Code", "Maschinencode des Programms",
`6000`, "Data", "Globale Variablen",
`9000`, "Heap", "Dynamische Variablen: `malloc`",
`999000`, "Stack", "Funktions-Lokale Variablen",
)
#uncover(2)[
```cpp
int global = 0;
int text (char local) {
Object local_object; // stirbt mit Ende der Funktion
Object* on_heap = malloc(sizeof(Object)); // existiert weiter
}
```
]
]
#slide(title: "simple String-Klasse")[
```cpp
/** wir wollen uns eine Klasse schreiben,
* die einen String speichert und seine maximale Länge kennt.
*/
class String {
public:
char* data;
unsigned int size;
```
]
#slide(title: "Konstruktor: Geburt")[
```cpp
// create space for a new String, with an initial capacity
String (unsigned int size_request) {
size = size_request; // save the capacity/size
printf("old data: '%s'\n", data);
data = (char*) malloc (size);
printf("new data: '%s'\n", data);
}
```
]
#slide(title: "Destruktor: Tod")[
```cpp
~String () {
free(data);
}
```
]
#slide(title: "String speichern")[
```cpp
// neuen text kopieren und dann data darauf zeigen lassen
void write (char* text, const int length) {
char new_data[length];
sprintf(new_data, "%s", text); // schreibt text in den Puffer new_data
data = &(new_data[0]); // data zeigt jetzt auf den Anfang von new_data
size = length; // update size of data
}
```
]
#slide(title: "printing itself")[
```cpp
void print () const {
printf("%s", data);
// oder (warum verhält sich das unterschiedlich?)
printf("%s\n", data);
}
};
```
]
#slide(title: "main(), erste Hälfte")[
```cpp
int main(int argc, const char* argv[]) {
String my_string (64); // create String with 64 Bytes Space
char* some_data;
if (argc > 2) { // just any condition
some_data = my_string.data;
} else {
some_data = (char*) malloc (64);
}
printf("Please write your favorite color: ");
scanf("%s", some_data); // read a line from user into buffer
printf("Thank you.\n");
```
]
#slide(title: "main(): zweite Hälfte")[
```cpp
// find length of string and write that into my_string
my_string.write(some_data, strlen(some_data));
printf("You said your favorite color was: ");
my_string.print();
printf("\n");
free(some_data); // potential double free
}
```
]
#slide(title: "typische Ausführung")[
```cpp
/** Funktioniert nur deswegen halbwegs, weil Speicher
* null-initialisiert ist und printf bisschen was abfängt.
$ g++ kaputt.cpp -o kaputt && ./kaputt
old data: '(null)'
new data: ''
Please write your favorite color: null_ptr
Thank you.
You said your favorite color was: 'null_ptr'
free(): invalid size
Aborted (core dumped)
*/
```
]
|
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Miscellaneous/test.typ | typst | #show ref: it => {
if it.element == none {
return it
}
if it.element.func() != figure {
return it
}
if it.element.kind != math.equation {
return it
}
if it.element.body == none {
return it
}
if it.element.body.func() != metadata {
return it
}
let num = numbering(
if type(it.element.numbering) == str {
// Trim numbering pattern of prefix and suffix characters.
let counting-symbols = (
"1",
"a",
"A",
"i",
"I",
"一",
"壹",
"あ",
"い",
"ア",
"イ",
"א",
"가",
"ㄱ",
"*",
)
let prefix-end = it.element.numbering.codepoints().position(c => c in counting-symbols)
let suffix-start = it.element.numbering.codepoints().rev().position(c => c in counting-symbols)
it.element.numbering.slice(
prefix-end,
if suffix-start == 0 {
none
} else {
-suffix-start
},
)
} else {
it.element.numbering
},
..it.element.body.value,
)
let supplement = if it.supplement == auto {
it.element.supplement
} else {
it.supplement
}
link(it.element.location(), [#supplement~#num])
}
#show math.equation.where(block: true): it => {
if it.numbering == none or numbering(it.numbering, 1) == none {
return it
}
// Main equation number.
let number = counter(math.equation).get()
// Extract lines and trim spaces.
let lines = if it.body.has("children") {
it.body.children.split(linebreak())
} else {
((it.body,),)
}
// Trim spaces at begin and end of line.
let lines = lines.map(line => {
if line.first() == [ ] and line.last() == [ ] {
line.slice(1, -1)
} else if line.first() == [ ] {
line.slice(1)
} else if line.last() == [ ] {
line.slice(0, -1)
} else {
line
}
})
// Replace fake labels with real labels.
let lines = lines.enumerate().map(((i, line)) => {
let last = line.last()
if last.func() == raw and last.lang == "typc" and last.text.match(
regex("<.+>"),
) != none {
// We use a figure with kind "equation" to make the sub-equation
// referenceable with the correct supplement. The numbering is stored
// in the figure body as metadata, as a counter would only show a
// single number.
let _ = if line.at(-2, default: none) == [ ] {
line.remove(-2)
}
line.at(-1) = [#figure(
metadata(number + if lines.len() > 1 {
(i + 1,)
}),
kind: math.equation,
outlined: false,
numbering: it.numbering,
)#label(last.text.slice(1, -1))]
}
line
}).map(array.join)
// Resolve text direction.
let text-dir = if text.dir == auto {
if text.lang in (
"ar",
"dv",
"fa",
"he",
"ks",
"pa",
"ps",
"sd",
"ug",
"ur",
"yi",
) {
rtl
} else {
ltr
}
} else {
text.dir
}
// Resolve number position in x-direction.
let number-pos = if it.number-align.x in (left, right) {
it.number-align.x
} else if text-dir == ltr {
if it.number-align.x == start {
left
} else {
right
}
} else if text-dir == rtl {
if it.number-align.x == start {
right
} else {
left
}
}
// Location of equation block.
let x-start = here().position().x
layout(bounds => {
// Add numbers to the equation body, so that they are aligned
// at their respective baselines. They are wrapped in a zero-width box
// to not mess with the center alignment.
let body = lines.enumerate().map(((i, line)) => {
let num = numbering(
it.numbering,
..(
number + if lines.len() > 1 {
(i + 1,)
}
),
)
line + box(
width: 0pt,
context {
move(
dx: x-start - here().position().x + if number-pos == right {
bounds.width
},
align(number-pos, box(width: measure(num).width, num)),
)
},
)
}).join(linebreak())
let max-num-width = if lines.len() == 1 {
measure(numbering(it.numbering, ..number)).width
} else {
calc.max(..for i in range(lines.len()) {
(
measure(
numbering(
it.numbering,
..(
number + if lines.len() > 1 {
(i + 1,)
}
),
),
).width,
)
})
}
// Fake numbering taking up space and add spacing.
let pad-key = if align.alignment.x == center {
"x"
} else if number-pos == left {
"left"
} else {
"right"
}
let pad-arg = ((pad-key): max-num-width)
// Step back counter to correct for additional equation.
counter(math.equation).update(n => n - 1)
pad(..pad-arg, math.equation(numbering: _ => none, block: true, body))
})
}
#set page(width: 5cm, height: auto)
#set math.equation(numbering: "(1.1)")
We have
$ a + b &= c #<first> \
&= 1, $
and
$
d + e &= f \
&= g \
&= 2,
$ <outer>
and
$ h = 3. $
See @first and @outer.
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/dynamic/handout.md | markdown | ---
sidebar_position: 5
---
# 创建讲义
在看幻灯片、听课的同时,听众往往会希望有一个讲义,以便能够回顾理解困难的地方,所以,作者最好能给听众提供这样一份讲义,如果能在听课前提供更好。
讲义模式与普通模式的区别是,其不需要过于繁杂的动画效果,因此只会保留每个 slide 的最后一张 subslide。
开启讲义模式是很简单的:
```typst
#let s = (s.methods.enable-handout-mode)(self: s)
```
|
|
https://github.com/WinstonMDP/math | https://raw.githubusercontent.com/WinstonMDP/math/main/exers/d.typ | typst | #import "../cfg.typ": *
#show: cfg
$
"Prove that"
f =_cal(B) O(g) and g =_cal(B) O(f) <->
ex(c_1\, c_2 > 0) ex(B in cal(B)) all(x in B):
c_1 abs(g(x)) <= abs(f(x)) <= c_2 abs(g(x))
$
- To right
$ex(B in cal(B)) ex(alpha) all(x in B): abs(f(x)) = abs(alpha(x) g(x))$
$all(x) in B: abs(f(x)) <= abs(g(x)) sup_(x in B) abs(alpha(x))$
$ex(B' in cal(B)) ex(beta) all(x in B'): abs(g(x)) = abs(beta(x) f(x))$
$all(x in B'): abs(g(x)) <= abs(f(x)) sup_(x in B') abs(beta(x))$
$all(x in B sect B'):
abs(g(x))/abs(sup_(x in B') beta(x)) <=
abs(f(x)) <=
abs(g(x)) sup_(x in B) abs(alpha(x))$
- To left
$all(x in B): abs((f(x))/(g(x))) <= c_2$
$all(x in B): abs((g(x))/(f(x))) <= 1/c_1$
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/lang_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 19-23 expected three or four letter script code (ISO 15924 or 'math')
// #set text(script: "ab") |
https://github.com/chubetho/Bachelor_Thesis | https://raw.githubusercontent.com/chubetho/Bachelor_Thesis/main/chapters/research.typ | typst | = State of the Art Review <section_review>
This chapter is dedicated to identifying instances where micro frontends have been implemented and evaluating the outcomes of these applications. It is organized into two sections: academic literature and industry case studies. The academic literature section examines research that investigates the application and effectiveness of micro frontends across various contexts. The industry case studies section, on the other hand, provides detailed insights into real-world examples, highlighting the practical benefits and challenges encountered by companies that have adopted micro frontend architecture.
== Academic Literature
In their paper, Wang et al. @wang_NovelApplicationEducational_2020 discuss the challenges faced by a monolithic single-page application within an educational management system, specifically issues such as complex logic, high coupling, and difficulties with incremental updates, which are similar to the problems observed at @dklb project. To address these challenges, they propose adopting a micro frontend architecture for East China Normal University's graduate information system, aiming to enhance agile development, service separation, and efficient incremental upgrades. The outcomes of this approach are positive. However, the authors also emphasize the importance of bounded contexts in the design of each micro frontend, which contributes to an improved user experience by maintaining clear functional boundaries.
Perlin et al. @perlin_ApproachFollowMicroservices_2023 explore the application of microservices principles to frontend development by introducing a micro frontend architecture that utilizes multiple frontend frameworks to achieve technological independence and modularity. This approach is validated through a prototype implemented on the Animal Health Defense Platform of Rio Grande do Sul, demonstrating the successful integration of components developed with various frontend frameworks. By employing this strategy, seamless integration and component sharing are achieved. While the case study underscores significant benefits in terms of modularity and flexibility, it also highlights challenges related to interface consistency and operational complexity.
Männistö et al. @mannisto_ExperiencesFrameworklessMicroFrontend_2023 examine the transformation of a monolithic user interface into a micro frontend solution at Visma, focusing on the work of a small development team. The primary motivations behind this transition were to enhance customer-specific configurability and reduce operational costs. During the process, the team observed significant improvements in scalability and deployment efficiency. These benefits were realized despite the team's limited size, highlighting the feasibility and advantages of adopting micro frontend architecture even within smaller organizational settings. The study's findings suggest that small teams can confidently pursue the development of frontend applications using a micro frontend approach.
In the field of the Internet of Things (IoT), Mena et al. @mena_ProgressiveWebApplication_2019 introduce a progressive web application that utilizes microservices and micro frontends to integrate geospatial data and IoT information. The micro frontend approach allows for the independent development and deployment of UI components, fostering modularity and scalability. This architecture enables the frontend to dynamically adapt to various user contexts, such as location and device type, ensuring a seamless user experience.
Similarly, in the mobile domain, Capdepon et al. @capdepon_MigrationProcessMonolithic_ present a model-driven engineering approach for migrating monolithic mobile applications to a micro frontend architecture. This method involves re-architecting applications into smaller, more manageable units, achieving comparable benefits in terms of modularity and scalability.
Further advancing this concept, Shakil et al. and Simoes et al. propose a modular architecture based on micro frontend principles, specifically designed to address the unique requirements of industrial applications. Their studies report positive outcomes from this architectural transition, demonstrating the effectiveness of micro frontends in enhancing the composability and adaptability of industrial systems @shakil_ModularArchitectureIndustrial_2020 @simoes_TwinArkUnifiedFramework_2023.
Lastly, a thorough literature review conducted by <NAME>, <NAME>, and <NAME>, as presented in their 2021 study @peltonen_MotivationsBenefitsIssues_2021, examines findings from 173 diverse sources, including blogs, articles, conference papers, and journal publications. Their review highlights the advantages of micro frontend architecture in frontend development, such as enhancing team autonomy, accelerating the delivery of new features, and supporting diverse technology stacks. These benefits contribute to easier onboarding processes and improved fault isolation, making micro frontends a valuable strategy for managing large and complex frontend applications. However, the review also brings several challenges, including increased payload size, potential code duplication, complexity in monitoring, and difficulties in maintaining a consistent user experience.
== Industry Case Studies
OTTO, a leading German online retailer, restructured its monolithic system to improve extensibility and maintainability. By adopting a distributed, vertical micro-architecture, now recognized as micro frontend architecture, OTTO successfully divided its application into smaller, independent units aligned with specific business domains. This transformation enhanced system adaptability, development efficiency, and overall performance @_MonolithsMicroservicesOTTO_. Similarly, <NAME>, another German retailer, adopted this approach in their "Jump" project, achieving comparable success in improving their system's performance and flexibility @gmbh_InoioGmbhJump_2014.
The German bookstore chain Thalia successfully transitioned from a monolithic system to micro frontends, particularly within their eReader-Shop team. For two years, this shift led to a more cohesive team, faster and higher-quality feature rollouts, and greater independence of services. The frequency of deployments increased significantly, with 49 deployments of new services occurring over two months, in contrast to five deployments under the previous system. This approach has enhanced the team's efficiency, transparency, and adaptability, thereby strengthening Thalia's system and streamlining their development processes @gruber_AnotherOneBites_2019.
Although there are no official documents confirming that SAP, the German software giant, uses micro frontends internally, they have developed a JavaScript framework called Luigi. This framework leverages iframes for implementing micro frontends and offers a comprehensive range of APIs and configuration options to facilitate smooth architectural transformations of applications. Luigi is designed to help developers integrate micro frontends seamlessly into existing systems, providing a flexible and robust solution for modernizing application architectures @_LuigiEnterpriseReadyMicro_.
Zalando, another leading German online retailer, transitioned to micro frontends through their Mosaic project, breaking down the front end into smaller, isolated components. This shift improved scalability, enabled independent deployments, and empowered team autonomy. However, it initially caused user experience inconsistencies and increased infrastructure complexity. To resolve these issues, Zalando developed the Interface Framework to centralize rendering and ensure platform-wide consistency, refining their micro frontends approach @_ZalandoEngineeringBlog_2018. Similarly, both HelloFresh and IKEA have adopted comparable strategies, underscoring the benefits of micro frontends in the retail sector @senders_FrontendMicroservicesHelloFresh_2017 @jan_ExperiencesUsingMicro_.
#pagebreak(weak: true) |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/heading_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test styling.
#show heading.where(level: 5): it => block(
text(font: "Roboto", fill: eastern, it.body + [!])
)
= Heading
===== Heading 🌍
#heading(level: 5)[Heading]
|
https://github.com/HEIGVD-Experience/docs | https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/CLD/docs/7-ContainerCluster/Kubernetes.typ | typst | #import "/_settings/typst/template-note-en.typ": conf
#show: doc => conf(
title: [
Kubernetes
],
lesson: "CLD",
chapter: "7 - Container Cluster",
definition: "",
col: 1,
doc,
)
= Software Containers
== Containers vs Virtual Machines
- Containers provide a lightweight alternative to virtual machines by sharing the host operating system's kernel while maintaining isolated user spaces.
- Containers are more efficient in terms of resource utilization compared to traditional virtual machines.
#image("/_src/img/docs/image copy 84.png")
== Building and Uploading Container Images
- The process involves creating a container image, usually with Docker, and uploading it to a container registry.
- Popular registries include Docker Hub, GitHub Container Registry, Amazon Elastic Container Registry, Azure Container Registry, and Google Artifact Registry.
= Container Cluster Management
== Introduction
- Managing container clusters is essential for deploying applications across multiple hosts to ensure robustness and service continuity.
- Key needs include monitoring container health, optimal placement of containers, and handling failures effectively.
== Container Scheduling
- Scheduling determines the placement of application containers on cluster nodes based on resource requirements and constraints like affinity and anti-affinity.
- Goals are to increase cluster utilization while meeting application requirements.
= YAML (Yet Another Markup Language)
- The operator can create K8s objects with the command line or he can describe the objects in manifest files.
- `kubectl` create -f file.yaml
- File format is JSON, which can also be written as YAML
== Structure
- Only two basic data structures: arrays and dictionaries, which can be nested
- YAML is a superset of JSON
- Easier for humans to read and write than JSON
- Indentation is significant
- Specification at http://yaml.org/
== YAML Example
```yaml
apiVersion: v1
kind: Pod
metadata:
name: redis
labels:
component: redis
app: todo
spec:
containers:
- name: redis
image: redis
ports:
- containerPort: 6379
resources:
limits:
cpu: 100m
args:
- redis-server
- --requirepass ccp2
- --appendonly yes
```
= Kubernetes
== Introduction
- Kubernetes is an open-source platform for automating the deployment, scaling, and management of containerized applications.
- Originally developed by Google, it is now maintained by the Cloud Native Computing Foundation (*CNCF*).
== Anatomy of a Cluster
#image("/_src/img/docs/image copy 85.png")
=== Master Node Components
- *etcd*: A key/value store for cluster configuration data.
- *API Server*: Serves the Kubernetes API.
- *Scheduler*: Decides the nodes on which pods should run.
- *Controller Manager*: Runs core controllers like the Replication Controller.
=== Worker Node Components
- *Kubelet*: Manages the state of containers on a node.
- *Kube-proxy*: Handles network routing and load balancing.
- *cAdvisor*: Monitors resource usage and performance.
- *Overlay Network*: Connects containers across nodes.
== Main Concepts
- *Cluster*: A set of machines (nodes) where pods are deployed and managed.
- *Pod*: The smallest deployable unit, consisting of one or more containers.
- *Controller*: Manages the state of the cluster.
- *Service*: Defines a set of pods and facilitates service discovery and load balancing.
- *Label*: Key-value pairs attached to objects for management and selection.
== Common Concepts
- Kubernetes objects can be created and managed using YAML or JSON files.
- YAML is a human-readable format used to describe Kubernetes objects in configuration files.
== Deploying an Application: IaaS vs Kubernetes
- Traditional IaaS involves manual steps like launching VMs, configuring them, and setting up load balancers.
- Kubernetes simplifies this process with container images and manifests, allowing automated deployment and scaling.
== Kubernetes YAML Example
#columns(2)[
- Every Kubernetes object description begins with two fields:
- *kind*: a string that identifies the schema this object should have
- *apiVersion*: a string that identifies the version of the schema the object should have
- Every object has two basic structures: Object Metadata and Specification (or Spec).
- The Object Metadata structure is the same for all objects in the system
- *name*: uniquely identifies this object within the current namespace
- *labels*: a map of string keys and values that can be used to organize and categorize objects
- *Spec* is used to describe the desired state of the object
#colbreak()
```yaml
apiVersion: v1
kind: Pod
metadata:
name: redis
labels:
component: redis
app: todo
spec:
containers:
- name: redis
image: redis
ports:
- containerPort: 6379
resources:
limits:
cpu: 100m
args:
- redis-server
- --requirepass ccp2
- --appendonly yes
```
] |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/lasaveur/0.1.3/typst-lasaveur.typ | typst | Apache License 2.0 | #let fh(a) = $hat(#a)$
#let ft(a) = $tilde(#a)$
#let f2(a) = $sqrt(#a)$
#let fb(a) = $bold(#a)$
#let fbb(a) = $bb(#a)$
#let fca(a) = $cal(#a)$
#let g6 = $diff$
#let g8 = $infinity$
#let g0 = $nothing$
#let go = $circle.stroked.tiny$
#let g_ = $without$
#let gd = $dot$
#let gt = $times$
#let gU = $union.big$
#let gI = $sect.big$
#let gb = $subset$
#let gbeq = $subset.eq$
#let gbne = $subset.neq$
#let gbneq = $subset.neq$
#let gp = $supset$
#let gpeq = $supset.eq$
#let gpne = $supset.neq$
#let gpneq = $supset.neq$
#let gal = $angle.l$
#let gar = $angle.r$
#let gV = $nabla$
#let gdd = $dot.double$
#let gddd = $dot.triple$
#let gdddd = $dot.quad$
#let g1 = $tilde.op$
#let ka = $alpha$
#let kb = $beta$
#let kc = $chi$
#let kd = $delta$
#let ke = $epsilon.alt$
#let kee = $epsilon$
#let kf = $phi.alt$
#let kff = $phi$
#let kg = $gamma$
#let kh = $eta$
#let ki = $iota$
#let kk = $kappa$
#let kl = $lambda$
#let km = $mu$
#let kn = $nu$
#let ko = $omicron$
#let kp = $pi$
#let kq = $theta$
#let kr = $rho$
#let ks = $sigma$
#let kt = $tau$
#let ku = $upsilon$
#let kv = $sigma.alt$
#let kw = $omega$
#let kx = $xi$
#let ky = $psi$
#let kz = $zeta$
#let kD = $Delta$
#let kG = $Gamma$
#let kL = $Lambda$
#let kX = $Xi$
#let kS = $Sigma$
#let kU = $Upsilon$
#let kF = $Phi$
#let kW = $Omega$
#let partial = $diff$
#let infty = $infinity$
#let circ = $circle.stroked.tiny$
#let setminus = $without$
#let cdot = $dot.op$
#let bigcup = $union.big$
#let bigcap = $sect.big$
#let prod = $product$
#let to = $arrow.r$
#let implies = $arrow.r.double$
#let gets = $arrow.l$
#let iff = $arrow.l.r.double.long$
#let cdots = $dots.h.c$
#let vdots = $dots.v$
#let ddots = $dots.down$
#let int = $integral$
#let iint = $integral.double$
#let iiint = $integral.triple$
#let oint = $integral.cont$
#let sim = $tilde.op$
#let ne = $eq.not$
#let ar = (
l: $arrow.l$,
r: $arrow.r$,
t: $arrow.t$,
b: $arrow.b$,
lr: $arrow.r.long$,
ll: $arrow.l.long$,
llr: $arrow.l.r.long$,
dl: $arrow.l.double$,
dr: $arrow.r.double$,
dlr: $arrow.l.r.double$,
dt: $arrow.t.double$,
db: $arrow.b.double$,
ldl: $arrow.l.long.double$,
ldr: $arrow.r.long.double$,
ldlr: $arrow.l.r.long.double$,
)
|
https://github.com/ryuryu-ymj/mannot | https://raw.githubusercontent.com/ryuryu-ymj/mannot/main/src/annot.typ | typst | MIT License | #import "util.typ": copy-stroke
#let _place-path-arrow(
stroke: 1pt,
tail-length: 5pt,
tail-angle: 30deg,
..vertices,
) = {
place(path(stroke: stroke, ..vertices))
let stroke = copy-stroke(stroke, (dash: "solid"))
context {
let vertices = vertices.pos()
let tail-length = tail-length.to-absolute()
let p1 = vertices.last()
let p1x = p1.at(0).to-absolute()
let p1y = p1.at(1).to-absolute()
let p2 = vertices.at(vertices.len() - 2)
let p2x = p2.at(0).to-absolute()
let p2y = p2.at(1).to-absolute()
let p12x = p2x - p1x
let p12y = p2y - p1y
let p12len = 1pt * calc.sqrt(p12x.pt() * p12x.pt() + p12y.pt() * p12y.pt())
p12x = p12x / p12len * tail-length
p12y = p12y / p12len * tail-length
let angle = 30deg
let sin = calc.sin(angle)
let cos = calc.cos(angle)
let t1x = p1x + p12x * cos - p12y * sin
let t1y = p1y + p12x * sin + p12y * cos
let t2x = p1x + p12x * cos + p12y * sin
let t2y = p1y - p12x * sin + p12y * cos
place(path(stroke: stroke, (t1x, t1y), (p1x, p1y), (t2x, t2y)))
}
}
/// Places a custom annotation to the marked content.
///
/// This function creates a custom annotation by placing an overlay on the content
/// that was previously marked with a specific tag.
/// It must be used within the same math block that contains the marked content.
///
/// *Example*
/// #example(```
///let myannot(tag, annotation) = {
/// let overlay(width, height, color) = {
/// set text(white, .8em)
/// let annot-block = box(fill: color, inset: .4em, annotation)
/// place(annot-block, dy: height)
/// }
/// return core-annot(tag, overlay)
///}
///
///$
///mark(x, tag: #<e>)
///#myannot(<e>)[This is x.]
///$
/// ```, preview-inset: 20pt)
///
/// - tag (label): The tag associated with the content you want to annotate.
/// This tag must match a previously used tag in a `core-mark` call.
/// - overlay (function): The function to create a custom annotation.
/// It takes `width`, `height`, and `color` as arguments,
/// where `width` and `height` represent the size of the marked content,
/// and `color` is the base color passed to `core-mark`.
#let core-annot(tag, overlay) = {
context {
let info = query(selector(tag).before(here())).last()
info = info.value
let hpos = here().position()
let dx = info.x - hpos.x
let dy = info.y - hpos.y
let width = info.width
let height = info.height
let color = info.color
box(place(dx: dx, dy: dy, overlay(width, height, color)))
}
}
/// Places an annotation to the marked content.
///
/// This function must be used within the same math block that contains the marked content.
///
/// *Example*
/// #example(```
///$
///mark(x, tag: #<e>)
///#annot(<e>)[Annotation]
///$
/// ```)
///
/// #example(```
///$
///mark(integral x dif x, tag: #<x>, color: #blue)
///+ mark(y, tag: #<y>, color: #red)
///
///#annot(<x>, pos: left)[Left]
///#annot(<x>, pos: top + left)[Top left]
///#annot(<y>, pos: left, yshift: 2em)[Left arrow]
///#annot(<y>, pos: top + right, yshift: 1em)[Top right arrow]
///$
/// ```, preview-inset: 20pt)
///
/// - tag (label): The tag associated with the content you want to annotate.
/// This tag must match a previously used tag in a `core-mark` call.
/// - annotation (content): The content of the annotation.
/// - pos (alignment): The position of the annotation relative to the marked content.
/// Possible values are (`top` or `bottom`) + (`left`, `center` or `right`).
/// - yshift (length): The vertical distance between the annotation and the marked content.
/// - text-props (dictionary): Properties for the annotation text.
/// If the `fill` field is not specified, it defaults to the color used in the marking.
/// - par-props (dictionary): Properties for the annotation paragraph.
/// - alignment (auto, alignment): The alignment of the annotation text within its box.
/// - show-arrow (auto, bool): Whether to display an arrow connecting the annotation to the marked content.
/// If set to `auto`, an arrow will be shown when `yshift > .4em`.
/// - arrow-stroke (auto, none, color, length, dictionary, stroke):
/// The stroke style for the arrow.
/// If the `paint` field is not specified, it defaults to the color used in the marking.
/// - arrow-padding (length): The space between the arrow and the annotation box.
#let annot(
tag,
annotation,
pos: center + bottom,
yshift: .2em,
text-props: (size: .6em, bottom-edge: "descender"),
par-props: (leading: .3em),
alignment: auto,
show-arrow: auto,
arrow-stroke: .08em,
arrow-padding: .2em,
) = {
assert(
pos.x == left or pos.x == center or pos.x == right or pos.x == none,
message: "The field `x` of the argument `alignment` of the function
`annot` must be `left`, `center`, `right` or `none`.",
)
assert(
pos.y == top or pos.y == bottom or pos.y == none,
message: "The field `y` of the argument `alignment` of the function
`annot` must be `top`, `bottom` or `none`.",
)
let pos = (
if pos.x == none {
center
} else {
pos.x
} + if pos.y == none {
bottom
} else {
pos.y
}
)
if alignment == auto {
alignment = pos.x.inv()
}
context {
let text-props = text-props
let annot-tsize = text-props.remove("size", default: 1em).to-absolute()
set text(size: annot-tsize)
context {
let annot-content = {
show: par.with(..par-props)
show: align.with(alignment)
text(..text-props, annotation)
}
let annot-size = measure(annot-content)
let overlay(width, height, color) = text(
size: annot-tsize,
{
let annot-content = text(annot-content)
if text-props.at("fill", default: auto) == auto {
annot-content = text(color, annot-content)
}
let draw-arrow = show-arrow
if draw-arrow == auto {
draw-arrow = if yshift > .4em {
true
} else {
false
}
}
if not draw-arrow {
// Place annotation.
let dx = width / 2 + if pos.x == center {
-annot-size.width / 2
} else if pos.x == left {
-annot-size.width
}
let dy = if pos.y == bottom {
height + yshift
} else {
-annot-size.height - yshift
}
place(annot-content, dx: dx, dy: dy)
} else {
// Place arrow and annotation.
let arrow-stroke = stroke(arrow-stroke)
if arrow-stroke.paint == auto {
arrow-stroke = copy-stroke(arrow-stroke, (paint: color))
}
let p3x = width / 2
let p3y = if pos.y == bottom {
height + arrow-stroke.thickness
} else {
-arrow-stroke.thickness
}
let p2x = p3x
let p2y = if pos.y == bottom {
if pos.x == center {
p3y + yshift
} else {
p3y + annot-size.height + arrow-padding * 2 + yshift
}
} else {
p3y - yshift
}
let p1x = if pos.x == right {
p2x + annot-size.width + arrow-padding
} else if pos.x == left {
p2x - annot-size.width - arrow-padding
}
let p1y = p2y
if arrow-stroke.thickness > 0pt {
// Place the arrow.
if pos.x == center {
_place-path-arrow(stroke: arrow-stroke, tail-length: .3em, (p2x, p2y), (p3x, p3y))
} else {
_place-path-arrow(stroke: arrow-stroke, tail-length: .3em, (p1x, p1y), (p2x, p2y), (p3x, p3y))
}
}
// Place the annotation.
if pos.x == right {
place(annot-content, dx: p2x + arrow-padding, dy: p2y - annot-size.height - arrow-padding)
} else if pos.x == left {
place(
annot-content,
dx: p2x - annot-size.width - arrow-padding,
dy: p2y - annot-size.height - arrow-padding,
)
} else {
if pos.y == bottom {
place(annot-content, dx: p2x - annot-size.width / 2, dy: p2y + arrow-padding)
} else {
place(annot-content, dx: p2x - annot-size.width / 2, dy: p2y - annot-size.height - arrow-padding)
}
}
}
},
)
return core-annot(tag, overlay)
}
}
}
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/decorations/slice/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#quantum-circuit(
ctrl(0), slice(), 1, [\ ],
slice(), slice(x: 4, y: 0, n: 1, stroke: blue)
) |
https://github.com/HPDell/typst-starter-journal-article | https://raw.githubusercontent.com/HPDell/typst-starter-journal-article/main/lib.typ | typst | MIT License | #let author-meta(
..affiliation,
email: none,
alias: none,
address: none,
cofirst: false
) = {
let info = (
"affiliation": affiliation
)
if email != none {
info.insert("email", email)
}
if alias != none {
info.insert("name", alias)
}
if address != none {
info.insert("address", address)
}
if cofirst != none {
info.insert("cofirst", cofirst)
}
info
}
#let default-title(title) = {
show: block.with(width: 100%)
set align(center)
set text(size: 1.75em, weight: "bold")
title
}
#let default-author(author) = {
text(author.name)
super(author.insts.map(it => str(it+1)).join(","))
if author.corresponding {
footnote[
Corresponding author. Address: #author.address.
#if author.email != none {
[Email: #underline(author.email).]
}
]
}
if author.cofirst == "thefirst" {
footnote("cofirst-author-mark")
} else if author.cofirst == "cofirst" {
locate(loc => query(footnote.where(body: [cofirst-author-mark]), loc).last())
}
}
#let default-affiliation(id, address) = {
set text(size: 0.8em)
super([#(id+1)])
address
}
#let default-author-info(authors, affiliations) = {
{
show: block.with(width: 100%)
authors.map(it => default-author(it)).join(", ")
}
let used_affiliations = authors.map(it => it.insts).flatten().dedup().map(it => affiliations.keys().at(it))
{
show: block.with(width: 100%)
set par(leading: 0.4em)
used_affiliations.enumerate().map(((ik, key)) => {
default-affiliation(ik, affiliations.at(key))
}).join(linebreak())
}
}
#let default-abstract(abstract, keywords) = {
// Abstract and keyword block
if abstract != [] {
stack(
dir: ttb,
spacing: 1em,
..([
#heading([Abstract])
#abstract
], if keywords.len() > 0 {
text(weight: "bold", [Key words: ])
text([#keywords.join([; ]).])
} else {none} )
)
}
}
#let default-bibliography(bib) = {
show bibliography: set text(1em)
show bibliography: set par(first-line-indent: 0em)
set bibliography(title: [References], style: "apa")
bib
}
#let default-body(body) = {
show heading.where(level: 1): it => block(above: 1.5em, below: 1.5em)[
#set pad(bottom: 2em, top: 1em)
#it.body
]
set par(first-line-indent: 2em)
set footnote(numbering: "1")
body
}
#let article(
// Article's Title
title: "Article Title",
// A dictionary of authors.
// Dictionary keys are authors' names.
// Dictionary values are meta data of every author, including
// label(s) of affiliation(s), email, contact address,
// or a self-defined name (to avoid name conflicts).
// Once the email or address exists, the author(s) will be labelled
// as the corresponding author(s), and their address will show in footnotes.
//
// Example:
// (
// "<NAME>": (
// "affiliation": "affil-1",
// "email": "<EMAIL>", // Optional
// "address": "Mail address", // Optional
// "name": "<NAME>", // Optional
// "cofirst": false // Optional, identify whether this author is the co-first author
// )
// )
authors: ("<NAME>": author-meta("affiliation-label")),
// A dictionary of affiliation.
// Dictionary keys are affiliations' labels.
// These labels show be constent with those used in authors' meta data.
// Dictionary values are addresses of every affiliation.
//
// Example:
// (
// "affiliation-label": "Institution Name, University Name, Road, Post Code, Country"
// )
affiliations: ("affiliation-label": "Affiliation address"),
// The paper's abstract.
abstract: [],
// The paper's keywords.
keywords: (),
// The bibliography. Accept value from the built-in `bibliography` function.
bib: none,
// Templates for the following parts:
// - `title`: how to show the title of this article.
// - `author-list`: how to show the list of the authors.
// - `author`: how to show each author's information.
// - `affiliation`: how to show the affiliations.
// - `abstract`: how to show the abstract and keywords.
// - `bibliography`: how to show the bibliography.
// - `body`: how to show main text.
// Please see below for more infomation.
template: (:),
// Paper's content
body
) = {
// Set document properties
set document(title: title, author: authors.keys())
show footnote.entry: it => [
#set par(hanging-indent: 0.54em)
#it.note #it.note.body
]
set footnote(numbering: "*")
show "cofirst-author-mark": [These authors contributed equally to this work.]
let template = (
title: default-title,
author-info: default-author-info,
abstract: default-abstract,
bibliography: default-bibliography,
body: default-body,
..template,
)
// Title block
(template.title)(title)
set align(left)
// Restore affiliations' keys for looking up later
// to show superscript labels of affiliations for each author.
let inst_keys = affiliations.keys()
// Find co-fisrt authors
let cofirst_index = authors.values().enumerate().filter(
meta => "cofirst" in meta.at(1) and meta.at(1).at("cofirst") == true
).map(it => it.at(0))
let author_list = ()
// Authors and affiliations
// Authors' block
// Process the text for each author one by one
for (ai, au) in authors.keys().enumerate() {
let author_list_item = (
name: none,
insts: (),
corresponding: false,
cofirst: "no",
address: none,
email: none,
)
let au_meta = authors.at(au)
// Write auther's name
let aname = if au_meta.keys().contains("name") and au_meta.name != none {
au_meta.name
} else {
au
}
author_list_item.insert("name", aname)
// Get labels of author's affiliation
let au_inst_id = au_meta.affiliation.pos()
let au_inst_primary = ""
// Test whether the author belongs to multiple affiliations
if type(au_inst_id) == array {
// If the author belongs to multiple affiliations,
// record the first affiliation as the primary affiliation,
au_inst_primary = affiliations.at(au_inst_id.first())
// and convert each affiliation's label to index
let au_inst_index = au_inst_id.map(id => inst_keys.position(key => key == id))
// Output affiliation
author_list_item.insert("insts", au_inst_index)
} else if (type(au_inst_id) == str) {
// If the author belongs to only one affiliation,
// set this as the primary affiliation
au_inst_primary = affiliations.at(au_inst_id)
// convert the affiliation's label to index
let au_inst_index = inst_keys.position(key => key == au_inst_id)
// Output affiliation
author_list_item.insert("insts", (au_inst_index,))
}
// Corresponding author
if au_meta.keys().contains("email") or au_meta.keys().contains("address") {
author_list_item.insert("corresponding", true)
let address = if not au_meta.keys().contains("address") or au_meta.address == "" {
au_inst_primary
} else { au_meta.address }
author_list_item.insert("address", address)
let email = if au_meta.keys().contains("email") and au_meta.email != none {
au_meta.email
} else { none }
author_list_item.insert("email", email)
}
if cofirst_index.len() > 0 {
if ai == 0 {
author_list_item.insert("cofirst", "thefirst")
} else if cofirst_index.contains(ai) {
author_list_item.insert("cofirst", "cofirst")
}
}
author_list.push(author_list_item)
}
(template.author-info)(author_list, affiliations)
(template.abstract)(abstract, keywords)
show: template.body
body
// Display bibliography.
if bib != none {
(template.bibliography)(bib)
}
}
|
https://github.com/Liusef/3403-tech-doc | https://raw.githubusercontent.com/Liusef/3403-tech-doc/main/basics.typ | typst |
#let sectctr = counter("mycounter")
#let pgctr = counter("values")
#let typ_rgb = rgb("258a98")
#let latex = box(image("assets/latex.svg", height: 13pt), height: 9pt)
#let typst = box(image("assets/typst_filled.svg", height: 11pt), height: 7.6pt)
#page(
background: rect(
fill: gradient.linear(rgb(24, 210, 182), rgb("3d98bb"), angle: 45deg),
height: 100%,
width: 100%
),
[
#align(
horizon,
[
#image("assets/typst.svg", width: 60%)
#text("COMPOSE DOCUMENTS\nFASTER.", size: 8mm, weight: "semibold", fill: white, tracking: 1mm, font: "Avenir Next LT Pro")
]
)
#align(
bottom,
[
#line(length: 100%, stroke: white)
#text("A quick start guide for users switching from LaTeX or Microsoft Word.", fill: white, font: "Aganè S", size: 13pt)
]
)
]
)
#set text(font: "Aganè", tracking: -.25pt, fill: black.lighten(20%))
// #set text(font: "Avenir Next LT Pro")
// #set text(font: "Helvetica Neue")
// #set text(font: "DIN 2014")
// #set text(font: "Graphik")
// #set text(font: "Linux Libertine")
// #set text(font: "New Computer Modern")
#show raw: set text(font: "Cascadia Mono PL", weight: "regular")
#let pagetitle(intext, count) = {
if count {
[
#box(height: 8mm, [
#circle(fill: typ_rgb, radius: 4.5mm,[
#align(center+horizon,[
#text(sectctr.display(), size: 6mm, weight: "bold", fill: white)
])
])
]) #h(2mm) #text(
intext, weight: 800, size: 1cm, fill: typ_rgb, tracking: -1pt
)
#v(4mm)
]
sectctr.step()
} else {
[
#text(
intext, weight: 800, size: 1cm, fill: typ_rgb, tracking: -1pt
)
#v(1mm)
]
}
}
#let uri(url, vis) = {
link(url, text(vis, fill: typ_rgb))
}
#set page(
background: [
#rect(
fill: gradient.linear(rgb(24, 180, 182), rgb("3d98bb"), angle: 45deg),
height: 120%,
width: 100%
)
#v(-31.5cm)
#stack( dir: ltr,
box(width: 2.5cm),
rect(
fill: white, radius: 7mm,
height: 100%,
width: 100%,
)
)
#align(bottom+left,
[
#pgctr.step()
#rotate( 90deg,
[
#h(17.5mm)
#image("assets/typst.svg", height: -7.6mm)
]
)
#h(0.5cm)
#text(pgctr.display(), fill: white, font: "Aganè")
#v(1cm)
]
)
]
)
#page(
background: [
#rect(
fill: gradient.linear(rgb(24, 180, 182), rgb("3d98bb"), angle: 45deg),
height: 120%,
width: 100%
)
#v(-27cm)
#stack( dir: ltr,
box(width: 2.5cm),
rect(
fill: white, radius: 7mm,
height: 100%,
width: 100%,
)
)
#align(bottom+left,
[
#pgctr.step()
#rotate( 90deg,
[
#h(17.5mm)
#image("assets/typst.svg", height: -7.6mm)
]
)
#h(0.5cm)
#text(pgctr.display(), fill: white, font: "Aganè")
#v(1cm)
]
)
],
[
#v(-.75cm)
#text(
"Welcome to typst !", weight: 800, size: 1.3cm, fill: white, tracking: -1pt, font: "Linux Libertine",
)
#v(.25cm)
Typst is a powerful, flexible, and friendly typesetting tool for the modern era. Using the built in functions and layouts, the ecosystem of external packages, and the powerful scripting tools, Typst can be used for any documents of your choosing, including research papers, theses, essays, reports, memos, and more.
= Why Typst?
For anyone who has used #latex in the past, after learning some of the basics, you'll feel right at home with Typst. However, Typst is faster to write, easier to read and debug, renders nearly instantly, and allows for real time collaboration with peers.
Typst also benefits people who currently typeset documents using conventional visual editors like Microsoft Word or Google Docs. The powerful template system allows you focus on writing and lets Typst handle the formatting as you type. And like LaTeX, Typst outputs higher quality documents with better justification and layouts.
= Who is this guide for?
Typst is an incredibly powerful piece of software with a rich featureset, limitless extensibility, and a plethora usecases. *However, the scope of this guide will be limited to basic features like simple typesetting and math/equations.* Someone who could find this document useful is a student or researcher who is frustrated with LaTeX and is looking for a better alternative for writing high quality documents.
Some of the topics this guide will cover include:
- Environment Setup
- Writing Basic Documents
- Math Mode
- Basic Scripting
- Third Party Packages
- Templates
= Precautions and Safety Warning
*Typst is still pre-release software*. Not everything is working and there may be core functionality still missing from the software. Although I have had few issues with Typst, your mileage may vary. If you encounter issues or want to request new features, feel free to contact the developers on Discord or GitHub (links at the end of the document).
If you use the online version of Typst, you will be sending possibly personally identifiable information to the maintainers of Typst. Typst uses opt-out trackers on its website. Typst uses Microsoft Azure for content distribution and your information may be logged by Microsoft. Typst is compliant with the EU's GDPR and California's CCPA data privacy laws.
If you use the offline version of Typst, you will need to download possible unstable software onto your computer. By using an offline version of Typst, you assume all risks.
]
)
#pagebreak()
#pagetitle("Environment Setup", true)
There are a few ways that you can get started with Typst.
= Web Editor
#grid(
columns: (2fr, 1fr), gutter: 5mm,
[
For a hassle free experience, use the online editor!
== Pros of the Web Editor
- No hassle setup
- Automatic updates
- Live updating and recompiling
- Real time collaboration
],
align(right, image(
"assets/setup/web.png",
height: 4cm, width: 4.5cm
))
)
#grid(
columns: (1fr, 1fr), [
== Getting Started
Getting started on the web editor is as easy as going to #uri("https://typst.app/", "typst.app") and signing up for an account! Once you're there, you can work on projects, collaborate with teams, and create whatever you want with Typst!
],
align(right, [
#let s_vs_i_h = 3.5cm
#let s_vs_i_w = 7cm
#stack(
spacing: -s_vs_i_h - 5pt,
image(
"assets/setup/webhome.jpg",
height: s_vs_i_h, width: s_vs_i_w
),
box(
height: s_vs_i_h + 10pt,
width: s_vs_i_w + 4pt,
radius: 16pt,
stroke: 10pt + white,
),
)
])
)
= Visual Studio Code + Typst LSP
Using Vscode with the Typst LSP is as easy as the online editor with more flexibility!
#grid(
columns: (auto, auto), gutter: 5mm,
[
== Pros of VSCode + Typst LSP
- Quick Setup
- Familiar Environment
- Fast, offline compilation
- Use local resources like fonts
To get started with Typst in Visual Studio Code, just install the "Typst LSP" extension and a PDF extension of your choice. Then create a ```bash .typ``` file and start writing!
],
[
#image(
"assets/setup/vsext.png"
)
#let s_vs_i_h = 4.5cm
#let s_vs_i_w = 8cm
#stack(
spacing: -s_vs_i_h - 5pt,
image(
"assets/setup/vscode.png",
height: s_vs_i_h, width: s_vs_i_w
),
box(
height: s_vs_i_h + 10pt,
width: s_vs_i_w + 4pt,
radius: 16pt,
stroke: 10pt + white,
),
)
]
)
#v(-1cm)
= Other Options
There are other options for setting up a development environment for typst as well!
Quarto, an open source scientific and technical publishing system, now supports typst as an input format.
Additionally, the Typst CLI (found at #uri("https://github.com/typst/typst", "github.com/typst/typst")) allows you to use typst with any text editor of your choosing!
#let typ_ex(height, input, content) = {
[
#v(2mm)
#grid(
columns: (1fr, 1fr), gutter: 5mm,
rect(
width: 100%, height: height, fill: rgb("293035"), radius: 2mm,
grid(
columns: (1.5mm, 1fr, 1.5mm),
box(),
[
#v(1mm)
#text(font: "Cascadia Code PL", weight: "bold", fill: blue.lighten(50%), "your_doc.typ")
#v(-1.8mm)
#line(length: 100%, stroke: white)
#v(-1mm)
#show raw: set text(fill: white)
#raw(input, lang: "typst")
],
box()
)
),
rect(width: 100%, height: height,
grid(
columns: (1.5mm, 1fr, 1.5mm),
box(),
[
#v(1mm)
#text(weight: "extrabold", tracking: 1pt, fill: typ_rgb, "OUTPUT", size: 12pt)
#v(-2.5mm)
#line(length: 100%)
#v(-1mm)
#set text(size: 10pt, font: "Linux Libertine")
#content
],
box()
)
)
)
]
}
#pagebreak()
#pagetitle("The Basics", true)
Basic text entry in Typst is just like typing in Word. If you type text into a blank typst file, it will render that text onto a blank document (like a pdf).
#typ_ex(
2.5cm,
"Hello! This is a blank typst document with some text in it. ",
[Hello! This is a blank typst document with some text in it.]
)
= Text Formatting
For formatting, Typst uses formatting similar to *Markdown*, a lightweight markup language. If you've used markdown or other markdown like editors (usually found in messaging applications), you'll feel right at home with Typst. If not, there are a few simple rules for formatting in Typst.
The main ones to remember are:
- Use \*s to make text *Bold*
- Use \_ to make text #text("Oblique", style: "italic", font: "Frutiger Neue LT W1G Book")
- Use \= to create headers of different sizes!
- \- to make Bulleted lists
- \+ to make Numbered Lists
- Wrap text in \`s to make a code block!
- Wrap text with 3 \`\`\`s and write the name of a language right after for syntax highlighting! (eg. #raw("```rust /* rust code here */ ```", lang: "md"))
#typ_ex(
6.4cm,
"Wrap text with \* to make it *Bold* \
Wrap text with \_ to make it _Oblique_\
Wrap with \` to make it `a code block`
= Large Header
// add '='s for smaller headers
== Smaller Header
- Bulleted List Item
+ Numbered List Item
Use the '\\\' character for line breaks
",
[
Wrap text with \* to make it *Bold* \
Wrap text with \_ to make it _Oblique_ \
Wrap with \` to make it `a code block`
= Large Header // add '='s for smaller headers
#v(-2mm)
== Smaller Header
- Bulleted List Item
+ Numbered List Item
Use the '\\' character for line breaks
]
)
#pagebreak()
#pagetitle("Math Input", true)
One of the major draws of Typst is it's strong but simple math input functionality. Users coming from Word may be familiar with how slow inputting math can be, and people switching from LaTeX are well aware of how messy TeX code can get with complex equations.
In Typst, there are two types of math blocks. Inline and Blocks. Both are created by wrapping text with `$`'s. However, blocks have whitespace between the `$` and the start of the math code.
#typ_ex(
3.8cm,
"There's *inline math*:
$nabla dot bold(E) = rho/epsilon_0$ \
$ bold(\"Block Math\") \"is centered.\"\
nabla times bold(B) = mu_0 (bold(J) + epsilon_0 frac(diff bold(E), diff t)) $",
[
There's *inline math*: $nabla dot bold(E) = rho/epsilon_0$ \
$
bold("Block Math") "is centered."\
nabla times bold(B) = mu_0 (bold(J) + epsilon_0 frac(diff bold(E), diff t))
$
]
)
=== Additional Syntax
Compared to Word and LaTeX, writing math code in Typst is a little different, but after learning some of the basic syntax, you'll be on your way to typesetting math in typst like a pro!
#let typ_demo(width, title, code, cont) = {
[
#rect( width: width, stroke: 1pt, radius: 6pt,
grid(
columns: (2mm, auto, 2mm),
box(),
[
#v(2mm)
#align(center, text(fill: typ_rgb, weight: "bold", title))
#v(-3mm)
#line(length: 100%)
#v(-1mm)
#grid(
columns: (1fr,0mm, 1fr),
align(center,raw(code, lang: "typst")),
$arrow.r$,
align(center, cont )
)
#v(2mm)
], box()
)
)
]
}
#let tdlw(width, lw, title, code, cont) = {
[
#rect( width: width, stroke: 1pt, radius: 6pt,
grid(
columns: (2mm, auto, 2mm),
box(),
[
#v(2mm)
#align(center, text(fill: typ_rgb, weight: "bold", title))
#v(-3mm)
#line(length: 100%)
#v(-1mm)
#grid(
columns: (lw,0mm, 1fr),
align(center,raw(code, lang: "typst")),
$arrow.r$,
align(right, cont )
)
#v(2mm)
], box()
)
)
]
}
#grid( columns: (auto, auto, auto), gutter: 3mm,
typ_demo(4.7cm, "Sub / Superscripts", " $x^u_d$ ", $x^u_d$),
typ_demo(3.5cm, "Fractions", "$1/x$", $1/x$),
typ_demo(7cm, "Greek Symbols", "$sigma$ $Sigma$", $sigma #h(2mm) Sigma$)
)
#v(-2mm)
#grid( columns: (auto, auto), gutter: 3mm,
typ_demo(6cm, "Some Shorthands", "$ => != >=$", $=> #h(2mm) != #h(2mm) >=$),
tdlw(9.5cm, 3fr, "Special Characters (See Docs for more)", "$arrow.l.curve integral.cont$", $arrow.l.curve #h(4mm) integral.cont$)
)
#v(-2mm)
#grid( columns: (auto, auto), gutter: 3mm,
tdlw(6.5cm, 1.5fr, "Text in Math", "$x_0 \"Text!\" x_1$", $x_0 "Text!" x_1$),
tdlw(9cm, 2.68fr, "Math Functions", "$floor(x), frac(X, z*y), sqrt(9)$", $floor(x), frac(X, z*y), sqrt(9)$)
)
=== Aligning
Use the `&` character to align math on different lines! This is good for if you're showing many different steps on different lines.
#v(-4mm)
#typ_ex(
3.5cm,
"Use & to align lines in block math:
$
nabla times D &= & &rho_v \
nabla times H &= &(diff D)/(diff t) + &J
$
",
[
Use & to align lines in block math:
$
nabla times D &= & &rho_v \
nabla times H &= &(diff D)/(diff t) + &J
$
]
)
#pagebreak()
#pagetitle("Scripting", true)
One of Typst's headlining features is the built in scripting features. Typst's scripting features allow you to automate repetitive tasks like layouting. Typst has lots of built in functions for layouting and visualization. Some of these include `text()` for rendering special text, `align()` for aligning content, `page()` for making special pages in your document, and many more!
Typst also includes functionality specifically for scripting and calculations. Some of these include control flow constructs like loops, conditionals, and others! Typst also has lots of built-in functions like `range()`, `zip()`, and `map()` which behaves like Python's range, zip, and map functions.
One sample usecase for the scripting is working on a tedious mathematical problem. You can write code that both does all the calculations for the problem while also generating code that shows all of your work!
#typ_ex(
5.1cm,
"#let factorial(n) = {\n\tlet curr = 1\n\tfor val in range(1, n+1) {\n\t\tlet prod = curr * val\n\t\t[ Round #val: $curr*val=prod$ \ ]\n\t\tcurr = prod\n\t}\n}
#factorial(8)",
[
#let factorial(n) = {
let curr = 1
for val in range(1, n+1) {
let prod = curr * val
[Round #val:#h(2mm) $curr * val = prod$\ ]
curr = prod
}
}
#factorial(8)
]
)
\
Learn more about scripting in Typst at #uri("https://typst.app/docs/reference/scripting/","typst.app/docs/reference/scripting")
#pagebreak()
#pagetitle("Templates", true)
"Templates" include a few different features within Typst.
You can create templates using scripting functions that apply certain styles and layouts automatically. This allows you to focus on writing and lets you make changes to the template that apply across the whole document.
Here's a basic example of a template!
#v(-2.2mm)
#typ_ex(
4cm,
"// Example from typst docs
#let amazed(term) = box[✨ #term ✨]
You are #amazed[beautiful]!",
[
#let amazed(term) = box[✨ #term ✨]
You are #amazed[beautiful]!
]
)
Templates can do as little or as much as you want them to! The only limitations on what you can do are the Typst scripting language and ✨ Your Imagination ✨
=== Separate Files
You can also create separate files for templates that can define the visual style of your document, how the text flows on the page, different graphic elements on the page, page numbers, and more! One place this would be useful would be if you need to follow a specific format for a document. Examples of this would be if a specific conference needs a paper to include certain visual elements, or if you need to follow an organizational template.
#let imdesc(imgp, desc) = {
align(center,
[
#image(imgp)
#text(desc, fill: gray)
]
)
}
#grid(
columns: (1fr, 1fr, 1fr),
imdesc("assets/template/ieee.png", "IEEE Format"),
imdesc("assets/template/oxford.png", "Oxford Format"),
imdesc("assets/template/mdpi.png", "MDPI Format")
)
#v(3mm)
Typst maintains a small repository of provided templates here #uri("https://github.com/typst/templates", "github.com/typst/templates")
Learn more about templates at #uri("https://typst.app/docs/tutorial/making-a-template", "typst.app/docs/tutorial/making-a-template").
#pagebreak()
#pagetitle("Third Party Packages", true)
Typst has a strong ecosystem of 3rd party packages that extend the core functionality of Typst with even more features. You can browse and learn how to install packages at #uri("https://typst.app/docs/packages/", "typst.app/docs/packages").
<NAME> also maintains a github repository containing a list of cool and helpful typst tools! Some things on there include chatbots for rendering typst code, typst extensions for other editors, templates for other formats and conferences, resume templates, formatting libraries, and even solutions for leetcode problems written with the typst scripting language! Check out the repo here: #uri("https://github.com/qjcg/awesome-typst", "github.com/qjcq/awesome-typst")
A package that students, engineers, and scientists alike may find useful is *Fletcher*, a package for making charts and diagrams. Here's an example of using fletcher:
#typ_ex(
10cm,
"#import \"@preview/fletcher:0.4.2\" as fletcher: node, edge
// https://xkcd.com/1195/
#import fletcher.shapes: diamond
#set text(font: \"Comic Neue\", weight: 600)
$
#fletcher.diagram(\n\tnode-stroke: 1pt,\n\tedge-stroke: 1pt,\n\tnode((0,0), [Start], corner-radius: 2pt, extrude: (0, 3)),\n\tedge(\"-|>\"),\n\tnode((0,1), align(center)[\n\t\tHey,\ this flowchart\ is a trap!\n\t], shape: diamond),\n\tedge(\"d,r,u,l\", \"-|>\", [Yes], label-pos: 0.1)
)
$",
[
#import "@preview/fletcher:0.4.2" as fletcher: node, edge
// https://xkcd.com/1195/
#import fletcher.shapes: diamond
#set text(font: "Comic Neue", weight: 600)
$
#fletcher.diagram(
node-stroke: 1pt,
edge-stroke: 1pt,
node((0,0), [Start], corner-radius: 2pt, extrude: (0, 3)),
edge("-|>"),
node((0,1), align(center)[
Hey,\ this flowchart\ is a trap!
], shape: diamond),
edge("d,r,u,l", "-|>", [Yes], label-pos: 0.1)
)
$
]
)
This example was borrowed from the documentation for fletcher: #uri("https://github.com/Jollywatt/typst-fletcher","github.com/Jollywatt/typst-fletcher")
#page(
background: rect(
fill: gradient.linear(rgb(14, 190, 152), rgb("2d78ab"), angle: 45deg),
height: 100%,
width: 100%
),
align(horizon ,[
#let alt_uri(lk, sh) = {
box( height: 7pt,
rect( height: 14pt, fill: white, radius: 2pt,
uri(lk, sh)
)
)
}
#let bau(label, lk, sh) = {
box( height: 1cm,
rect( height: 12mm, fill: white, radius: 2pt,
align(left,
[
#text(label, fill: black.lighten(40%))
#v(-4.5mm)
#link(lk, text(sh, fill: typ_rgb, size: 5mm, weight: "bold"))
])
)
)
}
#align(left,
[
#pgctr.step()
#text("WHAT NEXT?", font: "Avenir Next LT Pro", size: 2cm, weight: "bold", fill: white)
]
)
#set text(fill: white, size: 12pt)
Typst is still in beta and is getting new updates as we speak! To learn more about Typst, find more packages, or learn more about the features or Syntax of typst, visit the *Typst Docs* at #alt_uri("https://typst.app/docs", "typst.app/docs")!
There's also a community Discord Server and a GitHub page if you want to speak to the developers! For example, if you're facing an issue with Typst, have a question on how to accomplish a task, or want to request a feature, join the open Typst Discord Server or leave an issue on the Typst GitHub page.
#v(1cm)
#align( right,
align(
left,
[
#box(image("assets/doc.png", width: 1.2cm)) #h(5mm) #bau("Read the docs", "https://typst.app/docs", "typst.app/docs")
#box(image("assets/discord.svg", width: 1.2cm)) #h(5mm) #bau("Join the Discord", "https://discord.gg/2uDybryKPe", "discord.gg/2uDybryKPe")
#box(image("assets/github.svg", width: 1.2cm)) #h(5mm) #bau("Check out the GitHub", "https://github.com/typst/", "github.com/typst")
#box(image("assets/github.svg", width: 1.2cm)) #h(5mm) #bau("Awesome Typst Projects!", "https://github.com/qjcg/awesome-typst", "github.com/qjcq/awesome-typst")
#box(image("assets/github.svg", width: 1.2cm)) #h(5mm) #bau("Source code for this doc", "https://github.com/Liusef/3403-tech-doc", "github.com/Liusef/3403-tech-doc")
]
)
)
#align(
bottom+left,
[
#image("assets/typst.svg", width: 10%)
#v(-4mm)
#text("Compose Documents Faster.", size: 2mm, weight: "regular", fill: white, font: "Avenir Next LT Pro", tracking: 1pt)
]
)
])
)
#pagebreak()
#pagetitle("References", false)
- Typst GmbH. (2024). Typst. Typst. #link("https://typst.app")
- Typst GmbH. (2024). The Typst Tutorial. Typst. #link("https://typst.app/docs/tutorial")
- The LaTeX Project. (2024). LaTeX. The LaTeX Project. #link("https://www.latex-project.org/")
- Microsoft Corp. (2024). Microsoft 365. Microsoft Corp. #link("https://microsoft365.com/")
- Alphabet Inc. (2024). Google Docs. Alphabet Inc. #link("https://docs.google.com")
- Microsoft Corp. (2024). Microsoft Azure. Microsoft Corp. #link("https://azure.microsoft.com/")
- European Union. (2018). General Data Protection Reg. European Union. #link("https://gdpr.eu/")
- State of California. (2018). California Consumer Privacy Act. California Department of Justice, Office of the Attorney General. #link("https://www.oag.ca.gov/privacy/ccpa")
- Typst GmbH. (2024). Typst Live Collaboration Graphic. Typst. #link("https://typst.app")
- Microsoft Corp. (2024). GitHub. Microsoft Corp. #link("https://github.com/")
- Typst GmbH. (2024). Typst Homepage. Typst. #link("https://typst.app/home")
- Microsoft Corp. (2024). Visual Studio Code. Microsoft Corp. #link("https://code.visualstudio.com/")
- Microsoft Corp. (2024). Microsoft Windows. Microsoft Corp. #link("https://windows.com/")
- <NAME>. (2024). Typst Language Server Protocol. <NAME>. #link("https://github.com/nvarner/typst-lsp")
- Microsoft Corp. (2024). Visual Studio Marketplace. Microsoft Corp. #link("https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp")
- Quarto. (2024). Quarto. Quarto. #link("https://quarto.org/")
- Rust Foundation. (2024). Rust Lang. Rust Foundation. #link("https://rust-lang.org/")
- Python Software Foundation. (2024). the Python programming language. Python Software Foundation. #link("https://python.org/")
- Typst GmbH. (2024). Typst Package Repository. Typst. #link("https://github.com/typst/packages")
- <NAME>. (2024). Awesome Typst. <NAME>. #link("https://github.com/qjcg/awesome-typst")
- <NAME>. (2024). Fletcher. Jollywatt. #link("https://github.com/Jollywatt/typst-fletcher")
- <NAME>. (2024). XKCD. <NAME>. #link("https://xkcd.com/")
- Typst Gmbh. (2024). Typst Templates for IEEE, Oxford, MDPI. Typst. #link("https://typst.app/")
- Institute of Electrical and Electronics Engineers. (2024). IEEE. Institute of Electrical and Electronics Engineers. #link("https://www.ieee.org")
- Oxford University. (2024). Oxford University Press. Oxford University. #link("https://corp.oup.com")
- Multidisciplinary Digital Publishing Institute. (2024). MDPI. Multidisciplinary Digital Publishing Institute. #link("https://mdpi.com/")
- Typst GmbH. (2024). Typst Documentation. Typst. #link("https://typst.app/docs")
- Typst GmbH. (2024). Typst Privacy Policy. Typst. #link("https://typst.app/privacy/")
- Discord Inc. (2024). Discord. Discord Inc. #link("https://discord.com/")
- Microsoft Corp. (2021). Cascadia Code. Microsoft Corp.
- Microsoft Corp. (2021). Fluent Emojis. Microsoft Corp.
- Microsoft Corp. (2024). Fluent Design System. Microsoft Corp.
- <NAME>. (2017). The Aganè Font Family. <NAME>.
- <NAME>. (2015). Avenir Next. <NAME>.
- <NAME>. (2015). Neue Frutiger. <NAME>.
- Libertine Open Fonts Project. (2012). Linux Libertine. Libertine Open Fonts Project.
#page(
background: rect(
fill: gradient.linear(rgb(24, 210, 182), rgb("3d98bb"), angle: 135deg),
height: 100%,
width: 100%
),
[
#align(
top+right,
[
#image("assets/typst.svg", width: 20%)
#v(-2mm)
#text("Compose Documents Faster.", size: 4mm, weight: "regular", fill: white, font: "Avenir Next LT Pro")
]
)
#align(
bottom,
[
#line(length: 100%, stroke: white)
// #v(-1cm)
#align(center,[
#text("This document was typset in", fill: white) #text("typst", font: "Linux Libertine", weight: "bold", fill: white)
])
]
)
]
) |
|
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/decorations/lstick%20rstick/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 0pt)
#import "/src/quill.typ": *
#quantum-circuit(
lstick("a"), gate($H$), rstick("b"), [\ ],
1, gate($H$), rstick($mat(a,b;c,d,)$, n: 3), [\ ],
lstick("asd", n: 2), gate($H$), 1, [\ ],
1, gate($T$), 1
)
#pagebreak()
#quantum-circuit(
lstick("single with brace", brace: "{"), gate($H$), rstick("b", brace: "]"), [\ ],
1, gate($H$), rstick($mat(a,b;c,d)$, n: 3, brace: none), [\ ],
lstick("nobrace", n: 2, brace: none), gate($H$), 1, [\ ],
1, gate($T$), 1
)
#pagebreak()
#quantum-circuit(
1, gate($H$), rstick($mat(a,b;c,d)$, n: 3, brace: "|"), [\ ],
lstick("[-brace", n: 2, brace: "["), gate($H$), 1, [\ ],
1, gate($T$), 1
)
#pagebreak()
#quantum-circuit(
lstick("very long lstick"), 1
)
#pagebreak()
#quantum-circuit(
1, rstick("very long rstick")
)
#pagebreak()
// lstick with equation numbering
#set math.equation(numbering: "1")
#quantum-circuit(
lstick($|0〉$, brace: "{"), 1
)
#pagebreak()
#quantum-circuit(
lstick($|0〉$, brace: "{", pad: 10pt), 1, rstick($|0〉$, brace: "}", pad: 10pt)
)
|
https://github.com/kdog3682/2024-typst | https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/chinese-typography-fix.typ | typst | #let sample = [“大家你好。”我想吃一点烦。“aaa?”Okay!”” ]
#let test() = {
let nihao = "你好"
let symbols = "。?;:【】{}()"
}
#let periodMark = box(
inset: (left: 1pt, right: 0.5pt),
circle(radius: 1.2pt, stroke: 0.3pt, fill: red)
)
#let exclamMark = box( inset: (left: 0.1em, right: 0.1em), text(size: 1.05em, font: "TeX Gyre Schola Math", [!]) )
#let questionMark = box( inset: (left: 0.1em, right: 0.1em), text(size: 1.05em, font: "TeX Gyre Schola Math", [?]) )
//#let questionMark = box(inset: (left: 0.2em, right: 0.2em), text(weight: "bold", size: 1.1em, font: "New Computer Modern Math", [?]))
#let func(doc) = {
show "。": periodMark
show "?": questionMark
show "!": exclamMark
set smartquote(enabled: false)
set text(lang: "zn", font: "Noto Serif CJK HK")
set par(leading: 0.85em)
show par: set block(spacing: 1.2em)
doc
}
#func(sample)
|
|
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/rod_cutting.typ | typst | #import "/config.typ": theme
#import "@preview/cetz:0.2.2"
#import "@preview/fontawesome:0.4.0"
#let n = 4
#cetz.canvas(length: 100%, {
import cetz.draw: *
line(
(0, 0), (1, 0),
name: "rod",
stroke: 4pt
)
for i in range(n) {
let width = (i+1)/n
line(
(rel: (0, -(16pt + 24pt * i)), to: "rod.start"),
(rel: (width, 0)),
name: "subrod",
stroke: none
)
group({
set-viewport((0, 0), (1cm, 1cm))
cetz.decorations.flat-brace(
"subrod.end",
"subrod.start",
name: "brace"
)
content("brace.content")[$p_#(i+1)$]
})
line(
(
(rel: (0, 16pt), to: "rod.start"),
"-|",
"subrod.end"
),
"subrod.end",
stroke: (dash: "dashed", paint: theme.fg_light),
name: "cut"
)
content("cut.start", angle: -90deg)[
#fontawesome.fa-cut()
]
}
}) |
|
https://github.com/cui-ke/semantic-tech | https://raw.githubusercontent.com/cui-ke/semantic-tech/main/courses/Semantic%20Web/Chapters/04-SPARQL_GeoSPARQL/SPARQL-exercises.typ | typst | #let title = [Exercises on SPARQL]
#align(left, text(17pt)[
*#title*
])
<NAME>
#let with-solutions = true
#let solution(s) = {
if with-solutions [
== Solution
#s
]
}
#import "@preview/diagraph:0.2.0": *
#let renderc(code) = render(code.text)
#let number-until-with(max-level, schema) = (..numbers) => {
if numbers.pos().len() <= max-level {
numbering(schema, ..numbers)
}
}
#set heading(numbering: number-until-with(1, "1.1.a."))
= Query execution
Given the following RDF graph
```
@prefix x: <http://example.org/> .
x:a x:friend_of x:b , x:c , x:d .
x:c x:friend_of x:d , x:e , x:f .
x:a x:friend_of [x:speaks "Japanese", "German", "French"] .
x:d x:friend_of x:c , x:a .
x:a x:studies [x:subject "Knowledge representation"; x:level "master"] .
x:c x:name "Jim" .
x:e x:speaks "French" ; x:speaks "German" .
x:f x:friend_of x:c ; x:speaks "German" ; x:studies [x:subject "History"] .
```
What woould be the answer to the following queries
Q1 :
```sparql
select ?x
where {
?x x:friend_of ?y . ?y x:studies ?z. ?z x:subject "Knowledge representation" . }
```
Q2: (be careful)
```
select ?x
where {
?x x:speaks ?a .
filter (?a != "German" )
}
```
#solution[
Q1 :
```
x:d
```
Q2 :
```
x:e
blank node (from x:a x:friend_of [x:speaks "Japanese", ...])
```
]
= Querying friend-of-a-friend (foaf) graphs.
The FOAF vocabulary contains (among others) the classes
#table(columns: (auto,auto,auto), stroke: 0.0pt,
[Agent],
[Person],
[Project],
[Organization],
[Group],
[Document], [OnlineAccount], [PersonalProfileDocument],
[Image])
and the properties
#table(columns: (auto,auto,auto), stroke: 0.0pt,
[name],
[title],
[img],
[depiction(depicts)],
[familyName],
[givenName],
[knows],
[based_near],
[age],
[made(maker)],
[primaryTopic(primaryTopicOf)],
[member],
[nick],
[mbox],
[homepage],
[weblog],
[openid],
[jabberID],
[mbox_sha1sum],
[interest],
[topic_interest],
[topic(page)],
[workplaceHomepage],
[workInfoHomepage],
[schoolHomepage],
[publications],
[currentProject],
[pastProject],
[account],
[accountName],
[accountServiceHomepage],
[tipjar],
[sha1],
[thumbnail],
[logo])
(The full names of these classes and properties is obtained by adding the prefix `foaf`, defined as `http://xmlns.com/foaf/0.1/`)
Use this vocabulary to express in SPARQL the following queries:
1. Find the persons who use "bob001" as nickname
2. Find the persons who know somebody based near `<http://geo.org/geneva>`
3. Find the persons who know somebody who doesn't know anybody
4. Find all the projects that have at least three (different) persons currently working on them
5. Find the persons who have a common interest but who have no common group (there is no group that has these two persons as members)
#solution[
```
@prefix foaf: <http://xmlns.com/foaf/0.1/>
select ?p
where {
?p a foaf:Person ; foaf:nickname "bob001"}
@prefix foaf: <http://xmlns.com/foaf/0.1/>
select ?p
where {
?p a foaf:Person ; foaf:knows ?somebody.
?somebody foaf:based_near <http://geo.org/geneva>}
@prefix foaf: <http://xmlns.com/foaf/0.1/>
select ?p
where {
?p a foaf:Person ; foaf:knows ?somebody.
filter not exists{?somebody foaf:knows ?q}
@prefix foaf: <http://xmlns.com/foaf/0.1/>
select ?p
where {
?p a foaf:Project .
?p1 foaf:currentProject ?p .
?p2 foaf:currentProject ?p .
?p3 foaf:currentProject ?p .
filter (?p1 != ?p2 && ?p1 != ?p3 && ?p2 != ?p3)
}
@prefix foaf: <http://xmlns.com/foaf/0.1/>
select ?p1 ?2
where {
?p1 a foaf:Person . ?p2 a foaf:Person .
?p1 foaf:interest ?i. ?p2 foaf:interest ?i .
filter not exists{?g a foaf:Group. ?g member ?p1 , ?p2 }
}
```
]
= Querying networks and lists
A road network is represented by the following RDFS schema:
```
:Node a rdfs:Class .
:Link a rdfs:Class .
:MainRoad rdfs:subClassOf :Link .
:SecondaryRoad rdfs:subClassOf :Link .
:Town rdfs:subClassOf :Node .
:Junction rdfs:subClassOf :Node .
:Route a rdfs:Class .
:from a rdf:Property ; rdfs:domain :Link ; rdfs:range :Node .
:to a rdf:Property ; rdfs:domain :Link ; rdfs:range :Node .
:name a rdf:Property ; rdfs:domain :Node ; rdfs:range xsd:string .
:length a rdf:Property ; rdfs:domain :Link ; rdfs:range xsd:number .
:speedLimit a rdf:Property ; rdfs:domain :Link ; rdfs:range xsd:number .
:route-nodes a rdf:Property ; rdfs:domain :Route ; rdfs:range rdf:List .
```
Schematically:
#renderc(
```
digraph {
rankdir=TB;
ll [label = "rdfs:List (of Links)", fontname="Helvetica"]
":MainRoad" -> ":Link" [label = "subclass"]
":SecondaryRoad" -> ":Link" [label = "subclass"]
":Town" -> ":Node" [label = "subclass"]
":Junction" -> ":Node" [label = "subclass"]
":Link" -> ":Node" [label = "from"]
":Link" -> ":Node" [label = "to"]
":Link" -> "xsd:number" [label = "length"]
":Node" -> "xsd:string" [label = "name"]
":Route" -> ll [label = "route-nodes"]
ll -> ":Link" [style = "dashed"]
}
```
)
Sample data:
```
# sample data
@prefix : <http://unige.ch/rdf> .
:Geneva a :Town . :Lausanne a :Town ; :name "Lausanne"@fr.
:Sion a :Town . :Fribourg a :Town . :Zurich a :Town .
:r1 a :MainRoad ; :from :Geneva ; :to :Lausanne ; :length 58 .
:r2 a :MainRoad ; :from :Fribourg ; :to :Lausanne ; :length 78 .
:r3 a :MainRoad ; :from :Zurich ; :to :Fribourg ; :length 78 .
:r4 a :SecondaryRoad ; :to :Geneva ; :from :Lausanne ; :length 77 .
:j1 a :Junction .
:r66 a :Route ; :route-nodes (:r3 :r2 :r4) .
:r77 a :Route ; :route-nodes ([:from :Sion ; :to :j1] [:from :j1 ; :to :Zurich]) .
```
1. Write SPARQL queries to answer the following questions on this graph, when it is possible
+ find all the towns that can be reached from the node :Zurich by following at most three links (in the from $->$ to direction) (you can use path expressions)
+ find all the towns that can be reached from the node :Zurich (you must use path expressions)
+ find all the towns that cannot be reached from :Zurich
+ find the towns that can be reached from :Zurich by following only main roads
+ what is the total length of route "r66"?
+ find routes whose nodes are all towns (i.e. there are no nodes that are not towns)
+ find the towns that can be reached from :Zurcih by following a route that uses only main roads
*Remark.* To check if a condition holds find the entities that do not satisfy it
#solution[
```
# towns reachable from :Zurich in 1, 2, or 3 steps (links)
prefix : <http://unige.ch/rdf>
select distinct ?t where {
:Zurich ^:from/:to/(^:from/:to)?/(^:from/:to)? ?t
}
# towns reachable from :Zurich
prefix : <http://unige.ch/rdf>
select distinct ?t where {
:Zurich (^:from/:to)* ?t
}
# towns not reachable from :Zurich
prefix : <http://unige.ch/rdf>
select distinct ?t where {
{?t a :Town} minus
{:Zurich (^:from/:to)* ?t}
}
# towns that can be reached from :Zurich by following only main roads
# cannot be expressed in SPARQL
# would require complex path expression of the form. Something like
# {:Zurich (^:from/[a :MainRoad]/:to)* ?t}
prefix : <http://unige.ch/rdf>
select distinct ?t where {
:Zurich (^:from/:to)* ?m
}
# length of route "r66"
prefix : <http://unige.ch/rdf>
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
select (sum(?lng) as ?s) where {
:r66 :route-nodes/rdf:rest*/rdf:first/:length ?lng .
}
# routes whose nodes are all towns (i.e. there are no nodes that are not towns)
prefix : <http://unige.ch/rdf>
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
select ?r where {
?r a :Route .
filter not exists{?r :route-nodes/rdf:rest*/rdf:first/(:from|:to) ?node.
filter not exists {?node a :Town}} .
}
# towns that can be reached from :Zurcih
# by following a route that uses only main roads
prefix : <http://unige.ch/rdf>
prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
select ?r ?t ?ll where {
?r a :Route .
?r :route-nodes/rdf:first/:from :Zurich .
?r :route-nodes/rdf:rest* ?last_element .
?last_element rdf:rest rdf:nil; # make sure it's the last elt.
rdf:first/:to ?t .
filter not exists{?r :route-nodes/rdf:rest*/rdf:first ?link.
filter not exists {?link a :MainRoad}} .
}
```
]
= Linear algebra with SPARQL
In a RDF graph a matrix celle is represented by a node with 3 properties: `r` (row number), `c` (column number), `v` (value). A matrix is represented by a node connected to the matrix cells through the a `cell` property. For example, the matrix $M=mat(1, -1; 6, -8)$ is represented as
```
:M1 :cell
[:r 1; :c 1; :v 1], [:r 1; :c 2; :v -1],
[:r 2; :c 1; :v 6], [:r 2; :c 2; :v -8],
```
Write SPARQL queries to
1. extract the second column of a matrix $A$
2. computes the trace of a matrix $A$ (the sum of the elements on the diagonal (where the row and column numbers are equal))
3. compute the scalar product $A_(i dot) * B_(dot j)$ of row $i$ of $A$ and column $j$ of $B$, $ A_(i dot) * B_(dot j) =^(text("def")) sum_(k=1)^n A_(i,k) B_(k,j) $ ($A$ and $B$ must be compatible, i.e. if $A$ has $n$ columns then $B$ must have $n$ rows)
4. compute the matrix product $C=A*B$ of two compatible matrices $A$ and $B$. $ C_(i,j) =^(text("def")) A_(i dot) * B_(dot j) $
== Test data:
```
@prefix : <http://unige.ch/rdf> .
:M1 :cell
[:r 1; :c 1; :v 1], [:r 1; :c 2; :v 0], [:r 1; :c 3; :v 0],
[:r 2; :c 1; :v 0], [:r 2; :c 2; :v 1], [:r 2; :c 3; :v 0],
[:r 3; :c 1; :v 0], [:r 3; :c 2; :v 0], [:r 3; :c 3; :v 1].
:M2 :cell
[:r 1; :c 1; :v 1], [:r 1; :c 2; :v 2], [:r 1; :c 3; :v 3],
[:r 2; :c 1; :v 4], [:r 2; :c 2; :v 5], [:r 2; :c 3; :v 6],
[:r 3; :c 1; :v 7], [:r 3; :c 2; :v 8], [:r 3; :c 3; :v 9].
```
#solution[
```
# 1. column 2 of A
prefix : <http://unige.ch/rdf>
select ?val
where {:A :cell [:r ?r ; :c 2 ; :v ?val] .
}
order by ?r
# 2. trace of A
prefix : <http://unige.ch/rdf>
select (sum(?va) as ?trace)
where {:A :cell [:r ?n ; :c ?n ; :v ?va] .
}
# 3. Row iii of A scalar colum jjj of B (two integer literals)
@prefix : <http://unige.ch/rdf>
select (sum(?va * ?vb) as ?scal)
where {:A :cell [ :r iii ; :c :n ; :v ?va ].
:B :cell [ :r ?n ; :c jjj ; :v ?vb ].
}
# 4. Matrix product of A and B
prefix : <http://unige.ch/rdf>
select ?rnum ?cnum (sum(?va * ?vb) as ?scal)
where {:A :cell [:r ?rnum ; :c 1] . # to get all the row numbers of A
:B :cell [:r 1 ; :c ?cnum ]. # to get all the column numbers of B
:A :cell [ :r ?rnum ; :c ?n ; :v ?va ].
:B :cell [ :r ?n ; :c ?cnum ; :v ?vb ].
}
group by ?rnum ?cnum
order by ?rnum ?cnum
```
] |
|
https://github.com/AugustinWinther/codedis | https://raw.githubusercontent.com/AugustinWinther/codedis/main/lib.typ | typst | MIT License | #let code(
code,
lang: "py",
stroke: luma(170), // Stroke color
fill-1: luma(250), // First line block fill
fill-2: luma(240), // Second line block fill
) = {
// Change how raw.line looks
show raw.line: it => {
// Define line start and end numbers
let start = 1
let end = it.count
// Calculates where to have block strokes given line number
let get-stroke(line) = {
if line == start {
return (top: stroke + 1pt, x: stroke + 1pt)
} else if line == end {
return (bottom: stroke + 1pt, x: stroke + 1pt)
} else {
return (x: stroke + 1pt)
}
}
// Calculates block radius given line number
let get-radius(line) = {
if line == start {
return (top: 1em)
} else if line == end {
return (bottom: 1em)
} else {
return (0em)
}
}
// Calculates fill given line number
let get-fill(line) = {
if calc.rem(line, 2) == 0 {
return fill-2
} else {
return fill-1
}
}
// Line block
let line = it.number
block(
breakable: false,
height: 1.7em,
width: 100%,
inset: (x:0.8em, top:0.4em),
fill: get-fill(line),
radius: get-radius(line),
stroke: get-stroke(line),
spacing: 0em,
// Actual line of code with height adjustment for centering it
align(left)[#text(size: 9pt)[#it]]
)
// Remove spacing between line blocks
if line != end {v(-3.2em)} else {v(1em)}
}
raw(code, lang: lang)
} |
https://github.com/Joelius300/hslu-typst-template | https://raw.githubusercontent.com/Joelius300/hslu-typst-template/main/chapters/00_abstract.typ | typst | MIT License | #import "@preview/big-todo:0.2.0": todo
#import "../template.typ": eq
Abstract wird hier als Text geschrieben und kann auch referenzieren @noauthor_example_nodate.
Und eq etc. muss importiert werden.
#eq($2^999 approx infinity$, [reee])
#todo("Abstract schreiben")
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/recourses-2/quiz-1-2023-wed.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
title: "Quiz #1 (Spring-Summer 2024, Wednesday)",
authors: ((
name: "memset0",
email: "https://mem.ac/",
id: [_<EMAIL>_],
),),
semester: "Spring-Summer 2024",
date: "April 10, 2024",
)
#let int = math.integral
#let divider = [#v(15em)$ "" $]
*Problem 1.* 已知直线 $L:space display(cases(x+2y+z=3, 2x-3y+9z=1))$ 与平面 $pi:space x+y+2z=2$ 之间的关系为
#table(stroke: 0pt, columns: (1fr, 1fr, 1fr), inset: 0.6em, [(A) 垂直], [(B) 斜交], [(C) $L$ 在 $pi$ 上], [(D) 平行但 $L$ 不在 $pi$ 上], [(E) 其他选项均不合题意])
#divider
*Problem 2.* 设空间四个点 $P_1 (1,0,1),space P_2 (0,-1,2), space P_3 (1,a,-2),space P_4 (-1,b,0)$。则下列陈述正确的是:
#table(stroke: 0pt, columns: (1fr), inset: 0.6em, [(A) 无论 $a,b$ 取何值,$P_1,P_2,P_3,P_4$ 四点均不共线], [(B) 若 $Delta P_1 P_2 P_3$ 面积为 $display(3/2 sqrt(6))$,则 $a=display(3/2)$], [(C) 若 $P_1,P_2,P_3,P_4$ 四点共面,则向量 $arrow(P_1 P_2) parallel arrow(P_3 P_4)$], [(D) 若以 $P_1,P_2,P_3,P_4$ 为顶点的四面体体积为 $1$,则 $a=b+2$], [(E) 其他选项均不合题意])
#divider
*Problem 3.* 设幂级数 $display(sum_(i=1)^(+oo) a_n (x-2)^n)$ 的收敛半径 $r=1$,则级数 $display(sum_(n=1)^(+oo) (-1)^n 2^n a_n)$
#table(stroke: 0pt, columns: (1fr, 1fr, 1fr), [(A) 绝对收敛], [(B) 条件收敛], [(C) 发散], [(D) 敛散性无法确定], [(E) 其他选项均不合题意])
#divider
*Problem 4.* 设 ${u_n}$ 是实数列,则下列陈述正确的是
#table(stroke: 0pt, columns: (1fr), inset: 0.6em,
[(A) 若 $display(sum_(n=1)^(+oo)) (u_(2n-1) - u_(2n))$ 收敛,则 $display(sum_(n=1)^(+oo)) u_n$ 收敛],
[(B) 若 $display(sum_(n=1)^(+oo)) u_n$ 收敛,则 $display(sum_(n=1)^(+oo)) (u_(2n-1) - u_(2n))$ 收敛],
[(C) 若 $display(sum_(n=1)^(+oo)) u_n$ 收敛,则 $display(sum_(n=1)^(+oo)) (u_(2n-1) + u_(2n))$ 收敛],
[(D) 若 $display(sum_(n=1)^(+oo)) (u_(2n-1) + u_(2n))$ 收敛,则 $display(sum_(n=1)^(+oo)) u_n$ 收敛],
[(E) 其他选项均不合题意]
)
#divider
*Problem 5.* 设 $f(x) = display(cases(x\,quad &0<=x<=display(1/2), 2-2x\,quad & display(1/2) <= x <= 1))$,$S(x) = display((a_0)/2 + sum_(n=1)^(+oo) a_n cos n pi x space (x in RR))$,其中 $a_n = 2 display(int_0^1 f(x) cos n pi x dif x space (n=1,2,dots.c))$,则 $S(display(-5/2))$ 和 $S(-3)$ 的值分别为?
#divider
*Problem 6.* 级数 $display(sum_(n=1)^(+oo) (sin n alpha + (-1)^n n)/(n^2)) space (alpha in RR)$ 的敛散性为:
#table(stroke: 0pt, columns: (1fr, 1fr, 1fr), inset: 0.6em, [(A) 绝对收敛], [(B) 条件收敛], [(C) 发散], [(D) 敛散性与 $alpha$ 选择有关], [(E) 其他选项均不合题意])
#divider
*Problem 7.* 设 $alpha$ 是常实数,已知 $display(sum_(n=1)^(+oo) (-1)^n sqrt(n) sin (1/(n^alpha)))$ 绝对收敛,$display(sum_(n=1)^(+oo) ((-1)^(n-1))/(n^(2-a)))$ 条件收敛,则常数 $a$ 的取值范围是?
#divider
*Problem 8.* 已知幂级数 $display(sum_(n=0)^(+oo) a_n x^n)$ 的和函数为 $ln(2+x)$,求 $display(sum_(n=1)^(+oo) n a_(2n))$。
#divider
*Problem 9.* 在平行四边形 $A B C D$ 中,向量 $arrow(A C) = {1, 2, 4};space arrow(B D) = {-3, 0, 2}$,求 $A B C D$ 的面积 $S$。
#divider
*Problem 10.* 下列陈述错误的是:
#table(stroke: 0pt, columns: (1fr), inset: 0.6em,
[(A) 若正项级数 $display(sum_(n=1)^(+oo)) a_n$ 收敛,则级数 $display(sum_(n=1)^(+oo)) display((1-2/n)^n a_n)$ 也收敛],
[(B) 正数列 ${a_n}$ 单调递减,且 $display(sum_(n=1)^(+oo)) (-1)^(n-1) a_n$ 发散,则 $display(sum_(n=1)^(+oo) (1/(1+a_n))^n)$ 发散],
[(C) 若级数 $display(sum_(n=1)^(+oo)) a_n$ 收敛,则级数 $display(sum_(n=1)^(+oo)) a_n^3$ 也收敛],
[(D) 若正项级数 $display(sum_(n=1)^(+oo)) a_n$ 收敛,则 $a_n = o(display(1/n)) space (n->+oo)$],
[(E) 其他选项均不合题意],
) |
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/domace.typ | typst | = Domače naloge
#set heading(offset: 1)
#include "domace_seznam.typ"
#show outline: set heading(level: 2)
#include "domace_01.typ"
#include "domace_02.typ"
#include "domace_03.typ"
#set heading(offset: 0)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/game-theoryst/0.1.0/doc/gallery/mix-ex.typ | typst | Apache License 2.0 | #import "../../src/lib.typ": *
#set page(
width: auto,
height: auto,
margin: 0.25em
)
#nfg(
players: ("Chet", "North"),
s1: ([$F$], [$G$], [$H$]),
s2: ([$X$], [$Y$]),
mixings: (vmix: ($q$, $1-q$), hmix: ($p$, [], $1-p$)),
[$7,3$], [$2,4$],
[$5,2$], [$6,1$],
[$6,1$], [$5,4$]
) |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/packages/typst.node/__test__/inputs/post1.typ | typst | Apache License 2.0 | #set document(title: "Post 1")
= This is Post 1
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/lib/angle.typ | typst | Apache License 2.0 | #import "/src/drawable.typ"
#import "/src/styles.typ"
#import "/src/vector.typ"
#import "/src/util.typ"
#import "/src/coordinate.typ"
#import "/src/anchor.typ" as anchor_
#import "/src/draw.typ"
// Angle default-style
#let default-style = (
fill: none,
stroke: auto,
radius: .5,
label-radius: 50%,
mark: auto,
)
/// Draw an angle between `a` and `b` through origin `origin`
///
/// #example(```
/// line((0,0), (1,1.5), name: "a")
/// line((0,0), (2,-1), name: "b")
///
/// // Draw an angle between the two lines
/// cetz.angle.angle("a.start", "a.end", "b.end", label: $ alpha $,
/// mark: (end: ">"), radius: 1.5)
/// cetz.angle.angle("a.start", "b.end", "a.end", label: $ alpha' $,
/// radius: 50%, inner: false)
/// ```)
///
/// *Style Root:* `angle`
///
/// *Style Keys:*
/// #show-parameter-block("radius", ("number"), [
/// The radius of the angles arc. If of type `ratio`, it is relative to the smaller distance of either origin to a or origin to b.], default: .5)
/// #show-parameter-block("label-radius", ("number", "ratio"), [
/// The radius of the angles label origin. If of type `ratio`, it is relative to `radius`.], default: 50%)
///
/// *Anchors*
/// / `"a"`: Point a
/// / `"b"`: Point b
/// / `"origin"`: Origin
/// / `"label"`: Label center
/// / `"start"`: Arc start
/// / `"end"`: Arc end
///
/// - origin (coordinate): Angle origin
/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
/// - inner (bool): Draw the smaller (inner) angle if true, otherwise the outer angle gets drawn.
/// - label (none,content,function): Draw a label at the angles "label" anchor.
/// If label is a function, it gets the angle value passed as argument. The function must
/// be of the format `angle => content`.
/// - name (none,string): Element name, used for querying anchors.
/// - ..style (style): Style key-value pairs.
#let angle(
origin,
a,
b,
inner: true,
label: none,
name: none,
..style
) = draw.group(name: name, ctx => {
let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
let (ctx, origin) = coordinate.resolve(ctx, origin)
let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
assert(origin.at(2) == a.at(2) and a.at(2) == b.at(2),
message: "Angle z coordinates of all three points must be equal")
let (s, e, ss) = {
let s = vector.angle2(origin, a)
if s < 0deg { s += 360deg }
let e = vector.angle2(origin, b)
if e < 0deg { e += 360deg }
if s > e {
(s, e) = (e, s)
}
if inner == true {
let d = vector.angle(a, origin, b)
if e - s > 180deg {
(s, e) = (e, e + d)
} else {
(s, e) = (s, s + d)
}
} else if inner == false {
if e - s < 180deg {
let d = 360deg - vector.angle(a, origin, b)
(s, e) = (e, e + d)
}
}
(s, e, (s + e) / 2)
}
// Radius can be relative to the min-distance between origin-a and origin-b
if type(style.radius) == ratio {
style.radius = style.radius * calc.min(vector.dist(origin, a), vector.dist(origin, b)) / 100%
}
let (r, _) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
// Label radius can be relative to radius
if type(style.label-radius) == ratio {
style.label-radius = style.label-radius * style.radius / 100%
}
let (ra, _) = util.resolve-radius(style.label-radius).map(util.resolve-number.with(ctx))
let label-pt = vector.add(origin, (calc.cos(ss) * ra, calc.sin(ss) * ra, 0))
let start-pt = vector.add(origin, (calc.cos(s) * r, calc.sin(s) * r, 0))
let end-pt = vector.add(origin, (calc.cos(e) * r, calc.sin(e) * r, 0))
draw.anchor("origin", origin)
draw.anchor("label", label-pt)
draw.anchor("start", start-pt)
draw.anchor("end", end-pt)
draw.anchor("a", a)
draw.anchor("b", b)
if s != e {
if style.fill != none {
draw.arc(origin, start: s, stop: e, anchor: "origin",
name: "arc", ..style, radius: r, mode: "PIE", mark: none, stroke: none)
}
if style.stroke != none {
draw.arc(origin, start: s, stop: e, anchor: "origin",
name: "arc", ..style, radius: r, fill: none)
}
}
let label = if type(label) == function { label(e - s) } else { label }
if label != none {
draw.content(label-pt, label)
}
})
/// Draw a right angle between `a` and `b` through origin `origin`
///
/// #example(```
/// line((0,0), (1,2), name: "a")
/// line((0,0), (2,-1), name: "b")
///
/// // Draw an angle between the two lines
/// cetz.angle.right-angle("a.start", "a.end", "b.end",
/// radius: 1.5)
/// ```)
///
/// *Style Root:* `angle`
///
/// *Style Keys:*
/// #show-parameter-block("radius", ("number"), [
/// The radius of the angles arc. If of type `ratio`, it is relative to the smaller distance of either origin to a or origin to b.], default: .5)
/// #show-parameter-block("label-radius", ("number", "ratio"), [
/// The radius of the angles label origin. If of type `ratio`, it is relative to the distance between `origin` and the angle corner.], default: 50%)
///
/// *Anchors*
/// / `"a"`: Point a
/// / `"b"`: Point b
/// / `"origin"`: Origin
/// / `"corner"`: Angle corner
/// / `"label"`: Label center
///
/// - origin (coordinate): Angle origin
/// - a (coordinate): Coordinate of side `a`, containing an angle between `origin` and `b`.
/// - b (coordinate): Coordinate of side `b`, containing an angle between `origin` and `a`.
/// - label (none,content): Draw a label at the angles "label" anchor.
/// - name (none,string): Element name, used for querying anchors.
/// - ..style (style): Style key-value pairs.
#let right-angle(
origin,
a,
b,
label: "•",
name: none,
..style
) = draw.group(name: name, ctx => {
let style = styles.resolve(ctx.style, merge: style.named(), base: default-style, root: "angle")
let (ctx, origin) = coordinate.resolve(ctx, origin)
let (ctx, a, b) = coordinate.resolve(ctx, a, b, update: false)
let vo = origin; let va = a; let vb = b
// Radius can be relative to the min-distance between origin-a and origin-b
if type(style.radius) == ratio {
style.radius = style.radius * calc.min(vector.dist(vo, va), vector.dist(vo, vb)) / 100%
}
let (r, _) = util.resolve-radius(style.radius).map(util.resolve-number.with(ctx))
let va = vector.add(vo, vector.scale(vector.norm(vector.sub(va, vo)), r))
let vb = vector.add(vo, vector.scale(vector.norm(vector.sub(vb, vo)), r))
let angle-b = vector.angle2(vo, vb)
let vm = vector.add(va, (calc.cos(angle-b) * r, calc.sin(angle-b) * r, 0))
// Label radius can be relative to the distance between origin and the
// angle corner
if type(style.label-radius) == ratio {
style.label-radius = style.label-radius * vector.dist(vm, vo) / 100%
}
let (ra, _) = util.resolve-radius(style.label-radius).map(util.resolve-number.with(ctx))
if style.fill != none {
draw.line(vo, va, vm, vb, close: true, stroke: none, fill: style.fill)
}
draw.line(va, vm, vb, ..style, fill: none)
let label-pt = vector.scale(vector.norm(vector.sub(vm, vo)), ra)
if label != none {
draw.content(label-pt, label)
}
draw.anchor("a", a)
draw.anchor("b", b)
draw.anchor("origin", origin)
draw.anchor("corner", vm)
draw.anchor("label", label-pt)
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.