repo
stringlengths 27
90
| file
stringlengths 57
176
| language
stringclasses 2
values | license
stringclasses 13
values | content
stringlengths 25
180k
|
---|---|---|---|---|
https://github.com/iceghost/resume | https://raw.githubusercontent.com/iceghost/resume/main/5-projects/4-monoticity.typ | typst | === Monotonicity Table Maker
#place(right + top)[Sep 2020]
/ Links: #link("https://iceghost.github.io/ve-bbt")[Demo]
#sym.dot.c #link("https://github.com/iceghost/ve-bbt")[Source].
This tool parses simple monotonicity table construction language and
generates MathJax/LaTeX code. This saves a lot of time spent making those
tables by hand.
_Result_: My underclassmen and friends used and liked it.
This project was my first _usable_ software product. I learned functional
programming and its principles, such as pure functions and side effects. This
project helped me improve my programming skills and mindset.
|
|
https://github.com/lkndl/typst-bioinfo-thesis | https://raw.githubusercontent.com/lkndl/typst-bioinfo-thesis/main/README.md | markdown | # typst-bioinfo-thesis
This is a [typst](https://typst.app/) thesis template with front matter for TUM+LMU [bioinformatics](https://www.cit.tum.de/cit/studium/studiengaenge/master-bioinformatik/abschlussarbeit/#c2494) and TUM [informatics](https://www.cit.tum.de/cit/studium/studierende/abschlussarbeit-abschluss/informatik/#c4295). Therefore, it generally supports English and German as main document languages. It comes with ready-to-use outlines, configurable page numbers adapting to front and back matter, as well as flexible headers that can imitate `scrbook`. I also implemented `sidecap` and a basic `wrapfig` equivalent.
Although totally workable, this template is somewhat under development - just as Typst is. If you find a bug, please feel free to open an issue!
To get started, edit `main.typ` or make a new minimal `thesis.typ`:
```rs
#import "modules/template.typ": *
#show: doc.with(
title: [all beginnings are hard],
name: [silly old me])
= introduction
...
```
---
The TUM informatics and bioinformatics cover pages:
![tum cover pages](images/screen_00.png)
Table of contents with numbering up to level 2 headings, well-aligned fill characters and roman page numbers for the appendix:
![a dummy table of contents](images/screen_01.png)
![overkill header and wrap figure](images/screen_03.png "an overkill left-hand page header and a wrapfig")
![example header and caption](images/screen_02.png "right-hand page header with section info")
Defining a figure title for the list-of-figures is now less hacky:
```rs
#figure(
image("/images/dingos.jpg", width: 100%),
caption: flex-caption(
[Another example full-width image],
[. Consumers are generally unaware that ...]),
) <dingos>
``````
![list of figures](images/screen_04.png) |
|
https://github.com/smorad/um_cisc_7026 | https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_3_neural_networks.typ | typst | #import "@preview/polylux:0.3.1": *
#import themes.university: *
#import "@preview/cetz:0.2.2": canvas, draw, plot
#import "common.typ": *
// TODO: Missing x^2 term when we show polynomial+multivariate example (not 2^3, should be 3^2 + 1)
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#let la = $angle.l$
#let ra = $angle.r$
#let redm(x) = {
text(fill: color.red, $#x$)
}
// TODO: Deeper neural networks are more efficient
// FUTURE TODO: Label design matrix as X bar instead of X_D in linear regression lectures
// FUTURE TODO: Should not waste m/n in linear regression, use c for count and d_x, d_y
// TODO: Fix nn image indices
// TODO: Implement XOR is transposed
// TODO: is xor network actually wide?
// TODO: Handle subscripts for input dim rather than sample
// TODO: Emphasize importance of very deep/wide nn
#let argmin_plot = canvas(length: 1cm, {
plot.plot(size: (8, 4),
x-tick-step: 1,
y-tick-step: 2,
{
plot.add(
domain: (-2, 2),
x => calc.pow(1 + x, 2),
label: $ (x + 1)^2 $
)
})
})
#show: university-theme.with(
aspect-ratio: "16-9",
short-title: "CISC 7026: Introduction to Deep Learning",
short-author: "<NAME>",
short-date: "Lecture 1: Introduction"
)
#title-slide(
title: [Neural Networks],
subtitle: "CISC 7026: Introduction to Deep Learning",
institution-name: "University of Macau",
//logo: image("logo.jpg", width: 25%)
)
#slide(title: [Notation Change])[
*Notation change:* Previously $x_i, y_i$ referred to data $i$ #pause
Moving forward, I will differentiate between *data* indices $x_[i]$ and other indices $x_i$ #pause
$ bold(X)_D = vec(bold(x)_[1], dots.v, bold(x)_[n]) = mat(x_([1], 1), x_([1], 2), dots; dots.v, dots.v, dots.v; x_([n], 1), x_([n], 2), dots) $ #pause
$ bold(x) = vec(x_1, x_2, dots.v), quad bold(X) = mat(x_(1,1), dots, x_(1, n); dots.v, dots.down, dots.v; x_(m, 1), dots, x_(m, n)) $
]
#let agenda(index: none) = {
let ag = (
[Review],
[Multivariate linear regression],
[Limitations of linear regression],
[History of neural networks],
[Biological neurons],
[Artificial neurons],
[Wide neural networks],
[Deep neural networks],
[Practical considerations]
)
for i in range(ag.len()){
if index == i {
enum.item(i + 1)[#text(weight: "bold", ag.at(i))]
} else {
enum.item(i + 1)[#ag.at(i)]
}
}
}
#slide(title: [Agenda])[#agenda(index: none)]
#slide(title: [Agenda])[#agenda(index: 0)]
#slide(title: [Review])[
Since you are very educated, we focused on how education affects life expectancy #pause
Studies show a causal effect of education on health #pause
- _The causal effects of education on health outcomes in the UK Biobank._ Davies et al. _Nature Human Behaviour_. #pause
- By staying in school, you are likely to live longer #pause
- Being rich also helps, but education alone has a *causal* relationship with life expectancy
]
#slide(title: [Review])[
*Task:* Given your education, predict your life expectancy #pause
$X in bb(R)_+:$ Years in school #pause
$Y in bb(R)_+:$ Age of death #pause
$Theta in bb(R)^2:$ Parameters #pause
$ f: X times Theta |-> Y $ #pause
*Approach:* Learn the parameters $theta$ such that
$ f(x, theta) = y; quad x in X, y in Y $
]
#slide(title: [Review])[
Started with a linear function $f$ #pause
#align(center, grid(
columns: 2,
align: center,
column-gutter: 2em,
$ f(x, bold(theta)) = f(x, vec(theta_1, theta_0)) = theta_1 x + theta_0 $,
cimage("figures/lecture_2/example_regression_graph.png", height: 50%)
)) #pause
Then, we derived the square error function #pause
$ "error"(f(x, bold(theta)), y) = (f(x, bold(theta)) - y)^2 $
]
#slide(title: [Review])[
We wrote the loss function for a single datapoint $x_[i], y_[i]$ using the square error
$ cal(L)(x_[i], y_[i], bold(theta)) = "error"(f(x_[i], bold(theta)), y_[i]) = (f(x_[i], bold(theta)) - y_[i])^2 $ #pause
But we wanted to learn a model over *all* the data, not a single datapoint #pause
We wanted to make *new* predictions, to *generalize* #pause
$ bold(x) = mat(x_[1], x_[2], dots, x_[n])^top, bold(y) = mat(y_[1], y_[2], dots, y_[n])^top $ #pause
$
cal(L)(bold(x), bold(y), bold(theta)) = sum_(i=1)^n "error"(f(x_[i], bold(theta)), y_[i]) = sum_(i=1)^n (f(x_[i], bold(theta)) - y_[i])^2
$
]
#slide(title: [Review])[
Our objective was to find the parameters that minimized the loss function over the dataset #pause
We introduced the $argmin$ operator #pause
#side-by-side[ $f(x) = (x + 1)^2$][#argmin_plot] #pause
$ argmin_x f(x) = -1 $
]
#slide(title: [Review])[
With the $argmin$ operator, we formally wrote our optimization objective #pause
$
#text(fill: color.red)[$argmin_bold(theta)$] cal(L)(bold(x), bold(y), bold(theta)) &= #text(fill: color.red)[$argmin_bold(theta)$] sum_(i=1)^n "error"(f(x_[i], bold(theta)), y_[i]) \ &= #text(fill: color.red)[$argmin_bold(theta)$] sum_(i=1)^n (f(x_[i], bold(theta)) - y_[i])^2
$
]
#slide(title: [Review])[
We defined the design matrix $bold(X)_D$ #pause
$ bold(X)_D = mat(bold(x), bold(1)) = mat(x_[1], 1; x_[2], 1; dots.v, dots.v; x_[n], 1) $ #pause
We use the design matrix to find an *analytical* solution to the optimization objective #pause
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $
]
#slide(title: [Review])[
With this analytical solution, we were able to learn a linear model #pause
#cimage("figures/lecture_2/linear_regression.png", height: 60%)
]
#slide(title: [Review])[
Then, we used a trick to extend linear regression to nonlinear models #pause
$ bold(X)_D = mat(x_[1], 1; x_[2], 1; dots.v, dots.v; x_[n], 1) => bold(X)_D = mat(log(1 + x_[1]), 1; log(1 + x_[2]), 1; dots.v, dots.v; log(1 + x_[n]), 1) $
]
#slide(title: [Review])[
We extended to polynomials, which are *universal function approximators* #pause
$ bold(X)_D = mat(x_[1], 1; x_[2], 1; dots.v, dots.v; x_[n], 1) => bold(X)_D = mat(
x_[1]^m, x_[1]^(m-1), dots, x_[1], 1;
x_[2]^m, x_[2]^(m-1), dots, x_[2], 1;
dots.v, dots.v, dots.down;
x_[n]^m, x_[n]^(m-1), dots, x_[n], 1
) $ #pause
$ f: X times Theta |-> bb(R) $ #pause
$ Theta in bb(R)^2 => Theta in bb(R)^(m+1) $
]
#slide(title: [Review])[
Finally, we discussed overfitting #pause
$ f(x, bold(theta)) = theta_m x^m + theta_(m - 1) x^(m - 1), dots, theta_1 x^1 + theta_0 $ #pause
#grid(
columns: 3,
row-gutter: 1em,
image("figures/lecture_2/polynomial_regression_n2.png"),
image("figures/lecture_2/polynomial_regression_n3.png"),
image("figures/lecture_2/polynomial_regression_n5.png"),
$ m = 2 $,
$ m = 3 $,
$ m = 5 $
)
]
#slide(title: [Review])[
We care about *generalization* in machine learning #pause
So we should always split our dataset into a training dataset and a testing dataset #pause
#cimage("figures/lecture_2/train_test_regression.png", height: 60%)
]
// 16:00 fast
#slide[#agenda(index: 0)]
#slide[#agenda(index: 1)]
#slide[
Last time, we assumed a single-input system #pause
Years of education: $X in bb(R)$ #pause
But sometimes we want to consider multiple input dimensions #pause
Years of education, BMI, GDP: $X in bb(R)^3$ #pause
We can solve these problems using linear regression too
]
#slide[
For multivariate problems, we will define the input dimension as $d_x$ #pause
$ bold(x) in X; quad X in bb(R)^(d_x) $ #pause
We will write the vectors as
$ bold(x)_[i] = vec(
x_([i], 1),
x_([i], 2),
dots.v,
x_([i], d_x)
) $ #pause
$x_([i], 1)$ refers to the first dimension of training data $i$
]
#slide[
The design matrix for a *multivariate* linear system is
$ bold(X)_D = mat(
x_([1], d_x), x_([1], d_x - 1), dots, x_([1], 1), 1;
x_([2], d_x), x_([2], d_x - 1), dots, x_([2], 1), 1;
dots.v, dots.v, dots.down, dots.v;
x_([n], d_x), x_([n], d_x - 1), dots, x_([n], 1), 1
) $ #pause
Remember $x_([n], d_x)$ refers to dimension $d_x$ of training data $n$ #pause
The solution is the same as before
$ bold(theta) = (bold(X)_D^top bold(X)_D )^(-1) bold(X)_D^top bold(y) $
]
// 22:00 fast
#slide(title: [Agenda])[
#agenda(index: 1)
]
#slide(title: [Agenda])[
#agenda(index: 2)
]
#slide(title: [Limitations of Linear Regression])[
Linear models are useful for certain problems #pause
+ Analytical solution #pause
+ Low data requirement #pause
Issues arise with other problems #pause
+ Poor scalability #pause
+ Polynomials do not generalize well
]
#slide(title: [Limitations of Linear Regression])[
Issues arise with other problems
+ *Poor scalability*
+ Polynomials do not generalize well
]
#slide(title: [Limitations of Linear Regression])[
So far, we have seen: #pause
#side-by-side[
One-dimensional polynomial functions
$ bold(X)_D = mat(
x_[1]^m, x_[1]^(m-1), dots, x_[1], 1;
x_[2]^m, x_[2]^(m-1), dots, x_[2], 1;
dots.v, dots.v, dots.down;
x_[n]^m, x_[n]^(m-1), dots, x_[n], 1
) $ #pause][
Multi-dimensional linear functions
$ bold(X)_D = mat(
x_([1], d_x), x_([1], d_x - 1), dots, 1;
x_([2], d_x), x_([2], d_x - 1), dots, 1;
dots.v, dots.v, dots.down, dots.v;
x_([n], d_x), x_([n], d_x - 1), dots, 1
) $ #pause
]
Combine them to create multi-dimensional polynomial functions #pause
]
#slide(title: [Limitations of Linear Regression])[
Let us do an example #pause
#side-by-side[*Task:* predict how many #text(fill: color.red)[#sym.suit.heart] a photo gets on social media][#cimage("figures/lecture_1/dog.png", height: 30%)] #pause
$ f: X times Theta |-> Y; quad X: "Image", quad Y: "Number of " #redm[$#sym.suit.heart$] $ #pause
$ X in bb(Z)_+^(256 times 256) = bb(Z)_+^(65536); quad Y in bb(Z)_+ $ #pause
Highly nonlinear task, use a polynomial with order $m=20$
]
#slide(title: [Limitations of Linear Regression])[
$ bold(X)_D = mat(bold(x)_(D, [1]), dots, bold(x)_(D, [n]))^top $ #pause
$ &bold(x)_(D, [i]) = \ &mat(
underbrace(x_([i], d_x)^m x_([i], d_x - 1)^m dots x_([i], 1)^m, (d_x => 1, x^m)),
underbrace(x_([i], d_x)^m x_([i], d_x - 1)^m dots x_([i], 2)^m, (d_x => 2, x^m)),
dots,
underbrace(x_([i], d_x)^(m-1) x_([i], d_x - 1)^(m-1) dots x_([i], 1)^m, (d_x => 1, x^(m-1))),
dots,
)
$
*Question:* How many columns in this matrix? #pause
*Hint:* $d_x = 2, m = 3$: $x^3 + y^3 + x^2 y + y^2 x + x y + x + y + 1$ #pause
*Answer:* $(d_x)^m = 65536^20 + 1 approx 10^96$
]
#slide(title: [Limitations of Linear Regression])[
How big is $10^96$? #pause
*Question:* How many atoms are there in the universe? #pause
*Answer:* $10^82$ #pause
There is not enough matter in the universe to represent one row #pause
#side-by-side[We cannot predict how many #text(fill: color.red)[#sym.suit.heart] the picture will get][#cimage("figures/lecture_1/dog.png", height: 30%)] #pause
Polynomial regression does not scale to large inputs
]
#slide(title: [Limitations of Linear Regression])[
Issues arise with other problems
+ *Poor scalability*
+ Polynomials do not generalize well
]
#slide(title: [Limitations of Linear Regression])[
Issues arise with other problems
+ Poor scalability
+ *Polynomials do not generalize well*
]
#slide(title: [Limitations of Linear Regression])[
What happens to polynomials outside of the support (dataset)? #pause
Take the limit of polynomials to see their behavior #pause
#side-by-side[$ lim_(x -> oo) theta_m x^m + theta_(m-1) x^(m-1) + dots $][Equation of a polynomial] #pause
#side-by-side[$ lim_(x -> oo) x^m (theta_m + theta_(m-1) / x + dots) $][Factor out $x^m$] #pause
#side-by-side[$ lim_(x -> oo) x^m dot lim_(x-> oo) (theta_m + theta_(m-1) / x + dots) $][Split the limit (limit of products)]
]
#slide(title: [Limitations of Linear Regression])[
#side-by-side[$ lim_(x -> oo) x^m dot lim_(x-> oo) (theta_m + theta_(m-1) / x + dots) $][Split the limit (limit of products)]
#side-by-side[$ (lim_(x -> oo) x^m) dot (theta_m + 0 + dots) $][Evaluate right limit] #pause
#side-by-side[$ theta_m lim_(x -> oo) x^m $][Rewrite] #pause
#side-by-side[$ theta_m lim_(x -> oo) x^m = oo $][If $theta_m > 0$] #pause
#side-by-side[$ theta_m lim_(x -> oo) x^m = -oo $][If $theta_m < 0$]
]
#slide(title: [Limitations of Linear Regression])[
Polynomials quickly tend towards $-oo, oo$ outside of the support #pause
$ f(x) = x^3-2x^2-x+2 $ #pause
#cimage("figures/lecture_3/polynomial_generalize.png", height: 50%) #pause
Remember, to predict new data we want our functions to generalize
]
#slide(title: [Limitations of Linear Regression])[
Linear regression has issues #pause
+ Poor scalability #pause
+ Polynomials do not generalize well
]
// 38:00 fast
#slide(title: [Limitations of Linear Regression])[
We can use neural networks as an alternative to linear regression #pause
Neural network benefits: #pause
+ Scale to large inputs #pause
+ Slightly better generalization #pause
Drawbacks: #pause
+ No analytical solution #pause
+ High data requirement
//#cimage("figures/lecture_1/timeline.svg", height: 50%)
]
// 40:00 fast
#slide(title: [Agenda])[#agenda(index: 2)]
#slide(title: [Agenda])[#agenda(index: 3)]
#slide(title: [History of Neural Networks])[
In 1939-1945, there was a World War #pause
Militaries invested funding for research, and invented the computer #pause
#cimage("figures/lecture_3/turing.jpg", height: 70%)
]
#slide(title: [History of Neural Networks])[
#side-by-side[Meanwhile, a neuroscientist and mathematician (McCullough and Pitts) were trying to understand the human brain][#cimage("figures/lecture_3/mccullough-pitts.png", height: 70%)] #pause
They designed the theory for the first neural network
]
#slide(title: [History of Neural Networks])[
Rosenblatt implemented this neural network theory on a computer a few years later #pause
#side-by-side[
At the time, computers were very slow and expensive
][#cimage("figures/lecture_3/original_nn.jpg", height: 70%)]
]
#slide(title: [History of Neural Networks])[
Through advances in theory and hardware, neural networks became slightly better #pause
#cimage("figures/lecture_1/timeline.svg", height: 40%) #pause
Around 2012, these improvements culminated in neural networks that perform like humans
]
#slide(title: [History of Neural Networks])[
So what is a neural network? #pause
It is a function, inspired by how the brain works #pause
$ f: X times Theta |-> Y $
]
#slide(title: [History of Neural Networks])[
Brains and neural networks rely on *neurons* #pause
*Brain:* Biological neurons $->$ Biological neural network #pause
*Computer:* Artificial neurons $->$ Artificial neural network #pause
First, let us review biological neurons #pause
*Note:* I am not a neuroscientist! I may make simplifications or errors with biology
]
#slide(title: [Agenda])[#agenda(index: 3)]
#slide(title: [Agenda])[#agenda(index: 4)]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
A simplified neuron consists of many parts
]
// 47:00 fast
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Neurons send messages based on messages received from other neurons
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Incoming electrical signals travel along dendrites
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
Electrical charges collect in the Soma (cell body)
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
The axon outputs an electrical signal to other neurons
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
The axon terminals will connect to dendrites of other neurons through a synapse
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/synapse.png", height: 60%)
The synapse converts electrical signal, to chemical signal, back to electrical signal #pause
Synaptic weight determines how well a signal crosses the gap
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
For our purposes, we can model the axon terminals, dendrites, and synapses to be one thing
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
The neuron takes many inputs, and produces a single output
]
#slide(title: [Biological Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg")
The neuron will only output a signal down the axon ("fire") at certain times
]
#slide(title: [Biological Neurons])[
How does a neuron decide to send an impulse ("fire")? #pause
#side-by-side[Incoming impulses (via dendrites) change the electric potential of the neuron][ #cimage("figures/lecture_3/bio_neuron_activation.png", height: 50%)] #pause
In a parallel circuit, we can sum voltages together #pause
Many active dendrites will add together and trigger an impulse
]
#slide(title: [Biological Neurons])[
#side-by-side[Pain triggers initial nerve impulse, starts a chain reaction into the brain][#cimage("figures/lecture_3/nervous-system.jpg")]
]
#slide(title: [Biological Neurons])[
#side-by-side[When the signal reaches the brain, we will think][#cimage("figures/lecture_3/nervous-system.jpg")]
]
#slide(title: [Biological Neurons])[
#side-by-side[After thinking, we will take action][#cimage("figures/lecture_3/nervous-system.jpg")]
]
// 57:00
#slide(title: [Agenda])[#agenda(index: 4)]
#slide(title: [Agenda])[#agenda(index: 5)]
#slide(title: [Artificial Neurons])[
#cimage("figures/lecture_3/neuron_anatomy.jpg", height: 50%) #pause
*Question:* How could we write a neuron as a function? $quad f: "___" |-> "___"$ #pause
*Answer*:
$ f: underbrace(bb(R)^(d_x), "Dendrite voltages") times underbrace(bb(R)^(d_x), "Synaptic weight") |-> underbrace(bb(R), "Axon voltage") $
]
#slide(title: [Artificial Neurons])[
Let us implement an artifical neuron as a function #pause
#side-by-side[#cimage("figures/lecture_3/neuron_anatomy.jpg")][
#only((2,3))[
Neuron has a structure of dendrites with synaptic weights
]
#only(3)[
$ f(
#redm[$vec(theta_1, theta_2, dots.v, theta_(d_x))$])
$
$ f(#redm[$bold(theta)$]) $
]
#only((4,5))[
Each incoming dendrite has some voltage potential
]
#only(5)[
$ f(#redm[$vec(x_(1), dots.v, x_(d_x))$], vec(theta_(1), dots.v, theta_(d_x)) ) $
$ f(#redm[$bold(x)$], bold(theta)) $
]
#only((6, 7))[
Voltage potentials sum together to give us the voltage in the cell body
]
#only(7)[
$ f(vec(x_(1), dots.v, x_(d_x)), vec(theta_(1), dots.v, theta_(d_x)) ) = #redm[$sum_(j=1)^(d_x) theta_j x_(j)$] $
$ f(bold(x), bold(theta)) = #redm[$bold(theta)^top bold(x)$] $
]
#only((8, 9, 10))[
The axon fires only if the voltage is over a threshold
]
#only((9, 10))[
$ sigma(x)= H(x) = #image("figures/lecture_3/heaviside.png", height: 30%) $
]
#only(10)[
$ f(vec(x_(1), dots.v, x_(n)), vec(theta_(1), dots.v, theta_(n)) ) = #redm[$sigma$] (sum_(j=1)^(d_x) theta_j x_(j) ) $
]
]
]
// 1:05
#slide(title: [Artificial Neurons])[
#side-by-side[Maybe we want to vary the activation threshold][#cimage("figures/lecture_3/bio_neuron_activation.png", height: 30%)][#image("figures/lecture_3/heaviside.png", height: 30%)] #pause
$ f(vec(#redm[$1$], x_(1), dots.v, x_(d_x)), vec(#redm[$theta_0$], theta_(1), dots.v, theta_(d_x)) ) = sigma(#redm[$theta_0$] + sum_(j=1)^(d_x) theta_j x_j) = sigma(sum_(#redm[$j=0$])^(d_x) theta_j x_j) $ #pause
$ overline(bold(x)) = vec(1, bold(x)), quad f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))) $
]
#slide(title: [Artificial Neurons])[
$ f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))) $ #pause
This is the artificial neuron! #pause
Let us write out the full equation for a neuron #pause
$ f(bold(x), bold(theta)) = sigma( theta_0 1 + theta_1 x_1 + dots + theta_(d_x) x_(d_x) ) $ #pause
*Question:* Does this look familiar to anyone? #pause
*Answer:* Inside $sigma$ is the multivariate linear model!
$ f(bold(x), bold(theta)) = theta_(d_x) x_(d_x) + theta_(d_x - 1) x_(d_x - 1) + dots + theta_0 1 $
]
#slide(title: [Artificial Neurons])[
We model a neuron using a linear model and activation function #pause
#side-by-side(gutter: 4em)[#cimage("figures/lecture_3/neuron_anatomy.jpg", height: 40%)
][
#cimage("figures/lecture_3/neuron.svg", height: 40%)]
$ f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))) $
]
#slide(title: [Artificial Neurons])[
$ f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))) $ #pause
Sometimes, we will write $bold(theta)$ as a bias and weight $b, bold(w)$ #pause
$ bold(theta) = vec(b, bold(w)); quad vec(theta_0, theta_1, dots.v, theta_(d_x)) = vec(b_" ", w_1, dots.v, w_(d_x)) $ #pause
$ f(bold(x), vec(b, bold(w))) = b + bold(w)^top bold(x) $
]
// 1:15
#focus-slide[Relax]
#slide(title: [Artificial Neurons])[
#side-by-side[#cimage("figures/lecture_3/neuron.svg") #pause][
#align(left)[
In machine learning, we represent functions #pause
What kinds of functions can our neuron represent? #pause
Let us consider some *boolean* functions #pause
Let us start with a logical AND function
]
]
]
#slide(title: [Artificial Neurons])[
#side-by-side[#cimage("figures/lecture_3/neuron.png")][
#align(left)[
*Review:* Activation function (Heaviside step function) #pause
#cimage("figures/lecture_3/heaviside.png", height: 50%)
$
sigma(x) = H(x) = cases(
1 "if" x > 0,
0 "if" x <= 0
)
$
]
]
]
#slide(title: [Artificial Neurons])[
Implement AND using an artificial neuron #pause
$ f(mat(x_1, x_2)^top, mat(theta_0, theta_1, theta_2)^top) = sigma(theta_0 1 + theta_1 x_1 + theta_2 x_2) $ #pause
$ bold(theta) = mat(theta_0, theta_1, theta_2)^top = mat(-1, 1, 1)^top $ #pause
#align(center, table(
columns: 5,
inset: 0.4em,
$x_1$, $x_2$, $y$, $f(x_1, x_2, bold(theta))$, $hat(y)$,
$0$, $0$, $0$, $sigma(-1 dot 1 + 1 dot 0 + 1 dot 0) = sigma(-1)$, $0$,
$0$, $1$, $0$, $sigma(-1 dot 1 + 1 dot 0 + 1 dot 1) = sigma(0)$, $0$,
$1$, $0$, $0$, $sigma(-1 dot 1 + 1 dot 1 + 1 dot 0) = sigma(0)$, $0$,
$1$, $1$, $1$, $sigma(-1 dot 1 + 1 dot 1 + 1 dot 1) = sigma(1)$, $1$
))
]
#slide(title: [Artificial Neurons])[
Implement OR using an artificial neuron #pause
$ f(mat(x_1, x_2)^top, mat(theta_0, theta_1, theta_2)^top) = sigma(theta_0 1 + theta_1 x_1 + theta_2 x_2) $ #pause
$ bold(theta) = mat(theta_0, theta_1, theta_2)^top = mat(0, 1, 1)^top $ #pause
#align(center, table(
columns: 5,
inset: 0.4em,
$x_1$, $x_2$, $y$, $f(x_1, x_2, bold(theta))$, $hat(y)$,
$0$, $0$, $0$, $sigma(1 dot 0 + 1 dot 0 + 1 dot 0) = sigma(0)$, $0$,
$0$, $1$, $0$, $sigma(1 dot 0 + 1 dot 1 + 1 dot 0) = sigma(1)$, $1$,
$1$, $0$, $1$, $sigma(1 dot 0 + 1 dot 0 + 1 dot 1) = sigma(1)$, $1$,
$1$, $1$, $1$, $sigma(1 dot 0 + 1 dot 1 + 1 dot 1) = sigma(2)$, $1$
))
]
// Approx 1:30
#slide(title: [Artificial Neurons])[
Implement XOR using an artificial neuron #pause
$ f(mat(x_1, x_2)^top, mat(theta_0, theta_1, theta_2)^top) = sigma(theta_0 1 + theta_1 x_2 + theta_2 x_2) $ #pause
$ bold(theta) = mat(theta_0, theta_1, theta_2)^top = mat(?, ?, ?)^top $ #pause
#align(center, table(
columns: 5,
inset: 0.4em,
$x_1$, $x_2$, $y$, $f(x_1, x_2, bold(theta))$, $hat(y)$,
$0$, $0$, $0$, [This is IMPOSSIBLE!], $$,
$0$, $1$, $1$, $$, $$,
$1$, $0$, $1$, $$, $$,
$1$, $1$, $0$, $$, $$
))
]
#slide(title: [Artificial Neurons])[
Why can't we represent XOR using a neuron? #pause
$ f(mat(x_1, x_2)^top, mat(theta_0, theta_1, theta_2)^top) = sigma(1 theta_0 + x_1 theta_1 + x_2 theta_2) $ #pause
We can only represent $sigma("linear function")$ #pause
XOR is not a linear combination of $x_1, x_2$! #pause
We want to represent any function, not just linear functions #pause
Let us think back to biology, maybe it has an answer
]
#slide(title: [Artificial Neurons])[
*Brain:* Biological neurons $->$ Biological neural network #pause
*Computer:* Artificial neurons $->$ Artificial neural network
]
#slide(title: [Artificial Neurons])[
Connect artificial neurons into a network
#grid(
columns: 2,
align: center,
column-gutter: 2em,
cimage("figures/lecture_3/neuron.svg", width: 80%), cimage("figures/lecture_3/deep_network.png", height: 75%),
[Neuron], [Neural Network]
)
]
#slide(title: [Artificial Neurons])[
#side-by-side[
#cimage("figures/lecture_3/deep_network.png", width: 100%)
][
Adding neurons in *parallel* creates a *wide* neural network #pause
Adding neurons in *series* creates a *deep* neural network #pause
Today's powerful neural networks are both *wide* and *deep*
]
]
#slide(title: [Agenda])[#agenda(index: 5)]
#slide(title: [Agenda])[#agenda(index: 6)]
#slide(title: [Wide Neural Networks])[
How do we express a *wide* neural network mathematically? #pause
A single neuron:
$ f: bb(R)^(d_x) times Theta |-> bb(R) $
$ Theta in bb(R)^(d_x + 1) $ #pause
$d_y$ neurons (wide):
$ f: bb(R)^(d_x) times Theta |-> bb(R)^(d_y) $
$ Theta in bb(R)^((d_x + 1) times d_y) $
]
#slide(title: [Wide Neural Networks])[
For a single neuron:
$ f(vec(x_1, dots.v, x_(d_x)), vec(theta_0, theta_1, dots.v, theta_(d_x)) ) = sigma(sum_(i=0)^(d_x) theta_i overline(x)_i) $ #pause
$ f(bold(x), bold(theta)) = sigma(b + bold(w)^top bold(x)) $
]
#slide[
// Must be m by n (m rows, n cols)
#text(size: 24pt)[
For a wide network:
$ f(vec(x_1, x_2, dots.v, x_(d_x)), mat(theta_(0,1), theta_(0,2), dots, theta_(0,d_y); theta_(1,1), theta_(1,2), dots, theta_(1, d_y); dots.v, dots.v, dots.down, dots.v; theta_(d_x, 1), theta_(d_x, 2), dots, theta_(d_x, d_y)) ) = vec(
sigma(sum_(i=0)^(d_x) theta_(i,1) overline(x)_i ),
sigma(sum_(i=0)^(d_x) theta_(i,2) overline(x)_i ),
dots.v,
sigma(sum_(i=0)^(d_x) theta_(i,d_y) overline(x)_i ),
)
$
$ f(bold(x), bold(theta)) =
sigma(bold(theta)^top overline(bold(x))); quad bold(theta)^top in bb(R)^( d_y times (d_x + 1) )
$ #pause
$
f(bold(x), vec(bold(b), bold(W))) = sigma( bold(b) + bold(W)^top bold(x) ); quad bold(b) in bb(R)^(d_y), bold(W) in bb(R)^( d_x times d_y )
$
]
]
#slide[#agenda(index: 6)]
#slide[#agenda(index: 7)]
#slide(title: [Deep Neural Networks])[
How do we express a *deep* neural network mathematically? #pause
A wide network and deep network have a similar function signature:
$ f: bb(R)^(d_x) times Theta |-> bb(R)^(d_y) $ #pause
But the parameters change!
Wide: $Theta in bb(R)^((d_x + 1) times d_y)$ #pause
Deep: $Theta in bb(R)^((d_x + 1) times d_h) times bb(R)^((d_h + 1) times d_h) times dots times bb(R)^((d_h + 1) times d_y)$ #pause
$ bold(theta) = mat(bold(theta)_1, bold(theta)_2, dots, bold(theta)_ell)^top = mat(bold(phi), bold(psi), dots, bold(xi))^top $
]
#slide(title: [Deep Neural Networks])[
A wide network:
$ f(bold(x), bold(theta)) = sigma(bold(theta)^top overline(bold(x))) $ #pause
A deep network has many internal functions
$ f_1(bold(x), bold(phi)) = sigma(bold(phi)^top overline(bold(x))) quad
f_2(bold(x), bold(psi)) = sigma(bold(psi)^top overline(bold(x))) quad
dots quad
f_(ell)(bold(x), bold(xi)) = sigma(bold(xi)^top overline(bold(x))) $ #pause
$ f(bold(x), bold(theta)) = f_(ell) (dots f_2(f_1(bold(x), bold(phi)), bold(psi)) dots bold(xi) ) $
]
#slide(title: [Deep Neural Networks])[
Written another way
$ bold(z)_1 = f_1(bold(x), bold(phi)) = sigma(bold(phi)^top overline(bold(x))) $ #pause
$ bold(z)_2 = f_2(bold(z_1), bold(psi)) = sigma(bold(psi)^top overline(bold(z))_1) $ #pause
$ dots.v $ #pause
$ bold(y) = f_(ell)(bold(x), bold(xi)) = sigma(bold(xi)^top overline(bold(z))_(ell - 1)) $
We call each function a *layer* #pause
A deep neural network is made of many layers
]
/*
#slide[
Implement XOR using a deep neural network #pause
$ f(x_1, x_2, bold(theta)) = sigma( & theta_(3, 0) \
+ & theta_(3, 1) quad dot quad sigma(theta_(1,0) + x_1 theta_(1,1) + x_2 theta_(1,2)) \
+ & theta_(3, 2) quad dot quad sigma(theta_(2,0) + x_1 theta_(2,1) + x_2 theta_(2,2))) $ #pause
$ bold(theta) = mat(
theta_(1,0), theta_(1,1), theta_(1,2);
theta_(2,0), theta_(2,1), theta_(2,2);
theta_(3,0), theta_(3,1), theta_(3,2)
) = mat(
-0.5, 1, 1;
-1.5, 1, 1;
-0.5, 1, -2
) $ #pause
]
*/
/*
#slide(title: [Deep Neural Networks])[
What functions can we represent using a deep neural network? #pause
Consider a one-dimensional arbitrary function $g(x) = y$ #pause
We can approximate $g$ using our neural network $f$ #pause
$ f(x_1, x_2, bold(theta)) = sigma( & theta_(3, 0) \
+ & theta_(3, 1) quad dot quad sigma(theta_(1,0) + x_1 theta_(1,1) + x_2 theta_(1,2)) \
+ & theta_(3, 2) quad dot quad sigma(theta_(2,0) + x_1 theta_(2,1) + x_2 theta_(2,2))) $
]
*/
#slide(title: [Deep Neural Networks])[
What functions can we represent using a deep neural network? #pause
*Proof Sketch:* Approximate a continuous function $g: bb(R) |-> bb(R)$ using a linear combination of Heaviside functions #pause
#only(2)[#cimage("figures/lecture_3/function_noapproximation.svg", height: 50%)]
#only((3,4))[#cimage("figures/lecture_3/function_approximation.svg", height: 50%)]
#only(4)[$exists (bold(theta) in bb(R)^(1 times d_h), bold(phi) in bb(R)^((d_h + 1) times d_1)) "such that" lim_(d_h |-> oo) [ bold(phi)^top sigma(overline(bold(theta)^top overline(x)))]$
]
]
#slide(title: [Deep Neural Networks])[
A deep neural network is a *universal function approximator* #pause
It can approximate *any* continuous function $g(x)$ to precision $epsilon$ #pause
$ | g(bold(x)) - f(bold(x), bold(theta)) | < epsilon $ #pause
Making the network deeper or wider decreases $epsilon$ #pause
#align(center)[#underline[Very powerful finding! The basis of deep learning.]] #pause
#side-by-side[*Task:* predict how many #text(fill: color.red)[#sym.suit.heart] a photo gets on social media][#cimage("figures/lecture_1/dog.png", height: 30%)]
]
#slide(title: [Agenda])[#agenda(index: 7)]
#slide(title: [Agenda])[#agenda(index: 8)]
#slide(title: [Practical Considerations])[
We call wide neural networks *perceptrons* #pause
We call deep neural networks *multi-layer perceptrons* (MLP) #pause
#cimage("figures/lecture_3/timeline.svg", width: 85%)
]
#slide(title: [Practical Considerations])[
*All* the models we examine in this course will use MLPs #pause
- Recurrent neural networks #pause
- Graph neural networks #pause
- Transformers #pause
- Chatbots #pause
It is very important to understand MLPs! #pause
I will explain them again very simply
]
#slide(title: [Practical Considerations])[
A *layer* is a linear operation and an activation function
$ f(bold(x), vec(bold(b), bold(W))) = sigma(bold(b) + bold(W)^top bold(x)) $
#side-by-side[Many layers makes a deep neural network][
#text(size: 22pt)[
$ bold(z)_1 &= f(bold(x), vec(bold(b)_1, bold(W)_1)) \
bold(z)_2 &= f(bold(z)_1, vec(bold(b)_2, bold(W)_2)) \ quad bold(y) &= f(bold(z)_2, vec(bold(b)_2, bold(W)_2)) $
]
]
]
#slide(title: [Practical Considerations])[
Let us create a wide neural network in colab! https://colab.research.google.com/drive/1bLtf3QY-yROIif_EoQSU1WS7svd0q8j7?usp=sharing
]
#slide(title: [Practical Considerations])[
#side-by-side(align: left + top)[
Linear regression: #pause
$+$ Analytical solution #pause
$+$ Low data requirement #pause
$-$ Poor scalability #pause
$-$ Poor polynomials generalization #pause
][
Neural networks: #pause
$-$ No analytical solution #pause
$-$ High data requirement #pause
$+$ Scale to large inputs #pause
$+$ Slightly better generalization #pause
]
Next time, we will find out how to train our neural network #pause
Unlike linear regression, finding $theta$ is much more difficult for neural networks
]
#slide[#agenda(index: none)]
#slide(title: [Conclusion])[
There might be a quiz next time #pause
Always bring paper and a pen #pause
You should be able to write a neural network layer mathematically #pause
You should also know the shapes of $bold(theta), bold(x), overline(bold(x)), bold(y)$
]
/*
#slide[
#text(size: 21pt)[
```python
import torch
from torch import nn
class MyNetwork(nn.Module):
def __init__(self):
super().__init__() # Required by pytorch
self.input_layer = nn.Linear(5, 3) # 3 neurons, 5 inputs each
self.output_layer = nn.Linear(3, 1) # 1 neuron with 3 inputs
def forward(self, x):
z = torch.heaviside(self.input_layer(x))
y = self.output_layer(z)
return y
```
]
]
#slide[
#text(size: 21pt)[
```python
import jax, equinox
from jax import numpy as jnp
from equinox import nn
class MyNetwork(equinox.Module):
input_layer: nn.Linear # Required by equinox
output_layer: nn.Linear
def __init__(self):
self.input_layer = nn.Linear(5, 3, key=jax.random.PRNGKey(0))
self.output_layer = nn.Linear(3, 1, key=jax.random.PRNGKey(1))
def __call__(self, x):
z = jnp.heaviside(self.input_layer(x))
y = self.output_layer(z)
return y
```
]
]
#slide[
#side-by-side[#cimage("figures/neuron.png", width: 80%)][#cimage("figures/heaviside.png", height: 50%)] #pause
*Question:* What kind of functions can we represent with our neuron? #pause
*Hint:* The neuron is linear regression with an activation function
]
#slide[
#side-by-side[#cimage("figures/neuron.png", width: 80%)][#cimage("figures/heaviside.png", height: 50%)] #pause
*Answer:* Linear functions with cutoff
]
#slide[
#side-by-side[#cimage("figures/neuron.png") #pause][
The output of the neuron depends on the activation function $sigma$
]
]
#slide[
#side-by-side[#cimage("figures/neuron.png") #pause][
*Question:* What functions can a single neuron represent?
*Hint:* Think back to linear regression #pause
*Answer:*
]
]
#slide[
#side-by-side[#cimage("figures/neuron.png") #pause][
Many biological neurons (brain) $->$ many artificial neurons (deep neural network)
]
]
*/
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-aspect-06.typ | typst | Other | // Size cannot be relative because we wouldn't know
// relative to which axis.
// Error: 15-18 expected length or auto, found ratio
#square(size: 50%)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/smartquotes.typ | typst | Apache License 2.0 | // Test setting custom smartquotes
---
// Use language quotes for missing keys, allow partial reset
#set smartquote(quotes: "«»")
"Double and 'Single' Quotes"
#set smartquote(quotes: (double: auto, single: "«»"))
"Double and 'Single' Quotes"
---
// Allow 2 graphemes
#set smartquote(quotes: "a\u{0301}a\u{0301}")
"Double and 'Single' Quotes"
#set smartquote(quotes: (single: "a\u{0301}a\u{0301}"))
"Double and 'Single' Quotes"
---
// Error: 25-28 expected 2 characters, found 1 character
#set smartquote(quotes: "'")
---
// Error: 25-35 expected 2 quotes, found 4 quotes
#set smartquote(quotes: ("'",) * 4)
---
// Error: 25-45 expected 2 quotes, found 4 quotes
#set smartquote(quotes: (single: ("'",) * 4))
|
https://github.com/RY997/Thesis | https://raw.githubusercontent.com/RY997/Thesis/main/thesis_typ/abstract_en.typ | typst | MIT License | #let abstract_en() = {
set page(
margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm),
numbering: none,
number-align: center,
)
let body-font = "New Computer Modern"
let sans-font = "New Computer Modern Sans"
set text(
font: body-font,
size: 12pt,
lang: "en"
)
set par(
leading: 1em,
justify: true
)
// --- Abstract (DE) ---
v(1fr)
align(center, text(font: body-font, 1em, weight: "semibold", "Abstract"))
text[
In response to the challenges posed by larger class sizes in computer science education, Artemis, an open-source learning platform, adopts interactive learning principles to enhance scalability and adaptability. However, the platform faces shortcomings in catering to the diverse skill levels and learning needs of students. This motivates the exploration of adaptive programming exercise generation, aiming to offer tailored challenges for individual learners. Adaptive exercises have the potential to both challenge advanced students and support beginners effectively, fostering intellectual growth and confidence. Leveraging advancements in Artificial Intelligence (AI), particularly Large Language Models (LLMs), this thesis introduces a novel approach to create adaptive programming exercises. The objectives include the development of a chatbot named Iris for intelligent exercise planning, enabling LLMs for dynamic exercise change plan execution, and seamlessly integrating exercise changes into the Artemis platform. This innovative methodology promises to revolutionize computer science education by providing personalized learning experiences and promoting continuous growth among students.
]
v(1fr)
} |
https://github.com/Mc-Zen/quill | https://raw.githubusercontent.com/Mc-Zen/quill/main/examples/fault-tolerant-toffoli2.typ | typst | MIT License | #import "../src/quill.typ": *
#let group = gategroup.with(stroke: (dash: "dotted", thickness: .5pt))
#quantum-circuit(
fill-wires: false,
group(3, 3, padding: (left: 1.5em)), lstick($|0〉$), $H$, ctrl(2), ctrl(3), 3,
group(2, 1),ctrl(1), 1, group(3, 1), ctrl(2), $X$, 1, rstick($|x〉$), [\ ],
lstick($|0〉$), $H$, ctrl(0), 1, ctrl(3), 2, $Z$, $X$, 2, group(2, 1),
ctrl(1), rstick($|y〉$), [\ ],
lstick($|0〉$), 1, targ(), 2, targ(), 1, mqgate($Z$, target: -1, wire-count: 2), 1,
targ(fill: auto), 1, targ(fill: auto), rstick($|z plus.circle x y〉$), [\ ],
lstick($|x〉$), 2, targ(), 6, meter(target: -3), setwire(2), ctrl(-1, wire-count: 2), [\ ],
lstick($|y〉$), 3, targ(), 3, meter(target: -3), setwire(2), ctrl(-2, wire-count: 2), [\ ],
lstick($|z〉$), 4, ctrl(-3), $H$, meter(target: -3)
) |
https://github.com/T1mVo/shadowed | https://raw.githubusercontent.com/T1mVo/shadowed/main/examples/lorem.typ | typst | MIT License | #import "../src/lib.typ": shadowed
#set page(margin: 15pt, height: auto)
#set par(justify: true)
#shadowed(radius: 4pt, inset: 12pt)[
#lorem(50)
]
|
https://github.com/sinchang/typst-react | https://raw.githubusercontent.com/sinchang/typst-react/master/resume.typ | typst | // https://github.com/skyzh/typst-cv-template/blob/master/cv.typ
#show heading: set text(font: "Linux Biolinum")
#show link: underline
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
#set par(justify: true)
#let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
= <NAME>
<EMAIL> |
#link("https://github.com/example")[github.com/example] | #link("https://example.com")[example.com]
== Education
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
== Work Experience
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
== Projects
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
- #lorem(40) |
|
https://github.com/jamesrswift/dining-table | https://raw.githubusercontent.com/jamesrswift/dining-table/main/tests/topdown/header-none/test.typ | typst | The Unlicense | #import "../ledger.typ": *
#set text(size: 11pt)
#set page(height: 3.5cm, margin: 1em)
#dining-table.make(columns: example,
header: none,
data: data,
notes: dining-table.note.display-list
)
#dining-table.make(columns: example,
data: data,
notes: dining-table.note.display-list
) |
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/src/wp.typ | typst | MIT License | #import "_imports.typ": *
#let wochenplan(
..args,
body,
) = {
let (doc, page-init, tpl) = base-template(
type: "WP",
type-long: "Wochenplan",
title-block: doc => {
heading(level: 1, outlined: false, bookmarked: false, doc.title)
grid(
columns: (auto, 1fr),
align: center + horizon,
column-gutter: 5pt,
image(width: 1.5cm, "assets/calendar.svg"),
container(radius: 4pt, fill: theme.muted, stroke: 0pt)[
#set align(center)
#set text(1.2em, white)
#show heading: set text(white)
*#doc.from.display("[day].[month].[year]") bis #doc.to.display("[day].[month].[year]")*
],
)
},
_tpl: (
options: (
from: t.date(
pre-transform: t.coerce.date,
default: datetime.today(),
),
to: t.date(
optional: true,
pre-transform: (self, it) => {
if it != none {
return t.coerce.date(self, it)
} else {
let _today = datetime.today()
return datetime(
year: _today.year(),
month: _today.month(),
day: _today.day(),
)
}
},
),
),
aliases: (
von: "from",
bis: "to",
),
),
..args,
body,
)
{
show: page-init
tpl
}
}
#let gruppe(titel, beschreibung, body) = container(
radius: 6pt,
fill: theme.bg.muted,
stroke: 1.5pt + luma(120),
title-style: (boxed-style: (:)),
title: text(weight: "bold", hyphenate: false, size: .88em, titel),
)[#small(beschreibung)#container(fill: white, radius: 3pt, stroke: 1pt + luma(120), body)]
|
https://github.com/01mf02/jq-lang-spec | https://raw.githubusercontent.com/01mf02/jq-lang-spec/main/tour.typ | typst | #import "common.typ": example
= Tour of jq <tour>
This goal of this section is to convey an intuition about how jq functions.
The official documentation of jq is its user manual @jq-manual.
jq programs are called _filters_.
For now, let us consider a filter to be a function from a value to
a (lazy, possibly infinite) stream of values.
Furthermore, in this section, let us assume a value to be either
a boolean, an integer, or an array of values.
(We introduce the full set of JSON values in @json.)
The identity filter "`.`" returns a stream containing the input.#footnote[
The filters in this section can be executed on most UNIX shells by
`echo $INPUT | jq $FILTER`, where
`$INPUT` is the input value in JSON format and
`$FILTER` is the jq program to be executed.
Often, it is convenient to quote the filter; for example,
to run the filter "`.`" with the input value `0`,
we can run `echo 0 | jq '.'`.
In case where the input value does not matter,
we can also use `jq -n $FILTER`,
which runs the filter with the input value `null`.
We use jq 1.7.
]
Arithmetic operations, such as
addition, subtraction, multiplication, division, and remainder,
are available in jq.
For example, "`. + 1`" returns a stream containing the successor of the input.
Here, "`1`" is a filter that returns the value `1` for any input.
Concatenation is an important operator in jq:
The filter "`f, g`" concatenates the outputs of the filters `f` and `g`.
For example, the filter "`., .`" returns a stream containing the input value twice.
Composition is one of the most important operators in jq:
The filter "`f | g`" maps the filter `g` over all outputs of the filter `f`.
For example, "`(1, 2, 3) | (. + 1)`" returns `2, 3, 4`.
Arrays are created from a stream produced by `f` using the filter "`[f]`".
For example, the filter "`[1, 2, 3]`"
concatenates the output of the filters "`1`", "`2`", and "`3`" and puts it into an array,
yielding the value `[1, 2, 3]`.
The inverse filter "`.[]`" returns a stream containing the values of an array
if the input is an array.
For example, running "`.[]`" on the array `[1, 2, 3]` yields
the stream `1, 2, 3` consisting of three values.
We can combine the two shown filters to map over arrays;
for example, when given the input `[1, 2, 3]`,
the filter "`[.[] | (. + 1)]`" returns a single value `[2, 3, 4]`.
The values of an array at indices produced by `f` are returned by "`.[f]`".
For example, given the input `[1, 2, 3]`, the filter "`.[0, 2, 0]`"
returns the stream `1, 3, 1`.
Case distinctions can be performed with the filter "`if f then g else h end`".
For every value `v` produced by `f`, this filter
returns the output of `g` if `v` is true and the output of `h` otherwise.
For example, given the input `1`,
the filter "`if (. < 1, . == 1, . >= 1) then . else [] end`" returns `[], 1, 1`.
We can define filters by using the syntax "`def f(x1; ...; xn): g;`",
which defines an filter `f` taking `n` arguments by `g`,
where `g` can refer to `x1` to `xn`.
For example, jq provides the filter "`recurse(f)`" to calculate fix points,
which could be defined by "`def recurse(f): ., (f | recurse(f));`".
Using this, we can define a filter to calculate the factorial function, for example.
#example("Factorial")[
Let us define a filter `fac` that should return $n!$ for any input number $n$.
We will define `fac` using the fix point of a filter `update`.
The input and output of `update` shall be an array `[n, acc]`,
satisfying the invariant that the final output is `acc` times the factorial of `n`.
The initial value passed to `update` is the array "`[., 1]`".
We can retrieve `n` from the array with "`.[0]`" and `acc` with "`.[1]`".
We can now define `update` as "`if .[0] > 1 then [.[0] - 1, .[0] * .[1]] else empty end`",
where "`empty`" is a filter that returns an empty stream.
Given the input value `4`, the filter "`[., 1] | recurse(update)`" returns
`[4, 1], [3, 4], [2, 12], [1, 24]`.
We are, however, only interested in the accumulator contained in the last value.
So we can write "`[., 1] | last(recurse(update)) | .[1]`", where
"`last(f)`" is a filter that outputs the last output of `f`.
This then yields a single value `24` as result.
] <ex:fac>
Composition can also be used to bind values to _variables_.
The filter "`f as $x | g`" performs the following:
Given an input value `i`,
for every output `o` of the filter `f` applied to `i`,
the filter binds the variable `$x` to the value `o`, making it accessible to `g`, and
yields the output of `g` applied to the original input value `i`.
For example, the filter "`(0, 2) as $x | ((1, 2) as $y | ($x + $y))`"
yields the stream `1, 2, 3, 4`.
Note that in this particular case, we could also write this as "`(0, 2) + (1, 2)`",
because arithmetic operators such as "`f + g`" take as inputs
the Cartesian product of the output of `f` and `g`.
#footnote[
#set raw(lang: "haskell")
Haskell users might appreciate the similarity of the two filters
to their Haskell analoga
"`[0, 2] >>= (\x -> [1, 2] >>= (\y -> return (x+y)))`" and
"`(+) <$> [0, 2] <*> [1, 2]`", which both return
`[1, 2, 3, 4]`.
]
However, there are cases where variables are indispensable.
#example("Variables Are Necessary")[
jq defines a filter "`in(xs)`" that expands to "`. as $x | xs | has($x)`".
Given an input value `i`, "`in(xs)`" binds it to `$x`, then returns
for every value produced by `xs` whether its domain contains `$x` (and thus `i`).
Here, the domain of an array is the set of its indices.
For example, for the input
`1`, the filter
"`in([5], [42, 3], [])`" yields the stream
`false, true, false`,
because only `[42, 3]` has a length greater than 1 and thus a domain that contains `1`.
The point of this example is that
we wish to pass `xs` as input to `has`, but at the same point,
we also want to pass the input given to `in` as an argument to `has`.
Without variables, we could not do both.
]
Folding over streams can be done using `reduce` and `foreach`:
The filter "`reduce xs as $x (init; f)`" keeps
a state that is initialised with the output of `init`.
For every element `$x` yielded by the filter `xs`,
`reduce` feeds the current state to the filter `f`, which may reference `$x`,
then sets the state to the output of `f`.
When all elements of `xs` have been yielded, `reduce` returns the current state.
For example, the filter "`reduce .[] as $x (0; . + $x)`"
calculates the sum over all elements of an array.
Similarly, "`reduce .[] as $x (0; . + 1)`" calculates the length of an array.
These two filters are called "`add`" and "`length`" in jq, and
they allow to calculate the average of an array by "`add / length`".
The filter "`foreach xs as $x (init; f)`" is similar to `reduce`,
but also yields all intermediate states, not only the last state.
For example, "`foreach .[] as $x (0; . + $x)`"
yields the cumulative sum over all array elements.
Updating values can be done with the operator "`|=`",
which has a similar function as lens setters in languages such as Haskell
#cite(label("DBLP:conf/icfp/FosterPP08"))
#cite(label("DBLP:conf/popl/FosterGMPS05"))
#cite(label("DBLP:journals/programming/PickeringGW17")):
Intuitively, the filter "`p |= f`" considers any value `v` returned by `p` and
replaces it by the output of `f` applied to `v`.
We call a filter on the left-hand side of "`|=`" a _path expression_.
For example, when given the input `[1, 2, 3]`,
the filter "`.[] |= (. + 1)`" yields `[2, 3, 4]`, and
the filter "`.[1] |= (. + 1)`" yields `[1, 3, 3]`.
We can also nest these filters;
for example, when given the input `[[1, 2], [3, 4]]`,
the filter "`(.[] | .[]) |= (. + 1)`" yields `[[2, 3], [4, 5]]`.
However, not every filter is a path expression; for example,
the filter "`1`" is not a path expression because
"`1`" does not point to any part of the input value
but creates a new value.
Identities such as
"`.[] |= f`" being equivalent to "`[.[] | f]`" when the input value is an array, or
"`. |= f`" being equivalent to `f`,
would allow defining the behaviour of updates.
However, these identities do not hold in jq due the way it
handles filters `f` that return multiple values.
In particular, when we pass `0` to the filter "`. |= (1, 2)`",
the output is `1`, not `(1, 2)` as we might have expected.
Similarly, when we pass `[1, 2]` to the filter "`.[] |= (., .)`",
the output is `[1, 2]`, not `[1, 1, 2, 2]` as expected.
This behaviour of jq is cumbersome to define and to reason about.
This motivates in part the definition of more simple and elegant semantics
that behave like jq in most typical use cases
but eliminate corner cases like the ones shown.
We will show such semantics in @updates.
|
|
https://github.com/rangerjo/tutor | https://raw.githubusercontent.com/rangerjo/tutor/main/imgs/example.typ | typst | MIT License | #set page(
width: auto,
height: auto,
margin: (x: 0cm),
)
#table(
columns: 2,
stroke: none,
align: center,
[ Question Mode ], [ Solution Mode ],
[#rect(stroke: 2pt+blue,
image("../example/build/example_question_mode.svg", width: 12cm)
)],
[#rect(stroke: 2pt+green,
image("../example/build/example_solution_mode.svg", width: 12cm)
)]
)
|
https://github.com/lf-/typst-algorithmic | https://raw.githubusercontent.com/lf-/typst-algorithmic/main/algorithmic.typ | typst | // SPDX-FileCopyrightText: 2023 <NAME>
//
// SPDX-License-Identifier: MIT
/*
* Generated AST:
* (change_indent: int, body: ((ast | content)[] | content | ast)
*/
#let ast_to_content_list(indent, ast) = {
if type(ast) == "array" {
ast.map(d => ast_to_content_list(indent, d))
} else if type(ast) == "content" {
(pad(left: indent * 0.5em, ast),)
} else if type(ast) == "dictionary" {
let new_indent = ast.at("change_indent", default: 0) + indent
ast_to_content_list(new_indent, ast.body)
}
}
#let algorithm(..bits) = {
let content = bits.pos().map(b => ast_to_content_list(0, b)).flatten()
let table_bits = ()
let lineno = 1
while lineno <= content.len() {
table_bits.push([#lineno:])
table_bits.push(content.at(lineno - 1))
lineno = lineno + 1
}
table(
columns: (18pt, 100%),
// line spacing
inset: 0.3em,
stroke: none,
..table_bits
)
}
#let iflike_block(kw1: "", kw2: "", cond: "", ..body) = (
(strong(kw1) + " " + cond + " " + strong(kw2)),
// XXX: .pos annoys me here
(change_indent: 4, body: body.pos())
)
#let function_like(name, kw: "function", args: (), ..body) = (
iflike_block(kw1: kw, cond: (smallcaps(name) + "(" + args.join(", ") + ")"), ..body)
)
#let listify(v) = {
if type(v) == "list" {
v
} else {
(v,)
}
}
#let Function = function_like.with(kw: "function")
#let Procedure = function_like.with(kw: "procedure")
#let State(block) = ((body: block),)
/// Inline call
#let CallI(name, args) = smallcaps(name) + "(" + listify(args).join(", ") + ")"
#let Call(..args) = (CallI(..args),)
#let FnI(f, args) = strong(f) + " (" + listify(args).join(", ") + ")"
#let Fn(..args) = (FnI(..args),)
#let Ic(c) = sym.triangle.stroked.r + " " + c
#let Cmt(c) = (Ic(c),)
// It kind of sucks that Else is a separate block but it's fine
#let If = iflike_block.with(kw1: "if", kw2: "then")
#let While = iflike_block.with(kw1: "while", kw2: "do")
#let For = iflike_block.with(kw1: "for", kw2: "do")
#let Assign(var, val) = (var + " " + $<-$ + " " + val,)
#let Else = iflike_block.with(kw1: "else")
#let ElsIf = iflike_block.with(kw1: "else if", kw2: "then")
#let ElseIf = ElsIf
#let Return(arg) = (strong("return") + " " + arg,)
|
|
https://github.com/dismint/docmint | https://raw.githubusercontent.com/dismint/docmint/main/networks/pset1.typ | typst | #import "template.typ": *
#show: template.with(
title: "14.15 Problem Set #1",
subtitle: "<NAME>",
pset: true
)
= Problem 1
Let us the follow the convention for this problem that the first (top) row and (left) column specify the first node, and increase as they go down / right.
Since it is not explicitly stated, I will also make the assumption that there are no self-edges. This will be important in some calculations.
== (a)
We can consider each row as conveying information about the neighbors of that specific node. Then, to find the degree of the $n$th node, it simply suffices to add all the values in the $n$th row of the adjacency matrix. Thus we can accomplish this with matrix multiplication as follows:
$ bold(d) = boxed(bold(g) times bold(1)) $
In the above equation we are multiplying a $n times n$ matrix by a $n times 1$ vector, giving us the desired $n times 1$ dimensions for the vector $bold(d)$
== (b)
To get the total number of edges, we can take the sum of the degrees of each node, then divide by two to account for the fact that edges get double counted from both sides. Recall that the assumption has been made that there are no self-edges.
$ m = boxed(1/2 sum_(i,j) bold(g)_(i,j)) $
Alternatively we could have also notated this as $1^T dot (g times 1)$, or more simply $1^T dot bold(d)$
== (c)
Consider two rows in the $bold(g)$ matrix - by taking the dot product of binary vectors, we essentially determine how many positions both contain $1$, meaning that they have a shared edge. Thus to find the number of shared edges between two nodes $i, j$, simply take the dot product $bold(g)_i dot bold(g)_j$. Thus leads to our final formulation:
$ bold(N)_(i,j) = bold(g)_i dot bold(g)_j $
This of course, is the exact same thing as simply squaring the $bold(g)$ matrix.
$ bold(N) = boxed(bold(g) times bold(g)) $
Note that this has the consequence that the value of $bold(N)$ for a node and itself is its degree.
== (d)
Expanding off our answer from above, let us think about what happens when we further multiply by $bold(g)$, *cubing* the adjacency matrix.
Consider multiplying $bold(N)_i dot bold(g)_j$. For the $z$th element of each, we are essentially asking how many paths there are from $i$ to $z$ passing through some $x != i, z$ and then $z$ to $j$. What we really care about is the case where we loop back around and make a triangle, thus $j=i$. We should only care about the diagonal values of the resulting matrix as this is where that information lies.
Getting the answer by taking the trace would be an overestimate for a few reasons. Consider all the ways to count the triangle involving $a, b, c$
#enum(
enum.item(1)[
Fixing the starting point, we can run into both\
$a arrow.r b arrow.r c arrow.r a$\
$a arrow.r c arrow.r b arrow.r a$\
This accounts for a doubling in the total number of counted triangles.
],
enum.item(2)[
The cycle can start from any of the three nodes, leading to a tripling in the total number of counted triangles.
]
)
Therefore we conclude that we must take a sixth of this final number to get the accurate number of triangles.
$ \#"Triangles" = boxed(1 / 6 "Tr"(bold(g)^3)) $
= Problem 2
== (a)
#define(
title: "Betweenness Centrality"
)[
Recall that we define Betweenness Centrality (*BC*) for a node as the fraction of shortest paths between two arbitrary nodes that pass through this node, averaged over all pairs.
$ bold("BC")_k = sum_((i, j) : i != j, k != i, j) (P_k(i, j) \/ P(i, j)) / ((n-1)(n-2)) $
]
Since we are working with a tree, there are several nice simplifications that can be made.
As the graph is a tree, there is only one path between any two given nodes. Therefore $P(i, j)$ can be fixed to $1$
$ bold("BC")_k = sum_((i, j) : i != j, k != i, j) P_k(i, j) / ((n-1)(n-2)) $
With the new equation, we can now rephrase *BC* as "What fraction of paths contain $k$?". Alternatively this can also be phrased as $1 -$ "Fraction of paths that *don't* contain $k$". Let us work with this second definition, as that seems to be the rough form our desired answer takes.
For the disjoint regions, it is true that exactly one path existed in the original tree, so the path between one node in each region must have passed through $k$ previously. Conversely, it is also true that within the connected regions, $k$ did not impact the path between any two nodes since there already exists a path as the region is connected, and with exactly one path in a tree between two nodes, there cannot be an additional path passing through $k$. Therefore, it is sufficient to count the sum of pairs of nodes we can make with the restriction that both must be from the same region.
For the $m$th region, we can count the number of pairs of elements with $n_m (n_m-1)$, and we must take the total sum, leading us to:
$ sum_(m=1)^d n_m (n_m-1) $
However remember that we are taking the fraction of all paths so we end up with:
$ sum_(m=1)^d (n_m (n_m-1)) / ((n-1)(n-2)) $
And we finally remember that this is the inverse of the original desired quantity (the number of paths *including* $k$), so we must take the difference to $1$, resulting in the final form which matches the requested formula:
$ bold("BC")_k = boxed(1 - sum_(m=1)^d (n_m (n_m-1)) / ((n-1)(n-2))) $
== (b)
In a line graph, removing a node will always split the graph into at most $2$ pieces, depending on whether it is either the first / last node or one in the middle.
Let us assume that this graph contains at least two nodes and $i$ is zero-indexed. Then, the sizes of the two disjoins regions will be $i$ and $n-1-i$. Therefore the above formula can be simplified accounting for this new guarantee.
$ bold("BC")_i = boxed(1 - (i(i-1) + (n-1-i)(n-2-i)) / ((n-1)(n-2))) $
This expression can cancel the $(n-2)$ term out according to Wolfram Alpha, but I will leave the above as a sufficiently concise solution. Of course it only applies when we choose a node in the middle, as otherwise the terms can become negative. Thus if we pick the end, we instead have the simplified formula.
$ bold("BC")_i = 1 - ((n-1)(n-2)) / ((n-1)(n-2)) $
Thus, the centrality of an edge node is actually $0$, which makes sense as no shortest path in a line graph would ever pass through an edge except paths starting or ending from that edge (which are excluded from the calculation).
= Problem 3
== (a)
We want to take the sum across each degree multiplied by its chance of happening:
$ sum_i d_i dot "Chance to get" d_i $
Let us define this chance as the probability of picking an edge that connects to a node with degree $d_i$, divided by two since we need to pick the correct side of the edge. This works out nicely, even for cases where both ends of the edge are $d_i$ as the edge will get counted twice to make up for the incorrect fractional chance of picking it.
The chance we pick an edge that connects to a node with degree $d_i$ is tricker to derive:
+ $P(d_i) dot N$ is the number of nodes with degree $d_i$
+ $P(d_i) dot N dot d$ is the number of edges which have a $d_i$ degree endpoint.
+ $(P(d_i) dot N dot d_i) \/ M$ is the fraction of edges which have a $d_i$ degree endpoint.
+ $(P(d_i) dot N dot d_i) \/ (2 dot M)$ includes the likelihood of picking the correct end of the edge.
Therefore we now have the formula:
$ sum_i (d_i^2 dot P(d_i) dot N) / (2 dot M) $
We still need to get rid of the $M, N$ terms. To do this, observe that:
$ M = 1 / 2 sum_i P(d_i) dot d_i dot N $
Therefore we can make the following substitution in our equation:
$ M / N = (sum_i P(d_i) dot d_i dot N) / 2 $
And our equation now simplifies to:
$ sum_i (d_i^2 dot P(d_i) dot N dot 2) / (sum_i (P(d_i) dot d_i dot N) dot 2) = boxed(sum_i (P(d_i) dot d_i^2) / (sum_i P(d_i) dot d_i)) $
== (b)
The expected value in *(a)* was hard to calculate since a higher degree means there is an inherent higher chance to be picked, even more so than $P(d_i)$ would seem to indicate. Let us show that $E[D] >= E[X]$
We start with the fact that variance is always non-negative and work from there. Recall that $E[X] = sum_i P(d_i) dot d_i$
$ 0 <= "Var"[X] = sigma_X^2 = sum_i P(d_i)(d - E[X])^2 = sum_i P(d_i)(d^2+E[X]^2-2 dot d dot E[X]) $
Then notice the last step can be simplified as follows:
$
&= sum_i P(d_i) dot d^2 + sum_i P(d_i) dot E[X]^2 - sum_i P(d_i) dot 2 dot d dot E[X]\
&= sum_i P(d_i) dot d^2 + E[X]^2 - 2 dot E[X]^2\
&= sum_i P(d_i) dot d^2 - E[X]^2
$
After which we take the last couple steps to complete the proof:
$
0 &<= sum_i P(d_i) dot d^2 - E[X]^2\
E[X]^2 &<= sum_i P(d_i) dot d^2\
E[X] &<= sum_i (P(d_i) dot d^2) / (E[X])\
E[X] &<= E[D]
$
Thus we arrive at our desired conclusion, with the last step being made the same as the result of *(a)*
== (c)
We can simplify and show that:
$ sum_i d_i <= sum_i delta_i $
The left side can be reformatted since the sum of degrees is equal to two times the number of edges. The right side can be reformatted following a very similar style of logic, except this time instead of counting the edge twice back and forth, we need to count the ratio of degrees both ways.
$ sum_((i, j):i < j) 2 <= sum_((i, j):i < j) (d_i / d_j + d_j / d_i) $
Now all we need to do is to show $2 <= (d_i / d_j + d_j / d_i)$. Remember that since these are degrees, all numbers are positive. Let us start from a clearly true inequality and work onward.
$
(d_i - d_j)^2 &>= 0\
d_i^2 - 2 dot d_i dot d_j + d_j^2 &>= 0\
d_i^2 + d_j^2 &>= 2 dot d_i dot d_j\
d_i / d_j + d_j / d_i &>= 2
$
Thus we have shown that the inequality is satisfied for this problem. It turns out the last part of this proof actually works even if the numbers aren't always positive after graphing it on Desmos.
== (d)
Let us see how the idea of the friendship paradox is strengthened by the previous two parts.
*(b)* tells us that the expected degree of picking a random node is less than the expected value of picking an edge then picking a node. This speaks to the inherent bias there is in having more friends. You can only view your friends, and those friends are viewed through the connection (edge). As can be clearly seen in this part, there is a much heavier bias on being picked when you have a higher degree. This part can perhaps be summarized with the sentiment that the friendship paradox doesn't mean you have less friends than the average person, rather that you have less friends than *your* friends.
*(c)* tells us that the average degree of nodes in a graph is less than the average degree of its neighbors. This reinforces the fact that on average _your friends have more friends than you do_. Of course, this doesn't say anything about the magnitude of the difference, but nonetheless it is mathematically sound that there is a feeling of having less friends than your friends.
|
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/recipes/declaring-a-shell-environment.md | markdown | MIT License | # Declaring a shell environment
You can automatically pull your project's dependencies into your shell by
declaring a [shell environment][nix-dev-declarative-shell] and then activating
it with [`nix develop`][nix-ref-develop] or [`direnv`][direnv].
Here's an example in a flake using Typix's
[`devShell`](../api/derivations/dev-shell.md):
```nix
{
outputs = { typix }: let
system = "x86_64-linux";
typixLib = typix.lib.${system};
watch-script = typixLib.watchTypstProject {/* ... */};
in {
# packages, apps, etc. omitted
devShells.${system}.default = typixLib.devShell {
fontPaths = [/* ... */];
virtualPaths = [/* ... */];
packages = [
watch-script
];
};
};
}
```
What this example does:
- Fonts added to [`fontPaths`](../api/derivations/dev-shell.md#fontpaths) will
be made available to `typst` commands via the `TYPST_FONT_PATHS` environment
variable.
- Files in [`virtualPaths`](../api/derivations/dev-shell.md#virtualpaths) will be
recursively symlinked to the current directory (only overwriting existing
files when
[`forceVirtualPaths`](../api/derivations/dev-shell.md#forcevirtualpaths) is
`true`).
- For convenience, the
[`typst-watch`](../api/derivations/watch-typst-project.md#scriptname) script
is added, which will run
[`watchTypstProject`](../api/derivations/watch-typst-project.md).
[direnv]: https://direnv.net/
[nix-dev-declarative-shell]: https://nix.dev/tutorials/first-steps/declarative-shell
[nix-ref-develop]: https://nixos.org/manual/nix/stable/command-ref/new-cli/nix3-develop
|
https://github.com/linsyking/messenger-manual | https://raw.githubusercontent.com/linsyking/messenger-manual/main/appendix.typ | typst | #pagebreak()
= Appendix
== SOM Calls <sommsg>
`SOMMsg`s are top-level APIs (like system calls in OS) that can directly interact with the core. Users can send `SOMMsg` in any general model.
=== `SOMChangeScene`
*Definition.* `SOMChangeScene ( Maybe scenemsg ) String ( Maybe (Transition userdata) )`
*Definition.* `SOMChangeScene ( Maybe scenemsg ) String`
This message is used to change to another scene. Users need to provide the scene init data, the scene name, and the transition.
This message is used to change to another scene. Users need to provide the scene init data, the scene name.
=== `SOMPlayAudio`
*Definition.* `SOMPlayAudio Int String AudioOption`
This message is used to play an audio. It has three parameters: channel ID, audio name, and audio option. The channel ID is where this audio will be played. There might be multiple audios playing on the same channel. Audio name is what users define in the keys of `allAudio`.
`AudioOption` is defined in `Messenger.Audio.Base.elm`:
```elm
type AudioOption
= ALoop
| AOnce
```
`ALoop` means the audio will be played repeatedly. `AOnce` means the audio will be
played only once.
==== Example
Suppose we have two audio files `assets/bg.ogg` and `assets/se.ogg`.
First we need to import them to our projects, so edit `Lib/Resources.elm`:
```elm
allAudio : Dict.Dict String String
allAudio =
Dict.fromList
[ ( "bg", "assets/bg.ogg" )
, ( "se", "assets/se.ogg" )
]
```
This is very similar to `allTexture`.
After that, we decide to use 0 as the background music channel and 1 as the sound effect channel.
Then, when we want to play the background music `bg`, emit:
```elm
SOMPlayAudio 0 "bg" ALoop
```
And when we want to play the sound effect `se`, emit:
```elm
SOMPlayAudio 1 "se" AOnce
```
*Hint.* Users can use `newAudioChannel` to generate a unique channel ID.
=== `SOMStopAudio`
*Definition.* `SOMStopAudio Int`
This message is used to stop a channel. The parameter is the channel ID. If there are multiple audios playing on a channel, all of them will be stopped.
=== `SOMAlert`
*Definition.* `SOMAlert String`
This message is used to show an alert. The parameter is the content of the alert.
=== `SOMPrompt`
*Definition.* `SOMPrompt String String`
This message is used to show a #link("https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt")[prompt]. Users can use this to get text input from the user. The first parameter is the name of the prompt, and the second parameter is the title of the prompt.
When the user clicks the OK button, user code will receive a `Prompt String String` message. The first parameter is the name of the prompt, and the second parameter is the user’s input.
=== `SOMSetVolume`
*Definition.* `SOMSetVolume Float`
This message is to change the volume. It should be a value in $[0, 1]$. Users could use a larger value but it will sound noisy.
=== `SOMSaveGlobalData`
*Definition.* `SOMSaveGlobalData`
Save global data (including user data) to local storage.
See @localstorage.
== Game Configurations
Users may want to change the settings in `MainConfig.elm` to match their demand. This section explains what each options in that configuration file means.
- `initScene`. The first scene users will see when start the game
- `initSceneMsg`. The message to start the first scene
- `virtualSize`. The virtual drawing size. Users may use whatever they like but think carefully about the ratio (Support 4:3 or 16:9? screens)
- `debug`. A debug flag. If turned on, users can press `F1` to change to a scene quickly and press `F2` to change volume during anytime in the game
- `background`. The background users see. Default is a transparent background
- `timeInterval`. The update strategy. See @tick
- `initGlobalData` and `saveGlobalData`. See @localstorage
== Messenger CLI Commands <cli>
You can also use `messenger <command> --help` to view help.
=== Scene
Create a scene.
Usage: `messenger scene [OPTIONS] NAME`
Arguments:
- `name`. The name of the scene
- `--raw`. Use raw scene without layers
- `--proto`, `-p`. Create a sceneproto
- `--init`, `-i`. Create a `Init.elm` file
=== Init
Initialize a Messenger project.
Usage: `messenger init [OPTIONS] NAME`
Arguments:
- `name`. The name of project
- `--template-repo`, `-t`. Use customized repository for cloning templates.
- `--template-tag`, `-b`. The tag or branch of the repository to clone.
=== Layer
Create a layer.
Usage: `messenger layer [OPTIONS] NAME LAYER`
Arguments:
- `name`. The name of the scene
- `layer`. The name of the layer
- `--with-component`, `-c`. Use components in this layer
- `--cdir`, `-cd`. Directory of components in the scene
- `--proto`, `-p`. Create layer in sceneproto
- `--init`, `-i`. Create a `Init.elm` file
=== Level
Create a level.
Usage: `messenger level [OPTIONS] SCENEPROTO NAME`
Arguments:
- `sceneproto`. The name of the sceneproto
- `name`. The name of the level
=== Component
Create a component.
Usage: `messenger component [OPTIONS] SCENE NAME`
Arguments:
- `scene`. The name of the scene
- `name`. The name of the component
- `--cdir`, `-cd`. Directory to store components
- `--proto`, `-p`. Create component in sceneproto
- `--init`, `-i`. Create a `Init.elm` file
== Roadmap
This sections contains some ideas we'd like to implement in future versions of Messenger. We welcome users to post feature request in our Messenger repository's issue.
=== Multi-pass Updater
Some components may want to do some operations after all other components have finished. This is the _second-pass_ updater. We plan to extend this idea further to support _multi-pass_ updater. Components may update _any_ number of passes in one event update.
=== Advanced Component View
Users might want to have `List (Renderable, Int)` instead of `(Renderable, Int)` (In fact, this is what Reweave does). A use-case is that a component may have some part behind the player and some other part in front of the player.
=== Unified custom element
Unify `elm-canvas` and audio system.
=== Asset Manager
Design a better asset manager that helps manage all the assets, including audios, images, and other data.
=== On-demand Asset Loading
Users can load or pre-load assets when they want to, not at the beginning of the game.
== Acknowledgement
We express great gratitude to the FOCS Messenger team. Members are #link("<EMAIL>")[linsyking], #link("<EMAIL>")[YUcxovo], #link("<EMAIL>")[matmleave]. We also express sincere gratitude to all students using Messenger. |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/superb-pci/0.1.0/README.md | markdown | Apache License 2.0 | # superb-pci
Template for [Peer Community In](https://peercommunityin.org/) (PCI) submission and [Peer Community Journal](https://peercommunityjournal.org/) (PCJ) post-recommendation upload.
The template is as close as possible to the LaTeX one.
## Usage
To use this template in Typst, simply import it at the top of your document.
```
#import "@preview/superb-pci:0.1.0": *
```
Alternatively, you can start using this template from the command line with
```
typst init @preview/superb-pci:0.1.0 my-superb-manuscript-dir
```
or directly in the web app by clicking "Start from template".
Please see the main Readme about Typst packages [https://github.com/typst/packages](https://github.com/typst/packages).
## Configuration
This template exports the `pci` function with the following named arguments:
- `title`: the paper title
- `authors`: array of author dictionaries. Each author must have the `name` field, and can have the optional fields `orcid`, and `affiliations`.
- `affiliations`: array of affiliation dictionaries, each with the keys `id` and `name`. All correspondence between authors and affiliations is done manually.
- `abstract`: abstract of the paper as content
- `doi`: DOI of the paper displayed on the front page
- `keywords`: array of keywords displayed on the front page
- `correspondence`: corresponding address displayed on the front page
- `numbered_sections`: boolean, whether sections should be numbered
- `pcj`: boolean, provides a way to remove the front page and headers/footers for upload to the Peer Community Journal. `[default: false]`
The template will initialize your folder with a sample call to the `pci` function in a show rule and dummy content as an example.
If you want to change an existing project to use this template, you can add a show rule like this at the top of your file:
```typst
#import "@preview/superb-pci:0.1.0": *
#show: pci.with(
title: [Sample for the template, with quite a very long title],
abstract: lorem(200),
authors: (
(
name: "<NAME>",
orcid: "0000-0000-0000-0001",
affiliations: "#,1"
),
(
name: "<NAME>",
orcid: "0000-0000-0000-0001",
affiliations: "#,2",
),
(
name: "<NAME>",
affiliations: "2",
),
(
name: "<NAME>",
orcid: "0000-0000-0000-0001",
affiliations: "1,3"
),
),
affiliations: (
(id: "1", name: "Rue sans aplomb, Paris, France"),
(id: "2", name: "Center for spiced radium experiments, United Kingdom"),
(id: "3", name: "Bruce's Bar and Grill, London (near Susan's)"),
(id: "#", name: "Equal contributions"),
),
doi: "https://doi.org/10.5802/fake.doi",
keywords: ("Scientific writing", "Typst", "PCI", "Example"),
correspondence: "<EMAIL>",
numbered_sections: false,
pcj: false,
)
// Your content goes here
```
You might also need to use the `table_note` function from the template.
## To do
Some things that are not straightforward in Typst yet that need to be added in the futures:
- [ ] line numbers
- [ ] switch equation numbers to the left
|
https://github.com/Dr00gy/Typst-thesis-template-for-VSB | https://raw.githubusercontent.com/Dr00gy/Typst-thesis-template-for-VSB/main/thesis_template/pages.typ | typst | #let titlePage(
thesisTitle,
thesisDescription,
fullName,
supervisor,
type: "bachelor", // bachelor, bachelor-practice, master or phd
year: datetime.today().year(),
) = {
// Overwrite some global rules
set par(
first-line-indent: 0cm,
justify: false,
)
move(
dx: -8mm,
context(
image(
if text.lang == "en" {"logos/FEI EN.svg"} else {"logos/FEI CZ.svg"},
height: 3cm,
)
)
)
heading(outlined: false, level: 2)[#thesisTitle]
v(1.5em)
set text(spacing: .3em)
text(size: 14pt)[#thesisDescription]
v(2em)
text(size: 20pt)[#fullName]
align(bottom)[
#set text(size: 14pt)
#context([
#if type == "bachelor" {
if text.lang == "en" [Bachelor thesis] else [Bakalářská práce]
} else if type == "bachelor-practice" {
if text.lang == "en" [Bachelor professional practice] else [Bakalářská praxe]
} else if type == "master" {
if text.lang == "en" [Master thesis] else [Diplomová práce]
} else if type == "phd" {
if text.lang == "en" [PhD thesis] else [Disertační práce]
}
#if text.lang == "en" [Supervisor:] else [Vedoucí práce:]
])
#supervisor
Ostrava, #year
]
}
// Pages before Contents
#let abstracts(
czechAbstract, englishAbstract,
czechKeywords, englishKeywords,
slovakAbstract: none, slovakKeywords: none,
quote: none,
acknowledgment: none,
abstractSpacing: 2.5cm,
) = {
//show heading: set block(spacing: 1em)
// Abstract
grid(
rows: (auto, auto, auto),
row-gutter: abstractSpacing,
{
text({
heading(outlined: false, level: 2)[Abstrakt]
czechAbstract
heading(outlined: false, level: 2)[Klíčová slova]
czechKeywords.join(", ")
}, lang: "cs")
},
{
text({
heading(outlined: false, level: 2)[Abstract]
englishAbstract
heading(outlined: false, level: 2)[Keywords]
englishKeywords.join(", ")
}, lang: "en")
},
if slovakAbstract != none and slovakKeywords != none {
text({
heading(outlined: false, level: 2)[Abstrakt]
slovakAbstract
heading(outlined: false, level: 2)[Kľúčové slová]
slovakKeywords.join(", ")
}, lang: "sk")
},
)
// Acknowledgement
if acknowledgment != none {
pagebreak()
if quote != none {
quote
}
align(bottom)[
#heading(outlined: false, level: 2)[
#context(if text.lang == "en" [Acknowledgment] else [Poděkování])
]
#acknowledgment
]
}
}
|
|
https://github.com/Enter-tainer/mino | https://raw.githubusercontent.com/Enter-tainer/mino/master/typst-package/mino.typ | typst | MIT License | #import "@preview/jogs:0.2.3": compile-js, call-js-function
#let mj-src = read("./mino.js")
#let mj-bytecode = compile-js(mj-src)
#let get-text(src) = {
if type(src) == str {
src
} else if type(src) == content {
src.text
}
}
#let decode-fumen(fumen) = call-js-function(mj-bytecode, "mino", fumen)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/break-continue-03.typ | typst | Other | // Test joining with continue.
#let x = for i in range(5) {
"a"
if calc.rem(i, 3) == 0 {
"_"
continue
}
str(i)
}
#test(x, "a_a1a2a_a4")
|
https://github.com/drupol/master-thesis | https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/theme/common/titlepage.typ | typst | Other | #import "metadata.typ": *
#let titlepage(
title: "",
subtitle: "",
university: "",
faculty: "",
degree: "",
program: "",
supervisor: "",
advisors: (),
author: "",
authorOrcId: "",
doi: none,
startDate: none,
submissionDate: none,
rev: none,
shortRev: none,
builddate: none,
) = {
set page(
margin: (top: 1cm, left: 1cm, right: 1cm, bottom: 1cm),
numbering: none,
number-align: center,
header: {
place(top + left)[
#pad(top: 10pt)[
#set text(size: 4em)
#include "../UMONS-fs-logo.typ"
]
]
place(top + right)[
#pad(top: 10pt)[
#set text(size: 4em)
#include "../UMONS-logo.typ"
]
]
},
footer: align(
center,
text(font: sans-font)[
#faculty #sym.diamond.filled.small
#university #sym.diamond.filled.small
20, Place du Parc #sym.diamond.filled.small
B-7000 Mons
],
),
)
set text(
font: body-font,
size: 12pt,
lang: "en",
)
place(center + horizon, dy: 3em)[
#align(center, text(font: sans-font, 2em, weight: 700, title))
#if subtitle != none {
align(center, text(font: sans-font, 1em, weight: 700, subtitle))
}
#align(center, text(font: sans-font, 1.3em, weight: 100, view))
#grid(
columns: 3,
gutter: 1em,
align: (right, left, left),
strong("Author"),
":",
{
link("https://orcid.org/" + authorOrcId)[#author#box(
image(
"../../../../resources/images/ORCIDiD_iconvector.svg",
width: 10pt,
),
)]
},
strong("Supervisor"),
":",
supervisor,
..if advisors != none {
(strong("Advisors"), ":", advisors.join(", "))
},
..if startDate != none {
(strong("Academic year"), ":", startDate)
},
..if submissionDate != none {
(strong("Submission date"), ":", submissionDate)
},
..if builddate != "" {
(strong("Build date"), ":", builddate)
},
..if doi != none {
(
strong("DOI"),
":",
link(
"https://doi.org/" + doi,
doi,
),
)
},
..if shortRev != "" {
(
strong("Revision"),
":",
link(
"https://codeberg.org/p1ld7a/master-thesis/commit/" + rev,
shortRev,
),
)
},
)
]
}
|
https://github.com/WooSeongChoi/perl-5-study | https://raw.githubusercontent.com/WooSeongChoi/perl-5-study/main/main.typ | typst | #import "@preview/ilm:1.2.1": *
#show: ilm.with(
title: [Perl 5 배우기],
author: "Learning Perl",
figure-index: (enabled: true),
table-index: (enabled: true),
listing-index: (enabled: true)
)
#set text(
font: "NanumGothic",
size: 10pt
)
#include "./chapters/chapter01/introduction.typ"
|
|
https://github.com/Ttajika/class | https://raw.githubusercontent.com/Ttajika/class/main/microecon/quiz_bank.typ | typst | #import "functions.typ": *
#set text(font: "<NAME>")
#show strong: set text(font: "<NAME>")
//see https://typst.app/docs/reference/foundations/calc
#let Q2-price1 = 120
#let Q2-price2 = 100
#let Q2-dem1 = 3020
#let Q2-dem2 = 5240
#let cat_list =("Term1",)
Quiz_createで問題のリストを作成する. Quiz = Quiz_createとするとQuizが問題のリストを格納する変数
- quiz関数で,形式に合った問題を作成する. 以下その各種引数の説明
- 最初の引数はid: これがラベルにもなるので,問題を引用するときは @Q2 のようにできる.回答のラベルはAをつけて @Q2A
- なので別のidにAをつけたものをidにするとラベルが重複しエラーが出るので注意.
- question: 問題文. [] の中に入力する
- answer: 解答. [] の中に入力する
- commentary: 解説. [] の中に入力する
- point: 配点. 整数を入力する. 合計点を計算するシステムは未実装.
#let Quiz = Quiz_create(
quiz("Q1", question:[
ある会社が運営するテーマパークがある.日々の営業に必要な費用は30億円,これまでにかかった建設費は3200億円である.ある日,このテーマパークの所有権を320億円で買いたいという人が現れたがその会社はその申し出を断った.また,テーマパークを潰してデパートを立てれば建設費や運営費などを差し引いても350億円の利益が上がるという.しかしこの会社はテーマパークの運営を続けている.また,この会社は1000億円でならこのテーマパークの所有権を売るかと言う問いにそうだと答えている.この会社が利益追求するものだとするとき,テーマパークの収入は最大いくら *以下* であると考えられるか答えなさい.ただし,問題文以外の事情は無視して良い.
], answer:[
], point:10, show-answer:true, category:"Term1"),
quiz("Q2", question:[
ある財について,価格が#Q2-price1\円から#Q2-price2\円に変化したところ,需要量が#Q2-dem1\から#Q2-dem2\に変化した.このときの需要の価格弾力性を求めなさい.
], answer:[
$#calc.abs((Q2-price2 - Q2-price1))/#calc.abs((Q2-dem2 - Q2-dem1))$
], point:12, category:"Term1"),
quiz("Q3", question:[需要関数が$D(p)=5-p/2$,総費用関数が$C(q)=5q$であるとき,独占企業の利潤を最大にする価格を求めなさい.],
answer:[難しくない], commentary:[], point:12, category:"Term1"),
quiz("Q4", question:[卵の市場を考える.鳥インフルエンザによって卵の生産費用が上昇した.このとき,市場均衡における価格と取引量がどのように変化すると考えられるか,図を用いて答えなさい], answer:[難しくない], commentary:[], point:12, category:"Term1"),
quiz("Q5", question:[豊作貧乏が発生しうる理由を図を用いて文章で説明しなさい.
], answer:[難しくない], commentary:[], point:12, category:"Term1"),
quiz("Q6", question:[
ある年のアーティストのCDの価格と取引量が次のようになっていた
- 1月1日: 価格1000, 取引量1000
- 1月30日: 価格800, 取引量1700
また,1月15日にはそのアーティストが著名な賞を受賞し,人気が高まった.
以上の事柄からわかることとして最も適当なものを以下の中から一つ選び,その理由を説明しなさい.
+ CDの需要曲線は右下がりである.
+ CDの需要曲線は右上がりである.
+ CDの供給曲線は右下がりである.
+ CDの供給曲線は右上がりである.
ただし,需要と供給のパターンは以下の4つであるとする.
#image("img/patterns2.svg")
], answer:[難しくない], commentary:[], point:12, category:"Term1"),
quiz("Q7", question:[トゥイードゥルディーとトゥイードゥルダムは双子で見分けがつかないが,好みが違う.
- トゥイードゥルディーはケーキに600円,コーヒーに100円の支払意思額,
- トゥイードゥルダムはケーキに700円,コーヒーに500円の支払意思額を持っている.
このとき,彼らの支払う金額の合計が最大になるようなメニューを考えなさい.
], answer:[難しくない], commentary:[], point:12, category:"Term1"),
quiz("Q8",question:[
ある時点における需要曲線が下図の点線で表されるとする.このとき,あるショックが起き,どんな価格についても需要量が増加したという.このとき,ショック後の需要曲線として最も適当なものを次の図から選びなさい.ただしショック後の需要曲線は実線で描いている.
#image("img/Q8_img.png")
],answer:[],point:3, category:"Term1"),
quiz("Q9",question:[A氏はX社に入社すると2000万円,Y社に入社すると1500万円,Z社に入社すると3000万円の収入を得ることができるとする.彼はこのうちX社とY社には入社できるがZ社には入社できない.また同時に二社以上には就職できないものとする. 彼は今まで教育費用に7億円を費やしてきた.一方でA氏は現在就職していない.就職せずにニートでいることの効用は0である.このことから就職することによって心理的な費用がかかるようである.この心理的な費用はいくら以上であると考えられるか答えなさい.ただしこの問題文に出てきていない要素は無視して良いものとする.], category:"Term1"),
quiz("Q10",question:[従量税が$t$だけ課される財を考える.このとき,課税の死荷重損失の大きさを図示しなさい.
],category:"Term1"),
quiz("Q11",question:[鶏卵の価格と取引量が次のようになっていた
- 1月1日: 価格100, 取引量140
- 3月1日: 価格120, 取引量100
- 5月1日: 価格200, 取引量80
また,1月15日は鳥インフルエンザにより大量の鶏の殺処分が行われ,3月15日には鶏の餌代の価格が上昇したという.
以上の事柄からわかることとして最も適当なものを以下の中から一つ選び,その理由を説明しなさい.
+ 鶏卵の需要曲線は右下がりである.
+ 鶏卵の需要曲線は右上がりである.
+ 鶏卵の供給曲線は右下がりである.
+ 鶏卵の供給曲線は右上がりである.
ただし,需要と供給のパターンは以下の4つであるとする.
#image("img/patterns.png")],category:"Term1"),
quiz("Q12",question:[ある航空会社が航空機の運行のため,燃料を10億円分購入した.しかし,その直後,COVID2019の流行により,しばらくの間,燃料が使用される見込みがなくなった.また,全世界的に燃料の需要が低下したため,この燃料を転売することは二年間,不可能となった.一方,この燃料を用いたその他の事業は可能である.その他事業は複数種類あり,事業によってこの燃料を使う量は異なる.このときの燃料を購入した費用は固定費用と言えるか,また埋没費用と言えるか,答えなさい.],category:"Term1"),
quiz("Q13",question:[第1財と第2財しか購入しない消費者を考える.2024年時点では,第1財に全ての所得を使った場合,第1財を三十単位購入可能であった.また,2024年時点では消費者は第2財を三単位購入している.2025年時点では第1財の価格が増加した一方,所得も増加した.結果として,2025年には第1財に全ての所得を使った結果,第1財を三十単位購入することが可能である.このとき,この消費者の効用は2024年から25年にかけて増加するか,図を用いて理由を含めて答えなさい.ただし,2024年の意思決定と2025年の意思決定は独立であるとし,また消費者の無差別曲線は全く変わらないものとする.],category:"Term2"),
quiz("Q14", question:[財が二種類しかないとする.一つの財が上級財である場合,もう一つの財は下級財である.これは正しいか?], category:"Term2"),
quiz("Q15", question:[財が二種類しかないとする.一つの財が下級財である場合,もう一つの財は上級財である.これは正しいか?], category:"Term2"),
quiz("Q16", question:[消費プラン$w$と$w'$が無差別であるとはどう言うことか,効用関数$u$を用いて答えなさい.
], category:"Term2"),
quiz("Q17", question:[効用を最大化する消費プランにおいて,無差別曲線と予算制約線が接する理由を図を用いて説明しなさい.], category:"Term2"),
quiz("Q18", question:[次のマウスを用いた架空の実験を考える.マウスのケージにはレバーが二つあり,そのレバーを押すと一定の量のエサが出る.それぞれのレバーをAとBと呼ぶ.レバーAを1回押すと通常のエサが1粒でてくるが,レバーBを押すとキニーネ入りのエサが3粒でる. レバーを押すことができる回数はAとBの合計で100回と決まっている.
+ マウスがどちらのレバーを押すかという問題は,消費者理論における効用最大化問題と解釈できる.レバーを押した時に出てくるエサの粒の個数とレバーを押すことができる回数はそれぞれ消費者の効用最大化問題の何に対応するかを理由を含めて答えなさい.
+ レバーを押すことができる回数が100回から120回に増えた.このとき,マウスがレバーAを押す回数は増加し,レバーBを押す回数は減少した.この行動の変化を無差別曲線と予算制約線を用いて図示しなさい.
+ 2の結果から通常のエサとキニーネ入りのエサについて言えることのうち最も適当なものを次の中から選び,その理由を答えなさい.
#set enum(numbering: "a.")
+ 通常のエサはキニーネ入りのエサの粗補完財である.
+ 通常のエサはキニーネ入りのエサの粗代替材である.
+ 通常のエサは正常財(上級財)でキニーネ入りのエサは劣等財(下級財)である.
+ 通常のエサは劣等財(下級財)でキニーネ入りのエサは正常財(上級財)である.], category:"Term2"),
quiz("Q19", question:[無差別曲線が原点に向かって凸であるとする.いま,マグロとエビの寿司を何貫づつ食べるかと言う問題を考える.「マグロ1貫とエビ3貫の消費プラン」と「マグロ3貫とエビ1貫の消費プラン」が無差別であるとする.このとき,「マグロ2貫,エビ2貫と言う消費プラン」について言えることについて最も適当なものは次のうちどれか?
#set enum(numbering: "a.")
+ 「マグロ2貫,エビ2貫の消費プラン」は「マグロ1貫とエビ3貫の消費プラン」と「マグロ3貫とエビ1貫の消費プラン」のどちらよりも好ましい
+ 「マグロ2貫,エビ2貫の消費プラン」は「マグロ1貫とエビ3貫の消費プラン」と「マグロ3貫とエビ1貫の消費プラン」のどちらよりも好ましくない
+ 「マグロ2貫,エビ2貫の消費プラン」は「マグロ1貫とエビ3貫の消費プラン」より好ましいが,「マグロ3貫とエビ1貫の消費プラン」より好ましくない
+ 「マグロ2貫,エビ2貫の消費プラン」は「マグロ1貫とエビ3貫の消費プラン」より好ましくないが,「マグロ3貫とエビ1貫の消費プラン」より好ましい
+ 上記のうちいずれもいえない.], category:"Term2"),
quiz("Q20", question:[粗補完財と粗代替財の違いを例を挙げて述べなさい.], category:"Term2"),
quiz("Q21", question:[代替財と粗代替財の違いを例を挙げて述べなさい.], category:"Term2"),
quiz("Q22", question:[2種類しか財がないとする.このとき,一方が必需財であればもう一方は贅沢財である.これは常に正しいか?], category:"Term2"),
quiz("Q23", question:[二日間しか生きない人の貯蓄問題を考える.1日目の消費と2日目の消費が粗代替財でかつ両方とも上級財であるとき,利子率の増加は貯蓄を増加させるかどうか説明しなさい.], category:"Term2"),
quiz("Q24", question:[消費と余暇の選択問題を考える.余暇が下級財であるとき,時給の増加は余暇を増やすかどうか,説明しなさい.], category:"Term2"),
quiz("Q25", question:[ある価格と所得の組み合わせで下級財になっている財があるとする.このとき,効用関数をうまく作ればどんな価格と所得の組み合わせでも下級財になるようにできる.これは正しいか?], category:"Term2"),
quiz("Q26", question:[ギッフェン財は下級財である.これは正しいか?], category:"Term2"),
quiz("Q27", question:[財1と財2が代替財でも粗補完財になる可能性はある.これは正しいか?], category:"Term2"),
quiz("Q28", question:[財1と財2が代替財であるが粗補完財であるとする.このときどちらかの財は下級財である.これは正しいか?], category:"Term2"),
quiz("Q29", question:[財が2種類しかないとする.財1がギッフェン財であれば,財2は財1の粗補完財である.これは正しいか?], category:"Term2"),
quiz("Q30", question:[#kuranenv[以下の文章の空欄ア〜カを埋めなさい.
総費用関数を$C(q)= 7 q^3-5 q^2+ 3q+16$とする.
このとき,可変費用(変動費用)は #kuran() である.
価格が,$ #kuran() (q_1)^2- #kuran() q_1+ #kuran()$ を下回れば,操業を停止した方が良い.また,価格が $ #kuran(n:2) (q_2)^2- #kuran(n:3) q_2+ #kuran(n:4)$ を下回ると利潤がマイナスになる.
ただし,$q_1$は方程式,#kuran() の解のうち正のものであり,$q_2$は方程式,#kuran() の解のうち,実数のものである.]], category:"Term3"),
quiz("Q31", question:[$y$だけの財を生産するために必要な生産要素の投入組(生産プラン)について,費用を最小にする点において等産出量曲線(等量曲線)と等費用線が接する理由を説明しなさい.], category:"Term3"),
quiz("Q32", question:[#kuranenv[以下の文章の空欄アとイを埋めなさい.ただしどちらにも数字が入る.
総費用関数を$C(q)= 2 q^3-4 q^2+ 7q+16$とする.
このとき,固定費用は #kuran() である.
また,価格が,$#kuran() $ を下回れば,操業を停止した方が良い.
]], category:"Term3"),
quiz("Q33", question:[同じ生産量を生産するとき,長期の費用は必ず短期の費用を下回るか同じかである.これは正しいか?], category:"Term3"),
quiz("Q34", question:[生産関数が規模に関して収穫逓増であれば,価格受容者の企業にとっては生産要素を無限に投入することができるのであればそうするのが良い.これは正しいか?], category:"Term3"),
quiz("Q35", question:[生産関数が規模に関して収穫逓減であれば,価格受容者の企業にとっては生産要素を0にするのが良い.これは正しいか?], category:"Term3"),
quiz("Q36", question:[ある価格と生産要素価格において利潤が正であるとする.このとき,生産関数が規模に関して収穫逓増であれば,価格受容者の企業にとっては生産要素を無限に投入することができるのであればそうするのが良い.これは正しいか?], category:"Term3"),
quiz("Q37", question:[企業の利潤最大化問題では限界生産物と実質要素価格が等しくなるが,消費者の効用最大化問題では限界効用と価格が等しくなるとは限らない.この違いが生じる理由は何か?], category:"Term3"),
quiz("Q38", question:[#kuranenv[いま,経済の構成員がアダム,イヴ,ルツの三人だとする.可能な選択肢はx, y, z, w, vの5つであるとしよう.各選択肢から得られる各構成員の効用は次の表の通りであるとする.
#align(center)[
#table(columns:(4em,auto,auto,auto,auto,auto),
[名前],[x],[y],[z],[w],[v],
[アダム],[2],[2],[1],[8],[1],
[イヴ],[3],[8],[6],[9],[3],
[ルツ],[4],[4],[20],[1],[4]
)
]
+ 功利主義型社会厚生を最大にする選択肢を全て選びなさい.
+ ナッシュ型社会厚生を最大にする選択肢を全て選びなさい.
+ マキシミン型社会厚生を最大にする選択肢を全て選びなさい.
+ パレート効率的な選択肢を全て選びなさい.]], category:"Term4"),
quiz("Q39", question:[第一厚生定理(厚生経済学の第一基本定理)の主張を1行で説明しなさい.
], category:"Term4"),
quiz("Q40", question:[エッジワースボックス中の配分について,パレート効率的な配分とそうでない配分を図示し,それらがなぜそう言えるかを説明しなさい.
], category:"Term4"),
quiz("Q41", question:[財が2種類しかないとする.財$x$の需要関数が,$d_x (p_x,p_y)=20-4p_x+p_y$, 財$y$の需要関数が$d_y (p_x,p_y)=12+p_x-4p_y$とし,財$x$の供給量が$5$, 財$y$の供給量が$3$だとする.このとき,市場均衡の財$x$と$y$の価格を求めなさい.], category:"Term4"),
quiz("Q42", question:[第一厚生定理が成り立つ理由をエッジワースボックスを用いて説明しなさい.], category:"Term4"),
quiz("Q43", question:[第二厚生定理(厚生経済学の第一基本定理)の主張を1行で説明しなさい.], category:"Term4"),
quiz("Q44", question:[第二厚生定理が成り立つ理由をエッジワースボックスを用いて説明しなさい.
], category:"Term4"),
quiz("Q45", question:[純粋交換経済におけるワルラス均衡とはどのようなものか,消費者が二人,財の数が二人のケースで説明しなさい.], category:"Term4"),
quiz("Q46", question:[固定費用が負のとき,損益分岐点と操業停止点の関係はどのようになるか?], category:"Term3"),
quiz("Q47", question:[ある財の需要曲線が需要法則を満たすとする.その財の価格が120円から100円に価格が変化したとき,需要量は4000から4800に変化した. この財の価格が120円から130円に変化するとき,需要量の増加量として最も適当なものは以下のいずれか?
+ $800$
+ $400$
+ $130$
+ $-800$
], category:"Term1"),
quiz("Q48", question:[短期の企業の決定を考える.以下のうち,損益分岐点の価格と操業停止点の両方を変化させるのはどれか?ただし,総費用関数は変わらないものとする.
+ 補助金を生産量にかかわらず一定金額を与える.
+ 赤字が発生したとき,その30%を補填する補助金を与える.
+ 操業を停止すること(つまり生産量を0にすること)に対して,固定費用の30%の補助金を与える.
+ 生産量が0でない限り,固定費用の30%の補助金を与える.
], category:"Term3"),
quiz("Q49", question:[規模に関して収穫一定であるとき,利潤を最大にする要素投入量の組み合わせは一般に複数ある.これは正しいか?その理由を説明しなさい.ただし,要素投入量は正であると考える.], category:"Term3"),
quiz("Q50", question:[消費と余暇の選択問題を考える.消費と余暇が代替関係にあるとする.このとき余暇が時給の増加に伴って増えるのであれば余暇は上級財であるか?説明しなさい.], category:"Term2"),
quiz("Q51", question:[以下のある学生の意見を聞いて,その疑問を解消しなさい.
「消費と余暇の選択問題を考えるとき時給は実質余暇の価格と考えられます.時給が増えると余暇が増えるということは価格が増えると需要が増えるということなので余暇はギッフェン財っぽいですね.でもこのとき余暇は上級財ですよね.しかしギッフェン財は下級財とおっしゃいました.矛盾しませんか?」
], category:"Term2"),
quiz("Q52", question:[第一厚生定理より,市場均衡の配分がパレート効率的であるということは,市場均衡以外の配分を持ってきたとき,これを市場均衡の配分に変えれば全員が得をすることができる.これは正しいか?], category:"Term4"),
quiz("Q53", question:[第二厚生定理より,市場均衡以外の配分を持ってきたとき,全員が得をするような別の配分を見つけることができて,それは市場均衡の配分である.これは正しいか?], category:"Term4"),
quiz("Q54", question:[第二厚生定理より,市場均衡以外の配分を持ってきたとき,全員が得をするような別の配分を見つけることができる.これは正しいか?], category:"Term4"),
quiz("Q55", question:[財が二種類しかないとする.財1と財2が代替的で,財2が下級財とする.このとき財2は財1の粗補完財である.これは正しいか?], category:"Term2")
)
#tests_gen(Quiz, style:"both")
|
|
https://github.com/mintyfrankie/brilliant-CV | https://raw.githubusercontent.com/mintyfrankie/brilliant-CV/main/template/modules_en/skills.typ | typst | Apache License 2.0 | // Imports
#import "@preview/brilliant-cv:2.0.3": cvSection, cvSkill, hBar
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#cvSection("Skills")
#cvSkill(
type: [Languages],
info: [English #hBar() French #hBar() Chinese],
)
#cvSkill(
type: [Tech Stack],
info: [Tableau #hBar() Python (Pandas/Numpy) #hBar() PostgreSQL],
)
#cvSkill(
type: [Personal Interests],
info: [Swimming #hBar() Cooking #hBar() Reading],
)
|
https://github.com/tibs245/template-typst-CV | https://raw.githubusercontent.com/tibs245/template-typst-CV/main/README.md | markdown | # Mon CV en Typst
[Exemple of result in release V1](https://github.com/tibs245/template-typst-CV/releases/download/v1/CV-Thibault.Barske-blue.pdf)
> If you click on release V1 you can see differents colors generations examples
## Pourquoi faire mon CV en Typst ?
1. Mon dossier de compétences sous word à mal vieilli
- Template cassé
- Problème de polices
- Changement de template compliqué
- Transfert de données fastidieux
2. La réutilisation : J'ai la possibilité de générer ce CV a partir de fichiers
YML qui peuvent alimenter des pages web et autres
3. Je peux modifier mes templates facilement
- Pour m'adapter a une entreprise ou l'image que je souhaites renvoyer
4. Versionning via Git
5. Si vous faites des templates de CV plus élaboré après je pourrai m'en
reservir facilement 😄
## Quick Start
- Copy / Paste "author_example.yml" in "author.yml" with your own data
- Replace skills with ours in `main.typ`
- You can change your color with `primaryColor` in template
- Delete all missions and add yours
- Edit template with yours preferences ☺️
## To improve
- Organize icons by category
- Add yaml for all skill and use store to add in main.typ _(Better to improve
collaboration)_
- Add `skillsToImprove` logics
- Add automatics summary for relevant mission
- Add annotation for all missions relevant
- I need to think it again
|
|
https://github.com/RY997/Thesis | https://raw.githubusercontent.com/RY997/Thesis/main/thesis_typ/appendix.typ | typst | MIT License | *User 1*
- What do you think of the overall Iris exercise adaptation feature? Can it be useful for the real work of editor or is it a redundant feature and not very helpful?
- I find the Iris exercise adaptation feature quite useful, particularly for editing programming exercises. It offers a convenient way to customize exercises to different skill levels, making content more effective. This feature is far from redundant; it enhances the relevance and challenge of exercises, which is essential for both students and tutors/instructors.
- What needs to be improved? Which aspect is good?
- Iris sometimes struggled to interpret my prompts accurately, which could be improved. While its response time could be faster, I find it less critical. However, Iris's ability to adapt exercises remains as a strong point.
- What kind of tasks will you prefer to do by yourself instead of using Iris?
- For tasks like making minor manual code adjustments, such as removing or replacing snippets within functions, I'd prefer to handle them myself rather than using Iris.
- What kind of tasks will you prefer to let Iris do it?
- I'd let Iris handle tasks such as generating additional test cases, elaborating problem statements with clear explanations, and adding comments to the code for better understanding.
*User 2*
So what IRIS is good at is all the small stuff, like generating the algorithm for sorting etc and generating a nice theme and good explanantions for methods or tasks. What it does bad is that it fails with the consistent changes to all the files. I would maybe do it so that you could have more steps in between to check what IRIS is doing (good or bad) and also be able to specify better that it only has to change one part (e.g. a function)
In general i would say: Change the editor before IRIS and try to copy what copilot in VSCode does
*User 3*
The first request I made to Iris (to change from Binary to Jump Search) was handled well. However, it seems that it didn't understand the subsequent task at all. If it performs as it did with the first request, I would use it for significant changes, such as themes, and types of exercises changes, and would handle minor issues myself. But if it behaves as it did with all other requests I made, except the first one, then I wouldn't use it at all.
Overall, it seems that the understanding of my requests didn't work out as expected. It appeared that the second change to an exercise was consistently unsuccessful.
*User 4*
Iris is good at adapting exercise to meet specific and actionable requirements, making her the ideal choice for this scenario. However, for minor adjustments, I prefer handling them by myself.
*User 5*
The response time of Iris is somewhat slow, and I'm unable to resize Iris from the right side; only the left side can be adjusted, which is a bit inconvenient. |
https://github.com/chilingg/kaiji | https://raw.githubusercontent.com/chilingg/kaiji/main/template/main.typ | typst | Other | #let font_size_list = (16pt, 12pt, 9pt, 7pt);
#let font_cfg = (
font: "Source Han Serif",
weight: "light",
tracking: 0.1em,
lang: "zh"
)
#let sans_font_cfg = (
font: "Source Han Sans",
weight: "medium"
)
#let thin_line = 0.6pt
#let normal_line = 1pt
#let parenthese_numbers = ("⑴","⑵","⑶","⑷","⑸","⑹","⑺","⑻","⑼","⑽","⑾","⑿","⒀","⒁","⒂","⒃","⒄","⒅","⒆","⒇")
#let base_style(body) = [
#set page(margin: (x: 6em))
#set text(..font_cfg, size: font_size_list.at(2), tracking: 0.1em)
#set par(justify: true, leading: 0.8em)
#set list(indent: 0em, marker: none)
#set enum(indent: 0em)
#set line(stroke: thin_line)
#set rect(stroke: thin_line)
#show figure.where(
kind: image,
): it => box()[
#let n = counter(figure.where(kind: image)).at(it.location()).at(0)
#text(..sans_font_cfg, tracking: 0em)[⬜#(n + 500) #it.caption.body]
#it.body
]
#let chapter_title_interval = 32pt
#show heading.where(level: 1): it => {
if it.outlined {
return block(above: chapter_title_interval, below: chapter_title_interval)[
#set text(..sans_font_cfg, size: font_size_list.at(0), weight: "medium", tracking: 0em)
#counter(heading).display()
#it.body
]
} else {
let trancking = if it.has("label") and it.label == <wide_title> {
2em
} else {
0em
}
return text(size: font_size_list.at(0), weight: "medium", tracking: trancking)[#it.body]
}
}
#show heading.where(level: 2): it => {
if it.outlined {
return block(above: chapter_title_interval, below: chapter_title_interval)[
#set text(..sans_font_cfg, size: font_size_list.at(1), weight: "medium", tracking: 0em)
#counter(heading).display()
#it.body
]
} else {
let trancking = if it.has("label") and it.label == <wide_title> {
2em
} else {
0em
}
return text(size: font_size_list.at(1), weight: "medium", tracking: trancking)[#it.body]
}
}
#show heading.where(level: 3): it => [
#set text(..sans_font_cfg, size: font_size_list.at(2))
#it.body
]
#show <sans_font>: it => [
#set text(..sans_font_cfg)
#it
]
#show <center>: it => {
align(center)[#it]
}
#body
]
#let main_body(body) = [
#set page(
numbering: "1",
footer: locate(loc => {
let place = if calc.odd(counter(page).at(loc).first()){
right
} else {
left
}
return align(place)[#counter(page).display()]
})
)
#set heading(
outlined: true,
numbering: (..nums) => "61" + nums
.pos()
.map(str)
.join("-"),
)
#base_style(body)
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pad_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Pad can grow.
#pad(left: 10pt, right: 10pt)[PL #h(1fr) PR]
|
https://github.com/MultisampledNight/flow | https://raw.githubusercontent.com/MultisampledNight/flow/main/src/callout.typ | typst | MIT License | #import "gfx.typ"
#import "palette.typ": *
#let _callout(body, accent: fg, marker: none) = {
let body = if marker == none {
body
} else {
let icon = gfx.markers.at(marker).icon
grid(
columns: (1.5em, auto),
gutter: 0.5em,
align: (right + horizon, left),
icon(invert: false),
body,
)
}
block(
stroke: (left: accent),
inset: (
left: if marker == none { 0.5em } else { 0em },
y: 0.5em,
),
body,
)
}
#let question = _callout.with(
accent: status.unknown,
marker: "?",
)
#let remark = _callout.with(
accent: status.remark,
marker: "i",
)
#let hint = _callout.with(
accent: status.hint,
marker: "o",
)
#let caution = _callout.with(
accent: status.urgent,
marker: "!",
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/024_Shadows%20over%20Innistrad.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Shadows over Innistrad", doc)
#include "./024 - Shadows over Innistrad/001_Under the Silver Moon.typ"
#include "./024 - Shadows over Innistrad/002_A Gaze Blank and Pitiless.typ"
#include "./024 - Shadows over Innistrad/003_Unwelcome.typ"
#include "./024 - Shadows over Innistrad/004_Sacrifice.typ"
#include "./024 - Shadows over Innistrad/005_The Mystery of Markov Manor.typ"
#include "./024 - Shadows over Innistrad/006_The Drownyard Temple.typ"
#include "./024 - Shadows over Innistrad/007_Promises Old and New.typ"
#include "./024 - Shadows over Innistrad/008_Liliana's Indignation.typ"
#include "./024 - Shadows over Innistrad/009_Games.typ"
#include "./024 - Shadows over Innistrad/010_The Lunarch Inquisition.typ"
#include "./024 - Shadows over Innistrad/011_Stories and Endings.typ"
#include "./024 - Shadows over Innistrad/012_I Am Avacyn.typ"
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Physique_Mecanique_1.typ | typst | #import "@preview/bubble:0.1.0": *
#import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2": canvas, draw, tree
#import "@preview/cheq:0.1.0": checklist
#import "@preview/typpuccino:0.1.0": macchiato
#import "@preview/wordometer:0.1.1": *
#import "@preview/tablem:0.1.0": tablem
#show: bubble.with(
title: "Physique Mecanique 1",
subtitle: "18/09/2024",
author: "<NAME>",
affiliation: "EPFL",
year: "2024/2025",
class: "Génie Mécanique",
logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"),
)
#set page(footer: context [
#set text(8pt)
#set align(center)
#text("page "+ counter(page).display())
]
)
#set heading(numbering: "1.1")
#show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em)
= Rappels
La résistance à la mise en mouvement dépend de la géométrie.
$mat(p, F; L_0, M_0)$
$L_0 = m vec(v) and d$
= Action-Réaction
$ arrow(F)^(i arrow j) = - arrow(F)^(j arrow i) $
$ m_1dot(arrow(v))_1 = arrow(F)_1^("ext") + arrow(F)^(2 arrow 1) + arrow(F)^(3 arrow 1) $
$ m_2dot(arrow(v))_2 = arrow(F)_2^("ext") + arrow(F)^(1 arrow 2) + arrow(F)^(3 arrow 2) $
$ m_3dot(arrow(v))_3 = arrow(F)_3^("ext") + arrow(F)^(2 arrow 3) + arrow(F)^(1 arrow 3) $
= Moment de force
$ arrow(M)_0 colon.eq sum_alpha arrow(O P)_alpha and arrow(F)_alpha $
= Moment cinétique
$ arrow(L_0) colon.eq sum_alpha arrow(O P)_alpha and m arrow(v)_alpha $
= Loi de Newton en rotation
$ d/(d t) (arrow(L)_0) = arrow(M)_0 $
$ = sum dot(arrow( O P)) and m arrow(v) + sum arrow(O P) and m dot(arrow(v)) $
$ = sum arrow(v) and m arrow(v) + sum arrow(O P) and arrow(F) $
= Dérivée du produit scalaire
$ d/(d t) (arrow(a) dot arrow(b) ) = dot(arrow(a)) dot arrow(b) + arrow(a) dot dot(arrow(b))) $
= Dérivée du produit vectoriel
$ d/(d t) (arrow(a) and arrow(b) ) = dot(arrow(a)) and arrow(b) + arrow(a) and dot(arrow(b))) $
= Exercice le singe et la balle
$ dot(v_x) = 0 $
$ dot(v_z) = -g $
$ dot(x) = C_1 $
$ dot(z) = -g t + C_2 $
$ x = C_1 t + E $
$ z = -g/2 t² + C_2 t + E_2 $
$ C_1 = v_(x 0) = v_0 cos(theta) $
$ C_2 = v_(z 0) = v_0 sin(theta) $
$ E = x_0 $
$ E_2 = z_0 $
|
|
https://github.com/valentinvogt/npde-summary | https://raw.githubusercontent.com/valentinvogt/npde-summary/main/src/chapters/01.typ | typst | #import "../setup.typ": *
#show: thmrules
= Second-Order Scalar Elliptic Boundary Value Problems
<ch:01>
#counter(heading).step(level: 2)
== Quadratic Minimization Problems
<sub:quadratic-minimization-problems>
#v(0.2cm)
In the following, let $V$ be a vector space over $bb(R)$.\
#mybox(
"Linear forms",
)[
$ell : V arrow.r bb(R)$ is a #emph[linear form / linear functional] $arrow.l.r.double.long$
#neq(
$ ell (alpha u + beta v) = alpha ell (u) + beta ell (v) wide forall u , v in V , forall alpha , beta in RR $,
)
]
#v(-1cm)
#let bs = colMath("s", rgb("2900d3"))
#let bt = colMath("t", rgb("2900d3"))
#mybox(
"Bilinear forms",
)[
$a : V times V arrow.r bb(R)$ is a #emph[bilinear form] $arrow.l.r.double.long$
#neq(
$ a \( &bs u_1 + u_2 , bt v_1 + v_2 \)\
& = bs bt dot.op a (u_1 , v_1) + bs a (u_1 , v_2) + bt a (u_2 , v_1) + a (u_2 , v_2) forall u_1 , u_2 , v_1 , v_2 in V , forall bs , bt in bb(R) $,
)
]
#v(-1cm)
#mybox(
"Positive definiteness",
)[
A bilinear form $a : V times V arrow.r bb(R)$ is #emph[positive definite] if
$ u in V \\ { bold(0) } arrow.l.r.double.long a (u , u) > 0 $
It is #emph[positive semi-definite] if
$ a (u , u) & gt.eq 0 quad forall u in V $
]
#v(-1.1cm)
#mybox(
"Quadratic Functional",
)[
A #emph[quadratic functional] $J : V arrow.r bb(R)$ is defined by
#neq($ J (u) := 1 / 2 a (u , u) - ell (u) + c, quad u in V $)
where $a : V times V arrow.r bb(R)$ a symmetric bilinear form, $ell : V arrow.r bb(R)$ a
linear form and $c in bb(R)$.
]
#v(-1cm)
#mybox(
"Continuity of linear form",
)[
A linear form $ell : V arrow.r bb(R)$ is #emph[continuous / bounded] on $V$, if
#neq(
$ exists C > 0 quad lr(|ell (v)|) lt.eq C norm(v) quad forall v in V, $,
) <eq:continuity-linear-form>
where $norm(dot)$ is a norm on $V$.
]
== Sobolev Spaces
<sub:sobolev-spaces>
When we solve a minimization problem, we first need to define the space of
functions in which we look for the solution. For example, in Physics, we
generally want the solution to be continuous. E.g, a function describing the
shape of an elastic string should not have jumps.
It turns out that the correct space to describe our minimization problems is the #strong[Sobolev space];.
For functions $u$ in a Sobolev space, the bilinear form $a$ in the quadratic
functional is well defined (i.e., $a(u,u)<oo$). Hence the space in which we look
for minimizers is determined by the given quadratic functional. To select the
space for your problem, follow the guideline ...
#emph[Choose the largest space such that the problem is well defined];.
#mybox(
"Sobolev Spaces",
)[
$H^1_0 (Omega)$ is a vector space with norm
$ |v|_(H^1) := (integral_Omega norm(grad v)^2 dif bx)^(1 / 2) $
$H^1 (Omega)$ is another vector space with norm
$ norm(v)^2_(H^1) := norm(v)^2_(L^2) + |v|^2_(H^1) $
Note that $|dot|_(H^1)$ is not a norm on the space $H^1 (Omega)$, but a
seminorm.
Both spaces contain all functions for which the respective norm is finite (and, in the case
of $H^1_0 (Omega)$, which satisfy the boundary condition 0 on $partial Omega$).
]
*Alternative notation* for norms includes $norm(dot)_0$ for $norm(dot)_(L^2)$ and $|dot|_1$ for $|dot|_(H^1)$.
If the quadratic minimization problem is well defined, we get the following
lemma for existence and uniqueness of minimizers:
#theorem(
number: "1.3.3.6", "Existence of minimizers in Hilbert spaces",
)[
On a real Hilbert space $V$ with norm $norm(dot)_a$ for any
$norm(dot)_a$-bounded linear functional $ell : V arrow.r bb(R)$, the quadratic
minimization problem
#neq($ u_(\*) & = op("argmin", limits: #true)_(v in V) J (v)\
J (v) & := 1 / 2 norm(v)_a^2 - ell (v) $)
has a unique solution.
] <thm:existence-minimizer-hilbert>
Note that here, we use the bilinear form to define the norm
$norm(u)_a = sqrt(a (u , u))$. The main point is that we can see the bilinear
form of the quadratic minimization problem as the norm of some Sobolev space.
The above theorem guarantees that a solution exists in this space if the linear
form is bounded.
For checking boundedness we can often use Cauchy--Schwarz
(@eq:cauchy-schwarz-integrals) and Poincaré--Friedrichs
(@thm:poincare-friedrichs).
#pagebreak(weak: true)
== Linear Variational Problem
<sub:linear-variational-problem>
#definition(
number: "1.4.1.6", "Linear Variational Problem",
)[
Let $V$ be a vector (function) space, $mhat(V) subset V$ an affine space, and $V_0 subset V$ the
associated subspace. The equation
#neq(
$ #text("Find") u in mhat(V) med #text("such that") a (u , v) = ell (v) quad forall v in V_0 $,
) <eq:linear-variational-problem>
is called a (generalized) #emph[linear variational problem];, if
- $a : V times V_0 arrow.r bb(R)$ is a bilinear form
- $ell : V_0 arrow.r bb(R)$ is a linear form
]
@thm:existence-minimizer-hilbert tells us that the minimization problem has a
solution, but knowing that a solution exists is of course not enough: We want to
find it, but an infinite-dimensional minimization problem is hard to solve. To
make it easier, we reformulate the problems in a linear variational form
@eq:linear-variational-problem, which is quite close to something we can solve
numerically. To do this transformation, we use the following equivalence:
#theorem(
number: "1.4.1.8", "Equivalence of quadratic
minimization and linear variational problem",
)[
For a (generalized) quadratic functional $J (v) = 1 / 2 a (v , v) - ell (v) + c$ on
a vector space $V$ and with a symmetric positive definite bilinear form $a : V times V arrow.r bb(R)$ the
following is equivalent:
- The quadratic minimization problem for $J (v)$ has the unique minimizer $u_(\*) in mhat(V)$ over
the affine subspace $mhat(V) = g + V_0 , g in V$.
- The linear variational problem $ u in mhat(V) quad a (u , v) = ell (v) &quad forall v in V_0 $ has
the unique solution $u_(\*) in mhat(V).$
]<thm:variational-problem-equiv>
Note that the trial space $mhat(V)$, from which we pick a solution, and the test
space $V_0$ can be different. For an example of different trial and test spaces,
see @sub:boundary-conditions.
#pagebreak(weak: true)
== Boundary Value Problems
<sub:boundary-value-problems>
#lemma(
number: "1.5.2.1", "General product rule", ..unimportant,
)[
For all $bold(j) in (C^1 (overline(Omega)))^d , v in C^1 (overline(Omega))$ holds
#neq(
$ div (bold(j) v) = v div bold(j) + bold(j) dot.op grad v quad upright("in") Omega $,
)
] <thm:general-product-rule>
#lemma(
number: "1.5.2.4", "Gauss' Theorem",
)[
Let $bold(n) : partial Omega arrow.r bb(R)^d$ denote the exterior unit normal
vector field on $partial Omega$ and $dif S$ denote integration over a surface. We
have
#neq(
$ integral_Omega div bold(j (x)) dif bx = integral_(partial Omega) bold(j (x) dot.op n (x)) dif S (bx) quad forall bold(j) in (C_(upright(p w))^1 (overline(Omega)))^d $,
)
] <thm:gauss-theorem>
#lemma(
number: "1.5.2.7", "Green's first formula",
)[
For all vector fields $bold(j) in (C^1_"pw" (overline(Omega)))^d$ and functions $v in C^1_"pw" (overline(Omega))$ holds
#neq(
$ integral_Omega bold(j) dot.op grad v dif bx = - integral_Omega div bold(j) thin v dif bx + integral_(partial Omega) bold(j dot.op n) thin v dif S $,
)
] <thm:greens-formula>
#lemma(
number: "1.5.3.4", "Fundamental lemma of the calculus of variations",
)[
If $f in L^2 (Omega)$ satisfies
#neq(
$ integral_Omega f (bx) v (bx) dif bx = 0 quad forall v in C_0^oo (Omega), $,
)
then $f equiv 0$.
] <thm:fund-lemma>
We have seen that minimizing a quadratic functional is equivalent to solving a
linear variational problem @eq:linear-variational-problem. The variational
problem is called the #strong[weak form];. We can transform it (with extra
smoothness requirements) into the problem's #strong[strong form];, an elliptic
BVP (PDE with boundary conditions).
#tip-box(
"Weak to strong",
)[
+ Use @thm:greens-formula to get rid of derivatives on $v$ (e.g. turn $grad u dot grad v$ into $-div(grad u) +...$
+ Use properties of the test space (usually that $v=0$ on $partial Omega$) to get
rid of boundary terms
+ Use @thm:fund-lemma to remove the integrals and test functions
]
#pagebreak(weak: true)
#counter(heading).step(level: 2)
== Boundary Conditions
<sub:boundary-conditions>
For 2nd-order elliptic BVPs we need boundary conditions to get a unique
solution. To be more precise, we need #strong[exactly one] of the following
boundary conditions on every part of $partial Omega$.
#mybox("Main boundary conditions for 2nd-order elliptic BVPs")[
- #strong[Dirichlet]: $u$ is fixed to be
$g : partial Omega arrow.r bb(R)$
$ u = g quad upright("on") thin partial Omega $
- #strong[Neumann]: the flux $bold(j) = - kappa (bx) grad u$
through $partial Omega$ is fixed with
$h : partial Omega arrow.r bb(R)$
$ bold(j dot.op n) = - h quad upright("on") thin partial Omega $
- #strong[Radiation]: flux depends on $u$ with an increasing function
$Psi : bb(R) arrow.r bb(R)$
$ bold(j dot.op n) = Psi (u) quad upright("on") thin partial Omega $
]
In the weak form, Dirichlet conditions have to be imposed directly on the
*trial* space. The test space needs to be set to 0 wherever Dirichlet conditions
are given ("_Don't test where the solution is known_"). For example, trial and
test spaces for a standard Dirichlet problem are
$ V &= Set(u in C^1(Omega)&, && u=g "on" partial Omega) \
V_0 &= Set(v in C^1(Omega)&, && v=0 "on" partial Omega) $
Dirichlet BCs are called #strong[essential boundary conditions];.
Neumann conditions, which are only enforced through some term in the variational
equation, are called #strong[natural boundary conditions];.
There are some constraints on the boundary data:
#subtle-box[
- #strong[Admissible Dirichlet Data];: Dirichlet boundary values need to be
continuous.
- #strong[Admissible Neumann Data];: $h$ needs to be in $L^2 (Omega)$
(can be discontinuous)
]
The following theorem is frequently needed when dealing with integrals over the
boundary:
#theorem(
number: "1.9.0.19", title: "Theorem", "Multiplicative trace inequality",
)[
#neq(
$ exists C = C (Omega) > 0 : norm(u)_(L^2(partial Omega)) lt.eq C norm(u)_(L^2(Omega)) dot.op norm(u)_(H^1(Omega)) quad forall u in H^1 (Omega) $,
)
] <thm:mult-trace-inequality>
#pagebreak(weak: true)
== Second-Order Elliptic Variational Problems
<sub:second-order-elliptic-variational-problems>
We have seen how we can get from a minimization problem via a variational
problem to a BVP. Now we want to move in the opposite direction: from a PDE with
boundary conditions to a variational problem.
#tip-box(
"Strong to weak",
)[
+ Test the PDE with (multiply by $v$) and integrate over $Omega$
+ Use @thm:greens-formula to "shift" one derivative from $u$ to $v$ (e.g., from $-div(grad u)$ to $grad u dot grad v + ...$)
+ Use Neumann BC on boundary terms ($grad u dot n = h$)
+ Pick Sobolev trial/test spaces $V,V_0$ such that
- $a(u,u)$ is finite for $u in V,V_0$
- boundary conditions are satisfied ($u=g$ in $V$ $=>$ $v=0$ in $V_0$)
To fulfill the first condition, we can define the "base" space for both trial
and test as $Set(v, a(v,v)<oo)$, which is equal to $H^1$ for the usual $Delta u = f$ problem.
If there are extra (e.g., boundary) terms in $a$, try to bound these with the $H^1$ norm.
]
For Neumann problems there is a #strong[compatibility condition];. If we choose
test function $v equiv 1$ we get the requirement
$ - integral_(partial Omega) h dif S = integral_Omega f dif bx $
for the existence of solutions. Additionally, the solution of Neumann problems
is unique only up to constants. To address this we can use the constrained
function space
$ H_(\*)^1 (Omega) := { v in H^1 (Omega) : integral_Omega v dif bx = 0 } $
#theorem(
number: "1.8.0.20", title: "Theorem", [Second Poincaré--Friedrichs inequality],
)[
If $Omega subset bb(R)^d$ is bounded and connected, then
#neq(
$ exists C = C (Omega) > 0 : norm(u)_0 lt.eq C "diam" #h(-0.1pt) (Omega) thin norm(grad u)_0 quad forall u in H_(\*)^1 (Omega) $,
)
] <thm:poincare-friedrichs>
This theorem tells us that (under some conditions), the $L^2$ norm of functions
from this space is bounded by the $H^1$-seminorm.
|
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/decision-matrix.typ | typst | The Unlicense | #import "../colors.typ": *
#import "/utils.typ"
#let decision-matrix = utils.make-decision-matrix((properties, data) => {
set align(center)
let winning-row
for (index, choice) in data.values().enumerate() {
if choice.total.highest {
winning-row = index + 2
}
}
table(
stroke: none,
columns: properties.len() + 2,
fill: (_, row) => {
if row == winning-row { green }
else if calc.odd(row) { surface-3 }
else if calc.even(row) { surface-1 }
},
// Top line
table.hline(stroke: (cap: "round", thickness: 2pt)),
// Blank column to account for names of choices
[],
// Print out all the properties
..for property in properties {
([ *#property.name* ],)
},
// Last box in the row
[*Total*],
// Print out the data for each choice
..for (index, choice) in data {
(
[#index],
..for property in properties {
let value = choice.at(property.name)
([#value.weighted],)
},
[#choice.total.weighted]
)
},
//..for result in data {
// Override the fill if the choice has the highest score
//let cell = if choice.values.total.highest { cellx.with(fill: green) } else { cellx }
//(cell[*#choice.name*], ..for value in choice.values {
//(cell[#value.at(1).value],)
//})
//},
// Bottom line
table.hline(stroke: (cap: "round", thickness: 2pt)),
)
})
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/imp/analysis/dia.typ | typst | #import "/includes.typ":*
#import "@preview/prooftrees:0.1.0"
#let bisim = "≋"
#let conv(c, v) = { $#c arrow.b.double #v$ }
#let div(c) = { $#c arrow.t.double$ }
#let fails(c) = { $#c arrow.zigzag$ }
#linebreak()
=== Definite initialization analysis<subsection-imp-analysis_optimization-dia>
The first transformation we describe is *definite initialization analysis*. In
general, the objective of this analysis is to ensure that no variable is ever
used before being initialized, which is exactly the only kind of failure we
chose to model.
==== Variables and indicator functions<subsubsection-imp-dia-vars>
This analysis deals with variables. Before delving into its details, we show
first a function to compute the set of variables used in arithmetic and boolean
expressions. The objective is to come up with a _set_ of identifiers that appear
in the expression: we chose to represent sets in Agda using characteristic
functions, which we simply define as parametric functions from a parametric set
to the set of booleans, that is ```hs CharacteristicFunction = A -> Bool```;
later, we will instantiate this type for identifiers, giving the resulting type
the name of ```hs VarsSet```. First, we give a (parametric) notion of members
equivalence (that is, a function ```hs _==_ : A -> A -> Bool```); then, we the
usual operations on sets (insertion, union, and intersection) and the usual
definition of inclusion for characteristic functions.
#mycode(label: <code-charfun>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Data/CharacteristicFunction.agda#L13")[
//typstfmt::off
```hs
module Data.CharacteristicFunction {a} (A : Set a) (_==_ : A -> A -> Bool) where
-- ...
CharacteristicFunction : Set a
CharacteristicFunction = A -> Bool
-- ...
∅ : CharacteristicFunction
∅ = λ _ -> false
_↦_ : (v : A) -> (s : CharacteristicFunction) -> CharacteristicFunction
(v ↦ s) x = (v == x) ∨ (s x)
_∪_ : (s₁ s₂ : CharacteristicFunction) -> CharacteristicFunction
(s₁ ∪ s₂) x = (s₁ x) ∨ (s₂ x)
_∩_ : (s₁ s₂ : CharacteristicFunction) -> CharacteristicFunction
(s₁ ∩ s₂) x = (s₁ x) ∧ (s₂ x)
_⊆_ : (s₁ s₂ : CharacteristicFunction) -> Set a
s₁ ⊆ s₂ = ∀ x -> (x-in-s₁ : s₁ x ≡ true) -> s₂ x ≡ true
```
//typstfmt::on
]
#theorem(
name: "Equivalence of characteristic functions",
label: <thm-cf-equiv>
)[
(using the *Axiom of extensionality*)
#mycode(proof: <proof-cf-equiv>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Data/CharacteristicFunction.agda#L48")[
//typstfmt::off
```hs
cf-ext : ∀ {s₁ s₂ : CharacteristicFunction}
(a-ex : ∀ x -> s₁ x ≡ s₂ x) -> s₁ ≡ s₂
```
//typstfmt::on
]]
#theorem(name: "Neutral element of union",
label: <thm-if-neutral-union>)[
#mycode("https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Data/CharacteristicFunction.agda#L58")[
//typstfmt::off
```hs
∪-∅ : ∀ {s : CharacteristicFunction} -> (s ∪ ∅) ≡ s
```
//typstfmt::on
]]
#theorem(name: "Update inclusion")[
#mycode("https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Data/CharacteristicFunction.agda#L61")[
//typstfmt::off
```hs
↦=>⊆ : ∀ {id} {s : CharacteristicFunction} -> s ⊆ (id ↦ s)
```
//typstfmt::on
]]
#theorem(name: "Transitivity of inclusion", label: <thm-cf-trans> )[
#mycode("https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Data/CharacteristicFunction.agda#L87")[
//typstfmt::off
```hs
⊆-trans : ∀ {s₁ s₂ s₃ : CharacteristicFunction} -> (s₁⊆s₂ : s₁ ⊆ s₂)
-> (s₂⊆s₃ : s₂ ⊆ s₃) -> s₁ ⊆ s₃
```
//typstfmt::on
]]
We will also need a way to get a ```hs VarsSet``` from a ```hs Store```, which
is shown in @code-store-domain.
#mycode(label: <code-store-domain>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Syntax/Vars.agda#L35")[
//typsfmt::off
```hs
dom : Store -> VarsSet
dom s x with (s x)
... | just _ = true
... | nothing = false
```
//typstfmt::on
]
==== Realization<subsubsection-imp-dia-vars>
Following @concrete-semantics, the first formal tool we need is a way to
compute the set of variables mentioned in expressions, shown in
@code-avars and @code-bvars. We also need a function to compute the set of variables that
are definitely initialized in commands, which is shown in @code-cvars.
#grid(
columns: 2,
//align: center + horizon,
//auto-vlines: false,
//auto-hlines: false,
gutter: 5pt,
mycode(label: <code-avars>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Syntax/Vars.agda#L16")[
//typstfmt::off
```hs
avars : (a : AExp) -> VarsSet
avars (const n) = ∅
avars (var id) = id ↦ ∅
avars (plus a₁ a₂) =
(avars a₁) ∪ (avars a₂)
```
//typstfmt::on
],
mycode(label: <code-bvars>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Syntax/Vars.agda#L21")[
//typstfmt::off
```hs
bvars : (b : BExp) -> VarsSet
bvars (const b) = ∅
bvars (le a₁ a₂) =
(avars a₁) ∪ (avars a₂)
bvars (not b) = bvars b
bvars (and b b₁) =
(bvars b) ∪ (bvars b₁)
```
//typstfmt::on
])
#mycode(label: <code-cvars>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Syntax/Vars.agda#L27")[
//typstfmt::off
```hs
cvars : (c : Command) -> VarsSet
cvars skip = ∅
cvars (assign id a) = id ↦ ∅
cvars (seq c c₁) = (cvars c) ∪ (cvars c₁)
cvars (ifelse b cᵗ cᶠ) = (cvars cᵗ) ∩ (cvars cᶠ)
cvars (while b c) = ∅
```
//typstfmt::on
]
It is worth to reflect upon the definition of @code-cvars. This
code computes the set of _initialized_ variables in a command `c`; as
done in @concrete-semantics, we construct this set of initialized variables in
the most conservative way possible: of course, `skip` does not have any initialized
variable and `assign id a` adds `id` to the set of initialized variables.
However, when considering composite commands, we must consider that, except for
`seq c c₁`, not every branch of execution is taken; this means that we cannot
know statically whether `ifelse b cᵗ cᶠ` will lead to the execution to the
execution of `cᵗ` or `cᶠ`, we thus take the intersection of their initialized
variables, that is we compute the set of variables that will be surely
initialized wheter one or the other executes. The same reasoning applies to
`while b c`: we cannot possibly know whether or not `c` will ever execute, thus
we consider no new variables initialized.
At this point it should be clear that as `cvars c` computes the set of
initialized variables in a conservative fashion, it is not necessarily true
that the actual execution of the command will not add additional variables:
however, knowing that if the evaluation of a command in a store $sigma$
converges to a value $sigma'$, that is $#conv([$c$, $sigma$], $sigma'$)$ then by
@lemma-ceval-store-tilde[Lemma] $"dom" sigma subset.eq "dom" sigma'$;
this allows us to show the following lemma.
#lemma(label: <lemma-ceval-sc-subeq>)[
Let $c$ be a command and $sigma$ and $sigma'$ be two stores. Then
#align(center,
$#conv($"ceval" c space sigma$, $sigma'$) -> ("dom" sigma_1 union
("cvars" c)) space subset.eq ("dom" sigma')$)
#mycode(proof: <proof-ceval-sc-subeq>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Semantics/BigStep/Functional/Properties.agda#L133")[
//typstfmt::off
```hs
ceval⇓=>sc⊆s' : ∀ (c : Command) (s s' : Store) (h⇓ : (ceval c s) ⇓ s')
-> (dom s ∪ (cvars c)) ⊆ (dom s')
```
//typstfmt::on
]]
We now give inference rules that inductively build the relation that embodies
the logic of the definite initialization analysis, shown in @imp-dia-rel. In
Agda, we define a datatype representing the relation of type
//typstfmt::off
```hs Dia : VarsSet -> Command -> VarsSet -> Set```,
//typstfmt::on
which is shown in @code-dia. @lemma-ceval-sc-subeq[Lemma]
will allow us to show that there is a relation between the `VarsSet` in the
`Dia` relation and the actual stores that are used in the execution of a
command.
#figure(
tablex(
columns: 2,
align: center + horizon,
auto-vlines: false,
auto-hlines: false,
prooftrees.tree(prooftrees.axi[], prooftrees.uni[Dia v skip v]),
prooftrees.tree(
prooftrees.axi[avars $a$ $subset.eq$ $v$],
prooftrees.uni[Dia $v$ (assign $id$ $a$) ($id ↦ v$)],
),
prooftrees.tree(
prooftrees.axi(pad(bottom: 4pt, [Dia $v_1$ $c_1$ $v_2$])),
prooftrees.axi(pad(bottom: 4pt, [Dia $v_2$ $c_2$ $v_3$])),
prooftrees.nary(2)[Dia $v_1$ (seq $c_1$ $c_2$) $v_3$],
),
prooftrees.tree(
prooftrees.axi(pad(bottom: 2pt, [bvars $b$ $subset.eq$ $v$])),
prooftrees.axi(pad(bottom: 2pt, [Dia $v$ $c^t$ $v^t$])),
prooftrees.axi(pad(bottom: 2pt, [Dia $v$ $c^f$ $v^f$])),
prooftrees.nary(
3,
)[#pad(top: 2pt, [Dia $v$ (if $b$ then $c^t$ else $c^f$) ($v^t sect v^f$)])],
),
colspanx(2)[
#prooftrees.tree(
prooftrees.axi(pad(bottom: 3pt, [bvars $b$ $subset.eq$ $v$])),
prooftrees.axi(pad(bottom: 3pt, [Dia $v$ $c$ $v_1$])),
prooftrees.nary(2)[Dia $v$ (while $b$ $c$) $v$],
)
],
),
caption: "Inference rules for the definite initialization analysis",
supplement: "Table",
)<imp-dia-rel>
#mycode(label: <code-dia>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Analysis/DefiniteInitialization.agda#L22")[
//typstfmt::off
```hs
data Dia : VarsSet -> Command -> VarsSet -> Set where
skip : ∀ (v : VarsSet) -> Dia v (skip) v
assign : ∀ a v id (a⊆v : (avars a) ⊆ v) -> Dia v (assign id a) (id ↦ v)
seq : ∀ v₁ v₂ v₃ c₁ c₂ -> (relc₁ : Dia v₁ c₁ v₂) ->
(relc₂ : Dia v₂ c₂ v₃) -> Dia v₁ (seq c₁ c₂) v₃
if : ∀ b v vᵗ vᶠ cᵗ cᶠ (b⊆v : (bvars b) ⊆ v) -> (relcᶠ : Dia v cᶠ vᶠ) ->
(relcᵗ : Dia v cᵗ vᵗ) -> Dia v (ifelse b cᵗ cᶠ) (vᵗ ∩ vᶠ)
while : ∀ b v v₁ c -> (b⊆s : (bvars b) ⊆ v) ->
(relc : Dia v c v₁) -> Dia v (while b c) v
```
//typstfmt::on
]
What we want to show now is that if ```hs Dia``` holds, then the evaluation of
a command $c$ does not result in an error: while
@thm-adia-safe and @thm-bdia-safe show
that if the variables in an arithmetic expression or a boolean expression are
contained in a store the result of their evaluation cannot be a failure (i.e.
they result in "just" something, as it cannot diverge),
@thm-dia-safe shows that if ```hs Dia``` holds, then the
evaluation of a program failing is absurd: therefore, by
@post-exec, the program either diverges or converges to some
value.
#theorem( name: "Safety of arithmetic expressions", label: <thm-adia-safe>)[
#mycode(proof: <proof-adia-safe>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Analysis/DefiniteInitialization.agda#L47")[
//typstfmt::off
```hs
adia-safe : ∀ (a : AExp) (s : Store) (dia : avars a ⊆ dom s)
-> (∃ λ v -> aeval a s ≡ just v)
```
//typstfmt::on
]]
#theorem(name: "Safety of boolean expressions", label: <thm-bdia-safe>)[
#mycode(proof: <proof-bdia-safe>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Analysis/DefiniteInitialization.agda#L60")[
//typstfmt::off
```hs
bdia-safe : ∀ (b : BExp) (s : Store) (dia : bvars b ⊆ dom s)
-> (∃ λ v -> beval b s ≡ just v)
```
//typstfmt::on
]]
#theorem(
name: "Safety of definite initialization for commands",
label: <thm-dia-safe>
)[
#mycode(proof: <proof-dia-safe>, "https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Analysis/DefiniteInitialization.agda#L117")[
//typstfmt::off
```hs
dia-safe : ∀ (c : Command) (s : Store) (v v' : VarsSet) (dia : Dia v c v')
(v⊆s : v ⊆ dom s) -> (h-err : (ceval c s) ↯) -> ⊥
```
//typstfmt::on
]]
We now show an idea of the proof (the full proof, in Agda, is in
@proof-dia-safe), examining the two base cases `c ≡ skip` and `c ≡ assign id a`
and the coinductive case `c ≡ while b c'`. The proof for the base cases is, in
words, based on the idea that the evaluation cannot possibly go wrong: note
that by the hypotheses, we have that `(ceval c s) ↯`, which we can express in
math as $ceval space c space sigma bisim now nothing$.
#show figure.where(kind: "boxenv"): set block(breakable: true)
#proof[
1. Let $c$ be the command `skip`. Then, for any store $sigma$, by the
definition of `ceval` in @code-ceval and by the inference rule $arrow.b.double$skip in
@imp-commands-semantics, the evaluation of $c$ in the store $sigma$ must be
#align(center, $ceval "skip" sigma eq.triple now (just sigma)$)
Given the hypothesis that #fails([c, $sigma$]), we now have that it must be
$now nothing bisim now (just sigma )$, which is false for any $sigma$, making the hypothesis
#fails([c, $sigma$]) impossible.
2. Let $c$ be the command `assign id a`, for some identifier $id$ and
arithmetic expression $a$. By the hypothesis, we have that it must be $"Dia"
v space (assign id a) space v'$ for some $v$ and $v'$, which entails that
the variables that appear in $a$, which we named $"avars" a$, are all
initialized in $v$, that is $"avars" a subset.eq v$; this and the
hypothesis that $v subset.eq "dom" sigma$ imply by @thm-cf-trans
that $"avars" a subset.eq "dom" sigma$.
By @thm-adia-safe, with the assumption that $"avars" a subset.eq "dom" sigma$,
it must be $aeval a sigma eq.triple just n$ for some $n : ZZ$. Again, by the
definition of `ceval` in @code-ceval and by the inference rule $arrow.b.double$assign
in @imp-commands-semantics, the evaluation of $c$ in the store $sigma$ must be
#align(center, $ceval (assign id a) space sigma eq.triple now (just ("update"
id n space sigma))$)
and, as before, by the hypothesis that $c$ fails it must thus be that $now
nothing bisim now (just ("update" id n space sigma))$, which is impossible for any $sigma$,
making the hypotesis #fails([c]) impossible.
3. Let $c$ be the command `while b c'` for some boolean expression $b$ and
some command $c'$. By @thm-bdia-safe, with the assumption that $"bvars" b
subset.eq "dom" sigma$, it must be $"beval" b space sigma eq.triple "just" v$ for some
$v : BB$.
#linebreak()
If $v eq.triple "false"$, then by the definition of `ceval` in
@code-ceval and by the inference rule $arrow.b.double$while-false in
@imp-commands-semantics, the evaluation of $c$ in the store $sigma$ must be
#align(center, $ceval ("while" b space c') space sigma eq.triple now ("just" sigma)$)
making the hypothesis that the evaluation of $c$ fails impossible.
#linebreak()
If, instead, $v eq.triple "true"$, we must evaluate $c'$ in $sigma$.
The case $c' eq.triple now nothing$ is impossible by the inductive hypothesis.
#linebreak()
If $c' eq.triple now (just sigma')$ for some $sigma'$, then, by recursion, it must be
#align(center, [```hs dia-sound (while b c) s' v v dia (⊆-trans v⊆s (ceval⇓=>⊆ c s s' (≡=>≋ eq-ceval-c))) w↯```])
#linebreak()
Finally, if $c' eq.triple "later" x$ for some $x$, then we can prove inductively that
#mycode("https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Imp/Analysis/DefiniteInitialization.agda#L165", proof: <proof-dia-sound-while-later>)[
//typstfmt::off
```hs
dia-sound-while-later : ∀ {x : Thunk (Delay (Maybe Store)) ∞} {b c} {v}
(l↯⊥ : (later x)↯ -> ⊥) (dia : Dia v (while b c) v)
(l⇓s=>⊆ : ∀ {s : Store} -> ((later x) ⇓ s) -> v ⊆ dom s)
(w↯ : (bind (later x) (λ s -> later (ceval-while c b s))) ↯) -> ⊥
```
//typstfmt::on
] ]
The proof works by unwinding, inductively, the assumption that #fails([c]): if
it fails, then $ceval space c space sigma$ must eventually converge to $"now" space "nothing"$.
The proof thus works by showing base cases and, in the case of $"seq" space c_1 space c_2$
and $"while" space b space c' space eq.triple space "if" space b space "then" space ("seq" space c' space ("while" space b space c')) space "else" space "skip"$,
showing that by inductive hypotesis $c_1$ or $c'$ cannot possibly fail; then,
the assumption becomes that it is the second command ($c_2$ or $"while" space b space c'$)
that fails, which we can inductively show absurd.
#show figure.where(kind: "boxenv"): set block(breakable: false)
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/book/src/utils/side-by-side.typ | typst | #import "../../../polylux.typ": *
#set page(paper: "presentation-16-9")
#set text(size: 40pt)
#polylux-slide[
#side-by-side[
#lorem(7)
][
#lorem(10)
][
#lorem(5)
]
]
|
|
https://github.com/MattiaOldani/Informatica-Teorica | https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/12_riconoscibilità_automatica_insiemi.typ | typst | #import "../alias.typ": *
#import "@preview/lemmify:0.1.5": *
#let (
theorem, lemma, corollary,
remark, proposition, example,
proof, rules: thm-rules
) = default-theorems("thm-group", lang: "it")
#show: thm-rules
#show thm-selector("thm-group", subgroup: "theorem"): it => block(
it,
stroke: red + 1pt,
inset: 1em,
breakable: true
)
#show thm-selector("thm-group", subgroup: "proof"): it => block(
it,
stroke: green + 1pt,
inset: 1em,
breakable: true
)
= Riconoscibilità automatica di insiemi
Proviamo a dare una _gradazione_ sul livello di risoluzione dei problemi. Vogliamo capire se un dato problema:
- può essere risolto;
- non può essere risolto completamente (meglio di niente);
- non può essere risolto.
Costruiamo un programma che classifichi gli elementi di un insieme, quindi ci dica se un certo numero naturale appartiene o meno all'insieme.
Un insieme $A subset.eq NN$ è *riconoscibile automaticamente* se esiste un programma $P_A$ che classifica correttamente *ogni* elemento di $NN$ come appartenente o meno ad $A$, ovvero
$ x in NN arrow.long.squiggly P_A (x) = cases(1 & "se" x in A, 0 quad & "se" x in.not A) quad . $
Il programma $P_A$ deve essere:
- *corretto*: classifica correttamente gli elementi che riceve in input;
- *completo*: classifica tutti gli elementi di $NN$, nessuno escluso.
_Tutti gli insiemi sono automaticamente riconoscibili? Quali insiemi sono automaticamente riconoscibili? Quali invece non lo sono?_
Siamo certi che non tutti gli insiemi siano automaticamente riconoscibili, infatti grazie al concetto di _cardinalità_ sappiamo che:
- i sottoinsiemi di $NN$ sono densi come $RR$;
- io non ho $RR$ programmi quindi sicuramente c'è qualche insieme che non lo è.
== Insiemi ricorsivi
Un insieme $A subset.eq NN$ è un *insieme ricorsivo* se esiste un programma $P_A$ che si arresta su ogni input classificando correttamente gli elementi di $NN$ in base alla loro appartenenza o meno ad $A$.
Equivalentemente, ricordando che la funzione caratteristica di $A subset.eq NN$ è la funzione $ chi_A : NN arrow.long {0,1} $ tale che $ chi_A (x) = cases(1 "se" x in A, 0 "se" x in.not A) quad , $ diciamo che l'insieme $A$ è ricorsivo se e solo se $ chi_A in cal(T) . $
Che $chi_A$ sia totale è banale, perché tutte le funzioni caratteristiche devono essere definite su tutto $NN$. Il problema risiede nella calcolabilità di queste funzioni.
Le due definizioni date sono equivalenti:
- il programma $P_A$ implementa $chi_A$, quindi $chi_A in cal(T)$ perché esiste un programma che la calcola;
- $chi_A in cal(T)$ quindi esiste un programma $P_A$ che la implementa e che soddisfa la definizione data sopra.
=== Ricorsivo vs Decidibile
Spesso, si dice che _un insieme ricorsivo è un insieme decidibile_, ma è solo abuso di notazione. Questo è dovuto al fatto che ad ogni insieme $A subset.eq NN$ possiamo associare il suo *problema di riconoscimento*, così definito:
- Nome: $"RIC"_A$.
- Istanza: $x in NN$.
- Domanda: $x in A$?
La sua funzione soluzione $ Phi_("RIC"_A) : NN arrow.long {0,1} $ è tale che $ Phi_("RIC"_A) (x) = cases(1 & "se" x in A, 0 quad & "se" x in.not A) quad . $
Notiamo che la semantica del problema è proprio la funzione caratteristica, quindi $Phi_("RIC"_A) = chi_A$. Se $A$ è ricorsivo, allora la sua funzione caratteristica è ricorsiva totale, ma lo sarà anche la funzione soluzione $Phi$ e, di conseguenza, $"RIC"_A$ è decidibile.
=== Decidibile vs Ricorsivo
Simmetricamente, sempre con abuso di notazione, si dice che _un problema di decisione è un problema ricorsivo_. Questo perché ad ogni problema di decisione $Pi$ possiamo associare $A_Pi$ *insieme delle sue istanze a risposta positiva*.
Dato il problema
- Nome: $Pi$.
- Istanza: $x in D$.
- Domanda: $p(x)$?
definiamo $ A_Pi = {x in D bar.v Phi_Pi (x) = 1} "con" Phi_Pi (x) = 1 equiv p(x) $ insieme delle istanze a risposta positiva di $Pi$. Notiamo che, se $Pi$ è decidibile allora $Phi_Pi in cal(T)$, quindi esiste un programma che calcola questa funzione. La funzione in questione è quella che riconosce automaticamente l'insieme $A_Pi$, quindi $A_Pi$ è ricorsivo.
== Insiemi non ricorsivi
Per trovare degli insiemi non ricorsivi cerco nei problemi di decisione non decidibili. L'unico problema di decisione non decidibile che abbiamo visto è il *problema dell'arresto ristretto* $arresto(ristretto)$.
- Nome: $arresto(ristretto)$.
- Istanza: $x in NN$.
- Domanda: $phi_(ristretto) (x) = phi_x (x) arrow.b$?
Definiamo l'insieme delle istanze a risposta positiva di $arresto(ristretto)$ $ A = {x in NN bar.v phi_x (x) arrow.b}. $ Questo non può essere ricorsivo: se lo fosse, avrei un programma ricorsivo totale che mi classifica correttamente se $x$ appartiene o meno ad $A$, ma abbiamo dimostrato che il problema dell'arresto ristretto non è decidibile, quindi $A$ non è ricorsivo.
== Relazioni ricorsive
$R subset.eq NN times NN$ è una *relazione ricorsiva* se e solo se l'insieme $R$ è ricorsivo, ovvero:
- la sua funzione caratteristica $chi_R$ è tale che $chi_R in cal(T)$, oppure
- esiste un programma $P_R$ che, presi in ingresso $x,y in NN$ restituisce $1$ se $(x R y)$, $0$ altrimenti.
Un'importante relazione ricorsiva è la relazione $ R_P = {(x,y) in NN^2 bar.v P "su input" x "termina in" y "passi"} . $
È molto simile al problema dell'arresto, ma non chiedo se $P$ termina in generale, chiedo se termina in $y$ passi. Questa relazione è ricorsiva e per dimostrarlo costruiamo un programma che classifica $R_P$ usando:
- $U$ interprete universale;
- *clock* per contare i passi di interpretazione;
- *check del clock* per controllare l'arrivo alla quota $y$.
Definiamo quindi il programma $ overset(U,tilde) = U + "clock" + "check clock" $ tale che $ overset(U,tilde) equiv & "input"(x,y) \ & U(P,x) + "clock" \ & "ad ogni passo di" U(P,x): \ & quad "if clock" > y: \ & quad quad "output"(0) \ & quad "clock"++; \ & "output"("clock" == y) quad . $
Nel sistema RAM, ad esempio, per capire se l'output è stato generato o meno osservo se il PC, contenuto nel registro $L$, è uguale a 0.
Riprendiamo il problema dell'arresto ristretto: _come possiamo esprimere $A = {x in NN bar.v phi_x (x) arrow.b}$ attraverso la relazione ricorsiva $R_ristretto$?_
Possiamo definire l'insieme $ B = {x in NN bar.v exists y in NN bar.v (x R_ristretto y)}. $
Notiamo come $A = B$:
- $A subset.eq B$: se $x in A$ il programma codificato con $x$ su input $x$ termina in un certo numero di passi. Chiamiamo $y$ il numero di passi. $ristretto(x)$ termina in $y$ passi, ma allora $x R_ristretto y$ e quindi $x in B$;
- $B subset.eq A$: se $x in B$ esiste $y$ tale che $x R_ristretto y$, quindi $ristretto(x)$ termina in $y$ passi, ma allora il programma $ristretto = x$ su input $x$ termina, quindi $x in A$.
== Insiemi ricorsivamente numerabili
Un insieme $A subset.eq NN$ è *ricorsivamente numerabile* se è *automaticamente listabile*: esiste una _routine_ $F$ che, su input $i in NN$, dà in output $F(i)$ come l'$i$-esimo elemento di $A$.
Il programma che lista gli elementi di $A$ è: $ P equiv & i := 0; \ & "while" (1 > 0) space { \ & quad "output"(F(i)) \ & quad i := i + 1; \ & } $
Per alcuni insiemi non è possibile riconoscere tutti gli elementi che gli appartengono, ma può essere che si conosca un modo per elencarli. Alcuni insiemi invece non hanno nemmeno questa proprietà.
Se il meglio che posso fare per avere l'insieme A è listarlo con P, _come posso scrivere un algoritmo che "tenta di riconoscere" A?_ Questo algoritmo deve listare tutti gli elementi senza un clock di timeout: se inserissi un clock avrei un insieme ricorsivo per la relazione $R_P$ mostrata in precedenza.
Vediamo il programma di *massimo riconoscimento*: $ P equiv & "input"(x) \ & i := 0; \ & "while" (F(i) eq.not x) \ & quad i := i + 1; \ & "output"(1) quad . $
Come viene riconosciuto l'insieme $A$? $ x in NN arrow.long.squiggly P(x) = cases(1 & "se" x in A, "LOOP" quad & "se" x in.not A) quad . $
Vista la natura di questa funzione, gli insiemi ricorsivamente numerabili sono anche detti *insiemi parzialmente decidibili/riconoscibili* o *semidecidibili*.
Se avessi indicazioni sulla monotonia della routine $F$ allora avrei sicuramente un insieme ricorsivo. In questo caso non assumiamo niente quindi rimaniamo negli insiemi ricorsivamente numerabili.
=== Definizione formale
L'insieme $A subset.eq NN$ è *ricorsivamente numerabile* se e solo se:
- $A = emptyset.rev$ oppure
- $A = immagine(f)$, con $f : NN arrow.long NN in cal(T)$, ovvero $A = {f(0), f(1), f(2), dots}$.
Visto che $f$ è ricorsiva totale esiste un/a programma/routine $F$ che la implementa e che usiamo per il parziale riconoscimento di $A$: questo programma, se $x in A$, prima o poi mi restituisce 1, altrimenti entra in loop.
È come avere un _libro con infinite pagine_, su ognuna delle quali compare un elemento di $A$. Il programma di riconoscimento $P$, grazie alla routine $F$, non fa altro che sfogliare le pagine $i$ di questo libro alla ricerca di $x$:
- se $x in A$ prima o poi $x$ compare nelle pagine del libro come $F(i)$;
- se $x in.not A$ sfoglio il libro all'infinito, non sapendo quando fermarmi.
=== Caratterizzazioni
#theorem(numbering: none)[
Le seguenti definizioni sono equivalenti:
+ $A$ è ricorsivamente numerabile, con $A = immagine(f)$ e $f in cal(T)$ funzione ricorsiva totale;
+ $A = dominio(f)$, con $f in cal(P)$ funzione ricorsiva parziale;
+ esiste una relazione $R subset.eq NN^2$ ricorsiva tale che $A = {x in NN bar.v exists y in NN bar.v (x,y) in R}$.
]
#proof[
\ Per dimostrare questi teoremi dimostriamo che $1 arrow.long.double 2 arrow.long.double 3 arrow.long.double 1$, creando un'implicazione ciclica.
#block(
fill: rgb("#9FFFFF"),
inset: 8pt,
radius: 4pt,
[$1 arrow.long.double 2$]
)
Sappiamo che $A = immagine(f)$, con $f in cal(T)$, è ricorsivamente numerabile, quindi esistono la sua routine di calcolo $f$ e il suo algoritmo di parziale riconoscimento $P$, definiti in precedenza. Vista la definizione di $P$, abbiamo che $ phi_P (x) = cases(1 "se" x in A, bot "se" x in.not A) quad , $ ma allora $A = dominio(phi_P)$: il dominio è l'insieme dei valori dove la funzione è definita, in questo caso proprio l'insieme $A$. Inoltre, $phi_P in cal(P)$ perché ho mostrato che esiste un programma $P$ che la calcola.
#block(
fill: rgb("#9FFFFF"),
inset: 8pt,
radius: 4pt,
[$2 arrow.long.double 3$]
)
Sappiamo che $A = dominio(f)$, con $f in cal(P)$, quindi esiste un programma $P$ tale che $phi_P = f$. Considero allora la relazione $ R_P = {(x,y) in NN^2 bar.v P "su input" x "termina in" y "passi"}, $ che abbiamo dimostrato prima essere ricorsiva. Definiamo $ B = {x in NN bar.v exists y bar.v (x,y) in R_P}. $ Dimostriamo che A = B. Infatti:
- $A subset.eq B$: se $x in A$ allora su input $x$ il programma $P$ termina in un certo numero di passi $y$, visto che $x$ è nel "dominio" di tale programma. Vale allora $(x,y) in R_P$ e quindi $x in B$;
- $B subset.eq A$: se $x in B$ allora per un certo $y$ ho $(x,y) in R_P$, quindi $P$ su input $x$ termina in $y$ passi, ma visto che $phi_P (x) arrow.b$ allora $x$ sta nel dominio di $f = phi_P$, quindi $x in A$.
#block(
fill: rgb("#9FFFFF"),
inset: 8pt,
radius: 4pt,
[$3 arrow.long.double 1$]
)
Sappiamo che $A = {x in NN bar.v exists y bar.v (x,y) in R}$, con $R$ relazione ricorsiva.
Assumiamo che $A eq.not emptyset.rev$ e scegliamo $a in A$, sfruttando l'assioma della scelta. Definiamo ora la funzione $t : NN arrow.long NN$ come $ t(n) = cases(cantorsin(n) quad & "se" (cantorsin(n), cantordes(n)) in R, a & "altrimenti") quad . $
Visto che $R$ è una relazione ricorsiva esiste un programma $P_R$ che categorizza ogni numero naturale, ma allora la funzione $t$ è ricorsiva totale. Infatti, possiamo scrivere il programma $ P equiv & "input"(n) \ & x := cantorsin(n); \ & y := cantordes(n); \ & "if" (P_R (x,y) == 1) \ & quad "output"(x) \ & "else" \ & quad "output"(a) $ che implementa la funzione $t$, quindi $phi_P = t$.
Dimostriamo che $A = immagine(t)$. Infatti:
- $A subset.eq immagine(t)$: se $x in A$ allora $(x,y) in R$, ma allora $t(cantor(x,y)) = x$, quindi $x in immagine(t)$;
- $immagine(t) subset.eq A$: se $x in immagine(t)$ allora:
- se $x = a$ per l'assioma della scelta $a in A$ quindi $x in A$;
- se $x = cantorsin(n)$, con $n = cantor(x,y)$ per qualche $y$ tale che $(x,y) in R$, allora $x in A$ per definizione di $A$.
]
Grazie a questo teorema abbiamo tre caratterizzazioni per gli insiemi ricorsivamente numerabili e possiamo sfruttare la formulazione che ci è più comoda.
Nell'esperienza del Prof. <NAME>, è molto utile e comodo il punto 2. In ordine:
+ scrivo un programma $P$ che restituisce $1$ su input $x in NN$, altrimenti va in loop se $x in.not A$: $ P(x) = cases(1 quad & "se" x in A, bot & "se" x in.not A) quad ; $
+ la semantica di $P$ è quindi tale che: $ phi_P (x) = cases(1 "se" x in A, bot "se" x in.not A) quad ; $
+ la funzione calcolata è tale che $ phi_P in cal(P), $ visto che il programma che la calcola è proprio $P$, mentre l'insieme $A$ è tale che $ A = dominio(phi_P); $
+ $A$ è ricorsivamente numerabile per il punto 2.
== Insiemi ricorsivamente numerabili ma non ricorsivi
Un esempio di insieme che non è ricorsivo, ma è ricorsivamente numerabile, è identificato dal problema dell'*arresto ristretto*.
Infatti, l'insieme $ A = {x in NN bar.v phi_x (x) arrow.b} $ non è ricorsivo, altrimenti il problema dell'arresto ristretto sarebbe decidibile.
Tuttavia, questo insieme è *ricorsivamente numerabile*: infatti, il programma $ P equiv & "input"(x) \ & U(x,x); \ & "output"(1) $ decide parzialmente $A$. Come possiamo vedere, se $x in A$ allora $phi_x (x) arrow.b$, ovvero l'interprete universale $U$ termina, e il programma $P$ restituisce $1$, altrimenti non termina.
Di conseguenza $ phi_P (x) = cases(1 & "se" phi_U (x,x) = phi_x (x) arrow.b, bot quad & "altrimenti") quad . $
Dato che $A = dominio(phi_P in cal(P))$ posso applicare la seconda caratterizzazione data nella lezione precedente per dimostrare che l'insieme $A$ è un insieme ricorsivamente numerabile.
Alternativamente, possiamo dire che $ A = {x in NN bar.v phi_x (x) arrow.b} = {x in NN bar.v exists y in NN bar.v (x,y) in R_ristretto}, $ con $ R_ristretto = {(x,y) bar.v ristretto "su input" x "termina entro" y "passi"} $ relazione ricorsiva. Qui possiamo sfruttare la terza caratterizzazione degli insiemi ricorsivamente numerabili.
Come sono messi i due insiemi?
#theorem(numbering: none)[
Se $A subset.eq NN$ è ricorsivo allora è ricorsivamente numerabile.
]
#proof[
\ Se $A$ è ricorsivo esiste un programma $P$ che è in grado di riconoscerlo, ovvero un programma che restituisce $1$ se $x in A$, altrimenti restituisce $0$.
Il programma $P$ è del tipo $ P equiv & "input"(x) \ & "if"(P_A(x) == 1) \ & quad quad "output"(1) \ & "else" \ & quad quad "while"(1>0); quad . $
La semantica di questo programma è $ phi_(P_A) (x) = cases(1 & "se" x in A, bot quad & "se" x in.not A) quad , $ ma allora $A$ è il dominio di una funzione ricorsiva parziale, quindi $A$ è ricorsivamente numerabile per la seconda caratterizzazione.
]
Poco fa abbiamo mostrato come $A = {x in NN bar.v phi_x (x) arrow.b}$ sia un insieme ricorsivamente numerabile ma non ricorsivo, ma allora vale $ "Ricorsivi" subset "Ricorsivamente numerabili" . $
#figure(
image("assets/ricorsivi-rnumerabili-1.svg", width: 50%)
)
_Esistono insiemi che non sono ricorsivamente numerabili?_
== Chiusura degli insiemi ricorsivi
Cerchiamo di sfruttare l'operazione di complemento di insiemi sui ricorsivamente numerabili per vedere di che natura è l'insieme $ A^C = {x in NN bar.v phi_x (x) arrow.t} . $
#theorem(numbering: none)[
La classe degli insiemi ricorsivi è un'Algebra di Boole, ovvero è chiusa per complemento, intersezione e unione.
]
#proof[
\ Siano $A,B$ due insiemi ricorsivi. Allora esistono dei programmi $P_A, P_B$ che li riconoscono o, equivalentemente, esistono $chi_A, chi_B in cal(T)$.
È facile dimostrare che le operazioni di unione, intersezione e complemento sono facilmente implementabili da programmi che terminano sempre. Di conseguenza, $ A union B, A sect B, A^C $ sono ricorsive.
Vediamo questi tre programmi:
- *complemento* $ P_(A^C) equiv & "input"(x) \ & "output"(1 overset(-, .) P_A (x)) . $
- *intersezione* $ P_(A sect B) equiv & "input"(x) \ & "output"(min(P_A (x), P_B (x))) . $
- *unione* $ P_(A union B) equiv & "input"(x) \ & "output"(max(P_A (x), P_B (x))) . $
Allo stesso modo possiamo trovare le funzioni caratteristiche delle tre operazioni:
- $chi_(A^C) (x) = 1 overset(-, .) chi_A (x)$;
- $chi_(A sect B) = chi_A (x) dot chi_B (x)$;
- $chi_(A union B) = 1 overset(-, .) (1 overset(-, .) chi_A (x))(1 overset(-, .) chi_B (x))$.
Tutte queste funzioni sono ricorsive totali, quindi anche le funzioni $A^C, A sect B, A union B$ sono ricorsive totali.
]
Ora, però, vediamo un risultato molto importante riguardante nello specifico il complemento dell'insieme dell'arresto $A^C$ che abbiamo definito prima.
#theorem(numbering: none)[
$A^C$ non è ricorsivo.
]
#proof[
\ Se $A^C$ fosse ricorsivo, per la proprietà di chiusura dimostrata nel teorema precedente, avremmo $ (A^C)^C = A $ ricorsivo, il che è assurdo.
]
Ricapitolando abbiamo:
- $A = {x : phi_x (x) arrow.b}$ ricorsivamente numerabile, ma non ricorsivo;
- $A^C = {x : phi_x (x) arrow.t}$ non ricorsivo.
_L'insieme $A^C$ Potrebbe essere ricorsivamente numerabile?_
#theorem(numbering: none)[
Se $A$ è ricorsivamente numerabile e $A^C$ è ricorsivamente numerabile allora $A$ è ricorsivo.
]
#proof[\
\ *INFORMALE*
Essendo $A$ e $A^C$ ricorsivamente numerabili, esistono due libri con infinite pagine su ognuna delle quali compare un elemento di $A$ (_primo libro_) e un elemento di $A^C$ (_secondo libro_).
Per decidere l'appartenenza di $x$ ad $A$, possiamo utilizzare il seguente procedimento:
+ $"input"(x)$;
+ apriamo i due libri alla prima pagina;
- se $x$ compare nel libro di $A$, stampa $1$,
- se $x$ compare nel libro di $A^C$, stampa $0$,
- se $x$ non compare su nessuna delle due pagine, voltiamo la pagina di ogni libro e ricominciamo.
Questo algoritmo termina sempre dato che $x$ o sta in $A$ o sta in $A^C$, quindi prima o poi verrà trovato su uno dei due libri.
Ma allora questo algoritmo riconosce $A$, quindi $A$ è ricorsivo.
*FORMALE*
Essendo $A$ e $A^C$ ricorsivamente numerabili, esistono $f,g in cal(T)$ tali che $A = immagine(f) and A^C = immagine(g)$. Sia $f$ implementata dal programma $F$ e $g$ dal programma $G$. Il seguente programma riconosce $A$: $ P equiv & "input"(x) \ & i:= 0; \ & "while"("true") \ & quad quad "if" (F(i)=x) "output"(1); \ & quad quad "if" (G(i)=x) "output"(0); \ & quad quad i := i + 1; $
Questo algoritmo termina per ogni input, in quanto $x in A$ o $x in A^C$. Possiamo concludere che l'insieme $A$ è ricorsivo.
]
Concludiamo immediatamente che $A^C$ *non* può essere ricorsivamente numerabile.
In generale, questo teorema ci fornisce uno strumento molto interessante per studiare le caratteristiche della riconoscibilità di un insieme $A$:
- se $A$ non è ricorsivo, potrebbe essere ricorsivamente numerabile;
- se non riesco a mostrarlo, provo a studiare $A^C$;
- se $A^C$ è ricorsivamente numerabile, allora per il teorema possiamo concludere che $A$ non è ricorsivamente numerabile.
#v(12pt)
#figure(
image("assets/ricorsivi-rnumerabili-2.svg", width: 50%)
)
#v(12pt)
== Chiusura degli insiemi ricorsivamente numerabili
#theorem(numbering: none)[
La classe degli insiemi ricorsivamente numerabili è chiusa per unione e intersezione, ma non per complemento.
]
#proof[
\ Per complemento, abbiamo mostrato che $A = {x : phi_x (x) arrow.b}$ è ricorsivamente numerabile, mentre $A^C = {x : phi_x (x) arrow.t}$ non lo è.
Siano $A,B$ insiemi ricorsivamente numerabili. Esistono, perciò, $f, g in cal(T) bar.v A = immagine(f) and B = immagine(g)$. Sia $f$ implementata da $F$ e $g$ implementata da $G$. Siano
#grid(
columns: (50%, 50%),
align(center)[
$ P_i equiv & "input"(x); \ & i := 0; \ & "while"(F(i) eq.not x) \ & quad i++; \ & i := 0; \ & "while"(G(i) eq.not x) \ & quad i++; \ & "output"(1); $
],
align(center)[
$ P_u equiv & "input"(x); \ & i := 0; \ & "while"("true") \ & quad "if" (F(i) = x) \ & quad quad "output"(1); \ & quad "if" (G(i) = x) \ & quad quad "output"(1); \ & quad i++; $
]
)
i due programmi che calcolano rispettivamente $A sect B$ e $A union B$. Le loro semantiche sono
#grid(
columns: (50%, 50%),
align(center)[
$ phi_(P_i) = cases(1 & "se" x in A sect B, bot quad & "altrimenti") $
],
align(center)[
$ phi_(P_u) = cases(1 & "se" x in A union B, bot quad & "altrimenti") $
]
)
da cui ricaviamo che
#grid(
columns: (50%, 50%),
align(center)[
$ A sect B = dominio(phi_P' in cal(P)) $
],
align(center)[
$ A union B = dominio(phi_P'' in cal(P)) $
]
)
I due insiemi sono quindi ricorsivamente numerabili per la seconda caratterizzazione.
]
== Teorema di Rice
Il *teorema di Rice* è un potente strumento per mostrare che gli insiemi appartenenti a una certa classe non sono ricorsivi.
Sia ${phi_i}$ un SPA. Un insieme (_di programmi_) $I subset.eq NN$ è un *insieme che rispetta le funzioni* se e solo se $ (a in I and phi_a = phi_b) arrow.long.double b in I . $
In sostanza, $I$ rispetta le funzioni se e solo se, data una funzione calcolata da un programma in $I$, allora $I$ contiene tutti i programmi che calcolano quella funzione. Questi insiemi sono detti anche *chiusi per semantica*.
Per esempio, l'insieme $I = {x in NN bar.v phi_x (3) = 5}$ rispetta le funzioni. Infatti, $ underbracket(a in I, phi_a (3) = 5) and underbracket(phi_a = phi_b, phi_b (3) = 5) arrow.double b in I . $
#theorem(
name: "Teorema di Rice",
numbering: none
)[
Sia $I subset.eq NN$ un insieme che rispetta le funzioni. Allora $I$ è ricorsivo solo se $I = emptyset.rev$ oppure $I = NN$.
]
Questo teorema ci dice che gli insiemi che rispettano le funzioni non sono mai ricorsivi, tolti i casi banali $emptyset.rev$ e $NN$.
#proof[
Sia $I$ insieme che rispetta le funzioni con $I eq.not emptyset.rev$ e $I eq.not NN$. Assumiamo per assurdo che $I$ sia ricorsivo.
Dato che $I eq.not emptyset.rev$, esiste almeno un elemento $a in I$. Inoltre, dato che $I eq.not NN$, esiste almeno un elemento $overline(a) in.not I$.
Definiamo la funzione $t : NN arrow.long NN$ come: $ t(n) = cases(overline(a) quad & "se" n in I, a & "se" n in.not I) . $
Sappiamo che $t in cal(T)$ dato che è calcolabile dal programma $ P equiv & "input"(x); \ & "if"(P_I (n) = 1) \ & quad "output"(overline(a)); \ & "else" \ & quad "output"(a) $
Visto che $t in cal(T)$, il _teorema di ricorsione_ assicura che in un SPA ${phi_i}$ esiste $d in NN$ tale che $ phi_d = phi_t(d) . $
Per tale $d$ ci sono solo due possibilità rispetto a $I$:
- se $d in I$, visto che $I$ rispetta le funzioni e $phi_d = phi_t(d)$ allora $t(d) in I$. Ma $t(d in I) = overline(a) in.not I$, quindi ho un assurdo;
- se $d in.not I$ allora $t(d) = a in I$ ma $I$ rispetta le funzioni, quindi sapendo che $phi_d = phi_t(d)$ deve essere che $d in I$, quindi ho un assurdo.
Assumere $I$ ricorsivo ha portato ad un assurdo, quindi $I$ non è ricorsivo.
]
=== Applicazione
Il teorema di Rice suggerisce un approccio per stabilire se un insieme $A subset.eq NN$ non è ricorsivo:
+ mostrare che $A$ rispetta le funzioni;
+ mostrare che $A eq.not emptyset.rev$ e $A eq.not NN$;
+ $A$ non è ricorsivo per Rice.
=== Limiti alla verifica automatica del software
Definiamo:
- *specifiche*: descrizione di un problema e richiesta per i programmi che devono risolverlo automaticamente. Un programma è _corretto_ se risponde alle specifiche;
- *problema*: _posso scrivere un programma $V$ che testa automaticamente se un programma sia corretto o meno?_
Il programma che vogliamo scrivere ha semantica $ phi_V (P) = cases(1 & "se" P "è corretto", 0 quad & "se" P "è errato") quad . $
Definiamo $ "PC" = {P bar.v P "è corretto"} . $ Osserviamo che esso rispetta le funzioni: infatti, $ underbracket(P in "PC", P "corretto") and underbracket(phi_P = phi_Q, Q "corretto") arrow.long.double Q in "PC" $
Ma allora PC non è ricorsivo. Dato ciò, la correttezza dei programmi non può essere testata automaticamente. Esistono, però, dei casi limite in cui è possibile costruire dei test automatici:
- specifiche del tipo _"nessun programma è corretto"_ generano $"PC" = emptyset.rev$;
- specifiche del tipo _"tutti i programmi sono corretti"_ generano $"PC" = NN$.
Entrambi gli insiemi PC sono ovviamente ricorsivi e quindi possono essere testati automaticamente.
Questo risultato mostra che non è possibile verificare automaticamente le *proprietà semantiche* dei programmi (_a meno di proprietà banali_).
|
|
https://github.com/ckunte/m-one | https://raw.githubusercontent.com/ckunte/m-one/master/inc/cosfunc.typ | typst | = Cosine interaction
While reviewing the changes introduced in the new ISO 19902:2020 standard@iso19902_2020, this one jumped at me:
#quote()[
tubular member strength formulae for combined axial and bending loading now of cosine interaction form instead of previously adopted linear interaction;
]
In ISO 19902:2020, the combined unity check for axial (tension | compression) + bending takes the following general expression:
$ U_m = 1 - cos(pi / 2 (gamma_(R,t|c) sigma_(t|c)) / f_(t|y c)) + (gamma_(R,b) sqrt(sigma^2_(b,y)) + sigma^2_(b,z)) / f_b $
This form of unity check has existed since 1993 in API RP-2A LRFD@api_rp2a_lrfd, 1st edition, and whose introduction into ISO 19902:2020 is briefly described in $section$A13.3.2 and $section$A13.3.3. This form makes its presence felt throughout _$section$13 Strength of tubular members_.#footnote[This form, i.e., 1 - cos(x) occurs in as many as eleven equations, viz., Eq. 13.3-1, 13.3-2, 13.3-4, 13.3-8, 13.3-18, 13.3-19, 13.3-21, 13.3-23, 13.4-7, 13.4-13, and 13.4-19 in ISO 19902:2020. Curiously, this is not applied to dented tubes in §13.7.3, whose combined UC expression(s) remains like before.]
Previously, _Um_ in ISO 19902:2007 was expressed as:
$ U_m = gamma_(R,t|c) sigma_(t|c) / f_(t|y c) + gamma_(R,b) sqrt(sigma^2_(b,y) + sigma^2_(b,z)) / f_b $
The reduction of _Um_ in the first equation is notable, see Figure below. For example, if the axial unity check value (x) is, say, 0.2, then its contribution is reduced to $0.05 (= 1 - cos(pi / 2 x)$. Remember `cos()` is in radians.
#figure(
image("/img/tuc_under_cosint.svg", width: 100%),
caption: [
Axial utilisation versus axial component under cosine interaction in the combined utilisation expression
]
) <cf1>
#let cosint = read("/src/cosint.py")
#{linebreak();raw(cosint, lang: "python")}
$ - * - $ |
|
https://github.com/ThatOneCalculator/riesketcher | https://raw.githubusercontent.com/ThatOneCalculator/riesketcher/main/riesketcher.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
/// Draw a Riemann sum of a function, and optionally plot the function.
///
/// - fn (function): The function to draw a Riemann sum of.
/// - domain (array): Tuple of the domain of fn. If a tuple value is auto, that
/// value is set to start/end.
/// - start (number): Where to start drawing bars.
/// - end (number): Where to end drawing bars.
/// - n (number): Number of bars
/// - y-scale (number): Y scale of bars.
/// - method (string): Where points are derrived from. Can be "left", "mid"/"midpoint", or "right".
/// - transparency (number): Transparency fill of bars.
/// - dot-radius (number): Radius of dots.
/// - plot (boolean): Whether to add plot of the function.
/// - plot-grid (boolean): Show grid on plot.
/// - plot-x-tick-step (number): X tick step of plot.
/// - plot-y-tick-step (number): Y tick step of plot.
/// - positive-color (color): Color of positive bars.
/// - negative-color (color): Color of negative bars.
/// - plot-line-color (color): Color of plotted line.
#let riesketcher(
fn,
start: 0,
end: 10,
domain: (auto, auto),
n: 10,
y-scale: 1,
method: "left",
transparency: 40%,
dot-radius: 0.15,
plot: true,
plot-grid: false,
plot-x-tick-step: auto,
plot-y-tick-step: auto,
positive-color: color.green,
negative-color: color.red,
plot-line-color: color.blue,
size: (5, 5),
) = {
// Adjust the function domain if set to auto
if domain.at(0) == auto { domain.at(0) = start }
if domain.at(1) == auto { domain.at(1) = end }
let horizontal-hand-offset = 0%
if method == "right" {
horizontal-hand-offset = 100%
}
else if method == "mid" or method == "midpoint" {
horizontal-hand-offset = 50%
}
let col-trans(color, opacity) = {
let space = color.space()
space(..color.components(alpha: false), opacity)
}
let delta = end - start
let bar-width = (end - start) / n
let bar-position = if method == "left" {
"start"
} else if method == "right" {
"end"
} else {
"center"
}
let bar-y = range(0, n).map(x => {
let x = start + bar-width * (x + horizontal-hand-offset / 100%)
(x, fn(x))
})
let positive-bar-style = (
fill: col-trans(positive-color.lighten(70%).darken(8%), transparency),
stroke: col-trans(positive-color.darken(30%), 90%) + 1.1pt
)
let negative-bar-style = (
: ..positive-bar-style,
fill: col-trans(negative-color.lighten(70%).darken(8%), transparency),
stroke: col-trans(negative-color.darken(30%), 90%) + 1.1pt
)
let positive-dot-style = (
stroke: black,
fill: positive-color
)
let negative-dot-style = (
: ..positive-dot-style,
fill: negative-color,
)
cetz.plot.plot(
size: size,
x-grid: plot-grid,
y-grid: plot-grid,
axis-style: if plot { "school-book" } else { none },
x-tick-step: plot-x-tick-step,
y-tick-step: plot-y-tick-step,
{
for (x, y) in bar-y {
cetz.plot.add-bar(((x, y),),
bar-width: bar-width,
bar-position: bar-position,
style: if y >= 0 { positive-bar-style } else { negative-bar-style })
}
if plot {
cetz.plot.add(
domain: domain,
x => fn(x),
style: (stroke: plot-line-color + 1.5pt))
}
for (x, y) in bar-y {
cetz.plot.add(((x, y),),
mark: "o",
style: (stroke: none),
mark-size: dot-radius,
mark-style:if y >= 0 { positive-dot-style } else { negative-dot-style })
}
})
}
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/029%20-%20Aether%20Revolt/008_Puppets.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Puppets",
set_name: "<NAME>",
story_date: datetime(day: 25, month: 01, year: 2017),
author: "<NAME>",
doc
)
#emph[With the rest of the Gatewatch embroiled in the Inventors' revolution, Liliana has taken on the grim task of addressing what she sees as the ] real#emph[ problem on Kaladesh: the Planeswalker Tezzeret.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Long ago and worlds away, a young <NAME> had slipped through the trees of a dark forest while a battle raged around her. The croaking of ravens and the screams of the dying had accompanied her into the woods, and the course of her life had altered. The streets of Ghirapur were about as different from the Caligo Forest of Dominaria as the Liliana of today was from that naive, hopeful, desperate girl.
#figure(image("008_Puppets/01.jpg", width: 100%), caption: [Liliana, Heretical Healer | Art by Karla Ortiz], supplement: none, numbering: none)
But war was war. Buzzing thopters took the place of ravens here (for which she was deeply grateful), while screams mingled with the explosive sounds of aether cannons and quicksmithed incendiaries.
Her mission then had been life: finding a cure for the mysterious affliction that had laid her brother on death's doorstep. Today her mission was death—her mission and her constant companion. The death of Tezzeret. Nothing else mattered—not the struggles of Kaladesh's renegades, not the interference of her Planeswalker allies, not the Consulate's attempts to restore order.
Tezzeret had to die.
Of #emph[course] he had to die, and it was absurd that Gideon was queasy about it. Hells, right up until this whole business on Kaladesh had started, she had thought he was dead already. Killing him now was just tidying up a loose end left over from an unfortunate affair on Ravnica four years ago.
Liliana had been working for the dragon then, turning Jace against Tezzeret in an attempt to wrest away control of an interplanar consortium. Jace had wrecked Tezzeret's mind and left him for dead on some remote plane. A loose end—Tezzeret would come after her, would come after Jace, would no doubt make everything more complicated.
She sighed, looking around at the chaos wrought by Ghirapur's angry renegades. Everything was already complicated enough, and she had plenty of unresolved issues. Tezzeret and <NAME> and the Chain Veil. Bolas and her demonic pacts. The damned Raven Man. Even the events of the Caligo Forest had left certain questions unanswered. One tangled mess after another, each with its own loose ends. She paused and looked at the body of a hapless renegade, lying limp and broken in the wreckage of a small copter. She waved a hand in its direction, and a new zombie struggled to its feet.
#figure(image("008_Puppets/02.jpg", width: 100%), caption: [Cemetery Recruitment | Art by <NAME>], supplement: none, numbering: none)
She felt a little better.
If Tezzeret had been a loose end when she first found him here, now he was a clear danger not just to this plane, but as far as his ambitions extended. If Rashmi had any idea what she was talking about—and she was smart, so she probably did—then Tezzeret was building something like an old-fashioned planar portal, the sort of thing that had caused so much chaos in Dominaria's ancient history. As far as she had known, such things were impossible now, now that the Multiverse had...changed.
But judging from the vortex of energy that was now swirling around the Aether Spire, Liliana guessed that Tezzeret had activated that portal. That could not be good.
Gideon talked a good show about fighting interplanar threats, but Tezzeret was right in their reach and somehow Gideon didn't want to kill him. Instead, he and Jace and the others were hip-deep in this war, this rebellion. "None of our damned business," she muttered. Not that she really cared about the stated mission of the Gatewatch, but the revolt had become a huge distraction from what was really important.
"Me," Liliana said to herself with a sardonic smile.
She told the zombie to follow her, smiling at the thought of Gideon's disapproval. But she would need a bodyguard if she was going to get to Tezzeret.
#emph[And I ] am#emph[ going to get to Tezzeret] , she thought.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Fortunately Liliana didn't have much farther to go because her new friend drew a lot of attention. It was the best kind of attention, though: people gasping and recoiling in horror, pointing at her in shock and dismay, and staying the hell out of her way.
#emph[You'd think they'd never seen a necromancer before.]
But she knew it couldn't last; sooner or later, some Consulate soldiers would decide that she and her zombie were a threat to their precious order and put themselves between her and the Aether Spire. So she covered the remaining distance as quickly as she could manage, until at last she reached a barricade across the street and a dozen or so Consulate soldiers blocking her way. An unnatural wind, no doubt stirred up by the swirling energy vortex above, drowned out the sound of the dwarf captain's challenge, but her meaning was clear: Stop. Turn back.
#figure(image("008_Puppets/03.jpg", width: 100%), caption: [Bastion Enforcer | Art by <NAME>], supplement: none, numbering: none)
With the slightest nod of her head, Liliana directed the zombie to a position in front her, to keep the soldiers busy until she could deal with them.
"#emph[Deal with them?] " She could almost hear Jace's voice questioning her—in fact, for a moment she thought it was his voice in her mind. A single spell could drain the life from the soldiers and add their walking corpses to her retinue, and she had no doubt she could do it. Mana surged in her like bile, fueled by her hatred of Tezzeret, ready for the battle to come. Killing these soldiers would be easy—but, strangely, that had not been her plan. #emph[Perhaps Jace and] —she shuddered a little—#emph[and General Meat-Shield are rubbing off on me.]
Spears stood up a little straighter and aether weapons lit with their blue glow as she continued her approach. Then a keen-eyed soldier saw the nature of her escort and shouted a delightful expletive, audible even over the rushing wind.
"That's your cue," she muttered, willing the zombie ahead as she strode toward the soldiers. Purplish-black energy crackled around her hands and sparked like static in her skirt.
Then her magic surged out in front of her like a wave of death, sweeping over the soldiers. She was careful: just enough mana to suck the breath from their lungs until their vision went black and their knees buckled, just enough to keep them out of the way while she and her escort entered the spire, and not enough to turn them into withered husks. She almost wished Jace were there to witness her care and restraint.
The zombie cleared the barricade, and Liliana entered the Aether Spire.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Restraint was not entirely practical. It robbed her of the chance to build a whole retinue of zombie bodyguards. More important, it left people behind her, who could block her retreat once Tezzeret was dead. How easy it would be, she thought as a ghostly black hand coiled itself around the neck of another sentry, to tighten just a little, to twist, to send one more soul into the yawning Void. Jace and Sir Side-of-Beef would never know. So easy.
But she sighed, let her own hand fall to her side, and watched the sentry slump to the ground, clutching his throat and gasping for breath, unable to lift a finger to stop her. She patted his helmet as she walked past him.
And then she was inside. It was a vault of a room, dominated by the huge ring of Tezzeret's planar portal. More accurately, the portal was a ring within a ring, set within a vaguely ring-like structure made of whorls and glowing pipes and what looked like purely decorative filigree. Tezzeret stood just beneath the inner rings, his back to her, manipulating some piece of machinery. Beyond, a shattered glass wall left the room open to the gusting winds, with an orange sunset staining the sky.
#figure(image("008_Puppets/04.jpg", width: 100%), caption: [Planar Bridge | Art by Chase Stone], supplement: none, numbering: none)
She thrust both hands forward, the tattoos of her demonic contract glowing almost as brightly as the aether in the portal. The time for restraint was past. A roiling storm of smoky blackness surged across the room toward Tezzeret, coalescing into a spectral claw that would tear his soul from his flesh and end him.
But at the last second, a hulk of sharp-edged metal detached itself from the heaps of junk around the edges of the room and interposed itself between Tezzeret and the death that hurtled toward him. Liliana's spell tore into it, but not through it, and it seemed none the worse for wear as it coalesced into a vaguely humanoid figure.
Only then did Tezzeret turn around, his flesh-and-bone hand finishing up some kind of adjustment to his etherium arm. He seemed unfazed by her arrival and even her attack.
"Vess," he said. His voice echoed in the enormous room. "Did #emph[he] send you? What, to check up on me?"
#figure(image("008_Puppets/05.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none)
Liliana blinked. This was hardly the vicious counterattack she had expected—and prepared for. "Who?"
Tezzeret shrugged. He tugged the sleeve of his robe down to cover most of his etherium arm again, hiding a strange glow that seemed to echo the eddying light of his portal. Only then did he grace her with his full attention. He arched an eyebrow.
"No," she said. "You saw in the arena. I'm here with them."
"Of course you are. Baan's little mistake. What did he call them? The Gatewatch?" He chuckled. "Did they come to see my magnificent gate?" A broad gesture with his metal hand encompassed the ring behind and around him.
Liliana sauntered to her left, putting some distance between herself and the junk-heap of a construct that had saved him and was now lumbering in her direction. "I thought it was Rashmi's gate."
Tezzeret's face twisted in rage. "That idiot? She had no idea what she discovered."
Liliana smiled. His temper was his weakness, and pricking his ego seemed to be the surest way to make him lose control. "I wouldn't be so sure," she said.
"What, you think she glimpsed the Blind Eternities? You think she understood how her invention could be used to bridge worlds? She would have been sending vases across Ghirapur forever if I hadn't guided her tiny little mind." He was closing the gap between them now, as if to keep Liliana away from his precious creation.
Purple light coursed through the channels etched in Liliana's skin. "You should know better than to underestimate a woman like her." Emphasizing that point, while his guard was down, she hurled a focused blast at him, like dark lightning. He threw up his metal hand, blocking the attack and scattering its energy. She needed to get closer.
"Fair enough," he growled. The metallic hulk shambled closer, raising two fist-like masses over what passed for its head. Tezzeret continued talking as if nothing had happened. "And what about your new friends? Do they have any idea who they've gotten themselves tangled up with?"
A cascade of metal crashed to the floor, battering her zombie bodyguard but leaving Liliana unscathed. The zombie lurched at the walking scrap heap as Tezzeret advanced.
"Of course not," Liliana said. For all their hesitation, their displays of mistrust, the other members of the Gatewatch had welcomed her into the fold. In fact, the one person who might have known better—Jace—had encouraged them to trust her.
"You have them all wrapped around your finger, don't you?" Tezzeret said.
Liliana just smiled, pointed a single glowing finger, and shot another enervating bolt of energy at him.
He waved his metal hand, and a stream of sharp metal shards coursed through the air and intercepted her attack. "Even Beleren?" he said. "I find it hard to believe that he's forgotten what you did to him."
Liliana scowled. "Jace and I..." She trailed off, and decided to finish her sentence by snatching at the edges of Tezzeret's soul and sucking his vitality away.
Blue light shimmered in the air between them, and her magic vanished into tiny azure sparks. "Or has he forgotten?" Tezzeret said. "His memory seems so fragile."
"He certainly hasn't forgotten what #emph[you] did to him." Two crackling blasts, in rapid succession, punctuated her words. One was intercepted by Tezzeret's living scrap heap, tearing itself free of the zombie, and he caught the other one on his metal hand—with some apparent effort.
"It's too bad he didn't come with you." Tezzeret spread his arms wide, and two streams of metallic shards like the one that had torn into her zombie rose up behind him, snakelike. "We could have had quite a reunion."
#figure(image("008_Puppets/06.jpg", width: 100%), caption: [Battle at the Bridge | Art by <NAME>], supplement: none, numbering: none)
He had left himself open. A spectral black hand appeared from nowhere and clutched at his chest, sending him staggering back and gasping for breath as the metal shards cascaded down to the ground. But she had sacrificed power for speed, and he didn't fall.
His breathing was heavy and his voice rasped. "Are you certain Beleren isn't the one manipulating you?" he said. "Sending you to fight his battles and exact his revenge?"
"No one sent me." #emph[I took it upon myself to do the work none of them would do,] she thought. #emph[My choice. Right?]
"Are you sure?" Tezzeret said, as if he saw the hesitation in her mind. "Maybe he's playing you, worming his way into your thoughts."
Liliana's zombie was doing a pretty good job of dismantling the junk hulk, but she needed it to be harrying Tezzeret instead. "Oh, please," she said. "Jace likes to think he's a mastermind, but when he looks at me he turns into a schoolboy." But her words didn't come out sounding quite as convincing as she had intended.
"I think he's #emph[softened] you, Vess. The necromancer I knew four years ago would have marched in here at the head of a zombie army. And she might have lived to tell about it." Tezzeret pointed his real hand at a pile of construction materials, and something stirred to life.
#figure(image("008_Puppets/07.jpg", width: 100%), caption: [Tezzeret's Touch | Art by Chris Rallis], supplement: none, numbering: none)
The effort of will his spell required showed on his face, and she jumped at the opening. She felt blood well up in the lines carved into her flesh as she drew on just the smallest bit of the Chain Veil's power. "You don't know what you're talking about," she snarled, as a pulse of dark energy radiated out from her like a ripple. The ripple bounced off Tezzeret and turned back toward her, tearing his life from his body as it came. She reached for it, calling that scrap of vitality, of soul, toward her waiting arms. Tezzeret clutched at his throat and fell to his knees—where her zombie fell on him, biting and clawing.
She twisted her fingers in the air, claiming a better hold on the magic that had caught hold of his life, reeling it in like a wriggling fish on a line. Oh, she was #emph[enjoying] this!
She heard a loud buzz just before a hawk-sized thopter clipped her face, sending her sprawling on her back and opening a gash in her forehead. She heard Tezzeret gulping the air and looked up in time to see him throw the zombie off him and stagger to his feet, his eyes burning with rage. Two thopters took up positions hovering over his shoulders.
"Why are we fighting, Vess?" He took several labored breaths while she got to her feet. "Has your love for Beleren made you think you're some kind of hero?"
She gritted her teeth, biting back her own fury. "I assure you, my relationship with Jace has nothing to do with romance or sentiment." Her breath was coming faster as well, but the energy she had siphoned from Tezzeret surged through her. "And what kind of #emph[hero] uses magic like mine?" Her zombie lunged at him again.
Tezzeret's huge metal claw sliced across the zombie's rotting flesh in a wide arc, trailing foulness and offal. "So he really didn't send you?"
"Jace? Of course—"
"Not Beleren."
They stood facing each other in a moment of stillness.
"Oh," Liliana breathed. "Oh. You're here for Bolas."
A contemptuous sneer twisted his face. "Tell me you didn't #emph[just] figure that out."
#emph[It all makes sense now. ] Some part of her had suspected, but she hadn't wanted to believe it. But it explained why he was alive, why his mind seemed whole. #emph[And it's all so much worse now,] she thought as she ducked Tezzeret's swooping thopters.
"So #emph[he's] got #emph[you] wrapped around his finger," she said. #emph[Like he does everyone.]
Tezzeret snarled. "I'm working to pay off a debt. Thanks to your boyfriend." Jace had been just a pawn in their game, but the injury he'd done to Tezzeret was not the kind that's easily forgiven.
"And then what?"
Tezzeret shrugged, but Liliana saw a familiar cockiness in his eyes.
She laughed. "You have grand plans to turn the tables on him? On <NAME>? I'm pretty sure even you are not that stupid."
"Even if I had such plans, I certainly wouldn't tell you. It's only a matter of time before Bolas lays your mind bare and reads it like a book."
That was not a pleasant thought. She answered it with a barrage of necrotizing energy—enough to rot the flesh from his bones, drink his soul dry, and leave him a crumpled husk on the ground, if she had been able to get through his defenses. But another stream of metallic shards, like a swarm of bees, caught some blasts. His counterspells negated others, and one blast went wild when a thopter drove itself into her gut, knocking the wind out of her. Even so, Tezzeret was forced to his knees, choking and gasping, and what was left of the zombie managed to pin him to the floor.
#figure(image("008_Puppets/08.jpg", width: 100%), caption: [Metallic Rebuke | Art by <NAME>], supplement: none, numbering: none)
Blood flowed freely over her skin, not from any injury he had inflicted on her, but from the exertion of her spellcasting, the toll exacted by the Chain Veil. She wobbled—ever so slightly—as she walked to stand over him where he lay.
She rested one heel of her boot on his throat, just above his collarbone. "So, what?" she demanded. "All this is for him? What's he going to do with it?"
Tezzeret, breath ragged, stared up at her with fury and fear raging across his pale face.
"A transplanar shipping company?" she asked. "A new take on the Infinite Consortium?" She knew better, of course: Bolas's plans had never been that small. She'd known that even on Ravnica, when she helped him pursue them.
Tezzeret managed a chuckle. "Maybe you should ask him."
Liliana's mouth quirked into a smile. "But I have you right here."
"You know he never confides more than he needs to. He'd never tell me the full extent of his plans."
"Well, then you can tell me where to find him."
"So #emph[you] can turn the tables on him? Maybe you are as stupid as I thought."
"Who said anything about fighting him?" Liliana said. "Tell me where he is."
"I'm not sure he'd appreciate me divulging that."
Liliana put a little more of her weight onto her heel, squeezing a hoarse cough from his
throat. "I'm quite sure I #emph[don't] appreciate your reticence."
Tezzeret gagged, clearly unable to speak. She lightened up the pressure just enough to let him breathe. "Spit it out, Tezz."
"You should know. You've been there before."
She frowned, thinking of all the planes she'd visited. "Which one?"
Tezzeret tried to cough, but couldn't get any air out. He tried in vain to make sounds. "R— Ra—"
With an impatient sigh, she lifted her foot, looking for a different soft spot on his metallic body where she could grind in her heel.
"Razaketh," he gasped.
Every inch of her body was suddenly alive with a thrill of fear. Two demons remained who held power over her, thanks to the contract engraved on her skin. Kothophed and Griselbrand had fallen relatively easily, thanks to the Chain Veil. But the Chain Veil's power came with a cost, attested by the blood that still dripped from her skin and splattered on Tezzeret's face and chest. Razaketh was stronger than either of them.
She had planned to bring Jace and the rest of his precious Gatewatch to confront Razaketh eventually. But she had hoped to understand them better—to learn what they were capable of, to make sure she knew exactly what strings to pull and what buttons to press to get them to do what she wanted them to do—before she brought them to...
"Amonkhet," she said aloud. "He's on Amonkhet."
Tezzeret swallowed hard and with evident pain. #emph[Good.]
"This is the end, Tezzeret." She spread her hands above him, summoning the mana for the spell that would drain whatever life he had left in him.
"Is that what this is?"
He was looking past her. She ducked, expecting another swooping thopter. Indeed, something was flying toward her—something much larger than Tezzeret's birdlike thopters, hurtling toward the spire from outside the shattered glass wall.
The renegades' so-called hope. So the Gatewatch had done their job after all, getting the airship past the Consulate's blockade, close enough to launch the aether disruptor. Surprising, but pleasing.
"I think it's about to be," she said. She moved behind what looked like a sturdy wall, leaving Tezzeret in her zombie's grasp.
But something was wrong: she caught a glimpse as she ducked behind the wall, of flaming red hair at the tip of the oversized thopter. #emph[Chandra? What the hell] —
"We'll see," Tezzeret said, and then—
Then there was fire.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra's fist was a birthing star, searing hot against Gideon's chest despite the glowing golden light that shielded his body from the heat. Holding her tightly against him, he could feel every muscle in her body trembling with the effort to create and control the flame.
"Almost there," he said. The brilliant golden glow spread across the rest of his body—the magical force that had protected him from countless injuries. Would it be enough?
She gave the slightest nod and the heat grew even more intense.
#figure(image("008_Puppets/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Chandra," he said.
She didn't respond—maybe she hadn't heard, maybe she was too focused on the burning sun clutched in her palm.
"I'm glad you're here," he said. "I'm glad you left Regatha. The Gatewatch—the whole thing. I'm—"
"Gids," she said through clenched teeth. "I'm...I'm gonna let go."
He pulled her closer. Impact was a heartbeat away. The golden light enfolded them both now—it was working!—but the heat...
"I've got you," he said. "You're safe."
"I know," she said. Her other hand touched his arm, and that was enough.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Brilliant white light, an eruption of searing hot air, crumbling stone, and clouds of dust. Falling. Screams. Pain—too damned much pain.
When her vision cleared, Liliana found herself half-buried in the rubble of the workshop, shattered stone and fractured metal all around, the wall she had sheltered behind now mostly crumbled away. A huge column of smoke boiled up from where Tezzeret's gate had stood. No zombie moved in response to her mental call, so she set about extricating herself. She was smeared with blood and a bit woozy, thanks to the Chain Veil if not her small injuries.
With every stone she lifted and set aside, she breathed a creative new curse. She hadn't killed Tezzeret when she had the chance, and if she had survived this explosion then he probably had as well. He would escape, back to Bolas—or he'd find her now and kill her, while she was...not at full strength.
#emph[And stupid Chandra has gone and killed herself] , she thought. #emph[That was not the plan.] "What a waste," she said to herself. "Can't they do anything right without me?"
Freed from the rubble, she clambered toward the wreckage of Tezzeret's portal. If he was alive, or Chandra, or any shred of hope, she would find it there. As she went, she occasionally stopped to shove a piece or rubble or hunk of metal aside, clearing her path and distantly hoping she might find someone.
"I'd be perfectly content to find a corpse to help me move this junk."
#emph[Someone who obeys me without question] , she thought. #emph[Someone completely under my control. It's so much easier that way.]
Tezzeret's words rang in her mind: "You have them all wrapped around your finger, don't you?" #emph[That's the plan,] she thought. #emph[But nothing is going according to plan.]
The whole point of coming to Kaladesh had been to assess Chandra's usefulness. #emph[She's not very useful if she's dead—well, she's of very limited use.]
If she was going to kill the rest of her demons without killing herself, if she was ever to be free, she needed more than zombies. She needed powerful people, and she'd found them. But it was all so complicated.
She heard coughing. And in the midst of the dust and smoke swirling above the wreckage of the portal, she caught a glimpse of flame-red hair and brass goggles. Alive.
Liliana picked up her pace, turned her ankle once and ignored the jolt of pain, and finally reached Chandra.
"Chandra!" she scolded. "What in all the Nine Hells was—"
Chandra helped Gideon to his feet beside her. Towering over her, he picked a twisted hunk of filigree from her hair. They both looked like—well, like a building had fallen on them, and Liliana suspected she didn't look much better.
"Beef...side...guy," Liliana stammered.
Chandra was avoiding Gideon's eyes, and she smiled when she saw Liliana. Gideon followed her gaze.
"Liliana!" he said. He stepped forward and lifted his hand, then clearly thought better of it before bringing that meaty weight down on her shoulder. He awkwardly scratched his sideburn. "Did you...uh, did you find him?"
Liliana scowled. "He's either buried in this rubble or run home to his master."
In silence, the three Planeswalkers gazed around the wreckage for a long moment.
"Where's Jace?" Liliana said at last. "We #emph[really] need to talk."
#figure(image("008_Puppets/10.jpg", width: 100%), caption: [Dark Intimations | Art by Chase Stone], supplement: none, numbering: none)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/riesketcher/0.1.0/riesketcher.typ | typst | Apache License 2.0 | #import "@preview/cetz:0.1.2"
/// Draw a Riemann sum of a function, and optionally plot the function.
///
/// - fn (function): The function to draw a Riemann sum of.
/// - start (number): Where to start drawing bars.
/// - end (number): Where to end drawing bars.
/// - n (number): Number of bars (please make $Delta x =1$).
/// - y-scale (number): Y scale of bars.
/// - x-offset (number): X offset of bars.
/// - y-offset (number): Y offset of bars.
/// - hand (string): Where points are derrived from. Can be "left", "mid"/"midpoint", or "right".
/// - transparency (number): Transparency fill of bars.
/// - dot-radius (number): Radius of dots.
/// - plot (boolean): Whether to add plot of the function.
/// - plot-grid (boolean): Show grid on plot.
/// - plot-x-tick-step (number): X tick step of plot.
/// - plot-y-tick-step (number): Y tick step of plot.
/// - positive-color (color): Color of positive bars.
/// - negative-color (color): Color of negative bars.
/// - plot-line-color (color): Color of plotted line.
#let riesketcher(
fn,
start: 0,
end: 10,
n: 10,
y-scale: 1,
x-offset: 0,
y-offset: 0,
hand: "left",
transparency: 40%,
dot-radius: 0.055,
plot: true,
plot-grid: false,
plot-x-tick-step: auto,
plot-y-tick-step: auto,
positive-color: color.green,
negative-color: color.red,
plot-line-color: color.blue,
) = {
let hand-offset = 0
let mark-horizontal = "-left"
if hand == "right" {
hand-offset = 1
mark-horizontal = "-right"
}
else if hand == "mid" or hand == "midpoint" {
hand-offset = 0.5
mark-horizontal = ""
}
let col-trans(color, opacity) = {
let space = color.space()
space(..color.components(alpha: false), opacity)
}
if plot {
cetz.plot.plot(
size: (end + x-offset, end),
x-grid: plot-grid,
y-grid: plot-grid,
axis-style: "school-book",
x-tick-step: plot-x-tick-step,
y-tick-step: plot-y-tick-step,
{
cetz.plot.add(
domain: (start - x-offset, end),
x => fn(x),
style: (
stroke: plot-line-color + 1.5pt,
),
)
})
}
// Doesn't work if Delta n != 1
// Should be `for i in range(start, end, step: (end - start)/n).map(...`
// https://github.com/typst/typst/issues/2908
for i in range(start, end).map(x => x * n/(end - start)) {
let height = fn(i + hand-offset)
let bar-color = positive-color
let mark-vertical = "top"
if fn(i) <= 0 {
bar-color = negative-color
mark-vertical = "bottom"
}
cetz.draw.fill(col-trans(
bar-color.lighten(70%).darken(8%),
transparency
))
cetz.draw.rect(
(i + x-offset, y-offset),
(i + x-offset + 1, (height/y-scale) + y-offset),
stroke: col-trans(bar-color.darken(30%), 90%) + 1.1pt,
name: "r"
)
cetz.draw.circle(
"r." + mark-vertical + mark-horizontal,
radius: dot-radius,
fill: bar-color
)
}
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-rect_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(width: 150pt)
// Fit to text.
#rect(fill: conifer)[Textbox]
// Empty with fixed width and height.
#block(rect(
height: 15pt,
fill: rgb("46b3c2"),
stroke: 2pt + rgb("234994"),
))
// Fixed width, text height.
#rect(width: 2cm, fill: rgb("9650d6"))[Fixed and padded]
// Page width, fixed height.
#rect(height: 1cm, width: 100%, fill: rgb("734ced"))[Topleft]
// These are inline with text.
{#box(rect(width: 0.5in, height: 7pt, fill: rgb("d6cd67")))
#box(rect(width: 0.5in, height: 7pt, fill: rgb("edd466")))
#box(rect(width: 0.5in, height: 7pt, fill: rgb("e3be62")))}
// Rounded corners.
#stack(
dir: ltr,
spacing: 1fr,
rect(width: 2cm, radius: 30%),
rect(width: 1cm, radius: (left: 10pt, right: 5pt)),
rect(width: 1.25cm, radius: (
top-left: 2pt,
top-right: 5pt,
bottom-right: 8pt,
bottom-left: 11pt
)),
)
// Different strokes.
#set rect(stroke: (right: red))
#rect(width: 100%, fill: lime, stroke: (x: 5pt, y: 1pt))
|
https://github.com/hillbillybones/job-search | https://raw.githubusercontent.com/hillbillybones/job-search/main/README.md | markdown | # Job Search
This repository was created to manage the CV generation process using [Typst](https://github.com/typst/typst) and YAML.
## Files
- `cv.pdf`: The compiled CV in PDF format.
- `cv.typ`: The Typst source file.
- `cv.yaml`: The YAML file containing the CV data.
## Instructions
### Install Typst Compiler
To compile the Typst source file, you need to install the Typst compiler. Follow the instructions [here](https://github.com/typst/typst?tab=readme-ov-file#installation) to install the Typst compiler.
### Compile the CV
Once you have installed the Typst compiler, you can compile the CV by running the following command:
```typst compile cv.typ```
This will generate the `cv.pdf` file.
|
|
https://github.com/SkiFire13/master-thesis | https://raw.githubusercontent.com/SkiFire13/master-thesis/master/template.typ | typst | #import "config/printed.typ": pagebreak-to-right, pagebreak-to-left, left-right-margins, printed
#import "preface/titlepage.typ": titlepage
#import "preface/copyright.typ": copyright
#import "preface/acknowledgements.typ": acknowledgements
#import "preface/summary.typ": summary
#import "preface/toc.typ": toc
#let template(
affiliation: (
university: "University of Padua",
department: [Department of Mathematics "Tullio Levi-Civita"],
degree: "Master Degree in Computer Science",
),
title: "Titolo della tesi",
subtitle: "Tesi di laurea",
supervisor: "Prof. <NAME>",
candidate: (
name: "<NAME>",
id: 1234256
),
academic-year: "AAAA-AAAA",
keywords: (),
lang: "it",
date: datetime.today(),
body
) = {
set document(
title: title,
author: candidate.name,
keywords: keywords,
date: date,
)
set page(
margin: (top: 1in + 22pt + 18pt + 12pt, x: 3.5cm, bottom: 3.5cm),
header-ascent: 12pt + 18pt
)
set text(lang: lang)
set text(font: "New Computer Modern", size: 11pt)
set par(justify: true)
{
set heading(numbering: none)
set page(numbering: "i")
titlepage(
affiliation,
title,
supervisor,
candidate,
academic-year
)
pagebreak-to-right(weak: true)
copyright(candidate.name, title, date)
pagebreak-to-right(weak: true)
acknowledgements()
pagebreak-to-right(weak: true)
summary()
pagebreak-to-right(weak: true)
toc()
pagebreak-to-right(weak: true)
}
{
let header = context {
set text(size: 13pt)
let next_chapters = query(selector(heading.where(level: 1)).after(here()))
if next_chapters.len() > 0 and next_chapters.at(0).location().page() == here().page() {
align(right)[#counter(page).get().at(0)]
} else {
let chapter = query(selector(heading.where(level: 1)).before(here())).last()
if calc.rem(here().page(), 2) == 0 {
grid(
align: (left, right),
columns: (auto, 1fr),
[#counter(page).get().at(0)],
[#numbering("1", counter(heading).get().at(0)). #smallcaps(chapter.body)],
)
} else {
let subsection = query(selector(heading).before(here())).last()
grid(
align: (left, right),
columns: (1fr, auto),
[#numbering("1.1", ..counter(heading).get()). #smallcaps(subsection.body)],
[#counter(page).get().at(0)],
)
}
}
}
set page(numbering: "1", header: if printed { header }, footer: if printed { [] } else { none })
counter(page).update(1)
set heading(numbering: "1.1.1")
show heading.where(level: 1): it => {
pagebreak-to-right(weak: true)
smallcaps(text(size: 24pt, it))
v(1.5em)
}
show heading.where(level: 2): it => {
text(size: 18pt, it)
v(0.5em)
}
set list(indent: 0.5em)
show math.equation: it => {
show ".": math.class("punctuation", ".")
it
}
body
}
}
|
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/class.typ | typst | Apache License 2.0 | // Test math classes.
---
// Test characters.
$ a class("normal", +) b \
a class("binary", .) b \
lr(class("opening", \/) a/b class("closing", \\)) \
{ x class("fence", \;) x > 0} \
a class("large", \/) b \
a class("punctuation", :) b \
a class("relation", ~) b \
a + class("unary", times) b \
class("vary", :) a class("vary", :) b $
---
// Test custom content.
#let dotsq = square(
size: 0.7em,
stroke: 0.5pt,
align(center+horizon, circle(radius: 0.15em, fill: black))
)
$ a dotsq b \
a class("normal", dotsq) b \
a class("vary", dotsq) b \
a + class("vary", dotsq) b \
a class("punctuation", dotsq) b $
---
// Test nested.
#let normal = math.class.with("normal")
#let pluseq = $class("binary", normal(+) normal(=))$
$ a pluseq 5 $
---
// Test exceptions.
$ sqrt(3)\/2 quad d_0.d_1d_2 dots $ |
https://github.com/RiccardoTonioloDev/Bachelor-Thesis | https://raw.githubusercontent.com/RiccardoTonioloDev/Bachelor-Thesis/main/chapters/conclusioni.typ | typst | Other | #pagebreak(to: "odd")
= Conclusioni <ch:conclusioni>
== Raggiungimento obbiettivi
Si riassumono in seguito gli obbiettivi raggiunti durante il tirocinio:
- Il modello PyDNet V1 è stato verificato nei risultati enunciati dal proprio _paper_ @PyDNetV1;
- È stata migrata l'intera _codebase_ di PyDNet V1 e il modello di PyDNet V2 dal framework @Tensorflow al framework @PyTorch con successo:
- Sono stati ottenuti gli stessi risultati nell'allenamento a 50 epoche sul _dataset_ KITTI;
- Sono stati ottenuti gli stessi risultati nell'allenamento a 200 epoche sul _dataset_ KITTI;
- Sono stati ottenuti gli stessi risultati nell'allenamento a 50 epoche sul _dataset_ CityScapes, con successivo @finetune di 50 epoche sul _dataset_ KITTI;
- È stata di conseguenza acquisita conoscenza e abilità nell'uso della libreria @PyTorch e del linguaggio Python, specificatamente per la creazione di modelli di _machine learning_ e per la creazione di ambienti d'allenamento;
- È stata acquisita abilità nell'uso di _cluster_ di calcolo per l'allenamento dei modelli;
- È stata acquisita conoscenza relativamente a meccanismi di attenzione quali la _self attention_ e i _convolutional block attention module_, e ne è stata fatta successivamente l'implementazione in codice;
- È stata acquisita conoscenza nell'implementazione di moduli convoluzionali efficienti, specialmente lo _XiConv_ presentato in @xinet;
- È stata condotta dell'attività di ricerca e sviluppo con l'obbiettivo di implementare valide alternative ai modelli PyDNet nel contesto @embedded:
- È stato studiato come il cambiamento di vari iperparametri può portare a cambiamenti nelle prestazioni del modello;
- Sono stati eseguiti un totale di tredici esperimenti, per tredici modelli diversi;
- Tra i tredici modelli è stato trovato un modello particolarmente interessante ($beta$CBAM I), che con il 37% di parametri in meno rispetto a PyDNet V1, riesce ad essere migliore rispetto a quest'ultimo, nelle metriche di valutazione proposte in @eigen, di un minimo di $tilde 1%$ e di un massimo del $tilde 15%$.
#block([
== Considerazioni
In questa tesi, sono stati esplorati e sviluppati diversi modelli di rete neurale per la predizione della profondità da immagini monoculari, con l'obiettivo di migliorare la precisione e l'efficienza di tali predizioni. Le principali conclusioni raggiunte sono le seguenti:
+ *Migrazione di PyDNet*: La migrazione del modello PyDNet da @Tensorflow a @PyTorch ha dimostrato non solo la fattibilità di tale processo, ma ha anche permesso una più facile integrazione con modelli e blocchi più moderni;
],breakable: false,width: 100%)
+ *Esplorazione di XiNet*: L'introduzione di XiNet, un modello con un'architettura più efficiente, ha portato a miglioramenti significativi nella stima della profondità. Inoltre XiNet ha dimostrato di essere un modello più leggero e performante, quindi adatto per applicazioni su dispositivi con risorse computazionali limitate;
+ *Esplorazione dei Moduli di Attenzione (_CBAM_ e _self attention_)*: l'integrazione di moduli di attenzione come il _Convolutional Block Attention Module_ (_CBAM_) e i meccanismi di _self attention_ si è verificata essere una scelta vincente al fine di migliorare le performance del modello. Si è tuttavia notato come l'utilizzo della seconda non sia ideale per contesti di tipo _embedded_, mentre l'ultilizzo della prima deve essere fatto con criterio per ottenere buoni risultati;
+ *Ricerca e sviluppo di PyXiNet*: Le varianti sperimentali PyXiNet, che combinano le architetture di PyDNet e XiNet con moduli di attenzione, hanno dimostrato progressivi miglioramenti. In particolare PyXiNet $beta$CBAM I ha evidenziato come l'uso combinato di queste tecnologie possa portare a predizioni molto più accurate, con un piccolo compromesso sul tempo di inferenza e sul numero di parametri.
I risultati appena discussi fanno quindi capire che l'uso di tecniche di _deep learning_ per la stima delle profondità da immagini monoculari si è rivelato essere molto promettente, anche in ambienti con un potenziale di risorse molto limitato come il contesto _embedded_.
|
https://github.com/mangkoran/share.typ | https://raw.githubusercontent.com/mangkoran/share.typ/master/README.md | markdown | MIT License | <h1 align="center">
share.typ
</h1>
<p align="center">
<a href="LICENSE">
<img alt="MIT License" src="https://img.shields.io/badge/License-MIT_License-red"/>
</a>
</p>
A template to create awesome short writings to share in social media thanks to
[Typst](https://github.com/typst/typst) simple yet powerful syntax.
## Demo
<div align="center">
<img src="example.png" alt="Example Post">
</div>
## Usage
`share.typ` is intended to be used by importing `share.typ` file from a "content" file
([`example.typ`](example.typ) as example). This content file is used to call the functions which
apply document style & show post components and load post data from a YAML file
([`example.yml`](example.yml) as example). Inside the content file you can modify several style
variables and even override existing function implementations to your heart's content.
### With [Typst CLI](https://github.com/typst/typst) (Recommended)
The recommended usage with Typst CLI is by adding this `share.typ` repository as a [git
submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules). This way, upstream changes can be
pulled easily.
```
<your-post-repo>/
├── share.typ/ // git submodule
| └── share.typ
├── post/ // post YAML directory
| ├── 01-post-one.yml
| ├── 02-post-two.yml
| └── ...
└── <your-post-content>.typ // #import "share.typ/share.typ": *
```
1. Add [mangkoran/share.typ](https://github.com/mangkoran/share.typ) as git submodule into your
repo.
```
git submodule add https://github.com/mangkoran/share.typ
```
2. Copy and rename `example.typ` and `example.yml` to your repo root directory. For post YAML file
you can create a new directory (`post` or else) for better organization. Don't forget to update
the YAML import to reflect this. Use these files as template/starting point for your post.
3. Compile content file. Typst compiles to PDF by default. To compile Typst to PNG, use the
following command.
```bash
typst compile <your-post-content>.typ <output>.png
# or you can use `watch` command to auto recompile on change
# (a bit buggy tho especially with vi/vim/nvim)
typst watch <your-post-content>.typ <output>.png
```
### With [typst.app](https://typst.app)
1. Upload the [`share.typ`](share.typ), [`example.typ`](example.typ) and
[`example.yml`](example.yml) files to your Typst project. You may rename `example.typ` and
`example.yml`. For post YAML file you can create a new directory (`post` or else) for better
organization. Don't forget to update the YAML import to reflect this.
2. Use `example.typ` and `example.yml` (or whatever the names after you rename it) as
template/starting point for your post.
|
https://github.com/xubaiw/typst-rote | https://raw.githubusercontent.com/xubaiw/typst-rote/main/rote.typ | typst | #let measure-em(c) = {
let (width,) = measure(c)
int(width.pt() / 1em.to-absolute().pt())
}
#let cloze(it) = context {
show underline: u => {
[\u{ff3f}] * measure-em(u.body)
}
it
}
#let mnemonic(it) = context {
show terms.item: it => {
strong(it.term)
linebreak()
[\u{ff3f}] * measure-em(it.description)
linebreak()
}
it
}
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist/README.md | markdown | Apache License 2.0 |
# tinymist
This crate provides a CLI that starts services for [Typst](https://typst.app/) [taɪpst]. It provides:
+ `tinymist lsp`: A language server following the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/).
+ `tinymist preview`: A preview server for Typst.
## Usage
See [Features: Command Line Interface](https://myriad-dreamin.github.io/tinymist/feature/cli.html).
## Documentation
See [Crate Docs](https://myriad-dreamin.github.io/tinymist/rs/tinymist/index.html).
Also see [Developer Guide: Tinymist LSP](https://myriad-dreamin.github.io/tinymist/module/lsp.html).
## Contributing
See [CONTRIBUTING.md](https://github.com/Myriad-Dreamin/tinymist/blob/main/CONTRIBUTING.md).
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/027.typ | typst | #let date = datetime(
year: 2022,
month: 6,
day: 9,
)
#metadata((
title: "rust减少编译警告",
subtitle: [rust],
author: "dashuai009",
description: "项目前期开发中,可以通过RUSTFLAGS减少rust编译时给出的警告。后期去掉这些选项即可。",
pubDate: date.display(),
))<frontmatter>
#import "../__template/style.typ": conf
#show: conf
== rust编译信息
<rust编译信息>
#link("https://doc.rust-lang.org/reference/attributes/diagnostics.html")[diagnostics attributes]
#link("https://doc.rust-lang.org/rustc/lints/levels.html")[lints levels]
rust分为四种lint信息:
- #strong[allow( C )] overrides the check for C so that violations will go unreported,
- #strong[warn( C )] warns about violations of C but continues compilation.
- #strong[deny( C )] signals an error after encountering a violation of C,
- #strong[forbid( C )] is the same as deny( C ), but also forbids changing the lint level afterwards
默认情况下rust编译会给出#strong[大量警告信息];,比如变量命名不规范、未使用的变量等等。比较烦人,有很多种方法可以减少这些信息。
== 查看所有lint
<查看所有lint>
`rustc -W help`
== 通过lint check属性减少编译警告
<通过lint-check属性减少编译警告>
(lint check attribute 这不知道咋翻译了
将前边提到的C替换成`rustc -W help`看到的东西。比如给函数添加`#[allow(missing_docs)]`可以允许不写相关文档。
== 设置RUSTFLAGS
<设置rustflags>
执行rustc之前可以在export一些环境变量。
`export RUSTFLAGS="$RUSTFLAGS -A unused"; rustc balbalbaba`
在intellij系列的IDE中,可给运行/调试配置中自动添加这些环境变量。
不过,配置里#strong[不需要添加引号”];,他会自动加上。
#figure(
image("027/clion.png"),
caption: [
示意图
],
)
上边这个脚本配置相当于这条命令:
`export RUSTFLAGS="$RUSTFLAGS -A dead_code -A unused -A non_snake_case -A non_upper_case_globals -A non_camel_case_types"; wasm-pack build`
这里我用到了以下几个
- -A dead\_code
- -A unused 允许未使用(变量、函数等,一个lint group)
- -A non\_snake\_case 允许这三种不推荐的命名方式
- -A non\_upper\_case\_globals
- -A non\_camel\_case\_types
全给他allow。#strike[美滋滋,编译结果清净了] |
|
https://github.com/ilsubyeega/circuits-dalaby | https://raw.githubusercontent.com/ilsubyeega/circuits-dalaby/master/Type%201/1/25.typ | typst | #set enum(numbering: "(a)")
#import "@preview/cetz:0.2.2": *
#import "../common.typ": answer
1.25 다음 회로에서 주어진 시간 동안 전류가 흐르는 소자들만 포함하는 회로도를 그려라.
+ $t < 0$
+ $0 < t < 2 s$
+ $t > 2 s$
#answer[
+ $t < 0$
#image("../assets/t_first.png", width: 200pt)
+ $0 < t < 2$
#image("../assets/t_mid.png", width: 200pt)
+ $t > 2$
#image("../assets/t_large.png", width: 200pt)
] |
|
https://github.com/nicolasfara/presentation-2024-acsos-multi-tier-field-based-applications | https://raw.githubusercontent.com/nicolasfara/presentation-2024-acsos-multi-tier-field-based-applications/master/presentation-2024-acsos-multi-tier-field-based-applications.typ | typst | Apache License 2.0 | #import "@preview/polylux:0.3.1": *
#import "@preview/fontawesome:0.1.0": *
#import "@preview/ctheorems:1.1.2": *
#show: thmrules
#import themes.metropolis: *
#show: metropolis-theme.with(
aspect-ratio: "16-9",
// footer: [Optional Footnote]
)
#set text(font: "Fira Sans", weight: 350, size: 20pt)
#set enum(numbering: "(i)")
#show math.equation: set text(font: "New Computer Modern Math")
#set strong(delta: 200)
#set par(justify: true)
#set list(spacing: 1.9em)
#set quote(block: true)
#show quote: set align(left)
#show quote: set pad(x: 2em, y: -0.8em)
#set raw(tab-size: 4)
#show raw: set text(size: 0.75em)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: (x: 1em, y: 1em),
radius: 0.7em,
width: 100%,
)
#show bibliography: set text(size: 0.75em)
#show footnote.entry: it => {
block(inset: (x: 2em, y: 0.1em))[#text(size: 0.75em)[#it.note.body]]
}
#let fcite(clabel) = {
footnote(cite(form: "full", label(clabel)))
}
#let mail(email) = {
text(size: 1.3em)[#raw(email)]
}
#let authors = block(inset: 0.1em)[
#table(inset: 0.5em, stroke: none, columns: (auto, 4fr), align: (left, left),
[#alert[*N<NAME>*]], [#mail("<EMAIL>")],
[<NAME>], [#mail("<EMAIL>")],
[<NAME>], [#mail("<EMAIL>")],
)
#place(right, dy:-1em)[
#figure(image("images/disi.svg", width:40%))
]
]
// #set heading(numbering: "1")
#show: thmrules.with(qed-symbol: " ")
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#EDA7200F"))
#let proof = thmproof("proof", "Proof")
#title-slide(
title: [
Flexible Self-organisation for the Cloud-Edge Continuum: \
a Macro-programming Approach
],
// subtitle: "Subtitle",
author: authors,
// date: datetime.today().display("[day] [month repr:long] [year]"),
)
#new-section-slide("Background")
#slide(title: "Collective Self-organising Applications")[
A single program $mono("P")$ describes the *collective self-org* behavior of the system, using:
#side-by-side(columns: (2fr, auto))[
- *macroprogramming* abstractions
- *spatial* and *temporal* operators
- *proximity-based* interaction (neighbours)
- resilient *coordination* mechanisms
][
#align(right)[
#figure(image("images/scr-result.png", height: 44%))
]
// #figure(image("images/channel-sim.png", width: 42%))
]
#quote[Shift from a #underline[device-centric] to a #alert[collective-centric] view of the system.]
#align(center)[#underline[_Aggregate computing_] #fcite("DBLP:journals/computer/BealPV15") as a way to define such applications.]
]
#slide(title: "Self-org Computational Model")[
#alert[Behaviour]: _repeated_ execution with #underline[async rounds] \
#alert[Interaction]: _repeated_ *neighbours* #underline[messages exchange] \
#alert[Alignment]: each device execution is *aligned* with the others (program _AST_ alignment)
#line(length: 100%, stroke: 0.05em + rgb("#23373b"))
#only(1)[
1. Receiving #alert[messages] from neighbours
#figure(image("images/ac-messages-perception.svg", width: 74%))
]
#only(2)[
2. Computation of the #alert[macro-program] against the received messages
#figure(image("images/ac-computation.svg", width: 74%))
]
#only(3)[
3. Sending to neighbours the #alert[computed messages]
#figure(image("images/ac-messages-propagation.svg", width: 74%))
]
#only(4)[
4. Sleep until next #alert[round]...
#figure(image("images/ac.svg", width: 74%))
]
]
// Slide sul gradiente
#slide(title: [Distributed gradient])[
#side-by-side(columns: (1fr, 1fr))[
```scala
def gradient(source: Boolean): Int =
rep(PositiveInfinity): distance =>
mux(source)(0)(1 + minHood(nbr(distance)))
```
This function computes the distance from a #alert[source]
device to all the other devices in the network.
More complex *collective* components are built leveraging the #alert[gradient] function.
][
#only(1)[
#figure(image("images/gradient-1.svg"))
]
#only(2)[
#figure(image("images/gradient-1b.svg"))
]
#only(3)[
#figure(image("images/gradient-2.svg"))
]
#only(4)[
#figure(image("images/gradient-2b.svg"))
]
#only(5)[
#figure(image("images/gradient-3.svg"))
]
#only(6)[
#figure(image("images/gradient-4.svg"))
]
#only(7)[
#figure(image("images/gradient-4b.svg"))
]
#only(8)[
#figure(image("images/gradient-5.svg"))
]
#only(9)[
#figure(image("images/gradient-5b.svg"))
]
#only(10)[
#figure(image("images/gradient-6.svg"))
]
]
]
#slide(title: [Distributed gradient])[
#side-by-side(columns: (1fr, 1fr))[
```scala
def gradient(source: Boolean): Int =
rep(PositiveInfinity): distance =>
mux(source)(0)(1 + minHood(nbr(distance)))
```
This function computes the distance from a #alert[source]
device to all the other devices in the network.
More complex *collective* components are built leveraging the #alert[gradient] function.
][
#only(1)[
#figure(image("images/gradient-6b.svg"))
]
#only(2)[
#figure(image("images/gradient-7.svg"))
]
#only(3)[
#figure(image("images/gradient-7b.svg"))
]
#only(4)[
#figure(image("images/gradient-8.svg"))
]
#only(5)[
#figure(image("images/gradient-8b.svg"))
]
]
]
#slide(title: "Aggregate Programming")[
#side-by-side(columns: (2fr, auto))[
== Field Composition
```scala
def channel(source: Boolean, destination: Boolean): Boolean {
val toSource = gradient(source) // Field[Double]
val toDestination = gradient(destination) // Field[Double]
val distance = distanceTo(source, destination)
(toSource + toDestination - distance) <= 10
}
```
Functions take *fields* as #alert[input] and return *field* as #alert[output].
][
#figure(image("images/channel.svg", height: 50%))
]
//#v(0.5em)
#side-by-side(columns: (auto, auto), gutter: 2em)[
_Aggregate Computing_ provide us #alert[formal guarantees] on functional composition: reference for *deployment validation*.
][
The entire (_macro_-)program is executed by #alert[all the devices] in the network, \
assuming that each device *should* execute #alert[all] the functions.
]
]
#slide(title: "Edge-Cloud Continuum")[
#side-by-side(gutter: 2em, columns: (2fr, auto))[
#quote[Aggregation of #alert[computational resources] along the data path from the *edge* to the *cloud* #fcite("DBLP:journals/access/MoreschiniPLNHT22")]
#v(1em)
We must deal with different #alert[capabilities] and #alert[constraints]:
- #alert[edge devices]:
- used for #underline[sensing/acting] over the (physical) environment
- but they are typically *resources-constrained*
- #alert[cloud instances]:
- offer #underline[scalability] and #underline[computational power]
- but introduce *latency/privacy* issues
][
#figure(image("images/edge-cloud-continuum.svg", height: 80%))
]
// #align(center)[
// The #alert[opportunistic] use of the _continuum_ offers new possibilities, \
// but requires fexible #alert[deployment] strategies.
// ]
]
#new-section-slide("Motivation")
#slide(title: "Motivation")[
*Collective* programs are deployed on #alert[each physical device] of the application.
#side-by-side(columns: (2fr, auto), gutter: 1.5em)[
Two main #underline[limitations]:
1. *resource-constrained* devices cannot satisfy all the components' requirements
2. available *infrastructure* is not exploited to its full potential (performance vs cost)
Previous work #fcite("FARABEGOLI2024") tried to partition the _self-org/macroprogramming_ execution model but did not consider the *modularity* at the macro-program level.
][
#figure(image("images/ac-monolithic-motivation.svg", height: 68%))
]
]
#slide(title: "Different Service Requirements")[
#figure((image("images/macro-program-requirements.svg", width: 70%)))
#v(1em)
#align(center)[Each component *may* require multiple requirements to be executed.]
]
#new-section-slide("Macro-components") // Qui, se troviamo un nome per l'approccio, lo mettiamo
#slide(title: "Macro-programming Model")[
#side-by-side(columns: (2.5fr, 1fr), gutter: 1.5em)[
/ Macro-program: _direct acyclic graph_ (DAG) of #alert[components] // --- $mono("MP")\(overline(mono("C")), overline(mono("B"))\)$
/ Component: atomic functional macro-program taking a list of #alert[inputs] and producing an #alert[output] // --- $mono("C")$
/ Port: property of each _component_ through which the #alert[values] are received and produced (inputs and output of a function) // --- $mono("p")$
/ Binding: indicates that the #alert[output port] of a component is connected to the #alert[input port] of other components // --- $italic("component")\(mono("p"), mono("C"), overline(mono("p")))$
][
#figure(image("images/partitioned-macro-program.svg", width: 105%))
]
]
#slide(title: "Macro-programming Model: Local vs Collective Components")[
#side-by-side(columns: (2fr, auto), gutter: 1.5em)[
/ Local component: just a transformation of #alert[local inputs] to #alert[local outputs].
/ Collective component: requires the interaction with _instances_ of the #alert[same component] in *neighbours*.
][
#figure(image("images/collective-local-components.svg", height: 80%))
]
]
#slide(title: "System model")[
/ Application devices: devices executing the macro-program $mono("MP")$.
/ Infrastructural devices: devices supporting the execution of some parts of the $mono("MP")$.
#figure(image("images/system-model.svg", width: 55%))
]
#slide(title: "Application and deployment model")[
#side-by-side(columns: (2fr, auto), gutter: 1.5em)[
// The macro-program $#math.mono("MP")$ is executed by a $#math.bold("D")$ set of #alert[application devices].
// Typically the $#math.mono("C")^j_i$ component is executed on the $#math.delta _j$ device (called #alert[owner]).
// There may be conditions *preventing the execution* of the $#math.mono("C")^j_i$ component on the owner device (e.g., _lack sensor/actuators_, _computational capabilities_, ...).
Not all the components *can be executed* by the #alert[application device] (e.g., _lack sensor/actuators_, _computational capabilities_, _non-functional requirements_, ...).
In such cases, the _component_ is offloaded to an *infrastructural device* (#alert[surrogate]).
][
#figure(image("images/offloading-surrogate.svg", height: 75%))
]
#align(center)[
The offloading can be *iterative* determining a #alert[forward chain] involving multiple devices.
]
]
#slide(title: "Execution model: asyncronous round")[
- Each #underline[component] is #alert[independently executable].
- Its behaviour is organised in #alert[rounds].
- #underline[Outputs] of rounds at each component generate #alert[message] to be shipped.
#figure(image("images/message-propagation.svg", height: 52%))
_Execution model_ *formalised* via #alert[operational semantics].
// The #alert[main goals] of this execution model are (#underline[formalised in the paper]):
// - #alert[deployment independent] macro-program specification
// - #alert[self-stabilising] #fcite("DBLP:journals/tomacs/ViroliABDP18") property is preserved w.r.t. the "monolithic" deployment
]
#slide(title: "Deployment independence of self-stabilising computations")[
#only(1)[
#theorem(number: "1", [Self-stabilisation #fcite("DBLP:journals/tomacs/ViroliABDP18")])[
Given a $mono("MP")$ defining the components $mono(C)_1, #math.dots, mono(C)_n$ and a #underline[correct deployment], then, if:
+ all components implement #alert[self-stabilising] computation, and
+ sensor state is #alert[uniform] across all the #underline[forward chains]
then the result behaviour observed at the #underline[global output ports] is #alert[self-stabilising], and it is independently from the #alert[deployment] (same result of the *monolithic*).
]
]
#only(2)[
#proof("(base on operational semantics)")[
- No forwarding $#math.arrow$ same as #underline[monolithic] $#math.arrow$ #alert[true] as per#super("4")
- If only #underline[1] component $#math.arrow$ #alert[true] by #underline[hypotesis] (self-stabilising components)
- If #underline[multiple] components, #alert[true] as per #underline[functional composition]#fcite("DBLP:journals/tomacs/ViroliABDP18") of components
- If #underline[forward chain] > 1, and each device fairily #alert[fires], it is guaranteed that the message travels from #underline[source] to #underline[destination] and back $#math.arrow$ #alert[true] since the input messages are eventually the same
]
]
]
#slide(title: "Rescue scenario: partitioned macro-program")[
#figure(image("images/rescue-scenario.svg"))
]
#slide(title: "Rescue scenario: deployment example")[
#figure(image("images/rescue-scenario-deployment.svg"))
]
#new-section-slide("Evaluation")
// #slide(title: "Evaluation goals")[
// The evaluation aims at:
// 1. Validating the provided implementation toolchain and the proposed approach to test and #alert[simulate heterogeneous deployments]
// 2. Validating the ability of the system to converge to a stable state #alert[equal] to the one obtained in a monolithic deployment
// 3. Showcase the benefits of the proposal w.r.t. #alert[non-functional aspects] like low energy consumption
// ]
#slide(title: "Experimental setup")[
We setup #underline[three] incremental complex self-organising behaviours:
1. *Gradient*: computation of the distances from a source to all the other devices // #fcite("DBLP:journals/computer/BealPV15")
2. *SCR*: an implementation of the #alert[_self-organising coordination regions_] #fcite("DBLP:journals/fgcs/PianiniCVN21") pattern for splitting the network into sub-regions for handling problems in sub-spaces
3. *Rescue scenario*: a city event scenario where people participate in the event and when an emergency occurs, a rescue team intervenes to help the people
// ==== Objective
Empirically prove #alert[functional equivalence] w.r.t. the *monolithic deployment*, and #alert[non-functional benefits] of the approach.
]
#slide(title: "Results: gradient convergence")[
#figure(image("images/gradient_convergence.svg", width: 80%))
#figure(image("images/gradient_convergence_error.svg", width: 80%))
#align(center)[
When $t = 900$ the network stabilises, and the output converges to #alert[the same result].
]
]
#slide(title: "Results: SCR convergence")[
#figure(image("images/scr_convergence.svg", width: 80%))
#figure(image("images/scr_convergence_error.svg", width: 80%))
#align(center)[
When $t = 900$ the network stabilises, and the output converges to #alert[the same result].
]
]
#slide(title: "Results: rescue scenario")[
#figure(image("images/power_consumption.svg"))
#align(center)[
The #alert[modularisation] of the macro-program allows to #alert[reduce] the #alert[energy consumption] of the devices, but more messages are exchanged.
]
]
#new-section-slide("Conclusions")
#slide(title: "Conclusions and Future Work")[
We addressed the problem of #underline[multi-component] macro-program #alert[execution] and #alert[deployment] in the *ECC*, improving operational flexibility.
We proved both #underline[formally] and #underline[empirically] that the proposed approach preserves the same #alert[functional] behaviour of the monolithic counterpart, showing #alert[non-functional] benefits.
// *Future work*:
#figure(image("images/future-works.svg"))
// - Introduce #alert[capabilities] to constrain the components' execution
// - Support #alert[dynamic] deployments and #alert[reconfiguration] (also with *AI* techniques)
// - Integrates the approach with tools like #alert[kubernetes] to achieve *real deployments*
// - Exploit the *FaaS* paradigm for components offloading and execution
]
#focus-slide("Thank you!")
#slide[
#bibliography("bibliography.bib")
]
#slide(title: "System model: physical system")[
/ Physical system: network of #alert[physical devices] $#math.delta #math.in upright(bold("D"))_italic(P)$, exchanging messages according to #alert[physical neighbourhood] relation $cal(N)_P$.
#figure(image("images/physical-system.svg", width: 73%))
]
#slide(title: "System model: macro-program and application devices")[
/ Application logic: it is captured by a #alert[macro-program] $mono("MP")$.
/ Application devices: subset of the physical devices $upright(bold("D"))$ that execute the $mono("MP")$.
#only(1)[#figure(image("images/application-devices.svg", width: 73%))]
#only(2)[
#figure(image("images/application-devices-neighbourhood.svg", width: 73%))
#align(center)[The neighbouring relation of #alert[application devices] is a a #underline[subset] of $cal(N)_P$.]
]
]
#slide(title: "System model: infrastructural devices")[
/ Infrastructural devices: subset of the _physical devices_ $upright(bold("D"))_I #math.subset.eq upright(bold("D"))_P$ that #alert[can support execution] of some computation on behalf of some _application device_.
#only(1)[#figure(image("images/infrastructural-devices.svg", width: 73%))]
#only(2)[
#figure(image("images/infrastructural-devices-hybrid.svg", width: 73%))
#align(center)[A _physical deivce_ can be both an #alert[application device] and an #alert[infrastructural device].]
]
]
#slide(title: "System model: sensors and actuators")[
/ Sensors and actuators: a device is assumed to have #alert[sensors] and #alert[actuators] to interact with the local environment.
#figure(image("images/sensors-actuators.svg", width: 73%))
]
|
https://github.com/lelimacon/typst-minimal-cv | https://raw.githubusercontent.com/lelimacon/typst-minimal-cv/main/template/main.typ | typst | MIT No Attribution | #import "../package.typ": *
#let secondary-theme = (
accent-color: red,
body-color: red,
)
// To learn about theming, see https://github.com/lelimacon/typst-minimal-cv
#show: cv.with(
theme: (
//font: "Roboto",
//accent-color: purple,
//main-accent-color: red,
//main-body-color: green,
),
title: "<NAME>",
subtitle: "Developer, Developer, Developer",
aside: {
section(
theme: secondary-theme,
"Contact",
{
entry(
"Home",
"Hong Kong, China",
none,
)
entry(
"Phone",
link("https://wa.me/85212345678", "+852 1234 5678"),
none,
)
entry(
"Email",
link("mailto:<EMAIL>", "<EMAIL>"),
none,
)
entry(
"LinkedIn",
link("https://www.linkedin.com/in/john-doe", "in/john-doe"),
none,
)
},
)
section(
"Technology Stack",
{
entry(
"Web",
"ASP.NET + Blazor",
[
#progress-bar(100%)
],
)
entry(
none,
"Express + React",
[
#progress-bar(50%)
],
)
entry(
"Desktop",
"WPF",
[
#progress-bar(75%)
],
)
entry(
"Native",
"Xamarin, Flutter",
[
#progress-bar(50%)
],
)
entry(
"DBMS",
"MS SQL, PostgreSQL, MongoDB",
[
#progress-bar(75%)
],
)
entry(
"Ops",
"Scripting",
[PowerShell, VBS/VBA, Python],
)
entry(
none,
"Hosting, CI/CD",
[Terraform, Azure, DigitalOcean,\ GitHub Actions],
)
entry(
"Other",
"Gaming",
[Unity, Godot],
)
entry(
none,
"Graphics",
[Illustrator, Blender],
)
},
)
section(
"Languages",
{
entry(
right: [_Mother Ship_],
"Fluent",
"🇺🇸 English",
none,
)
entry(
right: [_Ich bin ein Berliner_],
"Proficient",
"🇩🇪 German",
none,
)
entry(
right: "恭喜發財",
none,
"🇨🇳 Mandarin",
none,
)
entry(
right: "いただきます",
"Basic",
"🇯🇵 Japanese",
none,
)
},
)
section(
"Extracurricular Activities",
{
entry(
"Culture",
none,
[Traveling, photography,\ cinephile, theater],
)
entry(
"Sport",
none,
[Hiking, bodybuilding, chess],
)
},
)
}
)
#section(
"Professional Experience",
{
entry(
right: [*\@Microsoft* – Cyberport, HK 🇭🇰],
"2020 - now",
"Software Engineer",
[
#par(lorem(24))
#list(
lorem(20),
lorem(7),
lorem(16),
lorem(16),
)
],
)
entry(
theme: secondary-theme,
right: [*\@Supersoft* -- Seattle, US 🇺🇸],
"2018 - now",
"Co-Founder, CTO",
[
#par(lorem(28))
#par(lorem(16))
],
)
entry(
right: [*\@Microsoft* -- Berlin, DE 🇩🇪],
"2016 - 2020",
"Software Engineer",
[
#par(lorem(12))
#list(
lorem(20),
lorem(16),
lorem(7),
)
],
)
entry(
right: [*\@Microsoft* -- Redmond, US 🇺🇸],
"2015 - 2016",
"CS Intern",
[
#par(lorem(12))
],
)
entry(
right: [*\@MIT* -- Cambridge, US 🇺🇸],
"2013, 2 yrs",
"Teaching Assistant",
[ #lorem(24) ],
)
},
)
#section(
"Educational Background",
{
entry(
theme: secondary-theme,
right: [*\@SNU 서울대학교* -- Seoul, KR 🇰🇷],
"2012, 6 mths",
"Univ. Exchange",
[ #lorem(16) ],
)
entry(
right: [*\@MIT* -- Cambridge, US 🇺🇸],
"2010 - 2015",
"Master of Engineering",
[ #lorem(24) ],
)
},
)
|
https://github.com/Coekjan/touying-buaa | https://raw.githubusercontent.com/Coekjan/touying-buaa/master/template/main.typ | typst | MIT License | #import "@preview/touying:0.5.2": *
#import "@preview/touying-buaa:0.2.0": *
// Specify `lang` and `font` for the theme if needed.
#show: buaa-theme.with(
// lang: "zh",
// font: ("Linux Libertine", "Source Han Sans SC", "Source Han Sans"),
config-info(
title: [Touying for BUAA: Customize Your Slide Title Here],
subtitle: [Customize Your Slide Subtitle Here],
author: [Authors],
date: datetime.today(),
institution: [Beihang University],
),
)
#title-slide()
#outline-slide()
= The section I
== Slide I / i
Slide content.
== Slide I / ii
Slide content.
= The section II
== Slide II / i
Slide content.
== Slide II / ii
Slide content.
|
https://github.com/luiswirth/bsc-thesis | https://raw.githubusercontent.com/luiswirth/bsc-thesis/main/src/setup.typ | typst | #import "@preview/cetz:0.2.1"
#import "math.typ": *
#import "layout.typ": *
#let monospaced(content) = text(font: "Fira Code", content)
#let weblink(url, content) = monospaced(link(url, content))
#let general-style(doc) = {
show: math-template
set page(paper: "a4")
set text(size: 10pt)
set text(font: "New Computer Modern Sans")
//set page(margin: 1cm)
//set par(justify: true)
//set page(fill: black)
//set text(white)
set page(fill: rgb("444352"))
set text(fill: rgb("fdfdfd"))
doc
}
#let preface-style(doc) = {
set page(numbering: "I")
set heading(numbering: none)
show heading: it => {
if it.level == 1 {
//pagebreak(weak: true)
v(70pt)
text(size: 25pt)[#it.body]
v(40pt)
} else {
let size = 20pt - 4pt * (it.level - 1)
set text(size, weight: "bold")
v(size, weak: true)
counter(heading).display()
h(size, weak: true)
it.body
v(size, weak: true)
}
}
doc
}
#let body-style(doc) = {
set page(numbering: "1")
counter(page).update(1)
set heading(numbering: "1.1.1")
show heading: it => {
if it.level == 1 {
pagebreak(weak: true)
v(60pt)
text(size: 18pt)[Chapter #counter(heading).display()]
v(0pt)
text(size: 25pt)[#it.body]
v(30pt)
} else {
let size = 20pt - 4pt * (it.level - 1)
set text(size, weight: "bold")
v(size, weak: true)
counter(heading).display()
h(size, weak: true)
it.body
v(size, weak: true)
}
}
doc
}
#let appendix-style(doc) = {
set page(numbering: "1")
set heading(numbering: "A.1.1")
counter(heading).update(0)
show heading: it => {
if it.level == 1 {
pagebreak(weak: true)
v(60pt)
text(size: 18pt)[Appendix #counter(heading).display()]
v(0pt)
text(size: 25pt)[#it.body]
v(30pt)
} else {
let size = 20pt - 4pt * (it.level - 1)
set text(size, weight: "bold")
v(size, weak: true)
counter(heading).display()
h(size, weak: true)
it.body
v(size, weak: true)
}
}
doc
}
#let postface-style(doc) = {
set page(numbering: "i")
counter(page).update(1)
set heading(numbering: none)
show heading: it => {
if it.level == 1 {
pagebreak(weak: true)
text(size: 25pt)[#it.body]
v(50pt, weak: true)
} else {
let size = 20pt - 4pt * (it.level - 1)
set text(size, weight: "bold")
v(size, weak: true)
counter(heading).display()
h(size, weak: true)
it.body
v(size, weak: true)
}
}
doc
}
|
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/brainstorm-launcher.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Identify: Moving Triballs",
type: "identify",
date: datetime(year: 2023, month: 9, day: 5),
author: "<NAME>",
witness: "<NAME>",
)
After discussing for a bit we realized that the only mechanism that would be
able to meet our goal of being able to get the triballs across the field in
under 5s is some kind of shooting mechanism.
= Options
#grid(columns: (1fr, 1fr), gutter: 20pt, [
== Puncher
#pro-con(pros: [
- Powerful (can reliably shoot under goal)
- Easy to tune
], cons: [
- Take up a lot of horizontal space
])
], image("/assets/launchers/puncher.svg", width: 90%), [
== Catapult
#pro-con(pros: [
- We have experience building them
- Powerful enough to shoot under goal
- Easy to tune
], cons: [
- Takes up a lot of space
])
], image("/assets/launchers/catapult.svg", width: 90%), [
== Flywheel
#pro-con(pros: [
- Very accurate speed control
], cons: [
- Easily burn out if not given enough power
- Difficult to correctly tune
])
], image("/assets/launchers/flywheel.svg", width: 90%))
|
https://github.com/johannesbrandenburger/typst-build-server | https://raw.githubusercontent.com/johannesbrandenburger/typst-build-server/main/README.md | markdown | # Typst Build Server
This project is a server that compiles a Typst project into a PDF. It accepts a ZIP file containing the Typst source files, extracts and compiles the project, and returns the compiled PDF.
## Features
- Accepts ZIP files with Typst projects.
- Compiles the specified Typst file into a PDF.
- Allows configuration of entry files, output names, and project root directories.
- Secures the build process with an API key.
## Endpoint: **POST /build**
This endpoint accepts a ZIP file containing the Typst project, extracts it, compiles the project, and returns the compiled PDF. The request must include an API key and specify the entry and output file names.
#### Request Parameters (URL or Form Data):
- `key` (required): A query parameter that must match the secret key (`TYPST_SECRET`) stored in environment variables. This is used for authentication.
- `entryfile` (optional): The name of the entry Typst file within the ZIP. Defaults to `main.typ`. Must end with `.typ`.
- `outputfile` (optional): The name of the compiled PDF file. Defaults to `main.pdf`. Must end with `.pdf`.
- `root` (optional): Gets passed to Typst as the root directory for the project `typst compile ... --root <root>`.
#### Request Body:
- The request body must contain the ZIP file under the `upload` field.
- The ZIP file must be a valid Typst project archive with the correct entry file specified.
#### Responses:
- **200 OK**: Returns the compiled PDF as a response with `application/pdf` content type.
- **400 Bad Request**: Returned if the request contains invalid parameters (e.g., wrong file type or filename).
- **401 Unauthorized**: Returned if the `key` parameter does not match the secret.
---
## Demo Request
Here is an example of how to make a request to the `/build` endpoint using `curl`:
```bash
# ZIP your Typst project
zip -r example-project.zip example-project
# Request to compile a Typst project
curl -X POST http://localhost:3000/build \
-H "Content-Type: multipart/form-data" \
-F "[email protected]" \
-F "entryfile=main.typ" \
-F "outputfile=compiled.pdf" \
-F "key=your_secret_key" \
--output compiled.pdf
```
In this example:
- `example-project.zip` is the ZIP file containing your Typst project.
- `main.typ` is the entry file for the project.
- `compiled.pdf` is the name of the generated PDF.
- `your_secret_key` is the secret key for authentication.
## Environment Variables
- `TYPST_SECRET`: The secret key used to authenticate requests to the server.
---
## Requirements (see below for Docker setup)
- **Typst**: Ensure that Typst is installed on the system, as it's required for compiling the projects.
- **Bun**: The project uses Bun.js for file handling and running shell commands.
---
## Setup
1. Clone the repository.
2. Install the dependencies using Bun:
```bash
bun install
```
3. Set up the environment variable `TYPST_SECRET` for authentication.
4. Start the server:
```bash
bun run dev
# or
bun run start
```
5. The server will be accessible at `http://localhost:3000`.
---
## Docker
You can also run the server using Docker. Here's how to build and run the Docker image:
1. Build the Docker image:
```bash
docker build -t typst-build-server .
```
2. Run the Docker container:
```bash
docker run -p 3000:3000 -e TYPST_SECRET=your_secret_key typst-build-server
```
3. The server will be accessible at `http://localhost:3000`.
|
|
https://github.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement | https://raw.githubusercontent.com/MyPedagogicalRessources/BUT1-R1-01-Initiation-developpement/main/TD/TD2-Trace-dessins.typ | typst | #let td2(isCorrection: true) = [
#import "@preview/lovelace:0.3.0": *
#import "../TD_TP_Commons.typ": *
= R101- TD2 - Tracé de dessins
== Objectifs
- Travailler l’écriture d’algorithmes par la méthode d’affinages successifs.
- Travailler les structures de contrôle.
== Spécifications du traceur
Soit un traceur défini par :
- une surface de travail,
- cinq compteurs notés c1, c2, c3, c4 et c5,
- un stylet,
- une position centrale notée o (ou origine),
- une orientation (ou points cardinaux),
- et une unité de longueur (u).
Les 6 actions élémentaires du traceur afin de manipuler le stylet sont :
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
table.header(
[*Nom de l'action*], [*Description*],
),
[_leverStylet_], [Cette action rompt le contact entre le stylet et la surface de travail ; si le stylet est déjà levé, l'opération est sans effet sur le dessin.],
[_baisserStylet_], [Cette action établit le contact entre le stylet et la surface de travail ; si le stylet est déjà baissé, l'opération est sans effet sur le dessin.],
[_centrerStylet_], [Cette action déplace le stylet à la position centrale, sans modification de sa hauteur ; si le stylet est déjà au centre, l'opération est sans effet sur le dessin.],
[_deplacerStylet_], [Cette action permet de déplacer le stylet d'une unité dans la direction cardinale courante sans modification de sa hauteur.],
[_pivoterDroite_], [Cette action modifie la direction cardinale courante de 90° dans le sens des aiguilles d'une montre.],
[_pivoterGauche_], [Cette action modifie la direction cardinale courante de 90° dans le sens inverse des aiguilles d'une montre.],
[_orienterNord_], [Cette action modifie la direction cardinale courante pour la faire pointer vers le nord.],
)
Concernant la manipulation d’un compteur nommé X, le traceur est capable de :
#table(
columns: (auto, auto),
inset: 10pt,
align: horizon,
table.header(
[*Nom de l'action*], [*Description*],
),
[_initialiser$C_x$_], [Cette action initialise le compteur $C_x$ à 0.],
[_ajouterUn$C_x$_], [Cette action incrémente le compteur $C_x$ de 1 ($C_x$ devient égal à $C_x + 1$.)],
[_comparerValeurs$C_x$Et$V$_], [Cette action compare la valeur du compteur $C_x$ à une valeur $V$ donnée.],
)
Voici quelques exemples pour manipuler les compteurs :
- _initialiser$C_1$_ → Le compteur C1 est initialisé vec la valeur 0 ;
- _comparerValeurs$C_1$Et$4$_ → La valeur du compteur $C_1$ st comparée avec 4. Le résultat peut être vrai ou faux.
- _comparerValeurs$C_1$Et$C_2$_ → La valeur du compteur $C_1$ st comparée avec la valeur du compteur $C_2$. Le résultat peut être vrai ou faux.
== Exercice 1
Nous proposons maintenant d’utiliser le traceur afin de tracer une croix centrée à l'origine de la surface de travail. Chaque branche de cette croix aura une longueur de 30 unités.
#figure(
image("figures/TD2/TD3_Fig1.png", width: 35mm)
)
+ Ecrire un algorithme en langage naturel permettant de tracer une telle croix en tenant compte des états initial et final suivants :
- *Etat initial (pré-condition):*
On admettra que la direction initiale de tracé est inconnue.
- *Etat final (post-condition):*
Le stylet devra être situé à l’origine, en position levée
#correction(displayCorrection: isCorrection)[
Même si l'écriture directe du programme est triviale, il est préférable d'écrire au préalable un algorithme. On peut imaginer pour le 1er niveau d'affinage :
#pseudocode-list(booktabs:true, title: smallcaps[Algorithme 1 : Tracé croix v1])[
+ orienter le stylet vers le Nord ;
+ aller au centre, stylet levé ;
+ tracer la branche Nord ;
+ revenir au centre, stylet levé ;
+ tracer la branche Est ;
+ revenir au centre, stylet levé ;
+ tracer la branche Sud ;
+ revenir au centre, stylet levé ;
+ tracer la branche Ouest ;
+ revenir au centre, stylet levé ;
]
Cet algorithme met en évidence quatre fois la séquence des deux actions :
- tracer une branche (alternativement Nord, Est, Sud et Ouest),
- revenir au centre, stylet levé.
On peut donc écrire une répétition et remplacer les actions de tracé des 4
branches par une seule action générique tracer une branche. Il vient alors :
#pseudocode-list(booktabs:true, title: smallcaps[Algorithme 2 : Tracé croix v2])[
+ orienter le stylet vers le Nord ;
+ aller au centre, stylet levé ;
+ *tant que* il reste une branche à tracer *faire*
+ tracer une branche de la croix;
+ passer à la branche suivante ;
+ fin *tant que* ;
]
Au 2ème niveau d'affinage, l'action complexe tracer une branche s'exprime aussi par une répétition :
#pseudocode-list(booktabs:true)[
+ #comment[tracer une branche de la croix]
+ baisser le stylet ;
+ *tant que* il reste une unité à tracer *faire*
+ tracer une unité ;
+ fin *tant que* ;
+ lever le stylet ;
]
On affine l’action complexe passer à la branche suivante par l’écriture :
#pseudocode-list(booktabs:true)[
+ #comment[passer à la branche suivante]
+ revenir au centre, stylet levé ;
+ pivoter à droite ;
]
On en déduit l'algorithme détaillé de tracé de la croix :
#pseudocode-list(booktabs:true, title: smallcaps[Algorithme 3 : Tracé croix v3])[
+ orienter le stylet vers le Nord ;
+ aller au centre, stylet levé ;
+ *tant que* il reste une branche à tracer *faire*
+ #comment[tracer une branche de la croix]
+ baisser le stylet ;
+ *tant que* il reste une unité à tracer *faire*
+ deplacer le stylet ;
+ fin *tant que* ;
+ lever le stylet ;
+ #comment[passer à la branche suivante]
+ revenir au centre, stylet levé ;
+ pivoter à droite ;
+ fin *tant que* ;
]
]
2. Traduire cet algorithme avec les actions élémentaires du traceur.
#correction(displayCorrection: isCorrection)[
#pseudocode-list(booktabs:true, title: smallcaps[Programme de tracé de la croix])[
+ orienterNord;
+ centrerStylet;
+ initialiserC1 ;
+ *tant que not* ComparerValeursC1Et4 *faire*
+ #comment[tracer une branche de la croix]
+ baisserStylet;
+ initialiserC2 ;
+ *tant que not* ComparerValeursC2Et30 *faire*
+ deplacerStylet;
+ ajouterUnC2 ;
+ fin *tant que* ;
+leverStylet;
+ #comment[passer à la branche suivante]
+ centrerStylet;
+ pivoterDroite;
+ ajouterUnC1 ;
+ fin *tant que* ;
]
]
] |
|
https://github.com/MobtgZhang/sues-thesis-typst | https://raw.githubusercontent.com/MobtgZhang/sues-thesis-typst/main/paper/chapters/abstract-cn.typ | typst | MIT License | #let 中文关键词 = ("论文", "typst", "模板")
本模板是为上海工程技术大学硕士研究生和学士本科生毕业涉及论文编写的Typst模板,旨在使用最新的高级Typst排版工具编写文档,专注于论文内容的写作,而不是花费过多时间和精力在格式的定制和调整上面。
本手册是对应模板的参考文档,其中提供了一些环境和命令可以让模板的使用更加方便,同时需要注意,使用者需要有一定的Typst编程基础和使用经验,至少学会使用Typst常见包的一些功能,例如调节字体间距或者修改字体大小等等。
上海工程技术大学硕士/学士毕业论文LaTeX模板更新地址参见#link("https://github.com/mobtgzhang/sues-thesis-typst","Github")。
|
https://github.com/sitandr/typst-examples-book | https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/index.md | markdown | MIT License | # Typst Basics
This is a chapter that consistently introduces you to the most things you need to know when writing with Typst.
It show much more things than official tutorial, so maybe it will be interesting to read for some of the experienced users too.
Some examples are taken from [Official Tutorial](https://typst.app/docs/tutorial/) and [Official Reference](https://typst.app/docs/reference/).
Most are created and edited specially for this book.
> _Important:_ in most cases there will be used "clipped" examples of your rendered documents (no margins, smaller width and so on).
>
> To set up the spacing as you want, see [Official Page Setup Guide](https://typst.app/docs/guides/page-setup-guide/).
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/125.%20top.html.typ | typst | top.html
The Top Idea in Your Mind
Want to start a startup? Get funded by
Y Combinator.
July 2010I realized recently that what one thinks about in the shower in the
morning is more important than I'd thought. I knew it was a good
time to have ideas. Now I'd go further: now I'd say it's hard to
do a really good job on anything you don't think about in the shower.Everyone who's worked on difficult problems is probably familiar
with the phenomenon of working hard to figure something out, failing,
and then suddenly seeing the answer a bit later while doing something
else. There's a kind of thinking you do without trying to. I'm
increasingly convinced this type of thinking is not merely helpful
in solving hard problems, but necessary. The tricky part is, you
can only control it indirectly.
[1]I think most people have one top idea in their mind at any given
time. That's the idea their thoughts will drift toward when they're
allowed to drift freely. And this idea will thus tend to get all
the benefit of that type of thinking, while others are starved of
it. Which means it's a disaster to let the wrong idea become the
top one in your mind.What made this clear to me was having an idea I didn't want as the
top one in my mind for two long stretches.I'd noticed startups got way less done when they started raising
money, but it was not till we ourselves raised money that I understood
why. The problem is not the actual time it takes to meet with
investors. The problem is that once you start raising money, raising
money becomes the top idea in your mind. That becomes what you
think about when you take a shower in the morning. And that means
other questions aren't.I'd hated raising money when I was running Viaweb, but I'd forgotten
why I hated it so much. When we raised money for Y Combinator, I
remembered. Money matters are particularly likely to become the
top idea in your mind. The reason is that they have to be. It's
hard to get money. It's not the sort of thing that happens by
default. It's not going to happen unless you let it become the
thing you think about in the shower. And then you'll make little
progress on anything else you'd rather be working on.
[2](I hear similar complaints from friends who are professors. Professors
nowadays seem to have become professional fundraisers who do a
little research on the side. It may be time to fix that.)The reason this struck me so forcibly is that for most of the
preceding 10 years I'd been able to think about what I wanted. So
the contrast when I couldn't was sharp. But I don't think this
problem is unique to me, because just about every startup I've seen
grinds to a halt when they start raising money � or talking
to acquirers.You can't directly control where your thoughts drift. If you're
controlling them, they're not drifting. But you can control them
indirectly, by controlling what situations you let yourself get
into. That has been the lesson for me: be careful what you let
become critical to you. Try to get yourself into situations where
the most urgent problems are ones you want to think about.You don't have complete control, of course. An emergency could
push other thoughts out of your head. But barring emergencies you
have a good deal of indirect control over what becomes the top idea
in your mind.I've found there are two types of thoughts especially worth
avoiding � thoughts like the Nile Perch in the way they push
out more interesting ideas. One I've already mentioned: thoughts
about money. Getting money is almost by definition an attention
sink.
The other is disputes. These too are engaging in the
wrong way: they have the same velcro-like shape as genuinely
interesting ideas, but without the substance. So avoid disputes
if you want to get real work done.
[3]Even Newton fell into this trap. After publishing his theory of
colors in 1672 he found himself distracted by disputes for years,
finally concluding that the only solution was to stop publishing:
I see I have made myself a slave to Philosophy, but if I get free
of Mr Linus's business I will resolutely bid adew to it eternally,
excepting what I do for my privat satisfaction or leave to come
out after me. For I see a man must either resolve to put out
nothing new or become a slave to defend it.
[4]
Linus and his students at Liege were among the more tenacious
critics. Newton's biographer Westfall seems to feel he was
overreacting:
Recall that at the time he wrote, Newton's "slavery" consisted
of five replies to Liege, totalling fourteen printed pages, over
the course of a year.
I'm more sympathetic to Newton. The problem was not the 14 pages,
but the pain of having this stupid controversy constantly reintroduced
as the top idea in a mind that wanted so eagerly to think about
other things.Turning the other cheek turns out to have selfish advantages.
Someone who does you an injury hurts you twice: first by the injury
itself, and second by taking up your time afterward thinking about
it. If you learn to ignore injuries you can at least avoid the
second half. I've found I can to some extent avoid thinking about
nasty things people have done to me by telling myself: this doesn't
deserve space in my head. I'm always delighted to find I've forgotten
the details of disputes, because that means I hadn't been thinking
about them. My wife thinks I'm more forgiving than she is, but my
motives are purely selfish.I suspect a lot of people aren't sure what's the top idea in their
mind at any given time. I'm often mistaken about it. I tend to
think it's the idea I'd want to be the top one, rather than the one
that is. But it's easy to figure this out: just take a shower.
What topic do your thoughts keep returning to? If it's not what
you want to be thinking about, you may want to change something.Notes[1]
No doubt there are already names for this type of thinking, but
I call it "ambient thought."[2]
This was made particularly clear in our case, because neither
of the funds we raised was difficult, and yet in both cases the
process dragged on for months. Moving large amounts of money around
is never something people treat casually. The attention required
increases with the amount—maybe not linearly, but definitely
monotonically.[3]
Corollary: Avoid becoming an administrator, or your job will
consist of dealing with money and disputes.[4]
Letter to Oldenburg, quoted in Westfall, Richard, Life of
Is<NAME>, p. 107.Thanks to <NAME>, <NAME>, <NAME>,
and <NAME> for reading drafts of this.
|
|
https://github.com/rzmk/various-dsat-math-notes | https://raw.githubusercontent.com/rzmk/various-dsat-math-notes/main/notes.typ | typst | // == Preamble ==
#import "@preview/ctheorems:1.1.0": *
#show: thmrules
#import "@preview/gentle-clues:0.4.0": abstract, question, info, example, error, warning, success, idea, memo, quote
#set page(margin: 1in, paper: "us-letter")
#set text(font: "Open Sans")
#show raw: set text(font: "New Computer Modern Mono")
#show heading: set block(above: 1.4em, below: 1em)
#show link: underline
#set page(
header: [
#h(1fr)
#counter(page).display(
"1/1",
both: true,
)
],
footer: [
#link("https://www.mueezkhan.com")[<NAME>] #h(0.4cm) #link("https://www.github.com/rzmk/various-dsat-math-notes")[_Various Digital SAT Math Notes_] #h(0.4cm)
#h(1fr)
v0.1.0 Released: 2023-11-22
]
)
// ctheorems setup
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
#let corollary = thmplain(
"corollary",
"Corollary",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
#let proof = thmplain(
"proof",
"Proof",
base: "theorem",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
// == Document ==
= Various Digital SAT Math Notes
Various notes based on various resources (refer to #link(label("bibliography"))[bibliography]). Authored by #link("https://www.mueezkhan.com")[<NAME>].
#info(title: "What is the Digital SAT?")[
- An exam taken on a laptop or tablet, using #link("https://bluebook.app.collegeboard.org/")[Bluebook]
- About 2 hours long
- Allows the use of a calculator on the entire math section
You may learn more about the Digital SAT from College Board and Khan Academy.
]
#idea(title: "Tip!")[Two methods you may prep for the Digital SAT are:
- Taking *full-length practice tests* (for example using College Board's #link("https://bluebook.app.collegeboard.org/")[Bluebook app])
- *Practicing skills* (for example by using #link("https://www.khanacademy.org/test-prep/v2-sat-math")[Khan Academy] to read articles, watch videos, and do exercises)
I also suggest watching *online videos* of instructors going through practice problems. You can pause videos and try to solve the problem yourself before continuing the video to learn the instructor's solution. This way you can get instant feedback on your work, and you'll be able to learn from the instructor's explanation.
]
#warning(title: "Important Message!")[
This document is intended as a *supplemental resource* for individuals preparing for the SAT. *The notes are not intended to be a comprehensive guide to the SAT nor as a sole resource used for preparing for the SAT.*
The notes are not endorsed by the College Board, Khan Academy, and any other organization mentioned in this document. Nor do I endorse any of the resources/organizations mentioned in this document.
If there are any errors, please open an #link("https://github.com/rzmk/various-dsat-math-notes/issues")[issue] or #link("https://github.com/rzmk/various-dsat-math-notes/pulls")[pull request] on #link("https://github.com/rzmk/various-dsat-math-notes")[GitHub].
]
#success(title: "One More Thing!")[
Believe in yourself! 🙌
]
#pagebreak()
#outline(title: "Table of Contents")
#pagebreak()
== "Essential SAT Math Formulas"
This section is primarily based on an SAT Math YouTube video by Scalar Learning @sl-math-full-review.
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*Name & Description*], [*Formula*], [*Example*],
[*Slope of a Line*: Finds the slope $m$ of a line passing through the points $(x_1, y_1)$ and $(x_2, y_2)$], [$ m = frac((y_1 - y_2), (x_1 - x_2)) $], [
Find the slope of the line that passes through the points $(7, 2)$ and $(5, 1)$.
$ m = frac((2 - 1), (7 - 5)) = frac(1, 2) $
],
[*Slope-Intercept Form*: Finds the equation of a line in the form $y = m x + b$ given the slope $m$ and $y$-intercept $b$], [$ y = m x + b $], [
Find the slope $m$ and $y$-intercept $b$ of the line $2x + 7y = 49$.
$ 2x + 7y = 49 $
$ 7y = -2x + 49 $
$ y = -frac(2, 7) x + 7 $
$ m = -frac(2, 7) $
$ b = 7 $
],
[*Point-Slope Form*: Finds the equation of a line in the form $y - y_1 = m (x - x_1)$ given the slope $m$ and a point $(x_1, y_1)$ on the line], [$ y - y_1 = m (x - x_1) $], [
Find the equation of the line that passes through the point $(3, 4)$ and has a slope of $frac(1, 2)$.
$ y - 4 = frac(1, 2) (x - 3) $
$ y - 4 = frac(1, 2) x - frac(3, 2) $
$ y = frac(1, 2) x + frac(5, 2) $
],
[*Midpoint Formula*: Finds the midpoint of the line segment with endpoints $(x_1, y_1)$ and $(x_2, y_2)$], [$ ((x_1 + x_2) / 2, (y_1 + y_2) / 2) $], [
Find the midpoint of the line segment with endpoints $(1, 2)$ and $(5, 6)$.
$ ((1 + 5) / 2, (2 + 6) / 2) = (3, 4) $
],
[*Distance Formula*: Finds the distance between the points $(x_1, y_1)$ and $(x_2, y_2)$], [$ sqrt((x_1 - x_2)^2 + (y_1 - y_2)^2) $], [
Find the distance between the points $(1, 2)$ and $(5, 6)$.
$ sqrt((1 - 5)^2 + (2 - 6)^2) $
$ sqrt(16 + 16) $
$ sqrt(32) $
],
[*Length of an Arc*: Finds the length of an arc with radius $r$ and central angle $theta$], [$ frac(theta, 360) (2 pi r) $], [
Find the length of an arc with radius $r = 5$ and central angle $theta = 60$.
$ frac(60, 360) (2 pi 5) = frac(1, 6) (10 pi) = frac(5 pi, 3) $
],
[*Area of a Sector*: Finds the area of a sector with radius $r$ and central angle $theta$], [$ frac(theta, 360) (pi r^2) $], [
Find the area of a sector with radius $r = 5$ and central angle $theta = 60$.
$ frac(60, 360) (pi 5^2) = frac(1, 6) (25 pi) = frac(25 pi, 6) $
],
[*Quadratic Formula*: Finds the roots ($x$-intercepts) of a quadratic equation $a x^2 + b x + c = 0$], [$ x = frac(-b plus.minus sqrt(b^2 - 4a c), 2a) $], [
Solve $x^2 + 3x - 4 = 0$.
$ x = frac(-3 +- sqrt(3^2 - 4(1)(-4)), 2(1)) $
$ x = frac(-3 +- sqrt(25), 2) $
$ x = frac(-3 +- 5, 2) $
$ x = -4, 1 $
],
[*SOHCAHTOA*: Finds the sine, cosine, and tangent of an angle $theta$ in a right triangle with hypotenuse $h$, adjacent side $a$, and opposite side $o$], [$ sin(theta) = frac(o, h) $ \ $ cos(theta) = frac(a, h) $ \ $ tan(theta) = frac(o, a) $], [
Find the sine, cosine, and tangent of an angle $theta$ in a right triangle with hypotenuse $h = 5$, adjacent side $a = 3$, and opposite side $o = 4$.
$ sin(theta) = frac(4, 5) $
$ cos(theta) = frac(3, 5) $
$ tan(theta) = frac(4, 3) $
],
[*Probability*: "How likely you're gonna win"], [$ frac("Number of Favorable Outcomes", "Total Number of Outcomes") $], [
Find the probability of rolling a 6 on a fair die.
$ frac(1, 6) $
],
[*Circle Equation*: $(h, k)$ is the center coordinate of the circle, and $r$ is the radius of the circle], [$ (x - h)^2 + (y - k)^2 = r^2 $], [
Find the equation of a circle with center $(h, k) = (3, 4)$ and radius $r = 5$.
$ (x - 3)^2 + (y - 4)^2 = 5^2 $
$ (x - 3)^2 + (y - 4)^2 = 25 $
\
Given the equation of a circle $x^2 + 4x + y^2 + 6y = 3$, find the center and radius.
$ x^2 + 4x + y^2 + 6y = 3 $
$ x^2 + 4x + 4 + y^2 + 6y + 9 \ = 3 + 4 + 9 $
$ (x + 2)^2 + (y + 3)^2 = 16 $
$ (x + 2)^2 + (y + 3)^2 = 4^2 $
$ (x + 2, y + 3) = (h, k) $
$ (h, k) = (-2, -3) $
$ r = 4 $
],
[*Exponential Growth/Decay*: When you increase/decrease in value. $y$ is the final amount, $a$ is the initial amount, $r$ is the rate of growth/decay, and $t$ is the time], [$ y = a (1 + r)^t $], [
Exponential Growth: Initial value of 200, growth rate of 13% per year, and time of 3 years.
$ y = 200 (1 + 0.13)^3 $
\
Exponential Decay: Initial value of 150, decay rate of 9% per year, and time of 2 years.
$ y = 150 (1 - 0.09)^2 $
],
[*Vertex of a Parabola*: When you have a quadratic in standard form ($y = a x^2 + b x + c$), you can get the $x$ value of the vertex. You may then plug the $x$ value back into the equation to get the $y$ value if required], [$ x = frac(-b, 2a) $], [
Find the vertex of the parabola $y = x^2 + 4x + 3$.
$ x = frac(-4, 2(1)) = -2 $
$ y = (-2)^2 + 4(-2) + 3 = -1 $
],
[*Vertex Form*: When you have a quadratic in vertex form ($y = a (x - h)^2 + k$), you can get the vertex $(h, k)$], [$ y = a (x - h)^2 + k $], [
Find the vertex of the parabola $y = 2x^2 + 4x + 3$.
$ y = 2(x^2 + 2x) + 3 $
$ y = 2(x^2 + 2x + 1 - 1) + 3 $
$ y = 2((x + 1)^2 - 1) + 3 $
$ y = 2(x + 1)^2 - 2 + 3 $
$ y = 2(x + 1)^2 + 1 $
$ (h, k) = (-1, 1) $
],
[*Pythagorean Theorem*: Finds the length of the hypotenuse $c$ of a right triangle with sides $a$ and $b$], [$ c^2 = a^2 + b^2 $], [
Find the length of the hypotenuse $c$ of a right triangle with sides $a = 3$ and $b = 4$.
$ c^2 = 3^2 + 4^2 $
$ c^2 = 9 + 16 $
$ c^2 = 25 $
$ c = 5 $
],
[*Distance = Rate $times$ Time*: Finds the distance $d$ traveled given the rate $r$ and time $t$], [$ d = r t $], [
Find the distance $d$ traveled given the rate $r = 5$ and time $t = 3$.
$ d = 5 * 3 = 15 $
\
If we're going 50 miles per hour and we've traveled 250 miles, how long have we been traveling?
$ d = r t $
$ 250 = 50 t $
$ t = frac(250, 50) = 5 $
We've been traveling for 5 hours.
],
[*Sine and Cosine*], [$ sin(x) = cos(90 - x) $], [
Find $sin(30)$.
$ sin(30) = cos(90 - 30) $
$ sin(30) = cos(60) $
],
[*Sum of Solutions of a Quadratic*: When you have a quadratic in standard form, you can get the sum of the solutions $x_1$ and $x_2$], [$ x_1 + x_2 = frac(-b, a) $], [
Find the sum of the solutions $x_1$ and $x_2$ of the quadratic $x^2 + 4x + 3 = 0$.
$ x_1 + x_2 = frac(-4, 1) = -4 $
],
[*The Discriminant of a Quadratic*: The number of real solutions _for a quadratic_ ($0 = a x^2 + b x + c$) \
- If $b^2 - 4a c > 0$, there are 2 real solutions
- If $b^2 - 4a c = 0$, there is 1 real solution
- If $b^2 - 4a c < 0$, there are 0 real solutions
], [$ b^2 - 4a c $], [
Find the number of real solutions for the quadratic $x^2 + 4x + 3 = 0$.
$ b^2 - 4a c $
$ = 4^2 - 4(1)(3) $
$ 16 - 12 = 4 > 0 $
There are 2 real solutions.
],
[*Area of an Equilateral Triangle*: Finds the area of an equilateral triangle with side length $s$. You may also draw an altitude to form a 30-60-90 right triangle and use the Pythagorean Theorem to find the height $h$], [$ frac(s^2 sqrt(3), 4) $], [
Find the area of an equilateral triangle with side length $s = 5$.
$ frac(5^2 sqrt(3), 4) = frac(25 sqrt(3), 4) $
],
[*30-60-90 Triangle*: When you have a 30-60-90 triangle with hypotenuse $h$, small leg length $a$, and the height $o$, you can find the side lengths using the following formulas], [
$ h = 2a $
$ a = a $
$ o = a sqrt(3) $
], [
Find the side lengths of a 30-60-90 triangle with hypotenuse $h = 10$.
$ a = frac(10, 2) = 5 $
$ o = 5 sqrt(3) $
],
[*Common Pythagorean Triples*], [
$ 3, 4, 5 $
$ 5, 12, 13 $
$ 7, 24, 25 $
$ 8, 15, 17 $
], [],
[*Perpendicular Slope*: the negative reciprocal of a slope $m = frac(a, b)$], [$ m = -frac(b, a) $], [
Find the perpendicular slope of $m = frac(3, 4)$.
$ m = -frac(4, 3) $
],
[*Parallel Slope*: the same slope as $m = frac(a, b)$ \ \ Also if two lines are parallel with a different $y$-intercept, then they have no solution. Otherwise if they're the same equation then they have infinitely many solutions.], [$ m = frac(a, b) $], [
Find the parallel slope of $m = frac(3, 4)$.
$ m = frac(3, 4) $
],
[*Sum of Angles (of any Polygon)*: Finds the sum of the interior angles of a polygon with $n$ sides], [$ "Sum" = (n - 2) 180 $], [
Find the sum of the interior angles of a pentagon.
$ (5 - 2) 180 = 3 * 180 = 540 $
]
)
#pagebreak()
#bibliography("bibliography.yml") #label("bibliography")
|
|
https://github.com/0xPARC/0xparc-intro-book | https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/ipa.typ | typst | #import "preamble.typ":*
= The inner product argument (IPA) <ipa>
IPA is actually a lot more general than polynomial commitment.
So the roadmap is as follows:
- In @ipa-pitch, describe the API of the inner product argument.
- In @ipa-induct and @ipa-base, describe the protocol.
- In @ipa-app, show two other applications of IPA, as a side demo.
- In @ipa-poly, show how IPA can be used as a polynomial commitment scheme.
Throughout this section, $E$ is defined as in @notation,
and there are fixed globally known generators
$g_1, ..., g_n, h_1, ..., h_n, u in E$ which are a computational basis (@comp_basis).
== Pitch: IPA allows verifying $c = sum a_i b_i$ without revealing $a_i$, $b_i$, $c$ <ipa-pitch>
Consider Pedersen commitments of the form
$ a_1 g_1 + ... + a_n g_n + b_1 h_1 + ... + b_n h_n + c u in E $
where $a_1, ..., a_n, b_1, ..., b_n, c in FF_p$.
#definition[
Let's say that an element
$ v = a_1 g_1 + ... + a_n g_n + b_1 h_1 + ... + b_n h_n + c u in E $
is *good*
(with respect to the basis $angle.l g_1, ..., g_n, h_1, ..., h_n, u angle.r$)
if $sum_1^n a_i b_i = c$.
]
The Inner Product Argument (IPA) is a protocol that kind of
resembles the older Sum-Check (described in @sumcheck) in spirit:
Peggy and Victor will do a series of interactions
which allow Peggy to prove to Victor that $v$ is good.
And Peggy will be able to do this without
having to reveal all of the $a_i$'s, $b_i$'s, and $c$.
(I think we missed a chance to call this "Inner Product Interactive Proof
Inductive Protocol" or something cute like this,
but I'm late to the party.)
== The interactive induction of IPA <ipa-induct>
The way IPA is done is by induction:
one reduces verifying a vector for $n$ is good (hence $2n+1$ length)
by verifying a vector for $n/2$ is good (of length $n+1$).
To see how you might think of the idea on your own,
check out this
#link("https://notes.0xparc.org/notes/pedersen-ipa", "0xPARC blog post").
To illustrate the induction, we'll first show how to get from $n=2$ to $n=1$.
So the given input to the protocol is
$ v = a_1 g_1 + a_2 g_2 + b_1 h_1 + b_2 h_2 + c u $
which has the basis $angle.l g_1, g_2, h_1, h_2, u angle.r$.
The idea is that we want to construct a new (good) vector $w$ whose basis is
$ angle.l (g_1 + lambda^(-1) g_2), (h_1 + lambda h_2), u angle.r $
for a randomly chosen challenge $lambda in FF_p$.
The construction is the following vector:
$ w(lambda) &:= (a_1 + lambda a_2) dot underbrace((g_1 + lambda^(-1) g_2), "basis elm")
+ (b_1 + lambda^(-1) b_2) dot underbrace((h_1 + lambda h_2), "basis elm")
+ (a_1 + lambda a_2)(b_1 + lambda^(-1) b_2) underbrace(u, "basis elm"). $
Expanding and isolating the parts with $lambda$ and $lambda^(-1)$ gives
$ w(lambda)
&= (a_1 g_1 + a_2 g_2 + b_1 h_1 + b_2 h_2 + c u) \
&#h(1em) + lambda dot underbrace((a_2 g_1 + b_1 h_2 + a_2 b_1 u), =: w_L)
+ lambda^(-1) dot underbrace((a_1 g_2 + b_2 h_1 + a_1 b_2 u), =: w_R) \
&= v + lambda dot w_L + lambda^(-1) dot w_R.
$
Note that, importantly, $w_L$ and $w_R$ don't depend on $lambda$.
So this gives a way to provide a construction of a good vector $w$
of half the length (in the new basis) given a good vector $v$.
This suggests the following protocol:
#algorithm[Reducing IPA for $n=2$ to $n=1$][
1. Peggy, who knows the $a_i$'s, computes
$ w_L := a_2 g_1 + b_1 h_2 + a_2 b_1 u in E
#h(1em) "and" #h(1em)
w_R := a_1 g_2 + b_2 h_1 + a_1 b_2 u in E, $
and sends those values to Victor.
(Note there is no dependence on $lambda$.)
2. Victor picks a random challenge $lambda in FF_q$ and sends it.
3. Both Peggy and Victor calculate the point
$ w(lambda) = v + lambda dot w_L + lambda^(-1) dot w_R in E. $
4. Peggy and Victor run the $n=1$ case of IPA to verify whether
$w(lambda)$ is good with respect the smaller $3$-element basis
$ angle.l (g_1 + lambda^(-1) g_2), (h_1 + lambda h_2), u angle.r . $
Victor accepts if and only if this IPA is accepted.
]
Assuming Peggy was truthful and $v$ was indeed good with respect
to the original 5-element basis for $n=2$,
the resulting $w(lambda)$ is good with respect to the new basis.
So the interesting part is soundness:
#claim[
Suppose $v = a_1 g_1 + a_2 g_2 + b_1 h_1 + b_2 h_2 + c u$ is given.
Assume further that Peggy can provide some $w_L, w_R in E$ such that
$ w(lambda) := v + lambda dot w_L + lambda^(-1) dot w_R $
lies in the span of the shorter basis,
and is good for at least four values of $lambda$.
Then all of the following statements must be true:
- $w_L = a_2 g_1 + b_1 h_2 + a_2 b_1 u$,
- $w_R = a_1 g_2 + b_2 h_1 + a_1 b_2 u$,
- $c = a_1 b_1 + a_2 b_2$, i.e., $v$ is good.
]
#proof[
At first, it might seem like a cheating prover has too many parameters
they could play with to satisfy too few conditions.
The trick is that $lambda$ is really like a formal variable,
and even the requirement that $w(lambda)$ lies in the span of
$ angle.l (g_1 + lambda^(-1) g_2), (h_1 + lambda h_2), u angle.r $
is going to determine almost all the coefficients of $w_L$ and $w_R$.
To be explicit, suppose a cheating prover tried to provide
$ w_L &= ell_1 g_1 + ell_2 g_2 + ell_3 h_1 + ell_4 h_2 + ell_5 \
w_R &= r_1 g_1 + r_2 g_2 + r_3 h_1 + r_4 h_2 + r_5. $
Then we can compute
$ w(lambda) &= v + lambda dot w_L + lambda^(-1) dot w_R \
&= (a_1 + lambda ell_1 + lambda^(-1) r_1)g_1 + (a_2 + lambda ell_2 + lambda^(-1) r_2)g_2 \
&+ (b_1 + lambda ell_3 + lambda^(-1) r_3)h_1 + (b_2 + lambda ell_4 + lambda^(-1) r_4)h_1 \
&+ (c + lambda ell_5 + lambda^(-1) r_5)u. $
In order to lie in the span we described, one needs the coefficient of $g_1$
to be $lambda$ times the coefficient of $g_2$, that is
$ lambda^(-1) r_1 + a_1 + lambda ell_1 = r_2 + lambda a_2 + lambda^2 ell_2. $
Since this holds for more than three values of $lambda$,
the two sides must actually be equal coefficient by coefficient.
This means that $ell_1 = a_2$, $r_2 = a_1$, and $r_1 = ell_2 = 0$.
In the same way, we get $ell_4 = b_1$, $r_3 = b_2$, and $ell_3 = r_4 = 0$.
So just to lie inside the span,
the cheating prover's hand is already forced for all the coefficients
other than the $ell_5$ and $r_5$ in front of $u$.
Then indeed the condition that $w(lambda)$ is good is that
$ (a_1 + lambda a_2) (b_1 + lambda^(-1) b_2) = c + lambda ell_5 + lambda^(-1) r_5. $
Comparing the constant coefficients we see that $c = a_1 b_1 + a_2 b_2$ as desired.
(One also can recover $ell_5 = a_2 b_1$ and $r_5 = a_1 b_2$,
but we never actually use this.)
]
So we've shown completeness and soundness for our protocol reducing $n=2$ to $n=1$.
The general situation is basically the same with more notation.
To prevent drowning in notation, we write this out for $n=6$,
with the general case of even $n$ being analogous.
So suppose Peggy wishes to prove
$v = a_1 g_1 + ... + a_6 g_6 + b_1 h_1 + ... + b_6 h_6 + c u $
is good with respect to the length-thirteen basis
$angle.l g_1, ..., h_6, u angle.r$.
#algorithm[Reducing IPA for $n=6$ to $n=3$][
1. Peggy computes
$ w_L &= (a_4 g_1 + a_5 g_2 + a_6 g_3) + (b_1 h_4 + b_2 h_5 + b_3 h_6)
+ (a_1 b_4 + a_2 b_5 + a_3 b_6) u \
w_R &= (a_1 g_4 + a_2 g_5 + a_3 g_6) + (b_4 h_1 + b_5 h_2 + b_6 h_3)
+ (a_4 b_1 + a_5 b_2 + a_6 b_3) u $
and sends these to Victor.
2. Victor picks a random challenge $lambda in FF_q$.
3. Both parties compute $w(lambda) = v + lambda dot w_L + lambda^(-1) dot w_R$.
4. Peggy runs IPA for $n=3$ on $w(lambda)$ to convince Victor it's good
with respect to the length-seven basis
$ angle.l g_1 + lambda^(-1) g_4, g_2 + lambda^(-1) g_5, g_3 + lambda^(-1) g_6,
h_1 + lambda h_4, h_2 + lambda h_5, h_3 + lambda h_6, u angle.r . $
]
== The base case <ipa-base>
If we're in the $n = 1$ case, meaning we have a Pedersen commitment
$ v = a g + b h + c u $
for $a,b,c in FF_q$, how can Peggy convince Victor that $v$ is good?
Well, one easy way to do that would be to just reveal all of $a$, $b$, $c$.
However, this isn't good enough in situations in which Peggy really
cares about the zero-knowledge part.
Is there a way to proceed without revealing anything about $a$, $b$, $c$?
The answer is yes, we just need more blinding factors.
#algorithm[The $n=1$ case of IPA][
1. Peggy picks random blinding factors $a', b' in FF_q$.
2. Peggy sends the following Pedersen commitments:
$
w_1 &:= a' g + a' b u \
w_2 &:= b' h + a b ' u \
w_3 &:= a' b' u.
$
3. Victor picks a random challenge $lambda in FF_q$.
4. Both parties compute
$
w &= v + lambda dot w_1 + lambda^(-1) dot w_2 + dot w_3 \
&= (a+lambda a') g + (b+lambda^(-1) b') h + (a+lambda a')(b + lambda^(-1) b') u.
$
5. Victor asks Peggy to reveal all three coefficients of $w$.
6. Victor verifies that the third coefficient is the product of the first two.
]
This is really the naive protocol we described except that
$a$ and $b$ have each been offset by a blinding factors
that prevents Victor from learning anything about $a$ and $b$:
he gets $a + lambda a'$ and $b + lambda^(-1) b'$, and knows $lambda$,
but since $a'$ and $b'$ are randomly chosen,
this reveals no information about $a$ and $b$ themselves.
== Two simple applications <ipa-app>
As we mentioned before, IPA can actually do a lot more than just
polynomial commitments.
=== Application: revealing an element of a Pedersen commitment
Suppose Peggy has a vector $arrow(a) = angle.l a_1, ..., a_n angle.r$
and a Pedersen commitment $v = sum a_i g_i$ to it.
Suppose Peggy wishes to reveal $a_1$.
The right way to think of this is as the dot product $arrow(a) dot arrow(b)$,
where $ arrow(b) = angle.l 1, 0, ..., 0 angle.r $
has a $1$ in the $1$st position and $0$'s elsewhere.
To spell this out:
#algorithm[Revealing $a_1$ in a Pedersen commitment][
1. Both parties compute $w = v + h_1 + a_1 u$.
2. Peggy runs IPA on $w$ to convince Victor that $w$ is good.
]
=== Application: showing two Pedersen commitments are to the same vector
Suppose there are two Pedersen commitments
$v = sum a_i g_i$ and $v' = sum a'_i g'_i$ in different bases;
Peggy wants to prove that $a_i = a'_i$ for all $i$
(i.e. the vectors $arrow(a)$ and $arrow(a')$ coincide)
without revealing anything else about the two vectors.
This can also be done straightforwardly:
show that the dot products of $arrow(a)$ and $arrow(a)'$
with a random other vector $arrow(lambda)$ are equal.
#algorithm[Matching Pedersen commitments][
1. Victor picks a random challenge vector
$arrow(lambda) = angle.l lambda_1, ..., lambda_n angle.r in FF_q^n$.
2. Both parties compute its Pedersen commitment
$w = lambda_1 h_1 + ... + lambda_n h_n$.
3. Peggy also privately computes the dot product
$c := arrow(a) dot arrow(lambda) = arrow(a)' dot arrow(lambda) = a_1 lambda_1 + ... + a_n lambda_n$.
4. Peggy sends a Pedersen commitment $c u$ to the number $c$.
5. Peggy runs IPA to convince Victor both $v + w + c u$ and $v' + w + c u$ are good.
]
This protocol provides a proof to Victor that $arrow(a)$ and $arrow(a)'$
have the same dot product with his random challenge vector $arrow(lambda)$,
without having to actually reveal this dot product.
Since Victor chose the random vector $arrow(lambda)$,
this check passes with vanishingly small probability
of at most $1/q$ if $arrow(a) != arrow(a)'$.
== Using IPA for polynomial commitments <ipa-poly>
Suppose now $P(X) = sum a_i X^(i-1)$ is a given polynomial.
Then Peggy can use IPA to commit the polynomial $P$ as follows:
- Peggy publishes Pedersen commitment of the coefficients of $P$;
that is, Peggy publishes $ g := sum a_i g_i in E. $
- Suppose Victor wants to open the commitment at a value $z$,
and Peggy asserts that $P(z) = y$.
- Victor picks a random constant $lambda in FF_p$.
- Both parties compute
$ v := underbrace((a_1 g_1 + ... + a_n g_n), C)
+ (lambda z^0 h_1 + ... + lambda z^(n-1) h_n) + lambda y u $
and run IPA on it.
(When Peggy does a vanilla IPA protocol, she can keep all $2n+1$ coefficients secret.
In this context, Peggy has published the first part $g$
and still gets to keep her coefficients $a_n$ private from Victor.
The other $n+1$ coefficients are globally known because
they're inputs to the protocol for opening the commitment at $z$.)
The introduction of the hacked constant $lambda$ might be a bit of a surprise.
The reason is that without it, there is an amusing loophole that Peggy can exploit.
Peggy can pick the vector $v$, so imagine she tries to swindle Victor by reporting
$v = a_1 g_1 + ... + a_n g_n - 10 u$ instead
of the honest $v = a_1 g_1 + ... + a_n g_n$.
Then, Peggy inflates all the values of $y$ she claims to Victor by $10$.
This would allow Peggy to cheat Victor into committing the polynomial $P$
but for each input $z$ giving Victor the value of $P(z) + 10$ rather than $P(z)$
(though the cheating offset would be the same at every value she opened).
The offset $lambda$ prevents this attack.
|
|
https://github.com/wumin199/wumin199.github.io | https://raw.githubusercontent.com/wumin199/wumin199.github.io/main/source/typst/math/understand_math.typ | typst | #set heading(numbering: "1.")
#show link: underline
#set text(
font: "Noto Serif CJK SC",
// font: "simsun",
size: 12.5pt
)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
= 常见公式
== 乘法公式
#figure(
image("乘法公式.png", width: 80%),
caption: [乘法公式],
) <multiplication_formula>
参考资料:
- #link("https://zh.wikipedia.org/zh-tw/%E4%B9%98%E6%B3%95%E5%85%AC%E5%BC%8F")[
wiki: 乘法公式]
== 三角函数
#figure(
image("trigonometric_functions.jpg", width: 80%),
caption: [特殊角三角函数值],
) <特殊角三角函数值>
#figure(
image("特殊角三角函数值.png", width: 80%),
caption: [特殊角三角函数值],
) <special_angle_rigonometrics>
参考资料:
- #link("https://www.geogebra.org/m/UtWkeRE5")[GeoGebra特殊角三角函数值]
- #link("https://zh.wikipedia.org/zh-sg/%E4%B8%89%E8%A7%92%E5%87%BD%E6%95%B0")[
wiki: 三角函数]
- #link("https://www.baike.com/wikiid/295765833290522275?view_id=1vh67qncay2o00")[特殊三角函数值]
== 泰勒展开
无穷可微函数$f(x)$的泰勒展开式为:
$
f(x) = sum_(n=0)^oo (f^n(a)) /(n!) (x-a)^n
$
$f^(n)(a)$表示函数$f$在$a$处的$n$阶导数,如果$a=0$,也把这个级数叫做麦克劳林级数.
#line(length: 100%, stroke: 0.2pt )
#set text(size: 14pt)
$
e ^ x = sum_(n=0)^oo x ^n /(n!)
= 1+ x + x^2/(2!) + x^3/(3!) + ... + x^n/(n!) + ... " "
forall ("对所有X都成立")
$
#line(length: 100%, stroke: 0.2pt )
$
sin x = sum_(n=0)^oo (-1)^n /((2n+1)!) x^(2n+1)
= x - x^3/(3!) + x^5/(5!) - ... " " forall
$
#line(length: 100%, stroke: 0.2pt )
$
cos x = sum_(n=0)^oo (-1)^n /((2n)!) x^(2n)
= 1 - x^2/(2!) + x^4/(4!) - ... " " forall
$
#line(length: 100%, stroke: 0.2pt )
参考资料:
- #link("https://zh.wikipedia.org/zh-sg/%E6%B3%B0%E5%8B%92%E7%BA%A7%E6%95%B0")[
wiki: 泰勒级数]
== 常见求导公式
#figure(
image("prime.png", width: 80%),
caption: [求导法则],
) <求导法则>
#line(length: 100%, stroke: 0.2pt )
$ (e^x)^prime = e^x $
$ (e^(f(x)))^prime = f^prime(x) e^(f(x)) $
#line(length: 100%, stroke: 0.2pt )
参考资料:
- #link("https://zh.wikipedia.org/zh-sg/%E5%AF%BC%E6%95%B0%E5%88%97%E8%A1%A8")[wiki: 导数列表]
= 公式理解
== 泰勒展开
=== $sin x$
```py
# 首先,计算 sin(x) 在 x=0 处的函数值和各阶导数。根据正弦函数的定义,有:
sin(0) = 0
# 对正弦函数求一阶导数,得到:
d/dx sin(x) = cos(x)
cos(0) = 1
# 对正弦函数求二阶导数,得到:
d^2/dx^2 sin(x) = -sin(x)
-sin(0) = 0
# 对正弦函数求三阶导数,得到:
d^3/dx^3 sin(x) = -cos(x)
-cos(0) = -1
# 对正弦函数求四阶导数,得到:
d^4/dx^4 sin(x) = sin(x)
sin(0) = 0
# 以此类推,可以得到:
d^5/dx^5 sin(x) = cos(x)
cos(0) = 1
d^6/dx^6 sin(x) = -sin(x)
-sin(0) = 0
d^7/dx^7 sin(x) = -cos(x)
-cos(0) = -1
d^8/dx^8 sin(x) = sin(x)
sin(0) = 0
# 根据泰勒级数展开式,将这些导数带入公式:
sin(x) = f(0) + f'(0)x + f''(0)x^2/2! + f'''(0)x^3/3! + ...
```
=== $e^x$
```py
e^x的导数还是e^x
e^0 = 1
...
带入到泰勒公式中得:
e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + x^5/5! + x^6/6! + ...
```
== 复数域内指数函数
#set text(size: 14pt)
$ z = a + i b " 复数的直角坐标表示" $
$ z = r e^(i theta) " 极坐标表示" $
$ r e^(i x) = r cos x + r * i *sin x $
#figure(
image("复指数函数.png", width: 80%),
caption: [复指数函数],
) <复指数函数>
当 $r=1, theta = pi$时,这就是欧拉公式:
$ e^(i pi) + 1 =0 $
常见的值如下:
$ e^((2 i pi) /3) = cos ((2 pi )/3) + i * sin((2 pi)/3) = -1/2 + i sqrt(3) /2 $ <cubic_root_formula>
它的意思是在复平面上以1为起点,沿着单位圆逆时针旋转120度到达的点。
根据 @复指数函数 的指数运算可得:
$ (e^((2 i pi) /3))^3 = e^(2 i pi) = 1 $ <120复根>
可以理解为走了3个120°
根据 @复指数函数 的指数运算可得:
$ (e^((2 i pi) /3))^2 = e^((4 i pi)/3 ) $
可以理解为走了2个120°
== 一元三次方程
一元二次方程有0,1,2个实根
一元3次方程,最多有3个实根,至少有1个实根
$
a x^3 + b x^2 + c x + d = 0, a eq.not 0 $ <一元三次方程>
令:
$ x = t - b/(3a) $ <一元三次方程求x>
$ p = (3 a c - b^2)/(3a^2) $
$ q = (2b^3 - 9 a b c + 27 a^2 d)/(27a^3) $
可化简的 @一元三次方程 为:
$ t^3 + p t = q = 0 $ <quadratic_equation>
有很多方法可以求解 @quadratic_equation
=== 卡尔达诺(Cardano)公式
$ u = root(3, (-q/2 + sqrt(q^2/4 + p^3/27))) $
$ v = root(3, (-q/2 - sqrt(q^2/4 + p^3/27))) $
简写以下:
$ Delta = sqrt(q^2/4 + p^3/27) $
$ u = root(3, (-q/2 + sqrt(Delta))) $
$ u = root(3, (-q/2 - sqrt(Delta))) $
$ w = e^((2 i pi) /3) = cos ((2 pi )/3) + i * sin((2 pi)/3) = -1/2 + i sqrt(3) /2 $
$ (e^((2 i pi) /3))^2 = e^((4 i pi)/3 ) = cos ((4 pi )/3) + i * sin((4 pi)/3) = -1/2 - i sqrt(3) /2 $
则:
$ t_1 = u + v $
$ t_2 = w u + w ^2 v = -(u + v)/2 + i sqrt(3)/2 (u - v) $
$ t_3 = w^2 u + w v = -(u + v)/2 - i sqrt(3)/2 (u - v) $
其中的 $0$, $w$, $w^2$ 可以根据 @120复根,理解为复平面内圆半径为1的三个点
然后根据 @一元三次方程求x 可得 $x$
=== 判别式(Discriminant)
#figure(
image("一元三次方程判别式.png", width: 100%),
caption: [一元三次方程判别式],
) <一元三次方程判别式>
参考资料:
- #link("https://zhuanlan.zhihu.com/p/137077558")[
知乎: 一元三次方程的求根公式]
- #link("https://zh.wikipedia.org/zh-sg/%E4%B8%89%E6%AC%A1%E6%96%B9%E7%A8%8B#%E5%8D%A1%E5%B0%94%E8%BE%BE%E8%AF%BA%E6%B3%95")[wiki: 一元三次方程,含推导和例子]
- #link("https://zhuanlan.zhihu.com/p/413976771")[从一元二次方程到群论(4):卡尔达诺公式] |
|
https://github.com/storopoli/cryptography-workshop | https://raw.githubusercontent.com/storopoli/cryptography-workshop/main/slides.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/slydst:0.1.0": *
#show: slides.with(
title: "Cryptography Workshop",
subtitle: none,
date: none,
authors: ("<NAME>", ),
layout: "medium",
ratio: 4/3,
title-color: orange,
)
#set text(size: 16pt)
#show link: set text(blue)
#let p = 1279
#let q = 71
/*
Level-one headings corresponds to new sections.
Level-two headings corresponds to new slides.
Blank space can be filled with vertical spaces like #v(1fr).
*/
== License
#align(horizon + center)[#image("images/cc-zero.svg", width: 80%)]
== Outline
#outline()
= One-way Functions
#align(horizon + center)[#image("images/omelet.jpg", width: 50%)]
== Factoring Numbers
#align(horizon)[
#text(size: 22pt)[
Factor this number into two prime numbers:
$ #{p * q } $
]
]
== Euclid GCD (300 BCE)
#link("https://en.wikipedia.org/wiki/Euclidean_algorithm")[Euclidean Algorithm]
#align(horizon + center)[#image("images/euclid.jpg", width: 30%)]
#text(size: 12pt)[
For 100+ digit numbers we have #link("https://en.wikipedia.org/wiki/General_number_field_sieve")[General Number Field Sieve].
]
== Easy to check
#align(horizon)[
#text(size: 22pt)[
- p: #p
- q: #q
$ p dot q = #{p * q } $
]
]
= Hash Functions
#definition(title: "Hash Functions")[
A hash function is any function that can be used to map data of arbitrary
size to fixed-size values.
]
#definition(title: "Cryptographic Hash Functions")[
A hash function that has statistical properties desirable for a
cryptographic application:
- One way function
- Deterministic
- Collision resistance
]
== SHA-2 and Its Functions
#definition(title: "SHA-2")[
SHA-2 (Secure Hash Algorithm 2) is a set of cryptographic hash functions
designed by the United States National Security Agency (NSA) and first
published in 2001.
- `SHA-224`
- `SHA-256`
- `SHA-384`
- `SHA-512`
]
== `SHA-256`
Our very special one:
- 64 rounds
- `AND`
- `XOR`
- `OR`
- `ROT`
- `ADD` $mod 2^(32)$
All of these stuff is non-linear and very difficult to keep track,
i.e. no way for you to "autodiff" this.
= Public-key Cryptography
#text(size: 14pt)[
#definition(title: "Public-key cryptography")[
Cryptography system that uses pair of keys: private and public.
Going from private to public is a one-way function.
]
Same idea as the prime number factoring problem:
- $S_k$: random integer
- $g$: "generator" number
- $p$: big fucking prime (4096 bits)
- $P_k$: $g^(S_k) mod p$
- Good luck finding $S_k$ from knowing only $P_k$
- But easy to verify that $P_k = g^(S_k) mod p$
]
= DSA
#text(size: 12pt)[
#algorithm(title: "DSA Signing")[
+ Choose two prime numbers $p, q$ such that $p - 1 mod q = 0$ (e.g. 1279 and 71)
+ Choose your private key $S_k$ as a random integer $∈ [1, q-1]$
+ Choose a generator $g$
+ Compute your public key $P_k$: $g^(S_k)$
+ Choose your nonce $k$: as a random integer $∈ [1, q-1]$
+ Compute your "public nonce" $K$: $(g^k mod p) mod q$ (also known as $r$)
+ Get your message ($m$) through a cryptopraphic hash function $H$: $H(m)$
+ Compute your signature $s$: $(k^(-1) (H(m) + S_k K)) mod q$
+ Send to your buddy $(p, q, g)$, $P_k$, and $(K, s)$
]
]
#text(size: 12pt)[
#algorithm(title: "DSA Verification")[
+ Compute $w = s^(-1) mod q$
+ Compute $u_1 = H(m) dot w mod q$
+ Compute $u_2 = K dot w mod q$
+ Compute $K^* = (g^(u_1) P^(u_2)_k mod p) mod q$
+ Assert $K = K^*$
]
]
== Why this works?
#align(horizon)[
#text(size: 14pt)[
#theorem(title: "DSA")[
- $s = k^(-1) dot (H + S_k K) mod q$ #text(blue)[($mod p$ and $H(m)$ implicit)]
- $k = s^(-1) dot (H + S_k K) mod q$ #text(blue)[(move $s$ to $k$)]
- $k = H dot s^(-1) + S_k K dot s^(-1) mod q$ #text(blue)[(distribute $s^(-1)$)]
- $k = H dot w + S_k K dot w mod q$ #text(blue)[($w = s^(-1)$)]
- $g^k = g^(H dot w + S_k K dot w mod q)$ #text(blue)[(put $g$ in both sides)]
- $g^k = g^(H dot w mod q) dot g^(S_k K dot w mod q)$ #text(blue)[(product of the exponents)]
- $g^k = g^(H dot w mod q) dot P^(K dot w mod q)_k$ #text(blue)[($P_k = g^(S_k)$)]
- $g^k = g^(u_1) dot P^(u_2)_k$ #text(blue)[(replace $u_1$ and $u_2$)]
- $K = K^*$ #text(blue)[(replace $K$ and $K^*$)]
]
]
]
= Schnorr
#text(size: 12pt)[
#algorithm(title: "Schnorr Signing")[
+ Choose a prime number $p$
+ Choose your private key $S_k$ as a random integer $∈ [1, p-1]$
+ Choose a generator $g$
+ Compute your public key $P_k$: $g^(S_k)$
+ Choose your nonce $k$: as a random integer $∈ [1, p-1]$
+ Compute your "public nonce" $K$: $g^k mod p$ (also known as $r$)
+ Get your message ($m$) through a cryptographic hash function $H$ concatenating with $K$: $e = H(K || m)$
+ Compute your signature $s$: $k - S_k e$
+ Send to your buddy $(p, g)$, $P_k$, and $(K, s)$
]
]
#v(2em)
#text(size: 12pt)[
#algorithm(title: "Schorr Verification")[
+ Compute $e = H(K || m)$
+ Compute $K^* = g^s P_k^e$
+ Compute $e^* = H(K^* || m)$
+ Assert $e = e^*$
]
]
== Why this works?
#align(horizon)[
#theorem(title: "Schnorr")[
- $K^* = g^s P_k^e$ #text(blue)[($mod p$ implicit)]
- $K^* = g^(k - S_k e) g^(S_k e)$ #text(blue)[($s = k - S_k e$ and $P_k = g^(S_k)$)]
- $K^* = g^k$ #text(blue)[(cancel $S_k e$ in the exponent of $g$)]
- $K^* = K$ #text(blue)[($K = g^k$)]
- Hence $H(K^* || m) = H(K || m)$
]
]
= Why we don't reuse nonces?
#v(2em)
#text(size: 20pt)[
#align(horizon + center)[
*Because we can recover $S_k$*:
]
]
== Recovering $S_K$ in DSA
#align(horizon)[
$ s' - s = (k'^(-1) (H(m_1) + S_k K')) - (k^(-1) (H(m_2) + S_k K)) $
If $k' = k$ (nonce reuse) then you can isolate $k$:
$ s' - s = k^(-1) (H(m_1) - H(m_2)) $
Remember: you know $s', s, H(m_1), H(m_2), K', K$.
And then derive $S_k$:
$ S_k = K^(-1) (k s - H(m)) $
]
== Recovering $S_k$ in Schnorr
#align(horizon)[
$ s' - s = (k' - k) - S_k (e' - e) $
If $k' = k$ (nonce reuse) then you can easily isolate $S_k$ with simple algebra.
Remember: you know $s', s, e, e'$ and $k' - k = 0$.
]
= Why we can combine Schnorr $s$ and not DSA?
#text(size: 10pt)[
Revisit the signature step in each one:
- DSA: $s = k^(-1) (H(m) + S_k K)$
- Schnorr: $s = k - S_k H(K || m)$
Modular addition, i.e. anything with $+, dot, -$, is linear:
$ P'_k + P_k = g^(S'_k) + g^(S_k) = g^(S_k' + S_k) $
and $s' + s$ in Schnorr is signed from $S_k' + S_k$ (assuming $m' = m$).
Modular inverse, i.e. anything with $x^(-1)$, is _not_ linear
and $s' + s$ in DSA is _not_ signed from $S_k' + S_k$ (assuming $m' = m$).
That is:
$ x^(-1) + y^(-1) != (x + y)^(-1) $
]
== Don't believe it?
#v(2em)
$ x^(-1) + y^(-1) != (x + y)^(-1) $
#align(horizon)[
```python
>>> p = 71; x = 13; y = 17;
>>> pow(x, -1, p) + pow(y, -1, p) == pow(x + y, -1, p)
False
```
]
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/048%20-%20Dominaria%20United/005_Episode%204%3A%20A%20Brutal%20Blow.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Episode 4: A Brutal Blow",
set_name: "Dominaria United",
story_date: datetime(day: 15, month: 08, year: 2022),
author: "<NAME>",
doc
)
Being on the #emph[Weatherlight] 's deck made Karn nostalgic. Even though a different crew scrambled along its rigging, laughed as they worked on the deck, and tinkered with its shining mechanisms, the scents and sounds felt comfortably eternal. Golden light scattered among the white clouds below and glistened on the beeswaxed decks. Blue skies stretched until the horizon. The sea breeze chilled his metal body. Only hours before, the four of them—Teferi, Jaya, Jodah, and <NAME>—had been pulled from the upper floor of Argive's watchtower one by one, dangling from a rope ladder like insects above the vast city below.
"Shanna is waiting," Jodah said. "We must set the #emph[Weatherlight] 's course."
Karn nodded, and Jaya fell into step beside them, her white hair streaming out behind her like a pennant. They entered the stateroom. Shanna stood near an oval table, her arms crossed over her burnished leather breastplate. Arvad, his already white skin sickly with his vampire's pallor, hung back in the shadows behind her. Teferi lay on a nearby cot, his eyes closed. Raff had pulled up a three-legged stool beside him. He'd splayed his hands over Teferi's gut wound and his magic's silvery sheen wafted from his palms like heat waves. Slimefoot joined them, mushroom-like pups cavorting around its base. Tiana squeezed her wings in tight to her body to fit through the door.
Shanna put out a fruit bowl Karn had thought to be ornamental and sat down. "I might be the captain, Karn, but you're setting the course. Tell me where the #emph[Weatherlight] flies."
"We must force the Phyrexians into open warfare," Karn said, "before they gain in strength and convert more populations. We will do this by baiting them with the three things the Phyrexians want more than anything else: the sylex, the Mana Rig, and~ me."
Jodah looked to Karn, worry brightening his eyes. "It's a risky plan. Defeat would mean losing Dominaria's most precious artifacts—and you, Karn. I don't like the idea of you in such danger."
"I like some risk," Jaya said. "If we draw them out, if we win, we kill the Phyrexians at the root. They're like ivy: you have to pull it early. Once it's established, it'll spread."
"If the events at Argivia have taught us anything," Karn said, "it is that our forces are stronger together than apart. Phyrexian tactics rely on dividing us, on the secret work the sleeper agents can perform in the shadows. If we are separate, we are vulnerable. Together, less so."
"Still," Jodah said, "our allies are stretched across all Dominaria. With Argivia fallen, the most powerful armed force on this continent is no longer ours—it is theirs. We have to recruit all the allies we can to make our stand."
"So we split up," Jaya said. "We recruit allies and bring them to the Mana Rig."
The crew from the #emph[Weatherlight ] had been quiet during this discussion, but now Raff sighed. The magic faded from his fingers. He looked up at Karn. "My sister will fight for you."
"I'll seek out Danitha," Jaya decided.
"Yavimaya's been attacked as well," Jodah said. "The elves will help us. I can go to them, to recruit them to fight at our side."
"I will go to the Mana Rig directly," Karn said, "to speak to Jhoira. I am the only one who has read and can remember the key I found to the sylex. I need to record that information for others to examine."
Teferi roused from his stupor. "I'll go with you, Karn. I need time to recover, and I can also recruit our Shivan allies while the Mana Rig and the sylex occupy you."
"You do not have good luck," Karn said, regarding Teferi's wounds.
"I think I have excellent luck," Teferi said. "I survived, didn't I?"
"If we split up," Jaya said, her hair gusting around her face, "how will we tell if any of us have been compromised? Stenn didn't even know he was one of them."
"The scryer has difficulty focusing on Phyrexians," Karn said. "If I cannot view you, I will assume you have been compromised."
"It's a good thing you don't sleep," Jaya said.
Shanna looked to her crew, who had been listening patiently. "It's decided. Let's set sail."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Red Iron Mountains were so beautiful that planning a war here seemed irreverent. Not that Jaya was the devout type, but those harsh jagged peaks with shale cascading down the ravines, white in the light, and the alpine blooms drooping from the meadows in sprays of purple and gold, and that massive androgynous statue of some hero whose story had been lost to time~
Well, maybe she was growing old, but Jaya could see herself relaxing outside a small cabin in a cedarwood tub in one of those shadowed valleys where war machines lay rotting, forgotten beneath emerald mosses and upright sword ferns, inert as boulders. Maybe with some chilled peppermint tea in hand. Now that would be a relaxing way to pass a decade or two.
She snorted at herself. #emph[Not like you're ever going to retire! ]
"Jaya!" Ajani strode from the trees' deep shadows, his white fur glinting in the light and his cloak rippling behind him. "Danitha told me you arrived. I have been seeking deer to feed the camp. There is good hunting here."
#figure(image("005_Episode 4: A Brutal Blow/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"Any luck?" Jaya asked.
Ajani offered her a fierce grin that revealed his teeth. "Always. The Llanowar millenaries remember the Phyrexian invasion well, and they've already sent scouts to join us. Some of the best archers in Dominaria."
When he'd leapt after <NAME>, Jaya had worried. "It looks like you didn't recover Aron?"
Ajani turned his gaze to Danitha's camp, established on the edge of a cloudy green glacier lake. Her Benalish knights had set up white canvas tents. In addition to House Capashen's proud tower with seven windows, House Tarmula's flag flew, a seven-pointed star upon it. A stewpot scented the air with smell of cooking onions.
"They outdistanced me, and by the time I circled around, you had left. So I started tracking them and encountered Danitha."
<NAME> strode through the camp toward Jaya and Ajani. Her light-brown skin glowed with health and her hair, shaved along the sides, had been drawn back into a tight plume. Her armor gleamed silver with ribbons of gold crossed across her chest like Gerrard's sash, embedded with stained glass that gleamed in red, scarlet, and yellow petals.
"I tracked the Phyrexians to a base south of here, concealed in some caves," Ajani said.
"My father must be there." Danitha turned to Jaya. "<NAME>, daughter of <NAME>, heir to the House Capashen. And you are?"
Well, well~ it had been some time since Jaya hadn't been recognized.
"J<NAME>," Ajani cleared his throat, "fights alongside Jodah the Eternal."
Jaya snorted. Jodah collected nicknames like some little boys collected marbles. "I'm here to invite you to bring reinforcements to Shiv."
"Any friend to Ajani is welcome here," Danitha said. "But unfortunately, I can't commit my troops to fight at Shiv until I've rescued my father."
"The delay—"
"Is worth it, and if you would like to assist me, I would appreciate your help," Danitha said. "If my father is alive, you'll have House Capashen's gratitude and knights to call upon. And if he's not~ well, you'll have House Capashen's new leader in your debt."
Jaya stretched her fingers, pulling flame from the air. The heat radiated across her skin. "Well, one sure way to get someone out of a cave is smoke."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
If there was any place on Dominaria where Jodah felt young, it was in the ruins of Kroog, in Yavimaya. The ancient domed building, its vaulting roof open to the sky, its golden stone draped with trailing pothos, seemed to hold the sunset's colors like a dragon-hoarded treasure. Exposed when a massive treefolk uprooted and migrated into the sea, it still smelled like earth.
"Jodah?"
He did not recognize the voice. A cerulean butterfly lit upon his shoulder. He moved to brush it away, then hesitated.
An elf stared at him, her light skin dappled with gold around her bright, intelligent eyes. Even though Jodah could not have said why, she seemed young. She wore a warrior's leather armor; scarlet, ochre, and orange, yet unlike the armor he'd seen on other Yavimayan elves, she'd integrated repurposed Thran technology.
#figure(image("005_Episode 4: A Brutal Blow/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"You're Jodah the Eternal?" she said. "The Archmage Jodah?"
Jodah coughed. For some reason, with the elf staring at him, he felt particularly self-conscious about the butterfly lazily beating its dinner plate-size wings near his face.
"<NAME> <NAME> told me all about you. Some people say there were many different Jodahs who took your name as a title, but I always thought there was only one."
"I'm here to negotiate with Meria," Jodah said, "to recruit troops to fight for the New Coalition at Shiv."
"You must be four thousand years old!" She looked him up and down like she'd look at an archaeological artifact. The butterfly flitted away. Jodah cleared his throat. He felt sized up, a sensation he did not appreciate.
Then the elf sighed. "I wish I could help you, Jodah. Since I was a child, I've dreamed of fighting alongside you, of leading my people to your aid~ of saving Dominaria together. But I'm sorry. I must think of my people."
Jodah smiled. So this was Meria. Only centuries of practice at diplomacy permitted him to conceal his shock. Seldom did elves follow someone with youth's freshness stamped upon their features—one reason he'd thought it best that he perform these negotiations himself. But then, seldom did elves seek shelter in old ruins, buildings of stone and metal. Dominaria was changing. "The Phyrexians are invading, Meria. It isn't a question of whether you fight. It's a question of when, of how—and the answers to both these questions, whether we will stand together, will determine if we achieve victory."
Meria dipped her head in solemn acknowledgement. "You are wise, Jodah the Eternal. I am honored to meet you. Truly, I am. But neither your words nor your name will sway me. I see no reason for my warriors to abandon their homes for your cause. Yes, if the Phyrexians shadowed our canopy, we would fight—on our home ground, with the advantage. But travel to Shiv? No, I think not."
"The Phyrexians can create sleeper agents," Jodah said. "They can infiltrate—"
"We know," Meria said. "But when Yavimaya allows my people to return, Multani will sort the good from the bad."
"Would you rather that the fight come here?" Jodah said. "Better to snuff the Phyrexian threat now than let Yavimaya burn."
Meria's eyes glinted. She wasn't angry. She wasn't scared. She wasn't even implacable. She was amused, and this befuddled Jodah most of all. He wasn't used to being laughed at by someone a fraction of his age.
"Very compelling arguments." Meria smiled and patted him on the shoulder. But Jodah could tell, as she turned away, that she'd made up her mind.
Jodah had failed. Meria would not lead her people to Shiv.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Jaya hunched behind a stone outcropping that overlooked the entire valley. Not the most comfortable position, but she couldn't complain about the view. At the end of a narrowing ravine, the cave's large triangular mouth gaped. Two Phyrexians guarded the opening, centipede-like monstrosities with butchered human bodies in their cores. Their multiple limbs glinted in the sunlight, restive.
From her vantage, Jaya could see what the Phyrexian monstrosities could not.
Ajani led half a dozen Llanowar scouts to remove the guards from the perimeter, clearing out the creatures that lurked in the shadowy woodlands. He'd been successful—so far. No dying creature had shouted an alert.
Danitha led the bulk of her force. Her knights lay in wait near the cave's mouth, concealing themselves in gullies, behind bushes and trees, in the mossy nooks behind granite boulders. Danitha held up her hand, signaling: #emph[Jaya, it's time.]
Jaya distilled her focus until it was keen as a blade inside her. She narrowed her eyes at the cave. The air itself combusted, exploding into flame. The pine needle turf smoldered, sending thick clouds of smoke toward the sky.
The Phyrexian guards launched into action, swarming through the underbrush. Danitha pointed at three knights, who charged, cleaving the nearest monstrosity with their broadswords. It fell into bloody hunks, each of which grew dozens of tiny legs. Danitha raised her hand again, and she sent another splinter force to drive the Phyrexian pieces toward Jaya's position.
Once they were near enough, Jaya sent out plumes of fire after each segment. This time, when the knights stabbed the cooking Phyrexian chunks, they stayed dead.
"Good riddance," Jaya muttered.
At the cave's entrance, heavy smoke coiled into the air. More Phyrexians poured from the cave—well over two dozen humanoid abominations.
"Nine Hells," Jaya muttered. The knights had revealed themselves too early. Their inexperience showed: they fought as if their opponents were ordinary soldiers, rather than interplanar horrors.
A vortex of flame shielding her, Jaya stalked down the hillside. As she blasted Phyrexians, she glimpsed brief horrors behind her gouts of fire: a compleated woman, iron coils escaping from her heart, stripping a Benalish knight of his armor like a child removing the limbs from an insect; a compleated child, plunging her wires beneath another knight's armor, bursting him apart from the inside. Danitha fought back-to-back with her second-in-command, her face grim.
The Benalish were being overwhelmed.
Ajani led his Llanowar scouts into the fray, cleaving the Phyrexian monstrosities with his double-headed axe. The Phyrexian advance halted, stymied.
#figure(image("005_Episode 4: A Brutal Blow/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
Jaya thought, for one hopeful moment, that the leonin had turned the battle in their favor, until a new Phyrexian emerged from the cave, more monstrosities at his heels. He was human-form, broad and muscular, with pale armor merging into his torso. Metal spikes curved through his pale blond hair like horns and his orange-irised eyes wept black oil across his ice-white cheeks. He held up his double set of arms, which merged at the biceps, in ironic welcome. "And here I was hoping some of my old crew might be in the rescue party. Shame—I was so looking forward to catching up."
Jaya, despite the fire in her hands, chilled down to her guts. #emph[Ertai.] She'd heard of him, sure—one of the original crew of the #emph[Weatherlight. ] He'd been dead for centuries—and still had death's pallor, though some force reanimated his twitching features. His eyes possessed a terrible intelligence.
"It's such a pleasure to be back," he said. "And I have learned so, so much in my time away. Would you like to see?"
And <NAME> stepped from the cave's mouth.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Karn brought out his sketch of the clay tablet he'd found in the Caves of Koilos, then lost in Oyster Bay. He traced the arcing symbols. Though he could remember what he had found perfectly, he could not make sense of it.
"Karn?" Teferi peeked into Jhoira's workshop, which Karn, in her absence, had co-opted. "I've spoken with Darigaaz, but the dragons are still deliberating."
"And the Ghitu?"
"The Ghitu will not commit until the dragons do. It's council politics."
"The viashino?"
"Same story." Teferi inclined his head. "Only the goblins have come forward."
"The goblins? That is a surprise," Karn admitted.
"They wanted to be first," Teferi said. "They're confident the dragons, the Ghitu, and the viashino will come to fight when the Phyrexians attack, but the goblins wanted to be able to say that #emph[they ] 'joined first' so they'll be able to use that as leverage in future relations." Teferi lay down on Jhoira's cot. He closed his eyes in exhaustion. Although magic had healed him, he was still recovering.
A screech broke the workshop's quiet—so loud that Jhoira's thinner beakers shattered. Teferi bolted upright, now alert. A second later an impact rattled down, shaking dust onto the delicate apparatuses, ruining experiments. The sulfurous stench wafting through the door made Teferi cough, though Karn's senses told him its concentration wasn't high enough to harm human life.
"What—" Teferi began.
Karn pressed his finger to his mouth to request quiet. He was listening. The #emph[Weatherlight] . Karn left the workshop. Though weary, Teferi followed.
In Shiv's skies—so hot they were not blue but a seared white—the #emph[Weatherlight ] wheeled through the sky, draped in the rotting detritus it had been using as camouflage from the Phyrexians hunting them. It seemed they hadn't been able to elude one, though, which circled them like a predator. Unfurled, the Phyrexian dominated the sky. Its thin bat-like wings had clawed metal tines with too many joints, and its body was a mass of fibers. The#emph[ Weatherlight ] fought it, firing harpoons into the beast, but the barbs fell through the loose mesh of fibers, useless. Magic blinked across the sky, but even Karn could see that this creature effortlessly outmatched the #emph[Weatherlight] .
But then a small shadow in Shiv's white sky grew closer, spreading two massive wings: a dragon. Even Karn had to appreciate a full-grown dragon: no mightier being existed on Dominaria, the apex of both violence and wisdom. The shadow brightened, glinting as the sun struck its scales. Darigaaz had come to their aid. He turned down, diving, and gained speed, until he struck the monstrosity.
The Phyrexian exploded at the impact, parted into a writhing mass. Still airborne, its fragmented body draped between its wings. The monstrosity attempted to draw itself together. Slick iron fibers wove and interlocked.
But Darigaaz had already pivoted midair. He exhaled a flame so white-hot over the Phyrexian monstrosity that it did not burn: it vaporized. Molten metal droplets rained onto the Mana Rig's deck, followed by Darigaaz himself. People scattered, retreating to a respectful distance.
"Planeswalker Teferi." Darigaaz bowed his head. "I accept your proposal to fight here at Shiv. I will defend our skies—no doubt, my brethren will join me. As will those from the other nations who have seats on the Shivan council."
Teferi strode toward the dragon. He bowed. "We accept the allegiance of the dragons of Shiv. Respectfully, of course."
Darigaaz bowed his head, solemn. He flung himself into the sky, his takeoff an economy of power, and spiraled upward into the blue.
In the silence, Jhoira slid down a rope from the #emph[Weatherlight] 's deck onto the Mana Rig. Her owl swooped down and landed on her shoulder, its metal body gleaming in the sun. "That's a hard act to follow."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
<NAME> stepped out from the cave. The surgical lines on his face still had raw edges, but they did not weep blood: instead, black oil glistened near the sutures. The lines did look~ artful, Jaya had to admit, as if Ertai had carefully considered each arcing cut over Aron's cheekbones, then deliberately contrasted it with the jagged line across his forehead. But otherwise, Aron seemed devastatingly human. His expression was anguished—unlike the other Phyrexians, he seemed self-aware. He was still <NAME>, and he knew what had been done to him, what it meant. His lips formed the words: #emph[please, don't look at me. ] But he did not, could not, voice them.
"Father." Danitha's gasp was hoarse—yet so pained. Jaya wished she could provide some iota of comfort.
"What have you done?" Ajani demanded.
"Sheoldred has taught me that beauty lies in change," Ertai said. "It's a hard lesson, when applied to oneself. But when applied to others, the beauty of change becomes more apparent, its aesthetics a revolution. Watch."
Aron's face opened along the surgical incision lines, unfurling to reveal that his skull had been replaced with steel, his eye with a crystal lens, and that his brain lay protected beneath glass. Unlike other Phyrexian monstrosities, Aron's changes had a clockwork intricacy, each delicate mechanism ticking and whirring. It reminded Jaya of a star map.
"My father is not your plaything." Danitha's voice sounded flat with shock, but her eyes burned with rage. Her hands on her broadsword, she stalked toward Ertai and Aron. Her father watched her with pained hope—for what, Jaya did not know.
No Phyrexians moved to intercept her.
Ertai watched with fascination. "Aron? Do your duty."
Aron lurched forward. He raised his hands, jerkily, and drew his sword. He lunged at Danitha. She parried, looking startled. His movements seemed bizarre, twitchy and unwieldy, like he was resisting himself. Or resisting Ertai's command? He swiped down again, and this time Danitha caught his blow on her broadsword. She forced him back, throwing him off. His intact eye wept glistening oil as he marched toward her again.
"Danitha," said Aron, his voice strange and distorted. "Do your duty." His words were a distorted echo of Ertai's.
Devastation crossed Danitha's face so quickly that Jaya, at this distance, almost missed it. But then Danitha's lips firmed. Her gaze turned both steely and pitying. "Yes, Father."
This time, when he brought his blade down on her, Danitha side-stepped. She raised her broadsword and swept it down in a graceful arc, separating his head from his shoulders.
Ertai watched all this with dispassion. "No respect for art. But I suppose I can always sew that back on."
He waved one three-fingered hand.
The mountains shook. Stone broke, and rubble tumbled down. Sharp shale spun past Jaya, cutting her cheek. She gasped and clutched at her injury. A Phyrexian monstrosity broke free from the mountain in front of them, shattering it into rubble. The roar of rock sliding from its body brought tears to Jaya's eyes. The monstrosity reared into the sky, so large that it blotted out the sun. Its plated body rose, brimming with complex mechanisms and weaponry, perched upon immense, deceptively thin legs. Its head was a battering ram, and its tail ended in a stinger, dripping with oily venom.
"Dim-Bulb's stupid horns~ that's #emph[huge] ," Jaya whispered. A Phyrexian dreadnought. It had to be the largest one she'd ever seen. "How are we supposed to fight #emph[that] ?"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Meria paused, her head cocked. Birds arrowed through the sky overhead, screaming. She watched them, a frown marring her forehead between her brows. Hoots boomed throughout the forest as monkeys shouted the alarm, and Jodah even heard the coughing roar of some great forest cat.
Meria turned to face him. "Something is coming."
She spun and ran out from the building. Jodah fell into pace beside her. In the distance, tree branches rocked—then shattered, exploding upward in a burst of greenery as a dragon engine reared into Yavimaya's vacant blue skies.
Jodah had never seen a mechanism so vast. Its bronze skull glistened in the hot tropical light, blotting out the sun. Its razor-edged back sloped away into the rainforest, longer than the ridge of a hill, and it waded through the trees—toward Jodah, Meria, and the elves.
The dragon engine's serrated mouth gaped open in a voiceless roar. Its thrum was so deep Jodah couldn't hear it: he could only feel it, like a blow to his heart. The vibrations traveled through the landscape, shattering branches. Parrots dropped from the trees, stunned. Small marsupials fell, eyes and noses bleeding. Jodah touched his face, pressing his index finger to the hot trickle that tickled his lips. He, too, bled. Yavimaya elves emerged from their buildings, scrambling to arm themselves. Riders led their kavu from the treetop stables. One male elf stumbled from his cottage holding an infant bleeding from its nose. He stared at Meria with beseeching eyes.
The dragon engine tore through the rainforest, uprooting a tree.
Meria gasped. "It's destroying Magnigoths. Those trees have stood for centuries!"
Jodah began to catalyze his spells. He could feel the power rising within him, so brilliant that it poured from his skin, that it lifted him from the ground, that it cradled him. To hold all this magic at the ready~ It was as integral to his being as his veins. He prepared himself.
All around him, Yavimaya elves evacuated their homes, dragging children and bundled belongings away from the fight. Jodah caught teary but brief farewells as warriors told their offspring to be quiet and brave and then embraced their partners before parting ways.
Warriors astride kavu clung to every tree branch, their bows, spears, and blades held at the ready. Spellcasters stood in phalanxes upon the mossy turf, brighter than blossoms in their finery, their fingers interlocked, their lips already moving with chants to conceal the retreating civilians. Meria gave Jodah an anguished look and led him to the forefront of her warriors.
With one sweep, the dragon engine cleared the ground between itself and the Yavimayan village. Ancient trees crashed to the ground, splintering, the leaf-shaped houses upon their boughs crushed. Soil clouded the air, then settled, revealing a raw ditch between the Yavimaya and the dragon engine. The dragon engine had not only uprooted ancient trees so that their roots framed the battlefield, exposing dirt—it had also revealed artifacts from the Thran city deep beneath the Ruins of Kroog. Ground water seeped through the rich loam, pooling around the golden objects. Meria gasped.
"I recognize that," she breathed. "From my studies. Oh, that—Jodah, that is our hope."
Jodah couldn't determine which object Meria meant in the jumble, but that she had picked out one artifact from this distance was remarkable. Little wonder that the Yavimayans followed her.
The dragon engine craned its head as if to look at their armed forces. Within its skull, its driver sat like a jewel, illuminated with a pale blue light. Even from this distance Jodah could make out her features, see the red light of her replaced eye. She matched Karn's descriptions: Rona. Her teeth were barred in a fierce smile.
In an echo of Rona's own body language, the dragon engine opened, exposing its barbed jaws. Within its mechanized armor plates, the remains of small, rotting forest creatures hung suspended between oily ligaments. Rona had butchered them to restore the dragon engine's bulk.
Jodah's stomach turned.
"Archers!" Meria cried.
The Yavimayans loosed their arrows, but they were useless against the dragon engine's plates. Jodah could feel the machine building its energy—and at this proximity another roar would wipe them out.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Ertai laughed softly. He lifted his arms. The upper set had only three stubby fingers on each hand, which he beckoned with. The dreadnought swung its tail around and crushed Phyrexians and Benalish knights alike as it spewed venom. The viscous fluid arced out, so acidic it melted trees and boiled the alpine creek. The blow echoed throughout the mountain range, triggering distant rockfalls and avalanches.
Despite the cacophony of tumbling rock, Jaya could still hear Ertai's delighted laughter. He waved his arms, and the Phyrexians launched themselves into the devastated Benalish forces. Ajani fought at Jaya's back, hacking away at the creatures that skittered toward her. Danitha retreated to aid her troops. She shouted orders that caused the Benalish knights to reform around the Llanowar archers, circling up now that they were surrounded.
"Fire," she called, and the Llanowar elves released their bowstrings. Their arrows rebounded off the dreadnought's legs, not even denting its armor.
The dreadnought stretched and straddled the battlefield. It arched its spine. If it released more acid, they'd surely be doomed~
"Stop!" Ertai called. His Phyrexians scuttled back, retreating into the rocks like so many crabs. The larger ex-human creatures ran toward the dreadnought's legs and clung there. Some knights paused. "Call off your fighters, Danitha."
"Or~?" Danitha asked.
Ertai smiled. He pointed at the dreadnought with one upper hand and the melted slag from its acid spray with the other. He raised his eyebrows. The bristles along his head seemed to lift with pleasure.
"Or," he said.
Danitha lifted one hand. Her knights stopped fighting. Jaya let her flames die, overexertion washing through her. Ajani settled back, his double-handed axe weighed between his palms with more than some reluctance, teeth bared. He met Jaya's gaze, and she gave him an exhausted shrug. She didn't have a plan.
"Jaya. Ajani. If you don't give yourselves up to me," Ertai said, "I will tell the dreadnought to eradicate these people. All of them."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Jodah lifted his hands, raising his energy to form a protective barrier. The shield rippled from its brightest point, a white sheen that colored the air itself. He couldn't mitigate the effects of the dragon's booming roar, but he could soften them—even if his spell, however powerful, would only hold up beneath one blast.
"There. I need to reach that." Meria pointed at an uncovered Thran artifact that lay in the dirt between her troops and the dragon engine. She touched Jodah on the arm and looked up at him hopefully. "Can you leave that shield there to protect my people while you come with me? Out on the battlefield, I mean."
Jodah nodded. What was the nature of this artifact, that Meria pinned her people's lives on it? "Yes, I can do that."
Meria raised her voice in a cry, which Jodah assumed meant "hold," because he saw the archers shift from offensive to defensive postures, eyes wary. She nodded in satisfaction, then returned her attention to Jodah. "Ready?"
Jodah stretched out his fingers and pressed them into the air. The spell shimmered in response, then stabilized. Meria smiled at him, her face sharpened with intelligence and eagerness. She tapped her spear on the ground, and an intricate Thran tracery illuminated its length. Metal spurs shot out from one end of the spear, and a translucent webbing unfurled between them. Her spear appeared to also function as a powered Thran glider.
Meria threw one arm around him. "Hold on tight!"
Jodah stiffened—but too late. The glider jerked them both from their feet. He found himself unceremoniously clinging to Meria as the glider drove them both through the air. They zipped through his magical barrier. It offered some resistance, flexing, but permitted them passage. Hot magic buzzed along their skin, shocking in its power. The glider took a sharp turn, then dived toward the earth. They splashed down into a crater quickly filling with brackish water—right at the dragon engine's feet.
"Cover me," Meria said.
"Is that why I'm here?" Jodah said, dryly. But he readied his spells. He could still feel the shield they'd left behind to protect the Yavimayan warriors draining him. This did not stop him from summoning his reserves. "I'll do my best."
"Good." Meria, heedless of the filth, dropped to her knees and started searching the muddy waters. "It's here somewhere. I know I saw it~"
The dragon engine roared. Jodah flung up a radiant white bubble, protecting them. The sonic force beat against both of Jodah's shields. He summoned more arcane force to meet and negate the concussive energy; the dragon engine's roar heightened, then died. Jodah's shields faded with it, and exhausted, he fell to his knees. His entire body felt pummeled, like he'd stretched himself physically behind those shields to hold them. He didn't have it in him to do it again.
The dragon engine craned its head toward them. Jodah had the nasty suspicion Rona intended to target both him and Meria more directly with her next blow. "Hurry!"
"Aha!" Meria fished a silver globe covered in delicate golden Thran traceries from the muck. "Found it! I knew I'd seen one of these."
Meria's eyesight had to be exquisite for her to pinpoint #emph[and ] recognize a Thran artifact amongst the roots, dirt, and debris after the dragon engine's attack. "What is it?"
Meria twisted the globe, realigning the symbols into new configurations. It lit up. Brightness raced along the globe's equator at a quicker and quicker pace. Jodah could recognize a countdown anywhere. Meria cocked her head. "How fast do you think you can get us out of here?"
Jodah grit his teeth and readied a portal. The effort winded him even though he'd set the portal to transport them only a short distance. But he had already expended much of his strength in this battle. It felt like he peeled open that doorway-in-the-air with his fingernails.
Meria dove through, and Jodah leaped after her. He spun, held out his hand, and clenched it into a fist. The portal collapsed—just in time. The Thran artifact flashed, a bright red light that saturated the landscape as if in warning, and then instead of a boom there was—
Silence.
Between the Yavimayan elves and the dragon engine, a thin film seemed to have formed. But it wasn't a film, not really. On the one side—the side on which Jodah stood—the air was thick with cloudy pollen, dust the dragon engine had kicked up, and humidity. He'd never realized that air had a color: not until he'd looked from an area #emph[with] air to an area #emph[without] it.
The Thran weapon had created a spherical vacuum. The dragon engine stood in the center of it, and it roared—and roared—in absolute silence.
But even from here Jodah could see how the dragon engine failed: the organic pieces inside it died. The mangled remains of the woodland creatures, confronted with vacuum, froze. Inside the dragon engine, tendons snapped, organs turned to slimy ice or burst, and muscle fibers solidified. The dragon's wires, writhing beneath its armor, seemed to have become more brittle. More than a few snapped off. The lights faded from the dragon engine, dimming inside its skull.
"I don't think the artifact is a weapon, really." Meria perched one hand on her hip. "I think the Thran used it to conduct scientific experiments in a vacuum. That's what I would do."
No, Jodah thought. This was a weapon. Perhaps even a Damping Sphere, though he'd never seen one do that before.
The dragon engine staggered toward the field's edge, then collapsed through the barrier. It fell so that half its body was in woodland and the other half remained in the vacuum. Rona, a distant mark in the dragon engine's head, opened a hatch and staggered out from her cavity. She half-slid, half-climbed from the dragon engine's head down its sloping body. The speed with which she made her descent awed Jodah—but then he supposed he'd be desperate, too. She paused at the edge of the woodlands, hands on her knees while she, apparently, breathed.
Meria made a small gesture with one hand. Spear-bearing kavu riders peeled away, shooting around the periphery toward Rona. She shot one glance behind her, then fled. Meria watched the chase, solemn. Her gaze shifted to the fallen Magnigoths. "Hundreds of years of life—lost in an instant."
Jodah inclined his head. "That's war."
"They will find us, won't they?" Meria said. "Wherever my people go."
Jodah nodded. Meria's eyes shone with both anger and grief.
"Then there's only one path for us. And it doesn't lie in Yavimaya."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Why am I worried that you won't let them go, even if I do hand myself over?" Jaya said to Ertai. She straightened her shoulders. She didn't intend to give herself up, but she didn't have another plan, either. Maybe, if she got close enough, she could summon a molten lance to spear him through the heart or superheat the air around Ertai's head~ something, anything that could get them out of this—
A sweet breeze cleared the battlefield's stink. It brought with it the clean scent of leather and oil. The horizon began to brighten—the #emph[western] horizon—with the sheen of gold. The air gained a peculiar, unearthly quality to it, as if its particles hummed with ancient tension.
An immense but sleek golden ship tore through the mountains' rubble, rocks kicking up in the wake behind it. The shimmering vessel swooped in a circle around the Phyrexian dreadnought. Hundreds of Keldon warriors leapt from the ship, landing on the dreadnought's wide scaley back, and they drove their blades and cleated boots into the creature's hide to secure themselves.
#figure(image("005_Episode 4: A Brutal Blow/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
The #emph[Golden Argosy] ! Jaya had thought it had been lost to legend. Radha had mentioned that she'd found an artifact during the negotiations in Oyster Bay, but Jaya had never guessed Radha had rediscovered that ancient ship.
Radha herself led her warriors onto the Phyrexian dreadnought's battering-ram head. The Phyrexian monstrosities still on the ground seemed to realize that the dreadnought was vulnerable to this assault. Rather than sheltering against the dreadnought's legs, they too started to scale it to attack the Keldons.
"Archers, cover us. Knights, after me." Danitha charged the dreadnought. "For Dominaria!"
The knights roared and followed, plowing into the Phyrexians that sought to defend the dreadnought. The dreadnought, beneath the Keldon onslaught, released a moan that shook the entire landscape.
Ajani bellowed, "Archers, to me! Fire on the Phyrexians climbing the dreadnought!"
Jaya raised her hands. Her flame brightened with her renewed spirits, and she blasted the skittering creatures that had pivoted to attack the archers. Ajani pressed close to her, defending her from any Phyrexian that headed her way.
Radha had pierced the dreadnought's eye, leaving a gash large enough for Radha to stand within the socket. Aqueous humor spurted, followed by the thicker clear goop of vitreous gel. Radha hacked through the muscular iris. The dreadnought shrieked in agony, tossing its head to throw her off. Its lower jaw gaped. It dripped blood, black fluid, and pinkish organic matter from its mouth.
Ertai bellowed, "Sheoldred will hear of this!"
"I hope she does!" Jaya called.
The creature crumpled, one joint at a time relaxing into death. The Keldons on its back let out a cheer and then flattened themselves, bracing to ride out its fall. The Benalish knights who'd been fighting underneath the dreadnought scattered. Jaya and Ajani both stared up at the nearing bulk of the dreadnought's underbelly, how it blotted the sky. Jaya scrambled out from underneath the dreadnought, squeaking past its final crash into the earth. The sound resounded in the mountains. Then, after that, the roar of avalanches and tumbling stone, until that, too, trickled into silence.
#figure(image("005_Episode 4: A Brutal Blow/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Karn looked up as Jhoira entered her workshop.
"Hiding out here isn't the cleverest way to avoid me," Jhoira said.
Karn faced her. "I'm not hiding."
"You never answered my letters." Jhoira didn't sound hurt—more rueful.
"You wished to speak about Venser," Karn said. "I did not."
"But you do now?"
Karn dipped his head. "It was self-centered of me to be so consumed by the personal ramifications of Venser's sacrifice. He was also your friend."
Jhoira tilted her head. "Yes, I'm sorry, too. I was grieving. You were withdrawing because you were, too. Nothing selfish about that."
"Just different reactions to the same stimulus," Karn mused.
"Ah, I missed you." Jhoira laughed and embraced him. Her mechanical owl, disturbed, flitted away from her shoulder and landed in the workshop's beams overhead.
Karn doubted she obtained the comfort she sought: his body had a similar heat to a human's, but he could not offer her the same softness of flesh. He enjoyed her proximity anyway. His friends were so small and so mysterious. He could divine the inner workings of quartz, but still he would never perfectly understand Jhoira.
Jhoira patted Karn's arm and then released him. She dug some glittering metal parts from her pocket, Thran by the look of the golden tracery on them. "These will help me install a self-destruct mechanism on the Mana Rig. It's too powerful to ever allow in Phyrexian hands~ Karn, it has been too long. We should not have let life come between us."
"Or unlife," Karn said.
Jhoira laughed. "I always forget that you have a sense of humor."
His communicator to the #emph[Weatherlight] chimed on his neck. Karn, though startled that anyone would use it when not communicating with the #emph[Weatherlight,] grasped it to activate it. "I am listening."
Jodah's voice came through, clear as if he stood in the room alongside them. "I am headed toward Shiv with the Yavimayan elves. Meria was able to recruit several neighboring groups. Since we're traveling by treefolk, it will take some time to reach you. Karn, there's something you need to know."
"Yes?" Karn asked.
Jodah hesitated. "There is a spy in the New Coalition."
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/008_Return%20to%20Dominaria%3A%20Episode%208.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Return to Dominaria: Episode 8",
set_name: "Dominaria",
story_date: datetime(day: 02, month: 05, year: 2018),
author: "<NAME>",
doc
)
Chandra walked across the planes to Regatha. She stepped through a storm of fire into existence again on the rocky ground below the broad stone steps of Keral Keep. The sun was setting over the mountains, the smoke from the nearest volcano turning the sky a brilliant red streaked with orange. The heat of the day sank into her bones, a comfort after the dank cold of the Dominarian swamp. She took a deep breath of warm air tinged with a crackling energy like the aftermath of a lightning strike and felt all her tense muscles relax.
#figure(image("008_Return to Dominaria: Episode 8/01.jpg", width: 100%), caption: [Mountain | Art by <NAME>], supplement: none, numbering: none)
She sighed and scrubbed at her face. #emph[I know it didn't look like it, Gideon,] #emph[but I have a plan] . She wasn't running away.
Nissa hadn't run away either. #emph[You didn't have to leave like that, leave me] , Chandra thought, her chest tightening at the memory of Nissa's furious expression. Nissa hadn't even given Chandra the chance to come with her. She knew how much danger Zendikar could be in from <NAME>, how much Nissa wanted to be there to help repair the damage. #emph[But she acted like she never wanted to see me again] , Chandra thought, and knew she sounded like an angry, jealous child. Well, that was part of the problem, wasn't it? #emph[You're not strong enough for this and you need to fix that] , she told herself.
From inside the monastery, voices echoed in an evening chant. She had arrived at just the right time; the monks would finish the ceremony and then sit down to dinner. It was a perfect opportunity.
She climbed the stairs silently, slipped inside the shadowy hall, and took the first corridor. She reached an open court and had to duck down behind a stone bench as two robed figures hurried past. Novices, distracted by their studies and running late, something Chandra had had to deal with during her brief time as abbot. She waited until the sound of their steps faded then quickly crossed the court.
It wasn't like anything would happen if they found her, Chandra just didn't want to argue about her plans. And they would see she was upset, know something had happened, she would have to explain . . . She didn't want to think about what had happened on Amonkhet, much less explain it.
She needed more firepower, better focus and accuracy, to do real damage to <NAME>. To get it, she had to be more in touch with her true self, or at least that was what they taught at Keral Keep. It was just that Chandra had never had any luck trying to do that. But for once she had stumbled on the perfect opportunity. Just after Nissa disappeared, Chandra had noticed fresh traces of a powerful pyromancer's aether trail on Dominaria.
Possibly Jaya Ballard's aether trail.
The fire mage Planeswalker hadn't been seen for longer than Chandra had been alive, and everyone at Keral Keep thought she was dead. But Jaya might be on Dominaria now, and if anyone could teach Chandra the trick to quickly getting in touch with herself and increasing her power, it had to be her.
Once past the court she was in the lesser-used area of the keep and it was easy to hurry along empty passages to the stairway leading down. She reached the dark hall at the bottom and released a small ball of fire from her open hand. It moved up to hover near the vaulted ceiling, lighting the chamber.
This was where the monastery kept its sacred relics, but there was only one thing here Chandra was interested in. She crossed the room to the plinth where Jaya's goggles sat. The light gold metal was just a little discolored, but the leather strap and buckle showed obvious wear. #emph[She'll want these back] , Chandra thought, #emph[and they'll prove I come from Keral Keep] . The gift would get Jaya to listen to her long enough for Chandra to explain how important the fight against <NAME> was. And it wasn't stealing when you were giving something back to the person who had originally owned it.
#figure(image("008_Return to Dominaria: Episode 8/02.jpg", width: 100%), caption: [Pyromancer's Goggles | Art by <NAME>], supplement: none, numbering: none)
As she reached for the goggles, a voice behind her said, "Chandra, what are you doing?"
Chandra snatched the goggles, clasping them to her chest as she spun around. It was <NAME>, staring at her from the doorway.
Chandra yelped, "It's not what it looks like!" Of all the people who could have caught Chandra in the act, Luti was the absolute worst. She didn't have an official rank in the monastery, but she was old and had been living here off and on for forever and everyone respected her and she was always trying to get Chandra to learn things Chandra didn't have time for.
Luti came toward her, her expression more bemused than anything else. "I have no idea what it looks like," she said. "What are you doing here? Why do you want those?"
"I found <NAME>," Chandra told her.
Luti froze for an instant, eyes wide. The shadows from Chandra's fire light etched even deeper lines around her mouth and eyes, darkened her long silver-gray hair. "You . . ."
"I think she's on Dominaria! We went there after Amonkhet—it was terrible, Bolas nearly killed us all, and we failed . . ." Chandra lifted the goggles. "But if I can find Jaya, I'm going to give her these, ask her to teach me the secrets and tricks I need to know! I have to do this, Luti, I need more power to fight <NAME>. Otherwise we're going to lose, he's going to kill me and all my friends, and then—" She waved a hand and the fireball floating overhead danced wildly, mirroring her agitation. "There won't be anybody left to stop him."
Luti let out her breath. "Chandra, you don't need Jaya. You should be concentrating on helping your friends, if they're in so much danger."
"You don't know what I need!" Chandra burst out. All the frustration and fear of the hopeless battle against Bolas, of Gideon taking Liliana's side, of Nissa's abrupt departure, it all boiled up at once. "You weren't there! Stop giving me advice I don't need and don't want!"
Luti gestured in exasperation. "Chandra—"
But Chandra had already turned, ghostly fire flaring up around her as she stepped out of the plane. This time, she knew exactly what she needed to do.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra followed the fading traces of what she hoped was Jaya's aether trail and stepped back into Dominaria. Cool air washed over her. She stood in an alley, surrounded by heavy stone buildings with crenellations and shuttered windows. She walked out of the shade into a sunny plaza, where people dressed in rough leather and muted colors hurried past. The sun warmed the stone cobbles underfoot, and it only felt cool because she had just been in Keral Keep's oven-like warmth. This place was Argivia, the capital city of New Argive, some distance west of Benalia and Aerona.
All the passersby seemed nervous, and lots of people were hauling baskets of food, bags, barrels, and ceramic jars, taking it all farther into the city. Everyone seemed to be talking in loud, worried voices. Chandra ducked out of the way of a herd of goats and bumped into a woman carrying a basket. The woman stumbled and the basket tipped, spilling apples onto the cobblestones.
"Oh, I'm sorry!" Chandra flung herself down and scrambled to pick them up.
"It's all right." The woman knelt down to scoop the fruit back into the basket. She laughed a little breathlessly. "If it's the worst thing that happens today, we'll both be lucky, hey?"
Fortunately, the crowd wasn't panicked and parted around Chandra and the woman like they were rocks in a stream. "What's all this about?" Chandra asked. The city was clearly preparing for something, but it was orderly and almost practiced, like everyone was used to it.
"You haven't heard?" The woman dumped the last of the apples into the basket, and Chandra helped her lift it as they both stood.
"I'm traveling, I just got here," Chandra said. As an explanation, it wasn't the best, but fortunately the woman was in too much of a hurry to question her further.
She said, "Oh, it's the kobolds of the Kher Ridges again, and that horrible god-dragon of theirs, Prossh. They're going to attack the city, but <NAME>'s got a troop of soldiers and a powerful pyromancer to settle them. Hopefully this time it'll be permanent."
#figure(image("008_Return to Dominaria: Episode 8/03.jpg", width: 100%), caption: [Prossh, Skyraider of Kher | Art by <NAME>wood], supplement: none, numbering: none)
"A powerful pyromancer?" That sounded promising. "Do you know who it is?"
"No, never heard a name." The woman settled the basket on her hip. "If you're meaning to move on, you should leave soon. They're going to lock down the gates until the troop gets back."
If the steward wasn't coming back until he finished off the Kobold threat, there was no telling how long that would take. Chandra had to go now. "Thank you!" she said, and plunged away through the crowd.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The city gates were still open and quite a few travelers and traders were leaving, not wanting to risk getting stuck in the city. Some enterprising peddlers had set up shop there, and Chandra was able to buy travel supplies and a map before she started out. All the other horses and wagons and foot traffic were taking the northern road; Chandra was the only one going south toward the ridges.
As she walked she could see signs that a large mounted force had recently passed this way. Hopefully she could catch up to the steward's party before the battle. If Jaya was really there, Chandra could volunteer to help, which would make an even better introduction than just charging up to Jaya and handing her the goggles. #emph[This is a great plan] , Chandra told herself. #emph[And it's getting better all the time!]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
A few days later, Chandra was starting to doubt a little. It was late afternoon and she had left the farm country near the city as the road gradually climbed into forested hills. Now she was walking through heavy forest, the road much rougher than it had been nearer the city. At least the weather had been good enough that she hadn't needed her tent, but she was worried about what would happen if she ran out of food.
She still saw signs of the Argivian troop's passage, and had stumbled over a couple of their old campsites, but they were obviously moving much faster than she was. She had the growing feeling she had probably already missed the battle. She told herself it didn't matter; as long as she found Jaya, everything would go according to plan.
She was trudging along, trying to dig the last piece of fruit out of her pack, when she spotted something lying beside the road. At first she thought it was more debris from the Argivians, a discarded or forgotten bedroll lying on the tree roots at the edge of the road. But a few steps closer she saw the outstretched arm and realized it was a dead body.
Chandra stopped, startled. All around her, the birdsong was silent. The road curved here to follow the shoulder of a hill, and she couldn't see too far ahead. She ran up to the body. It was a man, wearing the light armor of a scout and a tabard with the symbol of the Steward of Argive that she had seen in the city. From the ax wounds in his neck and shoulder, he was definitely dead, but when she touched his arm his flesh was only just cool. #emph[This didn't happen very long ago] , she thought. Maybe she hadn't missed the battle after all. Though it was weird that she couldn't hear—
A crash sounded in the forest, not far away. "Here we go," Chandra muttered to herself.
Chandra stepped off the road onto the thick loam between the trees. Heading in the direction of the crash, she found a second dead body, another Argivian scout, this one killed by crossbow bolts to the back. She kept moving, following the sounds of scraping and pounding. She reached the top of a rise and caught movement out of the corner of her eye. She stopped and squinted, trying to pinpoint it. Then she saw the movement again. "Hah, there you are," she whispered to herself.
Someone or something had just pushed the trunk of a fallen tree across the road where it curved around at the top of the hill. #emph[Now that looks like an ambush] , she thought.
There wasn't a lot of brush between the towering trees, but she still couldn't see who was up there moving around. She finally found a vantage point by climbing up among the trees at the top of a low hill. From there, she saw the kobolds.
#figure(image("008_Return to Dominaria: Episode 8/04.jpg", width: 100%), caption: [Kobolds of Kher Keep Token | Art by <NAME>te], supplement: none, numbering: none)
At least a dozen worked on each side of the road, short gaunt figures dressed in a variety of metal and leather armor and helmets, heavily armed with axes, spears, and swords. They were building a barricade across the road, probably meant to halt the Argivian troop and give the kobolds a chance to attack. The one Chandra guessed was the leader stood on a boulder, waving a sword and exhorting the others, "We will kill the Argivians for the glory of Prossh!"
"Prossh loves us," the others responded as they dragged another fallen tree across the road. "We honor Prossh."
As the kobold leader continued to rant about Prossh's greatness, Chandra snorted. Since Prossh was a dragon, she was pretty sure he didn't care about the kobolds at all, except for how tasty they were. But the kobolds must have surprised the scouts—they knew the steward's force was headed back this way and would be here any moment. It was all really annoying. If not for the kobolds, Chandra might be meeting Jaya right now.
Then two more kobolds rushed down through the trees from the south. They ran up to the leader and spoke, but it was too quiet for Chandra to hear. The leader turned and jumped off the boulder, hissing and gesturing at the others. "The Argivians draw near! Be ready!"
As the kobolds on the road ran for hiding places, Chandra eased away from the clearing. She was going to break up this ambush.
She scrambled backward and sat up to turn around. And found herself looking down at two kobolds, carefully creeping up the hill behind her. One yelled, "Kill her for Prossh!" They both lifted heavy axes and charged.
#emph[Well, damn it] , Chandra thought. There went any chance of being stealthy and clever enough to impress Jaya, who was hopefully nearby. She would have to do this the loud fiery way.
Chandra sent a fireball into the first kobold's chest and he tumbled back down the hill, screeching. The second one lunged at just the wrong moment and her fireball hit his ax instead of his body. He flailed backward as his ax handle turned to ash. Chandra took the opportunity to jump up and kick him in the face. He somersaulted down the hill to join his friend.
Muttering to herself, "Don't burn down the forest," she bolted through the trees, headed toward the section of road where the kobolds had laid their ambush. The steward's party would be arriving any moment.
Crossbow bolts landed in the ground near her feet. She spun and spotted three kobolds, running at her from the trees. She incinerated the rest of the bolts in mid-air and the crossbows for good measure, then charged out onto the road just above the point where the kobolds' tree trunks blocked it.
Chandra drew on her power and held out her hands toward the makeshift barrier. One clean blast down the middle, she told herself, focused and controlled. And she thought wryly, #emph[Just like <NAME> always tells you and you never listen.]
#figure(image("008_Return to Dominaria: Episode 8/05.jpg", width: 100%), caption: [Chandra, Bold Pyromancer | Art by <NAME>], supplement: none, numbering: none)
She sent the burst of fire streaking toward the logs. It hit dead center and slammed through all three trunks. Through smoke and burning fragments, Chandra got a glimpse of the road past the barricade, but she couldn't spot anyone approaching. She needed to make the opening bigger, to make sure the Argivians wouldn't be trapped. She sent another burst of fire, but then a lot of screaming kobolds charged her.
She drove the first charge back with a stream of fire, fighting the urge to just blast them all. The last thing she wanted to do was set fire to the forest, endangering the nearby Argivians and whatever else lived here. But her temper raged as the kobolds charged again. A crossbow bolt tore through her shirt sleeve, narrowly missing her. The carefully targeted stream of fire turned into a wild blast that fried the half dozen kobolds in its path.
Fortunately she had been facing north, away from the troop of Argivians who charged through the shattered barricade behind her at that same moment.
The kobolds tried to regroup to fight the Argivians, but it quickly turned into a rout. Chandra stood at the side of the road and spent a few minutes telling herself that she had been completely in control and had meant to send that wild blast and knew it was in the right direction. Then she gave up and just hoped that Jaya hadn't seen it.
Scanning the mounted Argivians, Chandra didn't see anyone who looked like she might be Jaya. She must be farther back in the troop, riding with the steward, maybe.
Finally the few surviving kobolds fled and Chandra headed up toward the remains of the barricade, where the Argivian supply wagons were waiting. Some soldiers had started to haul the remains of the barricade away, while others shoveled dirt over the still-smoldering debris.
A young woman hurried up to her and said, "<NAME> would like to thank you."
"Oh, right." Chandra followed her, her heart pounding a little with the thought of finally meeting Jaya.
But when the soldier led her to where the steward stood beside his horse, there was no one who looked like Jaya. Chandra managed to contain herself and accept Baird's formal thanks without looking too impatient, but at the first opportunity she said, "I was looking for the pyromancer who's supposed to be traveling with you. Is her name <NAME>?"
#figure(image("008_Return to Dominaria: Episode 8/06.jpg", width: 100%), caption: [Baird, Steward of Argive | Art by <NAME>oi], supplement: none, numbering: none)
Baird said, "Yes, that is her, but she left our force in the ridges."
"Left?" Chandra could hardly react. It was a relief that she had been right all along, and Jaya really had been here. And it was horribly disappointing that she wasn't here now. #emph[Please, don't let her have planeswalked away already] , she thought.
Baird explained, "She said she had come to Argivia looking for a friend of hers, and when she heard the dragon we were going to fight was on the way, she offered me her services."
That was a relief. Chandra asked, "So she's going farther south?"
Baird pointed up the road. "To the Yavimaya forest, I believe. It's just off the coast on the far side of the Kher Ridges."
That was on Chandra's map. This road connected with the trails over the ridges and ran through to the coast across from the island of Yavimaya. "Thank you!" Chandra told him. "I should go. I want to try to catch up with her as soon as I can."
Baird nodded to her and gestured toward the supply wagons. "If you mean to follow her, please accept some food and supplies from us. It's the least we can do in return for your help."
Chandra started toward the wagons, then thought of one last question. "Oh, Steward? Who is the friend Jaya is looking for?"
"I'm not certain." Baird shook his head. "She said it was someone who had been gone a long time."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra traveled for five days, out of the forest and past the end of the road, up into the rocky slopes and scrub brush of the ridges. She was careful with her food, though the Argivian supply master had told her she should have enough to reach the coast, and she refilled her waterskin whenever the road crossed a stream. The walk gave her plenty of time to think about what she was going to say to Jaya, rehearsing it over and over. It also gave her plenty of time to worry about Gideon and the others, and to miss Nissa. But she was sure she was doing the right thing.
Going up what her map assured her was the last ridge, the trail became harder to see, and Chandra found herself climbing more than walking. Finally, she reached the top and stopped, breathing hard. The sea spread out below from a beach at the bottom of the ridge, the water serene under blue sky and white clouds. Directly across from her, maybe only a mile or two away, was another coast, so thickly covered with trees that the shore looked like a nearly solid wall of intense green. This had to be Yavimaya.
#figure(image("008_Return to Dominaria: Episode 8/07.jpg", width: 100%), caption: [Forest | Art by <NAME> Ro], supplement: none, numbering: none)
Mist floated around shapes that might be small mountains or hills, but from her high vantage point on the ridge she couldn't see any sign that anyone lived there. No indication of paths or roads along its shore, no mark of civilization at all. Frustrated, she said aloud, "How am I going to find—"
Suddenly a whole section of huge trees on an inland hillside rippled and trembled, then waved back and forth as if a sudden wind shook them like children's toys. Carried on the breeze, Chandra distantly heard metallic banging and clanging, and something roaring faintly.
"I guess that answers that question." Chandra started down the ridge, moving as fast as she could. Whatever was going on over there, it was a good place to start looking for Jaya.
Below, in a cove at the bottom of the ridge, she found a small fishing village. An obliging though confused fisherman ferried her across the strait, and Chandra waded ashore to start her trek into Yavimaya.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra had thought the forest near the coast was thick, but the inland trees were huge, with heavy spiraling roots arching up above the ground. The leafy canopies turned the sunlight into green shadow, but there were colorful flowers everywhere. Fortunately, the ferny plants on the forest floor were low and easy to sprint through. Chandra drew closer to the noise until she reached the edge of a low, possibly unnatural valley. It was nearly round and the bottom was filled with a big, newly dug crater, surrounded by piles of disturbed earth. And the people who had done the digging were still there.
At first Chandra thought she was looking at muscular giants in armor, but then she muttered to herself, "Oh, right, I get it." She'd been traveling alone for too long, because these were obviously automatons.
They were each around twenty feet high, with scoops for hands and big blocky heads. As she watched, they stopped digging and climbed out of the crater to face the shadows of the forest.
Chandra hesitated, but they couldn't be after her; they were facing the wrong way. Then she saw the forest on the far side of the crater was moving.
The leaves and branches tossed like a harsh wind had passed through them. Creatures that looked like animate trees walked out of the shadows into the valley. #emph[No, wait, those ] are#emph[ animate trees] , Chandra thought, impressed.
#figure(image("008_Return to Dominaria: Episode 8/08.jpg", width: 100%), caption: [Verdant Force | Art by <NAME>], supplement: none, numbering: none)
They dragged themselves along, clots of dirt falling from their root bundles. Some were big, with trunks divided almost like legs, but others were smaller and crept out of the underbrush, moving their lower branches in a way that was far too giant-spider-like for Chandra's comfort.
She wasn't sure what was about to happen—if it was a battle, a standoff, or a meeting. Then suddenly a tree surged forward so fast Chandra yelped involuntarily. It leapt on the nearest automaton and ripped it apart.
Chandra gasped in astonishment as metal parts flew into the air and rained down on the dirt. The other automatons rushed to attack and the enraged trees lunged forward to grapple with them. She ran toward the battle instinctively, but at the bottom of the hill she slid to a halt. She had no idea which side to take.
She didn't want to end up accidentally fighting against Jaya's friends—that would be a huge disaster. Then a tree broke off from the battle and charged her, branches stabbing at her wildly. Reacting instinctively, Chandra flung a firebolt. It hit the tree dead-on and its branches caught fire. But even in flames it still came at her, bark and branches disintegrating, as if desperate to kill her. She hit it with another burst of fire just as a smaller, human-sized automaton reached her side. In a deep voice, it said, "Take care. They will attack any movement."
More trees rolled over the hill like giant angry tumbleweeds, headed toward the automatons. Three veered off toward Chandra, accelerating as they got closer. Chandra demanded, "What are these things?"
The automaton braced to meet the charge. "They're animated trees, created and sent by Multani."
#emph[Not people, then] , Chandra thought. She drew on her power and blasted the rapidly approaching trees, aiming for the trunks. If they weren't people, she wasn't going to restrain herself.
Then the automaton lunged past her. Chandra whipped around and saw a tree had crept up and was just about to slam its branches down on them. The automaton punched it in the trunk, over and over again, and splintered the heavy wood into fragments.
#figure(image("008_Return to Dominaria: Episode 8/09.jpg", width: 100%), caption: [Fiery Intervention | Art by Adam Paquette], supplement: none, numbering: none)
More trees slammed into the line of larger automatons and Chandra sprinted forward to get behind them. Two trees turned away from the automatons to rush her and Chandra blasted them out of her way. She reached a spot of higher ground where she had a better angle and sent a stream of fire down the whole row of trees. They didn't seem to realize they were on fire, and blindly shoved past each other to get to the automatons, spreading the blaze.
Chandra blasted the last few stragglers and moved back down to level ground. Finally, she and the surviving automatons stood surrounded by piles of punched-apart trees and smoldering wood. Chandra rubbed soot off her face and dusted her gloves. She looked around and spotted the smaller automaton who had saved her. He was shoving a fallen tree away from the edge of the excavation. She jogged over to him.
He straightened up and looked down at her. At that point, Chandra realized this couldn't be an automaton. His head and face were far more human-like than the others, more mobile. He said, "Thank you for your help."
"You're welcome. Thanks for getting that one that snuck up on me." She thought it might take a little time to get used to his metal features. She could tell he was making expressions, they were just hard for her to read. "You said somebody named Multani sent them after you?" It belatedly occurred to Chandra that Multani might be the friend Jaya had come to meet, in which case Chandra had really screwed up her plan.
The metal person said, "Multani is an elemental, and has been in a semiconscious state, recovering from terrible injuries. Animating these trees and sending them to attack us is an instinctive defensive action."
That was a relief. Jaya probably hadn't come to meet somebody who was mostly unconscious. "I'm Chandra. I've been looking for <NAME>, and the steward of Argive told me she was going to Yavimaya to look for a friend who was gone for a long time. You don't know who that is, do you?"
The metal person tilted his head, and it was hard to tell but Chandra thought his expression might be ironic. He said, "I'm Karn. And I am someone who has been gone for a long time."
"Is Jaya here—" Chandra started to say, then someone behind her said, "Well, fancy meeting me here."
Chandra spun around. <NAME> stood there, wearing a leather and metal jerkin over her red robes. #emph[What's she doing on Dominaria?] was Chandra's first baffled thought. Then, #emph[Hold it, ] how#emph[ is she on Dominaria? She's not a Planeswalker. I didn't think she was a Planeswalker] . "You can't be—How did—?"
<NAME> lifted a brow, and pointed to Jaya's goggles hanging from Chandra's belt. She said, "I believe those are mine."
#figure(image("008_Return to Dominaria: Episode 8/10.jpg", width: 100%), caption: [Jaya Ballard | Art by <NAME>uve], supplement: none, numbering: none)
|
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Buy_List.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Buy List",
authors: (
"<NAME>",
),
date: "27 Décembre, 2023",
)
#set heading(numbering: "1.1.")
- #link("https://www.amazon.fr/gp/product/B07PPY9N62/ref=ewc_pr_img_1?smid=AXZ3JQ1GVFPIF&th=1")[USB C cable]
- HDD/SDD backup
#link("https://www.amazon.fr/Seagate-St2000dmz08-Barracuda-Disque-Interne-Argent/dp/B07H2RR55Q/ref=sr_1_2_sspa?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&keywords=hdd%2B1to&sr=8-2-spons&ufe=app_do%3Aamzn1.fos.49fccda8-a887-4188-817b-b9a64bb30e43&sp_csd=d2lkZ2V0TmFtZT1zcF9hdGY&th=1")[HDD]
- Keyboard
- #link("https://www.amazon.fr/TP-Link-Adaptateur-UB500-imprimantes-smartphone/dp/B098K3H92Z/ref=sr_1_9?keywords=wifi+bluetooth+usb&sr=8-9")[Bluetooth dongle]
- #link("https://www.amazon.fr/Shure-Circum-Auriculaire-Monitoring-Enregistrement-Fr%C3%A9quencielle/dp/B09MV338KK/ref=sr_1_1?geniuslink=true&keywords=shure%2Bsrh440a%2Bover%2Bear%2Bwired%2Bheadphones%2Bfor%2Bmonitoring%2Brecording%2Bprofessional%2Bstudio%2Bgrade%2Benhanced%2Bfrequency%2Bresponse%2Bwork%2Bwith%2Ball%2Baudio%2Bdevices%2Badjustable%2Bcollapsible%2Bdesign%2B2022%2Bversion&sr=8-1&ufe=app_do%3Aamzn1.fos.49fccda8-a887-4188-817b-b9a64bb30e43&th=1")[Headset]
- #link("https://www.amazon.fr/dp/B09MHRYY5C/ref=emc_b_5_t")[Mic]
|
|
https://github.com/k0tran/typst | https://raw.githubusercontent.com/k0tran/typst/sisyphus/vendor/hayagriva/README.md | markdown | # Hayagriva
[![Build status](https://github.com/typst/hayagriva/workflows/Continuous%20integration/badge.svg)](https://github.com/typst/hayagriva/actions)
[![Current crates.io release](https://img.shields.io/crates/v/hayagriva)](https://crates.io/crates/hayagriva)
[![Documentation](https://img.shields.io/badge/docs.rs-hayagriva-66c2a5?labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,<KEY>xl<KEY>)](https://docs.rs/hayagriva/)
Rusty bibliography management.
Hayagriva is a tool that can help you or your apps deal with literature and
other media. Its features include:
- Data structures for literature collections
- Reading and writing said collections from YAML files
- Formatting literature into reference list entries and in-text citations as
defined by popular style guides
- Interoperability with BibTeX
- Querying your literature items by type and available metadata
Hayagriva can be used both as a library and as a Command Line Interface (CLI).
Skip to the [section "Usage"](#usage) for more information about usage in your
application or to the [section "Installation"](#installation) to learn about how
to install and use Hayagriva on your terminal.
## Supported styles
Hayagriva supports all styles provided in the
[official Citation Style Language repository](https://github.com/citation-style-language/styles),
currently over 2,600.
# Usage
```rust
use hayagriva::io::from_yaml_str;
let yaml = r#"
crazy-rich:
type: Book
title: Crazy Rich Asians
author: <NAME>
date: 2014
publisher: Anchor Books
location: New York, NY, US
"#;
// Parse a bibliography
let bib = from_yaml_str(yaml).unwrap();
assert_eq!(bib.get("crazy-rich").unwrap().date().unwrap().year, 2014);
// Format the reference
use std::fs;
use hayagriva::{
BibliographyDriver, BibliographyRequest, BufWriteFormat,
CitationItem, CitationRequest,
};
use hayagriva::citationberg::{LocaleFile, IndependentStyle};
let en_locale = fs::read_to_string("tests/data/locales-en-US.xml").unwrap();
let locales = [LocaleFile::from_xml(&en_locale).unwrap().into()];
let style = fs::read_to_string("tests/data/art-history.csl").unwrap();
let style = IndependentStyle::from_xml(&style).unwrap();
let mut driver = BibliographyDriver::new();
for entry in bib.iter() {
let items = vec![CitationItem::with_entry(entry)];
driver.citation(CitationRequest::from_items(items, &style, &locales));
}
let result = driver.finish(BibliographyRequest {
style: &style,
locale: None,
locale_files: &locales,
});
for cite in result.citations {
println!("{}", cite.citation.to_string())
}
```
To format entries, you need to wrap them in a `CitationRequest`. Each of these
can reference multiple entries in their respective `CitationItem`s.
Use these with a `BibliographyDriver` to obtain formatted citations and bibliographies.
You can either supply your own CSL files or choose from about 100 bundled
citation styles using the `archive` feature.
If the default features are enabled, Hayagriva supports BibTeX and BibLaTeX
bibliographies. You can use `io::from_biblatex_str` to parse such
bibliographies.
Should you need more manual control, the library's native `Entry` struct also
offers an implementation of the `From<&biblatex::Entry>`-Trait. You will need to
depend on the [biblatex](https://docs.rs/biblatex/latest/biblatex/) crate to
obtain its `Entry`. Therefore, you could also use your BibLaTeX content like
this:
```rust
use hayagriva::Entry;
let converted: Entry = your_biblatex_entry.into();
```
If you do not need BibLaTeX compatibility, you can use Hayagriva without the
default features by writing this in your `Cargo.toml`:
```toml
[dependencies]
hayagriva = { version = "0.2", default-features = false }
```
### Selectors
Hayagriva uses a custom selector language that enables you to filter
bibliographies by type of media. For more information about selectors, refer to
the [selectors.md
file](https://github.com/typst/hayagriva/blob/main/docs/selectors.md). While you
can parse user-defined selectors using the function `Selector::parse`, you may
instead want to use the selector macro to avoid the run time cost of parsing a
selector when working with constant selectors.
```rust
use hayagriva::select;
use hayagriva::io::from_yaml_str;
let yaml = r#"
quantized-vortex:
type: Article
author: <NAME>.
title: Structure of a Quantized Vortex in Boson Systems
date: 1961-05
page-range: 454-477
doi: 10.1007/BF02731494
parent:
issue: 3
volume: 20
title: Il Nuovo Cimento
"#;
let entries = from_yaml_str(yaml).unwrap();
let journal = select!((Article["date"]) > ("journal":Periodical));
assert!(journal.matches(entries.nth(0).unwrap()));
```
There are two ways to check if a selector matches an entry.
You should use [`Selector::matches`] if you just want to know if an item
matches a selector and [`Selector::apply`] to continue to work with the data from
parents of a matching entry. Keep in mind that the latter function will
return `Some` even if no sub-entry was bound / if the hash map is empty.
## Installation
Run this in your terminal:
```bash
cargo install hayagriva --features cli
```
Cargo will install the Hayagriva Command Line Interface for you. Now, you just
need a Hayagriva YAML literature file or a Bib(La)TeX file to get started. The
Hayagriva YAML file is intuitive to write and can represent a wealth of media
types, [learn how to write one in its dedicated
documentation.](https://github.com/typst/hayagriva/blob/main/docs/file-format.md)
Suppose you have this file saved as `literature.yml` in your current working
directory:
```yaml
dependence:
type: Article
title: The program dependence graph and its use in optimization
author: ["<NAME>", "<NAME>.", "<NAME>."]
date: 1987-07
serial-number:
doi: "10.1145/24039.24041"
parent:
type: Periodical
title: ACM Transactions on Programming Languages and Systems
volume: 9
issue: 3
feminism:
type: Article
title: She swoons to conquer
author: <NAME>
editor: <NAME>
date: 2015-09-25
url: https://aeon.co/essays/can-you-enjoy-romance-fiction-and-be-a-feminist
parent:
type: Blog
title: Aeon
```
You can then issue the following command to get reference list entries for both
of these articles.
```bash
hayagriva literature.yml reference
```
Hayagriva defaults to the Author-Date style of the Chicago Manual of Style (17th
edition). If you prefer to use another style, you can, for example, do the
following to use the style of the American Psychological Association instead:
```bash
hayagriva literature.yml reference --style apa
```
Available values for the `--style` argument can be viewed by calling
`hayagriva help reference`.
If you now need an in-text citation to the second article in the above file, you
can call:
```bash
hayagriva literature.yml cite --key feminism
```
The `--key` takes a comma-separated list of keys (or a single one). The
sub-command will then only work on the specified keys. Just like the `reference`
sub-command, the `cite` command also allows the `--style` argument. Its possible
values can be viewed with `hayagriva help cite`. It will default to the _Author
Date_ style.
Instead of the `--key` argument, you can also use `--select` to provide a custom
[Hayagriva selector.](https://github.com/typst/hayagriva/blob/main/docs/selectors.md)
For example, you could run the following to only reference entries that have a
URL or DOI at the top level:
```bash
hayagriva literature.yml --select "*[url] | *[doi]" reference
```
This expression would match both entries in our example and therefore the
command would return the same result as the first reference command.
Hayagriva also allows you to explore which values were bound to which
sub-entries if the selector matches. This is especially useful if you intend to
consume Hayagriva as a dependency in your application and need to debug an
expression. Consider this selector which always binds the sub-entry with the
volume field to `a`, regardless of if it occurred at the top level or in the
first parent: `a:*[volume] | * > a:[volume]`. You can then use the command below
to show which sub-entry the selector bound as `a` for each match:
```bash
hayagriva literature.yml --select "a:*[volume] | * > a:[volume]" --show-bound
```
The `--show-bound` flag shows all keys matching the selector or key filter and
details which sub-entries of each entry were bound by the selector. If, instead,
you only want to obtain a list of matching keys, use the `--keys` flag.
If you are working with BibTeX, you can use your `.bib` file with Hayagriva just
like you would use a `.yml` file. If you want to convert your `.bib` file to a
`.yml` file, you can simply pass the `.bib` file to the CLI without any additional
arguments. It will then show the YAML-formatted bibliography with key and selector
filters applied on standard output. If you therefore want to convert your `.bib`
file and save the result somewhere, you can just use `>`:
```bash
hayagriva literature.bib > converted.yml
```
## Contributing
We are looking forward to receiving your bugs and feature requests in the Issues
tab. We would also be very happy to accept PRs for bug fixes, minor
refactorings, features that were requested in the issues and greenlit by us, as
well as the planned features listed below:
- Implementing the YAML-to-BibLaTeX conversion
- Documentation improvements
- CSL bugfixes
- CSL-M Support
We wish to thank each and every prospective contributor for the effort you (plan
to) invest in this project and for adopting it!
## License
Hayagriva is licensed under a MIT / Apache 2.0 dual license.
Users and consumers of the library may choose which of those licenses they want
to apply whereas contributors have to accept that their code is in compliance
and distributed under the terms of both of these licenses.
Hayagriva includes CSL styles that are licensed as CC-BY-SA 3.0 Deed if the
`archive` feature is enabled. The file `styles.cbor.rkyv` is a collection of
these works and falls under this license. Retrieve attribution information by
deserializing it using the `styles` function and reading the `StyleInfo`
structs.
|
|
https://github.com/markcda/unitech-typst | https://raw.githubusercontent.com/markcda/unitech-typst/master/00-university-template.typ | typst | MIT License | // Составляет титульный лист.
#let mk_title_page(
header: "",
department_name: "",
institute_name: "",
work_type: "",
discipline_name: "",
theme: none,
author: (),
adviser: (),
city: "",
year: "",
) = {
// Указываем институт и кафедру.
set align(center)
set text(weight: "bold")
image(header, width: 100%)
linebreak()
upper(institute_name)
linebreak()
linebreak()
upper(department_name)
// По центру указываем тип работы, дисциплину и тему.
set align(center + horizon)
upper(work_type)
linebreak()
[
по дисциплине "#discipline_name"
]
if theme != none {
linebreak()
linebreak()
set text(weight: "regular")
theme
}
set align(bottom)
set align(right)
set text(weight: "bold")
if author.sex == "male" [
Выполнил:
] else [
Выполнила:
]
linebreak()
set text(weight: "regular")
[#author.degree группы #author.group]
linebreak()
author.nwa
linebreak()
linebreak()
set text(weight: "bold")
if adviser.sex == "male" [
Проверил:
] else [
Проверила:
]
linebreak()
set text(weight: "regular")
adviser.degree
linebreak()
adviser.nwa
linebreak()
linebreak()
linebreak()
set align(center)
[#city #year г.]
}
// Составляет содержание работы.
#let mk_table_of_contents() = {
{
set align(center)
set text(16pt, weight: "bold")
[Содержание]
}
set align(left)
outline(
title: [],
indent: auto,
)
}
// Составляет полноценную работу.
#let student_work(
title: "",
header: "",
department_name: "",
institute_name: "",
work_type: "",
discipline_name: "",
theme: "",
author: (),
adviser: (),
city: "",
year: "",
table_of_contents: false,
links: (),
content,
) = {
set document(author: author.name, title: title)
set page(
paper: "a4",
margin: (left: 30mm, right: 15mm, top: 15mm, bottom: 15mm),
)
set text(font: "Times New Roman", size: 14pt, lang: "ru")
mk_title_page(
header: header,
department_name: department_name,
institute_name: institute_name,
work_type: work_type,
discipline_name: discipline_name,
theme: theme,
author: author,
adviser: adviser,
city: city,
year: year,
)
set page(numbering: "1")
if table_of_contents == true {
mk_table_of_contents()
}
// Покажем основное содержимое работы.
{
let indent = 1.25cm
show heading: it => {
pagebreak()
set align(center)
set text(16pt, hyphenate: false)
it
par(text(size: 0.35em, h(0.0em)))
}
set par(justify: true, first-line-indent: indent)
set list(indent: indent)
show list: it => {
it
par(text(size: 0.35em, h(0.0em)))
}
set enum(indent: indent)
show enum: it => {
it
par(text(size: 0.35em, h(0.0em)))
}
content
}
if links.len() != 0 {
pagebreak()
show heading: set align(center)
set heading(numbering: none)
[= Источники]
linebreak()
let src_cntr = counter("source_counter")
src_cntr.step()
for source in links {
src_cntr.display()
[. ]
if source.type == "book" {
[#source.author - ]
}
source.title
[. ]
if source.type == "web" {
[Электронный ресурс. Режим доступа: ]
link(source.link)[#source.link]
[ (дата обращения: ]
source.access_date
[).]
} else if source.type == "book" {
[Издательство "]
source.publisher
[", ]
source.year
[ г.]
}
src_cntr.step()
linebreak()
}
}
}
|
https://github.com/Error-418-SWE/Documenti | https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/1%20-%20Candidatura/Verbali/Interni/30-10-23/30-10-23.typ | typst | ERROR\_418 \
Verbale 30/10/23
#figure(
align(center)[#table(
columns: 2,
align: (col, row) => (left,left,).at(col),
inset: 6pt,
[Mail:],
[<EMAIL>],
[Redattori:],
[<NAME>, <NAME>],
[Verificatori:],
[<NAME>, <NAME>, <NAME>],
[Amministratori:],
[<NAME>, <NAME>],
[Destinatari:],
[<NAME>, <NAME>],
)]
)
#figure(
align(center)[#table(
columns: 2,
align: (col, row) => (center,center,).at(col),
inset: 6pt,
[Inizio Meeting: 14:30 Fine Meeting: 18:30 Durata: 4:00h],
[],
[Presenze:],
[],
)]
)
#block[
#figure(
align(center)[#table(
columns: 5,
align: (col, row) => (center,center,center,center,center,).at(col),
inset: 6pt,
[Nome], [Durata Presenza], [], [Nome], [Durata Presenza],
[Antonio],
[4:00h],
[],
[Alessio],
[4:00h],
[Riccardo],
[4:00h],
[],
[Giovanni],
[4:00h],
[Rosario],
[4:00h],
[],
[Silvio],
[4:00h],
[Mattia],
[4:00h],
[],
[],
[],
)]
)
]
Ordine del giorno:
- Analisi carico di lavoro per la stesura del Preventivo Costi;
- Redazione del preventivo dei costi;
- Finalizzazione redazione Lettera di presentazione;
- Finalizzazione redazione Valutazione dei Capitolati;
- Organizzazione gruppi di lavoro per la revisione finale dei documenti,
quali:
- Verbali interni;
- Verbali esterni;
- Valutazione dei Capitolati;
- Lettera di presentazione.
- Riorganizzazione repo.
A fini organizzativi, il team, a seguito dell’analisi congiunta riguardo
il carico di lavoro e alla revisione della lettera di presentazione, si
è diviso in sotto gruppi per lavorare in contemporanea su documenti e
aspetti diversi. \
I gruppi formatisi prevedono:
- Primo sotto gruppo: 3 membri -\> revisione Valutazione capitolati;
- Secondo sotto gruppo: 2 membri -\> revisione Capitolati 17,18,21
ottobre;
- Terzo sotto gruppo: 2 membri -\> revisione Capitolati 25,26,29
ottobre.
= Analisi carico di lavoro
<analisi-carico-di-lavoro>
Al fine di redigere il preventivo dei costi, è stata necessaria
un’accurata analisi del carico di lavoro e del monte ore necessario.
L’idea alla base dell’organizzazione del lavoro è stata la suddivisione
del periodo di sviluppo \(Novembre - Marzo) in tre sotto-periodi che
affronteranno aspetti diversi ma fondamentali del prodotto, quali:
- Periodo di Analisi dei Requisiti;
- Periodo per PoC e RTB;
- Periodo per PB.
Costi e ore sono stati stabiliti mediante la realizzazione di una
tabella su Google Sheet in modo collaborativo con tutti i membri del
gruppo.
= Redazione documenti
<redazione-documenti>
== Preventivo Costi
<preventivo-costi>
A seguito dell’analisi precedente e delle decisioni riguardo ore e
costi, si è redatto il documento relativo al Preventivo dei Costi.
== Lettera di presentazione
<lettera-di-presentazione>
Dopo una revisione collettiva, si è proseguito con la finalizzazione
della Lettera di presentazione, con l’aggiunta del link alla repo github
dei documenti \(link al ramo main) e aggiunta del prezzo preventivato.
== Valutazione Capitolati
<valutazione-capitolati>
Uno dei sotto gruppi formati si è occupato della revisione,
riorganizzazione e finalizzazione del documento relativo alla
valutazione complessiva dei nove capitolati. Il documento, risultando
corposo e denso di analisi, ha richiesto una discreta quantità di tempo
per essere redatto e validato, prestando attenzione ad includere le
risposte ricevute da tutte e nove le aziende proponenti.
== Revisione Documenti
<revisione-documenti>
I due sotto gruppi impegnati nella revisione dei verbali hanno svolto un
completo lavoro di revisione e analisi di correttezza dei verbali fino a
quel momento redatti. Questa fase, a causa di un mancato salvataggio dei
file .tex di latex, ha purtroppo visto una nuova stesura completa di
alcuni verbali anche per piccole correzioni. Le nuove versioni dei
verbali rimangono pur sempre una fedele ritrascrizione dei verbali
originali, senza modificarne il contenuto, ma migliorandone la stesura,
rimuovendo eventuali errori ortografici e non. \
Terminata la revisione e la redazione dei verbali, si è susseguita
un’ulteriore revisione di conferma della documentazione rimanente, come
la lettera di presentazione e la valutazione dei capitolati \(documento
terminato durante lo svolgersi di queste revisioni).
== Riorganizzazione Repo
<riorganizzazione-repo>
Terminata la redazione dei documenti e la loro revisione il gruppo ha
potenzialmente tutto il necessario per procedere alla candidatura. In
questo modo, possedendo ora i file ufficiali e revisionati che saranno
oggetto di consegna, è stato possibile riorganizzare la repo al fine di
eliminare evetuali branch secondari e concludere le pull request, in
modo da riunire tutti i documenti prodotti dai vari branch creati al
ramo Develop, in attesa di unirli successivamente al ramo Main.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/spread-11.typ | typst | Other | // Error: 5-11 cannot spread array into dictionary
#(..(1, 2), a: 1)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-00.typ | typst | Other | // Test adding content.
// Ref: true
#([*Hello* ] + [world!])
|
https://github.com/RandomcodeDev/FalseKing-Design | https://raw.githubusercontent.com/RandomcodeDev/FalseKing-Design/main/engine/tools.typ | typst | = Tools
#table(
columns: 3,
[*Tool*], [*Use*], [*Custom made?*],
[#link("https://xmake.io")[xmake]], [Build system], [no],
[#link("https://visualstudio.microsoft.com")[Visual Studio 2022]], [Code editing, debugging (Windows, consoles)], [no],
[#link("https://code.visualstudio.com")[Visual Studio Code]/#link("https://neovim.io")[Neovim]], [Code editing (non-Windows)], [no],
[#link("https://www.sourceware.org/gdb")[GDB]/#link("https://lldb.llvm.org")[LLDB]], [Debugging (non-Windows)], [no],
[#link("https://github.com/microsoft/DirectXShaderCompiler")[DXC]], [Shader compiler], [no],
[#link("https://github.com/KhronosGroup/spirv-cross")[spirv-cross]], [Shader converter], [no]
)
|
|
https://github.com/Origami404/kaoyan-shuxueyi | https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/微积分/04-一元微分方程.typ | typst | #import "../template.typ": sectionline, gray_table, colored
#let dx = $dif x$
#let dy = $dif y$
#let dp = $dif p$
#let dt = $dif t$
#let _to_ = $quad => quad$
#let __to__ = $quad #_to_ quad$
= 一元微分方程
== 杂鱼一阶微分方程 (可分离变量)
如果可以把含 $y$ 的部分都赶到 $dy$ 前面, 含 $x$ 的部分都赶到 $dx$ 前面, 那么直接左右两边积分就可以解了.
有时候要注意看形如 $y dx + x dy$ 的部分, 它可以合成 $dif (x y)$, 有时候这样代换一下就可以接着解.
== 一阶齐次方程
特征为方程的每个项里 $y$ 和 $x$ 的总阶数是一样的, 这意味着可以两边除以 $x$ 再整理成左边这样:
$
y' = phi (y / x) #__to__ dp / (phi(p) - p) = dx / x
$
如果希望做得快, 可以背一下右边的代换后结果.
== 一阶线性方程
不同于高阶情况, 一阶方程即使不是常系数的也可以解:
$
y' + p y = q #__to__ y = e^(-P) (integral e^P q " " dx + C)
$
其中大 $P$ 是小 $p$ 的原函数, 即 $P = integral p " " dx$.
在套公式的时候要特别注意 $p$ 有时候是带着负号的, 不要丢了.
== 伯努利方程
如果一阶方程里的 "自由项" 多了一个 $y^n$, 那么可以左右除以 $y^n$ 再做代换 $z = y^(1 - n)$, 然后式子就可以变成一阶线性方程:
$
y' + p y = q y^n #__to__ z' + (1 - n) p z = (1 - n) q
$
== 可降阶的二阶方程
如果二阶方程里没有 $y$, 只有 $y''$, $y'$, $x$, 那么可以做代换 $p = y'$, 视为 $p$ 与 $x$ 的一阶方程.
如果二阶方程里没有 $x$, 只有 $y''$, $y'$, $y$, 那么同样可以做代换 $p = y'$, 但此时要视为 $p$ 与 $y$ 的一阶方程.
== 高阶线性方程
=== 任意系数通用结论
对于高阶线性方程而言, 它的解的结构都是一样的: 非齐次通解 = 线性组合的齐次通解 + 非齐次特解:
$
sum_(i=0)^(n) p_i y^((i)) = f #__to__ y = sum_(i=0)^(n) C_i y_i + y^*
$
有时候题目会给一个抽象的高阶线性方程然后考这个关系, 比如两个非齐次通解相减能得到什么之类的.
=== 常系数 + 齐次
常系数的高阶线性方程是我们真正能解的方程. 首先我们要写出它的特征多项式方程: #footnote()[为什么? 可以参考: #link("https://zh.wikipedia.org/zh-cn/线性微分方程") 中的 "欧拉注意到..." 部分]
$
sum_(i=0)^(n) p_i r^i = 0
$
它在 $CC$ 上有 $n$ 个复根 $z$. 每一个都对应一个形如 $e^(z x)$ 的解. 额外考虑重根并使用欧拉公式换掉复指数, 可以得到以下结论:
对于一个 $k$ 重实根 $r = r_i$, 它贡献一个含 $k$ 个待定系数的通解:
$
y = ( sum_(j=0)^(k-1) C_j x^j ) e^(r_i x)
$
对于一对共轭的 $k$ 重复根 $r = alpha plus.minus beta i$, 它们一起贡献一个含 $2k$ 个待定系数的通解:
$
y = [( sum_(j=0)^(k-1) C^(+)_j x^j ) cos beta x + ( sum_(j=0)^(k-1) C^(-)_j x^j ) sin beta x] e^(alpha x)
$
=== 常系数 + 非齐次
对于特殊形式的非齐次项, 我们可以用*待定系数法*求特解:
$
f = p(x) e^(lambda x) #_to_ y^* = x^k Q_m (x) e^(lambda x) \
f = [p^+(x) cos omega x + p^-(x) sin omega x] e^(lambda x) #_to_ y^* = x^k [Q_m^+ (x) cos omega x + Q_m^- (x) sin omega x] e^(lambda x)
$
特解由三个部分组成
#set list(marker: ([⤥], [›]))
- $x^k$ 是重根修正项
- 如果 $lambda$ 恰好是特征方程的 $k$ 重根, 那么就要多一项 $x^k$;
- 如果 $lambda$ 不是根, 那么 $k = 0$, $x^k = 1$ 可直接省略.
- $Q_m (x)$ 是一个和 $p(x)$ 阶数相同的多项式, 系数待定, 等待代回原微分方程求解.
- $e^(lambda x)$ 是特解必须具有的形式
== 欧拉方程
如果一个方程很像常系数线性方程, 但是每个项却多了一个 $x^i$, 那么它就是欧拉方程, 可用 $x = e^t$ 代换:
$
sum_(i=0)^(n) a_i y^((i)) colored(x^i) = 0
$
代换后的方程会把 $x^i$ 都消去, 变成一个关于 $y$ 和 $t$ 的常系数线性方程.
#pagebreak()
|
|
https://github.com/kilpkonn/typst-thesis | https://raw.githubusercontent.com/kilpkonn/typst-thesis/main/README.md | markdown | MIT License | # Typst thesis template for TalTech
See rendered [here](https://typst.app/project/rtvks-u_zE10N8kJMXSWpc)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/chart/barchart.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": draw, styles, palette
#import "/src/plot.typ"
#let barchart-default-style = (
axes: (tick: (length: 0), grid: (stroke: (dash: "dotted"))),
bar-width: .8,
cluster-gap: 0,
error: (
whisker-size: .25,
),
y-inset: 1,
)
/// Draw a bar chart. A bar chart is a chart that represents data with
/// rectangular bars that grow from left to right, proportional to the values
/// they represent.
///
/// = Styling
/// *Root*: `barchart`.
/// #show-parameter-block("bar-width", "float", default: .8, [
/// Width of a single bar (basic) or a cluster of bars (clustered) in the plot.])
/// #show-parameter-block("y-inset", "float", default: 1, [
/// Distance of the plot data to the plot's edges on the y-axis of the plot.])
/// You can use any `plot` or `axes` related style keys, too.
///
/// The `barchart` function is a wrapper of the `plot` API. Arguments passed
/// to `..plot-args` are passed to the `plot.plot` function.
///
/// - data (array): Array of data rows. A row can be of type array or
/// dictionary, with `label-key` and `value-key` being
/// the keys to access a rows label and value(s).
///
/// *Example*
/// ```typc
/// (([A], 1), ([B], 2), ([C], 3),)
/// ```
/// - label-key (int,string): Key to access the label of a data row.
/// This key is used as argument to the
/// rows `.at(..)` function.
/// - value-key (int,string): Key(s) to access values of a data row.
/// These keys are used as argument to the
/// rows `.at(..)` function.
/// - error-key (none,int,string): Key(s) to access error values of a data row.
/// These keys are used as argument to the
/// rows `.at(..)` function.
/// - mode (string): Chart mode:
/// / basic: Single bar per data row
/// / clustered: Group of bars per data row
/// / stacked: Stacked bars per data row
/// / stacked100: Stacked bars per data row relative
/// to the sum of the row
/// - size (array): Chart size as width and height tuple in canvas unist;
/// width can be set to `auto`.
/// - bar-style (style,function): Style or function (idx => style) to use for
/// each bar, accepts a palette function.
/// - y-label (content,none): Y axis label
/// - x-label (content,none): x axis label
/// - labels (none,content): Legend labels per x value group
/// - ..plot-args (any): Arguments to pass to `plot.plot`
#let barchart(data,
label-key: 0,
value-key: 1,
error-key: none,
mode: "basic",
size: (auto, 1),
bar-style: palette.red,
x-label: none,
x-format: auto,
y-label: none,
labels: none,
..plot-args
) = {
assert(type(label-key) in (int, str))
if mode == "basic" {
assert(type(value-key) in (int, str))
} else {
assert(type(value-key) == array)
}
if type(value-key) != array {
value-key = (value-key,)
}
if error-key == none {
error-key = ()
} else if type(error-key) != array {
error-key = (error-key,)
}
if type(size) != array {
size = (size, auto)
}
if size.at(1) == auto {
size.at(1) = (data.len() + 1)
}
let y-tic-list = data.enumerate().map(((i, t)) => {
(data.len() - i - 1, t.at(label-key))
})
let x-format = x-format
if x-format == auto {
x-format = if mode == "stacked100" {plot.formats.decimal.with(suffix: [%])} else {auto}
}
data = data.enumerate().map(((i, d)) => {
(data.len() - i - 1, value-key.map(k => d.at(k, default: 0)).flatten(), error-key.map(k => d.at(k, default: 0)).flatten())
})
draw.group(ctx => {
let style = styles.resolve(ctx.style, merge: (:),
root: "barchart", base: barchart-default-style)
draw.set-style(..style)
let y-inset = calc.max(style.y-inset, style.bar-width / 2)
plot.plot(size: size,
axis-style: "scientific-auto",
x-label: x-label,
x-grid: true,
x-format: x-format,
y-label: y-label,
y-min: -y-inset,
y-max: data.len() + y-inset - 1,
y-tick-step: none,
y-ticks: y-tic-list,
plot-style: bar-style,
..plot-args,
{
plot.add-bar(data,
x-key: 0,
y-key: 1,
error-key: if mode in ("basic", "clustered") { 2 },
mode: mode,
labels: labels,
bar-width: -style.bar-width,
cluster-gap: style.cluster-gap,
axes: ("y", "x"))
})
})
}
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/035%20-%20Core%202019/007_Chronicle%20of%20Bolas%3A%20Perspectives.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Chronicle of Bolas: Perspectives",
set_name: "Core 2019",
story_date: datetime(day: 08, month: 08, year: 2018),
author: "<NAME>",
doc
)
Naiva gripped her spear, leaning on it so she would not collapse from sheer stark terror. The huge dragon filled half the sky, blocking the canyon walls. He floated there effortlessly, his expression amused at her pathetic attempt to look bold.
"Little one, you cannot defy me, much less defeat me. But with my help, you can rule this sad little world and make it your own to do with as you wish. Just tell me where Ugin is, and why these hedrons have filled the place he fell."
Her throat was so dry the words came out in a croak. "Why do you hate Ugin? He's your twin."
The great dragon recoiled, a blast of angry fire roaring over her head. Sparks rained down upon the hedrons that concealed the Spirit Dragon's skeleton, but the flames and glowing ash slid harmlessly off the hard surface.
"He's no twin of mine. That's just a story he put about, trying to grab for a share of my glory and my triumph."
Naiva cared nothing for Ugin; she'd never met him, and she couldn't imagine any dragon could be a friend to humankind, even if people like her grandmother and Tae Jin's master called him the soul of Tarkir. Yet a seed of strength unfurled in her heart. Somehow, amazingly, this powerful dragon did not know Ugin's body lay concealed beneath the hedrons. That meant he couldn't see Baishya where she lay lost in a helpless trance. The thought of her twin dying filled her heart with such dread that it fueled a recklessly fierce determination. For once, her spear was of no use. She had to find another way.
"You are <NAME>," she said, trying to piece together what she'd learned from the stories and memories.
He smiled. "Of course I am. Who else could I be?"
If he was as the stories claimed, he would be able to get into her mind. Probably he already had. Once he picked through her thoughts, he'd realize Yasova Dragonclaw was right in front of him. Her only hope was to distract him. Hadn't Ugin said not ever to make him angry? If he killed her, then at least she couldn't betray her loved ones.
#figure(image("007_Chronicle of Bolas: Perspectives/01.jpg", width: 100%), caption: [<NAME>, the Arisen | Art by: <NAME>], supplement: none, numbering: none)
"Yes, I have heard of you. I know all about you. You're a liar when you say you aren't twin to Ugin. You were born together and fell together. Isn't that right?"
His roar shook the air. Rocks fell from the canyon wall, rolling and bouncing to crash against the hedron cocoon, but the hedrons held firm because they were stronger than rock.
"Of course that's not right! Who told you that?" He loomed closer, his shadow stealing the patch of sun in which she stood. His voice dropped from thunder to a threatening whisper. "Did Ugin tell you that?"
She took an involuntary step back toward the hedrons to put distance between herself and his teeth. Wasn't it odd that his first reaction was not to smite her but to quibble defensively? Maybe if she kept him busy she could find a way to get out of this. "If you and Ugin aren't twins, then what are you?"
He inhaled with such strength that snow swirled up from where it dusted distant hedrons, spinning around her like a blizzard. His voice boomed over her as he began to talk.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
This is the truth, not that you can appreciate it, weaned as you obviously have been on lies masquerading as truth.
I fell.
Ugin will have told you we fell together, but that is just his way of muddying the waters, telling half lies that people mistake for truth.
I fell out of the wings of the void. Falling was my first sensation: the roar of wind against my scales; a flash of lightning splitting the air; the boom of the progenitor's wing-beats.
The thunder of the progenitor's passage woke me from the dream of falling. When I awoke to conscious thought, I knew all at once with full understanding that my destiny is not to fall but to fly.
I opened my wings to catch the air. Ugin may tell you that he and I were wrapped together like one creature, born together, falling together, minds waking together in bewilderment and curiosity. He may tell you that as we realized we were beings—minds—consciousnesses—that we unfolded together. Flew together.
But that is wrong.
I flew first.
I breathed first.
I beheld the majesty of the sun and the splendor of the heavens and understood the magnificence of my mind in those first instants. Then I recognized the curled-up creature falling helplessly beside me. Of course, my instinct was to help.
Using the tip of my wing to swat his flank, I woke him. With my encouragement, he too unfurled his wings. His wings were not so mighty as mine even then, when we were not yet full grown. In this way he discovered flight or, I should say, I taught him that flight is what we dragons are made for.
Flight, and power.
Of course, I immediately noticed we had siblings. The tempest churning within the progenitor's shadowy wings had passed over, leaving us behind in a green and quiet land. We were alone, just the six of us.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"Six?" Naiva asked. "Weren't there eight of you? Didn't two fall without waking? Didn't their bodies shatter atop the mountain?"
One of his foreclaws swatted down next to her, the impact shaking her off her feet. Her knees hit the ground hard. Pain stabbed tears into her eyes.
"Do not interrupt me again!" he thundered.
As she braced herself to get back up her face was briefly hidden from his scrutiny, and in this moment of privacy, she allowed herself a tiny smile. How he loved the sound of his own voice! Maybe it would be possible to distract him after all, just as Grandmother all those years ago had chosen to distract Atarka with the promise of food in order to save her people.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Falling and flying is how it started.
We flew out of joy. We flew on a journey of discovery, eager to learn more about the complicated patterns of landforms and seas. At first, we thought these were living beings like us but soon comprehended this was nothing more than the world's natural order. We flew for what lesser creatures would measure as years. That was our childhood: the heavens, the wind, the sun, and the stars, and the song they made in their glorious existence, a perfect setting for creatures as splendid as we dragons.
At last, I alone had the courage, and the hunger, to dare fold my wings and set my claws upon the ground. Of course, that momentous decision presaged all that was and is to come: my wings span the heavens, and my presence, my weight, my size, my claws, all these give me dominion over the earth and all that lives on the earth. So, I named our home Dominaria, because I claimed its song for myself.
Naturally, the fractious and unstable humanoids had to be domesticated and made fit to live in peace. My exceptional success at these efforts naturally caused envy among my siblings and cousins, but their resentment and backbiting was easily dealt with by a personage of my talent and wisdom.
But all was not triumph in those days. Sadly, Ugin did not prove up to the challenge. In the early years of my struggle, he pledged to stand beside me, but in fact he hadn't the stomach for the work.
We had to clear out a nest of particularly foul humanoids who stumbled upon a wounded and already dying dragon and claimed they had killed it. A false sense of victory caused them to swagger about as if they had earned a shower of glory. Of course, they had to be eradicated. But Ugin lost his nerve. He flew out of range of their venom-soaked weapons, watching as I selflessly risked myself to avenge our sister's death. Even he would admit this is true. He made excuses, he quibbled, he whined, he kept trying to talk me out of taking control of a situation that would soon threaten all dragons on Dominaria had it been allowed to spread unchecked.
Even when I thoroughly vanquished our foes, he criticized me for my methods, as if I hadn't taken the only path available to end the threat! But I listened patiently to all his wheedling complaints. A few scraps of wisdom percolated up here and there within his words, and I heeded them, too, for I wished for nothing more than to bring a harmonious existence to all sapient creatures on Dominaria. I tried to explain how it would all work out, but he was still frightened.
And so, he fled. He vanished, there one moment and then as if with the blink of the eye and a ripple through the air~GONE.
What a sorrow and a grieving I felt at his disappearance! What a howl of despair I raised!
It happened so fast I truly believed it was my fault. I thought I had not properly reckoned with the cunning and hate of the surviving humanoids. I berated myself for overlooking the power of their sorcerers, for it was impossible for me to believe my dear Ugin was a coward. The only explanation that made sense was that a powerful spell had obliterated him right before my astonished eyes.
#figure(image("007_Chronicle of Bolas: Perspectives/02.jpg", width: 100%), caption: [Doublecast | Art by: <NAME>], supplement: none, numbering: none)
Of course, I rooted out all the humanoid sorcerers in the area. I persuaded them to give up their secrets. Those who refused I killed, while those who cooperated I learned from and then killed later. Since I could no longer trust them. Afterward I wisely created my own academies to train those with magic, so they could serve the greater good under my suzerainty.
Naturally my siblings and cousins envied my success. I did not want any conflict with them—"live and let live" is a good phrase, is it not?—but I had no choice if I wanted to protect my people.
I could speak at length about the war that the others forced upon me, but that would bore me. Suffice it to say that the wars lasted a long time, many generations as you short-lived humanoids measure time. One day, when I had finally driven that stubborn tyrant Arcades into retreat, Ugin returned. He flew right into the middle of our final battle, breaking it off.
The shock of his appearance quite undid me.
"What sorcery is this?" I roared. "Ugin is dead."
"No sorcery. Don't you know me, Nicol?"
My hearts swelled with joy, then constricted with fury. "This is some cursed illusion magic wielded by Arcades!"
With a blast of fire, I meant to obliterate the mirage.
"Nicol! Stop! It's truly me."
At the last moment, I turned my ire aside to blow harmlessly away over the land. What if it truly was him?
"You're dead. I saw you annihilated by a vile burst of human sorcery. It was their revenge for my victory, destroying what I love most. But I avenged you, and set out to make the world worthy of your vision of peace and harmony."
"Is this what you call peace and harmony?"
Spoken like Ugin! He was always finding fault with everything I did. But this time I would impress him, and he would admit I was right, that I had surpassed him.
"It will be. Come see what I have accomplished. Come, Ugin."
I acted as his guide to Dominaria, showing him all its beauty and splendor, all its power and glory, for he had always stuck close to our birth mountain and feared venturing too far away. When he tired of flying, we returned there and settled upon the birth mountain's peak, now crowned with twin horns in honor of the supremacy of dragon-kind. I surveyed the landscape from our high perch, Ugin silent beside me. I thought he was content, just as I was content to have him back beside me. But in fact, he was seething with envy, as I was soon to discover.
"Of course, you never suspected the world to be so vast a place, did you, Ugin? I have traveled everywhere, no place too small or too grand that I have not set claw upon it. No one dares call me "least" now."
Ugin laughed. "Do you really believe this petty squabbling means anything in the vast reaches of the universe?"
How it pained my hearts to hear this bit of mockery. Of course, I wanted to point out that he'd been hiding all this time in a coward's sanctuary, but I refrained and instead tried to soothe him.
"Have you returned only to insult me? I thought we were better friends than that. Now that you are returned, you can share in my triumph, just as we always did before."
"I don't want your leavings, Nicol. I have secrets of my own, learned at the feet of a wise woman."
"That old human is long vanquished by death and her prattling wisdom nothing more than dust. Her secrets were like bubbles that pop when you touch them: pretty to look at but without substance."
"You'll see!" Ugin screamed angrily. He began babbling about planes and walking paths between worlds. "I will find the way, as she promised me long ago, and then you'll be sorry. Then you'll regret thinking you are better than me."
The wind rumbled atop the mountain in a howl of storm. Snow fell so thickly that its blizzard obscured him from my vision.
"Ugin?" I shouted.
In a ripple of warm wind, he was gone.
Fled.
The ugly landscape of his hearts was starkly revealed. Hadn't he abandoned me the first time just when I most needed him? Now he had come back merely to taunt me with the affection I held for him that he clearly did not hold for me. Obviously, he had done it because he was envious of everything I had achieved. My vast intelligence and clever strategies. My mastery of magical skills he wanted for himself and that the old woman had promised him but never delivered. My myriad grateful subjects and the promise of the world I would soon rule as benevolent overlord beloved by all, awe-struck by my majesty and power.
#figure(image("007_Chronicle of Bolas: Perspectives/03.jpg", width: 100%), caption: [Draconic Disciple | Art by: Yongjae Choi], supplement: none, numbering: none)
How dare he claim to be better than me? How dare he flaunt magic that he refused to share? He was nothing, no one, too weak and cowardly to fight. He was least in standing among us elder-born dragons, not really deserving of even being counted among us. Probably he had hoped to steal my glory and claim it for himself. No wonder he was angry, recognizing he hadn't the gift or strength for what I had so easily managed.
And yet sharper than a dragon's tooth, the bite of his insults clawed their way regardless into my hearts.
He had abandoned me again. Deliberately. Mockingly. Condescendingly.
I, who burned with the bright heat of a thousand suns, felt cold for the first time, cold with the grief of rejection. He had returned with the express purpose of rebuffing my overtures of friendship, of flinging my generosity back in my face.
Such a one as he could not feel pleasure in the good fortune of another but only resentment.
Such a one as he could gain no satisfaction or delight in the accomplishments and successes of another but only bitterness.
Such a one as he could find refuge only in envy.
In rage.
RAGE
How dare he have what I had not!
A white-hot spark kindled deep in my chest with a flash of such sunlit brightness that it blinded me. Impenetrable blackness filled my vision. Tumbling, I fell, totally disoriented, until with a gut-wrenching twist I righted myself.
Only to find myself no longer atop the birth mountain but gliding over a boundless stretch of oceanic waters as flat and still as a mirror. I was the only thing in motion, my wings shadowing the sea's surface. There was no sun in this peculiar place, only the water and many craggy islets and a constant shushing whisper of secrets just out of my reach. By a faint humming vibration deep in my bones, I suspected this was not a plane but some manner of artificial construct, built by an unknown agent that had left neither claw nor footprint to mark its authorship. Who, or what, possessed so much power? And why had it been abandoned?
Bubbles floated peaceably in the sky, drifting downward until they touched my scales and popped
With each pop, a sweet vista sprang open before me for a breathtaking moment before it vanished: other lands, other worlds, other planes.
Ah!
With my next breath, I comprehended the whole: I had become a Planeswalker.
I had become the very thing Ugin had been ranting about all along, the magic he wanted for himself but could not achieve.
After that first unexpected passage, it was easy to keep going, to move in and out through a web of connections linked by a clot of darkness to which everything else adhered. I walked from one world to another to the next and the next.
What wonders lay beyond the meager treasures of Dominaria! A hundred worlds I visited, and then a hundred more. Yet in all that time I found no trace of any other creature who could walk between worlds. I was the first among all sapient creatures to discover the possibility of traveling between planes. No wonder eternity and infinity welcomed me, having sojourned alone for so long!
Even so I began to think again of Ugin, wanting to share this glory with another, or at least to forgive him, to hear how he might at last acknowledge how far I had come.
I am not a selfish creature. It seemed churlish to withhold this knowledge from Ugin, even if he could never manage to duplicate the planeswalking I had achieved, for at that time I did not yet understand how a peerless spark separates we rare Planeswalkers from the unworthy others of sapient life for whom untold worlds will lie forever out of reach.
I thought of him. I believed we could be friends as we once were at the dawn of days. So I went home.
Of course, a great deal of time had passed as you humanoids measure it. The Dominaria I had left was so changed, I barely recognized large swathes of it. The courses of rivers altered; islands sundered; lakes gone dry and seas risen to flood once habitable shores. There I found the wars between the elder dragons over long since. A tenuous peace had taken hold throughout much of the land. Of all the elder dragons and their children, only Chromium Rhuell, <NAME>, Palladia-Mors, and that vexatious beast Vaevictis Asmadi had survived. Rhuell wandered the land in the guise of a helpful observer, all offering praise for his wisdom and beneficence, yet he was no better than those of our siblings who plundered and ruled, for he poked his snout in wherever he wished, and who among the humanoids could tell him no? Vaevictis still roamed with restless fervor, pillaging and burning as he wished, sometimes teaming up with that ill-tempered creature Palladia-Mors but more often alone.
Yet as I searched the wide world over, I found no trace of Ugin. At length, I made my way to Arcades's kingdom, as Ugin and I had once done when we were fledglings.
#figure(image("007_Chronicle of Bolas: Perspectives/04.jpg", width: 100%), caption: [Arcades, the Strategist | Art by: <NAME>], supplement: none, numbering: none)
Arcades welcomed me in his most tendentious elder sibling manner, wondering where I had been hiding myself all this time and proudly showing me about the empire he considered meticulously regulated and magnificently vast. But I knew better.
"Ugin? I know you and he were particularly close, born as you were. But I haven't seen him since the earliest of days when you two left to root out those dragon killers. You told us he died."
"That's not what I said," I corrected him. "He wasn't dead at all. He was just hiding. He returned right at the climax of our last battle."
He regarded me with his usual patronizing superiority. "The battle you fled from, abandoning your troops? I gathered them under my wings. They were grateful for my protection, I assure you."
"Did you not see him, flying between our armies?" I demanded, utterly astonished by his obliviousness.
"You were not yourself that day, Bolas. No doubt you were seeing illusory things. You have always felt shame about Ugin's death, haven't you? Did you blame yourself for not protecting him? Or did you stand aside and allow him to be killed by some venomous sorcery? I've always wondered. I've always suspected you envied him because he was cleverer and wiser than you."
I, envy Ugin? Ridiculous.
Then I understood: Arcades was disparaging me, hoping to make me lose my temper as I would have done when I was young and volatile. But I was bigger than that. Much, much bigger. I was a Planeswalker, first and only one of my kind. To rule in Dominaria was all very well for a small-minded despot like Arcades, while I had grown as far beyond him as he was beyond pathetic, weak, short-lived humans.
I surveyed the graceful architecture and fastidiously ordered streets and districts of the city where he presided from a palace built atop a cliff. And I insinuated a worm of doubt in his haughty mind: Maybe the humanoids who lived here weren't as deserving as he thought them. Maybe they didn't really respect him or follow his laws, but only pretended to. Maybe they were plotting to rise up and overthrow him, for wasn't he nothing more than a tyrant even if he fancied himself a benevolent one? Wasn't that what his subjects whispered, when they were sure he couldn't hear? If he sent out agents into every corner and crevice of the realm, they could report back to him and thus root out instigators. He could offer rewards for people turning in traitors and pay handsomely for people brave and bold enough to turn on their own kinfolk. And if that wasn't enough, then he could burn down suspect districts or even whole cities. Burn them. BURN THEM.
With a last smile, I wrapped myself in magic and departed Dominaria. The doubts I had seeded would take root, or they would wither. Either way, Arcades would not trouble me again. He would never walk the planes. He didn't have it in him. Only I did.
So, you may imagine my shock and my joy when I walked out of the blind eternities into the place I had come to call my Meditation Realm only to find Ugin there! He was floating atop the waters staring at himself as if he could imagine nothing better than to look at his own reflection.
"Ugin! How is it you are here? I am overjoyed to see you, Brother, for I feared I had lost you forever."
But he had no words for me. He had only animosity, driven by his anger and envy and resentment and bitterness, by the memory of mocking, condescending laughter. By the fear I would reveal the truth about things he did not want others to know, and that those others would believe me over him.
He attacked, viciously and without warning, all raw fury and malignant resentment. I had no choice but to defend myself. First above the wide waters of the Meditation Realm and then on a wild pummeling path through the planes, we struggled for days, years, generations. We battled with claw and tooth and with magic. On and on the struggle raged, for he was unrelenting, rejecting all my attempted overtures for a truce. All he wanted was to kill me for the crime of walking the planes before he did. His hearts were eaten out by jealousy for what I had not shared with him.
What could I do? There was no placating him.
In the end, by diverse paths, we returned to the Meditation Realm. There, purely in self-defense, I killed him.
With a mighty splash, he fell into the still waters. The impact resounded like thunder. Monstrous waves rose from the displacement and swept across the craggy islets, crashing and destroying as they went. The waves ran on and on, washing far beyond the bounds of the Meditation Realm into the web of connection that links the planes themselves and maybe even into the blind eternities whose depths even dragons cannot plumb. The waves spilled out of the Meditation Realm as if Ugin's death had, like a weight dropped upon a ceramic bowl, broken cracks in the vessel itself.
The violence of the waves swept me out of the Meditation Realm. Like a cast spear, I was flung through ten or twenty or a hundred planes before I fell hard back into Dominaria, onto the island chain of Madara at a time when the memory of the Elder Dragon Wars had faded into legend. Bruised and stunned, I struggled to recover my strength, but recover it I did. Many battles lay before me, and I met them with ease.
Of course, little Naiva, you must be interested in the long course of my fascinating life, and I would gladly regale you with the whole now that I have set you right about Ugin's false story. But I know you believe you are distracting me from my purpose here.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
She could no longer see the sky, only his dazzling eyes and the brilliant curve of his horns with the egg-gem spinning mesmerically between the points.
His smile showed his teeth. In one gulp, he could eat her.
"It always discourages me," he said in a kindly voice, "that people are so quick to think we dragons like the taste of human flesh when in fact it is not to our taste at all."
His head dropped lower. She took another step back but could move no farther, trapped against the hedrons.
"What you don't understand is that I have all the time in the worlds, while your time is running out fast. Now. Where is Ugin?"
"Ugin is dead."
"So I believed when I killed him in the Meditation Realm. I departed, believing him dead. That was my mistake. Because somehow, he wasn't dead. He has plagued me ever since, most recently with a misbegotten plan to trap me on Ixalan by means of a magical artifact."
"Ixalan?" She croaked out the word, anything to keep him talking.
"The name means nothing to you. It's another plane. One you will never see in your entire short, brutish, nasty life."
#figure(image("007_Chronicle of Bolas: Perspectives/05.jpg", width: 100%), caption: [Highland Lake | Art by: <NAME>], supplement: none, numbering: none)
Her limbs were cold and her heart was sluggish, as if her body had decided it was better to collapse into insensibility than face the shattering power of <NAME>, Ugin's greatest enemy. But she would not cringe.
"Ugin is dead." She forced out the words in a harsh whisper. "His bones lie right here. Beneath the hedrons."
"Ah. Hmm." His rumble unnerved her as his gaze scanned the formation winding out of sight beyond the curve of the canyon. "His falling body cleaved this canyon. I suppose it's possible his bones really do lie here."
"Can't you see the bones?"
He slapped a foreclaw on the ground, the sound echoing off the canyon walls. "Do not question me. It's a shame the others consider you expendable, isn't it?"
"Expendable? They rely on me!"
"You cannot be so naive, little one. Your grandmother tolerates you only because she finds you useful in protecting the grandchild she clearly cares about, the one who inherited the shamanic gifts. You have no magic, do you?"
"I'm a hunter!"
"Yes, yes, you're a hunter. Everyone is a hunter. But your sister is a shaman. There's nothing worse than discovering someone you love holds tightly to a gift they've denied you. That they refuse to share with you. That you're expected to pander to and flatter them, admire them, when really, you're the valuable one. You're the one who will feed the tribe in the years to come. You're the one who will lead the people into the high mountains in the summer and to the lowlands during the winter. You're the leader, burdened by this sister you never asked for and didn't really want. They keep holding you back because of her, making you watch over her, wait for her, not giving you the scouting and hunting responsibilities you've earned with your skill. It's just not fair. If you were free of her, then you could finally come into your own, couldn't you? You could finally become the great hunter and leader you deserve to be. And I can help you with that, Naiva."
His words, uttered in such a soft, persuasive tone, insinuated themselves into her heart. The old resentment sparked. All the annoyances of years past clawed their way back into the forefront of her mind, throbbing like a headache only he could soothe. But she couldn't trust him. She clung to that fading thought. "How can you help me? Why would you help me?"
"Because if I don't help you, then I will be forced to destroy Tarkir. Wouldn't that be a shame? Especially since you are the only one who can prevent its destruction."
"Why would you destroy Tarkir?" she whispered hoarsely, horrified and shaking.
"Because he loves Tarkir. But mostly so there can be no chance of him being reborn here." He paused, then huffed a soft warm breeze, like magic, over her trembling body. "Do not fret, Naiva. I don't want to annihilate this plane because I'd rather help you. Together, we will clear Tarkir of all your enemies, all the dragons and all the other tribes. You can hunt the wide world over with no one to stand in your way. I will bring about everything you have ever dreamed of because I have that power, and I will use it on your behalf. All you need do is bring me Yasova. Now."
Now. The word reverberated in her head. It was true, after all. Baishya had always been a burden heavier than a net of dead goblins. When Grandmother died, no family group would risk taking in a young, inexperienced whisperer whose presence could get them all killed. Why should she be asked to give up everything she wanted just to protect her sister? The old ways had never belonged to Naiva. They were just obstacles in her path forward.
"She's here. Right here. Hiding."
His smile lit the entire world. "Fetch her for me. Then you will receive your reward."
There was no future for her in clinging to the past. She'd been right when she'd told Tae Jin that the old ways were a corpse better consumed by vultures.
#figure(image("007_Chronicle of Bolas: Perspectives/06.jpg", width: 100%), caption: [Atarka's Command | Art by: <NAME>], supplement: none, numbering: none)
Yet when she thought of the young ghostfire warrior, of his courage and sacrifice, a shudder passed through her frame and ripped a gash in her certainty. What would Tae Jin say when he learned she had handed over the great Yasova Dragonclaw to <NAME>?
"Little Naiva, you mustn't believe I want to hurt Yasova. I want to help. That's all. Now go." His voice hardened. A pressure built in her head until she thought her skull would burst. "#emph[Now] ."
Kneeling, she pulled aside the fragment of broken hedron and crawled in. There, in the dim, stuffy confines of the space, Baishya lay as if asleep, breathing evenly. Grandmother sat cross-legged in mediation, eyes closed, left hand resting open on a thigh while her right hand grasped Baishya's bare fingers with an affectionate clasp. The gesture ate a hole of envy right through Naiva's heart. Grandmother had always preferred Baishya. She loved her more than she loved Naiva.
She would have to bodily haul Grandmother outside. But that could wait. Pulling her knife from its sheath, she pressed the blade against Baishya's vulnerable throat.
|
|
https://github.com/PmaFynn/cv | https://raw.githubusercontent.com/PmaFynn/cv/master/src/metadata.typ | typst | The Unlicense | /* Personal information */
#let firstName = "Fynn"
#let lastName = "Friedrichs"
#let personalInfo = (
location: "Krefeld, Germany",
phone: "+49 152 09207000",
email: "<EMAIL> ",
homepage: "work.fynnfr.org",
github: "PmaFynn",
linked: "linkedin.com/in/fynnfr",
//TODO: maybe add something here -> current location or something
//extraInfo: "",
)
#let headerQuoteInternational = (
"": [Senior Software Engineer looking for a full time job],
"en": [Information Systems Student looking for a new challenge],
"fr": [Ingénieur logiciel expérimenté cherchant un emploi à temps plein],
)
/* Layout settings */
#let cvLanguage = "en"
#let accentColor = "burgundy"
#let profilePhoto = "images/cvImage-modified.png" // Leave empty if profil photo is not needed
#let varEntryOrganisationFirst = false // Choose whether to put company or position in bold
#let varDisplayLogo = false // Choose whether to display organisation logo
|
https://github.com/NOOBDY/formal-language | https://raw.githubusercontent.com/NOOBDY/formal-language/main/q9.typ | typst | The Unlicense | #import "@preview/finite:0.3.0": automaton, layout
#let q9 = [
9. Let $Sigma = {a_1,...,a_n}$ be an alphabet of $n$ symbols.
+ Construct an `NFA` with $2n + 1$ states accepting the set $L_n$ of strings over $Sigma$ such that, every string in $L_n$ has an odd number of $a_i$, for some $a_i in Sigma$. Equivalently, if $L^i_n$ is the set of strings over $Sigma$ with an odd number of $a_i$, then $L_n = L^1_n union...union L^n_n$.
#automaton(
(
q: (q11:"2", q21:"2", qn1:"2"),
q11: (q12:"1"),
q12: (q11:"1"),
q21: (q22:"1"),
q22: (q21:"1"),
qn1: (qn2:"1"),
qn2: (qn1:"1"),
d:()
),
labels: (
q: $ q $,
q11: $ q_11 $,
q12: $ q_12 $,
q21: $ q_21 $,
q22: $ q_22 $,
qn1: $ q_(n 1) $,
qn2: $ q_(n 2) $,
d: $ dots.v $
),
final: ("q12", "q22", "qn2"),
style: (
state: (
stroke: 0.5pt,
),
transition: (
stroke: 0.5pt,
curve: 0,
label: (
angle: 0deg
)
),
q-q11: (label: (text: $epsilon.alt$)),
q-q21: (label: (text: $epsilon.alt$)),
q-qn1: (label: (text: $epsilon.alt$)),
q11-q12: (curve: 0.5, label: (text: $a_1$)),
q12-q11: (curve: 0.5, label: (text: $a_1$)),
q21-q22: (curve: 0.5, label: (text: $a_2$)),
q22-q21: (curve: 0.5, label: (text: $a_2$)),
qn1-qn2: (curve: 0.5, label: (text: $a_n$)),
qn2-qn1: (curve: 0.5, label: (text: $a_n$)),
d: (stroke: 0.0pt)
),
layout: layout.custom.with(
positions: (..) => (
q: (0, -3),
q11: (2, 0),
q12: (4, 0),
q21: (2, -2.5),
q22: (4, -2.5),
qn1: (2, -6),
qn2: (4, -6),
d: (3, -4.25)
)
)
)
+ Prove that there is a `DFA` with $2^n$ states accepting the language $L_n$.
See (c)
+ Prove that every `DFA` accepting $L_n$ has at least $2^n$ states.
For every symbol $a_i in Sigma$, the `DFA` has to keep track of whether the count is odd or not. This would result in at least 2 states for each symbol, which is at least $2^n$ states in total.
]
|
https://github.com/sjedev/typst-notetaking-template | https://raw.githubusercontent.com/sjedev/typst-notetaking-template/main/README.md | markdown | The Unlicense | # typst-notetaking-template
Simple notetaking template for Typst
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/units.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
// ### Units
=== 单位
// First, though, how do you measure stuff in a font? When fonts were bits of metal, it was easy: you could use callipers or a micrometer to measure the sort, and get an answer in millimeters or printers points. But digital fonts, as we've seen in the previous chapter, are meant to be scalable; that is, usable at any size. With scalable fonts, there isn't such a thing as a 12pt Times Roman as distinct from a 16pt Times Roman; there isn't any *size* there at all.
首先有个疑问,在进行字体设计时我们怎么测量长度呢?当字体还是金属的时代这很容易,使用卡尺或者千分尺之类的工具就可以量出#tr[sort]的尺寸,用厘米或者点(pt)作为单位来记录即可。但数字字体,我们在上一章讨论过,它可以以任意大小显示。对于这些可缩放的字体来说,12pt和16pt的Times Roman并没有什么区别,它们根本没有大小这个概念。
// So coordinates and size values inside digital fonts are defined in terms of an *em square*, which is itself divided into an arbitrary number of *units*, typically 1000, 1024 or 2048. If we want to display text at 12 points, we draw the *em square* at that size, and then scale up the design to match.
数字字体内的坐标和尺寸由*#tr[em square]*来确定,它的高度会被分成任意数量个小单元,一般会是1000,1024或者2048个单位。如果我们希望显示12pt的文本,就把*#tr[em square]*定为这个尺寸,具体的字符设计就自然地缩放为相匹配的大小了。
#figure(caption: [
#tr[glyph]在不同字号时的缩放
], include "units-graph.typ") <figure:units>
// We can see a number of things from this diagram. First, we notice that the glyph outline doesn't need to be contained within the em square itself. It's just a notional rectangular box, a kind of digital type sort. (Yes, the old lining-up-boxes model of typography again.) In this case, with Bengali script, we want to make sure that the headline is always connected, so there is a slight overlap between the glyphs to make this happen, leading to the outline of the headline jutting out the left and right side of the em square.
从@figure:units 中我们可以看出很多信息。首先,#tr[glyph]#tr[outline]不需要充满整个#tr[em square],它只是一个用于参考的矩形框而已,就像#tr[sort]字身的数字版。(是的,又是古老的基于线和框那一套。)在图中的孟加拉文例子中,我们希望确保#tr[headline]总是连续的,所以将#tr[glyph]设计为有轻微的重叠,也就造成了这些#tr[headline]的#tr[outline]会突出于#tr[em square]的左右两侧。<pos:bengali-headline>
// Notice also that the baseline and full height of the glyph are not determined by the em square itself; the designer decides where to put the outlines within the em square, and even how high to make the outlines. This can mean that different digital fonts which are notionally the same type size actually appear at different sizes!
需要注意的是,#tr[baseline]和#tr[glyph]的高度并不由#tr[em square]决定。设计师会决定把它们放在#tr[em square]的什么位置,或者什么高度上。这也就意味着在使用相同的字号调用不同的字体时,实际的显示尺寸可以千差万别。
#figure(caption: [
Noto Sans和Trajan字体#footnote[译注:原文使用的应该是Trajan Pro 3的图片,因直接嵌入字体数据的许可证问题,此处换成同风格的Cinzel。]中的字母H、x
], placement: none, include "notional-size.typ") <figure:notional-size>
// Here the designers of Noto Sans and Trajan have placed the outlines in the em square in different ways: Trajan uses a bigger body, a higher x-height, and fills up the square more, whereas Noto Sans leaves space at the top. (Both of them leave space at the bottom for descenders.) We'll look at the differing heights used in font design a little later, but for now just remember that because the em-square is a notional size and designers can put outlines inside it however they like, a 12pt rendering of one font may be "bigger" than a 12pt rendering of another, even if the em square is scaled to be the same size.
@figure:notional-size 展示了Noto Sans和Trajan两个字体在把#tr[outline]放进#tr[em square]时采用的不同方式:Trajan拥有一个更高的#tr[x-height],它的体型更大,向上填满了整个方框;而Noto Sans则在上面留出了一些空间(两个字体都在下方为#tr[decender]预留了空间)。字体中的这些不同的高度会在后面的章节详述,现在只需要记住,因为#tr[em square]只是用于参考的名义上的边界,某个字体的12pt可能会比另一个字体的12pt更大,即使它们的#tr[em square]被缩放到了相同的大小。
// However, dividing this notional square up into a number of units gives us a co-ordinate system by which we can talk about where the outlines fall on the glyph. Instead of saying "make the horizontal stem width about a tenth of the height", we can say "make the horizontal stem width 205 units wide", and that'll be scalable - true for whatever size of font we're talking about.
但这个名义上的边界在被划分成小单元之后,我们就有了一个坐标系统,可以用于指定#tr[outline]位于整个#tr[glyph]的什么位置。我们不需要用“画一条大约是整体高度的1/10的水平#tr[stem]”这样的描述,只需要说“画一条205个单位宽的水平#tr[stem]”就行。而这也保持了可缩放的特性,因为对于任何字号来说这一描述都是成立的。
// We'll use these *font units* every time we talk about the dimensions within a font.
我们在讨论字体中的所有尺寸时都会使用这个单位长度。
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/identify-wedges/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Identify: Pushing Robots",
type: "identify",
date: datetime(year: 2023, month: 9, day: 3),
author: "<NAME>",
witness: "<NAME>",
)
VRC is a very contact heavy robotics competition. We will often be trying to
push other robots. During the Spin Up season, even with our 6 motor drivetrain,
we still struggled to push other robots.
We need to something that will give us an advantage while pushing robots without
adding more motors to our drivetrain.
#figure(image("modelone.png", width: 80%))
= Design Constraints
- No active actuators
- Must use vex materials
- Has to fit on the robot.
- Cannot exceed the 18" size limit.
=Design Goals
- Needs to be able to push another larger robot 2 feet while driving into it.
- Needs to be able to start folded in at the start of the match.
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/常微分方程/作业/2100012990 郭子荀 常微分方程 8.typ | typst | #import "../../template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: note.with(
title: "作业8",
author: "YHTQ",
date: none,
logo: none,
withOutlined : false,
withTitle : false,
withHeadingNumbering: false
)
= p247
== 1
不妨假设 $f$ 在 $(x_1, x_2)$ 上恒正,有:
$
f'(x_1) >= 0, f'(x_2) <= 0
$
假设 $g(x)$ 在 $(x_1, x_2)$ 上无零点,不妨设其恒正。令:
$
W(x) = Det(f, g;f', g') = f g' - f' g\
W'(x) = Det(f, g;f'', g'') = Det(f, g;-p(x)f' - q(x) f, -p(x) g' - r(x) g)\
=Det(f, g;-p(x)f', -p(x) g' - (r(x) - p(x)) g)\
= - p(x) W(x) - f g (r(x) - p(x))
$
注意到一定有:
$
f g(r(x) - p(x)) > 0
$
由一阶方程的比较定理,有:
$
B e^(-p(x)) < W(x) < A e^(-p(x))
$
其中 $A e^(-p(x))$ 是:
$
cases(
W'(x) = -p(x) W(x),
W(x_1) = - g(x_1) f'(x_1)
)
$
的解,而 $B e^(-p(x))$ 是:
$
cases(
W'(x) = -p(x) W(x),
W(x_1) = - g(x_2) f'(x_2)
)
$
的解,然而不难发现 $- g(x_1) f'(x_1) <= 0, - g(x_2) f'(x_2) => 0$ 导致 $A <= 0, B >= 0$,这是荒谬的!
== 2
考虑 $y'' + m y = 0$ 的解 $sin (sqrt(m) x)$ 由比较定理: $k/(sqrt(m)) pi$ 之间一定有 $phi$ 的解,因此 $phi$ 无限振动\
对于任何两个相邻零点 $x_1, x_2$:
- 可以找到 $y'' + m y = 0$ 的解 $sin (sqrt(m) x - x_1)$,加强的比较定理给出 $x_2 in (x_1, x_2 + pi/sqrt(m))$
- 可以找到 $y'' + M y = 0$ 的解 $sin (sqrt(M) x - x_1)$,加强的比较定理给出 $pi/sqrt(M) in (x_1, x_2)$
证毕
== 3
注意到:
$
(z/y)' = (z' y - z y') / y^2\
(z' y - z y')' = z'' y - z y'' = z q(x) y - z Q(x) y = (q(x) - Q(x)) z y < 0\
z' y - z y'|_(x = x_0) = 0
$
进而 $z' y - z y' < 0$,原式单调减少
== 7
由线性方程组结论,设 $u$ 是满足 $y(0) = a$ 的解,$v$ 是满足 $y(0) = 0$ 的非零解,则所有 $y(0) = a$ 的解恰为:
$
u+ C v, forall C in RR
$
进而满足给定初值的解就是要:
$
u(1) + C v(1) = b
$
只要 $v(1) != 0$ 方程就恰有唯一解,而若 $v(1) = 0$,由比较定理 $y'' = 0$ 的解 $y = 1$ 一定在 $[0, 1]$ 上有零点,这是荒谬的!(类似的,该方程的解至多一个零点)
对于第二个结论,不妨设 $a > 0$,已经说明解至多一个零点,无妨设 $phi(x)$ 在 $(0, 1)$ 上恒正,因此 $phi''$ 也恒正,导函数单调增加。然而由 $(0, 1)$ 间恒正可得 $y'(1) < 0$(不能等于零,否则整个解为零),进而函数严格单调减少。
= p258
== 1
- 设 $lambda = - m^2$,则 $y'' + lambda y = 0$ 的通解为:
$
linearCombinationC(e^(m x), e^(-m x))
$
代入初值:
$
cases(
C_1 + C_2 = 0,
C_1 e^m + C_2 e^(-m) = 1
)
$
只要 $m != 0$ 方程一定有解。若初值为 $(0, 0)$ 则无解
- 设 $lambda = m^2$,则 $y'' + lambda y = 0$ 的通解为:
$
linearCombinationC(cos m x, sin m x)
$
代入初值:
$
cases(
C_1 = 0,
C_1 cos m + C_2 sin m = 1
)
$
只要 $m != k pi$ 方程一定有解。若初值为 $(0, 0)$ 则除非 $m = k pi$ 方程无解
== 2
这是欧拉方程,令 $x = e^t$。计算:
$
der(y, x) = der(y, t)der(t, x) = der(y, t) e^(-t)\
der(der(y, x), x) = der(der(y, x), t)der(t, x) = der( der(y, t) e^(-t), t) e^(-t) \
= ((dif^2 y)/(dif t^2) e^(-t) - der(y, t) e^(-t))e^(-t)\
x^2 der(der(y, x), x) = (dif^2 y)/(dif t^2) - der(y, t)
$
代回方程得:
$
cases(
(y'' - y') - lambda y' + lambda y = 0,
y(0) = 0,
y(ln 2) = 0
)
$
方程化为:
$
y'' -(lambda + 1)y' + lambda y = 0
$
- $lambda != 1$ 时特征根分别为 $1, lambda$,通解为:
$
linearCombinationC(e^x, e^(lambda x))
$
代入初值:
$
cases(
C_1 + C_2 = 0,
2 C_1 + 2^lambda C_2 = 0
)
$
有非零解当且仅当 $lambda = 1$ ,这是不可能的
- $lambda = 1$ 时通解为:
$
linearCombinationC(x e^x, e^x)
$
代入初值:
$
cases(
C_2 = 0,
2 ln 2 C_1 + 2 C_2 = 0
)
$
仍然无非零解
== 4
用常数变易法,假设 $u_1, u_2$ 是对应齐次方程的两个基解,设:
$
y = linearCombinationC(u_1, u_2)\
y' = linearCombinationC(u'_1, u'_2) + C'_1 u_1 + C'_2 u_2\
$
设 $C'_1 u_1 + C'_2 u_2 = 0$,继续求导:
$
y'' = linearCombinationC(u''_1, u''_2) + C'_1 u'_1 + C'_2 u'_2\
linearCombinationC(u''_1, u''_2) + C'_1 u'_1 + C'_2 u'_2 + (lambda r(x) +q(x)) linearCombinationC(u_1, u_2) = f(x)\
C'_1 u'_1 + C'_2 u'_2 = f(x)
$
得到方程组:
$
cases(
C'_1 u_1 + C'_2 u_2 = 0,
C'_1 u'_1 + C'_2 u'_2 = f(x)
)
$
解得:
$
C'_2 (u_1 u'_2 - u'_1 u_2) = f(x) u_1\
C'_2 = (f(x) u_1) / (u_1 u'_2 - u'_1 u_2)\
C'_1 = (f(x) u_2) / (u'_1 u_2 - u_1 u'_2)\
C_2 = integral_(0)^(x) (f u_1) / (u_1 u'_2 - u'_1 u_2) + A_2\
C_1 = integral_(0)^(x) (f u_2) / (u'_1 u_2 - u_1 u'_2) + A_1
$
代入边值:
$
cases(
(C_1 (0) u_1 (0) + C_2 (0) u_2 (0)) cos alpha - (C_1 (0) u'_1 (0) + C_2 (0) u'_2 (0)) sin alpha = 0,
(C_1 (1) u_1 (1) + C_2 (1) u_2 (1)) cos alpha - (C_1 (1) u'_1 (1) + C_2 (1) u'_2 (1)) sin alpha = 0
)
$
观察发现,这是关于 $A_1, A_2$ 的非齐次线性方程组,系数矩阵为:
$
mat(u_1 (0) cos alpha - u'_1 (0) sin alpha, u_2 (0) cos alpha - u'_2 (0) sin alpha; u_1 (1) cos alpha - u'_1 (1) sin alpha, u_2 (1) cos alpha - u'_2 (1) sin alpha)
$
- 若其满秩,不难发现方程组有唯一解
- 否则,两行线性相关,不难得到齐次微分方程的特征函数,进而 $lambda$ 一定是特征值。此时不妨设 $u_1$ 是特征函数,方程化简为:
$
cases(
C_2 (0) u_2 (0) cos alpha - C_2 (0) u'_2 (0) sin alpha = 0,
C_2 (1) u_2 (1) cos alpha - C_2 (1) u'_2 (1) sin alpha = 0
)
$
断言 $u_2 (0) cos alpha - u'_2 (0) sin alpha != 0,u_2 (1) cos alpha - u'_2 (1) sin alpha != 0$ ,否则 $u_1, u_2$ 在 $0$ 或 $1$ 处线性相关,导致整个解线性相关,与无关假设矛盾!因此上式有解当且仅当 $C_2 (0) = C_2 (1)$
另一方面,令 $u_1 u'_2 - u'_1 u_2 = W(x)$,则有:
$
W'(x) = u_1 u''_2 - u''_1 u_2 = (lambda r(x) + q(x)) (u_1 u_2 - u_1 u_2) = 0
$
表明 $W(x)$ 是常数,当然非零(否则 $u_1, u_2$ 相关),因此:
$
C_2 (0) = C_2 (1) <=> integral_(0)^(1) (f u_1) / (u_1 u'_2 - u'_1 u_2) = 0 <=> integral_(0)^(1) f u_1 = 0
$
证毕
=
==
$
partialDer(z, x) - y / (x + 2y) partialDer(z, y) = 0\
(dif x)/(x + 2 y) + (dif y)/y = 0\
y' = - y/(x + 2 y)\
u = y /x \
y = x u\
y' = u + x u' = - u/(1 + 2 u)\
x u' + (2 u + 2 u^2)/(1 + 2 u) = 0\
1/x x' + (1 + 2 u)/(2 u + 2 u^2) = 0\
1/x dif x + (1 + 2 u)/(2 u + 2 u^2) dif u = 0\
dif ln x + dif 1/2 ln (2 u + 2 u^2) = 0\
ln x + 1/2 ln (2 y/x + 2 y^2/x^2) = C\
$
==
$
(dif x)/ (x - z) = (dif y)/ (y - z) = (dif z) / (2 z)\
(dif x)/ (x - z) = (dif z) / (2 z)\
2 z dif x - (x - z) dif z = 0\
2 dif x - (x / z - 1) dif z = 0\
u = x / z, x = z u, dif x = u dif z + z dif u\
2 (u dif z + z dif u) - (u - 1) dif z = 0\
(u + 1) dif z + 2 z dif u = 0\
1/z dif z + 2/(u + 1) dif u = 0\
ln z + 2 ln (u + 1) = C\
(x/z+1)^2 z = C\
(x - z) partialDer(u, x) = 2 (x/z + 1)(x - z)\
partialDer(u, z) = (x/z+1)^2 + z (-x/z^2) 2(x/z + 1)\
2 z partialDer(u, z) = 2(x+z)(x/z + 1) -4 x (x/z + 1) =
$
$
(dif y)/ (y - z) = (dif z) / (2 z)\
(y/z + 1)^2 z = C
$
==
$
(dif x)/(x y) = (dif y)/(x - 2 z) = (dif z)/(y z)
$
$
(dif x)/(x) = (dif z)/(z)\
x/z = C_1
$
$
y' = (x - 2 z)/(x y)\
z' = z / x\
y y' + 2 z' = 1\
1/2 y^2 + 2 z - x = C\
$
$
z = 1/2 x -1/4 y^2\
x y partialDer(z, x) = 1/2 x y\
(x - 2 z) partialDer(z, y) = (x - 2 z) (-1/2 y)
$
$
(dif x_i)/(x_i) = (dif y)/(k y)\
ln x_i - 1/k ln (k y) = 0\
y = C x_i^k
$
|
|
https://github.com/NOOBDY/formal-language | https://raw.githubusercontent.com/NOOBDY/formal-language/main/README.md | markdown | The Unlicense | # Formal Language 2024 Spring
```
typst c main.typ
```
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/pages/undergraduate-proposal-eval.typ | typst | MIT License | #import "../utils/fonts.typ": 字号, 字体
#import "../utils/datetime-display.typ": datetime-display
#import "./template-individual.typ": template-individual
#let undergraduate-proposal-eval(
comment,
scores-supervisor: none,
scores-college: none,
) = {
template-individual("毕业论文(设计)文献综述和开题报告考核", outlined: true)[
#set text(weight: "bold", size: 字号.小四)
导师对开题报告、外文翻译和文献综述的评语及成绩评定:<mzt:no-header-footer>\
#comment
#v(0.8fr)
#align(right)[
#table(
columns: 4,
align: center,
[成绩比例], [文献综述#linebreak() (10%)], [开题报告#linebreak()(15%)], [外文翻译#linebreak()(5%)],
[分值], ..(
if scores-supervisor == none {
()
} else {
(
[#scores-supervisor.at(0)],
[#scores-supervisor.at(1)],
[#scores-supervisor.at(2)],
)
}
)
)
导师签名#box(width: 5em, stroke: (bottom: 0.5pt))\
年#h(2em)月#h(2em)日
]
#v(1em)
学院盲审专家对开题报告、外文翻译和文献综述的评语及成绩评定:
#v(1fr)
#align(right)[
#table(
columns: 4,
align: center,
[成绩比例], [文献综述#linebreak() (10%)], [开题报告#linebreak()(15%)], [外文翻译#linebreak()(5%)],
[分值], ..(
if scores-college == none {
()
} else {
(
[#scores-college.at(0)],
[#scores-college.at(1)],
[#scores-college.at(2)],
)
}
)
)
开题报告审核负责人(签名/签章)#box(width: 5em, stroke: (bottom: 0.5pt))\
年#h(2em)月#h(2em)日
]
]
} |
https://github.com/kicre/note | https://raw.githubusercontent.com/kicre/note/main/study/测控/仪器仪表/报告论文.typ | typst | // 设置页面
#set page(
paper: "a4",
margin: (
top: 2.5cm,
bottom: 2.0cm,
left: 2.5cm,
right: 2.0cm
),
numbering: "1",
number-align: center,
)
// 设置段落
#set par(
first-line-indent: 2em,
justify: true,
leading: 20pt,
)
#let fake_par = {
v(-1em)
box()
}
#show heading: it => {
it
fake_par
}
// 设置正文文字格式
#set text(
lang: "zh",
region: "cn",
font: ("Times New Roman", "STsong"),
size: 12pt
)
//设置标题格式
#set heading(numbering: "1.1.1.1")
#show heading: it => locate(loc => {
let levels = counter(heading).at(loc)
let deepest = if levels != () {
levels.last()
} else {
1
}
set text(12pt)
if it.level == 1 [
#if deepest !=1 {
pagebreak()
}
#set par(first-line-indent: 0pt)
#let is-ack = it.body in ([Acknowledgment], [Acknowledgement])
#set align(center)
#set text(if is-ack { 15pt } else { 15pt },font:"SimHei")
#v(36pt, weak: true)
#if it.numbering != none and not is-ack {
numbering("第1章.", deepest)
h(7pt, weak: true)
}
#it.body
#v(36pt, weak: true)
]
else if it.level == 2 [
#set par(first-line-indent: 0pt)
#set text(size:14pt,font:"SimHei")
#v(24pt, weak: true)
#if it.numbering != none {
numbering("1.1.",..levels)
h(7pt, weak: true)
}
#it.body
#v(24pt, weak: true)
]
else if it.level == 3 [
#set par(first-line-indent: 0pt)
#set text(size:14pt,font:"SimHei")
#v(15pt, weak: true)
#if it.numbering != none {
numbering("1.1.1.",..levels)
h(7pt, weak: true)
}
#it.body
#v(15pt, weak: true)
]
else [
#set par(first-line-indent: 0pt)
#set text(size:12pt,font:"SimHei")
#v(12pt, weak: true)
#if it.numbering != none {
numbering("1.1.1.1.",..levels)
h(7pt, weak: true)
}
#it.body
#v(12pt, weak: true)
]
})
#align(center, text(36pt,font: "STXinwei")[
*本科生毕业设计*
])
#align(center, text(28pt,font: "STXihei")[
*智能手持式激光测距仪*
])
#grid(
columns: (1fr, 2fr),
align(center)[
姓名 \
学号 \
院系 \
专业 \
指导教师 \
],
align(center)[
王恺 \
20201804070
质量技术监督学院 \
测控技术与仪器 \
刘琨 \
]
)
#align(center)[
#set par(justify: false)
= 摘要 \
本课程设计项目设计了一款基于 LS-K-100激光测距模块和 ESP32 的高精度激光测距仪。该测距仪设计用于实现 100 米范围内的 ±2mm 高精度测量,适用于家装测量、工业控制等领域。报告从硬件选型、原理图 PCB 设计、软件编程到结构建模等方面,全面阐述了产品开发流程,并提供了详细的开发步骤和实现细节。通过本课程设计掌握硬件设计与软件编程的基础知识,提升解决实际问题的能力。未来工作可以进一步优化系统性能,如提高测量精度、降低功耗、增加无线通信功能等。
#strong[关键词:] 激光测距;PLS-K-100;ESP32;高精度测量
]
#outline(depth: 4,indent: 2em)
= 前言
在现代工业和日常生活中,精确测量成为了提高工作效率和质量的关键因素。激光测距仪作为一种高精度、非接触式的测量工具,其在建筑测量、室内装修、机械制造等领域的应用日益广泛。随着技术的发展,对激光测距仪的测量精度和操作便捷性提出了更高的要求。
本课程设计旨在开发一款基于 PLS-K-100 激光测距模块和 ESP32 微控制器的高精度激光测距仪。PLS-K-100 以其高精度、快速响应和易于集成的特点,成为本项目的核心元器件。而ESP32作为多功能的微控制器,不仅提供了强大的处理能力,还支持 Wi-Fi 和蓝牙通信,为产品的智能化和网络化提供了可能。
设计目标是实现一款能够在 100 米范围内提供 ±2mm 测量精度的激光测距仪,同时具备用户友好的操作界面和低功耗设计。本项目采用开源硬件和软件平台,以便于快速开发和迭代,同时也便于理解和学习整个设计流程。
通过本课程设计,深入了解硬件电路设计、微控制器编程、以及产品原型制作等关键技术。此外,也将学习到如何将理论知识应用于实际项目中,解决实际问题,培养创新思维和工程实践能力。最终,本项目的成功实施将为学生提供一个完整的电子产品开发经验,为未来的职业生涯打下坚实的基础。
= 设计目标与要求
本课程设计的核心目标是开发一款高精度激光测距仪,以下为项目设计的技术要求和性能指标:
+ *测量范围:* 能够在 100 米范围内进行测量,以适应多种测量场景,包括室内和室外环境。
+ *测量精度:* 测量精度 ±2mm,以确保测量结果的准确性,满足高精度测量的需求。
+ *响应时间:* 具有快速响应能力,测量响应时间再 1 秒左右,以便于用户实时获取测量数据。
+ *电源:* 设备采用单节锂电池供电,以便于携带和使用,同时考虑到电池的续航能力和充电便捷性。
+ *显示:* 配备 OLED 屏幕,用于直观显示测量结果和设备状态,提高用户体验。
+ *操作:* 设备通过实体按键操作功能,包括开关机、测量模式切换、单位选择等,确保用户可以在各种条件下操作实现实现需求。
+ *环境适应性:* 具有良好的环境适应性,能够在 -30℃ 至 +60℃ 的温度范围内正常工作,满足不同气候条件下的使用需求。
+ *安全性:* 符合相关安全标准,确保在使用过程中不会对用户或周围环境造成危害。
+ *易用性:* 设计应简洁明了,易于用户理解和操作,同时考虑设备的便携性和耐用性。
+ *可扩展性:* 设计留有有良好的可扩展性,便于未来根据需要增加新的功能或进行技术升级。
通过实现上述目标,本课程设计旨在提供一个高性能、易用、可靠的激光测距仪解决方案,不仅能够满足当前的测量需求,还具有一定的前瞻性和发展潜力。
= 系统设计
== 硬件设计
=== 硬件设计概述
硬件设计是实现高精度激光测距仪功能的基础,涉及元器件的选择、电路设计、PCB 布局以及外壳设计等多个方面。本节将详细介绍硬件设计的各个环节。
=== 核心元器件选择
核心元器件的选择对整个系统的性能至关重要。本项目的核心元器件为 PLS-K-100 激光测距模块,由它提供高精度的测量数据。
*PLS-K-100 激光测距模块:*
PLS-K-100 是一款高精度、长距离的激光测距模块,它采用了先进的激光测距技术,能够在 100 米范围内提供 ±2mm 的测量精度。该模块具有以下特点:
- *高精度*:测量精度高达 ±2mm,适用于需要精确测量的应用场景。
- *长测量距离*:最大测量距离可达 100 米,适用于室内外各种测量任务。
- *快速响应*:测量速度快,能够在短时间内提供测量结果。
- *串口通信*:通过串口与微控制器通信,便于数据传输和处理。
- *低功耗*:设计考虑了节能,适合长时间使用。
- *易于集成*:模块化设计,方便与其他硬件系统集成。
=== 微控制器选择与编程
微控制器的选择基于其处理能力、通信接口以及对外部库的支持。ESP32因其强大的处理能力、内置Wi-Fi和蓝牙功能,以及对Arduino编程环境的良好支持而被选为 MCU。编程环境采用 Arduino IDE,利用Arduino 框架丰富的库和社区支持简化开发过程。
*ESP32* 是一款功能强大的 MCU 单元,它集成了Wi-Fi、蓝牙和多个串口通信接口,非常适合于物联网(IoT) 应用。以下是 ESP32 的一些关键特性:
- *多核处理器*:具有双核处理器,可以同时处理多个任务,提高系统性能。
- *丰富的通信接口*:支持 Wi-Fi、蓝牙、SPI、I2C、UART 等多种通信协议,便于与其他设备连接。
- *大容量内存*:具有足够的 RAM 和 ROM,可以运行复杂的应用程序以满足项目要求。
- *低功耗模式*:支持多种低功耗模式,适合电池供电的便携设备。
- *开发环境友好*:支持 Arduino 开发框架,有丰富的库和社区支持,易于开发和调试。
选择 PLS-K-100 激光测距模块作为测量核心,是因为其高精度和长距离测量能力,而选择 ESP32 微控制器则是因为它强大的处理能力和丰富的通信接口,能够满足系统对数据处理和用户交互的需求。这两个核心元器件的结合,使得我们的激光测距仪能够实现高精度、快速响应和用户友好的操作体验。
=== 显示模块设计
显示模块采用 OLED 屏幕,优点是低功耗、高对比度和优秀的可编程性。OLED 屏幕通过 I2C 接口与 ESP32 通信,显示测量结果和系统状态。
=== 输入模块设计
输入模块包括一组按键,用于用户操作。按键设计考虑了耐用性以及不同环境和复杂使用场景下的操作便利性,确保用户可以轻松地进行测量、切换模式等操作。
=== 电源管理设计
电源管理模块包括电池、充电芯片和降压芯片。电池选用单节锂电池,以便于携带和更换。TP5100 充电芯片用于电池充电,LP3220 降压芯片则用于将电池电压稳定地降压至 3.3V。
=== 外壳设计
外壳设计暂时采用亚克力板与铜柱螺栓直架固定。提供简单的机械支撑和隔离功能,结构稳固可靠且易于安装,同时能够满足机械和隔离的要求,保护 PCB 板并提供额外支撑。
=== PCB设计
PCB设计是硬件设计的另一个关键环节。设计时需考虑元器件的布局、走线以及散热。PCB布局应合理,以便于焊接和维修。走线应尽量短且避免交叉,以减少干扰。PCB设计还应考虑散热问题,确保设备在长时间工作下不会过热。
=== 焊接与组装
焊接是将PCB上的元器件固定并连接起来的过程。焊接质量直接影响到设备的性能和可靠性。焊接顺序和方法对焊接质量至关重要。组装过程包括将焊接好的PCB装入外壳,安装显示屏和按键,以及连接电池。
=== 测试与调试
硬件组装完成后,需要进行全面的测试和调试,包括电源测试、功能测试、性能测试等,确保设备按照设计要求正常工作。
==== 性能优化
在测试过程中,可能会发现一些性能瓶颈或不足之处。针对这些问题,可以通过优化电路设计、改进焊接工艺或调整软件算法等方式进行性能优化。
=== 结论
硬件设计是一个复杂的过程,需要综合考虑多种因素。通过精心的设计和严谨的测试,可以确保激光测距仪的高性能和可靠性。本节详细介绍了硬件设计的各个环节,为后续的软件设计和系统实现奠定了坚实的基础。
== 软件设计
软件设计是实现激光测距仪功能的关键部分,它涉及到程序的逻辑结构、用户界面(UI)设计以及与硬件的交互。本节将详细介绍软件设计的各个方面。
=== 编程环境与语言
本项目采用 Arduino 编程环境,使用 c++ 语言进行开发。Arduino 是一个开源的电子原型平台,它包含了硬件(各种型号的 Arduino 板)和软件(Arduino IDE)。Arduino IDE 提供了一个易于使用的编程环境,支持 c++ 语言,并且有丰富的库和社区支持。
=== 程序结构
程序的主要结构包括初始化、主循环、按键扫描、数据处理和显示更新等部分。程序在初始化阶段设置硬件引脚、初始化显示屏和串口通信等。主循环中不断检测按键状态,根据按键输入执行相应的操作,如测量距离、切换测量模式、调整单位等。数据处理部分负责解析激光测距仪返回的数据,并计算出距离。显示更新部分则将测量结果和系统状态显示在OLED屏幕上。
=== 功能实现
软件的主要功能包括:
- 单次测量:用户按下测量键,系统发送测量指令,等待激光测距仪返回数据,然后显示测量结果。
- 连续测量:用户进入连续测量模式,系统持续发送测量指令,实时更新显示测量结果。
- 激光开关:用户可以通过按键控制激光的开启和关闭。
- 单位切换:用户可以切换测量单位,如毫米、厘米和米。
- 电池电量检测:系统可以检测电池电量,并在屏幕上显示。
- 蜂鸣器控制:用户可以通过按键控制蜂鸣器的开启和关闭。
=== OLED 显示驱动
使用了 U8g2 库来驱动 OLED 显示屏,以及可能的其他第三方库来处理串口通信、ADC转换等任务。这些库提供了现成的功能,使得开发者可以专注于实现产品的核心功能。
手动写入可能用到的中文字符集,定义文字显示像素。
```cpp
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);//1.30寸oled屏幕参数(SH1106)
//U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);//0.96寸oled屏幕参数(SSD1306)
/*距(0) 离(1) 单(2) 位(3) 切(4) 换(5) 错(6) 误(7)
码(8) 激(9) 光(10) 头(11) 开(12) 关(13) 整(14) 机(15)
硬(16) 件(17) 故(18) 障(19) 无(20) 效(21) 信(22) 号(23)
不(24) 稳(25) 定(26) 太(27) 弱(28) 强(29) 背(30) 景(31)
光(32) 无(33) 效(34) 的(35) 测(36) 量(37) 结(38) 果(39)
目(40) 标(41) 超(42) 出(43) 射(44) 程(45) 电(46) 池(47)
可(48) 信(49) 度(50)
*/
static const unsigned char PROGMEM str0[] = {0x00, 0x00, 0xBE, 0x7F, 0xA2, 0x00, 0xA2, 0x00, 0xA2, 0x00, 0xBE, 0x3F, 0x88, 0x20, 0x88, 0x20, 0xBA, 0x20, 0x8A, 0x20, 0x8A, 0x3F, 0x8A, 0x00, 0xBA, 0x00, 0x87, 0x00, 0x80, 0x7F, 0x00, 0x00}; /*"距",0*/
static const unsigned char PROGMEM str1[] = {0x40, 0x00, 0x80, 0x00, 0xFF, 0x7F, 0x00, 0x00, 0x28, 0x0A, 0xC8, 0x09, 0x28, 0x0A, 0xF8, 0x0F, 0x80, 0x00, 0xFE, 0x3F, 0x42, 0x20, 0x22, 0x22, 0xF2, 0x27, 0x22, 0x24, 0x02, 0x28, 0x02, 0x10}; /*"离",1*/
…
…
static const unsigned char PROGMEM str54[] = {0x00, 0x20, 0x00, 0x70, 0x00, 0xF8, 0x00, 0xA8, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0xFF, 0x21, 0x01, 0x21, 0x7D, 0x01, 0x45, 0x21, 0x45, 0x21, 0x7D, 0x21, 0x01, 0x01, 0x01, 0x21, 0x01, 0x21, 0x01, 0x21, 0x01, 0x21, 0x01, 0x01, 0x01, 0x21, 0x01, 0x21, 0x01, 0x21, 0x01, 0x01, 0x01, 0x21, 0x01, 0x21, 0x01, 0x21, 0x01, 0x01, 0x01, 0x21, 0x01, 0x21, 0x01, 0x21, 0x01, 0x01, 0xFF, 0xF9}; /*"后基准",54*/
static const unsigned char PROGMEM str55[] = {0x00, 0x20, 0x00, 0x70, 0x00, 0xF8, 0x00, 0xA8, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0xFF, 0xF9, 0x01, 0x01, 0x7D, 0x01, 0x45, 0x01, 0x45, 0x01, 0x7D, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xFF, 0x01}; /*"前基准",55*/
```
以上代码定义了一系列的字符串数组,用于在OLED显示屏上显示中文字符。使用`PROGMEM`关键字,将其存储在程序存储器(而非 RAM)中,以节省内存空间和提高程序效率。
通过`str0[]`这样的数组定义了字符,其内容是一个包含多个字节的数组,每个字节代表屏幕上的一个像素行。这些字节的值是通过位操作(如`0x00`、`0x7F`等)来设置的,其中`0x7F`表示该行的所有像素都亮起,而`0x00`表示该行的所有像素都熄灭。
这些字符串数组可以被用来在OLED显示屏上显示用户界面,例如在测量结果旁边显示相关的提示信息,或者在系统状态发生变化时提供反馈。通过这种方式,用户可以直观地了解设备的工作状态和测量结果。
在`u8g2`库的函数中指定位置绘制位图,在OLED屏幕上显示中文字符和图标,增强用户体验。
=== 测距模块驱动
根据激光测距模块规格书,定义与激光测距模块通信的协议。
==== 发送指令到测距模块串口
```cpp
//发送到测距模块串口
void measursend()
{
unsigned char S_A_M[9] = {0xAA, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x21}; //单次自动测量
unsigned char C_A_M[9] = {0xAA, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x04, 0x25}; //连续自动测量
unsigned char O_L[9] = {0xAA, 0x00, 0x01, 0xBE, 0x00, 0x01, 0x00, 0x01, 0xC1}; //打开激光
unsigned char C_L[9] = {0xAA, 0x00, 0x01, 0xBE, 0x00, 0x01, 0x00, 0x00, 0xC0}; //关闭激光
unsigned char EXIT[1] = {0x58}; //退出连续自动测量
switch (MEASUR_STATUS)
{
case MEASUR_OFF:
Serial.println("测量关闭"); break;
case CLOSE_LASER:
Serial2.write(C_L, 9); Serial.println("关闭激光"); MEASUR_STATUS = MEASUR_OFF; break;
case OPEN_LASER:
Serial2.write(O_L, 9); Serial.println("打开激光"); break;
case SINGLE_AUTO_MEASUR:
Serial2.write(S_A_M, 9); Serial.println("单次自动测量"); MEASUR_STATUS = MEASUR_OFF; break;
case CONTINUOUS_AUTO_MEASUR:
Serial2.write(C_A_M, 9); Serial.println("连续自动测量"); break;
case EXIT_MEASUR:
Serial2.write(EXIT, 9); Serial.println("关闭连续自动测量"); MEASUR_STATUS = MEASUR_OFF; break;
default: Serial.println("测量无发送");
}
}
```
定义`measursend()`函数用于发送指令到激光测距仪模块。这个函数根据当前的测量状态(`MEASUR_STATUS`)来决定发送哪种类型的指令。
函数首先定义了四个数组,每个数组代表一种不同的指令:
-`S_A_M`:用于单次自动测量。
-`C_A_M`:用于连续自动测量。
-`O_L`:用于打开激光。
-`C_L`:用于关闭激光。
-`EXIT`:用于退出连续自动测量。
这些数组包含了发送给激光测距仪的命令字节序列,这些字节序列遵循激光测距仪的通信协议。
然后,函数使用`switch`语句根据`MEASUR_STATUS`的值来选择发送哪个数组。`MEASUR_STATUS`是一个枚举类型,定义了激光测距仪的不同操作状态。
对于每种状态,函数执行以下操作:
-`MEASUR_OFF`:打印一条消息到串行监视器,说明测量已关闭,不发送任何指令。
-`CLOSE_LASER`:发送关闭激光的指令,然后重置`MEASUR_STATUS`为`MEASUR_OFF`。
-`OPEN_LASER`:发送打开激光的指令。
-`SINGLE_AUTO_MEASUR`:发送单次自动测量的指令,然后重置`MEASUR_STATUS`为`MEASUR_OFF`。
-`CONTINUOUS_AUTO_MEASUR`:发送连续自动测量的指令。
-`EXIT_MEASUR`:发送退出连续自动测量的指令,然后重置`MEASUR_STATUS`为`MEASUR_OFF`。
在每种情况下,函数都会打印一条消息到串行监视器,说明发送了哪种类型的指令。
==== 将测距模块返回结果保存
```cpp
enum
{
MEASUR_OFF,
CLOSE_LASER,
OPEN_LASER,
SINGLE_AUTO_MEASUR,
CONTINUOUS_AUTO_MEASUR,
EXIT_MEASUR,
} MEASUR_STATUS;
```
`MEASUR_STATUS`作为一个枚举类型(`enum`),定义了激光测距仪测量状态的不同可能值。枚举类型是一种用户定义的数据类型,它允许将整数值与特定的名字关联起来,使得代码更加清晰和易于理解。
这个枚举定义了以下状态:
+`MEASUR_OFF`:表示测量功能关闭,激光测距仪不进行任何测量操作。
+`CLOSE_LASER`:表示关闭激光,即关闭激光测距仪的激光发射器。
+`OPEN_LASER`:表示打开激光,即启动激光测距仪的激光发射器。
+`SINGLE_AUTO_MEASUR`:表示进行单次自动测量,即用户发起一次测量请求,设备自动进行测量并返回结果。
+`CONTINUOUS_AUTO_MEASUR`:表示进入连续自动测量模式,设备会持续进行测量并实时返回结果。
+`EXIT_MEASUR`:表示退出连续自动测量模式,设备停止连续测量。
使用枚举类型使得代码更加直观,便于维护和调试。当需要更改某个状态的值之时,只需在枚举定义中进行修改,而不需要在代码的其他部分进行查找和替换。此外,枚举类型为状态值提供了一个明确的范围,防止了意外地使用非法的值,也有助于减少错误。
=== 蜂鸣器
在按照顺序执行法时,让蜂鸣器 IO 变高,延迟 200ms,然后变低,导致 CPU 都被蜂鸣器时间占用。避免这种情况,使用 millis 函数检测按键时间,按键时间大于 200ms ,启动蜂鸣器。
```cpp
//蜂鸣器开
void buzzeron200ms()
{
if (BUZZER_STATUS == BUZZER_ON)
{
digitalWrite(Buzzer, HIGH);
buzzerstarttime = millis();//蜂鸣器开始计时
}
if (BUZZER_STATUS == BUZZER_OFF)
{
digitalWrite(Buzzer, LOW);
}
}
//蜂鸣器复位
void buzzerreset()
{
buzzerendtime = millis();
if (buzzerendtime < (buzzerstarttime + Time_200ms_setting))//蜂鸣器结束计时<按下计时+200ms
{
digitalWrite(Buzzer, LOW);//关闭蜂鸣器
}
}
```
=== 单位转换
定义`unitmanage()`函数实现了激光测距仪的单位转换功能。这个功能允许用户通过按下一个特定的按键(`UnitButton`定义的串口所连按键)来在毫米(mm)、厘米(cm)和米(m)之间切换测量单位。
```cpp
//单位切换
void unitmanage()
{
if (UnitKeyState == 1 && Unitkeyflag == 0)
{
delay(10);
if (UnitKeyState == 1 && UNIT_STATUS == UNIT_MM)//MM CM M切换
{
UNIT_STATUS = UNIT_CM;
}
else if (UnitKeyState == 1 && UNIT_STATUS == UNIT_CM)
{
UNIT_STATUS = UNIT_M;
}
else if (UnitKeyState == 1 && UNIT_STATUS == UNIT_M)
{
UNIT_STATUS = UNIT_MM;
}
Unitkeyflag = 1;
buzzeron200ms();
}
else if (UnitKeyState == 0)
{
delay(10);
if (UnitKeyState == 0)
{
Unitkeyflag = 0;
}
}
}
```
函数首先检查`UnitKeyState`是否为1,这表示单位转换按钮被按下。同时,它还检查`Unitkeyflag`是否为0,以确保这个操作不是重复的。如果这两个条件都满足,那么程序会进入一个`if-else`结构,根据当前的`UNIT_STATUS`值来决定新的单位。
- 如果当前单位是毫米(`UNIT_STATUS == UNIT_MM`),则新的单位设置为厘米(`UNIT_STATUS = UNIT_CM`)。
- 如果当前单位是厘米(`UNIT_STATUS == UNIT_CM`),则新的单位设置为米(`UNIT_STATUS = UNIT_M`)。
- 如果当前单位是米(`UNIT_STATUS == UNIT_M`),则新的单位设置为毫米(`UNIT_STATUS = UNIT_MM`)。
每次单位改变后,`Unitkeyflag`被设置为1,这表示单位已经改变,直到下一次按键操作。如果在单位改变后`UnitKeyState`变为0,`Unitkeyflag`也会被重置为0,以准备下一次的单位切换操作。
函数调用`buzzeron200ms()`来激活蜂鸣器200毫秒,为用户提供操作反馈,发出声音,让用户知道单位已经成功切换。
=== 基准切换
```cpp
//基准开关
void basemanage()
{
if (BaseKeyState == 1 && Basekeyflag == 0)
{
delay(10);
if (BaseKeyState == 1 && BASE_STATUS == BASE_FRONT)//基准切换
{
BASE_STATUS = BASE_BACK;
}
else if (BaseKeyState == 1 && BASE_STATUS == BASE_BACK)
{
BASE_STATUS = BASE_FRONT;
}
Basekeyflag = 1;
buzzeron200ms();
}
else if (BaseKeyState == 0)
{
delay(10);
if (BaseKeyState == 0)
{
Basekeyflag = 0;
}
}
}
```
`basemanage()`函数用于处理基准切换的按键操作,基准切换按钮的状态,并根据当前的基准状态来切换基准位置。
函数首先检查`BaseKeyState`是否为1,这表示基准切换按钮被按下。同时,它还检查`Basekeyflag`是否为0,以确保这个操作不是重复的。如果这两个条件都满足,那么程序会进入一个`if-else`结构,根据当前的`BASE_STATUS`值来决定新的基准状态。
- 如果当前基准状态是`BASE_FRONT`(基准在前),则新的基准状态设置为`BASE_BACK`(基准在后)。
- 如果当前基准状态是`BASE_BACK`(基准在后),则新的基准状态设置为`BASE_FRONT`(基准在前)。
每次基准状态改变后,`Basekeyflag`被设置为1,这表示基准已经改变,直到下一次按键操作。如果在基准状态改变后`BaseKeyState`变为0,`Basekeyflag`也会被重置为0,以准备下一次的基准切换操作。
=== 错误处理
当程序执行错误时,提示错误码,帮助用户在使用时排除错误。
```cpp
{
Serial.println("错误码校验和相等,错误码有效");
switch (Distance_raw[7])
{
case 0x00: Serial.println("错误码00:无错误"); errorcode = 1; break;
case 0x01: Serial.println("错误码01:输入功率过低,功率电压应>= 2.2V"); errorcode = 2; break;
case 0x02: Serial.println("错误码02:内在错误,没关系"); errorcode = 3; break;
case 0x03: Serial.println("错误码03:模块温度过低(< -20℃)"); errorcode = 4; break;
case 0x04: Serial.println("错误码04:模块温度过高(> + 40℃)"); errorcode = 5; break;
case 0x05: Serial.println("错误码05:目标超出射程"); errorcode = 6; break;
case 0x06: Serial.println("错误码06:无效的测量结果"); errorcode = 7; break;
case 0x07: Serial.println("错误码07:背景光太强"); errorcode = 8; break;
case 0x08: Serial.println("错误码08:激光信号太弱"); errorcode = 9; break;
case 0x09: Serial.println("错误码09:激光信号太强"); errorcode = 10; break;
case 0x0A: Serial.println("错误码0A:硬件故障1"); errorcode = 11; break;
case 0x0B: Serial.println("错误码0B:硬件故障2"); errorcode = 12; break;
case 0x0C: Serial.println("错误码0C:硬件故障3"); errorcode = 13; break;
case 0x0D: Serial.println("错误码0D:硬件故障4"); errorcode = 14; break;
case 0x0E: Serial.println("错误码0E:硬件故障5"); errorcode = 15; break;
case 0x0F: Serial.println("错误码0F:激光信号不稳定"); errorcode = 16; break;
case 0x10: Serial.println("错误码10:硬件故障6"); errorcode = 17; break;
case 0x11: Serial.println("错误码11:硬件故障7"); errorcode = 18; break;
case 0x81: Serial.println("错误码81:无效"); errorcode = 19; break;
default: Serial.println("错误码未知");
}
}
```
由于项目时间限制,错误码验证与输出部分未完成,留待后续完善。
=== 结论
软件设计是实现激光测距仪功能的关键部分。通过合理的程序结构、直观的用户界面和完善的功能实现,可以确保产品具有良好的用户体验和稳定的性能。同时,通过性能优化和错误处理,可以提高程序的可靠性和健壮性。
= 系统实现
== 硬件搭建与测试
- 使用杜邦线和面包板搭建初步硬件平台,进行功能验证和调试,确保电路设计的正确性。
- PCB 设计和焊接,确保电路连接正确无误,并通过焊接质量检查。
硬件搭建是将设计转化为实际可工作的系统的过程。这一部分将详细描述硬件搭建的步骤、测试方法以及可能出现的问题和解决方案。
=== 搭建步骤
+ *元器件准备*:根据BOM清单准备所有所需的元器件,包括PLS-K-100 激光测距模块、ESP32 微控制器、OLED显示屏、按键、电源管理芯片等。
+ *PCB焊接*:将元器件焊接到 PCB 板上。首先焊接较为复杂的部件,如 QFN 封装的 TP5100 芯片,然后是其他贴片元件,最后焊接插件元件。
+ *电源管理*:确保电源管理电路正确连接,包括锂电池、充电芯片TP5100、降压芯片LP3220等,以确保系统稳定供电。
+ *显示屏连接*:将 OLED 显示屏通过 I2C 接口连接到 ESP32 ,确保显示模块正确安装并固定。
+ *按键安装*:安装按键,确保按键与 PCB 板上的焊盘正确连接,并且按键操作灵活。
+ *激光测距模块连接*:将 PLS-K-100 激光测距模块通过串口连接到ESP32。
+ *组装外壳*:将焊接好的 PCB 板安装到 3D 打印的外壳中,确保所有连接线和接口都正确无误。
+ *初步测试*:在组装完成后,进行初步的电源测试,确保电源供应正常,无短路现象。
=== 测试方法
+ *电源测试*:使用万用表检查电源输出是否符合预期,确保电源管理电路工作正常。
+ *串口通信测试*:使用串口通信工具检查 ESP32 与激光测距模块之间的通信是否正常。
+ *按键功能测试*:通过按下各个按键,观察系统的反应,确保按键功能正确。
+ *显示屏测试*:检查 OLED 显示屏是否能够正常显示,包括文字、图标等。
+ *激光测距测试*:进行实际的测距操作,验证测量结果的准确性和稳定性。
+ *系统功能测试*:测试所有系统功能,包括单次测量、连续测量、激光开关控制、单位切换等。
=== 问题与解决方案
在搭建过程中可能会遇到以下问题:
- *焊接问题*:如果焊接不良,可能导致电路短路或断路。解决方案是通过视觉检查和使用万用表进行检测,必要时重新焊接。
- *连接问题*:电路连接错误可能导致系统无法正常工作。解决方案是仔细检查原理图和PCB布局,确保所有连接正确无误。
- *电源问题*:电源供应不稳定可能导致系统工作异常。解决方案是检查电源管理电路,确保电池和充电电路工作正常。
- *通信问题*:串口通信故障可能导致数据传输错误。解决方案是检查通信线路和通信协议设置。
- *测量精度问题*:如果测量结果不准确,可能是激光测距模块或软件算法的问题。解决方案是检查激光测距模块的设置和软件中的测量算法。
=== 结论
硬件搭建与测试是确保系统能够正常工作的重要步骤。通过细致的搭建和全面的测试,可以发现并解决潜在的问题,确保激光测距仪的性能和可靠性。
== 软件编程与调试
- 编写控制程序,实现与激光测距仪的通信,确保数据的准确传输。
- 实现按键扫描和处理逻辑,确保用户操作的准确性和系统的响应速度。
- 测试软件功能,确保测量结果的准确性和系统的稳定性,通过多次测试优化软件性能。
=== 编程环境配置
首先,需要配置Arduino开发环境。这包括安装 Arduino IDE,以及可能需要的其他插件,如 U8g2 库的安装,用于驱动 OLED 显示屏。确保所有必要的库和工具都已正确安装并配置。
=== 程序框架构建
在 Arduino IDE 中创建一个新的项目,定义所需的全局变量和常量,如 GPIO引脚定义、激光测距仪的串口通信参数等。然后,编写初始化函数,用于设置硬件引脚和初始化串口通信。
=== 功能模块编写
根据系统设计,编写各个功能模块的代码。这包括:
- *按键扫描*:编写函数来检测按键状态,并根据按键输入执行相应的操作。
- *激光测距仪通信*:编写发送指令和接收数据的函数,处理与激光测距仪的通信。
- *数据处理*:编写函数来解析激光测距仪返回的数据,并计算出距离。
- *用户界面更新*:编写代码来更新 OLED 显示屏上的显示内容。
- *电源管理*:编写代码来监控电池电量,并在电量低时发出警告。
- *错误处理*:实现错误检测和处理机制,确保系统在遇到问题时能够给出提示。
=== 程序调试
在编写代码的过程中,需要不断地进行调试。这包括:
- *语法检查*:确保代码没有语法错误,可以通过 IDE 的编译功能进行检查。
- *功能测试*:对每个功能模块单独进行测试,确保它们按预期工作。
- *整体测试*:将所有功能模块整合在一起,进行整体测试,确保系统功能完整。
- *性能优化*:对程序进行优化,提高运行效率,减少资源占用。
=== 错误处理与日志记录
在程序中实现错误处理机制,当发生错误时,能够记录错误信息,并在 OLED 显示屏上显示。同时,可以通过串口输出错误日志,便于开发者分析问题。
=== 程序优化
在确保程序功能完整且无明显错误后,对程序进行优化。这可能包括代码重构、减少不必要的计算、优化内存使用等。
=== 结论
软件编程与调试是确保激光测距仪能够正确运行的关键步骤。通过构建清晰的程序框架、编写功能模块、进行细致的调试和优化,可以确保软件的稳定性和可靠性。此外,良好的错误处理和日志记录机制有助于快速定位和解决潜在问题。
= 结论与展望
本课程设计实现了一款基于 PLS-K-100 激光测距模块和 ESP32 微控制器的高精度激光测距仪。通过详细的硬件设计、软件编程与调试,以及严格的测试流程确保产品的性能和可靠性。系统能够满足 100 米范围内的 ±2mm 高精度测量需求,具有良好的用户界面和低功耗设计,且能够在多种环境下稳定工作。
项目设计在达到预期设计目标的基础上,仍有进一步改进和扩展的空间。以下是一些可能的未来工作方向:
+ *无线通信功能*:增加 Wi-Fi 或蓝牙通信功能,使测距仪能够与智能手机或平板电脑连接,实现远程控制和数据传输。
+ *数据处理与存储*:集成数据存储功能,允许用户记录测量数据,并在需要时进行回溯分析。
+ *增强现实(AR)集成*:结合 AR 技术,通过智能手机或平板电脑的摄像头,将测量结果实时叠加到现实环境中,提高用户体验。
+ *多语言支持*:扩展用户界面,支持多种语言,以适应不同地区用户的需求。
+ *环境适应性增强*:进一步优化设备的设计,提高其在极端温度和湿度条件下的稳定性。
+ *智能算法优化*:利用机器学习算法对测量数据进行处理,提高测量精度和可靠性。
+ *商业化与市场推广*:将产品推向市场,为建筑、装修、工业测量等领域提供更高效、便捷的测量工具。
通过这些改进和扩展,我们希望这款激光测距仪将能够更好地满足市场需求,为用户提供更加完善的测量解决方案。
= 参考文献
[1] 激光测距模块 PLS-K-100 产品手册
[2] ESP32 开发文档
[3] Arduino 开发环境指南
[4] 电源管理芯片TP5100和LP3220的数据手册
== 附录
- 硬件原理图
- PCB布局图
- 软件源代码
|
|
https://github.com/lucifer1004/leetcode.typ | https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0007.typ | typst | #import "../helpers.typ": *
#let reverse-integer-ref(x) = {
let ans = 0
let sign = if x >= 0 { 0 } else { -1 }
if x == -2147483648 {
return 0
}
x = calc.abs(x)
while x != 0 {
let pop = calc.rem(x, 10)
x = calc.floor(x / 10)
if ans > 214748364 or (ans == 214748364 and pop - sign > 7) {
return 0
}
ans = ans * 10 + pop
}
ans * (2 * sign + 1)
}
|
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/保研/PPT(16-9)/university.typ | typst | #import "@preview/touying:0.4.0": *
#let data=yaml("./example.yml")
// University theme
// Originally contributed by <NAME> - https://github.com/drupol
#import "@preview/showybox:2.0.1": showybox
// #let colors_=()
#let slide(
self: none,
title: auto,
subtitle: auto,
header: auto,
footer: auto,
now_light:auto,
display-current-section: auto,
..args,
) = {
if title != auto {
self.uni-title = title
}
if subtitle != auto {
self.uni-subtitle = subtitle
}
if header != auto {
self.uni-header = header
}
if footer != auto {
self.uni-footer = footer
}
// if now_light != auto {
self.uni-now_light = now_light
// }
if display-current-section != auto {
self.uni-display-current-section = display-current-section
}
(self.methods.touying-slide)(
..args.named(),
self: self,
setting: body => {
show: args.named().at("setting", default: body => body)
body
},
..args.pos(),
)
}
#let title-slide(self: none, ..args) = {
self = utils.empty-page(self)
let info = self.info + args.named()
info.authors = {
let authors = if "authors" in info { info.authors } else { info.author }
if type(authors) == array { authors } else { (authors,) }
}
let content = {
if info.logo != none {
align(right, info.logo)
}
// place(top+left,dy:-0em,dx:2.6em,image("icon/SINTEF_Logo_Sentrert_RGB.jpg",width: 3.4em))
place(bottom+left,dy:-0em,dx:0.6em,image("icon/校标.png",width: 12em))
place(bottom+right,dy:-0em,dx:-0em,image("icon/background.png",width:18em))
v(2em)
place(center + horizon, dx:0em,{
block(
inset: 0em,
breakable: false,
{
v(-5.9em)
text(size: 2.1em, fill: self.colors.primary, strong(info.title))
if info.subtitle != none {
v(-1.1em)
parbreak()
text(size: 1.2em, fill: self.colors.primary, strong(info.subtitle))
}
}
)
// set text(size: .9em)
// grid(
// columns: (1fr,) * calc.min(info.authors.len(), 3),
// column-gutter: 1em,
// row-gutter: 1em,
// ..info.authors.map(author => text(fill: black, author))
// )
// v(1em)
// if info.institution != none {
// parbreak()
// text(size: .9em, info.institution)
// }
// if info.date != none {
// parbreak()
// text(size: .8em, utils.info-date(self))
// }
v(1em)
place(center,dy:1em,[
#showybox(
width:30%,
frame: (
border-color: rgb("#19448e").darken(80%),
title-color:rgb("#19448e").lighten(90%),
// body-color: rgb("#19448e").lighten(80%)
dash: "dashed",
// border-color: rgb("#19448e").darken(80%),
// title-color:rgb("#19448e").lighten(90%),
// // body-color: rgb("#19448e").lighten(80%)
// dash: "dashed",
),
title-style: (
color: black,
weight: "regular",
align: center
),
shadow: (
offset: 3pt,
),
title: [
#text(size: 0.8em, strong("汇报人: "+ data.标题页.姓名))
]
,[
#align(center,
[
#text(size: 0.8em, strong("汇报时间: "+ utils.info-date(self)))
// #h(2em)
// #text( "学校专业:"+info.institution)
])
],
)
])
// block(
// box[汇报人:古翱翔]
})
}
(self.methods.touying-slide)(self: self, repeat: none, content)
}
#let new-section-slide(self: none, short-title: auto, title) = {
self = utils.empty-page(self)
let content(self) = {
set align(horizon)
show: pad.with(20%)
set text(size: 1.5em, fill: self.colors.primary, weight: "bold")
states.current-section-with-numbering(self)
v(-.5em)
block(height: 2pt, width: 100%, spacing: 0pt, utils.call-or-display(self, self.uni-progress-bar))
}
(self.methods.touying-slide)(self: self, repeat: none, section: (title: title, short-title: short-title), content)
}
#let focus-slide(self: none, background-color: none, background-img: none, body) = {
let background-color = if background-img == none and background-color == none {
rgb(self.colors.primary)
} else {
background-color
}
self = utils.empty-page(self)
self.page-args += (
fill: self.colors.primary-dark,
margin: 1em,
..(if background-color != none { (fill: background-color) }),
..(if background-img != none { (background: {
set image(fit: "stretch", width: 100%, height: 100%)
background-img
})
}),
)
set text(fill: white, weight: "bold", size: 2em)
(self.methods.touying-slide)(self: self, repeat: none, align(horizon, body))
}
#let matrix-slide(self: none, columns: none, rows: none, ..bodies) = {
self = utils.empty-page(self)
(self.methods.touying-slide)(self: self, composer: (..bodies) => {
let bodies = bodies.pos()
let columns = if type(columns) == int {
(1fr,) * columns
} else if columns == none {
(1fr,) * bodies.len()
} else {
columns
}
let num-cols = columns.len()
let rows = if type(rows) == int {
(1fr,) * rows
} else if rows == none {
let quotient = calc.quo(bodies.len(), num-cols)
let correction = if calc.rem(bodies.len(), num-cols) == 0 { 0 } else { 1 }
(1fr,) * (quotient + correction)
} else {
rows
}
let num-rows = rows.len()
if num-rows * num-cols < bodies.len() {
panic("number of rows (" + str(num-rows) + ") * number of columns (" + str(num-cols) + ") must at least be number of content arguments (" + str(bodies.len()) + ")")
}
let cart-idx(i) = (calc.quo(i, num-cols), calc.rem(i, num-cols))
let color-body(idx-body) = {
let (idx, body) = idx-body
let (row, col) = cart-idx(idx)
let color = if calc.even(row + col) { white } else { silver }
set align(center + horizon)
rect(inset: .5em, width: 100%, height: 100%, fill: color, body)
}
let content = grid(
columns: columns, rows: rows,
gutter: 0pt,
..bodies.enumerate().map(color-body)
)
content
}, ..bodies)
}
#let slides(self: none, title-slide: true, slide-level: 1, ..args) = {
if title-slide {
(self.methods.title-slide)(self: self)
}
(self.methods.touying-slides)(self: self, slide-level: slide-level, ..args)
}
#let register(
self: themes.default.register(),
// nowlight:now_light,
aspect-ratio: "16-9",
progress-bar: true,
display-current-section: true,
footer-columns: (15%, 15%,15%,15%,15%,10%, 8%),
footer-a: "01基本信息",
footer-b: "02获得荣誉",
footer-d: "03竞赛获奖",
footer-e: "04项目经历",
footer-f: "05其他荣誉",
footer-g: "06规划",
footer-c: self => {
states.slide-counter.display() + " / " + states.last-slide-number
h(1fr)
},
) = {
// color theme
self = (self.methods.colors)(
self: self,
primary: rgb("#19448e"),
secondary: rgb("#165e83"),
tertiary: rgb("#507ea4"),
)
// save the variables for later use
self.uni-enable-progress-bar = progress-bar
self.uni-progress-bar = self => states.touying-progress(ratio => {
grid(
columns: (ratio * 100%, 1fr),
rows: 2pt,
components.cell(fill: self.colors.primary),
components.cell(fill: self.colors.tertiary)
)
})
self.uni-display-current-section = display-current-section
self.uni-title = none
self.uni-subtitle = none
// self.now_light=now_light;
self.uni-footer = (self) => {
let cell(fill: none, it) = rect(
width: 100%, height: 100%, inset: 1mm, outset: 0mm, fill: fill, stroke: none,
align(horizon, text(fill: white, it))
)
show: block.with(width: 100%, height: auto, fill: self.colors.secondary)
{
// 划分颜色数组
}
let colors_=()
// if(self)
let num11 = states.slide-counter;
// content to num;
// if num11==3 {
// now_light=1;
// }
// if num11==5 or num11==6 {
// now_light=1;
// }
self.now_light=1
for value in (0,1,2,3,4,5) {
if(value==0 or value==2 or value==4){
colors_.push(self.colors.secondary)
}
if(value==1 or value==3 or value==5){
colors_.push(self.colors.primary)
}
}
grid(
columns: footer-columns,
rows: (1.5em, auto),
cell(fill: colors_.at(0), utils.call-or-display(self,footer-a)),
// cell(fill: self.colors.primary, utils.call-or-display(self, footer-a)),
cell(fill: colors_.at(1), utils.call-or-display(self, footer-b)),
cell(fill: colors_.at(2), utils.call-or-display(self, footer-d)),
cell(fill: colors_.at(3), utils.call-or-display(self, footer-e)),
cell(fill: colors_.at(4), utils.call-or-display(self, footer-f)),
cell(fill: colors_.at(5), utils.call-or-display(self, footer-g)),
cell(fill: self.colors.secondary, utils.call-or-display(self, footer-c)),
)
}
self.uni-header = self => {
if self.uni-title != none {
block(inset: (x: .5em),
grid(
columns: 1,
gutter: .3em,
grid(
columns: (auto, 1fr, auto),
align(top + left, text(fill: self.colors.primary, weight: "bold", size: 1.2em, self.uni-title)),
[],
if self.uni-display-current-section {
align(top + right, text(fill: self.colors.primary.lighten(65%), states.current-section-with-numbering(self)))
}
),
text(fill: self.colors.primary.lighten(65%), size: .8em, self.uni-subtitle)
)
)
}
}
// set page
let header(self) = {
set align(top)
place(bottom+left,dx: 0em,dy: -0.4em,[
#showybox(
width:100%,
frame: (
border-color: self.colors.primary.darken(50%),
title-color: self.colors.primary.lighten(60%),
body-color: self.colors.primary.lighten(-0%)
),
[
#text(size: 1.1em, fill: white)[#strong([#self.uni-header])]
]
// [#text(font: "Microsoft YaHei",fill:white)[做最NB]]
)
])
place(bottom+right,dy:-0.5em,dx:-0.3em,image("icon/school_logo.png",width: 8em))
// grid(
// rows: (auto, auto),
// row-gutter: 5mm,
// if self.uni-enable-progress-bar {
// utils.call-or-display(self, self.uni-progress-bar)
// },
// utils.call-or-display(self, self.uni-header),
// )
}
let footer(self) = {
set text(size: .7em)
set align(center + bottom)
utils.call-or-display(self, self.uni-footer)
}
self.page-args += (
paper: "presentation-" + aspect-ratio,
header: header,
footer: footer,
header-ascent: 0em,
footer-descent: 0em,
margin: (top: 2.5em, bottom: 1.25em, x: 2em),
)
// register methods
self.methods.slide = slide
self.methods.title-slide = title-slide
self.methods.new-section-slide = new-section-slide
self.methods.touying-new-section-slide = new-section-slide
self.methods.focus-slide = focus-slide
self.methods.matrix-slide = matrix-slide
self.methods.slides = slides
self.methods.touying-outline = (self: none, enum-args: (:), ..args) => {
states.touying-outline(self: self, enum-args: (tight: false,) + enum-args, ..args)
}
self.methods.alert = (self: none, it) => text(fill: self.colors.primary, it)
self.methods.init = (self: none, body) => {
set text(size: 25pt,font:("Times New Roman"))
set text(font:"Source Han Serif")
show footnote.entry: set text(size: .6em)
body
}
self
}
#let basic_info(left_,right_)={
let size_=0.8em;
text(size: size_, fill: rgb("#19448e"), weight: "bold",font:("Times New Roman","Source Han Serif"), left_+": ")
text(size: size_, font:("Times New Roman","Source Han Serif"),fill: black, right_)
v(-0.5em)
}
#let big_small(big_,small_,big_size,small_size)={
align(center,[
#text(size: big_size, fill: rgb("#19448e"), weight: "bold", big_)
#v(-0.7em)
#text(size: small_size, fill: rgb("#19448e"), weight: "bold", small_)
])
}
#let big_small1(big_,small_,big_size,small_size)={
align(left,[
#text(size: big_size, fill: rgb("#19448e"), weight: "bold", big_)
#v(-0.7em)
#text(size: small_size, weight: "bold", small_)
])
}
#let 荣誉表_名称(荣誉名称,荣誉介绍)={
// box
showybox(
width:90%,
frame: (
border-color: rgb("#19448e").darken(80%),
title-color:rgb("#19448e").lighten(90%),
// body-color: rgb("#19448e").lighten(80%)
dash: "dashed",
),
title-style: (
color: black,
weight: "regular",
align: center,
boxed-style: (
anchor: (
x: center,
y: horizon
),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt),
)
),
shadow: (
offset: 3pt,
),
title: [
// #text(size: 0.8em, strong(荣誉名称))
#text(size: 0.8em, fill: rgb("#19448e"), weight: "bold", 荣誉名称)
]
,[
#align(center,
[
#text(size: 0.6em, strong(荣誉介绍))
// #h(2em)
// #text( "学校专业:"+info.institution)
])
],
)
}
// 图片+两段文字
#let 竞赛获奖(文字1,文字2,图片,size_,percent)={
showybox(
width:percent,
frame: (
border-color: rgb("#19448e").darken(80%),
title-color:rgb("#19448e").lighten(90%),
// body-color: rgb("#19448e").lighten(80%)
dash: "dashed",
// border-color: rgb("#19448e").darken(80%),
// title-color:rgb("#19448e").lighten(90%),
// // body-color: rgb("#19448e").lighten(80%)
// dash: "dashed",
),
title-style: (
color: black,
weight: "regular",
align: center
),
shadow: (
offset: 3pt,
),
title: [
// #text(size: 0.8em, strong("汇报人: "+ data.标题页.姓名))
// #text(size: 0.8em, fill: rgb("#19448e"), weight: "bold", "第十八届挑战杯特等奖")
#文字2
]
,[
#align(center,
[
#image(图片,width: size_)
// #text(size: 0.8em, strong("汇报时间: "+ utils.info-date(self)))
// #h(2em)
// #text( "学校专业:"+info.institution)
])
],
)
// v(-0.5em)
}
#let 专利_两个图片(文字1,文字2,图片1,图片2,图片间距,size_,percent)={
showybox(
width:percent,
frame: (
border-color: rgb("#19448e").darken(80%),
title-color:rgb("#19448e").lighten(90%),
// body-color: rgb("#19448e").lighten(80%)
dash: "dashed",
// border-color: rgb("#19448e").darken(80%),
// title-color:rgb("#19448e").lighten(90%),
// // body-color: rgb("#19448e").lighten(80%)
// dash: "dashed",
),
title-style: (
color: black,
weight: "regular",
align: center
),
shadow: (
offset: 3pt,
),
title: [
// #text(size: 0.8em, strong("汇报人: "+ data.标题页.姓名))
// #text(size: 0.8em, fill: rgb("#19448e"), weight: "bold", "第十八届挑战杯特等奖")
#文字2
]
,[
#align(center, grid(
columns: (auto,auto),
rows: (auto),
gutter: 3pt,
[#image(图片1,width: size_)],[#image(图片2,width: size_)]))
// #align(center,
// [
// #image(图片1,width: size_) #image(图片2,width: size_)
// // #text(size: 0.8em, strong("汇报时间: "+ utils.info-date(self)))
// // #h(2em)
// // #text( "学校专业:"+info.institution)
// ])
],
)
// v(-0.5em)
}
#let 分类(标题文字,list_,percent,bool)={
let data_=[];
let box_bssic(data1)=[
#showybox(
// height: 0.5em,
frame: (
border-color: rgb("#19448e").darken(80%),
title-color:rgb("#19448e").lighten(90%),
// body-color: rgb("#19448e").lighten(80%)
dash: "dashed",
),
title-style: (
color: black,
weight: "regular",
align: center
),
shadow: (
offset: 3pt,
),
[
// #v(-0.3em)
// #align(center,data1)
#align(center,[
#text(size: 0.6em, strong(data1))
])
]
)
#v(-0.6em)
]
for x in list_{
if(bool==1){
data_+=box_bssic(x);
}
}
if(bool==0) {
data_+=box_bssic(list_);
}
data_+=v(0.8em);
showybox(
width:percent,
frame: (
border-color: rgb("#19448e").darken(0%),
title-color:rgb("#19448e").darken(0%),
body-color: rgb("#19448e").lighten(100%),
dash: "dashed",
),
title-style: (
// color: black,
weight: "regular",
align: center,
boxed-style: (:),
// background:
// title-style: (),
),
shadow: (
offset: 3pt,
),
title: [
#text(size: 0.8em, strong(标题文字))
]
,[
#align(center,
[
#data_
])
],
)
// v(-0.5em)
} |
|
https://github.com/Ciolv/typst-template-bachelor-thesis | https://raw.githubusercontent.com/Ciolv/typst-template-bachelor-thesis/main/main.typ | typst | #import "acronyms.typ": ac,acl,acs,acsp,acp,aclp,acronyms // allows LaTeX "acro" like acronym management with only basic features
#import "helper.typ": page_ref
#import "config.typ": conf
#show: doc => conf(
title: "GIVE IT A NICE TITLE",
authors: (
(
name: "<NAME>",
company: "Example Company",
matriculation_number: "1234567",
department: "Example Department",
course: "Example course",
course_administrator: "Course Administrator",
scientific_advisor: "Scientific Advisor",
company_advisor: "Company Advisor",
period: "Editing period",
submission_date: "Submission date",
),
),
university: "Junivercity",
abstract: [#lorem(150)],
language: "en",
font: "Manrope",
outlines: (
("List of figures", image),
("List of tables", image),
("List of listings", raw)
),
acronym_outline_name: "List of abbreviations",
thesis_type: "Bachelor Thesis",
course_of_studies: "Course of studies - WOW",
field_of_studies: "Field of studies - Interesting",
company_logo: (path: "Company-logo.png", alternative_text: "Company Logo"),
university_logo: (path:"University-logo.png", alternative_text: "University Logo"),
declaration_on_honour: true,
bibliography-file: "references.yml",
bibliography-style: "ieee",
doc,
)
= This is a chapter headline
For real information, see @chap:useful-guides[chapter] on page #page_ref(<chap:useful-guides>). \
== Let's create a section
#lorem(12)
=== And a subsection
#lorem(80)
=== Yet another subsection
#lorem(10)
== How about another section
#lorem(10)
==== Now we are going really deep
#lorem(80)
#include "chapter.typ"
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.1.1/src/types/dictionary.typ | typst | Apache License 2.0 | #import "../base-type.typ": base-type, assert-base-type-dictionary
#import "../ctx.typ": z-ctx
/// Valkyrie schema generator for dictionary types
///
/// - ..args (schema): Variadic named arguments, the values for which are schema types. *MUST* not
/// contain positional arguments.
/// -> schema
#let dictionary(
..args
) = {
// Does not accept positional arguments
assert(args.pos().len() == 0, message: "Dictionary only accepts named arguments")
args = args.named()
assert-base-type-dictionary(args)
base-type() + (
name: "dictionary",
dictionary-schema: args,
validate: (self, dict, ctx: z-ctx(), scope: ("arguments",) ) => {
// assert type
if not (self.assert-type)(self, dict, scope: scope, ctx: ctx, types: (type((:)),)) {
return none
}
// If strict mode, ensure dictionary exactly matches schema
if ctx.strict {
for (key, value) in self.dictionary-schema {
if ( key not in dict ){
(self.fail-validation)(self, dict, ctx: ctx, scope: (..scope, key), message: "Missing expected dictionary entry")
}
}
}
// Check elements
for (key, schema) in self.dictionary-schema{
dict.at(key) = (schema.validate)(schema, dict.at(key), ctx: ctx, scope: (..scope, str(key)))
}
dict
}
)
}
|
https://github.com/Hobr/njust_thesis_typst_template | https://raw.githubusercontent.com/Hobr/njust_thesis_typst_template/main/template/chapter/2.typ | typst | MIT License | // 第二章
= 背景
学校学科门类齐全,办学特色鲜明。现有机械工程学院、化学与化工学院、电子工程与光电技术学院、计算机科学与工程学院(人工智能学院)、经济管理学院、能源与动力工程学院、自动化学院、物理学院、外国语学院、公共事务学院、马克思主义学院、材料科学与工程学院/格莱特研究院、环境与生物工程学院、设计艺术与传媒学院、知识产权学院、网络空间安全学院、智能制造学院、新能源学院、数学与统计学院、微电子学院(集成电路学院)、安全科学与工程学院(应急管理学院)等21个专业学院,以及钱学森学院、中法工程师学院、国际教育学院、创新创业教育学院、继续教育学院,并与合作方联合创办了南京理工大学紫金学院和南京理工大学泰州科技学院2个独立学院。学校在长期发展过程中形成了兵器与装备、信息与控制、化工与材料三大优势学科群,工程学、材料科学、化学、计算机科学、环境与生态学、物理学、数学、一般社会科学、生物与生物化学、地球科学10个学科进入ESI国际学科领域全球排名前1%,其中,工程学、材料科学、化学进入前1‰。现有国家重点学科9个,江苏省优势学科10个,江苏省重点学科12个,工信部重点学科7个,国防特色学科10个;国家级一流本科专业建设点38个,教育部卓越工程师教育培养计划试点专业13个;国家级一流本科课程46门,教育部课程思政示范课程3门;博士后流动站19个;一级学科博士学位授权点20个,一级学科硕士学位授权点35个;具有博士专业学位授权类别3个,硕士专业学位授权类别19个;具有高级管理人员工商管理硕士(EMBA)授予权;具有在职人员以同等学力申请博士、硕士学位的授予权以及外国留学生和港澳台学生的招生权。学校现有各类全日制在校生30000余名,留学生1000余名。
学校师资力量雄厚,领军人才集聚。具有教授任职资格评审权和博士生指导教师资格审批权。现有教职工3600余人,专任教师2400余人,其中具有高级职称1600余人。高层次人才700余人,包括:两院院士27人,外国院士4人,国家级领军人才67人,国家级青年人才126人,“国家级教学名师奖”3人,国家级“万人计划”教学名师5人,首届全国教材建设奖先进个人1人,“全国创新争先奖”获得者7人,“国家百千万人才工程”人选14人,国家级、省部级有突出贡献中青年专家26人等。拥有全国高校黄大年式教师团队3个、国家级教学团队5个、教育部创新团队5个、教育部虚拟教研室建设试点2个、工信部研究型教学创新团队3个、国防科技创新团队11个、江苏省创新团队39个。学校先后入选江苏省高层次人才创新创业基地、国家创新人才培养示范基地和首批江苏省课程思政示范高校。
== 方式
学校人才培养水平突出,育人成果丰硕。始终坚持人才培养的中心地位,围绕“工程精英、社会中坚”的人才培养定位,立足信息化社会对人才的知识、能力、素质等新要求,培养德才兼备、求真务实、具有家国情怀和国际竞争力、能引领未来的创新型精英人才。办学70余年以来,累计为国家培养输送了19万余名各类高级专门人才,其中16人当选两院院士。“十三五”以来,获得国家级教学成果奖8项,中国学位与研究生教育学会研究生教育成果奖一等奖1项,省部级教学成果奖33项。学校创新创业教育工作成效显著,获批国家双创示范基地、首批“国家级创新创业学院”,是首批“全国创新创业典型经验高校”“全国深化创新创业教育改革示范高校”,同时也是“中美青年创客交流中心”和“全国高校实践育人创新创业基地”落户高校;在各类重大赛事中屡获佳绩,其中,在第十四届“挑战杯”全国大学生课外学术科技作品竞赛中,学校以总分第一的成绩捧得“挑战杯”;在第八届中国国际“互联网+”大学生创新创业大赛中斩获总冠军,成为全国同时获得“挑战杯”和“互联网+”总冠军的三所高校之一。
学校科技优势突出,标志性成果不断涌现。主动对接服务国家重大战略,持续推进陆海空天信融合发展,为国防自主创新和经济社会发展提供强有力支撑。现有国家级重点实验室3个,前沿科学中心1个,国家级技术创新中心1个,国家级工程技术研究中心1个,国家地方联合工程实验室1个,省部共建协同创新中心1个,国家标准创新基地1个,国家级技术研究推广中心1个,国家级技术研究开发中心1个,国家级检测中心2个,省部级科研平台(哲社基地)75个,建有国家大学科技园,并以此为依托承担了一大批国家重大科研任务,产出了一批重大原创性成果。发明了世界领先的全等式模块装药技术,作为总师单位研制的某型车载炮武器系统亮相国庆70周年阅兵式并列装部队;首创复杂装备系统动力学快速计算方法,建立多体系统发射动力学理论与技术体系;合成了全球首个氮五阴离子盐,成果在《Science》《Nature》发表,引领国际新型高能含能材料发展;发明高温PST钛铝单晶,攻克钛铝合金室温脆性大和服役温度低两大国际性难题,推动我国航空发动机核心技术发展;研制出国内首个固态图像增强器件和红外图像信号处理专用芯片。“十三五”以来,获得省部级及以上科技奖励271项,其中国家科学技术奖17项,实现国家科学技术奖五大奖种全覆盖。学校大力推进产学研合作,推动重大科技成果的转化应用,被认定为首批高等学校科技成果转化和技术转移基地、首批国家知识产权示范高校,在高端装备、新一代信息技术、新材料等新兴产业领域创造了显著的经济效益和社会效益。
== 测试
#lorem(300)
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/styleCasoslov.typ | typst | #import "/style.typ": *
#import "texts.typ": *
#import "textsTmp.typ": *
#let si = [
#lettrine("Sláva:") #lettrine("I nýňi:")
]
#let ektenia(num) = [
==== Ekténia <X>
#lettrine("Hóspodi, pomíluj.") #primText[(#(num)x)]
#si
]
#let verse(verse) = [
#let c = counter("verse")
#c.update(10)
#let tbl = {
verse.map(k => (
primText[#c.display("1:"); #c.update(c => c - 1)]
,[#k]
)
)
}
#tbl.push((primText[S:I:], si))
#table(
columns: (15pt, auto),
stroke: none,
align: (x, y) => (right, left).at(x),
..tbl.flatten()
)
]
#let prokimenyVecierne = [
=== Pondelok - Nedeľa večer, 8. hlas <X>
#lettrine("Sé nýňi blahoslovíte Hóspoda vsí rabý Hóspodni.")
#vers[Stojáščiji v chrámi Hóspodni, vo dvórich Bóhu nášeho.]
=== Utorok - Pondelok večer, 4. hlas <X>
#lettrine("Hóspoď uslýšit mjá, vnehdá vozzváti mí k nemú:")
#vers[Vnehdá prizváti mí, uslýša mjá Bóh právdy mojejá.]
=== Streda - Utorok večer, 1. hlas <X>
#lettrine("Mílosť tvojá, Hóspodi, poženét mjá, vo svjá dní životá mojehó.")
#vers[Hóspoď pasét mjá, i ničtóže mjá lišít, na mísťi zláčňi támo vselí mjá.]
=== Štvrtok - Streda večer, 5. hlas <X>
#lettrine("Bóže, vo ímja tvojé spasí mjá, i síľi tvojéj sudí mí.")
#vers[Bóže uslýši molítvu mojú, vnuší hlahóly úst mojích.]
=== Piatok - Štvrtok večer, 6. hlas <X>
#lettrine("Pómošč mojá ot Hóspoda, sotvóršaho nébo i zémľu.")
#vers[Vozvedóch óči mojí v hóry, otňúduže prijídet pómošč mojá.]
=== Sobota - Piatok večer, 7. hlas <X>
#lettrine("Bóže zástupnik mój jesí tý, i mílosť tvojá predvarít mjá.")
#vers[Izmí mjá ot vráh mojích Bóže, i ot vostájuščich na mjá, izbávi mjá.]
]
#let slohy(slohy) = [
#let c = counter("verse")
#c.update(1)
#let tbl = {
slohy.map(k => (
[],primText[\[#c.display("1.") sloha\]],
primText[#c.display("i:"); #c.step()]
,[#k]
)
)
}
#tbl.push((
[],primText[\[#c.display("1.") sloha\]],
primText[S:I:], si,
[],primText("[Bohoródičen]")
))
#table(
columns: (15pt, auto),
stroke: none,
align: (x, y) => (right, left).at(x),
..tbl.flatten()
)
] |
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/module.typ | typst | // SKIP
// A file to import in import / include tests.
#import "modules/chap2.typ"
#let a
#let b = 1
#let c = 2
#let d = 3
#let value = [hi]
#let item(a, b) = a + b
#let push(a) = a + 1
#let fn = rect.with(fill: conifer, inset: 5pt)
Some _includable_ text.
|
|
https://github.com/loicreynier/sandbox | https://raw.githubusercontent.com/loicreynier/sandbox/main/typst-demo/template.typ | typst | The Unlicense | #let conf(title: none, authors: (), abstract: [], doc) = {
set document(title: title, author: authors.first().name)
set page(paper: "a4", numbering: "1/1")
set text(font: "New Computer Modern", size: 11pt)
set align(center)
text(17pt)[*#title*]
set math.equation(numbering: "(1)", supplement: [Eq.])
show heading: hname => [
#set align(center)
#set text(12pt, weight: "bold")
#block(smallcaps(hname.body))
]
let count = authors.len()
let ncols = calc.min(count, 3)
grid(columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [
#author.name \
#author.affiliation \
#link("mailto:" + author.email)
]))
par(justify: true)[
*#smallcaps("Abstract")* \
#abstract
]
set par(justify: true)
set align(left)
// columns(2, doc)
doc
}
|
https://github.com/j10ccc/algorithm-analysis-homework-template-typst | https://raw.githubusercontent.com/j10ccc/algorithm-analysis-homework-template-typst/main/layout/divider.typ | typst | #let divider = [
#v(10pt)
#line(length: 100%, stroke: .5pt)
#v(10pt)
]
|
|
https://github.com/ofurtumi/formleg | https://raw.githubusercontent.com/ofurtumi/formleg/main/h01/h1.typ | typst | #set heading(numbering: "1.")
#import "@preview/cetz:0.1.0"
= Proof by induction
Lets prove that:
$ (1+2+...+n)^2 > 1^2+2^2+...+n^2 "for" n >= 2 $
Let's rewrite both of the sums of $n$ numbers:
- sum of $n$ numbers: $1+2+...+n=((n(n+1))/2)^2$
- square sum of $n$ numbers: $1^2+2^2+...+n^2=(n(n+1)(2n+1))/6$
Now we can try to prove that $((n(n+1))/2)^2 > (n(n+1)(2n+1))/6$ and simplify it further
== Base case: $n=2$
$ ((2(2+1))/2)^2 = 3^2 = 9 > (2(2+1)(4+1))/6 = (30\/6)/6 = 5 $
== Inductive step:
The prove holds for the base case.
Now we can assume that the prove holds for $k$ and try to prove it for $k+1$.
$
(((k+1)(k+2))/2)^2 &> ((k+1)(k+2)(2(k+1)+1))/6 \
((k^2+3k+2)/2)^2 &> (2k^3+9k^2+13k+6)/6 \
(k^4 +6k^3 + 13k^2+12k+4)/4 &> (2k^3+9k^2+13k+6)/6
$
Since we know that $k >= 2$ we can say that $k^4 >= 4k^3$ and $k^2 >= 2k$ and $12k >= 13$ and $4 >= 6$.
= Triple $0$ state machine
#image("../imgs/h1-2.png")
Here we have a simle state machine tha only allows through itself binary strings that include a substring of _"000"_.
#pagebreak()
= Is $B$ a regular language
#grid(columns: (3fr, 1fr), gutter: 16pt, [
Suppose that $A$ is a regular language with alphabet $Sigma$. Let $B$ denote the language where we have omitted strings with an even length
$ B={w in A: |w| = 2k + 1 "for some" k = 1,2,...} $
We can show that *$B$ is regular* by creating a state machine for the language. We can only go between $S_0$ and $S_1$, and we can only end in $S_1$ if we have an odd number of letters in the input word.
],[
#align(center + horizon,
cetz.canvas({
import cetz.draw: *
circle((0, 0), name: "s0", radius: 0.5)
circle((2, 0), name: "s1", radius: 0.5)
circle("s1.center", name: "s11", radius: 0.4)
content("s0.center", [$S_0$])
content("s1.center", [$S_1$])
line("s0.right", "s1.left", name: "line", mark: (end: ">", start: ">"))
content((1, 0.25), [$Sigma$])
})
)]
)
= Calculating checksum
== Proofing that $w^R in A "for all" w in A$
We know that
$ c = a_0 xor a_1 xor ... xor a_n $
and $w^R$, being the reverse of $w$, should correspond to
$ c^R = a_n xor a_(n-1) xor ... xor a_0 $
Because of the commutitive properties of XOR we know that $a_0 xor a_1 = a_1 xor a_0$ and since $c^R$ is just $c$ reversed we can safely say that $c = c^R$ and therefore we proof that $w^R in A "for all" w in A$
|
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/字符串/最长回文子串.typ | typst | #import "../../../../lib.typ":*
=== #Title(
title: [最长回文子串],
reflink: "https://leetcode.cn/problems/longest-palindromic-substring/description/",
level: 2,
)<最长回文子串>
#note(
title: [
最长回文子串
],
description: [
给你一个字符串s,找到s中最长的回文子串。
],
examples: ([
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
],[
输入:s = "cbbd"
输出:"bb"
]
),
tips: [
1 <= s.length <= 1000
s 仅由数字和英文字母组成
],
solutions: (
( name:[动态规划],
text:[
对于一个子串而言,如果它是回文串,并且长度大于 2,那么将它首尾的两个字母去除之后,它仍然是个回文串。例如对于字符串 “ababa”,如果我们已经知道 “bab” 是回文串,那么 “ababa” 一定是回文串,这是因为它的首尾两个字母都是 “a”。
根据这样的思路,我们就可以用动态规划的方法解决本题。我们用 `P(i,j)` 表示字符串 s 的第 i 到 j 个字母组成的串(下文表示成 `s[i:j]`)是否为回文串:
$ cases(
P(i,j)="true" " 如果子串 "S_i…S_j"是回文串",
P(i,j)="false"" 其它情况"
) $
这里的「其它情况」包含两种可能性:
- `s[i,j]` 本身不是一个回文串;
- $i>j$,此时 `s[i,j]` 本身不合法。
那么我们就可以写出动态规划的状态转移方程:
$ P(i,j)=P(i+1,j−1)∧(S_i==S_j) $
也就是说,只有 `s[i+1:j−1]` 是回文串,并且 s 的第 i 和 j 个字母相同时,`s[i:j]` 才会是回文串。
上文的所有讨论是建立在子串长度大于 2 的前提之上的,我们还需要考虑动态规划中的边界条件,即子串的长度为 1 或 2。对于长度为 1 的子串,它显然是个回文串;对于长度为 2 的子串,只要它的两个字母相同,它就是一个回文串。因此我们就可以写出动态规划的边界条件:
$ cases(
P(i,i)="true",
P(i,i+1)=(S_i==S_{i+1})
) $
根据这个思路,我们就可以完成动态规划了,最终的答案即为所有 `P(i,j)=true` 中 `j−i+1`(即子串长度)的最大值。#YellowText[注意:在状态转移方程中,我们是从长度较短的字符串向长度较长的字符串进行转移的,因此一定要注意动态规划的循环顺序。]
],code:[
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
if (n < 2) {
return s;
}
int maxLen = 1;
int begin = 0;
// dp[i][j] 表示 s[i..j] 是否是回文串
vector<vector<int>> dp(n, vector<int>(n));
// 初始化:所有长度为 1 的子串都是回文串
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
// 递推开始
// 先枚举子串长度
for (int L = 2; L <= n; L++) {
// 枚举左边界,左边界的上限设置可以宽松一些
for (int i = 0; i < n; i++) {
// 由 L 和 i 可以确定右边界,即 j - i + 1 = L 得
int j = L + i - 1;
// 如果右边界越界,就可以退出当前循环
if (j >= n) {
break;
}
if (s[i] != s[j]) {
dp[i][j] = false;
} else {
if (j - i < 3) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}
// 只要 dp[i][L] == true 成立,就表示子串 s[i..L] 是回文,此时记录回文长度和起始位置
if (dp[i][j] && j - i + 1 > maxLen) {
maxLen = j - i + 1;
begin = i;
}
}
}
return s.substr(begin, maxLen);
}
};
```
]),
( name:[中心扩展算法],
text:[
我们仔细观察一下方法一中的状态转移方程:
$ cases(
P(i,j)="true",
P(i,i+1)=(S_i==S_{i+1}),
P(i,j)=P(i+1,j−1)∧(S_i==S_j)
) $
找出其中的状态转移链:
$ P(i,j)←P(i+1,j−1)←P(i+2,j−2)←⋯←"某一边界情况" $
可以发现,#BlueText[所有的状态在转移的时候的可能性都是唯一的]。也就是说,我们可以从每一种边界情况开始「扩展」,也可以得出所有的状态对应的答案。
边界情况即为子串长度为 1 或 2 的情况。我们枚举每一种边界情况,并从对应的子串开始不断地向两边扩展。如果两边的字母相同,我们就可以继续扩展,例如从 `P(i+1,j−1)` 扩展到 `P(i,j)`;如果两边的字母不同,我们就可以停止扩展,因为在这之后的子串都不能是回文串了。
聪明的读者此时应该可以发现,「边界情况」对应的子串实际上就是我们「扩展」出的回文串的「回文中心」。方法二的本质即为:我们枚举所有的「回文中心」并尝试「扩展」,直到无法扩展为止,此时的回文串长度即为此「回文中心」下的最长回文串长度。我们对所有的长度求出最大值,即可得到最终的答案。
],code:[
```cpp
class Solution {
public:
pair<int, int> expandAroundCenter(const string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
--left;
++right;
}
return {left + 1, right - 1};
}
string longestPalindrome(string s) {
int start = 0, end = 0;
for (int i = 0; i < s.size(); ++i) {
auto [left1, right1] = expandAroundCenter(s, i, i);
auto [left2, right2] = expandAroundCenter(s, i, i + 1);
if (right1 - left1 > end - start) {
start = left1;
end = right1;
}
if (right2 - left2 > end - start) {
start = left2;
end = right2;
}
}
return s.substr(start, end - start + 1);
}
};
```
]),
( name:[Manacher 算法],
text:[
略
],code:[
```cpp
class Solution {
public:
int expand(const string& s, int left, int right) {
while (left >= 0 && right < s.size() && s[left] == s[right]) {
--left;
++right;
}
return (right - left - 2) / 2;
}
string longestPalindrome(string s) {
int start = 0, end = -1;
string t = "#";
for (char c: s) {
t += c;
t += '#';
}
t += '#';
s = t;
vector<int> arm_len;
int right = -1, j = -1;
for (int i = 0; i < s.size(); ++i) {
int cur_arm_len;
if (right >= i) {
int i_sym = j * 2 - i;
int min_arm_len = min(arm_len[i_sym], right - i);
cur_arm_len = expand(s, i - min_arm_len, i + min_arm_len);
} else {
cur_arm_len = expand(s, i, i);
}
arm_len.push_back(cur_arm_len);
if (i + cur_arm_len > right) {
j = i;
right = i + cur_arm_len;
}
if (cur_arm_len * 2 + 1 > end - start) {
start = i - cur_arm_len;
end = i + cur_arm_len;
}
}
string ans;
for (int i = start; i <= end; ++i) {
if (s[i] != '#') {
ans += s[i];
}
}
return ans;
}
};
```
])
),
gain:none,
) |
|
https://github.com/clementjumel/resume-template | https://raw.githubusercontent.com/clementjumel/resume-template/main/template.typ | typst | #let resume(
author: "",
description: "",
phone: "",
location: "",
email: "",
github: "",
linkedin: "",
image-path: "",
accent-color: "#000000",
body,
) = {
// Sets document metadata
set document(author: author, title: author)
// Document-wide formatting, including font and margins
set text(
// LaTeX style font
font: "New Computer Modern",
size: 10pt,
lang: "en",
// Disable ligatures so ATS systems do not get confused when parsing fonts.
ligatures: false
)
// Reccomended to have 0.5in margin on all sides
set page(
margin: (0.5in),
"us-letter",
)
// Link styles
show link: underline
// Small caps for section titles
show heading.where(level: 2): it => [
#pad(top: 0pt, bottom: -10pt, [#smallcaps(it.body)])
#line(length: 100%, stroke: 1pt)
]
// Accent Color Styling
show heading: set text(
fill: rgb(accent-color),
)
show link: set text(
fill: rgb(accent-color),
)
// Name will be aligned left, bold and big
show heading.where(level: 1): it => [
#set align(left)
#set text(
weight: 700,
size: 20pt,
)
#it.body
]
let personal_data = [
#(
phone,
location,
link("mailto:" + email)[#email],
link(github)[GitHub],
link(linkedin)[LinkedIn],
).join(" | ")
]
let personal_section = [
= #(author) // Level 1 Heading
#pad(
top: 0.25em,
align(left)[
#(description)\ // Add a line break after description (smaller separation than new paragraph)
#(personal_data)
],
)
]
if image-path == "" [
#personal_section
] else [
#let personal_image = image(image-path)
#grid(
columns: (82%, 16%),
gutter: 2%,
align: horizon, // Center the line vertically
personal_section,
personal_image,
)
]
// Main body.
set par(justify: true)
body
}
// Generic two by two component for resume
#let generic-two-by-two(
top-left: "",
top-right: "",
bottom-left: "",
bottom-right: "",
) = {
pad[
#top-left #h(1fr) #top-right \
#bottom-left #h(1fr) #bottom-right
]
}
// Generic one by two component for resume
#let generic-one-by-two(
left: "",
right: "",
) = {
pad[
#left #h(1fr) #right
]
}
// Cannot just use normal --- ligature becuase ligatures are disabled for good reasons
#let dates-helper(
start-date: "",
end-date: "",
) = {
start-date + " " + $dash.em$ + " " + end-date
}
// Section components below
#let edu(
institution: "",
dates: "",
degree: "",
gpa: "",
location: "",
) = {
generic-two-by-two(
top-left: strong(institution),
top-right: dates,
bottom-left: degree,
bottom-right: emph(location),
)
}
#let work(
title: "",
dates: "",
company: "",
location: "",
) = {
generic-two-by-two(
top-left: strong(company),
top-right: dates,
bottom-left: title,
bottom-right: emph(location),
)
}
#let project(
role: "",
name: "",
url: "",
dates: "",
) = {
pad[
*#role*, #name (#link("https://" + url)[#url]) #h(1fr) #dates
]
}
#let extracurriculars(
activity: "",
dates: "",
) = {
generic-one-by-two(
left: strong(activity),
right: dates,
)
}
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/outline-indent_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// With heading numbering
#set page(width: 200pt)
#set heading(numbering: "1.a.")
#outline()
#outline(indent: false)
#outline(indent: true)
#outline(indent: none)
#outline(indent: auto)
#outline(indent: 2em)
#outline(indent: n => ([-], [], [==], [====]).at(n))
#outline(indent: n => "!" * calc.pow(2, n))
= About ACME Corp.
== History
#lorem(10)
== Products
#lorem(10)
=== Categories
#lorem(10)
==== General
#lorem(10)
|