repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
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/robot-rebuild/decide.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: Robot Rebuild",
type: "decide",
date: datetime(year: 2024, month: 3, day: 5),
author: "<NAME>",
witness: "<NAME>",
)
Upon coming up with some options we rated each one for the following
characteristics on a scale of 1-10:
- Complexity with a weight of 0.5x
- Weight with a weight of 0.6x
- Scoring potential with a weight of 0.9x
#admonition(
type: "note",
)[
Stretching the limits of what we can build is one of our goals for this rebuild,
so complexity is a positive here, rather than a negative.
]
#decision-matrix(
properties: ( //
(name: "Complexity", weight: 0.5),
(name: "Weight", weight: 0.6),
(name: "Scoring Potential", weight: 0.9),
), //
("Modular Elevation/Shooting", 3, 7, 9),
("PTO to Elevation", 6, 5, 10),
("Descore bot", 2, 7, 5),
)
#admonition(
type: "decision",
)[
We ended up choosing the PTO to Elevation option due to its incredibly high
scoring potential and complexity. If we are able to successfully pull this off,
we would be one of the only teams in 53 history to successfully build a PTO.
]
= Design Overview
Now that we've decided what we want out of our robot, we decided to plan things
out a little more. Here is our final motor distribution:
- 1 motor intake
- 1 motor shooting mechanism
- 6 motor drivetrain
- 6 motor hang
- 2 piston wings
We also decided to make more detailed sketches of our subsystem layout in order
to have a better idea of how they would be arranged before CADing them.
== Drivetrain
The drivetrain is the most important part of our robot, as it lets us drive
around. Having at least a rough idea of how this will look right now is
extremely important because so many subsystems depend on it.
#image("./driveTrainSide2024.svg")
The PTO is the most complicated part of the robot, and interfaces directly with
the drivetrain.
Here's a front view of the drivetrain that gives a better explanation of how the
PTO works:
#image("./driveTrain2024.svg")
== Climb
The actual mechanism for the climbing mechanism is relatively simple. The whole
design uses 3 joints, total. A piston extends to push the mechanism into the
air, and then we hook onto the top of the elevation bar.
#image("./climb2024.svg")
Once we do that, we switch our PTO in order to engage the motors of the
drivetrain with the winch. Then we simply turn our winch until the robot has
been pulled into the air.
== Intake
The intake is incredibly similar to our old design. The flex wheels spin in
either direction to pull in the triballs.
Here's a sketch detailing how it will work:
#image("./intake2024.svg")
|
https://github.com/li3zhen1/Typst-Templates | https://raw.githubusercontent.com/li3zhen1/Typst-Templates/main/README.md | markdown | # Typst-Templates
My Typst templates for personal usage.
### homework.typ

|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/3-methodology/study-1/configuration.typ | typst | MIT License | #import "../../../lib/mod.typ": *
#v(-0.8em)
=== Configuration <s.m.configuration>
#v(-0.5em)
To make the developed software more flexible and easier to use, several configuration formats have been developed. The main configuration file, `config.toml`, uses #acr("TOML"), and is used to define all the general parameters for the simulation, visualization, and #acr("UI"). The most important sections of the main configuration file are: `GBP`, `Robot`, `Simulation`, `Visualization`. The smaller sections are described in the code documentation itself.@repo
#set enum(numbering: box-enum.with(prefix: "Section "))
+ `GBP:` Outlines all initial factor standard deviations, $sigma$, used in the #acr("GBP") message passing, alogn with the iteration schedule to use and how many of _internal_ vs _external_ iterations to run.
+ `Robot:` Defines each robot's properties, such as size, target speed, communication radius and failure rate, and degrees of freedom. Additionally, some properties for the structure of the underlying factor are in this section; i.e. the planning-horizon, whether to use symmetric interrobot factors, and scaling of the safety distance between robots.
+ `Simulation:` Contains the parameters for the simulation itself, such as the maximum simulation time, the #acr("RNG") seed, and the fixed time-step frequency to run the #acr("GBP") algorithm at. More are described in @repo.
+ `Visualization:` Contains the parameters for the visual elements. This includes which properties to draw to the screen like communication radius, interrobot connections, planning horizon, waypoints, etc. Furthermore, some scaling factors, i.e. for the variable uncertainties, to make them visible on the screen, are defined here. Again, more are described in @repo.
==== Environment Configuration <s.m.configuration.environment>
A datastructure for describing the static environment has been developed, and includes two main parts; the overall environment, and the option to specify several placeable shapes.
#let unicodes = (
([─], [U+2500]),
([│], [U+2502]),
([┌], [U+250C]),
([┐], [U+2510]),
([└], [U+2514]),
([┘], [U+2518]),
([├], [U+251C]),
([┤], [U+2524]),
([┬], [U+252C]),
([┴], [U+2534]),
([┼], [U+253C]),
([█], [U+2588]),
([╴], [U+2574]),
([╵], [U+2575]),
([╶], [U+2576]),
([╷], [U+2577]),
).map(it => {
(
text(font: "JetBrainsMono NF", it.at(0)),
text(font: "JetBrainsMono NF", it.at(1))
)
})
#let unicode-fig = [
#v(1em)
#figure(
tablec(
columns: 4,
header: table.header(
[Character], [Unicode], [Character], [Unicode]
),
..unicodes.flatten()
),
caption: [Supported Unicode characters and their \ codes for environment generation.]
)<t.unicode-list>
]
#let b = [
===== The Main Environment<s.m.configuration.environment.main>
This section of the configuration file is a matrix of strings. Each character in the matrix represents a tile in the environment. The supported characters are listed in @t.unicode-list. The environment is generated from this matrix, where each character is a square tile, with a configurable side-length, and the colored-in parts of the characters are the free paths and the rest are walls. The path-width is configurable as a percentage of the tile side-length.
The#h(1fr)environment#h(1fr)shown#h(1fr)in#h(1fr)@f.m.maze-env#h(1fr)is#h(1fr)built
]
#grid(
columns: 2,
column-gutter: 1em,
b,
unicode-fig,
)
#v(-0.60em)
from the character matrix, in @f.m.maze-env#text(accent, "A"). Even though each character is taller than it is wide when written out in most fonts, the map-generation code produces one _square_ tile for each character. This makes up for the seeming descrepency in aspect ratio between the character grid in @f.m.maze-env#text(accent, "A"), and the actual environment in @f.m.maze-env#text(accent, "B"). A few special case characters are `U+2588 █`, and a space, where, the former represents free space, and the latter represents a filled-in tile, similarly to how the white-space in the other path characters are the actual obstacles.
The resulting grid of _tiles_ in @f.m.maze-env#text(accent, "B") is, 5$times$8, where a 2$times$1 segment is highlighted#sg. In @f.m.maze-env#text(accent, "C") the highlighted section is shown bigger, where, in red#sr, the resulting #acr("AABB") colliders are shown. These colliders are generated on a per-tile basis, which means that the there are seams between the tiles, where the colliders meet. One could argue that these seams could be eliminated to optimize computational efficiency, as less intersection tests would have to be made in the #acr("RRT*") algorithm.
#figure(
{
set par(justify: false)
set text(theme.text)
grid(
columns: (auto, 8em, 2.4125fr, 1fr, auto),
[],
std-block(breakable: false)[
#set par(leading: 0.25em)
#set text(size: 14pt)
// #let sp = 6.375em
#let sp = 5.42em
#let sp-top = 2.5em
// #v(sp-top)
#box(
fill: rgb(1, 1, 1, 0),
height: sp-top,
outset: 0em,
inset: 0em,
)
```
┌─┼─┬─┐┌
┼─┘┌┼┬┼┘
┴┬─┴┼┘│
┌┴┐┌┼─┴┬
├─┴┘└──┘
```
#v(sp - sp-top)
#set text(size: 10pt)
A: Character Matrix
],
std-block[
#image("../../../figures/out/maze-env.svg")
#v(0.5em)
B: Generated Environment Tiles
],
std-block[
#image("../../../figures/out/maze-env-crop.svg")
#v(0.5em)
C: Highlighted Tiles
],
[],
)
},
kind: image,
supplement: "Figure",
caption: [
#let outline = {
let l = place(dy: -0.35em, line(length: 1.6em, stroke: (thickness: 2pt, paint: theme.green, dash: "dashed", cap: "round")))
box(inset: (x: 2pt), outset: (y: 2pt), l + h(1.6em))
}
An example of a maze-like environment. A) Shows the character matrix used to generate the environment. B) Shows the generated environment tile grid with all obstacles in blue#sl, where two tiles are highlighted#outline. In C) the highlighted tiles are shown bigger, with the resulting AABB colliders in red#sr.
],
)<f.m.maze-env>
// The environment is generated from this matrix, where each character is a tile, and the environment is a grid of tiles. The environment is then used to generate the colliders for the robots to avoid, and the visual representation of the environment.
#let param-fig = [
#figure(
{
v(1.5em)
tablec(
columns: (auto, 1fr, auto),
alignment: (left, left, left),
header: table.header(
[Shape], [Parameters], [Symbols]
),
[Circle], [radius], $r$,
[Rectangle], [height, width], $h,w$,
[Regular polygon], [side-length, number of sides], $s,n$,
[Triangle], [base-length, height, mid-point], $b,h,m$,
)
},
caption: [Supported shapes for the environment generation.],
)<t.environment-shapes>
]
#let b = [
===== Placeable Obstacles<s.m.configuration.environment.obstacles>
Another section in the environment configuration is the `obstacles` list. This is a list of shapes that are completely configurable within each tile. That#h(1fr)is,#h(1fr)the#h(1fr)shapes#h(1fr)can#h(1fr)be#h(1fr)placed#h(1fr)any-
]
#grid(
columns: (3fr, 4fr),
column-gutter: 1em,
b,
param-fig,
)
#v(-0.5em)
where within the tile, and have any size. The map-generator supports the shapes listed in @t.environment-shapes. The table also details all configurable parameters for each shape.
#figure(
std-block(
grid(
columns: 2,
sourcecode[
```yaml
tiles:
grid:
- █
settings:
tile-size: 100.0
path-width: 0.1
obstacle-height: 1.0
sdf:
resolution: 200
expansion: 0.025
blur: 0.01
obstacles:
- shape: !regular-polygon
sides: 4
radius: 0.0525
translation:
x: 0.625
y: 0.60125
rotation: 0.0
tile-coordinates:
row: 0
col: 0
- shape: !regular-polygon
sides: 4
radius: 0.035
translation:
x: 0.44125
y: 0.57125
rotation: 0.0
tile-coordinates:
row: 0
col: 0
- shape: !regular-polygon
sides: 4
radius: 0.0225
translation:
x: 0.4835
y: 0.428
```
],
sourcecode(
numbers-start: 39
)[
```yaml
rotation: 0.0
tile-coordinates:
row: 0
col: 0
- shape: !rectangle
width: 0.0875
height: 0.035
translation:
x: 0.589
y: 0.3965
rotation: 0.0
tile-coordinates:
row: 0
col: 0
- shape: !triangle
angles:
A: 1.22
B: 1.22
radius: 0.025
rotation: 0.0
translation:
x: 0.5575
y: 0.5145
tile-coordinates:
row: 0
col: 0
- shape: !triangle
angles:
A: 0.6981317007977318
B: 1.9198621771937625
radius: 0.01
rotation: 5.2
translation:
x: 0.38
y: 0.432
tile-coordinates:
row: 0
col: 0
```
]
)
),
kind: "listing",
supplement: [Listing],
caption: [Example of an environment configuration with several placeable shapes. This configuration belongs to the *Environment Obstacles Experiment* scenario. It uses the _Circle_, _Rectangle_, _Regular polygon_, and _Triangle_ shapes.],
)<lst.env-obstacle-config>
Furthermore, which tile to place the shape in is given as a tile-$x$ and $y$ coordinate, to index which tile to place the obstacle in, along with a within-tile 2D translation. Important to note is that the parameters for the shapes are given in the local coordinate system of the tile, and as scalable percentage values of the tile side-length. As such, the placed obstacles are scaled along with the tile size, which produces a consistent environment, regardless of the size of the tiles. This way it is the tile-size that acts as a global scale. Another approach would be to have absolute coordinates for all these parameters, however, this is a more frictionfull approach, as understanding which tile you are attempting to place an obstacle inside will be harder to understand, along with the obstacles placement in relation to each other. Basically, this approach splits the global coordinate into a grid of local coordinates, which are easier to keep track of when a user is designing the environment. And example of an environment configuration with multiple placeable shapes is shown in @lst.env-obstacle-config.
==== Formation Configuration <s.m.configuration.formation>
The formation configuration is used to define how the robots are spawned in the environment. A great deal of care has gone into making this a highly flexible and declarative way to define new ways to spawn robots, and define their waypoints. The formation configuration is a list of formations, where each formation is a set of parameters for how to spawn the robots, and how to layout their waypoints.
Formations are described with the concept of _distribution shapes_. These shapes are an abstract way of representing dynamically placed points, but within some constraints. Say the shape is a line from $(0,0)$ to $(1,0)$, and we want this line to describe how to place 5 points. To know where to place these points, we need a technique to define where along the line, the points should be placed. Two techniques have been implemented; `random` and `even`. These two strategies inform whether to place the points with even spacing as in @f.m.formation-shapes#text(accent, "A"), or randomly as in @f.m.formation-shapes#text(accent, "B"). Note, that with both strategies, each robot's size is taken into account, as, when spawned they cannot be intersecting with each other. If this invariant is not possible to satisfy an error is reported.
#figure(
{
set text(theme.text)
grid(
columns: 2,
std-block[
#image("../../../figures/out/distribution-shapes-even.svg", height: 12em, fit: "contain") \
A: Even Distribution
],
std-block[
#image("../../../figures/out/distribution-shapes-random.svg", height: 12em, fit: "contain") \
B: Random Distribution
],
)
},
caption: [Different formation shapes and placement strategies. Both #text(accent, "A") and #text(accent, "B") show a line and a circle shape, where the points in #text(accent, "A") are placed evenly, and in #text(accent, "B") are placed randomly.],
)<f.m.formation-shapes>
Now that we understand _distribution shapes_, we can look at their use-cases. These shapes are used in a formation, to describe how to place initially place the robots when spawned into the environment. Thereafter, each formation has a list of waypoints, which is a list of these _distribution shapes_ and _projection strategies_. The _projection strategies_ are used to describe how to map the initial spawning locations of the robots, to the new waypoints. A couple strategies have been implemented, namely; `identity`, `cross`. A possible formation configuration is shown in @f.m.formation-config.
For each formation it is additionally possible to define when each waypoint is considered reached with the `waypoint-reached-when-intersects` key, and when the formation is considered finished with the `finished-when-intersects` key. Both of these take either `horizon`, `current`, or `!variable n`, where `n` is which variable in the factor graph to consider.
Lastly, some timing options are available; `repeat-every` and `delay`. The `repeat-every` key defines how often to spawn the amount of robots defined by the `robots` key on the _distribution shape_ given by the `initial-position` key. The `delay` sets an initial time offset before the first spawn event takes place.
#figure(
std-block(
grid(
columns: 2,
sourcecode[
```yaml
formations:
- repeat-every:
secs: 8
nanos: 0
delay:
secs: 2
nanos: 0
robots: 1
initial-position:
shape: !line-segment
- x: 0.45
```
],
sourcecode(
numbers-start: 12,
)[
```yaml
y: 0.0
- x: 0.55
y: 0.0
placement-strategy: !even
waypoints:
- shape: !line-segment
- x: 0.45
y: 1.25
- x: 0.55
y: 1.25
projection-strategy: cross
```
]
)
),
kind: "listing",
supplement: [Listing],
caption: [Formation configuration example spawning a single robot every 8 seconds with an initial delay of 2 seconds. Here, the `line-segment` _distribution shape_ is used, along with the `even` _placement strategy_, and `cross` _projection strategy_.],
)<f.m.formation-config>
#par(first-line-indent: 0pt)[For a complete example of each configuration format see the three files; #configs.config, #configs.environment, and #configs.formation used in the _Environment Obstacles_ scenario, experimented with later on in @s.r.scenarios.environment-obstacles.]
// #source-link("https://github.com/aalpatya/gbpplanner/blob/fd719ce6b57c443bc0484fa6bb751867ed0c48f4/config/circle_cluttered.json", "config/circle_cluttered.json")
=== Signed Distance Field <s.m.sdf>
As described above in @s.m.configuration.environment, the environment is generated from a matrix of characters, and a list of placeable obstacles. The advantage of being able to describe the environment in a constrained text format comes from the declarative nature of the format. You simply describe the geometrical shapes from their underlying data, and where to place them, and as such there will never be any dispute as to how that environment should look within the constraints of the format. This also provides a simple and compact single source of truth for the environment, which can be read for multiple purposes.
The simulation tool, #acr("MAGICS"), described in @s.m.simulation-tool, displays the environment in the _viewport_ as 3D meshes, showing the user what the world looks like. Furthermore, the tool also uses the environment configuration to automatically generate an #acr("SDF") file, which is then used by the obstacle factors, refer to #nameref(<s.m.factors.obstacle-factor>, [Obstacle Factor $f_o$]), as a way to measure the distance to nearest obstacle.
#figure(
{
set text(theme.text)
let cut-amount = 8em
grid(
columns: 3,
std-block[
#box(
clip: true,
pad(
x: -cut-amount,
y: -cut-amount,
image("../../../figures/img/img.png")
)
)
A: Rasterized Environment
],
std-block[
#box(
clip: true,
pad(
x: -cut-amount,
y: -cut-amount,
image("../../../figures/img/img_exp.png")
)
)
B: Expanded Environment
],
std-block[
#box(
clip: true,
pad(
x: -cut-amount,
y: -cut-amount,
image("../../../figures/img/sdf.png")
)
)
C: Blurred
],
)
},
caption: [An example of an automatically generated SDF file. A) Rasterize the environment into a black and white image. B) Expand the obstacles to make the eventual blur eat less into the obstacles. C) Blur the image to create the final SDF.],
)<f.m.sdf>
Furthermore, this single source of truth, allows the #acr("MAGICS") to visualize the true environment as meshes; generated from the same configuration file. As explained later, in , the user can choose to toggle visibility of both this _generated map_ mesh, and the #acr("SDF") image, which allows the user to understand both the actual environment and how the factors are measuring the environment. Furthermore, true collisions between the robots and the environment are calculated using the `parry2d`@parry2d library, which also uses the environment configuration to generate all the necessary colliders.
// ==== Signed Distance Field <s.m.sdf.sdf>
// Automatic generation of SDF image
// 1. Rasterize the environment into a black and white image.
// 2. Expand the obstacles to make the eventual blur eat less into the obstacles.
// 3. Blur the image to create the final SDF.
As shown in @f.m.sdf, the process of generating the #acr("SDF") image is done in three steps:
#set enum(numbering: box-enum.with(prefix: "Step "))
+ *Rasterization:* The rasterization of the environment happens by creating a white image with resolution calculated by @eq.sdf-rasterization:
$
"width" = r_t times c#h(1em)"and"#h(1em)"height" = r_t times r
$<eq.sdf-rasterization>
where $r_t$ is the tile-resolution from `environment.yaml`, and $c$ and $r$ are the number of columns and rows in the environment matrix respectively. Now going through each pixel of the environment, it is determined whether to make it black if it is either a part of the environment from the character matrix, or if it is part of an obstacle from the `obstacles` list. See @f.m.sdf#text(accent, "A") for the resulting rasterization of the `environment.yaml` written in @lst.env-obstacle-config, but without any expansion.
+ *Expansion:* The expansion of the obstacles is done, not by simply dilating the black pixels, but by expanding the underlying data of each of the placeable shapes providing the obstacles. This method provides a more accurate representation of the obstacles as if they were bigger, where a dilation would round over corners that would otherwise be sharp, which is an important detail to retain. See @f.m.sdf#text(accent, "B") for an example of the same `environment.yaml`, but with an expansion applied.
+ *Blurring:* The final step is to blur the image, which is done using a Gaussian blur. This step provides the #acr("SDF") aspects of the result with a smooth black-to-white, obstacle-to-free transition #gradient-box(black, white, width: 2em). The result of the blurring can be seen in @f.m.sdf#text(accent, "C"). The blurring is usually done with a non-zero expansion, as this provides a buffer between the obstacles and the free space. However, one should note that the resulting #acr("SDF") is _not_ an accurate representation of euclidean distances, but rather a sufficient approximation for the purposes of the simulation. Furthermore, one could argue that and accurate #acr("SDF") would be harmful, as we do not want the robots to react to any obstacles that they are far away from either way. Currently, avoiding this is encoded into the image here, but if an accurate #acr("SDF") is desired this behaviour should be transferred to the measurement function of the obstacles factor.
|
https://github.com/stepbrobd/nixology | https://raw.githubusercontent.com/stepbrobd/nixology/master/nixology/main.typ | typst | MIT License | #import "@preview/polylux:0.3.1": *
#import themes.simple: *
#let title = "Nixology"
#let author = "<NAME>"
#let date = datetime(year: 2024, month: 7, day: 1)
#set document(title: title, author: author, date: date)
#set page(paper: "presentation-16-9")
#show: simple-theme.with(footer: none)
#title-slide[
#image("nix.svg", width: 10%)
= #title
#v(4em)
#set text(16pt)
#author
#date.display("[month repr:long] [day padding:none], [year]")
]
#slide[
== Problem
#set align(center)
#image("works.jpg", width: 75%)
]
#slide[
== Solution
Functions:
#grid(
columns: 2, gutter: 2.5cm,
)[
```nix
{ inputs = { ... }; }
```
- Dependencies are inputs
- Usually tarballs or git repos
- Pinned and hashed
][
```nix
{ outputs = inputs: { ... }; }
```
- Outputs are functions of inputs// or contents of other outputs, or nothing
- Can be anything
- Lazily evaluated// evaluated only when needed
]
]
#slide[
== Trinity
#grid(columns: 2, gutter: 2mm, [
- Nix - the package manager
- Nix - the DSL
- Nixpkgs - the package collection
- NixOS - the operating system
], [#image("trinity.svg", width: 75%)])
]
#slide[
== Language Basics
#grid(columns: 2, gutter: 6cm)[
Integers: ```nix
> x = 1 + 1
> x
2
```
Floats: ```nix
> y = 1.0 + 1.0
> y
2.0
```
][
Strings: ```nix
> z = "world"
> "hello ${z}"
"hello world"
```
Attribute sets: ```nix
> s = { a = { b = 1; }; }
> s.a.b
1
```
]
]
#slide[
== Language Basics
#grid(columns: 2, gutter: 3cm)[
Lists:
```nix
> [ 1 "2" (_: 3) ]
[ 1 "2" <thunk> ]
```
Recursive attrsets:
```nix
> rec { x = 1; y = x; }
{ x = 1; y = 1; }
```
][
Bindings:
```nix
> let x = 1; in x + 1
2
```
Inherits:
```nix
> let x = 1; y = x; in
{ inherit x y; }
{ x = 1; y = 1; }
```
]
]
#slide[
== Language Basics
#grid(columns: 2, gutter: 3cm)[
Functions 1:
```nix
> f = x: x + 1
> f 2
3
> g = g': x: g' x + 1
> g f 2
4
```
][
Functions 2:
```nix
> h = { x ? 1 }: x + 1
> h
<function>
> h { }
2
> h { x = 2; }
3
```
]
]
#slide[
== Derivation
A _derivation_
#grid(columns: 2, gutter: 3cm)[
- is plan / blueprint
- it's used for producing
- `lib`: library outputs
- `bin`: binary outputs
- `dev`: header files, etc.
- `man`: man page entries
- ...
][
```hs
derivation ::
{ system : String
, name : String
, builder : Path | Drv
, ? args : [String]
, ? outputs : [String]
} -> Drv
```
]
]
#slide[
== Derivation
Example:
#grid(columns: 2, gutter: 0.75cm)[
```hs
derivation ::
{ system : String
, name : String
, builder : Path | Drv
, ? args : [String]
, ? outputs : [String]
} -> Drv
```
][
```nix
derivation {
system = "aarch64-darwin";
name = "hi";
builder = "/bin/sh";
args = ["-c" "echo hi >$out"];
outputs = ["out"];
}
```
]
]
#slide[
== Derivation
Special variables:
#grid(columns: 2, gutter: 0.75cm)[
```nix
derivation {
system = "aarch64-darwin";
name = "hi";
builder = "/bin/sh";
args = ["-c" "echo hi >$out"];
outputs = ["out"]; ^^^^
} ^^^
```
][
- `$src`: build source
- `$out`: build output (default)
- custom outputs
]
]
#slide[
== Nix Store
```nix
/nix/store/l2h1lyz50rz6z2c8jbni9daxjs39wmn3-hi
|---------|--------------------------------|-|
store hash name
prefix
```
- Store prefix can be either local or remote (binary cache)
- Hash either derived from input (default) or output (CA derivation)
- The hash ensures two realised derivations with the same name have different
paths if the inputs differ at all
]
#slide[
== Packaging
The process of: Nix expressions $arrow.r.double$ derivation(s)
- `builtins.derivation`
- `stdenv.mkDerivation` (from `nixpkgs`)
- `pkgs.buildGoApplication` (from `nixpkgs`)
- ...
]
#slide[
== Packaging #footnote("Example 1")
#set text(14pt)
#grid(columns: 2, gutter: 4cm, [
```nix
{
inputs = { ... };
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
in
{
packages.default = pkgs.writeShellApplication {
name = "moo";
runtimeInputs = [ pkgs.cowsay ];
text = "cowsay moo";
};
});
}
```
], [
#v(4.5cm)
```txt
_____
< moo >
-----
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
```
])
]
#slide[
== Development #footnote("Example 2")
#set text(14pt)
#grid(
columns: 2, gutter: 2cm, [
*Shell*:
- `nix develop` // starts a bash, cleans everything
- `direnv` // keep your current shell, enter a dir, it auto activates, leaves the dir, auto deactivates
#v(2em)
```nix
devShells.default = pkgs.mkShell {
packages = with pkgs; [
cargo
rustc
rustfmt
];
};
```
], [
*Formatter*:
- `nix fmt`
- a single package, or $arrow.b$
#v(2em)
```nix
formatter = pkgs.writeShellScriptBin "formatter" ''
set -eoux pipefail
shopt -s globstar
${pkgs.nixpkgs-fmt}/bin/nixpkgs-fmt .
${pkgs.rustfmt}/bin/rustfmt **/*.rs
'';
```
],
)
]
#slide[
== Pinning
#set text(14pt)
#grid(
columns: 2, gutter: 2cm, [
*w/ builtin versions*: // for most critical and popular packages: llvm, gcc, node, ...
```shell
nix-repl> pkgs.coq_8_
pkgs.coq_8_10 pkgs.coq_8_12
pkgs.coq_8_14 pkgs.coq_8_16
pkgs.coq_8_18 pkgs.coq_8_5
pkgs.coq_8_7 pkgs.coq_8_9
...
```
#v(2em)
*w/ `nix shell`*:
```shell
nix shell nixpkgs/<hash>#{pkg1,...}
```
#v(2em)
*or DIY!*
], [
*w/ flakes*:
```nix
inputs = {
nixpkgsForA.url = "github:nixos/nixpkgs/<branch or hash>";
nixpkgsForB.url = "github:nixos/nixpkgs/<branch or hash>";
...
};
outputs = { self, ... }: {
...
pkgsA.<some pkg>;
pkgsB.<some pkg>;
...
};
```
],
)
]
#slide[
== Build System #footnote("Example 3")
Example: `eJS`
- Combine multiple build tools (`ant`, `make`, ...)
- Build multiple targets (binary target, jar, ...)
- Wrap programs
- ...
]
#slide[
== System Configuration #footnote("Ugawa lab infra")
#set text(18pt)
i.e. NixOS
```nix
outputs = { nixpkgs, ... }: {
nixosConfigurations.test = nixpkgs.lib.nixosSystem {
modules = [ /* a list of modules goes here */ ];
};};
```
*System Closure*: ```shell
nix build .#nixosConfigurations.test.config.system.build.toplevel
```
*Rebuild*: ```shell
nixos-rebuild <switch|boot|...> --flake .#test
```
]
#slide[
== Resources
- Installer: https://github.com/determinatesystems/nix-installer
- REPL is your friend: `nix repl`
- Intro: https://zero-to-nix.com
- Mannual: https://nixos.org/manual/nix/unstable/
- Forum: https://discourse.nixos.org
- Options: https://mynixos.com
- Source code search:
- https://github.com/features/code-search
- https://sourcegraph.com
]
|
https://github.com/bojohnson5/iu_dissertation | https://raw.githubusercontent.com/bojohnson5/iu_dissertation/main/README.md | markdown | MIT License | # iu_dissertation
Typst template for IU Bloomington dissertations.
The template function is found in `iu_dissertation.typ`
with an example `main.typ` file and PDF included.
|
https://github.com/mitinarseny/invoice | https://raw.githubusercontent.com/mitinarseny/invoice/main/src/signature.typ | typst | #import "./utils.typ": format_date
#let signature(
date,
location,
name,
sign,
) = {
grid(
columns: (2fr, 1fr),
align: center,
table(
columns: (1fr, 1fr),
stroke: none,
align: (right, left),
[Date:],
[*#format_date(date)*],
..if location != none {(
[Location:],
[*#location*],
)},
[The contractor:],
[*#name*],
),
sign,
)
} |
|
https://github.com/antran22/typst-cv-builder | https://raw.githubusercontent.com/antran22/typst-cv-builder/main/lib/resume-template.typ | typst | MIT License | #import "./resume/layout.typ": *
#import "./resume/education.typ": *
#import "./resume/experiences.typ": *
#import "./resume/skills.typ": *
#import "./resume/projects.typ": *
#import "./resume/header.typ": *
#import "./resume/certification.typ": *
#let default-config = yaml("/data/default-config.yml")
#let config = default-config + yaml(sys.inputs.at("config", default: "/data/default-config.yml"))
#let profile-picture = image("/data/" + config.at("avatar", default: "avatar.jpg"), fit: "cover", width: 2cm, height: 2cm)
#let basic_info = yaml("/data/basic.yml")
#show: ResumeLayout.with(
basic_info: basic_info,
date: datetime.today().display(),
language: config.lang,
)
#let HeaderSection = [
#ResumeHeader(
basic_info: basic_info,
profile-picture: profile-picture,
positions: config.positions,
)
]
#let SectionMap = (:)
#SectionMap.insert(
"about",
[
= About me
#pad(
text(
size: 10pt,
cmarker.render(config.about),
)
)
]
)
#SectionMap.insert(
"certifications",
ResumeCertificationSection(
pull_entries(
yaml("/data/certification.yml"),
only: config.certifications,
),
column_count: 1
)
)
#SectionMap.insert(
"educations",
ResumeEducationSection(
pull_entries(
yaml("/data/education.yml"),
only: config.educations,
),
column_count: 1
)
)
#SectionMap.insert(
"languages",
ResumeSkillsSection(
basic_info.languages,
column_count: basic_info.languages.len(),
title: "Languages"
)
)
#SectionMap.insert(
"experiences",
ResumeExperienceSection(
pull_entries(
yaml("/data/experience.yml"),
only: config.experiences,
)
)
)
#SectionMap.insert(
"projects",
ResumeProjectsSection(
pull_entries(
yaml("/data/projects.yml"),
only: config.projects,
)
)
)
#SectionMap.insert(
"tech-skills" ,
ResumeSkillsSection(
pull_entries(
yaml("/data/tech-skill.yml"),
only: config.tech_skills,
)
)
)
#SectionMap.insert(
"soft-skills" ,
ResumeSkillsSection(
pull_entries(
yaml("/data/soft-skills.yml"),
only: config.soft_skills,
),
title: "Soft Skills",
column_count: 2,
)
)
#SectionMap.insert(
"interests",
ResumeSkillsSection(
pull_entries(
yaml("/data/interest.yml"),
only: config.interests
),
title: "Interests & Hobbies",
column_count: 2,
)
)
#let DisplayedSections = (HeaderSection,)
#for sec_name in config.sections {
if sec_name in SectionMap {
DisplayedSections.push(SectionMap.at(sec_name))
}
}
#stack(
dir: ttb,
spacing: config.layout.at("section_spacing", default: 30) * 1pt,
..DisplayedSections
)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/opticalsize_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test prime/double prime via scriptsize
#let prime = [ \u{2032} ]
#let dprime = [ \u{2033} ]
#let tprime = [ \u{2034} ]
$ y^dprime-2y^prime + y = 0 $
$y^dprime-2y^prime + y = 0$
$ y^tprime_3 + g^(prime 2) $
|
https://github.com/Midoria7/ComputerNetworkLab2 | https://raw.githubusercontent.com/Midoria7/ComputerNetworkLab2/main/essay.typ | typst | #import "template.typ": *
#import "@preview/subpar:0.1.0"
#import "@preview/tablex:0.0.8": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#set page(
header: align(right)[
#text(0.9em, "计算机网络实验二")
],
numbering: "1",
)
#show: project.with(
title: "网络协议分析实验",
authors: (
"计算机学院 谢牧航 2022211363",
),
)
#align(center)[
#set par(justify: false)
#block(text(weight: 700, 1.7em, "目录"))
]
#outline(
title: auto,
indent: auto,
)
#pagebreak(weak: true)
= 实验内容和实验环境描述
= 实验步骤和协议分析
== IP协议分析
=== 捕获短 IP 分组
输入命令 `ping 10.3.9.161`,将 Wireshark 过滤器设置为 `icmp`,捕获到数个 ICMP 数据包,其中一个由 `10.3.9.161` 发回的数据包的 IP 包头如下:
#block(
figure(
image("./image/ip-1.png", width: 100%),
caption: [
捕获到的短 IP 协议数据包头
],
)
)
=== 捕获长 IP 分组
输入命令 `ping 10.3.9.161 -l 8000 -n 1`,向目的主机发送一个长度为 8000 字节的 ICMP 数据包。Wireshark 过滤器设置为 `ip.dst == 10.29.180.42`,捕获到一组六个 ICMP 数据包如下。
#block(
figure(
image("./image/ip-2.png", width: 100%),
caption: [
捕获到的长 IP 协议数据分片
],
)
)
以下展示第一个分片的 IP 包头内容和最后一个分片的 IP 包头内容:
#subpar.grid(
figure(image("./image/ip-3.png"), caption: [
第一个分片的 IP 包头内容
]), <a>,
figure(image("./image/ip-4.png"), caption: [
最后一个分片的 IP 包头内容
]), <b>,
columns: (1fr, 1fr),
caption: [长 IP 数据包头详细信息],
label: <full>,
)
=== IP 包头内容分析
短 IP 分组:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[Version & HL(1)], [`45`], [版本:IPv4,头长度:20字节],
[DSCP (1)], [`00`], [服务类型:正常时延,正常吞吐量,正常可靠性],
[Total Length (2)], [`00 3c`], [总长度:60字节],
[Identification (2)], [`d5 b3`], [分组标识:`0xd5b3`],
[Flags (1)], [`00`], [标志:MF = 0, DF = 0,允许分片,此片为最后一片],
[Fragment Offset (1)], [`00`], [片偏移:偏移量为0],
[TTL (1)], [`3b`], [生存周期:每跳生存时间为59秒],
[Protocol (1)], [`01`], [协议:ICMP协议],
[Header CheckSum (4)], [`d8 22`], [头部校验和:`0xd822`],
[Source IP Address (4)], [`0a 03 09 a1`], [源地址:`10.3.9.161`],
[Destimation IP Address (4)], [`0a 1d b4 2a`], [目标地址:`10.29.180.42`],
)
长 IP 分组(第一个分片):
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[Version & HL(1)], [`45`], [版本:IPv4,头长度:20字节],
[DSCP (1)], [`00`], [服务类型:正常时延,正常吞吐量,正常可靠性],
[Total Length (2)], [`05 dc`], [总长度:1500字节],
[Identification (2)], [`e0 da`], [分组标识:`0xe0da`],
[Flags (1)], [`20`], [标志:MF = 0, DF = 1,允许分片,此片不是最后一片],
[Fragment Offset (1)], [`00`], [片偏移:偏移量为0],
[TTL (1)], [`3b`], [生存周期:每跳生存时间为59秒],
[Protocol (1)], [`01`], [协议:ICMP协议],
[Header CheckSum (4)], [`a7 5b`], [头部校验和:`0xa75b`],
[Source IP Address (4)], [`0a 03 09 a1`], [源地址:`10.3.9.161`],
[Destimation IP Address (4)], [`0a 1d b4 2a`], [目标地址:`10.29.180.42`],
)
六个分组的区别分别为 MF 标志位和 Fragment Offset 字段。
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*分组序号*], [*MF标志位*], [*分段偏移量*], [*数据长度*],
/* -------------- */
[14], [1], [0], [1480],
[15], [1], [1480], [1480],
[16], [1], [2960], [1480],
[17], [1], [4440], [1480],
[18], [1], [5920], [1480],
[19], [0], [7400], [608],
)
=== IP 包头问题解答
+ *包头校验和验证(以短 IP 分组为例)*
IP首部的检验和不采用复杂的CRC检验码而采用下面的简单计算方法:
在发送方,先把IP数据报首部划分为许多16位字的序列,并把检验和字段置零。用反码算术运算把所有16位字相加后,将得到的和的反码写入检验和字段。
接收方收到数据报后,将首部的所有16位字再使用反码算术运算相加一次。将得到的和取反码,即得出接收方检验和的计算结果。
若首部未发生任何变化,则此结果必为0,于是就保留这个数据报。否则即认为出差错。
以短 IP 分组为例,其头部校验和为`0xd822`,计算过程如下:
`ffff - (4500 + 003c + d5b3 + 0000 + 3b01 + 0a03 + 09a1 + 0a1d + b42a) = d822`
+ *分片的 MF 标志位和分段偏移量*
IP数据报分片时,每个分片的标志字段中的MF(More Fragment)位和DF(Don't Fragment)位用于指示分片的情况。MF位为1表示后面还有分片,为0表示这是最后一个分片;DF位为1表示不允许分片,为0表示允许分片。
分段偏移量字段指示了当前分片在原始数据报中的位置。第一个分片的偏移量为0,后续分片的偏移量为前一个分片的偏移量加上前一个分片的数据长度。
以长 IP 分组为例,其分片的 MF 标志位和分段偏移量如下:
- 第一个分片:MF = 1,分段偏移量 = 0
- 第二个分片:MF = 1,分段偏移量 = 1480
- 第三个分片:MF = 1,分段偏移量 = 2960
- 第四个分片:MF = 1,分段偏移量 = 4440
- 第五个分片:MF = 1,分段偏移量 = 5920
- 第六个分片:MF = 0,分段偏移量 = 7400
从分段偏移量可以看出,每个分片的数据长度为1480字节,这是因为原始数据包的长度为8000字节(实际上是8008字节,因为ICMP协议的规定,报文会包含产生ICMP差错报文的IP数据包的前8个字节),超过了以太网的最大传输单元(MTU),因此需要分片传输。而以太网数据链路层的最大传输单元为1500字节,去除IP首部的20字节,剩下1480字节。而最后一段的数据长度为608字节,因为原始数据包的长度为8000字节,减去前五个分片的总长度($1480 times 5 = 7400$),剩下的就是608字节。
#pagebreak(weak: true)
== ICMP协议分析
#pagebreak(weak: true)
== DHCP协议分析
=== 捕获 DHCP 协议数据包
在 Wireshark 软件中输入过滤器 `udp port 67`,在终端执行 `ipconfig -release` 和 `ipconfig -renew`,过滤出四个 DHCP 协议数据包如图。
#figure(
image("./image/dhcp-1.png", width: 100%),
caption: [
捕获到的 DHCP 协议数据包
],
)
#subpar.grid(
figure(image("./image/dhcp-2.png"), caption: [
DHCP Discover
]), <a>,
figure(image("./image/dhcp-3.png"), caption: [
DHCP Offer
]), <b>,
figure(image("./image/dhcp-4.png"), caption: [
DHCP Request
]), <c>,
figure(image("./image/dhcp-5.png"), caption: [
DHCP Ack
]), <d>,
columns: (1fr, 1fr),
caption: [DHCP 协议数据包详细信息],
label: <full>,
)
=== DHCP 数据包内容分析
DHCP Discover:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[OP (1)], [`01`], [消息类型:引导请求],
[HTYPE (1)], [`01`], [硬件地址类型:以太网],
[HLEN (1)], [`06`], [硬件地址长度:6],
[HOPS (1)], [`00`], [经过的DHCP中继的数目:0],
[XID (4)], [`78 1e 61 7e`], [处理ID,标记一次IP地址请求过程:`0x781e617e`,后面ID相同的数据包属于同一次DHCP请求],
[SECS (2)], [`00 00`], [从获取到IP地址或者续约过程开始到现在所消耗的时间:0秒],
[FLAGS (2)], [`00 00`], [标记:第一位为0,表示单播],
[CIADDR (4)], [`00 00 00 00`], [客户端IP地址],
[YIADDR (4)], [`00 00 00 00`], [服务器给你分配的IP地址],
[SIADDR (4)], [`00 00 00 00`], [在bootstrap过程中下一台服务器的地址],
[GIADDR (4)], [`00 00 00 00`], [客户端发出请求(没有经过中继)],
[CHADDR (16)], [`4c 77 cb b2 b2 59`], [客户端的MAC地址],
[CHADDR Padding (10)], [`00 00 00 00 00 00 00 00 00 00`], [MAC地址填充],
[SNAME (64)], [`00 00 ...`], [为客户端分配IP地址的服务器域名:未给出],
[FILE (128)], [`00 00 ...`], [为启动客户端指定的配置文件路径:未给出],
[Magic Cookie(4)], [`63 82 53 63`], [可选字段的格式:DHCP],
[OPTION (3)], [`35 01 01`], [DHCP消息类型:Discover],
[OPTION (9)], [`3d 07 01 4c 77 cb b2 b2 59`], [客户端标识符:以太网,MAC地址`4c:77:cb:b2:b2:59`],
[OPTION (6)], [`32 04 0a 1d b4 2a`], [请求的IP地址:`10.29.180.42`],
[OPTION (17)], [`0c 0f ...`], [主机名,长度为15],
[OPTION (8)], [`3c 08 ...`], [供应商标识符,长度为8],
[OPTION (16)], [`37 0e ...`], [参数需求列表,长度为14],
[OPTION (1)], [`ff`], [选项字段结束],
)
以下忽略重复部分,展示各数据包不同的部分:
DHCP Offer:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[OP (1)], [`02`], [消息类型:引导回复],
[HOPS (1)], [`01`], [经过的中继的数目:1],
[YIADDR (4)], [`0a 1d b4 2a`], [服务器分配的地址:`10.29.180.42`],
[GIADDR (4)], [`0a 1d 00 01`], [客户端发出请求分组后经过的第一个中继的地址:`10.29.0.1`],
[OPTION (3)], [`35 01 02`], [DHCP消息类型:Offer],
[OPTION (6)], [`36 04 0a 03 09 02`], [DHCP服务器标识符:`10.3.9.2`],
[OPTION (6)], [`33 04 00 00 13 8c`], [IP地址释放时间:`5004`秒],
[OPTION (6)], [`01 04 ff ff 00 00`], [子网掩码:`255.255.0.0`],
[OPTION (6)], [`03 04 0a 1d 00 01`], [路由器:`10.29.0.1`],
[OPTION (10)], [`06 0c 0a 03 09 04 0a 03 09 05 0a 03 09 06`], [域名服务器:`10.3.9.4`、`10.3.9.5`、`10.3.9.6`],
[OPTION (1)], [`ff`], [选项字段结束],
)
DHCP Request:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[OPTION (3)], [`35 01 03`], [DHCP消息类型:Request],
[OPTION (9)], [`3d 07 01 4c 77 cb b2 b2 59`], [客户端标识符:以太网,MAC地址`4c:77:cb:b2:b2:59`],
[OPTION (6)], [`32 04 0a 1d b4 2a`], [请求的IP地址:`10.29.180.42`],
[OPTION (6)], [`36 04 0a 03 09 02`], [DHCP服务器标识符:`10.3.9.2`],
colspanx(3)[...], (), (),
[OPTION (1)], [`ff`], [选项字段结束],
)
DHCP ACK:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[OP (1)], [`02`], [消息类型:引导回复],
[HOPS (1)], [`00`], [经过的DHCP中继的数目:1],
[YIADDR (4)], [`0a 1d b4 2a`], [服务器分配的地址:`10.29.180.42`],
[GIADDR (4)], [`0a 1d 00 01`], [客户端发出请求分组后经过的第一个中继的地址:`10.29.0.1`],
[OPTION (3)], [`35 01 05`], [DHCP消息类型:ACK],
colspanx(3)[...], (), (),
[OPTION (1)], [`ff`], [选项字段结束],
)
=== DHCP 分配过程和问题解答
DHCP(动态主机配置协议)是用于在网络上自动分配IP地址和其他相关配置信息的通信协议。这个过程通常包括四个主要步骤:Discover、Offer、Request、和ACK,具体如下:
+ *DHCP Discover*
客户端连接到网络后,如果需要动态IP地址,它会广播一个DHCP Discover消息。这个消息是客户端寻求可用的DHCP服务器来获取IP配置的请求。此消息中包含客户端的硬件(MAC)地址和其他识别信息。
+ *DHCP Offer*
网络上的DHCP服务器接收到Discover消息后,会对该请求做出响应,发送一个DHCP Offer消息。这个消息包括一个服务器提供给客户端的IP地址,同时还包括其他网络配置信息,如子网掩码、默认网关、DNS服务器地址等。如果网络上有多个DHCP服务器,客户端可能会收到多个Offer。
+ *DHCP Request*
客户端从一个或多个Offer中选择一个,并通过广播发送一个DHCP Request消息来请求这些网络参数。这个消息不仅重新请求先前Offer中提供的IP地址,还确认了客户端将接受哪个DHCP服务器的配置(通常是第一个收到的Offer)。
+ *DHCP ACK*
最后,DHCP服务器接收到Request后,会发送一个DHCP
ACK消息给客户端。这个ACK消息确认了IP地址和其他配置的分配,并可能包含其他详细信息,如租约的持续时间,即客户端可以保持这个IP地址的时间。成功接收到ACK消息后,客户端会配置其网络接口使用这些参数,并可以开始网络通信。
*从数据包中可以推断出关于DHCP服务器和DHCP中继(Relay)的使用情况:*
+ 是否有 DHCP Relay?
是的,存在DHCP Relay的使用。这可以从DHCP Offer和DHCP ACK消息中GIADDR字段的值判断。GIADDR(Gateway IP Address)字段在DHCP Relay环境中用来标识客户端请求消息首次经过的DHCP Relay代理的IP地址。在这些消息中,GIADDR被设置为`0a 1d 00 01`(即`10.29.0.1`),且HOPS字段为1,表明请求在到达DHCP服务器前经过了恰好一个DHCP Relay。
+ DHCP Server 是否由路由器充当?
由服务器标识符(DHCP Server Identifier)选项看出,DHCP服务器的IP地址是`10.3.9.2`。这个地址不是我的网关地址(`10.29.0.1`),因此DHCP服务器不是由我的路由器充当的。查询可知,这个地址是北京邮电大学的DHCP服务器地址。
#figure(
image("./image/dhcp-6.png", width: 80%),
caption: [
DHCP 地址分配过程的消息序列图
],
)
#pagebreak(weak: true)
== ARP 协议分析
=== 捕获 ARP 协议数据包
执行 `ipconfig -release` 和 `ipconfig -renew` 释放和续约 IP 地址,Wireshark 过滤器输入 `arp`,捕获到四种 ARP 协议数据包如下:
#subpar.grid(
figure(image("./image/arp-1.png"), caption: [
ARP Probe
]), <a>,
figure(image("./image/arp-2.png"), caption: [
ARP Announcement
]), <b>,
figure(image("./image/arp-3.png"), caption: [
ARP Request
]), <c>,
figure(image("./image/arp-4.png"), caption: [
ARP Reply
]), <d>,
columns: (1fr, 1fr),
caption: [ARP 协议数据包详细信息],
label: <full>,
)
查询可知,还有一种免费 ARP 包(Gratuitous ARP),免费ARP数据包是主机发送ARP查找自己的IP地址。通常,它发生在系统引导期间进行接口配置的时候。通过以太网线与另一台主机相连,重启另一台主机后捕获到 Gratuitous ARP 数据包如下:
#block(
figure(
image("./image/arp-6.png", width: 100%),
caption: [
捕获到的 Gratuitous ARP 数据包
],
)
)
通过以太网线和另一台主机相连,并手动将两者的 IP 地址设置为同一地址,可以捕获到 IP 地址冲突时的 ARP 数据包:
#subpar.grid(
figure(image("./image/arp-7.png"), caption: [
ARP 冲突时的现象
]), <a>,
figure(image("./image/arp-8.png"), caption: [
ARP Announcement(主机1)
]), <b>,
figure(image("./image/arp-9.png"), caption: [
ARP Request(主机1)
]), <c>,
figure(image("./image/arp-10.png"), caption: [
ARP Reply(主机2)
]), <d>,
columns: (1fr, 1fr),
caption: [ARP 冲突时的协议数据包详细信息],
label: <full>,
)
=== ARP 数据包内容分析
分析 ARP 数据包组成如下。一开始未分配 IP,IP 地址询问经过了 `169.254.101.246` -> `10.29.180.42` 的分配过程。以下展示了分配 `10.29.180.42` 后的 ARP 数据包内容:
ARP Probe:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[HTYPE (2)], [`00 01`], [硬件类型:以太网],
[PTYPE (2)], [`08 00`], [协议类型:IPv4],
[HLEN (1)], [`06`], [硬件地址长度:6],
[PLEN (1)], [`04`], [协议地址长度:4],
[OPER (2)], [`00 01`], [ARP消息类型:request],
[SHA (6)], [`4c 77 cb b2 b2 59`], [发送方MAC地址:`4c:77:cb:b2:b2:59`],
[SPA (4)], [`00 00 00 00`], [发送方IP地址:`0.0.0.0`(未分配状态)],
[THA (6)], [`00 00 00 00 00 00`], [接收方MAC地址(未知)],
[TPA (6)], [`a9 fe 65 f6`], [接收方IP地址:`10.29.180.42`,查询是否被分配],
)
分配后,本机会宣布 ARP Announcement:
ARP Announcement:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[SHA (6)], [`4c 77 cb b2 b2 59`], [发送方MAC地址:`4c:77:cb:b2:b2:59`],
[SPA (4)], [`a9 fe 65 f6`], [发送方IP地址:`10.29.180.42`],
[THA (6)], [`00 00 00 00 00 00`], [接收方MAC地址(未知)],
[TPA (6)], [`a9 fe 65 f6`], [接收方IP地址:`10.29.180.42`],
)
此时询问 `10.29.0.1` 的地址:
ARP Request:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[SHA (6)], [`4c 77 cb b2 b2 59`], [发送方MAC地址:`4c:77:cb:b2:b2:59`],
[SPA (4)], [`a9 fe 65 f6`], [发送方IP地址:`10.29.180.42`],
[THA (6)], [`00 00 00 00 00 00`], [接收方MAC地址(未知)],
[TPA (6)], [`a9 1d 00 01`], [接收方IP地址:`10.29.0.1`],
)
最后,收到 `10.29.0.1` 的回复:
ARP Reply:
#tablex(
columns: 3,
align: center + horizon,
auto-vlines: true,
repeat-header: true,
/* --- header --- */
[*字段 (字节数)*], [*内容(16进制)*], [*解释*],
/* -------------- */
[SHA (6)], [`10 4f 58 6c 0c 00`], [发送方MAC地址:`10:4f:58:6c:0c:00`],
[SPA (4)], [`a9 1d 00 01`], [发送方IP地址:`10.29.0.1`],
[THA (6)], [`4c 77 cb b2 b2 59`], [接收方MAC地址:`4c:77:cb:b2:b2:59`],
[TPA (6)], [`a9 1d 00 01`], [接收方IP地址:`10.29.0.1`],
)
=== ARP 工作流程
ARP协议(地址解析协议)是网络通信中用于将网络层的IP地址转换为数据链路层的MAC地址的关键协议。以下是ARP协议的基本工作流程:
+ #strong[冲突检测];:
- ARP Probe 和 ARP Announcement 用于检测 IP 地址冲突。ARP Probe 用于查询是否有其他设备使用了自己的 IP 地址,而 ARP Announcement 用于通知其他设备自己的 IP 地址。
+ #strong[发起ARP请求];:
- 当一个设备(例如,计算机A)需要将数据包发送到另一个设备(例如,计算机B),但只知道目标设备的IP地址时,它需要先获得目标设备的MAC地址。
- 设备A会在本地ARP缓存中查找是否已经有IP地址到MAC地址的映射。如果找到了,直接使用这个映射发送数据。
- 如果没有找到,设备A会构建一个ARP Request包,其中包含自己的IP地址和MAC地址,以及目标设备的IP地址。目标MAC地址字段填充为广播地址。
+ #strong[广播ARP请求];:
- 设备A将这个ARP Request包通过网络广播给同一局域网(LAN)上的所有设备。每个接收到请求的设备都会检查ARP包中的“目标IP地址”,以确定是否为自己的IP地址。
+ #strong[接收和响应ARP请求];:
- 如果一个设备(例如,计算机B)发现ARP请求中的目标IP地址与自己的IP地址匹配,它将构建一个ARP Reply包。在这个响应包中,它会填充自己的IP地址和MAC地址,并将发送者的IP和MAC地址设置为原ARP请求中的值。
- 然后计算机B将这个ARP响应包直接发送给原请求的发送者(计算机A),而不是广播。
+ #strong[更新ARP缓存];:
- 一旦计算机A接收到来自计算机B的ARP响应,它将解析出B的MAC地址,并将这个IP地址到MAC地址的映射存储在本地ARP缓存中。这样,未来发送到同一IP地址的数据可以直接使用这个映射,无需再次发送ARP请求。
- 这个映射通常会在ARP缓存中保留一段时间,然后过期删除,以应对网络配置的可能变更。
- 这个功能通常通过 Gratuitous ARP 包来实现,即设备定期发送ARP响应包来更新网络中其他设备的ARP缓存。
+ #strong[数据传输];:
- 有了目标MAC地址后,计算机A可以将数据包封装在以太网帧中,并设置正确的目标MAC地址,通过物理网络发送给计算机B。
这个过程确保了即使在只知道目标IP地址的情况下,数据也能被正确地发送到目标设备。ARP协议是局域网通信中不可或缺的一部分,它使得IP层和MAC层的转换成为可能。
#pagebreak(weak: true)
== TCP 协议分析
#pagebreak(weak: true)
= 实验结论和实验心得 |
|
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/pre-reveal.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: "Pre Reveal Thoughts",
type: "identify",
date: datetime(year: 2023, month: 4, day: 26),
author: "<NAME>",
witness: "<NAME>",
)
= Reflection on Last Season
53E grew greatly as a team during the last season on both the building side and
the programming side. We struggled to build a robot that could complete all of
the tasks in the Spin Up season. This was mainly due to overall inexperience and
lack of planning. While we did make an attempt to use CAD #footnote("See glossary")<nb_gl>,
we never really ended up with a 1 to 1 mirror of the robot digitally. More often
than not, we would simply put parts together and seeing what would work, rather
than planning it out beforehand. This lead to us being very behind, often
building on our robot at tournaments. Despite these challenges we eventually
built a fully functional robot and even made it to the state championship.
Our programming also had mixed successes. One of our big achievements was
working collaboratively. We were able to have two programmers working together
on the same team working on the code at the same time. As far as we are aware,
this is the first time in the club's history that this has worked. We did this
using git #footnote(<nb_gl>) and GitHub, #footnote(<nb_gl>) which let us easily
sync code across both programmer's computers. However we did not meet our major
goal of implementing odometry #footnote(<nb_gl>) in order to track our robot's
position on the field during the autonomous period. Complex algorithms like
odometry #footnote(<nb_gl>) require a lot of testing in order to be effective,
and we chose to prioritize getting a functioning robot over implementing it.
= Goals
== Team Management
- Create and adhere to a schedule of when planning, building, programming, and
testing should occur
- Create a more organized team structure
== Building
- Create a more structured process for planning and testing work
- Design everything system before building, using CAD software
- Undergo more rigorous testing before tournaments
== Programming
- Implement odometry
- Program an autonomous routine that can cross the field with minimal error
buildup.
Overall we are much better prepared for this season than we were the last. Our
team is much more capable, not just in the realm of design and building, but
also in our ability to write powerful and reliable software.
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-16FE0.typ | typst | Apache License 2.0 | #let data = (
"0": ("TANGUT ITERATION MARK", "Lm", 0),
"1": ("NUSHU ITERATION MARK", "Lm", 0),
"2": ("OLD CHINESE HOOK MARK", "Po", 0),
"3": ("OLD CHINESE ITERATION MARK", "Lm", 0),
"4": ("KHITAN SMALL SCRIPT FILLER", "Mn", 0),
"10": ("VIETNAMESE ALTERNATE READING MARK CA", "Mc", 6),
"11": ("VIETNAMESE ALTERNATE READING MARK NHAY", "Mc", 6),
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.0/template/content/02.typ | typst | Apache License 2.0 | /** 02.typ
*
* This is an example chapter in a multi-file typst project.
*
***/
#import "../preamble.typ": *
#import "@preview/scholarly-tauthesis:0.4.0" as tauthesis
= Writing practices <writing-practices>
Effective written communication requires both sound content and clear style.
Keep the layout of your thesis neat and pay attention to your writing style.
== Text <text>
Do not worry about the layout of the text, this template takes care of it
already. Brief basics of writing style:
- Always think of your reader when you are writing and proceed logically from
general to specific.
- Highlight your key points, for example, by discussing them in a
separate section or subsection, or presenting them in a table
or figure. Use _italics_ (`_text_`) for emphasis, but don’t
overdo it.
- Avoid long sentences and complicated statements. A full stop is
the best way
to end a sentence.
- Use active verbs to make a dynamic impression but avoid the
first person pronoun I, except in your preface.
- Avoid jargon and wordiness. Use established terminology and
neutral language.
- The minimum length of sections and subsections is two
paragraphs, and you need to consider the balance of chapters.
Paragraphs must always consist of more than one sentence.
- Do not use more than three levels of numbered headings, such as
$4.4.2$. However, keep in mind that $3$ different levels of
sections is already a bit much.
- Do not use too many abbreviations. Use capital and small
letters consistently. You might wish to define new commands in
the `preamble.typ` file, for words you do not wish to misspell.
For example, the `preamble.typ` file defines the command `#eeg`,
which is typeset as #eeg.
== Images <figures>
You must refer to all the images in the body text. The reference should
preferably appear on the same page as the actual image or before it. Images and
tables must be numbered consistently and primarily placed at the top of the
page, but you are free to decide where they fit best. typst takes care of the
numbering, if you specify a unique label `<label-name>` right after the a image
or a table. Cross-referencing is done by prefixing the identifier inside the
angle brackets with a `@` symbol: `@label-name`. For example, the code
```typst
#figure(
image(
"../images/tau-logo-fin-eng.svg",
width: 80%
),
caption: [Tampere University logo.],
) <tau-logo>
```
is rendered as seen in @tau-logo:
#figure(
image(
"../images/tau-logo-fin-eng.svg",
width: 80%
),
caption: [Tampere University logo. @tau-logo-image],
) <tau-logo>
Never start or end a chapter with a image, table, equation or list. The caption
is placed under an image. The contents of all images must be explained in the
text body, so that the readers know what they are supposed to notice. Images
generated by analysis software usually need further editing. The figures should
be in the same language as other text. The recommended font size is the same as
that of the body text, #unitful(11, "pt"). All images must be readable, even if
your thesis is printed in greyscale. Whenever possible, use images in vector
formats such as `.svg` (typst version #version(0,11,0) does not digest `.pdf`
or `.eps` files), as they can be scaled without loss of quality.
== Tables <tables>
Tables are convenient for presenting information in a concise way, especially
numerical data. Tables have numbered captions, see @tab-evaporation-conditions
for an example. The caption is placed on the same page but above the table,
unlike the captions that accompany images. You must refer to all the tables in
the body text. In addition, you must discuss the content of any tables in the
body text to ensure that readers understand their relevance.
Mark the titles of the columns and units clearly. You can use underscores
`_emph_` to highlight the titles, if necessary. The order of the columns and
rows must be carefully considered. Ideally, all cells should _not_ be
surrounded with a border, as it may make your table harder to read. The numbers
should be aligned at the decimal point for easy comparison. You should
preferably use SI units, established prefixes and rewrite large numbers so that
the power of ten should be placed in the title of the column instead of each
row, if possible. More suggestions can be found in @pubadvice2009.
To actually draw a table, we issue a ```typst #figure``` call
with a `table` as its argument:
```typst
#import table: cell, header, hline, vline
#[
#show table.cell.where(y: 0): strong
#figure(
table(
columns: 5,
stroke: none,
table.header(
[Substance],
table.vline(),
[Pressure (#unit(pascal))],
table.vline(),
[Pressure (#unit(bar))],
table.vline(),
[Pressure (#unit(mmHg))],
table.vline(),
[Temprature ($degree.c$)]
),
table.hline(),
[Mercury],
num(1.0),
num(0.0001),
num(0.0075),
num(41.85),
[Tungsten],
num(1.0),
num(0.0001),
num(0.0075),
num(3203),
),
caption: [Vapour pressures of two metals. @wikipedia-vapor-pressure],
) <tab-evaporation-conditions>
]
```
The added ```typst #[...]``` around the whole figure restricts the scope of the
show rule to this table. This results in @tab-evaporation-conditions being
displayed:
#[
#import table: cell, header, hline, vline
#show table.cell.where(y: 0): strong
#figure(
table(
columns: 5,
stroke: none,
table.header(
[Substance],
table.vline(),
[Pressure (#unit(pascal))],
table.vline(),
[Pressure (#unit(bar))],
table.vline(),
[Pressure (#unit(mmHg))],
table.vline(),
[Temprature ($degree.c$)]
),
table.hline(),
[Mercury],
num(1.0),
num(0.0001),
num(0.0075),
num(41.85),
[Tungsten],
num(1.0),
num(0.0001),
num(0.0075),
num(3203),
),
caption: [Vapour pressures of two metals. @wikipedia-vapor-pressure],
) <tab-evaporation-conditions>
]
A table should not end a section. That is why after every table
we state some observations about the table. Here we notice that
mercury and tungsten have identical vapour pressures, but at very
different tempratures.
== Mathematical notation and equations <equations>
Numbers are generally written using numerals for the sake of clarity, for
example "6 stages" rather than "six stages", which is nevertheless strongly
preferred to "a couple of stages". You should also use a thousand separator,
i.e. instead of $55700125$ write #num(55700125). Never omit the leading zero in
decimals. A comma is used as a decimal separator in the Finnish language and a
period in the English language.
Like numbers, it is advisable to abbreviate units of measurement. There is a
space between the number and the unit, but you must keep them on the same line.
The space is somewhat shorter than a word space, see 1.0 $mu$m and
$1.0 mu"m"$ for comparison. It is better to compile a table or graph
than include a great deal of numerical values in the body text. Use precise
language and put numbers on a scale (small, fast, expensive).
Use generally known and well defined concepts and standard conventions and
symbols for representing them. New concepts should be defined when they appear
in the text for the first time. Upper case and lower case letters mean
different things in symbols and units of measurement. Do not use the same
symbol to mean different things.
Strings of mathematical symbols such as $Theta(n^2)$ are typeset
in typst using the math mode, between dollar signs: ```typst $math$```
for inline mathematics or ```typst $ math $``` with spaces for
display math. Simple formulas may be displayed within the body of
the text without numbering. As an example of a highlighted
formula, the Fundamental theorem of calculus can be written in the
following way:
$
integral_[a,b]
f(x)
dif x
=
F(b) - F(a)
.
$ <fundamental-theorem-of-calculus>
Here $f$ is the _integrand_, $F$ its _anti-derivative_ and
$[a,b]$ the integration interval.
Please note that all the variables must be defined at the point
of their first appearance. The formulae are shown in a different
typeface on purpose and the symbols are almost always italicised.
Vectors can be written in slanted or upright boldface, or with
arrows:
$
bold(v)
&=
derivative(bold(x), t)
\
//
upright(bold(v))
&=
derivative(upright(bold(x)), t)
\
//
arrow(v)
&=
derivative(arrow(x),t)
$
The most important thing is to be consistent throughout your
thesis. Do not mix and match notations, as it will confuse the
reader. See the file `preamble.typ` for an example of how
you might define a `#vector` command for typesetting vectors
consistently. Defining a command also allows you to easily switch
notations globally, if you are not satisfied with your current
choice.
Units are written in an upright font with a normal weight, to
distinquish them from variables:
$
|vector(f)|
&=
m|vector(a)|
=
unitful(10.0, #kilo#gram)
dot
unitful(9.81, #meter/#second^2)
=
unitful(98.1, #newton)
.
$
Here $vector(f)$ is a force vector, $m$ is the mass of the object
experiencing the force, and $vector(a)$ is its acceleration
vector. Again, see the `preamble.typ` file for how you might
define commands for units.
Mathematical formulae are numbered, if they are written on
separate lines and referred to in the main body of the text. The
number is usually put in parenthesis and right aligned, see
@fundamental-theorem-of-calculus for an example. Include any punctuation
(commas, periods) surrounding an equation in the equations
themselves, as is again shown in @fundamental-theorem-of-calculus. Occasionally
the elements of mathematical text are preceded by an identifier,
such as Definition 1 or Theorem 1.
Do not start a sentence with a mathematical symbol but add some
word, such as the name or type of the symbol in front of it.
Variables, such as $x$ and $y$, are generally presented in
italics, whereas elementary functions, special functions and
multi-letter operators are not:
$
sin(2x + y)
" or "
lim_(x arrow.r -1)
(x^2 - 1) / (x + 1)
=
-2.
$ <lim-example>
As a rule of thumb, it is best to rely on the automated
formatting of an equation editor, such as the one provided by
typst.
Vectors and matrices are written with the `vec` and `mat` functions:
$
matrix(A)
vector(x)
=
mat(
A_(1,1), A_(1,2) ;
A_(2,1), A_(2,2) ;
)
vec(x_1,x_2)
=
vec(b_1,b_2)
=
vector(b)
.
$
See the typst documentation on mathematics @typst-math for examples of how
different symbols are written.
== Programs and algorithms <algorithms>
Codes and algorithms are written using a monospaced font. If the
length of the code or algorithm is less than 10 lines and you do
not refer to it later on in the text, you can present it
similarly to formulas. If the code is longer but shorter than a
page, you present like a figure titled "Listing" or "Algorithm".
In typst, code blocks are presented in backticks:
``````typst
```typst
#figure(
raw(
read("../code/square.jl"),
lang: "julia",
block : true
),
caption: [The square of $x in bb(R)$ and $x in bb(C)$, written in Julia.],
) <program-example>
```
``````
The above results in what is seen in @program-example-example:
#figure(
```typst
#figure(
raw(
read("../code/square.jl"),
lang: "julia",
block : true
),
caption: [The square of $x in bb(R)$ and $x in bb(C)$, written in Julia.],
) <program-example>
```,
caption: [ A code block.]
) <program-example-example>
and removing the backticks would actually load code from the file `code/square.jl`
to be displayed in the numbered @program-example:
#figure(
raw(
read("../code/square.jl"),
lang: "julia",
block : true
),
caption: [The square of $x in bb(R)$ and $x in bb(C)$, written in Julia.],
) <program-example>
Again, listings should not end sections. You should always
describe what is going on in the displayed code after presenting
a listing.
== Theorem blocks <theorems>
@pythagorean-theorem and @pythagoraan-lause show examples of theorem blocks:
#tauthesis.example(
title: [Pythagorean theorem],
reflabel: "pythagorean-theorem"
)[
For sides $a$, $b$ and $c$ of a right triangle, where $c$ is the _hypotenuse_, the following equality holds:
$
a^2 + b^2 = c^2.
$
]
#tauthesis.esimerkki(
title: [Pythagoraan lause],
reflabel: "pythagoraan-lause"
)[
Suorakulmaisen kolmion sivut $a$, $b$ and $c$, missä $c$ on _hypotenuusa_, toteuttavat yhtälön
$
a^2 + b^2 = c^2.
$
]
As one can see, these follow the same counter. The theorem box has been typeset with the command
```typst
#tauthesis.example(
title: [Pythagorean theorem],
reflabel: "pythagorean-theorem"
)[
For sides $a$, $b$ and $c$ of a right triangle, where $c$ is the _hypotenuse_, the following equality holds:
$
a^2 + b^2 = c^2.
$
]
```
Notice that the reference label is not placed after the function call,
but given as a named argument to the function.
The module `tauthesis` defines the theorem box functions
- `definition`,
- `theorem`,
- `lemma`,
- `corollary` and
- `example`,
and their Finnish equivalents
- `määritelmä`,
- `lause`,
- `apulause`,
- `seurauslause` and
- `esimerkki`.
These all follow the same counter, and can all be referenced by
suffixing the equivalent function call with a tag.
Try not to overuse these, however. Academic theses should _not_ be written in
the _Landau style_, where the entire text consists of definitions after
definitions and theorems after theorems. There should always be a full
paragraph between two theorems or other objects, such as figures and tables.
|
https://github.com/a-kkiri/SimpleNote | https://raw.githubusercontent.com/a-kkiri/SimpleNote/main/content/chapter2.typ | typst | Apache License 2.0 | #import "../template.typ": *
= 使用示例
== 特殊记号
你可以 Typst 的语法对文本进行#highlight[特殊标记],我们为如下标记设定了样式:
#enum(
[*突出*],
[_强调_],
[引用 @figure],
[脚注 #footnote("脚注例")],
)
== 代码
行内代码使用例 `println!("Hello, typst!")`,下面是代码块使用例:
#figure(
```rust
fn main() {
println!("Hello, typst!");
}
```,
caption: [代码块插入例]
) <cpp-example>
== 图片 <figure>
#figure(caption: [图片插入例])[#image("../figures/typst.png")]<image-example>
== 表格
#figure(caption: [表格插入例])[
#table(
columns: (1fr, 1fr, 1fr),
[表头1] , [表头2] , [表头3],
[单元格1], [单元格2], [单元格3],
[单元格1], [单元格2], [单元格3],
[单元格1], [单元格2], [单元格3],
)]
== 引用块
#blockquote[
引用块例
#blockquote[
二级引用块
]
]
== 公式
行内公式,例如 $integral_123^123a+b+c$ $a^2 + b^2 = c^2$。行内公式使用 `$$` 包裹,公式和两端的 `$$` 之间没有空格$$。
行间公式,例如:$ integral.triple_(Omega)\(frac(diff P, diff x) + frac(diff Q, diff y) + frac(diff R, diff z)\)d v = integral.surf_(Sigma)P d y d z + Q d z d x + R d x d y $<eq> @eq 是高斯公式。行间公式使用 `$$` 环境包裹,公式和两端的 `$$` 之间至少有一个空格。
以上仅为一些简单的公式示例,更多的公式使用方法可以查看 #link("https://typst.app/docs/reference/math/")[typst/docs/math]
另外,如果需要插入 LaTeX 公式可以使用外部包 #link("https://typst.app/universe/package/mitex")[mitex]。
== 定理环境
#definition("定义")[#lorem(30)]
#example("示例")[#lorem(30)]
#tip("提示")[#lorem(30)]
#attention("注意")[#lorem(30)]
#quote("引用")[#lorem(30)]
#theorem("定理")[#lorem(30)]
#proposition("命题")[#lorem(30)]
#sectionline |
https://github.com/daskol/typst-templates | https://raw.githubusercontent.com/daskol/typst-templates/main/cvpr/logo.typ | typst | MIT License | #let kern(length) = h(length, weak: true)
#let TeX = style(styles => {
let e = measure(text("E"), styles)
let T = "T"
let E = text(baseline: e.height / 2, "E")
let X = "X"
box(T + kern(-0.1667em) + E + kern(-0.125em) + X)
})
#let LaTeX = style(styles => {
let l = measure(text(10pt, "L"), styles)
let a = measure(text(7pt, "A"), styles)
let L = "L"
let A = text(7pt, baseline: a.height - l.height, "A")
box(L + kern(-0.36em) + A + kern(-0.15em) + TeX)
})
#let LaTeXe = style(styles => {
box(LaTeX + sym.space.sixth + [2#text(baseline: 0.3em, $epsilon$)])
})
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/unit/per-mode/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": unit, metro-setup
#set page(width: auto, height: auto)
#unit("joule per mole per kelvin")
#unit("metre per second squared")
#metro-setup(per-mode: "fraction")
#unit("joule per mole per kelvin")
#unit("metre per second squared")
#metro-setup(per-mode: "symbol")
#unit("joule per mole per kelvin")
#unit("metre per second squared")
|
https://github.com/mariuslb/thesis | https://raw.githubusercontent.com/mariuslb/thesis/main/main.typ | typst | #import "template.typ": Template, code
#import "@preview/glossarium:0.3.0": gls
#let translations = json("translations.json").at("de")
#show: Template.with(
bib: arguments("sources.bib", style: "frontiers"),
appendix: (
[
#heading("Struktur einer Fahrtaufzeichnung",supplement: [#translations.appendix])
#include "code-anhang/str-data.typ"
],
[
#heading("Wichtiger Anhang",supplement: [#translations.appendix])
#lorem(100)
],
[
#heading("Weiterer Wichtiger Anhang",supplement: [#translations.appendix]) <ref>
#lorem(100)
]
),
show_lists_after_content: false,
confidental_clause: true,
abbreviation_entries: (
( key: "oidc", short: "OIDC", long: "Open ID Connect" ),
( key: "lcmm", short: "LCMM", long: "Low Carbon Mobility Management"),
( key: "wltp", short: "WLTP", long: "Worldwide Harmonized Light Vehicles Test Procedure"),
( key: "tsi", short: "TSI", long: "T-Systems International GmbH"),
( key: "ev", short: "EVs", long:"Elektrofahrzeuge"),
( key: "ice", short: "ICEs", long: "Fahrzeuge mit Verbrennungsmotor")
),
glossary_entries: (
( key: "haus", short: "Haus", long: "Besteht aus 4 Wänden und einem Dach" ),
( key: "datascience", short: "Data Science", long: "Interdisziplinäres Feld, das Methoden aus Mathematik, Statistik und Informatik nutzt, um Wissen und Erkenntnisse aus großen Datenmengen zu gewinnen")
),
ai_entries: (
( "OpenAI ChatGPT", "Schreib meine Bachelorarbeit", "Bachelorarbeit schreiben lassen und lieber Fortnite zocken" ),
( "Google Gemini", "Gib mir Motivationstipps", "Die Nerven beibehalten" )
)
)
#include "content/01-einleitung.typ"
#include "content/02-theorie.typ"
#include "content/03-methodik.typ"
#include "content/04-analyse.typ"
#include "content/05-ergebnisse.typ"
#include "content/06-diskussion.typ"
// = Kein Teil
// = Einleitung
// #lorem(15)
// Wenn ich @oidc zum ersten mal erwähne wird es ausgeschrieben. \
// Beim zweiten Mal wird @oidc nur abgekürzt.
// Übrigens gibt es das @haus
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045%20-%20Kamigawa%3A%20Neon%20Dynasty/007_The%20Blade%20Reflected%20and%20Reborn.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Blade Reflected and Reborn",
set_name: "Kamigawa: Neon Dynasty",
story_date: datetime(day: 07, month: 02, year: 2022),
author: "<NAME>",
doc
)
Seven heads gathered around the shrine at the heart of the problem, young and old alike—unusual in a neighborhood like Far Corner, where it was usually just the old. Chishiro eyed their reverence from the roof of the brewery storehouse where he'd been invited to sleep. They wouldn't see him if they turned; though he was large, he had more than enough skill to conceal himself in the shadows.
Not that he expected the worshippers to pay heed of anything but that damnable shrine.
Ayari, a young local woman who crouched beside Chishiro, saw the tension in his arms: three crossed over his chest, a fourth massaging his scaled jaw.
"They're afraid," she said defensively.
"Are they?" Chishiro asked. Ayari did not respond, and he shrugged it off. "I suppose they are."
When he'd arrived in Far Corner, Chishiro had thought the worshippers foolish. The locals had hired him for his grim reputation; they knew the worst stories about him, the ones that sickened softer folk because they were true, and therefore gruesome. They thought his cunning and willingness to kill for any promise of coin would keep their heads attached to their necks. So, he thought, surely they would obey his orders, if only he glowered and laid a hand on his sharp silver blade. He had told them never to travel alone; to remain indoors, whenever possible; and to fastidiously observe their daily routines, lest their scheme be uncovered.
#figure(image("007_The Blade Reflected and Reborn/01.jpg", width: 100%), caption: [Chishiro, the Shattered Blade | Art by: <NAME>], supplement: none, numbering: none)
But no matter how often Chishiro instructed the people of Far Corner to stop clustering around that strange little shrine at the end of the neighborhood's main street, he was ignored. Inevitably, they would come, one at a time, to kneel and gaze upon the shrine with a dreamy reverence, like sleep-drunk children listening to a favored grandparent's stories.
In any case, they couldn't be allowed to stay—especially not now, with death breathing so rankly down their necks.
Chishiro bared his fangs at Ayari. "Tell them to get back inside before they make any more mistakes."
She frowned at him but slid down the tiled roof and hopped from the edge to the hard black pavement below. A spry young woman, already scarred on her arms and face, Ayari had designated herself Chishiro's right hand (his third, she said) from the moment the elders of Far Corner hired him. She possessed a budding gift for violence, which she employed most often with her knives, fending off the Reckoner gangs who sought to take tithes from her neighbors.
Shortly after the elders hired Chishiro, he had asked them if the missing Reckoner scout who was the origin of their woes had fallen to Ayari's blades as well. The elders had exchanged quiet, tense glances and answered in vague terms. Chishiro at first assumed that they disagreed over whether their dear girl had done something so rash. However, in the days since~
He watched as Ayari approached the seven townsfolk gathered at the shrine, coaxing them to rise from their knees and return to their assigned tasks. Their lingering, glassy looks back at the lonely, desolate shrine told him all he needed to know.
When they'd all gone their separate ways, Chishiro slid down the storehouse roof. Despite his muscled bulk and the power of his tail, he dislodged no tiles and made barely a sound, even as he landed. He crossed the dusty street to regard the shrine by himself.
<NAME> lived up to its name—once a modest village on the cusp of Jukai, it had been gradually subsumed by Towashi to become one of its newest and most ignored neighborhoods. It was too removed from the towering trunk of Boseiju and the light-limned shadows of Imperial skyscrapers to be considered part of the Undercity. Then there was the untended field at the end of the paved main road, which stretched until it met the ragged edge of the receding forest.
Nearly all plants within the black-paved boundaries of Far Corner had been intentionally placed. First and foremost, a lone pair of cherry trees had been transplanted from the Undercity canals to the gate that was the formal entrance to the neighborhood.
The only other vegetation was the shrine. It had split and burst through the stone pavement at the Jukai end of the main street like the heaving curve of a massive back, all dark searching wood. Distinctly paler, thinner roots whorled around it in intricate twists. The shrine itself, though small, was natural. An odd knot in the great black root formed a hollow about as large as Chishiro's fist. Within it, the paler root had clustered and tangled upon itself like a gnarled heart that seemed, when studied, to beat.
#figure(image("007_The Blade Reflected and Reborn/02.jpg", width: 100%), caption: [Go-Shintai of Boundless Vigor | Art by: <NAME>], supplement: none, numbering: none)
A kami slept within the shrine, the locals told him. It hadn't yet told them what sort of kami it was—when it spoke, it was in rumbling whispers and fractured dreams, images that coalesced and blurred together with a chasmic ache. They suspected that it was some shadow of harrowed Jukai, here on the edge of Towashi.
Chishiro loomed over the shrine as the sun set. The silver sword strapped to his back was only as heavy as metal ever could be, and the shadow it cast was as lifelessly black as his own. The kami didn't see fit to speak to him, though he didn't doubt its presence. It was as real as breath and unkindness. And however much it might love the people who loved it in turn, it would, inevitably, be disappointed in them.
As such, he had come to give it a warning:
"Don't trouble them more than you already have."
The kami said nothing in return. Chishiro wasn't surprised. He had already decided that it was a selfish creature.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Years ago, Chishiro had been more than himself. His friends and comrades, the ones with whom he hunted those Futurists who dared infringe on Jukai's borders, had known what he meant when he said so. He did not mean only that his jade-flecked blade was an extension of his being—rather, it was that his own spirit had been compounded with the resonance of his kami, and therefore with Kamigawa.
Chishiro was #emph[himself] to such an extent that he-as-self mattered not at all, for what #emph[did] matter was great Kaima, the darkly radiant blade forged by their bond and all that they meant to accomplish together.
Chishiro had tried, a few times, to explain himself to the Futurists they caught instead of killing. One had been greatly afraid of him and thought him possessed, and by dint of that, wholly unreasonable. Another had spoken to Chishiro as if he were Kaima, and she had aped obeisance because she thought she might trick her way to freedom. A third told him: "I understand, I think. There are moments when I see the plane folded upon itself—when I see the way in which I'm enfolded within it."
Kaima stirred in Chishiro. He said: #emph[A new branch wishing to unfurl and flower. A chill recedes, and the buds peek bravely.]
Chishiro leaned forward to study the Futurist, a moonfolk woman, her pearl-colored face creased in thought, her elegant hand pressed to her mouth. "And what do you do, when you feel that way?" he asked her.
"What I was doing when you caught me," she said.
Chishiro admired her honesty, brazen though it was. He had cornered her and her underlings in the depths of Jukai. This band of Futurists had been doing their best to understand kami by first isolating them in their most natural habitat, then breaking down and dissecting that habitat into its most elemental parts—in so doing, hoping to break and dissect the kami.
She doubtless expected him to kill her, as he and his comrades had killed others of her ilk. So, Chishiro let her go, stripped of all her technology and gear, into the depths of the forest she had sought to ravage. The kami would decide whether she escaped or died, as was their right.
Chishiro's comrades had said: "We wish you'd stop doing that."
He'd said: "I have to."
He'd meant: "I want to—and Kaima does, too. Therefore, we will. We must."
They had an obligation, one that defined the presence of Kaima in Chishiro and of them both on Kamigawa: forest and fellowship, the plane and its bindings. They would seek always, first, to understand.
Perhaps that had been the problem—a fundamental flaw writ into their being. They had been too eager to ask and listen, to give counsel and to take it. It had broken them, in the end.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Far Corner's trouble was the Mukotai, a Reckoner gang that had chosen to plague this otherwise quiet neighborhood. Every Reckoner family nursed its own brand of violence—poison, blade, or curse. The Mukotai prized the clever and sneak thieves, and only rarely did they decide to throw their weight around with the kind of threat that they had delivered to Far Corner.
#figure(image("007_The Blade Reflected and Reborn/03.jpg", width: 100%), caption: [Mukotai Ambusher | Art by: <NAME>], supplement: none, numbering: none)
It might have been different if their scout hadn't died in Far Corner's streets. Chishiro thought the problem lay less in the fact of the man's death than in how he had been killed, and why.
He had received no straighter story after the first non-answer the Far Corner elders offered. Ayari insisted, in a sideways manner, that she had killed the man. Chishiro doubted this. He had found the body where she attempted to dispose of it in the field between Far Corner and Jukai, and he had seen the roots running through the body's flesh and tangling out from its gawping mouth.
The Mukotai had signified their intent to retaliate with a hand nailed to the gate of Far Corner. The hand had belonged to a young mechanic called Jenzo—a son of Far Corner who had recently gone to study at the Imperial Academy. He was returned home the following day, left half-dead on the main street, shivering and sweat stained.
"A week," Jenzo told the elders and Ayari as a prosthetic edged in white light was fitted to his wrist. "We leave by then, or we die."
For the slight of their dead man, the Mukotai intended to burn Far Corner to the ground. Far Corner's kami had taken one of their own, and they intended to repay the transgression in kind.
Perhaps the people of Far Corner were more clear-eyed than Chishiro thought; after all, they had hired him. It suggested they realized that the kami they loved could not be expected to protect them.
So Chishiro had taught Far Corner's able-bodied the proper use of blade and arrow in the field between their homes and Jukai. Their dexterous and deft he sent to the brewery storehouse, where they salvaged scrap to construct the devices Chishiro described. Jenzo, the mechanic, had propped himself up in a corner of the storehouse, practicing with his new prosthetic, finessing the devices his neighbors constructed.
"Uniquely illegal, isn't this?" he'd asked Chishiro, his tone more inquisitive than accusatory as he cradled the palm-sized box of carved wood and wrought metal, tinkering with its innards.
"Yes," Chishiro had replied, and he'd said nothing more.
Only one sort of person knew how to craft a disruptor, a device that could tear magic from metal like claws tore life from flesh: the sort of person who pledged themselves to Jukai. Chishiro no longer pledged himself to anyone, but he had, once, and he had come away with his fair share of lessons to go with the scars.
To wit, the plan was to lure the Mukotai down to the Jukai end of Far Corner's main street. After all, the Reckoners wanted the shrine. There, they would meet the trap: a meticulously arranged series of disruptors, which would be triggered in rapid succession once the Mukotai reached the appointed area. Then, as the Mukotai were forced to pit whatever true blades they carried against the ones Far Corner brought to bear, the Reckoners would be forced toward the forest of Jukai—and toward the kami lurking within.
Thus, the people of Far Corner would give the Mukotai a choice, just as they had been given: Flee, or face those who hate you for daring to transgress against them.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The end of the week fell on a moonless night. Chishiro lurked on the roof of the teahouse—at three stories, it was the tallest structure in Far Corner. As had become her habit, Ayari crouched quietly beside him, ready to carry his orders wherever they needed to go—until she began to curse frenetically under her breath.
She darted away from Chishiro's side, toward the other end of the teahouse roof and nearly out of the shadows. He caught her just before she exited cover, his scaled hand snared at the back of her neck.
Ayari tensed under his touch but didn't struggle, only inclined her head toward the object of her frustration: Jenzo, crouched in the side street between the brewery and the storehouse, where one of the disruptors had been planted.
"What does he think he's doing?" Ayari hissed. "They're almost here. They'll gut him."
Other Far Corner locals lay in wait, hidden in alleys and behind doors, ready to dart out and herd the Mukotai toward the field once the disruptors had gone off. These were the individuals who Chishiro had chosen to train, for they had the strength to bludgeon and skewer. Jenzo, still recovering from his injuries, was in no state to do the same.
"It must be necessary," said Chishiro, though he eyed Jenzo, too, and the quick movements of his hands over the device nestled in the brewery's slatted sides.
"He's going to be seen." Ayari said this not with the heat of fear, but the even keel of certainty. Her eyes hardened as she looked to the Towashi entrance to Far Corner.
The Mukotai had arrived.
The Reckoner vanguard flitted in shadow, lithe shapes cleaving to dark corners and up onto the roofs. The rest came behind, stride unhurried, the enamel hilts and staffs from which their weapons would spring slung over their armored shoulders. As they approached, they ignited their blades, one after another. Eerie light crawled around the shapes of otherwise invisible swords, scythes, and other sharp-edged brutalities.
Behind them, the mech. It was all dark cherry wood, partly carved, partly grown in gnarled whorls to fashion the joints of its curving spine, its dragging, three-jointed arms, and its finely articulated feet. It had no head; a pale veil concealed the pilot's cockpit in its sunken belly.
And at their fore, a lumbering beast that moved with sudden speed and terrible impact. A corpse-swallower toad from the canals, its throat throbbing and its slow-blinking eyes rolling with lurid interest. Astride it, a man, limber with confidence, his searching gaze sharp.
"Far Corner—we know you didn't run," the toad-rider called. His voice, though lazy, cut the night with its sneer. "We know you're hiding. But the Mukotai aren't monsters. This is your last chance. Get out, or you'll wish you had."
#figure(image("007_The Blade Reflected and Reborn/04.jpg", width: 100%), caption: [Tatsunari, Toad Rider | Art by: Justine Cruz], supplement: none, numbering: none)
If one had the presence of mind to think such things, they might have thought this strange. Hadn't the Mukotai come to take from the kami of Far Corner what had been taken from them? If so, why would they tell their victims to flee? To flush them out of hiding, perhaps. Yet what mere citizen could hope to hide from the likes of a Mukotai Reckoner?
Such thoughts flitted through Chishiro's mind, but they remained at the surface, gossamer and insubstantial. Something else stirred in the depths of his heart, something dark and labored. Unconsciously, one of his hands settled on the hilt of his silver blade.
More pressingly, as the toad-rider spoke, one of the shadow vanguards slid into the alley where Jenzo frantically worked to hide the disruptor he had been tinkering with.
"Please let me go." Ayari pleaded with Chishiro, her tone as tight as her fists around her knives. "They can't learn what we've done. They—"
She broke off, though Chishiro thought little of this. His attention was now fixed on the unexpected nexus of his troubles—on the man who spoke for the Mukotai.
Tatsunari, they called him; as Chishiro gathered information on the Mukotai threat, he had learned this name but little else. He had not yet heard the man's voice, let alone seen his face. Nor had he seen the man's blade.
A simple thing, the last. Its metal edge barely gleamed in the pink and twilight glow cast by the Mukotai gear. A black metal hilt, tarnished by use and age.
Familiar.
And that face~the idle cant of Tatsunari's head. The serrated edge of his hungry grin.
Familiar as well.
Familiar like an old scar split open, like blood on his tongue and sick in his gut. Chishiro had in that moment been reduced. Honed. He had been a yawning deep, and now he was the small dark hollow at the center of it—a hollow in need of filling.
He had gone many long years with this absence within him. He had never thought to give it a name, for he had thought it obvious: treachery and betrayal; his own lacking self. And so, he had never thought to fill it. It hadn't seemed the sort of wound that could be mended.
But oh, now, the sight of this man, it was as water to parched earth. If Chishiro could have Tatsunari's torn heart in his hands, then at last, perhaps, he could know satisfaction.
Yes. It would be a selfish murder and a crude one, unhallowed too, but Chishiro desired it so viciously that he was no longer fettered by such thoughts.
"Chishiro," he heard, faintly, his name spoken in urgent whisper. Again, "Chishiro, what—"
Chishiro had by then descended.
He launched himself from the roof with the vicious totality of his bulk. He collided with a Mukotai bruiser who had not the time to be shocked before Chishiro's blade had slit his throat.
He left the man gurgling, thrashing in the street as he lunged toward the next—a guard with a bright-edged naginata. She tried to leap back, but Chishiro had already seized the head of her spear, just under the blade, with his two right arms. He wrenched it from her grasp. As she tripped toward him, he thrust his own silver blade between the grooves of her plate armor, into her belly.
By then, answering cries of alarm and shrills of violence rang out down the street. Panic bled into desperate action.
Chishiro heard none of it through the roar in his mind as he met Tatsunari's keen-eyed stare. The toad had half-turned, its body bristling with tension, its teeth wet with a glistening hunger. Tatsunari, atop it, threw back his head and crowed a laugh that melted into the rising clamor.
It was the delighted, frantic laugh of a man who knew he faced his death—who realized his only hope was to kill first.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Shortly after Chishiro sent that Futurist to her fate in the depths of Jukai, he and his comrades had returned to one of their Order's havens: a little copse of trees beside a waterfall, above a river that flowed to a nearby village on the edge of Jukai. The village was friendly with their Order and helped them hide supplies in the copse for different cells.
A young man—a boy—had been waiting for them there. Human, small, Towashi born and bred. Unfamiliar to them all, but he'd known the codes. Chishiro learned later that he had befriended one of the Order's spies and eked the truth from them before ending the friendship in the most abrupt fashion imaginable.
The boy did much the same that night. He played an eager student well—he was hungry enough for it. He wanted to better know the forest, he said, and the spirits who graced it.
"There are spirits aplenty in your city, too," Chishiro said.
"Not like yours," said the boy, eyeing the green-edged blade strapped to Chishiro's back—the weapon that was the crystallized focus of his bond with his kami. There was such envy in that gaze. Such want. And yet~
Kaima thought it strange as well. He said to Chishiro: #emph[An emptied nest. A fallen chick. A spring run dry, and the thirsting herd.]
Chishiro agreed. The boy so clearly yearned, and he reached with grasping hand toward anything that might answer the yearning. Yet his hands were empty. Why had nothing seen fit to fill them?
Chishiro pitied him, as did his comrades.
So, they listened. They spoke. They ate with the boy and failed to notice that he didn't eat from the supplies the rest of them shared.
That night, Chishiro and his fellows fell into a deep, unmoving sleep. He woke in a haze, the moon low between the branches.
Chishiro couldn't move. Neither could any of the other figures in his line of sight. Some didn't breathe either. They had bled from their throats into the mossy earth beside the raging waterfall.
The boy crouched over Chishiro, though he was looking elsewhere. He stared defiantly into the dark between trees, at the looming shape within the shadows that shuddered with terrible, heavy breaths, its massive claws digging nervous furrows into the earth and its branching fangs quivering. Kaima, great and fearful.
"Why won't you #emph[move] ?" The boy swept a hand toward the limp bodies he'd felled with his poison, and in that hand, he held a blade—a familiar one. Chishiro's focus, stolen from his side, though when not wielded by his hand, it held no light but for that which it caught under the moon. "Don't you love them?"
Chishiro felt Kaima's response all through his veins: #emph[Bones jutting through flesh. Gasping through rot.]
The kami's fury raged, impotent, a consequence of their unique bond. Kaima was by nature fettered to his home, but his bond with Chishiro enabled him to act in any stretch of the mortal realm that Chishiro carried him to. It also rendered him vulnerable to the vagaries visited upon Chishiro's flesh.
Great Kaima was now hindered by the confines of foolish, poisoned Chishiro. Even as their comrades were murdered one by one, Kaima could do nothing—even as the boy's stolen blade was poised to kill Chishiro, too.
In that fell moment, Chishiro struggled to wring something from his paralyzed throat. His mind was too clouded by grief and anger and fear to know what it would be before it leaked out from his mouth. #emph[Stop] , he wished to say. And #emph[why] . He managed only a feeble croak.
The boy sneered down at Chishiro, disgusted—delighted? He turned back up to Kaima, teeth bared. "Well? You know what I want. Bond with me, and I'll have no need to kill him."
#emph[Foolish] , thought Chishiro, and despaired. What idiot thought they could force a bond? Had the city folk fallen so very far?
#emph[No] , he thought as he stared at this desperate boy, and a chill set in from his lungs to his throat. It was the boy's hunger that kept him lonely. Not even a kami driven by that same need would open their arms to him—no kami would give themselves to a mortal who wanted only to take and take, who had no notion of what he would be expected to #emph[give] .
And what, now, did Chishiro have left to give to Kaima?
Great Kaima trembled still. His boar's head bent, a translucent shadow, and his glinting eyes met Chishiro's.
Chishiro thought: #emph[Let me go. Be free.]
Kaima lurched to the side, his breath a hot wind that shuddered the trees. He said: #emph[The tree wracked by storm, and the root clinging to the earth. Clinging. Clinging.]
The boy's jaw tightened, and he raised the blade over Chishiro's petrified neck.
The root in Chishiro's mind snapped, and the blade in the boy's hand shattered.
The forest shrieked with Kaima's roar. Shadows burst from between the trees, and the immensity of Kaima charged, bearing down on both boy and Chishiro with crushing force.
Chishiro felt the excruciating pressure of the kami's passage in the grooves of his scales—but he was not trampled, and in moments, he was alone.
Acutely so. Chishiro had not known #emph[alone] ness for long years—not since Kaima~
He could not hear Kaima.
Chishiro breathed raggedly in the silence, staring up at the moon through branches, feeling small, and frail, and finite. He struggled to drag himself onto his side to see what had come of the boy and his partner.
A line of ravaged, broken earth flowed from Chishiro's body to the riverbank. There was no sign of his kami, or his focus, or of the boy who had broken them apart.
Chishiro, numb and unthinking, waited and waited for Kaima to return, but when dawn crept through the branches overhead, there was still only nothing but himself. Only then did he manage to drag himself upright and discover what had come of the village below the waterfall. The last images Kaima had poured into him flashed again through his mind as he beheld the carnage below: #emph[A ravaged tree. A sundered root.]
The village lay in ruins, the villagers ruined with it. They had been reclaimed by Jukai's roots in a single night, and with savagery.
Chishiro knew not what to do with himself, absent Kaima. Even less, with the seeping surety that the responsibility for this destruction lay not wholly with the boy, but with himself. His frailty. His willingness to surrender.
In the end, he burned the bodies of his friends, and of every villager he could find. Then he left, returning in silence. He didn't choose to sell his violence so much as he began to be paid to do it, and he had done so ever since.
This was why the kami of Far Corner had only ever earned his wariness. Why, even if it loved its people, he could not bring himself to trust it.
Why now, even so, he would protect it: he hated the man who threatened it second only to how ferociously he hated himself.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The disruptors triggered in haphazard sequence. One stretch of Far Corner went suddenly dark as Mukotai weapons flared and died while others remained luminous with threat.
A samurai fell to her knees under the weight of deadened, hulking plate armor that now threatened to crush her. A group of Far Corner's neighbors set upon her with staff and sword, bludgeoning and cutting.
A ninja flung daggers into one Far Corner local, then another, and another. One by one, his victims staggered and fell, screaming as the daggers ignited with violet fire.
Jenzo tumbled over the pavement of the main street, smacked away from the disruptor he had tried to trigger by the uncanny three-jointed arm of the Mukotai mech. The disruptor landed between them. Jenzo scrambled toward it just as the mech dug its clawed feet into the cracking pavement and lunged.
Ayari dodged past another struggle just in time to tackle Jenzo out of the mech's trajectory. They skidded free, but the mech had swiveled amid its attack and, with eerie grace, flipped over its own body to land, squatting, before the abandoned disruptor. It picked the device up off the ground between its long, delicate fingers and held it before the tattered veil that concealed the cockpit, examining its prize.
A minuscule squeeze; the disruptor shattered.
Then the mech reached for them.
Until it lurched awkwardly forward. Something had struck its back. It twisted to turn on the assailant, but he had already clawed and coiled up the mech's spine.
As the mech staggered, trying to throw him off, Chishiro twisted around the side of the open cockpit and latched onto its roof with two of his arms. He tore the veil aside with a third, and with his fourth, he shoved a pulsing jade disruptor into the pilot's hands.
The pilot stared at it, then him, in knowing horror. They were laced into their mech by a forest of braided wires and tubes, and a second from now, when the disruptor detonated, they would likely die with their machine.
Chishiro didn't wait to see if they did. He threw himself from the mech moments before the disruptor sang out and sent the hulking construct toppling to the ground behind him, dead.
Chishiro pressed on. He passed Jenzo and Ayari, now back on their feet. Jenzo tried to thank him, but Ayari held him back. As if through smoke, Chishiro registered the fury in her face, and the contempt.
Chishiro had made the mistakes he had tried to stop her from committing. Now people—her people—were dying, and it was his fault.
Chishiro understood her ire. He knew what it was to lose comrades to someone else's selfishness.
Yet he could not stop. He was single-minded in his pursuit of Tatsunari, a man whose death Chishiro needed like a drowning body needed air.
Tatsunari had run from the conflict. He had directed his toad to bring him thundering down the street, past all resistance, to the shrine that awaited him at the end. He waited there now with his blade drawn—Chishiro's old focus, resurrected and whole, dull with mortal metal. He had not yet struck. Tatsunari knew it took more than a blow to kill a kami.
Chishiro approached Tatsunari, bloodied and heaving for breath, his silver blade discolored by viscera.
The toad-rider's face was cold with an enmity deep as a current. "You," said Tatsunari, as he might to an old friend. "Thought you'd curled up in a hole and died."
"Throw down your blade," said Chishiro.
"Why would I do that?"
"So I can kill you with it."
Tatsunari threw back his head and laughed again, delirious with disbelief. "You bonded! You're all the same. So self-righteous, so determined that the world will do what you say."
"Spiteful wretch." But even as Chishiro snarled, realization cracked through his chest and bloomed into his whole being. "You hate them," he said, "the kami."
Tatsunari's jaw tightened, just as it had that long-ago night when he raised his stolen blade over Chishiro's throat. "No more than I hate anyone who'd kill one of my Mukotai."
It was Chishiro's turn to laugh. It began in the bowels of his gut and filled his chest like smoke. Tatsunari's grip on his stolen blade tightened, and he raised it as if unsure of whether to strike the shrine or the mad warrior before him.
"You do hate them," Chishiro spat. "You hate them because they see you for what you are. An empty man. A nothing."
And it was likely the same hatred that had brought Tatsunari to send his Mukotai scout to Far Corner in the first place. Towashi afforded precious few opportunities to kill a kami; Far Corner's small new shrine must have seemed an irresistible target for the empty man's anger. His fear.
Indeed, Chishiro's words seemed to cut into Tatsunari more cruelly than any blade could have. The man's face twisted with a pain beyond rage. His stolen blade lanced out, toward Chishiro—but Chishiro didn't move, his silver blade held slack in his hand.
He was thinking of emptiness. This empty man lunged toward him, but if Tatsunari dug his sword into Chishiro, he would only find more emptiness. Chishiro couldn't have said why that made him laugh, but it was this sound and no other that escaped him upon realizing the horrifying degree to which they were both nothing creatures, wretched in their lack.
The once-blessed blade caught Chishiro through the gut, just below his ribs, where it plunged deep and deeper until blood was welling in his throat.
Then something else welled with the blood. Light and heat, unfurling from within Chishiro's wound and sprawling out through his laugh—changing its tenor, until it became not the hollow bark of despair but an uncanny howl of imminent satisfaction.
Tatsunari's eyes widened with a wild fear as roots crept up out of the wound he had dug into Chishiro, fine and pale at first, then darker, surer. They slithered up the blade toward his hand, and he tore his hand free in horror.
The kami of Far Corner's shrine had awoken, and it said this to Chishiro: #emph[A tree consumes the nail within it; the roots sup blood to grow and grow.]
It meant: Seize his vengeance and make it yours. I bid it. I covet it. For me, you'll do it.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The roots speared out of the ground in savage array. Powerful and lashing, they snarled up and around legs, through feet, into torsos.
Screams still ripped the air, but so did cries of delight and relief. The people of Far Corner saw their kami risen at last to save them—even as the dark roots sundered the walls and roofs of their homes to seize Reckoners striving to escape.
Chishiro had no time to spare for any fate but Tatsunari's. He coughed raggedly, but no blood spilled from his mouth as he released the meager silver sword from one hand and grasped the hilt of the sword stuck in his gut with another. The kami had bid him to retake the blade; it seemed to throb against his palms—just like it once had when it had been the core of his divine covenant. The kami of Far Corner urged him forward.
Tatsunari had fled back up onto his toad as it leapt away, croaking in fear at the bubbling torrent of roots cracking up out of the ground.
The kami spoke to Chishiro again; he dared not think it familiar, too: #emph[The forest floor reclaiming old bones.]
Chishiro wrenched the blade free of his chest. He should by all rights have bled out, and for a moment, his blood did pump forth—but it was swiftly stoppered by the roots that snarled up as if from within him and plugged the hole. He still had the pain, but more than that, he had adrenaline and #emph[need] .
Tatsunari was still alive. He didn't deserve to be.
Unthinking, Chishiro latched onto a river of roots that boiled up from the ground and carried him up into the air. From his high perch, he had the lay of Far Corner.
The Mukotai were struggling to retreat to the part of the neighborhood nearer to Towashi, where the roots struggled to worm past the thicker infrastructure. Tatsunari was with them, his toad leaping free of the kami's grasping rage.
Images surged behind Chishiro's eyes: #emph[The diving hawk. The lunging tiger. The snake, striking—]
"Needn't be so obvious," he said. And he leapt, lifted by a remorseless joy.
Swift and perfect, Chishiro and his blade and the power within them plunged toward his target.
Tatsunari saw Chishiro's falling shadow and turned, eyes wide. He had only a second to choose: meet the threat or save himself. He flung himself from his mount.
Chishiro cleaved into the toad. He dragged the blade through its meat, its bellows unraveling into the night, until he had carved so thoroughly into it that it wheezed and at last died.
The body split and fell apart from itself in an unsightly mess. But no sooner had its sides slid to the ground then they were caught and consumed by the grasping roots, which sought to nestle and flower through its richness.
Chishiro turned, flicking his blade clean of gore. The edge glinted green in the lamplight.
Tatsunari had tumbled into the street after his jump and landed badly on his leg. The angle of the limb was all wrong. Chishiro advanced on Tatsunari, who bared his teeth, his eyes wet with anguished tears.
Chishiro loomed over the broken man, and he knew in his screaming veins that Tatsunari's brokenness was not enough. This man had killed too many, and he would kill again, because he was only the ugly spite with which he stared up at Chishiro, a poison, a—
Something in that broken look paused Chishiro's blade. Tatsunari still sneered, but Chishiro didn't think he was covering fear.
"Why?" Chishiro found himself demanding. "What made you—this?"
Tatsunari choked down a laugh that died in his throat. "Like you would understand. You're chosen. I'm #emph[nothing] . You said it yourself. Now kill me."
Anger ran dark and jagged through Tatsunari's words, but beneath that fury, at once brittle and enduring, was despair.
And it was the despair that summoned an ache in Chishiro's chest, pulsing out from where Tatsunari had stabbed him mere moments ago.
A hot wind blew into the still night. Chishiro turned his eyes upward to meet the enormity of empty shadow that shuddered over broken Tatsunari. At last, he allowed himself to recognize the kami that had lurked in the gnarled little shrine, that had devoured a Reckoner for merely intruding upon its territory, and that now loomed over them with a silhouette both familiar and foreign—the majesty that had once been Kaima.
A seething brilliance lanced through the kami's image like lightning. A light like a poison, for with its every flash, another image burned through Chishiro's mind:
#emph[Crush. Gore. Devour. End this faithless wretch—and then end the next, and the next.]
More cries rose on that gathering wind. Frightened yelps and pained gasps from within Far Corner—not from the fleeing Mukotai, but from those who had stayed because they thought they were safe in their homes. But the roots were not yet satiated. Neither was Kaima.
"Why?" Chishiro said again. The question had fallen from his mouth without him thinking it.
Kaima said: #emph[Mortal flesh and mortal work. Only one sort of creature has heart enough to betray another.]
And for that, Chishiro realized, the kami intended to be their ruin; be they Mukotai or not, Kaima would raze them all for the sin of their fallibility.
Chishiro clutched the wound in his gut that Kaima had closed. It burned as if infected.
In the next moment, his world tilted. Someone had slammed into him from behind and knocked him aside. An armor-clad Mukotai bruiser had shoved Chishiro away for a crucial second to scoop Tatsunari up from the ground.
The shock never left Tatsunari's eyes as his ally carried him off, rescuing him from certain death. Chishiro's surprise faded far sooner—replaced by newfound resolve.
Betrayal, rot, and death, he had seen all this, yes, and he had seen them again and again. But these things were not the end. They never were.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chishiro turned to the scene behind him. Far Corner cracked in every foundation, its structures crumbling under the assault of Kaima's roots, its people struggling to free themselves of their kami's relentless hatred.
There in the center of the street rose great Kaima, betrayal and hate coalesced into a massive bristling back and jutting antlered tusks. He stepped out of shadow and into colored reality, and all who saw him were struck speechless by the rage running through his fur like fire.
One look was all they needed to know: He was the kami who had come to them so suddenly through the earth, who they had tried to nurture with their love and attention—but this had not been enough to calm his brewing rage. He meant to kill them all.
#figure(image("007_The Blade Reflected and Reborn/05.jpg", width: 100%), caption: [Kaima, the Fractured Calm | Art by: <NAME>], supplement: none, numbering: none)
Chishiro couldn't let him.
He spied Ayari and Jenzo down the street. He called their names, and they snapped out of their terror to stare instead at him, wary and wide-eyed. Chishiro jerked his head toward Towashi. It was all the message he had time to give.
As the two youths of Far Corner rushed to gather everyone they could save and ferry them into the city, Chishiro advanced toward his old friend—blade in hand and root in chest.
"Why these deaths, too, Kaima?" he asked as he glided over broken pavement and past shattered bodies. "They love you, you realize."
Kaima faced Chishiro, but Kaima was not looking at him. The kami's gaze, at once emerald deep and storm bright, was fixed on the space behind Chishiro. On Towashi and on the people fleeing toward it.
But it was what Kaima said that forced Chishiro to stop in his tracks. It came in image and sense, as it always did, only now there was a terrible specificity. When Kaima spoke to justify these deaths, he spoke not of the plane, but of:
#emph[Chishiro, teaching Reckoners the way of climbing trees and killing silently. Chishiro, teaching Futurists the means of shielding themselves against a disruptor's shattering force. Chishiro, once-bonded, now faithless and spiteful, moved not by creed but by coin, and hating not only himself, but—]
"You think I hated you," said Chishiro. A dull ache crept through his chest as Kaima's judgment pulsed through his limbs.
For if the mortal whose life had once defined Kaima now hated him, what could Kaima become other than hateful, too? No matter that hate had once been so far outside great Kaima's world that he had barely understood it, now it was what had broken him, and so it was all he had left.
Only now did Chishiro realize that Tatsunari had not been the blade who severed their bond; he had been merely a fulcrum, and under his pressure, their tether had snapped. The weight of that cruelty bearing down had undone them both—had left them jagged cruelties in themselves, broken by their pain and unwilling to do aught else but force their pain upon others.
Once, Chishiro had thought it the place of the kami to choose when—if—a mortal should die. Now he had taken that choice into his bloodied hands, and he'd made it again and again.
And yet now~
Far Corner creaked and splintered about them, and Chishiro couldn't hold his tongue.
"Who are #emph[you] to choose?" Anger cut each word from his mouth, but his voice lacked heat. Chishiro asked as a man judged who merely judged in turn. "You're a shadow of yourself. A murderous ghost. You abjure mortals, but we're of Kamigawa as much as any root and flower—as any bird and wolf. You reject us now because you fear being hurt again. Didn't we choose that? To be hurt, together, for their sake. How could you let one man's spite so ruin you?"
Chishiro met Kaima's looming, leering eye, a black and drowning depth with his own unflagging stare. He thought, in the pit of his stomach: #emph[We're going to kill each other.]
Then a crack ran through him, from skull through tail, and an image burst forth from it: #emph[A clear spring muddied by a festering body, and his own reflection within the fetid water—because it was his own flesh, run through with roots that had become his crown and claws, that had poisoned the spring with his death.]
#emph[Oh] , thought Chishiro, and he saw the realization rise in Kaima, too, who in that moment diminished, his rage skewered on his own self.
#emph[Oh] , he thought again. #emph[We already have.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The orochi and the kami who had once been were no longer. Their bond as well was nothing but a memory, one they grieved together as the night grew still and suffocating. Kaima's roots no longer writhed. Far Corner remained standing, ruined though it was.
"I would right this, Kaima," Chishiro said, and he lowered his head as he offered up the blade that had been the heart of their bond. "I'll cut my life from you if I must."
He had seen himself, after all—the mortal flesh in that poisoned spring, entwined with Kaima's divinity, that which forced it to know putridity and wrongness.
A strange sound rolled out of Kaima as the kami seemed to tilt. The great spirit thudded to the fragmented ground, sending up clouds of dust around his sagging, kneeling form. He shuddered again, that sound still churning from within him. Laughter, Chishiro realized with a start. Old and tired. Sickly.
"I cannot be righted," said Kaima, spoken language new to his ancient throat. New, but a gift. An apology, wetly wheezing and eerily mortal. "I am as I am. Become what I become. It is possible, though, that I no longer wish to be that which I was."
Chishiro ached again to hear the shadow of that old inquisitive bent—the wonder that had driven the Kaima he had given himself to. The kami who had always searched for some way to reach those unlike himself.
Chishiro extended a tentative, empty palm toward the tremendous snout and was allowed to touch it. "Then how can I give you peace?" he asked.
"Is that my due?" asked Kaima.
"It might not be," said Chishiro. They stood in the wreckage of Kaima's rage, which was only the latest of his cruelties. And yet. "But I wish for you to have it."
"Then give yourself to me again," said Kaima, more quickly than he had yet managed any other words. His want was clear, and the need. Chishiro saw himself reflected in the black of Kaima's eye, and for a moment, they shone together. "Remake me as I reforge you. Be my vigilance. My guard. My faith and bond."
Chishiro thought:#emph[ I can't. ] He thought: #emph[I mustn't.] And he thought: #emph[Why would you trust me again?]
But that, there, was the trick of a bond. Even when they lost hope in themselves, they could find it again, reflected in the other.
Chishiro once more raised the focal blade flat between them, and as he did, hairline fractures began to run down it. As the fragments fell away, one after the next, they revealed a light reborn.
|
|
https://github.com/fabriceHategekimana/master | https://raw.githubusercontent.com/fabriceHategekimana/master/main/3_Theorie/Autres_concepts.typ | typst | #pagebreak()
= Autres concepts <autre>
Dans le cadre de l'évolution de notre langage de programmation, nous exprimons un fort intérêt pour l'ajout de nouvelles fonctionnalités qui, bien que non discutées en détail ici, méritent une attention particulière. Notre focus principal a été sur les tableaux multidimensionnels et le typage des opérations associées, cependant, d'autres extensions potentiellement bénéfiques pourraient également être envisagées. Ces fonctionnalités supplémentaires s'inscriraient parfaitement dans la vision d'un futur projet de développement d'un système de types inspiré de R, reflétant sa philosophie de flexibilité et de puissance dans la manipulation de données. En intégrant ces nouvelles capacités, nous pourrions offrir une robustesse accrue et une expressivité améliorée à notre langage, alignant ainsi notre outil avec les attentes et les besoins des utilisateurs avancés dans des domaines variés tels que les statistiques, la science des données et l'analyse quantitative.
La communauté R rencontre plusieurs défis dans l'implémentation de la programmation orientée objet (POO), principalement en raison de la diversité des systèmes de POO disponibles. Contrairement à de nombreux langages de programmation qui adoptent un modèle unique et cohérent pour la POO, R offre plusieurs paradigmes distincts : S3, S4, R6 et le récent système basé sur les classes de référence. Cette pluralité de méthodes crée un environnement où les utilisateurs peuvent être confrontés à des choix déroutants, et où les différences entre ces systèmes peuvent conduire à des incompatibilités et à des difficultés d'intégration.
Le système S3, le plus ancien et le plus simple, est apprécié pour sa flexibilité et sa simplicité d'utilisation. Cependant, il manque de rigueur formelle, ce qui peut conduire à des comportements inattendus et à une gestion d'erreurs limitée. En contraste, le système S4 introduit une formalisation stricte des classes et des méthodes, avec une vérification des types plus rigoureuse, ce qui améliore la robustesse et la maintenabilité du code. Malgré ses avantages, S4 est souvent critiqué pour sa complexité et sa courbe d'apprentissage abrupte, ce qui peut dissuader les nouveaux utilisateurs.
Le système R6, introduit pour offrir une approche plus moderne et orientée vers la performance, permet la création de classes avec des champs et des méthodes, similaires aux objets dans des langages comme Python ou Java. Bien que R6 soit plus intuitif pour ceux ayant une expérience avec d'autres langages orientés objet, il n'est pas totalement intégré avec les systèmes S3 et S4, ce qui peut poser des problèmes d'interopérabilité dans des projets complexes qui utilisent plusieurs paradigmes de POO.
Cette multiplicité de systèmes de POO dans R peut non seulement semer la confusion parmi les utilisateurs, mais aussi engendrer des discordes sur la "meilleure" approche à adopter. Les développeurs peuvent avoir des préférences fortes basées sur leur familiarité avec un système particulier, conduisant à des débats au sein de la communauté sur les pratiques optimales. De plus, la documentation et les ressources pédagogiques peuvent être fragmentées, rendant l'apprentissage et la maîtrise de la POO en R plus ardus pour les nouveaux venus.
Ces fonctionnalité pourraient amener une meilleur implémentation de la programmation orientée objet ainsi que plusieurs avantage intéressantes dans la gestion de données.
== L'appel de fonction uniforme
L'appel de fonction uniforme, ou "uniform function call syntax" (UFCS), est un concept en programmation qui permet d'invoquer des fonctions de manière uniforme, indépendamment de leur définition en tant que méthodes d'une classe ou fonctions libres. Cela signifie que les fonctions peuvent être appelées de la même manière, qu'elles soient définies à l'intérieur d'une classe ou en dehors, améliorant ainsi la lisibilité et la flexibilité du code.
Par exemple, en utilisant l'UFCS, une fonction qui agit sur un objet peut être appelée comme une méthode de cet objet, même si elle n'est pas définie à l'intérieur de la classe de cet objet. Supposons qu'on ait une fonction libre `length(x)` et un objet `vec`. Avec l'UFCS, on pourrait appeler `vec.length()`, traitant `length` comme une méthode de `vec`. Cela permet aux développeurs de choisir l'appel le plus naturel ou le plus lisible pour leur contexte, sans se soucier de la localisation de la définition de la fonction.
L'UFCS est particulièrement utile dans les langages de programmation qui favorisent la composition fonctionnelle et la modularité. Par exemple, en C++, D, et Rust, l'UFCS permet d'appeler des fonctions de manière fluide et cohérente, réduisant la confusion entre les fonctions membres et les fonctions non membres. Cela encourage également la réutilisation du code, car les fonctions libres peuvent être facilement intégrées dans des chaînes d'appels de méthodes.
En R, l'adoption de l'UFCS pourrait potentiellement unifier les diverses méthodes de manipulation des objets, rendant le code plus intuitif et cohérent. Actuellement, la pluralité des systèmes de programmation orientée objet (POO) en R (comme S3, S4, et R6) entraîne des différences dans la manière dont les fonctions sont appelées et utilisées. L'introduction de l'UFCS pourrait atténuer certaines de ces divergences en permettant un style d'appel homogène, simplifiant ainsi l'interaction avec les objets et les fonctions.
== Typage nominal/structurel
Le typage nominal et le typage structurel sont deux approches distinctes pour la vérification des types dans les langages de programmation, chacune ayant ses avantages et inconvénients. Le typage nominal repose sur les noms des types pour déterminer la compatibilité entre eux. Deux types sont considérés comme compatibles si et seulement si ils portent le même nom ou si l’un est explicitement déclaré comme étant une sous-classe de l’autre. Ce système est courant dans des langages comme Java et C\#. L'avantage principal du typage nominal est la clarté et la sécurité qu'il procure : les relations de type sont explicites et faciles à comprendre, réduisant les risques d'erreurs de typage accidentelles. Cependant, il peut être rigide, car il nécessite souvent des déclarations répétitives et ne permet pas la compatibilité entre types structurellement similaires mais nominalement différents, limitant ainsi la flexibilité.
En revanche, le typage structurel se base sur la forme ou la structure des types pour vérifier leur compatibilité. Deux types sont compatibles si leurs structures internes (comme les champs et les méthodes) correspondent, indépendamment de leurs noms. Cette approche est utilisée dans des langages comme TypeScript et Go. Le principal avantage du typage structurel est sa flexibilité : il permet de traiter des objets de types différents mais ayant des structures similaires de manière interchangeable, facilitant ainsi la réutilisation du code et l'intégration de composants. Toutefois, le typage structurel peut introduire des ambiguïtés et des erreurs difficiles à diagnostiquer, car des types accidentellement similaires peuvent être considérés comme compatibles, menant potentiellement à des comportements inattendus.
Comme le langage R est un langage conçu pour être flexible, il aura un système de type qui favorisera le typage structurel avec l'usage de types comme les tableaux, les tuples ou les records (qui sont mentionnés après). Il y aura tout de même l'opportunité de passer au typage nominal à l'aide du concept de named tuple.
=== Records
Par défaut, le langage R n'utilise pas de classe, mais émule un système similaire à l'aide de label. Le langage que nous formons n'implémentera pas de classe avec des méthodes mais permettra de créer des types avec des fonctions dédiées. L'un des types les plus proche des classes sont les records. Ils n'ont pas le pouvoir d'héritages comme les classes mais offrent d'autres pouvoir plus intéressants.
Les records et les classes sont des concepts fondamentaux en programmation orientée objet et en gestion de données structurées, chacun ayant des avantages distincts selon le contexte d'utilisation. Les records, ou structures, sont des types de données simples qui regroupent un ensemble de champs ou de valeurs sous un même nom. Ils sont souvent utilisés pour représenter des données immuables et peuvent être comparés par leurs valeurs. Un avantage majeur des records est leur simplicité et leur efficacité pour représenter des données de manière directe et sans comportement associé. Cela les rend particulièrement adaptés pour la représentation de données de configuration, de résultats de calculs ou d'états immuables.
En revanche, les classes sont des structures plus complexes qui combinent à la fois des données (champs) et des comportements (méthodes). Elles permettent de définir des objets avec un état interne modifiable et des opérations spécifiques qui peuvent manipuler cet état. Les classes offrent une encapsulation des données et un haut niveau d'abstraction, facilitant ainsi la modélisation de concepts complexes et la gestion de l'état mutable. Un avantage clé des classes est leur capacité à encapsuler le comportement avec les données, promouvant ainsi la réutilisation du code et la modularité.
Cependant, les classes peuvent aussi introduire de la complexité, notamment en matière d'héritage et de gestion de la hiérarchie des classes. L'héritage multiple, par exemple, peut poser des défis de conception et de maintenance en introduisant des dépendances et des relations complexes entre les classes. De plus, la gestion de l'état mutable peut parfois conduire à des erreurs difficiles à diagnostiquer, telles que les problèmes de concurrence dans les environnements multi-threadés.
En comparaison, les records sont souvent plus simples à utiliser et à raisonner, mais peuvent être limités lorsque des comportements complexes doivent être associés aux données. Le choix entre records et classes dépend donc largement des besoins spécifiques du projet : les records sont souvent préférés pour la représentation de données simples et immuables, tandis que les classes sont utilisées pour modéliser des entités avec un état interne mutable et des comportements associés. En résumé, bien que les records et les classes aient des rôles distincts, ils offrent chacun des avantages significatifs en fonction du contexte d'utilisation et des exigences du projet.
=== Sous-typage
Le sous-typage est une part du polymorphism et a souvent été utilisé en programmation orienté objet à l'aide de l'héritage. Avec notre langage qui a une orientation fonctionnelle comme R, nous laissons ce context au profit d'autres méthodes de sous typage.
On peut mentionner l'usage d'interfaces qui permettrons à toutes les types les implémentant d'être considérés de "sous-type" car ils respectent les contrats imposés par par les dits interfaces. Ici les interfaces ne seront pas aussi puissant que dans le langage Rust mais permettrons d'implémenter des fonctions par défaut. Ils ne se baseront pas sur des génériques mais pourront être combinés pour créer de plus grandes interfaces. Nous aurons ainsi un peu plus de puissance et de flexibilité sans apporter trop de complexité.
Dans le contexte du sous-typage, un record peut aussi être considéré comme un sous-type d'un autre s'il possède tous les champs de ce dernier, éventuellement avec quelques champs supplémentaires. Par exemple, si nous avons un record `Person` avec des champs `name` et `age`, et un record `Employee` qui ajoute un champ `id` à ceux de `Person`, alors `Employee` est un sous-type de `Person`.
Le polymorphisme de ligne, quant à lui, permet de définir des types en termes de lignes de champs plutôt qu'en termes de noms de types fixes. Cela offre une flexibilité significative dans la définition et l'utilisation des types de données, car les types peuvent être étendus dynamiquement avec de nouveaux champs sans nécessiter de redéfinition explicite du type. Par exemple, un type polymorphe pourrait être défini comme ayant au moins certains champs spécifiques, mais la présence d'autres champs est autorisée et traitée de manière flexible.
L'interaction entre le sous-typage et le polymorphisme de ligne permet donc de créer des structures de données qui peuvent être étendues tout en maintenant les relations de sous-typage. Cela signifie qu'un code qui s'attend à manipuler un type plus général peut également interagir avec des instances de types plus spécifiques qui ajoutent des champs supplémentaires. Cette approche favorise la réutilisation du code et la gestion dynamique des données, car elle permet de traiter les types de manière plus générique tout en prenant en charge des variations spécifiques au sein de ces types, améliorant ainsi la flexibilité et l'expressivité du système de types.
=== Dataframe
Les dataframes sont des structures de données cruciales en sciences des données, particulièrement dans le langage de programmation R, en raison de plusieurs caractéristiques et fonctionnalités qui répondent aux besoins spécifiques de l'analyse de données.
Tout d'abord, les dataframes permettent de stocker et d'organiser des données tabulaires sous forme de lignes et de colonnes, où chaque colonne peut représenter une variable différente et chaque ligne correspond à une observation ou un enregistrement unique. Cette organisation est essentielle pour traiter et manipuler des ensembles de données complexes et hétérogènes provenant de diverses sources, comme des fichiers CSV, des bases de données ou des résultats d'expérimentations.
Ensuite, R est spécialement conçu pour le traitement statistique et graphique des données. Les dataframes offrent une structure de données optimisée pour les opérations statistiques courantes telles que le calcul de moyennes, de médianes, de corrélations, et la création de graphiques. Ils facilitent également la manipulation des données grâce à une large gamme de fonctions intégrées et de packages spécialisés dédiés à la manipulation, à la transformation et à l'analyse de dataframes.
De plus, les dataframes en R sont conçus pour être compatibles avec les autres outils et méthodes statistiques de la langue. Ils s'intègrent parfaitement aux fonctions de modélisation statistique, aux tests d'hypothèses, à l'analyse de variance, à la régression linéaire et non linéaire, ainsi qu'à la visualisation de données avancées. Cette intégration transparente permet aux scientifiques des données et aux analystes de travailler efficacement avec des données volumineuses tout en conservant la capacité d'appliquer des techniques statistiques sophistiquées.
Enfin, les dataframes facilitent la collaboration et le partage de données au sein d'une équipe de travail. Leur structure tabulaire standardisée et leur manipulation aisée permettent à différents analystes et chercheurs de travailler sur les mêmes données, en utilisant des méthodes cohérentes et reproductibles. Cela contribue à la transparence des analyses et à la vérifiabilité des résultats, des aspects essentiels dans le domaine scientifique et académique.
Si nous représentons les dataframes sous la forme de record de tableau (à 1 dimension) alors nous ouvrons la porte à une nouvelle façon de définir les opérations sur ces éléments. À l'aide du polymorphisme de rang discuté plus tôt, nous somme en mesure de developper des fonctions agissantes sur des dataframes aillants des colonnes spécifique et d'un type spécifique, facilitant la création de package sécurisés.
== Gestion d'erreur
La gestion des erreurs est un aspect crucial de la programmation moderne, essentiel pour assurer la fiabilité, la sécurité et la robustesse des applications logicielles. Les erreurs peuvent survenir pour diverses raisons : des données d'entrée invalides, des opérations non valides, des erreurs réseau, ou encore des bugs logiciels. Traiter ces erreurs de manière efficace est nécessaire pour garantir que l'application continue de fonctionner de manière prévisible et stable, même face à des conditions imprévues.
Les sum types (ou types somme) et les union types sont des concepts fondamentaux en programmation qui permettent de représenter des valeurs qui peuvent être de différents types. Ils offrent une façon élégante et expressive de modéliser des situations où une valeur peut prendre plusieurs formes possibles. Par exemple, un type union peut représenter une valeur numérique valide ou une valeur NaN pour indiquer un calcul incorrect.
Dans le contexte de la gestion des erreurs, les union types offrent une flexibilité particulière en permettant de représenter explicitement les cas où une opération peut échouer ou retourner un résultat indéterminé comme NaN. Cela permet aux développeurs de définir des fonctions et des structures de données capables de traiter ces situations de manière cohérente et prévisible. Par exemple, au lieu de retourner une valeur incorrecte ou de provoquer une exception non contrôlée, une fonction peut retourner un type union qui indique clairement si le calcul a réussi ou a produit une valeur non valide.
Cette approche renforce également la documentation du code et l'interopérabilité avec d'autres systèmes, car elle clarifie les attentes quant aux résultats des fonctions et aux données manipulées. En outre, les union types permettent de gérer de manière efficace les valeurs manquantes ou non valides dans les analyses de données, un aspect crucial dans les applications de science des données où des données manquantes ou incorrectes sont fréquentes et doivent être gérées avec soin pour éviter des résultats incorrects ou biaisés.
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PreventivoSprint/QuartoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": prospettoOrario, prospettoEconomico, glossary
== Quarto #glossary[sprint]
*Inizio*: Venerdì 15/12/2023
*Fine*: Giovedì 21/12/2023
#prospettoOrario(sprintNumber: "4")
#prospettoEconomico(sprintNumber: "4") |
https://github.com/rose-pine/typst | https://raw.githubusercontent.com/rose-pine/typst/main/src/apply.typ | typst | MIT License | #let apply-theme(content, theme-data) = [
#set page(fill: theme-data.base,)
#set text(fill: theme-data.text,)
#set table(fill: theme-data.surface, stroke: theme-data.highlight.high)
#set circle(stroke: theme-data.subtle, fill: theme-data.overlay)
#set ellipse(stroke: theme-data.subtle, fill: theme-data.overlay)
#set line(stroke: theme-data.subtle)
#set path(stroke: theme-data.subtle, fill: theme-data.overlay)
#set polygon(stroke: theme-data.subtle, fill: theme-data.overlay)
#set rect(stroke: theme-data.subtle, fill: theme-data.overlay)
#set square(stroke: theme-data.subtle, fill: theme-data.overlay)
#set highlight(fill: theme-data.highlight.high)
#show link: set text(fill: theme-data.iris)
#show ref: set text(fill: theme-data.foam)
#show footnote: set text(fill: theme-data.pine)
#set raw(theme: theme-data.codeThemePath)
#content
]
#let apply(
variant: "rose-pine"
) = {
return (content) => [
#import "themes/" + variant + ".typ": variant as theme-data
#apply-theme(content, theme-data)
]
}
|
https://github.com/andreinonea/igala | https://raw.githubusercontent.com/andreinonea/igala/master/post/prajitura-pufoasa-crema-vanilie-cocos/reteta.typ | typst | #set document(
title: "Prăjitură de post cu blat pufos și cremă de vanilie și cocos",
author: ("<NAME>", "<NAME>", "AUTOR ORIGINAL"),
keywords: ("rețetă", "prăjitură", "pufos", "vanilie", "cocos"),
date: auto
)
#set text(
lang: "ro",
region: "RO"
)
#align(center + top)[= Prăjitură de post cu blat pufos și cremă de vanilie și cocos]
#linebreak()
#grid(
columns: (1fr, 1fr),
[
=== Ingrediente cremă
- 300 ml de lapte de soia cu aromă de vanilie (eu am folosit Alpro Soya)
- 100 g de zahăr
- 100 g de unt de cocos (sau margarină pentru prăjituri)
- 1 lingurită de extract de vanilie
- 1 lingură cu vârf de făină
- 1 lingură cu vârf de amidon de porumb (zis și "corn starch", eventual de la Gustin)
- zeamă de lămâie (opțional)
],
[
=== Ingrediente blat
- 250 ml de lapte de soia cu aromă de vanilie (eu am folosit Alpro Soya)
- 200 g de făină
- 200 g de zahăr
- 60 ml de ulei
- 3 linguri de cacao
- 1 lingură de zeamă de lămâie (sau oțet)
- 1 lingură de extract de vanilie
- 1 linguriță de praf de copt
- 1 praf de sare (orice ar însemna asta)
]
)
=== Preparare cremă
+ Într-o crăticioară se omogenizează cu telul laptele de soia, zahărul, făina și amidonul de porumb
+ Se pune pe foc și se fierbe până se îngroasă, amestecând continuu cu telul în formă de pară (se poate trece la lingură odată ce devine greu de amestecat cu telul), apoi se dă deoparte ca să se răcească până ajunge la temperatura camerei.
Ideal ar fi să se răcească așezând crăticioara cu crema fiartă într-un vas mai mare cu apă rece, ca să fie gata până se pune blatul la cuptor (nu e musai).
+ În compoziția răcită se incorporează cu mixerul esența de vanilie și untul de cocos sau margarina.
+ (Opțional) La final, se poate adăuga și zeamă de lămâie, pentru a da un gust acrișor cremei - adăugați puțin, puțin până găsiți gustul deplin.
=== Preparare blat
+ Porniți cuptorul și setați-l la 180 °C.
+ Într-un castron, se bat cu telul laptele de soia, care e bine să fie rece, din frigider, uleiul, zahărul și zeama de lămâie sau oțetul.
+ Făina, sarea, praful de copt și cacaua se omogenizează bine, separat.
+ Ingredientele uscate se adaugă peste cele lichide și se omogenizează rapid amestecând cu telul în formă de pară.
Nu se amestecă exagerat, doar cât să se obțină un aluat cu o consistență tipică de blat de tort sau de chec.
+ Aluatul se toarnă într-o tavă căptușită cu hârtie de copt și se nivelează bine.
În funcție de dimensiunea tăvii, blatul va ieși mai subțire sau mai gros - rețeta originală a folosit o tavă de 35x38, eu una ceva mai mare.
+ Blatul se coace în cuptorul preîncins la 180 °C timp de 12-15 minute.
Practic, blatul este gata în momentul în care trece testul scobitorii, care trebuie să iasă curată și uscată atunci când este înțepat blatul copt cu ea.
Experimental, se poate prelungi coacerea cu până la 5 minute, voit sau din greșeală.
Mie mi-a ieșit un blat mai dens, dar moale.
+ Se așează blatul copt pe un grătar pentru prăjituri (sau un fund de lemn), ca să se răcească rapid.
=== Asamblarea
Imediat ce s-a răcit blatul, se desprinde hârtia de copt și blatul se taie în 3 fâșii egale, care se suprapun cu cremă.
Dacă se prepară mai multă cremă, se poate decora stratul de deasupra sau chiar îmbrăca complet prăjitura, finisând-o ca pe un tort.
Poftă bună!
#align(right, text(size: 12pt, "- A"))
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/sections/PreventivoSprint/SestoSprint.typ | typst | MIT License | #import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost
#import "../../functions.typ": prospettoOrario, prospettoEconomico, glossary
== Sesto #glossary[sprint]
*Inizio*: Venerdì 29/12/2023
*Fine*: Giovedì 04/01/2024
#prospettoOrario(sprintNumber: "6")
#prospettoEconomico(sprintNumber: "6") |
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/TA/Winter%202024/Math%20240/Midterm%20review%20solutions.typ | typst | #import "/Templates/generic.typ": latex,header
#import "@preview/truthfy:0.3.0": truth-table
#import "/Templates/math.typ": *
#import "/Templates/assignment.typ": MultiColumnBox
#show: latex
#show: doc => header(doc, title: "Midterm Review Solutions")
#show: symbol_replacing
#let show_answers = true
#let answer(answer) = {
if show_answers {
return answer
} else {
return []
}
}
#set page(margin: (top: 4cm), numbering: "1")
= Topic 1 - Sets
== Question 1
For each of the following sets denoted in set builder notation, describe this set. If it is infinite write 5 of its elements, otherwise write all its elements.
#MultiColumnBox[
+ ${ 4 y + 2 : ZZ }$
+ ${ x in ZZ : -5 <= x <= -2 }$
+ ${ x in RR : x^4 = 16 }$
+ ${ x in RR : x^2 + 11 x = -28 }$
+ ${ x in RR : tan pi x = 0 }$
+ ${ x in ZZ : |x| < 6 }$
]
#answer[
== Solution
+ This set contains all integers which have remainder $2$ when dividing by $4$, elements include $-2,2,6,10,14$.
+ This set contains all integers which are larger or equal to $-5$ and smaller or equal to $-2$, its elements are $-5,-4,-3,-2$.
+ This set contains all real 4th roots of 16, its elements are $-2,2$.
+ This set contains all real roots of the quadratic equation $x^2 + 11x + 28 = 0$, its elements are $-4,-7$.
+ This set contains all real roots of $tan pi x$, $tan$ is equal to zero when its input is equal to a multiple of $pi$ and thus this set is just all integers. Some elements include $-2,-1,0,1,2$.
+ This set contains all integers who's absolute value is strictly less than $6$, its elements are $-5,-4,-3,-2,-1,0,1,2,3,4,5$.
]
== Question 2
Find the cardinalities of the following sets
#MultiColumnBox[
+ ${{1},{2,{3,4}},nothing}$
+ ${{{1},{2,{3,4}},nothing}}$
+ ${ x in ZZ : |x| < 10 }$
+ ${ x in ZZ : x^2 < 10 }$
+ ${ x in NN : x^2 < 0 }$
+ ${ x in NN : 5x <= 20 }$
]
#answer[
== Solution
#MultiColumnBox(height: 39pt, column_number: 2)[
+ $|{{1},{2,{3,4}},nothing}| = 3$
+ $|{{{1},{2,{3,4}},nothing}}| = 1$
+ $|{ x in ZZ : |x| < 10 }| = 19$
+ $|{ x in ZZ : x^2 < 10 }| = 7$
+ $|{ x in NN : x^2 < 0 }| = 0$
+ $|{ x in NN : 5x <= 20 }| = 5$
]
]
= Topic 2 - Set Identities
== Question 3
For each of the following set equalities, prove it using set identities and then by double inclusion.
#MultiColumnBox(height: 39pt, column_number: 2)[
+ $A backslash B = A backslash (A sect B)$
+ $(A backslash B) sect C = (A sect C) backslash (B sect C)$
+ $A sect (A^c union B) = A sect B$
+ $A backslash (B union C) = (A backslash B) sect (A backslash C)$
+ $(A sect B) union (A sect B^c) = A$
+ $A backslash B = A triangle.t (A sect B)$
]
$A triangle.t B$ is defined to be $(A backslash B) union (B backslash A)$, in other words $x in A triangle.t B$ means $x$ is in $A$ or $B$ but not both.
#answer[
== Solution
+ First with set identities we have
$
A backslash B = A sect B^c = A sect B^c union (A sect A^c) = A sect (B^c union A^c) = A sect (A sect B)^c = A backslash (A sect B)
$
Then for double inclusion assume that $x in A backslash B$, then $x in A$ and $x in.not B$, but then $x in.not A sect B$ so we have $x in A backslash (A sect B)$.
On the other hand assume that $x in A backslash (A sect B)$, then $x in A$ and $x in.not A sect B$. But then we must have $x in.not B$ so $x in A backslash B$.
+ Again with the set identities we have
$
(A backslash B) sect C &= (A sect B^c) sect C = (A sect C) sect B^c
= ((A sect C) sect B^c) union ((A sect C) sect C^c)
\ &= (A sect C) sect (B^c union C^c) = (A sect C) sect (B sect C)^c = (A sect C) backslash (B sect C)
$
For double inclusion assume that $x in (A backslash B) sect C$, then $x in A, x in.not B, x in C$. But then $x in A sect C$ and $x in.not B sect C$ and thus $x in (A sect C) backslash (B sect C)$.
On the other hand assume that $x in (A sect C) backslash (B sect C)$, we have that $x in A sect C$ and $x in.not B sect C$. Then we have that $x in A$ and $x in C$ but then this combined with $x in.not B sect C$ means that $x in.not B$. Thus $x in (A backslash B) sect C$.
+ Again with the set identities we have
$
A sect (A^c union B) = (A sect A^c) union (A sect B)
= nothing union (A sect B) = A sect B.
$
For double inclusion assume that $x in A sect (A^c union B)$, then $x in A$ and $x in A^c union B$. But because $x in A$ we have $x in.not A^c$ so $x in B$. Thus $x in A sect B$.
For the other direction assume that $x in A sect B$, then $x in A$ and $x in B$. Then $x in A^c union B$ since $x in B$, thus $x in A sect (A^c union B)$.
+ Again with set identities we have
$
A backslash (B union C) = A sect (B union C)^c = A sect B^c sect C^c
= A sect B^c sect A sect C^c = (A backslash B) sect (A backslash C).
$
Now for double inclusion assume that $x in A backslash (B union C)$, then $x in A$ and $x in.not B union C$. Then we have $x in.not B$ and $x in.not C$ so we have $x in A backslash B$ and $x in A backslash C$. Thus $x in (A backslash B) sect (A backslash C)$.
For the other direction assume that $x in (A backslash B) sect (A backslash C)$, then $x in A backslash B$ and $x in A backslash C$. Then we have $x in A$ and $x in.not B$ and $x in.not C$. Thus we have $x in.not B union C$ so $x in A backslash (B union C)$.
+ Again with set identities we have
$
(A sect B) union (A sect B^c)
=
A sect (B union B^c) = A.
$
Now for double inclusion assume that $x in (A sect B) union (A sect B^c)$, then $x in A sect B$ and $x in A sect B^c$. Then we must have $x in A$.
For the other direction assume that $x in A$, then either $x in B$ or $x in B^c$. If $x in B$ then $x in A sect B$ so $x in (A sect B) union (A sect B^c)$. On the other hand if $x in B^c$ then $x in (A sect B^c)$ so $x in (A sect B) union (A sect B^c)$.
+ Again with set identities we have by part 1
$
A backslash B = A backslash (A sect B)
$
and we also know that
$
(A sect B) backslash A = (A sect B) sect A^c = nothing sect B = nothing
$
but then
$
A backslash (A sect B) = A backslash (A sect B) union nothing = (A backslash (A sect B)) union ((A sect B) backslash A)
= A triangle.t (A sect B).
$
Now for double inclusion assume that $x in A backslash B$, then $x in A$ and $x in.not B$. Then we have that $x in.not A sect B$ so $x$ is in $A$ but not $A sect B$ and thus $x in A triangle.t (A sect B)$.
For the other direction assume that $x in A triangle.t (A sect B)$, then either $x in A$ or $x in A sect B$ but not both. But now if $x in A sect B$ then surely $x in A$ which would mean $x$ is in both, thus we cannot have $x in A sect B$ and so $x in A$. But now if $x in A$ but $x in.not A sect B$ then we must have that $x in.not B$ and thus $x in A backslash B$.
]
== Question 4
For each of the following pairs of sets $A,B$, list the elements of $A times B, cal(P)(A), cal(P)(B)$.
Assume that the symbols $a,b,c,x,y,z$ all represent distinct elements.
#MultiColumnBox(column_number: 2)[
+ $A = {0, 5, 7}, B = {a,b,c}$.
+ $A = {0, 1, {0,1}}, B = {{x,y}}$.
+ $A = {2, {2}}, B = {x, {y,z}}$.
+ $A = {1,{1,2}}, B = {6,4,5}$.
]
#answer[
== Solution
+ $A times B = {(0,a),(0,b),(0,c),(5,a),(5,b),(5,c),(7,a),(7,b),(7,c)}$.
$cal(P)(A) = {{},{0},{5},{7},{0,5},{0,7},{5,7},{0,5,7}}$.
$cal(P)(B) = {{},{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c}}$.
+ $A times B = {(0,{x,y}),(1,{x,y}),({0,1},{x,y})}$.
$cal(P)(A) = {{},{0},{1},{0,1},{0,{0,1}},{1,{0,1}},{0,1,{0,1}}}$.\
$cal(P)(B) = {{},{{x,y}}}$.
+ $A times B = {(2,x),(2,{y,z}),({2},x),({2},{y,z})}$. \
$cal(P)(A) = {{},{2},{{2}},{2,{2}}}$. \
$cal(P)(B) = {{},{x,y}}$.
+ $A times B = {(1,6),(1,4),(1,5),({1,2},6),({1,2},4),({1,2},5)}$. \
$cal(P)(A) = {{},{1},{1,2},{1,{1,2}}}$. \
$cal(P)(B) = {{},{6},{4},{5},{6,4},{6,5},{4,5},{6,4,5}}$.
]
= Topic 3 - Propositional Logic
== Question 5
For each of the following formulas, write down their truth tables.
#MultiColumnBox(column_number: 2)[
+ $(not p or q) and (p or not q)$.
+ $not p => (q => p)$.
+ $(p or q) => (r and (p or q) => p and q)$
+ $(p and q) or (q and r) or (r and p)$
]
#answer[
== Solution
#box(height: 280pt)[
#columns(2)[
+ #truth-table($(not p or q) and (p or not q)$)
3. #truth-table($(p or q) => (r and (p or q) => p and q)$)
2. #truth-table($not p => (q => p)$)
4. #truth-table($(p and q) or (q and r) or (r and p)$)
]
]
]
== Question 6
For each of the following pairs of logical formulas, decide whether they are logically equivalent.
#MultiColumnBox(height: 39pt, column_number: 2)[
+ $p and q$ and $not (not p and not q)$.
+ $(p => q) or r$ and $not ((p and not q) and not r)$.
+ $not p and (p => q)$ and $not (q => p)$.
+ $not (p => q)$ and $p and not q$.
+ $p or (q and r)$ and $(p or q) and r$.
+ $p and (q or not q)$ and $not p => (q and not q)$.
]
#answer[
== Solution
+ First let us simplify the second formula using De Morgan's laws #h(1fr)
$ not (not p and not q) = not not p or not not q = p or q $
which we expect to not be equivalent to $p and q$. We can check this by setting $p$ to be true and $q$ to be false. Then $p and q$ is false but $not p and not q$ is also false and so $not (not p and not q)$ is true, making them not equivalent.
+ Again we simplify the second formula using De Morgan's laws
$
not ((p and not q) and not r) = (not (p and not q)) or (not not r)
= (not p or q) or r
$
and so we see that these two are indeed equivalent since we can rewrite $p => q$ as $not p or q$.
+ First we will substitute $not p or q$ and $not q or p$ for $p => q$ and $q => p$ respectively, the two formulas then become
$
not p and (not p or q) quad "and" quad not (not q or p)
$
then using De Morgan's laws we get for the second formula
$
not (not q or p) = q and (not p)
$
and for the first formula we see that using absorption laws
$
not p and (not p or q) = not p
$
and so we expect that they should not be equivalent. We test by setting $p$ to be true and $q$ being false. Then we get for the first formula
$
not p and (p => q) = F and (T => F) = F
$
and for the second formula
$
not (q => p) = not (F => T) = not (F) = T
$
and so indeed they are not equivalent.
+ We start by simplifying the first formula
$
not (p => q) = not (not p or q) = p and (not q)
$
and so we quickly reached the second equation, thus they are equivalent.
+ These formulas are hard to simplify any further but they don't look the same and so we suspect they are not equivalent. To check this is indeed the case we need to pick a specific assignment for which they disagree, after some trial and error we can see that if $p$ is true, $q$ is false, and $r$ is false we get
$
p or (q and r) = T or (F and F) = T or F = T
$
for the first formula, and
$
(p or q) and r = (T or F) and F = T and F = F
$
for the second formula.
+ We start by simplifying the first formula
$
p and (q or not q) = p and T = p,
$
and then we simplify the second formula
$
not p => (q and not q) = not p => T = T.
$
We thus get that the second formula is always true, where as the first formula could be false if $p$ is false. Thus the two are not equivalent.
]
= Topic 4 - Predicate logic
== Question 7
For each of the following logical formulas test whether it is a tautology, contradiction or neither.
#MultiColumnBox[
+ $not (p or not p)$.
+ $not (p or not not q) and (p and not q)$.
+ $(p and q) => (p => q)$.
+ $not p and not (not p or not q)$.
+ $(p <=> q) and (p => q)$.
+ $(p => (q => r)) and (r => p)$.
]
#answer[
== Solution
+ We can see that the formula simplifies as #h(1fr)
$
not (p or not p) = not T = F
$
and so is always false, thus it is a contradiction.
+ Simplifying this formula gives us
$
not (p or not not q) and (p and not q)
=
(not p and not q) and (p and not q)
=
F and not q
=
F
$
and so is also a contradiction.
+ Simplifying this formula gives us
$
(p and q) => (p => q) = not (p and q) or (not p or q)
= (not p or not q) or (not p or q)
= not p or not q or q
= T
$
and so this formula is always true, and thus a tautology.
+ Simplifying this formula gives us
$
not p and not (not p or not q)
=
not p and (p and q)
$
which we see is a contradiction since we can't have both $not p$ and $p$ be true.
+ Note that $p <=> q = (p => q) and (q => p)$ so
$
(p <=> q) and (p => q)
= p <=> q
$
which can be true if $p$ and $q$ are true, or false if $p$ is true and $q$ is false. Thus it is neither a contradiction nor a tautology.
+ Finally, here we could try simplify but that would be quite long, instead we notice that if we set $p,q,r$ all to be true then the formula is true, thus it cannot be a contradiction. Now we also notice that we can easily make this sentence false by making $r => p$ false, for example by setting $r$ to be true and $p$ to be false. Then this sentence is also not a tautology and thus it is neither.
]
== Question 8
For each of the following predicates and assignments of variables, find whether the predicate is true or false.
+ $(x + y = z) => (x - y = z)$ with $x = 5$,$y = 0$, $z = 5$.
+ $(2 x = y) or (2 x + 1 = y)$ with $x = 4$, $y = 9$.
+ $(2 x = y) or (2 x + 1 = y)$ with $x = 10$, $y = 9$.
+ $(z dot x = y) and (z + x = y)$ with $x = 2$, $y = 4$, and $z = 2$.
#answer[
== Solution
+ We check that $x + y = 5 + 0 = 5 = z$ and $x - y = 5 - 0 = 5 = z$ and so we have
$
(x + y = z) => (x - y = z) = T => T = T
$
and so this predicate is true for this variable assignment.
+ We check that $2 x = 8 != 9 = y$ but $2x + 1 = 8 + 1 = 9 = y$ and thus
$
(2 x = y) or (2 x + 1 = y) = F or T = T
$
and so this predicate is also true for this variable assignment.
+ Here we see that $2 x = 20 != 9 = y$ and also $2 x + 1 = 21 != 9 = y$ and thus
$
(2 x = y) or (2 x + 1 = y) = F or F = F
$
and so this predicate is not true for the this variable assignment.
+ Finally we have that $z dot x = 2 dot 2 = 4 = y$ as well as $z + x = 2 + 2 = 4 = y$ and thus
$
(z dot x = y) and (z + x = y) = T and T = T
$
and so this predicate is true for this variable assignment.
]
= Topic 5 - Quantifiers
== Question 9
For each of the following quantified formulas, write the formula in English, then prove whether it is true or false.
#MultiColumnBox(height: 3em+2pt, column_number: 2)[
+ $forall x in RR, x^2 > 0$.
+ $exists a in RR, forall x in R, a dot x = x$.
+ $forall n in NN, exists X in cal(P)(NN), |X| < n$.
+ $forall X in cal(P)(NN), exists n in ZZ, |X| = n$.
+ $forall n in ZZ, exists m in ZZ, m = n + 5$.
+ $forall n in NN, exists m in NN, 0 = m + n$.
]
#answer[
== Solution
First we will write the English interpretation, then discuss whether it is true or false.
+ For every real number, its square is strictly positive. This is false since $0 in RR$ and $0^2 = 0$.
+ There exists a real number $a$, such that for every real number $x$, their product is $x$. This is true since we can pick $a = 1$ then for any $x in RR$ we have $1 dot x = x$.
+ For every natural number $n$ there is a subset $X$ of the natural numbers who's cardinality is strictly less than $n$. This is false, since $0 in NN$ and there is no subset of the natural numbers who's cardinality is strictly less than $0$, the lowest it can be is $0$.
+ For every subset $X$ of the natural numbers, there is a natural number $n$ which is equal to the cardinality of $X$. This is not true, since $NN seq NN$ then $NN in cal(P)(NN)$, but there is no natural number such that the cardinality of $NN$ is equal to that number.
+ For every integer $n$ there is an integer $m$ which is equal to $n$ plus $5$. This is true since the addition of two integers is still an integer and so setting $m = n + 5$ gives us exactly what we want.
+ For every natural number $n$, there is a natural number $m$ such that their sum is zero. This is false, if $n = 1$ then there is no natural number which adds to $1$ to give zero.
]
== Question 10
For each of the following English sentences, translate it into a logical formula.
+ If $x$ is a prime, then $sqrt(x)$ is not a rational number.
+ For every positive number $epsilon$, there is a positive number $delta$ for which $|x-a| < delta$ implies $|f(x) - f(a)| < epsilon$.
+ If $x$ is a rational number and $x != 0$ then $tan(x)$ is not a rational number.
+ If $sin(x) < 0$ then it is not the case that $0 <= x <= pi$.
+ For every prime number $p$, there is another prime number $q$ with $q > p$.
#answer[
== Solution
We will use $P$ to denote the set of prime numbers.
+ "If $x$ is a prime" implicitly quantifies over all primes, then $sqrt(x)$ not being a rational number can be written as $sqrt(x) in.not QQ$. Together this gives us
$
forall x in P, sqrt(x) in.not QQ
$
+ To quantify over a positive number, we can quantify over all real numbers then include $epsilon > 0$ as 'assumption' as you will see later. Then the existence of $delta$ can be written as $exists delta in RR, delta > 0$. The last part of the sentence is a standard implication. Together this then gives us
$
forall epsilon in RR, (epsilon > 0 => exists delta, delta > 0 and (forall x in RR, |x - a| < delta => |f(x) - f(a)| < epsilon))
$
+ Again "If $x$ is a rational number" implicitly quantifies over all rational numbers, then we will again use $x != 0$ as an 'assumption' and then $tan(x)$ being not a rational number can be written as we did in part 1. All Together this gives us
$
forall x in QQ, (x != 0 => tan(x) in.not QQ)
$
+ We are again implicitly quantifying over all $RR$, then we will use $sin(x) < 0$ as our 'assumption'. Then "it is not the case that $0 <= x <= pi$" can be written as $not (0 <= x <= pi)$ but this is a sort of shorthand, really we need to write $not (0 <= x and x <= pi)$. Together this gives
$
x in RR, (sin(x) < 0 => not (0 <= x and x<= pi))
$
+ We are clearly quantifying over all primes, then we claim existence, so this easily translates to
$
forall p in P, exists q in P, q > p
$
]
= Topic 6 - Contrapositive and Contradiction
== Question 11
Prove the following statements using a contrapositive proof.
+ Suppose $a,b in ZZ$. If $a^2(b^2 - 2b)$ is odd, then $a$ and $b$ are odd.
+ Suppose $x in RR$. If $x^3 - x > 0$ then $x > -1$.
+ Suppose $n in ZZ$. If $3$ does not divide $n^2$, then $3$ does not divide $n$.
+ Suppose $a in ZZ$. If $a^2$ is not divisible by 4, then $a$ is odd.
+ Suppose $a,b in ZZ$. If both $a b$ and $a+b$ are even, then both $a$ and $b$ are even.
+ Suppose $x,y,z in ZZ$ and $x != 0$. If $x$ does not divide $y z$, then $x$ does not divide $y$ and also does not divide $z$.
#answer[
== Solution
The strategy here is quite simple, first we will rewrite the sentence as a logical formula, then we will apply the contrapositive rule to that formula which we will then try to prove.
+ We can rewrite this as #h(1fr)
$
forall a in ZZ, forall b in ZZ, (a^2(b^2 - 2b) "is odd" => a "is odd" and b "is odd")
$
then by the contrapositive rule this is equivalent to
$
forall a in ZZ, forall b in ZZ, (not (a "is odd" and b "is odd") => not (a^2(b^2 - 2b) "is odd") )
$
which simplifies
$
forall a in ZZ, forall b in ZZ, (a "is even" or b "is even" => a^2(b^2 - 2b) "is even" )
$
which we can write as: "Suppose $a,b in ZZ$, if $a$ is even or $b$ is even, then $a^2(b^2-2b)$ is even."
This we is quite simple to prove, if $a$ is even then $a = 2k$ for some integer $k$ so
$
a^2(b^2 - 2b) = 2 (2k^2 (b^2 - 2b)).
$
Then since $2 k^2 (b^2 - 2b)$ is an integer then $a^2 (b^2 - 2b)$ is even. On the other hand if $b$ is even then $b = 2k$ for some integer $k$ and so
$
a^2(b^2 - 2b) = a^2 (4k^2 - 4k) = 2(a^2 (2k^2 - 2k))
$
and so since $a^2 (2k^2 - 2k)$ is an integer then $a^2(b^2 - 2b)$ is even. Thus we have proved the contrapositive and thus also the original statement.
+ We can rewrite this statement as
$
forall x in RR, (x^3 - x > 0 => x > -1)
$
then by contrapositive this is equivalent to
$
forall x in RR, (x <= -1 => x^3 - x <= 0).
$
Now this is a true statement, to see this factorize $x^3 - x$ as $x(x^2 - 1)$, if $x<=-1$ then $x^2 >= 1$ and $x <= 0$ so $x$ is non-positive and $x^2 - 1$ is non-negative, thus their product is non-positive, which is exactly $x^3 - x <= 0$.
+ We can rewrite this statement as
$
forall n in ZZ, (n^2 "not divisible by" 3 => n "not divisible by" 3)
$
and so by contrapositive this is equivalent to
$
forall n in ZZ, (n "divisible by" 3 => n^2 "divisible by" 3).
$
Now this is clearly true since if $n$ is divisible by 3 then $n = 3k$ for some integer $k$ and so $n^2 = 9k^2 = 3(3k^2)$. But now $3k^2$ is an integer and so $n^2$ is divisible by $3$.
+ This is solved exactly as the above part.
+ We can rewrite this statement as
$
forall a in ZZ, forall b in ZZ, (a b "is even" and a + b "is even" => a "is even" and b "is even")
$
and so by contrapositive this is equivalent to
$
forall a in ZZ, forall b in ZZ, (a "is odd" or b "is odd" => a b "is odd" or a + b "is odd").
$
This is a true statement, if $a$ is odd and $b$ is odd then $a b$ is also odd. On the other hand if $a$ is odd and $b$ is even, then $a + b$ is also odd. If $a$ is even and $b$ is odd then $a + b$ is also odd.
+ We can rewrite this statement as
$
forall x in ZZ backslash {0}, y in ZZ, z in ZZ, (x "does not divide" y z => x "does not divide" y and x "does not divide" z).
$
then by contrapositive this is equivalent to
$
forall x in ZZ backslash {0}, y in ZZ, z in ZZ, (x "divides" y or x "divides" z => x "does divide" y z).
$
This is again true since if $y = x(k)$ for some integer $k$ then $y z = x (z k)$ and since $z k$ is an integer then $y z$ is divisible by $x$. Similarly if $z = x(k)$ for some integer $k$ then $y z = x (y k)$ and since $y k$ is an integer then $y z$ is divisible by $x$.
]
== Question 12
Prove the following statements using contradiction.
+ $root(3,2)$ is irrational.
+ If $a,b in ZZ$, then $a^2 - 4b - 2 != 0$.
+ Suppose $a,b in RR$. If $a$ is rational and $a b$ is irrational, then $b$ is irrational.
+ For every positive $x in QQ$, there is a positive $y in QQ$ for which $y < x$.
+ If $b in ZZ$ and $b$ does not divide $k$ for every $k in NN backslash {0}$, then $b = 0$.
+ Suppose $a,b in ZZ$. If $4$ does divide $a^2 + b^2$, then $a$ and $b$ are not both odd.
#answer[
== Solution
+ Assume that $root(3,2)$ is rational, then we can write $root(3,2) = p/q$ with $p,q$ integers, $q != 0$ and $gcd(p,q) = 1$. Now since this is true we have that
$
2 = (p/q)^3 = p^3/q^3 "and so" 2 q^3 = p^3
$
Now this means that $p^3$ is even and so $p$ must be even, since if $p$ was odd then $p^3$ would also be odd. But then $p = 2k$ for some integer $k$ and so $q^3 = 4 k^3$, but then $q^3$ is also even and so $q = 2 ell$ for some integer $ell$. But then $gcd(p,q) >= 2$ which contradicts our assumption. Thus by contradiction $root(3,2)$ is irrational.
+ Assume that there exists $a,b in ZZ$ with $a^2 - 4 b - 2 = 0$. Then we have $a^2 = 4b + 2$ and so $a^2$ is even, but now again if $a^2$ is even then $a$ is even. But then for some $k$ we have $a = 2k$ and so $a^2 = 4k^2$. But now we have $4 k^2 = 4 b + 2$.
Now we can rearrange this to give us that $2 = 4(k^2 - b)$ and so $4$ divides $2$ since $k^2 - b$ is an integer. But this is a contradiction since $4$ does not divide $2$.
+ Suppose for a contradiction that there exist $a,b in RR$ with $a$ rational, $a b$ irrational, and $b$ rational. Now $a b$ is then a product of two rational numbers, and is thus rational. But we assumed it is irrational, this is a contradiction, thus the statement holds.
+ Assume there exists a positive $x in QQ$ such that for every $y in QQ$ which is positive, $y >= x$. Then $x/2$ is a positive rational number but $x/2 < x$ since $x$ is positive, but also $x/2 >= x$ since it is a positive rational. This is a contradiction and so the statement holds.
+ Assume there exists a $b in ZZ$ which is not zero and does not divide any non-zero natural number $k in NN backslash {0}$. Then if $b$ is positive, then it is also a natural number and it divides itself, which is a contradiction. On the other hand if $b$ is negative, then $-b$ is positive and so $b$ divides $-b$ which is a natural number, this is also a contradiction. Thus the statement holds.
+ Assume that there exists $a,b in ZZ$ with $4$ dividing $a^2 + b^2$ and both $a$ and $b$ odd. Then since $a$ is odd it is equal to $2k + 1$ for some integer $k$, and $b = 2 ell + 1$ for some integer $ell$. Now from this we know that
$
a^2 + b^2 = (2k+1)^2 + (2ell+1)^2 = 4k^2 + 4k + 1 + 4ell^2 + 4ell +1
= 4(k^2 + k + ell^2 + ell) + 2.
$
But then if $a^2 + b^2$ divides 4 then since
$
2 = a^2 + b^2 - (4k^2 + k + ell^2 + ell)
$
then $2$ also divides $4$. This is a contradiction and thus the statement holds.
]
= Topic 7 - Induction and Functions
== Question 13
Prove the following statements using induction.
+ If $n in NN backslash {0}$, then $2^1 + 2^2 + 2^3 + dots.c + 2^n = 2^(n+1) - 2$.
+ Prove that $24 | (5^(2n) - 1)$ for every $n in NN$.
+ Prove that $2^n + 1 <= 3^n$ for every positive integer $n$.
+ Suppose that $A_1,A_2,...,A_n$ are sets in some universal set $U$, and $n >= 2$. Prove that $(A_1 union A_2 union ... union A_n)^c = (A_1)^c sect (A_2)^c sect ... sect (A_n)^c$.
+ If $n in NN backslash {0}$, then $1+1/4 +1/9 + ... + 1/n^2 <= 2 - 1/n$.
#answer[
== Solution
+ We start with the base case $n = 1$, in which we have
$
2^1 = 2^(1+1) - 2
$
and so in the base case it is true. Now assume that the statement holds for $n = k$, then for $n = k + 1$ we have
$
2^1 + dots.c + 2^k + 2^(k+1)
=
(2^1 + dots.c + 2^k) + 2^(k+1).
$
Now by inductive hypothesis, the contents of the brackets are equal to $2^(k+1) - 2$ and so we have
$
(2^1 + dots.c + 2^k) + 2^(k+1)
=
(2^(k+1) - 2) + 2^(k+1)
= 2^(k+2) - 2
= 2^((k+1) + 1) - 1
$
and so the statement holds for $n = k + 1$. Thus by induction it holds for all natural numbers.
+ Again we start with the base case, if $n = 0$ then
$
5^(2n) - 1 = 5^0 - 1 = 0,
$
and indeed $24$ divides $0$ since all integers divide $0$. Now assume that the statement hods for $n = k$, then for $n = k + 1$ we have
$
5^(2n) - 1 = 5^(2(k+1)) - 1 = 25 dot 5^(2k) - 1
= 25 dot (5^(2k) - 1) + 25 - 1
= 25 dot (5^(2k) - 1) + 24.
$
Now by inductive hypothesis, we have that $24$ divides $5^(2k) - 1$ and we have $5^(2k) - 1 = 24 dot m$ for some integer $m$. But then
$
25 dot (5^(2k) - 1) + 24 = 25 dot 24 dot m + 24 = 24 dot (25 dot m + 1),
$
but now $25 dot m + 1$ is certainly an integer and thus $25 dot (5^(2k) - 1)$ is divisible by $24$.
+ Again we start with the base case, since $n$ needs to be positive, our base case is $n = 1$. If $n = 1$ then
$
2^n + 1 = 2^1 + 1 = 2 + 1 = 3 = 3^n.
$
Assume now, that this statement holds for $n = k$, then for $n = k + 1$ we have
$
2^(n) + 1 = 2^(k+1) + 1 = 2 dot 2^k + 1 = 2 dot (2^k - 1) + 2 + 1
<= 2 dot 3^k + 3.
$
But now for $k >= 1$ we have $3 <= 3^k$ and so
$
2^n + 1 <= 2 dot 3^k + 3 <= 2 dot 3^k + 3^k = 3 dot 3^k = 3^(k + 1) = 3^n
$
+ Here the base case is $n = 2$ where we know by De Morgan's laws that
$
(A_1 union A_2)^c = A_1^c sect A_2^c.
$
Now assume that this holds for $n = k$, then for $n = k + 1$ we have
$
(A_1 union ... union A_n)^c
=
((A_1 union ... union A_k) union A_(k + 1))^c,
$
but then by De Morgan's laws we have that
$
((A_1 union ... union A_k) union A_(k+1))^c
=
(A_1 union ... union A_k)^c sect A_(k+1)^c.
$
But now by inductive hypothesis we have that
$
A_1^c sect ... sect A_k^c sect A_(k+1)^c,
$
which completes the proof.
+ Here again our base case is $n = 1$, for which we have
$
1 <= 2 - 1/1.
$
Now assume that the statement holds for $n = k$, then for $n = k + 1$ we have
$
1 + 1/4 + ... + 1/n^2 = (1 + 1/4 + ... + 1/k^2) + 1/(k+1)^2.
$
Now by inductive hypothesis we have that
$
(1 + 1/4 + ... + 1/k^2) + 1/(k+1)^2
<=
2 - 1/k + 1/(k+1)^2,
$
but also
$
-1/k + 1/(k+1)^2 =
(k-(k+1)^2)/k(k+1)^2
= (-1-k-k^2)/k(k+1)^2
<= (-k-k^2)/k(k+1)^2
= (-1)/(k+1)
$
and so
$
(1 + 1/4 + ... + 1/k^2) + 1/(k+1)^2
<=
2 - 1/k + 1/(k+1)^2
<=
2 - 1/(k+1).
$
]
== Question 14
For each of the following sets, state whether it is a function $f : {1,2,3} -> {1,2,3}$ or not.
#MultiColumnBox[
+ {(1,1),(2,1),(3,1)}
+ {(1,2),(1,3),(2,2),(3,1)}
+ {(1,2),(2,3)}
+ {(1,1),(2,2),(3,3),(2,2)}
+ {(1,3),(2,2),(3,1)}
+ {(1,5),(2,3),(3,2)}
]
#answer[
== Solution
+ This is indeed a function, for each element in ${1,2,3}$ there is exactly one tuple with that element on the left.
+ This this is not a function, since $1$ has two tuples with it on the left, $(1,2)$ and $(1,3)$.
+ This is also not a function, since $3$ has no tuples with it on the left.
+ This is a function, since these are sets we remove all duplicates which leaves us with ${(1,1),(2,2),(3,3)}$ which is a function as in part 1.
+ This is a function, which we can see as in part 1.
+ This is a function, but it is not a function to ${1,2,3}$ since $f(1) = 5$.
]
= Topic 8 - Function Properties and Cardinality
== Question 15
<question-15>
For each of the following functions, state and prove whether it is injective and whether it is surjective.
+ $f : (0,infinity) -> RR$ defined by $f(x) = ln(x)$.
+ $f : ZZ -> ZZ times ZZ$ defined by $f(n) = (2n, n + 3)$.
+ $f : ZZ times ZZ -> ZZ$ defined by $f(m,n) = 2n - 4m$.
+ $theta : {0,1} times NN -> ZZ$ defined by $theta(a,b) = (-1)^a b$.
+ $theta : cal(P)(ZZ) -> cal(P)(ZZ)$ defined by $theta(X) = X^c$.
+ $f : (NN backslash {0}) times (NN backslash {0}) -> (NN backslash {0})$ defined by $f(m,n) = 2^(m-1) (2n-1)$.
#answer[
== Solution
+ This function is indeed injective, to see this let $x,y in (0,infinity)$ be such that $ln(x) = ln(y)$.
Then $e^ln(x) = e^ln(y)$ and so $x = y$. It is also surjective, let $y in RR$ be arbitrary, then $e^y in (0, infinity)$ and $ln(e^y) = y$.
We can also prove both of these another way, since $x |-> e^x$ is an inverse of $ln$ and so the function must be bijective and thus is both injective and surjective.
+ This function is injective, if $n,m in ZZ$ and $f(n) = f(m)$ then $(2n, n+3) = (2m, m+3)$ and so in particular $2n = 2m$. But then by dividing by 2, this is only true if $n = m$.
This function is not surjective, to see this consider $(1,0)$, I claim that $(1,0)$ is never equal to $f(n)$ for any $n$. But for any $n$ we have $f(n) = (2n,n+3)$ and so if they were equal then we would have $1 = 2n$ for some integer $n$. But $2n$ is even for all integer $n$ and so we get a contradiction.
+ This function is not injective, consider $x = (0,0)$ and $y = (2,1)$. Clearly these are not equal but $f(x) =2 dot 0 - 4 dot 0 = 0$, but also $f(y) = 2 dot 2 - 4 dot 1 = 0$ and so $f(x) = f(y)$.
This function is also not surjective, we see this because
$
f(n,m) = 2n - 4m = 2(n - 2m)
$
and so $f(n,m)$ is even for all $n,m$. But then we cannot have $f(n,m) = y$ for any odd $y$ and so this function is not surjective.
+ This function is not injective, this is because for $x = (0,0)$ and $y = (1,0)$ we have $theta(x) = 0 = theta(y)$.
This function is surjective, to see this let $y in ZZ$ be arbitrary. If $y >= 0$ then $y$ is also a natural number and so $theta(0,y) = y$. On the other hand if $y < 0$ then $-y$ is a natural number and so $theta(1,-y) = y$.
+ This function is invertible since it is its own inverse, thus it is bijective and thus is injective and surjective.
+ This map is injective, assume that $f(m_1,n_1) = f(m_2,n_2)$ for some inputs $n_1,m_1,n_2,m_2$. Now since $2n_1 - 1$ and $2n_2 - 1$ are both odd then in the prime decomposition of $f(m_1, n_1)$ the only powers of $2$ come from $2^(m_1 - 1)$ and in the prime decomposition of $f(m_2, n_2)$ the only powers of 2 come from $2^(m_2 - 1)$ respectively. But now since they are equal, their prime decomposition is also equal and so we have $m_1 = m_2$.
Next by dividing both function outputs by $2^(m_1- 1) = 2^(m_2 - 1)$ we get that $2 n_1 - 1 = 2n_2 - 1$ and so $n_1 = n_2$.
This map is also surjective, to see this note that, by prime decomposition, we can write any non-zero integer as $2^k ell$ where $k$ is a natural number and $ell$ is an odd natural number. But every odd natural number can be written as $ell = 2n - 1$ for some non-zero natural number, and so
$
2^k ell = 2^(m-1) (2n - 1)
$
for some $m,n in NN backslash {0}$ and so we are done.
]
== Question 16
For every pair of sets below, show that they have equal cardinality by constructing explicit bijections between them.
#MultiColumnBox(height: 39pt, column_number: 2)[
+ $RR$ and $(0,infinity)$.
+ The set of even integers and the set of odd integers.
+ $ZZ$ and $S = {..., 1/8,1/4,1/2,1,2,4,8,16,...}$.
+ $[0,1]$ and $(0,1)$ (this one is quite tricky).
]
#answer[
== Solution
+ The map here is $ln(x)$, as we saw in #link(<question-15>)[Question 15] it is bijective and so we are done.
+ Here the map is also quite simple, let $E$ be the set of even integers and $O$ be the set of odd integers.
Consider the map $f(x) = x+1$, since for every even number $x$ we have $x + 1$ is odd and thus $f : E -> O$. Now this map is bijective since $g(x) : O -> E$ defined by $g(x) = x - 1$ is its inverse.
+ Consider the map $f : ZZ -> S$ defined by $(n) = 2^(n)$. This map is injective since, by taking logarithms base 2, if $2^n = 2^m$ then $n = m$. Now clearly it is also surjective since every element of $S$ can is some integer power of 2. Thus $f$ is bijective.
+ This is the trickiest of the bunch, to define this map we need to consider an infinite sequence of elements, $a_1,a_2,a_3,...$ such that all the elements are in $(0,1)$ and they are all distinct. We now define a map $f : (0,1) -> [0,1]$ by
$
f(x) = cases(x &"if" x in (0,1) "and" x != a_n "for some" n \
0 &"if" x = a_1 \
1 &"if" x = a_2 \
a_(i-2) &"if" x = a_i "for some" i > 2
)
$
We now claim that this map is bijective, first to see injective assume $x,y in (0,1)$ with $f(x) = f(y)$. Now if $f(x) in (0,1) backslash {a_i : i >= 1}$ then by the definition above we have that $f(x) = x$ and $f(y) = y$ and thus $x = y$. If $f(x) = 0$ or $f(x) = 1$ then by the definition above $x = a_1$ or $x = a_2$ respectively, and the same holds for $y$, thus we have $x = y$. Finally if $f(x) = a_i$ for some $i$, then $x = a_(i+2)$ and also $y = a_(i+2)$ and so again $x = y$. Thus we have showed injectivity.
To see that it is surjective let $y$ be arbitrary in $[0,1]$. If $y = 0$ or $y = 1$ then by the second and third case in the definition we have some $x$ such that $f(x) = y$. If $y = a_i$ for some $i$ then $f(a_(i+2)) = a_i = y$. Finally if neither of these are true then $y in (0,1) backslash {a_i : i >= 1}$ and so $f(y) = y$. Thus we have showed surjectivity.
]
= Topic 9 - Relations
== Question 17
For each of the following sets and relations on said sets, decide if they reflexive? Symmetric? Transitive?
+ On the set $A = {a,b,c,d}$, the relation $R = {(a,a),(b,b),(c,d),(d,d),(a,b),(b,a)}$.
+ On the set $A = {a,b,c}$, the relation $R = {(a,b),(a,c),(c,b),(b,c)}$.
+ On the set $RR$, the relation $R = {(0,0),(sqrt(2),0),(0,sqrt(2)),(sqrt(2),sqrt(2))}$.
+ On the set $ZZ$, the relation $R = {(x,y) in ZZ times ZZ : |x - y| < 1}$.
#answer[
== Solution
+ Since $(c,c)$ is not in the relation, this relation is not reflexive. This relation is also not symmetric, since $(c,d)$ is in the relation but $(d,c)$ is not. Finally this relation is transitive, we see this by checking each pair of tuples.
+ Since $(a,a)$ is not in the relation, this relation is not reflexive. This relation is not symmetric since $(a,c)$ is in the relation but $(c,a)$ is not. Finally, this relation is is also not transitive, for example the two pairs $(b,c)$ and $(c,b)$ are in the relation but $(b,b)$ is not.
+ This relation is not reflexive, for instance $1 in RR$ but $(1,1)$ is not in the relation. This relation is symmetric, we can see this by checking that the first and last pairs in the relation are their own reflections and the second and third pair are each others reflections. This relation is also transitive, to see this note that if $a R b$ under this relation then necessarily both $a$ and $b$ are in ${0,sqrt(2)}$. But all possible pairs of elements in this set are in the relation, so if $a R b$ and $b R c$ then both $a$ and $c$ are in ${0,sqrt(2)}$ and so $a R c$.
+ This relation is reflexive, for any $x in ZZ$ we have $|x - x| = 0 < 1$ and so $(x,x) in R$. Next this relation is also symmetric, if $(x,y) in R$ then $|x - y| < 1$ and so $|y - x| < 1$ and thus $(y,x) in R$. This relation is not transitive, for example $(0,1/2) in R$ since $|0-1/2| = 1/2 < 1$ and $(1/2,1) in R$ since $|1/2 - 1| = 1/2 < 1$, but $(0,1) in.not R$ since $|0 - 1| = 1 lt.not 1$.
]
== Question 18
For each of the following relations, prove they are equivalence relations.
For the second and the third relations, describe their equivalence classes.
+ On the set $A = {1,2,3,4,5,6}$ the relation
$
R = {(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(2,3),(3,2),(4,5),(5,4),(4,6),(6,4),(5,6),(6,5)}
$
+ On the set $ZZ$ the relation $R = {(x,y) : 3x - 5y "is even"}$.
+ On the set $A = { f "a function", f : RR -> RR }$ the relation $R = {(f,g) : f(0) = g(0)}$.
+ On the set $RR times RR$ the relation $R = { ((x_1,y_1),(x_2,y_2)) : x_1 y_1 = x_2 y_2 } $.
#answer[
== Solution
+ Clearly its reflexive, to see that it is symmetric we note that apart from the reflexive pairs, consecutive pairs in the set are reflections of each other. To see transitivity note that $1$ is not related to anything beside itself, $2,3$ are both related, and $4,5,6$ are all pairwise related. If $a R b$ and $b R c$ in this relation both $a$ and $c$ would fall in one of the 3 classes above and thus also be related. These happen to be the equivalence classes of this relation.
+ This relation is clearly reflexive since if $x in ZZ$ then $3x - 5x = -2x$ which is always even since $x$ is an integer. It is also symmetric since if $(x,y) in R$ then $3x - 5y$ is even but then
$
3y - 5x = 8 y - 5 y + 3 x - 8 x = 3x - 5y + 8(y - x).
$
Thus since $3x - 5y$ is even, $3y - 5x$ as a sum of even numbers is also even, thus $(y,x) in R$.
Finally this relation is also transitive, if $(x,y) in RR$ and $(y,z) in RR$ then
$
3x - 5z = 3x - 5y + 5y - 5z = (3x - 5y) + (3y - 5z) + 2y
$
and so since $3x - 5y$ and $3y - 5z$ are both even then $3x - 5z$ is also even.
The equivalence classes of this relation are exactly the even numbers and the odd numbers. Notice that for any two even numbers $x,y$, $3x - 5y$ is clearly even since both $3x$ and $-5y$ are even. Similarly for any two odd numbers $x,y$, $3x$ and $-5y$ are both odd so $3x - 5y$ is even. Finally if $x$ is odd and $y$ is even then $3x$ is odd and $-5y$ is even so $3x - 5y$ is odd.
+ This relation is clearly reflexive since for any $f in A$ we have $f(0) = f(0)$ and so $(f,f) in R$. This relation is also symmetric since if $(f,g) in R$ then $f(0) = g(0)$ and so $g(0) = f(0)$ and thus $(g,f) in R$. Finally for transitivity, assume that $(f,g) in R$ and $(g,h) in R$ then $f(0) = g(0)$ and $g(0) = h(0)$ so $f(0) = h(0)$ and thus $(f,h) in R$.
The equivalence classes of this relation correspond to numbers in $RR$, for each number $c in RR$ we have an equivalence class of all functions $f : RR -> RR$ with $f(0) = c$.
+ This relation is also clearly reflexive since if $(x,y) in RR times RR$ then $x y = x y$ and so $((x,y),(x,y) in R$.
This relation is also symmetric since if $x_1 y_1 = x_2 y_2$ then $x_2 y_2 = x_1 y_1$. Finally it is transitive since if $x_1 y_1 = x_2 y_2$ and $x_2 y_2 = x_3 y_3$ then $x_1 y_1 = x_3 y_3$.
]
|
|
https://github.com/miliog/typst-penreport | https://raw.githubusercontent.com/miliog/typst-penreport/master/typst-penreport/content/target_table.typ | typst | MIT No Attribution | #let targetTable(targets) = [
#table(
fill: (col, row) => if row == 0 { luma(240) },
columns: (auto, 1fr),
inset: 10pt,
stroke: (paint: gray, thickness: 1pt),
align: left,
[*Target*],
[*Additional Information*],
..for target in targets {
({target.name},{target.additionalInfo})
}
)
] |
https://github.com/EricWay1024/Homological-Algebra-Notes | https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/libs/bw.typ | typst | #import "@preview/ctheorems:1.1.2": *
#let thmboxparams = (
breakable: true,
separator: [#h(0em).#h(0.2em)],
padding: (top: 0.75em, bottom: 0.5em),
inset: 0em,
)
#let thmboxparams2 = (
bodyfmt: emph,
)
#let theorem = thmbox(
"theorem",
"Theorem",
..thmboxparams,
..thmboxparams2,
)
#let lemma = thmbox(
"theorem",
"Lemma",
..thmboxparams,
..thmboxparams2,
)
#let proposition = thmbox(
"theorem",
"Proposition",
..thmboxparams,
..thmboxparams2,
)
#let definition = thmbox(
"theorem",
"Definition",
..thmboxparams,
)
#let example = thmbox(
"theorem",
"Example",
breakable: true,
separator: [#h(0em).#h(0.2em)],
inset: 0em,
)
#let remark = thmplain(
"theorem",
"Remark",
breakable: true,
inset: 0em,
separator: [#h(0em).#h(0.2em)],
)
#let note = thmplain(
"theorem",
"Note",
breakable: true,
separator: [#h(0em).#h(0.2em)],
inset: 0em,
)
#let notation = thmplain(
"theorem",
"Notation",
breakable: true,
separator: [#h(0em).#h(0.2em)],
inset: 0em,
)
#let corollary = thmbox(
"theorem",
"Corollary",
..thmboxparams,
..thmboxparams2,
)
|
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/bug_mix_context_type.typ | typst | Apache License 2.0 | // contains: base
#let tmpl2(x, y) = {
assert(type(x) in (int, str) and type(y) == int)
x + y
}
#tmpl2( /* range -1..0 */) |
https://github.com/jaapgeurts/typst-templates | https://raw.githubusercontent.com/jaapgeurts/typst-templates/master/recipe/0.0.1/recipe.typ | typst | #let recipe(
// The paper's title.
title: "Recipe Title",
website: none,
// An array of authors. For each author you can specify a name,
// department, organization, location, and email. Everything but
// but the name is optional.
authors: (),
// A list of tags to show in the paper and the pdf
tags: (),
// The article's paper size. Also affects the margins.
paper-size: "a4",
illustration: "default.jpg",
// cooking time in minutes
duration: (15,20),
// number of people
people: 4,
// The recipies
ingredients: lorem(20),
instructions: lorem(20),
notes: none,
rest
) = {
// Set document metadata.
set document(title: title, keywords: tags)
// Set the body font.
set text(font: "Lato", size: 10pt)
// Configure the page.
set page(
paper: paper-size,
margin: 2cm
)
// Configure lists.
//set enum(indent: 10pt, body-indent: 9pt)
// set list(indent: 10pt, body-indent: 9pt)
// Display the paper's title.
line(length: 100%,stroke: 1.2pt)
v(0.7em, weak: true)
align(center, block(text(size:24pt, weight: "extrabold", upper(title))))
v(0.7em, weak: true)
line(length: 100%, stroke: 1.2pt)
v(0.4cm, weak: true)
if link != none {
set text(size:0.9em, style:"italic")
link(website)
}
v(0.7cm, weak: true)
let cell = block.with(fill: blue.lighten(80%), width: 100%, inset: 5pt)
grid(
columns: (30%-2.5mm,5mm, 70%-2.5mm),
gutter: (1cm),
// INGREDIENTS
block[
#align(right, block[
#stack(dir: ltr,
image("ingredients.svg", height:1.3em),h(3mm),
text(size:1.2em,fill: blue.darken(20%), weight: "bold",underline("INGREDIENTS:"))
)])
#v(5mm)
#set align(right)
#set list(marker:"")
#ingredients
#if notes != none {
v(5mm)
align(right, block(text(size:1.2em,fill: blue.darken(20%), weight: "bold",underline("NOTES:"))))
par(justify: true, notes)
}
],
line(length: 100%-4cm, angle: 90deg, stroke: 0.5pt),
// INSTRUCTIONS
block(width: 100%-2cm, inset: 0pt)[
// TIMES & PEOPLE
#grid(columns: (33%,34%,33%),
gutter: 0pt,
cell[#align(center)[Preparation time]],
cell[#align(center)[Cook time]],
cell[#align(center)[Nr of People]])
#v(0.6em,weak:true)
#grid(columns: (33%,34%,33%),
gutter: 0pt,
align(center)[#duration.at(0)min],
align(center)[#duration.at(1)min],
align(center)[#people])
#line(length: 100%, stroke: 0.5pt)
#figure(
rect(image(illustration, width: 100%, height: 5cm),inset: 0pt)
)
#v(7mm)
#align(left, block[
#stack(dir: ltr,
image("preparation.svg", height:1.3em),h(3mm),
text(size:1.2em,fill: blue.darken(20%),weight: "bold",underline("INSTRUCTIONS:")))
])
#v(5mm)
#set enum(full: true, numbering: (..args) => {
let nums = args.pos()
strong(numbering("1.", nums.last()))
},)
#instructions
]
)
rest
} |
|
https://github.com/adam-zhang-lcps/papers | https://raw.githubusercontent.com/adam-zhang-lcps/papers/main/barbie-bungee-jump.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "@preview/tablex:0.0.6": tablex, rowspanx
#import "aet-lab-report-template.typ": aet-lab-report
#show: doc => aet-lab-report(
title: "Calculating the Mass Needed to Stretch an Elastic Material",
course: "AET AP Physics C: Mechanics",
teacher: "Mr. <NAME>",
date: datetime(year: 2024, month: 01, day: 30),
appendix: [
#let data = csv("assets/barbie-bungee-jump/data.csv")
#show figure: set block(breakable: true)
#figure(caption: [Raw Data from Materials Tester])[
#table(columns: (auto, auto, auto, auto, auto), ..data.flatten())
] <raw-data>
],
doc,
)
= Introduction
== Purpose
Determine the mass $m$ required to stretch a 2.5m length of thin surgical
tubing exactly to the floor when dropped from a height of 6.0m.
== Hypothesis
0.515kg of mass will be needed to be attached to the end of the elastic
surgical tubing in order to stretch it 6.0m when dropped.
== Background <background>
Elastic materials exhibit relationships between force ($F$) and displacement ($x$).
While many materials obey Hooke's Law and demonstrate relationships that are
linear, others instead exhibit more complicated relationships.
Work done on a system is equal to the change in energy of that system, and can
be found by integrating force with respect to distance.
$ W = integral F(x) dif x $
Therefore, if the displacement vs. force graph for an elastic material is
known, the work done by that material can be calculated
@Hilsdorf2024BarbieBungeeJump. Part one of this experiment will use a material
testing device to empirically calculate a displacement vs. force function via
regression.
Part two of this experiment considers a bungee jump scenario. In such a
scenario, an elastic material with length $L$ is attached to a mass, which is
then dropped. The material stretches a distance $y$ until, for a moment in
time, the mass comes to rest. Since the elastic material exerts no force until
the mass has fallen its length, it will begin to do work once the mass reaches
a distance of $L$ @Hilsdorf2024BarbieBungeeJump.
$ W_"elastic" = -integral_L^y F(x - L) dif x $
$ W_"elastic" = -integral_0^(y-L) F(x) dif x $
Additionally, gravity also does work on the mass, equal to $m g y$. Since the
motion considered begins and ends at rest, the change in the kinetic energy of
the mass must be zero, which means that the work done by the elastic material
and the work done by gravity must be equal and opposite.
$ -W_"elastic" = W_g $
$ -integral_0^(y-L) F(x) dif x = m g y $
This experiment aims to calculate the mass required to stretch a 2.5m length
of thin surgical tubing 6.0m using the above equation.
= Methods
== Materials
- 3m of thin surgical tubing
- Meter stick
- Tape measure
- Mass set
- Materials Tester
- Tape
- Video recording device
- Barbie
- Scale
== Procedure
This experiment has two procedures. The first procedure will use the materials
tester to empirically calculate a force of distance function, $F(x)$, for the
surgical tubing. The second procedure will use the calculated function to
hypothesize a mass which, when dropped, will stretch 2.5m of thin surgical
tubing exactly 6.0m.
=== Part 1 <procedure-1>
+ Cut out 0.10m of thin surgical tubing.
+ Use the materials tester to obtain force vs. distance data for the surgical
tubing.
+ Using the obtained CSV data, calculate strain data ($epsilon_x$) with the load
and distance columns.
+ Fit a second-degree polynomial regression to strain vs. force ($epsilon_x$ vs $F$).
+ Using the calculated function, evaluate $integral_0^(y-L) F(x) dif x$.
+ With the resulting value for energy, solve for the needed mass $m$ as shown in
Equation 4.
An example of using the materials tester is shown in
@materials-tester-picture.
#figure(
caption: [Using the Materials Tester],
)[
#image("assets/barbie-bungee-jump/materials-tester-setup.png", width: 50%)
] <materials-tester-picture>
=== Part 2
+ Using the leftover surgical tubing, measure out 2.5m using the tape measure,
and indicate the exact length using tape. Ensure there is extra space on both
ends of the tubing to tie knots.
+ Measure Barbie's mass using the scale.
+ Attach the calculated mass from #link(label("procedure-1"), [Part 1]) minus
Barbie's mass to Barbie.
+ Tie one end of the surgical tubing to Barbie, ensuring that the knot ends
where the tape indicates.
+ Tie the other end of the surgical tubing to the drop platform, again ensuring
the knot ends where the tape indicates.
+ Place a meter stick on the ground to use as a frame of reference.
+ Drop Barbie from rest. Use a device to record the drop to determine how close
to the ground Barbie reached.
An example of Barbie's setup before dropping is shown in
@barbie-setup-picture.
#figure(caption: [Barbie's Drop Setup])[
#image("assets/barbie-bungee-jump/barbie-setup.jpg", width: 50%)
] <barbie-setup-picture>
= Results
== Data
The graph of strain vs. load obtained from the data collected using the
Materials Tester is shown in @strain-load-graph, along with a third-degree
polynomial regression. @potential-energy-graph shows the corresponding
potential energy curve. @summary shows a summary of the other values measured
or calculated (see #link(label("calculations"), "Calculations")) throughout
this experiment. A table containing all the raw readings from the materials
tester in available in @raw-data in the Appendix.
#figure(
image("assets/barbie-bungee-jump/strain-load.svg", width: 70%),
caption: [Strain (m/m) vs. Load (N)],
) <strain-load-graph>
#figure(
image("assets/barbie-bungee-jump/strain-potential-energy.svg", width: 70%),
caption: [Strain (m/m) vs. Potential Energy (J)],
) <potential-energy-graph>
#figure(table(
columns: (auto, auto),
[$L$],
[2.5m],
[$m$],
[0.515kg],
[$y_"experimental"$],
[5.47cm],
[% Error],
[8.83%],
), caption: [Summary of Values]) <summary>
== Calculations <calculations>
=== Part 1
The function obtained from regression is of strain; first, it must be adjusted
to use the specific trial distance (2.5m).
$ F_"strain" (epsilon) = 4.772epsilon^3 - 15.251epsilon^2 + 21.320epsilon + 0.419 $
$ F(x) = F_"strain" (x/L) = F_"strain" (x/2.5) = 0.305408x^3 - 2.44016x^2 + 8.528x + 0.419 $
Then, $F(epsilon)$ can be substituted into the left side of the equation from
the #link(label("background"), "Background"), and then solved for $m$.
$ integral_0^(y-L) F(x) dif x = m g y $
$ integral_0^(6.0-2.5) F(x) dif x = m (9.8) (6.0) $
$ integral_0^3.5 F(x) dif x = 58.8m $
$ 58.8m = 30.284 $
$ m = 0.515"kg" $
=== Part 2
The expected stretch length was 6.0m, while the experimental stretch length
was only 5.47m. This results in a percent error of 8.83%.
$ "% error" &= (|"experimental" - "theoretical"|)/"theoretical" dot 100 \
&= (|5.47 - 6.0|)/6.0 dot 100 \
&= 8.83% $
= Discussion
== Conclusion
The experiment was successful in accomplishing its purpose. The hypothesis
proved to be reasonably close to a real value, only off by 53cm (an error of
8.83%). This demonstrates that conservation of energy is a reasonable way to
predict motion.
== Errors
There are many sources of error throughout this experiment that could have
resulted in an 8.83% error. One such source of error is the inaccuracy of tied
knots in retaining the length of the tubing. Since extra tubing had to be left
in order to allow knots to be tied, it is likely that these knots did not
perfectly retain the length between them. However, it is difficult to know
whether the knots increased or decreased the true length of elastic material,
so it is uncertain how measurements were affected.
Another source of error in this experiment is the failure to account for
external forces acting upon the system. Energy is only conserved within an
isolated system; however, in this experiment, there are forces originating
from outside the system. The most notable is air resistance, which would
decrease the velocity of Barbie as she fell. Therefore, it would result in a
decrease in measured values, which is what was observed in the experiment.
== Applications
Conservation of energy is a well-established law in physics. Therefore,
understanding how to apply it to solve real-world problems is a key skill and
essential in dealing with real-world systems. For example, hydropower plants
convert the gravitational potential energy of the falling water into
mechanical and then electrical energy using generators.
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/cancel-03.typ | typst | Other | // Cross
$a + cancel(b + c + d, cross: #true, stroke: #red) + e$
$ a + cancel(b + c + d, cross: #true) + e $
|
https://github.com/yongweiy/cv | https://raw.githubusercontent.com/yongweiy/cv/master/skills.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvSkill, hBar
#let metadata = toml("./metadata.toml")
#let cvSection = cvSection.with(metadata: metadata, highlighted: false)
#cvSection("Skills")
#cvSkill(
type: [Programming],
info: [OCaml #hBar() C / C++ #hBar() F\# #hBar() Scala #hBar() Haskell #hBar() Python #hBar() TypeScript],
)
#cvSkill(
type: [Formal Methods],
info: [Dafny #hBar() Z3 #hBar() Coq #hBar() Lean #hBar() LLVM]
)
|
|
https://github.com/ShapeLayer/ucpc-solutions__typst | https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/lib/utils/make-prob-overview.typ | typst | Other | #import "/lib/i18n.typ": en-us
#let make-prob-overview(
font-size: 1em,
i18n: en-us.make-prob-overview,
..items,
) = [
#align(center + horizon)[
#text(size: 1.5em)[
#table(
columns: 4,
inset: (x: .5em, y: .65em),
align: horizon,
stroke: (x: none),
row-gutter: (5.2pt, auto),
table.vline(x: 2, start: 0),
table.vline(x: 3, start: 0),
table.cell(colspan: 2)[#i18n.problem], i18n.difficulty, i18n.author,
..items
)
]
]
]
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-40.typ | typst | Other | // Error: 18-19 number must not be zero
#range(10, step: 0)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/env-setup/renderer.typ | typst | Apache License 2.0 | #import "/docs/cookery/book.typ": book-page
#show: book-page.with(title: "Environment Setup for Renderer Developers")
= Environment Setup for Renderer Developers
Sample page
|
https://github.com/MaxAtoms/T-705-ASDS | https://raw.githubusercontent.com/MaxAtoms/T-705-ASDS/main/content/probability.typ | typst | = Probability
#include "week1.typ"
#include "week2.typ"
// Lecture 3 can be found in the recordings
// No lecture in week 4
#include "week5.typ"
// No lecture in week 6
#include "week7.typ"
#include "week8.typ"
#include "week9.typ"
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/041%20-%20Kaldheim/010_The%20Saga%20of%20Lathril.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Saga of Lathril",
set_name: "Kaldheim",
story_date: datetime(day: 05, month: 02, year: 2021),
author: "<NAME>",
doc
)
Lathril stood at the mouth to the cave, her veins pulsing with the magic that had been bestowed upon her during her crucible. Flexing her fingers, she could feel how the transformation was taking hold, every muscle and every bone, every sinew in her body changing as she became more than a mere mortal. She was taking on the mantle of godhood.
The decision had been easy in some ways. Her people needed protection, support, a stronger connection to the divine. There had been a war not long before, and while they had won, it had been by small margins. Lathril never wanted to see her community lose so much again, so she found a way to protect her people. She had to. She had asked for a god to accept them, to keep them, and she made sacrifices to make it so.
She opened her eyes to take in the faces of the crowd that she knew would be waiting to lead her back to the village in celebration. Something was different. Something about what she could see. She'd known that she would change, that something about her would no longer be as it was. The stories were clear: to become a god you would lose a piece of yourself. She'd accepted that there was a price, but she hadn't known what it would be.
Instead of seeing the world as she had always seen it, her focus had narrowed. She could see the face of her daughter in the crowd, blurred from a distance, making her out because of the clothing that she wore. She could see the trees, but instead of individual leaves being distinguishable from one another, she saw a green blur, backlit by the golden sun. It was disorienting for the world to be so small, especially since she knew that it was so much bigger than what she was now seeing. Turning her head, she could get more faces, more bodies, more blur. The world had become so small.
But she was still a god.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
She awoke in the middle of the night to a nose in her face. Her first instinct was to grab for the sword at the side of her bed, but her way was blocked~by fur. She wasn't used to turning her head to look at things just yet, but once she did, she found herself face-to-face with a pair of turquoise eyes, set in the face of a beautiful copper wolf. In the dim candlelight, Lathril could see the tri-color fur that the copper wolves were so known for—a white overlayer of fur with an underlayer in silvers and golds and, of course, coppers. Its fur would gleam in the sun or moonlight like a beacon. The wolf settled down next to her, draped its paws over its face, and went to sleep.
Lathril watched as long as she could, but eventually she slept. After all, the wolf wasn't doing anything to her—she was strangely unafraid of the wolf mauling her in her sleep.
She hadn't known who would select her, only that when she asked in supplication that she might be accepted. There was only one divine being that sent wolf children to his chosen, and that was Sarulf. This must be a wolf of his. That was the best explanation she could come up with.
She slept.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
When she woke the next morning and got out of her shallow bed, the wolf arched her back into Lathril's left palm and paced around her as she walked out of her room into the solarium situated in the center of her home. She had made adjustments since the Ordeal, tactile signals on the wall for when she found herself unable to see in the dark, footpaths to keep her oriented if she couldn't find her way (without peripheral vision, and the loss of some distance, she was still adjusting to her new reality, even in her own home).
The wolf raised its head and gently nipped at her sleeve, tearing a little at the soft fabric of her blouse.
"Don't eat my clothes, wolf," she growled, but followed the direction the wolf was pulling her in. If nothing else, it would be an interesting thing to see where the wolf wanted her to go in her own home. But the wolf led her to the tall green door that led out into the village. It took Lathril a moment to adjust her perception to what was hanging on the gleaming door handle—a harness. Leather, smooth and polished, with burnished metal accents. The wolf slid it over its head, then presented the handle, movement indicating that she was wagging. It was most definitely a "she" from the energy.
The leather was smooth and supple, perfectly comfortable in her hand, like a sword grip that had been designed for its bearer. The wolf pawed at the door, not clawing, but politely indicating that they needed to leave. Lathril had been adventuring for so long that she had the presence of mind to grab her sword from beside the door and sheathe it into the scabbard at her hip. That was one of the skills she hadn't lost, at least. She didn't need her eyes for that. She kicked the door open gently with her green-booted foot and followed the wolf out into the sunlight.
When she stepped through the door, her eyes reacted instantly, pain flaring. She closed them and stood still, hoping that the light sensitivity would fade quickly. The harness in her left hand tugged forward, a pull that wasn't hard, but that told her to take a step, then another. Even with her eyes closed, she was following the wolf in the harness along the path. Interesting.
She'd heard that the wolves sometimes picked companions for themselves, often choosing to help those who could not see or hear, or whose minds had trapped their traumas like memories captured in amber by witches. But Lathril hadn't expected that she would gain a companion of her own. The harness took a sharp jerk to the left and she followed, the shift of her hips likely to be almost imperceptible, should anyone be watching. Decades of sword fighting had made her nimble on her feet, and this was just another form of that same nimbleness, it seemed.
Her eyes had finally adjusted, so she opened them. She found herself surprised. They were not where she thought they were. Instead of heading into the village, they were down a path headed into the forest. Moss-covered rocks lined the almost invisible path that they were following through green and yellow trees and low hedges that made the world a green blur.
Up ahead, there was a figure. Lathril couldn't make it out, it was too far, but she could tell that it was a lone figure standing still at some distance, and that they were headed straight for it.
As they approached, the colors of the figure's clothing became more identifiable. Deep blues and sable browns made up the other's clothing, and Lathril knew, without having to ask, who it was that the wolf had brought her to see.
"Lathril! You've been summoned. Well. You and your wolf have—when did this wolf arrive, by the way?" said Yadira, the leader of her elven clan. "Anyway, you've been summoned to deal with a problem. I've no idea what, but there's a door your wolf can find. Something about walking between worlds. She'll know where to take you. Just tell her to take you where you're most needed."
Lathril considered that. Where #emph[she ] was most needed. She'd known there would be expectations and needs for her to attend to. She hadn't expected to be doing it down most of her sight and with a wolf at her side, but her life had never been predictable.
"All right, wolf. You're going to need a name. Take me to where I'm most needed." The wolf stepped forward, pulling hard on the harness, and Lathril followed as an Omenpath opened ahead of them, and they stepped through without a pause or a question.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Walking through the Omenpath was like walking through a waterfall made of lightning. It was as all-consuming as a waterfall is—your whole body experiencing the sensation of walking through water—but it wasn't water. It was energy.
When Lathril came out the other side, her clothes were dry, her hair stood on end, and the wolf growled. After she registered the growl, however, there was a much more important sound to be heard.
A scream.
Lathril's right hand went to the sword at her hip, and she drew, the sword arcing over the wolf's head in an elegant sweep. The wolf didn't react until she was ready, then they charged ahead, running together through grasping branches and trees until they reached a clearing. A blur at the center of other blurs was fending something off. Several somethings, it turned out, as Lathril and the wolf came closer.
#figure(image("010_The Saga of Lathril/01.jpg", width: 100%), caption: [Lathril, Blade of the Elves | Art by: <NAME>], supplement: none, numbering: none)
She appeared to be a human girl, maybe 11 or 12 years old. Looking human and being human were two different things—who knew what dwelled in this unfamiliar realm? But it didn't really matter. Here was someone who needed her help. Lathril let go of the wolf's harness and moved into action.
"Get behind the wolf, child!" she shouted to the obviously terrified girl as she swept into action, sliding herself directly into the fray.
Swordplay while blind worked better when she could assess their blades, and so she moved quickly to evaluate the situation. Up close, the something's were definitely draugrs and their blades were deep blue and as sharp as anything she'd ever seen up close. But her skills were honed to the degree that few can master. With a clash of her sword on his, she joined him.
She could have fought with her eyes closed. The tension between blades was everything to her, the way in which his blade pressed on hers, the way she slid back into a new position and parried. A snarl at her right side warned her that someone was incoming, and she slid her dagger out of her second sheath with her left hand, embedding it into the unseen target while continuing to beat back her other opponent with her right.
When their swords next met, she slid down and exacted the kind of disarm that makes it difficult to pick up a sword again for months on end, and with a swift kick to the head, the other target was out for the count. When she turned around, breath heavy from the fight, the visual she located was one that made her heart ache.
Her wolf, sparkling in the moonlight of this new world, was curled around the young girl who was sobbing into her fur.
With a few quick steps, she made it to the wolf and the girl, then knelt.
"Can I help you?"
The girl took a deep heaving gasp to collect herself then carefully peered up from the wolf's shoulders. Her eyes were aqua with no pupil, trending toward white.
"They took my wooooolf!" the girl howled, grasping tighter to the new one which had now claimed her.
This child was not any random blind child lost in the woods by herself, and if Lathril knew anything about the world she belonged to, that wolf that they stole wasn't any normal wolf.
Sarulf had children. Wolf children. And they often protected gifted magicians. This child had skills, but they would have to be protected from a world that would harm her until she could come of age to own her own power. That's what the wolf was for. Whoever those men were, they had meant to do the girl harm.
"You'll stay with us until we can take you to safety," said Lathril, glancing at the wolf as she growled gently in the direction of the unconscious attacker. "Yes, wolf—I'll deal with that first."
She crunched the snow underfoot until she reached the two downed foes, rifling through their gear carefully for rope and other options, finally resorting to binding their hands and feet with belts and shoelaces. It wouldn't hold forever, but the stab wound and the concussion should hold them for a while.
When she turned around, the child had placed her hand on the strap that arched over the wolf's back, leaving the harness clear for Lathril to hold onto while they walked together.
It was an odd world they'd come to. Snow covered the ground in blue, white, and purple crystals, but whether they reflected the light from Starnheim, or if that was simply the color of the ground, was beyond Lathril's knowing. The trees were tall and thin, their arms like dancers, or fighters, depending on your interpretation. They reached and grabbed, tendrils trying to stop them from their egress across the forest floor. Lathril kept her ears alert for danger, but aside from the crunching of eight feet as her party moved forward, there was little to hear.
"What can you tell me about this place? And what's your name?" Lathril asked.
The girl sniffed.
"Lyana," she warbled, sniffing snot up her nose dramatically, "and my wolf is named Kit."
"You named your wolf after a kitten, didn't you?" Lathril drawled, trying not to laugh. Her daughter had once done the same thing.
The girl giggled.
Behind the giggle, there was a rustle, then a soft whine from the wolf.
"Hold," Lathril whispered, stopping and unsheathing her blade again. She turned her head in a full circle, her body slowly guiding her gaze as she surveyed the forest, trying to ascertain where the sound had come from. Nothing.
"Let's keep moving. Where are we taking you, Lyana?"
"To the village, where I live. It's through the trees. The wolf knows where to go. They all do."
If it hadn't been in such a pleasant and sweet voice, Lathril would have found the implication ominous. But she followed the wolf's steady pull through the woods, every once in a while hearing a rustle in the trees, indicating that they were likely being followed. Soon enough, they came to the edge of a village.
As they moved into the village, she was aware of a circle of wooden and stone cottages around a central fire, stretching farther out into what she assumed were more circles of structures. They strode toward the first person they saw at the fire.
"I believe I've found one of your children," Lathril said to the tall elder, busy tending the flames. The elder turned, startled by the sudden intrusion.
"Why, yes, you have," the woman said, gazing down at Lyana with mild disapproval in her voice. "Lyana, where is Kit?"
"We were out for a walk when we were set upon by draugrs and one of them snatched her and ran off with her toward the north." Observant child, Lathril noted.
"And what did you do?" the elder queried.
"I tried to fight them off, and then #emph[she ] came," Lyana said in that accusatory tone that conveyed affection, approval, and the slight bit of disgust in adults that all children had. "And she brought me back and now I'd like my wolf back."
"I can do that. I was brought here by mine," Lathril found herself saying, thinking on how fortunate it had been that she had appeared when she did. This was the quest she had been sent on.
"What's #emph[your ] wolf's name?" the girl asked, more accusation in her voice.
"She hasn't told it to me yet," Lathril replied, truthfully.
"She will."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
After making her way back through the forest, sans child, Lathril found herself at the edge of a clearing with her wolf, secreted between what were certainly haunted bushes. They had thin branches with white and gray bark, and their leaves were black and caught no color whatsoever, but up close, Lathril could see that they had white veins.
At the center of the clearing, there was a stake in the ground with a long black chain attached to it. At the end of that chain was a wolf, a small one. In the glowing moon and fire's flickering light, she was more gold than Lathril's.
Near the fire, a man tended a stab in his arm while another sipped at a drinking horn. It was not the same man who she had kicked in the head earlier, so she assumed he had been tucked away in the tent to the left of their hiding place. If she strained her ears, she could hear snoring.
Lathril settled herself on the cold ground, careful not to make a sound, and waited. She knew the men would have to sleep. And, eventually, they did. It took hours of watching, but the fire began to burn down, and the embers glowed next to their sleeping bodies. Without the harness in hand, Lathril slid forward. The wolf slunk forward, too, curling around the pup for protection as Lathril successfully worked the lock on the pup's chain. With a glance to her wolf, she began to slowly back away.
As they began their escape, a cough came from the tent. A wheeze, and a curse.
They all froze.
Lathril had to turn all the way around to find herself now watching the man she had kicked coming out of the tent, his hands rubbing at his head. She moved as quietly and swiftly as she could, trying to mind her corners, but she wasn't quite quick enough. A hand darted forward, catching her right elbow before she could draw her sword.
#emph[More of a brawl than a sword fight, then] , she thought. Her instincts took over. #emph[Knee to the gut, shoulder forward, then spring back. Close your eyes because they're not useful anymore, anyway. Feel for the air as he swings for your face, then grab, twist, drop.] The near silence with which the fight was conducted made it clear he had been startled. The final whump of the air going out of him, like a badly fluffed pillow, as he now laid in the snow was her cue. #emph[Eyes open and run.]
The run through the forest was the first time that she had allowed herself to move more quickly than the pace reserved for blind people. The trees felt like enemies, encroaching on her narrow field, and she became disoriented quickly. Where were the wolves? Where was the village? Where were the enemies that surely would be coming for her?
Lathril spun around, grasping at branches and glancing wildly from side to side, finally stopping in a dead panic. She did not know where she was or where she could go.
Until she realized she was exactly where she was meant to be.
Ahead of her, a giant wolf curled up in the middle of a glade, and the two wolves with whom she had escaped were bowing low to him. His eyes glowed with power.
#figure(image("010_The Saga of Lathril/02.jpg", width: 100%), caption: [Sarulf, Realm Eater | Art by: <NAME>], supplement: none, numbering: none)
Lathril knew when to recognize power. She dipped her chip to her chest and then bowed, hands far as they could get from her weapons.
#emph[You have rescued one of my children from those who would harm the pack. You have accepted the one that I sent you. Her name is Lukya.]
Lathril did not speak or make direct eye contact with the wolf ahead of her.
"I have, and I accept the gift that she has given me in her service," she said, as Lukya made her way back to stand at her left side.
#emph[As another gift to you, any of your kind may safely walk my lands and communicate with my beasts, regardless of whether they carry my blessing.]
Lathril nodded again.
"We will return Kit to her human."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Kit, the little wolf, ran full bore into her person. The little girl rolled and tumbled with her wolf in the center of the town. They acted like wolf pups, happy blurs melding in with the crowd that surrounded them.
The Omenpath was opening, and Lathril walked through it, with her new friend safely at her side.
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-30000.typ | typst | Apache License 2.0 | #let data = (
"0": ("<CJK Ideograph Extension G, First>", "Lo", 0),
"134a": ("<CJK Ideograph Extension G, Last>", "Lo", 0),
)
|
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/pages/notation.typ | typst | MIT License | #let notation(
twoside: false,
title: "符号表",
outlined: true,
width: 350pt,
columns: (60pt, 1fr),
row-gutter: 16pt,
..args,
body,
) = {
heading(
level: 1,
numbering: none,
outlined: outlined,
title
)
align(center, block(width: width,
align(start, grid(
columns: columns,
row-gutter: row-gutter,
..args,
// 解析 terms 内部结构以渲染到表格里
..body.children
.filter(it => it.func() == terms.item)
.map(it => (it.term, it.description))
.flatten()
))
))
// 手动分页
if (twoside) {
pagebreak() + " "
}
} |
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/rounding/round-minimum/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#metro-setup(round-mode: "places")
#num(0.0055)
#num(0.0045)
#metro-setup(round-minimum: 0.01)
#num(0.0055)
#num(0.0045)
|
https://github.com/cs-24-sw-3-01/typst-documents | https://raw.githubusercontent.com/cs-24-sw-3-01/typst-documents/main/report/sources/LindaInterview.typ | typst | #import "../custom.typ": *
== Interview with Linda <InterviewLinda>
00:00:04,960 --> 00:00:10,099
Mads: Men når I opretter teams I dag og skal tilføje medarbejdere, jeg kan ikke huske, hvad det er en søgefunktion.
00:00:10,160 --> 00:00:13,120
Altså hvor I bare søger efter medarbejderen, og så kan slå dem ind.
00:00:13,120 --> 00:00:14,340
Og det samme med teams.
00:00:14,715 --> 00:00:19,135
Kan du søge I den der liste med dem, når du skal vælge det?
00:00:32,600 --> 00:00:33,980
Linda: I kan da lige se med.
00:00:39,480 --> 00:00:46,675
Nu har jeg egentlig bare lige klikket ind for at sige, at jeg gerne vil oprette et nyt userbaseret team.
00:00:48,015 --> 00:00:52,094
Så går jeg herind og siger, at jeg vil gerne have hvor den henne.
00:00:52,094 --> 00:00:54,415
Ja, nu er det så ikke særlig. Jeg gør det ikke.
00:00:54,415 --> 00:00:55,795
Det er ret tit det her.
00:01:06,460 --> 00:01:08,720
Mads: Okay, men den team der for eksempel.
00:01:09,500 --> 00:01:13,420
Så er det din egen teams, du er en del af de øverst. Ja. Så kan du scrolle.
00:01:13,420 --> 00:01:19,575
Linda: Så kan jeg scrolle ned, så har jeg faktisk et overblik over alle de teams, der er oprettet I KMD herinde.
00:01:20,595 --> 00:01:24,855
Mads: Tror du, det ville være mere lækkert, hvis den drop down der, at man kunne søge i den også?
00:01:30,140 --> 00:01:32,720
Linda: Ja. Du tænker på, at der skulle være en type head.
00:01:33,580 --> 00:01:36,080
Mads: Ja, som deroppe I felter, man bare kunne søge.
00:01:36,140 --> 00:01:38,060
Det kunne vi selvfølgelig tilføje, hvis det var.
00:01:38,060 --> 00:01:41,344
Men ellers er det jo fint nok, når ens teams bare ligger øverst.
00:01:41,564 --> 00:01:46,204
Zafir: Er det så alle teams, der er, eller alle de teams, du er en del af?
00:01:46,204 --> 00:01:50,145
Linda: Nej, det er alle teams, der er oprettet I det produkt her.
00:01:50,604 --> 00:01:54,944
Og så vil jeg kunne gå ind og se for eksempel den her.
00:01:55,040 --> 00:01:58,240
Ville jeg kunne gå ind og se deres kalender her.
00:01:58,240 --> 00:02:00,340
Og der kan I se, der bruger de det I hvert fald.
00:02:02,320 --> 00:02:09,525
Der er der registreringer, og det her er fravær, der egentlig blevet registreret I den manuelt.
00:02:09,985 --> 00:02:12,405
Og det kan jeg se ved, at det er et skraberet felt.
00:02:13,105 --> 00:02:14,785
Mads: Nå, nå det er der simpelthen forskel på.
00:02:14,785 --> 00:02:18,465
Linda: Ja, det er det. Hvis det var noget, der var kommet over fra, du prøver at se her, det her det
00:02:18,465 --> 00:02:19,925
er en hellig dag, ikke?
00:02:20,280 --> 00:02:23,099
Mads: Nå, det kommer det over fra SAP af eller hvad?
00:02:23,159 --> 00:02:32,280
Linda: Nej, det kommer egentlig fra en kalenderfunktion, som den gamle udvikler har sat herind.
00:02:32,280 --> 00:02:35,265
Som så viser, at det her er de hellige dage, de bliver sat ind.
00:02:35,745 --> 00:02:43,125
Og hvis man havde haft en funktion fra SAP, så havde den været fuld grøn.
00:02:43,665 --> 00:02:44,385
Mads: Nå, på den måde.
00:02:44,385 --> 00:02:47,444
Linda: Og skulle komme ind fra SAP af dengang vi integration ikke.
00:02:49,870 --> 00:02:53,630
Mads: Man kan faktisk se forskel på, var det her importeret for SAP eller lavet manuelt?
00:02:53,630 --> 00:02:55,810
Linda: Ja, eller noget jeg manuelt har selv det.
00:02:56,910 --> 00:03:06,475
Mads: Okay, men fungerer det fint nok med at det er skraberet af så du ikke kan vælge et par helligdage og sådan noget? Ja. I arbejder aldrig i helligdage.
00:03:06,694 --> 00:03:08,775
Linda: Det gør vi helst ikke der.
00:03:08,775 --> 00:03:11,115
Mads: Helst ikke? Nej især, det er selvfølgelig også fair nok.
00:03:11,895 --> 00:03:18,400
Linda: Men det kan man selvfølgelig blive nødt til, hvis vi har et eller andet, der crasher, så kan
00:03:18,400 --> 00:03:19,600
man godt blive nødt til det.
00:03:19,600 --> 00:03:22,500
Men det er jo ikke noget, man planlægger efter.
00:03:22,560 --> 00:03:23,220
Mads: Når nej, det er selvfølgelig rigtig.
00:03:23,840 --> 00:03:25,700
Linda: er altid et eller andet, der opstår akut.
00:03:25,840 --> 00:03:29,620
Og så kan man komme ind og arbejde hellig dage eller weekender.
00:03:30,480 --> 00:03:31,780
Mads: Det kan selvfølgelig god mening ja.
00:03:32,405 --> 00:03:38,965
Linda: Men det er en rigtig fin feature, at man kan se, hvornår der er hellig dage.
00:03:38,965 --> 00:03:44,025
Og som det kan I selvfølgelig ikke se, men den her ellvte.
00:03:44,165 --> 00:03:48,030
November, det er jo ikke en hellig dag I Danmark Eller en fridag.
00:03:48,030 --> 00:03:53,150
Så det er højst sandsynligt polak, som har en hellig dag.
00:03:53,150 --> 00:03:57,810
Der står også der, at det er deres Independence Day I Polen, når den hopper henover.
00:03:58,270 --> 00:03:59,250
Mads: Okay, ja.
00:03:59,925 --> 00:04:06,265
Linda: Så hvis man kan se de helligdage, der er til det pågældende land, man samarbejder med.
00:04:06,325 --> 00:04:11,685
Zafir: Er det noget, I godt kan lide, at man kan se, hvornår de for eksempel har helligdage?
00:04:11,685 --> 00:04:14,265
Linda: Ja, for så ved vi, at vi ikke kan få fat I dem.
00:04:14,920 --> 00:04:15,980
Mads: Det kan selvfølgelig godt være.
00:04:17,720 --> 00:04:24,300
Linda: De fleste af os har faktisk også alle slået til i vores kalender, at man kan se de polske helligdage også.
00:04:25,080 --> 00:04:30,175
Så når man arbejder tæt sammen med nogen fra et andet land, som har en helt anden sæt helligdage
00:04:30,175 --> 00:04:33,715
end vi har I Danmark, så giver det rigtig god mening, at man kan se dem.
00:04:33,855 --> 00:04:42,000
Mads: Okay. Lad os sige, at du vil registrere fravær på den dag med den polske helligdage, kunne du så gøre det?
00:04:42,160 --> 00:04:44,740
Ja, det er per person I rækkerne.
00:04:46,240 --> 00:04:46,400
Zafir: Når
00:04:46,400 --> 00:04:48,660
Linda: jeg hopper hen over, så kan jeg se, at det
00:04:53,120 --> 00:04:55,220
der. Men den der grønne,
00:04:55,440 --> 00:04:55,600
Mads: som
00:04:55,600 --> 00:05:00,115
Linda: kan I se, det er GPI, Og det er så også GPI, der har den der.
00:05:00,335 --> 00:05:05,635
Fordi de har sådan nogenlunde samme placering på kalenderen.
00:05:07,615 --> 00:05:08,835
Zafir: Så det er for hvert.
00:05:09,855 --> 00:05:11,660
Så det er en liste over team members.
00:05:12,040 --> 00:05:13,880
Linda: Ja. Jo, nu kan jeg ikke hjælpe ud af det.
00:05:13,880 --> 00:05:14,620
Zafir: Det var faktisk
00:05:16,040 --> 00:05:20,140
Mads: meget sat op ja. Så det er hver team member har sin egen række der. Ja.
00:05:20,920 --> 00:05:21,420
Linda: Præcis.
00:05:29,695 --> 00:05:33,935
Ja, det er sådan, at man ligesom kan dele det op.
00:05:33,935 --> 00:05:36,255
Det bliver lidt uoverskueligt, hvis der er rigtig mange.
00:05:37,055 --> 00:05:38,915
Linda:Så kan vi prøve at tage mit eget team her.
00:05:42,490 --> 00:05:48,490
Men det er jo ikke sådan, at det er en et til et vi skal have, sådan skal I endelig ikke forstå det.
00:05:48,490 --> 00:05:50,330
Zafir: Nej, vi prøver bare at forstå det.
00:05:50,330 --> 00:05:52,170
Linda: Ja ja og forstå, hvordan
00:05:52,170 --> 00:05:52,910
Zafir: det fungerer.
00:06:09,349 --> 00:06:13,530
føler du at svært at finde de teams, du er en del af.
00:06:15,190 --> 00:06:16,889
Linda: Ja, det er ikke ret nemt faktisk.
00:06:20,389 --> 00:06:22,069
Mads: Men de lå jo I toppen eller hvad?
00:06:22,069 --> 00:06:23,925
Linda: Jo, det er dem jeg selv har lavet.
00:06:24,485 --> 00:06:26,905
Det er dem jeg selv har kravet.
00:06:27,284 --> 00:06:31,865
Dem jeg så er med I, de ligger lidt i en spredt fægtning.
00:06:37,870 --> 00:06:40,350
Mads: Kunne det måske være fedt, hvis du havde to kategorier oppe I toppen?
00:06:40,350 --> 00:06:43,169
Både med dem du er en del af, og dem du selv har lavet?
00:06:44,110 --> 00:06:49,870
Linda: Ja, det kunne da helt klart give et rigtig godt overblik. Ja.
00:06:49,870 --> 00:06:53,615
Nu siger jeg her, der er jeg med. Nu klikker jeg igen.
00:06:59,035 --> 00:07:05,375
Jeg skal gå ind og sætte noget absence ind her, så klikker jeg på man maintenance.
00:07:05,629 --> 00:07:07,069
Så går jeg over til oktober.
00:07:07,069 --> 00:07:09,169
Så siger jeg: Jeg skal være væk her.
00:07:20,485 --> 00:07:23,544
Sådan, så har jeg lige sat min efterårs ferie ind der.
00:07:29,525 --> 00:07:32,985
Så er den skraberet på min placering her.
00:07:33,285 --> 00:07:37,680
Mads: Noget Vi har også snakket om, at man kunne sætte ind for for eksempel tidspunkter.
00:07:37,900 --> 00:07:41,040
Men kører I det bare som hele dage, når det er absence?
00:07:41,180 --> 00:07:43,980
Der er ikke noget med, at jeg kommer ikke halvdelen af dagen?
00:07:43,980 --> 00:07:49,085
Linda: Nej, det fortæller man sådan fra tid til anden.
00:07:49,956 --> 00:07:53,885
Linda: At man ikke er tilgængelig om eftermiddagen.
00:07:56,825 --> 00:08:01,965
Jeg har I hvert fald ikke det store behov for at kunne se halve dage på nogen.
00:08:02,620 --> 00:08:05,760
Og der har vi jo vores rigtige kalender.
00:08:06,060 --> 00:08:12,480
Så hvis man har en privat aftale, sætter man det ind I den rigtige kalender, og så kan man kigge derinde.
00:08:13,260 --> 00:08:14,700
Mads: Er der Outlook kalenderen I køre?
00:08:14,700 --> 00:08:17,015
Linda: Nej, det er I
00:08:18,995 --> 00:08:23,955
Zafir: kalenderen. Vi skal lige vide hvilken en i foretrækker at bruge for eksempel.
00:08:23,955 --> 00:08:32,620
Linda: Den her Outlook kalender, den skal altid være opdateret. <NAME>
00:08:35,640 --> 00:08:40,060
der skal man have sat tingene ind.
00:08:40,200 --> 00:08:46,595
Og der har vi en smart feature fra vores Succes Factor, når vi booker ferie.
00:08:47,055 --> 00:08:49,875
Vi prøver at gå hen på næste uge, hvor jeg er væk.
00:08:51,215 --> 00:08:56,495
Der har vi en smart feature, der gør, at når vi har booket det ind I Succes Factor så sender
00:08:56,495 --> 00:09:02,230
den en mail med en kalender invite Og så klikker vi den ind og gemmer I vores kalender.
00:09:02,230 --> 00:09:03,930
Så har vi vores ferie herinde.
00:09:06,550 --> 00:09:08,330
Det kan hurtigt blive mange steder,
00:09:10,950 --> 00:09:13,130
Linda: hvis man skal ind og justere rundt på det.
00:09:14,195 --> 00:09:16,455
Mads: Det er jo tre systemer allerede der. Ja,
00:09:18,035 --> 00:09:22,055
Linda: vi har Succes Factor, Outlook kalenderen, og så har vi ferieplanen.
00:09:23,475 --> 00:09:27,095
Zafir: Hvilken en vil du sige, du bruger mest eller foretrækker?
00:09:28,310 --> 00:09:29,190
Linda: Jeg bruger den her, for det
00:09:29,510 --> 00:09:30,550
er den jeg skal bruge.
00:09:30,550 --> 00:09:36,570
Det er den, alle mine kollegaer kan slå op I og se, hvornår er jeg væk og hvornår er jeg.
00:09:37,270 --> 00:09:40,170
Mads: det er da også sådan, at når du får mails, mødeindkaldelse.
00:09:41,430 --> 00:09:42,765
Linda: Så det er den her.
00:09:43,725 --> 00:09:52,225
Men bare for at gøre forvirringen total, så når vi går over I Teams, så har vi selvfølgelig også kalenderen herovre.
00:09:53,405 --> 00:09:55,665
Linda: Men den er så heldigvis integreret med Outlook-kalenderen.
00:09:55,965 --> 00:09:57,105
Mads: Ja, det vel den samme?
00:09:58,120 --> 00:10:00,139
Linda: Ja, det er ikke den samme, men den viser det samme.
00:10:00,360 --> 00:10:07,019
Det er en et-til-en, fordi den har en snabel nede I Outlook I 365. Okay.
00:10:08,759 --> 00:10:11,565
Zafir: Så I har fire cirkus?
00:10:12,345 --> 00:10:13,885
Linda: Ja, det er der faktisk.
00:10:16,745 --> 00:10:24,880
For at det ikke skal være løgn, så kan de Hvis vi tager Succes Factor
00:10:33,660 --> 00:10:37,040
Så er der faktisk også, så skal vi lige se, hvad jeg lander på her.
00:10:56,449 --> 00:11:03,990
Så er der faktisk også en Teams absence inden I Succes Factor.
00:11:05,970 --> 00:11:09,675
Men den kan man ikke
00:11:12,695 --> 00:11:16,455
gå ind og bygge et projekteam op.
00:11:16,455 --> 00:11:20,395
Det her er den afdeling, vi er med I, som bliver vist her inde.
00:11:21,260 --> 00:11:26,960
Så alle mine kollegaer, der har sat noget fravær op, det kommer til at stå herinde.
00:11:28,460 --> 00:11:32,860
Og det er heller ikke noget, som andre kan gå ind og se.
00:11:32,860 --> 00:11:37,795
For eksempel hvis jeg har en kollega helt uden for min afdeling, han ville ikke kunne gå ind
00:11:37,795 --> 00:11:41,255
og se min afdelings fravær.
00:11:41,475 --> 00:11:43,495
Så det er helt internt I afdelingen.
00:11:44,115 --> 00:11:48,355
Mads: Ja, okay. Så I realiteten for at koge det helt ned, så er det primært problem, I bruger KMD
00:11:48,355 --> 00:11:51,350
ferieplan til, det er bare for at I kan se på tværs af teams.
00:11:51,810 --> 00:11:55,829
Og alt andet, det komplicerede, det kører I ovre I Outlook I stedet for.
00:11:57,250 --> 00:11:58,470
Linda: Outlook og Succes Factor.
00:11:58,769 --> 00:12:06,045
Mads: Ja selvfølgelig. Så er det jo ikke, fordi vi skal til at lave alt muligt fancy, fordi det det er jo ikke brugt.
00:12:06,585 --> 00:12:08,025
Det er bedre at lægge det over Outlook.
00:12:08,025 --> 00:12:14,345
Linda: Nej lige præcis. Der hvor man kan sige, at I kunne lave noget fancy, som kunne give værdi, det
00:12:14,345 --> 00:12:18,685
var hvis man kunne få det her ekstrakt fra Succes Factor.
00:12:20,200 --> 00:12:22,140
Og så imbed det I koden.
00:12:22,920 --> 00:12:26,460
Lidt ligesom der er gjort med den gamle løsning her.
00:12:26,840 --> 00:12:35,495
Det her, der ligger herinde, det var egentlig baseret på et ekstrakt fra SAP Succes Factor,
00:12:36,595 --> 00:12:42,855
som så blev integreret I den her og gjort tilgængelig for alle på tværs.
00:12:43,315 --> 00:12:48,355
Mads: Okay, det var faktisk det, der kunne give allermest, hvis I ikke skulle ind og registrere, hvad der er?
00:12:48,355 --> 00:12:56,180
Linda: Ja, præcis. Hvis man kunne sige, at vi koncentrerer os om Succes Factor, og så bliver vores ferie
00:12:56,240 --> 00:13:00,260
populært herud til, så alle vil kunne se det på tværs.
00:13:01,120 --> 00:13:08,455
Og man kunne bygge tværgående projektteams
00:13:08,455 --> 00:13:10,715
Mads: Okay. Men lad os sige, at der var en integration til Succes Factors.
00:13:11,175 --> 00:13:14,935
Ville det så give bedre mening, at du slet ikke kunne gå ind manuelt og lægge noget ind, men
00:13:14,935 --> 00:13:19,575
at bare når du lagde det ind I Succes Factors, som du skulle uanset hvad, så blev det bare vist,
00:13:19,575 --> 00:13:21,035
og så kunne du oprette Teams?
00:13:23,550 --> 00:13:30,910
Linda: Ja, både og. Verden er jo bare ikke kun sort og hvid.
00:13:30,910 --> 00:13:37,090
Jeg kan jo godt blive udsat for, at jeg skal til en begravelse. Der havde jeg fri.
00:13:37,535 --> 00:13:41,635
Men det er ikke noget, jeg kan booke eller skrive ind I Succes Factor.
00:13:42,575 --> 00:13:46,255
Så går jeg til min chef og siger: Ved du hvad chef?
00:13:48,335 --> 00:13:49,955
Jeg skal lige til hendes begravelse.
00:13:50,015 --> 00:13:54,440
Og så går jeg herind for at vise til team, at jeg er væk hele dagen.
00:13:55,060 --> 00:13:57,459
Mads: Okay, altså der kan være nogle problemer med det?
00:13:57,459 --> 00:14:02,839
Linda: I dagligdagen vil jeg naturligvis også skrive det I min Outlook kalender. At det er væk.
00:14:06,185 --> 00:14:11,245
Mads: Dejligt at have den her fallback til hvis du ikke kan registrere det I Succes Factor. Okay.
00:14:12,905 --> 00:14:14,685
Det giver god mening.
00:14:17,385 --> 00:14:28,630
Linda: Enten tænker jeg, at skulle man skulle man bruge Outlook som et glas flade, der bliver populært ud til den tværgående.
00:14:29,490 --> 00:14:31,270
Sådan at den tager det derfra.
00:14:31,490 --> 00:14:35,894
Og så vil jeg lige glade med, at folk har registreret det i SAP.
00:14:35,894 --> 00:14:42,394
Man kan jo godt registrere det i SAP og undgå at få det I sin Outlook kalender.
00:14:43,175 --> 00:14:45,175
Det skal man jo gøre et aktivt valg på.
00:14:45,175 --> 00:14:46,394
Mads: Ja, det er det selvfølgelig rigtigt.
00:14:48,879 --> 00:14:54,100
Linda: Så hvis ens fraværskalender er opdateret, så kunne man jo trække det ind.
00:14:54,160 --> 00:14:57,279
Mads: Ja, for Outlook af I stedet for SAP. Eller hvad?
00:14:57,279 --> 00:15:00,339
Nej, begge dele. Eller hvad?
00:15:01,279 --> 00:15:03,300
Linda: Altså, Outlook er altid vores nej.
00:15:03,839 --> 00:15:09,055
Undskyld, SAP er altid vores base for fravær. Okay. Altid.
00:15:10,555 --> 00:15:16,095
Og så kan man vælge, om man vil putte det I sin kalender I Outlook eller ej.
00:15:16,870 --> 00:15:22,649
Linda: Så der er nogen, der ligesom mig, jeg har altså fået det ind I min Outlook kalender, det er der nogen, der glemmer at gøre.
00:15:22,709 --> 00:15:25,850
Selvom systemet sender en mail om det.
00:15:26,470 --> 00:15:29,209
Mads: Okay, her er det, fordi du skal ind og acceptere mig I gang.
00:15:29,454 --> 00:15:35,535
Linda: Ulempen ved at man brugte Outlook som glasplade, det er, at du får alle møderne med.
00:15:36,334 --> 00:15:40,274
Linda: og det er I princippet fuldstændig irrelevant, for dem har du et andet sted.
00:15:41,610 --> 00:15:43,709
Så det var faktisk en dårlig ide.
00:15:47,050 --> 00:15:49,550
Mads: kan da helt klart være relevant med noget SAP I hvert fald.
00:15:50,010 --> 00:15:54,350
Hvis I går ud fra, at I allerede har en måde at integrere med det nu, fordi I bruger store SAP.
00:15:56,755 --> 00:15:59,175
Jeg tror, at Dion og Mats snakkede om det.
00:15:59,555 --> 00:16:04,454
At de havde en eller anden dygtige SAP, vi kunne få lov at snakke med muligvis.
00:16:04,755 --> 00:16:07,415
Selvfølgelig hvis vi kom langt nok I projektet.
00:16:11,010 --> 00:16:18,450
Linda: Det, man næsten altid kan fra et vilkårligt system, det er jo at lave et ekstra abstrakt, hvor du
00:16:18,450 --> 00:16:27,855
siger: Jamen, så tager vi en fil ud med alle data på, med alle brugerne, med alt deres fravær og så videre.
00:16:27,855 --> 00:16:31,695
Og så kan man som koder stikke snabel ned I det og så plukke det ind.
00:16:31,695 --> 00:16:32,975
Det var det, vi gav tidligere.
00:16:32,975 --> 00:16:38,975
Mads: Jeg kan godt se, at I har nærmest bare taget en snapshot af den del af databasen med alt det, og så brugte råt-kurve. Ja, og
00:16:38,975 --> 00:16:40,880
Linda: så har vi trukket det ind. Ind.
00:16:40,880 --> 00:16:50,580
Så der har vi været vandt til at køre koden ned på den fil og så trække det ind I det her application.
00:16:50,880 --> 00:16:53,620
Mads: Så I simpelthen uploader det manuelt? Eller hvad?
00:16:53,920 --> 00:16:56,420
Linda: Altså, vi får SAP. Ja. De
00:16:59,014 --> 00:16:59,735
Mads: Nej, på den måde?
00:16:59,735 --> 00:17:05,995
Linda: En CSV-fil. Og så trækker vi data derfra og publicerer ind I KMD.
00:17:09,575 --> 00:17:11,914
Eller det var sådan, det blev bare gjort tidligere.
00:17:16,240 --> 00:17:19,300
Mads: Okay, det skal vi lige have kigget på, hvordan man kan gøre det så.
00:17:29,505 --> 00:17:32,544
Vi har også noget om medarbejdere laver fejl, når de ansætter ferie?
00:17:32,544 --> 00:17:33,585
Det gør de vel ikke.
00:17:33,585 --> 00:17:36,325
Det er så simpelt, at man kan bare klikke det fra igen.
00:17:36,865 --> 00:17:46,140
Linda: Ja, det kan du. Der hvor udfordringen er, I den sammenhæng, det er jo nu har jeg jo registreret mine juleferie.
00:17:47,480 --> 00:17:50,380
Linda: det har jeg jo gjort allerede nu, fordi jeg vil så gerne holde ferie.
00:17:50,680 --> 00:17:59,795
Så kommer jeg hen til jul, og så får jeg besked på fra min chef: Du kan ikke holde de der fridage til jul! Nå, okay, siger jeg. Det er så fint.
00:17:59,855 --> 00:18:03,235
Og så glemmer jeg alt om, at jeg manuelt har sat dem ind I ferieplanen.
00:18:04,095 --> 00:18:08,559
Så er de der stadigvæk, til trods for, at jeg ikke har holdt den frihed.
00:18:08,860 --> 00:18:11,600
Så det er jo en risiko ved at gøre tingene manuelt.
00:18:12,299 --> 00:18:14,640
At man skal huske at slette det igen.
00:18:14,860 --> 00:18:16,220
Mads: Ja, det er selvfølgelig rigtigt.
00:18:16,540 --> 00:18:19,740
Der kan man sige, at hvis det var synkroniseret med Succes Factors der.
00:18:19,740 --> 00:18:22,475
Var det derinde, du havde ønsket ferie?
00:18:22,934 --> 00:18:24,095
Linda: Nej, det var egentlig bare derinde.
00:18:29,095 --> 00:18:30,155
Linda: Og så hænger det jo ikke sammen.
00:18:30,455 --> 00:18:33,115
Så det er en ulempe ved at gøre tingene manuelt.
00:18:33,735 --> 00:18:35,995
Mads: Okay ja. Er det der, det kan gå galt
00:18:36,799 --> 00:18:38,720
Okay, det giver selvfølgelig god mening.
00:18:38,720 --> 00:18:41,679
Men hvad med egentlig Succes Factors? Hvordan fungerer det?
00:18:41,679 --> 00:18:44,240
Ansøger I om ferie der? Eller hvordan?
00:18:44,240 --> 00:18:45,860
Linda: Ja, det gør vi I princippet.
00:18:46,080 --> 00:18:55,135
Når vi har besluttet, at vi vil holde sommerferie, Så går vi ind I Succes Factor, og booker al
00:18:55,135 --> 00:18:56,915
den ferie, som vi har optjent.
00:18:57,375 --> 00:19:04,035
Der kan godt være en difference på et par dage, fordi den siger bagudrettet, at man får de her ferier.
00:19:05,054 --> 00:19:06,835
Så booker man sin ferie ind.
00:19:07,630 --> 00:19:15,970
Og når man kommer tilbage igen, så booker man lige de sidste to dage, og så er man klar.
00:19:16,350 --> 00:19:19,365
Mads: Okay, på den måde. Men bliver det godkendelse eller hvad?
00:19:19,605 --> 00:19:21,465
Linda: Ja, det tror jeg faktisk, det vil gøre nu.
00:19:21,925 --> 00:19:23,225
Det har det ikke gjort tidligere.
00:19:23,525 --> 00:19:31,304
Der har man egentlig bare aftalt en miss chef, og så har man tastet det ind, men nu er der faktisk et approval forløb på.
00:19:36,360 --> 00:19:43,975
Men umiddelbart som jeg tror, så tror jeg faktisk, den bliver godkendt som standard, og
00:19:43,975 --> 00:19:46,455
så kan chefen gå ind og decline dem, hvis der er.
00:19:46,455 --> 00:19:50,054
Mads: Okay, de skal ind og godkende det er mere, hvis der er noget, der er helt I.
00:19:50,054 --> 00:19:57,274
Linda: Ja, hvis det er et eller andet helt skævt, man kan se, at lige nu har taget I fem uger, det vil jeg ikke have.
00:19:58,054 --> 00:20:00,220
Kan man reagere på det.
00:20:02,920 --> 00:20:08,200
Mads: Okay. Så det I generelt kan lide ved kun det I ferie-planlæggeren er det der med, at den er
00:20:08,200 --> 00:20:10,220
simpel, og der er manuel kontrol.
00:20:10,680 --> 00:20:11,760
Der er ikke alt det der andet.
00:20:11,760 --> 00:20:15,555
Alle mulige knapper man skal igennem. Okay,
00:20:16,175 --> 00:20:18,915
Linda: fedt. Og man kan gøre det på tværs af teams.
00:20:19,135 --> 00:20:21,475
Mads: Ja, det er helt klart de stærke.
00:20:32,700 --> 00:20:34,240
Hvordan fungerer den på mobilen?
00:20:36,380 --> 00:20:38,060
Linda: Fungerer den overhovedet på mobilen?
00:20:38,060 --> 00:20:39,440
Mads: Det er jo lidt det om den gør.
00:20:40,460 --> 00:20:42,060
Jeg skulle godt forestille mig den ikke gjorde.
00:20:42,060 --> 00:20:43,215
Linda: Det tror jeg ikke den gør.
00:20:43,455 --> 00:20:49,235
Fordi det er jo et rent internt system, som ligger på en on premes server.
00:20:50,095 --> 00:20:53,875
Som vi ikke kan prøve, men som vi ikke kan få fat I udefra.
00:20:54,015 --> 00:20:56,434
Mads: Okay, vi skal simpelthen være her for at kunne gøre det?
00:20:56,640 --> 00:21:01,940
Linda: Nå okay. Og når vi er remote, så skal vi være på en VPN forbindelse for at kunne fange den.
00:21:03,200 --> 00:21:04,740
Mads: Nå, på den måde. Okay.
00:21:06,320 --> 00:21:07,280
Det giver selvfølgelig god mening.
00:21:07,280 --> 00:21:12,180
Linda: Det kunne være guld, hvis det var en, der kunne gå på mobilen.
00:21:12,634 --> 00:21:17,695
Og som kunne være et online set-up, som vi kender det på rigtig mange af vores applikationer.
00:21:18,634 --> 00:21:20,315
Mads: Det var det, vi snakkede om I hvert fald.
00:21:20,315 --> 00:21:24,575
Og udvikle som en webapplikation og sørge for, at den både kører på mobil og laptop.
00:21:25,355 --> 00:21:26,495
Det kunne være ret fint.
00:21:29,060 --> 00:21:30,680
Hvor højt vil de vægte det?
00:21:31,220 --> 00:21:36,840
Vil det være virkelig fedt at have, eller vil det bare være en mere nice to have?
00:21:38,980 --> 00:21:44,895
Linda: Jeg tror, at hvis man spørger rigtig mange, så ville det være nice to have at have på mobilen.
00:21:46,235 --> 00:21:47,915
Fordi det er du vandt til I dag.
00:21:47,915 --> 00:21:54,175
Du kan tilgå dit teams, du kan tilgå dit intranet og alle andre applikationer.
00:21:57,179 --> 00:21:58,460
Mads: Det giver selvfølgelig god mening.
00:21:58,460 --> 00:21:59,740
Det laver vi så I hvert fald.
00:21:59,740 --> 00:22:01,039
Den ligger lidt på kravspecifikation.
00:22:04,379 --> 00:22:07,519
Jeg tror faktisk ikke, at vi har mere.
00:22:09,580 --> 00:22:11,759
Jeg har fået en masse gode ting ud af det I hvert fald.
00:22:13,635 --> 00:22:21,235
Zafir: Jeg tænkte på I forhold til ferie planlæggeren, at der er forskel på farverne, når det er SAP, og
00:22:21,235 --> 00:22:23,175
når det bare er skrevet ind. Ja.
00:22:23,395 --> 00:22:25,235
Gør det noget, eller er det bare sådan?
00:22:25,235 --> 00:22:28,940
Linda: Nej, det kommer jo lidt an på, hvor I lander.
00:22:32,120 --> 00:22:40,440
Hvis I får en integration til SAP, så vil det give mening, at man kan se forskel på, om
00:22:40,440 --> 00:22:48,615
den kommer, om den er født automatisk fra Succes Factor eller om den er tastet ind af Linda selv.
00:22:48,615 --> 00:22:49,554
Zafir: Okay. Hvorfor
00:22:53,934 --> 00:22:57,554
føler du, at det er vigtigt, at man kan se den der forskel?
00:23:00,360 --> 00:23:05,580
Linda: Fordi så ved jeg, hvor jeg skal lede hvis jeg skal ændre det.
00:23:06,279 --> 00:23:14,794
For hvis jeg kan se, at der er en af de team medarbejdere, der har en skraberet felt så skal jeg
00:23:14,794 --> 00:23:18,635
have fat I Dorte for at sige til hende, at du skal lige gå ind og ændre den der, fordi du kan
00:23:18,635 --> 00:23:19,855
ikke holde fri den dag.
00:23:20,475 --> 00:23:26,460
Hvis den er fast, så ved jeg, at det er noget ferie, hun har planlagt I aftalen med sin chef
00:23:26,779 --> 00:23:29,600
Så kan jeg som projektleder ikke gå ind og overrule det.
00:23:33,740 --> 00:23:39,360
Det var et dårligt valg, jeg lige tog et bolche i munden, når vi skulle snakke videre.
00:23:50,865 --> 00:23:52,005
Mads: Hvad har du mere?
00:23:53,425 --> 00:23:57,940
Zafir: spørger du mig. Nej, jeg har ikke mere. Ikke sådan rigtigt.
00:23:58,320 --> 00:23:59,380
Linda: Nej, men da
00:24:02,160 --> 00:24:04,340
Hvordan har I tænkt jer at gribe den an, sådan?
00:24:05,040 --> 00:24:08,260
Zafir: Vi er ikke rigtig hundred procent sikre endnu.
00:24:08,895 --> 00:24:16,915
Nej, for vi vil gerne have det her interview med jer først så vi forstår, hvordan vi nu skal gøre.
00:24:17,455 --> 00:24:19,155
Og så kigger vi på det bagefter.
00:24:21,295 --> 00:24:27,120
Fordi vi vidste ikke jeg havde ikke forståelse af, at I brugte så mange forskellige kalendere. Nej,
00:24:27,340 --> 00:24:28,400
Linda: det gør man nu.
00:24:29,100 --> 00:24:31,520
Zafir: Og så også hundred procent, hvordan det virkede.
00:24:32,860 --> 00:24:35,200
Det er godt og se live. Ja.
00:24:35,980 --> 00:24:38,000
Zafir: Så det er egentlig bare det, vi gør I starten.
00:24:40,754 --> 00:24:49,654
Så skal vi sikkert have noget igen på et tidspunkt, hvor vi har lavet noget og forklare, hvad vi tænker. Altså, vores fremgang er.
00:24:50,914 --> 00:24:51,330
Linda: Dejligt!
00:24:52,289 --> 00:24:56,130
Mads: Jeg tror som udgangspunkt, vi snakkede lidt om at prøve at holde det lidt det samme uden at
00:24:56,130 --> 00:24:57,429
lave for meget om I brugerfladen.
00:24:57,570 --> 00:25:01,409
Fordi det kunne jo være fedt, at du ikke skulle lære det at kende igen.
00:25:01,409 --> 00:25:08,895
Linda: Ja, det er rigtigt. Men man kan jo så vende det om og sige, at I vil nok altid kunne hvis I går
00:25:08,895 --> 00:25:12,355
efter, at det skal være noget, der kan køre på en mobile
00:25:12,895 --> 00:25:15,555
Linda: så vil I næsten altid kunne gøre det mere simpelt.
00:25:15,935 --> 00:25:16,675
Mads: Det er rigtigt.
00:25:16,815 --> 00:25:22,740
Linda: Altså, hvor man bare siger: Okay, jeg har den her dato, som jeg gerne vil holde
00:25:25,440 --> 00:25:33,475
fri. Så går den ind og klasker dato og så Bing ind med den.
00:25:34,175 --> 00:25:38,815
Og så kan man sige: Okay, jeg vil også gerne lige se det overblik, jeg har, og hvor mange feriedage,
00:25:38,815 --> 00:25:40,515
jeg har flyttet over fra Succes Factor.
00:25:42,975 --> 00:25:44,340
Det er svært ved at sige nogen gange.
00:25:44,820 --> 00:25:46,580
Så kan man jo gå ind og se det.
00:25:46,580 --> 00:25:49,799
Men ellers har du jo kun de der datofelter.
00:25:50,820 --> 00:25:51,620
Mads: Det var det.
00:25:51,620 --> 00:25:54,919
Linda: Og så en submit knap. Ja.
00:25:56,100 --> 00:25:59,240
Så er den jo ekstremt simpel I forhold til den anden.
00:26:00,105 --> 00:26:07,625
Så er det jo kun projektlederen, der skal ind og lave et nyt team, der går på tværs af de øvrige
00:26:07,625 --> 00:26:09,965
teams, som har brug for en desktop.
00:26:10,665 --> 00:26:14,045
For det bliver lidt kompliceret at få mokket ned I telefonen.
00:26:14,600 --> 00:26:17,900
Mads: Ja, det kunne du nok have ret i. Med at oprette teams. Ja,
00:26:19,000 --> 00:26:21,420
Linda: men den kan du jo også altså Undskyld.
00:26:21,640 --> 00:26:26,700
Den kan du jo egentlig også gøre her ved, at du bare sætter den ind og giver den et navn.
00:26:26,855 --> 00:26:30,775
Og så får du valg muligheder for at søge de enkelte brugere frem.
00:26:30,775 --> 00:26:33,435
Så kan du også lave den relativt enkelte.
00:26:37,495 --> 00:26:41,175
Zafir: Jeg kom til at tænke på, om det er vigtigt at se et teams, som du ikke er en del af?
00:26:41,175 --> 00:26:45,299
Linda: Nej. Det er bestemt ikke vigtigt foran dig.
00:26:45,299 --> 00:26:47,320
Det tror jeg ikke, det er vigtigt for ret mange.
00:26:49,139 --> 00:26:56,279
Man skal kunne søge dem frem I det øjeblik, man skal ændre ejer på dem.
00:26:58,515 --> 00:27:02,935
Jeg tænker faktisk, at man skal indtænke en adminfunktion.
00:27:05,395 --> 00:27:10,455
Så der er en mindre gruppe, der vil kunne sige: Okay,
00:27:13,090 --> 00:27:17,490
nu er Yrsas team, hendes projekt team, det er overgået til en anden projektleder, Yrsa, som hun
00:27:17,490 --> 00:27:18,550
er stoppet i forretningen.
00:27:19,810 --> 00:27:27,875
Så skal jeg som admin kunne sige: Vi skifter ejeren til at være Solaima I stedet for os.
00:27:28,174 --> 00:27:30,035
Mads: Okay, det kan alle gå ind og gøre nu?
00:27:30,495 --> 00:27:32,275
Linda: Nej, det er der sgu ingen, der kan.
00:27:32,335 --> 00:27:33,395
Mads: Der er ingen, der kan.
00:27:33,455 --> 00:27:34,914
Linda: Du får måske, jeg kan.
00:27:37,135 --> 00:27:40,050
Det er tusind år siden jeg har forsøgt det.
00:27:40,050 --> 00:27:41,990
Men det er der ikke ret mange der kan.
00:27:42,130 --> 00:27:46,070
Mads: Jamen ligger det på deres login, eller hvad er det, at de kan få lov til det?
00:27:46,930 --> 00:27:53,274
Linda: Det ligger jo så snart du selv går ind som bruger og opretter det her team på tværs af de andre
00:27:53,274 --> 00:27:56,975
teams, så er den knyttet op på din bruger.
00:27:57,355 --> 00:28:05,034
Så når du stopper, kan de stadig se teamet, men de kan ikke administrere på, hvilke brugere
00:28:05,034 --> 00:28:06,235
der kan komme til og fra
00:28:07,660 --> 00:28:13,200
så det kan jo hurtigt gå ind og blive et problem, når man kører med nogle ret store projektteams I kompagniet.
00:28:13,340 --> 00:28:15,120
Mads: ja, det lidt noget træls noget.
00:28:15,660 --> 00:28:21,345
Der kunne man måske have noget med, at du kunne sige, at der var nogen, der ikke arbejdede længere,
00:28:21,745 --> 00:28:25,044
Og så får du nogle dialoger med, hvem teamsne skal overgå til.
00:28:25,505 --> 00:28:26,645
Ja, det kunne være fint.
00:28:27,105 --> 00:28:31,845
Linda: Ja, måske bare en mail til den næste kommende I listen, at I skal finde en ny ejer.
00:28:32,225 --> 00:28:34,325
Mads: Ja, det kunne man selvfølgelig godt gøre,
00:28:35,309 --> 00:28:37,090
Linda: Det gør vi på vores team sites.
00:28:38,030 --> 00:28:46,830
Der har vi sat et lille flow op, der gør, at den tager en tilfældig medlem af team sitet og siger:
00:28:46,830 --> 00:28:47,870
Nu er du blevet ejer.
00:28:47,870 --> 00:28:50,085
Fordi der var ikke nogen ejer på jeres teams.
00:28:51,684 --> 00:28:56,424
Så får de en guide med til, hvordan de kan ændre det, hvis de ikke selv vil være ejer.
00:28:56,804 --> 00:28:58,664
Mads: Okay, det var faktisk nem at gøre det på.
00:28:58,804 --> 00:29:00,645
Burde man ikke at skulle ind og tage et valg nødvendigvis.
00:29:00,645 --> 00:29:01,284
Linda: Nej nej, så
00:29:01,284 --> 00:29:02,904
Mads: bliver stafetten bare smidt videre.
00:29:03,125 --> 00:29:07,250
Linda: Så får de bare stafetten, og så må de sende sig for, at de ikke er sammen. Okay.
00:29:08,429 --> 00:29:09,549
Mads: Det er helt klart noget, vi skal have.
00:29:09,549 --> 00:29:14,370
Men vi har mange døde teams næsten så, eller døde, som vi ikke selv bestemmer over længere.
00:29:14,669 --> 00:29:16,110
Linda: Nej, det har vi jo så ikke.
00:29:16,110 --> 00:29:17,505
Det har vi så netop ikke.
00:29:17,585 --> 00:29:21,765
Mads: Er de væk så? Nej, de teams, der siger, der er en, der oprettede et team?
00:29:21,985 --> 00:29:28,945
Linda: Nej, inde I ferien. Ja, der er mange, som ikke fungerer længere.
00:29:28,945 --> 00:29:30,545
Mads: Nå, så ophober de sig op nærmest?
00:29:30,545 --> 00:29:37,740
Linda: Ja, det gør de. Og hvis du fx har et projekt team nu er det jo stor udskiftning, vi er I til verden, ikke?
00:29:40,280 --> 00:29:46,440
Så er der faktisk nogle team sites, hvor der ikke kun er tilbage, for eksempel fordi alle er
00:29:46,440 --> 00:29:49,575
stoppet, så forsvinder de jo.
00:29:49,715 --> 00:29:52,534
Så forsvinder de ud af vores miljø og systemer.
00:29:53,475 --> 00:29:55,095
Og så er der ikke nogen tilbage.
00:29:55,634 --> 00:30:00,134
Zafir: Er der nogen teams, også selvom de forsvinder, som I gerne vil have beholdt.
00:30:03,000 --> 00:30:11,179
Linda: Nej. Nej, nej. Hvis ikke der er nogen, der er I de der kalenderteams, så skal de jo bare dø.
00:30:12,600 --> 00:30:14,220
Mads: Det giver selvfølgelig god mening, ja.
00:30:14,715 --> 00:30:16,875
Hvad med deres konto, de logger ind med?
00:30:16,875 --> 00:30:18,495
Det er jo det der Azure directory.
00:30:18,554 --> 00:30:21,054
Når I er logget ind der, så har I et link, I er klik på.
00:30:21,515 --> 00:30:26,095
For de fjernet deres konto, når de stopper med at arbejde?
00:30:27,275 --> 00:30:27,755
Linda:Fuldstændig.
00:30:33,920 --> 00:30:37,940
Der er ikke nogen, der vil kunne komme ind på sådan en løsning, efter de er stoppet.
00:30:38,400 --> 00:30:42,400
Mads: Okay, men jeg tænkte mere på, for det kunne jo næsten være, at man kunne automatisere det.
00:30:42,400 --> 00:30:47,855
Lad os sige, når de alligevel stopper med arbejdet, og deres konto bliver fjernet, vil vi kunne
00:30:47,855 --> 00:30:49,715
se det fra Azzure directory.
00:30:49,935 --> 00:30:55,235
Og så sige, at nu skal vi smide stafetten videre på alle de teams, så der hele tiden bliver ryddet op automatisk.
00:30:55,695 --> 00:30:57,795
Linda: ja, det ville man jo kunne gøre.
00:30:58,015 --> 00:31:07,940
Så kunne være det smart at gøre, at så snart en ejer forsvinder fra et team, så kører man den nye.
00:31:08,240 --> 00:31:11,220
Mads: Ja, okay. Det skal vi først lige kigge på så.
00:31:13,955 --> 00:31:16,115
Zafir: Jeg har I fald ikke mere lige nu.
00:31:16,115 --> 00:31:19,795
Mads: Det tror jeg, du var det. Det var meget givende. Det var guld værd.
00:31:19,795 --> 00:31:20,995
Zafir: Det var faktisk virkelig
00:31:20,995 --> 00:31:23,155
Mads: guld værd. Det er en helt anden retning, vi lige havde forestillet os.
00:31:23,155 --> 00:31:28,049
Det er faktisk ret fedt. Det er Det er
00:31:28,049 --> 00:31:29,429
Zafir: lige at få svar på det.
00:31:30,210 --> 00:31:31,190
Mads: Ja, hundred procent.
00:31:32,529 --> 00:31:34,870
Linda: det var godt at kunne være til hjælp
00:31:36,289 --> 00:31:38,230
Så ville vi spise bolche til resten af tiden.
00:31:40,529 --> 00:31:43,335
Zafir: Er der forskel på, om de er pink eller blå? Overhovedet ikke.
00:31:43,335 --> 00:31:44,794
Nej, det er bare den samme derinde.
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/023_Oath%20of%20the%20Gatewatch.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Oath of the Gatewatch", doc)
#include "./023 - Oath of the Gatewatch/001_The Rise of Kozilek.typ"
#include "./023 - Oath of the Gatewatch/002_Retaliation of Ob Nixilis.typ"
#include "./023 - Oath of the Gatewatch/003_Reclamation.typ"
#include "./023 - Oath of the Gatewatch/004_The Blight We Were Born For.typ"
#include "./023 - Oath of the Gatewatch/005_Up in Flames.typ"
#include "./023 - Oath of the Gatewatch/006_Oath of the Gatewatch.typ"
#include "./023 - Oath of the Gatewatch/007_Brink of Extinction.typ"
#include "./023 - Oath of the Gatewatch/008_Zendikar's Last Stand.typ"
#include "./023 - Oath of the Gatewatch/009_Zendikar Resurgent.typ"
|
|
https://github.com/leyan/cetzpenguins | https://raw.githubusercontent.com/leyan/cetzpenguins/main/sample.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#import "src/penguins.typ" :penguin,penguinInternal
#cetz.canvas(length:1cm,{
import cetz.draw: *
penguinInternal()
translate(x:3,y:1)
penguinInternal()
translate(x:2.5,y:-0.5)
penguinInternal()
translate(x:2.5,y:0.2)
penguinInternal()
})
#penguin()
#penguin(
width:1.5cm,
color:aqua,
eyes:(
shape:"wink"
)
)
#penguin(
width:2cm,
body-color:blue,
head-color:red,
left-eye:(color:red,
shape:"shiny"),
right-eye:(
color:green,
shape:"wink")
)
#penguin(
width:3cm,
left-eye:(color:green),
right-eye:(shape:"none")
) |
https://github.com/lab57/TypstBot | https://raw.githubusercontent.com/lab57/TypstBot/master/test.typ | typst |
#import "@preview/physica:0.9.2" : *
#set page(width: auto, height: auto, margin: .1em, fill: rgb(49, 51,56 ,255))
#set text(size: 24pt, fill: white)
$ $
|
|
https://github.com/maantjemol/Aantekeningen-Jaar-2 | https://raw.githubusercontent.com/maantjemol/Aantekeningen-Jaar-2/main/Entrepreneurship/cases.typ | typst | #import "../template/lapreprint.typ": template
#import "../template/frontmatter.typ": loadFrontmatter
#import "@preview/drafting:0.2.0": *
#import "@preview/cetz:0.2.2"
#let default-rect(stroke: none, fill: none, width: 0pt, content) = {
pad(left:width*(1 - marginRatio), rect(width: width*marginRatio, stroke: stroke)[
#content
])
}
#let defaultColor = rgb("#2d75f2")
#let caution-rect = rect.with(inset: 1em, radius: 0.5em, fill: defaultColor.lighten(96%), width:100%, stroke: defaultColor.lighten(80%))
#let note = (content) => inline-note(rect: caution-rect, stroke: defaultColor.lighten(60%))[#content]
#show: template.with(
title: "Entrepreneurship cases",
subtitle: "Samenvatting",
short-title: "",
venue: [ar#text(fill: red.darken(20%))[X]iv],
// This is relative to the template fsile
// When importing normally, you should be able to use it relative to this file.
theme: defaultColor,
authors: (
(
name: "<NAME> . ",
),
),
kind: "Samenvatting",
abstract: (
(title: "Samenvatting", content: [#lorem(100)]),
),
open-access: true,
margin: (
(
title: "",
content: [
],
),
),
font-face: "Open Sans"
)
#set page(
margin: (left: 1in, right: 1in), paper: "a4"
)
#let marginRatio = 0.8
#let default-rect(stroke: none, fill: none, width: 0pt, content) = {
pad(left:width*(1 - marginRatio), rect(width: width*marginRatio, stroke: stroke)[
#content
])
}
#set-page-properties()
#show terms: it => [
#note[#text(defaultColor, weight: 600, size: 10pt)[#it.children.first().term]\ #it.children.first().description]
]
#set heading(numbering: none)
#show heading: set text(defaultColor, weight: "medium")
= GEOX
== Would you describe the founder of Geox as an innovator or inventor, and why?
I would describe the founder of Geox as an innovator. He did invent the idea of a breathable soles, but also commercialized it and made it a success. He converted his great idea into a successful product.
== Which aspects of creativity and problem solving do you recognize in the case?
- Mario encountered a problem, damp feet when walking in warm environments, and came up with a creative solution, a breathable sole.
- He fixed this problem in a creative way, by first cutting holes in the soles of his shoes, and later by inventing a new technology in collaboration with universities.
- He kept this problem solving up by continuously improving the technology and expanding the product range. Geox also has a big focus on R&D.
== Who are Geox's key competitors?
Geox's key competitors are Nike, Adidas, and C&J Clark. These companies are also big players in the sports and casual footwear industry.
== What strategies and options are available to Geox for sustaining its position in these industries?
- Geox has more then 50 patents, which gives them a competitive advantage. This makes it harder for other companies to copy their technology.
- Geox has a big focus on R&D, which allows them to continuously improve their products and come up with new products.
== What factors, other than product innovation, does Geox owe its competitive advantage to?
- Geox was founded in Italy and has a strong focus on fashion, not only technology. They realized that they have to ensure that the shoes looked good, and stay on top of fashion trends.
- They have a strong marketing strategy that focuses on the fashion and technology aspects of the shoes. |
|
https://github.com/Coekjan/touying-buaa | https://raw.githubusercontent.com/Coekjan/touying-buaa/master/lib.typ | typst | MIT License | // Stargazer theme - adapted for BUAA
#import "@preview/touying:0.5.2": *
#import themes.stargazer: *
#let buaa-theme(
aspect-ratio: "16-9",
lang: "en",
font: ("Linux Libertine",),
..args,
body,
) = {
set text(lang: lang, font: font)
show: if lang == "zh" {
import "@preview/cuti:0.2.1": show-cn-fakebold
show-cn-fakebold
} else {
it => it
}
show: stargazer-theme.with(
aspect-ratio: aspect-ratio,
config-info(
logo: image("assets/vi/buaa-logo.svg"),
),
..args,
)
body
}
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week5.typ | typst | #import "../../utils.typ": *
#section("Dezentralized Finance (DEFI)")
#subsection("Centralized Finance (CEFI)")
- fiat currencies -> USD, CHF etc
- gold, percious metals etc.
- perls
- first seen in mesopotamia -> clay tokens
#subsection("DEFI differences")
- trade of assets without intermediary -> the blockchain handles trust
- transparency
- public rules and protocols
- avoid private agreements, back deals and centralization
- control
- DeFi gives more control to its users. No-one should be able to censor, move or
destroy users assets
- accessibility
- anyone with a computer, internet connection and know-how can use or create DeFi
products
- mainly referred to creating DeFi -> much easier than creating a bank
#subsubsection("Flash Loan")
A small interest free loan meant for use inside of a contract by developers ->
take a loan, do the transaction of the contract, then pay the money back.
Flash loans are always paid back, if the transaction fails, then the tokens are
returned, this is because of atomicity of a contract.
#subsubsection("Truly DeFi?")
#align(
center,
[#image("../../Screenshots/2023_10_16_11_23_07.png", width: 80%)],
)
#subsubsection("High-Level Overview")
#align(
center,
[#image("../../Screenshots/2023_10_16_11_30_34.png", width: 100%)],
)
- Bear Raid: spreading FUD -> spreading bullshit in order to crash the market
- market cornering: Essentially majority stake in the market -> position to raise
its own prices
#subsection("DeFi Key Featurs")
+ *Public Verifiability*
- while the DeFi platform doesn't need to be open-source, the execution and
bytecode must be publicy verifiable on a blockchain
+ *Custody*
- you can buy or sell your coins at any time if you hold them yourselves, you are
not necessarily beholden to a platform.
- note, if you hold them yourself and you lose them, well shit
+ *Privacy*
- DeFi can be anonymous or not
- Blockchains offer pseudonimity -> not real privacy
- If I know what you buy from some twitter post, I might be able to find the
according transaction and hence your wallet.
- centralized exchanges do not offer privacy -> usually data is enforced by
government
+ *Atomicity*
- legal agreements can enforce atomicity for CeFi
- shop is forced to ship product by law when you paid for it
- multiple transactions can be made into one -> they appear atomic
- flash loan is a good example -> contract including flash loan is one single
thing
+ *Execution Order Malleability*
- transaction order can be manipulated by paying more for the transaction ->
higher gas price
- used with frontrunning -> by voting your transaction before a big transaction,
you can short-term pump and dump the coin to gain money. Usually, you need
knowledge of a future transaction, but by voting, you can change the transaction
order, removing this need.
- CeFi transaction order is set by law
+ *Transaction Costs*
- essential to prevent spam
- CeFi are usually without overhead other than tax
- fees can vary, making some blockchains unusable for selling/buying products
+ *Anonymous Development and Deployment*
+ *Non-Stop Market Hours*
- as long as the blockchain exists, you can do whatever
- for centralized exchanges, you are beholden to their hours
#subsection("Regulations")
- regulatory state is still unclear
- is there liability for code?
- blacklisting possible
- addresses who engage in malicious behavior can be blacklisted
- USDT and USDC have such blacklists
- USDT and USDC is controlled by the USA -> they can block your account and
destroy your tokens
- miners can choose what to mine on
- transactions can hence be censored by not mining the block with it
- USA has a lot of miners under its influence -> USA can potentially block
transactions by imposing restrictions on these miners
#subsection("Centralized Exchange Rate (CEX)")
- Centralized (CEX): ask/bid, sell/buy, the last trade, e.g., 200 DAI for 1 ETH →
price (order book)
- Workflow: create order, publish on exchange, wait to get filled. Browse orders,
start fill order.
- Prince changes if trade happens, ask was same or lower than bid. Ask/bid
submitted by users – add/remove orders
- *Slippage*: you see a price, submit, and until its executed, price can change.
- Set limits, order may stay in the orderbook
#subsection("Decentralized Exchange Rate (CEX)")
- Decentralized (DEX): ratio of pairs (automatic market making)
- Workflow: exchange pairs
- *Slippage*: the “same” - sometimes (mis)used as price impact
- difference from now to actual execution of transaction
- Example amount in pool: DAI 200, ETH 1 → price 200DAI/1ETH
#align(
center,
[#image("../../Screenshots/2023_10_16_12_12_48.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_16_12_13_18.png", width: 70%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_16_12_39_50.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_16_12_40_21.png", width: 100%)],
)
#subsubsection("Arbitrage Bots")
- they normalize costs after a transaction to keep prices in line with other
exchanges
- Dex would not work without it!
- essential part of the ecosystem
- Swapping in multiple pools or CEX, if a bootsees e.g., a trading opportunity,
- Example: Pool 1: 250 DAI for 1 ETH, pool 2: 200 DAI for 1 ETH
- Arbitrage bot has 1 ETH (not considering price impact in this example)
- Buy for 1 ETH 250 DAI in pool 1
- Sell 250 DAI for 1.25 ETH in pool 2, profit = 0.25 ETH
#subsubsection("Liquidity Providing")
Someone needs to fill the pool of a DeX, this means providing tokens for the
exchange.
- adding liquidity may not change price -> all pools must be increased so that all
exchange rates stay the same
- LP token is recieved for providing liquidity -> fees are collected
- can be seen as interest
- with more liquidity providers, you will receive less
- problem: "impermantent loss"
#align(
center,
[#image("../../Screenshots/2023_10_16_12_55_50.png", width: 100%)],
)
#align(
center,
[#image("../../Screenshots/2023_10_16_12_58_44.png", width: 100%)],
)
|
|
https://github.com/NwaitDev/Typst-Accessibility-Template | https://raw.githubusercontent.com/NwaitDev/Typst-Accessibility-Template/main/readme.md | markdown | # A Typst template for accessible content
This repository was born from a debate I had with a friend about wether to use MS Word or LaTeX to produce pdf documents.
Among all the arguments he talked to me about, the the most valuable one that I heard was the one on the accessibility of the documents.
Apparently, "What better than LaTeX to not produce an accessible document?" Unreadable, Old fashioned, lame...
I wanted to prove him wrong, so I decided I would write a template to easily generate accessible documents. And since that guy managed to get me interested into this Typst thing, I also wanted to give it a try at the same time.
## Requirements
To use that template, you will need the Typst compiler installed on your computer.
To compile the example document, open a terminal in this folder and run:
```bash
typst c article_template.typ
```
|
|
https://github.com/saimnaveediqbal/thesis-NTNU-typst | https://raw.githubusercontent.com/saimnaveediqbal/thesis-NTNU-typst/main/lib.typ | typst | MIT License | #import "@preview/subpar:0.1.1"
#import "@preview/physica:0.9.3": *
#let stroke-color = luma(200)
#let std-bibliography = bibliography
#let isappendix = state("isappendix", false)
#let front-matter(body) = {
set page(numbering: "i")
set heading(numbering: none)
body
}
#let main-matter(body) = {
set page(numbering: "1")
counter(page).update(1)
counter(heading).update(0)
set heading(numbering: "1.1")
body
}
#let subfigure = {
subpar.grid.with(
numbering: n => if isappendix.get() {numbering("A.1", counter(heading).get().first(), n)
} else {
numbering("1.1", counter(heading).get().first(), n)
},
numbering-sub-ref: (m, n) => if isappendix.get() {numbering("A.1a", counter(heading).get().first(), m, n)
} else {
numbering("a", m, n)
}
)
}
#let ntnu-thesis(
title: [Title],
short-title: [],
authors: ("Author"),
short-author: none,
paper-size: "a4",
date: datetime.today(),
date-format: "[day padding:zero]/[month repr:numerical]/[year repr:full]",
abstract-en: none,
abstract-no: none,
preface: none,
table-of-contents: outline(),
titlepage: true,
bibliography: none,
chapter-pagebreak: true,
chapters-on-odd: false,
figure-index: (
enabled: true,
title: "Figures",
),
table-index: (
enabled: true,
title: "Tables",
),
listing-index: (
enabled: true,
title: "Code listings",
),
body,
) = {
set document(title: title, author: authors)
// Set text fonts and sizes
set text(font: "Charter", size: 11pt)
show raw: set text(font: "DejaVu Sans Mono", size: 9pt)
//Paper setup
set page(
paper: paper-size,
margin: (bottom: 4.5cm, top:4cm, left:4cm, right: 4cm),
)
// Cover page
if titlepage {
page(align(center + horizon, block(width: 90%)[
#let v-space = v(2em, weak: true)
#text(2em)[*#title*]
#v-space
#for author in authors {
text(1.1em, author)
v(0.7em, weak: true)
}
#if date != none {
v-space
// Display date as MMMM DD, YYYY
text(1.1em, date.display(date-format))
}
]))
}
//Paragraph properties
set par(leading: 0.7em, justify: true, linebreaks: "optimized", first-line-indent: 1.2em)
show par: set block(spacing: 0.7em)
//Properties for all headings (incl. subheadings)
set heading(numbering: "1.1")
set heading(supplement: [Chapter ])
show heading: set text(hyphenate: false)
show heading: it => {
v(2.5em, weak: true)
it
v(1.5em, weak: true)
}
show: front-matter
// Properties for main headings (i.e "Chapters")
show heading.where(level: 1): it => {
//Show chapters only on odd pages:
if chapters-on-odd {
pagebreak(to: "odd", weak: false)
}
else if chapter-pagebreak {
//Show chapters on new page
colbreak(weak: true)
}
//Display heading as two lines, a "Chapter # \n heading"
v(10%)
if it.numbering != none {
set text(size: 20pt)
set par(first-line-indent: 0em)
text("Chapter ")
numbering("1.1", ..counter(heading).at(it.location()))
}
v(1.4em, weak: true)
set text(size: 24pt)
block(it.body)
v(1.8em, weak: true)
}
//Show abstract
if abstract-en != none {
page([
= Abstract
#abstract-en
])
}
//Show abstract
if abstract-no != none {
page([
= Sammendrag
#abstract-no
])
}
//Show preface
if preface != none {
page([
= Preface
#preface
])
}
// Display table of contents.
if table-of-contents != none {
set par(leading: 10pt, justify: true, linebreaks: "optimized")
show outline.entry.where(level: 1): it => {
strong(it)
}
set outline(indent: true, depth: 3)
table-of-contents
}
// Display list of figures
if figure-index.enabled {
outline(target: figure.where(kind: image), title: figure-index.title)
}
// Display list of tables
if table-index.enabled {
outline(target: figure.where(kind: table), title: table-index.title)
}
// Display list of code listings
if listing-index.enabled {
outline(target: figure.where(kind: raw), title: listing-index.title)
}
// Configure page numbering and footer.
set page(
header: context {
// Get current page number.
let i = counter(page).at(here()).first()
// Align right for even pages and left for odd.
let is-odd = calc.odd(i)
let aln = if is-odd { right } else { left }
// Are we on a page that starts a chapter?
let target = heading.where(level: 1)
// Find the chapter of the section we are currently in.
let before = query(target.before(here()))
if before.len() > 0 {
let current = before.last()
if query(target).any(it => it.location().page() == current.location().page() + 1) {
return
}
let chapter_number = counter(heading).at(here()).first()
if isappendix.get() {
chapter_number = numbering("A.1", chapter_number)
}
let chapter = emph(text(size: 10pt, current.supplement + [ #chapter_number: ] + current.body))
let display-title = []
if short-title != [] {
display-title = emph(text(size: 10pt, short-title))
} else {
display-title = emph(text(size: 10pt, title))
}
if short-author != none {
display-title = emph(text(size: 10pt, short-author)) + [: ] + display-title
}
if current.numbering != none {
if is-odd {
grid(
columns: (4fr, 1fr),
align(left)[#chapter],
align(right)[#i],
)
} else {
grid(
columns: (1fr, 4fr),
align(left)[#i],
align(right)[#display-title],
)
}
}
}
},
footer: ""
)
// Style code snippets
// Display inline code in a small box that retains the correct baseline.
show raw.where(block: false): box.with(
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code with padding.
show raw.where(block: true): block.with(
inset: (x: 5pt, y: 10pt),
stroke: stroke-color,
width: 100%,
)
show raw.where(block: true): set align(start)
show figure.where(
kind: raw
): set figure.caption(position: top)
// Configure proper numbering of figures and equations.
let numbering-fig = n => {
let h1 = counter(heading).get().first()
numbering("1.1", h1, n)
}
show figure: set figure(numbering: numbering-fig)
let numbering-eq = n => {
let h1 = counter(heading).get().first()
numbering("(1.1)", h1, n)
}
set math.equation(numbering: numbering-eq)
//Set table caption on top
show figure.where(
kind: table
): set figure.caption(position: top)
//Style lists
set enum(numbering: "1.a.i.", spacing: 0.8em, indent: 1.2em)
set list(spacing: 0.8em, indent: 1.2em, marker: ([•], [◦], [--]))
show: main-matter
body
//Style bibliography
if bibliography != none {
pagebreak()
show std-bibliography: set text(0.95em)
// Use default paragraph properties for bibliography.
show std-bibliography: set par(leading: 0.65em, justify: false, linebreaks: auto)
bibliography
}
}
//Style appendix
#let appendix(chapters-on-odd: false, body) = {
set heading(numbering: "A.1")
set heading(supplement: [Appendix ])
show heading: it => {
if chapters-on-odd {
pagebreak(to: "odd", weak: true)
} else {
colbreak(weak: true)
}
v(10%)
if it.numbering != none {
set text(size: 20pt)
set par(first-line-indent: 0em)
text("Appendix ")
numbering("A.1", ..counter(heading).at(it.location()))
}
v(1.4em, weak: true)
set text(size: 24pt)
block(it.body)
v(1.8em, weak: true)
}
// Reset heading counter
counter(heading).update(0)
// Equation numbering
let numbering-eq = n => {
let h1 = counter(heading).get().first()
numbering("(A.1)", h1, n)
}
set math.equation(numbering: numbering-eq)
// Figure and Table numbering
let numbering-fig = n => {
let h1 = counter(heading).get().first()
numbering("A.1", h1, n)
}
show figure.where(kind: image): set figure(numbering: numbering-fig)
show figure.where(kind: table): set figure(numbering: numbering-fig)
isappendix.update(true)
body
}
|
https://github.com/dainbow/FunctionalAnalysis2 | https://raw.githubusercontent.com/dainbow/FunctionalAnalysis2/main/themes/2.typ | typst | #import "../conf.typ": *
= Обратимый оператор. Обратимость
== Обратимость линейного, ограниченного снизу, оператора
#theorem[
Пусть $A in cal(L)(E)$ -- взаимно однозначный оператор $E -> "Im" A$. Тогда
обратный оператор $A^(-1)$ будет ограничен тогда и только тогда, когда образы $A$ оцениваются
снизу:
#eq[
$exists m : space forall x in E : space norm(A x) >= m norm(x)$
]
]
#proof[
$=>$ В силу ограниченности оператора $A^(-1)$, можно записать следующее:
#eq[
$forall y = A x : space norm(x) = norm(A^(-1) y) <= norm(A^(-1))norm(y) = norm(A^(-1))norm(A x)$
]
Отсюда имеем $norm(A x) >= 1 / norm(A^(-1))norm(x)$.
$arrow.l.double$ Раз $A$ -- биекция, то и $A^(-1)$ тоже. Поэтому вместо $x$ можно
подставить соответствующий ему $A^(-1) y, y in "Im" A$:
#eq[
$forall y in "Im" A : space norm(A A^(-1) y) >= m norm(A^(-1) y) <=> norm(A^(-1) y) <= 1/m norm(y)$
]
А это в точности ограниченность оператора $A^(-1)$.
]
== Обратимость возмущённого оператора
#theorem[
Пусть $E$ -- банахово пространство, $A in cal(L)(E)$, причём $norm(A) < 1$.
Тогда оператор $(I + A)$ обратим. Более того, справедлива формула
#eq[
$(I + A)^(-1) = sum_(k = 0)^oo (-1)^k A^k$
]
]
#note[
Выписанный ряд называется *рядом Неймана*.
]
#proof[
Нужно доказать, что ряд справа действительно является обратным к оператору $(I + A)$.
Обозначим $S_n = sum_(k = 0)^n (-1)^k A^k$.
+ Покажем, что $S_n$ сходится к некоторому $S in cal(L)(E)$. Во-первых, $S_n in cal(L)(E)$ тривиальным
образом, а в силу банаховости $E$, достаточно проверить фундаментальность этой
последовательности:
#eq[
$norm(S_(n + p) - S_n) = norm(sum_(k = n + 1)^(n + p)(-1)^k A^k) <= sum_(k = n + 1)^(n + p) norm(A)^k < epsilon$
]
Последнее неравенство выполняется, начиная с некоторого $n$, так как $norm(A), norm(A)^2, ...$ образуют
геометрическую прогрессию со знаменателем $< 1$.
+ Так как многочлены от одного и того же оператора коммутируют, то если мы
покажем, что предел
#eq[
$lim_(n -> oo)S_n (I + A) = I => S(I + A) = I = (I + A)S$
]
и всё доказано.
Раскроем выражение под пределом:
#eq[
$S_n (I + A) = S_n + S_n A &= sum_(k = 0)^n (-1)^k A^k + sum_(k = 1)^(n + 1)(-1)^(k - 1) A^k = \ &= A^0 + (-1)^n A^(n + 1) = I + (-1)^n A^(n + 1)$
]
Оценим норму последнего слагаемого:
#eq[
$norm((-1)^n A^(n + 1)) <= norm(A)^(n + 1) ->_(n -> oo)0$
]
Стало быть, $lim_(n -> oo)S_n (I + A) = I + 0$, что и требовалось доказать.
]
#theorem[
Пусть $E$ -- банахово пространство, $A in cal(L)(E)$ и $A^(-1) in cal(L)(E)$.
Также пусть $Delta A in cal(L)(E)$, причём $norm(Delta A) < 1 / norm(A^(-1))$.
Тогда $(A + Delta A)^(-1) in cal(L)(E)$.
]
#proof[
Сведём теорему к предыдущей:
#eq[
$A + Delta A = A(I + A^(-1)Delta A)$
]
Проверим, что норма оператора из скобки удовлетворяет условию на норму:
#eq[
$norm(A^(-1)Delta A) <= norm(A^(-1))dot norm(Delta A) < 1$
]
]
== Формулировка теормы Банаха об обратном операторе. Доказательство в случае гильбертова пространства.
#theorem(
"Банаха об обратном операторе",
)[
Пусть $E_1, E_2$ -- банаховы пространства, $A in cal(L)(E_1,E_2)$ -- биективный
оператор. Тогда $A^(-1) in cal(L)(E_2, E_1)$.
]
#proof[
Случай, когда $E_1 = E_2 = H$ -- гильбертово пространство над полем $CC$.
Основная идея состоит в том, чтобы доказать утверждение теоремы не для $A$, а
для $A^*$. Запишем 2 разложения пространства $H$ (тема про сопряжённый оператор
и разложение будет далее):
#eq[
$["Im" A] plus.circle "Ker" A^* = H$
$["Im" A^*] plus.circle "Ker" A = H$
]
Так как $A$ биективен, то $"Ker" A = {0}$ и мы сразу получаем $["Im" A^*] = H$.
С другой стороны, $["Im" A] = "Im" A = H$, а потому $"Ker" A^* = {0}$.
Далее вы узнаете, что сопряжённый оператор всегда ограничен снизу, а значит из
его сюръективности автоматически следует ограниченность обратного.
]
|
|
https://github.com/jrihon/multi-bibs | https://raw.githubusercontent.com/jrihon/multi-bibs/main/chapters/03_chapter/bib_03_chapter.typ | typst | MIT License | #let dict_03_chapter = (
"Iupac1983nucleicacids": 1,
"Neese2021orca": 2,
"Cremer1975general": 3,
)
#let biblio = (
bibchapter: dict_03_chapter,
bibyml: "../chapters/03_chapter/03_chapter.yml",
)
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-implementation/monaco.typ | typst | === Ungrammar Monaco Extension <subsec-impl-monaco>
The Ungrammar Monaco Extension represents a significant step forward in
bringing the Ungrammar language ecosystem to a broader audience within the
browser environment. By leveraging the Monaco editor, we've created a powerful
and accessible tool that offers a seamless coding experience.
Key Features and Benefits:
- *Direct Language Service Integration*: The extension directly integrates with
the Ungrammar Language Service (@subsec-impl-langservice), eliminating the
need for a separate Language Server module. This streamlined approach reduces
the overall size of the extension, resulting in faster downloads and a more
efficient user experience.
- *JSON-RPC Optimization*: We've optimized the communication between the
extension and the Language Service by removing the JSON-RPC layer. This
further contributes to improved performance and reduced overhead.
- *Enhanced Functionality*: The Ungrammar Monaco Extension provides a
comprehensive set of language features, including syntax highlighting, code
completion, diagnostics, and navigation, directly within the Monaco editor.
- *Seamless Integration*: The extension integrates seamlessly with the Monaco
editor, offering a familiar and intuitive user interface.
- *Online Demonstration*: The Ungrammar Online Demonstration Playground
(@subsec-impl-playground) utilizes the Ungrammar Monaco Extension to provide
a live coding environment for users to explore and experiment with the
language features.
In general, the Ungrammar Monaco Extension plays a crucial role in expanding
the reach of the Ungrammar language ecosystem and making it accessible to a
wider audience of developers.
==== Implementation Detail
The Ungrammar Monaco extension directly integrates with the Ungrammar Language
Service, eliminating the need for a separate Language Server. This streamlined
approach reduces overhead and improves performance by avoiding unnecessary JSON
parsing and server-side communication.
By leveraging the Language Service directly, the Monaco extension provides a
powerful and efficient environment for working with the Ungrammar language,
offering features like syntax highlighting, code completion, and diagnostics
without the additional complexity of a separate server.
#figure(
raw(read("/assets/tree-monaco.txt"), block: true),
caption: [Tree of Ungrammar Monaco workspace],
)
==== Deployment to NPM
Upon completion of development, we successfully deployed the Ungrammar Monaco
to the NPM registry. This strategic move allows other developers to easily
discover, integrate, and extend our project for their own language-related
endeavors. By making the Monaco extension readily available on NPM, we've
expanded the accessibility and potential impact of our work within the
developer community.
Here is our deployed Ungrammar Monaco, which has been downloaded by
158 users since its public release and is currently hosted at
#link("https://www.npmjs.com/package/ungrammar-monaco").
#figure(
image("/assets/monaco.jpg", width: 90%),
caption: [Deployed Ungrammar Monaco on NPM],
)
|
|
https://github.com/qujihan/toydb-book | https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter3/message.typ | typst | #import "../../typst-book-template/book.typ": *
#let path-prefix = figure-root-path + "src/pics/"
== Raft之Message
#code("src/raft/message.rs", "Message 类型")[
```rust
/// 发送者和接收者的消息信封(在Message上包装了一层额外信息).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Envelope {
pub from: NodeID, // 从哪里来
pub term: Term, // 发送者的当前term
pub to: NodeID, // 到哪里去
pub message: Message, // 具体发送的信息
}
/// Raft的Node之间的消息, 消息是异步发送的, 可能会丢失或者重排序.
/// 在实践中, 它们通过TCP连接发送, 并通过crossbeam通道确保消息不会丢失或重排序, 前提是连接保持完好.
/// 消息的发送以及回执都是通过单独的TCP连接.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Message {
/// Candidates 从其他Node中获取投票, 以便成为Leader.
/// 只有当Candidate的日志至少与投票者一样新时, 才会授予投票.
Campaign {
last_index: Index, // Candidate最后一个日志的index
last_term: Term, // Candidate最后一个日志的term
},
/// Followers 只有在Candidate的日志至少与自己一样新时, 才会投票.
/// Canidate会隐式的投票给自己.
CampaignResponse {
/// true表示投票给Candidate, false表示拒绝投票.
/// 拒绝投票不是必须的, 但是为了清晰起见, 还是会发送.
vote: bool,
},
/// Leader 会定期发送心跳, 这样有几个目的:
/// 1. 通知节点当前的 Leader, 防止选举.
/// 2. 检测丢失的 appends和 reads, 作为重试机制.
/// 3. 告知Followers 已经提交的 indexes, 以便他们可以应用 entries.
/// Raft论文中使用了一个空的AppendEntries RPC来实现心跳, 但是我们选择添加一个以更好的分离心跳消息.
Heartbeat {
/// last_index 是 Leader 最后一个日志的index, Term 是Leader 的当前 term.
/// 因为它在选举成功后会追加一个空的entry. Follower 会将这个与自己的日志进行比较, 以确定是否是最新的.
last_index: Index,
/// 表示的是 Leader 的最后一个提交的日志的 index.
/// Followers 会使用这个来推进他们的 commit index, 并应用 entries.
/// (只有在本地日志与 last_index 匹配时才能安全地提交这个).
commit_index: Index,
/// Leader在这个term中的最新读序列号.
read_seq: ReadSequence,
},
/// Followers 回应 Leader 的心跳, 以便 Leader 知道自己还是 Leader.
HeartbeatResponse {
/// 如果不为0, 表示Follower的日志与Leader的日志匹配, 否则Follower的日志要么是不一致的, 要么是落后于Leader.
match_index: Index,
/// 心跳的 读 序列号.
read_seq: ReadSequence,
},
/// Leaders replicate log entries to followers by appending to their logs
/// after the given base entry.
///
/// If the base entry matches the follower's log then their logs are
/// identical up to it (see section 5.3 in the Raft paper), and the entries
/// can be appended -- possibly replacing conflicting entries. Otherwise,
/// the append is rejected and the leader must retry an earlier base index
/// until a common base is found.
///
/// Empty appends messages (no entries) are used to probe follower logs for
/// a common match index in the case of divergent logs, restarted nodes, or
/// dropped messages. This is typically done by sending probes with a
/// decrementing base index until a match is found, at which point the
/// subsequent entries can be sent.
/// Leaders 复制日志到 Followers, 通过在给定的 base 之后 entry 追加到他们的 log 中.
Append {
/// 即将添加的 entry 之前的 entry 的 index
base_index: Index,
/// 即将添加的 entry 之前的 entry 的 term
base_term: Term,
/// 即将被添加的 entry 集合, index 从 base_index + 1 开始
entries: Vec<Entry>,
},
/// Followers accept or reject appends from the leader depending on whether
/// the base entry matches their log.
AppendResponse {
/// If non-zero, the follower appended entries up to this index. The
/// entire log up to this index is consistent with the leader. If no
/// entries were sent (a probe), this will be the matching base index.
match_index: Index,
/// If non-zero, the follower rejected an append at this base index
/// because the base index/term did not match its log. If the follower's
/// log is shorter than the base index, the reject index will be lowered
/// to the index after its last local index, to avoid probing each
/// missing index.
reject_index: Index,
},
/// Leaders need to confirm they are still the leader before serving reads,
/// to guarantee linearizability in case a different leader has been
/// estalished elsewhere. Read requests are served once the sequence number
/// has been confirmed by a quorum.
Read { seq: ReadSequence },
/// Followers confirm leadership at the read sequence numbers.
ReadResponse { seq: ReadSequence },
/// A client request. This can be submitted to the leader, or to a follower
/// which will forward it to its leader. If there is no leader, or the
/// leader or term changes, the request is aborted with an Error::Abort
/// ClientResponse and the client must retry.
ClientRequest {
/// The request ID. Must be globally unique for the request duration.
id: RequestID,
/// The request itself.
request: Request,
},
/// A client response.
ClientResponse {
/// The ID of the original ClientRequest.
id: RequestID,
/// The response, or an error.
response: Result<Response>,
},
}
```
] |
|
https://github.com/Arsenii324/matap-p2 | https://raw.githubusercontent.com/Arsenii324/matap-p2/main/t-repo/lecture7.typ | typst | #import "macros.typ" : *
= Лекция
== Интеграл Римана на n-мерном пространстве
=== Опр. n-мерный промежуток
$I_(overline(a), overline(b)) = {overline(x) in RR^n : a_i <= x_i <= b_i, i in {1..n}}$, где $overline(x) = (x_1, ..., x_n), overline(a) = (a_1, ..., a_n), overline(b) = (b_1, ..., b_n)$ - называется n-мерным промежутком, заданным точками $overline(a), overline(b) "в " RR^n$.
=== Опр. мера промежутка
Пусть $I_(overline(a), overline(b)) $ промежуток в $RR^n$. Тогда мерой промежутка $m(I_(overline(a), overline(b)))$ будем называть число $limits(product)_(i = 0)^n (b_i - a_i)$.
=== Мера промежутка в $RR^n$
- #underline[n-однородна]: $m(lambda dot I_(overline(a), overline(b))) = lambda^n dot m(I_(overline(a), overline(b)))$
- #underline[аддитивна]: Если промежутки $I, I_1, ..., I_k$ таковы, что
a) $I eq limits(union)_(i = 0)^k I_i$
b) $I_1, ..., I_k$ попарно не имеют общих точек
то: $m(I) = sm_(i = 0)^k m(I_k)$
- Если промежутки $I, I_1, ..., I_k$ таковы, что $I subset.eq limits(union)_(i = 0)^k I_i$, то $m(I) <= sm_(i = 0)^k m(I_k)$
=== Опр. разбиение промежутка
Если промежутки $I, I_1, ..., I_k$ таковы, что
a) $I eq limits(union)_(i = 0)^k I_i$
b) $I_1, ..., I_k$ попарно не имеют общих точек
то множество $P(I) = {I_1, ..., I_k} $ будем называть разбиением промежутка.
=== Опр. диаметр множества
Если $X subset.eq RR^n$, то диаметром множества мы будем называть:
$d(X) = limits(sup)_(overline(x_1), overline(x_2) in X) abs(abs(overline(x_1) - overline(x_2)))$, где $abs(abs(overline(x_1) - overline(x_2)))$ - евклидово расстояние между точками в $RR^n$.
=== Опр. диаметр разбиения
Если $P(I)$ - разбиение промежутка $I subset RR^n$, то диаметром разбиения называют:
$d(P(I)) = max{d(I_1), ..., d(I_k)})$
=== Опр. разбиение с отмеченными точками
Если $P(I) = {I_1, ..., I_k}$ разбиение промежутка $I$ и в каждом промежутке $I_i$ фиксирована некая точка $overline(xi_i)$, то говорят, что имеется разбиение промежутка $I$ с отмеченными точками . Набор отмеченных точек ${overline(xi_1), ..., overline(xi_k)}$ будем обозначать как $overline(xi)$, а разбиение промежутка с точками как $(P(I), overline(xi))$.
=== Опр. интеграл Римана
Пусть $I subset.eq RR^n, f: I -> R$.
Тогда величина $int_I f(overline(x)) d overline(x) := limits(lim)_(d(P(I, xi)) -> 0) sm_(I_i) f(xi_i) dot m(I_i) $, если предел существует и не зависит от выбора отмеченных точек называется интегралом Римана от функции $f$ на промежутке $I$.
=== Утв. Необходимое условие интегрируемости
$f in R(I) => f in B(I)$
*Proof:*
Пусть интегрируема, но не ограничена. Тогда возьмём исходный промежуток. Рассматриваем любое произвольное его разбиение. Оно конечное. Если функция неограничена на всём промежутке, то найдется хотя бы один промежуток (из разбиения), на котором она не ограничена.
Посколько на промежутке функция не ограничена мы можем выбирать точку так, чтобы величина $abs(f(x) dot m(I_i)) --> infinity$. Тогда в силу произвольности разбиения можем сделать вывод, что необходимого предела не существует $=> f in.not R(I)$. Противоречие.
=== Опр. множество Лебеговой меры нуль
Множество $E in RR^n$ является множеством лебеговой меры нуль, если:
$forall epsilon > 0 " " exists {I_alpha}_(alpha in A), $ где $I_alpha subset RR^n $ - промежуток и $A$ не более чем счётно.
a) $E subset.eq limits(union)_(alpha in A) I_alpha$ - система ${I_alpha}$ является не более чем счётным покрытием $E$.
b) $sm_(alpha in A) m(I_alpha) < epsilon$
=== Свойства
1) $mu(a) = 0$
2) Если $E$ не более чем счётно, то $mu(E) = 0$
3) $mu(E) = 0, F subset E ==> mu(F) = 0$
4) $E_beta, beta in B, B$ не более чем счетно. $mu(E_beta) = 0 ==> mu(limits(union)_(beta in B) E_beta) = 0$
*Proof:*
1) Если $a in RR^n$ - просто точка, то очевидно найдется интервал, содержащий её и имеющий сколь угодно малую меру.
2) Пусть $B$ - счётно $=> exists tau: B -> NN "- биекция."$
Пусть $epsilon > 0 "- фиксировано." => "т.к." mu(E_beta) = 0, forall beta " " exists {I_(beta alpha)}_(alpha in A_beta) "- не более чем счетное накрытие " E_beta$ промежутками $I_(beta alpha)$ такое, что $sm_(alpha in A_beta) m(I_(beta alpha)) < epsilon/(2^(tau(beta)))$.
Ясно, что ${I_(beta alpha)}_(beta in B, alpha in A_beta)$ есть накрытие множества $limits(union)_(beta in B) E_beta$. Осталось заметить, что $sm_(alpha in A_beta, beta in B) m(I_(beta alpha)) < epsilon$.
Действительно, т.к. ряд знакоположительный, то порядок суммирования не влияет и $sm_(1)^n m(I_(beta alpha)) <= sm_(beta in B) epsilon/(2^(tau(beta))) = |"сумма геом. прогрессии"| = epsilon$.
3) Следует из определения
4) Следует из пунктов 1 и 2.
\
=== Критерий Лебега
Пусть $f : I -> R, I subset.eq RR^n => (f in R(I)) <==> (f in B(I), " лебегова мера точек разрыва" = 0)$.
== Критерий Дарбу. Интеграл по измеримому множеству.
=== Опр. суммы Дарбу
Пусть $I subset RR^n$ - n-мерный промежуток. $f : I -> RR, P(I) - "разбиение " I$.
Тогда:
- $s(f, P(I)) = sm_(P(I)) limits(inf)_I_i (f(x)) dot m(I_i)$
- $S(f, P(I)) = sm_(P(I)) limits(sup)_I_i (f(x)) dot m(I_i)$
_#underline[Лемма]_
$s(f, P) <= s(f, P')$
$S(f, P) >= S(f, P')$ |
|
https://github.com/xdoardo/co-thesis | https://raw.githubusercontent.com/xdoardo/co-thesis/master/thesis/chapters/delay/monads.typ | typst | #import "/includes.typ": *
== Monads<section-monads>
In 1989, <NAME> published a paper @moggi-monads in which the term
_monad_, which was already used in the context of mathematics and, in
particular, category theory, was given meaning in the context of functional
programming. Explaining monads is, arguably, one the most discussed topics in
the pedagogy of computer science, and tons of articles, blog posts and books try
to explain the concept of monad in various ways.
A monad is a datatype equipped with (at least) two functions, `bind` (often
`_>>=_`) and `unit`; in general, we can see monads as a structure used to
combine computations. One of the most common instance of monad is the `Maybe`
monad, which we now present to investigate what monads are: in Agda, the `Maybe`
monad is composed of a datatype
#agdacode[
//typstfmt::off
```hs
data Maybe {a} (A : Set a) : Set a where
just : A → Maybe A
nothing : Maybe A
```
//typstfmt::on
]
// TODO label here to appropriate section
(where `{a}` is the _level_, see @subsection-agda-types[Subsection]) and two
functions representing its monadic features:
#agdacode[
//typstfmt::off
```hs
unit : A -> Maybe A
unit = just
_>>=_ : Maybe A → (A → Maybe B) → Maybe B
nothing >>= f = nothing
just a >>= f = f a
```
//typstfmt::on
]
The `Maybe` monad is a structure that represents how to deal with computations
that may result in a value but may also result in nothing; in general, the line
of reasoning for monads is exactly this, they are a tool used to model some
behaviour of the execution, which is also called *effect*. In the context of programming
monads are also "computation builders".
Consider @code-monad-example: this example, even if simple, is a practical
application of the line of reasoning a programmer applies when using monads. In
this example, we want to simply increment an integer variable which might be,
for some reason, unavailable. The `_>>=_` function encapsulates the reasoning
that the programmer should make explicit, perhaps matching on the value of `x`,
in a compositional and reusable fashion.
#code(label:<code-monad-example>)[
//typstfmt::off
```hs
h : Maybe ℕ → Maybe ℕ
h x = x >>= λ v -> just (v + 1)
```
//typstfmt::on
]
The underlying idea of monads in the context of computer science, as explained
by Moggi in @moggi-monads, is to describe "notions of computations" that may
have consequences comparable to _side effects_ in pure functional languages.
=== Formal definition<subsubsection-monad-formal_def>
We will now give a formal definition of what monads are. They're usually
understood in the context of category theory and in particular _Kleisli
triples_; here, we give a minimal definition following @kohl-monads-cs.
#definition(
name: "Monad",
label: <def-monad>
)[
Let $A$, $B$ and $C$ be types. A monad $M$ is defined as the triple (`M` ,
`unit`, `_>>=_`) where `M` is a monadic constructor; `unit : A -> M A`
represents the identity function and
// typstfmt::off
`_>>=_ : M A -> (A -> M B) -> M B` is used for monadic composition.
//typstfmt::on
The triple must satisfy the following laws.
1. (*left identity*) For every `x : A` and `f : A -> M B`, `unit x >>= f` $eq.triple$ `f x`;
2. (*right identity*) For every `mx : M A`, `mx >>= unit` $eq.triple$ `mx`; and
3. (*associativity*) For every `mx : M A`, `f : A -> M B` and `g : B -> M C`,
`(mx >>= f) >>= g` $eq.triple$ `mx >>= (λ my -> f my >>= g)`
]
== The Delay monad<subsection-monad-delay_monad>
In 2005, <NAME> introduced the `Delay` monad to represent recursive
(thus potentially infinite) computations in a coinductive (and monadic) fashion
@capretta-delay. As described in @abel-nbe, the `Delay` type is used to
represent computations whose result may be available with some _delay_ or never
be returned at all: the `Delay` type has two constructors; one, `now`, contains
the result of the computation. The second, `later`, embodies one "step" of delay
and, of course, an infinite (coinductive) sequence of `later` indicates a
non-terminating computation, practically making non-termination an effect.
In Agda, the `Delay` type is defined as follows (using _sizes_ and
_levels_, see @subsubsection-sizes-coinduction[Subsection]):
#agdacode[
//typstfmt::off
```hs
data Delay {ℓ} (A : Set ℓ) (i : Size) : Set ℓ where
now : A → Delay A i
later : Thunk (Delay A) i → Delay A i
```
//typstfmt::on
]
Paired with the following `bind` function (`return`, or `unit`, is `now`).
#agdacode[
//typstfmt::off
```hs
bind : ∀ {i} → Delay A i → (A → Delay B i) → Delay B i
bind (now a) f = f a
bind (later d) f = later λ where .force → bind (d .force) f
```
//typstfmt::on
]
In words, what `bind` does, is this: given a `Delay A i` `x`, it checks whether
`x` contains an immediate result (i.e., `x ≡ now a`) and, if so, it applies the
function `f`; if, otherwise, `x` is a step of delay, (i.e., `x ≡ later d`),
`bind` delays the computation by wrapping the observation of `d` (represented
as ```hs d .force```) in the `later` constructor. This is the only
possibile definition: for example,
//typstfmt::off
```hs bind' (later d) f = bind' (d .force) f```
//typstfmt::on
would not pass the termination and productivity checker; in fact, take the
`never` term as shown in @code-never: of course,
//typstfmt::off
```hs bind' never f```
//typstfmt::on
would never terminate.
#agdacode(label: <code-never>)[
//typstfmt::off
```hs
never : ∀ {i} -> Delay A i
never = later λ where .force -> never
```
//typstfmt::on
]
We might however argue that `bind` as well never terminates, in fact `never`
_never yields a value_ by definition; this is correct, but the two views on
non-termination are radically different. The detail is that `bind'` observes the
whole of `never` immediately, while `bind` leaves to the observer the job of
actually inspecting what the result of `bind x f` _is_, and this is the utility
of the `Delay` datatype and its monadic features.
== Bisimilarity<subsection-monad-bisimilarity>
Consider the following snippet.
#mycode(
label: <code-comp-a>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/Examples.agda#L9",
)[
//typstfmt::off
```hs
comp-a : ∀ {i} -> Delay ℤ i
comp-a = now 0ℤ
```
//typstfmt::on
]
The term represents in @code-comp-a a computation converging to the value `0` immediately, as
no `later` appears in its definition.
#mycode(
label: <code-comp-b>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/Examples.agda#L12",
)[
//typstfmt::off
```hs
comp-b : ∀ {i} -> Delay ℤ i
comp-b = later λ where .force -> now 0ℤ
```
//typstfmt::on
]
The term above represent the same converging computation, albeit in a different
number of steps. There are situations in which we want to consider equal
computations that result in the same outcome, be it a concrete value (or
failure) or a diverging computation. We cannot use Agda's
propositional equality, as the two terms _are not the same_:
#mycode(
label: <code-comp-a-eq-comp-b>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/Examples.agda#L15",
)[
//typstfmt::off
```hs
comp-a≡comp-b : comp-a ≡ comp-b
comp-a≡comp-b = refl
-- ^ now 0ℤ != later (λ { .force → now 0ℤ }) of type Delay ℤ ∞
```
//typstfmt::on
]
We thus define an equivalence relation on `Delay` known as *weak
bisimilarity*. In words, weak bisimilarity relates two computations such that
either both diverge or both converge to the same value, independent of the
number of steps taken#footnote[ *Strong* bisimilarity, on the other hand,
requires both computation to converge to the same value in the same number of
steps; it is easy to show that strong bisimilarity implies weak bisimilarity.].
#definition(
name: "Weak bisimilarity",
label: <def-weak-bisimilarity>
)[
Let $a_1$ and $a_2$ be two terms of type $A$. Then, weak bisimilarity of terms
of type `Delay A` is defined by the following inference rules.
#align(
center,
tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
auto-hlines: false,
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$a_1 space eq.triple space a_2$])),
prooftrees.uni[$"now" space a_1 space tilde.triple space "now" space a_2$],
),
[$"now"$],
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$"force" x_1 space tilde.triple space "force" x_2$])),
prooftrees.couni[$"later" space x_1 space tilde.triple space "later" space x_2$],
),
[$"later"$],
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$"force" x_1 space tilde.triple space x_2$])),
prooftrees.uni[$"later" space x_1 space tilde.triple space x_2$],
),
[$"later"_l$],
prooftrees.tree(
prooftrees.axi(pad(bottom: 5pt, [$x_1 space tilde.triple space "force" x_2$])),
prooftrees.uni[$x_1 space tilde.triple "later" space x_2$],
),
[$"later"_r$],
),
)
]
The implementation in Agda of @def-weak-bisimilarity follows the rules above
but uses sizes to deal with coinductive definitions (see
@subsubsection-sizes-coinduction[Subsection]) and retraces the definition of _strong_
bisimilarity as implemented in Agda's standard library at the time of writing:
the difference with the rules shown in @def-weak-bisimilarity is that in the
latter the inference rules imply that propositional equality is the only kind
of relation allowed for two terms to be weakly bisimilar at the level of
non-delayed terms, while this definition allows terms of two potentially
different "end" types to be bisimilar as long as they are related by some
relation $R$.
#mycode(
label: <code-weak-bisim>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/WeakBisimilarity/Core.agda#L16",
)[
//typstfmt::off
```hs
data WeakBisim {a b r} {A : Set a} {B : Set b} (R : A -> B -> Set r) i :
(xs : Delay A ∞) (ys : Delay B ∞) -> Set (a ⊔ b ⊔ r) where
now : ∀ {x y} -> R x y -> WeakBisim R i (now x) (now y)
later : ∀ {xs ys} -> Thunk^R (WeakBisim R) i xs ys
-> WeakBisim R i (later xs) (later ys)
laterₗ : ∀ {xs ys} -> WeakBisim R i (force xs) ys
-> WeakBisim R i (later xs) ys
laterᵣ : ∀ {xs ys} -> WeakBisim R i xs (force ys)
-> WeakBisim R i xs (later ys)
```
//typstfmt::on
]
Propositional equality is still the most frequently used
relation, so we define a special notation for this specialization, which
resembles that of the inference rules:
#mycode(
label: <code-weak-bisim-propeq>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/WeakBisimilarity/Core.agda#L33",
)[
//typstfmt::off
```hs
infix 1 _⊢_≋_
_⊢_≋_ : ∀ i → Delay A ∞ → Delay A ∞ → Set ℓ
_⊢_≋_ = WeakBisim _≡_
```
//typstfmt::on
]
We also show that weak bisimilarity as we defined it is an equivalence
relation. When expressing this theorem in Agda, it is also necessary to make
the relation `R` we abstract over be an equivalence relation, as shown in
@thm-weak-bisimilarity-equivalence; as shown in
@danielsson-operational-semantics, the transitivity proof is not claimed to be
size preserving.
#theorem(
name: "Weak bisimilarity is an equivalence relation",
label: <thm-weak-bisimilarity-equivalence>
)[
#mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/WeakBisimilarity/Relation/Binary/Equivalence.agda",
proof: <proof-weak-bisimilarity-equivalence>,
)[
//typstfmt::off
```hs
reflexive : ∀ {i} (r-refl : Reflexive R) -> Reflexive (WeakBisim R i)
symmetric : ∀ {i} (r-sym : Sym P Q) -> Sym (WeakBisim P i) (WeakBisim Q i)
transitive : ∀ {i} (r-trans : Trans P Q R) -> Trans (WeakBisim P ∞) (WeakBisim Q ∞) (WeakBisim R i)
```
//typstfmt::on
]
]
@thm-delay-monad states that `Delay` is a monad up to weak bisimilarity.
#theorem(
name: [`Delay` is a monad],
label: <thm-delay-monad>
)[
The triple (`Delay`, `now`, `bind`) is a monad and respects monad laws up to
weak bisimilarity. In Agda:
#mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/Delay/Examples.agda#L19",
proof: <proof-delay-monad>,
)[
//typstfmt::off
```hs
left-identity : ∀ {i} (x : A) (f : A -> Delay B i) -> (now x) >>= f ≡ f x
right-identity : ∀ {i} (x : Delay A ∞) -> i ⊢ x >>= now ≋ x
associativity : ∀ {i} {x : Delay A ∞} {f : A -> Delay B ∞}
{g : B -> Delay C ∞} -> i ⊢ (x >>= f) >>= g ≋ x >>= λ y -> (f y >>= g)
```
//typstfmt::on
]]
== Convergence, divergence and failure<section-convergence>
Using the relation of weak bisimilarity, we want to define a characterization
of computations, which we will use later when expressing theorems regarding the
semantics of the language we will consider.
The `Delay` monads allows us to model the effect of non-termination, but, other
than modeling converging computations, we also want to model the behaviour of
computations that terminate but in a wrong way, which we name _failing_. We
model this effect with the aid of the `Maybe` monad, creating a new monad that
combines the two behaviours: we baptize this new monad `FailingDelay`.
This monad does not have a specific datatype (as it is the combination of two
existing monads), so we directly show the definition of `bind` in Agda
(@code-bind-fd).
#mycode(
label: <code-bind-fd>,
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/FailingDelay/Effectful.agda#L31",
)[
//typstfmt::off
```hs
bind : ∀ {i} (d : Delay {ℓ} (Maybe A) i) (f : (A -> Delay {ℓ′} (Maybe B) i))
-> Delay {ℓ′} (Maybe B) i
bind (now (just x)) f = f x
bind (now nothing) f = now nothing
bind (later x) f = later (λ where .force -> bind (x .force) f)
```
//typstfmt::on
]
Having a monad that deals with the three effects (if we consider convergence
one) we want to model, we now define types for these three states. The
first we consider is termination (or convergence); in words, we define a
computation to converge when there exists a term `v` such that the computation
is (weakly) bisimilar to it (see @def-converging-computation).
#definition(
name: "Converging computation",
label: <def-converging-computation>
)[
#mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/FailingDelay/Relation/Binary/Convergence.agda#L21",
)[
//typstfmt::off
```hs
_⇓_ : ∀ (x : Delay (Maybe A) ∞) (v : A) -> Set ℓ
x ⇓ v = ∞ ⊢ x ≋ (now (just v))
_⇓ : ∀ (x : Delay (Maybe A) ∞) -> Set ℓ
x ⇓ = ∃ λ v -> ∞ ⊢ x ≋ (now (just v))
```
//typstfmt::on
]]
We then define a computation to diverge when it is bisimilar to an infinite chain of
`later`, which we named `never` in @code-never (see
@def-diverging-computation).
#definition(
name: "Diverging computation",
label: <def-diverging-computation>
)[ #mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/FailingDelay/Relation/Binary/Convergence.agda#L30",
)[
//typstfmt::off
```hs
_⇑ : ∀ (x : Delay (Maybe A) ∞) -> Set ℓ
x ⇑ = ∞ ⊢ x ≋ never
```
//typstfmt::on
]]
The third and last possibility is for a computation to fail: such a computation
converges but to no value (see @def-failing-computation).
#definition(
name: "Failing computation",
label: <def-failing-computation>
)[ #mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/FailingDelay/Relation/Binary/Convergence.agda#L27",
)[
//typstfmt::off
```hs
_↯ : ∀ (x : Delay (Maybe A) ∞) -> Set ℓ
x ↯ = ∞ ⊢ x ≋ now nothing
```
//typstfmt::on
]]
We can already say that a computation, in the semantics we will define later,
will not show any other kind of behaviour, therefore @post-exec seems clearly
true; in a constructive environment like Agda we can, however, only postulate
it, as a proof would essentially be a solution to the halting problem.
#postulate(
label: <post-exec>
)[
#mycode(
"https://github.com/ecmma/co-thesis/blob/master/agda/lujon/Codata/Sized/FailingDelay/Relation/Binary/Convergence.agda#L83",
)[
//typstfmt::off
```hs
three-states : ∀ {a} {A : Set a} {x : Delay (Maybe A) ∞}
-> XOr (x ⇓) (XOr (x ⇑) (x ↯))
```
//typstfmt::off
]]
|
|
https://github.com/open-datakit/accs-finalreport-whitepaper | https://raw.githubusercontent.com/open-datakit/accs-finalreport-whitepaper/main/cover.typ | typst | #[
#set text(font:"Cerebri Sans", weight: 800, fill: rgb("#212d49"), size: 20pt)
opendata.fit
]
Mr. <NAME>
UNSW Sydney
Ms. <NAME>
UNSW Sydney
#link("mailto:<EMAIL>")
|
|
https://github.com/1STEP621/typst-anshere | https://raw.githubusercontent.com/1STEP621/typst-anshere/main/README.md | markdown | # anshere
試験の解答欄を作るためのtypst関数を提供します。
[answerbox.sty](https://hohei3108.hatenablog.com/entry/2022/01/27/005123)のtypst版っぽいものを作ろうとしました。
## 使い方
[example.typ](./example/example.typ)を参考にしてください。
|
|
https://github.com/chen-qingyu/Typst-Code | https://raw.githubusercontent.com/chen-qingyu/Typst-Code/master/limit%201.typ | typst | #let LF = {v(3em); linebreak()}
$
& lim_(x -> infinity) ((a x + b) / (a x + c))^(h x + k) space (a != 0)
LF
=& lim_(x -> infinity) e^((h x + k) ln((a x + b) / (a x + c)))
LF
=& lim_(x -> infinity) e^((h x + k) ln((a x + b + c - c) / (a x + c)))
LF
=& lim_(x -> infinity) e^((h x + k) ln(1 + (b - c) / (a x + c)))
LF
=& lim_(x -> infinity) e^((h x + k) (b - c) / (a x + c))
LF
=& lim_(x -> infinity) e^(((b - c)h x + (b - c)k)/(a x + c))
LF
=& e^(((b - c)h)/a)
LF
$
|
|
https://github.com/GYPpro/Java-coures-report | https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/6.typ | typst | #set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
= 较复杂的学生信息管理系统
\
#text("*") 实验项目类型:设计性\
#text("*")此表由学生按顺序填写\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 面向对象程序设计/JAVA语言 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" 较复杂的学生信息管理系统 ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 1 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2023年11月1日上午 ")]#text("~")#underline[#text(" 2023年11月1日中午 ")]\
]
#set heading(
numbering: "一、"
)
#set par( first-line-indent: 1.8em)
= 实验目的
\
#h(1.8em)熟练运用对象设计工具。
熟练掌握以下工具或性质:
\
#h(1.8em) #box[
+ 访问控制
+ 内部类
+ 接口
+ 继承
+ 多态
]
了解异常处理
= 实验环境
\
#h(1.8em)计算机:PC X64
操作系统:Windows
编程语言:Java
IDE:Visual Studio Code
在线测试平台:leetcode
= 程序原理
\
提供了四个类:
#figure(
table(
columns: 2,
[`course`],[课程],
[`score`],[成绩],
[`student`],[学生],
[`SchoolLib`],[管理系统]
)
)
其中SchoolLib为主类,提供了对学生以下操作:
#box[+ 添加学生并自动创建学号
+ 添加课程并自动生成课程编号
+ 学生选课
+ 记录考试成绩,补考成绩
+ 与平时分加权,计算总评成绩
+ 计算绩点
+ 以绩点、学号、姓名字典序等对学生排序
]
保证所有操作线程安全,必要的地方法进行了异常处理与保护性拷贝。
测试用例的控制台规则:
中括号内为需要填入字符串,尖括号为可选参数,默认为列表第一个。
#set align(left)
#align(left+horizon)[
#figure(table(
columns: 2,
align: left+horizon,
[#align(left)[```shell-unix-generic
addStu [student name]
```]],[添加学生],
[#align(left)[```shell-unix-generic
addCur [Course name] [teacher name] [credit]
```]],[添加课程],
[#align(left)[```shell-unix-generic
celCur [student UID] [Course name]
```]],[选课],
[#align(left)[```shell-unix-generic
showStu <sort with:"UID" | "name" | "point">
```]],[显示学生列表],
[#align(left)[```shell-unix-generic
showCur <sort with:"UID" | "Course name" | " teacher name">
```]],[显示课程列表],
[#align(left)[```shell-unix-generic
addScore [student UID] [Course name] [Normally score] [Exam score]
```]],[添加成绩],
[#align(left)[```shell-unix-generic
addResc [student UID] [Course name] [Exam score]
```]],[添加补考成绩],
[#align(left)[```shell-unix-generic
cacu
```]],[计算总评成绩与绩点]
))
]
= 程序代码
文件`sis5\coures.java`实现了`coures`类
```java
package sis5;
import java.util.Comparator;
public class course {//课程
private String UID;//课程编号
private String name;//课程名称
private String teacher;//教师名称
private int credit;//学分
@Override public boolean equals(Object b)
{
if(!(b instanceof course)) return false;
course ts = (course)b;
if(ts.getUID().equals(this.UID)) return true;
else return false;
}
@Override public int hashCode()
{
return UID.hashCode();
}
@Override public String toString()
{
return UID + " " + name + " " + teacher + " " + credit;
}
public static class sortWithUID implements Comparator<course>
{
@Override public int compare(course o1, course o2)
{
return o1.UID.compareTo(o2.UID);
}
}
public static class sortWithName implements Comparator<course>
{
@Override public int compare(course o1, course o2)
{
return o1.name.compareTo(o2.name);
}
}
public static class sortWithCredit implements Comparator<course>
{
@Override public int compare(course o1, course o2)
{
if(o1.credit > o2.credit) return 1;
else if(o1.credit < o2.credit) return -1;
else return 0;
}
}
course(String _uuid,final String _name,final String _teacher,final int _credit)
{
UID = _uuid;
name = _name;
teacher = _teacher;
credit = _credit;
}
course(course _course)//深拷贝构造
{
this.UID = _course.getUID();
this.name = _course.getName();
this.teacher = _course.getTeacher();
this.credit = _course.getCredit();
}
public String getUID()
{
return UID;
}
public String getName()
{
return name;
}
public String getTeacher()
{
return teacher;
}
public int getCredit()
{
return credit;
}
}
```
文件`sis5\Student.java`实现了`Student`类
```java
package sis5;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Student{
private String UID;//学号
private String name;//姓名
private Set<course> curriculumList;//所选课程列表
private HashMap<course,score> scoreList;//成绩单
private double avgGPA = 0;//平均绩点
private int credit = 0;//已修学分
private void cacuGPA() //计算平均绩点
{
double sum = 0;
for(course cs : curriculumList)
{
sum += scoreList.get(cs).getGPA();
}
avgGPA = sum / curriculumList.size();
}
@Override public boolean equals(Object b)
{
if(!(b instanceof Student)) return false;
Student ts = (Student)b;
if(ts.getUID().equals(this.UID)) return true;
else return false;
}
@Override public int hashCode()
{
return UID.hashCode();
}
@Override public String toString()
{
return UID + " " + name + " " + avgGPA + " " + credit;
}
public static class sortWithGPA implements Comparator<Student>
{
@Override public int compare(Student o1, Student o2)
{
if(o1.avgGPA < o2.avgGPA) return 1;
else if(o1.avgGPA > o2.avgGPA) return -1;
else return 0;
}
}
public static class sortWithUID implements Comparator<Student>
{
@Override public int compare(Student o1, Student o2)
{
return o1.UID.compareTo(o2.UID);
}
}
public static class sortWithName implements Comparator<Student>
{
@Override public int compare(Student o1, Student o2)
{
return o1.name.compareTo(o2.name);
}
}
Student(String _uid,String _name)
{
UID = new String(_uid);
name = new String(_name);
curriculumList = new HashSet<course>();
scoreList = new HashMap<course,score>();
}
Student(Student _student) //深拷贝构造
{
this.UID = _student.getUID();
this.name = _student.getName();
this.scoreList = new HashMap<course,score>(_student.scoreList);
this.avgGPA = _student.avgGPA;
this.credit = _student.credit;
curriculumList = new HashSet<course>();
for(course cs : _student.curriculumList)
{
this.curriculumList.add(new course(cs));
}
}
public void addCourse(course _cs) //选课
{
curriculumList.add(_cs);
credit += _cs.getCredit();
}
public void ranking(course _cs,score rank) throws Exception //首次录入成绩
{
if(scoreList.containsKey(_cs)) throw new Exception("重复录入成绩\n");
else scoreList.put(_cs,rank);
}
public void reRanking(course _cs,score rank) throws Exception //补考
{
if(!scoreList.containsKey(_cs)) throw new Exception("未找到对应成绩\n");
else scoreList.replace(_cs, rank);
}
public String getUID()
{
return new String(UID);
}
public String getName()
{
String rt = new String(name);
return rt;
}
public double getAvgGPA()
{
cacuGPA();
return avgGPA;
}
public score getScore(course _cs) throws Exception
{
if(!scoreList.containsKey(_cs)) throw new Exception("未找到对应成绩\n");
else return new score(scoreList.get(_cs));
}
}
```
文件`sis5\score.java`实现了`score`类
```java
package sis5;
public class score {
private Integer normallyScore;//平时成绩
private Integer examScore;//期末成绩
private Integer finalScore;//总评成绩
private double GPA;//绩点
private boolean ifReExam;//是否补考
Integer NORMALLY_WEIGHT;//平时成绩权重
Integer EXAM_WEIGHT;//期末成绩权重
Integer TOTAL_WEIGHT;//总评成绩权重
@Override public boolean equals(Object b)
{
if(!(b instanceof score)) return false;
score ts = (score)b;
if(ts.getFinalScore() == this.finalScore) return true;
else return false;
}
@Override public int hashCode()
{
return finalScore;
}
private void cacuGPA() //根据暨大标准计算GPA
{
if(finalScore > 90) GPA = 4+(finalScore-90)/10.0;
else if(finalScore > 80) GPA = 3+(finalScore-80)/10.0;
else if(finalScore > 70) GPA = 2+(finalScore-70)/10.0;
else if(finalScore > 60) GPA = 1+(finalScore-60)/10.0;
else GPA = 0;
if(ifReExam) GPA = Math.min(GPA, 1.6);
}
private void cacuFinalScore() //计算分配权重后的总评成绩
{
finalScore = (int)(normallyScore.intValue() * ((double)NORMALLY_WEIGHT/(double)TOTAL_WEIGHT) + examScore.intValue() * ((double)EXAM_WEIGHT/(double)TOTAL_WEIGHT));
}
public score(Integer _normallyScore,Integer _examScore)
{
ifReExam = false;
NORMALLY_WEIGHT = 3;
EXAM_WEIGHT = 7;
TOTAL_WEIGHT = NORMALLY_WEIGHT + EXAM_WEIGHT;
normallyScore = _normallyScore;
examScore = _examScore;
cacuFinalScore();
cacuGPA();
}
public score(Integer _normallyScore,Integer _examScore,Integer _normallyWeight,Integer _examWeight)
{
ifReExam = false;
NORMALLY_WEIGHT = _normallyWeight;
EXAM_WEIGHT = _examWeight;
TOTAL_WEIGHT = NORMALLY_WEIGHT + EXAM_WEIGHT;
normallyScore = _normallyScore;
examScore = _examScore;
cacuFinalScore();
cacuGPA();
}
public score(score sc) throws Exception //深拷贝构造
{
this.normallyScore = sc.getNormallyScore();
this.examScore = sc.getExamScore();
this.finalScore = sc.getFinalScore();
this.GPA = sc.getGPA();
this.ifReExam = sc.ifReExam;
this.NORMALLY_WEIGHT = sc.NORMALLY_WEIGHT;
this.EXAM_WEIGHT = sc.EXAM_WEIGHT;
this.TOTAL_WEIGHT = sc.TOTAL_WEIGHT;
}
public void resetWeight(Integer _normallyWeight,Integer _examWeight) //重设分数分配权重
{
NORMALLY_WEIGHT = _normallyWeight;
EXAM_WEIGHT = _examWeight;
TOTAL_WEIGHT = NORMALLY_WEIGHT + EXAM_WEIGHT;
cacuFinalScore();
cacuGPA();
}
public void resetNormallyScore(Integer _normallyScore) //重设平时成绩
{
normallyScore = _normallyScore;
cacuFinalScore();
cacuGPA();
}
public void resetExamScore(Integer _examScore) throws Exception //补考
{
if(ifReExam) throw new Exception("重复补考\n");
if(finalScore >= 60) throw new Exception("非法补考\n");
ifReExam = true;
examScore = _examScore;
cacuFinalScore();
cacuGPA();
}
public Integer getNormallyScore()
{
return Integer.valueOf(normallyScore);
}
public Integer getExamScore()
{
return Integer.valueOf(examScore);
}
public Integer getFinalScore()
{
return Integer.valueOf(finalScore);
}
public double getGPA()
{
return GPA;
}
}
```
文件`sis5\SchoolLib.java`实现了`SchoolLib`类
```java
package sis5;
import java.util.ArrayList;
import java.util.HashMap;
import sis2.UIDmanager;
public class SchoolLib {
private HashMap<String,Student> studentList;
private HashMap<String,course> courseList;
final UIDmanager uidm = new UIDmanager();
private enum sortStuWith
{
UID,
name,
GPA
}
private enum sortCurWith
{
UID,
name,
credit
}
public SchoolLib()
{
studentList = new HashMap<String,Student>();
courseList = new HashMap<String,course>();
}
public SchoolLib(final SchoolLib _scl) //深拷贝构造
{
studentList = new HashMap<String,Student>(_scl.studentList);
courseList = new HashMap<String,course>(_scl.courseList);
}
private void addStudent(final Student student)
{
studentList.put(student.getUID(),new Student(student));
}
private void addCourse(final course cs)
{
courseList.put(cs.getName(),new course(cs));
}
private void celCur(final String stuUID,final String csName) throws Exception
{
if(!studentList.containsKey(stuUID)) throw new Exception("未找到对应学生\n");
if(!courseList.containsKey(csName)) throw new Exception("未找到对应课程\n");
Student stu = studentList.get(stuUID);
course cs = courseList.get(csName);
stu.addCourse(cs);
}
private ArrayList<Student> sortLocalStuList(final sortStuWith sw)
{
ArrayList<Student> tmp = new ArrayList<Student>();
for(Student stu : studentList.values())
{
tmp.add(new Student(stu));
}
if(sw == sortStuWith.UID)
{
tmp.sort(new Student.sortWithUID());
}
else if(sw == sortStuWith.name)
{
tmp.sort(new Student.sortWithName());
}
else if(sw == sortStuWith.GPA)
{
tmp.sort(new Student.sortWithGPA());
}
return tmp;
}
private ArrayList<course> sortLocalCurList(final sortCurWith sw)
{
ArrayList<course> tmp = new ArrayList<course>();
for(course cs : courseList.values())
{
tmp.add(new course(cs));
}
if(sw == sortCurWith.UID)
{
tmp.sort(new course.sortWithUID());
}
else if(sw == sortCurWith.name)
{
tmp.sort(new course.sortWithName());
}
else if(sw == sortCurWith.credit)
{
tmp.sort(new course.sortWithCredit());
}
return tmp;
}
public String parseCommand(final String cmd) throws Exception//解析命令
{
String[] cmdList = cmd.split(" ");
if(cmdList[0].equals("addStu"))
{
if(cmdList.length != 2) throw new Exception("命令格式错误\n");
String name = cmdList[1];
String uid = uidm.nextDate();
Student stu = new Student(uid,name);
uidm.bindUID(uid, stu);
addStudent(stu);
return "添加学生成功,UID为" + uid + "\n";
}
else if(cmdList[0].equals("addCur"))
{
if(cmdList.length != 4) throw new Exception("命令格式错误\n");
String name = cmdList[1];
String teacher = cmdList[2];
int credit = Integer.parseInt(cmdList[3]);
course cs = new course(uidm.nextSeq(),name,teacher,credit);
uidm.bindUID(cs.getUID(), cs);
addCourse(cs);
return "添加课程成功,UID为" + cs.getUID() + "\n";
}
else if(cmdList[0].equals("celCur"))
{
if(cmdList.length != 3) throw new Exception("命令格式错误\n");
String stuUID = cmdList[1];
String csName = cmdList[2];
celCur(stuUID,csName);
return "选课成功\n";
}
else if(cmdList[0].equals("showStu"))
{
if(cmdList.length != 2) throw new Exception("命令格式错误\n");
String sortWith = cmdList[1];
ArrayList<Student> tmp = sortLocalStuList(sortStuWith.valueOf(sortWith));
StringBuilder sb = new StringBuilder();
for(Student stu : tmp)
{
sb.append(stu.toString());
sb.append("\n");
}
return sb.toString();
}
else if(cmdList[0].equals("showCur"))
{
if(cmdList.length != 2) throw new Exception("命令格式错误\n");
String sortWith = cmdList[1];
ArrayList<course> tmp = sortLocalCurList(sortCurWith.valueOf(sortWith));
StringBuilder sb = new StringBuilder();
for(course cs : tmp)
{
sb.append(cs.toString());
sb.append("\n");
}
return sb.toString();
}
else if(cmdList[0].equals("addScore"))
{
if(cmdList.length != 5) throw new Exception("命令格式错误\n");
String stuUID = cmdList[1];
String csName = cmdList[2];
int normallyScore = Integer.parseInt(cmdList[3]);
int examScore = Integer.parseInt(cmdList[4]);
if(!studentList.containsKey(stuUID)) throw new Exception("未找到对应学生\n");
if(!courseList.containsKey(csName)) throw new Exception("未找到对应课程\n");
Student stu = studentList.get(stuUID);
course cs = courseList.get(csName);
stu.ranking(cs, new score(normallyScore,examScore));
return "添加成绩成功\n";
}
else if(cmdList[0].equals("addResc"))
{
if(cmdList.length != 4) throw new Exception("命令格式错误\n");
String stuUID = cmdList[1];
String csName = cmdList[2];
int examScore = Integer.parseInt(cmdList[3]);
if(!studentList.containsKey(stuUID)) throw new Exception("未找到对应学生\n");
if(!courseList.containsKey(csName)) throw new Exception("未找到对应课程\n");
Student stu = studentList.get(stuUID);
course cs = courseList.get(csName);
score tmp = stu.getScore(cs);
tmp.resetExamScore(examScore);
stu.reRanking(cs, tmp);
return "重设补考成绩成功\n";
}
else if(cmdList[0].equals("cacu"))
{
for(Student stu : studentList.values())
{
stu.getAvgGPA();
}
return "计算完成\n";
}
else throw new Exception("未知命令\n");
}
}
```
文件`sis5\Test`实现了主函数入口与输入输出
```java
package sis5;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
SchoolLib lib = new SchoolLib();
for(;;)
{
String s = sc.nextLine();
try {
System.out.print(lib.parseCommand(s));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
```
= 出现的问题、原因与解决方法
\
#h(1.8em)编码过程中选择命令解析方式时,初始思路为在`Test`类中直接实现,但是会导致抛出异常后程序直接结束,且不易灵活判定指令输入的内容是否正确,因此最终实现时,选择在类中实现一个解析命令的方法`parseCommand`,传入一行指令,返回程序输出,可以使得封装更加完备,类的使用更加方便。同时,在完备的异常处理下,此结构可以保证程序遇到指令错误时仍然可以跳过此条指令并继续执行。
在具体实现排序学生列表功能时,考虑到匿名函数的复用性较差,因此选择在内部类`sortWith...`中实现接口`Comparator<>`实现各种排序方法的灵活选择。调用时只需要`sort(new course.sortWith...())`即可。
同时,在决定排序方式时,避免使用了复杂的分支判断,而选择使用`enum Sort...With`的枚举类型,提高代码复用性、可读性与鲁棒性,且更方便地进行异常处理。
= 测试数据与运行结果
#figure(
table(
align: left + horizon,
columns: 3,
[*输入*],[*输出*],[*解释*],
[`addStu GYP
addStu XSX
addStu CXK
addStu ZY`],[`添加学生成功,UID为2312150001
添加学生成功,UID为2312150002
添加学生成功,UID为2312150003
添加学生成功,UID为2312150004`],[添加学生],
[`addCur java GXC 4
addCur cpp FZZ 3
addCur py LCC 2`],[`添加课程成功,UID为0000000001
添加课程成功,UID为0000000002
添加课程成功,UID为0000000003`],[添加课程],
[`celCur 2312150001 java
celCur 2312150001 cpp
celCur 2312150002 py
celCur 2312150002 java
celCur 2312150003 cpp
celCur 2312150003 py
celCur 2312150003 game
celCur 2312150004 java`],[`选课成功
选课成功
选课成功
选课成功
选课成功
选课成功
未找到对应课程
选课成功`],[学生选课\ 由于没有\ game课程\ 因此报错\ 不影响\ 继续运行],
[`addScore 2312150001 java 90 90
addScore 2312150001 cpp 80 80
addScore 2312150001 py 70 70
addScore 2312150002 java 60 60
addScore 2312150002 py 50 50
addScore 2312150003 cpp 93 34
addScore 2312150003 py 77 88
addScore 2312150003 game 100 100
addScore 2312150004 java 100 100
`],[`添加成绩成功
添加成绩成功
添加成绩成功
添加成绩成功
添加成绩成功
添加成绩成功
添加成绩成功
未找到对应课程
添加成绩成功`],[添加学生\ 平时成绩与\ 期末成绩\ 由于没有\ game课程\ 因此报错\ 不影响\ 继续运行],
[`cacu`],[`计算完成`],[],
[`shouStu GPA
showStu GPA`],[`未知命令
2312150004 ZY 5.0 4
2312150001 GYP 3.5 7
2312150003 CXK 1.7 5
2312150002 XSX 0.0 6`],[计算并\ 排序,显示\ 学生的GPA],
[],[],[续表]
))
#figure(
table(
align: left + horizon,
columns: 3,
[*输入*],[*输出*],[*解释*],
[`addResc 2312150002 py 99
addResc 2312150003 cpp 99
addResc 2312150003 py 99`],[`重设补考成绩成功
重设补考成绩成功
非法补考`],[总评60 以下的\ 可以补考],
[`cacu
showStu GPA`],[`计算完成
2312150004 ZY 5.0 4
2312150001 GYP 3.5 7
2312150003 CXK 2.5 5
2312150002 XSX 0.8 6`],[补考后重新计算GPA],
[`showStu name`],[`2312150003 CXK 2.5 5
2312150001 GYP 3.5 7
2312150002 XSX 0.8 6
2312150004 ZY 5.0 4`],[按姓名排序]
)
)
|
|
https://github.com/SeniorMars/tree-sitter-typst | https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/compiler/let.typ | typst | MIT License | // Test let bindings.
---
// Automatically initialized with none.
#let x
#test(x, none)
// Manually initialized with one.
#let z = 1
#test(z, 1)
// Syntax sugar for function definitions.
#let fill = conifer
#let f(body) = rect(width: 2cm, fill: fill, inset: 5pt, body)
#f[Hi!]
---
// Termination.
// Terminated by line break.
#let v1 = 1
One
// Terminated by semicolon.
#let v2 = 2; Two
// Terminated by semicolon and line break.
#let v3 = 3;
Three
#test(v1, 1)
#test(v2, 2)
#test(v3, 3)
---
// Error: 5 expected identifier
#let
// Error: 6 expected identifier
#{let}
// Error: 5 expected identifier
// Error: 5 expected semicolon or line break
#let "v"
// Error: 7 expected semicolon or line break
#let v 1
// Error: 9 expected expression
#let v =
// Error: 5 expected identifier
// Error: 5 expected semicolon or line break
#let "v" = 1
// Terminated because expression ends.
// Error: 12 expected semicolon or line break
#let v4 = 4 Four
// Terminated by semicolon even though we are in a paren group.
// Error: 18 expected expression
// Error: 18 expected closing paren
#let v5 = (1, 2 + ; Five
---
// Error: 13 expected equals sign
#let func(x)
// Error: 15 expected expression
#let func(x) =
|
https://github.com/soul667/typst | https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/progress/sections.md | markdown | ---
sidebar_position: 2
---
# Touying 的 Sections
Touying 维护了一份自己的 sections state,用于记录 slides 的 sections 和 subsections。
## touying-outline
`#touying-outline(enum-args: (:), padding: 0pt)` 用于显示一个简单的大纲。
## touying-final-sections
`#states.touying-final-sections(final-sections => ..)` 用于自定义显示大纲。
## touying-progress-with-sections
```typst
#states.touying-progress-with-sections((current-sections: .., final-sections: .., current-slide-number: .., last-slide-number: ..) => ..)
```
功能最强大,你可以用其搭建任意复杂的进度展示。
|
|
https://github.com/crd2333/Astro_typst_notebook | https://raw.githubusercontent.com/crd2333/Astro_typst_notebook/main/README.md | markdown | # Astro-typst Notebook
一个基于 [astro-typst](https://github.com/OverflowCat/astro-typst/tree/master) 的网页笔记本,支持 md 和 typ 两种格式
- Typst 原有的一些功能得到 astro-typst 的支持
- [x] Import packages in Typst Universe
- [x] import / include / read files or resources
- [x] Use system fonts
- [x] Selectable, clickable text layer
- [x] Set scale
- [x] Static SVGs without JavaScript
- [ ] Responsive SVGs
- [ ] Add font files or blobs
没有使用 Astro 原有的 content 内容集合(~~其实是不会~~)和 pages 内自动静态路由(也就是能够兼容)
实现方式非常丑陋且笨拙,不会前端且不熟悉 Astro,孩子不懂事做着玩的(x
- 例子

- 使用方法为直接在 `src/docs` 下添加文件,例如
```
src/docs
├── note.typ // first level must have note.md/typ
├── here
│ ├── index.typ // second level must have index.md/typ
│ ├── test
│ │ ├── 基本测试.typ
│ │ └── 第三方包.typ
│ └── to2
│ ├── 1.md
│ └──2.typ
├── sect2
│ ├── index.md
│ ├── topic1
│ │ └── 1.md
│ └── topic2
│ └── 1.typ
├── sect3
│ ├── index.typ
│ └── no_files_so_no_this
└── sect4
└── no_index_so_no_this
```
|
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/types/boolean/test.typ | typst | Other | #import "/src/lib.typ" as z
#import "/tests/utility.typ": *
#show: show-rule.with();
#let schema = z.boolean()
= types/boolean
== Input types
#{
let input-types = (
"boolean (true)": true,
"boolean (false)": false,
)
for (name, value) in input-types {
utility-expect-eq(
test: value,
schema: schema,
truth: value,
)([It should validate #name])
}
}
#{
let input-types = (
"none": none,
"number (0)": 0,
)
for (name, value) in input-types {
utility-expect-eq(
test: value,
schema: schema,
truth: none,
)([It should fail #name])
}
}
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/utils/math.typ | typst | #let def(
body,
supplement: "Опр.",
) = context {
let sup = text(weight: "bold", supplement)
let sup_wid = measure(sup).width
par(hanging-indent: sup_wid)[#sup #body]
}
#let defitem(body) = {
[#strong(body)<defitem>]
}
// TODO: defenitions list
#let blk(
title: none,
body,
) = context {
let has_title = if type(title) == str or type(title) == content {
true
} else if title == none {
false
} else {
panic("title must be content or string, not " + type(title))
}
let stroke = black + 0.5pt
let padding = 10pt
let title_padding = 5pt
let title_blk = block(
inset: title_padding,
radius: title_padding,
stroke: stroke,
fill: white,
strong(title),
)
let title_hei = measure(title_blk).height
if has_title {
v(5pt)
}
block(
inset: padding,
radius: padding,
stroke: stroke,
width: 100%,
{
if has_title {
place(
top + left,
dy: -title_hei / 2 - padding,
dx: -2 * padding,
title_blk,
)
v(5pt)
}
body
}
)
}
#let proof(
supplement: "Док-во",
body
) = {
blk(title: "Док-во", body)
}
|
|
https://github.com/binhtran432k/ungrammar-docs | https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/tailwindcss.typ | typst | #import "/components/glossary.typ": gls
== Tailwind CSS <sec-tailwindcss>
Tailwind CSS is a revolutionary #gls("css") framework that has gained immense
popularity due to its utility-first approach and focus on rapid development.
This section will explore the key features, benefits, and challenges of using
Tailwind CSS in your web projects.
Tailwind CSS is a powerful and versatile #gls("css") framework that can
significantly improve your web development workflow. Its utility-first
approach, customization options, and focus on accessibility make it a popular
choice for developers of all levels. By carefully considering the benefits and
challenges, you can determine if Tailwind CSS is the right fit for your
project @bib-tailwindcss.
=== Key Features of Tailwind CSS
- *Utility-First Approach*: Tailwind CSS provides a collection of low-level
utility classes that can be combined to create custom styles. This approach
eliminates the need for writing traditional #gls("css") rules, streamlining
the development process.
- *Customization*: Tailwind CSS allows you to customize the default styles and
generate a custom stylesheet tailored to your project's specific needs.
- *Responsiveness*: Tailwind CSS includes built-in responsive design utilities,
making it easy to create responsive layouts for different screen sizes.
- *Dark Mode Support*: Tailwind CSS provides built-in support for dark mode,
enabling you to create visually appealing interfaces for users who prefer
darker themes.
- *Plugins*: Tailwind CSS supports a growing ecosystem of plugins that extend
its functionality and provide additional features.
=== Benefits of Using Tailwind CSS
- *Rapid Development*: Tailwind CSS's utility-first approach can significantly
speed up the development process by reducing the amount of #gls("css") you
need to write.
- *Consistency*: Tailwind CSS helps ensure a consistent look and feel across
your entire application.
- *Customization*: Tailwind CSS's customization options allow you to create
unique and branded designs.
- *Accessibility*: Tailwind CSS is designed with accessibility in mind, making
it easier to create inclusive web applications.
- *Community and Ecosystem*: Tailwind CSS has a large and active community,
providing a wealth of resources, documentation, and support.
|
|
https://github.com/yhtq/Notes | https://raw.githubusercontent.com/yhtq/Notes/main/软件分析/main.typ | typst | #import "../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark
#import "../template.typ": *
#show: note.with(
title: "软件分析",
author: "YHTQ",
date: datetime.today().display(),
logo: none,
withChapterNewPage: true
)
#let sup = math.union.sq
= 前言
== 基本概念
给定软件系统,回答关于系统行为有关问题的技术称为软件分析技术。能否彻底避免软件中出现特定类型(例如内存泄漏)的缺陷?逻辑上而言这是不可能的,既然编程语言中总有无法证明的表达式 $T$,则以下程序:
```c
a = malloc(10);
if (T) free(a);
return
```
显然程序有内存泄漏当且仅当 $T$ 不是永真式。仿照停机问题,也可以构造:
```c
void Evil() {
int a = malloc();
if (LeakFree(Evil)) return;
else free(a); return;
}
```
称存在算法判定的问题为可判定问题,否则称为不可判定问题。
#theorem[Rice][
假设将任意程序看成输入到输出的函数,则关于这个函数的任何非平凡属性都不可判定。其中平凡属性指对所有程序都成立或都不成立的属性(命题)。
]
#proof[
给定非平凡性质 $P$,不妨假设空集(无输出,包括不停机的程序)不满足 $P, "ok_prog"$ 满足性质 $P$,并假设检测该性质的算法为 $"P_holds"$,如下程序:
```c
Bool Halt(program q){
void evil(Input n){
Output v = ok_prog(n);
q();
return v;
}
return P_holds(evil);
}
```
是一个判定停机问题的程序,这是荒谬的。
]
#remark[][
- Rice's theorem 中将程序抽象成函数,涉及程序结构的问题并不在讨论范围内,例如说程序中使用变量是否超过 50 个,这不是程序对应函数的性质。
- 上述的讨论均针对抽象的u图灵机或者无限的自动机,然而真实计算机内存是有限的,事实上现实计算机只是有限状态机,其停机性是可判定的。这个技术称为模型检查,在硬件领域被广泛应用,但在软件领域因为状态数过多无法应用。
]
现实中的软件分析往往采用工程式的思想,虽然不能给出完全正确的算法,但可以设计一些“近似”算法,允许它检查出一些程序,不能检查出另外的程序。
- 只判定“是”或者“不知道”的近似称为下近似/must analysis,例如问题是程序是否有某种 Bug,则测试是一种 must analysis
- 只判定“否”或者“不知道”的近似称为上近似/may analysis
对于非判定问题,同样也可以有下近似或者上近似,例如返回目标集合的超集或者子集。
另外,我们还有一些逻辑用语:
- 正确性:Soundness,指逻辑系统的推导规则是正确的,即如果前提为真,则结论也为真,类似于 Must 分析
- 完备性:Completeness,指逻辑系统的推导规则是完备的,即如果结论为真,则可以被推导出来,类似于 May 分析
#remark[][
程序分析早期源于编译器优化,在优化领域 Soundness 往往指编译器的改写是正确的(也叫 Safety),此时具体而言可能是 Must 分析和 May 分析的其中一个。
]
本门课程涉及的技术本质来说可以分为抽象和搜索。
== 抽象
给定表达式语言:
#let pterm = ``` term {x > 0}```
#let nterm = ``` term {x < 0}```
#let zterm = ``` term {x = 0}```
#let term = ``` term```
```haskell
term := term + term
| term * term
| term - term
| integer
| variable
```
若 $a, b, c >= 0$,希望得到 $a + b * c >= 0$,一般而言我们会设置:
- 抽象域:将所有输出分成几类,例如 #pterm, #nterm, #zterm, #term
- 计算规则,例如:
- #pterm $+$ #pterm = #pterm
- #pterm $*$ #pterm = #pterm
- ......
运用规则对抽象域进行运算即可。
更广泛的,抽象技术被广泛用于程序分析的过程分析。
== 搜索
判断以下程序是否发生内存泄漏:
```c
if (a == b && c == d && a != b) x = malloc();
return;
```
为了判断程序是否内存泄漏,理论上我们就是要搜索输入空间,判断是否存在输入使得程序发生内存泄漏。当然实践上通常引入各种剪枝和推断等方法。具体而言,表达式 ```c a == b && c == d && a != b``` 只是三个布尔变量的和,我们可以先枚举所有布尔值,再去判断是否存在输入恰好满足对应的布尔值。
一般而言,抽象给出的是所有执行情况的不精确分析,搜索考虑一部分执行的精确分析。两者往往结合使用,例如抽象出程序的执行情况,再搜索其中的一部分情况。
== 程序语言基础知识
- 语法(syntax):程序的静态书写方式
- 语义(semantic):程序的动态执行行为
#definition[文法][
文法是一个四元组 $(N, T, P, S)$,其中 $N$ 是非终结符集合,$T$ 是终结符集合,$P$ 是产生式集合,$S in N$ 是开始符号。
例如,取 $N = {S, A}, T = {a, b}, P = {S -> a A b, a A -> a a A b, A -> epsilon}$,则通过变化:
$
S &=> a A b\
&=> a a A b b\
&=> a a a A b b b\
&=> a a a b b b
$
可以得到一个终结符号串。所有这样的终结符号串的集合称为文法 $G$ 生成的语言。
文法可以分成以下几类:
- 正则文法:只有一种产生式形式 $A -> a B$ 或者 $A -> a$ 或者 $S -> epsilon$
- 上下文无关文法:产生式左边只有单个非终结符,例如 $A -> a B$
- 上下文有关文法:允许书写 $alpha A beta -> alpha gamma beta$,但不允许上下文 $alpha, beta$ 改变
- 任意文法,等价于图灵机
]
#remark[][
习惯上,现代程序语言使用正则语言将字符串解析成 token,再将 token 作为终结符采用上下文无关文法描述整个语言。对于更复杂的文法,目前还没有高效的解析算法,也并不常用。
]
对于语义,我们往往采取以下几种:
- 操作语义:将程序元素解释为计算步骤
- 指称语义:解释为数学中严格定义的符号
- 公理语义:严格写出前条件,后条件,使用霍尔逻辑推导
某种意义上,程序分析就是输入程序语法,返回程序语义的问题。通常程序分析涉及的层面是:
- 抽象语法树:表示程序的抽象语法结构
- 三地址码:将复杂程序简化到每个语句只有一个运算,控制语句全部简化成 goto 的中间代码
- 控制流图:(一般在三地址码的基础上),程序的执行构成一个图。控制流指语句执行的顺序,控制流图的节点表示一个不含跳转的单元,边表示跳转关系。
#example[IMP][
定义非常简单的命令式语言 IMP:
```haskell
data UnitCommand = SkipU
| AssignU string exp
| IfThenElseU exp
| IfEnd
| WhileU exp
| WhileEnd
data Command = Skip
| Assign string exp
| Seq Command Command
| IfThenElse exp Command Command
| While exp Command
```
以及图结构:
```haskell
newtype Node = Node UnitCommand
data Graph v = {
nodes :: Map Int v,
edges :: List (Int, Int),
start_node :: Int,
end_node :: Int
}
data GraphR = PlainGraph (Graph Node) | ComponentGraph (Graph GraphR) -- 递归的图类型
graphNode :: Node -> GraphR
graphNode n = PlainGraph $ Graph {
nodes = Map.fromList [(0, n)],
edges = [],
start_node = 0,
end_node = 0
}
```
]
#algorithm[][
在上面的例子中,可以给出到控制流图的翻译:
```haskell
toCFG :: Command -> GraphR
toCFG Skip = graphNode (Node SkipU)
toCFG (Assign s e) = graphNode (Node (AssignU s e))
toCFG (Seq c1 c2) =
let g1 = toCFG c1
g2 = toCFG c2
in GraphR (ComponentGraph (Graph {
nodes = Map.fromList [(1, g1), (2, g2)],
edges = [(1, 2)],
start_node = 1,
end_node = 2
}))
toCFG (IfThenElse e c1 c2) =
let g1 = toCFG c1
g2 = toCFG c2
gIF = graphNode (Node IfThenElseU e)
gEnd = graphNode (Node IfEnd)
in GraphR (ComponentGraph (Graph {
nodes = Map.fromList [(1, gIF), (2, g1), (3, g2), (4, gEnd)],
edges = [(1, 2), (1, 3), (2, 4), (3, 4)],
start_node = 1,
end_node = 4
}))
toCFG (While e c) =
let gWhile = graphNode (Node WhileU e)
in GraphR (ComponentGraph (Graph {
nodes = Map.fromList [(1, gWhile), (2, toCFG c), (3, graphNode (Node WhileEnd))],
edges = [(1, 2), (2, 1), (2, 3)],
start_node = 1,
end_node = 3
}))
```
]
#algorithm[三地址码的控制流图][
对于三地址码,没有结构化的 if-else 和 while,需要详细分析 goto 的目标
+ 首先,基本块就是每两个 goto 语句之间的代码块
+ 然后,基本块之间的跳转关系就是 goto 语句的目标
]
= 基于抽象解释的程序分析
== 数据流分析
=== 基本数据流分析
#definition[][
记 $A$ 为抽象域的集合,$X$ 为真实值的集合,记:
- $Gamma : A -> P(X)$ 将抽象域映射到真实值的集合
- $alpha : X -> A$ 将具体值映射到抽象域,需要满足 $alpha(Gamma(a)) = {a}$
]
所谓的数据流分析,就是要在带有条件,循环等控制流的程序中,处理类似前言中表达式正负的问题。数据流分析的常见手法是:
- 将全局状态(变量到值的映射)转换成抽象状态(变量到抽象值的映射)
- 为每个程序语句设计抽象状态函数,实时改变抽象状态
#algorithm[抽象状态计算][
- 对于一般的顺序语句,抽象状态函数是显然的
- 对于条件语句,抽象状态函数是两个分支的抽象状态函数的上确界
- 对于循环语句,考虑:
```c
x = 100;
y = 1;
while (y > x) {
x *= -100;
y += 1;
}
```
尽管我们不知道循环会执行多少次终止,从逻辑上我们仍然可以得到一些结果。为了实现,我们假设抽象域中有符号 $bot$ 使得 $Gamma(bot) = emptyset$,假设每个节点处符号的初始值都是 $bot$,从 entry 的后继节点开始,分析时随机选取节点使用分支合并更新状态,使用宽度优先方法,如果某节点更新就将其后继加入待更新节点,直至没有节点待更新。
]
#theorem[][
上面的算法是正确的,也即保证每个变量的值符合抽象状态。同时,它也保证停止,并且停止的结果与最开始选取的节点无关。
]
#remark[][
这种分析方法产生了以下几种不精确性:
- 将值抽象成有限个值的集合
- 值的运算抽象到集合上,加大了不精确性
- 发生分支时,往往事实上只有一个分支被执行,但我们假设两个都有可能执行
- 状态合并时,也会产生不精确性
]
#example[可达定值分析][
给定程序,判断每个变量的值可能在哪些行被赋值。这与数据流分析很接近,其中具体域是所有程序行号,转换函数是在赋值语句处替换,其他语句不变。注意算法中需要初始将所有节点全部加入待更新节点,否则非赋值语句可能保持 $bot$ 不变,导致算法停止。
]
#example[可用表达式分析][
给定程序,如果从入口到某一位置 $p$ 的所有路径都计算了表达式 $e$,并且最后一次执行后没有改变与 $e$ 相关的变量,则称 $e$ 是 $p$ 处的一个可用表达式。这个问题中的具体域是程序中的所有表达式,每个节点的初始值是程序表达式的全集,转换函数是计算表达式时增加,变量赋值时删去相关的的表达式,分支合并时取交而非并。
]
#example[活跃变量分析][
给定程序,如果语句 $s$ 执行前,一个变量的值在 $s$ 或后续的语句仍然使用,则称之为活跃变量。与之前问题的主要区别在于我们需要倒着程序的执行顺序进行分析,抽象值含义是从当前位置开始任意长度的具体执行序列的集合(注意由于程序会无限执行,在倒着分析的时候不能假设所有的执行序列都在最后的节点终止)初始值为空集,每个节点处先删去写入的变量,再加入读取的变量,分支合并时取并。
]
#remark[][
一般来说,数据流分析只能考虑从 entry 开始或者从 exit 结束的有限执行序列。对于可能无穷的执行序列,逻辑上无法分析。对于活跃变量分析,我们可以转而证明在任意位置结束的有限执行序列都正确,进而保证时间上的正确性。
]
一般而言,数据流分析有以下步骤:
- 设计抽象域
- 编写节点转换函数,注意可能需要处理复杂表达式,此时可以对递归的表达式结构进行分析,或者直接对三地址码进行分析。
- 处理控制流路径的分叉和合并
之前都没有讨论算法的终止性和合流性(节点选择顺序不影响结果),为此我们引入一套数据流分析的框架,并基于该框架进行证明。
#definition[半格 semilattice][
称 $(S, sup)$ 为半格,如果满足:
- 幂等性:$x sup x = x$
- 交换性:$x sup y = y sup x$
- 结合性:$(x sup y) sup z = x sup (y sup z)$
它是幂等的交换半群。不难验证,$x subset y := x sup y = y$ 是偏序关系,$sup$ 实际上是求上确界运算。
有最小值 $bot$ 的半格称为有界半格,它是幂等的交换幺半群。
称一个有界半格的高度指其中全序子集元素个数的最大值。
]
#theorem[不动点定理][
给定有限高度的有界半格 $S$ 和单调函数 $f: S -> S$,则 $bot, f(bot), ..., $ 一定在有限步停止在 $f$ 的最小不动点
]
#proof[
- 首先证明序列终止。不难验证:
$
bot subset f(bot) => f(bot) subset f(f(bot)) => ...
$
说明该序列是链,而有限高度意味着链有限长,进而最终稳定,而稳定的值当然是不动点。
- 其次,为了证明它是最小不动点,取 $x$ 是一个不动点,则:
$
bot subset x => f(bot) subset f(x) = x => ...
$
反复应用可得结论
]
#definition[数据流单调分析框架][
可以定义一般框架:
- 一个控制流图 $G$
- 一个有限高度的有界半格 $S$
- 一个 entry
- 一个单调函数 $f$
可以证明,对于该框架(对应的随机选取节点进行更新的算法称为工单算法),依次选取节点更新的算法称为轮询算法),容易证明轮询算法一定收敛到更新函数的最小不动点,而工单算法也会收敛到该点,因此一定收敛并且收敛到相同值
]
#definition[分配性][
假设转换函数 $f_v$ 满足 $f_v (x) sup f_v (y) = f_v (x sup y)$,则称满足分配性。满足分配性的数据流分析不会因为提前合并引入不精确性。由集合交/并操作构造的转换函数都满足分配性。
]
=== 数据流分析拓展:条件压缩
在上面的近似方案中,我们认为所有分支都会执行从而得到分析结果,这当然是荒谬的。为了使结果更精确,我们需要更精细地处理这个问题。一个常见的方案是增加条件压缩节点,也就是:
```c
if (x > 0)
{
x += 1;
}
else
{
x = 1;
}
```
转换成:
```c
if (x > 0)
{
assert(x > 0);
x += 1;
}
else
{
assert(x <= 0);
x = 1;
}
```
这里,我们的任务是要通过 assert 节点反解出 $x$ 满足的条件,这被称为*反向执行语义*。
这里,我们拓展抽象域的定义以满足布尔值:
$
{bot, T, F, top}
$
#let Inv = $"Inv"$
其中 $gamma(bot) = {}, gamma(top) = {T, F}$,定义规则:
- $Inv(and) (bot) = (bot, bot)$
- $Inv(and) (T) = (T, T)$
- $Inv(and) (\_) = (top, top)$
- $Inv(> 0)(bot) = bot$
- $Inv(> 0)(T) = {x: "int" > 0}$
- ...
事实上,我们可以做更精确的压缩,结合目前已知的信息给出更精确的结果,例如:
$
Inv(and) ((T, top), F) = (T, F)
$
其中前一个参数指变量当前的抽象状态,后一个参数指表达式的抽象值,结果是变量的新抽象状态。注意在实际的复杂表达式,例如:
$
x > 0 and y > x and z > y = T
$
时,我们要先正向执行,得到:
$
(x > 0, y > x, z > y): (top, top, top)
$
反向压缩得到:
$
(x > 0, y > x, z > y): (T, T, T)\
(x, y, z) : (>0, top, top)
$
不难看出这个过程并未终止,可以再次进行,迭代几次后可以得到:
$
(x, y, z) : (>0, >0, >0)
$
一般的,如果反向执行的规则足够单调,则这样的迭代会收敛,然而实践上往也会使用不能保证收敛的反向执行语义。
=== 区间分析:加宽和变窄
对于下面的程序:
```c
x = 1;
for (int i = 0; i < b; i++) {
x += 1;
}
```
求出一个 $x$ 的上界和下界,这样的分析称为区间分析。实际结果为 $[0, +infinity]$ ,然而如果使用通常的数据流分析技术,我们无法真正得到 $+infinity$,或者说半格的高度是无穷的,导致无法收敛。有些时候,即使有限高度,高度也会过高导致收敛过慢。为此我们引入加宽和变窄的概念:
- 加宽:通过降低精度加快分析过程,包括:
- 简易加宽:降低格的高度,例如在上面的问题中,抽象域不取全体整数,而是例如:
$
-infinity, 1, 2, ..., 100, +infinity
$
实际计算时,寻找与抽象域中格点接近的,保证正确的结果。尽管会导致精度损失,但安全性和收敛性往往容易保证。
- 通用加宽:根据趋势猜测结果。具体来说,引入加宽算子 $a nabla b$,其中 $a$ 是该节点旧值,$b$ 是一轮更新后得到的新值,定义:
$
[a, b] nabla [c, d] = (m, n) where\
m = "if" c >= a "then" a "else" -infinity\
n = "if" b <= d "then" b "else" +infinity
$
换言之,只要发现新结果的上界变大,就直接加宽到正无穷,否则采纳旧值(这里采纳旧值新值均可,采纳旧值可以更快收敛,采纳新值可能会造成无穷震荡);下界变小,就直接加宽到负无穷。这样收敛的速度很快。不幸的是,加宽函数往往没有单调性,目前并没有容易判断的属性保证通用加宽的收敛性,在除了循环之外的场景往往也会导致奇怪的问题。实践上往往只会在循环的入口处使用通用加宽。
- 变窄:加宽可以提高效率,然而往往会损失很多精确性。为此我们引入变窄技术,基本思想是在加宽收敛后,进行一轮普通的数据流分析,就可以得到较为精确的结果。
#theorem[][
设普通数据流分析更新函数为 $F$(具有单调性),添加加宽算子后为 $G$ ,并且满足 $G(x) >= F(x)$,则加宽-变窄是安全的
]
#proof[
假设 $x_0$ 是 $F$ 的不动点,也就是当前抽象域下最精确的估计。不难发现:
$
x <= x_0 => F(x) <= x_0 => G(x) <= x_0
$
蕴含着 $G$ 是加宽是安全的。为了考虑变窄,假设加宽 $n$ 次后采取变窄,得到结果:
$
F(G^n (bot))
$
]
=== 抽象解释
#definition[][
假设具体域为 $D$,抽象域为 $A$
称 $gamma: A -> D$ 为具体化函数,$alpha: A -> D$ 为抽象化函数,称他们构成一个 Galois 连接,如果满足:
$
alpha(X) <= Y <=> X <= gamma(Y)
$
]
#remark[][
事实上假设将偏序集看作范畴,一对 Galois 连接就是一对伴随函子。
]
#proposition[][
$alpha, gamma$ 是 Galois 连接当且仅当以下性质全部成立:
- $forall X in D, X <= gamma (alpha(X))$
- $forall Y in A. alpha(gamma(Y)) <= Y$
- $forall X, Y in D, X <= Y => alpha(X) <= alpha(Y)$
- $forall X, Y in A, X <= Y => gamma(X) <= gamma(Y)$
]
#definition[][
设 $alpha, gamma$ 是 Galois 连接,$f: A -> A, g: D -> D$,则:
- $f$ 是 $g$ 的安全抽象,如果:
$
(alpha compose g compose gamma) (X) <= f(X)
$
也等价于:
$
(g compose gamma) (X) <= (gamma compose f) (X)
$
- $f$ 是 $g$ 的最佳抽象,如果:
$
alpha compose g compose gamma = f
$
- $f$ 是 $g$ 的精确抽象,如果:
$
g compose gamma = gamma compose f
$
显然最佳抽象总是存在的,但精确抽象不一定存在。
]
取具体域为程序执行踪迹的集合,抽象域为分析结果,并令:
- $alpha$ 为踪迹集合对应的精确分析结果,也即 $alpha(X) := sup_(x in X) beta(x)$
- $gamma(Y) = {x | beta(x) <= Y}$
容易证明这构成一个 Galois 连接。事实上,一个精确的程序分析应该满足:
#align(center)[#commutative-diagram(
node((0, 0), $"抽象输入"$, 1),
node((0, 1), $"分析结果"$, 2),
node((1, 0), $"输入轨迹集合"$, 3),
node((1, 1), $"执行踪迹集合"$, 4),
arr(1, 2, $"抽象语义"$),
arr(3, 1, $beta$),
arr(4, 2, $alpha$),
arr(3, 4, $"具体语义"$),)]
而通常如果保证:
#align(center)[#commutative-diagram(
node((0, 0), $"抽象输入"$, 1),
node((0, 1), $"分析结果"$, 2),
node((1, 0), $"输入轨迹集合"$, 3),
node((1, 1), $"执行踪迹集合"$, 4),
arr(1, 2, $"抽象语义"$),
arr(3, 1, $beta$),
arr(4, 2, $alpha <= $),
arr(3, 4, $"具体语义"$),)]
#let trans = $"trans"$
#let State = $"State"$
#let Set = $"Set"$
#let Step = $"Step"$
#let List = $"List"$
#let Node = $"Node"$
#let Trace = $"Trace"$
#let Step = $"Step"$
就称之为安全的。具体而言,这里我们将单个节点 $v$ 的程序语义抽象成状态转换函数:
```hs
trans: Node -> State -> Set State
```
程序的一个具体执行序列 $T: Trace$ 定义为:
```hs
Trace := [(Node, State)]
```
则给定一个执行序列 $T$ ,可以定义:
```hs
Step T : Trace -> Set Trace
Step T = do
next_node <- next v
let (v, s) = last T
next_state <- trans v s
return $ T ++ [(next_node, next_state)]
Step_inf : Trace -> [Set Trace]
Step_inf T = iterate (\ma -> ma >>= Step) (return T)
```
有了这些定义,我们可以详细地证明程序分析在语义上的正确性。
=== 敏感性
我们往往用敏感性表示程序分析的精确性,往往包括:
- 流敏感性:分析结果忽略了程序的控制流,任意交换语句顺序不改变分析结果。数据流分析是流敏感的。如果在数据流分析中,直接认为所有节点都是当前节点的前驱,则产生的就是流不敏感的分析。
- 路径敏感:对于控制流不同的路径,分析结果可能不同。带有条件压缩的数据流分析是路径敏感的。
#block(width: 100%)[
$dots$
]
== 过程间分析
== 指针分析
= 基于约束求解的程序分析
== SAT
== SMT
== 符号执行
= 软件分析应用
== 程序合成
== 缺陷分析
== 缺陷修复 |
|
https://github.com/Akelio-zhang/cv-typst | https://raw.githubusercontent.com/Akelio-zhang/cv-typst/main/cv.typ | typst | #let render_mode = (la: "zh", output: "concise")
#import "meta.typ": *
#set text(font: ("New Computer Modern", "Noto Serif CJK SC"))
#show heading: set text(font: ("Linux Biolinum", "Noto Serif CJK SC"))
#show link: underline
// Uncomment the following lines to adjust the size of text
// The recommend resume text size is from `10pt` to `12pt`
// #set text(
// size: 12pt,
// )
// Custom heading color: https://typst.app/docs/reference/visualize/color/
#let head_color = black
// Feel free to change the margin below to best fit your own CV
#set page(
margin: (x: 0.9cm, y: 1.3cm),
)
// For more customizable options, please refer to official reference: https://typst.app/docs/reference/
#set par(justify: true)
#show heading: set text(fill: head_color)
#let chiline() = {v(-3pt); line(length: 100%, stroke: head_color); v(-5pt)}
// support language and output render mode switch
#let section(body, la: "zh", output: "concise") = {
let mode = (la: la, output: output)
if mode.la == render_mode.la and (mode.output == "concise" or mode.output == render_mode.output) [
#body
]
}
// default with Chinese and concise page
#section[
= 张三
<EMAIL> |
+86 188 8888 8888 |
#link("https://www.github.com")[github.com]
]
// for English and concise page
#section(la: "en")[
= ZHANG San
<EMAIL> |
+86 188 8888 8888 |
#link("https://www.github.com")[github.com]
]
#section[
== 教育经历
#chiline()
#link("https://typst.app/")[*#lorem(2)*] #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(10)
]
#section[
== 工作经历
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(40)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(30)
- #lorem(10)
]
#section[
== 项目经历
#chiline()
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
- #lorem(30)
*#lorem(2)* #h(1fr) 2333/23 -- 2333/23 \
#lorem(5) #h(1fr) #lorem(2) \
- #lorem(20)
]
#section(la: "zh", output: "full")[
其他项目 \
- *#lorem(2)*#lorem(5)
- *#lorem(1)*#lorem(10)
]
#section[
== 技术特点
#chiline()
- #lorem(2)
- #lorem(5)
]
#section[
== 语言能力
#chiline()
- #lorem(2)
- #lorem(2)
]
#section[
== 获奖经历
#chiline()
- #lorem(5)
]
#section[
#align(right, text(fill: gray)[更新于 #today()])
]
#section(la: "en")[
#align(right, text(fill: gray)[Last Updated on #today_en()])
] |
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/071.%20notnot.html.typ | typst | notnot.html
Why to Not Not Start a Startup
Want to start a startup? Get funded by
Y Combinator.
March 2007(This essay is derived from talks at the 2007
Startup School and the Berkeley CSUA.)We've now been doing Y Combinator long enough to have some data
about success rates. Our first batch, in the summer of 2005, had
eight startups in it. Of those eight, it now looks as if at least
four succeeded. Three have been acquired:
Reddit was a merger of
two, Reddit and Infogami, and a third was acquired that we can't
talk about yet. Another from that batch was
Loopt, which is doing
so well they could probably be acquired in about ten minutes if
they wanted to.So about half the founders from that first summer, less than two
years ago, are now rich, at least by their standards. (One thing
you learn when you get rich is that there are many degrees of it.)I'm not ready to predict our success rate will stay as high as 50%.
That first batch could have been an anomaly. But we should be able
to do better than the oft-quoted (and probably made
up) standard figure of 10%. I'd feel safe aiming at 25%.Even the founders who fail don't seem to have such a bad time. Of
those first eight startups, three are now probably dead. In two
cases the founders just went on to do other things at the end of
the summer. I don't think they were traumatized by the experience.
The closest to a traumatic failure was Kiko, whose founders kept
working on their startup for a whole year before being squashed by
Google Calendar. But they ended up happy. They sold their software
on eBay for a quarter of a million dollars. After they paid back
their angel investors, they had about a year's salary each.
[1]
Then they immediately went on to start a new and much more exciting
startup, Justin.TV.So here is an even more striking statistic: 0% of that first batch
had a terrible experience. They had ups and downs, like every
startup, but I don't think any would have traded it for a job in a
cubicle. And that statistic is probably not an anomaly. Whatever
our long-term success rate ends up being, I think the rate of people
who wish they'd gotten a regular job will stay close to 0%.The big mystery to me is: why don't more people start startups? If
nearly everyone who does it prefers it to a regular job, and a
significant percentage get rich, why doesn't everyone want to do
this? A lot of people think we get thousands of applications for
each funding cycle. In fact we usually only get several hundred.
Why don't more people apply? And while it must seem to anyone
watching this world that startups are popping up like crazy, the
number is small compared to the number of people with the necessary
skills. The great majority of programmers still go straight from
college to cubicle, and stay there.It seems like people are not acting in their own interest. What's
going on? Well, I can answer that. Because of Y Combinator's
position at the very start of the venture funding process, we're
probably the world's leading experts on the psychology of people
who aren't sure if they want to start a company.There's nothing wrong with being unsure. If you're a hacker thinking
about starting a startup and hesitating before taking the leap,
you're part of a grand tradition. Larry and Sergey seem to have
felt the same before they started Google, and so did Jerry and Filo
before they started Yahoo. In fact, I'd guess the most successful
startups are the ones started by uncertain hackers rather than
gung-ho business guys.We have some evidence to support this. Several of the most successful
startups we've funded told us later that they only decided to apply
at the last moment. Some decided only hours before the deadline.The way to deal with uncertainty is to analyze it into components.
Most people who are reluctant to do something have about eight
different reasons mixed together in their heads, and don't know
themselves which are biggest. Some will be justified and some
bogus, but unless you know the relative proportion of each, you
don't know whether your overall uncertainty is mostly justified or
mostly bogus.So I'm going to list all the components of people's reluctance to
start startups, and explain which are real. Then would-be founders
can use this as a checklist to examine their own feelings.I admit my goal is to increase your self-confidence. But there are
two things different here from the usual confidence-building exercise.
One is that I'm motivated to be honest. Most people in the
confidence-building business have already achieved their goal when
you buy the book or pay to attend the seminar where they tell you
how great you are. Whereas if I encourage people to start startups
who shouldn't, I make my own life worse. If I encourage too many
people to apply to Y Combinator, it just means more work for me,
because I have to read all the applications.The other thing that's going to be different is my approach. Instead
of being positive, I'm going to be negative. Instead of telling
you "come on, you can do it" I'm going to consider all the reasons
you aren't doing it, and show why most (but not all) should be
ignored. We'll start with the one everyone's born with.1. Too youngA lot of people think they're too young to start a startup. Many
are right. The median age worldwide is about 27, so probably a
third of the population can truthfully say they're too young.What's too young? One of our goals with Y Combinator was to discover
the lower bound on the age of startup founders. It always seemed
to us that investors were too conservative here—that they wanted
to fund professors, when really they should be funding grad students
or even undergrads.The main thing we've discovered from pushing the edge of this
envelope is not where the edge is, but how fuzzy it is. The outer
limit may be as low as 16. We don't look beyond 18 because people
younger than that can't legally enter into contracts. But the most
successful founder we've funded so far, <NAME>, was 19 at the
time.<NAME>, however, is an outlying data point. When he was 19,
he seemed like he had a 40 year old inside him. There are other
19 year olds who are 12 inside.There's a reason we have a distinct word "adult" for people over a
certain age. There is a threshold you cross. It's conventionally
fixed at 21, but different people cross it at greatly varying ages.
You're old enough to start a startup if you've crossed this threshold,
whatever your age.How do you tell? There are a couple tests adults use. I realized
these tests existed after meeting <NAME>, actually. I noticed
that I felt like I was talking to someone much older. Afterward I
wondered, what am I even measuring? What made him seem older?One test adults use is whether you still have the kid flake reflex.
When you're a little kid and you're asked to do something hard, you
can cry and say "I can't do it" and the adults will probably let
you off. As a kid there's a magic button you can press by saying
"I'm just a kid" that will get you out of most difficult situations.
Whereas adults, by definition, are not allowed to flake. They still
do, of course, but when they do they're ruthlessly pruned.The other way to tell an adult is by how they react to a challenge.
Someone who's not yet an adult will tend to respond to a challenge
from an adult in a way that acknowledges their dominance. If an
adult says "that's a stupid idea," a kid will either crawl away
with his tail between his legs, or rebel. But rebelling presumes
inferiority as much as submission. The adult response to
"that's a stupid idea," is simply to look the other person in the
eye and say "Really? Why do you think so?"There are a lot of adults who still react childishly to challenges,
of course. What you don't often find are kids who react to challenges
like adults. When you do, you've found an adult, whatever their
age.2. Too inexperiencedI once wrote that startup founders should be at least 23, and that
people should work for another company for a few years before
starting their own. I no longer believe that, and what changed my
mind is the example of the startups we've funded.I still think 23 is a better age than 21. But the best way to get
experience if you're 21 is to start a startup. So, paradoxically,
if you're too inexperienced to start a startup, what you should do
is start one. That's a way more efficient cure for inexperience
than a normal job. In fact, getting a normal job may actually make
you less able to start a startup, by turning you into a tame animal
who thinks he needs an office to work in and a product manager to
tell him what software to write.What really convinced me of this was the Kikos. They started a
startup right out of college. Their inexperience caused them to
make a lot of mistakes. But by the time we funded their second
startup, a year later, they had become extremely formidable. They
were certainly not tame animals. And there is no way they'd have
grown so much if they'd spent that year working at Microsoft, or
even Google. They'd still have been diffident junior programmers.So now I'd advise people to go ahead and start startups right out
of college. There's no better time to take risks than when you're
young. Sure, you'll probably fail. But even failure will get you
to the ultimate goal faster than getting a job.It worries me a bit to be saying this, because in effect we're
advising people to educate themselves by failing at our expense,
but it's the truth.3. Not determined enoughYou need a lot of determination to succeed as a startup founder.
It's probably the single best predictor of success.Some people may not be determined enough to make it. It's
hard for me to say for sure, because I'm so determined that I can't
imagine what's going on in the heads of people who aren't. But I
know they exist.Most hackers probably underestimate their determination. I've seen
a lot become visibly more determined as they get used to running a
startup. I can think of
several we've funded who would have been delighted at first to be
bought for $2 million, but are now set on world domination.How can you tell if you're determined enough, when Larry and Sergey
themselves were unsure at first about starting a company? I'm
guessing here, but I'd say the test is whether you're sufficiently
driven to work on your own projects. Though they may have been
unsure whether they wanted to start a company, it doesn't seem as
if Larry and Sergey were meek little research assistants, obediently
doing their advisors' bidding. They started projects of their own.
4. Not smart enoughYou may need to be moderately smart to succeed as a startup founder.
But if you're worried about this, you're probably mistaken. If
you're smart enough to worry that you might not be smart enough to
start a startup, you probably are.And in any case, starting a startup just doesn't require that much
intelligence. Some startups do. You have to be good at math to
write Mathematica. But most companies do more mundane stuff where
the decisive factor is effort, not brains. Silicon Valley can warp
your perspective on this, because there's a cult of smartness here.
People who aren't smart at least try to act that way. But if you
think it takes a lot of intelligence to get rich, try spending a
couple days in some of the fancier bits of New York or LA.If you don't think you're smart enough to start a startup doing
something technically difficult, just write enterprise software.
Enterprise software companies aren't technology companies, they're
sales companies, and sales depends mostly on effort.5. Know nothing about businessThis is another variable whose coefficient should be zero. You
don't need to know anything about business to start a startup. The
initial focus should be the product. All you need to know in this
phase is how to build things people want. If you succeed, you'll
have to think about how to make money from it. But this is so easy
you can pick it up on the fly.I get a fair amount of flak for telling founders just to make
something great and not worry too much about making money. And yet
all the empirical evidence points that way: pretty much 100% of
startups that make something popular manage to make money from it.
And acquirers tell me privately that revenue is not what they buy
startups for, but their strategic value. Which means, because they
made something people want. Acquirers know the rule holds for them
too: if users love you, you can always make money from that somehow,
and if they don't, the cleverest business model in the world won't
save you.So why do so many people argue with me? I think one reason is that
they hate the idea that a bunch of twenty year olds could get rich
from building something cool that doesn't make any money. They
just don't want that to be possible. But how possible it is doesn't
depend on how much they want it to be.For a while it annoyed me to hear myself described as some kind of
irresponsible pied piper, leading impressionable young hackers down
the road to ruin. But now I realize this kind of controversy is a
sign of a good idea.The most valuable truths are the ones most people don't believe.
They're like undervalued stocks. If you start with them, you'll
have the whole field to yourself. So when you find an idea you
know is good but most people disagree with, you should not
merely ignore their objections, but push aggressively in that
direction. In this case, that means you should seek out ideas that
would be popular but seem hard to make money from.We'll bet a seed round you can't make something popular that we
can't figure out how to make money from.6. No cofounderNot having a cofounder is a real problem. A startup is too much
for one person to bear. And though we differ from other investors
on a lot of questions, we all agree on this. All investors, without
exception, are more likely to fund you with a cofounder than without.We've funded two single founders, but in both cases we suggested
their first priority should be to find a cofounder. Both did. But
we'd have preferred them to have cofounders before they applied.
It's not super hard to get a cofounder for a project that's just
been funded, and we'd rather have cofounders committed enough to
sign up for something super hard.If you don't have a cofounder, what should you do? Get one. It's
more important than anything else. If there's no one where you
live who wants to start a startup with you, move where there are
people who do. If no one wants to work with you on your current
idea, switch to an idea people want to work on.If you're still in school, you're surrounded by potential cofounders.
A few years out it gets harder to find them. Not only do you have
a smaller pool to draw from, but most already have jobs, and perhaps
even families to support. So if you had friends in college you
used to scheme about startups with, stay in touch with them as well
as you can. That may help keep the dream alive.It's possible you could meet a cofounder through something like a
user's group or a conference. But I wouldn't be too optimistic.
You need to work with someone to know whether you want them as a
cofounder.
[2]The real lesson to draw from this is not how to find a cofounder,
but that you should start startups when you're young and there are
lots of them around.7. No ideaIn a sense, it's not a problem if you don't have a good idea, because
most startups change their idea anyway. In the average Y Combinator
startup, I'd guess 70% of the idea is new at the end of the
first three months. Sometimes it's 100%.In fact, we're so sure the founders are more important than the
initial idea that we're going to try something new this funding
cycle. We're going to let people apply with no idea at all. If you
want, you can answer the question on the application form that asks
what you're going to do with "We have no idea." If you seem really
good we'll accept you anyway. We're confident we can sit down with
you and cook up some promising project.Really this just codifies what we do already. We put little weight
on the idea. We ask mainly out of politeness. The kind of question
on the application form that we really care about is the one where
we ask what cool things you've made. If what you've made is version
one of a promising startup, so much the better, but the main thing
we care about is whether you're good at making things. Being lead
developer of a popular open source project counts almost as much.That solves the problem if you get funded by Y Combinator. What
about in the general case? Because in another sense, it is a problem
if you don't have an idea. If you start a startup with no idea,
what do you do next?So here's the brief recipe for getting startup ideas. Find something
that's missing in your own life, and supply that need—no matter
how specific to you it seems. <NAME> built himself a computer;
who knew so many other people would want them? A need that's narrow
but genuine is a better starting point than one that's broad but
hypothetical. So even if the problem is simply that you don't have
a date on Saturday night, if you can think of a way to fix that by
writing software, you're onto something, because a lot of other
people have the same problem.8. No room for more startupsA lot of people look at the ever-increasing number of startups and
think "this can't continue." Implicit in their thinking is a
fallacy: that there is some limit on the number of startups there
could be. But this is false. No one claims there's any limit on
the number of people who can work for salary at 1000-person companies.
Why should there be any limit on the number who can work for equity
at 5-person companies?
[3]Nearly everyone who works is satisfying some kind of need. Breaking
up companies into smaller units doesn't make those needs go away.
Existing needs would probably get satisfied more efficiently by a
network of startups than by a few giant, hierarchical organizations,
but I don't think that would mean less opportunity, because satisfying
current needs would lead to more. Certainly this tends to be the
case in individuals. Nor is there anything wrong with that. We
take for granted things that medieval kings would have considered
effeminate luxuries, like whole buildings heated to spring temperatures
year round. And if things go well, our descendants will take for
granted things we would consider shockingly luxurious. There is
no absolute standard for material wealth. Health care is a component
of it, and that alone is a black hole. For the foreseeable future,
people will want ever more material wealth, so there is no limit
to the amount of work available for companies, and for startups in
particular.Usually the limited-room fallacy is not expressed directly. Usually
it's implicit in statements like "there are only so many startups
Google, Microsoft, and Yahoo can buy." Maybe, though the list of
acquirers is a lot longer than that. And whatever you think of
other acquirers, Google is not stupid. The reason big companies
buy startups is that they've created something valuable. And why
should there be any limit to the number of valuable startups companies
can acquire, any more than there is a limit to the amount of wealth
individual people want? Maybe there would be practical limits on
the number of startups any one acquirer could assimilate, but if
there is value to be had, in the form of upside that founders are
willing to forgo in return for an immediate payment, acquirers will
evolve to consume it. Markets are pretty smart that way.9. Family to supportThis one is real. I wouldn't advise anyone with a family to start
a startup. I'm not saying it's a bad idea, just that I don't want
to take responsibility for advising it. I'm willing to take
responsibility for telling 22 year olds to start startups. So what
if they fail? They'll learn a lot, and that job at Microsoft will
still be waiting for them if they need it. But I'm not prepared
to cross moms.What you can do, if you have a family and want to start a startup,
is start a consulting business you can then gradually turn into a
product business. Empirically the chances of pulling that off seem
very small. You're never going to produce Google this way. But at
least you'll never be without an income.Another way to decrease the risk is to join an existing startup
instead of starting your own. Being one of the first employees of
a startup is a lot like being a founder, in both the good ways and
the bad. You'll be roughly 1/n^2 founder, where n is your employee
number.As with the question of cofounders, the real lesson here is to start
startups when you're young.10. Independently wealthyThis is my excuse for not starting a startup. Startups are stressful.
Why do it if you don't need the money? For every "serial entrepreneur,"
there are probably twenty sane ones who think "Start another
company? Are you crazy?"I've come close to starting new startups a couple times, but I
always pull back because I don't want four years of my life to be
consumed by random schleps. I know this business well enough to
know you can't do it half-heartedly. What makes a good startup
founder so dangerous is his willingness to endure infinite schleps.There is a bit of a problem with retirement, though. Like a lot
of people, I like to work. And one of the many weird little problems
you discover when you get rich is that a lot of the interesting
people you'd like to work with are not rich. They need to work at
something that pays the bills. Which means if you want to have
them as colleagues, you have to work at something that pays the
bills too, even though you don't need to. I think this is what
drives a lot of serial entrepreneurs, actually.That's why I love working on Y Combinator so much. It's an excuse
to work on something interesting with people I like.11. Not ready for commitmentThis was my reason for not starting a startup for most of my twenties.
Like a lot of people that age, I valued freedom most of all. I was
reluctant to do anything that required a commitment of more than a
few months. Nor would I have wanted to do anything that completely
took over my life the way a startup does. And that's fine. If you
want to spend your time travelling around, or playing in a band,
or whatever, that's a perfectly legitimate reason not to start a
company.If you start a startup that succeeds, it's going to consume at least
three or four years. (If it fails, you'll be done a lot quicker.)
So you shouldn't do it if you're not ready for commitments on that
scale. Be aware, though, that if you get a regular job, you'll
probably end up working there for as long as a startup would take,
and you'll find you have much less spare time than you might expect.
So if you're ready to clip on that ID badge and go to that orientation
session, you may also be ready to start that startup.12. Need for structureI'm told there are people who need structure in their lives. This
seems to be a nice way of saying they need someone to tell them
what to do. I believe such people exist. There's plenty of empirical
evidence: armies, religious cults, and so on. They may even be the
majority.If you're one of these people, you probably shouldn't start a
startup. In fact, you probably shouldn't even go to work for one.
In a good startup, you don't get told what to do very much. There
may be one person whose job title is CEO, but till the company has
about twelve people no one should be telling anyone what to do.
That's too inefficient. Each person should just do what they need
to without anyone telling them.If that sounds like a recipe for chaos, think about a soccer team.
Eleven people manage to work together in quite complicated ways,
and yet only in occasional emergencies does anyone tell anyone else
what to do. A reporter once asked <NAME> if there were any
language problems at Real Madrid, since the players were from about
eight different countries. He said it was never an issue, because
everyone was so good they never had to talk. They all just did the
right thing.How do you tell if you're independent-minded enough to start a
startup? If you'd bristle at the suggestion that you aren't, then
you probably are.13. Fear of uncertaintyPerhaps some people are deterred from starting startups because
they don't like the uncertainty. If you go to work for Microsoft,
you can predict fairly accurately what the next few years will be
like—all too accurately, in fact. If you start a startup, anything
might happen.Well, if you're troubled by uncertainty, I can solve that problem
for you: if you start a startup, it will probably fail. Seriously,
though, this is not a bad way to think
about the whole experience. Hope for the best, but expect the
worst. In the worst case, it will at least be interesting. In the
best case you might get rich.No one will blame you if the startup tanks, so long as you made a
serious effort. There may once have been a time when employers
would regard that as a mark against you, but they wouldn't now. I
asked managers at big companies, and they all said they'd prefer
to hire someone who'd tried to start a startup and failed over
someone who'd spent the same time working at a big company.Nor will investors hold it against you, as long as you didn't fail
out of laziness or incurable stupidity. I'm told there's a lot
of stigma attached to failing in other places—in Europe, for
example. Not here. In America, companies, like practically
everything else, are disposable.14. Don't realize what you're avoidingOne reason people who've been out in the world for a year or two
make better founders than people straight from college is that they
know what they're avoiding. If their startup fails, they'll have
to get a job, and they know how much jobs suck.If you've had summer jobs in college, you may think you know what
jobs are like, but you probably don't. Summer jobs at technology
companies are not real jobs. If you get a summer job as a waiter,
that's a real job. Then you have to carry your weight. But software
companies don't hire students for the summer as a source of cheap
labor. They do it in the hope of recruiting them when they graduate.
So while they're happy if you produce, they don't expect you to.That will change if you get a real job after you graduate. Then
you'll have to earn your keep. And since most of what big companies
do is boring, you're going to have to work on boring stuff. Easy,
compared to college, but boring. At first it may seem cool to get
paid for doing easy stuff, after paying to do hard stuff in college.
But that wears off after a few months. Eventually it gets demoralizing
to work on dumb stuff, even if it's easy and you get paid a lot.And that's not the worst of it. The thing that really sucks about
having a regular job is the expectation that you're supposed to be
there at certain times. Even Google is afflicted with this,
apparently. And what this means, as everyone who's had a regular
job can tell you, is that there are going to be times when you have
absolutely no desire to work on anything, and you're going to have
to go to work anyway and sit in front of your screen and pretend
to. To someone who likes work, as most good hackers do, this is
torture.In a startup, you skip all that. There's no concept of office hours
in most startups. Work and life just get mixed together. But the
good thing about that is that no one minds if you have a life at
work. In a startup you can do whatever you want most of the time.
If you're a founder, what you want to do most of the time is work.
But you never have to pretend to.If you took a nap in your office in a big company, it would seem
unprofessional. But if you're starting a startup and you fall
asleep in the middle of the day, your cofounders will just assume
you were tired.15. Parents want you to be a doctorA significant number of would-be startup founders are probably
dissuaded from doing it by their parents. I'm not going to say you
shouldn't listen to them. Families are entitled to their own
traditions, and who am I to argue with them? But I will give you
a couple reasons why a safe career might not be what your parents
really want for you.One is that parents tend to be more conservative for their kids
than they would be for themselves. This is actually a rational
response to their situation. Parents end up sharing more of their
kids' ill fortune than good fortune. Most parents don't mind this;
it's part of the job; but it does tend to make them excessively
conservative. And erring on the side of conservatism is still
erring. In almost everything, reward is proportionate to risk. So
by protecting their kids from risk, parents are, without realizing
it, also protecting them from rewards. If they saw that, they'd
want you to take more risks.The other reason parents may be mistaken is that, like generals,
they're always fighting the last war. If they want you to be a
doctor, odds are it's not just because they want you to help the
sick, but also because it's a prestigious and lucrative career.
[4]
But not so lucrative or prestigious as it was when their
opinions were formed. When I was a kid in the seventies, a doctor
was the thing to be. There was a sort of golden triangle involving
doctors, Mercedes 450SLs, and tennis. All three vertices now seem
pretty dated.The parents who want you to be a doctor may simply not realize how
much things have changed. Would they be that unhappy if you were
<NAME> instead? So I think the way to deal with your parents'
opinions about what you should do is to treat them like feature
requests. Even if your only goal is to please them, the way to do
that is not simply to give them what they ask for. Instead think
about why they're asking for something, and see if there's a better
way to give them what they need.16. A job is the defaultThis leads us to the last and probably most powerful reason people
get regular jobs: it's the default thing to do. Defaults are
enormously powerful, precisely because they operate without any
conscious choice.To almost everyone except criminals, it seems an axiom that if you
need money, you should get a job. Actually this tradition is not
much more than a hundred years old. Before that, the default way
to make a living was by farming. It's a bad plan to treat something
only a hundred years old as an axiom. By historical standards,
that's something that's changing pretty rapidly.We may be seeing another such change right now. I've read a lot
of economic history, and I understand the startup world pretty well,
and it now seems to me fairly likely that we're seeing the beginning
of a change like the one from farming to manufacturing.And you know what? If you'd been around when that change began
(around 1000 in Europe) it would have seemed to nearly everyone
that running off to the city to make your fortune was a crazy thing
to do. Though serfs were in principle forbidden to leave their
manors, it can't have been that hard to run away to a city. There
were no guards patrolling the perimeter of the village. What
prevented most serfs from leaving was that it seemed insanely risky.
Leave one's plot of land? Leave the people you'd spent your whole
life with, to live in a giant city of three or four thousand complete
strangers? How would you live? How would you get food, if you
didn't grow it?Frightening as it seemed to them, it's now the default with us to
live by our wits. So if it seems risky to you to start a startup,
think how risky it once seemed to your ancestors to live as we do
now. Oddly enough, the people who know this best are the very ones
trying to get you to stick to the old model. How can Larry and
Sergey say you should come work as their employee, when they didn't
get jobs themselves?Now we look back on medieval peasants and wonder how they stood it.
How grim it must have been to till the same fields your whole life
with no hope of anything better, under the thumb of lords and priests
you had to give all your surplus to and acknowledge as your masters.
I wouldn't be surprised if one day people look back on what we
consider a normal job in the same way. How grim it would be to
commute every day to a cubicle in some soulless office complex, and
be told what to do by someone you had to acknowledge as a boss—someone
who could call you into their office and say "take a seat,"
and you'd sit! Imagine having to ask permission to release
software to users. Imagine being sad on Sunday afternoons because
the weekend was almost over, and tomorrow you'd have to get up and
go to work. How did they stand it?It's exciting to think we may be on the cusp of another shift like
the one from farming to manufacturing. That's why I care about
startups. Startups aren't interesting just because they're a way
to make a lot of money. I couldn't care less about other ways to
do that, like speculating in securities. At most those are interesting
the way puzzles are. There's more going on with startups. They
may represent one of those rare, historic shifts in the way
wealth is created.That's ultimately what drives us to work on Y Combinator. We want
to make money, if only so we don't have to stop doing it, but that's
not the main goal. There have only been a handful of these great
economic shifts in human history. It would be an amazing hack to
make one happen faster.
Notes[1]
The only people who lost were us. The angels had convertible
debt, so they had first claim on the proceeds of the auction. Y
Combinator only got 38 cents on the dollar.[2]
The best kind of organization for that might be an open source
project, but those don't involve a lot of face to face meetings.
Maybe it would be worth starting one that did.[3]
There need to be some number of big companies to acquire the
startups, so the number of big companies couldn't decrease to zero.[4]
Thought experiment: If doctors did the same work, but as
impoverished outcasts, which parents would still want their kids
to be doctors?Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this, to the founders of Zenter
for letting me use their web-based PowerPoint killer even though
it isn't launched yet, and to Ming-<NAME>
of the Berkeley CSUA for inviting me to speak.
Comment on this essay.Russian TranslationJapanese TranslationKorean Translation
|
|
https://github.com/FkHiroki/ex-B2_typst | https://raw.githubusercontent.com/FkHiroki/ex-B2_typst/main/sections/section2.typ | typst | MIT No Attribution | \
\
\
\
= 3. 実験方法
== 3.1. レーザー光による回折強度パターン
今回は、レーザ光を用いて、スリットの回折強度パターンを観察することを実際には行わず、与えられた実験データをImageJを用いて解析することで、スリットの幅や個数による回折強度パターンの変化を観察した。まず、与えられた実験データには、3種類の幅の単スリットを用いた時のスリット画像とスクリーン画像の計6枚、幅やスリット間隔を変えた3種類のダブルスリットを用いた時のスリット画像とスクリーンの計6枚である。まず、単スリットの場合は、ImageJを用いてスリットの幅を測定し、また、精密な目盛りを顕微鏡で撮影した画像を用いて、pixel単位をm単位に変換した。次に、ImageJによってスクリーン画像の光強度のグラフを得た。光強度のグラフから、強度パターンの周期を測定し、理論値と比較を行った。また、ダブルスリットの場合も同様に、スリット間隔を測定し、スリット画像の光強度のグラフを得た。光強度のグラフから、強度パターンの周期を測定し、理論値と比較を行った。
ここで理論値の求め方について考える。単スリットの場合、スリットを表現する関数$f(x)$は、
$ f(x) = 1 space (|x| < a), space 0 space (|x| > a/2) $ <eq:slit>
と表し、$f(x)$の値を光の透過率とする。ここで、$a$はスリットの幅である。次に、ダブルスリットの場合、スリットを表現する関数$f(x)$は、
$ f(x) = 1 space (|x| < x_0 plus.minus a), space 0 space ("otherwise") $ <eq:double_slit>
と表せる。実験原理で述べたように、スクリーン上にはスリットのフーリエ変換が現れる。単スリットの場合のフーリエ変換は式@eq:AM2 より、
$ F(k) &= integral_(-infinity)^infinity f(x) e^(-i k x xi) d x \
&= integral_(-a)^a e^(-i k x xi ) d x \
&= - 1 / (i k xi) (e^(i k a xi) - e^(-i k a xi)) \
&= 2 a dot sinc(a k xi) \
&= 2 a dot sinc( (2 pi a) / (lambda b) xi ) $ <eq:slit_ft>
となる。ここで、sinc関数は、$sinc(x) = sin(x) / x$である。また、ダブルスリットの場合のフーリエ変換は、式@eq:AM2 より、
$ F(k) &= integral_(-infinity)^infinity f(x) e^(-i k x xi) d x \
&= integral_(-x_0 - a)^(-x_0 + a) e^(-i k x xi ) d x + integral_(x_0 - a)^(x_0 + a) e^(-i k x xi ) d x \
&= 2 a dot sinc(a k xi) e^(-i k x_0 xi) + 2 a dot sinc(a k xi) e^(i k x_0 xi) \
&= 4 a dot sinc(a k xi) cos(k x_0 xi) \
&= 4 a dot sinc( (2 pi a) / (lambda b) xi ) cos( (2 pi x_0) / (lambda b) xi )
$ <eq:double_slit_ft>
となる。よって、光強度の強度パターンの周期は、sinc関数によるものは、$(lambda b) / (2 a)$、cos関数によるものは、$(lambda b) / (2 x_0)$である。これを用いて、実験データと理論値を比較した。
== 3.2. 回折強度パターンのシミュレーション
フリーの数値計算ソフトウェア レーザ光源とスリットを用いて、いくつかのスリットを作成して、光の回折強度パターン、スクリーンに映し出される回折像のシミュレーションを行った。まず、Octave上で単スリット(幅$0.1$)を作成し、その回折強度パターンを計算させ、回折強度を表すグラフと回折像を表示させた。次に、スリットの幅を$0.2$に変更し、同様に回折強度パターンを計算させ、回折強度を表すグラフと回折像を表示させた。また、ダブルスリットの場合は、幅$0.1$、2つのスリット間隔を$0.8$に設定し、同様に回折強度パターンを計算させ、回折強度を表すグラフと回折像を表示させた。また、スリット間隔を$1.8$に変更し、同様に回折強度パターンを計算させ、回折強度を表すグラフと回折像を表示させた。最後に、四角い形状のスリット、オリジナルのスリットを作成し、同様のシミュレーションを行った。
= 4. 実験結果
== 4.1. レーザー光による回折強度パターン
まず、ImageJを用いて与えられたスクリーン画像の光強度グラフを得た。得られた光強度グラフを@fig:SS1_pattern、@fig:SS2_pattern、@fig:SS3_pattern、@fig:DS1_pattern、@fig:DS2_pattern、@fig:DS3_pattern に示す。
まず、単スリットの場合、スリット幅が狭いほど、回折強度パターンの周期が狭くなることが確認でき、これは式@eq:slit_ft のsincの位相成分から考えられる結果と一致している。また、ダブルスリットの場合、@fig:DS1_pattern と@fig:DS2_pattern を比較すると、スリット幅が広いほど、回折強度パターンの周期が狭くなることが確認でき、また、@fig:DS2_pattern と@fig:DS3_pattern を比較すると、スリット間隔が広いほど、小さい山の周期が狭くなることが確認できる。これらは、式@eq:double_slit_ft のsincとcosの位相成分から考えられる結果と一致していることがわかる。
#figure(
image("/figs/SS1_pattern.png", width: 50%),
caption: [スリット幅が1番狭い単スリットの回折強度パターン]
) <fig:SS1_pattern>
#figure(
image("/figs/SS2_pattern.png", width: 50%),
caption: [スリット幅が2番目に狭い単スリットの回折強度パターン]
) <fig:SS2_pattern>
#figure(
image("/figs/SS3_pattern.png", width: 50%),
caption: [スリット幅が一番広い単スリットの回折強度パターン]
) <fig:SS3_pattern>
#figure(
image("/figs/DS1_pattern.png", width: 50%),
caption: [ダブルスリットの回折強度パターン]
) <fig:DS1_pattern>
#figure(
image("/figs/DS2_pattern.png", width: 50%),
caption: [スリット幅が広いダブルスリットの回折強度パターン]
) <fig:DS2_pattern>
#figure(
image("/figs/DS3_pattern.png", width: 50%),
caption: [スリット幅が広く、スリット間隔が広いダブルスリットの回折強度パターン]
) <fig:DS3_pattern>
そして、これらの図から、ImageJを用いて強度パターンの周期を測定し、理論値と比較した。まず、pixelをm単位に変換するための定規と目盛りの計測値、また用いた光の波長$lambda$、開口とスクリーンの距離$b$を@tab:measure に示す。
#figure(
caption: [実験に使用した定規と目盛りの計測値、光の波長、開口とスクリーンの距離],
table(
columns: 7,
stroke: (none),
table.hline(),
table.header(
[],
[定規 /pixel], [定規 /cm], [目盛り /pixel], [目盛り /mm], [$lambda$ /nm], [$b$ /cm]
),
table.hline(),
[計測値], [$322.0$], [$5.0$], [$87.0$], [$0.1$], [$632.8$], [$96.5$],
table.hline(),
)
) <tab:measure>
@tab:measure の定規を用いて強度パターンの周期を、目盛りを用いてスリットの幅、間隔をそれぞれm単位に直した。次に実験に使用されたスリット画像をImageJを用いて解析し、スリットの幅を測定した。ここで、ダブルスリットの場合、スリット幅を2つ測定できるため、その平均をスリット幅の測定値とする。また、2つのスリットの間隔も計測した。それら測定値を@tab:slit_with に示す。
#figure(
caption: [スリットの幅とスリット間隔の測定値],
table(
columns: 10,
stroke: (none),
table.vline(x: 1, start: 1),
table.vline(x: 7, start: 1),
table.hline(),
table.header(
[],
table.cell(colspan: 6, [スリットの幅 $2a$]),
table.cell(colspan: 3, [スリットの間隔 $2x_0$]),
),
table.hline(),
[], [SS1], [SS2], [SS3], [DS1], [DS2], [DS3], [DS1], [DS2], [DS3],
[長さ /pixel], [$39.1$], [$75.1$], [$112.2$], [$50.5$], [$71.0$], [$72$], [$179.2$], [$203.0$], [$404.0$],
[長さ / µm], [$44.9$], [$86.3$], [$129$], [$58.1$], [$81.6$], [$82.7$], [$206$], [$233$], [$464$],
table.hline(),
)
) <tab:slit_with>
次に、強度パターンの周期の測定結果を@tab:pattern に示す。
#figure(
caption: [強度パターンの周期の測定結果],
table(
columns: 10,
stroke: (none),
table.vline(x: 1, start: 1),
table.vline(x: 7, start: 1),
table.hline(),
table.header(
[],
table.cell(colspan: 6, "sincの周期"),
table.cell(colspan: 3, "cosの周期"),
),
table.hline(),
[], [SS1], [SS2], [SS3], [DS1], [DS2], [DS3], [DS1], [DS2], [DS3],
[長さ /pixel], [$95.5$], [$44.8$], [$30.3$], [$67.1$], [$46.7$], [$48.3$], [$17.5$], [$15.3$], [$8.67$],
[長さ /mm], [$14.8$], [$6.96$], [$4.70$], [$10.4$], [$7.25$], [$7.50$], [$2.72$], [$2.37$], [$1.35$],
table.hline(),
)
) <tab:pattern>
@tab:slit_with 、@tab:pattern の結果から、単スリットの場合、スリット幅が狭いほど、sincの周期が狭くなることが確認できた。ダブルスリットの場合もスリット幅が広いほど、回折強度パターンの周期が狭くなることが確認できる。また、スリット間隔が広いほど、cosの周期が狭くなることが確認できた。次に、これらの周期の実験値を理論値と比較した。
最後に、@tab:measure 、@tab:slit_with 、@tab:pattern の測定値を用いて、強度パターンの実験値と理論値を比較した結果を@tab:compare に示す。
#figure(
caption: [強度パターンの実験値と理論値の比較],
table(
columns: 10,
stroke: (none),
table.vline(x: 1, start: 1),
table.vline(x: 7, start: 1),
table.hline(),
table.header(
[],
table.cell(colspan: 6, "sincの周期"),
table.cell(colspan: 3, "cosの周期"),
),
table.hline(),
[], [SS1], [SS2], [SS3], [DS1], [DS2], [DS3], [DS1], [DS2], [DS3],
[実験値 /mm], [$14.8$], [$6.96$], [$4.70$], [$10.4$], [$7.25$], [$7.50$], [$2.72$], [$2.37$], [$1.35$],
[理論値 /mm], [$13.6$], [$7.07$], [$4.74$], [$10.5$], [$7.48$], [$7.38$], [$2.97$], [$2.62$], [$1.32$],
[相対誤差 /%], [$8.97$], [$1.68$], [$0.81$], [$0.90$], [$3.11$], [$1.61$], [$8.38$], [$9.54$], [$2.31$],
table.hline(),
)
) <tab:compare>
@tab:compare の結果から、実験値と理論値の相対誤差はどれも$10 %$以下に収まったことが確認できる。
== 4.2. 回折強度パターンのシミュレーション
まず単スリットの場合で、Octaveを用いて出力した、作成したスリット、光の回折強度を表すグラフ、回折像を@fig:slit、@fig:slit_wave、@fig:slit_screen、@fig:slit_0.2、@fig:slit_0.2_wave、@fig:slit_0.2_screen に示す。
#figure(
image("/figs/slit.png", width: 40%),
caption: [単スリット(幅: 0.1)]
) <fig:slit>
#figure(
image("/figs/slit_wave.png", width: 60%),
caption: [単スリットの関数]
) <fig:slit_wave>
#figure(
image("/figs/slit_screen.png", width: 40%),
caption: [単スリットのスクリーン]
) <fig:slit_screen>
#figure(
image("/figs/slit_0.2.png", width: 40%),
caption: [単スリット(幅: 0.2)]
) <fig:slit_0.2>
#figure(
image("/figs/slit_0.2_wave.png", width: 60%),
caption: [単スリットの関数(幅: 0.2)]
) <fig:slit_0.2_wave>
#figure(
image("/figs/slit_0.2_screen.png", width: 40%),
caption: [単スリットのスクリーン(幅: 0.2)]
) <fig:slit_0.2_screen>
これらの結果から、シミュレーション上でも、スリット幅が大きくなると、回折強度パターンの周期が狭くなることが確認できる。次に、ダブルスリットの場合で、スリット間隔を変えた場合の結果を@fig:double_slit、@fig:double_slit_wave、@fig:double_slit_screen、@fig:double_slit_1.8、@fig:double_slit_1.8_wave、@fig:double_slit_1.8_screen に示す。
#figure(
image("/figs/double_slit.png", width: 40%),
caption: [ダブルスリット(幅: 0.1, 間隔: 0.8)]
) <fig:double_slit>
#figure(
image("/figs/double_slit_wave.png", width: 60%),
caption: [ダブルスリットの関数(幅: 0.1, 間隔: 0.8)]
) <fig:double_slit_wave>
#figure(
image("/figs/double_slit_screen.png", width: 40%),
caption: [ダブルスリットのスクリーン(幅: 0.1, 間隔: 0.8)]
) <fig:double_slit_screen>
#figure(
image("/figs/double_slit_1.8.png", width: 40%),
caption: [ダブルスリット(幅: 0.1, 間隔: 1.8)]
) <fig:double_slit_1.8>
#figure(
image("/figs/double_slit_1.8_wave.png", width: 60%),
caption: [ダブルスリットの関数(幅: 0.1, 間隔: 1.8)]
) <fig:double_slit_1.8_wave>
#figure(
image("/figs/double_slit_1.8_screen.png", width: 40%),
caption: [ダブルスリットのスクリーン(幅: 0.1, 間隔: 1.8)]
) <fig:double_slit_1.8_screen>
これらの結果から、シミュレーション上でも、スリット間隔が大きくなると、小さい山の周期が狭くなることが確認できる。最後に、四角い形状のスリット、オリジナルのスリットの場合の結果を@fig:square_slit、@fig:square_slit_wave、@fig:square_slit_screen、@fig:icon_slit、@fig:icon_slit_wave、@fig:icon_slit_screen に示す。
#figure(
image("/figs/square_slit.png", width: 40%),
caption: [四角い形状のスリット(幅: 0.1)]
) <fig:square_slit>
#figure(
image("/figs/square_slit_wave.png", width: 60%),
caption: [四角い形状のスリットの関数(幅: 0.1)]
) <fig:square_slit_wave>
#figure(
image("/figs/square_slit_screen.png", width: 40%),
caption: [四角い形状のスリットのスクリーン(幅: 0.1)]
) <fig:square_slit_screen>
#figure(
image("/figs/icon_slit.png", width: 40%),
caption: [オリジナルのスリット(絵文字)]
) <fig:icon_slit>
#figure(
image("/figs/icon_slit_wave.png", width: 60%),
caption: [オリジナルのスリットの関数(絵文字)]
) <fig:icon_slit_wave>
#figure(
image("/figs/icon_slit_screen.png", width: 40%),
caption: [オリジナルのスリットのスクリーン(絵文字)]
) <fig:icon_slit_screen>
|
https://github.com/egorsmkv/pdf-generator-gradio | https://raw.githubusercontent.com/egorsmkv/pdf-generator-gradio/master/ui/templates/typst_template.typ | typst | = Test
Privided text:
{{ text }}
== Another
- Writing lists in a simple way is great.
- Nothing complex, start your points with `-`
and this will become a list.
- Indented lists are created via indentation.
+ Numbered lists start with `+` instead of `-`.
+ There is no alternative markup syntax for lists
+ So just remember `-` and `+`, all other symbols
wouldn't work in an unintended way.
+ That is a general property of Typst's markup.
+ Unlike Markdown, there is only one way
to write something with it.
I will just mention math ($a + b/c = sum_i x^i$)
is possible and quite pretty there:
$
7.32 beta +
sum_(i=0)^nabla
(Q_i (a_i - epsilon)) / 2
$
To learn more about math, see corresponding chapter.
|
|
https://github.com/Goldan32/brilliant-cv | https://raw.githubusercontent.com/Goldan32/brilliant-cv/main/modules/projects.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Projects")
#cvEntry(
title: [Multicore Rust on STM32H7 Microcontroller],
date: [2023],
society: [],
location: [],
description: list(
[A software framework that enables the utilization of both cores of an STM32H745 microcontroller],
[Provides examples of the two cores communicating and cooperating],
[Contains a dual-core demo application using ethernet and analog interfaces]
)
)
#cvEntry(
title: [Neural Network Evaluation on Xilinx SoC],
date: [2022],
society: [],
location: [],
description: list(
[Run pre-trained neural networks to perform facial recognition on a Xilinx evaluation board using Petalinux],
[Use gstreamer to preprocess images and handle video feeds]
)
)
#cvEntry(
title: [Firmware Update Software for AURIX TriCore Microcontroller],
date: [2021],
society: [],
location: [],
description: list(
[A secondary bootloader for an Infineon Aurix microcontroller],
[Implements Software Over The Air by receiving the new firmware image via TFTP],
[Activates the new image by handling the Aurix security features]
)
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chordx/0.2.0/src/single.typ | typst | Apache License 2.0 | #import "./utils.typ": parse-content, has-number
/// The single chords are chords without diagram used to show the chord name over a word.
///
/// - ..text-params (auto): Are the same parameters of *text* from the standard library of *typst*. *Required*.
/// -> function
#let new-single-chords(..text-params) = {
/// Is the returned function by *new-single-chords*.
///
/// - body (content): Is the word or words where the chord goes. *Required*.
/// - name (content): Displays the chord name over the selected words in the body. *Required*.
/// - position (content): Positions the chord over a specific character in the body. *Required*.
/// - ```typ []```: chord name centered on the body.
/// - ```typ [number]```: the chord name starts over a specific body character. (First position ```js [1]```)
let single-chord(
body,
name,
position
) = {
assert.eq(type(body), "content")
assert.eq(type(name), "content")
assert.eq(type(position), "content")
style(styles => {
let horizontal-offset = 0pt
let vertical-offset = 1.2em
let anchor = center
let body-size = measure(body, styles)
let name-size = measure(text(..text-params)[#name], styles)
let body-array = parse-content(body)
if position.has("text") {
assert(has-number(position.at("text")) == true, message: "the \"position\" must to be a \"content\" with only numbers")
let body-chars-offset = 0pt
let pos = int(position.at("text")) - 1
let min-pos = 0
let max-pos = body-array.len() - 1
pos = calc.clamp(pos, min-pos, max-pos)
for i in range(pos) {
body-chars-offset += measure([#body-array.at(i)], styles).width
}
// gets the char-offset to center the first character of
// the chord with the selected character of the body
let chord-char = parse-content(name).at(0)
let chord-char-width = measure(text(..text-params)[#chord-char], styles).width
let body-char-width = measure([#body-array.at(pos)], styles).width
let char-offset = (chord-char-width - body-char-width) / 2
// final horizontal offset
horizontal-offset = body-chars-offset - char-offset
anchor = left
}
let canvas = (
width: 0pt,
height: body-size.height + name-size.height + 0.8em,
dx: horizontal-offset,
dy: -vertical-offset
)
if horizontal-offset > 0pt and name-size.width + horizontal-offset >= body-size.width {
canvas.width = name-size.width + horizontal-offset
} else if horizontal-offset <= 0pt and name-size.width >= body-size.width {
canvas.width = name-size.width
} else {
canvas.width = body-size.width
}
box(
width: canvas.width,
height: canvas.height, {
place(
anchor + bottom,
dx: canvas.dx,
dy: canvas.dy,
text(..text-params)[#name]
)
place(
anchor + bottom,
box(..body-size, body)
)
}
)
})
}
return single-chord
}
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Languages/Cpp.typ | typst | #import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "Cpp 笔记",
lang: "zh",
)
= Cpp+ 笔记
== Cpp 面向对象
=== 关键字 this
- 感觉上跟 python 中的 self 差不多,只不过是隐式的指针常量
- 可以看看这两篇文章比较一下区别: #link("https://www.cnblogs.com/douzi2/p/5579608.html")[C++中的this和Python的self对比 - 宋桓公 - 博客园 (cnblogs.com)]、#link("https://muyuuuu.github.io/2022/05/12/Cpp-this-and-python-self/")[C++ 中的 this 和 Python 中的 self | Just for Life. (muyuuuu.github.io)]
- `const` 修饰的成员函数实际上是对 `this` 加 `const` 修饰,变为 ```cpp const 类名 *const this```
=== 静态成员 static
- 可以对函数也可以对变量,用 static 修饰后会使得这个成员变成类似 python 中的类变量,使得类也能调用这个成员(当然实例也还是可以,只不过共用了)
- 注意对静态成员函数而言,没有 this 这个关键字,因为是对类(或者说所有实例)而言,那 this 就失去意义;而且静态成员只能访问同样的静态成员变量和静态成员函数,因为如果是对类调用时没有实例给你访问
- static
#tlt(
columns: 2,
[Static free functions],
[#strike[Internal linkage] (deprecated)],
[Static global variables],
[#strike[Internal linkage] (deprecated)],
[Static local variables],
[Persistent storage],
[Static member variables],
[Shared by all instances],
[Static member function],
[Shared by all instances,can only access static member variables],
)
- A non-local static object is:
+ defined at global or namespace scope
+ declared static in a class
+ defined static at file scope
- Order of construction 在一个文件内是确定的,但在多个文件时是不确定的,因此 non-local static object 可能引发问题
- 解决方法是:拒绝 non-local static object,或者把这种都放在一个文件中,以免发生意料外的情况
=== 成员函数 Menber Function
==== 构造函数 & 析构函数 Constructors & Destructors <构造函数和析构函数>
- #link("https://www.runoob.com/cplusplus/cpp-constructor-destructor.html")[C++ 类构造函数 & 析构函数 | 菜鸟教程 (runoob.com)]
- 类构造函数
- 它需要被放在 public 中;不加 `void`、`int` 等返回类型;名字和类名相同。它可以用于为某些成员变量设置初始值(即初始化),并做一些操作比如输出初始化信息等。可以带参数,且可以配合成员初始化列表来使用
- 成员初始化列表(Member Initialization List):用于初始化类的成员变量
- 成员初始化列表和普通的类构造函数的区别在于:性能,以及对 const 变量、引用变量的处理。总之能用初始化列表就用初始化列表
- 注意按照声明的顺序初始化,而不是按照 list 里的顺序,否则将导致不可预测的结果(ub!),销毁的顺序则是相反的
- 参考:#link("https://zhuanlan.zhihu.com/p/386604081")[C++成员初始化列表 - 知乎 (zhihu.com)]、#link("https://www.cnblogs.com/BlueTzar/articles/1223169.html")[C++类构造函数初始化列表 - BlueTzar - 博客园 (cnblogs.com)]
- 类析构函数
- 它需要被放在 public 中;不加 `void`、`int` 等返回类型;名字和类名相同,前面带一个`~`;不能带参数。它会在每次删除所创建的对象时执行并释放资源,也可以同时做一些操作比如输出删除信息等
- Constructor 不能修饰为 virtual,而 Destructor 可以(而且更应该,如果它为基类的话);Constructor 能被 overloaded,而 Destructor 不能
- 拷贝构造函数(复制构造函数,Copy Constructor)
- 用于从一个已有的对象创建新的类对象。它需要被放在 public 中;不加 `void`、`int` 等返回类型;名字和类名相同。那如何与类构造函数区分呢?答案是参数,用对象的常量引用(否则用值传递会出现递归调用问题)
- 语法 ```cpp T(const T& w) {...}```
- 如果类的设计者不写复制构造函数,编译器就会自动生成复制构造函数。大多数情况下,其作用是实现从源对象到目标对象逐个字节的复制,即使得目标对象的每个成员变量都变得和源对象相等。编译器自动生成的复制构造函数称为“默认复制构造函数”
- 注意,默认构造函数(即无参构造函数)不一定存在(程序员写了就不会自动生成),但是复制构造函数总是会存在。一般默认复制构造函数也能工作得很好,但在涉及指针的时候需要小心(shallow or deep copy)
- 拷贝构造函数常见于三种情况:直接从一个对象创建并初始化另一个对象、函数创建形参需要复制一个对象、函数返回对象需要复制一个对象
- copy constructor 在返回值时的调用与否
```cpp
Person copy_func(char *who) {
Person local(who);
local.print();
return local; // copy ctor called!
}
Person nocopy_func(char *who) {
return Person(who);
} // no copy needed!
```
- 委托构造函数
- 委托构造函数使得部分初始化的代码更加简洁
- 使用了委托构造函数就不能在初始化列表中初始化其它成员。这种情况下可以用一个私有的构造函数实现目的,通过私有保证平时访问不到它
```cpp
class MyClass {
private:
int a, b;
// 私有构造函数,用于初始化所有成员
MyClass(int a, int b) : a(a), b(b) {}
public:
// 公有构造函数,委托给私有构造函数
MyClass(int a) : MyClass(a, 0) {}
// 公有构造函数,委托给私有构造函数
MyClass() : MyClass(0, 0) {}
};
```
- 移动构造函数
- [ ] 待补充
=== 友元函数 Friend Function
- 是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数
- 友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元
```cpp
public:
friend void friend_func(classname obj);
```
==== 类成员函数的修饰符
- 有以下这些:
- const, override, final, static, virtual, friend
- const 修饰
- `void print() const;` 类成员函数的声明语法,下面简称为常函数
- `const` 表示约定了不会在函数中修改对象(不要错误理解为成员函数是常量),并且通过引用、指针返回的值也是常量(实际上这个 `const` 是加在了 `this` 上)
- 但也有例外,用 `mutable` 修饰的成员变量可以在常函数中修改
- 另外,const 对象只能调用常函数,而不能调用非常函数
```cpp
class A {
public:
A(int x) : val(x) {}
// 不能注释,否则 const 对象没有 print() 函数
void print() const { cout << "const " << val << endl; }
// 可以注释掉,都用上面那个
void print() { cout << "no const " << val << endl; }
private:
int val;
};
int main() {
A ob1(1);
const A ob2(2);
ob2.print();
ob1.print();
}
```
=== 继承与多态 Inheritance & Polymorphism
==== 继承
- 类之间可以继承,被继承的叫做*基类(父类)*,继承的叫做*派生类(子类)*
- 基类可以是一个或多个,需要指定修饰符以指定继承方式(public, protected, private)
- 公有继承(public): public $arrow.r$ public, protected $arrow.r$ protected, private $arrow.r$ unavailable(can indirectly)
- 保护继承(protected): public, protected $arrow.r$ protected
- 私有继承(private): public, protected $arrow.r$ private
- 总而言之,同一个类可以访问自己的 public, protected, private;派生类只能不能访问 private;外部类不能访问 protected, private
- 这些特殊成员不能被继承:基类的构造函数(这个好像不太对)、析构函数和拷贝构造函数;基类的重载运算符;基类的友元函数
- Upcast 与 Return types relaxation
- 当把派生类的指针或引用赋给基类的指针或引用时,称为 upcast
```
Manager pete( "Pete", "444-55-6666", "Bakery");
Employee* ep = &pete; // Upcast
Employee& er = pete; // Upcast
```
- Return types relaxation 类似
- 继承中的构造、析构顺序
- 一个自己编的构造函数和初始化列表和析构函数和派生类的例子
```cpp
class C {
public:
C() { cout << 8; }
~C() { cout << 9; }
};
class A {
private:
int x;
public:
A () { cout << 0; }
A(int x) : x(x) { cout << 1; }
A(A& a) { cout << 2; }
~A() { if (x == 0) cout << 3; else cout << 4;}
void set_x(int x) { this->x = x; cout << 5; }
};
class B : public A {
private:
C c;
A a;
public:
B() : a(1) {
cout << 6;
A a(3);
}
~B() {
// 这里 A, c, a 还没被析构
cout << 7;
} // 这里 a, c, A 先后被析构
};
int main() {
B b;
return 0; // 0816147493
}
```
- Inheritance 中的覆盖与重定义
- 当在派生类中定义了与基类同名的函数,基类的函数(包括重载)会被隐藏
- virtual 关键字会改变这一行为,这就是多态
==== 多态与虚函数
- 当类之间存在*层次结构*,并且类之间是通过*继承*关联时,就会用到*多态*
- 但有时会因为*静态链接*(函数调用在程序执行前就准备好了,有时候这也被称为*早绑定*)而出错,这时需要用到 *virtual* 关键字,相应的,这种操作被称为*动态链接*,或*后期绑定*
- 虚函数只要声明了就一定要定义(实现),不然会报错。但有时我们无法在基类中给出确切的定义,这时候就需要定义*纯虚函数*:`virtual void func() = 0;`
- 为什么我们需要虚函数呢?纯虚函数用来规范派生类的行为,即接口。而在 python 中不需要这样是因为 python 具有独一套的框架环境体系
- 我们将包含纯虚函数的类称为抽象类,抽象类不能定义实例(因为它的 virtual 函数未定义,不是为了拿来用的,是为了给其他类提供一个可以继承的适当的基类),但可以声明指向实现该抽象类的具体类的指针或引用。
- 父类声明的纯虚函数或定义的虚函数在实现它的子类中就变成了虚函数,子类的子类即孙子类可以覆盖该虚函数,由多态方式调用的时候动态绑定。但我们也可以加个 final 让该子类的实现成为最终版本不再覆盖,如下
```cpp
class Base
{
public:
virtual void func() { // 或者也可以定义为纯虚函数
cout<<"This is Base, the beta version of func"<<endl;
}
};
class _Base: public Base
{
public:
void func() final { // 最终版本
cout<<"This is _Base, the final version of func"<<endl;
}
};
```
- virtual 虚函数
- 之前一直把虚函数理解为纯虚函数了,含有纯虚函数(函数只声明不定义)的类叫做*抽象基类*,不能实例化
- 抽象基类更进一步,Protocol/Interface classes,即*协议类*
- 其 variables 均为 static,其 member function 要么是 static 的,要么是 pure virtual 的
- 纯虚函数可以用 `=0` 显式标识
- 但是虚函数并不一定是纯虚函数,如下面 Circle 类的 render 函数
- 如果一个函数被声明为虚函数,那么在运行时,调用该函数的代码将根据对象的实际类型来决定调用哪个版本的函数。这就是所谓的*动态绑定*或*运行时多态性*。
- Cpp 多态和虚函数的机理、本质还是不太懂,或者说根本就没懂,好难
#quote(caption: "Copied from Zhr")[
#tab 多态 (polymorphism) 是面向对象编程的一个重要特性,它允许一个基类的指针指向一个派生类的对象,通过基类的指针调用派生类的成员函数。
多态可以通过虚函数 (virtual function) 来实现,虚函数可以通过在成员函数的前面加上 virtual 关键字来定义,这会让编译器在运行时动态绑定函数的地址。派生类重写的虚函数前面也可以加上 virtual 关键字作为提示,但不是必须的。
如果不想在基类中给出虚函数的实现,可以将虚函数定义为纯虚函数 (pure virtual function),形式为 virtual type func(args) = 0。这会让基类变为抽象类,无法实例化,只能作为接口使用。
为了确认派生类成功重写了基类的虚函数,可以在基类的虚函数后面加上 override 关键字,例如 void func() override { ... }。这样的话,如果派生类没有成功重写基类的虚函数,编译器便会报错。override 关键字可以和 final 关键字一起使用,例如 void func() final override { ... },顺序并不要紧。
]
- 一个例子
```cpp
class Ellipse : public Shape {
public:
Ellipse(float maj, float minr);
virtual void render(); // will define own
protected:
float major_axis, minor_axis;
};
class Circle : public Ellipse {
public:
Circle(float radius):Ellipse(radius, radius){}
virtual void render();
};
void render(Shape* p) {
p->render(); // calls correct render function
} // for given Shape!
void func() {
Ellipse ell(10, 20);
ell.render(); // static -- Ellipse::render();
Circle circ(40);
circ.render(); // static -- Circle::render();
render(&ell); // dynamic -- Ellipse::render();
render(&circ); // dynamic -- Circle::render()
}
```
- 总结:定义一个函数为虚函数,不代表函数为不被实现的函数。定义它为虚函数是为了允许用基类的指针来调用子类的这个函数。定义一个函数为纯虚函数,才代表函数没有被实现。定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序员必须实现这个函数。
== 重载函数和重载运算符 Overload
- Cpp 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。
- 当你调用一个重载函数和重载运算符时,编译器通过你所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。这被称为*重载决策*
- 重载函数:实现鸭子类型
- 在同一个作用域内,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同。比如,定义一个同名但对 int、double 类型做不同处理的函数
- 重载函数中的 const:#link("https://www.cnblogs.com/qingergege/p/7609533.html")[C++中const用于函数重载]
- 重载运算符
- 我们重载大部分 Cpp 内置的运算符,来达到一些特殊效果
- 所谓重载的运算符,是带有特殊名称的函数,由关键字 operator 和需要重载的运算符直接连接而成,重载运算符需要带参数和返回类型
- 运算符重载的同时也可以发生函数重载!
- 值得注意的是:运算重载符不可以改变语法结构、不可以改变操作数的个数、不可以改变优先级、不可以改变结合性
- 非友元函数的非成员函数是不能被重载的(重载只能用于对象相关)
#note(caption: "类重载、覆盖、重定义之间的区别")[
+ 重载是指同一个类中函数具有的不同的参数列表,而函数名相同的函数。重载要求参数列表必须不同,比如参数的类型不同、参数的个数不同、参数的顺序不同。如果仅仅是函数的返回值不同是没办法重载的,因为重载要求参数列表必须不同。
+ 覆盖是指子类重写从基类继承过来的函数。被重写的函数不能是 static 的,必须是 virtual 的。但是函数名、返回值、参数列表都必须和基类相同(发生在基类和子类)
+ 重定义也叫做隐藏,子类重新定义父类中有相同名称的非虚函数(参数列表可以不同)。
]
- 重载运算符,但是有一些是没法重载的,比如 `::`、`.*`、`?:`、`sizeof`、`typeid` 以及四种 `cast`
- 可能会疑惑 `.*` 是个啥
```cpp
class MyClass {
public:
int myNumber;
void myFunction() { std::cout << "Function Called" << std::endl; }
};
int main() {
MyClass obj;
int MyClass::*ptrToNumber = &MyClass::myNumber;
void (MyClass::*ptrToFunction)() = &MyClass::myFunction;
obj.*ptrToNumber = 45; // 使用 .* 运算符访问成员变量
std::cout << "myNumber: " << obj.*ptrToNumber << std::endl; // 输出: myNumber: 45
(obj.*ptrToFunction)(); // 使用 .* 运算符调用成员函数
return 0;
}
```
- 成员函数重载与非成员函数重载
- 对二元运算符而言,如果在类内重载,第一个参数是隐式的,否则如果在类外重载,第一个参数需要显式指定
- 除此之外,类内(member)和类外(global,通常会声明为 friend)还有诸多不同,比如是否会进行类型转换(前者不会后者会)等。
- 总而言之,单目运算符最好用类内,`=`、`[]`、`->`、`->*` 必须用类内,其它二元运算符最好用类外
- 参数和返回值应该是否应该引用或是常量?参考运算符原型是怎么写的
#fig("/public/assets/Languages/Cpp/img-2024-05-14-15-22-59.png")
- 以及赋值运算符(拷贝赋值运算符) `T& operator=(const T& other);` 返回引用以支持连续赋值
- 赋值运算符是 cpp 六大默认成员函数之一;它必须是一个成员函数;需要 delete 掉原有的资源,然后再分配新的资源(重要!)
- operators `++` 和 `--`
- 怎么记呢?前缀用引用返回,后缀加个参数(编译器自动补 $0$),分别返回左值和右值
```cpp
const Integer& operator++(); // prefix++
const Integer operator++(int); // ++postfix
const Integer& operator--(); // prefix--
const Integer operator--(int); // --postfix
```
- 关系运算符
- implement `!=` in terms of `==`
- implement `>`, `>=`, `<=` in terms of `<`
```cpp
bool operator==(const Integer& rhs) const;
bool operator!=(const Integer& rhs) const;
bool operator<(const Integer& rhs) const;
bool operator>(const Integer& rhs) const;
bool operator<=(const Integer& rhs) const;
bool operator>=(const Integer& rhs) const;
```
== Cpp 类型
=== 基础类型
- 一些基础类型的大小
```cpp
std::cout << sizeof(int) << std::endl; // 4
std::cout << sizeof(long) << std::endl; // 4
std::cout << sizeof(long long) << std::endl; // 8
std::cout << sizeof(void*) << std::endl; // 8
```
=== class, struct, union
- cpp 的 struct 实际上已经扩充到和 class 差不多了,只有细微的差别
- 也就是说,struct 现在几乎也可以当做 class 来使用了
- 习惯上,不涉及数据处理的方法的数据类型封装才会用 struct,否则使用 class。也就是依然当做 C 中的 struct 使用
- Union(联合)是一种用于节省空间的特殊的结构体(or 类?),它的所有成员共用一个内存空间,只能同时存储一个值。
- 与结构体类似,有匿名和非匿名两种
- 可以为联合的成员指定长度,通过冒号操作符实现更精细的控制
```cpp
union U {
unsigned short int aa; // 要么用这个
struct { // 要么用这个
unsigned int bb : 7;//(bit 0-6)
unsigned int cc : 6;//(bit 7-12)
unsigned int dd : 3;//(bit 13-15)
};
} u; // 总共 16 位,2 字节
```
=== 类型转换 Type Conversion
- 类型转换
- cpp 会使用单参数构造函数和 implicit conversion operator 进行隐式类型转换
- 可以通过 explicit 关键字来阻止
- 类型转换运算符
+ 必须是成员函数,不能是友元函数 ,因为转换的主体是本类的对象。不能作为友元函数或普通函数
+ 没有参数,因为是把自己转换,无需参数
+ 不能指定返回类型,因为返回类型同函数名
+ 编译器会在 X $=>$ T 时调用它
```cpp
X::operator T() const {
}
```
- 事实上,使用这种东西会导致很多预想不到的问题,因此最好不要使用,或者使用“人为” explicit 的类型转换
```cpp
T to_T() const;
```
- Casting operators
- #link("https://zhuanlan.zhihu.com/p/151744661")[Cpp 四种 cast]
- static_cast: explicit type conversion, not safe for object pointers(但反过来,也不会增加检查的开销)
+ 基本类型的转换,比如 `int` 转 `char`
+ 类的 upcast,子类的指针或者引用转换为基类(安全)
+ 类的 downcast,基类的指针或引用转换为子类(不安全,没有类型检查)
- dynamic_cast: 只能用在指向类的指针或引用,允许 upcast 和 downcast(当不完整时返回 nullptr)
+ 类的 upcast,子类的指针或引用转化为基类(安全)
+ 类的 downcast,基类的指针或引用转化为子类(安全,有类型检查)
- const_cast: add or removes constness for 指针、引用、对象
- reinterpret_cast: 数据和指针(引用)之间的转换,最自由,没有类型检査
== 函数 Function
=== 内联函数 Inline Function
- 在函数前加一个 inline 的修饰
- 免去函数开销,如同预编译指令(跟 macro 很像,但更复杂更偏向编译层面)
- 比 macro 好,因为有类型检查
- 它的 declaration 等同于 definition(?)
- inline 是用于实现而非声明,因此它应当被加在函数定义前而不是函数声明前
- 最好放置在头文件中
- inline 不一定会被编译器实现(当函数太大或者递归)
- class 中的函数默认都是 inline 的,class 外的函数则不会
- 内联函数并不是 Cpp 相对 C 独有的,不过在 Cpp 中用的更多(隐式内联)
- 参考:
+ #link("https://blog.csdn.net/qq_35902025/article/details/127912415")[内联函数详解(搞清内联的本质及用法)\_c++内联函数\_赵大宝字的博客-CSDN博客]
+ #link("https://www.cnblogs.com/zsq1993/p/5978743.html")[内联函数的声明和定义]
=== 函数默认参数 Default Arguments
- C++ 允许在函数声明或定义中为一个或多个参数指定默认值,这样在调用函数时可以忽略这些参数
- 它们必须从右向左添加默认值,否则会报错
```cpp
int harpo(int n, int m = 4, int j = 5);
int chico(int n, int m = 6, int j); //illeagle
```
- 当函数采用先声明后定义的方式时,只能在声明中指定默认值,而不能在定义中指定默认值
- 在底层,其实也是利用了函数重载实现。所以一般来说慎用默认参数,不如自己显式地重载
=== 匿名函数 Lambda Function <Lambda>
- 匿名函数的概念等很好理解,这里不多赘述
- 匿名函数的优点
+ 可以就地定义,比函数更方便
+ 局部作用域更容易控制,有助于减少命名冲突
+ 利用捕获机制自动捕获上下文中的变量,比普通函数更方便
+ 结合 std::function, std::bind 使用达成更多功能,参考 #link("http://www.debugself.com/2017/09/20/cpp_bind_fun/")[c++11 function、bind用法详解]
- 格式为:```Cpp [捕获列表](参数列表) mutable throw(...) -> return_type { /* body */ } ```
+ *可能为空的*捕获列表,指明定义环境中的那些变量能被用在 lambda 表达式内,以及这些变量的捕捉形式
+ *可选的*参数列表,指明 lambda 表达式所需的参数
+ *可选的* mutable 修饰符,指明该 lambda 表达式可能会修改它自身的状态(即改变通过值捕获的变量的副本)
+ *可选的* `->` 形式的返回类型声明
+ 表达式体,指明要执行的代码
- 捕获的举例如下:
+ `[]`,空捕获列表,不捕获任何变量,此时引用外部变量则会提示编译错误
+ `[=]`,默认按值捕获全部变量
+ `[&]`,默认按引用捕获全部变量
+ `[=,&x,&y]`,默认按值捕获全部变量,但是变量 `x, y` 按引用捕获
+ `[=,x,y]`,编译出错,变量 `x, y` 按值捕获,和默认按值捕获全部变量重复
+ `[x,y]`,只按值捕获变量 `x, y`
+ `[&x,&y]`,只按引用捕获变量 `x, y`
+ `[=x,=y]`,编译出错,应为 `[x, y]`
+ `[this]`,捕获 this 指针,然后在 Lambda 表达式内部就可以直接引用类成员了
- 参数列表,和普通函数一样,不赘述
- mutable
```cpp
int x = 1;
auto f=[x]() {x++;}; // 编译错误,不能修改x的值
f();
```
- 但是如果加上 `mutable` 就可以了(但由于是值捕获,所以不会改变外部变量的值)
- `throw`,跟普通函数一样,不赘述
- 返回类型
- 一般情况下,编译器会自动推断出 lambda 的返回类型。但是如果函数体里面有多个返回语句,或者有一些常量 return 返回时候,编译器可能无法自动推断
- 函数体:注意匿名函数外面最后需要添加一个 `;` 分号
- 匿名函数的实质
- 每当你定义一个 lambda 表达式后,编译器会自动生成一个匿名类(这个类当然重载了 `()` 运算符),我们称为闭包类型(closure type)
- 例子
```cpp
int x = 1;
auto f = [x]() mutable { x++; cout<< x <<endl; };
f(); // 2
f(); // 3
```
- 泛型:赋值给 auto
=== 可调用对象 Callable Object <Callable_Object>
- 类似于 Python 那样把函数当作变量传递
- 参考:
+ #link("https://www.cnblogs.com/tuapu/p/14167159.html")[C++11中的std::bind和std::function]
+ #link("https://cloud.tencent.com/developer/article/2388825")[理解C++ std::function灵活性与可调用对象的妙用]
- [ ] 待补充
== 引用 Reference
- 引用是已经存在的某个变量的别名,一旦把引用初始化为某个变量,就可以通过这个别名来访问那个变量
- 引用的作用可以借由指针来理解,但又不同于指针
- 不存在空引用,引用必须连接到一块合法的内存
- 引用必须在创建时被初始化。指针可以在任何时间被初始化
- 引用初始化后就不能指向其他对象或者重复初始化为其他对象,指针可以在任何时间指向其他对象
- 引用在底层是一个 `T *const`
- 引用的简单例子
```cpp
int i = 1;
int &j = i; // j 是 i 的引用
```
- 引用作为函数参数的例子,很简单就略去了
- 引用作为函数返回值的例子,相对复杂一些,说是可以使程序更易读,虽然我看半天反应不过来
```cpp
include <iostream>
using namespace std;
double vals[] = {10.1, 12.6};
double& setValues(int i) {
double& ref = vals[i];
return ref; // 返回第 i 个元素的引用,ref 是一个引用变量,ref 引用 vals[i]
}
int main ()
{
cout << "改变前的值" << endl;
for (int i = 0; i < 2; i++)
cout << "vals[" << i << "] = " << vals[i] << endl;
setValues(1) = 20.23; // 改变第 2 个元素
cout << "改变后的值" << endl;
for (int i = 0; i < 2; i++)
cout << "vals[" << i << "] = " << vals[i] << endl;
return 0;
}
```
- 引用的本质就是常量指针
- 关于值传递、指针传递、引用传递的选择
#info(caption: [Tips])[
- Pass in an object if you want to store it
- Pass in a const pointer or reference if you want to get the values
- Pass in a pointer or reference if you want to do something to it
- Pass out an object if you create it in the function
- Pass out pointer or reference of the passed in only
- Never new something and return the pointer
]
==== 左值引用和右值引用 <左值引用和右值引用>
- 左值与右值
- 左值(Lvalue)和右值(Rvalue)是根据表达式是否可以*在赋值操作中作为左侧项*来区分的,或者可以通过是否能取地址和是否有名字来区分
- 左值(Lvalue):左值是一个表达式,它指向内存中的一个固定地址。左值通常指的是变量的名字,它们在程序的整个运行期间都存在
- 右值(Rvalue):右值是一个临时的、不可重复使用的表达式。右值通常包括字面量、临时生成的对象以及即将被销毁的对象
- 移动语义
- 移动语义涉及右值引用(`type&&`),用于绑定临时对象和 `std::move()` 函数返回的对象,它的目的是更精细地控制内存分配,加快程序运行速度
- `std::move()` 将一个对象的左值引用转换为右值引用,实质上是一个静态类型转换,告诉编译器将一个左值当作右值来处理
- 默认成员函数又多了移动构造函数和移动赋值操作符函数
- 可以看这篇文章,很通透 #link("https://zhuanlan.zhihu.com/p/455848360")[一文入魂:妈妈再也不担心我不懂C++移动语义了]
- 完美转发
- 完美转发是指在函数模板中保持参数的原始类型,不改变参数的类型,不改变参数的左值或右值属性
- 一个经典例子
```cpp
void process(int& i) {
std::cout << "处理左值: " << i << std::endl;
}
void process(int&& i) {
std::cout << "处理右值: " << i << std::endl;
}
// 完美转发的函数模板
template<typename T>
void logAndProcess(T&& param) {
// 调用 process 函数,同时保持param的左值 / 右值特性
process(std::forward<T>(param));
}
int main() {
int a = 5;
logAndProcess(a); // a 是左值,将调用处理左值的重载
logAndProcess(10); // 10 是右值,将调用处理右值的重载
return 0;
}
```
== 指针 Pointer
- 原始指针跟 C 里面应该没什么区别
==== 智能指针
- 智能指针是封装了原生指针的类模板,用于自动管理对象的生命周期,主要有 `unique_ptr`, `shared_ptr`, `weak_ptr`,在 `<memory>` 头文件中
- 从三个层次理解智能指针:
+ 用一种叫做 RAII(Resource Acquisition Is Initialization,资源获取即初始化)的技术对普通指针进行封装,使得智能指针实质是一个对象,行为表现得却像一个指针
+ 作用是确保动态资源得到安全释放,避免内存泄漏
+ 还有一个作用是把值语义转换成引用语义
- `unique_ptr`
- 不能拷贝和赋值,只能移动
- 什么时候用?相比原始指针确保动态资源能得到释放,相比 `shared_ptr` 开销小,大多数场景下用到的应该都是 `unique_ptr`
- `shared_ptr`
- 是 `unique_ptr` 的两倍空间,维护了一个引用计数,当引用计数为 0 时自动释放资源
- 什么时候用?通常用于一些资源创建昂贵比较耗时的场景, 比如涉及到文件读写、网络连接、数据库连接等。当需要共享资源的所有权时,例如,一个资源需要被多个对象共享,但是不知道哪个对象会最后释放它
- `weak_ptr`
- 用于解决 `shared_ptr` 的循环引用问题
- 什么时候用?当两个对象相互引用,且其中一个对象是 `shared_ptr` 类型时,会导致循环引用,从而导致内存泄漏。此时可以使用 `weak_ptr` 来解决这个问题
- 例子
```cpp
int main() {
{
std::unique_ptr<int> uptr(new int(10)); // 绑定动态对象
//std::unique_ptr<int> uptr2 = uptr; // 不能赋值
//std::unique_ptr<int> uptr2(uptr); // 不能拷贝
std::unique_ptr<int> uptr2 = std::move(uptr); // 转换所有权
uptr2.release(); // 释放所有权
} // 超过 unique_ptr 的作用域,自动释放
{
int a = 10;
std::shared_ptr<int> ptra = std::make_shared<int>(a);
std::shared_ptr<int> ptra2(ptra); // copy
std::cout << ptra.use_count() << std::endl;
int b = 20;
int *pb = &a;
// std::shared_ptr<int> ptrb = pb; \/\/ error,需要转换为 shared_ptr
std::shared_ptr<int> ptrb = std::make_shared<int>(b);
ptra2 = ptrb;
pb = ptrb.get();
std::cout << ptra.use_count() << std::endl;
std::cout << ptrb.use_count() << std::endl;
}
}
```
- 参考
+ #link("https://www.cnblogs.com/rebrobot/p/18215501")[现代 C++ 智能指针详解:原理、应用和陷阱]
+ #link("https://www.cnblogs.com/wxquare/p/4759020.html")[C++11 中智能指针的原理、使用、实现
]
== 常量 Constant
- Run-time constant 和 Compile-time constant
```cpp
const int x = 123; // x 为编译时常量(Compile-time constant),123为字面量(literal)
// 在这种简单的情况下,编译器会直接把x优化为汇编里的立即数,存储在静态存储区
cin >> size;
const int SIZE = size; // SIZE为运行时常量(Runtime constant),只有运行的时候才能知道常量的值
// 因此编译器只能把它设置成变量,然后保证它不会被修改,这样就会存储在栈或堆里,跟普通变量一样
// 这里的 const 纯粹是编译器帮你检查的工具,对二进制来说完全是透明的
// 所以实际上更好的叫法是只读 readonly
```
- 修改常量
```cpp
const int a = 1;
int size;
cin >> size; // input 1
const int SIZE = size;
cout << a << ", " << SIZE << endl;
int* p = (int*)&a; // 不会成功,因为 a 是 compile-time constant
*p = 10;
p = (int*)&SIZE; // 会成功,因为 SIZE 是 run-time constant
*p = 10;
cout << a << ", " << SIZE << endl;
// p = *const_cast<string*>(&a); // const cast 只能调节类型限定符;不能更改基础类型
// *p = 10; // 也就是说,如果它不是基础类型,compile-time constant 还真能这样改
cout << a << ", " << SIZE << endl;
```
- 关于可变长数组和 Run-time constant:
```cpp
int x;
cin >> x;
const int size = x;
double classAverage[size]; // error!
```
- 说是会报错,但实际上,只要不用 msvc 编译器,就不会
- C99 引入的特性,C++ 也支持
- Compile-time constants in classes
```cpp
class HasArray {
const int size=1;
int array[size]; // ERROR!
};
```
- 这样会报“非静态成员引用必须与特定对象相对”的错(在没有创建对象的情况下访问非静态成员)
- 解决办法是声明为 `static const int size=1;`
- 或者使用匿名枚举 hack: `enum { size = 1 };`(编译时会被替换为 1)
- 指针常量和常量指针
```cpp
int a = 1, b = 2;
int* const p = &a; // 指针常量,指针是常量,但指向内容不是
const int* q = &a; // 常量指针,指针指向内容是常量,但指针不是
// 或者写为 int const *q = &a; 效果是一模一样的
*p = 9; // 成功
// p = &b; // 错误
// *q = 9; // 错误
q = &b; // 成功
a = 3; // 但无论哪种,都不妨碍直接改 a
```
== 模板 Template
- 模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数、返回值取得任意类型。
- 通俗来讲,就是让程序员编写与类型无关的代码,而专注于语义实现。比如编写了一个交换两个 int 类型的 swap 函数,那它不重载就无法交换 double 类型。
- 模板通常有两种形式:函数模板和类模板
- 函数模板针对仅参数类型不同的函数
- 类模板针对仅数据成员和成员函数类型不同的类
- 注意:模板的声明或定义只能在全局,命名空间或类范围内进行。即不能在局部范围,函数内进行
- 函数模板的格式
```cpp
template <class 形参名, class 形参名, ......> 返回类型 函数名(参数列表)
{ ... }
```
- 类模板的格式
```cpp
template <class 形参名, class 形参名, ......> class 类名
{ ... };
```
- 一个结合的例子
```cpp
template<class T> class A{
public:
T g(T a,T b);
A();
};
template<class T> A<T>::A() {}
template<class T> T A<T>::g(T a,T b) {
return a+b;
}
int main(){
A<int> a;
cout<<a.g(1,2)<<endl;
return 0;
}
```
- 不能为同一个模板类型形参指定两种不同的类型(针对函数模板)
- 针对 Template functions:在输入参数的时候不会进行类型检查,也不会做隐式或显式类型转换。比如 `template<class T>void h(T a, T b){}`,语句调用 `h(2, 3.2)` 将出错,因为该语句给同一模板形参T指定了两种类型,第一个实参 `2` 把模板形参 `T` 指定为 `int`,而第二个实参 `3.2` 把模板形参指定为 `double`,两种类型的形参不一致,会出错。
- 针对 Template classes:当我们声明类对象为:`A<int> a`,比如 `template<class T>T g(T a, T b){}`,语句调用 `a.g(2, 3.2)` 在编译时不会出错,但会有警告,因为在声明类对象的时候已经将 `T` 转换为 `int` 类型,而第二个实参 `3.2` 把模板形参指定为 `double`,在运行时,会对 `3.2` 进行强制类型转换为 `3`。当我们声明类的对象为:`A<double> a`,此时就不会有上述的警告,因为从 `int` 到 `double` 是自动类型转换。
- 类型形参与非类型形参
- 前面那些 `T` 就是类型形参,指代之后实例化时的类型;还有非类型形参
- 非类型形参只能是常量(或常量表达式),另外只能是整型,指针和引用
- 非类型模板参数(non-type template parameter)常常用在容器的上限之类的地方。在 cpp17 后,这个 parameter 甚至可以是 auto 来让编译器自行推断
```cpp
template <class T, int bounds = 100>
class FixedVector{
private:
T elements[bounds]; // fixed size array!
}
```
- 参考:#link("https://www.runoob.com/w3cnote/c-templates-detail.html")[C++ 模板详解 | 菜鸟教程 (runoob.com)]
- 模板和继承
- 好像没什么好说的,基类是不是模板类以及派生类是不是模板类四种情况都支持
- Simulate virtual function in generic programming
- OOP PPT 38 页,没看懂,有点自指的感觉
- typename 与 template
- #link("https://feihu.me/blog/2014/the-origin-and-usage-of-typename/")[关于 typename]
- traits based design & policy based design
- 又没看懂
- template template parameters
==== 模板特化
- 不同与模板实例化。常用在为一个特定的类型提供特殊的实现
- 对多个模板参数还分为*偏特化*和*全特化*
- 比如下面的例子中,我们实现了两个类型的比较,它适用于大多数类型如 `int`, `double`,但无法用于 `char*`,这时需要函数模板特化
```cpp
#include <iostream>
#include <cstring>
// 一般的函数模版
template <class T>
int compare(const T left, const T right) {
std::cout <<"in template<class T>..." <<std::endl;
return (left - right);
}
// 这个是一个特化的函数模版
template < >
int compare<const char*>(const char* left, const char* right) {
std::cout << "in special template< >..." <<std::endl;
return strcmp(left, right);
}
// 特化的函数模版, 两个特化的模版本质相同, 因此编译器会报错
// error: redefinition of 'int compare(T, T) [with T = const char*]'|
// template < >
// int compare(const char* left, const char* right) {
// std::cout << "in special template< >..." <<std::endl;
// return strcmp(left, right);
// }
// 这个其实本质是函数重载,跟模版特化没有关系,但是会优先调用它
int compare(char* left, char* right) {
std::cout <<"in overload function..." <<std::endl;
return strcmp(left, right);
}
int main() {
compare(1, 4);
const char *left = "gatieme";
const char *right = "jeancheng";
compare(left, right);
return 0;
}
```
== Namespace
- Namespace
- `using` 既可以对某个 namespace,也可以是对 namespace 内的某个 object
- namespace aliases
- namespace composition
- 如果两个 namespace 有相同的 object,采用先出现的那个
- namespace selection
- multiple namespace(same name): 同名的多个 namespace——叠加
== File I/O
- 首先引入头文件 `#include <fstream>`,其中包含三个类:ofstream、ifstream、fstream,分别用于写、读、读写(包括两个功能)
- 打开文件与关闭文件
```cpp
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc ); // 写入模式打开文件
ifstream infile;
infile.open("file.dat", ios::out | ios::in ); // 读取模式打开文件
outfile.close(); // 关闭文件
infile.close(); // 关闭文件
```
- 打开文件的第一个参数是文件名,第二个参数是打开模式。打开模式有:ios::in(输入)、ios::out(输出)、ios::ate(定位到文件尾)、ios::app(追加)、ios::trunc(删除原有内容)。具体参见 #link("https://www.runoob.com/cplusplus/cpp-files-streams.html")[C++ 文件和流 | 菜鸟教程 (runoob.com)]
- 至于具体的读写操作,就是用 `<<` 和 `>>`,用法与 cin、cout 类似。给出写入文件的例子
```cpp
#include <fstream>
#include <iostream>
using namespace std;
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
outfile << "Hello, World!" << endl;
outfile.close();
```
== 异常 Exception
- Objects on stack destroyed properly
- try-catch 在执行时会应用基类转换
```cpp
class MathErr {
// ...
virtual void diagnostic();
};
class OverflowErr : public MathErr { }
class UnderflowErr : public MathErr { }
class ZeroDivideErr : public MathErr { }
try {
throw UnderFlowErr(); // code to exercise math options
} catch (ZeroDivideErr& e) {
// handle zero divide case
} catch (MathErr& e) {
// handle other math errors
} catch (...) {
// any other exceptions
}
```
- 在 `catch` 中还可以再次重抛异常 `throw;` (后面不用跟任何东西),用于告诉上级代码这里出问题了
- 函数的 exception specifications
- 用跟成员初始化列表类似的语法,但是成员函数和非成员函数都可以用
- 不在编译时刻检查,而是在运行时刻抛出 `unexpected` 异常
- 这个 `: throw()` 的语法好像错了,删掉 `:` 才能过编译
```cpp
PrintManager::print(Document&) : throw(BadDocument) {
... // raises or doesn’t handle BadDocument
}
void goodguy() : throw() { // 显式说明不会抛出任何异常(会处理所有异常),c++11 后应当使用 noexcept 关键字
... // handles all exceptions
}
void average() {
... // no spec, no checking(他可能会抛出任何异常)
}
```
- 如果在 constructors 中使用 `throw`,确保先释放已经分配的资源;destructors 中无法抛出异常(因此如果发生异常,程序会直接寄掉)
- Destructors and exceptions
- Destructors 在 object exits from scope 时被调用,或者抛出 exception 时清空 stack 上资源时被调用(在栈中的本地变量都会被正确析构,但 `throw` 出来的东西直到 `catch` 之后才被析构)
- 如果在 exception 中,调用的 destructor 也抛出异常,那么程序会唤起 `std::terminate()` 来终止程序
- 最好用 reference 来捕捉引用
- 使用 value 捕捉需要额外拷贝且会产生 slicing problem(派生异常被基异常捕捉,将会被截断)
- 使用 pointer 捕捉导致正常代码和异常处理代码的耦合
- #link("https://blog.csdn.net/u014038273/article/details/77816762")[C++之通过引用(reference)捕获异常(12)---《More Effective C++》]
- 没有被捕捉的异常会唤起 `std::terminate()` 来终止程序,但是可以通过 `std::set_terminate()` 来设置自定义的终止函数(甚至设置一个不终止的函数来拦截)
- 标准 exception 类
```cpp
class exception{
public:
exception () throw(); //构造函数
exception (const exception&) throw(); //拷贝构造函数
exception& operator= (const exception&) throw(); //运算符重载
virtual ~exception() throw(); //虚析构函数
virtual const char* what() const throw();
//虚函数,用于描述错误的具体情况
//继承的时候要override这个what()函数
};
```
- #link("https://www.baiy.cn/doc/cpp/inside_exception.htm")[C++异常机制的实现方式和开销分析]
== OOP 复习时的一些易错题
- 这些易错题感觉还是比较深入的,对 cpp 机理的理解要求比较高
```cpp
#include <iostream>
struct A {
virtual void f() { std::cout << "Af" << std::endl; }
virtual void f(int) { std::cout << "Afi" << std::endl; }
virtual void f(int, int) { std::cout << "Afii" << std::endl; }
};
struct B : A {
void f() override { std::cout << "Bf" << std::endl; }
void f(int) override { std::cout << "Bfi" << std::endl; }
};
struct C : B {
void f() override { std::cout << "Cf" << std::endl; }
};
int main() {
C xxx;
C* c = &xxx;
B* b = &xxx;
A* a = &xxx;
// for each one of the following calls, determine the output
// or if it causes a compile error
a->f(); // output or compile error?
a->f(1); // output or compile error?
a->f(1, 2); // output or compile error?
b->f(); // output or compile error?
b->f(1); // output or compile error?
// b->f(1, 2); // output or compile error?
c->f(); // output or compile error?
// c->f(1); // output or compile error?
// c->f(1, 2); // output or compile error?
return 0;
}
```
```cpp
#include <iostream>
using namespace std;
class A{
public:
void F(int) { cout << "A:F(int)" << endl; }
void F(double) { cout << "A:F(double)" << endl; }
void F2(int) { cout << "A:F2(int)" << endl; }
};
class B : public A {
public:
void F(double) {
cout << "B:F(double)" << endl;
}
};
int main() {
B b;
b.F(2.0); // B:F(double)
b.F(2); // B:F(double)
b.F2(2); // A:F2(int)
}
```
```cpp
class C {
public:
explicit C(int) {
std::cout << "i" << std::endl;
}
C(double) {
std::cout << "d" << std::endl;
}
};
int main() {
C c1(7); // "i"
C c2 = 7; // "d"
}
```
```cpp
struct A {
virtual void foo(int a = 1) {
std::cout << "A" << '\n' << a;
}
};
struct B : public A {
virtual void foo(int a = 2) {
std::cout << "B" << '\n' << a;
}
};
int main () {
A* a = new B;
a->foo(); // B, then 1
}
```
```cpp
class A {
public:
static void f(double) { std::cout << "f(double)" << std::endl; }
void f(int) { std::cout << "f(int)" << std::endl; }
};
int main() {
A a;
const A b;
a.f(3); // f(int)
b.f(3); // f(double)
}
```
```cpp
int f(int a) {
return ++a;
}
int g(int &a) {
return ++a;
}
int main() {
int i = 0, j = 0, m = 0, n = 0;
i += f(i);
j += g(j); // pay attention to '+='
cout << "i=" << i << endl; // i=1
cout << "j=" << j << endl; // j=2
}
```
```cpp
class A {
public:
A() { cout << "A()" << endl;}
~A() {cout << "~A()" << endl;}
};
class B : public A {
public:
B() { cout << "B()" << endl;}
~B() {cout << "~B()" << endl;}
};
int main() {
A* ap = new B[2]; // A() A() B() B()
delete ap; // 调用了 A 的析构函数,然后段错误(?
}
```
== 属性
- “属性”是 C11 标准中的新语法,用于让程序员在代码中提供额外信息。相较于风格各异的传统方式(`attribute`, `__declspec`, `#pragma`...),“属性”语法致力于将各种“方言”进行统一。
- 我们有理由担心属性的大量使用会引起 C++ 语言的混乱,很可能将产生很多 C++ 语言的“方言”。所以,我们推荐仅在不影响源代码的业务逻辑的前提下,才使用属性来帮助编译器作更好的错误检查(例如,`[[noreturn]]`,或者是帮助代码优化(例如,`[[carries_dependency]]`)
- 一些简单的例子:
```cpp
// 使用[[nodiscard]]避免忽略重要返回值
[[nodiscard]] int calculateImportantValue() {
// ... 计算逻辑 ...
return result;
}
void someFunction() {
calculateImportantValue(); // 编译器将警告此行忽略了返回值
}
// 利用[[likely]]和[[unlikely]]指导优化
void processCondition(bool condition) {
if ([[likely]] condition) {
// ... 常见情况处理 ...
} else {
// ... 较少发生的情况 ...
}
}
```
== 其它
- `std::optional`,C++17 新增的模板类,用于表示一个可能为空的值
= Cpp 新特性整理
== C++11
- 成员初始化列表,参见 @构造函数和析构函数
- 移动语义,参见 @左值引用和右值引用
- Lambda 表达式,参见 @Lambda
- 可调用对象,参见 @Callable_Object
- 智能指针
== C++14
- Lambda 表达式的泛型
== C++17
- if 和 switch 语句中初始化变量
- 字面意思,好处在于不用在外面初始化,而且不会污染外部作用域
-
= Cpp STL 库整理
- 一些通用的方法
- Vector
- 内部用
```cpp
```
- List
- 内部用双向链表实现
```cpp
list<int> l;
```
- Stack
-
```cpp
```
#quote(caption: "Copied from Zhr")[
- 常见容器的迭代器类型如下:
+ 有随机访问迭代器的容器包括 vector, deque, array
+ 有双向迭代迭代器的容器包括 list, set, map, multiset, multimap
+ 有前向迭代迭代器的容器包括 forward_list, unordered_set, unordered_map, unordered_multiset, unordered_multimap
+ 不支持迭代器的容器包括 stack, queue, priority_queue
- 除了常见的 iterator 类型以外,STL 容器还提供了 const_iterator 类型,它只能访问容器中的常量元素,不能修改元素的值。而对于支持双向迭代器的容器,STL 容器还提供了 reverse_iterator 和 const_reverse_iterator 类型,它们可以逆序访问容器中的元素。
- 支持迭代器的容器一般都有以下方法:
+ `begin()` 返回指向容器第一个元素的迭代器
+ `end()` 返回指向容器最后一个元素的下一个位置的迭代器
+ `cbegin()` 返回指向容器第一个元素的常量迭代器
+ `cend()` 返回指向容器最后一个元素的下一个位置的常量迭代器
+ `rbegin()` 返回指向容器最后一个元素的反向迭代器
+ `rend()` 返回指向容器第一个元素的前一个位置的反向迭代器
]
|
|
https://github.com/dyc3/senior-design | https://raw.githubusercontent.com/dyc3/senior-design/main/lib/use-cases.typ | typst | #let usecase(title, description: none, stakeholders: (), basic_flow: (), alt_flows: (), prereq: (), diagram: none) = {
let content = ()
if stakeholders.len() > 0 {
content.push([*Stakeholders*
#list(..stakeholders)
])
}
if description != none {
content.push([*Description*
#description])
}
if diagram != none {
content.push([*Diagram*: #diagram])
}
if prereq.len() > 0 {
content.push([*Prerequisites*
#list(..prereq)
])
}
if basic_flow.len() > 0 {
content.push([*Basic Flow*
#list(..basic_flow)
])
}
if alt_flows.len() > 0 {
for alt_flow in alt_flows {
content.push([*Alternate Flow*
#list(..alt_flow)
])
}
}
// prevent splitting individual blocks between pages
// content = content.map(c => {
// block(
// breakable: false,
// c,
// )
// })
figure(
align(left, table(
columns: 1,
..content,
)),
caption: figure.caption(
position: top,
title
),
supplement: [Use Case],
kind: "usecase",
)
}
#let userstory(stakeholder, want, why) = {
let content = [As a *#stakeholder*, I want *#want* so that *#why*]
figure(
[],
caption: content,
supplement: [User Story],
kind: "userstory",
)
}
= Testing
#usecase(
[Foo],
description: "This is a foo use case",
) <foo>
Link to @foo
#userstory(
[User],
[foo],
[bar],
) <bar>
Link to @bar
|
|
https://github.com/bigskysoftware/hypermedia-systems-book | https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch02-components-of-a-hypermedia-system.typ | typst | Other | #import "lib/definitions.typ": *
#import "lib/snippets.typ": fielding-rest-thesis
== Components Of A Hypermedia System
A _hypermedia system_ consists of a number of components, including:
- A hypermedia, such as HTML.
- A network protocol, such as HTTP.
- A server that presents a hypermedia API responding to network requests with hypermedia responses.
- A client that properly interprets those responses.
In this chapter we will look at these components and their implementation in the
context of the web.
Once we have reviewed the major components of the web as a hypermedia system, we
will look at some key ideas behind this system --- especially as developed by
<NAME> in his dissertation, "Architectural Styles and the Design of
Network-based Software Architectures." We will see where the terms
REpresentational State Transfer (REST), RESTful and Hypermedia As The Engine Of
Application State (HATEOAS) come from, and we will analyze these terms in the
context of the web.
This should give you a stronger understanding of the theoretical basis of the
web as a hypermedia system, how it is supposed to fit together, and why
Hypermedia-Driven Applications are RESTful, whereas JSON APIs --- despite the
way the term REST is currently used in the industry --- are not.
=== Components Of A Hypermedia System <_components_of_a_hypermedia_system>
==== The Hypermedia <_the_hypermedia>
The fundamental technology of a hypermedia system is a hypermedia that allows a
client and server to communicate with one another in a dynamic, non-linear
fashion. Again, what makes a hypermedia a hypermedia is the presence of _hypermedia controls_:
elements that allow users to select non-linear actions within the hypermedia.
Users can
_interact_ with the media in a manner beyond simply reading from start to end.
We have already mentioned the two primary hypermedia controls in HTML, anchors
and forms, which allow a browser to present links and operations to a user
through a browser.
#index[Uniform Resource Locator (URL)]
In the case of HTML, these links and forms typically specify the target of their
operations using _Uniform Resource Locators (URLs)_:
/ Uniform Resource Locator: #[
A uniform resource locator is a textual string that refers to, or
_points to_ a location on a network where a _resource_ can be retrieved from, as
well as the mechanism by which the resource can be retrieved.
]
A URL is a string consisting of various subcomponents:
#figure(caption: [URL Components],
```
[scheme]://[userinfo]@[host]:[port][path]?[query]#[fragment]
```)
Many of these subcomponents are not required, and are often omitted.
A typical URL might look like this:
#figure(caption: [A simple URL],
```
https://hypermedia.systems/book/contents/
```)
This particular URL is made up of the following components:
- A protocol or scheme (in this case, `https`)
- A domain (e.g., `hypermedia.systems`)
- A path (e.g., `/book/contents`)
This URL uniquely identifies a retrievable _resource_ on the internet, to which
an _HTTP Request_ can be issued by a hypermedia client that "speaks" HTTPS, such
as a web browser. If this URL is found as the reference of a hypermedia control
within an HTML document, it implies that there is a _hypermedia server_ on the
other side of the network that understands HTTPS as well, and that can respond
to this request with a _representation_ of the given resource (or redirect you
to another location, etc.)
Note that URLs are often not written out entirely within HTML. It is very common
to see anchor tags that look like this, for example:
#figure(caption: [A Simple Link],
```html
<a href="/book/contents/">Table Of Contents</a>
```)
Here we have a _relative_ hypermedia reference, where the protocol, host and
port are _implied_ to be that of the "current document," that is, the same as
whatever the protocol and server were to retrieve the current HTML page. So, if
this link was found in an HTML document retrieved from `https://hypermedia.systems/`,
then the implied URL for this anchor would be `https://hypermedia.systems/book/contents/`.
==== Hypermedia Protocols <_hypermedia_protocols>
The hypermedia control (link) above tells a browser: "When a user clicks on this
text, issue a request to
`https://hypermedia.systems/book/contents/` using the Hypertext Transfer
Protocol," or HTTP.
HTTP is the _protocol_ used to transfer HTML (hypermedia) between browsers
(hypermedia clients) and servers (hypermedia servers) and, as such, is the key
network technology that binds the distributed hypermedia system of the web
together.
HTTP version 1.1 is a relatively simple network protocol, so lets take a look at
what the `GET` request triggered by the anchor tag would look like. This is the
request that would be sent to the server found at
`hypermedia.systems`, on port `80` by default:
#figure(
```http
GET /book/contents/ HTTP/1.1
Accept: text/html,*/*
Host: hypermedia.systems
```)
The first line specifies that this is an HTTP `GET` request. It then specifies
the path of the resource being requested. Finally, it contains the HTTP version
for this request.
After that are a series of HTTP _request headers_: individual lines of
name/value pairs separated by a colon. The request headers provide
_metadata_ that can be used by the server to determine exactly how to respond to
the client request. In this case, with the `Accept`
header, the browser is saying it would prefer HTML as a response format, but
will accept any server response.
Next, it has a `Host` header that specifies which server the request has been
sent to. This is useful when multiple domains are hosted on the same host.
An HTTP response from a server to this request might look something like this:
#figure(
```http
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 870
Server: Werkzeug/2.0.2 Python/3.8.10
Date: Sat, 23 Apr 2022 18:27:55 GMT
<html lang="en">
<body>
<header>
<h1>HYPERMEDIA SYSTEMS</h1>
</header>
...
</body>
</html>
```)
In the first line, the HTTP Response specifies the HTTP version being used,
followed by a _response code_ of `200`, indicating that the given resource was
found and that the request succeeded. This is followed by a string, `OK` that
corresponds to the response code. (The actual string doesn’t matter, it is the
response code that tells the client the result of a request, as we will discuss
in more detail below.)
After the first line of the response, as with the HTTP Request, we see a series
of _response headers_ that provide metadata to the client to assist in
displaying the _representation_ of the resource correctly.
Finally, we see some new HTML content. This content is the HTML
_representation_ of the requested resource, in this case a table of contents of
a book. The browser will use this HTML to replace the entire content in its
display window, showing the user this new page, and updating the address bar to
reflect the new URL.
===== HTTP methods <_http_methods>
#index[HTTP methods]
#index[HTTP methods][GET]
#index[HTTP methods][POST]
#index[HTTP methods][PUT]
#index[HTTP methods][PATCH]
#index[HTTP methods][DELETE]
The anchor tag above issued an HTTP `GET`, where `GET` is the
_method_ of the request. The particular method being used in an HTTP request is
perhaps the most important piece of information about it, after the actual
resource that the request is directed at.
There are many methods available in HTTP; the ones of most practical importance
to developers are the following:
/ `GET`: #[
A GET request retrieves the representation of the specified resource. GET
requests should not mutate data.
]
/ `POST`: #[
A POST request submits data to the specified resource. This will often result in
a mutation of state on the server.
]
/ `PUT`: #[
A PUT request replaces the data of the specified resource. This results in a
mutation of state on the server.
]
/ `PATCH`: #[
A PATCH request replaces the data of the specified resource. This results in a
mutation of state on the server.
]
/ `DELETE`: #[
A DELETE request deletes the specified resource. This results in a mutation of
state on the server.
]
These methods _roughly_ line up with the
"Create/Read/Update/Delete" or #indexed[CRUD] pattern found in many
applications:
- `POST` corresponds with Creating a resource.
- `GET` corresponds with Reading a resource.
- `PUT` and `PATCH` correspond with Updating a resource.
- `DELETE` corresponds, well, with Deleting a resource.
#sidebar[Put vs. Post][
While HTTP Actions correspond roughly to CRUD, they are not the same. The
technical specifications for these methods make no such connection, and are
often somewhat difficult to read. Here, for example, is the documentation on the
distinction between a `POST` and a `PUT` from
#link("https://www.rfc-editor.org/rfc/rfc9110")[RFC-9110].
#blockquote(
attribution: [RFC-9110, https:\/\/www.rfc-editor.org/rfc/rfc9110\#section-9.3.4],
)[
The target resource in a POST request is intended to handle the enclosed
representation according to the resource’s own semantics, whereas the enclosed
representation in a PUT request is defined as replacing the state of the target
resource. Hence, the intent of PUT is idempotent and visible to intermediaries,
even though the exact effect is only known by the origin server.
]
In plain terms, a `POST` can be handled by a server pretty much however it
likes, whereas a `PUT` should be handled as a "replacement" of the resource,
although the language, once again allows the server to do pretty much whatever
it would like within the constraint of being
#link(
"https://developer.mozilla.org/en-US/docs/Glossary/Idempotent",
)[_idempotent_].
]
In a properly structured HTML-based hypermedia system you would use an
appropriate HTTP method for the operation a particular hypermedia control
performs. For example, if a hypermedia control such as a button
_deletes_ a resource, ideally it should issue an HTTP `DELETE`
request to do so.
A strange thing about HTML, though, is that the native hypermedia controls can
only issue HTTP `GET` and `POST` requests.
Anchor tags always issue a `GET` request.
Forms can issue either a `GET` or `POST` using the `method` attribute.
Despite the fact that HTML --- the world’s most popular hypermedia --- has been
designed alongside HTTP (which is the Hypertext Transfer Protocol, after all!):
if you wish to issue `PUT`, `PATCH` or `DELETE` requests you currently _have to_ resort
to JavaScript to do so. Since a
`POST` can do almost anything, it ends up being used for any mutation on the
server, and `PUT`, `PATCH` and `DELETE` are left aside in plain HTML-based
applications.
This is an obvious shortcoming of HTML as a hypermedia; it would be wonderful to
see this fixed in the HTML specification. For now, in Chapter 4, we’ll discuss
ways to get around this.
===== HTTP response codes <_http_response_codes>
HTTP request methods allow a client to tell a server _what_ to do to a given
resource. HTTP responses contain _response codes_, which tell a client what the
result of the request was. HTTP response codes are numeric values that are
embedded in the HTTP response, as we saw above.
The most familiar response code for web developers is probably `404`, which
stands for "Not Found." This is the response code that is returned by web
servers when a resource that does not exist is requested from them.
#index[HTTP response][codes]
HTTP breaks response codes up into various categories:
/ `100`-`199`: Informational responses that provide information about how the server is
processing the response.
/ `200`-`299`: Successful responses indicating that the request succeeded.
/ `300`-`399`: Redirection responses indicating that the request should be sent to some other
URL.
/ `400`-`499`: Client error responses indicating that the client made some sort of bad request
(e.g., asking for something that didn’t exist in the case of `404` errors).
/ `500`-`599`: Server error responses indicating that the server encountered an error
internally as it attempted to respond to the request.
Within each of these categories there are multiple response codes for specific
situations.
Here are some of the more common or interesting ones:
/ `200 OK`: The HTTP request succeeded.
/ `301 Moved Permanently`: The URL for the requested resource has moved to a new location permanently, and
the new URL will be provided in the `Location` response header.
/ `302 Found`: The URL for the requested resource has moved to a new location temporarily, and
the new URL will be provided in the `Location` response header.
/ `303 See Other`: The URL for the requested resource has moved to a new location, and the new URL
will be provided in the `Location` response header. Additionally, this new URL
should be retrieved with a `GET` request.
/ `401 Unauthorized`: The client is not yet authenticated (yes, authenticated, despite the name) and
must be authenticated to retrieve the given resource.
/ `403 Forbidden`: The client does not have access to this resource.
/ `404 Not Found`: The server cannot find the requested resource.
/ `500 Internal Server Error`: The server encountered an error when attempting to process the response.
There are some fairly subtle differences between HTTP response codes (and, to be
honest, some ambiguities between them). The difference between a `302` redirect
and a `303` redirect, for example, is that the former will issue the request to
the new URL using the same HTTP method as the initial request, whereas the
latter will always use a `GET`. This is a small but often crucial difference, as
we will see later in the book.
A well crafted Hypermedia-Driven Application will take advantage of both HTTP
methods and HTTP response codes to create a sensible hypermedia API. You do not
want to build a Hypermedia-Driven Application that uses a `POST` method for all
requests and responds with `200 OK` for every response, for example. (Some JSON
Data APIs built on top of HTTP do exactly this!)
When building a Hypermedia-Driven Application, you want, instead, to go
"with the grain" of the web and use HTTP methods and response codes as they were
designed to be used.
===== Caching HTTP responses <_caching_http_responses>
#index[HTTP response][caching]
A constraint of REST (and, therefore, a feature of HTTP) is the notion of
caching responses: a server can indicate to a client (as well as intermediary
HTTP servers) that a given response can be cached for future requests to the
same URL.
#index[HTTP response header][Cache-Control]
The cache behavior of an HTTP response from a server can be indicated with the `Cache-Control` response
header. This header can have a number of different values indicating the
cacheability of a given response. If, for example, the header contains the value `max-age=60`,
this indicates that a client may cache this response for 60 seconds, and need
not issue another HTTP request for that resource until that time limit has
expired.
#index[HTTP response header][Vary]
Another important caching-related response header is `Vary`. This response
header can be used to indicate exactly what headers in an HTTP Request form the
unique identifier for a cached result. This becomes important to allow the
browser to correctly cache content in situations where a particular header
affects the form of the server response.
#index[HTTP response header][custom]
#index[HX-Request][about]
A common pattern in htmx-powered applications, for example, is to use a custom
header set by htmx, `HX-Request`, to differentiate between
"normal" web requests and requests submitted by htmx. To properly cache the
response to these requests, the `HX-Request` request header must be indicated by
the `Vary` response header.
A full discussion of caching HTTP responses is beyond the scope of this chapter;
see the
#link(
"https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching",
)[MDN Article on HTTP Caching]
if you would like to know more on the topic.
==== Hypermedia Servers <_hypermedia_servers>
Hypermedia servers are any server that can respond to an HTTP request with an
HTTP response. Because HTTP is so simple, this means that nearly any programming
language can be used to build a hypermedia server. There are a vast number of
libraries available for building HTTP-based hypermedia servers in nearly every
programming language imaginable.
This turns out to be one of the best aspects of adopting hypermedia as your
primary technology for building a web application: it removes the pressure to
adopt JavaScript as a backend technology. If you use a JavaScript-heavy Single
Page Application-based front end, and you use JSON Data APIs, you are going to
feel significant pressure to deploy JavaScript on the back end as well.
In this latter situation, you already have a ton of code written in JavaScript.
Why maintain two separate code bases in two different languages? Why not create
reusable domain logic on the client-side as well as the server-side? Now that
JavaScript has excellent server-side technologies available like Node and Deno,
why not just use a single language for everything?
In contrast, building a Hypermedia-Driven Application gives you a lot more
freedom in picking the back end technology you want to use. Your decision can be
based on the domain of your application, what languages and server software you
are familiar with or are passionate about, or just what you feel like trying
out.
You certainly aren’t writing your server-side logic in HTML! And every major
programming language has at least one good web framework and templating library
that can be used to handle HTTP requests cleanly.
If you are doing something in big data, perhaps you’d like to use Python, which
has tremendous support for that domain.
If you are doing AI work, perhaps you’d like to use Lisp, leaning on a language
with a long history in that area of research.
Maybe you are a functional programming enthusiast and want to use OCaml or
Haskell. Perhaps you just really like Julia or Nim.
These are all perfectly valid reasons for choosing a particular server-side
technology!
By using hypermedia as your system architecture, you are freed up to adopt any
of these choices. There simply isn’t a large JavaScript code base on the front
end pressuring you to adopt JavaScript on the back end.
#sidebar[Hypermedia On Whatever you'd Like (HOWL)][
In the htmx community we call this (with tongue in cheek) the HOWL stack:
Hypermedia On Whatever you’d Like. The htmx community is multi-language and
multi-framework, there are rubyists as well as pythonistas, lispers as well as
haskellers. There are even JavaScript enthusiasts! All these languages and
frameworks are able to adopt hypermedia, and are able to still share techniques
and offer support to one another because they share a common underlying
architecture: they are all using the web as a hypermedia system.
Hypermedia, in this sense, provides a "universal language" for the web that we
can all use.
]
==== Hypermedia Clients <_hypermedia_clients>
#index[web browsers]
We now come to the final major component in a hypermedia system: the hypermedia
client. Hypermedia _clients_ are software that understand how to interpret a
particular hypermedia, and the hypermedia controls within it, properly. The
canonical example, of course, is the web browser, which understands HTML and can
present it to a user to interact with. Web browsers are incredibly sophisticated
pieces of software. (So sophisticated, in fact, that they are often re-purposed
away from being a hypermedia client, to being a sort of cross-platform virtual
machine for launching Single Page Applications.)
Browsers aren’t the only hypermedia clients out there, however. In the last
section of this book we will look at Hyperview, a mobile-oriented hypermedia.
One of the outstanding features of Hyperview is that it doesn’t simply provide a
hypermedia, HXML, but also provides a
_working hypermedia client_ for that hypermedia. This makes building a proper
Hypermedia-Driven Application with Hyperview extremely easy.
A crucial feature of a hypermedia system is what is known as _the uniform interface_.
We discuss this concept in depth in the next section on REST. What is often
ignored in discussions about hypermedia is how important the hypermedia client
is in taking advantage of this uniform interface. A hypermedia client must know
how to properly interpret and present hypermedia controls found in a hypermedia
response from a hypermedia server for the whole hypermedia system to hang
together. Without a sophisticated client that can do this, hypermedia controls
and a hypermedia-based API are much less useful.
This is one reason why JSON APIs have rarely adopted hypermedia controls
successfully: JSON APIs are typically consumed by code that is expecting a fixed
format and that isn’t designed to be a hypermedia client. This is totally
understandable: building a good hypermedia client is hard! For JSON API clients
like this, the power of hypermedia controls embedded within an API response is
irrelevant and often simply annoying:
#blockquote(
attribution: [<NAME>,
https:\/\/techblog.commercetools.com/graphql-and-rest-level-3-hateoas-70904ff1f9cf],
)[
The short answer to this question is that HATEOAS isn’t a good fit for most
modern use cases for APIs. That is why after almost 20 years, HATEOAS still
hasn’t gained wide adoption among developers. GraphQL on the other hand is
spreading like wildfire because it solves real-world problems.
]
HATEOAS will be described in more detail below, but the takeaway here is that a
good hypermedia client is a necessary component within a larger hypermedia
system.
=== REST <_rest>
Now that we have reviewed the major components of a hypermedia system, it’s time
to look more deeply into the concept of REST. The term "REST" comes from Roy
Fielding’s PhD dissertation on the architecture of the web. Fielding wrote his
dissertation at U.C. Irvine, after having helped build much of the
infrastructure of the early web, including the Apache web server. Roy was
attempting to formalize and describe the novel distributed computing system that
he had helped to build.
We are going to focus on what we feel is the most important section of
Fielding’s writing, from a web development perspective: Section 5.1. This
section contains the core concepts (Fielding calls them
_constraints_) of Representational State Transfer, or REST.
Before we get into the muck, however, it is important to understand that
Fielding discusses REST as a _network architecture_, that is, as an entirely
different way to architect a distributed system. And, further, as a novel
network architecture that should be _contrasted_ with earlier approaches to
distributed systems.
It is also important to emphasize that, at the time Fielding wrote his
dissertation, JSON APIs and AJAX did not exist. He was describing the early web,
with HTML being transferred over HTTP by early browsers, as a hypermedia system.
Today, in a strange turn of events, the term "REST" is mainly associated with
JSON Data APIs, rather than with HTML and hypermedia. This is extremely funny
once you realize that the vast majority of JSON Data APIs aren’t RESTful, in the
original sense, and, in fact, _can’t_
be RESTful, since they aren’t using a natural hypermedia format.
To re-emphasize: REST, as coined by Fielding, describes the
_pre-API web_, and letting go of the current, common usage of the term REST to
simply mean "a JSON API" is necessary to develop a proper understanding of the
idea.
==== The "Constraints" of REST <_the_constraints_of_rest>
#index[Fielding, Roy]
#index[REST][constraints]
In his dissertation, Fielding defines various "constraints" to describe how a
RESTful system must behave. This approach can feel a little round-about and
difficult to follow for many people, but it is an appropriate approach for an
academic document. Given a bit of time thinking about the constraints he
outlines and some concrete examples of those constraints it will become easy to
assess whether a given system actually satisfies the architectural requirements
of REST or not.
Here are the constraints of REST Fielding outlines:
- It is a client-server architecture (section 5.1.2).
- It must be stateless; (section 5.1.3) that is, every request contains all
information necessary to respond to that request.
- It must allow for caching (section 5.1.4).
- It must have a _uniform interface_ (section 5.1.5).
- It is a layered system (section 5.1.6).
- Optionally, it can allow for Code-On-Demand (section 5.1.7), that is,
scripting.
Let’s go through each of these constraints in turn and discuss them in detail,
looking at how (and to what extent) the web satisfies each of them.
==== The Client-Server Constraint <_the_client_server_constraint>
See
#link(
"https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_2",
)[Section 5.1.2]
for the Client-Server constraint.
The REST model Fielding was describing involved both _clients_
(browsers, in the case of the web) and _servers_ (such as the Apache Web Server
he had been working on) communicating via a network connection. This was the
context of his work: he was describing the network architecture of the World
Wide Web, and contrasting it with earlier architectures, notably thick-client
networking models such as the Common Object Request Broker Architecture (CORBA).
It should be obvious that any web application, regardless of how it is designed,
will satisfy this requirement.
==== The Statelessness Constraint <_the_statelessness_constraint>
See
#link(
"https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_3",
)[Section 5.1.3]
for the Stateless constraint.
As described by Fielding, a RESTful system is stateless: every request should
encapsulate all information necessary to respond to that request, with no side
state or context stored on either the client or the server.
In practice, for many web applications today, we actually violate this
constraint: it is common to establish a _session cookie_ that acts as a unique
identifier for a given user and that is sent along with every request. While
this session cookie is, by itself, not stateful (it is sent with every request),
it is typically used as a key to look up information stored on the server, in
what is usually termed "the session."
This session information is typically stored in some sort of shared storage
across multiple web servers, holding things like the current user’s email or id,
their roles, partially created domain objects, caches, and so forth.
This violation of the Statelessness REST architectural constraint has proven to
be useful for building web applications and does not appear to have had a major
impact on the overall flexibility of the web. But it is worth bearing in mind that
even Web 1.0 applications often violate the purity of REST in the interest of
pragmatic trade-offs.
And it must be said that sessions _do_ cause additional operational complexity
headaches when deploying hypermedia servers; these may need shared access to
session state information stored across an entire cluster. So Fielding was
correct in pointing out that an ideal RESTful system, one that did not violate
this constraint, would be simpler and therefore more robust.
==== The Caching Constraint <_the_caching_constraint>
See
#link(
"https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_4",
)[Section 5.1.4]
for the Caching constraint.
This constraint states that a RESTful system should support the notion of
caching, with explicit information on the cache-ability of responses for future
requests of the same resource. This allows both clients as well as intermediary
servers between a given client and final server to cache the results of a given
request.
As we discussed earlier, HTTP has a sophisticated caching mechanism via response
headers that is often overlooked or underutilized when building hypermedia
applications. Given the existence of this functionality, however, it is easy to
see how this constraint is satisfied by the web.
==== The Uniform Interface Constraint <_the_uniform_interface_constraint>
Now we come to the most interesting and, in our opinion, most innovative
constraint in REST: that of the _uniform interface_.
This constraint is the source of much of the _flexibility_ and
_simplicity_ of a hypermedia system, so we are going to spend some time on it.
See
#link(
"https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5",
)[Section 5.1.5]
for the Uniform Interface constraint.
In this section, Fielding says:
#blockquote(
attribution: fielding-rest-thesis,
)[
The central feature that distinguishes the REST architectural style from other
network-based styles is its emphasis on a uniform interface between components…
In order to obtain a uniform interface, multiple architectural constraints are
needed to guide the behavior of components. REST is defined by four interface
constraints: identification of resources; manipulation of resources through
representations; self-descriptive messages; and, hypermedia as the engine of
application state
]
So we have four sub-constraints that, taken together, form the Uniform Interface
constraint.
===== Identification of resources <_identification_of_resources>
In a RESTful system, resources should have a unique identifier. Today the
concept of Universal Resource Locators (URLs) is common, but at the time of
Fielding’s writing they were still relatively new and novel.
What might be more interesting today is the notion of a _resource_, thus being
identified: in a RESTful system, _any_ sort of data that can be referenced, that
is, the target of a hypermedia reference, is considered a resource. URLs, though
common enough today, end up solving the very complex problem of uniquely
identifying any and every resource on the internet.
===== Manipulation of resources through representations <_manipulation_of_resources_through_representations>
In a RESTful system, _representations_ of the resource are transferred between
clients and servers. These representations can contain both data and metadata
about the request (such as "control data" like an HTTP method or response code).
A particular data format or
_media type_ may be used to present a given resource to a client, and that media
type can be negotiated between the client and the server.
We saw this latter aspect of the uniform interface in the `Accept`
header in the requests above.
===== Self-descriptive messages <_self_descriptive_messages>
#index[self-descriptive messages]
The Self-Descriptive Messages constraint, combined with the next one, HATEOAS,
form what we consider to be the core of the Uniform Interface, of REST and why
hypermedia provides such a powerful system architecture.
The Self-Descriptive Messages constraint requires that, in a RESTful system,
messages must be _self-describing_.
This means that _all information_ necessary to both display
_and also operate_ on the data being represented must be present in the
response. In a properly RESTful system, there can be no additional
"side" information necessary for a client to transform a response from a server
into a useful user interface. Everything must "be in" the message itself, in the
form of hypermedia controls.
This might sound a little abstract so let’s look at a concrete example.
Consider two different potential responses from an HTTP server for the URL `https://example.com/contacts/42`.
Both responses will return information about a contact, but each response will
take very different forms.
The first implementation returns an HTML representation:
#figure(
```html
<html lang="en">
<body>
<h1><NAME></h1>
<div>
<div>Email: <EMAIL></div>
<div>Status: Active</div>
</div>
<p>
<a href="/contacts/42/archive">Archive</a>
</p>
</body>
</html>
```)
The second implementation returns a JSON representation:
#figure(
```json
{
"name": "<NAME>",
"email": "<EMAIL>",
"status": "Active"
}
```)
What can we say about the differences between these two responses?
One thing that may initially jump out at you is that the JSON representation is
smaller than the HTML representation. Fielding notes exactly this trade-off when
using a RESTful architecture:
#blockquote(
attribution: fielding-rest-thesis,
)[
The trade-off, though, is that a uniform interface degrades efficiency, since
information is transferred in a standardized form rather than one which is
specific to an application’s needs.
]
So REST _trades off_ representational efficiency for other goals.
To understand these other goals, first notice that the HTML representation has a
hyperlink in it to navigate to a page to archive the contact. The JSON
representation, in contrast, does not have this link.
What are the ramifications of this fact for a _client_ of the JSON API?
#index[JSON API][vs. HTML]
What this means is that the JSON API client must know _in advance_
exactly what other URLs (and request methods) are available for working with the
contact information. If the JSON client is able to update this contact in some
way, it must know how to do so from some source of information _external_ to the
JSON message. If the contact has a different status, say "Archived", does this
change the allowable actions? If so, what are the new allowable actions?
The source of all this information might be API documentation, word of mouth or,
if the developer controls both the server and the client, internal knowledge.
But this information is implicit and _outside_
the response.
Contrast this with the hypermedia (HTML) response. In this case, the hypermedia
client (that is, the browser) needs only to know how to render the given HTML.
It doesn’t need to understand what actions are available for this contact: they
are simply encoded _within_ the HTML response itself as hypermedia controls. It
doesn’t need to understand what the status field means. In fact, the client
doesn’t even know what a contact is!
The browser, our hypermedia client, simply renders the HTML and allows the user,
who presumably understands the concept of a Contact, to make a decision on what
action to pursue from the actions made available in the representation.
This difference between the two responses demonstrates the crux of REST and
hypermedia, what makes them so powerful and flexible: clients (again, web
browsers) don’t need to understand _anything_ about the underlying resources
being represented.
Browsers only (only! As if it is easy!) need to understand how to interpret and
display hypermedia, in this case HTML. This gives hypermedia-based systems
unprecedented flexibility in dealing with changes to both the backing
representations and to the system itself.
===== Hypermedia As The Engine of Application State (HATEOAS) <_hypermedia_as_the_engine_of_application_state_hateoas>
The final sub-constraint on the Uniform Interface is that, in a RESTful system,
hypermedia should be "the engine of application state." This is sometimes
abbreviated as "#indexed[HATEOAS]", although Fielding prefers to use the
terminology "the hypermedia constraint" when discussing it.
This constraint is closely related to the previous self-describing message
constraint. Let us consider again the two different implementations of the
endpoint `/contacts/42`, one returning HTML and one returning JSON. Let’s update
the situation such that the contact identified by this URL has now been
archived.
What do our responses look like?
The first implementation returns the following HTML:
#figure(
```html
<html lang="en">
<body>
<h1><NAME></h1>
<div>
<div>Email: <EMAIL></div>
<div>Status: Archived</div>
</div>
<p>
<a href="/contacts/42/unarchive">Unarchive</a>
</p>
</body>
</html>
```)
The second implementation returns the following JSON representation:
#figure(
```json
{
"name": "<NAME>",
"email": "<EMAIL>",
"status": "Archived"
}
```)
The important point to notice here is that, by virtue of being a self-describing
message, the HTML response now shows that the "Archive" operation is no longer
available, and a new "Unarchive" operation has become available. The HTML
representation of the contact _encodes_
the state of the application; it encodes exactly what can and cannot be done
with this particular representation, in a way that the JSON representation does
not.
A client interpreting the JSON response must, again, understand not only the
general concept of a Contact, but also specifically what the
"status" field with the value "Archived" means. It must know exactly what
operations are available on an "Archived" contact, to appropriately display them
to an end user. The state of the application is not encoded in the response, but
rather conveyed through a mix of raw data and side channel information such as
API documentation.
Furthermore, in the majority of front end SPA frameworks today, this contact
information would live _in memory_ in a JavaScript object representing a model
of the contact, while the page data is held in the browser’s
#link(
"https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model",
)[Document Object Model]
(DOM). The DOM would be updated based on changes to this model, that is, the DOM
would "react" to changes to this backing JavaScript model.
This approach is certainly _not_ using Hypermedia As The Engine Of Application
State: rather, it is using a JavaScript model as the engine of application
state, and synchronizing that model with a server and with the browser.
With the HTML approach, the Hypermedia is, indeed, The Engine Of Application
State: there is no additional model on the client side, and all state is
expressed directly in the hypermedia, in this case HTML. As state changes on the
server, it is reflected in the representation (that is, HTML) sent back to the
client. The hypermedia client (a browser) doesn’t know anything about contacts,
what the concept of "Archiving" is, or anything else about the particular domain
model for this response: it simply knows how to render HTML.
Because a hypermedia client doesn’t need to know anything about the server model
beyond how to render hypermedia to a client, it is incredibly flexible with
respect to the representations it receives and displays to users.
===== HATEOAS & API churn <_hateoas_api_churn>
This last point is critical to understanding the flexibility of hypermedia, so
let’s look at a practical example of it in action. Consider a situation where a
new feature has been added to the web application with these two end points.
This feature allows you to send a message to a given Contact.
How would this change each of the two responses—HTML and JSON—from the server?
The HTML representation might now look like this:
#figure(
```html
<html lang="en">
<body>
<h1><NAME></h1>
<div>
<div>Email: <EMAIL></div>
<div>Status: Active</div>
</div>
<p>
<a href="/contacts/42/archive">Archive</a>
<a href="/contacts/42/message">Message</a>
</p>
</body>
</html>
```)
The JSON representation, on the other hand, might look like this:
#figure(
```json
{
"name": "<NAME>",
"email": "<EMAIL>",
"status": "Active"
}
```)
Note that, once again, the JSON representation is unchanged. There is no
indication of this new functionality. Instead, a client must _know_
about this change, presumably via some shared documentation between the client
and the server.
Contrast this with the HTML response. Because of the uniform interface of the
RESTful model and, in particular, because we are using Hypermedia As The Engine
of Application State, no such exchange of documentation is necessary! Instead,
the client (a browser) simply renders the new HTML with this operation in it,
making this operation available for the end user without any additional coding
changes.
A pretty neat trick!
Now, in this case, if the JSON client is not properly updated, the error state
is relatively benign: a new bit of functionality is simply not made available to
users. But consider a more severe change to the API: what if the archive
functionality was removed? Or what if the URLs or the HTTP methods for these
operations changed in some way?
In this case, the JSON client may be broken in a much more serious manner.
The HTML response, however, would simply be updated to exclude the removed
options or to update the URLs used for them. Clients would see the new HTML,
display it properly, and allow users to select whatever the new set of
operations happens to be. Once again, the uniform interface of REST has proven
to be extremely flexible: despite a potentially radically new layout for our
hypermedia API, clients continue to work.
An important fact emerges from this: due to this flexibility, hypermedia APIs _do not have the versioning headaches that JSON Data APIs do_.
Once a Hypermedia-Driven Application has been "entered into" (that is, loaded
through some entry point URL), all functionality and resources are surfaced
through self-describing messages. Therefore, there is no need to exchange
documentation with the client: the client simply renders the hypermedia (in this
case HTML) and everything works out. When a change occurs, there is no need to
create a new version of the API: clients simply retrieve updated hypermedia,
which encodes the new operations and resources in it, and display it to users to
work with.
==== Layered System <_layered_system>
The final "required" constraint on a RESTful system that we will consider is The
Layered System constraint. This constraint can be found in
#link(
"https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_6",
)[Section 5.1.6]
of Fielding’s dissertation.
To be frank, after the excitement of the uniform interface constraint, the "layered
system" constraint is a bit of a let down. But it is still worth understanding
and it is actually utilized effectively by The web. The constraint requires that
a RESTful architecture be "layered," allowing for multiple servers to act as
intermediaries between a client and the eventual "source of truth" server.
These intermediary servers can act as proxies, transform intermediate requests
and responses and so forth.
A common modern example of this layering feature of REST is the use of Content
Delivery Networks (CDNs) to deliver unchanging static assets to clients more
quickly, by storing the response from the origin server in intermediate servers
more closely located to the client making a request.
This allows content to be delivered more quickly to the end user and reduces
load on the origin server.
Not as exciting for web application developers as the uniform interface, at
least in our opinion, but useful nonetheless.
==== An Optional Constraint: Code-On-Demand <_an_optional_constraint_code_on_demand>
We called The Layered System constraint the final "required" constraint because
Fielding mentions one additional constraint on a RESTful system. This Code On
Demand constraint is somewhat awkwardly described as
"optional" (Section 5.1.7).
In this section, Fielding says:
#blockquote(
attribution: fielding-rest-thesis,
)[
REST allows client functionality to be extended by downloading and executing
code in the form of applets or scripts. This simplifies clients by reducing the
number of features required to be pre-implemented. Allowing features to be
downloaded after deployment improves system extensibility. However, it also
reduces visibility, and thus is only an optional constraint within REST.
]
So, scripting was and is a native aspect of the original RESTful model of the
web, and thus should of course be allowed in a Hypermedia-Driven Application.
However, in a Hypermedia-Driven Application the presence of scripting should _not_ change
the fundamental networking model: hypermedia should continue to be the engine of
application state, server communication should still consist of hypermedia
exchanges rather than, for example, JSON data exchanges, and so on. (JSON Data
API’s certainly have their place; in Chapter 10 we’ll discuss when and how to
use them).
Today, unfortunately, the scripting layer of the web, JavaScript, is quite often
used to _replace_, rather than augment the hypermedia model. We will elaborate
in a later chapter what scripting that does not replace the underlying
hypermedia system of the web looks like.
=== Conclusion <_conclusion>
After this deep dive into the components and concepts behind hypermedia systems
--- including Roy Fielding’s insights into their operation --- we hope you have
much better understanding of REST, and in particular, of the uniform interface
and HATEOAS. We hope you can see _why_ these characteristics make hypermedia
systems so flexible.
If you were not aware of the full significance of REST and HATEOAS before now,
don’t feel bad: it took some of us over a decade of working in web development,
and building a hypermedia-oriented library to boot, to understand the special
nature of HTML, hypermedia and the web!
#html-note[HTML5 Soup][
#blockquote(attribution: [Confucius])[
The beginning of wisdom is to call things by their right names.
]
Elements like `<section>`, `<article>`, `<nav>`, `<header>`, `<footer>`,
`<figure>` have become a sort of shorthand for HTML.
By using these elements, a page can make false promises, like
`<article>` elements being self-contained, reusable entities, to clients like
browsers, search engines and scrapers that can’t know better. To avoid this:
- Make sure that the element you’re using fits your use case. Check the HTML spec.
- Don’t try to be specific when you can’t or don’t need to. Sometimes,
`<div>` is fine.
#index[HTML][spec]
The most authoritative resource for learning about HTML is the HTML
specification. The current specification lives on
#link("https://html.spec.whatwg.org/multipage").#footnote[The single-page version is too slow to load and render on most computers.
There’s also a "developers’ edition" at /dev, but the standard version has nicer
styling.] There’s no need to rely on hearsay to keep up with developments in
HTML.
Section 4 of the spec features a list of all available elements, including what
they represent, where they can occur, and what they are allowed to contain. It
even tells you when you’re allowed to leave out closing tags!
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/ionio-illustrate/0.1.0/manual.typ | typst | Apache License 2.0 | #import "lib.typ": *
#let data = csv("assets/isobutelene_epoxide.csv")
#let massspec = data.slice(1)
#set page(
numbering: "1/1",
header: align(right)[The `ionio-illustrate` package],
)
#set heading(numbering: "1.")
#set terms(indent: 1em)
#show link: set text(blue)
#set text(font: "Fira Sans")
#show raw.where(lang:"typ"): it => block(
fill: rgb("#F6F4EB"),
inset: 8pt,
radius: 5pt,
width: 100%,
text(font:"Consolas", it),
)
#align(center, text(16pt)[*The `ionio-illustrate` package*])
#align(center)[Version 0.1.0]
#set par(justify: true, leading: 0.618em)
#v(3em)
= Introduction
This package implements a Cetz chart-like object for displaying mass spectrometric data in Typst documents. It allows for individually styled mass peaks, callouts, titles, and mass calipers.
= Usage
This is the minimal starting point:
```typ
#import "@preview/ionio-illustrate:0.1.0": *
#let data = csv("isobutelene_epoxide.csv")
#let ms = mass-spectrum(massspec, args: (
size: (12,6),
range: (0,100),
))
#figure((ms.display)(ms))
```
The above code produces the following content:
#let ms = mass-spectrum(massspec, args: (
size: (12,6),
range: (0,100),
))
#v(1em)
#figure((ms.display)(ms))
It is important to note at this point that the syntax for interacting with mass spectrum objects will certainly change with the introduction of a native type system. This document will be updated to reflect this upon implementation of those changes.
#pagebreak()
== `mass-spectrum()`
The `mass-spectrum()` function takes two positional arguments:
- `data` (array or dictionary): This is a 2-dimensional array relating mass-charge ratios to their intensities. By default, the first column is the mass-charge ratio and the second column is the intensity.
- `args` (dictionary): This contains suplemental data that can be used to change the style of the mass spectrum, or to add additional content using provided functions (see @extra-content).
The defaults for the `args` dictionary are shown below:
```typ
keys: (
mz: 0,
intensity: 1
),
size: (auto, 1),
range: (40, 400),
style: (:),
labels: (
x: [Mass-Charge Ratio],
y: [Relative Intensity \[%\]]
),
linestyle: (idx)=>{},
```
=== `keys`
The `keys` entry in the `args` positional argument is a dictionary that can be used to change which fields in the provided `data` array/dictionary are to be used to plot the mass spectrum. An example usage of this may be to store several mass spectra within a single datafile.
Note that arrays are 0-index based.
```typ
#let ms = mass-spectrum(massspec, args: (
keys: (
mz: 0, // mass-charge is contained in the first column
intensity: 1 // intensity is contained in the second column
)
))
```
=== `size`
The `keys` entry in the `args` positional argument is a tuple specifying the size of the mass spectrum on the page, in `Cetz` units.
```typ
#let ms = mass-spectrum(massspec, args: (
size: (12,6)
))
```
=== `range`
The `range` entry in the `args` positional argument is a tuple specifying the min and the max of the mass-charge axis.
```typ
#let ms = mass-spectrum(massspec, args: (
range: (0,100) // Show mass spectrum between 0 m/z and 100 m/z
))
```
=== `style`
The `style` entry in the `args` positional argument is a cetz style dictionary. It is presently unused until it is better understood where styling is appropriate.
=== `labels`
The `labels` entry in the `args` positional argument is a dictionary specifying the labels to be used on each axis.
Note that if you provide this entry, you must provide both child entries.
```typ
#let ms = mass-spectrum(massspec, args: (
labels: (
x: [Mass-Charge Ratio],
y: [Relative Intensity \[%\]]
)
))
```
=== `linestyle`
The `linestyle` entry in the `args` positional argument is a function taking two parameters: `this` (refering to the `#ms` object), and `idx` which represents the mass-charge ratio of the peak being drawn. Returning a cetz style dictionary will change the appearence of the peaks. This may be used to draw the reader's attention to a particular mass spectrum peak by colouring it in red, for example.
```typ
#let ms = mass-spectrum(massspec, args: (
linestyle: (this, idx)=>{
if idx==41 {return (stroke: red)}
}
))
```
=== `plot-extras` <extra-content>
The `plot-extras` entry in the `args` positional argument is a function taking one parameter, `this`, which refers to the `#ms` object. It can be used to add additional content to a mass spectrum using provided functions
```typ
#let ms = mass-spectrum(massspec, args: (
size: (14,8),range: (0,100),
plot-extras: (this) => {
(this.callout-above)(this, 72, content: MolecularIon())
(this.callout-above)(this, 27)
(this.callout-above)(this, 41)
(this.calipers)(this, 43, 57, content: [\-CH#sub("2")])
(this.title)(this, [Isobutelene Epoxide])
}
))
#figure((ms.display)(ms))
```
#let ms = mass-spectrum(massspec, args: (
size: (12,6), range: (0,100),
plot-extras: (this) => {
(this.callout-above)(this, 72, content: MolecularIon())
(this.callout-above)(this, 27)
(this.callout-above)(this, 41)
(this.calipers)(this, 43, 57, content: [\-CH#sub("2")])
(this.title)(this, [Isobutelene Epoxide])
}
))
#v(1em)
#figure((ms.display)(ms))
== Method functions
This section briefly outlines method functions and where/why they might be used
=== `#ms.display(this)`
the `#ms.display` method is used to place a mass spectrum within a document. It can be called several times. It *must not* be called within the context of a `plot-extras(this)` function.
=== `#ms.title(this, content)`
the `#ms.title` method allows the addition of a title to a mass spectrum. It should be called within the context of a `plot-extras(this)` function.
=== `#ms.callout-above(this, mz, content: [])`
the `#ms.callout-above` method places a callout slightly above the intensity peak for a given mass-charge ratio. It should be called within the context of a `plot-extras(this)` function.
=== `#ms.calipers(this, mz1, mz2, content: none, height: none)`
the `#ms.calipers` method places a mass calipers between two mass spectrum peaks, along with any desired content centered above the calipers. If `height` is not specified, it is set automatically to a few units above the most intense peak. If `content` is not specified, it is set automatically to represent the loss of mass between the specified peaks. It should be called within the context of a `plot-extras(this)` function.
|
https://github.com/Araanee/TypStyle | https://raw.githubusercontent.com/Araanee/TypStyle/main/README.md | markdown | # TypStyle
Local IDE for Typst
## Usage
### Option 1
Open a terminal\
Go to the electron-app/out folder\
launch ./TypStyle on the command line\
### Option 2
Go to the electron-app/ folder\
write npm make on the command line\
Navigate to the out/make/deb/x64/ folder\
Depackage the .deb file with your packets tool manager:\
sudo dpkg -i TypStyle-1.0.0_amd64.deb\
Search for TypStyle and use it !\
## Support
If you're having any trouble concerning the projet please contact any of the following emails for help.\
<EMAIL>\
<EMAIL>\
yasmine.<EMAIL>\
<EMAIL>.fr\
[email protected]\
## Project status
Project starting on may 25 of 2024\
Project ending on july 7 of 2024
|
|
https://github.com/mitsuyukiLab/grad_thesis_typst | https://raw.githubusercontent.com/mitsuyukiLab/grad_thesis_typst/main/README.md | markdown | # grad_thesis_typst
これは、卒論・修論・博論などの卒業論文をTypstで書くためのフォーマットです。
## 事前準備
### Typstのインストール
公式のマニュアルは[こちら](https://github.com/typst/typst?tab=readme-ov-file#installation)。
Windowsの場合は、PowerShellか何かで、以下のコマンドを実行してください。
```bash
winget install --id Typst.Typst
```
Mac OSの場合は、Terminalか何かで、[Homebrew](https://formulae.brew.sh/)を使って、以下のコマンドを実行してください。
```bash
brew install typst
```
### フォントのインストール(Mac, Linuxのみ)
現在、フォントについては以下の設定になっています。
各自のPCにインストールされているフォントと照らし合わせて、前の方から優先的に使われるようです。
```ts
#let mincho = ("Times New Roman", "MS Mincho", "IPAMincho", "Noto Serif CJK JP", "Hiragino Mincho Pro")
#let gothic = ("Times New Roman", "MS Gothic", "IPAGothic", "Noto Sans CJK JP", "Hiragino Kaku Gothic Pro")
```
基本的には、英語の場合に優先的に選択されるTimes New Roman以外を除くと、前の方がおすすめなフォントですが、
- ゴシック: MS GothicとIPAGothic
- 明朝: MS MinchoとIPAMincho
くらいまででないと、仕上がりが[指定フォーマット](https://www.jasnaoe.or.jp/lecture/2024aut/thesis.html?id=yoryo)に近づきません。
Typstで認識されているフォントを確認するには、以下のコマンドを実行すると良いです。
```bash
typst fonts
```
#### Windows
おそらく、WindowsではMS GothicとMS Mincho、Times New Romanがデフォルトで入っているので、何もする必要がありません。
#### Mac OS
おそらく、MacではTimes New Romanは入っているけども、ゴシックや明朝はフォントをインストールする必要があります。
IPAフォントであれば、[Homebrew](https://formulae.brew.sh/)を利用して簡単にインストールできます。
```bash
brew install --cask font-ipafont
```
MSフォントは、Microsoft OfficeがインストールされているPCであれば[この記事](https://note.com/tomorrow311/n/ne835a8c525a9)の方法で取り込めそうですが、ご自身の責任でお願いします。
#### Linux
以下の方法でインストールできそうです。
```bash
# Debian系(Ubuntu)
sudo apt-get install fonts-ipafont
sudo apt-get install msttcorefonts # Times New Roman
```
## How to use
### 1. レポジトリの用意
- GitHubアカウントを持っている方は、`use this template` で、自分用のレポジトリを生成してください。
- レポジトリの名前は`年度-学位-名字`をおすすめします。例えば、2024年度に卒業論文を書く学部生の場合は`2024-B-mitsuyuki`とかが良いです。
- Privateレポジトリにし、指導教員を共同編集者に招待してください。
### 2. 執筆環境設定(VSCode)
ローカルPCにTypstとVisual Studio Code(VSCode)がインストールされている前提で説明を続けます。
複数ファイルに分割して記述するスタイルを採用しているため、VSCodeプラグイン固有の自動コンパイル機能は切っておいた方が良いと思います。
[Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)であれば、このワークスペースにおいては自動コンパイル機能をoffにする設定にしています。他のTypstコンパイル拡張機能をインストールしている場合は、ご自身で自動コンパイル機能をoffにしてください。
PowershellやTerminalか何かで以下のコマンドを実行することで、ファイルの変更時に自動でコンパイルを行ってpdfファイルを生成してくれます。コンパイルが失敗する場合はエラーメッセージが表示されるので、該当の場所を修正しましょう。
```sh
typst watch main.typ main.pdf
```
|
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/tests/pt/test.typ | typst | MIT License | #import "../../src/schule.typ": pt
#import pt: *
#show: praesentation.with(
/* @typstyle:off */
titel: "Informatik Leistungskurs Q1",
reihe: "Schuljahr 2024/25",
datum: "01.08.2024",
nummer: "1",
fach: "Informatik",
kurs: "Q1",
autor: (
name: "<NAME>",
kuerzel: "Ngb",
),
version: "2024-06-24",
theme: "digi"
)
#slide(subtitle: "Foo")[
= Organisatorisches
- *Bewertungskriterien*
- Schriftliche Arbeiten (50 #sym.percent)
- 2 Arbeiten _im Halbjahr_, jeweils 90 Minuten
]
#empty-slide[]
// #empty-slide[
// #lorem(50)
// ]
// #slide()[
// = Organisatorisches
// - *Bewertungskriterien*
// - Sonstige Mitarbeit (50 #sym.percent)
// - (Eigenverantwortliche) Beteiligung am Unterricht (Qualität und Quantität)
// - Präsentation von Lösungen und Zwischenprodukten
// - Selbstständiges Arbeiten in Kleingruppen
// - Projektergebnisse
// #pause
// #place(
// center + horizon,
// link(
// "https://www.helmholtz-bi.de/lernen/faecher/mathematik-naturwissenschaften/informatik/bewertung-des-bereichs-sonstige-mitarbeit/",
// note(width: 50%)[
// Siehe Leistungsbewertungs-\
// konzept Homepage
// ],
// ),
// )
// ]
#section-slide("Speicherung primitiver Daten")
#image-slide(image("wallpaper.jpg"), align: left, title: "Foo")[
#lorem(10)
]
#section-slide("Speicherung primitiver Daten", level: 2)
#slide[]
#full-image-slide(image("wallpaper.jpg"))
#subsection-slide[
= Objektarrays
#lorem(20)
]
#subsection-slide(level: 2)[
= Objektarrays
#lorem(20)
]
#quote-slide()[
#lorem(33)
]
#link-slide("https://link.ngb.schule/arrays")
#code-slide(light: true)[
```java
public class Muppet implements ComparableContent<Muppet> {
private String name;
private String color;
private double height;
}
```
]
|
https://github.com/SergeyGorchakov/russian-phd-thesis-template-typst | https://raw.githubusercontent.com/SergeyGorchakov/russian-phd-thesis-template-typst/main/parts/part1.typ | typst | MIT License | #import "../lib.typ": *
#part_count.step() // Обновление счетчика разделов
#show: fix-indent()
= Оформление различных элементов <ch1>
== Форматирование текста <ch1:sec1>
Мы можем сделать *жирный текст* и _курсив_.
== Ссылки <ch1:sec2>
Сошлёмся на библиографию. Одна ссылка: @Sokolov[с.~54];.
Две ссылки: @Sokolov @Sychev.
Сошлёмся на разделы: @ch1, @ch2:sec1, @ch1:sec2.
Сошлёмся на приложения: @app:A, @app:B.
Сошлёмся на формулу: @eq:equation1.
Сошлёмся на изображение: @fig:typst.
Сошлемся на определение : @typst. Все определения задаются в файле `common\glossary.typ`.
Также можно вставлять сокращения @si, @ацп и ссылки на символы: @pi.
А также ссылку на символы в уравнении:
$ #gls("pi") #gls("a") $
#print-eq-sym("pi","a")
И при повторном использовании: @si, @ацп.
Определения для списка сокращений и условных обозначений находятся в файлах `common/acronyms.typ` и `common/symbols.typ`.
== Формулы <ch1:sec3>
=== Нумерованные одиночные формулы <ch1:sec3:sub1>
Вот так может выглядеть формула, которую необходимо вставить в~строку по~тексту: $x approx sin x$ при $x -> 0$.
А вот так выглядит нумерованная отдельностоящая формула c подстрочными и надстрочными индексами:
$ (x_1+x_2)^2 = x_1^2 + 2 x_1 x_2 + x_2^2 $ <eq:equation1>
Формула с неопределенным интегралом:
$ integral f(alpha+x)= sum beta $
Подробнее можно прочитать здесь: https://typst.app/docs/reference/math/equation |
https://github.com/PmaFynn/cv | https://raw.githubusercontent.com/PmaFynn/cv/master/src/content/en/misc.typ | typst | The Unlicense | #import "../../template.typ": *
#cvSection("Miscellaneous")
#cvInterestTags(
tags: ("Driving Licence", "80+ wpm"),
)
|
https://github.com/jujimeizuo/ZJSU-typst-template | https://raw.githubusercontent.com/jujimeizuo/ZJSU-typst-template/master/README.md | markdown | Apache License 2.0 | # ZJGSU-typst-template
浙江工商大学毕业设计(本科)的 typst 模板。
## 为什么要使用typst
typst相较Latex具有较为简洁的[语法](https://typst.app/docs/reference/syntax/),更加用户友好的[教程及文档](https://typst.app/docs/tutorial/)。除去其用于支持用户自定样式的语法,typst具有与markdown高度相似的语法,使非模板编辑者能更好的聚焦文档编写本身。而且,typst具有快速的编译速度,搭配[vscode typst lsp](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)的监听修改自动编译的功能,可以即时预览编译出的pdf文件。
可以从[这里速通 typst](https://typst.app/docs/tutorial)
## 使用
### 安装typst
[typst Github主页](https://github.com/typst/typst)提供了详细的安装教程
#### 线上编辑
typst 也提供了线上编辑器(类似overleaf),查看本模板:
https://typst.app/project/pLKexPD4J5ADToO-HQEWz2
(ps:浏览器可能没宋体,字体可能不对,请忽略字体)
#### 本地编辑
``` shell
# macOS or Linux using Homebrew
brew install typst
# Arch Linux
pacman -S typst
```
### 编译
``` shell
# for linux and macos
$ make
# for Windows
$ .\make.bat
```
### 编辑
修改contents目录下各文件即可
## License
This template is released under the Apache License. See the [LICENSE](./LICENSE) file for more details. |
https://github.com/barddust/Kuafu | https://raw.githubusercontent.com/barddust/Kuafu/main/src/config.typ | typst | #let serif = ("Spectral", "Source Han Serif")
#let sans = "Source Han Sans CN"
#let kai = "LXGW WenKai"
#let default_author = "Bardust"
#let page_height = 841.89pt
#let math-font = "STIX Two Math"
#let env-lang = state("lang","zh")
#let cover(
title: none,
subtitle: none,
date: none,
author: none,
version: none,
) = page(
{
align(
center,
{
v(page_height / 5)
linebreak()
text(size: 2em, weight: "bold", title)
linebreak()
if subtitle != none{
text(size: 1.8em, weight: "bold", subtitle)
linebreak()
}
linebreak()
if author != none {
author
} else {
default_author
}
linebreak()
if date != none {
date
} else {
datetime.today().display()
}
linebreak()
if version != none [
V #version
]
}
)
}
)
#let toc() = page(
numbering: "I",
{
counter(page).update(1)
show heading: set align(center)
show heading: set block(below: 1.5em)
show outline: it => {
set par(leading: 1.2em)
it
}
show outline.entry.where(level: 1): set text(weight: "bold")
outline(
depth: 2,
indent: auto,
)
}
)
#let init(
doc,
) = {
show: set text(
font: serif,
lang: "zh",
)
doc
}
#let conf(
doc,
) = {
set page(
height: page_height,
numbering: "1",
)
show bibliography: set heading(numbering: none)
set heading(numbering: "1.")
show heading: it => {
set block(above: 2em, below: 1em)
if it.level == 1 {
align(
center,
{
if counter(here()).get().at(0) != 1 {
pagebreak()
}
if it.numbering != none {
if env-lang.get() == "zh" [
第#counter(heading).get().at(0)章#h(1em)#it.body
] else [
#text(size: 0.8em)[CHAPTER #counter(heading).get().at(0)]
#linebreak()
#it.body
]
} else {
it.body
}
}
)
} else {
it
}
par(text(size:0.35em, h(0.0em)))
}
show quote: set text(font: kai)
set quote(block: true)
set text(size: 14pt)
show link: set text(fill: blue)
counter(page).update(1)
set par(
first-line-indent: 2em,
justify: true,
leading: 1em,
)
show ref: it => {
super(it)
}
doc
}
#let reference() = [
#bibliography("ref.yml") <reference>
]
#let body(dir, chs) = {
if not dir.ends-with("/"){
dir = dir + "/"
}
include dir + chs.at(0)
for ch in chs.slice(1) {
pagebreak()
include dir + ch
}
}
#let project(
subtitle: none,
bio: true,
title,
version,
par-dir,
chapter,
) = {
show: init
cover(
title: title,
subtitle: subtitle,
version: version,
)
toc()
show: conf
body(
par-dir,
chapter)
if bio {
reference()
}
}
|
|
https://github.com/TechnoElf/mqt-qcec-diff-thesis | https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-thesis/main/main.typ | typst | #import "@preview/cetz:0.2.2"
#import "@preview/fletcher:0.5.1"
#import "@preview/gentle-clues:0.9.0"
#import "@preview/glossarium:0.4.1": make-glossary
#import "@preview/lovelace:0.3.0"
#import "@preview/tablex:0.0.8"
#import "@preview/unify:0.6.0"
#import "@preview/quill:0.3.0"
#import "@preview/wordometer:0.1.2": word-count, total-words
#import "template/conf.typ": conf
#show: make-glossary
#set document(title: "Equivalence Checking of Quantum Circuits using Diff Algorithms", author: "<NAME>")
#show: word-count
#show: doc => conf(
title: "Equivalence Checking of Quantum Circuits using Diff Algorithms",
author: "<NAME>",
chair: "Chair for Design Automation",
school: "School of Computation, Information and Technology",
degree: "Bachelor of Science (B.Sc.)",
examiner: "Prof. Dr. <NAME>",
supervisor: "<NAME>",
submitted: "05.10.2024",
doc
)
#set math.vec(delim: "[")
#set math.mat(delim: "[")
#include "content/introduction.typ"
#include "content/background.typ"
#include "content/state.typ"
#include "content/implementation.typ"
#include "content/benchmarks.typ"
#include "content/conclusion.typ"
#include "content/outlook.typ"
#counter(heading).update(0)
#heading(numbering: none)[List of Figures]
#outline(
title: none,
target: figure.where(kind: image),
)
#include "glossary.typ"
#counter(heading).update(0)
#bibliography("bibliography.bib", style: "ieee", full: true)
//#pagebreak()
//Total word count: #total-words
#set page(footer: [])
#locate(loc => if calc.rem(loc.page(), 2) == 1 { pagebreak(to: "even") })
|
|
https://github.com/AU-Master-Thesis/thesis | https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/equation.typ | typst | MIT License | #let as-set(xs) = eval("${ " + xs.map(str).join(", ") + " }$")
#let as-list(xs) = eval("$[ " + xs.map(str).join(", ") + " ]$")
#let overdot(x) = math.accent(x, sym.dot)
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/writing-chinese.typ | typst | Apache License 2.0 | #import "mod.typ": *
#show: book.page.with(title: "中文排版")
建议结合#link("https://typst-doc-cn.github.io/docs/chinese/")[《Typst中文文档:中文用户指南》]食用。
== 中文排版 —— 字体
== 设置中文字体
如果中文字体不符合 typst 要求,那么它不会选择你声明的字体,例如字体的变体数量不够,参考更详细的 issue。
+ typst fonts 查看系统字体,确保字体名字没有错误。
+ typst fonts --font-path path/to/your-fonts 指定字体目录。
+ typst fonts --variants 查看字体变体。
+ 检查中文字体是否已经完全安装。
== 设置语言和区域
如果字体与 ```typc text(lang: .., region: ..)``` 不匹配,可能会导致连续标点的挤压。例如字体不是中国大陆的,标点压缩会出错;反之亦然。
=== 伪粗体
=== 伪斜体
=== 同时设置中西字体(以宋体和Times New Roman为例)
== 中文排版 —— 间距
=== 首行缩进
#let empty-par = par[#box()]
#let fake-par = context empty-par + v(-measure(empty-par + empty-par).height)
#let no-indent = context h(-par.first-line-indent)
#let a = {
1
}
=== 代码片段与中文文本之间的间距
=== 数学公式与中文文本之间的间距
== 中文排版 —— 特殊排版
=== 使用中文编号
=== 为汉字和词组注音
=== 为汉字添加着重号
=== 竖排文本
=== 使用国标文献格式
== Typst v0.10.0为止的已知问题及补丁
=== 源码换行导致linebreak
=== 标点字体fallback
== 模板参考
#link("https://github.com/typst-doc-cn/tutorial/blob/b452e6ec436aa150a6429becb8cf046d08360f63/typ/templates/page.typ")[本书各章节使用的模板]
todo: 内嵌和超链接可直接食用的模板
== 进一步阅读
+ 参考#link("https://typst-doc-cn.github.io/docs/chinese/")[《Typst中文文档:中文用户指南》],包含中文用户常见问题。
+ 参考#(refs.scripting-modules)[《模块、外部库与多文件文档》],在你的电脑上共享中文文档模板。
+ 推荐使用的外部库列表
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/proposals/8-vector-representation-for-rendering.typ | typst | Apache License 2.0 |
#show link: underline
#set page(height: auto)
#show heading: it => {
set text(size: (- it.level * 4pt) + 32pt)
it
}
#import "bytefield.typ": *
// code block setting
#show raw: it => {
if it.block {
rect(
width: 100%,
inset: (x: 4pt, y: 5pt),
radius: 4pt,
fill: rgb(239, 241, 243),
[
#set text(fill: rgb("#000000"))
#place(right, text(luma(110), it.lang))
#it
],
)
} else {
it
}
}
= Vector Format
```rs struct FlatModule``` uses variable-length tagged union to store data. The first $0~3$ bytes store the fixed string: #text(fill: green.darken(20%), [`"tsvr"`]). The bytes range from $8+32N$ to 40+32N store the $N$-th metadata.
#bytefield(
bits(8, fill: yellow.lighten(80%))[Magic], bits(8, fill: blue.lighten(80%))[`Tag = BuildVersion`], bits(8, fill: green.lighten(80%))[`Arc<BuildInfo>`], bits(16, fill: green.lighten(90%))[Padding], bits(8, fill: blue.lighten(80%))[`Tag = X`], bits(24, fill: green.lighten(80%))[`Value: Type(X)`], bits(8, fill: blue.lighten(80%))[`Tag = ..`], bits(24, fill: green.lighten(80%))[`Value: Type(..)`],
)
Currently there are 7 types of metadata in total:
```rs
pub enum ModuleMetadata {
BuildVersion(Arc<BuildInfo>),
SourceMappingData(Vec<SourceMappingNode>),
PageSourceMapping(Arc<LayoutRegion>),
GarbageCollection(Vec<Fingerprint>),
Item(ItemPack),
Glyph(Arc<GlyphPack>),
Layout(Arc<LayoutRegion>),
}
```
The first 6 types are stable, and this upgrade accompanies the modification of the Layout format: the ```rs enum ModuleMetadata::Layout(Arc<LayoutRegion>)```.
Note: *rkyv* guarantees appending new variant types without modifying existing variants, the binary format is backward compatible.
Points:
- We do not intend to allow other programming languages to use this _Vector Format_, so using rkyv can greatly reduce the difficulty of protocol design.
- Since we use rkyv, `Arc<T>` is essentially `rkyv::RelativePtr` for indexing, which means that the data of type `T` is stored elsewhere in the binary data.
=== Format Validation
- Sometimes, users may accidentally try to deserialize data in other formats as _Vector Format_, in which case the `magic` segment will come in handy to provide an appropriate error message, e.g.:
```
trying to deserialize bad vector data: expect head "tsvr" got "<html>\n <"
```
- To ensure alignment, bytes $4~7$ are reserved as zero bytes. And they may be repurposed in the future.
- The 0th Tag must be equal to `BuildVersion`, and its Value type must be `Arc<BuildInfo>`, which is used for stronger format detection than `magic`, for example, to lock the version between `compiler` and ` renderer`.
=== Compatibility
- rkyv allows the types of the same variant to be upgraded backwards compatibly, and incompatible upgrades should be avoided.
- A special type: ```rs struct Deprecated(())```, can help us deprecate old type segments and give warnings. For example:
```rs
type ItemPack = ItemPackV2;
pub enum ModuleMetadata {
Item(Deprecated),
ItemV2(Arc<ItemPack>),
}
```
- Backward compatibility is only considered between major versions to avoid too much garbage variants.
- We assume rkyv must have produced a stable binary format. The known issue is the stability across rust versions. *Without sacrificing performance*, it may consider a more stable rkyv layout in 0.5.0.
In fact, we also assume that typst documents are open source. With this assumption, we don't have to maintain backward compatibility, insteadly trying our best to ensure version consistency between compiler and renderer!
=== Major Changes since 0.4.0: `LayoutRegion`
The original ```rs struct LayoutPack``` is modified to ```rs struct LayoutRegion```:
```rs
pub enum LayoutRegion {
ByScalar(LayoutRegionRepr<Scalar>),
ByStr(LayoutRegionRepr<ImmutStr>),
}
pub struct LayoutRegionRepr<T> {
pub kind: ImmutStr,
pub layouts: Vec<(T, LayoutRegionNode)>,
}
pub enum LayoutRegionNode {
// next indirection
Indirect(usize),
// flat page layout
Pages(Arc<Vec<Page>>),
// source mapping node
SourceMapping(SourceMappingNode),
}
pub struct Page {
/// Unique hash to content
pub content: Fingerprint,
/// Page size for cropping content
pub size: Size,
}
```
The main design goal is to allow nested compilation of multi-layer layouts.
===== Simplest Case
For `typst-preview`, there is only the simplest case: `LayoutRegionRepr::kind` is `width`, and the variant of `LayoutRegionNode` must be `Page`. As follows:
```rs
use LayoutRegionNode::*;
layout = LayoutRegionByScalar {
kind: "width",
layouts: {
(350 * pt, Pages(vec![p0, p1])),
(700 * pt, Pages(vec![p2])),
}
}
```
===== Featured Layout
Considering high compression rate of sharing item data of `theme`, `LayoutRegion` can pack multiple themes when the extra overhead is acceptable. An example is as follows:
```rs
use LayoutRegionNode::*;
layouts = vec![
LayoutRegionByScalar {
kind: "theme",
layouts: {
("light", Indirect(1)),
("dark", Indirect(2)),
}
}
LayoutRegionByScalar { /* light theme */ },
LayoutRegionByScalar { /* dark theme */ },
]
return FlatModule {
items, // all of items collected from the light,dark theme.
layouts,
}
```
===== Lazy Loading with HTTP Request Header `Byte-Range`
According to preliminary experiments, github pages supports the `Byte-Range` request header:
```
curl --silent --range 20-60 https://myriad-dreamin.github.io/typst-book/guide/get-started.ayu.multi.sir.in | xxd
00000000: 6275 696c 6420 796f 7572 2062 6f6f 6b20 build your book
00000010: 616e 6420 7374 6172 7420 6120 6c6f 6361 and start a loca
00000020: 6c20 7765 6273 6572 76 l webserv
```
Ideally, even if all the data is in one file, it can be mapped remotely like `mmap` syscall by requesting appropriate byte ranges.
+ This technology may not shine in the short term.
+ Whatever, the current ```rs struct LayoutRegion``` is designed to facilitate the implementation of remote file mapping technology based on `Byte-Range`.
Note:
+ All variants of ```rs struct LayoutRegion``` must be ```rs struct LayoutRegionRepr```, since the type `T` is hidden in the `layouts` field, no matter how `T` changes, it will not affect the layout of ```rs LayoutRegion```.
+ The specific content of ```rs struct LayoutRegion``` is re-designated as ```rs struct LayoutRegionNode``` to allow subsequent upgrades.
|
https://github.com/Aadamandersson/typst-analyzer | https://raw.githubusercontent.com/Aadamandersson/typst-analyzer/main/components/syntax/test_data/parser/ok/if_else_if_expr.typ | typst | Apache License 2.0 | #if false {} else if true {}
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/color-font.typ | typst | Other | #import "/template/template.typ": web-page-template
#import "/template/components.typ": note
#import "/lib/glossary.typ": tr
#show: web-page-template
// ## Color and bitmap fonts
== 彩色与#tr[bitmap]字体
// We've seen that OpenType is now the leading font format in the digital world, and that it contains glyphs made out of Bézier curves. But you can actually draw glyphs in other ways and embed them in OpenType fonts too.
我们已经知道OpenType是目前数字世界中字体格式的领军人物,其中的#tr[glyph]使用贝塞尔曲线构造。但你其实也可以通过其他的方式绘制#tr[glyph]并把它们嵌入OpenType字体中。
// As we saw in the history chapter, the earliest fonts were bitmap fonts: all of the glyphs were pictures made out of pixels, which were not scalable. But the early fonts had quite small bitmaps, and so didn't look good when they were scaled up. If the bitmap picture inside your font is big enough, you would actually be scaling it *down* at most sizes, and that looks a lot better.
在介绍字体历史的章节中,最早出现的数字字体是#tr[bitmap]的:所有#tr[glyph]实际上是像素组成的图片,它们没法缩放。但这是因为早期的字体中的#tr[bitmap]都很小,所以在放大显示时观感不佳。如果字体中的#tr[bitmap]图足够大的话,实际上大多数情况下是在*缩小*它们的尺寸,而这就比放大的效果要好多了。
// And of course, another thing that's happened since the 1960s is that computer displays support more than one colour. The rise of emoji means that we now expect to have fonts with multi-colored glyphs - meaning that the font determines the colors to paint the glyph in, instead of having the application specify the color.
自从20世纪60年代以来,计算机显示领域发生的另一个巨大变化是支持了多色显示。emoji 的大量出现也让我们希望字体能够显示出多种颜色的#tr[glyph],这就意味着现在字体需要决定用什么颜色来绘制#tr[glyph]。在此之前这都是由应用程序来控制的。
// OpenType gives you a range of options for embedding colored and bitmapped images into your fonts: monochrome bitmaps, color bitmaps, color fonts, "Apple-style color fonts", and SVG fonts. These options can be mixed and matched; you can use more than one of these technologies in the same font, to allow for a greater range of application compatibility. For example, at the time of writing, a font with "color font" (COLR) outlines and SVG outlines will have the SVG outlines displayed on Firefox and the COLR outlines displayed on Internet Explorer and Chrome (which do not support SVG). The color bitmap font format (CBDT) is only really used by Google for emoji on Android.
OpenType 为在字体中嵌入彩色/#tr[bitmap]图片提供了多种选择:灰度#tr[bitmap]图、彩色#tr[bitmap]图、彩色字形、“Apple格式彩色图片”、SVG。你可以在字体里混合使用上述的多种技术,来最大化应用程序兼容性。比如在本书写作时,如果字体同时含有彩色#tr[outline](`COLR`)和 SVG,则Firefox可以显示其中的 SVG,在还不支持 SVG 字体的 IE 和 Chrome 中则可以显示 `COLR` 彩色字形。彩色#tr[bitmap]图(`CBDT`)格式只用在Google公司Android系统中的emoji上。
// See ["Color Fonts! WTF?"](https://www.colorfonts.wtf) for the latest news on support for color fonts by applications and browsers.
Color Fonts! WTF? 网站#[@Unknown.ColorFonts]介绍了各个应用和浏览器对于彩色字体格式的最新支持情况。
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.1.1/README.md | markdown | Apache License 2.0 | # Fletcher
_(noun) a maker of arrows_
[](https://github.com/Jollywatt/typst-fletcher/raw/master/docs/manual.pdf)

A [Typst]("https://typst.app/") package for drawing diagrams with arrows,
built on top of [CeTZ]("https://github.com/johannes-wolf/cetz").
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/Jollywatt/typst-fletcher/raw/master/docs/examples/example-2.svg">
<img alt="logo" width="600" src="https://github.com/Jollywatt/typst-fletcher/raw/master/docs/examples/example-1.svg">
</picture>
```typ
#arrow-diagram(cell-size: 15mm, {
let (src, img, quo) = ((0, 1), (1, 1), (0, 0))
node(src, $G$)
node(img, $im f$)
node(quo, $G slash ker(f)$)
conn(src, img, $f$, "->")
conn(quo, img, $tilde(f)$, "hook-->", label-side: right)
conn(src, quo, $pi$, "->>")
})
#arrow-diagram(
node-stroke: black,
node-fill: blue.lighten(90%),
node((0,0), `typst`),
node((1,0), "A"),
node((2,0), "B", stroke: 2pt),
node((2,1), "C"),
conn((0,0), (1,0), "->", bend: 15deg),
conn((0,0), (1,0), "<-", bend: -15deg),
conn((1,0), (2,1), "=>", bend: 20deg),
conn((1,0), (2,0), "..>", bend: -0deg),
)
```
## Todo
- [x] Mathematical arrow styles
- [ ] Support CeTZ arrowheads
- [ ] Allow referring to node coordinates by their content
- [ ] Support loops connecting a node to itself
- [ ] More ergonomic syntax to avoid repeating coordinates? |
https://github.com/typst/typst | https://raw.githubusercontent.com/typst/typst/main/docs/reference/context.md | markdown | Apache License 2.0 | ---
description: |
How to deal with content that reacts to its location in the document.
---
# Context
Sometimes, we want to create content that reacts to its location in the
document. This could be a localized phrase that depends on the configured text
language or something as simple as a heading number which prints the right
value based on how many headings came before it. However, Typst code isn't
directly aware of its location in the document. Some code at the beginning of
the source text could yield content that ends up at the back of the document.
To produce content that is reactive to its surroundings, we must thus
specifically instruct Typst: We do this with the `{context}` keyword, which
precedes an expression and ensures that it is computed with knowledge of its
environment. In return, the context expression itself ends up opaque. We cannot
directly access whatever results from it in our code, precisely because it is
contextual: There is no one correct result, there may be multiple results in
different places of the document. For this reason, everything that depends on
the contextual data must happen inside of the context expression.
Aside from explicit context expressions, context is also established implicitly
in some places that are also aware of their location in the document:
[Show rules]($styling/#show-rules) provide context[^1] and numberings in the
outline, for instance, also provide the proper context to resolve counters.
## Style context
With set rules, we can adjust style properties for parts or the whole of our
document. We cannot access these without a known context, as they may change
throughout the course of the document. When context is available, we can
retrieve them simply by accessing them as fields on the respective element
function.
```example
#set text(lang: "de")
#context text.lang
```
As explained above, a context expression is reactive to the different
environments it is placed into. In the example below, we create a single context
expression, store it in the `value` variable and use it multiple times. Each use
properly reacts to the current surroundings.
```example
#let value = context text.lang
#value
#set text(lang: "de")
#value
#set text(lang: "fr")
#value
```
Crucially, upon creation, `value` becomes opaque [content] that we cannot peek
into. It can only be resolved when placed somewhere because only then the
context is known. The body of a context expression may be evaluated zero, one,
or multiple times, depending on how many different places it is put into.
## Location context
We've already seen that context gives us access to set rule values. But it can
do more: It also lets us know _where_ in the document we currently are, relative
to other elements, and absolutely on the pages. We can use this information to
create very flexible interactions between different document parts. This
underpins features like heading numbering, the table of contents, or page
headers dependent on section headings.
Some functions like [`counter.get`]($counter.get) implicitly access the current
location. In the example below, we want to retrieve the value of the heading
counter. Since it changes throughout the document, we need to first enter a
context expression. Then, we use `get` to retrieve the counter's current value.
This function accesses the current location from the context to resolve the
counter value. Counters have multiple levels and `get` returns an array with the
resolved numbers. Thus, we get the following result:
```example
#set heading(numbering: "1.")
= Introduction
#lorem(5)
#context counter(heading).get()
= Background
#lorem(5)
#context counter(heading).get()
```
For more flexibility, we can also use the [`here`] function to directly extract
the current [location] from the context. The example below
demonstrates this:
- We first have `{counter(heading).get()}`, which resolves to `{(2,)}` as
before.
- We then use the more powerful [`counter.at`] with [`here`], which in
combination is equivalent to `get`, and thus get `{(2,)}`.
- Finally, we use `at` with a [label] to retrieve the value of the counter at a
_different_ location in the document, in our case that of the introduction
heading. This yields `{(1,)}`. Typst's context system gives us time travel
abilities and lets us retrieve the values of any counters and states at _any_
location in the document.
```example
#set heading(numbering: "1.")
= Introduction <intro>
#lorem(5)
= Background <back>
#lorem(5)
#context [
#counter(heading).get() \
#counter(heading).at(here()) \
#counter(heading).at(<intro>)
]
```
As mentioned before, we can also use context to get the physical position of
elements on the pages. We do this with the [`locate`] function, which works
similarly to `counter.at`: It takes a location or other [selector] that resolves
to a unique element (could also be a label) and returns the position on the
pages for that element.
```example
Background is at: \
#context locate(<back>).position()
= Introduction <intro>
#lorem(5)
#pagebreak()
= Background <back>
#lorem(5)
```
There are other functions that make use of the location context, most
prominently [`query`]. Take a look at the
[introspection]($category/introspection) category for more details on those.
## Nested contexts
Context is also accessible from within function calls nested in context blocks.
In the example below, `foo` itself becomes a contextual function, just like
[`to-absolute`]($length.to-absolute) is.
```example
#let foo() = 1em.to-absolute()
#context {
foo() == text.size
}
```
Context blocks can be nested. Contextual code will then always access the
innermost context. The example below demonstrates this: The first `text.lang`
will access the outer context block's styles and as such, it will **not**
see the effect of `{set text(lang: "fr")}`. The nested context block around the
second `text.lang`, however, starts after the set rule and will thus show
its effect.
```example
#set text(lang: "de")
#context [
#set text(lang: "fr")
#text.lang \
#context text.lang
]
```
You might wonder why Typst ignores the French set rule when computing the first
`text.lang` in the example above. The reason is that, in the general case, Typst
cannot know all the styles that will apply as set rules can be applied to
content after it has been constructed. Below, `text.lang` is already computed
when the template function is applied. As such, it cannot possibly be aware of
the language change to French in the template.
```example
#let template(body) = {
set text(lang: "fr")
upper(body)
}
#set text(lang: "de")
#context [
#show: template
#text.lang \
#context text.lang
]
```
The second `text.lang`, however, _does_ react to the language change because
evaluation of its surrounding context block is deferred until the styles for it
are known. This illustrates the importance of picking the right insertion point for a context to get access to precisely the right styles.
The same also holds true for the location context. Below, the first
`{c.display()}` call will access the outer context block and will thus not see
the effect of `{c.update(2)}` while the second `{c.display()}` accesses the inner context and will thus see it.
```example
#let c = counter("mycounter")
#c.update(1)
#context [
#c.update(2)
#c.display() \
#context c.display()
]
```
## Compiler iterations
To resolve contextual interactions, the Typst compiler processes your document
multiple times. For instance, to resolve a `locate` call, Typst first provides a
placeholder position, layouts your document and then recompiles with the known
position from the finished layout. The same approach is taken to resolve
counters, states, and queries. In certain cases, Typst may even need more than
two iterations to resolve everything. While that's sometimes a necessity, it may
also be a sign of misuse of contextual functions (e.g. of
[state]($state/#caution)). If Typst cannot resolve everything within five
attempts, it will stop and output the warning "layout did not converge within 5
attempts."
A very careful reader might have noticed that not all of the functions presented
above actually make use of the current location. While
`{counter(heading).get()}` definitely depends on it,
`{counter(heading).at(<intro>)}`, for instance, does not. However, it still
requires context. While its value is always the same _within_ one compilation
iteration, it may change over the course of multiple compiler iterations. If one
could call it directly at the top level of a module, the whole module and its
exports could change over the course of multiple compiler iterations, which
would not be desirable.
[^1]: Currently, all show rules provide styling context, but only show rules on
[locatable]($location/#locatable) elements provide a location context.
|
https://github.com/SabrinaJewson/cmarker.typ | https://raw.githubusercontent.com/SabrinaJewson/cmarker.typ/main/examples/tests.typ | typst | MIT License | #import "../lib.typ" as cmarker
#import "@preview/mitex:0.2.4": mitex
#cmarker.render(
read("tests.md"),
blockquote: box.with(stroke: (left: 1pt + black), inset: (left: 5pt, y: 6pt)),
raw-typst: true,
math: mitex,
show-source: false,
)
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/ttt-utils/0.1.0/lib/helpers.typ | typst | Apache License 2.0 |
/// if value is auto then return other value else return value itself
#let if-auto-then(val, ret) = {
if (val == auto) {
ret
} else {
val
}
}
// #let push_and_return(a_list, value) = {
// a_list.push(value)
// return a_list
// }
// #let increase_last(a_list, value) = {
// a_list.last() += value
// return a_list
// } |
https://github.com/nathanielknight/tsot | https://raw.githubusercontent.com/nathanielknight/tsot/main/src/util.typ | typst | #let dicier(t) = {
text(font: "Dicier Round", size: 8pt)[#t]
}
#let checkbox = {
box(width: 2.5mm, height: 2.5mm, stroke: 0.15mm + black, [])
}
#let checklist(content) = [
#set list(marker: checkbox)
#content
]
|
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-8/BDC/homework1/doc/cafeteira.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 text(lang: "pt")
#set page(
footer: "Engenharia de Telecomunicações - IFSC-SJ",
)
#show: doc => report(
title: "Implementação de dados de 'Cafeteira' em CSV ",
subtitle: "Banco de Dados",
authors: ("<NAME>",),
date: "24 de Setembro de 2024",
doc,
)
= Objetivo
O objetivo desta tarefa é apresentar um sistema de gerenciamento de dados de uma cafeteira, onde o sistema deve ser capaz de armazenar informações de usuários e histórico de cafés em arquivos CSV.
= Desenvolvimento:
O sistema foi desenvolvido em Java, e é composto por duas funções principais: `escreve` e `le`. A função `escreve` é responsável por escrever uma lista de listas de strings em um arquivo CSV, enquanto a função `le` é responsável por ler um arquivo CSV e retornar uma lista de listas de strings.
Abaixo está o código .java modificado durante a aula de BDC:
#sourcecode[```java
// BDC - Homework 1
// Aluno: <NAME>
// Importando as bibliotecas necessárias
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
// Classe Cafeteira
public class Cafeteira {
/* Método escreve
* Escreve uma lista de listas de strings em um arquivo CSV
* @param linhas: lista de listas de strings
* @param filename: nome do arquivo
*/
public static void escreve(List<List<String>> linhas, String filename) {
try {
FileWriter arquivo = new FileWriter(filename, true);
for (List<String> elem : linhas) {
arquivo.append(String.join(",", elem));
arquivo.append("\n");
}
// imprimir o conteúdo da lista no terminal:
for (List<String> elem : linhas) {
System.out.println(String.join(",", elem));
}
arquivo.flush();
arquivo.close();
} catch(IOException e) {
e.printStackTrace();;
}
}
/* Método le
* Lê um arquivo CSV e retorna uma lista de listas de strings
* @param pathname: caminho do arquivo
* @return linhas: lista de listas de strings
*/
public static ArrayList<ArrayList<String>> le(String pathname) {
ArrayList<ArrayList<String>> linhas = new ArrayList<ArrayList<String>>(0);
try {
File entrada = new File(pathname);
Scanner linha = new Scanner(entrada);
while (linha.hasNext()) {
String[] registro = linha.nextLine().split(",");
ArrayList<String> list = new ArrayList<>(Arrays.asList(registro));
linhas.add(list);
}
} catch(FileNotFoundException e) {
e.printStackTrace();;
}
return linhas;
}
/* Método main
* Função principal do programa
* @param args: argumentos da linha de comando
*/
public static void main(String[] args) {
System.out.println("Cafeteira System");
// Inicializando variáveis
boolean continua = true;
int opcao = 0;
int id = 0;
// Inicializando o scanner
Scanner in = new Scanner(System.in);
while(continua) {
// Menu de opções
System.out.println("================");
System.out.println("Digite 1: Para informações de usuário");
System.out.println("Digite 2: Para histórico de cafés");
System.out.println("Digite 3: Para informações da cafeteira");
System.out.println("Digite 4: Para sair");
System.out.print("Sua opção: ");
opcao = in.nextInt();
// Laço de verifição de opções
if(opcao == 1) {
System.out.print("Entre com o id do usuário: ");
id = in.nextInt();
System.out.println("\tId " + id + " selecionado para informações de usuário");
ArrayList<ArrayList<String>> linhas = le("usuarios.csv");
// imprime todas as linhas do arquivo:
for (ArrayList<String> elem : linhas) {
System.out.println(String.join(",", elem));
}
}else if(opcao == 2) {
System.out.print("Entre com o id do usuário: ");
id = in.nextInt();
System.out.println("\tId " + id + " selecionado para histórico de cafés");
ArrayList<ArrayList<String>> linhas = le("usuarios.csv");
// imprime todas as linhas do arquivo:
for (ArrayList<String> elem : linhas) {
System.out.println(String.join(",", elem));
}
}else if(opcao == 3) {
System.out.println("Informações da cafeteira:");
System.out.println("\tÓtima cafeteira");
}else if(opcao == 4) {
continua = false;
}
}
}
}
```]
O código acima pode consultar e imprimir os dados de usuários e histórico de cafés armazenados em arquivos CSV, conforme apresentado abaixo:
#sourcecode[```csv
123,juca,arthur@email
124,maria,maria@email
125,joao,joao@email
```]
|
https://github.com/The-Notebookinator/notebookinator | https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/components.typ | typst | The Unlicense | #import "./toc.typ": *
#import "./glossary.typ": *
#import "./gantt-chart.typ": *
#import "./admonitions.typ": *
#import "./label.typ": *
#import "./team.typ": *
#import "./pro-con.typ": *
#import "./decision-matrix.typ": *
#import "./tournament.typ": *
#import "./graphs.typ": *
|
https://github.com/34j/hexo-renderer-pdf | https://raw.githubusercontent.com/34j/hexo-renderer-pdf/main/example.typ | typst | MIT License | // Title should be set (Modified here)
#set document(title: "Fibonacci sequence (title)", author: ("Author1", "Author2"), date: datetime.today(), keywords: ("Fibonacci", "Math"))
// Math font must be set (Modified here)
#show math.equation: set text(font: "Cambria Math")
#set page(width: 10cm, height: auto)
#set heading(numbering: "1.")
= Fibonacci sequence
The Fibonacci sequence is defined through the
recurrence relation $F_n = F_(n-1) + F_(n-2)$.
It can also be expressed in _closed form:_
$ F_n = round(1 / sqrt(5) phi.alt^n), quad
phi.alt = (1 + sqrt(5)) / 2 $
#let count = 8
#let nums = range(1, count + 1)
#let fib(n) = (
if n <= 2 { 1 }
else { fib(n - 1) + fib(n - 2) }
)
The first #count numbers of the sequence are:
#align(center, table(
columns: count,
..nums.map(n => $F_#n$),
..nums.map(n => str(fib(n))),
))
#emoji.face.grin
|
https://github.com/Area-53-Robotics/Unofficial-Old-53E-NB | https://raw.githubusercontent.com/Area-53-Robotics/Unofficial-Old-53E-NB/main/main.typ | typst | #import "/packages.typ": *
// applies the template
// the show rule essentially passes the entire document into the `notebook` function.
#show: notebook.with(
team-name: "53E",
season: "High Stakes",
year: "2024-2025",
theme: radial-theme,
cover: align(center + horizon)[
#text(size: 24pt, font: "Tele-Marines")[
#text(size:30pt)[
Engineering Notebook
]
#image("./photos/53E_logo.png", height: 70%)
2024-2025
#line(length: 50%, stroke: (thickness: 2.5pt, cap: "round"))
High Stakes
]
]
)
#include "./frontmatter.typ"
#include "./entries/entries.typ"
#include "./appendix.typ"
|
|
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/thesis.typ | typst | MIT License | #import "resources\lib.typ": documentclass, indent
// 你首先应该安装 /fonts/FangZheng 里的所有字体,
// 强烈推荐安装思源宋体和思源黑体的所有字重
// https://github.com/adobe-fonts/source-han-serif/releases/download/2.002R/09_SourceHanSerifSC.zip
// https://github.com/adobe-fonts/source-han-sans/releases/download/2.004R/SourceHanSansSC.zip
#let (
// 布局函数
twoside, doc, preface, mainmatter, mainmatter-end, appendix,
// 页面函数
fonts-display-page, cover, title, decl-page, abstract, abstract-en, bilingual-bibliography,
outline-page, list-of-figures, list-of-tables, notation, acknowledgement,conclusion,
onum: o,
) = documentclass(
// anonymous: true, // 盲审模式
twoside: false , // 双面模式,会加入空白页,便于打印
// 可自定义字体,先英文字体后中文字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」
// fonts: (楷体: ("Times New Roman", "FZKai-Z03S")),
info: (
//基本信息
title: "量子力学下的代码质量与代码进化论",
title-en: "Code Quality and Evolution under Quantum Mechanics",
grade: "20XX",
student-id: "218111545200",
author: "张居正",
author-en: "<NAME>",
department: "电气与信息工程学院",
department-en: "School of Electrical and Information Engineering",
major: "软件工程",
major-en: "Software Engineering",
supervisor: ("某某", "教授"),
supervisor-en: "Professor My Supervisor",
submit-date: datetime.today(),
sign-date:datetime(day: 17, month: 7, year: 2024),
),
// 参考文献源
bibliography: bibliography.with("ref.bib"),
)
// 文稿设置
#show: doc
// 字体展示测试页
#fonts-display-page()
// 封面页
#cover()
//标题页面
#title()
// 声明页
#decl-page()
// 前言
#show: preface
// 中文摘要
#abstract(
keywords: ("软件工程","量子力学","生物进化论","代码质量","代码进化")
)[
本文探讨了软件工程在量子力学与生物进化论指导下的种种奥秘。通过对代码的哲学思考和伪科学论证,我们揭示了代码质量对于软件宇宙平衡的重要性,以及量子态如何影响代码的演化与进化。
]
// 英文摘要
#abstract-en(
keywords: ("Software Engineering","Quantum Mechanics","Biological Evolution","Code Quality","Code Evolution")
)[
This paper explores the mysteries of software engineering under the guidance of quantum mechanics and biological evolution. Through philosophical reflections and pseudo-scientific arguments on code, we reveal the importance of code quality for the balance of the software universe and how quantum states affect the evolution and development of code.
]
// 目录
#outline-page()
// 插图目录
// #list-of-figures()
// 表格目录
// #list-of-tables()
//解决页码问题
#counter(page).update(0)
#pagebreak()
// 正文
#show: mainmatter
// 符号表
// #notation[
// / DFT: 密度泛函理论 (Density functional theory)
// / DMRG: 密度矩阵重正化群密度矩阵重正化群密度矩阵重正化群 (Density-Matrix Reformation-Group)
// ]
//要用空格控制间距的情况:请复制使用:这里的---> <---这里的,或者输入 \u{3000}
= 绪论
== 引言
软件工程,作为一种跨学科的领域,融合了计算机科学、项目管理、哲学及艺术等多重元素。
它不仅在科技进步中扮演着至关重要的角色,也是推动社会发展的不可或缺的力量。在这种复杂的工程活动中,代码质量是一个恒久不变的话题。代码的好坏不仅影响软件系统的稳定性和性能,更关系到整个开发团队的效率和产品的市场竞争力。
然而,当我们从传统观念中跳脱出来,用更具哲学与科学交融的视角来看待软件工程时,新的发现接踵而至。量子力学,通常用以描述微观世界的运动规律,赋予我们一种全新的思维方式来理解代码的状态和行为。而生物进化论,作为解释生物多样性和复杂性的理论基础,为我们提供了一个观察软件系统进化的类比视角。
本文试图以一种幽默风趣的方式,将量子力学与生物进化论的奇思妙想引入软件工程,探索这些前沿理论如何重塑我们对代码质量和代码演化的理解。通过结合量子态的叠加性、坍缩性和进化论的自然选择原理,我们将展开一场别开生面的代码哲学之旅。
首先,量子力学的基本思想使我们认识到代码的多重可能性。
在开发环境中,代码在被执行之前,可能存在于完美无瑕和漏洞百出的叠加态中;只有当开发者进行代码审查或测试时,系统才会从叠加态中坍缩到一个确定的状态。
其次,生物进化论为我们描绘了软件系统的成长与适应过程。通过自然选择,优秀的代码迎合环境需求不断演化,而劣质代码则逐渐被淘汰。就像生物体基因突变带来多样性一样,代码的重构和更新也推动着软件系统的进步。
最后,混沌理论提醒我们,软件系统中的微小变动可能引发巨大变化,小小的BUG或许会造成整个系统的奔溃,就如蝴蝶效应般不可预测。这在开发和维护过程中尤为显著,警示着我们对细节把控的重要性。
通过本文,我们不但希望揭示量子力学和生物进化论对软件工程的潜在影响,更期望带给读者一种全新的视角,以一种娱乐性的方式来思考和理解代码质量和演化的深刻内涵。
== 列表
=== 无序列表
- 无序列表项一
- 无序列表项二
- 无序子列表项一
- 无序子列表项二
=== 有序列表
+ 有序列表项一
+ 有序列表项二
+ 有序子列表项一
+ 有序子列表项二
=== 术语列表
/ 术语一: 术语解释
/ 术语二: 术语解释
== 图表
引用@tbl:timing-tlt2,以及@fig:just-logo。引用图表时,表格和图片分别需要加上 `tbl:`和`fig:` 前缀才能正常显示编号。
// #figure(
// table(
// align: center + horizon,
// columns: 4,
// [t], [1], [2], [3],
// [y], [0.3s], [0.4s], [0.8s],
// ),
// caption: [常规表],
// ) <timing>
#figure(
table(
columns: 8,
column-gutter: 1em,
stroke: none,
table.hline(),
[t], [1], [2], [3],[t], [121313], [2312331], [123123rrrrt],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [0.8s],[tttttt213], [1], [2], [3],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [0.8s],[t], [1], [2], [3],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [0.8s],[ttttt3], [1], [2], [3],
table.hline(),
),
caption: [三线表],
) <timing-tlt>
#align(center+horizon, (stack(dir: ltr)[
#figure(
table(
columns: 4,
column-gutter: 2em,
stroke: none,
table.hline(),
[t], [1], [2], [3],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [1.5s],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [1.5s],
table.hline(),
),
caption: [三线表],
) <timing-tlt1>
][
#h(40pt)
][
#figure(
table(
columns: 4,
column-gutter: 2em,
stroke: none,
table.hline(),
[t], [1], [2], [3],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [1.5s],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [1.5s],
table.hline(stroke: .5pt),
[y], [0.3s], [0.4s], [1.5s],
table.hline(),
),
caption: [三线表],
) <timing-tlt2>
]))
#figure(
image("images/just-emblem.png", width: 30%),
caption: [图片测试],
) <just-logo>
== 数学公式
可以像 Markdown 一样写行内公式 $x + y$,以及带编号的行间公式:
$ phi.alt := (1 + sqrt(5)) / 2 $ <ratio>
#indent 引用数学公式需要加上 `eqt:` 前缀,则由@eqt:ratio,我们有:
$ F_n = floor(1 / sqrt(5) phi.alt^n) $
#indent 我们也可以通过 `<->` 标签来标识该行间公式不需要编号
$ y = integral_1^2 x^2 dif x $ <->
#indent 而后续数学公式仍然能正常编号。
$ F_n = floor(1 / sqrt(5) phi.alt^n) $
== 参考文献
可以像这样引用参考文献:图书#[@2022Software]和会议#[@中国力学学会1990]。
理论上会自动缩进,偶尔失效段落前手动缩进加上\#indent即可
== 代码块
代码块支持语法高亮。引用时需要加上 `lst:` @lst:code
#figure(
```py
def add(x, y):
return x + y
```,
caption:[代码块],
) <code>
= 量子力学与代码质量
== 量子叠加态与代码状态
在量子态中,代码的状态既是完美的,又是充满BUG的。每一行代码在开发与测试阶段,都存在于完美无缺和漏洞百出的叠加态中。举例来说,一段代码在编写完成后,如果未经过测试或代码审查,从量子力学的角度看,它同时具有运行无误与出错的双重可能性。就像薛定谔的猫既是活的又是死的一样,代码在这一时刻处于未确定状态的叠加态。
这种现象在实际开发过程中尤为显著。假设开发者编写了一段新的功能代码,在代码审查、单元测试或集成测试之前,这段代码对系统的影响具有极大不确定性。代码本身的缺陷及其对系统的影响,只有在开发者进行代码审查和测试时,代码状态才从叠加态坍缩为单一的确定态,要么是运行正常,要么暴露出存在的BUG。
== 量子坍缩与代码检验
此坍缩过程的完美描述,只能通过量子力学的公式加以解释。薛定谔方程是量子力学的基本公式之一,它描述了量子系统在不同状态之间的演化:
$ hat(H)_psi = E_psi $
在这一方程中, $psi$ 表示系统的量子态, $hat(H)$ 是哈密顿量,描述系统的能量, $E$ 是系统的特征值。对应到代码质量上,代码在未进行审查前,其质量状态 $psi$ 是各种可能性的叠加态,而审查和测试过程则充当了观测者,促使代码状态坍缩到具体的运行结果。
== 量子纠缠与代码关联性
量子纠缠现象在软件工程中也能找到类比。例如,两个彼此关联的代码模块,即使相距甚远,在修改一个模块时,另一个模块也会受到不可预见的影响。这种现象类似于量子纠缠,无论两个粒子相距多远,对一个粒子的操作会即刻对另一个产生影响。这种神秘的关联性在代码维护和调试过程中同样存在。
== 量子视角下的代码质量洞见
通过量子力学的透镜,我们不仅可以重新思考代码状态的本质,还可以揭示代码质量问题的潜在原因。量子理论的引入,使我们对代码质量问题有了更深刻而多元的理解,也为未来的软件工程方法论提供了启示。
= 生物进化论与代码演化
在探讨代码演化的过程中,我们发现其与生物进化论之间存在惊人的相似性。正如达尔文在其著作《物种起源》中阐述的自然选择原理,代码也在不断地经历着“适者生存”的过程。本章节将深入分析这一类比,探讨代码如何像生物一样进化,以及遗传算法在代码优化中的应用。
== 达尔文进化论与代码演化
达尔文的进化论核心在于物种的变异、遗传和自然选择。这些概念同样适用于代码世界:
- 变异:在编程中,变异可以被视为代码的修改或重构,这可能是因为需求的变化、技术的进步或是对性能的追求。
- 遗传:代码库通过版本控制进行遗传,新版本继承了旧版本的特性,并在此基础上进行优化或扩展。
- 自然选择:在软件开发中,代码的质量决定了其生存能力。低效、冗余或错误的代码会被逐步淘汰,而高效、简洁且可靠的代码则会被保留下来。
== 遗传算法在代码演化中的应用
遗传算法是一种基于自然选择和遗传学原理的搜索算法,它在代码优化领域展现出了巨大的潜力。以下是遗传算法应用于代码演化的主要步骤:
- *初始化种群*:创建一个包含多种代码实现方案的初始种群,每个个体代表一种可能的解决方案。
- *适应度评估*:根据特定的标准(如运行效率、代码复杂度)评估每个个体的适应度。
- 选择:从当前种群中选择适应度较高的个体作为下一代的父母。
- 交叉(重组):通过组合两个父母的特征来产生新的后代,模拟生物中的遗传重组。
- 变异:随机改变一些后代的某些特征,引入新的变异,增加种群的多样性。
- 迭代:重复上述过程,直到达到预定的停止条件,如最大迭代次数或满足某个性能阈值。
== 案例研究:遗传算法优化代码实例
以一个简单的排序算法为例,假设我们的目标是寻找最优的排序策略,以最小化执行时间。我们可以定义一个包含不同排序方法的种群,如冒泡排序、插入排序、快速排序等。通过反复应用选择、交叉和变异操作,逐渐筛选出执行效率最高的排序算法。实验结果表明,经过多代演化后,种群中会出现显著优于原始算法的个体,证明了遗传算法在代码优化中的有效性。
== 结论
代码演化是一个复杂但有序的过程,它遵循类似于生物进化的规律。通过借鉴达尔文的进化论和应用遗传算法,我们不仅能够理解和预测代码的演变趋势,还能主动优化代码,提高软件系统的质量和效率。未来的研究应进一步探索代码演化与其他生物学理论之间的联系,以期在软件工程领域开辟新的研究方向和实践方法。
= 混沌理论与代码的反馈圈
== 蝴蝶效应与代码调试
混沌理论的核心之一是“蝴蝶效应”,即系统对初始条件的极端敏感性。在软件开发中,这种现象表现为微小的编码错误或参数调整可能导致系统行为的巨大偏差。例如,一个看似无关紧要的变量赋值错误,可能在一系列复杂的函数调用和数据交互后,引发整个系统的不稳定甚至崩溃。
== 反馈圈与代码演化
软件系统内部存在着复杂的反馈机制。代码的修改不仅影响当前功能的实现,还可能通过间接路径作用于其他模块,产生连锁反应。这种反馈圈使得代码的演化成为一项充满挑战的任务,因为任何变动都可能引起意想不到的结果。理解并管理这些反馈圈是确保软件稳定性和可维护性的关键。
== 随机漂移与代码质量
代码质量的衡量标准随时间和项目需求而变化,这使得代码库在多维度下呈现出随机漂移的特性。一方面,随着技术的发展和团队知识的积累,代码逐渐趋向于更加高效、安全和可读;另一方面,由于项目复杂度的增加和外部环境的不确定性,代码也可能出现退化。这种动态平衡状态体现了混沌理论中的非线性系统特征。
= 宇宙的代码:编程与人生哲学
== 代码的混沌与秩序
在软件工程中,混沌与秩序的辩证关系无处不在。一方面,代码的编写和调试充满了不确定性,需要开发者面对未知和混乱;另一方面,通过精心设计的架构和严谨的测试,可以建立有序的系统,使混沌得以控制。这种平衡反映了自然界和社会中普遍存在的混沌与秩序的共生现象。
== 编程与人生哲学
软件开发不仅仅是技术活动,更是一门艺术和哲学。每一行代码都是开发者思想的体现,包含了对问题的理解、解决问题的策略以及对未来的预判。编程过程中遇到的挑战和挫折,与人生旅途中的困难和抉择相呼应,每一次代码的优化和BUG的修复都像是生活中的成长与领悟。正如宇宙的运行遵循着复杂的物理法则,人生的轨迹也受制于内在的逻辑和外在的环境。
== 代码即人生,人生即代码
从某种意义上说,代码与人生有着深刻的相似性。它们都经历了从无到有、从小到大、从简单到复杂的过程,都在不断适应变化、寻求优化、追求完美。无论是编程还是生活,都需要我们保持好奇心、勇于探索、善于学习和反思。通过编程,我们不仅能构建出精妙的软件系统,也能更好地理解自己和这个世界。
= 测试正文
== 正文子标题
这是第二级标题
=== 正文子子标题
这是三级标题
#lorem(50)
3123798什么
+ 正文内容
+ 123什么什么标题
+ 如果你在这级标题下
#lorem(50)
+ 213 2312丑陋丑陋
+ 234234234非常丑陋
#lorem(50)
#o(1)3123123测试
#o(2)假如说这个序号后面的文字过长出现了需要换行的情况,那么缩进会出现错\ #h(3em)误,建议使用`\ #h(3em)`手动处理
#o(3)3123123
#o(4)3123123
=== 正文子子标题
231231
//结论
#show:conclusion
= 结论
== 量子力学、生物进化论与代码哲学
本文创新性地将量子力学和生物进化论的理论框架应用于软件工程领域,以一种新颖而幽默的角度探讨了代码质量与代码进化的问题。通过量子态的坍缩比喻代码状态的确定性,以及进化论中自然选择机制解释代码的优化过程,我们不仅揭示了代码背后的科学原理,也展现了其丰富的哲学内涵和人文价值。
== 代码的哲理与趣味
代码,作为人类智慧的结晶,承载着开发者的思想、情感和创造力。它不仅仅是一串指令的集合,更是连接现实与虚拟、过去与未来、个人与社会的桥梁。在代码的世界里,我们看到了量子力学中的不确定性原理与软件工程中对精确性的追求之间的张力,也体会到了进化论中优胜劣汰原则与代码持续改进过程的共鸣。这些哲理与趣味交织在一起,构成了软件工程独特的魅力。
== 展望未来
展望未来,随着人工智能、大数据、区块链等新兴技术的快速发展,代码将扮演更加重要的角色,成为推动社会进步和人类文明发展的关键力量。同时,代码的哲学思考也将日益深化,促使我们从更广阔的视角审视技术与社会的关系,思考人与机器、自然与创造之间的和谐共生之道。
// 手动分页
#if twoside {
pagebreak() + " "
}
// 中英双语参考文献
// 默认使用 gb-7714-2015-numeric 样式
#bilingual-bibliography(full: true)
// 致谢
#acknowledgement[
首先感谢 NJUThesis Typst 模板。
在结束这篇探索之旅之际,我想表达最深切的感激之情。首先,我要感谢量子力学与生物进化论这两大学科,它们不仅为自然科学的发展奠定了坚实的基础,更为我的研究提供了丰富的灵感源泉。正是这些理论的博大精深,激发了我将它们与软件工程这一现代技术领域相结合的创意,从而诞生了这篇别具一格的论述。
其次,我衷心感谢所有在学术道路上给予我指导和支持的导师和同行。你们的鼓励、批评和建议,如同一盏明灯,照亮了我前行的道路,帮助我克服了研究过程中的重重困难。特别要感谢那些愿意倾听我荒诞想法的人,是你们的开放心态和包容精神,让这场跨界对话成为了可能。
此外,我也要向家人和朋友们表示深深的谢意。你们的理解、耐心和爱,是我最坚强的后盾。在我沉浸于研究、疏于陪伴的日子里,是你们的无私支持让我能够心无旁骛地追求知识的光芒。
最后,我想对每一位读者说声谢谢。无论你是专业的学者、热情的学生,还是偶然间翻阅这篇文章的路人,你们的关注和反馈都是对我最大的鼓舞。希望我的研究能够激发你的好奇心,带给你新的启示,就如同量子力学与生物进化论曾经给予我的那样。
再次感谢量子力学与生物进化论,是它们的智慧之光,照亮了我的思维空间,让我在这片浩瀚的知识海洋中自由航行。这段旅程或许已经告一段落,但我相信,探索的脚步永远不会停歇。愿我们都能在各自的领域中,继续追寻真理,拥抱未知,共创美好未来。
谨以此文献给所有热爱探索、勇于创新的心灵。
]
// 手动分页
#if twoside {
pagebreak() + " "
}
// 附录
#show: appendix
= 附录
== 附录子标题
=== 附录子子标题
附录内容,这里也可以加入图片,例如@fig:appendix-img。
#figure(
image("images/just-emblem.png", width: 30%),
caption: [图片测试],
) <appendix-img>
// 正文结束标志,不可缺少
// 这里放在附录后面,使得页码能正确计数
#mainmatter-end() |
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/meta-documentation/information_architecture/controlled_vocabulary.typ | typst |
workpiece - the work being used in a machine. |
|
https://github.com/suspenss/Undergraduate-mathematics | https://raw.githubusercontent.com/suspenss/Undergraduate-mathematics/main/Probability%20Theory/main.typ | typst | #import "./../setup/templates.typ": *
#import "./../setup/theorem.typ": *
#show: thmrules
// #show math.equation: set text(font: "New Computer Modern Math")
// #show math.equation: set text(font: "Libertinus Math")
#show: project.with(
title: "概率论笔记", authors: ("epoche",), language: "ch", outl: [
#outline(indent: true, title: "目录", depth: 2)
],
)
#show math.ast: math.thin
#let obey = math.tilde
= 基本概念
== 运算
若 $A$ 代表事件 $A$ 发生, $overline(A)$ 代表事件没有发生,我们定义如下在随机事件上的关系运算:
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt, inset: 5pt,
[包含], [差集],
[ $ A subset B <=> A -> B
\ "另外有" A = B <=> A subset B and B subset A $ ],
[$ A - B <=> A and overline(B)
\ "另外有" A - B = A - A B = A overline(B) $],
[], [],
[交集], [并集],
[$ A sect B <=> A and B $], [$ A union B <=> A or B $],
)
对于交集和并集运算,符合以下四种运算律:
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt, inset: 5pt,
[_交换律_], [结合律 ],
[$ A union B = B union A
\ A sect B = B sect A $],
[$ (A union B) union C = A union (B union C)
\ (A sect B) sect C = A sect (B sect C) $ ],
[], [],
[分配律], [对偶律(德摩根定律)],
[$ (A union B) sect C = (A sect C) union (B sect C)
\ (A sect B) union C = (A union C) sect (B union C) $],
[$ overline(A union B) = overline(A) sect overline(B)
\ overline(A sect B) = overline(A) union overline(B) $],
)
== 关系
在事件间,存在如下两种关系:
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt,
[互斥事件], [对立事件],
[$A sect B = diameter$],
[$A sect B = diameter and A union B = Omega.$],
)
== 频率和概率
#definition[
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt,
[频率], [概率],
[$ f_n (A) = n_A / n $],
[$ P(A) = limits(lim)_(n -> infinity) f_n (A) -> P $],
)
]
#properties(
)[
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt,
[非负性], [规范性],
[ $ 0 <= P(A) <= 1 $ ],
[ $ P(Omega) = 1, P(diameter) = 0$ ],
[], [],
[无限可加性], [互补性],
[ $ "If" A sect B = diameter
\ "then" P(A union B) = P(A) + P(B) $ ],
[$ P(overline(A)) = 1 - P(A) $],
)
]
概率之间存在如下运算:
#definition(
"运算",
)[
+ 减法:$P(A - B) = P(A) - P(A B) ," If" B subset A, P(A - B) = P(A) - P(B)$
+ 加法:$P(A + B) = P(A union B) = P(A) + P(B) - P(A B)$
+ 乘法:$P(A B) = P(A sect B) = P(A) P(B | A) $
]
// #table(
// columns: 1fr,
// align: center,
// stroke: 0pt,
// [1. _减法_
// $ P(A - B) = P(A) - P(A B) \ "If" B subset A, P(A - B) = P(A) - P(B). $],
// )
// #table(
// columns: (1fr, 1fr),
// align: center,
// stroke: 0pt,
// [2. 加法
// $ P(A union B) = P(A) + P(B) - P(A B) $],
// [3. 乘法
// $ P(A B) = P(A) P(B | A) $]
// )
== 条件概率
#definition(
)[
如果 $P(A) > 0$,则条件概率为 $P(B | A) = P(A B) / P(A)$。
]
依此,我们有两条推广式:
+ $P(B union C | A) = P(B | A) + P(C | A) - P(B C | A)$
+ $P(B - C | A) = P(B | A) - P(B C | A)$
== 全概率与贝叶斯公式
#definition(
"完备事件组",
)[
$S = {A_1, A_2, A_3 , ... , A_n}$ 是一个属于 $Omega$ 的事件组,并且满足
$forall A_1, A_2 subset S, A_1 sect A_2 = diameter, and A_1 union A_2 union A_3 union ... union A_n = Omega$,则 $S$ 为一个完备事件组。
]
由定义,我们可以设 $B$ 是一个随机事件, ${A_1,A_2, ..., A_i}$ 是一个完备事件组,我们有:
#formula(
"全概率公式",
)[
$ P(B) &= sum_(i = 1)^n P(A_i)P(B | A_i)
\ & =sum_(i = 1)^n P(B A_i) $
]
#formula(
"贝叶斯公式",
)[
$ P(A_i | B) = P(A_i B) / P(B) = (P(A_i) P(B | A_i) ) / (sum_(i = 1)^n P(A_i)P(B | A_i)) $
]
== 事件的独立性
若 $A$,$B$ 是相互独立事件,则有 $ P(A | B) = P(A) &<=> P(A B) = P(A) P(B)
\ &<=> P(B | A) = P(B | overline(A))
\ &<=> P(B | overline(A)) = P(B) $
且 $A, overline(A), B, overline(B)$ 也相互独立,此外有
$ "若" A, B, C "互为独立事件" --> & A, B, C "两两独立" \
"若" A, B, C "互为独立事件" --> & "关于" A, B "的加法,乘法,减法"
\ &"以及逆运算也分别独立与" C "和 " overline(C) $
== 伯努利概型
#definition(
"伯努利实验",
)[
实验只有两种可能结果 $A, overline(A)$ 的实验叫做伯努利实验。
]
#formula(
"二项概率公式",
)[
$ binom(n, k) p^k (1 - p)^(n - k) $
]
= 随机变量及其分布
== $R.V.$ 和 分布函数
$R.V.$ 是一个从随机试验 $E$ 的样本空间 $Omega$ 到 $RR$ 的一个映射。
== 分布函数
#definition[
设 $X$ 是一个随机变量, $r$ 是任意实数,则称事件 ${X <= r}$ 的概率为 $R.V. space X$ 的分布函数,计作 $F(r)$ 。
]
分布函数有如下性质:
#properties(
"范围概率",
)[$P{x_1 < X <= x_2} = P{X <= x_2} - P{X <= x_1} = F(x_2) - F(x_1)$]
#properties(
"增减性",
)[$F(x)$ 是一个不减函数]
#properties(
"规范性",
)[$F(-oo) = 0,F(+oo) = 1$]
== 离散型随机变量及其分布
=== 常见的分布
#definition(
[0 - 1 分布],
)[
若随机变量 $X$ 分布服从下方分布列,其中 $0 < p < 1$,则称为 0 - 1 分布或两点分布。
#align(
center,
)[#table(
columns: 3, [$X$], [0], [1], [P], [$p$], [$1 - p$],
)]
]
#definition(
[二项分布],
)[
计作 $X tilde B(n, p)$
$ P{X = k} = C_n^k p^k (1 - p)^(n - k), k in {x | x in NN^+ sect [0, n]} $
]
#definition(
[泊松分布],
)[
计作 $X tilde P(lambda)$
$ P{X = k} = (lambda^k e^(-lambda))/(k!) , quad quad (lambda > 0) $
]
#definition(
[几何分布],
)[
$P{X = k} = (1 - p)^(k - 1) * p$
]
#definition(
[超几何分布],
)[
计作 $X tilde H(N, M, n)$
$ P{X = k} = (binom(M, k) binom(N - M, n - k)) / binom(N, n), space k in {1, 2, 3, ... min(M, N)} $
]
#theorem(
"泊松定理",
)[
当 $X tilde B(n, p)$ 且 $n$ 充分大,$p$ 充分小时
$
binom(n, k)p^k (1 - p)^(n - k) approx (lambda^k e^(-lambda)) / (k!), lambda = n p
$
]
== 连续型随机变量
#definition(
"分布函数",
)[
若 $f(t)$ 是概率密度函数,则分布函数 $F(x)$ 为
$
F(X) = integral_(-oo)^x f(t) dif t
$
]
#formula(
"区间概率公式",
)[
$F{ a < X < b} = integral_a^b f(x) dif x$
]
=== 常见形式
#definition(
"均匀分布",
)[
$ f(x) = cases(
1/(b - a) \, space &b < x < a, 0 \, &"otherwise",
) $
]
#definition(
"指数分布",
)[
$ f(x) = cases(
1/lambda e^(-x/lambda)\, space & x > 0, 0\, & "otherwize",
) $
指数分布具有无记忆性,即 $P{x > t + T | x > t} = P{x > T}$ 。
]
=== 正态分布
#definition(
"正态分布",
)[
计作 $X tilde N(mu, sigma^2)$, $sigma > 0&$
$ f(x) = 1/(sqrt(2 pi) sigma) e^(-(x-mu)^2/(2 sigma^2)) , space x in RR $
]
#properties(
[可加性],
)[若 $X tilde N(mu_1, sigma_1^2),Y tilde N(mu_2, sigma_2^2)$ 则有 $a X + b Y tilde N(a mu_1 + b mu_2, a^2 sigma_1^2 + b^2 sigma_2^2)$]
#annotation[
$integral^(+oo)_(-oo) e^(-x^2/A) dif x = sqrt(A pi) , space A > 0$
]
#proof[
设 $X tilde N(0, A/2)$, 因为概率分布函数具有规范性 $F(+oo) = 1$ 即 $integral_(-oo)^(+oo) f(x) = 1.$ 带入得
$ integral_(-oo)^(+oo) 1/(sqrt(A pi)) e^(-x^2 / A) dif x = 1
\ 1/(sqrt(A pi)) integral_(-oo)^(+oo) e^(-x^2 / A) dif x = 1
\ integral_(-oo)^(+oo) e^(-x^2 / A) dif x = sqrt(A pi) $
]
#definition(
"标准正态分布",
)[
当 $mu = 0, sigma^2 = 1, X tilde N(0, 1),x in RR$时,其为标准正态分布。
$
phi(x) = 1/sqrt(2 pi) -e^(x^2/2) \
Phi(x) = F(x) = integral_(-oo)^(x) phi(t) dif t
$
]
#definition(
"标准化",
)[
若 $X tilde N(mu, sigma^2)$ 不满足标准正态分布,则 $(X - mu)/sigma tilde N(0, 1)$
]
根据标准化,如果我们想要计算一个满足非标准化的正态分布的随机变量在范围 $(a, b]$上的概率,我们可以 $X$ 先将其标准化为 $(X - mu)/sigma$ 并计算 $Phi((b - mu)/sigma) - Phi((a - mu)/sigma)$ 即可。
#definition(
"分位点",
)[
$mu_(alpha)$ 表示 $P{x > mu_(alpha) } = alpha$. 并且有 $mu_(1 - alpha) = mu(-alpha)$.
]
== 随机变量的分布
对于离散型随机变量,我们可以先求出取值,在分别对对应的取值求出概率。而对于连续性随机变量,重点是求其密度函数:即已知 $X tilde f_X (x), Y = g(X)$,求 $R.V. Y$ 的分布函数 $f_Y (y)$。
首先介绍根据分布函数求 $R.V. Y$ 的 密度函数的方法:
#annotation(
"根据分布函数法",
)[\
+ 首先,找到密度函数 $f_Y (y)$ 的分段点,一般有如下两种情况
+ $f_X (x)$ 的分段点,带入 $g(x)$ 后得到的 $y$ 的值,和
+ $y = g(x)$ 的最值
+ 其次,根据以上分段点,求出区间 $(l, r]$ 的 $F_Y (y)$:$ F_Y (y) = P{Y <= y} = P{g(x) <= y} = integral_(l)^r f_X (x) dif x $
+ 最后,对求出的分布函数求导即可得到随机变量 $y$ 的密度函数 $f_Y (y) = F_Y ' (y)$。
]
除此之外,还可以用下方的定理中的公式来进行求解:
#formula(
)[
设 $f_X (x)$ 随机变量 $X$ 的密度函数,对于随机变量 $Y$ 有 $Y = g(X)$,且 $g(X)$ 为单调函数,令 $x = h(y)$ 是 $y = g(x)$ 的反函数,$alpha, beta$ 分别是 $g(x)$ 的最小值和最大值。则 $Y = g(X)$ 的密度函数 $f_Y (y)$ 为: $ f_Y (y) = cases(
f_X ( h(y))abs(h'(y)) &\, quad alpha < y < beta, 0 &\, quad "其他",
) $
]
= 多维随机变量
== 二维随机变量和联合分布函数
#definition(
"二维随机变量",
)[
设随机试验 $E$ 的样本空间 $Omega = {e}$,$X = X(e), Y = Y(e)$ 的定义在 $Omega$ 上的随机变量,则 $(X, Y)$ 为定义在 $Omega$ 上的二维随机变量。
]
#definition(
"联合分布函数",
)[设 $x, y in RR$,则 $x, y$ 的联合分布函数为事件 ${X <= x}$ 与事件 ${Y <= y}$ 同时发生的概率为二维随机变量的联合分布函数 $
F(x, y) = P{(X <= x) sect (Y <= y)} =^"计作" P{X <= x, Y <= y}
$
]
随机变量的分布函数的几何意义为在二维坐标轴中,$F(x, y)$ 为 $X <= x$ 与 $Y <= y$ 所围成的矩形区域的面积。易得,点 $(X, Y)$ 落在 ${(x, y) | x_1 < x <= x_2 , space y_1 < y <= y_2}$ 区域的概率为 $F(x_2, y_2) - F(x_2, y_1) - F(x_1, y_2) + F(x_1, y_1)$ 。
== 连续型随机变量
#definition(
"密度函数",
)[
联合概率密度指的是对于二维随机变量 $(X, Y)$,其概率分布函数为$ F(x, y) = integral_(-oo)^x integral_(-oo)^y f(u, v) dif u dif v $
其中的非负函数 $f(x, y)$ 即为联合概率密度。
]
二维随机变量的联合密度函数有如下性质:
#properties[
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt, [1. 非负性:
$ f(x, y) >= 0 $], [ 2. 规范性:
$ integral_(-oo)^(oo) integral_(-oo)^(oo) f(u, v) dif u dif v = F(oo, oo) = 1 $ ],
)
#table(
columns: 1fr, align: center, stroke: 0pt, [3. 设 $G$ 是平面 $x O y$ 上的闭区域,则点 $(X, Y)$ 落在 $G$ 区域上的概率为
$ F{(X, Y) in G} = limits(integral.double)_G f(x, y) dif x dif y $],
)
]
=== 常见形式
#definition(
"均匀分布",
)[
$ f(u, v) = cases(
1/S_G \, (u, v) in G, 0 \, "其他",
) $
]
// #definition("二维正态分布")[
// #image("./assets/截屏2023-12-29-21.59.19.svg")]
== 边缘分布
#definition(
"分布函数",
)[
设二维随机变量 $(X, Y)$ 的联合分布函数为 $F(X, Y)$,$Omega$ 为完备事件组,则
$F_X (x) = P{X <= x, Omega}, F_Y (y) = P{Omega, Y <= y}$ 分别为 二维随机变量关于 $X$ 或 $Y$ 的边缘分布函数。
]
#definition(
"分布律 / 质量函数",
)[已知 二维随机变量 $(X, Y)$ 的分布律为 $P{X, Y} = P{X = x_i sect Y = y_i}$ 则关于 $X$ 的边缘分布律为
$ P_X (x) = sum^i P(x, y_i) $
]
#definition(
"密度函数",
)[
设 $(X, Y)$ 的密度函数为 $f(x, y)$ 则关于 $X$ 的边缘密度函数和关于 $Y$ 的边缘密度函数为
$ f_X (x) = integral_(-oo)^(+oo) f(x, y) dif y quad quad quad quad quad
f_Y (y) = integral_(-oo)^(+oo) f(x, y) dif x $
]
#pagebreak()
== 条件分布
#definition(
"分布律",
)[
有二维随机变量 $(X, Y)$
$ P{X = x_i | Y = y_j} = (P{X = x_i, Y = y_j})/(P_Y {Y = y_j}) $
即为随机变量 $X$ 在 $Y = y_j$ 下的条件分布律
]
#definition(
"密度函数",
)[
有二维随机变量 $(X, Y)$ 及其联合概率密度$f(x, y)$,固定 $Y = y$,
则随机变量 $X$ 在 $Y = y$ 条件下的概率密度函数为 $ f_(X | Y) = f(x, y)/(f_Y (y))$
]
== 独立性
#definition[
有二维随机变量 $(X, Y)$,$F(x, y) = F_X (x) F_Y (y)$ 满足独立。对于离散型随机变量,
独立性在于是否满足 $P(x, y) = P_X (x) P_Y (y)$。对于连续性随机变量,
在于其密度函数是否满足 $f(x, y) = f_X (x) f_Y (y)$ 。
]
== 二维连续型随机变量的分布
对于离散型随机变量,依旧是先求取值,再求概率,而对于两个连续型随机变量,我们有如下方法:
#formula(
"分布函数法",
)[
有二维随机变量 $(X, Y)$ 及其联合概率分布 $f(x, y)$,
已知 $Z = g(X, Y)$,则 $Z$ 的概率分布为
$ F_Z (z) = P{Z <= z} = P{g(X, Y) <= z} &= P{(X, Y) | g(X, Y) <= z}
\ &= limits(integral.double)_G f(x, y) dif x dif y $
]
或使用卷积公式:
#formula(
"卷积公式",
)[
若随机变量 $X, Z, Y$ 存在 $Z = X + Y$ 关系,则
#table(
columns: (1fr, 1fr), align: center, stroke: 0pt,
[$X, Y$ 不独立], [$X, Y$ 独立],
[$f_Z (z) = integral_(-oo)^(+oo) f(x, z - x) dif x$],
[$f_Z (z) = integral_(-oo)^(+oo) f_X (x) f_Y (z- x) dif x$],
)
]
#proof[
对于 $Z = X + Y$
$ F_Z (z) &= integral_(-oo)^(+oo) dif x integral_(-oo)^(z - x) f(x, y) dif y $
令 $y + x = t$ 将二重积分中对 $y$ 的积分换为对 $t$ 的积分得 $
integral_(-oo)^(+oo) dif x integral_(-oo)^(z) f(x, t - x) dif t
$
改变积分次序后得 $
integral_(-oo)^(z) [integral_(-oo)^(+oo) f(x, t - x) dif x] dif t
$
要求 $Z$ 的密度函数,对变上限积分求导可得
$
f_Z (z) = integral_(-oo)^(+oo) f(x, z - x) dif x
$
若 $(X, Y)$ 独立,又有 $
f_Z (z) = integral_(-oo)^(+oo) f_X (x) f_Y (z- x) dif x
$
]
= 随机变量的数字特征
== 数学期望
#definition(
"离散型",
)[
对于离散型随机变量 $X$,设 $x_i$ 为其分布律的第 $i$ 个取值,相应概率为 $p_i$,
则其数学期望(均值)为:$ E(X) = sum^i x_i p_i $
]
#definition(
"连续型",
)[
若连续型随机变量 $X$ 的密度函数为 $f_X (x)$ 则它的均值为
$ E(X) = integral_(-oo)^(+oo) x f_X (x) dif x $
若要求 $Y = g(X)$ 的均值,则
$ E(g(X)) = integral_(-oo)^(+oo) g(x) f_X (x) dif x $
若 $Z = g(X, Y)$ 且二维随机变量 $(X, Y)$ 有联合概率密度 $f(x, y)$ 则
$ E(Z) = integral_(-oo)^(+oo) integral_(-oo)^(+oo) g(x, y) f(x, y) dif x dif y $
]
#properties[
有常数 $C$,随机变量 $X$ 与 $Y$:
+ $E(C) = C$
+ $E(C + X) = C + E(X)$
+ $E(C X) = C E(X)$
+ $E(X + Y) = E(X) + E(Y)$
+ 若 $X, Y$ 独立,则 $E(X Y) = E(X) E(Y)$
]
== 方差
#definition[
方差为随机变量与其均值的距离的平方的均值即 $D(X) = E[(X - E(X))^2]$,
其用来表示 $X$ 偏离其均值 $E(X)$ 的程度大小。且方差 $D(X) >= 0$。
]
#formula(
"方差计算公式",
)[
$D(X) = E(X^2) - E^2(X)$
]
#properties[ $C$ 为常数
+ $D(C) = 0$
+ $D(X + C) + D(X)$
+ $D(C X) = C^2 D(X)$
+ $D(X + Y) = D(X) + D(Y) - 2[E(X Y) - E(X) E(Y)]$ ]
#pagebreak()
== 常见形式
#theorem(
"0 - 1 分布",
)[
若随机变量 $X$ 服从 $0 - 1$ 分布,则 $ E(X) = p, D(X) = p(1- p) $
]
#theorem(
"二项分布",
)[
若随机变量 $X$ 服从二项分布即 $X tilde B(n, p)$ 则
$ E(X) = n p, D(X) = n p (1 - p) $
]
#proof[
若随机变量 $X tilde B(n, p)$ 则其含义为 $n$ 重伯努利实验中成功的次数即
$X = X_1 + X_2 + ... + X_n$,其中 $X_i$ 表示第 $i$ 次伯努利实验,
每次伯努利实验独立且都有相同的 $p$,即 $E(X_i) = p$,
则 $ E(X)& = E(X_1 + X_2 + ... + X_n) = n p
\ D(X)& = D(X_1 + X_2 + ... + X_n) = n p(1 - p) $
]
#theorem(
"泊松分布",
)[
若随机变量 $X$ 服从参数为 $lambda$ 的泊松分布即 $X tilde P(lambda)$ 则
$ E(X) = D(X) = lambda $
]
#theorem(
"均匀分布",
)[
若 $X tilde U(a, b)$ 则 $ E(X) = (a + b)/2, D(X) = (b - a)^2 / 12 $
]
#theorem(
"指数分布",
)[
若 $X tilde e(lambda)$ 则 $ E(X) = 1/lambda, D(X) = 1/lambda^2 $
]
#theorem(
"正态分布",
)[
若 $X tilde N(mu, sigma^2)$ 则 $ E(X) = mu, D(X) = sigma^2 $
]
== 协方差
#definition(
"协方差",
)[
有二维随机变量 $(X, Y)$,称 $E[(X - E(X)) (Y - E(Y))]$ 为随机变量 $(X, Y)$ 的协方差,
通常计作 $"cov"(X, Y)$ 即 $ "cov"(X, Y) &= E[(X - E(X)) (Y - E(Y))]
\ &= E(X Y) - E(X) E(Y) $
特别的,相同变量的协方差为其方差 $"cov"(X, X) = D(X)$。
]
已知方差的性质 3:$D(X + Y) = D(X) + D(Y) - 2[E(X Y) - E(X) E(Y)]$,
我们将协方差的计算公式带入可得到 $D(X + Y) = D(X) + D(Y) - 2"cov"(X, Y)$。
#properties[
协方差有以下性质
#table(
columns: (1fr, 1fr),
// align: center,
stroke: 0pt, [ 1. $"cov"(X, Y) = "cov"(Y, X)$ ], [
2. $"cov"(a X, b Y) = a b "cov"(X, Y)$
], [], [], [
3. $"cov"(X + Y, Z) = "cov"(X, Z) + "cov"(Y, Z)$
], [
4. 若 $X, Y$ 相互独立,则 $"cov"(X, Y) = 0$
],
)
]
#definition(
"相关系数",
)[
有随机变量 $X, Y$,则其相关系数为:
$ rho_(X Y) = "cov"(X, Y)/(sqrt(D(X)) sqrt(D(Y))) $
]
#properties[
相关系数有以下性质
+ $-1 <= rho_(X Y) <= 1$
+ 相关性 \
+ 若相关系数 $rho_(X Y) = 0$ 则称 $X, Y$ 不相关
+ 若 $rho_(X Y) = 1$,则称 $X, Y$ 为正相关,$y = a x + b, a > 0$
+ 若 $rho_(X Y) = -1$,则称 $X, Y$ 为负相关,$y = a x + b, a < 0$
]
= 大数定律和中心极限定理
== 大数定律
#theorem(
"切比雪夫不等式",
)[
有随机变量 $X$ 及其均值 $E(X)$ 方差 $D(X)$,存在任意正数 $epsilon$ 有
$ P{ | X - E(X) | >= epsilon } <= D(X) / epsilon^2 $
另有 $ P{ | X - E(X) | < epsilon } >= 1- D(X) / epsilon^2 $
]
#theorem(
"切比雪夫大数定律",
)[
设 $X_1, X_2, ..., X_n$ 是相互独立的随机变量序列,且 $E(X_i), D(X_i)$ 均存在,
且 $D(X_i) <= C$,记 $overline(X) = 1/n sum_(i = 1)^n X_i$ 则对于任意正数 $epsilon$,有
$ &lim_(n -> +oo) P{ | overline(X) - E(overline(X)) | < epsilon} = 1
\ <=> & overline(X) "依概率收敛到" E(overline(X)) "即:" overline(X) -->^P E(overline(X)) $
]
#theorem(
"伯努利大数定律",
)[
设 $n_A$ 为 $n$ 次独立重复试验中事件 $A$ 发生的次数,且 $P(A) = p$,则对于任意正数 $epsilon$,有
$
&lim_(n -> +oo) P{ | n_A/n - p | < epsilon} = 1
\
<=> & n_A / n -->^P p
$
]
#theorem(
"辛钦大数定律",
)[
有随机变量序列 $X_1, X_2, ..., X_n$,随机变量间相互独立且服从同一分布,$E(X_i)$ 存在,
则对于任意正数 $epsilon$ 有
$
&lim_(n -> +oo) P{ | overline(X) - E(overline(X)) | < epsilon } = 1
\
<=> & overline(X) -->^P E(overline(X))
$
]
== 中心极限定理
独立随机变量的和的分布当随机变量的个数足够大的时候,近似的服从正态分布。
#theorem(
[独立同分布(列维 --- 林德伯格)中心极限定理],
)[
若一随机变量序列 $X_1, X_2, ... , X_n$ 服从同一分布且具有相同的期望 $E(X_i) = mu$,
相同的方差 $D(X_i) = sigma^2$,将 $sum_(i = 1)^n X_i$ 计作 $eta_n$ 则当 $n$ 充分大的时候,有
$
eta_n "近似服从" &N(E(eta_n), D(eta_n)) \
&= N(n mu, n sigma^2)
$
又由正态分布的标准化可得
$ (sum_(i = 1)^n X_i - n mu)/(sqrt(n) sigma) = (overline(X) - mu)/(sigma / sqrt(n)) "近似服从" N(0, 1) $
]
#theorem(
[棣莫弗 --- 拉普拉斯(De Moivre --- Laplace)定理],
)[
若随机变量 $X_n, n = 1, 2, ...$ 服从参数为 $n, p$ 的二项分布,也即随机变量 $X$
可以分为 $n$ 的相互独立的随机变量 $X_i$ 服从 $0 - 1$ 分布,对于任意的 $x$ 有
$
lim_(n -> +oo) P{(X_n - n p) / sqrt(n p (1 - p)) <= x} = integral_(-oo)^x 1/sqrt(2 pi) e^(t^2/2) dif t = Phi(x).
$
也即:当 $n$ 充分大时,$sum_(i = 1)^n X_i$ 近似服从参数为 $n p$ 与 $n p(1-p)$ 的正态分布,
进而 $(sum_(i = 1)^n X_i - n p) / sqrt(n p (1 - p))$ 近似服从标准正态分布。
]
= 样本与抽样分布
== 基本概念
#definition(
"样本",
)[
设随机变量 $X$ 服从分布 $F$,若随机变量序列 $X_1, X_2, ..., X_n$ 具有同一分布 $F$ 且相互独立,
则称这一随机变量序列为从总体 $F$ 或总体 $X$ 得到的容量为 $n$ 的样本,
$x_1, x_2, ..., x_n$ 为 $X$ 的 $n$ 个独立观测值。
反之,若一随机变量序列是总体 $F$ 的一个样本,则序列中的随机变量同分布为 $F$ 且相互独立。
]
#definition(
"经验分布函数",
)[
有 样本 $x_1, x_2, ..., x_n$,用$S(x),-oo < z< oo$ 表示 $x_1, x_2, ..., x_n$
中不大于 $x$ 的随机变量的个数,定义经验分布函数 $F(z)$ 为
$ F_n(x) = 1/n S(x), quad -oo < x < oo $
]
=== 统计量
#definition(
"统计量与统计量的观测值",
)[
若有一随机变量序列 $X_1, X_2, ..., X_n$ 是总体 $F$ 的一个容量为 $n$ 的样本,
则称不含有位置参数的函数函数 $g(X_1, X_2, ..., X_n)$ 为统计量。
由定义可知,$g(X_1, X_2, ..., X_n)$ 也是一个随机变量,若有 $x_1, x_2, ..., x_n$
是样本的观测值,则 $g(x_1, x_2, ..., x_n)$ 是随机变量 $g(X_1, X_2, ..., X_n)$ 的观测值。
]
有总体 $X, E(X) = mu, D(X) = sigma^2$,下方为常见的统计量:
#definition(
"样本平均值",
)[
$overline(X) = 1/n limits(sum)_(i = 1)^n X_i$ .
根据定义可得 $E(overline(X)) = mu, D(overline(X)) = sigma^2 / n$
]
#definition(
"样本方差",
)[
$S^2 = 1/(n - 1) limits(sum)_(i = 1)^n (X_i - overline(X))^2 = 1/(n - 1) (limits(sum)_(i = 1)^n X_i^2 - n overline(X)^2 )$
根据定义可得,$E(S^2) = D(X) = sigma^2$
]
#definition(
"样本标准差",
)[
$S = sqrt(S^2) = sqrt(
1/(n - 1) limits(sum)_(i = 1)^n (X_i - overline(X))^2
)$
]
#definition(
"样本 k 阶原点矩",
)[
$A_k = 1/n limits(sum)_(i = 1)^n X_i^k ,quad k = 1, 2, 3, ...$
]
#definition(
"样本 k 阶中心矩",
)[
$B_k = 1/n limits(sum)_(i = 1)^n (X_i - overline(X))^k ,quad k = 2, 3, ...$
]
== 抽样分布
抽样分布即为统计量为 $g(X_1, X_2, ..., X_n)$ 的分布,在做题时题目一般会给出提示数据,可以查表求解。
=== $chi^2$ 分布,$t$ 分布和 $F$ 分布
#definition(
[ $chi^2$ 分布 ],
)[
设样本 $X_1, X_2, ..., X_n$ 相互独立,且均服从 $N(0, 1)$ 分布,则有
$X = X_1^2 + X_2^2 + ...+ X_n^2$ 服从自由度为 $n$ 的 $chi^2$ 分布,
即 $X tilde chi^2(n)$。
]
$chi^2$ 分布有如下几条性质:
#properties[
#table(
columns: (1fr, 1fr), stroke: 0pt, align: center, [
1. 可加性
若 $X tilde chi^2(n_1), Y tilde chi^2(n_2)$ 则 $X + Y tilde chi^2(n_1 + n_2)$.
], [ 2. 均值与方差
若 $X tilde chi^2(n)$,则 $E(X) = n, D(X) = 2n$. ],
)
#table(
columns: 1fr, stroke: 0pt, align: center, [ 3. 上 $alpha$ 分位点
在 $chi^2$ 分布的密度图形中,当 $x = x_alpha$ 时,$x > x_alpha$ 的面积为 $alpha$,
称此点为上 $alpha$ 分位点。此时有 $P{X > x_alpha} = alpha$ . ],
)
]
#definition(
[$t$ 分布],
)[
若有 $X tilde N(0, 1), Y tilde chi^2(n)$ 且相互独立,则 $
X / sqrt(Y / n) = t tilde t(n)
$
]
#definition(
[$F$ 分布],
)[
若有 $X_1 tilde chi^2(n_1), X_2 tilde chi^2(n_2)$ 且相互独立,则 $
(X_1\/n_1)/(X_2\/n_2) = F tilde F(n_1, n_2)
$
]
与 $chi^2$ 分布类似的,$t$ 分布及 $F$ 分布都具有上 $alpha$ 分位点。
#definition(
"正态总体的样本均值与样本方差的分布",
)[
设总体 $X tilde N(mu, sigma^2)$,$X_1, X_2, ..., X_n$ 为总体的一个样本,则
#table(
columns: (1fr, 1fr), stroke: 0pt, inset: 10pt,
[ + $overline(X) tilde N(mu, sigma^2/n)$ ],
[ 2. $((n - 1) * S^2)/sigma^2 obey chi^2(n - 1) $ ],
[3. $ overline(X) " 与 " S^2 "独立" $],
[ 4. $(overline(X) - mu)/(S \/ sqrt(n)) tilde t(n - 1) $ ],
)
]<正态总体的样本均值与样本方差的分布>
// #image("./assets/WeChat7464a5889c0f3cadca18c1f801d247c8.jpg")
= 参数估计
== 点估计
#definition[
已知总体 $X$ 的分布,含有未知参数 $theta$,用样本做参数来构造统计量
$hat(theta) thin (X_1, X_2, ..., X_n)$ 来估计 $theta$ 。
]
由一阶矩估计(点估计)推广到 $k$ 阶矩估计,由大数定理可得,当数量足够大时,样本矩趋近于总体矩,
根据矩估计中用样本矩代替总体矩的思想,由总体的分布可以得到总体矩,接着用样本矩代替总体矩,
也即构造未知参数 $theta$ 与样本矩的等价关系。最后解得 $hat(theta)$ 即为矩估计量。
=== 最大似然估计
基本思想是使得样本发生的概率最大的 $hat(theta)$ 即为最大似然估计。
在最大似然估计中,用似然函数去刻画样本出现的概率大小,对于离散型随机变量,
其最大似然函数即为样本间质量函数的积,基本思想是使得样本发生的概率最大的 $hat(theta)$ 即为最大似然估计。
在最大似然估计中,用似然函数去刻画样本出现的概率大小,其形式如下:$
"L"(theta) = &product_(i = 0)^n P{X = X_i} quad &"(离散型随机变量)" \
&product_(i = 0)^(n) f (x_i) quad &"(连续型随机变量)"
$
在求解最大似然估计时,一般通过求导求其导数的驻点来得到 $hat(theta)$,
对于连乘函数形式的似然函数而言,可以先等式两边同时取 *对数* 使连乘变为连加,
再求导求驻点即 $(dif ln "Li"(theta)) /( dif theta) eq.delta 0$ 。
== 评选标准
+ 无偏性,若 $E(hat(theta)) = theta$ 则称 $hat(theta)$ 为无偏估计,
若 $limits(lim)_(n -> oo) E(hat(theta)) = theta$ 则称为渐进无偏估计。
+ 有效性,若对于未知参数 $theta$ 有两个估计量 $hat(theta)_1" 与 " hat(theta)_2$,
两者当中方差较小的估计量更有效。
+ 一致性,若 $n$ 趋于无穷时,估计量以概率趋紧于未知参数,则称估计量与为质量一致,一般的,
若估计量的均值等于未知参数及具有无偏性,估计量的方差趋近于零,即具有有效性,
则满足估计量与未知参数具有一致性。
== 区间估计
#definition(
[置信区间],
)[
对于总体的一个未知参数 $theta$,存在一个 $alpha$,使得
$P{hat(theta)_1 < theta < hat(theta)_2} = 1 - alpha$,
则称 $(hat(theta)_1, hat(theta)_2)$ 为置信区间。
]
在求解置信区间时,通常先构造一个确定分布的含有参数 $theta$ 的样本统计量,也称作枢轴量 $J$,
根据其分布求出 $P{a < J < b} = 1 - alpha$,的左右端点 $a"," b$
(一般是由其分布的函数图像总结而来,用上分位点表示),进而解出 $theta$ 的置信区间。
#show link : set underline(
offset: 3pt, stroke: blue,
)
// #show link : set
在构造枢轴量时,可以根据#link(
<正态总体的样本均值与样本方差的分布>,
)[正态总体的样本均值与样本方差的分布]来进行构造。
#annotation[
当 $sigma^2$ 已知时,求未知参数 $mu$ 的置信区间,构造枢轴量 $
J = (overline(X) - mu) / (sigma / sqrt(n)) tilde N(0, 1)
$
此时,满足 $P{-z_(alpha/2) < J < z_(alpha/2) } = 1 - alpha$ 。
]
#annotation[
当 $sigma^2$ 未知时,求未知参数 $mu$ 的置信区间,构造枢轴量 $
J = (overline(X) - mu)/(S/sqrt(n)) tilde t(n - 1)
$
此时,满足 $P{-t_((alpha/2, n - 1)) < J < t_((alpha/2, n - 1)) } = 1 - alpha$ 。
]
#annotation[
当 $mu$ 未知时,求 $sigma^2$ 的置信区间,构造枢轴量 $
J = ((n - 1) S^2)/sigma^2 tilde chi^2(n - 1)
$
此时,满足 $P{-chi^2_((alpha/2, n - 1)) < J < chi^2_((alpha/2, n - 1)) } = 1 - alpha$ 。
]
= 假设检验
假设检验即对于所要检验的参数 $theta$,首先根据题意设定一个假设值 $H_0 = theta$,
求其所构造枢轴量 $J$ 的满足 $P{theta_1 < J < theta_2} = 1 - alpha$ 的区间
$(theta_1, theta_2)$,其补集 $(-oo, theta_1) union (theta_2, +oo)$ 为*拒绝域*,
将假设值代入所构造的枢轴量,若结果落在拒绝域上,则拒绝假设 $H_0$ 。
// #pagebreak()
// = 附录1:常见的分布类型的期望与方差及证明
// #image("./assets/截屏2024-01-08-22.04.16.svg")
// #image("./assets/截屏2024-01-08-22.05.04.svg")
// #image("./assets/截屏2024-01-08-22.05.38.svg")
// #image("./assets/截屏2024-01-08-22.05.58.svg")
// , |
|
https://github.com/dead-summer/math-notes | https://raw.githubusercontent.com/dead-summer/math-notes/main/notes/ScientificComputing/ch1-intro-to-scicomp/accuracy.typ | typst | #import "/book.typ": book-page
#import "../../../templates/conf.typ": *
#import "@preview/mitex:0.2.4": *
#show: book-page.with(title: "Accuracy")
#show: codly-init.with()
#show: thmrules.with(qed-symbol: $square$)
#codly_init()
= 4 Accuracy
There are two rules to minimize computer round-offs:
- *Rule one*: avoid adding a large number with a small number;
- *Rule two*: avoid subtracting two similar numbers.
They help improve accuracy.
#exm[
Compare
$
f(x) = sqrt(x + 1) - sqrt(x )
$
with
$
g(x) = 1/(sqrt(x + 1) + sqrt(x ))
$
]
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
float x = 1.0;
for (int i = 0; i < 10; i++) {
float f = sqrt(x + 1) − sqrt(x);
float g = 1.0 / (sqrt(x + 1) + sqrt(x));
std::cout << "x = " << x << ", f = " << f << ", g = " << g << std::endl;
x *= 10;
}
return EXIT SUCCESS;
}
```
#exm[
The roots of the quadratic equation
$
f(x) = a x^2 + b x + c = 0
$
are given by
$
x_1 = (-b + sqrt(b^2 - 4a c))/(2a), x_2 = (-b - sqrt(b^2 - 4a c))/(2a).
$
When $b > 0$ , we first compute $ x_2 $ by the expression above and then compute the other root by
$
x_1 = c/(a x_2)
$
Otherwise, we first compute $x_1$ by the expression above and then compute the other root by
$
x_2 = c/(a x_1)
$
]
#exm[
Compute partial sums of the Euler series,
$
s_n = sum_(k=1)^n 1 + 1/4 + 1/9 + dots.c + 1/n^2
$
for large integer $n$ .
]
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[ ])
{
int n = 100;
for (int i = 0; i <= 4; i++) {
float sum = 0.0;
for (int k = 1; k <= n; k++) {
float c = 1.0 / k;
sum += c * c;
}
float error = fabs(sum − M PI * M PI / 6.0);
std::cout << "n = " << n << ", sum = " << sum
<< ", error = " << error << std::endl;
n *= 10;
}
return EXIT SUCCESS;
}
```
One may alternatively compute the series by
$
s_n = sum_(k=0)^(n-1) 1/(n - k)^2 = 1/n^2 + 1/(n-1)^2 + dots.c + 1/9 + 1/4 + 1.
$
```cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[ ])
{
int n = 100;
for (int i = 0; i <= 4; i++) {
float sum = 0.0;
for (int k = n; k >= 1; k−−) {
float c = 1.0 / k;
sum += c * c;
}
float error = fabs(sum − M PI * M PI / 6.0);
std::cout << "n = " << n << ", sum = " << sum
<< ", error = " << error << std::endl;
n *= 10;
}
return EXIT SUCCESS;
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.