repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/mawkler/cv
https://raw.githubusercontent.com/mawkler/cv/main/README.md
markdown
MIT License
# CV Below you can download my CV as a PDF in either English or Swedish: <table cellspacing="0" cellpadding="0"> <tr> <th> <a href="https://github.com/mawkler/cv/releases/download/latest/english.pdf"> English Version </a> </th> <th> <a href="https://github.com/mawkler/cv/releases/download/latest/swedish.pdf"> Swedish Version </a> </th> </tr> <tr> <td> <a href="https://github.com/mawkler/cv/releases/download/latest/english.pdf"> <img src="https://github.com/mawkler/cv/releases/download/latest/english-thumbnail.png" alt="English CV"> </a> </td> <td> <a href="https://github.com/mawkler/cv/releases/download/latest/swedish.pdf"> <img src="https://github.com/mawkler/cv/releases/download/latest/swedish-thumbnail.png" alt="Swedish CV"> </a> </td> </tr> </table> The PDFs (and these thumbnails) are automatically built and deployed on each push using my GitHub Actions pipeline [here](./.github/workflows/build-cv.yaml). ## Compile it yourself Requires [Typst](https://github.com/typst/typst) to be installed, as well as the fonts [Fira Sans](https://github.com/mozilla/Fira), [Fira Code](https://github.com/tonsky/FiraCode) and [Font Awesome](https://github.com/FortAwesome/Font-Awesome). If you're on Arch Linux (btw) you can install these like so: ```sh sudo pacman -S typst ttf-fira-code ttf-fira-sans ttf-font-awesome ``` Here's how you compile the CV: ```sh git clone https://github.com/mawkler/cv.git # English version typst compile english.typ # Swedish version typst compile swedish.typ ``` ## Licence [MIT](./LICENSE)
https://github.com/simon-isler/zhaw-summaries
https://raw.githubusercontent.com/simon-isler/zhaw-summaries/main/S6%20-%20FS2024/MOBA2/sections/1-react.typ
typst
= Mobile Web == Components - break UIs down in a modular way - enable interchangeability - isolate state from application business logic -> based on shadow DOM == React React wraps an imperative API with a declarative one - React's rendering process must always be pure - Event handlers don't need to be pure, as they don't run during rendering - Virtual DOM - React compares the virtual DOM with the real DOM and only updates the parts that have changed = React Native - Application logic is written and executed in JavaScript - functional approach to constructing UIs - Bridge translates JavaScript to native code - Application UI is fully native == Navigation - Navigation works differently on each native platform. iOS uses view controllers, while android uses activities. - Navigation on mobile is stateful. On the web, navigation is typically stateless, where a url (i.e. route) takes a user to a single screen/page. On mobile, the history of the user's navigation state is persisted in the application so that the user can go back to previous screens - a stack of screens can even include the same screen multiple times. ```jsx import { createStackNavigator } from '@react-navigation/stack' import { NavigationContainer } from '@react-navigation/native' const Root = createStackNavigator() export default function App() { return ( <NavigationContainer> <Root.Navigator> <Root.Screen name="Screen1" component={Screen1} /> <Root.Screen name="Screen2" component={Screen2} /> </Root.Navigator> </NavigationContainer> ) } ``` == Redux (State Management) - Redux is a state management library that helps manage the state of an application - The entire state of the application will be represented by one JavaScript object - State tree is read-only, and can only be changed by dispatching actions - State changes are made with pure functions called reducers - Avoid array and object mutations
https://github.com/darkMatter781x/OverUnderNotebook
https://raw.githubusercontent.com/darkMatter781x/OverUnderNotebook/main/entries/auton/skills/skills.typ
typst
#import "../auto-util.typ": * #auton( "Programming Skills", datetime(year: 2024, month: 2, day: 25), "skills.cpp", [ This code attempts to score as many points as possible in the 60-second skills period. We do this by first matchloading, then crossing under the elevation bar to make 2 rams into the right side of the goal. Then we go around the center triballs and make 2 rams into the front side of the goal. Next, we sweep the triballs in the barrier corner and matchload zone and make 2 rams into the left side of the goal. Finally we elevate on the blue elevation bar and retract the lift with 2 seconds left in the period to gain 10 points. This auto skills route consistently scores 170+ points. ], )[ // https://excalidraw.com/#json=MVPLeZyU88mukurW_liIF,i0q5jTXChyP0Dsze-3bwcw #figure(image("./route.svg", width: 100%), caption: [ auton route ]) ```cpp void runSkills() { lemlib::Timer timer {60000}; matchload(2, INT_MAX); // matchload(); // set slew to 5 for skills Robot::chassis->lateralSettings.slew = 5; // intake matchload for jumping over bar Robot::Actions::intake(); // go down elevation alley // make sure we don't hit short barrier Robot::chassis->moveToPoint(-TILE_LENGTH * .75, -TILE_LENGTH * 2.65, 5000, {.minSpeed = 127}); pros::delay(500); // wait until the robot's y position is past the short barrier waitUntil([] { return Robot::chassis->getPose().y < -TILE_LENGTH * 2.3 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // get past second short barrier Robot::chassis->moveToPoint(TILE_LENGTH, -TILE_LENGTH * 2.5, 5000, {.minSpeed = 127}); // time catapult retract as we go under elevation bar waitUntil([] { return Robot::chassis->getPose().x > -TILE_LENGTH * .75 || !isMotionRunning(); }); printf("fire\n"); Robot::Subsystems::catapult->fire(); // wait until the robot's x position is past the elevation bar waitUntil([] { return Robot::chassis->getPose().x > -TILE_LENGTH * .5 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); Robot::chassis->setPose(Robot::chassis->getPose() + lemlib::Pose {0, -3}, false); // go to the right side of the goal Robot::chassis->moveToPose(TILE_LENGTH * 2.5, -TILE_LENGTH, UP, 5000); // wait until facing towards goal waitUntil([] { return robotAngDist(UP) < 15 || !isMotionRunning(); }); // give a bit of time to ram Robot::chassis->cancelMotion(); Robot::chassis->moveToPoint(TILE_LENGTH * 2.5, 0, 700, {.minSpeed = 127}); Robot::chassis->waitUntilDone(); printf("ram!!!\n"); // remove triball from intake Robot::Actions::outtake(); // second ram // back out of goal tank(-127, -127, 300, 3); tank(127,127,150,3); // ram into goal Robot::chassis->moveToPoint(0, 100000000, 600, {.minSpeed = 127}); Robot::chassis->waitUntilDone(); // adjust y a bit: y = y + 4 Robot::chassis->setPose(Robot::chassis->getPose().x, Robot::chassis->getPose().y + 4, Robot::chassis->getPose().theta); // back out of goal tank(-127, -127, 400, 0); // go around center triballs lemlib::Pose aroundFrontTriballsTarget {TILE_LENGTH * .75, -TILE_LENGTH * 1.35}; Robot::chassis->moveToPoint(aroundFrontTriballsTarget.x, aroundFrontTriballsTarget.y, 5000, {.minSpeed = 127}); // wait until having gone around center triballs waitUntilDistToPose(aroundFrontTriballsTarget, 12, 100, true); Robot::chassis->cancelMotion(); // prevent sudden jolt tank(96,96,0,0); tank(64,-64,600, 5); // face towards center triballs Robot::chassis->moveToPose(TILE_LENGTH * 1.75, -TILE_LENGTH * .75, RIGHT, 2000, {.minSpeed = 64}); // wait until facing towards center triballs waitUntil([] { return robotAngDist(RIGHT) < 10 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // expand the wings in preparation for ram into center Robot::Actions::expandBothWings(); Robot::chassis->moveToPoint(MAX_X, -TILE_RADIUS, 800, {.minSpeed = 127}); Robot::chassis->waitUntilDone(); //adjust odom Robot::chassis->setPose(Robot::chassis->getPose() + lemlib::Pose {-4, 2}, false); // get out of goal Robot::Actions::retractBothWings(); Robot::chassis->moveToPoint(TILE_LENGTH * .75, Robot::chassis->getPose().y, 5000, {.forwards = false, .minSpeed = 64}); // second center ram // face towards center triballs Robot::chassis->moveToPose(TILE_LENGTH * 1.75, TILE_LENGTH * .6, RIGHT, 2000, {.minSpeed = 64}); pros::delay(500); // wait until facing towards center triballs waitUntil([] { return robotAngDist(RIGHT) < 10 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // expand the wings in preparation for ram into center Robot::Actions::expandBothWings(); // ram into center second time Robot::chassis->moveToPoint(MAX_X, TILE_RADIUS, 1100, {.minSpeed = 127}); Robot::chassis->waitUntilDone(); Robot::Actions::retractBothWings(); // get out of goal lemlib::Pose outOfTheGoalTarget {Robot::Dimensions::drivetrainLength / 2 + 2, TILE_LENGTH}; Robot::chassis->moveToPoint(outOfTheGoalTarget.x, outOfTheGoalTarget.y, 1000, {.forwards = true, .minSpeed = 127}); // wait near pose waitUntilDistToPose(outOfTheGoalTarget, 9, 100, true); // then face up Robot::chassis->turnTo(0, 10000000, 1000); // wait until facing up waitUntil([] { return robotAngDist(UP) < 30 || !isMotionRunning(); }); Robot::chassis->cancelMotion(); // sweep triballs in barrier corner lemlib::Pose barrierCornerSweepTarget {TILE_LENGTH * 1.6, TILE_LENGTH * 1.5 - 2}; Robot::chassis->moveToPose(barrierCornerSweepTarget.x, barrierCornerSweepTarget.y, RIGHT, 2000, {.minSpeed = 64}); // wait until near pose waitUntilDistToPose(barrierCornerSweepTarget, 8, 100, true); Robot::chassis->cancelMotion(); // sweep triballs next to matchload zone lemlib::Pose matchloadZoneSweepTarget {TILE_LENGTH * 1.5, TILE_LENGTH * 2.7}; Robot::chassis->moveToPoint(matchloadZoneSweepTarget.x, matchloadZoneSweepTarget.y, 1500, {.minSpeed = 64}); // wait until near pose waitUntilDistToPose(matchloadZoneSweepTarget, 9, 100, true); Robot::chassis->cancelMotion(); // ram into left side of goal Robot::chassis->moveToPose(TILE_LENGTH * 2.6, TILE_LENGTH, DOWN, 2200, {.minSpeed = 64}); Robot::chassis->waitUntilDone(); // second ram // back out of goal tank(-127, -127, 300, 3); // ram into goal Robot::chassis->moveToPoint(0, -10000000, 700, {.minSpeed = 127}); Robot::chassis->waitUntilDone(); // back out of goal tank(-127, -64, 400, 0); // elevation Robot::chassis->moveToPose(-TILE_LENGTH, TILE_LENGTH * 2.5, LEFT, 5000); Robot::chassis->waitUntil(12); Robot::Subsystems::lift->extend(); // wait until 2 seconds left in auton to retract the lift waitUntil( [&timer] { return !isMotionRunning() || timer.getTimeLeft() < 2000; }); Robot::chassis->cancelMotion(); Robot::Subsystems::lift->retract(); } ``` ]
https://github.com/jeremiahdanielregalario/BS-Mathematics-UP-Diliman-Course-Notes
https://raw.githubusercontent.com/jeremiahdanielregalario/BS-Mathematics-UP-Diliman-Course-Notes/main/Math%20110.1%20(Abstract%20Algebra%20I)/Math%20110.1%20Unit%201.typ
typst
#set text(font: "Fira Sans Math") #set page(paper: "a4") #set text(size: 30pt) #set align(horizon) = Math 110.1 ABSTRACT ALGEBRA I: Unit I #set text(size: 14pt, ) #emph[Course Notes by: <NAME>] \ #emph[II-BS Mathematics] \ #emph[University of the Philippines - Diliman] \ #emph[Dr. <NAME>] #pagebreak() #set page( margin: (top: 60pt, bottom: 60pt), numbering: "1", ) #set text(font: "Fira Sans Math", size: 12pt) #set align(top) = The Division Algorithm in $ZZ$ (Theorem 1.1) #line(length: 100% ) #underline[=== Statement:] Let $n in ZZ$ such that $n > 0$. Let $m in ZZ$. Then, there exist unique $q, r in ZZ $ with the property $m=n q+r$ where $0 <= r <= n$. $ (forall n in NN)(forall m in ZZ)(exists!q, r in ZZ | m = n q + r and 0 <= r < n) $ #underline[=== Remark:] - We call $q$ and $r$ as the #underline[_quotient_] and #underline[_remainder_], respectively, when $m$ is divided by $n$. - The dividend $m$ #underline[may be] a _negative number_. #underline[=== Example:] - $n = 3 and m = -17 arrow.double.long m = 3(-6) + 1$ \ #underline[== The Divides ($divides$) Notation] #underline[=== Definition:] Let $m, n in ZZ$ with $n > 0$. We say that $n$ divides $m$ (or, equivalently, $n$ is a factor of $m$, or $n$ is a divisor of $m$) written $n divides m$ if (and only if): $ exists k in ZZ, m = n k $ #underline[=== Example:] - $6 divides -18$ since $-18=6(-3)$ - $3divides.not -16$ #underline[=== Remark:] - Let $a, b, n in ZZ$ with $n>0$. $n|(a - b)$ if and only if $a$ and $b$ leave the same remainder when divided by $n$. #block(stroke: 1pt, radius: 5pt, inset: 15pt)[ #underline[*Proof*]. By the division algorithm, there exists unique integers $q_1, r_1, q_2, r_2 in ZZ$ such that $a = n q_1 + r_1$ and $b = n q_2 + r_2$ where $0 <= r_1, r_2 < n$. ($arrow.double.long.l$) Assume that $r_1 = r_2$. Then, $r_1 - r_2 = 0$. It follows that: $ a - b &= (n q_1 + r_1) - (n q_2 + r_2) \ &= a - b \ &= n q_1 - n q_2 + (r_1 - r_2) \ &= n(q_1 - q_2) $ where $q_1 - q_2 in ZZ$. Hence, $n|(a - b). $ ($arrow.double.long$) Assume that $n divides (a - b)$. Then, there exists $k in ZZ$ such that $a-b=n k$. It follows that: $ n k &= a - b \ &= (n q_1 + r_1) - (n q_2 + r_2) \ &= n (q_1 - q_2) + (r_1 - r_2) \ $ From here, we get that: $ r_1 - r_2 = n(k - (q_1 - q_2)), \ space space k - (q_1 - q_2) in ZZ \ arrow.long.double n divides (r_1 - r_2) $ Note that $0 <= r_1, r_2 < n arrow.double.long -n < r_1 -r_2 < n$. where $q_1 - q_2 in ZZ$. Hence, $n divides (a - b). $ Since $0$ is the only integer between $-n$ and $n$ which is divisble by $n$, then $r_1 - r_2 = 0 arrow.long.double r_1 = r_2.$ $square.filled$ ] - The definition also holds for $n < 0$, so $n eq.not 0$ is a more powerful statement of the defintion. \ #underline[== Congruence Modulo _n_] #underline[=== Definition:] Let $a, b, n in ZZ$ such that $n > 0$. We say that #underline[$a$ is congruent to $b$ modulo $n$] written $a equiv b space (mod n)$ or $a scripts(equiv)_n b$ if (and only if): $ n divides( a - b) $ #underline[=== Example:] - $17 equiv 5 space. (mod 6)$ - $5 equiv.not 25 space.en (mod 7)$ - $6 equiv -4 space (mod 5)$ #underline[=== Remark:] - Let $a, b, n in ZZ$ with $n>0$. Then, $ a scripts(equiv)_n b arrow.double.l.r.long$ $a$ and $b$ have the same remainder when divided by $n $. \ #underline[== Equivalence Relation ] #underline[=== Definition:] An #underline[equivalence relation] is a special type of a relation $tilde$ written $x tilde y$ when $x$ is related to $y$ such that for every elements $a, b, c in S$, where $S$ is a set: - (_reflexive_) $a tilde a$ - (_symmetric_) $a tilde b arrow.double.long b tilde a $ - (_transitive_) $a tilde b and b tilde c arrow.double.long b tilde c $ #underline[=== Example:] - Let $S = ZZ$. Define the relation $tilde$ on $ZZ$ by $ a tilde b arrow.long.double.l.r a equiv b space (mod 3) $ (_reflexive_) Let $a in ZZ.$ Then, $a tilde a arrow.long.double.l.r 3 divides (a - a) arrow.long.double.l.r a equiv a space (mod 3)$. \ (_symmetric_) Let $a, b in ZZ.$ Suppose that $a tilde b$. (Show: $b tilde a$) $ a tilde b &arrow.double.long 3 divides (a - b)\ &arrow.double.long a - b = 3k, space.quad exists k in ZZ \ &arrow.double.long b - a = 3(-k), space.quad -k in ZZ \ &arrow.double.long 3 divides (b - a )\ &arrow.double.long b tilde a $ (_transitive_) Let $a, b, c in ZZ.$ Suppose that $a tilde b$ and $b tilde c$. (Show: $a tilde c$) $ a tilde b and b tilde c &arrow.double.long 3 divides (a - b) and 3 divides (b - c)\ &arrow.double.long a - b = 3k and b - c = 3 ell, space.quad exists k, ell in ZZ \ &arrow.double.long a = 3k + b and b = 3 ell + c, space.quad \ &arrow.double.long a = 3k + (3 ell + c) \ &arrow.double.long a - c = 3(k + ell), space.quad k + ell in ZZ \ &arrow.double.long 3 divides (a - c )\ &arrow.double.long a tilde c $ \ #underline[== Equivalence Classes] #underline[=== Definition:] Let $tilde$ be an equivalence relation on $S$. Let $a in S$. The #underline[equivalence class] determined by $a$ is the set: $ [a]_(tilde)=a slash tilde = {x in S | x tilde a} $ #underline[=== Remarks:] - $[a]_tilde eq.not diameter$ - An element of an equivalence class is called a #underline[representative] of the equivalence class. \ #underline[== Partition] #underline[=== Definition:] A #underline[partition] of a set $S$ is a collection of non-empty disjoint subsets of $S$ whose union is $S$. In other words, $cal(P)$ is a partion of $S$ if and only if the following holds - $forall P, Q in cal(P), P = Q or P sect Q = cancel(circle)$ - $display(union.big_(P in cal(P))) P = S$ \ #underline[== Theorem 1.2] #underline[=== Statement:] If $tilde$ is an equivalence relation on $S$, then the equivalence class form a partition of $S$. #underline[=== Examples:] - $S = RR^(*), a tilde b <==> a b > 0$ Equivalence classes of $tilde$: - $ [1] &= {x in S | 1 dot x >0} \= {x in RR^(*) | x >0} &= (0, + infinity) $ - $ [1] &= {x in S | (-1) x >0} \= {x in RR^(*) | x < 0} &= (-infinity, 0) $ - $S = ZZ, a <==> a equiv b space (mod 3) <==> 3divides (a-b)$ Equivalence classes: - $[0] = {dots, -6, -3, 0,3,6,dots} =: 3ZZ = [-3] = [6]$ - $[1] = {dots, -5, -2, 1,4,7,dots} =: 1+ 3ZZ = [-5] = [4]$ - $[2] = {dots, -4, -1, 2,5,8,dots} =: 2+ 3ZZ = [-1] = [8]$ #underline[=== Remark:] - When the equivalence relation is clearly defined, we can denote $[a]_(tilde)$ simply as $[a]$. - The equivalence relation congruence modulo $n$ $(scripts(equiv)_n)$ partitions $ZZ$ into $n$ equivalence classes: $ [0], [1], dots, [n - 1] $ #pagebreak() #set page( margin: (top: 60pt, bottom: 60pt), numbering: "1", ) #set text(font: "Fira Sans Math", size: 12pt) #set align(top) = Binary Operations and Groups #line(length: 100% ) #underline[=== Definition:] A binary operation $*$ on a non-empty set $S$ is a function from $S times S$ to $S$. $ *: S times S &-> S \ (a,b) &|-> a * b $ #underline[*Examples*]: + $S = RR$
https://github.com/lphoogenboom/typstThesisDCSC
https://raw.githubusercontent.com/lphoogenboom/typstThesisDCSC/master/README.md
markdown
# Typst Thesis Template for DCSC Students This is a transliteration of LaTeX template to Typst for theses at Delft Centre for Systems & Control at Delft University of Technology. Check out this [**Live Preview**](https://typst.app/project/rYJB_ORKNHmdgWC7pap-Cm) of the latest version!
https://github.com/sdsc-ordes/modos-poster
https://raw.githubusercontent.com/sdsc-ordes/modos-poster/main/src/modos.typ
typst
Creative Commons Attribution 4.0 International
// Import a theme #import "/src/sdsc_poster.typ": * #import themes.boxes: * // Set up paper dimensions and text #set page(width: 84.1cm, height: 118.9cm) #set text(font: "Museo", size: 26pt, weight: 100) #let big_text(t) = text(font: "Century Gothic Paneuropean", weight: 300, t); // Set up colors #show: theme.with(titletext-size: 86pt) // whenever we type zarr, show the logo :p #let linkml = box[ #box(image( "/assets/images/logos/linkml.png", height: 1em )) linkml ] #let zarr = box[ #box(image( "/assets/images/logos/zarr.png", height: 1em )) zarr ] // Add content #poster-content(col: 2)[ // Add title, subtitle, author, affiliation, logos #poster-header( title: big_text[MultiOmics Digital Objects (MODOS)], subtitle: big_text[One object to map them all], authors: [ <NAME>, <NAME>, <NAME>, <NAME> ], affiliation: [Swiss Data Science Center], logo-1: image("/assets/images/logos/modos_dark.svg", width: 90%), ) // Include content in the footer #poster-footer[ #set text(fill: black) #align(right)[ #grid( columns: 4, inset: 12mm, image("/assets/images/logos/sdsc.jpg", height: 2cm), image("/assets/images/logos/smoc.jpg", height: 3cm), image("/assets/images/logos/phrt.png", height: 3cm), image("/assets/images/logos/health2030.jpg", height: 3cm), )], ] // normal-box is used to create sections #normal-box()[ #big_text[= Challenges] - Omics file are often separated from their context, losing their traceability - Large data volumes require efficient storage and access - Research data is often siloed and not easily accessible ] // color can be overwritten #normal-box(color: rgb("#e0e2efff"))[ #big_text[= Objectives] #grid(columns: 2, gutter: 6mm, [ - FAIR queryable, linked metadata to facilitate further research - automatic metadata sync. across omics - efficient compression - remote (distributed) streaming access - standardization],[ #figure(image("/assets/images/figures/multiomics.svg", width: 60%), caption: [_Synchronizing multiomics data within one digital object_])] ) ] #normal-box()[ #big_text[= MODOS Design] - hierarchical #zarr archives for arrays - associated omics data files - metadata with formal #linkml schema linking all artifacts #figure(image("/assets/images/figures/digital-object-structure.svg", width: 100%), caption: [_Hierarchical object structure with metadata, arrays and files_]) ] #normal-box()[ #big_text[= MODOS Server] - htsget server to stream genomics data - S3 bucket for data storage - modos-server exposing a REST api - easy interactions via python API or CLI #figure(image("/assets/images/figures/architecture_simple.svg", width: 80%)) ] #normal-box()[ #big_text[= Roadmap] Development focused on internal deployment without access control so far. Once the deployment is stable, we will focus on scaling the system and adding access control. #figure(image("/assets/images/figures/roadmap.svg", width: 80%)) ] #normal-box()[ #big_text[= Demo] // syntax highlighting theme imported from file #set raw(theme: "/assets/themes/halcyon.tmTheme") #show raw: it => block( fill: rgb("#1d2433"), inset: 18pt, radius: 10pt, text(fill: rgb("#a2aabc"), it) ) Remote objects can be accessed viat the CLI or python API: #grid(columns: 2, rows: 2, row-gutter: 4mm, column-gutter: 2mm, [#box(image("/assets/images/figures/qr-api.png", width: 1.5em)) #big_text[CLI]], [#box(image("/assets/images/figures/qr-api.png", width: 1.5em)) #big_text[API]], [#text(23pt)[```bash $ modos show --zarr s3://bucket/ex data / └── data ├── calls1 └── demo1 $ modos show s3://bucket/ex data/demo1 data/demo1: '@type': DataEntity data_format: CRAM data_path: demo1.cram description: Dummy data for tests has_reference: - reference/reference1 has_sample: - sample/sample1 name: Demo 1 $ modos stream s3://bucket/ex/demo1.cram ```]], [#text(23pt)[```python >>> from modos.api import MODO >>> ex = MODO('s3://bucket/ex') >>> ex.list_samples() ['sample/sample1'] >>> ex.metadata["data/calls1"] {'@type': 'DataEntity', 'data_format': 'BCF', 'data_path': 'calls1.bcf', 'description': 'variant calls for tests', 'has_reference': ['reference/reference1'], 'has_sample': ['sample/sample1'], 'name': 'Calls 1'} >>> stream = ex.stream_genomics( "calls1.bcf", "chr1:103-1321" ) >>> next(stream).alleles ('A', 'C') ```]], ) ] #normal-box(color: rgb("#e0e2efff"))[ #big_text[= Want to know more?] MODOS is open-source! We would love to have you try it out, and contributions are welcome. #grid(columns: 2, gutter: 5mm, [- Repository:], [github.com/sdsc-ordes/modos-api], [- Documentation:], [sdsc-ordes.github.io/modos-api], [- Data model:], [sdsc-ordes.github.io/modos-schema] ) ] #big_text[= Acknowledgements] MODOS development is funded by the Personalized Health Data Analysis Hub, a joint initiative of PHRT and SDSC. We gratefully acknowledge members of the DAIP team at the Health 2030 Genome Center for their substantial contributions to the development of MODOS by providing test data sets, deployment infrastructure, and expertise #big_text[= References] #set text(size: 0.8em) + <NAME> (2024) “zarr-developers/zarr-python: v2.17.0”. Zenodo. doi: 10.5281/zenodo.10659377. + <NAME>, et al. (2019) "htsget: a protocol for securely streaming genomic data", Bioinformatics, doi: 10.1093/bioinformatics/bty492 #big_text[= Notes] #zarr: a hierarchical format for the storage of chunked, compressed, N-dimensional arrays #linkml: a modeling language that can be used with linked data, JSON, and other formalisms. #box( width: 4.5cm, image("/assets/images/logos/cc-by.svg"), ) This work is licensed under the #link("https://creativecommons.org/licenses/by/4.0")[Creative Commons Attribution 4.0 International License] ]
https://github.com/Tiggax/zakljucna_naloga
https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/figures/bioreactor.typ
typst
#import "@preview/cetz:0.2.2": canvas, plot, draw, vector #let reactor = canvas( length: 1cm, { import draw: * let mesalo(pos, shift: 0deg)= group( { set-origin(pos) for x in (1,2,3) { group( { rotate(y: x * 120deg + shift, x: 60deg) rect((0.1,-1), (1,1), fill: teal, stroke: .2pt) } ) } } ) rect((),(5,10), radius: 2, name: "canister") group( { let substrate = green.transparentize(60%) let pos = (2.5,6.5) stroke(none) fill(substrate) rect((rel: (-2.5,-6.5), to: (pos)), (rel: (2.5,0), to: pos), radius: (south: 2)) rotate(x: 100deg, z: -10deg, origin: pos) //circle((rel: (-2.05,-1.05), to: pos), radius: .01, stroke: black) //arc((rel: (-2.0,-1.1), to: pos),start: 200deg, stop: 37deg, radius: 2.3) circle(pos, radius: 2.3, stroke: substrate) } ) rect((2.4,2, 0),(2.6,10,0), fill: teal) mesalo((2.5,2)) mesalo((2.5,5), shift:50deg) } ) #let reactor = canvas( length: 1cm, { import draw: * rect((), (6,8), stroke: 2pt) line((rel: (-3,0), to: ()), (rel: (0,-5), to: ()), stroke: 2pt) line((), (rel: (1.5,0.5), to: ()),(rel: (0,-1)),(rel: (-1.5,0.5)), stroke: 1pt,) line((), (rel: (-1.5,0.5), to: ()),(rel: (0,-1)),(rel: (1.5,0.5)), stroke: 1pt,) } ) #let batch_reactor = canvas( length: 1cm, { import draw: * rect((), (6,8), stroke: 2pt) line((rel: (-3,0), to: ()), (rel: (0,-5), to: ()), stroke: 2pt) line((), (rel: (1.5,0.5), to: ()),(rel: (0,-1)),(rel: (-1.5,0.5)), stroke: 1pt,) line((), (rel: (-1.5,0.5), to: ()),(rel: (0,-1)),(rel: (1.5,0.5)), stroke: 1pt,) line((2,7.5), (rel: (0,2)), (rel: (-2,0)), mark:(start: ">")) line((1.5,7.5), (rel: (0,1.5)), (rel: (-1.5,0)), mark:(start: ">")) line((1.98,8), (1.52,8), stroke: white + 2.5pt) } )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/with_user_func.typ
typst
Apache License 2.0
#let f(font, stroke) = text(font: font, stroke: stroke); #let g = f.with(/* position */);
https://github.com/donghoony/KUPC-2023
https://raw.githubusercontent.com/donghoony/KUPC-2023/master/main.typ
typst
#import "template.typ": * #import "abstractions.typ" : abstract_page #import "problems.typ" : contest_problems #import "problem_info.typ" : info #import "colors.typ" : * #import "description.typ" : create_page #show: project.with() #abstract_page(problems: contest_problems) #for i in range(contest_problems.len()) { info(contest_problems.at(i)) create_page(i) }
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/linear/rules.typ
typst
The Unlicense
#import "format.typ": * #import "/utils.typ" #let rules = utils.make-rules(doc => { set text( font: "Blinker", size: 11pt, ) doc })
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/bytefield/0.0.4/lib/states.typ
typst
Apache License 2.0
// states #let __default_row_height = state("bf-row-height", 2.5em); #let __default_header_font_size = state("bf-header-font-size", 9pt); // function to use with show rule #let bf-config( row_height: 2.5em, header_font_size: 9pt, content ) = { __default_row_height.update(row_height); __default_header_font_size.update(header_font_size) content } #let _get_row_height(loc) = { __default_row_height.at(loc) } #let _get_header_font_size(loc) = { __default_header_font_size.at(loc) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-aspect_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that minimum wins if both width and height are given. #stack( dir: ltr, spacing: 2pt, square(width: 20pt, height: 40pt), circle(width: 20%, height: 100pt), )
https://github.com/ckunte/m-one
https://raw.githubusercontent.com/ckunte/m-one/master/inc/model.typ
typst
= Building a model #figure( image("/img/model.png", width: 100%), caption: [ Building this model from scratch with error-checking, testing for integrity, and preparing for pushover ] ) <model> A few months ago, I found the need to rebuild a complex finite element model of a jacket substructure. This was after exhausting the option of modifying one built by an agency. I needed to shift two of jacket's horizontal frames in the water column, and move to re-align all associated frames and elements. Thereafter port the model to USFOS@holmas_usfos_theory error-free, re-code loads, hydrodynamic properties, marine growth, and re-attach foundation model before proceeding to perform a series of non-linear progressive collapse analyses. Every time I tried modifying the geometry of the existing model, I found the highly fragmented launch truss in my way. The more I tried changing it, the more I found it exhausting and frustrating. But I dreaded building one from scratch more. For one, the existing model was built by a team of engineers, had undergone rigorous quality control, and was the foundation upon which an entire phase of the project was engineered. In other words, I was not sure I'd do any better than this team. And two, it's been years since I built one from ground up, and so it was going to test my rusty skills, and it would hammer my confidence if I failed. On building a model, Dr Holmas once said to me: #quote()[ _Build your computer model like you would build a scaled physical model with details relevant and sufficient (no less and no more) to undertake model testing._ ] It's common sense, of course, but in reality give man a sophisticated piece of software only to watch him get himself entangled in complexity. People build the most complex models even when all they need is a simple one. That said, it is hard not to empathise with teams that work under tremendous time pressures, and there are no credits for creating task-specific models. Instead, teams build one that can be used and re-purposed for performing a series of tasks. Fortunately, my task is always specific --- concept development, stress-testing asset integrity, design optimisation, or trouble-shooting. So Dr Holmas's words have since been guiding me. Planning my approach on building a model first on a piece of paper was therapeutic, and I set myself ample time, just to be consoled that I had the time necessary to build one needed for the task. In the process, I re-discovered that symmetry is your friend, which helps one produce error-free replicable and merge-able geometry. The planning allowed me to identify parts of the structure I could replicate. The first part (a two-dimensional frame) I actually built using a spreadsheet --- by mapping key coordinates, and then exporting it to a comma separated file. ``` Label, ID, X, Y, Z NODE,4,-15.0,-23.50,-18.0 NODE,5,-15.0,23.50,-18.0 NODE,6,15.0,-23.50,-18.0 NODE,7,15.0,23.50,-18.0 NODE,8,0.0,-36.50,-62.37 ... ``` Then I wrote this tiny script to format the above CSV file (say, _part.csv_): ```python #!/usr/bin/env python3 # -*- encoding: utf-8 -*- """Format model data from CSV file 2020 ckunte Usage: gendata.py --fn=filename.ext gendata.py --help gendata.py --version Options: --help Show help screen --fn=filename.ext Furnish datafile, e.g., part.csv --version Show version """ from docopt import docopt import csv from tabulate import tabulate args = docopt(__doc__, version="Format model data from CSV file, 0.1") f = str(args["--fn"]) with open(f, "r") as csvfile: alldata = [] reader = csv.reader(csvfile, skipinitialspace=True) for i in reader: alldata.append(i) print(tabulate(alldata, headers="firstrow", floatfmt=".6f")) ``` This would format the _part.csv_ file and produce the following output, which could be copy-pasted (or exported) to a new input file. ```bash $ python3 gendata.py --fn=part.csv Label ID X Y Z ------- ---- ---------- ---------- ----------- NODE 4 -15.000000 -23.500000 -18.000000 NODE 5 -15.000000 23.500000 -18.000000 NODE 6 15.000000 -23.500000 -18.000000 NODE 7 15.000000 23.500000 -18.000000 NODE 8 0.000000 -36.500000 -62.370000 ... ``` The good thing about the script is that it does not care how long your csv file is. For example, if it is less than ten lines, then one would think writing a script to format it is an overkill. But if it is made up of hundreds, then mindless formatting by hand is taxing. So it helps to work smart, while also keeping the edited file error-free. For parts that had complex geometric transitions, I ended up modelling these in SACS first as SACS Precede has excellent modelling features. In aggregate 25% of the model was built by hand and the rest by replication --- via copying, mirroring, and offsetting. In the part built by hand, I selectively excluded features in the stiffness model that were either not relevant or whose exclusion would not impact the quality of results. The parts excluded from the substructure pushover model, while retaining their self weight, were: + Topsides#footnote[While keeping load distribution intact via reactions and moments.] + Pile sleeves#footnote[Instead, I modelled piles to be connected directly to the diaphragm plates, which in turn lace jacket legs. I did this to simplify the model, since bond strength between piles and pile sleeves, which is enabled via infill grout, is assumed to be sufficiently developed to not undermine pile-to-sleeve mechanical strength at collapse level loads.] + Complex joint cans and conical transition segments within horizontal frames + Joint cans for reinforcing braces + Certain (secondary) supporting diagonal members + Conductor guide frames through the water column + Mudmats, and + Miscellaneous appurtenances Many items from the list above could also be excluded because I had prior estimates of loads from the environment (wave, wind, and current), which could be suitably factored without the need to have a full geometry for generating hydrodynamic loading accurately from the simplified model alone. This is not always possible, especially if one does not have the results from a detailed model that could be re-purposed, but in this case, it helped save a substantial amount of time. In the case of the latter, one could still reasonably account for geometry by hand-calculating effective contributions via drag and mass coefficients (_Cd_ and _Cm_ respectively), like so: $ C_d = Sigma(A_i C_("di")) / A' \ C_m = Sigma(V_i C_("mi")) / V' $ where, - $A_i$ -- drag area of a component (typically projected), - $C_("di")$ -- corresponding drag coefficient, - $A'$ -- drag area of adjusted members (typically projected), - $V_i$ -- volume of a component, - $C_("mi")$ -- corresponding mass coefficient, and - $V'$ -- volume of adjusted members Any manual work demands time, and therefore it's a trade-off --- whether to hand-code coefficients or to model the entire geometry. Most time-constrained engineers tend to take the latter route, since it is easier to build geometry than it is to calculate coefficients for adjusted members in at least three directions.#footnote[Drag and inertia coefficients for various shapes are available in &sect;6.8 Hydrodynamic loading, in the seminal book, _Dynamics of Fixed Marine Structures_, Barltrop and Adams, Third Edition, 1991.] In summary, taking the road generally not taken was both fruitful and satisfying. I could produce comparable results with a substantially simpler model, while also marginally improving its reserve strength in certain directions. Sometimes all that matters is moving the needle a little bit --- in incremental and positive ways that is not only reassuring to the business, but also in building confidence. $ - * - $
https://github.com/bkorecic/enunciado-facil-fcfm
https://raw.githubusercontent.com/bkorecic/enunciado-facil-fcfm/main/template/main.typ
typst
MIT License
#import "@preview/enunciado-facil-fcfm:0.1.0" as template #show: template.conf.with( titulo: "Auxiliar 5", subtitulo: "Usando el template", titulo-extra: ( [*Profesora*: <NAME>], [*Auxiliares*: <NAME> y <NAME>], ), departamento: template.departamentos.dcc, curso: "CC4034 - Composición de documentos", ) = Sumatorias Resuelva: 1. $ sum_(k=1)^n k^3 $ 2. $ sum_(k=1)^n k 2^k $ 3. $ sum_(k=1)^n k 2^k $ = Recurrencias 1. Resuelva la siguiente ecuación de recurrencia: $ T_n = 2T_(n-1) + n, #h(2cm) T_0 = c. $ 2. Sean $a_n, b_n$ secuencias tal que $a_n != 0$ y $b_n != 0$ $forall n in NN$. Sea $T_n$ definida como: $ a_n T_n = b_n T_(n-1) + f_n, #h(2cm) T_0 = c. $ Obtenga una fórmula no recursiva para $T_n$. 3. Usando el método visto en clases, resuelva: $ T_n = (T_(n-1)/T_(n-2))^4 dot 8^(n dot 2^n), #h(2cm) T_0 = 1, T_1 = 2. $ = Funciones generadoras 1. Considere la recurrencia definida para $n <= 0$: $ a_(n+3) = 5a_(n+2) - 7a_(n+1) + 3a_n + 2^n, $ con $a_0 = 0$, $a_1 = 2$ y $a_2 = 5$. Utilizando funciones generadoras, resuelva la recurrencia. 2. Cuente el número de palabras en ${0,1,2}^n$ tal que cada subpalabra maximal de ${0}^*$ tiene largo par.
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/docs/src/developer_documentation/custom_themes.md
markdown
The Unlicense
# Making Your Own Theme If you're unhappy with the existing themes, or just want to add your own flair to your notebook, the Notebookinator supports custom themes. We highly recommend you familiarize yourself with the [Typst Documentation](typst.app/docs) before trying to implement one yourself. Themes consist of two different parts, the theme itself, and its corresponding components. The theme is just a dictionary containing functions. These functions specify how the entries and cover should look, as well as global rules for the whole document. We'll cover the required structure of this variable in a [later](#the-theme-variable) section. Components are simply functions stored in a module. These functions contain things like pro/con tables and decision-matrices. Most components are just standalone, but the Notebookinator does supply some utility functions to help with implementing harder components. Implementing components will be covered in [this](#writing-components) section. ## File Structure The first thing you'll need to do is create a folder for your theme, somewhere in your notebook. As an example, lets create a theme called `foo`. The first thing we'll want to do is create a folder called `foo/`. Then, inside that folder, we'll want to create a file called `foo.typ` inside the `foo/` folder. This will be the entry point for your theme, and will contain your theme variable. Then, we'll want to create a `foo/components/components.typ` file. This file will contain all of your components. We recommend having each component inside of its own file. For example, an `example-component` might be defined in `foo/components/example-component.typ`. You'll also want to create an `entries.typ` file to contain all of your entry functions for your theme variable, and a `rules.typ` to store your global rules. Your final file structure should look like this: - `foo/` - `foo.typ` - `entries.typ` - `rules.typ` - `components/` - `components.typ` ```admonish info This is just the recommended file structure, as long as you expose a theme variable and components, your theme will work just like all the others. You can also add any additional files as you wish. ``` ## The Theme Variable The first thing you should do is create a theme variable. Going back to our `foo` example, lets create a `foo-theme` variable in our `foo/foo.typ` file. ```typ // foo/foo.typ // use this if you're developing inside the notebookinator #import "/utils.typ" // use this if you're developing a private theme #import "@local/notebookinator:1.0.1": * #let foo-theme = utils.make-theme() // will not currently compile ``` Themes are defined with the `make-theme` function found in the `utils` namespace. This function verifies that all of your inputs are correct, and will return a correctly structured theme. However, it requires that all of your theme functions are specified in order to compile, so that's the next thing we'll be doing. ### Creating The Entries Now that we actually have a place to put our theme functions, we can start implementing our entry functions. Each of these functions has 2 requirements: - it must return a `page` function as output - it must take a dictionary parameter named `ctx` as input, and a parameter called body. The `ctx` argument provides context about the current entry being created. This dictionary contains the following fields: - `title`: `str` - `type`: `str` - `date`: `datetime` - `author`: `str` - `witness`: `str` `body` contains the content the user has written. It should be passed into the `page` function in some shape or form. We'll write these functions in the `foo/entries.typ` file. Below are some minimal starting examples: ### Frontmatter ```typ // foo/entries.typ // to import utils, see The Theme Variable section #let frontmatter-entry = utils.make-frontmatter-entry((ctx, body) => { show: page.with( // pass the entire function scope into the `page` function header: [ = ctx.title ], footer: context counter(page).display("i") ) body // display the users's written content }) ``` ### Body ```typ // foo/entries.typ // to import utils, see The Theme Variable section #let body-entry = utils.make-body-entry((ctx, body) => { show: page.with( // pass the entire function scope into the `page` function header: [ = ctx.title ], footer: context counter(page).display("i") ) body // display the users's written content }) ``` ### Appendix ```typ // foo/entries.typ // to import utils, see The Theme Variable section #let appendix-entry = utils.make-appendix-entry((ctx, body) => { show: page.with( // pass the entire function scope into the `page` function header: [ = ctx.title ], footer: context counter(page).display("i") ) body // display the users's written content }) ``` With the entry functions written, we can now add them to the theme variable. ```typ // foo/foo.typ // to import utils, see The Theme Variable section // import the entry functions #import "./entries.typ": frontmatter-entry, body-entry, appendix-entry // add the entry functions to the theme #let foo-theme = utils.make-theme( frontmatter-entry: frontmatter-entry, body-entry: body-entry, appendix-entry: appendix-entry, ) ``` ### Creating a Cover Then you'll have to implement a cover. The only required parameter here is a context variable, which stores information like team number, game season and year. Here's an example cover: ```typ // foo/entries.typ // to import utils, see The Theme Variable section #let cover = utils.make-cover(ctx => [ #set align(center + horizon) *Default Cover* ]) ``` Then, we'll update the theme variable accordingly: ```typ // foo/foo.typ // to import utils, see The Theme Variable section // import the cover along with the entry functions #import "./entries.typ": cover, frontmatter-entry, body-entry, appendix-entry #let foo-theme = utils.make-theme( cover: cover, // add the cover to the theme frontmatter-entry: frontmatter-entry, body-entry: body-entry, appendix-entry: appendix-entry, ) ``` ### Rules Next you'll have to define the rules. This function defines all of the global configuration and styling for your entire theme. This function must take a doc parameter, and then return that parameter. The entire document will be passed into this function, and then returned. Here's and example of what this could look like: ```typ // foo/rules.typ // to import utils, see The Theme Variable section #let rules = utils.make-rules((doc) => { set text(fill: red) // Make all of the text red, across the entire document doc // Return the entire document }) ``` Then, we'll update the theme variable accordingly: ```typ // foo/foo.typ #import "./rules.typ": rules // import the rules #import "./entries.typ": cover, frontmatter-entry, body-entry, appendix-entry // to import utils, see The Theme Variable section #let foo-theme = utils.make-theme( rules: rules, // store the rules in the theme variable cover: cover, frontmatter-entry: frontmatter-entry, body-entry: body-entry, appendix-entry: appendix-entry, ) ``` ## Writing Components With your base theme done, you may want to create some additional components for you to use while writing your entries. This could be anything, including graphs, tables, Gantt charts, or anything else your heart desires. We recommend including the following components by default: - Table of contents `toc` - Decision matrix: `decision-matrix` - Pros and cons table: `pro-con` - Glossary: `glossary` We recommend creating a file for each of these components. After doing so, your file structure should look like this: - `foo/components/` - `components.typ` - `toc.typ` - `decision-matrix.typ` - `pro-con.typ` - `glossary.typ` Once you make those files, import them all in your `components.typ` file: ```typ // foo/components.typ // make sure to glob import every file #import "./toc.typ": * #import "./glossary.typ": * #import "./pro-con.typ": * #import "./decision-matrix.typ": * ``` Then, import your `components.typ` into your theme's entry point: ```typ // foo/foo.typ #import "./components/components.typ" // make sure not to glob import here ``` All components are defined with constructors from the `utils` module. ### Pro / Con Component Pro / con components tend to be extremely simple. Define a function called `pro-con` inside your `foo/components/pro-con.typ` file with the `make-pro-con` from `utils`: ```typ // foo/components/pro-con.typ // to import utils, see The Theme Variable section #let pro-con = utils.make-pro-con((pros, cons) => { // return content here }) ``` This syntax might look a little weird if you aren't familiar with functional programming. `make-pro-con` takes a [`lambda`](https://typst.app/docs/reference/foundations/function/#unnamed) function as input, which is just a function without a name. This function takes two inputs: `pros` and `cons`, which are available inside the scope of the function like normal arguments would be on a named function. For examples on how to create a pro / con table, check out how [other themes](https://github.com/The-Notebookinator/notebookinator/tree/main/themes) implement them. ### TOC Component The next three components are a bit more complicated, so we'll be spending a little more time explaining how they work. Each of these components requires some information about the document itself (things like the page numbers of entries, etc.). Normally fetching this data can be rather annoying, but fortunately the Notebookinator's constructors fetch this data for you. To get started with your table of contents, first define a function called `toc` in your `foo/components/toc.typ` file with the `make-toc` constructor. Using the `make-toc` constructor we can make a `toc` like this: ```typ // foo/components/toc.typ // to import utils, see The Theme Variable section #let toc = utils.make-toc((frontmatter, body, appendix) => { // ... }) ``` Using the constructor gives us access to three variables, `frontmatter`, `body`, and `appendix`. These variables are all [arrays](https://typst.app/docs/reference/foundations/array/), which are dictionaries that all contain the same information as the `ctx` variables from [this](#creating-the-entries) section, with the addition of a `page-number` field, which is an [integer](https://typst.app/docs/reference/foundations/int/). With these variables, we can simply loop over each one, and print out another entry in the table of contents each time. Here's what that looks like for the frontmatter entries: ```typ // foo/components/toc.typ // to import utils, see The Theme Variable section #let toc = utils.make-toc((_, body, appendix) => { // We replace the 'frontmatter' parameter with _ to indicate that we will not use it. // _ replaces frontmatter to indicate we aren't using it heading[Contents] stack( spacing: 0.5em, ..for entry in body { ( [ #entry.title #box( width: 1fr, line( length: 100%, stroke: (dash: "dotted"), ), ) #entry.page-number ], ) }, ) // You'll need to do something similar for the // appendix entries as well, if you want to display them }) ``` ### Decision Matrix Component The decision matrix code works similarly. You can define one like this: ```typ #let decision-matrix = utils.make-decision-matrix((properties, data) => { // ... }) ``` Inside of the function you have access to two variables, `properties`, and `data`. Properties contains a list of the properties the choices are being rated by, while `data` contains the choices alongside the scores for those choices. You can run a [`repr()`](https://typst.app/docs/reference/foundations/repr/) on either of those variables to get a better understanding of how they're structured. Here's a simple example to get you started, copied from the `default-theme`: ```typ // to import utils, see The Theme Variable section #let decision-matrix = utils.make-decision-matrix((properties, data) => { table( columns: for _ in range(properties.len() + 2) { (1fr,) }, [], ..for property in properties { ([ *#property.name* ],) }, [*Total*], ..for (index, choice) in data { let cell = if choice.total.highest { table.cell.with(fill: green) } else { table.cell } ( cell[*#index*], ..for value in choice.values() { (cell[#value.weighted],) }, ) }, ) }) ``` ### Glossary Component The glossary component is similar to the table of components in that it requires information about the document to function. To get access to the glossary entries, you can use the `make-glossary` function provided by the `utils` to fetch all of the glossary terms, in alphabetical order. The function passed into the `print-glossary` function has access to the `glossary` variable, which is an [array](https://typst.app/docs/reference/foundations/array/). Each entry in the array is a dictionary containing a `word` field and a `definition` field. Both are [strings](https://typst.app/docs/reference/foundations/str/). Here's an example from the `default-theme`: ```typ // foo/components/glossary.typ // to import utils, see The Theme Variable section #let glossary() = utils.print-glossary(glossary => { stack(spacing: 0.5em, ..for entry in glossary { ([ = #entry.word #entry.definition ],) }) }) ``` ## Using the Theme Now that you've written the theme, you can apply it to your notebook. In the entry point of your notebook (most likely `main.typ`), import your theme like this: ```typ // main.typ #import "foo/foo.typ": foo-theme, components ``` Once you do that, change the theme to `foo-theme`: ``` // main.typ #show: notebook.with( theme: foo-theme ) ```
https://github.com/drupol/master-thesis
https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/2-related-work.typ
typst
Other
#import "imports/preamble.typ": * #import "theme/template.typ": * #import "theme/common/titlepage.typ": * #import "theme/common/metadata.typ": * #import "theme/disclaimer.typ": * #import "theme/acknowledgement.typ": * #import "theme/abstract.typ": * #import "theme/infos.typ": * = Related work
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/examples/lorem.typ
typst
Other
#import "@preview/ucpc-solutions:0.1.0" as ucpc #import ucpc: color #import ucpc.presets: difficulties as lv #show: ucpc.ucpc.with( title: "Contest Name", authors: ("Solutions Commentary Editorial", ), hero: ucpc.utils.make-hero( title: [Contest Name], subtitle: [Solutions Commentary Editorial], authors: ("Contest Taskforce", ), ), ) #ucpc.utils.make-prob-overview( font-size: .8em, [A], [Problem A], lv.easy, [Author a], [B], [Problem B], lv.normal, [Author b], [C], [Problem C], lv.hard, [Author c], [D], [Problem D], lv.challenging, [Author b], ) #pagebreak() #ucpc.utils.problem( id: "A", title: "Problem A", tags: ("implementation", "graph_theory", ), difficulty: lv.easy, authors: ([Author a], ), stat-open: ( submit-count: 10 ), [ - Magna eu tempor sunt sint laboris nulla culpa labore et quis tempor ad labore ex eiusmod aliquip culpa et incididunt consectetur nostrud velit velit eu magna excepteur ut occaecat cillum aute mollit duis tempor ea officia ex reprehenderit anim eiusmod fugiat adipisicing anim ex do exercitation est anim aliqua irure ullamco tempor irure laboris elit deserunt esse laboris magna ullamco do culpa et ut cillum magna irure Lorem aute sit anim reprehenderit nostrud incididunt officia laborum sint sint adipisicing sint mollit labore excepteur est mollit culpa aliqua duis fugiat nostrud duis sint commodo aliqua proident est incididunt fugiat et irure. ] ) #ucpc.utils.problem( id: "B", title: "Problem B", tags: ("constructive", ), difficulty: lv.normal, authors: ([Author b], ), stat-open: ( submit-count: 128, ac-count: 51, ac-ratio: 39.844, first-solver: "participant #3", ), i18n: ucpc.i18n.en-us.problem, [ - Elit ullamco laborum sint aute deserunt laborum eiusmod dolor sint ut reprehenderit consectetur sunt et sunt in tempor esse amet excepteur deserunt ex mollit ipsum eiusmod enim mollit irure laboris proident enim non sit culpa in magna aliqua labore in ut laborum proident aliqua labore dolor velit proident dolor cupidatat pariatur amet magna magna ipsum incididunt qui dolore cupidatat incididunt in officia excepteur cupidatat irure ex mollit et proident sint amet duis minim officia anim aliqua commodo velit id ad proident consequat fugiat commodo cillum et adipisicing commodo anim est cupidatat irure ea amet dolore qui magna do incididunt ipsum. ] ) #ucpc.utils.problem( id: "C", title: "Problem C", tags: ("ad_hoc", ), difficulty: lv.hard, authors: ([Author c], ), i18n: ucpc.i18n.en-us.problem, [ - Magna aliqua reprehenderit amet ea Lorem cupidatat cillum esse sunt nisi magna tempor in qui proident enim aute veniam laboris amet cillum laboris magna ad laboris elit exercitation aute laborum magna Lorem cillum laborum officia veniam fugiat esse quis amet et consequat adipisicing duis ullamco occaecat quis quis ullamco Lorem sint deserunt anim tempor cillum tempor et ea fugiat pariatur qui fugiat magna sunt laboris sint sint minim incididunt ullamco quis laboris consectetur id sit aliqua sint eiusmod eiusmod esse magna duis ea irure ea laborum ex deserunt exercitation ullamco laboris est et velit sunt labore et proident officia nulla. ] ) #ucpc.utils.problem( id: "D", title: "Problem D", tags: ("dp", "greedy", ), difficulty: lv.challenging, authors: ([Author b], ), stat-open: ( submit-count: 165, ac-count: 41, ac-ratio: 24.848, first-solver: "participant #1" + super("@LOREM"), first-solve-time: 7, ), stat-onsite: ( submit-count: 111, ac-count: 77, ac-ratio: 70.270, first-solver: "participant a", first-solve-time: 2, ), i18n: ucpc.i18n.en-us.problem, [ - Ullamco non cupidatat deserunt anim dolor enim officia culpa excepteur irure aliquip sint non ipsum ea non consequat occaecat incididunt esse in ex enim duis velit consectetur dolor veniam deserunt cupidatat minim do non dolore irure et est in adipisicing commodo dolore ex culpa aute enim cupidatat irure magna minim adipisicing excepteur nostrud do nisi ea incididunt ex commodo anim sint dolore fugiat deserunt eiusmod sit adipisicing veniam eiusmod est reprehenderit non incididunt dolore nisi ad ipsum Lorem et Lorem amet nostrud incididunt irure ex commodo aliqua est fugiat in laboris aute veniam eiusmod eu in irure laboris exercitation nulla. ] )
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/042.typ
typst
#let date = datetime( year: 2023, month: 5, day: 18, ) #metadata(( title: "c++23的std::print简单示例", subtitle: [c++23], author: "dashuai009", description: "", pubDate: date.display(), ))<frontmatter> #import "../__template/style.typ": conf #show: conf == 介绍 cpp23中加入了一个标准库std::print,类似python中的print。据说不是基于std::cout,性能应该有保障。 == 支持的编译器 目前只有msvc支持了这一标准库。在2023/05/17发布的vs2022 17.7.0 preview1中,加入了#link("https://github.com/microsoft/STL/pull/3337")[相关代码]。 == 示例 ```cpp import std; int main() { std::vector test{ 10, 2, 3 }; std::ranges::sort(test); for (auto const& [index, value] : std::ranges::enumerate_view(test)) { std::println("index = {}, val = {}", index, value); } return 0; } ``` 输出 ``` index = 0, val = 2 index = 1, val = 3 index = 2, val = 10 ``` == 看起来不错 看起来有点pythonic
https://github.com/YunkaiZhang233/computer-science-notes
https://raw.githubusercontent.com/YunkaiZhang233/computer-science-notes/main/Symbolic-Reasoning-Imperial/symbolic-reasoning.typ
typst
MIT License
#import "../template.typ": * #show: template.with( title: [Symbolic Reasoning], short_title: "COMP 50009", description: [ for 2023/24 Year 2 Symbolic Reasoning course \ taught by Mr <NAME> and Dr <NAME>, Imperial College London ], date: datetime(year: 2024, month: 03, day: 26), authors: ( ( name: "<NAME>", link: "https://yunkaizhang233.github.io", affiliations: "1", ), ), affiliations: ( (id: "1", name: "Imperial College London"), ), lof: false, lot: false, lol: false, bibliography_file: "Symbolic-Reasoning-Imperial/refs.bib", paper_size: "a4", cols: 1, text_font: "XCharter", code_font: "Cascadia Mono", accent: "#DC143C", // blue ) hello
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/figure.typ
typst
// Test figures. --- figure-basic --- #set page(width: 150pt) #set figure(numbering: "I") We can clearly see that @fig-cylinder and @tab-complex are relevant in this context. #figure( table(columns: 2)[a][b], caption: [The basic table.], ) <tab-basic> #figure( pad(y: -6pt, image("/assets/images/cylinder.svg", height: 2cm)), caption: [The basic shapes.], numbering: "I", ) <fig-cylinder> #figure( table(columns: 3)[a][b][c][d][e][f], caption: [The complex table.], ) <tab-complex> --- figure-align --- #show figure: set align(start) #figure( rect[This is \ left], caption: [Start-aligned] ) --- figure-table --- // Testing figures with tables. #figure( table( columns: 2, [Second cylinder], image("/assets/images/cylinder.svg"), ), caption: "A table containing images." ) <fig-image-in-table> --- figure-placement --- #set page(height: 160pt, columns: 2) #set place(clearance: 10pt) #lines(4) #figure( placement: auto, scope: "parent", caption: [I], rect(height: 15pt, width: 80%), ) #figure( placement: bottom, caption: [II], rect(height: 15pt, width: 80%), ) #lines(2) #figure( placement: bottom, caption: [III], rect(height: 25pt, width: 80%), ) #figure( placement: auto, scope: "parent", caption: [IV], rect(width: 80%), ) #lines(15) --- figure-theorem --- // Testing show rules with figures with a simple theorem display #show figure.where(kind: "theorem"): it => { set align(start) let name = none if not it.caption == none { name = [ #emph(it.caption.body)] } else { name = [] } let title = none if not it.numbering == none { title = it.supplement if not it.numbering == none { title += " " + it.counter.display(it.numbering) } } title = strong(title) pad( top: 0em, bottom: 0em, block( fill: green.lighten(90%), stroke: 1pt + green, inset: 10pt, width: 100%, radius: 5pt, breakable: false, [#title#name#h(0.1em):#h(0.2em)#it.body#v(0.5em)] ) ) } #set page(width: 150pt) #figure( $a^2 + b^2 = c^2$, supplement: "Theorem", kind: "theorem", caption: "Pythagoras' theorem.", numbering: "1", ) <fig-formula> #figure( $a^2 + b^2 = c^2$, supplement: "Theorem", kind: "theorem", caption: "Another Pythagoras' theorem.", numbering: none, ) <fig-formula> #figure( ```rust fn main() { println!("Hello!"); } ```, caption: [Hello world in _rust_], ) --- figure-breakable --- // Test breakable figures #set page(height: 6em) #show figure: set block(breakable: true) #figure(table[a][b][c][d][e], caption: [A table]) --- figure-caption-separator --- // Test custom separator for figure caption #set figure.caption(separator: [ --- ]) #figure( table(columns: 2)[a][b], caption: [The table with custom separator.], ) --- figure-caption-show --- // Test figure.caption element #show figure.caption: emph #figure( [Not italicized], caption: [Italicized], ) --- figure-caption-where-selector --- // Test figure.caption element for specific figure kinds #show figure.caption.where(kind: table): underline #figure( [Not a table], caption: [Not underlined], ) #figure( table[A table], caption: [Underlined], ) --- figure-and-caption-show --- // Test creating custom figure and custom caption #let gap = 0.7em #show figure.where(kind: "custom"): it => rect(inset: gap, { align(center, it.body) v(gap, weak: true) line(length: 100%) v(gap, weak: true) align(center, it.caption) }) #figure( [A figure], kind: "custom", caption: [Hi], supplement: [A], ) #show figure.caption: it => emph[ #it.body (#it.supplement #context it.counter.display(it.numbering)) ] #figure( [Another figure], kind: "custom", caption: [Hi], supplement: [B], ) --- figure-caption-position --- #set figure.caption(position: top) --- figure-caption-position-bad --- // Error: 31-38 expected `top` or `bottom`, found horizon #set figure.caption(position: horizon) --- figure-localization-fr --- // Test French #set text(lang: "fr") #figure( circle(), caption: [Un cercle.], ) --- figure-localization-zh --- // Test Chinese #set text(lang: "zh") #figure( rect(), caption: [一个矩形], ) --- figure-localization-ru --- // Test Russian #set text(lang: "ru") #figure( polygon.regular(size: 1cm, vertices: 8), caption: [Пятиугольник], ) --- figure-localization-gr --- // Test Greek #set text(lang: "gr") #figure( circle(), caption: [Ένας κύκλος.], ) --- issue-2165-figure-caption-panic --- #figure.caption[] --- issue-2328-figure-entry-panic --- // Error: 4-43 footnote entry must have a location // Hint: 4-43 try using a query or a show rule to customize the footnote instead HI#footnote.entry(clearance: 2.5em)[There] --- issue-2530-figure-caption-panic --- #figure(caption: [test])[].caption --- issue-3586-figure-caption-separator --- // Test that figure caption separator is synthesized correctly. #show figure.caption: c => test(c.separator, [#": "]) #figure(table[], caption: [This is a test caption])
https://github.com/TechnoElf/mqt-qcec-diff-presentation
https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-presentation/main/main.typ
typst
#import "@preview/cetz:0.2.2" #import "@preview/fletcher:0.5.1" #import "@preview/gentle-clues:0.9.0" #import "@preview/lovelace:0.3.0" #import "@preview/polylux:0.3.1": * #import "@preview/tablex:0.0.8" #import "@preview/unify:0.6.0" #import "@preview/quill:0.3.0" #import "template/conf.typ": conf, slide #import "template/conf.typ": conf, slide #show: doc => conf( title: "Equivalence Checking of Quantum Circuits using Diff Algorithms", author: "<NAME>", chair: "Chair for Design Automation", school: "School of Computation, Information and Technology", degree: "Bachelor of Science (B.Sc.)", examiner: "Prof. Dr. <NAME>", supervisor: "DI <NAME>", submitted: "11.10.2024", doc ) #set math.vec(delim: "[") #set math.mat(delim: "[") #include("content/introduction.typ") #include("content/outline.typ") #include("content/background.typ") #include("content/implementation.typ") #include("content/results.typ") #include("content/conclusion.typ")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/par-justify-04.typ
typst
Other
// Test that the last line can be shrunk #set page(width: 155pt) #set par(justify: true) This text can be fitted in one line.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/layout-infinite-lengths.typ
typst
Apache License 2.0
// Test that passing infinite lengths to drawing primitives does not crash Typst. --- #set page(width: auto, height: auto) // Error: cannot expand into infinite width #layout(size => grid(columns: (size.width, size.height))[a][b][c][d]) --- #set page(width: auto, height: auto) // Error: 17-66 cannot create grid with infinite height #layout(size => grid(rows: (size.width, size.height))[a][b][c][d]) --- #set page(width: auto, height: auto) // Error: 17-41 cannot create line with infinite length #layout(size => line(length: size.width)) --- #set page(width: auto, height: auto) // Error: 17-54 cannot create polygon with infinite size #layout(size => polygon((0pt,0pt), (0pt, size.width)))
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/typescript.typ
typst
#import "/components/glossary.typ": gls == TypeScript <sec-typescript> TypeScript, a superset of JavaScript, has gained significant popularity in recent years due to its ability to enhance code quality, maintainability, and scalability. This section explores the key features, benefits, and challenges of using TypeScript, with a particular focus on its integration with tools like `tsc` for bundling and type support. TypeScript, in combination with `tsc`, offers a powerful and effective solution for modern web development. By leveraging static typing, type inference, and a robust ecosystem, developers can build more reliable, maintainable, and scalable applications. While there might be a learning curve, the benefits of using TypeScript often outweigh the challenges @bib-typescript. === A Superset of JavaScript - *Static Typing*: TypeScript introduces optional static typing, allowing developers to define data types for variables, functions, and classes. This enables early error detection and improved code comprehension. - *Type Inference*: TypeScript's type inference mechanism automatically infers types based on context, reducing the need for explicit type annotations. - *Compatibility with JavaScript*: TypeScript is fully compatible with existing JavaScript code, allowing for gradual adoption and migration. - *Object-Oriented Programming*: TypeScript supports object-oriented programming paradigms, including classes, interfaces, and inheritance. - *ES6+ Features*: TypeScript incorporates modern JavaScript features like modules, arrow functions, and destructuring, making it a powerful tool for building scalable applications. === The Role of `tsc` - *Bundler and Type Checker*: `tsc` is a TypeScript compiler that bundles TypeScript code into JavaScript and performs type checking to ensure code correctness. - *Configuration Flexibility*: `tsc` offers a wide range of configuration options to customize the compilation process and tailor it to specific project requirements. - *Integration with Build Tools*: `tsc` can be seamlessly integrated with popular build tools like `ESBuild` (@sec-esbuild) for efficient project management. === Benefits of Using TypeScript and `tsc` - *Improved Code Quality*: Static typing helps prevent common errors and improves code readability. - *Enhanced Maintainability*: Type annotations and code organization contribute to better code maintainability and collaboration. - *Scalability*: TypeScript is well-suited for large-scale projects, providing a strong foundation for building complex applications. - *Faster Development*: Type inference and intelligent code completion can accelerate development and reduce debugging time. - *Ecosystem Support*: TypeScript benefits from a vast and growing ecosystem of tools, libraries, and frameworks.
https://github.com/thaqibm/typst
https://raw.githubusercontent.com/thaqibm/typst/main/cheat_sheet.typ
typst
// The project function defines how your document looks. #let project(title: "", authors: (), body) = { set document(author: authors, title: title) set page(numbering: "1", number-align: center) set text(font: "New Computer Modern", lang: "en") show math.equation: set text(weight: 400) set page(width: 29.7cm, height: 21cm, margin: (x: 25pt, y:30pt)) set par(justify: true) // Title row. align(center)[ #block(text(weight: 200, 1.5em, title)) #block(text(weight: 200, 1.0em, ..authors.map(author => align(center, strong(author))))) ] show: columns.with(5, gutter: 1.3em) body }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/canonical-nthu-thesis/0.1.0/utils/cover-with-rect.typ
typst
Apache License 2.0
#let cover-with-rect(..cover-args, fill: auto, inline: true, body) = { if fill == auto { panic( "`auto` fill value is not supported until typst provides utilities to" + " retrieve the current page background" ) } if type(fill) == "string" { fill = rgb(fill) } let to-display = layout(layout-size => { style(styles => { let body-size = measure(body, styles) let bounding-width = calc.min(body-size.width, layout-size.width) let wrapped-body-size = measure(box(body, width: bounding-width), styles) let named = cover-args.named() if "width" not in named { named.insert("width", wrapped-body-size.width) } if "height" not in named { named.insert("height", wrapped-body-size.height) } if "outset" not in named { // This outset covers the tops of tall letters and the bottoms of letters with // descenders. Alternatively, we could use // `set text(top-edge: "bounds", bottom-edge: "bounds")` to get the same effect, // but this changes text alignment and also misaligns bullets in enums/lists. // In contrast, `outset` preserves spacing and alignment at the cost of adding // a slight, visible border when the covered object is right next to the edge // of a color change. named.insert("outset", (top: 0.15em, bottom: 0.25em)) } stack( spacing: -wrapped-body-size.height, body, rect(fill: fill, ..named, ..cover-args.pos()) ) }) }) if inline { box(to-display) } else { to-display } } #let cover-with-white-rect = cover-with-rect.with(fill: rgb(255, 255, 255, 213))
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/code/cond.typ
typst
Apache License 2.0
#if not true { // false } #if (is-tablex-cell(cell) and type(cell.y) in (_int-type, _float-type) and cell.y > acc) { cell.y } else { acc } #let a = 0 #let b = 1
https://github.com/mangkoran/utm-thesis-typst
https://raw.githubusercontent.com/mangkoran/utm-thesis-typst/main/02_declaration_thesis.typ
typst
MIT License
#import "@preview/tablex:0.0.7": tablex, rowspanx, colspanx #import "utils.typ": empty #let content( title: empty[title], author: empty[author], metric: empty[metric], dob: empty[dob], session: empty[session], utm_email: empty[utm email], supervisor: ( empty[supervisor 1], empty[supervisor 2], ) ) = [ #align(right)[PSZ 19:16 (Pind. 1/23)] #align(center)[ #upper[*Universiti Teknologi Malaysia*] \ #upper[*Declaration of Thesis*] ] #tablex( auto-lines: false, columns: (1fr, 2fr, 1fr, 2fr), [Author's Name], [: #upper[#author]], [Academic Session], [: #session], [Matric No.], [: #metric], [UTM Email], [: #utm_email], [Date of Birth], colspanx(3)[: #datetime.today().display()], (), (), [Thesis Title], colspanx(3)[: #upper[#title]], (), (), ) I declare that this thesis is classified as: #tablex( auto-lines: false, columns: (auto, auto, auto), [#square[]], [*OPEN ACCESS*], [I agree that my report to be published as a hard copy or made available through online open access.], [#square[]], [*RESTRICTED*], [Contains restricted information as specified by the organization/institution where research was done.], [#square[]], [*CONFIDENTIAL*], [Contains confidential information as specified in the Official Secret Act 1972.], ) _(If none of the options are selected, the first opetion will be chosen by default)_ I acknowledge the intellectual property in the thesis belongs to Universiti Teknologi Malaysia, and I agree to allow this to be placed in the library under the following terms: + This is the property of Universiti Teknologi Malaysia + The Library of Universiti Teknologi Malaysia has the right to make copies for the purpose of only. + The Library of Universiti Teknologi Malaysia is allowed to make copies of this thesis for academic exchanges. #tablex( auto-lines: false, columns: (auto, 1fr, auto, 1fr), colspanx(4, align: center)[Signature of Student], (), (), (), [Signature], colspanx(3)[:], (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), [Name], colspanx(3)[: #upper[#author]], (), (), [Date], colspanx(3)[: #datetime.today().display()], (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), colspanx(4, align: center)[Approved by Supervisor(s)], (), (), (), ..(if supervisor.len() == 1 {( [Signature of Supervisor I], colspanx(3)[:], (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), [Name of Supervisor I], colspanx(3)[: #upper[#supervisor.at(0)]], (), (), [Date], colspanx(3)[: #datetime.today().display()], (), (), )} else if supervisor.len() == 2 {( [Signature of Supervisor I], [:], [Signature of Supervisor II], [:], colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), colspanx(4)[], (), (), (), [Name of Supervisor I], [: #upper[#supervisor.at(0)]], [Name of Supervisor II], [: #upper[#supervisor.at(1)]], [Date], [: #datetime.today().display()], [Date], [: #datetime.today().display()], )} else {( panic("supervisor must be 1 or 2") )}), ) NOTES: If the thesis is CONFIDENTIAL or RESTRICTED, please attach with the letter from the organization with period and reasons for confidentiality or restriction. #pagebreak(weak: true) ] #content()
https://github.com/Akida31/anki-typst
https://raw.githubusercontent.com/Akida31/anki-typst/main/typst/src/config.typ
typst
#let anki_config = state( "anki::config", ( export: false, date: none, title: none, prefix_deck_names_with_numbers: false, ), ) /// Get a value from `sys.inputs`. /// /// - key (str): The input key to read from. /// - default (any): The default value if it can't be read. /// - options (dict): Map to get from option to value. /// -> any #let get_val_from_sys( key, default: false, options: ( (true, (true, "true", "yes")), (false, (none, false, "false", "no")), ), ) = { let val = sys.inputs.at(key, default: default) let option_vals = () for (key, vals) in options { if type(vals) == array { if vals.contains(val) { return key } option_vals += vals } else { if vals == val { return key } option_vals.push(vals) } } let expected = option_vals.map(str).dedup().map(s => "`" + s + "`").join(", ") panic("unexpected value for key " + key + ": `" + val + "`. Expected one of " + expected + ".") } /// Enable or disable export mode. /// /// - export (bool): The new value. #let set_export(export) = { anki_config.update(conf => { conf.export = export conf }) } /// Determine whether the export mode is active. /// - loc (location): Current location /// -> bool #let is_export(loc) = { anki_config.at(loc).export } /// Set the date. /// /// If the date is set (not `none`), all anki items after this will have an additional date field. /// - date (str, none): #v(0cm) #let set_date(date) = { anki_config.update(conf => { conf.date = date conf }) } /// Enable or disable export mode depending on `sys.inputs`. #let set_export_from_sys() = { let val = get_val_from_sys("export") set_export(val) }
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week4.typ
typst
#import "../../utils.typ": * #section("Solidity Basics") - always signify license -> \/\/ SPDX-License-Identifier: MIT - classes are made as *contracts* -> state storage //typstfmt::off ```sol contract SimpleStorage { uint256 storedData; // state variable } ``` //typstfmt::on - Functions are as normal //typstfmt::off ```sol function bid() public { // ... } ``` //typstfmt::on - visibility - internal: like private but can be overriden by other functions - private: as usual - external: *only* callable from outside - public: as usual - *Types* - pure\ no state reading or writing -> functional kekw - view\ no state view, but write - payable\ can send or receive ETH - returns\ written as returns (type) #subsection("Examples") //typstfmt::off ```sol contract Something { uint256 storedData = 1; function test() public returns (uint256) { storedData = 2; return 2; } } ``` //typstfmt::on #subsection("Modifiers") Modifiers are essentially traits: //typstfmt::off ```sol modifier onlyOwner() { require( msg.sender == owner, "Only owner allowed"); _; } ``` //typstfmt::on Then you can use functions like this: //typstfmt::off ```sol function abort() public view onlyOwner{ // ... } ``` //typstfmt::on #subsubsection("Simle modifiers") Modifiers are also what allows function overriding: //typstfmt::off ```sol contract Something { function first() public view virtual returns (bool) {} } contract Whatever is Something { function first() public view override returns (bool) {} } ``` //typstfmt::on #subsection("Events") Events allow you to communicate to the outside. //typstfmt::off ```sol contract EventContract { event TestEvent(string msg); function useevent() public { emit TestEvent("whatever"); } } ``` //typstfmt::on #subsection("Errors") Simple errors can be used like this: //typstfmt::off ```sol contract ErrorContract { error TestError(string msg); function useevent() public pure { revert TestError("whatever"); } } ``` //typstfmt::on You can also automatically use *require* in order to fail when something is not given: //typstfmt::off ```sol require(balance >= amount, "Not enough"); // fails when balance is not high enough ``` //typstfmt::on You can also use *assert* to check for bugs in your contract or use *try/catch* with errors. #subsection("Structs and Enums") #text(red)[Can only be used within contracts!] //typstfmt::off ```sol contract TypeContract { struct Type { uint256 num; string name; } enum Enum { FIRST, SECOND, THIRD } Type something = Type(5,"globi"); Enum someenum = Enum.FIRST; } ``` //typstfmt::on #subsection("Storage locations") We can store parameters on 3 different ways, memory, which means as long as the contract lives, callData, which means gone when the function ends, or storage for persistent blockchain storage(expensive!) //typstfmt::off ```sol // memory -> heap // calldata -> stack // storage -> blockchain function register(string memory name) internal {} ``` //typstfmt::on #subsection("Address Type") Obviously, this is a language for a blockchain, therefore it also offers an address type: //typstfmt::off ```sol contract AdressContract { address myledger = address(this); address payable wat = address(0x123); function whatever() public payable { if (wat.balance < 10 && myledger.balance >= 10) wat.transfer(10); // send does the same but without revert on gas failure! } function lel() public payable { bytes memory payload = abi.encodeWithSignature("register(string)", "MyName"); (bool success, bytes memory returnData) = address(this).call(payload); // call function on address remotely require(success); } function register(string memory name) internal {} // function to call with payload } myLedger.call(); myLedger.delegatecall(); myLedger.staticcall(); ``` //typstfmt::on #subsection("Arrays and Maps") //typstfmt::off ```sol contract MapContract { mapping(address => uint) public balances; uint[] arr = new uint[](3); function update(uint newBalance) public { balances[msg.sender] = newBalance; arr[1] = newBalance; } } ``` //typstfmt::on #subsection("Integrated Variables") - wei, gwei or ether - seconds, minutes, hours, days and weeks - blockhash, blocknumber - block.prevrandao (new) - block.timestamp - msg.data - *msg.sender* - *msg.value* #subsection("Creating Contracts (instantiation)") //typstfmt::off ```sol contract NewContract {} contract InsideContract { function wat() public { NewContract gg = new NewContract(); // inside } } InsideContract gg = web3.eth.InsideContract(); // this is a library, not builtin ``` //typstfmt::on #subsection("Spawn Contract in contract (expensive!)") //typstfmt::off ```sol contract ChildContract { string public data; constructor(string memory _data) { data = _data; } } contract FactoryContract { // address of the last deployed ChildContract address public lastDeployedAddress; function deployChild(string memory _data) public { // Deploy a new instance of ChildContract ChildContract child = new ChildContract(_data); // Store the address of the deployed contract lastDeployedAddress = address(child); } } ``` //typstfmt::on #subsection("Unchecked") This can save gas, only use if underflow or overflow is absolutely impossible! //typstfmt::off ```sol unchecked{} // make variables under/overflow ``` //typstfmt::on
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/minea/0_vseob/03_ApostolJeden.typ
typst
#let V = ( "HV": ( ("", 8, "Čto vy narečem", "Čto ťá imenújem Apoštole? nébo li? jáko slávu ispovídal jesí Bóžiju: rikú li? jáko tvar napajáješi tájno: zvizdú, ozarjájuščuju cérkov? čášu, pivo svjatoje izlivájuščuju?drúha Christóva blĺžňijšaho, Bezplótnych ravnosélnika: molí o spasénii duš nášich."), ("", none, "", "Slávne bohovídče Apoštole, ukrasíšasja tvojá nóhi, putém própovidi šéstvujuščyja dóbri, i pútí vsja vrážija sťisňájuščyja, širotóju božéstvennaho rázuma, Slova jávlšahosja debelstvóm plóti, i učeniká ťa preslávna izbrávšaho, blažénne: Jehóže molí, spastísja dušám nášym."), ("", none, "", "Voístinnu bohohlahólive Apoštole, póslan byl jesí jáko strilá ot Christá svitovídnaja, ujazvľájuščaja vrahí, ujázvlennym že dušám jávstvenno podajúšča izcilénije: ťímže ťa po dólhu ublažájem, i svjatóje tvojé dnes soveršájem toržestvó: molí spastísja dušám nášym."), ), "HV_S": ( ("", 6, "", "Izlijásja blahodáf vo ustnách tvoích, slávne Apoštole, (N.): í byl jesí svitílnik cérkve Christóvy, učá slovésnyja óvcy vírovati v Trójcu jedinosúščnuju, vo jedíno Božestvó."), ), "HV_SN": ( ("", none, "", "Tmámi, Prečístaja, obiščáchsja pokajánije sotvoríti o moích sohrišéniich, no ne ostavľájet mja lubímyj zol moích obýčaj: sehó rádi tebí vopijú i pripádaja moľásja: ty mja Vladýčice izmí takováho mučíteľstva, nastavTájušči mja k lúčšym, i spasénija bliz súščym."), ), "T": ( ("", 3, "", "Apoštole svjatýj (N.): molí mílostivaho Bóha, da prehrišénij ostavlénije podásť dušám nášym."), ) )
https://github.com/sahasatvik/typst-theorems
https://raw.githubusercontent.com/sahasatvik/typst-theorems/main/basic.typ
typst
MIT License
#import "theorems.typ": * #show: thmrules.with(qed-symbol: $square$) #set page(width: 16cm, height: auto, margin: 1.5cm) #set text(font: "Libertinus Serif", lang: "en") #set heading(numbering: "1.1.") #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof") = Prime numbers #definition[ A natural number is called a #highlight[_prime number_] if it is greater than 1 and cannot be written as the product of two smaller natural numbers. ] #example[ The numbers $2$, $3$, and $17$ are prime. @cor_largest_prime shows that this list is not exhaustive! ] #theorem("Euclid")[ There are infinitely many primes. ] #proof[ Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list, it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since $p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a contradiction. ] #corollary[ There is no largest prime number. ] <cor_largest_prime> #corollary[ There are infinitely many composite numbers. ] #theorem[ There are arbitrarily long stretches of composite numbers. ] #proof[ For any $n > 2$, consider $ n! + 2, quad n! + 3, quad ..., quad n! + n #qedhere $ ]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/217.%20superlinear.html.typ
typst
superlinear.html Superlinear Returns October 2023One of the most important things I didn't understand about the world when I was a child is the degree to which the returns for performance are superlinear.Teachers and coaches implicitly told us the returns were linear. "You get out," I heard a thousand times, "what you put in." They meant well, but this is rarely true. If your product is only half as good as your competitor's, you don't get half as many customers. You get no customers, and you go out of business.It's obviously true that the returns for performance are superlinear in business. Some think this is a flaw of capitalism, and that if we changed the rules it would stop being true. But superlinear returns for performance are a feature of the world, not an artifact of rules we've invented. We see the same pattern in fame, power, military victories, knowledge, and even benefit to humanity. In all of these, the rich get richer. [1]You can't understand the world without understanding the concept of superlinear returns. And if you're ambitious you definitely should, because this will be the wave you surf on.It may seem as if there are a lot of different situations with superlinear returns, but as far as I can tell they reduce to two fundamental causes: exponential growth and thresholds.The most obvious case of superlinear returns is when you're working on something that grows exponentially. For example, growing bacterial cultures. When they grow at all, they grow exponentially. But they're tricky to grow. Which means the difference in outcome between someone who's adept at it and someone who's not is very great.Startups can also grow exponentially, and we see the same pattern there. Some manage to achieve high growth rates. Most don't. And as a result you get qualitatively different outcomes: the companies with high growth rates tend to become immensely valuable, while the ones with lower growth rates may not even survive.Y Combinator encourages founders to focus on growth rate rather than absolute numbers. It prevents them from being discouraged early on, when the absolute numbers are still low. It also helps them decide what to focus on: you can use growth rate as a compass to tell you how to evolve the company. But the main advantage is that by focusing on growth rate you tend to get something that grows exponentially.YC doesn't explicitly tell founders that with growth rate "you get out what you put in," but it's not far from the truth. And if growth rate were proportional to performance, then the reward for performance p over time t would be proportional to pt.Even after decades of thinking about this, I find that sentence startling.Whenever how well you do depends on how well you've done, you'll get exponential growth. But neither our DNA nor our customs prepare us for it. No one finds exponential growth natural; every child is surprised, the first time they hear it, by the story of the man who asks the king for a single grain of rice the first day and double the amount each successive day.What we don't understand naturally we develop customs to deal with, but we don't have many customs about exponential growth either, because there have been so few instances of it in human history. In principle herding should have been one: the more animals you had, the more offspring they'd have. But in practice grazing land was the limiting factor, and there was no plan for growing that exponentially.Or more precisely, no generally applicable plan. There was a way to grow one's territory exponentially: by conquest. The more territory you control, the more powerful your army becomes, and the easier it is to conquer new territory. This is why history is full of empires. But so few people created or ran empires that their experiences didn't affect customs very much. The emperor was a remote and terrifying figure, not a source of lessons one could use in one's own life.The most common case of exponential growth in preindustrial times was probably scholarship. The more you know, the easier it is to learn new things. The result, then as now, was that some people were startlingly more knowledgeable than the rest about certain topics. But this didn't affect customs much either. Although empires of ideas can overlap and there can thus be far more emperors, in preindustrial times this type of empire had little practical effect. [2]That has changed in the last few centuries. Now the emperors of ideas can design bombs that defeat the emperors of territory. But this phenomenon is still so new that we haven't fully assimilated it. Few even of the participants realize they're benefitting from exponential growth or ask what they can learn from other instances of it.The other source of superlinear returns is embodied in the expression "winner take all." In a sports match the relationship between performance and return is a step function: the winning team gets one win whether they do much better or just slightly better. [3]The source of the step function is not competition per se, however. It's that there are thresholds in the outcome. You don't need competition to get those. There can be thresholds in situations where you're the only participant, like proving a theorem or hitting a target.It's remarkable how often a situation with one source of superlinear returns also has the other. Crossing thresholds leads to exponential growth: the winning side in a battle usually suffers less damage, which makes them more likely to win in the future. And exponential growth helps you cross thresholds: in a market with network effects, a company that grows fast enough can shut out potential competitors.Fame is an interesting example of a phenomenon that combines both sources of superlinear returns. Fame grows exponentially because existing fans bring you new ones. But the fundamental reason it's so concentrated is thresholds: there's only so much room on the A-list in the average person's head.The most important case combining both sources of superlinear returns may be learning. Knowledge grows exponentially, but there are also thresholds in it. Learning to ride a bicycle, for example. Some of these thresholds are akin to machine tools: once you learn to read, you're able to learn anything else much faster. But the most important thresholds of all are those representing new discoveries. Knowledge seems to be fractal in the sense that if you push hard at the boundary of one area of knowledge, you sometimes discover a whole new field. And if you do, you get first crack at all the new discoveries to be made in it. Newton did this, and so did Durer and Darwin. Are there general rules for finding situations with superlinear returns? The most obvious one is to seek work that compounds.There are two ways work can compound. It can compound directly, in the sense that doing well in one cycle causes you to do better in the next. That happens for example when you're building infrastructure, or growing an audience or brand. Or work can compound by teaching you, since learning compounds. This second case is an interesting one because you may feel you're doing badly as it's happening. You may be failing to achieve your immediate goal. But if you're learning a lot, then you're getting exponential growth nonetheless.This is one reason Silicon Valley is so tolerant of failure. People in Silicon Valley aren't blindly tolerant of failure. They'll only continue to bet on you if you're learning from your failures. But if you are, you are in fact a good bet: maybe your company didn't grow the way you wanted, but you yourself have, and that should yield results eventually.Indeed, the forms of exponential growth that don't consist of learning are so often intermixed with it that we should probably treat this as the rule rather than the exception. Which yields another heuristic: always be learning. If you're not learning, you're probably not on a path that leads to superlinear returns.But don't overoptimize what you're learning. Don't limit yourself to learning things that are already known to be valuable. You're learning; you don't know for sure yet what's going to be valuable, and if you're too strict you'll lop off the outliers.What about step functions? Are there also useful heuristics of the form "seek thresholds" or "seek competition?" Here the situation is trickier. The existence of a threshold doesn't guarantee the game will be worth playing. If you play a round of Russian roulette, you'll be in a situation with a threshold, certainly, but in the best case you're no better off. "Seek competition" is similarly useless; what if the prize isn't worth competing for? Sufficiently fast exponential growth guarantees both the shape and magnitude of the return curve — because something that grows fast enough will grow big even if it's trivially small at first — but thresholds only guarantee the shape. [4]A principle for taking advantage of thresholds has to include a test to ensure the game is worth playing. Here's one that does: if you come across something that's mediocre yet still popular, it could be a good idea to replace it. For example, if a company makes a product that people dislike yet still buy, then presumably they'd buy a better alternative if you made one. [5]It would be great if there were a way to find promising intellectual thresholds. Is there a way to tell which questions have whole new fields beyond them? I doubt we could ever predict this with certainty, but the prize is so valuable that it would be useful to have predictors that were even a little better than random, and there's hope of finding those. We can to some degree predict when a research problem isn't likely to lead to new discoveries: when it seems legit but boring. Whereas the kind that do lead to new discoveries tend to seem very mystifying, but perhaps unimportant. (If they were mystifying and obviously important, they'd be famous open questions with lots of people already working on them.) So one heuristic here is to be driven by curiosity rather than careerism — to give free rein to your curiosity instead of working on what you're supposed to. The prospect of superlinear returns for performance is an exciting one for the ambitious. And there's good news in this department: this territory is expanding in both directions. There are more types of work in which you can get superlinear returns, and the returns themselves are growing.There are two reasons for this, though they're so closely intertwined that they're more like one and a half: progress in technology, and the decreasing importance of organizations.Fifty years ago it used to be much more necessary to be part of an organization to work on ambitious projects. It was the only way to get the resources you needed, the only way to have colleagues, and the only way to get distribution. So in 1970 your prestige was in most cases the prestige of the organization you belonged to. And prestige was an accurate predictor, because if you weren't part of an organization, you weren't likely to achieve much. There were a handful of exceptions, most notably artists and writers, who worked alone using inexpensive tools and had their own brands. But even they were at the mercy of organizations for reaching audiences. [6]A world dominated by organizations damped variation in the returns for performance. But this world has eroded significantly just in my lifetime. Now a lot more people can have the freedom that artists and writers had in the 20th century. There are lots of ambitious projects that don't require much initial funding, and lots of new ways to learn, make money, find colleagues, and reach audiences.There's still plenty of the old world left, but the rate of change has been dramatic by historical standards. Especially considering what's at stake. It's hard to imagine a more fundamental change than one in the returns for performance.Without the damping effect of institutions, there will be more variation in outcomes. Which doesn't imply everyone will be better off: people who do well will do even better, but those who do badly will do worse. That's an important point to bear in mind. Exposing oneself to superlinear returns is not for everyone. Most people will be better off as part of the pool. So who should shoot for superlinear returns? Ambitious people of two types: those who know they're so good that they'll be net ahead in a world with higher variation, and those, particularly the young, who can afford to risk trying it to find out. [7]The switch away from institutions won't simply be an exodus of their current inhabitants. Many of the new winners will be people they'd never have let in. So the resulting democratization of opportunity will be both greater and more authentic than any tame intramural version the institutions themselves might have cooked up. Not everyone is happy about this great unlocking of ambition. It threatens some vested interests and contradicts some ideologies. [8] But if you're an ambitious individual it's good news for you. How should you take advantage of it?The most obvious way to take advantage of superlinear returns for performance is by doing exceptionally good work. At the far end of the curve, incremental effort is a bargain. All the more so because there's less competition at the far end — and not just for the obvious reason that it's hard to do something exceptionally well, but also because people find the prospect so intimidating that few even try. Which means it's not just a bargain to do exceptional work, but a bargain even to try to.There are many variables that affect how good your work is, and if you want to be an outlier you need to get nearly all of them right. For example, to do something exceptionally well, you have to be interested in it. Mere diligence is not enough. So in a world with superlinear returns, it's even more valuable to know what you're interested in, and to find ways to work on it. [9] It will also be important to choose work that suits your circumstances. For example, if there's a kind of work that inherently requires a huge expenditure of time and energy, it will be increasingly valuable to do it when you're young and don't yet have children.There's a surprising amount of technique to doing great work. It's not just a matter of trying hard. I'm going to take a shot giving a recipe in one paragraph.Choose work you have a natural aptitude for and a deep interest in. Develop a habit of working on your own projects; it doesn't matter what they are so long as you find them excitingly ambitious. Work as hard as you can without burning out, and this will eventually bring you to one of the frontiers of knowledge. These look smooth from a distance, but up close they're full of gaps. Notice and explore such gaps, and if you're lucky one will expand into a whole new field. Take as much risk as you can afford; if you're not failing occasionally you're probably being too conservative. Seek out the best colleagues. Develop good taste and learn from the best examples. Be honest, especially with yourself. Exercise and eat and sleep well and avoid the more dangerous drugs. When in doubt, follow your curiosity. It never lies, and it knows more than you do about what's worth paying attention to. [10]And there is of course one other thing you need: to be lucky. Luck is always a factor, but it's even more of a factor when you're working on your own rather than as part of an organization. And though there are some valid aphorisms about luck being where preparedness meets opportunity and so on, there's also a component of true chance that you can't do anything about. The solution is to take multiple shots. Which is another reason to start taking risks early. The best example of a field with superlinear returns is probably science. It has exponential growth, in the form of learning, combined with thresholds at the extreme edge of performance — literally at the limits of knowledge.The result has been a level of inequality in scientific discovery that makes the wealth inequality of even the most stratified societies seem mild by comparison. Newton's discoveries were arguably greater than all his contemporaries' combined. [11]This point may seem obvious, but it might be just as well to spell it out. Superlinear returns imply inequality. The steeper the return curve, the greater the variation in outcomes.In fact, the correlation between superlinear returns and inequality is so strong that it yields another heuristic for finding work of this type: look for fields where a few big winners outperform everyone else. A kind of work where everyone does about the same is unlikely to be one with superlinear returns.What are fields where a few big winners outperform everyone else? Here are some obvious ones: sports, politics, art, music, acting, directing, writing, math, science, starting companies, and investing. In sports the phenomenon is due to externally imposed thresholds; you only need to be a few percent faster to win every race. In politics, power grows much as it did in the days of emperors. And in some of the other fields (including politics) success is driven largely by fame, which has its own source of superlinear growth. But when we exclude sports and politics and the effects of fame, a remarkable pattern emerges: the remaining list is exactly the same as the list of fields where you have to be independent-minded to succeed — where your ideas have to be not just correct, but novel as well. [12]This is obviously the case in science. You can't publish papers saying things that other people have already said. But it's just as true in investing, for example. It's only useful to believe that a company will do well if most other investors don't; if everyone else thinks the company will do well, then its stock price will already reflect that, and there's no room to make money.What else can we learn from these fields? In all of them you have to put in the initial effort. Superlinear returns seem small at first. At this rate, you find yourself thinking, I'll never get anywhere. But because the reward curve rises so steeply at the far end, it's worth taking extraordinary measures to get there.In the startup world, the name for this principle is "do things that don't scale." If you pay a ridiculous amount of attention to your tiny initial set of customers, ideally you'll kick off exponential growth by word of mouth. But this same principle applies to anything that grows exponentially. Learning, for example. When you first start learning something, you feel lost. But it's worth making the initial effort to get a toehold, because the more you learn, the easier it will get.There's another more subtle lesson in the list of fields with superlinear returns: not to equate work with a job. For most of the 20th century the two were identical for nearly everyone, and as a result we've inherited a custom that equates productivity with having a job. Even now to most people the phrase "your work" means their job. But to a writer or artist or scientist it means whatever they're currently studying or creating. For someone like that, their work is something they carry with them from job to job, if they have jobs at all. It may be done for an employer, but it's part of their portfolio. It's an intimidating prospect to enter a field where a few big winners outperform everyone else. Some people do this deliberately, but you don't need to. If you have sufficient natural ability and you follow your curiosity sufficiently far, you'll end up in one. Your curiosity won't let you be interested in boring questions, and interesting questions tend to create fields with superlinear returns if they're not already part of one.The territory of superlinear returns is by no means static. Indeed, the most extreme returns come from expanding it. So while both ambition and curiosity can get you into this territory, curiosity may be the more powerful of the two. Ambition tends to make you climb existing peaks, but if you stick close enough to an interesting enough question, it may grow into a mountain beneath you.NotesThere's a limit to how sharply you can distinguish between effort, performance, and return, because they're not sharply distinguished in fact. What counts as return to one person might be performance to another. But though the borders of these concepts are blurry, they're not meaningless. I've tried to write about them as precisely as I could without crossing into error.[1] Evolution itself is probably the most pervasive example of superlinear returns for performance. But this is hard for us to empathize with because we're not the recipients; we're the returns.[2] Knowledge did of course have a practical effect before the Industrial Revolution. The development of agriculture changed human life completely. But this kind of change was the result of broad, gradual improvements in technique, not the discoveries of a few exceptionally learned people.[3] It's not mathematically correct to describe a step function as superlinear, but a step function starting from zero works like a superlinear function when it describes the reward curve for effort by a rational actor. If it starts at zero then the part before the step is below any linearly increasing return, and the part after the step must be above the necessary return at that point or no one would bother.[4] Seeking competition could be a good heuristic in the sense that some people find it motivating. It's also somewhat of a guide to promising problems, because it's a sign that other people find them promising. But it's a very imperfect sign: often there's a clamoring crowd chasing some problem, and they all end up being trumped by someone quietly working on another one.[5] Not always, though. You have to be careful with this rule. When something is popular despite being mediocre, there's often a hidden reason why. Perhaps monopoly or regulation make it hard to compete. Perhaps customers have bad taste or have broken procedures for deciding what to buy. There are huge swathes of mediocre things that exist for such reasons.[6] In my twenties I wanted to be an artist and even went to art school to study painting. Mostly because I liked art, but a nontrivial part of my motivation came from the fact that artists seemed least at the mercy of organizations.[7] In principle everyone is getting superlinear returns. Learning compounds, and everyone learns in the course of their life. But in practice few push this kind of everyday learning to the point where the return curve gets really steep.[8] It's unclear exactly what advocates of "equity" mean by it. They seem to disagree among themselves. But whatever they mean is probably at odds with a world in which institutions have less power to control outcomes, and a handful of outliers do much better than everyone else.It may seem like bad luck for this concept that it arose at just the moment when the world was shifting in the opposite direction, but I don't think this was a coincidence. I think one reason it arose now is because its adherents feel threatened by rapidly increasing variation in performance.[9] Corollary: Parents who pressure their kids to work on something prestigious, like medicine, even though they have no interest in it, will be hosing them even more than they have in the past.[10] The original version of this paragraph was the first draft of "How to Do Great Work." As soon as I wrote it I realized it was a more important topic than superlinear returns, so I paused the present essay to expand this paragraph into its own. Practically nothing remains of the original version, because after I finished "How to Do Great Work" I rewrote it based on that.[11] Before the Industrial Revolution, people who got rich usually did it like emperors: capturing some resource made them more powerful and enabled them to capture more. Now it can be done like a scientist, by discovering or building something uniquely valuable. Most people who get rich use a mix of the old and the new ways, but in the most advanced economies the ratio has shifted dramatically toward discovery just in the last half century.[12] It's not surprising that conventional-minded people would dislike inequality if independent-mindedness is one of the biggest drivers of it. But it's not simply that they don't want anyone to have what they can't. The conventional-minded literally can't imagine what it's like to have novel ideas. So the whole phenomenon of great variation in performance seems unnatural to them, and when they encounter it they assume it must be due to cheating or to some malign external influence.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/07_并发控制-互斥.typ
typst
#import "../template.typ": * #pagebreak() = 并发控制:互斥 == 互斥问题:定义与假设 #tip("Tip")[ 如果打破读写原子性的假设,那peterson的算法是错误的。 ] === 回顾:并发编程 理解并发的工具 - 线程 = 人 (大脑能完成局部存储和计算) - 共享内存 = 物理世界 (物理世界天生并行) - 一切都是状态机 (debugger & model checker) #tip("Tip")[ “躲进厕所锁上门,我就把全世界人锁在了厕所外” ] === 互斥问题:定义 互斥 (mutual exclusion),“互相排斥” 实现 lock_t 数据结构和 lock/unlock API: ```c typedef struct { ... } lock_t; void lock(lock_t *lk); void unlock(lock_t *lk); ``` 一把 “排他性” 的锁——对于锁对象 lk - 如果某个线程持有锁,则其他线程的 lock 不能返回 (Safety) - 在多个线程执行 lock 时,至少有一个可以返回 (Liveness) - 能*正确处理处理器乱序、宽松内存模型和编译优化* === 互斥问题的经典算法 Peterson 算法 - 包间、旗子和门上的字条 - 假设 atomic load/store - 实现这个假设也不是非常容易的 (peterson.c) 因此,*假设很重要* - 不能同时读/写共享内存 (1960s) 不是一个好的假设 - Load (环顾四周) 的时候不能写,“看一眼就把眼睛闭上” - Store (改变物理世界状态) 的时候不能读,“闭着眼睛动手” - 这是《操作系统》课 - 更喜欢*直观、简单、粗暴 (稳定)、有效*的解决方法 === 实现互斥的基本假设 允许使用使我们可以不管一切麻烦事的原子指令 ```c void atomic_inc(long *ptr); int atomic_xchg(int val, int *ptr); ``` 看起来是一个普通的函数,但假设: - 包含一个原子指令 - 指令的执行不能被打断 - 包含一个 compiler barrier - 无论何种优化都不可越过此函数 - 包含一个 memory fence - 保证处理器在 stop-the-world 前所有对内存的 store 都 “生效” > 例如,原子指令前有个sum++,那这个sum++的值必须在原子指令执行前写回到内存里。 - 即对 resume-the-world 之后的 load 可见 === Atomic Exchange 实现 ```c int xchg(int volatile *ptr, int newval) { int result; asm volatile( // 指令自带 memory barrier "lock xchgl %0, %1" : "+m"(*ptr), "=a"(result) // Output : "1"(newval) // Input // Compiler barrier : "memory" // clobber ); return result; } ``` == 自旋锁 (Spin Lock) === 实现互斥:做题家 v.s. 科学家 ```c void lock(lock_t *lk); void unlock(lock_t *lk); ``` 做题家:拿到题就开始排列组合 - 熟练得让人心疼 - 如果长久的训练都是 “必须在规定的时间内正确解出问题”,那么浪费时间的思考自然就少了 科学家:考虑更多更根本的问题 - 我们可以设计出怎样的原子指令? - 它们的表达能力如何? - 计算机硬件可以提供比 “一次 load/store” 更强的原子性吗? - 如果硬件很困难,软件/编译器可以么? === 自旋锁:用 xchg 实现互斥 在厕所门口放一个桌子 (共享变量) - 初始时放着 🔑 自旋锁 (Spin Lock) - 想上厕所的同学 (一条 xchg 指令) - Stop the world - 看一眼桌子上有什么 (🔑 或 🛑) - 把 🛑 放到桌上 (覆盖之前有的任何东西) - Resume the world - 期间看到 🔑 才可以进厕所,否则重复 - 出厕所的同学 - 把 🔑 放到桌上 #tip("Tip")[ 正确性是显然的, 只有一把锁,交换是原子的,谁拿到就是谁的。 ] === 实现互斥:自旋锁 ```c int table = YES; void lock() { retry: int got = xchg(&table, NOPE); if (got == NOPE) goto retry; assert(got == YES); } void unlock() { xchg(&table, YES); // 为什么不是 table = YES; ? } ``` (在 model checker 中检查) 非常常见的死锁方式: 1. 在unlock之前就返回了。 2. 在unlock之前程序crash了。 > C++在构造和析构的时候分别lock,unlock,可以一定程度上避免问题。 为什么不是 `table = YES;` ? 在编译优化,宽松内存模型下,都要正确。最安全的办法。 spinlock.py ```py def Tworker(enter, exit): for _ in range(2): while True: seen = heap.table heap.table = '❌' sys_sched() if seen == '✅': break sys_sched() sys_write(enter) sys_sched() sys_write(exit) sys_sched() heap.table = '✅' sys_sched() def main(): heap.table = '✅' = "(": lock `)`:unlock sys_spawn(Tworker, '(', ')') sys_spawn(Tworker, '[', ']') = Outputs: = ()()[][] = ()#link("")[][] = ()#link("")[][] = #link("")[]()[] = #link("")[]#link("")[] = #link("")[][]() ``` === 实现互斥:自旋锁 在 xchg 的假设下简化实现 - 包含一个原子指令 - 包含一个 compiler barrier - 包含一个 memory fence - sum-spinlock demo ```c int locked = 0; void lock() { while (xchg(&locked, 1)); } void unlock() { xchg(&locked, 0); } ``` sum-spinlock.c ```c #include "thread.h" #define N 100000000 #define M 10 long sum = 0; int xchg(int volatile *ptr, int newval) { int result; asm volatile( "lock xchgl %0, %1" : "+m"(*ptr), "=a"(result) : "1"(newval) : "memory" ); return result; } int locked = 0; void lock() { while (xchg(&locked, 1)) ; } void unlock() { xchg(&locked, 0); } void Tsum() { long nround = N / M; for (int i = 0; i < nround; i++) { lock(); for (int j = 0; j < M; j++) { sum++; // Non-atomic; can optimize } unlock(); } } int main() { assert(N % M == 0); create(Tsum); create(Tsum); join(); printf("sum = %ld\n", sum); } ``` O2优化下,中间的循环直接:`addq $0xa,0x2e63(%rip)` == 🌶️ 你们 (不) 想要的无锁算法 === 更强大的原子指令 Compare and exchange (“test and set”) - (lock) cmpxchg SRC, DEST ```py TEMP = DEST if accumulator == TEMP: ZF = 1 DEST = SRC else: ZF = 0 accumulator = TEMP ``` - 🤔 看起来没复杂多少,好像又复杂了很多 - 学编程/操作系统 “纸面理解” 是不行的 - 一定要写代码加深印象 - 对于这个例子:我们可以列出 “真值表” 写一个C语言的翻译版本. ```c int cmpxchg(int old, int new, int volatile *ptr) { asm volatile("lock cmpxchgl %[new], %[mem]" : "+a"(old), [mem] "+m"(*ptr) : [new] "S"(new) : "memory"); return old; } // 本质还是xchg,但是多了一个条件,在compare相等的情况下xchg。条件加强了。 int cmpxchg_ref(int old, int new, int volatile *ptr) { int tmp = *ptr; // Load if (tmp == old) { *ptr = new; // Store (conditionally) } return tmp; } void run_test(int x, int old, int new) { int val1 = x; int ret1 = cmpxchg(old, new, &val1); int val2 = x; int ret2 = cmpxchg_ref(old, new, &val2); assert(val1 == val2 && ret1 == ret2); printf("x = %d -> (cmpxchg %d -> %d) -> x = %d\n", x, old, new, val1); } int main() { for (int x = 0; x <= 2; x++) for (int old = 0; old <= 2; old++) for (int new = 0; new <= 2; new ++) run_test(x, old, new); } ``` ==== 在自旋锁中代替 `xchg` 在自旋锁的实现中,`xchg` 完全可以用 `cmpxchg` 代替 ```c // cmpxchg(old='🔑', new='🛑', *ptr) int tmp = *ptr; if (tmp == '🔑') { *ptr = '🛑' assert(tmp == '🔑'); } else { assert(tmp == '🛑'); } return tmp; ``` - 这么做有什么好处吗? - 有的,在自旋失败的时候减少了一次 store - 当然,现代处理器也可以优化 xchg ==== 多出的 Compare: 用处 同时检查上一次获得的值是否仍然有效 + 修改生效 实现一个并发的单链表. 有两个线程都想在head前插入一个节点。那这个compare就可以检查当前的head是不是自己认为的那个。只有一个能胜出。 ```c // Create a new node retry: expected = head; node->next = expected; seen = cmpxchg(expected, node, &head); if (seen != expected) goto retry; ``` 链表最难得不是插入/删除,而是回收。 习题:如何实现 `pop()`? 🌶️ [ Lockless Patterns: An Introduction to Compare-and-swap ](https://lwn.net/Articles/847973/) 🌶️️🌶️ [ Is Parallel Programming Hard, And, If So, What Can You Do About It? ](https://cdn.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html) (perfbook) 🌶️🌶️🌶️ [ The Art of Multiprocessor Programming ](https://www.sciencedirect.com/book/9780124159501/the-art-of-multiprocessor-programming) == 在操作系统上实现互斥 === 自旋锁的缺陷 ==== 性能问题 (1) - 除了进入临界区的线程,其他处理器上的线程都在空转 - 争抢锁的处理器越多,利用率越低 - 4 个 CPU 运行 4 个 sum-spinlock 和 1 个 OBS - 任意时刻都只有一个 sum-atomic 在有效计算 - 均分 CPU, OBS 就分不到 100% 的 CPU 了 ==== 性能问题 (2) 线程的数量比处理器的数量更多?寄,所有线程都在摸鱼。 - 持有自旋锁的线程可能被操作系统切换出去 - 操作系统不 “感知” 线程在做什么 - (但为什么不能呢?) - 实现 100% 的资源浪费 === Scalability: 性能的新维度 #image("images/2024-03-18-12-42-42.png") 同一份计算任务,时间 (CPU cycles) 和空间 (mapped memory) 会随处理器数量的增长而变化。(数量增加,效率越来越低) 用自旋锁实现 sum++ 的性能问题 - 严谨的统计很难 - CPU 动态功耗 - 系统中的其他进程 - 超线程 - NUMA - …… [ Benchmarking crimes ](https://www.cse.unsw.edu.au/~gernot/benchmarking-crimes.html) > 除了有锁的切出去这个原因之外,还因为有缓存,切换处理器执行的时候,要保证当前处理器的sum值是正确的,要从上一个处理器把sum拉过来,sum这个变量在处理器的缓存之间来回传送, 导致效率降低。 === 自旋锁的使用场景 1. 临界区几乎不 “拥堵”(所有线程都要一把锁,就会拥堵) 2. 持有自旋锁时禁止执行流切换 使用场景:操作系统内核的并发数据结构 (短临界区) - 操作系统可以关闭中断和抢占 - 保证锁的持有者在很短的时间内可以释放锁 - (如果是虚拟机呢...😂) - PAUSE 指令会触发 VM Exit - 但依旧很难做好 - [ An analysis of Linux scalability to many cores (OSDI'10) ](https://www.usenix.org/conference/osdi10/analysis-linux-scalability-many-cores) === 实现线程 + 长临界区的互斥 #tip("Tip")[ 作业那么多,与其干等 Online Judge 发布,不如把自己 (CPU) 让给其他作业 (线程) 执行? ] 在得不到锁的时候,不浪费CPU,让给别的线程执行。但是“让” 不是 C 语言代码可以做到的 (C 代码只能执行指令) - 但有一种特殊的指令:syscall - 把锁的实现放到操作系统里就好啦 - `syscall(SYSCALL_lock, &lk);` - 试图获得 lk,但如果失败,就切换到其他线程 - `syscall(SYSCALL_unlock, &lk);` - 释放 lk,如果有等待锁的线程就唤醒 操作系统 = 更衣室管理员 - 先到的人 (线程) - 成功获得手环,进入游泳馆 - \*lk = 🔒,系统调用直接返回 - 后到的人 (线程) - 不能进入游泳馆,排队等待 - 线程放入等待队列,执行线程切换 (yield) - 洗完澡出来的人 (线程) - 交还手环给管理员;管理员把手环再交给排队的人 - 如果等待队列不空,从等待队列中取出一个线程允许执行 - 如果等待队列为空,\*lk = ✅ - 管理员 (OS) 使用自旋锁确保自己处理手环的过程是原子的 === 关于互斥的一些分析 自旋锁 (线程直接共享 locked) - 更快的 fast path - xchg 成功 → 立即进入临界区,开销很小 - 更慢的 slow path - xchg 失败 → 浪费 CPU 自旋等待 互斥锁 (通过系统调用访问 locked) - 更经济的 slow path - 上锁失败线程不再占用 CPU - 更慢的 fast path(要进kernel溜一圈, 还要在内核上一把锁) - 即便上锁成功也需要进出内核 (syscall) === Futex: Fast Userspace muTexes #tip("Tip")[ 小孩子才做选择, os全都要! ] - fast path: 一条原子指令, 上锁成功立即返回。 - slow path: 上锁失败,执行system call睡眠 - 性能优化最常见的技巧 - 看average(frequent) case而不是worst case POSIX 线程库中的互斥锁(`pthread_mutex` - 观察线程库中的lock/unlock行为 1. Mutex没有争抢的情况 2. Mutex有争抢的情况
https://github.com/LaPreprint/typst
https://raw.githubusercontent.com/LaPreprint/typst/main/examples/pixels/main.typ
typst
MIT License
// Update this import to where you put the `lapreprint.typ` file // It should probably be in the same folder #import "../../lapreprint.typ": template #show: template.with( title: "Pixels and their Neighbours", subtitle: "A Tutorial on Finite Volume", short-title: "Finite Volume Tutorial", venue: [ar#text(fill: red.darken(20%))[X]iv], // This is relative to the template file // When importing normally, you should be able to use it relative to this file. logo: "examples/pixels/files/logo.png", doi: "10.1190/tle35080703.1", // You can make all dates optional, however, `date` is by default `datetime.today()` date: ( (title: "Published", date: datetime(year: 2023, month: 08, day: 21)), (title: "Accepted", date: datetime(year: 2022, month: 12, day: 10)), (title: "Submitted", date: datetime(year: 2022, month: 12, day: 10)), ), theme: red.darken(50%), authors: ( ( name: "<NAME>", orcid: "0000-0002-7859-8394", email: "<EMAIL>", affiliations: "1,2" ), ( name: "<NAME>", orcid: "0000-0002-1551-5926", affiliations: "1", ), ( name: "<NAME>", orcid: "0000-0002-4327-2124", affiliations: "1" ), ), kind: "Notebook Tutorial", affiliations: ( (id: "1", name: "University of British Columbia"), (id: "2", name: "Curvenote Inc."), ), abstract: ( (title: "Abstract", content: lorem(100)), (title: "Plain Language Summary", content: lorem(25)), ), keywords: ("Finite Volume", "Tutorial", "Reproducible Research"), open-access: true, margin: ( ( title: "Key Points", content: [ - #lorem(10) - #lorem(5) - #lorem(7) ], ), ( title: "Correspondence to", content: [ <NAME>\ #link("mailto:<EMAIL>")[<EMAIL>] ], ), ( title: "Data Availability", content: [ Associated notebooks are available on #link("https://github.com/simpeg/tle-finitevolume")[GitHub] and can be run online with #link("http://mybinder.org/repo/simpeg/tle-finitevolume")[MyBinder]. ], ), ( title: "Funding", content: [ Funding was provided by the Vanier Award to each of Cockett and Heagy. ], ), ( title: "Competing Interests", content: [ The authors declare no competing interests. ], ), ), ) = DC Resistivity <dc-resistivity> DC resistivity surveys obtain information about subsurface electrical conductivity, $sigma$. This physical property is often diagnostic in mineral exploration, geotechnical, environmental and hydrogeologic problems, where the target of interest has a significant electrical conductivity contrast from the background. In a DC resistivity survey, steady state currents are set up in the subsurface by injecting current through a positive electrode and completing the circuit with a return electrode (@dc-setup). #figure( image("files/dc-setup.png", width: 60%), caption: [Setup of a DC resistivity survey.], ) <dc-setup> // You can put this after the content that fits on the first page to set the margins back to full-width #set page(margin: auto) The equations for DC resistivity are derived in (@dc-eqns). Conservation of charge (which can be derived by taking the divergence of Ampere's law at steady state) connects the divergence of the current density everywhere in space to the source term which consists of two point sources, one positive and one negative. The flow of current sets up electric fields according to Ohm's law, which relates current density to electric fields through the electrical conductivity. From Faraday's law for steady state fields, we can describe the electric field in terms of a scalar potential, $phi$, which we sample at potential electrodes to obtain data in the form of potential differences. #figure( image("files/dc-eqns.png", width: 100%), caption: [Derivation of the DC resistivity equations.], ) <dc-eqns> To set up a solvable system of equations, we need the same number of unknowns as equations, in this case two unknowns (one scalar, $phi$, and one vector $arrow(j)$) and two first-order equations (one scalar, one vector). In this tutorial, we walk through setting up these first order equations in finite volume in three steps: (1) defining where the variables live on the mesh; (2) looking at a single cell to define the discrete divergence and the weak formulation; and (3) moving from a cell based view to the entire mesh to construct and solve the resulting matrix system. The notebooks included with this tutorial leverage the #link("http://simpeg.xyz/")[SimPEG] package, which extends the methods discussed here to various mesh types. = Where do things live? <where-do-things-live> To bring our continuous equations into the computer, we need to discretize the earth and represent it using a finite(!) set of numbers. In this tutorial we will explain the discretization in 2D and generalize to 3D in the notebooks. A 2D (or 3D!) mesh is used to divide up space, and we can represent functions (fields, parameters, etc.) on this mesh at a few discrete places: the nodes, edges, faces, or cell centers. For consistency between 2D and 3D we refer to faces having area and cells having volume, regardless of their dimensionality. Nodes and cell centers naturally hold scalar quantities while edges and faces have implied directionality and therefore naturally describe vectors. The conductivity, $sigma$, changes as a function of space, and is likely to have discontinuities (e.g. if we cross a geologic boundary). As such, we will represent the conductivity as a constant over each cell, and discretize it at the center of the cell. The electrical current density, $arrow(j)$, will be continuous across conductivity interfaces, and therefore, we will represent it on the faces of each cell. Remember that $arrow(j)$ is a vector; the direction of it is implied by the mesh definition (i.e. in $x$, $y$ or $z$), so we can store the array $bold(j)$ as _scalars_ that live on the face and inherit the face's normal. When $arrow(j)$ is defined on the faces of a cell the potential, $phi$, will be put on the cell centers (since $arrow(j)$ is related to $phi$ through spatial derivatives, it allows us to approximate centered derivatives leading to a staggered, second-order discretization). Once we have the functions placed on our mesh, we look at a single cell to discretize each first order equation. For simplicity in this tutorial we will choose to have all of the faces of our mesh be aligned with our spatial axes ($x$, $y$ or $z$), the extension to curvilinear meshes will be presented in the supporting notebooks. #figure( image("files/mesh.png", width: 100%), caption: [Anatomy of a finite volume cell.], ) <fig-mesh> = One cell at a time <one-cell-at-a-time> To discretize the first order differential equations we consider a single cell in the mesh and we will work through the discrete description of equations (1) and (2) over that cell. == In and out <id-1-in-and-out> #figure( image("files/divergence.png", width: 100%), caption: [Geometrical definition of the divergence and the discretization.], ) <fig-div> So we have half of the equation discretized - the left hand side. Now we need to take care of the source: it contains two dirac delta functions - these are infinite at their origins, $r_(s^+)$ and $r_(s^-)$. However, the volume integral of a delta function _is_ well defined: it is _unity_ if the volume contains the origin of the delta function otherwise it is _zero_. As such, we can integrate both sides of the equation over the volume enclosed by the cell. Since $bold(D) bold(j)$ is constant over the cell, the integral is simply a multiplication by the volume of the cell $"v"bold(D) bold(j)$. The integral of the source is zero unless one of the source electrodes is located inside the cell, in which case it is $q = plus.minus I$. Now we have a discrete description of equation 1 over a single cell: $ "v"bold(D) bold(j) = q $ <eq:div> == Scalar equations only, please <id-2-scalar-equations-only-please> Equation @eq:div is a vector equation, so really it is two or three equations involving multiple components of $arrow(j)$. We want to work with a single scalar equation, allow for anisotropic physical properties, and potentially work with non-axis-aligned meshes - how do we do this?! We can use the *weak formulation* where we take the inner product ($integral arrow(a) dot.op arrow(b) d v$) of the equation with a generic face function, $arrow(f)$. This reduces requirements of differentiability on the original equation and also allows us to consider tensor anisotropy or curvilinear meshes. In @fig-weak-formulation, we visually walk through the discretization of equation (b). On the left hand side, a dot product requires a _single_ cartesian vector, $bold(j_x comma j_y)$. However, we have a $j$ defined on each face (2 $j_x$ and 2 $j_y$ in 2D!). There are many different ways to evaluate this inner product: we could approximate the integral using trapezoidal, midpoint or higher order approximations. A simple method is to break the integral into four sections (or 8 in 3D) and apply the midpoint rule for each section using the closest $bold(j)$ components to compose a cartesian vector. A $bold(P)_i$ matrix (size $2 times 4$) is used to pick out the appropriate faces and compose the corresponding vector (these matrices are shown with colors corresponding to the appropriate face in the figure). On the right hand side, we use a vector identity to integrate by parts. The second term will cancel over the entire mesh (as the normals of adjacent cell faces point in opposite directions) and $phi$ on mesh boundary faces are zero by the Dirichlet boundary condition. This leaves us with the divergence, which we already know how to do! #figure( image("files/weak-formulation.png", width: 90%), caption: [Discretization using the weak formulation and inner products.], ) <fig-weak-formulation> The final step is to recognize that, now discretized, we can cancel the general face function $bold(f)$ and transpose the result (for convention's sake): $ frac(1, 4) sum_(i = 1)^4 bold(P)_i^top sqrt(v) bold(Sigma)^(-1) sqrt(v) bold(P)_i bold(j) = bold(D)^top v phi $ = All together now <all-together-now> We have now discretized the two first order equations over a single cell. What is left is to assemble and solve the DC system over the entire mesh. To implement the divergence on the full mesh, the stencil of $plus.minus$1's must index into $bold(j)$ on the entire mesh (instead of four elements). Although this can be done in a `for-loop`, it is conceptually, and often computationally, easier to create this stencil using nested Kronecker Products (see notebook). The volume and area terms in the divergence get expanded to diagonal matrices, and we multiply them together to get the discrete divergence operator. The discretization of the _face_ inner product can be abstracted to a function, $bold(M)_f (sigma^(-1))$, that completes the inner product on the entire mesh at once. The main difference when implementing this is the $bold(P)$ matrices, which must index into the entire mesh. With the necessary operators defined for both equations on the entire mesh, we are left with two discrete equations: $ "diag"(bold(v)) bold(D) bold(j) = bold(q) $ $ bold(M)_f (sigma^(-1)) bold(j) = bold(D)^top "diag"(bold(v)) phi $ Note that now all variables are defined over the entire mesh. We could solve this coupled system or we could eliminate $bold(j)$ and solve for $phi$ directly (a smaller, second-order system). $ "diag"(bold(v)) bold(D) bold(M)_f (sigma^(-1))^(-1) bold(D)^top "diag"(bold(v)) phi = bold(q) $ By solving this system matrix, we obtain a solution for the electric potential $phi$ everywhere in the domain. Creating predicted data from this requires an interpolation to the electrode locations and subtraction to obtain potential differences! #figure( image("files/dc-results.png", width: 90%), caption: [Electric potential on (a) tensor and (b) curvilinear meshes.], ) <fig-results> Moving from continuous equations to their discrete analogues is fundamental in geophysical simulations. In this tutorial, we have started from a continuous description of the governing equations for the DC resistivity problem, selected locations on the mesh to discretize the continuous functions, constructed differential operators by considering one cell at a time, assembled and solved the discrete DC equations. Composing the finite volume system in this way allows us to move to different meshes and incorporate various types of boundary conditions that are often necessary when solving these equations in practice. Associated notebooks are available on #link("https://github.com/simpeg/tle-finitevolume")[GitHub] and can be run online with #link("http://mybinder.org/repo/simpeg/tle-finitevolume")[MyBinder]. All article content, except where otherwise noted (including republished material), is licensed under a Creative Commons Attribution 3.0 Unported License (CC BY-SA). See #link("https://creativecommons.org/licenses/by-sa/3.0/")[https:\/\/creativecommons.org/licenses/by-sa/3.0/]. Distribution or reproduction of this work in whole or in part commercially or noncommercially requires full attribution of the @Cockett_2016, including its digital object identifier (DOI). Derivatives of this work must carry the same license. All rights reserved. // If you are using full-width pages, you must take care of your own bibliography. // Otherwise it will be on a separate page #{ show bibliography: set text(8pt) bibliography("main.bib", title: text(10pt, "References"), style: "apa") }
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/src/layout.typ
typst
MIT License
#import "length-helpers.typ": * /// Update bounds to contain the given rectangle /// - bounds (array): Current bound coordinates x0, y0, x1, y1 /// - rect (array): Bounds rectangle x0, y0, x1, y1 #let update-bounds(bounds, rect) = ( calc.min(bounds.at(0), rect.at(0).to-absolute()), calc.min(bounds.at(1), rect.at(1).to-absolute()), calc.max(bounds.at(2), rect.at(2).to-absolute()), calc.max(bounds.at(3), rect.at(3).to-absolute()), ) #let offset-bounds(bounds, offset) = ( bounds.at(0) + offset.at(0), bounds.at(1) + offset.at(1), bounds.at(2) + offset.at(0), bounds.at(3) + offset.at(1), ) #let make-bounds(x0: 0pt, y0: 0pt, width: 0pt, height: 0pt, x1: none, y1: none) = ( x0.to-absolute(), y0.to-absolute(), (if x1 != none { x1 } else { x0 + width }).to-absolute(), (if y1 != none { y1 } else { y0 + height }).to-absolute(), ) /// Take an alignment or 2d alignment and return a 2d alignment with the possibly /// unspecified axis set to a default value. #let make-2d-alignment(alignment, default-vertical: horizon, default-horizontal: center) = { let axis = alignment.axis() if axis == none { return alignment } if alignment.axis() == "horizontal" { return alignment + default-vertical } if alignment.axis() == "vertical" { return alignment + default-horizontal } } #let make-2d-alignment-factor(alignment) = { let alignment = make-2d-alignment(alignment) let x = 0 let y = 0 if alignment.x == left { x = -1 } else if alignment.x == right { x = 1 } if alignment.y == top { y = -1 } else if alignment.y == bottom { y = 1 } return (x, y) } #let default-size-hint(item, draw-params) = { let content = (item.draw-function)(item, draw-params) let hint = measure(content) hint.offset = auto return hint } #let lrstick-size-hint(item, draw-params) = { let content = (item.draw-function)(item, draw-params) let hint = measure(content) let dx = 0pt if item.data.align == right { dx = hint.width } hint.offset = (x: dx, y: auto) return hint } /// Place some content along with optional labels while computing bounds. /// /// Returns a pair of the placed content and a bounds array. /// /// - content (content): The content to place. /// - dx (length): Horizontal displacement. /// - dy (length): Vertical displacement. /// - size (auto, dictionary): For computing bounds, the size of the placed content /// is needed. If `auto` is passed, this function computes the size itself /// but if it is already known it can be passed through this parameter. /// - labels (array): An array of labels which in turn are dictionaries that must /// specify values for the keys `content` (content), `pos` (strictly 2d /// alignment), `dx` and `dy` (both length, ratio or relative length). /// - draw-params (dictionary): Drawing parameters. /// -> pair #let place-with-labels( content, dx: 0pt, dy: 0pt, size: auto, labels: (), draw-params: none, ) = { if size == auto { size = measure(content) } let bounds = make-bounds( x0: dx, y0: dy, width: size.width, height: size.height ) if labels.len() == 0 { return (place(content, dx: dx, dy: dy), bounds) } let placed-labels = place(dx: dx, dy: dy, box({ for label in labels { let label-size = measure(label.content) let ldx = get-length(label.dx, size.width) let ldy = get-length(label.dy, size.height) if label.pos.x == left { ldx -= label-size.width } else if label.pos.x == center { ldx += 0.5 * (size.width - label-size.width) } else if label.pos.x == right { ldx += size.width } if label.pos.y == top { ldy -= label-size.height } else if label.pos.y == horizon { ldy += 0.5 * (size.height - label-size.height) } else if label.pos.y == bottom { ldy += size.height } let placed-label = place(label.content, dx: ldx, dy: ldy) let label-bounds = make-bounds( x0: ldx + dx, y0: ldy + dy, width: label-size.width, height: label-size.height ) bounds = update-bounds(bounds, label-bounds) placed-label } }) ) return (place(content, dx: dx, dy: dy) + placed-labels, bounds) } // From a list of row heights or col widths, compute the respective // cell center coordinates, e.g., (3pt, 3pt, 4pt) -> (1.5pt, 4.5pt, 8pt) #let compute-center-coords(cell-lengths, gutter) = { let center-coords = () let tmpx = 0pt gutter.insert(0, 0pt) // assert.eq(cell-lengths.len(), gutter.len()) for (cell-length, gutter) in cell-lengths.zip(gutter) { center-coords.push(tmpx + cell-length / 2 + gutter) tmpx += cell-length + gutter } return center-coords } // Given a list of n center coordinates and n cell sizes along one axis (x or y), retrieve the coordinates for a single cell or a list of cells given by index. // If a cell index is out of bounds, the outer last coordinate is returned // center-coords: List of center coordinates for each index // cell-sizes: List of cell sizes for each index // cells: Indices of cell for which to retrieve coordinates // These may also be floats. In this case, the integer part determines the cell index and the fractional part a percentage of the cell width. e.g., passing 2.5 would return the center coordinate of the cell #let get-cell-coords(center-coords, cell-sizes, cells) = { let last = center-coords.at(-1) + cell-sizes.at(-1) / 2 let get(x) = { let integral = calc.floor(x) let fractional = x - integral let cell-width = cell-sizes.at(integral, default: 0pt) return center-coords.at(integral, default: last) + cell-width * (fractional - 0.5) } if type(cells) in (int, float) { get(cells) } else if type(cells) == array { cells.map(x => get(x)) } else { panic("Unsupported coordinate type") } } #let get-cell-coords1(center-coords, cell-sizes, cells) = { let last = center-coords.at(-1) + cell-sizes.at(-1) / 2 let get(x) = { let integral = calc.floor(x) let fractional = x - integral let cell-width = cell-sizes.at(integral, default: 0pt) let c1 = center-coords.at(integral, default: last) let c2 = center-coords.at(integral + 1, default: last) return c1 + (c2 - c1) * (fractional) } if type(cells) in (int, float) { get(cells) } else if type(cells) == array { cells.map(x => get(x)) } else { panic("Unsupported coordinate type") } } #let std-scale = scale
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.1/src/anchor.typ
typst
Apache License 2.0
#import "deps.typ" #import deps.oxifmt: strfmt #import "util.typ" #import util: typst-length #import "intersection.typ" #import "drawable.typ" #import "path-util.typ" #import "matrix.typ" #import "vector.typ" // Compass direction to angle #let named-border-anchors = ( east: 0deg, north-east: 45deg, north: 90deg, north-west: 135deg, west: 180deg, south-west: 225deg, south: 270deg, south-east: 315deg, ) // Path anchors #let named-path-anchors = ( start: 0%, mid: 50%, end: 100%, ) /// Calculates a border anchor at the given angle by testing for an intersection between a line and the given drawables. Returns `none` if no intersection is found for better error reporting. /// /// - center (vector): The position from which to start the test line. /// - x-dist (number): The furthest distance the test line should go in the x direction. /// - y-dist (number): The furthest distance the test line should go in the y direction. /// - drawables (drawables): Drawables to test for an intersection against. Ideally should be of type path but all others are ignored. /// - angle (angle): The angle to check for a border anchor at. /// -> (vector, none) #let border(center, x-dist, y-dist, drawables, angle) = { x-dist += util.float-epsilon y-dist += util.float-epsilon if type(drawables) == dictionary { drawables = (drawables,) } let test-line = ( center, ( center.at(0) + x-dist * calc.cos(angle), center.at(1) + y-dist * calc.sin(angle), center.at(2), ) ) let pts = () for drawable in drawables { if drawable.type != "path" { continue } pts += intersection.line-path(..test-line, drawable) } if pts.len() == 1 { return pts.first() } return if pts.len() == 1 { pts.first() } else if pts.len() > 1 { // Find the furthest intersection point from center util.sort-points-by-distance(center, pts).last() } } /// Setup an anchor calculation and handling function for an element. Unifies anchor error checking and calculation of the offset transform. /// /// A tuple of a transformation matrix and function will be returned. /// The transform is calculated by translating the given transform by the distance between the position of `offset-anchor` and `default`. It can then be used to correctly transform an element's drawables. If either are none the calculation won't happen but the transform will still be returned. /// The function can be used to get the transformed anchors of an element by passing it a string. An empty array can be passed to get the list of valid anchors. /// /// - callback (function, auto): The function to call to get a named anchor's position. The anchor's name will be passed and it should return a vector (str => vector). If no named anchors exist on the element `auto` can be passed instead. /// - anchor-names (array<str>): A list of valid anchor names. This list will be used to validate an anchor exists before `callback` is used. /// - default (str): The name of the default anchor. /// - transform (matrix): The current transformation matrix to apply to an anchor's position before returning it. If `offset-anchor` and `default` is set, it will be first translated by the distance between them. /// - name (str): The name of the element, this is only used in the error message in the event an anchor is invalid. /// - offset-anchor (str): The name of an anchor to offset the transform by. /// - border-anchors (bool): If true, add border anchors. /// - path-anchors (bool): If true, add path anchors. /// - radii (none,tuple): Radius tuple used for border anchor calculation /// - path (none,drawable): Path used for path and border anchor calculation /// -> (matrix, function) #let setup( callback, anchor-names, default: none, transform: none, name: none, offset-anchor: none, border-anchors: false, path-anchors: false, radii: none, path: none ) = { // Passing no callback is valid! if callback == auto { callback = (anchor) => {} } // Add enabled anchor names if border-anchors { assert("center" in anchor-names and radii != none and path != none, message: "Border anchors need a center anchor, radii and the path set!") } if path-anchors { assert(path != none, message: "Path anchors need the path set!") } // Anchor callback let calculate-anchor(anchor, transform: none) = { if anchor == () { return (anchor-names + if border-anchors { named-border-anchors.keys() } + if path-anchors { named-path-anchors.keys() }).dedup() } let out = none if type(anchor) == str { if anchor in anchor-names or (anchor == "default" and default != none) { if anchor == "default" { anchor = default } out = callback(anchor) } else if path-anchors and anchor in named-path-anchors { anchor = named-path-anchors.at(anchor) } else if border-anchors and anchor in named-border-anchors { anchor = named-border-anchors.at(anchor) } else { panic( strfmt( "Anchor '{}' not in anchors {} for element '{}'", anchor, repr(anchor-names), name ) ) } } if out == none { if type(anchor) in (ratio, float, int) { assert(path-anchors, message: strfmt("Element '{}' does not support path anchors.", name)) out = path-util.point-on-path(path.segments, anchor) } else if type(anchor) == angle { assert(border-anchors, message: strfmt("Element '{}' does not support border anchors.", name)) out = border(callback("center"), ..radii, path, anchor) assert(out != none, message: strfmt("Element '{}' does not have a border for anchor '{}'.", name, anchor)) } else { panic(strfmt("Unknown anchor '{}' for element '{}'", repr(anchor), name)) } } return if transform != none { util.apply-transform( transform, out ) } else { out } } if default != none and offset-anchor != none { let offset = matrix.transform-translate( ..vector.sub(calculate-anchor(default), calculate-anchor(offset-anchor)).slice(0, 3) ) transform = if transform != none { matrix.mul-mat( transform, offset ) } else { offset } } return (if transform == none { matrix.ident() } else { transform }, calculate-anchor.with(transform: transform)) }
https://github.com/isaacholt100/isaacholt100.github.io
https://raw.githubusercontent.com/isaacholt100/isaacholt100.github.io/master/maths-notes/3-durham%3A-year-3/galois-theory/galois-theory.typ
typst
#import "../../template.typ": * #show: doc => template(doc, hidden: (), slides: false) // FIND: - \*(\w+)\*: ([\s\S]*?)(?=\n-|\n\n)\n // REPLACE: #$1[\n $2\n]\n #let char = $op("char")$ #let cbrt(arg) = $root(3, #arg)$ #let ideal(..gens) = $angle.l #gens.pos().join(",") angle.r$ #let Aut = $"Aut"$ #let Gal = $"Gal"$ #let gtlex = $scripts(>)_"lex"$ = Introduction #definition[ *Epimorphism* is surjective homomorphism. ] #definition[ *Embedding* or *monomorphism* is injective homomorphism. ] == Cubic equations over $CC$ - For a polynomial equation, a *solution by radicals* is a formula for solutions using only addition, subtraction, multiplication, division and radicals $root(m, dot.op)$ for $m in NN$. - For general cubic equation $x^3 + a_2 x^2 + a_1 x + a_0 = 0$: - *Tschirnhaus transformation* is substitution $t = x + a_2 / 3$, giving $ t^3 + p t + q = 0, quad p := (-a_2^2 + 3a_1) / 3, quad q := (2a_2^3 - 9a_1 a_2 + 27a_0)/27 $ This is a *reduced* (or *depressed*) cubic equation. - When $t = u + v$, $t^3 - (3u v)t - (u^3 + v^3) = 0$ which is in the reduced cubic form with $p = -3u v, q = -(u^3 + v^3)$. - We have $ (y - u^3)(y - v^3) = y^2 - (u^3 + v^3)y + u^3 v^3 = y^2 + q y - p^3/27 = 0 $ so $u^3, v^3 = -q/2 plus.minus sqrt(q^2/4 + p^3/27)$. - So a solution to $t^3 + p t + q = 0$ is $ t = u + v = cbrt(-q/2 + sqrt(q^2/4 + p^3 / 27)) + cbrt(-q/2 - sqrt(q^2/4 + p^3 / 27)) $ The other solutions are $omega u + omega^2 v$ and $omega^2 u + omega v$ where $omega = e^(2pi i \/ 3)$ is the 3rd root of unity. This is because $u$ and $v$ each have three solutions independently to $u^3, v^3 = -q/2 plus.minus sqrt(q^2/4 + p^3/27)$, but also $u v = -p/3$. #remark[ The above method doesn't work for fields of characteristic $2$ or $3$ since the formulas involve division by $2$ or $3$ (which is dividing by zero in these respective fields). ] == Quartic equations over $CC$ - For general quartic equation $x^4 + a_3 x^3 + a_2 x^2 + a_1 x + a_0 = 0$: - Substitution $t = x + a_3/4$ gives *reduced* quartic equation $ t^4 + p t^2 + q t + r = 0 $ - We then manipulate the polynomial so that it is the sum or difference of two squares and use $a^2 + b^2 = (a + i b)(a - i b)$ or $a^2 - b^2 = (a + b)(a - b)$: $ (t^2 + w)^2 + (p - 2w)t^2 + q t + (r - w^2) = 0 $ - $(p - 2w)t^2 + q t + (r - w^2) = 0$ is a square iff its discriminant is zero: $ q^2 - 4(p - 2w)(r - w^2) = 0 <==> w^3 - 1/2 p w^2 - r w + 1/8 (4p r - q^2) = 0 $ - This *cubic resolvent* is solvable by radicals. Taking any of the solutions and substituting for $w$ gives a sum or difference of two squares in $t$. The quadratic factors can then be solved. = Fields and polynomials == Basic properties of fields #definition[ Ring $R$ is *field* if every element of $R - {0}$ has mutliplicative inverse and $1 != 0 in R$. ] #lemma[ Every field is integral domain. ] #definition[ *Field homomorphism* is ring homomorphism $phi: K -> L$ between fields: - $phi(a + b) = phi(a) + phi(b)$ - $phi(a b) = phi(a) phi(b)$ - $phi(1) = 1$ These imply $phi(0) = 0$, $phi(-a) = -phi(a)$, $phi(a^(-1)) = phi(a)^(-1)$. ] #lemma[ Let $phi: K -> L$ field homomorphism. - $im(phi) = {phi(a): a in K}$ is field. - $ker(phi) = {a in K: phi(a) = 0} = {0}$, i.e. $phi$ is injective. ] #definition[ *Subfield* $K$ of field $L$ is subring of $L$ where $K$ is field. $L$ is *field extension* of $K$. ] - The above lemma shows image of $phi: K -> L$ is subfield of $L$. #lemma[ Intersections of subfields are subfields. ] #definition[ *Prime subfield* of $L$ is intersection of all subfields of $L$. ] #definition[ *Characteristic* $char(K)$ of field $K$ is $ char(K) := min{n in NN: chi(n) = 0} $ (or $0$ if this does not exist) where $chi: ZZ -> K$, $chi(m) = 1 + dots.h.c + 1$ ($m$ times). ] #example[ $char(QQ) = char(RR) = char(CC) = 0$, $char\(FF_p\) = p$ for $p$ prime. ] #lemma[ For any field $K$, $char(K)$ is either $0$ or prime. ] #theorem[ - If $char(K) = 0$ then prime subfield of $K$ is $tilde.equiv QQ$. - If $char(K) = p > 0$ then prime subfield of $K$ is $tilde.equiv FF_p$. ] #corollary[ - If $QQ$ is subfield of $K$ then $char(K) = 0$. - If $FF_p$ is subfield of $K$ for prime $p$ then $char(K) = p$. ] #remark[ Let $char(K) = p$, then $p | binom(p, i)$ so $(a + b)^p = a^p + b^p$ in $K$. Also in $K[x]$ for $p$ prime, $x^p - 1 = (x - 1)^p$. ] #theorem(name: "Fermat's little theorem")[ $forall a in FF_p, a^p = a$. ] == Polynomials over fields #definition[ *Degree* of $f(x) = a_0 + a_1 x + dots.h.c + a_n x^n$, $a_n != 0$, is $deg(f(x)) = n$. - Degree of zero polynomial is $deg(0) = -oo$. - $deg(f(x)g(x)) = deg(f(x)) + deg(g(x))$. - $deg(f(x) + g(x)) <= max{deg(f(x)), deg(g(x))}$ with equality if $deg(f(x)) != deg(g(x))$. ] - Only invertible elements in $K[x]$ are non-zero constants $f(x) = a_0 != 0$. - Similarities between $ZZ$ and $K[x]$ for field $K$: - $K[x]$ is integral domain. - There is a division algorithm for $K[x]$: for $f(x), g(x) in K[x]$, $exists! q(x), r(x) in K[x]$ with $deg(r(x)) < deg(g(x))$ such that $ f(x) = q(x) g(x) + r(x) $ - Every $f(x), g(x) in K[x]$ have greatest common divisor $gcd(f(x), g(x))$ unique up to multiplication by non-zero constants. By Euclidean algorithm for polynomials, $ exists a(x), b(x) in K[x]: a(x) f(x) + b(x) g(x) = gcd(f(x), g(x)) $ - Can construct field from $K[x]$: *field of fractions* of $K[x]$ is $ K(x) := "Frac"(K[x]) = {f(x) / g(x): f(x), g(x) in K[x], g(x) != 0} $ where $f_1 (x) \/ g_1 (x) = f_2 (x) \/ g_2 (x) <==> f_1 (x) g_2 (x) = f_2 (x) g_1 (x)$. (We can construct the field of fractions for any integral domain). - $K[x]$ is PID and so UFD. #definition[ For field $K$, $f(x) in K[x]$ *irreducible in $K[x]$* (or $f(x)$ is *irreducible over $K$*) if - $deg(f(x)) >= 1$ and - $f(x) = g(x) h(x) ==> g(x) "or" h(x) "is constant"$ ] == Tests for irreducibility #proposition[ If $f(x)$ has linear factor in $K[x]$, it has root in $K[x]$. ] #proposition(name: "Rational root test")[ If $f(x) = a_0 + dots.h.c + a_n x^n in ZZ[x]$ has rational root $b/c in QQ$ with $gcd(b, c) = 1$ then $b | a_0$ and $c | a_n$. *Note*: this can't be used to show $f$ is irreducible for $deg(f(x)) >= 4$. ] #theorem(name: "Gauss's lemma")[ Let $f(x) in ZZ[x]$, $f(x) = g(x) h(x)$, $g(x), h(x) in QQ[x]$. Then $exists r in QQ: r g(x), r^(-1) h(x) in ZZ[x]$. i.e. if $f(x)$ can be factored in $QQ[x]$ it can be factored in $ZZ[x]$. ] #example[ Let $f(x) = x^4 - 3x^3 + 1 in QQ[x]$. Using the rational root test, $f(plus.minus 1) != 0$ so no linear factors in $QQ[x]$. Checking quadratic factors, let $ f(x) = (a x^2 + b x + c)(r x^2 + s x + t), quad a, b, c, r, s, t in ZZ "by Gauss's lemma" $ So $1 = a r => a = r = plus.minus 1$. $1 = c t => c = t = plus.minus 1$. $-3 = b + s$ and $0 = c(b + s)$: contradiction. So $f(x)$ irreducible in $QQ[x]$. ] #example[ Let $f(x) = x^4 - 3x^2 + 1 in QQ[x]$. The rational root test shows there are no linear factors. Checking quadratic factors, let $ f(x) = (a x^2 + b x + c)(r x^2 + s x + t), quad a, b, c, r, s, t in ZZ "by Gauss's lemma" $ As before, $a = r = plus.minus 1$, $c = t = plus.minus 1$. $0 = b + s => b = -s$, $-3 = a t + b s + c r = -b^2 plus.minus 2$. $b = 1$ works. So $f(x) = (x^2 - x - 1)(x^2 + x - 1)$. ] #proposition[ Let $f(x) = a_0 + dots.h.c + a_n x^n in ZZ[x]$. If exists prime $p divides.not a_n$ such that $overline(f)(x)$ is irreducible in $FF_p [x]$, then $f(x)$ irreducible in $QQ[x]$. ] #example[ Let $f(x) = 8x^3 + 14x - 9$. Reducing $mod 7$, $overline(f)(x) = x^3 - 2 in FF_7 [x]$. No roots exist for this, so $f(x)$ irreducible in $QQ[x]$. For some polynomials, no $p$ is suitable, e.g. $f(x) = x^4 + 1$. ] - Gauss's lemma works with any UFD $R$ instead of $ZZ$ and field of fractions $"Frac"(R)$ instead of $QQ$: e.g. let $F$ field, $R = F[t]$, $K = F(t)$, then $f(x) in R[x]$ irreducible in $K[x]$ if $f(x)$ is irreducible in $R[x]$. #proposition(name: "Eisenstein's criterion")[ Let $f(x) = a_0 + dots.h.c + a_n x^n in ZZ[x]$, prime $p in ZZ$ such that $p | a_0, ..., p | a_(n - 1)$, $p divides.not a_n$, $p^2 divides.not a_0$. Then $f(x)$ irreducible in $QQ[x]$. ] #example[ Let $f(x) = x^3 - 3x + 1$. Consider $f(x - 1) = x^3 - 3x^2 + 3$. Then by Eisenstein's criterion with $p = 3$, $f(x - 1)$ irreducible in $QQ[x]$ so $f(x)$ is as well, since factoring $f(x - 1)$ is equivalent to factoring $f(x)$. ] #example[ *$p$-th cyclotomic polynomial* is $ f(x) = (x^p - 1)/(x - 1) = 1 + dots.h.c + x^(p - 1) $ Now $ f(x + 1) = ((1 + x)^p - 1)/(1 + x - 1) = x^(p - 1) + p x^(p - 2) + dots.h.c + binom(p, p - 2) x + p $ so can apply Eisenstein with $p = p$. ] #proposition(name: "Generalised Eisenstein's criterion")[ Let $R$ be integral domain, $K = "Frac"(R)$, $ f(x) = a_0 + dots.h.c + a_n x^n in R[x] $ If there is irreducible $p in R$ with $ p | a_0, ..., p | a_(n - 1), p divides.not a_n, p^2 divides.not a_0 $ then $f(x)$ is irreducible in $K[x]$. ] = Field extensions == Definitions and examples #definition[ *Field extension* $L \/ K$ is field $L$ containing subfield $K$. Can specify homomorphism $iota: K -> L$ (which is injective). ] #example[ - $CC \/ RR$, $CC \/ QQ$, $RR \/ QQ$. - $L = QQ\(sqrt(2)\) = \{a + b sqrt(2): a, b in QQ\}$ is field extension of $QQ$. $QQ(theta)$ is field extension of $QQ$ where $theta$ is root of $f(x) in QQ[x]$. - $L = QQ\(root(3, 2)\) = \{a + b root(3, 2) + c root(3, 4): a, b, c in QQ\}$ is smallest subfield of $RR$ containing $QQ$ and $root(3, 2)$. - $K(t)$ is field extension of $K$. ] #definition[ Let $L \/ K$ field extension, $S subset.eq L$. Then *$K$ with $S$ adjoined*, $K(S)$, is minimal subfield of $L$ containing $K$ and $S$. If $|S| = 1$, $L \/ K$ is a *simple extension*. ] #example[ $QQ\(sqrt(2), sqrt(7)\) = \{a + b sqrt(2) + c sqrt(7) + d sqrt(14): a, b, c, d, in QQ\}$ is $QQ$ with $S = \{sqrt(2), sqrt(7)\}$. ] #example[ $RR \/ QQ$ is not simple extension. ] #definition[ *Tower* is chain of field extensions, e.g. $K subset M subset L$. ] == Algebraic elements and minimal polynomials #definition[ Let $L \/ K$ field extension, $theta in L$. Then $theta$ is *algebraic over $K$* if $ exists 0 != f(x) in K[x]: f(theta) = 0 $ Otherwise, $theta$ is *transcendental over $K$*. ] #example[ For $n >= 1$, $theta = e^(2pi i\/n)$ is algebraic over $QQ$ (root of $x^n - 1$). ] #example[ $t in K(t)$ is transcendental over $K$. ] #lemma[ The algebraic elements in $K(t)\/K$ are precisely $K$. ] #lemma[ Let $L\/K$ field extension, $theta in L$. Define $I_K (theta) := {f(x) in K[x]: f(theta) = 0}$. Then $I_K (theta)$ is ideal in $K[x]$ and - If $theta$ transcendental over $K$, $I_K (theta) = {0}$ - If $theta$ algebraic over $K$, then exists unique monic irreducible polynomial $m(x) in K[x]$ such that $I_K (theta) = angle.l m(x) angle.r$. ] #definition[ For $theta in L$ algebraic over $K$, *minimal polynomial of $theta$ over $K$* is the unique monic polynomial $m(x) in K[x]$ such that $I_K (theta) = angle.l m(x) angle.r$. The *degree* of $theta$ over $K$ is $deg(m(x))$. ] #remark[ If $f(x) in K[x]$ irreducible over $K$, monic and $f(theta) = 0$ then $f(x) = m(x)$. ] #example[ - Any $theta in K$ has minimal polynomial $x - theta$ over $K$. - $i in CC$ has minimal polynomial $x^2 + 1$ over $RR$. - $sqrt(2)$ has minimal polynomial $x^2 - 2$ over $QQ$. $root(3, 2)$ has minimal polynomial $x^3 - 2$ over $QQ$. ] == Constructing field extensions #lemma[ Let $K$ field, $f(x) in K[x]$ non-zero. Then $ f(x) "irreducible over" K <==> K[x] \/ angle.l f(x) angle.r "is a field" $ ] #definition[ Let $L_1 \/ K$, $L_2 \/ K$ field extensions, $phi: L_1 -> L_2$ field homomorphism. $phi$ is *$K$-homomorphism* if $forall a in K, phi(a) = a$ ($phi$ fixes elements of $K$). - If $phi$ is isomorphism then it is *$K$-isomorphism*. - If $L_1 = L_2$ and $phi$ is bijective then $phi$ is *$K$-automorphism*. ] #theorem[ Let $m(x) in K[x]$ irreducible, monic, $K_m := K[x] \/ ideal(m(x))$. Then - $K_m \/ K$ is field extension. - Let $theta = pi(x)$ where $pi: K[x] -> K_m$ is canonical projection, then $theta$ has minimal polynomial $m(x)$ and $K_m tilde.equiv K(theta)$. ] #proposition(name: "Universal property of simple extension")[ Let $L\/K$ field extension, $tau in L$ with $m(tau) = 0$ and $K_L (tau)$ be minimal subfield of $L$ containing $K$ and $tau$. Then exists unique $K$-isomorphism $phi: K_m -> K_L (tau)$ such that $phi(theta) = tau$. ] #example[ - Complex conjugation $CC -> CC$ is $RR$-automorphism. - Let $K$ field, $char(K) != 2$, $sqrt(2) in.not K$, so $x^2 - 2$ is minimal polynomial of $sqrt(2)$ over $K$, then $K\(sqrt(2)\) tilde.equiv K[x] \/ ideal(x^2 - 2)$ is field extension of $K$ and $a + b sqrt(2) |-> a - b sqrt(2)$ is $K$-automorphism. ] #proposition[ Let $theta$ transcendental over $K$, then exists unique $K$-isomorphism $phi: K(t) -> K(theta)$ such that $phi(t) = theta$: $ phi(f(t)/g(t)) = phi(f(theta)/g(theta)) $ ] == Explicit examples of simple extensions #example[ - Let $r in K^times$ non-square in $K$, $char(K) != 2$, then $x^2 - r$ irreducible in $K[x]$. E.g. for $K = QQ(t)$, $x^2 - t in K[x]$ is irreducible. Then $K\(sqrt(t)\) = QQ\(sqrt(t)\) tilde.equiv K[x] \/ ideal(x^2 - t)$. - Define $FF_9 = FF_3 [x] \/ ideal(x^2 - 2) tilde.equiv FF_3 (theta) = {a + b theta: a, b in FF_3}$ for $theta$ a root of $x^2 - 2$. ] #proposition[ Let $K(theta)\/K$ where $theta$ has minimal polynomial $m(x) in K[x]$ of degree $n$. Then $ K[x] \/ ideal(m(x)) tilde.equiv K(theta) = {c_0 + c_1 theta + dots.h.c + c_(n - 1) theta^(n - 1): c_i in K} $ and its elements are written uniquely: $K(theta)$ is vector space over $K$ of dimension $n$ with basis ${1, theta, ..., theta^(n - 1)}$. ] #example[ $QQ\(cbrt(2)\) = \{a + b cbrt(2) + c cbrt(4): a, b, c in QQ\} tilde.equiv QQ[x] \/ ideal(x^3 - 2)$. $QQ\(omega cbrt(2)\)$ and $QQ\(w^2 cbrt(2)\)$ where $omega = e^(2pi i \/ 3)$ are isomorphic to $QQ\(cbrt(2)\)$ as $omega cbrt(2)$, $omega cbrt(4)$ have same minimal polynomial. ] == Degrees of field extensions #definition[ *Degree* of field extension $L\/K$ is $ [L: K] := dim_K (L) $ ] #example[ - When $theta$ algebraic over $K$ of degree $n$, $[K(theta): K] = n$. - Let $theta$ transcendental over $K$, then $[K(theta): K] = oo$, so $[K(t): K] = oo$, $[QQ(pi): QQ]$, $[RR: QQ] = oo$. ] #definition[ $L\/K$ is *algebraic extension* if every element in $L$ is algebraic over $K$. ] #proposition[ Let $[L: K] < oo$, then $L\/K$ is algebraic extension and $L = K(alpha_1, ..., alpha_n)$ for some $alpha_1, ..., alpha_n in L$. The converse also holds. ] #theorem(name: "Tower law")[ Let $K subset.eq M subset.eq L$ tower of field extensions. Then - $[L: K] < oo <==> [L: M] < oo and [M: K] < oo$. - $[L: K] = [L: M] [M: K]$. ] #example[ - $K = QQ subset M = QQ\(sqrt(2)\) subset L = QQ\(sqrt(2), sqrt(7)\)$. $M\/K$ has basis $\{1, sqrt(2)\}$ so $[M: K] = 2$. Let $sqrt(7) in QQ\(sqrt(2)\)$, then $sqrt(7) = c + d sqrt(2)$, $c, d in QQ$ so $7 = (c^2 + 2d^2) + 2c d sqrt(2)$ so $7 = c^2 + 2d^2$, $0 = 2c d$ so $d^2 = 7/2$ or $c^2 = 7$, which are both contradictions. So $[L: K] = 4$ with basis $\{1, sqrt(2), sqrt(7), sqrt(14)\}$. - Let $K = QQ subset M = QQ(i) subset QQ\(i, sqrt(2)\)$. We know $[QQ(i): QQ] = 2$, and $\[QQ\(sqrt(2)\): QQ\] = 2$, $\[QQ\(i, sqrt(2)\): QQ\] = 4$ (since $i in.not RR$) so $\[QQ\(i, sqrt(2)\): QQ\(sqrt(2)\)\] = 2$. - Let $K = QQ subset M = QQ\(sqrt(2)\) subset L = QQ\(sqrt(2), cbrt(3)\)$. Then $\[QQ\(sqrt(2)\): QQ\] = 2$, $\[QQ\(cbrt(3)\): QQ\] = 3$ so $2 | [L: K]$ and $3 | [L: K]$ so $6 | [L: K]$ so $[L: K] >= 6$. But $[L: M] <= 3$ and $[M: K] <= 2$ so $[L: K] <= 6$ hence $[L: K] = 6$. ] - More generally, we have $[K(alpha, beta): K] <= [K(alpha): K] [K(beta): K]$. #example[ - Let $theta = cbrt(4) + 1$. $QQ(theta) = QQ\(cbrt(4)\)$ so minimal polynomial over $QQ$, $m$, has $deg(m) = 3$. $(theta - 1)^3 = 4$ so minimal polynomial is $x^3 - 3x^2 + 3x - 5$. - Let $theta = sqrt(2) + sqrt(3)$. $QQ\(sqrt(2), theta\) = QQ\(sqrt(2), sqrt(3)\)$ which has degree $2$ over $QQ\(sqrt(2)\)$ so minimal polynomial of $theta$ over $QQ\(sqrt(2)\)$ has degree $2$, $theta - sqrt(2) = sqrt(3)$ so minimal polynomial is $x^2 - 2 sqrt(2) x - 1$. - Let $theta = sqrt(2) + sqrt(3)$. $QQ subset QQ(theta) subset QQ\(sqrt(2), sqrt(3)\)$ so $[QQ(theta): QQ] | \[QQ\(sqrt(2), sqrt(3)\): QQ\] = 4$ so $[QQ(theta): QQ] in {1, 2, 4}$. Can't be $1$ as $theta in.not QQ$. If it was $2$ then $1, theta, theta^2$ are linearly dependent over $QQ$ which leads to a contradiction. So degree of minimal polynomial of $theta$ over $QQ$ is $4$. $theta^2 = 5 + 2 sqrt(6) => (theta^2 - 5)^2 = 24$ so minimal polynomial is $x^4 - 10x^2 + 1$. ] = Galois extensions == Splitting fields #definition[ For field $K$, $0 != f(x) in K[x]$, $L\/K$ is *splitting field* of $f(x)$ over $K$ if - $exists c in K^times, theta_1, ..., theta_n in L: f(x) = c (x - theta_1) thin dots.h.c thin (x - theta_n)$ ($f(x)$ *splits over $L$*). - $L = K(theta_1, ..., theta_n)$. ] #example[ - $CC$ is splitting field of $x^2 + 1$ over $RR$, since $x^2 + 1 = (x + i)(x - i)$ and $CC = RR(i, -i) = RR(i)$. - $CC$ is not splitting field of $x^2 + 1$ over $QQ$ as $CC != QQ(i, -i)$. - $QQ$ is splitting field of $x^2 - 36$ over $QQ$. - $CC$ is splitting of $x^4 + 1$ over $RR$. - $QQ\(i, sqrt(2)\)$ is splitting field of $x^4 - x^2 - 2 = (x^2 + 1)(x^2 - 2) = (x + i)(x - i)\(x + sqrt(2)\)\(x - sqrt(2)\)$ over $QQ$. - $FF_2 (theta)$ where $theta^3 + theta + 1 = 0$ is splitting field of $x^3 + x + 1$ over $FF_2$. - Consider splitting field of $x^3 - 2$ over $QQ$. Let $omega = e^(2pi i\/3) = \(-1 + sqrt(-3)\)\/2$ then $QQ\(cbrt(2), omega\)$ is splitting field since it must contain $cbrt(2)$, $omega cbrt(2)$, $omega^2 cbrt(2)$. ] #theorem[ Let $0 != f(x) in K[x]$, $deg(f) = n$. Then there exists a splitting field $L$ of $f(x)$ over $K$ with $ [L: K] <= n! $ ] #notation[ For field homomorphism $phi: K -> K'$ and $f(x) = a_0 + dots.h.c + a_n x^n in K[x]$, write $ phi_* (f(x)) := phi(a_0) + dots.h.c + phi(a_n) x^n in K'[x] $ ] #lemma[ Let $sigma: K -> K'$ isomorphism and $K(theta)\/K$, $theta$ has minimal polynomial $m(x) in K[x]$, $theta'$ be root of $sigma_* (m(x))$. Then there exists unique $K$-isomorphism $tau: K(theta) -> K'(theta')$ such that $tau(theta) = theta'$. ] #theorem[ For field isomorphism $sigma: K -> K'$ and $0 != f(x) in K[x]$, let $L$ be splitting field of $f(x)$ over $K$, $L'$ be splitting field of $sigma_* (f(x))$ over $K'$. Then there exists a field isomorphism $tau: L -> L'$ such that $forall a in K, tau(a) = sigma(a)$. ] #corollary[ Setting $K = K'$ and $sigma = id$ implies that splitting fields are unique. ] == Normal extensions #definition[ $L\/K$ is *normal* if: for all $f(x) in K[x]$, if $f$ is irreducible and has a root in $L$ then all its roots are in $L$. In particular, $f(x)$ splits completely as product of linear factors in $L[x]$. So the minimal polynomial of $theta in L$ over $K$ has all its roots in $L$ and can be written as product of linear factors in $L[x]$. ] #example[ - If $[L: K] = 1$ then $L\/K$ is normal. - If $[L: K] = 2$ then $L\/K$ is normal: let $theta in L$ have minimal polynomial $m(x) in K[x]$, then $K subset.eq K(theta) subset.eq L$ so $deg(m(x)) = [K(theta): K] in {1, 2}$: - If $deg(m(x)) = 1$ then $m(x)$ is already linear. - If $deg(m(x)) = 2$ then $m(x) = (x - theta) m_1 (x)$, $m_1 (x) in L[x]$ is linear so $m(x)$ splits completely in $L[x]$. - If $[L: K] = 3$ then $L\/K$ is not necessarily normal. Let $theta$ be root of $x^3 - 2 in QQ[x]$. Other two roots are $omega theta$, $omega^2 theta$ where $omega = e^(2pi i\/3)$. If $omega theta in QQ(theta)$ then $omega = (omega theta)/theta in L$ so $QQ subset QQ(omega) subset QQ(theta)$ but $[QQ(omega): QQ] = 2$ which doesn't divide $[QQ(theta): QQ] = 3$. - Let $theta in CC$ be root of irreducible $f(x) = x^3 - 3x - 1 in QQ[x]$. Let $theta = u + v$, then $(u + v)^3 - 3 u v(u + v) - (u^3 + v^3) equiv 0$ implies $u v = 1 = u^3 v^3$, $u^3 + v^3 = 1$. So $(y - u^3)(y - v^3) = y^2 - y + 1$ has roots $u^3$ and $v^3$. So the three roots of $f$ are $ theta_1 = u + v = e^(pi i\/9) + e^(-pi i\/9) & = 2 cos(pi\/9) \ theta_2 = omega u + omega^2 v = e^(7pi i\/9) + e^(-7 pi i\/9) & = 2 cos(7 pi \/ 9) \ theta_3 = omega^2 u + omega v = e^(13 pi i\/9) + e^(-13pi i\/9) & = 2 cos(13pi\/9) $ Furthermore, for each $i, j$, $theta_i in QQ(theta_j)$, e.g. $ theta_2 = 2 cos(pi - (2pi)/9) = -2cos((2pi)/9) = -2(2cos(pi/9)^2 - 1) = 2 - theta_1^2 $ Also $theta_1 + theta_2 + theta_3 = 0$ so $theta_3 in QQ(theta_1)$. So $QQ(theta_1)$ contains all roots of $f(x)$. ] #theorem(name: "normality criterion")[ $L\/K$ is finite and normal iff $L$ is splitting field for some $0 != f(x) in K[x]$ over $K$. ] #example[ - $QQ\(sqrt(2), sqrt(3), sqrt(5), sqrt(7)\)\/QQ$ is normal as it is the splitting field of $f(x) = (x^2 - 2)(x^2 - 3)(x^2 - 5)(x^2 - 7) in QQ[x]$. - $QQ\(cbrt(2)\)\/QQ$ is not normal but $QQ\(cbrt(2), omega\)\/QQ$ is normal as it is the splitting field of $x^3 - 2 in QQ$. - $QQ\(root(4, 2)\)\/QQ$ is not normal but $QQ\(root(4, 2), i\)\/QQ$ is normal. - Let $theta$ root of $f(x) = x^3 - 3x - 1 in QQ[x]$. Then $QQ(theta)\/QQ$ is normal as is splitting field of $f(x)$ over $QQ$. - $FF_2 (theta)\/FF_2$ where $theta^3 + theta^2 + 1 = 0$ is normal, as $FF_2 (theta)$ contains all roots of $x^3 + x^2 + 1$. - $FF_p (theta)\/FF_p (t)$ where $theta^p = t$ is normal as it is the splitting field of $x^p - t = x^p - theta^p = (x - theta)^p$ so $f(x)$ splits into linear factors in $L[x]$. ] #definition[ Field $N$ is *normal closure* of $L\/K$ if $K subset.eq L subset.eq N$, $N\/K$ is normal, and if $K subset.eq L subset.eq N' subset.eq N$ with $N'\/K$ normal then $N = N'$. ] #theorem[ Every finite extension $L\/K$ has normal closure, unique up to a $K$-isomorphism. ] #definition[ $Aut(L\/K)$ is group of $K$-automorphisms of $L\/K$ with composition as the group operation. ] #example[ - $Aut(CC\/RR)$ contains at least two elements: complex conjugation: $sigma(a + b i) = a - b i$ and the identity map $id = sigma^2$. If $tau in Aut(CC\/RR)$ then $tau(a + b i) = a + b tau(i)$. But $tau(i)^2 = tau(i^2) = tau(-1) = -1$ hence $tau(i) = plus.minus i$. So there are only two choices for $tau$. So $Aut(CC\/RR) = {id, sigma}$. - Let $f(x) = x^2 + p x + q in QQ[x]$ irreducible with distinct roots $theta, theta'$. Then $Aut(QQ(theta)\/QQ) = {id, sigma} tilde.equiv ZZ\/2$ where $sigma(a + b theta) = a + b theta'$. - Let $theta$ root of $x^3 - 2$, let $sigma in Aut(QQ(theta)\/QQ)$. Now $sigma(theta)^3 = sigma(theta^3) = sigma(2) = 2$ so $sigma(theta) in {theta, omega theta, omega^2 theta}$ but $omega theta, omega^2 theta in.not QQ(theta)$ so $sigma(theta) = theta ==> sigma = id$. - Let $theta^p = t$, $sigma in Aut(FF_p (theta)\/ FF_p (t))$. Then $ sigma(theta)^p = sigma(theta^p) = sigma(t) = t = theta^p $ so $(sigma(theta) - theta))^p = sigma(theta)^p - theta^p = 0 ==> sigma(theta) = theta ==> sigma = id$. - Let $sigma in Aut(RR\/QQ)$. Then $alpha <= beta in RR ==> beta - alpha = gamma^2$, $gamma in RR$, so $sigma(beta) - sigma(a) = sigma(gamma)^2 >= 0$ so $sigma(alpha) <= sigma(beta)$. Given $alpha in RR$, there exist sequences $(r_n), (s_n) subset QQ$ with $r_n <= alpha <= s_n$ and $r_n -> alpha$, $s_n -> alpha$ as $n -> oo$. Hence $r_n = sigma(r_n) <= sigma(alpha) <= sigma(s_n) = s_n$ so $sigma(alpha) = alpha$ by squeezing. Hence $Aut(RR\/QQ) = {id}$. ] #theorem[ Let $L = K(theta)$, $theta$ root of irreducible $f(x) in K[x]$, $deg(f) = n$. Then $|Aut(L\/K)| <= n$, with equality iff $f(x)$ has $n$ distinct roots in $L$. ] #theorem[ Let $L\/K$ be finite extension. Then $|Aut(L\/K)| <= [L: K]$, with equality iff $L\/K$ is normal and minimal polynomial of every $theta in L$ over $K$ has no repeated roots (in a splitting field). ] == Separable extensions #definition[ Let $L\/K$ finite extension. - $theta in L$ is *separable over $K$* if its minimal polynomial over $K$ has no repeated roots (in its splitting field). - $L\/K$ is *separable* if every $theta in L$ is separable over $K$. ] #example[ Let $K = FF_p (t)$, then $f(x) = x^p - t in K[x]$ is irreducible by Eisenstein's criterion with $p = t$, and $f(x) = x^p - theta^p = (x - theta)^p$ so $theta$ is root of multiplicity $p >= 2$. So $FF_p (theta)\/FF_p (t)$ is normal but not separable. ] #definition[ Let $f(x) = sum_(i = 0)^n a_i x^i in K[x]$. *Formal derivative* of $f(x)$ is $ D f(x) = D(f) := sum_(i = 1)^n i a_i x^(i - 1) in K[x] $ ] #note[ Formal derivative satisfies: $ D(f + g) = D(f) + D(g), quad D(f g) = f dot.op D(g) + D(f) dot.op g, quad forall a in K, D(a) = 0 $ Also $deg(D(f)) < deg(f)$. But if $char(K) = p$, then $D(x^p) = p x^(p - 1) = 0$ so it is not always true that $deg(D(f)) = deg(f) - 1$. ] #note[ If $f(x)$ has a repeated root $alpha$, then $D f(alpha) = 0$. ] #theorem(name: "sufficient conditions for separability")[ Finite extension $L\/K$ is separable if any of the following hold: - $char(K) = 0$, - $char(K) = p$ and $K = {b^p: b in K} = K^p$ for prime $p$, - $char(K) = p$ and $p divides.not [L: K]$ ] #definition[ $K$ is *perfect field* if either of first two of above properties hold. ] #remark[ All finite extensions of any perfect extension (e.g. $QQ, FF_p$) are separable (recall Fermat's little theorem: $forall a in FF_p, a = a^p$). So to find a non-separable extension $L\/K$, we need $char(K) = p > 0$, $K$ infinite and $p | [L: K]$. For example, $L = FF_p (theta)$, $K = FF_p (t)$ where $theta^p = t$. ] #theorem[ Let $alpha_1, ..., alpha_n$ algebraic over $K$, then $K(alpha_1, ..., alpha_n)\/K$ is separable iff every $alpha_i$ is separable over $K$. ] #remark[ For tower $K subset.eq M subset.eq L$, $L\/K$ is separable iff $L\/M$ and $M\/K$ are separable. However, the same statement for normality does not hold. ] #theorem(name: "Theorem of the Primitive Element")[ Let $L\/K$ finite and separable. Then $L\/K$ is simple, i.e. $exists alpha in L: L = K(alpha)$. ] == The fundamental theorem of Galois theory #definition[ Finite extension $L\/K$ is *Galois extension* if it is normal and separable. Equivalently, $|Aut(L\/K)| = [L: K]$. When $L\/K$ is Galois, the *Galois group* is $Gal(L\/K) := Aut(L\/K)$. ] #definition[ Let $cal(F) := {"intermediate fields of" L\/K}$ and $cal(G) := {"subgroups of" Gal(L\/K)}$. Define the map $Gamma: cal(F) -> cal(G)$, $Gamma(M) = Gal(L\/M)$. ] #definition[ Let $L$ field, $G$ a group of automorphisms of $L$. *Fixed field* $L^G$ of $G$ is set of elements in $L$ which are invariant under all automorphisms in $G$: $ L^G := {alpha in L: forall alpha in G, thick sigma(alpha) = alpha} $ ] #theorem[ If $G$ is finite group of automorphisms of $L$ then $L^G$ is subfield of $L$ and $[L: L^G] = |G|$. ] #corollary[ If $L\/K$ is Galois then - $L^(Gal(L\/K)) = K$. - If $L^G = K$ for some group $G$ of $K$-automorphisms of $L$, then $G = Gal(L\/K)$. ] #note[ Let $sigma in Gal(L\/K)$. If $alpha in L$ has minimal polynomial $f(x) in K[x]$ over $K$, then $f(alpha) = 0$, and $ f(sigma(alpha)) = sigma(f(alpha)) $ by properties of field homomorphisms. Hence $sigma(alpha)$ is also a root of $f(x)$ for any $sigma in Gal(L\/K)$, i.e. $sigma$ permutes the roots of $f(x)$. ] #remark[ If $L\/K$ is Galois and $alpha in L$ but $alpha in.not K$, then there exists an automorphism $sigma in Gal(L\/K)$ such that $sigma(alpha) != alpha$. ] #definition[ For $H$ subgroup of $Gal(L\/K)$, set $L^H := {alpha in L: forall sigma in H, thick sigma(alpha) = alpha}$, then $K subset.eq L^H subset.eq L$. Define $Phi: cal(G) -> cal(F)$, $Phi(H) = L^H$. ] - $Gamma$ and $Phi$ are inclusion-reversing: $M_1 subset.eq M_2 ==> Gamma(M_2) subset.eq Gamma(M_1)$, and $H_1 subset.eq H_2 ==> Phi(H_2) subset.eq Phi(H_1)$. #theorem(name: "Fundamental theorem of Galois theory - Theorem A")[ For finite Galois extension $L\/K$, - $Gamma: cal(F) -> cal(G)$ and $Phi: cal(G) -> cal(F)$ are mutually inverse bijections (the *Galois correspondence*). - For $M in cal(F)$, $L\/M$ is Galois and $|Gal(L\/M)| = [L: M]$. - For $H in cal(G)$, $L\/L^H$ is Galois and $Gal(L\/L^H) = H$. ] #remark[ $Gal(L\/K)$ acts on $cal(F)$: given $sigma in Gal(L\/K)$ and $K subset.eq M subset.eq L$, consider $sigma(M) = {sigma(alpha): alpha in M}$ which is a subfield of $L$ and contains $K$, since $sigma$ fixes elements of $K$. Given another automorphism $tau: L -> L$, $ tau in Gal(L\/sigma(M)) & <==> forall alpha in M, tau(sigma(alpha)) = sigma(alpha) \ & <==> forall alpha in M, sigma^(-1) (tau (sigma(alpha))) = alpha \ & <==> sigma^(-1) tau sigma in Gal(L\/M) \ & <==> tau in sigma Gal(L\/M) sigma^(-1) $ Hence $sigma Gal(L\/M) sigma^(-1)$ and $Gal(L\/M)$ are conjugate subgroups of $Gal(L\/K)$. Now $ [M: K] = ([L: K]) / ([L: M]) = abs(Gal(L\/K)) / abs(Gal(L\/M)) $ ] #theorem(name: "Fundamental theorem of Galois theory - Theorem B")[ Let $L\/K$ be finite Galois extension, $G = Gal(L\/K)$ and $K subset.eq M subset.eq L$. Then the following are equivalent: - $M\/K$ is Galois. - $forall sigma in G, quad sigma(M) = M$. - $H = Gal(L\/M)$ is normal subgroup of $G = Gal(L\/K)$. When these conditions hold, we have $Gal(M\/K) tilde.equiv G\/H$. ] #example[ Let $L\/K$ be Galois, $[L: K] = p$ prime. - By the tower law, any $K subset.eq M subset.eq L$ has $[L: M] in {1, p}$, $[M: K] in {p, 1}$, so $M = L$ or $K$. In both cases, $M\/K$ is normal. - $|Gal(L\/K)| = [L: K] = p$ so $Gal(L\/M) tilde.equiv ZZ\/p$, so the only subgroups are $Gal(L\/K)$ and ${id}$. In both cases, $H$ is normal subgroup of $Gal(L\/K)$. ] == Computations with Galois groups #example(name: "quadratic extension")[ $QQ\(sqrt(2)\)\/QQ$ is normal (since degree is $2$) and separable (since characteristic is zero). Any element of $phi in G = Gal\(QQ\(sqrt(2)\)\/QQ\)$ is determined by the image of $sqrt(2)$. But $phi\(sqrt(2)\)^2 = phi(2) = 2$ so $phi\(sqrt(2)\) = plus.minus sqrt(2)$. This gives two automorphisms $id\(sqrt(2)\) = sqrt(2)$ and $sigma\(sqrt(2)\) = -sqrt(2)$. So $G = {id, sigma} = ideal(sigma) tilde.equiv ZZ\/2$. Subgroup ${id}$ corresponds to $QQ\(sqrt(2)\)$, $G$ corresponds to $QQ$. ] #example(name: "biquadratic extension")[ $L = QQ\(sqrt(2), sqrt(3)\)$ over $QQ$ is normal (as splitting field of $(x^2 - 2)(x^2 - 3)$ over $QQ$) and separable (as $char(QQ) = 0$), so is Galois extension. Let $sigma$ be given as before. - Suppose $sqrt(3) in QQ\(sqrt(2)\)$, then $sigma\(sqrt(3)\)^2 = sigma(3) = 3$, so $sigma\(sqrt(3)\) = plus.minus sqrt(3)$. - If $sigma\(sqrt(3)\) = sqrt(3)$, then $sqrt(3) in QQ\(sqrt(2)\)^({id, sigma}) = QQ$: contradiction. - If $sigma\(sqrt(3)\) = -sqrt(3)$, then $sigma\(sqrt(2)\) sigma\(sqrt(3)\) = sigma\(sqrt(6)\) = \(-sqrt(2)\)\(-sqrt(3)\) = sqrt(6)$, so $sqrt(6) in QQ\(sqrt(2)\)^({id, sigma}) = QQ$: contradiction. - So $sqrt(3) in.not QQ\(sqrt(2)\)$, hence $[L: QQ] = \[L: QQ\(sqrt(2)\)\] \[QQ\(sqrt(2)): QQ\] = 4$. - Now $G = Gal(L\/QQ)$ has order $[L: QQ] = 4$, so $G tilde.equiv ZZ\/4$ or $ZZ\/2 times ZZ\/2$. - For $phi in G$, $phi\(sqrt(2)\)^2 = 2 ==> phi\(sqrt(2)\) = plus.minus sqrt(2)$, $phi\(sqrt(3)\)^2 = 3 ==> phi\(sqrt(3)\) = plus.minus sqrt(3)$. So there are four choices, corresponding to choices of $plus.minus$ signs. - Define $sigma, tau$ by $sigma\(sqrt(2)\) = -sqrt(2)$, $sigma\(sqrt(3)\) = sqrt(3)$, $tau\(sqrt(2)\) = sqrt(2)$, $tau\(sqrt(3)\) = -sqrt(3)$. Now $sigma^2 = tau^2 = id$, $sigma tau \(sqrt(2)\) = - sqrt(2)$, $sigma tau \(sqrt(3)\) = -sqrt(3)$ and $sigma tau = tau sigma$. - So $G = angle.l sigma, tau: sigma^2 = tau^2 = id, sigma tau = tau sigma angle.r = ideal(sigma) times ideal(tau) tilde.equiv ZZ\/2 times ZZ\/2$. - $G$ has proper subgroups $H_1 = ideal(sigma)$, $H_2 = ideal(tau)$, $H_3 = ideal(sigma tau)$. - So the intermediate fields are $L^(H_1), L^(H_2), L^(H_3)$. - $sigma\(sqrt(3)\) = sqrt(3) ==> sqrt(3) in L^(H_1)$ so $QQ\(sqrt(3)\) subset.eq L^(H_1)$, but $\[L: QQ\(sqrt(3)\)\] = 2 = |H_1| = [L: L^(H_1)]$. Hence $L^(H_1) = QQ\(sqrt(3)\)$. Similarly $L^(H_2) = QQ\(sqrt(2)\)$. - $sigma tau \(sqrt(6)\) = sqrt(6) ==> sqrt(6) in L^(H_3)$, so $L^(H_3) = QQ\(sqrt(6)\)$. ] #remark[ It is not generally true that $\[K\(sqrt(a), sqrt(b)\): K\] = 4$, e.g. $QQ\(sqrt(2), sqrt(8)\) = QQ\(sqrt(2)\)$. ] #remark[ Can generalise above example to arbitrary $K\(sqrt(a), sqrt(b)\)\/K$ where $char(K) != 2$, and $a, b in K$, $a, b, a b in.not (K^times)^2$ where $(K^times)^2$ is set of squares of $K^times$. ] #example(name: [degree $8$ extension])[ - Consider $L = QQ\(sqrt(2), sqrt(3), sqrt(5)\)$ over $QQ$. $L$ is splitting field of $(x^2 - 2)(x^2 - 3)(x^2 - 5)$, so is normal, and $char(QQ) = 0$, so is separable, so is Galois. - Let $M = QQ\(sqrt(2), sqrt(3)\)$. By above, $Gal(M\/Q) = ideal(sigma) times ideal(tau) tilde.equiv ZZ\/2 times ZZ\/2$. - Suppose $sqrt(5) in M$. Then $sigma\(sqrt(5)\)^2 = tau\(sqrt(5)\)^2 = 5$, so $sigma\(sqrt(5)\) = plus.minus sqrt(5)$, $tau\(sqrt(5)\) = plus.minus sqrt(5)$. - If $sigma\(sqrt(5)\) = sqrt(5)$, then $sqrt(5) in M^(ideal(sigma)) = QQ\(sqrt(3)\)$. - If $tau\(sqrt(5)\) = sqrt(5)$, $sqrt(5) in M^(ideal(sigma, tau)) = QQ$: contradiction. - If $tau\(sqrt(5)\) = -sqrt(5)$, then since $sqrt(15) in M^(ideal(sigma))$, $tau\(sqrt(15)\) = sqrt(15)$, so $sqrt(15) in M^(ideal(sigma, tau)) = QQ$: contradiction. - If $sigma\(sqrt(5)\) = -sqrt(5)$, then $sigma\(sqrt(10)\) = sigma\(sqrt(2)\) sigma\(sqrt(5)\) = \(-sqrt(2)\)\(-sqrt(5)\) = sqrt(10)$, so $sqrt(10) in M^(ideal(sigma)) = QQ\(sqrt(3)\)$. - If $tau\(sqrt(5)\) = sqrt(5)$, $tau\(sqrt(10)\) = sqrt(10) in M^(ideal(sigma, tau)) = QQ$: contradiction. - If $tau\(sqrt(5)\) = -sqrt(5)$, $tau\(sqrt(30)\) = tau\(sqrt(5)\) tau\(sqrt(3)\) tau\(sqrt(2)\) = sqrt(30) in M^(ideal(sigma, tau)) = QQ$: contradiction. - So $sqrt(5) in.not M$, so $[L: QQ] = [L: M][M: QQ] = 8$. The $8$ elements in $Gal(L\/QQ)$ are determined by choices of $sqrt(a) |-> plus.minus sqrt(a)$ where $a in {2, 3, 5}$. - $Gal(L\/QQ) = ideal(sigma_1, sigma_2, sigma_3) tilde.equiv ZZ\/2 times ZZ\/2 times ZZ\/2$ where $sigma_1 \(sqrt(2)\) = -sqrt(2)$, $sigma_2 \(sqrt(3)\) = -sqrt(3)$, $sigma_1 \(sqrt(5)\) = -sqrt(5)$ and the $sigma_i$ fix all other square roots. - More generally, write $sigma\(sqrt(5)\) = (-1)^j sqrt(5)$, $tau\(sqrt(5)\) = (-1)^k sqrt(5)$, $j, k in {0, 1}$. Define $m = 2^j 3^k$, then $sigma\(sqrt(m)\) = (-1)^j sqrt(m) => sigma\(sqrt(5 m)\) = sqrt(5m)$ and $tau\(sqrt(m)\) = (-1)^k sqrt(m) => tau\(sqrt(5m)\) = sqrt(5m)$, so $sqrt(5 m) in M^ideal(sigma, tau) = QQ$: contradiction. ] #example(name: "cubic extension and its normal closure")[ - Let $L = QQ(theta)$, $theta^3 - 2 = 0$. $L\/QQ$ isn't Galois since not normal. Take the normal closure $N = QQ(theta, omega) = QQ\(theta, sqrt(-3)\)$. - Let $M = QQ(omega)$ so $[M: QQ] = 2$, $[L: QQ] = 3$ and $[N: QQ] = 6$. Let $G = Gal(N\/QQ)$. - Since $|G| = [N: QQ] = 6$, $G tilde.equiv ZZ\/6$ or $G tilde.equiv D_3 tilde.equiv S_3$. - $G$ contains $Gal(N\/L)$. Since $N = L(omega)$, $ Gal(N\/L) = {id, tau} = ideal(tau) tilde.equiv ZZ\/2 $ where $tau\(sqrt(-3)\) = -sqrt(-3)$ (i.e. $tau(w) = omega^2$) and $tau(theta) = theta$ as $theta in L$. - $G$ contains $H = Gal(N\/M)$. $N = M(theta)$, $|H| = [N: M] = 3$ so $Gal(N\/M)$ is cyclic so $ H = {id, sigma, sigma^2} = ideal(sigma) tilde.equiv ZZ\/3 $ where $sigma(theta) = omega theta$, also $sigma(omega) = omega$ as $omega in M$ and $sigma^2 (theta) = omega^2 theta$, so $H$ permutes the three roots of $x^3 - 2$. - $tau in.not H$ so $H = {id, sigma, sigma^2}$ and $tau H = {tau, tau sigma, tau sigma^2}$ are disjoint cosets. So $G = H union tau H = ideal(tau, sigma)$ so $|G| = 6$. $tau^2 = sigma^3 = id$ and $sigma tau = tau sigma^2$. So $G tilde.equiv S_3 tilde.equiv D_3$. - $G$ has one subgroup of order $3$, $H = ideal(sigma)$. Fixed field is $N^H = M$. $H$ is only proper normal subgroup of $G$. Correspondingly, $M$ is only normal extension of $Q$ in $N$. - There are $3$ order $2$ subgroups: $ideal(tau)$, $ideal(tau sigma)$, $ideal(tau sigma^2)$. $N^ideal(tau) = QQ(theta) = L$, $N^ideal(tau sigma) = QQ(omega theta) = sigma(L)$, $N^ideal(tau sigma^2) = QQ(omega^2 theta) = sigma^2 (L)$. ] #example[ Show $cbrt(3) in.not QQ\(cbrt(2)\)$. - Assume $cbrt(3) in QQ\(cbrt(2)\)$. Then $cbrt(3) in N = QQ\(omega, cbrt(2)\)$, the normal closure. - As above, let $sigma in Gal(N\/QQ)$, $sigma\(cbrt(2)\) = omega cbrt(2)$ and $N^ideal(sigma) = QQ(omega)$. Also, $ sigma\(cbrt(3)\)^3 = sigma(3) = 3 ==> sigma\(cbrt(3)\) in \{cbrt(3), omega cbrt(3), omega^2 cbrt(3)\} $ - If $sigma\(cbrt(3)\) = cbrt(3)$, then $cbrt(3) in N^ideal(sigma) = QQ(omega)$, so $QQ\(cbrt(3)\) subset.eq QQ(omega)$: contradiction. - If $sigma\(cbrt(3)\) = omega cbrt(3)$, then $sigma\(cbrt(3)\/cbrt(2)\) = cbrt(3)\/cbrt(2)$ hence $cbrt(3\/2) in N^ideal(sigma) = QQ(omega)$, so $QQ\(cbrt(3\/2)\) = QQ\(cbrt(12)\) subset.eq QQ(omega)$: contradiction. - If $sigma\(cbrt(3)\) = omega^2 cbrt(3)$, $QQ\(cbrt(3\/4)\) = QQ\(cbrt(6)\) subset.eq QQ(omega)$: contradiction. ] #remark[ In the above example, $N = QQ(theta_1, theta_2, theta_3) = QQ\(cbrt(2), omega\)$ where $theta_i$ are the roots of $x^3 - 2$. Plotting these roots on Argand diagram gives the symmetry group $S_3 tilde.equiv D_3$ of an equilateral triangle. $tau$ reflects the $theta_i$ (complex conjugation), $sigma$ rotates the roots (but *doesn't* rotate all of $N$, as it fixes $QQ$). For $g in G$, $g(theta_j) = theta_(pi(j))$ where $pi$ is permutation of ${1, 2, 3}$. So there is a group homomorphism $phi: G -> S_3$, $phi(g) = pi$. $ker(phi) = {id}$, so $phi$ is injective and also surjective, since $|G| = |S_3| = 6$, so $phi$ is isomorphism. ] #definition[ For $f(x) in K[x]$, $deg(f) = n >= 1$, with $n$ distinct roots, the *Galois group* of $f(x)$, $G_f$, is Galois group of splitting field of $f(x)$ over $K$ (provided it is separable). ] #remark[ Elements of $G_f$ permute roots of $f$, so $G_f$ is subgroup of $S_n$. If $f(x)$ irreducible over $K$, then $G_f$ is *transitive* subgroup, i.e. given $2$ roots $alpha, beta$ of $f$, there is a $g in G_f$ with $g(alpha) = beta$. This gives a general pattern $ "polynomial" --> "field extension" --> "permutation group" $ ] #example[ Consider $QQ subset L = QQ(theta) subset N = QQ(theta, i)$ where $theta = root(4, 2)$. $N$ is normal closure of $QQ(theta)$, $[N: QQ] = 8$ so $|Gal(N\/QQ)| = 8$. - Define $sigma(theta) = i theta$, $sigma(i) = i$, $tau(theta) = theta$, $tau(i) = -i$. Then $tau^2 = sigma^4 = id$. We have $ #table( columns: (auto, auto, auto, auto, auto, auto, auto, auto, auto), inset: 10pt, align: horizon, [], $id$, $sigma$, $sigma^2$, $sigma^3$, $tau$, $tau sigma$, $tau sigma^2$, $tau sigma^3$, $theta$, $theta$, $i theta$, $-theta$, $-i theta$, $theta$, $-i theta$, $-theta$, $i theta$, $i$, $i$, $i$, $i$, $i$, $-i$, $-i$, $-i$, $-i$ ) $ so $G = Gal(N\/QQ) = angle.l sigma, tau: sigma^4 = tau^2 = id, sigma tau = tau sigma^3 angle.r tilde.equiv D_4$. - Order $2$ subgroups are $ideal(tau)$, $ideal(tau sigma)$, $ideal(tau sigma^2)$, $ideal(tau sigma^3)$, $ideal(sigma^2)$. - Order $4$ subgroups are $ideal(sigma^2, tau) tilde.equiv (ZZ\/2)^2$, $ideal(sigma) tilde.equiv ZZ\/4$, $ideal(sigma^2, tau sigma) tilde.equiv (ZZ\/2)^2$. - Respectively, intermediate field extensions of degree $4$ are $QQ\(root(4, 2)\)$, $QQ\(i root(4, 2)\)$, $QQ\(sqrt(2), i\)$, $QQ\((1 - i) root(4, 2)\)$, $QQ\((1 + i) root(4, 2)\)$. - Respectively, intermediate field extensions of degree $2$ are $QQ\(sqrt(2)\)$, $QQ(i)$, $QQ\(i sqrt(2)\)$. ] = Cyclotomic field extensions == Roots of unity #definition[ $zeta in K^*$ is *$n$-th primitive root of unity* if $zeta^n = 1$ and $forall 0 < m < n$, $zeta^m != 1$, i.e. order of $zeta$ in $K^*$ is $n$. ] #example[ - $zeta$ is primitive $1$-st root of unity iff $zeta = 1$. - $-1$ is primitive $2$-nd root of unity iff $char(K) != 2$. - If $char(K) = p$ prime, then $K$ contains no $p$-th primitive roots of unity (since $zeta^p = 1 <==> (zeta - 1)^p = 0 <==> zeta = 1$). - If $K = CC$, $exp(2pi i\/n)$ is $n$-th primitive root of unity. ] #proposition[ Let $zeta in K^*$ primitive $n$-th root of unity, let $d = gcd(m, n)$. Then $zeta^m$ is primitive $(n\/d)$-th root of unity. ] #corollary[ Let $zeta in K^*$ primitive $n$-th root of unity. - $zeta^m = 1 <==> m equiv 0 mod n$. - $zeta^m$ is primitive $n$-th root of unity iff $gcd(m, n) = 1$. ] #definition[ Let $mu(K)$ denote subgroup of all roots of unity in $K^*$. ] #theorem[ Let $K$ field, $H$ finite subgroup of $K^*$, then $H$ is cyclic. ] #remark[ This implies that any finite field $FF_q$ can be written $FF_q = FF_(p^n) = FF_p (alpha)$ where $alpha$ is generator of $FF_q^times$. ] #corollary[ Let $K$ field, $n in NN$ be largest such that $K$ contains primitive $n$-th root of unity $zeta$. Then $mu(K)$ is cyclic subgroup in $K^*$ generated by $zeta$. ] == $n$-th cyclotomic field extensions #notation[ Let $zeta_n = exp(2pi i \/ n) in CC$. ] #definition[ $QQ\(zeta_n\)\/QQ$ is *$n$-th cyclotomic field extension*. ] #proposition[ $QQ\(zeta_n\)\/QQ$ is Galois. ] #definition[ $Phi_n (x) := product_(a in A) (x - zeta_n^a)$ where $A = {a in NN: 0 < a < n, gcd(a, n) = 1}$. ] #proposition[ $Phi_n (x) in QQ[x]$ is irreducible and so is minimal polynomial of a primitive $n$-th root of unity over $QQ$. In particular, $[QQ\(zeta_n\): QQ] = phi(n)$, where $phi(n) = |(ZZ\/n)^times|$ is Euler function. ] #proposition[ Properties of $phi$ function: - For prime $p$, $phi(p) = p - 1$. - For prime $p$, $phi(p^k) = p^k - p^(k - 1)$. - If $gcd(n, m) = 1$, then $phi(n m) = phi(n) phi(m)$. - If $n = product_(i = 1)^r p_i^(k_i)$ is prime factorisation of $n$, then $ phi(n) = n product_(i = 1)^r (1 - 1/p_i) $ ] #proposition[ $forall n in NN, x^n - 1 = product_(n_1 divides n) Phi_(n_1)(x)$. ] #example[ - $Phi_1 (x) = x - 1$. - $Phi_1 (x) Phi_2 (x) = x^2 - 1 ==> Phi_2 (x) = x + 1$. - $Phi_1 (x) Phi_3 (x) = x^3 - 1 ==> Phi_3 (x) = x^2 + x + 1$. ] #proposition[ - For $p$ prime, $Phi_p (x) = x^(p - 1) + dots.h.c + x + 1$. - For $p$ prime, $Phi_(p^k)(x) = Phi_p \(x^(p^(k - 1))\)$. - For every $n in NN$, $Phi_n (x)$ has integer coefficients. ] == Galois properties of cyclotomic extensions #theorem[ $Gal(QQ\(zeta_n\)\/QQ) tilde.equiv (ZZ\/n)^times$. ] #remark[ To compute $(ZZ\/n)^times$, note that for $m, n$ coprime, $(ZZ\/m n)^times tilde.equiv (ZZ\/m)^times times (ZZ\/n)^times$ and - If $p != 2$ prime, then $(ZZ\/p^r)^times$ is cyclic of order $phi(p^r)$. - $(ZZ\/4)^times tilde.equiv ZZ\/2$ and for $r >= 3$, $(ZZ\/2^r)^times tilde.equiv ZZ\/2 times ZZ\/2^(r - 2)$. ] #corollary[ $Gal(QQ\(zeta_n\)\/QQ)$ is abelian so every subgroup is normal, so any subfield of $QQ\(zeta_n\)$ is Galois over $QQ$. ] #corollary[ For $p$ prime, $G = Gal(QQ\(zeta_p\)\/QQ) tilde.equiv (ZZ\/p)^times tilde.equiv ZZ\/(p - 1)$. In particular, for $d | (p - 1)$, $QQ\(zeta_p\)$ contains exactly one subfield of degree $d$ and there are no other subfields. ] #remark[ For $d = 2$ in above corollary, $QQ\(zeta_p\)$ contains unique quadratic subfield $QQ\(sqrt(D_p)\)$, where $D_p = (-1)^((p - 1)\/2) p$ ] #example[ $Gal(QQ\(zeta_n\)\/QQ)$ not always cyclic, e.g. $Gal(QQ(zeta_8)\/QQ) tilde.equiv ZZ\/2 times ZZ\/2$. ] #proposition[ - If $n$ odd, $mu(QQ\(zeta_n\))$ is cyclic of order $2n$ and is generated by $-zeta_n$. - If $n$ even, $mu(QQ\(zeta_n\))$ is cyclic of order $n$ and is generated by $zeta_n$. - If $gcd(m, n) = d$, then $QQ(zeta_m, zeta_n) = QQ(zeta_(m n \/ d))$. ] == Special properties of $QQ\(zeta_p\)$, where $p > 2$ is prime #example[ $Gal(QQ(zeta_5)\/QQ) tilde.equiv (ZZ\/5)^times$ has generator $tau: zeta_5 |-> zeta_5^2$. $QQ$-basis ${1, zeta_5, zeta_5^2, zeta_5^3}$ is not invariant under action of $tau$ or any power of $tau$ (since $tau(zeta_5^2) = zeta_5^4$) but ${zeta, zeta_5^2, zeta_5^3, zeta_5^4}$ is invariant. The same holds for general $p > 2$ prime. For $alpha_i in QQ$, $alpha_1 zeta_p + dots.h.c + alpha_(p - 1) zeta_p^(p - 1) in QQ$ iff $alpha_1 = dots.h.c = alpha_(p - 1)$. ] #example[ If $x in QQ\(zeta_p\)$, $[QQ(x): QQ] = |\{sigma(x): sigma in Gal\(QQ\(zeta_p\)\/QQ\)\}|$ In particular, if $tau$ is generator of $G = Gal\(QQ\(zeta_p\)\/QQ\)$ and $x = alpha_1 zeta_p + dots.h.c + alpha_(p - 1) zeta_p^(p - 1)$ then set of all conjugates of $x$ is equal to (note not all elements are distinct) $ {tau^a (x): a in [p - 1]} = {sum_(i = 1)^(p - 1) alpha_i zeta_p^(a i): a in [p - 1]} $ ] #example[ Let $x = zeta_5 + zeta_5^4$, $tau: zeta_5 |-> zeta_5^2$ is a generator of $Gal(QQ\(zeta_5\)\/QQ)$. $tau(x) = zeta_5^2 + zeta_5^3 != x$ but $tau^2 (x) = x$, so $[QQ(x): QQ] = 2$, i.e. $QQ(zeta_5 + zeta_5^4)$ is unique quadratic subfield in $QQ(zeta_5)$. ] #definition[ Let $x in QQ\(zeta_p\)$, let minimal polynomial of $x$ over $QQ$ be $m(t) = (t - x^((1))) dots.h.c (t - x^((d)))$. *Conjugates* of $x$ over $QQ$ are $x^((1)) = x, ..., x^((d))$. ] #example[ Minimal polynomial of $zeta_5 + zeta_5^4 = 2 cos(2pi\/5)$ over $QQ$ is $m(x) = (x - zeta_5 - zeta_5^4)(x - zeta_5^2 - zeta_5^3) = x^2 + x - 1$, with roots $(-1 plus.minus sqrt(5))\/2$. So $cos(2pi\/5) = (-1 + sqrt(5))\/4$, and unique quadratic subfield of $QQ(zeta_5)$ over $QQ$ is $QQ\(sqrt(5)\)$. ] #example[ Let $tau in G$ be generator of $G = Gal(QQ\(zeta_p\)\/QQ)$, i.e. $tau(zeta_p) = zeta_p^a$, $a mod p$ generates $(ZZ\/p)^times$. Let $ Theta_p = zeta_p - tau(zeta_p) + tau^2 (zeta_p) - dots.h.c + tau^(p - 3) (zeta_p) - tau^(p - 2) (zeta_p) $ $Theta_p$ behaves like $sqrt(D_p)$: $tau\(Theta_p\) = -Theta_p$, $tau^2 \(Theta_p\) = Theta_p$. So $Theta_p in QQ\(zeta_p\)^ideal(tau^2)$. Also, $tau\(Theta_p^2\) = Theta_p^2$ so $Theta_p^2 in QQ\(zeta_p\)^ideal(tau) = QQ$. In fact, $Theta_p^2 = D_p$. Therefore $ Theta_p^2 = A + B (zeta_p + dots.h.c + zeta_p^(p - 1)) = A - B $ So when computing $Theta_p^2$, only need to consider coefficients for $1$ and $zeta_p$. ] = Cyclic field extensions == Cyclic extensions of degree $2$ #example[ Let $L\/K$ cyclic of degree $2$, so $Gal(L\/K) = {e, tau}$, $tau^2 = e$. Let $theta in L - K$, then $tau(theta) != theta$ (as otherwise $theta in L^ideal(tau) = K$). Let $theta_1 = tau(theta) - theta$, so $tau(theta_1) = tau^2 (theta) - tau(theta) = -theta_1$. If $char(K) != 2$, then $theta_1 != -theta_1$ and so $theta_1 in.not K$, $L = K(theta_1)$. $theta_1$ is "better" than $theta$, since $tau(theta_1) = -theta_1$. Now if $a = theta_1^2$, then $tau(a) = a$, so $L = K\(sqrt(a)\)$. ] #theorem[ If $char(K) != 2$ and $L\/K$ is cyclic quadratic extension, then $ exists a in K^times - K^times^2: quad L = K\(sqrt(a)\) $ ] #definition[ $a_1, ..., a_n$ are *independent modulo $K^times^2$ (independent modulo squares)* if $ a_1^(epsilon_1) dots.h.c a_n^(epsilon_n) in K^times^2 <==> "all" epsilon_i "are even" $ ] #proposition[ If $char(K) != 2$: - $K\(sqrt(a_1)\) = K\(sqrt(a_2)\) <==> a_1 equiv a_2 mod K^times^2$, i.e. $a_1 = a_2 dot.op b^2$, $b in K^times$. - If $a_1, ..., a_n in K^times$ are independent modulo $K^times^2$ then $K\(sqrt(a_1), ..., sqrt(a_n)\)$ has degree $2^n$ over $K$ with Galois group $tilde.equiv (ZZ\/2)^n$. - If $L\/K$ Galois with Galois group $(ZZ\/2)^n$, then $ exists a_1, ..., a_n in K^times: quad L = K\(sqrt(a_1), ..., sqrt(a_n)\) $ ] #remark[ Let $char(K) = 2$, then $forall a in K^times$, $L = K\(sqrt(a)\)$ is normal but not separable (since minimal polynomial of e.g. $sqrt(a)$ is $x^2 - a = (x + sqrt(a))(x - sqrt(a)) = (x - sqrt(a))^2$ so has repeated roots). ] == Cyclic extensions of degree $n$ (the Kummer theory) #definition[ $L\/K$ is *cyclic of degree $n$* if it is Galois and $Gal(L\/K)$ is cyclic of order $n$. ] #theorem[ If $K$ contains primitive $n$-th root of unity and for all divisors $d > 1$ of $n$, $a in K^times$ is not $d$-th power in $K$, then $L = K\(root(n, a)\)$ is cyclic extension of $K$ of degree $n$. In particular, $x^n - a in K[x]$ is irreducible. ] #proposition[ If $zeta_p in K$, $a in K^times - K^times^p$, then $K(root(p, a))\/K$ is cyclic of degree $p$. In particular, $x^p - a in K[x]$ is irreducible. ] #theorem[ Let $K$ contain primitive $n$-th root of unity $zeta_n$, $L\/K$ is cyclic extension of degree $n$, $Gal(L\/K) = ideal(sigma)$. Then $ exists a in K^times: L = K\(root(n, a)\) $ Such an $a$ is given by $theta_b^n$ for some $b in L$, where $ theta_b = b + zeta_n^(-1) sigma(b) + dots.h.c + zeta_n^(-(n - 1)) sigma^(n - 1)(b) $ is *Lagrange resolvent* for $b$, i.e. $L = K(theta_b)$. ]<lagrange-resolvent> #lemma(name: "Artin's lemma")[ There exists $b in L$ such that $theta_b != 0$. ] = Finite fields == Existence and uniqueness #lemma[ Let $K$ finite field, then $K$ is field extension of $FF_p$ for some prime $p$ and $|K| = p^n$ where $n = \[K: FF_p\]$. ] #theorem[ Let $p$ prime. Then $forall n in NN$, there is field $K$ with $|K| = p^n$. ] #theorem[ Let $K$ finite field with $|K| = q = p^n$. Then - $forall alpha in K, alpha^q = alpha$. - $x^q - x = product_(alpha in K) (x - alpha)$ - $K$ is splitting field of $x^q - x$ over $FF_p$. ] #corollary[ If $K_1$, $K_2$ finite fields, $|K_1| = |K_2|$, then $K_1 tilde.equiv K_2$. ] #definition[ Let $q = p^n$, then $FF_q$ is the unique (up to isomorphism) field containing $q$ elements. ] #definition[ For $q = p^n$, the *Frobenius automorphism* is $ sigma: FF_q -> FF_q, quad sigma(alpha) = alpha^p $ which is an $FF_p$-automorphism by Fermat's little theorem. ] #theorem[ Let $q = p^n$, $p$ prime. - $FF_q \/ FF_p$ is Galois of degree $n$. - Frobenius automorphism generates $Gal(FF_q \/ FF_p)$ and there is group isomorphism $ Gal(FF_q \/ FF_p) <-> ZZ\/n, quad sigma <--> 1 mod n $ ] == Counting irreducible polynomials over finite fields #notation[ Let $"Irr"_(FF_p) (m)$ denote set of all irreducible polynomials in $FF_p [x]$ of degree $m$. Let $N_p (m) = |"Irr"_(FF_p)(m)|$. ] #theorem[ Let $q = p^m$, then $m N_p (m) = |\{alpha in FF_q: FF_p (alpha) = FF_q\}|$. ] #remark[ To use above theorem, note that $FF_p (alpha) != FF_(p^m)$ iff $alpha$ belongs to proper subfield of $FF_(p^m)$. ] #example[ - If $m$ is prime, then $FF_(p^m)$ has only one proper subfield $FF_p$, so $m N_p (m) = |FF_(p^m)| - |FF_p| = p^m - p$. - The proper subfields of $FF_(p^4)$ are $FF_p$ and $FF_(p^2)$, but $FF_p subset FF_(p^2)$, so $4 N_p (4) = |FF_(p^4)| - |FF_(p^2)|$. - $FF_p (alpha) != FF_(p^6)$ iff $alpha in FF_(p^3) union FF_(p^2)$. Since $FF_(p^3) sect FF_(p^2) = FF_p$, we have $6 N_p (6) = |FF_(p^6)| - |FF_(p^3)| - |FF_(p^2)| + |FF_p| = p^6 - p^3 - p^2 + p$. ] #proposition[ We have $ p^n = sum_(m | n) m N_p (m) $ which we can use recursively to compute any $N_p (m)$. ] #example[ We construct $L = FF_(3^16)$ by finding irreducible polynomial of degree $16$ in $FF_3 [x]$. - $FF_9 = FF_3 (theta)$ where $theta^2 + 1 = 0$, $FF_9 = {a + b theta: a, b in FF_3}$. $K := FF_9$ contains primitive $8$-th root of unity since $FF_9^times tilde.equiv ZZ\/8$. - $L\/K$ is cyclic extension of degree $8$, so by Kummer theory there exists $alpha in K$ such that $L = K\(root(8, alpha)\)$. $alpha$ must be element that is not square or fourth power in $FF_9$, so we can look for elements that have order $8$. - $alpha = theta$ doesn't work since $theta^2 = -1 ==> theta^4 = 1$. $alpha = 1 + theta$ works since $ (1 + theta)^2 = theta^2 + theta + 1 = -theta, quad (1 + theta)^4 = theta^2 = -1, (1 + theta)^8 = 1 $ so $alpha = 1 + theta$ has order $8$ in $FF_9$. - So $L = K\(root(8, a)\) = FF_9 \(root(8, 1 + theta)\) = FF_3 \(theta, root(8, 1 + theta)\) = FF_3 (eta)$ where $eta^8 = 1 + theta$. Now $[L: FF_3] = 16$ by tower law, so $L = FF_(3^16)$ by uniqueness of finite fields. - $eta^8 = 1 + theta ==> (eta^8 - 1)^2 = theta^2 = -1 ==> eta^16 + eta^8 + 2 = 0$ so $f(x) = x^16 + x^8 + 2 in FF_3 [x]$ is irreducible. ] = Galois groups of polynomials == Symmetric functions #definition[ Define action of $S_n$ on $L = k(x_1, ..., x_n)$ by $tau: x_j |-> x_(pi(j))$ where $pi in S_n$, which gives $k$-automorphism $ tau: L -> L, quad f(x_1, ..., x_n) / g(x_1, ..., x_n) |-> (f\(x_(pi(1)), ..., x_(pi(n))\)) / (g\(x_(pi(1)), ..., x_(pi(n))\)) $ The *symmetric functions* in $L$ are elements of fixed field $L^(S_n)$. ] #definition[ The *elementary symmetric polynomials* $e_r in L$ for $r in [n]$ are $ e_1 & = sum_(1 <= i <= n) x_i \ e_2 & = sum_(1 <= i < j <= n) x_i x_j \ & dots.v \ e_r & = sum_(1 <= i_1 < dots.h.c < i_r <= n) x_(i_1) dots.h.c x_(i_r) \ & dots.v \ e_n & = x_1 dots.h.c x_n $ Define $K = k(e_1, ..., e_n)$. ] #theorem[ $K = L^(S_n)$ and $L\/K$ is Galois with $Gal(L\/K) tilde.equiv S_n$. ]<symmetric-polynomial-extension-galois-group-is-symmetric-group> #proof[ - Note that $f(x) = (x - x_1) dots.h.c (x - x_n) = x^n - e_1 x^(n - 1) + dots.h.c + (-1)^n e_n$. - Show $L$ splitting field of $f(x)$ over $K$ and $[L: K] <= n!$. - Show $[L: K] >= n!$. ] #remark[ Every finite group $G$ is subgroup of $S_n$ for some $n$, so there is always Galois extension with Galois group $G$: let $L = k(x_1, ... x_n)$, let $G subset.eq S_n$ act on $L$ as above, then $Gal(L\/L^G) = G$. ] #definition[ For $f(x) in K[x]$, *Galois group* of $f(x)$, $G_f$, is Galois group of splitting field of $f(x)$ over $K$ (provided this extension is separable). If $deg(f) = n$, $G_f$ acts by permuting roots $theta_1, ..., theta_n$ of $f$, so is subgroup of $S_n$. There can be non-trivial relationships between roots, so $G_f$ may be proper subgroup. ] #corollary[ Any symmetric polynomial in $k[x_1, ..., x_n]$ can be expressed as polynomial in elementary symmetric polynomials, i.e. $ k[x_1, ..., x_n]^(S_n) = k[e_1, ..., e_n] $ where LHS is set of symmetric polynomials, RHS is set of polynomials in elementary symmetric polynomials. ] #example[ - When $n = 2$, $x_1^2 + x_2^2 = e_1^2 - 2e_2$ and $x_1^3 + x_2^3 = e_1^3 - 3e_1 e_2$. - When $n = 3$, $x_1^2 x_2 + x_1 x_2^2 + x_2^2 x_3 + x_2 x_3^2 + x_3^2 x_1 + x_3 x_1^2 = e_1 e_2 - 3e_3$. ] #definition[ *Lexicographic ordering of monomials*, $gtlex$ (or $scripts(gt.curly)_L$), is $ x_1^(a_1) dots.h.c x_n^(a_n) gtlex x_1^(b_1) dots.h.c x_n^(b_n) $ iff $exists 0 <= j <= n - 1$ such that $a_1 = b_1, ..., a_j = b_j$ and $a_(j + 1) > b_(j + 1)$. ] #example[ $x_1^2 x_2^3 x_3 gtlex x_1^2 x_2^2 x_3^4$. ] #definition[ *Leading term* of $f(x_1, ..., x_n) in k[x_1, ..., x_n]$ is largest monomial $c x_1^(a_1) dots.h.c x_n^(a_n)$ with $c != 0$, $a_i != 0$ for some $i$, appearing in $f$ with respect to lexicographic ordering. ] #note[ If $f$ is symmetric, then $a_1 >= dots.h.c >= a_n$. ] #algorithm[ Given $f(x_1, ..., x_n) in k[x_1, ..., x_n]^(S_n)$, express $f$ as polynomial in elementary symmetric polynomials: + Find leading term $c x_1^(a_1) dots.h.c x_n^(a_n)$ of $f$, compute $ f_1 = f - c e_1^(a_1 - a_2) dots.h.c e_(n - 1)^(a_(n - 1) - a_n) e_n^(a_n) $ Note leading term of $c e_1^(a_1 - a_2) dots.h.c e_(n - 1)^(a_(n - 1) - a_n) e_n^(a_n)$ is also $c x_1^(a_1) dots.h.c x_n^(a_n)$ so leading term of $f_1$ is strictly smaller than leading term of $f$. Also, $f_1$ is symmetric. + If $f_1 != 0$, apply step $1$ to get $f_2$, $f_3$, .... Since leading term of $f_1, f_2, ...$ is strictly decreasing, eventually $f_i = 0$. ] #example[ Express $f(x_1, x_2) = x_1^3 + x_2^3$ in elementary symmetric polynomials: - Leading term of $f$ is $x_1^3 = x_1^3 x_2^0$, so $ f_1 = f - e_1^(3 - 0) e_2^0 = -3x_1^2 x_2 - 3x_1 x_2^2 $ - Leading term of $f_1$ is $-3x_1^2 x_2$, so $ f_2 = f_1 - (-3) e_1^(2 - 1) e_2^1 = -3x_1^2 x_2 - 3x_1 x_2^2 + 3(x_1 + x_2) x_1 x_2 = 0 $ - So $f_1 = f_2 + (-3) e_1^(2 - 1) e_2^1 = -3e_1 e_2$ and $f = e_1^3 + f_1 = e_1^3 - 3e_1 e_2$. ] #example[ - Let $theta_1 = 1/3(x_1 + omega x_2 + omega^2 x_3)$, $theta_2 = 1/3(x_1 + omega^2 x_2 + omega x_3)$, where $omega = zeta_3$. - Let $sigma = (1 thick 2 thick 3) in S_3$, then $sigma (theta_1) = omega^2 theta_1$, $sigma (theta_2) = omega theta_2$, hence $ sigma(theta_1^3 + theta_2^3) = omega^6 theta_1^3 + omega^3 theta_2^3 = theta_1^3 + theta_2^3 $ - Let $tau = (2 thick 3) in S_3$, then $tau(theta_1) = theta_2$, $tau(theta_2) = theta_1$ so $tau(theta_1^3 + theta_2^3) = theta_1^3 + theta_2^3$. - Since $S_3 = ideal(sigma, tau)$, $f(x_1, x_2, x_3) = 27(theta_1^3 + theta_2^3) in QQ[x_1, x_2, x_3]^(S_3)$. Applying the algorithm: - $f_1 = f - 2 e_1^3 = 9 (x_1^2 x_2 + dots.h.c)$. - $f_2 = f_1 - (-9) e_1 e_2 = 27 x_1 x_2 x_3$. - $f_3 = f_2 - 27 e_3 = 0$. - So $f = 2 e_1^3 - 9 e_1 e_2 + 27 e_3$. - By a similar process, $9 theta_1 theta_2 = e_1^2 - 3 e_2$. ]<example:theta_i-for-cubic> == Galois theory for cubic polynomials #example(name: "Solving quadratic")[ Let $char(k) != 2$. General quadratic polynomial can be written as $ f(x) = x^2 - e_1 x + e_2 = (x - x_1)(x - x_2) in K[x] $ where $e_1 = x_1 + x_2, e_2 = x_1 x_2 in K = k(e_1, e_2)$. Let $L = k(x_1, x_2) = K(x_1)$, then $L\/K$ is Galois and $Gal(L\/K) = {id, sigma} tilde.equiv S_2 tilde.equiv ZZ\/2$ where $sigma(x_1) = x_2$, $sigma(x_2) = x_1$. Since $L\/K$ cyclic and $zeta_2 = -1 in K$, by @lagrange-resolvent, Lagrange resolvent of $x_1$ is $ theta = theta_(x_1) = x_1 + zeta_2^(-1) sigma(x_1) = x_1 - x_2 $ So $sigma(theta) = -theta$ and $theta^2 = e_1^2 - 4e_2$. $Delta = theta^2$ is *discriminant* of $f(x)$. So we have $x_1 = \(e_1 + sqrt(Delta)\)\/2$, $x_2 = \(e_1 - sqrt(Delta)\)\/2$. If $f(x)$ is irreducible, it has distinct roots, and so Galois group $G_f tilde.equiv ZZ\/2$. ] #example(name: "Solving cubic")[ - Let $char(k) != 2, 3$, let $ f(x) = x^3 - e_1 x^2 + e_2 x - e_3 = (x - x_1)(x - x_2)(x - x_3) in K[x] $ where $e_1 = x_1 + x_2 + x_3$, $e_2 = x_1 x_2 + x_1 x_3 + x_2 x_3$, $e_3 = x_1 x_2 x_3 in K = k(e_1, e_2, e_3) subset L = K(x_1, x_2, x_3)$. - By @symmetric-polynomial-extension-galois-group-is-symmetric-group, $Gal(L\/K) = S_3$ with normal subgroup $A_3 tilde.equiv ZZ\/3$. We have tower $K subset M = L^(A_3) subset L$. So $Gal(L\/M) tilde.equiv A_3 tilde.equiv ZZ\/3$, $Gal(M\/K) tilde.equiv S_3 \/ A_3 tilde.equiv ZZ\/2$. - Assume $k$ contains primitive $3$rd root of unity $omega$, so $w^2$ is also primitive $3$rd root of unity. Define $ theta_1 & = 1/3(x_1 + omega x_2 + omega^2 x_3), quad t_1 = theta_1^3, \ theta_2 & = 1/3(x_1 + omega^2 x_2 + omega x_3), quad t_2 = theta_2^3 $ then $t_1, t_2 in M$ and $L = M(theta_1) = M(theta_2)$. By @example:theta_i-for-cubic, $27(theta_1^3 + theta_2^3) = 2e_1^3 - 9e_1 e_2 + 27e_3$, $9 theta_1 theta_2 = e_1^2 - 3e_2$, so $t_1, t_2$ are roots of *quadratic resolvent* of $f(x)$: $ (t - t_1)(t - t_2) = t^2 - ((2e_1^3 - 9e_1 e_2 + 27e_3)/27) t + ((e_1^2 - 3e_2)/9)^3 $ - To find roots $x_1, x_2, x_3$ of $f$: - Solve quadratic resolvent to find $t_1, t_2$. - Choose $theta_1 = cbrt(t_1)$, find $theta_2$ from $9 theta_1 theta_2 = e_1^2 - 3e_2$. - Solve the linear system $ cases(x_1 + x_2 + x_3 = e_1, x_1 + omega x_2 + omega^2 x_3 = 3 theta_1, x_1 + omega^2 x_2 + omega x_3 = 3 theta_2) quad ==> quad cases(x_1 = e_1\/3 + theta_1 + theta_2, x_2 = e_1\/3 + omega^2 theta_1 + omega theta_2, x_3 = e_1\/3 + omega theta_1 + omega^2 theta_2) $ ] #remark[ To solve general cubic $f(x) = x^3 + a x^2 + b x + c$, first perform shift: $ f(x - a\/3) = x^3 + p x + q $ then quadratic resolvent is (_memorise_) *$ t^2 + q t - p^3 / 27 $* with roots $t_1 = theta_1^3$, $t_2 = theta_2^3$, choose $theta_1, theta_2$ such that $theta_1 theta_2 = -p/3$, then roots of $f(x - a\/3)$ are $x_1 = theta_1 + theta_2$, $x_2 = omega^2 theta_1 + omega theta_2$, $omega theta_1 + omega^2 theta_2$. ] #example(name: "Galois groups of cubic polynomials")[ Let $char(K) != 2, 3$, $f(x) = x^3 + a x^2 + b x + c in K[x]$, let $L$ be splitting field for $f(x)$ over $K$, then $G_f = Gal(L\/K)$. Let $alpha_1, alpha_2, alpha_3$ be roots of $f(x)$ in $L$. - If $alpha_1, alpha_2, alpha_3 in K$, then $L = K$, $G_f = {id}$. - If $f(x) = (x - alpha_j) g(x)$ where $alpha_j in K$, $g(x) in K[x]$ irreducible quadratic, then $[L: K] = 2$, $G_f tilde.equiv ZZ\/2$. - If $f(x)$ irreducible in $K[x]$, then $K subset K(alpha_1) subset.eq K(alpha_1, alpha_2, alpha_3) = L$, then either $[L: K(alpha_1)] = 1$, so $[L: K] = 3$ and $G_f tilde.equiv A_3 tilde.equiv ZZ\/3$, or $[L: K(alpha_1)] = 2$, so $[L: K] = 6$ and $G_f tilde.equiv S_3$. ] #definition[ *Discriminant* of $f(x) = (x - alpha_1)(x - alpha_2)(x - alpha_3)$ is $Delta = delta^2$ where $ delta = (alpha_1 - alpha_2)(alpha_2 - alpha_3)(alpha_3 - alpha_1) $ Note $Delta != 0$ if $f$ has distinct roots. ] #note[ If $G_f tilde.equiv A_3$, then $G_f = ideal(tau)$ where $tau: alpha_1 |-> alpha_2$, $alpha_2 |-> alpha_3$, $alpha_3 |-> alpha_1$, then $tau(delta) = delta$ so $delta in L^(G_f) = K$ and $Delta in K^times^2$. But if $G_f tilde.equiv S_3$, then if $tau in A_3$, $tau(delta) = delta$ and if $tau in S_3 - A_3$, then $tau(delta) = -delta$ so $delta in.not K$ but $Delta in K$. ] #theorem[ Let $f(x) in K[x]$ irreducible, $deg(f) = 3$. Then - $G_f tilde.equiv A_3 <==> Delta in K^times^2$, - $G_f tilde.equiv S_3 <==> Delta in K^times - K^times^2$. ] #theorem[ Let $f(x) = x^3 + a x^2 + b x + c in K[x]$, then $ Delta = 18 a b c - 4a^3 c + a^2 b^2 - 4b^3 - 27c^2 $ For reduced cubic $f(x) = x^3 + p x + q$, (_memorise_) *$ Delta = -4p^3 - 27q^2 $* ] #note[ The reduced form of $f(x)$ has same discriminant as $f(x)$. ] == Galois theory for quartic polynomials #example[ Let $char(k) != 2, 3$, $K = k(e_1, e_2, e_3, e_4) subset.eq L = k(x_1, x_2, x_3, x_4)$, so $L$ is splitting field over $K$ of $f(x) = x^4 - e_1 x^3 + e_2 x^2 - e_3 x + x_4$ and $Gal(L\/K) tilde.equiv S_4$. ] #remark[ $S_4$ can be visualised as symmetries of regular tetrahedron with vertices labelled ${1, 2, 3, 4}$. Consider three pairs of opposite edges $ P_1 = {(1, 2), (3, 4)}, quad P_2 = {(1, 3), (2, 4)}, quad P_3 = {(1, 4), (2, 3)} $ Any permutation in $S_4$ of the four vertices permutes $P_1$, $P_2$, $P_3$, which gives map $pi: S_4 -> S_3$. - $pi$ is surjective group homomorphism. - $pi$ has kernel $ker(pi) = {id, (1 thick 2)(3 thick 4), (1 thick 3)(2 thick 4), (1 thick 4)(2 thick 3)} = V_4 tilde.equiv ZZ\/2 times ZZ\/2$. - $A_4 subset S_4$ is subgroup of even permutations (orientation-preserving symmetries). Restriction of $pi$ to $A_4$ gives another surjective homomorphism $A_4 -> A_3$ (and $pi^(-1) (A_3) = A_4$) also with kernel $V_4$. - $V_4$ is kernel so is normal subgroup of $S_4$ and of $A_4$. Note that $V_4$ is only subgroup of $A_4$ isomorphic to $ZZ\/2 times ZZ\/2$, but there are four subgroups of $S_4$, isomorphic to $ZZ\/2 times ZZ\/2$, with $V_4$ the only normal one. - This gives increasing sequence of subgroups in $S_4$ $ {id} subset ZZ\/2 subset V_4 subset A_4 subset S_4 $ and $V_4 tilde.equiv ZZ\/2 times ZZ\/2$, $A_4 \/ V_4 tilde.equiv A_3 tilde.equiv ZZ\/3$, $S_4 \/ A_4 tilde.equiv ZZ\/2$. - Each $G_i$ in this sequence is normal subgroup of $G_(i + 1)$ and $G_(i + 1)\/G_i$ is cyclic, meaning that $S_4$ is *solvable (soluble) group*. - We have tower $ K = L^(S_4) subset L^(V_4) subset L = L^({e}) $ By fundamental theorem, $Gal(L\/L^(V_4)) = V_4 tilde.equiv ZZ\/2 times ZZ\/2$, so $L\/L^(V_4)$ appears as biquadratic extension. - $V_4$ is normal in $S_4$ so by fundamental theorem, $Gal(L^(V_4)\/K) tilde.equiv S_4 \/ V_4 tilde.equiv S_3$ by first isomorphism theorem. Hence $L^(V_4)$ appears as splitting field of a cubic polynomial over $K$. ] #example(name: "Solving quartic equations")[ Define $ theta_1 & = 1/2 (x_1 + x_2 - x_3 - x_4), \ theta_2 & = 1/2 (x_1 - x_2 + x_3 - x_4), \ theta_3 & = 1/2 (x_1 - x_2 - x_3 + x_4) $ Then $forall j in [3], forall sigma in V_4$, $sigma (theta_j) = plus.minus theta_j$. The $theta_j$ arise from Lagrange resolvents for the three quadratic subextensions of $L^(V_4)$ in $L$. They behave like $sqrt(2)$, $sqrt(3)$, $sqrt(6)$ in $QQ\(sqrt(2), sqrt(3)\)$. Each $t_i = theta_i^2$ is fixed by $V_4$ and are permuted by $S_4 \/ V_4 tilde.equiv S_3$. They are roots of *cubic resolvent* of $f(x)$: $ (t - t_1)(t - t_2)(t - t_3) = t^3 + s_1 t^2 + s_2 t + s_3 $ which has coefficients in $\(L^(V_4)\)^(S_3) = L^(S_4) = K$. To find roots $x_1, x_2, x_3, x_4$ of $f(x)$: - Solve cubic resolvent to find $t_1$, $t_2$, $t_3$. - Set $theta_j = plus.minus sqrt(t_j)$ where signs are chosen so that $theta_1 theta_2 theta_3 = (e_1^3 - 4e_1 e_2 + 8 e_3)\/8$. - Solve the linear system $ cases(x_1 + x_2 + x_3 + x_4 & = e_1, x_1 + x_2 - x_3 + x_4 & = 2theta_1, x_1 - x_2 + x_3 - x_4 & = 2theta_2, x_1 - x_2 - x_3 + x_4 & = 2theta_3) quad ==> quad cases(x_1 & = e_1\/4 + (theta_1 + theta_2 + theta_3)\/2, x_2 & = e_1\/4 + (theta_1 - theta_2 - theta_3)\/4, x_3 & = e_1\/4 + (-theta_1 + theta_2 - theta_3)\/2, x_4 & = e_1\/4 + (-theta_1 - theta_2 + theta_3)\/2) $ ] #remark[ In practice, perform shift to kill $x^3$ coefficient to obtain *reduced quartic*: $ f(x - a\/4) = x^4 + p x^2 + q x + r $ - Cubic resolvent is _(memorise)_ *$ t^3 + 2 p t^2 + (p^2 - 4r)t - q^2 $* - Choose $theta_1, theta_2, theta_3$ such that _(memorise)_ *$ theta_1 theta_2 theta_3 = -q $* - Roots of $f(x - a\/4)$ are _(memorise)_ *$ x_1 & = 1/2 (theta_1 + theta_2 + theta_3), \ x_2 & = 1/2 (theta_1 - theta_2 - theta_3), \ x_3 & = 1/2 (-theta_1 + theta_2 - theta_3), \ x_4 & = 1/2 (-theta_1 - theta_2 + theta_3) $* - Recover roots of $f(x)$ by subtracting $a\/4$. ] #example[ Find all complex roots of $f(x) = x^4 + 6x^3 + 18x^2 + 30x + 25$. - Eliminate $x^3$ term: $ f(x - 6\/4) = x^4 + 9/2 x^2 + 3x + 85/16 $ - $p = 9\/2$, $q = 3$, $r = 85\/16$, so cubic resolvent is $ t^3 + 2p t^2 + (p^2 - 4r)t - q^2 = t^3 + 9t^2 - t - 9 = (t - 1)(t + 1)(t + 9) $ So roots are $t_1 = 1$, $t_2 = -1$, $t_3 = -9$. Set $theta_1 = sqrt(t_1) = 1$, $theta_2 = sqrt(t_2) = i$, $theta_3 = plus.minus sqrt(t_3) = plus.minus 3i$ so that $theta_1 theta_2 theta_3 = -q = -3$, i.e. $theta_3 = 3i$. - So roots of $f(x - 3\/2)$ are $ x_1 & = 1/2 (theta_1 + theta_2 + theta_3) = 1/2 (1 + 4i), \ x_2 & = 1/2 (theta_1 - theta_2 - theta_3) = 1/2 (1 - 4i), \ x_3 & = 1/2 (-theta_1 + theta_3 - theta_3) = 1/2 (-1 - 2i), \ x_4 & = 1/2 (-theta_1 - theta_2 + theta_3) = 1/2 (-1 + 2i) $ - So roots of $f(x)$ are $-1 plus.minus 2i$, $-2 plus.minus i$. ] #example(name: "Galois groups of quartic polynomials")[ - Let $char(K) != 2, 3$, $f(x) = x^4 + a x^3 + b x^2 + c x + d in K[x]$. Galois group is $G_f = Gal(L\/K)$ where $L$ is splitting field for $f(x)$ over $K$, and $G_f$ is subgroup of $S_4$. - Assume that $f(x)$ irreducible in $K[x]$. It can be shown there are five possible isomorphism classes of Galois groups: $S_4, A_4, V_4, ZZ\/4$ or $D_4$. - Let $R(t) in K[t]$ be cubic resolvent of $f(x)$ with roots $t_1 = theta_1^2$, $t_2 = theta_2^2$, $t_3 = theta_3^2$. Let $M$ be splitting field of $R(t)$ over $K$, so $ K subset K(t_1, t_2, t_3) subset M subset L = M(theta_1, theta_2, theta_3) $ ] #theorem[ Let $f(x) in K[x]$ irreducible and have irreducible cubic resolvent $R(t) in K[t]$ with roots $t_1 = theta_1^2$, $t_2 = theta_2^2$, $t_3 = theta_2^3$. Let $L$ be splitting field of $f(x)$ over $K$ (so $G_f = Gal(L\/K)$) and let $M$ be splitting field of $R(t)$ over $K$ (so $G_R = Gal(M\/K)$). - If $Delta_R in K^times^2$ (i.e. $G_R tilde.equiv A_3$ and $[M: K] = 3$), then $G_f tilde.equiv A_4$. - If $Delta_R in K^times - K^times^2$ (i.e. $G_R tilde.equiv S_3$ and $[M: K] = 6$), then $G_f tilde.equiv S_4$. ] #proof[ - Sufficient to prove $[L: M] = 4$ since then $[L: K] = 12$ or $24$ by Tower Law. - Show $M$ does not contain $theta_1, theta_2$ or $theta_3$. - Suppose it does, so WLOG $theta_1 in M$. $Gal(M\/K) tilde.equiv A_3$ or $S_3$, so must be order 3 element $sigma in Gal(M\/K)$. $sigma(theta_1)$ and $sigma^2 (theta_1)$ are the other two roots $theta_2$ and $theta_3$ since $R(t)$ is irreducible and $theta_1, theta_2, theta_3 in M$. But this implies $M = L$ so $[L: K] = 3$ or $6$, but $4 | [L: K]$ since $L$ contains roots of irreducible quartic. - $M(theta_1)\/M$ is degree $2$. Assume $theta_2 in M(theta_1)$. $Gal(M(theta_1)\/M) = {id, tau}$ for some $tau: theta_1 |-> -theta_1$. Also $theta_2^2 in M$ so $tau(theta_2) = plus.minus theta_2$. - If $tau(theta_2) = theta_2$, then $theta_2 in M$: contradiction. - If $tau(theta_2) = -theta_2$, then $tau(theta_1 theta_2) = (-theta_1)(-theta_2) = theta_1 theta_2$ hence $theta_1 theta_2 in M$. But $theta_1 theta_2 theta_3 in K$ and $theta_1 theta_2 != 0$ since $R(t)$ irreducible. But then $theta_3 in M$: contradiction. - Hence $[M(theta_1, theta_2): M] >= 4$, and $theta_1 theta_2 theta_3 in M$ so $L = M(theta_1, theta_2)$ and $[L: M] = 4$. ] #example[ - If $f(x) in K[x]$ but cubic resolvent $R(t) in K[t]$ is reducible, it is possible that all roots $t_1 = theta_1^2$, $t_2 = theta_2^2$, $t_3 = theta_3^2$ are in $K$. Then $M = K$ and $L = K(theta_1, theta_2, theta_3)$. Since $theta_1 theta_2 theta_3 in K$, $L\/K$ is obtained by adjoining only two square roots to $K$. Since $f(x)$ irreducible of degree $4$, we have $[L: K] >= 4$, hence only option is biquadratic extension $G_f = Gal(L\/K) = V_4 tilde.equiv ZZ\/2 times ZZ\/2$. - If only one root $t_1, t_2, t_3$ is in $K$ (say it is $t_1$): - $M$ is splitting field of irreducible quadratic over $K$. Hence $M = K\(sqrt(d)\)$ for some $d in K^times - K^times^2$ and $Gal(M\/K) = {id, phi} tilde.equiv ZZ\/2$ where $phi\(sqrt(d)\) = -sqrt(d)$. - We have $ K subset M = K\(sqrt(d)\) = K(alpha, overline(alpha)) subset L = M\(sqrt(alpha), sqrt(overline(alpha))\) $ where $alpha$ and $overline(alpha) = phi(alpha)$ are conjugate elements in $M^times - M^times^2$ (corresponding to $t_2$ and $t_3$). - In this case, $L\/K$ is normal extension, since if $alpha, overline(alpha)$ are roots of $x^2 + a x + b in K[x]$, then $plus.minus sqrt(alpha), plus.minus sqrt(overline(alpha))$ are roots of $x^4 + a x^2 + b in K[x]$. So $L$ is splitting field of $x^4 + a x^2 + b$ over $K$. For above tower of fields, we have Galois groups $ {id} subset Gal(L\/M) = H subset Gal(L\/K) = G $ and $G\/H tilde.equiv Gal(M\/K) = {id, phi} tilde.equiv ZZ\/2$. ] #theorem[ Let $M = K\(sqrt(d)\)$, $d in.not K^times^2$, $Gal(M\/K) = {id, phi}$. Let $alpha$, $overline(alpha) = phi(alpha) in M^times - M^times^2$, and let $L = M\(sqrt(alpha), sqrt(overline(alpha))\)$, $G = Gal(L\/K)$. - If $alpha overline(alpha) in K^times^2$, then $[L: K] = 4$ and $G tilde.equiv ZZ\/2 times ZZ\/2$. - If $alpha overline(alpha) in M^times^2 - K^times^2$ then $[L: K] = 4$ and $G tilde.equiv ZZ\/4$. - If $alpha overline(alpha) in.not M^times^2$, then $[L: K] = 8$ and $G tilde.equiv D_4$. ] #note[ In the case that $C := alpha overline(alpha) in.not M^times^2$ and so $G tilde.equiv D_4$: - We have $Gal(M\/K) = {id, phi}$, $phi: sqrt(d) |-> -sqrt(d)$. - There are two lifts of $phi$ to $L$: $ tau: \(sqrt(d), sqrt(C), sqrt(alpha)\) & |-> \(-sqrt(d), sqrt(C), sqrt(overline(alpha))\), \ sigma: \(sqrt(d), sqrt(C), sqrt(alpha)\) & |-> \(-sqrt(d), -sqrt(C), sqrt(overline(alpha))) $ (so $tau\(sqrt(overline(alpha))\) = sqrt(alpha)$, $sigma\(sqrt(overline(alpha))\) = -sqrt(alpha)$) - Then $G = Gal(L\/K) = ideal(tau, sigma | tau^2 = sigma^4 = e, tau sigma = sigma^3 tau)$. ] == A criterion for solvability by radicals #note[ Assume all fields in this section have characteristic $0$. ] #definition[ $L\/K$ is *radical extension* if there is tower of field extensions $ K = K_0 subset dots.h.c subset K_m = L $ where for each $1 <= i <= m$, $K_i = K_(i - 1)(root(n_i, alpha_i))$ with $alpha_i in K_(i - 1)$ and $n_i in NN$. ] #example[ Let $alpha = cbrt(2 + root(5, 3 - sqrt(7)))$. We have $ K_0 = QQ subset K_1 = QQ\(sqrt(7)\) subset K_2 = K_1 (root(5, 3 - sqrt(7))) subset K_3 = K_2 (alpha) $ ] #definition[ $f(x) in K[x]$ is *solvable in radicals* over $K$ if there is a radical extension $L$ of $K$ containing at least one root of $f(x)$. ] #lemma[ If $f(x)$ irreducible and solvable in radicals, then all its roots belong to the radical field extension $L$. ] #definition[ A finite group $G$ is *solvable (soluble)* if there exists decreasing sequence of subgroups $ G = G_0 supset dots.c supset G_m = {id} $ where for each $1 <= i <= m$, $G_i$ is normal subgroup of $G_(i - 1)$ and $G_(i - 1)\/G_i$ is cyclic. ] #lemma(name: "Properties of solvable groups")[ - Every subgroup of finite solvable group is solvable. - Abelian groups are solvable. - $S_n$ is solvable iff $n <= 4$. - Let $G$ finite group with normal subgroup $H$. Then $G$ is solvable iff both $H$ and $G\/H$ are solvable. ] #theorem(name: "Galois' Theorem: Criterion for solvability in radicals")[ Let $f(x) in K[x]$ irreducible. Then $f(x)$ is solvable in radicals over $K$ iff Galois group $G_f$ is solvable. ] == Polynomials not solvable by radicals #lemma[ $A_n$ is generated by $3$-cycles $(i med j med k)$. ] #proof[ - $A_1 = A_2 = {id}$. - For $n >= 3$, any element in $A_n$ is product of even number of transpositions. - Combine pairs of transpositions as follows: - $(i j)(i j) = id$. - $(i j)(i k) = (i k j)$. - $(i j)(k l) = (i k)(j k)(j k)(k l) = (i j k)(j k l)$. ] #theorem[ For $n >= 5$, $A_n$ and $S_n$ are not solvable. ] #proof[ - Assume $A_n$ solvable, so there is decreasing sequence of subgroups $ A_n = G_0 supset dots.c supset G_m = {id} $ with $G_i$ normal in $G_(i - 1)$, $G_(i - 1)\/G_i$ cyclic and so abelian. So we have canonical projection homomorphism $pi: A_n -> Q = A_n\/G_1$, $Q$ is abelian and non-trivial. - Let $g = (i_1 i_2 i_3) in A_n$. There are $i_4, i_5 in [n]$ (since $n >= 5$) such that $i_1, i_2, i_3, i_4, i_5$ distinct. Let $g_1 = (i_1 i_2 i_4)$, $g_2 = (i_1 i_3 i_5)$, then $g_1 g_2 g_1^(-1) g_2^(-1) = g$. - Since $Q$ abelian, $pi(g) = pi(g_1) pi(g_2) pi(g_1)^(-1) pi(g_2)^(-1) = id$. - So $pi$ sends $3$-cycles to $id$, and $A_n$ is generated by $3$-cycles, so $pi(A_n) = {id}$ which is the trivial group: contradiction. ] #theorem[ Let $f(x) in QQ[x]$ irreducible polynomial of degree $5$ with exactly $3$ real roots. Then $f(x)$ has Galois group $G_f tilde.equiv S_5$ (and so $f(x)$ is not solvable by radicals over $QQ$). ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/009_Episode%209%3A%20Beauty%20in%20Destruction.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 9: Beauty in Destruction", set_name: "Murders at Karlov Manor", story_date: datetime(day: 17, month: 01, year: 2024), author: "<NAME>", doc ) Silence filled the room until it felt like they were collectively choking on it. Ezrim looked to Kaya. "Did you know this?" he asked, shattering the silence into something more manageable. "What? No! We sat quietly for a while, and then that flower came out of the wall, and Proft put it in the jar and announced that he'd solved the whole case," said Kaya. "He didn't say anything to me about accusing Trostani." "Trostani could #emph[never] ," protested Tolsimir. "Even if she were somehow corrupted by the influence of Phyrexia, she can't leave Vitu-Ghazi while the tree is healing! If anyone is above suspicion in all of this, it's her." "A fact I believe she was counting on," said Proft, still watching the tripart dryad as her pieces twined around one another in silent confusion. As before, her heads were out of unity, each reflecting its own response to the situation. Ses looked even angrier than she had before, the dryad of order incensed by the accusations being hurled at her roots. Cim looked shocked and horrified, the dryad of harmony unable to accept the disharmony all around her. Only Oba's face hadn't changed. The dryad of life still looked serene and detached, removed from the situation by a barrier of her own making. Whatever was happening here, she took no part of it as her own, only watched the people arguing about guilt and obligations. Proft continued: "It's become easy, in the aftermath of war, to blame everything on the Phyrexians. Every pothole is from damage they did to our streets, not our own failures to maintain them. Every rumor roots back to Phyrexia. Every lie, every inequality, every mistake we lay at Phyrexia's feet. But we were capable of cruelty long before them. We were capable of crime. And we were capable of betrayal." The other guild leaders protested, some with sincere dismay at the idea that one of their own could have been behind this, others with seemingly performative dismay. Even as Judith began to snarl and rave about false accusations and unqualified investigators trying to push blame away from their Dimir lackeys, she was scanning the room, checking the exits to see how best to make her escape. Krenko backed deeper and deeper into a corner, looking for something he could use as a weapon against the violence his honed understanding of danger was telling him would erupt at any moment. Only Izoni remained calm and silent, watching this unfold like she was observing the blooming of some rare and deadly flower. Etrata rose and slithered through the crowd, slick as any snake, to station herself by Proft's side. He shot her a look, a smug smile playing at the corner of his mouth. "I knew you wouldn't be able to resist stepping in for the big reveal," he said, almost teasing. Etrata rolled her eyes. "Please. Like I'm going to let you get yourself slaughtered #emph[now] , after I've worked so hard to keep you alive. Go ahead, go back to explaining the nice lady's horrible murderous plan and how she was able to accomplish it with all of Ravnica trying to hunt her down. Please, tell us." "I'd prefer it if #emph[she] told us," Proft said. "I know she was responsible. What I'm still missing is a large portion of the #emph[why] . Why now? Why betray the trust Ravnica has put in her, allowing Vitu-Ghazi to become the repository of our history, putting the original Guildpact into her keeping? Why, during this period of rebuilding, when decapitating the guilds could very easily cause them to collapse completely? I have not always been the biggest advocate of the guild system, even as I've both benefited from and suffered under it, but I recognize that it is essential to a healthy, stable city, and we need both those things to be true if we're to recover after the invasion." "We didn't—" began Cim. "How dare you—" Ses said at the same time. Oba was silent, and remained silent as her sisters turned, with terrible slowness, to look at her. Their expressions of horror and fury melted into confusion, followed by shock. Through it all, Oba looked at them unwavering, her own expression never changing. "How—?" asked Cim. "Why—?" asked Ses. #figure(image("009_Episode 9: Beauty in Destruction/01.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Because they #emph[deserved] it," snapped Oba, facade of calm finally shattering. Kaya was on her feet before she recognized the intent to move, her daggers already drawn and ready. Etrata shot her a quelling look, and she sank slowly back to her seat, never taking her eyes off Trostani. "They failed Ravnica in its time of greatest need," continued Oba. "In #emph[our] time of greatest need. They play at finance and invention, at pleasure and pain. #emph[We] are the will of Mat'Selesnya! #emph[We] are Ravnica, the plane itself, not merely the city our world has become! We are the green and growing heart of this plane, and without us, there would be no Ravnica, no city, no guilds! Mat'Selesnya nearly fell in defense of #emph[their] workings, and as we teetered, they did their best to cut us off at the roots!" Cim and Ses recoiled, as much as their conjoined nature allowed. Proft, meanwhile, took a step closer to the dryad. "If you would explain to the rest of us precisely how we failed Mat'Selesnya in specific and Ravnica in general, perhaps we could all come closer to understanding," he said. "It might be possible to find a path through this that requires no further punishment for anyone." "I think not," growled Aurelia. Lavinia shot her a look, and she quieted. Proft, meanwhile, continued looking at Oba with the patient attentiveness of a schoolboy waiting for his most-essential lessons. The dryad leaned closer to him. "As the invasion occurred, I watched through the root system. Vitu-Ghazi #emph[is] Ravnica, and we are Vitu-Ghazi; there is no inch of this plane's soil that is not ours to keep. I #emph[felt] the taint of their foul oil seep into our earth, #emph[felt] their unnatural footsteps as they strode along our streets, #emph[tasted] the blood of our citizens soaking into our roots. It … hurt me." Oba glanced at Cim and Ses, and for a moment, her expression softened. "I feared what it would do to us if it was allowed to spread unhindered, and so I chose to pull the pain into myself for the sake of my sisters. I fought the corruption of Realmbreaker alone." "We never asked you to," said Ses. "You never asked why it was hurting all of Ravnica, and not hurting us," said Oba. "You were as selfish as the rest of them, when you saw the chance to be. I felt it all. Every sick, terrible instant, every vicious drop. We came so close to falling to Realmbreaker, to becoming part of their terrible design, and if Mat'Selesnya, which #emph[is] Ravnica, had fallen, nothing anyone else did would have been enough to save them. I fought in the darkness, with no one to assist me, and I saw what they did." "What who did?" asked Proft, trying to guide the conversation. Oba shot him a glare so filled with hatred that it should have been as deadly as any Golgari toxin. "He," she jabbed a finger at Krenko, "was hoarding resources. His little lackeys would raid stores and warehouses while their protectors were elsewhere, trying to save Ravnican lives, and they would take everything they could get their hands on, stripping the shelves down to dust. Then he sold those things, those necessary, vital things—clean water, food, medical supplies—back to the Ravnican people at a markup even the Orzhov would have been embarrassed to impose. He gouged people who were already bleeding." Aurelia and Lavinia turned to Krenko, expressions questioning and cold. Krenko shrank back against the wall, refusing to meet their eyes, but didn't deny the accusations. Oba wasn't finished. "Without his actions, thousands of citizens may have survived the invasion. Because of him, they had no chance. And you!" She swung her attention toward Vannifar. "You cry false tears for your compatriot, but I heard how you spoke to each other behind closed doors. I know how little love was lost between you. Zegana was #emph[fascinated] by the Phyrexian oil. She had begun infecting ordinary creatures with it, the beasts of Ravnica who had no voices of their own, no way to object to what was being done. She would have moved on to intelligent subjects had the invasion lasted any longer. She was well along the road to dooming us all." Vannifar didn't contradict the furiously raving Oba, only looked at her hands with an expression of profound sorrow. Oba turned her attention to the rest of the room, scanning their faces one by one before settling on Kaya. Kaya sat up straighter, waiting to hear what poison Oba would spit in her direction. Coward? If there was anything she knew she wasn't, it was a coward. Deserter? She'd come back to Ravnica even knowing she would be condemned for leaving them. Failure? That was the one word Kaya didn't think she could endure. If Oba flung that at her, she would probably walk into the Blind Eternities whether she wanted to or not, fleeing yet another crisis that needed her attention. There were some things she still couldn't bear to lift. Oba said none of those things. Instead, leaning as far forward as her conjoined state allowed, she said, "You grieve Teysa. You're here, in this room, as a part of this #emph[ridiculous] investigation, because you mourn her so deeply. No one should mourn her. She was a monster. What she did, what she was preparing to do, is far greater than any crime I could possibly have committed. <NAME> was in league with the Phyrexians, communicating with them in secret. She intended to rule Ravnica in their name once the invasion was complete. She betrayed every person in this room, and if I passed judgment on her crimes, who are #emph[you] to pass judgment on #emph[me] ? All I did was what any one of you would have done, given the means. You all clearly had the motive." "Sister, no," said Cim, reaching for Oba. Her hand was shaking. "No. You drank in the anger and grief, the suffering of the whole city, and it has poisoned your judgment. We stand for Selesnya, but Selesnya is not the judge and executioner for all of Ravnica. What you do, what you have been doing … it's wrong." Vannifar took a sharp breath and stood, eyes on Oba. "You're right," she said. "Zegana #emph[was] experimenting with the Phyrexian oil, but what you missed in your eagerness to take our bickering for hatred was the fact that she did so with my full consent. She was seeking a cure for phyresis, the spreading taint of Phyrexia; she sought a way to bring our lost citizens back to us. She had no intention of wielding the oil as a weapon. I would have known. I watched her so closely." "Roots are, by their nature, buried," said Ses. "We can hear through them, but distantly. What you overheard may not have been—was not—the whole of the story that unfolded before you." "You have no right to say such things of <NAME>, who was a hero in every way possible." For a moment, Kaya thought she had spoken without intending to. Then the voice fully registered in her ears, and she turned to see Etrata scowling at the dryad, eyes narrowed. "Yes, Teysa was in communication with the invaders," said Etrata. "She learned their language from the dead who had not been fully converted to the Phyrexian cause before they gave their lives for Ravnica, and she opened communication in their own words. They saw her as a useful curiosity, and replied. Once she was able to reliably communicate with them, she began funneling information to the resistance. She used the spirits who serve the Orzhov to spy on every movement those monsters made, risking the possibility of phyresis, putting her own life secondary to the needs of her city. I was one of her contacts. She was working with House Dimir the whole time—she, and her dead. She was a #emph[hero] . She never betrayed Ravnica. But you, who saw without understanding … you were more than happy to betray #emph[her] ." For a moment, there was silence. Krenko began inching toward the door. Ezrim fixed him with a glare, the archon's mighty wings flexing as if he were considering the merits of a pounce. "What of you, criminal?" he asked, voice sharp. "Don't try to lie. The head of the Senate is here, and she will know." "Yeah, and so what?" asked Krenko. "Goblins died getting those supplies from behind enemy lines. The Phyrexians sure weren't going to share! You expect me to risk my life without a profit?" "Everything I say he did, he did," said Oba. "I #emph[watched] him. Even if I believe your stories about secret heroism and double agency, he committed the crimes I know I saw." "What did Kylox do?" asked Ral abruptly. Kaya turned to look at him. She'd almost forgotten the death of the Izzet inventor; she'd only heard about it from Proft, rather than witnessing it herself. Oba sneered at Ral. "He got in the way," she said. "I sent that assassin after the goblin, and your inventor was standing in his path. And even if he hadn't been out of place, your house needs cleaning as much as any of the others! You'd think this city would have learned the danger of putting Planeswalkers at the head of any guild. Always here to go. But you didn't watch your people closely enough. Your man Kylox was fascinated by Phyrexian technology. The oil powered and transformed them, but the things they built … he thought to steal their designs as his own, to rise within the guild on the strength of corrupt engineering." "You killed him for #emph[industrial espionage] ?" demanded Ral, electricity crackling around his hands. "I have no doubt you could kill half my guild for the same crime!" "#emph[Then maybe I should!] " snapped Oba. "Maybe cleansing Ravnica from the stains of the invasion means killing every soul who was tempted, even for a moment, by the people who came to destroy us!" "Sister, #emph[no] ," said Ses. "You should have told us you were suffering." "You should have let us share in what you felt," said Cim. "We would have shouldered our fair share of the burden." "You're wounded, and you need to be healed," said Ses. "Please," said Cim. "Please, let us help you now, even if you couldn't before." For a moment, it seemed like Oba might listen. Then they reached for her, and she recoiled. "Fools, all of you," she said. Her voice filled the room, shoving everything else aside. "You refused to look. You refused to listen. You refused to #emph[see] . And worst of all, you still congratulate yourselves on a battle well fought and a war well won—even here, where you stand smugly in front of me and assume you've unraveled my plan. I've been killing for #emph[weeks] ." Silence fell. Even Proft looked shocked. Now triumphant, Oba stood taller and declared, "I witnessed countless examples of cruelty, cowardice, weakness, all in need of nature's righteous judgment. The streets of Ravnica ran with the blood of the guilty long before I started hunting larger prey. You only noticed when I targeted people you cared about. The ones you considered important enough to grieve. And #emph[I'm not done yet] ." "Yes, you are," said Aurelia, standing. "By the authority given to me as guild leader of the Boros Legion, I formally place you, Oba of Selesnya, under arrest." "Oh, do you?" Oba looked theatrically around herself, first at the room, then at her sisters. "How were you intending to do that? #emph[We] are Trostani. We are three and we are one, and my sisters committed no crime save for being sheltered from the horrors of war. Your own laws won't allow you to place them under arrest, any more than you can arrest the weapons used to deliver my justice. #emph[That] has been pointed out in excruciating detail. One who does not act of their own free will carries no culpability in the crimes their hands commit." "I'll find a way," spat Aurelia. "You'll sit #emph[down] ," said Oba. The room shook, not hard, but hard enough to drop Aurelia back to her seat and Detective Proft to the floor. He landed on his behind, hands splayed to keep him upright as he narrowed his eyes at Oba. "That was quite impolite," he said. "Believe me, we're done with civility," said Oba. She turned to Cim and Ses, who were still speaking in quiet, soothing tones, trying to calm her. Oba clapped her hands. Her sisters went limp, sagging on their single trunk like wilted flowers, their eyes half-closed and unseeing. "That's better," said Oba. "And I'd like to thank you, Detective Proft. I'm sorry you have to be here for this. You're as close to innocent as I've seen." "Be here for what?" asked Judith, sounding alarmed rather than bored for the first time. In answer, the room began to rock, Vitu-Ghazi responding to the commands of the single mind controlling the great tree. The manor room buckled, twisting in on itself as Ezrim roared and Etrata produced long, wicked-looking knives from inside her shirt, focusing on Oba. "I am Vitu-Ghazi!" bellowed Oba, the branch that was her body pulling away from the bough where her sisters dangled, silent and stunned. Farther and farther from them she pulled herself, until she was, while still attached to the tree itself, an entirely independent entity, Trostani no longer. For the first time since they had been chosen by Mat'Selesnya, she was Oba, one and alone. "I am Mat'Selesnya! I am #emph[Ravnica] !" #figure(image("009_Episode 9: Beauty in Destruction/02.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Thorny vines burst through the walls, grabbing for the assembled Ravnican leadership. Kaya phased through the loop that tried to entangle her, spinning her daggers in her hand as she rushed to cut first Kellan and then Ral free. "Thank you," said Ral, eyes flashing electric fire as he pulled lightning from the accumulator on his back and whipped it at Oba. She absorbed the blast, barely seeming to notice what should have been a devastating assault. Instead, she moved one hand in a slashing motion, and a massive branch snapped across the room, slamming into Ral's chest and knocking him into the nearest bookshelf. It teetered dangerously, spilling volumes in all directions. All this had happened in a matter of seconds. Lavinia tried to spring to her feet, only to find herself held down by thick, knobbed roots that had grown up from the floor and wrapped around her ankles, so gently she hadn't even noticed, but leaving her with no leverage to pull herself free. Aurelia tried to go to her aid but discovered she was in the same situation, more vines wrapped around her wings, pinning them. The chain holding Massacre Girl went limp—all at once, the assassin was nowhere to be found. Izoni remained perfectly still as the vines wrapped around her, watching them without blinking. Only once they were in place did she move her hands, easing a tiny vial from her pocket. She sprinkled its contents on the vines and watched dispassionately as they withered and dropped away. Kaya continued slicing as she raced across the room, stepping through any vines or roots that tried to grab her. She released Ezrim next. He roared, pouncing on the nearest branch, as she moved to free the now struggling Etrata. Oba continued lashing out with a seemingly endless parade of roots, vines, and branches, as if she had brought the fury of all Ravnica's long-razed forests to the fight. The ceiling grew distant as the room stretched like a street vendor's hand-pulled taffy, becoming taller with every passing second. Kaya had never been inside Vitu-Ghazi while it was in the process of becoming something new, had been unaware the vast living guildhall #emph[could] become something new before she'd seen the manor on the moor, and with the way the walls were shaking, she was increasingly unsure any of them would be able to survive if they stayed here much longer. There were no windows. Their absence had seemed like a good thing when Proft told her to request this room, ensuring there would be no witnesses, no chance of assassins taking advantage of an unclosed latch or broken seal, but now it seemed they had allowed themselves to be herded into a killing box. And there wasn't time to dwell on that as Ral hurled another bolt of lightning at Oba, which she deflected with a swing of one mighty branch, sending it ricocheting into the wall just above Krenko's head. Krenko yelped and swore, swinging a punch at the nearest cluster of vines, and was promptly tied down by more loops of root growing from the floor. His struggles were to no avail, as he had already been tied fast. Yarus, saying nothing, gestured for Kaya to come to him. She jumped and kicked off a swinging branch, launching herself in his direction. He grinned. Kaya was momentarily taken aback by the sheer joy of that expression, then remembered who she was looking at. For someone high enough in the fragmented Gruul leadership to be called to this sort of meeting, a dull assembly about crime and politics turning into an out-and-out brawl must have been #emph[fantastic] . She glanced back. Kellan had managed to fight his way through the swinging branches to join Etrata in protecting Proft. She approved. Of everyone in the room, the detective was the least equipped to protect himself—save possibly Krenko, who was pinned in his increasingly dense prison of roots and vines. Unless Oba planned to constrict him to death, he was probably fine for the moment. She retuned her attention to Yarus. "Big beast rider took my weapons before he'd bring me here, but I can improvise," he said. "Let me out of these tangles and I'll show you." "You'll be attacking—?" "Got called to the Agency because someone let Anzrag out. Right thing to do. Gods shouldn't be confined. Wrong place to do it. She," his eyes narrowed as he focused on Oba, "used my god as a weapon. She doesn't get to do that." Kaya didn't hesitate before cutting his legs free. Yarus grinned again, even wider. He moved away from her, grabbing a chunk of fallen rafter and holding it like a spear as he rushed across the room toward Oba, whose attention was fixed on deflecting Ral's lightning while her roots struggled to tie Aurelia and Ezrim ever more firmly down. Izoni was free, stepping lightly through the chaos, poisoning the roots that grabbed for her, occasionally pausing to do the same to any particularly troublesome vines. Kellan and Etrata hacked away at the roots that targeted them or Proft, but they were fighting a defensive battle, making no forward progress. Yarus might have reached his target had he not given in to the Gruul urge to roar a challenge. His voice boomed through the distorting room, horribly loud. Tolsimir heard the sound and leapt for Yarus, knocking him away from Oba and driving the rafter straight through his own chest. Yarus glared at him, still holding fast to the portion of the rafter that wasn't buried in Tolsimir. "Why did you do that?" he demanded. "I had a clear shot!" Tolsimir made a thick choking noise before falling backward, pulling the rafter from Yarus's hands. Yarus began scavenging for a new weapon, only for everything he grabbed to be immediately wrenched away by furiously twisting roots. He was still trying to rearm himself when the roots wrapped around all six of his limbs, yanking him off his hooves and jerking him toward Oba, who took her eyes off Ral to lean closer, her face tight with fury. "He was #emph[mine] !" she snarled. A root rose from the floor, trailing ends twisting together until they formed a sharp-pointed spear. It pulled back like a rearing snake as she aimed it at Yarus's chest. "How #emph[dare] you!" "I dare for the Clans!" shouted Yarus. "I dare for Ravnica! You are not the world, you're a #emph[gardener] , and I have never accepted your authority over me." He spat at Oba. She pulled the root spear farther back, preparing to slam it home. Before she could complete her strike, Etrata leapt into its path, knocking Yarus aside. The spear smashed through the left side of her chest, shattering muscle and bone. Kaya stiffened, feeling the last traces of hesitation leave her body. There hadn't been much: after what Oba had admitted, she'd known the dryad had to die. But that strike had been so similar to the one that killed Teysa that suddenly what had been a story—a what-if spun by a woman who had clearly suffered enormous, if invisible, damage during the war—became a confession of murder. Proft had cracked the case: Oba had been telling the truth all along. Trostani was an essential enough part of Ravnica that Kaya hadn't fully believed her until she struck Etrata. The Dimir lay motionless on the floor, a trickle of blood painting one corner of her mouth. Proft dropped to his knees, searching her body for signs of life. It looked as if the smug, stoic detective was on the verge of tears. Yarus grabbed for another weapon, but a cascade of vines tied him down, immobilizing him next to the woman who had taken a possibly killing blow for his sake. And all that was a distraction from what still needed to be done. With a roar that would have made Tyvar proud, Kaya flung herself, solidifying and knocking Kellan out of the way of a swinging branch. He hit the floor and rolled to his feet, already in a fighting stance. Kaya spun her daggers in her hands and lunged, solid enough that when Oba wrapped a root around her waist, she didn't tumble through it. "Little deserter," Oba sneered. "Little runaway." She wrapped more and more roots around Kaya, layering them on so quickly that Kaya couldn't turn insubstantial long enough to escape, pinning them both in a seemingly endless race for dominance. When Oba began to pull back as if to hurl her away, Kaya realized what she was doing and stopped trying to phase, allowing herself to position for the throw. Half the room's occupants were chained to the floor with loops of root and vine, branches pinning them down. The other half fought or knelt around the motionless Etrata. Izoni still moved freely, but her little vials were starting to run empty, and even as Kaya watched, Oba got a root around her, dragging her to the floor. Kellan shouted something and leapt for Kaya. Jamming one of her daggers into a loop in the root, she grabbed his hand, pulling him along as Oba hoisted her into the air. Above them, the ceiling opened like an iris, branches pulling apart to reveal an oblong section of sky. "Hold on!" Kaya shouted. "Oh, I am #emph[holding on] ," Kellan yelled back. As Kaya had hoped, the higher Oba hoisted them, the more the room below shifted to look like a section of natural tree, Vitu-Ghazi reaching for its original form even as Oba's rage distorted it. Holes appeared in the walls, not windows, but breaks in the wood, places where the growing bark had peeled away. Judith broke free of a loop of root and fled for one of those openings, wildly forcing her way outside. "Coward," Kaya muttered, pulling her dagger out of the wood just as Oba hauled back and threw them. The force of the throw separated her from Kellan, leaving him spinning away into the sky. Kaya stretched a hand after him, before she was pulled up short by a vine wrapping around her ankle, and realized two things at the same time: The throw hadn't been the point of the attack. And Oba wasn't doing this on her own. Even connected to Vitu-Ghazi, she wouldn't have this sort of power. She was drawing directly on the Ravnican Worldsoul, Mat'Selesnya, ripping strength from the very plane and using it against the people she had designated her enemies. Kaya attempted to phase free, preferring the fall to what was sure to come. The strength of the Worldsoul was a shackle around her skin, and she was yanked back into the crumbling manor. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kellan fell without anything to catch or hold onto, arms in front of his face to shield him from the inevitable impact. He could still see Vitu-Ghazi beneath him, now caught midway between the manor house it had appeared to be and a twisted, unhealthy-looking oak. The damage the Phyrexians had done went deep; the damage Oba was doing might go deeper. Of course, if he hit the ground, the damage she did to him would be the last thing he ever had to worry about. Kellan tried to twist in the air, hoping he might slow his descent, and succeeded only in going into a sort of spin that left him dizzy in addition to weightless. He screwed his eyes shut, not wanting to see himself hit the ground, and felt his spin stop as his fall slowed to something almost pleasant. Cracking one eye open, he glanced over his shoulder and saw that pure, gold-rimmed fae magic of the same kind his hilts produced now enveloped him. #figure(image("009_Episode 9: Beauty in Destruction/03.png.jpg", width: 100%), caption: [Art by: Durion], supplement: none, numbering: none) He opened both eyes, blinking at the unexpected sight. "Hey! I'm okay!" he said, waving his arms to control his position in the air without much success. Below him in the courtyard, Judith ran around ground-breaking roots, almost falling several times before she rounded the front of the manor and the road was in sight. So was a familiar figure in red and black, a painted doll's smile on her face. Massacre Girl smiled a vicious, natural smile below her harlequin's grin, producing a viciously barbed knife from somewhere on her person. "This is for leaving me to the wolves," she said. "Naughty, naughty. Rakdos doesn't like it when the children fight." She lunged. Judith stumbled back. Not even Kellan, still occupied in falling, heard what happened next over the screams from inside.
https://github.com/stalomeow/resume-template
https://raw.githubusercontent.com/stalomeow/resume-template/main/template.typ
typst
MIT License
// 获取 metadata #let get-var(name) = query(label(name)).first().value // 设置 metadata #let set-var(name, value) = [#metadata(value) #label(name)] // 图标 #let svg-icon(path) = context { let theme-color = get-var("theme-color") let box-base-line = get-var("box-base-line") let svg = read(path) svg = svg.replace(regex("fill=\".*?\""), "") // 先把旧的 fill 全删掉 svg = svg.replace("<path", "<path fill=\"" + theme-color.to-hex() + "\"") box( baseline: box-base-line, height: 1.0em, width: 1.25em, align(center + horizon, image.decode(svg)), ) } // Font Awesome #let fa-bilibili = svg-icon("icons/fa-bilibili.svg") #let fa-code = svg-icon("icons/fa-code.svg") #let fa-envelope = svg-icon("icons/fa-envelope.svg") #let fa-github = svg-icon("icons/fa-github.svg") #let fa-graduation-cap = svg-icon("icons/fa-graduation-cap.svg") #let fa-link = svg-icon("icons/fa-link.svg") #let fa-phone = svg-icon("icons/fa-phone.svg") #let fa-weixin = svg-icon("icons/fa-weixin.svg") #let fa-work = svg-icon("icons/fa-work.svg") #let fa-wrench = svg-icon("icons/fa-wrench.svg") // 隐私 #let privacy(body) = context { let anonymous = get-var("anonymous") let box-base-line = get-var("box-base-line") if (anonymous) { let size = measure(body) // 用黑块挡住 box( fill: black, baseline: box-base-line, width: size.width, height: size.height ) } else { body } } // 设置 #let resume( body, margin-top: 1.5cm, margin-bottom: 2cm, margin-left: 2cm, margin-right: 2cm, page-numbering: none, fonts: ("Noto Sans SC",), text-size: 10pt, theme-color: rgb(38, 38, 125), box-base-line: 0.15em, name-size: 1.4em, par-leading: 0.4em, name: "名字", phone: "(+86) 123-4567-8910", wechat: "wechat", email: "<EMAIL>", github: "github", sites: ("site.com",), anonymous: false, ) = { // 页面设置 set page(paper: "a4", numbering: page-numbering, margin: ( top: margin-top, bottom: margin-bottom, left: margin-left, right: margin-right, )) // 字体设置 set text(font: fonts, size: text-size, lang: "zh", cjk-latin-spacing: auto) // 标题颜色 show heading: set text(theme-color) // 二级标题下加一条横线 show heading.where(level: 2): it => stack( // v(-0.2em), it, v(0.6em), line(length: 100%, stroke: 0.05em + theme-color), ) // 链接颜色和下划线 show link: it => { set text(fill: theme-color) underline(it) } // 段落设置 show par: set block(spacing: 0.5em) // 段间距,但似乎没用?? set par(justify: true, leading: par-leading) // 行间距 // 全局变量,某些函数会用到 set-var("theme-color", theme-color) set-var("box-base-line", box-base-line) set-var("par-leading", par-leading) set-var("anonymous", anonymous) // 标题 heading(text(name-size, privacy(name))) // 基本信息 grid( columns: (1fr, 1fr, auto), align: (left, left, left), row-gutter: 0.25em, [#fa-phone #privacy(phone)], [#fa-weixin #privacy(wechat)], [#fa-envelope #privacy(link("mailto:" + email, email))], [#fa-github #link("https://github.com/" + github, "github.com/" + github)], if (sites.len() > 0) [#fa-link #link("https://" + sites.at(0), sites.at(0))], if (sites.len() > 1) [#fa-link #link("https://" + sites.at(1), sites.at(1))], ) // 正文 body } // Section #let section(title, body, icon: none) = [ == #if (icon != none) { icon } #title #body ] // 事件信息 #let event-info(title, time, ..body) = context { let par-leading = get-var("par-leading") grid( columns: (auto, 1fr), align: (left, right), row-gutter: par-leading, // 第一行标题和时间,时间的颜色调灰 title, text(fill: rgb(90, 90, 90), time), // 后面 n 行正文 ..body.pos().map(it => grid.cell(it, colspan: 2)), ) } // 教育 #let education(..body, school: "学校", major: "专业", degree: "学位", start-time: "开始时间", end-time: "结束时间") = event-info( [*#school* · #major · #degree], [#start-time \~ #end-time], ..body ) // 工作 #let work(..body, company: "公司", job: "职位", start-time: "开始时间", end-time: "结束时间") = event-info( [*#company* · #job], [#start-time \~ #end-time], ..body ) // 项目 #let project(name, ..body, time: "", github: false, bv: none) = { let proj-title = if (github) [ #fa-github #link("https://github.com/" + name, [*#name*]) ] else [ *#name* ] let bilibili-link = if (bv != none) [ · #fa-bilibili #link("https://www.bilibili.com/video/" + bv + "/", bv) ] event-info([#proj-title #bilibili-link], time, ..body) }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/040%20-%20Zendikar%20Rising/001_Episode%201%3A%20In%20the%20Heart%20of%20the%20Skyclave.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: In the Heart of the Skyclave", set_name: "Zendikar Rising", story_date: datetime(day: 02, month: 09, year: 2020), author: "<NAME>", doc ) Nahiri studied the rising Skyclave before her where it floated vast, imposing, and ruined. She remembered when it was beautiful. She stood on one of the impossible precipices of Akoum, a jutting of rock extended like a long, gravity-defying finger. A lava field was spread out before her feet, and the hot air carried the scent of molten metal. Ancient kor strongholds like this one had begun appearing all over Zendikar in the aftermath of the war with the Eldrazi. Suddenly, these grand, crumbling structures were revealing themselves after being lost for centuries. As they rose, so did the secrets they carried within. #figure(image("001_Episode 1: In the Heart of the Skyclave/01.jpg", width: 100%), caption: [Mountain | Art by: Chase Stone], supplement: none, numbering: none) Nahiri smiled. With those secrets, she was going to change the world. "I remember you," she told the Skyclave floating in front of her, "and all of your power." Now it was just a simple matter of reaching the ruins. Nahiri raised her arms, eager to begin stone crafting, eager to climb. But she was too focused on looking up, looking ahead. She didn't notice what was happening below. She'd foolishly thought that defeating the Eldrazi had slowed the chaos of Zendikar. So she didn't see the Roil begin. It started as bubbles in the lava field. Like a monster awakening, it began quietly and quickly became undeniable. What was first a murmur became an earsplitting roar as the Roil shook the earth, traveling up through the slender stone ledges, filling the air with raw heat and ash so thick it made Nahiri's breath catch. There was an earth-shattering #emph[crack] and, suddenly, the rocky ledge under her feet crumbled. She fell. "No," she hissed as she plunged. "NO!" She was the master of lithomancy, the guardian of this plane, and she would not be undone by a simple earthquake. With one smooth motion, Nahiri twisted in the air and stretched out her arms, calling on the stone that was an extension of herself. And the stone responded. Her freefall slowed to a stop midair, until she was floating. She took the chaotic swirl of magma and rocks below her and bent the elements to her will. Her will—not the Roil's. She gathered that power, that raw energy around her, and used it to create. She twirled streams of lava, loose rocks, and askew hedrons with her lithomancy, moving like a dancer. With a few snaps of her wrists, a pillar began curling upward. Nahiri hovered above it, traveling up with the pillar as it shot into the air, growing taller and taller until the Roil came to a shuttering stop. Only then did Nahiri alight down on top of her creation, even closer now to the Skyclave. She smirked at the treacherous ground below her. "I win," she said and tried to feel pleased by the victory. But it was a bitter win. The Roil was a symptom of a deep sickness in Zendikar. A sickness that Nahiri had inadvertently helped spread. And lately, the guilt of her failures haunted her. The stone always told her when another planeswalker was near. But Nahiri didn't turn when she felt the stone hum their warning. There was someone behind her on this pillar in the sky. "Akoum is still as beautiful~and unpredictable as ever," Nissa said, coming up beside Nahiri, staff in hand, and peering down at the lava field. "Nothing I can't handle," Nahiri replied. She didn't know if that was true, but she wasn't about to admit it. "It's not that. I~this place~" Nissa stammered. Nahiri raised an eyebrow as the diminutive elf struggled to find words. Nissa took a deep breath and said, "What I mean is, I grew up with the Roil. It's not something you can tame." "You don't know me, then," said Nahiri, with a prick of anger. Nissa raised a placating hand. "I meant no offense. I saw you during the battle with <NAME>. How you command the stone. You were amazing." "You were there?" Nahiri asked, uncoiling a bit at the compliment. "Oh, yes, the tree. I remember." Nissa flushed with embarrassment. That encounter did not end well for the ancient tree of Ravnica. Nahiri redirected her gaze back up toward the Skyclave. "There are some battles I prefer to never fight again." "Yes," Nissa said, "and some battles that still need to be fought." She was calmly studying Akoum stretched out before them, vast and tumultuous, but her voice was thick with emotion. "Why did you ask me to come here, Nahiri?" "When I was young, this land was peaceful. There was none of #emph[this] ." Nahiri gestured at the ground, wrinkling her nose in disgust. Far below, there were bubbles rising from the lava again, heralding another earthquake from the Roil. "The Eldrazi caused an unspeakable amount of damage to this plane." Guilt swelled in Nahiri again. She should have never listened to Ugin and Sorin. She should have found a different plane to trap the Eldrazi in millennia ago. "Yes," Nissa said. "I can feel Zendikar's hurt. It haunts me." She stared at something far in the distance, but her face was full of grief. "I might have a solution," Nahiri replied, inclining her head toward the Skyclave. "Something that will heal Zendikar." Nissa blinked. "You do?" she blurted in surprised, and then awkwardly added, "Sorry, I mean, you're not exactly known for healing. After what you did on Innistrad~" Nahiri raised an eyebrow. "Says the person who set the Eldrazi free." "I didn't—" The elf stammered, but Nahiri raised a hand. "We've both done things that have caused great damage. Let's try to undo some of it." Nissa blushed and nodded. "Why now? I mean, you're old enough~" #emph[To remember when this Skyclave was built] , Nahiri thought. Nahiri hesitated. "No matter how far I've traveled," she replied, finally, "or how long I've lived, this place has always felt~feels~" "Like home," Nissa said, quietly. Nahiri's lip quirked upward. "Exactly." She pointed to the Skyclave before them. "Our answers are up there." She smiled mischievously. "Shall we race to the top? Best Zendikari wins." Nissa didn't respond. She just broke into a sly smile, stretched out her hands, and shot long thick vines upward. The brambles streamed toward the Skyclave, almost too quick for the eye. But not faster than Nahiri. In a blur of movement, she used her lithomancy to create a stairway, and then she was running almost as fast as she crafted, grinning madly. She glanced back and saw Nissa struggling to keep pace, slowly falling behind, and laughed. Plants were no contender in this place of stone. Nahiri didn't make many mistakes, and she rarely repeated them. The benefits of millennia of experience. But the Roil, the damn Roil~ The ground began to shake again, and the vibrations swelled louder and stronger until Nahiri's staircase cracked under her feet. She sprinted faster, but she was not fast enough. The stairs crumbled and suddenly, Nahiri was falling again. She reached out to the stone, preparing to quell the Roil again, when something caught her around her torso, stopping her fall. "Got you," Nissa murmured. Her hand was outstretched and the other was curled tight around her staff. Nahiri looked down to see that she was saved by a vine. Silently, she seethed as Nissa's vine lifted her up and placed her gently on a makeshift ladder of brambles. "Thanks," she said, not meeting Nissa's eye. "Shall we try again?" Nissa asked, nervously, staring at her hands. "Best Zendikari wins?" "No, let's just go," Nahiri said, anger seeping into her voice. They climbed in silence with Nahiri swallowing down her growing guilt with every step. She had neglected her home for too long. #figure(image("001_Episode 1: In the Heart of the Skyclave/02.jpg", width: 100%), caption: [Nissa of Shadowed Boughs | Art by: <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The first thing Nissa thought when they finally reached the Skyclave: #emph[wow] . Even broken, neglected, and hidden for centuries, there was still a breathtaking beauty to the floating fortress. All around her, there were tall pillars and archways, partial ceilings with intricately carved patterns, elaborately tiled floors that mosaicked into pictures. Of course, there were floating rocks, cracked stonework, and ruined edifices, but it was clear to Nissa that this place had once been a beacon of civilization. The second thing Nissa thought: #emph[it's going to take years to find anything here.] Now that they had made it, she realized just how #emph[big ] the Skyclave was. Though they were standing in an ancient courtyard of sorts, Nissa could see a dozen different archways and entrances leading into the belly of the fortress. "Thousands of people must have lived here," Nissa said. "Tens of thousands," Nahiri said, coming up beside her. Nissa hesitated, worried that the question she wanted to ask would annoy Nahiri, that it would shatter any chance of forging a bond with this self-assured, ancient kor. Not that Nissa was particularly good at making connections. It seemed the harder she tried to reach out to someone, the larger the mess she made of things. She wished she were more like Gideon with his cool confidence and steady charm. #emph[Well, what would Gideon do? ] she thought. #emph[Start acting like him if you want to be more like—.] #emph[Like he was.] And suddenly, the grief of his death hit her in a fresh wave. #emph[Gideon wouldn't hesitate.] So, Nissa took a deep breath and asked, "Nahiri, how are we going to find what we need in such a vast place?" Nahiri's lips quirked in amusement. "We start looking." She began to walk ahead, jumping nimbly over the places where the floor cracked or there was simply a hole to the sky. "And what exactly are we looking for?" Nissa asked, hurrying to catch up. Nahiri hesitated. "I'll know it when I see it." Nissa's heart sank. "You don't know?" Nahiri opened her mouth to answer, but the damned Roil would not be silenced. Once again, waves of disruption shook the Skyclave. Nissa stepped back quickly as the ancient stones around her began to shift and crack. She thrust out her staff, ready to create a safety net of vines. But Nahiri was quicker. She spread her hands and held the fortress together with what looked like a sheer force of will, though Nissa knew lithomancy helped. When the rumbling stopped, Nahiri scowled as if the Roil were a personal attack. "I don't know exactly what we seek," she said, striding ahead, anger lacing her voice. "The ancient kor weren't exactly #emph[descriptive] in their texts"—she stopped suddenly in the middle of a vast mosaic in the center of the courtyard. She squatted and placed a hand against the floor. "The stones will know more." Nahiri closed her eyes, and Nissa waited, unsure of what to do. From where she stood, she couldn't tell what the tile mural was supposed to be. #emph[Jace would know] , she thought, but then quickly shook the thought away. She didn't want to think about Jace or the battle with <NAME> and its toll on Ravnica or the shattered state of the Gatewatch or Gideon's death or Chandra. Especially not Chandra. After a minute, Nahiri opened her eyes and rose. "All the best things are hidden in the heart," Nahiri said with a smirk. She pointed to a particularly dark and forbidding archway. "That looks like a promising place to start. Let's go." "How will we know if we're on the right path?" Now that Nahiri had moved away from the center, Nissa could see that the mosaic depicted a sun, with rays shining out from the center. Or something like a sun. Nahiri was already far ahead, but she called back, "When something tries to stop us from getting past." Nissa halted, heart pounding with unexpected panic. Suddenly, this expedition seemed like a terrible idea. What if her attempts to help Nahiri only ended up hurting Zendikar again? Like so many of her mistakes in the past. Once again, she was following someone else's lead. When was that going to change? #emph[What would Gideon do?] "He'd help however he could," Nissa whispered to herself, "but he wouldn't follow Nahiri blindly." Zendikar was her home. Not Ravnica or any other plane. She belonged here and was the voice of its soul. She had a responsibility to care for it and all the living things in this world. So, Nissa took a steadying breath, tightened her grip on her staff, and followed. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) From the outside, the old Skyclave looked flat and wide, like a stone archipelago floating in the air. From the inside, it seemed like it was looming and bottomless. Nahiri kept a hand on the wall as the passageway went down and down, sometimes becoming steps, sometimes revealing other passageways with untold mysteries. But Nahiri didn't fall for the Skyclave's bait. The stones under her hand whispered of a great power below, and Nahiri was going to be the one to find it and claim it. Behind her, Nissa moved almost silently, like the child of the forest that she was. Occasionally, her staff clicked against a stone or she would gasp softly when a stray light found its way in through a crack and illuminated their surroundings. They continued traveling down until they came to the main meeting halls of the ancient kor, where they would gather in the thousands and show off their wealth and artistry. And the halls reflected it. Literally. When the tiles caught the sunlight that snuck in, they sparkled like rare gems. The ceilings were breathtakingly tall, and the carvings on the pillars intricate and detailed. Yes, it #emph[was] beautiful, Nahiri admitted to herself. But it was also a painful reminder of all this plane had lost. Especially as the Roil kept making the ancient fortress tremble as they traveled within its belly; a constant, pestering reminder that Nahiri, the guardian of Zendikar, had failed to protect her home. So, Nahiri didn't look too closely at the grand halls or the beautiful carvings. She just kept moving forward, always looking ahead. The passageway halted abruptly in front of a pair of huge, but collapsed, doors. "Looks like a dead end," Nissa said, walking up and putting a hand on the door. "Maybe for you," Nahiri replied and widened her stance. "Stand back." With one powerful motion, Nahiri brought her hands together with a #emph[clap] , and the massive doors flew apart, booming as they slammed against the stone walls to the right and left of them. "Let's go," Nahiri said and strode toward the threshold. Nervousness pricked at her, and alarmed whispers followed her from the stones. Beyond, there was a deep darkness, full of the unknown. But Nahiri would not be stopped. Not now. "Wait," Nissa shouted from behind her, "there's a fe—" Something fast and hard slammed against Nahiri and pinned her to the wall. She groaned but immediately commanded the stone wall behind her to punch back. It did, with a sharp, jabbing column, smashing into whatever was holding her and causing it to groan loudly and let go. Nahiri rolled to the side, coming to her feet in a single fluid motion. She clenched her hands and bared her teeth. Now she was angry. With barely a thought, Nahiri summoned seven swords, radiating heat and glowing red as if just drawn from a forge. They floated around her, giving Nahiri an ungodly halo. And casting some light on her attacker. Before her, heaving and furious, was the biggest felidar she had ever seen. Its hairless body was covered in razor protrusions; its massive antlers swept back over its head. Its talons clicked as it prowled in front of her; its wet, colossal canines slick with saliva in anticipation of fresh meat. "Like hell," Nahiri growled and sent all seven swords straight at the creature's heart. The felidar reeled back, but between its paws and its armor-like protrusions, it managed to deflect the worst of the attack. It snarled and lunged at Nahiri with unnerving speed, mouth wide. But before it collided with her, the felidar was halted mid-leap. It took a moment for Nahiri to realize that Nissa was standing between her and the foul beast, shoving it back with more strength than it seemed possible. "No you don't," Nissa grunted as brambles began to wrap themselves around the felidar. But the beast shook and reared up, swiping its massive paws. One connected with Nissa's shoulder and sent her flying with a shout and a harsh #emph[thud.] But Nissa had bought Nahiri just enough time to craft chains of stone and snake them around the angry, distracted felidar. With a yell, Nahiri yanked her arm back, and the stone chains snapped to tightness and pinned the monster to the floor, "Eat this," Nahiri growled as she leaned low, spreading her fingers. Behind her, seven radiating swords appeared again. With a smirk and a flick of her fingers, Nahiri drove all seven blades into the felidar, making certain to hit its vulnerable points this time. The creature shrieked once, a long and terrible cry, and then went limp. Nahiri walked over to where Nissa was getting up from the ground and offered a hand, pulling her up to her feet. "It was like the felidar was waiting for us," Nissa said, rubbing her shoulder. "It probably was," Nahiri said, as she crafted another glowing sword for light. "It was guarding something." She grinned, sending the sword down the darkened corridor before them. "Let's go find out what." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) That uneasy feeling that they were somehow on the wrong path didn't leave Nissa the further they traveled in the Skyclave. Despite Nahiri's reassurances, she still wasn't sure. She could hear the plane's life force humming to her. It also sounded unsure. Or maybe that was just her? At least they didn't run into any more hungry felidars on the way. The dark passage they traveled went down and down. The Roil flaring up now and then, dogging their steps. Until it didn't. The Skyclave opened up into a cavern-like chamber. There were long, thin, golden-tiled arches that could serve as walkways, crisscrossed and intertwined like a spider's web. The chasm below the walkways had no visible bottom, though here and there, stray shafts of light managed to slip through at sharp angles. The air smelled stale and musty, though to Nissa's relief, there were moss and ferns in some nooks. Nissa smiled as she moved to a cluster of ferns growing in an unlikely clump on the side. This was the Zendikar she knew and loved, even here in this strange, dead, kor stronghold. Nahiri, on the other hand, was frowning, clearly unsure of where to go next. Because it was no longer a straight path forward, Nissa realized. Nahiri crouched down and placed a hand on the floor, closing her eyes. She stayed like that for a long minute. Finally, Nahiri scowled. "The stones aren't saying which way to go." "Why not?" Nissa asked. She didn't think stones could deny Nahiri anything. She shrugged. "We're close now. Might as well choose a path at random." Nissa hesitated. This definitely didn't feel like the right solution. #emph[What would Gideon do?] "No," Nissa said, quietly. "What?" Nahiri turned to look at her, her face full of surprise. "Wait—" Nissa crouched down to one of the ferns. Its leaves were as large as she was, but its flowers were tiny, delicate, and blue. "How is it possible for plants to thrive here?" Nahiri asked, coming up behind her. Nissa smiled. "You'd be surprised at how many things thrive in unlikely places on this plane." "How—" Nahiri began to speak again, but Nissa tuned her out. She rested a hand on the top of the fern, like a parent's hand on the head of a child. She closed her eyes and felt its life under her fingers, felt its struggle and its pride in surviving in such a foreboding place. Nissa smiled at that strength and that pride. And she called it forth. She heard Nahiri give a gasp as the elemental emerged into existence. It was a tall thing, twice her height, green and vibrant as its life force, its head a mass of fronds with small chains of blue flowers entwining its arms and neck. "What is #emph[that] ?" Nahiri said, taking a step back. "A friend," Nissa said as the elemental knelt so it was almost eye level. She wasn't about to explain that before she became a planeswalker, before she joined the Gatewatch, these were the first creatures to accept her as she was. She grasped the elemental's six-fingered hand, saw its love for her in its eyes, and for the first time in a long time, Nissa felt like she belonged. "We need to find the Skyclave's heart," Nissa said to the elemental. "Can you help us?" The elemental blinked slowly, then with a groan, raised itself up to its full, towering height and began leading Nissa by the hand. "Let's go," Nissa called over her shoulder. She caught sight of Nahiri gaping at them and had to suppress a laugh. The fern elemental led them through the maze of archways, pausing only when the Roil struck again, and Nahiri had to use her power to keep the arches whole. But it never hesitated for long, as if something was beckoning it forth through this relic of a fortress. Eventually, they came to a landing, a small platform with a narrow bridge to a darkened entrance beyond. Nissa moved to cross it, but Nahiri grabbed her sleeve. "Wait"—she hissed and pointed—"look." Nissa followed Nahiri's finger up and on the ceiling above was a giant geopede suspended by some invisible force. It writhed its long carapace against its unseen restraints, giving the planeswalkers below an unadulterated look at its hundreds of squirming legs. Nissa shuddered. Geopedes reminded her too much of snakes. A snake with little snake legs. "Any idea what will spring the trap?" "No," Nahiri said, "send the Fern Thing first." "Don't call it that," replied Nissa, tersely. Why could no one understand that elementals were living, feeling creatures? That they weren't just tools to be summoned, used, and die on command? No, Nissa wasn't going to send it to its death knowingly. She turned to the elemental. "Can you disarm it?" she asked, nodding up at the trap. The elemental looked doubtful, its huge, bright brown eyes looking between her and the squirming creature above. "I won't let it harm you." Nissa raised her hand up, sending vines to create a makeshift net under the geopede. Carefully, the elemental reached up its giant, leafy hands and tapped the underbelly of the geopede once. The creature hissed and wriggled. For a moment, the invisible trap held. Then it didn't. And the massive creature fell. As soon as it hit Nissa's net, though, she closed her fist, and the vine snapped around the monster. She pulled her arm back, and the vines yanked the geopede to the ground, slamming it into the floor. The monster shrieked and twitched. Then it went limp and expired. Nissa grinned. #emph[Take that, not-a-snake.] She didn't expect, however, for Nahiri to smash it again with a stone fist. Nissa and the elemental jumped back in surprise. "What?" Nahiri asked, grinning. "This is Zendikar. Everything born on this plane is hard to kill." For a moment, Nissa was about to argue. She couldn't help but think of her first home on Bala Ged and how most of her tribe and all that she knew was wiped out so easily by the Eldrazi. Then she realized Nahiri was talking about them—Zendikar's two planeswalkers. Nissa smiled. Maybe they#emph[ were] going to heal this plane. Together. "True. Let's go take this Skyclave's heart." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("001_Episode 1: In the Heart of the Skyclave/03.jpg", width: 100%), caption: [Inscription of Insight | Art by: Zoltan Boros], supplement: none, numbering: none) The heart of the Skyclave was aglow. Ancient runes covered every surface, every inch of the stone walls, floors, and ceiling. The runes shone with a golden light that pulsed with their footfalls as the two planeswalkers entered the room. Nissa's fern elemental—or fern monstrosity as far as Nahiri was concerned—trailed behind them. But it wasn't the runes that interested Nahiri, it was the dais in the very center of the room, in the heart of the heart. And in the middle of that, there was a small tile, glowing like a star. "What is that?" Nissa asked, by her side. Nahiri smiled. This was promising. Very promising. And it filled her with more hope than she felt in a long time. "A key," she replied "A key for what?" "To unlock the true power we seek." Nissa frowned. "I thought you said that we'd find something to heal Zendikar here." "I said the ancient kor texts are not always clear," Nahiri started, briskly, "but the object we seek is both powerful and dangerous. It's~an orb. It roughly translates to #emph[lithoform core] . And it's the last one in existence." The fern elemental shifted uncomfortably, and Nissa looked skeptical. "How do you know that?" she asked. "Says so," Nahiri said, walking up to the dais. The runes flashed brighter, more intently as she drew closer, as if to beckon her on. "In the writing around us." Nissa trailed her. "You can read the runes?" "Of course," Nahiri replied, "I #emph[am] an ancient kor." "Oh. Right." Nissa blushed and hung back with her Fern-Thing as Nahiri approached the dais. She heard Nissa whisper to it, "Stay close to me." At the foot of the dais, the runes around Nahiri flared once, then dimmed. Before her, the key glowed brightly, almost welcoming. But she didn't reach for it yet. Instead, she placed her hand on the cool marble on either side of the key and listened to the stones, felt their power, searched for any traps. She found none. So, slowly, gently, Nahiri reached for the key and picked it up. It shone brighter in her hand, greeting her like a long-lost friend. "Well, now that we have the key," Nissa said, "I suppose we need to find the lock." "Yes," Nahiri said, head tilted in thought. "Runes say Murasa. In a Skyclave there." "It's never easy, is it?" Nissa said with a sigh, "What else do your runes say?" "There's a little bit of the core's power in this room," Nahiri said, "and also, in this." She held up the key. "I—" She stopped. She felt the faint rumbles of the Roil again. She'd been paying attention, feeling the earth though she was miles above it. Learning to predict the unpredictable episodes. Nahiri gritted her teeth. The Roil, the damn Roil. From her expression, she could see Nissa felt it too. "Show me," Nissa said. So, Nahiri spoke the words, the ancient language she hadn't used in millennia. She felt the power stir under her feet, felt it rising, answering her call. Then with that freshly drawn power, she set it loose toward the shifting and shaking earth. There was a blinding flash in the room, and Nahiri shielded her eyes. Far below, she felt the Roil hesitate, then, like a monster pierced through the heart, the Roil shuddered and stopped completely. She heard grinding noises around her and felt the Skyclave knit itself back together, though not completely. The runes hadn't contained #emph[that] much power. But still, this ancient and broken fortress was mending itself. Happiness bloomed in Nahiri, and she clutched the key to her chest. She had found it. She had found a way to heal Zendikar. Then, behind her, she heard the Fern-Thing scream. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "No!" Nissa shouted. She felt the elemental's pain before she understood what was happening. Before she saw its green limbs twist and wither, before she heard it give a heart-tearing scream, before she saw its bright eyes go dark and it crumble away into ash. Nissa reached out with her power, with her hands, trying to stop the elemental from dying, but it was no use. She was left with fistfuls of ash. "What did you do?" Nissa yelled at Nahiri. "What?" Nahiri asked, turning around. Nissa saw that she was holding the key to her chest and #emph[smiling] , like she just won a battle. "It stopped the Roil." "You murdered the elemental!" "Your plant?" #emph[My family.] Nissa didn't say. #emph[A piece of Zendikar. ] Because the elementals #emph[were ] Zendikar, and if quelling the Roil with the core meant their death, then Zendikar was in mortal danger. Nissa stared at the ashes in her hands, felt anger and grief well up inside her. Over this mistake. Over all her mistakes. #emph[What would Gideon do?] "He wouldn't let this continue," Nissa whispered to herself, straightening, squaring her shoulders back. "What?" Nahiri asked, puzzled. "Is this your solution?" Nissa asked. She wasn't shouting anymore, but there was a quiet fury in her voice that made Nahiri pause. "Look around you—this Skyclave is healing. The Roil stopped below us, and the land is calming. People will be able to rebuild here!" Nahiri said gesturing at the Skyclave's repair. "At the expense of Zendikar's #emph[life] ," Nissa retorted. She reached out her awareness to the plants and moss that grew in the corners and cracks of the Skyclave, but they didn't respond. Nissa knew then that everything that lived in that ruined fortress was dead. "You don't know what Zendikar was like," Nahiri said, her voice tight with anger, "you don't know how stunning and bright its people and cities used to be." "And you don't know what Zendikar is like #emph[now] . It's still beautiful, Nahiri"—Nissa reached out her hand—"give me the key." Nahiri didn't respond. Instead, she set her jaw, widened her stance, and spread her arms. Nissa didn't think, she just reacted—dodging the pillars that suddenly jutted out of the floor, avoiding them by inches. She didn't think as she released a mass of vines to deflect the stone swords that came flying toward her. She didn't think as she commanded the vines to snake around Nahiri's ankles and pull her to the ground. Nahiri fell with a groan and a curse. But before Nissa could attack again, the other planeswalker raised a wall of stone between them that Nissa couldn't breach, despite creating lashing brambles as thick as tree trunks. Her brambles hit the stone uselessly over and over. After a few minutes, the wall between them turned to glass, revealing a bruised and seething Nahiri on the other side. "I can't just stand by and let this plane tear itself apart!" Nahiri shouted, "I am the guardian of Zendikar!" Nissa looked at the other planeswalker and realized she was a fool to hope that this ancient, uncaring person could help heal her home. "So am I." #emph[What would Gideon do?] He would get help. So, Nissa planeswalked away. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("001_Episode 1: In the Heart of the Skyclave/04.jpg", width: 100%), caption: [Jace, Mirror Mage | Art by: <NAME>], supplement: none, numbering: none) Ravnica, the plane of cities. Or rather, one large, world-spanning city. Nissa could see the beauty in it: the elegant floating towers and marble-paved streets, the autumn trees contrasting with the gray skies. She could admire the beauty and still remember its war-ravaged streets. Still remember how the spirit of Vitu-Ghazi fell. It was best not to be recognized, she reasoned, so she didn't linger long on the streets before arriving at Jace's home. She was led to Jace's inner sanctum, with nothing more than a polite bow and a dark look from the guard at the door. She supposed she deserved the anger of Ravnica's citizens. Though, it stung. Maybe Chandra was right. Maybe she #emph[was] a walking disaster. Nissa didn't want to think about Chandra. Especially now that she needed Jace's and the others' help. Inside the sanctum, the room was brimming with books and scrolls, magical objects that she had no name for scattered around the massive place. Light streamed in from tall, arched windows, but there were still dark corners. It took a moment for Nissa to find Jace perched up on a ladder, against the furthermost wall, reading a book from the top shelf. "Be with you in a moment," he called. Nissa knew that "a moment" could mean a few seconds to an hour with Jace. But she was too nervous to interrupt him, so she waited. "Nissa!" Jace said when he finally caught sight of her. "Why didn't, I mean, I thought you wouldn't, I mean, why"—he stopped himself, slid down the ladder, and came toward her—"I mean, I'm happy to see you're all right." He reached out, remembering at the last second she didn't care to be touched. He withdrew his hand and gave her a warm smile instead. This caught Nissa by surprise. She thought he'd be furious with her, like the rest of Ravnica. But relief that he wasn't, that he was pleased to see her, washed over her as he led her to a table. "Come, sit," Jace said. "What can I do for you?" Nissa wasn't sure how to begin, so she just said it—"Zendikar's in trouble." "The Eldrazi?" Jace asked, alarmed. "No, no," said Nissa quickly, "nothing like that. It's Nahiri." "Nahiri," Jace said, brows knitting together. "The #emph[other] guardian of Zendikar?" "Yes," said Nissa. Suddenly, she felt exhausted. She wasn't sure how she was going to explain this all to Jace, who had never felt a connection to a life force. "She's trying to heal the plane." "Yes, you mentioned that she asked to see you. But I don't understand. That's what you want, right?" "Yes, but there's this ancient orb—" "Elven or kor?" "Kor. But—" Jace was already moving to the shelves. "I think I have a scroll about that—" "Jace! Listen," Nissa said, with more force than she meant to. "Please." Jace paused and looked surprised, but he sat back down and nodded. Nissa felt a small flush of pride at this victory. Jace never listened to her. Maybe channeling Gideon was working after all. Nissa recounted what happened in the Skyclave in Akoum, what Nahiri told her about the lithoform core, and what it did to the fern elemental. Jace listened quietly, intently. She had to pause and take a few steadying breaths as she described the elemental's death. "I know you don't have a connection to elementals," she said, "but they're important to me. Not that the Gatewatch isn't~" She couldn't meet Jace's eyes as she said this. "No, I don't truly understand elementals," Jace said, "but I know they are important to you. How can we help?" Nissa exhaled, relieved. She felt a wave of gratitude that though she routinely made a mess of potential friendships and relationships, she could still rely on Jace and the others when she needed them. "Well, I need Nahiri to destroy the lithoform core when she finds it. And I don't know how to convince her to do that"—Nissa's shoulders hunched slightly—"I miss Gideon. He'd know how to reason with an ancient, angry stone crafter." Jace's face was a complex array of emotions. "I miss him too." "What should I do, Jace? I don't think I'm strong enough to fight Nahiri on my own if I had to." Jace steepled his fingers. "If we bring the lithoform core here—" "No!" Nissa said, half rising out her chair. Jace stared at her in surprise, and honestly, the force in her own voice surprised Nissa, too. "You haven't seen the damage it causes, Jace." "Yes, but if we can study it," Jace said, rising and moving toward his shelves again. "And who will be your test subjects?" Nissa asked with growing alarm. She was losing him. "I suspect the lithoform core is channeling Zendikar's power—" "Jace!" "Then its power can become malleable—" "It's not that simple." "Perhaps based on the wielder?" Jace plucks a scroll from the shelves. "This should—" "You're not listening!" Nissa shouted, sending out a vine to knock the scroll from Jace's hand. He stepped back, surprised. Nissa could feel her face flush with anger, and her heart thrummed against her chest. This was going all wrong. She lost the Gatewatch and she was going to lose Zendikar's elementals. Her families. #emph[What would Gideon do?] "Nissa, what are you thinking?" Jace asked, standing before her, trying to catch her eye. #emph[What would Gideon do?] Gideon would seize the moment. "I will not lose both of my families," Nissa said as her expression turned into something more than determination. "I'm going to protect my home. With or without the Gatewatch's help." "Wait—" Jace began, but Nissa didn't wait. She was done waiting. With one breath, one movement, one thought, Nissa planeswalked back to Zendikar. The only place she'd ever belong. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Jace stood in his now empty sanctum and planned. He should have listened better, convinced Nissa to stay, to rejoin the Gatewatch. Guilt gnawed at him for the secrets he was keeping about <NAME>. He was the only one who knew the truth. That the ancient, terrible dragon was still alive. And every day Jace kept that secret was a lie of omission to his friends. But he could make it up to them. He would. He considered what Nissa said about the core and wondered if it was somehow connected to the Roil. If it was, what could Nahiri do with such power? What could the Gatewatch do? A great deal, Jace realized. So, he planned—knowing that soon he'd be on Zendikar.
https://github.com/andymeneely/examify.typst
https://raw.githubusercontent.com/andymeneely/examify.typst/master/examples/quick/quick.typ
typst
MIT License
#import "@local/exam:0.1.0": * = Final Exam, #total_points() points and #num_questions() questions // <show_solutions> //uncomment for answer key Name: #blank(4cm) #question[ #points(2) Hello, #fill_in_blank(3cm, [world!]) ] #question[ #points(3) Speak friend and enter. #solution(height: 2.5cm, [melloch]) ] #question[ #points(2) #choices[ + #correct[Right] + Wrong ] ]
https://github.com/akagiyuu/math-document
https://raw.githubusercontent.com/akagiyuu/math-document/main/integral/(%5Cfrac%7B1-e%5E-x%7D%7Bx%7D)%5E2.typ
typst
#set text(size: 20pt) $ integral_0^(infinity) ((1-e^(-x))/x)^2 dif x &= integral_0^(infinity) (integral_0^1 e^(-x y) dif y)^2 dif x \ &= integral_0^(infinity) (integral_0^1 e^(-x y) dif y)(integral_0^1 e^(-x z) dif z) dif x \ &= integral_0^(infinity) integral_0^1 integral_0^1 e^(-x (y + z)) dif z dif y dif x \ &= integral_0^1 integral_0^1 integral_0^(infinity) e^(-x (y + z)) dif x dif z dif y \ &= integral_0^1 ln(y+1) - ln(y) dif y \ &= lr(((y+1)ln(y+1) - y - y ln(y) + y) bar)_0^1 \ &= lr(((y+1)ln(y+1) - y ln(y)) bar)_0^1 \ &= 2 ln(2) + lim_(y->0) y ln(y) \ &= 2 ln(2) $
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/019%20-%20Magic%20Origins/002_Liliana's%20Origin%3A%20The%20Fourth%20Pact.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Liliana's Origin: The Fourth Pact", set_name: "Magic Origins", story_date: datetime(day: 17, month: 06, year: 2015), author: "<NAME>", doc ) #figure(image("002_Liliana's Origin: The Fourth Pact/01.jpg", width: 100%), caption: [Art by Chase Stone], supplement: none, numbering: none) = Gift of the Raven Man A man died somewhere nearby—too near—wasting his last breath on an inarticulate cry that only his killer and <NAME> could hear. Liliana hurried away from the sound, putting as many twisted trees between herself and the killer as she could. She'd grown up walking the tracks and trails of the Caligo Forest and knew them as well as anyone—certainly better than any of the soldiers fighting and dying under its branches now. Even at night, the woods felt like home to her, with owls and nightingales calling softly among the dark boughs. But on this night the forest had become a battlefield, and the only calls were the screams of the dying and the harsh croak of ravens squabbling over the flesh of the dead. #figure(image("002_Liliana's Origin: The Fourth Pact/02.jpg", width: 100%), caption: [Art by Karla Ortiz], supplement: none, numbering: none) She stopped and listened, straining her ears for any sound of pursuit, some indication that she'd been detected. No human soldier came behind her, she was sure—just one raven hopping and fluttering from branch to branch behind her, waiting for her to die. "Not tonight, bird," she whispered. "Josu is depending on me." The thought of her brother—delirious with fever as he lay on death's door back at their father's house—quickened her step, and soon the sounds of battle faded behind her. If no one else would brave the forest to find the esis root that would cure him, then Liliana would. "I'm ready," she told the bird. "I'll make him well, and together we'll crush these raiders." The raven croaked. "Don't you laugh at me." She stooped to the ground and picked up a pebble to throw at it, but when she lifted her head the bird was gone. In its place stood a man, his features hidden in the shadows of his cowled coat. She threw the pebble anyway; it tapped his shoulder and fell back to the ground. He drew back his hood as Liliana fumbled with the knife at her belt. He was tall and had a noble air, dressed in a suit of black and gold that showed no signs of his passage through the trees and brambles. White hair crowned his head, tousled by his hood, but the hair at his temples was black and swept back over his ears. His eyes—strangely gold, like the embroidery on his clothing—seized and held her gaze. "I'm not here to harm you, <NAME>," the man said. "You know my name," she said, gripping her dagger. "Somehow that doesn't inspire me with trust." He held up his empty hands. "Your father is our lord and general. Of course I know you." "You've been following me?" "Like you, I'd rather lie low in the woods than end up a headless corpse dragged behind the horses of your father's foes, my skin stretched over their shields and my skull dancing through the trees." #figure(image("002_Liliana's Origin: The Fourth Pact/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) As he spoke, Liliana thought she heard hoof beats in the distance. "I have to go," she said. "But where will you go?" "The glade…" "Where the esis root used to grow?" She scowled. "How did you know…wait. 'Used to grow?'" "You don't know? They burned it." "The raiders?" "Their skin-witches did. It's a circle of ash now, where they chant their rites and raise more soldiers to fight your father." "No," Liliana said. Turning her back on the strange man, she ran, heedless of the noise she made as she tore through bushes and stumbled over roots. She smelled the smoke long before she reached the glade, and stopped her rush when she saw the light of gleaming embers. A raven's wings beat the air behind her, and she turned. The golden-eyed man stood, looking down at the ground. "So much death," he said. Liliana dropped her gaze and started in surprise when her eyes met those of a dead man lying at her feet. Corpses littered the ground—soldiers in her father's colors, black and gold. Some clutched horrible wounds, some carried terrible burns, and some were headless, their skin flayed off their glistening fat and muscle by the skin-witches' dark magic. Not one carrion bird flapped among them. "And without the esis root," the man said, "your brother will be next." "No!" she cried. "I'm not going to let that happen." "No, you're not." The steady certainty of his voice only exacerbated the panic that pounded in Liliana's chest. "There has to be another way," she said. "More esis root…another glade." "You know there isn't another glade." "What are you saying?" Liliana fought the urge to slap the infuriating man. "You know another way to save Josu? What is it?" The man pointed in the direction of the glade. She turned and looked into the trees, where a dim glow of embers smoldered in the darkness. His voice was right behind her, his breath in her ear: "You know." But she didn't know. For years she had studied faithfully at Lady Ana's side, memorizing the healing properties of roots and herbs, learning the signs and symptoms of hundreds of illnesses and the best treatment for dozens of kinds of wounds. Esis root was the only possible cure. "You said the glade was burned, the root gone." "You know more than that." All of her studies, her lessons, the daily routines of crushing herbs and mixing potions—nothing else suggested a possible cure. "Unless…" she murmured. "You know." #emph[Of course!] She nearly jumped at the unexpected thought. Over the years, she had expanded her studies beyond what Lady Ana could teach, dabbling in magic that took a more…direct approach to life and death. All in service to her work as a healer, of course. She knew magic that could turn even a burned and shriveled esis root into a cure for Josu. At least in theory. #figure(image("002_Liliana's Origin: The Fourth Pact/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) But how did #emph[he] know that? "I'm not ready," she said. "I have so much more to learn." "I'm sure Josu will wait while you complete your studies." Liliana swore violently under her breath and pulled away from the man, taking a few steps closer to the burnt glade. He followed her, speaking right into her ear. "You can't afford to wait, <NAME>. You know enough now. You are already a great mage, though you won't admit it to yourself. And you will be greater still, once you embrace your power." Her panic was changing, turning into a heady rush of excitement. She #emph[was ] powerful, but she had always hidden her forbidden knowledge away, afraid of censure. To embrace it, damn the consequences—she had to admit that, like other forbidden things, exulting in her power sounded like #emph[fun.] She wheeled on him, planting a hand on his chest and pushing him back. "How do you know so much about my magic?" She could feel the magic surge inside her, the chill prickle of death's approach. "I suppose both of us are more than we seem," he said. Liliana had always known it: she was more, so much more than anyone had ever seen in her before. And now she would prove it. She felt something inside her break free, like a dark flower blossoming in a deep swamp. Spells came to her mind, weaving together into a desperate, terrifying plan. "Yes," the man said. "You see it now. Esis root is a powerful cure, but it was the safe course. You know a mightier one." She did, she realized with surprise. Stretching out her senses, she felt the power that brewed in all the rot and decay of the nearby bog. She drew the mana into herself with a grim smile, only vaguely aware that the strange man had vanished again. With each step forward, the power that had broken free inside her seemed to blossom a little more, solidifying her resolve. It propelled her, urging her to embrace her strength. A dozen paces brought her out of the sheltering trees and into the clearing. It was now a blasted circle of ash with smoldering embers in a ring around the edge. Terror struggled with fury in her heart as she took in the scene, remembering the peaceful glade it had once been. Three withered crones stood back to back in the center, eyes closed as they sent their spells winging through the wood to the battlefields across her father's lands. Three ghastly sentinels—grisly skulls with dangling bits of flesh, sickly purple light gleaming in their empty eye sockets—floated around the periphery. Six foes, and Liliana stood alone. But Josu's life depended on her, and the power blossoming within her was more than enough. "Hello, ladies," Liliana cooed. One of the floating skulls bobbed toward her, a ghostly shriek rising from its gaping, fleshless mouth. She answered it with a chant of her own, a string of low syllables that echoed in the dead air. A knife of utter blackness shot from her outstretched finger and stabbed through the skull, severing the necromantic energy that gave it the semblance of life, and it tumbled to the ground. The skin-witches opened their milk-white eyes and turned to her as one. Twice more, Liliana pointed, and the two remaining skulls fell into the ash, kicking up little clouds where they landed. "I think you need some stronger bodyguards," she said. Her confidence was building, replacing her fear with cold resolve. She was good at this, she realized. It was so easy, once she embraced it. So much easier than her dreary studies under <NAME>. And it felt so good! The skin-witches began a chant, their three voices speaking as one, and pain danced over Liliana like claws tracing marks in her flesh. She screamed. But she turned her scream into another spell, using the pain to focus her mind. The spell rolled from her mouth like the tolling of a bell, and a deathly chill soothed her burning skin as her magic took shape. Three spectral hands floated up from the ground at the crones' feet, trailing wisps of shadow like ghostly arms. #figure(image("002_Liliana's Origin: The Fourth Pact/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Now it was the witches' turn to howl in pain as the hands disappeared into their chests and emerged from their backs, clutching glowing motes of golden light. Their screams turned to pathetic moans as they sank to the ground, clutching their chests with what little strength Liliana's spell had left them. One skin-witch stretched out a hand toward her and mumbled something that might have been a spell, but Liliana felt nothing. The three spectral hands converged on one spot near Liliana's feet and dived back into the earth with their prizes. With a smirk, Liliana started to bend down, but the harsh croak of a raven behind her startled her and she spun around. One of the corpses she'd seen outside the glade was on its feet now, shambling toward her. "So you cast a spell after all," she called to the skin-witch behind her. "A valiant effort, but I think it was your last." With a deep breath, she focused her will and simply snuffed out the semblance of life that animated the zombie's flesh. Behind her, the witch gave a strangled cry. Liliana looked down at the soldier's body, his torn armor, and his blood-stained uniform. "So much death," she said. She lifted her eyes and met the gaze of the raven perched above her. "And this is just the beginning." At her feet, a golden glow emerged from the ash where the spectral hands had sunk. Sinking to her knees, she plunged her own hand into the ground and seized her prize. When she lifted her hand again, it clutched a shriveled, blackened chunk of esis root, glowing softly gold. It would make a potion far more powerful than what she'd originally planned, infused with the life she'd stolen from the skin-witches. The man had been right—she'd known what to do. Of course she'd known. Cradling the root to her chest, she walked back into the forest toward her father's house. She grinned up at the bird as she passed it. "Thanks, <NAME>." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Promise of the Void The blackened esis root made a potion that glowed gold like dawn warming the morning fog, reassuring Liliana of the life-giving power it held. She cradled it in her palms as she drifted through the clamor of the house, contemplating the light that had come from her dark magic. The servants bowed and backed away as she approached, but quickly resumed their shouting and scrambling behind her. "Cold water!" "New linens!" "Where's that broth?" "Water!" She ignored all the cries, convinced that the elixir she carried would soon enough bring an end to all the worry and commotion. "<NAME> has returned!" one servant called out ahead of her, and at last she looked up. She stood in the hall outside Josu's room. In answer to the servant's cry, <NAME> stepped out of the room and put her hands on her hips, frowning at the vial in Liliana's hands. "That's not esis root," the healer said. Liliana paused, her confidence faltering in the face of her imperious teacher. But then she heard Josu cry out in the room—"Skulls! Skulls floating through the trees!"—and she remembered what she had gone through to make the potion and what was at stake. She straightened her back and met <NAME>'s imperious gaze. "It's better," she declared. Ana scoffed. "I'll be the judge of that. How did you make it? What are the components?" "This is no time for an examination. Josu is dying!" "The administration of curatives is not to be rushed," Ana said, folding her arms over her chest. "Some potions can do more harm than good." Her eyes flicked down to the vial in Liliana's hands and her lips curled. "The witches!" Josu cried from his bed. "No, no, the flames!" "I made it from esis root," Liliana said, "but I enhanced it." "Enhanced it? How?" "The burning!" Josu was screaming, and Liliana could hear the hubbub of servants trying to calm him, to cool his fever, to bring some measure of relief to his torment. "Stand aside, <NAME>," she said. "Josu needs to drink this. Now!" Ana drew herself up, her face reddening. "An apprentice does not address her master that way." Liliana took a deep breath, steeling herself. It was not just power blossoming inside her—she was opening, her mind expanding, her true self coming to the fore. This was her time. Her brother's life hung in the balance. She knew what she needed to do. "Then it's time for my apprenticeship to come to an end," she said. "Your power is no match for mine anyway." "Power? The healing arts aren't about power." "You don't think so?" Liliana laughed. "Stand back and watch." She pushed past the healer into her brother's room and fell on her knees at his bedside. "Stay away from my patient!" Ana snapped. All the long years of her apprenticeship, that voice had commanded instant obedience, and Liliana almost backed away out of pure reflex. But Josu seized her hand and looked at her—no, past her—and everything else faded away. "Josu?" she murmured. "Can you hear me?" "The witches," he said. No longer yelling, he sounded like a frightened child. "They stripped the skin…." Liliana lifted her glowing vial, and its golden light glimmered in Josu's eyes as he stared at it. "Drink this, Brother." She lifted it to his lips. "It will bring you rest." "Don't!" <NAME> made one final protest, but too late. #figure(image("002_Liliana's Origin: The Fourth Pact/06.jpg", width: 100%), caption: [Art by Izzy], supplement: none, numbering: none) The potion filled Josu's mouth, and a gleaming golden drop spilled down his chin. For a moment fear twisted his face and Liliana worried he might spit out the precious liquid, but then he swallowed, and again, and one more time. Then his eyes closed and he settled back on his pillow. His only movement was the slow rise and fall of his chest as he breathed. Liliana smoothed his hair away from his sweaty forehead, and the hint of a smile came to the corners of his mouth. "Liliana," he sighed. Behind her, one of the servants gave a strangled gasp. "He knows her!" the woman said. <NAME> harrumphed. "Fine. You've calmed his sleep. Now you can tell me…." "Lili!" Josu shouted. His eyelids opened wide to reveal two jet black orbs. For an instant, she saw her face reflected in them, but dead—her own eyes rotted away, her skin drawn tight over her bones. He stiffened, his blank eyes staring up at the ceiling. Liliana noticed a blackened spot on his lip—where her potion had dribbled from his mouth. As she watched, he seemed to shrink. His eyes sank back into his skull and his pale skin grew waxy and tight. His cheekbones jutted from his face and his lips drew back away from his teeth. "What have you done, child?" <NAME> whispered. She shouldered Liliana aside and bent over Josu's still form. Liliana drifted to the foot of the bed, her mind reeling as she stared down at her brother. What #emph[had] she done? The potion—#emph[her] potion, brewed by her skill and her magic—hadn't cured him at all. It had killed him. All her efforts…and the result was worse than if she'd done nothing at all. Much worse. <NAME> stood up from the bedside, her face grave, and began shooing the servants out of the room. Liliana sat on the edge of the bed next to her brother, pressing his cold, rigid hand between hers as if she could restore its warmth. Then his hand wrenched free of her grasp and seized her throat. Sharp nails bit into her skin. "So much pain…" Josu said. He sat up, bringing his face right next to hers. "Where have you sent me?" he asked. The foul air of his breath stung her nostrils even as she fought to inhale, trying to pry his fingers off her neck. "So…much…#emph[pain] !" he screamed, and threw Liliana against the wall. She crumpled to the floor as <NAME> shrieked. "Josu," Liliana whispered, "I'm so sorry." "Sorry!" He staggered to his feet and lurched at her. "You #emph[damned] me, Sister!" Glaring at her, he brought his clawed fingers to his own neck. "Damned me to endless torment!" He raked his nails down his neck and onto his chest, tearing skin and cloth alike…but not a drop of blood welled in the gashes. "Torment!" #figure(image("002_Liliana's Origin: The Fourth Pact/07.jpg", width: 100%), caption: [Art by Izzy], supplement: none, numbering: none) Bracing herself against the wall, Liliana fought her way to her feet, edging away from him. But despite the stiffness of his limbs, he was fast, and he caught her neck in his hand again, pressing her back against the plaster. "Let me help you, Josu," she pleaded. "Come back, come back and we'll make this right." "Help me?" His voice was a growling whisper in her face. "I am lost to the Void, Lili. Lost! So why do I linger here?" "I don't know, Brother. I don't know. But we'll fix it. Trust…." He tightened his grip and choked off her words. "Trust you? #emph[Trust] you? No!" "Let go of me," she croaked. "The Void will have you, Lili. Its hunger will never die. It will have us both." "Let me go," she said again. Her terror and grief burned away, leaving only cold anger. Memories of the moss-draped trees, clammy air, and reeking water at the heart of the Caligo flitted through her mind as mana streamed into her, chilling her blood and prickling her skin. "I'll never let you go, little sister. Not anymore. We'll be together, you and I. Joined in this eternal agony!" "Let go!" Liliana's fury erupted into a blast of livid darkness between them, sending Josu toppling onto the bed as the plaster cracked and crumbled at her back. The shadows danced across his body then disappeared, seeping into his pale skin. He stood upright again, not so stiffly, and glared at her. "So my sweet little sister dabbled in necromancy," he said. "And turned me into #emph[this] !" He thrust his hand toward her, and a fountain of shadows flew from his fingertips. She threw her hands up to protect herself, and the shadows pierced her, tearing at her soul and smashing into the wall behind and around her. Though it left her bitterly cold, Josu's spell didn't harm her as much as it damaged the wall. As the support at her back crumbled into ash, she stumbled and fell amid the debris. Liliana was dimly aware of the chaos erupting around them, the household staff screaming, running, whimpering in pain or crying in grief. #emph[How did it go so wrong?] she wondered. She had exulted in the blossoming power within her, but now it seemed to collapse in on itself, leaving a desolate void. #emph[No,] she thought. #emph[I have to make this right.] Scrambling back as he strode at her again, she tried to think of a spell that could undo what she'd done, somehow take his twisted semblance of life and ignite it into true life again. In the meantime, though, she had to keep him away from her. She tossed spell after spell at him, blasts of darkness and grasping claws of shadow. Over and over he howled in pain, leveling an endless stream of invectives at her. Instead of stopping his advance, though, her spells seemed to make him stronger. Which made sense, she realized. The magnitude of the lies she had told herself became clear. All this time, she had believed that she'd been studying necromancy from her secret books and doing dark research in order to aid her healing arts. That she could turn the power of death to the service of life and health. That a healer should use every tool at her disposal. But Josu was the result, a horrible fusion of life and death, and all her spells meant to manipulate the life force of the living could do nothing to harm the dead. And Josu returned every spell with one of his own, smashing walls and shattering windows. Stray blasts, deflected from their intended targets, struck servants and withered their flesh, melted their bones, or consumed their souls. #emph[So much death, ] she thought. #emph[And unless I think of something soon, I'm next.] Josu's relentless assault was taking its toll on her. The mana that suffused her and fueled her magic seemed to dampen the effect of his spells on her, but it wasn't a perfect shield. Her hands were cold, her limbs stiff, and her thoughts slowing as the magic of death sapped her strength, body and soul. Josu—the thing that had been Josu—stretched out his hands and shadow engulfed her. Claws of darkness clutched at her, lifting her from the ground and snatching at the motes of life and strength that remained in her body. She choked as shadows reached into her mouth, seizing the breath right out of her lungs. She felt as cold as death itself, suffocating as though she'd been buried alive, trapped in the viselike grip of her brother's magic. He stood right in front of her now, looking up into her eyes, his clawlike hands upraised as if they, not his spell, were holding her in the air and squeezing the life from her. "Join me, Lili," he said. "All the torment of the Void will be ours to share forever." Her eyes pleaded with him, but not a glimmer of compassion lit his lifeless black orbs. Finally she closed her eyes, unable to look upon the horror she had created. Death closed in on her and her head swam. Then, in her moment of utter desolation, something inside Liliana caught fire, a spark of infinite darkness, at once colder than the grip of death and hotter than the sun, dark and endless as the Void but eternally alive, an infinity of possibility, the power of creation itself…and annihilation. She snatched at this new power, seizing this last shred of hope. Her soul burned in exquisite agony, and Josu's magic dissipated, unable to contain her anymore. She opened her eyes and saw Josu recoiling from her, his shrunken face twisted in shock. She stretched her hands to her sides and the corpses strewn about in the rubble rose up, her servants to command once more. The mob of zombies lurched at Josu, swallowed him up and overwhelmed him. #figure(image("002_Liliana's Origin: The Fourth Pact/08.jpg", width: 100%), caption: [Art by Izzy], supplement: none, numbering: none) As Josu struggled against the press of undead flesh, something pulled at her from behind. Whirling around, she saw the ruins of her father's house change. The walls twisted and split, forming dark tree trunks under a shroud of black leaves. Clouds of dust became billowing fog, and the rubble-strewn floor turned into swampy ground strewn with dead leaves and gnarled roots. Her feet didn't move, but she felt that she was being drawn through unspeakable eternities, plucked from the world she knew and thrust into a whole other world. Then her home was gone, Josu was gone, the zombies, everything she knew was gone, and she sank to her knees on the swampy ground. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Once, We Were Gods More than a century later, an old woman stepped from one world into another. The years were a burden on her shoulders as heavy as her grief. "You're late." The rumbling voice greeted her before she had fully left the other world behind, and with her first step on the marble floor of the great hall, she felt it vibrating with the power of the voice. "Not yet," Liliana said with a smirk. "Not ever, if you can help me as you promise." Gazing ahead at the prospect of death—as mundane a death as could be imagined, withering away from age—she had come to seek the aid of the one being in all the planes powerful enough to keep it at bay. The floor shook again as the dragon chuckled, and Liliana turned to look at him—turned, and raised her head, and stepped back to see more, and still his enormity filled her vision. As vast as the hall was, the great, curled horns atop his head scraped the ceiling and his outstretched wings reached the walls on either side. She suppressed a scowl—<NAME> was trying to intimidate her, to remind her who held the upper hand in their negotiations. Worse, it was working. "I can help you, <NAME>," Bolas said. "But immortality is beyond the reach of us all, now." #figure(image("002_Liliana's Origin: The Fourth Pact/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "Says the thirty-thousand-year-old dragon." Liliana turned her back on him again, staring down at her hands. Creased and spotted with age, her skin hung loose on her bones. She stood as straight as she could manage, unwilling to display her body's frailty in front of the mighty dragon. But it was not just her body—her soul was a withered bloom, bereft of hope. "How we have fallen," he said. "Once, we were gods, working our private havoc through planes known and unknown." His words stung. They were Planeswalkers, not gods, but in those first years there had not been much difference. The spark that had ignited in her heart had unlocked greater power than she could ever have imagined, making her immortal and virtually omnipotent, putting the endless ranks of the dead firmly under her command. She had walked the numberless planes of the Multiverse for decades, exerting her will, her whims, on worlds that were powerless to resist her. Only one thing, in those days, had seemed beyond the reach of her magic: undoing what she had done to Josu. Then the Multiverse reshaped itself, robbing her—and every other Planeswalker—of the godlike power they once had wielded. Some called it the Mending, as if something broken had been repaired, but to Liliana, it seemed the opposite. It broke her beyond any hope of repair. She had spent decades working to regain even a fraction of the magical might she had lost, and it was not enough—not enough to keep death at bay. Josu had promised that they would be together in death, sharing his eternal pain, and Liliana would never let the icy claws of death fulfill that promise. "You have not fallen so far," Liliana said, unable to keep the bitterness from her voice. "You did not know me at my height. I have lost more power than you could learn in a dozen lifetimes." "Then give me a hundred!" Liliana whirled on him. "Look at me, Bolas! I can feel death breathing down my neck." "Perhaps that is because it has been such a close companion all these years." "Not a companion, a tool. Something to be inflicted on others, not embraced." "I'm sure some of your old teachers would disagree." The floor rumbled with the dragon's amusement again. "Surely you learned from vampires when you went to Innistrad, studied with liches—the masters of necromancy. They would have you embrace death and move beyond it, not fear its approach." As <NAME> spoke, he lowered his head closer to Liliana's and turned so that she saw her face reflected in one huge, black eye—wrinkled and drawn, her beauty faded, the specter of death haunting her eyes, not too different from what she had seen in Josu's dead, black eyes all those years ago. Liliana turned away. #emph[I am more than I seem,] she reminded herself. "A queen doesn't rule her people by being one of them," she said. "If I'd wanted to go down that path, I'd be on Innistrad right now, not here. So can you help me or not?" "As I told you, I can put you in touch with the beings that can help you." "Four demons, you said. And the cost is my soul, right? Payable upon my death?" "It's not quite that simple." "Of course not." Liliana sighed. "Nothing is ever simple with you, is it, Bolas?" "On the contrary, many things that your mind can't even begin to fathom are quite simple to me." She snorted. "Your modesty is truly breathtaking." "A simple statement of fact, Liliana Vess. After all, you are merely human." "'Once, we were gods.' I need that power back, Bolas. Power and youth and strength. Even if it costs my soul." "Good." The dragon's breath was close, scalding the back of her neck. "But a soul isn't a trinket you can hand over to a demon, or an ember it can seize upon your death. You'll give up your soul, all right—because no one with a shred of soul could possibly undertake the tasks you will perform to pay off your debt." Liliana tried to suppress a shudder. "But why should that bother you," the dragon said, "after all that you have already done? You have studied with the greatest necromancers on all the planes. You slaughtered angels. And you bested the one who started you on this path. What did you call him? The Raven Man?" Liliana nodded absently, thinking of her first encounter with the Raven Man, all those years ago, and the terrible events that followed. She had bested him, as the dragon said, but not killed him—not yet. "Perhaps you have already given up your soul," Bolas said. The prospect did bother her, Liliana realized with some surprise. Bolas was right. Since her first encounter with the Raven Man in the Caligo Forest, when she had embraced her power and let it steer her, her life had been one moral compromise after another, an inexorable slide into darkness. What was left that separated her from the wickedest villains in the Multiverse? #emph[Just this moment,] she thought, #emph[this one instant of hesitation.] Liliana turned and stared into the dragon's unblinking eye. "Let's get this over with." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = Written on Your Skin For the fourth time, <NAME> led Liliana from his great marble hall to a plane she didn't recognize. After forging three pacts with three different demons, power surged through her body—yet she was still a rag doll in the dragon's claws. And she was still old. The dragon deposited her in another great hall. Leaping flames filled an archway in front of her, but as Bolas withdrew, the flames died down and the fourth demon came—slithered—into view. In place of legs, he had a bulbous tail trailing behind him into the fires. His bestial head jutted forward from his hulking shoulders, dominated by a leering grin that showed his sharp teeth. Two horns, surmounted by an elaborate headdress, swooped out to the sides from a tawny mane. Tattered, leathery wings stretched out from his shoulders. And his long arms trailed sharp claws almost to the ground. #figure(image("002_Liliana's Origin: The Fourth Pact/10.jpg", width: 100%), caption: [Art by Tianhua X], supplement: none, numbering: none) "<NAME>," he said, stooping so his breath washed over her face. His voice was a harsh whisper, and a serpent's tongue flicked out between his teeth as he drew out the end of her name. "I am Kothophed." "And you know my name, so I guess that's the end of our pleasantries." The demon barked a short laugh. "Indeed. And I understand I am the fourth of your patrons. Did your other agreements meet your expectations?" "I am satisfied." Bolas had warned her against telling any of the demons about the others, and she tried to keep even the thought of them from surfacing in her mind. "Are you? Shall we forego our arrangement, then? You have all you desired?" She smirked. "I am satisfied with the benefit I reaped from each previous agreement, and I'm sure I will be satisfied with this one when it's complete." "Oh, but I will be your most demanding master, Liliana. I have great things in mind for you. So if you have the least hesitation, you might want to reconsider. You have gained a great deal of power already." "That's not enough," she said. Bolas had warned her, too, that if she tried to renege on a bargain, the demons would be free to kill her, and even with the power she'd gained, she doubted she was a match for Kothophed. Dark mana radiated from him like heat from a bonfire. "So hungry for immortality," the demon said, slithering forward and around her. "But you've gained power enough to sustain your life for decades at least, maybe a century. And you could have your way with the Multiverse in the meantime. Is that not enough?" "Holding death at arm's length for whatever years are left to me? No, that's not enough. I want to be free of its shadow." #emph[Like I was before Josu, ] she thought. #emph[Young and alive and blissfully unaware of the number of my days.] "But you have already embraced death," the demon said, now behind her. "You've taken it into your soul, stitched it with your Planeswalker spark, woven it into every shred of magical power within you. It casts a very long shadow over you, my dear." "Everyone's death but my own," she said, more to herself than to the demon. As she spoke, the room melted away around her and she stood on a barren plain. Corpses littered the field as far as she could see, and ravens hopped from body to body, picking at the tastiest bits. "I am your death," Kothophed whispered in her ear. "Kill me, and you will never die." She whirled around, a spell forming on her lips, but the demon was gone. She heard his barking laugh from behind her again, now a dozen yards away. Liliana stretched out her hands and black birds rose in a storm of flapping wings as corpses across the battlefield lurched to their feet and shambled toward the demon. Kothophed surveyed the field as if counting the zombies, his jackal's grin unwavering. "Impressive," he called. Then two flicks of the demon's tail sent bodies—lifeless once more—scattering in every direction. "Just a warm-up," Liliana called back, trying to hide her fear. Bolas had told her the demons had agreed not to kill her, not as long as she held to the terms of the bargain. But Kothophed had seemed eager to break that deal from the start, and this battle didn't feel like a test. Half a dozen shades, wisps of shadow radiating bone-chilling cold, swept down at the demon, passing through his body but emerging empty-handed on the other side. One such shade could kill a man, seizing his soul and leaving his corpse cold on the ground, but six had no effect on the demon at all. As Liliana found the rhythm of her spellcasting, she slowly rose from the ground surrounded by an Aura of shadow. She grasped at the demon's life energy herself, trying to draw power from him to fuel her own magic. Kothophed slithered closer to her in response to her pull, and then a wave of power surged out from him and knocked her backward. Wave after wave of grasping shades, shambling zombies, and specters on great winged shadows answered her frantic summons and rushed at the demon at her command, only to fall at Kothophed's tail, swordlike claws, or gnashing jaws. But they bought her time—time to shape a horror from the bones and flesh of the fallen, a venom-spewing monster with the soul-sucking claws of a specter and the sheer strength of a titan. For a moment, she thought that Kothophed was actually struggling with the creature. The demon wrestled with it, surging closer to Liliana as the two monsters grappled in a tangle of limbs, claws, and fangs. But as the demon came close, it was clear who was in control of the fight. Kothophed seized the horror and pulled its limbs apart, depositing them at her feet. Then he seized her. The demon's cold breath numbed her skin. His claws bit into her flesh. He held her in one great hand. With the other, he drew one claw from the crown of her head to the toes of one foot, slicing deep, scraping against bone. She screamed. The incision made, the demon peeled back her age-worn skin, pulling it off her like a rabbit's hide. But what Liliana saw beneath was a younger body, slick with blood but supple and smooth. Kothophed set her back on her feet, and she felt solid marble beneath her. The charnel field melted away and she stood once more in the demon's pillared hall. She looked down. Her black gown remained in place. But her skin, her shape, her posture were those of her younger self, beautiful once more. "What," she spat, "was that?" The demon laughed, long and loud. "If that was supposed to be a test," she said, "then clearly I failed. So why am I still here? Why do I look like I do?" The demon stifled his laughter and lowered his face until his yellow eyes gazed right into hers. "It was not a test. It was a #emph[lesson] —one I trust you will never forget." He reached a claw toward her face again and she winced in anticipation, bringing another barking laugh. "Hold still," he said. "I'm not done with my end of the bargain." His touch was more gentle, but still agonizing, as he traced the claw in whorls across her face. "You are a Planeswalker," he said as he worked. "That makes you special. You are also one of the most powerful mages in all the planes, and that makes you extraordinary." #figure(image("002_Liliana's Origin: The Fourth Pact/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) #emph[Yes,] she thought. #emph[So the Raven Man said] . Done with her face, Kothophed moved on to her neck and shoulders. "But next to me, you are #emph[nothing] . Your mightiest spells could barely touch me. Your merely human mind will never match mine." #emph[You go ahead and think that] , she thought through the pain. The demon had meant to crush her, but the power inside her was blossoming again, brighter and stronger than ever. It was worth the agony. "If you ever get the idea of testing your strength against me," the demon said, "I will slit you open again. But this time, there will not be a young and beautiful Liliana underneath." The lines traced by Kothophed's claw didn't bleed, but they glowed with pale, violet light as if the power they granted her was spilling out. Despite the agony, despite the demon's threats, she felt the shadow of death recede from her. She was young and powerful, and she would stay that way for #emph[ages] . Or until the demons came to collect the debt she owed. But some part of Liliana knew that Kothophed was the one who should be afraid. She was more than she seemed, and the demon had underestimated her, like so many others before him. It was her destiny to overthrow the demons that claimed her. She knew it, as if the knowledge were a part of her flesh. As if Kothophed, unwitting, had woven that destiny into her being. It was written on her skin. #figure(image("002_Liliana's Origin: The Fourth Pact/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Research/Summer%202024/Geometry%20School/Kahlar%20Metrics.typ
typst
#import "/Templates/generic.typ": latex #import "/Templates/notes.typ": chapter_heading #import "@preview/ctheorems:1.1.0": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #import "/Templates/math.typ": * //#import "/Templates/monograph.typ": frontpage //#import "@preview/cetz:0.2.2": canvas, draw, tree #show: latex #show: chapter_heading #show: thmrules #show: symbol_replacing #show: equation_references #set pagebreak(weak: true) #set page(margin: (x: 2cm, top: 2cm, bottom: 2cm), numbering: "1") #set enum(numbering: "(1)", indent: 1em) #outline() #pagebreak(weak: true) = The metric completion of the space of Kahler metrics and applications Goal: teach overview about metric Geometry. Let $(X, omega)$ be a compact connected Kahler manifold. That is a form $omega$ such that locally $ omega = i partial ov(partial) g $ If $omega'$ is another such metric with $[omega'] = [omega]$ we know that $omega' = omega + i diff ov(diff) v$ where $v$ is some smooth function. This is a sort of local to global result. This allows us to define what are called Kahler potentials $ cal(H)_omega := { v in C^infinity (X) "such that" omega_v := omega + i diff ov(diff) v > 0 } $ The natural question is to then nice nice/canonical metrics in $cal(H)_omega$, for us that will mean constant scalar curvature metrics. Try try and tackle this we introduce $K$ energy functional, $K(u)$, who's critical points are constant scalar curvature metrics. Now this doesn't always happen, so we want to attain a characterization of when this happens. Specifically, we want to prove a theorem of the form #theorem[ The following are equivalent + There exists a unique cscK metric in $cal(H)_omega$. + The $K$-energy is proper. + The $K$-energy is geodesically stable. ] The second condition sort of controls the behaviour of energy $K$ 'at infinity'. The third one has to do with the variational structure of the functional. To get a handle on these problems we look towards finite dimensions. #theorem[ Suppose $F : RR^n -> RR$ is a strictly convex functional. If $F$ has a minimizer it has to be unique. The following are equivalent: + $F$ has a unique minimizer. + $F$ is proper, in the sense that there exists $C,D > 0$ such that $ F(x) >= C |x| - D, x in RR. $ + $F$ is geodesically stable, i.e. there exist $C$ such that // TODO: FINISH ] This is easy to prove for yourself, $(2) => (1)$ is easily seen by using compactness and convexity properties of $RR^n$ and $(1) => (2)$ is also easy using convexity and completeness. Almost immediately this breaks when we try to apply it in our infinite dimensional setting, $cal(H)_omega$ is not classically convex. The next attempt is to try and change the geometry of $C^infinity (M)$ to change what geodesics look like. We can do this using a Riemannian metric on $C^infinity (M)$ as a Frechet manifold, the metric being $ |phi|_(2,u) := sqrt(integral_X |phi|^(2)omega_u^n) $ where $u in H_omega, phi in C^infinity (M)$. For added flexibility we want a family of metrics given by $ |phi|_(p,u) := (integral_X |phi|^(p)omega_u^n)^(1 / p) $ One can check that the geodesic equation is independent of $p$. The good news is that if $u_t : [0,1] -> cal(H)_omega$ is a smooth geodesic, $K(u_t)$ is convex. The bad news is, unfortunately such geodesics do not exist, but we can instead weaken the notion of of geodesic to $t -> u_t$ joining $u_0$ and $u_1$, with bounded Hessian. Our key idea is then to extend $cal(H)_omega$ to accommodate weak geodesic segments. We consider the $L^p$ length $ l_p (gamma) = integral_0^1 ||dot(gamma)_t||_(p) dif t = integral_0^1 ( integral_X |dot(gamma)_t|^p omega_(gamma_t)^n )^(1 / p) dif t $ with $ d_p (u, v) = inf_(gamma_0= u, gamma_1=v) l_p (gamma) $ Now what we want to check is that this is indeed a metric space, since in infinite dimension these metrics can become degenerate. The metric completion is then the nice space $cal(E)^p$ and the $K$-energy extends to a convex functional $cal(K) : cal(E)^p -> RR union { infinity }$. And so we have convexity, and also we have compactness, since #theorem[ Let $C > 0$. The set ${ cal(K)(u) <= C, d_1 (0, u) <= C } seq cal(E)^1$ is $d_1$-compact. ] We do lose some regularity but it turns out that this does not hurt our goal. #theorem("Elliptic regularity")[ Minimizers of $cal(K)$ in $cal(E)^1$ are smooth cscK metrics inside $cal(H)_omega$. ] We then get the following theorem #theorem[ The following are equivalent: + There exists a unique cscK metric in $cal(H)_omega$. + The $cal(K)$-energy is 'proper' in the sense that there exists $C,D$ with $ cal(K)(u) >= C d_1 (0, u) - D, quad u in cal(H)_omega $ + The $K$-energy is uniformly stable along geodesic rays with bounded Laplacian. $ lim_(t -> infinity) (cal(K)(u_t)) / t >= C > 0 $ ] // OVERALL IDEAS // Convexity for functionals is super cool and we like it. // Convexity doesn't usually exist, so we add a metric to change what convexity means. // Changed metric breaks existence of geodesics so we must weaken geodesics. // With this weakening we need to add some extra points to guarantee their existence // We then can with a clever choice of parameters, fix both elliptic regularity and compactness. // This is enough to get what we want.
https://github.com/medewitt/bio720
https://raw.githubusercontent.com/medewitt/bio720/main/signalling.typ
typst
BSD 3-Clause "New" or "Revised" License
#import "template.typ": * #show: ams-article.with( title: "Reading notes: Signalling", authors: ( ( name: "<NAME>", department: [Department of Biology], organization: [Wake Forest University], location: [Winston Salem, NC 27101], email: "<EMAIL>", url: "www.michaeldewittjr.com" ), ), abstract: "Caveat Emptor", bibliography-file: "integratedbio.bib", ) #set heading(numbering: "1.") #let today = datetime.today() = Signals and Responses - Receptors can be extracellular or intracellurlar - Extracellualr receptors activate intracelluar cascades that affect protein activity or transcription - Intracelluar receptors initiate transcription - Extracelluar ligands can act locally or through long distance pathways - Many proteins don't move into the cell but they can initiate efficient signalling - If a protein is hydrophillic it won't move into the cell without some additional help (e.g., a channel, a chaperone protein) - Hydrophobic and some gases can permeate the cell membrane and thus don't necessarily require chaperones or channels - Hydrophobic molecules work through intracelluar receptors to often direct nuclear transcription - *Steriods* are large hydrophobic molecules which are developmental signals == Cell-cell communication - *Contact dependent* cells touch each other - *Paracrine* acts through nearby cells (e.g., local mediators and signal cells interact with local targeted cells) - *Synaptic* often in neurons which acts more locally - *Endocrine* most common in mamalian cells where a endocrine cell enters blood stream, interacts with a receptor, then triggers target cell. == Response Rates - *Gene expression* is generally slower (minutes to hours) due to the number of steps (transcription, translation, error checking) - *Altered protein function* are fast. Typically phosphoration. Molecules with rapid turnover can in concentration much more dramatically. Also describes inherit stability. Many RNAs and proteins are unstable so they have a typically smaller halflife. Smaller/ shorter half-lives have a more drastic impacts to signalling. Extracellular ligands can act locally or long distance. = Aspects of receptor function - Specificity - Signal molecules fits binding site on its complementary receptors while other signals do not fit - Protein structures define the specific binding and associated affinity - Influenced both the hormone and receptors - Amplification - Amplification occurs when an enzyme activate enzymes and the number of affected molecules increases geometric in an enzyme cascade - Amplification can within signal transduction cascades - For example coupled protein receptors, activates a G-protein, activates 20x cyclic AMP, binds to enzymes - *Kinase* adds a phosphate - Desensitization/ Adaption/ Feedback - Receptor activation triggers a feeeedback circuit that shuts off the receptor or removes it from the - Integration - Protein complex formation - Concentration depdendent action
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/037%20-%20Ravnica%20Allegiance/005_The%20Gathering%20Storm%3A%20Chapter%2011.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Gathering Storm: Chapter 11", set_name: "Ravnica Allegiance", story_date: datetime(day: 21, month: 08, year: 2019), author: "<NAME>", doc ) Nivix was never truly quiet. Even in the dead of the night, there was always some inventor who couldn’t sleep scratching new designs at a drafting table, some chemister working around the clock to meet a funding deadline. But normally, the building at least slowed down after midnight, the hallways emptying out except for the scorchbringer guards and watchful automata. Even madmen needed rest, eventually. But not tonight, or any of the nights in the week since the disaster at the guild summit. Huge banks of lights turned darkness into broad daylight, while mizzium generators in the bowels of the building hummed and sparked. Every desk was full, every laboratory, every testing chamber, the air full of the smell of ink and fumes and hot metal. When workers collapsed, they were dragged away to makeshift barracks in the halls, laid out on blankets and given a few hours rest before being revived with coffee and sent back to work. And, perhaps uniquely in the history of the guild, all that effort was bent toward a single goal. Committees had ceased meeting. Bureaucratic in-fighting between the different laboratories had been put on hold. A thousand bickering geniuses had had their heads cracked together until they were all pointing in at least approximately the same direction. Word had come down from the top—from the #emph[very] top—that every resource the Izzet possessed was at Ral Zarek’s disposal, and anyone who got in his way would answer to the Firemind. Ral hadn’t left his office since his return from New Prahv. Meals were brought in, changes of clothes, fresh rolls of drafting paper, and the outputs of a hundred other offices for collation and combination. He had long since lost track of the time, or even the day. He worked until he could no longer force his eyes open, then put his head down on his desk and slept until he was woken by the next delivery or disaster. While he slept, he dreamed. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Ral remembered being torn into pieces so small as to be invisible, flowing through a sea of strange energies and twisted space, and reassembled bit by agonizing bit. He opened his eyes and found himself face-down on a sewer grate. It had a strange brass design, not like the Tovrna’s wrought iron, and the walls around him were sun-burnt brown brick instead of gray stone. Rain was falling, pounding up and down his back, and a stream of water ran past him and down into the sewers. Ral could see a streak of crimson in it, and felt a sharp pain in his side. #emph[That’s right.] He put his hand to the wound, felt blood pulsing wetly against his palm. #emph[That boy stabbed me. And I made it home . . . and Elias . . .] Thunder rumbled overhead, and the sky flickered. "Well," said a voice with a strange accent. "You’re dressed pretty nice to be lying in a gutter." "Someone’s having a bad night," a second voice said. "Bad for him," the first voice corrected. "Good for us." Ral sat up, with an effort. There were two men leaning against the walls of the alley, watching him with amused, unhurried expressions. Their clothes were strange, loose flowing shirts and trousers, but he recognized their manner at once. Thugs were thugs, no matter where you traveled. #emph[And where have I traveled?] Some magic had taken him, that was certain. He cleared his throat. "What district is this?" "District?" the second man said. He was the shorter of the two. "You must be from #emph[way] out of town." "Figured him for a merchant," the taller man said. "From somewhere they dress like that without anyone laughing at them, I s’pose." Ral shuffled to his knees, his hair beaten flat against his skull by the pounding rain. He forced words out through gritted teeth. "Where. Am. I?" The taller man strolled forward. "Where you #emph[are] , friend, is deep in the dungheap. Now, it’s been nice chatting with you, but you might have noticed it’s pissing down out here, and I for one would like to off somewhere warm and dry and full of drinks. So. Hand over what’s in your pockets, and then strip off those nice things, and we’ll leave you as healthy as when we found you." His hand went into his pocket and came out with a knife. His partner drew one as well, the steel blades shining as lightning crawled across the sky overhead. Ral took a deep breath. "No," he said. "That seems like a mistake to me," the first man said. "So I’m going to give you one more chance to think things over—" #emph[BOOM.] Flash and thunder were simultaneous, the lightning bolt snaking down through the rooftops to earth itself in the flowing water of the alley. Ral felt heat washing over him, power running through him, like fire in his blood. His hair frizzed and stood on end, and when he smiled, sparks arced between his teeth. Above him, the rain started to bend in gentle arcs, leaving a dry circle where he stood. Moments later, Ral left the alley, richer by two twisted, slightly melted knives, a couple of purses full of copper, and two pairs of still-smoking boots. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Something was always exploding. Again, not an unusual state for Nivix. But the explosions were usually a little less frequent, and accompanied with a little more fanfare. Most of the goblins believed that the best time to do a field test was at the grand unveiling, so that if whatever you were building blew up, at least everyone was there to see it. Now the blasts shook the vast structure, day and night. Hydromancers put out the fires, and workers descended on the stricken laboratory, hauling away the bodies and hammering the metal back into shape before it had even stopped smoking. Danger was irrelevant—not that it was ever #emph[that] relevant—and cost was no object. The work went on, as the lines sketched by Ral’s frantic pencil took shape in arcs of mizzium and steel, and chemisters with soot-blackened faces hurried upstairs to report success or failure. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[APPRENTICE NEEDED] Ral stared at the sign for a long while, and sighed. But the profits from a couple of knives and pairs of boots only went so far, and his stomach was rumbling. The tinkerer’s workshop was two stories of crumbling brick, with a strange glass-and-steel contraption emerging from the roof. Lightning swirled inside a globe at the top, but only weakly, and a gear train descending from the machine moved only in fits and starts. An old man, wearing a pair of goggles with one lens badly cracked, wrenched open the door when Ral knocked. "YES?" he shouted, then worked his jaw and swiveled one finger in his ear. "What?" "I’m here about the apprenticeship," Ral said. "Aren’t you a little old to be an apprentice?" the old man said, looking him up and down. "I want to learn about machines," Ral said. Machines were everywhere in this strange city, buzzing through the air and rolling along the streets. So many of them were powered by tame lightning that his power twinged in sympathy wherever he went. He’d been staring at them, fascinated, since he’d arrived. "You and half the city," the old man said. "Can you pay the ‘prentice fee?" "No," Ral admitted. "But I can work." "I can hire a boy to clean my scuttle and launder my drawers for a half-bit. What else can you do for me?" Ral raised his hand and concentrated. Power crackled in his fingertips, then arced upward, to the big globe. The lightning inside blazed with light, its weak glow strengthening until it was as bright as the sun. The chain of gears running down into the workshop started to spin, turning faster and faster, smoke rising from their bearings. Behind the old man, a metal whine rose to a shriek, and then something broke with a tremendous crash. The old man looked over his shoulder, then back at Ral. He smiled. "You’re hired," he said. "What do you want to learn?" "Everything you have to teach me," Ral said, running one hand through his hair with a crackle. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Hellooooooo?" Hekara said, in a stage whisper. She opened the door to Ral’s office. Ral looked at her, bleary-eyed. "What?" "Just thought you could use a bit of, you know, cheering up." She spread her arms. "That’s what mates are for, right? Keen!" "I don’t have time," Ral said. "None of us have time." "Awww, there’s always time for a little fun, eh?" Hekara spun gayly across the room. Her trailing hand caught a jar of pencils on the corner of Ral’s desk, which tipped over, sending them rolling across the floor. "Oops." "#emph[Hekara] ," Ral began, voice rising. Hekara flinched, looking so chagrined that he paused and let out a breath. "Just pick those up. And . . . sit in the corner and stay very quiet. Can you do that?" "Ooh, like in hide and seek! I’m terrible at that. Not like my mate Brevia, she’s the best. We played down in the basement of the Flaming Whips, and it took me #emph[three weeks] to find the spot where she’d hidden under the floorboards!" Hekara wrinkled her nose. "Of course she did whiff a bit by then." Ral leaned back in his chair with a sigh and closed his eyes. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Harith was unlike Elias in almost every way—tall and broad-shouldered instead of willow-slender, with a laborer’s muscles and rough, callused hands instead of a poet’s dexterous fingers. Perhaps, Ral thought, that was why he’d been drawn to him immediately, three drinks into a bad night in a cheap tavern. Or perhaps he was just the first person in a long time who seemed interested in talking to Ral instead of exploiting him. The room was Harith’s, much bigger than the rat trap Ral rented with the pitiful stipend Ghazz, the old tinker, was willing to pay him. It was on the top floor of a red brick building, overlooking a neighboring alley, spiderwebbed with clotheslines and hanging laundry. Harith kept the windows open for the hot, dry breeze; it meant that anyone in the alley could probably hear what they’d been up to, but Ral found he didn’t much care. Harith stood by the window, looking down, wearing only a sleeveless dressing gown. Ral rolled onto his side to admire him, the hard planes of his body, the tight thatch of orange-red curls that felt just right when he curled his fingers through them. Sensing his regard, Harith looked over his shoulder and gave a lopsided grin. "Thought you were going to sleep until noon," he said. "Hangover?" "Surprisingly, no," Ral said, flopping onto his back. His own hair hung lank and disheveled with sweat. "Just lazy." "What about <NAME> Ghazz? He’s not going to be mad you’re late?" There was a long pause. Ral stared at the ceiling for a moment, eyes tracing the spiderweb cracks in the plaster, trying to keep his racing heart under control. "I didn’t tell you who I was working for," he said, quietly. Harith swore under his breath. When he turned away from the window, his smile was broad and as false as a tin zino. "I must have heard it somewhere," he said. "And that’s why you talked to me," Ral said, still not moving. "You need something." "It’s not like that—" "Just admit it." Ral let out a deep breath and sat up, running his hand through his hair. Lightning crackled, restoring its frizz. "What were you hoping to get from me?" Harith looked at him, all cold calculation, no desire left in his eyes. "The combination to the vault. Ghazz has some toys that people I know would pay well for." "And I was supposed to hand it over for a tumble and a pretty smile." "Ral . . ." "Thirty percent." Harith blinked. "What?" "That’s my cut. Thirty percent." "Ten," Harith snapped. "I’m the one taking all the risk." "Twenty-five," Ral said. "Ghazz will know it was me, and I won’t be able to get another apprenticeship. Besides, you should have been honest with me from the beginning." Harith looked like he’d been sucking on a lemon, but he nodded. "Twenty-five." He hesitated. "You’re not worried, about having to leave Ghazz?" Ral forced his features into a carefully engineered smile. "I don’t have anything left to learn from him." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The walk up to the Aerie seemed especially long when you had to make it in the middle of the night, in response to the Firemind’s peremptory summons. Ral rubbed his eyes, feeling deep bags under them from lack of sleep, and grit his teeth. In his wake, a dozen goblins carried long rolls of paper under their arms, hurrying to keep up with his purposeful stride. When they reached the great doors that led to Niv-Mizzet’s sanctum, Ral gestured for his assistants to stop. "I’ll call when I need you," he muttered. "W . . . what if the Firemind devours you?" one wide-eyed goblin woman stammered. "Then I’ll scream," Ral said, "and you can take the rest of the day off." He pushed the doors open. Niv-Mizzet sat on his haunches in front of the great window, among the arcane detritus and machinery of his Aerie, several books hovering in the air in front of him. They carefully bookmarked and stacked themselves on a table as the dragon’s long neck swung around to face Ral, fins flaring. "<NAME>," Niv said, his voice both clear in Ral’s mind and an ominous rumble in the dragon’s throat. "I have been waiting for your report." "My apologies, Guildmaster," Ral said, bowing. "The situation has been . . . confused." "I dare say," Niv said. "It is not every day the supreme judge of the Azorius is assassinated under our noses." His head snaked closer, breath a hot wind on Ral’s face. "But I require answers, not excuses." "Of course," Ral said. "Our representatives have visited every guild since the . . . incident at the summit, with some success. With Isperia’s death, <NAME> has assumed leadership of the Azorius, and I understand his position as supreme judge is only awaiting confirmation by the Senate. He has been most accommodating and remains convinced that cooperation is the best way to meet Bolas’s threat. Aurelia of the Boros Legion also sent her firm commitment to continuing the negotiations. Kaya of the Orzhov and Lazav of the Dimir have expressed similar sentiments." Ral tried not to let his expression shift at this last. #emph[I still don’t trust Lazav.] "And Hekara has communicated with Rakdos himself and assures me that the demon remains willing to assist us." "Six guilds," Niv rumbled thoughtfully. "And the rest?" Ral took a deep breath. "The Simic have retreated to their zonots and raised their defenses, refusing all communications. Emmara of the Selesnya says that with Trostani still . . . at odds, forces counseling caution have gained the upper hand. She offers neutrality, but nothing more." Niv’s huge eyes bored into him. Ral felt sweat beading on his forehead. "The Gruul appear to have suffered some sort of leadership struggle in the aftermath of the summit," he went on. "Borborygmos has fallen, and we do not yet know who has taken his place. But the clans seem agitated, and raids at the borders of the rubble belts have increased. Aurelia has promised to increase patrols and step up her defenses." "And Vraska?" Niv said softly. "No one has seen Vraska since the night of the summit," Ral said. "But reports from the undercity are that the Golgari Swarm is mobilizing for war." "We need all ten guilds to amend the Guildpact," Niv said. "Including ourselves, then, we have six, with two neutral and two actively hostile to our cause." "Yes, Guildmaster," Ral said, inclining his head. "In other words," Niv said, his voice rising to a dangerous rumble, "you have #emph[failed] ." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) There was a loose board, just beside the bed where Ral and Harith had spent so many nights that—Ral had to admit—had been at least diverting. Ral set down the bag that contained his few possessions and levered the plank out with a dagger. In the space between the top floor and the one below was a canvas sack, which clinked dully as Ral extracted it. It was half-full of the strange, rod-shaped silver tokens that passed for coins here, the wages of months of theft, sabotage, and occasional violence. There was also the black notebook. Ral had watched Harith scribble in it, when he thought no one was looking. He’d finally stolen a glance a week before, after getting his lover blind drunk on fortified wine. The book had Harith’s lists of contacts, his potential targets, ways in and ways out. Secrets, and who might be most vulnerable to their use. A treasure trove for another time. Ral tucked the book under his arm, stowed the money in his bag, and replaced the floorboard. He stole out of the building as quietly as possible. Harith was out on a job tonight, and Ral had pleaded illness. With any luck— "You know," Harith said, "I didn’t want to believe it." Ral paused, on the landing leading to the stairs. Harith was waiting one flight below. Two hulking thugs in street leathers backed him up, a big, heavily tattooed man with a cudgel and a lanky minotaur with enormous scarred fists. "I thought we had a pretty good deal," Harith said. "You had your twenty-five percent, didn’t you? You had protection, a place to sleep, someone to sleep with." He stepped forward. "That wasn’t enough for you?" "It’s time for me to move on," Ral said, coming down the stairs. "And we both know you couldn’t let me do that. Not with what I’ve seen." "Why move on?" Harith fixed him with a gaze that was half furious, half despairing. #emph[He actually cares] , Ral realized. He forced another smile, and shrugged. #emph[The fool.] Harith scowled and jerked his head, and the two thugs came forward. Ral spread his hands, as though bidding them to wait. On his pack, the thing he’d spent the last month building, a jury-rigged mess of wire and steel plates, whirred jerkily to life. Power crackled through him, the kind of energy he’d normally only get by standing in a thunderstorm. He grinned at Harith’s hired muscle as he closed his hands into fists, and white sparks crawled out along his fingers. "I have nothing left to learn here," he said. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Not yet," Ral said. He wasn’t an expert on reading draconic expressions—who was?—but he was fairly sure Niv-Mizzet was surprised. The dragon’s long tongue flicked out, and his lips pulled back to bare sword-sized teeth. "Explain," Niv rumbled. "Bring it in," Ral shouted toward the doors. His goblin assistants scuttled in, nearly frozen in obvious terror of the dragon. Under Niv’s impassive gaze, they deposited their rolled papers at Ral’s feet, and he gestured for them to spread the things out on the floor. After a certain amount of confusion and argument—goblins were goblins, even under the eyes of the Firemind—they assembled the sheets in the proper order. What took shape was a huge map of the Tenth District, detailed enough to show every alley. Drawn on top of the street plan was a complex network of colored lines, thick and interconnected in some areas, sparse in others. The basic shape of it was familiar, of course; the Implicit Maze, the contest Beleren had somehow managed to win and become the Living Guildpact, only to abandon that responsibility when Ravnica needed him. #emph[This] map, though, was much more detailed, and assembling it had consumed much of Ral’s attention for the past week. "The power network," Niv said. He did not sound impressed. "Indeed," Ral said. "Which is, as we learned, the underlying structure of the Guildpact itself. It is laid out in the city, all around us, nodes and lines linked to create the power that binds us all." "All this is well known to me," Niv said. "I watched Azor lay the foundations." Ral nodded. "Azor stipulated that all ten guilds be in agreement to change the Guildpact," he said. "But that rule is #emph[part] of the Guildpact itself, which means it is embodied in these lines of power, just like all the rest. If we cannot meet the Guildpact’s conditions, then we must simply evade them." "#emph[Evade] them?" Niv said. "You think #emph[you] can tamper with Azor’s work?" "Only superficially," Ral said. He ran a hand through his hair, raising sparks, and walked across the vast map. "We can construct artificial lines of energy to alter the design. Most of the technology is already in place—power condensers, a resonating chamber, mizzium-coil batteries. It only needs to last for a moment. A machine that will span the Tenth District. The greatest creation the Izzet have ever attempted." "And this . . . thing," Niv said. He sounded skeptical. "It will allow you to alter the Guildpact, enable my ascension, without the consent of all the guilds?" "Yes," Ral said, with considerably more confidence then he felt. "There are just a few trifling difficulties to overcome." "Such as?" the dragon rumbled. Ral looked down at the map. "There are a limited number of effective configurations of nodes," he said. "The resonating stations must be very precisely placed across the district. Finding an arrangement that avoids the territory of Simic, Selesnya, Gruul, and Golgari has been . . . impractical." "Hmm," Niv said, head snaking forward. "These red markings are your current plan?" "Yes," Ral said. "Simic and Selesnya may come to their senses, but we cannot count on it. Not in time. This arrangement requires only nodes in Gruul and Golgari territory, here and here." He pointed. "The Gruul and the Golgari will not simply allow us the use of these nodes," Niv said. "They will not," Ral said, and straightened up. "So we will have to take them by force." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) A conference room in Nivix, more commonly occupied by a half-dozen chemisters plotting some deadly mischief, had been hastily appropriated for a council of war. Ral sat at the head of a long stone table, scarred and discolored by decades of experiments. On his right, the angel Aurelia stood with her arms folded, watching the others with blank, glowing eyes. Her second, the minotaur woman <NAME>, sat in a bulky chair and wore an expression of unabashed suspicion. Opposite the Boros contingent were the Azorius representatives. The vedalken Planeswalker <NAME>, now that guild’s leader, looked back at Aurelia with equal imperturbability. At his side was a young woman in silver armor he’d introduced as Hussar Capt<NAME>, who stood so painfully upright that Ral’s back hurt in sympathy. Finally, at the other end of the table, Kaya lounged in her chair, a broad smile on her face. A pinch-faced priest in black robes sat beside her, glaring as though he’d like to start scolding, but she didn’t seem inclined to pay him any mind. Ral glanced at the door one last time, sighed, and put his hands on the table. "We might as well get started." "Our company is not complete," Aurelia said. "I assumed the rest of our allies would be joining us." "Small loss," Ferzhin muttered. "Lazav has already sent word that his agents will be available to help gather intelligence, but direct combat is not their specialty," Ral said. "As for the Rakdos . . ." #emph[Where ] is#emph[ Hekara, anyway?] Normally she was impossible to keep from getting underfoot. "I don’t think they’ll be missed at a planning session. We’ll see them when the fighting starts, I imagine." "And you’re certain there is no other way?" Dovin said. "Not in the time we have left to us," Ral said. "The Firemind has directed that all Izzet resources be committed to this project. We #emph[will] have the resonators assembled and ready. For the nodes that we control, it’s a simple matter of installing them and linking them to the master node here at Nivix. But we must have two more." He pushed a map of the Tenth District, annotated in pencil, across the table. "Here, and here. And it seems unlikely that we’ll be able to take them peacefully." "Certainly not this one," Ferzhin said, tapping the map with one clawed finger. "That part of the rubble-belt has changed hands a dozen times in the last two years as it is." "And the other is in the Undercity," Dovin said, calmly. "Which means Vraska will be in an excellent position to try to stop us." Ral nodded. "Fortunately, united, we should have the strength to seize both nodes. And with any luck, our enemies won’t realize their importance." He looked around the table. "It should go without saying that the nature of our objective should not leave this room." "The Gruul will fight, because that is their nature," Aurelia said. "However, if we defeat them in the initial encounter, they are unlikely to counter-attack. Instead they will search for weaker targets to raid." "There are several garrisons within an easy march of this node," Ferzhin said. "And we conduct operations against the Gruul regularly. We should be able to field a sizable force without raising any eyebrows." "Good," Ral said. "I’d like to suggest that the Boros provide the bulk of our forces on the surface, then, with Izzet and Azorius providing a few elite units to assist. I will join you myself, of course." "That should be enough to send the savages scurrying," Ferzhin said, grinning at the prospect. "Do not underestimate the Gruul," said Aurelia. "They are cannier than they appear." "We won’t," Ral promised. "As for the Undercity operation, that’s where you come in." He looked across the table at Kaya. "I was hoping we could rely on the Orzhov for support underground." "Hmm?" Kaya blinked, looking distracted. "Of course. Whatever you need." "Guildmaster," the priest said, "perhaps a more limited commitment—" "#emph[Whatever] you need," Kaya said firmly. "And I’ll be there." "Guildmaster, please," the priest said. "Your safety is paramount." "I owe Ral for his help," Kaya said. "And I pay my debts." "Good," Ral said. "I’m going to ask Hekara for Rakdos help there, too. And Vraska is more likely to try something clever after we take the node, so we’ll need to fortify our position." "Our people can handle that," Dovin said. "With help from our Boros friends, of course." The minotaur bristled, but Aurelia only nodded. "Okay." Ral took a deep breath. "I know what happened to Isperia was a . . . shock. But we always knew Bolas had allies here, and now they’ve revealed themselves. All that’s left is to crush them." He looked around the table. "Thank you for your commitment to Ravnica." "Of course," Dovin said, after a moment of silence. "What other course could we take, after all?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)  #linebreak #emph[It’s done.] Nivix was still a hive of activity, but none of it required Ral’s intervention. The great machine was under construction in dozens of labs and workshops, pieces being forged and welded that, when finally assembled, would create forces that would stitch the Tenth District together into a single vast work of magic. The work of Azor himself, tweaked and modified by the combined genius of hundreds of the Izzet’s best. Ral felt a fierce pride in his guild, his adopted home. #emph[We’ll make it.] #emph[] #linebreak The thought of his bed was suddenly unbelievably appealing. Ral got up from his desk with a groan as his aching body complained, stretched, and stumbled toward the door. Plans for the attack on Gruul territory were well under way, with Aurelia handling the tactical details. Ral would be the first to admit he was no military expert, so he was happy to leave those matters to the angel and her subordinates. #emph[So there’s no harm in my getting some sleep.] #emph[] #linebreak In the corridor outside his office, though, a thin figure sat cross-legged against the wall. Ral looked down at her and sighed. "Hekara." She didn’t move, and he prodded her with his boot. "Hekara." "I didn’ do nothing!" Hekara said, starting suddenly awake. "No one said you did," Ral said. "Sorry." She yawned and wiped her eyes. "I was waiting for you to finish." Ral held out a hand, and she took it and pulled herself up. Her skinny frame seemed to weigh almost nothing. She gave him a smile, as always, but there was a strain at the edges that felt off. "You missed the strategy meeting," Ral said. "I’d just have died of boredom," Hekara said. "His Stompiness says just tell us when you want our help. Against the Gruul, or . . ." She trailed off, then fell silent. "Hekara," Ral said. "What’s wrong?" "I just . . ." she began, then shook her head. "Ain’t there a way we can work things out with Vraska?" "Vraska is working for Bolas," Ral said. "She betrayed us all at the guild summit. She killed the supreme judge of the Azorius." "I #emph[know] ," Hekara said miserably. "I know all that. But she’s our #emph[mate] , Ral. We fought with her. You don’t go against your mates, not ever. That’s just . . . the way it is." "I understand." Ral put a hand on her shoulder and lowered his voice. "I . . . thought I could trust her." A rare thing. The old Ral, the Ral of his dreams, had decided never to trust anyone. With the help of Tomik and a few others—#emph[even Hekara, odd as that seems] —he’d thought that was beginning to change. But now . . . "She hasn’t given us any choice," Ral said. "Bolas is #emph[coming] , and if we’re going to stop him, we need those nodes. If Vraska tries to stop us, that makes her the enemy of all of Ravnica." "Yeah. But . . ." Hekara shook her head. "Never mind." She turned, dejectedly, and walked away. Ral looked after her for a moment, then sighed again, and headed for the stairs.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/flow-1_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 70pt) #block[This file tests a bug where an almost empty page occurs.] #block[ The text in this second block was torn apart and split up for some reason beyond my knowledge. ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/outrageous/0.1.0/outrageous.typ
typst
Apache License 2.0
#let align-helper(state-key, what-to-measure, display) = style(styles => { let max-width = state(state-key, 0pt) let this-width = measure(what-to-measure, styles).width max-width.update(max => calc.max(this-width, max)) locate(loc => { display(max-width.final(loc), this-width) }) }) #let presets = ( // outrageous preset for a Table of Contents outrageous-toc: ( font-weight: ("bold", auto), font-style: (auto,), vspace: (12pt, none), font: ("Noto Sans", auto), fill: (none, repeat[~~.]), fill-right-pad: .4cm, fill-align: true, body-transform: none, page-transform: none, ), // outrageous preset for List of Figures/Tables/Listings outrageous-figures: ( font-weight: (auto,), font-style: (auto,), vspace: (none,), font: (auto,), fill: (repeat[~~.],), fill-right-pad: .4cm, fill-align: true, body-transform: (lvl, body, state-key: "outline-figure-numbering-max-width") => { let (supplement, _, number, separator, ..text) = body.children let v = if number.text.ends-with(regex("[^\d]1[^\d]*")) and not number.text.starts-with("1") { v(10pt) } align-helper( state-key, [#number.], (max-width, this-width) => box[#v#number.#h(max-width - this-width) #text.join()], ) }, page-transform: none, ), // preset without any style changes typst: ( font-weight: (auto,), font-style: (auto,), vspace: (none,), font: (auto,), fill: (auto,), fill-right-pad: none, fill-align: false, body-transform: none, page-transform: none, ), ) #let show-entry( entry, font-weight: presets.outrageous-toc.font-weight, font-style: presets.outrageous-toc.font-style, vspace: presets.outrageous-toc.vspace, font: presets.outrageous-toc.font, fill: presets.outrageous-toc.fill, fill-right-pad: presets.outrageous-toc.fill-right-pad, fill-align: presets.outrageous-toc.fill-align, body-transform: presets.outrageous-toc.body-transform, page-transform: presets.outrageous-toc.page-transform, label: <outrageous-modified-entry>, state-key: "outline-page-number-max-width", ) = { fill-right-pad = if fill-right-pad == none { 0pt } else { fill-right-pad } let max-width = state(state-key, 0pt) if entry.at("label", default: none) == label { entry // prevent infinite recursion } else { let font-weight = font-weight.at(calc.min(font-weight.len(), entry.level) - 1) let font-style = font-style.at(calc.min(font-style.len(), entry.level) - 1) let vspace = vspace.at(calc.min(vspace.len(), entry.level) - 1) let font = font.at(calc.min(font.len(), entry.level) - 1) let fill = fill.at(calc.min(fill.len(), entry.level) - 1) set text(font: font) if font not in (auto, none) set text(weight: font-weight) if font-weight not in (auto, none) set text(style: font-style) if font-style not in (auto, none) if vspace != none { v(vspace, weak: true) } let fields = entry.fields() if body-transform != none { let new-body = body-transform(entry.level, entry.body) fields.body = if new-body == none { entry.body } else { new-body } } if page-transform != none { let new-page = page-transform(entry.level, entry.page) fields.page = if new-page == none { entry.page } else { new-page } } if fill in (none, auto) or not fill-align { if fill != auto { fields.fill = if fill == none { none } else { box(width: 100% - fill-right-pad, fill) } } [#outline.entry(..fields.values()) #label] } else { align-helper( state-key, entry.page, (max-width, this-width) => { let fields = fields fields.fill = box(width: 100% - (max-width - this-width) - fill-right-pad, fill) [#outline.entry(..fields.values()) #label] } ) } } }
https://github.com/Lucas-Wye/tech-note
https://raw.githubusercontent.com/Lucas-Wye/tech-note/main/src/ask.typ
typst
= How to Ask Question #label("how-to-ask-question") #link("http://www.catb.org/%7Eesr/faqs/smart-questions.html")[Click here]
https://github.com/jomaway/typst-bytefield
https://raw.githubusercontent.com/jomaway/typst-bytefield/main/lib/gen.typ
typst
MIT License
#import "types.typ": * #import "utils.typ": * #import "asserts.typ": * #import "states.typ": * #let assert-level-cols(levels, cols, side) = { if (cols != auto) { cols = if (int == type(cols)) { cols } else if (array == type(cols)) { cols.len() } else { panic(strfmt("expected {} argument to be auto, int or array, found {}",if (side == "left") {"pre"} else {"post"} ,type(cols) )) } assert(cols >= levels, message: strfmt("max notes level on the {} is {}, but found only {} cols.",side, levels, cols)) } } /// generate metadata which is needed later on #let generate-meta(fields, args) = { // collect metadata into an dictionary let bh = fields.find(f => is-header-field(f)) // check level indentation for annotations let (pre-levels, post-levels) = get-max-annotation-levels(fields.filter(f => is-note-field(f) )) assert-level-cols(pre-levels, args.side.left-cols, "left") assert-level-cols(post-levels, args.side.right-cols, "right") // check if msb value is valid assert(args.msb in (left,right), message: strfmt("expected left or right for msb, found {}", args.msb)) let meta = ( // the total size in bits of all data-fields inside the bytefield. // todo: check if this is calculated correct if msb:left is selected. size: fields.filter(f => is-data-field(f) ).map(f => if (f.data.size == auto) { args.bpr /* fix: this is not consistent with how auto is handled in generate_fields */ } else { f.data.size } ).sum(), // the position of the msb (left | right), default: right msb: args.msb, // number of cols for each grid. cols: ( pre: pre-levels, main: args.bpr, post: post-levels, ), // contains the height of the rows. rows: ( header: auto, // !unused main: args.rows, // default: auto ), // contains information about the header header: if (bh == none) { none } else { ( fill: bh.data.format.at("fill", default: none), stroke: bh.data.format.at("stroke", default: none), ) }, // stores the cols arguments for annotations side: ( left: ( cols: if (args.side.left-cols == auto) { (auto,)*pre-levels } else { args.side.left-cols }, ), right: ( cols: if (args.side.right-cols == auto) { (auto,)*post-levels } else { args.side.right-cols }, ) ) ) return meta; } /// helper to calc number values from autofill string arguments #let get-header-autofill-values(autofill, fields, meta) = { if (autofill == "bounds") { return fields.filter(f => is-data-field(f)).map(f => if f.data.range.start == f.data.range.end { (f.data.range.start,) } else {(f.data.range.start, f.data.range.end)}).flatten() } else if (autofill == "all") { return range(meta.size) } else if (autofill == "offsets") { let _fields = fields.filter(f => is-data-field(f)).map(f => f.data.range.start).flatten() _fields.push(meta.cols.main -1) _fields.push(meta.size -1) return _fields.dedup() } else if (autofill == "bytes") { let _fields = range(meta.size, step: 8) _fields.push(meta.cols.main -1) _fields.push(meta.size -1) return _fields.dedup() } else { () } } /// Index all fields #let index-fields(fields) = { fields.enumerate().map(((idx, f)) => { assert-bf-field(f) dict-insert-and-return(f, "field-index", idx) }) } /// indexes all fields and add some additional field data #let finalize-fields(fields, meta) = { // This part must be changed if the user low level api changes. let _fields = index-fields(fields) // Define some variables let bpr = meta.cols.main let range_idx = 0; let fields = (); // data fields - important! must be processed first. let data_fields = _fields.filter(f => is-data-field(f)) if (meta.msb == left ) { data_fields = data_fields.rev() } for f in data_fields { let size = if (f.data.size == auto) { bpr - calc.rem(range_idx, bpr) } else { f.data.size } let start = range_idx; range_idx += size; let end = range_idx - 1; fields.push(data-field(f.field-index, size, start, end, f.data.label, format: f.data.format)) } // note fields for f in _fields.filter(f => is-note-field(f)) { let row = if (f.data.row == auto) { let anchor = get-index-of-next-data-field(f.field-index, _fields) let anchor_field = fields.find(f => f.field-index == anchor) int( if (meta.msb == left) { (meta.size - anchor_field.data.range.end)/bpr } else { anchor_field.data.range.start/bpr }) } else { f.data.row } let data = dict-insert-and-return(f.data, "row", row) let field = dict-insert-and-return(f, "data", data) assert-note-field(field); fields.push(field) } // header fields -- needs data fields already processed !! for f in _fields.filter(f => is-header-field(f)) { let autofill_values = get-header-autofill-values(f.data.autofill, fields, meta); let numbers = if f.data.numbers == none { () } else { f.data.numbers + autofill_values } let labels = f.data.at("labels", default: (:)) fields.push(header-field( start: if f.data.range.start == auto { if meta.msb == right { 0 } else { meta.size - bpr } } else { assert.eq(type(f.data.range.start),int); f.data.range.start }, end: if f.data.range.end == auto { if meta.msb == right { bpr } else { meta.size } } else { assert.eq(type(f.data.range.end),int); f.data.range.end }, numbers: numbers, labels: labels, ..f.data.format, )) break // workaround to only allow one bitheader till multiple bitheaders are supported. } return fields } /// generate data cells from data-fields #let generate-data-cells(fields, meta) = { let data_fields = fields.filter(f => is-data-field(f)) if (meta.msb == left ) { data_fields = data_fields.rev() } data_fields = data_fields let bpr = meta.cols.main; let _cells = (); let idx = 0; for field in data_fields { assert-data-field(field) let len = field.data.size let slice_idx = 0; let should_span = is-multirow(field, bpr) let current_offset = calc.rem(idx, bpr) while len > 0 { let rem_space = bpr - calc.rem(idx, bpr); let cell_size = calc.min(len, rem_space); // calc stroke let _default_stroke = (1pt + black) let _stroke = ( top: _default_stroke, bottom: _default_stroke, rest: _default_stroke, ) if ((len - cell_size) > 0 and data_fields.last().field-index != field.field-index) { _stroke.at("bottom") = field.data.format.fill } if (slice_idx > 0){ _stroke.at("top") = none } let cell_index = (field.field-index, slice_idx) let x_pos = calc.rem(idx,bpr) let y_pos = int(idx/bpr) let cell_format = ( stroke: _stroke, ..field.data.format, ) // adjust label for breaking fields. let middle = int(field.data.size / 2 / bpr) // roughly calc the row where the label should be displayed let label = if (should_span or middle == slice_idx) { field.data.label } else if (slice_idx < 2 and len < bpr) { "..." } else {none} // prepare for next cell let tmp_size = if should_span {field.data.size} else {cell_size} idx += tmp_size; len -= tmp_size; slice_idx += 1; // add bf-cell to _cells _cells.push( //type, grid, x, y, colspan:1, rowspan:1, label, idx ,format: auto bf-cell("data-cell", x: x_pos, y: y_pos, colspan: cell_size, rowspan: if(should_span) { int(field.data.size/bpr)} else {1}, label: label, cell-index: cell_index, format: cell_format ) ) } } return _cells } /// generate note cells from note-fields #let generate-note-cells(fields, meta) = { let note_fields = fields.filter(f => is-note-field(f)) let _cells = () let bpr = meta.cols.main for field in note_fields { assert-note-field(field) let side = field.data.side let level = field.data.level _cells.push( bf-cell("note-cell", cell-index: (field.field-index, 0), grid: side, x: if (side == left) { meta.cols.pre - level - 1 } else { level }, y: int(field.data.row), rowspan: field.data.rowspan, label: field.data.label, format: field.data.format, ) ) } return _cells } /// generate header cells from header-fields #let generate-header-cells(fields, meta) = { let header_fields = fields.filter(f => is-header-field(f)) let bpr = meta.cols.main let _cells = () for header in header_fields { assert-header-field(header) let nums = header.data.at("numbers", default: ()) + header.data.at("labels").keys().map(k => int(k)) let cell = nums.filter(num => num >= header.data.range.start and num < header.data.range.end).dedup().map(num =>{ // extract the label from the header field. let label = header.data.labels.at(str(num), default: "") // check if the number should be shown on this cell. let show_number = num in header.data.numbers // calculate the x position inside the grid depending on the msb let x_pos = if (meta.msb == left) { (bpr - 1) - calc.rem(num,bpr) } else { calc.rem(num, bpr) } // check if a marker should be used. let marker = header.data.format.at("marker", default: true) // false if (type(marker) == array) { assert(marker.len() == 2, message: strfmt("expected a array of length two, found array with length {}", marker.len())); if (show_number) { marker = marker.at(0, default: true) } else { marker = marker.at(1, default: true) } } assert(type(marker) == bool, message: strfmt("expects marker to be a bool, found {}", type(marker))); bf-cell("header-cell", cell-index: (header.field-index, num), grid: top, x: x_pos, y: 0, label: ( num: str(num), text: label, ), format: ( // Defines if the number should be shown or ommited number: show_number, // Defines the angle of the labels angle: header.data.format.at("angle", default: -60deg), // Defines the text-size for both numbers and labels. text-size: header.data.format.at("text-size",default: auto), // Defines if a marker should be shown marker: marker, // Defines the alignment align: header.data.format.at("align", default: center + bottom), // Defines the inset inset: header.data.format.at("inset", default: (x: 0pt, y: 4pt)), ) ) }) _cells.push(cell) } return _cells } /// generates cells from fields #let generate-cells(meta, fields) = { // data let data_cells = generate-data-cells(fields, meta); // notes let note_cells = generate-note-cells(fields, meta); // header let header_cells = generate-header-cells(fields, meta); return (header_cells, data_cells, note_cells).flatten() } /// map bf custom cells to tablex cells #let map-cells(cells) = { cells.map(c => { assert-bf-cell(c) let body = if is-header-cell(c) { let label_text = c.label.text let label_num = c.label.num context { style(styles => { set text(if c.format.text-size == auto { get-default-header-font-size() } else { c.format.text-size }) set align(center + bottom) let size = measure(label_text, styles).width stack(dir: ttb, spacing: 0pt, if is-not-empty(label_text) { box(height: size, inset: (left: 50%, rest: 0pt))[ #set align(start) #rotate(c.format.at("angle"), origin: left, label_text) ] }, if (is-not-empty(label_text) and c.format.at("marker") != false){ line(end:(0pt, 5pt)) }, if c.format.number {box(inset: (top:3pt, rest: 0pt), label_num)}, ) }) } } else { { [ #if (is-data-cell(c) and (get-default-field-font-size() != auto)) { [ #set text(get-default-field-font-size()); #c.label ] } else if (is-note-cell(c) and (get-default-note-font-size() != auto)) { [ #set text(get-default-note-font-size()); #c.label ] } else { c.label } ] } } return grid.cell( x: c.position.x, y: c.position.y, colspan: c.span.cols, rowspan: c.span.rows, inset: c.format.at("inset", default: 0pt), stroke: c.format.at("stroke", default: none), fill: c.format.at("fill", default: none), align: c.format.at("align", default: center + horizon), body ) }) } /// produce the final output #let generate-table(meta, cells) = { let table = context { let rows = if (meta.rows.main == auto) { get-default-row-height() } else { meta.rows.main } if (type(rows) == array) { rows = rows.map(r => if (r == auto) { get-default-row-height() } else { r } )} // somehow grid_header still needs to exists. let grid_header = if (meta.header != none) { grid( columns: (1fr,)*meta.cols.main, rows: auto, ..map-cells(cells.filter(c => is-in-header-grid(c))) ) } else { none } let grid_left = grid( columns: meta.side.left.cols, rows: rows, ..map-cells(cells.filter(c => is-in-left-grid(c))) ) let grid_right = grid( columns: meta.side.right.cols, rows: rows, ..map-cells(cells.filter(c => is-in-right-grid(c))) ) let grid_center = grid( columns:(1fr,)*meta.cols.main, rows: rows, ..map-cells(cells.filter(c => is-in-main-grid(c))) ) return grid( columns: (if (meta.cols.pre > 0) { auto } else { 0pt }, 1fr, if (meta.cols.post > 0) { auto } else { 0pt }), inset: 0pt, ..if (meta.header != none) { ([/* top left*/], align(bottom, box( width: 100%, fill: if (meta.header.fill != auto) { meta.header.fill } else { get-default-header-background() }, stroke: if (meta.header.stroke != auto) { meta.header.stroke } else { get-default-header-border() }, grid_header )), [/*top right*/],) }, align(top,grid_left), align(top,grid_center), align(top,grid_right), ) } return table }
https://github.com/crd2333/typst-admonition
https://raw.githubusercontent.com/crd2333/typst-admonition/master/examples/example.typ
typst
MIT License
#import "../lib.typ": * #note(caption: [Self_defined Title], footer: [This is a footer.])[admonitions implemented by showybox, making the box more flexible.] #info(caption: "Change size and info", caption_size: 20pt, size: 14pt, [Caption and content size can be changed.], [Currently supported types are:\ *note, abstract, info, tip, success, question, warning, failure, bug, danger, example, quote.* ] ) #abstract(caption: "Abstract", footer: [This is a footer.])[test] #note(icon: emoji.face.cry)[command for note but use emoji icon] #info(caption: "Info", [test], footer: [This is a footer.], ) #tip(caption: "Tip", [test], footer: [This is a footer.], ) #success( [test], footer: [This is a footer.], ) #question( [This block is breakable.], footer: [This is a footer.], ) #warning( [test], footer: [This is a footer.], ) #failure( [test], footer: [This is a footer.], ) #bug( [test], footer: [This is a footer.], ) #danger( [test], footer: [This is a footer.], ) #example( [test], footer: [This is a footer.], ) #example2( [test], footer: [This is a footer.], ) #quote( [test], footer: [This is a footer.], )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/data-13.typ
typst
Other
// Error: 6-16 failed to parse xml file: found closing tag 'data' instead of 'hello' in line 3 #xml("test/assets/files/bad.xml")
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch05-htmx-patterns.typ
typst
Other
#import "lib/definitions.typ": * == Htmx Patterns Now that we’ve seen how htmx extends HTML as a hypermedia, it’s time to put it into action. As we use htmx, we will still be using hypermedia: we will issue HTTP requests and get back HTML. But, with the additional functionality that htmx provides, we will have a more _powerful hypermedia_ to work with, allowing us to accomplish much more sophisticated interfaces. This will allow us to address user experience issues, such as long feedback cycles or painful page refreshes, without needing to write much, if any, JavaScript, and without creating a JSON API. Everything will be implemented in hypermedia, using the core hypermedia concepts of the early web. === Installing Htmx <_installing_htmx> #index[htmx][installing] The first thing we need to do is install htmx in our web application. We are going to do this by downloading the source and saving it locally in our application, so we aren’t dependent on any external systems. This is known as "vendoring" the library. We can grab the latest version of htmx by navigating our browser to `https://unpkg.com/htmx.org`, which will redirect us to the source of the latest version of the library. We can save the content from this URL into the `static/js/htmx.js` file in our project. You can, of course, use a more sophisticated JavaScript package manager such as Node Package Manager (NPM) or yarn to install htmx. You do this by referring to its package name, `htmx.org`, in the manner appropriate for your tool. However, htmx is very small (approximately 12kb when compressed and zipped) and is dependency free, so using it does not require an elaborate mechanism or build tool. With htmx downloaded locally to our applications `/static/js` directory, we can now load it in to our application. We do this by adding the following `script` tag to the `head` tag in our `layout.html` file, which will make htmx available and active on every page in our application: #figure(caption: [Installing htmx], ```html <head> <script src="/js/htmx.js"></script> ... </head> ```) Recall that the `layout.html` file is a _layout_ file included in most templates that wraps the content of those templates in common HTML, including a `head` element that we are using here to install htmx. Believe it or not, that’s it! This simple script tag will make htmx’s functionality available across our entire application. === AJAX-ifying Our Application <_ajax_ifying_our_application> #index[hx-boost] #index[htmx patterns][boosting] To get our feet wet with htmx, the first feature we are going to take advantage of is known as "boosting." This is a bit of a "magic" feature in that we don’t need to do much beyond adding a single attribute, `hx-boost`, to the application. When you put `hx-boost` on a given element with the value `true`, it will "boost" all anchor and form elements within that element. "Boost", here, means that htmx will convert all those anchors and forms from "normal" hypermedia controls into AJAX-powered hypermedia controls. Rather than issuing "normal" HTTP requests that replace the whole page, the links and forms will issue AJAX requests. Htmx then swaps the inner content of the `<body>` tag in the response to these requests into the existing pages `<body>` tag. This makes navigation feel faster because the browser will not be re-interpreting most of the tags in the response `<head>` and so forth. ==== Boosted Links <_boosted_links> Let’s take a look at an example of a boosted link. Below is a link to a hypothetical settings page for a web application. Because it has `hx-boost="true"` on it, htmx will halt the normal link behavior of issuing a request to the `/settings` path and replacing the entire page with the response. Instead, htmx will issue an AJAX request to `/settings`, take the result and replace the `body` element with the new content. #figure(caption: [A boosted link], ```html <a href="/settings" hx-boost="true">Settings</a> <1> ```) 1. The `hx-boost` attribute makes this link AJAX-powered. You might reasonably ask: what’s the advantage here? We are issuing an AJAX request and simply replacing the entire body. Is that significantly different from just issuing a normal link request? Yes, it is in fact different: with a boosted link, the browser is able to avoid any processing associated with the head tag. The head tag often contains many scripts and CSS file references. In the boosted scenario, it is not necessary to re-process those resources: the scripts and styles have already been processed and will continue to apply to the new content. This can often be a very easy way to speed up your hypermedia application. A second question you might have is: does the response need to be formatted specially to work with `hx-boost`? After all, the settings page would normally render an `html` tag, with a `head` tag and so forth. Do you need to handle "boosted" requests specially? The answer is no: htmx is smart enough to pull out only the content of the `body` tag to swap in to the new page. The `head` tag is mostly ignored: only the title tag, if it is present, will be processed. This means you don’t need to do anything special on the server side to render templates that `hx-boost` can handle: just return the normal HTML for your page, and it should work fine. Note that boosted links (and forms) will also continue to update the navigation bar and history, just like normal links, so users will be able to use the browser back button, will be able to copy and paste URLs (or "deep links") and so on. Links will act pretty much like "normal", they will just be faster. ==== Boosted Forms <_boosted_forms> Boosted form tags work in a similar way to boosted anchor tags: a boosted form will use an AJAX request rather than the usual browser-issued request, and will replace the entire body with the response. Here is an example of a form that posts messages to the `/messages` endpoint using an HTTP `POST` request. By adding `hx-boost` to it, those requests will be done in AJAX, rather than the normal browser behavior. #figure(caption: [A boosted form], ```html <form action="/messages" method="post" hx-boost="true"> <1> <input type="text" name="message" placeholder="Enter A Message..."> <button>Post Your Message</button> </form> ```) 1. As with the link, `hx-boost` makes this form AJAX-powered. #index[Flash Of Unstyled Content (FOUC)] A big advantage of the AJAX-based request that `hx-boost` uses (and the lack of head processing that occurs) is that it avoids what is known as a _flash of unstyled content_: / Flash Of Unstyled Content (FOUC): A situation where a browser renders a web page before all the styling information is available for the page. A FOUC causes a disconcerting momentary "flash" of the unstyled content, which is then restyled when all the style information is available. You will notice this as a flicker when you move around the internet: text, images and other content can "jump around" on the page as styles are applied to it. With `hx-boost` the site’s styling is already loaded _before_ the new content is retrieved, so there is no such flash of unstyled content. This can make a "boosted" application feel both smoother and also snappier in general. ==== Attribute Inheritance <_attribute_inheritance> Let’s expand on our previous example of a boosted link, and add a few more boosted links alongside it. We’ll add links so that we have one to the `/contacts` page, the `/settings` page, and the `/help` page. All these links are boosted and will behave in the manner that we have described above. This feels a little redundant, doesn’t it? It seems silly to annotate all three links with the `hx-boost="true"` attribute right next to one another. #figure(caption: [A set of boosted links], ```html <a href="/contacts" hx-boost="true">Contacts</a> <a href="/settings" hx-boost="true">Settings</a> <a href="/help" hx-boost="true">Help</a> ```) #index[htmx][attribute inheritance] Htmx offers a feature to help reduce this redundancy: attribute inheritance. With most attributes in htmx, if you place it on a parent, the attribute will also apply to children elements. This is how Cascading Style Sheets work, and that idea inspired htmx to adopt a similar "cascading htmx attributes" feature. To avoid the redundancy in this example, let’s introduce a `div` element that encloses all the links and then "hoist" the `hx-boost` attribute up to that parent `div`. This will let us remove the redundant `hx-boost` attributes but ensure all the links are still boosted, inheriting that functionality from the parent `div`. Note that any legal HTML element could be used here, we just use a `div` out of habit. #figure(caption: [Boosting links via the parent], ```html <div hx-boost="true"> <1> <a href="/contacts">Contacts</a> <a href="/settings">Settings</a> <a href="/help">Help</a> </div> ```) 1. The `hx-boost` has been moved to the parent div. Now we don’t have to put an `hx-boost="true"` on every link and, in fact, we can add more links alongside the existing ones, and they, too, will be boosted, without us needing to explicitly annotate them. That’s fine, but what if you have a link that you _don’t_ want boosted within an element that has `hx-boost="true"` on it? A good example of this situation is when a link is to a resource to be downloaded, such as a PDF. Downloading a file can’t be handled well by an AJAX request, so you probably want that link to behave "normally", issuing a full page request for the PDF, which the browser will then offer to save as a file on the user’s local system. To handle this situation, you simply override the parent `hx-boost` value with `hx-boost="false"` on the anchor tag that you don’t want to boost: #figure(caption: [Disabling boosting], ```html <div hx-boost="true"> <1> <a href="/contacts">Contacts</a> <a href="/settings">Settings</a> <a href="/help">Help</a> <a href="/help/documentation.pdf" hx-boost="false"> <2> Download Docs </a> </div> ```) 1. The `hx-boost` is still on the parent div. 2. The boosting behavior is overridden for this link. #index[hx-boost][disabling] Here we have a new link to a documentation PDF that we wish to function like a regular link. We have added `hx-boost="false"` to the link and this declaration will override the `hx-boost="true"` on the parent `div`, reverting it to regular link behavior and, thus, allowing for the file download behavior that we want. ==== Progressive Enhancement <_progressive_enhancement> #index[progressive enhancement] A nice aspect of `hx-boost` is that it is an example of _progressive enhancement_: / Progressive Enhancement: #[ A software design philosophy that aims to provide as much essential content and functionality to as many users as possible, while delivering a better experience to users with more advanced web browsers. ] Consider the links in the example above. What would happen if someone did not have JavaScript enabled? No problem. The application would continue to work, but it would issue regular HTTP requests, rather than AJAX-based HTTP requests. This means that your web application will work for the maximum number of users; those with modern browsers (or users who have not turned off JavaScript) can take advantage of the benefits of the AJAX-style navigation that htmx offers, and others can still use the app just fine. Compare the behavior of htmx’s `hx-boost` attribute with a JavaScript heavy Single Page Application: such an application often won’t function _at all_ without JavaScript enabled. It is often very difficult to adopt a progressive enhancement approach when you use an SPA framework. This is _not_ to say that every htmx feature offers progressive enhancement. It is certainly possible to build features that do not offer a "No JS" fallback in htmx, and, in fact, many of the features we will build later in the book will fall into this category. We will note when a feature is progressive enhancement friendly and when it is not. Ultimately, it is up to you, the developer, to decide if the trade-offs of progressive enhancement (a more basic UX, limited improvements over plain HTML) are worth the benefits for your application users. ==== Adding "hx-boost" to Contact.app <_adding_hx_boost_to_contact_app> For the contact app we are building, we want this htmx "boost" behavior…​ well, everywhere. Right? Why not? How could we accomplish that? Well, it’s easy (and pretty common in htmx-powered web applications): we can just add `hx-boost` on the `body` tag of our `layout.html` template, and we are done. #figure(caption: [Boosting the entire contact.app], ```html <html> ... <body hx-boost="true"> <1> ... </body> </html> ```) 1. All links and forms will be boosted now! Now every link and form in our application will use AJAX by default, making it feel much snappier. Consider the "New Contact" link that we created on the main page: #figure(caption: [A newly boosted "add contact" link], ```html <a href="/contacts/new">Add Contact</a> ```) Even though we haven’t touched anything on this link or on the server-side handling of the URL it targets, it will now "just work" as a boosted link, using AJAX for a snappier user experience, including updating history, back button support and so on. And, if JavaScript isn’t enabled, it will fall back to the normal link behavior. All this with one htmx attribute. The `hx-boost` attribute is neat, but is different than other htmx attributes in that it is pretty "magical": by making one small change you modify the behavior of a large number of elements on the page, turning them into AJAX-powered elements. Most other htmx attributes are generally lower level and require more explicit annotations in order to specify exactly what you want htmx to do. In general, this is the design philosophy of htmx: prefer explicit over implicit and obvious over "magic." However, the `hx-boost` attribute was too useful to allow dogma to override practicality, and so it is included as a feature in the library. === A Second Step: Deleting Contacts With HTTP DELETE <_a_second_step_deleting_contacts_with_http_delete> For our next step with htmx, recall that Contact.app has a small form on the edit page of a contact that is used to delete the contact: #figure(caption: [Plain HTML form to delete a contact], ```html <form action="/contacts/{{ contact.id }}/delete" method="post"> <button>Delete Contact</button> </form> ```) This form issued an HTTP `POST` to, for example, `/contacts/42/delete`, in order to delete the contact with the ID 42. #index[hx-delete] We mentioned previously that one of the annoying things about HTML is that you can’t issue an HTTP `DELETE` (or `PUT` or `PATCH`) request directly, even though these are all part of HTTP and HTTP is _obviously designed_ for transferring HTML. Thankfully, now, with htmx, we have a chance to rectify this situation. The "right thing," from a RESTful, resource-oriented perspective is, rather than issuing an HTTP `POST` to `/contacts/42/delete`, to issue an HTTP `DELETE` to `/contacts/42`. We want to delete the contact. The contact is a resource. The URL for that resource is `/contacts/42`. So the ideal is a `DELETE` request to `/contacts/42/`. Let’s update our application to do this by adding the htmx `hx-delete` attribute to the "Delete Contact" button: #figure(caption: [An htmx-powered button for deleting a contact], ```html <button hx-delete="/contacts/{{ contact.id }}">Delete Contact</button> ```) Now, when a user clicks this button, htmx will issue an HTTP `DELETE` request via AJAX to the URL for the contact in question. #index[htmx patterns][delete] A couple of things to notice: - We no longer need a `form` tag to wrap the button, because the button itself carries the hypermedia action that it performs directly on itself. - We no longer need to use the somewhat awkward `"/contacts/{{ contact.id }}/delete"` route, but can simply use the `"/contacts/{{ contact.id }}` route, since we are issuing a `DELETE`. By using a `DELETE` we disambiguate between a request intended to update the contact and a request intended to delete it, using the native HTTP tools available for exactly this reason. Note that we have done something pretty magical here: we have turned this button into a _hypermedia control_. It is no longer necessary that this button be placed within a larger `form` tag in order to trigger an HTTP request: it is a stand-alone, and fully featured hypermedia control on its own. This is at the heart of htmx, allowing any element to become a hypermedia control and fully participate in a Hypermedia-Driven Application. We should also note that, unlike with the `hx-boost` examples above, this solution will _not_ degrade gracefully. To make this solution degrade gracefully, we would need to wrap the button in a form element and handle a `POST` on the server side as well. In the interest of keeping our application simple, we are going to omit that more elaborate solution. ==== Updating The Server-Side Code <_updating_the_server_side_code> We have updated the client-side code (if HTML can be considered code) so it now issues a `DELETE` request to the appropriate URL, but we still have some work to do. Since we updated both the route and the HTTP method we are using, we are going to need to update the server-side implementation as well to handle this new HTTP request. #figure(caption: [The original server-side code for deleting a contact], ```python @app.route("/contacts/<contact_id>/delete", methods=["POST"]) def contacts_delete(contact_id=0): contact = Contact.find(contact_id) contact.delete() flash("Deleted Contact!") return redirect("/contacts") ```) We’ll need to make two changes to our handler: update the route, and update the HTTP method we are using to delete contacts. #figure(caption: [Updated handler with new route and method], ```python @app.route("/contacts/<contact_id>", methods=["DELETE"]) <1> def contacts_delete(contact_id=0): contact = Contact.find(contact_id) contact.delete() flash("Deleted Contact!") return redirect("/contacts") ```) 1. An updated path and method for the handler. Pretty simple, and much cleaner. ===== A response code gotcha <_a_response_code_gotcha> #index[Flask][redirect] Unfortunately, there is a problem with our updated handler: by default, in Flask the `redirect()` method responds with a `302 Found` HTTP Response Code. According to the Mozilla Developer Network (MDN) web docs on the #link( "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302", )[`302 Found`] response, this means that the HTTP _method_ of the request _will be unchanged_ when the redirected HTTP request is issued. We are now issuing a `DELETE` request with htmx and then being redirected to the `/contacts` path by flask. According to this logic, that would mean that the redirected HTTP request would still be a `DELETE` method. This means that, as it stands, the browser will issue a `DELETE` request to `/contacts`. This is definitely _not_ what we want: we would like the HTTP redirect to issue a `GET` request, slightly modifying the Post/Redirect/Get behavior we discussed earlier to be a Delete/Redirect/Get. Fortunately, there is a different response code, #link( "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303", )[`303 See Other`], that does what we want: when a browser receives a `303 See Other` redirect response, it will issue a `GET` to the new location. So we want to update our code to use the `303` response code in the controller. Thankfully, this is very easy: there is a second parameter to `redirect()` that takes the numeric response code you wish to send. #figure(caption: [Updated handler with `303` redirect response], ```python @app.route("/contacts/<contact_id>", methods=["DELETE"]) def contacts_delete(contact_id=0): contact = Contact.find(contact_id) contact.delete() flash("Deleted Contact!") return redirect("/contacts", 303) <1> ```) 1. The response code is now a 303. Now, when you want to remove a given contact, you can simply issue a `DELETE` to the same URL as you used to access the contact in the first place. This is a natural HTTP-based approach to deleting a resource. ==== Targeting The Right Element <_targeting_the_right_element> #index[hx-target][example] We aren’t quite finished with our updated delete button. Recall that, by default, htmx "targets" the element that triggers a request, and will place the HTML returned by the server inside that element. Right now, the "Delete Contact" button is targeting itself. That means that, since the redirect to the `/contacts` URL is going to re-render the entire contact list, we will end up with that contact list placed _inside_ the "Delete Contact" button. Mis-targeting like this comes up from time to time when you are working with htmx and can lead to some pretty funny situations. The fix for this is easy: add an explicit target to the button, and target the `body` element with the response: #figure(caption: [A fixed htmx-powered button for deleting a contact], ```html <button hx-delete="/contacts/{{ contact.id }}" hx-target="body"> <1> Delete Contact </button> ```) 1. An explicit target added to the button. Now our button behaves as expected: clicking on the button will issue an HTTP `DELETE` to the server against the URL for the current contact, delete the contact and redirect back to the contact list page, with a nice flash message. Is everything working smoothly now? ==== Updating The Location Bar URL Properly <_updating_the_location_bar_url_properly> Well, almost. #index[htmx][location bar] If you click on the button you will notice that, despite the redirect, the URL in the location bar is not correct. It still points to `/contacts/{{ contact.id }}`. That’s because we haven’t told htmx to update the URL: it just issues the `DELETE` request and then updates the DOM with the response. As we mentioned, boosting via `hx-boost` will naturally update the location bar for you, mimicking normal anchors and forms, but in this case we are building a custom button hypermedia control to issue a `DELETE`. We need to let htmx know that we want the resulting URL from this request "pushed" into the location bar. #index[hx-push-url] We can achieve this by adding the `hx-push-url` attribute with the value `true` to our button: #figure(caption: [Deleting a contact, now with proper location information], ```html <button hx-delete="/contacts/{{ contact.id }}" hx-target="body" hx-push-url="true"> <1> Delete Contact </button> ```) 1. We tell htmx to push the redirected URL up into the location bar. _Now_ we are done. We have a button that, all by itself, is able to issue a properly formatted HTTP `DELETE` request to the correct URL, and the UI and location bar are all updated correctly. This was accomplished with three declarative attributes placed directly on the button: `hx-delete`, `hx-target` and `hx-push-url`. This required more work than the `hx-boost` change, but the explicit code makes it easy to see what the button is doing as a custom hypermedia control. The resulting solution feels clean; it takes advantage of the built-in features of the web as a hypermedia system without any URL hacks. ==== One More Thing…​ <_one_more_thing> #index[hx-confirm] #index[htmx patterns][confirmation dialog] There is one additional "bonus" feature we can add to our "Delete Contact" button: a confirmation dialog. Deleting a contact is a destructive operation and as it stands right now, if the user inadvertently clicked the "Delete Contact" button, the application would just delete that contact. Too bad, so sad for the user. Fortunately htmx has an easy mechanism for adding a confirmation message on destructive operations like this: the `hx-confirm` attribute. You can place this attribute on an element, with a message as its value, and the JavaScript method `confirm()` will be called before a request is issued, which will show a simple confirmation dialog to the user asking them to confirm the action. Very easy and a great way to prevent accidents. Here is how we would add confirmation of the contact delete operation: #figure(caption: [Confirming deletion], ```html <button hx-delete="/contacts/{{ contact.id }}" hx-target="body" hx-push-url="true" hx-confirm="Are you sure you want to delete this contact?"> <1> Delete Contact </button> ```) 1. This message will be shown to the user, asking them to confirm the delete. Now, when someone clicks on the "Delete Contact" button, they will be presented with a prompt that asks "Are you sure you want to delete this contact?" and they will have an opportunity to cancel if they clicked the button in error. Very nice. With this final change we now have a pretty solid "delete contact" mechanism: we are using the correct RESTful routes and HTTP Methods, we are confirming the deletion, and we have removed a lot of the cruft that normal HTML imposes on us, all while using declarative attributes in our HTML and staying firmly within the normal hypermedia model of the web. ==== Progressive Enhancement? <_progressive_enhancement_2> #index[progressive enhancement] As we noted earlier about this solution: it is _not_ a progressive enhancement to our web application. If someone has disabled JavaScript then this "Delete Contact" button will no longer work. We would need to do additional work to keep the older form-based mechanism working in a JavaScript-disabled environment. Progressive Enhancement can be a hot-button topic in web development, with lots of passionate opinions and perspectives. Like nearly all JavaScript libraries, htmx makes it possible to create applications that do not function in the absence of JavaScript. Retaining support for non-JavaScript clients requires additional work and complexity in your application. It is important to determine exactly how important supporting non-JavaScript clients is before you begin using htmx, or any other JavaScript framework, for improving your web applications. === Next Steps: Validating Contact Emails <_next_steps_validating_contact_emails> #index[validation] Let’s move on to another improvement in our application. A big part of any web app is validating the data that is submitted to the server: ensuring emails are correctly formatted and unique, numeric values are valid, dates are acceptable, and so forth. Currently, our application has a small amount of validation that is done entirely server-side and that displays an error message when an error is detected. We are not going to go into the details of how validation works in the model objects, but recall what the code for updating a contact looks like from Chapter 3: #figure(caption: [Server-side validation on contact update], ```python def contacts_edit_post(contact_id=0): c = Contact.find(contact_id) c.update( request.form['first_name'], request.form['last_name'], request.form['phone'], request.form['email']) <1> if c.save(): flash("Updated Contact!") return redirect("/contacts/" + str(contact_id)) else: return render_template("edit.html", contact=c) <2> ```) 1. We attempt to save the contact. 2. If the save does not succeed we re-render the form to display error messages. So we attempt to save the contact, and, if the `save()` method returns true, we redirect to the contact’s detail page. If the `save()` method does not return true, that indicates that there was a validation error; instead of redirecting, we re-render the HTML for editing the contact. This gives the user a chance to correct the errors, which are displayed alongside the inputs. Let’s take a look at the HTML for the email input: #figure(caption: [Validation error messages], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="text" placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> <1> </p> ```) 1. Display any errors associated with the email field We have a label for the input, an input of type `text` and then a bit of HTML to display any error messages associated with the email. When the template is rendered on the server, if there are errors associated with the contact’s email, they will be displayed in this span, which will be highlighted red. #sidebar[Server-Side Validation Logic][Right now there is a bit of logic in the contact class that checks if there are any other contacts with the same email address, and adds an error to the contact model if so, since we do not want to have duplicate emails in the database. This is a very common validation example: emails are usually unique and adding two contacts with the same email is almost certainly a user error. Again, we are not going into the details of how validation works in our models, but almost all server-side frameworks provide ways to validate data and collect errors to display to the user. This sort of infrastructure is very common in Web 1.0 server-side frameworks.] The error message shown when a user attempts to save a contact with a duplicate email is "Email Must Be Unique", as seen in @fig-emailerror. #figure([#image("images/screenshot_validation_error.png")], caption: [ Email validation error ])<fig-emailerror> All of this is done using plain HTML and using Web 1.0 techniques, and it works well. However, as the application currently stands, there are two annoyances. - First, there is no email format validation: you can enter whatever characters you’d like as an email and, as long as they are unique, the system will allow it. - Second, we only check the email’s uniqueness when all the data is submitted: if a user has entered a duplicate email, they will not find out until they have filled in all the fields. This could be quite annoying if the user was accidentally reentering a contact and had to put all the contact information in before being made aware of this fact. ==== Updating Our Input Type <_updating_our_input_type> #index[HTML][inputs] For the first issue, we have a pure HTML mechanism for improving our application: HTML 5 supports inputs of type `email`. All we need to do is switch our input from type `text` to type `email`, and the browser will enforce that the value entered properly matches the email format: #figure(caption: [Changing the input to type `email`], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" <1> placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> </p> ```) 1. A change of the `type` attribute to `email` ensures that values entered are valid emails. With this change, when the user enters a value that isn’t a valid email, the browser will display an error message asking for a properly formed email in that field. So a simple single-attribute change done in pure HTML improves our validation and addresses the first problem we noted. #sidebar[Server-Side vs. Client-Side Validations][ Experienced web developers might be grinding their teeth at the code above: this validation is done on _the client-side_. That is, we are relying on the browser to detect the malformed email and correct the user. Unfortunately, the client-side is not trustworthy: a browser may have a bug in it that allows the user to circumvent this validation code. Or, worse, the user may be malicious and figure out a mechanism around our validation entirely, such as using the developer console to edit the HTML. This is a perpetual danger in web development: all validations done on the client-side cannot be trusted and, if the validation is important, _must be redone_ on the server-side. This is less of a problem in Hypermedia-Driven Applications than in Single Page Applications, because the focus of HDAs is the server-side, but it is worth bearing in mind as you build your application. ] ==== Inline Validation <_inline_validation> #index[htmx patterns][inline validation] While we have improved our validation experience a bit, the user must still submit the form to get any feedback on duplicate emails. We can next use htmx to improve this user experience. It would be better if the user were able to see a duplicate email error immediately after entering the email value. It turns out that inputs fire a `change` event and, in fact, the `change` event is the _default trigger_ for inputs in htmx. So, putting this feature to work, we can implement the following behavior: when the user enters an email, immediately issue a request to the server and validate that email, and render an error message if necessary. Recall the current HTML for our email input: #figure(caption: [The initial email configuration], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" placeholder="Email" value="{{ contact.email }}"> <1> <span class="error">{{ contact.errors['email'] }}</span> <2> </p> ```) 1. This is the input that we want to have drive an HTTP request to validate the email. 2. This is the span we want to put the error message, if any, into. So we want to add an `hx-get` attribute to this input. This will cause the input to issue an HTTP `GET` request to a given URL to validate the email. We then want to target the error span following the input with any error message returned from the server. Let’s make those changes to our HTML: #figure(caption: [Our updated HTML], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" hx-get="/contacts/{{ contact.id }}/email" <1> hx-target="next .error" <2> placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> </p> ```) 1. Issue an HTTP `GET` to the `email` endpoint for the contact. 2. Target the next element with the class `error` on it. Note that in the `hx-target` attribute we are using a _relative positional_ selector, `next`. This is a feature of htmx and an extension to normal CSS. Htmx supports prefixes that will find targets _relative_ to the current element. #sidebar[Relative Positional Expressions in Htmx][ / `next`: #[ Scan forward in the DOM for the next matching element, e.g., `next .error` ] / `previous`: #[ Scan backwards in the DOM for the closest previous matching element, e.g., `previous .alert` ] / `closest`: #[ Scan the parents of this element for matching element, e.g., `closest table` ] / `find`: #[ Scan the children of this element for matching element, e.g., `find span` ] / `this`: #[ the current element is the target (default) ] ] By using relative positional expressions we can avoid adding explicit ids to elements and take advantage of the local structure of HTML. So, in our example with added `hx-get` and `hx-target` attributes, whenever someone changes the value of the input (remember, `change` is the _default_ trigger for inputs in htmx) an HTTP `GET` request will be issued to the given URL. If there are any errors, they will be loaded into the error span. ==== Validating Emails Server-Side <_validating_emails_server_side> Next, let’s look at the server-side implementation. We are going to add another endpoint, similar to our edit endpoint in some ways: it is going to look up the contact based on the ID encoded in the URL. In this case, however, we only want to update the email of the contact, and we obviously don’t want to save it! Instead, we will call the `validate()` method on it. That method will validate the email is unique and so forth. At that point we can return any errors associated with the email directly, or the empty string if none exist. #figure(caption: [Code for our email validation endpoint], ```python @app.route("/contacts/<contact_id>/email", methods=["GET"]) def contacts_email_get(contact_id=0): c = Contact.find(contact_id) <1> c.email = request.args.get('email') <2> c.validate() <3> return c.errors.get('email') or "" <4> ```) 1. Look up the contact by id. 2. Update its email (note that since this is a `GET`, we use the `args` property rather than the `form` property). 3. Validate the contact. 4. Return a string, either the errors associated with the email field or, if there are none, the empty string. With this small bit of server-side code in place, we now have the following user experience: when a user enters an email and tabs to the next input field, they are immediately notified if the email is already taken. Note that the email validation is _still_ done when the entire contact is submitted for an update, so there is no danger of allowing duplicate email contacts to slip through: we have simply made it possible for users to catch this situation earlier by use of htmx. It is also worth noting that this particular email validation _must_ be done on the server side: you cannot determine that an email is unique across all contacts unless you have access to the data store of record. This is another simplifying aspect of Hypermedia-Driven Applications: since validations are done server-side, you have access to all the data you might need to do any sort of validation you’d like. Here again we want to stress that this interaction is done entirely within the hypermedia model: we are using declarative attributes and exchanging hypermedia with the server in a manner very similar to how links or forms work. But we have managed to improve our user experience dramatically. ==== Taking The User Experience Further <_taking_the_user_experience_further> Despite the fact that we haven’t added a lot of code here, we have a fairly sophisticated user interface, at least when compared with plain HTML-based applications. However, if you have used more advanced Single Page Applications you have probably seen the pattern where an email field (or a similar sort of input) is validated _as you type_. This seems like the sort of interactivity that is only possible with a sophisticated, complex JavaScript framework, right? Well, no. It turns out that you can implement this functionality in htmx, using pure HTML attributes. #index[hx-trigger][change] #index[hx-trigger][keyup] #index[event][change] #index[event][keyup] In fact, all we need to do is to change our trigger. Currently, we are using the default trigger for inputs, which is the `change` event. To validate as the user types, we would want to capture the `keyup` event as well: #figure(caption: [Triggering With `keyup` events], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" hx-get="/contacts/{{ contact.id }}/email" hx-target="next .error" hx-trigger="change, keyup" <1> placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> </p> ```) 1. An explicit `keyup` trigger has been added along with `change`. With this tiny change, every time a user types a character we will issue a request and validate the email. Simple. ==== Debouncing Our Validation Requests <_debouncing_our_validation_requests> #index[debouncing] Simple, yes, but probably not what we want: issuing a new request on every key up event would be very wasteful and could potentially overwhelm your server. What we want instead is only issue the request if the user has paused for a small amount of time. This is called "debouncing" the input, where requests are delayed until things have "settled down". Htmx supports a `delay` modifier for triggers that allows you to debounce a request by adding a delay before the request is sent. If another event of the same kind appears within that interval, htmx will not issue the request and will reset the timer. This turns out to be exactly what we want for our email input: if the user is busy typing in an email we won’t interrupt them, but as soon as they pause or leave the field, we’ll issue a request. Let’s add a delay of 200 milliseconds to the `keyup` trigger, which is long enough to detect that the user has stopped typing.: #figure(caption: [Debouncing the `keyup` event], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" hx-get="/contacts/{{ contact.id }}/email" hx-target="next .error" hx-trigger="change, keyup delay:200ms" <1> placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> </p> ```) 1. We debounce the `keyup` event by adding a `delay` modifier. Now we no longer issue a stream of validation requests as the user types. Instead, we wait until the user pauses for a bit and then issue the request. Much better for our server, and still a great user experience. ==== Ignoring Non-Mutating Keys <_ignoring_non_mutating_keys> There is one last issue we should address with the keyup event: as it stands we will issue a request no matter _which_ keys are pressed, even if they are keys that have no effect on the value of the input, such as arrow keys. It would be better if there were a way to only issue a request if the input value has changed. #index[event modifier][changed] And it turns out that htmx has support for that exact pattern, by using the `changed` modifier for events. (Not to be confused with the `change` event triggered by the DOM on input elements.) By adding `changed` to our `keyup` trigger, the input will not issue validation requests unless the keyup event actually updates the inputs value: #figure(caption: [Only sending requests when the input value changes], ```html <p> <label for="email">Email</label> <input name="email" id="email" type="email" hx-get="/contacts/{{ contact.id }}/email" hx-target="next .error" hx-trigger="change, keyup delay:200ms changed" <1> placeholder="Email" value="{{ contact.email }}"> <span class="error">{{ contact.errors['email'] }}</span> </p> ```) 1. We do away with pointless requests by only issuing them when the input’s value has actually changed. That’s some pretty good-looking and powerful HTML, providing an experience that most developers would think requires a complicated client-side solution. With a total of three attributes and a simple new server-side endpoint, we have added a fairly sophisticated user experience to our web application. Even better, any email validation rules we add on the server side will _automatically_ just work using this model: because we are using hypermedia as our communication mechanism there is no need to keep a client-side and server-side model in sync with one another. A great demonstration of the power of the hypermedia architecture! === Another Application Improvement: Paging <_another_application_improvement_paging> #index[htmx patterns][paging] Let’s move on from the contact editing page for a bit and improve the root page of the application, found at the `/contacts` path and rendering the `index.html` template. Currently, Contact.app does not support paging: if there are 10,000 contacts in the database we will show all 10,000 contacts on the root page. Showing so much data can bog a browser (and a server) down, so most web applications adopt a concept of "paging" to deal with data sets this large, where only one "page" of a smaller number of items is shown, with the ability to navigate around the pages in the data set. Let’s fix our application so that we only show ten contacts at a time with a "Next" and "Previous" link if there are more than 10 contacts in the contact database. The first change we will make is to add a simple paging widget to our `index.html` template. We will conditionally include two links: - If we are beyond the "first" page, we will include a link to the previous page - If there are ten contacts in the current result set, we will include a link to the next page This isn’t a perfect paging widget: ideally we’d show the number of pages and offer the ability to do more specific page navigation, and there is the possibility that the next page might have 0 results in it since we aren’t checking the total results count, but it will do for now for our simple application. Let’s look at the jinja template code for this in `index.html`. #figure(caption: [Adding paging widgets to our list of contacts], ```html <div> <span style="float: right"> <1> {% if page > 1 %} <a href="/contacts?page={{ page - 1 }}">Previous</a> <2> {% endif %} {% if contacts|length == 10 %} <a href="/contacts?page={{ page + 1 }}">Next</a> <1> {% endif %} </span> </div> ```) 1. Include a new div under the table to hold our navigation links. 2. If we are beyond page 1, include an anchor tag with the page decremented by one. 3. If there are 10 contacts in the current page, include an anchor tag linking to the next page by incrementing it by one. Note that here we are using a special jinja filter syntax `contacts|length` to compute the length of the contacts list. The details of this filter syntax is beyond the scope of this book, but in this case you can think of it as invoking the `contacts.length` property and then comparing that with `10`. Now that we have these links in place, let’s address the server-side implementation of paging. We are using the `page` request parameter to encode the paging state of the UI. So, in our handler, we need to look for that `page` parameter and pass that through to our model, as an integer, so the model knows which page of contacts to return: #figure(caption: [Adding paging to our request handler], ```python @app.route("/contacts") def contacts(): search = request.args.get("q") page = int(request.args.get("page", 1)) <1> if search is not None: contacts_set = Contact.search(search) else: contacts_set = Contact.all(page) <2> return render_template("index.html", contacts=contacts_set, page=page) ```) 1. Resolve the page parameter, defaulting to page 1 if no page is passed in. 2. Pass the page through to the model when loading all contacts so it knows which page of 10 contacts to return. This is fairly straightforward: we just need to get another parameter, like the `q` parameter we passed in for searching contacts earlier, convert it to an integer and then pass it through to the `Contact` model, so it knows which page to return. And, with that small change, we are done: we now have a very basic paging mechanism for our web application. And, believe it or not, it is already using AJAX, thanks to our use of `hx-boost` in the application. Easy! ==== Click To Load <_click_to_load> #index[htmx patterns][click to load] This paging mechanism is fine for a basic web application, and it is used extensively on the internet. But it has some drawbacks associated with it: every time you click the "Next" or "Previous" buttons you get a whole new page of contacts and lose any context you had on the previous page. Sometimes a more advanced paging UI pattern might be better. Maybe, rather than loading in a new page of elements and replacing the current elements, it would be nicer to append the next page of elements _inline_, after the current elements. This is the common "click to load" UX pattern, found in more advanced web applications. #figure( caption: [A Click To Load UI], image("images/screenshot_click_to_load.png"), )<fig-clicktoload> In @fig-clicktoload, you have a button that you can click, and it will load the next set of contacts directly into the page, rather than "paging" to the next page. This allows you to keep the current contacts "in context" visually on the page, but still progress through them as you would in a normal, paged user interface. Let’s see how we can implement this UX pattern in htmx. It’s actually surprisingly simple: we can just take the existing "Next" link and repurpose it a bit using nothing but a few htmx attributes! #index[hx-select][example] We want to have a button that, when clicked, appends the rows from the next page of contacts to the current, existing table, rather than re-rendering the whole table. This can be achieved by adding a new row to our table that has just such a button in it: #figure(caption: [Changing to "click to load"], ```html <tbody> {% for contact in contacts %} <tr> <td>{{ contact.first }}</td> <td>{{ contact.last }}</td> <td>{{ contact.phone }}</td> <td>{{ contact.email }}</td> <td> <a href="/contacts/{{ contact.id }}/edit">Edit</a> <a href="/contacts/{{ contact.id }}">View</a></td> </tr> {% endfor %} {% if contacts|length == 10 %} <1> <tr> <td colspan="5" style="text-align: center"> <button hx-target="closest tr" <2> hx-swap="outerHTML" <3> hx-select="tbody > tr" <4> hx-get="/contacts?page={{ page + 1 }}"> Load More </button> </td> </tr> {% endif %} </tbody> ```) 1. Only show "Load More" if there are 10 contact results in the current page. 2. Target the closest enclosing row. 3. Replace the entire row with the response from the server. 4. Select out the table rows from the response. Let’s go through each attribute in detail here. First, we are using `hx-target` to target the "closest" `tr` element, that is, the closest _parent_ table row. Second, we want to replace this _entire_ row with whatever content comes back from the server. Third, we want to yank out only the `tr` elements in the response. We are replacing this `tr` element with a new set of `tr` elements, which will have additional contact information in them, as well as, if necessary, a new "Load More" button that points to the _next_ next page. To do this, we use a CSS selector `tbody > tr` to ensure we only pull out the rows in the body of the table in the response. This avoids including rows in the table header, for example. Finally, we issue an HTTP `GET` to the url that will serve the next page of contacts, which looks just like the "Next" link from above. Somewhat surprisingly, no server-side changes are necessary for this new functionality. This is because of the flexibility that htmx gives you with respect to how it processes server responses. So, four attributes, and we now have a sophisticated "Click To Load" UX, via htmx. ==== Infinite Scroll <_infinite_scroll> #index[htmx patterns][infinite scroll] Another common pattern for dealing with large sets of things is known as the "Infinite Scroll" pattern. In this pattern, as the last item of a list or table of elements is scrolled into view, more elements are loaded and appended to the list or table. Now, this behavior makes more sense in situations where a user is exploring a category or series of social media posts, rather than in the context of a contact application. However, for completeness, and to just show what you can do with htmx, we will implement this pattern as well. It turns out that we can repurpose the "Click To Load" code to implement this new pattern quite easily: if you think about it for a moment, infinite scroll is really just the "Click To Load" logic, but rather than loading when a click event occurs, we want to load when an element is "revealed" in the view portal of the browser. As luck would have it, htmx offers a synthetic (non-standard) DOM event, `revealed` that can be used in tandem with the `hx-trigger` attribute, to trigger a request when, well, when an element is revealed. #index[hx-select][example] So let’s convert our button to a span and take advantage of this event: #figure(caption: [Changing to "infinite scroll"], ```html {% if contacts|length == 10 %} <tr> <td colspan="5" style="text-align: center"> <span hx-target="closest tr" hx-trigger="revealed" hx-swap="outerHTML" hx-select="tbody > tr" hx-get="/contacts?page={{ page + 1 }}">Loading More...</span> </td> </tr> {% endif %} ```) 1. We have converted our element from a button to a span, since the user will not be clicking on it. 2. We trigger the request when the element is revealed, that is when it comes into view in the portal. All we needed to do to convert from "Click to Load" to "Infinite Scroll" was to update our element to be a span and then add the `revealed` event trigger. The fact that switching to infinite scroll was so easy shows how well htmx generalizes HTML: just a few attributes allow us to dramatically expand what we can achieve in the hypermedia. And, again, we are doing all this while taking advantage of the RESTful model of the web. Despite all this new behavior, we are still exchanging hypermedia with the server, with no JSON API response to be seen. As the web was designed. #html-note[Caution With Modals and "display: none"][ #index[modal window] #index[display: none] _Think twice about modals._ Modal windows have become popular, almost standard, in many web applications today. Unfortunately, modal windows do not play well with much of the infrastructure of the web and introduce client-side state that can be difficult (though not impossible) to integrate cleanly with the hypermedia-based approach. Modal windows can be used safely for views that don’t constitute a resource or correspond to a domain entity: - Alerts - Confirmation dialogs - Forms for creating/updating entities Otherwise, consider using alternatives such as inline editing, or a separate page, rather than a modal. _Use `display: none;` with care_. The issue is that it is not purely cosmetic --- it also removes elements from the accessibility tree and keyboard focus. This is sometimes done to present the same content to visual and aural interfaces. If you want to hide an element visually without hiding it from assistive technology (e.g. the element contains information that is communicated through styling), you can use this utility class: #figure( ```css .vh { clip: rect(0 0 0 0); clip-path: inset(50%); block-size: 1px; inline-size: 1px; overflow: hidden; white-space: nowrap; } ```) `vh` is short for "visually hidden." This class uses multiple methods and workarounds to make sure no browser removes the element’s function. ]
https://github.com/OI-wiki/remark-typst
https://raw.githubusercontent.com/OI-wiki/remark-typst/main/README.md
markdown
Apache License 2.0
# OI Wiki: Export to PDF (WIP) 为 OI Wiki 的 Typst PDF 自动化导出工具开发的 Markdown 到 Typst 编译器。 **注意:本项目正在开发当中,请勿用于生产环境。** ## 使用方法 请使用下面的命令克隆本仓库: ```sh git clone --recurse-submodules --remote-submodules https://github.com/OI-wiki/remark-typst.git ``` 按如下方法使用: ```js import { unified } from 'unified' import remarkParse from 'remark-parse' import remarkTypst from 'remark-typst' import vfile from 'to-vfile' unified() .use(remarkParse) // 调用 remark 解析引擎 .use(remarkTypst, { // 编译到 Typst prefix: filename.replace(prefixRegEx, "").replace(/md$/, ""), // 文件名(不含 md 后缀) depth: depth, // 指定 <h1> 对应标题深度(0, 1, 2 分别表示一、二、三级标题),用于全书的结构组织 current: filename, // 文件名(含 md 后缀) root: path.join(oiwikiRoot, 'docs'), // OI Wiki 的 docs 目录位置 path: filename.replace(/\.md$/, "/") // 去掉 md 后的路径 }) .process(vfile.readSync(filename), function (err, file) { if (err) { throw err } file.dirname = 'typ' file.stem = filename.replace(prefixRegEx, "") file.extname = '.typ' vfile.writeSync(file) }) // 保存到文件(md 后缀换成 typ) ``` ## 依赖 参见 `package.json`。 ## 维护 编译器核心代码位于 `remark-typst/lib/compiler.js` 中,其中用到的某些函数位于 `remark-typst/lib/util.js`。remark 的所有种类 AST 结点都通过 `parse` 这一个函数处理。
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/spacing.typ
typst
Apache License 2.0
// Test the `h` and `v` functions. --- // Linebreak and leading-sized weak spacing are equivalent. #box[A \ B] #box[A #v(0.65em, weak: true) B] // Eating up soft spacing. Inv#h(0pt)isible // Multiple spacings in a row. Add #h(10pt) #h(10pt) up // Relative to area. #let x = 25% - 4pt |#h(x)|#h(x)|#h(x)|#h(x)| // Fractional. | #h(1fr) | #h(2fr) | #h(1fr) | --- // Test spacing collapsing before spacing. #set align(right) A #h(0pt) B #h(0pt) \ A B \ A #h(-1fr) B --- // Test spacing collapsing with different font sizes. #grid(columns: 2)[ #text(size: 12pt, block(below: 1em)[A]) #text(size: 8pt, block(above: 1em)[B]) ][ #text(size: 12pt, block(below: 1em)[A]) #text(size: 8pt, block(above: 1.25em)[B]) ] --- // Test RTL spacing. #set text(dir: rtl) A #h(10pt) B \ A #h(1fr) B --- // Missing spacing. // Error: 11-13 missing argument: amount Totally #h() ignored
https://github.com/herbhuang/utdallas-thesis-template-typst
https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/content/proposal/transparency_ai_tools.typ
typst
MIT License
#import "/utils/todo.typ": TODO #TODO[ Change this paragraph to reflect the tools you used in your proposal ] In preparing this proposal, I utilized Grammarly for grammar and style correction across the Abstract, Introduction, and Conclusion sections, ensuring clarity and coherence in my writing. I used DeepL to enhance language quality and translate parts of the Literature Review. I used ChatGPT to generate initial drafts and expand on ideas in the Introduction and Discussion sections, providing valuable suggestions and examples. Additionally, I used GitHub Copilot to generate code snippets for the developed functionality and code snippets in the Methodology section.
https://github.com/wznmickey/typst_workshop
https://raw.githubusercontent.com/wznmickey/typst_workshop/main/2024Fall/a.typ
typst
#import "@preview/codly:1.0.0": * #import "@preview/gentle-clues:1.0.0": * #set text(font: ("Noto Sans", "Noto Sans CJK SC")) #show: codly-init.with() #set page(height: auto, width: 35cm) #let LaTeX = { set text(font: "New Computer Modern") box( width: 2.55em, { [L] place(top, dx: 0.3em, text(size: 0.7em)[A]) place(top, dx: 0.7em)[T] place(top, dx: 1.26em, dy: 0.22em)[E] place(top, dx: 1.8em)[X] }, ) } #let getExample(ex) = { example[ #columns()[ #raw(ex, block: true, lang: "typst") #colbreak() #eval(ex, mode: "markup") ] ] } = Typst workshop 王梓宁 <NAME> #link("mailto:<EMAIL>") #datetime.today().display() == 介绍 Typst 是一个Markup语言,目前是用 `Rust` 写的实现,支持多种模式,包括*标记模式*、*数学模式*和*代码模式*。它的设计目标是提供一种更加直观、易用的文档编辑方式,同时提供 #LaTeX 的强大功能。 == 使用Typst的方式 文件名后缀为`.typ`,可以通过以下方式使用Typst: 1. 在Typst的官网上使用在线编辑器 https://typst.app/ 2. 使用Typst的VSCode插件,在vscode中编辑 == 一些资源 === 文档 - https://typst-doc-cn.github.io/docs/packages/ - https://typst.app/docs/ === 包和模板 - https://typst.app/universe/ - https://github.com/wznmickey/JI_Lab_Report_typst_template == 三种模式 参考 https://typst.app/docs/reference/syntax/ - 标记模式 Markup Mode (类似 Markdown) - 默认模式 - 数学模式 Math Mode (类似 #LaTeX) - 在 `$` 与 `$`之间输入,同时支持行间公式和行内公式 - 代码模式 Code Mode (类似 一般编程代码) - 使用`#` 开头。 - 所有的标记模式里面的格式实际上都是代码模式里的部分函数的语法糖,可以通过函数方式调用以与其他代码协同 === 标记模式 - 标题 #getExample("= 我是标题1 == 我是标题2") - 列表 #getExample("1. 有序列表 1. 有序列表 2. 有序列表 1. 有序列表 2. 有序列表 - 无序列表 - 无序列表 - 无序列表 - 无序列表 - 无序列表 + 有序列表 + 有序列表 + 有序列表 ") - 强调 #getExample("*强调* _emphasis_") === 数学模式 - 行内公式 #getExample("这是一个行内公式 $a^2 + b^2 = c^2$ 这是一个行内公式") - 行间公式 #getExample("这是一个行间公式 $ a^2 + b^2 = c^2 $ 这是一个行间公式") - 各类符号 #getExample("$alpha dot beta dots gamma sum_(-15)^(infinity) 3<=10 overline(1 + 2 + ... + 5) , a eq 3, b eq.not 3, a in NN^* sqrt(123) sin(x) = sin (2 pi), 1/2, 1/((2+2^e + 4/c)^(3^delta)) integral arrow.r.double.bar Delta sect \\u{2229} ∩$ $ alpha dot beta dots gamma sum_(-15)^(infinity) 3<=10 overline(1 + 2 + ... + 5) $ $ a eq 3, b eq.not 3, a in NN^* sqrt(123) sin(x) = sin (2 pi), 1/2 $ $ 1/((2+2^e + 4/c)^(3^delta)) integral arrow.r.double.bar Delta sect \\u{2229} ∩ $") - 分段函数、矩阵等多行情况 #getExample("$ f(x, y) := cases( 1 \"if\" (x dot y)/2 <= 0, 2 \"if\" x \"is even\", 3 \"if\" x in NN, 4 \"else\", ) mat( 1, 2, ..., 10; 2, 2, ..., 10; dots.v, dots.v, dots.down, dots.v; 10, 10, ..., 10; ) $ ") == 代码模式 语法 (与rust语法不同,请不要混淆) - 以`#` 开头(如果需要多行命令,使用大括号包起来)。 部分内容需要一定的编程基础。 === 部分常用的 #LaTeX 和 markdown 功能在typst使用方法 1. 代码: 原生自带,使用`raw`函数或\`导入, 与markdown类似 https://typst.app/docs/reference/text/raw/ #getExample("`a = 5` ") #getExample("```python a = 5 b = 10 ``` ") #getExample("#raw(\"int x = 5;\")") #getExample("#raw(\"int x = 5;\",block: true, lang: \"c++\")") 2. bibliography: 原生自带,使用`bibliography`函数导入,需要引用时使用`@`(也可以引用如图片之类的内部材料)。 https://typst.app/docs/reference/model/bibliography/ #getExample("@madje2022programmable") #getExample("#bibliography(\"a.bib\")") 3. 图片: 原生自带,使用`image`函数导入 https://typst.app/docs/reference/visualize/image/ #getExample("#image(\"Feishu_Group.jpg\",width: 70%) ") 4. 表格: 原生自带,使用`table`函数导入 #getExample("#table(columns:3)[Name][ID][Score][Zining Wang][520370910042][A+]") 5. beamer: 使用第三方包(比如`touying`) 6. 引用:原生自带,使用`quote`函数导入 #getExample("#quote()[Hello, world!]") #getExample("#quote(block:true)[Hello, world!]") === 代码编写 - 以`#` 开头(如果需要多行命令,使用大括号包起来)。 #getExample("#text(\"123\")") #getExample("#set text(size: 1.5em) #text(\"123\")") #getExample("#{set text(size: 1.5em) text(\"123\") }") - 如果临时要使用标记模式的文本材料,使用`[]`包起来。 #getExample("#[= Hello]") - 表达式(函数等的返回值)会以默认文本格式显示 #example[ #columns(3)[ ```typst "hello".len() ``` #colbreak() #"hello".len() #colbreak() ```python print(len("hello")) ``` ```c printf("%d",strlen("hello"));//严格来说这一句有点小问题,因为strlen返回的是size_t类型,但是printf的格式化符号是%d,应该是%zu ``` ```matlab disp(strlength("hello")); ``` ] ] - 使用`let` 赋值与(解)绑定 #example[ #columns(3)[ ``` #{ let x = 1 x } ``` #colbreak() #{ let x = 1 x } #colbreak() ```python x = 1 print(x) ``` ```c int x = 1; printf("%d",x); ``` ```matlab x = 1; disp(x); ``` ] ] #example[ #columns(3)[ ``` #{ let myFun(x,y) = {x+y} myFun(1,2) } ``` #colbreak() #{ let myFun(x, y) = { x + y } myFun(1, 2) } #colbreak() ```python def myFun(x, y): return x + y print(myFun(1, 2)) ``` ```c int myFun(int x, int y) { return x + y; } printf("%d", myFun(1, 2)); ``` ```matlab function z = myFun(x, y) z = x + y; end disp(myFun(1, 2)); ``` ] ] - 函数调用的一些语法糖 #getExample("#{ let alert1(body, fill: red) = { rect( fill: fill, [*Warning:\ #body*], ) } let alert2(fill: red, body) = { rect( fill: fill, [*Warning:\ #body*], ) } alert1[ Danger is imminent! ] alert1(fill: blue)[ KEEP OFF TRACKS ] alert1(\"KEEP OFF TRACKS\",fill: blue) alert2(\"KEEP OFF TRACKS\",fill: blue) } ") - 有 `if`, `while`。 `for` 是 in-range 设计。 #example[ #columns(3)[ ``` #{ let array = (1, 2, 3) for i in array { if i >= 2 [#i] } } ``` #colbreak() #{ let array = (1, 2, 3) for i in array { if i >= 2 [#i] } } #colbreak() ```python array = (1, 2, 3) for i in array: if i >= 2: print(i) ``` ```c int array[] = {1, 2, 3}; for (int i = 0; i < 3; i++) { if (array[i] >= 2) { printf("%d", array[i]); } } ``` ```matlab array = [1, 2, 3]; for i = array if i >= 2 disp(i); end end ``` ]] - `set` and `show` 修改文档的样式属性 https://typst.app/docs/reference/styling - `set` 设置属性 #getExample("#set text(size: 1em,style:\"italic\") 交大\ 密院\ #set text(size: 1.5em) 交大\ 密院\ #set text(style:\"normal\") 上海\ 闵行\ #highlight[SJTU] #highlight[Shanghai] #set highlight(fill:blue) #highlight[China] #highlight[Asia]") - `show` 修改文档的默认设置 #getExample("#{ set heading(numbering: \"I.I\") show heading: it => [ #set align(center) \~ #emph(it.body) #counter(heading).display(it.numbering) \~ ] [ = Typst == A == B = Markdown === D ] }") === 代码编写 Advanced - 类型 - 字符串 String`""` - 数组(变长) Array`()` - 字典 Dict `(key:value)` - 使用`.`访问字段和方法 #example[ #columns()[ ``` #let it = [== Typst] #it.depth #let dict = (name: "JI") #dict.at("name") #dict.values() ``` #colbreak() #let it = [== Typst] #it.depth #let dict = (name: "JI") #dict.at("name") #dict.values() ]] - 使用let解包数组 #example[ #columns()[ ``` #{ let (a,..,b) = (1,2,3,4,5) b } ``` #colbreak() #{ let (a, .., b) = (1, 2, 3, 4, 5) b } ]] == Lab 模板 https://github.com/wznmickey/JI_Lab_Report_typst_template
https://github.com/justinvulz/document
https://raw.githubusercontent.com/justinvulz/document/main/REU/ncube_poster.typ
typst
#import "../typst_packages\poster.typ": * #import "@preview/fletcher:0.4.5" as fletcher: diagram,node,edge #import "@preview/cetz:0.2.2" #show: doc => conf( "Critical Groups of n-cube Graphs", "<NAME>", advisor:"test", logo: "../pic/REU/logo.png", doc ) = Abstract The critical group, also known as the sandpile group or Jacobian group, is a finite abelian group that reflects the combinatorial and algebraic properties of a graph. This project focuses on the critical group of the $n$-cube graph $Q_n$ , a structure central to both theoretical and applied graph theory. = Background We want to find the firing script of the divisor $[N,-N,0,dots, 0]$ of the $n$-cube graph $Q_n$. = Simplified Graphs The $n$-cube graph $Q_n$ is a graph with $2^n$ vertices, thus the original graph is too large to compute. For this question, we found that the $n$-cube graph $Q_n$ can be simplified to a graph with $2n$ vertices. Define the simplified graph $Q_n'$ as follows: - Define $V_1(x)$ is a set of vertices which first bit is $1$, and the remaining $n-1$ bits have $x$ ones. - Define $V_0(x)$ is a set of vertices which first bit is $0$, and the remaining $n-1$ bits have $x$ ones. #set text(size: 26pt) #figure( caption: [Simplified Graph of $Q_n$], gap: 1em, grid( columns: 3, align: center+horizon, gutter: 1em, diagram( spacing: (6em,3em), node-stroke: aqua, node-inset: 0.3em, { node((0,0),$V_0(0)$) node((0,1),$V_0(1)$) edge((0,0),(0,1),$binom(n-1,0)$) node((1,0),$V_0(1)$) node((1,1),$V_1(1)$) edge((1,0),(1,1),$binom(n-1,1)$) edge((0,0),(1,0),$binom(n-1,0)binom(n-1-0,1)$) edge((0,1),(1,1)) node((2,0),$V_1(2)$) node((2,1),$V_0(2)$) edge((2,0),(2,1),$binom(n-1,2)$) edge((1,0),(2,0),$binom(n-1,1)binom(n-1-1,1)$) edge((1,1),(2,1)) } ), $dots$, diagram( spacing: (8em,3em), node-stroke: aqua, node-inset: 0.3em, { node((0,0),$V_0(n-2)$) node((0,1),$V_1(n-2)$) edge((0,0),(0,1),$binom(n-1,n-2)$) edge((0,0),(1,0),$binom(n-1,n-2)binom(n-1-(n-2),1)$) edge((0,1),(1,1)) node((1,0),$V_0(n-1)$) node((1,1),$V_1(n-1)$) edge((1,0),(1,1),$binom(n-1,n-1)$) } ) ) ) #set text(size: 30pt) The number next to the line is the number of multiple edges between two vertices. In general, a parte of simplified graph of $Q_n$ can be represented as follows: #figure( caption: [A part fo simplified Graph of $Q_n$], align(center)[ #diagram( spacing: (6em,5em), node-stroke: aqua, node-inset: 0.3em, { edge((-1,0),(0,0)) edge((-1,1),(0,1)) edge((1,0),(2,0)) edge((1,1),(2,1)) node((0,0),$V_0(x)$) node((0,1),$V_1(x)$) edge((0,0),(0,1),$binom(n-1,x)$) edge((0,0),(1,0),$binom(n-1,x)binom(n-1-x,1)$) edge((0,1),(1,1),$binom(n-1,x)binom(n-1-x,1)$) node((1,0),$V_0(x+1)$) node((1,1),$V_1(x+1)$) edge((1,0),(1,1),$binom(n-1,x+1)$) } ) ] ) = Firing Script By use the simplified graph and computer program, we can find the firing script of the divisor $[N,-N,0,dots, 0]$ of the $n$-cube graph $Q_n$. = heding1 #lorem(300) = heding2 #lorem(500)
https://github.com/tweaselORG/ReportHAR
https://raw.githubusercontent.com/tweaselORG/ReportHAR/main/templates/en/style.typ
typst
MIT License
#let tweaselStyle(doc) = [ #set page(numbering: (current, total) => "Page " + str(current) + " of " + str(total), number-align: end) #set text(font: "Linux Libertine", size: 12pt, lang: "en") #set heading(numbering: "1.1.") #show link: underline #set text(hyphenate: true) #set enum(numbering: "a.") #set quote(block: true, quotes: true) #show quote: set pad(top: -1em) #set footnote.entry(indent: 0em) #show footnote.entry: set par(hanging-indent: 1em) #doc ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-invalid-03.typ
typst
Other
// Error: 3-13 cannot apply '+' to content #(+([] + []))
https://github.com/Clay438/3bao-hbut-typst
https://raw.githubusercontent.com/Clay438/3bao-hbut-typst/master/文献阅读表.typ
typst
附件3-1: #strong[湖北工业大学2023 / 2024学年(上)本科生课程文献阅读情况汇总表] #strong[课程名称: 学号: 学生姓名: 班级: 成绩:] #figure( align(center)[#table( columns: 7, align: (col, row) => (auto,auto,auto,auto,auto,auto,auto,).at(col), inset: 6pt, [#strong[序号];], [#strong[文献作者];], [#strong[参考文献标题] #strong[(或教材著作名称)] ], [#strong[发表期刊] #strong[\(或出版社)] ], [#strong[时间期卷] #strong[(出版时间)] ], [#strong[主要观点或结论];], [#strong[主要学术贡献] #strong[或不足评述] ], [ 第 章到 第 章阅读文献(或者 问题/课题文献阅读);], [], [], [], [], [], [], [1], [], [], [], [], [], [], [2], [], [], [], [], [], [], [3], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], )] )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/004%20-%20Dragon's%20Maze/007_The%20Pursuit%2C%20Part%202.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Pursuit, Part 2", set_name: "Dragon's Maze", story_date: datetime(day: 14, month: 05, year: 2013), author: "<NAME>", doc ) "You should not have come." The words hung for a moment in the stale air of the damp sewer chamber. #figure(image("007_The Pursuit, Part 2/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) Madarrak knelt opposite the mizzium suit he had uncovered in the muck. His vedalken attendant, Castan, peered over his shoulder into the depths of suit’s spherical bell helmet from which the unsettling phrase came. She was staring into the fiery eyes of a glowing human visage that returned her stare from behind the thick glass of the suit’s viewing lens. Madarrak tapped the glass with his forefinger. "Are you <NAME>?" the aging Izzet mage asked, a hint of impatience in his voice. The face dispersed into a swirling cloud of energy and suddenly reformed. "I am damned." Madarrak held the receiver up to the glass. "This brought us to you. We are looking for <NAME>, the Izzet chemister who disappeared from his lab more than thirty years ago." "I damned us all." Madarrak rose sharply in frustration and kicked at the muck. Castan took up her mentor’s position, face to face with the suit’s occupant. She took hold of the helmet in both hands and said, "We are here to help you." After a moment, Castan felt the mizzium grow warm. "We are beyond help." "What happened here?" she pressed. And as though Castan’s question were a release valve for decades of pressure, the voice erupted, "The hypermana focusing lens I designed had worked. I was certain. But after meeting with them, I tampered with it." In an instant, the metal of the helmet became uncomfortably hot, and Castan had to let go. "I altered the design. Something compelled me to do it. When I activated the device, it brought us here. I somehow knew it would. How? How did I know? They had hold of my mind! They must have. I had been sick. Coughing and vomiting—mucus! They did this. And we are damned for it. All of us are damned!" "Who are #emph[they] ? The Izmagnus? Dimir?" Castan looked around. "Golgari? Who?" "Golgari don’t come here anymore. They know better." "Who then? Who made you sick?" "The biomancer." Castan gave a quizzical look. "Simic?" "When we appeared here, I had transformed into what I am now." "The device reacted with the mizzium suit," said Madarrak. "Where is the dev—" "The transformation cleared my mind, cured me. Then things came for us out of the darkness. They took no notice of me; I can only assume it was because of my new form. But they collected my attendant, Johrum, who had already begun to change." "Change into what?" "Never mind that now," Madarrak snapped. "We must find the device. Where is what brought you here?" Madarrak sifted through more filth. A large, cylindrical canister, cast of mizzium, was revealed to be wedged between the suit and the sewer floor. "This must be it!" "Mentor," Castan said, "what now? Madarrak waved her over. "We recover the device." "That’s not what I mean. Look." Madarrak looked. At the other end of the chamber, partially cloaked in shadow, stood a figure staring back at them. The person stepped forward. Its legs were not the legs of person, but those of an insect. Then two more legs. From the waist up, it was humanoid, but protected by a carapace. It wielded a formidable axe. #figure(image("007_The Pursuit, Part 2/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) "We are damned!" said the voice in the helmet. Another one of these creatures emerged from the shadows, followed by a third. They spoke in a series of sharp clicks, and although the words were unknown to the Izzet mages, their intent was not lost. The lead creature raised its axe toward them, and the creatures charged. A bluish, crackling energy formed around Castan’s hands. "Mentor?" she asked. "Do it." Castan raised her hands and bolts of electricity arced around her. She let them fly at the attackers. The bolts found their targets, connecting with exoskeletons in three distinct pops. The creatures each tumbled to the ground mid-stride as three lifeless husks. Castan’s mouth hung open, and she stood there for a moment, stunned by her own display of destructive power. #figure(image("007_The Pursuit, Part 2/06.jpg", width: 100%), caption: [], supplement: none, numbering: none) Madarrak struggled with the canister, "Quickly now, assist me." Castan came to his aid, and together they worked it free. A chorus of countless scuttling legs and indistinguishable clicks permeated the chamber, growing louder, and echoing through the unseen heights. "Mentor! More are coming!" Madarrak strapped the canister to his back, and for a moment he was lost in his own world of impending redemption. Castan’s words seemed somehow distant. Something heavy struck his shoulder, dragging his senses back to the present. "Eh?" Instinctively, his hand went to where he’d been hit, and he felt a thick gelatinous mass. He raised his gaze and peered into the shadows that appeared to stretch ever upward. There was movement up there. Before Madarrak could process the thought, it was on him. The Izzet mage suddenly found himself pinned against the ground, grappling with a figure that was human in shape, but massive and grotesque. #figure(image("007_The Pursuit, Part 2/08.jpg", width: 100%), caption: [], supplement: none, numbering: none) Castan moved to help her mentor, but her path was blocked as dozens of kraul warriors poured into the chamber. She was surrounded. And she did not hold back. The darkness gave way to the harsh light of crackling energy that branched from the attendant’s hands. "We are all damned!" declared the voice in the helmet once again. Madarrak struggled to free his hands to cast something, anything. The bulk of the mutated thing was too great. It looked Madarrak in the face and a large translucent blue-green globule emerged from its open mouth. It slid out, held there for a moment by strands of sticky saliva before dropping. Madarrak turned his head in attempt to avoid the mucus, but it struck him on the side of his face, and on its own, began to move toward his nose and mouth. "Johrum!" Madarrak heard the familiar voice, and from the corner of his eye, he saw fire streak across his field of vision. It slammed into the mutant, knocking him off the old man. The fire had taken the vague shape of a man, swirling around the mutant. #figure(image("007_The Pursuit, Part 2/10.jpg", width: 100%), caption: [], supplement: none, numbering: none) Without missing a beat, Madarrak raised his hands to his face. He felt the mucus, which had reached his nostrils and the corner of his mouth. He let electricity flow from his fingers. Upon contact, the mucus curled up and fell away. The only sign of Castan was the lighting that arced out from the far side of the chamber. Between mentor and attendant were kraul beyond count. The mutant tore what was left of <NAME> in two. There was no time to lose. Madarrak extended his arms, and a jet of boiling hot steam erupted from his hands, completely engulfing the mutant. Blisters bubbled up on its surface and it fell to the ground with a horrible shriek. Kraul turned toward him, and there was one thing he thought to do. "Yzaak! Yzaak, to me!" Madarrak’s voice was hoarse as he hurtled down the familiar passage toward the hulking Cyclops, who was sitting with his back against an algae-slick wall. Even though Yzaak did not heed Madarrak’s calls, the old man found comfort in the sight of the Cyclops. When he reached Yzaak, he allowed himself a moment’s rest. He was out of breath, his knees shaking from the strain of the run and the weight of Erno’s device on his back. "Come, Yzaak," Madarrak steadied himself on Yzaak’s gauntleted arm. "We must get out of here." The Cyclops remained motionless. Madarrak shook Yzaak’s arm, and beneath his hand, the Yzaak’s gauntlet gave, crumbling in on itself in a cloud of red-brown dust. He leapt back in horror and brought his lamp up to illuminate the scene. The light that washed over the scene revealed the Cyclops to be in a state of decomposition. The mizzium augmentations had corroded. Where flesh was exposed, putrefaction had begun, and fungal growths had sprouted. #figure(image("007_The Pursuit, Part 2/12.jpg", width: 100%), caption: [], supplement: none, numbering: none) He backed away and collapsed to his knees, fighting back the urge to scream, or vomit. The Golgari had condemned this place, and he recalled the eyes in the darkness. They were not rot farmers, but watchers. Sentries. Slowly, Madarrak raised the lamp to the darkness beyond the passageway. Eyes in the darkness. Eyes that were growing larger. Madarrak was alone. It was just him, accompanied only by Yzaak’s rotting corpse and Erno’s— He scrambled to get the device off his back. A shuffling was audible from the darkness, and although Madarrak knew members of the Golgari guild were converging on him, he did not care. He had his task. In the brief moments of light, he analyzed the Izzet contraption, allowing his fingers to intuit how it worked. The device suddenly came alive with a buzz, and Madarrak slung it across his back. A cloud of dust swirled around him, and in an instant, he was gone. #figure(image("007_The Pursuit, Part 2/14.jpg", width: 100%), caption: [], supplement: none, numbering: none) Before the dust settled, Madarrak was bombarded by the familiar crackling of energy, hissing of steam, and clanks of metal on mizzium. He wasn’t certain of his precise location, but as the last whiff of the sewer dissipated, he was at least certain that he had returned to Nivix, the guild tower of the Izzet League. There wasn’t a moment to lose. Erno’s device worked, and he must report that to Niv-Mizzet at once. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Madarrak returned from his quarters after meeting with Niv-Mizzet. His quarters were little more than a modest cot set into a cramped alcove in a corner of his laboratory. He peeled the layers of clothes from his tired frame. The fabric had grown stiff from dried muck and rot. The old man, back in the Dracogenius’s good graces after delivering Erno’s teleportal, was to meet with his guild leader once again as soon as he was able to clean himself up and eat something. He stood for a long moment, looking down at the soiled garments crumpled between his hands. His brow furrowed. His thoughts went to the words that followed through the sewers, "There are too many, Mentor! Mentor!" There were too many. What choice did he have? And Yzaak. The Golgari knew what was hidden in their abandoned territory. They were making sure nothing came out. He felt his fingers clench, and as they tightened around the fabric, they wrapped around something solid. Madarrak shook out his balled-up clothes, and the receiver tumbled to the floor, light pulsing from it in the all-too-familiar sequence. It began to slide toward the door. Not Erno. Castan? Madarrak pulled his filthy clothes back on. He plucked the receiver from the floor. Niv-Mizzet would have to wait. Or not. For Madarrak, it no longer mattered. He was tired, but he would not leave his attendant to the twisted tests of the Simic. His eyes fell on the monstrous bipedal construct that started this whole thing by smashing its way into Erno’s abandoned laboratory. It had been put back together. At the foot of the construct was its schematic. Small piles of metal bits and tools at each corner kept it from rolling up. While Madarrak recognized the designs to be his own, he also noticed notes and tiny diagrams that had been scrawled by another hand—Castan’s hand. He looked from the schematic to the construct, and back once more. Castan’s adjustments made sense. They seemed so simple, seeing them as they appeared in her rough penmanship, and yet they had eluded him. No time for that now. It had to work. He climbed into the pilot’s seat atop the construct’s shoulders. He turned knobs, and flipped switches. Power surged into the construct. Everything sounded right. It felt right. With this, he would save Castan. And, failing that, he would bring the whole cursed facility down on itself. He prepared to crank the final lever, when he felt something splash against the back of his hand. Another drip, this one falling upon an array of gauges. As it slid down the glass, he saw it to a blue-green viscous material. The old man’s face went white, and he looked up, hiding behind a raised arm. Nothing. His eyes frantically panned across the ceiling of his lab. Still nothing. Horror swept over him, and he brought a shaky hand to his nose. When he pulled it away and looked down at it, his horror was confirmed.
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/tests/evel-math/test.typ
typst
MIT License
#import "../../src/schule.typ": ab #import ab: * #show: arbeitsblatt.with( /* @typstyle:off */ titel: "Base template test", reihe: "TYPST-TEST", datum: "15.06.2024", nummer: "1", fach: "Typst", kurs: "101", autor: ( name: "<NAME>", kuerzel: "Ngb", ), version: "2024-06-15", ) // #eval-math($12 + 12$) #eval-math(`12 + 12`) #eval-math(`(12 + 12) / 6`) - #eval-math(`12 - (7 - 2)`) - #eval-math(`120 : (4 dot 15)`) - #eval-math(`4 dot (25 : (15 : 3))`) - #eval-math(`(25 - 13) : (11 - 7)`) - #eval-math(`22 : (33 : (5 - 2))`) - #eval-math(`50 : (30 - (25 - 5))`)
https://github.com/frugal-10191/frugal-typst
https://raw.githubusercontent.com/frugal-10191/frugal-typst/main/README.md
markdown
Apache License 2.0
# frugal-typst A collection of templates for Typst ## book-template Based largely on the excellent Orange Legrand LaTeX template, with a lot of the original Typst code by flavio20002 (https://github.com/flavio20002/typst-orange-template). Features: - Title page with optional logo and full page background - Parts which act as groups of chapters and. Each of which have their own title page and table of contents. - Chapters have an optional background image to make them stand out. There is an complete example in the examples directory.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.3.0/src/draw/util.typ
typst
Apache License 2.0
/// Assert that the cetz version of the canvas matches the given version (range). /// /// min (version): Minimum version (current >= min) /// max (none, version): First unsupported version (current < max) /// hint (string): Name of the function/module this assert is called from #let assert-version(min, max: none, hint: "") = { if hint != "" { hint = " by " + hint } (ctx => { /* Default to 2.0.0, as this is the first version that had elements as single functions. */ let v = ctx.at("version", default: version(0,2,0)) assert(min <= v, message: "CeTZ canvas version is " + str(v) + ", but the minimum required version" + hint + " is " + str(min)) if max != none { assert(max > v, message: "CeTZ canvas version is " + str(v) + ", but the maximum supported version" + hint + " is " + str(min)) } return (ctx: ctx) },) }
https://github.com/catarinacps/typst-abnt
https://raw.githubusercontent.com/catarinacps/typst-abnt/main/README.md
markdown
MIT License
# A Typst Template for ABNT documents This is far, far from ready.
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/text/case.typ
typst
Apache License 2.0
// Test the `upper` and `lower` functions. // Ref: false --- #let memes = "ArE mEmEs gReAt?"; #test(lower(memes), "are memes great?") #test(upper(memes), "ARE MEMES GREAT?") #test(upper("Ελλάδα"), "ΕΛΛΆΔΑ") --- // Error: 8-9 expected string or content, found integer #upper(1)
https://github.com/kazewong/lecture-notes
https://raw.githubusercontent.com/kazewong/lecture-notes/main/Engineering/SoftwareEngineeringForDataScience/syllabus.typ
typst
#set page( paper: "us-letter", header: align(center, text(17pt)[ *Software engineering for data science* ]), numbering: "1", ) #set text( font: "Times New Roman", size: 11pt ) #show heading.where( level: 1, ): it => text( size: 18pt, weight: "extrabold", it.body ) #set par(justify: true) = Course Description Software engineering in data science requires a wide variety of technical skills. Not only ones need to know how to build a model for their data, but also engineer around the model from continous ingestion of new data to produce a deployable product. This course aims to expose the students to many modern software engineering practices for software engineering. We will start with problem analysis, programming languages, toolings such as version control, testing, debugging, to MLOps such as data base interaction and experiment tracking, all the way to open source developement cycle and governance, continous integration and deployment, and user interface and experience design. After this course, the student should have working knowledge to design and start an end-to-end data science project. This course focuses on hands-on experience, labs and tutorials, which the students will design and develop a semester-long project with the guidance of the instructor. Prerequisite(s): prior experience with programming is highly recommended. While each students should have their own project for the course, students are encouraged to work with each other. The most important part of this course is to have fun, and by the end of the course the students should have build some small products that will be available to the general public. = Philosophy == I choose to teach everything but building neural network If you want to learn how to build a certain neural network, this is not the course, I have another course that focuses on deep learning engineering. This course is about everything around neural network, which in my opinion is way harder to get into and definite need a mentor more than building neural network. Most of the neural network library such as PyTorch and Jax are very well-documented, and there are tons of great blog post teaching you how to do it. The workflow of building a neural network is usually quite well defined, get data, tune numbers, publish paper. There are not much choices you have to make, and for the choices you do have to make, often you can rely on your mathematical intuition to guide yourself. On the other hand, mathematical insight is not going to be immediately useful when we are talking about how to setup a CI/CD pipeline, or how to write a good documentation. Navigating the design space of neural network is relatively straight forward, but navigating the design space of a full fledge software is like kayaking in a stormy sea. I believe taking this course first before you dive into deep learning specific engineering will benefit you tremendously, since you will be equipped with the tools that bring your neural networks to the world and make a difference. == I am just your guide There are different schools of thought when it comes to building software, just look at how many javascript frameworks and linux distro there. In the end, it is more about what you are trying to achieve and your style more than anything. There are general principles, best practice and anti-pattern, but a lot of engineering is about trade-offs and taste. I am structuring this course and the material according to my taste and preference, which is aligned with scientific computing and open source software developement. This may not be the best option in a different environment, such as in cyber security space. I am designing to course not only to show you the tools and workflows I prefer, but also why I pick the way I program. Style evolves over time as well, so remember to be agile and be ready to change if betters options are available. == I can help you to get your A, but you have to get it yourself Since this is a class that suppose to teach you practical skills instead of the truth of the universe, I do not see the point in quizing and grading you. Instead, I value whether you can build some software and serve the community in the end, so that is how the assessment scheme is going to work: for the official grading, we will set up some simple labs for each topics, as long as you have done all of them, you will get an A. However, the true A in this class will be a software that you build and make it available to the world, and I will not be the (only) judge of whether you get an A or not. Alongside with the labs, you will pick a software project at the beginning of the course and build it as we progress in the class. At the end of the course, we will have a showcase of everyone's project. This *do not* contribute to your grade in any way. The catch is, hopefully you pick something that you are truly passionate about instead of just something that you think will be easy to build for the class, and you can actually show the world what software you have made. As a continuation of the course, I will help you publish and leverage your software for your career path, whether that involves publishing a code paper, or submitting to conferences. In the end, I think the grading is mutual, the grade for my teaching is how much fun you have, and the grade for your coursework is how proud of your software you are. == Use of AI-assistant I am very okay with students using AI-assistant tools such as copilot or ChatGPT in labs and projects. I uses copilot extensively in my daily workflow, and it has been a great productivity boost to what I do. In the end, your clients will not care whether you use copilot or voodoo magic to cook up the products, all they care is whether the product is good or not. On top of that, as much as I want AI to take over my job, it still kind of fails miserably. I am not even talking about the science bits of it, which we can go into hours of why AI may struggle on that. I am talking about the engineering part of AI. I dropped my ChatGPT subscription quick a while ago, since it just constantly fail to give me an answer that will work out of the box. Instead, I use ChatGPT like a search engine, usually in order to find the keyword that is related to what I want to search, then I just punch them into Google. My bottom line with AI-assistant is it has to make you a better engineer, not worse. If ChatGPT helps you find new concepts and write codes that are more efficient than what you would have written on your own, by all mean go for it. However, if you start to rely too much on ChatGPT, and produce inefficient code or buggy code, that is an issue. The goal of this course is to make you a capable software engineer in the era which AI-assistant exists, and whatever we can do to achieve that is appericated. = Logistics == Labs The labs serve two purposes: first, it is good to have some very well defined tasks you can practice whatever we have learning during the lectures. It is beneficial to you to get that muscle memory, at the same time to have some reference points if you want to do the same task in the future. Second, the labs are going to be 100% of your grade. I fundamentally do not value the labs as much as all the other non-graded activites, so my policy is as long as you complete all the labs as intended in time, then you will get an A. They should be relatively straight forward and should not take too much of your time on average. However, let me be clear here that the labs taking up a 100% of the grade does not mean you can slack off the other activites. I make the labs simple in order to make room for all the other fun stuffs, so they are the highlights. If you just want an easy A from doing the labs and planning to go easy on the other activities, I will strongly advise against taking this course. == "Pitch" session and Mid-semester update At the beginning of the course, you will pick a project that you will work on throughout the semester, which I have a couple examples of what I think is reasonable for this course in terms of size. We will have a pitch session, which everyone will introduce their project to the class, specify the scope and layout a couple of milestones. It is a pitch session in qoutation because there is no seed money for this, but it is a good practice to go through the thought process which helps you laying down a solid plan for the project. In the middle of the semester, we will have an update session which everyone presents their progress they have been makeing to the class. These will not contribute toward your final grade, but I value this more than your lab. == Showcase By the end of the semester, I think it will be really fun to showcase your tools to each other and people outside the class. I will organize a showcase event which everyone will have an opportunity to present their project. In the ideal scenario, everyone should have some codes together with a demo web app we can all play with. The idea of having the pitch session and the showcase session is to give you the full experience of how to present your projects. Once again this will not count toward your final grade, but I also value this more than your lab. == Attendance Since the course is very hands-on and we meet only once a week, it does not really make sense to skip the class. I understand life happens from time to time, and if there is very legitimate reason you cannot make it to a particular class, there is a quota for missing the class once, not including the mid-semester update session and the show case session. If you miss the class more than once, every missed class will limit your highest grade by one letter grade, e.g. if you missed the class twice, the highest grade you can get is a B. If you miss the mid-semester update session or the show case session without an extremely legitimate reason, you will not be able to pass the course. I believe coming to the class on time and participate in the class is critical to learning from this course, so I will be completely strict with this policy. == Continuous feedback Even though I have a particular plan for this course, I think it makes the most sense if you tell me what could be useful to you. I cannot promise I will always be able to accomodate your need by switching up my lecture plan, but I do leave some flexibility when I am designing the syllabus for this course, so there is some chance I can touch on some popular topics. If there is really popular demand, I may also hold additional hacking session outside this course. For more granular feedbacks such as finding bugs in assignments or have general questions, feel free to open issues or pull requests on Github. == Debugging help As much as I want to promise you everything will be smooth, I would lying if I told you there will not be any bugs and problems during your lab. And during the class, I will probably need to resolve multiple situations in a relatively short time scale. There will be an office hour from the TA the day after the class, which the TA will help you tackle the problems you have during the lab. = Schedule While there are a few sessions that are going to be a bit different in format, such as the pitch session and the showcase session, the majority of the sessions is going to share the following structure: 1. *Overview*: A brief lecture about the topics of the day (\~30 mins) 2. *Lab*: Pre-defined assingments (\~30 mins) 3. *Break*: Stretch, get coffee, walk around. Long sitting is unhealthy. (\~10 mins) 4. *Hacking*: Integrating newly learned techniques into semester long project (\~1 hrs) 5. *Wrap-up*: Summarize and report the progress of the day (\~20mins) During the lab session and integration session, I will go around help people with their problems. #set enum(numbering: "Week 1") + *Introduction to the course:* There will not be lab, instead, we will go through the class logistics, and have a brainstorming session help you formalize your semester long project. + *Version control:* We will learn how to do version control with git. Since this is at the beginning of the course, instead of a hacking session, we will go around and pitch our project to each other. + *Python*: We will introduce python, some best practices in python, and how to set up a package in python. + *Julia*: We will introduce julia, and learn about how to set up a project in julia. + *Rust*: We will introduce rust, some unique features of rust, and how to set up a project in rust. + *Machine Learning frameworks in the three languages*: We will play with three machine larning (-related) libraries in the three languages we learned, including `jax` in `python`, `flux` in `julia`, and `burn` in `rust`. + *Mid-semester update:* There will be no lab, and hacking. Instead, people should present their progress so far. + *Fall break* + *Environment management and Containerization:* You will learn how to manage your environment with nix and containerize your applications with docker. + *Frontend:* We will learn about the basic of building web frontend with svelte. + *Backend and database:* You will learn the basic of database and storage. + *Continous integration:* You will learn how to use actions to continously update and test your code. + *MLOps:* You will learn how to build an automatic machine learning pipeline. + *Fall Recess* + *Show case*: There will be no lab and hacking. Instead, we will celerate everyone's hardwork!
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fauve-cdb/0.1.0/src/utils.typ
typst
Apache License 2.0
#let balanced-cols(n-cols, gutter: 11pt, body) = layout(bounds => context { // Measure the height of the container of the text if it was single // column, full width let textHeight = measure(box( width: (bounds.width - (n-cols - 1) * gutter) / n-cols, body )).height // Recompute the height of the new container. Add a few points to avoid the // second column being longer than the first one let balanced-height = (1/n-cols) * textHeight + 0.5 * text.size box( height: balanced-height, columns(n-cols, gutter: gutter, body) ) })
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/square-base.typ
typst
Apache License 2.0
// Test that square sets correct base for its content. --- #set page(height: 80pt) #square(width: 40%, rect(width: 60%, height: 80%))
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/docs/external/typst-preview.md
markdown
--- sidebar_position: 2 --- # Typst Preview The Typst Preview extension for VS Code provides an excellent slide mode, allowing us to preview and present slides. Press `Ctrl/Cmd + Shift + P` and type `Typst Preview: Preview current file in slide mode` to open the preview in slide mode. Press `Ctrl/Cmd + Shift + P` and type `Typst Preview: Preview current file in browser and slide mode` to open the slide mode in the browser. Now, you can press keys like `F11` to enter fullscreen mode in the browser, making it suitable for slide presentations. Since Typst Preview is based on SVG, it can play GIF animations, which is very helpful for dynamic slides.
https://github.com/ellmau/cv-typst
https://raw.githubusercontent.com/ellmau/cv-typst/main/cv.typ
typst
//#import "@preview/modern-acad-cv:0.1.0": * #import "modern-acad-cv.typ":* #let metadata = yaml("metadata.yaml") #let multilingual = yaml("data/i18n.yaml") #let infoline = yaml("data/infoline.yaml") #let education = yaml("data/education.yaml") #let feducation = yaml("data/feducation.yaml") #let work = yaml("data/work.yaml") #let skills = yaml("data/skills.yaml") #let awards = yaml("data/awards.yaml") #let volunteering = yaml("data/volunteering.yaml") #let reviewing = yaml("data/reviewing.yaml") #let professional = yaml("data/prof_act.yaml") #let teach_responsible = yaml("data/teaching/responsible.yaml") #let teach_courses = yaml("data/teaching/courses.yaml") #let superv = yaml("data/teaching/cosuper.yaml") #let stud_ass = yaml("data/teaching/ass.yaml") //#let language = "de" #let extraData() = { } #let my-cv(language: "de",body)=[ #let headerLabs = create-headers(multilingual, lang: language) #show: modern-acad-cv.with( metadata, multilingual, lang: language, font: "Noto Sans Bhaiksuki", show-date: true ) #let extra_data = () #for (entry,field) in metadata.personal.extras{ let icon = if field.keys().contains("icon"){ fa-icon(field.at("icon"),fill:rgb(metadata.colors.main_color)) } extra_data.push( [#icon #field.at("content")] ) } #align(center+top)[ #extra_data.join(" | ") ] #line(length:100%, stroke: (paint:rgb(metadata.colors.main_color))) #align(center + top)[ #eval(metadata.personal.pitch,mode:"markup") ] //#cv-auto(infoline,multilingual,lang:language) = #headerLabs.at("work") #cv-auto-stc(work,multilingual,lang:language) #pagebreak(weak:true) = #headerLabs.at("education") #cv-auto-stc(education, multilingual, lang: language) = #headerLabs.at("feducation") #cv-auto-stc(feducation,multilingual,lang:language) #if language == "de"{ pagebreak(weak: true) } #if language == "en" { pagebreak(weak:true) } = #headerLabs.at("skills") #cv-auto-list(skills, multilingual,lang:language) #if language == "de"{ cv-cols[Sprachen][ #table( columns: (15%,40%), stroke: none, inset: 0pt, row-gutter: 0.9em, )[Deutsch][Muttersprache][Englisch][verhandlungssicher] ] }else if language == "en"{ cv-cols[Languages][ #table( columns: (15%,40%), stroke: none, inset: 0pt, row-gutter: 0.9em, )[German][native tongue][English][fluent] ] } = #headerLabs.at("awards") #cv-auto(awards,multilingual,lang:language) = #headerLabs.at("volunteering") #cv-auto(volunteering,multilingual,lang:language) = #headerLabs.at("acad") == #headerLabs.at("reviewing") #cv-auto(reviewing,multilingual,lang:language) #if language == "de"{ pagebreak(weak: true) } #if language == "en"{ pagebreak(weak: true) } == #headerLabs.at("scientific") #cv-auto(professional,multilingual,lang:language) = #headerLabs.at("teaching") == #headerLabs.at("teaching_resp") #cv-auto(teach_responsible,multilingual,lang:language) == #headerLabs.at("courses") #cv-auto-stc(teach_courses,multilingual,lang:language) == #headerLabs.at("cosuper") #cv-auto(superv,multilingual,lang:language) == #headerLabs.at("teaching_assistance") #cv-auto(stud_ass,multilingual,lang:language) ] #show: my-cv.with(language:"de")
https://github.com/Dherse/ugent-templates
https://raw.githubusercontent.com/Dherse/ugent-templates/main/slides/ugent-theme.typ
typst
MIT License
#import "@preview/polylux:0.3.1": * #import "../common/colors.typ": * #import utils: polylux-outline, polylux-progress, current-section, register-section #let ratio = 1.621784511784512 #let text_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) #let config(callback) = locate(loc => { let cfg = state("ugent-theme-config").at(loc) callback(cfg, loc) }) #let ugent-theme( authors: none, role: none, short-authors: none, title: none, subtitle: none, short-title: none, date: datetime.today(), email: none, mobile: none, dept: none, research-group: none, linkedin: none, color: ugent-blue, text-color: white, logo: "ugent/logo_ugent.png", second-logo: "ugent/logo_ea.png", body, handout: false, progress-bar: true, ) = { // Set the document properties set document( author: authors, date: date, ) // Configure the page set page( paper: "presentation-16-9", numbering: "1", margin: 0pt, header: none, footer: none, ) // Configure the font set text(font: "UGent Panno Text") // Additional styling of bold text. show strong: set text(fill: ugent-blue) enable-handout-mode(handout) if type(authors) in ("string", "content") { authors = (authors,) } // Save the configuration state("ugent-theme-config").update(( authors: authors, short-authors: short-authors, role: role, title: title, subtitle: subtitle, short-title: short-title, date: date, email: email, mobile: mobile, dept: dept, research-group: research-group, linkedin: linkedin, color: color, text-color: text-color, logo: logo, second-logo: second-logo, handout: handout, progress-bar: progress-bar, )); show figure: align.with(center) show figure.caption: it => { let supplement = [ #set text(fill: ugent-blue) #smallcaps[*#it.supplement #it.counter.display(it.numbering)*] ]; let gap = 0.64em let cell = block.with( inset: (top: 0.32em, bottom: 0.32em, rest: gap), stroke: ( left: ( paint: ugent-blue, thickness: 1.5pt, ), rest: none, ) ) grid( columns: (5em, auto), gutter: 0pt, rows: (auto), cell(height: auto, stroke: none, width: 5em)[ #align(right)[#supplement] ], cell(height: auto)[ #set text(size: 16pt) #align(left)[#it.body] ], ) } /*show figure: it => { set figure.caption(position: bottom) let supplement = [ #set text(fill: rgb(30,100,200)) #smallcaps[*#it.supplement #it.counter.display(it.numbering)*] ]; let gap = 0.64em let cell = block.with( inset: (top: 0.32em, bottom: 0.32em, rest: gap), breakable: true, stroke: ( left: ( paint: rgb(30,100,200), thickness: 1.5pt, ), rest: none, ) ) set text(size: 16pt) v(-0.64em) grid( columns: (5em, 1fr), rows: (auto), cell(height: auto, stroke: none, width: 5em)[ #align(right)[#supplement] ], cell(height: auto)[ #set text(size: 16pt) #align(left)[#it.caption] ], ) }*/ body } // Create a progress bar at the bottom of every slide #let progress-bar(loc) = place(bottom + left, { polylux-progress(ratio => { box(width: ratio * 100%, height: 2pt, fill: ugent-blue) }) }) #let corporate-logo() = { let content = config((cfg, _) => { if cfg.logo == none { panic("No logo provided") } align(center + horizon, image(cfg.logo)) }) pagebreak(weak: true) polylux-slide(content) } #let title-slide() = { let content = config((cfg, loc) => { let box_size = (width: 45.63cm / ratio, height: 18.07cm / ratio) let box_inset = (dx: 2.54cm / ratio, dy: 3.87cm / ratio) let text_box_inset = (dx: 3.59cm / ratio - box_inset.dx, dy: 6.53cm / ratio - box_inset.dy) let text_box_size = (width: 42.18cm / ratio, height: 12.32cm / ratio) let subtitle_inset = (dx: 3.59cm / ratio - box_inset.dx, dy: 19.1cm / ratio - box_inset.dy) let subtitle_size = (width: 42.18cm / ratio, height: 1.62cm / ratio) let body = place(top + left, box({ set text(size: 60pt, fill: cfg.text-color) show text: smallcaps underline(cfg.title) }, ..text_box_size, ..text_inset), ..text_box_inset) let subtitle = place(top + left, box({ align(horizon, { set text(size: 20pt, fill: ugent-accent1) show par: set block(spacing: 10pt) cfg.subtitle }) }, ..subtitle_size), ..subtitle_inset) if "dept" in cfg or "research-group" in cfg { let dept_size = (width: 23.04cm / ratio, height: 1.5cm / ratio) let dept_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) let dept_offset = (dx: 23.84cm / ratio, dy: 1.1cm / ratio) place(top + left, box({ align(horizon, { set text(size: 14pt, fill: ugent-blue) show par: set block(spacing: 5pt) if "dept" in cfg { smallcaps[*#cfg.dept*] if "research-group" in cfg { parbreak() } } if "research-group" in cfg { smallcaps[#cfg.research-group] } }) }, ..dept_size, ..dept_inset), ..dept_offset) } place(bottom + left, image(cfg.logo, width: 6.41cm / ratio)) place(top + left, box(fill: cfg.color, body + subtitle, ..box_size), ..box_inset) if cfg.second-logo != none { place(top + left, image(cfg.second-logo, height: 3.87cm / ratio)) } if cfg.progress-bar { progress-bar(loc) } }) pagebreak(weak: true) polylux-slide(content) } #let end-slide() = { let content = config((cfg, loc) => { set text(font: "UGent Panno Text", fill: cfg.text-color) let icon(icon) = text(font: "tabler-icons", size: 24pt, baseline: -4pt, fill: cfg.text-color, icon) let added-content = () if "linkedin" in cfg and cfg.linkedin != none { added-content.push(icon("\u{ec8c}")) added-content.push(link(cfg.linkedin, [ #cfg.authors.at(0) ])) } let social = { set text(size: 24pt) table( columns: 2, stroke: none, column-gutter: 0pt, inset: 0.2em, icon("\u{ec1a}"), link("https://www.facebook.com/ugent/", [ Universiteit Gent ]), icon("\u{ec27}"), link("https://twitter.com/ugent", [ \@ugent ]), icon("\u{ec20}"), link("https://www.instagram.com/ugent/", [ \@ugent ]), icon("\u{ec8c}"), link("https://www.linkedin.com/school/ghent-university/", [ Ghent University ]), ..added-content, ) } let body = { set text(size: 24pt, fill: cfg.text-color) show par: set block(spacing: 12pt) let content = () if "email" in cfg and cfg.email != none { content.push(text(size: 25pt, "E")) content.push(link( "mailto:" + cfg.email, text(size: 25pt, cfg.email) )) } if "phone" in cfg and cfg.phone != none { content.push(text(size: 25pt, "T")) content.push(text(size: 25pt, cfg.phone)) } if "mobile" in cfg and cfg.mobile != none { content.push(text(size: 25pt, "M")) content.push(text(size: 25pt, cfg.mobile)) } text(size: 35pt, cfg.authors.join(", ")) linebreak() text(size: 25pt, cfg.role) linebreak() linebreak() smallcaps(text(size: 25pt, cfg.research-group)) linebreak() linebreak() table( columns: (1cm, auto), stroke: none, inset: 0pt, row-gutter: 0.5em, align: left, ..content ) align( bottom + left, link("https://ugent.be", text(size: 25pt, "www.ugent.be")) ) } let box_size = (width: 45.63cm / ratio, height: 18.07cm / ratio) let box_offset = (dx: 2.54cm / ratio, dy: 3.87cm / ratio) let icon_box_size = (width: 20.16cm / ratio, height: 10cm / ratio) let icon_box_offset = (dx: 24.1cm / ratio, dy: 8.6cm / ratio) let icon_box_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) let body_box_size = (width: 20.6cm / ratio, height: 16.03cm / ratio) let body_box_offset = (dx: 3.59cm / ratio, dy: 4.84cm / ratio) let body_box_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) if cfg.logo != none { place(bottom + left, image(cfg.logo, width: 6.41cm / ratio)) } place(top + left, box(fill: cfg.color, ..box_size), ..box_offset) place(top + left, box(fill: cfg.color, social, ..icon_box_size, ..icon_box_inset), ..icon_box_offset) place(top + left, box(fill: cfg.color, body, ..body_box_size, ..body_box_inset), ..body_box_offset) if cfg.second-logo != none { place(top + left, image(cfg.second-logo, height: 3.87cm / ratio)) } if cfg.progress-bar { progress-bar(loc) } }) pagebreak(weak: true) polylux-slide(content) } #let section-slide(title) = { register-section(title) let content = config((cfg, loc) => { let box_size = (width: 45.63cm / ratio, height: 21.94cm / ratio) let box_inset = (dx: 2.54cm / ratio, dy: 0cm) let text_box_inset = (dx: 3.59cm / ratio - box_inset.dx, dy: 9.02cm / ratio - box_inset.dy) let text_box_size = (width: 42.18cm / ratio, height: 12.32cm / ratio) let text_inset = (inset: (x: text_inset.inset.x, y: 15pt)) let body = place(top + left, box({ set text(size: 100pt, fill: cfg.text-color) show text: smallcaps show text: underline align(bottom + left, title) }, ..text_box_size, ..text_inset), ..text_box_inset) place(top + left, box(fill: cfg.color, body, ..box_size), ..box_inset) if cfg.logo != none { place(bottom + left, image(cfg.logo, width: 6.41cm / ratio)) } if cfg.progress-bar { progress-bar(loc) } }) pagebreak(weak: true) polylux-slide(content) } #let body-slide(box-size, box-inset, ..bodies) = { let named = bodies.named() let bodies = bodies.pos() if bodies == none { panic("No bodies provided") } else if bodies.len() == 1 { bodies.first() } else { let colwidths = none let thisgutter = 5pt if "colwidths" in named { colwidths = named.colwidths if colwidths.len() != bodies.len(){ panic("Provided colwidths must be of same length as bodies") } } else { colwidths = (1fr,) * bodies.len() } if "gutter" in named { thisgutter = named.gutter } grid( columns: colwidths, gutter: thisgutter, ..bodies .enumerate() .map(((i, body)) => body) ) } } #let content-image-slide(box-size, box-inset, ..bodies) = { if bodies == none { panic("missing bodies") } let bodies = bodies.pos() if bodies.len() != 2 { panic("content,image must have exactly two bodies, found: " + str(bodies.len())) } let (content, image) = bodies let content_size = (width: 23.45cm / ratio, height: 18.6cm / ratio) let content_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) let image_size = (width: 17.5cm / ratio, height: 18.05cm / ratio) stack( dir: ltr, spacing: 2.3cm / ratio, box(..content_size, ..content_inset, content), box(..image_size, clip: true, image) ) } #let image-slide(..args) = { let named = args.named() let bodies = args.pos() if bodies == none { panic("missing bodies") } if bodies.len() != 2 { panic("content,image must have exactly two bodies") } let (content, picture) = bodies let content_size = (width: 21.54cm / ratio, height: 19.19cm / ratio) let content_offset = (dx: 2.54cm / ratio, dy: 2.81cm / ratio) let content_inset = (inset: (x: 0.25cm / ratio, y: 0.3em)) let content_bg = rgb("#E9F0FA") let image_size = (width: 45.62cm / ratio, height: 22cm / ratio - 0.5pt) let image_offset = (dx: 2.54cm / ratio + 1pt, dy: 0cm / ratio) let content = config((cfg, loc) => { place(top + left, box(fill: ugent-blue, ..image_size, clip: true, picture), ..image_offset) place(top + left, box(fill: content_bg, ..content_size, ..content_inset, { set text(size: 24pt, fill: ugent-blue) content }), ..content_offset) place(bottom + left, image(cfg.logo, width: 6.41cm / ratio)) if "footer" in named { let footer_size = (width: 22.21cm / ratio, height: 1.22cm / ratio) let footer_offset = (dx: 18.92cm / ratio, dy: 24.99cm / ratio) let footer_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) place(top + left, ..footer_offset, box(..footer_size, ..footer_inset, { set text(size: 17.1pt, fill: ugent-accent2, font: "UGent Panno Text") show: align.with(center + horizon) named.footer })) } // Show the slide number in the bottom right corner { set text(fill: ugent-blue, size: 17.1pt) let numbering = current-section let offset = (dx: 43.31cm / ratio, dy: 24.86cm / ratio) let box_size = (width: 1.4 * 2.56cm / ratio, height: 1.44cm / ratio) place(top + left, ..offset, box(..box_size, align(horizon + right, numbering))) } if cfg.progress-bar { progress-bar(loc) } }) polylux-slide(content) } #let slide(kind: "slide", ..bodies) = { let named = bodies.named() let content = { set text(font: "UGent Panno Text", size: 22pt) let box_size = (height: 18.6cm / ratio, width: 43.61cm / ratio) let box_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) let body = if kind == "slide" { body-slide(box_size, box_inset, ..bodies) } else if kind == "content,image" { content-image-slide(box_size, box_inset, ..bodies) } else if kind == "image" { align(center + horizon, body-slide(box_size, box_inset, ..bodies)) } else if kind == "outline" { body-slide(box_size, box_inset, ..bodies) } else { panic("Unknown kind: " + kind) } config((cfg, loc) => { let elems = () // If we have a title, append it to the list of elements if "title" in named { let text_box_size = (width: 43.63cm / ratio) let text_inset = (inset: (x: text_inset.inset.x, y: 10pt)) elems.push( box(..text_box_size, ..text_inset, { set text(size: 50pt, weight: "light", fill: ugent-blue) show text: smallcaps show text: underline align(horizon + left, named.title) }) ) } elems.push(box(..box_size, ..box_inset, body)) place( top + left, dx: 2.54cm / ratio, dy: 0.7cm / ratio, stack( dir: ttb, spacing: 0.75cm / ratio, ..elems ) ) if cfg.logo != none { place(bottom + left, image(cfg.logo, width: 6.41cm / ratio)) } if "footer" in named { let footer_size = (width: 22.21cm / ratio, height: 1.22cm / ratio) let footer_offset = (dx: 18.92cm / ratio, dy: 24.99cm / ratio) let footer_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) place(top + left, ..footer_offset, box(..footer_size, ..footer_inset, { set text(size: 17.1pt, fill: ugent-accent2) show: align.with(center + horizon) named.footer })) } if "date" in named { let date_size = (width: 6.38cm / ratio, height: 1.22cm / ratio) let date_offset = (dx: 11.31cm / ratio, dy: 24.99cm / ratio) let date_inset = (inset: (x: 0.25cm / ratio, y: 0.13cm / ratio)) place(top + left, ..date_offset, box(..date_size, ..date_inset, { set text(size: 17.1pt, fill: ugent-accent2) show text: set align(left + horizon) named.date })) } // Show the slide number in the bottom right corner { set text(fill: ugent-blue, size: 17.1pt) let numbering = current-section let offset = (dx: 43.31cm / ratio, dy: 24.86cm / ratio) let box_size = (width: 1.4 * 2.56cm / ratio, height: 1.44cm / ratio) place(top + left, ..offset, box(..box_size, align(horizon + right, numbering))) } if cfg.progress-bar { progress-bar(loc) } }) } pagebreak(weak: true) polylux-slide(content) } #let outline-slide() = slide(kind: "outline", title: "Outline", polylux-outline())
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/layout/hiding.md
markdown
MIT License
# Hiding things ```typ // author: GeorgeMuscat #let redact(text, fill: black, height: 1em) = { box(rect(fill: fill, height: height)[#hide(text)]) } Example: - Unredacted text - Redacted #redact("text") ```
https://github.com/arthurcadore/eng-telecom-workbook
https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/semester-7/MEC/homework1/homework.typ
typst
MIT License
#import "@preview/klaro-ifsc-sj:0.1.0": report #import "@preview/codelst:2.0.1": sourcecode #show heading: set block(below: 1.5em) #show par: set block(spacing: 1.5em) #set text(font: "Arial", size: 12pt) #set highlight( fill: rgb("#c1c7c3"), stroke: rgb("#6b6a6a"), extent: 2pt, radius: 0.2em, ) #show: doc => report( title: "Flexão Máxima em Vigas Bi-Apoiadas", subtitle: "Mecânica dos Sólidos", authors: ("<NAME>",), date: "08 de Agosto de 2024", doc, ) = Questões: == Questão 1: Determine qual é a Tensão máxima de flexão atua na viga bi-apoiada mostrada a seguir. Desenhe o diagrama de Momento Fletor e de esforço cortante. Fazer manualmente e enviar foto da solução. #figure( figure( rect(image("./pictures/q1.png")), numbering: none, caption: [Representação da viga bi-apoiada - Primeira Questão] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) === Esforço Cortante: #figure( figure( rect(image("./pictures/r1.1.png", width: 90%)), numbering: none, caption: [Calculo do Esforço Cortante] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) === Momento Fletor: #figure( figure( rect(image("./pictures/r1.2.png", width: 90%)), numbering: none, caption: [Calculo do Momento Fletor] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) == Questão 2: Desenhe o diagrama de momento fletor, o diagrama de esforço cortante e a tensão de flexão máxima. O momento de inércia para vigas retangulares é b.h³ /12. Use medidas em metros para obter I (MOMENTO DE INÉRCIA) em m4. #figure( figure( rect(image("./pictures/q2.png")), numbering: none, caption: [Representação da viga bi-apoiada - Segunda Questão] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) === Calculo das Reações: Aplicando no Viga-Online temos: $ X = (x_i + x_f)/2 = (0 + 10)/2 = 5m $ Substituindo na fórmula, encontra-se $ R_1 + R_2 = 50000N ; 10R_2 = 250000N $ Portanto: $ R_1 = 25000N ; R_2 = 25000N $ === Esforço Cortante: Para o calculo do esforço cortante, foi verificado o valor diretamente no software: #figure( figure( rect(image("./pictures/r2.2.png"), width: 70%), numbering: none, caption: [Calculo do Esforço Cortante] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Valor do esforço cortante total: $ W_1 - R_1 + V(x) = 0 $ Portanto: $ W_1 = w(x - x_i) = 5000x - 0 $ Substituindo os valores, temos: $ V(x) = 5000x - 25000 $ A partir dos resultados, temos o seguinte gráfico apresentado para a distribuição do esforço cortante ao longo da viga: #figure( figure( rect(image("./pictures/r2.3.png"), width: 90%), numbering: none, caption: [Plot do Esforço Cortante] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) === Momento Fletor: Para o calculo do momento fletor, da mesma maneira, foi verificado o valor diretamente no software: #figure( figure( rect(image("./pictures/r2.4.png"), width: 70%), numbering: none, caption: [Calculo do Momento Fletor] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Valor do momento fletor total: $ W_1 (x - x_i) - R_1(x - x_i) + M(x) = 0 $ Portanto: $ M(x) = -2500x^2 - 25000x $ A partir dos resultados, temos o seguinte gráfico apresentado para a distribuição do momento fletor ao longo da viga: #figure( figure( rect(image("./pictures/r2.5.png"), width: 90%), numbering: none, caption: [Plot do Momento Fletor] ), caption: figure.caption([Elaborada pelo Autor], position: top) )
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/23-12-15/23-12-15.typ
typst
#import "/template.typ": * #show: project.with( date: "15/12/23", subTitle: "Discussione a seguito del meeting con il Proponente", docType: "verbale", authors: ( "<NAME>", ), timeStart: "12:30", timeEnd: "13:00", ); = Ordine del giorno A seguito dell'incontro odierno che il gruppo ha avuto con il proponente, sono avvenute discussioni riguardanti: - considerazioni fatte durante il meeting esterno; - aggiornamento per ogni membro del gruppo riguardo lo stato di avanzamento dei singoli lavori; - discussione su problemi relativi alle tecnologie da poco implementate; - to do. == Considerazioni fatte durante il meeting esterno I diversi aspetti discussi durante il meeting esterno sono stati analizzati senza grosse difficoltà in quanto la nostra visione del capitolato e le tecnologie proposte sono perfettamente in linea con la visione del proponente. == Aggiornamento per ogni membro del gruppo riguardo lo stato di avanzamento dei singoli lavori È stata colta l'occasione per elencare rapidamente il proprio stato dei lavori agli altri membri del gruppo così da fare un punto della situazione e coordinare al meglio i lavori. == Discussione su problemi relativi alle tecnologie da poco implementate Sono stati analizzati alcuni problemi riscontrati da alcuni membri del gruppo relativamente all'utilizzo di Docker e delle sue versioni. == To do Visti i buoni progressi ottenuti nello sviluppo dei PoC, nelle prossime settimane si intende creare un PoC principale integrando le feature dei singoli PoC minori tra loro così da poter avere un prodotto utile alla valutazione RTB di gennaio.
https://github.com/EvanLuo42/rcore-notes
https://raw.githubusercontent.com/EvanLuo42/rcore-notes/main/Chapter%201/template.typ
typst
// The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let project(body, title: "") = { // Set the document's basic properties. set page(numbering: "1", number-align: center) set text(font: "PingFang SC", lang: "en") set math.equation(numbering: "(1)") // Title align( center, text(weight: "extrabold", size: 20pt)[#title] ) v(15pt) // Main body. set par(justify: true) set heading(numbering: "1.") body }
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/graphs.typ
typst
The Unlicense
#import "../colors.typ": * #import "/packages.typ": cetz #import "/utils.typ" /// Creates a labeled pie chart. /// /// Example Usage: /// /// ```typ /// #pie-chart( /// (value: 8, color: green, name: "wins"), /// (value: 2, color: red, name: "losses") /// ) /// ``` /// /// - ..data (dictionary): Each dictionary must contain 3 fields. /// - value: `<integer>` The value of the section /// - color: `<color>` The value of the section /// - name: `<string>` The name of the section /// -> content #let pie-chart = utils.make-pie-chart(data => { let total let percentages = () for value in data.pos() { total += value.value } for value in data.pos() { percentages.push(calc.round(value.value / total * 100)) } cetz.canvas({ import cetz.draw: * let chart(..values, name: none) = { let values = values.pos() let anchor-angles = () let offset = 0 let total = values.fold(0, (s, v) => s + v.value) let segment(from, to) = { merge-path( close: true, { stroke((paint: black, join: "round", thickness: 0pt)) line((0, 0), (rel: (360deg * from, 2))) arc((), start: from * 360deg, stop: to * 360deg, radius: 2) }, ) } let chart = group( name: name, { stroke((paint: black, join: "round")) for v in values { fill(v.color) let value = v.value / total // Draw the segment segment(offset, offset + value) // Place an anchor for each segment let angle = offset * 360deg + value * 180deg anchor(v.name, (angle, 1.75)) anchor-angles.push(angle) offset += value } }, ) return (chart, anchor-angles) } // Draw the chart let (chart, angles) = chart(..data, name: "chart") chart set-style( mark: (fill: white, start: "o", stroke: black), content: (padding: .1), ) for (index, value) in data.pos().enumerate() { let anchor = "chart." + value.name let angle = angles.at(index) let (line-end, anchor-direction) = if angle > 90deg and angle < 275deg { ((-0.5, 0), "east") } else { ((0.5, 0), "west") } line(anchor, (to: anchor, rel: (angle, 0.5)), (rel: line-end)) content((), [#value.name], anchor: "south-" + anchor-direction) content( (), [ #percentages.at(index)% ], anchor: "north-" + anchor-direction, ) } }) }) /// Example Usage: /// ```typ /// #plot( /// title: "My Epic Graph", /// (name: "thingy", data: ((1,2), (2,5), (3,5))), /// (name: "stuff", data: ((1,1), (2,7), (3,6))), /// (name: "potato", data: ((1,1), (2,3), (3,8))), /// ) /// ``` /// /// - title (string): The title of the graph /// - x-label (string): The label on the x axis /// - y-label (string): The label on the y axis /// - ..data (dictionary): /// -> content #let plot = utils.make-plot((title, x-label, y-label, length, data) => { // The length of the whole plot is 8.5 units. let length = if length == auto { 8.5% } else { length / 8.5 } // Will be populated by the names of the rows of data, and their corresponding colors let legend = () set align(center) cetz.canvas( length: length, { import cetz.draw: * import cetz.plot import cetz.palette // Style for the data lines let plot-colors = (blue, red, green, yellow, pink, orange) let plot-style(i) = { let color = plot-colors.at(calc.rem(i, plot-colors.len())) return ( stroke: (thickness: 1pt, paint: color, cap: "round", join: "round"), fill: color.lighten(75%), ) } set-style(axes: ( grid: ( stroke: (paint: luma(66.67%), dash: "loosely-dotted", cap: "round"), fill: none, ), tick: (stroke: (cap: "round")), stroke: (cap: "round"), )) plot.plot( name: "plot", plot-style: plot-style, size: (9, 5), axis-style: "left", x-grid: "both", y-grid: "both", { for (index, row) in data.pos().enumerate() { plot.add(row.data) legend.push((color: plot-colors.at(index), name: row.name)) } }, ) content("plot.north", [*#title*]) content((to: "plot.south", rel: (0, -0.5)), [#x-label]) content((to: "plot.west", rel: (-0.5, 0)), [#y-label], angle: 90deg) }, ) // legend time for label in legend [ #box(rect(fill: label.color, radius: 1.5pt), width: 0.7em, height: 0.7em) #label.name #h(10pt) ] })
https://github.com/Ombrelin/adv-java
https://raw.githubusercontent.com/Ombrelin/adv-java/master/Slides/4-oriente-fonction.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/sourcerer:0.2.1": code #import themes.clean: * #show: clean-theme.with( logo: image("images/efrei.jpg"), footer: [<NAME>, EFREI Paris], short-title: [EFREI LSI L3 ALSI62-CTP : Java Avancé], color: rgb("#EB6237") ) #title-slide( title: [Java Avancé], subtitle: [Cours 4 : Eléments de programmation orienté fonction], authors: ([<NAME>]), date: [25 Janvier 2024], ) #new-section-slide("Concepts") #slide(title: "Définition")[ - *Fonction de première classe* : manipuler les fonction comme des variables - *Référence de méthode* : variable / argument qui contient une méthode - *Interface fonctionnelle* : interface Java qui type une référence de méthode - *Lamba* : méthode anonyme déclarée en tant qu'expression ] #slide(title: "Exemples")[ #code( lang: "Java", ```java Runnable printHelloWorld = () -> System.out.println("Hello World"); Consumer<String> printHelloName = (String name) -> System.out.println("Hello, " + name); Function<Integer,Integer> square = (Integer number) -> number * number; BiFunction<Integer, Integer,Integer> plus = (leftOperand, rightOperand) -> leftOperand + rightOperand; Calculator<Integer> calculator = new Calculator<Integer>(); calculator.addOperator( "+", (leftOperand, rightOperand) -> leftOperand + rightOperand ); BiFunction<Integer, Integer,Integer> bigDecimalPlus = Integer::add; calculator.addOperator( "+", Integer::add ); ``` ) ] #new-section-slide("Traitement fonctionnels des collections") #slide(title: "Interface `Stream<T>`")[ *`Stream<T>`* : abstraction d'une séquence d'éléments. On peut faire des opération fonctionnelles dessus. _`.stream()` permet de transformer n'importe quelle collection Java en `Stream<T>`_ ] #new-section-slide("Opérateurs de filtrage") #slide(title: "filter")[ Filtrer à partir d'un prédicat #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Shepard",28), new Employee("Liara",106) ); Stream<Employee> seniors = employees .stream() .filter(employee -> employee.getAge() >= 50); // Resultat : [ Employee {name = "Liara", age = 106} ] ``` ) ] #slide(title: "limit")[ Récupérer un certain nombre d'éléments #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Shepard",28), new Employee("Liara",106) ); Stream<Employee> seniors = employees .stream() .limit(1); ``` ) ] #slide(title: "skip")[ Sauter des éléments #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Shepard",28), new Employee("Liara",106), new Employee("Tali",23) ); Steam<Employee> skipTwoEmployees = users .stream() .skip(2); // Resultat : [ Employee {name = "Tali", age = 23} ] ``` ) ] #new-section-slide("Opérateurs de transformation") #slide(title: "map")[ Associer chaque élément à un nouvel élément #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Shepard",28), new Employee("Liara",106), new Employee("Tali",23) ); Stream<String> employeesNames = employees .stream() .map(employee -> employee.getName()) // Resultat : [ "Shepard","Liara","Tali" ] ``` ) ] #new-section-slide("Opérateurs de transformation") #slide(title: "flatMap")[ Applatir des collections #code( lang: "Java", ```java List<Team> teams = List.of( new Team( "First Team", List.of( new Employee("Shepard", 28), new Employee("Liara", 106), new Employee("Tali", 23) }; ), new Team( "Second Team", List.of( new Employee("Garrus", 27), new Employee("Kaidan", 34), new Employee("Joker", 30) ); ), ); Stream<String> employeesName = teams .stream() .flatMap(team -> team.getMembers().stream()) // Retourne Stream<Employee> qui contient les 6 employés ``` ) ] #new-section-slide("Opérateurs terminaux") #slide(title: "Collecter sous formation de collection")[ Enumère le Stream<T> sous forme d'une collection : - Une liste `toList()` - Un ensemble `toSet()` - Un dictionnaire `toMap()` ] #slide(title: "findFirst")[ Récupérer le premier élément de la série (retourne un `Optionnal<T>`). #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Liara",106), new Employee("Tali",23) ); Employee tali = employees .stream() .filter(employee -> Objects.equals(employee.getName(), "Tali")) .findFirst() .get(); ``` ) ] #slide(title: "allMatch et anyMatch")[ Vérifie si les éléments valident un prédicats : - `allMatch` vérifie tous les éléments valide le prédicat - `anyMatch` vérifie qu'au moins un élément valide le prédicat #code( lang: "Java", ```java List<Employee> employees = List.of( new Employee("Shepard",28), new Employee("Liara",106), new Employee("Tali",23) ); boolean areAllEmployeesAdults = employees .stream() .allMatch(employee -> employee.getAge() > 18); // Resultat : true boolean isSomeOneOlderThan100 = employees .stream() .allMatch(employee => employee.getAge() > 100); // Résultat : true ``` ) ] #slide(title: "Comptage")[ - `count` - `min` - `max` ] #new-section-slide("Autre outils fonctionnels") #slide(title: "Pattern matching")[ Tester une expression, pour vérifier si elle a certaines caractéristiques. #code( lang: "Java", ```java public State PerformOperation(String command) { return switch (command) { case "SystemTest" -> runDiagnostics(); case "Start" -> startSystem(); case "Stop" -> stopSystem(); case "Reset" -> resetToReady(); default -> throw new IllegalArgumentException("Invalid string value for command"); }; } ``` ) ] #slide(title: "Record class")[ Classe qui représente des objets-valeur : - Syntaxe plus concise - `equals()`, `hashcode()` et `toString()` générés automatiquement - Immutable #code( lang: "Java", ```java record Rectangle(double length, double width) { } ``` ) ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/outline-entry_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 2-27 cannot outline metadata // #outline(target: metadata) // #metadata("hello")
https://github.com/mattheww/tyroshup
https://raw.githubusercontent.com/mattheww/tyroshup/funcalls/funcalls/expressions.typ
typst
#import "fns.typ": dt, t, t2, rubric, std, syntax = Expressions #rubric[Syntax] #syntax[``` Expression ::= ExpressionWithBlock | ExpressionWithoutBlock ExpressionWithBlock ::= OuterAttributeOrDoc* ( AsyncBlockExpression | BlockExpression | IfExpression | IfLetExpression | LoopExpression | MatchExpression | UnsafeBlockExpression ) ExpressionWithoutBlock ::= OuterAttributeOrDoc* ( ArrayExpression | AwaitExpression | BreakExpression | CallExpression | ClosureExpression | ContinueExpression | FieldAccessExpression | IndexExpression | LiteralExpression | MethodCallExpression | MacroInvocation | OperatorExpression | ParenthesizedExpression | PathExpression | RangeExpression | ReturnExpression | StructExpression | TupleExpression | UnderscoreExpression ) ExpressionList ::= Expression ($$,$$ Expression)* $$,$$? Operand ::= Expression LeftOperand ::= Operand RightOperand ::= Operand ```] #rubric[Legality Rules] An #t("operand") is an #t("expression") nested within an #t("expression"). %SKIPPING% #rubric[Dynamic Semantics] #t("Evaluation") is the process by which an #t("expression") achieves its runtime effects. == Dereference Expression %SKIPPING% The #t("value") of a #t("dereference expression") is determined as follows: - If the #t("type") of the #t("operand") is `&mut T`, `&T`, `*mut T`, or `*const T`, then the #t("value") is the pointed-to #t("value"). - Otherwise the #t("value") is the result of evaluating #t("expression") `*core::ops::Deref::deref(&operand)` or #t("expression") `*core::ops::DerefMut::deref_mut(&mut operand)` respectively. %SKIPPING% == Invocation Expressions === Call Expressions #rubric[Syntax] #syntax[``` CallExpression ::= CallOperand $$($$ ArgumentOperandList? $$)$$ CallOperand ::= Operand ArgumentOperandList ::= ExpressionList ```] #rubric[Legality Rules] A #t("call expression") is an #t("expression") that invokes a #t("function") or constructs a #t("tuple enum variant value") or a #t("tuple struct value"). An #t("argument operand") is an #t("operand") which is used as an argument in a #t("call expression") or a #t("method call expression"). A #t("call operand") is the #t("function") being invoked or the #t("tuple enum variant value") or the #t("tuple struct value") being constructed by a #t("call expression"). %SKIPPING% A #t("callee type") is either a #t("function item type"), a #t("function pointer type"), a #t("tuple enum variant"), a #t("tuple struct type"), or a #t("type") that implements any of the #std("core::ops::Fn"), #std("core::ops::FnMut"), or #std("core::ops::FnOnce") #t2("trait")[traits]. The #t("type") of a #t("call expression") is the #t("return type") of the invoked #t("function"), the #t("type") of the #t("tuple enum variant") or the #t("tuple struct") being constructed, or #t("associated type") #std("core::ops::FnOnce::Output"). A #t("call expression") whose #t("callee type") is either an #t("external function item type"), an #t("unsafe function item type"), or an #t("unsafe function pointer type") shall require #t("unsafe context"). The #t("value") of a #t("call expression") is determined as follows: - If the #t("callee type") is a #t("function item type") or a #t("function pointer type"), then the #t("value") is the result of invoking the corresponding #t("function") with the #t2("argument operand")[argument operands]. - If the #t("callee type") is a #t("tuple enum variant") or a #t("tuple struct type"), then the #t("value") is the result of constructing the #t("tuple enum variant") or the #t("tuple struct") with the #t2("argument operand")[argument operands]. - If the #t("callee type") implements the #std("core::ops::Fn") #t("trait"), then the #t("value") is the result of invoking `core::ops::Fn::call(adjusted_call_operand, argument_operand_tuple)`, where `adjusted_call_operand` is the #t("adjusted call operand"), and `argument_operand_tuple` is a #t("tuple") that wraps the #t2("argument operand")[argument operands]. - If the #t("call operand") implements the #std("core::ops::FnMut") #t("trait"), then the #t("value") is the result of invoking `core::ops::FnMut::call_mut(adjusted_call_operand, argument_operand_tuple),` where `adjusted_call_operand` is the #t("adjusted call operand"), and `argument_operand_tuple` is a #t("tuple") that wraps the #t2("argument operand")[argument operands]. - If the #t("call operand") implements the #std("core::ops::FnOnce") #t("trait"), then the #t("value") is the result of invoking `core::ops::FnOnce::call_once(adjusted_call_operand, argument_operand_tuple),` where `adjusted_call_operand` is the #t("adjusted call operand"), and `argument_operand_tuple` is a #t("tuple") that wraps the #t2("argument operand")[argument operands]. A #t("call expression") is subject to #t("call resolution"). #rubric[Dynamic Semantics] The #t("evaluation") of a #t("call expression") proceeds as follows: + The #t("call operand") is evaluated. + The #t2("argument operand")[argument operands] are evaluated in left-to-right order. + If the #t("adjusted call operand") is a #t("function item type") or #t("function pointer type"), then corresponding #t("function") is invoked. + If the #t("type") of the #t("call operand") implements the #std("core::ops::Fn") #t("trait"), then `core::ops::Fn::call(adjusted_call_operand, argument_operand_tuple)` is invoked. + If the #t("type") of the #t("call operand") implements the #std("core::ops::FnMut") #t("trait"), then `core::ops::FnMut::call_mut(adjusted_call_operand, argument_operand_tuple)` is invoked. + If the #t("type") of the #t("call operand") implements the #std("core::ops::FnOnce") #t("trait"), then `core::ops::FnOnce::call_once(adjusted_call_operand, argument_operand_tuple)` is invoked. #rubric[Undefined Behavior] It is undefined behavior to call a #t("function") with an #t("ABI") other than the #t("ABI") the #t("function") was defined with. #rubric[Examples] ```rust let three: i32 = add(1, 2); ``` === Call Conformance %SKIPPING% An #t("argument operand") matches a #t("function parameter") or #t("field") of the #t("callee type") when its position and the position of the #t("function parameter") or #t("field") are the same. Such an #t("argument operand") is a #dt("matched argument operand"). The #t("type") of a #t("matched argument operand") and the #t("type") of the corresponding #t("function parameter") or #t("field") shall be #t("unifiable"). The number of #t2("argument operand")[argument operands] shall be equal to the number of #t2("field")[fields] or #t2("function parameter")[function parameters] of the #t("callee type"). == Return Expressions #rubric[Syntax] #syntax[``` ReturnExpression ::= $$return$$ Expression? ```] #rubric[Legality Rules] A #t("return expression") is an #t("expression") that optionally yields a #t("value") and causes control flow to return to the end of the enclosing #t("control flow boundary"). A #t("return expression") shall appear within a #t("control flow boundary"). The #t("type") of a #t("return expression") is the #t("never type"). The #t("value") returned by a #t("return expression") is determined as follows: - If the #t("return expression") has an #t("operand"), then the #t("value") is the #t("value") of the #t("operand"). - If the #t("return expression") does not have an #t("operand"), then the #t("value") is the #t("unit value"). #rubric[Dynamic Semantics] The #t("evaluation") of a #t("return expression") proceeds as follows: + If the #t("return expression") has an #t("operand"), then + The #t("operand") is evaluated. + The #t("value") of the #t("operand") is #t2("passing convention")[passed] #t("by move") into the designated output location of the enclosing #t("control flow boundary"). + Control destroys the current activation frame. + Control is transferred to the caller frame. #rubric[Examples] ```rust fn max(left: i32, right: i32) -> i32 { if left > right { return left; } return right; } ```
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_fisica/macchine.typ
typst
= Macchine <macchine> == Rendimenti <rendimenti> \*rendimenti isoentropici === Turbina adiabatica <turbina-adiabatica> $ eta = upright("Lavoro")_(upright("Estratto")) / upright("Lavoro")_(upright("Isoentropico")) = frac(h_2 - h_1, h_2^(upright("iso")) - h_1) $ L'energia utile qui è il lavoro estratto dalla turbina, a spese del ciclo durante la trasformazione di espansione isoentropica. === Pompa <pompa> $ eta = upright("Lavoro")_(upright("tecnico isoentropico")) / upright("Lavoro")_(upright("tecnico reale")) = frac(h_2^(i s o) - h_1, h_2 - h_1) $ Qui isoentropico sta a numeratore perchè la spesa è data dal lavoro che diamo alla macchina(compressore) per ottenere una compressione, la compressione che otteniamo corrisponde al $Delta h_"isoentropico"$ che sarà sempre inferiore al lavoro che forniamo per il II° principio.
https://github.com/sabitov-kirill/comp-arch-conspect
https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/questions/6_ram.typ
typst
#heading[Оперативная память.] #emph[Оперативная память (процесс чтения и записи, тайминги для чтения, развитие оперативной памяти).] #import "/commons.typ": imagebox == Чтение и запись в оперативную память === Внутреннее устройство Для начала вспомним, как выглядит оперативная память. #columns(2)[ #imagebox("DRAM.png", height: 120pt, label: [ DRAM (Dynamic Random Access Memory) ]) Динамическая память имеет: - 1 n-mos транзистор - 1 конденсатор #colbreak() #imagebox("SRAM.png", height: 120pt, label: [ SRAM (Static Random Access Memory) ]) Статичнская память имеет: - 2 n-mos транзистора - 2 инвертора (ещё 2 n-mos и 2 p-mos) ] === Чтение #columns(2)[ *Процесс чтения из _DRAM_*: + Подаём на COL 0.5 от нормального напряжения; + Подаём 1 на ROW (открываем n-mos транзистор); + Производим замер: - если напряжение стало $0.5 - epsilon$, значит хранился 0; - если напряжение стало $0.5 + epsilon$, значит хранился 1. #colbreak() *Процесс чтения из _SRAM_*: + Подаём на COL и #overline[COL] нормальное напряжение; + Подаём 1 на ROW (открываем n-mos транзисторы); + Смотрим напряжение на COL и #overline[COL]: - если $V_"COL" < V_accent("COL", macron)$ , значит в ячейке был записан 0; - если $V_"COL" > V_accent("COL", macron)$ , значит в ячейке был записан 1. ] === Запись Что если мы хотим записать значение $x in {0, 1}$ в ячейку? #columns(2)[ *Процесс записи в _DRAM_*: + Подаём на COL x; + Подаём 1 на ROW (открываем n-mos транзистор); + Ждём тайминг зарядки конденсатора. #colbreak() *Процесс записи в _SRAM_*: + Подаём на COL $x$, а на #overline[COL] $not x$; + Подаём 1 на ROW (открываем n-mos транзисторы); Тем самым мы фактически либо заземляем значение на $Q$ и подаём напряжение на $accent(Q, macron)$, если хотим записать 0, либо подаём напряжение на $Q$ и заземляем на $accent(Q, ‾)$, если хотим записать 1. ] #pagebreak() == Тайминги для чтения #emph[Тайминг оперативной памяти] --- временна́я задержка сигнала при работе динамической оперативной памяти. Измеряются в тактах тактового генератора. От них в значительной степени зависит пропускная способность участка «процессор-память» и задержки чтения данных из памяти и, как следствие, быстродействие системы. #imagebox("DRAM_timings.png", height: 160pt) - tRAS (Row Active Strobe) Минимальное время между открытием и закрытием строки. - tRCD (RAS to CAS Delay) Число тактов между открытием строки и доступом к столбцам в ней. - tCL (CAS Latency) Время, требуемое на чтение бита из памяти, когда нужная строка уже открыта. - tRP (Row Precharge) Время перезарядки конденсаторов после того, как мы использовали строку. === Latency и Throughput #emph[Latency] (скорость доступа) --- время от подачи запроса до начала получения данных. (tRCD + tCL). #emph[Throughput] (пропускная способность) --- время между получением двух порций данных. (tRAS + tRP). == Историческая справка "Так исторически сложилось, что до какого-то момента скорость доступа получалось увеличивать довольно неплохо, но в какой-то момент улучшение скорости доступа почти полностью остановилось и после этого весь прогресс стремится к скорости передачи данных для какого-то конкретного устройства. Есть не очень много способов, чтобы увеличивать скорость доступа, но есть огромное количество ухищрений и техник, чтобы увеличивать скорость передачи данных." #align(right)[Роман Мельников ©] == Про модификации модулей памяти === Многопортовая ячейка памяти Отличием _многопортовой ячейки памяти_ от _однопортовой_ является то, что у каждой ячейки есть 2 набора проводов. Это позволяет одновременно производить операции с двумя ячейками памяти (правда с оговоркой: они должны быть не из одной строки). #columns(2)[ #imagebox("two-port_DRAM.png", label: [Двухпортовая DRAM], height: 117pt) #colbreak() #imagebox("two-port_SRAM.png", label: [Двухпортовая SRAM], height: 117pt) ] === Многобанковая ячейка памяти В _многобанковых ячейках памяти_, RAM разделена на отдельные независимые банки. При обращении в разные банки, тк они являются независимыми и при считывании ячейки (открыть строчку, задать столбец, закрыть строку, перезарядить конденсатор) на другие банки не оказывается никакое влияние, мы можем производить чтение не дожидаясь перезарядки конденсаторов. Таким образом, такой подход выходит выгоднее, когда у нас последовательные запросы обращаются в разные участки памяти(банки). === Синхронная и асинхронная память #emph[Ассинхронная память] --- когда контроллер и модуль памяти взаимодействуют не согласованно(может быть, даже работают с разной частотой). #emph[Синхронная память] --- контроллер и модуль памяти синхронизированы, частота одинаковая. Раньше память была асинхронна, но сейчас (со второй половины 90-х) инженеры научились нормально собирать всё и согласовывать ячейки с контроллером. == Исторически сложившиеся стандарты оперативной памяти \ + *FPM DRAM* (начало 90-х) - Не закрываем строку и не перезаряжаем конденсаторы, если запросы идут последовательно в одну и ту же строку, но в разные столбцы. Например, выполняется последовательный кусок кода, или происходит итерация по массиву; - Ассинхронна. + *EDO DRAM* (первая половина 90-х) - Заведём дополнительный буфер, в котором мы храним адрес cтолбца, к которому мы сейчас обращаемся. Таким образом мы можем передавать адрес столбца для следующего запроса параллельно с тем, как мы получаем данные от предыдущего запроса. - Асинхронна. + *BEDO DRAM* (всё ещё первая половина 90-х) - Будем вместе с запроешенной ячейкой отдавать данные сразу из 4-х следующих ячеек. Это опять же даёт нам ускорение, так как подавляющее большинтсво данных лежат в памяти последовательно и читаются последовательно. - Адрес должен быть кратен 4. - Всё ещё асинхронна. + *SDRAM* (вторая половина 90-х) - Наконец-то контроллер и модуль памяти стали синхронизированы. За счёт этого получилось значительно увеличить частоту. - Шина взаимодействия была расширена до 64 бит. - Начали появляться банки памяти(2-4 шт). + *DDR* (Double Data Rate — удвоенная скорость передачи данных, 1998 год) - Внутренняя шина была расширена в 2 раза. - Передача данных происходит и на фронте, и на спаде сигнала синхронизации. Благодаря этому частота "выросла" в 2 раза. + *DDR2* (2003 год) - Внутренная шина расширена ещё в 2 раза. - Число банков увеличено до 8. - Частота внешней шины увеличена в 2 раза. + *DDR3* (2007 год) - Расширили внутреннюю шину ещё в 2 раза. - Увеличили частоту внешней шины ещё в 2 раза. - Снизили напряжение питания до 1.5 V. + *DDR4* (2014 год) - #strike[Расширили внутреннюю шину ещё в 2 раза.] - Уменьшили напряжение питания до 1.2 V. - Появились группы банков. - Увеличили число банков до 16. + *DDR5* (2020 год) - Уменьшили напряжение питяния до 1.1 V. - Увеличили чисто банков до 32. - Количество данных, отдаваемых подряд (burth length) увеличили вдвое. - У DIMM два независимых канала по 32 бита.
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/03-lebesgue-integral/01-integral-definition.typ
typst
#import "../../utils/core.typ": * == Определение Интеграла #lemma[ Пусть $f >= 0$ простая#rf("def-simple-fn"), $A_i$ --- допустимое разбиение#rf("def-simple-fn"), $a_i$ --- значения $f$ на $A_i$. $B_j$ --- допустимое разбиение, $b_j$ --- значения $f$ на $B_j$. Тогда $sum_(i = 1)^m a_i mu (E sect A_i) = sum_(j = i)^n b_j mu(E sect B_j)$. ] #proof[ $E sect A_i$ = $usb_(j = 1)^m E sect A_i sect B_j$. $ sum_(i = 1)^m a_i mu(E sect A_i) = sum_(i = 1)^m sum_(j = 1)^n underbrace(a_i mu(E sect A_i sect B_j), = b_j mu(E sect A_i sect B_j)) = sum_(j=1)^n sum_(i=1)^m b_j mu (E sect A_i sect B_j) = sum_(j=1)^m b_j mu(E sect B_j). $ Если $E sect A_i sect B_j != nothing$, то $a_i = b_j$. Отметим, что $f >= 0$ нужно, так как меры могут быть бесконечными и в этом случае суммы бесконечностей с разными знаками начнут зависеть от порядка слагаемых (RIP ассоциативность)#rf("inf-arithmetic"). ] #def(label: "def-integral-simple")[ Пусть $f >= 0$ простая#rf("def-simple-fn"), $A_j$ --- допустимое разбиение#rf("def-simple-fn"), $a_i$ --- значения $f$ на $A_i$, $E$ --- измеримо (во всех дальнейших определениях $E$ также будет измеримо!). _Интегралом Лебега_ называется $ integral_E f dif mu = integral_E f(x) dif mu(x) := sum_(i = 1)^m a_i mu(E sect A_i). $ ] #props(label: "integral-simple-props")[ 1. #sublabel("const") Пусть $c >= 0$. Тогда $ integral_E c dif mu = c mu E. $ 2. #sublabel("inequality") Если $f <= g$ --- неотрицательные простые функции, то $ integral_E f dif mu <= integral_E g dif mu. $ 3. #sublabel("sum") Пусть $f, g >= 0$ простые: $ integral_E (f + g) dif mu = integral_E f dif mu + integral_E g dif mu. $ 4. #sublabel("uniform") Пусть $alpha in RR_(>= 0)$, $f >= 0$ --- простая. Тогда $ integral_E alpha f dif mu = alpha integral_E f dif mu. $ ] #proof[ 1. Очевидно: $E$ --- допустимое разбиение себя, $c$ --- значение $f$ на $E$. 2. Рассмотрим общее допустимое разбиение#rf("simple-fn-props", "common-partition") $A_i$ для $f$ и $g$. Тогда $a_i <= b_i$ и $sum_(i = 1)^m a_i mu(E sect A_i) <= sum_(i = 1)^m b_i mu(E sect A_i)$. 3. Тоже самое, только надо сложить. 4. Аналогично и тривиально. ] #def(label: "def-integral-mfn")[ Пусть $f >= 0$ --- измеримая. _Интегралом Лебега_ называется $ integral_E f dif mu = sup {integral_E phi dif mu : 0 <= phi <= f, phi #[--- простая#rf("def-simple-fn")]} $ ] #notice[ Для простых $f$ определения совпадают. ] #def(label: "def-integral")[ Пусть $f$ --- измеримая. _Интегралом_ называется $ integral_E f dif mu = integral_E f_+ dif mu - integral_E f_- dif mu. $ Если при вычитании, получается $(+oo) - (+oo)$, то интеграл не определен. ] #notice[ Для неотрицательных $f$ определения совпадают. ] #props(name: "интеграла от неотрицательных функций", label: "mfn-props")[ 1. #sublabel("inequality") $0 <= f <= g$ измеримые, тогда $ integral_E f dif mu <= integral_E g dif mu. $ 2. #sublabel("zero-domain-zero") Если $mu E = 0$, то $ integral_E f dif mu = 0. $ 3. #sublabel("indicator-extension") Если $f: X --> overline(RR)$, $f >= 0$ измерима на $E$ и $X$ измеримо, то $ integral_E f dif mu = integral_X bb(1)_E dot f dif mu. $ 4. #sublabel("subset-domain-le") $f >= 0$ измеримая, $ A subset B ==> integral_A f dif mu <= integral_B f dif mu. $ ] #proof[ 1. Все подходящие в супремум функции для $f$#rf("def-integral-mfn"), есть и в супремуме функции для $g$. 2. Интеграл любой простой функции $0$ (очевидно из определения#rf("def-integral-simple")), значит в супремуме#rf("def-integral-mfn") множество только из нулей. 3. Если $0 <= phi <= bb(1)_E f$, то такая функция подойдет для супремума#rf("def-integral-mfn") интеграла слева тоже, поэтому знак $>=$ есть. Если $0 <= phi <= f$, то $0 <= bb(1)_E phi <= bb(1)_E f$, отсюда неравенство в другую сторону. 4. $ integral_A f dif mu =^rf("mfn-props", "indicator-extension") integral_B bb(1)_A f dif mu <=^rf("mfn-props", "inequality") integral_B f dif mu. $ ] #th(name: "<NAME>", label: "levy")[ Пусть $0 <= f_1 <= f_2 <= f_3 <= ...$, такие что $f_n$ поточечно сходится к $f$ на $E$. Тогда $ lim integral_E f_n dif mu = integral_E f dif mu. $ ] #proof[ $f_n <= f_(n + 1)$, значит#rf("mfn-props", "inequality") $integral_E f_n dif mu <= integral_E f_(n + 1) dif mu$. Тогда существует $lim integral_E f_n dif mu =: L$. $f_n <= f$, поэтому $integral_E f_n dif mu <= integral_E f dif mu ==> L <= integral_E f dif mu.$ Одно неравенство доказали. Надо доказать, что $L >= integral_E f dif mu =^rf("def-integral-mfn") sup { integral_E phi dif mu bar 0 <= phi <= f, phi #[--- простая] }$. Достаточно доказать, что $L$ --- верхняя граница, то есть что $L >= integral_E phi dif mu$, где $phi$ --- простая $0 <= phi <= f$. Возьмем $theta in (0, 1)$ и докажем, что $L >= theta integral_E phi dif mu =^rf("integral-simple-props", "uniform") integral_E (theta phi) dif mu$, потом перейдем к пределу. Пусть $E_n := E{f_n >= theta phi}$. Это растущая последовательность, $E_1 subset E_2 subset E_3 subset ...$ и $Union_(n = 1)^oo E_n = E$ (это следует из поточечной сходимости $f_n$ к $f >= theta phi$). По непрерывности меры снизу#rf("bottom-up-continious"), $forall A - "измеримое" mu (A sect E_n) -->_(n-->oo) mu (A sect E)$, а значит $ integral_E f_n dif mu >=^rf("mfn-props", "subset-domain-le") integral_(E_n) f_n dif mu >=^rf("mfn-props", "inequality") integral_(E_n) theta phi dif mu =^rf("integral-simple-props", "uniform") theta integral_(E_n) phi dif mu =^rf("def-integral-simple") \ =^rf("def-integral-simple") theta sum_(k = 1)^m a_k mu(A_k sect E_n) -->_(n -> oo) theta sum_(k = 1)^m a_k mu(A_k sect E) =^rf("def-integral-simple") theta integral_E phi dif mu ==> \ ==> lim_(n-->oo) integral_E f_n dif mu >= theta integral_E phi dif mu. $ ] #props(label: "mfn-props'")[ 5. #sublabel("add") _Аддитивность_. Пусть $f, g >= 0$ измеримые. Тогда $ integral_E (f + g) dif mu = integral_E f dif mu + integral_E g dif mu. $ 6. #sublabel("uniform") _Однородность_. $alpha in RR_(>= 0)$, $f >= 0$ измеримая. Тогда $ integral_E (alpha f) dif mu = alpha integral_E f dif mu. $ ] #proof[ Возьмем#rf("simple-approx") простые#rf("def-simple-fn") $phi_n$ такие что $0 <= phi_1 <= phi_2 <= ... --> f$ поточечно, $psi_n$ такие что $0 <= psi_1 <= psi_2 <= ... -> g$ поточечно. Тогда $0 <= phi_1 + psi_1 <= phi_2 + psi_2 <= ... --> f + g$ поточечно. 5. $ underbrace(integral_E (phi_n + psi_n) dif mu, -->^rf("levy") integral_E (f + g) dif mu) = underbrace(integral_E phi_n dif mu, -->^rf("levy") integral_E f dif mu) + underbrace(integral_E psi_n dif mu, -->^rf("levy") integral_E g dif mu). $ 6. $ underbrace(integral_E (alpha phi_n) dif mu, -->^rf("levy") integral_E (alpha f) dif mu) = alpha underbrace( integral_E phi_n dif mu, -->^rf("levy") integral_E f dif mu). $ ] #props(label: "mfn-props''")[ 7. #sublabel("set-additive") _Аддитивность по множеству_. Пусть $f >= 0$ Тогда $ integral_A f dif mu + integral_B f dif mu = integral_(A union.sq B) f dif mu. $ 8. #sublabel("nonzero") Если $mu E > 0$ и $f > 0$ на $E$ то $integral_E f dif mu > 0$. ] #proof[ 7. $bb(1)_A f + bb(1)_B f = bb(1)_(A union.sq B) f$. Выразим интегралы из условия через произведение на характеристическую функцию, все получится по аддитивности#rf("mfn-props'", "add"). 8. $E_n := E{f >= 1/n}$. $E_1 subset E_2 subset ...$ $ Union_(n = 1)^oo E_n = E ==>^rf("bottom-up-continious") mu E_n --> mu E > 0 ==> mu E_n > 0 "при больших" n ==> \ ==> integral_E f dif mu >=^rf("mfn-props", "subset-domain-le") integral_(E_n) f dif mu >=^rf("mfn-props", "inequality") integral_(E_n) 1/n dif mu =^rf("integral-simple-props", "const") 1/n mu E_n > 0. $ ] #example[ Рассмотрим следующую меру: $T = {t_1, t_2, ...}$ --- не более чем счетное. $w_1, w_2, ... >= 0$. $mu A := sum_(t_i in A) w_i$. Пусть $f >= 0$. Тогда проверим, что $ integral_E f dif mu = sum_(t_i in E) f(t_i) w_i. $ Напомню, $integral_E f dif mu =^rf("def-integral-mfn") sup{integral_E phi dif mu : 0 <= phi <= f, phi #[--- простая]}$. - Шаг 1. $f = bb(1)_A$. $ integral_E bb(1)_A dif mu = mu(E sect A) = sum_(t_i in E sect A) w_i = sum_(t_i in E) f(t_i) w_i. $ - Шаг 2. $f >= 0$ --- простая. По линейности#rf("integral-simple-props", "uniform")#rf("integral-simple-props", "add") доказано. - Шаг 3. $f >= 0$ --- измеримая. Будем проверять неравенства с супремумом: - "$sup >= sum$": $phi_n := f dot bb(1)_{t_1, t_2, ..., t_n} <= f$. $ integral_E phi_n dif mu =^rf("def-integral-simple") sum_(t_i in E \ i <= n) f(t_i) dot w_i -->_(n -> oo) sum_(t_i in E) f(t_i) w_i $ - "$sup <= sum$": Доказываем $ integral_E phi dif mu <= sum_(t_i in E) f(t_i) w_i. $ Можно записать для простых: $ integral_E phi dif mu =^rf("def-integral-simple") sum_(t_i in E) phi(t_i) w_i <= sum_(t_i in E) f(t_i) w_i $ так как $phi(t_i) <= f(t_i)$. Если $f$ --- произвольная измеримая, то $ integral_E f dif mu = sum_(t_i in E) f(t_i) w_i $ (если $integral_E f_(plus.minus) dif mu$ конечны, иначе интеграл не определен). ] #def(label: "def-ae")[ Свойство $P(x)$ верно _при почти всех_ $x in E$ или _почти везде_ на $E$, если существует $e subset E$, $mu e = 0$ такое, что $P(x)$ верно при любом $x in E without e$. ] #notice(label: "ae-props-on-countable-union")[ Если имеется последовательность свойств $P_1(x), P_2(x), ...$ выполняющихся почти везде на $E$, то они все вместе тоже выполняются почти везде на $E$. ] #proof[ Возьмем все исключительные множества: $e_1, e_2, ...$ и рассмотрим $e = Union e_n$. Тогда $mu e = 0$. На $E without e$ все $P_n$ выполняются. ] #th(name: "неравенство Чебышева (не путать с неравенством Чебышева из теорвера, где оно называется \"неравенство Маркова\", а неравенство Чебышева там другое)", label: "chebyshev-inequality")[ Пусть $f >= 0$ измеримая, $p, t in [0, +oo)$. Тогда $ mu E{f >= t} <= 1/(t^p) integral_E f^p dif mu. $ ] #proof[ $ integral_E f^p dif mu >=^rf("mfn-props", "subset-domain-le") integral_(E{f >= t}) f^p dif mu >=^rf("mfn-props", "inequality") integral_(E{f >= t}) t^p dif mu =^rf("integral-simple-props", "const") t^p mu E{f >= t}. $ ] #props(name: "связанные с понятием \"почти везде\"", label: "ae-props")[ 1. #sublabel("finite-integral-finite") Если $integral_E abs(f) dif mu < +oo$, то $f$ почти везде конечна на $E$. 2. #sublabel("zero-integral-zero") Если $integral_E abs(f) dif mu = 0$, то $f = 0$ почти везде на $E$. 3. #sublabel("integral-without-zero-eq") Если $A subset B$ и $mu (B without A) = 0$, то $integral_A f dif mu = integral_B f dif mu$. 4. #sublabel("eq-integral-eq") Если $f = g$ почти везде на $E$, то $integral_E f dif mu = integral_E g dif mu$. ] #proof[ 1. $E{f = plus.minus oo} subset E {abs(f) >= n}$. $ mu E{abs(f) >= n} <=_"Чебышев"^rf("chebyshev-inequality") 1/n integral_E abs(f) dif mu -->_(n->oo) 0. $ 2. Если $mu E{abs(f) > 0} > 0$, то интеграл положительный#rf("mfn-props''", "nonzero"), значит $mu E{abs(f) > 0} = 0$. 3. $ integral_B f dif mu =^rf("mfn-props'", "set-additive") integral_A f dif mu + underbrace(integral_(B without A) f dif mu, 0^rf("mfn-props", "zero-domain-zero")). $ 4. Пусть#rf("def-ae") $e subset E$ такое, что $mu e = 0$ и $f = g$ на $E without e$. $ integral_E f dif mu =^rf("ae-props", "integral-without-zero-eq") integral_(E without e) f dif mu = integral_(E without e) g dif mu =^rf("ae-props", "integral-without-zero-eq") integral_E g dif mu. $ ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test automatic numbering in summed content. #for i in range(5) { [+ #numbering("I", 1 + i)] }
https://github.com/furkan/cv
https://raw.githubusercontent.com/furkan/cv/main/modules/education.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Education") #cvEntry( title: [Master of Science in Electrical - Electronics Engineering], society: [Middle East Technical University], date: [2020 - 2023], location: [Ankara, TR], // logo: "../src/logos/ucla.png", description: list( [Thesis: Geometric model error reduction in inverse problem of electrocardiography], [Course: CENG501 Deep Learning], [CGPA: 3.11/4.00] ) ) #cvEntry( title: [Bachelors of Science in Electrical - Electronics Engineering], society: [Middle East Technical University], date: [2016 - 2020], location: [Ankara, TR], // logo: "../src/logos/ucla.png", description: list( [CGPA: 3.53/4.00] ) )
https://github.com/MrToWy/Bachelorarbeit
https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Diagrams/full_ER.typ
typst
```pintora erDiagram Faculty { INT id PK STRING color } Faculty_Translation { INT id PK STRING name INT languageId FK INT facultyId FK } Department { INT id PK INT facultyId FK } Department_Translation { INT id PK STRING name INT languageId FK INT departmentId FK } DegreeProgram { INT id PK STRING abbreviation STRING degree INT semesters STRING start STRING form STRING link STRING po INT departmentId FK BOOLEAN locked BOOLEAN hidden } DegreeProgram_Translation { INT id PK STRING name STRING pruefungsordnung INT languageId FK INT degreeProgramId FK } ModuleGroup { INT id PK INT requiredCreditsFromThisGroup INT degreeProgramId FK } ModuleGroup_Translation { INT id PK STRING name INT languageId FK INT moduleGroupId FK } Module { INT id PK INT number STRING abbreviation INT credits INT hoursPresence INT hoursSelf STRING semester INT courseLength BOOLEAN elective BOOLEAN specialization INT requirementsHardId FK INT requirementsSoftId FK INT responsibleId FK INT degreeProgramId FK INT groupId FK } Module_Translation { INT id PK STRING name STRING subtitle STRING description STRING exam STRING learningOutcomes INT languageId FK INT moduleId FK } SubModule { INT id PK INT number STRING abbreviation INT weeklyHours INT groupSize INT credits INT hoursSelf INT hoursPresence STRING semester INT responsibleId FK INT degreeProgramId FK INT requirementsSoftId FK } SubModule_Translation { INT id PK STRING name STRING subtitle STRING type STRING content STRING presenceRequirements STRING selfStudyRequirements STRING spokenlanguage STRING literature STRING selfStudyHints STRING learningOutcomes STRING exam STRING semester INT languageId FK INT subModuleId FK } User { INT id PK STRING email STRING firstName STRING lastName STRING password INT role BOOLEAN canBeResponsible INT degreeProgramId } User_Translation { INT id PK STRING title INT languageId FK INT userId FK } RequirementList { INT id PK STRING requiredSemesters INT degreeProgramId FK } RequirementList_Translation { INT id PK STRING name INT languageId FK INT requirementListId FK } Changelog { INT id PK INT userId FK STRING description DATETIME created STRING table INT objectId } ChangelogItem { INT id PK INT changelogId FK STRING field STRING oldValue STRING newValue } Job { INT id PK STRING sourceFilePath STRING resultFilePath STRING guid INT degreeProgramId FK INT languageId FK DATETIME startedAt DATETIME finishedAt DATETIME errorAt DATETIME publishedAt } PdfStructure { INT id PK INT degreeProgramId FK } PdfStructureTranslation { INT id PK STRING date STRING page STRING of STRING faculty STRING handbook STRING poVersion INT languageId FK INT pdfStructureId FK } PdfStructureItem { INT id PK INT pdfStructureId FK INT position BOOLEAN takeTwoColumns BOOLEAN moduleBased BOOLEAN subModuleBased } PdfStructureItemPath { INT id PK INT pdfStructureItemId FK INT fieldId FK INT position } PdfStructureItemField { INT id PK STRING path STRING suffix BOOLEAN moduleBased BOOLEAN subModuleBased } PdfStructureItemTranslation { INT id PK STRING name INT languageId FK INT pdfStructureItemId FK } Language { INT id PK STRING abbreviation } User ||--o{ User_Translation : "translations" Module }o--|| DegreeProgram : "degreeProgram" Module }o--o{ SubModule : "subModules" Module ||--o{ Module_Translation : "translations" Module }o--|| ModuleGroup : "group" Module ||--|| RequirementList : "requirementsSoft&Hard " Module }o--o| User : "responsible" RequirementList }o--o{ Module : "modules" SubModule }o--|| DegreeProgram : "degreeProgram" SubModule }o--o| User : "responsible" SubModule ||--o{ SubModule_Translation : "translations" SubModule ||--|| RequirementList : "requirementsSoft" DegreeProgram }o--|| Department : "department" DegreeProgram ||--o{ DegreeProgram_Translation : "translations" DegreeProgram ||--o{ Job : "Job" DegreeProgram }o--|| PdfStructure : "PdfStructure" DegreeProgram |o--o| User : "responsible" ModuleGroup ||--o{ ModuleGroup_Translation : "translations" Faculty ||--o{ Faculty_Translation : "translations" Department }o--|| Faculty : "faculty" Department ||--o{ Department_Translation : "translations" RequirementList ||--o{ RequirementList_Translation : "translations" Changelog }o--|| User : "user" Changelog ||--o{ ChangelogItem : "items" PdfStructure ||--o{ PdfStructureTranslation : "translations" PdfStructureItem }o--|| PdfStructure : "pdfStructure" PdfStructureItem ||--o{ PdfStructureItemTranslation : "translations" PdfStructureItem ||--|{ PdfStructureItemPath : "paths" PdfStructureItemPath }o--|| PdfStructureItemField : "PdfStructureItemPath" Faculty_Translation }o--|| Language : "language" Department_Translation }o--|| Language : "language" DegreeProgram_Translation }o--|| Language : "language" ModuleGroup_Translation }o--|| Language : "language" Module_Translation }o--|| Language : "language" SubModule_Translation }o--|| Language : "language" User_Translation }o--|| Language : "language" RequirementList_Translation }o--|| Language : "language" PdfStructureTranslation }o--|| Language : "language" PdfStructureItemTranslation }o--|| Language : "language" Job }o--|| Language : "language" ```
https://github.com/EdwinChang24/resume
https://raw.githubusercontent.com/EdwinChang24/resume/main/README.md
markdown
MIT License
# <NAME>'s Resume Built with [Typst](https://typst.app/).
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/selection_sort.typ
typst
#import "/components/num_row.typ": num_row #let row_swap(nums, i, j) = num_row( nums, hl_primary: i, hl_secondary: j, arrow: ( from: j, to: i, direction: "bidirectional" ) ) #let row_done(nums, i) = num_row( nums, hl_success: range(i+1) ) #let rows(nums) = { let min_index(nums, start) = { let sublist = nums.slice(start, nums.len()) return sublist.enumerate() .find(((i, x)) => x == calc.min(..sublist)) .at(0) + start } for i in range(nums.len()) { let j = min_index(nums, i) row_swap(nums, i, j) let h = nums.at(i) nums.at(i) = nums.at(j) nums.at(j) = h row_done(nums, i) //empty_row(nums.len()+1) } } #let selection_sort(..nums) = table( columns: (auto,) + (1fr,) * nums.pos().len(), align: center, ..rows(nums.pos()) )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/par-justify_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that there are no hick-ups with justification enabled and // basically empty paragraph. #set par(justify: true) #""
https://github.com/frederiksemmel/linicrypt_typst
https://raw.githubusercontent.com/frederiksemmel/linicrypt_typst/main/lib/template_fs.typ
typst
#import "@preview/ctheorems:1.1.0": * #let script-size = 8pt #let footnote-size = 8.5pt #let small-size = 9pt #let normal-size = 10pt #let large-size = 12pt #let title-size = 14pt // This function gets your whole document as its `body` and formats // it as an article in the style of the American Mathematical Society. #let fs-article( // The article's title. title: [Paper title], // An array of authors. For each author you can specify a name, // department, organization, location, and email. Everything but // but the name is optional. authors: (), // Your article's abstract. Can be omitted if you don't have one. abstract: none, // The article's paper size. Also affects the margins. paper-size: "us-letter", // The path to a bibliography file if you want to cite some external // works. bibliography-file: none, // The document's content. body, ) = { // Formats the author's names in a list with commas and a // final "and". let names = authors.map(author => author.name) let author-string = if authors.len() == 2 { names.join(" and ") } else { names.join(", ", last: ", and ") } // Set document metadata. set document(title: title, author: names) // Set the body font. AMS uses the LaTeX font. set text(size: normal-size, font: "New Computer Modern") // Configure the page. set page( paper: paper-size, // The margins depend on the paper size. margin: { (top: 10em, left: 8em, right: 8em, bottom: 8em) }, ) set par(justify: true) // Configure headings. set heading(numbering: "1.") show heading: it => { // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } // Level 1 headings are centered and smallcaps. // The other ones are run-in. set text(size: normal-size, weight: 400) if it.level == 1 { set align(center) set text(size: large-size, weight: 700) smallcaps[ #v(25pt, weak: true) #number #it.body #v(large-size, weak: true) ] counter(figure.where(kind: "theorem")).update(0) } else { v(21pt, weak: true) number let styled = if it.level == 2 { strong } else { emph } styled(it.body + [. ]) h(17pt, weak: true) } } // show heading: it => { // // Create the heading numbering. // let number = if it.numbering != none { // counter(heading).display(it.numbering) // h(7pt, weak: true) // } // // Level 1 headings are centered and smallcaps. // // The other ones are run-in. // // set text(size: normal-size, weight: 400) // if it.level == 1 { // // set text(size: large-size) // [ // #v(15pt, weak: true) // #number // #it.body // #v(normal-size, weak: true) // ] // counter(figure.where(kind: "theorem")).update(0) // } else { // v(11pt, weak: true) // number // let styled = if it.level == 2 { strong } else { emph } // styled(it.body + [. ]) // h(7pt, weak: true) // } // } // Configure lists and links. // set list(indent: 24pt, body-indent: 5pt) // set enum(indent: 24pt, body-indent: 5pt) show link: set text(font: "New Computer Modern Mono") // show link: set text(font: "New Computer Modern") // Configure equations. // show math.equation: set block(below: 8pt, above: 9pt) // show math.equation: set text(weight: 400) // Configure citation and bibliography styles. set bibliography(style: "springer-mathphys", title: [References]) // Theorem setup show: thmrules // Setup equations and math stuff set math.mat(delim: "[") set math.equation(numbering: "(1)") // Display the title and authors. v(35pt, weak: true) align(center, { upper(text(size: large-size, weight: 700, title)) v(25pt, weak: true) upper(text(size: footnote-size, author-string)) v(15pt, weak: true) text(size: footnote-size, datetime.today().display("[day] [month repr:long] [year]")) }) // Display the abstract if abstract != none { v(20pt, weak: true) set text(script-size) show: pad.with(x: 35pt) smallcaps[Abstract. ] abstract } // Display the article's contents. v(29pt, weak: true) body // Display the bibliography, if any is given. if bibliography-file != none { show bibliography: set text(8.5pt) show bibliography: pad.with(x: 0.5pt) pagebreak() bibliography(bibliography-file) } // The thing ends with details about the authors. show: pad.with(x: 11.5pt) set par(first-line-indent: 0pt) set text(8pt) for author in authors { let keys = ("department", "organization", "location") let dept-str = keys .filter(key => key in author) .map(key => author.at(key)) .join(", ") smallcaps(dept-str) linebreak() if "email" in author [ _Email address:_ #link("mailto:" + author.email) \ ] if "url" in author [ _URL:_ #link(author.url) ] v(12pt, weak: true) } } // concrete theroem setup #let theorem = thmbox("theorem", "Theorem") #let conjecture = thmbox("conjecture", "Conjeture") #let idea = thmbox("idea", "Idea") #let lemma = thmbox("lemma", "Lemma") #let proposition = thmbox("proposition", "Proposition") #let corollary = thmbox("corollary", "Corollary") #let definition = thmbox("definition", "Definition", inset: (x: 0em, top: 0.2em, bottom: 0.8em)) #let example = thmplain("example", "Example").with(numbering: "none") #let remark = thmplain("remark", "Remark") #let proof = thmplain("proof", "Proof", base: "theorem", bodyfmt: body => [#body #h(1fr) $square$ #v(2em)]).with(numbering: none) #let sketch = thmplain( "sketch", "Proof Sketch", base: "theorem", bodyfmt: body => [#body #h(1fr) $square$ #v(2em)], ).with(numbering: none)
https://github.com/Mufanc/hnuslides-typst
https://raw.githubusercontent.com/Mufanc/hnuslides-typst/master/templates/slides.typ
typst
#import "/configs.typ" #import "/utils/colors.typ" #let leading(title, content) = context { let header = text(size: 2em, weight: 300, fill: colors.secondary.transparentize(20%), title) let decoration-color = colors.primary.transparentize(60%) place( center, box(width: configs.slide.width)[ #set align(left) #let hline = pad(top: 2.5em, line(length: 100%, stroke: decoration-color)) #let right-polygon = polygon(fill: decoration-color, (75%, 0em), (75% + 0.6em, -0.8em), (120%, -0.8em), (120%, 0em)) #stack(dir: ltr, spacing: 1em)[ #pad(top: 1em, line(length: 5em, stroke: decoration-color)) ][ #header ][ #hline #hide(right-polygon) ] #pad(top: -measure(hline).height, right-polygon) ] ) hide(header) v(0.5em) parbreak() box() content pagebreak() } #let normal(content) = { content pagebreak() }
https://github.com/Mouwrice/resume
https://raw.githubusercontent.com/Mouwrice/resume/main/modules/professional.typ
typst
#import "../brilliant-CV/template.typ": * #import "@preview/fontawesome:0.1.1": * #let link-icon = super[#fa-arrow-up-right-from-square()] #cvSection("Professional Experience") #cvEntry( title: [Software Developer Internship], society: [Guardsquare], logo: "../src/logos/guardsquare.jpg", date: [July - August 2023 ], location: [Leuven, Belgium], description: list( [Mainly worked on improving the error messages thrown by the #link("https://github.com/Guardsquare/proguard-core")[proguard-core #link-icon] open source project.], [Created an #link("https://github.com/Mouwrice/proguard-core-visualizer")[internal tool #link-icon] to visualize the proguard core reasoning using compose multiplatform. ], ), tags: ("Java", "Kotlin", "Gradle", "Compose Multiplatform", "Java Bytecode") ) #cvEntry( title: [Student Software Developer], society: [Stampix], logo: "../src/logos/stampix.png", date: [July 2022], location: [Ghent, Belgium], description: list( [Responsible for creating the new shop page for the Stampix mobile application.], ), tags: ("TypeScript", "React Native", "GraphQL", "Full-Stack Development") ) #cvEntry( title: [Student Software Developer], society: [Stampix], logo: "../src/logos/stampix.png", date: [July 2021], location: [Ghent, Belgium], description: list( [Responsible for adding the ability to buy extra products at the checkout page, both in the frontend and backend of the site.], [Constructed the complete track and trace page for customer orders.] ), tags: ("TypeScript", "React", "Python", "SQL", "Full-Stack Development") )
https://github.com/BrainTmp/MetaNote
https://raw.githubusercontent.com/BrainTmp/MetaNote/main/README.md
markdown
# MetaNote: LaTeX/Typst Template for Everyday Mathematics Note Taking Welcome to MetaNote, the LaTeX/Typst template designed specifically for everyday mathematics note taking! Typesetting should be the least of your concerns when taking notes. MetaNote is designed to be as minimal as possible, so that you can focus on the content of your notes. We've provided you with plenty of environments to get you started, including theorems, definitions, examples, and more. These boxes feature a clean, minimal design with a light background and a coloured line to the left, consistent with the rest of the document. ## Examples Here are some examples of what you can do with MetaNote. ### Theorems ![Theorem](./assets/theorem1.png) LaTeX ``` ``` Typst ``` #theorem("Infinitesimal Increment Formula")[ If $f(x)$ is differentiable at $x_0$, then $ f(x)=f(x_0)+f'(x_0)(x-x_0)+o(x-x_0). $ This can also be written as $ f(x_0+h)=f(x_0)+f'(x_0)h+o(h). $ These formulas are called the infinitesimal increment formula, and they reveal the change of $f(x)$ when $x-x_0 -> 0$. ] ``` ## Getting Started If you are fond of LaTeX, you can use the `metanote.tex` file to get started. Howeever, if you prefer Typst, you can see the example in the Typst folder. Both `metanote.typ` and `metatheorem.typ` should be copied to your project folder. You may also install the package locally. For current beta version, put the contents of the Typst folder in this repo to `{data-dir}/typst/packages/local/MetaNote/0.0.1`. Here, {data-dir} is `$XDG_DATA_HOME` or `~/.local/share` on Linux `~/Library/Application` Support on macOS `%APPDATA%` on Windows And you can get started by adding the following line to your Typst file: ``` #import "@local/MetaNote:0.0.1": * ``` Happy note taking!
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/styling/fold.typ
typst
--- fold-vec-order-text-features --- // Test fold order of vectors. #set text(features: (liga: 1)) #set text(features: (liga: 0)) fi --- fold-vec-order-text-decos --- #underline(stroke: aqua + 4pt)[ #underline[Hello] ] --- fold-vec-order-meta --- #let c = counter("mycounter") #c.update(1) // Warning: 1:2-7:3 `locate` with callback function is deprecated // Hint: 1:2-7:3 use a `context` expression instead #locate(loc => [ #c.update(2) #c.at(loc) \ // Warning: 12-36 `locate` with callback function is deprecated // Hint: 12-36 use a `context` expression instead Second: #locate(loc => c.at(loc)) ])
https://github.com/Zuttergutao/Typstdocs-Zh-CN-
https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/version/reference.typ
typst
这是一段测试文本@ss @yy #linebreak() 这也是一段测试文本#cite("ss","yy") #bibliography("ref.yml",title:"参考文献")
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/Tutorial-Writing%20in%20Typst/Tutorial-Writing%20in%20Typst.typ
typst
Writing in Typst 用Typst写作 Let's get started! Suppose you got assigned to write a technical report for university. It will contain prose, maths, headings, and figures. To get started, you create a new project on the Typst app. You'll be taken to the editor where you see two panels: A source panel where you compose your document and a preview panel where you see the rendered document. 我们开始吧!假设你被分配为大学写一份技术报告。它将包含散文、数学、标题和数字。要开始,您可以在Typst应用程序上创建一个新项目。您将被带到编辑器,在那里您会看到两个面板:一个是编写文档的源面板,一个是您可以看到渲染文档的预览面板。 You already have a good angle for your report in mind. So let's start by writing the introduction. Enter some text in the editor panel. You'll notice that the text immediately appears on the previewed page 你已经为你的报告想好了。因此,让我们从写导言开始。在编辑器面板中输入一些文本。您会注意到文本立即出现在预览页面上。 Throughout this tutorial, we'll show code examples like this one. Just like in the app, the first panel contains markup and the second panel shows a preview. We shrunk the page to fit the examples so you can see what's going on. 在本教程中,我们将展示像这样的代码示例。就像在应用程序中一样,第一个面板包含标记,第二个面板显示预览。我们缩小了页面以适应示例,以便您可以看到发生了什么。 The next step is to add a heading and emphasize some text. Typst uses simple markup for the most common formatting tasks. To add a heading, enter the = character and to emphasize some text with italics, enclose it in _underscores_. 下一步是添加一个标题并强调一些文本。Typst使用简单的标记来执行最常见的格式化任务。要添加标题,请输入=字符,并用斜体强调一些文本,请将其括在_underscores_。 That was easy! To add a new paragraph, just add a blank line in between two lines of text. If that paragraph needs a subheading, produce it by typing == instead of =. The number of = characters determines the nesting level of the heading. Now we want to list a few of the circumstances that influence glacier dynamics. To do that, we use a numbered list. For each item of the list, we type a + character at the beginning of the line. Typst will automatically number the items. 那很容易!要添加新段落,只需在两行文本之间添加一行空白。如果该段落需要子标题,请键入==而不是=来生成。=字符的数量决定了标题的嵌套级别。 现在,我们想列出一些影响冰川动态的情况。要做到这一点,我们使用一个编号列表。对于列表的每个项目,我们在行的开头键入一个+字符。Typst将自动对项目进行编号。 If we wanted to add a bulleted list, we would use the - character instead of the + character. We can also nest lists: For example, we can add a sub-list to the first item of the list above by indenting it. 如果我们想添加一个项目符号列表,我们将使用-字符而不是+字符。我们也可以嵌套列表:例如,我们可以通过缩进将子列表添加到上述列表的第一个项目中。 Adding a figure 添加一个数字 ou think that your report would benefit from a figure. Let's add one. Typst supports images in the formats PNG, JPEG, GIF, and SVG. To add an image file to your project, first open the file panel by clicking the box icon in the left sidebar. Here, you can see a list of all files in your project. Currently, there is only one: The main Typst file you are writing in. To upload another file, click the button with the arrow in the top-right corner. This opens the upload dialog, in which you can pick files to upload from your computer. Select an image file for your report. 你认为你的报告会从一个数字中受益。让我们添加一个。Typst支持PNG、JPEG、GIF和SVG格式的图像。要将图像文件添加到项目中,请先单击左侧边栏中的框图标打开文件面板。在这里,您可以看到项目中所有文件的列表。目前,只有一个:您正在编写的主要Typst文件。要上传另一个文件,请单击右上角带有箭头的按钮。这将打开上传对话框,您可以在其中选择要从计算机上传的文件。为您的报告选择一个图像文件。 We have seen before that specific symbols (called markup) have specific meaning in Typst. We can use =, -, +, and to create headings, lists and emphasized text, respectively. However, having a special symbol for everything we want to insert into our document would soon become cryptic and unwieldy. For this reason, Typst reserves markup symbols only for the most common things. Everything else is inserted with functions. For our image to show up on the page, we use Typst's image function. 我们以前见过,特定符号(称为标记)在Typst中具有特定含义。我们可以分别使用=、-、+和来创建标题、列表和重点文本。然而,对于我们想插入到文档中的所有内容都有一个特殊的符号,很快就会变得神秘和笨笨脚。出于这个原因,Typst只为最常见的东西保留标记符号。其他一切都插入了功能。为了将我们的图像显示在页面上,我们使用Typst的image功能。 In general, a function produces some output for a set of arguments. When you call a function within markup, you provide the arguments and Typst inserts the result (the function's return value) into the document. In our case, the image function takes one argument: The path to the image file. To call a function in markup, we first need to type the 3 character, immediately followed by the name of the function. Then, we enclose the arguments in parentheses. Typst recognizes many different data types within argument lists. Our file path is a short string of text, so we need to enclose it in double quotes. 一般来说,函数为一组参数产生一些输出。当您在标记中调用函数时,您提供参数,Typst将结果(函数的返回值)插入文档中。在我们的案例中,image函数需要一个参数:图像文件的路径。要在标记中调用函数,我们首先需要键入3 字符,紧跟函数的名称。然后,我们将参数括在括号中。Typst识别参数列表中的许多不同数据类型。我们的文件路径是一个简短的文本字符串,因此我们需要将其括在双引号中。 The inserted image uses the whole width of the page. To change that, pass the width argument to the image function. This is a named argument and therefore specified as a name: value pair. If there are multiple arguments, they are separated by commas, so we first need to put a comma behind the path 插入的图像使用页面的整个宽度。要更改这一点,请将width参数传递给image函数。这是一个命名参数,因此指定为名name: value对。如果有多个参数,它们用逗号分隔,所以我们首先需要在路径后面放一个逗号。 The width argument is a relative length. In our case, we specified a percentage, determining that the image shall take up 70% of the page's width. We also could have specified an absolute value like 1cm or 0.7in. width参数是相对长度。在我们的案例中,我们指定了一个百分比,确定图像应占页面宽度的70%。我们还可以指定一个绝对值,比如1cm或0.7in。 Just like text, the image is now aligned at the left side of the page by default. It's also lacking a caption. Let's fix that by using the figure function. This function takes the figure's contents as a positional argument and an optional caption as a named argument. 就像文本一样,默认情况下,图像现在在页面左侧对齐。它也缺乏标题。让我们通过使用图形函数来解决这个问题。此函数将图形的内容作为位置参数,将可选标题作为命名参数。 Within the argument list of the figure function, Typst is already in code mode. This means, you now have to remove the hash before the image function call. The hash is only needed directly in markup (to disambiguate text from function calls). 在figure函数的参数列表中,Typst已经处于代码模式。这意味着,您现在必须在图像函数调用之前删除散列。散列仅在标记中直接需要(以消除函数调用文本的歧义). The caption consists of arbitrary markup. To give markup to a function, we enclose it in square brackets. This construct is called a content block. 标题由任意标记组成。为了给函数加价,我们把它括在方括号里。这种构造被称为内容块 You continue to write your report and now want to reference the figure. To do that, first attach a label to figure. A label uniquely identifies an element in your document. Add one after the figure by enclosing some name in angle brackets. You can then reference the figure in your text by writing an@ symbol followed by that name. Headings and equations can also be labelled to make them referenceable. 你继续写报告,现在想参考这个数字。要做到这一点,首先在图上贴上标签。标签唯一标识文档中的元素。在图后添加一个,在角括号中附上一些名称。然后,您可以通过写一个@ 符号后跟该名称来引用文本中的图形。标题和方程也可以贴上标签,使其可参考。 So far, we've passed content blocks (markup in square brackets) and strings (text in double quotes) to our functions. Both seem to contain text. What's the difference? 到目前为止,我们已经将内容块(方括号中的标记)和字符串(双引号中的文本)传递给我们的函数。两者似乎都包含文本。有什么区别? A content block can contain text, but also any other kind of markup, function calls, and more, whereas a string is really just a sequence of characters and nothing else. 内容块可以包含文本,也可以包含任何其他类型的标记、函数调用等,而字符串实际上只是一个字符序列,仅此而已。 For example, the image function expects a path to an image file. It would not make sense to pass, e.g., a paragraph of text or another image as the image's path parameter. That's why only strings are allowed here. On the contrary, strings work wherever content is expected because text is a valid kind of content. 例如,图像函数期望图像文件的路径。传递,例如,一段文本或另一张图像作为图像的路径参数是没有意义的。这就是为什么这里只允许使用字符串。相反,字符串在预期内容的地方工作,因为文本是一种有效的内容。 Adding a bibliography 添加参考书目 As you write up your report, you need to back up some of your claims. You can add a bibliography to your document with the bibliography function. This function expects a path to a bibliography file. 当你写报告时,你需要支持你的一些索赔。您可以使用bibliography功能将参考书目添加到文档中。此函数需要参考书目文件的路径。 Typst's native bibliography format is Hayagriva, but for compatibility you can also use BibLaTeX files. As your classmate has already done a literature survey and sent you a .bib file, you'll use that one. Upload the file through the file panel to access it in Typst. Typst的原生参考书目格式是Hayagriva,但为了兼容性,您也可以使用BibLaTeX文件。由于你的同学已经做了文献调查,并给你发了一个.bib文件,你将使用那个。通过文件面板上传文件,以在Typst中访问它。 Once the document contains a bibliography, you can start citing from it. Citations use the same syntax as references to a label. As soon as you cite a source for the first time, it will appear in the bibliography section of your document. Typst supports different citation and bibliography styles. Consult the reference for more details. 一旦文档包含参考书目,您就可以开始引用它。引文使用与引用标签相同的语法。一旦您首次引用来源,它就会出现在文档的参考书目部分。Typst支持不同的引用和参考书目风格。有关更多详细信息,请参阅参考资料。 Maths 数学 After fleshing out the methods section, you move on to the meat of the document: Your equations. Typst has built-in mathematical typesetting and uses its own math notation. Let's start with a simple equation. We wrap it in 4 signs to let Typst know it should expect a mathematical expression: 充实方法部分后,您将转到文档的实质内容:您的方程。Typst内置了数学排版,并使用自己的数学符号。让我们从一个简单的等式开始。我们用4符号包装它,让Typst知道它应该期待一个数学表达式: The equation is typeset inline, on the same line as the surrounding text. If you want to have it on its own line instead, you should insert a single space at its start and end: 方程是内联排版的,与周围文本在同一行上。如果您想把它放在自己的行上,您应该在其开头和结尾插入一个空格: We can see that Typst displayed the single letters Q, A, v, and C as-is, while it translated rho into a Greek letter. Math mode will always show single letters verbatim. Multiple letters, however, are interpreted as symbols, variables, or function names. To imply a multiplication between single letters, put spaces between them. 我们可以看到,Typst按原封不变地显示单个字母Q、A、v和C,而它将rho翻译成希腊字母。数学模式将始终逐字显示单个字母。然而,多个字母被解释为符号、变量或函数名。要暗示单个字母之间的乘法,请在它们之间加空格。 If you want to have a variable that consists of multiple letters, you can enclose it in quotes: 如果您想有一个由多个字母组成的变量,您可以将其括在引号中: You'll also need a sum formula in your paper. We can use the sum symbol and then specify the range of the summation in sub- and superscripts: 你还需要在论文中写一个总和公式。我们可以使用总和符号,然后在子和上标中指定总和的范围: To add a subscript to a symbol or variable, type a - character and then the subscript. Similarly, use the ^ character for a superscript. If your sub- or superscript consists of multiple things, you must enclose them in round parentheses. 要向符号或变量添加下标,请键入-字符,然后键入下标。同样,使用^字符作为上标。如果您的子标或上标由多个东西组成,您必须将它们括在圆括号中。 The above example also showed us how to insert fractions: Simply put a / character between the numerator and the denominator and Typst will automatically turn it into a fraction. Parentheses are smartly resolved, so you can enter your expression as you would into a calculator and Typst will replace parenthesized sub-expressions with the appropriate notation. 上面的示例还向我们展示了如何插入分数:只需在分子和分母之间放置一个/字符,Typst将自动将其转换为分数。括号被巧妙地解决;因此您可以像在计算器中一样输入表达式,Typst会用适当的符号替换括号中的子表达式。 Not all math constructs have special syntax. Instead, we use functions, just like the image function we have seen before. For example, to insert a column vector, we can use the vec function. Within math mode, function calls don't need to start with the 3character. 并非所有的数学结构都有特殊的语法。相反,我们使用函数,就像我们之前看到的图像函数一样。例如,要插入一个列向量,我们可以使用 vec 函数。在数学模式下,函数调用不需要以3字符开始。 Some functions are only available within math mode. For example, the cal function is used to typeset calligraphic letters commonly used for sets. The math section of the reference provides a complete list of all functions that math mode makes available. 有些函数只能在数学模式下使用。例入,cal 函数用于对通常用于集合的书法字母进行排版。引用的数学部分提供了数学模式提供的所有函数的完整列表。 One more thing: Many symbols, such as the arrow, have a lot of variants. You can select among these variants by appending a dot and a modifier name to a symbol's name: 还有一件事: 许多符号,比如箭头,有许多变体。您可以通过在符号名称后面附加一个点和一个修饰符名称来在这些变体中进行选择: This notation is also available in markup mode, but the symbol name must be preceded with #sym. there. See the symbols section for a list of all available symbols. 此表示法在标记模式下也可用,但符号名称前必须加上 3sym。那里。有关所有可用符号的列表,请参见符号部分。 Review 评论 You have now seen how to write a basic document in Typst. You learned how to emphasize text, write lists, insert images, align content, and typeset mathematical expressions. You also learned about Typst's functions. There are many more kinds of content that Typst lets you insert into your document, such as tables, shapes, and code blocks. You can peruse the reference to learn more about these and other features. 您现在已经看到了如何在Typst中编写基本文档。您学会了如何强调文本、编写列表、插入图像、对齐内容和排版数学表达式。您还了解了Typst的功能。Typst允许您将更多类型的内容插入到文档中,例如表格、形状和代码块。您可以阅读参考资料,以了解有关这些和其他功能的更多信息。 For the moment, you have completed writing your report. You have already saved a PDF by clicking on the download button in the top right corner. However, you think the report could look a bit less plain. In the next section, we'll learn how to customize the look of our document. 目前,您已经完成了报告的撰写。您已经通过单击右上角的下载按钮保存了PDF。然而,你认为这份报告可能看起来不那么简单。在下一节中,我们将学习如何自定义文档的外观。
https://github.com/frosty884/vex-typst-notebook
https://raw.githubusercontent.com/frosty884/vex-typst-notebook/main/template.typ
typst
#let notebook(title: "", authors: (), organization: "", location: "", header: none, body) = { set document(author: authors, title: title) // PDF metadata set page(paper:"a4") // Font setup let body-font = "New Computer Modern" let sans-font = "NewCMSans" set text(font: body-font, lang: "en") show math.equation: set text(weight: 400) show heading: set text(font: sans-font) // Title page (flagged for reconstruction) move(dy:-100pt)[ #if header != none { align(center, image(header, width: 650pt, height: 400pt)) } ] move(dx:-100pt, dy:-100pt, rect(width: 300%, outset: 20pt, fill:rgb("#FAC898"))[ #move(dx:95pt)[ #pad( right: 20%, text(font: sans-font, 2.5em, weight: 700, title), ) #pad( right: 20%, text(font: sans-font, 1em, weight: 700, authors), ) ] ] ) pad( top: -6em, right: 20%, text(font: body-font, 1em, organization) ) pad( top: -0.5em, right: 20%, text(font: body-font, 1em, location), ) v(1fr) pagebreak() // Blank page pagebreak() // Table of contents table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [], [], [], [], [], [], [], [], [] ) pagebreak() // Blank page pagebreak() // Main body set page(numbering: "1", footer: locate(loc => { let i = counter(page).at(loc).first() // Get page number if calc.even(i) { return align(left,[#i]) } if calc.odd(i) { return align(right,[#i]) } })) counter(page).update(1) set par(justify: true) body }
https://github.com/dark-flames/apollo-typst
https://raw.githubusercontent.com/dark-flames/apollo-typst/main/content/posts/without-title.md
markdown
Apache License 2.0
+++ title = "Ancestors: Typst (Without Title)" date = "2024-07-09" [taxonomies] tags=["documentation"] [extra] typst = "posts/test" hide_title = true +++