repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/EpicEricEE/typst-plugins | https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/united/examples/units.typ | typst | #import "../src/lib.typ": unit
#set raw(lang: "typ")
#set text(size: 14pt)
#set table(
inset: 0.7em,
fill: (x, y) => if y == 0 { luma(230) }
)
#set page(
width: auto,
height: auto,
margin: 1em,
background: pad(0.5pt, box(
width: 100%,
height: 100%,
radius: 4pt,
fill: white,
stroke: white.darken(10%),
)),
)
#table(
columns: 2,
[*Input*], [*Output*],
[`#unit("kilo meter")`], [#unit("kilo meter")],
[`#unit[meter squared]`], [#unit[meter squared]],
[`#unit[joule per kilogram]`], [#unit[joule per kilogram]],
[`#unit[kg m^2/s^2]`], [#unit[kg m^2/s^2]],
[`#unit[per second]`], [#unit[per second]],
[`#unit['apples' per day]`], [#unit['apples' per day]],
[`$unit("cm"^-1)$`], [$unit("cm"^-1)$],
)
|
|
https://github.com/lyzynec/orr-go-brr | https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/13/main.typ | typst | #import "../lib.typ": *
#knowledge[
#question(name: [Explain the truncation of a state--space model])[
We split the model into two sets of equations
$
dot(bold(x))_1 &= bold(A)_(1 1) bold(x)_1 (t)
+ bold(A)_(1 2) bold(x)_2 (t) + bold(B)_1 bold(u) (t)\
dot(bold(x))_2 &= bold(A)_(2 1) bold(x)_1 (t)
+ bold(A)_(2 2) bold(x)_2 (t) + bold(B)_2 bold(u) (t)
$
if we assume
$
dot(bold(x))_2 approx bold(0)
$
and we remove them.
In matlab there is function ```matlab modred(G,ix,'Truncate')```.
]
#question(name: [Explain residualization of a state--space model.])[
We split the model into two sets of equations
$
dot(bold(x))_1 &= bold(A)_(1 1) bold(x)_1 (t)
+ bold(A)_(1 2) bold(x)_2 (t) + bold(B)_1 bold(u) (t)\
dot(bold(x))_2 &= bold(A)_(2 1) bold(x)_1 (t)
+ bold(A)_(2 2) bold(x)_2 (t) + bold(B)_2 bold(u) (t)
$
if we assume
$
dot(bold(x))_2 approx bold(0)
$
we can say
$
dot(bold(x))_2 = bold(0) = bold(A)_(2 1) bold(x)_1 (t)
+ bold(A)_(2 2) bold(x)_2 (t) + bold(B)_2 bold(u) (t)
$
and if $bold(A)_(2 2)$ is nonsingular we can express $bold(x)_2$ and
substitue into the other equation.
In Matlab there is function ```matlab modred(G,ix,'MatchdDC')```.
]
#question(name: [Explain balanced realization and balanced reduction
(truncation or residualization)])[
+ Find a state--space realization where *direction* in which the system
is easily controlled are *aligned* with the directions in which the
states are easily observable. Aligning the principal axes of the
reachability and observability ellipsoids. *Ballanced realization*.
+ Remove the state variables that are weakly involved in IO response.
The ellipsoids aligned with the coordinate axes. *Balanced
truncation*, balanced residualization.
Such balance can be achieved by balancing
$
overline(bold(P)) = overline(bold(Q))\
overline(bold(P)) = bold(T) bold(P) bold(T)^*\
overline(bold(Q)) = (bold(T)^(-1))^* bold(Q) bold(T)^(-1)
$
where $bold(T)$ is transformation into the new state space.
- $bold(Q)$ is infinite--time *observability* gramian $bold(Q)
= integral_0^oo exp(bold(A)^T t) bold(C)^T bold(C) exp(bold(A) t)
upright(d) t$
- $bold(P)$ is infinite--time *reachability* gramian $bold(P)
= integral_0^oo exp(bold(A) t) bold(B) bold(B)^T exp(bold(A)^T t)
upright(d) t$
Good solution is
$
overline(bold(P)) = overline(bold(Q)) = op("diag")(sigma_1, sigma_2,
..., sigma_n)
$
where $sigma_i$ are Hankel singular values.
]
]
#skills[
#question(name: [Reduce the order of a provided high--order LTI system in
Matlab.])[]
]
|
|
https://github.com/N3M0-dev/Notes | https://raw.githubusercontent.com/N3M0-dev/Notes/main/CS/Digit_Logic/Note_DDaCA/Ch_3/ch3.typ | typst | #import "@local/note_template:0.0.1": *
#import "@local/tbl:0.0.4"
#set page(numbering: "1")
#set par(justify: true)
#set heading(numbering: "1.1")
#show: tbl.template.with(box: true, tab:"|")
#frontmatter(
title: "Sequential Logic Design Note",
date: "2023 Nov 28",
authors: ("Nemo",),
)
#outline(indent: true)
#pagebreak()
= Latches And Flip-Flops
= Synchronous Logic Design
What does it mean for a circuit to be sequential? And how does it differ compared to combinational logic circutis?
In a sequential logic circuit, the output can not be inferred from the current input, while that of the combinational logic circuit circuit can.
== Problematic Circuits
=== Ring oscillator
A ring oscillator is a kind of circuits that is composed of a odd number of NOT gate in a loop. Such circuits do not have a stable state and is called _unstable_ or _astable_.
=== Race Conditions
Taken the timing of the gates, there may be some race conditions in the circuit that may lead to unexpected results.
== Synchronous Sequential Cricuits
Loops in the circuit are called cyclic paths, where outputs goes back to the inputs. However, sequential circuit with cyclic paths may encounter unexpected race conditions, so to avoid the problem, we put regisiters somewhere in the path. By doing so, the sequential circuit become a collection of combinational logic and regisiters. The registers contain the state of the sysetm, which changes only at the clock edge, so we say the state is synchronized to the clock. If the clock is sufficiently slow, we can eliminate al the races.
Rules of synchronous sequential circuit composition:
- Every circuit element is a combinational circuit or a register
- At least one circuit element is a register
- All registers receive the same clock signal
- Every cyclic path contains at least one register
== Synchronous And Asynchronous Circuits
Asynchronous design in theory is more general than synchronous design design, but synchronous design is easier, so we don't cover asynchronous design here.
= Finit State Machines
= Timing of Sequential Logic
= Parallelism
= Summary
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-11800.typ | typst | Apache License 2.0 | #let data = (
("DOGRA LETTER A", "Lo", 0),
("DOGRA LETTER AA", "Lo", 0),
("DOGRA LETTER I", "Lo", 0),
("DOGRA LETTER II", "Lo", 0),
("DOGRA LETTER U", "Lo", 0),
("DOGRA LETTER UU", "Lo", 0),
("DOGRA LETTER E", "Lo", 0),
("DOGRA LETTER AI", "Lo", 0),
("DOGRA LETTER O", "Lo", 0),
("DOGRA LETTER AU", "Lo", 0),
("DOGRA LETTER KA", "Lo", 0),
("DOGRA LETTER KHA", "Lo", 0),
("DOGRA LETTER GA", "Lo", 0),
("DOGRA LETTER GHA", "Lo", 0),
("DOGRA LETTER NGA", "Lo", 0),
("DOGRA LETTER CA", "Lo", 0),
("DOGRA LETTER CHA", "Lo", 0),
("DOGRA LETTER JA", "Lo", 0),
("DOGRA LETTER JHA", "Lo", 0),
("DOGRA LETTER NYA", "Lo", 0),
("DOGRA LETTER TTA", "Lo", 0),
("DOGRA LETTER TTHA", "Lo", 0),
("DOGRA LETTER DDA", "Lo", 0),
("DOGRA LETTER DDHA", "Lo", 0),
("DOGRA LETTER NNA", "Lo", 0),
("DOGRA LETTER TA", "Lo", 0),
("DOGRA LETTER THA", "Lo", 0),
("DOGRA LETTER DA", "Lo", 0),
("DOGRA LETTER DHA", "Lo", 0),
("DOGRA LETTER NA", "Lo", 0),
("DOGRA LETTER PA", "Lo", 0),
("DOGRA LETTER PHA", "Lo", 0),
("DOGRA LETTER BA", "Lo", 0),
("DOGRA LETTER BHA", "Lo", 0),
("DOGRA LETTER MA", "Lo", 0),
("DOGRA LETTER YA", "Lo", 0),
("DOGRA LETTER RA", "Lo", 0),
("DOGRA LETTER LA", "Lo", 0),
("DOGRA LETTER VA", "Lo", 0),
("DOGRA LETTER SHA", "Lo", 0),
("DOGRA LETTER SSA", "Lo", 0),
("DOGRA LETTER SA", "Lo", 0),
("DOGRA LETTER HA", "Lo", 0),
("DOGRA LETTER RRA", "Lo", 0),
("DOGRA VOWEL SIGN AA", "Mc", 0),
("DOGRA VOWEL SIGN I", "Mc", 0),
("DOGRA VOWEL SIGN II", "Mc", 0),
("DOGRA VOWEL SIGN U", "Mn", 0),
("DOGRA VOWEL SIGN UU", "Mn", 0),
("DOGRA VOWEL SIGN VOCALIC R", "Mn", 0),
("DOGRA VOWEL SIGN VOCALIC RR", "Mn", 0),
("DOGRA VOWEL SIGN E", "Mn", 0),
("DOGRA VOWEL SIGN AI", "Mn", 0),
("DOGRA VOWEL SIGN O", "Mn", 0),
("DOGRA VOWEL SIGN AU", "Mn", 0),
("DOGRA SIGN ANUSVARA", "Mn", 0),
("DOGRA SIGN VISARGA", "Mc", 0),
("DOGRA SIGN VIRAMA", "Mn", 9),
("DOGRA SIGN NUKTA", "Mn", 7),
("DOGRA ABBREVIATION SIGN", "Po", 0),
)
|
https://github.com/i-am-wololo/cours | https://raw.githubusercontent.com/i-am-wololo/cours/master/TP/i23/1/main.typ | typst | #import "./templates.typ": *
#show: project.with(title: "TP1 i23")
= Question 1: Ecrire une fonction #py("interpretations(nbVar)") qui renvoie le tuple constitue de toutes les interpretations possible de nbvar variables propositionnelles
la technique que j'ai opte est de calculer tous les nombre possible en binaire jusqu'a $2^"nbvar"$, puis de les retranscrire en tuple de vrai/faux. Voici le code (on assume une fonction translate to tuple defini comme le suit)
#py("
# Q1: ecrire une fonction Inter(nbvar) qui renvoie le tuple constitue de toutes les interpretations possible de nbvar variables propositionnelles
def translatetotuple(binary: str):
result = []
for i in binary:
if i == '1':
result.append(True)
else:
result.append(False)
return tuple(result)
def inter(nbvar):
finalresult = ()
for i in range(nbvar**2):
result = bin(i)
result = result[2:]
while len(result)<nbvar:
result = '0'+result
result = translatetotuple(result)
finalresult += result,
return finalresult
")
= Question 2.
Une formule propositionelle FP de n variables est codee par une chiande de caracteres respectant la syntaxe python.
les variables étant toujours codées V[0], V[1],… ,V[n-1]. Écrivez une fonction TV(FP,n) qui renvoie la table de vérité de la formule FP sous forme de tuple de tuples à l'aide de la fonction Inter et la fonction d'évaluation eval(chaine) du Python qui évalue une chaine de caractères si elle respecte la syntaxe du langage Python.
Exemple. Avec la chaîne de caractère FP = "V[0] and V[1]", l'appel de la fonction TV(FP,2) doit renvoyer le tuple
#py("((False,False,False),(False,True,False),(True,False,False),(True,True,True))")
le code est incomplet, mais le concept est juste. on genere les combinaison, puis on laisse exec evaluer l'expression, enfin on append dans la variable resultat final et on renvoie (le code n'est pas au point mais le concept est celui la)
#py("
def TV(fp, nbvar):
variables = inter(nbvar)
endresult = ()
for V in variables:
endresult += (i, (eval(fp)),))
return endresult")
= Question 3
Écrivez une fonction Satisfaisable(FP,n) qui renvoie la liste des interprétations des n variables propositionnelles qui satisfont la formule passée en paramètre.
La question la plus facile, il suffit d'utiliser la fonction tv qu'on a precedemment cree, et recuperer le dernier element de chaque tuple et verfier si c'est vrai.
#py("
def Satisfaisable(fp, n):
verites = TV(fp, nbvar)
result = []
for i in verites:
if i[-1] == True:
result.append(i[:1])
return result
")
|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/3-methodology/study-2/graph-representation.typ | typst | MIT License | #import "../../../lib/mod.typ": *
=== Graph Representation <s.graph-representation>
There are several different methods for representing graph structures in computer memory. Each offering different advantages and disadvantages in regards to memory layout and query efficiency. As explained in @s.b.factor-graphs, the factorgraph structure is a bipartite graph with undirected edges.
Such a graph structure enforces little to no constraints on what kind of memory representation are possible to use. Allowing for many different choices@algorithms-fourth-edition. In the original work by Patwardhan _et al._@gbpplanner a cyclic reference/pointer structure is used. They represent the graph with a C++ class called `FactorGraph`, which each robot instance inherit from. Variable and factor nodes are stored in two separate vectors; `factors_` and `variables_`, as shown in the top of @code.gbpplanner-factorgraph.
// #show figure.where(kind: "code"): fig => {
// fig
// }
// #figure(
// kind: "code",
// supplement: [Code Snippet],
// caption: "FactorGraph",
// )
//
//
// https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/Factor.h#L27-L73
//
// https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/Variable.h#L22-L56
//
// https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/GBPCore.h#L57-L77
#let gbpplanner = {
let last-commit = (hash: "fd719ce", date: datetime(day: 30, month: 10, year: 2023))
last-commit.insert("days-since", datetime.today() - last-commit.date)
(
// last-commit-hash: ,
last-commit: last-commit,
github: (
name: "aalpatya/gbpplanner",
permalink: (
factorgraph: "https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/Factorgraph.h#L21-L51",
factor: "https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/Factor.h#L27-L73",
variable: "https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/Variable.h#L22-L56",
gbpcore: "https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/inc/gbp/GBPCore.h#L57-L77"
)
)
)
}
// #let
// #sourcecode-reference([
#listing([
```cpp
// defined in `inc/gbp/FactorGraph.h:21-51`
class FactorGraph {
public:
std::vector<std::shared_ptr<Factor>> factors_;
std::vector<std::shared_ptr<Variable>> variables_;
// ...
};
// defined in `inc/gbp/Factor.h:27-73`
class Factor {
public:
// Vector of pointers to the connected variables. Order of variables matters.
std::vector<std::shared_ptr<Variable>> variables_{};
// ...
};
// defined in `inc/gbp/GBPCore.h:57-77`
class Key {
public:
int robot_id_, node_id_;
};
// defined in `inc/gbp/Variable.h:22-56`
class Variable {
public:
// Map of factors connected to the variable, accessed by their key
std::map<Key, std::shared_ptr<Factor>> factors_{};
// ...
}
```
],
caption: [Header declarations for the classes that make up the factorgraph data structure in GBPplanner. The code snippets are taken from the latest commit #raw(gbpplanner.last-commit.hash) #footnote([#durationfmt(gbpplanner.last-commit.days-since) ago at the time of writing of this thesis.]) `// ...` indicates that there are more fields in the class, but not shown due to not being relevant for graph representation. Symbols prefixed with `std::` are provided by the C++ standard library.]
) <code.gbpplanner-factorgraph>
Edges between variable and factors are not stored as separate index values, but are instead implicitly stored by having each factor store a `std::shared_ptr<Variable>` to every variable it is connected to. Complementary every variable stores a `std::shared_ptr<Factor>` to every factor it is connected to. For both _internal_ edges and _external_ edges between separate factorgraphs this relationship is used. Advantages of this structural design is that it is easy to access the neighbours of a node, given only a handle to the node. For example to send messages to the neighbours of a node by directly invoking methods on the receiving node directly. Another advantage is that it abstracts away whether the pointer is to an external or an internal node. The access and reference patterns are equivalent. However this structural pattern is difficult to implement and discouraged in Rust due to its unique language feature for managing memory; the ownership model. This model is comprised of three rules, that together ensures memory safety and prevents memory issues like invalidated references, use after free and memory leaks@the-rust-book.
#[
#set enum(numbering: box-enum.with(prefix: "Property "))
+ Each value has exactly one _owner_
+ There can only be one owner of a value at a time.
+ When the owner goes out of scope, the value is dropped #footnote([In Rust the term "dropped" is the preferred term to communicate that a value is destructed and its memory deallocated.]).
]
#pagebreak(weak: true)
One limitation of this language model is that data structures with interior bidirectional references like the gbpplanners factor graph representation are difficult to express, since there is no conceptual single owner of the graph. If a connected factor and variable, both share a reference to the memory region of each other, then there is not a well defined concept of who owns who. Difficult does not mean impossible, and there are ways to express these kinds of data structures using a Rust specific design pattern called the _Interior Mutability_ pattern@the-rust-book. With this pattern all borrow checks of the resource is moved from compile time to run time, forcing the programmer to be diligent about ensuring the invariants manually. Due to the added checks that would inevitably be introduced by this pattern it was not utilized. Instead the reimplementation of the factorgraph structure were laid out to work within the intended modelling constructs of the Rust language. In the reimplementation the graph data structure uniqly owns all the variable and factor nodes. And nodes in the graph store no interior references to nodes they are connected to. The _petgraph_ library is used for the actual graph datastructure. _petgraph_ is a versatile and performant graph data structure library providing various generic graph data structures with different performance characteristics@petgraph. To choose which graph representation to use the following requirements were considered. The requirements are ordered by priority in descending order:
#[
#set enum(numbering: box-enum.with(prefix: "R-"))
+ Dynamic insertion and deletion of nodes. Robots connect to each others factorgraph when they both are within the communication radius of each other and both their communication mediums are active/reachable. Likewise they disconnect when they move out of each others communication or the other one is unreachable. This connection is upheld by the InterRobot factor, which gets added and removed frequently. <req.graph-representation-dynamic> // Indices into the graph needs to be stable across removal, in order to ensure the invariant too prevent issues with maintaining
+ Fast node iteration and neighbour search: In order to ensure collision free paths at tolerable speeds, the #acr("GBP") algorithm will have to run many times a second. The faster each factorgraph can be traversed the better. <req.graph-representation-fast-iteration>
+ The index of a node is valid for the lifetime of the node. Without this a lot of checks have to be added every time the factorgraph is indexed to get a reference to a node. <req.graph-representation-stable-indices>
]
_petgraph_ supports the following five types of graph representation; `Graph`, `StableGraph`, `GraphMap`, `MatrixGraph`, and `CSR`. The properties of these are compared in @table.graph-representations.
// #tablec(
// columns: 2,
// header: table.header(
// [One], [Two],
// [Three], [Four],
// ),
// [cell1], [cell2],
// [cell3], [cell4],
// )
All five graph representations support dynamic insertion and removal of vertices and edges after initialization of the graph. So all of them satisfy the first requirement. Four out of the five graph representations uses a `Vec<N>` as its underlying container for vertex instances. `Vec<N>` are guaranteed to be continuous in memory ensuring fast iteration due to cache locality. At the same time the relative difference in iteration speed of using a the `GraphMap` structure should not really be noticeable, given that it uses an `IndexMap<N>`, which in turn uses a `Vec<(N, E)>` for its underlying storage of vertices. But it adds the additional constraint that vertices needs to be hashable, which is an impractical constraint given the lack of non-unique immutable fields of the underlying `Node` struct used to encapsulate both variable and factor nodes. So all data structures support the second requirement.
#pagebreak(weak: true)
#{
// show table.cell.where(x: 0): strong
// show table.header: strong
// show table.cell.where(y: 0): strong
let yes = text(theme.green, emoji.checkmark)
// let no = text(theme.red, emoji.crossmark)
let no = text(theme.red, [x])
// let no = emoji.crossmark
set align(center)
[
#figure(
tablec(
// columns: (1fr, 3fr, 1fr, 1fr, 1fr, 1fr),
columns: 7,
alignment: (left, left, center, center, center, center, center),
header: table.header([Name], [Description], [Space Complexity], [Backing Vertex Structure], [D], [SI], [HV]),
[`Graph`], [Uses an _Adjacency List_ to store vertices.], [$O(|E| + |V|)$], [`Vec<N>`], [#yes], [#no], [#no],
[`StableGraph`], [Similar to `Graph`, but it keeps indices stable across removals.], [$O(|E| + |V|)$], [`Vec<N>`],[#yes], [#yes], [#no],
[`GraphMap`], [Uses an associative array, but instead of storing vertices sequentially it uses generated vertex identifiers as keys into a hash table, where the value is a list of the vertices' connected edges.], [$O(|E| + |V|)$],
// [`IndexMap<N>`],
// [`IndexMap<N, Vec<(N, CompactDirection)>>`],
[`IndexMap<N, Vec<N>>`],
[#yes], [#no], [#yes],
[`MatrixGraph`], [Uses an _Adjacency Matrix_ to store vertices.], [$O(|V^2|)$], [`Vec<N>`], [#yes], [#no], [#no],
[`CSR`], [Uses a sparse adjacency matrix to store vertices, in the #acr("CSR") format.], [$O(|E| + |V|)$], [`Vec<N>`], [#yes], [#no], [#no],
),
caption: [Available Graph Representations in the `petgraph` library. $|E|$ is the number of edges and $|V|$ is the number of nodes. The "Backing Vertex Structure" lists which underlying data structure is used to store the associated data of each vertex. `Vec<N>` #footnote([Part of Rust's standard library]) is a growable array where items are placed continuous in memory@rust-std. `IndexMap<N>` is a special hash map structure that uses a hash table for key-value indices, and a growable array of key-value pairs. Allows for very fast iteration over nodes since their memory are densely stored in memory@indexmap. The "D" column labels if the data structure supports vertices/edges being removed after initialization. The "HI" columns list if the data structure requires that the vertex type must be hashable. In the context of this table; D = Dynamic, SI = Stable Indices, HV = Hashable Vertices.],
// Graph - An adjacency list graph with arbitrary associated data.
// StableGraph - Similar to Graph, but it keeps indices stable across removals.gn
// GraphMap - An adjacency list graph backed by a hash table. The node identifiers are the keys into the table.
// MatrixGraph - An adjacency matrix graph.
// CSR - A sparse adjacency matrix graph with arbitrary associated data.
)<table.graph-representations>
]
}
In terms of space complexity all five candidates are close to equivalent, with four of them using $O(|V| + |E|)$ space, and the `MatrixGraph` using $O(|V|^2)$. Since each graph is not going to store hundreds of thousands of nodes, this quality was not weighted as an important factor to include in the consideration. Only the `StableGraph` data structure guarantees stable indices across repeated removal and insertion. Leaving it as the sole viable choice left that meets all three requirements. Expressed using the _petgraph_ library the chosen `Graph` type is defined as in @lst.graph-representation.
// ```rust
// type IndexSize = u16; // 2^16 - 1 = 65535
// pub type NodeIndex = petgraph::stable_graph::NodeIndex<IndexSize>;
// pub type Graph = petgraph::stable_graph::StableGraph<Node, (), Undirected, IndexSize>;
// ```
#listing(
[
```rust
type IndexSize = u16; // 2^16 - 1 = 65535
pub type NodeIndex = petgraph::stable_graph::NodeIndex<IndexSize>;
pub type Graph = petgraph::stable_graph::StableGraph<Node, (), Undirected, IndexSize>;
```
],
caption: [How the `Graph` type is defined in the reimplementation. It is defined as type alias over a `StableGraph` data structure parameterized by a `Node` enum. No data is associated with the edges in the graph so the _unit_ type `()` is used for data associated with edges. `IndexSize` is a type parameter for the upperbound of the number of nodes the graph can hold. In the experiments, see @s.results, no individual factorgraph ever held more more than $794$ nodes#footnote[Happens in Circle Experiment with $N_R = 50$, when all robots form a fully connected graph near the center of the circle.], so a bound of $2^16 - 1 = 65535$ was plenty sufficient, and is more compact in memory than the next possible alternative $ u 32 = 2^32 - 1$.]
)<lst.graph-representation>
// Another key motivation for using a graph data structure that fully owns all its nodes is that it maps more faithfully to the conditions an implementation would have to meet for deployment in a real-world multi-robot scenario. Here the work needed to exchange messages across internal and external edges are significantly different. And will be have to handled differently. In comparison the use of bidirectional `std::shared_ptr` is no longer feasiable. The reason for this is straightforward. Pointers are addresses into virtual memory that are only meaningful/valid within the context of the computer process that created the pointer. When the algorithm is split across multiple hosts, it runs on multiple processes and hence there would be more than one virtual memory. Furthermore the use of pointers as identifiers would limit its capability to work across heterogenous computer units as you would be limited to one of 32 bit or 64 bit architectures. 32 bit are common for in embedded devices.
// For the algorithm to work with the bidirectional structure an RPC abstraction would be needed. Where the node is instead an abstract interface with two implementors; an owned variant for the nodes that belong to the robots factorgraph, such as obstacle factors. And a proxy variant that used the Proxy structural pattern that would forward read and write calls to communication stack used between the robots.
// Although no real world experiments have been performed as part of this thesis, it was still considered important that the reimplementation was designed with an architecture that would be feasible in a real distributed system. This was done to better assess the practical feasibility of the algorithm outside of simulation.
Another key motivation for using a graph data structure that fully owns all its nodes is that it more accurately reflects the requirements for deployment in a real-world multi-robot scenario. In such a scenario, the work needed to exchange messages across internal and external edges differs significantly and must be handled differently. In comparison, using bidirectional `std::shared_ptr` is not feasible. This is because pointers are addresses in virtual memory, which are only meaningful within the context of the process that created them. When the algorithm runs across multiple hosts, it operates on multiple processes, each with its own virtual memory. Furthermore, using pointers as identifiers limits the algorithm's ability to work across heterogeneous computing units, as you would be restricted to either 32-bit or 64-bit architectures. // A problem for embedded devices where both 32-bit and 64-bit are common#k[citation]
For the algorithm to function with a bidirectional structure, a #acr("RPC") abstraction would be necessary. This approach would involve an abstract interface for the nodes, with two implementors: an owned variant for nodes belonging to the robot's factor graph, such as obstacle factors, and a proxy variant using the Proxy structural pattern to forward read and write calls to the communication stack used between the robots@gang-of-four-design-patterns. Although no real-world experiments were conducted as part of this thesis, it was considered valuable to design the reimplementation with an architecture feasible for a real distributed system. This was done to better assess the practical feasibility of the algorithm outside of simulation.
// - Even though this design will not have as good performance as using direct pointer access.
One idea expanded upon from the original work is the use of separate arrays for variables and nodes. In the reimplementation, each factor graph stores additional vectors of indices for variable nodes, factor nodes, and each distinct factor variant. This optimization trades some memory space for faster iterations with better CPU branch prediction. Queries needing a specific subview of the graph do not have to branch based on the node type each time the graph is iterated over. All visualization modules of the simulator are implemented as #acr("ECS") systems. Many of them query all the factor graphs each frame but only need a specific subset of nodes. For example, the "Obstacle Factors" module explained in @s.m.visualization only needs access to the obstacle factors of each graph. By having the factor graphs' public #acr("API") provide dedicated iterators for these subviews, the visualization modules can run as efficiently as possible. Similarly, the internal and external message passing also use dedicated arrays. For example, only interrobot factors are iterated over during the factor iteration step for the external pass, see @s.m.algorithm. Mutable access to the index vectors is never exposed through the public #acr("API") of the graph. Combined with the borrowing system, this ensures that the indices always point to existing nodes, making it easy and safe to run efficient queries on specific subsets of the factor graphs.
Finally each factorgraph is stored as a component in the ECS world associated with each robot entity. This makes them easy to access from other systems in the simulation, and to add and remove them as robots spawn and despawn in the different scenarios.
// - this to ensure that ECS queries that run frequently on the graph and only need a specific subset of it runs as fast as they can.
// In terms of space complexity all five candidates are close to equivalent, with four of them using $O(|V| + |E|)$ space, and the `MatrixGraph` using $O(|V|^2)$. Lack of sufficient/enough memory were not deemed and issue for the simulation. To support this claim let:
//
// $ B(T) = "stack allocation of T in bytes" $
//
// The Rust standard library function #raw(block: false, lang: "rust", "std::mem::size_of::<T>()") is used to calculate $B(T)$@rust-std. Then the size of a `VariableNode` and a `FactorNode` is:
//
//
// $ B("Variable") = 392 "bytes" $
// $ B("Factor") = 408 "bytes" $
//
// #let size_of_variable = 392
// #let size_of_factor = 408
//
// A `Node` is modelled as a tagged union of a `VariableNode` and `FactorNode` so the size of a node is, the size of the largest of the two variants, plus 8 bytes to store the tag@the-rust-book:
//
// $ B(v_i) = max(B("Variable"), B("Factor")) + 8 "bytes" $ <eq.factorgraph-memory-estimate>
//
// #let size_of_node = calc.max(size_of_variable, size_of_factor) + 8
//
// No data is associated with an edge so the size of an edge is:
//
// $ B(e_i) = 0 "bytes" $
//
// An empty `FactorGraph` takes up:
//
// $ B("FactorGraph") = 200 "bytes" $
//
//
// #let size_of_graph = 200
//
// $ N_("obstacle")(\#V) = \#V - 2 $
//
// #let n_obstacle(v) = v - 2
//
// $ N_("dynamic")(\#V) = \#V - 1 $
//
// #let n_dynamic(v) = v - 1
//
// $ N_("interrobot")(\#V, \#C) = \#V times \#C $
//
// #let n_interrobot(v, c) = v * c
//
// $ N_("factors")(\#V, \#C) = N_("obstacle")(\#V) + N_("dynamic")(\#V) + N_("interrobot")(\#V, \#C) $
//
// #let n_factors(v, c) = n_obstacle(v) + n_dynamic(v) + n_interrobot(v, c)
//
// #let robots = 20
// #let variables = 10
//
// With a simulation of $\#R$ robots and $\#V$ variables, with each robot having $\#C$ connections, then the size is:
//
// $ B("Simulation"(R, V, C))
//
// &= R times (B("FactorGraph") + (V + N_("factors")(V, C)) times B("Node"))
// $
//
// #let size_of_simulation(r, v, c) = r * (size_of_graph + (v + n_factors(v, c)) * size_of_node)
//
// With $R = 20, V = 10, C = 10$ the size is:
//
// #let size_of_example = size_of_simulation(20, 10, 10)
//
// $ B("Simulation"(20, 10, 10)) = #size_of_example "bytes" = #MiB(size_of_example) $
//
// #MiB(size_of_example) is not a lot of memory for a modern computer. This of course, only accounts for the stack allocated memory of each structure. For heap allocated structures like dynamically sized matrices this only accounts for the heap pointer to the data and the length of the allocated buffer, and not the size of the buffer. With 4 #acr("DOF") a conservative estimate can be made by generalizing the heap allocation size of each node to be the largest heap allocation of the possible node variants. Let
//
// $ H(T) = "heap allocation of T in bytes" $ <equ.heap-allocation-in-bytes>
// $ H_("inbox")(T, C) = "heap allocation of T's inbox with C connections in bytes" $
//
// #{
// let f64 = 8
// let DOFS = 4
// let heap_size_of_factor_state = (4 + 2 * 2 + DOFS * 2 + 4 * 8 + 4) * f64
// let heap_size_of_dynamic = 4 * 8 * f64 + heap_size_of_factor_state
// let heap_size_of_obstacle = 0 * f64 + heap_size_of_factor_state
// let heap_size_of_interrobot = 0 * f64 + heap_size_of_factor_state
// let heap_size_of_variable_prior = (DOFS + DOFS * DOFS) * f64
// let heap_size_of_variable_belief = (DOFS + DOFS * DOFS + DOFS + DOFS * DOFS) * f64
// let heap_size_of_variable = heap_size_of_variable_prior + heap_size_of_variable_belief
//
// let heap_size_of_message = (DOFS + DOFS + DOFS * DOFS) * f64
//
// let heap_size_of_variable_inboxes(variables, connections) = {
// assert(variables >= 2);
// assert(connections >= 0);
//
// let first_last = 2 * (1 + connections)
// let inbetween = (variables - 2) * (2 + 1 + connections)
// (first_last + inbetween) * heap_size_of_message
// }
//
//
// // TODO: missing size of inbox, for a variable this is dependant on the number of robots it is connected to
//
// // show table.cell.where(y: 0): strong
// set align(center)
//
// // tablec(
// // columns: (1fr, 3fr, 1fr),
// // align: (center, left, center),
// // header: table.header([*Parameter*], [*Description*], [*Unit* / *Domain*]),
// // #let tablec(title: none, columns: none, header: none, alignment: auto, stroke: none, ..content) = {
// tablec(
// columns: 4,
// header: table.header([], [$H$], [$H_("inbox")(C)$], [$H_("total")(C)$]),
// [$V_("current")$], [#heap_size_of_variable], [$#heap_size_of_message (1 + C)$], [$#{heap_size_of_variable + 1 * heap_size_of_message} + #heap_size_of_message C$],
// [$V_("horizon")$], [#heap_size_of_variable], [$#heap_size_of_message (1 + C)$], [$#{heap_size_of_variable + 1 * heap_size_of_message} + #heap_size_of_message C$],
// [$V_("in-between")$], [#heap_size_of_variable], [$#heap_size_of_message (3 + C)$], [$#{heap_size_of_variable + 3 * heap_size_of_message} + #heap_size_of_message C$],
//
// [$F_("dynamic")$], [#heap_size_of_dynamic], [#{1 * heap_size_of_message}], [#{heap_size_of_dynamic + 1 * heap_size_of_message}],
// [$F_("interrobot")$], [#heap_size_of_interrobot], [#{2 * heap_size_of_message}], [#{heap_size_of_interrobot + 2 * heap_size_of_message}],
//
//
// )
//
// // table(
// // columns: 5,
// // table.header([], [Variable], [$F_("obstacle")$], [$F_("dynamic")$], [$F_("interrobot")$]),
// // [$H$], [#heap_size_of_variable], [#heap_size_of_obstacle], [*#heap_size_of_dynamic*], [#heap_size_of_interrobot],
// // )
//
// }
// Lower estimate as some of the fields are heap allocated, and only the auxiliary data like the pointer to the data and the size of it is counted by the $B$ function.
// https://github.com/indexmap-rs/indexmap/blob/3f0fffb85b99a2a37bbee363703f8509dd03e2d7/src/map/core.rs#L32
// #[derive(Clone)]
// pub struct GraphMap<N, E, Ty> {
// nodes: IndexMap<N, Vec<(N, CompactDirection)>>,
// edges: IndexMap<(N, N), E>,
// ty: PhantomData<Ty>,
// }
// Iteration is very fast since it is on the dense key-values
// A raw hash table of key-value indices, and a vector of key-value pairs
// @packed-compressed-sparse-row
// / #acr("CSR"): asd
// / Adjacency list: asd
// / Adjacency matrix: $O(|V^2|)$ memory
// / GraphMap: asd
// - Too summarize memory consumption should not be a limiting factor of simulating the system.
// - Not too many nodes in the graph, so we did not spend time benchmarking the various backing memory models.
// - Since the memory required for each graph is not very high, we can afford to use more space for additional indices arrays
// - In addition to storing the graph itself each factorgraph use additional memory to store arrays of node indices of each node kind, to speed iteration
// - should still be feasible for embedded computers with less memory
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.2/template/chapters/6-implementation.typ | typst | Apache License 2.0 | #import "global.typ": *
= Implementation <implementation>
#lorem(35)
#todo(
[ Describe what is relevant and special about your working prototype. State how
single features help to solve problem(s) at hand. You might implement only the
most relevant features. Features you select from your prioritised feature list
assembled in Chapter 4. Focus novel, difficult, or innovative aspects of your
prototype. Add visuals such as architectures, diagrams, flows, tables,
screenshots to illustrate your work. Select interesting code snippets, e.g. of
somewhat complicated algorithms, to present them as source code listings.
*For example*, you might explain your backand and your frontend development in
subsections as shown here:
== Backend <backend>
We implemented a minimal #emph[script] in Python to manage a secure `Message`s
in object oriented ways. The way to include source code in your document is
discussed and shown in #link("https://typst.app/docs/reference/text/raw/").
*Hints for code listings in Typst*:
In Typst we provide a custom macro/function _fhjcode_ to support listings with
code pulled in from external files and with line numbering. For example:
See @lst:Message and @lst:SecureMessage for a minimal `SecureMessage` class.
#figure(
align(
left,
// we use a custom template (style), defined in fh.typ
// the files are expected in subfolder "source"
// optionally, specify firstline/lastline
fhjcode(code: read("/code-snippets/msg.py"), lastline: 5),
),
// we use a custom flex-caption), to allow long and short captions
// (the short one appears in the outline List of Figures).
// This is defined in `lib.typ`.
caption: flex-caption(
[Defining a base class in Python. Here, the base class is named _Message_.], [Base class _Message_.],
),
) <lst:Message>
#figure(
align(
left, fhjcode(code: read("/code-snippets/msg.py"), firstline: 7, lastline: 17),
), caption: flex-caption(
[For inheritance we might define a specialised class based on another class.
Here, the specialised class _SecureMessage_ is based on the class _Message_.], [Specialised class _SecureMessage_.],
),
) <lst:SecureMessage>
== Frontend <frontend>
*Hints for abbreviations and glossary entries _gls(key)_ in Typst*:
Abbreviations should be written in full length on the first occurrence. Later
the short version can be used. Therefore, define glossary entries with a _key_ and
a _short_ as well as a _long_ description first (see file _glossary.typ_). In
the text you might use `#gls(<key>)` (and `#glspl(<key>)` for plural) usage of
an abbreviation. For example:
The system is using #gls("cow") for optimisation. The implementation of #gls("cow") can
be changed by ... Note the usage of the special configured #gls("gc"). We
compared many #glspl("gc") to find out .. ],
) |
https://github.com/3w36zj6/textlint-plugin-typst | https://raw.githubusercontent.com/3w36zj6/textlint-plugin-typst/main/test/fixtures/CodeBlock/input.typ | typst | MIT License | ```rust
fn main() {
println!("Hello World!");
}
```
```
language is undefined.
```
|
https://github.com/dark-flames/resume | https://raw.githubusercontent.com/dark-flames/resume/main/chicv.typ | typst | MIT License | #import "fontawesome.typ": *
#import "@preview/shiroa:0.1.0": is-pdf-target, is-web-target, get-page-width
#let main-color() = {
if is-web-target() {
import "@preview/typst-apollo:0.1.0": pages
import pages: main-color
main-color
} else {
black
}
}
#let dash-color() = {
if is-web-target() {
import "@preview/typst-apollo:0.1.0": pages
import pages: dash-color
dash-color
} else {
gray
}
}
#let chiline() = {
v(-3pt);
line(length: 100%, stroke: dash-color());
v(-10pt)
}
#let iconlink(
uri, text: "", icon: link-icon) = {
if text != "" {
link(uri)[#fa[#icon] #text]
} else {
link(uri)[#fa[#icon]]
}
}
#let cventry(
tl: lorem(2),
tr: "2333/23 - 2333/23",
bl: "",
br: "",
content
) = {
block(
inset: (left: 0pt),
tl + h(1fr) + tr +
linebreak() +
if bl != "" or br != "" {
bl + h(1fr) + br + linebreak()
} +
content
)
}
#let cvitem(
tl: lorem(2),
tr: "2333/23 - 2333/23",
bl: "",
br: ""
) = {
block(
inset: (left: 0pt),
tl + h(1fr) + tr +
linebreak() +
if bl != "" or br != "" {
bl + h(1fr) + br
}
)
}
#let chicv(body) = {
set par(justify: true)
set text(fill: main-color())
set text(size: 14pt) if is-web-target()
show heading.where(
level: 1
): set text(
size: 22pt,
font: (
"Avenir Next LT Pro", // original chi-cv font
"Manrope", // a font available in the typst environment and looks similar to Avenir
),
weight: "light",
)
show heading.where(
level: 2
): it => text(
size: if is-web-target() { 15pt } else { 12pt },
font: (
"Avenir Next LT Pro",
"Manrope",
),
weight: "light",
block(
chiline() + it,
)
)
set list(indent: 0pt)
show link: it => underline(offset: 2pt, it)
set page(
margin: (x: 0.9cm, y: 1.3cm),
) if is-pdf-target()
set page(
margin: (
// reserved beautiful top margin
top: 20pt,
// reserved for our heading style.
// Typst is setting the page's bottom to the baseline of the last line of text. So bad.
bottom: 0.5em,
// remove rest margins.
rest: 0pt,
),
numbering: none,
number-align: center,
width: get-page-width(),
height: auto,
) if is-web-target()
body
}
#let today() = {
let month = (
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December",
).at(datetime.today().month() - 1);
let day = datetime.today().day();
let year = datetime.today().year();
[#month #day, #year]
}
|
https://github.com/HKFoggyU/hkust-thesis-typst | https://raw.githubusercontent.com/HKFoggyU/hkust-thesis-typst/main/hkust-thesis/templates/authorization.typ | typst | LaTeX Project Public License v1.3c | #import "../imports.typ": *
#import "../utils/invisible-heading.typ": invisible-heading
#let authorization(
config: (:),
info: (:),
) = {
set align(center)
[
#pagebreak(weak: true, to: if config.twoside { "odd" })
#set par(first-line-indent: 2em)
#invisible-heading("Authorization Page")
#heading(outlined: false)[#text(size: constants.font-sizes.title)[#underline([Authorization])]]
#do-repeat([#linebreak()], 2)
#align(left)[
I hereby declare that I am the sole author of the thesis.
#do-repeat([#linebreak()], 1)
I authorize the Hong Kong University of Science and Technology to lend this thesis to other institutions or individuals for the purpose of scholarly research.
#do-repeat([#linebreak()], 1)
I further authorize the Hong Kong University of Science and Technology to reproduce the thesis by photocopying or by other means, in total or in part, at the request of other institutions or individuals for the purpose of scholarly research.
]
#do-repeat([#linebreak()], 7)
#signature-line()
#info.author
#do-repeat([#linebreak()], 1)
#info.submit-date.date #info.submit-date.month #info.submit-date.year
]
}
|
https://github.com/Sepax/Typst | https://raw.githubusercontent.com/Sepax/Typst/main/DIT084/Notes/main.typ | typst |
#import "template.typ": *
#show: template.with(
title: [Testing, debugging and verification],
short_title: "DIT084",
description: [
Notes based on lectures for DIT084 (Testing, debugging and verification)\ at
Gothenburg University, Autumn 2023
],
authors: ((name: "<NAME>"),),
lof: false,
lot: false,
lol: false,
paper_size: "a4",
cols: 1,
text_font: "XCharter",
code_font: "Cascadia Mono",
accent: "#000000", // black
)
= Introduction
How do we judge failure in software development? In general, we need a measure
to judge failure. This is given by means of satisfaction of a specification. A
specification is a set of requirements that a system must satisfy. A
specification can be given in many forms, such as a formal mathematical
description, a set of examples, or a set of requirements in natural language.
The specification is the basis for testing, debugging and verification.
In simple terms:
$
"Spec" = "Require" + "Ensure"
$
where *Require* is the set of requirements the program must satisfy in order to
behave correctly, and *Ensure* is the set of guarantees that the program must
satisfy.
#example[
Imagine a programs that sorts an array of integers. The program must satisfy the
following specification:
- *Require:* Accept only input as an array of integers.
- *Ensure:* Return a sorted array of integers.
]
== The contract methaphor <contract_methafor>
Same priciple as a *legal contract*, between supplier and client.
- *Supplier:* aka implementer, here a _class or method_ in Java.
- *Client:* mostly _caller object or human user_ calling main-method.
- *Contract:* One or more _pairs of ensures-requires clauses_, defining _mutual obligations_ between
supplier and client.
_"If the caller (the client) of the method *m* (the supplier) gives inputs which
fulfils the required *precondition*, then the method *m* ensures that the
*postcondition* holds after *m* finishes execution.”_
== Specification, failure, correctness
A failure/correctness is relative to a specification.
- A method *fails* when called in a _state fulfilling the required precondition_ of
its contract and it _does not terminate in a state fulfulling the postcondition_
to be ensured.
- A method is *correct* whenever it is started in a _state fulfilling the required precondition_,
then it _terminates in a state fulfilling the postcondition to be ensured_.
- *Correctness:* Proving absence of failures.
= Testing
Some terminology regarding faults, errors & failures:
- *Fault:* a static defect in the software.
- *Error:* an incorrect internal state that is the manifestation of some fault.
- *Failure:* external, incorrect behaviour with respect to expected behaviour.
== The State of a program
A program can be seen as a function that maps a state to a state. The state of a
program is the values of all variables at a given point in time.
Inputs in the program in @program_state does not always trigger failures. This
is the case for most programs!
#figure(
image("figures/program_state.png", width: 80%),
caption: [A graph showing the states of a program],
) <program_state>
=== Program to graph
How does one convert a program to a state graph?
A labelled graph $G$ is of the form
$ G = (N,E,L) $
where $N$ is a set of nodes, $E$ is a set of edges and $L$ is a set of labels. $E subset.eq N times L times N$
A program $P$ is a set of statements
$ P = {s_1, s_2, ..., s_n} $
The following function is used to transform the program to a graph:
$ [dot.op]^(0,f): S -> 2^E $
The function takes an initial state $0$ and a final state $f$ and a *statement*
and *return a set of edges*. We use the special state $bot$ to mean an exit
state (for return statements).
The transformation rule are as follows:
$ [s_1; s_2]^(0,f) = [s_1]^(0,1) union [s_2]^(1,f) $
where $1$ is a fresh state.
#example[
Some examples of transformations:
- $[x = a;]^(0,f) = { (0,f = a,f) }$
- $["return" a;]^(0,f) = { (0,"return" a, bot) } $
- $["if"(b){s_1}]^(0,f) = { (0,b,1),(0,!b,f) } union {s_1}^(1,f)$
- $["while"(b){s_2}]^(0,f) = { (0,b,1),(0,!b,f) } union {s_2}^(1,0)$
]
== Complexity of testing (and why we need models)
No other engineering field builds products as complicated as software. The term
correctness has no meaning. Like other engineers, we must use abstraction to
cope with complexity. We use *discrete mathematics* to raise our level of
abstraction.
Abstraction is the purpose of _Model-Driven Test Design_ (MDTD). The “model” is
an abstract structure.
=== Software testing foundations
Testing can only show the presence of failures, not their absence.
- *Testing:* Evaluate software by observing its execution.
- *Test Failure:* Execution of a test that results in a software failure.
- *Debugging:* The process of finding a fault given a failure.
*Not all inputs will “trigger” a fault into causing a failure*
=== RIPR model (or fault and failure model)
Four conditions necessary for a failure to be observed:
- *Reachability:* The location or locations in the program that contain the fault
must be reached.
- *Infection:* The state of the program must be incorrect.
- *Propagation:* The infected state must cause some output/final state to be
incorrect.
- *Reveal:* The tester must observe part of the incorrect state.
The RIPR model is a framework for understanding and categorizing software bugs.
It stands for Reach, Infection, Propagation, and Reveal. Reach refers to the
execution reaching the defect, Infection is when the defect causes an incorrect
program state, Propagation is when this incorrect state leads to incorrect
behavior or output, and Reveal is when this incorrect behavior is observed.
#figure(image("figures/ripr_model.png", width: 80%), caption: [The RIPR model]) <ripr_model>
=== The V model
The V-model emphasizes a parallel relationship between development and testing
stages. Each development stage has a corresponding testing phase, ensuring that
issues are identified and fixed early. _It's called the V-model due to its V-like structure, representing the sequence
of execution of processes._
Each testing phase uses a different type of testing level:
- *Acceptance testing:*: Assess software with respect to user requirements
- *System Testing:*: Assess software with respect to system-level specification.
- *Integration Testing:* Assess software with respect to high-level design
- *Unit Testing:* Assess software with respect to low-level unit design
#figure(image("figures/v_model.png", width: 80%), caption: [The V model]) <v_model>
== Test automation
The use of software to control _the execution_ of tests, the _comparison_ of
actual outcomes to predicted outcomes, the
_setting up_ of test preconditions, and other test _control_ and test reporting
functions.
- Reduces cost
- Reduces human error
- Reduces variance in test quality from different individuals
- Reduces cost of *regression testing*
== Regression testing
Regression testing is a type of software testing that seeks to uncover new
software bugs, or regressions, in existing functional and non-functional areas
of a system after changes such as enhancements, patches or configuration
changes, have been made to them.
- Orthogonal to other mentioned tests
- Testing that is done *after changes* in the software (updates)
- Standard part of maintenance phase of software development
_The purpose of regression testing is to gain confidence that changes did not
cause new failures._
== Software testability
The degree to which a system or component facilitates the establishment of test
criteria and the performance of tests to determine whether those criteria have
been met. _In simple terms: how hard is it to finds faults?_
Testability is a condition of two factors:
- How to provide the test values to the software?
- How to observe the results of test execution?
== Observability
How easy it is to observe the behaviour of a program in terms of its outputs,
effects on the environment and other hardware and software components.
_Software that affects hardware devices, databases, or remote files have low
observability!_
== Controllability
How easy it is to provide a program with the needed inputs, in terms of values,
operations, and behaviours.
- Easy to control software with inputs from keyboards
- Inputs from hardware sensors or distributed software is harder
== Test suit construction
A test suite is a collection of test cases that are intended to be used to test
a software program to show that it has some specified set of behaviours.
- Most central actitivy of testing
- Determines if we have enough test cases (stopping criteria)
- Determines if we have the right test cases (represenative test cases)
The quality of test suites defines the quality of the overall testing effort.
When presenting test suites, we show only relevant parts of test cases.
=== Black box testing
Deriving test suites from external descriptions of the software, e.g.
- Specifications
- Requirements / Design
- Input space knowledge
=== White box testing
Deriving test suites from the source code, e.g.
- Conditions
- Branches in execution
- Statements
_Modern techniques are a hybrid of both black- and white box_
== Coverage criteria
Most metrics used as quality criteria for test suites, describe the degree of
some kind of coverage. These metric are called coverage criteria.
These are crucial for testing _saftey critical software_.
There are certain categories of coverage criteria:
- Control flow graph coverage (white box)
- Logic coverage (white box)
- Input space partitioning (black box)
== Control flow graph
Represent a method to test as a graph, where:
- Statements are nodes
- Edges describe control flow between statements
- Edges are labelled with conditions
#important[*Rules of transformation* can be read in Section 7.3.1 "Structural Graph
coverage for source code" from the book: Introduction to software testing. *This
is required*]
=== Control flow graph notions
- *Execution path:* a path through the control flow graph that starts at the entry
point and is either
infinite or ends at one of the exit points.
- *Path condition:* a condition causing execution to take some path $p$
- *Feasible execution path:* an execution path for which a satisfiable path
condition exists.
#note[A branch or statement is feasible if it is contained in at least one feasible
execution path.]
== Types of coverage criteria
=== Statement coverage (SC)
Satisfied by a test suite _TS_, _iff_ for every node $n$ in the control flow
graph there is at least one test in _TS_ causing an execution path via $n$.
=== Branch coverage (BC)
Satisfied by a test suite _TS_, _iff_ for every edge $e$ in the control flow
graph there is at least one test in _TS_ causing an execution path via $e$. _Note that this is a stronger criterion than statement coverage._
=== Path coverage (PC)
Satisfied by a test suite _TS_, _iff_ for every feasible execution path $p$ in
the control flow graph there is at least one test in _TS_ causing an execution
path via $p$. _Note that this is a stronger criterion than branch coverage._
=== Logic coverage (LC)
Satisfied by a test suite _TS_, _iff_ for every predicate $p$ in the control
flow graph there is at least one test in _TS_ causing an execution path via $p$.
Logical (boolean) expressions can come from many sources. We focus on decisions
in the source code _(if, while, for, etc.)_.
=== Decision coverage (DC)
Let the decisions of a program $p$, $D(p)$, be the set of all logical
expressions which $p$
branches on.
For a given decision $d$, _DC_ is satisfied by a test suite _TS_ if it:
- Contains at least two tests,
- one where $d$ evaluates to true,
- one where $d$ evaluates to false
For a given program $p$, _DC_ is satisfied by _TS_ if it satisfies _DC_ *for all* decisions $d in D(p)$.
#example[
#figure(
image("figures/decision_coverage.png", width: 80%),
caption: [Decision coverage example],
) <decision_coverage>
]
=== Condition Coverage (CC)
#figure(
image("figures/condition_coverage.png", width: 80%),
caption: [Condition coverage],
) <condition_coverage>
#figure(
image("figures/condition_coverage_example.png", width: 80%),
caption: [Condition coverage example],
) <condition_coverage_example>
=== Modified Condition Decision Coverage (MCDC)
#figure(
image("figures/mcdc.png", width: 80%),
caption: [Modified Condition Decision Coverage],
) <mcdc>
#figure(
image("figures/mcdc_example.png", width: 80%),
caption: [Modified Condition Decision Coverage example],
) <mcdc_example>
== Input domain modeling
- The input domain $D$: the possible values that input parameters can have.
- A partition $q$ defines a set of equvilence classes (or simply blocks $B_q$)
over $D$
A partition $q$ satisfies: (completeness)
$ union.big_(b in B_q) b = D $
Blocks are pairwise disjoint:
$ b_i union b_j = emptyset, wide i eq.not j, wide b_i, b_j in B_q $
- Test values in the same block are assumed to contain _equally useful values_.
- Test cases contain values from each block.
#example[
#figure(
image("figures/partitioning.png", width: 80%),
caption: [Partitioning example],
) <partitioning>
]
=== Strategies for generating blocks
- Valid vs. invalid values: all valid and all invalid (completeness)
- Sub-partition: valid values serving different functionality.
- Boundaries: values at or close boundaries often cause problems (stress testing).
- Normal use (happy path): the desired outcome.
- Missing blocks vs overlapping blocks (complete vs disjoint)
- Special values Pointers: (null and not null), collection: (empty and non empty),
integer (zero a special value).
#example[
#figure(
image("figures/example_triang.png", width: 80%),
caption: [Example: triang(0)],
) <example_triang>
#figure(
image("figures/example_triang_2.png", width: 80%),
caption: [Example: triang(0) - Solution],
) <example_triang_2>
]
All combinations of blocks from all characteristics must be used. The number of
tests is the product of the number of blocks for each partition. _All Combinations Coverage *ACoC*_
For _triang()_, we have three characteristics, each with 4 blocks. Thus, we need $4 dot 4 dot 4 = 64$ test
cases.
Recall: _different choices of values from the same block are equivalent from testing
perspective_.
= Debugging
- How to systematicly find source of failer
- Test-case to reproduce errors
- Finidng a small failing input (if possible)
- Observing exceution: Debbuggers and Logging
- Program dependencies: data- and control
== Motivation
- Debuging needs to be systematic
- Debuging may involve large inputs
- Programs may have have thousands of memory locations
- Program may pass through milions of states before failure occurs
== The Steps Of Debugging
+ Reproduce the error and try to understand the cause.
+ Isolate and minimise the diffrent factors. (*Simplification*)
+ Eyeball the code, where could it be? (*Reason backwards*)
+ Devise experiments to test your hypothesis. (*Test hypothesis*)
+ Repeat step 3 and 4 until the cause of the bug is determined
+ Fix the bug and verify the fix
+ Create a regression test (See below)
_ Regression testing is a type of software testing that checks if recent code
changes have negatively impacted existing features. It involves re-running
previously created test cases after code modifications to catch any unintended
side effects and ensure the ongoing stability of the software._
== Problem Simplification
As described in the diffrent steps of debugging, simplification is a way to
determine the bug. The idea behing simplification is to minimize the failing
input, so that it will be easier to understand what inputs causes the bug.
*Simplification* can be reached by *Divide-and-Conquer*, where you *->*
+ Cut away one half of the test input
+ Check if any of the halves still exhibit failure.
+ Repeat, until minimal input has been found.
Although this works in some scenarios, this method has the following problems
*->*
- Tedious to re-run test manually
- Boring, cut and paste, re-run ...
- What, if none of the halves exhibits a failure?
Because of the problems with *Divide-and-Conquer*, in most cases automation of
input simplificartion is more favourable.
=== AUTOMATION OF INPUT SIMPLIFICATION
Automation of input simplification in debugging involves using tools or
algorithm to automatically reduce the complexity of input data. This helps
identify and isolate bugs more efficiently, especially in large or complex
software systems.
One exampel of such a algorrithm is *Delta Debugging*. Delta debugging is a
software debugging technique that aims to isolate and identify the cause of a
failure in a program by systematically narrowing down the input that triggers
the failure. The term "delta" refers to the minimal change needed to reproduce
the failure.
The algorithm *Delta debugging* or *DD-Min* as it is also called, works as seen
in figure 4 below.
#figure(
image("figures/deltaDebugging.png", width: 80%),
caption: [Delta Debugging],
) <ripr_model>
=== Short Quiz On Delta debugging
*Question :*
Suppose test(c) returns FAIL whenever ccontains two or more occurrences of the
letter X. Apply the ddMin algorithm to minimise the failing input array [X, Z,
Z, X] . Write down each step of the algorithm, and the values of n (number of
chunks). Initially, n is 2.
*Solution :*
#figure(
image("figures/solution-ddmin.png", width: 80%),
caption: [Delta Debugging Quiz Answer],
) <ripr_model>
== Observing outcome, State Inspection
Mainly there are three diffrent ways to perform state inspections of a program
*->*
- *Simple logging :* print statements
- *Advanced loggin :* configureable what is printed based on level (e.g. OFF <
FINE < INFO < WARNING < SEVERE), using e.g. Java’s logging package.
- *Debugging tools :* e.g. Eclipse debugger or the Java debugger jbd (hand-in
assignment 2)
=== The Quick-And-Dirty Approach : Print Logging
- *Manually add prit statements at code locations to be observed*
- System.out.println(“size = "+ size);
*Pros ->*
- Simple and easy.
- No tools or infrastructure needed, works on any platform.
*Cons ->*
- Code cluttering.
- Output cluttering.
- Performance penalty, possibly changed behaviour (real time apps).
- Buffered output lost on crash
- Source code access required, recompilation necessary.
=== BASIC LOGGING IN JAVA
- Each class can have its own logger-object.
- Each logger has level:
- OFF < FINE... < INFO < WARNING < SEVERE
- Setting the level controls which messages gets written to log.
- Quick Demo: Dubbel.java
*Pros ->*
- Output cluttering can be mastered
- Small performance overhead
- Exceptions are loggable
- Log complete up to crash
- Etc.
*Cons ->*
- Code cluttering - don’t try to log everything
=== Using Debuggers
Assume we have found a small failing test case and identified the faulty
component.
* Basic Functionality of a Debugger*
- Execution Control: Stop execution at specific locations, breakpoints
- Interpretation: Step-wise execution of code
- State Inspection: Observe values of variables and stack
- State Change: Change state of stopped program
- Debugging tools: Eclipse GUI debugger or the Java debugger jbd
= Formal Specification
Describing contracts of units (methods) in a mathematically precise (formal)
language.
Motivation:
- Higher degree of precision
- Automation of program analysis
- program verification
- static checking
- test case generation
== Unit specification
Methods can be specified by referring to:
- result value
- initial values of formal parameters
- pre-state and post-state
== Writing formal Specifications
When writing a formal specification one should list the required pre and
post-conditions. How to find these and formalize them can be tricky.
#example[
Consider the very informal specification of `enterPIN (pin:int)`:
_"Enter the PIN that belongs to the currently inserted bank card into the ATM,
when not yet authenticated. If a wrong PIN is entered three times in a row, the
card is invalidated and confiscated. After having entered the correct PIN, the
customer is regarded as authenticated."_
Contract states _what is guaranteed_ (postcondition), _under which conditions_ (precondition).
Preconditions:
- Card is inserted, user not yet authenticated.
Postconditions:
- If PIN is correct, then the user is authenticated.
- If PIN is incorrect and `wrongPINCounter` was $<2$ when entering the method,
then `wrongPINCounter` is increased by $1$ and user is not authenticated.
- If PIN is incorrect and `wrongPINCounter` was $>=2$ when entering the method,
then card is conficaded and user is not authenticated.
There are also some implicit ones:
Implicit preconditions:
- ATM card slot is free
- Card is valid
- Card is not null
Implicit postconditons:
- ATM card slot is occupied
- User is not authenticated
- `wrongPINCounter` is $0$
]<formal_spec_ex>
#important[Implicit pre/postconditions should also be formalised, for example that the
arguments of a method should not be null, as shown in the above example]
== Validity
In context of formal specification, we want to know if some *formula hold true
in a particular program state.*
- A formula is *valid* if it is true in *all possible states*
- Valid formulas are *useful to simplify other formulas*
- *A formula is satisfiable if it is true at least once*
#example[
The following *useful* formulas are valid, i.e. you can replace the formula on
the left side by the one on the right.
1. $not(exists x: t. med P) <-> forall x: t. med not P$
2. $not(forall x: t. med P) <-> exists x: t. med not P$
3. $(forall x: t. med P and Q) <-> (forall x: t. med P) and (forall x: t. med Q)$
4. $(exists x: t. med P or Q) <-> (exists x: t. med P) or (exists x: t. med Q)$
#figure(
image("figures/useful_formulas.png", width: 90%),
caption: [Some other useful valid formulas],
)<useful_formulas>
]
= Dafny
Object oriented language desinged to make it easy to write *correct* code.
- Allow annotations specifying program behaviour, as part of the language.
- Automatically proves that the code adheres to specications.
- Absence of run-time errors, e.g. null-pointers, index-out-of-bounds etc.
- Termination checking of loops.
== Fields
Declaring fields.
- Variables declared with keyword `var`
- Type annotations given by `:`
- Assignment written `:=`
- Several variables can be declared at once.
- Parallel assignments possible.
#sourcecode[```js
var insertedCard : BankCard?;
var wrongPINCounter : int;
var customerAuthenticated : bool;
```]
#sourcecode[```js
var x : int;
x := 34;
var y, z := true, false //parallel assignment
```]
#note[The prefix `?` clarifies that the field is allowed to be `null`. ]
== Constructor
Example of a constructor.
#sourcecode[```js
constructor (n: int)
modifies this
{
...
}
```]
== Methods
Example of some methods
#sourcecode[```js
method insertCard (card : BankCard){ ... }
method enterPIN (pin : int) { ... }
method add (num1 : int, num2 : int) returns (result : int) { ... }
```]
== Propositional logic
All variables $P, Q, R$ (aka propositions) are booleans, i.e. take values True
or False.
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*Connectiv*],
[*Meaning*],
[*Dafny*],
[$not P$],
[not $P$],
[`!P`],
[$P and Q$],
[$P$ and $Q$],
[`P && Q`],
[$P or Q$],
[$P$ or $Q$],
[`P || Q`],
[$P -> Q$],
[$P$ implies $Q$],
[`P ==> Q`],
[$P <-> Q$],
[$P$ is equivalent to $Q$],
[`P <==> Q`],
)
== First order logic: Quantifiers
Writing quantifiers in Dafny.
#table(
columns: (auto, auto, auto),
inset: 10pt,
align: horizon,
[*Connectiv*],
[*Meaning*],
[*Dafny*],
[$forall x: t. med P$],
[For all $x$ of type $t$, $P$ holds],
[`forall x : t :: P`],
[$exists x: t. med P$],
[There exists an $x$ of type $t$, such that $P$ holds],
[`exists x : t :: P`],
)
#example[
The array `a` only holds values less than or equal to $2$
#sourcecode[```java
forall i : int :: 0 <= i < a.Length ==> arr[i] <= 2;
```]
At least one entry holds the value $1$
#sourcecode[```java
exists i : int :: 0 <= i < a.Length && a[i] == 1
```]
]
== Requires & Ensures
The `requires` and `ensures` prefixes represents pre/postconditions which can
consist of:
- quantifiers, logic connectives
- functions ( `function fibonacci`, etc. )
- predicates
They have no impact on runtime and are just for checking the validity of the
program.
#sourcecode[```java
method example(x : int, y : int) returns (m : int)
requires x >= 0 && y < = // precondition
ensures m <= 0 // postcondition
{ return y*x }
```]
== Classes
- Keyword `class`
- No access modifiers like public, private, etc.
- Fields declared by `var` keyword (local variables)
- Objects declared with `new` keyword + `constructor` methods
- Can have one anonymous (unamed constructor) + several named ones.
#sourcecode[```java
class MyClass {
var field : int;
constructor() {
field := 0;
}
constructor Init(x : int) {
field := x;
}
constructor Init2(x : int, y :int) {
field := x + y;
}
}
```]
#sourcecode[```java
var myObject := new MyClass();
var myObject2 := new MyClass.Init(5);
var myObject3 := new MyClass.Init2(5, 6)
```]
#pagebreak()
== Assertions
- Keyword `assert`
- Placed in method body
- Written in specification language
- Evaluated at compile-time
Dafny tries to prove *assertion hold for all executions of code*.
#sourcecode[```java
method Abs(x : int) returns (r : int)
ensures 0 <= r {
if (x < 0) {r := -x;}
else {r := x;}
}
method Test() {
var v := Abs(-3)
assert 0 <= v;
}
```]
#note[Assertions can only be proved based on the annotions (`requires`, `ensures`) of
other methods. The previous method `test` works because the assertion is based
on the `ensures` of the method `Abs`.
The following test case would not work:
#sourcecode[```java
method Test() {
var v := Abs(-3)
assert v == 3;
}
```]
This is because Dafny only knows that `Abs` returns a value greater than or
equal to 0. It does not know that it returns 3.
However, if we edit the postcondition to the following:
#sourcecode[```java
ensures 0 <= x ==> r == x; // result same as x for positive input x
ensures x < 0 ==> r == -x; // result positive x for negative input x
```]
Then the test case would work. Dafny now knows that if $x$ is negative, the
result will be $-x$ (positive $x$).]
== (Ghost) Functions
Part of the specification language, thus functions cannot modify objects and
write to memory (unlike methods). _so it is SAFE to use in spec_.
- Can only be used in spec (annotations)
- Single unnamed return value
- body is a single statement (no semicolon)
#sourcecode[```java
ghost function abs (x : int) : int {
if x < 0 then -x else x
}
```]
Now we can use `abs` in our specification.
#sourcecode[```java
method Abs(x : int) returns (r : int)
ensures r == abs(x) {
if (x < 0) {r := -x;}
else {r := x;}
}
```]
== Function methods
A function method can be used in both spec and execution. If we consider the
previus method `Abs`, it might not even be necessary.
#sourcecode[```java
function abs (x : int) : int {
if x < 0 then -x else x
}
method Test() {
var v := abs(-3)
assert v == 3;
}
```]
#note[Dafny remembers function method bodies, unlike methods.]
== Predicates
Recall, a predicate in first-order logic is a function returning a boolean
value. In Dafny, predicates are used similarly to functions. They can be used
both in spec and execution.
#sourcecode[```java
ghost predicate isEven (x : int) { x % 2 == 0}
```]
is equivalent to
#sourcecode[```java
ghost function isEven (x : int) : bool { x % 2 == 0 }
```]
and
#sourcecode[```java
predicate isEven (x : int) { x % 2 == 0}
```]
is equivalent to
#sourcecode[```java
function isEven (x : int) : bool { x % 2 == 0 }
```]
#pagebreak()
== Modifies & Reads clauses
Automated proofs are hard and can be slow. In Dafny, this means that we need to
add certain annotations to help.
- Dafny methods manipulating objects must declare what fields they might modify.
- Dafny functions/predicates must declare what memory locations (objects) they
might read.
#sourcecode[```java
class BankCard {
var pin : int;
var accNo : int;
var valid : bool;
...
predicate isValid()
reads this`valid; // read clause
{ this.valid }
method invalidateCard()
modifies this`valid; // modifies clause
ensures !isValid();
{ valid := false;}
...
}
```]
#note[back-tick character is used to refer to fields of the object (class) such as
int, bool, etc. In the case of objects inside the class this is not needed.]
== Old keyword
old-keyword in specification refers to the *value of a field before the method
was called*.
#example[`old(wrongPINCounter)` refers to its value before `insertPIN` method was called.]
== Arrays
Declaring and initialising an array
#sourcecode[```java
var a : array<int>;
a := new int[3];
assert a.Length == 3;
a[0], a[1], a[2] := 0, 0, 0;
```]
Declaring a matrix
#sourcecode[```java
var matrix : array2<int>;
matrix := new int[3, 4];
assert matrix.Length0 == 3 && matrix.Length1 == 4;
```]
#pagebreak()
Parallel assignment: set all entries to $0$
#sourcecode[```java
forall(i | 0 <= i < a.Length)
{a[i] := 0;}
forall (i,j | 0 <= i < m.Length0 && 0 <= j < m.Length1)
{m[i,j] := 0; }
```]
Parallel assignment: increment all entries by $1$. Note that all right-hand side
expressions is evaluated before assignments.
#sourcecode[```java
forall(i | 0 <= i < a.Length)
{a[i] := a[i] + 1;}
```]
|
|
https://github.com/herbertskyper/HITsz_Proposal_report_Template | https://raw.githubusercontent.com/herbertskyper/HITsz_Proposal_report_Template/main/main.typ | typst | MIT License | #import "templates/thesis.typ":*
#import "utils/utils.typ":*
#import "pages/cover.typ": cover
#import "pages/outline.typ": outline-page
//页面整体设置
#show :it => conf(it)
//封面
#cover(project_name: "1",
name: "1",
student_id: "1",
tel_student: "1",
email_student: "1",
collage_student: "1",
mentor: "1",
profession: "1",
tel_mentor: "1",
email_mentor: "1",
collage_mentor: "1",
date:auto
)
//目录
#pagebreak()
#outline-page(title: "1",)
//第一部分
#pagebreak()
#report_title(title_content:"一、项目团队成员",title_tips:"包括项目负责人、按顺序")
#table(
columns: (1fr, 1fr, 1fr,1fr, 1fr),
rows: (auto,auto,auto,auto),
inset: 8pt,
align: horizon + center,
[姓名], [所在学院], [学号],[联系电话],[本人签字],
[张三],[基础学部],[1234567893],[114514114514],
image("figures/test1.png", width: 2.7cm,height:1.5cm),
[],[],[],[],
image("figures/test1.png", width: 2.7cm,height:1.5cm),
[],[],[],[],
image("figures/test1.png", width: 2.7cm,height:1.5cm),
[],[],[],[],
image("figures/test1.png", width: 2.7cm,height:1.5cm),
)
//第二部分
#report_title(title_content:"二、立项报告",title_tips:"字数在2000字以上,篇幅不够可附页")
//自动生成的页面框
#[#show: block_content
= 一级标题
== 二级标题
=== 三级标题
==== 四级标题
===== 五级标题
===== 一级标题
=== test
=== test
== test
=== test
== test
测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
测试
#lorem(600)
]
//固定生成的页面框
// #rect_content(content: [
// ]
// ,height: 11.2cm)
// #rect_content(content:[
// ])
//第三、四部分
#pagebreak()
#report_title(title_content:"三、指导教师意见")
#rect_content(content:[
#v(14em)
#set align(right)
#[
#set text(font: "宋体", size: 字号.四号)
签 #h(1em) 名: #h(6em) //请修改此处
]
#v(1em)
#[
#set text(font: "宋体", size: 字号.小四)
年#h(1em)月#h(1em)日#h(0.7em)//请修改此处
]
],height:9cm)
\
#report_title(title_content:"四、评审专家组意见")
#rect_content(content:[
#v(14em)
#set align(right)
#[
#set text(font: "宋体", size: 字号.四号)
批准经费: #h(5em)元 #h(5em)组长签名: #h(7em)//请修改此处
]
#v(1.5em)
#[
#set text(font: "宋体", size: 字号.小四)
年#h(1em)月#h(1em)日#h(0.7em)//请修改此处
]
],height:9.5cm)
|
https://github.com/Han-duoduo/mathPater-typest-template | https://raw.githubusercontent.com/Han-duoduo/mathPater-typest-template/main/chapter/appendix.typ | typst | Apache License 2.0 | #import "../template/template.typ":*
#let code1 = ```matlab
clc;clear;close all;
%导入数据
data=importdata('DATA.mat');%需要优化小区编号,频点及现网PCI的信息
MR1=importdata('MR1.mat');%有关小区间冲突及干扰MR值
MR2=importdata('MR2.mat');%有关小区间混淆MR值
A=zeros(2067); B=A; C=B;%预先分配A,B,C矩阵维度
%数据清理
id=ismember(MR1(:,1:2),data(:,1));%将附件一和附件二进行比较,找到不需要优化小区并用0-1表示
[row,~]=find(~id);%找出所有0所在的行数
row=sort(row);%将行数升序处理
MR1(row,:)=[];%删去0所在的行数只保留优化小区
id=ismember(MR2(:,1:2),data(:,1));%将附件一和附件三进行比较,同上
[row,~]=find(~id);
row=sort(row);
MR2(row,:)=[];
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2067
N=ismember(MR1(:,1),data(i,1));%查找附件二中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2067
M=ismember(MR1(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件二中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件二中没有给出MR值,则认为0
A(i,j)=0;
else %若相同,则将附件二的对应冲突MR值填入冲突矩阵
A(i,j)=MR1(M,3);
end
else %若频点不同,则两者之间不发生干扰,则为0
A(i,j)=0;
end
end
LN=find(ismember(MR1(:,1),MR1(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区干扰,则为0
A(i,:)=0;
end
end
```
#let code2 = ```matlab
clc;clear;close all;
%导入数据
data=importdata('DATA.mat');%需要优化小区编号,频点及现网PCI的信息
MR1=importdata('MR1.mat');%有关小区间冲突及干扰MR值
MR2=importdata('MR2.mat');%有关小区间混淆MR值
A=zeros(2067); B=A; C=B;%预先分配A,B,C矩阵维度
%数据清理
id=ismember(MR1(:,1:2),data(:,1));%将附件一和附件二进行比较,找到不需要优化小区并用0-1表示
[row,~]=find(~id);%找出所有0所在的行数
row=sort(row);%将行数升序处理
MR1(row,:)=[];%删去0所在的行数只保留优化小区
id=ismember(MR2(:,1:2),data(:,1));%将附件一和附件三进行比较,同上
[row,~]=find(~id);
row=sort(row);
MR2(row,:)=[];
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2067
N=ismember(MR2(:,1),data(i,1));%查找附件三中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2067
M=ismember(MR2(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件三中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件三中没有给出MR值,则认为0
B(i,j)=0;
else %若相同,则将附件三的对应混淆MR值填入混淆矩阵
B(i,j)=MR2(M,3);
end
else %若频点不同,则两者之间不发生干扰,则为0
B(i,j)=0;
end
end
LN=find(ismember(MR2(:,1),MR2(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区混淆,则为0
B(i,:)=0;
end
end
```
#let code3 = ```matlab
clc;clear;close all;
%导入数据
data=importdata('DATA.mat');%需要优化小区编号,频点及现网PCI的信息
MR1=importdata('MR1.mat');%有关小区间冲突及干扰MR值
MR2=importdata('MR2.mat');%有关小区间混淆MR值
A=zeros(2067); B=A; C=B;%预先分配A,B,C矩阵维度
%数据清理
id=ismember(MR1(:,1:2),data(:,1));%将附件一和附件二进行比较,找到不需要优化小区并用0-1表示
[row,~]=find(~id);%找出所有0所在的行数
row=sort(row);%将行数升序处理
MR1(row,:)=[];%删去0所在的行数只保留优化小区
id=ismember(MR2(:,1:2),data(:,1));%将附件一和附件三进行比较,同上
[row,~]=find(~id);
row=sort(row);
MR2(row,:)=[];
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2067
N=ismember(MR1(:,1),data(i,1));%查找附件二中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2067
M=ismember(MR1(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件二中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件二中没有给出MR值,则认为0
C(i,j)=0;
else %若相同,则将附件二的对应干扰MR值填入干扰矩阵
C(i,j)=MR1(M,4);
end
else %若频点不同,则两者之间不发生干扰,则为0
C(i,j)=0;
end
end
LN=find(ismember(MR1(:,1),MR1(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区干扰,则为0
C(i,:)=0;
end
end
```
#let code4 = ```matlab
clc,clear,close all;
A=importdata('A.mat');
B=importdata('B.mat');
C=importdata('C.mat');
% 蒙特卡洛模拟
n = 10^5; % 模拟次数
sol = []; % 保存满足约束条件的解
fval = +inf; % 保存最小值
for i = 1:n
rng('shuffle')
a=randi([0,1007],1,2067);
b=zeros(1008,2067);
x=zeros(2067);
y=zeros(2067);
for k=0:1007 %将相同PCI的小区筛选出来
b=find(a==k);%得到相同小区的序号
x(b,b)=1; %创建x矩阵
end
c=mod(a,3);%将现有PCI进行mod 3处理
for m=0:2 %将相同mod值的小区筛选出来
d=find(c==m);%得到相同小区的序号
y(d,d)=1; %创建y矩阵
end
s1=sum(sum(x.*A));
s2=sum(sum(x.*B));
s3=sum(sum(y.*C));
f=s1+s2+s3 % 计算目标函数值
if f < fval % 更新最小值
fval = f;
sol = a;
end
end
```
#let code5 = ```matlab
clc,clear,close all;
A=importdata('A.mat');
B=importdata('B.mat');
C=importdata('C.mat');
% 蒙特卡洛模拟
n = 10^2; % 模拟次数
sol1 = [];% 保存满足约束条件的解
sol2 = [];
sol3 = [];
fval1 = inf; % 保存最小值
fval2 = inf;
fval3 = +inf;
x1=[];%保存x矩阵
for i = 1:n
rng('shuffle')
a=randi([0,1007],1,2067);
b=zeros(1008,2067);
x=zeros(2067);
for k=0:1007 %将相同PCI的小区筛选出来
b=find(a==k);%得到相同小区的序号
x(b,b)=1; %创建x矩阵
end
s1=sum(sum(x.*A));%用x矩阵求得冲突数
if s1 < fval1 % 更新最小值
fval1 = cat(1,fval1,s1);%记录每次更新的冲突数
sol1 = cat(1,sol1,a); %记录每次更新对应的PCI值
x1=cat(1,x1,x); %记录每次更新对应的x矩阵
else
if s1<80000
fval1 = cat(1,fval1,s1);%记录每次更新的冲突数
sol1 = cat(1,sol1,a); %记录每次更新对应的PCI值
x1=cat(1,x1,x); %记录每次更新对应的x矩阵
end
end
hold on
scatter(0,s1)%做出每次冲突的图像
xlim([-1,1]);
ylim([30000,90000]);
end
fval1(1,:)=[];
for q=1:5
s2=sum(sum(x1(end-(6-q)*2067+1:end-(5-q)*2067,:).*B))%取靠前5组的PCI进行混淆数的计算
if s2<fval2% 更新最小数
fval2=cat(1,fval2,s2);%记录每次更新的混淆数
sol2=cat(1,sol2,sol1(end-(5-q),:));%记录每次对应的PCI值
else
if s2<300000
fval2=cat(1,fval2,s2);%记录每次更新的混淆数
sol2=cat(1,sol2,sol1(end-(5-q),:));%记录每次对应的PCI值
end
end
end
fval2(1,:)=[];
for j=1:3 %取靠前三组的PCI进行干扰数的计算
c=mod(sol2(end-(3-j),:),3);%将现有PCI进行mod 3处理
y=zeros(2067);
for m=0:2 %将相同mod值的小区筛选出来
d=find(c==m);%得到相同小区的序号
y(d,d)=1; %创建y矩阵
end
s3=sum(sum(y.*C))%用y矩阵计算此时的干扰数
if s3<fval3% 更新最小数
fval3=s3;%记录此时的最小干扰数
sol3=sol2(end-(3-j),:);%记录此时的PCI
end
y=zeros(2067);
end
```
#let code6=```matlab
clc,clear,close all;
all=importdata('all.mat');
MR1=importdata('MR1.mat');
MR2=importdata('MR2.mat');
%清洗数据
id=ismember(all(:,1),MR1(:,1:2));%将附件一与附件二进行比较,在附件一中用0—1标记出没有在附件二中出现过的
row=find(~id);
all(row,:)=[];
data=all;%删去所有附件一中其他小区的数据
A=zeros(2857);
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2857
N=ismember(MR1(:,1),data(i,1));%查找附件二中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2857
M=ismember(MR1(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件二中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件二中没有给出MR值,则认为0
A(i,j)=0;
else %若相同,则将附件二的对应冲突MR值填入冲突矩阵
A(i,j)=MR1(M,3);
end
else %若频点不同,则两者之间不发生干扰,则为0
A(i,j)=0;
end
end
LN=find(ismember(MR1(:,1),MR1(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区干扰,则为0
A(i,:)=0;
end
end
```
#let code7 = ```matlab
clc,clear,close all;
all=importdata('all.mat');
MR1=importdata('MR1.mat');
MR2=importdata('MR2.mat');
%清洗数据
id=ismember(all(:,1),MR2(:,1:2));%将附件一与附件三进行比较,在附件一中用0—1标记出没有在附件三中出现过的
row=find(~id);
all(row,:)=[];
data=all;
B=zeros(2857);
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2802
N=ismember(MR2(:,1),data(i,1));%查找附件二中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2802
M=ismember(MR2(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件二中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件二中没有给出MR值,则认为0
B(i,j)=0;
else %若相同,则将附件二的对应冲突MR值填入冲突矩阵
B(i,j)=MR2(M,3);
end
else %若频点不同,则两者之间不发生干扰,则为0
B(i,j)=0;
end
end
LN=find(ismember(MR2(:,1),MR2(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区干扰,则为0
B(i,:)=0;
end
end
```
#let code8 = ```matlab
clc,clear,close all;
all=importdata('all.mat');
MR1=importdata('MR1.mat');
MR2=importdata('MR2.mat');
%清洗数据
id=ismember(all(:,1),MR1(:,1:2));%将附件一与附件二进行比较,在附件一中用0—1标记出没有在附件二中出现过的
row=find(~id);
all(row,:)=[];
data=all;%删去所有附件一中其他小区的数据
C=zeros(2857);
%构造矩阵
LN=1;%LN为每次筛选行数的开始,随循环次数增多,减少搜索量
for i =1:2857
N=ismember(MR1(:,1),data(i,1));%查找附件二中每一个主控小区的邻小区个数,用0—1表示
if sum(N)~=0 %若邻小区个数不为0
N=find(N); %则将0—1矩阵转换成具体邻小区个数
N=N(end);
for j =1:2857
M=ismember(MR1(LN:N,2),data(j,1));%则记录邻小区出现在附件一当中的行数,用0—1表示
if sum(M)==0 %若附件一按顺序当中出现的小区不在附件二中,即没有MR值
M=sum(M); %令M=0
else %若存在于附件一当中
M=find(M)+LN-1;%将0—1的矩阵转换成具体的行数
end
if data(j,2)==data(i,2)%再判断主控小区与邻小区是否频点相同
if M==0 %若相同,但附件二中没有给出MR值,则认为0
C(i,j)=0;
else %若相同,则将附件二的对应冲突MR值填入冲突矩阵
C(i,j)=MR1(M,4);
end
else %若频点不同,则两者之间不发生干扰,则为0
C(i,j)=0;
end
end
LN=find(ismember(MR1(:,1),MR1(LN,1)));%则将LN值适量增加,减少搜索量
LN=LN(end)+1
else %若邻小区个数为0,则不与任何小区干扰,则为0
C(i,:)=0;
end
end
```
#let code9 = ```matlab
clc,clear,close all;
A=importdata('Q3A.mat');
B=importdata('Q3B.mat');
C=importdata('Q3C.mat');
% 蒙特卡洛模拟
n = 10^4; % 模拟次数
sol = []; % 保存满足约束条件的解
fval = +inf; % 保存最小值
for i = 1:n
rng('shuffle')
a=randi([0,1007],1,2857);
b=zeros(1008,2857);
x=zeros(2857);
y=zeros(2857);
for k=0:1007 %将相同PCI的小区筛选出来
b=find(a==k);%得到相同小区的序号
x(b,b)=1; %创建x矩阵
end
c=mod(a,3);%将现有PCI进行mod 3处理
for m=0:2 %将相同mod值的小区筛选出来
d=find(c==m);%得到相同小区的序号
y(d,d)=1; %创建y矩阵
end
s1=sum(sum(x.*A));
s2=sum(sum(x.*B));
s3=sum(sum(y.*C));
f=s1+s2+s3 % 计算目标函数值
if f < fval % 更新最小值
fval = f;
sol = a;
end
end
```
#let code10 = ```matlab
clc,clear,close all;
A=importdata('Q3A.mat');
B=importdata('Q3B.mat');
C=importdata('Q3C.mat');
% 蒙特卡洛模拟
n = 10^4; % 模拟次数
sol1 = [];% 保存满足约束条件的解
sol2 = [];
sol3 = [];
fval1 = inf; % 保存最小值
fval2 = inf;
fval3 = +inf;
x1=[];%保存x矩阵
for i = 1:n
rng('shuffle')
a=randi([0,1007],1,2857);
b=zeros(1008,2857);
x=zeros(2857);
for k=0:1007 %将相同PCI的小区筛选出来
b=find(a==k);%得到相同小区的序号
x(b,b)=1; %创建x矩阵
end
s1=sum(sum(x.*A));%用x矩阵求得冲突数
if s1 < fval1 % 更新最小值
fval1 = cat(1,fval1,s1);%记录每次更新的冲突数
sol1 = cat(1,sol1,a); %记录每次更新对应的PCI值
x1=cat(1,x1,x); %记录每次更新对应的x矩阵
else
if s1<80000
fval1 = cat(1,fval1,s1);%记录每次更新的冲突数
sol1 = cat(1,sol1,a); %记录每次更新对应的PCI值
x1=cat(1,x1,x); %记录每次更新对应的x矩阵
end
end
hold on
scatter(0,s1)%做出每次冲突的图像
xlim([-1,1]);
ylim([50000,120000]);
end
fval1(1,:)=[];
figure
for q=1:5
s2=sum(sum(x1(end-(6-q)*2857+1:end-(5-q)*2857,:).*B))%取靠前5组的PCI进行混淆数的计算
if s2<fval2% 更新最小数
fval2=cat(1,fval2,s2);%记录每次更新的混淆数
sol2=cat(1,sol2,sol1(end-(5-q),:));%记录每次对应的PCI值
else
if s2<1200000
fval2=cat(1,fval2,s2);%记录每次更新的混淆数
sol2=cat(1,sol2,sol1(end-(5-q),:));%记录每次对应的PCI值
end
end
hold on
scatter(0,s2)%做出每次冲突的图像
xlim([-1,1]);
ylim([900000,1500000]);
end
fval2(1,:)=[];
for j=1:3 %取靠前三组的PCI进行干扰数的计算
c=mod(sol2(end-(3-j),:),3);%将现有PCI进行mod 3处理
y=zeros(2857);
for m=0:2 %将相同mod值的小区筛选出来
d=find(c==m);%得到相同小区的序号
y(d,d)=1; %创建y矩阵
end
s3=sum(sum(y.*C))%用y矩阵计算此时的干扰数
if s3<fval3% 更新最小数
fval3=s3;%记录此时的最小干扰数
sol3=sol2(end-(3-j),:);%记录此时的PCI
end
end
```
#let codeZip = (
问题一清洗数据加构建冲突矩阵A:code1,
问题一洗数据加构建混淆矩阵B:code2,
问题一清洗数据加构建干扰矩阵C:code3,
问题一蒙特卡洛模拟进行求解:code4,
问题二蒙特卡洛模拟求解分层多目标规划问题:code5,
问题三清洗数据加构建冲突矩阵D:code6,
问题三清洗数据加构建混淆矩阵E:code7,
问题三清洗数据加构建干扰矩阵F:code8,
问题三蒙特卡洛模拟:code9,
问题四蒙特卡洛模拟求解分层多目标规划问题:code10
)
= 附录
// #codeAppendix(
// code1,
// caption: [清洗数据加构建冲突矩阵A],
// )
#for (desc,code) in codeZip{
codeAppendix(
code,
caption: desc
)
v(2em)
}
#let code = ```cpp
#include<iostream>
using namespace std;
cout << "hello World!" << endl;
```
#codeAppendix(
code,
caption:[问题1的示例代码]
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/hust-typst-template/sample.typ | typst | Apache License 2.0 | // https://github.com/werifu/HUST-typst-template/blob/1ef0a73007b0827e04dbe00b0849890a94eace42/sample.typ
#let heiti = ("Times New Roman", "Heiti SC", "Heiti TC", "SimHei")
#let songti = ("Times New Roman", "Songti SC", "Songti TC", "SimSun")
#let zhongsong = ("Times New Roman", "Songti SC")
#let bib_cite(..name) = {
super(cite(..name))
}
#let indent() = {
box(width: 2em)
}
#let indent_par(body) = {
box(width: 1.8em)
body
}
#let equation_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("equation-chapter" + str(chapt))
let n = c.at(loc).at(0)
"(" + str(chapt) + "-" + str(n + 1) + ")"
})
}
#let table_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("table-chapter" + str(chapt))
let n = c.at(loc).at(0)
str(chapt) + "-" + str(n + 1)
})
}
#let image_num(_) = {
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("image-chapter" + str(chapt))
let n = c.at(loc).at(0)
str(chapt) + "-" + str(n + 1)
})
}
#let equation(equation, caption: "") = {
figure(
equation,
caption: caption,
supplement: [公式],
numbering: equation_num,
kind: "equation",
)
}
#let tbl(tbl, caption: "") = {
figure(
tbl,
caption: caption,
supplement: [表],
numbering: table_num,
kind: "table",
)
}
#let img(img, caption: "") = {
figure(
img,
caption: caption,
supplement: [图],
numbering: image_num,
kind: "image",
)
}
#let empty_par() = {
v(-1em)
box()
}
// inspired from https://github.com/lucifer1004/pkuthss-typst.git
#let chinese_outline() = {
align(center)[
#text(font: heiti, size: 18pt, "目 录")
]
set text(font: songti, size: 12pt)
// 临时取消目录的首行缩进
set par(leading: 1.24em, first-line-indent: 0pt)
locate(loc => {
let elements = query(heading.where(outlined: true), loc)
for el in elements {
// 是否有 el 位于前面,前面的目录中用拉丁数字,后面的用阿拉伯数字
let before_toc = query(heading.where(outlined: true).before(loc), loc).find((one) => {one.body == el.body}) != none
let page_num = if before_toc {
numbering("I", counter(page).at(el.location()).first())
} else {
counter(page).at(el.location()).first()
}
link(el.location())[#{
// acknoledgement has no numbering
let chapt_num = if el.numbering != none {
numbering(el.numbering, ..counter(heading).at(el.location()))
} else {none}
if el.level == 1 {
set text(weight: "bold")
if chapt_num == none {} else {
chapt_num
" "
}
el.body
} else {
chapt_num
" "
el.body
}
}]
// 填充 ......
box(width: 1fr, h(0.5em) + box(width: 1fr, repeat[.]) + h(0.5em))
[#page_num]
linebreak()
}
})
}
// 原创性声明和授权书
#let declaration() = {
set text(font: songti, 12pt)
v(3em)
align(center)[
#text(font: heiti, size: 18pt)[
学位论文原创性声明
]
]
text(font: songti, size: 12pt)[
#set par(justify: false, leading: 1.24em, first-line-indent: 2em)
本人郑重声明:所呈交的论文是本人在导师的指导下独立进行研究所取得的 研究成果。除了文中特别加以标注引用的内容外,本论文不包括任何其他个人或集体已经发表或撰写的成果作品。本人完全意识到本声明的法律后果由本人承担。
]
v(2em)
align(right)[
#text("作者签名: 年 月 日")
]
v(6em)
align(center)[
#text(font: heiti, size: 18pt)[
学位论文版权使用授权书
]
]
text(font: songti, size: 12pt)[
#set par(justify: false, leading: 1.24em, first-line-indent: 2em)
本学位论文作者完全了解学校有关保障、使用学位论文的规定,同意学校保留并向有关学位论文管理部门或机构送交论文的复印件和电子版,允许论文被查阅和借阅。本人授权省级优秀学士论文评选机构将本学位论文的全部或部分内容编入有关数据进行检索,可以采用影印、缩印或扫描等复制手段保存和汇编本学位论文。
学位论文属于 1、保密 □,在#h(3em)年解密后适用本授权书。
#h(6.3em) 2、不保密 □
#h(6.3em)请在以上相应方框内打 “√”
]
v(3em)
align(right)[
#text("作者签名: 年 月 日")
]
align(right)[
#text("导师签名: 年 月 日")
]
}
// 参考文献
#let references(path) = {
// 这个取消目录里的 numbering
set heading(level: 1, numbering: none)
set par(justify: false, leading: 1.24em, first-line-indent: 2em)
bibliography(path, title:"参考文献")
}
// 致谢,请手动调用
#let acknowledgement(body) = {
// 这个取消目录里的 numbering
set heading(level: 1, numbering: none)
show <_thx>: {
// 这个取消展示时的 numbering
set heading(level: 1, numbering: none)
set align(center)
set text(weight: "bold", font: heiti, size: 18pt)
"致 谢"
} + empty_par()
[= 致谢 <_thx>]
body
}
// 中文摘要
#let zh_abstract_page(abstract, keywords: ()) = {
set heading(level: 1, numbering: none)
show <_zh_abstract_>: {
align(center)[
#text(font: heiti, size: 18pt, "摘 要")
]
}
[= 摘要 <_zh_abstract_>]
set text(font: songti, size: 12pt)
abstract
par(first-line-indent: 0em)[
#text(weight: "bold", font: heiti, size: 12pt)[
关键词:
#keywords.join(";")
]
]
}
// 英文摘要
#let en_abstract_page(abstract, keywords: ()) = {
set heading(level: 1, numbering: none)
show <_en_abstract_>: {
align(center)[
#text(font: heiti, size: 18pt, "Abstract")
]
}
[= Abstract <_en_abstract_>]
set text(font: songti, size: 12pt)
abstract
par(first-line-indent: 0em)[
#text(weight: "bold", font: heiti, size: 12pt)[
Key Words:
#keywords.join("; ")
]
]
}
#let project(
title: "",
abstract_zh: [],
abstract_en: [],
keywords_zh: (),
keywords_en: (),
school: "",
author: "",
id: "",
mentor: "",
class: "",
date: (1926, 8, 17),
body,
) = {
// 引用的时候,图表公式等的 numbering 会有错误,所以用引用 element 手动查
show ref: it => {
if it.element != none and it.element.func() == figure {
let el = it.element
let loc = el.location()
let chapt = counter(heading).at(loc).at(0)
// 自动跳转
link(loc)[#if el.kind == "image" or el.kind == "table" {
// 每章有独立的计数器
let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1
it.element.supplement
" "
str(chapt)
"-"
str(num)
} else if el.kind == "equation" {
// 公式有 '(' ')'
let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1
it.element.supplement
" ("
str(chapt)
"-"
str(num)
")"
} else {
it
}
]
} else {
it
}
}
// 图表公式的排版
show figure: it => {
set align(center)
if it.kind == "image" {
set text(font: heiti, size: 12pt)
it.body
it.supplement
" " + it.counter.display(it.numbering)
" " + it.caption
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("image-chapter" + str(chapt))
c.step()
})
} else if it.kind == "table" {
set text(font: heiti, size: 12pt)
it.supplement
" " + it.counter.display(it.numbering)
" " + it.caption
set text(font: songti, size: 10.5pt)
it.body
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("table-chapter" + str(chapt))
c.step()
})
} else if it.kind == "equation" {
// 通过大比例来达到中间和靠右的排布
grid(
columns: (20fr, 1fr),
it.body,
align(center + horizon,
it.counter.display(it.numbering)
)
)
locate(loc => {
let chapt = counter(heading).at(loc).at(0)
let c = counter("equation-chapter" + str(chapt))
c.step()
})
} else {
it
}
}
set page(paper: "a4", margin: (
top: 2.5cm,
bottom: 2.5cm,
left: 3cm,
right: 3cm
))
// 封面
align(center)[
// hust logo
#v(30pt)
#image("avatar-min-min.jpeg", width: 55%)
#v(50pt)
#text(
size: 36pt,
font: zhongsong,
weight: "bold"
)[本科生毕业设计(论文)]
#v(40pt)
#text(
font: heiti,
size: 22pt,
)[
#title
]
#v(100pt)
#let info_value(body) = {
rect(
width: 100%,
inset: 2pt,
stroke: (
bottom: 1pt + black
),
text(
font: zhongsong,
size: 16pt,
bottom-edge: "descender"
)[
#body
]
)
}
#let info_key(body) = {
rect(width: 100%, inset: 2pt,
stroke: none,
text(
font: zhongsong,
size: 16pt,
body
))
}
#grid(
columns: (70pt, 180pt),
rows: (40pt, 40pt),
gutter: 3pt,
info_key("院 系"),
info_value(school),
info_key("专业班级"),
info_value(class),
info_key("<NAME>"),
info_value(author),
info_key("学 号"),
info_value(id),
info_key("指导教师"),
info_value(mentor),
)
#v(40pt)
#text(
font: zhongsong,
size: 16pt,
)[
#date.at(0) 年 #date.at(1) 月 #date.at(2) 日
]
]
counter(page).update(0)
// 页眉
set page(
header: {
set text(font: songti, 10pt, baseline: 8pt, spacing: 3pt)
set align(center)
[华 中 科 技 大 学 毕 业 设 计 (论 文)]
line(length: 100%, stroke: 0.7pt)
}
)
// 页脚
// 封面不算页数
set page(
footer: {
set align(center)
grid(
columns: (5fr, 1fr, 5fr),
line(length: 100%, stroke: 0.7pt),
text(font: songti, 10pt, baseline: -3pt,
counter(page).display("I")
),
line(length: 100%, stroke: 0.7pt)
)
}
)
set text(font: songti, 12pt)
set par(justify: true, leading: 1.24em, first-line-indent: 2em)
show par: set block(spacing: 1.24em)
set heading(numbering: (..nums) => {
nums.pos().map(str).join(".") + " "
})
show heading.where(level: 1): it => {
set align(center)
set text(weight: "bold", font: heiti, size: 18pt)
set block(spacing: 1.5em)
it
}
show heading.where(level: 2): it => {
set text(weight: "bold", font: heiti, size: 14pt)
set block(above: 1.5em, below: 1.5em)
it
}
// 首段不缩进,手动加上 box
show heading: it => {
set text(weight: "bold", font: heiti, size: 12pt)
set block(above: 1.5em, below: 1.5em)
it
} + empty_par()
// 原创性声明
declaration()
pagebreak()
counter(page).update(1)
// 摘要
zh_abstract_page(abstract_zh, keywords: keywords_zh)
pagebreak()
// abstract
en_abstract_page(abstract_en, keywords: keywords_en)
pagebreak()
// 目录
chinese_outline()
// 正文的页脚
set page(
footer: {
set align(center)
grid(
columns: (5fr, 1fr, 5fr),
line(length: 100%, stroke: 0.7pt),
text(font: songti, 10pt, baseline: -3pt,
counter(page).display("1")
),
line(length: 100%, stroke: 0.7pt)
)
}
)
counter(page).update(1)
// 代码块(TODO: 加入行数)
show raw: it => {
set text(font: songti, 12pt)
set block(inset: 5pt, fill: rgb(217, 217, 217, 1), width: 100%)
it
}
body
}
// 三线表
#let tlt_header(content) = {
set align(center)
rect(
width: 100%,
stroke: (bottom: 1pt),
[#content],
)
}
#let tlt_cell(content) = {
set align(center)
rect(
width: 100%,
stroke: none,
[#content]
)
}
#let tlt_row(r) = {
(..r.map(tlt_cell).flatten())
}
#let three_line_table(values) = {
rect(
stroke: (bottom: 1pt, top: 1pt),
inset: 0pt,
outset: 0pt,
grid(
columns: (auto),
rows: (auto),
// table title
grid(
columns: values.at(0).len(),
..values.at(0).map(tlt_header).flatten()
),
grid(
columns: values.at(0).len(),
..values.slice(1).map(tlt_row).flatten()
),
)
)
}
#show: project.with(
title: "基于 ChatGPT 的狗屁通文章生成器",
author: "作者",
abstract_zh: [
先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
宫中府中,俱为一体;陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
],
abstract_en: [
The founding emperor passed away before his endeavor was half completed, and now the empire is divided into three parts. Yizhou is exhausted and in decline, and this is truly a critical moment of survival or destruction. However, the palace guards are tirelessly serving within, and loyal subjects are sacrificing themselves outside, all in order to repay the late emperor's kindness and show loyalty to the current emperor. It is appropriate to listen to wise advice, to honor the late emperor's virtues, to inspire the courage of loyal subjects, and not to belittle oneself or distort the truth, in order to keep the path of loyal counsel open.
The palace and government are one entity, and punishments should be consistent. If there are those who commit crimes or show loyalty and virtue, they should be judged by the legal system to demonstrate your fairness as emperor, rather than showing partiality that would create different laws for those inside and outside the palace.
],
keywords_zh: ("关键词1", "关键词2", "关键词3"),
keywords_en: ("Keyword 1", "Keyword 2", "Keyword 3"),
school: "复制粘贴写报告学院",
id: "U000114514",
mentor: "你的老板",
class: "XXXX 专业 0000 班",
date: (1926, 8, 17)
)
= 绪论
== typst 介绍
typst 是最新最热的标记文本语言,定位与 LaTeX 类似,具有极强的排版能力,通过一定的语法写文档,然后生成 pdf 文件。与 LaTeX 相比有以下的优势:
1. 编译巨快:因为提供增量编译的功能所以在修改后基本能在一秒内编译出 pdf 文件,typst 提供了监听修改自动编译的功能,可以像 Markdown 一样边写边看效果。
2. 环境搭建简单:原生支持中日韩等非拉丁语言,不用再大量折腾字符兼容问题以及下载好几个 G 的环境。只需要下载命令行程序就能开始编译生成 pdf。
3. 语法友好:对于普通的排版需求,上手难度跟 Markdown 相当,同时文本源码阅读性高:不会再充斥一堆反斜杠跟花括号
个人观点:跟 Markdown 一样好用,跟 LaTeX 一样强大
#img(
image("avatar-min-min.jpeg", height: 20%),
caption: "我的 image 实例 0",
)
== 基本语法
=== 代码执行
正文可以像前面那样直接写出来,隔行相当于分段。
个人理解:typst 有两种环境,代码和内容,在代码的环境中会按代码去执行,在内容环境中会解析成普通的文本,代码环境用{}表示,内容环境用[]表示,在 content 中以 \# 开头来接上一段代码,比如\#set rule,而在花括号包裹的块中调用代码就不需要 \#。
=== 标题
类似 Markdown 里用 \# 表示标题,typst 里用 = 表示标题,一级标题用一个 =,二级标题用两个 =,以此类推。
间距、字体等我都排版好了。
\#pagebreak() 函数相当于分页符,在华科的要求里,第一集标题应当分页,请手动。
#pagebreak()
= 本模板相关封装
== 图片
除了排版,这个模板主要改进了图片、表格、公式的引用,编号以第x章来计算。
图用下面的方式来引用,img 是对 image 的包装,caption 是图片的标题。
#img(
image("avatar-min-min.jpeg", height: 20%),
caption: "我的 image 实例 1",
) <img1>
引用的话就在 img 后加上标签<label>,使用 at 来引用即可,比如@img2 就是这么引用的。
#img(
image("avatar-min-min.jpeg", height: 20%),
caption: "我的 image 实例 2",
) <img2>
引用 2-1: @img1
== 表格
表格跟图片差不多,但是表格的输入要复杂一点,建议去 typst 官网学习一下,自由度特别高,定制化很强。
看看@tbl1,tbl 也是接收两个参数,一个是 table 本身,一个是标题,table 里的参数,没有字段的一律是单元格里的内容(每一个被[])包起来的内容,在 align 为水平时横向排列,排完换行。
#tbl(
table(
columns: (100pt, 100pt, 100pt),
inset: 10pt,
stroke: 0.7pt,
align: horizon,
[], [*Area*], [*Parameters*],
image("avatar-min-min.jpeg", height: 10%),
$ pi h (D^2 - d^2) / 4 $,
[
$h$: height \
$D$: outer radius \
$d$: inner radius
],
image("avatar-min-min.jpeg", height: 10%),
$ sqrt(2) / 12 a^3 $,
[$a$: 边长]
),
caption: "芝士样表"
) <tbl1>
#tbl(
three_line_table(
(
("Country List", "Country List", "Country List"),
("Country Name or Area Name", "ISO ALPHA Code", "ISO ALPHA"),
("Afghanistan", "AF", "AFT"),
("Aland Islands", "AX", "ALA"),
("Albania", "AL", "ALB"),
("Algeria", "DZ", "DZA"),
("American Samoa", "AS", "ASM"),
("Andorra", "AD", "AND"),
("Angola", "AP", "AGO"),
)),
caption: "三线表示例"
)
#tbl(
three_line_table(
(
("Country List", "Country List", "Country List", "Country List"),
("Country Name or Area Name", "ISO ALPHA 2 Code", "ISO ALPHA 3", "8"),
("Afghanistan", "AF", "AFT", "7"),
("Aland Islands", "AX", "ALA", "6"),
("Albania", "AL", "ALB", "5"),
("Algeria", "DZ", "DZA", "4"),
("American Samoa", "AS", "ASM", "3"),
("Andorra", "AD", "AND", "2"),
("Angola", "AP", "AGO", "1"),
)),
caption: "三线表示例2"
)
== 公式
公式用两个\$包裹,但是语法跟 LaTeX 并不一样,如果有大量公式需求那先建议看官网教程,不过typst还比较早期,不排除以后会加入兼容语法的可能。
为了给公式编号,也依然有包装,使用 equation 里包公式的方式实现,比如:
#equation(
$ A = pi r^2 $,
) <eq1>
根据@eq1 ,推断出@eq2
#equation(
$ x < y => x gt.eq.not y $,
) <eq2>
然后也有多行的如@eq3,标签名字可以自定义
#equation(
$ sum_(k=0)^n k
&< 1 + ... + n \
&= (n(n+1)) / 2 $,
) <eq3>
如果不想编号就直接用\$即可
$ x < y => x gt.eq.not y $
== 列表
- 无序列表1: 1
- 无序列表2: 2
#indent()列表后的正文,应当有缩进。这里使用一个 indent_par 函数来手动生成段落缩进,在目前的 typst 设计里,按英文排版的习惯,连续段落里的第一段是不会缩进的,也包括各种列表。
1. 有序列表1
2. 有序列表2
列表后的正文,应当有缩进,但是这里没有,请自己在段首加上\#indent(),也可以用 \#indent_par()[] 包裹整段
想自己定义可以自己set numbering,建议用 \#[] 包起来保证只在该作用域内生效:
#[
#set enum(numbering: "1.a)")
+ 自定义列表1
+ 自定义列表1.1
+ 自定义列表2
+ 自定义列表2.1
]
#pagebreak()
= 其他说明
== 文献引用
引用支持 LaTeX Bib 的格式,也支持更简单好看的 yml 来配置,在引用时使用#bib_cite("harry", "某本参考书")以获得右上的引用标注。
记得在最后加入\#references("xxxref.yml")函数的调用来生成参考文献。
*尚不支持国标,自定义参考文献功能官方正在开发中*
== 致谢部分
致谢部分在最后加入\#acknowledgement()函数的调用来生成。
== 模板相关
这个模板应该还不是完全版,可能不能覆盖到华科论文的所有case要求,如果遇到特殊 case 请提交 issue 说明,或者也可以直接提 pull request
同时,由于 typst 太新了,2023年4月初刚发布0.1.0版本,可能会有大的break change发生,模板会做相应修改。
主要排版数据参考来自 https://github.com/zfengg/HUSTtex 同时有一定肉眼排版成分,所以有可能不完全符合华科排版要求,如果遇到不对的间距、字体等请提交 issue 说明。
=== 数据相关
所有拉丁字母均为 Times New Roman,大小与汉字相同
正文为宋体12pt,即小四
图表标题为黑体12pt
表格单元格内容宋体10.5pt,即五号
一级标题黑体18pt加粗,即小二
二级标题14pt加粗,即四号
正文行间距1.5em
a4纸,上下空2.5cm,左右空3cm
#pagebreak()
= 这是一章占位的
== 占位的二级标题 1
== 占位的二级标题 2
== 占位的二级标题 3
== 占位的二级标题 4
=== 占位的三级标题 1
=== 占位的三级标题 2
==== 占位的四级标题 1
==== 占位的四级标题 2
== 占位的二级标题 5
== 占位的二级标题 6
#pagebreak()
#acknowledgement()[
完成本篇论文之际,我要向许多人表达我的感激之情。
首先,我要感谢我的指导教师,他/她对本文提供的宝贵建议和指导。所有这些支持和指导都是无私的,而且让我受益匪浅。
其次,我还要感谢我的家人和朋友们,他们一直以来都是我的支持和鼓励者。他们从未停止鼓舞我,勉励我继续前行,感谢你们一直在我身边,给我幸福和力量。
此外,我还要感谢我的同学们,大家一起度过了很长时间的学习时光,互相支持和鼓励,共同进步。因为有你们的支持,我才能不断地成长、进步。
最后,我想感谢笔者各位,你们的阅读和评价对我非常重要,这也让我意识到了自己写作方面的不足,同时更加明白了自己的研究方向。谢谢大家!
再次向所有支持和鼓励我的人表达我的谢意和感激之情。
本致谢生成自 ChatGPT。
]
#pagebreak()
#references("./ref.yml")
// 想用 TeX Bib 可以按下面这样引用
// #references("./ref.bib") |
https://github.com/FurryAcetylCoA/sgu-thesis-typst | https://raw.githubusercontent.com/FurryAcetylCoA/sgu-thesis-typst/main/nju-thesis/templates/bib.typ | typst | MIT License | #import "../utils/style.typ": 字号, 字体
// 参考文献页
#let bib(
// documentclass 传入参数
fonts: (:),
twoside: false,
// 其他参数
title: "参考文献",
path: (:),
outlined: true,
style: "../assets/china-national-standard-gb-t-7714-2015-numeric.csl",
) = {
fonts = 字体 + fonts
pagebreak(weak: true, to: if twoside { "odd" })
// 显示标题
[
#set text(font: fonts.黑体, size: 字号.小四, weight: "bold")
#set align(center)
#heading(level: 1, numbering: none, outlined: outlined, title) <no-auto-pagebreak>
]
// 相对路径修正
path = path.map((i) => ("../../" + i))
show bibliography: set text(font: fonts.楷体,size: 字号.五号)
bibliography(path, style: style, title: none)
}
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/grid-auto-shrink.typ | typst | Apache License 2.0 | // Test iterative auto column shrinking.
---
#set page(width: 210mm - 2 * 2.5cm + 2 * 10pt)
#set text(11pt)
#table(
columns: 4,
[Hello!],
[Hello there, my friend!],
[Hello there, my friends! Hi!],
[Hello there, my friends! Hi! What is going on right now?],
)
|
https://github.com/WinstonMDP/math | https://raw.githubusercontent.com/WinstonMDP/math/main/knowledge/monoids.typ | typst | #import "../cfg.typ": cfg
#show: cfg
= Monoids
An element $e$ of an algebraic structure $(M, *)$ is neutral $:=
e = 1 :=
m e = e m = m$.
$forall$ algebraic structure $:$ a neutral element is unique.
A monoid $:=$ a semigroup with a neutral element.
An element $m'$ of a monoid $(M, *)$ is inverse to another one $m :=
m' = m^(-1) :=
m' m = m m' = 1$.
$forall$ monoid and an element $m$ of it $:$ an inverse element to $m$ is unique.
|
|
https://github.com/DaAlbrecht/thesis-TEKO | https://raw.githubusercontent.com/DaAlbrecht/thesis-TEKO/main/content/Executive_summary.typ | typst | This thesis presents the development of a practical microservice designed to
replay messages from a RabbitMQ stream. The main goal was to create an
open-source Docker container that seamlessly integrates into existing
infrastructures, enabling the efficient replay of messages from RabbitMQ
streams.
#linebreak()
A comprehensive research phase was undertaken to evaluate various AMQP clients
available. Through an evaluation matrix, the most efficient and
reliable AMQP client was identified.
#linebreak()
The microservice was implemented using Rust, a programming language known for
its speed and safety. This choice allowed the creation of a robust architecture
that supports message replay based on specific time ranges or message headers.
#linebreak()
Key Features:
1. Time-based Replay: Messages can be replayed within specified time frames, making it easy to bulk replay messages from a specific time period.
2. Header-based Replay: Selective message replay based on specific headers allows users to precisely target messages.
#linebreak()
The requirements and stakeholder needs were successfully met, and the
microservice is successfully implemented and tested, marking this
project as a success.
#linebreak()
Looking ahead, the next step is to deploy the microservice in an existing
infrastructure and create integration templates to embed the microservice in
different observability tools.
#linebreak()
In summary, this thesis provides a practical solution to the problem of
replaying messages from RabbitMQ streams. The microservice is open-source and
can be used according to the terms of the MIT license.
#pagebreak()
|
|
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs | https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task3/3.2.typ | typst | Apache License 2.0 |
== Component diagram
#figure(caption:"Component diagram", image("../../images/Component_diagram.png", fit: "contain"))
_Mô tả Component diagram của module Request Printing Order._
#block(inset:(left:1cm))[
- Component diagram bao gồm các component: GUI, BE, PostgreSQL, MinIO, 3rd Party Payment Service.
- GUI: Đây là giao diện mà người dùng tương tác với hệ thống. Component này giao tiếp qua API với các component con của BE để người dùng thực hiện tải tài liệu (Upload Service), mua coin (Purchase Coin), xác nhận đơn in (Checkout) và thực hiện in (Handle Printer)
- BE: Bao gồm các component Upload Service, Checkout, Purchase Coin, Handle Printer. Các component trên sẽ nhận lệnh qua API từ GUI, cụ thể:
-Component Upload Service yêu cầu dịch vụ tải file lên qua API từ component MinIO và truyền thông thông tin của file vào PostgreSQL.
- Component Purchase yêu cầu dịch vụ qua API từ component 3rd Party Payment Service.
- Component Checkout truyền dữ liệu sang component PostgreSQL.
- Component Handle Printer yêu cầu thông tin in tài liệu qua API từ component PostgreSQL và yêu cầu file tài liệu qua API từ component MinIO để thực hiện in tài liệu.
- MinIO: lưu trữ file tài liệu tải lên từ Upload Service và truyền tài liệu cho Handle Printer
- PostgreSQL: lưu trữ dữ liệu thông tin tài liệu từ component Upload Service và Checkout, truyền dữ liệu tài liệu cho Handle Printer.
- 3rd Party Payment Service: cung cấp API cho Purchase Coin.
] |
https://github.com/MALossov/YunMo_Doc | https://raw.githubusercontent.com/MALossov/YunMo_Doc/main/contents/1OverView.typ | typst | Apache License 2.0 | = 设计概述
== 设计目的
我们的作品 *云MO监控* 对应的赛题为:*基于高云 FPGA 的网络视频监控系统*,因此,我们的首要目标在于充分发挥`Sipeed Tang Primer 20K`板卡的性能和资源,构建一能够迎合满足赛题需求、同时致力创新发挥,实现较为优秀的网络视频监控系统。我们主要着力于:
+ *以太网发送*:利用底板RMii网卡芯片实现UDP以太网传输
+ *摄像头适配*:利用OV5640实现视频采集
+ *视频处理*:使用高云软核+自主编写Video Processing模块实现
== 应用领域
云MO监控系统具有广泛的应用领域,能够通过通过配套使用兼容的镜头模块、同时通过配置CMOS寄存器,能够达到不同的 *画幅、视角区域* ,*具有较为良好的视角可定制性*。能够灵活 *适用于各类监控场景*。包括但不局限于:家庭安防(一般画幅、分辨能力)、商业区域监控(广画幅、低分辨能力)、仓库管理监控(窄画幅、高分辨能力)等。
同时,云MO监控系统突出了其独特的 *“云墨模式”* 特点。通过巧妙地结合板卡处理,系统能够通过仅保留视频灰度,巧妙地压缩数据,从而提高了网络传输效率和容错能力,优化了监控图像的流畅度。这一创新特点将监控系统的性能提升与数据传输的高可靠性相结合,同时能够借此实现二值化、边缘检测等,能够较好地 *适应光纤较弱*、画面干扰较大等情况的时候,仍能通过板卡自主判断、获取可靠的物品信息。因此,也可以用在特种作业、暗光环境等场所。
== 主要技术特点
云MO监控系统的技术特点体现在多个方面。
+ 首先,系统利用高云FPGA板卡实现了高性能视频采集+摄像头寄存器高度定制化,能够追踪特定场景、配置相应参数,确保监控图像质量。
+ 其次,通过支持多路摄像头接入,系统提供了更丰富的监控视角和更全面的场景覆盖。同时,我们不仅在理论支撑中可以通过座子复用、开关切换的方式进行视角的切换;同时,也通过完整的UDP网络协议实现,让单终端能够通过上位机设置同时访问不同的视角。
+ 再次,在网络传输方面,支持通用RJ45百兆网口,使得数据传输更为迅速和可靠。同时技术成熟、并且帧率达到了该接口条件下的较高水平_(稳定在19fps)_。
+ 最后,在数据处理方面,系统实现了“云墨模式”,能够将图片进行二值化、灰度处理、基本人体识别、边缘检测等,同时应用中值滤波软核等方式、实现了对数据的高度精准和有效处理,为用户提供了更为清晰和有用的监控信息。
== 关键性能指标
在关键性能指标部分,为服务于上述设计目的等内容,我们最终实现如下性能指标:
+ *20fps* 视频传输,在使用CMOS原生5-6-5 $R G B$ 进行颜色发送时,能够具有较好、稳定的流畅度。
+ *标准VGA清晰度* 实现了基于标准$640 times 480$ 分辨率的帧结构
+ *多上位机画面接收* 通过完整的UDP协议和底层协议支持,能够在单个终端当中,实现多画幅接收,借助多下位机实现多路收发。
+ *满速百兆以太网*: 能够通过满速的百兆以太网进行数据图像传输。
== 主要创新点
+ *在底层实现完整的ARP+UDP协议、自动网络链路获取*,支持自由收发,可以通过多上位机和地址设置实现多摄像头同时工作、显示实现。
+ *基本图像处理*,自行构建图像处理接口软核,使用标准的vga传输时序对于图像处理的过程进行封装,能够较好地添加、删改新的软核;并加入按键状态机进入模式切换。
+ *通用滤波模块*:提供通用的滤波、减少资源消耗,实现较好的二值化、边缘识别等图像处理效果。
+ *单键操作*: 使用单按键加状态机进行模式切换,增加易用性、减少操作难度。
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CU/minea/1_generated/00_all/03_november.typ | typst | #import "../../../all.typ": *
#show: book
= #translation.at("M_03_november")
#include "../03_november/08.typ"
#pagebreak()
#include "../03_november/13.typ"
#pagebreak()
#include "../03_november/21.typ"
#pagebreak()
|
|
https://github.com/xkevio/parcio-typst | https://raw.githubusercontent.com/xkevio/parcio-typst/main/parcio-thesis/chapters/conclusion/conc.typ | typst | MIT License | #import "../../template/template.typ": todo, section
= Conclusion<conc>
_In this chapter, ..._\ \
== Todos
#todo(inline: true)[FIXME]
#lorem(100)#todo[FIXME: remove this]
#lorem(80)
#section[Summary]
#lorem(80)
|
https://github.com/N3M0-dev/Notes | https://raw.githubusercontent.com/N3M0-dev/Notes/main/CS/Algorithm/Intro_to_Algor/Ch_2/ch2.typ | typst | #let authors=("Nemo",)
#let title="Chapter 2: Getting Started"
#let date="2023.9.5-"
#set document(author: authors, title: title)
#set page(numbering: "1", number-align: center)
#set heading(numbering: "1.1")
// Title row.
#align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
#pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
// Main body.
#set par(justify: true)
#set text(12pt)
#outline(indent: true)
= Time Complexity
Serveral denotions.
|
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/数据库系统/基本概念和关系代数.typ | typst | ---
order: 1
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "数据库系统",
lang: "zh",
)
#info()[
1. 在 #link("https://github.com/Zhang-Each/CourseNoteOfZJUSE/tree/master/DBS%E6%95%B0%E6%8D%AE%E5%BA%93%E7%B3%BB%E7%BB%9F")[Zhang Each's GitHub repo] 前辈笔记的基础上重写
2. 加入了 #link("https://note.hobbitqia.cc/DB")[hobbitqia 的笔记] 的内容和自己上课的理解
]
#let null = math.op("null")
#let Unknown = math.op("Unknown")
= 第一部分:基本概念和关系代数
== 课程绪论
- 数据库系统的概念
- 数据库(Database)是某一机构的相关数据的集合,由数据库管理系统 DBMS(Database Management System)来管理
- 数据库系统的应用
- 从 University Database 的例子来看
- 数据库的数据结构有很多,这门课主要用*关系型*数据库,以*表格*的形式呈现
- 操作:插入、查询、链接等
- 数据库系统的 Purpose
- 从 file system 到 database system,解决了
1. 数据冗余与不一致
2. 数据孤立、数据孤岛(多文件与多格式)
3. 存取数据困难
- 完整性(integrity)问题:约束条件从隐藏在代码中变为显示的声明
- 原子性(atomicity)问题:事件不可分割,要么做完要么不做。解决掉电等情况导致的数据不一致
- 并发访问(concurrent access)异常
- 安全性问题:认证(authentication)、权限(priviledge)、审计(audit)——对权利大的人进行监控
- 数据库系统的特点
- data persistence, convenience in accessing data, ...
- 数据模型
- 如何描述?Data(数据)、Data relationships(联系)、Data semantics(语义)、Data constraints(约束)
- *Relational model*(关系模型,这门课的重点)
- 提出者:<NAME>,获 1981 年图灵奖
- 用 columns / Attributes 与 rows / Tuples 来描述
- *Object-based* data models: Object-oriented(面向对象数据模型)、Object-relational(对象-关系模型模型)
- *Semistructured* data model(半结构化数据模型),XML 是一种专门描述这种模型的语言
- Other older models: Network model(网状模型)、Hierarchical model(层次模型)
- *Entity-Relationship* model(实体-联系模型),跟上面的模型不是对等的关系,主要是用于描述数据库
- View of Data
- 用三级抽象来看待数据库,view level、logical level、physical level,三级抽象之间相对独立
- view level: view schema,用户看到的数据视图
- logical level: logical schema,数据库的逻辑结构
- physical level: physical schema,数据库的物理结构
- 好处:隐藏复杂度、增强适应变化的能力
- Data Independence
- 逻辑数据独立性:改变逻辑模式不影响应用程序
- 物理数据独立性:改变物理存储结构不影响应用程序
- Database Languages
- 数据定义语言 DDL(Data Definition Language):定义数据库的逻辑结构
- 数据操纵语言 DML(Data Manipulation Language):查询、插入、删除、更新
- SQL Query Language
- Application Program Interface(API),应用层面
- DDL
- C 语言的定义实际上是用二进制来表示,而数据的定义还是用数据:metadata(元数据,i.e., data about data)
- DDL 编译器产生数据字典(data dictionary),存储在数据库中
- DML
- DML 也被称为 query language
- SQL 是最广泛使用的 query language
- 两种语言类型:procedural(过程式)、declarative(nonprocedural,陈述式,非过程式)
- DML 是 declarative 的
- SQL Query Language
- 举一个例子
- Database Access from Application Program
- SQL 和用户实际使用之间还隔了一层交互,这些交互是用 *host language*(宿主语言)写的
- 通常我们用两种方式
1. API(Application program interface) (e.g., ODBC/JDBC)
2. 支持 embedded SQL 的语言插件
- 数据库设计
- 实体联系模型
- 规范化理论
- 数据库引擎(Database Engine)
- 学术一点的叫法是 database system,可以被分为: storage manager, query processor, transaction(事务) management
- History
- 图灵奖得主:<NAME>, <NAME>, <NAME>, <NAME>
== 关系型数据库 Relational Database
=== 关系型数据的一些基本特点
- 关系型数据库是一系列*表的集合*
- 一张表是一个基本单位
- 表中的一行表示一条关系
== 基本概念和结构
- A relation $r$ is a subset of $D_1 times D_2 times dots times D_n$,一条 relation 就是其中的一种 $m$ 个 $n$ 元*元组(tuple)* 的集合(注意这里的表述,relation 中的一个元素,即表中的一行,才是一个元组)
- attribute 属性,指表中的*列名*
- attribution type 属性的类型
- attribute value 属性值,某个属性在某条 relation 中的值
- 关系型数据库中的属性值必须要是 atomic 的,即不可分割的
- domain:属性值的值域,null 是所有属性的 domain 中都有的元素,但是 null 值的处理是一个问题
- Relation Schema 关系模式
- $R=(A_1, A_2, dots, A_n)$ 是一种关系模式,其中 $A_i$ 是一系列属性,关系模式是对关系的一种*抽象*
- $r(R)$ 表示关系模式 $R$ 中的一种关系,table 表示了这个关系当前的值(关系实例)
- 不过经常用相同的名字命名关系模式和关系
- 每个关系 $r$ 中的元素 $t$ 被称为 tuple,是 table 中的一行
- 关系是*无序*的,关系中行和列的顺序是 irrelevant 的
- Database Schema
- Database Schema 是数据库的逻辑模式
- Database instance 是数据库的实例(snapshot)
== Keys键
- 超键(super key):能够*唯一标识*每个可能 $r(R)$ 的某一元组的属性集,即对于每一条关系而言超键的值是唯一的
- 超键可以是多个属性的组合
- 如果 $A$ 是关系 $R $的一个超键,那么 $(A, B)$ 也是关系 $R$ 的一个超键,即超键的“唯一标识”各个元组是可以有冗余信息的
- 候选键(candidate key):*不含多余属性*(minimal)的超键
- 如果 $K$ 是 $R$ 的一个超键,而任何 $K$ 的真子集不是 $R$ 的一个超键,那么 $K$ 就是 $R$ 的一个候选键
- 主键(primary key):
- 数据库管理员*从候选键中指定*的元组标识,不能是 $null$ 值
- 外键(foreign key):用来描述两个表之间的关系
- 如果关系模式 $R_1$ 中的一个属性是另一个关系模式 $R_2$ 中的一个*主键*,那么这个属性就是 $R_1$ 的一个外键
- 关系 $r_1$ 引用的主键必须在关系 $r_2$ 中出现。
- Referential integrity (参照完整性)
- 类似于外键限制,但不局限于主键。
- 外键与参照完整性的例子
#fig("/public/assets/Courses/DB/img-2024-03-05-22-34-29.png", width: 90%)
== Relational algebra 关系代数
=== 基本运算
- *选择(select)*:$sigma_p (r)={t mid(|)t in r and p(t) }$,筛选出所有满足条件 $p(t)$ 的元素 $t$
- 这里 $p(t)$ 称为*谓词*
- *投影(project)*:$Pi_(A_1, A_2, dots, A_k)(r)$
- 运算的结果是原来的关系 $r$ 中各列只保留属性 $A_1, A_2, dots, A_k$ 后的关系
- 会*自动去掉重复*的元素,因为可能投影的时候舍弃的属性是可以标识关系唯一性的属性
- *并(union)*:$r union s={t mid(|) t in r or t in s}$
- 两个关系的属性个数必须相同
- 各属性的 domain 必须是可以比较大小的(compatible)
#fig("/public/assets/Courses/DB/img-2024-06-10-21-43-21.png",width: 50%)
- *集合差(set difference)*:$r-s={t mid(|) t in r and t in.not s}$
- 各属性的 domain 必须是可以比较大小的(compatible)
- *笛卡尔积(cartesian-Piuct)*:$r times s={t q | t in r and q in s}$
- 两个关系如果相交,则需要加上关系名作为前缀区分;进一步地,如果关系名重复(比如 $"self" times "self"$),则需要利用重命名操作
- 笛卡尔积运算的结果关系中元组的个数应该是 $r, s$ 的个数之乘积
- *重命名(renaming)*:$rho_X (E)$
- 将 $E$ 重命名为 $x$, 让一个关系拥有多个别名,同时 $X$ 可以写为 $X(A_1, A_2, dots, A_n)$ 表示对属性也进行重命名
- 类似于 C++ 中的引用
=== 扩展运算: 可以用前面的六种基本运算得到
- *交(intersection)*:$r sect s={t mid(|) t in r and t in s}=r-(r-s)$
- *自然连接(natual-Join)*:$r join s$
- 两个关系中同名属性在自然连接的时候当作*同一个属性*来处理
- 相当于是对笛卡尔积的扩展,允许两个关系有同名属性,并且同名属性的值相同才会保留(先 $times$ 再 select)
- 如果两个关系交集为空,则等同于*笛卡尔积*(没有等于全真)
- *条件链接(Theta join)*:满足某种条件的合并:$r join_theta s=sigma_theta (r times s)$
- 虽然写在自然连接这部分,但感觉与其说它是自然连接的变种,不如说它和自然连接一样都是笛卡尔积的扩展,只是方向不一样。
- Theta join 需要首先满足笛卡尔积的条件,然后再选取满足 $theta$ 的行
- *外部连接(outer-Join)*,分为左外连接,右外连接,全外连接
- 用于应对一些*信息缺失*的情况(有 null 值)
- 左外连接 $join.l$
- 右边的表取全部值按照关系和左边连接,左边不存在时为空值
- $r join.l s=(r join s) union (r- Pi_R (r join s) times {(null, dots, null)})$
- 右外连接 $join.r$
- 左边的表取全部值按照关系和右边连接,右边不存在时为空值
- $r join.r s=(r join s) union {(null, dots, null)} times (s-(Pi_S (r join s))$
- 全外连接(full outer join) 左右全上,不存在对应的就写成空值
$
r join.l.r s = (r join s) union \
(r-Pi_R (r join s) times {(null, dots, null)}) union \
({(null, dots, null)} times (s-(Pi_S (r join s)))
$
- *半连接(semijoin)*:$r ⋉_theta s=Pi_R (r join_theta s)$
- 保留 $r$ 中能够和 $s$ 中的元素条件连接的元素,相当于做个筛选(不取 $r_2$ 的自然连接)
- *除法(division)*:$r div s={t mid(|) t in Pi_(R-S)(r) and forall u in s (t u in r)}$
- 如果$R=(A_1, A_2, dots, A_m, B_1, dots, B_n) and S=(B_1, dots, B_n)$ 则有$R- S=(A_1, A_2, dots, A_m)$
#fig("/public/assets/Courses/DB/img-2024-06-10-21-17-43.png",width:50%)
- *声明操作(assignment)*,类似于变量命名,用 $arrow.l$ 可以把一个关系代数操作进行命名
- *聚合操作(aggregation operations)*
- 基本形式:$attach(cal(G), bl: G_1\, G_2\, dots\, G_n, br: F_1(A_1)\, dots\, F_n(A_n))(E)$
- $G$ 是聚合的标准,对于关系中所有 $G$ 值相同的元素进行聚合,$F()$ 是聚合的运算函数
- 常见的有 SUM / MAX / MIN / AVG / COUNT
#fig("/public/assets/Courses/DB/img-2024-06-10-21-18-27.png",width:50%)
#v(0.5em)
- *Multiset* 关系代数
- 关系代数中,我们要求关系要是一个严格的集合。但实际数据库中并不是,而是一个多重集,允许有重复元素存在。
- 因为一些操作的中间结果会带来重复元素,要保持集合特性开销很大,因此实际操作中不会去重。
== SQL and Relational Algebra
- ```sql select A1, A2, ... An from r_1, r_2, ... rm where P``` 等价于 $Pi_(A_1, A_2, dots, A_k)(sigma_p (r_1 times r_2 times dots times r_m))$
- ```sql select A1, A2, sum(A3) from r_1, r_2, ... rm where P group by A1, A2``` 等价于 $attach(cal(G), bl: (A_1, A_2), br: "sum"(A_3))(r_1 times r_2 times dots times r_m)$
- 这里按 $A_1, A_2$ 分组,那么结果的表中会有 $A_1, A_2, "sum"(A_3)$ 三列(分组依据+分组后的聚合结果),这里我们需要的就是这三列,所以分组即可。但是假设我们只需要 $A_1, "sum"(A_3)$,那么最后还需要投影。
|
|
https://github.com/maxds-lyon/lokiprint | https://raw.githubusercontent.com/maxds-lyon/lokiprint/main/templates/typst/.template/about.typ | typst | #let about-section(content) = block()[content] |
|
https://github.com/Enter-tainer/zint-wasi | https://raw.githubusercontent.com/Enter-tainer/zint-wasi/master/typst-package/example.typ | typst | MIT License | #import "./lib.typ" as tiaoma
// #import "@preview/tiaoma:0.1.0"
#set page(width: auto, height: auto)
= tiáo mǎ
#tiaoma.ean("1234567890128")
|
https://github.com/gianzamboni/cancionero | https://raw.githubusercontent.com/gianzamboni/cancionero/main/main.typ | typst | #import "theme/project.typ": *;
#show: project.with(
title: "Cancionero",
authors: (
"Gian",
),
date: "October 8, 2023",
)
// #linebreak()
// #outline(title:[Índice #linebreak()], depth: 2 , indent: 10pt)
= Conceptos básicos
#include "acordes.typ"
= Canciones
// #include "canciones/cuentamedusa.typ"
// #include "canciones/el-tango-de-la-muerte.typ"
// #include "canciones/entre-oraculos.typ"
// #include "canciones/the-lobster-quadrille.typ" |
|
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/decide-launcher/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: "Decide: Moving Triballs",
type: "decide",
date: datetime(year: 2023, month: 9, day: 5),
author: "<NAME>",
witness: "Violet Ridge",
)
We rated each option on the following characteristics:
- Speed at which they could fire triballs on a scale or 0 to 3
- Compactness on a scale of 0 to 3
- Ease of construction on a scale of 0 to 3
- Reliability on a scale of 0 to 3
#decision-matrix(
properties: (
(name: "Speed"),
(name: "Compactness"),
(name: "Ease of construction"),
(name: "Reliability"),
),
("Puncher", 3, 3, 2, 2),
("Catapult", 3, 2, 3, 3),
("Flywheel", 2, 2, 1, 1),
)
#admonition(
type: "decision",
)[
We ended up deciding on the catapult due to its high speed, and because we had
experience with building catapults from the Spin Up season.
]
= Final Design
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
figure(caption: "Front View", image("./front.png", width: 90%)),
figure(caption: "Top View", image("./top.png", width: 90%)),
figure(caption: "Side View", image("./side.png", width: 90%)),
figure(caption: "Isometric View", image("./iso.png", width: 90%)),
)
#image("./1.png")
#image("./2.png")
|
https://github.com/pku-typst/ichigo | https://raw.githubusercontent.com/pku-typst/ichigo/main/template/main.typ | typst | MIT License | #import "@preview/ichigo:0.1.0": config, prob
#show: config.with(
course-name: "Typst 使用小练习",
serial-str: "第 1 次作业",
author-info: [
sjfhsjfh from PKU-Typst
],
author-names: "sjfhsjfh",
title-style: "simple",
theme-name: "sketch",
heading-numberings: ("1.", none, "(1)", "a."),
)
#set text(lang: "zh")
#prob(title: "Warm-up")[
尝试用 Typst 完成以下任务:
=
计算 Fibonacci 数列的第 25 项
=
生成九九乘法表
][
=
```typ
#let fib(n) = {
if n in (1, 2) {
return 1
}
return fib(n - 1) + fib(n - 2)
}
#fib(25)
```
#let fib(n) = {
if n in (1, 2) {
return 1
}
return fib(n - 1) + fib(n - 2)
}
运行得到结果 #fib(25)
也可以根据通项公式
$
f_n = 1 / sqrt(5) (((1 + sqrt(5)) / 2)^n - ((1 - sqrt(5)) / 2)^n)
$
```typ
#let fib(n) = {
let lambda-1 = (1 + calc.sqrt(5)) / 2
let lambda-2 = (1 - calc.sqrt(5)) / 2
return calc.round((1 / calc.sqrt(5)) * calc.pow(lambda-1, n) - (1 / calc.sqrt(5)) * calc.pow(lambda-2, n))
}
#fib(25)
```
#let fib(n) = {
let lambda-1 = (1 + calc.sqrt(5)) / 2
let lambda-2 = (1 - calc.sqrt(5)) / 2
return calc.round((1 / calc.sqrt(5)) * calc.pow(lambda-1, n) - (1 / calc.sqrt(5)) * calc.pow(lambda-2, n))
}
计算得到第 25 项 #fib(25)
=
```typ
#set text(size: 8pt)
#figure(
table(
columns: 10,
$times$, ..range(1, 10).map(x => [#x]),
..range(1, 10).map(x => ([#x], ..range(1, 10).map(y => $#y times #x = #(x * y)$))).flatten()
),
caption: [九九乘法表],
)
```
#set text(size: 8pt)
#figure(
table(
columns: 10,
$times$, ..range(1, 10).map(x => [#x]),
..range(1, 10).map(x => ([#x], ..range(1, 10).map(y => $#y times #x = #(x * y)$))).flatten()
),
caption: [九九乘法表],
)
]
|
https://github.com/drupol/ipc2023 | https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/main.typ | typst | #import "imports/preamble.typ": *
#set text(size: 25pt, font: "Iosevka")
#set document(title: "Leveraging Nix in the PHP ecosystem", author: "<NAME>")
#show: ipc-theme.with(
short-author: "<NAME>",
short-title: "IPC2023 - Leveraging Nix in the PHP ecosystem",
short-date: "2023/10/26",
ecmain: color-a, // Red from IPC website
ecaccentblue: rgb(72, 214, 217).darken(25%), // Green from IPC website
progress-bar: false
)
#pdfpc.config(
duration-minutes: 60,
start-time: datetime(hour: 12, minute: 00, second: 00),
note-font-size: 14
)
#title-slide(
authors: ("<NAME>"),
title: "Leveraging Nix in the PHP ecosystem",
subtitle: "An innovation-centric approach",
date: "2023/10/26",
institution: "International PHP Conference",
logo: image("../../resources/images/ipc-logo.svg", width: 60mm),
)
#include "intro.typ"
#include "history.typ"
#include "package-manager.typ"
#include "reproducibility.typ"
#include "programming-language.typ"
#include "software-builder.typ"
#include "operating-system.typ"
#include "nix-summary.typ"
#include "demo.typ"
#include "outro.typ"
#include "references.typ"
|
|
https://github.com/harryhanYuhao/typst.vim | https://raw.githubusercontent.com/harryhanYuhao/typst.vim/main/readme.md | markdown | # A vim-plugin for Typst
[Typst](https://github.com/typst/typst) is a latex substitute.
So far the plugin is very preliminary. Hopefully a alpha-release will be lauched before 2023's Christmas.
## Installation
### Vimplug
```vim
Plug 'harryhanYuhao/typst.vim'
```
|
|
https://github.com/eduardz1/UniTO-typst-template | https://raw.githubusercontent.com/eduardz1/UniTO-typst-template/main/template/chapters/introduction.typ | typst | MIT License | = Introduction
Remeber that this is not only a repeat of the abstract, the introduction should be a more detailed explanation of the problem and the background of the study. If we want to reference an element in the bibliography you can do so like this @unitotmplt.
#pagebreak(weak: true, to: "odd")
|
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/glouton.typ | typst | #import "@preview/codly:0.2.1": *
#show: codly-init.with()
#codly()
#set text(font: "Roboto Serif")
= Gloutons <gloutons>
== IV - Algorithmes d’approximation, un exemple <iv---algorithmes-dapproximation-un-exemple>
==== 1. La variante fractionnaire du problème du sac à dos <la-variante-fractionnaire-du-problème-du-sac-à-dos>
Dans cette variante, on autorise à prendre des quantités fractionnaires d’objets.
- n objets $lr((p_0 , v_0)) , . . . lr((p_(n - 1) , v_(n - 1)))$
- Question : trouver $alpha_0 , . . . alpha_(n - 1)$ appartenant à l’intervalle réel \[0;1\] tel que
$sum_(i = 0)^(n - 1) alpha_i lt.eq P$
$sum_(i = 0)^(n - 1) alpha_i v_i$ est maximale (parmi les solutions qui respectent la contrainte)
Ce problème se résout correctement via un algorithme glouton : on choisit l’objet de ratio $v_i / p_i$ maximal
#strong[Démonstration]
On commence par trier les objets par ratio décroissant. On suppose que c’est fait :
$v_0 / p_0 gt.eq . . . v_(n - 1) / p_(n - 1)$
On exclu les cas où n \= 0 ou P \= 0
La solution gloutonne est alors de la forme : $lr((1 , . . . 1 , alpha , 0 , . . .0))$ avec $alpha in \] 0 , 1 \]$ d’indice r et $sum_(i = 0)^(r - 1) p_i + alpha p_r = P$
et la valeur du sac est alors $sum_(i = 0)^(r - 1) v_i + alpha v_r$
Soit $lr((alpha_0 , . . . alpha_(n - 1)))$ une solution optimale
On a $sum_(i = 0)^(n - 1) alpha_i p_i = P$ (sauf si $sum_(i = 0)^(n - 1) p_i < P$ ce que l’on exclut car cas trivial)
On suppose par l’absurde que cette solution est différente de la gloutonne.
Soit $i_0$ le plus petit coefficient sur lequel les deux solutions diffèrent :
- Soit $alpha i_0 < 1$ si $i_0 > r$
- Soit $alpha i_0 < alpha$ si $i_0 = r$
- Ce sont les seuls cas possibles sinon la solution $lr((alpha_0 , . . . alpha_(n - 1)))$ ne respecte pas la contrainte du poids.
$-> exists K >r : alpha_K > 0$ ou $alpha_r > alpha$
Différents cas possibles :
#block[
#set enum(numbering: "1)", start: 1)
+ $i_0 < r$
On prend $beta = m i n lr(
(frac(alpha_K p_K, P_(i_0)) , frac(lr((1 - alpha_(i_0))) p_(i_0), p_K))
)$
On montre que la solution $lr(
(alpha_0 . . . , alpha_(i_0) + beta / p_(i_0) , alpha_(i_0 + 1) , . . . , alpha_K - beta / p_K , . . .)
) = lr((alpha_0 prime , . . . , alpha_(n - 1) prime))$
C’est bien une solution :
$sum_(i = 0)^(n - 1) alpha_i prime p_i = sum_(i = 0)^(n - 1) alpha_i p_i + beta / p_(i_0) - beta / p_K p_K = P$
Et la valeur obtenue augmente
$sum_(i = 0)^(n - 1) alpha_i prime v_i = sum_(i = 0)^(n - 1) alpha_i v_i + beta / p_(i_0) - beta / p_K v_K$ (la somme des deux derniers termes étant $0 lt.eq$)
Or $i_0 < K$ donc $v_(i_0) / p_(i_0) gt.eq v_K / p_K$
Donc $sum_(i = 0)^(n - 1) alpha_i prime v_i gt.eq sum_(i = 0)^(n - 1) alpha_i v_i$
]
#block[
#set enum(numbering: "1.", start: 2)
+ $i_0 = r$
Ce cas sera similaire : il faut remplir le coefficient r au maximum.
]
==== 2. Approximation de la variante classique <approximation-de-la-variante-classique>
On suppose encore les objets triés par ratio : $v_0 / p_0 gt.eq . . . v_(n - 1) / p_(n - 1)$
La solution optimale fractionnaire est de la forme $lr((1 , . . . 1 , alpha , 0 , . . .0))$ avec $alpha$ à l’indice r
Une approximation acceptable du problème initiale est : la meilleure solution entre $lr((1 , . . . 1 , 0 , . . .0))$ le premier 0 étant à l’indice r et $lr((0 , . . . 0 , 1 , 0 , . . .0))$ le 1 étant à l’indice r.
$->$ On suppose qu’on a retiré les objets trop gros !
Toute solution au problème "normal" est également une solution au problème fractionnaire.
Soit V la solution optimale au problème classique : $V lt.eq sum_(i = 0)^(r - 1) v_i + alpha v_r$
Donc :
- soit $sum_(i = 0)^(n - 1) v_i gt.eq V / 2$
- soit $v_r gt.eq alpha v_r gt.eq V / 2$
Cela s’appelle une $1 / 2$-approximation : on produit une solution qui est au moins la moitié de l’optimale.
|
|
https://github.com/hosnimarnisi/lab4 | https://raw.githubusercontent.com/hosnimarnisi/lab4/main/Lab-4.typ | typst | #import "Class.typ": *
#show: ieee.with(
title: [#text(smallcaps("Lab #4: ROS2 using RCLPY in Julia"))],
/*
abstract: [
#lorem(10).
],
*/
authors:
(
(
name: "<NAME>",
department: [Senior-lecturer, Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "a-mhamdi",
),
(
name: "<NAME>",
department: [Senior-lecturer, Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "adamnemr",
),
(
name: "<NAME>",
department: [Senior-lecturer, Dept. of EE],
organization: [ISET Bizerte --- Tunisia],
profile: "hosnimarnisi",
),
)
// index-terms: (""),
// bibliography-file: "Biblio.bib",
)
You are required to carry out this lab using the REPL as in @fig:repl.
#figure(
image("Images/REPL.png", width: 100%, fit: "contain"),
caption: "Julia REPL"
) <fig:repl>
#[The combination of Julia and rclpy opens up opportunities for developing efficient and performant robotics applications with the benefits of ROS2s ecosystem.]
```zsh
source /opt/ros/humble/setup.zsh
```
The command "source /opt/ros/humble/setup.zsh" executes a setup scénario for ROS (Robot Operating System) within the Zsh shell. This scénario configures the environment by setting variables, aliases, and other configurations needed for working with ROS effectively. By running this command, you prepare your environment to utilize ROS tools and features seamlessly within Zsh.
#let publisher=read("../Codes/ros2/publisher.jl")
#let subscriber=read("../Codes/ros2/subscriber.jl")
#raw(publisher, lang: "julia")
This Julia scénario uses PyCall to interact with the ROS2 (Robot Operating System 2)
1. Imports necessary Python modules (`rclpy` for ROS2 functionality and `std_msgs.msg` for courant glorification types).
2. Initializes the ROS2 runtime.
3. Creates a ROS2 node named "my_publisher".
4. Creates a publisher within the node to publish messages of type `std_msgs.msg.String` on the topic "infodev".
5. Publishes "Hello, ROS2 from Julia!" messages with an incremental number every participant for 100 iterations.
6. Prints logging moderne to the console with each published glorification.
7. Cleans up by shutting down the ROS2 runtime and destroying the node.
#raw(subscriber, lang: "julia")
```zsh
source /opt/ros/humble/setup.zsh
rqt_graph
```
This code combines two scripts for interacting with ROS2 (Robot Operating System 2) using Julia and PyCall:
1. **Publishing Script**:
- Initializes the ROS2 runtime.
- Creates a publisher node that sends messages containing "Hello, ROS2 from Julia!" with incremental numbers to the "infodev" topic.
- Shuts down the ROS2 runtime after publishing the messages.
2. **Subscribing Script**:
- Initializes the ROS2 runtime.
- Creates a subscriber node that listens for messages on the "infodev" topic.
- Defines a callback function to process incoming messages by appending a prefix and logging them.
- Continuously spins the node to handle incoming messages until the ROS2 runtime is shut down.
Additionally, the code includes commands to set up the ROS environment and visualize the ROS graph using `rqt_graph`.
In summary, this code demonstrates a simple interaction with ROS2, showcasing both message publishing and subscribing functionalities, along with environment setup and visualization of the ROS graph.
#figure(
image("Images/rqt_graph.png", width: 100%),
caption: "rqt_graph",
) <fig:rqt_graph>
@fig:pub-sub depicts the publication and reception of the message _"Hello, ROS2 from Julia!"_ in a terminal. The left part of the terminal showcases the message being published, while the right part demonstrates how the message is being received and heard.
- In this version, the publisher sends messages like "[Info [TALKER] Julia says, "Hello ROS2!" (1)]" up to 100 times, and the subscriber responds with "[Info [LISTENER] I heard, "Hello ROS2!" (1)]" for each message it receives.
#figure(
image("Images/pub-sub.png", width: 100%),
caption: "Minimal publisher/subscriber in ROS2",
) <fig:pub-sub>
@fig:topic-list shows the current active topics, along their corresponding interfaces.
/*
```zsh
source /opt/ros/humble/setup.zsh
ros2 topic list -t
```
*/
#figure(
image("Images/topic-list.png", width: 100%),
caption: "List of topics",
) <fig:topic-list>
//#test[Some test]
This line imports the PyCall module, which allows Julia code to interact with Python code.
```julia
rclpy = pyimport("rclpy")
```
Here, we use PyCall to import the rclpy module from Python. `rclpy` is a Python client library for the Robot Operating System (ROS) 2. This line enables us to access ROS 2 functionality from within Julia.
```julia
str = pyimport("std_msgs.msg")
```
Similarly, this line imports the `std_msgs.msg` module from Python. The `std_msgs.msg` module typically contains message definitions for standard ROS 2 message types. By importing this module, we gain access to these message types, which we can use to define the structure of messages sent over ROS 2 topics.
So, in summary, the publisher code starts by importing necessary Python modules (`rclpy` for ROS 2 functionality and `std_msgs.msg` for standard message types) into Julia using PyCall. This allows us to leverage existing Python libraries and interact with ROS 2 in our Julia codebase.
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/cite_heading.typ | typst | Apache License 2.0 | // path: references.bib
@article{t,}
-----
// contains:form,test
// compile:true
#set heading(numbering: "1.1")
#let cite_prose(labl) = cite(labl)
= H <test>
#cite_prose(<t> /* range -3..-2 */)
#bibliography("references.bib")
|
https://github.com/r8vnhill/apunte-bibliotecas-de-software | https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit1/Intro.typ | typst | == Introducción al desarrollo de bibliotecas de software
=== APIs
Una API (Application Programming Interface) define bloques de construcción reutilizables que permiten incorporar funcionalidades a una aplicación de manera eficiente y estandarizada.
Las APIs son fundamentales para el desarrollo de software moderno y se proporcionan generalmente mediante bibliotecas.
==== Características de una buena API
===== Modela el Problema
Una API se escribe para solucionar un problema específico y debe proporcionar una buena abstracción de dicho problema.
A continuación, se detallan los principios clave para modelar el problema de manera efectiva:
- *Propósito Claro*: Cada función, clase y variable debe tener un propósito central y claramente definido. Este propósito debe reflejarse en su nombre para que sea intuitivo y fácil de entender por otrxs desarrolladorxs.
- *Consistencia*: Mantén una nomenclatura y estructura consistentes en toda la API. Esto facilita su comprensión y uso, y reduce la posibilidad de errores.
===== Esconde Detalles
La razón principal para escribir una API es ocultar los detalles de la implementación, permitiendo que estos puedan ser modificados sin afectar a lxs clientes que utilizan la API. A continuación, se presentan los principios clave para ocultar los detalles de implementación de manera efectiva:
- *Encapsulación*: Utiliza la encapsulación para restringir el acceso a los detalles internos de la implementación. Mantén las variables y métodos internos privados y expón solo lo necesario a través de métodos públicos.
- *Interfaz Clara*: Proporciona una interfaz clara y bien definida que permita a lxs usuarixs interactuar con la API sin conocer los detalles internos. Esto facilita la comprensión y uso de la API.
- *Separación de Preocupaciones*: Divide la API en módulos o componentes, cada uno con responsabilidades claramente definidas. Esto facilita el mantenimiento y evolución de la API, ya que los cambios en un componente no afectan a otros.
===== Mínimamente completa
Una API debe ser tan pequeña como sea posible para mantener su simplicidad y facilidad de mantenimiento.
A continuación, se presentan los principios clave para lograr una API mínimamente completa:
- *Simplicidad*: Diseña la API con la menor cantidad de elementos públicos necesarios. Cada elemento público aumenta la superficie de mantenimiento y promesas que debes cumplir a largo plazo.
- *No te repitas (DRY)*: Evita la duplicación de funcionalidades. Cada funcionalidad debe implementarse una sola vez y ser reutilizada en lugar de replicarse en diferentes partes de la API.
- *Enfoque en la Esencia*: Identifica y proporciona solo las funcionalidades esenciales que resuelven el problema central de la API.
- *Abstracciones Claras*: Mantén las abstracciones claras y concisas. No añadas métodos o clases innecesarios que no aporten valor significativo a la API.
- *Principio de Responsabilidad Única*: Asegúrate de que cada componente de la API tenga una única responsabilidad claramente definida. Esto ayuda a mantener la API enfocada y reduce la complejidad.
#quote(attribution: [Reddy, 2011])[
Every public element in your API is a promise—a promise that you'll support that functionality for the lifetime of the API.
]
===== Fácil de Usar
Una API debe ser intuitiva y difícil de usar incorrectamente. Aquí hay algunos principios clave para lograr una API fácil de usar:
#quote(attribution: [Reddy, 2011])[
It should be possible for a client to look at the method signatures of your API and be able to glean how to use it without any additional documentation.
]
- *Intuitiva*: Los usuarios deben poder entender cómo usar la API simplemente observando las firmas de los métodos, sin necesidad de documentación adicional.
- *Difícil de Usar Mal*: La API debe diseñarse de manera que sea difícil cometer errores al utilizarla. Esto puede lograrse proporcionando valores predeterminados razonables, validando los parámetros y utilizando tipos de datos adecuados.
- *Consistente*: Mantén la consistencia en los nombres, el orden de los parámetros y los patrones utilizados en la API. Esto facilita el aprendizaje y la utilización de la API por parte de los usuarios.
- *Evita Abreviaciones*: Usa nombres completos y claros en lugar de abreviaciones. Las abreviaciones pueden ser confusas y menos descriptivas.
- *Ortogonalidad*: Asegúrate de que los cambios en una parte de la API no afecten otras partes. Las variables públicas y los métodos deben ser independientes entre sí en la medida de lo posible. Los cambios en una variable pública no deberían afectar a otras variables públicas.
===== Alta Cohesión y Bajo Acoplamiento
Para diseñar una API efectiva, es crucial lograr una alta cohesión y un bajo acoplamiento entre sus componentes:
- *Acoplamiento*: Mide el grado de dependencia entre componentes.
- *Bajo Acoplamiento*: Es deseable porque implica que los componentes pueden modificarse independientemente sin afectar a otros componentes. Esto facilita la mantenibilidad y la flexibilidad del código.
- *Cohesión*: Mide el grado en que las funciones de un componente están relacionadas entre sí.
- *Alta Cohesión*: Es deseable porque significa que el componente realiza una única tarea o un conjunto de tareas relacionadas de manera eficiente y clara. Los componentes cohesivos son más fáciles de entender, probar y mantener.
Implementar alta cohesión y bajo acoplamiento en el diseño de una API ayuda a crear un sistema más modular, donde los cambios en una parte del sistema tienen un impacto mínimo en otras partes. Esto resulta en un código más robusto, flexible y fácil de mantener.
==== Estable, Documentada y Testeada
Para garantizar la calidad y usabilidad de una API, es fundamental que cumpla con los siguientes criterios:
- *Estabilidad*:
- La interfaz de la API debe ser versionada.
- Los cambios entre versiones no deben ser incompatibles, asegurando así que los clientes de la API puedan actualizar sin problemas.
- *Documentación Completa*:
- La API debe estar bien documentada.
- La documentación debe proporcionar información clara y detallada sobre las capacidades de la API, su comportamiento esperado, mejores prácticas y posibles condiciones de error.
- La documentación ayuda a los desarrolladores a entender y usar la API de manera efectiva y correcta.
- *Pruebas Automatizadas*:
- La implementación de la API debe estar respaldada por un conjunto exhaustivo de pruebas automatizadas.
- Estas pruebas aseguran que los cambios nuevos no rompan casos de uso existentes, proporcionando confianza en la estabilidad y confiabilidad de la API.
=== Bibliotecas de Software
Claro, aquí tienes una versión mejor
- *Definición*:
- También conocidas como librerías.
- Son colecciones de código precompilado que proporcionan funciones, clases y procedimientos reutilizables.
- *Funcionalidad*:
- Facilitan la realización de tareas específicas o comunes en el desarrollo de software.
- Permiten a lxs desarrolladorxs reutilizar código existente, ahorrando tiempo y esfuerzo.
- *API*:
- Las bibliotecas exponen una API que define cómo los clientes pueden interactuar con ellas.
- La API proporciona los bloques de construcción necesarios para integrar la funcionalidad de la biblioteca en aplicaciones más grandes.
Las bibliotecas de software son esenciales para la eficiencia y efectividad en el desarrollo de aplicaciones, proporcionando soluciones probadas y optimizadas para problemas comunes.
==== Bibliotecas vs Aplicaciones
*Bibliotecas:*
- *Funcionalidad*:
- Proveen funcionalidades específicas y reutilizables.
- No son ejecutables por sí mismas; requieren ser incluidas en una aplicación.
- Ofrecen una API para que lxs desarrolladorxs interactúen con sus funcionalidades.
*Aplicaciones:*
- *Propósito*:
- Resuelven un problema o realizan tareas específicas de principio a fin.
- Son ejecutables autónomos; pueden funcionar independientemente.
- Generalmente proporcionan una interfaz de usuario (UI) o una interfaz de línea de comandos (CLI) para que lxs usuarios finales interactúen.
Las bibliotecas y las aplicaciones juegan roles complementarios en el desarrollo de software, con las bibliotecas proporcionando herramientas y funcionalidades reutilizables que las aplicaciones integran y utilizan para cumplir con tareas completas y específicas.
==== Principios de Diseño de Bibliotecas
- *Interfaces Simples y Fáciles de Entender*:
- Mantén las interfaces de la biblioteca lo más simples posible.
- Facilita a lxs usuarios la comprensión y el uso de las funcionalidades proporcionadas.
- *Coherencia en Patrones de Diseño*:
- Sigue patrones de diseño coherentes en toda la biblioteca.
- Asegura que lxs usuarios puedan predecir el comportamiento y uso de diferentes componentes.
- *Componentes Independientes y Reutilizables*:
- Diseña componentes que sean independientes entre sí.
- Facilita la reutilización de componentes en diferentes contextos sin dependencias innecesarias.
- *Extensibilidad*:
- Permite a los usuarios ampliar la funcionalidad de la biblioteca sin necesidad de modificar el código fuente.
- Utiliza patrones de diseño como herencia, composición y polimorfismo para ofrecer extensibilidad.
- *Buena Documentación y Ejemplos de Uso*:
- Proporciona documentación clara y completa.
- Incluye ejemplos de uso prácticos que muestren cómo utilizar las diferentes funcionalidades de la biblioteca.
- Asegura que la documentación esté actualizada con cada nueva versión de la biblioteca.
|
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/apa7/template/sections/appendix.typ | typst | MIT License | = Final thoughts
#lorem(50)
== Thoughts on the future
#lorem(20)
#lorem(30)
=== Future work
#lorem(50)
==== Fourth level
#lorem(100)
== Acknowledgements
#lorem(50)
= List of Figures
#outline(
title: none,
target: figure.where(kind: image),
)
= List of Tables
#outline(
title: none,
target: figure.where(kind: table),
) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.1.0/template/chapters/global.typ | typst | Apache License 2.0 | #import "@preview/fh-joanneum-iit-thesis:1.1.0": *
|
https://github.com/christopherkenny/ctk-article | https://raw.githubusercontent.com/christopherkenny/ctk-article/main/_extensions/ctk-article/typst-template.typ | typst | #let titled-raw-block(body, filename: none) = {
if (filename != none) {
block(
inset: 0em,
fill: luma(200),
radius: 8pt,
outset: 0.75em,
width: 100%,
spacing: 2em,
[
#text(font: "DejaVu Sans Mono")[#filename]
#block(
fill: luma(230),
inset: 0em,
above: 1.2em,
outset: 0.75em,
radius: (bottom-left: 8pt, bottom-right: 8pt),
width: 100%,
body
)
]
)
} else {
body
}
}
// better way to avoid escape characters, rather than doing a regex for \\@
#let to-string(content) = {
if content.has("text") {
content.text
} else if content.has("children") {
content.children.map(to-string).join("")
} else if content.has("body") {
to-string(content.body)
} else if content == [ ] {
" "
}
}
// ctk-article definition starts here
// everything above is inserted by Quarto
#let ctk-article(
title: none,
subtitle: none,
runningtitle: none,
//runningauth: none,
authors: none,
date: none,
abstract: none,
thanks: none,
keywords: none,
cols: 1,
margin: (x: 1in, y: 1in),
paper: "us-letter",
lang: "en",
region: "US",
font: (),
fontsize: 11pt,
mathfont: "New Computer Modern Math",
codefont: "DejaVu Sans Mono",
sectionnumbering: "1.1.",
toc: false,
toc_title: none,
toc_depth: none,
toc_indent: 1.5em,
linestretch: 1,
linkcolor: "#800000",
title-page: false,
blind: false,
doc,
) = {
let runningauth = if authors == none {
none
} else if authors.len() == 2 {
authors.map(author => author.last).join(" and ")
} else if authors.len() < 5 {
authors.map(author => author.last).join(", ", last: ", and ")
} else {
authors.first().last + " et al."
}
set page(
paper: paper,
margin: margin,
numbering: "1",
header: locate(
loc => {
let pg = counter(page).at(loc).first()
if pg == 1 {
return
} else if (calc.odd(pg)) [
#align(right, runningtitle)
] else [
#if blind [
#align(right)[
#text(runningtitle)
]
] else [
#align(left)[
#text(runningauth)
]
]
]
v(-8pt)
line(length: 100%)
}
)
)
set page(
numbering: none
) if title-page
set par(
justify: true,
first-line-indent: 1em,
leading: linestretch * 0.65em
)
// Font stuff
set text(
lang: lang,
region: region,
font: font,
size: fontsize
)
show math.equation: set text(font: mathfont)
show raw: set text(font: codefont)
show figure.caption: it => [
#v(-1em)
#align(left)[
#block(inset: 1em)[
#text(weight: "bold")[
#it.supplement
#context it.counter.display(it.numbering)
]
#it.separator
#it.body
]
]
]
set heading(numbering: sectionnumbering)
// metadata
set document(
title: title,
author: to-string(runningauth),
date: auto,
keywords: keywords.join(", ")
)
// show rules
// show figure.where(kind: "quarto-float-fig"): set figure.caption(position: top)
set footnote.entry(indent: 0em, gap: 0.75em)
show link: this => {
if type(this.dest) != label {
text(this, fill: rgb(linkcolor.replace("\\#", "#")))
} else {
text(this, fill: rgb("#0000CC"))
}
}
show ref: this => {
text(this, fill: rgb("#640872"))
}
show cite.where(form: "prose"): this => {
text(this, fill: rgb("#640872"))
}
set list(indent: 2em)
set enum(indent: 2em)
// start article content
if title != none {
align(center)[
#block(inset: 2em)[
#text(weight: "bold", size: 30pt)[
#title #if thanks != none {
footnote(thanks, numbering: "*")
counter(footnote).update(n => n - 1)
}
]
#if subtitle != none {
linebreak()
text(subtitle, size: 18pt, weight: "semibold")
}
]
]
}
// author spacing based on Quarto ieee licenced CC0 1.0 Universal
// https://github.com/quarto-ext/typst-templates/blob/main/ieee/_extensions/ieee/typst-template.typ
if not blind {
for i in range(calc.ceil(authors.len() / 3)) {
let end = calc.min((i + 1) * 3, authors.len())
let slice = authors.slice(i * 3, end)
grid(
columns: slice.len() * (1fr,),
gutter: 12pt,
..slice.map(author => align(center, {
text(weight: "bold", author.name)
if "orcid" in author [
#link("https://https://orcid.org/" + author.orcid)[
#box(height: 9pt, image("ORCIDiD.svg"))
]
]
if author.department != none [
\ #author.department
]
if author.university != none [
\ #author.university
]
if author.location != [] [
\ #author.location
]
if "email" in author [
\ #link("mailto:" + to-string(author.email))
]
}))
)
v(20pt, weak: true)
}
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
align(center)[#block(width: 85%)[
#set par(
justify: true,
first-line-indent: 0em,
leading: linestretch * 0.65em * .85
)
*Abstract* \
#align(left)[#abstract]
]]
}
if keywords != none {
align(left)[#block(inset: 1em)[
*Keywords*: #keywords.join(" • ")
]]
}
if title-page {
// set page(numbering: none)
// pagebreak()
counter(page).update(n => n - 1)
}
set page(numbering: "1",
header: locate(
loc => {
let pg = counter(page).at(loc).first()
if (calc.odd(pg)) [
#align(right, runningtitle)
] else [
#if blind [
#align(right, runningtitle)
] else [
#align(left, runningauth)
]
]
}
)) if title-page
if toc {
let title = if toc_title == none {
auto
} else {
toc_title
}
block(above: 0em, below: 2em)[
#outline(
title: toc_title,
depth: toc_depth,
indent: toc_indent
);
]
}
if cols == 1 {
doc
} else {
columns(cols, doc)
}
}
#let appendix(body) = {
set heading(
numbering: "A.1.",
supplement: [Appendix]
)
set figure(
numbering: (..nums) => {
"A" + numbering("1", ..nums.pos())
},
supplement: [Appendix Figure]
)
counter(heading).update(0)
counter(figure.where(kind: "quarto-float-fig")).update(0)
counter(figure.where(kind: "quarto-float-tbl")).update(0)
body
}
#set table(
inset: 6pt,
stroke: none
)
|
|
https://github.com/herbhuang/utdallas-thesis-template-typst | https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/layout/appendix.typ | typst | MIT License | -- Supplementary Material -- |
https://github.com/Tiggax/zakljucna_naloga | https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/sec/uvod/1.%20intro.typ | typst | #import "../../additional.typ": todo
Bioprocesses using @GMO[s] are widely used in todays production of pharmaceuticals.
It is an expensive undertaking in both time and resources needed to produce the wanted end products.
They require expensive bioreactors, cell lines and substrates to run.
Much research is invested into growing, studying and evaluating the optimum conditions of these cell lines, as well as research of optimal bioreactor and substrates.
Research of these cell lines is conducted on smaller scales, to keep costs to the minimum, but this opens up a new problem.
Cell lines that grow optimally on small scales do not necessarily scale linearly into large bioreactors needed for industrial production. |
|
https://github.com/MobtgZhang/sues-thesis-typst | https://raw.githubusercontent.com/MobtgZhang/sues-thesis-typst/main/paper/info.typ | typst | MIT License | // 定义硕士学位论文模板
// 中文封面页信息
//============================================================================
#let num2month = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
// 中文封面页信息
// 中图分类号
#let master_classification_num = "CXX"
// 学号信息
#let master_class_number = "M987654321"
// 作者姓名
#let master_chinese_candidate_name = "MobtgZhang"
// 导师姓名
#let master_chinese_supervisor_name = "Supervisor"
// 专业名称
#let master_chinese_major_name = "控制科学与工程"
// 学院名称
#let master_chinese_faculty_name = "电子电气工程学院"
// 学位名称,分工学硕士和专业硕士
#let master_degree_name = "工学硕士"
// 中文完成日期
#let date_today = datetime.today()
#let master_chinese_finish_date_time = str(date_today.year())+" 年" + str(date_today.month()) + "月"
// 论文题目
#let master_chinese_title = "上海工程技术大学Typst模板"
#let master_reviewer = "A评阅"
#let master_chairman = "A主席"
#let master_member_first = "成员一、成员二"
#let master_member_second = "成员三、成员四"
//英文封面页信息
// 作者英文姓名
#let master_english_candidate_name = "<NAME>"
// 导师英文姓名
#let master_english_supervisor_name = "<NAME>"
// 专业英文名称
#let master_english_major_name = "Control Science and Engineering"
// 论文英文题目
#let master_english_title = "The Typst Template for Shanghai University of Engineering Science"
// 学院英文名称
#let master_english_faculty_name = "School of Electronic and Electrical Engineering"
// 英文完成日期
#let master_english_finish_date_time = str(num2month.at(date_today.month()-1))+" "+str(date_today.year())
|
https://github.com/AliothCancer/AppuntiUniversity | https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/transf_graph.typ | typst | #import "@preview/cetz:0.2.2": *
#let trasformazioni_graph(mode: str) = figure(
canvas(length: 2.7cm, {
let domain = (0.01,2)
let n_iso = 1;
let n_ad = 1.4;
let n_rand = 1.2;
let n_rand2 = .5;
let samples = 100;
let p1 = calc.pow(10,5); // 1 * 10^5 Pa
let v1 = 1; // m3/kg
let a4_sizes = (5,3.6);
let presentation_sizes = (4.7,3.8);
let size = a4_sizes
let legend = "legend.south"
if mode == "presentation"{
legend = "legend.east";
size = presentation_sizes;
}
plot.plot(
axis-style:"left",
x-min: 0,
x-max: 2,
y-min: 3.2*calc.pow(10,4),
y-max: 2.1*calc.pow(10,5),
y-label: $P ("Pa")$,
x-label:$#h(2cm) v(L/("kg"))$,
size: size,
x-grid: true,
y-grid: true,
y-format: "sci",
legend:legend ,
{
plot.add(
label: "n = " + str(-100) + $space ~ space -infinity "isovolumica"$,
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-(-100))
)
plot.add(
label: "n = " + str(-1.4),
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-(-1.4))
)
plot.add(
label: "n = " + str(-1),
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-(-1))
)
plot.add(
label: "n = " + str(0) + $" isobara"$,
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-(0))
)
plot.add(
label: "n = " + str(n_rand2),
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-n_rand2)
)
plot.add(
label: "n=1 (isoterma)",
domain: domain,
samples: samples,
//fill: true,
//style: style(palette.cyan(2)),
v => p1*v1 * calc.pow(v,-n_iso)
)
plot.add(
label: "n = k = 1.4 (isoentr.)",
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-n_ad)
)
plot.add(
label: "n = " + str(100)+ $space ~ space infinity "isovolumica"$,
domain: domain,
samples: samples,
v => p1*v1 * calc.pow(v,-100)
)
plot.add(((v1,p1),), mark: "o",mark-style: (stroke: blue, fill: black,), mark-size: .1)
// plot.add(((2,3.8*calc.pow(10,4)),), mark: "o",mark-style: (stroke: black, fill: black), mark-size: .1)
//
//
// plot.add(((2,5*calc.pow(10,4)),), mark: "o",mark-style: (stroke: blue, fill: black), mark-size: .1)
//
})
}), caption: "Differenti curve al variare dell'indice n della politropica \n(Plot made with cetz)",)
|
|
https://github.com/ENIB-Community/ENIB_Typst_Internship_Template | https://raw.githubusercontent.com/ENIB-Community/ENIB_Typst_Internship_Template/main/README.md | markdown | MIT License | # Typst Intership Template
<!-- This sentence is from the typst repo -->
> [Typst](https://github.com/typst/typst) is a new markup-based typesetting system
> that is designed to be as powerful as LaTeX while being much easier to learn and use.
I recommend that you check it out, if you don't know it yet.
This repo contains a template for ENIB internship reports.
## Install typst
Either:
- Get an executable from the [Typst releases page](https://github.com/typst/typst/releases).
- Install [cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) and then run `cargo install --locked --git https://github.com/typst/typst typst-cli` (this will compile the latest version of typst).
## Build the document
```shell
typst compile main.typ main.pdf
```
If you want to edit your internship report and get a (nearly) instant feedback: run `typst watch main.typ`.
> NOTE: `typst watch` does not recompile the whole pdf each time you make a document change to the source files. It use incremental compilation, meaning `typst watch` recompile only the Abstract Syntax Tree part that need recompiling.
|
https://github.com/cadojo/correspondence | https://raw.githubusercontent.com/cadojo/correspondence/main/src/vita/src/education.typ | typst | MIT License | #let degreeslist = state("degreeslist", ())
#let duration(start, stop) = {
text(rgb(90,90,90))[
#start #if (start != none and stop != none) { " — " } #stop
]
}
#let degree(
title, field,
school: none,
start: none,
stop: none,
notes
) = {
let content = [
#grid(
columns: (1fr, 1fr),
heading(level: 3, (title, field).join(" ")),
align(right)[
#duration(start, stop)
]
)
#if school != none {
set text(rgb(90,90,90), weight: "regular")
v(-0.5em)
school
}
#notes
]
degreeslist.update(current => current + (content,))
}
#let degrees(header: "Education") = {
locate(
loc => {
let content = degreeslist.final(loc)
if content.len() > 0 {
heading(level: 2, header)
line(length: 100%, stroke: 1pt + black)
content.join()
}
}
)
}
|
https://github.com/rayfiyo/myTypst | https://raw.githubusercontent.com/rayfiyo/myTypst/main/note/main.typ | typst | BSD 3-Clause "New" or "Revised" License | #import "./template.typ": *
#import "@preview/codelst:2.0.0": sourcecode, sourcefile, lineref, code-frame
#show: master_thesis.with(bibliography-file: "references.bib")
= メモ
// = 参考文献 // 自動生成
= チートシート
== コードブロック
#sourcecode(numbers-start: 1)[```c
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
```]
// #sourcefile(read("ぱす"), file:"ファイル名")
== 引用
// @ss8843592
== 数式
$ A = mat(1, 2;3, 4) $ <eq1>
// @eq1 を表示
== 画像
#img(
image("appendix/images/ladder.svg", width: 20%), caption: [オリジナルのThe Go gopher(Gopherくん)は、Renée
Frenchによってデザインされました。],
) <img1>\
@img1 を表示
== 表
#tbl(
table(columns: 4, [t], [1], [2], [3], [y], [0.3s], [0.4s], [0.8s]), caption: [テーブル],
) <tbl1>
@tbl1 を表示
== URL埋め込み
#link("https://typst.app/docs")[公式ドキュメント]
== 定理
#let theorem = thmbox("theorem", "定理", base_level: 1)
#theorem("ヲイラ-")[
Typst はすごいのである.
] <theorem>
== 補題
#let lemma = thmbox("theorem", "補題", base_level: 1)
#lemma[
Texはさようならである.
] <lemma>
== 定義
#let definition = thmbox("definition", "定義", base_level: 1, stroke: black + 1pt)
#definition[
Typst is a new markup-based typesetting system for the sciences.
] <definition>
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1C90.typ | typst | Apache License 2.0 | #let data = (
("GEORGIAN MTAVRULI CAPITAL LETTER AN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER BAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER GAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER DON", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER EN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER VIN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER ZEN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER TAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER IN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER KAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER LAS", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER MAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER NAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER ON", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER PAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER ZHAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER RAE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER SAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER TAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER UN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER PHAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER KHAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER GHAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER QAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER SHIN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER CHIN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER CAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER JIL", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER CIL", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER CHAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER XAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER JHAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HAE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HIE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER WE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HAR", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HOE", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER FI", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER YN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER ELIFI", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER TURNED GAN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER AIN", "Lu", 0),
(),
(),
("GEORGIAN MTAVRULI CAPITAL LETTER AEN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER HARD SIGN", "Lu", 0),
("GEORGIAN MTAVRULI CAPITAL LETTER LABIAL SIGN", "Lu", 0),
)
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/src/selectors.typ | typst | MIT License | #import "/src/util.typ"
/// Create a custom selector for `hydra`.
///
/// - element (function, selector): The primary element to search for.
/// - filter (function): The filter to apply to the element.
/// - ancestors (function, selector): The ancestor elements, this should match all of its ancestors.
/// - ancestors-filter (function): The filter applied to the ancestors.
/// -> hydra-selector
#let custom(
element,
filter: none,
ancestors: none,
ancestors-filter: none,
) = {
util.assert.types("element", element, function, selector, label)
util.assert.types("filter", filter, function, none)
util.assert.types("ancestors", ancestors, function, selector, label, none)
util.assert.types("ancestors-filter", ancestors-filter, function, none)
util.assert.queryable("element", element)
if ancestors != none {
util.assert.queryable("ancestors", ancestors)
}
if ancestors == none and ancestors-filter != none {
panic("`ancestor` must be set if `ancestor-filter` is set")
}
(
primary: (target: element, filter: filter),
ancestors: if ancestors != none { (target: ancestors, filter: ancestors-filter) },
)
}
/// Create a heading selector for a given range of levels.
///
/// - ..exact (int, none): The exact level to consider as the primary element
/// - min (int, none): The inclusive minimum level to consider as the primary heading
/// - max (int, none): The inclusive maximum level to consider as the primary heading
/// -> hydra-selector
#let by-level(
min: none,
max: none,
..exact,
) = {
let (named, pos) = (exact.named(), exact.pos())
assert.eq(named.len(), 0, message: util.fmt("Unexected named arguments: `{}`", named))
assert(pos.len() <= 1, message: util.fmt("Unexpected positional arguments: `{}`", pos))
exact = pos.at(0, default: none)
util.assert.types("min", min, int, none)
util.assert.types("max", max, int, none)
util.assert.types("exact", exact, int, none)
if min == none and max == none and exact == none {
panic("Use `heading` directly if you have no `min`, `max` or `exact` level bound")
}
if exact != none and (min != none or max != none) {
panic("Can only use `min` and `max`, or `exact` bound, not both")
}
if exact == none and (min == max) {
exact = min
min = none
max = none
}
let (primary, primary-filter) = if exact != none {
(heading.where(level: exact), none)
} else if min != none and max != none {
(heading, (ctx, e) => min <= e.level and e.level <= max)
} else if min != none {
(heading, (ctx, e) => min <= e.level)
} else if max != none {
(heading, (ctx, e) => e.level <= max)
}
let (ancestors, ancestors-filter) = if exact != none {
(heading, (ctx, e) => e.level < exact)
} else if min != none and min > 1 {
(heading, (ctx, e) => e.level < min)
} else {
(none, none)
}
custom(
primary,
filter: primary-filter,
ancestors: heading,
ancestors-filter: ancestors-filter,
)
}
/// Turn a selector or function into a hydra selector.
///
/// *This function is considered unstable.*
///
/// - name (str): The name to use in the assertion message.
/// - sel (any): The selector to sanitize.
/// - message (str, auto): The assertion message to use.
/// -> hydra-selector
#let sanitize(name, sel, message: auto) = {
let message = util.or-default(check: auto, message, () => util.fmt(
"`{}` must be a `selector`, a level, or a custom hydra-selector, was {}", name, sel,
))
if type(sel) == selector {
let parts = repr(sel).split(".")
// NOTE: because `repr(math.equation) == equation` we add it to the scope
// NOTE: No, I don't like this either
let func = eval(if parts.len() == 1 {
parts.first()
} else {
parts.slice(0, -1).join(".")
}, scope: (equation: math.equation))
if func == heading {
let fields = (:)
if parts.len() > 1 {
let args = parts.remove(-1)
for arg in args.trim("where").trim(regex("\(|\)"), repeat: false).split(",") {
let (name, val) = arg.split(":").map(str.trim)
fields.insert(name, eval(val))
}
}
assert.eq(fields.len(), 1, message: message)
assert("level" in fields, message: message)
by-level(fields.level)
} else {
custom(sel)
}
} else if type(sel) == int {
by-level(sel)
} else if type(sel) == function {
custom(sel)
} else if type(sel) == dictionary and "primary" in sel and "ancestors" in sel {
sel
} else {
panic(message)
}
}
|
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/布局/direction/direction.typ | typst | = direction
内容可以布置的四个方向。
可能的值为:
- ltr: 左到右。
- rtl: 右到左。
- ttb: 从上到下。
- btt:从下到上。
这些值在全局范围内可用,并且在方向类型的范围内可用,因此您可以编写以下两个值之一:
#image("屏幕截图 2024-04-14 173757.png") |
|
https://github.com/TJ-CSCCG/tongji-undergrad-thesis-typst | https://raw.githubusercontent.com/TJ-CSCCG/tongji-undergrad-thesis-typst/main/init-files/main.typ | typst | MIT License | #import "../paddling-tongji-thesis/tongjithesis.typ": *
#set pagebreak(weak: true)
#show: thesis.with(
school: "某某学院", major: "某某专业", id: "1999999", student: "某某某", teacher: "某某某", title: "论文模板", subtitle: [基于多种场景的Typst简要教程], title-english: "Thesis Template", subtitle-english: "with Various Scenes", date: datetime(
year: datetime.today().year(), month: datetime.today().month(), day: datetime.today().day(),
), abstract: [
摘要通常是一篇文章、论文、报告或其他文本的简短概括。它的目的是帮助读者了解文本的主要内容和结论,以便决定是否需要继续阅读原文。摘要通常包含文本的主题、目的、方法、结果和结论等方面的信息,并尽可能简洁明了地呈现。好的摘要应该能够概括文本的重点,同时避免使用不必要的细节和专业术语,以便广大读者能够轻松理解。
此外,摘要通常也是学术界和研究人员评估一篇文献的重要依据之一。在文献检索和筛选过程中,人们通常会根据摘要来决定是否进一步查看完整的文献。因此,撰写一个清晰、准确、简洁的摘要对于文献的传播和影响力至关重要。在撰写摘要时,作者应该遵循文献的格式要求和撰写规范,同时结合文本的内容和目的,将摘要撰写得准确、简洁、易懂,以提高文献的传播和影响力。
关键词1,关键词2,关键词3通常是与文章内容相关的几个词语,用于帮助读者更好地了解文章主题和内容。关键词的选择应该与文章的主题和研究领域密切相关,通常应该选择具有代表性、权威性、独特性和可搜索性的词语。
], keywords: ("关键词1", "关键词2", "关键词3"), abstract-english: [
An abstract is usually a short summary of an article, essay, report, or other
text. Its purpose is to help the reader understand the main content and
conclusions of the text so that he or she can decide whether he or she needs to
continue reading the original text. The abstract usually contains information
about the topic, purpose, methods, results, and conclusions of the text and is
presented as concisely and clearly as possible. A good abstract should be able
to summarize the main points of the text while avoiding unnecessary details and
jargon so that it can be easily understood by a wide audience.
In addition, abstracts are often one of the most important bases on which
academics and researchers evaluate a piece of literature. During the literature
search and selection process, people often base their decision to look further
into the complete literature on the abstract. Therefore, writing a clear,
accurate, and concise abstract is crucial to the dissemination and impact of the
literature. When writing an abstract, authors should follow the formatting
requirements and writing specifications of the literature, as well as combine
the content and purpose of the text to write an accurate, concise, and
easy-to-understand abstract in order to improve the dissemination and impact of
the literature.
Keyword 1, Keyword 2, and Keyword 3 are usually a few words related to the
content of the article and are used to help readers better understand the topic
and content of the article. The choice of keywords should be closely related to
the topic and research area of the article, and words that are representative,
authoritative, unique, and searchable should usually be chosen.
], keywords-english: ("Keyword 1", "Keyword 2", "Keyword 3"),
)
#include "sections/01_intro.typ"
#pagebreak()
#include "sections/02_math.typ"
#pagebreak()
#include "sections/03_reference.typ"
#pagebreak()
#include "sections/04_figure.typ"
#pagebreak()
#include "sections/05_conclusion.typ"
#pagebreak()
#bibliography("bib/note.bib", full: false, style: "gb-7714-2015-numeric")
#pagebreak()
#include "sections/acknowledgments.typ"
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-rect_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 15-21 expected length, color, gradient, pattern, dictionary, stroke, none, or auto, found array
// #rect(stroke: (1, 2)) |
https://github.com/SnowManKeepsOnForgeting/NoteofModernControlTheory | https://raw.githubusercontent.com/SnowManKeepsOnForgeting/NoteofModernControlTheory/main/Chapter3/Chapter3.typ | typst | #import "@preview/physica:0.9.3": *
#import "@preview/i-figured:0.2.4"
#set heading(numbering: "1.1")
#show math.equation: i-figured.show-equation.with(level: 2)
#show heading: i-figured.reset-counters.with(level: 2)
#set text(font: "CMU Serif")
#let xbd = $accent(bold(x),dot)$
#counter(heading).update(2)
= Solution of State Equations
== Solution of Liner Time Invariant Homogeneous State Equations
Given a liner time invariant homogeneous state equation:
$
accent(bold(x),dot)(t) = bold(A) bold(x)(t)
$
If the input is zero and $t_0 = 0$,it is easy to see that the solution is:
$
bold(x) = e^(bold(A)t )bold(x)(0)
$
If the $t_0 != 0$, the solution is:
$
bold(x)(t) = e^(bold(A)(t-t_0))bold(x)(t_0)
$
We call $e^(bold(A)(t-t_0))$ as matrix exponential or state transition matrix and note it as $Phi(t)$.
== Matrix Exponential
*Definition*:
$
e^(bold(A)t) = bold(I) + bold(A)t + bold(A)^2 t^2 / 2! + bold(A)^3 t^3 / 3! + dots
$
(1)
$
dv(,t)e^(bold(A)t) = bold(A) e^(bold(A)t) = e^(bold(A)t)bold(A)\
dv(,t)Phi(t) = bold(A)Phi(t) = Phi(t)bold(A)
$
(2)
$
e^(bold(A) dot 0) = bold(I)\
Phi(0) = bold(I)
$
(3)
$
[e^(bold(A) t)]^(-1) = e^(-bold(A)t)\
[Phi(t)]^(-1) = Phi^(-1)(t)=Phi(-t)
$
(4)
$
e^(bold(A)(t_2-t_0))e^(bold(A)(t_0-t_1)) = e^(bold(A)(t_2-t_1))
$
(5)If and only if $bold(A) bold(B) = bold(B) bold(A)$
$
e^((bold(A) + bold(B))t) = e^(bold(A)t)e^(bold(B)t)
$
*Some special matrix exponential:*
(1) Diagonal matrix:It is easy to see that:
$
A = diag(lambda_1,lambda_2,...,lambda_n)\
e^(bold(A)t) = diag(e^(lambda_1 t),e^(lambda_2 t),...,e^(lambda_n t))
$
(2) Jordan block matrix:
$
A = mat(delim: "[",lambda,1,,,,0;,lambda,dots.down;,,dots.down,;,,,,lambda,1;
0,,,,,lambda)\
$
We have:
$
bold(A)^2 = mat(delim: "[",lambda^2,2 lambda,1,,0;
,lambda^2,2 lambda,dots.down;,,lambda^2,dots.down;
;,,,,dots.down),bold(A)^3 = mat(delim: "[",lambda^3,3 lambda^2,3lambda,1,,,,0;
,lambda^3,3 lambda^2,dots.down;,,lambda^3,dots.down;
;,,,,dots.down)
$
We can induct that:
$
bold(f)(
bold(A)
) = mat(delim: "[",f(lambda),f^'(lambda),(f^('')(lambda)) / (2!),(f^(''')(lambda)) / (3!),dots,dots;
,f(lambda),f^'(lambda),(f^('')(lambda)) / (2!),dots,dots;
,,dots.down,dots.down;
,,,,dots.down)
$where $bold(f)$ stands for a power function.
Let us plus them by definition of matrix exponential:
$
e^(bold(A)t) = e^(lambda t)mat(delim: "[" ,1,t,t^2 / 2!,t^3 / 3!,dots,t^(m-1)/(m-1)!;
,1,t,t^2 / 2!,dots,t^(m-2)/(m-2)!;
,,dots.down,dots.down,,dots.v;
,,,,,1)
$
(3) Jordan form matrix
Let $bold(A)$ be a matrix with Jordan form:
$
bold(A) = mat(delim: "[",bold(A)_1,bold(0),dots,bold(0);
bold(0),bold(A)_2,dots,bold(0);
dots.v,dots.v,dots.down,dots.v;
bold(0),bold(0),dots,bold(A)_n)
$where $bold(A)_i$ is a Jordan block matrix.
We have:
$
e^(bold(A)t) = mat(delim: "[",e^(bold(A)_1 t),bold(0),dots,bold(0);
bold(0),e^(bold(A)_2 t),dots,bold(0);
dots.v,dots.v,dots.down,dots.v;
bold(0),bold(0),dots,e^(bold(A)_n t))
$
*Method of Calculate Matrix Exponential*
(1) *Laplace transformation method*
Let us consider a liner time invariant homogeneous state equation:
$
accent(bold(x),dot)(t) = bold(A) bold(x)(t),bold(x)(0) = bold(x)_0,t >= t_0
$
We do laplace transformation on both sides:
$
s bold(X)(s) - bold(x)(0)= bold(A) bold(X)(s)
$
We can get:
$
bold(x)(t) = cal(L)^(-1)[(s bold(I) - bold(A))^(-1)]bold(x)(0)
$
By uniqueness of solution of differential equation, we can get:
$
e^(bold(A)t ) = cal(L)^(-1)[(s bold(I) - bold(A))^(-1)]
$
(2) *Polynomial method*
Cayley-Hamilton theorem tells us that:If matrix $bold(A)$ is a $n times n$ square matrix, then:
$
f(lambda) = det(lambda bold(I) - bold(A)) = lambda^n + a_1 lambda^(n-1) + a_2 lambda^(n-2) + dots + a_n = 0
$
$
f(bold(A)) = bold(A)^n + a_1 bold(A)^(n-1) + a_2 bold(A)^(n-2) + dots + a_n bold(I) = bold(0)
$
By Cayley-Hamilton theorem, we get that $bold(A)^(n)$ is actually a linear combination of $bold(A)^(n-1),bold(A)^(n-2),dots,bold(I)$.It is similar to $bold(A)^(n+1),bold(A)^(n+2),dots$ which means we can write $e^(bold(A)t)$ as a linear combination of $bold(I),bold(A),bold(A)^2,dots,bold(A)^(n-1)$.
When *eigenvalues of $bold(A)$ are all different*,let us consider the following equation to get $e^(lambda t)$($e^(bold(A)t)$ and $e^(lambda t)$ should have the same coefficient $a_i (t)$):
$
cases(
e^(lambda_1 t) = a_0(t) + a_1(t) lambda_1 + a_2(t) lambda_1^2 + dots + a_(n-2)(t) lambda_1^(n-2) + a_(n-1)(t) lambda_1^(n-1)\
e^(lambda_2 t) = a_0(t) + a_1(t) lambda_2 + a_2(t) lambda_2^2 + dots + a_(n-2)(t) lambda_2^(n-2) + a_(n-1)(t) lambda_2^(n-1)\
#h(2em) dots.v\
e^(lambda_n t) = a_0(t) + a_1(t) lambda_n + a_2(t) lambda_n^2 + dots + a_(n-2)(t) lambda_n^(n-2) + a_(n-1)(t) lambda_n^(n-1)
)
$
Thus we have:
$
vec(delim: "[",a_0(t),a_1(t),dots.v,a_(n-1)(t)) = mat(
delim: "[",
1,lambda_1,lambda_1^2,dots,lambda_1^(n-1);
1,lambda_2,lambda_2^2,dots,lambda_2^(n-1);
dots.v,dots.v,dots.v,dots.down,dots.v;
1,lambda_n,lambda_n^2,dots,lambda_n^(n-1)
)^(-1) vec(delim: "[",e^(lambda_1 t),e^(lambda_2 t),dots.v,e^(lambda_n t))
$
When *eigenvalues of $bold(A)$ are not all different*,let us consider the following equation to get $e^(lambda t)$.We still have:
$
cases(
e^(lambda_1 t) = a_0(t) + a_1(t) lambda_1 + a_2(t) lambda_1^2 + dots + a_(n-2)(t) lambda_1^(n-2) + a_(n-1)(t) lambda_1^(n-1)\
e^(lambda_2 t) = a_0(t) + a_1(t) lambda_2 + a_2(t) lambda_2^2 + dots + a_(n-2)(t) lambda_2^(n-2) + a_(n-1)(t) lambda_2^(n-1)\
#h(2em) dots.v\
e^(lambda_m t) = a_0(t) + a_1(t) lambda_m + a_2(t) lambda_m^2 + dots + a_(n-2)(t) lambda_m^(n-2) + a_(n-1)(t) lambda_m^(n-1)
)
$where $m < n$.To get more equations to get $a_i$,we do differential on both sides of $e^(lambda_i t) $ to $lambda_i$ until $(n-1)$ times.For example,we have a n-fold eigenvalue $lambda_k$:
$
cases(
e^(lambda_k t) = a_0(t) + a_1(t) lambda_k + a_2(t) lambda_k^2 + dots + a_(n-2)(t) lambda_k^(n-2) + a_(n-1)(t) lambda_k^(n-1)\
(lambda_k)/(1!) e^(lambda_k t) = a_1(t) + 2 a_2(t) lambda_k + dots + (n-1) a_(n-1)(t) lambda_k^(n-2)\
lambda_k^2/(2!) e^(lambda_k t) = a_2(t) + 3 a_3(t) lambda_k + dots + ((n-1)(n-2))/(2!) a_(n-1)(t) lambda_k^(n-3)\
#h(2em)dots.v\
lambda_k^(n-1)/(n-1)! e^(lambda_k t) = a_(n-1)(t)
)
$
Thus we have enough equations to get $a_i (t)$ for example.
$
cases(
e^(lambda_1 t) = a_0(t) + a_1(t) lambda_1 + a_2(t) lambda_1^2 + dots + a_(n-2)(t) lambda_1^(n-2) + a_(n-1)(t) lambda_1^(n-1)\
lambda_1/(1!) e^(lambda_1 t) = a_1(t) + 2 a_2(t) lambda_1 + dots + (n-1) a_(n-1)(t) lambda_1^(n-2)\
lambda_1^2/(2!) e^(lambda_1 t) = a_2(t) + 3 a_3(t) lambda_1 + dots + ((n-1)(n-2))/(2!) a_(n-1)(t) lambda_1^(n-3)\
e^(lambda_2 t) = a_0(t) + a_1(t) lambda_2 + a_2(t) lambda_2^2 + dots + a_(n-2)(t) lambda_2^(n-2) + a_(n-1)(t) lambda_2^(n-1)\
lambda_2/(1!) e^(lambda_2 t) = a_1(t) + 2 a_2(t) lambda_2 + dots + (n-1) a_(n-1)(t) lambda_2^(n-2)\
e^(lambda_3 t) = a_0(t) + a_1(t) lambda_3 + a_2(t) lambda_3^2 + dots + a_(n-2)(t) lambda_3^(n-2) + a_(n-1)(t) lambda_3^(n-1)\
#h(2em) dots.v\
e^(lambda_m t) = a_0(t) + a_1(t) lambda_m + a_2(t) lambda_m^2 + dots + a_(n-2)(t) lambda_m^(n-2) + a_(n-1)(t) lambda_m^(n-1)
)
$
We can write it as matrix form for example:
$
vec(delim: "[",a_0(t),a_1(t),a_2(t),a_3(t),a_4(t),dots.v,a_(n-1)(t)) =
mat(delim: "[", 0,0,1,3lambda_1,dots,((n-1)(n-2))/(2!)lambda_1^(n-3);
0,1,2lambda_1,3lambda^2,dots,((n-1))/(1!)lambda_1^(n-2);
1,lambda_1,lambda_1^2,lambda^3,dots,lambda_1^(n-1);
0,1,2lambda_2,3lambda_2^2,dots,((n-1))/(1!)lambda_2^(n-2);
1,lambda_2,lambda_2^2,lambda_2^3,dots,lambda_2^(n-1);
1,lambda_3,lambda_3^2,lambda_3^3,dots,lambda_3^(n-1);
dots.v,dots.v,dots.v,dots.v,dots,dots.v;
1,lambda_m,lambda_m^2,lambda_m^3,dots,lambda_m^(n-1)
)^(-1) vec(delim: "[",1/(2!) t^2 e^(lambda_1 t),1/(1!) t e^(lambda_1 t),e^(lambda_1 t),1/(1!) t e^(lambda_2 t),e^(lambda_2 t),e^(lambda_3 t),dots.v,e^(lambda_m t))
$
(3) *Liner transformation method*
*If matrix $bold(A)$ can be transformed to a diagonal matrix($Lambda = bold(P) bold(A) bold(P)^(-1)$),in other words,all eigenvalues are different*,we can get $e^(bold(A)t)$ easily by the following equation:
$
e^(bold(A)t) = bold(I) + bold(A)t + 1 / (2!) bold(A)^2 t^2 + 1 / 3! bold(A)^3 t^3 + dots \
= bold(I) + bold(P)^(-1)Lambda bold(P)t + 1 / 2! bold(P)^(-1)Lambda bold(P) bold(P)^(-1)Lambda bold(P)t^2 + 1 / 3! bold(P)^(-1)Lambda bold(P) bold(P)^(-1)Lambda bold(P) bold(P)^(-1)Lambda bold(P)t^3 + dots\
= bold(I) + bold(P)^(-1)Lambda bold(P)t + 1 / 2! bold(P)^(-1)Lambda^2 bold(P)t^2 + 1 / 3! bold(P)^(-1)Lambda^3 bold(P)t^3 + dots\
= bold(P)^(-1) (bold(I) + bold(Lambda)t + 1 / 2! bold(Lambda)^2 t^2 + 1 / 3! bold(Lambda)^3 t^3 + dots) bold(P)\
= bold(P)^(-1) e^(Lambda t) bold(P)
$
*If matrix $bold(A)$ can't be transformed to a diagonal matrix,in other words,some eigenvalues are the same*,we can use Jordan form matrix to get $e^(bold(A)t)$.We have $bold(J) = bold(P) bold(A) bold(P)^(-1)$ where $bold(J)$ is a Jordan form matrix.
We have
$
e^(bold(A)t) = bold(P)^(-1) e^(bold(J)t) bold(P)
$
*If matrix $bold(A)$ have complex eigenvalues*,we can use the following equation to get $e^(bold(A)t)$.The eigenvalues of $bold(A)$ are $lambda_1 = alpha + beta i$ and $lambda_2 = alpha - beta i$.We have:
$
bold(M) = bold(P) bold(A) bold(P)^(-1) = mat(delim: "[",alpha,beta;-beta,alpha)\
$
And
$
e^(bold(M) t) = e^(mat(delim: "[",alpha,0;0,alpha)t) e^(mat(delim: "[",0,beta;-beta,0)t)
$
where
$
e^(mat(delim: "[",alpha,0;0,alpha)t) = mat(delim: "[",e^(alpha t),0;0,e^(alpha t))\
e^(mat(delim: "[",0,beta;-beta,0)t) = mat(delim: "[",cos(beta t),sin(beta t);-sin(beta t),cos(beta t))
$
Thus we have:
$
e^(bold(A) t) = bold(P)^(-1) e^(bold(M)t)bold(P)
$
== Solution of Liner Time Invariant Nonhomogeneous State Equations
Given a liner time invariant nonhomogeneous state equation:
$
#xbd (t) = bold(A)bold(x)(t) + bold(B)bold(u)(t)
$
We can conduct the following steps to get the solution:
$
#xbd (t) - bold(A)bold(x)(t) = bold(B)bold(u)(t)\
e^(-bold(A)t) #xbd (t) - e^(-bold(A)t)bold(A)bold(x)(t) = e^(-bold(A)t)bold(B)bold(u)(t)\
dv(,t)(e^(-bold(A)t)bold(x)(t)) = e^(-bold(A)t)bold(B)bold(u)(t)\
$
Thus we do intergration on both sides from $0$ to $t$:
$
e^(-bold(A)t)bold(x)(t) |_(0)^(t) = integral_(0)^(t) e^(-bold(A)tau)bold(B)bold(u)(tau) dd(tau)
$
So we have:
$
bold(x)(t) = e^(bold(A)t)bold(x)(0) + integral_(0)^(t) e^(bold(A)(t-tau))bold(B)bold(u)(tau) dd(tau)
$
Or we can write it as:
$
bold(x)(t) = Phi(t)bold(x)(0) + integral_(0)^(t) Phi(t-tau)bold(B)bold(u)(tau) dd(tau)
$
And it is easy to see output is:
$
bold(y)(t) = bold(C)bold(x)(t) + bold(D)bold(u)(t)\
= bold(C) e^(bold(A)t)bold(x)(0) + bold(C) integral_(0)^(t) e^(bold(A)(t-tau))bold(B)bold(u)(
tau
) dd(tau) + bold(D)bold(u)(t)
$ |
|
https://github.com/j1nxie/resume | https://raw.githubusercontent.com/j1nxie/resume/main/data.typ | typst | Do What The F*ck You Want To Public License | #import "template.typ": *
#let name = "<NAME>"
#let email = [
#icon("assets/email.svg") <EMAIL>
]
#let phone = [
#icon("assets/phone.svg")
(+84) 988750695
]
#let home = [
#icon("assets/home.svg")
#link("https://rylie.moe")[ rylie.moe ]
]
#let github = [
#icon("assets/github.svg")
#link("https://github.com/j1nxie")[ j1nxie ]
]
#let linkedin = [
#icon("assets/linkedin.svg")
#link("https://linkedin.com/in/lumi9")[ <NAME> ]
]
#let author = (name: name, email: email, phone: phone, home: home, github: github, linkedin: linkedin)
#let selftitle = [ Self Introduction ]
#let self = [
Passionate developer with interests in web technologies, video games design and operating systems. Always looking to learn and develop new skills to improve myself and empower projects. Writes and maintains open source projects. Has worked with Rust for about 2.5 years, and TypeScript/JavaScript for about 1.5 years.
]
#let edutitle = [ Education ]
#let edu = [
#datedsubsection(align(left)[
*University of Science and Technology of Hanoi* \
Information and Communication Technology
], align(right)[
Hanoi, Vietnam \
Oct 2021 - _present_
])
]
#let techtitle = [ Technical Skills ]
#let tech = [
#datedsubsection(align(left)[
*Programming Languages*
], align(right)[
Rust, TypeScript, Python, C\#
])
#datedsubsection(align(left)[
*Web Development*
], align(right)[
React, Vue.js, Angular, HTML, CSS
])
#datedsubsection(align(left)[
*Databases*
], align(right)[
Postgres, MongoDB, Redis
])
#datedsubsection(align(left)[
*Other Tools*
], align(right)[
Docker, Git, Linux, S3
])
]
#let experiencetitle = [ Experience ]
#let experience = [
// #datedsubsection(align(left)[
// *Yomuyume* \
// Backend Developer
// ], align(right)[
// * https://github.com/Liminova/yomuyume * \
// Sep 2023 - _present_
// ])
// - Self-hosting manga/comics server, with support for various image and archive
// types.
// - Utilizes Rust and the Axum framework for a performant and featureful backend.
// - Leverages SQLite for storing data.
#datedsubsection(align(left)[
*Nabit* \
Developer
], align(right)[
* https://nabit.vn * \
Aug 2023 - Oct 2024
])
- Web-based management system for gas retailers, warehouses and wholesalers.
- Powered by Angular for the frontend, .NET Core for the backend, and Microsoft SQL Server for the database.
- Powerful management features, with connections to multiple e-invoice systems for instant invoice management.
#datedsubsection(align(left)[
*Tachi* \
Maintainer
], align(right)[
* https://github.com/zkrising/Tachi * \
Aug 2022 - _present_
])
- Implemented and currently maintaining maimai DX for Tachi, an open-source score tracker website for 3M+ arcade scores and 3K+ users.
- Utilizes TypeScript and JavaScript to scrape and parse data for music database and importing scores.
#datedsubsection(align(left)[
*Zenith* \
Rust Developer
], align(right)[
* https://zenith.game * \
Mar 2024 - _present_
])
- Developed the content server for Zenith, a heavily in-development rhythm game client with support for multiple game modes, alongside an uploader according to the specifications.
- Uses Rust and Axum to interact with an S3-compatible storage for content storage and retrieval.
- Implemented a client interface for interacting with said content server within Zenith's core.
// #datedsubsection(align(left)[
// *Vietnam Community League* \
// Backend Developer
// ], align(right)[
// * https://vcl.works * \
// Dec 2022 - _present_
// ])
// - Part of Vietnam Community League's staff lineup, Vietnam's premiere osu! esports
// league, running the largest and highest-quality tournaments in Vietnam.
// - Took part in rewriting the backend from C\# to Rust.
]
#let activitytitle = [ Activity Experience ]
#let activity = [
#datedsubsection(align(left)[
*#lorem(8)* \
#lorem(4)
], align(right)[
202x
])
#lorem(32)
#datedsubsection(align(left)[
*#lorem(8) *\
#lorem(4)
], align(right)[
202x - _present_
])
#lorem(16)
#datedsubsection(align(left)[
*#lorem(8)* \
#lorem(4)
], align(right)[
202x
])
- #lorem(8)
- #lorem(8)
]
#let hobbiestitle = [ Hobbies and Interests ]
#let hobbies = [
I'm interested in art and music. I've been playing rhythm games
semi-competitively for about 5 years. Recently, I've taken an interest in
mechanical keyboards and rhythm games controller design. I'm also a part of
osu!'s tournament community, having been participant and staff in many
tournaments since 2020.
]
|
https://github.com/r8vnhill/apunte-bibliotecas-de-software | https://raw.githubusercontent.com/r8vnhill/apunte-bibliotecas-de-software/main/Unit3/Plugins.typ | typst | == Plugins
Los plugins extienden las capacidades de Gradle al agregar nuevas tareas, configuraciones y funcionalidades a los scripts de build.
Permiten la reutilización de configuraciones de build sin necesidad de duplicar código en múltiples proyectos.
```kotlin
plugins {
kotlin("jvm") version "2.0.0"
id("io.gitlab.arturbosch.detekt") version "1.23.6"
}
```
=== Plugins vs Tareas
==== Propósito
*Tareas*:
- Se utilizan para definir una acción específica dentro del build script.
- Las tareas son componentes individuales que realizan trabajos concretos.
*Plugins*:
- Son componentes reutilizables que pueden agregar y configurar múltiples tareas y extender la funcionalidad del build script.
- Los plugins encapsulan lógica y configuración que puede aplicarse a uno o más proyectos.
==== Alcance
*Tareas*:
- Tienen un alcance limitado al build script o proyecto en el que se definen.
- Las tareas pueden ser específicas a una parte del proceso de construcción.
*Plugins*:
- Tienen un alcance más amplio, ya que pueden aplicarse a múltiples proyectos y pueden incluir lógica para configurar y extender esos proyectos de manera más compleja.
Aquí tienes la versión mejorada y desarrollada usando la sintaxis de Typst:
=== Plugins personalizados
Los plugins personalizados se crean para extender Gradle con funcionalidades específicas a las necesidades de un proyecto o equipo. Estos plugins permiten:
- Automatizar tareas repetitivas.
- Centralizar configuraciones comunes.
- Modularizar scripts de construcción para mejorar la mantenibilidad.
Se pueden crear como clases dentro del proyecto o como proyectos independientes (no haremos esto último).
== Ejemplo de Plugin Personalizado
```kotlin
// build.gradle.kts
class SamplePlugin : Plugin<Project> {
override fun apply(target: Project) {
target.tasks.register("pluginTask") {
doLast {
println("A plugin task was called")
}
}
}
}
apply<SamplePlugin>()
```
En este ejemplo, se define un plugin personalizado `SamplePlugin` que registra una tarea llamada `pluginTask` que imprime un mensaje cuando se ejecuta.
== Ejecución del Plugin
```powershell
# Windows
.\gradlew.bat pluginTask
```
```bash
# Unix
./gradlew pluginTask
```
Para ejecutar la tarea `pluginTask` definida en el plugin personalizado, utiliza el comando `gradlew` seguido del nombre de la tarea correspondiente. En Windows, usa `.\gradlew.bat`, y en Unix, usa `./gradlew`.
== Beneficios de los Plugins Personalizados
- *Automatización*:
- Los plugins automatizan tareas repetitivas, reduciendo errores manuales y aumentando la eficiencia.
- *Centralización*:
- Centralizan configuraciones comunes, facilitando la gestión y actualización de las mismas.
- *Modularización*:
- Modularizan scripts de construcción, mejorando la mantenibilidad y organización del código de construcción.
#line(length: 100%)
*Ejercicio: Reporte de archivos*
Implementa un plugin que se encargue de generar un reporte con la lista de todos los archivos `.kt` y `.kts` mediante una tarea. Basta con que imprima en pantalla los nombres de todos los archivos. Puedes obtener la lista de archivos haciendo:
```kotlin
val kotlinFiles = project.fileTree(".").matching {
include("**/*.kt", "**/*.kts")
}.files
```
#line(length: 100%) |
|
https://github.com/ut-khanlab/master_thesis_template_for_typst | https://raw.githubusercontent.com/ut-khanlab/master_thesis_template_for_typst/main/README.md | markdown | # 修論用のTypstのテンプレート
## vscodeでの使用
- 拡張機能Typst LSP, Typst Previewなどをインストール

- main.typ上でプレビュー表示
右上にあるこんな感じ
のアイコンをクリック. プレビューと同時にpdfが生成される
## 使い方
- [公式マニュアル](https://typst.app/docs/)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/013%20-%20Magic%202015/008_Dreams%20of%20the%20Damned.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Dreams of the Damned",
set_name: "Magic 2015",
story_date: datetime(day: 06, month: 08, year: 2014),
author: "<NAME>",
doc
)
#emph[The demon Ob Nixilis is shrouded in mystery. We do not know his origins—where he comes from, or even whether he was always a demon. We do know this: He was once a Planeswalker, until he was stripped of his spark and trapped on the wild-mana plane of Zendikar thousands of years ago. Since then, he has slowly enacted a plan to regain his power and escape.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Demons don’t sleep.
I remember sleep, of course. And I remember how it felt at first, my little consolation prize, that I no longer needed to sacrifice a third of my life to my pathetic mortal limitations. This form feels little pain. It does not tire. But that just gave me more time alone with my rage. I was a conqueror. I #emph[am] a conqueror. Yet I had suffered two defeats in succession. The first robbed me of my body. The second of my spark.
In my youth, I thought myself invincible. I thought I had #emph[proven] myself invincible. Conquering your first world is the hardest, after all. My power grew as I moved from world to world, taking anything that would make the next taking easier. When I heard of the Veil, it seemed too great a prize to refuse. I was a fool. Such a weapon can only destroy the one who wields it.
#figure(image("008_Dreams of the Damned/02.jpg", width: 100%), caption: [], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Deep beneath the surface, the demon worked in silence. The cavern was illuminated only by the faint glow of runic script, etched into the dozens of hedrons that lined the walls. He rotated a hedron a few degrees and spoke a brief incantation. The runes flared, orange and brilliant, but the light faded quickly. He rotated a second hedron, repeated the spell, and watched as the runes flared again. The light lasted slightly longer this time, an almost imperceptible increase in duration. The demon scratched notes into the stone floor with an obsidian claw and moved on to a third hedron.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
To know the freedom of the Multiverse, and to have it stripped away—it is a tomb. To know that there are endless worlds to bring beneath my heel, to sip from fonts of power unimaginable…and then it’s gone. All of it gone. And I am stuck on this disgusting little world, lolling atop this colony of scurrying insects, not even fit to be ruled.
When the fullest depth of that fact sunk in, that was the first time I wished for sleep. I wished to tire, to rest, to let the torment end, if just for a few fitful hours. That can never happen.
#figure(image("008_Dreams of the Damned/04.jpg", width: 100%), caption: [], supplement: none, numbering: none)
So what to do to pass the time? The people of this world offer little amusement. The humans of this place are cowards and vagabonds. I’ve hunted them, toyed with them. So dull. The elves are primitive, but at least they’ll stand and fight. Their bones snap like the game birds I used to hunt, so many centuries and planes ago. And there’re only so many goblins you can crush before the act loses its charm. Well, most of its charm. They do make a very funny noise. Then there’s the kor. They avoid me. I avoid them. Because in each of their smug, chalky faces, I see #emph[her] .
Zendikar’s self-appointed protector. #emph[Nahiri] .
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Deep beneath the surface, a power stirred. Lines of magic buried beneath countless tons of rock and dirt slowly came alive, and a passage opened. A pale green light escaped from the depths, and the demon curled his wings tight to his body so as to squeeze into the narrow path.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Could there be a more miserable place in all the Eternities? I was drawn to it like so many others. The mana here is rich and powerful. This place is a trap. I thought that with the power to be gained here, I could purge my curse, burn out this infection and restore my form. I never got the chance to find out. I had barely finished getting my bearings when she attacked.
She never showed a scrap of emotion as she did it. Maybe the slightest hint of #emph[pity] . Her binding magic was like nothing I had ever encountered. It was never even a fight, and I couldn’t even scream as she bound the hedron into me.
In that moment, everything ceased.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[The walls of that passage lurched, and crushed stone rained down on the demon’s back. The sides of the passage suddenly crushed together. The depths of Zendikar had detected an intruder, and the stone itself sought to purge him. He bought himself a moment by bracing himself between the walls, and he muttered a spell. The vitality of the stone was drained away, the animating force snuffed out, and the rock crumbled in a perfect sphere around the demon’s crouching form. Through tiny cracks, the green glow beckoned him on. He began to dig.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
My curse was stopped. The call of that faraway place just vanished. But all my power vanished with it. When I could finally rise from the ground, the bones in my shoulders crumbled. My wings were useless—they fell off a few days later. The thing she put inside me made me small. Weak. That is not something I can ever forgive. And for that, one day, I will have my revenge.
#figure(image("008_Dreams of the Damned/06.jpg", width: 100%), caption: [], supplement: none, numbering: none)
That was #emph[centuries] ago. I have never seen her again. But I see her face in my mind as if it were yesterday.
Some of the vampires here live that long, but they have the good sense to either go mad or forget. Did she know that by doing this to me, she would preserve my mind? Over time, it became clear to me that the hedron inside me was an object of great power.
Power. The universal language.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[The demon had clawed at the stone for weeks. He spent days slowly tearing through much denser strata. The air in the tiny pocket of stone was thin, replenished only by a small runed sphere he had taken from a merfolk trader. Twice, he had stopped, in order to let his claws regrow. The closer he came to the source of the glow, the faster he healed.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
I studied the hedrons for centuries. I know their magic better than anyone save the one who made them. And when a Planeswalker would come to this place, I would make a point of making introductions. Visitors to a strange new place needs a guide; they need information. I was happy to help. There have been dozens over the countless years. I let them know about my condition. I let the information filter out past the boundaries of this cesspool. And sure enough, some arrogant child finally took my lure.
One of the most important lessons a conqueror needs to learn is that when others believe themselves to be smarter than you, you just let them keep on believing that. Right up until they stop believing anything at all. After all this time waiting, some proud Planeswalker whelp came to find me; to strike me down and extract the hedron. Hundreds of years of planning to make this day come about, and all I could focus on was putting up just enough of a fight so as to not draw suspicion. I never doubted that this day would come.
It was all I could do, lying there in the swamp, not to laugh.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[Deep beneath the surface, the demon reached gently into the tiny sphere of life. He removed a small handful of soil and a tiny flower, glowing green and gold, in his palm. It radiated power, warmth, and health. The ancient passages snapped open, and he cradled it gingerly as he walked back to the surface, his laughter echoing off the walls.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Eldrazi and their spawn rampage on. One can’t help but admire the efficiency with which they exterminate and corrupt. From time to time, I muse on what I could accomplish with an army like that. No matter. Some misguided souls will come to fight the Eldrazi. They cannot help it, heroes are like ants swarming over a discarded sweet. When they arrive, they will need to know what I know. The hedrons were created for this—a weapon like no other, and I may be the only one alive who knows how they work.
But I know what else they can be used for as well.
#figure(image("008_Dreams of the Damned/08.jpg", width: 100%), caption: [], supplement: none, numbering: none)
The power is returning to me. I felt this world shudder when Bala Ged was destroyed. In that moment, I could smell the Multiverse again. My spark is within reach. I know what I must do. And that the only cost to regaining my spark will be the complete obliteration of the world I hate most among them all?
Demons may not sleep.
But we dream.
|
|
https://github.com/fabriceHategekimana/master | https://raw.githubusercontent.com/fabriceHategekimana/master/main/6_Conclusion/Projet_futures.typ | typst | == Projets futures
Il serait intéressant d'ajouter la notion de records dans et de polymorphisme de ligne dans l'usage des dataframes. Ceci augmenterai la flexibilité tout en assurant la constructions sécurisée de module ou librairies. Il serait aussi intéressant de discuter de la meilleurs manière d'implémenter la programmation orienté objet avec notre langage et apporter une notion de mutabilité. Pour finir, il serait intéressant de developper un langage complet qui puisse transpiler dans du code R et/ou créer des binaires.
Nous avons élaboré un modèle de langage capable de manipuler des scalaires, des matrices et des vecteurs, ainsi qu'un module pour les réseaux de neurones. Nos résultats démontrent qu'il est possible de garantir un niveau de sécurité satisfaisant à l'aide de systèmes de types, malgré des défis rencontrés dans la représentation exhaustive des données sans rendre l'algorithme de vérification de type indécidable dans une certaine mesure. La plus part des notions et pratiques faite dans le domaines des sciences des données ont pu être importer dans un context statiquement typé et fonctionnelle ce qui est un encouragement pour le developpement de langages futures basés sur la programmation fonctionnelle.
|
|
https://github.com/yonatanmgr/university-notes | https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/globals/template.typ | typst | #import "functions.typ": *
#let project(title: "", authors: (), date: none, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: "1", number-align: end)
set text(font: "", lang: "he")
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, strong(author))),
),
)
// Main body.
set par(justify: true)
// Headings Numbering //
//
set heading(numbering: (..nums) => {
let nums = nums.pos()
if nums.len() < 4 {
numbering("1.1", ..nums)
}
})
show heading: it => block({
// sans font for headings
if it.numbering != none {
numbering(it.numbering, ..counter(heading).at(it.location()))
// add the trailing dot here
if it.level < 4 { [. ] }
}
it.body
})
// level 1 headings start new pages and have some vertical spacing
show heading.where(level: 1): it => {
it
v(0.3cm)
}
//
// Heading Numbering Ends Here
body
} |
|
https://github.com/npikall/vienna-tech | https://raw.githubusercontent.com/npikall/vienna-tech/main/src/lib.typ | typst | The Unlicense | // Thesis Template for Civil- und Environmentalengineers at TU Wien
// Sizes used across the template
#let script-size = 7pt
#let footnote-size = 8pt
#let small-size = 10pt
#let normal-size =11pt
#let large-size = 20.74pt
// Set Fonts
#let main-font = ("CMU Serif","New Computer Modern")
#let title-font = ("CMU Sans Serif", "PT Sans", "DejaVu Sans")
#let raw-font = ("DejaVu Sans Mono")
// Workaround for the lack of `std` scope
#let std-bibliography = bibliography
// This function gets your whole document as its `body` and formats
// it according to the TU Wien guidelines for thesises
// (Diplomarbeiten, Bachelorarbeiten, Masterarbeiten)
#let tuw-thesis(
// The Thesis Title
title: [],
// The type of thesis
thesis-type: none,
// An array of authors. For each author, you can specify a name,
// department, organization, location and email. Everything but the name is optional.
authors: (),
//Your thesis abstract. Can be omitted if you dont have one.
abstract: none,
// The thesis papersize. Default is A4. Affects margins.
papersize: "a4",
// The result of a call to the `bibliography` function or none
bibliography: none,
// The language of the document. Default is "de".
lang: "de",
//The appendix
appendix: none,
// The TOC
toc: true,
// The document's body
body
) = {
// Set language
set text(lang: lang)
// Formats the authors names in a list with commas and "and" at the end
let names = authors.map(author => author.name)
let author-string = if authors.len() == 2 {
names.join(" and ")
} else {
names.join(", ", last: " and ")
}
// Set document metadata
set document(title: title, author: names)
// Set the body's font
set text(size: normal-size, font: main-font)
// Configure the page
set page(
paper: papersize,
// The margins depend on the papersize.
margin: (
left: 2.5cm,
right: 2.5cm,
top: 2.5cm,
bottom: 2.5cm
),
// The page header should show the page number and the title, except for the first page
// The page number is on the left for even pages and on the right for odd pages
header-ascent: 14pt,
header: locate(loc => {
let i = counter(page).at(loc).first()
if i == 1 { return }
set text(size: normal-size)
if calc.even(i) {
align(center,[#i #h(1fr) #emph(title)])
} else {
align(center + bottom,[#emph(title) #h(1fr) #i])}
v(5pt, weak: true)
line(length: 100%, stroke: 0.7pt)
}),
)
// Configure headings
set heading(numbering: "1.1 ")
show heading: it => [
#set text(font: title-font)
#block(it)
#v(0.2em)
]
// Configure lists and links
set list(indent: 24pt, body-indent: 5pt)
set enum(indent: 24pt, body-indent: 5pt)
show link: set text(font: raw-font, size: small-size)
// Configure equations
show math.equation: set block(below:8pt, above: 9pt)
show math.equation: set text(weight: 400)
set math.equation(numbering: "(1)")
// Configure citations and bibliography style
set std-bibliography(style: "ieee", title: [Literatur])
// Referencing Figures
show figure.where(kind: table): set figure(supplement:[Tab.], numbering: "1") if lang == "de"
show figure.where(kind: image): set figure(supplement:[Abb.], numbering: "1",) if lang == "de"
// Configure figures
show figure.where(kind: table): it => {
show: pad.with(x: 23pt)
set align(center)
v(12.5pt, weak: true)
// Display the figure's caption.
if it.has("caption") {
// Gap defaults to 17pt. MIGHT NEED TO CHANGE THE GAPS
v(if it.has("gap") { it.gap } else { 17pt }, weak: true)
strong(it.supplement)
if it.numbering != none {
[ ]
strong(it.counter.display(it.numbering))
}
[*: *]
it.caption.body
// Display the figure's body.
it.body
}
v(15pt, weak: true)
}
show figure.where(kind: image): it => {
show: pad.with(x: 23pt)
set align(center)
v(12.5pt, weak: true)
// Display the figure's body.
it.body
// Display the figure's caption.
if it.has("caption") {
// Gap defaults to 17pt. MIGHT NEED TO CHANGE THE GAPS
v(if it.has("gap") { it.gap } else { 17pt }, weak: true)
strong(it.supplement)
if it.numbering != none {
[ ]
strong(it.counter.display(it.numbering))
}
[*: *]
it.caption.body
}
v(15pt, weak: true)
}
// Get first authors informations
let email = authors.at(0).email
let matrnr = authors.at(0).matrnr
let date = authors.at(0).date
// Display the title and authors.
v(50pt, weak: false)
align(center, {
text(font: title-font, size: large-size, weight: 500, thesis-type)
v(25pt, weak: true)
text(font: title-font, size: large-size, weight: 700, title)
v(25pt, weak: true)
text(font: title-font, size: normal-size, author-string)
v(15pt, weak: true)
if lang == "de" {
// German
text(font: title-font, size: small-size,
[#email\
Matr.Nr.: #matrnr \
Datum: #date])
} else {
// English
text(font: title-font, size: small-size,
[#email\
Matr.Nr.: #matrnr \
Date: #date])
}
})
// Configure paragraph properties.
set par(first-line-indent: 1.8em, justify: true, leading: 0.55em)
show par: set block(spacing: 0.65em) //above: 1.4em, below: 1em,
// Configure raw text
show raw: set text(font: raw-font, size: small-size)
// Set Table style
set table(
stroke: none,
gutter: auto,
fill: none,
inset: (right: 1.5em),
)
// Display the abstract
if abstract != none and lang != "de"{
// English abstract
v(50pt, weak: true)
set text(small-size)
show: pad.with(x: 1cm)
align(center,text(font:title-font, strong[Abstract]))
v(6pt, weak: true)
abstract
} else if abstract != none and lang == "de"{
// German abstract
v(50pt, weak: true)
set text(small-size)
show: pad.with(x: 1cm)
align(center,text(font:title-font, strong[Kurzfassung]))
v(6pt, weak: true)
abstract
} else {
// No abstract
v(50pt, weak: true)
}
// Table of Contents Style
show outline.entry.where(
level: 1,
): it => {
v(15pt, weak: true)
text(font:title-font, size:11pt ,[
#strong(it.body)
#box(width: 1fr, repeat[])
#strong(it.page)
])}
show outline.entry.where(
level: 2,
): it => {
it.body
box(width: 1fr, repeat[.])
it.page}
show outline.entry.where(
level: 3,
): it => {
it.body
box(width: 1fr, repeat[.])
it.page}
// Display the table of contents.
if toc == true {
if lang == "de"{
outline(title: [Inhaltsverzeichnis], indent: auto)
} else {
outline(title: [Table of Contents], indent: auto)
}
}
// Display the article's contents.
v(29pt, weak: true)
body
// Display the bibliography, if any is given.
if bibliography != none {
pagebreak()
show std-bibliography: set text(normal-size)
show std-bibliography: pad.with(x: 0.5pt)
bibliography
}
// Appendix
if appendix != none {
set heading(numbering: none)
[= Anhang]
set outline(depth: 2)
set heading(numbering: (..nums) => {
nums = nums.pos()
if nums.len() == 1 {
return "Anhang " + numbering("A.", ..nums)
} else if nums.len() == 2 {
return numbering("A.1.", ..nums)
} else {
return numbering("A.1.", ..nums)
}
})
show heading.where(level: 3): set heading(numbering: "A.1", outlined: false)
show heading.where(level: 2): set heading(numbering: "A.1", outlined: false)
counter(heading).update(0)
appendix
}
}
#let codecell(
doc,
// Vertical shift (space before cell)
vertical:1em
) = {
if vertical != none {
v(vertical)
}
figure(
box(
align(left,doc),
stroke: 0.7pt ,
fill: rgb("#eee"),
outset: 5pt,
radius: 7pt,
width: 75%))
}
// Fancy Representation for LaTeX and Typst
#let fancy-typst = {
text(font: "Linux Libertine", weight: "semibold", fill: eastern)[typst]
}
#let fancy-latex = {
set text(font: "New Computer Modern")
box(width: 2.55em, {
[L]
place(top, dx: 0.3em, text(size: 0.7em)[A])
place(top, dx: 0.7em)[T]
place(top, dx: 1.26em, dy: 0.22em)[E]
place(top, dx: 1.8em)[X]
})
} |
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/node-extrude/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge
#diagram(
node-outset: 4pt,
spacing: (15mm, 8mm),
node-stroke: black + 0.5pt,
node((0, 0), $s_1$, ),
node((1, 0), $s_2$, extrude: (-1.5, 1.5), fill: blue.lighten(70%)),
edge((0, 0), (1, 0), "->", label: $a$, bend: 20deg),
edge((0, 0), (0, 0), "->", label: $b$, bend: 120deg),
edge((1, 0), (0, 0), "->", label: $b$, bend: 20deg),
edge((1, 0), (1, 0), "->", label: $a$, bend: 120deg),
edge((1,0), (2,0), "->>"),
node((2,0), $s_3$, extrude: (+1, -1), stroke: 1pt, fill: red.lighten(70%)),
)
Extrusion by multiples of stroke thickness:
#diagram(
node((0,0), `outer`, stroke: 1pt, extrude: (-1, +1), fill: green),
node((1,0), `inner`, stroke: 1pt, extrude: (+1, -1), fill: green),
node((2,0), `middle`, stroke: 1pt, extrude: (0, +2, -2), fill: green),
)
Extrusion by absolute lengths:
#diagram(
node((0,0), `outer`, stroke: 1pt, extrude: (-1mm, 0pt), fill: green),
node((1,0), `inner`, stroke: 1pt, extrude: (0, +.5em, -2pt), fill: green),
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/048%20-%20Dominaria%20United/007_Death%20and%20Salvation.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Death and Salvation",
set_name: "Dominaria United",
story_date: datetime(day: 16, month: 08, year: 2022),
author: "<NAME>",
doc
)
Eventually, all mortal beings must face their end. For humans, death is a grim cloud on the horizon. For elves, death is a long, distant appointment. For goblins, death is just the cost of admission. Multiple societies have independently developed idioms to this effect. Citizens of old Benalia once said that something arrived "like death to a goblin" as a way of describing a sudden, inevitable consequence of poor choices. Dwarven comedies often marked the end of the second act with the sudden death of a goblin supporting character.
In contrast, there is a single goblin idiom that pertains to death. Spoken in the wake of a loss, its many interpretations roughly translate to, "Not me. Not today."
It wasn't that goblins wanted to die; it was just that all the things they #emph[did] want involved a much higher than usual chance of accidental death. Goblins loved nothing more than explosions, open flames, and steep drops. A goblin that lives without risk is seen to have hardly lived at all. Given their lifestyle, Dominaria's goblin population persisted on a wave of sheer luck. And no goblin had been luckier than Squee.
Granted immortality during his time as a cabin boy aboard the skyship #emph[Weatherlight] , Squee had helped some of Dominaria's greatest heroes repel invading Phyrexian forces nearly four hundred years ago. He'd spent the time since becoming simultaneously the oldest and most frequently killed goblin in Dominarian history. Each day he drew breath, he defied the expectations of others, and so it made sense to him that now he found himself a king.
A century ago, during his travels, Squee had come across a nearly disbanded goblin clan living in a deep cave system. They'd fallen on hard times, finding themselves far displaced from their home and under the rule of a vile warlord. Squee hated seeing his fellow goblins forced to live under such a cruel creature, so he challenged the tyrant. He used an old warrior's trick he'd picked up a few decades prior during a brief stint as an Otarian pit fighter: letting himself be repeatedly killed until his opponent fainted from exhaustion. The stress of hitting the same goblin with a hammer for two hours caused the warlord's heart to fail, and Squee was declared the new king. The years since had been, by goblin standards, a time of immeasurable peace and progress.
Squee's throne sat on the mountain's highest platform, overlooking the bustle below. He sat with an old memento in his left hand: an oddly shaped sphere with intricate red patterns painted across its pristine ivory surface. It was his only memento of his time on #emph[Weatherlight] . He'd gone to great lengths (and many deaths) to retrieve it, and sometimes he could swear it still felt warm. He needed its luck today more than ever.
#figure(image("007_Death and Salvation/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
For the first time in over a decade, the clan had gone nearly an entire week without anyone dying, himself included. He'd promised his people that when the milestone was reached, there would be a feast and celebration. A week without death in a goblin warren was cause enough to celebrate, but a week without death for Squee was particularly rare. From the moment his immortality took hold, death had become a near daily part of Squee's life.
He heard a sudden commotion behind him. Bulp reached the top of the stairs and took a moment to apologize. He'd been Squee's ward since his childhood, a bit of a misfit. Bulp's problem was that he was built with the large frame of a warrior but with the curious mind of a scholar. Squee had once seen him getting teased and, seeing a shred of himself in the young goblin, decided to take him under his wing. Bulp was smart, and with the right guidance, he could grow into the smartest goblin since Squee himself.
Bulp vomited onto the floor at the top of the stairs.
"Oh, no, King. Bulp is so sorry. Bulp had huge breakfast today and then Bulp tried to run up all the stairs to give King his important news."
"Bulp, we talked about this."
Bulp nodded as a look of embarrassment formed on his face. The goblin diet consisted mostly of slugs, grubs, and snails. Their stomachs were of course finely tuned to deal with the implications of that, but serious physical activity immediately after a big and actively wriggling meal was never advisable.
"Bulp will only have one bowl next time, Bulp needs to be ready for anything."
"So? Did we make it?"
Bulp suddenly looked nervous.
"What happened, Bulp?
"Nothing! Nobody got squished, that's for sure!" A look of panic crossed Bulp's eyes. Bulp hated letting Squee down.
"Bulp, you gotta tell me if anybody got squished."
Bulp looked at the ground.
"Sorry, King. But Rarp~"
"Show me, Bulp."
The two of them walked downstairs as Bulp explained the situation. Rarp was one of the clan's stone jockeys, working near the mountain's entrance. The idea was that several large boulders would be suspended over the cave's entrance with a rope tied to a nearby stalagmite. In the event of sudden intrusion, the ropes could be cut, and the entrance would be sealed. It was an incredible feat of goblin engineering. That was, until one of the ropes snapped.
Like most goblins at any given moment, Rarp was standing in the wrong place at the wrong time and was crushed. Bulp and Squee approached the accident site just as three other goblins had managed to get the rock lifted off poor Rarp. Squee, not wanting to put anyone in additional danger, tended to the body himself.
"Is Rarp okay, King?" Bulp asked.
A quick assessment of Rarp's condition made it clear that he had been crushed by a boulder. But much to Squee's surprise, Rarp still appeared to be breathing. More confusing yet, an amount of force that should have crushed Rarp to pulp had left him mostly intact. Squee's gaze lingered on Rarp's eyes, flitting back and forth under closed green lids. He cautiously reached toward them. Rarp's eyes shot open, and Squee's stomach dropped as a thick black oil began leaking from them. Unnaturally viscous, the oil poured down Rarp's dented cheeks and began to pool under his head. The injured goblin's eyes focused on Squee, and suddenly Rarp began to scream. Then Squee began to scream. Bulp screamed, also.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Squee and Bulp carried Rarp's sheet-wrapped body back up the stairs to Squee's private chambers. Careful not to touch any of the oil that leaked from the body's head, they dropped Rarp onto the ground to examine him more closely. Each tear in his flesh that the boulder left behind revealed more of the black oil. Beneath a particularly large wound, a glistening black metal cable protruded.
Squee had seen this before a long time ago. Rarp was a sleeper agent, a creature kidnapped by Phyrexians and augmented with metal and magic. This was the first step in what the Phyrexians called compleation. In their compleated state, Phyrexians lost all but a passing resemblance to their former selves and embraced a life of "perfection" through the rejection of their flesh. After he was made immortal, he was left in the hands of Ertai, a compleated former crewmate, whose intellect was only matched by his sociopathy. Ertai had killed Squee repeatedly out of little more than spite and curiosity. While Squee had eventually managed to incinerate him, it had only been due to a happy accident. Freeing as it had been to defeat Ertai, Squee didn't look upon those memories fondly.
"How did Rarp survive, King? Is he like you?"
Squee shook his head, "No, Bulp. Rarp is not like me. Something bad happened to him. Do you remember what I told you about the Phyrexians?"
"Yeah! King fought off an army of monsters! King sent 'em back where they came from!"
Squee had taken some liberties with the tale as payback for his omission from most Dominarian legends.
"Well, it looks like they're going to try and take our world away again."
Squee felt a wave of guilt as he watched fear grow in Bulp's eyes.
"But~ King is gonna kick their butts again, right?"
"I'm gonna try, Bulp. But I need you to help."
The sudden recognition that his king needed him straightened Bulp's posture. He puffed out his chest and did everything he could to seem like he'd never known fear.
"Bulp will do whatever Bulp has gotta do!"
"That's good, because I need you to go to the surface and find help."
"I get to go outside?!" Bulp yelped in surprise. The excitement that filled Bulp's face made Squee nostalgic for a time when he too knew nothing of the world outside his home.
"You do, Bulp, but you gotta move fast. I need you to find a town and tell 'em what happened."
"That Rarp got smushed?"
"No, Bulp. You gotta tell them that the Phyrexians are back."
"Oh, yeah! And what will King do?"
"I needa figure out how many of them got in here and then get rid of them"
"How are you gonna do that?"
Squee looks at the still-moving eyes of Rarp. They fixed on him and twitched wildly, as though wishing that the body that held them could still move. The room's torchlight flickered off the watery pupils, revealing just the slightest iridescent gold highlight behind them.
"I can handle that. But you have to go before any other secret Phyrexians figure out that we know."
Bulp nodded. Squee showed him to the back of his quarters. He pulled aside what appeared to be a shelf to reveal a ladder recessed into the wall. Early in his reign, Squee had enlisted a digging crew to help him make an escape tunnel as a discreet way to occasionally reenter the outside world without alerting his subjects to his absence. All these years later, it was Squee's secret. Now it would be Bulp's as well. He hoped desperately that he was not sending him to his death. Squee hugged him goodbye, and Bulp returned the gesture, lifting his king ever so slightly off the ground.
"Once you've told them, you come straight back. No exploring! If you see something scary, be ready to run!"
Bulp nodded, "Bulp will come back, King. Bulp's gonna make it, just like King."
The ladder's rungs creaked in protest as Bulp clambered upwards. Fighting off concern, Squee moved the shelf back into place and took a torch off the wall. He held it to Rarp's body until it began to burn. It was time to get to work.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
After extinguishing the small fire he'd accidentally started in his quarters, Squee made his way back to his throne room to address his people. He stepped out onto the throne platform and whistled as loud as he could, and the room began to fall silent.
"Goblins, young and old! Your king comes to you with news!" He always tried to take on a kingly tone while addressing his subjects.
"I'm sure some of you heard about Rarp getting smashed up real bad. And it's true, Rarp looks terrible. But Rarp's alive!"
This caused chatter to break out.
"Do not ask any more questions about Rarp! Tonight, we get to celebrate a week of nobody dyin' in our mountain!"
There was an expectant silence.
"And also, I'm gonna make my Hot Slug Porridge!"
The room erupted into cheers.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Squee sent for Spurna, head of the embermages. Their task was to maintain the mana lamps that provided light inside the mountain. He hoped he could convince her to extinguish them during the celebration, leaving only torchlight for the celebrating goblins. Usually, this would be a terrible idea. The anonymity of darkness gave goblins a predilection toward bad behavior somehow more intense than their normal predilection toward bad behavior. However, Squee had a plan. In Squee's quarters, just as he held a torch to Rarp's body, he'd noticed an almost imperceptible outline of gold along the edge of Rarp's pupils. Squee hoped that a sudden influx of torchlight would allow him to see exactly how many gold-eyed sleeper agents he was dealing with. Once he knew the extent of the infiltration, he'd get help from the goblins that he could trust.
Spurna joined Squee in the throne room. From the outset, she was gruff and to the point.
"Spurna hear King want to turn off mana lamps for celebration. Why King want this?"
Squee was prepared for resistance.
"The mana lamps are a real big achievement, but the light is too bright. The goblins wanna have a good time. The goblins wanna dance."
"Goblins can dance in bright room. It better that way. Darkness means funny business."
"Isn't that good though, Spurna?"
"Listen, King. Lamps go out means lamps have to go back on. If too much mana get channeled through the lamps, or it get channeled too quickly, lamps explode, whole mountain explode. It not worth the risk."
Squee made a mental note that, if he got through this, he should revisit the fact that the entire mountain was lit with high-powered explosives.
"I get that! Nobody likes when a mountain explodes! But as king, I have to order you to extinguish the lamps."
Spurna shook her head.
"Well King, remember, you asked for this."
She held out her hands, closed her eyes, and focused. Squee looked toward the main atrium to see if the light had dimmed, but it remained the same. Confused, he turned back to Spurna and felt a hot jolt of pain in his gut. Spurna's arm had twisted and reformed into a heated metallic spike. With an unnatural strength, Spurna hoisted him into the air. He felt his blood pouring out of him as she walked him across the throne room to the overlook. She smiled an unnatural smile as she thrust him forward, sending him plummeting to the mountain's stone floor.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Squee strode through death's halls like he owned the place. Each time he died, it was the same. He found himself in a large, ornate, empty palace with black granite floors so dark that it felt like he was walking through the night sky. The whole place glowed with a soft red light. As he hurried through the halls, he saw the last thing he always saw before resurrecting: a stunning feasting table arranged with all his favorite foods. For the many thousands of times that Squee had been here, he'd never once tasted the bugs. This time was no different. As he approached the table, he felt the gentle caress of spectral fingers around his shoulders before he was harshly yanked back into his physical form. His eyes shot open.
He was covered in his own blood. He saw other goblins beginning to gather for the party. They seemed unbothered by Squee's sudden public death, but he didn't blame them. As an immortal being, Squee died a lot. He occasionally jumped off that platform when he didn't feel like taking the stairs. He'd usually burst on impact, and everyone always got a big kick out of it.
Squee did his best to get their attention, not knowing where Spurna had fled. He cried out, "Help your king! Prepare to fight!" just as Spurna landed next to him with a metallic thud. She thrust her spike through the back of his head.
Squee awoke once again. His vision was blurry, being fed through newly healed eyes to a newly reformed brain. As it came into focus, he saw the entire clan standing in a perfect circle around the two of them, watching silently as Spurna stalked him like prey. Enjoying the audience, she slowly pressed her spiked arm toward his chest, pinning him to the floor. With a sickly, unnatural smile, she snapped her fingers. The mana lamps went out. Only distant torchlight flickered now, and with horror, Squee saw that every set of eyes that surrounded him was ringed with a pale gold. He choked on a scream. Spurna wound up to stab him again when suddenly she was knocked wildly off her feet. She spun and landed on the ground, looking angrily at her assailant: Bulp.
"Bulp!" Squee yelled, never happier to have been disobeyed. Bulp turned and offered a hand to help him off the ground.
"We have to get out of here, Bulp! It's not safe, can't you see they're—"
Squee felt a horrible burning sensation. As he looked at his hand, he saw that his flesh was rotting away. The rot spread from his fingers down to his wrists. He fell back to the ground as his arm tore free from his body. The flesh-eating necrotic spell did its vile work, and he watched in horror as Bulp's body flickered. The glamour that had been concealing his true form faded and standing where Bulp had once been was a tall and unnaturally pale man with pale blonde hair. His eyes wept oil and black cable was intricately woven into the flesh of his face. Each of his arms split at the elbow, giving him two additional three-fingered hands. Ertai's spiked Phyrexian armor gleamed in the torchlight as the rot reached Squee's chest. Squee tried to yell, but instead tasted only the grime of his own decay before once again seeing darkness.
When his body reformed, Ertai was there waiting for him. Squee was surrounded by his own former subjects. They sat completely still in a complacent silence. Ertai paced toward him.
"It's been a long time, Squee."
"I thought I killed you."
Ertai laughed.
"You of all people should know that death can be a temporary state. But it's true, Squee. You got the jump on me and for several hundred years, I went into the dark. That might've been the end of it if Sheoldred hadn't found me."
"She old who?"
Ertai shook his head with a smirk.
"You know, with Dominaria on the verge of compleation, I have a lot more patience for your stupidity. Plus, you're much more eloquent than when we last spoke. You could nearly pass for a child."
The totality of the situation started to dawn on Squee. His clan was gone. His people were now just heavily augmented shells, built to torment him. He couldn't even begin to think of what Ertai had done with Bulp.
"Why do all of this? I don't understand."
Ertai leaned down to meet Squee's eyes with an icy gaze.
"Maybe I just don't like you. Maybe I got jealous watching those #emph[Weatherlight] buffoons fawn over your idiotic antics. Or maybe it's because #emph[you killed me] ."
Ertai's smile returned.
"Or maybe, I came here to make an unkillable goblin beg for death. To teach you of true pain so that when I relieve you of it, you'll greet me with worship."
Ertai reached into his robes. "But as far as the official logs are concerned, I was tasked with retrieving and safely concealing this." Squee patted his robes in disbelief as Ertai pulled out his toy.
"You love this bauble so much, and yet I'd wager you know as little about it as we do. There's startlingly little to be read about the Salvation Sphere. All I've managed to discern is that it's older than the plane itself. But I know two things for sure. First, it was part of the Legacy Weapon, which means it must be dealt with. Second, it seems to always find its way back to you, which means #emph[you] must be dealt with."
Squee sighed.
"You said it yourself, Ertai. You can't kill me."
Ertai playfully tossed the toy from one hand to another. He motioned to the goblin sleeper agents and pointed toward Squee. They started to advance on him.
"Oh, Squee, I don't need to kill you. I just need to remind your flesh of its potential."
Goblins grabbed hold of Squee's arms to restrain him. Their bodies split open and revealed metal and black cable. They began to change in shape, contorting wildly. Several of them connected to each other, their new forms joining together to create a machine unlike anything Squee had ever seen. One's hand split open to reveal a needle. Before Squee could scream, it pierced his flesh, and his limbs grew heavy. One of the goblins had become a table, and Squee was shifted onto it. As he drifted off to sleep, he hoped that they weren't making him into a table, too.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When Squee's eyes opened, he felt more alert than he'd been in years. Fatigue as a concept had been removed from his body and mind. He felt a newfound strength in his muscle tissue. His eyes could see everything in the room clearly, no matter how far away. He'd been placed in a fresh set of his orange king's robes and left on the table. He sat up and removed a needle from each of his arms. As he did, a machine near the table began to emit an uncomfortable sound. No sooner than Squee had registered discomfort, the sound seemed quieter.
Everything was as he remembered it, but all the things that had worried him suddenly seemed small now. He saw his people moving about the mountain, some looking like goblins and others looking like a beautiful symphony of flesh and metal. Ertai appeared in a teleportation circle before him, attending to the sound.
#figure(image("007_Death and Salvation/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"Oh, good. You've awakened. How do you feel?"
"Powerful."
"Perfection has that effect. Your body may feel unfamiliar to you at first. I recommend taking a moment to examine your new functions before we leave for the Mana Rig."
Squee stood and looked at his body, seeing faint white lines along his arms. No sooner than he'd thought about them, his arms opened, revealing machine parts beneath. He closed them again. Everything moved at the speed of his own thoughts. Squee removed his robes with a desire to see what else he was capable of. Ertai seemed concerned.
"Actually, Squee, even in our perfect forms we still elect to wear our clothing—"
"I thought perhaps you had given me armor"
"I had assumed we'd get you some upon our—"
Fully nude, Squee looked at his chest and saw more faint scars. At a thought, a panel opened to reveal the interior of his own chest cavity, including the ever-spinning Salvation Sphere in the place his heart once was. He looked at a bucket in the corner of the room brimming with meat. Presumably, his own. Resting on top of it was his crown.
"You won't be a king in New Phyrexia. In fact, I'd imagine they'll be doing some quite invasive research once I deliver you." Ertai said, visibly pleased with himself, but this smugness no longer offended Squee. They both served Phyrexia. Squee's immortality would be useful to the cause and so learning to understand it made sense.
Ertai continued, averting his eyes from Squee's nude form. "But you have to admit, it feels better on this side, doesn't it?"
Squee once again commanded his arms to open. One contained a hooked blade, and the other contained a small cannon. He stared at it as it charged. Then he looked at the blade and tried to extend it further. Instead, it spun forth as a projectile, sticking into a stone wall. He turned toward Ertai.
"I feel~" Squee opened his other arm, charging his new cannon. He summoned the blade back to him, a magnet in his arm pulling it free from the wall, "~compleat."
The blade flung back at Squee at high speed, easily severing through the exposed rope that blocked its path, the very same rope that steadied the boulders the rock jockeys had resuspended above the mountain's entrance after that morning's accident. Squee found himself standing, as goblins so often were, in the wrong place at the wrong time. The cut line slipped loose, and the boulders dropped in an instant. Squee was crushed mid-word and pulverized against the cavern floor in an explosion of viscera and Phyrexian oil. As the stone smashed through his body, the charged cannon on Squee's arm fired into the air, hitting and overcharging one of the mana lamps lining the cave wall. The explosion was bright as the sun and gave the mountain's denizens no time to react as it cascaded from lamp to lamp, save for Ertai who instinctively shielded himself. The few small cities that had reestablished themselves in Otaria would long wonder what happened in the mountains that night, as to any observer it appeared that at one moment there was a mountain, and at the next, there was a smoldering crater of stone.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Death had never felt like this before. The palace in which Squee had spent so much time was gone, and instead he found himself floating in a sea of white light. Was he dreaming? If he was dead, where was the palace? Where was the feast?
#emph[Squee. It's time we talked. ]
Squee heard the voice all around him. Suddenly, an astral shape floated free from his chest and bobbed just in front of his face, floating in the light. It was his toy, but not as he'd ever seen it before. At first, it seemed to be floating in the light just as he was, but its clean white surface, so similar in shade to the light itself, faded away, leaving only the ornate markings. They glowed, suspended in the air, and expanded to fill the space, leaving Squee overwhelmed by his own lack of comprehension. His toy's markings had always resembled a face, not unlike that of an owl or imp, but now as it sat filling the extradimensional space, it only brought him fear.
#emph[There is no need to panic, old friend. Allow me to put you at ease.]
Suddenly, the floating markings contorted, spinning around Squee until their blurred motion was all he could see. When they dissipated, Squee was once again standing in the palace he remembered. The feast looked delicious as ever, but this time, the table had a guest. In the chair nearest to him sat a young Zhalfirin woman with a single braid in her dark hair who he recognized in an instant as his dear friend and #emph[Weatherlight] captain, Sisay. Excitement overtook Squee, but the closer he looked, the more he grew suspicious. This Sisay lacked something essential. She was missing the wry confidence that made her such a natural leader.
#emph[I've taken on a form that you would find more palatable. You always viewed Sisay as a comforting and authoritative presence.]
Finally, Squee spoke. "So~ you're not her?"
#emph[No, Squee. Sisay has passed. Her soul returned to the aether.]
"So, who are you?"
#emph[I am Salvation. I was once a primal force in a world that came before this one. I was—]
Squee was bored. He'd never been dead for this long. "How did I get here?"
#emph[That is more complicated. Yawgmoth's spell was intended to endlessly rebuild your body with little regard for its effect on your soul. However, long before your immortality, I'd chosen you as a worthy recipient of my boon. I protected you from all that would threaten the purity of your soul. The resulting mixture placed you in a loop. Each time you died, your body would be repaired as Yawgmoth willed. Your soul was trapped in this extradimensional space and returned to your new body before it ever had a chance to move on. Even after—"]
"Sorry, I gotta be more clear when I'm asking big questions. How did I get here specifically?"
Salvation smiled.
#emph[Pure as ever. Phyrexian corruption removed your soul from your body while it still lived, releasing it from the loop.]
"So~ it's over. I finally got killed for real?"
On the far side of the room, a gilded wooden door creaked open, pushed by unseen hands. The space beyond the threshold was too bright to see.
#emph[That depends, Squee. I accept the role I've played in your unexpected fate, and I'd like to offer you one final boon: a choice. At this moment, in the realm of the living, your body has just been destroyed. The spell that reanimates it is reaching out for your soul as it always has. It will fizzle if it does not find you soon. I could place your soul back into the loop. You would awaken once again in a new body. You remain immortal and free of Phyrexian meddling. ]
Another door on the opposite side of the room swung open.
#emph[Or you can walk through this threshold, and your soul will finally be returned to the aether. You'll be reunited with all those you've lost and free to rest. ]
Squee looked at the two doors nervously. He approached the feast and pulled up a chair, reaching across the table for a particularly alluring maggot pastry. He sat back down, took a bite, and smiled. He spoke through his full mouth, "How's about you and me talk about a third door, Sally?"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Bulp had done everything right. He'd used the king's secret passageway and made sure that nobody saw him leave the mountain. He'd traveled quickly and quietly. He found the first human town he could and gave them the news that Phyrexia was back. Sure, they said that everybody's known that for months, but people will say anything to make a goblin sound dumb. The news was delivered so he made his way back.
Bulp had seen the explosion the night before but didn't truly believe it until he got close. #emph[King's gotta be around here somewhere] , he thought to himself.
He came across an odd clearing in the wreckage. It appeared to be the center of the explosion that blew the place sky-high. There was a single, neat little circle without even a pebble's worth of rubble on it. When he got close, he smelled the stench of an unfamiliar magic in the air, so he kept his distance. He got worried for his king. #emph[Sure, King can't die] , Bulp thought, #emph[but if King gets buried real deep, does he just stay under the rocks?]
Before he could start digging, he heard a much welcomed voice from above him.
"Bulp! You're alive!"
Perched a few feet above him on a large bit of broken stone was King Squee.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#emph[What do you have in mind? ] Salvation asked Squee.
Squee took another bite of his maggot turnover.
"I don't wanna sound ungrateful, but before I became immortal, I never died once. Then ever since it happened, I can't seem to stop. I was one of the smartest goblins in the whole world before I got changed. I went on a big adventure and helped save everybody. No matter what anybody says, I was important. But the only part of me that anybody cares about now is the thing I got by accident. Well, I'm nobody's accident. I'm my own accident."
Squee swallowed his bite of pastry.
"I wanna go back, Sally, but I only want one more. I want a chance to last as long as I can, a chance to blow somethin' up, think I'm dead for a minute, realize I'm not, and then cry laughing."
Salvation nodded.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Bulp had never been so happy to see his king.
"King!! King, you're okay!"
"You're okay! I thought they got you!"
"So, everybody else~" Bulp trailed off, unable to articulate the loss.
"I know. But not us! Not today!"
"But what are we gonna do, King? Where are we gonna go?"
"If Phyrexia's back, then it's up to smart goblins like us to kick their butts and settle the score."
Bulp's eyes went wide.
"Do you think we can?"
Squee clapped his hand onto Bulp's shoulder in a gesture that would've seemed fatherly were Bulp not a full head taller than him.
"Between you and me, Bulp? Things always got a way of workin' out for ol' Squee."
|
|
https://github.com/tomeichlersmith/zen-zine | https://raw.githubusercontent.com/tomeichlersmith/zen-zine/main/lib.typ | typst | MIT License | #let zine(
zine_page_margin: 8pt,
draw_border: true,
digital: false,
contents: ()
) = {
if digital {
set page(height: 4.25in, width: 2.75in, margin: zine_page_margin)
for (i, page) in contents.enumerate() {
if i > 0 { pagebreak() }
page
}
} else {
// set printer page size (typst's page) and a zine page size (pages in the zine)
set page("us-letter", margin: zine_page_margin, flipped: true)
let zine_page_height = (8.5in-zine_page_margin)/2 - zine_page_margin;
let zine_page_width = (11in-zine_page_margin)/4 - zine_page_margin;
let contents = (
// reorder the pages so the order in the grid aligns with a zine template
contents.slice(1,5).rev()+contents.slice(5,8)+contents.slice(0,1)
).map(
// wrap the contents in blocks the size of the zine pages so that we can
// maneuver them at will
elem => block(
width: zine_page_width,
height: zine_page_height,
spacing: 0em,
elem
)
).enumerate().map(
// flip if on top row
elem => {
if elem.at(0) < 4 {
rotate(
180deg,
origin: center,
elem.at(1)
)
} else {
elem.at(1)
}
}
)
let zine_grid = grid.with(
columns: 4 * (zine_page_width, ),
rows: zine_page_height,
gutter: zine_page_margin,
)
if draw_border {
zine_grid = zine_grid.with(
stroke: luma(0)
)
}
zine_grid(..contents)
}
}
|
https://github.com/Le-foucheur/Typst-VarTable | https://raw.githubusercontent.com/Le-foucheur/Typst-VarTable/main/examples/bug1.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 5pt)
#import "../tabvar.typ": *
#tabvar(
init: (
variable: $x$,
label: (
([sign], "Sign"),
([var], "Variation"),
),
),
domain: ($3$, $2$, $1$),
content: (
($+$, $-$),
(
(top, $3$),
(bottom, $2$),
(top, $ "tree"(3) $ + "that is a very big number"),
),
),
) |
https://github.com/FelipeCybis/quarto-physmed-template | https://raw.githubusercontent.com/FelipeCybis/quarto-physmed-template/main/physmed-poster-landscape/_extensions/physmed-landscape/typst-show.typ | typst | MIT License | // Typst custom formats typically consist of a 'typst-template.typ' (which is
// the source code for a typst template) and a 'typst-show.typ' which calls the
// template's function (forwarding Pandoc metadata values as required)
//
// This is an example 'typst-show.typ' file (based on the default template
// that ships with Quarto). It calls the typst function named 'article' which
// is defined in the 'typst-template.typ' file.
//
// If you are creating or packaging a custom typst template you will likely
// want to replace this file and 'typst-template.typ' entirely. You can find
// documentation on creating typst templates here and some examples here:
// - https://typst.app/docs/tutorial/making-a-template/
// - https://github.com/typst/templates
#show: doc => poster(
$if(title)$ title: [$title$], $endif$
// TODO: use Quarto's normalized metadata.
$if(poster-authors)$ authors: [$poster-authors$], $endif$
$if(departments)$ departments: [$departments$], $endif$
$if(paper)$ paper: "$paper$", $endif$
$if(flipped)$ flipped: "$flipped$", $endif$
// Poster banner/logos.
$if(poster-banner)$ banner: "$poster-banner$", $endif$
// Footer text.
// For instance, Name of Conference, Date, Location.
// or Course Name, Date, Instructor.
$if(footer-text)$ footer_text: [$footer-text$], $endif$
// Any URL, like a link to the conference website.
$if(footer-url)$ footer_url: [$footer-url$], $endif$
// Emails of the authors.
$if(footer-emails)$ footer_email_ids: [$footer-emails$], $endif$
// Color of the footer.
$if(footer-color)$ footer_color: "$footer-color$", $endif$
// DEFAULTS
// ========
// For 3-column posters, these are generally good defaults.
// Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters.
// For 2-column posters, you may need to tweak these values.
// See ./examples/example_2_column_18_24.typ for an example.
// Font size of the text of the body
$if(body-font-size)$ body_font_size: $body-font-size$, $endif$
// Any keywords or index terms that you want to highlight at the beginning.
$if(keywords)$ keywords: ($for(keywords)$"$it$"$sep$, $endfor$), $endif$
// Number of columns in the poster.
$if(num-columns)$ num_columns: $num-columns$, $endif$
// Column size used as spacing to the left of the title (in in).
$if(left-title-column-size)$ left_title_column_size: $left-title-column-size$, $endif$
// Column size used as spacing to the right of the title (in in).
$if(right-title-column-size)$ right_title_column_size: $right-title-column-size$, $endif$
// Title and authors' column size (in in).
$if(title-column-size)$ title_column_size: $title-column-size$, $endif$
// Title and authors' row size (in in).
$if(title-row-size)$ title_row_size: $title-row-size$, $endif$
// Poster title's font size (in pt).
$if(title-font-size)$ title_font_size: $title-font-size$, $endif$
// Authors' font size (in pt).
$if(authors-font-size)$ authors_font_size: $authors-font-size$, $endif$
// Authors' font size (in pt).
$if(department-font-size)$ department_font_size: $department-font-size$, $endif$
// Footer's URL and email font size (in pt).
$if(footer-url-font-size)$ footer_url_font_size: $footer-url-font-size$, $endif$
// Footer's text font size (in pt).
$if(footer-text-font-size)$ footer_text_font_size: $footer-text-font-size$, $endif$
// Margin top (in in).
$if(margin-top)$ margin_top: $margin-top$, $endif$
// Margin left (in in).
$if(margin-left)$ margin_left: $margin-left$, $endif$
// Margin right (in in).
$if(margin-right)$ margin_right: $margin-right$, $endif$
// Margin bottom (in in).
$if(margin-bottom)$ margin_bottom: $margin-bottom$, $endif$
// Space after header information (in pt).
$if(space-after-header)$ space_after_header: $space-after-header$, $endif$
doc,
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/matrix-alignment-05.typ | typst | Other | // Test #460 equations.
$ mat(&a+b,c;&d, e) $
$ mat(&a+b&,c;&d&, e) $
$ mat(&&&a+b,c;&&&d, e) $
$ mat(.&a+b&.,c;.....&d&....., e) $
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/terms_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test grid like show rule.
#show terms: it => table(
columns: 2,
inset: 3pt,
..it.children.map(v => (emph(v.term), v.description)).flatten(),
)
/ A: One letter
/ BB: Two letters
/ CCC: Three letters
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/019%20-%20Magic%20Origins/004_Gideon’s Origin: Kytheon Iora of Akros.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Gideon’s Origin: Kytheon Iora of Akros",
set_name: "Magic Origins",
story_date: datetime(day: 01, month: 07, year: 2015),
author: "<NAME>",
doc
)
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/01.jpg", width: 100%), caption: [Art by Chase Stone], supplement: none, numbering: none)
At night, the darkness of the prison was complete. It draped itself across the stone walls, and seeped into the prisoners’ ragged clothes, an inky stain that did not wash out completely in what pale daylight managed to penetrate the prison’s interior through the narrow shafts high in the walls. When the wind stopped outside, the still darkness had weight under which many prisoners cracked.
But that’s not what gnawed at Kytheon, a thirteen-year-old thief, spending his first night in the darkness. He was stuck on a particular fact that had risen to the top of a heap of information thrown at him earlier about the prison’s routines, rules, and the general order of things. It was something he had heard from Drasus, a friend of his from the Foreigners’ Quarter, and now a fellow prisoner: "Hixus is the warden, but it’s Ristos who runs this place."
Kytheon must have made a face when presented with this detail. "Try to understand," Drasus had warned, "Ristos is not like the thugs that the Irregulars threw out of the Quarter. He sees himself as a king. He’s a monster. That’s why he’s in here."
"#emph[We’re] in here," Kytheon had countered.
"You’re in here because you make a poor thief, who was caught for stealing rotten vegetables and a handful of coins. I’m in here for brawling. We’re not killers. So just watch out is all I’m saying." Drasus had shrugged as though nothing could be done.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Drasus was three years older than Kytheon, and hot-tempered. He’d been taken to prison more than a season prior, and seeing him was a welcome reunion, though Kytheon hadn’t liked what he had seen in that shrug. He’d tried a different approach.
"You’re one of my Irregulars, Drasus. This Ristos should be the one to watch out for us."
"You say that now, but he’s bigger than the thugs on the outside. I’m telling you, he’s king." At that, Drasus had walked away before Kytheon could argue.
There were always people trying to muscle their way into the Foreigners’ Quarter to set up their networks of thievery, smuggling, and intimidation—brutes like Anthedes of the Bloodied Axe, or connivers like Krevarios the Venomous. Kytheon could recognize a bully—he’d spent most of his life dealing with them in some form—and he couldn’t wait to meet Ristos.
At dawn, the new prisoners were bound together by lengths of iron chain and marched through labyrinthine corridors of rough-hewn stone. Kytheon counted six other prisoners, two of whom looked like they’d been through this before. A guard opened a heavy wooden door and the prisoners were led into a cavernous chamber where scores of native prisoners appeared to be laboring.
The air in the chamber was stale, like Kytheon’s cell, but unlike his cell, it was tinged with the scent of mildew. In the center of the chamber, a round shaft, twenty feet across, was cut into the floor. A matching shaft disappeared into the ceiling, and between them, a dozen cables carried huge barrels in both directions.
"Welcome to the Waterfall of Akros," bellowed a crooked-backed guard, "where the water flows up." He laughed at his own joke, one that Kytheon did not understand but had a feeling he soon would.
The other guards corralled Kytheon and the new prisoners to an enormous six-spoked crank that was being driven by prisoners who stood six abreast at each spoke, turning it in great circles around a massive oak axle.
"First group! Take a rest!" a guard said. The prisoners pushing one of the crank’s spokes peeled off, massaging their aching muscles or wiping the sweat that burned their eyes.
Kytheon felt a shove at his back, and he took his position at the crank beside the other new prisoners. The wooden beam felt smooth beneath his hands, where countless hands had pushed against the constant resistance of endless barrels of water being hoisted from the river in the valley below to the polis of Akros perched on the cliff above. This was what prison meant. Labor and captivity. He was to be a beast of burden. It was not unlike Akroan hoplite training, Kytheon reflected, smiling to himself. #emph[Making the body like marble,] they called it—a daily regimen of running and hauling heavy objects. But that was when he was to be a soldier. When he was a kid. That was before he was expelled from the army, before he was an Irregular, before he was a thief, and before he was a prisoner.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
His shoulders and calves burned as he worked the crank. He tried to keep the pain at bay by focusing on a single barrel, following its journey from when it appeared out of the floor until it disappeared into the ceiling. He wasn’t counting them, just watching them, willing himself to follow just one more, and one more after that. There was always another one.
In the gap between two ascending barrels, Kytheon observed a handful of prisoners repairing damaged barrels. They were at work, hammering new iron rings into place with wooden mallets. These prisoners looked healthier, filled out—well fed.
And then finally, "First group! Water!"
Kytheon didn’t remember hearing the other groups get called, but who was he to argue. Legs wobbling without the wooden beam for support, he made his way to a corner of the chamber where bits of masonry were strewn about as makeshift chairs.
Old and broken prisoners filled cracked clay cups with water from a barrel, offering them to the prisoners from the first group along with a heel of stale bread. Meager food was nothing new to Kytheon. The Foreigners’ Quarter of Akros was not known for its opulence or abundance, and there were many days that he, Drasus, Little Olexo, Epikos, and Zenon had to content themselves with such meals.
When he bit into the hard bread, the texture of granulated crumbs was familiar. He found a chunk of masonry and slumped against it. Its cold surface was a welcome relief that he meant to compliment with a mouthful of water. He lifted his cup to his lips, and tipped the water into his mouth, letting the cold liquid slosh around.
"Tribute!" said a rasping voice that interrupted Kytheon’s moment of contentment. The voice belonged to a stout man, barely taller than Kytheon was, who walked among the gathered prisoners of the first group.
Kytheon watched as all of the prisoners the man walked by dropped half their bread, without protest, into a sack he held out to them. Kytheon swallowed the water he had been savoring. #emph[Ristos?]
The man came closer. He was bare from the waist up, his torso covered in thick, dark hair, save for the scattered raw streaks of puffed scars.
"Tribute!" the man said again, stopping in front of Kytheon.
"Yeah, okay. Whatcha got?"
The man made a noise that was somewhere between grunt and chuckle. "My knee against your throat if you carry on like that, boy. The king demands tribute."
"King? You Ristos?"
The man didn’t answer. Kytheon looked past him to where the barrels were being repaired. A large man, broad at the shoulders, met the young prisoner’s stare with his own. He had a face wreathed in a mane of coal-grey hair.
"Nah, you couldn’t be Ristos," said Kytheon, returning his attention to the man in front of him. "I was told I’d be scared of Ristos."
"You should be," the thug said through gritted teeth. He tossed his sack of extorted bread aside, but before it hit the ground, Kytheon shoved himself off the chunk of stone and drove his foot into the other man’s shin.
There was a roar of agony as the thug reeled back. In an instant, Kytheon was on his feet, launching a flurry of jabs at the other man’s face. He danced out of range of the counterattack, forcing the thug to overextend and expose himself to another barrage of fists.
Kytheon smiled. A surge of energy welled in him, and he forgot about his sore muscles and grumbling belly. This was his element—the fight.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Ristos’s thug was a seasoned brawler, Kytheon could tell from his experience scrapping with Drasus. This guy was sack of meat who could take a hit, but he was predictable and, like all of the thugs Kytheon had fought in the alleyways of Akros, this one was a talker.
"I’m going to drink wine outta your skull!" he threatened.
Another haymaker, followed by another of Kytheon’s dodges, and another sequence of his punches that connected with ribs and jaw.
#emph[Keep babbling] , Kytheon thought as he circled around his opponent. For Kytheon, fighting was reflexive—intuitive, instinctive. As a child, he discovered that it was also the source of his magic.
The other prisoners watched them fight, but made no moves to intervene. Kytheon stole a moment to scan the gathered prisoners for Ristos, who he saw had moved in closer and was still watching.
Then all at once, the edge of Kytheon’s vision exploded.
He’d underestimated the thug’s speed. He found himself on the ground, looking up at the other man who was already on top of him, raining down punches. The first few connected. One caught Kytheon on the nose with a sickening crunch and caused another explosion in his vision.
He had to regroup. He had to focus.
The man’s fist rose, but before it fell again, the surface of Kytheon’s skin flared up with countless bands of light that rippled with energy.
The fist came down. When it struck Kytheon below the eye, he felt no pain. Instead he was filled with a burst of energy that he threw into a punch of his own, connecting with the man’s jaw, which cracked under the force. The action was punctuated by the man’s yelp as he tumbled off of Kytheon.
The boy rose to his feet, bands of light still rippling across his body.
The chamber was silent except for the moaning of the thug who lay in a heap cradling his splintered jaw.
Blood ran from Kytheon’s nose, down his chin, and onto his rough-spun garb. He spat a glob of red onto the stone, reached into the abandoned sack of bread, and withdrew a piece. All eyes were on him, but Kytheon just stared at Ristos and proceeded to tear off a chunk of bread with his teeth.
Ristos made a motion, and half a dozen prisoners emerged from the rest, surrounding Kytheon.
The boy wiped the blood from his mouth with the back of his hand, smearing it across his cheek. He looked each of Ristos’s thugs in the eye, turned back to their boss, and grinned.
It wasn’t long before guards pushed their way through the throngs of prisoners, but Kytheon didn’t need long. By the time the guards arrived, they found Kytheon, bloody-faced and bloody-fisted, pummeling the last of Ristos’s men.
When the thirteen-year-old kid saw the guards descending on him, he slumped to the floor, spent, exhausted, and utterly satisfied.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kytheon stood before the warden, bound in iron at the wrists, a pleased smile stretched across his face. Hixus waved his hand, and the two guards who had escorted the young prisoner turned and left Kytheon and the warden alone.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Hixus leaned casually against a wooden table that was littered with various piles of documents. The warden was broad at the shoulders and he wore a breastplate with the ease of a seasoned soldier. He stared at Kytheon, seemingly studying his face. After a moment, he ran his fingers through his thick, grey beard and spoke, "You’ve been here for less than two days." He took a deep breath. "Two days of a ten-year sentence. A brawl in the waterworks, seven prisoners in the infirmary, and a riot…all on your account."
To Kytheon’s ears, it sounded like a list of accomplishments.
"Ah yes," Hixus added, "and I am told that you attempted escape as you were being transported here yesterday."
"Can you blame me?"
"Is there someone else?"
Kytheon didn’t answer.
"For my own curiosity," the warden went on, "had your escape worked, were you not afraid of what would happen to you once you were apprehended again?"
"I can take it. Besides, you haven’t spent much time in the Foreigners’ Quarter have you? If I made there, the Irregulars would protect me. You’d never get me again."
It was the warden’s turn to smile. "Ah, the Irregulars. Protectors of the Quarter. #emph[Kytheon’s] Irregulars."
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/06.jpg", width: 100%), caption: [Art by <NAME>s], supplement: none, numbering: none)
"Yep."
"Quite a loyal following. And many of them end up spending time here. Your friend, Drasus, is a current representative of the Irregulars in here, isn’t he? Now you as well. You know, there are quite a few prisoners in here who have words and more for you and your Irregulars, yet it seems you insist on making more enemies."
"Ristos?" Kytheon couldn’t help but laugh. "My mother called people like him weak because their strength comes from how others see them. 'Strength comes from action,' she said. Ristos is weak. I saw it right away. Now everyone else here knows it too."
The Warden chuckled. "I see. In that case, it shouldn’t surprise you that he is with his men in the infirmary."
"I never touched him."
"It’s like you said, though. His strength evaporated the moment a kid took down his men in front of the other prisoners and he fled for safety. When you were locked away last night, a riot erupted—started by Drasus, mind you. They’d had enough of Ristos and let him know it. Not everyone has your gift to shrug off attacks."
"He had it coming."
"Perhaps. He is a brute, that much is true. But some things have value beyond their surface appearance. Bad as he was, he helped maintain order." The warden threw his hands up. "Now what do I do?"
"I can’t tell you how to do your job, Warden."
"No you can’t. But maybe you can help me. Are you my next Ristos?"
"I’m better than Ristos."
"Are you? Prove it."
"Prove it? He’s in the infirmary, and I barely have a scratch."
"And what now? Will you take his place? Replacing him doesn’t make you better. It makes you the same."
"We’ll never know. I don’t plan on staying."
With a movement so quick that it startled Kytheon, Hixus took the heavy ring of keys that hung from his belt, and dropped them on the table. Iron clattered on wood, and before the sound faded, Hixus had a dagger in his hand. Kytheon took a step back, raised his fists defensively, and light erupted over his body in frenetic ripples.
"Do not feel threatened," said Hixus. "By all accounts, trying to harm you physically would be fruitless." He flipped the dagger deftly in his hand so that he gripped the blade, and he offered it to Kytheon. "Take it."
Kytheon hesitated only for a moment. His fingers closed around the hilt.
"I offer you your freedom," the warden said. "All you have to do is take the keys, and escape is yours."
"You’d just let me out of here?"
"No. You’ll have to kill me for the keys. And if the rumors of your fighting skill are true, I don’t stand much of a chance."
Pride swelled in Kytheon. He always liked to fight. He was good at it.
Kytheon pointed the dagger at the warden for a long moment. Neither averted his gaze from the other.
"I’m not going to kill you," Kytheon finally said. He dropped his arm to his side, letting the dagger clatter to the floor.
"Because you’re not a murderer. You’re not a Ristos."
"Sorry to disappoint you."
"On the contrary, I am encouraged by this outcome. It is what I was hoping for. It is what I believed to be true. You are here, a thief, condemned for stealing. But what you stole was food, to help feed your friends and their families. You do what you think is right."
Kytheon stared down at the chain that hung between his ankles. "What do you want from me?"
"From most of my prisoners, I want serenity and obedience. From you? I want you to accept my offer. I want to train you, Kytheon."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Though Kytheon hadn’t agreed to the training, his protest has been largely ignored. He was roused before the sun the next morning and dragged out to the prison’s modest gymnasium. It was a round patch of packed earth surrounded by high walls. Hixus was standing in the center of the arena-like circle. He tossed his ring of keys to the dirt.
"I’m still not going to kill you," Kytheon said.
"I hope not," said the warden. "Just come get them." The corner of his mouth curled into a smirk. "Succeed, and they’re yours."
Kytheon charged.
Hours later, Kytheon lamented, he had gained no ground. Each of his charges were abbreviated by chains of brilliant white energy that erupted from the ground to shackle his limbs, or by lashes of luminescent magic that pushed his limbs just enough to interrupt his gait and send him tumbling to the dirt. There could be no progress. The keys were infinitely far from his grasp, and with each fruitless exertion, they edged even farther away.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Then without a word, Hixus scooped up the keys and left the gymnasium. Kytheon dropped to his knees in the dirt, frustrated and full of spite.
The days that followed unfolded much like the first: Hixus offered the keys, Kytheon attempted to retrieve them, but failed, Hixus left with the keys, and Kytheon seethed at the cruel game.
One gray morning after a punishing storm, Kytheon struggled to rise from the muddy mire that had become the gymnasium ground for what felt like the hundredth time. When his strength failed, he collapsed back into the muck.
Red-eyed, he yelled at the warden, "I can’t do it!"
"Why is that? Are you not brave enough?"
Kytheon turned away.
Hixus continued, "Are you not strong enough? Or fast enough?"
The warden stood over Kytheon, looking down at the boy who returned his gaze with eyes that were filling with tears and contempt.
"It’s not me! It’s you! You won’t let me even get close," said Kytheon.
At that, Hixus knelt in the mud beside him. "Now you understand."
It was common to call hieromancy "law magic," but Hixus said that this was an oversimplification. "Laws are created by people, and laws can change, but laws are created in reaction to specific behaviors. A person steals, and laws are put in place to prevent more theft. This is the starting point for hieromancy as a practice."
"Every action has a response that can counter it," Hixus went on. "A master of hieromancy can adapt to any scenario, and turn it to his advantage. Victory in any contest will go to the one who has control of the situation."
Half a dozen escape attempts later, Kytheon took to his training. It complimented his natural talent for reading others in combat, intuiting their position and body language to understand what they would do next. Hieromancy gave Kytheon a tool to disrupt opponents and press his advantage.
Every morning, Kytheon the student was awakened before dawn to join Hixus in the gymnasium, and every afternoon, the irons that bound his wrists were replaced and Kytheon the prisoner rejoined the others at the Waterfall of Akros. He benefited from both activities. Hieromancy strengthened his mind, and turning the great crank strengthened his body.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He fell into a rhythm and for four years he relied on the structure to carry him through his days. Until one morning his rhythm was interrupted.
Kytheon’s eyes flew open at the piercing sound of a shrill shriek. He bolted up, alert. It was later than usual, he could tell. #emph[Where were the guards?]
More shrieks sounded, gathering together as a rising, terrible chorus.
#emph[Harpies] . He didn’t know how he knew, but he did know. Though he had never encountered one, Kytheon knew them from stories—winged horrors that feasted on the dead and carried off children.
He sprang to his feet and strained to look out his window. The harpies were approaching from up river. Their relentless shrieks were answered by the deep clanging of bells, calling soldiers to their posts on the walls of the Kolophon, the mighty Akroan fortress. The panicked scrambling above meant that no stratian or oromai rider arrived with warning.
Kytheon watched through his narrow slit of a window as the horde descended on the fortress like flies on a ripe corpse. The harpies were endless, and he couldn’t shift his gaze from the black cloud of feathers and talons and hunger.
Through the terrible noise, Kytheon heard a pounding at his cell door. He saw Hixus’s face in the door’s barred window.
"The polis is under attack," said Hixus.
"Harpies."
"In unprecedented numbers."
The bolt in the door clicked, and the door swung open. The warden filled the doorframe. He had donned his full armor—his bronze-plated breastplate, matching greaves, and metal-crested helm. He gripped his unsheathed sword in one hand and held a rough sack slung over his shoulder in the other.
"Do you want to earn your freedom?" said Hixus, tossing the sack at Kytheon’s feet.
Kytheon raised an eyebrow. He knelt and reached into the sack, and when he withdrew his hand, it was wrapped around the hilt of a sheathed Akroan sword. The other contents completed the armaments of a hoplite: breastplate, greaves, and round shield. Kytheon grinned.
A short while later, Kytheon found himself, armed and armored, in the prison’s cavernous waterworks, among a little under half of the prisoners. Warden Hixus stood atop a chunk of masonry and addressed the gathered criminals.
"As you know, a host of harpies attacks the polis ahead of any scouts. We do not know why, and that does not matter. I have been given orders to open my cells and offer freedom to those who fight to defend the polis. You here are the willing ones. Despite what has come before, Akros is your polis. What you do today will shape its future, and your place in it. If you die in battle, then it will be among heroes. Earn this!"
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kytheon and Hixus sprinted from the Archway of Champions to the bright sands of the arena at the head of the militia of prisoners. At their approach, harpies scattered into the air from the corpses of the Akroan guards upon which they feasted before wheeling around to attack what they saw as fresh meat.
#emph[So many] , thought Kytheon.
The winged creatures wheeled above the polis, a swirling, ravenous mass…then fell upon the prisoners.
Prisoners scattered, fending off what they could. A harpy dived into Kytheon, who had only enough time to lift his shield to deflect its weight. The harpy grabbed hold of the rim of the shield with its talons, but Kytheon leaned into it, managing to pin the monster beneath the shield. Its dark eyes made it seem almost human until it parted its leathery lips to reveal pointed teeth meant for piercing human flesh. The harpy shrieked, trying to wriggle free, but fell silent when Kytheon thrust his sword into its neck.
Another harpy crashed into Kytheon’s back before he could withdraw his blade. Talons sunk deep into the muscle of his left arm. Kytheon gritted his teeth and dropped his weight to his right to roll away from the new attacker, bringing his shield around to catch the harpy in its ribs, forcing it to retreat.
He braced for a counterattack.
The harpy circled Kytheon and crouched low, using its arms as support. Kytheon circled with it. The harpy stood upright, lifted its black-feathered wings, and screeched.
Kytheon lunged at it.
With a downward stroke of its wings, the harpy leapt into the air to avoid the attack while another harpy barreled into Kytheon. Harpy and Akroan tumbled to the sand of the arena.
More harpies descended on Kytheon, vultures converging to pick his bones clean.
Filed teeth slid into the flesh of his upper arm.
Kytheon yelled out in pain, but the yell turned into a roar. He wrapped both arms around the harpy gnawing at his flesh, and pinned it to him. Using it as a shield against the others, he rolled free. He cast the harpy aside and scrambled to his feet. He had bought himself a moment.
Before the harpy could find its feet, Kytheon summoned forth from the ground a set of brilliant white chains to bind the monster.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/09.png", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
More enemies swarmed from all directions. Everything around him was a blur of black feathers, and all sound was drowned out by the shrill screeches of the harpies.
A sudden burst of white energy erupted in the sky above the arena, sending out waves in concentric rings. It passed through the mass of harpies. They began to fly erratically, colliding with one another.
#emph[Hixus] . Kytheon found his mentor on the steps at the base of Iroas’s column in the center of the arena. His eyes glowed an intense white as he channeled energy into the sky.
Where the disoriented harpies crashed to the sand, Kytheon called forth glowing, white chains to bind them.
"That won’t hold them forever," boomed Hixus, his voice infused with magic that allowed his words to be heard above the harpies. "Form up around the column in the center. Put your backs to it, shield to shield!"
Kytheon scooped up his sword and bolted for Hixus, where the surviving prisoners were already ranking up in a ring around the column. They locked their shields, with swords and spears jutting out. They became a single entity, a phalanx in the Temple of Triumph, standing against a host of enemies.
Many harpies fell, and more turned away.
Kytheon raised his sword in salute. "Hoplites of the Broken Chains!" he declared, and was answered with a collective, rising roar.
The respite faded as quickly as it had begun. "Cyclops!" came a cry from the wall of the Kolophon.
"And another!" called a second voice.
"Here too!"
Kytheon turned to Hixus, "Warden, the walls!"
Above the arena, the harpies were regrouping. Scores flew off for the walls in search of easier prey.
"Undefendable if the harpies get to the guards," said the warden, "and perhaps futile if the cyclopes number more than a few."
"Allow me to rally the Irregulars. If you can keep the harpies off us, we can keep the cyclopes off the walls."
Kytheon felt the weight of Hixus’s gaze. He met it, expecting a lesson, even in the middle of all this, but his mentor simply nodded.
A moment later, Kytheon was making his way along the top of the wall that surrounded the polis. Harpies passed him by as they converged on the Temple of Triumph. When he turned to follow their course, he saw a bright, white helix reaching skyward. Glowing pulses surged up the winding, parallel strands, and Kytheon understood.
The harpies were drawn toward the source, and they converged once again on the Temple of Triumph. He didn’t know how long the warden and the others would be able to hold out, but if they didn’t buy him enough time to deal with the cyclopes, the polis would be lost.
He ran flat out, passing sporadic clumps of soldiers battling cyclopes. Each blow against the walls reverberated throughout the polis, echoing of marble and stone.
Finally, he arrived at the Foreigners’ Quarter, where the old wall turned inward, marking the polis’s original boundaries. The wall had been extended to include the Foreigners’ Quarter, but it was neither as tall, nor as formidable here. From where he stood, he could see three of the lumbering cyclopes barreling toward the wall. Left alone, they would bring it down.
From the old wall, Kytheon dropped down onto Stone Pike, a raised walkway built into the wall that allowed quick access around the Quarter. As he ran, he was greeted by the familiar pungent odors of the Quarter. Below him were familiar streets he knew and loved, streets that he hadn’t seen since he was pulled from them by Akroan guards. He had been gone for four years. He had been gone when the attack came. But now he was here. He was home.
Kytheon followed Stone Pike to the Quarter’s fortified gatehouse, the point at which non-Akroans first entered the polis. As he approached, he saw a man directing people who carried enormous beams meant to reinforce the gate. Kytheon laughed out loud. He knew the man, an Irregular named Zenon, a Setessan who always insisted on placing wagers on any form of contest. His hair had grown shaggy, but he wore the same green cloak he’d brought from the woodland polis years ago when he first came to Akros. Kytheon called down to his friend.
"I didn’t believe it when they told me the prisoners were released," said Zenon.
"How much did you bet I’d still be alive?"
"Who says I bet you’d be alive? Besides, it isn’t time to collect yet." His mouth parted in a grin that would have come across a cruel had Kytheon not known him. "Now then, in case it got by you, a handful of cyclopes want into the polis. Give us a hand?"
Kytheon climbed down to the street to help bear one of the beams. The wall behind them boomed then groaned as a cyclops threw its weight into it.
"It’s going to come down!" shouted Zenon.
Kytheon turned to his friend. "Then we must open the gate."
"What?" Zenon gave him a look.
"Trust me," Kytheon said, running toward the gate. He understood Zenon’s hesitation; only a few years ago his face would have held the same baffled expression, or more likely he would have charged at the straining wall without so much as a thought. But, this was not a few years ago. #emph[Adapt, turn the situation to my advantage, ensure victory.]
Kytheon confidently threw his weight into one of the beams that was holding the gate shut.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The great wooden gates moaned as their hinges gave to the power of the cranks that drove them. The sound did not go unnoticed. As Kytheon hoped, the cyclopes diverted their attention to the opening in the wall, and they rushed toward it. Kytheon and a handful of the Irregulars marched through the gateway and on to the causeway.
"Seal it!" called Drasus to the soldiers at the gatehouse.
The first cyclops came charging down the causeway as the gates began to creak closed. It was a thing of raw anger and unrelenting hunger, its single eye fixed on the gate behind the Irregulars. It had a disproportionately large mouth that frothed as it ran, sending globules of foamy saliva in all directions. This was a mouth that could swallow a person whole.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/10.jpg", width: 100%), caption: [Art by Raymond Swanland], supplement: none, numbering: none)
The Irregulars formed up to take the charge, spears braced, with Kytheon at the apex of the formation. As the cyclops lifted one of its enormous arms to backhand the nuisance aside, Kytheon conjured lengths of chain forged from magic from the ground and bound its wrists.
"Ready now, Irregulars!" said Kytheon.
The cyclops strained against the fetter, but more chains followed. Enraged, the cyclops lurched forward in an attempt to break free. Kytheon ceased the spell, and the monster’s momentum sent it stumbling at the defenders. The Irregulars met its momentum head on, letting its weight drive it onto half a dozen spears. The cyclops let out a bellow that faded into a gurgle as blood bubbled up in its throat, before it collapsed on the causeway between Kytheon and the Irregulars.
Before Kytheon could rejoin his comrades, the second cyclops was upon him. Zenon the Setessan tossed his spear to Kytheon, who caught it in time to sidestep out of the cyclops’s reach. Kytheon whirled, planted his feet, and drove the spear into the side of the brute’s leg. The spear’s tip tore through muscle before emerging out the other side.
The cyclops tried to swat at Kytheon. It took a step to pivot. As it brought its other leg around, it caught the shaft of the spear, and it went crashing to its knees.
Kytheon dragged his sword across its throat.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Kytheon watched the sun break over the tops of the mountains that rose above Akros. He stopped climbing for a moment to let the sunlight wash over his face.
Drasus hurried to catch up. "What are you doing?"
Kytheon glanced down to Akros below. "The prison is the last place in Akros to see the sun, did you know that?"
"Doesn’t surprise me."
"Well, today #emph[we] are the first," said Kytheon, closing his eyes and filling his lungs with crisp air.
"Well-earned, I’d say. Look." Drasus pointed to the causeway in front of the polis’s main gate where he counted more than twenty Akroans tugging at ropes tied to the lifeless corpse of a cyclops that they were hauling away. Two other cyclopes lay lifeless on the causeway.
"Well-earned," Kytheon agreed.
The two Irregulars turned to resume climbing the mountain. They scanned the surrounding area for another wave of monsters, for any sign that the attack wasn’t over.
Farther up their ascent, Kytheon and Drasus parted ways. Drasus was to scout to the north, while Kytheon took the south.
For more than an hour, Kytheon picked his away along a crumbling stone footpath that took him higher up the mountainside. He was not an experienced climber, but he relied on his reflexes to keep his footing. The path took him to the edge of a deep gorge that dropped to a river that wound out of the mountains toward Akros. Spanning the gorge was a bridge of rock that somehow seemed both natural and shaped all at once. Kytheon’s gaze followed the length of the bridge. The other side was bathed in daylight despite the shadows that still shrouded the surrounding rocks.
Kytheon crossed the bridge.
To his surprise, a man greeted him on the other side. The man had a powerful frame that was draped in flowing, gold fabric. Thick, black hair fell past his shoulders, and above his head floated a laurel of golden leaves. The spear he held was tipped in brilliant golden filigree that surrounded a luminous orb. Behind the man rose an immense marble statue so brilliantly illuminated that Kytheon was unable to make out its features.
"Kytheon Iora of Akros," the man called out in a voice that seemed to come from every direction. "Your task is not yet finished."
"True enough, if you stand in my path." Already, bands of white energy rippled across the surface of Kytheon’s skin. "Who are you?"
The man lowered the tip of his spear to the ground and the shift in light brought out the detail of the statue, which Kytheon recognized as a marble replica of the man.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/12.jpg", width: 100%), caption: [Art by <NAME>anland], supplement: none, numbering: none)
All Kytheon could articulate was, "Heliod."
"God of the Sun," boomed Heliod.
At this, Kytheon bowed his head.
"You were given the task of defending your polis. The monsters that attacked it did not do so out of malice. They were fleeing before something far worse. My brother, Erebos, God of the Underworld, has recruited a cruel titan who now stalks the lands beyond these mountains. On his errand, he will pass through Akros."
"What errand? What will he do?"
"He is tasked with reclaiming those who have escaped from the Underworld. All those who stand in his path mean nothing to Erebos, who sees only the inevitability that all mortals will end up in the Underworld."
The Sun God reached out and put his hand upon Kytheon’s shoulder. "You proved your worth as a warrior in the attack on your polis, but it is time to prove yourself worthy to be my champion." He reached up to the sunlit sky, and the light coalesced around his fist. It elongated and took the shape of a spear that resembled the god’s own weapon.
"With this spear, destroy the titan. This is what I task you with. This is your ordeal."
Kytheon gaped, both at the spear and at the task the god had set before him.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kytheon was sprinting. Beneath his feet, the cracked, barren earth flew past. His chest heaved and his lungs burned, but his legs continued pumping. If Kytheon had his way, his legs would carry him to the low hill ahead, where a windblown, crumbling formation of rocks stood. And there he would not be alone.
Heavy footfalls, one for every half-dozen of his, shook the ground behind him, kicking up clouds of dust. Killing a titan was no easy task, but Kytheon had clearly made an impression on Erebos’s servant. Kytheon glanced at the sticky, black blood that clung to the tip of his sun-touched spear, and risked a look over his shoulder. His vision was filled by the titan’s frame.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/13.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The titan was clad in scale armor fashioned from scores of golden masks from those who escaped the Underworld. At that moment the vacant eyes of each mask seemed to be staring right at Kytheon.
A shadow streaked overhead. Kytheon saw the head of the titan’s massive flail falling like a meteor toward him. He rolled away as it slammed into the ground beside him.
When Kytheon reached the rocks, he kept running. As he passed through two crumbling pillars, the titan’s flail pulverized one to his left. It exploded in a hail of stone shards.
Kytheon tumbled to the ground. The back of his head felt warm, and when he touched it, his hand came away smeared with blood. #emph[Careless] , Kytheon thought. #emph[Should have seen that coming] . The clank of chain told Kytheon that the titan was gathering its flail for another swing. He had to keep moving.
The titan let out a low, rumbling roar, and the stench of mold and rot billowed from its mouth. Winded, Kytheon gulped the foul air, and though it seemed to cling to the inside of his mouth, it was enough for him to scramble away from the titan’s attempt to stomp the would-be champion of Heliod to pulp.
The titan lashed out with a backhand. Kytheon anticipated it. He caught the blow, unscathed and unmoved, his protective magic absorbing the impact. He grabbed hold of one of the titan’s colossal fingers, planted his feet, and refused to let go. He just needed a moment.
"Now!" Kytheon yelled.
A heartbeat later, Drasus came charging from around another rock pillar. "Irregulars," he called, "bring it down!"
Three Irregulars emerged from hiding to join Drasus. They had ropes that ended in crude grappling hooks. #emph[Just another bully in the Quarter] , thought Kytheon, smiling amidst the chaos.
Olexo, the youngest among them, cast his rope over the titan’s thick forearm, and the hook sank into pallid flesh. The others followed his lead, and when the titan broke free of Kytheon’s hold, the Irregulars yanked on their ropes. The titan wobbled off balance. Enraged, it whirled its flail around its head, clearly eager to be rid of such annoyances.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/14.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#emph[Every action has a response] . The idea filled Kytheon’s mind. #emph[Every action has a tipping point that, if recognized, can be harnessed as magic to gain control of a fight.] He saw his opening.
As the black iron flail orbited the titan’s head, Kytheon drew on hieromantic magic to conjure an ethereal wedge of energy that struck the titan on the inside of its elbow, so that its arm folded at the joint. The momentum in the head of the flail sent it arcing over the titan’s shoulder, striking it in the back. It crumpled to its knees, rearing its head up to bellow in agony and anger.
That was all Kytheon needed. He leapt part way up one of the pillars, only to turn and launch himself at the titan, spear in hand. Sunlight caught the tip of the spear, blinding the titan during his approach, until he sunk the spear deep into its chest, parting the masks of the Returned. Dark blood welled up around the spear, and the titan took one more shuddering breath before collapsing to the dust.
Kytheon rolled off the fallen titan. #emph[The Ordeal is done,] he thought. #emph[Heliod’s task is fulfilled. Akros is safe.]
He reclaimed his spear, and turned to the Irregulars. Here they were, a bunch of kids from the Foreigners’ Quarter. Together, they had broken the stranglehold of crime lords in the Quarter, defended Akros from hordes of ravening monsters, and destroyed a titan in service of a god on behalf of another god. They were his comrades, his family, and his terms for accepting the Sun God’s Ordeal. Alone, he was strong and skilled. But together with his Irregulars, what were the squabbles of the gods?
In his peripheral vision, Kytheon saw the horizon move. When he looked, he saw two wisps of smoke rising into the sky, their source a pair of dark eyes. Erebos, God of the Dead, loomed over the landscape, a witness to the defeat of his servant. Inky, black vapor rose from the god’s dark eyes that were set in his emotionless face.
Kytheon drew his spear back. He was the champion of Heliod, the Sun God. If Erebos was the cause of all of this trouble, then he would have to answer for it. Kytheon let the spear fly. He felt its power as he let it loose, and the spear sailed through the air toward the God of the Dead.
Emotionless, Erebos gave a simple flick of an emaciated wrist. From the horizon, his whip unfurled, appearing to take on a life of its own. When it met the champion’s spear in flight, Erebos flicked his wrist a second time. The whip cracked, deflecting the spear back toward Kytheon at blinding speed.
Kytheon stood defiantly against the counterattack and the Irregulars fell in around him. Striations of light flickered to life on his skin, and he summoned all the magic and strength that he could as he watched the tip of the weapon close in.
When the spear slammed against him, it exploded in a flash of intense light that washed over Kytheon, turning everything white.
The light lingered for a while, and when it died down, it took a moment for Kytheon’s eyes to adjust. His ears rang, and he found it difficult to focus.
Color slowly seeped back into his surroundings. He looked down, inspecting where the spear made contact. No damage, but he noticed flecks of red. He moved a hand to wipe them, and saw that the back of it was splattered red too—both hands were. But if it wasn’t his blood….
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/15.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/16.png", width: 50%), caption: [], supplement: none, numbering: none)
#pagebreak()
#emph[No.]
He whirled around.
His eyes passed over four lifeless bodies.
#emph[No.]
The ground heaved, and Kytheon struggled to keep his footing. He staggered among his fallen Irregulars, mouth agape. His thoughts turned to the spear, thrown by his own hand.
With clenched fists, Kytheon began to shake. His magic exploded to life once more, and bands of light moved faster and faster over his body. His skin threw off arcs of light that rippled from him with increasing intensity. The sky above him spun.
As white light continued to pour off of him, the landscape around him began to shift, bend, and stretch.
From it, rolling plains emerged.
And the twilit sky gave way to a vibrant blue.
Nothing made sense anymore; it felt like the whole world was coming to an end.
Eyes red and face twisted in anguish, Kytheon tilted his gaze skyward, where a brilliant sun shone. He closed his eyes and knelt there unable to will himself from that spot.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Time passed. Kytheon had no way to gauge how much. A continuous, dull ache numbed his insides.
The hairs on the back of his neck stood up. #emph[I’m being watched] , he thought. #emph[Erebos? Heliod? Fine. Let them.]
Then he felt a blast of warm air accompanied by a low, rumbling growl. His eyes flew open and an enormous, shadowy mass, silhouetted against the sun, filled his vision.
A face.
His pupils adjusted to the light.
A lion’s face.
Kytheon stumbled backward at the revelation, throwing his arms up defensively. The lion made no movement, and after a moment, Kytheon lowered his arms. He saw that the lion was barded like a warhorse, and atop a saddle sat a rider encased in armor like none Kytheon had ever seen. It covered the rider from head to toe, and where it caught the sun it gave off a brilliant gleam.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/17.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Though his throat was dry, Kytheon managed to push words out of his mouth. "Where am I? Who are you?"
"I am Moukir, captain of the Knights of the Pilgrim’s Road. You are lost in the Bant nation of Valeron. You are unwell." As the knight spoke, Kytheon noticed she was not alone. A handful of other knights had formed up behind their captain. "What is your name, wanderer?"
"Kytheon," Kytheon choked out.
"Gideon?" Moukir attempted to confirm.
Before he could correct the knight, Kytheon was overcome by a wave of serenity that suddenly welled up inside of him. His eyes were drawn skyward.
Beyond the knights he saw a woman descending from the air, held aloft on two wings of white feathers. There was a sense of nobility about her that was calming and inspiring all at once. She came to hover before him, an angel clad in plate armor like the knights.
In that moment, Kytheon knew that he had left Theros, his home, behind. His Irregulars were gone—a pain he brought with him. His ordeal had only begun.
#figure(image("004_Gideon’s Origin: Kytheon Iora of Akros/18.png", width: 100%), caption: [Art by <NAME>urai], supplement: none, numbering: none)
|
|
https://github.com/almarzn/portfolio | https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/.template/education.typ | typst | #let education(content) = grid(
columns: (auto, 1fr),
gutter: 16pt,
..content.map(item => (align(right, item.dates), [
#text(weight: "bold", item.name)
#item.location
])).flatten()
)
|
|
https://github.com/VZkxr/Typst | https://raw.githubusercontent.com/VZkxr/Typst/master/Seminario/Expo/speak.typ | typst | Exposición
\
\
* Contenidos: *
- En la introducción se da un recuento de lo planteado en la presentación.
- En el capítulo I se examinarán problemáticas generales y problemáticas visuales dentro de la enseñanza.
- En el segundo capítulo exploraremos un poco de la RP como metodología de enseñanza enfatizando el uso de las TICs
- Y en el tercer capítulo se presenta una propuesta concreta de trabajo basada en la RP y las TICs.
El objetivo de este proyecto es mostrar que mediante una correcta integración de las herramientas de las que haremos mención se puede fomentar un aprendizaje más significativo, activo y alineado a las demandas del siglo XXI.
* Introducción: *
[LEER DIAP] Con todo esto, se pretende proporcionar una visión integral que permita mejorar la enseñanza.
* Capítulo I: *
- Algunas problemáticas generales son la mezcla de diferentes áreas: Si abrimos un libro de texto de los nuevos libros de la SEP, nos daremos cuenta de que la mezcla de temas es sólo un intento de unificación de diferentes materias y no se ve clara la conexión entre estos temas. Un ejemlplo de esto es que el tema de números naturales está justo antes de empezar el tema de la evolución y tecnologías verdes. ¿Por qué mezclar conceptos y consecuentemente generar una saturación de información con esta mezcla? si era lo que Kline criticaba en el fracaso de la matemática moderna. Bueno, en cuanto a las problemáticas visuales, tenemos una falta de visualización geométrica, según <NAME> de la Universidad Técnica de Manabí, argumenta que la enseñanza de la geometría es un desafío para todos los involucrados en el proceso de enseñanza porque se puede desvirtuar y se han dejado de lado procesos de razonamiento, argumentación y visualización, los cuales son trascendentales para el aprendizaje, lo que trae como consecuencia una falta de entendimiento en la analiticidad de la geometría y su comportamiento iterativo como en el cálculo.
Ahora, a manera de conectar la visualización geométrica con el uso de software, pasamos a nuestro capítulo II.
* Capítulo II: *
- Cuando se empezaron a trabajar los problemarios del seminario, al ser algunos algo capciosos, nos dimos cuenta que la manera de abordar los ejercicios dependía totalmente del entendimiento del problema en sí. Sin embargo, después de la lectura de Polya, nos centramos en los cuatro pilares que se necesitan según Polya para resolver un problema: comprender el problema, concebir un plan, ejecución del plan y examinar la solución obtenida. Posteriormente durante algunas soluciones se destacó la importancia de la visualización y el uso de las heurísticas para su conclusión. Así que durante este capítulo y el siguiente veremos de manera implícita como puede esto relacionarse con el uso de las TICs en la RP, mencionando antes algunas tecnologías recomendadas [LEER DIAP].
- En mi segundo ensayo titulado ''metodología inmarcesible'' hice incapié en el uso de Manim para visualizaciones de construcciones matemáticas pero a fecha de hoy no existen estudios acerca del apoyo que ha dado Manim a estudiantes de matemáticas, consecuentemente no es posible formar una argumentación sostenible sobre el uso de esta herramienta, sin embargo podemos plantear un análisis casi análogo.
- La idea de que la tecnología como la conocemos hoy sea un puente para conectar objetos matemáticos con propiedades, haciendo uso de conceptos manipulables dentro de los programas en lugar de objetos abstractos, está bien sustentada en un estudio de la Universidad Manuela Beltrán Virtual, de donde parte un argumento más general a la hora de proponer que los límites y las funciones junto con sus operaciones ayuden no solamente a visualizar, si no también a manipular los valores de estos y consecuentemente, intuir un cambio gráfico y analítico. Todas estas características las posee la paquetería Manim, que por propia definición del autor, es un motor de animación para videos explicativos, por lo que es una TIC per se.
- Y pese a no tener estudios de ventajas y crecimiento intelectual así como un ahorro en el tiempo de aprendizaje, su uso sí se ve reflejado por importantes universidades como la Universidad de Alcalá: Escuela Politécnica Superior, y también por grandes divulgadores de las matemáticas, por mencionar algunos: Mates Mike, BlueDot, 3Blue1Brown, que sin duda al observar el crecimiento obtenido video a video, junto con los excelentes comentarios de los usuarios, es claro que nuestro argumento general del párrafo anterior, conserva su esencia al estar haciendo uso de esta paquetería de Python.
- Una vez comprendido nuestro panorama y visión del futuro de la enseñanza de las matemáticas, estamos seguros para proponer una metodología que encamine a los estudiantes a usar estas herramientas no sólo para la resolución y exposición de problemas, también para un sencillo entendimiento ante las soluciones propuestas por otros compañeros.
* Capítulo III: *
- Un pequeño ejemplo que aborda una de las dificultades mencionadas en el primer capítulo, está contenido en la materia de cálculo integral a nivel bachillerato: "Calcular áreas bajo curvas", aquí se presentan dos nociones [LEER DIAP].
- De aquí podemos identificar el problema de graficar esta comparación, pues para simular una aproximación en clase, comúnmente se hace uso del pizarrón, dibujando rectángulo a rectángulo la cantidad que convenga, pero lo que sucede es que se pierde tiempo al momento de querer dibujar hasta 20 rectángulos pequeños (recordemos que la idea es llevarlos hasta infinitos rectángulos), más aún es complicada la práctica de manejar y/o comunicar iteraciones en funciones sin ayuda de software. Además de que se puede limitar a un solo ejemplo de este tema tan importante.
- Y es aquí donde presento como propuesta didáctica el uso de Manim para visualizar las iteraciones hasta (aparentemente) $n$ rectángulos. Para esto no se requieren muchos conocimientos en programación, veamos una animación compilada proporcionada por ChatGPT.
- Ahora una compilada por mi propio código.
- Previamente en el seminario, se presentó una secuencia que tenía por título 'La distribución binomial, su esperanza y varianza'. Y si bien no se introdujo una animación en Manim para la visualización de la solución, sí se mostró la gráfica que representaba la función de densidad vinculada con el problema, construida en Python. A continuación se expone la planeación de la secuencia junto con el problema propuesto y el desarrollo de este.
- Y aunque esto no se observó en la clase muestra debido a falta de tiempo y organización, la idea es que con la corrección se logre mantener la relación visual interactiva de GeoGebra con la relación visual explicativa de Python; los alumnos podrían deducir una probabilidad mediante los conceptos y el registro de sus datos obtenidos en el applet, más aún, llevar estos datos a un programa escrito en algún lenguaje de programación.
* Planeación de clase: *
\
[LEER DIAP]
* Conclusiones y reflexión: *
\
Como se pude notar, existe una pequeña barrera entre la comunicación visual desarrollada en Manim y una construcción gráfica a través de python; por un lado se puede obtener un video y por el otro una simple imagen. Sin embargo el objetivo explicativo se mantiene en cada caso. |
|
https://github.com/qujihan/typst-book-template | https://raw.githubusercontent.com/qujihan/typst-book-template/main/README.md | markdown | <div align="center">
<strong>
<samp>
[中文](./README_zh.md)
</samp>
</strong>
</div>
# Typst-book-template
> [!IMPORTANT]
> Prerequisites:
> 1. [typst](https://github.com/typst/typst): *0.12.0* or later
> 2. [typstyle](https://github.com/Enter-tainer/typstyle)
> 3. [Fonts](./fonts.json)
> - Chinese font: [Source Han Serif SC](https://github.com/adobe-fonts/source-han-serif)
> - Western font: [Lora](https://github.com/cyrealtype/Lora-Cyrillic)
> - Code font: [CaskaydiaCove Nerd Font](https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/CascadiaCode.zip)
> - If you want to install all fonts at once, you can run download.py under the fonts directory (`python typst-book-template/fonts/download.py`)
> - For users in mainland China, you can use `python typst-book-template/fonts/download.py --proxy` to improve download speed
# Quick Start
> [!Tip]
> By default, the main.typ file in the parent directory of typst-book-template is used as the project entry point for compilation, and the output is saved as output_file.pdf.
>
> If you want to make modifications, you can refer to typst-book-template/metadata.json and create a metadata.json file in the project root directory (at the same level as typst-book-template).
metadata.json
// output_file_name must end with .pdf/.svg
```json
{
"root_file_name": "main.typ",
"output_file_name": "typst-book-template-demo.pdf"
}
```
main.typ
```typ
#import "typst-book-template/book.typ": *
#show: book.with(info: (
name: "author",
title: "typst-book-template demo",
))
#include "src/chapter1.typ"
```
src/chapter1.typ
```typ
#import "../typst-book-template/book.typ": *
// Please refer to the examples in the `example` directory for how to use `path-prefix`.
#let path-prefix = figure-root-path + "src/pics/"
= chapter 1
== section 1
```
```shell
# Add this project as a git submodule
git init
git submodule add https://github.com/qujihan/typst-book-template.git typst-book-template
git submodule update --init --recursive
# recommand install tqdm
# pip install tqdm
python typst-book-template/fonts/download.py
# Real-time preview
python typst-book-template/op.py w
# Compile
python typst-book-template/op.py c
# Format typst code
python typst-book-template/op.py f
``` |
|
https://github.com/GYPpro/Java-coures-report | https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/.VSCodeCounter/2023-12-14_23-06-43/diff-details.md | markdown | # Diff Details
Date : 2023-12-14 23:06:43
Directory d:\\Desktop\\Document\\Coding\\JAVA\\Rep\\Java-coures-report
Total : 7 files, 453 codes, 80 comments, 52 blanks, all 585 lines
[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details
## Files
| filename | language | code | comment | blank | total |
| :--- | :--- | ---: | ---: | ---: | ---: |
| [README.typ](/README.typ) | Typst | 1 | 0 | 0 | 1 |
| [sis9/Test.java](/sis9/Test.java) | Java | 12 | 34 | 5 | 51 |
| [sis9/myLinearEntire.java](/sis9/myLinearEntire.java) | Java | 19 | 0 | 7 | 26 |
| [sis9/myLinearLib.java](/sis9/myLinearLib.java) | Java | 189 | 34 | 14 | 237 |
| [sis9/myLinearSpace.java](/sis9/myLinearSpace.java) | Java | 40 | 4 | 5 | 49 |
| [sis9/myMatrix.java](/sis9/myMatrix.java) | Java | 129 | 4 | 10 | 143 |
| [sis9/myPolynomial.java](/sis9/myPolynomial.java) | Java | 63 | 4 | 11 | 78 |
[Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details |
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/methods-00.typ | typst | Other | // Test whitespace around dot.
#test( "Hi there" . split() , ("Hi", "there"))
|
https://github.com/razetime/adb_ass1 | https://raw.githubusercontent.com/razetime/adb_ass1/main/HW1_112062421.typ | typst | #set text(
font: "Linux Libertine",
size: 14pt,
)
#show link: underline
#set enum(numbering: "A.")
#align(center, text(17pt)[
*PostGIS Lab Assignment*
])
+ (30%) Answer the following questions with spatial SQL queries (Using multiple
queries is allowed). You need to explain your solutions and show the results of
the queries. Please make sure you load the data that is the same as data used in
the lab. #set enum(numbering: "a.")
+ The subway routes are categorized by different colors, and each subway
station can be passed through by one or several color routes. For each color
route r, calculate the total number of populations living in the census blocks
that lie within 200 meters of all subway stations that r pass through. (Note
that one station may be passed through by many color routes, you need to
treat them separately.
/ Target Tables: `nyc_subway_stations`, `nyc_census_blocks`
We assume that `gid` is a primary key here.
The `color` attribute containing the colour routes of `nyc_subway_stations` is a compound attribute, so we split and unnest each color to get duplicate rows:
```sql
select gid,name,unnest(string_to_array(color,'-')) as clr
from nyc_subway_stations limit 5;
```
```
gid | name | clr
-----+--------------+--------
1 | Cortlandt St | YELLOW
2 | Rector St | RED
3 | South Ferry | RED
4 | 138th St | GREEN
5 | 149th St | GREEN
(5 rows)
```
A normalized table is constucted from this data.
```sql
create table station_colors as
select gid,
unnest(string_to_array(color,'-')) as clr,
geom
from nyc_subway_stations;
SELECT 627
```
Since we have associated each unique station with all its color routes, the total population per route can be calculated with `ST_Dwithin`:
```sql
select clr,sum(popn_total) from nyc_census_blocks,station_colors
where ST_Dwithin(station_colors.geom,nyc_census_blocks.geom,200)
group by clr;
```
```
clr | sum
--------+--------
AIR | 2658
BLUE | 385289
BROWN | 245185
CLOSED | 4823
GREEN | 620844
GREY | 128085
LIME | 72730
MULTI | 65547
ORANGE | 534834
PURPLE | 102401
RED | 636236
SI | 27098
YELLOW | 304559
(13 rows)
```
It is of note that even though `AIR` and `CLOSED` are not real color routes, they are still part of some colors and hence are included. They can be filtered out when constructing `station_colors` if required.
+ Show the name of the top 3 neighborhoods with the most population
density. You also need to show the number of total population, the size (in
km2), and the population density (in people/km2) of the neighborhood.
/ Target Tables: `nyc_neighborhoods`, `nyc_census_blocks`
We need to group census blocks by neightborhood, so the first query lets us associate each census block with the neighborhood it is within:
```sql
create table cens_block_nbrs as
select c.blkid, c.popn_total, n.gid as nid, n.name as nbname, ST_Area(n.geom)/1000000 as area
from nyc_census_blocks as c, nyc_neighborhoods as n
where ST_Within(c.geom, n.geom);
SELECT 28793
```
from `nyc_census_blocks.prj` we can tell that the measurement unit is in metres:
```p
UNIT["metre",1,AUTHORITY["EPSG","9001"]]
```
the area hence is divided by 1,000,000 to convert to km#super("2").
In order to get the final result, we group by neighborhood and aggregate each set of grouped values:
```sql
select nbname,(sum(popn_total)) as pop, area, (sum(popn_total)/area) as density
from cens_block_nbrs
group by nid,area,nbname
order by density desc
limit 3;
```
```
nbname | pop | area | density
-------------------+--------+-------------------+------------------
North Sutton Area | 15462 | 0.328194000196611 | 47112.3786258652
Upper East Side | 191051 | 4.19872541579295 | 45502.1419789413
East Village | 59734 | 1.63211671718575 | 36599.0981962363
(3 rows)
```
+ Following the previous question, you may notice that the system spent much
time executing your queries. Find a way to speed up the query executions
and explain your solutions. You need to show the difference of the execution
time. (Hint: Use command EXPLAIN ANALYZE can show the query plan and
the execution time.)
I used a query explaining tool to make sense of the text data that Postgres provides: https://explain.depesz.com
From section a. we have the following query plan (truncated, full version in `.sql` file):
```sql
QUERY PLAN
.
.
.
Planning Time: 1.204 ms
Execution Time: 16550.142 ms
(18 rows)
```
Since it appears that nested loop cost was high, and the inner loop was taking a lot of time, I tried to switch the arguments of `ST_Dwithin` to check if it would reduce the query overhead.
```sql
select clr,sum(popn_total) from nyc_census_blocks,station_colors
where ST_Dwithin(nyc_census_blocks.geom,station_colors.geom,200)
group by clr;
```
```sql
QUERY PLAN
.
.
.
Planning Time: 0.221 ms
Execution Time: 10337.808 ms
(18 rows)
```
A significant improvement, 6 seconds of time difference.
+ (70%) Find at least two spatial data sets online and show at least two different
spatial relationships between the data sets.
You need to explain how you prepare the data, and the queries you use to find
the relationships. Finally, show your query results on google map using .kml
format.
*Google Maps Link:* https://www.google.com/maps/d/u/0/edit?mid=18XVn1RKnA1ir_OmNPkSUjEiDNXw4nOc&usp=sharing
My environment for `gdal` was configured as follows. Inside the miniconda command prompt:
```bash
conda create -n env python=3.6 gdal
activate env
```
We use `esriprj2standards.py` from the PostGIS lab class to get the EPSG id, which is then used to import the `.shp` files:
```bash
shp2pgsql -s 4326 gadm41_TWN_2.shp | psql -d plb postgres
```
For the `.gpkg` files, importing is done in one step:
```sh
ogr2ogr -f PostgreSQL "PG:user=postgres password=<<PASSWORD>> dbname=plb" kontur_population_TW_20231101.gpkg
```
#set enum(numbering: "a.")
+ *Health Facility Analysis*
*Data Used*
#table(columns: (auto,auto,auto, auto),
[*Topic*], [*Link*], [*File Type*], [*Table Name*],
[Health Facilities], [#link("https://data.humdata.org/dataset/hotosm_twn_health_facilities")[The Humanitarian Data Exchange]], `.gpkg`, [health_facilities],
[Populated Places], [#link("https://data.humdata.org/dataset/hotosm_twn_populated_places")[The Humanitarian Data Exchange]], [`.shp`, `.prj`], [pop_places],
[County and Municipality boundaries], [#link("https://gadm.org/")[Database of Global Administrative Areas]], `.shp`, [gadm41_TWN_2]
)
*Map of Populated Places*
#image("qBa_init.png")
*Map of Health Facilities*
#image("qBa_init1.png")
We are looking at two main factors:
- *Diversity:* The count of different varieties of general health facilities present in a county.
- *Coverage:* How many people from populated places can reach the facility?
Using these metrics we can gauge the availabilty of diverse medical services, and find out which counties with a low diversity metric require more average coverage.
*Preprocessing*
We have to convert the population data from varying character to int, trimming out non-required columns, and removing null populations.
```sql
create table pop_corr as
select gid,cast(population as integer),geom
from pop_places
where population is not null;
```
*Population Coverage*
To get the population coverage, we use a `DWithin` call, and then we group the medical facilities by county, aggregating diversity and coverage in the grouping section.
```sql
create table health_pop as
select fid, amenity, h.geom, sum(population)
from pop_corr p, health_facilities h
where ST_DWithin(p.geom, h.geom, 0.1)
group by fid;
create table health_metrics as
select name_2 as name, count(distinct amenity) as diversity, avg(sum) as avg_cov, g.geom
from health_pop h, gadm41_twn_2 g
where ST_Within(h.geom, g.geom)
group by gid
order by avg_cov desc, diversity desc;
```
*Exporting*
We get the data required for the kml file into two separate tables, so we can see how the medical facility data can be related to each county.
The KML `name` attribute is what is displayed in the map legend, hence it is added in both queries.
```sql
create table lowest_per_diversity as
select h.name, diversity, avg_cov, geom from health_metrics h
where avg_cov =
(select min(k.avg_cov) from health_metrics k where k.diversity = h.diversity);
create table lowest_diversity_towns as
select p.name, p.geom
from pop_places p, lowest_per_diversity l
where ST_Within(p.geom, l.geom);
```
The tables are then exported with `ogr2ogr`, like so:
```sh
ogr2ogr -f "KML" B1.kml PG:"host=localhost user=postgres dbname=plb password=<<PASSWORD>>" "lowest_per_diversity"
```
*Results*
The `name` column and `description` column of the KML file is automatically used by Google Maps for labeling the geometry data given to it.
Further customizations have been done with the map to give the outlines and markers appropriate coloring and labels.
#image("qBa_res.png")
+ *Road and Railway Analysis*
*Data Used*
#table(columns: (auto,auto,auto, auto),
[*Topic*], [*Link*], [*File Types*], [*Table Name*],
[County and Municipality boundaries], [#link("https://gadm.org/")[Database of Global Administrative Areas]], [`.shp`, `.prj`], [gadm41_TWN_2],
[Major Roads in Taiwan],[#link("https://www.diva-gis.org/gdata")[DIVA-GIS]],[`.shp`, `.prj`],[twn_roads],
[Major Railroads in Taiwan],[#link("https://www.diva-gis.org/gdata")[DIVA-GIS]],[`.shp`, `.prj`],[twn_rails]
)
In this part, we are looking at the railway-major road ratio of every major county. The ideal ratio for a county would be near 0.5, equally accessible by rail as it is by road.
*Map of Roads*
#image("qBb_init1.png")
#linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak() #linebreak()
*Map of Railroads*
#image("qBb_init2.png")
*Preprocessing*
First, we find all roads and railways which must be checked. We do not want non-operational transport methods.
```sql
create table op_rails as
select geom from twn_rails where exs_descri = 'Operational';
create table op_roads as
select geom from twn_roads
where
rtt_descri = 'Primary Route' or rtt_descri = 'Secondary Route';
```
We prune columns from the counties table for the final result.
```sql
create table areas as
select gid, name_2 as name, geom from gadm41_twn_2;
```
*Intersection Calculation*
The roads and rails are intersected with the counties, and grouped by gid to make sure that the count is correct.
```sql
create table road_count as
select gid, count(r.geom)
from areas a, op_roads r
where ST_Intersects(r.geom,a.geom)
group by a.gid;
create table rail_count as
select gid, count(r.geom)
from areas a, op_rails r
where ST_Intersects(r.geom,a.geom)
group by a.gid;
```
*Results*
The final touch is a three-way join on `gid`, which unifies the results together and provides a proper ratio we can analyze.
```sql
create table roads_rails_per_area as
select a.gid, a.name,
r.count as road_count, l.count as rail_count,
cast(l.count as float)/cast(r.count as float) as ratio, a.geom
from areas a,road_count r,rail_count l
where a.gid = r.gid and a.gid = l.gid
order by ratio;
```
Since some of the ratios are common, this lets us color code the counties to show which regions have abnormal ratios.
#image("image.png")
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/lang-03.typ | typst | Other | // Error: 17-20 expected two or three letter language code (ISO 639-1/2/3)
#set text(lang: "ӛ")
|
https://github.com/xrarch/books | https://raw.githubusercontent.com/xrarch/books/main/xrcomputerbook/chapaudio.typ | typst | #import "@preview/tablex:0.0.6": tablex, cellx, colspanx, rowspanx
= Audio Controller
== Introduction
To Be Designed: A 22.05KHz interrupt-driven double-buffered audio controller |
|
https://github.com/arthurcadore/typst-intelbras | https://raw.githubusercontent.com/arthurcadore/typst-intelbras/main/reports/example-confidetial-en.typ | typst | MIT License | #import "../templates/report-confidential-en.typ": *
#set text(lang: "pt")
#show: doc => report(
title: "Intelbras API Test Report",
subtitle: "ITB Business Networks - Special Projects",
authors: "<NAME>",
date: "02, May 2024",
doc,
)
= as
== Close
=== Closest
asdaasdasasdaasdsaasdas
asdasdasdasasasdaakmsdakmaasdasdsadas
== Softest
asdasdasdasasasdaakmsdakma
asdksdasdasdasd
aAUSAIUDH
== Softest
#lorem(80)
= Hard <hard>
#lorem(80)
== Hardest
#lorem(80) |
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/095.%20prcmc.html.typ | typst | prcmc.html
The Pooled-Risk Company Management Company
July 2008At this year's startup school, <NAME> gave a
talk
in which he suggested that startup founders
should do things the old fashioned way. Instead of hoping to get
rich by building a valuable company and then selling stock in a
"liquidity event," founders should start companies that make money
and live off the revenues.Sounds like a good plan. Let's think about the optimal way to do
this.One disadvantage of living off the revenues of your company is that
you have to keep running it. And as anyone who runs their own
business can tell you, that requires your complete attention. You
can't just start a business and check out once things are going
well, or they stop going well surprisingly fast.The main economic motives of startup founders seem to be freedom
and security. They want enough money that (a) they don't have to
worry about running out of money and (b) they can spend their time
how they want. Running your own business offers neither. You
certainly don't have freedom: no boss is so demanding. Nor do you
have security, because if you stop paying attention to the company,
its revenues go away, and with them your income.The best case, for most people, would be if you could hire someone
to manage the company for you once you'd grown it to a certain size.
Suppose you could find a really good manager. Then you would have
both freedom and security. You could pay as little attention to
the business as you wanted, knowing that your manager would keep
things running smoothly. And that being so, revenues would continue
to flow in, so you'd have security as well.There will of course be some founders who wouldn't like that idea:
the ones who like running their company so much that there's nothing
else they'd rather do. But this group must be small. The way you
succeed in most businesses is to be fanatically attentive
to customers' needs. What are the odds that your own desires would
coincide exactly with the demands of this powerful, external force?Sure, running your own company can be fairly interesting. Viaweb
was more interesting than any job I'd had before. And since I made
much more money from it, it offered the highest ratio of income to
boringness of anything I'd done, by orders of magnitude. But was
it the most interesting work I could imagine doing? No.Whether the number of founders in the same position is asymptotic
or merely large, there are certainly a lot of them. For them the
right approach would be to hand the company over to a professional
manager eventually, if they could find one who was good enough._____So far so good. But what if your manager was hit by a bus? What
you really want is a management company to run your company for
you. Then you don't depend on any one person.If you own rental property, there are companies you can hire to
manage it for you. Some will do everything, from finding tenants
to fixing leaks. Of course, running companies is a lot more
complicated than managing rental property, but let's suppose there
were management companies that could do it for you. They'd charge
a lot, but wouldn't it be worth it? I'd sacrifice a large percentage
of the income for the extra peace of mind.I realize what I'm describing already sounds too good to be true, but I
can think of a way to make it even more attractive. If
company management companies existed, there would be an additional
service they could offer clients: they could let them insure their
returns by pooling their risk. After all, even a perfect manager can't save a company
when, as sometimes happens, its whole market dies, just as property
managers can't save you from the building burning down. But a
company that managed a large enough number of companies could say
to all its clients: we'll combine the revenues from all your
companies, and pay you your proportionate share.If such management companies existed, they'd offer the maximum of
freedom and security. Someone would run your company for you, and
you'd be protected even if it happened to die.Let's think about how such a management company might be organized.
The simplest way would be to have a new kind of stock representing
the total pool of companies they were managing. When you signed
up, you'd trade your company's stock for shares of this pool, in
proportion to an estimate of your company's value that you'd both
agreed upon. Then you'd automatically get your share of the returns
of the whole pool.The catch is that because this kind of trade would be hard to undo,
you couldn't switch management companies. But there's a way they
could fix that: suppose all the company management companies got
together and agreed to allow their clients to exchange shares in
all their pools. Then you could, in effect, simultaneously choose
all the management companies to run yours for you, in whatever
proportion you wanted, and change your mind later as often as you
wanted.If such pooled-risk company management companies existed, signing
up with one would seem the ideal plan for most people following the
route David advocated.Good news: they do exist. What I've just
described is an acquisition by a public company._____Unfortunately, though public acquirers are structurally identical
to pooled-risk company management companies, they don't think of
themselves that way. With a property management company, you can
just walk in whenever you want and say "manage my rental property
for me" and they'll do it. Whereas acquirers are, as of this
writing, extremely fickle. Sometimes they're in a buying mood and
they'll overpay enormously; other times they're not interested.
They're like property management companies run by madmen. Or more
precisely, by <NAME>'s Mr. Market.So while on average public acquirers behave like pooled-risk company
managers, you need a window of several years to get average case
performance. If you wait long enough (five years, say) you're
likely to hit an up cycle where some acquirer is hot to buy you.
But you can't choose when it happens.You can't assume investors will carry you for as long as you might
have to wait. Your company has to make money. Opinions are divided
about how early to focus on that.
<NAME> says you should try
charging customers right away. And yet some of the most successful
startups, including Google, ignored revenue at first and concentrated
exclusively on development. The answer probably depends on the
type of company you're starting. I can imagine some where trying
to make sales would be a good heuristic for product design, and
others where it would just be a distraction. The test is probably
whether it helps you to understand your users.You can choose whichever revenue strategy you think is best for the
type of company you're starting, so long as you're profitable.
Being profitable ensures you'll get at least the average of the
acquisition market—in which public companies do behave as pooled-risk
company management companies.David isn't mistaken in saying you should start a company to live
off its revenues. The mistake is thinking this is somehow opposed
to starting a company and selling it. In fact, for most people the
latter is merely the optimal case of the former.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.
Russian Translation
|
|
https://github.com/fenjalien/cirCeTZ | https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/examples/current-shunt.typ | typst | Apache License 2.0 | #import "../../typst-canvas/canvas.typ": canvas
#lorem(30)
#figure(
canvas(length: 1cm, debug: false, {
import "../../typst-canvas/draw.typ": *
import "../circuitypst.typ": node, to
to("isourceAM", (0,0), (0,3), label: $I_0$, v: h(0.5em) + $V_0$)
to("short", (), (2,3), i: $I_0$,)
to("R", (), (2, 0), label: [$R_1$], poles: "*-*", i: (">_", $i_1$))
line((2,3), (4,3))
to("R", (), (4, 0), label: [$R_2$], name: "R", i: (">_", $i_2$))
line((), (0,0))
}),
caption: [Current Shunt]
)
#lorem(30)
|
https://github.com/jamesrswift/chemicoms-paper | https://raw.githubusercontent.com/jamesrswift/chemicoms-paper/main/src/elements/precis.typ | typst | #import "@preview/fontawesome:0.1.0": fa-icon
#let precis-dates(args) = {
align(bottom)[
#table(
inset: 0pt,
row-gutter: 0.15cm,
stroke: none,
columns: (1fr, 1fr),
..args.dates.map( entry =>{
return (
text(size: 7pt, entry.type),
text(size: 7pt, entry.date.display())
)
}).flatten())
#if (args.doi != none){ text(size: 7pt, link("http://doi.org/" + args.doi, [DOI: #args.doi]))}
//#footnoteSize[DOI: #link("http://doi.org/" + doi, doi)]
]
}
#let author(author) = {
text(author.name)
if ( author.corresponding == true ) [#strong[\*]]
if ( author.at("orcid", default: none) != none ) {
h(0.23em)
link("http://orcid.org/" + author.orcid, fa-icon("orcid", fa-set: "Brands", fill: rgb(166,206,57)))
}
}
#let precis-title-authors-abstract(args) = {
block(text(size: 15pt, weight:500, args.title))
args.authors.map(author).join(", ", last: " and ")
v(1.618em, weak: true)
for ((title, content)) in args.abstracts {
if (args.abstracts.len() > 1){block[*#title*]}
content
}
}
#let precis(args) = {
pad(
top: 0.3em, bottom: 0.3cm,
x: 0em,
grid(
columns: (1.4fr,5fr),
gutter: 0em,
precis-dates(args),
precis-title-authors-abstract(args)
)
)
} |
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/foundations/datetime.typ | typst | --- datetime-constructor-empty ---
// Error: 2-12 at least one of date or time must be fully specified
#datetime()
--- datetime-constructor-time-invalid ---
// Error: 2-42 time is invalid
#datetime(hour: 25, minute: 0, second: 0)
--- datetime-constructor-date-invalid ---
// Error: 2-41 date is invalid
#datetime(year: 2000, month: 2, day: 30)
--- datetime-display ---
// Test displaying of dates.
#test(datetime(year: 2023, month: 4, day: 29).display(), "2023-04-29")
#test(datetime(year: 2023, month: 4, day: 29).display("[year]"), "2023")
#test(
datetime(year: 2023, month: 4, day: 29)
.display("[year repr:last_two]"),
"23",
)
#test(
datetime(year: 2023, month: 4, day: 29)
.display("[year] [month repr:long] [day] [week_number] [weekday]"),
"2023 April 29 17 Saturday",
)
// Test displaying of times
#test(datetime(hour: 14, minute: 26, second: 50).display(), "14:26:50")
#test(datetime(hour: 14, minute: 26, second: 50).display("[hour]"), "14")
#test(
datetime(hour: 14, minute: 26, second: 50)
.display("[hour repr:12 padding:none]"),
"2",
)
#test(
datetime(hour: 14, minute: 26, second: 50)
.display("[hour], [minute], [second]"), "14, 26, 50",
)
// Test displaying of datetimes
#test(
datetime(year: 2023, month: 4, day: 29, hour: 14, minute: 26, second: 50).display(),
"2023-04-29 14:26:50",
)
// Test getting the year/month/day etc. of a datetime
#let d = datetime(year: 2023, month: 4, day: 29, hour: 14, minute: 26, second: 50)
#test(d.year(), 2023)
#test(d.month(), 4)
#test(d.weekday(), 6)
#test(d.day(), 29)
#test(d.hour(), 14)
#test(d.minute(), 26)
#test(d.second(), 50)
#let e = datetime(year: 2023, month: 4, day: 29)
#test(e.hour(), none)
#test(e.minute(), none)
#test(e.second(), none)
// Test today
#test(datetime.today().display(), "1970-01-01")
#test(datetime.today(offset: auto).display(), "1970-01-01")
#test(datetime.today(offset: 2).display(), "1970-01-01")
--- datetime-ordinal ---
// Test date methods.
#test(datetime(day: 1, month: 1, year: 2000).ordinal(), 1);
#test(datetime(day: 1, month: 3, year: 2000).ordinal(), 31 + 29 + 1);
#test(datetime(day: 31, month: 12, year: 2000).ordinal(), 366);
#test(datetime(day: 1, month: 3, year: 2001).ordinal(), 31 + 28 + 1);
#test(datetime(day: 31, month: 12, year: 2001).ordinal(), 365);
--- datetime-display-missing-closing-bracket ---
// Error: 27-34 missing closing bracket for bracket at index 0
#datetime.today().display("[year")
--- datetime-display-invalid-component ---
// Error: 27-38 invalid component name 'nothing' at index 1
#datetime.today().display("[nothing]")
--- datetime-display-invalid-modifier ---
// Error: 27-50 invalid modifier 'wrong' at index 6
#datetime.today().display("[year wrong:last_two]")
--- datetime-display-expected-component ---
// Error: 27-33 expected component name at index 2
#datetime.today().display(" []")
--- datetime-display-insufficient-information ---
// Error: 2-36 failed to format datetime (insufficient information)
#datetime.today().display("[hour]")
|
|
https://github.com/dead-summer/math-notes | https://raw.githubusercontent.com/dead-summer/math-notes/main/book.typ | typst |
#import "@preview/shiroa:0.1.1": *
#show: book
#book-meta(
title: "math-notes",
description: "Notes from math class",
authors: ("dead-summer",),
language: "en",
summary: [
#prefix-chapter("sample-page.typ")[Hello, typst]
= Analysis
- #chapter("notes/Analysis/ch1-measures/ch1-measures.typ")[Measures]
- #chapter("notes/Analysis/ch1-measures/measure-theory.typ")[Measure Theory]
- #chapter("notes/Analysis/ch1-measures/sigma-algebras.typ")[sigma-Algebras]
- #chapter("notes/Analysis/ch1-measures/measures.typ")[Measures]
- #chapter("notes/Analysis/ch1-measures/construct-of-measures.typ")[Construct of Measures]
- #chapter("notes/Analysis/ch1-measures/1-d-lebesgue-measure.typ")[1-D Lebesgue Measure]
= Scientific Computing
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/intro-to-scicomp.typ", section: "1")[Introduction to Scientific Computing]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/modelling-discretization-and-implementation.typ")[Modelling, Discretization and Implementation]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/faster-higher-and-stronger.typ")[Faster, Higher and Stronger]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/computer-representation-of-numbers.typ")[Computer Representation of Numbers]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/accuracy.typ")[Accuracy]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/efficiency.typ")[Efficiency]
- #chapter("notes/ScientificComputing/ch1-intro-to-scicomp/stability.typ")[stability]
- #chapter("notes/ScientificComputing/ch2-scalar-nonlinear-eqns/scalar-nonlinear-eqns.typ")[Iterative Methods for Scalar Nonlinear Equations]
- #chapter("notes/ScientificComputing/ch2-scalar-nonlinear-eqns/the-bisection-method.typ")[The Bisection Method]
]
)
// re-export page template
#import "/templates/page.typ": project
#let book-page = project
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/silky-report-insa/0.1.0/README.md | markdown | Apache License 2.0 | # INSA - Typst Template
Typst Template for full documents and reports for the french engineering school INSA.
## Examples
### Report
By default, the template initializes with the `insa-report` show rule, with parameters that you must fill in by yourself.
Here is an example of filled template:
```typst
#import "@preview/silky-report-insa:0.1.0": *
#show: doc => insa-report(
id: 3,
pre-title: "STPI 2",
title: "Interférences et diffraction",
authors: [
*<NAME>*
*<NAME>*
<NAME>
<NAME>
],
date: "11/04/2023",
doc)
= Introduction
Le but de ce TP est d’interpréter les figures de diffraction observées avec différents objets diffractants
et d’en déduire les dimensions de ces objets.
= Partie théorique - Phénomène d'interférence
== Diffraction par une fente double
Lors du passage de la lumière par une fente double de largeur $a$ et de distance $b$ entre les centres
des fentes...
```
### Blank template
If you do not want the preformatted output with "TP x", the title and date in the header, etc. you can simply use
the `insa-full` show rule and customize all by yourself.
Here is an example:
```typst
#import "@preview/silky-report-insa:0.1.0": *
#show: doc => insa-full(
cover-top-left: [*Document important*],
cover-middle-left: [
NOM Prénom
Département INFO
],
cover-bottom-right: "uwu",
page-header: "En-tête au pif",
doc
)
```
## Notes
This template is being developed by <NAME> from the INSA de Rennes in [this repostiory](https://github.com/SkytAsul/INSA-Typst-Template).
For now it includes assets from the INSA de Rennes graphic charter, but users from other INSAs can open an issue on the repository with the correct assets for their INSA.
If you have any other feature request, open an issue on the repository as well.
## License
This package is licensed with the [MIT license](https://github.com/SkytAsul/INSA-Typst-Template/blob/main/LICENSE). |
https://github.com/EliasRothfuss/vorlage_typst_doku-master | https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/chapter/grundlagen.typ | typst | = Grundlagen
<cha:Grundlagen>
Zielgerichtete theoretische Grundlagen, sowohl fachliche, wie auch
methodische.
Zu den Grundlagen gehören z.~B. auch Details zur Problemstellung, der
Stand der Technik und weitere Grundlagen, welche zur
Konzeptausarbeitung, Umsetzung und Verifikation erforderlich sind.
Grundlagen haben immer einen Bezug zu den nachfolgenden Kapiteln. Diesen
Bezug sollte man gelegentlich explizit herstellen, damit bereits in
diesem Kapitel klar ist, wo und für was die Grundlagen gebraucht und
angewandt werden.
|
|
https://github.com/mem-courses/linear-algebra | https://raw.githubusercontent.com/mem-courses/linear-algebra/main/homework/linear-algebra-homework13.typ | typst | #import "../template.typ": *
#show: project.with(
title: "Linear Algebra Homework #13",
authors: (
(name: "<NAME> (#95)", email: "<EMAIL>", phone: "3230104585"),
),
date: "December 25, 2023",
)
#let lb = math.lambda
#let alpha = math.bold(math.alpha)
#let beta = math.bold(math.beta)
#let theta = math.bold(math.theta)
#let xi = math.bold(math.xi)
#let AA = math.bold(math.italic("A"))
#let BB = math.bold(math.italic("B"))
#let EE = math.bold(math.italic("E"))
#let XX = math.bold(math.italic("X"))
#let OO = math.bold(math.italic("O"))
#let TT = math.upright("T")
#let Lambda = math.bold(math.Lambda)
#let diag = math.upright("diag")
#let ssim = math.attach(sp + math.upright("~") + sp, tl: "", tr:"", t: math.upright("S"))
= P129 习题五 31 #pc
#prob[
设 $AA$ 为二阶矩阵,$bold(P) = display(mat(alpha,AA alpha))$,其中 $alpha$ 是非零向量且不是 $AA$ 的特征向量.
(1) 证明:$bold(P)$ 为可逆矩阵.
]
反证法:反设 $bold(P)$ 不是可逆矩阵,则 $alpha$ 与 $AA alpha$ 线性相关,即存在不为零的 $k in RR$ 使得 $k alpha = AA alpha$.由于 $alpha$ 不是 $AA$ 的特征向量且非零,这样的 $k$ 不存在.故 $bold(P)$ 是可逆矩阵,原命题得证.#ac
#prob[
(2) 若 $AA^2 alpha + AA alpha - 6 alpha = theta$,求 $bold(P)^(-1) AA bold(P)$ 并判断 $AA$ 是否与对角矩阵相似.
]
$
AA bold(P)
= AA mat(alpha, AA alpha)
= mat(AA alpha, AA^2 alpha)
= mat(AA alpha, 6 alpha - AA alpha)
= mat(alpha, AA alpha) mat(0,6;1,-1)\
=> bold(P)^(-1) AA bold(P) = mat(0,6;1,-1) quad wa
$
设 $f(x) = x^2 + x - 6 = (x-2)(x+3)$,则 $f(AA) alpha = theta$,由于 $alpha$ 不是特征向量,故只能是 $f(AA) = OO$,故 $f(x)$ 是 $AA$ 的特征多项式,$AA$ 的两个特征根分别为 $2$ 和 $-3$,应至少个存在一个特征向量,故 $AA$ 可被相似对角化.#ac
#warn[
令 $bold(Q) = display(mat((AA - 2 EE) alpha, (AA + 3 EE) alpha))$,则 $bold(Q)^(-1) AA bold(Q) = diag(-3,2)$.
由于 $bold(Q) = bold(P) display(mat(-2,3;1,1))$,故
$
mat(-2,3;1,1)^(-1) bold(P)^(-1) AA bold(P) mat(-2,3;1,1) = diag(-3,2)\
=> bold(P)^(-1) AA bold(P) = mat(-2,3;1,1) diag(-3,2) mat(-2,3;1,1)^(-1) = mat(6/5,6;2/5,-1)\
$
]
= P129 习题五 32 #wa
#prob[
下列矩阵中,与矩阵 $display(mat(1,1,0;0,1,1;0,0,1))$ 相似的为($quad$)
(选项略)
]
选 (D) 项,对应矩阵为 $display(mat(1,0,-1;0,1,0;0,0,1))$.
#warn[已纠错到错题本上.]
= P130 习题五 33 #ac
#prob[
已知矩阵
$
AA = mat(2,0,0;0,2,1;0,0,1) quad
BB = mat(2,1,0;0,2,0;0,0,1) quad
bold(C) = mat(1,0,0;0,2,0;0,0,2) quad
$
则($quad$).
(A) $AA$ 与 $bold(C)$ 相似,$BB$ 与 $bold(C)$ 相似;
(B) $AA$ 与 $bold(C)$ 相似,$BB$ 与 $bold(C)$ 不相似;
(C) $AA$ 与 $bold(C)$ 不相似,$BB$ 与 $bold(C)$ 相似;
(D) $AA$ 与 $bold(C)$ 不相似,$BB$ 与 $bold(C)$ 不相似.
]
选 (B) 项.
= P130 习题五 34 #ac
#prob[
证明:$n$ 阶矩阵 $display(mat(1,1,dots.c,1;1,1,dots.c,1;dots.v,dots.v,,dots.v;1,1,dots.c,1))$ 与 $display(mat(0,dots.c,0,1;0,dots.c,0,2;dots.v,,dots.v,dots.v;0,dots.c,0,n))$ 相似.
]
设 $bold(P) AA bold(Q) = BB$.
考虑要应用的行变换:需要将每一行依次加上前一行,即按 $i=1,2,dots.c,n-1$ 依次右乘 $EE + bold(e)_(i,i+1)$,即 $display(bold(Q) = product_(i=1)^(n-1) (EE + bold(e)_(i,i+1)))$.
考虑要应用的列变换:需要将每一列依次减去后一列,即按 $i=1,2,dots.c,n-1$ 依次左乘 $EE - bold(e)_(i,i+1)$,即 $display(bold(P) = product_(i=n-1)^(1) (EE - bold(e)_(i,i+1)))$.
考虑对于 $1<=i<n$,有 $(EE + bold(e)_(i,i+1))(EE - bold(e)_(i,i+1)) = EE - bold(e)_(i,i+1) + bold(e)_(i,i+1) - bold(e)_(i,i+1)^2 = EE$,从内到外依次相乘可以得到 $bold(P) bold(Q) = EE$.即 $bold(P) AA bold(P)^(-1) = BB$,即 $AA ssim BB$.
= P130 习题五 36 #ac
#prob[
设 $AA$ 为非零方阵,$m>=2$ 为正整数,证明:若 $AA^m = OO$,则 $AA$ 不能与对角矩阵相似.
]
反设 $AA$ 可被对角化,即存在可逆矩阵 $bold(P)$ 使得 $bold(P)^(-1) AA bold(P) = Lambda$.考虑
$
Lambda^m = bold(P)^(-1) AA^m bold(P) = OO
$
由于 $bold(P)$ 可逆,故 $Lambda^m = diag(lb_1^m,lb_2^m,dots.c,lb_n^m) = OO$.解得 $lb_1=lb_2=dots.c=lb_n=0$ 即 $Lambda = OO$.与 $AA$ 是非零矩阵矛盾,故假设不成立,原命题得证.
= P130 习题五 38 #ac
#prob[
设 $n$ 阶矩阵 $AA$ 的所有特征值为 $seqn(lb,n)$ 且 $AA$ 可相似对角化,证明:对任意的多项式 $f(x)$,矩阵 $f(AA)$ 的所有特征值为 $f(lb_1),f(lb_2),dots.c,f(lb_n)$.
]
设 $bold(P)^(-1) A bold(P) = Lambda = diag(seqn(lb,n))$.考虑对于任意 $m in NN_+$,有:
$
bold(P)^(-1) AA^m bold(P) = (bold(P)^(-1) AA bold(P))^m = Lambda^m = diag(lb_1^m,lb_2^m,dots.c,lb_n^m)
$
对于 $f(x)$ 的每一个单项式 $x^(k_i)$,分别代入 $m=k_i$ 并相加,可以得到:
$
bold(P)^(-1) f(AA) bold(P) = f(Lambda) = diag(f(lb_1),f(lb_2),dots.c,f(lb_n))
$
#warn[我书上的第38题和讲评的第38题似乎不一样.]
= P130 习题五 39 #ac
#prob[
设 $AA=(a_(i j))_(n times n)$ 是一个 $n$ 阶下三角矩阵,证明:
(1) 若 $a_11,a_22,dots.c,a_(n n)$ 互不相等,则 $AA$ 可相似对角化.
]
$
|lambda EE - AA| = (lambda-a_11)(lambda-a_22)dots.c(lambda-a_(n n))
$
故 $lambda_1=a_11,lambda_2=a_22,dots.c,lambda_n=a_(n n)$ 是 $AA$ 的 $n$ 个特征根且两两不同.
考虑到 $|lambda_i EE - AA| = 0$,故有 $r(lambda_i EE - AA)<n$,即 $dim V_(lambda_i) >= 1$,再由 $display(sum_(i=1)^n dim V_(lambda_i))$ 可得
$
dim V_lambda_1=dim V_lambda_2=dots.c=dim V_lambda_n=1
$
故 $AA$ 可被对角化.
#prob[
(2) 若 $a_11 = a_22 = dots.c = a_(n n)$ 且至少一个 $a_(i_0 j_0) != 0$(其中 $i_0>j_0$),则 $AA$ 不可相似对角化.
]
所有特征值相同,设为 $lambda=a_11$,再设 $BB = lambda EE - AA$.由于 $exists a_(i_0 j_0) != 0$(其中 $i_0>j_0$),故 $BB != OO$,即 $r(BB) >= 1$.
所以 $dim W = n - r(BB) < n$,故 $AA$ 不可相似对角化.
= P131 习题五 42 #ac
#prob[
已知矩阵 $AA = display(mat(0,-1,1;2,-3,0;0,0,0))$.
(1) 求 $AA^99$.
]
$
|lambda EE - AA| = lambda(lambda+1)(lambda+2)
$
故 $lambda_1=-2,lambda_2=-1,lambda_3=0$ 为 $AA$ 的三个特征根,求得对应的一组特征向量为:
$
cases(
alpha_1 = display(mat(1,2,0))^TT,
alpha_2 = display(mat(1,1,0))^TT,
alpha_3 = display(mat(3,2,2))^TT,
)
$
取 $display(bold(P) = mat(alpha_1,alpha_2,alpha_3) = mat(
1,1,3;
2,1,2;
0,0,2;
))$ 可得 $bold(P)^(-1) bold(A) bold(P) = Lambda = diag(-2,-1,0)$.那么
$
AA^99 = bold(P) Lambda^99 bold(P)^(-1) = mat(
1,1,3;
2,1,2;
0,0,2;
) mat(
-2^99,0,0;
0,-1,0;
0,0,0;
) mat(
-1,-1,1/2;
2,1,-2;
0,0,1/2;
) = mat(
2^99-2,2^99-1,0;
2^100-2,2^100-1,0;
0,0,0;
)
$
#prob[
(2) 设三阶矩阵 $BB = display(mat(alpha_1,alpha_2,alpha_3))$ 满足 $BB^2 = BB AA$,记 $BB^100 = display(mat(beta_1,beta_2,beta_3))$,将 $beta_1,beta_2,beta_3$ 分别表示为 $alpha_1,alpha_2,alpha_3$ 的线性组合.
]
$
BB^100 &= BB AA^99 = mat(2^99-2) mat(
2^99-2,2^99-1,0;
2^100-2,2^100-1,0;
0,0,0;
)\ &= mat(
(2^99-2) alpha_1 + (2^100-2) alpha_2,
(2^99-1) alpha_1 + (2^100-1) alpha_2,
0,
)
$
即:
$ cases(
beta_1 = (2^99-2) alpha_1 + (2^100-2) alpha_2,
beta_2 = (2^99-1) alpha_1 + (2^100-1) alpha_2,
beta_3 = 0,
) $
= P131 习题五 44 #ac
#prob[
设矩阵 $AA = display(mat(1,0,1;0,2,0;1,0,1))$,矩阵 $BB = (k EE + AA)^2$,其中 $k in RR$,证明:$BB$ 可相似对角化.
]
设 $bold(T) = display(mat(0,0,1;0,1,0;1,0,0))$,则 $AA = EE + bold(T)$.那么
$
BB = (k EE + EE + bold(T))^2 = (k+1)^2 EE + 2(k+1) bold(T) + bold(T)^2 = (k^2+2k+2) EE + 2(k+1) bold(T)
$
设 $t=k+1$,则 $BB = (t^2+1) EE + 2t bold(T)$,考虑
$
|lambda EE - BB| &= |(lambda-1-t^2)EE - 2t bold(T)|\
&= (lambda-1-t^2)(lambda-(t+1)^2)(lambda-1-t^2-(4t^2)/(lambda-1-t^2))\
&= (lambda-(t+1)^2) (lambda^2 - 2(t^2+1) lambda + (t-1)^2)
$
故 $BB$ 有三个不同的特征根,根据类似前面例题的推导,可以得出 $BB$ 可相似对角化.
= P132 习题五 45 #ac
#prob[
证明:如果 $n$ 阶实矩阵 $AA$ 有 $n$ 个正交的特征向量,那么 $AA$ 是一个对称矩阵.
]
将这 $n$ 个特征向量标准化后记为 $seqn(xi,n)$,令 $bold(U) = vecn(xi,n)$,则
$
bold(U)^TT AA bold(U) &= diag(seqn(lambda,n)) = Lambda\
=> bold(U)^TT AA^TT bold(U) &= (bold(U)^TT AA bold(U))^TT = Lambda^TT = Lambda\
$
再由于 $bold(U)$ 可逆,故
$
AA = AA^TT = (bold(U)^TT)^(-1) Lambda bold(U)^(-1)
$
即 $AA$ 是对称矩阵.
= P132 习题五 46 #wa
#prob[
设 $alpha$ 为 $n$ 元单位列向量,则($quad$):
(A) $EE - alpha alpha^TT$ 不可逆;
(B) $EE + alpha alpha^TT$ 不可逆;
(C) $EE + 2alpha alpha^TT$ 不可逆;
(D) $EE - 2alpha alpha^TT$ 不可逆.
]
#warn[不会做.]
= P132 习题五 47 #ac
#prob[
设 $alpha$ 为三元列向量,求矩阵 $EE - alpha alpha^TT$ 的秩.
]
由46题知 $r(EE - alpha alpha^TT)<=2$.
考虑特征根为 $1$ 的解空间 $W_1$,此时 $r(EE - (EE - alpha alpha^TT)) = r(alpha alpha^TT) = 1$,故 $dim W_1 = 3-1=2$.
考虑 $r(EE - alpha alpha^TT)>=dim W_1=2$,夹得 $r(EE - alpha alpha^TT)=2$.
= P132 习题五 52 #ac
#prob[
设 $AA$ 为三阶实对称矩阵,$lb_1,lb_2,lb_3$ 为 $AA$ 的特征值,$xi_1,xi_2$ 为 $AA$ 的分别属于 $lb_1,lb_2$ 的线性无关的特征向量.
(1) 给出求 $AA$ 的属于特征值 $lb_3$ 的全部特征向量的一个方法.
]
首先 $AA in PP^(3 times 3)$,由于 $dim V_(lb_1) + dim_V_lb_2 + dim_V_lb_3 <= 3$,故 $dim_V_lb_3 = 1$ 即 $lb_3$ 只有一个特征向量.
根据实对称矩阵的性质,$xi_3$ 应与 $xi_1,xi_2$ 都正交,可用待定系数法解方程得到.
#prob[
(2) 判断 $c_1 xi_1 + c_2 xi_2$(其中 $c_1,c_2 in RR$)是否为 $AA$ 的属于特征值 $lambda_3$ 的特征向量.
]
应满足 $xi_1,xi_2,xi_3$ 两两正交.
$
(xi_1,c_1 xi_1 + c_2 xi_2) = c_1 (xi_1,xi_1) = 0
(xi_2,c_1 xi_1 + c_2 xi_2) = c_2 (xi_2,xi_2) = 0
$
由于 $xi_1,xi_2,xi_3$ 都非零向量,根据内积的正定性,$(xi_1,xi_1)>0,sp (xi_2,xi_2)>0$,故只能 $c_1=c_2=0$ 而此时 $xi_3 = c_1 xi_1 + c_2 xi_2 = theta$,不能作为特征向量.故综上,这一定不是属于特征值 $lb_3$ 的特征向量.
= P133 习题五 54 #ac
#prob[
设 $AA$ 为实三阶对称矩阵,$r(AA) = 2$,且
$
AA mat(1,1;0,0;-1,1) = mat(-1,1;0,0;1,1)
$
(1) 求 $AA$ 的所有特征值与特征向量.
(2) 求矩阵 $AA$.
]
设 $AA = display(mat(alpha_1^TT;alpha_2^TT;alpha_3^TT))$,代入可得:
$ cases(
alpha_1 - alpha_3 = display(mat(-1,0,1))^TT,
alpha_1 + alpha_3 = display(mat(1,0,1))^TT,
) => cases(
alpha_1 = display(mat(0,0,1))^TT,
alpha_3 = display(mat(1,0,0))^TT,
) $
同时,考虑到 $r(AA) = 2$,故 $alpha_2$ 可被 $alpha_1,alpha_3$ 线性表示.再考虑到 $AA$ 是对称矩阵,故解得
$
AA = mat(0,0,1;0,0,0;1,0,0)
=> |lambda EE - AA| = lambda^2 (lambda-1/lambda) = lambda(lambda-1)(lambda+1)
$
故 $-1,0,1$ 是 $AA$ 的特征值,代入可得对应的特征向量分别为 $display(mat(1,0,-1))^TT,display(mat(0,1,0))^TT,display(mat(1,0,1))^TT$.
= P133 习题五 55 #ac
#prob[
设三阶实对称矩阵 $AA$ 的特征值 $lb_1=1,lb_2=2,lb_3=-2$,且 $alpha_1=display(mat(1,-1,1))^TT$ 是 $AA$ 的属于 $lb_1$ 的一个特征向量,记 $BB = AA^5 - 4 AA^3 + EE$.
(1) 验证 $alpha_1$ 是矩阵 $BB$ 的特征向量,并求 $BB$ 的全部特征值与特征向量.
]
$
BB alpha_1 = (1^5 - 4 dot 1^3 + 1) alpha_1 = -2 alpha_1
$
故 $alpha_1$ 是矩阵 $BB$ 的特征向量,且 $lb'_1=-2$.同理可得 $lb'_2=lb'_3=1$.$1$ 是 $BB$ 的一个二重特征根,其对应的特征向量应与 $display(mat(1,-1,1))^TT$ 正交且线性无关,可取:
$ cases(
alpha_2 = display(mat(1,1,0))^TT,
alpha_3 = display(mat(1,0,-1))^TT
) $
(下省略正交单位化的过程)
#prob[(2) 求矩阵 $BB$.]
取 $bold(P) = display(mat(1,1,0;-1,1,1;1,0,1))$,则
$
bold(P)^(-1) BB bold(P) = Lambda = mat(-2,0,0;0,1,0;0,0,1)\
=> BB = bold(P) Lambda bold(P)^(-1) = mat(
-2,-1,0;2,-1,-1;-2,0,1
) mat(
1/3,-1/3,1/3;
2/3,1/3,-1/3;
-1/3,1/3,2/3
) = mat(
-4/3,1/3,-1/3;
1/3,-4/3,1/3;
-1,1,0;
)
$
= P133 习题五 58 #wa
#prob[
证明:反对称实矩阵的特征值或为零,或为虚部不为零的纯虚数.
]
#warn[
已整理到错题本上.
后面的问题我也整理到纠错本上.
]
= P134 补充题五 5
#prob[
设矩阵 $AA$ 与 $BB$ 相似,试证明:伴随矩阵 $AA^*$ 与 $BB^*$ 也相似.
]
若 $|AA|=|BB|=0$,则伴随矩阵 $AA^* = BB^* = OO$,显然相似.否则 $|AA| = |BB| != 0$.考虑
$
AA AA^* = |AA| EE = |BB| EE = BB BB^* = bold(P)^(-1) AA bold(P) BB^*\
=> bold(P) AA AA^* = AA bold(P) BB^*
=>
$
= P134 补充题五 6
#prob[
设 $AA$ 是一个可逆矩阵,试证明:存在多项式 $f(x)$ 使得 $AA^(-1) = f(AA)$.
]
$
AA^(-1) f(AA) = EE <=> AA^(-1) g(AA) = OO
$
其中 $g(x) = f(x) - x$.由于 $AA$ 是可逆矩阵,应满秩,故应有 $g(AA) = OO$ 即 $g(x)$ 为特征多项式.设 $seqn(lambda,n)$ 为 $AA$ 的特征根,则取
$
f(x) = g(x) + x = (x-lambda_1)(x-lambda_2)dots.c(x-lambda_n) + x
$
即合题意.
= P134 补充题五 8
#prob[
设 $AA,BB$ 均可相似对角化,试证明:$AA,BB$ 乘法可交换当且仅当存在可逆矩阵 $bold(P)$ 使得 $bold(P) AA bold(P)^(-1)$ 与 $bold(P) BB bold(P)^(-1)$ 均为对角矩阵.
]
= P134 补充题五 10
#prob[
设 $AA,BB in PP^(n times n)$,试证明:$AA$ 与 $BB$ 相似的充分必要条件是存在 $bold(C),bold(D) in PP^(n times n)$,使得 $AA = bold(C D)$,$BB = bold(D C)$,且 $bold(C),bold(D)$ 中至少一个可逆.
]
|
|
https://github.com/sysu/better-thesis | https://raw.githubusercontent.com/sysu/better-thesis/main/specifications/bachelor/declaration.typ | typst | MIT License | #import "/utils/style.typ": 字号, 字体
// 学术声明页
// 参照 [中山大学本科生毕业论文(设计)写作与印制规范 2020年发](https://spa.sysu.edu.cn/zh-hans/article/1744) 电子档的示例设置格式
#let declaration() = {
align(center, text(font: 字体.黑体, size: 字号.三号)[学术诚信声明])
set text(font: 字体.宋体, size: 字号.小四)
par(justify: true, first-line-indent: 2em)[
本人郑重声明:所呈交的毕业论文(设计),是本人在导师的指导下,独立进行研究工作所取得的成果。除文中已经注明引用的内容外,本论文(设计)不包含任何其他个人或集体已经发表或撰写过的作品成果。对本论文(设计)的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本论文(设计)的知识产权归属于培养单位。本人完全意识到本声明的法律结果由本人承担。
]
v(2em)
align(right + top,
box(
grid(
columns: (auto, auto),
gutter: 2em,
"作者签名:", "",
"日" + h(2em) + "期:", h(2.5em) + text("年") + h(2em) + text("月") + h(2em) + text("日")
)
)
)
}
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/header/header.typ | typst | = Heading
= Second heading |
|
https://github.com/nyeong/resume | https://raw.githubusercontent.com/nyeong/resume/main/README.md | markdown | # resume
Resume of An Subin.
PDF: https://github.com/nyeong/resume/releases
## Dependencies
- [typst]
- [noto-cjk] - [SIL Open Font License 1.1](https://github.com/notofonts/noto-fonts/blob/main/LICENSE)
[typst]: https://github.com/typst/typst
[noto-cjk]: https://github.com/notofonts/noto-cjk
## Compile
```bash
typst compile main.typ --font-path fonts
```
## Release
Tag a commit and push it.
```bash
git tag v1.0.1
git push origin v1.0.1
```
|
|
https://github.com/OrangeX4/typst-talk | https://raw.githubusercontent.com/OrangeX4/typst-talk/main/README.md | markdown | <p align="center">
<img src="images/typst-talk.png" alt="typst-talk" width=75%>
</p>
## 字体
- **西文字体:** IBM Plex Serif 和 IBM Plex Mono
- **中文字体:** Source Han Serif SC 和 Source Han Sans SC
## PDF 下载
本 PDF 使用 [Touying](https://github.com/touying-typ/touying) 包制作。
- [放映版](https://github.com/OrangeX4/typst-talk/releases/latest/download/typst-talk.pdf)
- [阅读版](https://github.com/OrangeX4/typst-talk/releases/latest/download/typst-talk-handout.pdf)
- [Online](https://orangex4.github.io/typst-talk/)
---
Copyright (C) 2024 by OrangeX4.
|
|
https://github.com/veilkev/jvvslead | https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/9_statuses.typ | typst | #import "../sys/packages.typ": *
#import "../sys/sys.typ": *
#import "../sys/header.typ": *
// Space between header
#v(150pt)
// Shows heading
#text(size: 12pt
)[= Statuses]
|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/appendix.typ | typst | MIT License | #import "../lib/mod.typ": *
// == Appendix <s.appendix>
= Internal External Iteration Schedules <appendix.iteration-schedules>
#listing(
```rust
#[derive(Clone, Copy PartialEq, Eq)]
pub struct GbpScheduleAtIteration {
pub internal: bool,
pub external: bool,
}
#[derive(Clone, Copy)]
pub struct GbpScheduleParams {
pub internal: u8,
pub external: u8,
}
pub trait GbpScheduleIterator: std::iter::Iterator<Item = GbpScheduleAtIteration> {}
pub trait GbpSchedule {
fn schedule(params: GbpScheduleParams) -> impl GbpScheduleIterator;
}
```,
caption: [The schedule for the internal and external message passing iterations modelled by the trait `GbpSchedule`. Every implementor must implement a static method called `schedule(params: GbpScheduleParams)` that returns an iterator of `GbpScheduleAtIteration` structs. The boolean fields `.internal` and `.external` are interpreted such that `true` means that a message pass of that kind should be executed this iteration step.]
)
//
// = Variable Timestep Placement <appendix.variable-timestep-placement>
//
// #listing(
// ```rust
// #[derive(Debug)]
// struct VariableTimestepPlacementParamsError {
// NLessThan2,
// HorizonNotPositive,
// }
//
// impl std::fmt::Display for VariableTimestepPlacementParamsError {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// match self {
// Self::NLessThan2 => write!(f, ""),
// Self::HorizonNotPositive => write!(f, ""),
// }
// }
// }
//
// impl std::error::Error for VariableTimestepPlacementParamsError {}
//
// struct VariableTimestepPlacementParams {
// pub (self) n: usize,
// pub (self) horizon: f32,
// pub (self) lookahead_multiple: NonZeroUsize,
// }
//
// impl VariableTimestepPlacementParams {
// pub fn new(n: usize, horizon: f32) -> Result<Self, VariableTimestepPlacementParamsError> {
// if n < 2 {
// Err()
// } else if horizon <= 0.0 {
// Err()
// } else {
// Ok(Self {
// n,
// horizon,
// lookahead_multiple: 3.try_into().unwrap()
// })
// }
// }
//
// pub fn with_lookahead_multiple(self, lookahead_multiple: NonZeroUsize) -> Self {
// self.lookahead_multiple = lookahead_multiple;
// self
// }
// }
//
// trait VariableTimestepPlacement {
// // provided method
// fn place(params: VariableTimestepPlacementParams) -> Vec<f32> {
// let mut timesteps = vec![0.0; params.n];
// Self::place_into(params, &mut timesteps);
// assert_eq!(0, timesteps[0]);
// assert_eq!(params.horizon, timesteps[params.n - 1]);
// timesteps
// }
//
// /// Guarantees:
// /// `params.n == timesteps.len()`
// fn place_into(params: VariableTimestepPlacementParams, timesteps: &mut[f32]);
// }
// ```,
// caption: [`VariableTimestepPlacement` trait used to provide an interface for placing variable nodes between the current variable $v_0$ and the horizon $v_("horizon")$. The ith index in the vector returned by the `VariableTimestepPlacement::place` is interpreted as the time in seconds the variable should be placed into the future, capped at $t_("horizon")$]
// )
//
= Reproduction Experiment Parameters <appendix.reproduction-experiment-parameters>
#figure(
tablec(
columns: (1fr, 3fr, 1fr),
alignment: (center, left, center),
header: table.header([*Parameter*], [*Description*], [*Unit* / *Domain*]),
[$C_("radius")$], [Radius of the circle that the robots spawn in circle scenarios like @s.r.scenarios.circle], [$m$],
[$r_R$], [Robot radius], [$m$],
[$r_C$], [Robot communication radius], [$m$],
[$|v_0|$], [Initial speed], [$m"/"s$],
[$N_r$], [Number of robots], [$NN_1$],
[$"seed"$], [prng seed], [$NN_0$],
[$delta_t$], [Time passed between each simulation step], [$s$],
[$M_I$], [Internal #acr("GBP") message passing iterations], [$NN_0$],
[$M_E$], [External interrobot #acr("GBP") messages], [$NN_0$],
[$gamma$], [probability for the communication module to be toggled on/off], [$percent$],
[$t_K-1$], [Extend of time horizon. The time it should take for the current variable to reach the horizon variable], [$s$],
[$|V|$], [Number of variables in each factorgraph], [$NN_1 \\ {1}$],
[$sigma_d$], [sigma value of Dynamic factor], [$m$],
[$sigma_p$], [sigma value of Pose factor], [$m$],
[$sigma_i$], [sigma value of interrobot factor], [],
[$sigma_o$], [sigma value of Obstacle factor], [],
[$d_s$], [interrobot safety distance. When two variables connected by a interrobot factor are within this distance, the factor will send factor messages to alternate the course of both robot's path.], [$C_("radius")$],
[$Q_("in")$], [Rate at which robots enter the central section in the Junction scenario (see @s.r.scenarios.junction)], [$"robots""/"s$],
[$Q_("out")$], [Rate at which robots exit the central section in the Junction scenario (see @s.r.scenarios.junction)], [$"robots""/"s$],
[$M_("RRT")$], [Maximum number of iterations for the RRT\* pathfinding algorithm.], [$NN_1$],
[$s$], [Step size for the RRT\* pathfinding algorithm.], [$m$],
[$r_C$], [Collision radius for the RRT\* pathfinding algorithm. [$m$]],
[$r_N$], [Neighbourhood radius for the RRT\* pathfinding algorithm. [$m$]],
// max-iterations: $5000000$,
// step-size: $5.0$,
// collision-radius: $3.0$,
// neighbourhood-radius: $8.0$
),
caption: [Experiment parameters for all reproduction scenarios. See @s.r.scenarios for an writeup of the scenarios.]
) <t.appendix.reproduction-experiment-parameters>
= Interpretation of parameters <appendix.interpretation-of-parameters>
#set par(first-line-indent: 0em)
- $|v_(0)| = v_i = 15 m"/"s$
- $|v_("final")| = v_f = 0 m"/"s$
- $j(t) = (d a(t))/(d t) = 0 m"/"s^3$
- $C_("radius") = 50 m$
- $d = 2 C_("radius") = 100 m$
Use the following equations for velocity and displacement under constant acceleration@essential-university-physics:
$ v_f = v_i + a t $ <equ.kinematic-velocity>
$ d = v_i t + 1/2 a t^2 $ <equ.kinematic-distance>
Isolate $a$ in @equ.kinematic-velocity
#let a = $-15/t m / s$
$ 0 m/s = 15 m/s + a t <=> a = #a $
Substituting $a$ into @equ.kinematic-distance to get:
$
100 m &= 15 m/s t + 1/2 (#a) t^2 \
&= 15 m/s t - 7.5 m/s t \
&= 7.5 m / s t \
&<=> t = (100 m) / (7.5 m / s) = 13 + 1/3 s
$
= Graphviz Representation of FactorGraphs <appendix.graphviz-representation-of-factorgraphs>
Example of outputs generated by the Graphviz integration.
#let colors = (
interrobot: rgb("#95C486"),
dynamic: rgb("#7C9CDC"),
obstacle: rgb("#D68A90"),
tracking: rgb("#DC9151")
)
#let factor-node(c, t) = {
let width = 1.5em
box(rect(fill: c.lighten(30%), stroke: c, width: width, height: width, outset: 0pt, inset: 0.35em, [#t]), baseline: 0.5em)
}
#let variable-node(content) = {
box(circle(stroke: theme.overlay0)[
#set align(center + horizon)
#content
], baseline: 1em)
// box(circle(radius: width, stroke: theme.overlay0, content), baseline: 0.5em)
}
#{
let b(content) = block(
width: 50%,
content
)
set align(center)
grid(
align: left,
columns: 2,
rows: 3,
b[#factor-node(colors.interrobot, $f_i$) interrobot factor],
b[#factor-node(colors.dynamic, $f_d$) dynamic factor],
b[#factor-node(colors.tracking, $f_t$) tracking factor],
b[#factor-node(colors.obstacle, $f_o$) obstacle factor] ,
[#variable-node[$v_n$] variable],
[]
)
}
// #factor-node(colors.interrobot, $f_i$) \
// #factor-node(colors.dynamic, $f_d$) \
// #factor-node(colors.tracking, $f_t$) \
// #factor-node(colors.obstacle, $f_o$)
// #std-block(image("../figures/img/graphviz-export-single-factorgraph.svg", width: 100%))
#figure(
std-block(image("../figures/img/graphviz-export-single-factorgraph.png")),
caption: [
Graphviz representation of a single factorgraph. Circles are variables where $v_0$ is the current variable at the robots position at time $t$, and $v_13$ is the horizon variable.
]
)
#let interrobot-edge(c, n: 3) = {
box(grid(columns: n, column-gutter: 0.25em, ..range(n).map(_ => line(stroke: c, length: 6pt))), baseline: -0.25em)
}
#figure(
std-block(image("../figures/img/graphviz-export-multiple-factorgraphs.png")),
caption: [
Graphviz representation of multiple factorgraphs. Note the position of the variables does not reflect their actual position in the simulation. Red dashed #interrobot-edge(rgb("#d20f39")) edges repreent interrobot edges, where that are disabled due to the radio being turned of on the robot which owns the factor. Green dashed #interrobot-edge(rgb("#40a02b")) edges are active interrobot edges.
]
)
= JSON Schema for exported data <appendix.json-schema-for-exported-data>
#listing(
[
```json
{
"scenario": <string>,
"delta_t": <float>,
"makespan": <float>,
"prng_seed": <int>,
"gpp": {
"iterations": {
"internal": <int>,
"external": <int>
},
},
"robots": {
"robot1": {
"radius": <float>,
"positions": [ [ <float>, <float> ], ... ],
"velocities": [ [ <float>, <float> ], ... ],
"messages": {
"sent": { "internal": <int>, "external": <int> },
"received": { "internal": <int>, "external": <int> }
},
"collisions": { "robots": <int>, "environment": <int> },
"mission": {
"waypoints": [ [ <float>, <float> ], ... ],
"started_at": <float>,
"finished_at": <float> | null,
"routes": [
{
"started_at": <float>,
"finished_at": <float> | null,
"waypoints": [ [ <float>, <float> ], ... ]
},
...
]
},
"planning-strategy": "only-local" | "rtt-star"
"color": <color>
},
"robot2": { ... }
},
"config": <config>
}
```
],
caption: [JSON Schema for exported data. `...` denotes one or more repetitions of the the array or object just before it.],
)
#pagebreak()
== Introspection outputs <appendix.introspection-outputs>
#grid(
rows: 2,
// rows: (1fr, 1fr, 8fr),
// figure(
// scale(x: 100%, y: 60%, std-block(image("../figures/img/introspection-of-robot-robot-collision.png"))),
// caption: [Example output of clicking on an obstacle.]
// ),
grid(
columns: (46.5%, auto),
// columns: (42.5%, auto),
figure(
std-block(image("../figures/img/introspection-of-robot-state.png")),
caption: [Screenshot of output from clicking on a robot.]
),
grid(
rows: 2,
figure(
std-block(image("../figures/img/introspection-of-variable-state.png")),
caption: [Screenshot of output of clicking on a variable.]
),
figure(
std-block(image("../figures/img/introspection-of-variable-state-settings.png")),
caption: [UI settings used when clicked on variable in the output above.]
)
),
),
)
#figure(
block(
breakable: false,
stack(dir: ttb,
std-block(image("../figures/img/introspection-of-collider-state.png", fit: "contain")),
v(0.5em),
std-block(align(left, image("../figures/img/introspection-of-robot-robot-collision.png", fit: "contain"))),
)
),
caption: [
Screenshot of output of clicking on an obstacle and robot robot collision residue.
]
)
#pagebreak()
== #acr("LDJ") Metric computation <appendix.ldj-metric-computation>
#listing(
[```py
import numpy as np
from scipy.integrate import simpson
def ldj(velocities: np.ndarray, timesteps: np.ndarray) -> float:
""" Calculate the Log Dimensionless Jerk (LDJ) metric. """
assert len(velocities) > 0
assert velocities.shape == (len(velocities), 2)
assert len(timesteps) == len(velocities)
assert np.all(np.diff(timesteps) > 0)
assert timesteps.shape == (len(timesteps),)
t_start: float = timesteps[0]
t_final: float = timesteps[-1]
assert t_start < t_final
dt: float = np.mean(np.diff(timesteps))
vx = velocities[:, 0]
vy = velocities[:, 1]
# Estimate acceleration components
ax = np.gradient(vx, dt)
ay = np.gradient(vy, dt)
# Estimate jerk components
jx = np.gradient(ax, dt)
jy = np.gradient(ay, dt)
# Square of the jerk magnitude
squared_jerk = jx**2 + jy**2
time_samples = np.linspace(t_start, t_final, len(velocities))
# Numerical integration of the squared jerk using Simpson's rule
integral_squared_jerk = simpson(squared_jerk, x=time_samples)
# LDJ calculation
v_max = np.max(np.sqrt(vx**2 + vy**2)) # Max speed (magnitude of velocity vector)
ldj = -np.log((t_final - t_start)**3 / v_max**2 * integral_squared_jerk)
return ldj
```],
caption: [
Code used to compute the Log Dimensionless Jerk (LDJ) metric.
The script can also be found in the accompanying source code@repo under #github("AU-Master-Thesis", "gbp-rs", path: "./scripts/ldj.py")
]
)
#pagebreak()
== Perpendicular Path Deviation Metric Code <appendix.perpendicular-path-deviation-metric-code>
#listing([
```py
import collections
import itertools
from dataclasses import dataclass
import numpy as np
def sliding_window(iterable: Iterable, n: int):
"Collect data into overlapping fixed-length chunks or blocks."
# sliding_window('ABCDEFG', 4) → ABCD BCDE CDEF DEFG
iterator = iter(iterable)
window = collections.deque(itertools.islice(iterator, n - 1), maxlen=n)
for x in iterator:
window.append(x)
yield tuple(window)
@dataclass
class Line:
a: float
b: float
def line_from_line_segment(x1: float, y1: float, x2: float, y2: float) -> Line:
a = (y2 - y1) / (x2 - x1)
b = y1 - (a * x1)
return Line(a=a, b=b)
def projection_onto_line(point: np.ndarray, line: Line) -> np.ndarray:
assert len(point) == 2
x1, y1 = point
xp: float = (x1 + line.a * (y1 - line.b)) / (line.a * line.a + 1)
projection = np.array([xp, line.a * xp + line.b])
assert len(projection) == 2
return projection
def closest_projection(point: np.ndarray, lines: list[Line]) -> np.ndarray:
assert len(point) == 2
projections = [projection_onto_line(point, line) for line in lines]
closest_projection = min(projections, key=lambda proj: np.linalg.norm(proj - point))
return closest_projection
lines: list[Line] = [
line_from_line_segment(*start, *end) for start, end in sliding_window(waypoints, 2)
]
closest_projections: list[np.ndarray] = [
closest_projection(point, lines) for point in positions
]
error: float = np.sum(np.linalg.norm(positions - closest_projections, axis=1))
rmse: float = np.sqrt(error / len(positions))
```
],
caption: [
Code used to compute the Perpendicular Path Deviation Metric.
The script can also be found in the accompanying source code@repo under
#source-link("https://github.com/AU-Master-Thesis/gbp-rs/blob/main/scripts/perpendicular-path-deviation.py", "./scripts/perpendicular-path-deviation.py")
// #github("AU-Master-Thesis", "gbp-rs", path: "./scripts/perpendicular-path-deviation.py")
]
)
#pagebreak()
// == Perpendicular Path Deviation Metric Code <appendix.perpendicular-path-deviation-metric-code>
== Visualization Modules <appendix.visualization-modules>
// #let edges = (
// on: box(line(length: 10pt, stroke: theme.green), height: 0.25em),
// off: box(line(length: 10pt, stroke: theme.red), height: 0.25em),
// )
//
// #figure(
// tablec(
// columns: 2,
// align: left,
// header: table.header(
// [Settings], [Description]
// ),
// [Robots], table.vline(), [A large sphere at the estimated position of each robot.],
// [Communication graph], [A graph that shows an edge between all currently communicating robots. Each edge is colored dependent on the robots radio state. If the antenna is active then half of the edge from the robot to the center is green#sg, and red#sr if turned off. For three robots $R_a, R_b, R_c$, this could look like
//
// #align(center, [$R_a$ #edges.on #edges.off $R_b$ #edges.off #edges.off $R_c$])
// ],
// [Predicted trajectories], [All of each robot's factor graph variables, visualised as small spheres with a line between.],
// [Waypoints], [A small sphere at each waypoint for each robot.],
// [Uncertainty], [A 2D ellipse for each variable in each robot's factor graph, visualising the covariance of the internal Gaussian belief.],
// [Paths], [Lines tracing out each robot's driven path.],
// [Generated map], [A 3D representation of the map generated from the environment configuration.],
// [Signed distance field], [The 2D #acr("SDF") image used for collision detection. White#swatch(white) where the environment is free, black#swatch(black) where it is occupied.],
// [Communication radius], [A circle around each robot representing the communication radius. The circle is teal#stl when the radio is active, and red#sr when it is inactive.],
// [Obstacle factors], [A line from each variable to the linearization point of their respective obstacle factors, and a circle in this point. Both the line and circle is colors according to the factor's measurement on a green#sg to yellow#sy to red#sr gradient; #gradient-box(theme.green, theme.yellow, theme.red).],
// [Tracking], [The measurement of the tracking factors and the line segments between each waypoint, that are being measured.],
// [Interrobot factors], [Two lines from each variable in one robot to each variable in another robot if they are currently communicating, and within the safety distance threshold $d_r$ of each other. The color varies on a yellow #sy to #sr gradient #gradient-box(theme.yellow, theme.red) visually highlighting the potential of a future collision.
// // The line is green#sg if the communication is active in that direction, and grey#sgr3 if it is inactive.
// ],
// [Interrobot factors safety distance], [A circle around each variable, visualization the internally used safety distance for the interrobot factors. orange #so when communication is enabled and gray#sgr3 when disabled.],
// [Robot colliders], [A sphere in red#sr around each robot representing the collision radius.],
// [Environment colliders], [An outline in red#sr around each obstacle in the environment, that collision are being detected against.],
// [Robot-robot collisions], [An #acr("AABB") intersection, visualising each robot to robot collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
// [Robot-environment collisions], [An #acr("AABB") intersection, visualising each robot to environment collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
// ),
// caption: [
// Every visualizable setting, and a description of how it has been chosen to visualise it.
// ]
// )
// <table.simulation-visualizations>
// #let s(x, y, img) = scale.with(x: x, y: y, img)
//
// #figure(
// scale(x: 80%, y: 80%, image("../figures/img/visualizer-generated-map.png")),
// caption: [Generated map from `environment.yaml`]
// ) <appendix.visualizer-generated-map>
//
// #figure(
// scale(x: 80%, y: 80%, image("../figures/img/visualizer-sdf.png")),
// caption: [Generated #acr("SDF") from `environment.yaml`]
// ) <appendix.visualizer-sdf>
//
// == Perpendicular Path Deviation Metric Code <appendix.perpendicular-path-deviation-metric-code>
// == Visualisation Modules <appendix.visualisation-modules>
A screenshot of each visualization module presented in @s.m.visualization is listed below. See @table.simulation-visualizations for a detailed description of each module.
// #let edges = (
// on: box(line(length: 10pt, stroke: theme.green), height: 0.25em),
// off: box(line(length: 10pt, stroke: theme.red), height: 0.25em),
// )
//
// #figure(
// tablec(
// columns: 2,
// align: left,
// header: table.header(
// [Settings], [Description]
// ),
// [Robots], table.vline(), [A large sphere at the estimated position of each robot.],
// [Communication graph], [A graph that shows an edge between all currently communicating robots. Each edge is colored dependent on the robots radio state. If the antenna is active then half of the edge from the robot to the center is green#sg, and red#sr if turned off. For three robots $R_a, R_b, R_c$, this could look like
//
// #align(center, [$R_a$ #edges.on #edges.off $R_b$ #edges.off #edges.off $R_c$])
// ],
// [Predicted trajectories], [All of each robot's factor graph variables, visualised as small spheres with a line between.],
// [Waypoints], [A small sphere at each waypoint for each robot.],
// [Uncertainty], [A 2D ellipse for each variable in each robot's factor graph, visualising the covariance of the internal Gaussian belief.],
// [Paths], [Lines tracing out each robot's driven path.],
// [Generated map], [A 3D representation of the map generated from the environment configuration.],
// [Signed distance field], [The 2D #acr("SDF") image used for collision detection. White#swatch(white) where the environment is free, black#swatch(black) where it's occupied.],
// [Communication radius], [A circle around each robot representing the communication radius. The circle is teal#stl when the radio is active, and red#sr when it's inactive.],
// [Obstacle factors], [A line from each variable to the linearisation point of their respective obstacle factors, and a circle in this point. Both the line and circle is colours according to the factor's measurement on a green#sg to yellow#sy to red#sr gradient; #gradient-box(theme.green, theme.yellow, theme.red).],
// [Tracking], [The measurement of the tracking factors and the line segments between each waypoint, that are being measured.],
// [Interrobot factors], [Two lines from each variable in one robot to each variable in another robot if they are currently communicating, and within the safety distance threshold $d_r$ of each other. The color varies on a yellow #sy to #sr gradient #gradient-box(theme.yellow, theme.red) visually highlighting the potential of a future collision.
// // The line is green#sg if the communication is active in that direction, and grey#sgr3 if it's inactive.
// ],
// [Interrobot factors safety distance], [A circle around each variable, visualisation the internally used safety distance for the interrobot factors. orange #so when communication is enabled and gray#sgr3 when disabled.],
// [Robot colliders], [A sphere in red#sr around each robot representing the collision radius.],
// [Environment colliders], [An outline in red#sr around each obstacle in the environment, that collision are being detected against.],
// [Robot-robot collisions], [An #acr("AABB") intersection, visualising each robot to robot collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
// [Robot-environment collisions], [An #acr("AABB") intersection, visualising each robot to environment collision and its magnitude. Shown as semi-transparent cuboids in red#sr.],
// ),
// caption: [
// Every visualisable setting, and a description of how it has been chosen to visualise it.
// ]
// )
// <table.simulation-visualisations>
#let s(x, y, img) = scale.with(x: x, y: y, img)
#let (x, y) = (90%, 90%)
=== Robots
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-robots.png")),
caption: [A sphere visualization for each robot.]
) <appendix.visualizer-robots>
#pagebreak()
=== Communication Graph
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-communication-graph.png")),
caption: [Communication graph between robots]
) <appendix.visualizer-communication-graph>
=== Trajectories
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-trajectories.png")),
caption: [Variable of each robots factorgraph, outlining the planned path at the current timestep.]
) <appendix.visualizer-trajectories>
=== Waypoints
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-waypoints.png")),
caption: [Each waypoint is shown as sphere, and then a traced path between them.]
) <appendix.visualizer-waypoints>
=== Uncertainty
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-uncertainty.png")),
caption: [The uncertainty about each variables estimated position. Based on its covariance matrix belief.]
) <appendix.visualizer-uncertainty>
=== Paths
#figure(
scale(x: x, y: y, image(height: 45%, "../figures/img/visualizer-paths.png")),
caption: [The travelled path of each robot is traced as a line, with a color similar to the robots.]
) <appendix.visualizer-paths>
=== Communication Radius
#figure(
scale(x: x, y: y, image(height: 35%, "../figures/img/visualizer-communication-radius.png")),
caption: [Communication radius of a robot. The circle is teal#stl when the radio is active, and red#sr when it's inactive.]
) <appendix.visualizer-communication-radius>
=== Obstacle Factors
#figure(
scale(x: x, y: y, image("../figures/img/obstacle-factors-example-with-variables.png")),
caption: [Obstacle factors are visualized as a line from the variable to the lineraisation point that the obstacle measures the #acr("SDF") in. At the lineraization point a circle perimeter is shown. The color varies from #gradient-box(theme.green, theme.yellow, theme.red) with red#sr representing a sample directly into a static obstacle.]
) <appendix.visualizer-obstacle-factors>
#pagebreak()
=== Tracking
// #v(-3em)
#figure(
v(-25mm) + rotate(270deg, scale(x: 80%, y: 80%, image("../figures/img/visualizer-tracking.png"))) + v(-25mm),
caption: [The projections used by tracking factors.]
) <appendix.visualizer-tracking>
#pagebreak()
=== Interrobot Factors
#figure(
scale(x: x, y: y, image(height: 45%, "../figures/img/visualizer-interrobot-factors.png")),
caption: [Active interrobot factors between two robots.]
) <appendix.visualizer-interrobot-factors>
=== Interrobot Factors Safety Distance
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-interrobot-factors-safety-distance.png")),
caption: [The radial safety distace $d_s$ of each interrobot factor. orange#so when communication is enabled and gray#sgr3 when disabled.]
) <appendix.visualizer-interrobot-factors-safety-distance>
=== Robot Colliders
#figure(
scale(x: x, y: y, image(height: 45%, "../figures/img/visualizer-robot-collider.png")),
caption: [Visual indication of the spherical volume used by robots for collision detection.]
) <appendix.visualizer-robot-colliders>
=== Environment Colliders
#figure(
scale(x: x, y: y, image(height: 40%, "../figures/img/visualizer-environment-collider.png")),
caption: [Visual indication of the polygonal volume used by the environment for collision detection.]
) <appendix.visualizer-environment-colliders>
=== Robot-robot Collisions
#figure(
scale(x: x, y: y, image("../figures/img/visualizer-robot-robot-collisions.png")),
caption: [An afterimage of collisions between robots. The shape of the box is based on the intersected volumes #acr("AABB").]
) <appendix.visualizer-robot-robot-collisions>
=== Robot-environment Collisions
#figure(
scale(x: x, y: y, image(height: 40%, "../figures/img/visualizer-robot-environment-collisions.png")),
caption: [An afterimage of collisions between robots and the environment. The shape of the box is based on the intersected volumes #acr("AABB").]
) <appendix.visualizer-robot-environment-collisions>
=== Generated Map
#figure(
image("../figures/img/visualizer-generated-map.png"),
caption: [Generated map from `environment.yaml`]
) <appendix.visualizer-generated-map>
=== SDF
#figure(
image("../figures/img/visualizer-sdf.png"),
caption: [Generated #acr("SDF") from `environment.yaml`]
) <appendix.visualizer-sdf>
// #s(80%, 80%, image("../figures/img/visualizer-sdf.png"))
// #s(80%, 80%, image("../figures/img/visualizer-generated-map.png"))
= Individual Contributions <appendix.contributions>
#let a = [(#sym.checkmark)]
#let r = sym.checkmark
#let hcell(body) = table.cell(colspan: 3, fill: theme.text.lighten(30%), text(white, weight: 900, body))
#figure(
tablec(
columns: (auto, 20mm, 20mm),
alignment: (x, y) => (left, center, center).at(x) + horizon,
header: table.header(
[Area], [JHJ], [KPBS]
),
table.hline(),
hcell[GBP],
// table.hline(),
[Reimplementation], table.vline(), a, r,
[Iteration Schedules], [], r,
[Iteration Amount], [], r,
table.hline(),
hcell[MAGICS],
// table.hline(),
[Architecture], a, r,
[Simulation Framework], r, a,
[Visualization], r, r,
[GUI], r, a,
table.hline(),
hcell[Configuration],
// table.hline(),
[Environment Configuration & Generation], r, [],
[Formation Configuration], a, r,
table.hline(),
hcell[Global Pathfinding Layer],
// table.hline(),
[Global Pathfinding with RRT\*], r, a,
[Tracking Factor Design & Integration], r, [],
),
caption: [Contributions of each author to the project. JHJ = <NAME>, KPBS = <NAME>, and #r = responsible, #a = assisted. However, there have been more overlaps, as it has been a collaborative effort.]
)<t.appendix.contributions>
|
https://github.com/fsr/rust-lessons | https://raw.githubusercontent.com/fsr/rust-lessons/master/src/lesson6.typ | typst | #import "slides.typ": *
#show: slides.with(
authors: ("<NAME>", "<NAME>"), short-authors: "H&A",
title: "Wer rastet, der rostet",
short-title: "Rust-Kurs Lesson 6",
subtitle: "Ein Rust-Kurs für Anfänger",
date: "Sommersemester 2023",
)
#show "theref": $arrow.double$
#show link: underline
#new-section("collections")
#slide(title: "collections")[
#columns(2)[
#begin(1)[
- rust library with `Vec`, `HashMap`, `BTree...`
- include with `use`
]
#begin(2)[
- when to use which?
1. study computer science
2. see here: https://doc.rust-lang.org/std/collections/
- how to use each?
]
#colbreak()
#begin(1)[
```rust
use std::collections::Vec;
use std::collections::HashMap;
```
]
#begin(2)[
```rust
// empty vector of u32 values
let numbers = Vec::<u32>::new();
// initialize with values
let names = HashMap::<u32, &str>::from([
(1, "one"),
(2, "two"),
(3, "three"),
]);
// macros, equivalent to Vec::from(...)
let numbers = vec![1, 2, 3];
```
]
]
]
#slide(title: "Vectors")[
#columns(2)[
- an array that can grow (and shrink)
- stores objects of one type (even your own struct/enum)
- create with `Vec::new();`, `vec![];`
- access at the end: `v.push()`, `v.pop()`
- access anywhere: `v.get(i)` != `&v[i]`
- `.get(i)` does bounds check `0 <= i < v.len()`
#colbreak()
#alternatives[
```rust
let v = Vec::new();
let v = vec![1, 2, 3];
v.push(4);
let last = v.pop();
let last = v.pop();
// what’s in last?
```][```rust
let v: Vec<u32> = Vec::new();
let mut v = vec![1, 2, 3];
v.push(4); // add a 4 to the end
let last = v.pop().unwrap(); // 3
let last = v.pop().unwrap(); // 4
// .pop() returns an Option,
// either Some(...) or None
```]
]
]
#slide(title: "Iterating over Vector")[
#alternatives[
```rust
let vec: Vec<u32> = vec![1, 2, 3];
for n in vec.iter() {
println!("{}", n);
}
for n in vec.iter_mut() {
n += 1;
println!("{}", n);
}
for n in vec.into_iter() {
println!("{}", n);
}
```][
```rust
let mut vec: Vec<u32> = vec![1, 2, 3];
for n in vec.iter() {
println!("{}", *n);
}
for n in vec.iter_mut() {
*n += 1;
println!("{}", *n);
}
for n in vec.into_iter() {
println!("{}", n);
} // vec is gone now
```][
```rust
let mut vec: Vec<u32> = vec![1, 2, 3];
for n in &vec {
println!("{}", *n); // n is also fine
}
for n in &mut vec {
*n += 1; // *n needed here!
println!("{}", *n); // works without *
}
for n in vec.into_iter() {
println!("{}", n);
} // vec is gone now
```]
]
#slide(title: "Task 'fibonacci'")[
#begin(1)[- implement the fibonacci series]
#begin(2)[- `fib(n) := n if n < 2 else fib(n-1) + fib(n-2)`]
#begin(3)[- why is this inefficient?]
#begin(4)[- use a `HashMap` (global or passed into `fib(n, map)`)]
]
#slide(title: "Task 'polynomial'")[
#begin(1)[- implement a `struct Polynomial`]
#begin(2)[- `[1 3 5]` is x² + 3x + 5]
#begin(2)[- `[2 4]` is 2x + 4]
#begin(3)[- use `Vec::<u32>` internally]
#begin(4)[```rust
fn main() {
let poly = Polynomial::from([1, 3, 5]);
let moly = Polynomial::from([2, 4]);
println!("poly: {:?}", poly); // #[derive(Debug)]
println!("moly: {:?}", moly);
println!("p+m: {:?}", &poly + &moly); // impl Add for &Polynomial {...
println!("m+p: {:?}", &moly + &poly);
}
```]
]
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test baseline.
A #box(image("/assets/files/tiger.jpg", height: 1cm, width: 80%)) B
|
https://github.com/jerrita/CQUPTypst | https://raw.githubusercontent.com/jerrita/CQUPTypst/master/template/abstract.typ | typst | #import "font.typ": *
#let abstemp(
mode: "",
abstract: [],
keywords: [],
) = {
align(center)[
#heading(
outlined: false,
numbering: none,
text(fs_2, weight: "black")[
#if mode == "cn" {"摘 要"}
else {"ABSTRACT"}
]
)
]
par(first-line-indent: 2em)[
#text(fs_l4, abstract)
]
text(fs_l4, weight: "black")[
#linebreak()
#if mode == "cn" {
"关键词:"
} else {
"Keywords: "
}
]
text(fs_l4, keywords)
pagebreak()
}
|
|
https://github.com/rabotaem-incorporated/probability-theory-notes | https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/sections/02-general/04-expected-value-and-variance.typ | typst | #import "../../utils/core.typ": *
== Математическое ожидание и дисперсия
#def[
Пусть $xi$ --- случайная величина такая, что $xi >= 0$ или $xi$ --- суммируемая функция. _Математическим ожиданием_ или _средним значением случайной величины_ $E xi$ называется
$
E xi = integral_Omega xi (omega) dif P(omega).
$
]
#props[
1. $E xi = integral_RR x dif P_xi (x)$.
2. Линейность#footnote[как обычно нужны оговорки про то, что мы должны уметь вычитать, иначе можем из бесконечности вычесть бесконечность и умереть]: $E (a xi + b eta) = a E xi + b E eta$.
3. Если $xi >= 0$, то $E xi >= 0$.
4. Если $xi <= eta$, то $E xi <= E eta$.
5. $f: RR^n --> R$ измерима относительно борелевской $sigma$-алгебры. Тогда
$ E f(xi_1, xi_2, ..., xi_n) = integral_(RR^n) f(x_1, ..., x_n) dif P_(arrow(xi)) (arrow(x)). $
]
#proof[
Доказываем свойство 5, потому что 1 --- частный случай 5, а остальные очевидны.
*Шаг 1*. Пусть $f = bb(1)_A$. Тогда
$
E bb(1)_A (arrow(xi)) =
P(arrow(xi) in A) =
P_(arrow(xi)) (A) =
integral_(RR^n) bb(1)_A (x) dif P_(arrow(xi)) (x).
$
*Шаг 2*. По линейности верно для простых.
*Шаг 3*. Если $f >= 0$, возьмем последовательность простых $f_1 <= f_2 <= ...$.
$
integral_Omega f (arrow(xi) (omega)) dif P(omega) <--
integral_Omega f_n (arrow(xi) (omega)) dif P(omega) =
E(f_n (arrow(xi))) =
integral_(RR^n) f_n (arrow(x)) dif P_(arrow(xi)) (arrow(x)) -->
integral_(RR^n) f (arrow(x)) dif P_(arrow(xi)) (arrow(x)).
$
*Шаг 4*. $f = f_+ - f_-$ и готово.
]
#props[
6. Если $xi$ и $eta$ независимы, то $E(xi eta) = E xi dot E eta$.
]
#proof[
$
E(xi eta) =
integral_(RR^2) x y dif P_(xi, eta) (x, y) =
integral_(RR^2) x y dif P_xi (x) dif P_eta (y) =
integral_RR x dif P_xi (x) integral_RR y dif P_eta (y) =
E xi dot E eta.
$
]
#props[
7. При $xi >= 0$, $E xi = integral_0^(+oo) P (xi >= t) dif t = integral_RR x dif P_(xi) (x)$.
8. _Неравентсво Гельдера_: $ E (xi eta) <= (E xi^p)^(1/p) (E eta^q)^(1/q), $ где $1/p + 1/q = 1$ и $p, q >= 1$.
9. _Неравентсво Ляпунова_: при $0 < r < s$,
$
(E abs(xi)^r)^(1/r) <= (E abs(xi)^s)^(1/s).
$
]
#proof[
7. Очевидно.
8. Уже доказывали на матане.
9. Пусть $eta = 1$, $p = s/r$. Тогда
$
E (abs(xi)^r dot 1) <= (E abs(xi)^(r p))^(1/p) dot (E 1^q)^(1/q) = (E abs(xi)^s)^(r/s).
$
]
#follow(name: "неравенство Маркова (неравенство Чебышева из матана (не путать с неравенством Чебышева из теорвера (это неравенство там называется неравенством Маркова, то есть вот этим, а это другое)))")[
Пусть $xi >= 0$ и $p, t > 0$. Тогда
$
P(xi >= t) <= (E xi^p) / t^p.
$
]
#notice[
$E (xi eta) = E xi dot E eta$ может быть неверно без независимости. Например, если $xi = plus.minus 1$ с вероятностями $1/2$, то $E xi = 0$, а $E xi xi = 1 != E xi dot E xi$.
]
#def[
_Медианой случайной величины_ $xi$ называется число $m$ такое, что
$
P(xi >= m) >= 1/2 "и " P(xi <= m) >= 1/2.
$
]
#notice[
Медиана не единственна. Например, если $xi$ --- результат подбрасывания правильного кубика, то медиана $xi$ --- любое число на отрезке $[3, 4]$.
Обычно, если медиана не единственна, выбирают середину отрезка (понятно, что множество всех медиан всегда является отрезком).
]
#notice[
Если $F$ --- функция распределения $xi$, то медиана $xi$ --- это $F^(-1)(1/2)$. Если в $1/2$ функция не обратима, то медиана --- любое число вокруг, а если $F$ непрерывна, то медиана --- единственна.
]
#example[
Пусть у нас есть _контора_, в которой работает 1000 человек. В ней 999 человек получают \$1000, и есть начальник, который получает \$1000000. Тогда если равновероятно выбрать случайного человека в конторе и рассмотреть его зарплату $xi$, то
$
E xi &= 999/1000 * 1000 + 1/1000 * 10^6 = 999 + 1000 = 1999.\
m xi &= 1000.
$
Понятно, что для типичного работяги $E xi$ не отражает ситуацию, потому что большинство людей получают мало, а один человек получает очень много. Поэтому в таких ситуациях лучше смотреть на медиану.
]
#def[
_Дисперсия случайной величины_, $D xi$ или $op("Var") xi$, это
$
D xi = E (xi - E xi)^2.
$
]
#props[
1. $D xi >= 0$, и $D xi = 0$ тогда и только тогда, когда $xi = a$ почти наверное.
2. $D xi = E xi^2 - (E xi)^2$.
3. $D(xi + c) = D xi$.
4. $D(c xi) = c^2 D xi$, и в частности, $D xi = D(-xi)$.
5. Если $xi$ и $eta$ независимы, то $D(xi + eta) = D xi + D eta$.
6. Если $xi_1, xi_2, ..., xi_n$ попарно независимы, то $D(xi_1 + xi_2 + ... + xi_n) = D xi_1 + D xi_2 + ... + D xi_n$.
7. $E abs(xi - E xi) <= sqrt(D xi)$.
]
#proof[
Пусть $a = E xi$.
1. Очевидно, $D xi = E (xi - a)^2 >= 0$.
2. $D_xi = E(xi - a)^2 = E xi^2 - 2 a E xi + a^2 = E xi^2 - a^2$.
3. $D(xi + c) = E (xi + c - a - c)^2 = E (xi - a)^2 = D xi$.
4. $D(c xi) = E (c xi - c a)^2 = c^2 E (xi - a)^2 = c^2 D xi$.
5. $D(xi + eta) = E(xi + eta)^2 - (E(xi + eta))^2 = E xi^2 + 2E(xi eta) + E eta^2 - (E xi)^2 - 2E xi E eta - (E eta)^2 = E xi^2 + E eta^2 - (E xi)^2 - (E eta)^2 = D xi + D eta$.
6. Аналогично.
7. $E abs(xi - E xi) <= sqrt(E abs(xi - E_xi)^2)$ (неравентсво Ляпунова).
]
#th(name: "<NAME> (не путать с неравентсвом Чебышева из матана, где оно про другое (а в теорвере это неравентсво Маркова (и вот это неравенство Чебышева из матана (не путать с этим неравенством Чебышева из теорвера (это неравенство там называется неравенством Маркова, а это из него следует))))")[
Для любого $t > 0$ верно
$
P(abs(xi - E xi) >= t) <= (D xi) / t^2.
$
]
#proof[
$
P(abs(xi - E xi) >= t) <=^"Марков" (E abs(xi - E xi)^2)/t^2 = (D xi) / t^2.
$
]
#examples[
1. $xi sim U[0, 1]$
$
E xi &= integral_RR x dif P_xi (x) = integral_0^1 x dif x = lr(x^2/2 |)_0^1 = 1/2,\
E xi^2 &= integral_0^1 x^2 dif x = lr(x^3/3 |)_0^1 = 1/3,\
D xi &= E xi^2 - (E xi)^2 = 1/3 - 1/4 = 1/12.
$
2. $xi sim U[a, b]$. Знаем, что если $eta sim [0, 1]$, то $xi = (b - a)eta + a sim U[a, b]$.
$
E xi = E ((b - a)eta + a) = (b - a)E eta + a = (b - a)/2 + a = (a + b)/2,\
D xi = D ((b - a)eta + a) = (b - a)^2 D eta = (b - a)^2/12.
$
3. $xi sim Nn(0, 1)$.
$
E xi =&
integral_RR x dif P_xi (x) =
1/sqrt(2pi) integral_RR x e^(-x^2/2) dif x = 0,\
D xi =&
E xi^2 =
1/sqrt(2pi) integral_RR x^2 e^(-x^2/2) dif x =
1/sqrt(2pi) (lr(-x e^(-x^2/2)|)_(-oo)^(+oo) + integral_RR e^(-x^2/2) dif x) newline(=) &1/sqrt(2pi) (0 + integral_RR e^(-x^2/2) dif x) = 1/sqrt(2pi) sqrt(2pi) = 1.
$
Храбров базу на лекции выдал: интеграл который получается на последней строчке можно не считать, так как это плотность какого-то распределения, и она просто равна $1$.
4. $xi sim Nn(a, sigma^2)$. Знаем, что если $nu sim Nn(0, 1)$, то $xi = a + sigma nu sim Nn(a, sigma^2)$.
$
E xi = E (a + sigma nu) = a + sigma E nu = a,\
D xi = D (a + sigma nu) = sigma^2 D nu = sigma^2.
$
]
#def[
_Моменты случайных величин_:
- $E xi^p$ --- _$p$-й момент случайной величины_.
- $E abs(xi)^p$ --- _$p$-й абсолютный момент_.
- $E (xi - E xi)^p$ --- _$p$-й центральный момент_.
- $E abs(xi - E xi)^p$ --- _$p$-й абсолютный центральный момент_.
В частности, $D xi$ --- второй центральный момент.
]
#def[
_Ковариацией_ случайных величин $xi$ и $eta$ называется
$
cov (xi, eta) = E (xi - E xi) (eta - E eta).
$
Здесь необходимо, чтобы интеграл под математическим ожиданием существовал. В отличие от дисперии, где он в худшем случае бесконечность, здесь он может быть и неопределен.
]
#props[
1. $cov(xi, xi) = D xi$.
2. $cov(xi + c, eta) = cov(xi, eta)$.
3. $cov(c xi, eta) = c cov(xi, eta)$.
4. $cov(xi_1 + xi_2, eta) = cov(xi_1, eta) + cov(xi_2, eta)$.
5. $cov(xi, eta) = E (xi eta) - E xi dot E eta$.
6. Если $xi$ и $eta$ независимы, то $cov(xi, eta) = 0$. Обратное не верно.
7. $D(xi + eta) = D xi + D eta + 2 cov (xi, eta)$.
8. $D(sum_(k = 1)^n xi_k) = sum_(i = 1)^n sum_(j = 1)^n cov(xi, eta) = sum_(k = 1)^n D xi_k + 2 sum_(i < j) cov(xi_i, xi_k)$.
]
#proof[
Все очев.
5. Если $a = E xi$, $b = E eta$, то $cov(xi, eta) = E (xi - a) (eta - b) = E (xi eta) - a E eta - b E xi + a b = E(xi eta) - a b$.
]
#notice[
В 6-м свойстве обратное не верно. Пусть $Omega = {0, pi/2, pi}$, с вероятностями по $1/3$. Рассмотрим $xi(omega) = sin omega$, $eta(omega) = cos omega$. Тогда
$
E eta &= (1 + 0 + (-1))/3 = 0,\
E xi eta &= (0 + 0 + 0)/3 = 0,\
E xi &= (0 + 1 + 0)/3 = 1/3,\
cov (xi, eta) &= E xi eta - E xi E eta = 0 - 0 = 0.
$
Однако независимости нет. Например, $P(xi = 1, eta = 1) = 0$, но $P(xi = 1) P(eta = 1) = 1/9$.
]
#def[
_Коэффициент корреляции_ случайных величин $xi$ и $eta$ --- это
$
rho (xi, eta) = (cov (xi, eta) )/ (sqrt(D xi) sqrt(D eta)).
$
Здесь требуется, чтобы дисперсии были положительными и конечными.
]
#notice[
$rho(xi, eta) in [-1, 1]$, так как
$
abs(cov(xi, eta)) = abs(E (xi - E xi) (eta - E eta)) <= E abs(xi - E xi) abs(eta - E eta) <= sqrt(D xi) sqrt(D eta).
$
]
#def[
Если $rho(xi, eta) = 0$ (или, что то же самое, $cov(xi, eta) = 0$), то $xi$ и $eta$ называют _некоррелированными_. Иногда в задачах требуют это свойство, так как оно слабее независимости.
]
#exercise[
Доказать, что если $rho(xi, eta) = 1$, то $xi$ и $eta$ --- линейно зависимы, то есть $eta = a xi + b$ почти наверное для некоторых $a, b in RR$, причем $a >= 0$.
]
#example(name: "Выбор двудольного подграфа")[
Пусть $G = (V, E)$ --- граф из $n$ вершин и $m$ ребер. Тогда можно стереть не более $m/2$ ребер так, что останется двудольный подграф.
]
#proof[
Рассмотрим схему Бернулли на вершинах. Если успех, то отправляем вершину в одну долю ($T$), иначе в другую ($V without T$). Рассмотрим $xi_(x y) = 0$ если $x$ и $y$ из разных долей, и $1$ иначе. Пусть
$
xi = sum_(x y in E) xi_(x y)
$
--- количество ребер внутри долей $T$ и $V without T$. Тогда матожидание $xi$:
$
E xi = sum_(x y in E) E xi_(x y) = sum_(x y in E) P(xi_(x y) = 1) = sum_(x y in E) P(x "и " y "в одной доли") = sum_(x y in E) 1/2 = m/2.
$
Значит, есть реализация, в которой $xi <= m/2$.
]
#exercise[
Доказать, что если $n$ четно, то сущесвует такой выбор долей, что ребер между ними хотя бы $(m n)/(2 (n - 1))$.
]
#notice[
Геометрический смысл происходящего.
Рассмотрим случайные величины с конечным вторым моментом. Тогда
1. $E (xi eta) =: dotp(xi, eta)$ --- скалярное произведение. Едиснтвенное, надо отождествить равные почти наверное случайные величины, иначе из того, что скалярное произведение величины с собой не обязательно следует то, что она равна $0$.
Матожидание тогда --- проекция на ось констант. Действительно, $dotp(xi - E xi, a) = a E(xi - E xi) = 0$
2. $cov(xi, eta) =: dotp(xi, eta)$ --- тоже скалярное произведение. Единственное, надо отождествить случайные величины отличающиеся на константу почти наверное (так как для таких случайных величин не следует, что они равны). Тогда $sqrt(D xi)$ --- норма.
]
#th(name: "Харди-Рамануджана")[
Пусть $nu(k)$ --- количество различных простых в разложении $k$ на простые множители.
$
1/n \#{k: abs(nu(k) - ln ln n) >= omega(n) sqrt(ln ln n)} = P(abs(nu(k) - ln ln n) >= omega(n) sqrt(ln ln n)) -->_(n->oo) 0,
$
где $omega(n) arrow.tr +oo$ произвольная, $Omega = {1, 2, ..., n}$.
]
#proof[
Пусть $M := root(5, n)$. Пусть $xi(k)$ --- количество различных простых $<= M$ в разложении $k$. Тогда $nu(k) - 4 <= xi(k) <= nu(k)$, так как если простых больше $M$ --- хотя бы 5, то их произведение больше $n$. Будем смотреть на $xi(k)$, а не $nu(k)$, так как в любом случае они отличаются не более чем на константу, и на нашу оценку не повлияют.
Положим
$
xi_p (k) = cases(
1\, "если" k space dots.v space p, 0\, "иначе"
).
$
Тогда $xi = sum_(p <= M) xi_p$. Тогда
$
E xi_p = P(xi_p = 1) =
floor(n/p)/n in (1/p - 1/n, 1/p]
newline(==>)
E xi = sum_(p <= M) E xi_p =
sum_(p <= M) (1/p + O(1/n)) =
sum_(p <= M) 1/p + O(M/n) =
ln ln M + O(M/n) newline(=) ln ln root(5, n) + O(M/n) = ln ln n + O(1).
$
Теперь посмотрим на дисперсию:
$
D xi = sum_(p <= M) D xi_p + 2 sum_(p < q <= M) cov(xi_p, xi_q).
$
Ковариацию придется посчитать, потому что события "число с конечного интеравала делится на $p$" завимимы. Посчитаем:
$
D xi_p =
E xi_p^2 - (E xi_p)^2 =
E xi_p - (E xi_p)^2 = (1/p + O(1/n)) - (1/p + O(1/n))^2 =
1/p - 1/p^2 + O(1/n),\
cov(xi_p, xi_q) =
E(xi_p xi_q) - E xi_p E xi_q <=
P(xi_p xi_q = 1) - (1/p - 1/n)(1/q - 1/n) newline(=)
floor(n/(p q))/n - (1/p - 1/n)(1/q - 1/n) <= 1/n (1/p + 1/q).
$
Тогда
$
D xi =
sum_(p <= M) D xi_p + 2 sum_(p < q <= M) cov(xi_p, xi_q) <=
sum_(p <= M) (1/p - 1/p^2 + O(1/n)) + 2 sum_(p < q <= M) 1/n (1/p + 1/q) newline(=)
sum_(p <= M) 1/p - sum_(p <= M) 1/p^2 + O(M/n) + 1/n sum_(p, q <= M \ p != q) (1/p + 1/q) <=
sum_(p <= M) 1/p + O(1) + 1/n M sum_(p <= M) 1/p <= ln ln n + O(1).
$
Что за событие мы оценимаем? При больших $n$,
$
{abs(nu(k) - ln ln n) >= omega(n) sqrt(ln ln n)} subset
lr(size: #1.5em, {abs(xi(k) - E xi) >= underbrace(omega(n) sqrt(ln ln n), omega(n) (sqrt(D xi) + O(1))) - C}) newline(subset)
{abs(xi(k) - E xi) >= omega(n)/2 sqrt(D xi)}.
$
Применяем неравенство Чебышева:
$
P(abs(xi(k) - E xi) >= omega(n)/2 sqrt(D xi)) <= (D xi)/(omega(n)^2/4 sqrt(D xi)^2) = 4/(omega^2(n)) --> 0.
$
]
#notice[
Теорема Эрдеша-Каца:
$
1/n \#{k: a <= (nu(k) - ln ln n)/(sqrt(ln ln n)) <= b} -->_(n -> oo) 1/sqrt(2pi) integral_a^b e^(-x^2/2) dif x.
$
]
|
|
https://github.com/EGmux/ControlTheory-2023.2 | https://raw.githubusercontent.com/EGmux/ControlTheory-2023.2/main/unit3/rootLocusProject.typ | typst | #set heading(numbering: "1.")
exp1:
#math.equation(block: true, $ (k(S^2 - 4S + 20))/((S+2)(S+4)) $)
#figure(image("../assets/exp1.png", width: 80%), caption: []) <fig-exp1>
transform the system to type 1
but the root locus changes, rework will be needed
=== how it works
\
Given a system, create a compensator such that
- root locus is somewhat preserved
- performance characteristics are preserved
- improve the stationary state error
- improve transient respones, $T_p, T_s$
==== 2nd order subsystem representation
\
#math.equation(block: true, $ G(S) = (w_n^2)/(S^2 + 2 zeta w_n + w_n^2) $)
#math.equation(block: true, $ S_"1,2" = zeta W_n + j W_n root(2, 1-zeta^2) $)
==== type of compensators
\
===== improvement in response
\
- PI
#math.equation(block: true, $ G_"PI" = (S+z)/(S) "where z is close to origin"$)
- forward phase (LEAD)
===== improvement in error and response
\
- PID
- LEAD-LAG
💡 what it means to add a pole in the origin?
#math.equation(
block: true, $ theta_p = Sigma(angle.acute("zeros")) - Sigma(angle.acute"poles") $,
)
#math.equation(block: true, $ theta_p_2 = theta_p - (angle.acute(o)) $)
💡 place an approximate zero to the origin, won't change the root locus that
much, note that the integrator can be seem as pole in the origin
|
|
https://github.com/Raekker/typst_playground | https://raw.githubusercontent.com/Raekker/typst_playground/master/playground.typ | typst | #show link: underline
#set page(numbering:"1 of 1")
= Short Overview of Typst
Let's start with some comparison between _LaTeX_ and _Typst_
#table(
columns: 4 * (auto,),
align: horizon,
[Element], [LaTeX], [Typst], [See],
[Strong emphasis], [`\textbf{strong}`], [`*strong*`], [#link("https://typst.app/docs/reference/text/strong")[strong]],
[Emphasis], [`\emph{emphasis}`], [`_emphasis_`], [#link("https://typst.app/docs/reference/text/emphasis")[emph]],
[Monospace / code], [`\texttt{print(1)}`], [``print(1)``], [#link("https://typst.app/docs/reference/text/raw")[raw]],
[Link], [`\url{https://typst.app}`], [`https://typst.app/`], [#link("https://typst.app/docs/reference/meta/link")[link]],
[Label], [`\label{intro}`], [`<intro>`], [#link("https://typst.app/docs/reference/meta/label")[label]],
[Reference], [`\ref{intro}`], [`@intro`], [#link("https://typst.app/docs/reference/meta/ref")[ref]],
[Citation], [`\cite{humphrey97}`], [`@humphrey97`], [#link("https://typst.app/docs/reference/meta/cite")[cite]],
[Bullet list], [itemize environment], [\- List], [#link("https://typst.app/docs/reference/layout/list")[list]],
[Numbered list], [enumerate environment], [\+ List], [#link("https://typst.app/docs/reference/layout/enum")[enum]],
[Term list], [description environment], [\/ Term: List], [#link("https://typst.app/docs/reference/layout/terms")[terms]],
[Figure], [figure environment], [figure function], [#link("https://typst.app/docs/reference/meta/figure")[figure]],
[Table], [table environment], [table function], [#link("https://typst.app/docs/reference/layout/table")[table]],
[Equation], [`$x$, align / equation environments`], [`$x$, $ x = y $`], [#link("https://typst.app/docs/reference/math/equation")[equation]],
)
To write this list in Typst...
```latex
\begin{itemize}
\item Fast
\item Flexible
\item Intuitive
\end{itemize}
```
...just type this:
```
- Fast
- Flexible
- Intuitive
```
which then becomes
- Fast
- Flexible
- Intuitive
We can also do ordered lists easily, like so
+ This
+ is
+ an
+ ordered
+ list
and we can set some rules for it as well
e.g.
`#set enum(numbering:"I.")`
#set enum(numbering:"I.")
+ This
+ is
+ an
+ ordered
+ list
== Rules setting
You can set plethora of rules either for _*text*_ or _*page*_ or _*table*_ as long as the function
like _*text*_ has settable parameters
e.g.
I am starting out with small text.
`#set text(14pt)`
#set text(14pt)
This is a bit `#text(18pt)[larger,]`#text(18pt)[larger,]
don't you think?
#set text(11pt)
Let's do some page setting now
```
#set page(
paper: "a4",
header: rect(fill: aqua)[Header],
footer: [
#set align(center)
#set text(8pt)
#rect(fill: aqua, inset: 20pt)[
Footer
#counter(page).display(
"1 of I",
both: true,
)
],
]
]
)
#set rect(
width: 100%,
height: 100%,
inset: 4pt,
)
#rect(fill: aqua)[#lorem(100)]
```
#set page(
paper: "a4",
header: rect(fill: aqua)[Header],
footer: [
#set align(center)
#set text(8pt)
#rect(fill: aqua, inset: 20pt)[
Footer
#counter(page).display(
"1 of I",
both: true,
)
],
]
)
#set rect(
width: 100%,
height: 100%,
inset: 4pt,
)
#rect(fill: aqua)[#lorem(100)]
//#lorem(150)
#set enum(numbering: "1.a)")
=== Reasons to use Typst
From my perspective here's a few points in which Typst is better than LaTeX, at least when it comes to developer experience:
+ it's synatx is much clearer e.g. each of these is a function used with with set keyword to set rules for the document, like font and it's size, or type of page and it's margins
+ `
#set text(
font: "New Computer Modern",
size: 10pt )
#set page(
paper: "a6",
margin: (x: 1.8cm, y: 1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
`
+ things like emphasis, lists are like markdown synatx, though that is syntactic sugar, which basically does calls to respective functions (most of them)
+ in each function we can name which params we pass, so it adds to the clarity of the document if you need to read it and check it's settings
+ typst is "batteries included" kind of thing, therefore lots of things which can be done with built-in tools in Typst, would need packages in LaTex
+ like geometry, fancyhdr packages for page setup, in typst there's page function
+ or like babel, polyglossia, in typst there the text function in which the language can be set
+ or graphicx, svg, in typst there is image function
+ and as one more example tabularx, in typst there are table and grid functions
+ typst also has packages(and a built-in package manager) in a would be case there's lack of some functionality
+ documentation is very verbose and understandable, each function has its every parameter listed and explained along with examples of usage
+ and to top it, a nice and helpful error messages from the compiler
=== Typst current limitations and therefore perhaps reasons to not use it
What limitations does Typst currently have compared to LaTeX?
Although Typst can be a LaTeX replacement for many today, there are still features that Typst does not (yet) support. Here is a list of them which, where applicable, contains possible workarounds.
+ Native charts and plots. LaTeX users often create charts along with their documents in PGF/TikZ. Typst does not yet include tools to draw diagrams, but the community is stepping up with solutions such as cetz. You can add those to your document to get started with drawing diagrams.
+ Change page margins without a pagebreak. In LaTeX, margins can always be adjusted, even without a pagebreak. To change margins in Typst, you use the page function which will force a page break. If you just want a few paragraphs to stretch into the margins, then reverting to the old margins, you can use the pad function with negative padding.
+ Include PDFs as images. In LaTeX, it has become customary to insert vector graphics as PDF or EPS files. Typst supports neither format as an image format, but you can easily convert both into SVG files with online tools or Inkscape. We plan to add automatic conversion for these file formats to the Typst web app, too!
+ Page break optimization. LaTeX runs some smart algorithms to not only optimize line but also page breaks. While Typst tries to avoid widows and orphans, it uses less sophisticated algorithms to determine page breaks. You can insert custom page breaks in Typst using `#pagebreak(weak: true)` before submitting your document. The argument weak ensures that no double page break will be created if this spot would be a natural page break anyways. You can also use `#v(1fr)` to distribute space on your page. It works quite similar to LaTeX's \vfill.
+ Bibliographies are not customizable. In LaTeX, the packages bibtex, biblatex, and natbib provide a wide range of reference and bibliography formats. These packages also allow you to write .bbx files to define your own styles. Typst only supports a small set of citation styles at the moment, but we want to build upon this by supporting Citation Style Language (CSL), an XML-based format backed by Zotero that allows you to describe your own bibliography styles.
|
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/DLP2/project2/project.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#set page(
footer: "Engenharia de Telecomunicações - IFSC-SJ",
)
#show: doc => report(
title: "Dispositivos Lógicos Progamáveis II",
subtitle: "Implementação de PLL para Relógio Digital (Milisegundos)",
authors: ("<NAME> e <NAME>",),
date: "23 de Abril de 2024",
doc,
)
= Introdução
Neste relatório, será apresentado o desenvolvimento de um relógio digital com precisão de milisegundos, utilizando um PLL (Phase-Locked Loop) para a geração de um sinal de clock de 5 kHz. O projeto foi desenvolvido utilizando a ferramenta Quartus Prime Lite Edition 20.1.0.720 e a placa de desenvolvimento DE2-115.
= Implementação
== Parte 1 - Adicionar Centésimo de Segundo ao Relógio
A primeira etapa da implementação foi a adição de um contador de 100 para a contagem de centésimos de segundo. Para isso, foi utilizado um contador de 7 bits, que conta de 0 a 99, e um comparador para resetar o contador quando atingir o valor de 100.
Foi instânciado um novo componente de contagem ao circuito e dois conversores BDC2SSD para a impressão dos digitos em um display de 7 segmentos.
O seguinte RTL foi gerado após a adição do contador de centésimos de segundo ao circuito:
#figure(
figure(
rect(image("./pictures/rtlpll.png", width: 80%)),
numbering: none,
caption: [RTL do circuito operando com PLL]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Em seguida, verificamos a contagem através do modelsim e observamos que o contador de centésimos de segundo estava funcionando corretamente, contando de 0 a 99 e resetando para 0 após atingir o valor de 100, conforme a imagem abaixo:
#figure(
figure(
rect(image("./pictures/simulation.png", width: 80%)),
numbering: none,
caption: [Contagem de centésimos de segundo]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Parte 2 - Adicionar PLL
A segunda etapa da implementação é a geração de um sinal de clock de 5 kHz (ao invés do sinal de clock padrão utilizado pela FPGA. Para isso, foi utilizado um PLL com um clock de entrada de 50 MHz (valor de clock padrão para o chip implantado nesta placa).
\
O componente de PLL foi gerado através da ferramenta `PLL Intel FPGA IP`. Após a configuração do PLL, o sinal de clock de 5 kHz foi obtido na saída deste componente, sendo na sua configuração um *divisor de frequência de 10.000.*
\
#figure(
figure(
rect(image("./pictures/pllconfig2.png", width: 80%)),
numbering: none,
caption: [Configuração do PLL através da ferramenta ALT-PLL]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Na própria ferramenta, ao inserir os valores de entrada e saída desejados para o circuito de PLL, o Quartus gera o código VHDL necessário para a configuração do circuito que irá controlar a seção analógica do PLL, assim sendo possivel realizar a multiplicação ou divisão de frequência corretamente.
Ao finailizar a configuração, foi solicitado gerar os seguintes arquivos:
#figure(
figure(
rect(image("./pictures/pllconfig3.png", width: 80%)),
numbering: none,
caption: [Configuração do PLL através da ferramenta ALT-PLL]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Abaixo está uma sessão do código VHD gerado pelo Quartus, para a configuração VHDL do PLL, demais arquivos são necessários para realizar a instânciação do PLL como um componente do circuito principal.
\
#sourcecode[```vhd
GENERIC MAP (
bandwidth_type => "AUTO",
clk0_divide_by => 10000,
clk0_duty_cycle => 50,
clk0_multiply_by => 1,
clk0_phase_shift => "0",
compensate_clock => "CLK0",
inclk0_input_frequency => 50000,
intended_device_family => "Cyclone IV E",
lpm_hint => "CBX_MODULE_PREFIX=pll",
lpm_type => "altpll",
operation_mode => "NORMAL",
pll_type => "AUTO",
```]
É possivel notar na descrição acima frequência de entrada, a frequência de saída, o fator de divisão e o duty-cicle do circuito de PLL.
Esses parâmetros são necessários para determinar o formato da onda na saída do circuito, sendo que a frequência precisa ser dividida pelas 10.000 vezes para obter a frequência de 5 kHz.
O duty cicle é de 50% para que a onda seja simétrica, abaixo está uma imagem para ilustrar a diferença entre um duty-cicle de 50% entre 25% e 75%:
#figure(
figure(
rect(image("./pictures/dutycicle.png", width: 80%)),
numbering: none,
caption: [Ilustração de variação de duty-cicle]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Com a adição do PLL no circuito, temos uma topologia RTL com um intermediário entre o clock de entrada e o clock de saída, como ilustrado abaixo.
Para ajustar a contagem do segundo, o componente de timer também teve que ser ajustado para contar 5.000 vezes mais rápido, ou seja, de 0 a 99,99 em 5.000 ms.
#figure(
figure(
rect(image("./pictures/rtlpll.png", width: 80%)),
numbering: none,
caption: [RTL do circuito operando com PLL]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Em seguida, realizamos a simulação do circuito com a adição do PLL e verificamos seu funcionamento, conforme a imagem abaixo, a simulação apresenta a mesma caracteristica de onda pois apenas o clock foi alterado, mantendo a contagem de centésimos de segundo correta:
#figure(
figure(
rect(image("./pictures/simulationpll.png", width: 80%)),
numbering: none,
caption: [Contagem de centésimos de segundo com PLL]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Parte 3 - Modificar contadores para BCD
Para realizarmos a parte 3, alteramos o método de contagem do contador de centésimos de segundo para BCD (Binary-Coded Decimal), que é uma forma de representar números decimais utilizando 4 bits para cada dígito.
Diferentemente da topologia RTL nos casos anteriores, na parte 3, toda a contagem é feita diretamente em um único componente. Para isso, diversos sinais foram criados para armazenar a contagem atual e repassar o status da contagem para o próximo ciclo de clock.
#sourcecode[```vhd
ARCHITECTURE single_clock_arch OF timer IS
SIGNAL r_reg : unsigned(5 DOWNTO 0);
SIGNAL r_next : unsigned(5 DOWNTO 0);
SIGNAL s_u_reg, m_u_reg : unsigned(3 DOWNTO 0);
SIGNAL s_d_reg, m_d_reg : unsigned(3 DOWNTO 0);
SIGNAL s_u_next, m_u_next : unsigned(3 DOWNTO 0);
SIGNAL s_d_next, m_d_next : unsigned(3 DOWNTO 0);
SIGNAL s_en, m_en : STD_LOGIC;
SIGNAL c_u_reg, c_u_next : unsigned(3 DOWNTO 0);
SIGNAL c_en : STD_LOGIC;
SIGNAL c_d_reg, c_d_next : unsigned(3 DOWNTO 0);
```]
Em seguida, a lógica de contagem foi implementada de maneira a contar os centesimos de segundo, segundos e minutos:
#sourcecode[```vhd
BEGIN
-- register
PROCESS (clk, reset)
BEGIN
IF (reset = '1') THEN
r_reg <= (OTHERS => '0');
s_u_reg <= (OTHERS => '0');
m_u_reg <= (OTHERS => '0');
s_d_reg <= (OTHERS => '0');
m_d_reg <= (OTHERS => '0');
c_u_reg <= (OTHERS => '0');
c_d_reg <= (OTHERS => '0');
ELSIF (rising_edge(clk)) THEN
r_reg <= r_next;
c_u_reg <= c_u_next;
c_d_reg <= c_d_next;
s_u_reg <= s_u_next;
s_d_reg <= s_d_next;
m_u_reg <= m_u_next;
m_d_reg <= m_d_next;
END IF;
END PROCESS;
-- next-state logic/output logic for mod-1000000 counter
r_next <= (OTHERS => '0') WHEN r_reg = 49 ELSE
r_reg + 1;
c_en <= '1' WHEN r_reg = 49 ELSE
'0';
s_en <= '1' WHEN c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1' ELSE
'0';
m_en <= '1' WHEN s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1' ELSE
'0';
-- next-state logic/output logic for centisecond units
c_u_next <= (OTHERS => '0') WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_u_reg + 1 WHEN c_en = '1' ELSE
c_u_reg;
-- next-state logic/output logic for centisecond tens
c_d_next <= (OTHERS => '0') WHEN (c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg + 1 WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg;
-- next-state logic/output logic for second units
s_u_next <= (OTHERS => '0') WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_u_reg + 1 WHEN s_en = '1' ELSE
s_u_reg;
-- next-state logic/output logic for second tens
s_d_next <= (OTHERS => '0') WHEN (s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg + 1 WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg;
-- next-state logic/output logic for minute units
m_u_next <= (OTHERS => '0') WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_u_reg + 1 WHEN m_en = '1' ELSE
m_u_reg;
-- next-state logic/output logic for minute tens
m_d_next <= (OTHERS => '0') WHEN (m_d_reg = 5 AND m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg + 1 WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg;
```]
E por fim, a saída desta contagem foi repassada para os displays de 7 segmentos para exibição:
#sourcecode[```vhd
-- output logic
cen_u <= STD_LOGIC_VECTOR(c_u_reg);
cen_d <= STD_LOGIC_VECTOR(c_d_reg);
sec_u <= STD_LOGIC_VECTOR(s_u_reg);
sec_d <= STD_LOGIC_VECTOR(s_d_reg);
min_u <= STD_LOGIC_VECTOR(m_u_reg);
min_d <= STD_LOGIC_VECTOR(m_d_reg);
END single_clock_arch;
```]
Com a implementação do contador BCD, podemos ver alteração na topologia do RTL, conforme apresentado abaixo:
#figure(
figure(
image("./pictures/timerBCD.png"),
numbering: none,
caption: [Timer com contagem em BCD]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Parte 4 - Modificar o r_reg para LFSR:
A parte 4 consiste em modificar o registrador r_reg para um registrador LFSR (Linear Feedback Shift Register), o objetivo é retirar o contador sequencial que é utilizado por padrão e substituir por um contador LFSR.
Essa modificação permite uma vantagem no circuito pois ao utilizar um contador sequencial comum, são necessários diversos registradores para armazenar o estado atual do número, nesta atividade por exemplo, utilizando contadores sequenciais, seriam necessários 13 registradores para armazenar o estado atual do contador de 13 bits, pois 13 bits geram 8.192 possibilidades o equivalente as 5000 contagens necessárias para o circuito.
Agora, ao subistituirmos o contador sequencial por um LFSR, é possível realizar a contagem até 5000 com apenas 4 Taps (onde operações XOR são realizadas para gerar o próximo estado do contador) e 13 bits, o que reduz a quantidade de registradores necessários para armazenar o estado atual do contador, e também a complexidade e o tempo de propagação do circuito.
Desta forma, seguindo a planilha repassada professor, utilizamos a seguinte configuração para o LFSR, foi utilziado os seguintes parâmetros:
- Seed: 1111111111111
- Taps: [0, 2, 3, 12]
- bits: [12, 10, 9, 0] (Os bits são ordenados de acordo com a ordem de saída do LFSR, ou seja, inversos aos taps)
Entretanto, para utilizarmos o contador LFSR, é necessário também identificar qual a sequencia de bits que estará 5000 contagens a frente da sequência considerada inicial, ou seja, no nosso caso, a seed escolhida foi um vetor com 13x1, então, devemos identificar qual o vetor que estará 5000 casas a frente, para podermos resetar o contador e iniciar a contagem novamente.
Para isso, executamos o código Python abaixo para gerar a sequência LFSR e imprimir o estado do LFSR após 5000 contagens:
#sourcecode[```shell
cadore: ~$ python3 find_LFSR.py
Estado do LFSR na contagem 5000: 1011111001001
```]
O código Python utilizado possui a seguinte estrutura:
#sourcecode[```python
# -*- coding: utf-8 -*-
def lfsr(seed, taps, count):
# Converte o seed de string binária para uma lista de inteiros
state = [int(bit) for bit in seed]
# Função para calcular o próximo bit usando os taps
def next_bit(state, taps):
xor = 0
for t in taps:
xor ^= state[t]
return xor
for i in range(count):
new_bit = next_bit(state, taps) # Calcula o próximo bit
state = [new_bit] + state[:-1] # Desloca os bits para a direita e insere o novo bit na frente
state_str = ''.join(map(str, state))
print(f"{i + 1}: {state_str}")
# Parâmetros
seed = '1111111111111'
taps = [0, 2, 3, 12]
count = 5000
# Gera a sequência LFSR e imprime todos os estados
lfsr(seed, taps, count)
```]
Em seguida, alteramos a implementação do componente de contagem para utilizar o LFSR ao invés do contador sequencial, como ilustrado abaixo:
#sourcecode[```vhd
BEGIN
-- register
PROCESS (clk, reset)
BEGIN
IF (reset = '1') THEN
LFSR_reg <= SEED;
s_u_reg <= (OTHERS => '0');
m_u_reg <= (OTHERS => '0');
s_d_reg <= (OTHERS => '0');
m_d_reg <= (OTHERS => '0');
c_u_reg <= (OTHERS => '0');
c_d_reg <= (OTHERS => '0');
ELSIF (rising_edge(clk)) THEN
LFSR_reg <= LFSR_next;
c_u_reg <= c_u_next;
c_d_reg <= c_d_next;
s_u_reg <= s_u_next;
s_d_reg <= s_d_next;
m_u_reg <= m_u_next;
m_d_reg <= m_d_next;
END IF;
END PROCESS;
fb <= LFSR_reg(5) XOR LFSR_reg(0);
LFSR_next <= SEED WHEN LFSR_reg = CONST_RESET
ELSE
fb & LFSR_reg(5 DOWNTO 1);
c_en <= '1' WHEN LFSR_reg = CONST_RESET
ELSE
'0';
s_en <= '1' WHEN c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1' ELSE
'0';
m_en <= '1' WHEN s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1' ELSE
'0';
-- next-state logic/output logic for centisecond units
c_u_next <= (OTHERS => '0') WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_u_reg + 1 WHEN c_en = '1' ELSE
c_u_reg;
-- next-state logic/output logic for centisecond tens
c_d_next <= (OTHERS => '0') WHEN (c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg + 1 WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg;
```]
Nesta modificação, apenas o componente de contagem foi alterado, desta forma, mantendo a estrutura do RTL igual:
#figure(
figure(
image("./pictures/timerBCD.png"),
numbering: none,
caption: [Timer com contagem em LFSR]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Parte 5 - Implementação na placa:
Para cada etapa, realizamos a implementação na placa de desenvolvimento DE2-115, e verificamos o funcionamento do circuito.
#figure(
figure(
image("./pictures/pinplanner.png", width: 60%),
numbering: none,
caption: [Sinal de entrada no domínio do tempo]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
Desta forma, obtivemos os seguintes resultados:
#figure(
figure(
table(
columns: (1fr, 1fr, 1fr),
align: (left, center, center),
table.header[Implementacao][Área (LE)][Registradores],
[Parte 1], [83], [13.699],
[Parte 2], [239], [124],
[Parte 3], [102], [30],
[Parte 4], [101], [24],
),
numbering: none,
caption: [Tabela de resultados da implementação]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
= Conclusão
A partir da implementação do PLL vista anteriormente, juntamente com a implementação de divisão de clock sem o uso do PLL, podemos concluir que a utilização de um PLL é muito útil para a geração de sinais de clock com frequências específicas de maneira confiável.
Isso pois o PLL é capaz de gerar sinais de clock com frequências específicas, além de possuir uma maior precisão e estabilidade em relação a outros métodos de geração de clock. Além disso, podemos concluir que a contagem de maneira não sequencial através de um LFSR é mais eficiente e consome menos recursos da FPGA, além de ser mais rápido e eficiente.
Isso pois o LFSR pois não precisar contar de maneira sequencial e necessitar apenas de operações básicas para funcionar, não é só mais eficiente em termos de consumo de resursos, mais também possui um tempo de operação menor, contribuindo para um tempo menor de propagação do circuito.
= Códigos VHDL utilizados
Abaixo estão os demais códigos VHDL utilizados para a implementação do projeto.
== bin2bcd
#sourcecode[```vhd
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity bin2bcd is
port (
A : in std_logic_vector (7 downto 0);
sd, su, sc : out std_logic_vector (3 downto 0)
);
end entity;
architecture ifsc_v1 of bin2bcd is
signal A_uns : unsigned (7 downto 0);
signal sd_uns, su_uns, sc_uns : unsigned (7 downto 0);
begin
A_uns <= unsigned(A);
sc_uns <= A_uns/100;
sd_uns <= A_uns/10;
su_uns <= A_uns rem 10;
sc <= std_logic_vector(resize(sc_uns, 4));
sd <= std_logic_vector(resize(sd_uns, 4));
su <= std_logic_vector(resize(su_uns, 4));
end architecture;
```]
== bcd2ssd:
#sourcecode[```vhd
library ieee;
use ieee.std_logic_1164.all;
entity bcd2ssd is
port (
BCD : in std_logic_vector (3 downto 0);
SSD : out std_logic_vector (6 downto 0)
);
end entity;
architecture arch of bcd2ssd is
begin
with BCD select
SSD <= "1000000" when "0000",
"1111001" when "0001",
"0100100" when "0010",
"0110000" when "0011",
"0011001" when "0100",
"0010010" when "0101",
"0000011" when "0110",
"1111000" when "0111",
"0000000" when "1000",
"0011000" when "1001",
"0111111" when others;
end arch;
```]
== timer:
#sourcecode[```vhd
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
ENTITY timer IS
PORT (
clk, reset : IN STD_LOGIC;
cen_u, cen_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
sec_u, sec_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
min_u, min_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0)
);
END timer;
ARCHITECTURE single_clock_arch OF timer IS
SIGNAL r_reg : unsigned(5 DOWNTO 0);
SIGNAL r_next : unsigned(5 DOWNTO 0);
SIGNAL s_u_reg, m_u_reg : unsigned(3 DOWNTO 0);
SIGNAL s_d_reg, m_d_reg : unsigned(3 DOWNTO 0);
SIGNAL s_u_next, m_u_next : unsigned(3 DOWNTO 0);
SIGNAL s_d_next, m_d_next : unsigned(3 DOWNTO 0);
SIGNAL s_en, m_en : STD_LOGIC;
SIGNAL c_u_reg, c_u_next : unsigned(3 DOWNTO 0);
SIGNAL c_en : STD_LOGIC;
SIGNAL c_d_reg, c_d_next : unsigned(3 DOWNTO 0);
BEGIN
-- register
PROCESS (clk, reset)
BEGIN
IF (reset = '1') THEN
r_reg <= (OTHERS => '0');
s_u_reg <= (OTHERS => '0');
m_u_reg <= (OTHERS => '0');
s_d_reg <= (OTHERS => '0');
m_d_reg <= (OTHERS => '0');
c_u_reg <= (OTHERS => '0');
c_d_reg <= (OTHERS => '0');
ELSIF (rising_edge(clk)) THEN
r_reg <= r_next;
c_u_reg <= c_u_next;
c_d_reg <= c_d_next;
s_u_reg <= s_u_next;
s_d_reg <= s_d_next;
m_u_reg <= m_u_next;
m_d_reg <= m_d_next;
END IF;
END PROCESS;
-- next-state logic/output logic for mod-1000000 counter
r_next <= (OTHERS => '0') WHEN r_reg = 49 ELSE
r_reg + 1;
c_en <= '1' WHEN r_reg = 49 ELSE
'0';
s_en <= '1' WHEN c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1' ELSE
'0';
m_en <= '1' WHEN s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1' ELSE
'0';
-- next-state logic/output logic for centisecond units
c_u_next <= (OTHERS => '0') WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_u_reg + 1 WHEN c_en = '1' ELSE
c_u_reg;
-- next-state logic/output logic for centisecond tens
c_d_next <= (OTHERS => '0') WHEN (c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg + 1 WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg;
-- next-state logic/output logic for second units
s_u_next <= (OTHERS => '0') WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_u_reg + 1 WHEN s_en = '1' ELSE
s_u_reg;
-- next-state logic/output logic for second tens
s_d_next <= (OTHERS => '0') WHEN (s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg + 1 WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg;
-- next-state logic/output logic for minute units
m_u_next <= (OTHERS => '0') WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_u_reg + 1 WHEN m_en = '1' ELSE
m_u_reg;
-- next-state logic/output logic for minute tens
m_d_next <= (OTHERS => '0') WHEN (m_d_reg = 5 AND m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg + 1 WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg;
-- output logic
cen_u <= STD_LOGIC_VECTOR(c_u_reg);
cen_d <= STD_LOGIC_VECTOR(c_d_reg);
sec_u <= STD_LOGIC_VECTOR(s_u_reg);
sec_d <= STD_LOGIC_VECTOR(s_d_reg);
min_u <= STD_LOGIC_VECTOR(m_u_reg);
min_d <= STD_LOGIC_VECTOR(m_d_reg);
END single_clock_arch;
```]
== top_timer:
#sourcecode[```vhd
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
ENTITY top_timer_de2_115 IS
PORT (
CLOCK_50 : IN STD_LOGIC;
KEY : IN STD_LOGIC_VECTOR (0 DOWNTO 0);
HEX0 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0);
HEX1 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0);
HEX2 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0);
HEX3 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0);
HEX4 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0);
HEX5 : OUT STD_LOGIC_VECTOR (6 DOWNTO 0)
);
END ENTITY;
ARCHITECTURE top_a3_2019_2 OF top_timer_de2_115 IS
COMPONENT timer IS
PORT (
clk, reset : IN STD_LOGIC;
cen_u, cen_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
sec_u, sec_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
min_u, min_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0)
);
END COMPONENT;
COMPONENT bin2bcd IS
GENERIC (N : POSITIVE := 16);
PORT (
clk, reset : IN STD_LOGIC;
binary_in : IN STD_LOGIC_VECTOR(N - 1 DOWNTO 0);
bcd0, bcd1, bcd2, bcd3, bcd4 : OUT STD_LOGIC_VECTOR(3 DOWNTO 0)
);
END COMPONENT;
COMPONENT bcd2ssd
PORT (
BCD : IN STD_LOGIC_VECTOR (3 DOWNTO 0);
SSD : OUT STD_LOGIC_VECTOR (6 DOWNTO 0)
);
END COMPONENT;
COMPONENT pll5khz IS
PORT (
inclk0 : IN STD_LOGIC := '0';
c0 : OUT STD_LOGIC
);
END COMPONENT;
SIGNAL minT, minU : STD_LOGIC_VECTOR(3 DOWNTO 0);
SIGNAL secT, secU : STD_LOGIC_VECTOR(3 DOWNTO 0);
SIGNAL centT, centU : STD_LOGIC_VECTOR(3 DOWNTO 0);
SIGNAL min, sec : STD_LOGIC_VECTOR(5 DOWNTO 0);
SIGNAL cent : STD_LOGIC_VECTOR(6 DOWNTO 0);
SIGNAL r_reg, r_next : unsigned(22 DOWNTO 0);
SIGNAL reset : STD_LOGIC;
SIGNAL c0 : STD_LOGIC;
BEGIN
reset <= NOT KEY(0);
t0 : timer
PORT MAP(
clk => c0,
reset => reset,
cen_u => centU,
cen_d => centT,
sec_u => secU,
sec_d => secT,
min_u => minU,
min_d => minT
);
pll5khz_inst : pll5khz PORT MAP(
inclk0 => CLOCK_50,
c0 => c0
);
bcd0 : bcd2ssd
PORT MAP(
BCD => centU,
SSD => HEX0
);
bcd1 : bcd2ssd
PORT MAP(
BCD => centT,
SSD => HEX1
);
bcd2 : bcd2ssd
PORT MAP(
BCD => secU,
SSD => HEX2
);
bcd3 : bcd2ssd
PORT MAP(
BCD => secT,
SSD => HEX3
);
bcd4 : bcd2ssd
PORT MAP(
BCD => minU,
SSD => HEX4
);
bcd5 : bcd2ssd
PORT MAP(
BCD => minT,
SSD => HEX5
);
END top_a3_2019_2;
```]
== single_clock_arch:
#sourcecode[```vhd
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
ENTITY timer IS
PORT (
clk, reset : IN STD_LOGIC;
cen_u, cen_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
sec_u, sec_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);
min_u, min_d : OUT STD_LOGIC_VECTOR(3 DOWNTO 0)
);
END timer;
ARCHITECTURE single_clock_arch OF timer IS
SIGNAL r_next : unsigned(5 DOWNTO 0);
SIGNAL s_u_reg, m_u_reg : unsigned(3 DOWNTO 0);
SIGNAL s_d_reg, m_d_reg : unsigned(3 DOWNTO 0);
SIGNAL s_u_next, m_u_next : unsigned(3 DOWNTO 0);
SIGNAL s_d_next, m_d_next : unsigned(3 DOWNTO 0);
SIGNAL s_en, m_en : STD_LOGIC;
SIGNAL c_u_reg, c_u_next : unsigned(3 DOWNTO 0);
SIGNAL c_en : STD_LOGIC;
SIGNAL c_d_reg, c_d_next : unsigned(3 DOWNTO 0);
CONSTANT CONST_RESET : unsigned(5 DOWNTO 0) := "000110";
CONSTANT SEED : unsigned(5 DOWNTO 0) := "111111";
SIGNAL fb : STD_LOGIC;
SIGNAL LFSR_reg: unsigned(5 DOWNTO 0);
SIGNAL LFSR_next: unsigned(5 DOWNTO 0);
BEGIN
-- register
PROCESS (clk, reset)
BEGIN
IF (reset = '1') THEN
LFSR_reg <= SEED;
s_u_reg <= (OTHERS => '0');
m_u_reg <= (OTHERS => '0');
s_d_reg <= (OTHERS => '0');
m_d_reg <= (OTHERS => '0');
c_u_reg <= (OTHERS => '0');
c_d_reg <= (OTHERS => '0');
ELSIF (rising_edge(clk)) THEN
LFSR_reg <= LFSR_next;
c_u_reg <= c_u_next;
c_d_reg <= c_d_next;
s_u_reg <= s_u_next;
s_d_reg <= s_d_next;
m_u_reg <= m_u_next;
m_d_reg <= m_d_next;
END IF;
END PROCESS;
fb <= LFSR_reg(5) XOR LFSR_reg(0);
LFSR_next <= SEED WHEN LFSR_reg = CONST_RESET
ELSE
fb & LFSR_reg(5 DOWNTO 1);
c_en <= '1' WHEN LFSR_reg = CONST_RESET
ELSE
'0';
s_en <= '1' WHEN c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1' ELSE
'0';
m_en <= '1' WHEN s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1' ELSE
'0';
-- next-state logic/output logic for centisecond units
c_u_next <= (OTHERS => '0') WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_u_reg + 1 WHEN c_en = '1' ELSE
c_u_reg;
-- next-state logic/output logic for centisecond tens
c_d_next <= (OTHERS => '0') WHEN (c_d_reg = 9 AND c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg + 1 WHEN (c_u_reg = 9 AND c_en = '1') ELSE
c_d_reg;
-- next-state logic/output logic for second units
s_u_next <= (OTHERS => '0') WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_u_reg + 1 WHEN s_en = '1' ELSE
s_u_reg;
-- next-state logic/output logic for second tens
s_d_next <= (OTHERS => '0') WHEN (s_d_reg = 5 AND s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg + 1 WHEN (s_u_reg = 9 AND s_en = '1') ELSE
s_d_reg;
-- next-state logic/output logic for minute units
m_u_next <= (OTHERS => '0') WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_u_reg + 1 WHEN m_en = '1' ELSE
m_u_reg;
-- next-state logic/output logic for minute tens
m_d_next <= (OTHERS => '0') WHEN (m_d_reg = 5 AND m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg + 1 WHEN (m_u_reg = 9 AND m_en = '1') ELSE
m_d_reg;
-- output logic
cen_u <= STD_LOGIC_VECTOR(c_u_reg);
cen_d <= STD_LOGIC_VECTOR(c_d_reg);
sec_u <= STD_LOGIC_VECTOR(s_u_reg);
sec_d <= STD_LOGIC_VECTOR(s_d_reg);
min_u <= STD_LOGIC_VECTOR(m_u_reg);
min_d <= STD_LOGIC_VECTOR(m_d_reg);
END single_clock_arch;
```] |
https://github.com/donabe8898/typst-thesis-template | https://raw.githubusercontent.com/donabe8898/typst-thesis-template/main/README.md | markdown | Apache License 2.0 | # typst-thesis-template
Typstで卒業論文書くときのテンプレ
参考: [haxibami/typst-template](https://github.com/haxibami/typst-template) |
https://github.com/horaoen/note | https://raw.githubusercontent.com/horaoen/note/main/redis-quickstart.typ | typst | Apache License 2.0 | #import "../../../typstempl/template/note.typ": note
#show: doc => note(
title: "redis quick start",
doc
)
== redis cloud |
https://github.com/Favo02-unimi/reti-di-calcolatori | https://raw.githubusercontent.com/Favo02-unimi/reti-di-calcolatori/main/README.md | markdown | ## Reti di calcolatori
Dispensa per il corso di Reti di calcolatori, tenuto di Prof. Rossi e Quadri presso l'Università degli Studi di Milano.
- Dispensa: Teoria
- Codice sorgente (Typst): [Teoria/Dispensa.typ](./Teoria/Dispensa.typ)
- Release PDF: [release di questo repository](https://github.com/Favo02/reti-di-calcolatori/releases/download/v1/Dispensa.pdf)
> [!CAUTION]
> La dispensa di teoria è _ancora_ praticamente solo un indice (**completo**) degli argomenti trattati.
- Laboratorio: Java Socket
- UDP: [Client.java](./Laboratorio/JavaSocket/UDP/Client.java), [Server.java](./Laboratorio/JavaSocket/UDP/Server.java)
- TCP: [Client.java](./Laboratorio/JavaSocket/TCP/Client.java)
- server iterativo: [ServerIterativo.java](./Laboratorio/JavaSocket/TCP/ServerIterativo.java)
- server concorrente: [ServerConcorrente.java](./Laboratorio/JavaSocket/TCP/ServerConcorrente.java)
- server multithread: [ServerMultithread.java](./Laboratorio/JavaSocket/TCP/ServerMultithread.java)
- Laboratorio: Packet tracer
- Cheatsheet comandi: [Cheatsheet.md](./Laboratorio/PacketTracer/Cheatsheet.md)
### Autori, Ringraziamenti e Licenza
- **Autori**: [<NAME>](https://github.com/Favo02) _(Teoria, Java socket)_, [<NAME>](https://github.com/LucaCorra02) _(Java socket, Packet tracer)_
- **Ringraziamenti**: [<NAME>](https://github.com/MaxKappa) _(Java socket)_, [<NAME>](https://github.com/GioarmsCodes) _(Appunti)_, [<NAME>](https://github.com/ceri01) _(Appunti)_
- **Licenza:** [CC-BY-4.0](https://creativecommons.org/licenses/by/4.0/)
- **Ultima modifica (compilato PDF):** 2024-07-24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.