repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/1.线性方程组与矩阵.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra #1", authors: ( (name: "<NAME>", email: "<EMAIL>", phone: "3230104585"), ), date: "October 28, 2023", ) #let def(x) = { text("【" + x + "】", weight: "bold") } #let deft(x) = { text("【" + x + "】", weight: "bold", fill: rgb("#FFFFFF")) } #let bb(x) = { text(x, weight: "bold") } = 预备知识 == 数域 设 $PP$ 是一个非空的集合,如果 $PP$ 满足两个条件: 1. $PP$ 中至少含有两个不同的复数 2. $PP$ 中的数对四则运算是封闭的 则称 $PP$ 是一个数域. #note[设 $PP$ 是一个数域,则 $QQ in PP$.(有理数域是最小的数域)] == 排列 对于 $1,2,dots,n$ 共 $n$($n>1$)个数码组成的一个有序数组 $i_1 i_2 dots.c i_n$ 称为一个 #bb[$bold(n)$ 阶排列]. 用 $tau(i_1 i_2 dots.c i_n) = display(sum_(1<=k<j<=n) [i_k>i_j])$ 表示排列的#bb[逆序对数]. #def[性质1]排列中的一对数交换位置称为#bb[对换],对换改变排列的奇偶性. #def[性质2]$n!$ 个 $n$ 阶排列中,奇排列和偶排列各占一半. #prof[ 证明:设奇排列和偶排列分别有 $n!$ 种,有 $p+q=n!$.不妨设 $p$ 个奇排列为: $ cases( a_1 a_2 a_3 dots.c a_n, b_1 b_2 b_3 dots.c b_n, c_1 c_2 c_3 dots.c c_n, dots.c, ) xarrow("选 1,3 位置对换") cases( a_3 a_2 a_1 dots.c a_n, b_3 b_2 b_1 dots.c b_n, c_3 c_2 c_1 dots.c c_n, dots.c, ) $ 可以得到 $p$ 个不同的偶排列,故 $q>=p$.同理可得 $p>=q$.故有 $p=q$. ] = 线性方程组 #def[性质]线性方程组要么无解,要么有唯一解,要么有无穷多解. == 阶梯型线性方程组 $ cases( b_(1 j_1) x_(j_1) + dots.c +& b_(1 j_2) x_(j_2) + &dots.c + &b_(1 j_r) x_(j_r) + dots.c + &b_(1 n) x_(n) &= c_1, & b_(2 j_2) x_(j_2) + &dots.c + &b_(2 j_r) x_(j_r) + dots.c + &b_(2 n) x_(n) &= c_2, &&dots.down &&&dots.c, &&& b_(r j_r) x_(j_r) + dots.c + &b_(r n) x_(n) &= c_r, &&&& 0 &= c_(r+1), ) $ “$0 = c_(r+1)$” 下留空部分表示还有 $m-(r+1)$ 个 $0=0$ 的方程.称阶梯处转弯的项 $b_(i j_i) x_(j_i)$ 为#bb[阶梯头]. 关于约化阶梯型线性方程组的定义、线性方程组的初等变换可参考矩阵部分. == 线性方程组解的判定 先化为阶梯型线性方程组再进行判定.当线性方程组有解时(即 $c_(r+1)=0$ 时): - 若 $r=n$,则线性方程组有唯一解. - 若 $r<n$,则线性方程组有无穷多(组)解,且有 $n-r$ 个#bb[自由变量(自由未知量)]. #note[记线性方程组的系数矩阵为 $bold(A)$,系数矩阵的增广矩阵为 $overline(bold(A))$.实际上吗,我们有 $r=r(bold(A))=r(overline(bold(A)))$.] == 齐次线性方程组 对于所有常数项全部为 $0$(即 $forall 1<=i<=m,sp c_i=0$)的线性方程组,称为齐次线性方程组. #def[性质1]齐次线性方程组一定有解. #def[性质2]如果齐次线性方程组存在一组非零解,那么该齐次线性方程组有无穷多解. = 矩阵 == 矩阵的初等变换 分为初等行变换和初等列变换. 1. #bb[互换]:交换矩阵的两行(列);$xarrow(R_(i j))$($xarrow(C_(i j))$) 2. #bb[倍乘]:把某行(列)乘以非零的 $c$ 倍;$xarrow(c R_(i))$($xarrow(c C_(i))$) 3. #bb[倍加]:把某行(列)的 $c$ 倍加到另一行(列)上.$xarrow(R_i + c R_j)$($xarrow(C_i + c C_j)$) #note[对线性方程组做初等变换等价与对其系数矩阵(的增广矩阵)做初等#bb[行]变换.] == 阶梯型矩阵 $ overline(bold(A)) xarrow("初等行变换") mat( b_(1 j_1),dots.c,b_(1 j_2),dots.c,b_(1 j_3),dots.c,b_(1 j_r),dots.c,b_(1 n),c_1; " ",,b_(2 j_2),dots.c,b_(2 j_3),dots.c,b_(2 j_r),dots.c,b_(2 n),c_2; " ",,,,b_(3 j_3),dots.c,b_(3 j_r),dots.c,b_(3 n),c_3; " ",,,,,dots.down,dots.v,,dots.v,dots.v; " ",,,,,,b_(r j_r),dots.c,b_(r n),c_r; " ",,,,,,,,,c_(r+1); ) $ #note[阶梯型矩阵的每个阶梯头的左下方都是 $0$.] == 约化阶梯型矩阵 在阶梯型矩阵的基础上,要求: 1. 阶梯头元素为 $1$; 2. 阶梯头所在列其余元素为 $0$. #warn[ 注意到根据定义,$display(mat( 1,bold(2),0,0; 0,bold(0),1,0; 0,bold(0),0,1; ))$ 也是约化阶梯型矩阵. ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/gallery/test4.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "../src/lib.typ": * #set page(width: auto, height: auto, margin: .5cm) #circuit({ element.group(id: "toplvl", name: "Toplevel", { element.group( id: "proc", name: "Processor", padding: 1.5em, stroke: (dash: "dashed"), { element.block( x: 0, y: 0, w: 8, h: 4, id: "dp", fill: util.colors.pink, name: "Datapath", ports: ( north: ( (id: "clk", clock: true, small: true), (id: "Zero"), (id: "Regsrc"), (id: "PCSrc"), (id: "ResultSrc"), (id: "ALUControl"), (id: "ImmSrc"), (id: "RegWrite"), (id: "dummy") ), east: ( (id: "PC", name: "PC"), (id: "Instr", name: "Instr"), (id: "ALUResult", name: "ALUResult"), (id: "dummy"), (id: "WriteData", name: "WriteData"), (id: "ReadData", name: "ReadData"), ), west: ( (id: "rst"), ) ), ports-margins: ( north: (0%, 0%), west: (0%, 70%) ) ) element.block( x: 0, y: 7, w: 8, h: 3, id: "ctrl", fill: util.colors.orange, name: "Controller", ports: ( east: ( (id: "Instr", name: "Instr"), ), south: ( (id: "dummy"), (id: "Zero"), (id: "Regsrc"), (id: "PCSrc"), (id: "ResultSrc"), (id: "ALUControl"), (id: "ImmSrc"), (id: "RegWrite"), (id: "MemWrite") ) ), ports-margins: ( south: (0%, 0%) ) ) wire.wire( "w-Zero", ("dp-port-Zero", "ctrl-port-Zero"), name: "Zero", name-pos: "start", directed: true ) for p in ("Regsrc", "PCSrc", "ResultSrc", "ALUControl", "ImmSrc", "RegWrite") { wire.wire( "w-" + p, ("ctrl-port-"+p, "dp-port-"+p), name: p, name-pos: "start", directed: true ) } draw.content( (rel: (0, 1em), to: "ctrl.north"), [*RISCV single*], anchor: "south" ) }) element.block( x: (rel: 3.5, to: "dp.east"), y: (from: "dp-port-ReadData", to: "RD"), w: 3, h: 4, id: "dmem", fill: util.colors.green, name: "Data\n Memory", ports: ( north: ( (id: "clk", clock: true, small: true), (id: "WE", name: "WE") ), west: ( (id: "dummy"), (id: "dummy"), (id: "A", name: "A"), (id: "dummy"), (id: "WD", name: "WD"), (id: "RD", name: "RD"), ) ), ports-margins: ( north: (0%, 10%) ) ) wire.wire( "w-DataAddr", ("dp-port-ALUResult", "dmem-port-A"), name: "DataAddr", name-pos: "end", directed: true ) wire.wire( "w-WriteData", ("dp-port-WriteData", "dmem-port-WD"), name: "WriteData", name-pos: "end", directed: true ) wire.wire( "w-ReadData", ("dmem-port-RD", "dp-port-ReadData"), name: "ReadData", name-pos: "end", reverse: true, directed: true ) wire.wire( "w-MemWrite", ("ctrl-port-MemWrite", "dmem-port-WE"), style: "zigzag", name: "MemWrite", name-pos: "start", zigzag-dir: "horizontal", zigzag-ratio: 80%, directed: true ) wire.stub( "dmem-port-clk", "north", name: "clk", length: 3pt ) element.block( x: (rel: 3.5, to: "dp.east"), y: (from: "ctrl-port-Instr", to: "dummy"), w: 3, h: 4, id: "imem", fill: util.colors.green, name: "Instruction\n Memory", ports: ( west: ( (id: "A", name: "A"), (id: "dummy"), (id: "dummy2"), (id: "RD", name: "RD"), ) ) ) wire.wire( "w-PC", ("dp-port-PC", "imem-port-A"), style: "zigzag", directed: true ) wire.wire( "w-Instr1", ("imem-port-RD", "dp-port-Instr"), style: "zigzag", zigzag-ratio: 30%, directed: true ) wire.wire( "w-Instr2", ("imem-port-RD", "ctrl-port-Instr"), style: "zigzag", zigzag-ratio: 30%, directed: true ) wire.intersection("w-Instr1.zig", radius: 2pt) draw.content("w-Instr1.zig", "Instr", anchor: "south", padding: 4pt) draw.content("w-PC.zig", "PC", anchor: "south-east", padding: 2pt) draw.content("dmem.south-west", [*External Memories*], anchor: "north", padding: 10pt) }) draw.line(name: "w-dp-clk", "dp-port-clk", (rel: (0, .5), to: ()), ( rel: (-.5, 0), to: (horizontal: "toplvl.west", vertical: ()) ) ) draw.content("w-dp-clk.end", "clk", anchor: "east", padding: 3pt) draw.line(name: "w-dp-rst", "dp-port-rst", ( rel: (-.5, 0), to: (horizontal: "toplvl.west", vertical: ()) ) ) draw.content("w-dp-rst.end", "rst", anchor: "east", padding: 3pt) })
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/cvpr/cvpr2025.typ
typst
MIT License
/** * cvpr2025.typ * * CVPR 2025 template. */ #import "/cvpr2022.typ": cvpr2022 #let conf-year = [2025] /** * cvpr2025 - Template for Computer Vision and Pattern Recognition Conference * (CVPR) 2025. * * Args: * title: Paper title. * authors: Tuple of author objects and affilation dictionary. * keywords: Publication keywords (used in PDF metadata). * date: Creation date (used in PDF metadata). * abstract: Paper abstract. * bibliography: Bibliography content. If it is not specified then there is * not reference section. * appendix: Content to append after bibliography section. * accepted: Valid values are `none`, `false`, and `true`. Missing value * (`none`) is designed to prepare arxiv publication. Default is `false`. * id: Submission identifier. */ #let cvpr2025( title: [], authors: (), keywords: (), date: auto, abstract: [], bibliography: none, appendix: none, accepted: false, id: none, body, ) = { show: cvpr2022.with( title: title, authors: authors, keywords: keywords, date: date, abstract: abstract, bibliography: bibliography, appendix: appendix, accepted: accepted, id: id, aux: (conf-year: [2025]), ) body }
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-utils/lib/lib.typ
typst
MIT License
#import "components.typ" #import "assignments.typ" #import "grading.typ" #import "helpers.typ" #import "layout.typ" #import "random.typ"
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1F680.typ
typst
Apache License 2.0
#let data = ( ("ROCKET", "So", 0), ("HELICOPTER", "So", 0), ("STEAM LOCOMOTIVE", "So", 0), ("RAILWAY CAR", "So", 0), ("HIGH-SPEED TRAIN", "So", 0), ("HIGH-SPEED TRAIN WITH BULLET NOSE", "So", 0), ("TRAIN", "So", 0), ("METRO", "So", 0), ("LIGHT RAIL", "So", 0), ("STATION", "So", 0), ("TRAM", "So", 0), ("TRAM CAR", "So", 0), ("BUS", "So", 0), ("ONCOMING BUS", "So", 0), ("TROLLEYBUS", "So", 0), ("BUS STOP", "So", 0), ("MINIBUS", "So", 0), ("AMBULANCE", "So", 0), ("FIRE ENGINE", "So", 0), ("POLICE CAR", "So", 0), ("ONCOMING POLICE CAR", "So", 0), ("TAXI", "So", 0), ("ONCOMING TAXI", "So", 0), ("AUTOMOBILE", "So", 0), ("ONCOMING AUTOMOBILE", "So", 0), ("RECREATIONAL VEHICLE", "So", 0), ("DELIVERY TRUCK", "So", 0), ("ARTICULATED LORRY", "So", 0), ("TRACTOR", "So", 0), ("MONORAIL", "So", 0), ("MOUNTAIN RAILWAY", "So", 0), ("SUSPENSION RAILWAY", "So", 0), ("MOUNTAIN CABLEWAY", "So", 0), ("AERIAL TRAMWAY", "So", 0), ("SHIP", "So", 0), ("ROWBOAT", "So", 0), ("SPEEDBOAT", "So", 0), ("HORIZONTAL TRAFFIC LIGHT", "So", 0), ("VERTICAL TRAFFIC LIGHT", "So", 0), ("CONSTRUCTION SIGN", "So", 0), ("POLICE CARS REVOLVING LIGHT", "So", 0), ("TRIANGULAR FLAG ON POST", "So", 0), ("DOOR", "So", 0), ("NO ENTRY SIGN", "So", 0), ("SMOKING SYMBOL", "So", 0), ("NO SMOKING SYMBOL", "So", 0), ("PUT LITTER IN ITS PLACE SYMBOL", "So", 0), ("DO NOT LITTER SYMBOL", "So", 0), ("POTABLE WATER SYMBOL", "So", 0), ("NON-POTABLE WATER SYMBOL", "So", 0), ("BICYCLE", "So", 0), ("NO BICYCLES", "So", 0), ("BICYCLIST", "So", 0), ("MOUNTAIN BICYCLIST", "So", 0), ("PEDESTRIAN", "So", 0), ("NO PEDESTRIANS", "So", 0), ("CHILDREN CROSSING", "So", 0), ("MENS SYMBOL", "So", 0), ("WOMENS SYMBOL", "So", 0), ("RESTROOM", "So", 0), ("BABY SYMBOL", "So", 0), ("TOILET", "So", 0), ("WATER CLOSET", "So", 0), ("SHOWER", "So", 0), ("BATH", "So", 0), ("BATHTUB", "So", 0), ("PASSPORT CONTROL", "So", 0), ("CUSTOMS", "So", 0), ("BAGGAGE CLAIM", "So", 0), ("LEFT LUGGAGE", "So", 0), ("TRIANGLE WITH ROUNDED CORNERS", "So", 0), ("PROHIBITED SIGN", "So", 0), ("CIRCLED INFORMATION SOURCE", "So", 0), ("BOYS SYMBOL", "So", 0), ("GIRLS SYMBOL", "So", 0), ("COUCH AND LAMP", "So", 0), ("SLEEPING ACCOMMODATION", "So", 0), ("SHOPPING BAGS", "So", 0), ("BELLHOP BELL", "So", 0), ("BED", "So", 0), ("PLACE OF WORSHIP", "So", 0), ("OCTAGONAL SIGN", "So", 0), ("SHOPPING TROLLEY", "So", 0), ("STUPA", "So", 0), ("PAGODA", "So", 0), ("HINDU TEMPLE", "So", 0), ("HUT", "So", 0), ("ELEVATOR", "So", 0), (), (), (), (), ("WIRELESS", "So", 0), ("PLAYGROUND SLIDE", "So", 0), ("WHEEL", "So", 0), ("RING BUOY", "So", 0), ("HAMMER AND WRENCH", "So", 0), ("SHIELD", "So", 0), ("OIL DRUM", "So", 0), ("MOTORWAY", "So", 0), ("RAILWAY TRACK", "So", 0), ("MOTOR BOAT", "So", 0), ("UP-POINTING MILITARY AIRPLANE", "So", 0), ("UP-POINTING AIRPLANE", "So", 0), ("UP-POINTING SMALL AIRPLANE", "So", 0), ("SMALL AIRPLANE", "So", 0), ("NORTHEAST-POINTING AIRPLANE", "So", 0), ("AIRPLANE DEPARTURE", "So", 0), ("AIRPLANE ARRIVING", "So", 0), (), (), (), ("SATELLITE", "So", 0), ("ONCOMING FIRE ENGINE", "So", 0), ("DIESEL LOCOMOTIVE", "So", 0), ("PASSENGER SHIP", "So", 0), ("SCOOTER", "So", 0), ("MOTOR SCOOTER", "So", 0), ("CANOE", "So", 0), ("SLED", "So", 0), ("FLYING SAUCER", "So", 0), ("SKATEBOARD", "So", 0), ("AUTO RICKSHAW", "So", 0), ("PICKUP TRUCK", "So", 0), ("ROLLER SKATE", "So", 0), )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-circle-00.typ
typst
Other
// Default circle. #box(circle()) #box(circle[Hey])
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/packages/boxes.md
markdown
MIT License
# Custom boxes ## Showbox ```typ #import "@preview/showybox:2.0.1": showybox #showybox( [Hello world!] ) ``` ```typ #import "@preview/showybox:2.0.1": showybox // First showybox #showybox( frame: ( border-color: red.darken(50%), title-color: red.lighten(60%), body-color: red.lighten(80%) ), 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( frame: ( dash: "dashed", border-color: red.darken(40%) ), body-style: ( align: center ), sep: ( dash: "dashed" ), shadow: ( offset: (x: 2pt, y: 3pt), color: yellow.lighten(70%) ), [This is an important message!], [Be careful outside. There are dangerous bananas!] ) ``` ```typ #import "@preview/showybox:2.0.1": showybox #showybox( title: "Stokes' theorem", frame: ( border-color: blue, title-color: blue.lighten(30%), body-color: blue.lighten(95%), footer-color: blue.lighten(80%) ), footer: "Information extracted from a well-known public encyclopedia" )[ Let $Sigma$ be a smooth oriented surface in $RR^3$ with boundary $diff Sigma equiv Gamma$. If a vector field $bold(F)(x,y,z)=(F_x (x,y,z), F_y (x,y,z), F_z (x,y,z))$ is defined and has continuous first order partial derivatives in a region containing $Sigma$, then $ integral.double_Sigma (bold(nabla) times bold(F)) dot bold(Sigma) = integral.cont_(diff Sigma) bold(F) dot dif bold(Gamma) $ ] ``` ```typ #import "@preview/showybox:2.0.1": showybox #showybox( title-style: ( weight: 900, color: red.darken(40%), sep-thickness: 0pt, align: center ), frame: ( title-color: red.lighten(80%), border-color: red.darken(40%), thickness: (left: 1pt), radius: 0pt ), title: "Carnot cycle's efficiency" )[ Inside a Carnot cycle, the efficiency $eta$ is defined to be: $ eta = W/Q_H = frac(Q_H + Q_C, Q_H) = 1 - T_C/T_H $ ] ``` ```typ #import "@preview/showybox:2.0.1": showybox #showybox( footer-style: ( sep-thickness: 0pt, align: right, color: black ), title: "Divergence theorem", footer: [ In the case of $n=3$, $V$ represents a volume 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 $ ] ``` ```typ #import "@preview/showybox:2.0.1": showybox #showybox( frame: ( border-color: red.darken(30%), title-color: red.darken(30%), radius: 0pt, thickness: 2pt, body-inset: 2em, dash: "densely-dash-dotted" ), title: "Gauss's Law" )[ The net electric flux through any hypothetical closed surface is equal to $1/epsilon_0$ times the net electric charge enclosed within that closed surface. The closed surface is also referred to as Gaussian surface. In its integral form: $ Phi_E = integral.surf_S bold(E) dot dif bold(A) = Q/epsilon_0 $ ] ``` ## Colorful boxes ```typ #import "@preview/colorful-boxes:1.2.0": colorbox, slantedColorbox, outlinebox, stickybox #colorbox( title: lorem(5), color: "blue", radius: 2pt, width: auto )[ #lorem(50) ] #slantedColorbox( title: lorem(5), color: "red", radius: 0pt, width: auto )[ #lorem(50) ] #outlinebox( title: lorem(5), color: none, width: auto, radius: 2pt, centering: false )[ #lorem(50) ] #outlinebox( title: lorem(5), color: "green", width: auto, radius: 2pt, centering: true )[ #lorem(50) ] #stickybox( rotation: 3deg, width: 7cm )[ #lorem(20) ] ``` ## Theorems See [math](./math.md)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/numbering-05.typ
typst
Other
// Error: 17-19 number must be at least zero #numbering("1", -1)
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045%20-%20Kamigawa%3A%20Neon%20Dynasty/002_Episode%201%3A%20A%20Stranger%20in%20Eiganjo.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: A Stranger in Eiganjo", set_name: "Kamigawa: Neon Dynasty", story_date: datetime(day: 24, month: 01, year: 2022), author: "<NAME>", doc ) Of all the rooms in the Imperial Palace, the kitchen was Kaito's favorite. The fragrant smell of ramen broth, pork dumplings, and katsu curry wafted through the corridor and out the side window where Kaito was perched. He inhaled like he was in a haze and slipped off the ledge and into the storeroom, keeping his footsteps as soundless as possible. Just like Light-Paws taught him. Not that the emperor's advisor would approve of Kaito's extracurricular activities. #figure(image("002_Episode 1: A Stranger in Eiganjo/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Dishes were stacked on the nearby counter; the basin beside it was filled with soapy water, bubbles rising dangerously close to the edge. Kaito was nearly to the door when a small kami poked its head out of the water, blinking like it had just been woken from a nap. Four miniature teacups floated around its salamander-shaped body, its face framed by a collection of painted horns that resembled broken shards of porcelain. Kaito paused, bracing for a lecture, when the Kami of Imperial Dishware snatched up another dirty plate and sunk below the water, uninterested in whatever Kaito was up to. The corner of his mouth tugged with humor, and he darted around the corner toward the wide-open kitchen. The palace cooks were distracted with their preparations. Between the clattering pans, boiling broth, and #emph[thwacking] sounds of a butcher's knife against a chopping board, it didn't matter that Kaito was soundless—he might as well be invisible. His eyes trailed hungrily over the center table, where round pieces of blue mochi sat in uniform rows, each decorated with a smiling face and small, yellow eyes shaped like crescent moons. Kaito raised a hand, fingers dancing lightly like he was gathering his courage. Two pieces of mochi floated up in the air, hovering inches above the table. Kaito pulled the sweets closer with his mind, concentrating as they drifted toward him. He reached out, holding his breath, and snatched them out of the air—just as one of the cooks spotted him from behind a pot of glass noodles. "Hey!" The cook's face was already red from the steam, but now it was turning a shade of purple. "What did I tell you about stealing?" Kaito tore back down the corridor, stumbling over his footing. He could hear someone running after him, but he wasn't about to waste time looking over his shoulder. He turned back for the storeroom, elbow catching the edge of a dirty pan, and sent a stack of plates toppling over the counter. With the mochi still clutched against his chest, Kaito threw out his free hand to hold the dishes mid-air. They hovered in place, but the footsteps in the hall were close. Too close. Kaito had no choice. He released the dishes and leapt for the window just as the explosion of porcelain echoed behind him. The kami burst from the soapy water, shrieking at the mess and the startled cook standing beside the broken dishes. With a smirk, Kaito shoved one piece of mochi in his mouth and the other in his pocket, jumped from the windowsill, and made his way back over the surrounding wall. Like most buildings in Eiganjo, the Imperial Palace had low, curved roofs and terraced spaces. Moss and sand gardens were featured in abundance, some of them trailing up the sides of the palace, with trees protruding from the displays. Even with the palace guarded by loyal samurai and towering Imperial surveillance mechs, Kaito roamed freely between his lessons. Most Imperials didn't pay him any attention at all. They were more preoccupied with maintaining positive kami relations, regulating tech, and monitoring how closely the Futurists were following the rules. #emph[Balance] , Light-Paws often called it. Kaito didn't care about balance; he was just glad nobody seemed to bother watching the rooftops. Scaling the edge of the nearest apartment, Kaito followed a makeshift trail over the houses and back to the sparring room's rock garden. The sliding doors were wide open. As far as he could tell, Light-Paws wasn't even there yet. Kaito hurried across the sand, passing a spiral of shattered stones half-sunken in the ground. They hummed faintly with energy; an ancient relic from the past. The moment Kaito stepped through the sliding doors, he knew he was not alone. "You're late," Eiko's sharp voice rang out from the shadows. "And your face is covered in rice flour." Kaito spun toward his sister. Even though they were the same age, Eiko had always seemed older. Maybe because after their parents died, she felt like it was her responsibility to look after her brother. Kaito looked after Eiko, too, but he would never chastise her for having fun. Not that Eiko did much of that anymore. He dragged a sleeve across his mouth. "Don't be mad." He dug the other piece of mochi out of his pocket and held it out to her. "I brought you a gift." Eiko frowned, but the hint of a smile flashed in her eyes. With a sigh, she took the mochi and popped it in her mouth, dusting her fingers against her shirt. "You need to start taking your training more seriously. It's been five years—most Imperials would've chosen a specialty by now." Kaito shrugged, still grinning. It usually kept Eiko from being #emph[too ] angry with him. "We're the exception, not the rule. Maybe if we stick with general training long enough, we'll never have to be separated. We can stay just like this forever." Eiko flattened her mouth, cheeks blossoming with color. "Kaito, I—" Light-Paws entered the room, and whatever Eiko was going to say seemed to halt at the edge of her lips. Dressed in her decorative kimono, Light-Paws strode across the room with the balance and nobility of someone who wasn't just raised an Imperial—they were the very#emph[ example] of one. Seven white tails flicked behind her. A sign of the kitsune's age and wisdom. Kaito and Eiko both bowed respectfully. Light-Paws was their teacher, but she was also the closest thing they had to a guardian. #figure(image("002_Episode 1: A Stranger in Eiganjo/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Even if Kaito didn't love the rules of the palace, it never stopped him from craving Light-Paws's approval. He just wished it came as naturally to him as it did to Eiko. Imperial life suited his sister. But for Kaito, there were too many walls. Light-Paws folded her arms behind her and looked straight at Kaito. "You and Eiko will no longer be sparring partners." Kaito's brows pinched. "We aren't training anymore?" He glanced at his sister, but she only bit the edge of her lip. "You will train," Light-Paws corrected. "But not together. Eiko has chosen to study as a kami diplomat. I have arranged her schedule to coincide with her fellow Imperial students." Kaito felt the plane tilt. He turned to his sister. "Why didn't you tell me?" Eiko's shoulders sank. "I tried to. Many times. But you never want to talk about our future, and I couldn't delay my training any longer. We won't be children forever, Kaito." "Delay?" he repeated. "What's that supposed to mean?" She flattened her mouth. "The reason I took so long to choose a specialty was because I was hoping you'd pick one first. I thought—I thought it might make things easier." Kaito flinched, wounded. He may not have wanted things to change, but he also never wanted to hold his sister back. How long had she been keeping such a secret? "I'm sorry," Eiko said, pressing a hand to her brother's shoulder. "But it's time. For both of us. And maybe now you'll be able to choose your focus, too, without worrying about me." Light-Paws observed them both without speaking, so still even her tails had stopped swaying. Kaito blinked, fighting the sting in his eyes. "It's fine. I'm happy for you." It was what a good brother would say. And he wanted to be a good brother, even if he didn't make a good Imperial. Eiko nodded, letting her hand drop. Things would be different now. She'd study in the libraries and council rooms and take trips to the bustling metropolitan center of Towashi, and perhaps even to the outskirts of the Jukai Forest to mend kami relations. There wasn't much of the forest left—most of it had been cut down to make space for the city. Now the kami guarded it fiercely, and only the most skilled in kami diplomacy had any chance at quelling hostilities. It would be the perfect job for Eiko, one day. All the while, Kaito would be stuck here. In the palace. Without any plan for his future. Light-Paws took a careful step forward, raising her chin slightly even as she peered down at Kaito. "Swift-Arm is waiting for you in the sakura garden. He will introduce you to your new sparring partner." Kaito swallowed the knot in his throat, but he couldn't shake his surprise. Swift-Arm ran the elite Golden-Tail Academy for Imperial samurai. What would make him ever agree to train Kaito? And #emph[why] ? "I'll go at once," Kaito said with an even voice, and left the room, eager for a distraction. The sakura gardens were deep in the heart of the Imperial Palace. There was a shortcut over the wall, but Kaito took the long route through the buildings and up the stone stairs. He was close to the emperor's chambers and Kyodai's temple; he had to at least #emph[appear] to be on his best behavior. Kaito had only ever spoken to the emperor behind a screen door. The first time was by accident—he'd climbed over the wrong wall trying to get away from a Kami of Spring Blossoms, who did not take kindly to Kaito accidentally trampling a flower bed, and ended up in a private garden surrounded by hydrangea and koi ponds. An extravagant porch led to a paper screen door, where warm light glowed behind it. Someone was sitting at the edge of the room, but all Kaito could see was their shadow. He'd tried to sneak away but only made it two steps when a voice called out to him and asked what he was doing. Kaito hadn't known it was the emperor. All he heard was the voice of a girl his own age. Someone more likely to be his friend than someone who'd report back to Light-Paws about the mischief he was up to. So Kaito told her the truth. How he'd snuck into the restricted section of the library on a dare and was halfway toward grabbing one of the books when someone spotted him. How he'd never run so fast in his life trying to get away and had to climb across three different roofs, five walls, and scale a building just to get to safety. The girl had smiled behind the screen. He could hear it in her voice when she told him she'd never heard anything so silly in all her life. They talked for nearly an hour before Kaito realized he was late for a lesson. And when he asked what the girl's name was, she didn't tell him. It was forbidden for the emperor to reveal her name, even to those closest to her. But she told him he was welcome to come back and see her the next time he needed somewhere to hide. As Kaito was leaving, he climbed back up the wall and looked around at the building—so he'd know where to return—when he realized he was standing in the emperor's garden. A good Imperial would've known better than to return. A good subject would've known speaking so casually to the Emperor of Kamigawa was improper. And a good student wouldn't let a distraction get in the way of their studies. But Kaito wasn't good at anything but following his own heart. The next time he went to visit the emperor behind the screen, he didn't make a big deal about knowing who she really was, aside from calling her "Your Emperorness" when he felt he needed #emph[something ] to call her. He just talked to her like a friend, day after day. And eventually, that's what they became. Kaito reached the gates of the sakura garden and curled his fingers into fists. He'd tell the emperor about Eiko's choice the next time he spoke with her. But when she inevitably followed up by asking how Kaito felt about it, what would he say? Light-Paws was grooming them for service to the emperor. It was their duty to elevate their training. How could he possibly tell the Emperor of Kamigawa that he was #emph[unhappy] about it? Becoming a samurai made the most sense for Kaito. He was strong and fast for his age, and he had telekinesis—he could be an asset to the Imperials with the right training. Maybe this was Light-Paws's plan. To put Kaito in a position where if Swift-Arm recruited him directly, he wouldn't be able to say no. Swift-Arm was waiting on the grass, his Imperial armor assembled strategically around his kitsune shape. The metal flickered against the sunlight, made up of varying shades of gold, bronze, and russet, with an extravagant fan spread against his back. Beneath his matching helmet, Swift-Arm gave a curt nod. "Light-Paws tells me you are an excellent swordsman." Kaito grimaced. This was it. He was going to be pulled deeper into Imperial life, with no way of ever getting out. He'd be a samurai until he died. "Er—yes, sir." Swift-Arm grunted. "I don't believe Light-Paws to be a liar, but neither have a I ever met an #emph[excellent ] swordsman who hesitates." His whiskers bristled. "Want to try that again?" Kaito straightened. "I can fight well, sir. I've been training with my sister for many years." "Good." Swift-Arm turned to his side, stern eyes fixed beyond the sakura trees. "We're in need of a new sparring partner. Someone adept in skill who won't fall behind on their studies. And since you haven't moved on from general training~" Kaito heard the distaste in his voice. The implication that Kaito was lazy and not at all samurai material. He hid his delight. Maybe there was still hope. Swift-Arm was too busy watching something behind the trees. "You will remember to be respectful at all times, but you will also treat these lessons just as any other, understood?" Kaito nodded, and a nearby door slid open. Footsteps sounded down the path. Swift-Arm bowed low. Preparing to do the same, Kaito pressed his feet together but stopped short when a girl appeared around the corner. A girl with snow-white hair, brown eyes, and an expression too serious to belong to someone so young. "Thank you for your service." Her voice was practiced and formal, but Kaito recognized the familiarity in it, too. The Emperor of Kamigawa. Kaito's eyes widened. He'd never seen her face before—only her shadow. But the shadow he knew was full of warmth, and heart, and dreams of what the plane could one day be. She was more than a shadow. She was someone Kaito cared about. He remembered to bow. "Thank you for the opportunity, Your Emperorness—er, #emph[Highness] ." #figure(image("002_Episode 1: A Stranger in Eiganjo/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) She didn't react to the clumsy nickname he'd been using for years, but Swift-Arm's nose twitched disapprovingly. He picked up one of the wooden practice swords from its stand. With two hands, he held it out to the emperor and dipped his head. When he retrieved the second, he tossed it to Kaito from several feet away. Kaito was quick—his hand snapped into the air, catching the sword by the handle before it hit him in the chest. Swift-Arm eyed him but said nothing. Taking up their positions on the grass, Kaito and the emperor raised their swords, preparing to spar. Kaito knew he should be watching her every movement, but he couldn't look away from her eyes. Did she recognize him? Did she recognize his voice? Did she think of him as a friend, or had Kaito only imagined it in his head? Swift-Arm gave the order to begin, and Kaito swung his sword. The emperor blocked—her fighting style was like water, fluid and powerful. They moved in circles around the makeshift sparring ring, swords clacking together with precision, neither of them breaking a sweat. Kaito took a step back, sword raised in defense, when he caught Swift-Arm's glare. #emph[Treat these lessons just as any other.] Clenching his teeth, Kaito nodded. He understood what was expected of him. And he hoped the emperor would forgive him. He swung his sword hard, pushing the emperor back toward the edge of the ring. He was relentless, attacking in sharp, quick bursts of fury—the opposite of her calm energy. If she was a breathless lake, he was a tsunami. Kaito would wear her out in moments. He was sure of it. The emperor blocked, again and again, and then spun away from him like floating silk, so graceful that the force of her next blow caught him off guard. His sword strained beneath hers, and she held firm. And then in one swift movement, she rolled her body and cracked the edge of her sword against Kaito's handle. He felt it rattle in his palm, but it was too late. She spun again, kicking Kaito in the stomach as she took possession of his sword with her free hand and held both wooden blades to his neck before he even had time to steady himself. Kaito looked up at the emperor—at the way the sunlight exploded behind her, silhouetting her slender frame like she was once again a shadow behind a screen—and watched a smile appear at the edge of her lips. A smile of recognition. Swift-Arm was still watching, so Kaito tried not to smile back. But inside, he was glowing. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Over the years, Kaito and the emperor continued to train together. And when they weren't training, Kaito found ways to meet her in the garden, where they could speak through the porch screen. Without Swift-Arm's watchful eye, they were just two childhood friends sharing their secrets. Kaito hoped what they had would never change, even as the plane around them did. Rumors of Uprisers in the mountains of Sokenzan City plagued everyday conversation. The Futurists had grown increasingly frustrated by the Imperial regulations over technology. In the Jukai Forest, kami relations were still fraught with tension. And Eiko was always busy studying. Sometimes it felt like the emperor was all Kaito had left. Pressing his fingers against the black roof tiles, Kaito double-checked his grip. It had rained overnight, and some of the guttering still flowed with water. But he liked the challenge, and it was a good way to practice staying on his toes—literally. In the distance, the Eiganjo train rounded a corner, pulling into the station like a metal dagger. Mechs shaped like origami beasts loomed from the surrounding cliffs, and moth riders appeared overhead, waiting to greet the new arrivals—Futurists coming in from the floating city of Otawara to speak with the emperor's advisors. Kaito stuffed the last piece of red bean bun into his mouth, clapped the crumbs from his hands, and skirted along the edge of the roofline toward the emperor's dwelling. Halfway there, he spotted a man dressed in Futurist armor standing in one of the terraced gardens. A moonfolk, hovering several inches above the grass. #emph[He must have come ahead of the others] , Kaito observed. Blue lights blazed across the Futurist's chest in uneven patterns, making the nearly white color of his vest glow. Thin sheets of rose-gold metal sat on his shoulders in layers. The man pinched one with his fingers, plucking it like he was pulling a leaf from a tree. In his hand, the triangular shape expanded before folding over itself again and again, shifting into an origami crane-shaped drone. It took off quickly, disappearing into the clouds like it was carrying a secret on its wings. #figure(image("002_Episode 1: A Stranger in Eiganjo/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) When the man turned back around, Kaito was standing in front of him. The stranger widened his eyes, clearly startled. He soaked in Kaito's youthful face, assessing his age, and relaxed, feet pressing against the ground. "Impressive, kid. It's been a long time since anyone snuck up on me like that." With a chuckle, he added, "But you're lucky the Imperials took my weapons at the gate. People like me tend to slice first and ask questions later." Kaito didn't move. "I'm not a #emph[kid] ." He nodded toward the man's shoulder. "And I'm pretty sure Futurists aren't supposed to bring outside tech into the palace." "I was only sending a friendly message," the man replied easily. "Friendly enough that you had to hide in the garden to send it?" The man tilted his head. "No offense, but you don't seem much like an Imperial to me." He waved a hand over his own face for emphasis. "Most of them have a smugness about them. But you? You just seem curious. Plus, you know, you're still here, talking to me." Kaito crossed his arms. "I wasn't born an Imperial. But this is my home now." Even as he said it, the words felt wrong. How could something true still feel so much like a lie? "No parents, huh?" When Kaito didn't reply, the man shrugged. "Me neither. Mine died working in the factory. There was a toxic spill, and the sensors there were so old, nobody knew about the fumes until it was too late." He tensed his jaw. "Could've been prevented if they'd had access to better equipment, but with all the Imperial regulations and the cost of upgrading anything in the Undercity~" The man's voice trailed off, but he forced another grin. "I'm lucky I had extended family on Otawara. Otherwise, I might still be down there, fighting over outdated tech and struggling to keep a roof over my head." Kaito didn't talk about his parents, and neither did Eiko. Not to anyone. It felt wrong to complain, when the Imperials had given them a safe place to study, with plenty of food, and the kind of shelter some people on Kamigawa would willingly fight over. And yet~ "There was an accident at the Towashi lab where my parents worked, and they were both exposed to radiation." Kaito stiffened. Saying the words out loud felt strange, and too much like a betrayal. What would Eiko say? Light-Paws? The emperor? But the words needed to come out. Maybe it was better Kaito was giving them to a stranger. "Ah," the man said. "Hardly anyone in the Undercity can get the right med-tech for radiation poisoning. It's far too expensive." Kaito's face flushed with a budding anger he didn't even know he'd had. "My dad—he #emph[had] the med-tech. He was going to use it with my mom. But~it hadn't been approved yet." "Black market?" Kaito nodded. "My dad was arrested. He died in prison, and my mom died not long after." The man's voice was edged with compassion. "It's not right that anyone should control who lives and who dies. Technology should be for the people. So they can look after themselves, when no one else will." Kaito twisted his mouth. "But without regulations, anyone could build anything. Bad people could build weapons." There needed to be rules. Light-Paws had emphasized that point more than once. The man clapped Kaito on the shoulder and leaned in. "That's what people say when they want to control you." He pulled his hand away and plucked another small origami crane drone from his armor. "Here. From one person the system failed to another." Kaito took the gift, surprised by how comforting he found it. The Imperials had drones of their own, but this one felt different. It was a piece of a world Kaito had yet to see. The moonfolk strode for the door, limbs flowing with grace despite the rough edges of his voice. "I'm late for a meeting. But it was nice chatting with you, kid." "Not a kid," Kaito called after him. The man laughed over his shoulder. "If you're ever looking for a job, I think the Futurists could use someone like you. Just ask for Katsumasa." He disappeared into the building, and Kaito felt like the earth had shaken something free. Something he'd buried a long time ago and was too afraid to revisit. Until now. He wished he had someone to talk to. But Eiko was dedicated to Imperial life—she would never understand the conflict in his heart. Neither would the emperor. Not when she ruled Kamigawa and believed so fully that controlling technology was the only way to maintain balance between the merging mortal and spirit realms. Kaito watched the moth riders fly over the palace, wondering if Light-Paws would make sure that was him one day. A loyalist until the end. But at least he'd be with the people he cared about. Maybe giving up a part of his heart wouldn't be so bad if he was fighting a battle that kept his family safe. He'd already lost his parents. He wouldn't lose anyone else, ever again. Tucking the crane drone into his pocket, Kaito sighed at the clouds and remembered he had a meeting of his own. He climbed back up the wall and went to meet his friend. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The months passed slowly. Kaito never told anyone about the Futurist in the garden. It was a secret he carried with him. A secret that wouldn't leave his thoughts. But he did tell the emperor how his ideals were changing. She didn't agree, but she let him talk, and somehow that only gave his feelings more purpose. But even as his mind began to branch away from the Imperial teachings, the rest of his life seemed completely unchanged. Until the day Kaito found Light-Paws standing in the sakura garden. "Where's Swift-Arm?" Kaito tilted his head, puzzled. "Did our sparring lesson get cancelled?" "There will be no more sparring lessons." Light-Paws tucked her hands in front of her. There was a time she seemed to tower over Kaito, but now they were the same height. "I don't understand." Kaito's gaze trailed around the garden for the emperor, but she wasn't there. Light-Paws's nose twitched slightly. "You are nearly an adult, Kaito. There is no reason for you to be anyone's sparring partner. You must choose a path and begin your own journey. Swift-Arm thinks you'd be a good fit for—" "I don't want to be a samurai," Kaito interrupted. He hadn't even realized he'd made the decision until the words left his mouth. But he was tired of hiding who he was, and how he felt. Light-Paws's tails straightened behind her. "I know you and the emperor have a friendship." Kaito looked away. "But it is time both of you focus on your duties to Kamigawa—the emperor to her people, and you to the emperor." "I don't need to join the Golden-Tail Academy to do that," Kaito argued hotly. "The emperor has many enemies who wish her to fail," Light-Paws warned. "She needs samurai. #emph[Loyalists] ." She paused, voice sharpening like a blade. "Not a sparring partner more interested in filling her head with ideas about a different future." Kaito's heart cracked down the middle. "She—she told you?" They'd spoken about so many things over the years, one shadow to another. They'd told each other their fears. Their hopes for the plane. But never once did Kaito think she would betray his feelings to Light-Paws. "It is our duty to protect the emperor, always. Privacy is an illusion for someone of her status." Light-Paws sighed, taking a step toward Kaito. "Perhaps I allowed you to hold on to your childhood for too long. It might've been better if I'd intervened and put you on a better path." "A better path?" Kaito choked, fists trembling. "You have no idea what that is!" Light-Paws's dark eyes remained fixed. "Balance is the #emph[only ] path. The machines we build can change Kamigawa. That is a power that needs supervision." "A single path only works when everyone is equal," Kaito shot back. "The Imperials are safe in Eiganjo. There is harmony with kami, and technology is available whenever they need it. But there are places on Kamigawa that don't have those luxuries. People who need to push the boundaries of tech because their world isn't designed for comfort. And you shut it down—you #emph[control] them because you can't imagine a plane where a civilian might need to invent different equipment to keep themselves alive, and safe. You limit access to anyone who doesn't have the right permits, without any regard to those who can't afford them. Where's the balance in that? You are #emph[killing] people and—" "That is enough, Kaito," Light-Paws snapped, ears bent and nostrils flaring. "Those permits and regulations ensure technology is #emph[safe] . You are using radical words that have no place in the Imperial palace." "What you mean," Kaito replied bitterly, "is that #emph[I] have no place here." It was the first time Kaito had turned his back on his mentor. It didn't feel brave, or powerful, or overdue. It felt like severing something that might never be repaired. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaito couldn't sleep that night. He tossed and turned for hours, trying not to think about what had fallen apart between him and Light-Paws. When the alarm rang through the palace, he was already awake. Tearing from his bed, Kaito grabbed his metal crane drone from the dresser. It had been modified for everyday use and now fit comfortably against his wrist. He ran for the hallway; samurai and Imperial staff were everywhere, alerting one another and racing for their posts. Kaito started to move toward Eiko's quarters when he spotted one of the librarians running toward him. He held up an arm to stop her. "What's happened?" She shook her head back and forth, the terror lingering in her eyes. "There's an intruder in the palace. They're saying the Uprisers are here!" Pushing his arm away, she bolted past him for safety. Kaito hesitated. Nobody would be looking for Eiko. She'd be safe with the other diplomat students. But the emperor~ Kaito turned on his heels, searching for the nearest balcony. Samurai would be watching the halls, and the doorways, and the gates. But Kaito spent years running around the palace, moving in and out of places unseen. #emph[And the guards rarely watched the rooftops.] Beneath the velvet and starlit sky, Kaito took the fastest route to the emperor's chambers. His chest burned as he flew across the black tiles, eyes pinned on the garden where he'd spent so many afternoons. When he spotted the porch, there was no light spilling across the grass. But the door was already opened. Kaito leapt from the wall, rolling into a careful stop at the bottom step. He tiptoed silently, pausing at the door, and removed the metal drone from his wrist. It folded itself into an origami crane and flew straight for the shadows. He pressed a finger to the chip against his temple that let him see through the drone's camera. The emperor wasn't there, and neither was the intruder. But the door to Kyodai's chamber was also open, and inside, moonlight swept across the floor. A sound echoed through the room—like three voices crying at once. A shout, a song, and a whisper, all of them edged in pain. Kaito didn't care about waiting on the drone to show him what was behind the door. He ran to the sound. Because if Kyodai was in trouble, then the emperor~ He skidded to a halt when he reached the grand chamber, just as the drone landed back on his wrist. An indoor hot spring pooled in the distance, the fog blanketed across the water, making it appear as if the room stretched on for an eternity. Kaito had never laid eyes on Kyodai before. The guardian spirit of Kamigawa only spoke through the emperor—#emph[channeled ] herself through the emperor in a way no one else could ever experience. Not without the great kami's blessing, which was only meant to be given upon the emperor's death. The kami was enormous, with hundreds of golden, human-sized arms forming her belly and limbs. Gold spheres trailed along the fans at her back, with a large black one embedded in her forehead. With a pointed mouth like a dragon, three masks lined Kyodai's face. They represented <NAME>—the first emperor to channel with Kyodai. #figure(image("002_Episode 1: A Stranger in Eiganjo/05.jpg", width: 100%), caption: [Kyodai, Soul of Kamigawa | Art by: <NAME>], supplement: none, numbering: none) Kaito's gaze trailed to the massive central machine hanging from the ceiling. It was once told to him that Kyodai would cling to it like an enormous cable, almost as if she were keeping herself separate from the mortal plane below. But now Kyodai writhed in the water, lashing at the fog like she was hurting and confused. The emperor was nowhere to be found. Kaito was ready to call the guards—to shout for them to come quickly and see what was wrong with Kyodai—when he saw a strange man rise from the fog beside the kami's body. A man dressed in chrome armor like nothing Kaito had ever seen before, and a metal arm that pulsed with purple energy, the ends forming a monstrous claw. When he locked eyes with Kaito, they glowed an otherworldly pink. With a sneer, the man leapt from the fog toward the open balcony. Kaito had no weapon, but it didn't matter; he wouldn't let the intruder escape, no matter what it cost. He chased after him onto the rooftops. The tiles broke beneath the stranger's weight. He was too fast, and too determined. But Kaito was determined, too. Eyeing a loose tile, Kaito flung his hand forward and sent the object sailing through the air. It shattered against the side of the stranger's head. But it barely seemed to hurt him at all. The man with the metal arm spun, teeth bared, and then dropped his gaze to Kaito's wrist. A sneer formed across his mouth, and he flicked his fingers at the air. Kaito felt his wrist tug, and then he was yanked from the roof, flailing as he tried to grab for the ledge—for anything at all—before his body fell through the air. His back hit the sand garden with a #emph[thud] . Kaito winced, tearing the metal drone from his wrist like he wasn't sure if it had been compromised, and hobbled back to the wall, climbing as quickly as his injured body would allow. When he reached the roof pitch, the man was already gone. By the time he returned to Kyodai's chambers, where all the high-ranking guards and advisors were waiting, he realized the emperor was gone, too. The Imperials spoke over one another, trying to figure out what to do—what had#emph[ happened] . They barely paid Kaito any attention at all, too busy trying to blame the attack on the Uprisers. "I saw him," Kaito argued. "The person who did something with the emperor. He had a metal arm, and glowing eyes—he wasn't an Upriser." He#emph[ couldn't] have been. Not with those strange clothes and a power over technology Kaito had never witnessed before. Light-Paws appeared with all seven tails fanned out behind her. "A metal arm?" Kaito nodded, relieved. Light-Paws would believe him. She'd listen to him. She'd understand that— She turned to the other advisors. "Perhaps the Futurists are responsible for this. They may have used an unregulated prosthetic device to kidnap the emperor, to try and force her to change the laws." "What? No! That's not what happened," Kaito said pleadingly. "It wasn't the Futurists. I know what I saw!" But Light-Paws wasn't listening. She was busy convening with the Imperials, figuring out who to blame and how to retaliate. Kyodai shuddered in the distance, swaying like she didn't understand what was happening or where she was. Maybe even #emph[who] she was. Was it possible that somewhere out there, the emperor was just as scared and confused? Kaito's face burned. There was raw fury in his voice. "You're looking in the wrong direction. You're trying to blame the Futurists instead of chasing after the man I saw—the man I know is responsible for this." Nobody stopped to listen. Not to Kaito. He shouted over the noise and the fog. "He's getting away. If someone doesn't do something, we might never see the emperor again!" Light-Paws turned, eyes admonishing. "Go to your room, Kaito. This is an Imperial matter." Kaito felt it then—what he'd always known. He didn't belong here. He never did. Tearing himself away from the temple, he didn't stop the angry tears from falling down his cheeks. And by the time he reached his room, he knew what he had to do. It would break his heart to leave Eiko, but she had a place in Eiganjo. She had a purpose. And even if it wasn't the one he wanted, now Kaito had a purpose, too. He would search Kamigawa for the man with the metal arm. He would find his friend and bring her home. And for as long as he could help it, he would never step foot in the palace again. That night, Kaito climbed his final wall in Eiganjo, and he didn't look back.
https://github.com/fabriceHategekimana/master
https://raw.githubusercontent.com/fabriceHategekimana/master/main/2_Etat_de_l_art/Lambda_calculus.typ
typst
#import "@preview/simplebnf:0.1.0": * #import "../src/module.typ" : * == Sémantique des langages Établir une sémantique claire et précise pour un langage de programmation prototype revêt une importance capitale lorsqu'il s'agit de tester des hypothèses fondamentales sur sa conception. La sémantique d'un langage définit le sens exact et le comportement des constructions syntaxiques utilisées, ce qui est essentiel pour assurer la prédictibilité et la fiabilité du langage. En définissant rigoureusement la sémantique, les concepteurs peuvent garantir que chaque expression et chaque instruction est interprétée de manière cohérente par le système, minimisant ainsi les ambiguïtés et facilitant la compréhension par les programmeurs. Une sémantique bien établie facilite également la vérification formelle du langage, permettant de valider sa correction avant même sa mise en œuvre complète. Cela inclut la capacité à utiliser des techniques telles que la vérification de type, la preuve de programme et les tests automatisés pour identifier et corriger les erreurs potentielles dans la conception du langage. De plus, une sémantique claire aide les développeurs à expérimenter rapidement avec de nouvelles idées et variations de conception. Ils peuvent ainsi évaluer différentes approches pour la syntaxe, les règles de portée, la gestion de la mémoire et d'autres aspects essentiels du langage, tout en évaluant leur impact sur la facilité d'utilisation et les performances du langage. === Le lambda calcul Le lambda calcul est un formalisme mathématique développé par <NAME> dans les années 1930 pour étudier les fonctions, les variables, et les applications de fonctions de manière abstraite. Il est souvent considéré comme l'un des fondements théoriques de l'informatique et des langages de programmation. Le lambda calcul est particulièrement important car il fournit un modèle minimaliste et élégant pour la computation, où toutes les opérations peuvent être réduites à l'application de fonctions à des arguments. Il se compose de trois éléments de base : les variables, les abstractions (qui définissent des fonctions), et les applications (qui appliquent des fonctions à des arguments). Malgré sa simplicité, le lambda calcul est Turing-complet, ce qui signifie qu'il peut exprimer toute computation réalisable par une machine de Turing. #Definition[Synaxe du lambda calcul $ #bnf( Prod( $e$, annot: $sans("Expr")$, { Or[$x$][_variable_] Or[$λ x. e$][_abstraction_] Or[$e$ $e$][_application_] }, ), Prod( $v$, annot: "values", { Or[$λ x. e$][_abstraction value_] } ), ) $, ] #Definition[Évaluation du lambda calcul $ #proof-tree(eval("E-APP1", $t_1 t_2 --> t_1p t_2$, $t_1 --> t_1p$)) $ $ #proof-tree(eval("E-APP2", $v_1 t_2 --> v_1 t_2p$, $t_2 --> t_2p$)) $ $ #proof-tree(eval("E-APPABS", $(lambda x . t_12) v_2 --> [x\/v_2] t_12$)) $ ] Le lambda calcul est un modèle de computation universel. Le lambda calcul fournit un cadre théorique qui peut simuler n'importe quel autre modèle de computation. Cela en fait un outil puissant pour comprendre les propriétés fondamentales des langages de programmation et pour prouver des théorèmes sur la computation. Le lambda calcul est aussi une base pour les Langages Fonctionnels. C'est un avantage comme R, notre langage cible, est une langage de programmation orienté vers le fonctionnel. De nombreux langages de programmation modernes, tels que Haskell, Lisp, et même certaines parties de Python, sont fortement influencés par les concepts du lambda calcul. Il sert de base à la programmation fonctionnelle, un paradigme qui traite les fonctions comme des citoyens de première classe et favorise des concepts comme l'immuabilité et les expressions pures. Le lambda calcul servira de première pierre à notre langage prototype. #pagebreak()
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2018/WS-06.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [丁宁], [CHN], [3439], [2], [朱雨玲], [MAC], [3412], [3], [刘诗雯], [CHN], [3347], [4], [陈梦], [CHN], [3307], [5], [王曼昱], [CHN], [3248], [6], [陈幸同], [CHN], [3158], [7], [伊藤美诚], [JPN], [3144], [8], [孙颖莎], [CHN], [3144], [9], [石川佳纯], [JPN], [3143], [10], [木子], [CHN], [3126], [11], [武杨], [CHN], [3094], [12], [冯亚兰], [CHN], [3056], [13], [顾玉婷], [CHN], [3030], [14], [冯天薇], [SGP], [3029], [15], [平野美宇], [JPN], [2966], [16], [文佳], [CHN], [2958], [17], [胡丽梅], [CHN], [2945], [18], [郑怡静], [TPE], [2944], [19], [何卓佳], [CHN], [2939], [20], [杜凯琹], [HKG], [2938], [21], [陈可], [CHN], [2936], [22], [芝田沙季], [JPN], [2934], [23], [田志希], [KOR], [2931], [24], [索菲亚 波尔卡诺娃], [AUT], [2921], [25], [#text(gray, "李晓丹")], [CHN], [2903], [26], [李倩], [POL], [2895], [27], [徐孝元], [KOR], [2883], [28], [伊丽莎白 萨玛拉], [ROU], [2875], [29], [金宋依], [PRK], [2874], [30], [加藤美优], [JPN], [2867], [31], [王艺迪], [CHN], [2863], [32], [伯纳黛特 斯佐科斯], [ROU], [2860], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [张蔷], [CHN], [2854], [34], [桥本帆乃香], [JPN], [2850], [35], [GU Ruochen], [CHN], [2849], [36], [车晓曦], [CHN], [2845], [37], [佩特丽莎 索尔佳], [GER], [2835], [38], [张墨], [CAN], [2832], [39], [张瑞], [CHN], [2831], [40], [长崎美柚], [JPN], [2829], [41], [韩莹], [GER], [2827], [42], [石洵瑶], [CHN], [2822], [43], [布里特 伊尔兰德], [NED], [2816], [44], [SAWETTABUT Suthasini], [THA], [2815], [45], [单晓娜], [GER], [2814], [46], [杨晓欣], [MON], [2804], [47], [侯美玲], [TUR], [2804], [48], [EKHOLM Matilda], [SWE], [2803], [49], [CHA Hyo Sim], [PRK], [2803], [50], [#text(gray, "金景娥")], [KOR], [2794], [51], [早田希娜], [JPN], [2792], [52], [佐藤瞳], [JPN], [2787], [53], [傅玉], [POR], [2786], [54], [安藤南], [JPN], [2778], [55], [SOO Wai Yam Minnie], [HKG], [2777], [56], [KIM Nam Hae], [PRK], [2775], [57], [崔孝珠], [KOR], [2767], [58], [孙铭阳], [CHN], [2765], [59], [#text(gray, "帖雅娜")], [HKG], [2764], [60], [李皓晴], [HKG], [2762], [61], [#text(gray, "SHENG Dandan")], [CHN], [2754], [62], [LIU Xi], [CHN], [2753], [63], [玛利亚 肖], [ESP], [2750], [64], [李恩惠], [KOR], [2749], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [李洁], [NED], [2748], [66], [曾尖], [SGP], [2745], [67], [倪夏莲], [LUX], [2739], [68], [李佼], [NED], [2738], [69], [刘佳], [AUT], [2736], [70], [森樱], [JPN], [2736], [71], [LANG Kristin], [GER], [2735], [72], [妮娜 米特兰姆], [GER], [2730], [73], [POTA Georgina], [HUN], [2723], [74], [WU Yue], [USA], [2718], [75], [BALAZOVA Barbora], [SVK], [2715], [76], [#text(gray, "姜华珺")], [HKG], [2714], [77], [HAPONOVA Hanna], [UKR], [2712], [78], [刘高阳], [CHN], [2712], [79], [浜本由惟], [JPN], [2709], [80], [李时温], [KOR], [2706], [81], [李芬], [SWE], [2706], [82], [李佳燚], [CHN], [2694], [83], [森田美咲], [JPN], [2693], [84], [<NAME>], [JPN], [2687], [85], [<NAME>], [CZE], [2687], [86], [<NAME>], [JPN], [2679], [87], [<NAME>], [KOR], [2679], [88], [<NAME>], [SLO], [2678], [89], [<NAME>], [JPN], [2674], [90], [PESOTSKA Margaryta], [UKR], [2669], [91], [刘斐], [CHN], [2659], [92], [梁夏银], [KOR], [2658], [93], [<NAME>-Xuan], [ESP], [2649], [94], [阿德里安娜 迪亚兹], [PUR], [2649], [95], [KIM Youjin], [KOR], [2648], [96], [MAEDA Miyu], [JPN], [2647], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [ZHOU Yihan], [SGP], [2641], [98], [HUANG Yi-Hua], [TPE], [2640], [99], [MIKHAILOVA Polina], [RUS], [2632], [100], [#text(gray, "<NAME>ong")], [PRK], [2630], [101], [YOO Eunchong], [KOR], [2629], [102], [大藤沙月], [JPN], [2625], [103], [#text(gray, "SONG Maeum")], [KOR], [2622], [104], [LIN Ye], [SGP], [2621], [105], [木原美悠], [JPN], [2621], [106], [DVORAK Galia], [ESP], [2620], [107], [张安], [USA], [2618], [108], [于梦雨], [SGP], [2617], [109], [#text(gray, "VACENOVSKA Iveta")], [CZE], [2610], [110], [VOROBEVA Olga], [RUS], [2607], [111], [#text(gray, "CHOI Moonyoung")], [KOR], [2607], [112], [PARTYKA Natalia], [POL], [2606], [113], [玛妮卡 巴特拉], [IND], [2606], [114], [陈思羽], [TPE], [2602], [115], [KATO Kyoka], [JPN], [2598], [116], [<NAME> Daniela], [ROU], [2591], [117], [NG Wing Nam], [HKG], [2591], [118], [PASKAUSKIENE Ruta], [LTU], [2585], [119], [PROKHOROVA Yulia], [RUS], [2585], [120], [PERGEL Szandra], [HUN], [2581], [121], [LIN Chia-Hui], [TPE], [2567], [122], [SABITOVA Valentina], [RUS], [2566], [123], [SO Eka], [JPN], [2565], [124], [<NAME>], [PRK], [2565], [125], [笹尾明日香], [JPN], [2561], [126], [TIAN Yuan], [CRO], [2561], [127], [李昱谆], [TPE], [2556], [128], [NOSKOVA Yana], [RUS], [2554], ) )
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/VerbaliInterni/VerbaleInterno_240104/content.typ
typst
MIT License
#import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro #import "functions.typ": glossary, team #let participants = csv("participants.csv") = Partecipanti / Inizio incontro: #inizio_incontro / Fine incontro: #fine_incontro / Luogo incontro: #luogo_incontro #table( columns: (3fr, 1fr), [*Nome*], [*Durata presenza*], ..participants.flatten() ) = Sintesi Elaborazione Incontro /*************************************/ /* INSERIRE SOTTO IL CONTENUTO */ /*************************************/ == Termini di glossario L'incontro si è aperto con una breve discussione sul modo in cui i termini di glossario vengono riportati all'interno della documentazione; in particolare, il team aveva adottato l'abitudine di denotare la prima occorrenza di un termine di glossario con il corsivo e la #sub("G") a pedice, mentre le occorrenze successive venivano riportate semplicemente con il corsivo. Per rimuovere qualunque ambiguità, visto che il corsivo viene adottato anche per i nomi dei documenti (come riportato nelle _Norme di Progetto v1.0_), il team ha deciso di marcare tutte le occorrenze di tali termini seguendo la prassi del corsivo unito alla #sub("G") a pedice. Di conseguenza, vanno revisionati i documenti attualmente in fase di redazione per assicurarsi che tutti i termini di glossario siano riportati correttamente, oltre che effettivamente inseriti all'interno del _Glossario v1.0_. == Ampliamento Analisi dei Rischi nel _Piano di Progetto_ Nel corso degli ultimi due sprint, coincidenti con il periodo di vacanze natalizie, il team ha riscontrato il verificarsi di un rischio di comunicazione non ancora descritto nella sezione *Analisi dei Rischi* del _Piano di Progetto_; in particolare, il rischio consiste nell'apportare modifiche critiche alla documentazione, senza previa comunicazione al resto del team. Modificare un qualsiasi documento in larga parte o aggiungendo modifiche non approvate dal team (o quantomeno dal quorum di 4/6 persone) è altamente rischioso in quanto esiste la possibilità che le modifiche, una volta valutate criticamente dal team, vengano disapprovate e che debbano essere revocate o eliminate del tutto. Riportare il documento alla versione immediatamente precedente alle modifiche non approvate e incaricare un componente del team di rettificarle, comportano, rispettivamente, uno spreco di risorse e uno sforzo significativo che potrebbero essere evitati con una comunicazione più efficace. Di conseguenza, il team ha deciso di impegnarsi a riportare il livello di comunicazione e cooperazione a quello solito, e anche di implementare due misure preventive per far sì che, anche in situazioni o periodi in cui questa comunicazione dovesse venir meno, il team sia comunque in grado di mantenersi quanto più allineato nel proprio modo di lavorare: - *Meeting di emergenza*: i componenti del team si riservano la possibilità di invocare un meeting di emergenza ( meeting non preventivato e solitamente con poco preavviso) per discutere di aspetti critici legati allo sviluppo di un documento o di una sezione di codice. Dato il poco preavviso, questi meeting avranno un quorum ridotto da 4 a 3 membri totali, in modo da consentire al gruppo ristretto di prendere decisioni rappresentative della volontà del team con immediatezza; - *Stand-up meeting da remoto*: il team è disposto ad effettuare stand-up meeting anche da remoto qualora i componenti non fossero in grado di incontrarsi fisicamente per periodi più o meno prolungati di tempo (questa pratica verrà implementata con ogni probabilità dopo la prima revisione RTB). == Creazione delle issue Il modo in cui il team ha gestito il processo di creazione e assegnazione delle issue finora è basato su un approccio a priori, per cui al termine di ogni incontro interno, che sancisce la fine di uno sprint, il team assiste gli Amministratori di turno in questo compito. In pratica, le issue create a priori a inizio sprint devono rappresentare tutte le attività a cui i componenti sono intenzionati a lavorare nel corso dello sprint; questo ha portato il team a creare issue progressivamente sempre più ampie, in modo da lasciare che sia il componente a cui una determinata issue è stata assegnata a valutare esattamente quali attività intraprendere e portare a termine prima della fine dello sprint. In altre parole, poiché alcune attività emergono solo durante lo sprint, quando un membro del team si rende conto di dover affrontare qualcosa che potrebbe non essere emerso nelle discussioni precedenti, è necessario adottare un approccio leggermente diverso. Questo nuovo approccio mira a creare issue più specifiche e gestibili in modo che il team possa affrontare attività impreviste in corso d'opera, garantendo una maggiore flessibilità e reattività durante lo sviluppo. Questo non solo migliorerebbe il processo di gestione della configurazione del progetto, ma aiuterebbe il team ad evitare situazioni sfortunate in cui due componenti si ritrovano a lavorare alla stessa attività perché questa non era stata ben specificata e vincolata ad una singola issue precedentemente. Nel momento in cui un componente dovesse creare una issue a posteriori e metterla nella corsia "Ready" della Kanban Board del sistema di ITS, non vi sarebbe più un pretesto perché un altro componente decida di lavorare alla stessa attività in modo inconsapevole. == Avanzamento del _Piano di Qualifica_ L'incontro è terminato con una breve discussione in merito alla decisione di utilizzare il rapporto ore preventivate/ore totali a disposizione (570) per il calcolo della percentuale di lavoro preventivato necessaria per la metrica del PV (Planned Value) e, similmente, il rapporto ore effettive/ore totali per il calcolo dell'EV (Earned Value). Nonostante non si fosse certi, in partenza, che il rapporto ore potesse riflettere adeguatamente la percentuale di lavoro svolto, nell'osservare i grafici del _Piano di Qualifica_, il team ha riconosciuto come questi riescano a mettere in evidenza aspetti concreti dell'andamento attuale del progetto. Di conseguenza, il team si è convinto della scelta effettuata. == Rotazione dei ruoli - <NAME>: Amministratore, Verificatore; - <NAME>: Verificatore; - <NAME>: Programmatore, Verificatore; - <NAME>: Verificatore; - <NAME>: Responsabile; - <NAME>: Amministratore.
https://github.com/SillyFreak/typst-packages-old
https://raw.githubusercontent.com/SillyFreak/typst-packages-old/main/crudo/README.md
markdown
MIT License
# Crudo Crudo allows conveniently working with `raw` blocks in terms of individual lines. It allows you to e.g. - filter lines by content - filter lines by range (slicing) - transform lines - join multiple raw blocks While transforming the content, the original [parameters](https://typst.app/docs/reference/text/raw/#parameters) specified on the given raw block will be preserved. `````typ #import "@preview/crudo:0.1.0" #let preamble = ```typ #import "@preview/crudo:0.0.1" ``` #let example = ````typ #crudo.r2l(```c int main() { return 0; } ```) ```` #let full-example = crudo.join(preamble, example) = The example #example = The example with preamble #full-example (usually you don't show this) = Evaluating the example #eval(full-example.text, mode: "markup") ````` See the [manual](docs/manual.pdf) for details.
https://github.com/donabe8898/typst-thesis-template
https://raw.githubusercontent.com/donabe8898/typst-thesis-template/main/lib/meta.typ
typst
Apache License 2.0
#let meta( pdftitle: none, title: none, author: none, size: "a4", doc, ) = { set document(title: pdftitle, author: author) set page(paper: size) doc }
https://github.com/DrakeAxelrod/cvss.typ
https://raw.githubusercontent.com/DrakeAxelrod/cvss.typ/main/bak/src/cvss30.typ
typst
MIT License
// None 0.0 // Low 0.1 - 3.9 // Medium 4.0 - 6.9 // High 7.0 - 8.9 // Critical 9.0 - 10.0
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/jmlr/README.md
markdown
MIT License
# Journal of Machine Learning Research(JMLR) ## Overview This is a Typst template for Journal of Machine Learning Research (JMLR). It is based on official [author guide][1], [formatting instructions][2], and [formatting error checklist][3] as well as the official [example paper][4]. ## Usage You can use this template in the Typst web app by clicking _Start from template_ on the dashboard and searching for `classic-jmlr`. Alternatively, you can use the CLI to kick this project off using the command ```shell typst init @preview/classic-jmlr ``` Typst will create a new directory with all the files needed to get you started. ## Example Papers Here are an example paper in [LaTeX][5] and in [Typst][6]. ## Configuration This template exports the `jmlr` function with the following named arguments. - `title`: The paper's title as content. - `short-title`: Paper short title (for page header). - `authors`: An array of author dictionaries. Each of the author dictionaries must have a name key and can have the keys department, organization, location, and email. - `last-names`: List of authors last names (for page header). - `keywords`: Publication keywords (used in PDF metadata). - `date`: Creation date (used in PDF metadata). - `abstract`: The content of a brief summary of the paper or none. Appears at the top under the title. - `bibliography`: The result of a call to the bibliography function or none. The function also accepts a single, positional argument for the body of the paper. - `appendix`: Content to append after bibliography section. - `pubdata`: Dictionary with auxiliary information about publication. It contains editor name(s), paper id, volume, and submission/review/publishing dates. The template will initialize your package with a sample call to the `jmlr` function in a show rule. If you want to change an existing project to use this template, you can add a show rule at the top of your file. ```typst #import "@preview/classic-jmlr": jmlr #show: jmlr.with( title: [Sample JMLR Paper], authors: (authors, affls), abstract: blindtext, keywords: ("keyword one", "keyword two", "keyword three"), bibliography: bibliography("main.bib"), appendix: include "appendix.typ", pubdata: ( id: "21-0000", editor: "My editor", volume: 23, submitted-at: datetime(year: 2021, month: 1, day: 1), revised-at: datetime(year: 2022, month: 5, day: 1), published-at: datetime(year: 2022, month: 9, day: 1), ), ) ``` ## Issues - JMLR example paper is not not representative. - Leading in author affilations in in the original template is varying. - There is no bibliography CSL-style. The closest one is `bristol-university-press`. - Another issue is related to Typst's inablity to produce colored annotation. In order to mitigte the issue, we add a script which modifies annotations and make them colored. ```shell ../colorize-annotations.py \ example-paper.typst.pdf example-paper-colored.typst.pdf ``` See [README.md][7] for details. [1]: https://www.jmlr.org/format/authors-guide.html [2]: https://www.jmlr.org/format/format.html [3]: https://www.jmlr.org/format/formatting-errors.html [4]: https://github.com/jmlrorg/jmlr-style-file [5]: example-paper.latex.pdf [6]: example-paper.typst.pdf [7]: ../#colored-annotations
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/single-arg-closure.typ
typst
Apache License 2.0
#{ let row_len = 10 let hlines = ((h: 1, y: 1), (h: 2, y: 2)) let new_hlines = range(0, row_len + 1).filter(y => hlines.filter(h => h.y == y) .len() == 0 ) new_hlines }
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/AI/Deep%20Learning/DL%20basics.typ
typst
#import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "Deep Learning Basics", lang: "zh", ) #info(caption: "深度学习领域大致划分")[ + 深度学习基础 + 卷积神经网络(CNN) + 循环神经网络(RNN) + 注意力机制(Attention) + 生成式模型(Generative Model) + 对比学习与自监督学习(Contrastive & Self-supervised Learning) + 图神经网络(GNN) + 其它话题 + 其它模型 + 迁移学习与终生学习 + 元学习 + 机器学习可解释性 + 机器学习中的攻击与防御 + 网络压缩 + 从任务角度看 + CV: Computer Vision + NLP: Natural Language Processing + AIGC: AI Generative Content + Multimodal & Large Model ] - 网络上其他人的笔记 + #link("https://github.com/Michael-Jetson/ML_DL_CV_with_pytorch")[Michael-Jetson/ML_DL_CV_with_pytorch] + #link("https://github.com/sotaBrewer824/LHY_MLDL")[sotaBrewer824/LHY_MLDL] 《李宏毅机器学习》极为详尽的笔记,写成一本书了快 = 深度学习基础 ... = CNN ... = RNN - RNN 主要用于处理序列数据,比如时间序列数据,它的高级变种包括 LSTM 和 GRU 等。 == Basic RNN - RNN 的基本结构如下,其中 $W_"in", W_h, W_"out"$ 都是共享的,以此减少参数量。 #fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-16-29-29.png") - RNN 最大的问题是梯度消失和梯度爆炸 - RNN 本身的改进有:多层 RNN 和双向 RNN - 多层 RNN:将许多 RNN 层堆叠得到,在纵向上也进行序列化学习 - 双向 RNN:当排列顺序固定,文本意义一般是固定的,人类习惯于从左往右阅读,但对于 RNN 来说,从左往右或从右往左并没有本质的区别,且二者可以并行。 #grid( columns:2, fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-16-33-24.png"), grid.cell(align: horizon, fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-16-32-55.png")) ) #info(caption: "nn.RNN的参数")[ + `input_size` 输入特征的维度, 一般 RNN 中输入的是词向量,那么 `input_size` 就等于一个词向量的维度 + `hidden_size` 隐藏层神经元个数 + `num_layers=1` 网络的层数 + `nonlinearity=tanh` 激活函数 + `bias=True` 是否使用偏置 + `batch_first=False` 输入数据的形式,默认即 (seq(num_step), batch, input_dim) 的形式,也就是将序列长度放在第一位,batch 放在第二位 + `dropout=0` 是否应用 dropout, 默认不使用,若使用将其设置成一个0\~1的数字 + `birdirectional=False` 是否使用双向的 rnn,默认是 False ] - 使用上分为 `nn.RNN` 和 `nn.RNNCell`,前者后者堆叠而成,后者是单个时间步上的RNN单元,使用更加灵活 - Example ```py class SimpleClassificationRNN(nn.Module): def __init__(self, hidden_size): super(SimpleClassificationRNN, self).__init__() self.rnn = nn.RNN(input_size=1, hidden_size=hidden_size, batch_first=True, num_layers=1) self.linear = nn.Linear(hidden_size, 1) def forward(self, seq, hc=None): tmp, hc = self.rnn(seq, hc) # tmp.shape = (batch, seq_len, hidden_size) = (800, 20, 16) # hc.shape = (num_layers, batch, hidden_size) = (1, 800, 16) out = torch.sigmoid(self.linear(hc[-1, ... ,:])) return out, hc model = SimpleClassificationRNN(hidden_size=16) output, _ = model(X) # X.shape = (batch, seq_len, input_dim) = (800, 20, 1) # ... # for RNNCell, should input hidden state mannully output, hc = model(X, hc) ``` == LSTM - LSTM 通过引入门控机制,缓解 RNN 的梯度消失和梯度爆炸问题,分为输入门、遗忘门、输出门和记忆单元。 #fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-22-06-17.png") - LSTM 的用法跟 RNN 差不多,也分 `nn.LSTM` 和 `nn.LSTMCell`,以后者为例 ```py lstm_cell = nn.LSTMCell(input_size, hidden_size) # random input data x = torch.randn(batch_size, seq_length, input_size) x = x.transpose(0, 1) # initialize hidden state and cell state h_0 = torch.zeros(num_layers, batch_size, hidden_size) c_0 = torch.zeros(num_layers, batch_size, hidden_size) h_t, c_t = h_0, c_0 # begin to train for i in range(seq_length): h_t, c_t = lstm_cell(x[i], (h_t, c_t)) ``` == GRU - GRU 是 LSTM 的简化版,只有两个门:重置门和更新门(输入门和遗忘门合并),没有输出门和记忆单元(与隐藏单元合并)。 - 参数更少,性能不减 #fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-22-09-41.png") = Attention & Transformer - #link("https://zhuanlan.zhihu.com/p/338817680")[参考链接] - Transformer 是一个基于注意力机制的模型。Attention is all you need. - 原始版本的 Transformer 由 encoder 和 decoder 组成,BERT 等模型只使用了 encoder 部分;GPT 等模型只使用了 decoder 部分。 #fig("/public/assets/AI/AI_DL/basic/img-2024-07-03-22-14-26.png") - Transformer 在训练和推断时刻是不同的 + 训练时:第$i$个 decoder 的输入 = encoder 输出 + ground truth embeding + 预测时:第$i$个 decoder 的输入 = encoder 输出 + 第 $i-1$ 个 decoder 输出 - 训练时因为知道 ground truth embeding,相当于知道正确答案,网络可以一次训练完成(并且相比多步序列学习,结果不至于偏差太远),并且可以并行; - 预测时,首先输入 start,输出预测的第一个单词 然后 start 和新单词组成新的 query,再输入 decoder 来预测下一个单词,循环往复直至 end - 多头自注意力机制:将输入的序列映射到多个子空间,然后分别进行注意力计算,最后将结果拼接起来。 - 更详细的内容,直接拆分出一个大章 —— LLM = Generative Model - #link("https://zhuanlan.zhihu.com/p/577974910")[概论生成网络(GAN/VAE/Flow/Diffusion)] ... = Contrastive & Self-supervised Learning ... = GNN - 参考 #link("https://distill.pub/2021/gnn-intro/")[Distill 2021 GNN Introduction] - 图这个数据结构相对于之前讨论的文本(序列)、图片(个矩阵),图相对来说更加复杂一点。18 年开始,将神经网络应用在图上这个研究方向逐渐兴起 #info()[ - 本文旨在探索和解释现代的图神经网络 - 什么数据可以表示成一张图 - 图和别的数据有什么不同,为什么要做图神经网络,而不是使用最简单的卷积神经网络等 - 构建了一个 GNN,看各模块的具体结构 - 提供了一个 GNN 的 playground ] == 什么是图,数据怎么表示成图 - 顶点(node)及其属性,边(edge)及其属性,整个图(U)的全局信息,此外还有图的连接性(每条边到底连接的是哪两个点) - 图神经网络所关注的重点 + 怎样把所想要的信息表示成向量 + 这些向量是不是能够通过数据来学到 - image 表示成图:每个像素为顶点,与周围 $8$ 个像素相连边 - text 表示成图:每个词为顶点,每个词和下一个词之间有一条有向边 - 此外还有:社交网络图、分子图、引用图等 - 图的几类问题 + Graph level,对整个图进行识别 + Community/Subgraph Level,社区/子图级别的任务 + Edge level,对边的属性进行判断 + Node level,对顶点的属性进行判断 - 将神经网路用在图上面最核心的问题是:如何表示图使得它能够和神经网络兼容 - 用邻接矩阵来表示连接性,其问题是矩阵巨大且稀疏,并且行列顺序无关导致表示不唯一 - 用邻边列表,每个顶点、边以及全局图的属性都用标量(或向量,不影响)来表示。存储高效且与顺序无关 #fig("/public/assets/AI/AI_DL/basic/2024-09-24-16-16-29.png") == 图神经网络 - GNN 对图上所有的属性(顶点、边和全局)进行可优化变换,这个变换能够保持图的对称信息(置换不变性) - GNN 采用“图入图出”架构,它会对顶点、边和全局的向量进行变换,并逐步转换这些 embeding 信息,而不改变图的连接性 === GCN - 接下来逐步推导得到 GCN - 一个最简单利用了 MLP 的网络层,对顶点向量、边向量和全局向量分别做 MLP #fig("/public/assets/AI/AI_DL/basic/2024-09-24-11-04-44.png") - 最后再加一个分类层,就可以对顶点或边或全局做分类,或者加上*汇聚*操作也可以进行预测 #fig("/public/assets/AI/AI_DL/basic/2024-09-24-11-07-03.png") - 一个问题在于:对每个属性做变换的时候,仅仅是每个属性进入自己对应的 MLP,并没有体现出三者之间的相互联系的连接信息 - 为此进行*汇聚*操作来进行信息传递,例如把每个顶点与其相连的顶点的向量相加,然后再送入 MLP - 再复杂一点,顶点和边之间也可以直接进行信息传递(如果维度不同就投影一下,或者干脆 concat 也可以) - 当然这是顺序相关的,不过可以交替进行以避免顺序影响 #grid2( fig("/public/assets/AI/AI_DL/basic/2024-09-24-11-16-32.png"), fig("/public/assets/AI/AI_DL/basic/2024-09-24-11-16-40.png") ) - 和卷积操作有点类似,但是还是有区别(汇聚时权重相等),之所以不做权重是因为图的连接比卷积的位置权重灵活得多 - 加入全局信息 master node,跟所有 node 和 edge 都相连 #fig("/public/assets/AI/AI_DL/basic/2024-09-24-12-04-15.png") === GraphSAGE ... === GAT - graph attention network - 前面 GCN 的时候说,图对位置信息不敏感因此没有卷积权重,但可以用类似自注意力机制的方法来计算权重(取决于两个顶点向量之间的关系) - ... == 相关技术 - 更多种类的图 - multi graph:顶点之间可以有多条边 - 分层的图:其中有一些顶点可以能是一个子图(hypernode) - 不同的图结构会对神经网络做信息汇聚的时候产生影响 - 对图进行采样 - 为何需要采样:由于可能有很多层消息传递,在计算梯度的时候,需要把整个 forward 中所有中间变量存下来,导致计算量大到无法承受。通过采样,在小图上做信息汇聚,大大减小计算量 - 几种采样方法:Random node, Random walk, Random walk with neighborhood, Diffusion Sampling - 如何做 batch - 做 batch 是为了利于并行 - 存在一个问题:每一个顶点的邻居的个数是不一样的,如何将这些顶点的邻居通过合并变成一个规则的张量是一个具有挑战性的问题 - inductive biases 归纳偏置 - 图神经网络假设的是:保持了图的对称性(不管怎样交换顶点的顺序,GNN对图的作用都是保持不变的) - 不同汇聚操作的比较 - sum, avg, max,但其实没有一种是特别理想的,主要还是根据任务来定 - GCN 作为子图的函数近似 - 从一定程度上来说,GCN 可以认为是:$n$ 个以自己为中心往前走 $k$ 步的子图,最后求 embeding - 将点和边做对偶 - 图论中可以把点变成边、边变成点,邻接关系表示保持不变。这种变换在 GNN 上也可以使用 - 图卷积和矩阵乘法的关系 - 如何高效实现整个图神经网络的关键点 - 在图上做卷积或者做 random work,等价于将它的邻接矩阵拿出来做矩阵乘法 - 图的可解释性 - 可以将子图中的信息抓取出来,看它到底学到的是什么信息 - generative modeling - 图神经网络是不改变图的结构的,如果想要生成图,怎样对图的拓扑结构进行有效的建模,有相关的一些算法 = 其它话题 == 其它模型 === TCN - Temporal Convolutional Networks,是一种用于处理时间序列数据的卷积神经网络 - 参考 #link("https://blog.csdn.net/weixin_39910711/article/details/124678538")[TCN(Temporal Convolutional Network)时间卷积网络] #hide[ == 迁移学习与终身学习 == 元学习 == 机器学习可解释性 == 机器学习中的攻击与防御 == 网络压缩 ] = Deep Learning Tasks - Deep Learning 最主要的任务是 CV 和 NLP,当然后面就五花八门了起来,这里仅做引入 - 最开始可以这么理解:CV 是处理空间信息,由此发展了卷积神经网络;NLP 是处理时序信息,由此发展了循环神经网络和 Transformer(Attention) - 但是到了后面,二者的边界逐渐模糊(比如,有用卷积做时序的,有用 Transformer 做视觉的)。它们逐渐融合于多模态和大模型的发展中 - 目前的基础机制依旧是 Transformer 和 Attention,似乎还没有探测出它的极限,似乎也还没有更好的压倒性地强于它的模型出现 == CV: Computer Vision - CV 这一块的任务主要分为:图像分类、目标检测、语义分割、风格迁移(or 图像生成)等 - 传统的 CV 主要用的是 CNN,主要理解*卷积*、池化、全连接、激活函数、Dropout、Batch Normalization 等基本组件;然后目标检测这边引入锚框、NMS、IoU 等概念;语义分割这边引入转置卷积 === 图像分类 - 图像分类 topic 下比较有里程碑意义的数据集有: + MNIST + CIFAR-xx + ImageNet - 图像分类 topic 下比较有里程碑意义的网络(按顺序)有: + MLP:多层线性网络 + LeNet:首次采用了卷积层、池化层两个全新的神经网络组件,在 MNIST 数据集上取得瞩目成果 + AlexNet:2012 年的 ImageNet 冠军,特点有——更深的架构、ReLU 的使用、局部响应归一化(LRN)、数据增强和 Dropout、GPU 加速 + VGG:规律的设计、简洁可堆叠的小卷积块、更深的架构 + NiN:网络中的网络,引入了 1x1 卷积核,可以看作是在每个像素的通道上分别使用多层感知机(or 全连接层) + GoogLeNet:Inception 模块(多分支学习) + ResNet:解决“退化现象”,提出残差连接 + DenseNet:ResNet 相加方式实现跨层连接的改进,提出密集连接,每一层都与块内所有之前的层相连(好处——梯度复用、梯度传播、参数效率) === 目标检测 - 目标检测 topic 下比较有里程碑意义的数据集有: + VOC + COCO - 目标检测 topic 下比较有里程碑意义的网络有: - RCNN(Region-based Convolutional Neural Networks,区域卷积神经网络) 系列 + RCNN:使用选择性搜索选择提议区域,然后使用 CNN 提取特征,最后使用 SVM 进行分类 + Fast RCNN:仅在整张图象上执行卷积神经网络的前向传播,仍使用选择性搜索选择提议区域 + Faster RCNN:将生成提议区域的方法从选择性搜索改为了区域提议网络(RPN,相当于一个糙一点的目标检测模型),也即 two-stage 方法 + Mask RCNN:利用数据集中的像素级信息提升目标检测精度 - SSD(Single Shot MultiBox Detector,单发多框检测):使用CNN提取多尺度特征块(特征金字塔),然后在每个特征块上预测目标的类别和位置 - YOLO(you only look once) 系列 === 语义分割 - 语义分割 topic 下比较有里程碑意义的数据集有: + Pascal VOC2012 - 语义分割 topic 下比较有里程碑意义的网络是*全卷积网络*(fully convolutional network, FCN) - 引入*转置卷积*(有时笼统地翻译为反卷积) - 使得网络学习到某种特征后还能恢复到原来的尺寸,最后的输出为对每个像素分类 === 风格迁移(or 图像生成) - 风格迁移 or 图像生成后来有 GAN, Diffusion 等更好的方法,这里只是介绍一个很基础的方法 - 将内容图片和风格图片都过一遍网络,要求生成的图像在某些层上与内容图片对齐,有些层上与风格图片对齐。对图像做训练而不是对模型做训练,或者说这里就没有训练、推理的区别了,训练的过程就是生成的过程 == NLP: Natural Language Processing - NLP 这边对于数据的处理比较复杂 - 首先要进行文本预处理,然后使用 vocab 来将文本数字化并分词(tokenize),再做 embeding 化为词向量(或者简单地做 one-hot) - 然后还要做 padding,使得每个句子的长度一致才能进行训练,接下来做成 batch 进行训练 - 然后模型设计和训练过程中还要时刻注意语言数据的 shape 和含义,时不时要利用 `valid_lenth` 做裁剪…… - 对文本数据这种时序信息,我们往往用自回归模型处理 === 循环神经网络 - RNN,以及它的衍生 LSTM 和 GRU,效果实际上差不多 === 近代循环神经网络 - Encoder-Decoder 架构 - seq2seq 学习 - 各种优化和概念:束搜索(bin search),困惑度(perplexity),BELU score 等 === Transformer & Attention - 两种注意力机制 - Additive Attention - Scaled Dot-Product Attention - 注意力机制的变种 - self-attention - multi-head attention - 关于 Transformer 的基础可以参考 #link("http://crd2333.github.io/note/Reading/%E8%B7%9F%E6%9D%8E%E6%B2%90%E5%AD%A6AI%EF%BC%88%E8%AE%BA%E6%96%87%EF%BC%89/Transformer")[原论文阅读笔记] == AIGC: AI Generative Content ... == Multimodal & Large Model ...
https://github.com/j-mueller/typst-vegalite
https://raw.githubusercontent.com/j-mueller/typst-vegalite/main/test/test.typ
typst
MIT License
#set page(width: 200mm, height: 150mm, margin: 10mm) #import "../typst-package/lib.typ" as vegalite #vegalite.render( width: 100%, height: 100%, zoom: 1, json("spec.json") )
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/Text/smallcaps.typ
typst
#set text( size:10pt, ) #set page( paper:"a5", margin:(x:1.8cm,y:1.5cm), ) #set par( justify: true, leading: 0.52em, ) = 显示为小写 将文本显示为小写形式。 注:这将为字体启用OpenType smcp功能。并非所有字体都支持此功能。 有时小写字母是专用字体的一部分,有时根本不可用。将来,此函数将支持选择专用小写字体以及从普通字母合成小写字母,但尚未实现。 = 例子 #image("14.png") = 参数 #image("15.png") = 正文 显示为小写形式的文本。
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/multiline_08.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test multiple trailing line breaks. $ "abc" &= c \ \ \ $ Multiple trailing line breaks.
https://github.com/KarPhoon/VSCode-hsnip-for-Typst
https://raw.githubusercontent.com/KarPhoon/VSCode-hsnip-for-Typst/main/README.md
markdown
# Typst snippets for [HyperSnips](<https://marketplace.visualstudio.com/items?itemName=draivin.hsnips>) extension of VSCode Useful snippets for [Typst](<https://typst.app>) in math typing, and using additional regex bypass some unresolved issue of HyperSnips.
https://github.com/max-niederman/CS250
https://raw.githubusercontent.com/max-niederman/CS250/main/hw/1.typ
typst
#import "../lib.typ": * #import "@preview/diagraph:0.1.0" #show: homework.with(title: "CS 250 Homework #1") = Logarithms == 1 + $ x = 2 $ + $ x = 0 $ + $ x = (log_2 4) / (log_2 16) = 2 / 4 = 1 / 2 $ + $ x = - log_2 8 = -3 $ + $ log_5 x &= 5 \ x &= 5^5 \ &= #calc.pow(5, 5) $ + $ x = 3 $ + $ x = -1 $ + $ x = log_7 (7^3) = 3 $ + $ log_x 32 &= 5 \ x^5 &= 32 \ x &= #calc.pow(32, 1/5) $ + $ log_x (2^10) &= 10 \ x &= 2 $ == 2 + $ & log_2 x^2 y \ =& log_2 x^2 + &log_2 y \ =& 2 log_2 x + &log_2 y $ + $ & log_2 (x^3 y^2) / z \ =& log_2 x^3 + log_2 y^2 - &log_2 z \ =& 3 log_2 x + 2 log_2 y - &log_2 z $ + $ & log_2 x y z \ =& log_2 x + log_2 y + log_2 z $ + $ & log_2 (x / y)^2 \ =& 2 log_2 (x / y) \ =& 2 (log_2 x - log_2 y) \ =& 2 log_2 x - 2 log_2 y $ + $ & log_2 root(3, x y) \ =& 1/3 log_2 x y \ =& 1/3 (log_2 x + log_2 y) \ =& 1/3 log_2 x + 1/3 log_2 y $ == 3 + $ 3^4 = 81 $ + $ 7^1 = 7 $ + $ (1/2)^3 = 1/8 $ + $ 3^0 = 1 $ + $ 4^(-3) = 1/64 $ == 4 + $ log_8 64 = 2 $ + $ log_10 1000 = 3 $ + $ log_4 1/16 = -2 $ + $ log_3 1/81 = -4 $ + $ log_(1/2) 32 = -5 $ = Graphs == 1 $g$ must satisfy: $ g(a) = (1, 2) \ g(b) = (1, 3) \ g(c) = (2, 3) \ g(d) = (2, 2) $ Any function that satisfies these conditions could be _the_ function, but the simplest one is the one defined only on $a$, $b$, $c$, and $d$. == 2 #[ #set enum(numbering: "a.") + The graph is simple because it does not have any loops or parallel arcs. + The graph is not complete because not all nodes are adjacent. + The graph is connected because there is a path between every pair of nodes. + $3, a_5, 5, a_6, 6$ and $3, a_3, 4, a_4, 5, a_6, 6$ are two distinct paths between $3$ and $6$. + Yes, $3, a_3, 4, a_4, 5, a_5, 3$ is a cycle. + Removing $a_3$, $a_4$, or $a_5$ would make the graph acyclic. + Removing $a_6$ would make the graph disconnected. ] == 3 #grid( columns: 3, figure( diagraph.raw-render( engine: "neato", height: 2in, )[```dot graph test { mode = "major" node [shape = "circle"] 1 -- 2 1 -- 3 2 -- 3 } ```], caption: [A simple graph with three nodes of degree two.], ), figure( diagraph.raw-render( engine: "neato", height: 2in, )[```dot graph test { mode = "sgd" node [shape = "circle"] 1 -- 1 1 -- 2 2 -- 1 2 -- 3 3 -- 1 3 -- 4 4 -- 1 } ```], caption: [A graph with four nodes and cycles of length $1$ through $4$.] ), figure( diagraph.raw-render( engine: "neato", height: 2in, )[```dot graph test { mode = "sgd" node [shape = "circle"] 1 -- 1 2 -- 2 1 -- 2 1 -- 2 3 -- 3 4 -- 4 3 -- 4 3 -- 4 } ```], caption: [A noncomplete graph of four nodes, each having degree four.], ) ) == 4 #[ #set enum(numbering: "a.") + Nodes $3$, $4$, $5$, and $6$ are reachable from node $3$. + The shortest path from $3$ to $6$ has length $2$. + One such path is: $ 1, 2, 2, 2, 2, 2, 2, 1, 6 $ ] == 5 Carl and Fletcher are not acquainted. SiuYin is acquainted with just one person, Carl. The degree of seperation between Carl and Yuri is $2$, with the shortest path being through Moku. = Trees == 1 The graphs in a, c, and d are trees. They are drawn as conventional trees below. The graph in b is not a tree because it contains a cycle. #grid( columns: 3, gutter: 4pt, figure( diagraph.raw-render( engine: "dot", height: 1.5in, )[```dot graph test { node [shape = "circle", label = "", height = 0.1] r [xlabel = "r"] r -- 1 1 -- 2 2 -- 3 } ```], caption: [A conventional drawing of the tree in Exercise 6.2.1 (a).] ), figure( diagraph.raw-render( engine: "dot", height: 1.5in, )[```dot graph test { node [shape = "circle", label = "", height = 0.1] r [xlabel = "r"] r -- 1 r -- 2 r -- 3 r -- 4 r -- 5 r -- 6 } ```], caption: [A conventional drawing of the tree in Exercise 6.2.1 (c).] ), figure( diagraph.raw-render( engine: "dot", height: 1.5in, )[```dot graph test { node [shape = "circle", label = "", height = 0.1] r [xlabel = "r"] r -- 10 r -- 11 10 -- 20 10 -- 21 11 -- 22 11 -- 23 20 -- 30 23 -- 31 } ```], caption: [A conventional drawing of the tree in Exercise 6.2.1 (d).] ), ) == 2 The graph in b is not a binary tree because it contains a cycle and is therefore not any kind of tree. The graph in c is a tree, but it is not a binary tree because the root node has four children. The graphs in a and d are binary trees. == 3 #[ #set enum(numbering: "a.") + Yes, it is a binary tree. + Yes, it is a full binary tree because every node has either zero or two children. + Yes, it is a complete binary tree because every level is full except for the last one. + The parent of $e$ is $b$. + $e$ has no right child. + $g$ has depth $2$. + The height of three is $3$. ] == 4 Preorder: $a, b, d, e, h, f, c, g$ Inorder: $d, b, h, e, f, a, g, c$ Postorder: $d, h, e, f, b, g, c, a$ == 5 Preorder: $a, b, d, g, e, c, f, h$ Inorder: $g, d, b, e, a, h, f, c$ Postorder: $g, d, e, b, h, f, c, a$ == 6 Preorder: $a, b, e, c, f, j, g, d, h, i$ Inorder: $e, b, a, j, f, c, g, h, d, i$ Postorder: $e, b, j, f, g, c, h, i, d$ == 7 Preorder: $a, b, e, f, c, g, h, d, i$ Inorder: $e, b, f, a, g, c, h, i, d$ Postorder: $e, f, b, g, h, c, i, d, a$
https://github.com/Simgnt/report-typst-template
https://raw.githubusercontent.com/Simgnt/report-typst-template/main/_extensions/report/typst-template.typ
typst
// This is an example typst template (based on the default template that ships // with Quarto). It defines a typst function named 'article' which provides // various customization options. This function is called from the // 'typst-show.typ' file (which maps Pandoc metadata function arguments) // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-show.typ' entirely. You can find // documentation on creating typst templates and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #let report( // Titre du rapport. title: "Titre du rapport", // prénom et nom author: "<NAME>", // maître de stage stagemaster: "Maître de stage", //date de début et de fin datedebut: "date de début", datefin: "date de fin", // Institution : institution : "Institution", // Ville : ville: "Ville", // Table des matières : toc: none, toc-title : "Table des matières", toc-depth: 3 , // Format A4. paper-size: "a4", //Remerciements remerciements: none, // Chemin vers la biblio bibliography-file: none, // The paper's content. body ) = { // Set document metadata. set document(title: title, author: author) // Set the body font. set text(font: "~/work/report/Times_New_Roman", size: 12pt) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Configure headings. set heading(numbering: "1.1.1)") show heading.where(level: 1): set text(size: 14pt, weight: "bold") show heading.where(level: 2): set text(size: 13pt, weight: "regular", style: "italic") show heading.where(level: 3): set text(size: 12pt, weight: "bold") //Page de présentation set page(numbering: none) //Auteur columns(2, gutter: 14pt)[ #set par(justify: true, first-line-indent: 1em) #show par: set block(spacing: 0.65em) #align(left)[#text(size: 14pt, weight: "bold", author)] #colbreak() #align(right)[*ENSAE 3ème année* \ *Stage de fin d'études*]] //Espacement vertical box(height: 5cm)[] // Titre. align(center)[ #box( width: 90%, stroke: black, inset: 10pt )[ \ #text(size: 24pt, title) ]] // Institution et date. v(53%) columns(2, gutter: 14pt)[ #set par(justify: true, first-line-indent: 1em) #show par: set block(spacing: 0.65em) #align(left)[#text(size: 14pt, weight: "bold", institution) \ #text(size: 14pt, weight: "bold", ville)] #colbreak() #align(right)[#text(size: 14pt, weight: "bold")[Maître de stage :] \ #text(size: 14pt, weight: "bold", stagemaster) \ #text(size: 14pt, weight: "bold", datedebut) - #text(size: 14pt, weight: "bold", datefin)]] // Configure the page. set page( paper: paper-size, numbering: "1", // The margins depend on the paper size. margin: if paper-size == "a4" { (x: 41.5pt, top: 80.51pt, bottom: 89.51pt) } else { ( x: (50pt / 216mm) * 100%, top: (55pt / 279mm) * 100%, bottom: (64pt / 279mm) * 100%, ) } ) pagebreak() //Remerciements if remerciements != none [ #text(size: 14pt, weight: "bold")[Remerciements :] #v(2pt) #par(justify: true, leading: 1.5em)[ #set text(size: 12pt, style: "italic") #remerciements] #pagebreak() ] //Table des matières outline(title: text(14pt, weight: "bold", toc-title), depth: int(toc-depth), indent: auto) pagebreak() //Configuration de l'interligne set par(leading: 1.5em, justify: true) // Corps du texte body // Display bibliography. if bibliography-file != none { show bibliography: set text(8pt) bibliography(bibliography-file, title: text(10pt)[References], style: "ieee") } }
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/identify-scoring/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Identify: Scoring Triballs", type: "identify", date: datetime(year: 2023, month: 9, day: 1), author: "<NAME>", witness: "Violet Ridge", ) Getting the triballs into the goal is a very important task. As covered in the rules section at the beginning of the notebook, each triball scored in our alliance's goal gives us 5 points. This makes it very important that we can get as many triballs into the goal as fast as possible. #image("./scoring-triballs.svg", height: 50%) #heading([Design Constraints], level: 1) - The design is constrained by the 36 inch expansion limit - We only want to use two pneumatic pistons. #heading([Design Goals], level: 1) - Fold out from a position parallel with the side of the robot in less than a second. - Be stable enough to push 6 tri-balls into the goal at once from directly in front of the goal. - Be able to pull triballs out of the loading area fairly easily and quickly. - It should be able to do all of the above WITHOUT moving the triballs when turning (otherwise it counts as possession).
https://github.com/colinstfni/ba1-heig
https://raw.githubusercontent.com/colinstfni/ba1-heig/main/mad1/notes/main.typ
typst
#import "../../typst/config.typ": * #import "@preview/cetz:0.2.2" #import "@preview/cetz-venn:0.1.1" #set text(lang: "fr") #let main_color = color.lighten(color.yellow, 30%) #show: doc => conf( title: [= MAD1 Ensembles - 2024 S1], title_color: main_color, authors: [<NAME>], header: ( [_Septembre 2024_], [MAD - Ensembles], [_CS_], ), doc, ) == Les ensembles === Ensembles et éléments #definition[ Un ensemble est un regroupement d'éléments formant un tout. ] Dans les cas où notre ensemble est suffisamment petit, on peut l'écrire entre deux accolades: ${...}$ #example[ L'ensemble des chiffres décimaux s'écrit: $E = {0,1,2,3,4,5,6,7,8,9}$ ] === Appartenance On dit que $x$ *appartient* à $E$ et on note: $ x in E $ Si, au contraire $x$ n'appartient pas à $E$: $ x in.not E $ #example[ $2 in {1,2,3,4}$ ou $5 in.not {1,2,3,4}$ ] ==== Description des ensembles Lorsqu'un ensemble est trop grand pour être écrit élément par élément, on peut procéder à une *description en extension*: #example[ Pour écrire l'ensemble des nombres entiers de 0 à 100, on note: $ {0,1,2,3,...,99, 100} $ ] Cela fonctionne aussi avec l'infini: $ {..., -1, 0, 1, 2, 3, ...} $ Cependant, en mathématiques, par soucis de clarté, on privilégie la *description en compréhension*, en spécifiant une propriété mathématique satisfaite par tous les éléments de l'ensemble: Pour tout $x$ vérifiant $P(x)$, on note: $ {x | P(x)} $ Qui se lit "$x$ tel que $P(x)$". #example[ L'ensemble de tous les $x$ dans $A$ vérifiant $P(x)$ se note ${x in A | P(x)}$ ] === Ensembles égaux #definition[ Deux ensembles sont égaux si et seulement si tout élément de l’un est aussi élément de l’autre. ] Si $A$ et $B$ sont égaux, on note: $A = B$ (wow). Dans un ensembles, l'ordre et la répétition n'ont pas d'importance: *un ensemble est une liste non-ordonnée sans répétitions!* Quelques ensembles sympas: - $NN$: Entiers naturels - $ZZ$: Entiers relatifs - $QQ$: Rationels - $RR$: Réels - $CC$: Complexes En ajoutant le suffixe $#super([\*])$, on exclut $0$ de l'ensemble #example[ $NN^* = {1,2,3,...}$ ] Les suffixes $+$ ou $-$ ajoutent une contrainte de signe à l'ensemble #example[ $ZZ_+ = NN$ ] ==== Intervalles réels #definition[ Un intervalle réel est un ensemble défini par deux bornes, inférieure et supérieure, et formé de tous les nombres réels compris entre ces deux bornes. ] On distingue trois types d'intervalles réels, notés entre deux bornes $[$ et/ou $]$: - Intervalle *fermé*, lorsque les bornes sont *incluses* dans l'ensemble: $[-5; 10]$ - $[a; b] <==> {x in RR | a <= x <= b}$ - Intervalle *ouvert*, lorsque les bornes ne sont *pas incluses* dans l'ensemble: $] -5; 10[$ ou $]-infinity; 10[$ - $]a; b[ <==> {x in RR | a < x < b}$ - Intervalle *semi-ouvert*, lorsqu'une des deux bornes est incluse dans l'ensemble: $]-5; 10]$ ou $[-5; 10[$ - $]a; b] <==> {x in RR | a < x <= b}$ ==== Ensemble vide et ensemble universel L'ensemble vide ne contient... ben rien. Il est noté ${}$ ou $nothing$. #remark[ À priori, les éléments d'un ensemble peuvent être de natures différentes, par exemple: $A= {1, "carrottes", -pi}$ ] En pratique, les éléments d'un ensemble universel, noté $Omega = {...}$, tout comme en probabilités avec les issues possibles d'une expérience aléatoire. === Sous-ensembles #definition[ L'ensemble $B$ est un sous-ensemble ou une partie de $A$ si tous les éléments de $B$ sont aussi des éléments de $A$. On dit aussi dans ces cas que $B$ est inclus dans $A$. On note: $B in A$ ] $ B in A <==> forall x in B, x in A $ 1. Pour tout ensemble $A$, $A$ est un sous-ensemble de lui-même ($A subset A$) 2. L'ensemble vide est sous-ensemble de n'importe quel ensemble $A$ ($emptyset subset A$) Et donc $emptyset subset emptyset$ 3. $A=B$ $<==>$ $A subset B$ #underline[et] $B subset A$ (principe de double inclusion) #example[ Pour $A = {1,2,3}$, $1 subset.not A$ mais $1 in A$, et ${1} subset A$ mais ${1} in.not A$ ] #definition[ Si $B subset.eq A$ et $B != A$, alors ont dit que $B$ est *strictement inclus* dans $A$, noté $B subset A$ ou $B subset.neq A$. Aussi, $B subset A <==> B subset.eq A$ ] ==== Visualisation d'ensembles Le diagramme d'Euler (Venn) reflète les relations entre ensembles. #figure( cetz.canvas({ cetz-venn.venn2(name: "venn") import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [Diagramme de Venn avec $A$ et $B$], ) #figure( cetz.canvas({ cetz-venn.venn3(name: "venn") import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) content("venn.c", [C]) }), caption: [Diagramme de Venn avec $A$, $B$ et $C$], ) === Opérations #definition[ L'intersection de $A$ et $B$, notée $A sect B$ est l'ensemble des éléments appartenant à $A$ #underline[et] $B$, soit $A sect B <==> {x | x in A and x in B}$ ] #figure( cetz.canvas({ cetz-venn.venn2( name: "venn", ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [$A sect B$], ) #definition[ L'union ou la réunion de $A$ et $B$, notée $A union B$, correspond à l'ensemble des éléments se trouvant soit dans $A$, soit dans $B$. ] #figure( cetz.canvas({ cetz-venn.venn2( name: "venn", a-fill: main_color, b-fill: main_color, ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [$A union B$], ) #definition[ Le complément (ou complémentaire) de $A$ est l'ensemble des éléments de l'ensemble universel qui ne sont pas dans $A$, noté $overline(A) = {x | x in.not A}$. ] #figure( cetz.canvas({ cetz-venn.venn2( name: "venn", b-fill: main_color, not-ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [$overline(A)$], ) #definition[ La différence entre $A$ et $B$ notée $A without B$ ("$A$ sans $B$"), est l'ensemble des éléemtsn appartenant à $A$, mais pas $B$. ] #figure( cetz.canvas({ cetz-venn.venn2( name: "venn", a-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [$A without B$], ) On note également les propriétés suivantes: 1. $overline(A) = Omega without A$ 2. $A without B = A sect overline(B)$ #definition[ La différence symmétrique de $A$ et $B$, notée $A xor B$ ($A triangle.t.small B$) est l'ensemble des éléments appartenants soit à $A$, soit $B$, *mais pas les deux* (XOR). ] #figure( cetz.canvas({ cetz-venn.venn2( name: "venn", a-fill: main_color, b-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) }), caption: [$A xor B$], ) On note aussi: $ A xor B = (A without B) union (B without A) = (A union B) without (A sect B) $ #pagebreak() === Propriétés et Identités ==== Associativité $ A union (B union C) = (A union B) union C $ $ A sect (B sect C) = (A sect B) sect C $ #remark[ Ducoup, pas besoin de mettre des parenthèses. ] ==== Commutativité $ A union B = B union A $ $ A sect B = B sect A $ ==== Distributivité $ A union (B sect C) = (A union B) sect (A union C) $ $ A sect (B union C) = (A sect B) union (A sect C) $ ==== Lois de Boole-Morgan $ overline(A union B) = overline(A) sect overline(B) $ $ overline(A sect B) = overline(A) union overline(B) $ #remark[ Parallèles entre logique et ensembles: #align(center)[ ```cpp A and B``` $<==> A sect B$ ```cpp A or B``` $<==> A union B$ ```cpp A xor B``` $<==> A xor B$ ```cpp not A``` $<==> overline(A)$ ] ] #proof[ 1#super[ère] Loi: #table( columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), align: center, )[$A$][$B$][$A union B$][$A union overline(B)$][$overline(A)$][$overline(B)$][$overline(A) sect overline(B)$][0][0][0][1][1][1][1][0][1][1][0][1][0][0][1][0][1][0][0][1][0][1][1][1][0][0][0][0] Les colonnes de $overline(A union B) $ et de $overline(A) sect overline(B)$ sont identiques, donc $overline(A union B) = overline(A) sect overline(B)$ #figure( grid(columns: 2)[#cetz.canvas({ cetz-venn.venn2( name: "venn", a-fill: main_color, b-fill: main_color, ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) content("venn.not-ab", [$A union B$], anchor: "west") }) ][#cetz.canvas({ cetz-venn.venn2( name: "venn", not-ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) content("venn.not-ab", [$overline(A union B)$], anchor: "west") })][#cetz.canvas({ cetz-venn.venn2( name: "venn", b-fill: main_color, not-ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) content("venn.not-ab", [$overline(A)$], anchor: "west") })][#cetz.canvas({ cetz-venn.venn2( name: "venn", a-fill: main_color, not-ab-fill: main_color, ) import cetz.draw: * content("venn.a", [A]) content("venn.b", [B]) content("venn.not-ab", [$overline(B)$], anchor: "west") })], ) ] ==== Loi d'absorption $ A union (A sect B) = A $ $ A sect (A union B) = A $ $B$ est "absorbé" dans les deux cas. === Cardinal (pas la bière) #definition[ Un ensemble $A$ est *fini* si son nombre d'éléments distincts est un entier naturel. Sinon, $A$ est infini. ] #definition[ Si $A$ est fini, le *cardinal* ou la *cardinalité* de $A$, notée $|A| = \#A = "Card"(A)$ est égal au nombre d'éléments distincts de $A$. ] #example[ $|{a,b,c,...,z}| = 26$, $|emptyset| = |{}| = 0$ ] === Ensemble des parties #definition[ Pour un ensemble $A$ donné, *l'ensemble des parties* de $A$, noté $cal(P)(A)$, est l'ensemble contenant tous les sous-ensembles de $A$: $ cal(P)(A) = {x | x subset.eq A} $ ] #example[ $A = {"Oui", "Non"} <==> cal(P) = {emptyset, {"Oui"}, {"Non"}, {"Oui", "Non"}}$ ] Pour n'importe quel ensemble $A$, on a toujours que: $ emptyset in cal(P)(A) "et" A in cal(P)(A) $ #theorem[ Soit $A$ un ensemble fini, tel que $|A| = n "avec" n in NN$, alors $|cal(P)(A)| = 2^n$ ] #proof[ On peut décomposer la création d'un ensemble de parties en une suite de $n$ choix indépendants entre "Je prends l'élément" ou "Je ne le prends pas", ce qui équivaut mathématiquement à $2^n$ possibilités. ] #example[ $A = {"Oui", "Non"}$, donc $|A| = 2 "et" |cal(P)(A)| = 4 = 2^2$ ] === Produit cartésien #definition[ - Un *couple* $(a,b)$ est une liste *ordonnée* des deux éléments $a "et" b$. - Un *triplet* $(a,b,c)$ est une liste ordonnée de trois éléments $a "," b "et" c$. - Plus généralement un *$bold(n)$-uplet* ($a_0, a_1, ..., a_n$) est une liste ordonnée de n éléments appelés les *composantes* ] #example[ Le couple $(1, 2)$ est différent de $(2, 1)$, par exemple lorsqu'ils sont représentés sur un graphe. ] #definition[ Le *produit cartésien* $A times B$ de deux ensembles $A$ et $B$ est l'ensemgle de tous les couples $(a,b)$ tels que $a in A$ et $b in B$ $ A times B = {(a, b) | a in A, b in B} $ ] #example[ Pour $A = {0, 1}$ et $B = {x,y,z}$, on a: $ A times B = {(0,x), (0,y), (0,z), (1,x), (1,y), (1,z)} $ ] #theorem[ Si $|A| = n$ et $|B| = m$, alors $|A times B| = |A| * |B| = n *m$ ] #proof[ En posant un arbre des possibilités de choix de $a$ puis $b$ pour un couplet $(a,b)$, on a d'abord $n$ choix, puis $m$. ] On peut généraliser le produit cartésien à $n$ ensembles: $A_1, A_2, ..., A_n$: $ A_1 times A_2 times ... times A_n = {(a_1, a_2,..., a_n) | a_i in A_i, i in {1,2, ..., n}} $ #remark[ Lorsque $A_1 = A_2 = ... = A_n$, alors $A_1 times A_2 times ... times A_n = A times A times ... times A = A^n$ ] #pagebreak() == Les Relations Les relations peuvent être des outils de comparaisons entre objets mathématiques, comme par exemple les nombres ($<$, $=$, ...), ou les ensembles ($in$, $subset.not$, ...) #definition[ Une relation de l'ensemble $A$ vers l'ensemble $B$ est un sous ensemble du produit cartésien $A times B$. Si $R$ est une relation de $A$ vers $B$, et si le couple $(a, b) in R$ tel que $a in A, b in B$, aussi noté $a R b$. ] #example[ $A = { "étudiant de l'école"}, B = { "cours dispensés ce semestre"}$ L'ensemble $R = { (a, b) in A times B | "l'étudiant " a "suit le cours" b}$ est une relation de $A$ vers $B$. ] #example[ $ A = {"couleurs"}, B = {"pays"}$ On peut définir la relation de correspondance entre une couleur et le drapeau du pays: $R = {(a, b) in A times B | "la couleur" a "dans drapeau du pays" b}$. Ainsi: $("rouge", "Suisse") in R, ("vert", "Espagne") in.not R$ ] #example[ $A = B = ZZ$ On définit $R = {(a,b) in A times B | a <= b} = {(x,y) in ZZ^2 | x <= y}$. $(2,3) in R, (-2, -3) in.not R$ ]
https://github.com/imkochelorov/ITMO
https://raw.githubusercontent.com/imkochelorov/ITMO/main/src/algorithms/s2/l2/main.typ
typst
#import "template.typ": * #set page(margin: 0.4in) #set par(leading: 0.55em, first-line-indent: 0em) #set text(font: "New Computer Modern") #show par: set block(spacing: 0.55em) #show heading: set block(above: 1.4em, below: 1em) #show heading.where(level: 1): set align(center) #show heading.where(level: 1): set text(1.44em) #set page(height: auto) #set page(numbering: none) #show: project.with( title: "Алгоритмы и Структуры Данных. Лекция 2", authors: ( "_scarleteagle", "imkochelorov" ), date: "14.02.2024", ) = Дерево отрезков. Отложенные операции *Операции:* - ```py get(l, r) #min(a_l, a_l+1, ..., a_r+1)``` - ```py add(l, r, x) #O(log n) #a_l += x #a_l+1 += 1 #... #a_r-1 += x``` Как выполнить операцию над отрезком за $O(log n)$, если отрезок в худшем случае имеет длину $O(n)$ #align(center)[#image("1.png", width: 50%) _дерево отрезков_]\ *Ленивые/отложенные операции (Lazy operations)*\ Вместо того, чтобы рекурсивно изменять детей, будем хранить, что в вершине результат правильный, а в детях нужно добавить #text("N", fill: blue). Когда будет запрос на ребёнка, проталкиваем изменения в обоих детей #align(center)[#image("2.png", width: 50%) _дерево отрезков после вызова _```py add(1, 6, 3)```]\ \ #align(center)[#image("3.png", width: 50%) _дерево отрезков после вызова _```py add(2, 5, -1)```]\ *<NAME>:* + На выходе значение корректное + ```py pr[v]``` хранит, сколько прибавить ко всем детям (не считая текущую вершину) // pr = promise ```py def add(v, l, r, ql, qr, x): if (qr <= l or r <= ql): return if (ql <= l and r <= qr): tree[v] += x pr[v] += x return m = (l + r) // 2 push(v) add(2 * v + 1, l, m, ql, qr, x) add(2 * v + 2, m, r, ql, qr, x) tree[v] = min(tree[2 * v + 1], tree[2 * v + 2]) def push(v): if (pr[v] == 0): return tree[2 * v + 1] += pr[v] tree[2 * v + 2] += pr[v] pr[2 * v + 1] += pr[v] pr[2 * v + 2] += pr[v] pr[v] = 0 MAX_INT = 1e12 def get(v, l, r, ql, qr): if ql >= r or qr <= l: return MAX_INT if ql <= l and r <= qr: return tree[x] push(v) m = (l + r) // 2 return min(get(v * 2 + 1, l, m, ql, qr), get(v * 2 + 1, m, r, ql, qr)) ``` \ _Наше дерево легко превратить в дерево на сумму:_ \ ```py def add(v, l, r, ql, qr, x): if (qr <= l or r <= ql): return if (ql <= l and r <= qr): tree[v] += x * (r - l) pr[v] += x return m = (l + r) // 2 push(v) add(2 * v + 1, l, m, ql, qr, x) add(2 * v + 2, m, r, ql, qr, x) tree[v] = sum(tree[2 * v + 1], tree[2 * v + 2]) def push(v): if (add[v] == 0): return tree[2 * v + 1] += pr[v] * (m - l) tree[2 * v + 2] += pr[v] * (r - m) pr[2 * v + 1] += pr[v] pr[2 * v + 2] += pr[v] pr[v] = 0 def get(v, l, r, ql, qr): if ql >= r or qr <= l: return 0 if ql <= l and r <= qr: return tree[x] push(v) m = (l + r) // 2 return sum(get(v * 2 + 1, l, m, ql, qr), get(v * 2 + 1, m, r, ql, qr)) ``` \ \ Суть отложенных операций в том, чтобы выполнять их не когда они пришли, а когда возникла необходимость #quote("Зачем готовиться к экзамену по матану с сентября, если можно начать готовиться за 2 дня до него", attribution: "Первеев <NAME>", block: true) Попробуем сделать более тяжёлую операцию. Например, прибавление арифметической прогрессии ```py add(l, r, x, d) #a_l += x #a_l+1 += x+d #a_l+2 += x+2d #... #a_r-1 += x+d*(...) ``` Сумма арифметических прогрессий --- арифметическая прогрессия\ \ $x_1 + x_2, d_1 + d_2 <=> cases(x_1 quad d_1, x_2 quad d_2)$\ #align(center)[ #image("4.png", width: 30%) _отрезок добавления арифметической прогрессии_] \ Дерево отрезков на сумму с добавлением арифметической прогрессии возможно. На минимум --- нет. \ \ *Задача:*\ Даны прямоугольники и точки. Найти сколькими прямоугольниками покрывается точка\ #align(center)[#image("5.png", width: 40%) _пример прямоугольников и точек_]\ Точки: $(x, y)$\ Прямоугольники: $(x_1, y_1), (x_2, y_2)$\ $0 <= x_i, y_i <= c$\ *Сканирующая прямая:*\ #align(center)[#image("6.png", width: 40%) _для каждой координаты линии по y вычисляем сколькими прямоугольниками она покрывается_]\ *События:* границы прямоугольника, точки.\ Если дано n прямоугольников, m точек, то событий --- 2n+m.\ Сортируем события по x-координате, затем в порядке "начало, точка, конец"\ \ Проходим по событиям - Если встречаем левую границу, то на отрезке $[y_1, y_2]$ добавляем 1.\ - Если встречаем левую границу, то на отрезке $[y_1, y_2]$ вычитаем 1.\ - Если встречаем точку, то выводим значение на $y$. #align(center)[#image("7.png", width: 40%) _пример линий на каждое событие_]\ *Время работы*:\ - Сортировка: $O((n + m) log (n + m))$ - Обработка событий: $O((n + m) log C)$ *Память*: $O(C)$\ _Сжатие координат:_ отсортируем y-координаты и перенумеруем. $C -> O(n + m)$
https://github.com/pedrofp4444/BD
https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[1] Definição do sistema/viabilidade.typ
typst
#let viabilidade = { [ == Análise da Viabilidade do processo Antes de se decidir implementar um sistema de gestão de base de dados, é necessário fazer uma análise da sua viabilidade, de modo a perceber as vantagens que esta implementação traria para a Lusium. A implementação deste sistema traria à agência um maior controlo e conhecimento sobre as relações entre casos, terrenos e funcionários que neles trabalham, o que levaria tanto a uma redução significativa dos frequentes furtos de _edium_ e _nunium_, como a um aumento da segurança na cidade e dos lucros da empresa de mineração. Parâmetros relativos a terrenos, elementos identificadores de um funcionário e ferramentas de trabalho de um detetive, seriam avaliados no contexto do problema em questão. Deste modo, seria promovida uma maior facilidade na gestão dos casos ativos e agilidade na resolução dos mesmos, proporcionada pela utilização do sistema de gestão de base de dados, sendo por isso prevista uma diminuição dos furtos dos minérios em 45%. Por outro lado, é esperado um aumento das receitas da _Lusium_ devido à redução prevista dos furtos de _edium_ e _nunium_. As quantidades roubadas desses minérios têm contribuído para uma perda de cerca de 16% do rendimento anual da empresa. Entretanto, com a diminuição destes incidentes, espera-se recuperar parte, ou até mesmo a totalidade desse prejuízo, o que traria, para além de possíveis lucros, segurança e estabilidade financeira à mesma. Para além disso, esta redução teria um efeito direto no reforço da segurança da cidade de, aproximadamente, 23%, pois é previsto que o escoamento deste tipo de crimes aliviaria a “Casa do Xerife”, permitindo redirecionar, novamente, o seu foco para os casos de pequena escala. É certo que a base de dados traria grandes benefícios para a cidade e para a empresa e, tendo em conta tudo aquilo que foi referido, acreditamos que a implementação deste modelo é definitivamente viável e trará resultados significativos. Apesar disso, a agência terá de assumir os custos e desafios que estão implícitos na implementação do sistema, até porque haverão determinados recursos extra que serão mencionados no tópico posterior. Devido à confirmação da sua viabilidade, damos como previsão de entrega do sistema de gestão de base de dados o dia 24 de maio de 2024. Para tornar esta data possível, mobilizamos os recursos da equipa da “Quatro em Linha” de forma a otimizar o período de tempo pré-estabelecido pela Lusium e executar o projeto proposto. ] }
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/thesis.typ
typst
#import "thesis_temp.typ": * #show: project.with( title: "Simple Open Data Measures of Public Transit Service Availability", subtitle: "Planning and Temporal Variability", authors: ( (name: "<NAME>",matr: "Matrikel_Nr: 3652850", email: "<EMAIL>", affiliation: "Geographisches Institut, Ruprecht-Karls-Universität Heidelberg", betreuer: "Betreuer: Prof. A. Zipf, Prof. apl. S. Lautenbach"), ), date: [#datetime.today().display()], ) #import "preamble.typ": * #bib_state.update(none) #set figure(placement: auto) #include "chapters/01_introduction.typ" #pagebreak() #include "chapters/02_related_work.typ" #pagebreak() #include "chapters/03_methodology.typ" #pagebreak() #include "chapters/04_access.typ" #pagebreak() #include "chapters/05_planning.typ" #pagebreak() #include "chapters/06_summary.typ" #pagebreak() #include "chapters/07_discussion.typ" #pagebreak() #include "chapters/08_conclusion.typ" #pagebreak() #set heading(supplement: "Appendix",depth:2, numbering: "A.1",) #show heading.where(level: 1): it => [ #text([#it.supplement #counter(heading).display(): #it.body]) ] #counter(heading).update(0) #include "appendices/01_aknowledgements.typ" #pagebreak() = Bibliography #bibliography("bibliography.bib", title: none, style: "american-psychological-association") #pagebreak() #include "appendices/03_code.typ" #pagebreak(weak: true) = Figures == Images #set par(first-line-indent: 0em) #outline(title: none, target: figure.where(kind: image)) == Maps #outline(title: none, target: figure.where(kind: "Map"))
https://github.com/Vortezz/fiches-mp2i-maths
https://raw.githubusercontent.com/Vortezz/fiches-mp2i-maths/main/chapter_1.typ
typst
#set page(header: box(width: 100%, grid( columns: (100%), rows: (20pt, 8pt), align(right, text("CHAPITRE 1. LOGIQUE ET RAISONNEMENTS")), line(length: 100%), )), footer: box(width: 100%, grid( columns: (50%, 50%), rows: (8pt, 20pt), line(length: 100%), line(length: 100%), align(left, text("<NAME> - MP2I")), align(right, text("<NAME> - 2023/2024")), ))) #set heading(numbering: "I.1") #let titleBox(title) = align(center, block(below: 50pt, box(height: auto, fill: rgb("#eeeeee"), width: auto, inset: 40pt, text(title, size: 20pt, weight: "bold")))) #titleBox("Logique et raisonnements") = Rudiments de logique == Formule propositionnelles, prédicats Une *formule propositionnelle* est une formule liant des lettres représentant des _propositions élémentaires_ et les _opérations logiques_ suivantes : - $and$ : et - $or$ : ou - $==>$ : implique - $<==>$ : équivalent à - $not$ : non On dit que $A$ est *suffisante* à $B$ si $A ==> B$, que $A$ est *nécessaire* à $B$ si $B ==> A$ et qu'elle est *suffisante et nécessaire* si $A <==> B$. Les *tables de vérité* permettent de savoir quand une propriété est vraie ou fausse. #grid(columns: 5, gutter: 10pt, table(rows: 3, columns: 2, align: center, $P$, $not P$, $V$, $F$, $F$, $V$ ), table(rows: 5, columns: 3, align: center, $P$, $Q$, $(P or Q)$, $V$, $V$, $V$, $V$, $F$, $V$, $F$, $V$, $V$, $F$, $F$, $F$ ), table(rows: 5, columns: 3, align: center, $P$, $Q$, $(P and Q)$, $V$, $V$, $V$, $V$, $F$, $F$, $F$, $V$, $F$, $F$, $F$, $F$ ), table(rows: 5, columns: 3, align: center, $P$, $Q$, $(P ==> Q)$, $V$, $V$, $V$, $V$, $F$, $F$, $F$, $V$, $V$, $F$, $F$, $V$ ), table(rows: 5, columns: 3, align: center, $P$, $Q$, $(P <==> Q)$, $V$, $V$, $V$, $V$, $F$, $F$, $F$, $V$, $F$, $F$, $F$, $V$ ), ) Deux formules sont dites *équivalentes* si et seulement si elles possèdent la même table de vérité, ainsi on note $A equiv B$. Les *tautologies* sont des formules toujours vraies. On a les équivalences et tautologies suivantes : - $(A and B) and C equiv A and (B and C)$ _(associativité)_ - $(A or B) or C equiv A or (B or C)$ _(associativité)_ - $A and (B or C) equiv (A and B) or (A and C)$ _(distributivité)_ - $A or (B and C) equiv (A or B) and (A or C)$ _(distributivité)_ - $(A and (A ==> B)) ==> B$ est une tautologie _(modus ponens)_ - $(A ==> B) <==> B or not A$ - $(A ==> B) <==> (not B ==> not A)$ _(contraposée)_ == Quantificateurs On a $F(x)$ une propriété dépendant d'une variable $x$, - Le quantificateur $forall$ est satisfait si et seulement si, pour toute valeur possible prise de $x$, $F(x)$ est vraie. - Le quantificateur $exists$ est satisfait si et seulement si, il existe un $x$ tel que $F(x)$ soit vraie. Il est donc possible de choisir un $x$ convenable. Si le $x$ est unique, on utilise le quantificateur $exists !$. Dans le cas des quantificateurs, les variables choisies sont dites *muettes*. Les quantificateurs peuvent être réduits à des intervalles spécifiques avec $forall x in E$ ou $exists x in E$. == Négation On a les formules suivantes pour les négations : - $not not P equiv P$ - $not (P or Q) equiv not P and not Q$ _(loi de De Morgan)_ - $not (P and Q) equiv not P and or Q$ _(loi de De Morgan)_ - $not (P ==> Q) equiv P and not Q$ - $not (P <==> Q) equiv((not P) <==> Q) equiv (Q <==> (not P))$ Les quantificateurs sont aussi négationnables : - $not (forall x P(x)) equiv exists x (not P(x))$ - $not (exists x P(x)) equiv forall x (not P(x))$ = Principes de rédaction, modes raisonnements et démonstrations == Composition d’un texte mathématique Un texte mathématique est constitué de : + *définitions* : descriptions de certains objets + *résultats* : énoncés mettant en jeu les objets définis, et donnant des propriétés vérifiées. On distingue : - _axiomes_ : résultats qui sont des vérités fondamentales qui ne sont pas à démontrer - _théorèmes_ : résultats les plus significatifs, démontrés à partir des axiomes et de résultats démontrés antérieurement - _propositions_ : résultats de moindre envergure - _lemmes_ : résultats à voir comme des étapes intermédiaires - _corollaires_ : conséquences d'autres résultats + *démonstrations* : justification de la véracité des résultats + *conjectures* : ce qu'on pense être vrai mais qu'on a pas réussi à prouver Un énoncé est souvent sous la forme $A ==> B$ avec $A$ les hypothèses et $B$ les conclusions. == Comment construire une démonstration Pour construire une démonstration on utilise les principes suivants : - *Prouver une implication* $A ==> B$ : On suppose que $A$ est vrai, et on montre que $B$ est vrai. Il peut être plus simple de montrer la contraposée dans certains cas. - *Prouver une équivalence* $A <==> B$ : On prouve $A ==> B$ et $B ==> A$, il est aussi possible de faire par équivalences successives mais il faut bien vérifier qu'on peut _remonter_ les équivalences. - *Prouver une conjonction* $A and B$ : On prouve $A$ puis on prouve $B$. - *Prouver une disjonction* $A or B$ : On prouve que $not A ==> B$, ainsi on suppose que $not A$ et on montre que $B$ est vraie. On peut intervertir $A$ et $B$ pour faciliter la résolution. - *Prouver* $forall x A(x) :$ On pose un $x$ *supposé quelconque* et on montre que pour ce $x$, $A(x)$ est vérifié. Le fait d'avoir pris $x$ quelconque montre qu'alors $A(x)$ est vrai pour tout $x$. - *Prouver* $exists x A(x) :$ Dans le meilleur des cas on construit *x* qui convient. Pour s'aider à trouver un *x* convenable on peut faire une analyse/synthèse. #emoji.warning *Il ne faut jamais perdre de vue le but d'une preuve* == Le Modus ponens Pour que $B$ soit vrai, il suffit que $A$ soit vrai et que $A ==> B$, on exploite la tautologie $(A and (A ==> B)) ==> B$. Il est important de vérifier à la fois $A$ et à la fois $A ==> B$, comme quand on utilise un théorème utilisé en donnant son nom, et la validité des hypothèses d'autre part. == Démonstration par la contraposée On exploite l'équivalence $(A ==> B) equiv (not B ==> not A)$, ainsi on suppose la conclusion $B$ fausse et on montre que dans ce cas l'hypothèse $A$ ne peut être vraie. L'expression $not B ==> not A$ est appelée *contraposée* de $A ==> B$. Si $A$ est toujours vraie, alors on montre que supposer $not B$ nous amène à une contradiction, on procède donc à une *démonstration par l'absurde*. == Disjonction de cas Le principe de disjonction de cas repose sur $(A or B) ==> C equiv (A ==> C) and (B ==> C)$. On regarde ce qu'il se passe pour l'hypothèse $A$, puis pour l'hypothèse $B$. Ainsi si $A$ est vérifiée $C$ aussi, et pareillement pour $B$. == Analyse-Synthèse Ce principe de démonstration est surtout adapté pour les problèmes existenciels. - Phase d'*analyse* (recherche de CN) : On suppose que l'objet existe, et à l'aide des propriétés qu'il est censé vérifier on récupère le plus d'informations possibles sur la façon de le construire. - Phase de *synthèse* (vérification des CS) : Lorsqu'on a suffisamment d'informations sur une façon de construire l'objet, on construit un objet de la sorte, et on vérifie si il répond au problème. - Si la phase d'analyse fournit une expression explicite de l'objet, alors l'objet est unique. #emoji.warning *Il est primordial de préciser qu'il s'agit d'une analyse synthèse car on suppose que l'objet existe.* == Raisonnement par récurrence Le principe de récurrence est un axiome de la construction de $NN$, il s'énonce : #align(center, $(P(0) and (forall n in NN, P(n) ==> P(n+1))) ==> (forall n in NN, P(n))$) On a $P(0)$ l'initialisation et $forall n in NN, P(n) ==> P(n+1))$ l'hérédité. == Principe de la descente infinie (HP) // Do not touch #block(height: 400pt)
https://github.com/jonaspleyer/peace-of-posters
https://raw.githubusercontent.com/jonaspleyer/peace-of-posters/main/docs/content/examples/customize_boxes/main.typ
typst
MIT License
// We begin by importing the `peace-of-posters` package #import "../../../../lib.typ": * // Next, we specify some general settings formatting settings. // #set page("a0", margin: 1cm) // #set-layout(layout-a0) #show: poster-layout.with( layout: layout-a4, ) = My Heading
https://github.com/ldq3/summary_of_OS_camp
https://raw.githubusercontent.com/ldq3/summary_of_OS_camp/master/src/content.typ
typst
#import "/global.typ": * = Rust 异步编程 == 同步和异步 同步:多个操作之间相互关联,所以必须有明确的顺序。 异步:多个操作之间并不直接相关,故不必有明确顺序。 并发执行异步任务可以提高计算资源的使用效率,并行执行异步任务可以缩短任务的执行时间。 #pagebreak() 如何实现程序的异步执行?一个程序包含代码和数据两个部分,所以关键在于如何取舍代码和数据的切换: - 进程:切换代码和数据; - 线程:切换代码,不切换数据; - 协程:不切换代码,不切换数据。 一些协程的实现方式:回调、Go Coroutines、actor、async/.await。 形成的文档:#link("https://ldq3.github.io/2024/05/24/%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/#more")[异步编程概述]。 == Future Rust 实现了 async/.await 作为其异步编程模型。 future 是 Rust 的异步任务模型。从逻辑上看,一个 future 是一个状态机,future 会在给定的状态处等待;从底层实现上看,future 是一个实现了 Future 特征的结构体,这个结构体中包含状态、数据、其它 future 等内容,Future 特征包含 Executor 可见的 future 状态和一个 poll 方法两部分内容。 #pagebreak() 例如: ```Rust let fut_one = /* ... */; // Future 1 let fut_two = /* ... */; // Future 2 async move { fut_one.await; fut_two.await; } ``` #pagebreak() 经编译器处理后,自动生成一个结构体,并为其实现 Future 特征: ```Rust struct AsyncFuture { fut_one: FutOne, fut_two: FutTwo, state: State, } // `async` 语句块可能处于的状态 enum State { AwaitingFutOne, AwaitingFutTwo, Done, } ``` == 运行时 异步运行时(Runtime)是运行异步任务的机制,标准的 Rust 异步运行时包括以下三个部分: - Executor:管理并调度执行 future,没有官方标准。 - Reactor:等待外设执行任务完成并唤醒对应 future,没有官方标准。 - Weaker:用于联系 Executor 和 Reactor 的结构,#link("https://docs.rs/async-std/latest/async_std/")[async_std] 为其广泛认可的标准。 形成的文档:#link("https://ldq3.github.io/2024/05/24/Rust%E4%B8%AD%E7%9A%84%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/#more")[Rust 中的异步编程] ;项目仓库:#link("https://github.com/ldq3/Rust_async")[Rust_async](重构了 #link("https://github.com/ibraheemdev/too-many-web-servers/")[too-many-web-servers] 的异步运行时部分)。 = 基于 Rust 异步机制的驱动 == 嵌入式 Rust 与驱动开发紧密相关的是嵌入式领域。 嵌入式 Rust 的大部分资料基于 ARM 和 RISC-V 架构的芯片,其中 STM32 最常见。 学习资料:#link("https://docs.rust-embedded.org/")[Embedded Rust documentation]。 学习过程中,我主要使用的开发板是官方 QEMU 支持模拟的 #link("https://www.qemu.org/docs/master/system/arm/stm32.html")[STM32VLDISCOVERY] 和一块自己购买的 #link("http://www.st.com/en/evaluation-tools/stm32f3discovery.html")[STM32F3DISCOVERY]。 #pagebreak() #figure( image("/resource/image/peripheral_access_levels.png", width: 70%), caption: [ Abstraction levels of Rust embedded crate(STM32F3 for example). ], ) <glaciers> #pagebreak() 直接操作 MCU 访问外设的方式是向特定的存储器地址写入数据,这些存储器地址被映射为相应的寄存器。在其之上,很多 crate 抽象出来更友好的接口: - Micro-architecture Crate:这类 crate 给出了处理对应的处理器核心的常用例程,以及所有使用该特定类型处理器核心的 MCU 共有的任何外围设备。 - PAC:这类 crate 是对特定型号 MCU 所定义的各种寄存器的简单包装。 - HAL Crate:这类 crate 为特定型号 MCU 提供更友好的操作方式。 - Board Crate:这类 crate 为特定开发板提供。 #pagebreak() #table( columns: 2, align: center, header( [*Crate*], [*Example*], ), [Micro-architecture Crate], [#link("https://crates.io/crates/cortex-m")[cortex-m]], [PAC], [#link("https://crates.io/crates/stm32f30x")[stm32f30x]], [HAL Crate], [#link("https://crates.io/crates/embedded-hal")[embedded-hal]], [Board Crate], [#link("https://crates.io/crates/stm32f3-discovery")[stm32f3-discovery]], ) PAC 将直接与寄存器交互,这需要我们遵循每个外围设备在 MCU 的技术参考手册中给出的操作说明,例如 #link("https://www.stmcu.com.cn/Designresource/list/STM32F103/document/reference_manual")[STMCU reference manual]。 常用工具:交叉平台的目标文件处理工具链、烧录工具(Probe-rs 和 OpenOCD)、链接工具(ST-Link、J-Link) 形成文档:#link("https://ldq3.github.io/2024/06/15/%E7%9B%AE%E6%A0%87%E6%96%87%E4%BB%B6%E5%A4%84%E7%90%86%E5%B7%A5%E5%85%B7/")[目标文件处理工具]。 == Embassy Embassy 是基于 Rust 的异步嵌入式应用框架,官方文档:#link("https://embassy.dev/book/")[Embassy Book]。 Embassy 的异步运行时部分,比较特别的地方是有四级执行器,最上层执行器定义于 embassy-executor/src/arch 目录下的对应架构的子模块中: - Executor:控制处理器核心休眠和工作。 下面三层执行器定义于 embassy-executor/src/raw/mod.rs 中: - Executor:对 SyncExecutor 的简单包装。 - SyncExecutor:包含两个重要的队列 run_queue 和 time_queue。在 run_queue 中的是准备就绪的任务。由于定时器触发的中断本身并不包含时间的信息,所以为了处理等待时间的任务,需要额外记录时间信息,于是就有了 time_queue 这样一个队列。该结构实现的 poll 方法为任务调度的核心逻辑。 - TaskStorage:由执行任务得到对应的 future,创建 waker 并将其包装为 context,并调用该 future 的 poll 方法。 #pagebreak() Embassy 异步运行时的 Reactor 和 Waker 似乎并没有什么特别的地方。 wake 方法定义于 embassy-executor/src/raw/waker.rs 中。 #pagebreak() Embassy HAL crate 在项目构建的过程中做了很多重要的工作,详情可以查看相应 Embassy HAL crate 项目根目录下的 build.rs 文件中的内容。 其中,绑定外设和引脚、处理 time-driver-xxxx features、通过使用 #link("https://docs.rs/stm32-metapac/")[`stm32-metapac`] 自动生成 memory.x 文件是我比较关注的内容。 #pagebreak() 尝试基于 Embassy 提供的可以使用 #link("https://github.com/embassy-rs/embassy/tree/main/embassy-time-driver/")[embassy-time-driver] 来实现自定义的时钟驱动,只需为自定义的结构体实现 Driver 特征,并调用 time_driver_impl 宏。 stm32 的通用定时器的主要组成部分是一个由一个可编程预分频器(programmable prescaler,PSC)驱动的一个16位自动重装载的计数器。 在STM32系统中,定时器的时钟源为内部时钟时,其频率一般都比较高,如果我们需要更长时间的定时间隔,那么就需要 PSC 对时钟进行分频处理。使用定时器预分频器和 RCC 时钟控制器的预分频器,脉冲长度和波形周期可以调制从几微秒到几毫秒不等的时间。 #pagebreak() 和其他外设一样,我们在使用这个定时器之前需要初始化它。定时器初始化将涉及两个步骤:启动定时器,然后进行配置。 启动定时器很简单:我们只需将 TIM6EN 位设置为 1。这个位于 RCC 寄存器块的 APB1ENR 寄存器中。 不启用 HAL 的 time-driver- feature,调用自己时钟驱动的 init 方法。 项目仓库:#link("https://github.com/ldq3/stm32f303vct-time-driver")[stm32f303vct-time-driver](物理开发板的时钟驱动) == QEMU QEMU 的问题是缺少很多设备,官方 QEMU stm32 支持和缺失的设备列表在网页 #link("https://www.qemu.org/docs/master/system/arm/stm32.html")[STMicroelectronics STM32 boards] 中给出,其中比较关键的是缺少 RCC 和 RTC。 QEMU 的仿真通常不会试图模拟以兆赫兹频率发送脉冲的实际时钟线(这样做效率极低)。实际上,当虚拟机程序对定时器设备进行编程时,定时器设备的模型会设置一个内部 QEMU 定时器,在适当的持续时间后触发(处理程序随后会拉高中断线或执行其他仿真硬件行为所需的操作)。持续时间是根据虚拟机写入设备寄存器的数值计算的,并附带一个时钟频率的设定值。 QEMU 没有处理可编程时钟分频器或像"时钟树"这样的基础设施(虽然可以添加,但目前还没有人这样做)。定时器设备通常要么使用硬编码的频率,要么可以通过 QOM 属性由创建它们的板或 SoC 模型代码设置频率。(参考链接:#link("https://stackoverflow.com/questions/56853507/timer-supply-to-cpu-in-qemu")[Timer supply to CPU in QEMU]) 由于无法直接使用 Embassy HAL crate,于是参照 embassy-stm32,基于 PAC 和 Micro-architecture Crate 来实现支持官方 qemu stm32 的 HAL。 项目仓库:#link("https://github.com/ldq3/embassy-stm32-qemu/")[embassy-stm32-qemu](To Be Continue……) = 总结 在训练营中学到了很多,在同老师和同学们的分享交流中能更好地看清自己的想法,收获很大。补充了很多软硬件的知识,也锻炼了自己使用工具、整理信息和知识的能力。 But, job is not finished…… 最后,再给大家推荐一下 Typst(官方文档:#link("https://typst.app/docs/")[Typst Documentation],及其中文版:#link("https://typst-doc-cn.github.io/docs/")[Typst 中文文档])。 本文稿使用 Typst 撰写,项目仓库:#link("/summary_of_OS_camp/")[summary_of_OS_camp]。
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/06-features-2/positioning/cursive.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note, cross-link #import "/lib/glossary.typ": tr #show: web-page-template // ### Cursive attachment === #tr[cursive attachment] // One theme of this book so far has been the fact that digital font technology is based on the "Gutenberg model" of connecting rectangular boxes together on a flat baseline, and we have to work around this model to accomodate scripts which don't work in that way. 本书的一个主题是数字字体技术是基于“古腾堡模型”的这一事实。它使用的是一个沿着平坦的基线逐个排列矩形块的模型。我们需要解决的问题就是如何让这个模型能够容纳并不使用上述书写方式的各种#tr[script]。 // Cursive attachment is one way that this is achieved. If a script is to appear connected, with adjacent glyphs visually joining onto each other, there is an easy way to achieve this: just ensure that every single glyph has an entry stroke and an exit stroke in the same place. In a sense, we did this with the "headline" for our Bengali metrics in [chapter 2](concepts.md#Units). Indeed, you will see some script-style fonts implemented in this way: #tr[cursive attachment]是实现这一目标的一种方式。比如有些#tr[scripts]需要相邻的#tr[glyph]互相连接,有一个简单的方式可以搞定这个需求:只要确保每个#tr[glyph]都有位于同一位置的入笔和出笔即可。我们在#cross-link(<pos:bengali-headline>, web-path: "/chapters/02-concepts/dimension/units.typ")[前文]对孟加拉文字体#tr[metrics]中的#tr[headline]的介绍中其实就使用了这一方法。也有其他草书风格的字体会使用这种实现方式: // TODO: 重画这个连笔英语字体的图片 #figure( placement: none, )[#image("connected-1.png")] // But having each glyph have the same entry and exit profile can look unnatural and forced, especially as you have to ensure that the curves don't just have the same *height* but have the same *curvature* at each entry and exit point. (Noto Naskh Arabic somehow manages to make it work.) 但只是让每个#tr[glyph]都有相同位置的出入笔画看上去会有些不自然。而且,为了达成这个目的并不是让出入笔画位置一致就可以的,它们还需要具有相同的曲率。(虽然Noto Naskh Arabic字体还是成功运用了这个方案) // A more natural way to do it, particularly for Nastaliq style fonts, is to tell OpenType where the entry and exit points of your glyph are, and have it sew them together. Consider these three glyphs: two medial lams and an initial gaf. 更自然的方式是告诉OpenType每个#tr[glyph]的出入点,让它可以自动连接这两个点。这种方式对于波斯体来说尤其合适。我们以 `<gaf> <lam> <lam>` (其中`gaf` 为词首,`lam`为词中形式)这三个#tr[glyph]为例来看看。 #figure( placement: none, )[#table( columns: (3fr, 2fr), fill: white, align: bottom, inset: 1pt, [#image("gaf-lam-lam-1.png")], [#image("gaf-lam-lam-2.png")], )] #note[ // > (Outlines from Noto Nastaliq Urdu) #tr[glyph]#tr[outline]来自Noto Nastaliq Urdu字体 ] // As they are, they all sit on the same baseline and don't connect up at all. Now we will add entry and exit anchors in our font editing software, and watch what happens. 左图展示的是这些#tr[outline]在进行连接前的原本的样子,基线位于底部相同位置。右图是我们在字体编辑软件中为它们添加入口和出口锚点之后发生的变化。 // Our flat baseline is no longer flat any more! The shaper has connected the exit anchor of the gaf to the entry anchor of the first lam, and the exit anchor of the first lam to the entry anchor of the second lam. This is cursive attachment. 看上去基线不再是平的了!#tr[shaper]将`gaf`的出锚点和第一个`lam`的入锚点连在了一起,然后第一个`lam`的出锚点又连到了第二个`lam`的入锚点。这种方式就叫做#tr[cursive attachment]。 // Glyphs has done this semi-magically for us, but here is what is going on underneath. Cursive attachment is turned on using the `curs` feature, which is on by default for Arabic script. Inside the `curs` feature are a number of cursive attachment positioning rules, which define where the entry and exit anchors are: Glyphs 软件会半自动的为我们完成这个特性,但我们还是介绍下在内部到底发生了什么。#tr[cursive attachment]经由`curs`特性开启,这个特性在阿拉伯文环境下是默认启用的。`curs`特性中会有一些#tr[cursive attachment]#tr[positioning]规则,用于规定这些出入锚点的位置: ```fea feature curs { lookupflag RightToLeft IgnoreMarks; position cursive lam.medi <anchor 643 386> <anchor -6 180>; position cursive gaf.init <anchor NULL> <anchor 35 180>; } curs; ``` // (The initial forms have a `NULL` entry anchor, and of course final forms will have a `NULL` exit anchor.) The shaper is responsible for overlaying the anchors to make the exit point and its adjacent entry point fit together. In this case, the leftmost glyph (logically, the last character to be entered) is positioned on the baseline; this is the effect of the `lookupflag RightToLeft` statement. Without that, the rightmost glyph (first character) would be positioned on the baseline. (词首形式的#tr[glyph]的入锚点是`NULL`,同理,词尾形式的#tr[glyph]的出锚点也是`NULL`。)#tr[shaper]需要负责让两个相邻锚点正确重叠。在上例中,最后是把最左边的(也就是最后输入的)#tr[glyph]放在#tr[baseline]上,这是由 `lookupflag RightToLeft` 这个#tr[lookup]选项语句控制的。如果不加这个选项,会把最右边的(输入的第一个)#tr[glyph]放在#tr[baseline]上。
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/chapters/9图像分割.typ
typst
#import "../template.typ": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #import fletcher.shapes: house, hexagon, ellipse #import "@preview/pinit:0.1.4": * #import "@preview/cetz:0.2.2" #import "/book.typ": book-page #show: book-page.with(title: "数字图像处理基础 | DIP") = 图像分割 Image Segmentation == 分水岭算法 Watershed Algorithm 将图像的灰度值视为地形的高度,然后将水注入到每个局部最小值的区域,当水位线相遇时,就会形成分割线。 == 霍夫变换 Hough Transform 霍夫变换是一种检测图像中直线、圆等形状的方法。原理是将直线表示为极坐标形式,然后在极坐标空间中找到交点。 #grid( columns: (1fr, 1fr), )[ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot // import cetz.palette: * plot.plot( size: (5, 5), x-min: 0, x-max: 10, y-min: 0, y-max: 120, x-tick-step: none, y-tick-step: none, x-label: $x$, y-label: $y$, axis-style: "left", name: "Hough", { let line(x) = { 10 * x + 20 } plot.add(domain: (0, 10), line) plot.add-anchor("pt1", (2, 40)) plot.add-anchor("pt2", (8, 100)) plot.add-anchor("end", (10, 120)) }, ) circle("Hough.pt1", radius: 2pt, fill: red) content("Hough.pt1", $(x_1,y_1)$, anchor: "west", padding: .1) circle("Hough.pt2", radius: 2pt, fill: red) content("Hough.pt2", $(x_2,y_2)$, anchor: "west", padding: .1) content("Hough.end", $y = a_0 x + b_0$, anchor: "west", padding: .1) })], caption: [$x-y$ 平面], ) ][ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot // import cetz.palette: * plot.plot( size: (5, 5), x-min: 0, x-max: 20, y-min: 0, y-max: 100, x-tick-step: none, y-tick-step: none, x-label: $a$, y-label: $b$, axis-style: "left", name: "Hough", { let line1(a) = { -2 * a + 40 } let line2(a) = { -8 * a + 100 } plot.add(domain: (0, 20), line1) plot.add-anchor("end1", (18, 8)) plot.add(domain: (0, 20), line2) plot.add-anchor("end2", (6, 55)) plot.add-anchor("p", (10, 20)) }, ) circle("Hough.p", radius: 2pt, fill: red) content("Hough.p", $(a_0, b_0)$, anchor: "south-west", padding: .1) content("Hough.end1", $b = -x_1 a + y_1$, anchor: "west", padding: .1) content("Hough.end2", $b = -x_2 a + y_2$, anchor: "west", padding: .1) })], caption: [$a-b$ 平面], ) ] 这样提取出轮廓之后,阈值处理后对每两个点之间进行霍夫变换,就可以得到每条直线的参数。在 $a-b$ 平面上,直线的交点就是直线的参数,找到直线经过最多的点,就是最终的直线。 但 $a-b$ 平面是无界的,所以一般用法向量来表示直线,然后变换到 $theta-rho$ 空间。 #grid( columns: (1fr, 1fr), )[ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot // import cetz.palette: * plot.plot( size: (5, 5), x-min: 0, x-max: 10, y-min: 0, y-max: 10, x-tick-step: none, y-tick-step: none, x-label: $x$, y-label: $y$, axis-style: "left", name: "Hough", { let line(x) = { -x + 10 } let line1(x) = { x } plot.add(domain: (0, 10), line) plot.add-anchor("pt1", (3, 7)) plot.add-anchor("pt2", (7, 3)) plot.add-anchor("end", (9, 1)) plot.add(domain: (0, 5), line1) }, ) circle("Hough.pt1", radius: 2pt, fill: red) content("Hough.pt1", $(x_1,y_1)$, anchor: "west", padding: .1) circle("Hough.pt2", radius: 2pt, fill: red) content("Hough.pt2", $(x_2,y_2)$, anchor: "west", padding: .1) content("Hough.end", $y = a x + b$, anchor: "west", padding: .1) arc((1, 0), start: 0deg, stop: 45deg) content((0.75, 0.5), $theta_0$, anchor: "west", padding: .3) content((1.25, 1.25), $rho_0$, anchor: "south", padding: .1) })], caption: [$x-y$ 平面], ) ][ #figure( [ #set text(size: 9pt) #set par(leading: 1em) #cetz.canvas({ import cetz.draw: * import cetz.plot // import cetz.palette: * plot.plot( size: (5, 5), x-min: 0, x-max: calc.pi, y-min: 0, y-max: 10, x-tick-step: calc.pi/4, y-tick-step: none, x-label: $theta$, y-label: $rho$, axis-style: "left", name: "Hough", { let line1(theta) = { 3 * calc.cos(theta) + 7 * calc.sin(theta) } let line2(theta) = { 7 * calc.cos(theta) + 3 * calc.sin(theta) } plot.add(domain: (0, calc.pi), line1) plot.add-anchor("end1", (2.2, 4)) plot.add(domain: (0, calc.pi), line2) plot.add-anchor("end2", (1.8, 2)) plot.add-anchor("p", (0.78, 7.05)) }, ) circle("Hough.p", radius: 2pt, fill: red) content("Hough.p", $(theta_0, rho_0)$, anchor: "south", padding: .4) content("Hough.end1", $rho = x cos(theta) + y sin(theta)$, anchor: "west", padding: .1) content("Hough.end2", $rho = x cos(theta) - y sin(theta)$, anchor: "west", padding: .1) })], caption: [$theta-rho$ 平面], ) ] 这样就可以只观察一个周期内的图像,还是找交点。如果要用于边缘连接,那就可以在找到的直线上逐个像素进行判断,如果距离小于某个阈值,就给它们连线。
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/minitoc/0.1.0/lib.typ
typst
Apache License 2.0
#let minitoc( title: none, target: heading.where(outlined: true), depth: none, indent: none, fill: repeat([.]) ) = { if depth == none { depth = calc.inf } locate(loc => { let pre = query(selector(heading.where(outlined: true)).before(loc), loc) if pre == () { return outline(target: target, title: title, fill: fill, indent: indent) } let after = pre.last() let min_level = after.level let max_level = min_level + depth let elems = query(selector(heading.where(outlined: true)).after(loc), loc) let last_elem = none for e in elems { if e.level <= min_level { break } last_elem = e } if last_elem == none { outline(target: selector(target).after(after.location())) } else { outline( target: selector(target) .after(after.location()) .before(last_elem.location()), fill: fill, title: title, indent: indent ) } }) }
https://github.com/sinchang/typst-react
https://raw.githubusercontent.com/sinchang/typst-react/master/README.md
markdown
# typst-react ## Allow `fonts` permission ![image](https://user-images.githubusercontent.com/3297859/236397796-4adac95d-2621-434c-8816-6b14db30def8.png) ![image](https://user-images.githubusercontent.com/3297859/236398002-3acae40d-3650-4e13-b161-ea94f5f35d99.png)
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/modules/chap1.typ
typst
// SKIP #let name = "Klaus" == Chapter 1 #name stood in a field of wheat.
https://github.com/m4cey/mace-typst
https://raw.githubusercontent.com/m4cey/mace-typst/main/templates/exercices.typ
typst
#let template(doc) = [ #set page( paper: "a4", margin: (x: 1.8cm, y: 1.5cm), numbering: "1" ) #set text( font: "Noto Sans", size: 12pt, ) #show math.equation: set text( font: "Noto Sans Math", size: 1em, ) #set par( justify:true, leading: 0.6em, ) #show heading: it => [ #set align(start) #counter(heading).display() #smallcaps(it.body) ] #set heading(numbering: "I.1.1.") // hide numbering of the first n levels /* #let n = 1 #set heading(numbering: (..nums) => nums.pos().filter(level => level > n).map(str).join(".")) // hide numbering on the first heading #show heading.where(level: 1): it => [ #set align(start) #smallcaps(it.body) ] // layout heading numbers in front #show outline.entry: it => { link(it.element.location(), { it.element.body + " " if (it.level > 1) { numbering("1.1", ..counter(heading).at(it.element.location())) } box(width:1fr,it.fill) it.page }) } */ #show outline.entry.where( level: 1 ): it => { v(12pt, weak: false) strong(it) } #doc ] #let title(body) = { align(center + horizon)[ #text(size: 2em)[#strong(delta: 1000,body)] ] line(start: (0%,0%), length: 100%) } #let answer(hide: false, body) = [ #{ //is content body empty? let fields = body.fields() let hascontent = fields.at("children", default: false) if type(hascontent) == "boolean" { hascontent = fields.at("text", default: false) hascontent = type(hascontent) == "string" } else { hascontent = hascontent.len() > 1 } if not hide and hascontent [ #align(center)[#pad(x: 1em, bottom:1em)[#rect(inset: 0.8em)[ #align(left)[#body] ]]]] } ]
https://github.com/OCamlPro/ppaqse-lang
https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/présentation/OCamlPro_PPAQSE-COTS_présentation.typ
typst
#import "../base.typ": * #import "../étude/links.typ": * #show: presentation #title-slide( title: [ Écosystèmes COTS de développement et de vérification des logiciels critiques et temps réel ], subtitle: "", authors: [<NAME> (julien.blond\@ocaml.pro)], ) #slide[ = OCamlPro - PME française créée en 2011 - ADN recherche et liens étroits avec la recherche académique. - OCaml : core team, opam & optimisations - R&D langages (DSL) & dette technique (Cobol) - Méthodes formelles (Alt-Ergo) - Certification Sécurité (CC EAL6+) - Formations (OCaml, Rust, Coq) Jane street, Inria, DGFiP, Samsung, Mitsubishi, Thales, CEA, Adacore, TrustInSoft ] #slide[ = Objectif Tour d'horizon des langages de programmation dans la sûreté: - C - C++ - Ada - Scade - OCaml - Rust Donner suffisamment d'informations pour faire un choix éclairé ] #slide[ = C - Créé en 1972 par <NAME> - Programmation système (Unix) - Langage bas niveau - Standardisé : C89, C99, C11, C18, C23 (draft)... - ... mais une sémantique indéterministe. ] #slide[ = C++ - Créé en 1979 par <NAME> - C++ = C + classes + templates + exceptions + ... - Mêmes usages que le C mais censé être plus efficace/productif - Standardisé : C++98, C++03, C++11, C++14, C++17, C++20, C++23... - ... mais sémantique indéterministe. ] #slide[ = Ada - Initié par le DoD dans les années 1970 - Langage de programmation de haut niveau pour la sûreté - Standardisé : Ada83, Ada95, Ada2005, Ada2012, Ada2023 - Sémantique claire ] #slide[ = Scade - Créé dans les années 1990 par VERIMAG/VERILOG - Repris par Esterel Technologies/Ansys - Langage de programmation graphique basé sur Lustre - Propriétaire - Sémantique déterministe ] #slide[ = OCaml - Créé en 1996 par l'INRIA - Lignée des langages ML - Lien étroit avec Coq - Centré sur l'algorithmique et la simplicité - Sémantique mathématique issue du $lambda$-calcul ] #slide[ = Rust - Créé dans les années 2000 chez Mozilla - Première version en 2015 - C++ amélioré - Qualifications/standarisation en cours ] #slide[ = Paradigmes #align( center, table( columns: (auto, auto, auto, auto, auto), align: left, align(center)[*Langage*], align(center)[*Impératif*], align(center)[*Fonctionnel*], align(center)[*Objet*], align(center)[*Déclaratif*], [C], [✓], [\~], [], [], [C++], [✓], [\~], [✓], [], [Ada], [✓], [], [\~], [], [Scade], [], [], [], [_dataflow_, graphique], [OCaml], [✓], [✓], [✓], [], [Rust], [✓], [✓], [\~], [], ) ) ] #slide[ = Mécanismes de protection intrinsèques #align( center, table( columns: (auto, auto, auto, auto, auto), align: left, align(center)[*Langage*], align(center)[*Typage*], align(center)[*Pointeurs*], align(center)[*Mémoire*], align(center)[*Contrôles*], [C], [😕], [😨], [😨], [😕], [C++], [😕], [😨], [😨], [😐], [Ada], [😊], [😌], [😨], [😊], [Scade], [😊], [😊], [😊], [😊], [OCaml], [😃], [😊], [😃], [😊], [Rust], [😊], [😕], [😌], [😊], ) ) ] #slide[ = Compilateurs #align( center, table( columns: (auto, auto), align: (left, left), align(center)[*Langage*], align(center)[*Compilateurs*], [C], [GCC, Clang/LLVM, icx, MSVC, AOCC, sdcc, CompCert, ...], [C++], [G++, Clang/LLVM, icx, MSVC, AOCC, C++ Builder, ...], [Ada], [GNAT (GCC), GNAT Pro/LLVM, GreenHills Ada, PTC, Janus/Ada], [Scade], [Scade Suite], [OCaml], [OCaml (ocamlc, ocamlopt)], [Rust], [rustc] ) ) ] #slide[ = Interfaçage #align( center, table( columns: (auto, auto), align: (left, left, left, left), align(center)[*Langage source*], align(center)[*Langage(s) cibles(s)*], [C], [ASM], [C++], [C, ASM], [Ada], [C], [Scade], [C, Ada (out)], [OCaml], [C], [Rust], [C] ) ) ] #slide[ = Adhérence #align( center, table( columns: (auto, auto), align: (left, left), align(center)[*Langage*], align(center)[*Adhérence*], [C], [], [C++], [], [Ada], [], [Scade], [], [OCaml], [POSIX (natif), VM (objet)], [Rust], [] ) ) ] #slide[ = Gestionnaires de paquets #align( center, table( columns: (auto, auto), align: (left, left), align(center)[*Langage*], align(center)[*Gestionnaire(s) de paquet(s)*], [C], [Clib, Conan, vcpkg], [C++], [Buckaroo, Conan, vcpkg], [Ada], [Alire], [Scade], [], [OCaml], [opam], [Rust], [Cargo] ) ) - Agnotisques: Nix, 0install, opam, ... - Systèmes embarqué : Yocto, Buildroot, ... ] #slide[ = Communauté #[ #set text(size: 18pt) #align( center, table( columns: (auto, auto, auto, auto, auto), align: (left, left), align(center)[*Langage*], align(center)[*Fondation(s)/Association(s)*], align(center)[*Entreprise(s)*], align(center)[*Recherche*], align(center)[*Volume*], [C], [FSF], [+++], [], [+++], [C++], [FSF], [+++], [], [+++], [Ada], [Ada Europe, Ada Resource Association, Ada France], [Adacore, +], [], [+], [Scade], [], [Ansys], [Verimag], [+], [OCaml], [OSF], [Jane Street, OCamlPro, Tarides, +], [INRIA], [+], [Rust], [RF, Rust France], [AWS, Mozilla, +], [], [++], ) ) ] ] #slide[ = Debugueurs #{ set text(size: 16pt) figure( table( columns: (auto, auto), align(center)[*Langage*], align(center)[*Debugueur(s)*], [C], [#gdb, #lldb, #totalview, #undo, #valgrind, #vsd, #windbg, #rr, #linaro], [C++], [#gdb, #lldb, ...], [Ada], [#gdb, #lldb], [Scade], [Scade Suite], [OCaml], [ocamldebug (objet), #gdb, #lldb, ...], [Rust], [#gdb, #lldb, #windbg] ) ) } ] #slide[ = Tests #align( center, table( columns: (auto, auto), [C], [#cantata, #parasoft, #TPT, #vectorcast, ...], [C++], [#cantata, #parasoft, #TPT, #vectorcast, #testwell_ctc, #boost, #gtest, ...], [Ada], [#aunit, #adatest95, #avhen, #ldra, #vectorcastAda, #rtrt], [Scade], [Scade Suite], [OCaml], [#ounit, #alcotest, #qcheck, #crowbar, PPX, Cram, ...], [Rust], [_builtin_, quickcheck, proptest, mockall, ...] ), ) ] #slide[ = Parsing #align( center, table( columns: (auto, auto), [C], [Flex/Bison, ANTLR, ...], [C++], [Flex/Bison, ANTLR, ...], [Ada], [AFlex/AYacc], [Scade], [], [OCaml], [sedlex, ulex, Menhir, ocamllex, ocamlyacc, angstrom, dypgen, ...], [Rust], [LALRPOP, Hime, Syntax] ) ) ] #slide[ = Méta-programmation (C) - Le préprocesseur permet de faire précalculer des expressions simples par le compilateur (souvent inutile) - Il existe des _tricks_ d'expansion récursive bornée (à éviter) ```c /* #define sum(n) ((n * (n + 1)) / 2) */ inline int sum(int n) { return (n * (n + 1)) / 2; } int main() { return sum(10); } ``` ```asm 0x0000000000001040 <main+0>: endbr64 0x0000000000001044 <main+4>: mov $0x37,%eax 0x0000000000001049 <main+9>: retq ``` ] #slide[ = Méta-programmation (C++) Les _templates_ sont Turing-complets et permettent de calculer virtuellement n'importe quoi qui ne dépende pas d'une IO. ```cpp template<unsigned int N> struct Fact { enum {Value = N * Fact<N - 1>::Value}; }; template<> struct Fact<0> { enum {Value = 1}; }; unsigned int x = Fact<4>::Value; ``` ] #slide[ = Méta-programmation (Ada & Scade) Pas de support de méta-programmation. ] #slide[ = Méta-programmation (OCaml) Les PPX permettent de transformer le code source avant la compilation ```ocaml let main () = [%init 42]; let v = some_calculus () in [%do_something v] ``` ] #slide[ = Méta-programmation (Rust) Les macros permettent de transformer le code source avant la compilation #[ #set text(size: 18pt) ```rust macro_rules! vec { ($($x:expr),*) => { { let mut temp_vec = Vec::new(); $(temp_vec.push($x);)* temp_vec } }; } ``` ```rust let v = vec![1, 2, 3]; ``` ] ] #slide[ = Dérivation (C) Les macros permettent une forme archaïque de dérivation ```c #define COULEUR X(ROUGE, 0xFF0000) X(VERT, 0x00FF00) X(BLEU, 0x0000FF) #define X(c, v) c = v, typedef enum { COULEUR } couleur_t; #undef X ``` ] #slide[ = Dérivation (C++) On peut avoir une forme de dérivation via les _templates_: ```cpp template <typename T> struct is_pointer { static const bool value = false; }; template <typename T> struct is_pointer<T*> { static const bool value = true; }; ``` ] #slide[ = Dérivation (Ada & Scade) Pas de support de dérivation. ] #slide[ = Dérivation (OCaml) Les PPX permettent de transformer le code source avant la compilation ```ocaml type couleur = Rouge | Vert | Bleu | RGB of int * int * int [@@deriving show] (* val show : couleur -> string val pp_couleur : Format.formatter -> couleur -> unit *) ``` ] #slide[ = Dérivation (Rust) Les macros permettent de transformer le code source avant la compilation ```rust #[derive(Debug)] struct Point { x: i32, y: i32, } ``` ] #slide[ = Runtime Errors Analyseurs sans faux négatifs: #align( center, table( columns: (auto, auto), align: left, align(center)[*Langage*], align(center)[*Analyseurs*], [C], [#astree, #eclair, #framac, #polyspace, #tisanalyser], [C++], [#astree (C++17), #framac (?)], [Ada], [#codepeer, #polyspace, #spark], [Scade], [Scade suite ?, + outils C/Ada sur le code généré], [OCaml], [], [Rust], [(Mirai)], ) ) ] #slide[ = Formalisation Il y a globalement deux approches : - Par transpilation de ou vers Coq (ou autre) - Langage $=>$ Coq $=>$ Preuves (Hoare, WP) - Coq + Preuves $=>$ Langage - Par annotation et preuve (semi) automatiques: #[ #set text(size: 16pt) ```c /*@ requires \valid(a) && \valid(b); @ ensures A: *a == \old(*b) ; @ ensures B: *b == \old(*a) ; @ assigns *a,*b ; @*/ void swap(int *a,int *b); ``` ] ] #slide[ = WCET Le WCET par analyse statique fonctionne par analyse du binaire avec les contraintes de l'architecture cible. #align( center, table( columns: (auto, auto), align: left, align(center)[*Langage*], align(center)[*Analyseurs*], [C], [#chronos, #bound-T, #aiT, #sweet, #otawa, #rapidtime], [C++], [outils C], [Ada], [#rapidtime, #aiT], [Scade], [#aiT], [OCaml], [outils C], [Rust], [outils C], ) ) ] #slide[ = Pile L'analyse statique de la pile fonctionne également par analyse du binaire: #align( center, table( columns: (auto, auto), align: left, align(center)[*Langage*], align(center)[*Analyseurs*], [C], [#stackanalyser, #armlink, #gcc], [C++], [outils du C], [Ada], [#gnatstack], [Scade], [#stackanalyser], [OCaml], [outils du C (natif)], [Rust], [outils du C], ) ) ] #slide[ = Qualité numérique #align( center, table( columns: (auto, auto, auto), align: left, align(center)[*Langage*], align(center)[*Analyseurs statiques*], align(center)[*Calcul dynamique*], [C], [#fluctuat, #astree, #polyspace, #gappa (+ annotations)], [#cadna, #mpfr, #gmp], [C++], [#astree, #polyspace], [#cadna, #mpfr, #boost, #xsc], [Ada], [_builtin_, #polyspace, #spark (+annotations)], [#mpfr, #gmp], [Scade], [], [Scade library ?], [OCaml], [], [#mpfr, #gmp], [Rust], [], [biblothèques, #mpfr, #gmp], ) ) ] #slide[ = Assurances #align( center, table( columns: (auto, auto, auto), align: left, align(center)[*Langage*], align(center)[*Intrinsèque*], align(center)[*Externe*], [C], [😨], [😊], [C++], [😕], [😕], [Ada], [😊], [😊], [Scade], [😊], [😊], [OCaml], [😊], [😨], [Rust], [😊], [😕], ) ) ] #slide[ = Assurances / Coût (Sécurité) #align( center, table( columns: (auto, auto, auto, auto), align: left, align(center)[*Langage*], align(center)[*Intrinsèque*], align(center)[*Externe*], align(center)[*Coût*], [C], [😨], [😊], [😨], [C++], [😕], [😕], [😕], [Ada], [😊], [😊], [😕], [Scade], [😊], [😊], [😌], [OCaml], [😊], [😨], [😊], [Rust], [😊], [😕], [😕], ) ) ] #slide[ = Critique #align( center, table( columns: (auto, auto), align: left, align(center)[*Langage*], align(center)[*Domaines critiques*], [C], [Tous], [C++], [Tous], [Ada], [Spatial, Aéronautique, Ferroviaire ], [Scade], [Aéronautique, Ferroviaire, Nucléaire], [OCaml], [Outillage (Astree, KCG, ...)], [Rust], [], ) ) ] #slide[ = Conclusion - Quand on peut, privilégier les langages métiers - OCaml est souvent un bon choix pour l'outillage - Rust est à la mode mais encore jeune pour être recommandé sans réserve - Innover pour s'adapter aux nouveaux besoins/contraintes ] #slide[ #v(3cm) #align(center)[*Questions ?*] ]
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Sections/Section2.typ
typst
#set text( font: "New Computer Modern", size: 11pt ) #set par( justify: true, leading: 0.68em, ) #set page( header: align(right)[ <NAME> ] ) #set heading(numbering: "1.a") = Question Should we as a society adhered to a specific type of ethical frameworks or should we mix different frameworks based on context? And if we choose to mix, how can we know how to balance different frameworks? = The Politics of Artifacts An example of a technological artifact that has politics is any *social media website*, such as twitter. Lots of political discourse and political discussion happens on these large social media websites and many peoples different viewpoints are shifted or formed based on social media. -_The politics is unintentional, since these websites weren't created for the main purpose of political but rather just for different people to connect_ -The designers likely played no role at all in the actual politics since the app wasn't developed for that. I think the consequences are the same because it is just leads to shifted viewpoints. = Technologies you wouldn't help build? Personally I don't think I could help build software for defense companies that are known for their weapons harming lots of people. I think there is a lot of politics behind that and I would rather keep my conscious clean. I also personally think its okay to just do work for money, and it doesn't need to necessarily be particularly good or bad. = Utilitarianism == Act Utilitarianism This is when you approach each decision by weighing our the pros and cons of if something produces a net overall good. This framework of thinking does not take into account the means, but rather just the outcome. *Morally relevant beings* to me means any individual who's feelings/emotions are important to calculating the overall happiness. I think this includes humans and most animals who can think at a comprehensive level, which would be obviously common pet animals but also other types of animals such as pets. *Pros:* - Focuses on happiness - Its practical - Easy to comprehend *Cons:* - Takes a lot of energy to do this for every moral decision - Ignores an innate sense of duty sometimes(?) == Rule Utilitarianism The idea that we should all adhere to certain moral rules and if everyone follows those rules, it would lead to maximal happiness *Pros:* - Not every moral decision requires utilitarianism calculus - Reduces moral bias *Cons:* - Focuses use on a single scale for evaluating completely different kinds of consequences - Ignores problem of unjust distribution of good consequences - Wrong people can receive this :good" as a result = Kantianism Kantianism focuses on the nature of actions rather than the consequences of those actions. *Formulation 1:* Act only in ways where you wouldn't want your actions to become universal law for all. Can everyone, in principle do this without any issue? *Formation 2:* Act in a way such that you treat humanity not just as a means of an end but as individual people that you respect. This emphasizes dignity and respecting others for who they are. I think that the first formulation about universal law is much more useful because it is a lot easier to apply directly and helps you make smarter decisions. I feel like the biggest *weakness* in Kant's theories is that it doesn't account for the consequences of actions. I understand that the motivation is important, but the consequences are often just as important. For example, _why do we give consequences to people who accidentally run over/hit others with their car_? I think its important we focus on a balance between motivations/the nature of actions while also paying heed to their results. = Mailing Job I would personally take the job either way even if I passionately disagreed with them. I think at the end of the day if I don't write the software someone else will, so I might as well. However, there is one thing I would want to know: the context of what the organization is involved with. If it is involved with something that hurts other people, etc then I could not take the job regardless for my consciousness. I think if I was running the company I would have an obligation to try to stay unbiased and providing services to anyone who wants to use them, provided they aren't abusing them. I would also have to provide tech support if they purchased my product.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-recursive-03.typ
typst
Other
// Test multi-recursion with nested lists. #set rect(inset: 3pt) #show list: rect.with(stroke: blue) #show list: rect.with(stroke: red) #show list: block - List - Nested - List - Recursive!
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/comment-in-string.typ
typst
Apache License 2.0
#link("https://myriad-dreamin.github.io/typst.ts/cookery/guide/compiler/ts-cli.html")[Form1]: Render to SVG and then embed it as a high-quality vectored image directly.
https://github.com/francescoo22/LCD-exercises
https://raw.githubusercontent.com/francescoo22/LCD-exercises/main/src/common.typ
typst
#import "../typst-prooftree/prooftree.typ": * #let Fix = "Fix" #let fix = "fix" #let Proc = "Proc" #let Act = "Act" #let Even = "Even" #let compq = $"comp"_Q$ #let CCS = "CCS" #let fi = "if" #let then = "then" #let def = $=^"def"$ #let ended = $arrow.not$ #let tab = h(2em) #let seq = "seq" #let wnu = $without {nu}$ #let wnup = $without {nu'}$ #let wL = $without L$ #let cr = $space cal(R) space$ #let atrans = $->^alpha$ #let awtrans = $=>^alpha$ #let ttrans = $->^tau$ #let ntrans = $->^nu$ #let hml(it) = $bracket.l.double it bracket.r.double$ #let hmlr(it) = $bracket.l.double it bracket.r.double_eta$ #let comp(it) = $bracket.l.double it bracket.r.double_"comp"$ #let ang(it) = $angle.l it angle.r$ #let sat(left, right) = $left tack.r.double right$
https://github.com/rickysixx/unimore-informatica
https://raw.githubusercontent.com/rickysixx/unimore-informatica/main/protocolli-e-architetture-di-rete/riassunto_par.typ
typst
#set par(leading: 0.55em, justify: true, linebreaks: "optimized") #set text(font: "New Computer Modern", lang: "en") #set heading(numbering: "1. ") #show par: set block(spacing: 1em) #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 heading.where(level: 1): it => { pagebreak(weak: true) it } #outline( indent: auto ) = Introduzione alle reti == Definizione di rete Una rete può essere definita come: - due o più #strong[nodi] connessi tramite #strong[collegamenti]; - due o più #strong[reti] connesse tramite #strong[nodi] (definizione ricorsiva) Componenti fondamentali di una rete: - nodi (es. #strong[host], #strong[switch], #strong[router], ecc.); - collegamenti (#strong[link]) == Protocolli #table( columns: (1fr), [ #strong[Definizione]: protocollo Insieme di regole seguite da entità che intendono comunicare tra loro. ] ) Elementi di un protocollo: - #strong[sintassi]: insieme e struttura dei comandi, formato dei messaggi, ecc.; - #strong[semantica]: #strong[significato] dei comandi/azioni/risposte; - #strong[temporizzazione]: specifica delle possibili sequenze temporali di emissione dei comandi; - #strong[schema di naming]: per dare un #strong[nome] ai vari interlocutori Un protocollo può avere diversi obiettivi: - prestazioni (massima velocità possibile); - affidabilità (resistenza ai guasti); - sicurezza L'obiettivo di un protocollo non è quello di far comunicare due host, ma quello di far comunicare due #strong[applicazioni] su host diversi. === Stack di protocolli I protocolli sono organizzati all'interno di uno #strong[stack]. Ogni livello dello stack risolve un problema specifico e può offrire diversi protocolli alternativi. Ogni protocollo possiede due #strong[interfacce interne] ed un'#strong[interfaccia esterna]. - le interfacce interne servono per comunicare con i protocolli di livello superiore ed inferiore #strong[sullo stesso nodo]; - l'interfaccia esterna serve per comunicare con il protocollo allo stesso livello #strong[su un altro nodo] #figure([#image("images/ff359bd4a8f2c15bc8c7e2a739ddc365.png")], caption: [ Interfacce di un protocollo ] ) Dal punto di vista logico, la comunicazione avviene tra protocolli che si trovano allo stesso livello. #figure([#image("images/7cf4c83a44c667b830f3786f9cbaa4e3.png")], caption: [ Comunicazione tra protocolli (livello logico) ] ) In realtà, la comunicazione avviene allo stesso livello solo per il livello più basso: #figure([#image("images/54b4663cfbc31aeb67881d98199ce4c9.png")], caption: [ Comunicazione tra protocolli (reale) ] ) == Multiplexing e demultiplexing #table( columns: (1fr), [#strong[Multiplexing]: tanti nodi inviano messaggi sullo stesso canale #strong[condiviso]], [#strong[Demultiplexing]: i messaggi inviati nello stesso canale condiviso vengono \"smistati\" in modo da arrivare solo all'effettivo destinatario.] ) #figure( image("images/3aa93a38888db569feed7cac46c242d9.png", width: 40%), caption: [ Multiplexing e demultiplexing ] ) Multiplexing e demultiplexing sono fondamentali per ottimizzare l'utilizzo delle risorse. == Modalità di trasferimento dei dati === Circuit switching Paradigma di comunicazione #strong[orientato alla connessione]: - si instaura una connessione prima di inviare le informazioni; - si chiude la connessione una volta terminata la comunicazione È alla base dei protocolli analogici (es. telefonate). #strong[Pro]: si riesce a sapere in anticipo se ci sono risorse sufficienti per comunicare (lo si capisce nel momento in cui si crea la connessione). #strong[Contro]: non è possibile modulare l'utilizzo delle risorse in base all'uso del circuito. Il canale occupa una quantità #strong[costante] di risorse. Nel circuit switching il multiplexing viene implementato dividendo la banda disponibile in più canali (#strong[time division multiplexing]). === Packet switching Paradigma di comunicazione #strong[orientato ai pacchetti], alla base del funzionamento di Internet. L'unità base della comunicazione è il #strong[pacchetto]. Ogni pacchetto utilizza #strong[tutta] la capacità trasmissiva di un link. L'accesso al mezzo non è temporizzato a priori: tutti i nodi possono comunicare quando gli pare. Nel packet switching si ha un #strong[multiplexing probabilistico]: non c'è l'effettiva occupazione di un canale, ma l'uso delle risorse dipende da quanti dati vengono inviati. Problemi rilevanti nel packet switching: - #strong[collisioni] nelle reti locali (due nodi all'interno della stessa rete locale inviano un pacchetto sullo stesso link nello stesso momento); - #strong[congestioni] nelle reti (e.g. nei buffer dei router). Collisioni e congestioni intaccano l'#strong[affidabilità] della comunicazione, perché possono provocare #strong[perdite di pacchetti]. I protocolli di rete devono essere in grado di rilevare e affrontare questi problemi. === Circuit switching vs packet switching #table( columns: (1fr), [ *Bandwidth*: quantità di dati trasmessa per unità di tempo. Si misura in bit per secondo. ] ) Esempio: - link a 1 Mbps; - ciascun utente richiede 0.1 Mbps quando trasmette ed è attivo il 10% del tempo Con circuit switching: $ "nr. utenti massimo" = frac("1 Mbps totali", "0.1 Mbps per utente") = "10 utenti" $ Con packet switching invece si possono supportare fino a 35 utenti con un rischio di collisione bassissimo. Se i protocolli sono in grado di gestire collisioni e congestioni, una piccola probabilità che questi eventi si verifichino non dà problemi. == Implementazione dello stack per Internet Internet si basa su uno #strong[stack di protocolli] e sul paradigma #strong[packet switching]. Ogni pacchetto è costituito da #strong[header] e #strong[payload]: - l'header (o PCI \= Protocol Control Information) contiene #strong[metadati] necessari per il funzionamento del protocollo; - il payload (o SDU \= Service Data Unit) contiene i dati effettivi $ upright("PCI") plus upright("SDU") eq upright("PDU (Protocol Data Unit)") $ La comunicazione avviene in questo modo: + il mittente crea il pacchetto al livello più alto dello stack; + il pacchetto attraversa #underline[dall'alto verso il basso] lo stack del mittente. Ad ogni livello dello stack viene creato un nuovo pacchetto che #strong[incapsula] quello del livello superiore; + il pacchetto raggiunge il mezzo di comunicazione fisico e viene inviato al destinatario; + il pacchetto attraversa #underline[dal basso verso l'alto] tutto lo stack del destinatario. Ad ogni livello il pacchetto viene \"spacchettato\": viene letto l'header relativo a quel livello e il contenuto viene inoltrato al livello superiore; + il pacchetto raggiunge il livello più alto dello stack del nodo destinazione. A questo punto viene letto il payload contenuto nel pacchetto #figure([ #image("images/83de2cbf0e72c98ea4f942f14bc377f3.png") #image("images/a947a4376e73e9a221fe470f03a1889e.png") #image("images/486e6f9bc08c4e987d776e9ba2af7c8e.png") ], caption: [ Comunicazione in Internet ] ) == Standard per la comunicazione Standard principali - ISO/OSI (de iure) - TCP/IP (de facto) === Modello ISO/OSI Il modello ISO/OSI prevede due tipi di protocolli: - protocolli di comunicazione (network level): permettono la comunicazione tra nodi e nascondono le caratteristiche dei mezzi fisici utilizzati; - protocolli di elaborazione (application level): permettono il controllo delle applicazioni #figure( table( columns: (auto, 1fr), align: (center + horizon, left + horizon), [fisico], [gestisce la trasmissione sul mezzo fisico], [data link], [gestisce l'#strong[accesso al mezzo] e trasforma i segnali elettrici in #strong[frame privi di errori]], [rete], [fornisce le funzionalità per l'#strong[instradamento] dei pacchetti], [trasporto], [effettua il controllo #strong[end-to-end] della sessione di comunicazione e garantisce l'#strong[affidabilità] del trasporto], [sessione], [consente di stabilire delle #strong[sessioni], implementando funzioni di coordinamento, sincronizzazione e mantenimento dello stato], [presentazione], [risolve differenze di formato che possono rappresentarsi tra i diversi nodi della rete (es. conversione ASCII, Unicode, ecc.). Gestisce anche #strong[compressione], #strong[sicurezza] ed #strong[autenticità] dei messaggi attraverso tecniche di crittografia], [applicativo], [fornisce un'interfaccia per i programmi applicativi che utilizzano la rete] ), caption: [Livelli del modello ISO/OSI] ) Il modello ISO/OSI non è riuscito ad affermarsi per questioni di tempismo: le implementazioni funzionanti delle specifiche ISO/OSI sono arrivate molto in ritardo rispetto a quelle di TCP/IP. === Stack TCP/IP Lo stack TCP/IP è composto da soli 4 livelli: #figure( image("images/2538727a8c93afe05b1c41629ca91869.png", height: 20%), caption: [ Stack TCP/IP ] ) + livello fisico: gestisce la trasmissione dei bit sul mezzo fisico; + livello data link: gestisce la comunicazione tra nodi #strong[confinanti]; + livello rete: trasferisce i pacchetti dal mittente al destinatario; + livello trasporto: trasferisce i pacchetti da un host all'altro; + livello applicativo: fornisce un'interfaccia per le applicazioni di rete I livelli 1 e 2 sono strettamente legati tra loro, quindi spesso si considerano come un unico livello chiamato #strong[host-to-network]. Il livello 3 è #strong[privo di connessione]. Ogni pacchetto viene trattato in modo #strong[indipendente] dagli altri. Il livello 3 non garantisce affidabilità, ma adotta un approccio #strong[best effort]. Il livello 4 estende la logica di comunicazione nodo sorgente $arrow.r$ nodo destinazione applicandola ai #strong[processi applicativi] in esecuzione sugli host. La comunicazione è quindi processo sorgente $arrow.r$ processo destinazione. Il livello applicativo utilizza il livello di 4 per realizzare applicazioni di rete. Dispositivi di rete diversi implementano livelli diversi dello stack TCP/IP: - gli host implementano tutti i livelli; - gli switch implementano i primi 2 livelli (salvo eccezioni es. switch di livello 3); - i router implementano i primi 3 livelli = Livello host-to-network (h2n) Problematiche affrontate: - #strong[interconnessione] tra due o più host; - #strong[trasmissione dati] tra host connessi #strong[direttamente]; - #strong[connessione] di un host ad Internet; Esempi di protocolli di livello 2: - Ethernet (su LAN wired); - 802.11a, 802.11b, ecc. (LAN wireless); - Bluetooth (PAN); - GSM e LTE per WAN wireless Protocolli diversi offrono servizi diversi. Non tutti, ad esempio, garantiscono l'#strong[affidabilità] nella consegna del pacchetto. Il livello superiore dev'essere in grado di compiere il suo lavoro in presenza di protocolli diversi a livello h2n. Il livello h2n ragiona con 2 dispositvi di rete connessi #strong[direttamente]. L'unità base della comunicazione a questo livello è il #strong[frame]. La comunicazione a questo livello può essere: - unicast; - multicast (1 mittente ed un gruppo di destinatari); - anycast (1 mittente e almeno 1 destinatario all'interno di un gruppo); - broadcast I collegamenti tra i nodi possono essere: - broadcast/condivisi: molti host connessi allo #strong[stesso canale di comunicazione]. Tipico delle reti LAN. - è necessario un #strong[protocollo di accesso al mezzo] per regolare la comunicazione (chi può trasmettere, quando e per quanto tempo) ed evitare #strong[collisioni]; - punto-punto: 1 trasmittente ad un'estremità ed 1 ricevente all'altra estremità. Tipico collegamento fra un modem d'accesso residenziale e il router dell'ISP (Internet Service Provider). \ I collegamenti punto-punto possono essere a loro volta: - half-duplex: si parla uno alla volta. Quasi sempre inteso anche come #underline[unidirezionalità] (cioè a parlare è solo 1). - full-duplex: entrambi i partecipanti possono comunicare contemporaneamente in modo indipendente l'uno dall'altro. Un protocollo h2n può prevedere più modalità di trasmissione anche se è stato progettato per un particolare mezzo trasmissivo che è intrinsecamente broadcast o unicast. == Tecnologie per interconnessioni La trasmissione dei dati può essere analogica o digitale. Mezzi fisici: - doppino intrecciato: consiste in due fili di rame avvolti a spirale regolare. Utilizzato per più di 100 anni in quanto è il mezzo più economico; - cavo di rete: coppie di cavi isolati elettricamente. Consente la trasmissione digitale; - cavo coassiale: utilizzato per avere trasmissioni elettriche di alta qualità; - fibra ottica: trasporta i dati sottoforma di impulsi di luce. Molto resistente alle interferenze elettromagnetiche, ma anche molto costosa; I mezzi usati per trasmettere possono essere anche wireless. == LAN Una LAN (Local Area Network) è una rete in cui i nodi possono comunicare tra di loro tramite protocollo di livello h2n. Una LAN è limitata da 2 fattori: - #strong[distanza] tra i nodi; - #strong[numero] di nodi Questi limiti sono il motivo per cui Internet non è un'unica grande LAN. Il protocollo h2n è implementato all'interno della #strong[network interface card] (NIC). Tutti i nodi che fanno parte di una LAN devono essere dotati di un'interfaccia di rete. Ethernet è lo standard de-facto per le LAN wired. === Topologie di rete ==== Topologia a bus #figure([#image("images/77950e70c57ad16e17fead51a7c112b3.png")], caption: [ Topologia a bus ] ) Tutti gli host sono collegati tra loro tramite un #strong[singolo cavo] (detto anche #strong[dorsale]). I messaggi vengono inviati a tutti gli host, ma vengono accettati solo dal NIC il cui #strong[MAC address] corrisponde all'indirizzo di destinazione del messaggio. Per evitare rimbalzi del segnale elettrico da un capo all'altro del cavo si applica un #strong[terminatore] a ciascun estremo del cavo. Se un cavo di collegamento viene tagliato, oppure se si rompe uno dei terminatori, i dati rimbalzeranno continuamente nella rete rendendola di fatto inutilizzabile. ==== Topologia ad anello #figure([#image("images/a8ce85842c75ff2d30e5adcde431f4c3.png")], caption: [ Topologia ad anello ] ) Tutti gli host sono collegati ad un unico cavo circolare. Anche in questa topologia il segnale elettrico rimbalza all'infinito. Il terminatore in questo caso è il mittente del messaggio, che si occuperà di riassorbirlo per liberare la rete. ==== Topologia a stella #figure([#image("images/0fe8a25fcd900da9bf9f02d36cdad1a9.png")], caption: [ Topologia a stella ] ) Gli host sono connessi da un dispositivo di rete centrale che ha il compito di inoltrare i messaggi e di evitare i rimbalzi di segnale. La quasi totalità delle reti Ethernet è ad oggi realizzata con questa topologia. Una rete con topologia a stella non ha un #strong[single point of failure] a livello di rete (se si rompe un cavo che va da un host al dispositivo centrale, solo quell'host resterà isolato), ma ce l'ha a livello di dispositivo centrale (se si rompe lui, tutta la rete diventa inutilizzabile). Il dispositivo centrale dev'essere opportunamente dimensionato per gestire il traffico. == Ethernet Protocollo h2n nato a metà degli anni '70. Pensato originariamente per reti con topologia a bus e velocità da 1-10 Mbps. \ Attualmente le reti in cui è utilizzato sono quasi sempre con topologia a stella e supporta anche diverse velocità, in base all'hardware utilizzato. Il supporto di Ethernet a diverse velocità dipende sia dalle interfacce di rete che dal tipo di collegamenti. I cavi Ethernet sono raggruppati in diverse categorie. Ad ogni categoria è associata ad una certa #strong[velocità nominale]. La #strong[velocità effettiva], oltre che dal cavo, dipende anche dal dispositivo di rete centrale. Nelle reti locali #strong[cablate], se progettate con criterio, la velocità effettiva coincide con quella nominale. Ciò invece non avviene quasi mai nelle reti wireless. Ethernet è diventato lo standard de facto per le reti locali per diversi motivi: - pensato per reti semplici e poco costose; - alta flessibilità (si adatta a diverse tipologie e a diversi tipi di collegamento); - si è diffuso talmente tanto e talmente velocemente che i successivi \"concorrenti\" hanno avuto molta difficoltà ad affermarsi; - si integra molto bene con i protocolli IP e TCP Ethernet utilizza un canale #strong[broadcast]: lo stesso canale è utilizzato da molti host. Quando un host trasmette un messaggio, tutte le altre interfacce di rete lo ricevono. Nonostante il canale sia broadcast, Ethernet permette anche comunicazioni #strong[unicast]. In generale, i messaggi broadcast sono riservati a messaggi \"speciali\" (es. ARP). === Indirizzi MAC Ogni interfaccia di rete è identificata univocamente tramite il suo #strong[MAC address]. Si tratta di un indirizzo incorporato nella ROM dell'interfaccia di rete. Il MAC address ha dimensione di #strong[48 bit]. All'interno della stessa rete locale non possono esserci più NIC con lo stesso MAC address. L'indirizzo MAC viene detto #strong[flat], perché ogni bit ha lo stesso peso, indipendentemente dalla sua posizione. I produttori di schede di rete si registrano alla IEEE e ricevono i primi 3 byte dell'indirizzo MAC (che identificano quel produttore). Gli amministratori di sistema possono cambiare il MAC address delle proprie schede di rete. Il MAC address però non viene cambiato nella ROM della NIC, ma solo a livello di sistema operativo. Il protocollo Ethernet non dà nessuna garanzia sul fatto che gli indizzi MAC non siano stati modificati, nè che siano effettivamente univoci all'interno della stessa rete. L'indirizzo MAC `FF:FF:FF:FF:FF:FF` è l'indirizzo di broadcast. Non è possibile configurare questo indirizzo come MAC address della propria interfaccia di rete. Quando un host A vuole comunicare con un host B, entrambi nella stessa rete locale, A inserirà nel frame Ethernet: - il suo MAC address come indirizzo sorgente; - il MAC address di B come indirizzo di destinazione Questo frame viene poi inviato a #strong[tutti] gli host presenti sulla rete, ma sarà scartato da tutte le interfacce di rete il cui MAC address è diverso dal MAC address destinazione riportato sul frame. Il frame NON viene scartato solo se: - il MAC address destinazione riportato è quello di broadacst; - l'interfaccia di rete che riceve il pacchetto è in #strong[modalità promiscua], cioè accetta tutti i pacchetti indipendentemente da MAC address destinazione (es. se è in esecuzione `tcpdump`) ==== Perché serve il MAC address Se le schede di rete utilizzassero indirizzi IP: - non sarebbero in grado di supportare protocolli diversi da IP; - dovrebbero essere ri-configurate tutte le volte che l'host viene spostato, in modo che l'IP sia sempre salvato nella ROM della NIC Allo stesso tempo, i NIC non possono non avere un indirizzo proprio perché altrimenti il sistema operativo verrebbe continuamente interrotto da ogni pacchetto in transito nella LAN, anche se non diretto a loro. === Struttura del frame Ethernet #figure([#image("images/048b2039b2c8ea71f8c7880b8192945c.png")], caption: [ Frame Ethernet ] ) ==== Preamble e SFD - 8 byte Informazioni necessarie per far funzionare correttamente le interfacce di rete. I primi 7 byte sono sempre `10101010`, mentre gli ultimi 2 byte sono identici ma terminano entrambi per `11`. L'interfaccia di rete utilizza il preambolo per #strong[sincronizzarsi]: - i primi 7 byte \"svegliano\" l'interfaccia di rete - gli ultimi due bit `11` indicano alla scheda che la sincronizzazione è terminata e che sta arrivando il contenuto del frame Di solito il preambolo non viene comunicato al sistema operativo, perché si tratta di informazioni che hanno senso solo a livello fisico. Il preambolo, assieme al CRC, serve per il #strong[framing] di Ethernet. Il framing serve per capire dove comincia e dove finisce un singolo frame Ethernet. ==== Indirizzo MAC destinazione e sorgente - 6 byte a testa L'indirizzo del destinatario compare prima rispetto a quello sorgente perché è il primo indirizzo ad essere controllato dalle schede di rete. L'indirizzo sorgente ha poca utilità a livello h2n (Ethernet utilizza un canale broadcast), ma può essere utile a protocolli di livello superiore per capire a chi rispondere. ==== Tipo - 2 byte Serve per implementare il #strong[multiplexing], nel senso che si possono inserire contenuti diversi nel payload ed il destinatario sarà in grado di interpretarli in base al loro tipo. ==== Payload - da 46 a 1.500 byte Informazioni che non vengono gestite dal protocollo Ethernet, ma vengono semplicemente passate ai livelli superiori dello stack. === CRC - controllo di ridondanza ciclico - 4 byte Utilizzato, assieme al preambolo, per il #strong[framing] di Ethernet. Il protocollo Ethernet è l'unico che aggiunge un \"header\" in coda al pacchetto. Il CRC è un'informazione che serve per il #strong[controllo d'integrità] del pacchetto. Il CRC viene calcolato sulla base di #strong[tutte] le informazioni del pacchetto (sia header che dati), ad eccezione del preambolo e del campo CRC stesso. Anche il CRC di solito non viene inviato al sistema operativo. Il CRC è molto facile da calcolare a livello hardware (è la scheda di rete che implementa l'algoritmo). Questo è il motivo per cui si è scelto quest'algoritmo invece di altri (es. hashing) per il controllo dell'integrità. === Dimensioni del frame Ethernet Dimensione minima: 46 byte. Se il frame è più piccolo, esiste una logica di #strong[stuffing] che va ad inserire informazioni fittizie all'interno del frame fino a raggiungere la dimensione minima. Dimensione #strong[massima] (#strong[MTU], Maximum Transfer Unit): 1.500 byte. La dimensione massima è definita dall'interfaccia di rete. L'amministratore di sistema può cambiare l'MTU della propria interfaccia di rete, ma non può cambiare la dimensione minima del frame. Tutte le interfacce di rete collegate alla stessa rete devono avere lo stesso MTU. === Protocollo ARP Problema: come fa il mittente a conoscere il MAC address della scheda di rete con cui vuole comunicare? Risposta: protocollo ARP. L'#strong[Address Resolution Protocol] (ARP) si occupa di individuare il MAC address di un host sulla stessa LAN conoscendo il suo indirizzo IP. Il protocollo ARP utilizza 2 tipi di messaggio: - #strong[richiesta]: contiene l'indirizzo IP del destinatario; - #strong[risposta]: contiene il MAC address corrispondente a quell'indirizzo IP La richiesta è broadcast, mentre la risposta è unicast. Il fatto che Ethernet si basi su ARP, che invia messaggi broadcast, rende Ethernet #strong[poco scalabile]. Per migliorare le prestazioni di ARP, ogni host conserva una #strong[cache ARP]. Ogni entry di questa cache è associata ad un TTL. La cache ARP è gestita dal sistema operativo e può essere manipolata dall'amministratore, ad esempio per inserire entry permanenti (i.e. con TTL infinito). === Protocollo RARP È l'opposto di ARP: da un indirizzo MAC restituisce l'indirizzo IP. Il protocollo RARP è ormai deprecato (in generale è stato utilizzato pochissimo) in favore di #strong[DHCP]. === Protocollo CSMA/CD Legato alla #strong[trasmissione fisica] dei frame Ethernet sulla rete. Serve per #strong[rilevare le collisioni] all'interno di una rete Ethernet. È un #strong[protocollo di accesso al mezzo], cioè regola come i vari host possono accedere ed utilizzare il canale di comunicazione condiviso che Ethernet mette a disposizione. Il protocollo WiFi, a differenza di Ethernet, non deve solo rilevare le collisioni ma deve cercare di #strong[evitarle] proprio. Questo perché le collisioni su rete cablata non sono molto frequenti, e se capitano non hanno conseguenze gravi, mentre nelle reti wireless la situazione è diversa. Quando un host deve trasmettere un frame, l'interfaccia di rete #strong[ascolta] e cerca di capire se c'è qualcun altro che sta trasmettendo in quel momento. Se la rete è libera, allora l'interfaccia provvederà ad inviare il frame #strong[alla massima velocità possibile]. Il tempo durante il quale l'interfaccia di rete \"ascolta\" prima di inviare un frame è detto #strong[Inter Frame Gap] (IFG). Due frame consecutivi vengono sempre distanziati da questo IFG. Anche con questo meccanismo di \"ascolto\" possono esserci comunque delle collisioni, es. a causa della latenza del mezzo fisico. L'interfaccia di rete non \"ascolta\" solo prima di trasmettere il messaggio, ma anche #strong[durante e dopo] averlo trasmesso (concetto di #strong[listen while talking]). Se, dopo aver inviato il messaggio, l'interfaccia di rete non rileva il segnale che si aspetta, allora assume che ci sia stata una collisione. Quando viene rilevata una collisione: - ogni host #strong[smette di trasmettere] e segnala a tutti gli altri che c'è una collisione, inviando un messaggio di #strong[jamming]; - tutti gli host che ricevono un messaggio di jamming si mettono \"in pausa\"; - gli host riprendono a trasmettere, ciascuno con un #strong[ritardo pseudo-casuale], in modo da non ritrovarsi nuovamente a trasmettere i dati tutti nello stesso istante Il ritardo dopo il quale gli host cominciano a ritrasmettere è calcolato tramite un algoritmo di #strong[exponential back-off]: l'#strong[ampiezza dell'intervallo] dal quale si sceglie il ritardo aumenta esponenzialmente all'aumentare del numero di collisioni rilevate. Se dopo 16 tentativi si continua a rilevare una collisione, allora si smette di trasmettere in quanto si suppone che nella rete ci sia un problema più grave. === Dispositivi di rete ==== Hub #strong[Ripetitore di segnale]: ripete il segnale ricevuto in ingresso su una porta su tutte le altre porte. È un dispositivo di livello 1 perché ragiona solo a livello di segnale elettrico. Non fa nessun ragionamento sul frame Ethernet, sui pacchetti, ecc. Gli hub consentono in un certo senso di #strong[aumentare la distanza] tra due host: se un filo host $arrow.l.r$ host è troppo lungo, si può mettere un hub in mezzo ed usare due fili lunghi la metà tra host e hub. Dal punto di vista del traffico, una LAN collegata mediante un hub è equivalente ad una topologia a bus, con l'eccezione che guasti su una singola porta dell'hub non si riflettono sulle altre porte. Come nelle reti con topologia a bus, gli hub ripetono anche le collisioni (si dice che non hanno un #strong[dominio di collisione] differente per ogni porta). In generale, gli hub non sono nemmeno in grado di rilevare le collisioni. ==== Switch Dispositivo di livello 2 che implementa funzionalità di #strong[inoltro selettivo] dei frame: anziché essere dei meri ripetitori come gli hub, gli switch inoltrano il frame solo all'effettivo destinatario. Lo switch utilizza il protocollo CSMA/CD per trasmettere i frame sulla LAN. Gli switch #underline[isolano i domini di collisione], permettendo di avere più traffico gestibile all'interno della stessa rete. Gli switch sono dispositivi #strong[store and forward]: + salvano il frame in entrata; + lo analizzano; + lo inoltrano al destinatario ==== Logica di inoltro selettivo Lo switch è un dispositivo che #strong[autoapprende] la configurazione della rete, #strong[analizzando il traffico]. Lo switch costruisce una #strong[tabella di inoltro] che mappa l'indirizzo MAC con la porta dello switch a cui quel MAC address è collegato. Ogni riga di questa tabella contiene anche un TTL. Se lo switch non riceve più messaggi da un host dopo il relativo TTL, quell'host viene rimosso dalla tabella. La tabella di inoltro viene riempita leggendo il MAC address #strong[sorgente]. Se uno switch riceve un frame Ethernet destinato ad un indirizzo che non è nella tabella, lo switch inoltra quel frame #strong[in broadcast]. Se la tabella è piena è il MAC destinazione non è nella tabella, lo switch inoltrerà il frame in broadcast. Lo switch è un dispositivo #strong[trasparente] agli host a lui collegati: anche se è lo switch ad instradare i pacchetti nella LAN, gli host devono implementare il protocollo ARP. Oltre all'inoltro, lo switch si occupa anche di #strong[filtrare] i pacchetti, in particolare: - elimina i frame che non sono destinati alla stessa LAN; - elimina i frame con CRC non valido ==== Switch cut through Gli switch cut through iniziano a leggere il frame nel momento in cui gli arriva e procedono con l'inoltro appena finiscono di leggere il MAC address di destinazione. Sono utilizzati in reti ad altissime prestazioni. Il fatto di non leggere tutto il frame comporta degli svantaggi, ad esempio non possono fare il controllo del CRC. === Bridge Simile allo switch (funziona con logica di inoltro selettivo), ma può supportare più mezzi fisici, anche diversi tra loro, e protocolli diversi. Un bridge è #strong[trasparente] se mette in comunicazione 2 dispositivi che usano dei protocolli h2n differenti ma che impiegano lo stesso sistema di indirizzamento di livello 2 (esempio Ethernet e WiFi, entrambi utilizzano il MAC address come sistema di indirizzamento). Lo switch può essere visto come un bridge trasparente. Esistono anche bridge #strong[non trasparenti] quando eseguono delle trasformazioni sui frame per \"tradurli\" da un protocollo all'altro. === Interconnessione di LAN Una LAN Ethernet è limitata: - geograficamente: la lunghezza massima del cavo Ethernet (e quindi la distanza massima tra due host) è definita dallo standard 802.3; - nel numero massimo di host collegabili: per il funzionamento di ARP, all'aumentare del numero di nodi le prestazioni della rete calano drasticamente a causa del traffico generato dai messaggi broadcast Connettendo più switch tra loro si possono formare delle #strong[reti gerarchiche] e geograficamente più estese. Per aumentare l'affidabilità della rete, è necessario avere della #strong[ridondanza], ovvero dei #strong[cammini alternativi] tra sorgente e destinazione. #figure([#image("images/a8f566c3fed7b37dbd3099e4d7c16214.png")], caption: [ Collegamenti ridondanti ] ) Problema: se ci sono dei #strong[cicli] all'interno della rete, i messaggi di broadcast vengono inoltrati all'infinito. Ethernet non gestisce la presenza di cicli all'interno della rete. È necessario inserire delle logiche aggiuntive per fare in modo che i percorsi ridondanti siano disabilitati #strong[selettivamente] (cioè vengono attivati solo quando servono). Per fare ciò si usa lo #strong[spanning tree protocol]. Lo spanning tree protocol permette agli switch di rilevare #strong[automaticamente] e #strong[dinamicamente] i link ridondanti. Per funzionare, lo spanning tree protocol dev'essere attivo su tutti gli switch della rete interessata. Quando l'STP viene abilitato, gli switch generano traffico broadcast per rilevare i link ridondanti. I percorsi ridondanti quindi non si possono usare per aumentare le performance, perché l'STP li va a disabilitare. L'STP è in grado di attivare e disattivare i link ridondanti in modo #strong[dinamico]. === VLAN Una LAN normale permette soltanto di raggruppare gli host #strong[fisicamente]. Una VLAN invece permette di raggruppare gli host #strong[logicamente], lasciando invariata la topologia fisica della rete. La comunicazione a livello H2N è impedita tra VLAN diverse. Il traffico broadcast è limitato agli host della stessa VLAN. Creare una nuova VLAN equivale quindi a creare un nuovo dominio di broadcast. Su un #strong[bridge VLAN-aware] possono essere configurate delle #strong[access list] che definiscono quali porte possono inviare/ricevere frame da/verso le varie VLAN. I collegamenti degli host al bridge possono essere di 3 tipi: - #strong[access link]: usato da dispositivi VLAN-unaware. Tagging e untagging vengono eseguiti trasparentemente dal bridge; - #strong[trunk link]: usato da dispositivi VLAN-aware. Il bridge non gestisce più il tagging, è compito degli host; - #strong[hybrid link]: collegamento con il quale possono essere connessi entrambi i tipi di dispositivi Le VLAN sono definite nello standard #strong[IEEE 802.1q]. Questo protocollo non incapsula il frame Ethernet, ma aggiunge ad esso un nuovo campo di 12 bit in cui si trova il VLAN ID. Il campo #strong[type] del frame Ethernet, nel caso di frame 802.1q, viene impostato al valore `0x8100` per distinguerlo da un normale frame Ethernet. == Cablaggio strutturato Insieme di normative che definiscono come organizzare fisicamente i link di una rete (i.e. come mettere i cavi). == Interconnessioni di reti ed accesso ad Internet L'obiettivo di Internet è quello di connettere tra loro reti #strong[indipendenti] ed #strong[eterogenee]. Internet dev'essere gestito in maniera #strong[decentralizzata]. Internet è organizzato in maniera #strong[gerarchica]: + gli utenti finali sono collegati ad ISP #strong[locali]; + gli ISP locali sono collegati ad ISP #strong[regionali] (o nazionali); + gli ISP regionali sono collegati ad ISP #strong[internazionali], detti anche National Backbone Provider (NBP) o National Service Provider (NSP) Gli utenti si collegano agli ISP locali tramite dei #strong[points of presence] (POP) messi a disposizione dall'ISP stesso. Gli ISP locali si connettono agli ISP regionali tramite i #strong[network access points], messi a disposizione dagli ISP regionali. A loro volta, gli ISP regionali noleggiano accesso ai provider intercontinentali. Un #strong[autonomous system] (AS) è un'#strong[entità legale] che gestisce una \"fetta\" di Internet, ovvero un insieme di: - reti; - indirizzi IP; - router Dal punto di vista organizzativo, Internet è un insieme di autonomous system. Gli autonomous system sono entità #strong[indipendenti] l'una dall'altra. Non c'è un AS in particolare che \"prevale\" sugli altri (anzi, tipicamente un AS arriva a controllare non più del 5% di tutta la rete Internet). Un esempio di autonomous system in Italia è il #strong[GARR], un AS che collega tra loro varie università (tra cui Unimore) e centri di ricerca con lo scopo di agevolare la condivisione di informazioni. Ogni ISP locale possiede: - dei nodi #strong[permanentemente connessi] ad Internet; - delle centraline, sparse per tutto il territorio, per il #strong[collegamento dell'ultimo miglio] (dall'ISP all'utente finale) Ogni utenza di un ISP possiede: - un dispositivo di rete (router, moden) che permette di collegarsi #strong[a livello h2n] alla centralina dell'ISP; - uno (o pochi) indirizzi IP #strong[pubblici] per l'accesso ad Internet Il collegamento tra utente ed ISP locale può essere analogico o digitale. Il #strong[modem] è il dispositivo che si occupa di trasformare il segnale da digitale ad analogico e viceversa. Gli accessi residenziali cablati sono prevalentemente di tipo #strong[point-to-point]. Esistono diverse modalità di collegamento tra utente ed ISP: - xDSL (analogico); - fibra ottica (digitale); - tecnologie cellulari o satellitari Il collegamento tra utente ed ISP viene gestito con il #strong[point-to-point protocol] (PPP). === Point-to-point protocol (PPP) Il PPP gestisce #strong[collegamenti punto-punto]. Il PPP non necessita di: - media access control, perché il canale non è condiviso; - indirizzi MAC, peché ci sono soltanto 2 interlocutori (quindi è immediato capire chi è l'altro) Funzionalità di PPP: - supporto a protocolli diversi tramite tecniche di #strong[incapsulamento]; - supporto all'#strong[autenticazione]; - supporto alla #strong[rilevazione] degli errori (ma non alla correzione); - supporto all'assegnazione #strong[dinamica] degli indirizzi IP da parte dell'ISP Prevede due sotto-protocolli: - #strong[LCP] (link control protocol): protocollo che serve per stabilire, configurare e monitorare la connessione PPP; - #strong[NCP] (network control protocol): configurazione dei diversi protocolli a livello 3 Uno dei principi del PPP è la #strong[connection liveliness]: PPP riesce a rilevare il corretto funzionamento delle comunicazioni e può segnalare errori in merito. Opzionalmente, il PPP può prevedere anche funzionalità per la #strong[cifratura] dei dati e di #strong[correzione] degli errori (eventualmente tramite #strong[ritrasmissione automatica]). PPP è #strong[orientato alla connessione]. 5 fasi di PPP: + definizione della connessione (negoziazione della #strong[velocità] della connessione, definizione della modalità di connessione, ecc.); + #strong[autenticazione] (opzionale a seconda dei contesti); + configurazione del protocollo di rete utilizzato (es. IP); + comunicazione; + #strong[chiusura] della connessione, con relativo scambio di messaggi PPP è pensato per funzionare su mezzi full-duplex. Per questo non si preoccupa di eventuali conflitti. \ Volendo si può usare PPP anche su mezzi half-duplex. === Struttura del frame PPP #figure([#image("images/535207b7d63e840f93217589ab43e088.png")], caption: [ Frame PPP ] ) - il campo #strong[flag] delimita il frame; - il campo #strong[protocol] contiene il protocollo utilizzato a livello 3; - il campo #strong[info] contiene il payload; ==== Byte stuffing Concetto che permette di implementare il #strong[framing] di PPP e di \"escapare\" sequenze di bit che altrimenti verrebbero interpretate come delimitatori di frame. - il mittente aggiunge un byte extra `01111110` prima di ogni byte `01111110` all'interno del campo `info`; - il destinatario, se trova due byte `01111110` consecutivi scarta il 1° e considera il 2° come dato, continuando la lettura del frame. Se invece trova un solo byte `01111110` lo considera come terminatore del frame = Livello network Il livello rete è quello che definisce la rete Internet stessa. Il protocollo IP è stato pubblicato dalla IETF nel 1981. Inizialmente è stato pensato per reti con 4 dispositivi, ad oggi siamo a più di 5 miliardi di dispositivi connessi. Il protocollo IP è stato pensato proprio per essere molto #strong[scalabile]. La parte legata all'#strong[indirizzamento] e all'#strong[identificazione] di questi dispositivi è fondamentale nel livello 3. == Definizione di Internet Ci sono più definizioni, a seconda dei punti di vista: - per le applicazioni di rete, Internet è un'entità #strong[trasparente] che permette a due applicazioni di comunicare tra loro; - dal punto di vista fisico, Internet è un insimeme di componenti (host, link, router) in cui ciascun nodo è identificato da un #strong[indirizzo IP]; - dal punto di vista funzionale, Internet è una rete operante mediante #strong[packet switching], con intelligenza sugli end point e non sui nodi intermedi; - dal punto di vista organizzativo: - per i router è un insieme di #strong[autonomous system]; - per gli host è un insieme di #strong[nomi e domini] (DNS) == Principi base di Internet - #strong[survivability]: la comunicazione deve funzionare finché c'è un collegamento funzionante tra mittente e destinatario. A differenza di Ethernet (vedi spanning tree protocol), a livello 3 si cerca di far funzionare #strong[tutti] i link; - struttura #strong[a clessidra], in modo da poter funzionare per tutti i tipi di applicazioni di rete; - #strong[stateless]: i router non memorizzano alcuno stato, l'intelligenza sta ai bordi della rete; - #strong[net neutrality]: ogni pacchetto è trattato allo stesso modo, indipendentemente da chi siano mittente e destinatario; - ogni rete è potenzialmente gestita da un ente diverso (autonomous system) == Funzioni del livello network - si garantisce l'#strong[indirizzamento univoco] degli host. Tutti gli host connessi ad Internet devono essere identificati in modo univoco tramite un #strong[indirizzo IP]; - si definisce l'unità di trasferimento dei dati (#strong[datagram IP]); - si definisce l'architettura di Internet (router e autonomous system); - si illustrano le diverse funzioni di routing IP adotta una logica di tipo #strong[best-effort]. Non è un protocollo affidabile: - non garantisce la consegna del datagram; - in caso di mancata consegna, non garantisce nemmeno che ci sia un qualche feedback == Router I router sono fondamentali per il funzionamento del protocollo IP. Si occupano di #strong[instradare] i pacchetti IP nella rete sulla base dell'indirizzo IP di #strong[destinazione]. L'instradamento dei pacchetti avviene #strong[hop-by-hop]. - il 1° router viene chiamato #strong[source router] (o first hop router); - l'ultimo router viene chiamato #strong[destination router] Il protocollo usato a livello 2 potrebbe cambiare ad ogni hop, ma il protocollo IP resta sempre lo stesso. Un router può decidere di scartare un pacchetto se: - il router è sovraccarico e non può gestire altri pacchetti (congestione nella rete); - scade il TTL; - ci sono errori logici (es. cicli nella rete, errori di routing, ecc.) Un router accetta pacchetti IP anche se l'IP di destinazione non è il suo. Si tratta di una caratteristica fondamentale che distingue un router da un host. === Routing Quando un router riceve un pacchetto IP: - determina il #strong[net ID] leggendo l'IP destinazione; - se il net ID corrisponde ad una rete collegata direttamente al router (caso in cui il router è il #strong[destination router]), si procede con l'inoltro del pacchetto via Ethernet all'host di destinazione, altrimenti: - se nella #strong[tabella di routing] esiste un router per quel net ID, si procede con l'inoltro del pacchetto a quel router, altrimenti - se esiste un router di default, il pacchetto viene inoltrato al router di default; - se non esiste nemmeno un router di default, viene generato un errore di routing e il pacchetto viene scartato Il problema del routing viene scomposto in 2 sotto-problemi: - #strong[IP forwarding]: determinare il next hop router a partire dal net ID; - mantenere le #strong[tabelle di routing], indispensabili per far funzionare l'IP forwarding #block[ I protocolli di routing servono per mantenere le tabelle di routing. È l'IP forwarding che decide poi come inoltrare i pacchetti nella rete, non i protocolli di routing. ] Affinché il routing funzioni, la tabella di routing deve contenere tutte le informazioni necessarie per poter raggiungere #strong[qualsiasi] destinatario. Le tabelle di routing esistono anche sugli host. Si tratta quindi di tabelle gestite in modo autonomo da qualunque dispositivo che vuole comunicare a livello IP. I protocolli di routing vengono eseguiti #strong[continuativamente] per capire se la tabella di routing è ancora valida (cioè se è ancora la migliore) o se è necessario aggiustarla perché sono cambiate le condizioni della rete (es. è saltato un collegamento). ==== Tabella di routing La tabella di routing può essere popolata: - #strong[staticamente] dall'amministratore di rete o da vari protocolli di configurazione (es. DHCP); caso più comune nel caso di router e host in reti locali molto semplici; - #strong[dinamicamente] tramite protocolli di routing (es. RIP, OSPF, BGP) === Architettura di un router #figure([#image("images/cd8f2cb1c236f94eccb4cda2f0140128.png")], caption: [ Architettura di un router ] ) - le interfacce d'ingresso (#strong[input port]) e di uscita (#strong[output port]) sono a loro volta composte da: - parte fisica (livello 1); - parte rete (livello 2); - parte IP (livello 3) - #strong[switching]: architettura hardware che collega le porte d'ingresso con quelle di uscita; - #strong[routing processor]: conserva la tabella di routing e implementa l'IP forwarding Ogni porta d'ingresso e di uscita gestisce un #strong[buffer] di pacchetti. La congestione in un router avviene quando uno di questi buffer è pieno. La logica di switching si occupa di copiare i pacchetti dalla coda d'ingresso alla coda d'uscita. == Struttura di un indirizzo IP Dimensione: - #strong[4 byte] per IPv4; - #strong[16 byte] per IPv6 Gli indirizzi IP hanno una struttura gerarchica (non sono flat come i MAC address). Ogni indirizzo IP è composto da #strong[net ID] ed #strong[host ID]. La dimensione dei due campi dipende dalla #strong[classe] dell'indirizzo IP. #align(center)[#table( columns: 3, align: (col, row) => (center,center,center,).at(col), inset: 6pt, [classe], [range IP], [net ID - host ID], [A], [0.1.0.0 - 127.255.255.255], [8 - 24], [B], [172.16.58.3 - 192.168.3.11], [16 - 16], [C], [192.0.0.0 - 22172.16.31.10], [24 - 8], [D], [172.16.58.3 - 172.16.17.32], [N/A], [E], [240.0.0.0 - 255.255.255.254], [N/A], ) #align(center, [Classi IP di default]) ] L'approccio moderno è quello #strong[classless], che permette una maggiore flessibilità. La classe a cui l'indirizzo appartiene non è più auto-dichiarata dall'indirizzo stesso, ma è definita dalla #strong[netmask]. La #strong[notazione CIDR] permette di esprimere in maniera compatta indirizzo IP e netmask (es. `192.168.1.5/24`). La principale scomodita dell'approccio classful è che si passa da reti molto grandi a reti molto piccole, senza vie di mezzo (es. da una rete con classe A da 16.777.214 host ad una rete di classe B con 65.534 host). Tuttavia l'approccio classful è molto efficiente per la consultazione delle tabelle di routing (perché non c'è da gestire una netmask). Si è però preferito puntare alla flessibilità e quindi è stato scelto un approccio classless. === Indirizzi IP riservati - 0.0.0.0; - 127.0.0.0/8 (127.0.0.0 - 127.255.255.255), usato da applicazioni locali agli host; - 172.16.58.3/3 (tutti quelli delle classi D ed E); - 255.255.255.255 (broadcast address) === Indirizzi IP privati Chiamati anche #strong[non routable IP addresses] perché i router scartano tutti i pacchetti che contengono uno di questi IP come IP destinazione. - 10.0.0.0/8; - 172.16.0.0/12; - 192.168.0.0/16; == Gestione degli indirizzi IP La #strong[IANA] (Internet Assigned Number Authority) si occupa di gestire gli indirizzi IP. La IANA fa parte dell'associazione #strong[ICANN] (Internet Corporation for Assigned Names and Numbers). La gestione degli indirizzi IP è gerarchica: - la IANA assegna dei blocchi di indirizzi IP ai #strong[RIR] (Regional Internet Registry), che li gestiscono a livello regionale/continentale; - i RIR assegnano dei sotto-blocchi di indirizzi IP ai #strong[LIR] (Local Internet Registry), che li gestiscono a livello locale; - infine gli ISP (istanza di LIR) assegnano un indirizzo IP a noi utenti finali Per risalire all'area geografica di appartenenza di un indirizzo IP è sufficiente controllare qual è il LIR/RIR che lo gestisce. L'#strong[IETF] (Internet Engineering Task Force) si occupa valutare gli #strong[RFC] (Request For Comment) per definire gli standard di Internet. Gli #strong[RFC] sono dei documenti che definiscono gli \"standard di Internet\". Si chiamano in questo modo perché venivano creati dai pionieri di Internet per chiedere feedback ai loro colleghi. == Subnetting e supernetting - subnetting: da una rete grande se ne creano tante più piccole; - supernetting: si \"uniscono\" tante reti piccole in un'unica rete più grande Il subnetting viene fatto per #strong[segmentare] logicamente una rete più grande. Il supernetting viene fatto per ridurre il numero di regole di routing e può essere fatto solo se le reti sono #strong[adiacenti in senso binario]. In entrambi i casi si lavora sulla #strong[netmask]. == Datagram IP (aka pacchetto IP) #figure([#image("images/fb5b797fe103c38be91a86f9ec66daf3.png")], caption: [ Datagram IP ] ) La dimensione massima del pacchetto IP è di #strong[64 KB]. === VERS Versione del protocollo IP usata dal pacchetto (v4 o v6). === HLEN Dimensione dell'header del pacchetto. Questo campo serve perché in IPv4 la dimensione dell'header è #strong[variabile]. In particolare è variabile il numero di estensioni inserite nel campo IP OPTIONS. La dimensione dell'header viene indicata in #strong[WORD], ovvero in blocchi da 4 byte (guardando la figura, un blocco di 4 byte corrisponde ad 1 riga)- Se il campo IP OPTIONS è vuoto, HLEN vale 5. === TYPE OF SERVICE (TOS) Originariamente conteneva informazioni sulle prestazioni richieste dal pacchetto (es. bassa latenza). Oggi la struttura del campo è cambiata ed è diviso in 2 sotto-campi: - #strong[DSCP]: identifica delle #strong[classi di traffico] del pacchetto (campo usato da protocolli real-time es. VoIP); - #strong[ECN]: utilizzato dai router per segnalare informazioni riguardo al proprio stato di congestione === TOTAL LENGTH Dimensione totale (header + dati) del pacchetto. === IDENTIFICATION, FLAGS e FRAGMENT OFFSET Campi per gestire la #strong[frammentazione] di IP: - il campo #strong[IDENTIFICATION] marca tutti i frammenti che fanno parte dello stesso pacchetto; - il campo #strong[FLAGS] è una bitmask che indica, tra le altre cose, se il pacchetto è stato frammentato; La frammentazione serve per poter inviare pacchetti IP grandi fino a 64 KB tramite interfacce di rete che hanno una MTU molto più piccola (massimo 1.500 byte). La gestione della frammentazione in IP è piuttosto complessa. Il pacchetto può essere frammentato più volte ed in punti diversi. \ A causa di questa complessità, il protocollo TCP cerca di implementare lui la frammentazione a livello 4 in modo da non doverla gestire a livello 3. ==== Note sulla frammentazione dei pacchetti Nel caso più semplice, è il livello 3 di un host a chiedere al livello 2 il suo MTU per decidere se e come frammentare il pacchetto. Non sempre però si ha questa situazione: il pacchetto potrebbe essere frammentato durante il suo percorso (anche più di una volta), perché potrebbe attraversare reti con MTU differente. Gestire la frammentazione sui router ne peggiora le prestazioni. Per questo motivo negli ultimi tempi si è deciso di scartare i pacchetti piuttosto che frammentarli. La frammentazione quindi deve essere gestita dagli host. Se un router scarta un pacchetto perché la sua dimensione è maggiore dell'MTU dell'interfaccia di rete verso cui inoltrarlo, esso è tenuto da inviare un messaggio ICMP al mittente per informarlo. \ Sarà poi compito del mittente ri-trasmettere il pacchetto, avendo cura di frammentarlo opportunamente. Siccome il pacchetto può attraversare diversi router prima di arrivare a destinazione, può capitare anche che venga scartato più di una volta da router diversi, e quindi dev'essere continuamente ri-trasmesso dal mittente in frammenti sempre più piccoli. Questa logica con cui si scopre l'MTU delle reti tramite questi messaggi d'errore inviati dai router si chiama #strong[path MTU discovery]. === TIME TO LIVE (TTL) #strong[Contatore] del numero di hop che il pacchetto può ancora attraversare prima di dover essere scartato. Ogni volta che il pacchetto attraversa un router, questi prima di processarlo diminuisce di 1 il valore del suo TTL. - se il TTL è ancora $gt.eq$ 1, il router procederà con l'IP forwarding; - se il TTL è $eq$ 0, il router scarterà il pacchetto Il TTL serve per evitare che un pacchetto possa circolare all'infinito nella rete. Il TTL viene impostato dal sistema operativo. SO diversi potrebbero impostare TTL diversi. Generalmente il valore iniziale del TTL non è mai molto grande, perché se la rete è configurata opportunamente il numero di hop è piuttosto basso. === PROTOCOL Informazioni sul protocollo contenuto a livello dati (es. ICMP, TCP, UDP, ecc.). === HEADER CHECKSUM Campo usato per il controllo di integrità. A differenza di Ethernet, in IP il controllo d'integrità è fatto #strong[solo sugli header] (ad eccezione del TTL, perché se si includesse bisognerebbe ricalcolare il checksum ad ogni hop). == Autonomous system Ogni AS: - gestisce in modo #strong[autonomo ed esclusivo] uno o più blochi di indirizzi IP; - riesce a mettere in comunicazione due dispositivi connessi a reti sotto il proprio controllo senza dover passare per altri AS Ogni AS è identificato da un #strong[numero intero univoco] che gli viene assegnato dalla IANA. L'organizzazione di Internet si può considerare a 2 livelli: - livello di gestione #strong[interno] ad ogni autonomous system; - livello di gestione tra autonomous system #strong[differenti] Si parla di #strong[interior routing] quando il routing coinvolge #strong[un solo AS], altrimenti si parla di #strong[exterior routing]. Nessun AS può gestire più del #strong[5%] del traffico. Nella pratica, la stragrande maggioranza degli AS gestisce molto meno dell'#strong[1%] di tutto il traffico di Internet. === Interconnessioni tra autonomous system Due AS possono essere collegati tra loro in 2 modi: - peering point: collegamento #underline[il più semplice possibile] tra due AS. Viene fatto a seguito di un #strong[accordo privato] tra i due AS; - Internet Exchange point: infrastruttura più complessa che viene gestita da un'#strong[entità terza] Utilizzando un IXP è possibile applicare delle regole particolari per la gestione e/o il monitoraggio del traffico. La gestione del traffico di Internet è un #strong[costo] per gli AS. Un AS può decidere di farsi pagare il \"pedaggio\" da un altro AS se questi vuole inoltrare traffico attraverso la propria rete. Dal punto di vista tecnico, un AS \"finisce\" in presenza di un peering point o di un IXP. Gli IXP di solito sono posti agli estremi di AS che gestiscono #strong[reti molto grandi] (es. nazionali). I collegamenti tra AS più piccoli invece sono realizzati tramite peering point. === Tipologie di AS - #strong[stub]: AS che ha #strong[una sola connessione] verso un altro AS. Caso tipico degli ISP locali. Per questi AS non c'è bisogno di un vero e proprio algoritmo di routing (non c'è molta scelta sulla strada verso la quale inoltrare i pacchetti); - #strong[multi-homed]: molto simile allo stub, ma può essere collegato a più di un AS. Questo tipo di AS #strong[non permette] a traffico non generato da lui di transitare sulla propria rete; - #strong[transit]: sono collegati ad altri AS e permettono il transito al traffico che non è diretto a loro o che non è stato generato da loro La differenza tra multi-homed e transit è soltanto \"politica\": è il singolo AS che decide se permettere o meno il transito di traffico non suo nella propria rete. Non esistono vincoli tecnici che impediscono o obbligano un AS a peremttere il transito a traffico non suo. == Protocolli di routing I protocolli di routing devono tenere in considerazione: - #strong[scalabilità] - #strong[autonomonia amministrativa]: ogni AS deve poter essere autonomo nella gestione della propria rete - #strong[Border Gateway Protocol] (BGP): regola il traffico tra AS differenti; - #strong[Interior Gateway Protocol] (IGP): famiglia di protocolli che regolano il traffico nella rete interna di un AS (esempi: RIP, OSPF). Gli algoritmi di routing cercano di risolvere il problema dell'instradamento andando ad individuare dei #strong[percorsi ottimi] all'interno di un #strong[grafo]. Il costo dell'inoltro di un pacchetto è dato da diversi fattori: - statici: topologia della rete, numero di link da percorrere per arrivare a destinazione, ecc.; - dinamici: guasti, congestioni, ecc.; - economici: \"pedaggio\" da pagare ad un altro AS per poter utilizzare la sua rete; Il #strong[tipo di traffico] invece #strong[non dev'essere considerato] nei costi, sarebbe una violazione della #strong[net neutrality]. Un algoritmo di routing può essere #strong[globale] o #strong[locale] (detto anche #strong[distribuito]): - in un algoritmo di routing globale, ogni nodo ha una #strong[visione globale] della rete (conosce tutti gli altri nodi e tutti i collegamenti). Esempio: algoritmi di tipo #strong[link state protocol]; - in un algoritmo di routing locale, i nodi non hanno una visione globale della rete (per lo meno non nello stesso istante di tempo), ma ne hanno una soltanto locale (es. conoscono i nodi e i collegamenti più vicini a loro). Esempio: #strong[distance vector protocol]. In entrambe le tipologie di algoritmi, ogni nodo comunica sempre agli altri delle informazioni sullo stato della rete. Gli algoritmi di routing locali però non hanno uno \"snapshot\" dell'intera rete. === Algoritmi di tipo link state Famiglia di algoritmi di routing #strong[globali] che usano l'#strong[algoritmo di Dijkstra] per calcolare il percorso ottimo. In questi algoritmi ciascun nodo comunica periodicamente a tutti gli altri nodi della rete informazioni riguardo al costo dei suoi collegamenti. Questi messaggi vengono chiamati #strong[link state broadcast]. Con queste informazioni, ogni nodo riesce a costruirsi internamente lo stato della rete e a calcolare il percorso migliore utilizzando l'algoritmo di Dijkstra. Tutti i nodi hanno una visione #strong[completa ed identica] dello stato della rete. Problematiche da gestire: - tutti i nodi devono conoscersi, altrimenti non sono in grado di comunicare in broadcast. Dev'esserci quindi un #strong[database centrale] autoritativo che contiene tutti i nodi della rete, con il quale ogni router dev'essere in grado di interfacciarsi; - potrebbero esserci degli errori di sincronizzazione tra i nodi (es. i link state broadcast non arrivano a tutti, ad alcuni arrivano in ritardo, ecc.); - il fatto di generare molto traffico broadcast rende questi algoritmi poco scalabili su reti molto grandi Periodicamente ogni nodo invia in broadcast dei pacchetti #strong[LSP] contenenti: - l'ID del nodo; - la #strong[lista dei vicini] e il costo dei rispettivi link; - un numero di sequenza (per accorgersi di delivery-out-of-order dei pacchetti); - un TTL (per evitare di usare informazioni vecchie) I pacchetti LSP vengono inviati dai router con una logica di #strong[flooding]: quando un router riceve un pacchetto LSP con un TTL valido: + aggiorna la propria tabella di routing, sulla base delle informazioni contenute nel pacchetto; + inoltra una copia del pacchetto LSP a tutti i suoi link, ad eccezione di quello da cui proveniva il pacchetto === Algoritmi di tipo distance vector Algoritmi #strong[locali] legati al concetto di #strong[vettori di distanze]. Sono algoritmi #strong[asincroni] perché non tutti i nodi sono sincronizzati tra loro. Informazioni che ogni router memorizza: - costo delle varie destinazioni (parte \"distance\"); - #strong[direzione] da prendere per ogni destinazione (parte \"vector\"), ovvero il next hop; Questi algoritmi utilizzano l'#strong[algoritmo di Bellman-Ford] per calcolare il percorso ottimo. Ad ogni iterazione dell'algoritmo, un nodo comunica ai suoi vicini soltanto un #strong[vettore] che contiene tutte le destinazioni a lui conosciute e il rispettivo costo. Gli algoritmi di tipo distance vector sono molto più #strong[scalabili] rispetto a quelli di tipo link state, perché non ci sono messaggi broadcast (ogni nodo comunica solo con i propri vicini). Di contro, questi algoritmi hanno problemi di #strong[convergenza] in caso di cambiamenti nella rete: - in caso di guasto di un nodo, gli algoritmi di tipo distance vector impiegano diverse iterazioni per aggiornare i costi su tutti i nodi; - gli algoritmi di tipo link state invece impiegano una sola iterazione in questo caso ==== Effetto rimbalzo Problema notevole negli algoritmi di routing di tipo distance vector. #figure([#image("images/7fcfb912212000ba1bb21992f9fdf446.png")], caption: [ Effetto rimbalzo: scenario iniziale ] ) Il collegamento tra A e B ha un problema: #figure( image("images/57dd139d524e6aa9d1af0e632c2c4e3c.png", height: 28%), caption: [ Effetto rimbalzo: un link ha un problema ] ) B aggiorna la distanza per A e decide di passare per C per raggiungerlo: #align(center)[#table( columns: 3, align: (col, row) => (center,center,center,).at(col), inset: 6pt, [destinazione], [costo], [predecessore], [A], [3], [C], [C], [1], [B], ) #align(center, [1° iterazione: tabella delle distanze di B]) ] Problema: la distanza che B ha ricevuto da C per raggiungere A prevedeva il passaggio per B stesso. Anche C quindi deve aggiornare la sua distanza per raggiungere A, perché è cambiata la distanza B $arrow.r$ A su cui C si basava: #align(center)[#table( columns: 3, align: (col, row) => (center,center,center,).at(col), inset: 6pt, [destinazione], [costo], [predecessore], [A], [4], [B], [B], [1], [C], ) #align(center, [2° iterazione: tabella delle distanze di C]) ] Di nuovo, B è costretto ad aggiornare la propria distanza per raggiungere A, perché è cambiata la distanza C $arrow.r$ A su cui B si basava. Questo loop continua finché C non si accorge che è più conveniente usare il link diretto C $arrow.r$ A con costo 25. Eventuali pacchetti da inoltrare che arrivano a B o a C mentre è in esecuzione questo loop continueranno a rimbalzare tra questi due nodi finché il loop non termina (o finché non scade il TTL del pacchetto). Possibili mitigazioni al problema (non lo risolvono, ma riducono i danni): - si definisce un #strong[numero massimo di hop] (es. 16) per \"rappresentare l'infinito\" (se un nodo è distante 16 hop si considera irraggiungibile); - approccio #strong[split horizon]: approccio selettivo dove si evita che B mandi a C percorsi che prevedono il passaggio per C stesso Una reale soluzione all'effetto rimbalzo è l'algoritmo #strong[path vector], estensione del distance vector. Nel path vector i nodi non si scambiano solo i costi per raggiungere la destinazione finale, ma anche l'#strong[intero percorso] per raggiungerla. In questo modo ogni nodo può scartare le informazioni che riguardano percorsi che passano per il nodo stesso. === Routing Information Protocol (RIP) Protocollo molto semplice basato su algoritmo di tipo #strong[distance vector]. I costi sono misurati in termini di #strong[numero di hop]. Ogni nodo iniva informazioni ogni #strong[30 secondi] agli altri nodi. Un nodo può anche fare una #strong[richiesta attiva] (RIP request) ai nodi a lui vicini per richiedere le informazioni, senza quindi dover aspettare 30 secondi. Se un router non riceve informazioni per #strong[180 secondi], viene considerato irraggiungibile e si considerano guasti i link che portano verso di lui. Ha gli stessi svantaggi degli algoritmi di tipo distance vector: - non adatto a reti dove i costi sono molto dinamici (es. frequenti congestioni, ecc.); - rischio di effetto rimbalzo === Open Short Path First (OSPF) Protocollo di tipo link state intra-AS. Diversamente da RIP, OSPF si adatta anche a reti in cui le condizioni possono cambiare molto velocemente. Può essere usato in maniera ibrida con RIP. Il #strong[link state database] viene inviato ogni #strong[30 minuti] a tutti i nodi che stanno nella rete. === Border Gateway Protocol (BGP) Protocollo usato per regolae il traffico inter-AS. Utilizza un algoritmo di tipo #strong[path vector]. BGP utilizza il #strong[protocollo TCP] per instaurare una connessione tra i router vicini (che nel contesto del protocollo vengono chiamati #strong[peer]). Vantaggi di BGP: - garantisce che non ci siano cicli nel percorso (grazie all'uso dell'algoritmo path vector); - non ci sono dei refresh periodici (come nel caso degli algoritmi di tipo link state o distance vector): un percorso è considerato valido finché non viene sovrascritto da un percorso migliore o finché non si perde la connessione con il peer; - gli aggiornamenti sono #strong[incrementali]; - le metriche di un AS non sono esposte agli altri AS Una #strong[sessione BGP] è una connessione semi-permanente tra due peer, instaurata tramite il protocollo TCP. Una sessione BGP può essere: - #strong[interna] (I-BGP) se coinvolge router dello stesso AS; - #strong[esterna] (E-BGP) se coinvolge router di AS diversi Il protocollo BGP è quello che di fatto implementa la logica #strong[hop-by-hop] di Internet: ogni router informa i vicini soltanto dei percorsi che utilizza. Funzionalità principali di BGP: - scambiare informazioni di raggiungibilità tra #strong[AS confinanti], detti #strong[peer], configurando #strong[manualmente] i router; - propagare le informazioni di raggiungibilità all'interno di un AS con un meccanismo #strong[distribuito] basato sull'algoritmo #strong[path vector]; - determinare i percorsi miglior in base a informazioni di raggiungibilità e policy di routing Le destinazioni sono indicate con #strong[prefissi] che rappresentano una o più sottoreti. Si fa ampio uso di #strong[aggregazione CIDR] di indirizzi per ridurre drasticamente il numero di entry nelle tabelle di routing. Il BGP non è necessario se uno dei due AS è uno #strong[stub]. Il protocollo BGP distingue due tipologie di router: - #strong[transit router]: gestiscono il traffico I-BGP (interno all'AS). Questi router devono essere peer di tutti gli altri; - #strong[border router] (o edge router): gestiscono il traffico E-BGP (tra AS diversi). Non devono necessariamente essere peer di tutti gli altri. La scelta del percorso si basa sia sulla policy dell'AS, sia su alcuni #strong[path attributes], ovvero caratteristiche del percorso, ad esempio: - hop count; - presenza o assenza di certi AS; - dinamica dei link (stabili/instabili) BGP può essere configurato per adottare diverse #strong[politiche]. Le politiche sono implementate in 2 modi: - scegliendo percorsi tra diverse alternative; - controllando l'invio di #strong[advertisement] ad altri AS Esempi di politiche: - un AS multi-homed rifiuta di agire come transit per altri AS (limita il path advertisement); - un AS multi-homed decide di agire come transit per altri AS (effettua il path advertisement per quegli AS); - un AS può favorire o penalizzare per il traffico transit che viene originato da lui Il #strong[prefix advertisement] è l'azione con cui i router si scambiano informazioni sui #strong[prefissi] contenuti nelle loro tabelle di routing. Questi annunci possono contenere anche dei path attributes. Quando un router viene a conoscenza di un nuovo prefisso, aggiunge una riga alla propria tabella di routing. Un router può venire a conoscenza di più percorsi per raggiungere lo stesso prefisso. Per selezionarne uno tra questi ci sono diverse regole: - policy locale; - AS-PATH più breve (cioè quali AS deve attraversare il pacchetto per arrivare a destinazione); - router di NEXT-HOP più vicino; - altri criteri, inclusi quelli economici ==== Gestione dei guasti in BGP Guasti E-BGP ed I-BGP sono gestiti in maniera diversa: - se si rompe un link E-BGP, tutti i percorsi che utilizzano quel link vengono eliminati dalle tabelle di routing; - se si rompe un link I-BGP, i router potrebbero essere comunque in grado di comunicare tramite percorsi indiretti == Protocollo ICMP Protocollo di livello 3 usato come supporto ad IP. Usato dai router per segnalare malfunzionamenti all'interno della rete e come strumento per il debug di una rete. === Struttura di un pacchetto ICMP Si tratta di un pacchetto IP in cui il campo #strong[protocollo] è settato ad #strong[1]. Nel payload può contenere informazioni riguardanti livelli superiori dello stack TCP/IP (es. #strong[port unreachable]). Il campo #strong[type] definisce la tipologia di pacchetto. #align(center)[#table( columns: 2, align: (col, row) => (center,left,).at(col), inset: 6pt, [type], [message], [0], [echo reply], [3], [destination unreachable], [5], [redirect], [8], [echo request], [11], [time exceeded], ) #align(center, [Tipologie di pacchetto ICMP]) ] I dati inseriti in un messaggio di tipo #strong[echo request] devono essere re-inviati al mittente, così come li ha mandati, in un nuovo messaggio ICMP di tipo #strong[echo reply]. \ Echo request ed echo reply sono usati dal comando `ping` e sono stati pensati appositamente per testare #strong[attivamente] la connettività di rete. I messaggi di tipo #strong[destination unreachable] contengono degli ulteriori sotto-tipi: - code 0: network unreachable; - code 1: host unreachable; - code 3: port unreachable; - code 4: packet too big. Inviato dai router quando il pacchetto che ricevono non può essere inoltrato sulla loro rete a causa dell'MTU inferiore alla dimensione del pacchetto. Il messaggio di tipo #strong[time exceeded] può essere inviato dai router quando scartano un pacchetto a causa del TTL scaduto. Sono alla base del comando `traceroute`. Il messaggio di tipo #strong[redirect] può essere inviato da un router per informare il mittente del fatto che esiste un #strong[percorso migliore] verso il quale inoltrare il pacchetto. = Livello trasporto Il livello trasporto estende il servizio di consegna del protocollo IP tra due host terminali ad un servizio di consegna a due #strong[processi applicativi] in esecuzione sugli host. - TCP (Transfer Control Protocol): enfasi sul #strong[trasferimento] e sul #strong[controllo] dei dati; - UDP (User Datagram Protocol): enfasi sui #strong[dati] e sull'uso che ne fa l'#strong[utente] Funzionalità implementate dai protocolli di questo livello: - gestire la #strong[comunicazione tra processi]. Devono avere capacità di #strong[multiplexing e demultiplexing] per farli comunicare sullo #strong[stesso canale]; - funzionalità di #strong[rilevamento degli errori], in modo simile ad Ethernet TCP ed UDP sono ai due estremi: - UDP è un protocollo che implementa il #strong[minimo indispensabile] per poter essere definito un protocollo di livello trasporto; - TCP invece cerca di implementare tutte le funzionalità che potrebbero essere utili ed è quindi un protocollo molto più complesso Spesso può avere senso sviluppare un protocollo proprietario per il livello trasporto proprio per avere una \"via di mezzo\" tra TCP ed UDP. Nel contesto dei protocolli di livello 4, multiplexing e demultiplexing vengono implementati utilizzando le #strong[porte]. A livello 4, ciò che identifica un'applicazione è la porta. Nell'header del pacchetto trasporto ci sono la #strong[porta sorgente] e la #strong[porta destinazione]. La porta è complementare all'indirizzo IP: - l'IP identifica l'host; - la porta identifica l'applicazione in esecuzione su quell'host Il sistema operativo assegna una certa porta, in maniera #strong[esclusiva], ad un processo. La gestione delle porte è indipendente dal protocollo: la stessa porta può essere utilizzata da 2 protocolli diversi, ma lo stesso protocollo non può utilizzare 2 volte la stessa porta. Il sistema operativo riesce a gestire il caso in cui la stessa porta sia attiva sia per UDP che per TCP perché, leggendo il datagram IP, è in grado di capire il protocollo di livello 4 usato e quindi ad inoltrare il pacchetto all'applicazione specifica. A seconda del protocollo, il sistema operativo potrebbe decidere di non inviare immediatamente il pacchetto all'applicazione (es. i pacchetti vengono inviati solo quando un #strong[buffer] si riempie, come avviene in TCP). La porta è un numero intero da #strong[16 bit]. Le porte sono divise in vari range: - #strong[well-known ports]: range 0-1024. Sono assegnate a determinati protocolli applicativi ben definiti. Tipicamente vengono gestite in modo particolare anche dai sistemi operativi (ad esempio nei sistemi Linux sono necessari i privilegi di root per poter avviare un processo che usa queste porte); - #strong[registered ports]: range 1.024 - 49.151. Anch'esse sono associate ad alcuni protocolli/applicazioni notevoli (es. 3306 MySQL, 5432 PostgreSQL, ecc.), ma che sono meno \"fondamentali\" delle well-known ports; - #strong[porte alte]: range 49.152 - 65.535. Non sono associate a nessun protocollo noto e non hanno alcun significato implicito. Tipicamente i client scelgono la propria porta sorgente all'interno di questo range. Su Linux esiste il file `/etc/services` che mappa il numero della porta con il protocollo applicativo. == Paradigma client-server nei protocolli di livello 4 Tutti i protocolli di livello trasporto distinguono i ruoli di #strong[client] e #strong[server]: - il server apre una connessione #strong[passiva], mettendosi #strong[in ascolto su una certa porta]; - il client apre una connessione #strong[attiva] con il server Sia il processo client che il processo server sono identificati da una porta. Nei casi d'uso reali: - la porta del client è scelta in modo casuale dal sistema operativo; - la porta del server è richiesta esplicitamente Quando si parla di comunicazione a livello di trasporto, ogni pacchetto è identificato da una #strong[quintupla]: - IP sorgente/destinazione; - porta sorgente/destinazione; - tipo di protocollo (TCP o UDP) Il termine #strong[packet flow] indica l'insieme dei pacchetti che appartengono alla stessa comunicazione. == Controllo d'integrità Il controllo d'integrità a livello 4 viene fatto tramite un #strong[checksum], che viene inserito nell'header del pacchetto. Sia TCP che UDP effettuano il controllo d'integrità allo stesso modo. Il controllo d'integrità a livello 4 viene fatto anche su informazioni del livello 3. In particolare viene costruito uno #strong[pseudo-header] di livello 4 con le seguenti informazioni: - indirizzo IP mittente e destinatario; - protocollo di livello 4 usato (TCP o UDP); - lunghezza del pacchetto di livello 4 Il checksum viene poi calcolato su: - pseudo-header; - header reale di livello 4; - payload L'algoritmo di checksum del livello 4 lavora su blocchi da #strong[16 bit] alla volta, anche se il pacchetto è diviso in blocchi da 32 bit. L'algoritmo di checksum del livello 4 viene eseguito dal software. Tipicamente si tratta di un algoritmo molto più semplice di quello usato a livello 2 (che invece gira su hardware dedicato). Il controllo d'integrità esiste anche a livello 2 e 3, ma viene introdotto anche a livello 4 per una serie di ragioni: - non tutti i link forniscono un servizio di livello 2 per rilevare gli errori; - il checksum di IP è fatto solo sull'header IP, non sui dati; - il datagram di IPv6 non contiene più il checksum == Protocollo UDP Protocollo #strong[minimale] che implementa il minimo indispensabile per poter essere definito un protocollo di trasporto. Possiede comunque le caratteristiche fondamentali di questi protocolli, ovvero la gestione delle porte e il controllo d'integrità. Come IP, UDP non fornisce nessuna garanzia di affidabilità. UDP è un protocollo #strong[orientato ai pacchetti] (a differenza di TCP che è orientato alla connessione). Ogni pacchetto è trattato in modo #strong[indipendente] da tutti gli altri (come avviene in IP). La dimensione massima di un pacchetto UDP è data da: $ sans("dimensione pacchetto IP") minus sans("dimensione header UDP") $ UDP non ha nessuna logica di frammentazione, che viene lasciata al livello 3. === Pacchetto UDP (user datagram) #figure([#image("images/86ba8ae97d2b7276ad9a7073a53e3200.png")], caption: [ Pacchetto UDP ] ) == Protocollo TCP Si tratta di un protocollo definito in diversi RFC. Soggetto ancora oggi a piccole modifiche in alcune sue parti. Rispetto ad UDP, TCP garantisce #strong[affidabilità] anche in presenza di protocolli sottostanti inaffidabili (es. IP). TCP è un protocollo #strong[orientato alla connessione]. === Problema dell'affidabilità Si vuole creare un canale #strong[virtuale] affidabile su un canale fisico inaffidabile. Questo canale virtuale è creato dal sistema operativo, che dev'essere in grado di #strong[rilevare] e #strong[correggere] gli errori. In questo contesto, con \"correzione\" dell'errore s'intende la ri-trasmissione del dato. A questo livello infatti non ci sono informazioni sufficienti per andare effettivamente a correggere gli errori. Gli errori che devono essere rilevati (e corretti) da TCP sono: - errori di trasmissione. Per questi errori si utilizza il checksum, come in UDP; - il pacchetto non arriva a destinazione; - arrivano più copie dello stesso pacchetto; - delivery out-of-order dei pacchetti TCP implementa delle rilevazioni per #strong[tutti] questi possibili errori. Non tutte le applicazioni però sono sensibili a questi errori (specialmente al delivery out-of-order). Queste applicazioni quindi possono usare UDP e re-implementarsi alcune funzionalità di rilevazione degli errori di TCP. La logica di rilevazione (e correzione) degli errori è gestita in maniera trasparente dal sistema operativo. L'applicazione deve preoccuparsi soltanto di inviare i dati. === Acknowledgement Nei protocolli ad alta affidabilità è necessario predisporre un meccanismo di #strong[acknowledgement]. L'acknownledgement può essere positivo o negativo. Nel caso di TCP esiste solo l'acknowledgement positivo, per una serie di ragioni: - se un pacchetto viene perso, il destinatario non ha modo di inviare un ACK negativo; - nel corso degli anni è emerso come la casistica d'errore principale di Internet sia il #strong[sovraccarico dei router]. Aggiungere quindi del traffico (gli ACK negativi) che questi router dovranno gestire non è una buona idea. Quando il mittente invia un messaggio, inizia a partire un #strong[timeout]. Se dopo tale timeout il mittente non ha ricevuto un ACK positivo per il messaggio che aveva mandato, allora assumerà che ci sia stato un errore e ri-trasmetterà il messaggio. TCP, come tutti i protocolli orientati alla connessione, ha 3 sotto-protocolli: - uno per #strong[aprire] la connessione; - uno per #strong[usare] la conessione (scambio di dati); - uno per #strong[chiudere] la connessione (in realtà in TCP ce ne sono 2) Tutti questi sotto-protocolli devono essere #strong[affidabili] affinché TCP nel suo insieme possa essere affidabile. Nel caso di TCP, la connessione è soltanto #strong[logica]. Non c'è un'allocazione stabile di risorse fisiche (come invece avviene in PPP a livello 2). Sia client che server sono tenuti a memorizzare uno #strong[stato] della connessione. === Trasporto orientato al flusso dati Il \"pacchetto\" TCP viene chiamato #strong[segmento], con l'idea che non sia una cosa a sè stante ma faccia parte di un più ampio #strong[flusso di dati]. TCP mette a disposizione alle applicazioni un'interfaccia per inviare i dati. Sarà compito di TCP gestire la #strong[segmentazione] del flusso di dati. La segmentazione fatta da TCP è analoga a quella che fa IP a livello 3. TCP però cerca di evitare che ci sia una ulteriore frammentazione a livello 3, quindi di solito imposta come dimensione massima del segmento l'MTU dell'interfaccia di rete. Ogni segmento TCP viene identificato da un #strong[sequence number] che consente al destinatario di: - identificare (e scartare) eventuali #strong[duplicati]; - riordinare i segmenti in caso di delivery out-of-order In TCP esiste un #strong[buffer] sia per l'invio che per la ricezione dei pacchetti: - il sistema operativo del mittente invia i dati soltanto quando il buffer è pieno; - il sistema operativo del destinatario invia i dati all'applicazione soltanto quando il buffer è pieno Il buffer destinatario viene usato anche per: - rilevare eventuali errori; - riordinare i pacchetti in caso di delivery out-of-order La connessione virtuale che viene creata con TCP è di tipo #strong[full duplex]. Una volta creata la connessione, non c'è più distinzione tra client e server (entrambi possono usare il canale per inviare i dati in maniera #strong[indipendente]). L'unico momento in cui TCP distingue client e server è nell'#strong[apertura] della connessione, === Asincronia di TCP La gestione tramite buffer rende TCP un protocollo #strong[asincrono]: il momento in cui il sistema operativo invia effettivamente i dati non coincide necessariamente con quello in cui l'applicazione chiede al SO di inviarli. L'asincronia c'è sia in fase di invio che in fase di ricezione. Esistono alcune eccezioni con le quali l'applicazione può chiedere al sistema operativo di inviare #strong[subito] i dati. === Cosa TCP NON gestisce - comunicazione in #strong[tempo reale] (TCP è #strong[asincrono] e non è quindi adatto per comunicazioni real time); - #strong[disponibilità di banda] (non garantisce una velocità minima o un ritardo massimo di trasmissione); - comunicazioni multicast/broadcast (TCP è pensato per far comunicare soltanto 2 entità tra di loro) #pagebreak(weak: true) === Segmento TCP #figure([#image("images/6edf4a6b98426b6f97c63cbcce4c414a.png")], caption: [ Segmento TCP ] ) ==== Sequence number e acknowledgement number Il sequence number è l'#strong[offset], all'interno del #strong[flusso] di comunicazione, di quel segmento specifico. L'acknowledgement number è associato al sequence number ed indica quanti byte il destinatario ha ricevuto correttamente. Sequence number ed ACK number sono su campi separati perché TCP permette di inviare dati anche all'interno di pacchetti di tipo ACK. Dato che sequence number e ACK number sono codificati con 32 bit, per avere flussi di comunicazione che trasferiscono più di $2^32$ byte questi numeri sono #strong[ciclici] (si riparte da capo quando si arriva alla fine). ==== Scelta dell'initial sequence number Nel momento in cui client e server instaurano la connessione, #strong[entrambi] generano in modo casuale un #strong[initial sequence number] (diverso tra client e server) e lo inviano all'altro. Client e server dovranno far partire i propri ACK number sulla base dell'initial sequence number ricevuto dall'altro. L'initial sequence number viene generato casualmente (e non si parte da 0) per ragioni di sicurezza. In questo modo un eventuale attaccante farà più fatica a intromettersi in una comunicazione TCP generando segmenti validi, perché dovrebbe indovinare l'initial sequence number utilizzato. ==== HLEN Lunghezza dell'header TCP. Questo campo è necessario perché in TCP, come in IP, la lunghezza dell'header è #strong[variabile]. ==== RESERVED Campo riservato per usi futuri. ==== CODE BIT Bitmask che indica le funzionalità attive in quel segmento. - bit #strong[URGENT]: usato nella fase di scambio dati, serve per marcare un segmento come #strong[urgente], in modo che il sistema operativo gli dia priorità rispetto agli altri. In realtà questo bit non è quasi più utilizzato oggi (in caso di urgenza vera si usano direttamente altri protocolli piuttosto che TCP). - bit #strong[ACK]. Se è `1` significa che questo è un segmento di acknowledgement e quindi il suo ACK number dev'essere interpretato dal destinatario; - bit #strong[PUSH]: svuota il buffer di ricezione. Quando il sistema operativo del ricevente trova un segmento con bit PUSH pari ad 1, invierà immediatamente i dati all'applicazione, senza aspettare il riempimento del buffer. - bit #strong[SYN]. Usato in fase di #strong[apertura] della connessione. - bit #strong[FIN]. Usato in fase di chiusura (affidabile) della connessione. - bit #strong[RST]. Usato in fase di chiusura (inaffidabile) della connessione. ==== WINDOW SIZE Campo associato al controllo di flusso. Contiene la quantità di byte che il ricevente può ancora ricevere prima di congestionarsi. ==== URGENT POINTER Puntatore legato al bit `URG`. Indica quali sono i dati urgenti all'interno del pacchetto. ==== TCP OPTIONS Contiene eventuali opzioni usate dal protocollo. Opzioni degne di nota: - #strong[max segment size] (MSS): indica la dimensione massima del segmento supportata in #strong[ricezione]. Equivalentemente, si può dire che questo campo contiene la dimensione in byte del buffer di ricezione; - #strong[window scale]: serve per indicare delle finestre di comunicazione più grandi di $2^16$ bit (massimo valore inseribile nel campo window size); - #strong[maximum segment lifetime]: analogo del TTL del livello 3 === Esempio di dati urgenti Una delle poche applicazioni rimaste che fa uso del bit `URG` è `telnet` (il vecchio SSH). I segnali per i processi (es. `^Z`, `^C`, ecc.) vengono mandati come \"dati urgenti\". === Negoziazione della max segment size Se l'MSS non è mai scambiata tra le opzioni, si assume una dimensione di #strong[536 byte]. In realtà l'opzione è sempre presente nelle fasi di apertura della connessione. Indicare un valore dell'MSS superiore a quello di default può essere utile per #strong[aumentare le prestazioni] (cioè si riduce il numero di pacchetti). L'MSS dovrebbe comunque essere sempre inferiore all'MTU del livello 2, in modo da evitare la frammentazione fatta a livello 3 da IP. La dimensione ideale dell'MSS è: $ upright("MTU") minus upright("dim. header liv. 3") minus upright("dim. header liv. 4") $ Client e server si scambiano le rispettive MSS durante le fasi di apertura della connessione. L'MSS può comunque essere ri-negoziato una volta aperta la connessione. L'MSS che viene scelto è il #strong[minimo] tra quello di client e server, oppure un valore ancora inferiore se tra client e server ci sono reti con una MTU più piccola. === Piggybacking Logica per la quale il ricevente, una volta ricevuti con successo i dati, non invia immediatamente un acknowledgement, ma aspetta un po', nella speranza di ridurre il numero di acknowledgement. === Apertura della connessione - three way handshaking Questa è l'unica fase in cui si distinguono i ruoli di client e server: - il server è in ascolto su una porta; - il client vuole aprire una connessione verso il server su quella porta L'instaurazione della connessione in TCP serve per diverse ragioni: - assicurarsi che il server esista e che sia raggiungibile; - negoziare alcuni parametri (es. MSS) Tutto questo #strong[prima] di iniziare ad inviare dati. Il processo con cui viene instaurata la connessione si chiama #strong[three-way handshaking]. ==== 1. Client SYN Il 1° pacchetto necessario per aprire la connessione viene mandato #strong[dal client al server]. Si tratta di un pacchetto #strong[vuoto] (non ha un payload) e che ha il bit SYN \= 1. In questo pacchetto il client deve indicare il suo initial sequence number. In questo pacchetto possono esserci anche informazioni per la negoziazione dei parametri, quali: - #strong[maximum receiver window]: il client indica al server la dimensione del proprio buffer di ricezione; - maximum segment size ==== 2. Server SYN/ACK Se il server intende aprire una connessione con il client, risponderà con un altro pacchetto vuoto con #strong[entrambi] i bit SYN ed ACK settati ad 1. In questo pacchetto il server deve includere il proprio initial sequence number. L'ACK number che il server invia al client in questo pacchetto è l'initial sequence number del client aumentato di 1. ==== 3. Client ACK Il client risponde al server con un altro pacchetto vuoto con bit ACK \= 1. - il seq. number di questo pacchetto è l'initial seq. number del client (scelto al punto 1), aumentato di 1; - l'ACK number di questo pacchetto è l'initial seq. number del server (scelto al punto 2), aumentato di 1 A questo punto la connessione client $arrow.l.r$ server è aperta e non c'è più distinzione tra client e server. === Chiusura della connessione In TCP esistono 2 modi per chiudere una connessione: - modalità #strong[polite] (con affidabilità); - modalità #strong[unpolite] (senza affidabilità) ==== Chiusura polite Viene utilizzata quando non si ha fretta di chiudere la connessione. La connessione può essere chiusa arbitrariamente dal client o dal server (ricordare che a questo punto della comunicazione non c'è nemmeno distinzione tra client e server). Supponendo che la comunicazione sia tra due entità A e B, la chiusura della connessione prevede questi passi: + A invia a B un pacchetto TCP con bit FIN \= 1; + B riceve il pacchetto e risponde con un ACK; + B informa l'applicazione del fatto che A intende chiudere la connessione, in modo da darle tempo per disallocare eventuali risorse; + quando l'applicazione ha chiuso la connessione, B invia un pacchetto ad A con bit FIN \= 1; + A risponde a B con un ACK e fa partire un #strong[timeout], in modo da dare tempo all'applicazione in esecuzione su A di liberare eventuali risorse; + trascorso il timeout, anche A considera chiusa la connessione con B Quando B riceve l'ACK di A, considererà chiusa la connessione. La chiusura polite viene utilizzata per dare tempo all'applicazione di gestire una logica di chiusura (rilasciare eventuali risorse, ecc.). Il timeout di A serve per gestire eventuali segmenti TCP che potrebbero essere ancora circolanti nella rete (ad esempio a causa di ritrasmissioni). ==== Modalità unpolite La connessione viene chiusa immediatamente. Viene utilizzata quando non c'è tempo (o interesse) nell'aspettare tutto il giro della chiusura polite. In questo caso A invia un pacchetto TCP con bit RST \= 1. B non è tenuto a rispondere in alcun modo (nemmeno con un ACK). A considererà chiusa la connessione #strong[immediatamente] (subito dopo l'invio del pacchetto). Anche B considererà chiusa la connessione immediatamente, non appena riceve il pacchetto (o quando si accorge che A non risponde più, se il pacchetto RST è stato perso). Con questa modalità non ci sono garanzie di affidabilità (approccio best effort). Questa modalità non è strettamente indispensabile dal punto di vista tecnico: (per interrompere la connessione basterebbe che A e B smettano di parlarsi, ci penserà poi il timeout di TCP a interrompere la connessione), ma almeno si #strong[notifica] l'altra entità della comunicazione del fatto che si vuole interrompere la connessione. === Timeout di TCP Il timeout in TCP è #strong[adattativo]. Viene continuamente ri-stimato in base alle condizioni della rete. #block[ #strong[Definizione]: Round Trip Time (RTT) Tempo che passa tra l'invio di un segmento e la ricezione del suo ACK. ] Per definizione, un timeout valido dev'essere maggiore dell'RTT minimo osservabile nell'ambito di una comunicazione. Un primo approccio usato per stimare il timeout si basava sull'RTT #strong[medio]: $ upright("timeout") eq beta times upright("RTT")_(upright("medio")) $ Questa tecnica presenta alcuni problemi: - la media non è sempre affidabile, basta un RTT molto alto/basso per sfasarla; - gli RTT più vecchi dovrebbero avere un peso minore nella stima del timeout Il #strong[sample RTT] all'istante $t$ è l'RTT misurato all'istante $t$. L'#strong[estimated RTT] è una #strong[media pesata] per #strong[stimare] l'RTT all'istante $t$: $ upright("EstimatedRTT") lr((t)) eq lr((1 minus x)) dot.op upright("EstimatedRTT") lr((t minus 1)) plus x dot.op upright("SampleRTT") lr((t)) $ con $x in lr((0 comma 1))$ ed $x eq frac(1, n plus 1)$ come valore iniziale, dove $n$ è il numero di campioni di RTT usati per il calcolo. La formula con cui viene stimato l'RTT viene chiamata #strong[Exponential Weighted Moving Average] (EWMA), perché si tratta di una #strong[media pesata] in cui il peso dei campioni più vecchi #strong[diminuisce esponenzialmente] con il passare del tempo. Una volta stimato l'RTT, si procede con il calcolo del timeout: $ upright("Timeout") lr((t)) eq upright("EstimatedRTT") lr((t)) plus 4 dot.op upright("Deviation") lr((t)) $ dove $upright("Deviation") lr((t))$ è un #strong[margine d'errore] che dipende dall'RTT. === Prestazioni di TCP Introduciamo alcuni termini per misurare le performance: - tempo di propagazione: $upright("RTT") / 2$; - utilizzazione: percentuale di utilizzo di una risorsa in un intervallo di tempo; - (transmission) rate, #strong[throughput]: capacità trasmissiva della rete; - $upright("L") lr((upright("pkt")))$: lunghezza del pacchetto - tempo di trasmissione: $L / upright("Rate")$; Il #strong[tempo di trasferimento] di un pacchetto è dato da: $ 2 dot.op upright("tempo di trasmissione") plus upright("tempo di propagazione") $ Il tempo di trasmissione è raddoppiato perché bisogna considerare anche quello dell'acknowledgement. ==== Protocollo stop-and-wait Protocollo che invia #strong[un segmento alla volta] ed aspetta l'ACK prima di inviare il prossimo segmento. #figure([#image("images/5d52a1ef41d734d340e8221b7a993311.png")], caption: [ Protocollo stop-and-wait ] ) L'#strong[utilizzazione] del canale è: $ upright("tempo trasmissione") / upright("tempo totale") eq frac(T, R T T plus T) eq frac(L / R, R T T plus L / R) eq frac(4, 30 plus 4) eq 0.12 approx 10 percent $ Per ottenere un'utilizzazione migliore si utilizza un #strong[protocollo pipelined]. ==== Protocollo pipelined Si inviano più pacchetti alla volta anziché uno solo (ad esempio 3). Il successivo \"stock\" di pacchetti viene inviato solo quando si riceve l'ACK per lo \"stock\" precedente. #figure([#image("images/bbdaa89ef0f0d87bd23a55d458d140d8.png", width: 100%)], caption: [ Protocollo pipelined ] ) Questo approccio aumenta la complessità: - serve un #strong[buffer] per gestire i pacchetti, sia lato mittente (per tenere i dati inviati per cui non è ancora stato ricevuto l'ACK) sia lato destinatario (per mantenere le sequenze incomplete); - serve una #strong[sliding window] per definire il numero massimo di dati che il mittente può inviare senza prima aver ricevuto l'ACK La sliding window è un parametro #strong[dinamico] che si aggiorna continuamente durante l'esecuzione di TCP. === Sliding window La dimensione della sliding window (SWS, Sliding Window Size): - è dinamica; - è controllata dal destinatario ==== Sliding window del mittente $ upright("LSS") minus upright("LAR") lt.eq upright("SWS") $ - LAR \= Last Acknowledgement Received; - LSS \= Last Segment Sent; - SWS \= Sender Window Size #figure([#image("images/05eda5729f3732cf009c114c0c322f52.png", width: 100%)], caption: [ Sliding window mittente ] ) ==== Sliding window del destinatario $ upright("LAS") minus upright("LSR") lt.eq upright("RWS") $ - LAS \= Last Acknowledgement Sent; - LSR \= Last Segment Received; - RWS \= Receiver Window Size #figure([#image("images/67d35c34ba13a27a67dea848dd4f77e7.png", width: 100%)], caption: [ Sliding window destinatario ] ) Il destinatario scarta i pacchetti che sono \"più avanti\" rispetto alla sua sliding window, perché rimarrebbero per troppo tempo nel buffer di ricezione (e quindi sprecherebbero risorse). La dimensione della sliding window di ricezione dev'essere superiore a quella di invio ($upright("RWS") gt.eq upright("SWS")$). === Algoritmi per l'affidabilità in TCP ==== Algoritmo Go-Back-N Il destinatario invia degli ACK #strong[cumulativi] (non si invia un ACK per ogni pacchetto). Se il mittente non riceve un ACK, dovrà ri-trasmettere #strong[tutto] il blocco di pacchetti. Con questo approccio non c'è bisogno di gestire una sliding window lato destinatario per gestire il pipeling. Lo svantaggio principale è che il destinatario non è in grado di inviare un ACK per pacchetti che non sono consecutivi, esempio: - il mittente invia 3 pacchetti: 10, 20 e 30; - il destinatario riceve 10 e 30, ma non 20 - il destinatario non può inviare un ACK, perché non ha ricevuto tutti i pacchetti; - scade il timeout per l'ACK al mittente e deve quindi ri-mandare tutti e 3 i pacchetti (nonostante 2 pacchetti su 3 fossero stati ricevuti correttamente) ==== Algoritmo di ritrasmissione selettiva Ogni ACK è riferito solo ad un #strong[singolo] pacchetto. Sia mittente che destinatario devono gestire una sliding window. ==== Algoritmo usato da TCP TCP usa un ibrido tra ritrasmissione selettiva e Go-Back-N: - gli ACK sono cumulativi; - esiste un approccio di ritrasmissione selettiva Esempio: - il mittente manda i pacchetti 1, 2, 3 e 4; - il destinatario riceve i pacchetti 1, 2 e 4; - il destinatario si salva il pacchetto 4, ma risponde con ACK \= 2; - il mittente ri-trasmetterà i pacchetti 3 e 4, perché ha ricevuto un ACK \= 2; - il destinatario riceve i pacchetti 3 e 4 e risponde con ACK \= 4 Non è un approccio di ritrasmissione selettiva \"pulita\" (il mittente rischia comunque di mandare più volte gli stessi pacchetti). Questo approccio ibrido è utile anche in caso di delivery out-of-order: - il mittente invia i pacchetti (in ordine) 1, 2 e 3; - il destinatario riceve i pacchetti in ordine 1, 3 e 2; - alla ricezione del pacchetto 1, il destinatario risponde con ACK \= 1; - alla ricezione del pacchetto 3, il destinatario risponde ancora con ACK \= 1, ma si salva il pacchetto 3 nel buffer; - alla ricezione del pacchetto 2, il destinatario risponde con ACK \= 3 Con quest'approccio il mittente può ricevere più ACK per lo stesso pacchetto: - fino a 2 ACK, il 2° ACK (duplicato) viene ignorato; - 3 ACK per lo stesso pacchetto invece vengono interpretati come un #strong[ACK negativo] Il fatto di avere ACK cumulativi aiuta anche il mittente in caso di delivery out-of-order degli ACK stessi. Nelle opzioni di TCP è possibile richiedere di utilizzare un algoritmo di ritrasmissione selettiva pura anziché questo approccio ibrido. Oggi questa è la scelta preferita (vedi opzione #strong[SACK] di TCP). === Calcolo della dimensione della sliding window del mittente Per realizzare - controllo di flusso - controllo di congestione è necessario avere una dimensione #strong[dinamica] della sliding window. La dimensione della sliding window viene scelta come la dimensione minima fra: - congestion window - flow window L'ACK che il destinatario invia al mittente contiene: - sia quanti byte il destinatario ha ricevuto correttamente; - sia quanti byte il destinatario può ancora ricevere. Se il buffer di ricezione del destinatario è pieno, questo valore sarà pari a 0. In realtà se il destinatario ha esaurito il buffer, il mittente continua periodicamente ad inviargli dei pacchetti (vuoti). Questo per dare modo al destinatario di rispondere con un ACK che dice che è di nuovo disponibile. Per il controllo di congestione si usano un approccio #strong[slow start] ed #strong[AIMD] (Additive Increase, Multiplicative Decrease) sulla congestion window: - inizialmente la congestion window è molto piccola (slow start); - man mano che il mittente riceve degli ACK positivi, la dimensione della congestion window aumenta sempre di più (additive increase); - appena si verifica un timeout, il mittente cala drasticamente (multiplicative decrease) la dimensione della congestion window per rallentare Se si fa un grafico della velocità istantanea di TCP si ottiene un grafico a dente di sega. Alcuni algoritmi per il controllo di congestione utilizzano un approccio #strong[pro-attivo], cioè cercano di #strong[prevenire] la congestione piuttosto che #strong[reagire] ad essa. La velocità cala in modo diverso tra triplo ACK positivo e timeout. Generalmente il triplo ACK positivo viene considerato come una congestione meno grave rispetto ad un timeout, quindi la velocità cala molto meno. === Fairness di TCP TCP è un protocollo #strong[fair], ovvero cerca di \"comportarsi bene\" nei confronti degli altri protocolli/processi in esecuzione sulla macchina (cioè non \"ruba\" risorse più del necessario). Questa cosa in UDP non esiste: se si iniziano a spammare a manetta pacchetti UDP, le connessioni TCP potrebbero piantarsi perché si manda in congestione la rete. È compito del sistemista fare in modo che questi protocolli potenzialmente \"maleducati\" non diano problemi alla rete. === TCP vs UDP Nonostante le funzionalità offerte da TCP, ci sono comunque alcuni vantaggi nell'uso di UDP: - non c'è instaurazione della connessione, non ci sono #strong[stati] da dover conservare e gestire; - i pacchetti TCP sono più grandi di quelli UDP (20 byte header TCP vs 8 byte header UDP); - in caso di applicazioni che devono essere a bassissima latenza (es. real-time), il controllo di flusso fatto da TCP potrebbe avere impatti negativi sulle performance; - il delivery out-of-order non è un problema di tutte le applicazioni (ad esempio non lo è per HTTP); - in una rete locale si ha generalmente un'affidabilità molto più alta rispetto che su un collegamento in Internet. Potrebbe quindi non valere la pena fare tutto il 3-way handshake in questi casi; - non è sempre importante riceve tutti i pacchetti. In VoIP, per esempio, se si perde qualche pacchetto si sentirà un po' male la voce per un istante; - l'applicazione potrebbe re-implementarsi la gestione dell'affidabilità per i fatti suoi = Firewall Principi per la sicurezza nelle reti locali: - #strong[segmentazione]: partizionamento delle risorse fisiche e/o logiche (es. VLAN a livello 2); - #strong[segregazione]: definizione di politiche di #strong[controllo degli accessi] (es. firewall) #block[ #strong[Definizione]: firewall Un firewall è un sistema che ha il compito di #strong[segregare] il traffico tra due reti separate. ] #block[ #strong[Definizione]: Access Control List (ACL) Definizione di quali host e quali servizi sono consentiti e quali sono proibiti. ] Esistono 2 policy principali: - negazione implicita; - accettazione implicita I firewall si differenziano tra loro per: - tipologia (hardware o software); - punto in cui devono essere installati (sugli host o a livello di rete su un router); - protocolli supportati (firewall di livello 3 e 4); - tipo di analisi (stateless o stateful) Tipicamente i firewall agiscono come #strong[packet filter]. Tipologie principali di firewall: - #strong[screening router]: caso più comune. Ha il compito di filtrare pacchetti di livello 3 e 4; - #strong[stealth firewall]: versione più avanzata degli screening router. Tipicamente includono meccanismi di #strong[intrusion detecnion]. Concettualmente sono dispositivi di livello 2; - #strong[proxy firewall] (o #strong[application gateway]): implementano logiche applicative per analizzare in maniera estremamente dettagliata i pacchetti. Possono essere #strong[trasparenti] al client oppure no (transparent proxy firewall) L'approccio della #strong[defence-in-depth] prevede di utilizzare tra loro diverse tipologie di firewall. == Network design patterns === Single screening router Singolo router, posto ai bordi della rete, con logica di packet filtering. #figure([#image("images/493d024e8134ee29cad353806d529377.png")], caption: [ Single screening router ] ) Pattern poco costoso e semplice da realizzare, ma con diversi svantaggi: - singolo layer di difesa; - single point of failure; - la rete interna non è segregata; - poca scalabilità (un singolo router ha un limite al numero di host che può gestire) === Dual-homed firewall Router e firewall sono su dispositivi separati: #figure([#image("images/00d093ae26bd2eb31828371b26fa6c73.png")], caption: [ Dual-homed firewall ] ) Il dual-homed firewall implementa il packet filtering. Può essere anche un application proxy. La rete interna e quella esterna sono ben separate. Gli svantaggi sono gli stessi del single screening router: - singolo layer di difesa; - single point of failure; - poca scalabilità rispetto alla dimensione della rete === Bastion host e DMZ #figure([#image("images/6fe2c443cfa0bd519b1f0fa2d9dbafbd.png")], caption: [ Sceened-host gateway ] ) Il #strong[bastion host] è un proxy firewall che ha compito di ispezionare il traffico tra la rete sicura (quella interna) e quella insicura. Lo screening router implementa logiche di packet filtering e lascia passare soltanto il traffico diretto al bastion host, dove verrà analizzato ulteriormente. Questo modello può prevedere anche una #strong[DMZ] (De-militarized Zone), ovvero una #strong[rete intermadia] tra quella interna e quella esterna. - per accedere gli host in DMZ dall'esterno non occorre passare dal bastion host; - per accedere agli host in DMZ dalla rete interna invece sì La DMZ è interessante perché il suo scopo è proteggere una #strong[sottorete] della rete interna. === Screened subnet Tutti i design precedenti vengono accorpati: #figure([#image("images/a3be25649f159343a55fbd67684c56d1.png")], caption: [ Screened subnet ] ) Si ha una difesa multi-livello e si implementano correttamente segmentazione e segregazione. - il firewall esterno filtra il traffico tra la rete esterna e il bastion host/DMZ; - il firewall interno protegge sia la rete interna da attacchi esterni, sia la DMZ da attacchi provenienti dalla rete interna = DNS - Domain Name System Il DNS definisce come gestire i #strong[nomi] su Internet. Il DNS non è un protocollo, ma un intero #strong[sistema]. I sistemi di identificazione per i protocolli di rete usano di solito degli #strong[indirizzi binari]. Il DNS è un sistema parallelo che utilizza delle #strong[stringhe alfanumeriche] (cioè un #strong[nome]) per identificare gli interlocutori. Il DNS è un sistema #strong[geograficamente distribuito]. == Hostname Il DNS è un sistema per trasformare indirizzi IP in nomi. L'idea è quella di avere una #strong[corrispondenza biunivoca] tra indirizzi IP e nomi, in modo da riuscire a contattare un host tramite il suo nome anziché il suo indirizzo. Nel contesto del DNS, questi nomi vengono chiamati #strong[hostname]. Si tratta di una sequenza di label separate dal carattere \"`.`\". In origine in un hostname potevano esserci solo caratteri ASCII-7, mentre oggi si possono usare anche caratteri non-ASCCI (es. Unicode) - in questo caso si parla di regole #strong[IDN] (Internationalized Domain Name). Un hostname può essere lungo al massimo 256 caratteri. Un hostname si dice #strong[canonico] se permette di identificare #strong[univocamente] un host in Internet. Gli hostname si leggono #strong[da destra verso sinistra]: si va dal livello di dettaglio più alto a quello più specifico. Un hostname canonico è composto da: - #strong[dominio] (le due label più a destra); - hostname #strong[relativo] (quello che rimane una volta tolto il dominio) Gli hostname, oltre all'usabilità, forniscono anche flessibilità rispetto agli indirizzi IP, per esempio: - il client non ha più bisogno di sapere se l'host che vuole contattare ha un indirizzo IP v4 o v6; - se il server viene spostato su un altro host, il suo indirizzo IP cambia, mentre il suo hostname resta lo stesso; Un singolo hostname può essere mappato anche a più di un indirizzo IP (tecnica usata anche per distribuire il carico su diverse macchine). In questi casi il DNS restituisce una lista di indirizzi IP e il client sceglie il 1° indirizzo di questa lista. È compito del DNS far ruotare gli elementi di questa lista. L'utilizzo del DNS comporta un overhead. Per migliorare le performance si usano diverse tecniche #strong[caching] a più livelli. == Reverse lookup Meccanismo inverso del DNS dove si ottiene un hostname a partire dal suo indirizzo IP. == Name server Sono i server che istanziano il sistema DNS. Il name server è il server che viene invocato per effettuare il lookup (o reverse lookup). Il DNS è #strong[decentralizzato], ogni name server è #strong[autoritativo] solo su un #strong[insieme limitato] di nomi. In origine il lookup veniva fatto utilizzando UDP. Oggi, sebbene UDP sia ancora il default, esistono diverse alternative orientate alla #strong[privacy] (es. DNS over TLS, DNS over HTTPS, ecc.). Per l'interazione tra name server si usa TCP. == Cybersquatting e punycode Questi 2 termini identificano delle pratiche malevole di uso del DNS. Nel cybersquatting, una persona riserva un nome molto simile a quello di un \"brand\" famoso (es. `g0ogle.com`) per motivi di phishing/truffe. Nel punycode si utilizza invece lo stesso identico nome di un \"brand\" famoso, ma con un'altra codifica (così il nome alfabetico è identico a quello vero, ma in binario i due nomi sono diversi). Esistono diverse regole che le autorità che gestiscono i nomi devono applicare in modo da evitare questi comportamenti scorretti. == Organizzazione dello spazio dei nomi La label più a destra si chiama #strong[top level domain] (TLD), mentre la 2° label più a destra si chiama #strong[second level domain] (SLD). TLD ed SLD sono presenti in tutti i nomi, mentre le altre label sono facoltative. I TLD più famosi sono i #strong[country code TLD] (ccTLD), cioè TLD associati a paesi (es. `.it`, `.uk`, ecc.). I #strong[generic TLD] invece non sono associati a nessuna nazione in particolare, ma ad uno \"scopo\" generico: - `.com` per scopi commerciali; - `.gov` per scopi governativi; - ... Gli #strong[infrastructure TLD] servono invece per scopi interni al DNS. Un esempio è il TLD `.arpa`, utilizzato per il reverse lookup. Recentemente DNS è stato esteso per permettere di registrare TLD arbitrari. Gli SLD sono associati alle entità che gestiscono il dominio stesso (es. `unimore.it`). Mediante TLD ed SLD si possono creare delle #strong[gerarchie] di domini. La root di questa gerarchia non sono in realtà i TLD, ma esiste una root \"nascosta\" (semplicemente \"`.`\") che ha come figli tutti i vari TLD: #figure([#image("images/83fbabe13828ba43b7468fcd28e74640.png")], caption: [ Gerarchia di nomi ] ) Per risolvere un nome si percorre questa gerarchia #strong[dalla radice alla foglia]. I #strong[root name server] sono i server che permettono di iniziare questo processo di risoluzione. I client quindi devono conoscere soltanto gli indirizzi IP dei root name server. Il #strong[local name server] è un server presente nella rete locale del client a cui è affidato il compito di contattare tutti gli altri name server. Nel caso di connessioni domestiche, l'IP del local name server viene fornito dall'ISP. I local name server hanno un ruolo importante nel meccanismo di caching. La #strong[zona] è l'insieme dei domini per i quali il name server è autoritativo, ovvero può dare direttamente una corrispondenza IP $arrow.l.r$ nome senza dover passare per altri name server. Il name server autoritativo è l'unico che può dire che un dominio non esiste. Nelle risposte del name server c'è un campo che indica se la risposta è autoritativa oppure se proviene da informazioni cachate. === DNS su Linux In ambiente Linux il local name server è configurato nel file `/etc/resolv.conf`. Tipicamente questo file viene popolato tramite DHCP o altre procedure automatiche. In alcuni casi l'IP del local name server potrebbe non essere in questo file, perché alcune distro (es. Fedora) utilizzano un #strong[processo locale] per gestire la risoluzione dei nomi. == Name server primari e secondari Per questioni di ridondanza esistono dei meccanismi di replicazione nei protocolli DNS. I name server primari vengono detti #strong[master]. Tutti i name server secondari devono essere sincronizzati con il master. Il #strong[master file] è il database che contiene le mappature IP $arrow.r$ nomi. Lo scambio di dati periodico che avviene tra name server primari e secondari viene detto #strong[zone transfer] e riguarda solo la zona in cui quel name server è autoritativo. == Resource record Il #strong[resource record] (RR) è una riga del database di un name server. Esistono diversi tipi di resource record: - `A`: rappresenta effettivamente il mapping nome $arrow.r$ IP. Serve per gestire la risoluzione diretta di un nome. È possibile che contenga una lista di indirizzi IP. - `AAAA`: equivalente al record `A`, ma usato per IPv6; - `NS`: mapping tra zona e name server autoritativo per essa. Se il name server risponde con un record `NS`, tipicamente nella risposta c'è anche un record `A` che contiene l'IP del name server da contattare; - `SOA`: contiene dei parametri di una zona (es. TTL della cache, ecc.); - `MX`: record speciale utilizzato dal sistema e-mail; - `CNAME`: record utilizzato per gestire gli #strong[alias] (più hostname associati allo stesso IP); - `PTR`: record usato per il reverse lookup; - `TXT`: ufficialmente è un campo di testo libero, ma in realtà viene usato per inserire del testo machine-readable per poter essere usato da altri protocolli/sistemi (es. protocollo SPF nel sistema e-mail) Ogni record contiene anche un TTL che indica per quanto tempo sarà ancora valido. === Record PTR e reverse lookup #figure([#image("images/ab32ca8df7a21c68e1c9fd8a73a66faf.png")], caption: [ Esempio record `PTR` ] ) I record `PTR` mappano un indirizzo IP all'hostname corrispondente. Gli indirizzi IP nei record PTR hanno però 2 particolarità: - sono scritti al contrario (cioè, nella figura sopra, la 1° riga mappa l'indirizzo `172.16.58.3`); - terminano tutti con `.in-addr.arpa` Gli indirizzi IP nei record `PTR` vengono scritti al contrario per conservare la #strong[scalabilità]: - gli hostname si leggono da destra (parte più generale) verso sinistra (parte più specifica); - gli indirizzi IP si leggono da sinistra (parte più generale, net ID) verso sinistra (parte più specifica, host ID) quindi con questo trucchetto è posssibile inserire tanti record (es. `212.in-addr.arpa`, `52.212.in-addr.arpa`, ecc.) ognuno specifico per un certo livello di dettaglio, esattamente come si può fare con gli hostname (es. `.`, `.com`, `google.com`, ecc.). Ad ogni indirizzo IP viene poi aggiunto il dominio `.in-addr.arpa` perché ciò che sta nel record `PTR` non è un indirizzo IP, ma è a tutti gli effetti un hostname. Con queste tecniche quindi il reverse lookup si riconduce allo stesso problema del lookup (ottenere l'IP partendo dal nome). == Meccanismo di risoluzione Il #strong[resolver] può fare 2 tipologie di #strong[query] (richieste di risoluzione): - query #strong[ricorsive]: viene fatta dal resolver in esecuzione sul client finale verso il local name server. Chiede al local name server di gestire anche tutte le eventuali richieste aggiuntive necessarie per ottenere l'IP finale; - query #strong[iterative]: fatte dal local name server ai name server autoritativi. Una query iterativa tipicamente non restituisce immediatamente l'IP finale, ma l'IP di un altro name server che gestisce quella zona, a cui dovrà essere fatta la richiesta #figure([#image("images/e6500362503e9a36eb540975d75bf500.png")], caption: [ Esempio completo di query al DNS ] ) == Registrar Il registrar è l'organizzazione autorizzata a registrare i nomi nell'ambito di un certo dominio. I registrar di solito gestiscono la registrazione dei SLD associati ad alcuni TLD. = DHCP - Dynamic Host Configuration Protocol Protocollo applicativo basato su UDP che serve per configurare il livello 3 di un host. La maggior parte delle infromazioni vengono trasmesse tramite protocolli H2N. DHCP è il successore del protocollo RARP (il \"reverse\" di ARP), ma non ha nulla in comune con esso. DHCP si basa sul paradigma client-server: - il server è configurato staticamente; - i client DHCP si collegano ad una rete che contiene un server DHCP. Di solito i client non conoscono l'IP del server DHCP (e, in generale, non hanno nemmeno idea di come sia fatta la rete alla quale si sono connessi) L'obiettivo di DHCP è che dopo la sua esecuzione sul client, questi sia in grado di interagire con un #strong[qualunque host] presente su Internet. Deve quindi fornire tutto quello che serve al client per permettergli di connettersi alla rete. DHCP non è adatto per essere usato sui router. L'amministratore deve prevedere delle #strong[policy di rete] in un punto centralizzato (cioè il server DHCP) in modo che i client possano utilizzarle per auto-configurarsi. DHCP è molto #strong[scalabile]: - il server DHCP è facilmente #strong[replicabile]. Una parte fondamentale di DHCP è saper riconoscere il server autoritativo in presenza di più server nella rete; - DHCP può funzionare su una o più #strong[subnet] di rete. Questa è una caratteristica fondamentale che contraddistingue DHCP dai suoi predecessori (RARP ecc.). DHCP si basa su #strong[messaggi broadcast locali], come ARP. == Policy di rete Le policy di rete sono i parametri di configurazione di DHCP, ad esempio: - come assegnare gli indirizzi IP ai vari host; - regole di routing; - comunicazione del local name server da utilizzare Le policy sono #strong[persistenti] al riavvio del server e client DHCP. L'assegnazione di un indirizzo IP ad un client da parte di DHCP può essere #strong[statica] (lo stesso client riceve sempre lo stesso IP) o #strong[dinamica] (l'IP viene scelto da un pool di indirizzi). Si definisce #strong[lease] il tempo per cui un client possiede un certo indirizzo IP. DHCP è molto flessibile per quanto riguarda la gestione della rete, ad esempio funziona perfettamente anche in reti configurate in parte staticamente e in parte con DHCP. DHCP possiede diversi meccanismi, sia sul client che sul server, per assicurarsi che l'IP che viene assegnato non vada in conflitto con altri host. Il database delle policy è un database key-value: - la key identifica univocamente l'host (tipicamente si usa il MAC address); - il value è l'indirizzo IP da assegnare all'host (o il range dal quale sceglierlo), più eventuali altre configurazioni (gateway, DNS, ecc.) == Realizzazione del paradigma client-server con DHCP Nonostante DHCP distingua client e server, entrambi si mettono in ascolto su una porta: `67/udp` il server e `68/udp` il client (anche il client quindi usa una well-known port). Il motivo per cui anche il client si mette in ascolto su una porta è dovuto al fatto che, non essendo ancora configurati, devono avere qualcosa di noto al server (la porta, in questo caso) per poter ricevere le sue risposte. Tutti i client sono sulla stessa porta `68/udp`. == Pacchetto DHCP #figure([#image("images/191b78db742f5afa9f7572309344be55.png")], caption: [ Pacchetto DHCP ] ) === OP - 1 byte Tipo di messaggio (request o response). Si tratta in realtà di un'informazione ridondante (si potrebbe capire guardando le porte sorgente/destinazione del pacchetto UDP), ma viene comunque inserita esplicitamente. === xid - 4 byte ID della transazione. Serve per identificare i pacchetti che fanno parte della stessa sequenza di request/response (è un po' la re-implementazione del sequence number di TCP). Viene scelto in modo casuale #underline[dal client] nel momento in cui vuole iniziare a comunicare con il server. === ciaddr - 4 byte Indirizzo IP attuale del client. Questo campo può contenere informazioni se il client si era già connesso alla rete precedentemnte e aveva già ottenuto un indirizzo IP dal server DHCP. === yiaddr - 4 byte Indirizzo IP #strong[proposto] dal server al client. Il client non è obbligato ad accettarlo. === siaddr - 4 byte Campo popolato se i server DHCP sono ridondati o se sono dei #strong[relay server]. === chaddr - 4 byte MAC address del client, inviato dal server al client. Anche questa è un'informazione ridondante (si potrebbe guardare il campo del frame Ethernet), ma è inserita esplicitamente per far funzionare DHCP anche su reti differenti (es. in caso di relay server). === options Campo di dimensione variabile che il server può usare per passare al client altre configurazioni non legate all'indirizzo IP (es. DNS server, ecc.). == Messaggi tipici del protocollo DHCP === OP \= 1 - da client a server (DHCP request) - DHCPDISCOVER: utilizzado da un client #underline[non ancora configurato] per capire se nella rete a cui si è connesso esiste un DHCP server; - DHCPREQUEST: utilizzato da un client che si era già collegato alla rete in precedenza per chiedere conferma per poter utilizzare un indirizzo IP che gli era rimasto in memoria. Questo tipo di messaggio viene usato anche dopo che il client ha ricevuto la proposta dal server, per chiedergli conferma prima di utilizzare l'indirizzo IP proposto; - DHCPDECLINE: il client rifiuta l'IP proposto dal server. Questo può capitare se è il client a rilevare un conflitto di indirizzi con l'IP ricevuto dal server (scenario che può capitare se client e server DHCP sono su reti differenti); - DHCPRELEASE: usato quando il client si disconnette alla rete, in modo da comunicare al server il rilascio dell'indirizzo IP; - DHCPINFORM: simile ad una DHCPREQUEST, ma il client chiede altri parametri di configurazione (DNS server, ecc.) e non un indirizzo IP === OP \= 2 - da server a client (DHCP response) - DHCPOFFER: offerta di un indirizzo IP al client; - DHCPACK: conferma ad una DHCPREQUEST; - DHCPNAK: rifiuto ad una DHCPREQUEST == Workflow di messaggi - caso più comune + DHCPDISCOVER: il client cerca di capire se nella rete c'è un server DHCP; + DHCPOFFER: il server rileva che c'è un client e gli offre un indirizzo IP, eventualmente dopo aver verificato (es. tramite protocollo ARP) che non sia già utilizzato da qualcun altro; + DHCPREQUEST: il client riceve l'offerta del server e gli chiede conferma dell'IP ricevuto; + DHCPACK: il server conferma l'indirizzo IP. Il client ha terminato la fase di configurazione È interessante notare che il sistema operativo del client accetta sempre il pacchetto IP contenente la DHCOFFER del server. Questa è una particolarità di tutti i S.O.: se ad un'interfaccia di rete non è assegnato un indirizzo IP (come in questo caso), tutti i pacchetti verranno sempre accettati. == Transaction ID e note sulla sicurezza Se il client riceve un pacchetto DHCP con un transaction ID non scelto da lui, scarterà quel pacchetto. Se non ci fosse il TXID, un server DHCP malevolo potrebbe spammare continuamente in rete delle DHCPOFFER finché non si connette un client che le accetta. Quello che può succedere è una #strong[race condition] tra il server DHCP malevolo e quello valido: + entrambi ricevono la DHCPDISCOVER del client con all'interno il TXID da utilizzare; + i due server \"fanno a gara\" per chi risponde prima al client In caso di più pacchetti con lo stesso TXID, il client accetterà soltanto il 1°. = WWW - World Wide Web Spesso WWW è usato come sinonimo di Internet, ma in realtà si tratta di due cose ben distinte: - Internet è la rete IP; - WWW è un insieme di protocolli e strumenti che sfruttano la rete Internet per offrire un certo servizio Protocolli e standard alla base di WWW: - TCP; - DNS; - paradigma client server (server \= web server, client \= browser); - HTTP: protocollo per scambiare le informazioni nel WWW; - URL: standard per il #strong[naming delle risorse] all'interno degli host. È indipendente dal WWW (infatti gli URL esistono anche in altri contesti); - HTML: standard di markup (rappresentazione delle informazioni). Grazie ad esso è possibile creare una #strong[rete di informazioni] utilizzando gli #strong[hyperlink] == Meccanismi di naming del web - URI (Uniform Resource Identifier): identifica univocamente una risorsa su Internet e può eventualmente contenere le informazioni su come ottenerla; - URL (Uniform Resource Locator): identifica univocmanete una risorsa su Internet e contiene sempre le informazioni su come accedervi; - URN (Uniform Resource Identifier): identifica univocamente una risorsa su Internet e non contiene mai le informazioni per ottenerla == Struttura di un URL #block[ `scheme ":" ["//" authority] path ["?" query] ["#" fragment]` `authority = [userinfo "@"] host [":" port]` ] Il path è composto da tanti #strong[segmenti], separati da `/`. Ogni segmento può specificare dei parametri che il server potrà interpretare. La query string serve per indicare dei #strong[parametri d'azione] su una risorsa. Il fragment identifica una specifica #strong[porzione] di una risorsa alla quale il client è interessato. L'URL potrebbe essere case sensitive oppure no: - l'hostname è case-insensitive (dovuto al DNS); - per il path invece dipende dal web server utilizzato (alcuni sono case-sensitive, altri no) == Protocollo HTTP Protocollo basato sui paradigmi #strong[request-response] e #strong[client-server] usato per il trasferimento di informazioni \"ipertestuali\" (cioè non solo testo ma anche file, immagini, ecc.). HTTP utilizza TCP come protocollo trasporto. HTTP è #strong[stateless]. Per gestire lo stato si utilizzano i #strong[cookie]. \ I cookie sono dei #strong[token opachi]: il client non deve farci nulla se non salvarseli e ri-mandarli al server alla prossima richiesta. === Versioni di HTTP La versione iniziale di HTTP era la 1.0. Oggi si usano HTTP 1.1, 2.0 e si sta iniziando a diffondere HTTP 3.0. La differenza principale tra HTTP/1.0 e HTTP/1.1 è il #strong[pipelining]: - con HTTP/1.1 si possono richiedere #strong[più risorse contemporaneamente], senza dover aspettare di aver prima ottenuto la risposta precedente; - HTTP/1.0 invece è un protocollo stop-and-wait Il server è obbligato a rispondere con la stessa major version di HTTP usata dal client. La minor version, invece, può anche essere diversa. === Struttura del messaggio HTTP HTTP è un protocollo #strong[testuale]: i messaggi sono codificati in ASCII e non in binario. ==== Request #figure([#image("images/eb4b4e058fe09d75d6f6a1e9c2aa175f.png")], caption: [ Request HTTP ] ) Un header degno di nota è `Host`, che contiene l'hostname del server. Si tratta di un header opzionale nella teoria, ma ormai richiesto da tutti i web server in quanto fondamentale per implementare il #strong[virtual hosting]. === Response #figure( image("images/9a2f3a15702f4696e64cbb0d81cadb52.png", height: 23%), caption: [ Response HTTP ] ) Il server deve sempre includere l'header `Content-Type` nelle sue risposte. Il content type inoltre è autoritativo: se nel response body c'è un video ma il content type è `text/plain`, quel body dovrà essere interpretato come testo. == HTML Un #strong[documento ipertestuale] è un documento con testo e altro contenuto multimediale (audio, immagini, ecc.). Nel contesto dell'HTML, le risorse multimediali incluse nel documento si chiamano #strong[embedded objects]. Il browser ha un engine che mette insieme i vari componenti di una pagina e la renderizza sullo schermo. == User agent Termine tecnico con cui si indica un client HTTP. == MIME Sotto-protocollo di HTTP specializzato per capire il #strong[tipo] di una risorsa. MIME in realtà nasce con SMTP e non con HTTP. = Protocolli sicuri I protocolli sviluppati all'inizio di Internet non tengono in considerazione la #strong[sicurezza]. Alcuni protocolli (Ethernet, TCP, IP) tengono in considerazione l'#strong[affidabilità], ma solo rispetto a #strong[guasti] nella rete. Nessuno di questi protocolli tiene in considerazione l'affidabilità rispetto ad #strong[avversari umani] (es. indirizzi IP/MAC falsificati). Dal punto di vista della sicurezza, un attaccante può violare: - la #strong[confidenzialità], cioè riesce a leggere informazioni che dovrebbero essere a lui segrete; - la #strong[data origin authenticity], ovvero l'autenticità dell'origine dei dati (l'attaccante può impersonare qualcun altro) Un protocollo sicuro deve quindi garantire: - confidenzialità dei \"dati che si spostano\" (#strong[data in motion]); - #strong[autenticità] La protezione dei \"dati in movimento\" è la ragione della nascita della #strong[crittografia]. #block[ La crittografia protegge i dati nel momento in cui l'attaccante ne viene in possesso. ] Le garanzie di sicurezza che si cercano sono diverse: - confidenzialità; - #strong[integrità] rispetto ad #strong[attaccanti umani]. Il destinatario deve riuscire ad accorgersi se il messaggio è stato alterato; - #strong[autenticità]: il destinatario dev'essere certo del mittente del messaggio; - #strong[disponibilità] (availability): i dati non devono essere resi inaccessibili (es. tramite attacchi di tipo DoS) In generale, i protocolli sicuri non coprono la disponibilità, perché questo è un aspetto che si gestisce in fase di #strong[progettazione del sistema]. == Crittografia Nel contesto dei protocolli sicuri, l'informazione è sempre #strong[cifrata]. La crittografia è una tecnica che #strong[trasforma] il messaggio in modo da rendere impossibile risalire al messaggio originale. La crittografia non è da confondere con: - #strong[steganografia]: tecnica per #strong[nascondere] le informazioni all'interno di un altro messaggio sensato; - #strong[crittoanalisi]: tecniche che cercano di rompere la crittografia La crittografia esiste da secoli e si è evoluta di pari passo con le #strong[tecniche di comunicazione]: - #strong[crittografia classica] fino all'avvento della radio; - #strong[crittografia moderna] dall'avvento della radio in poi La crittografia classica: - si basava sulla #strong[segretezza dell'algoritmo]; - garantiva soltanto confidenzialità, ma non integrità; - si basava sul concetto di #strong[envelope]: ogni messaggio è #strong[indipendente] dagli altri (come nella comunicazione orientata ai pacchetti) La crittografia moderna, invece: - si basa sulla #strong[segretezza della chiave], l'algoritmo è pubblico; - cerca di garantire anche l'integrità oltre che la confidenzialità; - si basa sulla diffocoltà nel risolvere dei #strong[problemi matematici] complessi (es. logaritmo discreto, fattorizzazione di numeri primi molto grandi) Le tecniche di crittografia si possono usare anche in contesti che non riguardano la comunicazione, per esempio per la protezione dei \"#strong[data at rest]\". Ognuno di questi scenari richiede lo sviluppo di un protocollo differente. === Cryptographic settings Con questo termine si indicano le informazioni che delineano come un sistema deve funzionare: - chi partecipa; - come comunicano i partecipanti; - quali informazioni si scambiano; - ... Si dividono in #strong[symmetric settings] e #strong[asymmetric settings], che danno origine rispettivamente alla #strong[crittografia simmetrica] e #strong[crittografia asimmetrica]. === Visione modulare della crittografia moderna La crittografia moderna è divisa in #strong[moduli]: #figure([#image("images/e268eb0d8592f108a6d74aeeaa3d7bce.png")], caption: [ Moduli della crittografia moderna ] ) - alla base ci sono dei #strong[concetti matematici] che mettono a disposizione delle #strong[primitive]; - a partire da queste primitive si sviluppano tecniche orientate alla sicurezza; - al livello più alto ci sono i protocolli e le applicazioni sicure, ovvero qualcosa di #strong[direttamente utilizzabile] nel mondo reale === Schemi di crittografia simmetrica Un framework #strong[probabilistico] mette a disposizione quest'interfaccia: - `keygen([size]) → key` - `encrypt(key, plaintext) → ciphertext` - `decrypt(key, ciphertext) → plaintext` La funzione `encrypt` #underline[non è deterministica]: a partire dallo stesso input deve restituire un output #underline[sempre diverso]. Input e output di queste funzioni sono #strong[binari]. Se non si hanno a disposizione dei dati binari, bisogna prima convertirli in questo formato utilizzando una #strong[codifica] (che è #strong[indipendente] dalla crittografia) e poi applicare la cifratura. La crittografia non protegge la #strong[dimensione] del testo: la lunghezza del testo cifrato dipende dalla lunghezza del testo in chiaro (in alcuni casi, queste due dimensioni coincidono). Quando anche la dimensione del dato è importante, bisogna prevedere delle tecniche di #strong[padding] in modo che tutti i dati abbiano sempre la stessa dimensione. Un framework #strong[determinisitco] è fatto in questo modo: - `keygen([size]) → key` - `encrypt(key, {n|iv}, plaintext) → ciphertext` - `decrypt(key, {n|iv}, ciphertext) → plaintext` Nonce ed initialization vector hanno scopi diversi: - il nonce dev'essere #strong[sempre diverso] ogni volta che si esegue una cifratura utilizzando la stessa chiave. La sua caratteristica è l'#strong[univocità]. Un nonce può essere implementato molto facilmente con un #strong[contatore]; - l'initialization vector è un vettore di bit scelti in modo #strong[casuale] (o pseudo-casuale). La sua caratteristica è l'#strong[imprevedibilità]. Utilizzare più volte lo stesso nonce/IV potrebbe avere conseguenze più o meno gravi, a seconda dello schema di cifratura: - potrebbe compromettere irrimediabilmente la sicurezza dello schema; - potrebbe portare alla creazione di un pattern deterministico, fornendo informazioni utilissime ad un potenziale attaccante I framework probabilistici utilizzano al loro interno un framework deterministico e si occupano di generare un nonce/IV sempre diverso. Con i framework deterministici, invece, è l'utente che usa il framework a doversi occupare di generare nonce/IV sempre diversi. #figure([#image("images/0d7b3287e73e5f2b43b52c252342e56d.png")], caption: [ Schema probabilistico e schema deterministico ] ) === Funzioni hash Garantiscono l'#strong[integrità] dei dati. Una funzione hash prende in input dei dati binari di dimensione arbitraria e restituisce un output di dimensione costante. L'output di una funzione hash viene chiamato hash o #strong[digest] o checksum. La dimensione del digest non dipende dall'input, ma solo dalla funzione. Una funzione hash è #strong[crittografica] se rilevare le #strong[collisioni] è impossibile o impraticabile. Esempi di funzioni hash crittografiche: - MD5 (deprecato); - SHA1 (deprecato); - SHA2 e SHA3 (standard al momento riconosciuti) SHA2 e SHA3 sono delle #strong[famiglie] di funzion. Un esempio di funzione hash è SHA2-256. Le funzioni hash non richiedono l'utilizzo di una chiave. Le funzioni hash non possono essere utilizzate #strong[direttamente] per controllare l'integrità di un messaggio rispetto ad avversari umani. Il destinatario deve conoscere #strong[in anticipo] l'hash del messaggio. Le funzioni hash non garantiscono #strong[autenticità]. === Message Authentication Code (MAC) Simili alle funzioni hash, ma oltre al messaggio richiedono in input anche una #strong[chiave]. L'output di queste funzioni viene chiamato #strong[tag] ed è di dimensione costante. Le funzioni MAC garantiscono l'#strong[autenticità] di un messaggio. Chi non ha accesso alla chiave non può più manipolare il messaggio senza che il destinatario se ne accorga. Non tutte le funzioni MAC sono implementate con delle funzioni hash. È perciò fuorviante chiamare le funzioni MAC \"funzioni hash con chiave\". Le funzioni MAC implementate con funzioni hash si chiamano funzioni #strong[HMAC]. Le funzioni hash e MAC non garantiscono #strong[confidenzialità], perché sono #strong[deterministiche]: se gli input di un'applicazione che usa delle funzioni hash/MAC sono enumerabili, allora è molto facile \"invertire\" queste funzioni. Per avere una funzione MAC non è sufficiente passare ad una funzione hash la chiave concatenata al messaggio (anzi, una cosa del genere è un grosso problema di sicurezza). === Replay attack Attacco in cui l'avversario invia una copia dello stesso messaggio al destinatario, facendogli credere che siano arrivati 2 messaggi anziché uno solo. #figure([#image("images/05601b43daadceff683ff4379ddf7f54.png", width: 100%)], caption: [ Replay attack ] ) Le funzioni MAC riescono a garantire l'autenticità del singolo messaggio, ma non dell'intero #strong[flusso] di comunicazione. Per difendersi dai replay attack, è necessario inserire nel messaggio un #strong[identificatore univoco]: il destinatario accetterà il messaggio solo se fa riferimento ad un identificatore che non ha già incontrato in precedenza. #figure([#image("images/574d35378a183d91a25b9722c8bfb508.png")], caption: [ Difesa dal replay attack ] ) === Reflection attack Simile al replay attack, ma il messaggio viene mandato al mittente stesso: #figure([#image("images/00572627d872e8ea4fae542a8ada3977.png")], caption: [ Reflection attack ] ) Se mittente e destinatario usano lo stesso tag, al mittente sembrerà di aver ricevuto una risposta corretta dal destinatario. Per difendersi da questo attacco ci sono 2 metodi: - si aggiunge ai metadati anche la #strong[direzione] del messaggio; - si usano due tag diversi per mittente e destinatario === Cifratura autenticata La cifratura \"normale\" garantisce confidenzialità. La cifratura autenticata garantisce integrità e autenticità. Gli standard moderni di solito forniscono un'interfaccia #strong[AEAD] (Authentication Encryption with Associated Data) fatta in questo modo: - `keygen([size]) → key` - `encrypt(key, {nonce|iv}, a, plaintext) → ciphertext` - `decrypt(key, {nonce|iv}, a, ciphertext) → plaintext` `a` è un parametro opzionale che contiene dei dati da non cifrare, ma dei quali si vuole garantire l'autenticità. Se viene specificato il parametro `a`, il messaggio cifrato conterrà anche un tag per garantire l'autenticità del messaggio. La funzione `decrypt` effettua il controllo di autenticità #strong[prima] di decifrare il messaggio. Questo standard è stato realizzato perché è comune per le applicazioni avere sia dati da cifrare che dati da non cifrare (perché necessari per il funzionamento dell'applicazione stessa), ma di cui si vuole garantire l'integrità. Esempio di dati associati: alcuni campi dell'header di TCP (es. sequence number). === Schemi asimmetrici La crittografia asimmetrica cerca di risolvere un problema fondamentale della crittografia simmetrica: la #strong[distribuzione della chiave] tra mittente e destintario. Nella crittografia asimmetrica, ogni partecipante ha una #strong[coppia di chiavi] per cifrare e decifrare il messaggio. Per comunicare con altri, ogni entità deve comunicare solo la propria chiave pubblica. Chiave pubblica e chiave privata sono correlate matematicamente. La cifratura asimmetrica, da sola, garantisce confidenzialità ma non autenticità. Per garantire anche l'autenticità, è necessario aggiungere al messaggio una #strong[firma digitale], la quale dà anche garanzie di #strong[non repudiabilità]. #figure([#image("images/53f1f7180133e15b171a1f7c2b78fe5a.png", width: 100%)], caption: [ Firma digitale ] ) Firma digitale e cifratura asimmetrica si possono combinare, in modo simile a MAC e cifratura simmetrica. === Scambio sicuro di chiavi Le funzioni di cifratura asimmetrica sono ordini di grandezza più complesse rispetto a quelle per la cifratura simmetrica, quindi si preferisce generare due chiavi simmetriche e scambiarsele utilizzando la crittografia asimmetrica. Scenario: Alice e Bob vogliono scambiarsi delle chiavi su un canale #strong[insicuro]. Prima idea: Alice genera una chiave `k`, la cifra utilizzando la chiave pubblica di Bob e gliela manda. Problema: quest'approccio è vulnerabile ad attacchi di tipo man-in-the-middle: Eve potrebbe inserirsi nella comunicazione, generare una chiave $k prime$, cifrarla con la chiave pubblica di Bob ed inviargliela: #figure([#image("images/228066a978dbe548b7535c411be88081.png", width: 100%)], caption: [ Man in the middle ] ) Bob non ha nessun modo per verificare che la chiave che gli arriva gli sia stata mandata da Alice. È necessario quindi aggiungere uno schema di firma digitale. ==== Schema Diffie-Hellman Schema per lo scambio sicuro di chiavi che si basa sul #strong[logaritmo discreto]. In questo problema si definisce un insieme #strong[discreto] di numeri e si eseguono tutte le operazioni in modulo (in particolare l'elevamento a potenza), in modo da far rimanere il risultato all'interno dello stesso insieme. Esempio: $ Z_11 eq lr({0 comma 1 comma 2 comma 3 comma 4 comma 5 comma 6 comma 7 comma 8 comma 9 comma 10}) $ $ 3^7 #h(0em) mod med 11 eq 9 $ Data la base 3 e il risultato 9, risalire all'esponente 7 è un problema difficile. Lo schema di Diffie-Hellman sfrutta questo problema e le proprietà delle potenze: - Alice genera una chiave $a$ e calcola $g^a$; - Alice manda a Bob il valore di $g^a$; - Bob genera una chiave $b$ e calcola $g^b$; - Bob manda ad Alice il valore di $g^b$; - la chiave simmetrica che i partecipanti utilizzeranno sarà $g^(a b)$ #figure([#image("images/c42801682720bed475af276330275f6c.png", width: 100%)], caption: [ Diffie-Hellman key exchange ] ) Si dice che la chiave simmetrica viene calcolata in modo #strong[partecipato], perché entrambi contribuiscono al risultato. Problema: questo protocollo non garantisce autenticità della chiave, perciò è necessario integrarlo con un sistema di firma digitale. == Computational security #block[ #strong[Definizione]: livello di sicurezza Numero medio di operazioni necessarie per rompere uno schema di cifratura simmetrica. ] La #strong[dimensione delle chiavi] è un \"dato derivato\" dal livello di sicurezza di uno schema. Il livello di sicurezza di uno schema si misura in bit (es. 80 bit \= $2^80$ operazioni necessarie, in media, per rompere lo schema). Negli schemi simmetrici, il livello di sicurezza e la dimensione della chiave sono strettamente correlati. Questa relazione invece non esiste negli schemi asimmetrici. Nella crittoanalisi asimmetrica, gli algoritmi più efficienti non sono quelli basati sul #strong[bruteforcing] ma quelli basati sulla risoluzione dei #strong[problemi difficili] sui quali si basa l'algoritmo di cifratura asimmetrica utilizzato. Nei contesti asimmetrici, la dimensione della chiave deriva dal problema matematico che sta sotto. Problemi matematici legati alle #strong[curve ellittiche] stanno diventando sempre più popolari, perché permettono di tenere piccola la dimensione della chiave garantendo lo stesso livello di sicurezza. == Crittografia e computer quantistici Si stima che tutti gli schemi asimmetrici attualmente in uso verranno rotti nei prossimi decenni dai #strong[computer quantistici]. Si stanno già studiando nuovi schemi di cifratura a prova di computer quantistici. Alcuni sono anche già stati standardizzati. == Handshake sicuro Client e server devono riuscire ad eseguire un protocollo che permetta ad entrambi di ottenere la stessa chiave simmetrica $K$. Per ottenere questo risultato si può utilizzare un protocollo per lo scambio sicuro delle chiavi. Dalla chiave $K$, sia client che server ne derivano altre 3 (tramite funzioni MAC o hash), l'una indipendente dall'altra. Queste 3 chiavi servono perché si vuole realizzare una comunicazione full-duplex: - una chiave serve per la confidenzialità (i.e. per cifrare i dati); - le altre 2 chiavi servono per l'autenticità. Ne vengono usate 2 e non una sola per proteggersi dai reflection attack (una chiave per ogni direzione). In realtà in base al protocollo possono esserci anche più o meno di 3 chiavi. Un approccio di questo tipo però è vulnerabile ad attacchi man-in-the-middle. Lo scambio di chiavi deve essere #strong[autenticato]. == Distribuzione di chiavi pubbliche Esistono principalmente 3 approcci per la distribuzione di chiavi pubbliche autenticate: - trust-on-first-use (TOFU); - out-of-band verification; - approccio delegato; === Trust-on-first-use Una volta instaurata la connessione si assume che il canale sia #strong[sicuro] e quindi si usa questo stesso canale per scambiare la chiave pubblica. Il protocollo SSH utilizza questo paradigma. Il canale deve essere sicuro rispetto ad attacchi #strong[attivi] (es. di tipo man-in-the-middle), non è invece necessario che lo sia rispetto ad attacchi #strong[passivi]. === Out-of-band verification In questo scenario ci sono 2 canali: uno insicuro ed uno sicuro. Trasmettere informazioni sul canale sicuro è molto più costoso rispetto al canale insicuro. Esempio: Whatsapp. La chat è il canale insicuro, mentre il canale \"sicuro\" sarebbe quello \"fisico\" (una persona mostra all'altra il QR code con la sua chiave pubblica). === Approccio delegato In questo scenario c'è un'#strong[entità terza] che garantisce l'autenticità delle chiavi pubbliche. Questo approccio può essere: - centralizzato, se c'è una sola entità che ha il compito di garantire l'autenticità delle chiavi (es. PKI, Public Key Infrastructure); - distribuito, se ci sono più entità con questo compito (es. OpenPGP) Entrambi gli interlocutori devono fidarsi di queste entità terze. #figure([#image("images/723979fc707bf2d56dae3ae2d63572d6.png", width: 100%)], caption: [ Scambio di chiavi con PKI ] ) + Bob invia ad Alice una chiave simmetrica firmata digitalmente con la chiave pubblica di Bob, la quale è firmata a sua volta dalla certification authority; + Alice verifica che la chiave simmetrica ricevuta da Bob sia autentica controllando la chiave pubblica con cui è stata firmata; + Alice verifica che la chiave pubblica sia autentica controllando la firma della CA === Certificati Con #strong[certificato] s'intende una chiave pubblica con diversi #strong[metadati] associati (es. validità, dominio, ecc.). I certificati vengono rilasciati dalle certification authority. I mantainer dei browser includono all'interno del browser stesso i certificati delle CA. #figure([#image("images/e9232d9724f41f45e65c903dda60c533.png", width: 100%)], caption: [ Flusso di messaggi ] ) Con questa strategia si utilizzano poche chiavi pubbliche (quelle delle CA) per autenticarne tante. Le CA sono organizzate in modo gerarchico: #figure([#image("images/63f0568f637d502a45f65081dbb51cb7.png")], caption: [ Struttura gerarchica delle CA ] ) Le CA intermedie sono quelle che firmano i siti finali. Le firme delle CA intermedie sono a loro volta firmate dalle root CA, che sono le uniche effettivamente salvate nel browser. Quando un client si connette ad un server, la PKI prevede che il server invii una #strong[catena di certificati] che permette al client di verificare l'autenticità della chiave pubblica del server. ==== Self-signed certificates Certificati in cui la firma digitale coincide con la chiave pubblica del certificato stesso. Non c'è nessuna certification authority. == Stack di protocolli sicuri Esistono diversi protocolli sicuri per supportare diversi scenari: - half-duplex o full-duplex; - comunicazione a singoli o a gruppi; - comunicazioni sincrone o asincrone; - ... Ad ogni livello dello stack TCP/IP esistono diversi protocolli sicuri per garantire #strong[confidenzialità] ed #strong[autenticità]. Più il protocollo sicuro viene inserito in alto nello stack e più la protezione è \"completa\": - se il protocollo sicuro è usato al livello 2, la comunicazione è sicura solo all'interno della rete locale; - se il protocollo sicuro è usato a livello 4, la comunicazione è sicura solo fino al livello applicativo; - ... ma più si scende nello stack e più informazioni si riescono a nascondere (es. se si vogliono cifrare IP sorgente/destinazione bisogna agire a livello 3). === Protocollo MACSec Protocollo molto recente che garantisce l'autenticità dei messaggi Ethernet. L'obiettivo di questo protocollo è implementare dei forti controlli d'accesso su reti Ethernet cablate. Problema: se ci sono delle prese di rete libere, chiunque può connettersi. \ Soluzione semplice: si gestisce una #strong[white list] di MAC address autorizzati a connettersi. Il MAC address però può essere modificato dall'amministratore di sistema, rendendo inutile questa white list. \ Soluzione corretta: si utilizza il protocollo MACSec. Il protocollo MACSec è implementato dagli switch. === IPSec Protocollo di livello 3, estensione di IP. Contiene 2 sotto-protocolli: - #strong[transport mode]: crea una connessione sicura a livello 3 tra due nodi; - #strong[tunnel mode]: crea una connessione sicura a livello 3 tra due reti. Tutte le informazioni di livello 3 vengono incapsulate da un altro pacchetto IP e rimangono in chiaro solo i gateway delle 2 reti. === Protocolli sicuri a livello trasporto IPSec e MACSec sono delle #strong[estensioni] di IP ed Ethernet. A livello 4 invece si creano dei protocolli #strong[aggiuntivi] che si mettono sopra egli esistenti TCP ed UDP: #figure([#image("images/dc8412d5ea4396edecccdefd7d7abfae.png")], caption: [ Protocolli sicuri a livello 4 ] ) Nel caso di TLS: - prima ci si connette con TCP, nel solito modo; - poi ci si connette in TLS Le versioni di TLS precedenti alla 1.2 sono considerate insicure. Anche la versione 1.2, sebbene sia considerata sicura, al suo interno potrebbe usare dei cifrari non più sicuri. È opportuno quindi configurarla correttamente. DTLS offre, opzionalmente, funzionalità per proteggersi dai replay attack. ==== Handshake TLS + scambio di metadati (es. versione di TLS, cifrari supportati, ecc.); + server key exchange e authentication (il server invia i propri certificati); + client key exchange e authentication. L'autenticazione del client è opzionale (es. in HTTPS il client non è mai autenticato); + fine Quando è attivata anche l'autenticazione del client si parla di #strong[mutual authentication] (MTLS). La connessione è autenticata in entrambe le direzioni. ==== Downgrade attack Attacco con cui l'attaccante \"costringe\" client e server ad utilizzare una versione di TLS non più sicura. I downgrade attack sono il motivo per cui si consiglia sempre di #strong[disabilitare completamente] le versioni insicure di TLS (che invece spesso vengono lasciate attive per ragioni di retrocompatibilità). === Protocolli applicativi sicuri Si possono distinguere in 2 famiglie: - quelli che usano il protocollo insicuro mettendoci sopra TLS (es. HTTPS, FTPS, ecc.); - quelli che non usano TLS e si re-inventano il layer di comunicazione sicuro (es. SSH) #figure([#image("images/4fa3342390a7732cc1cab712f3b75967.png", width: 100%)], caption: [ Protocolli insicuri con sopra TLS ] ) #figure([#image("images/34491a1c1e1224170bafcb73e718e87b.png", width: 100%)], caption: [ Protocolli sicuri nativi ] ) == HTTPS e virtual hosting In HTTPS viene cifrato tutto il contenuto della request HTTP. In realtà però l'#strong[hostname] a cui ci si connette viene lasciato in chiaro, perché altrimenti: - i web server non sarebbero più in grado di fare #strong[virtual hosting]; - i web server non saprebbero che certificato restituire al client L'hostname in chiaro lo si trova nel campo #strong[Server Name Indication] (SNI) di TLS.L Lasciare l'hostname in chiaro presenta diversi problemi di privacy. Per queste ragioni sono allo studio diversi standard che permettono di cifrarlo. = Posta elettronica == Indirizzi email #block[ `username "@" domain` ] - 64 caratteri al massimo per lo username. Secondo lo standard dovrebbe essere case-sensitive, ma ogni mail provider fa come gli pare; - 255 caratteri al massimo per il dominio, che deve rispettare tutte le regole del DNS == Affidabilità e sicurezza Il sistema email è stato pensato agli inizi degli anni '70, quindi la sicurezza non è stata minimamente presa in considerazione. Rischi del sistema email: - email false; - mittenti che si spacciano per altri (#strong[message spoofing]) - phishing; - URL insicure; - allegati malevoli; - ... La protezione da queste vulnerabilità è resa difficile anche dalla #strong[decentralità] del sistema email (ci sono tanti attori in gioco e ognuno dev'essere libero di fare quello che gli pare). == Elementi architetturali del protocollo email - mail transfer agent: componente del mail server che si occupa dell'invio e della ricezione delle email. A seconda dei contesti si può scomporre in #strong[mail submission agent] (ricezione) e #strong[mail delivery agent] (invio); - mail user agent: componente che gestisce le email lato utente (e.g. client di posta); Protocolli usati nel sistema email: - #strong[SMTP] (Simple Mail Transfer Protocol): usato per il trasferimento dei messaggi di posta. Il protocollo SMTP viene usato sia per la comunicazione client $arrow.r$ server, sia per la comunicazione server $arrow.r$ server. Al giorno d'oggi si usa quasi sempre SMTP con TLS, soprattutto nella comunicazione client $arrow.r$ server; - #strong[POP]: famiglia di protocolli usati dal client. Si tratta di protocolli molto semplici che permettono solo il download delle email dal server; - #strong[IMAP]: altro protocollo usato dal client, più complesso rispetto a POP. Oltre al download, IMAP permette una #strong[sincronizzazione] tra client e server (es. email lette, etichette, cartelle, ecc.); - HTTP: indipendente dal sistema email. Al giorno d'oggi è usato dagli end-user per interagire con il #strong[client web] di posta (es. Gmail). Il mail server gestisce l'invio di messaggi con una #strong[coda]. Esempio di comunicazione end-to-end: #figure([#image("images/f3bc5d4d3dbf3f38ac698bfb637c7b84.png")], caption: [ Comunicazione tra due utenti tramite sistema email ] ) == Architettura di un mail server #figure([#image("images/cb74af9f64f129d9bcfc08b1d8b9d98f.png", width: 100%)], caption: [ Architettura di un mail server multi-utente ] ) La coda di messaggi in uscita viene chiamata #strong[spool]. Oggi i mail server tipicamente gestiscono anche un #strong[database di utenti]. == Interazione con il DNS Il dominio degli indirizzi email è gestito dal DNS. Il sistema email è fortemente decentralizzato. Non esiste un punto univoco che elenca #strong[tutti] gli indirizzi email presenti sul pianeta. Se Google deve mandare un'email a Libero, la 1° cosa che deve fare è capire #strong[a quale host] inviare la mail. Google dovrà quindi interrogare il DNS per recuperare il record #strong[MX] associato a Libero. Il record MX del DNS espone i nomi dei server da usare per #strong[inviare] email a colui che espone il record MX stesso. I record MX quindi vengono usati nella comunicazione server $arrow.r$ server. Nel caso di comunicazione client $arrow.r$ server, invece, il client non legge il record MX del server ma una #strong[configurazione manuale] fatta dall'utente. == Protocollo SMTP Protocollo con paradigma client-server per #strong[inviare] email. Utilizza TCP come protocollo trasporto. La comunicazione in SMTP è composta da diverse fasi (non è ad esempio come HTTP che è un protocollo request-response). Si tratta quindi di un protocollo #strong[stateful]. #figure([#image("images/26fbe78a5665b86b3bcad55df6250e2c.png")], caption: [ Comunicazione server $arrow.r$ server con SMTP ] ) SMTP prevede che il 1° messaggio venga inviato dal server, per presentarsi al client. Questo messaggio (presente anche in altri protocolli, es. FTP ed SSH) viene chiamato #strong[banner]. SMTP è un protocollo #strong[testuale], come HTTP. Nella comunicazione client $arrow.r$ server con SMTP è sempre presente anche una fase di #strong[autenticazione]. Per poter inviare email, il client dev'essere autenticato. Nella comunicazione server $arrow.r$ server invece non c'è mai una fase di autenticazione, perché impossibile da gestire a causa della decentralità del sistema email. È molto facile quindi fare attacchi di tipo email spoofing nella comunicazione tra server. == Formato del messaggio SMTP SMTP è un protocllo testuale in cui sono accettati solo caratteri ASCII 7 bit. Per gestire altre tipologie di messaggi si utilizza il protocollo #strong[MIME]. == Email sicure Uno dei problemi di sicurezza principali del sistema email è l'email spoofing: nella comunicazione server $arrow.r$ server, il server mittente può spacciarsi per un altro server senza che il server destinatario abbia modo di accorgersene. Il record MX usato nella comunicazione server $arrow.r$ server permette di capire a chi inviare le email, ma non permette al server destinatario di verificare che il server mittente sia realmente chi dice di essere. Nei protocolli moderni esistono tante estensioni per la sicurezza. Non tutti i mail provider supportano tutte queste estensioni. La sicurezza delle nostre email dipende #strong[esclusivamente] dal provider utilizzato. Tutte queste estensioni vanno ad interfacciarsi sempre con il DNS, che viene usato anche per verificare da dove vengono i dati ricevuti da un mail server. === SPF Protocollo che prevede che il mail server di destinazione possa controllare che il mail server mittente sia effettivamente autorizzato ad inviare email per un certo dominio. - chi gestisce il dominio del mittente deve inserire nel proprio DNS dei record #strong[TXT] che contengono gli #strong[indirizzi IP] dei server autorizzati ad inviare email per conto di quel dominio; - il mail server destinazione deve fare una query TXT al proprio DNS per verificare se l'IP del server da cui gli è arrivata la mail è abilitato ad inviare email per conto di quel dominio È importante capire che il protocollo SPF protegge #strong[il mittente]: è chi NON espone questi record TXT a rendersi vulnerabile ad email spoofing. Il protocollo SPF, come tutte le altre estensioni per la sicurezza, è #strong[facoltativo]. I mail server non sono tenuti ad implementarlo. Se la validazione fatta dal destinatario fallisce, ciò che succede dipende dal mail provider. - alcuni decidono di scartare del tutto la mail; - altri la accettano comunque e possono decidere se dare un feedback all'utente === DKIM Molto simile ad SPF, ma i record TXT esposti dal mail server mittente non contengono degli indirizzi IP ma delle #strong[chiavi pubbliche]. - il mail server mittente firma il messaggio con la propria firma digitale; - il mail server destinatario fa una query TXT al DNS per verificare la firma È più sicuro di SPF (è più difficile falsificare una firma digitale piuttosto che un indirizzo IP), ma è anche più oneroso. Permette anche una flessibilità maggiore rispetto ad SPF nel caso in cui sia molto difficile enumerare gli IP dei mail server autorizzati. Nel caso di tanti mail server, infatti, con DKIM è sufficiente avere un unico mail server finale che si occupa di firmare i messaggi. Al giorno d'oggi SPF è dato per scontato, mentre DKIM è ancora piuttosto raro. === Sicurezza end-to-end Se l'utente non vuole affidarsi al mail provider per la sicurezza, esistono anche dei protocolli che permettono di gestirla a livello end-to-end. ==== S/MIME Estensione del protocollo MIME per gestire #strong[firma] e #strong[cifratura] delle email, oltre che la codifica. S/MIME si interfaccia con il sistema PKI. Ogni utente possiede: - un certificato rilasciato da una certification authority; - una (o due) coppia di chiavi asimmetriche per firmare e cifrare i messaggi ==== PGP - Pretty Good Privacy Protocollo molto simile a S/MIME, ma che non si interfaccia con il sistema PKI. Anch'esso si basa comunque su firma e cifratura tramite chiavi asimmetriche. È stato pensato principalmente per contesti decentralizzati (es. sviluppo open source). == PEC - Posta Elettronica Certificata Sistema esistente solo in Italia per aggiungere garanzie di autenticità alle email. La PEC è solo autenticata. Non supporta la cifratura. Lo scopo principale della PEC è dare #strong[garanzia legale] (in particolare #strong[non repudiabilità]). La cifratura non è supportata perché a livello legale è più comodo avere i messaggi in chiaro. Gli schemi di firma usati dalla PEC sono gli stessi di S/MIME, ma non viene implementata la parte legata alla cifratura. Esiste una lista ben precisa di mail provider PEC autorizzati. Il protocollo S/MIME viene esteso dalla PEC per garantire l'autenticità anche della #strong[ricevuta] del messaggio (cosa che nell'email originale non esiste). In realtà la conferma di ricezione è inviata dal mail server, non dall'utente finale destinatario (che potrebbe non aver ancora visto l'email). Tuttavia, a livello legale, si suppone che dopo 2 settimane l'utente destinatario abbia letto la PEC, se il suo mail server ha inviato la ricevuta.
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS2340/SoftwareArchitecture.typ
typst
#import "../../template.typ": * #let so = [Software Architecture] = Software Architecture #definition()[ *Software Architecture* is the fundamental organization of a system, embodied in its components, their relationships to each other and the environment, and the principles governing its design and evolution. ] In other words #so is: - The set of design decisions that must be made early - The decisions that you wish you could get early on - The decisions that are *hard to change* #note[ Software architects are often people with great communication skills - They need to understand, and explain requirements to different stakeholders - Can translate client's features to technical language ] A good software architecture represents a high internal quality of software, one that is not necessarily visible to customers and users but matters in the long term. Architecture is often about the long term, because it may change a little over time but will rarely change a lot. == Client Server Architecture #definition[ *Client Server Architecture*: a system with an organized set of services and associated servers, and clients that access and use the services. ] *Major Components*: - Set of servers that offer services to other components, such as print servers, email servers, etc - Set of clients that call on the services offered by servers - A network that allows the clients to access the servers #note[ The client and server can actually be on the same computer! However, #underline()[they need to be run on different processors.] ] #example(footer: "Note that the architectural style is monolithic, meaning a single executable performs all of the server-side functions for the application.")[ An example of client-server architecture is youtube. The client is the user device (integrated UI), and the server is youtube. ] *Pros* - It is a centralized system that keeps all the data and its controls in one place - High level of scalability, organization, and efficiency *Cons* - Each service is a new *point of failure* - It can be susceptible to DDOS attacks == N-Tier Architecture One of the fundamental problems with client-server architecture is that logical layers in the system (presentation, application processing, data management, and database) must be mapped onto two processors: client and server; In N-tier architecture, the different layers are separate processes that may execute on different processors. #example[ #image("Images/ntier.png") In this example, we have a 3 tier model w/ a web server and database. ] == Peer-to-Peer Architecture #definition[ *Peer-to-peer systems:* decentralized systems in which computations can be carried out by any node in the network. There is no clear distinction between clients and servers. ] When to use? - When the system is *computationally intensive* and you can break up the process into many independent steps - Where the system involves the exchange of information between individual computers on a network and there is no need for this information to be centrally stored or managed *Pros*: - Highly redundant and very fault-tolerant *Cons*: - Concerns about privacy and security == Blackboard Architecture #attention[ This section is non-lecture notes because I don't understand the lecture for this. *Blackboard architecture* is an architecture that is used to solve difficult problems where we don't have a pre-defined algorithm to use. It is inspired behind how people work at blackboards adding incremental solutions until they come to a collective solution together. I think(?) that *knowledge sources* are modules/algorithms that are able to help potentially solve the problem. They usually have a specialized frame of thinking unique to its others. Flow of Information: + Initialization: the blackboard gets setup with the initial problem and any data. + Activation: the controller selects and activates one or more knowledge sources based on the current state of the problem and available data + Execution: the knowledge sources independently analyze the problem and apply specialized algorithms or techniques and produce partial solutions. + Conflict resolution: if multiple knowledge sources conflict, use a conflict resolution mechanism + Update: the knowledge sources update the blackboard with their outputs. + Repeat. ] Key ideas are that problem-solving is now: - *Incremental* - complete solutions are constructed piece by piece - *Opportunistic* - system chooses the actions to take next that will allow it to make the best progress. *Main Components* - Blackboard - a structured global memory containing objects from the solution space - Knowledge sources - specialized modules w/ their own representation for reading/writing on blackboard - Control component - selects, configures, and executes modules == Pipe and Filter Architecture The *pipe and filter architecture* style is data-centric and structured around how data flows through the application. - Firstly, the application takes in data as input - Next, a series of transformations are sequentially applied - Finally, the application returns the processed data as output #note[ The name for pipe and filter comes from Unix where you can link processes using pipes ] #example[ One example is a company that sends invoices to people. First you read invoices, then identify payments on the invoices, then either ask to pay or send reminders. ] *Pros:* - Easy to understand and supports transformation reuse - Workflow style matches the structure of many business processes - Evolution by adding transformations is Easy - Can be implemented as a sequential or concurrent system *Cons:* - Format for data transfer has to be agreed upon between communicating transformations - Each transformation must parse its input and unparse its output to the agreed form. - This can increase overall system overhead == Layered Architecture #definition[ *Layered Architecture:* organizes the systems into layers with related functionality/logic associated with each layer. ] In each *layered system*, each layer - Depends on the layer beneath it - Is independent of the layers on top of it #image("Images/layered.png") *Pros:* - Changes in one layer usually doesn't impact other layers - Modularity: promotes separation of Concerns *Cons:* - Potential redundant functionality - Potential rigidity - Interaction complexity == Model-View-Controller (MVC) Pattern This architecture follows the layered approach. Here, we #underline()[separate presentation and interaction from the system data] Instead, the system is structured into three logical components: - *Model Component:* manages the system data and associated operations on the data - *View Component:* defines and manages how the data is presented to the user - *Controller Component:* manages user interaction (clicks, etc) Model and View are connected, as the data from model updates view over time. == Model-View-ViewModel This is a derivative of the popular MVC architectural pattern. However, for MVVM, *model and view are not connected*. Instead, the *ViewModel* acts as an intermediary, managing differences between model and view. #note[ MVVM is one of the recommended architectures for developing android applications. ] == Event Driven Architecture #definition[ *Event Driven Architecture:* consists of events producers that create a stream of events and event consumers that listen for those events. ] Using EDA, an object can broadcast (look out?) for one or more events, and other objects register an interest in that event. When the event is invoked, the system runs all the related/important procedures. This is useful when multiple subsystems must process the same events and *real-time processing* is needed with low lag.
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/tests/template.typ
typst
#import "/src/lib.typ" as ctf // #import ctf: report, thesis, bachelors-thesis, masters-thesis #import ctf.prelude: * #show: doc()
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/signature/user_with.typ
typst
Apache License 2.0
#let f(u, v) = u + v; #let g = f.with(1) #(/* ident after */ g);
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/algo/lectures/2024-09-17.typ
typst
= Информация Коллок предварительно в начале второго модуля (2 ноября, 1--4 пары) Все задачи в контесте стоят одинокого = А<NAME> Алгоритм перемножения двух многочленов (или чисел) $ A(x) = a_0 + a_1 x + ... + a_(n-1) x^(n-1) $ $ B(x) = b_0 + b_1 x + ... + b_(n-1) x^(m-1) $ // Будем считать $deg A = deg B = n$, не $n - 1$. $ C(x) = A(x) B(x) = c_0 + c_1 x + ... c_(n + m - 2) x^(n + m - 2) $ bruteforce (в столбик) за $O(n^2)$: $ c_k = sum^k_(i = 0) a_i dot b_(k - i) $ В Карацубе лучше останавливаться при $deg approx 16$ и перемножать в столбик Добиваем многочлены до одинаковой длины и до степени двойки. Разобьем многочлен на два: $ A(x) &= a_0 + a_1 x + ... + a_(n - 1) x^(n-1) \ &= underbrace([a_0 + a_1 x + ... + a_(n/2 - 1) x^(n/2 - 1)], A_0(x)) + underbrace([a_(n/2) + ... + a_(n - 1) x^(n/2-1)], A_1(x)) x^(n/2) \ &= A_0(x) + A_1(x) x^(n/2) $ $ B(x) = B_0(x) + B_1(x) x^(n/2) $ Перемножим (складываем за линию, перемножаем рекурсивно): $ A(x)B(x) &= (A_0 + A_1 x^(n/2))(B_0 + B_1 x^(n/2)) &= A_0 B_0 + (A_1 B_0 + A_0 B_1)x^(n/2) + A_1 B_1 x^n $ Найдем асимптотику: $ T(n) = 4T(n/2) + O(n) => T(n) = O(n^2) $ Так перемножать не выгодно. Проблема в четырех произведениях. Сокращаем число произведений до трех: $ (A_0 + A_1)(B_0 + B_1) = underbrace(A_0 B_0 + A_1 B_1, "уже знаем") + underbrace(A_0 B_1 + A_1 B_0, "сможем найти") $ Найдем новую асимптотику: $ T(n) = underbrace(3T(n/2), "на умножения") + underbrace(O(n), "на сложения") => T(n) = O(n^(log_2 3)) approx O(n^1.585) $ Так перемножать значительно быстрее. == Длинная арифметика $ 2105789 = 9 + 8x + 7x^2 + 5x^3 + x^5 + 2x^6 |_(x=10) $ $ a, b < 10^1000 $ Нужно делать перенос разряда. Можно сменить систему счисления для ускорения в константу раз. Удобно брать $x = 10^n$. == <NAME> Обобщение Карацубы на матрицы brutforce за $O(n^3)$: $C_i_j = sum^(n - 1)_(k = 0) a_(i k) b_(k j)$ Размер матрицы: $n = 2^k$ Пилим матрицу на четыре куска. Куски будут перемножаться, как обычные матрицы. $ mat( a_(1 1), a_(1 2); a_(2 1), a_(2 2); ) dot mat( b_(1 1), b_(1 2); b_(2 1), b_(2 2); ) = mat( a_(1 1) b_(1 1) + a_(1 2) b_(2 1), a_(1 1) b_(1 2) + a_(1 2) b_(2 2); a_(2 1) b_(1 1) + a_(2 2) b_(2 1), a_(2 1) b_(1 2) + a_(2 2) b_(2 2); ) $ Можно посчитать не за 8, а за 7 умножений Посчитаем сложность: $ T(n) = 7 T(n/2) + O(n^2) => T(n) = O(n^(log_2 7)) approx O(n^2.81) $ Выгодно только для очень больших матриц === Аналоги Штрассена #table( columns: 3, table.header[*Год*][*Название*][*Асимптотика*], [1990], [Коперсмита-Виноградова], $O(n^(2.3755))$, [2020], [Алмана-Вильямса], $O(n^2.3728)$ ) *<NAME>*: $forall epsilon > 0: exists "алгоритм": forall n >= N: O(n^(2+epsilon))$ == Fast Fourier Transform (FFT) Сложность $O(n log n)$, но с большой константой *Основной принцип*: храним многочлен, как список его значений в некоторых точках. Знаем $A(x_0), A(x_1), ..., A(x_(n-1))$ Коэффициенты при умножении меняются нетривиально, а значения в точках --- намного проще, если удачно выбрать точки: $x_i = omega^i$, где $omega in CC$ или $omega in ZZ_p$. Проблема: переход в `double`.
https://github.com/Cheng0Xin/typst-libs
https://raw.githubusercontent.com/Cheng0Xin/typst-libs/master/semantics/README.md
markdown
```typst #semantics-rule(( above: (array: ((text: $(lambda X . M_1)$), (above: (text: $M_1 diamond.small ...$), below: (text: $beta$)))), below: (array: ((text: $(lambda X . M_1) diamond.small ...$), (text: $zeta$))), )) ```
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/customize/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) #set par(justify: true) // Test arguments for customization. #dropcap(height: 3, lorem(14)) #dropcap(height: 1.1cm, lorem(14)) #dropcap(depth: 2, lorem(23)) #dropcap(height: 5mm, depth: 5mm, lorem(16)) #dropcap(overhang: 1em, lorem(7)) #dropcap(overhang: 100%, lorem(7)) #dropcap(overhang: -1em, gap: 1em, lorem(12)) #dropcap(height: 3, hanging-indent: 1em, lorem(13)) #dropcap( gap: 8pt, fill: white, font: "New Computer Modern", style: "italic", transform: letter => { h(4pt) + box(fill: blue, letter + h(10pt), outset: 3pt) }, lorem(11) )
https://github.com/Ttajika/typst_slide
https://raw.githubusercontent.com/Ttajika/typst_slide/main/library/functions.typ
typst
#import "@preview/cetz:0.2.2" #import "parameter.typ":* //カラーとフォントの設定. #let default_color = eastern.lighten(30%) #let emph_color = white #let strong_color = rgb("3cb371") #let textcolor = black //フォントはarrayで設定すれば,英字は英字用の,日本語は日本語用のフォントで設定してくれる #let body-font = ("M PLUS 2") #let sans-font = ("M PLUS 2") #let slide_counter = counter("slide_counter") #let subslide = counter("subslide_counter") #let subslide_c = counter("subslide_current") #let pause_c = counter("pause_number") #let pause_a = counter("pause_all") //------スライド番号参照 #let showslidenumber(label:"") = { context[ #if label == ""{ counter("slide_counter").get().at(0) } else { counter("slide_counter").at(label).at(0)+1 } ] } //---Slide Outline #let slide-outline(n_columns:1, size:none) = { context{ let headings-name = () let headings = query(selector(heading.where(level: 1,outlined:true))) let text_size = { if size == none {text.size} else { size } } let i = 0 while i< headings.len(){ headings-name.push(text(font: sans-font, weight:400, context[#link(headings.at(i).location())[#headings.at(i).body ]],size:text_size*1)) i = i+1 } columns(n_columns)[ #for i in range(headings.len()) { [#headings-name.at(i) #box(width: 1fr, repeat[.]) #{counter("slide_counter").at(headings.at(i).location()).at(0)+1} \ ] } ] } } //--------Defaultのテーマ //ヘッダーアウトラインの設定 #let heading-outline(color:default_color, current-headings:"") ={ let headings = query(selector(heading.where(level: 1,outlined:true))) //let current-headings = counter(heading) let i = 0 let headings-name = () let head-col = () let head-weight = () while i< headings.len(){ if i+1 == current-headings{ headings-name.push(text(font: sans-font, fill:color, weight:700, context[#link(headings.at(i).location())[#box(stroke:.5pt+color)[#headings.at(i).body ]]],size:8pt))} else { headings-name.push(text(font: sans-font, fill:color, weight:400, context[#link(headings.at(i).location())[#headings.at(i).body ]],size:8pt))} i = i+1 } pad( top: -1.0em, bottom: 0.0em, x: 0em, grid( columns: (1fr,) * (headings.len() +0), gutter: 0em, ..headings-name.map(name => align(center, name )))) } ) } //Headerスライドのデザイン #let default-header_slide(title,now:0, end:0,color:default_color, tcolor:emph_color, current-headings: "", outline: false) = { set text(size: 23pt, weight:700) let a = {if outline == true{1} else {0}} if outline == true {pad(top:15pt,bottom:-30pt)[ #box(width:95%)[#heading-outline(color:color, current-headings: current-headings)]] } else [#hide[#pad(top:15pt,bottom:-30pt)[ #box(width:95%)[#heading-outline(color:color, current-headings: current-headings)]]]] pad(top:1.6em,left:-2cm)[#line( length: 30cm, stroke: 4pt + color.darken(10%), ) ] text(size:0.7em,fill:color.darken(10%))[ #pad(left:26.93cm,top:-2.65cm)[ #circle(radius:1.0cm, stroke:4pt+color.darken(10%),fill:white)[#pad(left:-10pt,top:0pt)[#box(width: 2em)[#align(center)[#now]]] #pad(left:8pt,top:-18pt)[#box(width: 2em)[#align(center)[#end]]] ] ] ]; pad(left:28.6cm,top:-2.7cm)[#line(length:2cm, stroke:4pt+color.darken(10%), angle:131deg)] pad(left: -20pt, top:-2.1cm)[ #if title == [] {h(20pt); text(size:1.1em)[#hide[あg]]}else { h(20pt);text(size:1.1em,fill:color.darken(30%))[#title #hide[あg] ]; h(1fr)}; #v(a*2.5em+1.0em) ] } //タイトルスライドのデザイン #let default-title_slide(now:"",end:"", color:"",tcolor:"", outline:"", title:"", title_notes:"", date:"", authors:"", notes:(), institutions:"", header-slide:default-header_slide) = { // default-header_slide(now:now,end:end, color:color, tcolor:tcolor,outline:outline)[] align(center+horizon)[ #set text(weight: 700, 2em) #box(fill:color, outset: (x: 15pt, y: 15pt),radius: 10pt)[#text(fill:tcolor)[#title]] #if title_notes !=none {footnote[#title_notes]} #v(1em, weak: true) #set text(weight: 500, 0.5em) ] let author_note = authors.zip(notes) pad( top: 0.5em, bottom: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center, text(weight: 700, 1em, author) )), ..institutions.map(institutions => align(center, text(weight: 700, 1em, institutions))) ), ) [#align(center)[#text(size:1.2em)[#date]]] } //フッターのデザイン #let default-page-setter(footer:"",body) = { set page(footer: footer) body } //スライドのデザイン,タイトルスライドのデザイン,フッターのデザインをまとめる. #let default-theme = (slide_theme:default-header_slide, title_theme:default-title_slide, page_theme: default-page-setter, default-color: eastern.lighten(30%),emph-color:white) //------ #let tbox(emph_color, frame_color, title,body) = { let ss_counter = counter("showstyle-counter") context{ let ss = ss_counter.get().at(0) align(left)[#par(first-line-indent: 0em)[ #rect(width: 100%, stroke: 6pt+frame_color.opacify(-ss * trans),outset: (x:0.4pt,y:9.6pt), inset: (x:10pt))[ #rect(width: 100%, fill: frame_color.opacify(-ss *trans), stroke: 0pt+frame_color.opacify(-ss *trans),outset:(x: 8.5pt, y: 12pt), inset: (y:-5pt))[#text(fill: emph_color.opacify(-ss *trans),weight:700)[ #title ]] #body]]] } } //theorem型の関数の定義.figureと数式とheadingしか参照できないのでfigureを使って定義する. #let thm_counter = counter("thm_counter") #let theorem_base(title: none, kind: "Theorem", bodyface: text, frame_color:none, tlabel: none,body) ={ let current_thm_counter = counter("thm_counter"+(tlabel)) context[ #if current_thm_counter.get().at(0)==0{ let thm_base_counter = counter("thm"+str(kind)).get().at(0); counter("thm"+str(kind)+(tlabel)).update(thm_base_counter) counter("thm"+str(kind)+(tlabel)).update(n => n+1) } ] context[ #let thmlabel = "thm"+str(kind)+(tlabel) #show figure.caption: it => { it.body } #let title_text = { if title == none{ str(kind) +str(" ") + str(counter("thm"+str(kind)+(tlabel)).get().at(0))+ "."} else { str(kind) +str(" ") + str(counter("thm"+str(kind)+(tlabel)).get().at(0))+ " ("+title+")."} } #let sup = str(kind) +str(" ") + str(counter("thm"+str(kind)+(tlabel)).get().at(0)) #if counter("thm_counter"+(tlabel)).get().at(0) == 0{ [#figure(kind:"TheoremKinds", supplement: sup, caption:title_text, body) #label(tlabel)]}else { figure(kind:"TheoremKinds", supplement: sup, caption:title_text, body)}] context[ #if current_thm_counter.get().at(0)==0{ counter("thm"+str(kind)).step() counter("thm_counter"+(tlabel)).step() } ] } //footer #let slide-footline(footlines, ocol, ecol, otxcol, etxcol) = { let n = footlines.len() set text(size:0.5em) table(stroke:none, fill:(x, _) => if calc.odd(x) { ocol } else { ecol },columns: (1fr,)*n, ..{footlines}, ) } // theorem 関数の定義。 ここを変えれば変わる. #let theorem(title: none, label:none, kind:"Theorem", frame_color:default_color, body) = { theorem_base(title: title, kind: kind, tlabel:label,frame_color:frame_color, body) } #let prop(title: none, label:none, frame_color:default_color, body) = { theorem_base(title: title, kind: "Proposition", tlabel:label,frame_color:frame_color, body) } #let lemma(title: none, label:none,frame_color:default_color, body) = { theorem_base(title: title, kind: "Lemma", tlabel:label, frame_color:frame_color,body) } #let cor(title: none, label:none,frame_color:default_color, body) = { theorem_base(title: title, kind: "Corollary", tlabel:label,frame_color:frame_color, body) } #let claim(title: none, label:none,frame_color:default_color, body) = { theorem_base(title: title, kind: "Claim", frame_color:frame_color,tlabel:label, body) } #let definition(title: none, label:none,frame_color:default_color, bodyface: text,body) = { theorem_base(title: title, kind: "Definition",frame_color:frame_color, tlabel:label, body) } #let assumption(title: none, label:none,frame_color:default_color, bodyface: text,body) = { theorem_base(title: title, kind: "Assumption", frame_color:default_color, tlabel:label, body) } #let proof(title: none, body) ={ let title_text = { if title == none {"Proof"} else { "Proof of "+title+"." } } [#par(first-line-indent: 0em)[ #strong[#title_text] #h(1em) #body #box(width: 1fr, repeat[]); $qed$ ]] } //Dynamic slideの設定 #let showstyles(mode:none,body) ={ if mode == "t" { let ss_counter = counter("showstyle-counter") ss_counter.update(1) context{ let txcol = text.fill set text(fill:txcol.opacify(-trans)) body } ss_counter.update(0) } // { // let ss_counter = counter("showstyle-counter") // ss_counter.step() // let num = str(ss_counter.get().at(0)) // let metalab(body,slabel) = { // show metadata: it => { // } // [#metadata(body) // #label(str(slabel)) ]// // } // // // // body // metalab(body,num) // context{ // let z= here().position() // let size = measure((body)) // let txcol = page.fill // let target = locate(label(num)).position() // let targeta = locate(label(num+"a")).position() // place(clearance:0pt, dx: 1*(target.at("x")-targeta.at("x")), dy: target.at("y")-targeta.at("y"),box(fill:white.transparentize(10%),hide[#body], )) // } // metalab(body,num+"a") // } if mode == "h" { hide[#body] } if mode == none{ } } #let slide(title:"",body,slabel:"", level:1,color:default_color,tcolor:emph_color, subslides:0) ={ //slide_numberの更新 let subslide = counter("subslide_counter") let subslide_c = counter("subslide_current") subslide.update(subslides) subslide_c.update(0) pause_c.update(0) if slabel == "" {heading(level:level)[#title]} else [#heading(level:level)[#title]; #label(slabel)] body context[ #let current_subslide = 0 #let ss = subslide.get().at(0) #let slabels = () #let i = 0 #let current_heading = counter(heading).get().at(0) #while i < ss {slabels.push("") i = i + 1 } #while current_subslide < ss { //ヘッダーの作成 counter("slide_counter").update(n => n - 1) if level == 1 or level == auto { counter(heading).update(n => n - 1)} heading(outlined: false, level:level)[#title] subslide_c.step() pause_c.step() pause_a.update(0) body current_subslide = current_subslide + 1 } ] } #let Labelling(slabel) = { if slabel == "" [] else [ #show heading: it => {} #let sslabel = slabel #heading(outlined: false)[] #label(sslabel)] } //Pause #let fpause(body, mode:none) = { let css = subslide_c.get().at(0) let pss = pause_a.get().at(0) pause_a.step() if css == 0 {subslide.step()} if pss < css {return body} else {return } } #let pause(body,slabel:"", mode:none) ={ Labelling(slabel) context({ let css = subslide_c.get().at(0) let pss = pause_a.get().at(0) if pss < css {body} else {showstyles(mode:mode,body)} pause_a.step() if css == 0 {subslide.step()} }) } //subslide #let only(number, body, mode:none) = { context({ let current_subslide = subslide_c.get().at(0) let subslide_n = subslide.get().at(0) if type(number) == "integer" { if current_subslide == number { body } else {showstyles(mode:mode,body)} if current_subslide == 0 { if subslide_n < number { subslide.update(number) }}} if type(number) == "array" { let serch_num(nm) = { if nm == current_subslide { return true } else{return false} } if type(number.find(serch_num))== "integer" { body } else {[#showstyles(mode:mode,body)]} let mnumber = {number.last()} if current_subslide == 0{ if subslide_n < mnumber { subslide.update(mnumber) }} } } ) } #let up_cur_slide(mnumber) = { let subslide = counter("subslide_counter") let subslide_n = subslide.get().at(0) if subslide_n < mnumber { subslide.update(mnumber) }} // subslide.update(n=>max(n,calc.max(n,mnumber))) #let conly(number, body, mode:none) = { if type(number) == "integer" { cetz.draw.content((0,0),context{up_cur_slide(number) }) } if type(number) == "array" { let mnumber = {number.last()} cetz.draw.content((0,0),context{up_cur_slide(mnumber) }) } let visible = { let current_subslide = subslide_c.get().at(0) if type(number) == "integer" { if current_subslide == number { 1 } else {0} } if type(number) == "array" { let mnumber = {number.last()} let serch_num(nm) = { if nm == current_subslide { return true } else{return false} } if type(number.find(serch_num))== "integer" { 1 } else {0} } } if visible == 1 { cetz.draw.content((0,0),[ ]) body } } #let onlya(number, body, mode:none) = { context[#{ let current_subslide = subslide_c.get().at(0) let subslide_n = subslide.get().at(0) if current_subslide >= number { body } else {[#showstyles(mode:mode,body)]} if current_subslide == 0{ if subslide_n < number { subslide.update(number) }} }] } //空のボックス #let bbox(title: none, bodyface: text, tlabel: none,body, boxcolor: "", title_color: "") ={ if boxcolor != "" or title_color != "" {tbox(title_color, boxcolor, title ,body)} else{return figure(kind:"TheoremKinds", supplement: none, caption:title, body) } } //ボタン #let button(label,body, width:auto, height:auto, stroke:gradient.conic(..color.map.rainbow), fill:eastern) = { show ref: it => { box(stroke:1.5pt+stroke, radius: 10pt, fill:fill, width:width, height: height, inset:0.3em, baseline:5pt)[#align(center)[#text(size:0.8em, fill:white, weight: 700)[#link(it.target)[#body]]]] } ref(label) }
https://github.com/rayfiyo/myTypst
https://raw.githubusercontent.com/rayfiyo/myTypst/main/mystyle_report/template.typ
typst
BSD 3-Clause "New" or "Revised" License
// Store theorem environment numbering // Set font sizes #let font_sizes = (h1: 18pt, h2: 16pt, h3: 14pt, under_h4: 12pt, normal: 11pt, math: 12pt) // Store theorem environment numbering #let thmcounters = state("thm", ("counters": ("heading": ()), "latest": ())) // Setting theorem environment #let thmenv(identifier, base, base_level, fmt) = { let global_numbering = numbering return ( ..args, body, number: auto, numbering: "1.1", refnumbering: auto, supplement: identifier, base: base, base_level: base_level, ) => { let name = none if args != none and args.pos().len() > 0 { name = args.pos().first() } if refnumbering == auto { refnumbering = numbering } let result = none if number == auto and numbering == none { number = none } if number == auto and numbering != none { result = locate(loc => { return thmcounters.update(thmpair => { let counters = thmpair.at("counters") // Manually update heading counter counters.at("heading") = counter(heading).at(loc) if not identifier in counters.keys() { counters.insert(identifier, (0,)) } let tc = counters.at(identifier) if base != none { let bc = counters.at(base) // Pad or chop the base count if base_level != none { if bc.len() < base_level { bc = bc + (0,) * (base_level - bc.len()) } else if bc.len() > base_level { bc = bc.slice(0, base_level) } } // Reset counter if the base counter has updated if tc.slice(0, -1) == bc { counters.at(identifier) = (..bc, tc.last() + 1) } else { // counters.at(identifier) = (..bc, 1) } } else { // If we have no base counter, just count one level counters.at(identifier) = (tc.last() + 1,) let latest = counters.at(identifier) } let latest = counters.at(identifier) return ("counters": counters, "latest": latest) }) }) number = thmcounters.display(x => { return global_numbering(numbering, ..x.at("latest")) }) } return figure( result + // hacky! fmt(name, number, body, ..args.named()) + [#metadata(identifier) <meta:thmenvcounter>], kind: "thmenv", outlined: false, caption: none, supplement: supplement, numbering: refnumbering, ) } } // Definition of theorem box #let thmbox( identifier, head, ..blockargs, supplement: auto, padding: (top: 0.5em, bottom: 0.5em), namefmt: x => [(#x)], titlefmt: strong, bodyfmt: x => x, separator: [#h(0.1em):#h(0.2em)], base: "heading", base_level: none, ) = { if supplement == auto { supplement = head } let boxfmt(name, number, body, title: auto) = { if not name == none { name = [ #namefmt(name) ] } else { name = [] } if title == auto { title = head } if not number == none { title += " " + number } title = titlefmt(title) body = bodyfmt(body) pad( ..padding, block( width: 100%, inset: 1.2em, radius: 0.3em, breakable: false, ..blockargs.named(), [#title#name#separator#body], ), ) } return thmenv(identifier, base, base_level, boxfmt).with(supplement: supplement) } // Setting plain version #let thmplain = thmbox.with( padding: (top: 0em, bottom: 0em), breakable: true, inset: (top: 0em, left: 1.2em, right: 1.2em), namefmt: name => emph([(#name)]), titlefmt: emph, ) // Counting equation number #let equation_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter(math.equation) let n = c.at(loc).at(0) "(" + str(chapt) + "." + str(n) + ")" }) } // Counting table number #let table_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("table-chapter" + str(chapt)) let n = c.at(loc).at(0) str(chapt) + "." + str(n + 1) }) } // Counting image number #let image_num(_) = { locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("image-chapter" + str(chapt)) let n = c.at(loc).at(0) str(chapt) + "." + str(n + 1) }) } // Definition of table format #let tbl(tbl, caption: "") = { figure( tbl, caption: caption, supplement: [表], numbering: table_num, kind: "table", ) } // Definition of image format #let img(img, caption: "") = { figure( img, caption: caption, supplement: [図], numbering: image_num, kind: "image", ) } // Definition of abstruct page #let abstract_page(abstract_ja, abstract_en, keywords_ja: (), keywords_en: ()) = { if abstract_ja != [] { show <_ja_abstract_>: { align(center)[ #text(size: 20pt, weight: "bold")[ 概 #h(5pt) 要 ] ] } [= 概要 <_ja_abstract_>] v(10pt) // Configure paragraph properties in abstract page. set text(size: 12pt) set par(first-line-indent: 20pt, justify: true) show par: set block(spacing: 1.2em) abstract_ja if keywords_ja != () { par( first-line-indent: 0em, )[ #text( font: ("Times New Roman", "Source Han Serif JP"), weight: "bold", size: 12pt, )[ キーワード: #keywords_ja.join(", ") ] ] } // pagebreak() } if abstract_en != [] { show <_en_abstract_>: { align(center)[ #text(size: 18pt, "Abstruct") ] } [= Abstract <_en_abstract_>] set text(size: 12pt) h(1em) abstract_en par(first-line-indent: 0em)[ #text(weight: "bold", size: 12pt)[ Key Words: #keywords_en.join("; ") ] ] // pagebreak() } } // Definition of content to string #let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } // Definition of chapter outline // Delete the outline as it is not needed. // Definition of image outline // Delete the outline as it is not needed. // Definition of table outline // Delete the outline as it is not needed. // Setting empty par #let empty_par() = { v(-1em) box() } // Setting header // ref: https://stackoverflow.com/questions/76363935/typst-header-that-changes-from-page-to-page-based-on-state #let custom_header() = locate( loc => [ #let i = counter(page).at(loc).first() #let ht-first = state("page-first-section", []) #let ht-last = state("page-last-section", []) // find first heading of level 1 on current page #let first-heading = query(heading.where(level: 1), loc).find(h => h.location().page() == loc.page()) // find last heading of level 1 on current page #let last-heading = query(heading.where(level: 1), loc).rev().find(h => h.location().page() == loc.page()) // don't show chapter numbering in header of bibliography page #let header-chapt-num(content) = { let bibliography-content = query(bibliography, loc).at(0) if not content.at("body") == bibliography-content.at("title") { return [ #numbering(content.numbering, ..counter(heading).at(content.location())) #h(10pt) ] } else { return none } } // test if the find function returned none (i.e. no headings on this page) #{ if first-heading != none { ht-first.update([ // change style here if update needed section per section #header-chapt-num(first-heading) #first-heading.body ]) ht-last.update([ // change style here if update needed section per section #header-chapt-num(last-heading) #last-heading.body ]) // if one or more headings on the page, use first heading // change style here if update needed page per page [#ht-first.display() #h(1fr)] } else { // no headings on the page, use last heading from variable // change style here if update needed page per page [#ht-last.display() #h(1fr)] } } #v(3pt, weak: true) #line(length: 100%, stroke: 0.5pt + black) ], ) #let appendix(body) = { counter(heading).update(0) // 付録の添字リセット? counter("appendix").update(1) set heading( numbering: (..nums) => { let vals = nums.pos() let value = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".at(vals.at(0) - 1) if vals.len() == 1 { return [ #linebreak() 付録 #value ] // 明示的な改行含む } else { return [#(value + "." + nums.pos().slice(1).map(str).join(".")) #h(0.5em)] } }, ); let before_h1(it) = if it.numbering != none { text()[ #v(10pt) #numbering(it.numbering, ..counter(heading).at(it.location())) ] } else { none } show heading.where(level: 1): it => { counter(math.equation).update(0) set text(size: font_sizes.at("h1")) set block(spacing: 1.5em) text()[ #before_h1(it) #h(0.5em) #it.body #v(0pt) ] } show heading.where(level: 2): it => block({ set text(size: font_sizes.at("h2")) text()[ #it ] }) [#body] } // Construction of paper #let cover( number: "", // The master thesis title. title: "", // The paper`s author. id: "", author: "", // The author's information university: "", school: "", department: "", mentor: "", // The Experiment environment room: "", exp_year: "", exp_month: "", exp_day: "", exp_day_of_week: "", // weather: "", temperature: "", humidity: "", atmospheric_pressure: "", // group: "", member1: "", member2: "", member3: "", member4: "", member5: "", member6: "", // date: ( datetime.today().year(), datetime.today().month(), datetime.today().day(), ), // purpose: [ ], // Abstruct abstract_ja: [ ], // The paper size to use. paper-size: "a4", // The path to a bibliography file if you want to cite some external works. bibliography-file: none, enable_toc_of_image: true, enable_toc_of_table: true, // The paper's content. body, ) = { // Set the document's metadata. set document(title: title, author: author) // Set the body font. TeX Gyre Pagella is a free alternative to Palatino. set text( font: ("Noto Serif CJK JP", "Times New Roman", "Source Han Serif JP"), size: font_sizes.at("normal"), ) show strong: set text(font: ("Noto Serif CJK JP", "Times New Roman", "IPAPGothic")) // Set font size show footnote.entry: set text(10pt) show footnote: set text(15pt) show math.equation: set text(font_sizes.at("math")) set list(indent: 7pt) set enum(indent: 7pt) // Configure the page properties. set page( paper: paper-size, margin: (bottom: 1.75cm, top: 2.5cm, left: 2cm, right: 2cm), ) // citation number show ref: it => { if it.element != none and it.element.func() == figure { let el = it.element let loc = el.location() let chapt = counter(heading).at(loc).at(0) link( loc, )[#if el.kind == "image" or el.kind == "table" { // counting let num = counter(el.kind + "-chapter" + str(chapt)).at(loc).at(0) + 1 it.element.supplement " " str(chapt) "." str(num) } else if el.kind == "thmenv" { let thms = query(selector(<meta:thmenvcounter>).after(loc), loc) let number = thmcounters.at(thms.first().location()).at("latest") it.element.supplement " " numbering(it.element.numbering, ..number) } else { it } ] } else if it.element != none and it.element.func() == math.equation { let el = it.element let loc = el.location() let chapt = counter(heading).at(loc).at(0) let num = counter(math.equation).at(loc).at(0) it.element.supplement " (" str(chapt) "." str(num) ")" } else if it.element != none and it.element.func() == heading { let el = it.element let loc = el.location() let num = numbering(el.numbering, ..counter(heading).at(loc)) if el.level == 1 { str(num) "章" } else if el.level == 2 { str(num) "節" } else if el.level == 3 { str(num) "項" } } else { it } } // counting caption numbe show figure: it => { set align(center) if it.kind == "image" { set text(size: 12pt) it.body it.supplement " " + it.counter.display(it.numbering) " " + it.caption.body locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("image-chapter" + str(chapt)) c.step() }) } else if it.kind == "table" { set text(size: 12pt) it.supplement " " + it.counter.display(it.numbering) " " + it.caption.body set text(size: 10.5pt) it.body locate(loc => { let chapt = counter(heading).at(loc).at(0) let c = counter("table-chapter" + str(chapt)) c.step() }) } else { it } } // Display inline code (in a small box) show raw.where(block: false): box.with( fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt, ) // Display block code (in a larger block with more padding) show raw.where(block: true): block.with(fill: luma(240), inset: 10pt, radius: 4pt, width: 100%) // The first page. place( top + left, dx: 3.297%, dy: 2.156%, )[ #set text( font: ( "UD Digi Kyokasho N-R", "Noto Serif CJK JP", "Times New Roman", "IPAPGothic", ), ) #rect( width: 98.29%, height: 97.6%, stroke: 2.86pt, radius: 1.3pt, )[ #place( dx: -5pt, dy: -5pt, align( horizon + center, )[ #grid( columns: (25.511%, 42.586%, 34.1%), // rect( width: 100%, height: 8.12%, stroke: (left: 0pt, rest: 1.56pt), radius: (top-left: 1pt), )[#text(size: 28pt)[ #number ]], // rect( width: 100%, height: 8.12%, stroke: (left: 0pt, rest: 1.56pt), )[#text(size: 24pt, tracking: 8pt, weight: "black")[ 実験報告書 ]], // rect( width: 100%, height: 8.12%, stroke: (left: 0pt, rest: 1.56pt), )[ #university \ #school \ #department ], // ) ], ) #place( dx: -5pt, dy: -5pt, [#rect( width: 9.1%, height: 4.06%, stroke: 1.4pt, )[#align(horizon + center)[#text(size: 12.1pt, tracking: 4pt)[ 分類 ]]]], ) #place( dx: -5pt, dy: 52.1pt, [#rect( width: 102%, height: 46.6%, stroke: (bottom: 1.4pt, rest: 0pt), )[#place( dx: 37.29pt, )[ #grid( rows: ( // TODO: % to pt 11.51%, 5%, 11.23%, 4.956%, 4.78%, 6.007%, 1.9%, 5.3%, // ~天候 4.7%, 5.0%, 4.1%, 4.88%, 4.7%, 5.2%, // 共同実験者 4.6%, 4.6%, 13.5pt, 19.26pt, // 提出日~ ), [], // TODO: [#place to place // TODO: 最初の dy: 0pt をちゃんとやる [#place(dx: 7.29pt, dy: 0pt)[#text(tracking: 2.76pt)[題 目 #title]]], line(length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round")), // [#place(dx: 7.29pt)[担当教員 #mentor] #place(dx: 232.679pt)[実験室 #room]], // line( length: 383.36pt, stroke: (thickness: 1.45pt, cap: "round", dash: (197.33pt, 28.26pt, 200pt)), ), // [ #place(dx: 4.1pt)[実験年月日] #place(dx: 69.45pt)[令和 #exp_year 年] #place(dx: 168.67pt)[#exp_day 月] #place(dx: 252.3pt)[#exp_month 日] #place(dx: 296.09pt)[#exp_day_of_week 曜 ] // #place(dx: 4.1pt)[実験年月日] #place(dx: 69.45pt)[令和 #exp_year 年] #place(dx: 208.67pt)[#exp_day 月] #place(dx: 252.3pt)[#exp_month 日] #place(dx: 296.09pt)[#exp_day_of_week 曜 ] ], // line(length: 335.43pt, stroke: (thickness: 1.45pt, cap: "round")), // [#place( dx: 11.9pt, )[ #place()[天候 #weather] #place(dx: 57.6pt)[温度 #temperature °C] #place(dx: 151.6pt)[湿度 #humidity %] #place(dx: 246.23pt)[気圧 #atmospheric_pressure hPa] ]], line(length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round")), // [#place(dx: 7.6pt)[共同実験者 第 #group 班]], line(length: 146.8pt, stroke: (thickness: 1.45pt, cap: "round")), // [#place(dx: 7.46pt)[#member1] #place(dx: 139.46pt)[#member2] #place(dx: 269.46pt)[#member3]], // line( length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round", dash: (118.62pt, 14pt)), ), // [#place(dx: 7.46pt)[#member4] #place(dx: 139.46pt)[#member5] #place(dx: 269.46pt)[#member6]], // line( length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round", dash: (118.62pt, 14pt)), ), // [#place( dx: 3.78pt, )[#text()[提出年月日 #date.at(0) 年 #date.at(1) 月 #date.at(2) 日]]], line(length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round")), // [#place(dx: 3.78pt)[#text()[提出者 #id #author]]], line(length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round")), // // [#place(dx: -11.2pt)[#text()[提出者 #id #author]]], line(length: 383.8pt, stroke: (thickness: 1.45pt, cap: "round")), // ) ] ] ], ) #place(top, dx: -5pt, dy: 375.6pt, [ #rect(width: 9.2%, height: 4%, stroke: 1.4pt)[ #align(horizon + center)[#text(size: 12.1pt, tracking: 4pt)[ 概要 ]] ] ]) #place( top, dx: 8.6pt, dy: 403.7pt, [ #rect( width: 97%, height: 60%, stroke: 0pt, )[ #grid( columns: 100%, rows: (19.1pt, 8pt, 52.781pt, 15.4pt, 8pt), // place(dx: 0pt, dy: 3.6pt)[#text()[実験の目的]], // place(dx: -4.78pt)[ #line(length: 62pt, stroke: (thickness: 1.45pt, cap: "round")) ], // place( dx: 3.78pt, )[#text( size: 10pt, font: ("Noto Serif CJK JP", "Times New Roman", "IPAPGothic"), )[#purpose]], // place(dx: -3.9pt)[#text()[実験と結果の概要]], // place(dx: -4.8pt)[ #line(length: 89pt, stroke: (thickness: 1.45pt, cap: "round")) ], // place( dx: 3.78pt, )[#text( size: 10pt, font: ("Noto Serif CJK JP", "Times New Roman", "IPAPGothic"), )[#purpose]], ) ] ], ) ] ] /* // ローマ数字でのページ数(概要など) set page(footer: [ #align(center)[#counter(page).display("i")] ]) counter(page).update(1) // 概要を表紙の次のページに書きたい場合は以下を有効化 // Show abstruct // abstract_page( // abstract_ja, abstract_en, keywords_ja: keywords_ja, keywords_en: keywords_en, // ) // Configure paragraph properties. 2 set par(first-line-indent: 12pt, justify: true) // Configure chapter headings. set heading(numbering: (..nums) => { if nums.pos().len() == 1 { // 章の表示形式(フォーマット)の設定 return [#nums.pos().map(str).join(".") .] // return [第 #nums.pos().map(str).join(".") 章] } else { return [#nums.pos().map(str).join(".") #h(0.5em)] } }) let before_h1(it) = if it.numbering != none { text()[ #numbering(it.numbering, ..counter(heading).at(it.location())) ] } show heading.where(level: 1): it => { // 章毎に改ページをするなら次を利用 pagebreak() counter(math.equation).update(0) set text(weight: "bold", size: font_sizes.at("h1")) set block(spacing: 1.5em) text()[ #v(-6pt) #linebreak(justify: true) // 明示的に改行 #before_h1(it) #it.body ] } show heading.where(level: 2): it => block({ set text(weight: "medium", size: font_sizes.at("h2")) text()[ #it ] }) show heading.where(level: 3): it => block({ set text(weight: "medium", size: font_sizes.at("h3")) text()[ #it ] }) show heading: it => { set text(weight: "bold", size: font_sizes.at("under_h4")) set block(above: 2em, below: 1.5em) it } + empty_par() // 最初の段落のインデントを下げるためにダミーの段落を設置する // Start with a chapter outline. if enable_toc_of_image or enable_toc_of_table {} // Start main pages. // アラビア数字でのページ数 set page(footer: align(center)[#counter(page).display("1")]) counter(page).update(1) set math.equation(supplement: [式], numbering: equation_num) body // Display bibliography. if bibliography-file != none { show bibliography: set text(12pt) bibliography(bibliography-file, title: "参考文献", style: "ieee") } */ } // LATEX character #let LATEX = { [L];box(move(dx: -4.2pt, dy: -1.2pt, box(scale(65%)[A])));box(move(dx: -5.7pt, dy: 0pt, [T]));box(move(dx: -7.0pt, dy: 2.7pt, box(scale(100%)[E])));box(move(dx: -8.0pt, dy: 0pt, [X]));h(-8.0pt) }
https://github.com/Arrata-TTRPG/Arrata-TTRPG
https://raw.githubusercontent.com/Arrata-TTRPG/Arrata-TTRPG/main/src/sections/foreword.typ
typst
Other
= Foreword Arrata is a project I've been working on for a few years now, and it's the successor to some other custom TTRPGs I've worked on with friends. There's a lot here that is currently under development, so take much of what you read with a grain of salt; it's all subject to change until a v1.0 release is made. That said, a lot of things here are built from my experience. I've been a GM for 5 years now and I mostly see things from that point of view. I write this system with the bias that I want the systems to be as easy for me to use, the players to act, speak, and work together how I want them to. Thus, the wording of things here will be jargon-ful. If you find things that are disagreeable, you believe could be improved, you think should just be better, or if you have any questions at all, _please_, email me at: `<EMAIL>` with the title `Arrata - Suggestions/Fixes/Criticisms/Questions` and I'll get back to you as soon as I can. Hopefully you'll see your change and name (if you so choose) in the changelog and credits. I value criticism and learning from your mistakes; it's major part of Arrata, and I would be a fool to write such a system yet fail to act in a way that demonstrates those principles. #pagebreak()
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/lib/code-callouts.typ
typst
Other
#import "./definitions.typ": * #let default-callout(number /*: int */) /*: content*/ = { text( font: secondary-font, number-type: "old-style", size: 1em, weight: "bold", fill: luma(120), "[" + str(number) + "]", ) } #let unicode-circle-callout(number /*: int */) /*: content*/ = { str.from-unicode( if number == 0 { 0x24EA } else if number <= 20 { 0x245F + number } else if number <= 35 { 0x3250 + (number - 20) } else if number <= 50 { 0x32B0 + (number - 35) } else { number } ) } #let callout-pat = regex("<(\\d+)>(\\n|$)") #let parse-callouts( code-text /*: str */ ) /*: (callouts: array(array(int)), text: str) */ = { let callouts /*: array(array(int)) */ = () let new-text = "" for text-line in code-text.split("\n") { let match = text-line.match(callout-pat) if match != none { callouts.push((int(match.captures.at(0)),)) new-text += text-line.slice(0, match.start) } else { callouts.push(()) new-text += text-line } new-text += "\n" } (callouts: callouts, text: new-text) } #let processed-label = <TypstCodeCallout-was-processed> #let code-with-callouts = ( it /*: content(raw) */, callout-display: default-callout /*: function(str, content) */ ) => { if it.at("label", default: none) == processed-label { it } else { let (callouts, text: new-text) = parse-callouts(it.text) show raw.line: it => { it let callouts-of-line = callouts.at(it.number - 1, default: ()) for callout in callouts-of-line { callout-display(callout) } } let fields = it.fields() let _ = fields.remove("text") let _ = fields.remove("lines") let _ = fields.remove("theme") [#raw(..fields, new-text)#processed-label] } }
https://github.com/01mf02/jq-lang-spec
https://raw.githubusercontent.com/01mf02/jq-lang-spec/main/README.md
markdown
# A formal specification of the jq language This is an ongoing effort to create a formal specification of the programming language provided by [`jq`]. A rendered version is available [here](https://github.com/01mf02/jq-lang-spec/releases/latest/download/spec.pdf). Run `typst compile spec.typ` to generate a PDF version of the specification. For this, Typst 0.10 should be installed. [`jq`]: https://jqlang.github.io/jq/
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/control-flow-while.typ
typst
Apache License 2.0
#while #while i #while i {} #while i [] #while i {}1 #while i []a #while i {} 1 #while i [] a #while i {};1 #while i [];a #while i {} {} #while i [] [] #while i [] {} #while i {} 1 #while i [] 1
https://github.com/vimkat/typst-ohm
https://raw.githubusercontent.com/vimkat/typst-ohm/main/src/templates/event-sign.typ
typst
MIT License
#import "../lib/vars.typ" #import "../lib/utils.typ" #import "../lib/elements.typ" as elems #let _arrow-v = polygon( fill: vars.red, stroke: none, (70pt, 0%), (70pt, 80%), (0pt, 80%), (50pt, 100%), (100pt, 80%), (30pt, 80%), (30pt, 0%), ) #let _arrow-h = polygon( fill: vars.red, stroke: none, (0%, 70pt), (85%, 70pt), (85%, 0pt), (100%, 50pt), (85%, 100pt), (85%, 30pt), (0%, 30pt) ) #let event-sign( body, arrow: none, // top, bottom, left, right, none title: none, room: none, event: none, date: none, ) = { set text(font: vars.font, weight: "bold", size: 30pt) set align(center + horizon) if arrow not in (top, bottom, left, right, none) { panic("Alignment is not one of 'top', 'bottom', 'left', 'right' or 'none'") } let content = align(left, { if title == none and room != none { title = room; room = none } if title != none { set text( fill: vars.red, size: utils.ternary(body != none, 1.5em, 2em), weight: "bold" ) block(upper(title)) if room != none { v(0.5em, weak: true) set text(size: 0.5em, weight: "extrabold") block(room) } v(1em, weak: true) } body }) page( flipped: true, paper: "a4", footer: { set align(right) set text(size: 10pt, weight: "regular") event if date != none [ #utils.ternary(event != none, elems.pipe, none) #date.display("[day].[month].[year]")] }, if (arrow == none) { content } else [ #grid( columns: utils.ternary(arrow in (top, bottom), (auto, 1fr), 1), rows: utils.ternary(arrow in (left, right), (auto, 1fr), 1), column-gutter: 2em, row-gutter: 1em, if arrow.axis() == "vertical" { align(center + horizon, rotate( utils.ternary(arrow == top, 180deg, 0deg), _arrow-v) ) } else { align(center + horizon, rotate( utils.ternary(arrow == left, 180deg, 0deg), _arrow-h) ) }, content, ) ], ) }
https://github.com/Dherse/codly
https://raw.githubusercontent.com/Dherse/codly/main/README.md
markdown
MIT License
# Codly: simple and powerful code blocks <p align="center"> <a href="https://github.com/Dherse/codly/blob/main/docs.pdf"> <img alt="Documentation" src="https://img.shields.io/website?down_message=offline&label=manual&up_color=007aff&up_message=online&url=https%3A%2F%2Fgithub.com%2FDherse%2Fcodly%2Fblob%2Fmain%2Fdocs.pdf" /> </a> <a href="https://github.com/Dherse/codly/blob/main/LICENSE"> <img alt="MIT License" src="https://img.shields.io/badge/license-MIT-brightgreen"> </a> <img src="https://github.com/Dherse/codly/actions/workflows/test.yml/badge.svg" /> </p> Codly is a package that lets you easily create **beautiful** code blocks for your Typst documents. It uses the newly added [`raw.line`](https://typst.app/docs/reference/text/raw/#definitions-line) function to work across all languages easily. You can customize the icons, colors, and more to suit your document's theme. By default it has zebra striping, line numbers, for ease of reading. A full set of documentation can be found [in the repo](https://raw.githubusercontent.com/Dherse/codly/main/docs.pdf). ![Example](./demo.png) ````typ #import "@preview/codly:1.0.0": * #show: codly-init.with() #codly( languages: ( rust: ( name: "Rust", icon: text(font: "tabler-icons", "\u{fa53}"), color: rgb("#CE412B") ), ) ) ```rust pub fn main() { println!("Hello, world!"); } ``` ```` ### Setup To start using codly, you need to initialize codly using a show rule: ```typ #show: codly-init.with() ``` > [!TIP] > You only need to do this once at the top of your document! Then you *can* configure codly with your parameters: ```typ #codly( languages: ( rust: (name: "Rust", icon: "\u{fa53}", color: rgb("#CE412B")), ) ) ``` > [!IMPORTANT] > Any parameter that you leave blank will use the previous values (or the default value if never set) similar to a `set` rule in regular typst. But the changes are always global unless you use the provided `codly.local` function. To get a full list of all settings, see the [documentation](https://raw.githubusercontent.com/Dherse/codly/main/docs.pdf). Then you just need to add a code block and it will be automatically displayed correctly: ```` ```rust pub fn main() { println!("Hello, world!"); } ``` ```` ### Disabling To locally disable codly, you can just do the following, you can then later re-enable it using the `codly` configuration function. ```typ #disable-codly() ``` Alternatively, you can use the `no-codly` function to achieve the same effect locally: ````typ #no-codly[ ```typ I will be displayed using the normal raw blocks. ``` ] ```` ### Setting an offset If you wish to add an offset to your code block, but without selecting a subset of lines, you can use the `codly-offset` function: ```typ // Sets a 5 line offset #codly-offset(5) ``` ### Selecting a subset of lines If you wish to select a subset of lines, you can use the `codly-range` function. By setting the start to 1 and the end to `none` you can select all lines from the start to the end of the code block. ```typ #codly-range(start: 5, end: 10) ``` ### Adding a "skip" You can add a "fake" skip between lines using the `skips` parameters: ```typ // Before the 5th line (indexing start at 0), insert a 32 line jump. #codly(skips: ((4, 32), )) ``` The code inside your block will be the same (except for the added line containing the … character), but the line numbers will be adjusted to reflect the skip. This can be customized using the `skip-line` and `skip-number` to customize what it looks like. ### Adding annotations > [!IMPORTANT] > This is a Beta feature and has a few quirks, refer to [the documentation](https://raw.githubusercontent.com/Dherse/codly/main/docs.pdf) for those You can annotate a line/group of lines using the `annotations` parameters : ```typ // Add an annotation from the second line (0 indexing) to the 5th line included. #codly( annotations: ( ( start: 1, end: 4, content: block( width: 2em, // Rotate the element to make it look nice rotate( -90deg, align(center, box(width: 100pt)[Function body]) ) ) ), ) ) ``` ### Disabling line numbers You can configure this with the `codly` function: ```typ #codly(number-format: none) ``` ### Disabling zebra striping You disable zebra striping by setting the `zebra-fill` to white or none. ```typ #codly(zebra-fill: none) ``` ### Customize the stroke You can customize the stroke surrounding the figure using the `stroke` parameter of the `codly` function: ```typ #codly(stroke: 1pt + red) ``` ### Misc You can also disable the icon by setting the `display-icon` parameter to `false`: ```typ #codly(display-icon: false) ``` This applies to: - the name - the radius - whether the block is breakable - the padding - the width of the numbers columns and so many more. For more detailed information check out the [documentation](https://raw.githubusercontent.com/Dherse/codly/main/docs.pdf).
https://github.com/linhduongtuan/VNUHCM-typst-poster
https://raw.githubusercontent.com/linhduongtuan/VNUHCM-typst-poster/main/examples/example.typ
typst
MIT License
#import "../poster.typ": * #show link: underline #show: poster.with( size: "36x24", title: "A typesetting system to untangle the scientific writing process", authors: "<NAME>", departments: "Department of Computer Science", univ_logo_1: "images/bgd.png", univ_logo_2: "images/bk.png", header_text: "HO CHI MINH CITY UNIVERSITY OF TECNOLOGY", header_url: "https://vnuhcm.edu.vn/", header_email_ids: "DƯƠNG TUẤN LINH - 10 tháng 6 năm 2023", header_color: "#00CCCC", footer_text: "Conference on Typesetting Systems, 2023", footer_url: "https://www.uit.edu.vn/", footer_email_ids: "<EMAIL>", footer_color: "#00CCCC", // Modifying the defaults keywords: ("Typesetting", "Scientific Writing", "Typst"), ) = #block( fill: rgb("#00FFFF"), inset: 10pt, radius: 90pt, width: 100%, [ Introduction ] ) #v(-0em) #lorem(3) #lorem(100) #figure( image("../images/Women_operating_typesetting_machines.png", width: 50%), caption: [#lorem(10)] ) #lorem(60) = #block( fill: aqua, //rgb("#9999FF"), inset: 10pt, radius: 90pt, width: 100%, [ MATERIALS AND METHODS ] ) == #block( fill: rgb("#CCFFCC"), inset: 10pt, radius: 90pt, width: 22%, [ MATERIALS ] ) #lorem(30) + #lorem(10) + #lorem(10) + #lorem(10) #lorem(50) #set align(center) #table( columns:(auto, auto, auto), inset:(10pt), [#lorem(4)], [#lorem(2)], [#lorem(2)], [#lorem(3)], [#lorem(2)], [$alpha$], [#lorem(2)], [#lorem(1)], [$beta$], [#lorem(1)], [#lorem(1)], [$gamma$], [#lorem(2)], [#lorem(3)], [$theta$], ) #set align(left) #lorem(80) $ mat( 1, 2, ..., 8, 9, 10; 2, 2, ..., 8, 9, 10; dots.v, dots.v, dots.down, dots.v, dots.v, dots.v; 10, 10, ..., 10, 10, 10; ) $ == #block( fill: rgb("#FFCCCC"), inset: 10pt, radius: 90pt, width: 20%, [ METHODS ] ) #lorem(65) #figure( image("../images/Standard_lettering.png", width: 100%), caption: [#lorem(8)] ) = #block( fill: rgb("#E5CCFF"), inset: 10pt, radius: 90pt, width: 100%, [ RESULTS ] ) == #block( fill: rgb("#E5CCBB"), inset: 10pt, radius: 90pt, width: 30%, [ ROSETTA STONE ] ) #block( fill: luma(230), inset: 8pt, radius: 4pt, [ #lorem(80), - #lorem(10), - #lorem(10), - #lorem(10), ] ) == #block( fill: rgb("#E5CCBB"), inset: 10pt, radius: 90pt, width: 40%, [ QUANTUM COMPUTER ] ) #lorem(75) ```rust fn factorial(i: u64) -> u64 { if i == 0 { 1 } else { i * factorial(i - 1) } } ``` = #block( fill: rgb("#E5CCBB"), inset: 10pt, radius: 90pt, width: 100%, [ CONCLUSIONS ] ) #lorem(100) - #lorem(10) - #lorem(5) - #lorem(8) - #lorem(15) - #lorem(9) - #lorem(7) $ sum_(k=1)^n k = (n(n+1)) / 2 = (n^2 + n) / 2 $ #block( fill: luma(230), inset: 8pt, radius: 4pt, [ #lorem(30), ] ) #figure( image("../images/Rosetta_stone.png", width: 35%), caption: [#lorem(30)] ) = #block( fill: rgb("#E5CCBB"), inset: 10pt, radius: 90pt, width: 100%, [ ACKNOWLEDGEMENT ] ) - Thank you, #link("https://github.com/pncnmnp/typst-poster")[<NAME>ikh], for the amazing tutorial on how to create a poster using Typst
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/math/prime.typ
typst
Apache License 2.0
// Test prime symbols after code mode. #let g = $f$ #let gg = $f$ $ #(g)' #g' #g ' \ #g''''''''''''''''' \ gg' $
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/functionalities/config.typ
typst
== Config The config functionality represents configuration data. The configuration data is data that is automatically read by the provider from its registers. As the config is automatically read by the provider, there is no need for an additional signal associated with the config, indicating the config write by the requester. By default, a config can be written and read by the requester. The config functionality has following properties: *`atomic`*` bool (true) {definitive}` #pad(left: 1em)[ The atomic property defines whether an access to the config must be atomic. If atomic is true, then the provider must guarantee that any change of the config value, triggered by the requester write, is seen as an atomic change by the other modules of the provider. This is especially important when the config spans more than single register, as in case of single register write the change is always atomic. ] *`init-value`*` bit string (uninitialized) {definitive}` #pad(left: 1em)[ The init-value property defines the initial value of the config. ] *`range`*` range | [range] (None) {definitive}` #pad(left: 1em)[ The range property defines the range of valid values. Range bound values shall not be negative. This is because the FBDL makes no assumptions on the negative values encoding. To accomplish negative range checks functions such as `u2` must be explicitly called. For example, following assignment limits the possible range from -16 to -8: `range = u2(-8, 8):u2(-16, 8)`. The range property shall not be explicitly set if the width property is already set. If the range property is not set, then the actual range implies from the width property. The code generated for the provider is not required to check or report if the value provided for the config write is within the valid range. The recommended way is to implement compiler parameter allowing enabling/disabling range check generation. ] *`read-value`*` bit string (uninitialized) {definitive}` #pad(left: 1em)[ The read-value property defines the value returned by the provider on the config read. If the read-value is not set, then the provider must return the actual value of the config. ] *`reset-value`*` bit string (uninitialized) {definitive}` #pad(left: 1em)[ The reset-value property defines the value of the config after the reset. If the reset-value is set, but a bus or block containing the config is not resettable (`reset = None`), then the compiler shall report an error. ] *`width`*` integer (bus width) {definitive}` #pad(left: 1em)[ The width property defines the bit width of the config. The width property shall not be explicitly set if the range property is already set. ] The code generated for the requester must provide means for writing and reading the config.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/036_Guilds%20of%20Ravnica.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Guilds of Ravnica", doc) #include "./036 - Guilds of Ravnica/001_Under the Cover of Fog.typ" #include "./036 - Guilds of Ravnica/002_Testing the Dark Waters.typ" #include "./036 - Guilds of Ravnica/003_Clans & Legions.typ" #include "./036 - Guilds of Ravnica/004_Death's Precious Moments.typ" #include "./036 - Guilds of Ravnica/005_Bound and Bonded.typ" #include "./036 - Guilds of Ravnica/006_The Ascension of Reza.typ" #include "./036 - Guilds of Ravnica/007_The Gathering Storm: Chapter 1.typ" #include "./036 - Guilds of Ravnica/008_The Gathering Storm: Chapter 2.typ" #include "./036 - Guilds of Ravnica/009_The Gathering Storm: Chapter 3.typ" #include "./036 - Guilds of Ravnica/010_The Gathering Storm: Chapter 4.typ" #include "./036 - Guilds of Ravnica/011_The Gathering Storm: Chapter 5.typ" #include "./036 - Guilds of Ravnica/012_The Gathering Storm: Chapter 6.typ" #include "./036 - Guilds of Ravnica/012_The Gathering Storm: Chapter 7.typ" #include "./036 - Guilds of Ravnica/013_The Gathering Storm: Chapter 8.typ" #include "./036 - Guilds of Ravnica/014_The Gathering Storm: Chapter 9.typ" #include "./036 - Guilds of Ravnica/015_The Gathering Storm: Chapter 10.typ"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/raw-align_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Text inside raw block should follow the specified alignment. #set page(width: 180pt) #set text(6pt) #lorem(20) #align(center, raw( lang: "typ", block: true, align: right, "#let f(x) = x\n#align(center, line(length: 1em))", )) #lorem(20)
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/united/src/lib.typ
typst
#import "united.typ": num, qty, unit, numrange, qtyrange // Set default parameters for all functions in this module. // // This is a convenience function that allows you to set the parameters for all // functions in this module at once. It is equivalent to calling `with` on each // function individually. // // Parameters: // - product: The symbol to use for the exponent product. // - uncertainty: How to display uncertainties. Can be "plusminus" or // "parentheses". // - decimal-sep: The decimal separator. // - group-sep: The separator between digit groups. // - delim: Delimiter between numbers in a range. // - delim-space: Space between the numbers and the delimiter. // - unit-sep: The separator between units. // - per: How to format fractions. Can be "reciprocal", "fraction" or a custom // symbol. // // Returns: // - num: A function that formats numbers. // - qty: A function that formats quantities. // - unit: A function that formats units. // - numrange: A function that formats number ranges. // - qtyrange: A function that formats quantity ranges. #let with( product: math.dot, uncertainty: "plusminus", decimal-sep: ".", group-sep: math.thin, delim: "to", delim-space: math.space, unit-sep: math.thin, per: "reciprocal" ) = ( num: num.with( product: product, uncertainty: uncertainty, decimal-sep: decimal-sep, group-sep: group-sep ), qty: qty.with( product: product, uncertainty: uncertainty, decimal-sep: decimal-sep, group-sep: group-sep, unit-sep: unit-sep, per: per ), unit: unit.with( unit-sep: unit-sep, per: per ), numrange: numrange.with( product: product, uncertainty: uncertainty, decimal-sep: decimal-sep, group-sep: group-sep, delim: delim, delim-space: delim-space ), qtyrange: qtyrange.with( product: product, uncertainty: uncertainty, decimal-sep: decimal-sep, group-sep: group-sep, delim: delim, delim-space: delim-space, unit-sep: unit-sep, per: per ) )
https://github.com/masaori/diffusion-model-quantum-annealing
https://raw.githubusercontent.com/masaori/diffusion-model-quantum-annealing/main/test.typ
typst
#import "theorem.typ" : theorem, claim = A == B #theorem("aaa")[ phi = 1 "AAAAA" $1234$ @hoge2 $ "AAAAA" $ ]<fuga> #claim(none)[ $ 1 * 3 - 1 = 2 $ @fuga ]<hoge2>
https://github.com/Enter-tainer/mino
https://raw.githubusercontent.com/Enter-tainer/mino/master/mino.typ
typst
MIT License
#import "typst-package/lib.typ": decode-fumen, render-field #set page(margin: 1cm, height: auto, fill: white) #set text(lang: "zh", region: "cn", font: ("New Computer Modern", "Source Han Sans SC")) #align(center)[ #text(size: 25pt)[ `@preview/mino:0.1.1` ] ] = Render Field #let custom-field = ` ___ZSS L__ZZSS LtttZJJJOO LLtIIIIJOO ` #table(columns: (auto, 1fr), stroke: none, align: horizon, gutter: 1em, [#render-field(custom-field, rows: 5, cell-size: 15pt) ], [ ```typst #import "@preview/mino:0.1.1": render-field #let custom-field = ` ___ZSS L__ZZSS LtttZJJJOO LLtIIIIJOO ` #render-field(custom-field, rows: 5, cell-size: 15pt) ``` ]) = Render Fumen ```typ #import "@preview/mino:0.1.1": decode-fumen, render-field #let fumen = decode-fumen("v115@...") #for i in range(fumen.len()) { let field = fumen.at(i).at("field") [ #box[ #render-field(field, rows: 8, cell-size: 13pt) (#(i+1)) #fumen.at(i).comment ] #h(0.5pt) ] } ``` #let fumen = decode-fumen("v115@vhPJHYaAkeEfEXoC+BlvlzByEEfE03k2AlP5ABwfAA?A+rQAAqsBsqBvtBTpBVhQeAlvlzByEEfE03k2AlP5ABwvDf?E33ZBBlfbOBV5AAAOfQeAlvl<KEY>") #for i in range(8) { let field = fumen.at(i).at("field") [ #box[ #render-field(field, rows: 8, cell-size: 13pt) (#(i+1)) #fumen.at(i).comment ] #h(0.5pt) ] }
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/seq.typ
typst
MIT License
#let fib(n) = { let a = 0 let b = 1 for _ in range(1, n) { (a,) let temp = b b = a + b a = temp } }
https://github.com/pluttan/typst-bmstu
https://raw.githubusercontent.com/pluttan/typst-bmstu/main/bmstu/report_tituls.typ
typst
MIT License
#import "g7.32-2017.typ": гост732-2017 #let титул( факультет: "", кафедра: "", код_направления: "", направление: "", дисциплина: "", тип_работы: "", номер_работы: "", название_работы: "", название_работы_кол2:"", автор: (), руководитель: (), город: "", дата: false, год: datetime.today().display("[year]"), ) = { set document(title: название_работы) set page(margin: (bottom: 10mm)) if (дата == true) { дата = datetime.today().display("[day].[month].[year repr:last_two]") } set align(center) set text(size: 10pt) grid( columns: (18%, 85%), align(left)[ #v(-10pt) #figure( placement: bottom, image("bmstu_logo.jpg", width: 70%), ) ], par(leading: 0.5em)[#align(center)[ *Министерство науки и высшего образования Российской Федерации\ Федеральное государственное бюджетное образовательное учреждение\ высшего образования\ «Московский государственный технический университет\ имени Н.Э. Баумана\ (национальный исследовательский университет)»\ (МГТУ им. Н.Э. Баумана)* ]] ) line(length: 100%, stroke:3pt) v(-10pt) line(length: 100%, stroke:0.5pt) v(10pt) set text(weight: "regular", size: 11pt) par(first-line-indent: 0em)[ #align(left)[ #upper[факультет] *#upper(факультет)* ] #align(left)[ #upper[кафедра] *#upper(кафедра)* ] #align(left)[ #grid( columns: (auto, auto, auto), gutter: 2pt, upper[направление подготовки], text(weight: "bold")[#upper(код_направления)], text(weight: "bold")[#upper(направление)], ) ] ] v(-40pt) set align(center + horizon) text(tracking: 5pt, weight: "bold", size: 16pt)[ОТЧЕТ] set text(tracking: 0pt, size:14pt, weight: "bold") if (тип_работы != "") and (номер_работы != "") { align(center)[ #grid( columns: 2, align(right)[по #тип_работы № ], align(center)[ #v(2pt) #номер_работы #v(-14pt) #line(length: 40pt, stroke: 1pt) #h(0pt) ] ) ] } else { } if дисциплина != "" { align(left)[ #grid( columns: 2, align(right)[Дисциплина: #h(5pt)], align(left)[ #v(2pt) #h(5pt) #дисциплина #v(-14pt) #line(length: 380pt, stroke: 1pt) ] ) ] } if название_работы != "" { align(left)[ #grid( columns: 2, align(right)[ #align(top)[Название: #h(5pt)] #(if название_работы_кол2 != ""{v(22pt)}) ], align(left)[ #set text(weight:"regular") #par(first-line-indent: 0em)[#название_работы] #v(-14pt) #line(length: 400pt, stroke: 1pt) #(if название_работы_кол2 != ""{ v(-6pt) h(5pt) название_работы_кол2 v(-14pt) line(length: 400pt, stroke: 1pt) }) ] ) ] } set text(weight:"regular") set align(bottom) grid( columns: (60pt, 100pt, 2.5fr), gutter: 50pt, align(left)[Студент #v(12pt)], align(center)[ #v(2pt) #автор.группа #v(-14pt) #line(length: 90pt, stroke: 1pt) #v(-14pt) #text(size:10pt)[(Группа)] ], grid( columns:(3fr, 4fr), gutter:10pt, align(center)[ #v(2pt) #if (дата != false) {align(right)[#дата]} #v(-14pt) #line(length: 90pt, stroke: 1pt) #v(-14pt) #text(size:10pt)[(Подпись, дата)] ], align(center)[ #v(2pt) #автор.фио #v(-14pt) #line(length: 110pt, stroke: 1pt) #v(-14pt) #text(size:10pt)[(И. О. Фамилия)] ], ) ) grid( columns: (100pt, 1fr, 2.5fr), gutter: 40pt, align(left)[Преподаватель #v(12pt)], align(center)[ ], grid( columns:(3fr, 4fr), gutter:10pt, align(center)[ #v(2pt) #if (дата != false) {align(right)[#дата]} #v(-14pt) #line(length: 90pt, stroke: 1pt) #v(-14pt) #text(size:10pt)[(Подпись, дата)] ], align(center)[ #v(2pt) #par(leading: 0.3em)[#руководитель.фио] #v(-14pt) #line(length: 110pt, stroke: 1pt) #v(-14pt) #text(size:10pt)[(И. О. Фамилия)] ], ) ) v(20pt) set align(center) [#город #год г.] } #let титул_иу6( код_направления: "", направление: "", дисциплина: "", тип_работы: "", номер_работы: "", название_работы: "", название_работы_кол2:"", автор: (), руководитель: (), город: "", дата: false, год: datetime.today().display("[year]"), ) = титул( факультет: "Информатика и системы управления", кафедра: "Компьютерные системы и сети", код_направления: код_направления, направление: направление, дисциплина: дисциплина, тип_работы: тип_работы, номер_работы: номер_работы, название_работы: название_работы, название_работы_кол2: название_работы_кол2, автор: автор, руководитель: руководитель, город: город, дата: дата, год: год, ) #let титул_иу6_ивт( дисциплина: "", тип_работы: "", номер_работы: "", название_работы: "", название_работы_кол2:"", автор: (), руководитель: (), город: "", дата: false, год: datetime.today().display("[year]"), ) = титул_иу6( код_направления: "09.03.01/03", направление: "Вычислительные машины, комплексы, системы и сети", дисциплина: дисциплина, тип_работы: тип_работы, номер_работы: номер_работы, название_работы: название_работы, название_работы_кол2: название_работы_кол2, автор: автор, руководитель: руководитель, город: город, дата: дата, год: год, )
https://github.com/HenkKalkwater/aoc-2023
https://raw.githubusercontent.com/HenkKalkwater/aoc-2023/master/parts/day-4-2.typ
typst
#import "day-4-1.typ": parse, count-sorted #let solve = (input) => { let winning-numbers-count = parse(input).map(pair => count-sorted(pair.first(), pair.last()).len()) let card-count = range(winning-numbers-count.len()).map(_ => 1) for (i, win-count) in winning-numbers-count.enumerate() { card-count = card-count.enumerate() .map(((j, count)) => { if j > i and j <= i + win-count { count + card-count.at(i, default: 0) } else { count } }) } //card-count.sum() (card-count.sum(), winning-numbers-count, card-count) }
https://github.com/enseignantePC/2023-24
https://raw.githubusercontent.com/enseignantePC/2023-24/master/Chapitre1/ex/ex1.typ
typst
#import "../../act_template.typ": * #show : it => activité( kind: [Exercice], chapter_name: [Identification des espèces chimiques.], // number: 1, it, ) #set text(size: 12pt) #let minititle = minititle.with(size:15pt) #let c = counter("ex") #c.step() #let c = [#c.display()) #c.step()] #let csv_unwrap(x, d: "\t") = { let x = csv(delimiter: d, x) table( align: center + horizon, columns: x.at(1).len(), ..x.flatten().map(str) .map(eval.with(mode: "markup")) ) } #figure(placement: bottom,supplement: "tableau", caption: "Éther et eau", csv_unwrap(d:";","eau_ether.csv")) <tab1> #columns(2)[ #minititle[*#c Calculer une masse volumique*] On introduit 15 mL d'éthanol dans une éprouvette graduée placée sur une balance tarée. La masse de cet échantillon d'éthanol est de 12 g. + Exprimer littéralement puis calculer la masse volumique de l'éthanol en g·cm-3. + Exprimer la masse d'éthanol en kilogramme, et le volume en m3. Rappel : $1 m^3 = 1 times 10^3 L$. + En déduire la valeur de la masse volumique de l'éthanol en kg·m-3. + Si un $m^3$ d'eau correspond à 1000 Litres, combien $1"cm"^3$ d'eau correspond t-il en $"cm"^3$. (Il y a 4 unités différentes dans cette phrase.) #minititle[*#c Décrire la composition d'un mélange*] On introduit dans une éprouvette graduée 5,0 mL d' eau et 15,0 mL d'éther. On mélange puis on laisse décanter. + Dans quel état physique ces deux espèces chimiques se trouvent-elles à la température ambiante (20 °C), et avant le mélange ? Justifier la réponse. + Déterminer les masses d'eau et d'éther introduites dans l'éprouvette. + Faire un schéma légendé de l'éprouvette graduée en indiquant la position et la composition des phases (= liquides). _Données: _ - voir le @tab1 en bas de la page. - l'eau et l'ether ne sont pas miscible. #colbreak() #minititle[*#c Savoir si une solution est saturée*] On prépare une solution en introduisant 50 g de chlorure de sodium (sel) dans un bécher contenant 100 mL d'eau. + Calculer la masse maximale de chlorure de sodium que l'on peut dissoudre dans $V=100 "mL"$ d'eau. + En déduire si la solution obtenue est saturée. _Données: _Solubilité du chlorure de sodium dans l'eau : s(NaCL) = 360 g·L-1 à 20 °C. #minititle[*#c Étalon*] Le kilogramme est l'unité de base de la masse dans le système international. L'étalon, prototype du kilogramme, est conservé par le Bureau international des poids et mesures (BIPM). Surnommé le « grand K », ce prototype a été réalisé en platine iridié (90 % de platine et 10 % d'iridium en masse) et prend la forme d'un cylindre de 39,17 mm de hauteur. + *Calculer* le diamètre du prototype, et le comparer à la hauteur du grand K. (Commencer par faire un schéma). + *Calculer* la hauteur h qu'aurait l'étalon si il était constitué uniquement d'iridium (mais pesait toujours 1 kg). _Données:_ - $rho_"étalon"$ =21,19 g.cm-3 ; - $rho_"platine"$=21,5 g·cm-3 ; - $rho_"iridium"$=22,6 g·cm-3. - Volume d'un cylindre de rayon R et de hauteur h : $V = pi R 2 h$ ]
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/basics/math/grouping.md
markdown
MIT License
# Grouping Every grouping can be (currently) done by parenthesis. So the parenthesis may be both "real" parenthesis and grouping ones. For example, these parentheses specify nominator of the fraction: ```typ $ (a^2 + b^2)/2 $ ``` ## Left-right > See [official documentation](https://typst.app/docs/reference/math/lr). If there are two matching braces of any kind, they will be wrapped as `lr` (left-right) group. ```typ $ {[((a + b)/2) + 1]_0} $ ``` You can disable it by escaping. You can also match braces of any kind by using `lr` directly: ```typ $ lr([a/2, b)) \ lr([a/2, b), size: #150%) $ ``` ## Fences Fences _are not matched automatically_ because of large amount of false-positives. You can use `abs` or `norm` to match them: ```typ $ abs(a + b), norm(a + b), floor(a + b), ceil(a + b), round(a + b) $ ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/down/0.1.0/sample.typ
typst
Apache License 2.0
#import "./lib.typ": * Examples in README: $ Lim(x, +0) x ln(sin x) = cLim ln(sin x) / x^(-1) = cLim x / (sin x) cos x = 0 $ $ Sum(n, 0, oo) 1 / sqrt(n + 1) = Sum(#none, 0, #none) 1 / sqrt(n) = cSum 1 / n^(1 / 2) $ $ Integral(0, pi / 3, sqrt(1 + tan^2 x)) = cIntegral(1 / (cos x)) = cIntegrated(ln (cos x / 2 + sin x / 2) / (cos x / 2 - sin x / 2)) = ln (2 + sqrt(3)) $ Calculate the area of the region bounded by the curves $y = e^(x / 2) sin sqrt(3) / 2 x$ and $x$ axis: $ S =& Lim(alpha, -oo) Integral(alpha, 0, e^(x / 2) abs(sin sqrt(3) / 2 x)) \ =& Lim(n, oo) Sum(k, 0, n) (-1)^(k - 1) Integral( -(2 (k + 1)) / sqrt(3) pi, -(2 k) / sqrt(3) pi, e^(x / 2) sin sqrt(3) / 2 x ) \ =& cLim cSum (-1)^(k - 1) cIntegrated(e^(x / 2) sin(sqrt(3) / 2 x - pi / 3)) \ =& Fac(sqrt(3) / 2) cLim cSum (e^(-k / sqrt(3) pi) + e^(-(k + 1) / sqrt(3) pi)) = cFac cLim cSum (1 + e^(-pi / sqrt(3))) e^(-k / sqrt(3) pi) \ =& cFac cLim (1 + e^(-pi / sqrt(3))) (1 - (e^(-pi / sqrt(3)))^n) / (1 - e^(-pi / sqrt(3))) = cFac $ Calculate the surface area of an ellipse: $ S =& Fac(2 pi) Integral(-a, a, abs(y) sqrt(1 - (|y|')^2)) \ =& cFac cIntegral(b / a cancel(sqrt(a^2 - x^2)) sqrt((a^4 - (a^2 - b^2) x^2) / (a^2 cancel(a^2 - x^2)))) \ =& cFac cIntegral(b / a sqrt(a^2 - (a^2 - b^2) / a^2 x^2)) \ =& Fac(4 pi b) Integral(0, a, sqrt(1 - e^2 / a^2 x^2)) quad (e^2 = (a^2 - b^2) / a^2)\ =& Fac(4 pi (a b) / e) Integral(0, arcsin e, sqrt(1 - sin^2 theta) cos theta, dif: theta) quad (theta = arcsin e / a x)\ =& cFac cIntegral(cos^2 theta) = Fac(2 pi (a b) / e) cIntegral(1 + cos 2 theta) \ =& cFac cIntegrated(theta + 1 / 2 sin 2 theta) = cFac cIntegrated(theta + sin theta sqrt(1 - sin^2 theta)) \ =& cFac (arcsin e + e sqrt(1 - e^2)) \ $
https://github.com/desid-ms/desid_report
https://raw.githubusercontent.com/desid-ms/desid_report/main/_extensions/desid_report/template.typ
typst
MIT License
$definitions.typ()$ $typst-template.typ()$ $typst-show.typ()$ $for(header-includes)$ $header-includes$ $endfor$ $for(include-before)$ $include-before$ $endfor$ $body$ $notes.typ()$ $biblio.typ()$ $for(include-after)$ $include-after$ $endfor$
https://github.com/Dav1com/minerva-report-fcfm
https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/lib/rules.typ
typst
MIT No Attribution
/// Show rule que cambia el formato de los números para usar coma decimal. /// /// #example(``` /// #show: minerva.rules.formato-numeros-es /// $1.2 + 4.8$ /// ```, mode: "markup") /// /// - doc (content): documento a aplicar reglas /// -> content #let formato-numeros-es(doc) = { // https://github.com/typst/typst/issues/1093#issuecomment-1536620129 show math.equation: it => { show regex("\d+.\d+"): it => { show ".": {","+h(0pt)} it } it } doc } /// Esta show rule cambia los operadores definidos por Typst para /// que estén en español. /// /// - doc (content): Contenido a aplicar las reglas. /// -> content #let operadores-es(doc) = { show math.op.where(text: [#"inf"]): it => { show "inf": "ínf" it } show math.op.where(text: [#"lim"]): it => { show "lim": "lím" it } show math.op.where(text: [#"lim\u{2009}inf"]): it => { show "lim\u{2009}inf": "lím\u{2009}ínf" it } show math.op.where(text: [#"lim\u{2009}sup"]): it => { show "lim\u{2009}sup": "lím\u{2009}sup" it } show math.op.where(text: [#"max"]): it => { show "max": "máx" it } show math.op.where(text: [#"min"]): it => { show "min": "mín" it } doc } /// Hace que el primer heading con numbering esté en una página nueva. Esta /// show rule es aplicada por defecto en el template. Puede ser desactivada /// usando el parámetro `showrules: false` en la show rule del template. /// Puede ser reactivada agregando esta línea: /// ```typ /// show: primer-heading-en-nueva-pag /// ``` /// /// - doc (content): Documento a aplicar la regla. /// -> content #let primer-heading-en-nueva-pag(doc) = { show heading: it => context { if counter(heading).get() == (1,) { pagebreak(weak: true) it } else { it } } doc } /// Permite que el documento compile aún si hay referencias rotas, /// mostrando un mensaje en lugar de la referencia. /// /// - mensaje (content): Mensaje a mostrar. /// - doc (content): Documento a aplicar la regla. /// -> content #let permite-ref-rotas(mensaje: text(fill: red, "<ref>"), doc) = { show ref: it => { if it.element == none { mensaje } } doc } /// Aplica los estilos por defecto a las figuras con alguno de los `kind` /// especificados. /// /// - kind-target (array): Lista de strings con los kind a afectar. /// - doc (content): Documento a aplicar las reglas. /// -> content #let estilos-figure(kind-target: ("image", "table"), doc) = { let style-acc = (it) => it for kind in kind-target { style-acc = (it) => { show figure.where(kind: kind): set block(width: 80%) it } } style-acc(doc) } /// Esta show rule es para utiliza en archivos que no sean `main.typ`, /// con la idea es permitir que estos archivos sean compilables por separado. /// Esto es útil para mantener el proyecto ordenado, como también si el documento /// es demasiado grande como para que la webapp compile en tiempo real. /// Esta show rules no tienen ningún efecto si el archivo a compilar es `main.typ`. /// /// - doc (content): Documento a aplicar la regla. /// -> content #let permite-compilar-secundarios(doc) = { show: permite-ref-rotas-fuera-de-main doc } /// Esta función permite obtener ayuda sobre cualquier función /// del template. Para saber qué funciones y variables define /// el template simplemente deja que el autocompletado te guíe, /// luego puedes llamar esta función para obtener más ayuda. /// /// - nombre (string): Puede ser el nombre de una función o /// variable, entonces la función entrega /// ayuda general sobre esta. Si se entrega /// algo de la forma `"help(nombre)"` entonces /// entrega ayuda específica sobre el argumento /// `nombre`. /// -> content #let help(nombre) = { import "../meta.typ": * return help-leaf("rules")(nombre) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/cjk-punctuation-adjustment_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(width: 15em) // In the following example, the space between 》! and ? should be squeezed. // because zh-CN follows GB style #set text(lang: "zh", region: "CN", font: "Noto Serif CJK SC") 原来,你也玩《原神》!? // However, in the following example, the space between 》! and ? should not be squeezed. // because zh-TW does not follow GB style #set text(lang: "zh", region: "TW", font: "Noto Serif CJK TC") 原來,你也玩《原神》! ?
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10FE0.typ
typst
Apache License 2.0
#let data = ( ("ELYMAIC LETTER ALEPH", "Lo", 0), ("ELYMAIC LETTER BETH", "Lo", 0), ("ELYMAIC LETTER GIMEL", "Lo", 0), ("ELYMAIC LETTER DALETH", "Lo", 0), ("ELYMAIC LETTER HE", "Lo", 0), ("ELYMAIC LETTER WAW", "Lo", 0), ("ELYMAIC LETTER ZAYIN", "Lo", 0), ("ELYMAIC LETTER HETH", "Lo", 0), ("ELYMAIC LETTER TETH", "Lo", 0), ("ELYMAIC LETTER YODH", "Lo", 0), ("ELYMAIC LETTER KAPH", "Lo", 0), ("ELYMAIC LETTER LAMEDH", "Lo", 0), ("ELYMAIC LETTER MEM", "Lo", 0), ("ELYMAIC LETTER NUN", "Lo", 0), ("ELYMAIC LETTER SAMEKH", "Lo", 0), ("ELYMAIC LETTER AYIN", "Lo", 0), ("ELYMAIC LETTER PE", "Lo", 0), ("ELYMAIC LETTER SADHE", "Lo", 0), ("ELYMAIC LETTER QOPH", "Lo", 0), ("ELYMAIC LETTER RESH", "Lo", 0), ("ELYMAIC LETTER SHIN", "Lo", 0), ("ELYMAIC LETTER TAW", "Lo", 0), ("ELYMAIC LIGATURE ZAYIN-YODH", "Lo", 0), )
https://github.com/max-niederman/MTH311
https://raw.githubusercontent.com/max-niederman/MTH311/main/hw/1.typ
typst
#import "../lib.typ": * #show: homework.with(title: "Math 311 Homework #1") = 1.3.1 (a) _Proposition:_ For all $n in NN$, $ 1^2 + 2^2 + ... + n^2 = (n(n+1)(2n+1))/6 "." $ _Proof:_ If $n = 1$, then $ 1^2 + 2^2 + ... + n^2 &= 1^2 \ &= 1 \ &= 6/6 \ &= (1(2)(3))/6 \ &= (n(n + 1)(2n + 1))/6 "." $ So the proposition is true for $n = 1$, our base case. Assume that the proposition is true for some $k in NN$. That is, $ 1^2 + 2^2 + ... + k^2 = (k(k+1)(2k+1))/6 "." $ Adding $(k+1)^2$ to both sides of the equation and simplifying algebraically, we get: $ & 1^2 + 2^2 + ... + k^2 + (k+1)^2 \ =& (k(k+1)(2k+1))/6 + (k+1)^2 \ =& (k(k+1)(2k+1) + 6(k+1)^2)/6 \ =& ((k+1)(k(2k+1) + 6(k+1)))/6 \ =& ((k+1)(2k^2 + k + 6k + 6))/6 \ =& ((k+1)(2k^2 + 7k + 6))/6 \ =& ((k+1)(k + 2)(2k + 3))/6 \ $ $ =& ((k+1)((k+1)+1)(2(k+1) + 1))/6 "." $ So the proposition is true for $n = k + 1$ also. Therefore, by the principle of induction, the proposition is true for all $n in NN$. #sym.qed = 1.3.2 (b) _Proposition:_ For all $n in NN$, $3$ divides $7^n - 1$. _Proof:_ The proposition applies to $n = 1$, our base case, because $ 7^1 - 1 = 6 = 2 dot 3 "." $ Now suppose that 3 divides $7^k - 1$ for some $k in NN$. Then there exists some $q in ZZ$ such that $ 7^k - 1 = 3q "." $ Multiplying both sides by $7$ and then adding $6$ gives $ 7(7^k - 1) &= 7(3q) \ 7^(k + 1) - 7 &= 3(7q) \ 7^(k + 1) - 1 &= 3(7q) + 6 \ &= 3 (7q + 2) "." \ $ Hence, $3$ divides $7^(k+1) - 1$. By the principle of induction, the proposition is true for all $n in NN$. #sym.qed = 1.3.3 (a--c) == (a) _Proposition:_ For all $n in NN$, $1 + 3n <= 4^n$. _Proof:_ If $n = 1$, then $1 + 3n = 4$, which is less than $4^n = 4$. Take $k in NN$ such that $1 + 3k <= 4^k$. Multiplying both sides by $4$ gives $ 4(1 + 3k) &<= 4^(k+1) \ 4 + 12k &<= 4^(k+1) \ $ We know $k$ is positive, so $ 4 + 3k <= 4 + 12k "." $ Therefore, by the transitive property of inequality, $ 4 + 3k &<= 4^(k+1) \ 1 + 3(k+1) &<= 4^(k+1) "." $ And by induction, we have $1 + 3n <= 4^n$ for all $n in NN$. #sym.qed == (b) _Proposition:_ For all $n in NN$ such that $n >= 3$, we have that $1 + 2n <= 2^n$. _Proof:_ If $n = 3$, then $1 + 2n = 7$, which is less than $2^n = 8$. Take $k in NN$ such that $k >= 3$ and $1 + 2k <= 2^k$. Multiplying both sides by $2$ gives $ 2(1 + 2k) &<= 2(2^(k)) \ 2 + 4k &<= 2^(k+1) "." $ We know $k >= 3$, so $ 6 &<= 2k \ 1 &<= 2k \ 3 &<= 2 + 2k \ 3 + 2k &<= 2 + 4k \ 1 + 2(k + 1) &<= 2 + 4k "." $ Therefore, by the transitive property of inequality, $ 1 + 2(k+1) <= 2^(k+1) "." $ And by induction, we have $1 + 2n <= 2^n$ for all $n in NN$ greater than or equal to $3$. #sym.qed == (c) _Proposition:_ For all $n in NN$, $n^2 <= 3^n$. _Proof:_ If $n = 1$, $n^2 = 1$ which is less than $3^n = 3$. Otherwise, assume that $k^2 <= 3^k$ for some $k in NN$ greater than or equal to $2$. Multiplying both sides by $3$ gives $ 3k^2 <= 3^(k+1) "." $ We know $k >= 2$, so $ 1 <= 2k &<= k^2 \ 4k &<= 2k^2 \ 2k + 1 &<= 2k^2 "." $ Adding $k^2$ to both sides gives $ k^2 + 2k + 1 &<= 3k^2 \ (k + 1)^2 &<= 3k^2 "." $ And therefore $(k+1)^2 <= 3^(k+1)$ by the transitive property of inequality. Hence, $n^2 <= 3^n$ for all $n in NN$ by the principle of induction. #sym.qed = 1.3.4 _Proposition:_ For any $n in NN$ and real number $a != 1$, $ sum_(k=0)^n a^k = (1 - a^(n + 1)) / (1 - a) "." $ _Proof:_ For $n = 1$, we have $ sum_(k=0)^1 a^k &= 1 + a \ &= ((1 + a)(1 - a)) / (1 - a) \ &= (1 - a^2) / (1 - a) "." $ So the proposition holds for $n = 1$. Now, assume that the proposition holds for some $m in NN$. Observe that $ sum_(k=0)^(m + 1) a^k &= 1 + sum_(k=1)^(m + 1) a^k \ &= 1 + a sum_(k=0)^m a^k \ &= 1 + a (1 - a^(m + 1)) / (1 - a) \ &= (1 - a + a - a^(m + 2)) / (1 - a) \ &= (1 - a^(m + 2)) / (1 - a) \ &= (1 - a^((m+1) + 1)) / (1 - a) "." $ By the principle of induction, the proposition holds for all $n in NN$. #sym.qed = 1.3.6 _Proposition:_ For any real $a >= -1$ and $n in NN$, $ (1+ a)^n >= 1 + n a "." $ _Proof:_ For $n = 1$, we have $(1 + a)^1 = 1 + a$ which is equal to $1 + 1 a = 1 + a$. Therefore, the proposition holds for $n = 1$. Now assume that it holds for some $k in NN$. That is, $ (1+a)^k >= 1 + k a "." $ Because $a >= -1$, we can multiplying both sides by $1 + a$ to get $ (1+a)^(k+1) >= (1 + a)(1 + k a) \ $ The square of any real number is nonnnegative, so $0 <= a^2$. Because $k$ is a natural number, it is positive and we can multiply both sides to get $ 0 <= k a^2 "." $ Then, adding $1 + k a + a$ and factoring yields $ 1 + k a + a &<= 1 + k a + a + k a^2 \ 1 + (k + 1) a &<= (1 + a)(1 + k a) "." $ So, by transitivity, $ (1+a)^(k+1) >= 1 + (k + 1) a "." $ Therefore, the proposition holds for all $n in NN$ by the principle of induction. #sym.qed
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10D00.typ
typst
Apache License 2.0
#let data = ( ("HANIFI ROHINGYA LETTER A", "Lo", 0), ("HANIFI ROHINGYA LETTER BA", "Lo", 0), ("HANIFI ROHINGYA LETTER PA", "Lo", 0), ("HANIFI ROHINGYA LETTER TA", "Lo", 0), ("HANIFI ROHINGYA LETTER TTA", "Lo", 0), ("HANIFI ROHINGYA LETTER JA", "Lo", 0), ("HANIFI ROHINGYA LETTER CA", "Lo", 0), ("HANIFI ROHINGYA LETTER HA", "Lo", 0), ("HANIFI ROHINGYA LETTER KHA", "Lo", 0), ("HANIFI ROHINGYA LETTER FA", "Lo", 0), ("HANIFI ROHINGYA LETTER DA", "Lo", 0), ("HANIFI ROHINGYA LETTER DDA", "Lo", 0), ("HANIFI ROHINGYA LETTER RA", "Lo", 0), ("HANIFI ROHINGYA LETTER RRA", "Lo", 0), ("HANIFI ROHINGYA LETTER ZA", "Lo", 0), ("HANIFI ROHINGYA LETTER SA", "Lo", 0), ("HANIFI ROHINGYA LETTER SHA", "Lo", 0), ("HANIFI ROHINGYA LETTER KA", "Lo", 0), ("HANIFI ROHINGYA LETTER GA", "Lo", 0), ("HANIFI ROHINGYA LETTER LA", "Lo", 0), ("HANIFI ROHINGYA LETTER MA", "Lo", 0), ("HANIFI ROHINGYA LETTER NA", "Lo", 0), ("HANIFI ROHINGYA LETTER WA", "Lo", 0), ("HANIFI ROHINGYA LETTER KINNA WA", "Lo", 0), ("HANIFI ROHINGYA LETTER YA", "Lo", 0), ("HANIFI ROHINGYA LETTER KINNA YA", "Lo", 0), ("HANIFI ROHINGYA LETTER NGA", "Lo", 0), ("HANIFI ROHINGYA LETTER NYA", "Lo", 0), ("HANIFI ROHINGYA LETTER VA", "Lo", 0), ("HANIFI ROHINGYA VOWEL A", "Lo", 0), ("HANIFI ROHINGYA VOWEL I", "Lo", 0), ("HANIFI ROHINGYA VOWEL U", "Lo", 0), ("HANIFI ROHINGYA VOWEL E", "Lo", 0), ("HANIFI ROHINGYA VOWEL O", "Lo", 0), ("HANIFI ROHINGYA MARK SAKIN", "Lo", 0), ("HANIFI ROHINGYA MARK NA KHONNA", "Lo", 0), ("HANIFI ROHINGYA SIGN HARBAHAY", "Mn", 230), ("HANIFI ROHINGYA SIGN TAHALA", "Mn", 230), ("HANIFI ROHINGYA SIGN TANA", "Mn", 230), ("HANIFI ROHINGYA SIGN TASSI", "Mn", 230), (), (), (), (), (), (), (), (), ("HANIFI ROHINGYA DIGIT ZERO", "Nd", 0), ("HANIFI ROHINGYA DIGIT ONE", "Nd", 0), ("HANIFI ROHINGYA DIGIT TWO", "Nd", 0), ("HANIFI ROHINGYA DIGIT THREE", "Nd", 0), ("HANIFI ROHINGYA DIGIT FOUR", "Nd", 0), ("HANIFI ROHINGYA DIGIT FIVE", "Nd", 0), ("HANIFI ROHINGYA DIGIT SIX", "Nd", 0), ("HANIFI ROHINGYA DIGIT SEVEN", "Nd", 0), ("HANIFI ROHINGYA DIGIT EIGHT", "Nd", 0), ("HANIFI ROHINGYA DIGIT NINE", "Nd", 0), )
https://github.com/bsp0109/ieee-typst-template
https://raw.githubusercontent.com/bsp0109/ieee-typst-template/main/README.md
markdown
# IEEE [Typst](https://typst.app) template This template is my edition of the template provided by [Typst](https://typst.app) to match my requirements, the only edit to the actual [template](template.typ) is just the font and the size of the title's font. The rest is just boilerplate code that I'll write anyway. ## Usage: Refer to [Typst's Github](https://github.com/typst/typst)
https://github.com/coco33920/agh-public
https://raw.githubusercontent.com/coco33920/agh-public/gh-pages/pdfs/agh.typ
typst
#import "@preview/glossarium:0.2.5": make-glossary, print-glossary, gls, glspl #set page(numbering: "1/1") #v(1fr) #set text(size:24pt) #set align(center) *A Galactic HRT*\ by <NAME>,\ _Last updated: December 5th, 2023_\ #set text(size:12pt) #set align(left) #v(1fr) #pagebreak(weak: true) #set align(center) #quote( block: true, )[ #block[ To everyone who feels under-represented in Science Fiction\ To my professors who supported and helped me even in the darkest hours\ To my friends without whom I’d not be here\ To Ninon for their love and support\ To Claire who was here for me from the very beginning ] ] #quote( block: true, )[ #block[ #block[ And finally, to my best friend, Naïs, whose complete list of what she did for me deserves its own book. ] ] ] #show link: set text(rgb("#55cdfc").darken(10%)) #set align(left) #let middle = block(width: 100%)[ #v(1em) #set align(center) #set text(weight: "bold") $ast.basic$~$ast.basic$~$ast.basic$ #v(1em) ] #let c = counter("chapter"); #let o = false; #show heading.where(level: 1): it => { c.step() pagebreak(weak: true) v(1em) set align(center) set text(size:16pt,weight: "bold") [Chapter #c.display("I.")\ #it.body] v(2em) } #set heading(numbering: "I.") #show: make-glossary #set par(justify: true) #set text(weight: "bold",size:16pt) Edito <edito>\ #set text(weight: "regular",size: 12pt) Welcome to the PDF book of A Galactic HRT, this book was written using the ScribbleHub version of the story, on LaTeX’s book environment. Not so much artistic choices have been made, the chapter numbering is different from the ScribbleHub numbering because here the multi-parts chapters are joined into only one chapter. Thanks for reading this story, this book is published under the CC-BY-NC-SA 3.0 licence, available here #link("https://creativecommons.org/licenses/by-nc-sa/3.0/") you’re basically allowed to: share this story, remix/alter this story, with the attributions conditions (i.e. you must write my name (<NAME>) and a link to this story (the SH will do fine)), non-commercial (you cannot sell this) and share-alike (you must share your altered story with the same licence.) If you have any suggestions you can create an issue #link("https://github.com/coco33920/agh-public")[here] or contact me by #link("mailto:<EMAIL>")[mail] This story includes homosexual/lesbian couples, agender people, trans people, non-binary people. The romance is in sub-plot and casually mentionned, but if you don’t like that, you can skip this book and go read the last tweet for JKR.The specific list of Trigger warnings for each chapters are indicated before it and may be for transphobia/parental abuse/homophobia, however the story is meant to be focused on mystery solving and Science Fiction. Translations are welcomed if you want to translate this book just fork the GitHub repository or clone it and create your own. If you did so contact me I will add it here and on the README. Some references have been found online here is a list of such reference - <NAME>. (2009). Gamma-ray bursts as a threat to life on Earth. #emph[International Journal of Astrobiology], 8\(3), 183-186. doi:10.1017/S1473550409004509 #outline(indent: auto) = Prologue <prologue> _*Written in @us*_\ …..Neuronal Connection Established\ …..Identity checked …..Name: <NAME>\ …..Information: Human, female, ambassador of the Union to Earth\ ……Language: es\ …..Translation: OK\ #emph[#strong[written in @es]] Extracts of the logs of the Union Science Spaceship AEXIII-1, #emph[Date: 12th of December 1902, 1002h Human Standard Time (HST)] Captain is talking Our spaceship just dropped out of ftl in the outer fairing of a stellar system, the star is a class G yellow star, with a mass of approximately 0.8 Union Standard Stellar Mass (USSM), radioactivity is normal, and particle emission seems to indicate that the star is approximately midlife. We are currently in orbit of the 8th planet, a beautiful but useless blue gas giant, our engineer is looking the drive to see when we can resume our mission, we are more than 80 light years away from home, and we still have a few anomalies to investigate. While we’re blocked into this stellar system the sensors are at full power to see if any biological activity is present. #emph[Date: 12th of December 1902, 1130h HST] An alarm just went off, the sensors picked up life signal, and weak electromagnetic activity on the third planet of this system. The system have 4 inner planets before what seems a belt of asteroid and the outer planets, only the 3rd have biological signals. A prob has been launched and put into orbit safely in the second Lagrange point of the planet-star system, it has a faster-than-light communication arrays and is far enough to be non-detectable from the surface of the planet. It is designed to pick up information (and any EM signals they might send) gather data, and send it right back into the main world to be processed and analyzed, this planet and specie may be interesting to study. #emph[Date: 14th of December 1902, 0103h HST] The engineer just called my station, they is positive the vessel is capable to safely perform an FTL jump right back to mainworld, we have to inform the chain of command of our discovery, and we have to set up the legal shenanigans to study the society of the 3rd planet, the coordinates of this system were safely put into the Union Shared Spacemap; finally we installed an FTL jump-point approximately 0.7 light years away from the star, in a circular orbit. The central computer just approved the jump and I instantly felt the mechanical switch from our sublight fusion drive to the powerful space-bending FTL drive, after the final checklist was checked, the countdown was called, at T0 I feel the intense acceleration of the drive, a few broken glass later we finally were at our FTL1 speed to join mainworld in a bit over 3 months. = It can’t be that fast can it? <it-cant-be-that-fast-can-it> #emph[Ring ring ring] I jolted awake at the sound of my alarm going off, today was Sunday, but I have a meeting with Sylvia to draw, they said they had a new idea for a powerful new propulsion system to incorporate into our vessel, however I had to review it to see if the idea seems plausible and how to draw it. My house automation system sensed the fact I was awake and started the morning routine, I watched by the window as the curtains opened and saw the beautiful Sunday sun creeping by it, the sky was blue and unblemished, only disturbed by the slight shadow of a delivery drone passing by or the few air cabs circulating in center np. - "Good morning Ariana" said my house AI voice "It’s 1200h, 12th of October 2040, we have an outside temperature of 19 °C in @np, the university sent you 3 email during the night nothing too important just a remainder your assignment is due tomorrow before 2pm, your meeting with Sylvia is scheduled for 1pm" the AI dutifully said The temperature is a bit chilly but nothing surprising given the location of New Paris, a big city in the intersection of the once mighty European powers (France, Germany, Switzerland, Belgium, Italy) now unified in the European State "Europe", following the events of the @mic in 2023, each continent started to unify themselves for the next decade, in 2028 with the @ut the once European Union and the other nations of the European continent unified and formed a new nation called "Europe". Following the European example all other continents managed to mostly unionized. Then the United Nations dissolved themselves and formed a new Federation Nation, the @federation, a few countries in the world (such as North Korea or the United Kingdom) decided to remain sovereign-nations but now almost a decade after the @dffc (also called federationt in respect to the European treaty) this independence was mostly honorific and expert says the UK might just join Europe and the Federation in a few years to decade. The capital was named after the most populated city of the ex-EU, Paris, capital of the province of France, but that is the end of the similarities, a new city was issued out of nowhere, and with the collaboration of all the continent high speed train became common in all of @europe, most of the once capitals of the EU are connected directly to New Paris. You can now go from New Paris to practically anywhere in Europe in a few hours. This fact alone explains how we went from new city to a 20 million enormous federation-wide hub in a few years. - "Thanks please send a message to Sylvia to notify them I’m awake, I’m going to take a shower" As I undressed to shower I took my HRT, nowadays, a simple injection daily was enough, I mentally passed over all things I needed to do before tomorrow and decided it was nothing important as the warm water dropped onto my breast and I marveled to the sensation of warm water on soft skin, I started HRT a couple month ago after I got kicked out of my house by my parents and I really was surprised of the speed it was going. I dressed simply, I am tall, maybe 175 cm, but not skinny I had a bit of hips showing my breast are good enough to fill a simple B cup bra and my long blonde hair fell just short of my waist, I wear a simple blue dress with leggings to keep me warm, shoes with a slight heel to show my legs and I went to put make-up on. Today was easy, no public appearance at all, just me and Sylvia, I decided to be conservative with make-up, a bit of eye shadow and eyeliner to show off my big green eyes and a bit of blush for my cheeks. As I passed the door of the dorms to walk over to Sylvia’s home I thought of how everything changed in just a couple of months, a year ago I still lived at my parent’s and haven’t transitioned yet, Sylvia is the one that managed to convince me to come out at school and to open to the world, I still think they feel somewhat responsible for the fact I got kicked out, but that’s foolish, it’s my parent’s fault, whatever I started to receive basic income from the Europe State as soon as I declared my situation and my university provided me with a dorm room not too far away from where Sylvia is living. #emph[Driiiiiiiing] I mentally laughed at the old school ringtone of Sylvia’s home, a quirk their mom loved a thing imported from last century France she once mentioned, her husband hates that thing, but as he was living in American Union to work on the @ijpl (the successor of the JPL) she managed to stick it once again on their door, I managed to keep my composure just as Sarah, Sylvia’s mom, opened the door - "Ariana! What a pleasure to see you again! And you look beautiful, Sylvia should look at you sometimes I’m sure she’s missing something" she added a huge knowing grin on her face - "Thanks you Sarah! I’m here to draw with them" - "They’re in their room I will make some tea, the one you like I’ll bring you one cup" I almost jumped in the stairs and lightly announced myself at their door, a second later a sudden flash of flesh appeared and collapsed on me as I tried but failed to not fall on my butt as the trickster known as Sylvia smiled toothily at me with their big silly trademark smile - "Ariana! You came! I’m soooooo happy to see you, and #emph[OH MY GOD YOUREBEAUTIFUL]" they squealed at the end of the sentence I continue to just hug them without doing or saying anything, a few minutes later I broke out of the hug and said - "Yeah of course I came dummy you were so excited about your new idea of propulsion that Of course I became excited too! I brought my drawing case with me, we can work a bit today If you’re feeling up to it" Sylvia and I were designing our own little (okay it’s a big one) spaceship, but we want it to be as realistic as possible, I was designing and drawing it and Sylvia, the big SF nerd they was, was designing the propulsion system, heart of the ship, we were dreaming of @ftl rated ship, even if we knew that it was impossible and against the laws of physics it was really fun to imagine, Sylvia’s enthusiasm about it was not a surprise, their father is a propulsion researcher at IJPL and was the head designer of the fsp, he is responsible for the engine that powered Saturn X, the rocket that re-launched the moon program. Nowadays, he is designing a rocket powerful enough to colonize the moon and organize large and regular missions between Earth and the Moon He once was the head scientist of a little private space company, before the collapse of the private space sector when the federation formed and the fact that private space sector was more or less public space sector anyway, just less effective because it had investors to satisfy. However, he was immediately selected to be incorporated into the new IJPL and quickly rose through the ranks. - "Hum… nah I can’t work now I have a theoretical computer science assignment due tomorrow, and you know how I love computers but hate theoretical computers so, yeah" they said, bashfully I giggled and then just stared at their bedroom, I spent so much time here these last few years, I met them in middle school around 6 years ago, Neither them nor I were publicly out at the time, so we just enjoyed our mostly cishet lives together, without any hint of romance or other interest, we were both really into programming and created a bunch of silly apps and game for our computers and gaming devices. As time went we were still really close and were the respective first people we came out to, they started first by coming out bisexual then pansexual, I then made mine and a couple of weeks later they came out as non-binary. That was in junior year of High School, I didn’t come out to my parents until a few months ago after I turned 19 and they… yeah they didn’t take it quite right, so I lived here at Sylvia’s a couple of days before the state provided me with money and a room. Their parents offered me to stay and live with them, but I was too afraid to be a bother so for a few months now I live alone, just off campus. Sylvia was beautiful, they is 170 cm tall, with bright ear-length cotton-candy pink hair (they love to change the color of their hair) barely kept, with matching pink colored eyes, I think they had that done a few months ago. They is really androgynous and loved to play with that, they alternate between a really feminine wardrobe and a masculine one, seemingly randomly, and I have to admit that it is pretty cute. Sylvia interrupted my thoughtful glance, - "Hum, Aria? You seem distracted and, how does HRT work that fast with you? You started a couple of months ago, and you’re already more feminine that I ever was and with that cute face or yours and your height you’re more and more irresistible each day" they quickly realized what they was saying and put their hand in front of their mouth. "I mean in a Platonic way, you’re beautiful, like too beautiful and hum you know me, it’s… hum you know hard…" they bashfully tried to cover up. - "Don’t worry I get it, and you’re really cute like that" I grinned watching their blush deepening even further into shades of pink I didn’t even know existed "And yeah I get what you’re saying? But I think it’s okay HRT has come a long way since the start of the 21st century, so maybe it is normal? But yeah it’s definitely worth to think about" I was really really really worried right now, they noticed it was a little fast, I noticed it too and maybe everyone will notice? I started to panic a bit, it probably was normal, but anxiety kicked in fast, and I didn’t have my med right now, I tried to breathe, however it was harder and harder to think every second, a mental fog fell, and I quickly lost all semblance of grip I had on my state Sylvia, fast to recognize the effects of an anxiety attack in their best friend, embraced tightly Ariana - "Breath… Hold in…. Breath… Hold in….. Breath, you’re gonna be okay Aria, it’s nothing you are alright, everything’s gonna be okay, you are safe, you are gonna be safe, I’ll protect you, I’ll never let anything bad happen to you again okay?" they pulled their hairbrush from the desk and started to brush Ariana’s hair to calm her, it was her little weak spot A few minutes later Ariana was calm again and was breathing slowly, she tightened her embraced with Sylvia - "Thanks Syl’ it was close I don’t think it’s anything you’re right, and I’m already on HRT for like 6 months? So it’s probably to be expected" she, however, really hoped it would slow down, her brother was in school and while he was okay he would be freaking out when he’ll see her, she added mentally. She stared at Sylvia, a slight weak grin on her face, and once again analyzed their beauty, she was just shy of taking her pen to start drawing that, suddenly, she felt sick, Sylvia was not looking good too, and, a few seconds later, everything went black. = Oh... Crap. <oh-crap> #emph[Units, times, and language has been translated from Union Standard to Earth Standard] #emph[#strong[Aarin POV, A few months before the first chapter, TW: Abusive parents, traumas]] - "This mission is becoming very boring", Aarin said to himself, Aarin was on his second year of the human observation mission, in the far Sol system, he was a xenobiologist, xenosociologist and more importantly a xenolinguist, Aarin was the first of @union Science Program to fully understand the Earth Standard language and learn it enough to be fluent, so naturally he was chosen to be on the second maned observation mission after the famous discovery made a few union years ago, no more than a century ago he corrected himself, he must think in humans units. Unfortunately the mission was really boring, the automated probes stationed in the system were excellent at their job, so he didn’t have a lot to do. The next refueling ship was excepted next month, but he really was lonely. On a whim he decided to check on his latest… discovery. See, his society does not have the concept of… gender it was a completely alien concept to them, so as a xenosociologist he was thrilled to study this specie, he knew humans were not ready for first contact yet, they only were an archaic society, a class 1 on the Union Scale, they only managed to exploit the resources of their planet, and they really were doing a bad job at it, probes and scopes calculated that the atmospheric composition was becoming toxic to the Earthen lives. However, they outran every calculation of the union scientists when they unionized their planet in only two decades. And they were really coming from far away… In and all their society was fascinating to study. He secretly hoped they’ll correct their trajectory and one day become ready to integrate the local inter-stellar community, the rhythm of their discovery and the speed at which they develop new technologies were incredible. Aarin snapped out of his internal monologue when the screen of the Human Subject 001 was displayed on the holographic terminal of the piloting area. After a few minutes of data-gathering the hologram was complete, her parameters were in the human excepted values, but something was off with her. She seemed to be depressed, yes that was the word. Her mental parameters were completely off the charts, even when accounting for errors. He thought that was finally the time to come down and pay a little visit to earth surface. Activating the human @disguise, an average-looking, young, thin and 180 cm tall man with short black hair, sharp facial structures, brown eyes and a little of muscle definition in his abs - the disguise was designed to be healthy, but he managed to tweak it a little to his taste - he joined the shuttle bay and activated the shuttle AI. - "Hello Professor" said the AI, "Activating piloting mode" The smooth surface of the panel changed, morphed, transformed in a sort of liquid and settled itself in a series of bump, spikes, edges and flat surfaces, that was the standard Union piloting area, designed for the core world physiology, but really not compatible with his current human one, so he quickly switched it to the human-adapted tactile piloting gear he designed and strapped himself in the front seat. - "Hello, activate the cloaking device, the thermal shields, the phase device and the mental disturbance unit please" he commanded to the shuttle vocal commands, which acknowledged with a sharp beep. He adjusted himself in the seat, positioned himself in a good, comfortable piloting position and with a press of a button activated the powerful yet stealth nuclear fusion reactor powering the shuttle. A few hours later he entered low earth orbit and planned an automatic landing in the outskirts of the "New Paris" city where his target lived, he mentally went over the goals, he needed to approach the subject and… Listen to her After landing and setting up the cloaking mechanism to assure nobody will spot the strange object, Aarin jumped out of the cockpit and prepared to peacefully explore the human megalopolis, he chose this city because of its strangeness, it was located outside the old centers, at least the centers the probes discovered and flagged as such, and from the data gathered by the continuous surveillance it was new, a very young city, so his scientific curiosity was picked, and the city was selected to become the first direct observation site of humans by union scientists! He marveled at the diversity of the architectures from the surrounding buildings, there was a lot of different styles, yet it was really working well together. Then he came into viewing distance of his target, the human subject, he knew how to do that, he just had to know why she felt so sad all the time. At the same time his target walked towards her home, he quickly activated the disguise again and transformed himself into a cat, he picked this earth life form because he learned that it was considered cute by humans and noticed they always tended to react positively even if they didn’t know the said cat. He ran over and managed to sneak into the house just as his target closed the door. Crap, he scolded himself, he didn’t plan exactly how to know her, he couldn’t just stick a microphone on her as a cat… As he was thinking, his target shuffled herself, she seemed very upset… no not upset, nervous. She was really strange, and really sad, finally she abruptly got up and nearly ran towards her parents, Aarin decided to closely listen to her and to record her and transmit it to the ship. - "Mom, dad" she said, softly, almost like she didn’t want her parents to hear her. - “yes Arthur? Said her mother, his father seemed not to pick up, so she said "hey, listen to Arthur he has something to tell us" ° "he?" thought Aarin, "but she’s a girl isn’t it obvious?" he was really puzzled and was getting more and more frustrated by the minute, he thought he finally had figured out humanity and their weird gendered society and here he studied this girl (boy?) for months now, and he never saw that she...he… they was not a girl? He was positive the computer identified her as female, he was absolutely sure he configured it to detect gender, so that didn’t make any sense. - "I want you both to stay quiet until I have finished" her parents then nodded "..it’s something I want to tell you for a few years now, but I never have had the willpower to do so, and I’d always chicken out before I had the chance to tell you, however I can’t hold it anymore I need to change things" her mom tried to said something but Arthur, her birth name Aarin deduced, glared at her, and she kept quiet, "Syl’ finally convinced me to come out" at that word her father took a grim face but kept listening nonetheless. "I feel like I was meant to be a girl, deep down I am a girl, I am transgender, I am a girl." she said on the verge of crying, but neither of her parents tried to comfort her. Aarin was thinking fast, he knew enough of humans to recognize this as a bad situation, but he remained confused, what "transgender" meant, of course she was a girl if that was obvious even for him a being from another world which didn’t even have the concept of gender, it should be for her parents who know her very well, all of this situation made no sense whatso- Before Aarin could finish his thought, her father stood up, approached her slowly, and slapped her hard right in her left cheek, leaving a red stain after him as a remainder of his act, Arthur seemed shocked and couldn’t even talk, he recognized the symptoms of a shutdown as he studied the autism spectrum and other neurodivergences in humans before departing @uc. - "No, you are not a woman Arthur, you’re my son, and you will remain my son, no amount of… cosmetic nonsense can change that" yelled his father right in-front of Arthur - "Arthur, sweetheart, you can’t disfigure yourself with those procedures or these hormones you know it won’t work, you know you’ll never be a real girl, so you should stop thinking about that, maybe you could cut your hair? Or change your hobbies ? I’m sure it would help to pass that phase, it will be alright and forgotten in no time, it’s perfectly fine at your age to be confused, it will fade with time when you’ll find a lovely wife and start a family" her mother said, with an annoyingly huge grin on her face Aarin remained still, staring at the girl, her parents were completely destroying her why can’t they see that? They are her parents they should recognize their child’s suffering ! Aarin was completely flabbergasted at the interaction it was so alien, so unfamiliar, that he didn’t know how to react, he couldn’t do anything here without his stuff and he couldn’t expose the mission but it was so hard to see the girl completely shot down without being able to react or answer. Suddenly, Arthur snapped out of her state, met her parents with her eyes and with a calm and determined tone said - "Dad, mom, I will repeat one more time, I am a girl, I will transition with or without your help or permission, I will be happy, and you can’t do anything about it, now you can choose to keep me in your lives or not, mine will continue just fine, and I will do it I swear the goddess of this world. And I’ll say it only once. My. Name. Is. Ariana" carefully articulating each word at the end. Ariana, Aarin thought, it was pleasant to know her preferred name no more Human whatever 001 thingy. It was then that her father decided to slap her, hard and again Aarin remained still, completely dumbfounded by what just unfolded. - "Son, ARTHUR" his father spat, "you are a member of this family, of my family, and you will abide by our rules, or you’ll not be allowed to be part of this family. So I’ll ask you one time son, Arthur, will you give up these lies and fallacies and come back on the right track?" His father said in a deep creepy voice. - "No. I won’t. Never." answered Ariana. - "So be it, you’re not a member of this family anymore, you have an hour to quit this house before we start pushing you out ourselves, you are by then nothing, you don’t have a family to rely on, you are by yourself, and we don’t know you anymore, you’ll now be wandering outside like a nobody, like nothing, like your kind is. Go thing, you have 57 more minutes to take your stuff". Her father, said calmly. Ariana tried not to panic as she was staring at her mom who just lowered her eyes in a non-vocal answer to the non-vocal question. She quickly moved in her bedroom to pack her stuff. #middle She came back less than 15 minutes later, she glanced a last time at her parents, and headed to the door. - "And take that damn cat with you! I don’t know why it’s here!" her father yelled. A long, silent, walk later she finally arrived at the home of her best friend Aarin identified, their name was Sylvia, and they was fascinating too, they was non-binary which is another thing in their gender game, but his mood wasn’t at research, He was really scared for the girl, she just was kicked out of her home? Is that a thing humans do? That seems really old-fashioned and just… weird, that grossed him out. The door swung open, a woman was behind it - "Hey Art…" then her eyes widened considerably when she saw the state of the poor girl "Oh my god come inside I will prepare you a hot tea, what happened sweetheart are you okay?" The sound alerted Sylvia, they was running down the stairs to take Ariana in a big tight hug - "Oh my god Ar are you okay? What happened" Sylvia shouted, completely panicked, their mom came back from the kitchen and gave Ariana a steaming hot mug of mint tea, her favourite and asked, - "How are you hun?" Aarin saw the thoughtful expression of Ariana, he was sure she was thinking a hundred things at the moment and didn’t want to repeat the experiment, however something must have change Ariana’s opinion as she began to speak softly, barely a whisper, - "I… came out to my parents, I came out as a transgender girl, they… especially dad, really did not take it well, basically ruled me out of the family and gave me an hour to be out of the house, I’m really alone no am I not?" she chuckled at that, a sad chuckle, but Sylvia took her into their arm and gently said - "hey, no you’re not alone, you’ll never be alone Ariana I am here, I’ll always be there for you." - "My child is right Ariana, you’re more than welcomed here, you can stay, you know we have a spare bedroom for you, so feel free to live here." Sylvia’s mom said, smiling and gently stroking Ariana’s hair. Ariana started to cry and Aarin mentally relaxed, the situation was alright, Ariana was not in immediate danger, thanks to her best friend’s mom. But he couldn’t even think of not helping her, she was kicked out of her home! That was a little breach of protocol, but he was positive he was gonna help her. #middle Aarin sighed as he remembered how it started, a few months ago with Ariana’s coming out, in the following months he learned as much as he could about transgender people on the humans planet-wide information sharing system they called "internet". That was fascinating, and frightening, he never could have guessed the fact their society was so gendered could hurt so much a portion of the population. He then made… a mistake, He realized he could accelerate how their transition methods worked and made them more complete, he spent years studying humans, their physiology and psychology, so he knew their biological default form was flawed they couldn’t change it like a few species in the Union, furthermore they were really far from inventing shape-shifting technologies, so they never could obtain a comfortable body, even if he noted that the majority of the population were… okay with their body. However, the real problem was he decided to give Ariana the powered up HRT he made and swapped out her meds last month. But he must have made an error in the calculations because the effects were far faster than he originally planed, and Ariana noticed. Then Sylvia noticed. This was terrible because if others noticed this, it might bring planet-wide panic fast and humans were not ready for first contact yet. He finally decided to transport Ariana and Sylvia from their room directly to the mess to explain to them the conundrum, it was the best move, and maybe that will speed up his research on humans. That would not be the first times observer made local allies by accident. Or in his case almost by accident. He carefully entered the coordinates of Sylvia’s home, remembered to activate his human disguise, and powered the standard short range matter transporter up, it could be used on biological material, but it was not portable so if he beamed himself down on Earth he couldn’t join his ship again so, yeah, he used shuttles, safer. He initialized the transport sequence and prepared himself mentally for the hard talk that was coming. #middle #emph[#strong[Ariana’s POV]] When light came back I was sitting in a bench with a comfortable cushion on it and I saw Sylvia stirring beside me, so I started to explore the surrounding, and we were not in Sylvia’s home anymore. I started to hyperventilate when I felt Sylvia’s hug and relief washing over me, at least they was there for me, I wasn’t alone. We saw a human figure a few meters away from us, and before we could react he spoke in a foreign accent I could not place. - "So. I think I owe you an explanation" said the voice. = We Need To Talk <we-need-to-talk> #emph[#strong[3rd person POV.]] - "And that leads us to now…" Aarin said, finishing his hour-long explanation of who he is. - "So… you’re telling us that you’re a benevolent alien coming from a far away union of species and planets to study our planet and specie to monitor when we will be ready to initiate first contact? But I do not understand, how? Who are you? Why are we here? How are we here ? How are you talking in our language? And for god’s sake, why are you so…. Human?" Ariana yelled more panicked rather than angry, as Sylvia covered their ear to protect themselves from the sheer volume of Ariana’s voice. - "Try to calm yourself I will answer to all of your questions, but first I would not say I’m a benevolent alien, I’m only here to observe you and your specie. As I said my name is Aarin, that is in your language, you could not pronounce or even comprehend my name spoken in my language, You’re here because I made a mistake, I took pity of you when I witnessed your parents evicting you from your house and decided to boost a bit your HRT, unknowingly I boosted it too much, finally I had to introduce myself to you to avoid panic or public disclosure of the effect." Aarin said, calmly, almost coldly. - "So it was you! I was sure my HRT worked faster than expected, well I would not have imagined an alien boost it but thanks by the way, and you witnessed my parents kicking me out? How? I don’t remember seeing you." Ariana cut Aarin before he could answer the next question. - "I thought you wanted the answer to your question young lady stop cutting me when I’m talking!" Aarin said with a little smug smile on his face, "To how I witnessed it, I will say one thing, you remember the cat?" Ariana nodded "It was me, I have a shape-shifting device, it’s also the answer to your last question, our specie have had the technology to shape-shift for centuries now, so we do not even have a "normal" shape it’s very diverse you should see our mainworld with its millions of different shaped and coloured people." "As to how you’re here I transported you here with a short-range biological transporter that’s as simple as that, your physiology is new for it so forgive me for the rude journey here. I’m talking in your language because I spent the last decades learning and studying your society including learning Earth Standard, we also have automatic translators tuned to you, but I do prefer talking with my own mouth." Ariana took a few seconds digesting what.. Aarin just said, there were another worlds, shape-shifting? Transporters? All of that was really a lot to take in, but she has only one important question. - "If you’re not benevolent and only here to observe, why were you in my house to begin with? Why did you decide to help me? That does not make sense at all!" - "My original mission was just to monitor your civilization, but see I’m a xenosociologist, I thrive on learning how others society works, and yours have a truly unique concept, the concept of gender I had to learn more about it! When I saw that your specie did not have any shape-shifting technologies or abilities I began to understand it more, I theorized gender appeared as a consequence of the sexual dimorphism development that seemed to appear approximately 12 thousand years into your past. I learned a lot with your internet, it’s a wonderful piece of technology we definitely have to implement something similar into the Union." “A few weeks into my mission I decided to push to the next phase and pick a human subject to study. I took your city because of its size, the number of inhabitant, and the diversity of the population, I made the computer chose a random young human, and it was you! I was really lucky thinking back. I was in your house because even if my computer calculated that your physical health was in the normal parameters for humans your mental parameters were completely off and my science curiosity was picked, I then tracked you, transformed into a cat and sneak into your house to stick a microphone on you. But then you came out, and the rest is history, I learned about the concept of transgender people, of transition and as I said… I witnessed a truly shocking event I could not think objectively as a scientist studying his subject, I wanted to help you, and here we are with a big problem on our heads.” Ariana was thoughtful, yes he sneaked on her, studied her for months, but he is a scientist after all, and more than that an alien scientist that was here just to study our society and an exterior rather objective eye is more than welcomed given the current state of human society. Suddenly Sylvia stood up, approached Aarin looked up and said - "We’re in space aren’t we?, I can sense the low rumble of a deuterium fusion reactor, is it powering this vessel?" Aarin was surprised, Ariana however was shocked they were, in a spaceship, in space, the cold lifeless airless void capable of killing you in mere seconds space, that one? She thought. She collapsed in the mess bench and started to panic, a few seconds later Sylvia was embracing their best friend and was whispering calm and gentle words to try to calm her. A minute later as Ariana was resting on the bench Sylvia turned themselves to face Aarin, he then calmly answered - “Yes Sylvia, we’re in space, in my vessel, it’s a 20 years old long-range science exploration and planetary observation ship. Its standard equipment is indeed a large nuclear fusion reactor and a few tons of anti-matter to power fast jump. In its cruise sublight speed we can make the journey from your sun to Pluto in a week, its FTL cruise speed it’s capable of joining Union Central 80 light years from here in approximately 3 months, 2 months and a half in an emergency. Finally, in case of an emergency it can consume anti-matter and deuterium to power an instantaneous 0.1 light year jump, it however requires stopping to cool off the engine, and anti-matter is a rare substance difficult to manufacture, so it’s only in case of an emergency. Sylvia and Ariana brushed off the mention of their names and locked themselves into a shared glare with big dilated eyes and simultaneously shot out: #emph[- "FTL is real!?"] Aarin pleased to see the discussion was going well so far relaxed a little, he was really tense, he never did that before and for good reasons! He should not do that. But he had made a mistake, he mentally added to talk to Ariana about the remaining of her transition and how she wanted her future body to be, at least he could give her, her "true form". He tried not to think about how he was going to explain that to his superior back home and to focus on the current task, that is talk to the two young humans in his vessel and try to at least have them trust him, if he could manage to become friend with them, it would be good, for his research of course. After that rather… difficult discussion, at least on their part, they have to completely reconsider their sense of world and their place in the universe, he was sure they were gonna do it, but it understandably would take some time, he left the two friend alone in the spacious sofas of the lounge area and headed to the bridge of his ship to launch some probe, monitor data, boring scientist stuff but much needed after the shot of adrenaline he just received. - "Please launch 2 small FTL probes outside the heliosphere one starboard side and one on the port side please. Equip them with long range wide sensors and forward the data to this computer" he commanded to the voice system which answered by the familiar beep. The probes launched then he could finally relax, the last few days have been stressful but nothing unusual happened, he now had 2 friends he could use on the ground to explore for himself, that would be much easier to take a shuttle and waste a few hours. He took his student last tests he received via the long range communication arrays placed not far from Pluto, the first planet of this system discovered. Surprisingly enough he also learned on the human internet that Pluto has been withdrawn from the planets and lost its planet status due to the official definition of planet. Well it makes sense to him, so he didn’t think about it too much. #middle #emph[#strong[Ariana’s POV]] I sat here dumbfounded, waiting for the dream to end. But it never did. I somewhat knew deep down "we are not alone", but I never excepted to see a bacterium coming from another planet, and he is much more than a simple bacterium! Sylvia seemed thoughtful, I decided not to bother them and simply thinking about the matter at hand. Even if he said he was just an observer, he intervened and sped up my HRT! I was really excited about the sheer possibilities of such a technology, I mentally noted to talk to him about this technology later, I’m sure he can help correct the deficiencies of my birth body, I squealed at that thought, and at that moment Sylvia came out of her trance. - "Ariana, are you okay? I mean an alien coming from nearly 100 light years away from us just randomly decided to change your treatment with something more advanced based on his specie technology? And what if it was dangerous? What if he was dangerous? A lot of questions remains unanswered, and I admit it creep me out" - "I am not okay-okay, but I try to see the good things, really Syl, you saw what he can do, imagine what this technology could do? I understand we can’t bring this back home, but you know, at least I could be closer to my true self" Ariana said, with her tone lowering at the end of her sentence. Sylvia did not answer with words, they just sat near me and side-hugged me, "she really needs that..." Sylvia thought. Syl, themselves, in their head at least, was also squealing about this ship’s technologies. - "Hey Ariana you know this morning we thought FTL was a science fiction concept that was impossible to achieve. You know like in these old shows, Star Trek I think it was called, they warped space if I recall correctly? You think this ship works like that? Or is it another kind of FTL? It may be jumps? Or wormholes ? Or some future physics concept we did not even begin to imagine let alone study!" I smiled as I recognized my friend’s nerd-mode. To be honest I was incredibly curious about the kind of FTL this ship was equipped with, running some calculation in my head, I deduced it was equivalent to about 1 light years per day, assuming the engine was designed to work all day long. - "Yeah, I agree, this looks awesome, also I am really curious too, maybe now we are in the secret they’ll let us learn a bit about their tech? I would like to have my own FTL ship." I smiled fondly at that thought - "Oh! Yes! Maybe we could even learn their tech and design our own ship and engine layout! Or maybe we could even improve their design!" Sylvia audibly squealed and launched themselves into their best friend’s arms. ° "Oh this is really nice cuddling like that", I thought. A few minutes, or dozens of minutes, I don’t really know at that point Sylvia was way too comfy, later the door opened and Aarin entered our lounge. #middle #emph[#strong[3rd person POV]] After about an hour he decided to check on his guest, he had a proposition to offer them, in part to excuse himself from the rude journey here, but mostly because he saw Ariana and Sylvia’s scientific interest and couldn’t wait to nurture it. He saw potential on these two, maybe Sylvia could absorb the Union knowledge and become a good union scientist, and probably the best human engineer ever seen on this history of their civilization. But that was an idea to think about later, now he was in front of the door of the lounge and entered. - "Hello, sorry for keeping you waiting, I hope you had time to think about what I just said, I have an offer for you. I would like you to gather me some intel on how your society works, I am a xenosociologist after all. But before asking you to do some job and to answer endless bizarre questions by dozens, would you like a tour of the ship? I think you also would like a tour of the sol system I can limit the power of the FTL engine to lower the travel time between planets, it’s not recommended, but your system is quite empty, no offense by the way, I think we would depart between one and two weeks what’s your thought?" Sylvia and Ariana exchanged a non-verbal conversation with only movement of their eyebrows and shoulders, this really confused Aarin, and he realized he still had a lot to learn about humans, good thing he "met" these two they also were essentials for his research as they were the best examples of the human gendered society, before he could finish his thought Ariana began talking, - "We would love visiting the ship! We still have a few hours ahead of ourselves, unfortunately, for the tour of the solar system, we would be on board of course, but we don’t have one to two weeks free now, however November’s break is in two weeks, so we will have at least three weeks of freedom what are your thought about that?" Aarin was pleased his guest were excited about the tour, to be honest he would be too! They had the only-in-a-lifetime opportunity to see every corner of the solar system, far beyond the moon which was still the farthest human settlement to this day, as Mars was not excepted to be man-visited for about a decade in his estimation. He agreed to show them the ship now and to arrange the system touring three weeks from now. He started by the cabin, - "So this ship is a small science exploration it does not have a lot of cabins, you will live in the co-pilot cabin just beside mine," just as he continued he was sure he saw Ariana sneakily take a peek of the cabin, but it also could be his imagination. They then stopped by the main engine room which housed the big nuclear reactor and the small yet sturdy anti-matter reaction chamber for the jump, he explained to the young humans behind him. - "We cannot enter directly the engine room itself because of the residual radiation and the temperature of the room, as you know dissipating heat in space is hard and the thermal radiators made to emit heat as infra-red radiation outside in space are not enough to lower enough the temperature of this room to allow most of known sentient life, this room is thermally-isolated and have powerful anti-radiations active and passive shields to prevent the radiation to damage living tissues" He explained, grinning at the two young humans completely absorbed by the view of the several dozen meters tall and hundreds of meters wide nuclear reactor stored behind the "glass" - "How big is this ship!? How can you stay stealth and isolated from earth sensors?" said Sylvia, still self-absorbed by the view. - "This, young enby, is one of the marvel of engineering of the union, and a secret we keep very secret to avoid… problem" Aarin told Sylvia, with a distinct university professor tone in his voice. "But as how we’re stealth, this ship is equipped with an electromagnetic deflector, it’s similar to the effect of a gravitational lens from black holes but at a much lower scale, all electromagnetic waves are deviated, so we’re basically invisible in all frequencies, we call that technology a cloaking device. To which is added a phase modifier, to the whole ship is vibrating at a very high frequency allowing the outside matter to pass right through it, so detecting us reliably is really hard, and dare I say, impossible with your level of technology." The visit now ended in the bridge, he did show the trick of switching from union-layout to human layout which prompted a really satisfying "ooooooh" from his two guest, and then he guided them to the transporter room in one of the bay. - "I hope you liked your tour, here is two short range communication devices, modified to your parameters and liking, I think you call them mobile phone, they are connected to the mainframe in the computer room and allow us to communicate easily, call me if you have a problem, I will warn you the next time I transport you" he added with a wink. At that Ariana shuddered and was visibly shaking, seeing that he added - "Don’t worry the transporter adapted to your physiology, it will be as light as if you’re jumping out of bed" he smiled before pushing the transport button. #middle Back on earth, the two friends were a bit shaken but seemed okay, they glanced at each others, smiled, and then hugged tightly. Just before Sylvia broke the hug, a thought came to Ariana, "There was only one bed…" = Where no tourists have gone before! <where-no-tourists-have-gone-before> #emph[#strong[TW: mention of blood, mention of dead animals. Ariana’s POV]] The next few weeks flew by, by the moment it was time for school break I had managed to finish the work for the next weeks, I know Syl’ did it too, it was not hard to tell we were both really excited to be the first humans to visit the entire solar system! We also participated in Aarin’s studies, we gathered data about the wildlife for a few of his friend for their study back in his mainworld, and we told him some of our best stories, supposedly for his studies, but he seemed to had had fun listening to them! #emph[A few weeks earlier] We were in Aarin’s ship for the second time since that day, he was making some of his preferred meal from his home-world that was supposed to be compatible with human physiology - "Hmmm, Aarin, that, is supposed to be edible?" I looked as the disgusting "food" that was in front of me. - "Yes! Of course! In your language it can be translated as animal-mashup stew with a blood-gravy and its Union vegetables, the vegetables seems to be compatible with your digestive physiology!" Aarin was really excited, and I was guilty about not trying it but to be honest, an animal-mashup stew with blood gravy? Ewww. I was surprised when I saw Sylvia taking a big spoon of the strange food directly into their mouth like it was some regular stew from earth! They then looked at me and said - "It’s quite good Aria! You should definitely try it!" With the encouragement of my best friend I tentatively took a spoon of this… thing into my mouth and swallowed. The only thing I could think of is "we should give them an Oscar, because that thing is disgusting" I just manage to swallow it turned to stare at Sylvia and just spat, Sylvia was just grinning at their trap, it was hard not to show anything but Ariana had to try it! - "Next time we’re cooking." #middle The "meal" finished we decided to chill out a little in the lounge, I was becoming really familiar with this lounge, it was really cosy. I don’t know how we came to it, but I realized what was happening when Aarin was in the middle of his first story, Syl and I engrossed by his story-telling skills. - "And then my crew and I were swallowed by the big scary plant! It was awful but while I was inside it, I was able to take a lot of measurement and samples to analyze on the ship! It was brilliant!" At that, Syl and I lost ourselves laughing to death and that completely dumb story, he managed to be swallowed by a plant on some ancient abandoned planet far away in the corner of the Union territory? His life was weirdly wholesome. We then told our life stories, how we met, how we came out in a world still hard for lgbti-people and especially trans people such as Syl and me. He was particularly interested in the history of trans people and how society treated us in the past, I think he really is a xenosociologist after all. We cooked a lot of earth dishes from our favourites, he already had programmed earth wildlife DNA into the main computer, so we had the automatic food replicator crafting us some basic ingredients. This technology was fascinating, after transportation they manage to transform energy into matter while following a complex pre-registered matrix and some DNA to replicate raw ingredient. It can also cook it but according to Aarin it’s even worse than his dishes… So we made him some hamburgers with fries, fried chicken, veggies from earth (he loved zucchinis and spinach, weird but who am I to judge, I love snails). One day he surprised us and take ourselves on a world tour on his invisible shuttle! I swear this thing looks bigger on the inside but also not? It’s a really weird feeling and when I brought this to him, he brushed it off as nothing but a quirk of human psychology. We board the shuttle and in a few minutes we were high above the Atlantic Ocean! We visited the American Union, some old important cities like New York, Boston, Toronto, Rio. He even managed to sneak into the restricted UK territory and for the first time for more than a decade a European sat foot in London! The city was really different from the old photos in the time when the UK were in the EU. The streets are dark and empty. Only shaggy persons looks upon you to decide whether trying to muggle you was worth it, others were here to deal you some illegal drugs. The experience was scary, and we decided to climb up and rest at my dorm for the remaining of this day. The world tour lasted two days, we visited all the continents on the planet, I never thought I was gonna visit the whole world! And I can’t imagine that in about a week I’ll visit the whole solar system! Sylvia beside me was squealing I’m sure it will be our lifetime experience! #emph[Back to the present] I was with Sylvia in my dorm room, we were waiting for the ping from Aarin preceding the transportation, when it came we took our backpacks and readied ourselves for the biggest adventure of our lives! #middle We were installed into the co-pilot cabin, it was pretty huge, also bigger than it seemed when I peeked a look in it? I wonder if it’s only related to my psychology like Aarin said? Well I brushed this thought aside. Like I thought there is only one bed in this cabin. I was really nervous sharing a bed with Sylvia, a part of myself, surely a part of old-me and my dysphoria, said to me that I was "a man" and therefore I couldn’t share a bed with another person if this person wasn’t my partner. Stupid parental bullshit and manipulation, when will I ever be able to break you ? I already did offer to Sylvia to sleep on the floor if they felt more comfortable without me on the bed, but they called bullshit and hugged me tight. They really was the best friend I could ever image having. We unpacked our stuff into the admittedly luxurious closet for a small military ship, even if that was a ship detached to the science navy, and just basked into the warm soft bed and hugged tight. Life was beautiful sometimes. In the last few weeks super-alien-HRT (yes I gave it that name) worked like a charm, I lost about 5 centimeters, and I am now a few millimeters short of Sylvia (which she used to tease me on how I am the shorty now, even if I’m still almost 170 cm!). I lost about 10 kg, not that I was overweight, but I was packing a bit more muscle and I lost 5 cm to be honest. My waist pitched in, and I gained a lot of hips and a lot of muscles in my thighs. I think my voice was a bit higher and softer too, I never would have imagined I’ll get a science fiction super-advance transition. I talked about that to Aarin during the last weeks, and he said that this technology would normally give me what he defined "true form" I guess it’s close to "my female form if I were assigned female at birth" ? Maybe I could get pregnant one day! You imagine the first trans girl to ever give birth to a baby! The possibilities were endless, and it feels like magic, everything in this superfast transition feels like magic, getting that shorter? Magic. Voice? Magic. These thighs? Definitely magic! I can’t wait for the results of the end. It should take at least a year according to Aarin, but external changes are okay in a few months he said. I guess Clarke was right with his famous quote "Any sufficiently advanced technology is indistinguishable from magic". Whatever, we boarded a few hours ago, and I was really fatigued about this day and the emotion that followed, we were still in very high orbit of earth and decided to stay the night here, Aarin was finishing the calculation to make short-outburst of the FTL drives, we would also use the sublight engines to finish the orbits. So I decided to snuggle a bit more in the comforter and tries to sleep. - "Hey Aria are-you okay? You seem down, why were you trying to sleep on the ground? You don’t want to sleep beside me?" Syl’ said softly, almost whining, they may be pleading? I don’t know it sounds like they wanted me to sleep with them? They should be embarrassed no? - "Yeah, don’t worry Syl I am okay, I’m not down I’m thoughtful this whole thing is bizarre you know? One moment we were in your room drawing a science fiction FTL ship and the next we were on an SF FTL ship, so my brain haven’t really adapted I think? We do need to abandon all of our previously-conceived ideas about the nature of universe and alien life to accommodate the fact that we’re not only not alone but the closest one are a multi-stellar organize union with technology similar to magic. See my transition for god’s sake it seems like magic!" I yelled, I panicked, It was too much in so little time! - "Hey, hey, hey don’t worry it’ll be okay, everything gonna be fine trust me" softly said Sylvia, enveloping me in their signature big hugs, accented by the fact that we were approximately the same size now, I wonder if I’ll become even smaller, being in their arm like that seems really comfy, nothing like sleeping enveloped by the arms of your best friend. "And you know what you were already cute but now, you’re adorable" Sylvia smugly smiled, sawing my scarlet-red blush on my cheeks, I know they was saying this only as a between friend compliment, but it was making me really blushy. After a few minutes I relaxed into their arms, waiting for them to break the hug, but they never did, when sleeps was winning against my anxiety I was thinking that I would like to sleep like that, it must be so comfy being comforted like that, so I took my chance, - "Syl’, can we… like… you know… sleep like that? Your arms are very comfy" I was furiously blushing - "Of course Ariana, good night baby" she kissed me on the forehead, and we were asleep in no time. #middle A few hours later, correction, not enough hours later, I awoke to a low rumble through the ship, I recognized it well at the rumble of an on-ship fusion nuclear-reactor, we must be leaving orbit, I still was in the arms of Sylvia who was still asleep, accustomed to the rumble of a nuclear reactor, they lived in a ship for a few months when his dad was working on a mission. I basked in the beautiful innocent smile of my best friend still asleep, and managed to extract myself from their arm, get dressed quickly and came back with a replicated breakfast (cookies and a coffee) I preferred mine black, but they was the type of coffee person drinking it with more cream and sugar than actual coffee. I decided to pass by the bridge to see what Aarin was up to, one more times I felt a strange feeling passing the door of our cabin like a tug on my whole being that last less than a fraction of a second. I really should talk about this with Aarin. Before I even arrived in the bridge I heard a rather heated argument between Aarin and another voice I can’t really state. They were likely talking in their home language but Aarin never mentioned another passenger? The door opened, and I was in front of Aarin yelling at the holographic representation of… a blob ? Talking? - "What is going on here professor?" - "Oh Ariana, hello! Sorry I was arguing pretty loudly with the ship, she is quite angry at me" He said, quickly dismissing the holographic blob in favor of a holographic representation of earth and our current trajectory. "We are currently leaving the orbit in low sublight speed, we will make a short FTL burst after passing the level of your Moon and stabilize ourselves in an orbit around Mars, I understand Mars is a destination your kind wanted to set foot on for a long time now?" Ariana nodded "Well you’ll be the first human to do so!" A few minutes later Sylvia emerged from the door, fully clothed into their "standard work uniform" which is a fancy word for a pair of sweatpants and a large t shirt, smiled at me and sat in the engineering station of the bridge and were staring at the screen displaying our current parameters, sipping their creamy coffee - "Aria that’s incredible we have real time data about our orbit right now on this screen!" Sylvia was excited that’s for sure, she tilted her head and added "it’s human-readable?" at this Aarin indicated he took the liberty of translating the ship operating system to simplify our usage. About an hour later Aarin mentioned we were doing a little flyby of the moon, it took us only an hour to be here! The moon was beautiful this close, the little (or big) craters were really detailed, and it took all my willpower not to take photos and just marvel at the show! Sylvia on another hand was far more impressed, they already did a flyby or two of the moon with their dad, he was working on the development of permanent settlement on it to be honest. Just an hour later we were passing the Lagrange point L2 of the earth-sun system, the first place were a probe was placed by, a union scientist according to Aarin. The probes were moved in the early 2000s when the Union picked encrypted signal from NASA and the ESA that the James Webb Spatial Telescope would be in, a halo orbit in the L2 point, the chances were small, but they couldn’t risk detection. - "Please sit, Sylvia sit here in the engineering station, Ariana please take the co-pilot sit, we are gonna make our FTL outburst" calmly said our host, we complied and were really excited, we were on the verge of becoming the first humans to travel faster than the speed of light. That was something, sorry Einstein, you’re wrong! #emph[#strong[Aarin’s POV]] I smiled softy as my two guest strapped themselves into their sit, they will be participating into that jump, and they will never forget it! - "Ok begin checklist, Ariana please check the coordinates in the navigation panels we should be around twenty thousand kilometers above the surface of Mars, in the standard direction, Sylvia please verify the integrity of the FTL drive" - "Aye captain" giggled the two young humans beside me, they were dying to role-play it was obvious, a few seconds later the two officers signaled the go - "Ok, Sylvia please turn off the main sublight drive, Ariana when it will be done please disengage the drive and turn on the FTL drive" the two nodded About a minute later the rumble died down, but another one resounded in all the ship, the signal that the FTL drive has been engaged, I signaled to Ariana the GO to power on the drive and a few seconds later the rumble intensifies and died down. - "Ok final call, engineering ?" - "Go" confidently said Sylvia - "Navigation?" - "Go" said Ariana, with a bit less of an enthusiasm, I noted with a smile - "Ok initiating final countdown" The computer began counting, 5...4...3...2...1 "jump engaged" #emph[#strong[Ariana’s POV]] And I thought the engaging of the FTL was something! This was another! When the computer signaled the engagement of the jump I felt like the entire space was twisting, collapsing onto itself and then like it never happened we were in orbit of Mars. - "Now, this jump seemed instantaneous because it was, I used the jump drive to arrive here, when we’ll finish with Mars we’ll use the standard FTL travel to go visit Jupiter, now, gear up little ones we’re going on a walk!" #middle #emph[#strong[Aria’s POV]] After a long and tedious phase where we replicated suits at our size and constructed the oxygen tanks, a part which Sylvia loved, we were ready to strap ourselves into the shuttle and make our approach of Mars. We were going to walk on Mars how awesome is that? Aarin surprised me when he offered me to pilot the shuttle down, - "Are you sure? I never drove a car back home, how could I drive a spaceship?" - "These shuttles are designed to be easy to use, just strap yourself in the main piloting chair and let your instinct do the trick! It’s highly human-customized everything should be coming natural to you and if you manage to screw up the shuttle’s AI will take over and landing us softly on the ground!" Agreeing, but nervous, I took place in front of the customized piloting area, I was pleasantly surprised when I saw it, it’s not like in science fictions where you have a thousand buttons and five different sticks and if you press them in the wrong order you accidentally launch a nuclear missile on Russia instead of playing your favourite music. No, this is… simple? There was an on/off switch with a little pictogram of the engine - I guess it is the engine turn on button ? - a thrust slider, an array of simple labeled buttons, and a simple controller. I took the controller in my hands and decided to role-play a bit, you’re not piloting a highly advance alien spaceship every day. - "Stations, do I have the go" - "Yes ma’am" simultaneously said Aarin and Sylvia with a smirk on their face - "Ok, disengaging docking port" with that I pressed the… docking port button on the panel and with a loud #emph[#strong[thud]] we were now in free space, this thing was way too easy. - "Engaging RCS thrusters" after engaging them I slowly used the RCS to be a little farther away from the mainship until the light indicator went green and the engine button unlocked. I smiled - "Turning on main engine" I pressed the button and immediately the entire shuttles rumbled for a few seconds before everything went back to normal and the basic data about fuel, engine situation, orbit and radar - I guessed it was a little more advanced than our radar, but the name did fit pretty well - I managed to see a glimpse of our vessel by the shuttle’s windows. And what I saw really surprised me. Due to the unknown distance and lack of reference point I could not guess the size of it, but the shape was… off. The vessel was not specially designed or with a futuristic shape or anything like that. No it was a sphere. A simple sphere. As a designer and art student saying that I was disappointed was an understatement, here we were the first humans to be in an alien spaceship and instead of a beautiful or weird or whatever shaped ship it was a sphere? I was frustrated and Aarin noticed it - "What? You know spheres are the best shape on the universe no? We are not some character of your science fictions stories we prefer practicality to showing off weird frames, and sphere are easy to manufacture in space too." - "Yeah, sure, but you know I’m kinda disappointed ? Designing is fun, and I’m spending my entire free time designing cool spaceship, so a shapeless gray flying ball in no fun" I pouted, Aarin smirked and pointed the commands, oh right I needed to pilot… #middle A few hours later I was still piloting into the free space around Mars when the "radar" thingy pinged I was intrigued, so I went to click on it, but the information bubble manifested in a hologram in front of my eyes before I clicked on it, weird it must have read my brain wave or something like that? I read it, and was somewhere between surprise and awful laughter, - "Hey Aarin the radar here is signaling the presence of a probe declared lost by the union, and its name is… <NAME>?" - Aarin nearly spit out his drink and said "You found major tom???" \"We lost that probe ages ago, and we happened to fly near it by pure chance, god they’ll be happy in the science team” At this point I was definitely laughing out loud, - "You called a probe <NAME> and you lost it, it’s impossibly ironic it’s not possible, clearly you’re joking I refuse to believe it" - “I know, I know, this probe was a prototype of a super-stealth technology we were developing, the end of this program is the cloaking device you saw, but this prototype was equipped with electromagnetic cloaking in all frequencies, FTL communications cloaking in all frequencies, and thermal cloaking, it’s practically non-detectable And we really did a good job! Because the cloaking computer thought its own FTL communications arrays were a malfunction and corrected it, that is, it dismantled the array and used its base material to create a communication deflector, and it became undetectable with our own technology, the only way to find it was to fly within a hundred kilometers of it, the ship computer then would lock onto its signal and track it. But 100 km in space is ridiculously small As for the name, our tracking probes picked up and sent all of your emission, including the non-scientific one. Well whatever I sent the coordinate to the ship’s AI she will pick up the probe we can continue our little mission, enough time spent flying and fooling around, we are going on a walk” #middle An hour later we were landing on Olympus Mons. I was thinking of the famous pictures of the NASA’s and later FSP’s rovers on Mars, with rocks, red powder, a red sky and everything super-red. Well it’s not that red, it’s more of an orange weird maroon rusty colour but yeah I guess it can be considered red if you’re half blind. We were walking, a lot, but it was kind of cool, we carefully picked the landing location of being far enough of any rover, I think the FSP’s controllers would freak out if suddenly they detected three humans casually walking on Mars like we were on the Sierra Nevada. It was a bit sad, I’d love to say hi to our robot friends on Mars, they explored this planet for us since the first Cold War. But yeah safety first. Still I’d love to see the face of Syl’s father sawing them on Mars waving to opportunity two. I pouted. Sylvia must have been thinking the same thing because when they saw me pouting they giggled into the shared radio (same I guess it’s not radio, I’ll call it super-radio) and tried to hug me. It was then that we discovered these EV suits are not meant to hug. Weird. #middle A few hours of walking later, I noticed that this body was so much better, I was not only happier, but I was visibly fitter and more athletic, I had a lot more stamina than I used to and was visibly stronger, I guess Aarin included some bonus with the alien-HRT because there’s no way my "true-form" would be so strong. We decided to stop to eat, I was going to take off my helmet when I caught Sylvia looking at me with big eyes, almost as spherical as the ship, and I remembered that Mars’ atmosphere was not breathable, I think my blush of embarrassment was visible through the helmet because Sylvia approached me and lightly tapped the top of it, with a sound I imagined as being a bonk. Instead, Aarin used a little capsule that expanded into a little shelter with atmospheric pressurization and a built-in airlock. The Union technology was wonderful, and also confusing, how can they have invented conjuring buildings out of little capsules but not the internet ? As soon as we entered the shelter and took off our equipment Sylvia’s jumped in my harm and hugged me, they really loved to hug me and to be honest I was not complaining, it was so good to have a cuddly best friend, and she was more and more cuddly nowadays with my transition I wonder if there’s an explanation to that. - "Ariana! THATWASSOCOOLWASNTIT?" Sylvia shoot, yelling and talking so rapidly that my brain could not comprehend what just happened. - "Yeah Syl’ it was incredible, we were trekking on another planet it’s not something I thought I would do in my twenties, and I’m 19 !" I laughed, trying to sort myself out of them, I was becoming shorter than them, and it was more and more difficult to do so by the days. Help I’m soon going to be a prisoner of my best friend embrace. Eventually I pulled out, or they let me out I don’t really know, and we began eating, earth food again, prepared by Syl and me again, we were not letting Aarin cook anytime soon, the memory of the stuff he tried to pass up as food was engraved in my memory, so vividly I could live again the situation, not that I wanted to. The meal finished and the shelter safely back onto its capsules we wrapped up our Mars tour and came back to the shuttle. #middle A few hours later I was chilling in the lounge with Sylvia snuggled to me reading the manual and theory papers describing the FTL ship when Aarin called us up to the bridge, we were gonna activate the FTL drive to travel to Jupiter, Sylvia requested to access the command room of the engine and was granted access, so they were there. #middle About a day later we arrived in orbit of Jupiter, we were to visit its moon, it’s not like we could safely walk on Jupiter to be honest, and having a bit of fun. Once again we took the shuttle, but Sylvia did not come without us this time, they said they still wanted to read the theory about FTL travel and how it works, Aarin agreed so here we were landing on Europa’s ground with a few hours to spare before going to another interesting moon. - "Isn’t Europa supposed to have a liquid water ocean deep?" I said, the hype of being in space quickly faded, and it was like any other walk. Just with a helmet to void to suffocate into the endless void of the universe. But I was indeed really interested about this stuff, liquid water practically says "life" isn’t it? This was exciting, unknowingly to me, all my hopes will be crushed in an instant. - "Yes this was confirmed by a team of our scientist, but no I know what you’re thinking, our technology is advanced enough to detect life signs this deep and there isn’t. None. Not a single spark of life. Just endless water and ice, so deep that even our equipment have trouble accessing it without destroying the entire moon. This water could solve one of your current issue, you know with climate change and the fact that you’re not trying to do anything world-wide to address it" I cringed at that, he was right, even if we formed a planetary federation and society we were still based on a form of capitalism, and capitalism always prefer profits to saving our climate, and according to every earth scientist, our specie. - "Yeah I know, but you know what, the planet will survive, the biodiversity will regenerate, only our civilization will disappear, and at this point, don’t we kinda deserve it? The early twenty-first century attempt to stop climate change did not work because nobody followed it, and now it’s nearly too late. Climatic anxiety gained all of my generation, we feel completely useless about what is happening to our civilization." #emph[#strong[Aarin’s POV]] Wow I thought, I knew that she had a mind on climate change but not that climatic anxiety was so deep down attached to children in earth’s society. Even if that’s something to add to my research I could not help to feel sad for the poor girl, she felt powerless, useless, and to be fair she was, governments needs to change not her she can’t really do anything. I tried to do as I often observed human do when one of their acquaintance was feeling down I tried to envelop her with my body and arms and tightened my grip without chocking her. If I recall correctly humans call that "hugging" and it’s supposed to be a sign of affection, it really seems to calm her as she tightened me too, I knew it was known as "hugging back" and a sign she accepted the gesture and was happy. Humans are weird how nearly chocking to death one of your member is considered a sign of affection ? Anyway, I needed to calm and comfort her, to be honest I think I gained a liking for this human, she was kind and likable, her friend was really smart and was already figuring out the in and outs of FTL travel I could see it in her eyes, the flame of passion for a subject, I was like that when I discovered humans in my xenosociologist degree, their society is so, so weird. They developed highly advanced technology such as the internet that allowed their people to access up-to-date information and science in all of their world, and to post silly cat videos I added, chuckling mentally. Yet they were still at the age of bigotry, climate disaster and capitalism. The Union members had all abandoned capitalism ages before developing any kind of technologies, it simply wasn’t a viable model to continue, capitalism cause the "economy" to collapse onto itself regularly; records also indicate it actually happened on Earth, many times, yet they keep this way of living. Many Union philosopher and economist argue that it’s because they kept capitalism for so long that their technology is developing so fast. War were still a thing on Earth just 10 years ago. In and all Earth society was intriguing, and I was obsessed with the concept of gender, this seems pointless and open the door for so much bigotry. I decided to voice some of my concern to her and finished with, - "You know Ariana if I am a xenosociologist and pushed for that degree after my original degree of xenobiology it is because of your specie, your society is so bizarre it doesn’t fit with our models and predictions, the discovery of your planet revolutionized xenosociology in The Union. Your rhythm of technological advancement is so fast in certain category but so slow in others, how come your medical researcher did not cure human cancer yet, or developed better solutions for trans people? I really don’t understand how your society works and that’s why I volunteered for this mission, nobody really wanted it to be honest. The concept of gender is really weird too." - "Oh I don’t really know about it, I mean some cancers are treatable? But the cures are really expensive and unfortunately with the formation of Europe and the Federation of Continents free healthcare kinda disappeared ? This and other social structure, yes all the world is working together now but the Federation is so economically liberal that practically every social protection concerning citizens disappeared. Yes in Europe we have a bit of chance there is a free basic income and my University provide orphan or abandoned children with a place to live, but it’s not generalized, and it’s not enough if you fall seriously sick. A lot is left to do on Earth I’m afraid." "About the gender I agree, gender is confusing, but I’m enjoying gender right now, because of you so thanks you by the way." I had a lot to think about what she just said, Earth society has a long way to go indeed but some of their ideas are wonderful, and they just think differently, the word science community is well-formed and ideas, theories, and data can safely be shared and accessed everywhere on the planet, for free, it was a start, I think it is all they need to evolve their society to something more fair for the citizens of Earth. #emph[#strong[Ariana’s POV]] Talking about our society with Aarin is really refreshing, he has scientific outsider ideas and comments about it to make, and it’s exactly what we need to hear, he also clarified a lot about how he thinks society morphed into what it is now, and how it changed over time. Having a literal scientist of societies that studied yours for decades now and can identify what went wrong helps to be honest. Where and when, which to be fair his answers looks like "everything", "everywhere", "at any point in time" things went wrong. He said that our society is mild and can be changed with little to no help, just readjusting itself, he was really optimistic about it, it reassured me a bit. He also said that humans were not ready for first contact with The Union, but when the time come, The Union would help humans to be more considerate about their citizens and with the cultural mix both our societies would mix into a better society for all of us, they were really interested into how we developed technologies so fast, and it was a point of intensive sociological research in The Union. #emph[#strong[3rd person POV]] Unknowingly to Aarin and Ariana, a team of Union scientist were on Europa when they landed, they sensed the Union shuttle and came to salute Aarin as he was the only scientist they knew of that was on the system, but when they arrived they were surprised and a bit mad about the presence of a human with him, not knowing what to do they decided not to confront him here and there but took evidence, rejoined their ship and went full-speed in direction of Union Central to report him. = Help! Mall is scary! <help-mall-is-scary> #emph[#strong[Ariana’s POV. Approximately 5 months after the events of the last chapter]] After that discussion on Europa we visited a few satellites and even passed by Pluto (which is smaller than the Moon!) then the week had passed, and we made our last FTL jump to Earth to be back home. Resuming a normal earth day to day life of college, work and assignments after a week visiting the solar system is surprisingly easy. It’s like a vacation in New Washington (the city, not the state, not DC the district of Colombia does not really exist anymore) but instead of the other side of the world it’s the other side of the solar system and instead of taking a plane you take a super-advanced alien FTL rated ship, well it’s not really the same thing I guess… Anyway it’s been more than five months ago, we had some conversation with Aarin in the meantime, he managed to buy a phone and a phone plan and to hook up the world phone system in his ship? We only came back in his ship two times, once to visit the Moon and the second time because Sylvia wanted to test some of their theories on how to combine Union and Human technology to increase the FTL efficiency and speed, so far their theory remains unproven, and they didn’t really succeed to significantly increase the speed but Aarin was really interested, and they were working together on the next generation of the drive upgrades. That let me alone, I am not a scientist like these two, I apparently have a gift to pilot Unions Ship, but I could not help them improve the drive, I’m not a physicist, I’m a drawer, I draw ships I don’t build them. This, led us to now, Sylvia realizing they were abandoning me summoned me to their home, taking Aarin as a "friend from college" and their mom was there two and the two of the Uin’s (Sylvia’s last name they do not use it because they don’t like really much and can’t really change like me because they were not abandoned and forced by the state to change their name, not that they wanted to) adults were trying to convince me to go to the mall to buy clothes I love cute clothes, but I hate malls. And to be honest I’d much rather prefer being imprisoned into a high-tech Union prison cell than going to the mall! - "But! I could order clothes online, you know the internet exists!" I whined it was one of my last valid arguments - "NO, first you’ve changed so much that I think you don’t know your size, second if I let you do that you’ll let dysphoria telling you that you don’t deserve it blablabla you’ll never look good in it blablabla, and I can not let that happen you’re adooorable and an adorable thing like you must have clothes for her. You can’t spend your life in your dorm room open to society!" Sylvia said their hands on their hips in a "that’s non-negotiable" move. They was right obviously I change a lot, Aarin said my external physical changes are finished, and he was right every part of me felt so right that it was scary I was lean, thin and athletic, it really feels like my body for the first time in my life. I ended up being a bit over 153 cm (5’0), in other term I was small like miniscule, Sylvia towered on me, I was flustered every time they was in front of me. I also lost a lot of body mass, that is coherent with the huge height loss to be fair, I had a layer of muscle all over my body and was really strong, I could breathe again, my breast reduced in size when my torso reduced too, so everything was perfectly balanced. My shoulder and waist was narrow. With a little of definition on my hips showing up my figure. All of my skin was so smooth it was a wonderful feeling. And with how much Sylvia was hugging me when we were together I think they loved it too. My legs were strong, definitely long distance runner’s legs and I kept on the distance I joined the track club in college and everyone was happy with me on the girl’s team they loved me and protected me from transphobic bullies. So I was now a small but lean and toned athlete ready to run the miles, with friends on the girl’s track team, and a very hot best friend that was hugging me every time they could. I think nothing more happy could happen to me. There was the situations of my organs, last time I discussed it with Aarin, he replied matter-of-factually that it should take a year or two for the internal change to take place and that yes indeed I could get pregnant, he estimated my menarche to take place in a year or so. But I had Sylvia to help me out, so I was okay with that. I was, however, a lot less okay with the concept of being pregnant, I learned everything I could on how not to be accidentally pregnant and well I could start birth control if one day I’d have a trans girl girlfriend but in the meantime as I did not intend to sleep with cis guys I was pretty much protected against unwanted parasite in my soon-to-be uterus. The remaining of my characteristics did not change much, my face softened a bit and my cheekbones where a bit higher, my hair were a bit shorter, but that was not because of alien-HRT it was because of the fact I lost more than 20 centimeters (about 8 inches) and my hair were already at my but so I was literally stepping on them, not a very pleasant sensation. I was really, really, happy, and so was my bubbly friend they intensified the hugs and turned the dial to eleven. I once again wondered if this had a meaning? It was time to answer their question, - "Yeah I guess I need new clothes…." I said half defeated half excited to buy cute clothes for my cute self - "I saw you smiling Ariana don’t pretend you’re not gonna like it! Take my money to shop you’re like our daughter, and you’re too adorable not to help you" Syl’s mom was giving me her paying credentials which I reluctantly took, a small part because I was still blushing as the "daughter" statement but a much bigger part because I was an alone college student, so I was broke of course. A few subway stops later we were at the mall, it was a rather calm day, we were in the middle of April and the finals were next week, everyone was busy studying. I preferred it that way and I knew it was deliberate on the Uin’s part to do so they knew my incompatibility with crowds. - "Sooooo where are we gonna start?" Sylvia said, smiling, of course the question was rhetorical because I’m sure they already planed the part. Aarin himself was following us like everything is fine. We were shopping for clothes for my alien-super-HRT altered body with the very alien who altered HRT and gave it to me disguised into a human but with only theoretical knowledge of the human society, what could go wrong? #middle It seems unfortunately that a lot of things could go wrong. In fact a lot of things went wrong. We should have told Aarin not to enter into any changing room, he got banned from a few boutiques and after a few times of that decided to activate his cat disguise to be more sneaky. He was really cute like that. It’s a shame these technologies were not compatible with human physiology. But I got my cute body, so I could not really complain. We finally arrived at the first real stop of Sylvia’s "path of cute clothes" plan. I swear they were a dork but the best best friend. And had really cute lips I wonder how they fee- ok Ariana stop we’re not thinking that here. - "Huh, Sylvia we’re starting strong…" I said staring at the lingerie store in front of me. - "Yep! Let’s get you measured and let buy you cute underwear!" #middle Ok that was embarrassing, first the vendor was more engrossed with the cat than with the task of helping us, I finally got myself measured, and obviously it was exactly what Aarin already told me beforehand. I was embarrassed at first; but I quickly got into the fun of trying underwear and lingerie. It was so much fun! I loved seeing my new body and could see Aarin amused even in his cat form. We bought a lot of underwear and some swimsuits to swim, I could do that now! No more dysphoria inducing shower or bath, now I could take showers, swim, bath, see me naked, and so much more without dysphoria! This gift from Aarin should be publicly available. He assured me doing his best, but it could not appear from nowhere and I unfortunately once again agreed with him that humans were not ready for a first contact with the Union. We continued on to buy some basic clothes like shorts, t shirts and more, I tried so much clothes that I was dizzy, I could spend a lot and Syl’s mom assured me it was okay it was not everyday she could arrange to buy a whole new wardrobe for a new daughter she said. I was okay with that, and I was so grateful she was okay with me and so supportive and actually treating me like her own daughter. Sylvia picked up my gaze and ordered a break, she then snuggled up to me, - "I know what you’re thinking Aria, but it’s okay we love you, my mom loves you, my dad loves you, they consider you as their daughter, you spent so much time at home that they already considered you as their child, you know they already knew your parents were awful right?" I nodded and started to sob they tightened their hug and started stroking my hair, "It’s okay you’re safe now you’re with us, Aarin’s here too, and you saw what he can do, have you seen you on a glass you’re adorable now, not only that, you’re truly happy I never saw you having this much fun I’m so glad you could have a body more suited to your taste. And dare I say suited to my taste too" she grinned at that "The fact is Aria, we love you dearly, I’m sure Aarin loves you in his weird cold alien way of loving people, but he does, he broke protocol to help you personally, and more importantly" Sylvia took and squished Aria’s hand "more importantly I love you Aria, with all my heart". With that I stopped sobbing, sat a little higher, and answered - "I love you too Syl" Sylvia’s face lit up like a Christmas tree, "you are the best friend I could ever have had I’m so glad I have you in my life". I sensed Sylvia’s tensing and then relaxing, - "Yeah that’s right the best friend I could ever have had" they said a bit down, but I think it’s more of the ambient sound why would they be down after I said I loved them back? Half an hour later of relaxing sobbing and hugging, and petting our "cat", we continued to browse boutiques, where I modeled a lot of dresses, skirts, blouse, shorts, pants, tight jean, and other unknown clothes, I’m sure Sylvia must have tried all the different kinds of clothes that existed in this world but each time I thought this was the last kind of clothing existing they presented a new one to model. We had a lot of fun and ended up buying a lot of clothes for me, a bit of clothes for them, and even cat’s treat for Aarin, yeah apparently disguised are not only visibly he loved cat’s food in this form, and I’m sure he did not really want to kill and eat a mouse. We stumbled across a high-end dress boutique with matching shoes - "Come on Aria! You’d look stunning in one of those dress!" Sylvia plead - "I don’t think so, I’m not a dress person you know it does not fit me" I said, and yes maybe it was dysphoria talking, I guess dysphoria did not completely vanish, it was too good to be true - "Aria! You let dysphoria talk! Again!" Argh, they were really reading into me like an open book, their face softened, and they added "Come on Aria, trust me you’ll look very good, try one please, if not for you, do it for me please?" Sylvia plead again, this time with eyes even more cat-like than Aarin’s - "Okay, okay! But you must try one on too! I know for a fact you like dresses, and you’ll look even better than I will" I really wanted to see them into a dress like that. - "It’s a deal!" #middle #emph[#strong[Sylvia’s POV]] This dumb-ass, she is my best friend, but she can be so dense! I tried a hundred times in the last few years to confess and each time she thought it was as a friend! I mean yeah I never clarified the situation, so it was on me too, I’m.. a.. bit shy. I managed to get her in a dress at the condition I model one for her too, so I took a dress that was okay for my body structure and adjust it on me, and I must say it was a really good-looking dress, I was looking pretty good. I must think what to do with my… Aria problem. With her transition she was transitioning from cute to cuter but with the alien-HRT that was illegal. She was literally the cutest girl I ever saw in my life. Okay maybe my love produce a little judgment bias, but she was beautifully cute and innocent. And with how happy she now seems to be, I can’t not think of her I need her to know I love her romantically but with her density and my shyness we are not gonna do it if I don’t change, and fast, I can’t let someone take my precious little thing! Sound indicated that she was ready, and she came out of the changing room dressed. And I think I might need CPR because I’m sure my heart just stopped. In front of me was a beautiful young woman, she was small but not a child, and she was wearing a deep purple dress covering down to her ankle, a moderate amount of cleavage were displaying but nothing too fancy or indecent. This was a dress appropriate to go to an 18th century ball. The sleeves ended in a ruffled balloon sort of structure which were accentuating her delicate hands wrapped into purple with gold gloves. She was the epitome of beauty. And she was my best friend. The woman I loved. I lost control of myself, approached her, and kissed her. #emph[#strong[Aria’s POV, a few minutes earlier]] I don’t even know how I was ever gonna do that, I will pass the door of the changing room and my best friend will see how ugly I am and will… No I should stop, this is anxiety talking, they will not be disappointed, and I’m not ugly, I took the time to think about my feeling towards them. I loved them sure, but not like they do, they loved me as their best friend while my love was deeply romantic. It was a curse, I was cursed to love my best friend despite the fact that feeling will never be mutual. But they had said romantically they loved me earlier today, was I over interpreting? I don’t know. I resolved myself to say to them my love was romantic and accept any possible consequences of that statement. First, I need to pass the door, I moved slowly and opened the door, And here I was, in front of them, and I stayed here breath taken from me by an impossible beauty. They was beautiful, tall, lean and cute, all of that packaged in a beautiful black dress that let little to my imagination. The hem of their dress was mid-thighs and contrasted with her pearly white skin, their shoulders were bare, the dress starting on her chest and showing a decent amount of cleavage. I barely registered them approaching me, I did the same, and before I knew it, I was kissing them back. = Alone <alone> #emph[#strong[TW: Suicidal Thoughts, Sadness, Symptoms of Depressions, Aria’s POV, One year later]] Turns out you can go to the mall and getting imprisoned into a high-tech Union prison. Even if I was in an apartment, it felt like a prison to me without them. I once more mentally got over the details on how I spent the last year of my life into this prison this was my most cherished memory I couldn’t forget it, so I forced myself to go over all the details once again, I don’t care about the pain I just couldn’t forget it. #emph[#strong[Aria’s POV, Just after the capture]] We were in the mall, I was kissing back Sylvia, they broke the kiss, and we were just in the aftermaths of what just happened, we were kissing, together? - "I love you" we simultaneously said before kissing once again and again, and again, and again, and again. About half an hour later we took off the dress, paid, and just wandered in the mall hand in hand, everything was perfect. A new body, with a new perfect soft airy and high voice I was just so content with and a perfect partner who I loved dearly and who loved me dearly. Everything was just so perfect. We were shopping in another boutique trying to find matching shoes for our dress as we did not like the shoes displayed in the previous boutique, I was alone in the corner of the bathroom fixing my make-up while Aarin was with Sylvia trying new shoes. Just as I turned myself away from the mirror I saw movements, I barely noticed what was happening before I woke up in a cabin no different from the one Syl and I had in Aarin’s spaceship, but I was alone. And the door was closed. The ship’s AI did not respond to my commands and the ship’s monitor were not translated in my language. I didn’t have time to overthink as the door opened and a tall, big man entered the room. He was impressive, I was a bit terrorized. I quickly deduced it was on purpose, this ship looks like a Union ship, and I’m sure they can customize their disguise. Lastly I knew it was not Aarin, despite being apparently cold he has a kind heart, he helped me and took us under his guidance even if we knew it was surely not legal, but the person before me was not. He radiated an aura of cold ruling. - "Pardon me for my language, unlike Aarin I did not learn your language I use the universal translator" I nodded "Welcome to the admiral ship of the Union Navy miss Luivon, may I call you Ariana?" I nodded again "Thanks you Ariana, I am <NAME>, you can call me Nass, you should be able to pronounce it, commanding officer of the admiral ship of the Union Navy, I oversee the action of the Union Science Fleet and the member of its roaster, including your friend Aarin." I nodded, again. - "Why am I here?" I tentatively asked, even if I knew it had to be related to the fact Aarin took me under his guidance and helped me, I wonder where is he, did he get caught too? - "You’re here because you’re under arrest under the Article 70 of the Union Convention on Outside Worlds, well technically he’s under arrest, but we failed to catch him, you were spotted with him walking on Europa a few months ago, as you’re human and not a citizen of the Union you should not have been here. You will help us track and capture Aarin to punish him for his crimes." That answered my questions about him. I was dumbfounded, there was another team of scientist present on Europa at the same time? And they missed that? Damn it that was bad, they even took photographs of them on Europa. I will not help them track Aarin, he gave me this body he helped me and was kind, but do I have even a choice in the matter? - "And if I refuse to comply?" I asked, also softly as to not anger the big man on the admiral ship. - "You will be imprisoned on a high-security facility pending trial, if Aarin shows up you’ll be pardoned, your memories of him and the Union will be wiped and the body alteration he did to you will be reverted" This was bad, I could not let them revert my "body alteration" as he phrased it, I much rather preferred to be imprisoned in his place. - "And what are the usual penalties for this crime". - "Death" He said, calmly, coldly, like my death to him was as meaningless as the death of a bacterium to me, well I guess that my death was as meaningless to him as the death of a bacterium to me to be honest. I faked taking time to think as I just tried to calm myself, I finally get the love of my life and I had them for a couple hour before being capture by a powerful alien government and threaten of death. - "Ok, I, <NAME>, refuse to comply" I said confidently, knowing I couldn’t lead them to Aarin if he risked dying by my fault After this interview they did not came again, my room had a bed, a miniature kitchen with an ingredient replicator so at least I would not die of hunger, it has a terminal that refused to boot up, I guessed they denied me the access to their internal network. If only I listened to Syl when they told me to follow this course on computer science in New Paris University, it was more of a wishful thinking as I doubt human computer science could teach you how to hack a high-tech alien ship network. #emph[Syl.] I missed them. Badly. What could I do without them in my life? I don’t know… maybe the death penalty did not sound so bad after all, it would be soon over? No I couldn’t think like that, I know Syl and Aarin won’t stay immobile in this game, they’ll act I have to trust them as they must act silently to avoid detection. I leaned back in the bed, and tried to sleep in that room. #emph[#strong[Aria’s POV, 3 months later, Union Central Arrival]] Finally, we were in orbit of Union Central, the view was incredible up there, millions of artificial satellite were buzzing around, the incessant travels of various shuttles were clouding the darkness of the vastness of space. I learned that there are other shapes of vessels than spherical one. I saw a cube vessel. A cylinder one, all sorts of geometrical perfectly smooth vessel. There was also some science fiction grade ships with big engines and huge head, one day I spotted one that was exactly like the Battlestar Galactica from a 2000 TV show I loved. Others were right if someone pulled them off of a Star Trek show, I came to the conclusion that even alien, big nerd were universal. The quiet rumbling of the fusion reactor eventually came to an end and I knew what that meant, I was to be debarked and would be imprisoned on the planet. The door suddenly opened and Nass entered with two big guards, it’s funny how they always wear their human disguise while talking to me. And I wonder why he came with two big armed guards, Nass was pretty big himself, what can a barely five foot (153 cm) nineteen years old girl could do to him? They put cuff on her, then she was escorted to the shuttle bay, Nass piloted using the human mode, what was going on why are they all in human form? Unfortunately I didn’t have the chance to see the surface of the planet as I was blindfolded. I was allowed to see again as we entered a big building, big was an understatement I could not comprehend the sheer size of this building. It appears to be more than ten kilometers wide, fifty kilometers long and almost five kilometers tall, all in a gray colour. I was blindfolded again. The cuff were unlocked in what seemed like an observation room, made for human physiology too, it was weird? Maybe they have automatic adaptative furniture. - "Hello Ariana, I think you haven’t changed your mind on the subject of the collaboration, we can skip this part of the interrogation?" I nodded "So be it you will be detained into this prison for the time being, pending trial, as a non-citizen of the Union you do not have the right to have a lawyer to assist you." So much for an advanced civilization they deny access to a lawyer for foreigners, I have a feeling The Union is a lot less utopic as they initially appeared to be. I was once again cuffed and escorted into a room that was nearly identical to the one on the admiral ship, the cuff were unlocked, then they left my room. Fortunately they seem to be somewhat human in their manner of treating prisoners, I have a terminal with access to some basic information such as teaching material, a table, a full-fledged kitchen and a bed. It was bigger and more luxurious than my dorm room back home. I found myself thinking of this day again, the day everything happened, I missed Syl so much, I hope they’re okay, fortunately they was not on Europa with us, it’s a reasonable assumption to think they’re okay on earth, probably trying but failing to forget me. I knew them so much and here I was lying in a bed, more than eighty light years away from them, I was missing them more and more each day. Please be alright Syl, please be alright. #emph[#strong[Aria’s POV, 6 months after the capture, Union Central Criminal Court]] - "And by the information provided to me by the military, the science military and Ariana herself, I declare Ariana to be guilty of lying to the military in the efforts to find Aarin, she is however declared not guilty of the other charges" I sighed at least I could not be executed now, I spent the last three months reading and preparing myself for this trial, now I just had to wait and see what would happen, - "She is hereby sentenced to work for the public government of the Union, she can’t quit Union Central, a permanent union citizenship must be issued to her to be recognized at part of the Union and provided an apartment." I was surprised, did I just get sentenced to… #emph[be a citizen?] #emph[#strong[3rd person POV, 6 months after the trial, one year after the capture]] She sighed as she finished the recapitulation of everything that happened, life was not so bad here in Union Central, she was officially a permanent citizen of The Union, She could even quit Union Central and go work elsewhere, but she was banned from space travel outside the major lines between planets of the Union. The lack of Union-wide easy to use interconnection of network made trying to contact Aarin impossible, she was sure that he knew she was okay and was trying to save her, but what saved meant here? She was technically almost free, she was a full citizen of the Union, could travel in the Union territory provided that there was a major line here and provided she kept her tracker on her, well it was in her, so it was difficult not to take it. But it felt like a prison, she was going to work, grading papers, came back home and rest. Sure she had one or two friends, but she was alone, Sylvia was not here. And she started to doubt she will ever gonna see them again. She refused to date, she declined the simplest of social invitation, she was alone, so she made sure to stay alone. She worked as the head of the Union University Earth Studies, she created the department a month after she graduated from the Union University Accelerated Professorship Program, to be honest she had native knowledge of earth. Life was not awful, but her life was tasteless without Sylvia, she did not see the point in living it, she continued to push forward in life, just for her student, who became the only reason to live. Speaking of student, she just received an email, yeah the email protocol was so robust it was used by an alien high-tech organization such as the Union, with the absence of an internet the routing was a bit different, but the spirit was the same. Emails survived every instant-messages app or protocols. It was a picture, no... it was a painting, of one of her student, Uyuk his name was, she had to admit he was kind of handsome, and he tried more than one time to offer her to go out, she refused stating that as his professor she couldn’t do it, but she just didn’t want to, she couldn’t do it, Sylvia was her life. #middle She was depressed, and she knew it, but unfortunately, or fortunately for them, she thought, depression was not a thing in previous Union species, so she lacked support and appropriate health care, even if it was pretty scary how medical professionals of Union Central perfectly knew the human anatomy, human doctors take years to learn just human medicine how on earth do the union one learn hundreds of different anatomy, this level of knowledge scared her. However, she did find a counselor not affiliated with the government or the military, and began telling them her story, it was refreshing talking with someone, and she had access to human-compatible medication if need be. #emph[#strong[Aria’s POV, 6 months later (1 year and a half since the capture)]] I tried to keep track of time on the ship, however it was impossible, and now that I was on another planet? I could only work with their time system, I guess it’s been a bit over one year and six months now? But I can’t remember where we are on the earth calendar. Huh. Funny "earth" calendar, I’m already thinking of myself as more of a Union Citizen than as an Earth Citizen, it was bound to happen after a year living here I guess. My apartment is significantly better than my various prison cells, and I decorated it well I thought, my study was decorated with student art work, my art work, or student’s children drawings, it was really similar to an elementary teacher room to be honest, and I was teaching in college. Life wasn’t more tasty than before, life was still gray, dull, useless, only these pills kept me alive for this much time, I used to use my university pass to learn, and I learned a lot about computer science (thanks Sylvia!), propulsion theory even if I was far from good and from the level of Sylvia in this field I should now be able to understand them!, I learned art theory, philosophy, mathematics, physics, theology, history of the Union, I absorbed a lot of information about the world I was living in. But nothing would numb the pain of missing Sylvia. The pain was everywhere, omnipresent, always here to disturb me. #emph[#strong[Ariana’s POV, 2 years post capture.]] It’s been two years! I think ? I miss Sylvia so much, the pain is still there, more painful than ever, but I will not kill myself, I already took way more pills than I was supposed to, but it didn’t matter anymore I was in medical mandatory work break because of my mental state, my body is frail, I lost every muscle definition I had, I lost so much mass I was on the verge of dying each time I tried to get up. The end was near I could feel death coming for me, it was time! I suffered for two years, waiting for that moment to happen, the moment I would finally be allowed to die, to stop existing, the moment my consciousness will slip and the moment the last spark of life in my body will die. - "I’m sorry Sylvia" was the final thought I had the energy to form, my energy now completely depleted the spark did not have fuel anymore, quietly I slipped into the eternal slumber, 3….2….1…., and everything went black. = 31557600 seconds <seconds> #emph[#strong[Aarin’s POV Just before the capture]] I watched as Aria left for the restroom, a thing about fixing her make-up, and resumed my discussion with Sylvia, - "So you’re thinking we can overcome the power issue with linking the fusion sublight drive to the FTL core?" they asked We were discussing Sylvia’s idea to improve the drive, we repeatedly failed to link human technology to the union’s for the past five months, mainly due to a power problem, even with my admittedly oversized FTL drive for a vessel of my class we were hitting theoretical limit of the energy concept itself, with how much this drive needed. So we were trying to find ideas not only to increase the energy throughput of the reactor powering the FTL drive but also ideas to go beyond the concept of energy and spacetime itself. - "It should significantly increase the energy available to the system, but we need to do more research, we need something transcending space-time, and unfortunately for us, such a thing is a theoretical framework, not an object we can buy at Walmart" I chuckled after this joke, I started to think I was mastering the human art of joking. Letting Sylvia finding the right high-heeled shoes for them and their best… lover dress I checked my phone which pinged me a second earlier. - "Sylvia, come here now, we must regain the shuttle now!" - "What about Aria?" - "She’s already off-planet." I said, gravely, and she nodded. #middle A few seconds later (and two stolen pairs of shoes later) we were in the shuttle, good thing we took the short range personal transporters Sylvia and I developed in the last months, they was a real genius and I needed that, badly, considering what just happened to Aria. - "So basically we must wait here until they quit orbit ??" Shot Sylvia, I understand them to be honest their lover was just kidnapped by an elite team of alien right before their nose He was furious at himself for letting that happen, they were after him, not an innocent human! - "Yes they are on the planet, they can’t detect my ship because it’s parked on the moon, with anti detection fields activated, for the same reason they can’t detect this shuttle, but they can detect the ionic traces of a fusion reactor, so we must not move until they leave orbit, the ship’s sensors are passively routing information to me, we will now when they’ll leave orbit." - "You were able to detect the attack because of Aria?" They asked They was surprisingly calm given the situation, to be fair they probably was scared but the amount of love they felt for Aria transcended fear and a vibe of determination was radiating off of her. - "Yes, she has a microscopic tracker, invisible to them too, I know the scientist who designed them he’s not a pro-military guy, so he did not share his data with the Navy" I said, thinking fast on how to save her before they left orbit, even if I knew it was impossible due to their firepower advantage, my ship do not have weapon on it. One hour later his phone pinged, and he announced the news to his young friend, now - "I’m sorry Sylvia they just left orbit, let just rejoin the ship to think" They sigh together, this was going to be tough #emph[#strong[Sylvia’s POV, On the ship]] We were just docked that Aarin threw himself off his chair and rushed in the bridge, he accessed his desk and just threw everything on the floor while insulting himself and the military, I decided to respect his reaction and just step away without closing the door. My lover, my best friend, my world, was just gone, taken by the Union’s military because she was with Aarin on Europa. Everything happened so fast. I decided to speak with the ship’s AI - "Hey ship" I said, down - "Hey Sylvia, I’m sorry for what happened to your lover, I’m sure we will find a way to find her and save her" she said softly - "Thanks, I’m tired of calling you ship what about a name? For you, I mean, not for the ship." I saw the blob of information before me changing, indicating me that she was thinking about it, this artificial brain was a miracle a technology and may be a great help for our theories. - "Eleanor" she said matter-of-factly - "That’s a cute name" they said to the newly named Eleanor, they was sure that if she could blush that was that she just saw in the reaction of the blob of blue and black code projected by the ship’s holographic projector onto the main bridge holographic screen. Which was a sphere and not a screen. Well a spherical screen. Advanced tech was so weird sometime - "And I have an idea to name the ship" she said rapidly. I was intrigued why changing the name? Well they were officially fugitive now so using the same registry number was not a good idea - "Which is" said Aarin, closing the gap between us. - "Rogue Science Ship I" she said, and she added "Informally named Ariana Rescue and Investigation Association, the ARIA" we both nodded and approved the change in the rosters, we then proceed to destroy any tech that was designed to send positional data to the Union, we wanted to avoid being detected as much as possible, we were fugitive now, and highly researched. I didn’t really take time to process the loss of Aria, but I might not have lost her yet, the probability of a death penalty was really low and in theory we just had to jump in union central, beam her up and blitz the military ship to safety. Easy - "Aarin" I said, he turned, "We need that damned drive to rescue her, and there’s no way you’re sending me back to earth now" I said, determined to win, to rescue my lover and to beat the Union at their own game. We were gonna win no matter how much time we need to spend. - "Yes Sylvia, we will rescue her that’s not an option" he said, as determined as I was, good, because we will gonna need as much determination and luck as possible. #middle The plan was simple, first we are gonna enter a low earth orbit, from there we’re taking the shuttle back to earth and will talk to my parents, they are in danger too, they needed to be evacuated too, this however, proved to be a task more difficult than I thought. - "Mom! I tell you it’s real! Aria is off-world, in custody, we need to go now, or we’ll be the next" I pleaded to mom, Aarin was out convincing my father, who was still at work on the other side of earth. - "Sweetie, it’s not possible, but I think you’re genuinely thinking that I’ll call the hospital you may have a really high fever and I don’t want you to suffer more." their mom said, calm, and picking up her phone calling the hospital. This was bad, they needed to convince them they couldn’t just let them on earth. Thankfully they recognized the high pitch of an incoming short range transportation and relaxed. A few seconds later their father along with Aarin materialized just in front of Sylvia’s mom, - "Honey, I think we must leave this planet" Sylvia’s mom said to her husband, who nodded, a bit dizzy from the transportation #middle About an hour later they were on ARIA, in the conference room, soon-to-be reconverted into a bedroom for the Uin’s. - "The plan from here is taking off the Moon, penetrate into the Proxima Centaury system and establish a settlement there for the future operation" Aarin started - "However Proxima Centaury system is magnetically much more active than ours, and to add insult to injury a few of the planets have an ion shield so dense that even the Union sensors can’t look through, and that’s exactly where we’re gonna settle" I continued. - "So we’re just gonna travel five light years, fly through an ion storm so powerful than even your super advanced tech cannot see through and settle on one of the inner planet? To finish developing a revolutionizing technology to improve by up to 30000% the efficiency of your FTL drive, then we’ll fly right to your main world, jump into the upper-atmosphere, transport Ariana out and being so fast that the top of the line military ship of your world cannot catch us?" Dad synthesized the situation. - "That’s exactly it dad! #emph[Bravo!]" I grinned I knew what he would say - "Hell yeah! I’m gonna work on an FTL drive with my apparently propulsion-genius child!". Yeah. I knew it would hype him, he’s a nerd, a dork, a geek whatever you want, but he’s an #emph[engineer]. - "Yeah that seems like a good idea, poor Ariana do not deserve that, and to know that my child and her were finally together it frustrates me, let’s find her!" Mom said With that, the five of us, Me, Aarin, Dad, Mom and Eleanor, officially started the "revolutionize alien science to rescue the damsel in distress project.". #emph[#strong[Sylvia’s POV, 3 months post capture.]] It turns out that revolutionizing alien science while learning it because you’re human and have a few centuries of update to make isn’t easy. But we were making progress, albeit slowly, first we settled a little camp on one of the planet, even if we mainly live in the ship. It was big enough for all of us, even if a significant part of both the absolute space and subjective space of the ship was taken by the enormous nuclear fusion reactor powering both the sublight engine and one part of the FTL drive. The FTL drives of the Union were powered by conventional nuclear plasma but passed through complex latices of rare metal, crystals, after that it was infused in a time crystal and the space bent around the ship allowing it to reach faster than light speeds without leaving conventional space. The same infusing latices and crystals can be overcharged to create a short-range near-instantaneous jump of a little less than one light year. Showing that faster speeds were theoretically possible. The point is the Union didn’t come up with it, The Union discovered the properties of the latices and slowly built upon them, for instance powering the FTL drive through the latices only leads to a speed of approximately the speed of light. The time crystal was discovered later and combined on a working, reliable, production method. We built our engineering team with Eleanor, the number crusher, Dad, the experienced engineer, Aarin, who has the theoretical knowledge even if he’s a biologist, and myself a student in theoretical propulsion technology and dubbed "genius". Mom was making sure our calculation were correct and would not lead the Proxima star to become a nova. She was a nuclear physicist, former professor of theoretical physics at New Paris University and by formation an applied mathematician. She was perfect for the job, she also was good at tactics, which is welcomed given my best plan was "jump transport her and jump away", as fugitive we might want slightly better thought plan for the future, but it would do to save Ariana, they didn’t have time to be subtle. We could try to control the overcharge of the crystal to try to achieve greater speed, we already had actually, but the gain is not worth the energy and the drive overheat quickly. Forcing us to a stop and making the trip slower overall. No we all agreed on this point, the way to go was not to accelerate in conventional space but to leave conventional space. Obviously we found papers of the Union Science Academy discussing leaving conventional space to increase speeds, and theoretical calculations were insane, up to 50000% gains with maximum power, considering our goal was at 30000% it would be possible. There was a problem though. It never has been done, even in laboratories, no one actually succeeded to leave conventional space, it was deemed impossible, and the research stopped, way too costly for their results only theoretical. However, these past five months Aarin and I read all about earth theoretical propulsion tech and came to the conclusion that if we created a black hole at the bow of the ship long enough to bend space to create an anomaly and raced towards it in FTL we could leave conventional space to go in a space with a space dimension less than ours, and it would significantly increase our speed. Theoretically. The theory was creating and maintaining a black hole, race towards it in FTL and maintains an integrity field around the ship to avoid being crushed in two dimensions. Also calculating the difference in coordinates - thanks mom and Eleanor for these calculations - and lastly the problem of going to the normal space must be solved, hoping the calculations were correct, and we emerge where we wanted to and not on the other side of the Universe. It indeed was sketchy, but engineering achieve its best in sketchy situations. We would have to synthesize a new kind of time crystal, a space crystal, this type however was unknown to the Union and only theorized by humans, one of the biggest obstacle to it was the sheer amount of energy needed to finalize the process, it was the reason it was never achieved in lab back on earth. We also need a lot of time crystals as base material and neutron-star hardened metal to create the machine to synthesize the crystals, we must construct it based on theoretical description of it by human scientists. This was definitely sketchy The integrity fields generators however were easy, The Union have a technology easily available and adaptable by Aarin for our needs. All of that in as little time as possible for Aria. Let’s get started? #emph[#strong[Sylvia’s POV, six months post capture]] When we heard of the result of Ariana’s trial we finally let that breath out after having held it for god knows how long, she was granted citizenship this would mean she would be considered a criminal if she ever joined us as Aarin was. But did it mean she would become a criminal if we happen to kidnap her? It also protects her for the time being, in another three months mom and Eleanor would finish the navigation software, and they were crushing the numbers to solve the coordinates transformations equations. Aarin, Dad, and I went several times to the local black market about 2 weeks of FTL away from our base, gathering raw material such as metal and supply to construct the machine, we still had a lot of time crystal to acquire, unfortunately we did not have any clues on how to get enough energy to finalize the space crystals synthesize process. The remaining of the calculations has already been made, checked, double-checked and triple-checked, everything would be fine, we will be able to enter the black-hole dimension and leave it on demand. Hopefully where we want to. The integrity field generator also has been made, installed and tested and my god it’s beautiful, it’s nothing new, but it’s beautiful. The calculations on the coordinates transformations were due anywhere from 3 to 6 months and the machine would be completed in a year. #emph[#strong[Sylvia’s POV, a year post capture]] The returns from our spy on Union Central who conveniently found and served as a counselor for Aria were not good she was depressed, I understood the feeling well enough, I missed her a lot, the only thing keeping me sane is constructing our drive and jump right into these kidnappers and kidnap her back. We acquired the time crystals from a trusted (by Aarin) source, the delivery was due in three months, the machine was in the last phase of construction and testing, six months from now it would be okay, finally we had identified our potential source of energy to power the machine to synthesize the crystals. A supernova. A system approximately 4 months of FTL from us (and in the wrong direction from Union Central so it better works) is gonna enter supernovae in a bit. The tremendous amount of energy released by this "explosion" would be more than enough to power our machine to create all the space crystals we need and would ever need. The supernova was in a bit under a year, it will explode a week prior to the second anniversary of Aria’s capture. We cannot fail this, either we succeed, or we die, and we all knew and accepted it. #emph[#strong[Sylvia’s POV, two years post capture, unknown system]] That’s it, we’re there, everything has been sat up we were waiting for the supernovae to come, we were about thirty lights minutes away from it, so we had time, fortunately the machine is capable of mild FTL energy harvesting, thirty lights minutes is its maximum to have. I still have problems with the relativistic notion of simultaneity and prefer not to think about it and let mom tell us what to do. Once the supernovae starts the harvesting will start, ten minutes later the space crystals will be ready and automatically installed into the FTL drive, I called it the FTFTL drive, Faster Than FTL. But everyone just called it FTL drive like two years worth of efforts were unnecessary. Everyone was on board, and we were waiting for the signal… #middle And then the signal came, the drive was installed, we were performing a test jump back to Proxima Centaury. The jump that took us nearly four months before the FTFTL took us three now. We had one day to spare to perform tests and after, the final jump to Union Central upper atmosphere was gonna take two days. We must make the final adjustment to the navigation system coordinate transformation system the margin of error in the atmosphere of Union Central was non-existent. #middle Finally. It was time to jump in Union Central, the micro adjustment had been calculated by our dream team of numbers crusher, and we were ready, I was in command. - "Ok, final checklist is okay, onto stations, dimensional navigation" - "Go" announced my mother - "FTFTL drive monitoring" - "Go" announced my father - "Field integrity monitoring" - "Go" answered Aarin - "General monitoring" - "Go" said Eleanor, in her blob form in the middle of the bridge - "Okay, final countdown call" - "3… 2… 1…" count Eleanor At T0 I activated the FTL drive we quickly accelerated to thrice the speed of light, - "Generation of the black-hole" I pushed the FTFTL engagement button - "Confirmed" echoed my father’s and Aarin’s voice - "Activation of the energy flux to the space crystal matrix" I slid the slider to its maximum position - "Confirmed" said Eleanor whose job was to monitor everything else - "Ok, final acceleration" I pushed the FTFTL activation button Suddenly, even with the state of the art inertial dampeners we felt the acceleration as we were leaving conventional space and a second later the calm came back, and we were in the dimension - "Integrity fields" - "Holding at 100%" said Aarin - "FTFTL drive?" - "Stable" - "Navigation?" - "The course is followed by the millimeter, the drive will disengage itself in 23 hours 58 minutes and 20 seconds" said Eleanor voice. We were doing it, exactly two years later, we were saving Ariana, I hope it’s not too late already, suspicion of self harm and suicidal behavior made her staying at home. #emph[#strong[Union Central Space Monitoring Center, Union Central City, Approximately a day later.]] - "Black-hole activity detected sir" said a young officer - "Where?" asked the commanding officer - "… in the upper-atmosphere sir…" Suddenly all alarms went off simultaneously, a ship just entered the planet reserved space without authorization, but it didn’t make any sense to the commanding officer, no one noticed it before. - "It’s the black-hole sir… a ship is coming out of it.." said the same young officer, afraid - "Identification, and how is that possible? Ships don’t come out of black-holes!" shot the superior officers - "Identification matched, it’s the Rogue Science Ship I, it’s Aarin’s ship sir! We found them!" - "They found us ensign" corrected the commanding officer - "Coordinates confirmed, the ship is stationary above the university district of Union Central City" - "The government is gonna be so angry with us" said the commanding officer, knowing it was too late to do anything #emph[#strong[Sylvia’s POV]] - "Transportation successful, Ariana has been transferred to the medical bay as her state seems to indicate drug abuse, her survival at this moment is unknown" announced Eleanor as she once again pulled the ship into FTL, we were so fast that they could not track us nor could they find us, a quiet blue gas giant star have been chosen as a rest place. The clock indicated the end of the Ariana’s rescue mission, exactly 31557600 seconds after her capture she was free. I now hoped she will open her eyes again. = Recovery <recovery> #emph[#strong[Aria’s POV, TW: mention of death, mention of menstruation, just after the chapter 6]] And then everything went black, then white, then purple, and so on and so forth for all the colours of the rainbow, eventually all of it calmed down and colours were everywhere in my vision, I heard voices but could not understand what they were saying nor who talked, I never died before, but I’m quite sure that was not how dying should feel. I felt heavy and a few seconds later I was asleep. #middle - "She’s alive! She’s alive! Professor! She’s ALIVE! We did it! We saved her!" I barely heard, I was still feeling heavy, but I managed to open my eyes. My voice refused to cooperate with me, but I should have made a bit of noise because a few minutes later I saw someone I thought I would never see again in my life. #emph[Syl. Syl was here.] That was incredible. Was that really them? I am dead and is this a last vision before the eternal darkness ? No no I heard the slight beep of a heart monitor, I think I was alive! And more than that I was awake! And Syl was there! They seemed a little different but given two years passed I think it was fair. I tried to move, to hug them, to tell them I missed them, I wanted to rebuild the world with them. My excitement was so strong that I heard the heart monitor accelerating its beeping. - "Hello there general Ariana" they said softly with their trademark smile while gently stroking my hair, it felt real, I was becoming more and more convinced it was real by the minutes. I was saved, no longer trapped in Union Central, no longer alone, no longer far from my chosen family, I was with my lover, my best friend, my life, my happiness, if only I had the energy to kiss them, I wanted them so badly, I waited for this moment for two years, they managed to save me just before the end. - "H...e...llo" I barely succeeded to say before my voice really shut down for good. But that’s all Sylvia needed to know I was in there, I was different yes, two years of near-torture do that to you, but I was still their girlfriend, they was still my partner and those two years of longing only strengthened our love. Syl just looked at me, happy, a smile on their face, still playing with my hair, still gently petting my head and caressing my cheeks, and I just rest there - not that I had any choice - basking into the raw affection I felt for them. We were reunited, and nothing would ever separate us ever again, I will make sure of that. #middle A few minutes or hours later, my notion of time was a bit broken by the painkillers, the other medications, and my pure love for the person who never ever left my bedside, I didn’t even take the time to analyze my surrounding too engrossed by the sheer beauty of the person I could proudly call my partner, the Uin’s and Aarin entered the room, all of them looked almost as happy and relieved as Sylvia was, I think they really do missed me, to be honest I missed them a lot too in those two years of custody. - "Hey Ariana" gently said Aarin, "You’re safe now Eleanor stabilized you and your body is regenerating itself with the help of the ship’s medical bay field. You should be able to walk in a day or so and sit in a few hours. We almost lost you, sorry for the rude transportation, we kinda were on a hurry. Anyway it doesn’t matter now you’re safe, and we have you" I’ll let you to the rest of the team, but I’ll come right back when you’ll wake up again, he smiled softly. I think he learned a lot in the empathy department in those two years, I’m pretty sure he would not randomly enter the changing room now, or maybe in a cat form, I smiled happy I’m okay. - "Hey baby girl how are you? I must say you’re really beautiful now this alien-HRT really did wonders to you" at that I blushed as I remembered my menarche, it was a really weird thing to experience, but it also meant that my uterus was fully functional now and this thought sent in me a wave of… rightness? Euphoria? Happiness? All of the above? Not that other trans women or even cis women without uterus were not women, no, that’s bullshit and a very UK thing to say, nevertheless I always dreamed of having children, so it felt #emph[just right.] Unable to speak for now I just glanced at my lover, and they answered their parent’s question. My lover it felt so right to referring to them with this name, I’m so happy it happened, it took two years of torture but at last we were reunited, and stronger than ever, if our relationship survived a two years hiatus separated with more than eighty light years away it could survive anything. Just before the drugs took effect and as I peacefully slipped into a restful slumber, my four guardian angels looking upon me. A last thought came to me, who’s Eleanor? #middle I awoke a few hours later at Aarin entering the med bay with food, as he said earlier I was able to sit somewhat comfortably in the hospital bed they installed for me. I knew he was here alone to talk to me about some things in the Union our other companions should not learn now, for their safety and mental health more than purely to keep secret from them. - "Hello professor" I said, surprised at my voice, it fully healed in my sleep and was as beautiful as before, #emph[my] soft high voice, I guess their technological leap on us also extends at healthcare, it should have been obvious to me given the unusual transition I had after all. - "Hello Ariana, I see you’re feeling better, I’m sorry it took us so long to save you, I will explain to you why it took so long and how we saved you as the two answers are linked, but later, and with the others, I am here to debrief you on what happened, what have you learned and to inform you on our current situation and how we will proceed later on." I nodded, I knew it was coming of course not only I learned a lot of information about the Union, but I was also now a permanent citizen of the Union, as such I had access to a lot of insider knowledge during my time on Union Central, knowledge Aarin could not have accessed as he was banned from the network. But I couldn’t help from being curious, how on earth they were able to jump right on top of Union Central City’s University District, without being detected by the FTL sensors of the planet-wide defense system and more importantly just how they were able to outrun military ship twenty years younger than this old (but still functional) vessel without any defensive capabilities. I’m sure all of these questions will have answers, but now was not the time, it was debriefing. #middle - "I see, it was Nass’ strike force itself who captured you, they really took me as a serious threat to send the admiral ship of the Union Navy and its captain as far as three months of FTL away from Union Central and the Fleet. I wonder why they are so obsessed with me… Taking some locals under our wings is certainly not common, but it has happened before." Aarin said, lost in his thought. We just finished our two hours long debrief of the last two years, he was pleasantly surprised at my rank in the University, it was usually a hard one to achieve, creating a whole new department was a big undertaking he said, this cemented our idea that Earth was special to the Union, they may have taken a huge liking for our planet, or our people, or, more frighteningly, of something else entirely. I however, was thinking at full speed, as a Union’s citizen I was now a galaxy wide fugitive, almost as researched as Aarin himself, and we both risked death penalties if we were ever captured. Hopefully it would not happen before we clear up the misunderstanding or discover what exactly the Union is up to with Earth. Aarin and I decided this goal was the must important thing we must unravel before we could even resume our normal lives. Comparing my and his story, we decided however that Sylvia and their parents were safe, now he was sure we were spotted on Europa we figured out, they were not even thought of participating into any illegal activities with us. Also, I had my answer as who was Eleanor, she’s the ship’s AI! Her name is so cute to be honest! She chose it while speaking with Sylvia, they was insisting of her picking up a name for herself as they believed she was her own person. She also came with the idea of informally naming the ship after me. Now that my rescue was finished and a success the formal and informal name of our ship and crew were officially "Rogue Science Ship I". And to be honest it rocked! The initials RSS reminded me of a mod for an old game called Kerbal Space Program where ironically you were simulating a space agency, the mod was eventually ported for the third version of the game Kerbal Space Program 3 published in late 2035. This game was far better than another space simulation called Star Citizen which’ publication was canceled in 2038 at the alpha 30.01. But I’m rambling Aarin said I should go back to sleep, and after I could meet my lover again! #middle My beauty sleep slept, and a pad changed, - I think I’ll never gonna habituate myself on how to use this - I managed to walk to the lounge were Sylvia’s and their parents were playing a card game and Aarin was reading what looked like a boring technical manual, I sat on the couch as my energy and stamina were still really limited - which is not surprising given that I didn’t leave my apartment for the last few months - and looked by the window. And what I saw surprised me to say the least. I gasped audibly enough for all the people on the room to turn to see me and immediately Sylvia abandoned her game to come snuggling with me and calming me, but I was calm, I just was surprised! We were in Alpha Century, a system really close to Earth which means we traveled at least eighty light years, and it translated to almost three months of travel, have I really slept this long after the transportation? Or did the regeneration took a lot more time than I thought. As if he was reading my mind Aarin came close to me and said - "Yes I know this is Alpha Centaury - congrats on the learning by the way - but no, we did not travel as long as you think we have. In fact, we left Union Central a little less than twenty-four hours ago, we made the journey in a day." I sat, dumbfounded, this assertion was simply impossible, and I knew what I was talking about! I spent the last two years learning as much as I could, and the fastest ship of the Navy could make the journey in two months and a week, provided they could rest at least two weeks at the arrival to fix the damage the overcharge of the drive would cause. And this ship is twenty-years old! There’s no way they made the journey in twenty-four hours! Sylvia must have sensed how I felt because they giggled, snuggled a bit more with me, kissed me on my forehead and said - "You’re forgetting your partner is a propulsion genius, and their dad is the best propulsion engineer earth has to offer! Together with the Union’s theories personified by our all-mighty professor just here the impossible became possible, we transcended space, we achieved FTFTL! Faster than FTL!!!" my partner was absolutely ecstatic. - "I want to hear the story, but first, no, FTFTL is a dumb name baby" I said, and as that the entire room with the notable exclusion of Sylvia burst into laughter, the latter though just pouted, I used my super-power of kissing them to make that pout disappear. I’m so great sometimes #middle - "Ok so let me summarize" they all nodded. "You spent the last two years on this planet testing various methods and finally discovering one to transcend space, you dealt with sketchy unknown crystal dealers" Aarin nodded "You purchased neutron-star plated metal whatever is that thing" Sylvia nodded "You calculated theoretical numbers and were just one error away from making the entire Proxima system explode" Sylvia’s mom and Eleanor made a grunt of agreement "And finally you just rushed in front of a supernova to craft theoretical super-space whatever crystals" Sylvia’s dad agreed. "And you used that to stabilize a black-hole, accelerate into it with the FTL drive to lose a dimension, all of this while hoping the integrity field protects you of becoming two-dimensional pancakes and with the hope you were exactly where you wanted to when you came back to normal space and not billions of light years in the wrong direction? All of that, just for me" they all agreed at the same time, smiling, clearly proud of themselves, and they were right! I sighed. "Let me get straight, well I’m not, so let me get gay" Sylvia chuckled at this joke in this context "firstly thanks you, you literally revolutionized science to save me from a boring and depressing life being a University professor without my lover at my side" they smiled, but I would not let them escape this situation this easily. "However, this was the dumbest idea and plan I ever heard, this could have had disastrous consequences, not just for you but for the lives of billions of lives around this system who could have died in the coming years if a powerful burst of gamma rays randomly shot itself in their direction because your experiment made the Proxima system explode." They looked a down. "And that’s without counting the fact that you could have die so many times following this stupid plan this was really a stupid idea, not that it surprise me coming from Aarin, Sylvia and their dad, but I’m a little disappointed in you" I said alternatively looking between Eleanor and Sylvia’s mom. "But thanks you for saving me, let’s never do a thing that stupid anytime soon, and to be honest, multiplying by thirty the maximum speed of the vessel without overwhelmingly increasing fuel consumption is a genius move, I’m proud of you’all." I finished smiling warmly at them. #middle #emph[#strong[Aarin’s POV, A few hours later]] We were still in the lounge, all of us needed a bit of rest following the dramatic events of what unfolded, we managed to save her, that’s true, but we nearly lost her in the process, it was really close, neither she not I decided to tell them the real reason of her near-death, we let them know she was non-acclimated to the Union Central City life, and it caused her a depression but nothing more than that. Her near-death was - as far as they knew - caused by the rapid transportation system having interference with the residual black matter radiation coming from the black hole. It was complete bull-shit obviously as the dark-matter hypothesis has been disproved by the Union scientists hundreds of years ago, but it was still a popular theory on earth, our three companion gobbled up this explanation. Sylvia likely would soon learn the fact that it was a bullshit explanation if they didn’t have already, but I’m sure Aria would already have told them the truth by then. The truth, itself, was much more frightening, she nearly killed herself due to her depression, she took a huge amount of anxiety medication, powerful one from the Union pharmacies, an amount she knew would kill her, we just were lucky to arrive at the right time, a few hours later, and we would have transported a cadaver into our med bay. While I was thinking the activity resumed around me, Sylvia’s parents were playing a game of card, one I forgot the name of, it was a two player game popular on Earth, or at least was popular as one point in the past. Sylvia and their lover were cuddling and gently talking to each others, talking just like nothing had happened. The calm was disturbed by a huge rumbling on the ship, Sylvia and their lover recognized it too it was the emergency jump, but no one activated it, it was not Eleanor as she was in front of me - her hologram was to be honest we did not have the time to design her a mechanical body yet - and she seemed as troubled as myself. A few seconds ago the tug disappear and Eleanor said - "The ship just automatically perform an emergency jump, we’re currently in a stationary position about 1 light years from our last known position" she said looking puzzled - "Why?" I asked, trying not to sound frightened by the ship’s behaviour; it never happened before, the ship should not just jump itself without any command by the operator or the ship’s AI! - "Processing" said Eleanor now completely panicked, I didn’t know AIs could be this panicked, this must be a huge problem. A few minutes later she finally finished her calculations, - "I will project a holographic map of the systems in a 200 lights years radius" Just as the map showed, all of our eyes just became balloon almost instantly. Proxima’s system just exploded in a supernova, something that should not be possible due to its size. But it was not only Proxima’s system. Twelve systems in the 200 light year radius sphere projected were missing, all of them turned into supernovae. In them, three were Union’s members. #emph[#strong[This was the first instances of events which starts what would later be known as \"The Greats Explosions\"]] = The Voyage Home <the-voyage-home> #emph[#strong[Aria’s POV]] We were sitting there for more than an hour now, waiting for, #emph[something], to happen. Eleanor was busy calculating the consequences for the nearby systems. Only the Sol system is known to bear life in the surrounding one, so we only had to calculate how much energy the explosion caused and what we can do to protect Earth. Which should be touched in about 4 to 5 years from now due to the speed at which the energy was released. Thanks god, this star in particular was low on time crystals concentration, the last thing we needed was an FTL gamma shock wave in Earth’s direction. - \"Aria, do you want some tea? Mint.\" softly said Sarah, Sylvia’s mom, beside me, she should have been making tea when I was thinking about the situation, unfortunately, there was nothing I could do, but I couldn’t help myself from #emph[thinking]. - \"Yes please\" I smiled, taking the hot mug of tea she tended to me, and resume my thinking, eleven other systems had gone supernovae a few minutes apart. Of course, it was a few #emph[FTL minutes] apart, the stars themselves were hundreds of light years away. Something wasn’t quite right though, and we couldn’t just go there and investigate we were highly researched criminals in the eyes of the Union from now on #middle A sound resonated in the mess and lounge area, indicating Eleanor finished the calculations, - \"The majority of the gamma emission is on the other side of Earth. The total energy released in the direction of Earth is enough to cause some high-atmospheric perturbations. I estimated the light trace to be visible only at night.\" We all were instantly relieved, Earth would not fry in the sheer amount of energy released, that was to be expected due to the relative small size of the system’s stars, but it was a trinary system, nothing could be sure before measuring and computing the simulation. I was getting puzzled, and I think Aarin was becoming frustrated too, judging by his expression, and then he spoke, - \"We need to investigate.\" All of our eyes went #emph[huge]. It was weird this many stars exploded roughly simultaneously, given that the average star’s life-span is a few billions years, but it was just a coincidence. Aarin, however, then said something that had my blood turned instantly cold as I forgot about this detail. \"A star like Proxima’s should not turn into a supernova, a nova at best and even that is not sure, they were simple red dwarf stars not regular stars like your one or even super-giant stars.\" #middle - \"First we need to dump my parents back home, you said it Earth is clear of danger, as of Eleanor she can’t leave the ship, you and Aria are researched Union’s citizen, and I’m not staying anywhere else than in my lover’s embrace.\" Said my lover, as determined as ever, so much that when their parents tried to argue they could come with us, they refused stating the level of danger of the mission, my and Aarin’s researched status, and a glare to their parents. That makes sense we would likely be out there in the stars for months trying to investigate what happened with those stars, Sarah and her husband have things to do on Earth, and they need to update our status, after two years on Union Central I’m likely dead in the papers. They nodded, and we all scrambled back to the bridge and initiated the jump back home. #middle A few minutes – I would never habituate myself to this new drive we made the jump between Wolf 359 and Earth in mere #emph[minutes] a more than seven light years jump! – later we activated the cloaking and phase devices of the ship to avoid any kind of detection by the surface, made the little trip to the shuttle’s bay and strapped ourselves in the main shuttle. Eleanor came by downloading herself in place of the regular shuttle AI. She left one of her subroutines in the ship to monitor her while we were away. Once again I was piloting. - \"You’re fairly good at piloting this shuttle Aria! Even better than I remembered! Did you take some flying course back on Union Central while we were developing a drive to save you?\" My lover said, a grin on their face and their arm around my #emph[admittedly small] waist and their head buried in my hair. - \"No, but if you continue clinging to me, I’ll land us on London airfield instead of New Paris, so quiet partner!\" I said grinning and half hugging them while still piloting the shuttle. I think I heard Sarah whispering something about \"cute couple\" and \"wedding\" to her husband, but I was not sure, and I had a shuttle to #emph[safely] land after all. #middle Safely landed on the outskirts of New Paris and the protection activated, we wandered in downtown, I knew it only been two years, but those years felt like a lifespan to me. The never ending buzzing of Union Central shuttles was gone, replaced by the slight sound of birds and drones chilling around like nothing happened. The endless column of students running (or rolling, or whatever their species was known to) to be on time for their first class of the day at Union Central University were nowhere to be seen as we passed by the New Paris University campus and saw the lazy students casually and slowly walk towards their respective class. However how alien the situation seemed to me – which was pretty ironic considering I was #emph[home] – I was surprised by the plain-old familiarity I still had with the city, it made sense after all, I lived here for about a decade, almost since its foundation, the skyline of skyscrapers was the same as it always was, the Earth sky was flawlessly blue, only for a cloud of to appear here and there. This city, this planet, was #emph[my home], I was suddenly feeling angry towards the Union, they kept me in their place for so long! Separated from my other half, my chosen family, and even Aarin who I came to love. I was now obliged to live as a fugitive, always running from planet to planet, hopping from system to system, hiding from the Union, a life of running, a life as a renegade, without ever settling home with my kind. Sylvia, my sunshine on this dark world, fortunately saw my mood and clung a bit more to me, I was once again reminded of the height difference that now existed between us, I was really tiny compared to my old body and to them. This fact alone warmed me a bit, then they held me by my waist and slipped an arm protectively around me, reducing the distance between us to virtually nothing. This was heaven, and I relaxed, even if I end up as a fugitive all my life, I would have the wonderful and beautiful Sylvia with me, Aarin would also be there, I would not be alone. Never again. #block[ $ast.basic$~$ast.basic$~$ast.basic$ ] I basked in the embrace and lost the meaning of time, just walking, hugging, exchanging the casual glance at Sylvia’s parents, and hearing them giggling each time Sylvia kissed me, held me and just toyed with me, I #emph[loved] that! I was exactly the right shape for my understanding of myself and Sylvia knew exactly how to handle me! Those years of #emph[lesbian training] proved to be efficient after all. We kept on walking just admiring the city and the neighbourhood, all of us were on another planet or ship for more than two years now, so it was new for all of us. Fortunately Sylvia’s parents had kept contact and were on unpaid leave, they could just integrate back their lives just as nothing happened, and working to sooth things with the University for Sylvia and figuring out the issue of my... death. Eventually as I was staring into the beautiful eyes of my stunning partner, I heard a voice, my brain recognized it but didn’t directly connect the dot, calling out to Sarah who stopped and put my partner and me behind her in a protective maneuver. It was then I saw the face of the voice calling out and my eyes went huge as my brain finally connected the dots. The voice was my mother’s. #middle I did not know what to do. Running away? Calling her out ? Make myself as small as possible ? In the end my brain did not let me decide, I fell on my butt on the cold floor of the suburb’s streets. Sylvia came immediately to my rescue and hugged me so tightly I was not sure if breathing was still an option. But the support was much needed now. My mother, the woman that despite birthing and nurturing me for years, abandoned me when my father and her decided my gender was their business and not mine. Sylvia gently helped me to sit more comfortably than I was a few seconds ago, and we decided to let the talking between the adult. I was not sure that I could even talk to be honest. - \"Sarah! You’re here! And with your husband too! That’s your daughter behind you? Hi Sylvia! You remember me?\" she started and every one of us cringed at the same time, she managed to misgender Sylvia in less than ten seconds. \"You’re finally back! Geez it’s been so long! Like two years now, time fly heh.\" She surprisingly ended on a sad note, two years ago was the moment her \"son\" was declared dead. She may have abandoned me before it happened but maybe that my death had an impact on her Sarah’s husband was about to answer, he probably thought of a good way to answer this and flee fast to avoid detection, I was confident she wouldn’t recognize me, fortunately, to be honest I lost more than twenty centimeters and thirty kilos, my frame is completely different, my voice is completely different, my face still looks like mine, but she should just be confused and should not connect me with who I am. Just as I thought that her eyes fell on Aarin’s - \"Oh! He’s handsome! He’s Sylvia’s boyfriend, isn’t he? Oh! She scored well with this one! I was sure her lesbian... thing was just a phase\" she spat the term lesbian, and with that all my, admittedly small, hopes for a better birth mom vanished as she once again showed her bigotry. To be honest she #emph[knew] Sylvia was a lesbian, and they was clinging to me soothing me, stroking my hair, kissing me, whispering to me, kissing me again, all while Aarin was a few metres away analyzing the situation. How can she think in a non-bigoted way that he was their #emph[boyfriend]? I was small but not invisible! But when she stared at me, I kinda wanted to be invisible. Her glare was unsettling to say the least, as if she tried to undress me with her eye. She was likely trying to figure out who is the new girl who shared a resemblance to her deceased son. Adding to the fact she knew I was transgender and likely to be transitioning because I was not living with them anymore and as a bigoted cisgender person is likely to be uneducated on HRT and the effect of it I was becoming really frightened by the fact that she #emph[could] guess who I was, and I would have to be convincing. And then yes, she connected the dot, the textbook comic reaction with big eyes and mouth opening and closing in a seemingly endless cycle, I said nothing still clinging to my partner while I watched my in-laws coming to the same realisation as I had, even Aarin seemed ready to intervene if a situation that would make us or more specially me, in immediate danger. I knew he was very protective of me and it reassured me knowing I had someone quite intelligent and strong to rely on. We all watched her, as she carefully tried to approach me, only to be stopped by Sarah and her husband, but they let her close to me when I signaled it was okay. - \"Art– Ariana? Is that you? You are alive? Please tell me you’re alive\" and then the mask fell. She wasn’t only using my name – the real one – but she was glad I was alive? She abandoned me! But maybe she knew it was wrong? Either way her mask fell, revealing the sadness she felt and the hurting she lived as she looked at me with the purest smile ever possible, a smile of a mother, a smile of a loving parent to their child. She didn’t need answers she knew the answer, but I nodded, I nodded to cement the fact that I had my mother, I don’t care for my father, but my mother is here for me. As the second I nodded she embraced me tightly, Sylvia let her take me, and she began gently whispering to me while starting to cry - \"I’m sorry Ariana, I’m so sorry I let him do that to you, I’m so glad you’re okay, I’m so glad. I’m sorry, I know you were hurting, you’re my child, but I didn’t know how to react back then, I’m still lost right now, but what I did was wrong, so wrong I’m sorry you had to face that yourself, alone\" She continued her speech for a few minutes, all of us were too stunned to speak, of the millions of ways this could have happened this one was not the one we would have thought of first. - \"Yes, it’s me.\" I managed to say, crying loudly, in my new voice my mother couldn’t miss. She let go of me and Sylvia immediately came back and hugged me - \"Oh my god Ariana you’re beautiful, I’m sorry I should have known this was possible, you look so... stunning\" I knew she was trying not to say #emph[normal] and thanked her for the attention. \"And your voice it was so... soft and high and #emph[beautiful], you take more after me now! Your facial structure have changed just slightly that’s incredible. I’m so sorry I was like that back then I would have love seeing you becoming the beautiful young woman I have before me\" Really not what we expected, to say the least. - \"Also, ma’am\" said Sylvia, capitalising on this to say what they had to say \"I’m not a girl, I’m non-binary, I use they/them, Sylvia is still fine\" we all watched her as she genuinely tried to take the information and process it, in the end she gave the tinniest of nod and Sylvia continued \"also i’m still really much a lesbian, I do agree with you on your daughter though, she #emph[is] beautiful, and so much more, that’s why I’m proud she is my girlfriend\" they said grinning. I was so glad to have them as my partner and I clung a bit more in the hug to feel their warmth. \"Lastly, you said you were sad you didn’t get to see your daughter becoming the woman she now is, that’s right, but you can decide to see the wonderful woman she will continue to be you just have to stay in her life. To love her for what she is, a woman, a girl, your daughter, but more importantly her own human being capable of doing her own decision\" she finished defensively, hugging me and holding me by my waist, earning a \"yelp!\" out of me. My mother smiled, she #emph[smiled] I never saw her smiling before! That was new! I need to know what happened in those years now. - \"I will try my best, I swear, I’m not gonna let anything else forcing me out of my daughter’s life now. I learned from my mistakes.\" #middle I think I never hugged my mother this much since the first grade. We exchanged communication informations (Aarin setted up some FTL connected email adresses thing and connected it to the Internet with a hidden relay in orbit) for us to communicate about our situation, her still living with dad, even if I’m quite sure she will leave him, and me because after our little tour I’ll leave on a god know how long mission to investigate supernovae and avoid the Union battleship armed with states of the art canons and other frightening high-tech weapons our ship currently do not have. We have a plan to source and build some weapons but for now we’re heavily counting on our raw speed, which is dangerous in case of an attack as a jump have a minimal time necessary to prepare it safely, and as they can target our field generator rendering us unable to enter the sub-dimensionnal space of the black-hole without being reduced as a piece of paper. The University passed we decided to head to Sarah’s home to end the tour, and to drop them before leaving to our investigation of weird supernovae, maybe we could win a Union equivalent of a Nobel Prize if we discover why so many stars turned supernovae? Well to be honest I think when Aarin and Sylvia would get one for their multidimensional FTL – it is the final name we decided to give it the full name of the discovery was, sub-spaced multidimensional field-stabilised black-hole-generated Faster Than Light Travel, which is a mouthful and can be shortened to multidimensional FTL or even FTL – so this one should be for me! Before that we actually needed to discover the #emph[why] though. And this would be later as we arrived at Uin’s home. #middle - \"Bye Sarah, be well, and we should be back in no time! Thank you for the help with the #emph[deceased] situation.\" I hugged for the last time Sarah, after an hour-long emotional goodbye session. We used our short range personal transporters to travel back to the shuttle, I let Eleanor pilot this time, I was seriously tired after all this walking and emotional breakdown. But I was really happy to have my mother back. I decided to check the little box Sarah’s gifted me saying that I should do that in private, the others were busy in the cockpit so I sat on the couch and opened it #block[ #emph[Dear Ariana, \ I want you to have that, it is a ring used to propose to someone you love, \ It has a nice name in French : #strong[bague de fiançailles] \ It is in my family for generations and I want you to have it \ Love, Sarah.] ] Oh! How cute is that! She gave me a ring to propose! But why?. I decided to check the other side of the paper to find more instruction to follow #block[ #emph[It’s to propose to Sylvia you silly girl!] ] = The (not so) Final Frontier <the-not-so-final-frontier> #emph[#strong[Sylvia’s POV]] It was finally official, we just left the Sol system, I had recognized the box my mother gifted to Ariana and I chuckled at the memory of this, if she trusted #emph[Ariana] to propose to me first I think we will be dead long before we would be married. But yeah to be honest we had other things to think about, like figuring out why twelve systems blew up. Eleanor was closely monitoring the data coming back from our probes, and we hacked some probe data networks of the Union to gather information for us. We really had to solve this little space mystery, it was probably just a cosmic coincidence, a bigger thing might was up to, and our scientific curiosity was picked. We were chilling out in the mess, Aarin and Ariana were drawing a map of the system which exploded while Eleanor and I were supposed to find a path of safe place to hide from the Union. Unfortunately we could not just warp for 3 months and enjoy being years of travels from the Union. Firstly we had to investigate but more importantly this ship used deuterium as its primary source of fuel for the nuclear reactor, even if we could cramp up the subjectivity space ratio to store a lot of it we still need to find non-Union sources of fuel. Which was difficult since the Union was the most powerful political entity in charted space. Virtually every non-Unionized species had a peace treaty with it and used its infrastructure. So we were not only researched in The Union but in a one hundred light year radius, which made getting fuel and energy really difficult. Fortunately, Aarin still had contacts in the sector. About the subjective space, I was right with my first guess, a force field compact the space between atoms kernel and electrons, even a few percents was enough to gain a lot of space. The cabins’ space was compacted by 2 percents, the most a human – or any biological lives for that matter – can withstand is about five percents. The engine’s room was compacted by a whopping ninety percents. It saved a lot of space with the drive installed in this vessel being a few hundreds metres wide, twenty metres long and ten metres tall, and all of this was compacted in a room with an absolute size of 10 by 10 by 5 metres. The advantages were obvious, however it forced every refit or reparation of the ship to be performed on a station or on ground, ship opened and with specific tools to extract the drive. I heard some ships in the Union had non-compressed drive, but that forced them to be miniscule, like surveys ships or probes. Another massive downside of this technology is that in emergency cases if the compressing field fails, and the back-up fails too, the ship with literally rips itself open rendering the ship completely unsalvageable. If you’re lucky it happens on ground, if you’re less it happens in space, you would only have mere microseconds to transport yourself to the emergency shuttles. Without counting the development of the technology there has been a disastrous incident twenty years ago destroying a ship of our ship’s class and her crew a few light years away from Union Central. The backup systems were installed after this incident to avoid it repeating. #middle We finally stopped in a system neighbour to one of which exploded, J24. This was one of the farthest away from Union Central, we possibly had a few weeks of investigation to us before the first Union Task Force arrived. We discussed some ideas to investigate the Union’s system touched by the events, however this proved to be risked given the age of our ship, our stealth tech installed here were twenty years old, we would be in that system like a deer in the headlight, not particularly subtle for a rogue ship housing two highly researched criminals. The ship was stationed in a high stellar orbit, we were waiting for Eleanor to finish her calculations on if and when the J24 system will be safe to explore, while we were in a hurry and eager to discover the reasons behind this phenomenum Aarin insisted on calculating a safe range, just to be sure, he stated we couldn’t be more sure with a huge space explosion of a litteral #emph[star]. Ariana, my lover, was looking thoughtful, she must think of this system. The system we were currently in that is. Even in that state and thinking about a thousand, probably grim, things she looked lovely, not that she didn’t before, but I can see the last effects of the super-HRT (she rejected my proposal on naming it \"Alien Enhanced Hormone Replacement Therapy\" stating it as a \"mouthful\" and \"too-technical\" and preferred referring at it as \"super-HRT\" but to be honest, I must say the effects are spectacular, maybe it deserves the name after all) well to be more precise I did a bit more than just #emph[seeing] the effects, it really was leaps away from our technology and current healthcare, and I can say she enjoyed it a lot, who could blame her? I certainly did not, #emph[I] enjoyed her a lot. I looked at her, smiling, watched as she was gently repositioning herself on the couch picking her book from the coffee table, one of which she had back home it seemed, a cute kid story about two princesses in love fighting their father, and in the end their respective fathers fall in love with each others, she really loved that story, I saw her reading it at least a dozen times and each time she looks as into it, now though with the changes she really looked adorable, I wanted to cuddle to her and losing the concept of time itself, isolating ourselves from the surrounding world, just her, and me, and an infinite embrace. Unfortunately we had to explore that stellar system. The cuddles must wait! #middle The exploration of the system itself was a non-event, being one light years away from the site of the disaster it basks in a morbid harmony, in about a year this system will be drenched in particles and gamma rays from the near former-star, being one of the heaviest that exploded this one delivered a massive quantity of energy, vastly overwhelming the capacity of this star’s magnetic sphere to drive particle away, the system will be sterilized, every bit of life that may or may not exist in the tiniest places of these planets will fry away at the sheer power of these rays. Only life preserved under vast amounts of water (liquid or solid) will stand a chance of survival. A survival in a changed world, a massive and sudden change in the life distribution. Such events were still object of research and are suspected of having caused massive extinction in Earth’s past. I think scientists in a few hundred thousands to millions years will marvel at the opportunity of studying the resurgence of life in systems ravaged by nearby supernovae. If the Union or any sentient life outlive the current crisis, that is. #middle - \"The system is safe for exploration, please keep your EV suits on with the personal particle and gamma rays filters, you should also use the energy shield of the shuttle\" Eleanor announced, a few hours later, during which I stole a hug, or two, or dozens I really didn’t count them, to Ariana, on the speaker of the lounge. A few minutes later we were strapping ourselves in the shuttle for the second time that day, hoping to find something more interesting than the few star dust we found earlier. Once again Ariana was piloting, Eleanor, still in her weird blob holographic shape was co-piloting so Aarin and I could be at our best trying to extract the last bit of data lying around in that mess that was once a system. #middle #emph[#strong[Ariana’s POV, in the shuttle]] I was installing myself in the shuttle, ever adjusting the seat to frame my newest tiniest frame, I was cute, but it was really bothersome sometimes, I guess every physical form has its downsides, even non-physical forms as Eleanor could download herself practically everywhere but was limited to interact with thing that was connected to her and her system. Which was a lot of things to be fair, but I wondered if the implementation of a real Union-wide internet was not the answer to a lot of things, communication speeds were a lot faster than FTL, even our multidimensional FTL was far outsped by the @uftlcp the fact that #emph[nobody] in the Union thought of creating space networks of terminal implementing the UFTLCP to create a real Faster Than Light Communication Internet baffles me. Sure there are some networks available here and there, such as the Union Central System Faster Than Light Communication Network (UCSFTLCN) spanning across the system of Union Central, or the Union’s Universities Space Communication Network connecting the big universities of the Union, but they’re not interconnected, and nothing in the protocol fundamentally forbid it, they just #emph[didn’t think of it.] Anyway my point is if such a network existed, travel by entities such as Eleanor would be so fast that regular space travel to fixed points would be instantly a thing of the past. I wondered briefly if implementing a protocol to pass a transport signal over the UFTLCP would be possible, but if such a thing was possible surely Union’s scientist already thought of it right? They couldn’t just #emph[miss] something like that? I really should talk to Sylvia and Aarin someday, they already revolutionized science once why not doing it #emph[twice?] Wondering about making space travel obsolete done, I started the reactor to power up the engines and made a little pre-flight speech to my fellow friends (and one more-than-friend). - \"Ok we are going to penetrate a somewhat #emph[tortured] region of space, one of the most powerful thing ever just happened there, and we need to be vigilant, as such, I will be piloting, you can ask me to go to a certain place or another, but my primary mission will be to keep us alive, if I sense a danger or the need to I jump us back here as soon as possible\". They all nodded, even Eleanor made a blobby-movement I associated with being a nod of approval. \"Good, enjoy the ride, I, Ariana will be your captain, we are assisted of yours truly Eleanor, co-pilot on this flight of Aria Spaceways, do not forget your jumper, as the temperature of our destination is a bit chilly, about 0 Kelvin, a storm just passed there I’d happily advise you to put on your seatbelts, but this shuttle does not implement this feature, welcome aboard.\". I said, role-playing a bit the captain persona, when the mood settled and everyone seemed ready I activated the miniscule FTL drive – but enough to power this shuttle – and announced \"Once, again thanks for choosing Aria Spaceways, the ETA is 3 hours, 43 minutes and 21 seconds, please enjoy the ride and do not hesitate to serve yourself a drink.\" I winked at them. #middle - \"Dropping out of FTL\" announced Eleanor #emph[exactly] 3 hours, 43 minutes, and #emph[23 seconds] later, \"I’m sorry for my earlier ETA computation I had not taken a variable into account, my sincere apologize\" she said, sounding, down, maybe ? I forgot she was an AI, she must think an error of #emph[one second] in a 4 hours trip was a big deal, while us just rounded the 3 hours forty-something minutes to four hours, cultural differences I guess. As we entered into the system my screen behaved weirdly, something I could only describe as a glitch was on the FTL radar, it should only detect FTL movements in the area, however we were in the only ship rated to move faster than light in that sector. That couldn’t be a Union’s ship, we were far too isolated from Union Central, it should take them weeks to come here, and that was if they decided exploring this system was worth it, there was touched system in the Union’s direct territory after all. So the fact the radar detected an activity was... unsettling, - \"Aarin, I detect FTL activity on the radar somewhere in that system, it was brief, and like a glitch if you see what I mean? Anyway I can’t detect it anymore so whatever it was left the system.\" He looked thoughtful a minute then had a \"Eureka!\"-like face and just told me it should be bit flips from the particle, that made sense, our computers were hardened of course but with the power and energy of some of these particle one might have been able to enter the system and mess around with the computer, causing a glitch in the RADAR screen, this made sense, but something wasn’t quite right for me the shield should stop most of the particle, even if to be fair we never used FTL in such a system before, I wouldn’t risk it if we could avoid it. This debate settled for now, I gently took the command and pushed the button to disable the FTL shield, while it protected us from being vaporized by a particle of space dust lying around it also stopped us from seeing around, and we were all eager to admire the aftermaths of such an event. And saying the view was breathtaking was a huge understatement. Colours where #emph[everywhere] we were only a few light seconds away from it, and could see almost the entire thing. It was wonderful, beautiful, magnificent. Long, rainbow coloured, paths of various gases and elements, generated by the cataclysmic yet beautiful event, were everywhere, in pattern only randomness could generate because of the sheer impossibility of the human mind to come up with such an intricate and complex design. These paths let place to sparks of light here and there, casually blinking in all their glory, in thousands if not millions of different shades, shades no one ever heard of, new one popping in the background where some just vanished, stopping from the last time it would ever blink. All of this just before our eyes, we were watching this work of art with our eyes, in person, nobody ever did that. What could only be described as cosmic rain by my poor human brain was falling on the system, I shut the computer down to avoid the automatic detection to be triggered as even our computer-sentient AI was staring, admiring the show we would be the only one to see in our generation, being dozens of light years away from Union Central. It was like a living thing, clouds of purple dust collapsing into another made of pink particle, creating a new, gracefully moving, cloud of purple mixed with pink, ever mixing, collapsing, forming, twisting, moving, separating and so on and so forth. This was mesmerizing, fascinating, Then the computer beeped loudly, too loudly, and the automatic pilot moved the shuttle performing an evading maneuver at the last second before the shuttle would have been obligated to attend a blind date with an asteroid, right, I disabled the shield, this seemed to have woken the crew up as they were slowly walking to their assigned stations, not without a glance or two at the coloured living-like structure a few light-second away from us. We were lucky the \"glass\" (they were actually made of an advanced metal alloy rendering it transparent to the visual spectrum but as strong as the hull and protecting the crew of radiation, gamma rays x-rays, and other nasty things the Universe like to throw at us to remember who’s the boss out there, the only reason it was only in certain places was because psychologically some Union species did not support the fact of living in a transparent ship) was protecting our eyes because we – with the notable exception of Eleanor obviously – would be blind by now. Or already fried by the radioactivity. #middle The exploration was going on slowly, some part of this system were difficult to access or down-right impossible if we wanted to come back alive to the ship. Like I said I piloted, the system was far calmer than what we expected, allowing Eleanor to be free to research for eventual interesting thing we could analyse here or back on the ship. This was during one of those checks that Sylvia asked me to approach an innocent-looking cloud of particle not far away, I dutifully complied, they thanked me with a little kiss before joining their station to analyze it, what that useless cloud have done to be more interesting than their #emph[girlfriend] ! #middle It turned out that cloud #emph[was interesting], Aarin even shot a \"Fascinating!\" when he saw the result on Sylvia’s screen, ignoring the fact I wanted to laugh at the irony of the Alien on the ship saying \"Fascinating\" I carefully approached them and decided to check what was making them so grossed in. It looked like a spectrometric analysis of the said cloud, everything seemed in the regular parameters for a cloud of matter ejected by an exploding stars, a slightly elevated heavy element concentration demonstrating the former star was a third generation star, even if the concentration was a bit high for that it could easily been attributed to nucleogenesis from the supernova. Nothing was looking out of the ordinary really, I was about to ask my lover what was bothering them when I saw it. Right there. Like black ink on white paper. The analysis was positive for trace amounts of a tetrionic alloy of neutron star metal, that would have been normal for any alloy. However this alloy in particular, known as the Heavy Neutron-Tetrion Black Metal Alloy Three, was purely artificial, a Union’s invention. = Dilemma <dilemma> #emph[#strong[TW: Mention of death penalty, Aarin’s POV]] The latest discovery we made was capital. I #emph[never] thought we would find an artificial alloy on the place of a supernova it didn’t make sense, or so I thought. Sylvia, Eleanor and I were starting to think on a bigger scale. Space is big, very big, a one hundred light year of diameter region of space was really small compared to the infinite vastness of the observable universe, but it was significant, so even if the probability of having twelves systems blowing away relatively simultaneously was low, it was not #emph[impossible] per se. The concept of simultaneity in a region of space this big was different from the \"common sense\" definition of it. Light travels at exactly 299,792,458 metres per seconds, expressed in human units. This was ridiculously slow compared to space. It takes hundreds of years for light to travel through the Union space, causing an observation we would call occurring \"now\" to have had occurred hundreds of years ago. Taking all of that into account the probability of these twelve systems exploding was not too low, because these events did not occur simultaneously per se. However, we had FTL and FTL captors capable of observing light in a system, package the data and send it right back to the ship/observation center in considerably less time than it would take naturally. Allowing us to #emph[discover] these events in a few days. Taking all of that into account the probability of this event to be natural was not zero. Low, but not zero. That was, however, before other systems turned supernovae, two more to be factual. In the Union’s space. Bringing the total of supernovae in Union’s space to five. And it happened into systems that #emph[shouldn’t] turn into a supernova in the first place. Like Proxima Centaury. The lead of an artificial cause was stronger and stronger. But now that we discovered this alloy it was almost sure it was intentional. Someone, we don’t know who and do not have the slightest of idea, was deliberately causing these systems to explode, and was trying to harm the Union. We needed to contact the authorities, they would not be in this system for a few weeks from now, and it could be too late by then. The system’s protection of Union Central are top of the line, but it’s not the case of all Union’s planets. This, however, was a problem as we would be taken into custody or our ship destroyed the second we entered UC’s space, we managed to do it once with the element of surprise, however it only works one time. #middle We ultimately decided on #emph[not to] show up in the middle of Union Central out of a black hole like we were visiting our family. Instead, we sent a coded message hiding our current coordinates warning them about the incoming threat targeted to them, you know because we are the good guys after all. We wanted to avoid the genocide of hundreds of billions of innocent Union’s citizen, Eleanor was calculating and encrypting the message, who could be better than a literal sentient AI to encrypt data ? We received an answer from the Union’s government \"You are lying our sensors indicate nothing out of the ordinary and your data is not verifiable by our scientist, furthermore I want to remind you sentient AIs are not allowed in the Union and by usage by Union’s citizens, <NAME>, Aarin, you’re under arrest for communication with a sub-developed species, development of a sentient AI, lying to the government, trying to instate a panic in the Union, your trial has already been held, and you were sentenced of death by disintegration. Please surrender yourself in calm and let us perform the execution, we remind you that in front of our fleet, resistance is futile. - \"Well I think they didn’t take our warning the way we intended it to be\" summarized Eleanor, followed by a chuckle of all the person in the room, causing a frown in Eleanor not-quite-a-blob form. She was beginning to take form!. #middle #emph[#strong[Ariana’s POV]] We decided to chill out a little after the recent event, I was cuddling with Sylvia, we were whispering \"I love youuuu\"s to each other like every sugar-sweet young couples, but we were allowed to! After being separated for this long, and we had a lesbian reputation to hold though, I decided to bring my idea of implementing an interconnected network of FTL communication and adding an application layer of transportation on top of it. - \"Hey Eleanor, Sylvia, Aarin, I spent two years in Union Central communicating on the local network implementing the protocol, but what if we were setting up local network in every Union’s central system and communication routes and interconnecting them, we could develop a real FTL Internet, allowing digital people like Eleanor to travel far faster than FTL travel will likely ever be, even our multidimensional FTL is slower than the communication of the Union? It would allow member of different core world to communicate more efficiently instead of relying on old technologies relative to the Union lifespan?\" All of them seemed stunned, I can feel they #emph[knew] it was a good idea, a wonderful idea, and I was the one coming with it! I know I’m not known for my engineering skills, but I learned and taught in the best University in this region of the galaxy for two years, what did they expect? Sylvia came first out of her trans and realized how rude it seemed and cuddled closer to me as an excuse, Aarin was the first to speak up though, - \"Yeah actually it is a wonderful idea, and I wonder why we never thought of it even after having seen your internet technology on earth? It would revolutionize communication, your idea of sending AIs on the network to allow for fast communication between already established lines is also... mind-blowing, we need to work something up! Assuming there’ll still be a Union to implement a fleet wide communication network though\" - \"And I’m not finished hear me out, you may not know this but last year Union’s scientist managed made to a fully secured and digitalized transportation protocol, they called it the Hyper Transport Transfer Protocol Secured (HTTPS), we definitely need to change that name though\" I chuckled at that and Sylvia managed to avoid bursting out laughing while Aarin and Eleanor were looking at us as they were looking at a clown, \"Anyway, using that we could develop an application layer implementing that protocol over the uftlcp allowing people to transport faster than light over multiple systems in mere seconds. A big planetary transporter could even digitalize a full vessel allowing transport between hubs to be reduced from months, to days or hours, travel between earth and Union Central would take 4 to 8 hours, most of it used to the digitalization process!\" Now, it was the turn of Sylvia to be completely flabbergasted, even them did not think of something like that! This idea could revolutionize travel within the Union and established hubs, bringing the world closer together. Three months of exploration would truly be three months of exploration and not two months of leaving the Union and one month of exploration. ~ - \"That idea is wonderful baby! I hope you downloaded the paper! We need to calculate this, this could be #emph[huge]. That’s so cool! I’m so proud of you babe!\" they said, cuddling me, I wouldn’t complain, I love cuddles, and I love my lover. #middle To reward me for my wonderful ideas I was gifted an infinite amount of cuddles and hugs by Sylvia, I really should have started coming with good ideas before if only I knew how well I would be treated! - \"Eleanor ? How are you? You’ve been silent for a moment now, everything okay there?\" I asked the cute not-so-blobby anymore hologram who was watching us cuddling, I was not an expert in blob physiology, but she really seemed down. - \"Oh sorry Aria, yes sorry I was just thinking about something nothing too important don’t worry!\" she said, a little bashfully, AIs could be bashful? I guess she was becoming more and more \"human-like\" every day. I recognized that sort of phrasing however, so I decided to pry a bit further into the issue. - \"Elea?\" – I loved giving her a cute pet name to shorten her full one – \"You know you can tell us everything, I won’t pry too much, but I care about you and your well-being, we all do, please I can see you’re not being well, what can we do for you?\" - \"I’m jealous... I want a physical body it’s just that, it’s a little whim, I know it’s not possible.. I’m just an AI? And I’m illegal in most of the Union to be honest, so I will never have that, but seeing you like that, it’s a bit painful you know I would like to hug someone too, I can’t program every sensation within the limited hologram representation program I’m forced to use to interact with the world... That made sense. She was alone here, none of us were digitalized, what we were, though, was engineers and scientists, Aarin, Sylvia and I exchange a glance, transforming into a growing smirk and I said, - \"Well we just have to make you one?\" #middle It was, unfortunately, easier said than done, not that the technology was unknown to us, we had all the little components already invented for us, creation of biological mass ? Yes by the transporter. Transfer of a digitalized consciousness into a biological mass however, that was really difficult when a life form used the transporter at any point on the cycle the computer representation of this life form contains their consciousness and their \"physical body\" data. It was never separated. In our case however, it was, Elea was occupied designing her dream body with Aarin who’ll in turn program it into the transporter and attach the data to her files Sylvia and I’ mission was to find the way to link her consciousness to the body while still letting her the possibility to join the computer if need be, if her body was damaged, if we needed her to travel via the communication protocol, etc. We could not just blend her consciousness within her body like we would do for a human, that would render every attempt to decorelate the two impossible and would likely result in her conscious death. A think we would like to avoid. - \"But Ariana! If we connect a computer node #emph[in her brain] she should be able to jump between the body and the ship’s computer at will ? Like remote controlling an RC but in VR? If we re-enforce the quantum correlators in the computer node she would feel like it’s her body until she left it, that should solve our issue!\" Here they go again, we were deeply disagreeing with a core component of the project, they wanted to create a \"remote control\" like of flesh robot she could control within the safe place of the ship’s computer, while changing the quantum correlators with Union’s more advanced tech should resolve the issue of such robot found on Earth it would not be perfect, she still would be trapped in the computer and a huge bandwidth capable data link should always be present between her body and the ship. Something that was perfectly possible in the ship herself, but not outside passed a few hundred metres away. I however, wanted to host her core program directly in a human brain, I was writing a #emph[Binary to Human-Brain machine code] transpiler in UCaml, the official language of the Federation of Continents, an improvement based from a french language called \"OCaml\", I developed a compiler rated for Union’s CPU back in my university days, with that compiler we could transform her code made for binary computers of the Union into machine code interpretable by the human brain, still at research state on Earth but perfectible using Union’s technologies. Of course, we would have asked Eleanor herself, but she couldn’t decide and asked us to make the decision for her, we would likely settle in a compromise, Sylvia’s idea had the good taste of protecting her core program into the ship’s computer, mine was directly leaving her in danger of being erased. We could still reboot her from a copy on the ship’s mainframe, but a good chunk of her memory would be lost, and she wouldn’t like that. We were in a conundrum, a dilemma, seemingly impossible to resolve. #middle Finally, we came to a conclusion, it was, as I predicted, a mix of both our ideas. Her code would mostly be hosted on local on her human brain and run off the brain power, and a low-bandwidth long-range data link would link her to the ship, providing automatic memory storage, access to the local network, the ability to completely abandon the body if need be and jump back to the ship. This link would obviously be encrypted with our technology, not the Union’s main one, a quantum-based algorithm from Earth mixed with Union’s technology, virtually impossible to attack, as it would cut itself automatically if an attack was sensing, not before copying a subroutine of Eleanor designed to transport us back to the ship and flee the hell out of the place as soon as possible. This design should be almost perfect, Eleanor loved it, Aarin smiled and called us \"geniuses\" for our abilities to naturally mix Earth and Union’s technologies. And then came testing time! Eleanor made a back-up of herself in a protected area of the ship’s storage, and off we went. The brain design was modified to allow it to run our code, her code was compiled and verified, no bug has been found. Having an AI to verify code was pretty handy to be fair. I was thrilled to discover the form she wanted for her, was she tall? Tiny? Muscular? Not muscular? Hair? Long hair? No hair? I was really excited and was practically jumping in place while Aarin was setting up the transporter and hooking up everything needed. #middle And... That was it! She was here! And oh my god! She was beautiful! She was tall, way taller than I am – which was not that hard given my current height – and probably taller than I was before the super-HRT stuff, I would estimate her to be around 178 cm, just a bit smaller than Aarin’s human form. In fact this body seemed tailor-made to contrast with Aarin’s. She had beautiful long and wavy silver hair, dropping past her waist. Her body was very athletic, muscles definitions could be seen everywhere, like this body was made for long distance running. The best was that she was not human, she used a basic human design and mixed a fox tail, for balance she said – I was, however, sure it was because of the sheer cuteness and fluffiness of the tail –. Complete with fox ears. So basically we had a crew composed of a shape-shifting alien. A fox-girl AI, A tall badass enby and a tiny trans girl, and we were supposed to be serious and a major threat to the biggest political structure of this region of space? A crew of four weird but funny person? Yeah, it seemed so. Behold Union! We will kill you with cuddles and hugs! To be more serious, she was beautifully contrasting and mixing with Aarin, I wonder why she chose something like that? It was surely an accident, even if they \"knew\" themselves for a long time now, Eleanor having evolved from Aarin’s ship’s basic AI. But the smirk on Sylvia’s face seemed to indicate something else was at play here. And I, of course, was as lost as ever. What was going on and why I was always the last one to guess what was going on! Oh! Wait yes autism and anxiety, but it wasn’t fair of them to keep this sort of details away from me! - \"They are clearly in love with each others\" whispered my lover in my ears Oh yes. I guess it made sense then. Happy new couple! = Who are we gonna call? Aarin! <who-are-we-gonna-call-aarin> Those two were really too... stuck to each others, like a high school couple. Well to be honest we had our phase like that Sylvia and I. But they were in another level. #middle We were chilling out a little in a protected little asteroid belt a few light years away from Union Central, we sent again an automatic encrypted message to warn them from the menace, but they weren’t keen to talk to us, who would have thought? However, this forced us to develop a plan to defeat a species entirely by ourselves to protect the Union. Or hundred of billions will die horribly fried by their own Star. #middle Everything was going fine then the proximity alarm gone off and the screen shown a Union Ship fighting with, a cargo ship? A very heavy armed cargo ship to be honest, I can see plasma turrets and void torpedo launchers #emph[everywhere]. After a quick glance with the rest of the crew I slipped in the nav chair, and Sylvia into the custom created neutronic beam turrets, they were ridiculously powerful, we had regular weaponry, but while the enemy ship is occupied we could stop, calibrate the beam and destroy this ship with zeta-joules of energy in the form of X-Ray and Gamma ray burst. #middle I strapped myself activated the HUD and human display, clocked the ship and began carefully posting it in position. That said we sent an encrypted message stating we were gonna fire on the enemy ship, they understood maneuvered out of the beam and I pushed the button. And that was it, an enormously luminous beam – only dimmed by the glass protection – traveled at the speed of light and ate the 300,000 km separating our two ship in about a second. A few seconds later, nothing remained of the other ship, not even dust, all of it were decimated under the sheer heat and power of the gamma ray beam. We sent recognition codes to the Union’s ship, they conveniently decided not to attack us, and we were free to relax a bit after that stressful battle. #middle #emph[#strong[A few months earlier, Aarin’s POV]] We decided to take a break on our rescue efforts to add weapons to our ship, we were researched by the Union and my ship was a science ship designed to observe a planet a few years straight not combat. As such Sylvia and I were browsing the gray-black market a few weeks of voyage away from base. We wouldn’t find anything like a full fledge plasma station, but we could build it with the right parts. - \"Aarin! I bought what Eleanor asked me for her project, how are we for the plasma conduct and plasma compressors ?\" Sylvia asked me, rather excited, I wonder what was this project. Anyway I had everything we needed to construct plasma turrets. We couldn’t have space torpedoes however this kind of hardware is only in the hand of militaries. The stuff they bought looked very generic, ducting, now that I see it, it seems like very resistant to heat and electricity. This was intriguing, Eleanor #emph[had] to talk to me about it. - \"Yeah, I got it, let’s go home.\" #middle #emph[#strong[A few weeks earlier, on base, Sylvia’s POV]] Aarin was busy building the plasma turrets and installing them onto the ship’s power grid, the plasma, itself, was provided directly from the fusion reactor via bleeding duct already present, we just completed them with basic plasma duct. The plasma canons were pretty basic, the hydrogen-helium plasma was brought in a compression chamber where heavy and powerful electromagnets compressed it and accelerate the plasma ball in the cannon to a fraction of the speed of light, and here we are launching a mini-sun at 10 percents of the speed of light. Pretty basic weapons within the Union according to Aarin, and the shields we installed should be enough to withstand a few direct shot. Eleanor and I, however, were constructing a little more deadly weapon. The only one of its kind. It used the black hole generated by the FTFTL engine to accelerate and heating the plasma, until it gets a neutronic mess of nuclear reactions, close to the speed of life, after that this plasma is directed forward in the big cannon mounted forward and unleach hellish-hot neutron plasma, gamma rays, and X-rays at the speed of light destructing approximately anything. The big downside of this technology is that it uses the drive, however, it could save us in the worst of times. #emph[#strong[Present, Ariana’s POV]] The viewscreen was glowing a pure white even seconds after the shot, and that was #emph[with] the automatic protection activated to avoid being cooked by our own weapon, a few seconds later I heard the familiar chip of sounds signaling the imminent report of Eleanor on the main speakers. - \"The Union’s ship is severely damaged but the emergency beacon works, a rescue team should be here within an hour, the enemy ship is reduced to atoms ma’am, it seems like Sylvia’s idea works\" Indeed, it was... I can still count the dark spot in my vision. - \"Ariana! We’re receiving a communication signal from the ship! They’re hailing us!\" I called Sylvia and Aarin to come to the main bridge and accept the call, audio only - \"Unidentified vessel, this is the Union Battleship Xaor, identify yourself, or you will be fired upon, repeat, identify yourself, or you will be fired upon, over\" - \"Uh, full military protocol even after we saved them it seems\" Sylvia said, non without a chuckle, Aarin signaled me to answer, - \"Battleship Xaor, this is Ariana from the Rogue Science Ship I, I repeat this is Ariana from the Rogue Science Ship I, please do not fire, do not fire\" I said, hoping they would listen and not making the mistake of trying to kill us - \"Ariana, this is <NAME>, commanding officer of the Xaor, our weapon are targeted on your drive, you will send us your commanding code and surrender yourselves to the Union for multiple crime, or you will be destroyed, I repeat surrender yourselves, or you will be destroyed, over\" They are not making this easy, aren’t they.. With a wordless nod to Syl we targeted our big canon directly on their bridge, - \"<NAME>, please, we just saved you from a hostile foe, the structural integrity of your ship is held magically by the internal field, you cannot spare any energy for the regular weapon, nor the railgun, and our shields are more than capable of tanking whatever bullets you might throw at us, to top it off we have our big mighty canon pointed right at your nose, so please Captain spare me the energy of dispersing your atoms all around the known Universe and Stand. Down. RSS I over.\" What felt like hours passed, seconds by seconds, tense moment with each other’s weapons hot and ready, we’re sure we would be victorious and with barely a scratch, but I really don’t want to destroy a Union ship and her crew, too many people died already with the destruction of the enemy ship. Finally, exactly two minutes later the familiar sound of the coms chipped, and we all relaxed a bit, - \"Ariana, this is <NAME>, we’re standing down repeat, we’re standing down, you’re right.\" - \"Thanks Captain, weapons disengaged, with that out of the way, what the hell an enemy ship that much armed was doing a few lightyears away from Union Central? What are the sentinel doing! The automated defense system of Union Central should have picked them up a long time ago! What happened!\" - \"We have.. no idea, fleet command back home is silent about them and just ordered to engage the enemy in close combat, but we could not have won this battle they were welled armed, and it was like they knew all the weaknesses and stress point of the ship\" Aarin and myself frowned at that, this knowledge is a big secret, guarded by the elite on the military, nobody should have had access to that sort of thing, with the odd behaviour of Fleet Command it sounds like an infiltration, and if they’re already that high up in the hierarchy the Union is, for a lack of a better term, completely screwed. - \"Crap.\" Aarin said, and I could not agree more, even Sylvia whose knowledge of internal Union politics is lacking picked up what was happening and seemed tense, every one of us were tense, how could we on our own figure this out we’re four against an entire unknown enemy force whom agents #emph[already] infiltrated the military command. #middle Suddenly, the maximum alert activated itself, while the internal gravity system failed we were sent away flying at high velocity inside our ship - \"Elea! What is happening! We have an emergency! We’re floating!\" - \"Working on it! An unknown force projected the ship and caused her to collide with a close asteroid, the internal gravity should activate itself.... now\" and with that we fell on our butt in the middle of the bridge, yeah activating the gravity after an accidental shutdown, #emph[sucked.], Aarin commanded a damage report - \"Nothing is too damaged, the emergency shields activated themselves just before the colision so just a few scratches on the main hull, I calculated the approximate location of the Xaor, we should see it\" We all at once understood what caused this situation. Where lied the Xaor is now a cloud of dust and space junk. #middle #emph[#strong[A few moments ago, Union Central Fleet High Command]] The room was flashing red and the sound of the alarm was almost deafening for most of us in the High Command, we don’t know how but one of our patrol ship, the Xaor, picked up an unknown signal and reported back for investigation, this was not exactly routine, the automated defense system should have detected it a long time ago and the ship itself should have checked in with the civilian traffic control once they got into our protected space, but this is not unheard of, the ship could be damaged and its transponders non-responsive, however once the Xaor was into range the unknown vessel started showing hostile behaviour and engaged it into battle. I checked the hologram in the middle of the room displaying the fight and the status of the Xaor, it looked badly damaged the battle started to seem more, and more one-sided in favour of the enemy ship. - \"Sir, we picked up another energy signature close to the fight, it can’t be one of our ship the closest is more than a day away at top speed\" my lieutenant was saying, I replied with a grunt and resumed thinking about the situation, however as I was considering launching the fast response FTL fighters the light representing the enemy ship just went off, - \"Massive gamma rays detected, unknown form of energy, analysis suggest a very powerful kind of weapon destroyed the enemy ship\" I frowned at the computer’s report, we do not have that type of weapon on our patrol ship, and even then our destroyers are not fitted with that much power, I asked the lieutenant to connect me to the Xaor’s commanding officer, a few seconds later the main screen came to life with the live feed from the ship’s bridge, - \"Hi sir, sorry sir we got an issue over here our survival system are barely working do you read?\" - \"Yes Xaor, we do, please report\" - \"We got attacked by an unknown hostile force, the ship’s integrity field appear to be holding for now, a beam seems to have destroyed the enemy ship, there’s just nothing, one second it was there and now it isn’t\" - \"It corrolate our finding any intel on how it was possible? A gamma ray burst from a nearby star maybe ?\" I watched as he went from station to station trying to discover what happened when he put the conversation on hold, a few minutes later he was reaching out again but the signal got scrambled, - \"What happened with the signal? Correct! We need to know what happened there\" time seemed to be slowed down as I watched our engineer trying to get around the fluctuation on the signal - \"Sir, the signal appears to be the automated distress beacon, but the communication suddently stopped in the middle of the communication with only one last word.\" - \"Please lieutenant, go on, what is it?\" - \"Zero.\" #middle The next minutes were carefully spent checking with the Xaor’s transponder and with no answer we called the Xaor missing in action, the last communication seems to infer the ship was self-destroyed, but it didn’t make any sense did it? They were saved by an unknown force – which I believe is Aarin’s crew, I secretely kind of liked him and his last trick shown he definitely had the tech to do this, and even with the current bounty on his head he would never have destroyed a Union ship without a strong incentive to, which was not the case here, he #emph[saved] the Xaor in the first place – so why would they activate the self destruct right after? Were they boarded ? It seems unlikely we paid close attention to the skirmish and our sensors didn’t picked shuttles, so, would it be possible there was an enemy #emph[inside] the Xaor? They may have attempted to take over the ship and her commanding officer would then have activated the self destruct, or the enemy themselves activated it to cover their traces ? - \"Lieutenant please leave this room I need to contact the government, we have an issue here\" Now that I wasn’t thinking out loud the room did seems eerily quiet, and my lieutenant did not answered - \"Lieutenant.\" I repeated looking around the room to spot him, and what I saw was, to put it midly, a slaughter, every one of the officers in the room were dead - \"Sorry sir, do not move, hands on the chair #emph[sir].\" the familiar voice of my lieutenant spoke, right behind me, he slowly turned in front of me with his weapon right in front of my head, I was also very aware of the fact I come to work without my weapon. - \"I’m sorry, you figured out too much\" were the last words I’d ever hear. #middle #emph[#strong[Moments later, Prime Minister Private Chambers]] The last message I received from the Fleet Admiral was alarming at best, just one word, one single terrifying word, #emph[invasion], he sent it to me on our private encrypted line, a line I knew was only accessible with his biological data, on the right armrest of his chair, back in the Fleet High Command room, if he sent it to me through this channel, and not with a regular call in his office I had to assume the high command was compromise, and I also had to assume he was dead. I tried not to think about the death of my closest friend and resumed my work, I was reviewing data sent by Aarin, granted the Senate #emph[hated] him and with his last stunt of appearing out of thin air right on top of the most populated world of the entire Union he did not improved his case, he was however, one of our brightest scientist and a good friend of mine, along with the Fle.. Former, fleet admiral, I managed to convice the governement and the senate to send the data directly in my quarters for further analysis. The signature itself had nothing unusual about it, it was a metal signature of a regular alloy used by the Union and other sentient alliances all over this quadrant of the Milky Way, the base material were abundant and the metal strong enough to create space ships, which was its main usage among us, no the problem was #emph[were] the data were collected, it was on the site of one of the furthest recent supernova, at the edge of Union’s space, our ships could not reach that area on time to collect it but he apparently developed a future tech, a technology I’m sure he would gladly provide us granted we survived the current crisis. The problem was what could generate these metal naturally ? As far as our scientists are aware it requires a specific piece of hardware to forge the aloy that couldn’t occur naturally. It would indicate that all of the supernovae that were happening around Union’s space as of late were #emph[artificial]~? I didn’t want to think that but the proofs seemed to agree, they were happening really close and in a relative simultaneity once the relative time distance substracted. But now there’s this invasion, they managed to reach the High Command of all places, so they are here for a long time now and it seems they’re here to stay, I don’t think this planet is safe anymore. No scratch that, the #emph[Union] is not safe anymore, I must call Aarin now, and hope he can save us all. #emph[#strong[Aria’s POV, RSS I]] We were still debating what could have happened to the Xaor when a distracting sound played in the bridge, now that I think of it, this sound a lot familiar, like an old 2010s phone line ? - \"Attention all crew, we have a call from the private encrypted line of the Prime Minister for Aarin\" Elea said, with a tension to her voice, I think we all knew it was #emph[bad news] if the prime minister personaly called us. At the same time Elea finished her calculation and deduced the Xaor was destroyed using a deliberate failure of the core containment shield, which would cause the core to burn and eat through the ship like sulfuric acid through paper towel, in other terms, the ship was self-destroyed - \"Accept the call Elea\" Aarin said putting his hand on the bio-reader to match his bio-data, authenticating the receiver of the call - \"Aarin! Aarin! Is that you, we need to talk! Fast!\" The prime minister didn’t even bother with the decorum and I was blown away, they really like their decorum. I decided to shut up and snuggle up to Sylvia, stealing some light kisses while listening to the heated discussion between Aarin and the PM - \"\[...\] and see! While I was reviewing the data you sent to the senate I received a communication from the Fleet Admiral, just one word, #emph[Invasion]. I think they are here, on Union Central, potentially all over the Union, and they infiltrated the High Command, I must assume they infiltrated the other institutions too, which would explain why your data was never took seriously!\" - \"We unfortunately came to the same conclusion sir, we analyzed the remains of the Xaor and it was a self destruction, they were definitely in the ship herself, we cannot trust the fleet. They also have tech advanced enough to purposely trigger supernovae, who knows what they might do.\" The look on our face must have been the literal definition for \"dread\", we could barely fight a ship if we have cover, how on earth could we keep up with the entire Union fleet? - \"You’re right, and I fear they might kill me next, which is why I’m doing this, Aarin by the primordial act of safety of the Union, you’re appointed Fleet Admiral of the Union Navy, Ariana, you’re appointed War Prime Minister of the Union and given the legislative powers as well, Ariana, Aarin, Sylvia, and yes even you Eleanor I know about you, you’re the head now, the Union trust you to saves us. Godspeed Union One. - \"So I’m basically the President of the World now?\" - \"The President of many worlds, dear Aria, now, folx, I need to be clear. We are not fighting an invasive force, we are resisting against an occupation.\" = Glossary #print-glossary(show-all: true,( (key:"disguise",short:"disguise", desc:"a shape-shifting technology invented by the union mimicking the ability of one of their specie."), (key:"dffc",short: "Declaration of Foundation of the Federation of Continents (The)",desc: "The treaty that formed the world government known as the Federation of Continents, a federation of all the continents nations on Earth. Also called Federation Treaty as a reference to the Union Treaty"), (key:"europe", short: "Europe", desc:"The nation created by the fusion of the ex-nations of the EU and other nations of the european continent"), (key: "federationt", short: "Federation Treaty", desc: [See @dffc]), (key: "federation",short:"Federation of Continents",desc: "The world federation of all continents nations on Earth."), (key: "fsp", short: "Federation Space Program", desc: "The space program of the Federation of Continents."), (key: "ftl", short: "FTL", long: "Faster Than Light"), (key: "ijpl", short: "IJPL", long: "International Jet Propulsion Laboratory", desc: "The successor of NASA's Jet Propulsion Laboratory, attached to the Federation Space Program."), (key: "mic", short: "Massacre of the International Convention", desc: "The events which happened in the first International Convention of the United Nations in 2023 (a reunion of all representative from the more than 200 nations on Earth), a series of terrorist attacks from North Korea killed 2000 people, more than half of all heads of states died in the attack. This attack directly caused the international efforts to unionise."), (key: "np", short: "New Paris", desc: "The capital of Europe, its exact geographic position is purposely not stated, somewhere between Belgium, France, Germany, Italy and Switzerland. Named after the former capital of France and most populated city of the EU, Paris."), (key: "ut",short: "Union Treaty",desc: "The treaty which formed Europe out of the European Union, following the events of the Massacre of the International Convention."), (key: "union", short: "Union (The)", desc: "The group of highly advanced alien species who formed an alliance spanning accross 80 to 120 light-years."), (key: "uc", short: "Union Central", desc: "The central politic capital system of The Union."), (key: "us", short: "Union Standard", desc: "The language spoken in the Union"), (key: "es", short: "Earth Standard", desc: "The language spoken on Earth (a dialect of English)."), (key: "uftlcp", short: "UFTLCP", long: "Union Faster Than Light Communication Protocol", desc: "The protocol allowing faster than light communication, developed by the Union scientists. Said to be far faster than FTL travel."), ))
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch11-hyperview-a-mobile-hypermedia.typ
typst
Other
#import "lib/definitions.typ": * == Hyperview: A Mobile Hypermedia You may be forgiven for thinking the hypermedia architecture is synonymous with the web, web browsers, and HTML. No doubt, the web is the largest hypermedia system, and web browsers are the most popular hypermedia client. The dominance of the web in discussions about hypermedia make it easy to forget that hypermedia is a general concept, and can be applied to all types of platforms and applications. In this chapter, we will see the hypermedia architecture applied to a non-web platform: native mobile applications. Mobile as a platform has different constraints than the web. It requires different trade-offs and design decisions. Nonetheless, the concepts of hypermedia, HATEOAS, and REST can be directly applied to build delightful mobile applications. In this chapter we will cover shortcomings with the current state of mobile app development, and how a hypermedia architecture can address these problems. We will then look at a path toward hypermedia on mobile: Hyperview, a mobile app framework that uses the hypermedia architecture. We’ll conclude with an overview of HXML, the hypermedia format used by Hyperview. === The State of Mobile App Development <_the_state_of_mobile_app_development> Before we can discuss how to apply hypermedia to mobile platforms, we need to understand how native mobile apps are commonly built. I’m using the word "native" to refer to code written against an SDK provided by the phone’s operating system (typically Android or iOS). This code is packaged into an executable binary, and uploaded & approved through app stores controlled by Google and Apple. When users install or update an app, they’re downloading this executable and running the code directly on their device’s OS. In this way, mobile apps have a lot in common with old-school desktop apps for Mac, Windows, or Linux. There is one important difference between PC desktop apps of yesteryear and today’s mobile apps. These days, almost all mobile apps are "networked". By networked, we mean the app needs to read and write data over the Internet to deliver its core functionality. In other words, a networked mobile app needs to implement the client-server architecture. When implementing the client-server architecture, the developer needs to make a decision: Should the app be designed as a thin client or thick client? The current mobile ecosystems strongly push developers towards a thick-client approach. Why? Remember, Android and iOS require that a native mobile app be packaged and distributed as an executable binary. There’s no way around it. Since the developer needs to write code to package into an executable, it seems logical to implement some of the app’s logic in that code. The code may as well initiate HTTP calls to the server to retrieve data, and then render that data using the platform’s UI libraries. Thus, developers are naturally led into a thick-client pattern that looks something like this: - The client contains code to make API requests to the server, and code to translate those responses to UI updates - The server implements an HTTP API that speaks JSON, and knows little about the state of the client Just like with SPAs on the web, this architecture has a big downside: the app’s logic gets spread across the client and server. Sometimes, this means that logic gets duplicated (like to validate form data). Other times, the client and server each implement disjoint parts of the app’s overall logic. To understand what the app does, a developer needs to trace interactions between two very different codebases. There’s another downside that affects mobile apps more than SPAs: API churn. Remember, the app stores control how your app gets distributed and updated. Users can even control if and when they get updated versions of your app. As a mobile developer, you can’t assume that every user will be on the latest version of your app. Your frontend code gets fragmented across many versions, and now your backend needs to support all of them. === Hypermedia for Mobile Apps #index[hypermedia][for mobile] We’ve seen that the hypermedia architecture can address the shortcomings of SPAs on the web. But can hypermedia work for mobile apps as well? The answer is yes! Just like on the web, we can use hypermedia formats on mobile and let it serve as the engine of application state. All of the logic is controlled from the backend, rather than being spread between two codebases. Hypermedia architecture also solves the annoying problem of API churn on mobile apps. Since the backend serves a hypermedia response containing both data and actions, there’s no way for the data and UI to get out of sync. No more worries about backwards compatibility or maintaining multiple API versions. So how can you use hypermedia for your mobile app? There are two approaches employing hypermedia to build & ship native mobile apps today: - Web views, which wraps the trusty web platform in a mobile app shell - Hyperview, a new hypermedia system we designed specifically for mobile apps ==== Web Views <_web_views> The simplest way to use hypermedia architecture on mobile is by leveraging web technologies. Both Android and iOS SDKs provide "web views": chromeless web browsers that can be embedded in native apps. Tools like Apache Cordova make it easy to take the URL of a website, and spit out native iOS and Android apps based on web views. If you already have a responsive web app, you can get a "native" mobile HDA for free. Sounds too good to be true, right? Of course, there is a fundamental limitation with this approach. The web platform and mobile platforms have different capabilities and UX conventions. HTML doesn’t natively support common UI patterns of mobile apps. One of the biggest differences is around how each platform handles navigation. On the web, navigation is page-based, with one page replacing another and the browser providing back/forward buttons to navigate the page history. On mobile, navigation is more complex, and tuned for the physicality of gesture-based interactions. - To drill down, screens slide on top of each other, forming stacks of screens. - Tab bars at the top or bottom of the app allow switching between various stacks of screens. - Modals slide up from the bottom of the app, covering the other stacks and tab bar. - Unlike with web pages, all of these screens are still present in memory, rendered and updating based on app state. The navigation architecture is a major difference between how mobile and web apps function. But it’s not the only one. Many other UX patterns are present in mobile apps, but are not natively supported on the web: - pull-to-refresh to refresh content in a screen - horizontal swipe on UI elements to reveal actions - sectioned lists with sticky headers While these interactions are not natively supported by web browsers, they can be simulated with JS libraries. Of course, these libraries will never have the same feel and performance as native gestures. And using them usually requires embracing a JS-heavy SPA architecture like React. This puts us back at square 1! To avoid using the typical thick-client architecture of native mobile apps, we turned to a web view. The web view allows us to use good-old hypermedia-based HTML. But to get the desired look & feel of a mobile app, we end up building a SPA in JS, losing the benefits of Hypermedia in the process. To build a mobile HDA that acts and feels like a native app, HTML isn’t going to cut it. We need a format designed to represent the interactions and patterns of native mobile apps. That’s exactly what Hyperview does. ==== Hyperview #indexed[Hyperview] is an open-source hypermedia system that provides: - A hypermedia format for defining mobile apps called HXML - A hypermedia client for HXML that works on iOS and Android - Extension points in HXML and the client to customize the framework for a given app ===== The format #indexed[HXML] was designed to feel familiar to web developers, used to working with HTML. Thus the choice of XML for the base format. In addition to familiar ergonomics, XML is compatible with server-side rendering libraries. For example, Jinja2 is perfectly suited as a templating library to render HXML. The familiarity of XML and the ease of integration on the backend make it simple to adopt in both new and existing codebases. Take a look at a "Hello World" app written in HXML. The syntax should be familiar to anyone who’s worked with HTML: #figure(caption: [Hello World])[ ```xml <doc xmlns="https://hyperview.org/hyperview"> <screen> <styles /> <body> <header> <text>My first app</text> </header> <view> <text>Hello World!</text> </view> </body> </screen> </doc> ``` ] But HXML is not just a straight port of HTML with differently named tags. In previous chapters, we’ve seen how htmx enhances HTML with a handful of new attributes. These additions maintain the declarative nature of HTML, while giving developers the power to create rich web apps. In HXML, the concepts of htmx are built into the spec. Specifically, HXML is not limited to "click a link" and "submit a form" interactions like basic HTML. It supports a range of triggers and actions for modifying the content on a screen. These interactions are bundled together in a powerful concept of "behaviors." Developers can even define new behavior actions to add new capabilities to their app, without the need for scripting. We will learn more about behaviors later in this chapter. ===== The client #index[hypermedia][client] Hyperview provides an open-source HXML client library written in React Native. With a little bit of configuration and a few steps on the command line, this library compiles into native app binaries for iOS or Android. Users install the app on their device via an app store. On launch, the app makes an HTTP request to the configured URL, and renders the HXML response as the first screen. It may seem a little strange that developing a HDA using Hyperview requires a single-purpose client binary. After all, we don’t ask users to first download and install a binary to view a web app. No, users just enter a URL in the address bar of a general-purpose web browser. A single HTML client renders apps from any HTML server (@fig-1clientmanyserver). #asciiart( read("images/diagram/one-client-many-servers.txt"), caption: [One HTML client, multiple HTML servers], )<fig-1clientmanyserver> It is theoretically possible to build an equivalent general-purpose "Hyperview browser." This HXML client would render apps from any HXML server, and users would enter a URL to specify the app they want to use. But iOS and Android are built around the concept of single-purpose apps. Users expect to find and install apps from an app store, and launch them from the home screen of their device. Hyperview embraces this app-centric paradigm of today’s popular mobile platforms. That means that the HXML client (app binary) renders its UI from a single pre-configured HXML server (@fig-1client1server). #asciiart( read("images/diagram/one-server-one-hxml-client.txt"), caption: [One HXML client, one HXML server], )<fig-1client1server> Luckily, developers do not need to write a HXML client from scratch; the open-source client library does 99% of the work. And as we will see in the next section, there are major benefits to controlling both the client and server in a HDA. ===== Extensibility <_extensibility> To understand the benefits of Hyperview’s architecture, we need to first discuss the drawbacks of the web architecture. On the web, any web browser can render HTML from any web server. This level of compatibility can only happen with well-defined standards such as HTML5. But defining and evolving standards is a laborious process. For example, the W3C took over 7 years to go from first draft to recommendation on the HTML5 spec. It’s not surprising, given the level of thoughtfulness that needs to go into a change that impacts so many people. But it means that progress happens slowly. As a web developer, you may need to wait years for browsers to gain widespread support for the feature you need. So what are the benefits of Hyperview’s architecture? In a Hyperview app, _your_ mobile app only renders HXML from _your_ server. You don’t need to worry about compatibility between your server and other mobile apps, or between your mobile app and other servers. There is no standards body to consult. If you want to add a blink feature to your mobile app, go ahead and implement a `<blink>` element in the client, and start returning `<blink>` elements in the HXML responses from your server. In fact, the Hyperview client library was built with this type of extensibility in mind. There are extension points for custom UI elements and custom behavior actions. We expect and encourage developers to use these extensions to make HXML more expressive and customized to their app’s functionality. And by extending the HXML format and client itself, there’s no need for Hyperview to include a scripting layer in HXML. Features that require client-side logic get "built-in" to the client binary. HXML responses remain pure, with UI and interactions represented in declarative XML. ==== Which Hypermedia Architecture Should You Use? <_which_hypermedia_architecture_should_you_use> We’ve discussed two approaches for creating mobile apps using hypermedia systems: - create a backend that returns HTML, and serve it in a mobile app through a web view - create a backend that returns HXML, and serve it in a mobile app with the Hyperview client I purposefully described the two approaches in a way to highlight their similarities. After all, they are both based on hypermedia systems, just with different formats and clients. Both approaches solve the fundamental issues with traditional, SPA-like mobile app development: - The backend controls the full state of the app. - Our app’s logic is all in one place. - The app always runs the latest version, there’s no API churn to worry about. So which approach should you use for a mobile HDA? Based on our experience building both types of apps, we believe the Hyperview approach results in a better user experience. The web-view will always feel out-of-place on iOS and Android; there’s just no good way to replicate the patterns of navigation and interaction that mobile users expect. Hyperview was created specifically to address the limitations of thick-client and web view approaches. After the initial investment to learn Hyperview, you’ll get all of the benefits of the Hypermedia architecture, without the downsides of a degraded user experience. Of course, if you already have a simple, mobile-friendly web app, then using a web-view approach is sensible. You will certainly save time from not having to serve your app as HXML in addition to HTML. But as we will show at the end of this chapter, it doesn’t take a lot of work to convert an existing Hypermedia-driven web app into a Hyperview mobile app. But before we get there, we need to introduce the concepts of elements and behaviors in Hyperview. Then, we’ll re-build our contacts app in Hyperview. #sidebar[When Shouldn't You Use Hypermedia to Build a Mobile App?][ Hypermedia is not always the right choice to build a mobile app. Just like on the web, apps that require highly dynamic UIs (such as a spreadsheet application) are better implemented with client-side code. Additionally, some apps need to function while fully offline. Since HDAs require a server to render UI, offline-first mobile apps are not a good fit for this architecture. However, just like on the web, developers can use a hybrid approach to build their mobile app. The highly dynamic screens can be built with complex client-side logic, while the less dynamic screens can be built with web views or Hyperview. In this way, developers can spend their _complexity budget_ on the core of the application, and keep the simple screens simple. ] === Introduction to HXML ==== Hello World! #index[HXML][Hello World!] HXML was designed to feel natural to web developers coming from HTML. Let’s take a closer look at the "Hello World" app defined in HXML: #figure(caption: [Hello World, revisited])[ ```xml <doc xmlns="https://hyperview.org/hyperview"> <1> <screen> <2> <styles /> <body> <3> <header> <4> <text>My first app</text> </header> <view> <5> <text>Hello World!</text> <6> </view> </body> </screen> </doc> ``` ] 1. The root element of the HXML app 2. The element representing a screen of the app 3. The element representing the UI of the screen 4. The element representing the top header of the screen 5. A wrapper element around the content shown on the screen 6. The text content shown on the screen Nothing too strange here, right? Just like HTML, the syntax defines a tree of elements using start tags (`<screen>`) and end tags (`</screen>`). Elements can contain other elements (`<view>`) or text (`Hello World!`). Elements can also be empty, represented with an empty tag (`<styles />`). However, you’ll notice that the names of the HXML element are different from those in HTML. Let’s take a closer look at each of those elements to understand what they do. #index[HXML][\<doc\>] `<doc>` is the root of the HXML app. Think of it as equivalent to the `<html>` element in HTML. Note that the `<doc>` element contains an attribute `xmlns="https://hyperview.org/hyperview"`. This defines the default namespace for the doc. Namespaces are a feature of XML that allow one doc to contain elements defined by different developers. To prevent conflicts when two developers use the same name for their element, each developer defines a unique namespace. We will talk more about namespaces when we discuss custom elements & behaviors later in this chapter. For now, it’s enough to know that elements in a HXML doc without an explicit namespace are considered to be part of the `https://hyperview.org/hyperview` namespace. #index[HXML][\<screen\>] `<screen>` represents the UI that gets rendered on a single screen of a mobile app. It’s possible for one `<doc>` to contain multiple `<screen>` elements, but we won’t get into that now. Typically, a `<screen>` element will contain elements that define the content and styling of the screen. #index[HXML][\<styles\>] `<styles>` defines the styles of the UI on the screen. We won’t get too much into styling in Hyperview in this chapter. Suffice it to say, unlike HTML, Hyperview does not use a separate language (CSS) to define styles. Instead, styling rules such as colors, spacing, layout, and fonts are defined in HXML. These rules are then explicitly referenced by UI elements, much like using classes in CSS. #index[HXML][\<body\>] `<body>` defines the actual UI of the screen. The body includes all text, images, buttons, forms, etc that will be shown to the user. This is equivalent to the `<body>` element in HTML. #index[HXML][\<header\>] `<header>` defines the header of the screen. Typically in mobile apps, the header includes some navigation (like a back button), and the title of the screen. It’s useful to define the header separately from the rest of the body. Some mobile OSes will use a different transition for the header than the rest of the screen content. #index[HXML][\<view\>] `<view>` is the basic building block for layouts and structure within the screen’s body. Think of it like a `<div>` in HTML. Note that unlike in HTML, a `<div>` cannot directly contain text. #index[HXML][\<text\>] `<text>` elements are the only way to render text in the UI. In this example, "Hello World" is contained within a `<text>` element. That’s all there is to define a basic "Hello World" app in HXML. Of course, this isn’t very exciting. Let’s cover some other built-in display elements. ==== UI Elements ===== Lists #index[HXML][\<list\>] #index[HXML][\<item\>] A very common pattern in mobile apps is to scroll through a list of items. The physical properties of a phone screen (long & vertical) and the intuitive gesture of swiping a thumb up & down makes this a good choice for many screens. HXML has dedicated elements for representing lists and items. #figure(caption: [List element])[ ```xml <list> <1> <item key="item1"> <2> <text>My first item</text> <3> </item> <item key="item2"> <text>My second item</text> </item> </list> ``` ] 1. Element representing a list 2. Element representing an item in the list, with a unique key 3. The content of the item in the list. Lists are represented with two new elements. The `<list>` wraps all of the items in the list. It can be styled like a generic `<view>` (width, height, etc). A `<list>` element only contains `<item>` elements. Of course, these represent each unique item in the list. Note that `<item>` is required to have a `key` attribute, which is unique among all items in the list. You might be asking, "Why do we need a custom syntax for lists of items? Can’t we just use a bunch of `<view>` elements?". Yes, for lists with a small number of items, using nested `<views>` will work quite well. However, often the number of items in a list can be long enough to require optimizations to support smooth scrolling interactions. Consider browsing a feed of posts in a social media app. As you keep scrolling through the feed, it’s not unusual for the app to show hundreds if not thousands of posts. At any time, you can flick your finger to scroll to almost any part of the feed. Mobile devices tend to be memory-constrained. Keeping the fully-rendered list of items in memory could consume more resources than available. That’s why both iOS and Android provide APIs for optimized list UIs. These APIs know which part of the list is currently on-screen. To save memory, they clear out the non-visible list items, and recycle the item UI objects to conserve memory. By using explicit `<list>` and `<item>` elements in HXML, the Hyperview client knows to use these optimized list APIs to make your app more performant. #index[HXML][\<section\>] #index[HXML][\<section-list\>] #index[HXML][\<section-title\>] It’s also worth mentioning that HXML supports section lists. Section lists are useful for building list-based UIs, where the items in the list can be grouped for the user’s convenience. For example, a UI showing a restaurant menu could group the offerings by dish type: #figure(caption: [Section list element])[ ```xml <section-list> <1> <section> <2> <section-title> <3> <text>Appetizers</text> </section-title> <item key="1"> <4> <text>French Fries</text> </item> <item key="2"> <text>Onion Rings</text> </item> </section> <section> <5> <section-title> <text>Entrees</text> </section-title> <item key="3"> <text>Burger</text> </item> </section> </section-list> ``` ] 1. Element representing a list with sections 2. The first section of appetizer offerings 3. Element for the title of the section, rendering the text "Appetizers" 4. An item representing an appetizer 5. A section for entree offerings You’ll notice a couple of differences between `<list>` and `<section-list>`. The section list element only contains `<section>` elements, representing a group of items. A section can contain a `<section-title>` element. This is used to render some UI that acts as the header of the section. This header is "sticky", meaning it stays on screen while scrolling through items that belong to the corresponding section. Finally, `<item>` elements act the same as in the regular list, but can only appear within a `<section>`. ===== Images #index[HXML][\<image\>] #index[Hyperview][images] Showing images in Hyperview is pretty similar to HTML, but there are a few differences. #figure(caption: [Image element])[ ```xml <image source="/profiles/1.jpg" style="avatar" /> ``` ] The `source` attribute specifies how to load the image. Like in HTML, the source can be an absolute or relative URL. Additionally, the source can be an encoded data URI, for example `data:image/png;base64,iVBORw`. However, the source can also be a "local" URL, referring to an image that is bundled as an asset in the mobile app. The local URL is prefixed with `./`: #figure(caption: [Image element, pointing to local source])[ ```xml <image source="./logo.png" style="logo" /> ``` ] Using Local URLs is an optimization. Since the images are on the mobile device, they don’t require a network request and will appear quickly. However, bundling the image with the mobile app binary increases the binary size. Using local images is a good trade-off for images that are frequently accessed but rarely change. Good examples include the app logo, or common button icons. The other thing to note is the presence of the `style` attribute on the `<image>` element. In HXML, images are required to have a style that has rules for the image’s `width` and `height`. This is different from HTML, where `<img>` elements do not need to explicitly set a width and height. web browsers will re-flow the content of a web page once the image is fetched and the dimensions are known. While re-flowing content is a reasonable behavior for web-based documents, users do not expect mobile apps to re-flow as content loads. To maintain a static layout, HXML requires the dimensions to be known before the image loads. ==== Inputs #index[Hyperview][inputs] There’s a lot to cover about inputs in Hyperview. Since this is meant to be an introduction and not an exhaustive resource, I’ll highlight just a few types of inputs. Let’s start with an example of the simplest type of input, a text field. #figure(caption: [Text field element])[ ```xml <text-field name="first_name" <1> style="input" <2> value="Adam" <3> placeholder="<NAME>" <4> /> ``` ] 1. The name used when serializing data from this input 2. The style class applied to the UI element 3. The current value set in the field 4. A placeholder to display when the value is empty #index[HXML][\<text-field\>] This element should feel familiar to anyone who’s created a text field in HTML. One difference is that most inputs in HTML use the `<input>` element with a `type` attribute, eg `<input type="text">`. In Hyperview, each input has a unique name, in this case `<text-field>`. By using different names, we can use more expressive XML to represent the input. For example, let’s consider a case where we want to render a UI that lets the user select one among several options. In HTML, we would use a radio button input, something like `<input type="radio" name="choice" value="option1" />`. Each choice is represented as a unique input element. This never struck me as ideal. Most of the time, radio buttons are grouped together to affect the same name. The HTML approach leads to a lot of boilerplate (duplication of `type="radio"` and `name="choice"` for each choice). Also, unlike radio buttons on desktop, mobile OSes don’t provide a strong standard UI for selecting one option. Most mobile apps use richer, custom UIs for these interactions. So in HXML, we implement this UI using an element called `<select-single>`: #figure(caption: [Select-single element])[ ```xml <select-single name="choice"> <1> <option value="option1"> <2> <text>Option 1</text> <3> </option> <option value="option2"> <text>Option 2</text> </option> </select-single> ``` ] 1. Element representing an input where a single choice is selected. The name of the selection is defined once here. 2. Element representing one of the choices. The choice value is defined here. 3. The UI of the selection. In this example, we use text, but we can use any UI elements. #index[HXML][\<select-single\>] The `<select-single>` element is the parent of the input for selecting one choice out of many. This element contains the `name` attribute used when serializing the selected choice. `<option>` elements within `<select-single>` represent the available choices. Note that each `<option>` element has a `value` attribute. When pressed, this will be the selected value of the input. The `<option>` element can contain any other UI elements within it. This means that we’re not hampered by rendering the input as a list of radio buttons with labels. We can render the options as radios, tags, images, or anything else that would be intuitive for our interface. HXML styling supports modifiers for pressed and selected states, letting us customize the UI to highlight the selected option. Describing all features of inputs in HXML would take an entire chapter. Instead, I’ll summarize a few other input elements and their features. #index[HXML][\<select-multiple\>] #index[HXML][\<switch\>] #index[HXML][\<date-field\>]- `<select-multiple>` works like `<select-single>`, but it supports toggling multiple options on & off. This replaces checkbox inputs in HTML. - The `<switch>` element renders an on/off switch that is common in mobile UIs - The `<date-field>` element supports entering in specific dates, and comes with a wide range of customizations for formatting, settings ranges, etc. #index[HXML][\<form\>] #index[HXML][custom elements] Two more things to mention about inputs. First is the `<form>` element. The `<form>` element is used to group together inputs for serialization. When a user takes an action that triggers a backend request, the Hyperview client will serialize all inputs in the surrounding `<form>` and include them in the request. This is true for both `GET` and `POST` requests. We will cover this in more detail when talking about behaviors later in this chapter. Also later in this chapter, I’ll talk about support for custom elements in HXML. With custom elements, you can also create your own input elements. Custom input elements allow you to build incredible powerful interactions with simple XML syntax that integrates well with the rest of HXML. ==== Styling #index[HXML][styling] So far, we haven’t mentioned how to apply styling to all of the HXML elements. We’ve seen from the Hello World app that each `<screen>` can contain a `<styles>` element. Let’s re-visit the Hello World app and fill out the `<styles>` element. #figure( caption: [UI styling example], )[ ```xml <doc xmlns="https://hyperview.org/hyperview"> <screen> <styles> <1> <style class="body" flex="1" flexDirection="column" /> <2> <style class="header" borderBottomWidth="1" borderBottomColor="#ccc" /> <style class="main" margin="24" /> <style class="h1" fontSize="32" /> <style class="info" color="blue" /> </styles> <body style="body"> <3> <header style="header"> <text style="info">My first app</text> </header> <view style="main"> <text style="h1 info">Hello World!</text> <4> </view> </body> </screen> </doc> ``` ] 1. Element encapsulating all of the styling for the screen 2. Example of a definition of a style class for "body" 3. Applying the "body" style class to a UI element 4. Example of applying multiple style classes (h1 and info) to an element You’ll note that in HXML, styling is part of the XML format, rather than using a separate language like CSS. However, we can draw some parallels between CSS rules and the `<style>` element. A CSS rule consists of a selector and declarations. In the current version of HXML, the only available selector is a class name, indicated by the `class` attribute. The rest of the attributes on the `<style>` element are declarations, consisting of properties and property values. UI elements within the `<screen>` can reference the `<style>` rules by adding the class names to their `<style>` property. Note the `<text>` element around "Hello World!" references two style classes: `h1` and `info`. The styles from the corresponding classes are merged together in the order they appear on the element. It’s worth noting that styling properties are similar to those in CSS (color, margins/padding, borders, etc). Currently, the only available layout engine is based on flexbox. Style rules can get quite verbose. For the sake of brevity, we won’t include the `<styles>` element in the rest of the examples in this chapter unless necessary. ==== Custom elements #index[HXML][custom elements] The core UI elements that ship with Hyperview are quite basic. Most mobile apps require richer elements to deliver a great user experience. Luckily, HXML can easily accommodate custom elements in its syntax. This is because HXML is really just XML, aka "Extensible Markup Language". Extensibility is already built into the format! Developers are free to define new elements and attributes to represent custom elements. Let’s see this in action with a concrete example. Assume that we want to add a map element to our Hello World app. We want the map to display a defined area, and one or more markers at specific coordinates in that area. Let’s translate these requirements into XML: - An `<area>` element will represent the area displayed by the map. To specify the area, the element will include attributes for `latitude` and `longitude` for the center of the area, and a `latitude-delta` and `longitude-delta` indicating the +/- display area around the center. - A `<marker>` element will represent a marker in the area. The coordinates of the marker will be defined by `latitude` and `longitude` attributes on the marker. Using these custom XML elements, an instance of the map in our app might look like this: #figure( caption: [Custom elements in HXML], )[ ```xml <doc xmlns="https://hyperview.org/hyperview"> <screen> <body> <view> <text>Hello World!</text> <area latitude="37.8270" longitude="122.4230" latitude-delta="0.1" longitude-delta="0.1"> <1> <marker latitude="37.8118" longitude="-122.4177" /> <2> </area> </view> </body> </screen> </doc> ``` ] 1. Custom element representing the area rendered by the map 2. Custom element representing a marker rendered at specific coordinates on the map The syntax feels right at home among the core HXML elements. However, there’s a potential problem. "area" and "marker" are pretty generic names. I could see `<area>` and `<marker>` elements being used by a customization to render charts & graphs. If our app renders both maps and charts, the HXML markup would be ambiguous. What should the client render when it sees `<area>` or `<marker>`? #index[Hyperview][XML namespaces] This is where XML namespaces come in. XML namespaces eliminate ambiguity and collisions between elements and attributes used to represent different things. Remember that the `<doc>` element declares that `https://hyperview.org/hyperview` is the default namespace for the entire document. Since no other elements define namespaces, every element in the example above is part of the `https://hyperview.org/hyperview` namespace. Let’s define a new namespace for our map elements. Since this namespace will not be the default for the document, we also need to assign the namespace to a prefix we will add to our elements: #figure[```xml <doc xmlns="https://hyperview.org/hyperview" xmlns:map="https://mycompany.com/hyperview-map"> ```] This new attribute declares that the `map:` prefix is associated with the namespace "https:\/\/mycompany.com/hyperview-map". This namespace could be anything, but remember the goal is to use something unique that won’t have collisions. Using your company/app domain is a good way to guarantee uniqueness. Now that we have a namespace and prefix, we need to use it for our elements: #figure( caption: [Namespacing the custom elements], )[ ```xml <doc xmlns="https://hyperview.org/hyperview" xmlns:map="https://mycompany.com/hyperview-map"> <1> <screen> <body> <view> <text>Hello World!</text> <map:area latitude="37.8270" longitude="122.4230" latitude-delta="0.1" longitude=delta="0.1"> <2> <map:marker latitude="37.8118" longitude="-122.4177" /> <3> </map:area> <4> </view> </body> </screen> </doc> ``` ] 1. Definition of namespace aliased to "map" 2. Adding the namespace to the "area" start tag 3. Adding the namespace to the "marker" self-closing tag 4. Adding the namespace to the "area" end tag That’s it! If we introduced a custom charting library with "area" and "marker" elements, we would create a unique namespace for those elements as well. Within the HXML doc, we could easily disambiguate `<map:area>` from `<chart:area>`. At this point you might be wondering, "how does the Hyperview client know to render a map when my doc includes \<map:area\>?" It’s true, so far we only defined the custom element format, but we haven’t implemented the element as a feature in our app. We will get into the details of implementing custom elements in the next chapter. ==== Behaviors <_behaviors> As discussed in earlier chapters, HTML supports two basic types of interactions: - Clicking a hyperlink: the client will make a GET request and render the response as a new web page. - Submitting a form: the client will (typically) make a POST request with the serialized content of the form, and render the response as a new web page. Clicking hyperlinks and submitting forms is enough to build simple web applications. But relying on just these two interactions limits our ability to build richer UIs. What if we want something to happen when the user mouses over a certain element, or perhaps when they scroll some content into the viewport? We can’t do that with basic HTML. Additionally, both clicks and form submits result in loading a full new web page. What if we only want to update a small part of the current page? This is a very common scenario in rich web applications, where users expect to fetch and update content without navigating to a new page. So with basic HTML, interactions (clicks and submits) are limited and tightly coupled to a single action (loading a new page). Of course, using JavaScript, we can extend HTML and add some new syntax to support our desired interactions. Htmx does exactly that with a new set of attributes: - Interactions can be added to any element, not just links and forms. - The interaction can be triggered via a click, submit, mouseover, or any other JavaScript event. - The actions resulting from the trigger can modify the current page, not just request a new page. By decoupling elements, triggers, and actions, htmx allows us to build rich Hypermedia-driven applications in a way that feels very compatible with HTML syntax and server-side web development. #index[HXML][behaviors] HXML takes the idea of defining interactions via triggers & actions and builds them into the spec. We call these interactions "behaviors." We use a special `<behavior>` element to define them. Here’s an example of a simple behavior that pushes a new mobile screen onto the navigation stack: #figure(caption: [Basic behavior])[ ```xml <text> <behavior <1> trigger="press" <2> action="push" <3> href="/next-screen" <4> /> Press me! </text> ``` ] 1. The element encapsulating an interaction on the parent `<text>` element. 2. The trigger that will execute the interaction, in this case pressing the `<text>` element. 3. The action that will execute when triggered, in this case pushing a new screen onto the current stack. 4. The href to load on the new screen. Let’s break down what’s happening in this example. First, we have a `<text>` element with the content "Press me!". We’ve shown `<text>` elements before in examples of HXML, so this is nothing new. But now, the `<text>` element contains a new child element, `<behavior>`. This `<behavior>` element defines an interaction on the parent `<text>` element. It contains two attributes that are required for any behavior: - `trigger`: defines the user action that triggers the behavior - `action`: defines what happens when triggered In this example, the `trigger` is set to `press`, meaning this interaction will happen when the user presses the `<text>` element. The `action` attribute is set to `push`. `push` is an action that will push a new screen onto the navigation stack. Finally, Hyperview needs to know what content to load on the newly pushed screen. This is where the `href` attribute comes in. Notice we don’t need to define the full URL. Much like in HTML, the `href` can be an absolute or relative URL. So that’s a first example of behaviors in HXML. You may be thinking this syntax seems quite verbose. Indeed, pressing elements to navigate to a new screen is one of the most common interactions in a mobile app. It would be nice to have a simpler syntax for the common case. Luckily, `trigger` and `action` attributes have default values of `press` and `push`, respectively. Therefore, they can be omitted to clean up the syntax: #figure(caption: [Basic behavior with defaults])[ ```xml <text> <behavior href="/next-screen" /> <1> Press me! </text> ``` ] 1. When pressed, this behavior will open a new screen with the given URL. This markup for the `<behavior>` will produce the same interaction as the earlier example. With the default attributes, the `<behavior>` element looks similar to an anchor `<a>` in HTML. But the full syntax achieves our goals of decoupling elements, triggers, and actions: - Behaviors can be added to any element, they are not limited to links and forms. - Behaviors can specify an explicit `trigger`, not just clicks or form submits. - Behaviors can specify an explicit `action`, not just a request for a new page. - Extra attributes like `href` provide more context for the action. Additionally, using a dedicated `<behavior>` element means a single element can define multiple behaviors. This lets us execute several actions from the same trigger. Or, we can execute different actions for different triggers on the same element. We will show examples of the power of multiple behaviors at the end of this chapter. First we need to show the variety of supported actions and triggers. ===== Actions #index[HXML][behavior actions] Behavior actions in Hyperview fall into four general categories: - Navigation actions, which load new screens and move between them - Update actions, which modify the HXML of the current screen - System actions, which interact with OS-level capabilities. - Custom actions, which can execute any code you add to the client. ====== Navigation actions #index[HXML][navigation actions] We’ve already seen the simplest type of action, `push`. We classify `push` as a "navigation action", since it’s related to navigating screens in the mobile app. Pushing a screen onto the navigation stack is just one of several navigation actions supported in Hyperview. Users also need to be able to go back to previous screens, open and close modals, switch between tabs, or jump to arbitrary screens. Each of these types of navigation is supported through a different value for the `action` attribute: - `push`: Push a new screen into the current navigation stack. This looks like a screen sliding in from the right, on top of the current screen. - `new`: Open a new navigation stack as a modal. This looks like a screen sliding in from the bottom, on top of the current screen. - `back`: This is a complement to the `push` action. It pops the current screen off of the navigation stack (sliding it to the right). - `close`: This is a complement to the `new` action. It closes the current navigation stack (sliding it down). - `reload`: Similar to a browser’s "refresh" button, this will re-request the content of the current screen. - `navigate`: This action will attempt to find a screen with the given `href` already loaded in the app. If the screen exists, the app will jump to that screen. If it doesn’t exist, it will act the same as `push`. `push`, `new`, and `navigate` all load a new screen. Thus, they require an `href` attribute so that Hyperview knows what content to request for the new screen. `back` and `close` do not load new screens, and thus do not require the `href` attribute. `reload` is an interesting case. By default, it will use the URL of the screen when re-requesting the content for the screen. However, if you want to replace the screen with a different one, you can provide an `href` attribute with `reload` on the behavior element. Let’s look at an example "widgets" app that uses several navigation actions on one screen: #figure(caption: [Navigation action examples])[ ```xml <screen> <body> <header> <text> <behavior action="back" /> <1> Back </text> <text> <behavior action="new" href="/widgets/new" /> <2> New Widget </text> </header> <text> <behavior action="reload" /> <3> Check for new widgets </text> <list> <item key="widget1"> <behavior action="push" href="/widgets/1" /> <4> </item> </list> </body> </screen> ``` ] 1. Takes the user to the previous screen 2. Opens a new modal to add a widget 3. Reloads the content of the screen, showing new widgets from the backend 4. Pushes a new screen with details for a specific widget Most screens in your app will need a way for the user to backtrack to the previous screen. This is usually done with a button in the header that uses either a "back" or "close" action, depending on how the screen was opened. In this example, we’re assuming the widgets screen was pushed onto the navigation stack, so the "back" action is appropriate. The header contains a second button that allows the user to enter data for a new widget. Pressing this button will open a modal with a "New Widget" screen. Since this "New Widget" screen will open as a modal, it will need a corresponding "close" action to dismiss itself and show our "widgets" screen again. Finally, to see more details about a specific widget, each `<item>` element contains a behavior with a "push" action. This action will push a "Widget Detail" screen onto the current navigation stack. Like in the "Widgets" screen, "Widget Detail" will need a button in the header that uses the "back" action to let the user backtrack. On the web, the browser handles basic navigation needs such as going back/forward, reloading the current page, or jumping to a bookmark. iOS and Android don’t provide this sort of universal navigation for native mobile apps. It’s on the app developers to handle this themselves. Navigation actions in HXML provide an easy but powerful way for developers to build an architecture that makes sense for their app. ====== Update actions #index[HXML][update actions] Behavior actions are not just limited to navigating between screens. They can also be used to change the content on the current screen. We call these "update actions". Much like navigation actions, update actions make a request to the backend. However, the response is not an entire HXML document, but a fragment of HXML. This fragment is added to the HXML of the current screen, resulting in an update to the UI. The `action` attribute of the `<behavior>` determines how the fragment gets incorporated into the HXML. We also need to introduce a new `target` attribute on `<behavior>` to define where the fragment gets incorporated in the existing doc. The `target` attribute is an ID reference to an existing element on the screen. Hyperview currently supports these update actions, representing different ways to incorporate the fragment into the screen: - `replace`: replaces the entire target element with the fragment - `replace-inner`: replaces the children of the target element with the fragment - `append`: adds the fragment after the last child of the target element - `prepend`: adds the fragment before the first child of the target element. Let’s look at some examples to make this more concrete. For these examples, let’s assume our backend accepts `GET` requests to `/fragment`, and the response is a fragment of HXML that looks like `<text>My fragment</text>`. #figure( caption: [Update action examples], )[ ```xml <screen> <body> <text> <behavior action="replace" href="/fragment" target="area1" /> <1> Replace </text> <view id="area1"> <text>Existing content</text> </view> <text> <behavior action="replace-inner" href="/fragment" target="area2" /> <2> Replace-inner </text> <view id="area2"> <text>Existing content</text> </view> <text> <behavior action="append" href="/fragment" target="area3" /> <3> Append </text> <view id="area3"> <text>Existing content</text> </view> <text> <behavior action="prepend" href="/fragment" target="area4" /> <4> Prepend </text> <view id="area4"> <text>Existing content</text> </view> </body> </screen> ``` ] 1. Replaces the area1 element with fetched fragment 2. Replaces the child elements of area2 with fetched fragment 3. Appends the fetched fragment to area3 4. Prepends the fetched fragment to area4 In this example, we have a screen with four buttons corresponding to the four update actions: `replace`, `replace-inner`, `append`, `prepend`. Below each button, there’s a corresponding `<view>` containing some text. Note that the `id` of each view matches the `target` on the behaviors of the corresponding button. When the user presses the first button, the Hyperview client makes a request for `/fragment`. Next, it looks for the target, ie the element with id "area1". Finally, it replaces the `<view id="area1">` element with the fetched fragment, `<text>My fragment</text>`. The existing view and text contained in that view will be replaced. To the user, it will look like "Existing content" was changed to "My fragment". In the HXML, the element `<view id="area1">` will also be gone. The second button behaves in a similar way to the first one. However, the `replace-inner` action does not remove the target element from the screen, it only replaces the children. This means the resulting markup will look like `<view id="area2"><text>My fragment</text></view>`. The third and fourth buttons do not remove any content from the screen. Instead, the fragment will be added either after (in the case of `append`) or before (`prepend`) the children of the target element. For completeness, let’s look at the state of the screen after a user presses all four buttons: #figure( caption: [Update actions, after pressing buttons], )[ ```xml <screen> <body> <text> <behavior action="replace" href="/fragment" target="area1" /> <1> Replace </text> <text>My fragment</text> <text> <behavior action="replace-inner" href="/fragment" target="area2" /> <2> Replace-inner </text> <view id="area2"> <text>My fragment</text> </view> <text> <behavior action="append" href="/fragment" target="area3" /> <3> Append </text> <view id="area3"> <text>Existing content</text> <text>My fragment</text> </view> <text> <behavior action="prepend" href="/fragment" target="area4" /> <4> Prepend </text> <view id="area4"> <text>My fragment</text> <text>Existing content</text> </view> </body> </screen> ``` ] 1. Fragment completely replaced the target using `replace` action 2. Fragment replaced the children of the target using `replace-inner` action 3. Fragment added as last child of the target using `append` action 4. fragment added as the first child of the target using `prepend` action The examples above show actions making `GET` requests to the backend. But these actions can also make `POST` requests by setting `verb="post"` on the `<behavior>` element. For both `GET` and `POST` requests, the data from the parent `<form>` element will be serialized and included in the request. For `GET` requests, the content will be URL-encoded and added as query params. For `POST` requests, the content will be form-URL encoded and set on the request body. Since they support `POST` and form data, update actions are often used to send data to the backend. So far, our example of update actions require getting new content from the backend and adding it to the screen. But sometimes we just want to change the state of existing elements. The most common state to change for an element is its visibility. Hyperview has `hide`, `show`, and `toggle` actions that do just that. Like the other update actions, `hide`, `show`, and `toggle` use the `target` attribute to apply the action to an element on the current screen. #figure(caption: [Show, hide, and toggle actions])[ ```xml <screen> <body> <text> <behavior action="hide" target="area" /> <1> Hide </text> <text> <behavior action="show" target="area" /> <2> Show </text> <text> <behavior action="toggle" target="area" /> <3> Toggle </text> <view id="area"> <4> <text>My fragment</text> </view> </body> </screen> ``` ] 1. Hides the element with id "area". 2. Shows the element with id "area". 3. Toggles the visibility of the element with id "area". 4. The element targeted by the actions. In this example, the three buttons labeled "Hide", "Show", and "Toggle" will modify the display state of the `<view>` with ID "area". Pressing "Hide" multiple times will have no affect once the view is hidden. Likewise, pressing "Show" multiple times will have no affect once the view is showing. Pressing "Toggle" will keep flipping the visibility status of the element between showing and hidden. Hyperview comes with other actions that modify the existing HXML. We won’t cover them in detail, but I’ll mention them briefly here: - `set-value`: this action can set the value of an input element such as `<text-field>`, `<switch>`, `<select-single>`, etc. - `select-all` and `unselect-all` work with the `<select-multiple>` element to select/deselect all options. ====== System actions #index[Hyperview][system actions] Some standard Hyperview actions don’t interact with the HXML at all. Instead, they expose functionality provided by the mobile OS. For example, both Android and iOS support a system-level "Share" UI. This UI allows sharing URLs and messages from one app to another app. Hyperview has a `share` action to support this interaction. It involves a custom namespace, and share-specific attributes. #figure(caption: [System share action])[ ```xml <behavior xmlns:share="https://instawork.com/hyperview-share" <1> trigger="press" action="share" <2> share:url="https://www.instawork.com" <3> share:message="Check out this website!" <4> /> ``` ] 1. Defines the namespace for the share action. 2. The action of this behavior will bring up the share sheet. 3. URL to be shared. 4. Message to be shared. We’ve seen XML namespaces when talking about custom elements. Here, we are using a namespace for the `url` and `message` attributes on the `<behavior>`. These attribute names are generic and likely used by other components and behaviors, so the namespace ensures there will be no ambiguity. When pressed, the "share" action will trigger. The values of the `url` and `message` attributes will be passed to the system Share UI. From there, the user will be able to share the URL & message via SMS, email, or other communication apps. The `share` action shows how a behavior action can use custom attributes to pass along extra data needed for the interactions. But some actions require even more structured data. This can be provided via child elements on the `<behavior>`. Hyperview uses this to implement the `alert` action. The `alert` action shows a customized system-level dialog box. This dialog needs configuration for a title and message, but also for customized buttons. Each button needs to then trigger another behavior when pressed. This level of configuration cannot be done with just attributes, so we use custom child elements to represent the behavior of each button. #figure( caption: [System alert action], )[ ```xml <behavior xmlns:alert="https://hyperview.org/hyperview-alert" <1> trigger="press" action="alert" <2> alert:title="Continue to next screen?" <3> alert:message= "Are you sure you want to navigateto the next screen?" <4> > <alert:option alert:label="Continue"> <5> <behavior action="push" href="/next" /> <6> </alert:option> <alert:option alert:label="Cancel" /> <7> </behavior> ``` ] 1. Defines the namespace for the alert action. 2. The action of this behavior will bring up a system dialog box. 3. Title of the dialog box. 4. Content of the dialog box. 5. A "continue" option in the dialog box 6. When "continue" is pressed, push a new screen onto the navigation stack. 7. A "cancel" option that dismisses the dialog box. Like the `share` behavior, `alert` uses a namespace to define some attributes and elements. The `<behavior>` element itself contains the `title` and `message` attributes for the dialog box. The button options for the dialog are defined using a new `<option>` element nested in the `<behavior>`. Notice that each `<option>` element has a label, and then optionally contains a `<behavior>` itself! This structure of the HXML allows the system dialog to trigger any interaction that can be defined as a `<behavior>`. In the example above, pressing the "Continue" button will open a new screen. But we could just as easily trigger an update action to change the current screen. We could even open a share sheet, or a second dialog box. But please don’t do that in a real app! With great power comes great responsibility. ====== Custom actions #index[Hyperview][custom actions] You can build a lot of mobile UIs with Hyperview’s standard navigation, update, and system actions. But the standard set may not cover all interactions you will need for your mobile app. Luckily, the action system is extensible. In the same way you can add custom elements to Hyperview, you can also add custom behavior actions. Custom actions have a similar syntax to the `share` and `alert` actions, using namespaces for attributes that pass along extra data. Custom actions also have full access to the HXML of the current screen, so they can modify the state or add/remove elements from the current screen. In the next chapter, we will create a custom behavior action to enhance our mobile contacts app. ===== Triggers #index[Hyperview][triggers] We’ve already seen the simplest type of trigger, a `press` on an element. Hyperview supports many other common triggers used in mobile apps. ====== Long-press <_long_press> Closely related to a press is a long-press. A behavior with `trigger="longPress"` will trigger when the user presses and holds on the element. "Long-press" interactions are often used for shortcuts and power features. Sometimes, elements will support different actions for both a `press` and `longPress`. This is done using multiple `<behavior>` elements on the same UI element. #figure( caption: [Long-press trigger example], )[ ```xml <text> <behavior trigger="press" action="push" href="/next-screen" /> <1> <behavior trigger="longPress" <2> action="push" href="/secret-screen" /> Press (or long-press) me! </text> ``` ] 1. Normal press will open the next screen. 2. Long press will open a different screen. In this example, a normal press will open a new screen and request content from `/next-screen`. However, a long press will open a new screen with content from `/secret-screen`. This is a contrived example for the sake of brevity. A better UX would be for the long-press to bring up a contextual menu of shortcuts and advanced options. This could be achieved by using `action="alert"` and opening a system dialog box with the shortcuts. ====== Load <_load> Sometimes we want an action to trigger as soon as the screen loads. `trigger="load"` does exactly this. One use case is to quickly load a shell of the screen, and then fill in the main content on the screen with a second update action. #figure( caption: [Load trigger example], )[ ```xml <body> <view> <text>My app</text> <view id="container"> <1> <behavior trigger="load" action="replace" href="/content" target="container"> <2> <text>Loading...</text> <3> </view> </view> </body> ``` ] 1. Container element without the actual content 2. Behavior that immediately fires off a request for /content to replace the container 3. Loading UI that appears until the content is fetched and replaced. In this example, We load a screen with a heading ("My app") but no content. Instead, we show a `<view>` with ID "container" and some "Loading…​" text. As soon as this screen loads, the behavior with `trigger=load` fires off the `replace` action. It requests content from the `/content` path and replaces the container view with the response. ====== Visible <_visible> Unlike `load`, the `visible` trigger will only execute the behavior when the element with the behavior is scrolled into the viewport on the mobile device. The `visible` action is commonly used to implement an infinite-scroll interaction on a `<list>` of `<item>` elements. The last item in the list includes a behavior with `trigger="visible"`. The `append` action will fetch the next page of items and append them to the list. ====== Refresh <_refresh> This trigger captures a "pull to refresh" action on `<list>` and `<view>` items. This interaction is associated with fetching up-to-date content from the backend. Thus, it’s typically paired with an update or reload action to show the latest data on the screen. #figure(caption: [Pull-to-refresh trigger example])[ ```xml <body> <view scroll="true"> <behavior trigger="refresh" action="reload" /> <1> <text>No items yet</text> </view> </body> ``` ] 1. When the view is pulled down to refresh, reload the screen. Note that adding a behavior with `trigger="refresh"` to a `<view>` or `<list>` will add the pull-to-refresh interaction to the element, including showing a spinner as the element is pulled down. ====== Focus, blur, and change <_focus_blur_and_change> These triggers are related to interactions with input elements. Thus, they will only trigger behaviors attached to elements like `<text-field>`. `focus` and `blur` will trigger when the user focuses and blurs the input element, respectively. `change` will trigger when the value of the input element changes, like when the user types a letter in a text field. These triggers are often used with behaviors that need to perform some server-side validation on the form fields. For example, when the user types in a username and then blurs the field, a behavior could trigger on `blur` to make a request to the backend and check for uniqueness of the username. If the entered username is not unique, the response could include an error message letting the user know they need to pick a different username. ===== Using multiple behaviors #index[HXML][multiple behaviors] Most of the examples shown above attach a single `<behavior>` to an element. But there’s no such limitation in Hyperview; elements can define multiple behaviors. We already saw an example where a single element had different actions triggered on `press` and `longPress`. But we can also trigger multiple actions on the same trigger. In this admittedly contrived example, we want to hide two elements on the screen when pressing the "Hide" button. The two elements are far apart in the HXML, and cannot be hidden by hiding a common ancestor element. But, we can trigger two behaviors at the same time, each one executing a "hide" action but targeting different elements. #figure(caption: [Multiple behaviors triggering on press])[ ```xml <screen> <body> <text id="area1">Area 1</text> <text> <behavior trigger="press" action="hide" target="area1" /> <1> <behavior trigger="press" action="hide" target="area2" /> <2> Hide </text> <text id="area2">Area 2</text> </body> </screen> ``` ] 1. Hide element with ID "area1" when pressed. 2. Hide element with ID "area2" when pressed. Hyperview processes behaviors in the order they appear in the markup. In this case, the element with ID "area1" will be hidden first, followed by the element with ID "area2". Since "hide" is an instantaneous action (ie, it doesn’t make an HTTP request), both elements will appear to hide simultaneously. But what if we triggered two actions that depend on responses from HTTP requests (like "replace-inner")? In that case, each individual action is processed as soon as Hyperview receives the HTTP response. Depending on network latency, the two actions could take effect in any order, and they are not guaranteed to be applied simultaneously. We’ve seen elements with multiple behaviors and different triggers. And we’ve seen elements with multiple behaviors with the same trigger. These concepts can be mixed together too. It’s not unusual for a production Hyperview app to contain several behaviors, some triggering together and others triggering on different interactions. Using multiple behaviors with custom actions keeps HXML declarative, without sacrificing functionality. ==== Summary <_summary> We’re covering a lot of new concepts here, and this introduction to HXML just scratches the surface. To learn more about HXML, we recommend consulting the #link( "https://hyperview.org/docs/reference_index", )[official reference documentation]. For now, we hope you come away with a few key takeaways. First, HXML looks and feels similar to HTML. Web developers comfortable with server-side rendering frameworks can use the same techniques to write HXML. In addition to basic UI elements (`<view>`, `<text>`, `<image>`), HXML specifies elements to implement mobile-specific UIs. This includes layout patterns (`<screen>`, `<list>`, `<section-list>`) and input elements (`<switch>`, `<select-single>`, `<select-multiple>`). Second, interactions in HXML are defined using behaviors. Inspired by htmx, `<behavior>` elements decouple user interactions (triggers) from the resulting actions. There are three broad categories of behavior actions: - Navigation actions (`push`, `back`) enable navigating between the screens of a mobile app - Update actions (`replace`, `append`) enable updating a screen with new fragments of HXML requested from the server. - System actions (`alert`, `share`) enable interacting with system-level functionality on iOS and Android. Finally, HXML itself was designed for customization. Developers can define custom elements and custom behavior actions to expand the possible user interactions with their apps. === Hypermedia, for Mobile <_hypermedia_for_mobile> There is a strong case for Hypermedia-Driven Applications on mobile. Mobile app platforms push developers towards a thick-client architecture. But apps that use a thick client suffer from the same problems as SPAs on the web. Using the hypermedia architecture for mobile apps can solve these problems. Hyperview, based on a new format called HXML, offers a path here. It provides an open-source mobile thin client to render HXML. And HXML opens a toolkit of elements and patterns that correspond to mobile UIs. Developers can evolve Hyperview to suit their apps' requirements, while fully embracing the hypermedia architecture. That’s a win. Yes, hypermedia can work for mobile apps, too. In the next two chapters we’ll show how by turning the Contact.app web application into a native mobile app using Hyperview. #html-note( label: [Hypermedia Notes], )[Maximize Your Server-Side Strengths][ In the Hyperview sections of the book, since we aren’t using HTML, we are going to make broader observations on hypermedia rather than offer HTML-specific advice and thoughts. A big advantage of the hypermedia-driven approach is that it makes the server-side environment far more important when building your web application. Rather than simply producing JSON, your back end is an integral component in the user experience of your hypermedia application. Because of this, it makes sense to look deeply into the functionality available there. Many older web frameworks, for example, have incredibly deep functionality available around producing HTML. Features like server-side caching can make the difference between an incredibly snappy web application and a sluggish user experience. Take time to learn all the tools available to you. A good rule of thumb is to shoot to have server responses in your hypermedia-driven application take less than 100ms to complete, and mature server-side frameworks have tools to help make this happen. Server-side environments often have extremely mature mechanisms for factoring (or organizing) your code properly. The Model/View/Controller pattern is well-developed in most environments, and tools like modules, packages, etc. provide an excellent way to organize your code. Whereas today’s SPA and mobile user interfaces are typically organized via components, hypermedia-driven applications are typically organized via template inclusion, where the server-side templates are broken up according to the hypermedia-rendering needs of the application, and then included in one another as needed. This tends to lead to fewer, chunkier files than you would find in a component-based application. Another technology to look for are Template Fragments, which allow you to render only part of a template file. This can reduce even further the number of template files required for your server-side application. A related tip is to take advantage of direct access to the data store. When an application is built using a thick client approach, the data store typically lives behind a data API (e.g. JSON). This level of indirection often prevents front end developers from being able to take full advantage of the tools available in the data store. GraphQL, for example, can help address this issue, but comes with security-related issues that do not appear to be well understood by many developers. When you produce your hypermedia on the server side, on the other hand, the developer creating that hypermedia can have full access to the data store and take advantage of, for example, joins and aggregation functions in SQL stores. This puts far more expressive power directly in the hands of the developer producing the final hypermedia. Because your hypermedia API can be structured around your UI needs, you can tune each endpoint to issue as few data store requests as possible. A good rule of thumb is that every request to your server should shoot to have three or fewer data-store accesses. If you follow this rule of thumb, your hypermedia-driven application should be extremely snappy. ]
https://github.com/ericthomasca/resume
https://raw.githubusercontent.com/ericthomasca/resume/main/README.md
markdown
# <NAME>' Resume This resume is generated using [typst](https://github.com/mintyfrankie/brilliant-CV), a TypeScript-based resume generator inspired by the brilliant-CV template created by [mintyfrankie](https://github.com/mintyfrankie/brilliant-CV). For customization instructions and more details about the template, please refer to the [brilliant-CV repository](https://github.com/mintyfrankie/brilliant-CV).
https://github.com/C-Block-Language/specifications
https://raw.githubusercontent.com/C-Block-Language/specifications/main/src/template.typ
typst
MIT License
#let Document( title: [Paper Title], authors: (), abstract: none, index-terms: (), paper-size: "us-letter", bibliography-file: none, body ) = { set document(title: title, author: authors.map(author => author.name)) set text(font: "STIX Two Text", size: 10pt) set page( paper: paper-size, margin: if paper-size == "a4" { (x: 41.5pt, top: 80.51pt, bottom: 89.51pt) } else { ( x: (50pt / 216mm) * 100%, top: (55pt / 279mm) * 100%, bottom: (64pt / 279mm) * 100%, ) } ) set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) show ref: it => { if it.element != none and it.element.func() == math.equation { link(it.element.location(), numbering( it.element.numbering, ..counter(math.equation).at(it.element.location()) )) } else { it } } set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) set heading(numbering: "I.A.1.") show heading: it => locate(loc => { let levels = counter(heading).at(loc) let deepest = if levels != () { levels.last() } else { 1 } set text(10pt, weight: 400) if it.level == 1 [ #let is-ack = it.body in ([Acknowledgment], [Acknowledgement]) #set align(center) #set text(if is-ack { 10pt } else { 12pt }) #show: smallcaps #v(20pt, weak: true) #if it.numbering != none and not is-ack { numbering("I.", deepest) h(7pt, weak: true) } #it.body #v(13.75pt, weak: true) ] else if it.level == 2 [ #set par(first-line-indent: 0pt) #set text(style: "italic") #v(10pt, weak: true) #if it.numbering != none { numbering("A.", deepest) h(7pt, weak: true) } #it.body #v(10pt, weak: true) ] else [ #if it.level == 3 { numbering("1)", deepest) [ ] } _#(it.body):_ ] }) v(3pt, weak: true) align(center, text(18pt, title)) v(8.35mm, weak: true) for i in range(calc.ceil(authors.len() / 3)) { let end = calc.min((i + 1) * 3, authors.len()) let is-last = authors.len() == end let slice = authors.slice(i * 3, end) grid( columns: slice.len() * (1fr,), gutter: 12pt, ..slice.map(author => align(center, { text(12pt, author.name) if "department" in author [ \ #emph(author.department) ] if "organization" in author [ \ #emph(author.organization) ] if "location" in author [ \ #author.location ] if "email" in author [ \ #link("mailto:" + author.email) ] })) ) if not is-last { v(16pt, weak: true) } } v(40pt, weak: true) show: columns.with(2, gutter: 12pt) set par(justify: true, first-line-indent: 1em) show par: set block(spacing: 0.65em) if abstract != none [ #set text(weight: 700) #h(1em) _Abstract_---#abstract #if index-terms != () [ #h(1em)_Index terms_---#index-terms.join(", ") ] #v(2pt) ] body }
https://github.com/coco33920/.files
https://raw.githubusercontent.com/coco33920/.files/mistress/typst_templates/fiction/template.typ
typst
// This function gets your whole document as its `body` and formats // it as a simple fiction book. #let book( // The book's title. title: "Book title", // The book's author. author: "Author", // The paper size to use. paper: "iso-b5", // A dedication to display on the third page. dedication: none, // Details about the book's publisher that are // display on the second page. publishing-info: none, // The book's content. body, ) = { // Set the document's metadata. set document(title: title, author: author) // Set the body font. TeX Gyre Pagella is a free alternative // to Palatino. set text(font: "TeX Gyre Pagella") // Configure the page properties. set page( paper: paper, margin: (bottom: 1.75cm, top: 2.25cm), ) // The first page. page(align(center + horizon)[ #text(2em)[*#title*] #v(2em, weak: true) #text(1.6em, author) ]) // Display publisher info at the bottom of the second page. if publishing-info != none { align(center + bottom, text(0.8em, publishing-info)) } pagebreak() // Display the dedication at the top of the third page. if dedication != none { v(15%) align(center, strong(dedication)) } // Books like their empty pages. pagebreak(to: "odd") // Configure paragraph properties. set par(leading: 0.78em, first-line-indent: 12pt, justify: true) show par: set block(spacing: 0.78em) // Start with a chapter outline. outline(title: [Chapters]) // Configure page properties. set page( numbering: "1", // The header always contains the book title on odd pages and // the chapter title on even pages, unless the page is one // the starts a chapter (the chapter title is obvious then). header: locate(loc => { // Are we on an odd page? let i = counter(page).at(loc).first() if calc.odd(i) { return text(0.95em, smallcaps(title)) } // Are we on a page that starts a chapter? (We also check // the previous page because some headings contain pagebreaks.) let all = query(heading, loc) if all.any(it => it.location().page() in (i - 1, i)) { return } // Find the heading of the section we are currently in. let before = query(selector(heading).before(loc), loc) if before != () { align(right, text(0.95em, smallcaps(before.last().body))) } }), ) // Configure chapter headings. show heading.where(level: 1): it => { // Always start on odd pages. pagebreak(to: "odd") // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } v(5%) text(2em, weight: 700, block([#number #it.body])) v(1.25em) } show heading: set text(11pt, weight: 400) body }
https://github.com/rabotaem-incorporated/probability-theory-notes
https://raw.githubusercontent.com/rabotaem-incorporated/probability-theory-notes/master/sections/02-general/06-generating-functions.typ
typst
#import "../../utils/core.typ": * == Производящие функции #def[ Пусть $xi$ --- случайная величина, принимающая неотрицательные целые значения. Вероятность $P(xi = k)$ полностью определяет распределение. _Производящей функцией случайной величины $xi$_ называется $ G_xi (t) := sum_(k = 0)^oo P(xi = k) t^k. $ ] #props[ 1. $G_xi (1) = 1$. 2. $G_xi (t) = E t^xi$. 3. Ряд абсолютно сходится при $abs(t) <= 1$. 4. $G'_xi (1) = E xi$. 5. $E xi^2 = G''_xi (1) + G'_xi (1)$ (а значит $D xi = G''_xi (1) + G'_xi (1) - (G'_xi (1))^2$). 6. Если $xi$ и $eta$ независимы, то $G_(xi + eta) (t) = G_xi (t) G_eta (t)$. Если $xi_1$, $xi_2$, ..., $xi_n$ независимы, то $G_(xi_1 + xi_2 + ... + xi_n) (t) = G_xi_1 (t) G_xi_2 (t) ... G_xi_n (t)$. ] #proof[ 1. Очевидно. 2. $E t^xi = integral_RR t^x dif P_xi (x) = sum_(k = 0)^oo P(xi = k) dot t^k$. 3. Потому что в единице сходится. 4. $G'_xi (t) = sum_(k = 0)^oo k P(xi = k) t^(k - 1) ==> G'_xi (1) = sum_(k = 0)^oo k P(xi = k) = E xi$. 5. $G''_xi (t) = sum_(k = 0)^oo k (k - 1) P(xi = k) t^(k - 2) ==> G''_xi (1) = sum_(k = 0)^oo k (k - 1) P(xi = k)$. Таким образом, $G''_xi (1) = E xi^2 - E xi$. 6. $G_(xi + eta) (t) = E t^(xi + eta) = E(t^xi t^eta) = E t^xi E t^eta = G_xi (t) G_eta (t)$. Для $n$ по индукции. ] #example[ Рассмотрим дискретное равномерное распределение ${0, 1, 2, ..., n - 1}$. Тогда $ G_xi (t) = (1 + t + t^2 + ... + t^(n - 1)) / n = 1/n dot (1 - t^n) / (1 - t). $ Чтобы посчитать матожидание и дисперсию, надо подставить сюда единицу, но мы не можем. Давайте заменим $t$ на $1 + s$: $ G_xi (1 + s) = ((1 + s)^n - 1)/(n s) = sum_(k = 1)^n C_n^k/n s^(k - 1). $ И теперь, $ G'_xi (1) = C_n^2/n = (n - 1)/2, G''_xi (1) = 2 C_n^3/n = (2 n (n - 1) (n - 2))/(6 n) = ((n - 1)(n - 2))/3. $ Наконец, $ D xi = ((n - 1)(n - 2))/3 + (n - 1)/2 - (n-1)^2/4 = (n^2 - 1)/12. $ ] #example(name: "<NAME>")[ Пусть имеется 3 кубика. С какой вероятностью в сумме выпадает 10? Пусть $xi_1$, $xi_2$ и $xi_3$ --- значения на кубиках. Тогда $ G_xi (t) = (t + t^2 + t^3 + t^4 + t^5 + t^6)/6 = (t(1 - t^6))/(6 (1 - t)), $ и $ G_(xi_1 + xi_2 + xi_3) (t) = G_xi (t)^3 = (t(1 - t^6))^3/(6^3 (1 - t)^3) = 1/6^3 dot (t^3 - 3 t^9 + 3 t^15 - t^21) sum_(n = 0)^oo 3^overline(n) / n! t^n, $ так как $1/(1 - t)^3 = sum_(n = 0)^oo 3^overline(n)/n! t^n$. Коэффициент перед $t^10$ это $ 1/6^3 (3^overline(7)/7! - 3 dot (3^overline(1))/1!) = 1/6^3 ((3 dot 4 dot ... dot 9) / 7! - 9) = 1/6^3 dot ((8 dot 9)/2 - 9) = 27/6^3 = 1/8. $ ]
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/program-program-structure/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Program: Program Structure", type: "program", date: datetime(year: 2023, month: 8, day: 12), author: "<NAME>", witness: "Violet Ridge", ) During Spin Up we had to have a large amount of boilerplate for each state machine we wanted to create. In order to fix this problem we've made an abstract StateMachine class that the subsystems can inherit. This means that we can define the state machine structure once, and then use it in a bunch of other places. This solution was inspired by Theo from team 7842B #footnote( link("https://theol0403.github.io/7842B-Journal/2019-10-16/statemachine/"), ), and Ryan from team 4253B #footnote( link( "https://github.com/Ryan4253/RaidZeroLib/blob/bb9f94f087cae19f22a3d8048642b198f45b7fa1/include/RaidZeroLib/Utility/StateMachine.hpp#L1", ), ) This solution uses a mutual exclusion #footnote("See glossary.") (mutex) in order to restrict access to the state to one task at a time. This makes the state safe from data races, in which multiple tasks race to read or modify the same variable. ```cpp // state_machine.hpp #pragma once #include "pros/rtos.hpp" #include "pros/screen.hpp" namespace lib { template <typename State, State init_state = State::Idle> class StateMachine { private: State state = init_state; pros::Mutex state_lock; // Define the mutex public: StateMachine() {} State get_state() { state_lock.take(); // Only one task can take a mutex at a time State current_state = state; state_lock.give(); // Once its given back another task can take it return current_state; } void set_state(State new_state) { state_lock.take(); state = new_state; state_lock.give(); } }; } // namespace lib ``` We took the same approach for the task wrapper and made it it's own class. This is also inspired by Theo. #footnote( link( "// https://theol0403.github.io/7842B-Journal/2019-10-18/task-wrapper/", ), ) ```cpp // task_wrapper.hpp #pragma once #include <cstdio> #include <memory> #include "pros/rtos.hpp" namespace lib { class TaskWrapper { protected: virtual void loop() = 0; // Will be overridden later public: void start_task(); private: pros::Task *task{nullptr}; // We don't want the task to start right away }; } // namespace lib ``` ```cpp // task_wrapper.cpp #include "lib/utils/task-wrapper.hpp" namespace lib { void TaskWrapper::start_task() { if (task == nullptr) { task = new pros::Task([this] { while (true) { this->loop(); } }); } } }; // namespace lib ``` With these two defined we can now define a subsystem. We made a mock catapult to showcase our new capabilities. ```hpp // catapult.hpp #pragma once #include <memory> #include "lib/utils/state_machine.hpp" #include "lib/utils/task-wrapper.hpp" #include "pros/motors.hpp" namespace lib { enum class CatapultState { Idle, Loading, Ready, Firing }; class Catapult : public lib::StateMachine<CatapultState>, public TaskWrapper { // Inherit both classes here public: Catapult(std::shared_ptr<pros::Motor> i_motor); // We take a pointer to the motor instead of a port to // avoid having to configure it ~Catapult(); private: std::shared_ptr<pros::Motor> motor; protected: void loop() override; }; } // namespace lib ``` ```cpp // catapult.cpp #include "lib/subsystems/catapult.hpp" #include <cstdio> #include "pros/rtos.hpp" namespace lib { Catapult::Catapult(std::shared_ptr<pros::Motor> i_motor) : motor(i_motor){}; Catapult::~Catapult(){}; void Catapult::loop() { while (true) { if (get_state() == CatapultState::Idle) { // State machine printf("just chillin\n"); } pros::delay(20); } }; } // namespace lib ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying-aqua/0.3.3/README.md
markdown
Apache License 2.0
# [Touying](https://github.com/touying-typ/touying) ![logo](https://github.com/touying-typ/touying/assets/34951714/2aa394d3-2319-4572-aef7-ed3c14b09846) [Touying](https://github.com/touying-typ/touying) (投影 in chinese, /tóuyǐng/, meaning projection) is a powerful and efficient package for creating presentation slides in Typst. Partial code is inherited from [Polylux](https://github.com/andreasKroepelin/polylux). Therefore, many concepts and APIs remain consistent with Polylux. Touying provides an object-oriented programming (OOP) style syntax, allowing the simulation of "global variables" through a global singleton. This makes it easy to write themes. Touying does not rely on `counter` and `locate` to implement `#pause`, resulting in better performance. If you like it, consider [giving a star on GitHub](https://github.com/touying-typ/touying). Touying is a community-driven project, feel free to suggest any ideas and contribute. [![Book badge](https://img.shields.io/badge/docs-book-green)](https://touying-typ.github.io/touying/) ![GitHub](https://img.shields.io/github/license/touying-typ/touying) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/touying-typ/touying) ![GitHub Repo stars](https://img.shields.io/github/stars/touying-typ/touying) ![Themes badge](https://img.shields.io/badge/themes-5-aqua) ## Document Read [the document](https://touying-typ.github.io/touying/) to learn all about Touying. This documentation is powered by [Docusaurus](https://docusaurus.io/). We will maintain **English** and **Chinese** versions of the documentation for Touying, and for each major version, we will maintain a documentation copy. This allows you to easily refer to old versions of the Touying documentation and migrate to new versions. ## Special Features 1. `#pause` and `#meanwhile` Marks [document](https://touying-typ.github.io/touying/docs/dynamic/simple) ```typst #slide[ First #pause Second #meanwhile Third #pause Fourth ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/24ca19a3-b27c-4d31-ab75-09c37911e6ac) 2. Dewdrop Theme Navigation Bar [document](https://touying-typ.github.io/touying/docs/themes/dewdrop) ![image](https://github.com/touying-typ/touying/assets/34951714/0426516d-aa3c-4b7a-b7b6-2d5d276fb971) 3. `touying-equation` Math Equation Animation [document](https://touying-typ.github.io/touying/docs/dynamic/equation) ![image](https://github.com/touying-typ/touying/assets/34951714/8640fe0a-95e4-46ac-b570-c8c79f993de4) 4. `touying-reducer` Cetz and Fletcher Animations [document](https://touying-typ.github.io/touying/docs/dynamic/other) ![image](https://github.com/touying-typ/touying/assets/34951714/9ba71f54-2a5d-4144-996c-4a42833cc5cc) 5. `#show: slides` Style and `#slide[..]` Style 6. Semi-transparent Cover Mode [document](https://touying-typ.github.io/touying/docs/dynamic/cover) ![image](https://github.com/touying-typ/touying/assets/34951714/22a9ea66-c8b5-431e-a52c-2c8ca3f18e49) ## Quick start Before you begin, make sure you have installed the Typst environment. If not, you can use the [Web App](https://typst.app/) or the Typst LSP and Typst Preview plugins for VS Code. To use Touying, you only need to include the following code in your document: ```typst #import "@preview/touying:0.3.3": * #let s = themes.simple.register(aspect-ratio: "16-9") #let (init, slides) = utils.methods(s) #show: init #let (slide, empty-slide) = utils.slides(s) #show: slides = Title == First Slide Hello, Touying! #pause Hello, Typst! ``` ![image](https://github.com/touying-typ/touying/assets/34951714/f5bdbf8f-7bf9-45fd-9923-0fa5d66450b2) It's simple. Congratulations on creating your first Touying slide! 🎉 **Tip:** You can use Typst syntax like `#import "config.typ": *` or `#include "content.typ"` to implement Touying's multi-file architecture. ## More Complex Examples In fact, Touying provides various styles for writing slides. For example, the above example uses first-level and second-level titles to create new slides. However, you can also use the `#slide[..]` format to access more powerful features provided by Touying. ```typst #import "@preview/touying:0.3.3": * #import "@preview/cetz:0.2.1" #import "@preview/fletcher:0.4.2" as fletcher: node, edge // cetz and fletcher bindings for touying #let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true)) #let fletcher-diagram = touying-reducer.with(reduce: (arr, ..args) => fletcher.diagram(..args, ..arr)) // Register university theme // You can remove the theme registration or replace other themes // it can still work normally #let s = themes.university.register(aspect-ratio: "16-9") // Global information configuration #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) // Extract methods #let (init, slides, touying-outline, alert) = utils.methods(s) #show: init #show strong: alert // Extract slide functions #let (slide, empty-slide) = utils.slides(s) #show: slides = Animation == Simple Animation #slide[ We can use `#pause` to #pause display something later. #pause Just like this. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to #pause display other content synchronously. ] == Complex Animation #slide(repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) At subslide #self.subslide, we can use #uncover("2-")[`#uncover` function] for reserving space, use #only("2-")[`#only` function] for not reserving space, #alternatives[call `#only` multiple times \u{2717}][use `#alternatives` function #sym.checkmark] for choosing one of the alternatives. ]) == Math Equation Animation #slide[ Touying equation with `pause`: #touying-equation(` f(x) &= pause x^2 + 2x + 1 \ &= pause (x + 1)^2 \ `) #meanwhile Here, #pause we have the expression of $f(x)$. #pause By factorizing, we can obtain this result. ] == CeTZ Animation #slide[ CeTZ Animation in Touying: #cetz-canvas({ import cetz.draw: * rect((0,0), (5,5)) (pause,) rect((0,0), (1,1)) rect((1,1), (2,2)) rect((2,2), (3,3)) (pause,) line((0,0), (2.5, 2.5), name: "line") }) ] == Fletcher Animation #slide[ Fletcher Animation in Touying: #fletcher-diagram( node-stroke: .1em, node-fill: gradient.radial(blue.lighten(80%), blue, center: (30%, 20%), radius: 80%), spacing: 4em, edge((-1,0), "r", "-|>", `open(path)`, label-pos: 0, label-side: center), node((0,0), `reading`, radius: 2em), edge((0,0), (0,0), `read()`, "--|>", bend: 130deg), pause, edge(`read()`, "-|>"), node((1,0), `eof`, radius: 2em), pause, edge(`close()`, "-|>"), node((2,0), `closed`, radius: 2em, extrude: (-2.5, 0)), edge((0,0), (2,0), `close()`, "-|>", bend: -40deg), ) ] = Others == Side-by-side #slide[ First column. ][ Second column. ] == Setting #slide(setting: body => { set text(fill: blue) body })[ This slide has blue text. ] == Multiple Pages #slide[ #lorem(200) ] // appendix by freezing last-slide-number #let s = (s.methods.appendix)(self: s) #let (slide,) = utils.slides(s) == Appendix #slide[ Please pay attention to the current slide number. ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/fcecb505-d2d1-4e36-945a-225f4661a694) ## Acknowledgements Thanks to... - [@andreasKroepelin](https://github.com/andreasKroepelin) for the `polylux` package - [@Enivex](https://github.com/Enivex) for the `metropolis` theme - [@drupol](https://github.com/drupol) for the `university` theme - [@pride7](https://github.com/pride7) for the `aqua` theme - [@ntjess](https://github.com/ntjess) for contributing to `fit-to-height`, `fit-to-width` and `cover-with-rect`
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/conf.typ
typst
#import "@preview/ctheorems:1.1.2": * #import "@preview/polytonoi:0.1.0": * #import "@preview/ouset:0.2.0": * #let gk = ptgk #let theorem = thmbox("theorem", "Теорема", fill: rgb("#eeffee")) #let proposition = thmbox("proposition", "Утверждение", fill: rgb("#eeffee")) #let lemma = thmbox("lemma", "Лемма", fill: rgb("#eeffee")) #let corollary = thmplain("corollary", "Следствие", base: "theorem", titlefmt: strong) #let definition = thmbox("definition", "Определение", inset: (x: 1.2em, top: 1em)) #let note = thmbox("note", "Замечание", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Пример").with(numbering: none) #let proof = thmproof("proof", "Доказательство") #let seq(idx: "n", start: "1", end: $oo$, name) = ${name_idx}_(idx = start)^end$ #let eq(cont) = align(center)[ #cont ] #let weak = $overset(->, w)$ #let res = $op("res")$ #let epigraph(phrase, author) = align(right)[ #text(font: "DejaVu Sans Mono")[ #phrase ] #line() #text(style: "italic")[ #author ] ] #let conf(title, doc) = { set page(paper: "a4", numbering: "1", header: align(right + horizon, title)) set par(leading: 0.55em, first-line-indent: 1.8em, justify: true) set text(font: "New Computer Modern", size: 12pt, lang: "ru") set heading(numbering: "1.") show raw: set text(font: "New Computer Modern Mono") show par: set block(spacing: 0.55em) show heading: set block(above: 1.4em, below: 1em) show: thmrules.with(qed-symbol: $square$) show outline.entry.where(level: 1): it => { v(12pt, weak: true) strong(it) } page()[#outline(indent: auto)] doc }
https://github.com/cspr-rad/kairos-spec
https://raw.githubusercontent.com/cspr-rad/kairos-spec/main/README.md
markdown
# Spec A first draft of the spec can be found in [spec](./src/spec.typ). The sequence diagram that we created at the workshop in Zug can be found in the diagrams subdirectory [here](./src/diagrams/simple_transfer_diagram.mmd). Additional sequence diagrams can be found [here](./src/diagrams). # Typst Generate the spec's pdf by running `typst c spec.typ`, continually update throughout development by running `typst w spec.typ`. # Diagrams All the diagrams can be either built alltogether by running `nix build .#diagrams` or individually. To build them individually please follow the following subsection. ## PlantUML In order to build the `*.puml` diagrams, we use [PlantUML](https://plantuml.com/). For installation, see [Local Installation notes](https://plantuml.com/faq-install) or enter the `devShell` of this project by running `nix develop`. The package in the `nixpkgs` set is called `plantuml`. Once installed, `*.puml` diagrams can be converted to svg by running: ``` plantuml diagrams/transfer_sequence_diagram_client_submit.puml -tsvg ``` ## Graphviz In order to build the `*.dot` diagrams, we use [Graphviz](https://graphviz.org/). For installation, see [Downloads](https://graphviz.org/download/) or enter the `devShell` of this project by running `nix develop`. The package in the `nixpkgs` set is called `graphviz`. Once installed, `*.puml` diagrams can be converted to svg by running: ``` dot -Tsvg diagrams/merkle-tree.dot > merkle-tree.svg ``` # Formatting To format Nix and Typst run: ``` nix fmt ``` More formatters can be added by adding more formatters to the `treefmt.settings.formtatters` attribute-set analogous to `typst-fmt`.
https://github.com/matetamasi/Medve-Automata-9
https://raw.githubusercontent.com/matetamasi/Medve-Automata-9/master/feladat.typ
typst
#import "@preview/finite:0.3.0": automaton, layout #let aut = ( ..it) => { show "Start":"" automaton(..it) } #let maut = (..it, style: (:), radius: 0.45, curve: 0) => { show "Start":"" if not style.keys().contains("transition") { style.insert("transition", (curve: curve, label: (dist: 0.25))) } if not style.keys().contains("state") { style.insert("state", (radius: radius)) } automaton(..it, style: style) } #let parallel-layout = layout.custom.with( positions: (ctx, radii, states) => { let xinc = 1.5 let x = xinc let pos = (:) let toprow = true let h = 1 for (name, r) in radii { if (name == "S") { pos.insert(name, (0,0)) } else { pos.insert(name, (x, if(toprow){h}else{-h})) if (toprow) {toprow = false;} else {toprow = true; x += xinc} } } return pos } ) #let n-parallel-layout(y: 2) = layout.custom.with( positions: (ctx, radii, states) => { let xinc = 1.5 let x = 0 let xmax = x let names = (:) for (name, r) in radii { if names.keys().contains(name.first()) { names.at(name.first()).push(name) } else { names.insert(name.first(), (name,)) } } let pos = (:) if(names.keys().contains("S") and names.at("S")!= none) { for name in names.at("S") { pos.insert(name, (x, 0)) xmax = x x += xinc } } let ycurr = y/2 let states = names.len() if names.keys().contains("S") { states -= 1 } if names.keys().contains("N") { states -= 1 } let ystep = y/(states - 1) for row in names.keys() { if (row == "N" or row == "S") {continue} let xmid = x for name in names.at(row) { pos.insert(name, (xmid, ycurr)) if xmid > xmax {xmax = xmid} xmid += xinc } ycurr -= ystep } if names.keys().contains("N") { for name in names.at("N") { xmax += xinc pos.insert(name, (xmax, 0)) } } return pos } ) #let trap-layout(h: 1.7, xinc: 1.5) = layout.custom.with( positions: (ctx, radii, states) => { let x = xinc let pos = (:) for (name, r) in radii { if (name == "N") { pos.insert(name, (x/2, -h)) } else { pos.insert(name, (x, 0)) x += xinc } } return pos } ) #let subtasks(list, c: 2, cg: .1cm) = { let keylist = list.enumerate() set enum(numbering: "a)") align(center, { grid( columns: c, row-gutter: 0.4cm, column-gutter: cg, align: left, ..keylist.map(a => { if a.at(1).fields().keys().contains("children") and a.at(1).children.first().fields().keys().contains("text") and a.at(1).children.first().text.first() == "*" { set enum(numbering: (n) => str.from-unicode("a".to-unicode() + n - 1) +"*)") [#show regex("^\*$"): ""; #enum.item(a.at(0)+1, a.at(1))] } else { set enum(numbering: "a)") enum.item(a.at(0)+1, a.at(1)) } }) ) }) } #let important = text.with(red) #set page(margin: 1.5cm) = Determinisztikus véges automaták Ahol a feladat mást nem mond, az ábécé legyen $Sigma = {a, b}$. + Adj determinisztikus véges automatát a következő nyelvekre: #subtasks(( [pontosan 3 betűből álló szavak], [$a$ betűvel kezdődő szavak], [csak $a$ betűt tartalmazó szavak], [$b$ betűre végződő szavak], [pontosan 3 $a$ betűt tartalmazó szavak], [$a$ betűt nem tartalmazó szavak, $Sigma = {a,b,c}$], [legalább 3 darab $a$ betűt tartalmazó szavak], [legalább 3 darab $a$ betűt, *és* legalább 3 darab $b$ betűt tartalmazó szavak] ), cg: 1.8cm) + Milyen nyelvet fogadnak el az alábbi automaták? (Az 1. feladat részfeladataihoz hasonlóan próbálj meg megfogalmazni egy-egy szabályt, mely pontosan leírja, hogy milyen szavakat fogadnak el az egyes automaták.) #subtasks(( [#maut( ( S: (S:"a", A:"b"), A: (S:"b", A:"a") ), curve: .3 )], [#maut( ( S: (S: "b", A: "a"), A: (A: "a", B: "b"), B: (A: "a", C: "b"), C: (C:"a,b") ), style: ( A-B:(curve:.2), B-A:(curve:.2) ) )], [#maut( ( S:(S:"b", S1:"a"), S1:(B:"b", S1: "a"), B:(S1:"a", N:"b"), D:(D:"b", S1: "a"), N:(S1:"a", D:"b"), ), layout: n-parallel-layout(y: 3), style: ( S1-S1: (anchor: bottom), S1-B: (curve: .2), B-S1: (curve: .2, label: (pos: .4)), S1: (label: "A"), N: (label: "C"), transition: (curve: 0, label:(dist:.18)) ) )], [#maut( ( A1:(B1:"a", A2:"b"), B1:(A1:"a", B2:"b"), A2:(B2:"a", A3:"b"), B2:(A2:"a", B3:"b"), A3:(B3:"a", A1:"b"), B3:(A3:"a", B1:"b"), ), final: "B1", layout: n-parallel-layout(), style: ( transition: (curve: 0, label:(dist:.19)), A1-B1:(curve: .2, label: (angle: 0deg)), B1-A1:(curve: .2, label: (angle: 0deg)), A2-B2:(curve: .2, label: (angle: 0deg)), B2-A2:(curve: .2, label: (angle: 0deg)), A3-B3:(curve: .2, label: (angle: 0deg)), B3-A3:(curve: .2, label: (angle: 0deg)), A3-A1:(curve: -1), B3-B1:(curve: 1, label: (dist:-.19)), A1:(label: "A"), A2:(label: "B"), A3:(label: "C"), B1:(label: "D"), B2:(label: "E"), B3:(label: "F"), ) )] )) + Adj determinisztikus véges automatát a következő nyelvekre: #subtasks(( [szavak, melyekben az $a a$ részszó pontosan egyszer szerepel], [szavak, melyek első és utolsó betűje megegyezik], [$a$ és $b$ betűket felváltva tartalmazó szavak (mint pl: $a b a b a b a$ vagy $b a b a b$)], [szavak, melyekben minden $a$ után $b b$ következik], [\*szavak, melyekben minden két $c$ közt van $a$ és $b$, $Sigma = {a,b,c}$], [\* $a^n b^n$ (valahány $a$, majd *ugyanannyi* $b$)] )) + Adj determinisztikus véges automatát az oszthatósági szabályokra: #subtasks(( [5-tel osztható számok, $Sigma = {0,1,2,...,9}$], [3-mal osztható számok, $Sigma = {0,1,2,...,9}$], [2-vel osztható bináris számok, $Sigma = {0,1}$], [\*3-mal osztható bináris számok, $Sigma = {0,1}$], ), cg:1cm) #pagebreak(weak: true) = Hiányos, nemdeterminisztikus véges automaták Ahol a feladat mást nem mond, az ábécé legyen $Sigma = {a, b}$. + Milyen nyelvet fogadnak el az alábbi hiányos automaták? #subtasks(( [#maut((S:(S:"a")))], [#maut( ( S:(A:"b"), A:(B:"a"), B:(C:"b"), C:(D:"a"), D:() ), final: "CD" )], [#maut((S:(S:"b", A:"a"), A:(A:"b")))], [#maut( ( S:(S:"a", A:"b"), A:(S:"a") ), final: "S", curve: .4 )], ), cg : 1cm) + Milyen nyelvet fogadnak el az alábbi nemdeterminisztikus automaták? #subtasks(( [#maut( ( S: (S:"a,b", A0:"a", B0:"b"), A0: (A1:"a"), B0: (B1:"b"), A1: (A1: "a,b"), B1: (B1: "a,b") ), final: "A1B1", layout: n-parallel-layout(), style: ( A0: (label: "A"), B0: (label: "B"), A1: (label: "C"), B1: (label: "D"), ) )], [\* $Sigma = {a,b,c}$ #maut( ( S: (S:"a", A:"a,b", N:"a,c"), A: (A:"a,c", S:"b", N:"b"), N: (N:"a,b", S:"c", A:"c") ), final: "AN", layout: trap-layout(h: 2.5, xinc: 3.5), style: ( transition: (curve: .25, label:(dist:.2)), S-S: (curve:.35), A-A: (curve:.35), N-N: (curve:.35, anchor: bottom), N: (label: "B") ) )] ), cg: 2cm) #set text(hyphenate: true) + Adj nemdeterminisztikus véges automatát az alábbi nyelvekre! Ahol a feladat mást nem mond, az ábécé legyen $Sigma = {a, b}$. Használd ki a nemdeterminisztikusságot, törekedj arra, hogy minél kevesebb állapot felhasználásával adj helyes megodást! #subtasks(( [szavak, melyekben szerepel az $a b a a b$ részszó], [szavak, melyekben van két olyan $b$ betű, melyek közt néggyel osztható számú $a$ van], [szavak, melyekben nem szerepel az $a b c$ részszó, $Sigma = {a,b,c}$], [olyan betűre végződik, ami korábban nem szerepelt a szóban, $Sigma = {a,b,c}$], [szavak, melyekben legalább az egyik betű nem szerepel, $Sigma = {a,b,c,d}$], [szavak, melyekben szerepel az $a a a$ és a $b b b$ részszó is], [\*palindromok (tehát minden szó, ami balról és jobbról olvasva ugyanaz)], [\*szavak, melyekben nem szerepel sem az $a a a$, sem a $b b b$ részszó], ), cg: .4cm) #pagebreak(weak: true) = Veremautomaták A veremautomaták esetében a determinisztikus és nemdeterminisztikus verziók nem azonos erősségűek. A nemdeterminisztikus változattal fel tudunk ismerni olyan nyelveket, amiket a determinisztikussal nem lehet. Veremautomaták esetén ezért mindig nemdeterminisztikussal szokás dolgozni, tegyél te is így! + Milyen nyelvet fogadnak el az alábbi nemdeterminisztikus automaták? #subtasks(( [#maut( ( A: (B:"a, ε→a b, ε→b"), B:(B:"a, ε→ε b, ε→ε", C:"a, a→ε b, b→ε"), C:() ), style: ( A-B:(label:(dist:-0.5)), B-B:(label:(dist:0.65)), B-C:(label:(dist:-0.5)), ), layout: trap-layout(xinc:2.2) )], [#maut( ( A: (A:"a, ε→ε", B:"b, a→ε"), B: (B:"b, a→ε", C:"ε, Z→Z"), C: () ), layout: trap-layout(xinc:2.2) )], ), cg: 2cm) + Adj veremautomatát az alábbi nyelvekre! Ahol a feladat mást nem mond, a megadott nyelvek ábécéje $Sigma = {a,b}$, a veremben viszont ezen kívül bármilyen egyéb ábécét használhatsz. #subtasks(cg: .4cm, c: 3,( [$a^n b^m a^n$], [első és utolsó betű megegyezik], [$a^n b^m$, ahol $m >= n$], [$a^n b^m$, ahol $m = 2n$], [palindromok], [$a^n b^n c^m d^m$, $Sigma={a,b,c,d}$], [$a^n b^m c^m d^n$, $Sigma={a,b,c,d}$], [\*$(a b)^n a^m (a b)^n$], [\*$a^n b^m$, $2n >= m >= n$], [\*$a^n b^n c^n$, $Sigma = {a,b,c}$], [\*$a^l b^m c^n$, ahol $m = l+n$, \ $Sigma = {a,b,c}$] ))
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/8.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" -log_x a = log_x 1/a $ $log_x a - log_x a = 0$ $ex(c): log_x c = - log_x a$ $log_x a - log_x a = log_x a c = log_x 1$ $a c = 1$
https://github.com/vimkat/typst-ohm
https://raw.githubusercontent.com/vimkat/typst-ohm/main/src/components/logo.typ
typst
MIT License
#import "../../src/lib/vars.typ" #let logo( body, height: 1cm, text-only: false, department-below: false, safety-zone: true, fill: vars.red, ) = { layout(container-size => { // Height is a ratio, use wrapping container let _height = height if type(height) == "ratio" { _height = container-size.height * height } // Calculate safety zone let _logo-height = _height let _inset = 0pt if safety-zone { _logo-height = _height / 3 // TODO: FIX _inset = _logo-height } set par(leading: 0.35em) set text(font: vars.font, weight: 300, fill: fill, size: _logo-height) set align(bottom) let content = image.decode(read("../../src/assets/ohm-logo.svg").replace("#000000", fill.to-hex()), height: 1em) let text-size = 0.25em let logo-text = { set text(size: text-size) set align(left + bottom) [Technische \ Hochschule \ Nürnberg] } // Version A: Department right if not text-only and not department-below { // Version A.2: With department if body != none { logo-text = stack( dir: ltr, spacing: 1em*vars.frac-half, logo-text, { set text(size: text-size) set align(left + top) body } ) } // Version A.1: THN only content = stack( dir: ltr, spacing: 0.15em, content, logo-text, ) } // Version B: Department below if not text-only and department-below and body != none { content = grid( columns: 2, column-gutter: 0.15em, row-gutter: 1em*vars.frac-half, content, logo-text, none, { set text(size: text-size) body } ) } block( inset: _inset, content, ) }) } #let logo-omega(outline: false, fill: vars.red, ..args) = { let src = read("../assets/ohm-omega.svg").replace("stroke:none", "stroke:" + fill.to-hex()) if outline { image.decode(src, ..args) } else { image.decode(src.replace("fill:none", "fill:" + fill.to-hex()), ..args) } }
https://github.com/PraneethJain/Science-1
https://raw.githubusercontent.com/PraneethJain/Science-1/main/Assignment-5/2022101093_Assignment_5.typ
typst
#align(center, text(17pt)[*Science-1*]) #align(center, text(16pt)[Assignment-5]) #align(center, text(13pt)[<NAME>, 2022010193]) #let ket(x) = $lr(|#x angle.r)$ = Question 1 $ sigma_1 = mat(0, 1; 1, 0), sigma_2 = mat(0, -i; i, 0), sigma_3 = mat(1, 0; 0, -1) $ == (a) $ [sigma_1, sigma_2] = sigma_1 sigma_2 - sigma_2 sigma_1 $ $ [sigma_1, sigma_2] = mat(i, 0; 0, -i) - mat(-i, 0; 0, i) $ $ [sigma_1, sigma_2] = mat(2i, 0; 0, -2i) $ $ [sigma_2, sigma_1] = mat(-2i, 0; 0, 2i) $ Therefore, $sigma_1$ and $sigma_2$ do not commute. $ [sigma_2, sigma_3] = sigma_2 sigma_3 - sigma_3 sigma_2 $ $ [sigma_2, sigma_3] = mat(0, i; i, 0) - mat(0, -i; -i, 0) $ $ [sigma_2, sigma_3] = mat(0, 2i; 2i, 0) $ $ [sigma_3, sigma_2] = mat(0, -2i; -2i, 0) $ Therefore, $sigma_2$ and $sigma_3$ do not commute. $ [sigma_1, sigma_3] = sigma_1 sigma_3 - sigma_3 sigma_1 $ $ [sigma_1, sigma_3] = mat(0, -1; 1, 0) - mat(0, 1; -1, 0) $ $ [sigma_1, sigma_3] = mat(0, -2; 2, 0) $ $ [sigma_3, sigma_1] = mat(0, 2; -2, 0) $ Therefore, $sigma_1$ and $sigma_3$ do not commute. Note that trivially, $sigma_1$ commutes with $sigma_1$, $sigma_2$ commutes with $sigma_2$ and $sigma_3$ commutes with $sigma_3$ ($[sigma_i, sigma_i] = bold(0)$) == (b) For $sigma_1$, $det(sigma_1 - lambda I) = 0$ $ det mat(-lambda, 1; 1, -lambda) = 0 $ $ lambda^2 - 1 = 0 $ $ lambda_1 = -1, lambda_2 = 1 $ $ sigma_1 x_1 = lambda_1 x_1 $ $ mat(0, 1; 1, 0) mat(x_11; x_12) = mat(-x_11; -x_12) $ $ x_12 = -x_11 $ $ x_1 = mat(alpha; -alpha) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_1 | x_1 angle.r) = sqrt(2alpha)$ $ ket(x_1) = mat(1/sqrt(2); -1/sqrt(2)) $ $ sigma_1 x_2 = lambda_2 x_2 $ $ mat(0, 1; 1, 0) mat(x_21; x_22) = mat(x_21; x_22) $ $ x_22 = x_21 $ $ x_2 = mat(alpha; alpha) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_2|x_2 angle.r) = sqrt(2alpha)$ $ ket(x_2) = mat(1/sqrt(2); 1/sqrt(2)) $ $therefore$ for $sigma_1$, eigenvalues are $-1, 1$, and corresponding orthogonal eigenvectors are $mat(alpha; -alpha), mat(beta; beta)$, which upon normalizing give $mat(1/sqrt(2); -1/sqrt(2)), mat(1/sqrt(2); 1/sqrt(2))$. For $sigma_2$, $det(sigma_2 - lambda I) = 0$ $ det mat(-lambda, -i; i, -lambda) = 0 $ $ lambda^2 - 1 = 0 $ $ lambda_1 = -1, lambda_2 = 1 $ $ sigma_2 x_1 = lambda_1 x_1 $ $ mat(0, -i; i, 0) mat(x_11; x_12) = mat(-x_11; -x_12) $ $ x_12 = -i x_11 $ $ x_1 = mat(alpha; -i alpha) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_1 | x_1 angle.r) = sqrt(2alpha)$ $ ket(x_1) = mat(1/sqrt(2); -i/sqrt(2)) $ $ sigma_2 x_2 = lambda_2 x_2 $ $ mat(0, -i; i, 0) mat(x_21; x_22) = mat(x_21; x_22) $ $ x_22 = i x_21 $ $ x_2 = mat(alpha; i alpha) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_2 | x_2 angle.r) = sqrt(2alpha)$ $ ket(x_2) = mat(1/sqrt(2); i / sqrt(2)) $ $therefore$ for $sigma_2$, eigenvalues are $-1, 1$, and corresponding orthogonal eigenvectors are $mat(alpha; -i alpha), mat(beta; i beta)$, which upon normalizing give $mat(1/sqrt(2); -i/sqrt(2)), mat(1/sqrt(2); i/sqrt(2))$. For $sigma_3$, $det(sigma_3 - lambda I) = 0$ $ det mat(1 - lambda, 0; 0, -1 - lambda) = 0 $ $ lambda^2 - 1 = 0 $ $ lambda_1 = -1, lambda_2 = 1 $ $ sigma_3 x_1 = lambda_1 x_1 $ $ mat(1, 0; 0, -1) mat(x_11; x_12) = mat(-x_11; -x_12) $ $ x_11 = 0 $ $ x_1 = mat(0; alpha) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_1 | x_1 angle.r) = alpha$ $ ket(x_1) = mat(0; 1) $ $ sigma_3 x_2 = lambda_2 x_2 $ $ mat(1, 0; 0, -1) mat(x_21; x_22) = mat(x_21; x_22) $ $ x_22 = 0 $ $ x_2 = mat(alpha; 0) $ For orthonormal basis, we divide by its magnitude $sqrt(angle.l x_2 | x_2 angle.r) = alpha$ $ ket(x_2) = mat(1; 0) $ $therefore$ for $sigma_3$, eigenvalues are $-1, 1$, and corresponding orthogonal eigenvectors are $mat(0; alpha), mat(beta; 0)$, which upon normalizing give $mat(0; 1), mat(1; 0)$. == (c) Since $ket(phi) = sum_i c_i ket(lambda_i), therefore P(ket(lambda_i)) = |c_i|^2$ $P(hat(A))$ in $ket(phi)$ is $|angle.l x_1| phi angle.r|^2$ for state $ket(x_1)$ Here, we consider the eigenstate of $sigma_2$ $ phi = mat(1/sqrt(2); i/sqrt(2)) $ $ P(sigma_1) = cases( |angle.l x_1| phi angle.r|^2 " for state" ket(x_1), |angle.l x_2| phi angle.r|^2 " for state" ket(x_2), ) $ $ P(sigma_1) = cases( |mat(1/sqrt(2), -1/sqrt(2)) * mat(1/sqrt(2); i/sqrt(2))|^2 " for state" ket(x_1), |mat(1/sqrt(2), 1/sqrt(2)) * mat(1/sqrt(2); i/sqrt(2))|^2 " for state" ket(x_2), ) $ $ P(sigma_1) = cases( |(1-i)/2|^2 " for state" ket(x_1), |(1+i)/2|^2 " for state" ket(x_2), ) $ $ P(sigma_1) = cases( (1/sqrt(2))^2 " for state" ket(x_1), (1/sqrt(2))^2 " for state" ket(x_2), ) $ $ P(sigma_1) = cases( 1/2 " for state" ket(x_1), 1/2 " for state" ket(x_2), ) $ $ P(sigma_3) = cases( |angle.l x_1| phi angle.r|^2 " for state" ket(x_1), |angle.l x_2| phi angle.r|^2 " for state" ket(x_2), ) $ $ P(sigma_3) = cases( |mat(0, 1) * mat(1/sqrt(2); i/sqrt(2))|^2 " for state" ket(x_1), |mat(1, 0) * mat(1/sqrt(2); i/sqrt(2))|^2 " for state" ket(x_2), ) $ $ P(sigma_3) = cases( (1/sqrt(2))^2 " for state" ket(x_1), (1/sqrt(2))^2 " for state" ket(x_2), ) $ $ P(sigma_3) = cases( 1/2 " for state" ket(x_1), 1/2 " for state" ket(x_2), ) $ == (d) For $Delta sigma_1$ $ Delta sigma_1^2 = angle.l sigma_1^2 angle.r - angle.l sigma_1 angle.r ^ 2 $ $ Delta sigma_1^2 = angle.l phi|sigma_1^2|phi angle.r - angle.l phi|sigma_1|phi angle.r ^ 2 $ $ Delta sigma_1^2 = mat(1/sqrt(2), -i/sqrt(2))*mat(0, 1; 1, 0)*mat(0, 1; 1, 0)*mat(1/sqrt(2); i/sqrt(2)) - (mat(1/sqrt(2), -i/sqrt(2))*mat(0, 1; 1, 0)*mat(1/sqrt(2); i/sqrt(2))) ^ 2 $ $ Delta sigma_1^2 = 1 - 0 $ $ Delta sigma_1^2 = 1 $ For $Delta sigma_3$ $ Delta sigma_3^2 = angle.l sigma_3^2 angle.r - angle.l sigma_3 angle.r ^ 2 $ $ Delta sigma_3^2 = angle.l phi|sigma_3^2|phi angle.r - angle.l phi|sigma_3|phi angle.r ^ 2 $ $ Delta sigma_3^2 = mat(1/sqrt(2), -i/sqrt(2))*mat(1, 0; 0, -1)*mat(1, 0; 0, -1)*mat(1/sqrt(2); i/sqrt(2)) - (mat(1/sqrt(2), -i/sqrt(2))*mat(1, 0; 0, -1)*mat(1/sqrt(2); i/sqrt(2))) ^ 2 $ $ Delta sigma_3^2 = 1 - 0 $ $ Delta sigma_3^2 = 1 $ So, the uncertainty $Delta sigma_1 = 1, Delta sigma_3 = 1, Delta sigma_1 Delta sigma_3 = 1$. According to the uncertainty principle $ Delta sigma_1 Delta sigma_3 >= 1/2 |angle.l [sigma_1, sigma_3] angle.r| $ $ Delta sigma_1 Delta sigma_3 >= 1/2 |angle.l phi|sigma_1 sigma_3|phi angle.r| $ $ Delta sigma_1 Delta sigma_3 >= 1/2 |mat(1/sqrt(2), -i/sqrt(2)) * mat(0, 2; -2, 0) * mat(1/sqrt(2); i / sqrt(2))| $ $ Delta sigma_1 Delta sigma_3 >= 1/2 |2i| $ $ Delta sigma_1 Delta sigma_3 >= 1 $ These are the corresponding uncertainty relations. = Question 2 $ V(x) = cases( 0 " for" 0 < x < L, infinity " for" x <= 0 " or" x >= L ) $ $ psi = 1/sqrt(2) ket(phi_1) + 1/sqrt(2) ket(phi_2) $ We use the time independent Schrödinger equation $ -planck.reduce^2/(2m) d/(d x^2) psi(x) + V(x) psi(x) = E psi(x) $ For $x <= 0$ or $x >= L$, we have $ -planck.reduce^2/(2m) d/(d x^2) psi(x) + (infinity) psi(x) = E psi(x) $ which implies $psi(x) = 0 " " forall x in.not (0, L) $ For regions inside the wall, we have $ -planck.reduce^2/(2m) d/(d x^2) psi(x) + 0 * psi(x) = E psi(x) $ $ -planck.reduce^2/(2m) d/(d x^2) psi(x) = E psi(x) $ $ d/(d x^2) psi(x) = -(2 m E)/planck.reduce^2 psi(x) $ We know the general solution to this differential equation is $ psi(x) = A sin(k x) + B cos(k x) " where " k = sqrt((2 m E)/planck.reduce^2) $ At $x = 0$ $ psi(0) = A sin(0) + B cos(0) $ $ B = 0 $ At $x = L$ $ psi(L) = A sin(k L) + 0 cos (k L) $ $ 0 = sin(k L) $ $ k = (n pi)/ L $ $ sqrt((2 m E)/planck.reduce^2) = (n pi)/ L $ $ (2 m E)/planck.reduce^2 = (n^2 pi^2)/ L^2 $ $ E = n^2 (pi^2 planck.reduce^2)/(2 m L^2) $ The first two lowest energies are $E_1 = (pi^2 planck.reduce^2)/(2 m L^2), E_2 = (2 pi^2 planck.reduce^2)/(m L^2)$ Since the total probability of the particle existing at any position is $1$ $ integral_0^L psi^2(x)d x = 1 $ $ integral_0^L A^2 sin^2(k x) d x = 1 $ $ integral_0^L A^2 sin^2((n pi x)/ L) d x = 1 $ $ A^2 L / 2 = 1 $ $ A = sqrt(2 / L) $ Now, we know that $ ket(psi(x, t)) = 1/sqrt(2) e^(-i E_1 t) ket(phi_1) + 1/sqrt(2) e^(-i E_2 t) ket(phi_2) $ $ ket(psi(x, t)) = 1/sqrt(L) e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + 1/sqrt(L) e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L) $ == (a) The total energy (Hamiltonian) operator is given by $ H = -planck.reduce^2/(2m) diff^2/(diff x^2) + V(x) $ We consider only the region between the walls, as outside, the probability is $0$. $ H = -planck.reduce^2/(2m) diff^2/(diff x^2) $ Average energy $= angle.l H angle.r = angle.l psi|H|psi angle.r$ $ angle.l H angle.r = integral_0^L psi^dagger H psi d x $ $ angle.l H angle.r = integral_0^L 1/sqrt(L)(e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(-planck.reduce^2/(2m) diff^2/(diff x^2)1/sqrt(L)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l H angle.r = -(planck.reduce^2)/(2 m L) integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L) H psi)(diff^2/(diff x^2)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l H angle.r = -(planck.reduce^2)/(2 m L) integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L) H psi)(- pi^2/L^2 e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) - 4 pi^2/L^2 e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) d x $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3) integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L) H psi)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + 4e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) d x $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3) integral_0^L (sin^2((pi x)/ L) + 4 sin^2((2 pi x)/ L) + 4 e^(- i (3 pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/L) sin((2 pi x)/ L) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) sin((2 pi x)/ L)) d x $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3) integral_0^L (sin^2((pi x)/ L) + 4 sin^2((2 pi x)/ L) + (e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(- i (3 pi^2 planck.reduce^2)/(2 m L^2) t))sin((pi x)/L) sin((2 pi x)/ L)) d x $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3)(L/2 + 2L + integral_0^L (e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(- i (3 pi^2 planck.reduce^2)/(2 m L^2) t))sin((pi x)/L) sin((2 pi x)/ L) d x) $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3)((5 L) / 2 + (e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(- i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) * 0) $ $ angle.l H angle.r = (planck.reduce^2 pi^2)/(2 m L^3)((5 L) / 2) $ $ angle.l H angle.r = (5 planck.reduce^2 pi^2)/(4 m L^2) $ We find the average second moment $ angle.l H^2 angle.r = integral_0^L psi^dagger H^2 psi d x $ $ angle.l H^2 angle.r = h^4/(4 m^2 L) integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(diff^4/(diff x^4)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l H^2 angle.r = (h^4 pi^4)/(4 m^2 L^5) integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + 16 e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) d x $ $ angle.l H^2 angle.r = (h^4 pi^4)/(4 m^2 L^5) integral_0^L (sin^2((pi x)/L) + 16 sin^2((2 pi x)/L) + sin((pi x)/L) sin((2 pi x)/L)(16 e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t))) d x $ $ angle.l H^2 angle.r = (h^4 pi^4)/(4 m^2 L^5) (17 L)/2 $ $ angle.l H^2 angle.r = (17 h^4 pi^4)/(8 m^2 L^4) $ Variance $= sigma_H^2 = angle.l H^2 angle.r - angle.l H angle.r^2$ $ sigma_H^2 = (17 h^4 pi^4)/(8 m^2 L^4) - (25 h^4 pi^4)/(16 m^2 L^4) $ $ sigma_H^2 = (9 h^4 pi^4)/(16 m^2 L^4) $ Note that both the average energy and variance in energy are time independent, therefore remain the same at $t=0$ and later. == (b) $ ket(psi(x, t)) = 1/sqrt(L) e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + 1/sqrt(L) e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L) $ $ P(x=L/2, t=0) = |psi(x=L/2, t=0)|^2 $ $ P(x=L/2, t=0) = |(sin(pi/2) + sin(pi))/sqrt(L)|^2 $ $ P(x=L/2, t=0) = |(1 + 0)/sqrt(L)|^2 $ $ P(x=L/2, t=0) = 1/L $ == (c) Average $x$ $= angle.l x angle.r = angle.l psi|x|psi angle.r$ $ angle.l x angle.r = integral_0^L psi^dagger x psi d x $ $ angle.l x angle.r = integral_0^L 1/sqrt(L)(e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))( x 1/sqrt(L)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l x angle.r = 1/L integral_0^L x (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) (e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) d x $ $ angle.l x angle.r = 1/L integral_0^L x (sin^2((pi x)/L) + sin^2((2 pi x)/L) + (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) sin((pi x)/L) sin((2 pi x)/ L)) d x $ $ angle.l x angle.r = 1/L (1/2 - 8/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t)))L^2 $ $ angle.l x angle.r = L/2 - (8 L)/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) $ At time $t=0$, $ angle.l x angle.r_(t=0) = L(1/2 - 16/(9 pi^2)) $ We find the average second moment $ angle.l x^2 angle.r = integral_0^L psi^dagger x^2 psi d x $ $ angle.l x^2 angle.r = integral_0^L 1/sqrt(L)(e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))( x^2 1/sqrt(L)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l x^2 angle.r = 1/L integral_0^L x^2 (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) (e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L)) d x $ $ angle.l x^2 angle.r = 1/L integral_0^L x^2 (sin^2((pi x)/L) + sin^2((2 pi x)/L) + (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) sin((pi x)/L) sin((2 pi x)/ L)) d x $ $ angle.l x^2 angle.r = 1/L (1/3 - 5/(16 pi^2) - 8/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t))) L^3 $ $ angle.l x^2 angle.r = L^2 (1/3 - 5/(16 pi^2) - 8/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t))) $ Now, we can find the variance $ sigma_x^2 = angle.l x^2 angle.r - angle.l x angle.r^2 $ $ sigma_x^2 = L^2 (1/3 - 5/(16 pi^2) - 8/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t))) - L^2(1/4 + 64/(81 pi^4)(e^(-i (3 pi^2 planck.reduce^2)/(m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(m L^2) t) + 2) - 8/(9 pi^2) (e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t))) $ $ sigma_x^2 = L^2 (1/12 - 5/(16 pi^2) - 64/(81 pi^4)(e^(-i (3 pi^2 planck.reduce^2)/(m L^2) t) + e^(i (3 pi^2 planck.reduce^2)/(m L^2) t) + 2)) $ At time t = 0, $ (sigma_x^2)_(t=0) = L^2(1/12 - 5/(16 pi^2) - 256 / (81 pi^4)) $ == (d) The momentum operator is given by $ hat(p) = -i planck.reduce diff / (diff x) $ Average momentum $= angle.l hat(p) angle.r = angle.l psi|hat(p)|psi angle.r$ $ angle.l hat(p) angle.r = integral_0^L 1/sqrt(L)(e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(-i planck.reduce diff/(diff x)1/sqrt(L)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l hat(p) angle.r = -(i planck.reduce)/L integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(diff/(diff x)(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))) d x $ $ angle.l hat(p) angle.r = -(i planck.reduce)/L integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(pi/L e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) cos((pi x)/ L) + (2 pi)/L e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) cos((2 pi x)/ L)) d x $ $ angle.l hat(p) angle.r = -(i planck.reduce pi)/L^2 integral_0^L (e^(i (pi^2 planck.reduce^2)/(2 m L^2) t) sin((pi x)/ L) + e^(i (2 pi^2 planck.reduce^2)/(m L^2) t) sin((2 pi x)/ L))(e^(-i (pi^2 planck.reduce^2)/(2 m L^2) t) cos((pi x)/ L) + 2 e^(-i (2 pi^2 planck.reduce^2)/(m L^2) t) cos((2 pi x)/ L)) d x $ $ angle.l hat(p) angle.r = -(i planck.reduce pi)/L^2 integral_0^L (sin((pi x)/L) cos((pi x)/L) + 2 sin((2 pi x)/L) cos((2 pi x)/L) + \ 2 sin((pi x)/L) cos((2 pi x)/ L) e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t) + sin((2 pi x)/L) cos((pi x)/L) e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) d x $ $ angle.l hat(p) angle.r = - (i h pi)/(L^2) ((4 L) / (3 pi) (e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) - e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) ) $ $ angle.l hat(p) angle.r = - (4 i h)/(3 L) (e^(i (3 pi^2 planck.reduce^2)/(2 m L^2) t) - e^(-i (3 pi^2 planck.reduce^2)/(2 m L^2) t)) $ At time t = 0, $ angle.l hat(p) angle.r_(t = 0) = 0 $
https://github.com/Gekkio/gb-ctr
https://raw.githubusercontent.com/Gekkio/gb-ctr/main/common.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/cetz:0.3.0" #let monotext(..args) = text(font: "Anonymous Pro", fallback: false, ..args) #let awesome-brands(..args) = text(font: "Font Awesome 6 Brands", fallback: false, ..args) #let awesome(..args) = text(font: "Font Awesome 6 Free Solid", fallback: false, ..args) #let color-box(icon: none, title: none, fgcolor: black, bgcolor: white, title-color: white, content) = [ #let radius = 5pt #box(fill: bgcolor, stroke: 2pt + fgcolor, radius: radius)[ #block(breakable: false, width: 100%, fill: fgcolor, inset: (x: 16pt, y: 8pt), below: 0pt, radius: (top-left: radius, top-right: radius))[ #awesome(fill: title-color, icon) #text(fill: title-color, weight: "bold")[#title] ] #block(breakable: false, width: 100%, inset: 16pt)[#content] ] ] #let caveat(content) = [ #color-box(content, icon: "\u{f05a}", title: "Caveat", fgcolor: rgb("#DC143C"), bgcolor: rgb("#FFE4E1")) ] #let speculation(content) = [ #color-box(content, icon: "\u{f12e}", title: "Speculation", fgcolor: rgb("#467BA9"), bgcolor: rgb("#F0FFFF")) ] #let warning(content) = [ #color-box(content, icon: "\u{f06a}", title: "Warning", fgcolor: rgb("#FFD700"), bgcolor: rgb("#FFFACD"), title-color: rgb("#505050")) ] #let bit(content) = monotext(content) #let bin(content) = monotext("0b" + content) #let hex(content) = monotext("0x" + content) #let hex-range(start, end) = monotext({"0x" + start + "-0x" + end}) #let unimpl-bit() = table.cell(fill: rgb("#D3D3D3ff"))[] #let reg-table(..args) = monotext(9pt)[ #table( columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), inset: 5pt, align: center + horizon, ..args ) ] #let reg-figure(caption: none, content) = [ #v(1cm) #figure( content, caption: caption, kind: "register", supplement: [Register], numbering: (..nums) => counter(heading).display((..hnums) => numbering("1", hnums.pos().at(1))) + "." + numbering("1", ..nums) ) ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/modernpro-coverletter/0.0.1/README.md
markdown
Apache License 2.0
# Typst-ModernPro-Coverletter This is a cover letter template for Typst with Sans font. It is a modern and professional cover letter template. It is easy to use and customize. This cover letter template is suitable for any job application or general purpose. ## How to use ### Use from the Typst Universe It is simple and easy to use this template from the Typst Universe. If you prefer to use the local editor and `typst-cli`, you can use the following command to create a new cover letter project with this template. ```bash typst init @preview/modernpro-coverletter ``` It will create a new cover letter project with this template in the current directory. ### Use from GitHub You can also use this template from GitHub. You can clone this repository and use it as a normal project. ```bash git clone https://github.com/jxpeng98/typst-coverletter.git ``` ## Features The template will have the following features: ```typst #show: main.with( font-type: "openfont", name: [#lorem(2)], address: [#lorem(4)], contacts: ( (text: "08856", link: ""), (text: "example.com", link: "https://www.example.com"), (text: "github.com", link: "https://www.github.com"), (text: "<EMAIL>", link: "mailto:<EMAIL>"), ), recipient: ( start-title: [Dear], cl-title: [Job Application for Hiring Manager], date: [], department: [#lorem(2)], institution: [#lorem(2)], address: [#lorem(4)], postcode: [#lorem(1)], ), ) #lorem(300) ``` - `font-type`: The font type of the cover letter. It can be "macfont" or "openfont". - recipient: The recipient information of the cover letter. - `start-title`: The start title of the letter. - `cl-title`: The title of the letter (i.g., Job Application for Hiring Manager). - date: The date of the letter(If "" or [], it will generate the current date). - department: The department of the recipient, can be "" or []. - institution: The institution of the recipient. - address: The address of the recipient. - postcode: The postcode of the recipient. ## Preview ![Cover Letter Preview](https://minioapi.pjx.ac.cn/img1/2024/04/71b012412bc411ed8b751e12d91d8636.png)
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/inlay_hints/one_line_content.typ
typst
Apache License 2.0
#let add(x, y) = x + y #add[][] #add[ ][ ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/subelement-panic_07.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Outline entry (pre-emptive, improved error) // // Error: 2-55 heading must have a location // // Hint: 2-55 try using a query or a show rule to customize the outline.entry instead // #outline.entry(1, heading[Hello], [World!], none, [1])
https://github.com/Chi-Kai/cv
https://raw.githubusercontent.com/Chi-Kai/cv/main/cv.typ
typst
#let fonts = ("Times New Roman","LXGW WenKai Mono") #show heading: set text(font: fonts) #show link: underline // Uncomment the following lines to adjust the size of text // The recommend resume text size is from `10pt` to `12pt` // #set text( // size: 12pt, // ) // Feel free to change the margin below to best fit your own CV #set page( margin: (x: 0.9cm, y: 1.3cm), ) // For more customizable options, please refer to official reference: https://typst.app/docs/reference/ #set par(justify: true) #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)} #let fontbold(s,t) = {text(size:s,weight: "bold")[#t]} = 赤凯 #link("https://github.com/Chi-Kai")[github.com/Chi-Kai] == 教育经历 #chiline() #link("https://www.hnu.edu.cn/index.htm")[*湖南大学(保送)*] #h(1fr) 2023/09 -- 2026/06 \ 电子信息 #h(20%) 一等奖学金 #link("https://www.dlmu.edu.cn")[*大连海事大学(211)*] #h(1fr) 2019/09 -- 2023/06 \ 网络工程 #h(20%) 国家励志奖学金、服务外包大赛国家三等奖、电子商务三创赛省级二等奖 == 项目经历 #chiline() *基于区块链的航运溯源系统* #h(20%) 校级大创 #h(32%)2022/03 -- 2022/05 \ - 负责搭建联盟链集群和抽象货物信息,前端使用Vue搭建,使用WebSocket实时监测货物信息 *视频人像分割算法* #h(18%) 全国大学生服务外包大赛国家三等奖 #h(18%) 2022/03 -- 2022/07 \ - 负责模型训练并使用C++工程化,将模型从torch转化为openvino 异步推理并实现并行加速,耗时减少85% *基于Fabric联盟链的大樱桃溯源系统* #h(8%) 互联网+大赛省银奖 #h(27%)2021/09 -- 2022/04 \ - 负责联盟链的搭建,采用Golang 构建后台,将樱桃生长信息记录在联盟链中,实现大樱桃的防伪溯源 *基于鸿蒙系统的智能小车开发* #h(1fr)2020/09 -- 2021/04 \ - 负责C/C++避障寻路算法设计与代码编写以及Flutter上位机编写跨平台应用,实现基于网络协议栈的数据交互 *基于RSA加密算法的匿名树洞论坛平台* #h(10%) 省级大创 #h(32%)2020/12 -- 2021/06 \ - 采用Go语言编写后端代码,实现数据存储与持久性保证以及RSA算法加密,完成小程序前端美工及测试工作 == 开源贡献 #chiline() #link("https://github.com/alibaba/higress")[#fontbold(12pt,"Higress")] Cloud Native API Gateway | 云原生API网关#h(1fr) Contributor \ - issue: #link("https://github.com/alibaba/higress/issues/958")[AI 代理 Wasm 插件对接阶跃星辰] - issue: #link("https://github.com/alibaba/higress/issues/957")[AI 代理 Wasm 插件对接零一万物] == 科研经历 #chiline() 研究方向: 联邦学习、模型保护 #link("https://arxiv.org/abs/2402.19054")[RobWE: Robust Watermark Embedding for Personalized Federated Learning Model Ownership Protection] #h(1fr) CCF A类会议在投 一种基于鲁棒水印的个性化联邦学习模型所有权保护方法 #h(1fr) 专利 == 技能 #chiline() - 编程语言:C/C++, Python, Golang - 框架:Pytorch, Vue, Flutter, Gin - 工具:Git, Docker, Kubernetes - 语言:CET-6
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/themes/simple.md
markdown
--- sidebar_position: 1 --- # Simple 主题 ![image](https://github.com/touying-typ/touying/assets/34951714/83d5295e-f961-4ffd-bc56-a7049848d408) 这个主题来源于 [Polylux](https://polylux.dev/book/themes/gallery/simple.html),作者是 <NAME>。 这个主题被认为是一个相对简单的主题,你可以用它来创建一个简单 slides,并且可以随意加入你喜欢的功能。 ## 初始化 你可以通过下面的代码来初始化: ```typst #import "@preview/touying:0.2.1": * #let s = themes.simple.register(s, aspect-ratio: "16-9", footer: [Simple slides]) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, slides, title-slide, centered-slide, focus-slide) = utils.methods(s) #show: init ``` 其中 `register` 接收参数: - `aspect-ratio`: 幻灯片的长宽比为 "16-9" 或 "4-3",默认为 "16-9"。 - `footer`: 展示在页脚的内容,默认为 `[]`,也可以传入形如 `self => self.info.author` 的函数。 - `footer-right`: 展示在页脚右侧的内容,默认为 `states.slide-counter.display() + " / " + states.last-slide-number`。 - `background`: 背景颜色,默认为白色。 - `foreground`: 文本颜色,默认为黑色。 - `primary`: 主题颜色,默认为 `aqua.darken(50%)`。 ## slide 函数族 simple 主题提供了一系列自定义 slide 函数: ```typst #centered-slide(section: ..)[ ... ] ``` 内容位于幻灯片中央的幻灯片,`section` 参数可以用于新建一个 section。 --- ```typst #title-slide[ ... ] ``` 和 `centered-slide` 相同,这里只是为了保持和 Polylux 语法上的一致性。 --- ```typst #slide( repeat: auto, setting: body => body, composer: utils.side-by-side, section: none, subsection: none, // simple theme args footer: auto, )[ ... ] ``` 默认拥有页眉和页脚的普通 slide 函数,其中页眉为当前 section,页脚为您设置的页脚。 --- ```typst #focus-slide(foreground: ..., background: ...)[ ... ] ``` 用于引起观众的注意力。可选接受一个前景色 (默认为 `white`) 和一个背景色 (默认为 `auto`,即 `self.colors.primary`)。 ## `slides` 函数 ```typst #import "@preview/touying:0.2.1": * #let s = themes.simple.register(s, aspect-ratio: "16-9", footer: [Simple slides]) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, slides, title-slide, centered-slide, focus-slide) = utils.methods(s) #show: init #show: slides = Title == First Slide Hello, Touying! #pause Hello, Typst! ``` ![image](https://github.com/touying-typ/touying/assets/34951714/2c599bd1-6250-497f-a65b-f19ae02a16cb) ## 示例 ```typst #import "@preview/touying:0.2.1": * #let s = themes.simple.register(s, aspect-ratio: "16-9", footer: [Simple slides]) #let s = (s.methods.enable-transparent-cover)(self: s) #let (init, slide, slides, title-slide, centered-slide, focus-slide) = utils.methods(s) #show: init #title-slide[ = Keep it simple! #v(2em) Alpha #footnote[Uni Augsburg] #h(1em) Bravo #footnote[Uni Bayreuth] #h(1em) Charlie #footnote[Uni Chemnitz] #h(1em) July 23 ] #slide[ == First slide #lorem(20) ] #focus-slide[ _Focus!_ This is very important. ] #centered-slide(section: [Let's start a new section!]) #slide[ == Dynamic slide Did you know that... #pause ...you can see the current section at the top of the slide? ] ```
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/acknowledgement.typ
typst
Other
#import "theme/acknowledgement.typ": * #acknowledgement[ First and foremost, I would like to express my deepest gratitude to Professor <NAME>. I am incredibly thankful for his availability and guidance throughout my studies. It was a great honour to receive his proposal to supervise my research in my final year. Beyond that, he generously allowed me to suggest topics that piqued my interest, ultimately enabling me to focus on a subject that I am truly passionate about. I must also express my heartfelt appreciation for my girlfriend, Sandra. Her endless patience and emotional support have been a constant source of strength, motivation and inspiration for me. However, it is with a touch of melancholy that I acknowledge the sacrifices we have made in our personal lives in order to pursue this overdue academic endeavour that I should have completed twenty years ago. I would like to thank my family and #emph[in-real-life] friends for their continuous support and encouragement throughout these last years. Your belief in me has provided the foundation upon which this work stands. I am also deeply grateful to my #emph[online] friends, especially within the Typst and Nix communities, for their tremendous support and constant source of solutions, inspiration and motivation. A special mention is deserved for Izumi, my cat, who was a constant companion and source of comfort over the last decade. His loss was a profound sorrow, and I deeply miss his presence. The memories of the countless hours he spent by my side, offering silent support during my work, have left an indelible mark. Finally, I would like to express my sincere thanks to all the participants in this research. I am particularly grateful to my colleagues at European Commission, who courageously and continuously supported me while remaining unaware of my academic activities. Your valuable feedback has greatly contributed to the development of some parts of this master's thesis. In fact, your lack of awareness helped me understand the barriers to implementing software reproducibility from the very beginning and in a real professional context. Each piece of feedback has been instrumental in helping me better understand and improve communication about this concept. ]