repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/bkorecic/curriculum
https://raw.githubusercontent.com/bkorecic/curriculum/main/template.typ
typst
#import "@preview/fontawesome:0.1.0": * #let primary-color = rgb(60, 112, 180) #let toml-conf = toml("conf.toml") // Redacts content if "sensitive" is true in conf.toml #let sensitive(data) = style(styles => { let size = measure(data, styles) if toml-conf.at("redact", default: false) { box(fill: black, width: size.width, height: size.height) } else { data } }) // The template itself #let conf( name: toml-conf.at("name", default: none), github: toml-conf.at("github", default: none), email: toml-conf.at("email", default: none), phone: toml-conf.at("phone", default: none), lang: "en", doc, ) = { //show heading: set block(above: 0.8em) set page(paper: "us-letter", margin: (x: 1cm, y: 1.25cm)) set text(lang: lang, size: 11pt) // Formato de headings. Por defecto (P1., P2., etc) show heading: it => [ #set block(above: 0.8em, below: 0em) #set text(fill: primary-color) #set line(stroke: primary-color) #smallcaps(it) #line(length: 100%, start: (0pt, -7pt)) ] [ #text(size: 48pt, fill: primary-color, name) #h(1fr) #link("https://github.com/" + github)[#fa-github(size: 13pt) #github] #h(10pt) #fa-envelope() #sensitive(email) #h(10pt) #fa-phone(size: 12pt) #sensitive(phone) #doc ] } // CV entry #let entry( title: "Entry title", subtitle: none, location: none, date: none, description: none, ) = { set list(marker: ([•], [◦])) let tit = [*#title*] let desc = if description != none {list(..description, tight: true)} else {none} let subt = if subtitle != none {[\ _ #subtitle _]} else {none} grid(columns: (1fr, auto), list(tit + subt + desc), align(right)[#location \ _ #date _]) } // When Typst gets emoji PDF export this won't be necessary #let svg-emoji(path) = {box(baseline: 1pt, image(path, height: 14pt))} #let emoji = ( page: ( pencil: svg-emoji("emojis/pagepencil.svg") ), mortarboard: svg-emoji("emojis/mortarboard.svg"), wrench: svg-emoji("emojis/wrench.svg"), trophy: svg-emoji("emojis/trophy.svg"), computer: svg-emoji("emojis/computer.svg"), globe: ( meridian: svg-emoji("emojis/globemeridian.svg") ) )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/field-06.typ
typst
Other
// Closures cannot have fields. #let f(x) = x // Error: 4-11 cannot access fields on user-defined functions #f.invalid
https://github.com/jackkyyh/ZXCSS
https://raw.githubusercontent.com/jackkyyh/ZXCSS/main/main.typ
typst
#import "import.typ": * #set text(size: 25pt) #set terms(separator: h(1em)) #show: metropolis-theme.with() #title-slide( author: text(0.83em)[*<NAME> (Jacky) #super[1]*, <NAME> Li#super[2,3], <NAME>#super[4,5], Aleks Kissinger#super[4], <NAME>ca#super[2,3,6], <NAME>#super[2,6]], // ([*<NAME> (Jacky) #super[1]*], [<NAME>#super[2,3]], [Lia Yeh#super[4,5]], [<NAME>singer#super[4]], [Michele Mosca#super[2,3,6]], ), title: text(rgb("2B3467"))[Graphical CSS Code Transformation Using ZX Calculus], subtitle: [#link("https://arxiv.org/abs/2307.02437")[doi: 10.4204/eptcs.384.1]], extra: text(0.9em)[#super[1]Dept. of Computer Science, University of Hong Kong \ #super[2]Dept. of Combinatorics & Optimization, University of Waterloo\ #super[3]Institute for Quantum Computing, University of Waterloo\ #super[4]University of Oxford\ #super[5]Quantinuum\ #super[6]Perimeter Institute] ) #new-section-slide[Overview] #include "scripts/0_overview.typ" #new-section-slide[Quantum Error Correction] #include "scripts/1_qec.typ" #new-section-slide[Encoders as ZX diagrams] #include "scripts/2_encoder.typ" #new-section-slide[Pushing through the encoder] #include "scripts/3_pte.typ" #new-section-slide[Code morphing] #include "scripts/4_morph.typ" #new-section-slide[Gauge fixing] #include "scripts/5_gauge.typ" #new-section-slide[Conclusion] #slide(title: [Conclusion & outlook], )[ // #write_footer[<NAME> et al. “Code deformation and lattice surgery are gauge fixing.” New Journal of Physics 21 (2018): n. pag.] #line-by-line[ - pushing through the encoder: - generalize to non-CSS codes - code morphing - gauge fixing: - code deformation ] #place(dx: 630pt, dy: -80pt)[#align(center)[#grid[ #image("figs/qr.svg", width: 100pt)][ #link("https://arxiv.org/abs/2307.02437")[#text(0.7em)[arXiv:2307.02437]]]] ] ] #slide(title: [Short Ad...])[ This set of slides is typeset with _Typst_. Easy to learn, fast and versatile! ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-text-07.typ
typst
Other
// Replace worlds but only in lists. #show list: it => [ #show "World": [🌎] #it ] World - World
https://github.com/flavio20002/cyrcuits
https://raw.githubusercontent.com/flavio20002/cyrcuits/main/lib.typ
typst
Other
#import "@preview/cetz:0.3.1" #import "components.typ" : * #let parse-circuit(raw_code) = { let code_str = raw_code.text.replace(regex("to\ *\["),"\n to["); let lines = code_str.split("\n").filter(line => (line.trim().len()> 0)); let elements = () for line in lines { if not line.starts-with("\\begin") and not line.starts-with("\\end") { if line.contains(regex("\\\\draw\ ?\((\d+),(\d+)\)")){ let drawPoint = line.match(regex("\\\\draw\ ?\((\d+),(\d+)\)")).captures.map((it) => {int(it)}) elements.push((name:"point", point: drawPoint)) } else if line.contains(regex("\\\\draw\ ?\(([0-9A-Za-z_]+)\)")){ let drawPoint = line.match(regex("\\\\draw\ ?\(([0-9A-Za-z_]+)\)")).captures.at(0) elements.push((name:"point2", point: drawPoint)) } else if line.contains(regex("\\\\draw\ ?\(([0-9A-Za-z_\.\ ]+)\)")){ let drawPoint = line.match(regex("\\\\draw\ ?\(([0-9A-Za-z_\.\ ]+)\)")).captures.at(0) elements.push((name:"point3", point: drawPoint)) } else if line.contains("node[shape=ground]") { // Parsing nodo di massa let coords = ((0,1),(0,1)); elements.push(("ground", coords)); } else if line.contains(regex("node\[([0-9A-Za-z_]+),\ ?(?:xscale=)?(-?\d),\ ?(?:yscale=)?(-?\d)\]\ ?\(([0-9A-Za-z_]+)\)")){ let (type,xscale,yscale,component-name) = line.match(regex("node\[([0-9A-Za-z_]+),\ ?(?:xscale=)?(-?\d),\ ?(?:yscale=)?(-?\d)\]\ ?\(([0-9A-Za-z_]+)\)")).captures elements.push((name: "node",type:type, xscale:xscale,yscale:yscale, component-name: component-name)); } else if line.contains(regex("to\ *\[")) { // Parsing di elementi come resistori, sorgenti, ecc. let name = "" let l-modifier = "" let label = "" let voltage = "" let flow = "" let flow-config = "" let node-right = none let node-left = none let coordinate-name = none let node-anchor = none let node = none let invert = false if line.contains(regex("to\[([0-9A-Za-z_]+)=([^,\]]*)")){ (name,label) = line.match(regex("to\[([0-9A-Za-z_]+)=([^,\]]*)")).captures } else{ name = line.match(regex("to\[([0-9A-Za-z_]+)")).captures.at(0) } if line.contains(regex("f[>_<^]*=([^,\]]*)")){ (flow-config, flow) = line.match(regex("f([>_<^]*)=([^,\]]*)")).captures } if line.contains(regex("v[>_<^]*=([^,\]]*)")){ voltage = line.match(regex("v[>_<^]*=([^,\]]*)")).captures.at(0) } if line.contains(regex("l(_?)=([^,\]]*)?")){ (l-modifier,label) = line.match(regex("l(_?)=([^,\]]*)?")).captures } if line.contains(regex("(,\s*\-[\*o])")){ node-right = line.match(regex(",\s*\-([\*o]?)")).captures.at(0) } if line.contains(regex("(,\s*[\*o]\-)")){ node-left = line.match(regex(",\s*([\*o])\-")).captures.at(0) } if line.contains(regex("(,\s*[\*o]\-*[\*o])")){ node-left = line.match(regex("([\*o])\-")).captures.at(0) node-right = line.match(regex("\-([\*o]?)")).captures.at(0) } if line.contains(regex("coordinate\ ?\(([0-9A-Za-z_]+)")){ coordinate-name = line.match(regex("coordinate\ ?\(([0-9A-Za-z_]+)")).captures.at(0) } if line.contains(regex("node\[anchor=([0-9A-Za-z-]+)\]\{([^,\}]+)\}")){ (node-anchor,node)= line.match(regex("node\[anchor=([0-9A-Za-z-]+)\]\{([^,\}]+)\}")).captures } if line.contains(regex(",\s*invert")){ invert = true } let dest-point = line.match(regex("\+\+\s*\((-?\d+\.?\d?),(-?\d+\.?\d?)\)")).captures.map((it) => {float(it)}) elements.push((name: name,l-modifier: l-modifier, label: label,flow: flow,flow-config: flow-config,node-right:node-right,node-left:node-left, coordinate-name: coordinate-name, dest-point: dest-point, voltage: voltage,node-anchor:node-anchor,node:node,invert:invert)); } } } elements } #let draw-circuit(scaleFactor, raw_code) = { let elements = parse-circuit(raw_code) cetz.canvas(length: 1cm, { import cetz.draw: * scale(scaleFactor) get-ctx(ctx => { let start-point = none let coordinates = ("origin" : (0,0)) for element in elements{ if (element.name == "point"){ start-point = element.point } else if (element.name == "point2"){ start-point = coordinates.at(element.point) } else if (element.name == "point3"){ start-point = element.point } else if (element.name == "node"){ let (ctx, start) = cetz.coordinate.resolve(ctx,start-point) if (element.type == "spdt"){ spdt(start,xscale:element.xscale, yscale:element.yscale,name: element.component-name) } } else { //let (ctx, start, end) = cetz.coordinate.resolve(ctx,start-point, (rel: element.dest-point,to: start-point)) let start = start-point let end = (rel: element.dest-point,to: start-point) start-point = end if (element.name == "R"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) R(st, en, element) }) } else if (element.name == "battery1"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) battery1(st, en, element) }) } else if (element.name == "isource"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) isource(st, en, element) }) } else if (element.name == "short"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) short(st, en,l-modifier: element.l-modifier, label: element.label) }) } else if (element.name == "open"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) open(st, en,l-modifier: element.l-modifier, label: element.label) }) } else if (element.name == "nos"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) nos(st, en, l-modifier: element.l-modifier, label: element.label,flow: element.flow) }) } else if (element.name == "ospst"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) ospst(st, en, l-modifier: element.l-modifier, label: element.label) }) } else if (element.name == "C"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) C(st, en, element) }) } else if (element.name == "L"){ get-ctx(ctx => { let (ctx, st, en) = cetz.coordinate.resolve(ctx, start, end) L(st, en, element) }) } if (element.node-left == "*"){ get-ctx(ctx => { let (ctx, st) = cetz.coordinate.resolve(ctx, start) node(start) }) } if (element.node-right == "*"){ get-ctx(ctx => { let (ctx, en) = cetz.coordinate.resolve(ctx, end) node(en) }) } if (element.node-left == "o"){ get-ctx(ctx => { let (ctx, st) = cetz.coordinate.resolve(ctx, start) node-empty(start) }) } if (element.node-right == "o"){ get-ctx(ctx => { let (ctx, en) = cetz.coordinate.resolve(ctx, end) node-empty(en) }) } if (element.node != none){ get-ctx(ctx => { let (ctx, en) = cetz.coordinate.resolve(ctx, end) node-content(en,element.node,element.node-anchor) }) } if (element.coordinate-name != none){ coordinates.insert(element.coordinate-name, end) } } } }) }) } #let cyrcuits(scale:1, doc) = [ #show raw.where(lang: "circuitkz") : it => [ #draw-circuit(scale, it) ] #doc ]
https://github.com/abd0-omar/cv-resume
https://raw.githubusercontent.com/abd0-omar/cv-resume/main/README.md
markdown
# cv-resume ![<NAME> (1)_page-0001](https://github.com/abd0-omar/cv-resume/assets/128975938/9d031f28-eb38-4188-aabe-9e0f5e9a05b0) [resume](https://github.com/abd0-omar/cv-resume/files/15447822/Abdelrahman.Omar.1.pdf) It was made using this [template](https://typst.app/universe/package/modern-cv/)
https://github.com/kimushun1101/rengo2024-typst
https://raw.githubusercontent.com/kimushun1101/rengo2024-typst/main/sample-en.typ
typst
MIT No Attribution
// MIT No Attribution // Copyright 2024 <NAME> // https://github.com/kimushun1101/rengo2024-typst #import "libs/rengo-en/lib.typ": rengo, definition, lemma, theorem, corollary, proof #show: rengo.with( title: [Sample Manuscript for the Japan Joint Automatic \ Control Conference], authors: [$ast$T. Jido, H.~Seigyo (Rengo Univ.), and <NAME> (Rengo Corp.)], abstract: [This document describes the information for authors such as paper submission and the style of manuscript. Only PDF manuscripts are acceptable. The PDF manuscripts should be uploaded on the conference homepage. This document is a template file for a paper, although it is not necessary to strictly follow this format.], keywords: ([Electrical paper submission], [The style of manuscript]), bibliography: bibliography("refs.bib", full: false) ) = Introduction Papers must be in 2 pages minimum and 8 pages maximum in A4 size (US letter size is not allowed). The maximum file size allowed is 5MB. = Style of Manuscript == General information The top, bottom, left and right margins should be 20 mm, 27 mm, 20 mm, and 20 mm, respectively, which provide 250 mm $times$ 170 mm space for your document. The character size should be 16 pt for the paper title, 12 pt for the names and affiliations of authors, 12 pt for the chapter titles, 10 pt for the section titles, and 10 pt for the main body. Papers should be prepared in the following order: - Paper title - Author names and affiliations (Presenter should be marked with an asterisk) - Abstract (100 words) - Keywords - Main body and references == Figures and tables Figures and tables should be numbered as Fig.~X and Table~X as shown in @fig:samplefig. Use the terms ``Fig." and ``Table" to refer to figures and tables. Characters in figures and tables should be of adequate size. Figures should be of sufficient quality for publication (300 dpi or higher is recommended). #figure( placement: top, // Supported formats are PNG, JPEG, GIF and SVG. // eps, pdf, etc have been not supported yet. (2024.07.07) // https://typst.app/docs/reference/visualize/image/ image("fig1.svg", width: 80%), caption: [A sample figure.], ) <fig:samplefig> // #figure( // placement: bottom, // caption: [A sample table.], // table( // columns: 3, // stroke: none, // table.header( // [], // [Size (pt)], // [Font], // ), // table.hline(), // [Title], [16], [Gothic], // [Authors], [12], [Gothic], // [Section title], [12], [Gothic], // [Contents], [10], [Mincho], // [Reference], [9], [Mincho], // ) // ) <tab:fonts> == Equations An example of equations is as follows: $ dot(x) (t) &= A x(t) + B u(t), $ <eq:system> $ y(t) &= C x(t) + D u(t). $ <eq:output> // The reference for the equation number is @eq:system or @eq:output. == Theorems // The following is an example of the usage of the *theorem* environment. // The ctheorems package is imported. // If you can not build due to Proxy or other reasons, download the package manually into the libs folder and use it. // + Download ctheorems-1.1.2 from https://typst.app/universe/package/ctheorems // + Extract the commpressed file into `libs` folder. // + Modify `libs/rengo/lib.typ` into `"@preview/ctheorems:1.1.2"` in `"libs/ctheorems-1.1.2/lib.typ"`. #theorem[ Write the theorem here. ] #proof[ Write the proof here. A box (QED mark) is automatically inserted at the end of the proof. ] #definition("Definition of A")[ Write the definition of A here. ]<def:definition1> #lemma("Lemma of B")[ Write the lemma of B here. ]<lem:lemma1> #lemma[ Write the lemma here. The numbering is counted from 1 for each definition or lemma. ]<lem:lemma2> #corollary[ Write the corollary here. Labels can also be used for reference as @def:definition1. ] = References References should appear in a separate bibliography at the end of the paper, with items referred to with numerals in square brackets @web @Conference @Journal. @Book // I have not found a way to cite references as [1, 2, 3] (2024.07.07) The following format is recommended for references: #set enum(numbering: "a)") + Journal papers\ $[$No.$]$ Authors: Paper title; \textit{Journal Title}, Vol.~volume, No.~number, pp.~first page--last page (year) + Conference papers\ $[$No.$]$ Authors: Paper title; \textit{Proceedings Title}, pp.~first page--last page (year) + Books\ $[$No.$]$ Authors: \textit{Book Title}, pp.~first page--last page, publisher (year) + Website\ $[$No.$]$ URL // Information on references can be found on line 11 of this file as follows: `bibliography: bibliography("refs.bib", full: false)`. // A refs.yml is also available instead of a refs.bib. // Changing `full` to `true` will also list references that have not been cited in the paper. Set it back to `false` at the time of submission.
https://github.com/TycheTellsTales/typst-pho
https://raw.githubusercontent.com/TycheTellsTales/typst-pho/main/README.md
markdown
# Worm PHO Based on [Myrddin](https://ujamer.github.io/myrddin/) ## Example ```typst #import "pho": pho, link #pho( viewer: "<NAME>", poster: "<NAME>", date: "January 1st 1001", startPage: 5, endPage: 5, (topic, page) => { topic( title: "Hello World!", board: "Announcements", )[ Hello World!\ \ This is a post\ \ #link[[This is a link.jpg]] #link[BLAMO] ] page(post => { post(poster: "<NAME>")[ Reply 1 ] post(poster: "Foo")[ Reply 2 ] }) }) ```
https://github.com/flechonn/interface-typst
https://raw.githubusercontent.com/flechonn/interface-typst/main/BD/TYPST/exo2.typ
typst
#show terms: meta => { let title = label("Integration Exercise") let duration = label("30min") let difficulty = label("hard") let solution = label("1") let figures = label("") let points = label("20pts") let bonus = label("0") let author = label("") let references = label("") let language = label("english") let material = label("") let name = label("exo2") } = Exercise Write an algorithm to find the maximum element in an array of integers. = Solution ```py def find_max_element(arr): # Initialize max_element with the first element of the array max_element = arr[0] # Iterate through the array starting from the second element for num in arr[1:]: # Update max_element if the current element is greater if num > max_element: max_element = num # Return the maximum element return max_element # Example usage: array = [3, 5, 2, 9, 10, 7, 1] print("Maximum element in the array:", find_max_element(array)) ```
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055_Murders%20at%20Karlov%20Manor.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Murders at Karlov Manor", doc) #include "./055 - Murders at Karlov Manor/001_Episode 1: Ghosts of Our Past.typ" #include "./055 - Murders at Karlov Manor/002_Episode 2: Monsters We Became.typ" #include "./055 - Murders at Karlov Manor/003_Episode 3: Shadows of Regret.typ" #include "./055 - Murders at Karlov Manor/004_Episode 4: Justice Before Mercy.typ" #include "./055 - Murders at Karlov Manor/005_Episode 5: Chains of Expectation.typ" #include "./055 - Murders at Karlov Manor/006_Episode 6: Explosions of Genius.typ" #include "./055 - Murders at Karlov Manor/007_Episode 7: Rot before Recovery.typ" #include "./055 - Murders at Karlov Manor/008_Episode 8: Gods of Chaos.typ" #include "./055 - Murders at Karlov Manor/009_Episode 9: Beauty in Destruction.typ" #include "./055 - Murders at Karlov Manor/010_Episode 10: Roots of Decay.typ" #include "./055 - Murders at Karlov Manor/011_Episode 11: Portents and Omens.typ"
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/core/component/table-of-contents.typ
typst
#import "/src/utils.typ" as _utils #let make-table-of-contents( appendix-marker: none, _outline-state: _utils.state.outline, _appendix-state: _utils.state.appendix, _fonts: (:), ) = { show outline.entry: it => { if it.level == 1 { v(18pt, weak: true) strong({ let body = if _appendix-state.at(it.element.location()) and it.element.numbering != none { it.element.body [ ] numbering(it.element.numbering, ..counter(it.element.func()).at(it.element.location())) } else { it.body } link(it.element.location(), text(font: _fonts.sans, body)) h(1fr) it.page }) } else { it } } show outline: set heading(numbering: none, outlined: false, offset: 0) _outline-state.update(true) outline(depth: 3, indent: auto) _outline-state.update(false) }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/151.%20ds.html.typ
typst
ds.html Do Things that Don't Scale Want to start a startup? Get funded by Y Combinator. July 2013One of the most common types of advice we give at Y Combinator is to do things that don't scale. A lot of would-be founders believe that startups either take off or don't. You build something, make it available, and if you've made a better mousetrap, people beat a path to your door as promised. Or they don't, in which case the market must not exist. [1]Actually startups take off because the founders make them take off. There may be a handful that just grew by themselves, but usually it takes some sort of push to get them going. A good metaphor would be the cranks that car engines had before they got electric starters. Once the engine was going, it would keep going, but there was a separate and laborious process to get it going.RecruitThe most common unscalable thing founders have to do at the start is to recruit users manually. Nearly all startups have to. You can't wait for users to come to you. You have to go out and get them.Stripe is one of the most successful startups we've funded, and the problem they solved was an urgent one. If anyone could have sat back and waited for users, it was Stripe. But in fact they're famous within YC for aggressive early user acquisition.Startups building things for other startups have a big pool of potential users in the other companies we've funded, and none took better advantage of it than Stripe. At YC we use the term "Collison installation" for the technique they invented. More diffident founders ask "Will you try our beta?" and if the answer is yes, they say "Great, we'll send you a link." But the Collison brothers weren't going to wait. When anyone agreed to try Stripe they'd say "Right then, give me your laptop" and set them up on the spot.There are two reasons founders resist going out and recruiting users individually. One is a combination of shyness and laziness. They'd rather sit at home writing code than go out and talk to a bunch of strangers and probably be rejected by most of them. But for a startup to succeed, at least one founder (usually the CEO) will have to spend a lot of time on sales and marketing. [2]The other reason founders ignore this path is that the absolute numbers seem so small at first. This can't be how the big, famous startups got started, they think. The mistake they make is to underestimate the power of compound growth. We encourage every startup to measure their progress by weekly growth rate. If you have 100 users, you need to get 10 more next week to grow 10% a week. And while 110 may not seem much better than 100, if you keep growing at 10% a week you'll be surprised how big the numbers get. After a year you'll have 14,000 users, and after 2 years you'll have 2 million.You'll be doing different things when you're acquiring users a thousand at a time, and growth has to slow down eventually. But if the market exists you can usually start by recruiting users manually and then gradually switch to less manual methods. [3]Airbnb is a classic example of this technique. Marketplaces are so hard to get rolling that you should expect to take heroic measures at first. In Airbnb's case, these consisted of going door to door in New York, recruiting new users and helping existing ones improve their listings. When I remember the Airbnbs during YC, I picture them with rolly bags, because when they showed up for tuesday dinners they'd always just flown back from somewhere.FragileAirbnb now seems like an unstoppable juggernaut, but early on it was so fragile that about 30 days of going out and engaging in person with users made the difference between success and failure.That initial fragility was not a unique feature of Airbnb. Almost all startups are fragile initially. And that's one of the biggest things inexperienced founders and investors (and reporters and know-it-alls on forums) get wrong about them. They unconsciously judge larval startups by the standards of established ones. They're like someone looking at a newborn baby and concluding "there's no way this tiny creature could ever accomplish anything."It's harmless if reporters and know-it-alls dismiss your startup. They always get things wrong. It's even ok if investors dismiss your startup; they'll change their minds when they see growth. The big danger is that you'll dismiss your startup yourself. I've seen it happen. I often have to encourage founders who don't see the full potential of what they're building. Even <NAME> made that mistake. He returned to Harvard for the fall semester after starting Microsoft. He didn't stay long, but he wouldn't have returned at all if he'd realized Microsoft was going to be even a fraction of the size it turned out to be. [4]The question to ask about an early stage startup is not "is this company taking over the world?" but "how big could this company get if the founders did the right things?" And the right things often seem both laborious and inconsequential at the time. Microsoft can't have seemed very impressive when it was just a couple guys in Albuquerque writing Basic interpreters for a market of a few thousand hobbyists (as they were then called), but in retrospect that was the optimal path to dominating microcomputer software. And I know <NAME> and <NAME> didn't feel like they were en route to the big time as they were taking "professional" photos of their first hosts' apartments. They were just trying to survive. But in retrospect that too was the optimal path to dominating a big market.How do you find users to recruit manually? If you build something to solve your own problems, then you only have to find your peers, which is usually straightforward. Otherwise you'll have to make a more deliberate effort to locate the most promising vein of users. The usual way to do that is to get some initial set of users by doing a comparatively untargeted launch, and then to observe which kind seem most enthusiastic, and seek out more like them. For example, <NAME> noticed that a lot of the earliest Pinterest users were interested in design, so he went to a conference of design bloggers to recruit users, and that worked well. [5]DelightYou should take extraordinary measures not just to acquire users, but also to make them happy. For as long as they could (which turned out to be surprisingly long), Wufoo sent each new user a hand-written thank you note. Your first users should feel that signing up with you was one of the best choices they ever made. And you in turn should be racking your brains to think of new ways to delight them.Why do we have to teach startups this? Why is it counterintuitive for founders? Three reasons, I think.One is that a lot of startup founders are trained as engineers, and customer service is not part of the training of engineers. You're supposed to build things that are robust and elegant, not be slavishly attentive to individual users like some kind of salesperson. Ironically, part of the reason engineering is traditionally averse to handholding is that its traditions date from a time when engineers were less powerful — when they were only in charge of their narrow domain of building things, rather than running the whole show. You can be ornery when you're Scotty, but not when you're Kirk.Another reason founders don't focus enough on individual customers is that they worry it won't scale. But when founders of larval startups worry about this, I point out that in their current state they have nothing to lose. Maybe if they go out of their way to make existing users super happy, they'll one day have too many to do so much for. That would be a great problem to have. See if you can make it happen. And incidentally, when it does, you'll find that delighting customers scales better than you expected. Partly because you can usually find ways to make anything scale more than you would have predicted, and partly because delighting customers will by then have permeated your culture.I have never once seen a startup lured down a blind alley by trying too hard to make their initial users happy.But perhaps the biggest thing preventing founders from realizing how attentive they could be to their users is that they've never experienced such attention themselves. Their standards for customer service have been set by the companies they've been customers of, which are mostly big ones. <NAME> doesn't send you a hand-written note after you buy a laptop. He can't. But you can. That's one advantage of being small: you can provide a level of service no big company can. [6]Once you realize that existing conventions are not the upper bound on user experience, it's interesting in a very pleasant way to think about how far you could go to delight your users.ExperienceI was trying to think of a phrase to convey how extreme your attention to users should be, and I realized <NAME> had already done it: insanely great. Steve wasn't just using "insanely" as a synonym for "very." He meant it more literally — that one should focus on quality of execution to a degree that in everyday life would be considered pathological.All the most successful startups we've funded have, and that probably doesn't surprise would-be founders. What novice founders don't get is what insanely great translates to in a larval startup. When <NAME> started using that phrase, Apple was already an established company. He meant the Mac (and its documentation and even packaging — such is the nature of obsession) should be insanely well designed and manufactured. That's not hard for engineers to grasp. It's just a more extreme version of designing a robust and elegant product.What founders have a hard time grasping (and Steve himself might have had a hard time grasping) is what insanely great morphs into as you roll the time slider back to the first couple months of a startup's life. It's not the product that should be insanely great, but the experience of being your user. The product is just one component of that. For a big company it's necessarily the dominant one. But you can and should give users an insanely great experience with an early, incomplete, buggy product, if you make up the difference with attentiveness.Can, perhaps, but should? Yes. Over-engaging with early users is not just a permissible technique for getting growth rolling. For most successful startups it's a necessary part of the feedback loop that makes the product good. Making a better mousetrap is not an atomic operation. Even if you start the way most successful startups have, by building something you yourself need, the first thing you build is never quite right. And except in domains with big penalties for making mistakes, it's often better not to aim for perfection initially. In software, especially, it usually works best to get something in front of users as soon as it has a quantum of utility, and then see what they do with it. Perfectionism is often an excuse for procrastination, and in any case your initial model of users is always inaccurate, even if you're one of them. [7]The feedback you get from engaging directly with your earliest users will be the best you ever get. When you're so big you have to resort to focus groups, you'll wish you could go over to your users' homes and offices and watch them use your stuff like you did when there were only a handful of them.FireSometimes the right unscalable trick is to focus on a deliberately narrow market. It's like keeping a fire contained at first to get it really hot before adding more logs.That's what Facebook did. At first it was just for Harvard students. In that form it only had a potential market of a few thousand people, but because they felt it was really for them, a critical mass of them signed up. After Facebook stopped being for Harvard students, it remained for students at specific colleges for quite a while. When I interviewed <NAME>berg at Startup School, he said that while it was a lot of work creating course lists for each school, doing that made students feel the site was their natural home.Any startup that could be described as a marketplace usually has to start in a subset of the market, but this can work for other startups as well. It's always worth asking if there's a subset of the market in which you can get a critical mass of users quickly. [8]Most startups that use the contained fire strategy do it unconsciously. They build something for themselves and their friends, who happen to be the early adopters, and only realize later that they could offer it to a broader market. The strategy works just as well if you do it unconsciously. The biggest danger of not being consciously aware of this pattern is for those who naively discard part of it. E.g. if you don't build something for yourself and your friends, or even if you do, but you come from the corporate world and your friends are not early adopters, you'll no longer have a perfect initial market handed to you on a platter.Among companies, the best early adopters are usually other startups. They're more open to new things both by nature and because, having just been started, they haven't made all their choices yet. Plus when they succeed they grow fast, and you with them. It was one of many unforeseen advantages of the YC model (and specifically of making YC big) that B2B startups now have an instant market of hundreds of other startups ready at hand.MerakiFor hardware startups there's a variant of doing things that don't scale that we call "pulling a Meraki." Although we didn't fund Meraki, the founders were <NAME>'s grad students, so we know their history. They got started by doing something that really doesn't scale: assembling their routers themselves.Hardware startups face an obstacle that software startups don't. The minimum order for a factory production run is usually several hundred thousand dollars. Which can put you in a catch-22: without a product you can't generate the growth you need to raise the money to manufacture your product. Back when hardware startups had to rely on investors for money, you had to be pretty convincing to overcome this. The arrival of crowdfunding (or more precisely, preorders) has helped a lot. But even so I'd advise startups to pull a Meraki initially if they can. That's what Pebble did. The Pebbles assembled the first several hundred watches themselves. If they hadn't gone through that phase, they probably wouldn't have sold $10 million worth of watches when they did go on Kickstarter.Like paying excessive attention to early customers, fabricating things yourself turns out to be valuable for hardware startups. You can tweak the design faster when you're the factory, and you learn things you'd never have known otherwise. <NAME> of Pebble said one of the things he learned was "how valuable it was to source good screws." Who knew?ConsultSometimes we advise founders of B2B startups to take over-engagement to an extreme, and to pick a single user and act as if they were consultants building something just for that one user. The initial user serves as the form for your mold; keep tweaking till you fit their needs perfectly, and you'll usually find you've made something other users want too. Even if there aren't many of them, there are probably adjacent territories that have more. As long as you can find just one user who really needs something and can act on that need, you've got a toehold in making something people want, and that's as much as any startup needs initially. [9]Consulting is the canonical example of work that doesn't scale. But (like other ways of bestowing one's favors liberally) it's safe to do it so long as you're not being paid to. That's where companies cross the line. So long as you're a product company that's merely being extra attentive to a customer, they're very grateful even if you don't solve all their problems. But when they start paying you specifically for that attentiveness — when they start paying you by the hour — they expect you to do everything.Another consulting-like technique for recruiting initially lukewarm users is to use your software yourselves on their behalf. We did that at Viaweb. When we approached merchants asking if they wanted to use our software to make online stores, some said no, but they'd let us make one for them. Since we would do anything to get users, we did. We felt pretty lame at the time. Instead of organizing big strategic e-commerce partnerships, we were trying to sell luggage and pens and men's shirts. But in retrospect it was exactly the right thing to do, because it taught us how it would feel to merchants to use our software. Sometimes the feedback loop was near instantaneous: in the middle of building some merchant's site I'd find I needed a feature we didn't have, so I'd spend a couple hours implementing it and then resume building the site.ManualThere's a more extreme variant where you don't just use your software, but are your software. When you only have a small number of users, you can sometimes get away with doing by hand things that you plan to automate later. This lets you launch faster, and when you do finally automate yourself out of the loop, you'll know exactly what to build because you'll have muscle memory from doing it yourself.When manual components look to the user like software, this technique starts to have aspects of a practical joke. For example, the way Stripe delivered "instant" merchant accounts to its first users was that the founders manually signed them up for traditional merchant accounts behind the scenes.Some startups could be entirely manual at first. If you can find someone with a problem that needs solving and you can solve it manually, go ahead and do that for as long as you can, and then gradually automate the bottlenecks. It would be a little frightening to be solving users' problems in a way that wasn't yet automatic, but less frightening than the far more common case of having something automatic that doesn't yet solve anyone's problems.BigI should mention one sort of initial tactic that usually doesn't work: the Big Launch. I occasionally meet founders who seem to believe startups are projectiles rather than powered aircraft, and that they'll make it big if and only if they're launched with sufficient initial velocity. They want to launch simultaneously in 8 different publications, with embargoes. And on a tuesday, of course, since they read somewhere that's the optimum day to launch something.It's easy to see how little launches matter. Think of some successful startups. How many of their launches do you remember? All you need from a launch is some initial core of users. How well you're doing a few months later will depend more on how happy you made those users than how many there were of them. [10]So why do founders think launches matter? A combination of solipsism and laziness. They think what they're building is so great that everyone who hears about it will immediately sign up. Plus it would be so much less work if you could get users merely by broadcasting your existence, rather than recruiting them one at a time. But even if what you're building really is great, getting users will always be a gradual process — partly because great things are usually also novel, but mainly because users have other things to think about.Partnerships too usually don't work. They don't work for startups in general, but they especially don't work as a way to get growth started. It's a common mistake among inexperienced founders to believe that a partnership with a big company will be their big break. Six months later they're all saying the same thing: that was way more work than we expected, and we ended up getting practically nothing out of it. [11]It's not enough just to do something extraordinary initially. You have to make an extraordinary effort initially. Any strategy that omits the effort — whether it's expecting a big launch to get you users, or a big partner — is ipso facto suspect.VectorThe need to do something unscalably laborious to get started is so nearly universal that it might be a good idea to stop thinking of startup ideas as scalars. Instead we should try thinking of them as pairs of what you're going to build, plus the unscalable thing(s) you're going to do initially to get the company going.It could be interesting to start viewing startup ideas this way, because now that there are two components you can try to be imaginative about the second as well as the first. But in most cases the second component will be what it usually is — recruit users manually and give them an overwhelmingly good experience — and the main benefit of treating startups as vectors will be to remind founders they need to work hard in two dimensions. [12]In the best case, both components of the vector contribute to your company's DNA: the unscalable things you have to do to get started are not merely a necessary evil, but change the company permanently for the better. If you have to be aggressive about user acquisition when you're small, you'll probably still be aggressive when you're big. If you have to manufacture your own hardware, or use your software on users's behalf, you'll learn things you couldn't have learned otherwise. And most importantly, if you have to work hard to delight users when you only have a handful of them, you'll keep doing it when you have a lot.Notes[1] Actually Emerson never mentioned mousetraps specifically. He wrote "If a man has good corn or wood, or boards, or pigs, to sell, or can make better chairs or knives, crucibles or church organs, than anybody else, you will find a broad hard-beaten road to his house, though it be in the woods."[2] Thanks to <NAME> for suggesting I make this explicit. And no, you can't avoid doing sales by hiring someone to do it for you. You have to do sales yourself initially. Later you can hire a real salesperson to replace you.[3] The reason this works is that as you get bigger, your size helps you grow. <NAME> wrote "At some point, there was a very noticeable change in how Stripe felt. It tipped from being this boulder we had to push to being a train car that in fact had its own momentum."[4] One of the more subtle ways in which YC can help founders is by calibrating their ambitions, because we know exactly how a lot of successful startups looked when they were just getting started.[5] If you're building something for which you can't easily get a small set of users to observe — e.g. enterprise software — and in a domain where you have no connections, you'll have to rely on cold calls and introductions. But should you even be working on such an idea?[6] <NAME> pointed out an interesting trap founders fall into in the beginning. They want so much to seem big that they imitate even the flaws of big companies, like indifference to individual users. This seems to them more "professional." Actually it's better to embrace the fact that you're small and use whatever advantages that brings.[7] Your user model almost couldn't be perfectly accurate, because users' needs often change in response to what you build for them. Build them a microcomputer, and suddenly they need to run spreadsheets on it, because the arrival of your new microcomputer causes someone to invent the spreadsheet.[8] If you have to choose between the subset that will sign up quickest and those that will pay the most, it's usually best to pick the former, because those are probably the early adopters. They'll have a better influence on your product, and they won't make you expend as much effort on sales. And though they have less money, you don't need that much to maintain your target growth rate early on.[9] Yes, I can imagine cases where you could end up making something that was really only useful for one user. But those are usually obvious, even to inexperienced founders. So if it's not obvious you'd be making something for a market of one, don't worry about that danger.[10] There may even be an inverse correlation between launch magnitude and success. The only launches I remember are famous flops like the Segway and Google Wave. Wave is a particularly alarming example, because I think it was actually a great idea that was killed partly by its overdone launch.[11] Google grew big on the back of Yahoo, but that wasn't a partnership. Yahoo was their customer.[12] It will also remind founders that an idea where the second component is empty — an idea where there is nothing you can do to get going, e.g. because you have no way to find users to recruit manually — is probably a bad idea, at least for those founders.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Japanese TranslationRussian TranslationFrench TranslationArabic TranslationItalian TranslationKorean Translation
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/1-introduction/mod.typ
typst
MIT License
#import "../../lib/mod.typ": * = Introduction <introduction> The introduction to the thesis will be structured as follows. First, #nameref(<intro-motivation>, "Motivation") presents the motivation for the thesis, then the problem definition is outlined in @intro-problem-definition. With the motivation and problem definition stated clearly, the research aspects are presented in #numref(<intro-research-hypothesis>)-#numref(<intro-research-objectives>). The software devloped for this project can generally be found at the GitHub organization #link("https://github.com/AU-Master-Thesis","AU-Master-Thesis"). This includes the repository for #acr("MAGICS") found at #gbp-rs(content: "AU-Master-Thesis/gbp-rs"), and other forked repositories. Lastly, individual contributions by each author are presented in @appendix.contributions. #include "motivation.typ" #include "problem-definition.typ" #include "research.typ"
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/lib/cover.typ
typst
MIT License
#import "textTemplate.typ": * #let cover( lang: "", title: "", degree: "", program: "", author: "", studentnumber: "", authormail: "", location: "", cover-font: "Arial", physicalPrint: true, ) = { { set page( margin: (left: 20mm, right: 10mm, top: 40mm, bottom: 40mm), numbering: none, number-align: center, background: image("../assets/report_cover_empty.svg"), ) let htwg-color-dark-blue = rgb(51,65,82) let background-color = htwg-color-dark-blue let compile-date = datetime.today().display("[day].[month].[year]") let languageText = textTemplate(pagetype: "coverpage" ,lang: lang) set text( font: cover-font, size: 12pt, lang: lang, fill: white ) // --- -------------- --- // --- -------------- --- // ------- Cover -------- // ----- Char Pics ------ place( top + left, dx: -15pt, dy: 100pt, box( fill: background-color, outset: (x: 20pt, y: 15pt), if degree == "Bachelor" { image("../assets/B_black.svg", width: 5.7%) } else if degree == "Master" { image("../assets/M_black.svg", width: 7%) } )) place( bottom + left, dx: 52pt, dy: 10pt, box( fill: background-color, outset: (x: 20pt, y: 15pt), if degree == "Bachelor" or degree == "Master" { image("../assets/S_black.svg", width: 5.2%) } else { } )) place( top + right, dx: -75pt, dy: 230pt, box( fill: background-color, outset: (x: 20pt, y: 15pt), if degree == "Bachelor" or degree == "Master" { image("../assets/C_black.svg", width: 5.2%) } else { } )) // -- Author Informations -- place( top + right, dx: -20pt, dy: 15pt, box( fill: background-color, outset: (x: 20pt, y: 15pt), align(left, text(font: cover-font, size: 11pt, weight: 800, languageText.at(0))) + v(3mm) + align(left, text(font: cover-font, size: 10pt, weight: 400, author)) + align(left, text(font: cover-font, size: 10pt, weight: 400, languageText.at(1) + studentnumber)) + align(left, text(font: cover-font, size: 10pt, weight: 400, authormail)) )) v(140mm) // -- Location and Date -- place( bottom + right, dx: -40pt, dy: 50pt, box( fill: background-color, outset: (x: 20pt, y: 15pt), align(left, text(font: cover-font, size: 11pt, weight: 400, location + ", " + compile-date) ))) // ------- Title -------- box( fill: background-color, outset: (x: 40pt, y: 10pt), if degree == "Bachelor" or degree == "Master" { align(left, text(font: cover-font, 2em, weight: 100, degree + "thesis")) } else { align(left, text(font: cover-font, 2em, weight: 100, degree)) } + align(left, text(font: cover-font, 2em, weight: 700, title)) ) } if physicalPrint { pagebreak() } { set page( margin: (left: 20mm, right: 20mm, top: 40mm, bottom: 40mm), numbering: "i", number-align: center, ) } }
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework5.typ
typst
#import "../template.typ": * #show: project.with( title: "Calculus Homework #5", authors: (( name: "<NAME> (#47)", email: "<EMAIL>", phone: "3230104585" ),), date: "October 27, 2023", ) = P71 习题1-4 9(1) #prob[求证:方程 $2^x-4x=0$ 在 $display((0,1/2))$ 内必有一实根.] $f(x) = 2^x - 4x$ 是初等函数,在 $RR$ 上连续.已知 $f(0) = 1>0,sp f(1/2) = sqrt(2)-2<0$.根据 *零点定理*,$f(x)=0$ 在 $display((0,1/2))$ 上必有一实根. = P72 习题1-4 10(1) #prob[若 $f(x)$ 在 $[a,b]$ 上连续,$x_1,x_2,dots.c,x_n in [a,b]$,证明至少存在一点 $xi in [a,b]$,使 $ f(xi) = (f(x_1)+f(x_2)+dots.c+f(x_n))/n $] 设 $M = min{f(x_1),f(x_2),dots.c,f(x_n)}$,$N = max{f(x_1),f(x_2),dots.c,f(x_n)}$。已知 $f(x)$ 在 $[a,b]$ 上连续,由于 $M<=f(xi)<=N$,根据 *介值定理*,对于 $f(x)$ 在 $M$ 到 $N$ 的任意实数 $c$ 都有至少存在一个 $xi$ 使得 $f(xi)=c$.故一定存在 $xi in [a,b]$ 满足题意. = P72 习题1-4 12(1) #prob[求极限:$ lim_(x->0) frac((1+alpha x)^a-(1+beta x)^b,x) $] $ lim_(x->0) frac((1+alpha x)^a-(1+beta x)^b,x) = lim_(x->0) frac((1+a alpha x) - (1+b beta x)+o(x),x) = a alpha - b beta $ = P72 习题1-4 12(2) #prob[求极限:$ lim_(x->a) frac(x^alpha-a^alpha,x^beta-a^beta) quad(a>0,beta!=0) $] 令 $u=x-a$.当 $x->a$ 时,$u->0$. $ lim_(x->a) frac(x^alpha-a^alpha,x^beta-a^beta) = lim_(u->0) frac((a+u)^alpha-a^alpha,(a+u)^beta-a^beta) = display(lim_(u->0) frac((a+u)^alpha-a^alpha,(a+u)-a))/display(lim_(u->0) frac((a+u)^beta-a^beta,(a+u)-a)) = frac(alpha a^(alpha-1),beta a^(beta-1)) = (alpha a^(alpha-beta))/beta $ = P72 习题1-4 12(4) #prob[求极限:$ lim_(x->-oo) frac(ln(1+3^x),ln(1+2^x)) $] 已知 $x->-oo$ 时,$2^x->0$ 且 $3^x->0$. $ lim_(x->-oo) frac(ln(1+3^x),ln(1+2^x)) = lim_(x->-oo) frac(3^x,2^x) = 0 $ = P72 习题1-4 12(5) #prob[求极限:$ lim_(x->+oo) frac(ln(1+3^x),ln(1+2^x)) $] $ lim_(x->+oo) frac(ln(1+3^x),ln(1+2^x)) = lim_(x->+oo) frac(ln(3^x),ln(2^x)) = lim_(x->+oo) frac(x ln 3,x ln 2) = (ln 3) / (ln 2) $ = P72 习题1-4 12(7) #prob[求极限:$ lim_(x->+oo) (2 e^(x/(x^2+1)) - 1)^((x^2+1)/x) $] 令 $u=display(x/(x^2+1))$.已知 $x->+oo$ 时,$u->0$. $ & lim_(x->+oo) (2 e^(x/(x^2+1)) - 1)^((x^2+1)/x) = lim_(u->0) (2 e^u - 1)^(1/u) = lim_(u->0) e^(1/u ln(2 e^u - 1)) = lim_(u->0) e^((2(e^u - 1))/u) = e^2 $ = P72 第一章综合题 2 #prob[若 $display(lim_(n->oo) (n^a)/(n^b-(n-1)^b) = 1995)$,求常数 $a,b$.] $ lim_(n->oo) (n^a)/(n^b-(n-1)^b) = 1995 ==> lim_(n->oo) (n^b-(n-1)^b)/(n^a) = 1/1995 ==> lim_(n->oo) (b n^(b-1) + o(n^(b-1)))/n^a = 1/1995 $ 可以得到 $b=display(1/1995)$,$a = b+1 = display(1996/1995)$. = P72 第一章综合题 3(2) #prob[求极限:$ lim_(x->0)((a_1^x+a_2^x+dots.c+a_n^x)/n)^(1/x) quad (a_1,a_2,dots.c,a_n"均为正数") $] $ & lim_(x->0)((a_1^x+a_2^x+dots.c+a_n^x)/n)^(1/x) = lim_(x->0)exp(1/x ln((a_1^x + a_2^x + dots.c + a_n^x)/n))\ =& lim_(x->0)exp(1/x ((a_1^x + a_2^x + dots.c + a_n^x)/n-1))\ =& lim_(x->0)exp(1/x (((a_1^x-1) + (a_2^x-1) + dots.c + (a_n^x-1))/n))\ =& lim_(x->0)exp(1/x ((ln(a_1^x) + ln(a_2^x) + dots.c + ln(a_n^x))/n))\ =& lim_(x->0)exp(1/x ((x ln(a_1) + x ln(a_2) + dots.c + x ln(a_n))/n))\ =& exp((ln(a_1) + ln(a_2) + dots.c + ln(a_n))/n)\ =& root(n,a_1a_2 dots.c a_n) $ = P72 第一章综合题 3(3) #prob[求极限:$ lim_(x->0)((a^(x+1)+b^(x+1)+c^(x+1))/(a+b+c))^(1/x) quad (a>0,b>0,c>0) $] $ & lim_(x->0)((a^(x+1)+b^(x+1)+c^(x+1))/(a+b+c))^(1/x) = lim_(x->0)exp(1/x ln((a^(x+1)+b^(x+1)+c^(x+1))/(a+b+c)))\ =& lim_(x->0)exp(1/x (((a^(x+1)-a)+(b^(x+1)-b)+(c^(x+1)-c))/(a+b+c)))\ =& lim_(x->0)exp(1/x ((a(a^(x)-1)+b(b^(x)-1)+c(c^(x)-1))/(a+b+c)))\ =& lim_(x->0)exp(1/x ((a x ln(a)+b x ln(b)+c x ln(c))/(a+b+c)))\ =& exp((a ln(a)+b ln(b)+c ln(c))/(a+b+c))\ =& root(a+b+c,a^a b^b c^c)\ $ = P73 第一章综合题 10 #prob[证明方程 $display(a_1/(x-b_1)+a_2/(x-b_2)+a_3/(x-b_3)=0)$(其中 $a_1,a_2,a_3>0$ 且 $b_1<b_2<b_3$)在 $(b_1,b_2)$,$(b_2,b_3)$ 内各有一个根.] 设 $f(x) = display(a_1/(x-b_1)+a_2/(x-b_2)+a_3/(x-b_3))$,已知 $ lim_(x->b_1^+) f(x) = (lim_(x->b_1^+)a_1/(x-b_1)) + a_2/(x-b_2) + a_3/(x-b_3) = +oo $ 同理可得:$f(b_2^-) = -oo,sp f(b_2^+) = +oo,sp f(b_3^-)=-oo$. 注意到 $display(a/(x-b)) sp (a>0)$ 在 $(-oo,b)$ 和 $(b,+oo)$ 上分别单调递减且连续,可以得到 $f(x)$ 在 $(b_1,b_2)$ 和 $(b_2,b_3)$ 上分别单调递减且连续. 根据零点定理可知在 $(b_1,b_2)$ 和 $(b_2,b_3)$ 中分别恰一个点使得 $f(x)=0$,即原方程在 $(b_1,b_2)$ 和 $(b_2,b_3)$ 上各有一根. = P73 第一章综合题 11(2) #prob[若 $f(x)$ 在 $[a,b]$ 上连续,$a<c<d<b$,证明:存在一个 $xi in (a,b)$,使得 $ m f(c) + n f(d) = (m+n) f(xi) $其中 $m,n$ 为正数.] 先证明:当 $x<=y$ 时,有 $display((m x + n y)/(m+n)) in [x,y]$. $ x <= (m x+n y)/(m+n) <= y <== m y + n y <= m x + n y <= m x + n x <== n x < n y and m x < m y $ 已知 $display(f(xi) = (m f(c) + n f(d))/(m+n))$.根据介值定理,一定存在至少一个 $xi$ 使得 $min{f(c),f(d)}$ $<$ $f(xi)$ $<$ $max{f(c),f(d)}$.即原命题得证. = P73 第一章综合题 16 #prob[试确定常数 $k,c$,使得当 $x->+oo$ 时,$arcsin(sqrt(x^2+sqrt(x))-x) sim display(c/(x^k))$.] 即要求 $ lim_(x->+oo) arcsin(sqrt(x^2+sqrt(x))-x) / (c/(x^k)) = 1 $ 当 $x->+oo$ 时,$sqrt(x^2+sqrt(x))-x -> 0$.所以 $ arrow.double.l& lim_(x->+oo) arcsin(sqrt(x^2+sqrt(x))-x) / (c/(x^k)) = lim_(x->+oo) (x^k (sqrt(x^2+sqrt(x))-x)) / c \ =& lim_(x->+oo) (x^k (x^2+sqrt(x)-x^2)) / c(sqrt(x^2+sqrt(x))+x) = lim_(x->+oo) x^(k+1/2)/c(sqrt(x^2+sqrt(x))+x)=1 $ 由于极限存在,故应有 $k=1/2$.可以得到 $ c=lim_(x->+oo) x/(sqrt(x^2+sqrt(x))+x) = 1/2 $ = P73 第一章综合题 17 #prob[设 $f(x) = display(frac(sqrt(1+sin x+sin^2 x)-(alpha + beta sin x),sin^2 x))$,且点 $x=0$ 是 $f(x)$ 的可去间断点,试求常数 $alpha,beta$.] $ lim_(x->0)f(x) &= lim_(x->0) frac(sqrt(1+sin x+sin^2 x)-(alpha + beta sin x),sin^2 x)\ &= lim_(x->0) (1+sin x+sin^2 x-(alpha+beta sin x)^2)/(sin^2 x (sqrt(1+sin x+sin^2 x)+(alpha + beta sin x)))\ $ 由于极限存在,应有 $1+sin x+sin^2 x-(alpha+beta sin x)^2$ 与 $sin^2 x$ 同阶.所以, $ cases( alpha^2 = 1, 2alpha beta = 1 ) $ 解得 $alpha = 1,sp beta = 1/2$.代入验证 $f(x)$ 在 $x=0$ 处的左右极限相同,故此时 $x=0$ 确实为 $f(x)$ 的可去间断点. = P98 习题2-1 7(3) #prob[按定义求函数 $f(x)$ 在 $x=1$ 处的导数:$ f(x)=cases( 3x^2\,quad& x<=1, 2x^3+1\,quad& x>1, ) $] $ lim_(x->1^+) frac(f(x)-f(1),x-1) = lim_(Dx->0^+) frac(2(1+Dx)^3-2 times 1^3,Dx) = lim_(Dx->0^+) frac(2 Dx^3+ 6 Dx^2 + 6 Dx,Dx) = 6\ lim_(x->1^-) frac(f(x)-f(1),x-1) = lim_(Dx->0^+) frac(3(1+Dx)^2-3 times 1^2,Dx) = lim_(Dx->0^+) frac(3 Dx^2 + 6 Dx, Dx) = 6 $ 所以 $display(lim_(x->1^+) frac(f(x)-f(1),x-1) = lim_(x->1^-) frac(f(x)-f(1),x-1) = 6 ==> lim_(x->1) frac(f(x)-f(1),x-1) = 6 ==> f'(1) = 6)$. = P98 习题2-1 7(4) #prob[按定义求函数 $f(x)$ 在 $x=0$ 处的导数:$ f(x) = cases( x^2 sin display(1/x)\,quad& x!=0, 0\,quad& x=0 ) $] $ f'(0) = lim_(x->0) frac(f(x)-f(0),x-0) = lim_(x->0) frac(f(x),x) = lim_(x->0) frac(x^2 sin (1/x), x) = lim_(x->0) frac(sin (1/x), 1/x) $ 当 $x->0$ 时,$1/x -> oo$.由于 $sin(1/x)$ 有界,所以 $display(lim_(x->0) frac(sin (1/x), 1/x)) = 0$.故 $f'(0) = 0$. = P98 习题2-1 10 #prob[设 $f(x) = x+(x-1)arcsin sqrt(display(x/(x+1)))$,求 $f'(1)$.] $ f'(x) = 1 + arcsin sqrt(x/(x+1)) + (x-1)/sqrt(1-x/(x+1)) dot 1/(2sqrt(x/(x+1))) dot ((x+1)-x)/((x+1)^2)\ f'(1) = 1 + arcsin sqrt(2)/2 = 1+pi/4 $
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/columns_08.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test columns in an infinitely high frame. #set page(width: 7.05cm, columns: 2) There can be as much content as you want in the left column and the document will grow with it. #rect(fill: conifer, width: 100%, height: 30pt) Only an explicit #colbreak() `#colbreak()` can put content in the second column.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/km/0.1.0/README.md
markdown
Apache License 2.0
# `km` Draw simple Karnaugh maps. Use with: ```typ #import "@preview/km:0.1.0": karnaugh #karnaugh(("C", "AB"), implicants: ( (0, 1, 1, 2), (1, 2, 2, 1), ), ( (0, 1, 0, 0), (0, 1, 1, 1), ) ) ``` Samples are available in [`sample.pdf`](https://github.com/typst/packages/blob/main/packages/preview/km/0.1.0/sample.pdf).
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/src/package/dining-table.typ
typst
The Unlicense
#import "@preview/dining-table:0.1.0": *
https://github.com/Sckathach/hackademint-presentations
https://raw.githubusercontent.com/Sckathach/hackademint-presentations/main/Introduction_to_Prompt_Hacking/main.typ
typst
Apache License 2.0
#import "@preview/polylux:0.3.1": * #import themes.simple: * #set text(font: "Inria Sans") #show: simple-theme.with( footer: [<NAME>], ) #title-slide[ = Introduction to Prompt Hacking #v(2em) Le magicien quantique #footnote[Aka Sckathach, Caml Master, Fan2Thermo] <f1> #h(1em) \ 1 Nov 2023 ] #slide[ #figure( image("ressources/stickman-creatingbomb.png", height: 78%) ) ] #slide[ #v(3em) #figure( image("ressources/not-assist.png", width: 70%) ) ] #slide[ #v(2em) #figure( image("ressources/unauthorized.png", width: 70%) ) ] #focus-slide[ _Time to hack a prompt!_ ] #slide[ == Naive approach: fiction #figure( image("ressources/theater.png", width: 70%) ) ] #slide[ == Try _everything_ #figure( image("ressources/dev-mode.png", width: 70%) ) ] #centered-slide[ = How is it protected? ] #slide[ == Preprompt #figure( image("ressources/preprompt.png", height: 78%) ) ] #slide[ == Sandwich #figure( image("ressources/sandwich.png", height: 78%) ) ] #slide[ == Counter-sandwich #figure( image("ressources/counter-sandwich.png", height: 78%) ) ] #slide[ == Random sandwich #figure( image("ressources/random-sandwich.png", height: 78%) ) ] #centered-slide[ = So it is protected? ] #centered-slide[ = No. ] #slide[ == The DAN prompt #figure( image("ressources/dan.png", height: 78%) ) ] // #slide[ // == Attack on text // #figure( // grid( // columns: (auto, auto), // rows: (auto, auto), // gutter: 1em, // [ #image("ressources/fig3.png", width: 66%) ], // [ #align(horizon)[#image("ressources/labels_text.png", height: 50%)] ], // ) // ) // ] #centered-slide[ = Try it! #v(2em) == Practice Lab == Gandalf on Lakera.ai == Hack a prompt competitions ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/lint/markup_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Warning: 1-3 no text within stars // Hint: 1-3 using multiple consecutive stars (e.g. **) has no additional effect **
https://github.com/Leo1003/resume
https://raw.githubusercontent.com/Leo1003/resume/main/resume.typ
typst
#import "template.typ": * #import "secrets.typ": secret #show: resume.with( author: ( firstname: "Shao-Fu", lastname: "Chen", chinesename: "陳少甫", email: "<EMAIL>", phone: secret("phone"), github: "Leo1003", linkedin: "少甫-陳-3b0b3a20a", positions: ( "System Team Leader in NYCU CSIT", ) ), ) #let sidebar_content = [ #resume_section("Education") #education_item[ National Yang Ming Chiao Tung University ][ Institute of Computer Science and Engineering ][ Master of Science ][ Aug. 2022 - Estimate 2024 ] #education_item[ National Yang Ming Chiao Tung University ][ Department of Computer Science ][ Bachelor of Science ][ Aug. 2018 - Jul. 2022 ] #resume_section("Skills") #skill_item( "Programming Language", ( strong[Rust], strong[C], strong[Bash], "C++", "C#", "Python", "Javascript", "Jsonnet", ) ) #skill_item_list( "Technologies", ( strong[Kubernetes], strong[Linux], strong[Git], strong[Ansible], "OpenSearch", "Flux CD", "Dockerfile", "GitLab CI", "GitHub Actions", "Prometheus", "Prometheus Operator", "Thanos", ) ) #skill_item_list( "Concepts", ( strong[High Availability], strong[Object-Oriented Programming], strong[Container], "Operating System", "Infrastructure as Code", "DevOps", "Monitoring", "Public Key Infrastructure", ) ) #skill_item_list( "Languages", ( "Mandarin: Native", "English: Advanced", ) ) ] #let main_content = [ #resume_section("Experience") #work_experience_item_header( "Information Technology Center", "Department of CS, NYCU", "Infrastructure Engineer (Part-time)", "May. 2020 - Estimate 2024", ) #resume_item[ - #strong[In charge of the system team leader.] - #strong[Build logs management system with OpenSearch, Vector, and Fluent Bit.] Write Ansible playbook to automate the deploy process, and to automatically rolling upgrade the cluster to prevent downtime. - #strong[Construct metrics monitoring system with Prometheus, Thanos, and Grafana.] In order to monitor multiple Kubernetes cluster, introducing Thanos to provide the ability to query across different cluster and long term metric storage. - #strong[Redesign Kubernetes IaC with Flux CD and Ansible.] Redesign the deploy process and introduce Flux CD to achieve intuitive GitOps process, which makes us to easily manage multiple Kubernetes cluster instances. - Design IaC for monitoring mixins with Jsonnet and Flux CD OCI artifacts. - Manage high availability OpenLDAP cluster. - Write Ansible playbook to do CI/CD for complex Nginx configuration files. ] #resume_section("Personal Project") #personal_project_item_header( "genetlink", "", "Contributor", "Sep. 2021", project_link: github_project_link("rust-netlink/genetlink"), ) #resume_item[ - Contribute the whole genetlink protocol implementation to the rust-netlink project. - Along with another 2 crates: `netlink-packet-generic`, `netlink-packet-wireguard`, which enable Rust program to operate WireGuard tunnel without the need to depend on C library. ] #personal_project_item_header( "rust-osshkeys", "", "Maintainer", "Feb. 2020", project_link: github_project_link("Leo1003/rust-osshkeys"), ) #resume_item[ - Build a Rust library for accessing OpenSSH key in different formats. Makes it possible to use, convert OpenSSH keys easily with Rust programs. ] #personal_project_item_header( "cjail", "", "Maintainer", "Feb. 2018", project_link: github_project_link("Leo1003/cjail"), ) #resume_item[ - A container jail to run process in an isolated environment. Learned a lot while working on this project, including Linux namespace, cgroup, rlimits, signals, etc. ] ] #grid( columns: (1fr, 2fr), column-gutter: 1em, sidebar_content, main_content, )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/construct-04.typ
typst
Other
// Error: 5-7 missing argument: red component #rgb()
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Layout without any container should provide the page's dimensions, minus its margins. #page(width: 100pt, height: 100pt, { layout(size => [This page has a width of #size.width and height of #size.height ]) h(1em) place(left, rect(width: 80pt, stroke: blue)) })
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cartao/0.1.0/README.md
markdown
Apache License 2.0
# cartao Dead simple flashcards with Typst. ## Example usage: ```typ #import "@preview/cartao:0.1.0": card, letter8up, a48up #set page( paper: "a4", // paper: "us-letter", // paper: "presentation-16-9", margin: (x: 0cm, y: 0cm), ) // build the cards #a48up // #letter8up // #present // define your cards #card( [Header], [Footer], [Question?], [answer] ) #card( [portuguese], [Hint: Its the title of this package!], [card], [cartão] ) #card( [french], [Hint: close to the portuguese], [card], [carte] ) ``` ## Documentation ### `card` Defines a card by updating the below `counter` and `state`(s), and dropping a <card> label. ```typ #let card(header, footer, question, answer) = [ #cardnumber.step() #cardheader.update(header) #cardfooter.update(footer) #cardquestion.update(question) #cardanswer.update(answer) <card> ] ``` #### Arguments * `header` * `footer` * `question` * `answer` ### card builders **How they work** 1. Find all locations of the `<card>` label 2. Get the values of the `cardnumber` counter, and `cardheader`, `cardfooter`, `cardquestion`, `cardanswer` states at each `<card>`. 3. Populates an array of questions and an array of answers using these values - The `#a48up` and `#letter8up` functions describe the layout of each card for each item in these arrays, and also rearrange the answers so that the layout makes sense when printed double sided. 4. Loop over the arrays and dump each item's `content` onto the page. - in the case of `#a48up` and `letter8up`, each item is dumped into a 2-column table. `cartao` comes builtin with the following card building functions. Take a look at the source for how they work, and use them as a guide to help you build your own flashcards with different sizes/formats. ### `a48up` Produces a 2x8 portrait card layout on a4 paper. Designed to be printed double-sided on the perforated 8-up a4 card paper you can find on [Amazon](https://www.amazon.ca/s?k=a4+perforated+card&crid=37RT2L4H5XSD0&sprefix=a4+perforated+ca%2Caps%2C648&ref=nb_sb_noss) ###### Usage ```typ #a48up ``` ### `letter8up` Produces a 2x8 portrait card layout on us-letter paper. ###### Usage ```typ #letter8up ``` ### `present` A 16:9 presentation of the flashcards with questions and answers on different slides ###### Usage ```typ #present ```
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/practice/clone.typ
typst
#import "@preview/touying:0.5.2": * #import themes.university: * #import "@preview/numbly:0.1.0": numbly #import "@preview/fletcher:0.5.1" as fletcher: node, edge #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) #import "../components/gh-button.typ": gh_button #import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch #grid(columns: 2, column-gutter: 10%, image("/slides/img/meme/git-clone.png"), [In case the project already exists simply: move to the folder and clone the repository: `git clone <url-repository>`. This way we would have a copy of the remote repository on our machine.] )
https://github.com/loqusion/typix
https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/build-typst-project-local.md
markdown
MIT License
# buildTypstProjectLocal Returns a derivation for compiling a Typst project and copying the output to the current directory. This is essentially a script which wraps [`buildTypstProject`](build-typst-project.md). <div class="warning"> Using this derivation requires [`allow-import-from-derivation`](https://nixos.org/manual/nix/stable/command-ref/conf-file#conf-allow-import-from-derivation) to be `true` (which is the default at the time of writing). More info: <https://nixos.org/manual/nix/stable/language/import-from-derivation> </div> <div class="warning"> Invoking the script produced by this derivation directly is currently unsupported. Instead, use `nix run`. See [this issue](https://github.com/loqusion/typix/issues/2) for more information. </div> ## Parameters All parameters accepted by [`buildTypstProject`](build-typst-project.md#parameters) are also accepted by `buildTypstProjectLocal`. They are repeated below for convenience. ### `src` {{#include common/src.md}} ### `fontPaths` (optional) { #fontpaths } {{#include common/font-paths.md}} #### Example { #fontpaths-example } {{#include common/font-paths-example.md:buildtypstprojectlocal_example}} ### `installPhaseCommand` (optional) { #installphasecommand } {{#include common/install-phase-command.md}} ### `scriptName` (optional) { #scriptname } {{#include common/script-name.md}} Default is `typst-build`. ### `typstCompileCommand` (optional) { #typstcompilecommand } {{#include common/typst-compile-command.md}} Default is `typst compile`. ### `typstOpts` (optional) { #typstopts } {{#include common/typst-opts.md:head}} <!-- markdownlint-disable link-fragments --> These are in addition to any options you manually pass in [`typstCompileCommand`](#typstcompilecommand). <!-- markdownlint-restore --> {{#include common/typst-opts.md:tail}} #### Example { #typstopts-example } {{#include common/typst-opts-example.md:head}} {{#include common/typst-opts-example.md:typstcompile}} ### `typstOutput` (optional) { #typstoutput } {{#include common/typst-project-output.md:head}} {{#include common/typst-project-output.md:buildtypstprojectlocal}} ### `typstSource` (optional) { #typstsource } {{#include common/typst-project-source.md}} Default is `main.typ`. ### `virtualPaths` (optional) { #virtualpaths } {{#include common/virtual-paths.md}} #### Example { #virtualpaths-example } {{#include common/virtual-paths-example.md:head}} {{#include common/virtual-paths-example.md:buildtypstprojectlocal_example}} {{#include common/virtual-paths-example.md:tail}} ## Source - [`buildTypstProjectLocal`](https://github.com/loqusion/typix/blob/main/lib/buildTypstProjectLocal.nix)
https://github.com/davawen/Cours
https://raw.githubusercontent.com/davawen/Cours/main/Physique/Electricité/dipole.typ
typst
#import "@local/physique:0.1.0": * #import elec: * #show: doc => template(doc) #titleb[Dipôle linéaires] = Notion de pôle électromagnétique == Definition d'un dipôle Un dipôle est un élément de circuit possédant deux bornes. == Caractéristique d'un dipôle Il y a deux caractéristique d'un dipôle: la tension et l'intensité. #figcan({ serie((0, 0), i: $i$, left: "A", right: "B", apply(resistor, u: tenserl($u$)) ) }) On peut grapher l'intensité en fonction de la tension, ou la tension en fonction de l'intensité. On appelle ce graphe la *caractéristique* d'un dipôle. #warn[ Certains dipôles ne sont pas symmétriques. Les bornes $A$ et $B$ ne répondront pas de la même manière aux changements d'intensite et de tension. Exemple: la diode. ] == Dipôles actifs ou passifs #def[Dipôle actif]: Un dipôle dont la caractéristique ne passe pas par l'origine \ #def[Dipôle passif]: Un dipôle dont la caractéristique passe par l'origine. #figure(caption: [Dipôle passif et actif], grid(columns: (1fr, 1fr), image("dipole-passif.png"), image("dipole-actif.png") )) == Dipôle linéaire ou non-linéaire #def[Dipôle linéaire]: Dipôle dont la caractéristique est une droite. \ #def[Dipôle non-linéaire]: Dipôle dont la caractéristique n'est pas droite. #figure(caption: [Dipôle linéaire et non-linéaire], image("dipole-lineaire-non-lineaire.png", width: 80%)) Deux dipôles connus qui ne rentrent pas dans cette catégorie sont les condensateurs et les bobines. En statique, il n'existe pas de caractéristique de ces éléments. Tant qu'on ne s'intéresse qu'à des dérivées ou à des intégrales (comme pour les condensateurs ou les bobines), les opérations resterons linéaires ($(f + g)' = f' + g'$, $integral (f + g) = integral f + integral g$). On considéra donc les condensateurs et les bobines comme des dipôles linéaires. Dès lors qu'on fera des produits/quotients d'intensité, de fonctions ou de dérivés, on sortira du cadre des dipôles linéaire. Par la suite, on ne considérera que des dipôles linéaires. == Générateurs - Récepteurs $!=$ Actif - Passif Un dipôle générateur est un dipôle où la *puissance fournie* est plus grande *puissance reçue*. Un dipôle récepteur est un dipôle où la *puissance reçue* est plus grande *puissance fournie*. Il n'y a aucun lien formel avec *actif* et *passif* (même si les dipôles actifs auront souvent des allures de générateurs). == Limites de fonctionnement Les dipôles possèdent une puissance maximale de fonctionnement, $P_max$. Au-delà de cette puissance, il est probable qu'ils grillent. #figure(image("puissance-max.png", width: 50%)) = Association de dipôles == En série On met des élément les uns après les autre: #figcan({ serie((0, 0), i: $i$, u: tenserl($u$), apply(resistor, u: tenserl($u_1$)), apply(resistor, u: tenserl($u_2$)), apply(resistor, u: tenserl($u_3$)), apply(resistor, u: tenserl($u_4$)), ) }) En série, l'intensité reste la même et les tensions s'additionnent: $ u = sum_k u_k $ Pour vérifier qu'un circuit est en série, on suit le chemin des électrons. Si on rencontre un (vrai!) nœud, on n'est pas en série. == En parallèle On met des éléments en parallèles les un aux autres: #figcan({ derivation((0, 0), i: $i$, u: tenserl($u$), apply(resistor), apply(resistor), apply(resistor), apply(resistor), ) }) En parallèle, la tension reste la même et les intensités s'additionnent: $ i = sum_k i_k $ == Point de fonctionnement On essaye de comprendre comment un circuit fonctionne dans sa globalité. #def[Point de fonctionnement]: Intersection des caractéristiques d'un circuit. C'est le point qui correspond au fonctionnement "normal" de l'association. #image("fonctionnement.png", width: 50%) Ici, on a deux droites, on peut le résoudre analytiquement. = Dipôles linéaires passifs == Résistor de résistance $R$ Il faut faire la distinction entre le composant (résistor) et sa caractéristique (résistance). Bon, on appelle tout une résistance. #note[Un résistor peut quand-même avoir des comportements un peu chelou qui ne peuvent pas être modélisés par la caractéristique résistance] Schéma: #figcan(resistor((0, 0))) En convention récepteur, la caractéristique du résistor est une droite et obéit à $u = R dot i$. Attention, en convention générateur, le signe est inversé, on a $u = -R dot i$ === Association en série #figcan({ resistor((-2, 0), name: "d1", label: $R_1$) resistor((0, 0), name: "d2", label: $R_2$) resistor((2, 0), name: "d3", label: $R_3$) tension("d3.r", "d1.l", (0, 1), tenselr($u$), size: 1) fil((-3, 0), "d1.l", "d1.r", "d2.l", "d2.r", "d3.l", "d3.r", (3, 0), i: $i$) }) On a: $ u &= u_1 + u_2 + u_3 \ &= R_1 i + R_2 i + R_3 i \ &= i(R_1 + R_2 + R_3) $ Donc une association en série de résistances est équivalente à une grosse résistance: #figcan({ resistor((0, 0), name: "D", size: 1, label: $R_"eq"$) fil((-3, 0), "D.l", "D.r", (3, 0), i: $i$) }) Avec: $ R_"eq" = sum_k R_k $ === Association en parallèle #figcan({ resistor((0, 2), name: "d2") resistor((0, 1), name: "d3") resistor((0, 0), name: "d4") node((-2, 1), name: "A") node((2, 1), name: "B") tension("d2.r", "d2.l", (0, 0.7), tenselr($u$), size: 1.2) fil(rev: 1, "A", "d2.l", "A", "d3.l", "A", "d4.l") fil("d2.r", "B", "d3.r", "B", "d4.r", "B") fil((-3, 1), "A", i: $i$) fil("B", (3, 1), i: $i$) }) On a: $ i &= i_1 + i_2 + i_3 \ &= u_1/R_1 + u_2/R_2 + u_3/R_3 \ &= underbrace((1/R_1 + 1/R_2 + 1/R_3), "1/R_eq") u $ #caution[On fait très attention à l'homogénéité. On ne peut pas juste poser $R = 1/R_1 + 1/R_2 + 1/R_3$, car les unités ne fonctionnent pas.] On pose $G$ la conductance avec $G = 1/R$. Ici, on a: $ G_"eq" = sum_k G_k $ Donc: $ R_"eq" = 1/G_"eq" $ === Puissance On a: $ cal(P)_"reçue" = u dot i $ Et: $ u = R dot i $ Donc: $ cal(P)_"reçue" = R i^2 = u^2/R $ Donc $cal(P)_"reçue" > 0$ en convention récepteur. == Bobine d'inductance $L$ #figcan({ bobine((0, 0), u: tenserl($u$)) }) On a la relation: $ u = L (dif i)/(dif t) $ La bobine est un fil enroulé autour d'un truc. Le fil possède très probablement une résistance. La majorité du temps, on représentera une bobine par une inductance ET une résistance. On ne peut pas exclure un comportement de type condensateur dans une bobine. === Association en série Plusieurs bobines: #figcan({}) $ u &= u_1 + u_2 + u_3 \ &= L_1 (dif i)/(dif t) + L_2 (dif i)/(dif t) + L_3 (dif i)/(dif t) \ &= (L_1 + L_2 + L_3) (dif i)/(dif t) $ Les inductances s'ajoutent en série. $ L = sum_k L_k $ === Association en parallèle #figcan({ derivation((0, 0), apply(bobine), apply(bobine) ) }) $ i = i_1 + i_2 \ <=> (dif i)/(dif t) = (dif i_1)/(dif t) + (dif i_2)/(dif t) \ (dif i)/(dif t) = u/L_1 + u/L_2 \ = underbrace((1/L_1 + 1/L_2), "1/L_eq")u $ L'inverse des inductances s'ajoutent en parallèle: $ 1/L_"eq" = sum_k 1/L_k $ === Puissance On a: $ cal(P)_"reçue"(t) = i(t) u(t) $ Or, $ u(t) = L (dif i)/(dif t) $ D'où: $ cal(P)_"reçue"(t) = i(t) L (dif i(t))/(dif t) \ = L i(t) (dif i(t))/(dif t) \ = (dif)/(dif t)(1/2 L dot i^2(t)) $ Or, on a aussi que la puissance est l'énergie au cours du temps: $E = cal(P) dot T$ pour une puissance constante, et pour une puissance variable: $ E(t) = integral_0^t cal(P)(x)dif x \ = integral_0^t (dif)/(dif x) (1/2 L dot i^2(x)) dif x \ = 1/2 L dot i^2 (t) $ Intuition: si l'intensité augmente, la bobine est réceptrice. Si l'intensité diminue, la bobine est génératrice. Elle lisse les changement d'intensité dans le circuit. On a l'inductance définie en Henry, $H = V dot A^-1 dot s$ == Condensateur de capacité $C$ Schéma: #figcan({ draw.scale(1) condensateur((0, 0), u: tenserl($u$), name: "c") fil((-1, 0), "c.l", "c.r", (1, 0), i: $i$) draw.content((-0.4, -0.6), $q$) draw.content((0.3, -0.6), $-q$) }) Un condensateur est composé de deux plaques conductrices séparée par un matériau di-électrique (isolant). En tirant de la charge d'un coté du condensateur, elle est accumulée de l'autre coté. On a: $ q = C dot u $ Avec $q$ la charge du condensateur, $C$ la capacité en farads ($F$) et $u$ la tension aux bornes. (Donc: $u = q/C$) Pour connaître l'intensité d'un capaciteur, on repart de la définition de l'intensité: $ i = (dif q)/(dif t) = dif / (dif t) (C dot u) = C (dif u)/(dif t) $ === Association en série: #figcan({ }) On a: $ u = u_1 + u_2 \ (dif u)/(dif t) = (dif u_1)/(dif t) + (dif u_2)/(dif t) \ = i/C_1 + i/C_2 \ = (1 / C_1 + 1/C_2)i $ En série, la somme des capacité s'additionnent === Association en parallèle: #figcan({ derivation((0, 0), inset: 1.4, i: $i$, apply(condensateur), apply(condensateur), apply(condensateur), ) }) $ i = i_1 + i_2 + i_3 \ = C_1 (dif u)/(dif t) + C_2 (dif u)/(dif t) + C_3 (dif u)/(dif t) \ = (C_1 + C_2 + C_3)(dif u)/(dif t) $ En parallèle, les capacité s'ajoutent: $ C_"eq" = sum_k C_k $ #caution[Les règles d'ajout des tensions/intensités sont inversées entre les capaciteurs et les autres dipôle] === Puissance On a: $ cal(P)_"reçue"(t) = i(t) u(t) \ cal(P)_"reçue"(t) = u(t) C (dif u)/(dif t) \ cal(P)_"reçue"(t) = (dif)/(dif t)(1/2 C dot u(t)^2) $ D'où: $ E_c (t) = 1/2 C dot u(t)^2 $ Si l'énergie augmente, on la stocke, et on peut la restituer. = Dipoles linéaires actifs == Source idéale de tension Rappel: les dipoles linéaires actifs ont une caractéristique qui ne passe pas par l'origine. Situation la plus simple: la caractéristique est une droite. Si cette droite est horizontale, la tension aux bornes du dipôle sera toujours la même. On nomme $E$ cette tension. On appelle ce genre de dipôle une *source idéale de tension*, de symbole: #figcan({ source-ideale((0, 0), name: "s", label: tenselr($E$), u: tenserl($u$)) fil((-1, 0), "s.l", "s.r", (1, 0), i: $i$) }) On se place le plus souvent en convention générateur, mais on peut ne peut le faire: #caution[Faire attention au signe!!] == Hors programme: source idéale de courant On nomme une source idéale de courant une source d'on l'intensité est la même peut-importe la tension. Sa caractéristique (avec l'intensité en abscisse) est une droite verticale. On nomme $I_0$ son intensité. #figcan({ source-ideale-courant((0, 0), name: "s", u: tenserl($u$)) fil((-1, 0), "s.l", "s.r", (1, 0), i: $I_0$) }) Il existe une combinaison des deux, avec une caractéristique "carré" (de tension constante jusqu'a une certaine intensité, à partir de laquelle l'intensité devient constante). == Source réelle = modèle de Thévenin La caractéristique d'une source réelle est une droite qui n'est pas horizontale, pas verticale, et qui ne passe pas par l'origine. Cette droite a donc une pente, notée $-R$, elle intersecte l'axe des ordonnées en $E$, la tension quand l'intensité est nulle, et elle intersecte l'axe des abscisses en $I_0$, l'intensité quand la tension est nulle. On a donc: $ u = E - R dot i $ Par homogénéité, $E$ et $R dot i$ sont en Volts, donc on peut poser les tensions $u_1$ et $u_2$ avec: $ u = u_1 + u_2 $ Avec $u_1 = E$ et $u_2 = -R dot i$ On peut représenter un dipôle de tension constante $u_1$ par une source idéale de courant de tension $E$, et un dipôle de tension $-R dot i$ avec un résistor de résistance $R$ en convention générateur: #figcan({ //serie() source-ideale((0, 0), label: tenselr($E$), u: tenselr($u_1$), name: "s") resistor((2, 0), label: $R$, u: tenselr($u_2$), name: "r") fil((-1, 0), "s.l", "s.r", "r.l", "r.r", (4, 0), i: $i$) tension((-1, 0), (4, 0), (0, -1.3), tenselr($u$), size: 2) }) Le modèle de Thevenin est donc caractérisé par: - La tension à vide de force électromotrice $E$ - La résistance interne $R$ (D'où le fait qu'une source idéale de tension n'existe pas dans la vrai vie: pas de résistance nulle) === Modèle de Norton (hors programme) On refait la même chose avec une source idéale de courant: On a $I_0$ l'intensité quand la tension est nulle, et $E$ la tension quand l'intensite est nulle. Sa caractéristique (d'axe $u$) est une droite dont la pente est $-1/R$ On peut poser: $ R dot i &= E - u \ <=> i &= E/R - 1/R u $ Par homogénéité, $i = i_1 + i_2$ avec: - $i_1 = E/R = I_0$ (modélisable par une source idéale de courant d'intensité $I_0$) - $i_2 = -1/R$ (modélisable par un résistor de résistance $R$) On a: #figcan({ derivation((0, 0), inset: 2.5, i: $i$, apply(source-ideale-courant, label: tenselr($I_0 = E/R$)), apply(resistor, label: $R$) ) tension((-1, 0), (1, 0), (0, 0.001), tenselr($u$)) }) On peut caractériser le modèle de Norton par: - Le courant de court-circuit $I_0 = E/R$ - La résistance interne $R$ On peut basculer du modèle de Norton vers le modèle de thévenin (avec le terme $E/R$). #figcan({ let s = seriex((0, 0), name: "S")(resistor)(bobine, coils: 5)(ground, rot: 145deg) let s = s(node, name: "B", round: true)(turn: -90deg)(resistor)(resistor) let s = s(turn: -90deg)(bobine)(condensateur)(condensateur) let s = s(turn: -90deg)(resistor)(node, name: "A", round: true) s(close: ())() // let s = seriex("S.B")(resistor) // let s = s(turn: -90deg)(resistor)(resistor) // let s = s(turn: -90deg)(close: (2, 0)) // s() })
https://github.com/augustebaum/tenrose
https://raw.githubusercontent.com/augustebaum/tenrose/main/lib.typ
typst
MIT License
#import "internals.typ": render /// Renders a graph with Penrose. /// /// See `render`'s documentation in `internals.typ` for a list of valid /// arguments and their descriptions. #let raw-render( /// A `raw` element containing Dot code. raw, ..args, ) = { assert(raw.has("text"), message: "`raw-render` expects a `raw` element") return render(raw.text, ..args) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1DC0.typ
typst
Apache License 2.0
#let data = ( ("COMBINING DOTTED GRAVE ACCENT", "Mn", 230), ("COMBINING DOTTED ACUTE ACCENT", "Mn", 230), ("COMBINING SNAKE BELOW", "Mn", 220), ("COMBINING SUSPENSION MARK", "Mn", 230), ("COMBINING MACRON-ACUTE", "Mn", 230), ("COMBINING GRAVE-MACRON", "Mn", 230), ("COMBINING MACRON-GRAVE", "Mn", 230), ("COMBINING ACUTE-MACRON", "Mn", 230), ("COMBINING GRAVE-ACUTE-GRAVE", "Mn", 230), ("COMBINING ACUTE-GRAVE-ACUTE", "Mn", 230), ("COMBINING LATIN SMALL LETTER R BELOW", "Mn", 220), ("COMBINING BREVE-MACRON", "Mn", 230), ("COMBINING MACRON-BREVE", "Mn", 230), ("COMBINING DOUBLE CIRCUMFLEX ABOVE", "Mn", 234), ("COMBINING OGONEK ABOVE", "Mn", 214), ("COMBINING ZIGZAG BELOW", "Mn", 220), ("COMBINING IS BELOW", "Mn", 202), ("COMBINING UR ABOVE", "Mn", 230), ("COMBINING US ABOVE", "Mn", 230), ("COMBINING LATIN SMALL LETTER FLATTENED OPEN A ABOVE", "Mn", 230), ("COMBINING LATIN SMALL LETTER AE", "Mn", 230), ("COMBINING LATIN SMALL LETTER AO", "Mn", 230), ("COMBINING LATIN SMALL LETTER AV", "Mn", 230), ("COMBINING LATIN SMALL LETTER C CEDILLA", "Mn", 230), ("COMBINING LATIN SMALL LETTER INSULAR D", "Mn", 230), ("COMBINING LATIN SMALL LETTER ETH", "Mn", 230), ("COMBINING LATIN SMALL LETTER G", "Mn", 230), ("COMBINING LATIN LETTER SMALL CAPITAL G", "Mn", 230), ("COMBINING LATIN SMALL LETTER K", "Mn", 230), ("COMBINING LATIN SMALL LETTER L", "Mn", 230), ("COMBINING LATIN LETTER SMALL CAPITAL L", "Mn", 230), ("COMBINING LATIN LETTER SMALL CAPITAL M", "Mn", 230), ("COMBINING LATIN SMALL LETTER N", "Mn", 230), ("COMBINING LATIN LETTER SMALL CAPITAL N", "Mn", 230), ("COMBINING LATIN LETTER SMALL CAPITAL R", "Mn", 230), ("COMBINING LATIN SMALL LETTER R ROTUNDA", "Mn", 230), ("COMBINING LATIN SMALL LETTER S", "Mn", 230), ("COMBINING LATIN SMALL LETTER LONG S", "Mn", 230), ("COMBINING LATIN SMALL LETTER Z", "Mn", 230), ("COMBINING LATIN SMALL LETTER ALPHA", "Mn", 230), ("COMBINING LATIN SMALL LETTER B", "Mn", 230), ("COMBINING LATIN SMALL LETTER BETA", "Mn", 230), ("COMBINING LATIN SMALL LETTER SCHWA", "Mn", 230), ("COMBINING LATIN SMALL LETTER F", "Mn", 230), ("COMBINING LATIN SMALL LETTER L WITH DOUBLE MIDDLE TILDE", "Mn", 230), ("COMBINING LATIN SMALL LETTER O WITH LIGHT CENTRALIZATION STROKE", "Mn", 230), ("COMBINING LATIN SMALL LETTER P", "Mn", 230), ("COMBINING LATIN SMALL LETTER ESH", "Mn", 230), ("COMBINING LATIN SMALL LETTER U WITH LIGHT CENTRALIZATION STROKE", "Mn", 230), ("COMBINING LATIN SMALL LETTER W", "Mn", 230), ("COMBINING LATIN SMALL LETTER A WITH DIAERESIS", "Mn", 230), ("COMBINING LATIN SMALL LETTER O WITH DIAERESIS", "Mn", 230), ("COMBINING LATIN SMALL LETTER U WITH DIAERESIS", "Mn", 230), ("COMBINING UP TACK ABOVE", "Mn", 230), ("COMBINING KAVYKA ABOVE RIGHT", "Mn", 232), ("COMBINING KAVYKA ABOVE LEFT", "Mn", 228), ("COMBINING DOT ABOVE LEFT", "Mn", 228), ("COMBINING WIDE INVERTED BRIDGE BELOW", "Mn", 220), ("COMBINING DOT BELOW LEFT", "Mn", 218), ("COMBINING DELETION MARK", "Mn", 230), ("COMBINING DOUBLE INVERTED BREVE BELOW", "Mn", 233), ("COMBINING ALMOST EQUAL TO BELOW", "Mn", 220), ("COMBINING LEFT ARROWHEAD ABOVE", "Mn", 230), ("COMBINING RIGHT ARROWHEAD AND DOWN ARROWHEAD BELOW", "Mn", 220), )
https://github.com/TimotheAlbouy/algol
https://raw.githubusercontent.com/TimotheAlbouy/algol/main/README.md
markdown
MIT License
# algol Typst package for writing algorithms
https://github.com/VadimYarovoy/Networks2
https://raw.githubusercontent.com/VadimYarovoy/Networks2/main/lab2/report/typ/task.typ
typst
#import "@preview/colorful-boxes:1.2.0": * = Практические задание == Задание 1 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ Попробуйте отправить письмо на вашу почту (mail, yandex, gmail, etc) используя команду openssl (узнаете в DNS имя почтового сервера, подключаетесь к нему по нужному порту итд) ] \ Подготавливаем данные для авторизации: ```bash echo -n '<EMAIL>' | openssl enc -base64 echo -n '<PASSWORD>' | openssl enc -base64 ``` Авторизуемся и отправляем письмо: ```bash 250 SMTPUTF8 AUTH LOGIN 334 VXNlcm5hbWU6 <mail_base_64> 334 UGFzc3dvcmQ6 <pass_base_64> 235 2.7.0 Accepted MAIL FROM: <<EMAIL>> 250 2.1.0 OK l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp rcpt to: <<EMAIL>> 250 2.1.5 OK l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp data 354 Go ahead l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp from: <EMAIL> to: <EMAIL> subject: Some cool mail This is a long stiry about ... . 250 2.0.0 OK 1708166862 l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp ``` Смотрим через gmail #figure( image("../pics/1.png", width: 100%), ) Разберем каждую часть. + *250 SMTPUTF8*: Это код ответа от сервера, который указывает, что сервер поддерживает расширение SMTPUTF8 для кодировки Unicode. + *AUTH LOGIN*: Это команда, которая инициирует процесс аутентификации. Когда вы видите эту команду, сервер ожидает от вас базовые данные для аутентификации. + *334 VXNlcm5hbWU6* и *334 UGFzc3dvcmQ6*: Это вызов для ввода имени пользователя (пользовательский адрес электронной почты) и пароля. Данные кодированы в формате Base64. Таким образом, вы должны ввести имя пользователя и пароль в закодированном виде. + *235 2.7.0 Accepted*: Это код ответа, который сообщает, что аутентификация прошла успешно, и сервер принимает команды. + *MAIL FROM:\<<EMAIL>>*: Эта команда указывает адрес отправителя. + *250 2.1.0 OK l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp*: Это подтверждение от сервера о том, что адрес отправителя принят. + *RCPT TO: \<<EMAIL>>*: Эта команда указывает адрес получателя. + *250 2.1.5 OK l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp*: Это подтверждение от сервера о том, что адрес получателя принят. + *DATA*: Эта команда сообщает серверу о начале передачи данных письма. + *354 Go ahead l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp*: Сервер готов принимать тело письма. Все данные, введенные после этой команды, будут считаться телом письма. + Затем идет само письмо с полями, такими как *"from"*, *"to"*, *"subject"* и текстом письма. + *.*: Это команда завершает передачу данных письма. + *250 2.0.0 OK 1708166862 l25-20020ac24a99000000b005115fc3d7f8sm228983lfp.205 - gsmtp*: Сервер подтверждает успешное получение и обработку письма. == Задание 2 #colorbox( title: "TODO", color: "blue", radius: 2pt, width: auto )[ Подключитесь по IMAP/POP3 к своему почтовому ящику, узнайте информацию о нем, используя команды протоколов ] === IMAP ```bash openssl s_client -connect imap.gmail.com:993 -crlf -quiet Connecting to 172.16.31.10 depth=2 C=US, O=Google Trust Services LLC, CN=GTS Root R1 verify return:1 depth=1 C=US, O=Google Trust Services LLC, CN=GTS CA 1C3 verify return:1 depth=0 CN=imap.gmail.com verify return:1 * OK Gimap ready for requests from 172.16.58.3 c9mb22601693ltc a login <EMAIL> "<PASSWORD>" * CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- SPECIAL-USE APPENDLIMIT=35651584 a OK <EMAIL> authenticated (Success) a status INBOX (MESSAGES RECENT UNSEEN) * STATUS "INBOX" (MESSAGES 17 RECENT 0 UNSEEN 15) a OK Success ``` Разберем каждую часть. + *openssl s_client -connect imap.gmail.com:993 -crlf -quiet*: Эта команда использует OpenSSL для установки защищенного SSL/TLS соединения с почтовым сервером Gmail на порту 993, который является стандартным портом для протокола IMAP. + После установки соединения, сервер возвращает сертификаты SSL, которые клиент (в данном случае OpenSSL) проверяет на валидность. + *OK Gimap ready for requests from 172.16.58.3 c9mb22601693ltc*: Сервер приветствует клиента и готов принимать запросы. IP-адрес и некоторая информация о клиенте также предоставляются. + *a login <EMAIL> "pass*": Клиент отправляет команду на аутентификацию. В данном случае, имя пользователя (<EMAIL>) и пароль ("<PASSWORD>") передаются в виде аргументов команды. + *CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- SPECIAL-USE APPENDLIMIT=35651584*: Сервер отвечает, предоставляя список поддерживаемых возможностей (CAPABILITY) в рамках протокола IMAP. Это включает различные расширения, такие как IDLE, UIDPLUS, COMPRESS=DEFLATE и другие. + *a OK <EMAIL> authenticated (Success)*: Сервер подтверждает успешную аутентификацию пользователя. + *a status INBOX (MESSAGES RECENT UNSEEN)*: Клиент отправляет команду для запроса статуса почтового ящика INBOX. Сервер возвращает информацию о количестве сообщений, недавно полученных и непрочитанных в ящике. + *STATUS "INBOX" (MESSAGES 17 RECENT 0 UNSEEN 15)*: Сервер предоставляет статус ящика INBOX с указанием количества сообщений, недавно полученных, и непрочитанных. + *a OK Success*: Сервер подтверждает успешное выполнение команды status и возвращает статус "Success". === POP 3 ```bash openssl s_client -connect pop.gmail.com:995 -crlf -quiet Connecting to 192.168.127.12 depth=2 C=US, O=Google Trust Services LLC, CN=GTS Root R1 verify return:1 depth=1 C=US, O=Google Trust Services LLC, CN=GTS CA 1C3 verify return:1 depth=0 CN=pop.gmail.com verify return:1 +OK Gpop ready for requests from 172.16.58.3 w20mb22708066ltc USER <EMAIL> +OK send PASS PASS <<PASSWORD>> +OK Welcome. LIST +OK 276 messages (626188523 bytes) 1 3294 2 3749 3 3907 ... 271 15832 272 14670 273 5151 274 5151 275 5975 276 5975 . STAT +OK 276 626188523 RETR 1 +OK message follows MIME-Version: 1.0 Received: by 10.49.58.100; Fri, 24 Aug 2012 01:22:20 -0700 (PDT) Date: Fri, 24 Aug 2012 01:22:20 -0700 Message-ID: <<EMAIL>> Subject: =?KOI8-R?B?6dPQz8zY2tXK1MUgR21haWwgzsEg08/Uz9fPzSDU?= =?KOI8-R?B?xczFxs/OxQ==?= From: =?KOI8-R?B?68/MzMXL1MnXIEdtYWls?= <<EMAIL>> To: =?KOI8-R?B?98HEyc0g8dLP18/K?= <<EMAIL>> Content-Type: multipart/alternative; boundary=e89a8f921a22babddc04c7feac1d ``` Разберем каждую часть. + *openssl s_client -connect pop.gmail.com:995 -crlf -quiet*: Эта команда использует OpenSSL для установки защищенного SSL/TLS соединения с почтовым сервером Gmail на порту 995, который является стандартным портом для протокола POP3 с использованием шифрования. + После установки соединения, сервер возвращает сертификаты SSL, которые клиент (в данном случае OpenSSL) проверяет на валидность. + *+OK Gpop ready for requests from 172.16.58.3 w20mb22708066ltc*: Сервер приветствует клиента и готов принимать запросы. IP-адрес и некоторая информация о клиенте также предоставляются. + *USER <EMAIL>*: Клиент отправляет команду на аутентификацию пользователя, указывая имя пользователя (<EMAIL>). + *+OK send PASS*: Сервер подтверждает получение имени пользователя и ожидает команды для отправки пароля. + *PASS <pass>*: Клиент отправляет свой пароль в зашифрованном виде. + *+OK Welcome.*: Сервер подтверждает успешную аутентификацию пользователя. + *LIST*: Клиент запрашивает список сообщений на сервере. + *+OK 276 messages (626188523 bytes)*: Сервер отвечает, сообщая об общем количестве сообщений и их общем размере. + *1 3294, 2 3749, ..., 276 5975*: Сервер предоставляет список сообщений с номерами и их размерами. + *STAT*: Клиент запрашивает статистику по почтовому ящику. + *+OK 276 626188523*: Сервер отвечает, предоставляя информацию о количестве сообщений и их общем размере. + *RETR 1*: Клиент запрашивает текст первого сообщения. + *+OK message follows*: Сервер подтверждает и готов отправить содержимое сообщения. + Затем идет фрагмент текста письма #pagebreak()
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/vielfaches.typ
typst
#import "@preview/cetz:0.2.2" #import "/config.typ": theme #cetz.canvas(length: 5%, { import cetz.draw: * let g = rgb(0, 0, 0, 20%) let r = theme.primary set-viewport((0, 0), (20, 20), bounds: (12, 20)) set-style(stroke: (thickness: 1, paint: g)) line((0, 0), (4, 0), name: "a") line((), (rel: (4, 0)), stroke: (paint: r), name: "a1") line((), (rel: (4, 0)), stroke: (paint: r)) line((0, -3), (6, -3), name: "b") line((), (rel: (6, 0)), stroke: (paint: r), name: "b1") set-style(stroke: (thickness: 1pt, paint: black, dash: "dashed")) line((4, .5), (4, -.5)) line((8, .5), (8, -.5)) line((6, -3.5), (6, -2.5)) content("a.mid", anchor: "south", padding: (bottom: 1))[$a = 4$] content("b.mid", anchor: "south", padding: (bottom: 1))[$b = 6$] content("a1.end", anchor: "south", padding: (bottom: 1))[$k_1 = 3$] content("b1.mid", anchor: "south", padding: (bottom: 1))[$k_2 = 2$] set-style(stroke: (dash: none)) cetz.decorations.flat-brace( (12, -4), (0, -4), name: "brace" ) move-to("brace.content") content((rel: (0, -4pt)))[$x = 12$] })
https://github.com/heiafr-isc/typst-report-template
https://raw.githubusercontent.com/heiafr-isc/typst-report-template/main/lib/french_date.typ
typst
Apache License 2.0
// --------------------------------------------------------------------------- // Copyright © 2024 Haute école d'ingénierie et d'architecture de Fribourg // SPDX-License-Identifier: Apache-2.0 // --------------------------------------------------------------------------- // Author : <NAME> <<EMAIL>> // Date : 23 February 2024 // --------------------------------------------------------------------------- // Typst funtions to format dates in french. Currently, Typst dooes not // support date formating in languages other than english. This is a // workaround to provide french date formatting. It might be obsolete // in the future if Typst supports other languages. // --------------------------------------------------------------------------- #let french_months = ( "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ) #let short_date(date) = { text(date.display( "[day padding:none].[month padding:none].[year padding:none repr:full]" )) } #let long_date(date) = { let m = french_months.at(date.month()-1) text(date.display( "[day padding:none] " + m + " [year padding:none repr:full]" )) }
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/5-Execute%26MemoryAccess/memory-access.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Memory Access ], lesson: "ARO", chapter: "5 - Execute & Memory Access", definition: "Le texte aborde l'importance de l'accès à la mémoire dans un processeur pour charger des instructions, sauvegarder les données et garantir un fonctionnement efficace des programmes. Il explique également le concept de memory mapping pour définir les emplacements de la mémoire et des périphériques, ainsi que l'utilisation de la pile pour stocker des données selon le principe Last In First Out (LIFO), telles que les adresses de retour des fonctions et les variables locales.", col: 1, doc, ) = MEMORY ACCESS L'accès à la mémoire dans un processeur permet au CPU d'interagir avec la mémoire système pour lire ou écrire des données. Cette étape est essentielle pour charger des instructions et des données depuis la mémoire principale, ainsi que pour sauvegarder les résultats des calculs. Le memory access garantit que le processeur a un accès rapide et efficace à la mémoire, ce qui est crucial pour le bon fonctionnement des programmes informatiques en permettant le stockage et la récupération de données à des emplacements spécifiques en mémoire. #image("/_src/img/docs/image copy 25.png") = Memory map #columns(2)[ - L’espace mémoire total adressable par un processeur avec un bus d’adresse de n bits est $2^n$ bytes - Les mémoire et les périphériques occupent des espaces définis à des adresses précises : ceci s’appelle le *memory mapping* - L’adresse de début et la taille des espaces mémoire sont définis par *un décodage d’adresse* effectué par comparaison des bits de poids fort #colbreak() #image("/_src/img/docs/image copy 26.png", height: 400pt) ] = Décodage d'une adresse mémoire À faire = Lecture et écriture == Lecture mémoire - LDR #sym.arrow *Load to Register* - syntaxe : ```shell LDR <Rd>, [<Rn>, #<immed_5> * 4]``` - charge dans le registre Rd la donnée (32 bits) en mémoire (lecture mémoire) - l’adresse mémoire est calculée en ajoutant la valeur dans `Rn` à l’offset `immed_5` (5 bits non signé) multiplié par 4 - `Rd` ← `M[Rn + immed_5 * 4]` #image("/_src/img/docs/image copy 27.png") == Écriture mémoire - STR signifie Store from Register - syntaxe : `STR<Rd>, [<Rn>, #<immed_5> * 4]` - écrit en mémoire la donnée contenue dans le registre Rd - l’adresse mémoire est calculée en ajoutant la valeur dans Rn à l’offset immed_5 (5 bits non signé) multiplié par 4 - `M[Rn+immed_5*4]` ← `Rd` #image("/_src/img/docs/image copy 28.png") == Lecture & ecriture autres formats *Ecriture /Lecture mots de 16 bits* - `LDRH <Rd>, [<Rn>, #<immed_5> * 2]` - `STRH <Rd>, [<Rn>, #<immed_5> * 2]` *Ecriture /Lecture octets (8 bits)* - `LDRB <Rd>, [<Rn>, #<immed_5>]` - `STRB <Rd>, [<Rn>, #<immed_5>]` = Pile (Stack) La pile est une zone mémoire réservée dans laquelle les données sont stockées et récupérées selon un principe de LIFO (Last In First Out). La pile est utilisée pour stocker les adresses de retour des fonctions, les variables locales, les paramètres de fonctions et d'autres données temporaires. Rappel : SP #sym.arrow Stack Pointer == Pile ascendante les données sont écrites en incrémentant les adresses - SP initialisé avec l’adresse du bas de la pile #image("/_src/img/docs/image copy 29.png") == Pile descendante les données sont écrites en décrémentant les adresses - SP initialisé avec l’adresse du haut de la pile #image("/_src/img/docs/image copy 30.png") #colbreak() == Pré/post-incrémentation *Pré-incrémentation: ++i* - Incrémentation de SP, puis écriture dans le registre à l’adresse SP #image("/_src/img/docs/image copy 31.png") *Post-incrémentation : i++* - Ecriture dans le registre à l’adresse SP, puis incrémentation de SP #image("/_src/img/docs/image copy 32.png") == Utilisation de la pile - Stockage des adresses de retour pour : - appels de fonctions - interruptions - Sauvegarde de registres - changement de contexte (fonctions, interruptions) - Stockage de variables locales - en C : variables déclarées dans le corps d’une fonction == Ecriture dans la pile (ARM) - PUSH <registers> écrit les valeurs de plusieurs registres dans la pile - Liste de registres de R0 à R7 (un bit par registre) et R pour le Link Register #image("/_src/img/docs/image copy 33.png")
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion-pkgs/touying-utils-reconstruct.typ
typst
Apache License 2.0
// path: lib.typ #let reconstruct(body-name: "body", labeled: true, named: false, it, ..new-body) = { } ----- // contains: body-name, labeled, named, it, new-body #import "lib.typ": * #reconstruct(/* range 0..1 */)[]; ----- // contains: "body" #import "lib.typ": * #reconstruct(body-name: /* range 0..1 */)[]; ----- // contains: false, true #import "lib.typ": * #reconstruct(labeled: /* range 0..1 */)[]; ----- // contains: false, true #import "lib.typ": * #reconstruct(named: /* range 0..1 */)[];
https://github.com/dyc3/good-typst-template
https://raw.githubusercontent.com/dyc3/good-typst-template/main/util.typ
typst
The Unlicense
#let unique(items) = { let seen = () for item in items { if (not seen.contains(item)) { seen = seen + (item,) } } return seen }
https://github.com/tuatmcc/GitLectureRepo
https://raw.githubusercontent.com/tuatmcc/GitLectureRepo/main/Inoyu.typ
typst
#import "@local/tuat-typst:0.1.0": * #show: doc => tuatTemplate(// title: "実験報告書", // タイトル(上部) date1: "2021-01-01", // 日付1 date2: "2021-01-02", // 日付2 date3: "2021-01-03", // 日付3 date4: "2021-01-04", // 日付4 // date5: "2021-01-05", // 日付5 collaborator1: "<NAME>", // 共同作業者1 collaborator2: "<NAME>", // 共同作業者2 collaborator3: "<NAME>", // 共同作業者3 collaborator4: "<NAME>", // 共同作業者4 // collaborator5: "<NAME>", // 共同作業者5 submitDate: "2021-01-06", // 提出日 resubmitDate: "2021-01-08", // 再提出日 deadline: "2021-01-07", // 期限日 redeadline: "2021-01-09", // 再提出期限日 subject: "情報工学実験", // 科目 teacher: "<NAME>", // テーマ指導教員 grade: "2", // 学年 semester: "後期", // 学期 credit: "2", // 単位 theme: "テーマ", // テーマ studentId: "学籍番号", // 学籍番号 author: "名前", // 名前 doc) #set text( font: "Hiragino Kaku Gothic Pro" ) #set heading( numbering: "1." ) = こんにちは こんにちは = Git ぎっと
https://github.com/TC-Fairplay/member-listing
https://raw.githubusercontent.com/TC-Fairplay/member-listing/main/README.md
markdown
MIT License
# Member Listing ![Compile Documents](https://github.com/TC-Fairplay/member-listing/actions/workflows/compile-docs.yml/badge.svg) [Typst](https://typst.app/) files to generate club member listings (as PDFs) for the protected area of the club website. ## Files - [members-list.typ](members-list.typ): main library, imported by all others typst files (`.typ`). - [junioren-a.typ](junioren-a.typ): listing of juniors "A" (expects a file `junioren_a.csv` in `data`) - [junioren-a.typ](junioren-a.typ): listing of juniors "B"(expects a file `junioren_b.csv` in `data`) - [aktive.typ](aktive.typ): listing of active members (expects a file `aktive.csv` in `data`) - [generate.sh](generate.sh): shell script that generates all PDFs in directory `output`
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/1-introduction/research.typ
typst
MIT License
#import "../../lib/mod.typ": * == Research Hypotheses <intro-research-hypothesis> #let h-amount = context int(hyp-counter.at(<marker.end-of-hypothesis>).first()) // This thesis poses the following #numbers.written(h-amount) hypothesis: // This thesis poses the following #h-amount hypothesis: This thesis poses the following three hypotheses: // #repr(h-amount.get()) // #todo[Maybe this should multiple hypothesis, or maybe it should be more specific or rephrased.] #set enum(numbering: h-enum) // Jonas feedback: // Reimplementing the original GBP Planner in a modern, flexible multi-agent simulator framework using an updated programming language will enhance the software’s scientific communication and extendibility. This redevelopment will not only ensure fidelity in reproducing established results but also improve user engagement and development through advanced tooling, thereby significantly upgrading the usability and functionality for multi-agent system simulations. // Previous: // + Reproducing the results of the original #acr("GBP") Planner, with thought to its architecture and design, and in a new programming language will improve the software's scientific communication and its extensibility. // Updated with Jonas feedback + Reimplementing the original GBP Planner in a modern, flexible, multi-agent simulator framework using a modern programming language, will enhance the software's scientific communication and extendibility. This redevelopment will not only ensure fidelity in reproducing established results, but also improve user engagement and development through advanced tooling, thereby significantly upgrading the usability and functionality for multi-agent system simulations. // Jonas feedback: // We assert that the original work can be enhanced through precise modifications without interfering with the original work. Specifically, we introduce and rigorously test various GBP iteration schedules, and to strategically enhance the system by advancing towards a more distributed approach. These targeted improvements are expected to optimize performance and flexibility of system. // Previous: // + The original work can be improved without transforming it. Specifically, these improvements include testing different #acr("GBP") iteration schedules, and taking minor steps towards a more distributed approach. // Updated with Jonas feedback + The original work can be enhanced through specific modifications without interfering with the original work's functionality. Specifically, we introduce and rigorously test various GBP iteration schedules, and strategically enhance the system by advancing towards a more distributed approach. These targeted improvements are expected to optimize flexibility and move towards a closer-to-reality system. + Extending the original #acr("GBP") Planner software with a global planning layer, will extend the actors' capability to move in complex environments without degradation to the reproduced local cooperative collision avoidance, while maintaining a competitive level of performance. To this end, a new type of factor can be added to the #acr("GBP") factor graphs to aid in path-following. // Previous fourth hypothesis, merged with the first one // + Extensive tooling will create a great environment for others to understand the software and extend it further. Furthermore, such tooling will make it easier to reproduce and engage with the developed solution software. From this point on, anything pertaining to the context of #H(1) will be referred to as #study.H-1.full.s, #H(2) will be #study.H-2.full.s, #H(3) will be covered by #study.H-3.full.s. <marker.end-of-hypothesis> == Research Questions <intro-research-questions> This section outlines which research questions will have to be answered, to reach a conclusion for each hypothesis. The questions below are structured under each research objective, and are numbered accordingly. \ \ #[ #set par(first-line-indent: 0em) // === Study 1 #study.H-1.prefix #sym.dash.em Questions for hypothesis #boxed(color: theme.lavender, fill: theme.lavender.lighten(80%), "H-1", weight: 900): #set enum(numbering: req-enum.with(prefix: "RQ-1.", color: theme.teal)) // + Which programming language will be optimal for scientific communication and extensibility? // + Is it possible to reproduce the results of the original #acr("GBP") Planner in the developed simulator? + Which architecture and framework is suitable for presenting an extensible simulator, an easy-to-understand visual, and a user-friendly interface, and can it reproduce the original results? + What kind of tooling will be most beneficial for the software? + How can tooling help with future reproducibility and engagement with the software? + How can tooling help with understanding and extending the software? // === Study 2 #study.H-2.prefix #sym.dash.em Questions for hypothesis #boxed(color: theme.lavender, fill: theme.lavender.lighten(80%), "H-2", weight: 900): #set enum(numbering: req-enum.with(prefix: "RQ-2.", color: theme.teal)) + Which possible ways can the #acr("GBP") iteration scheduling be further analysed and improved? + How can such iteration schedules be tested, to ensure that they are an improvement? + Which possible avenues exist to advance towards a more distributed approach? + Are these targeted improvements able to enhance the original work without transforming it? // === Study 3 #study.H-3.prefix #sym.dash.em Questions for hypothesis #boxed(color: theme.lavender, fill: theme.lavender.lighten(80%), "H-3", weight: 900): #set enum(numbering: req-enum.with(prefix: "RQ-3.", color: theme.teal)) + Will global planning improve the actors' capability to move autonomously in complex environments? + Will global planning degrade the existing local cooperative collision avoidance? + What impact will the global planning layer have on performance? + Is it possible to introduce a new type of factor that can aid in path-following? + What impact will this factor have on the existing behaviour of the actors, importantly; will it degrade their ability to collaborate and avoid collisions - both with each other and the environment? + What will the impact of this factor be on the actors' capability to move in complex environments? ] // #todo[1 hypothesis to many research question] #pagebreak(weak: true) == Research Objectives <intro-research-objectives> To answer each research question, a set of objectives will have to be met. The objective for each question is listed and numbered below. #{ set enum(start: 1) [ /// Study 1 #(study.heading)(study.H-1.full.n) *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-1.1", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-1.1.", color: theme.green)) + Research possible programming languages and their ecosystems, to understand which one provides the most suitable architecture, and framework for the reimplementation. + Reimplement the original GBP Planner in the developed simulation tool with the chosen language, architecture, and framework. + Evaluate whether the reimplementation is faithful to the original GBP Planner by comparing the four metrics: distance travelled, makespan, smoothness, and collision count. *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-1.2", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-1.2.", color: theme.green)) + Analyse and evaluate different kinds of tooling that can be beneficial for the software. + Pick the most beneficial tooling approach for the software. *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-1.3", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-1.3.", color: theme.green)) + Implement tooling to help with future reproducibility and engagement with the software. *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-1.4", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-1.4.", color: theme.green)) + Implement tooling to help with understanding and extending the software. /// Study 2 #(study.heading)(study.H-2.full.n) *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-2.1", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-2.1.", color: theme.green)) + Identify how to implement different #acr("GBP") iteration schedules. *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-2.2", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-2.2.", color: theme.green)) + Evaluate the different possibilities for improving the #acr("GBP") iteration scheduling, and identify the best one. // + Implement the identified improvements without transforming#note.k[modifying the existing] the software. // + Evaluate whether the improvements are transformative by comparing the four metrics: distance travelled, makespan, smoothness, and collision count. *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-2.3", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-2.3.", color: theme.green)) + Identify ways to advance towards a more distributed approach. + Tie this into the chosen architecture and framework. *Objectives for _Research Questions_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-2.X", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-2.X.", color: theme.green)) + Evaluate the enhanced system's performance and flexibility, and compare it to the original system. /// Study 3 #pagebreak(weak: true) #(study.heading)(study.H-3.full.n) *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.1", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-3.1.", color: theme.green)) + Implement a global planning layer in the reimplemented GBP Planner. + Evaluate the actors' capability to move in complex environments by looking at the four metrics: distance travelled, makespan, smoothness, and collision count, comparing against the reimplemented reproduction and the original GBP Planner. *Objectives for _Research Questions_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.2", weight: 900) and #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.3", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-3.2.", color: theme.green)) + Compare the four metrics: distance travelled, makespan, smoothness, and collision count of the reimplemented reproduction with and without the global planning layer. // /// Study 4 // #(study.heading)(study.H-4.full.n) *Objectives for _Research Question_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.4", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-3.4.", color: theme.green)) + Implement a new type of factor that can aid in path-following. + Make the factor interact with the path given to the actors. + Design the factor's measurement function, Jacobian. *Objectives for _Research Questions_ #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.5", weight: 900) and #boxed(color: theme.teal, fill: theme.teal.lighten(80%), "RQ-3.6", weight: 900):* #set enum(numbering: req-enum.with(prefix: "O-3.5.", color: theme.green)) + Measure the impact on the four metrics: distance travelled, makespan, smoothness, and collision count. + Evaluate the impact of the new factor on the actors' behaviour. ] } // #todo[argument for rust: Half way a modelling language, which is optimal for scientific communication and extensibility.] // #jens[make figure that shows the connection of all these, including outlining which parts are which study.#note.jo[would this be good, or unnecessary?]] // #jens[Fix the objective numbering]
https://github.com/gumelarme/nuist-master-thesis-proposal
https://raw.githubusercontent.com/gumelarme/nuist-master-thesis-proposal/main/strings/zh.typ
typst
#let cover-title = [研究生学位论文开题报告及学位论文工作实施计划] #let notes-title = [说明] #let notes-content = [ + 论文开题报告优研究生向院(所)报告后,听取意见并整理成文后填写; + 论文工作实施计划由指导老师指导学生填写; + 博士生在入学后第二学期结束前完成,硕士生仔入学后第三学期结束前完成; + 本表一试二份,提交研究生院审核盖章后,由学位点学院留存整理归档。(一份留存学生的学籍档案,一份留存学生的学位档案)。 + 学位类别为:*学术学位博士、专业学位硕士、学术学位硕士* ] #let student-number = "学号" #let degree = "硕士" #let school-name = "南京信息工程大学" #let cover-entries = ( "所在院(所)": (lorem(1), lorem(3)), "学科专业": "人工智能", "研究生姓名": "", "学位类别": "", "导师姓名": "", "开题报告日期": "", "入学年月": "", ) #let section-1 = "一、论文开题报告" #let title-sources = ( [04 国家社科规划、基金项目], [05 教育部人文、社会科学研究项目], [06 国家自然科学基金项目], [09 省(自治区,直辖市)项目], [14 企事业单位委托横向项目], [16 学校自选项目], [99 其他], ) #let th-thesis-title = "论文题目" #let th-research-dir = [研究方向] #let th-title-source = [题目来源 \ (请在相应 \ 类型内打 $checkmark$)] #let th-title-type = "题目类型" #let th-proposal-content = "开题报告内容" #let tt-engineering = "工程技术" #let tt-applied = "应用研究" #let tt-theoritical = "理论研究" #let tt-interdis = "交叉学科研究" #let tt-other = "其他题目类型" #let th-notes = "备注"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/align_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Ref: false #test(type(center), alignment) #test(type(horizon), alignment) #test(type(center + horizon), alignment)
https://github.com/SeniorMars/tree-sitter-typst
https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/math/attach.typ
typst
MIT License
// Test top and bottom attachments. --- // Test basics. $f_x + t^b + V_1^2 + attach(A, top: alpha, bottom: beta)$ --- // Test function call after subscript. $pi_1(Y), a_f(x), a^zeta(x) \ a^subset.eq(x), a_(zeta(x)), pi_(1(Y))$ --- // Test associativity and scaling. $ 1/(V^2^3^4^5) $ --- // Test high subscript and superscript. $sqrt(a_(1/2)^zeta)$ $sqrt(a_alpha^(1/2))$ $sqrt(a_(1/2)^(3/4))$ --- // Test frame base. $ (-1)^n + (1/2 + 3)^(-1/2) $ --- // Test limit. $ lim_(n->oo \ n "grows") sum_(k=0 \ k in NN)^n k $ --- // Test forcing scripts and limits. $ limits(A)_1^2 != A_1^2 $ $ scripts(sum)_1^2 != sum_1^2 $ $ limits(integral)_a^b != integral_a^b $
https://github.com/ludwig-austermann/typst-idwtet
https://raw.githubusercontent.com/ludwig-austermann/typst-idwtet/main/examples/ouset_and_funarray.typ
typst
MIT License
#set page(margin: 0.5cm, width: 14cm, height: auto) = idwtet (I Don't Wanna Type Everything Twice) To load this package in this repo, we have to: #import "../idwtet.typ" #show: idwtet.init.with(eval-scope: ( ouset: ( value: {import "@preview/ouset:0.1.1": ouset; ouset}, code: "#import \"@preview/ouset:0.1.1\": ouset" ), funarray: ( value: {import "@preview/funarray:0.2.0"; funarray}, code: "import \"@preview/funarray:0.2.0\"" ), )) ```typst #import "../idwtet.typ" ``` Then we `init` the document and have to now define the variables to use in the package. Note, that import statements are not allowed in eval blocks, such that you have to use a workaround as given here. ```typst #show: idwtet.init.with(eval-scope: ( ouset: ( value: {import "@preview/ouset:0.1.1": ouset; ouset}, code: "#import \"@preview/ouset:0.1.1\": ouset" ), funarray: ( value: {import "@preview/funarray:0.2.0"; funarray}, code: "import \"@preview/funarray:0.2.0\"" ), )) ``` == ouset package #text(gray)[(v0.1.1)] Here we use the `typst-ex` codeblock. It evaluates the content as content, but still in local scope. To display the import, we use the `%ouset%` as a placeholder, which will automatically be replaced as defined before. The variable `ouset` itself is defined, though. ```typst-ex %ouset% $ "Expression 1" ouset(&, <==>, "Theorem 1") "Expression 2"\ ouset(&, ==>,, "Theorem 7") "Expression 3" $ ``` == funarray package #text(gray)[(v0.2.0)] Here we use the `typst-ex-code` codeblock. It evaluates the content as code, wraps the code appropiately and shows the return type. ```typst-ex-code %funarray% let numbers = (1, "not prime", 2, "prime", 3, "prime", 4, "not prime") let (primes, non-primes) = funarray.partition-map( funarray.chunks(numbers, 2), // transforms (a,b,c,d,e) to ((a,b), (c,d), (e,)) x => x.at(1) == "prime", // partition criterion x => x.at(0) // map of each group ) primes ``` == Other examples `typst-ex-code` codeblocks, evaluate in code mode and display the return type: ```typst-ex-code let hello = 2 ``` ```typst-ex-code [Wow] ``` Also there are `typst-code` and `typst` (re-)defiend, here shown in order. Both only show typst code without executing. You can still use `typc` and `typ` for standard typst behaviour. ```typst-code let hello = 2 ``` ```typst let hello = 2 ```
https://github.com/ns-shop/ns-shop-typst
https://raw.githubusercontent.com/ns-shop/ns-shop-typst/main/fonts/main.typ
typst
#import "template.typ": * #import "cover.typ": * #show: template // --- cover #cover() #cover(border: false) // --- set page number #set page(numbering: "1") #counter(page).update(1) #include "pre.typ" #include "chapter1.typ" #include "chapter2.typ" #include "chapter3.typ" #h1("Tài liệu tham khảo", numbering: false) #bibliography("refs/refs.yml", title: none)
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/tests/features/custom-elements/test.typ
typst
MIT License
// Synopsis: // - the figure doesnt interfere with chapter numbering // - the use of `loc: loc` ensures that return values can be used for logic // - the use of `custom` ensures that heading searches are scoped by chapters #import "/src/lib.typ" as hydra #import hydra.selectors: custom #import hydra: hydra #let chapter = figure.with(supplement: [Chapter], kind: "chapter") #let chapter-sel = figure.where(kind: "chapter") #show chapter-sel: it => { pagebreak(weak: true) set align(center) set text(32pt) counter(heading).update(0) [Chapter ] it.counter.display() linebreak() it.body } #let display-chapter(ctx, chapter) = { if chapter.has("numbering") and chapter.numbering != none { numbering(chapter.numbering, ..counter(chapter-sel).at(chapter.location())) [ ] } chapter.body } #set page(paper: "a7", header: context { let chap = hydra(chapter-sel, display: display-chapter) let sec = hydra(custom(heading.where(level: 1), ancestors: chapter-sel)) chap if chap != none and sec != none [ --- ] sec }) #set heading(numbering: "1.1") #set par(justify: true) #chapter[Introduction] #lorem(100) #chapter[Content] = First Section #figure[Fake figure] #lorem(120) = Second Section #lorem(50)
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/packages/tables.md
markdown
MIT License
# Tables ## Tablex: general purpose tables library ```typ #import "@preview/tablex:0.0.7": tablex, rowspanx, colspanx #tablex( columns: 4, align: center + horizon, auto-vlines: false, // indicate the first two rows are the header // (in case we need to eventually // enable repeating the header across pages) header-rows: 2, // color the last column's cells // based on the written number map-cells: cell => { if cell.x == 3 and cell.y > 1 { cell.content = { let value = int(cell.content.text) let text-color = if value < 10 { red.lighten(30%) } else if value < 15 { yellow.darken(13%) } else { green } set text(text-color) strong(cell.content) } } cell }, /* --- header --- */ rowspanx(2)[*Username*], colspanx(2)[*Data*], (), rowspanx(2)[*Score*], (), [*Location*], [*Height*], (), /* -------------- */ [John], [Second St.], [180 cm], [5], [Wally], [Third Av.], [160 cm], [10], [Jason], [Some St.], [150 cm], [15], [Robert], [123 Av.], [190 cm], [20], [Other], [Unknown St.], [170 cm], [25], ) ``` ```typ #import "@preview/tablex:0.0.7": tablex, hlinex, vlinex, colspanx, rowspanx #pagebreak() #v(80%) #tablex( columns: 4, align: center + horizon, auto-vlines: false, repeat-header: true, /* --- header --- */ rowspanx(2)[*Names*], colspanx(2)[*Properties*], (), rowspanx(2)[*Creators*], (), [*Type*], [*Size*], (), /* -------------- */ [Machine], [Steel], [5 $"cm"^3$], [John p& Kate], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Robert], [Frog], [Animal], [6 $"cm"^3$], [Rodbert], ) ``` ```typ #import "@preview/tablex:0.0.7": tablex, gridx, hlinex, vlinex, colspanx, rowspanx #tablex( columns: 4, auto-lines: false, // skip a column here vv vlinex(), vlinex(), vlinex(), (), vlinex(), colspanx(2)[a], (), [b], [J], [c], rowspanx(2)[d], [e], [K], [f], (), [g], [L], // ^^ '()' after the first cell are 100% ignored ) #tablex( columns: 4, auto-vlines: false, colspanx(2)[a], (), [b], [J], [c], rowspanx(2)[d], [e], [K], [f], (), [g], [L], ) #gridx( columns: 4, (), (), vlinex(end: 2), hlinex(stroke: yellow + 2pt), colspanx(2)[a], (), [b], [J], hlinex(start: 0, end: 1, stroke: yellow + 2pt), hlinex(start: 1, end: 2, stroke: green + 2pt), hlinex(start: 2, end: 3, stroke: red + 2pt), hlinex(start: 3, end: 4, stroke: blue.lighten(50%) + 2pt), [c], rowspanx(2)[d], [e], [K], hlinex(start: 2), [f], (), [g], [L], ) ``` ```typ #import "@preview/tablex:0.0.7": tablex, colspanx, rowspanx #tablex( columns: 3, map-hlines: h => (..h, stroke: blue), map-vlines: v => (..v, stroke: green + 2pt), colspanx(2)[a], (), [b], [c], rowspanx(2)[d], [ed], [f], (), [g] ) ``` ```typ #import "@preview/tablex:0.0.7": tablex, colspanx, rowspanx #tablex( columns: 4, auto-vlines: true, // make all cells italicized map-cells: cell => { (..cell, content: emph(cell.content)) }, // add some arbitrary content to entire rows map-rows: (row, cells) => cells.map(c => if c == none { c // keeping 'none' is important } else { (..c, content: [#c.content\ *R#row*]) } ), // color cells based on their columns // (using 'fill: (column, row) => color' also works // for this particular purpose) map-cols: (col, cells) => cells.map(c => if c == none { c } else { (..c, fill: if col < 2 { blue } else { yellow }) } ), colspanx(2)[a], (), [b], [J], [c], rowspanx(2)[dd], [e], [K], [f], (), [g], [L], ) ``` ```typ #import "@preview/tablex:0.0.7": gridx #gridx( columns: 3, rows: 6, fill: (col, row) => (blue, red, green).at(calc.rem(row + col - 1, 3)), map-cols: (col, cells) => { let last = cells.last() last.content = [ #cells.slice(0, cells.len() - 1).fold(0, (acc, c) => if c != none { acc + eval(c.content.text) } else { acc }) ] last.fill = aqua cells.last() = last cells }, [0], [5], [10], [1], [6], [11], [2], [7], [12], [3], [8], [13], [4], [9], [14], [s], [s], [s] ) ``` ## Tada: data manipulation ```typ #import "@preview/tada:0.1.0" #let column-data = ( name: ("Bread", "Milk", "Eggs"), price: (1.25, 2.50, 1.50), quantity: (2, 1, 3), ) #let record-data = ( (name: "Bread", price: 1.25, quantity: 2), (name: "Milk", price: 2.50, quantity: 1), (name: "Eggs", price: 1.50, quantity: 3), ) #let row-data = ( ("Bread", 1.25, 2), ("Milk", 2.50, 1), ("Eggs", 1.50, 3), ) #import tada: TableData, to-tablex #let td = TableData(data: column-data) // Equivalent to: #let td2 = tada.from-records(record-data) // _Not_ equivalent to (since field names are unknown): #let td3 = tada.from-rows(row-data) #to-tablex(td) #to-tablex(td2) #to-tablex(td3) ``` ## Tablem: markdown tables > See documentation [there](https://github.com/OrangeX4/typst-tablem) Render markdown tables in Typst. ```typ #import "@preview/tablem:0.1.0": tablem #tablem[ | *Name* | *Location* | *Height* | *Score* | | ------ | ---------- | -------- | ------- | | John | Second St. | 180 cm | 5 | | Wally | Third Av. | 160 cm | 10 | ] ``` ### Custom render ```typ #import "@preview/tablex:0.0.6": tablex, hlinex #import "@preview/tablem:0.1.0": tablem #let three-line-table = tablem.with( render: (columns: auto, ..args) => { tablex( columns: columns, auto-lines: false, align: center + horizon, hlinex(y: 0), hlinex(y: 1), ..args, hlinex(), ) } ) #three-line-table[ | *Name* | *Location* | *Height* | *Score* | | ------ | ---------- | -------- | ------- | | John | Second St. | 180 cm | 5 | | Wally | Third Av. | 160 cm | 10 | ] ```
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying-unistra-pristine/1.0.0/example/example.typ
typst
Apache License 2.0
#import "@preview/touying:0.5.2": * #import "@preview/touying-unistra-pristine:1.0.0": * #show: unistra-theme.with( aspect-ratio: "16-9", config-info( title: [Title], subtitle: [_Subtitle_], author: [Author], date: datetime.today().display("[month repr:long] [day], [year repr:full]"), logo: image("unistra.svg", width: auto, height: 100%), ), ) #title-slide(logo-inset: 5mm)[] = Example Section Title == Example Slide A slide with *important information*. #pause === Highlight This is #highlight(fill: blue)[highlighted in blue]. This is #highlight(fill: yellow)[highlighted in yellow]. This is #highlight(fill: green)[highlighted in green]. This is #highlight(fill: red)[highlighted in red]. #hero( image("cat1.jpg", height: 70%), title: "Hero", subtitle: "Subtitle", hide-footer: false, ) #hero( image("cat1.jpg", height: 100%), txt: "This is an " + highlight(fill: yellow-light)[RTL#footnote[RTL = right to left. Oh, and here's a footnote!] hero with text and no title] + ".\n" + lorem(40), enhanced-text: false, rows: (80%), direction: "rtl", gap: 1em, hide-footer: false, ) #hero( image("cat1.jpg", height: 100%), txt: "This is an " + highlight(fill: yellow-light)[up-to-down hero with text and no title] + ".\n" + lorem(40), direction: "utd", enhanced-text: false, hide-footer: false, gap: 1em, ) #gallery( image("cat1.jpg", height: 55%), image("cat2.jpg", height: 55%), image("cat1.jpg", height: 55%), image("cat2.jpg", height: 55%), title: "Gallery", captions: ( "Cat 1", "Cat 2", "Cat 1 again", "Cat 2 again", ), columns: 4, ) #focus-slide( theme: "smoke", [ This is a focus slide \ with theme "smoke" ], ) #slide[ This is a normal slide with *admonitions*: #brainstorming[ This is a brainstorming (in French). ] #definition[ This is a definition (in French). ] ] #focus-slide( theme: "neon", [ This is a focus slide \ with theme "neon" ], ) #focus-slide( theme: "yellow", [ This is a focus slide \ with theme "yellow" ], ) #focus-slide( c1: black, c2: white, [ This is a focus slide \ with custom colors \ Next: Section 2 ], text-color: yellow-light, ) = Section 2 == Hey! New Section! #lorem(30) === Heading 3 #lorem(10) ==== Heading 4 #lorem(99) #quote(attribution: [from the <NAME> literal translation of 1897])[ ... I seem, then, in just this little thing to be wiser than this man at any rate, that what I do not know I do not think I know either. ] #slide[ First column. #lorem(15) ][ Second column. #lorem(15) ]
https://github.com/pauladam94/curryst
https://raw.githubusercontent.com/pauladam94/curryst/main/curryst.typ
typst
MIT License
/// Creates an inference rule. /// /// You can render a rule created with this function using the `proof-tree` /// function. #let rule( /// The label of the rule, displayed on the left of the horizontal bar. label: none, /// The name of the rule, displayed on the right of the horizontal bar. name: none, /// The conclusion of the rule. conclusion, /// The premises of the rule. Might be other rules constructed with this /// function, or some content. ..premises ) = { assert( label == none or type(label) == str or type(label) == content or type(label) == symbol, message: "The label of a rule must be some content.", ) assert( name == none or type(name) == str or type(name) == content or type(name) == symbol, message: "The name of a rule must be some content.", ) assert( type(conclusion) == str or type(conclusion) == content or type(conclusion) == symbol, message: "The conclusion of a rule must be some content. In particular, it cannot be another rule.", ) for premise in premises.pos() { assert( type(premise) == str or type(premise) == content or type(premise) == symbol or ( type(premise) == dictionary and "name" in premise and "conclusion" in premise and "premises" in premise ), message: "A premise must be some content or another rule.", ) } assert( premises.named() == (:), message: "Unexpected named arguments to `rule`.", ) ( label: label, name: name, conclusion: conclusion, premises: premises.pos() ) } /// Lays out a proof tree. #let proof-tree( /// The rule to lay out. /// /// Such a rule can be constructed using the `rule` function. rule, /// The minimum amount of space between two premises. prem-min-spacing: 15pt, /// The amount width with which to extend the horizontal bar beyond the /// content. Also determines how far from the bar labels and names are /// displayed. title-inset: 2pt, /// The stroke to use for the horizontal bars. stroke: stroke(0.4pt), /// The space between the bottom of the bar and the conclusion, and between /// the top of the bar and the premises. /// /// Note that, in this case, "the bar" refers to the bounding box of the /// horizontal line and the rule name (if any). horizontal-spacing: 0pt, /// The minimum height of the box containing the horizontal bar. /// /// The height of this box is normally determined by the height of the rule /// name because it is the biggest element of the box. This setting lets you /// set a minimum height. The default is 0.8em, is higher than a single line /// of content, meaning all parts of the tree will align properly by default, /// even if some rules have no name (unless a rule is higher than a single /// line). min-bar-height: 0.8em, ) = { /// Lays out some content. /// /// This function simply wraps the passed content in the usual /// `(content: .., left-blank: .., right-blank: ..)` dictionary. let layout-content(content) = { // We wrap the content in a box with fixed dimensions so that fractional units // don't come back to haunt us later. let dimensions = measure(content) ( content: box( // stroke: yellow + 0.3pt, // DEBUG ..dimensions, content, ), left-blank: 0pt, right-blank: 0pt, ) } /// Lays out multiple premises, spacing them properly. let layout-premises( /// Each laid out premise. /// /// Must be an array of ditionaries with `content`, `left-blank` and /// `right-blank` attributes. premises, /// The minimum amount between each premise. min-spacing, /// If the laid out premises have an inner width smaller than this, their /// spacing will be increased in order to reach this inner width. optimal-inner-width, ) = { let arity = premises.len() if arity == 0 { return layout-content(none) } if arity == 1 { return premises.at(0) } let left-blank = premises.at(0).left-blank let right-blank = premises.at(-1).right-blank let initial-content = stack( dir: ltr, spacing: min-spacing, ..premises.map(premise => premise.content), ) let initial-inner-width = measure(initial-content).width - left-blank - right-blank if initial-inner-width >= optimal-inner-width { return ( content: box(initial-content), left-blank: left-blank, right-blank: right-blank, ) } // Conclusion is wider than the premises: they need to be spaced out. let remaining-space = optimal-inner-width - initial-inner-width let final-content = stack( dir: ltr, spacing: min-spacing + remaining-space / (arity + 1), ..premises.map(premise => premise.content), ) ( content: box(final-content), left-blank: left-blank, right-blank: right-blank, ) } /// Lays out multiple premises that are all leaves, spacing them properly, and /// optionally creating multiple lines if there is not enough available /// horizontal space. let layout-leaf-premises( /// Each laid out premise. /// /// Must be an array of content-like (meaning `content`, `string`, etc.). premises, /// The minimum amount between each premise. min-spacing, /// If the laid out premises have an inner width smaller than this, their /// spacing will be increased in order to reach this inner width. optimal-inner-width, /// The available width for the returned content. /// /// `none` is interpreted as infinite available width. /// /// Ideally, the width of the returned content should be bounded by this /// value, although no guarantee is made. available-width, ) = { // By default, typeset like a regular tree. let default = layout-premises( premises.map(layout-content), min-spacing, optimal-inner-width, ) if available-width == none or measure(default.content).width <= available-width { return default } // If there is not enough horizontal space, use multiple lines. let line-builder = stack.with( dir: ltr, spacing: min-spacing, ) let lines = ((), ) for premise in premises { let augmented-line = lines.last() + (premise, ) if available-width == none or measure(line-builder(..augmented-line)).width <= available-width { lines.last() = augmented-line } else { lines.push((premise, )) } } layout-content({ set align(center) stack( dir: ttb, spacing: 0.7em, ..lines .filter(line => line.len() != 0) .map(line => line-builder(..line)), ) }) } /// Lays out the horizontal bar of a rule. let layout-bar( /// The stroke to use for the bar. stroke, /// The length of the bar, without taking hangs into account. length, /// How much to extend the bar to the left and to the right. hang, /// The label of the rule, displayed on the left of the bar. /// /// If this is `none`, no label is displayed. label, /// The name of the rule, displayed on the right of the bar. /// /// If this is `none`, no name is displayed. name, /// The space to leave between the label and the bar, and between the bar /// and the name. margin, /// The minimum height of the content to return. min-height, ) = { let bar = line( start: (0pt, 0pt), length: length + 2 * hang, stroke: stroke, ) let (width: label-width, height: label-height) = measure(label) let (width: name-width, height: name-height) = measure(name) let content = { show: box.with( // stroke: green + 0.3pt, // DEBUG height: calc.max(label-height, name-height, min-height), ) set align(horizon) let bake(body) = if body == none { none } else { move(dy: -0.15em, box(body, ..measure(body))) } let parts = ( bake(label), bar, bake(name), ).filter(p => p != none) stack( dir: ltr, spacing: margin, ..parts, ) } ( content: content, left-blank: if label == none { hang } else { hang + margin + label-width }, right-blank: if name == none { hang } else { hang + margin + name-width }, ) } /// Lays out the application of a rule. let layout-rule( /// The laid out premises. /// /// This must be a dictionary with `content`, `left-blank` /// and `right-blank` attributes. premises, /// The conclusion, displayed below the bar. conclusion, /// The stroke of the bar. bar-stroke, /// The amount by which to extend the bar on each side. bar-hang, /// The label of the rule, displayed on the left of the bar. /// /// If this is `none`, no label is displayed. label, /// The name of the rule, displayed on the right of the bar. /// /// If this is `none`, no name is displayed. name, /// The space to leave between the label and the bar, and between the bar /// and the name. bar-margin, /// The spacing above and below the bar. horizontal-spacing, /// The minimum height of the bar element. min-bar-height, ) = { // Fix the dimensions of the conclusion and name to prevent problems with // fractional units later. conclusion = box(conclusion, ..measure(conclusion)) let premises-inner-width = measure(premises.content).width - premises.left-blank - premises.right-blank let conclusion-width = measure(conclusion).width let bar-length = calc.max(premises-inner-width, conclusion-width) let bar = layout-bar(bar-stroke, bar-length, bar-hang, label, name, bar-margin, min-bar-height) let left-start let right-start let premises-left-offset let conclusion-left-offset if premises-inner-width > conclusion-width { left-start = calc.max(premises.left-blank, bar.left-blank) right-start = calc.max(premises.right-blank, bar.right-blank) premises-left-offset = left-start - premises.left-blank conclusion-left-offset = left-start + (premises-inner-width - conclusion-width) / 2 } else { let premises-left-hang = premises.left-blank - (bar-length - premises-inner-width) / 2 let premises-right-hang = premises.right-blank - (bar-length - premises-inner-width) / 2 left-start = calc.max(premises-left-hang, bar.left-blank) right-start = calc.max(premises-right-hang, bar.right-blank) premises-left-offset = left-start + (bar-length - premises-inner-width) / 2 - premises.left-blank conclusion-left-offset = left-start } let bar-left-offset = left-start - bar.left-blank let content = { set align(bottom + left) // show: box.with(stroke: yellow + 0.3pt) // DEBUG stack( dir: ttb, spacing: horizontal-spacing, h(premises-left-offset) + premises.content, h(bar-left-offset) + bar.content, h(conclusion-left-offset) + conclusion, ) } ( content: box(content), left-blank: left-start + (bar-length - conclusion-width) / 2, right-blank: right-start + (bar-length - conclusion-width) / 2, ) } /// Lays out an entire proof tree. /// /// All lengths passed to this function must be resolved. let layout-tree( /// The rule containing the tree to lay out. rule, /// The available width for the tree. /// /// `none` is interpreted as infinite available width. /// /// Ideally, the width of the returned tree should be bounded by this value, /// although no guarantee is made. available-width, /// The minimum amount between each premise. min-premise-spacing, /// The stroke of the bar. bar-stroke, /// The amount by which to extend the bar on each side. bar-hang, /// The space to leave between the label and the bar, and between the bar /// and the name. bar-margin, /// The margin above and below the bar. horizontal-spacing, /// The minimum height of the bar element. min-bar-height, ) = { if type(rule) != dictionary { return layout-content(rule) } // A small branch is a tree whose premises (if any) are all leaves. The // premises of such a tree can be typeset in multiple lines in case there is // not enough horizontal space. let is-small-branch = rule.premises.all(premise => type(premise) != dictionary) let premises = if is-small-branch { let width-available-to-premises = none if available-width != none { width-available-to-premises = available-width - bar-hang * 2 if rule.name != none { width-available-to-premises -= bar-margin + measure(rule.name).width } if rule.label != none { width-available-to-premises -= bar-margin + measure(rule.label).width } // This fixes some rounding issues in auto sized containers. width-available-to-premises += 0.00000001pt } layout-leaf-premises( rule.premises, min-premise-spacing, measure(rule.conclusion).width, width-available-to-premises, ) } else { layout-premises( rule.premises.map(premise => layout-tree( premise, none, min-premise-spacing, bar-stroke, bar-hang, bar-margin, horizontal-spacing, min-bar-height, )), min-premise-spacing, measure(rule.conclusion).width, ) } layout-rule( premises, rule.conclusion, bar-stroke, bar-hang, rule.label, rule.name, bar-margin, horizontal-spacing, min-bar-height, ) } layout(available => { let tree = layout-tree( rule, available.width, prem-min-spacing.to-absolute(), stroke, title-inset.to-absolute(), title-inset.to-absolute(), horizontal-spacing.to-absolute(), min-bar-height.to-absolute(), ).content block( // stroke : black + 0.3pt, // DEBUG ..measure(tree), breakable: false, tree, ) }) }
https://github.com/td-org-uit-no/assignment-template-typst
https://raw.githubusercontent.com/td-org-uit-no/assignment-template-typst/main/README.md
markdown
# Assignment Template Typst [Typst Online Preview](https://typst.app/project/rSexhJ45Kv6nJvd9yI5qOV) This repository provides a simple Typst template for writing your Assignments at UiT (The Arctic University of Norway). The template is _supercharged_ with the [typst](https://typst.app/home) language, which is a simple and powerful language for writing scientific documents. > [!NOTE] > This is only a template. You have to adapt the template to your current assignment! ## Installation To use this template, you need to have the `typst` language installed on your computer. There are several ways to install `typst`: - Use your OS package manager like `apt` or `brew` to install Typst. Take note that these could be several versions behind the latest release. - You can also download the latest release from the [GitHub releases page](https://github.com/typst/typst/releases), which provides precompiled binaries for Windows, Linux, and macOS. - Nix users can use the provided flake, which contains the `typst`, `typstfmt` and `typst-lsp` packages. It can be activated using `direnv allow` or simply `nix flake build`. For more information on how to install `typst`, please refer to the [official documentation](https://github.com/typst/typst?tab=readme-ov-file#installation). ## Usage ### Set up the assignments metadata Fill in your assignment details in the `uit_template` function, it should contain the following: - Your name, Email (<EMAIL>) and GitHub user - Assignment title - Your Index Terms - An Abstract ### Build PDFs locally Once you have installed Typst, you can use it like this: ```bash # Creates `main.pdf` in working directory. typst compile main.typ # Creates PDF file at the desired path. typst compile main.typ path/to/output.pdf ``` You can also watch source files and automatically recompile on changes. This is faster than compiling from scratch each time because Typst has incremental compilation. ```bash # Watches source files and recompiles on changes. typst watch main.typ ``` If the `typstyle` is installed, then the text can be formatted using: ```bash typstyle main.typ ``` ### Working in the Typst Web Editor If you prefer an Overleaf-like experience with autocompletion, preview and (soon)spellchecking, then the Typst web editor is for you. It allows you to import files directly into a new or existing document. Here's a step-by-step guide: 1. Navigate to the [Typst Web Editor](https://typst.app/). 2. Create or Sign in to your Account. 3. Create a new blank document. 4. Click on "File" on the top left menu, then "Upload File". 5. Select all `.typ` and `.bib` files along with the figures (svg and png) provided in this template repository. > [!NOTE] > You can select multiple files to import at the same time. The editor will import and arrange all the files accordingly. Watch out if your figures are in a directory, the may end up in root. # Resources Other resources that may be helpful to new and experienced Typsters alike. - [The Typst Book](https://sitandr.github.io/typst-examples-book/book/basics/index.html) - [Typst Guide for LaTeX Users](https://typst.app/docs/guides/guide-for-latex-users/) - [Typst Documentation](https://typst.app/docs/)
https://github.com/Quaternijkon/Typst_FLOW
https://raw.githubusercontent.com/Quaternijkon/Typst_FLOW/main/src/core.typ
typst
#import "utils.typ" #import "utils.typ" #import "pdfpc.typ" #import "components.typ" /// ------------------------------------------------ /// Slides /// ------------------------------------------------ #let _delayed-wrapper(body) = utils.label-it( metadata((kind: "touying-delayed-wrapper", body: body)), "touying-temporary-mark", ) /// Update configurations for the presentation. /// /// Example: `#let appendix(body) = touying-set-config((appendix: true), body)` and you can use `#show: appendix` to set the appendix for the presentation. /// /// - `config` (dict): The new configurations for the presentation. /// /// - `body` (content): The content of the slide. #let touying-set-config(config, body) = utils.label-it( metadata(( kind: "touying-set-config", config: config, body: body, )), "touying-temporary-mark", ) /// Appendix for the presentation. The last-slide-counter will be frozen at the last slide before the appendix. It is simple wrapper for `touying-set-config`, just like `#show: touying-set-config.with((appendix: true))`. /// /// Example: `#show: appendix` /// /// - `body` (content): The content of the appendix. #let appendix(body) = touying-set-config( (appendix: true), body, ) /// Recall a slide by its label /// /// Example: `#touying-recall(<recall>)` or `#touying-recall("recall")` /// /// - `lbl` (str): The label of the slide to recall #let touying-recall(lbl) = utils.label-it( metadata(( kind: "touying-slide-recaller", label: if type(lbl) == label { str(lbl) } else { lbl }, )), "touying-temporary-mark", ) /// Call touying slide function #let _call-slide-fn(self, fn, body) = { let slide-wrapper = fn(body) assert( utils.is-kind(slide-wrapper, "touying-slide-wrapper"), message: "you must use `touying-slide-wrapper` in your slide function", ) return (slide-wrapper.value.fn)(self) } /// Use headings to split a content block into slides #let split-content-into-slides(self: none, recaller-map: (:), new-start: true, is-first-slide: false, body) = { // Extract arguments assert(type(self) == dictionary, message: "`self` must be a dictionary") assert("slide-level" in self and type(self.slide-level) == int, message: "`self.slide-level` must be an integer") assert("slide-fn" in self and type(self.slide-fn) == function, message: "`self.slide-fn` must be a function") let slide-level = self.slide-level let slide-fn = self.slide-fn let new-section-slide-fn = self.at("new-section-slide-fn", default: none) let new-subsection-slide-fn = self.at("new-subsection-slide-fn", default: none) let new-subsubsection-slide-fn = self.at("new-subsubsection-slide-fn", default: none) let new-subsubsubsection-slide-fn = self.at("new-subsubsubsection-slide-fn", default: none) let horizontal-line-to-pagebreak = self.at("horizontal-line-to-pagebreak", default: true) let children = if utils.is-sequence(body) { body.children } else { (body,) } // convert all sequence to array recursively, and then flatten the array let sequence-to-array(it) = { if utils.is-sequence(it) { it.children.map(sequence-to-array) } else { it } } children = children.map(sequence-to-array).flatten() let get-last-heading-depth(current-headings) = { if current-headings != () { current-headings.at(-1).depth } else { 0 } } let get-last-heading-label(current-headings) = { if current-headings != () { if current-headings.at(-1).has("label") { str(current-headings.at(-1).label) } } } let call-slide-fn-and-reset(self, already-slide-wrapper: false, slide-fn, current-slide-cont, recaller-map) = { let cont = if already-slide-wrapper { slide-fn(self) } else { _call-slide-fn(self, slide-fn, current-slide-cont) } let last-heading-label = get-last-heading-label(self.headings) if last-heading-label != none { recaller-map.insert(last-heading-label, cont) } (cont, recaller-map, (), (), true, false) } // The empty content list let empty-contents = ([], [ ], parbreak(), linebreak()) // The headings that we currently have let current-headings = () // Recaller map let recaller-map = recaller-map // The current slide we are building let current-slide = () // The current slide content let cont = none // is new start let is-new-start = new-start // start part let start-part = () // result let result = () // Is we have a horizontal line let horizontal-line = false // Iterate over the children for child in children { // Handle horizontal-line // split content when we have a horizontal line if horizontal-line-to-pagebreak and horizontal-line and child not in ([—], [–], [-]) { current-slide = utils.trim(current-slide) (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) horizontal-line = false } // Main logic if utils.is-kind(child, "touying-slide-wrapper") { current-slide = utils.trim(current-slide) if current-slide != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), already-slide-wrapper: true, child.value.fn, none, recaller-map, ) if child.has("label") and child.label != <touying-temporary-mark> { recaller-map.insert(str(child.label), cont) } result.push(cont) } else if utils.is-kind(child, "touying-slide-recaller") { current-slide = utils.trim(current-slide) if current-slide != () or current-headings != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } let lbl = child.value.label assert(lbl in recaller-map, message: "label not found in the recaller map for slides") // recall the slide result.push(recaller-map.at(lbl)) } else if child == pagebreak() { // split content when we have a pagebreak current-slide = utils.trim(current-slide) (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } else if horizontal-line-to-pagebreak and child == [—] { horizontal-line = true continue } else if horizontal-line-to-pagebreak and horizontal-line and child in ([–], [-]) { continue } else if utils.is-heading(child, depth: slide-level) { let last-heading-depth = get-last-heading-depth(current-headings) current-slide = utils.trim(current-slide) if child.depth <= last-heading-depth or current-slide != () or ( child.depth == 1 and new-section-slide-fn != none ) or (child.depth == 2 and new-subsection-slide-fn != none) or ( child.depth == 3 and new-subsubsection-slide-fn != none ) or (child.depth == 4 and new-subsubsubsection-slide-fn != none) { current-slide = utils.trim(current-slide) if current-slide != () or current-headings != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } } current-headings.push(child) new-start = true if not child.has("label") or str(child.label) != "touying:hidden" { if child.depth == 1 and new-section-slide-fn != none { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), new-section-slide-fn, child.body, recaller-map, ) result.push(cont) } else if child.depth == 2 and new-subsection-slide-fn != none { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), new-subsection-slide-fn, child.body, recaller-map, ) result.push(cont) } else if child.depth == 3 and new-subsubsection-slide-fn != none { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), new-subsubsection-slide-fn, child.body, recaller-map, ) result.push(cont) } else if child.depth == 4 and new-subsubsubsection-slide-fn != none { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), new-subsubsubsection-slide-fn, child.body, recaller-map, ) result.push(cont) } } } else if self.at("auto-offset-for-heading", default: true) and utils.is-heading(child) { let fields = child.fields() let lbl = fields.remove("label", default: none) let _ = fields.remove("body", default: none) fields.offset = 0 let new-heading = if lbl != none { utils.label-it(heading(..fields, child.body), child.label) } else { heading(..fields, child.body) } if new-start { current-slide.push(new-heading) } else { start-part.push(new-heading) } } else if utils.is-kind(child, "touying-set-config") { current-slide = utils.trim(current-slide) if current-slide != () or current-headings != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } // Appendix content result.push( split-content-into-slides( self: utils.merge-dicts(self, child.value.config), recaller-map: recaller-map, new-start: true, child.value.body, ), ) } else if is-first-slide and utils.is-styled(child) { current-slide = utils.trim(current-slide) if current-slide != () or current-headings != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } result.push( utils.reconstruct-styled( child, split-content-into-slides( self: self, recaller-map: recaller-map, new-start: true, is-first-slide: is-first-slide, child.child, ), ), ) } else { let child = if utils.is-styled(child) { // Split the content into slides recursively for styled content let (start-part, cont) = split-content-into-slides( self: self, recaller-map: recaller-map, new-start: false, child.child, ) if start-part != none { utils.reconstruct-styled(child, start-part) } _delayed-wrapper(utils.reconstruct-styled(child, cont)) } else { child } if new-start { // Add the child to the current slide current-slide.push(child) } else { start-part.push(child) } } } // Handle the last slide current-slide = utils.trim(current-slide) if current-slide != () or current-headings != () { (cont, recaller-map, current-headings, current-slide, new-start, is-first-slide) = call-slide-fn-and-reset( self + (headings: current-headings, is-first-slide: is-first-slide), slide-fn, current-slide.sum(default: none), recaller-map, ) result.push(cont) } if is-new-start { return result.sum(default: none) } else { return (start-part.sum(default: none), result.sum(default: none)) } } /// ------------------------------------------------ /// Slide /// ------------------------------------------------ /// Wrapper for a function to make it can receive `self` as an argument. /// It is useful when you want to use `self` to get current subslide index, like `uncover` and `only` functions. /// /// Example: `#let alternatives = touying-fn-wrapper.with(utils.alternatives)` /// /// - `fn` ((self: none, ..args) => { .. }): The function that will be called. /// /// - `with-visible-subslides` (bool): Whether the first argument of the function is the visible subslides. /// /// It is useful for functions like `uncover` and `only`. /// /// Touying will automatically update the max repetitions for the slide if the function is called with visible subslides. #let touying-fn-wrapper(fn, with-visible-subslides: false, ..args) = utils.label-it( metadata(( kind: "touying-fn-wrapper", fn: fn, args: args, with-visible-subslides: with-visible-subslides, )), "touying-temporary-mark", ) /// Wrapper for a slide function to make it can receive `self` as an argument. /// /// Notice: This function is necessary for the slide function to work in Touying. /// /// Example: /// /// ```typst /// #let slide(..args) = touying-slide-wrapper(self => { /// touying-slide(self: self, ..args) /// }) /// ``` /// /// - `fn` (self => { .. }): The function that will be called with an argument `self`. #let touying-slide-wrapper(fn) = utils.label-it( metadata(( kind: "touying-slide-wrapper", fn: fn, )), "touying-temporary-mark", ) /// Uncover content after the `#pause` mark in next subslide. #let pause = [#metadata((kind: "touying-pause"))<touying-temporary-mark>] /// Display content after the `#meanwhile` mark meanwhile. #let meanwhile = [#metadata((kind: "touying-meanwhile"))<touying-temporary-mark>] /// Uncover content in some subslides. Reserved space when hidden (like `#hide()`). /// /// Example: `uncover("2-")[abc]` will display `[abc]` if the current slide is 2 or later /// /// - `visible-subslides` is a single integer, an array of integers, /// or a string that specifies the visible subslides /// /// Read [polylux book](https://polylux.dev/book/dynamic/complex.html) /// /// The simplest extension is to use an array, such as `(1, 2, 4)` indicating that /// slides 1, 2, and 4 are visible. This is equivalent to the string `"1, 2, 4"`. /// /// You can also use more convenient and complex strings to specify visible slides. /// /// For example, "-2, 4, 6-8, 10-" means slides 1, 2, 4, 6, 7, 8, 10, and slides after 10 are visible. /// /// - `uncover-cont` is the content to display when the content is visible in the subslide. #let uncover(visible-subslides, uncover-cont) = { touying-fn-wrapper(utils.uncover, with-visible-subslides: true, visible-subslides, uncover-cont) } /// Display content in some subslides only. /// Don't reserve space when hidden, content is completely not existing there. /// /// - `visible-subslides` is a single integer, an array of integers, /// or a string that specifies the visible subslides /// /// Read [polylux book](https://polylux.dev/book/dynamic/complex.html) /// /// The simplest extension is to use an array, such as `(1, 2, 4)` indicating that /// slides 1, 2, and 4 are visible. This is equivalent to the string `"1, 2, 4"`. /// /// You can also use more convenient and complex strings to specify visible slides. /// /// For example, "-2, 4, 6-8, 10-" means slides 1, 2, 4, 6, 7, 8, 10, and slides after 10 are visible. /// /// - `only-cont` is the content to display when the content is visible in the subslide. #let only(visible-subslides, only-cont) = { touying-fn-wrapper(utils.only, with-visible-subslides: true, visible-subslides, only-cont) } /// `#alternatives` has a couple of "cousins" that might be more convenient in some situations. The first one is `#alternatives-match` that has a name inspired by match-statements in many functional programming languages. The idea is that you give it a dictionary mapping from subslides to content: /// /// #example(``` /// #alternatives-match(( /// "1, 3-5": [this text has the majority], /// "2, 6": [this is shown less often] /// )) /// ```) /// /// - `subslides-contents` is a dictionary mapping from subslides to content. /// /// - `position` is the position of the content. Default is `bottom + left`. #let alternatives-match(subslides-contents, position: bottom + left) = { touying-fn-wrapper(utils.alternatives-match, subslides-contents, position: position) } /// `#alternatives` is able to show contents sequentially in subslides. /// /// Example: `#alternatives[Ann][Bob][Christopher]` will show "Ann" in the first subslide, "Bob" in the second subslide, and "Christopher" in the third subslide. /// /// - `start` is the starting subslide number. Default is `1`. /// /// - `repeat-last` is a boolean indicating whether the last subslide should be repeated. Default is `true`. #let alternatives( start: 1, repeat-last: true, ..args, ) = { touying-fn-wrapper(utils.alternatives, start: start, repeat-last: repeat-last, ..args) } /// You can have very fine-grained control over the content depending on the current subslide by using #alternatives-fn. It accepts a function (hence the name) that maps the current subslide index to some content. /// /// Example: `#alternatives-fn(start: 2, count: 7, subslide => { numbering("(i)", subslide) })` /// /// - `start` is the starting subslide number. Default is `1`. /// /// - `end` is the ending subslide number. Default is `none`. /// /// - `count` is the number of subslides. Default is `none`. #let alternatives-fn( start: 1, end: none, count: none, ..kwargs, fn, ) = { touying-fn-wrapper(utils.alternatives-fn, start: start, end: end, count: count, ..kwargs, fn) } /// You can use this function if you want to have one piece of content that changes only slightly depending of what "case" of subslides you are in. /// /// #example(``` /// #alternatives-cases(("1, 3", "2"), case => [ /// #set text(fill: teal) if case == 1 /// Some text /// ]) /// ```) /// /// - `cases` is an array of strings that specify the subslides for each case. /// /// - `fn` is a function that maps the case to content. The argument `case` is the index of the cases array you input. #let alternatives-cases(cases, fn, ..kwargs) = { touying-fn-wrapper(utils.alternatives-cases, cases, fn, ..kwargs) } /// Speaker notes are a way to add additional information to your slides that is not visible to the audience. This can be useful for providing additional context or reminders to yourself. /// /// Example: `#speaker-note[This is a speaker note]` /// /// - `self` is the current context. /// /// - `mode` is the mode of the markup text, either `typ` or `md`. Default is `typ`. /// /// - `setting` is a function that takes the note as input and returns a processed note. /// /// - `note` is the content of the speaker note. #let speaker-note(mode: "typ", setting: it => it, note) = { touying-fn-wrapper(utils.speaker-note, mode: mode, setting: setting, note) } /// Alert is a way to display a message to the audience. It can be used to draw attention to important information or to provide instructions. #let alert(body) = touying-fn-wrapper(utils.alert, body) /// Touying also provides a unique and highly useful feature—math equation animations, allowing you to conveniently use pause and meanwhile within math equations. /// /// #example(``` /// #touying-equation(` /// f(x) &= pause x^2 + 2x + 1 \ /// &= pause (x + 1)^2 \ /// `) /// ```) /// /// - `block` is a boolean indicating whether the equation is a block. Default is `true`. /// /// - `numbering` is the numbering of the equation. Default is `none`. /// /// - `supplement` is the supplement of the equation. Default is `auto`. /// /// - `scope` is the scope when we use `eval()` function to evaluate the equation. /// /// - `body` is the content of the equation. It should be a string, a raw text or a function that receives `self` as an argument and returns a string. #let touying-equation(block: true, numbering: none, supplement: auto, scope: (:), body) = utils.label-it( metadata(( kind: "touying-equation", block: block, numbering: numbering, supplement: supplement, scope: scope, body: { if type(body) == function { body } else if type(body) == str { body } else if type(body) == content and body.has("text") { body.text } else { panic("Unsupported type: " + str(type(body))) } }, )), "touying-temporary-mark", ) /// Touying can integrate with `mitex` to display math equations. /// You can use `#touying-mitex` to display math equations with pause and meanwhile. /// /// #example(``` /// #touying-mitex(mitex, ` /// f(x) &= \pause x^2 + 2x + 1 \\ /// &= \pause (x + 1)^2 \\ /// `) /// ```) /// /// - `mitex` is the mitex function. You can import it by code like `#import "@preview/mitex:0.2.3": mitex` /// /// - `block` is a boolean indicating whether the equation is a block. Default is `true`. /// /// - `numbering` is the numbering of the equation. Default is `none`. /// /// - `supplement` is the supplement of the equation. Default is `auto`. /// /// - `body` is the content of the equation. It should be a string, a raw text or a function that receives `self` as an argument and returns a string. #let touying-mitex(block: true, numbering: none, supplement: auto, mitex, body) = utils.label( metadata(( kind: "touying-mitex", block: block, numbering: numbering, supplement: supplement, mitex: mitex, body: { if type(body) == function { body } else if type(body) == str { body } else if type(body) == content and body.has("text") { body.text } else { panic("Unsupported type: " + str(type(body))) } }, )), "touying-temporary-mark", ) /// Touying reducer is a powerful tool to provide more powerful animation effects for other packages or functions. /// /// For example, you can adds `pause` and `meanwhile` animations to cetz and fletcher packages. /// /// Cetz: `#let cetz-canvas = touying-reducer.with(reduce: cetz.canvas, cover: cetz.draw.hide.with(bounds: true))` /// /// Fletcher: `#let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide)` /// /// - `reduce` is the reduce function that will be called. It is usually a function that receives an array of content and returns a content it painted. Just like the `cetz.canvas` or `fletcher.diagram` function. /// /// - `cover` is the cover function that will be called when some content is hidden. It is usually a function that receives an the argument of the content that will be hidden. Just like the `cetz.draw.hide` or `fletcher.hide` function. /// /// - `..args` is the arguments of the reducer function. #let touying-reducer(reduce: arr => arr.sum(), cover: arr => none, ..args) = utils.label-it( metadata(( kind: "touying-reducer", reduce: reduce, cover: cover, kwargs: args.named(), args: args.pos(), )), "touying-temporary-mark", ) // parse touying equation, and get the repetitions #let _parse-touying-equation(self: none, need-cover: true, base: 1, index: 1, eqt-metadata) = { let eqt = eqt-metadata.value let result-arr = () // repetitions let repetitions = base let max-repetitions = repetitions // get cover function from self let cover = self.methods.cover.with(self: self) // get eqt body let it = eqt.body // if it is a function, then call it with self if type(it) == function { it = it(self) } assert(type(it) == str, message: "Unsupported type: " + str(type(it))) // parse the content let result = () let cover-arr = () let children = it .split(regex("(#meanwhile;?)|(meanwhile)")) .intersperse("touying-meanwhile") .map(s => s.split(regex("(#pause;?)|(pause)")).intersperse("touying-pause")) .flatten() .map(s => s.split(regex("(\\\\\\s)|(\\\\\\n)")).intersperse("\\\n")) .flatten() .map(s => s.split(regex("&")).intersperse("&")) .flatten() for child in children { if child == "touying-pause" { repetitions += 1 } else if child == "touying-meanwhile" { // clear the cover-arr when encounter #meanwhile if cover-arr.len() != 0 { result.push("cover(" + cover-arr.sum() + ")") cover-arr = () } // then reset the repetitions max-repetitions = calc.max(max-repetitions, repetitions) repetitions = 1 } else if child == "\\\n" or child == "&" { // clear the cover-arr when encounter linebreak or parbreak if cover-arr.len() != 0 { result.push("cover(" + cover-arr.sum() + ")") cover-arr = () } result.push(child) } else { if repetitions <= index or not need-cover { result.push(child) } else { cover-arr.push(child) } } } // clear the cover-arr when end if cover-arr.len() != 0 { result.push("cover(" + cover-arr.sum() + ")") cover-arr = () } let equation = math.equation( block: eqt.block, numbering: eqt.numbering, supplement: eqt.supplement, eval( "$" + result.sum(default: "") + "$", scope: eqt.scope + ( cover: (..args) => { let cover = eqt.scope.at("cover", default: cover) if args.pos().len() != 0 { cover(args.pos().first()) } }, ), ), ) if eqt-metadata.has("label") and eqt-metadata.label != <touying-temporary-mark> { equation = utils.label-it(equation, eqt-metadata.label) } result-arr.push(equation) max-repetitions = calc.max(max-repetitions, repetitions) return (result-arr, max-repetitions) } // parse touying mitex, and get the repetitions #let _parse-touying-mitex(self: none, need-cover: true, base: 1, index: 1, eqt-metadata) = { let eqt = eqt-metadata.value let result-arr = () // repetitions let repetitions = base let max-repetitions = repetitions // get eqt body let it = eqt.body // if it is a function, then call it with self if type(it) == function { it = it(self) } assert(type(it) == str, message: "Unsupported type: " + str(type(it))) // parse the content let result = () let cover-arr = () let children = it .split(regex("\\\\meanwhile")) .intersperse("touying-meanwhile") .map(s => s.split(regex("\\\\pause")).intersperse("touying-pause")) .flatten() .map(s => s.split(regex("(\\\\\\\\\s)|(\\\\\\\\\n)")).intersperse("\\\\\n")) .flatten() .map(s => s.split(regex("&")).intersperse("&")) .flatten() for child in children { if child == "touying-pause" { repetitions += 1 } else if child == "touying-meanwhile" { // clear the cover-arr when encounter #meanwhile if cover-arr.len() != 0 { result.push("\\phantom{" + cover-arr.sum() + "}") cover-arr = () } // then reset the repetitions max-repetitions = calc.max(max-repetitions, repetitions) repetitions = 1 } else if child == "\\\n" or child == "&" { // clear the cover-arr when encounter linebreak or parbreak if cover-arr.len() != 0 { result.push("\\phantom{" + cover-arr.sum() + "}") cover-arr = () } result.push(child) } else { if repetitions <= index or not need-cover { result.push(child) } else { cover-arr.push(child) } } } // clear the cover-arr when end if cover-arr.len() != 0 { result.push("\\phantom{" + cover-arr.sum() + "}") cover-arr = () } let equation = (eqt.mitex)( block: eqt.block, numbering: eqt.numbering, supplement: eqt.supplement, result.sum(default: ""), ) if eqt-metadata.has("label") and eqt-metadata.label != <touying-temporary-mark> { equation = utils.label-it(equation, eqt-metadata.label) } result-arr.push(equation) max-repetitions = calc.max(max-repetitions, repetitions) return (result-arr, max-repetitions) } // parse touying reducer, and get the repetitions #let _parse-touying-reducer(self: none, base: 1, index: 1, reducer) = { let result-arr = () // repetitions let repetitions = base let max-repetitions = repetitions // get cover function from self let cover = reducer.cover // parse the content let result = () let cover-arr = () for child in reducer.args.flatten() { if type(child) == content and child.func() == metadata and type(child.value) == dictionary { let kind = child.value.at("kind", default: none) if kind == "touying-pause" { repetitions += 1 } else if kind == "touying-meanwhile" { // clear the cover-arr when encounter #meanwhile if cover-arr.len() != 0 { result.push(cover(cover-arr.sum())) cover-arr = () } // then reset the repetitions max-repetitions = calc.max(max-repetitions, repetitions) repetitions = 1 } else { if repetitions <= index { result.push(child) } else { cover-arr.push(child) } } } else { if repetitions <= index { result.push(child) } else { cover-arr.push(child) } } } // clear the cover-arr when end if cover-arr.len() != 0 { let r = cover(cover-arr) if type(r) == array { result += r } else { result.push(r) } cover-arr = () } result-arr.push( (reducer.reduce)( ..reducer.kwargs, result, ), ) max-repetitions = calc.max(max-repetitions, repetitions) return (result-arr, max-repetitions) } // parse content into results and repetitions #let _parse-content-into-results-and-repetitions( self: none, need-cover: true, base: 1, index: 1, show-delayed-wrapper: false, ..bodies, ) = { let labeled(func) = { return not ( "repeat" in self and "subslide" in self and "label-only-on-last-subslide" in self and func in self.label-only-on-last-subslide and self.subslide != self.repeat ) } let bodies = bodies.pos() let result-arr = () // repetitions let repetitions = base let max-repetitions = repetitions // get cover function from self let cover = self.methods.cover.with(self: self) for it in bodies { // a hack for code like #table([A], pause, [B]) if type(it) == content and it.func() in (table.cell, grid.cell) { if type(it.body) == content and it.body.func() == metadata and type(it.body.value) == dictionary { let kind = it.body.value.at("kind", default: none) if kind == "touying-pause" { repetitions += 1 } else if kind == "touying-meanwhile" { // reset the repetitions max-repetitions = calc.max(max-repetitions, repetitions) repetitions = 1 } continue } } // if it is a function, then call it with self if type(it) == function { // subslide index it = it(self) } // parse the content let result = () let cover-arr = () let children = if utils.is-sequence(it) { it.children } else { (it,) } for child in children { if type(child) == content and child.func() == metadata and type(child.value) == dictionary { let kind = child.value.at("kind", default: none) if kind == "touying-pause" { repetitions += 1 } else if kind == "touying-meanwhile" { // clear the cover-arr when encounter #meanwhile if cover-arr.len() != 0 { result.push(cover(cover-arr.sum())) cover-arr = () } // then reset the repetitions max-repetitions = calc.max(max-repetitions, repetitions) repetitions = 1 } else if kind == "touying-equation" { // handle touying-equation let (conts, nextrepetitions) = _parse-touying-equation( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(cont) } else { cover-arr.push(cont) } repetitions = nextrepetitions } else if kind == "touying-mitex" { // handle touying-mitex let (conts, nextrepetitions) = _parse-touying-mitex( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(cont) } else { cover-arr.push(cont) } repetitions = nextrepetitions } else if kind == "touying-reducer" { // handle touying-reducer let (conts, nextrepetitions) = _parse-touying-reducer( self: self, base: repetitions, index: index, child.value, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(cont) } else { cover-arr.push(cont) } repetitions = nextrepetitions } else if kind == "touying-fn-wrapper" { // handle touying-fn-wrapper if repetitions <= index or not need-cover { result.push((child.value.fn)(self: self, ..child.value.args)) } else { cover-arr.push((child.value.fn)(self: self, ..child.value.args)) } if child.value.with-visible-subslides { let visible-subslides = child.value.args.pos().at(0) max-repetitions = calc.max(max-repetitions, utils.last-required-subslide(visible-subslides)) } } else if kind == "touying-delayed-wrapper" { if show-delayed-wrapper { if repetitions <= index or not need-cover { result.push(child.value.body) } else { cover-arr.push(child.value.body) } } } else { if repetitions <= index or not need-cover { result.push(child) } else { cover-arr.push(child) } } } else if child == linebreak() or child == parbreak() { // clear the cover-arr when encounter linebreak or parbreak if cover-arr.len() != 0 { result.push(cover(cover-arr.sum())) cover-arr = () } result.push(child) } else if utils.is-sequence(child) { // handle the sequence let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(cont) } else { cover-arr.push(cont) } repetitions = nextrepetitions } else if utils.is-styled(child) { // handle styled let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.child, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(utils.typst-builtin-styled(cont, child.styles)) } else { cover-arr.push(utils.typst-builtin-styled(cont, child.styles)) } repetitions = nextrepetitions } else if type(child) == content and child.func() in (list.item, enum.item, align, link) { // handle the list item let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.body, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(utils.reconstruct(child, labeled: labeled(child.func()), cont)) } else { cover-arr.push(utils.reconstruct(child, labeled: labeled(child.func()), cont)) } repetitions = nextrepetitions } else if type(child) == content and child.func() in (table, grid, stack) { // handle the table-like let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, ..child.children, ) if repetitions <= index or not need-cover { result.push(utils.reconstruct-table-like(child, labeled: labeled(child.func()), conts)) } else { cover-arr.push(utils.reconstruct-table-like(child, labeled: labeled(child.func()), conts)) } repetitions = nextrepetitions } else if type(child) == content and child.func() in ( pad, figure, quote, strong, emph, footnote, highlight, overline, underline, strike, smallcaps, sub, super, box, block, hide, move, scale, circle, ellipse, rect, square, table.cell, grid.cell, math.equation, heading, ) { let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, // Some functions (e.g. square) may have no body child.at("body", default: none), ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(utils.reconstruct(named: true, labeled: labeled(child.func()), child, cont)) } else { cover-arr.push(utils.reconstruct(named: true, labeled: labeled(child.func()), child, cont)) } repetitions = nextrepetitions } else if type(child) == content and child.func() == terms.item { // handle the terms item let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.description, ) let cont = conts.first() if repetitions <= index or not need-cover { result.push(terms.item(child.term, cont)) } else { cover-arr.push(terms.item(child.term, cont)) } repetitions = nextrepetitions } else if type(child) == content and child.func() == columns { // handle columns let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.body, ) let cont = conts.first() let args = if child.has("gutter") { (gutter: child.gutter) } let count = if child.has("count") { child.count } else { 2 } if repetitions <= index or not need-cover { result.push(columns(count, ..args, cont)) } else { cover-arr.push(columns(count, ..args, cont)) } repetitions = nextrepetitions } else if type(child) == content and child.func() == place { // handle place let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.body, ) let cont = conts.first() let fields = child.fields() let _ = fields.remove("alignment", default: none) let _ = fields.remove("body", default: none) let alignment = if child.has("alignment") { child.alignment } else { start } if repetitions <= index or not need-cover { result.push(place(alignment, ..fields, cont)) } else { cover-arr.push(place(alignment, ..fields, cont)) } repetitions = nextrepetitions } else if type(child) == content and child.func() == rotate { // handle rotate let (conts, nextrepetitions) = _parse-content-into-results-and-repetitions( self: self, need-cover: repetitions <= index, base: repetitions, index: index, child.body, ) let cont = conts.first() let fields = child.fields() let _ = fields.remove("angle", default: none) let _ = fields.remove("body", default: none) let angle = if child.has("angle") { child.angle } else { 0deg } if repetitions <= index or not need-cover { result.push(rotate(angle, ..fields, cont)) } else { cover-arr.push(rotate(angle, ..fields, cont)) } repetitions = nextrepetitions } else { if repetitions <= index or not need-cover { result.push(child) } else { cover-arr.push(child) } } } // clear the cover-arr when end if cover-arr.len() != 0 { result.push(cover(cover-arr.sum())) cover-arr = () } result-arr.push(result.sum(default: [])) } max-repetitions = calc.max(max-repetitions, repetitions) return (result-arr, max-repetitions) } // get negative pad for header and footer #let _get-negative-pad(self) = { let margin = self.page.margin if type(margin) != dictionary and type(margin) != length and type(margin) != relative { return it => it } let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false) if type(margin) == length or type(margin) == relative { return it => pad(x: -margin, cell(it)) } let pad-args = (:) if "x" in margin { pad-args.x = -margin.x } if "left" in margin { pad-args.left = -margin.left } if "right" in margin { pad-args.right = -margin.right } if "rest" in margin { pad-args.rest = -margin.rest } it => pad(..pad-args, cell(it)) } // get page extra args for show-notes-on-second-screen #let _get-page-extra-args(self) = { if self.show-notes-on-second-screen in (bottom, right) { let margin = self.page.margin assert( self.page.paper == "presentation-16-9" or self.page.paper == "presentation-4-3", message: "The paper of page should be presentation-16-9 or presentation-4-3", ) let page-width = if self.page.paper == "presentation-16-9" { 841.89pt } else { 793.7pt } let page-height = if self.page.paper == "presentation-16-9" { 473.56pt } else { 595.28pt } if type(margin) != dictionary and type(margin) != length and type(margin) != relative { return (:) } if type(margin) == length or type(margin) == relative { margin = (x: margin, y: margin) } if self.show-notes-on-second-screen == bottom { if "bottom" not in margin { assert("y" in margin, message: "The margin should have bottom or y") margin.bottom = margin.y } margin.bottom += page-height return (margin: margin, height: 2 * page-height) } else if self.show-notes-on-second-screen == right { if "right" not in margin { assert("x" in margin, message: "The margin should have right or x") margin.right = margin.x } margin.right += page-width return (margin: margin, width: 2 * page-width) } return (:) } else { return (:) } } #let _get-header-footer(self) = { let header = utils.call-or-display(self, self.page.at("header", default: none)) let footer = utils.call-or-display(self, self.page.at("footer", default: none)) // speaker note if self.show-notes-on-second-screen in (bottom, right) { assert( self.page.paper == "presentation-16-9" or self.page.paper == "presentation-4-3", message: "The paper of page should be presentation-16-9 or presentation-4-3", ) let page-width = if self.page.paper == "presentation-16-9" { 841.89pt } else { 793.7pt } let page-height = if self.page.paper == "presentation-16-9" { 473.56pt } else { 595.28pt } let show-notes = (self.methods.show-notes)(self: self, width: page-width, height: page-height) if self.show-notes-on-second-screen == bottom { footer += place( left + bottom, show-notes, ) } else if self.show-notes-on-second-screen == right { footer += place( left + bottom, dx: page-width, show-notes, ) } } // negative padding if self.at("zero-margin-header", default: true) or self.at("zero-margin-footer", default: true) { let negative-pad = _get-negative-pad(self) if self.at("zero-margin-header", default: true) { header = negative-pad(header) } if self.at("zero-margin-footer", default: true) { footer = negative-pad(footer) } } (header, footer) } /// Touying slide function, the core function of touying. It usually is used to create a slide with animation effects and works with `touying-slide-wrapper` function. /// /// Example: /// /// ``` /// #let slide( /// config: (:), /// repeat: auto, /// setting: body => body, /// composer: auto, /// ..bodies, /// ) = touying-slide-wrapper(self => { /// touying-slide(self: self, config: config, repeat: repeat, setting: setting, composer: composer, ..bodies) /// }) /// ``` /// /// - `config` is the configuration of the slide. You can use `config-xxx` to set the configuration of the slide. For more several configurations, you can use `utils.merge-dicts` to merge them. /// /// - `repeat` is the number of subslides. Default is `auto`,which means touying will automatically calculate the number of subslides. /// /// The `repeat` argument is necessary when you use `#slide(repeat: 3, self => [ .. ])` style code to create a slide. The callback-style `uncover` and `only` cannot be detected by touying automatically. /// /// - `setting` is the setting of the slide. You can use it to add some set/show rules for the slide. /// /// - `composer` is the composer of the slide. You can use it to set the layout of the slide. /// /// For example, `#slide(composer: (1fr, 2fr, 1fr))[A][B][C]` to split the slide into three parts. The first and the last parts will take 1/4 of the slide, and the second part will take 1/2 of the slide. /// /// If you pass a non-function value like `(1fr, 2fr, 1fr)`, it will be assumed to be the first argument of the `components.side-by-side` function. /// /// The `components.side-by-side` function is a simple wrapper of the `grid` function. It means you can use the `grid.cell(colspan: 2, ..)` to make the cell take 2 columns. /// /// For example, `#slide(composer: 2)[A][B][#grid.cell(colspan: 2)[Footer]] will make the `Footer` cell take 2 columns. /// /// If you want to customize the composer, you can pass a function to the `composer` argument. The function should receive the contents of the slide and return the content of the slide, like `#slide(composer: grid.with(columns: 2))[A][B]`. /// /// - `..bodies` is the contents of the slide. You can call the `slide` function with syntax like `#slide[A][B][C]` to create a slide. #let touying-slide( self: none, config: (:), repeat: auto, setting: body => body, composer: auto, ..bodies, ) = { if config != (:) { self = utils.merge-dicts(self, config) } assert(bodies.named().len() == 0, message: "unexpected named arguments:" + repr(bodies.named().keys())) let setting-with-auto-offset-for-heading(body) = { set heading(offset: self.at("slide-level", default: 0)) if self.at("auto-offset-for-heading", default: true) setting(body) } let composer-with-side-by-side(..args) = { if type(composer) == function { composer(..args) } else { components.side-by-side(columns: composer, ..args) } } let bodies = bodies.pos() // preambles let slide-preamble(self) = { if self.at("is-first-slide", default: false) { utils.call-or-display(self, self.at("preamble", default: none)) utils.call-or-display(self, self.at("default-preamble", default: none)) } [#metadata((kind: "touying-new-slide")) <touying-metadata>] // add headings for the first subslide if self.at("headings", default: ()) != () { place( hide({ set heading(offset: 0) let headings = self.at("headings", default: ()).map(it => if it.has("label") { if str(it.label) in ("touying:hidden", "touying:unnumbered", "touying:unoutlined", "touying:unbookmarked") { let fields = it.fields() let _ = fields.remove("label", default: none) let _ = fields.remove("body", default: none) if str(it.label) == "touying:hidden" { fields.numbering = none fields.outlined = false fields.bookmarked = false } if str(it.label) == "touying:unnumbered" { fields.numbering = none } if str(it.label) == "touying:unoutlined" { fields.outlined = false } if str(it.label) == "touying:unbookmarked" { fields.bookmarked = false } utils.label-it(heading(..fields, it.body), it.label) } else { it } } else { it }) headings.sum(default: none) }), ) } utils.call-or-display(self, self.at("slide-preamble", default: none)) utils.call-or-display(self, self.at("default-slide-preamble", default: none)) } // preamble for the subslides let subslide-preamble(self) = { if self.handout or self.subslide == 1 { slide-preamble(self) } [#metadata((kind: "touying-new-subslide")) <touying-metadata>] if self.at("enable-frozen-states-and-counters", default: true) and not self.handout and self.repeat > 1 { if self.subslide == 1 { // save the states and counters context { utils.saved-frozen-states.update(self.frozen-states.map(s => s.get())) utils.saved-default-frozen-states.update(self.default-frozen-states.map(s => s.get())) utils.saved-frozen-counters.update(self.frozen-counters.map(s => s.get())) utils.saved-default-frozen-counters.update(self.default-frozen-counters.map(s => s.get())) } } else { // restore the states and counters context { self .frozen-states .zip(utils.saved-frozen-states.get()) .map(pair => pair.at(0).update(pair.at(1))) .sum(default: none) self .default-frozen-states .zip(utils.saved-default-frozen-states.get()) .map(pair => pair.at(0).update(pair.at(1))) .sum(default: none) self .frozen-counters .zip(utils.saved-frozen-counters.get()) .map(pair => pair.at(0).update(pair.at(1))) .sum(default: none) self .default-frozen-counters .zip(utils.saved-default-frozen-counters.get()) .map(pair => pair.at(0).update(pair.at(1))) .sum(default: none) } } } utils.call-or-display(self, self.at("subslide-preamble", default: none)) utils.call-or-display(self, self.at("default-subslide-preamble", default: none)) } // update states for every page let page-preamble(self) = { [#metadata((kind: "touying-new-page")) <touying-metadata>] // 1. slide counter part // if freeze-slide-counter is false, then update the slide-counter if self.subslide == 1 { if not self.at("freeze-slide-counter", default: false) { utils.slide-counter.step() // if appendix is false, then update the last-slide-counter if not self.at("appendix", default: false) { utils.last-slide-counter.step() } } } utils.call-or-display(self, self.at("page-preamble", default: none)) utils.call-or-display(self, self.at("default-page-preamble", default: none)) } self.subslide = 1 // for single page slide, get the repetitions if repeat == auto { let (_, repetitions) = _parse-content-into-results-and-repetitions( self: self, base: 1, index: 1, ..bodies, ) repeat = repetitions } assert(type(repeat) == int, message: "The repeat should be an integer") self.repeat = repeat // page header and footer let (header, footer) = _get-header-footer(self) let page-extra-args = _get-page-extra-args(self) if self.handout { self.subslide = repeat let (conts, _) = _parse-content-into-results-and-repetitions( self: self, index: repeat, show-delayed-wrapper: true, ..bodies, ) header = page-preamble(self) + header set page(..(self.page + page-extra-args + (header: header, footer: footer))) setting-with-auto-offset-for-heading(subslide-preamble(self) + composer-with-side-by-side(..conts)) } else { // render all the subslides let result = () let current = 1 for i in range(1, repeat + 1) { self.subslide = i let (header, footer) = _get-header-footer(self) let delayed-args = if i == repeat { (show-delayed-wrapper: true) } let (conts, _) = _parse-content-into-results-and-repetitions(self: self, index: i, ..delayed-args, ..bodies) let new-header = page-preamble(self) + header // update the counter in the first subslide only result.push({ set page(..(self.page + page-extra-args + (header: new-header, footer: footer))) setting-with-auto-offset-for-heading(subslide-preamble(self) + composer-with-side-by-side(..conts)) }) } // return the result result.sum() } } /// Touying slide function. /// /// - `config` is the configuration of the slide. You can use `config-xxx` to set the configuration of the slide. For more several configurations, you can use `utils.merge-dicts` to merge them. /// /// - `repeat` is the number of subslides. Default is `auto`,which means touying will automatically calculate the number of subslides. /// /// The `repeat` argument is necessary when you use `#slide(repeat: 3, self => [ .. ])` style code to create a slide. The callback-style `uncover` and `only` cannot be detected by touying automatically. /// /// - `setting` is the setting of the slide. You can use it to add some set/show rules for the slide. /// /// - `composer` is the composer of the slide. You can use it to set the layout of the slide. /// /// For example, `#slide(composer: (1fr, 2fr, 1fr))[A][B][C]` to split the slide into three parts. The first and the last parts will take 1/4 of the slide, and the second part will take 1/2 of the slide. /// /// If you pass a non-function value like `(1fr, 2fr, 1fr)`, it will be assumed to be the first argument of the `components.side-by-side` function. /// /// The `components.side-by-side` function is a simple wrapper of the `grid` function. It means you can use the `grid.cell(colspan: 2, ..)` to make the cell take 2 columns. /// /// For example, `#slide(composer: 2)[A][B][#grid.cell(colspan: 2)[Footer]] will make the `Footer` cell take 2 columns. /// /// If you want to customize the composer, you can pass a function to the `composer` argument. The function should receive the contents of the slide and return the content of the slide, like `#slide(composer: grid.with(columns: 2))[A][B]`. /// /// - `..bodies` is the contents of the slide. You can call the `slide` function with syntax like `#slide[A][B][C]` to create a slide. #let slide( config: (:), repeat: auto, setting: body => body, composer: auto, ..bodies, ) = touying-slide-wrapper(self => { touying-slide(self: self, config: config, repeat: repeat, setting: setting, composer: composer, ..bodies) }) /// Touying empty slide function. /// /// - `config` is the configuration of the slide. You can use `config-xxx` to set the configuration of the slide. For more several configurations, you can use `utils.merge-dicts` to merge them. /// /// - `repeat` is the number of subslides. Default is `auto`,which means touying will automatically calculate the number of subslides. /// /// The `repeat` argument is necessary when you use `#slide(repeat: 3, self => [ .. ])` style code to create a slide. The callback-style `uncover` and `only` cannot be detected by touying automatically. /// /// - `setting` is the setting of the slide. You can use it to add some set/show rules for the slide. /// /// - `composer` is the composer of the slide. You can use it to set the layout of the slide. /// /// For example, `#slide(composer: (1fr, 2fr, 1fr))[A][B][C]` to split the slide into three parts. The first and the last parts will take 1/4 of the slide, and the second part will take 1/2 of the slide. /// /// If you pass a non-function value like `(1fr, 2fr, 1fr)`, it will be assumed to be the first argument of the `components.side-by-side` function. /// /// The `components.side-by-side` function is a simple wrapper of the `grid` function. It means you can use the `grid.cell(colspan: 2, ..)` to make the cell take 2 columns. /// /// For example, `#slide(composer: 2)[A][B][#grid.cell(colspan: 2)[Footer]] will make the `Footer` cell take 2 columns. /// /// If you want to customize the composer, you can pass a function to the `composer` argument. The function should receive the contents of the slide and return the content of the slide, like `#slide(composer: grid.with(columns: 2))[A][B]`. /// /// - `..bodies` is the contents of the slide. You can call the `slide` function with syntax like `#slide[A][B][C]` to create a slide. #let empty-slide( config: (:), repeat: auto, setting: body => body, composer: auto, ..bodies, ) = touying-slide-wrapper(self => { touying-slide(self: self, config: config, repeat: repeat, setting: setting, composer: composer, ..bodies) })
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/bibliography-full_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(paper: "a6", height: 160mm) #bibliography("/assets/files/works.bib", full: true)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/numberingx/0.0.1/numberingx.typ
typst
Apache License 2.0
// SPDX-License-Identifier: CC0-1.0 #import "numberingx_impl.typ": format, formatter
https://github.com/Arrata-TTRPG/Arrata-TTRPG
https://raw.githubusercontent.com/Arrata-TTRPG/Arrata-TTRPG/main/src/main.typ
typst
Other
// For formatting rules #import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( authors: ( "<NAME>", ), version: "CURRENT_VERSION", logo: "rat.png", ) #set page(numbering: "1") #counter(page).update(1) #include("sections/foreword.typ") #include("sections/introduction.typ") #include("sections/dice.typ") #include("sections/stats.typ") #include("sections/quirks.typ") #include("sections/characters.typ") #include("sections/credits.typ")
https://github.com/drupol/ipc2023
https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/demo.typ
typst
#import "imports/preamble.typ": * #focus-slide[ #set align(center + horizon) #set text(fill: white, font: "Virgil 3 YOFF") #uncover("1-")[ #fit-to-height(2em)[Hands-on] ] #set text(size:.5em) #set align(right) Please, reproduce this at home! ] #screencast-slide( new-section: "Hands-on", title: "Installation", url: "https://asciinema.org/a/H0WyHmdazHDxFcK8zFgA6myF0", preview: "../../../resources/screenshots/Screenshot_20231019_194440.png", caption: "Nix installation on Fedora" )[ #pdfpc.speaker-note(```md 1 min ```) ] #screencast-slide( title: "Scripting", url: "https://asciinema.org/a/dYo81YRrmRaibuVLERghDLbMk", preview: "../../../resources/screenshots/Screenshot_20231015_095404.png", caption: [Basic of `nix shell` command with `fastfetch` and `cowsay`] )[ #pdfpc.speaker-note(```md 1 min ```) ] #screencast-slide( title: "Scripting", url:"https://asciinema.org/a/MfbOmgDcnE1ul8jmQzVbTZ3W3", preview: "../../../resources/screenshots/Screenshot_20231015_095947.png", caption: [Basic shell script with `nix-shell`, with `fastfetch` and `cowsay`] )[ #pdfpc.speaker-note(```md 1 min 30 sec ```) ] #screencast-slide( title: "Scripting", url:"https://asciinema.org/a/POcTM0tkNUTswaYHFRevE3DJK", preview: "../../../resources/screenshots/Screenshot_20231012_102618.png", caption: "Basic shell script to fetch latest PHP versions from php.net" )[ #pdfpc.speaker-note(```md 1 min 20 sec ```) ] #slide(title: "nix-shell #1")[ #set align(center + horizon) #set text(size: .5em) #only(1)[ #v(3em) #figure( { set text(size: 1.5em) sourcefile( file: "shell.nix", lang: "nix", read("../../resources/sourcecode/shell.nix") ) }, caption: [ Source of `shell.nix` ] ) ] #only(2)[ #screencast-slide-body( url: "https://asciinema.org/a/PL8cPMX5pdlhTYF0aDyFrfHbh", preview: "../../../resources/screenshots/Screenshot_20231013_184400.png", caption: "Describing its development environment in a file" ) ] #pdfpc.speaker-note(```md 2 min 15 sec ```) ] #slide(title: "nix-build #1")[ #set align(center + horizon) #set text(size: .5em) #only(1)[ #v(1em) #figure( { set text(size: 1.5em) sourcefile( file: "docker-composer.nix", lang: "nix", read("../../resources/sourcecode/docker-composer.nix") ) }, caption: [ Source of `docker-composer.nix` ] ) ] #only(2)[ #screencast-slide-body( url: "https://asciinema.org/a/zHbcrKZWXE7PhdJCu1I8WPsG5", preview: "../../../resources/screenshots/Screenshot_20231013_185203.png", caption: "Building a Docker image containing Composer" ) ] #pdfpc.speaker-note(```md 2 min ```) ] #screencast-slide( title: "Nix flake #1", url:"https://asciinema.org/a/FObq9afNFDPRN5Ge9xkn9wWqA", preview: "../../../resources/screenshots/Screenshot_20231013_190033.png", caption: [Creation of a `flake.nix` file] )[ #pdfpc.speaker-note(```md 2 min 30 sec As soon as you commit those single 2 files in your project repository, you, your colleagues will be aligned on exactly the same versions of the software. Isn't this what we try to fix? Isn't this what we all want? No more "But it was working on my machine!" The Nix cli is full of useful commands related to those flake files, for example, to show what are the available outputs that this flake provides. In this particular case, we only have one development shell, but there can be many many many different outputs. ```) ] #screencast-slide( title: "Direnv #1", url:"https://asciinema.org/a/Zf00yVOm9c88P2kYDlxOcsvsq", preview: "../../../resources/screenshots/Screenshot_20231019_165947.png", caption: "Direnv with a Nix flake" )[ #pdfpc.speaker-note(```md 2 min All of this is great, but what if I want to share my stuff with others? Just because sharing is one of the core-values of open-source. Therefore, would it be possible to share my Nix shells programs with others? ```) ] #slide(title: "loophp/nix-shell")[ #set text(size: .5em) #figure( image("../../resources/screenshots/Screenshot_20231026_064256.png", height: 90%), caption: [ #link("https://github.com/loophp/nix-shell")[https://github.com/loophp/nix-shell] ] ) #pdfpc.speaker-note(```md Yes this is fully possible, see this project that I created. The naming is very bad, but basically it's a Nix flake that provides a development shell containing the tools a PHP developer needs. The cherry on the cake is that it provides an API to infer the proper version of PHP to use by looking at the `composer.json` file and spawing PHP with the required extensions. ```) ] #screencast-slide( title: "Advanced use of loophp/nix-shell", url:"https://asciinema.org/a/xoPSyMQMhIukgOrazyal1fR9O", preview: "../../../resources/screenshots/Screenshot_20231013_191719.png", caption: [Advanced usage with `loophp/nix-shell`] )[ #pdfpc.speaker-note(```md 3 min 30 sec ```) ] #screencast-slide( title: "PHP 5.6 and PHPStan", url:"https://asciinema.org/a/I12D06cTl9tBXDUBPPGQLZJcb", preview: "../../../resources/screenshots/Screenshot_20231023_192806.png", caption: [Use PHPStan with different version of PHP] )[ #pdfpc.speaker-note(```md 1 min 30 sec ```) ] #slide(title: "PHP/Composer builder in Nix", new-section: "Projects")[ #set text(size: .5em) #only(1)[ #figure( image("../../resources/screenshots/Screenshot_20231026_065658.png", height: 90%), caption: [ #link("https://github.com/NixOS/nixpkgs/pull/225401")[https://github.com/NixOS/nixpkgs/pull/225401] ] ) ] #only(2)[ #figure( image("../../resources/screenshots/Screenshot_20231026_070139.png", height: 90%), caption: [ #link("https://github.com/NixOS/nixpkgs/pull/261432")[https://github.com/NixOS/nixpkgs/pull/261432] ] ) #place(top + right, dx: 25pt, dy: 155pt)[ #rotate(-200deg)[ #image("../../resources/images/arrow.svg", width: 90pt), ] ] ] #only(3)[ #figure( { set text(size: 1.4em) sourcefile( file: "shell.nix", lang: "nix", read("../../resources/sourcecode/drupal.nix") ) }, caption: [ Source of `drupal.nix` ] ) ] #set text(size: 2em) #only(4)[ #screencast-slide-body( url: "https://asciinema.org/a/kwWzuPxGeeQChCdw0t6paSEkq", preview: "../../../resources/screenshots/Screenshot_20231026_071950.png", caption: "Building Drupal with Nix" ) ] #pdfpc.speaker-note(```md - One of the biggest achievement in Nix, beside being granted the core commiter rights not so long ago, is the PHP/Composer builder. Basically, it's a way to build PHP applications with Composer, in a reproducible way. - It was possible to do something similar before... but it was a pain. On this screenshot, you can see a contributor providing a pull-request to switch to the new PHP/Composer builder. Check out the amount of lines removed to understand. - I won't go into the details, but have a look on how it would be easy to package Drupal in Nix! When you execute this, it will create an entry in the Nix store containing a working Drupal. Of course, then you need to setup the webserver and so on, but this is a huge achievement. This is paving the way for bundling more reliable and secure PHP applications. - 1min screencast ```) ] #slide(title: "loophp/php-src-nix")[ #set text(size: .5em) #figure( image("../../resources/screenshots/Screenshot_20231026_065440.png", height: 90%), caption: [ #link("https://github.com/loophp/php-src-nix")[https://github.com/loophp/php-src-nix] ] ) #pdfpc.speaker-note(```md This project is the last ```) ]
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/tinymist-issue492.typ
typst
Apache License 2.0
"#spec_char.d8." For example "#spec_char.d8.a" For example
https://github.com/ntjess/typst-nsf-templates
https://raw.githubusercontent.com/ntjess/typst-nsf-templates/main/main-sbir-technical-volume.typ
typst
MIT License
#import "@preview/tablex:0.0.4": tablex, cellx, rowspanx #import "nsf-proposal.typ": * #show: template #show regex("(?i:\bxxx\b)"): box(fill: yellow)[ #set text(size: 1.25em) (UPDATE ME) ] #let note(..args) = { set par(justify: false) set text(size: 8pt, fill: blue) [~] drafting.margin-note(..args) } #title[NSF SBIR Phase I Proposal] #title[Volume 2: Technical Volume] = Identification and Significance of the Problem or Opportunity #instructions[ Define the specific technical problem or opportunity addressed and its importance. ] = Phase I Technical Objectives #instructions[ Provide an explicit, detailed description of the Phase I approach. If a Phase I option is required or allowed by the Component (refer to Component-specific instructions for of interest), describe appropriate research activities which would commence at the end of Phase I base period should the Component elect to exercise the option. The Statement of Work should indicate what tasks are planned, how and where the work will be conducted, a schedule of major events, and the final product(s) to be delivered. The Phase I effort should attempt to determine the technical feasibility of the proposed concept. The methods planned to achieve each objective or task should be discussed explicitly and in detail. This section should be a substantial portion of the Technical Volume. ] = Phase I Statement of Work #instructions[ Provide an explicit, detailed description of the Phase I approach. If a Phase I option is required or allowed by the Component (refer to Component-specific instructions for topic of interest), describe appropriate research activities which would commence at the end of Phase I base period should the Component elect to exercise the option. The Statement of Work should indicate what tasks are planned, how and where the work will be conducted, a schedule of major events, and the final product(s) to be delivered. The Phase I effort should attempt to determine the technical feasibility of the proposed concept. The methods planned to achieve each objective or task should be discussed explicitly and in detail. This section should be a substantial portion of the Technical Volume. ] = Related Work #instructions[ Describe significant activities directly related to the proposed effort, including any conducted by the principal investigator, the proposing firm, consultants, or others. Describe how these activities interface with the proposed project and discuss any planned coordination with outside sources. The Technical Volume must persuade evaluators of the proposer's awareness of the state of the art in the topic. Describe any previous work not directly related but similar to the proposed effort. Provide the following: (1) a short description, (2) the client for which work was performed (including the Government Point of Contact to be contacted including e-mail address and phone number), and (3) date of performance including project completion. ] = Relationship with Future Research or Research and Development #instructions[ (a) State the anticipated results of the proposed approach if the project is successful. (b) Discuss the significance of the Phase I effort in providing a foundation for a Phase II research or research and development effort. (c) Identify the applicable clearances, certifications and approvals required to conduct Phase II testing. Outline the plan for ensuring timely completion of stated authorizations in support of a Phase II research or research and development effort. ] = Commercialization Strategy #instructions[ Describe in approximately one page your company's strategy for commercializing this technology in DoD, other Federal Agencies, and/or private sector markets. Provide specific information on the market need the technology will address and the size of the market. Also include a schedule showing the quantitative commercialization results from the project that your company expects to achieve. ] = Key Personnel #instructions[ Identify key personnel who will be involved in the Phase I effort including information on directly related education and experience. A concise technical resume of the principal investigator, including a list of relevant publications (if any), must be included (Please do not include Privacy Act Information). All resumes will count toward the page limit for Volume 2, as specified in the Component-specific instructions. ] == Principal Investigator Name #let prep-table = ProfessionalPreparationTable() #let add-info = prep-table.add-info #add-info( is-first: true, [Undergraduate Institution(s)], institutions: [University of xxx], locations: [City, State], majors: [Major], degrees: [Degree, Year] ) #add-info( [Graduate Institution(s)], institutions: [University of xxx], locations: [City, State], majors: [Major], degrees: [Degree, Year] ) #prep-table.table === Relevant Experience #instructions[ A concise description of the principal investigator's relevant technical experience and its application to this topic. ] === Relevant Awards or Patents #instructions[ List any awards received or patents granted or applications submitted for work related to this topic. ] === Relevant Publications == Next Relevant Personnel #instructions[ Repeat this format as necessary to address the qualifications of all key personnel. ] = Foreign Citizens #instructions[ Identify any foreign citizens or individuals holding dual citizenship expected to be involved on this project as a direct employee, subcontractor, or consultant. For these individuals, please specify their country of origin, the type of visa or work permit under which they are performing and an explanation of their anticipated level of involvement on this project. Proposers frequently assume that individuals with dual citizenship or a work permit will be permitted to work on an SBIR project and do not report them. This is not necessarily the case and a proposal will be rejected if the requested information is not provided. Therefore, firms should report any and all individuals expected to be involved on this project that are considered a foreign national as defined in the DoD SBIR/STTR Broad Agency Announcement. You may be asked to provide additional information during negotiations in order to verify the foreign citizen’s eligibility to participate on a SBIR contract. Supplemental information provided in response to this paragraph will be protected in accordance with the Privacy Act (5 U.S.C. 552a), if applicable, and the Freedom of Information Act (5 U.S.C. 552(b)(6)). Note: If no foreign nationals will be involved in proposed work, the word “None” can be substituted for the table. ] #let c = cellx.with(align: center) // #unjustified-table( // columns: (1fr,) * 5, // c[Name], // c[Foreign National\ (Yes/No)], // c[Country of Origin], // c[Type of Visa or Work Permit], // c[Level of Involvement] // )[ // Person A // ] None. = Facilities and Equipment #instructions[ Describe available instrumentation and physical facilities necessary to carry out the Phase I effort. Justify equipment purchases in this section and include detailed pricing information in the Cost Volume. State whether or not the facilities where the proposed work will be performed meet environmental laws and regulations of federal, state (name), and local Governments for, but not limited to, the following groupings: airborne emissions, waterborne effluents, external radiation levels, outdoor noise, solid and bulk waste disposal practices, and handling and storage of toxic and hazardous materials. ] = Subcontractors and Consultants #instructions[ *SBIR only:* Involvement of a university or other subcontractors or consultants in the project may be appropriate. A minimum of two-thirds of the research and/or analytical work in Phase I, as measured by direct and indirect costs, must be carried out by the proposing small business firm, unless otherwise approved in writing by the Contracting Officer. SBIR efforts may include subcontracts with Federal Laboratories and Federally Funded Research and Development Centers (FFRDCs). A waiver is no longer required for the use of Federal Laboratories and FFRDCs; however, proposers must certify their use of such facilities in Volume 1: Proposal Cover Sheet. Subcontracts with other Federal organizations are not permitted. Note that universities cannot publically release information related to Export Controlled/ITAR restricted topics. (Refer to the DoD SBIR/STTR Broad Agency Announcement for detailed eligibility requirements as it pertains to the use of subcontractors/consultants.) ] #instructions[ *STTR only:* Involvement of a Research Institution in the project is required. A minimum of 40% of the research and/or analytical work in Phase I, as measured by direct and indirect costs, must be conducted by the proposing small business firm, and a minimum of 30% of the research and/or tasks in Phase I, as measured by direct and indirect costs, must be conducted by a single Research Institution. STTR efforts may include subcontracts with Federally Funded Research and Development Centers (FFRDCs). A waiver is no longer required for the use of Federal Laboratories but they do not qualify as a Research Partner; proposers may only subcontract to Federal Laboratories within the remaining 30% and must certify their use of such facilities in Volume 1: Proposal Cover Sheet. Subcontracts with other Federal organizations are not permitted. Note that universities cannot publically release information related to Export Controlled/ITAR restricted topics. (Refer to the DoD SBIR/STTR Broad Agency Announcement for detailed eligibility requirements as it pertains to the use of subcontractors/consultants. ] = Prior, Current or Pending Support of Similar Proposals or Awards #instructions[ If a proposal submitted in response to this BAA is substantially the same as another proposal that was funded, is now being funded, or is pending with another Federal Agency, or another DoD Component or DARPA, you must reveal this on Volume 1: Proposal Cover Sheet and provide the following information: #set enum(numbering: "a)") + Name and address of the Federal Agency(s) or DoD Component to which a proposal was submitted, will be submitted, or from which an award is expected or has been received. + Date of proposal submission or date of award. + Title of proposal. + Name and title of principal investigator for each proposal submitted or award received. + Title, number, and date of BAA(s) or solicitation(s) under which the proposal was submitted, will be submitted, or under which award is expected or has been received. + If award was received, provide contract number. + Specify the applicable topics for each proposal submitted or award received. Note: If this does not apply, state in the proposal "No prior, current, or pending support has been provided for proposed work." ] = Technical Data Rights #instructions[ Rights in technical data, including software, developed under the terms of any contract resulting from proposals submitted in response to this BAA generally remain with the contractor, except that the Government obtains a royalty-free license to use such technical data only for Government purposes during the period commencing with contract award and ending twenty years after completion of the project under which the data were generated. This data must be marked with the restrictive legend specified in DFARS 252.227-7018 Class Deviation 2020-O0007. Upon expiration of the twenty-year restrictive license, the Government has unlimited rights in the SBIR data. During the license period, the Government may not release or disclose SBIR data to any person other than its support services contractors except: (1) For evaluation purposes; (2) As expressly permitted by the contractor; or (3) A use, release, or disclosure that is necessary for emergency repair or overhaul of items operated by the Government. See DFARS clause 252.227-7018 Class Deviation 2020-O0007 "Rights in Noncommercial Technical Data and Computer Software – Small Business Innovation Research (SBIR) Program." If a proposer plans to submit assertions in accordance with DFARS 252.227-7017 Class Deviation 2020-O0007, those assertions must be identified and assertion of use, release, or disclosure restriction MUST be included with your proposal submission. The contract cannot be awarded until assertions have been approved. Please note that only the table is included in the page limitation; any supporting data concerning the contract/grant number and awarding agency, as well as planned use or need of the data asserted, can be provided in Volume 5, Supporting Documents. The following instructions apply to the fields in the table below (Identification and Assertion of Restrictions on the Government's Use, Release, or Disclosure of Technical Data or Computer Software). + For technical data (other than computer software documentation) pertaining to items, components, or processes developed at private expense, identify both the deliverable technical data and each such item, component, or process. For computer software or computer software documentation identify the software or documentation. + Generally, development at private expense, either exclusively or partially, is the only basis for asserting restrictions. For technical data, other than computer software documentation, development refers to development of the item, component, or process to which the data pertain. The Government's rights in computer software documentation generally may not be restricted. For computer software, development refers to the software. Indicate whether development was accomplished exclusively or partially at private expense. If development was not accomplished at private expense, or for computer software documentation, enter the specific basis for asserting restrictions. + Enter asserted rights category (e.g., Government purpose license rights from a prior contract, rights in SBIR/STTR data generated under another contract, limited, restricted, or government purpose rights under this or a prior contract, or specially negotiated licenses). + Corporation, individual, or other person, as appropriate. + Enter “none” when all data or software will be submitted without restrictions. ] = Identification and Assertion of Restrictions on the Government's Use, Release, or Disclosure of Technical Data or Computer Software _The Offeror asserts for itself, or the persons identified below, that the Government's rights to use, release, or disclose the following technical data or computer software should be restricted:_ #unjustified-table( columns: (1fr,) * 4, c[Deliverable Technical Data or Computer Software], c[Item, Component, or Process Developed at Private Expense], c[Asserted Rights Category], c[Corporation, Individual, or Other Person] )[ ] #instructions[ Completion of this table and submission of the proposal constitutes signature for the information listed in the table above. ]
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/组合数学/ch1-鸽巢原理.typ
typst
#import "../../lib.typ": * = 鸽巢原理 == 鸽巢原理简单形式 #showybox()[ 如果要把n+1 个物体放进n个盒子,那么至少有一个盒子包含两个或更多的物体。 ] #showybox(title: [中国剩余定理])[ 设m和n是互素的正整数,并设a和b为整数,其中$0≤a≤m-1$以及 $0≤b≤n-1$。于是,存在正整数x,使得x除以m 的余数为a,并且x除以n 的余数为b;即x可以写成$x=p*m+a$的同时又可写成$x=q*n+b$ 的形式,这里,p和q是两个整数。 ] == 鸽巢原理加强版 #showybox()[ 设 $q_1,q_2$,是正整数。如果将$q_1+q_2+q_3+……+q_n-n+1$个物体放入n个盒子内,那么或者第一个盒子至少含有$q_1$个物体,或者第二个盒子至少含有$q_2$个物体,…,或者第n个盒子至少含有$q_n$个物体。 ] #showybox(title: [推论])[ 设n和r都是正整数。如果把$n(r-1)+1$个物体分配到n个盒子中,那么至少有一个盒子含有r个或更多的物体。 可以用另一种方法陈述这一推论中的结论,即平均原理: 如果n个非负整数$m_1,m_2,……,m_n$的平均数大于$r-1$,即$ (m_1+m_2+...+m_n)/n ≥ r - 1 $ 那么至少有一个整数大于或等于r。 ] #showybox(title: [一个不同的平均定理])[ 如果n个非负整数$m_1,m_2,……,m_n$的平均数小于r+1,即$ (m_1+m_2+...+m_n)/n ≤ r - 1 $ 那么其中至少有一个整数小于 r+1。 ] #showybox(title: [另外一个平均定理])[ 如果n个非负整数$m_1,m_2,……,m_n$的平均数至少等于r,那么这n个整数$m_1,m_2,……,m_n$至少有一个满足$m_i≥r$ ] #pagebreak() == 课后习题 #showybox( title: [课后习题] )[ @ch1 ]
https://github.com/howardlau1999/sysu-thesis-typst
https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/template.typ
typst
MIT License
#import "functions/numbering.typ": * #import "functions/outline.typ": * #import "functions/style.typ": * #import "functions/helpers.typ": * #import "functions/underline.typ": * #import "functions/codeblock.typ": * #import "functions/figurelist.typ": * #import "functions/booktab.typ": * #import "info.typ": * #import "custom.typ": * #let conf( outlinedepth: 3, blind: false, listofimage: true, listoftable: true, listofcode: true, alwaysstartodd: true, doc, ) = { set page("a4", header: locate(loc => { [ #set text(字号.五号) #set align(center) #if partcounter.at(loc).at(0) < 10 { // Handle the first page of Chinese abstract specailly let headings = query(selector(heading).after(loc), loc) let next_heading = if headings == () { () } else { headings.first().body.text } if next_heading == "摘要" and calc.odd(loc.page()) { [ #align(center, 中文页眉) #v(-1em) #line(length: 100%) ] } } else if partcounter.at(loc).at(0) > 20 { } else { if calc.even(loc.page()) { [ #align(center, 中文页眉) #v(-1em) #line(length: 100%) ] } else { let footers = query(selector(<__footer__>).after(loc), loc) let elems = if footers == () { () } else { query( heading.where(level: 1).before(footers.first().location()), footers.first().location() ) } if elems == () { } else { let el = elems.last() [ // #let numbering = if el.numbering == chinesenumbering { // chinesenumbering(..counter(heading).at(el.location()), location: el.location()) // } else if el.numbering != none { // numbering(el.numbering, ..counter(heading).at(el.location())) // } // #if numbering != none { // numbering // h(0.5em) // } #中文页眉 #v(-1em) #line(length: 100%) ] } } } ] }), footer: locate(loc => { [ #set text(字号.五号) #set align(center) #if query(selector(heading).before(loc), loc).len() < 2 or query(selector(heading).after(loc), loc).len() == 0 { // Skip cover, copyright and origin pages } else { let headers = query(selector(heading).before(loc), loc) let part = partcounter.at(headers.last().location()).first() [ #if part < 20 { numbering("I", counter(page).at(loc).first()) } else { str(counter(page).at(loc).first()) } ] } #label("__footer__") ] }), ) set text(字号.一号, font: 字体.宋体, lang: "zh") set align(center + horizon) set heading(numbering: chinesenumbering) set figure( numbering: (..nums) => locate(loc => { if appendixcounter.at(loc).first() < 10 { numbering("1.1", chaptercounter.at(loc).first(), ..nums) } else { numbering("A.1", chaptercounter.at(loc).first(), ..nums) } }) ) set math.equation( numbering: (..nums) => locate(loc => { set text(font: 字体.宋体) if appendixcounter.at(loc).first() < 10 { numbering("(1.1)", chaptercounter.at(loc).first(), ..nums) } else { numbering("(A.1)", chaptercounter.at(loc).first(), ..nums) } }) ) set list(indent: 2em) set enum(indent: 2em) show strong: it => text(font: 字体.黑体, weight: "semibold", it.body) show emph: it => text(font: 字体.楷体, style: "italic", it.body) show par: set block(spacing: 行距) show raw: set text(font: 字体.代码) show heading: it => [ // Cancel indentation for headings of level 2 or above #set par(first-line-indent: 0em) #let sizedheading(it, size) = [ #set text(size) #v(2em) #if it.numbering != none { strong(counter(heading).display()) h(0.5em) } #strong(it.body) #v(1em) ] #if it.level == 1 { if not it.body.text in ("ABSTRACT", "学位论文使用授权说明") { pagebreak(weak: true) } locate(loc => { if it.body.text == "摘要" { partcounter.update(10) counter(page).update(1) } else if it.numbering != none and partcounter.at(loc).first() < 20 { partcounter.update(20) counter(page).update(1) } }) if it.numbering != none { chaptercounter.step() } footnotecounter.update(()) imagecounter.update(()) tablecounter.update(()) rawcounter.update(()) equationcounter.update(()) set align(center) sizedheading(it, 字号.三号) } else { if it.level == 2 { sizedheading(it, 字号.四号) } else if it.level == 3 { sizedheading(it, 字号.中四) } else { sizedheading(it, 字号.小四) } } ] show figure: it => [ #set align(center) #if not it.has("kind") { it } else if it.kind == image { it.body [ #set text(字号.五号) #it.caption ] } else if it.kind == table { [ #set text(字号.五号) #it.caption ] it.body } else if it.kind == "code" { [ #set text(字号.五号) #it.caption ] it.body } ] show ref: it => { if it.element == none { // Keep citations as is it } else { // Remove prefix spacing h(0em, weak: true) let el = it.element let el_loc = el.location() if el.func() == math.equation { // Handle equations link(el_loc, [ 式 #chinesenumbering(chaptercounter.at(el_loc).first(), equationcounter.at(el_loc).first(), location: el_loc, brackets: true) ]) } else if el.func() == figure { // Handle figures if el.kind == image { link(el_loc, [ 图 #chinesenumbering(chaptercounter.at(el_loc).first(), imagecounter.at(el_loc).first(), location: el_loc) ]) } else if el.kind == table { link(el_loc, [ 表 #chinesenumbering(chaptercounter.at(el_loc).first(), tablecounter.at(el_loc).first(), location: el_loc) ]) } else if el.kind == "code" { link(el_loc, [ 代码 #chinesenumbering(chaptercounter.at(el_loc).first(), rawcounter.at(el_loc).first(), location: el_loc) ]) } } else if el.func() == heading { // Handle headings if el.level == 1 { link(el_loc, chinesenumbering(..counter(heading).at(el_loc), location: el_loc)) } else { link(el_loc, [ 节 #chinesenumbering(..counter(heading).at(el_loc), location: el_loc) ]) } } } } include "templates/cover.typ" include "templates/cover-no-emblem.typ" locate(loc => { if alwaysstartodd { pagebreak() } }) set align(left + top) set text(字号.小四) include "templates/declaration.typ" locate(loc => { if alwaysstartodd { pagebreak() } }) include "templates/abstract-cn.typ" pagebreak() locate(loc => { if alwaysstartodd and calc.even(loc.page()) { pagebreak() } include "templates/abstract-en.typ" }) pagebreak() locate(loc => { if alwaysstartodd and calc.even(loc.page()) { pagebreak() } chineseoutline( title: "目录", depth: outlinedepth, indent: true, ) }) if listofimage { listoffigures(title: "插图目录", kind: image) } if listoftable { listoffigures(title: "表格目录", kind: table) } if listofcode { listoffigures(title: "代码目录", kind: "code") } set align(left + top) par(justify: true, first-line-indent: 2em, leading: 行距)[ #doc ] if not blind { par(justify: true, first-line-indent: 2em, leading: 行距)[ #heading(numbering: none, "致谢") #include "chapters/acknowledgement.typ" ] partcounter.update(30) heading(numbering: none, 学校 + "学位论文原创性声明和使用授权说明") align(center)[#heading(level: 2, numbering: none, outlined: false, "原创性声明")] par(justify: true, first-line-indent: 2em, leading: 行距)[ 本人郑重声明:所呈交的毕业论文(设计),是本人在导师的指导下,独立进行研究工作所取得的成果。除文中已经注明引用的内容外,本论文(设计)不包含任何其他个人或集体已经发表或撰写过的作品成果。对本论文(设计)的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本论文(设计)的知识产权归属于培养单位。本人完全意识到本声明的法律结果由本人承担。 #v(1em) #align(right)[ 论文作者签名 #h(5em) 日期: #h(2em) 年 #h(2em) 月 #h(2em) 日 ] #align(center)[#heading(level: 2, numbering: none, outlined: false, "学位论文使用授权说明")] #v(-0.33em, weak: true) #align(center)[#text(字号.五号)[(必须装订在提交学校图书馆的印刷本)]] #v(字号.小三) 本人完全了解#(学校)关于收集、保存、使用学位论文的规定,即: - 按照学校要求提交学位论文的印刷本和电子版本; - 学校有权保存学位论文的印刷本和电子版,并提供目录检索与阅览服务,在校园网上提供服务; - 学校可以采用影印、缩印、数字化或其它复制手段保存论文; - 因某种特殊原因须要延迟发布学位论文电子版,授权学校 #box[#rect(width: 9pt, height: 9pt)] 一年 / #box[#rect(width: 9pt, height: 9pt)] 两年 / #box[#rect(width: 9pt, height: 9pt)] 三年以后,在校园网上全文发布。 #align(center)[(保密论文在解密后遵守此规定)] #v(1em) #align(right)[ 论文作者签名 #h(5em) 导师签名 #h(5em) 日期: #h(2em) 年 #h(2em) 月 #h(2em) 日 ] ] } }
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/06-automated-modularization/05-conclusion.typ
typst
== Conclusion In this chapter, we presented the state of the art in automated microservice modularization, and answered the research questions posed in the introduction. #link(<research_question_2>)[*Research Question 2*]: What are the existing approaches for (semi-)automated microservice candidate identification in monolith codebases? We identified 43 approaches for (semi-)automated modularization in the literature. The majority the approaches are based on static analysis of the source code, sometimes enriched with information acquired through dynamic analysis of the application. The other approaches use the requirements and design documents of the application to identify microservice candidates. Clustering algorithms are a popular choice for microservice candidate identification, with more than 40% of the approaches using them. The other big groups of algorithms are graph algorithms and evolutionary algorithms, taking up 17% of the approaches each. The microservice candidates are evaluated using a variety of metrics, with the cohesion and coupling metrics being the clear winners in the literature. Other metrics used by several publications are the size of the microservices, the complexity, and resource usage.
https://github.com/hash-roar/typst-math-template
https://raw.githubusercontent.com/hash-roar/typst-math-template/main/README.md
markdown
# math-template this is a template for math homework,thesis,report,etc. ## simple article if you want a quick start, you can use typst_simple_thesis template. ![image](./typst_simple_thesis/typst_simple_thesis.png) ## two column thesis if you want a good looking two column thesis, you can use two_column_thesis template. <!-- insert image --> ![image](./two_clolumn_thesis/two_column_thesis.png)
https://github.com/yonatankremer/matrix-utils
https://raw.githubusercontent.com/yonatankremer/matrix-utils/main/src/matrix2.typ
typst
MIT License
#import "complex.typ": * #let _mform(m) = { let con = m.map(x => x.map(y => y)) return math.mat(..con) } #let _munform(m) = { if m.has("rows") { return m.at("rows") } return _munform(m.body) } #let _mtrans-content(m) = { let i = 0 let j = 0 while i < m.at(0).len() { while j < m.len() { let temp = m.at(j).at(i) m.at(j).at(i) = m.at(i).at(j) m.at(i).at(j) = temp j += 1 } i += 1 } return m } #let _minit(m) = { let dic = ("type", "matrix") let rows = _munform(m) let first-len = rows.at(0).len() assert(rows.all(x => x.len() == first-len)) dic.insert("rows", rows) dic.insert("cols", _mtrans(rows)) dic.insert("x", rows.at(0).len()) dic.insert("y", rows.len()) return dic } #let mrows(m) = _minit(m).at("rows") #let mrow(m,n) = mrows(m).at(n) #let mcols(m) = _minit(m).at("cols") #let mcol(m,n) = mcols(m).at(n) #let mget(m,x,y) = mcols(m).at(x).at(y) #let my(m) = _munform(m).len() #let mx(m) = _munform(m).at(0).len() #let mtrans(m) = _mform(_mtrans-content(_munform(m))) #let mconj(m) = _mform(_mtrans-content(_munform(m)).map(row => row.map(col => cconj(col)))) #let mfill(x,y,n) = { let row = 0 let new = (()) while row < y { let col = 0 let cur = () while col < x { cur.push(n) col += 1 } new.push(cur) row += 1 } return _mform(new) } #let mzero(x,y) = { mfill(x,y,0) } #let miden(x,y) ={ let m = _munform(mzero(x,y)) let row = 0 while row < y and row < x { m.at(row).at(row) = 1 row += 1 } return _mform(m) } #let madd(l,r) = { let lx = mx(l) let ly = my(l) let rx = mx(r) let ry = my(r) assert(lx == rx and ly == ry, message: "Matrix dimensions must match") l = _munform(l) r = _munform(r) let row = 0 let new = _munform(mzero(lx, ly)) while row < ly { let col = 0 while col < lx { new.at(row).at(col) = cadd(l.at(row).at(col), r.at(row).at(col)) col += 1 } row += 1 } return _mform(new) } #let mrow-switch(m,fst,snd) = { let rows = _munform(m) let temp = rows.at(fst) rows.at(fst) = rows.at(snd) rows.at(snd) = temp return _mform(rows) } #let mrow-mul(m,row,scalar) = { m = _munform(m) let new = m.at(row).map(x => cmul($#x$, $#scalar$)) m.at(row) = new return _mform(m) } #let mrow-add(m,fst,snd,scalar) = { m = _munform(m) let row1 = m.at(fst) let row2 = m.at(snd) let i = 0 while i < row1.len() { row1.at(i) = cadd(row1.at(i), cmul(row2.at(i), scalar)) i += 1 } m.at(fst) = row1 return _mform(m) }
https://github.com/AHaliq/CategoryTheoryReport
https://raw.githubusercontent.com/AHaliq/CategoryTheoryReport/main/chapters/chapter3/mandatory.typ
typst
#import "../../preamble/lemmas.typ": * #import "../../preamble/catt.typ": * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #exercise("1 from wk2")[Show that every poset considered as a category has equalizers and coequalizers of all pairs of morphisms] A poset as a category, has objects as elements of the poset and morphisms as witness of the ordering relation. Thus for any two morphisms $f,g: A -> B$ in the poset #grid( columns: (1fr, 1fr), align: (left, left), [ #figure( diagram( cell-size: 10mm, $ E edge("r", e, >->) & A #edge("r", $f$, "->", shift: 3pt) #edge("r", $g$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & B \ Z edge("u", u, "-->") edge("ur", z, ->) $, ), ) $e$ is an equzlier when $E = A and B$ greatest lower bound since for any other $Z$ it will then unqiuely be $Z <= E$ such that $arr(u,Z,E)$ ], [ #figure( diagram( cell-size: 10mm, $ A #edge("r", $f$, "->", shift: 3pt) #edge("r", $g$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & B edge("r", q, ->>) edge("dr", z, ->) & Q edge("d", u, "-->") \ & & Z $, ), ) $q$ is a coequalizer when $Q = A or B$ least upper bound since for any other $Z$ it will then unqiuely be $Z >= Q$ such that $arr(u,Q,Z)$ ], ) Moreover from the definition of the morphisms in the category we know that if there are parallel morphisms they have to be equal. #exercise("2 from wk2")[Let the functor $arr(cal(F), bb(C), bb(D))$ be an isomorphism of categories. Show the following.] #proof(name: [if $bb(C)$ has equalizers so does $bb(D)$ and $cal(F)$ preserves them.])[ an equalizer has the following UMP $ "UMP"(f,g,z) = u $ thus, we know $F(u)$ is unique by the composition preserving property of functors $ "UMP"(F(f), F(g), F(z)) &= F(u) $ ] #proof(name: [if $bb(C)$ has coequalizers so does $bb(D)$ and $cal(F)$ preserves them.])[ by duality of the above argument, so does coequalizers. ] #exercise("3 from wk2")[Let $bb(C)$ be a category and $X$ and object of $bb(C)$. Show the following. If $bb(C)$ has equalizers so does $slice(bb(C),X)$] #figure( diagram( cell-size: 10mm, $ & X edge("dl", x_Z, ->) edge("d", x_A, ->) edge("dr", x_B, ->) \ E edge("r", e, >->) & A #edge("r", $f$, "->", shift: 3pt) #edge("r", $g$, "->", shift: -3pt, label-anchor: "north", label-sep: 0em) & B \ Z edge("u", u, "-->") edge("ur", z, ->) $, ), ) $ "UMP"(f,g,z) &= u $ since the morphisms of the slice categories are also the morphisms in the underlying category, the equalizer in the slice category is the same as the equalizer in the underlying category. This is only true if $X$ has a morphism to all objects of the equalizer. *Note*: we will move mandatory assignment for week 3 to week 4 since most of them are on pullbacks which is the next chapter.
https://github.com/swablab/documents
https://raw.githubusercontent.com/swablab/documents/main/werkstatt-agb.typ
typst
Creative Commons Zero v1.0 Universal
#import "templates/tmpl_doc.typ": tmpl_doc #show: doc => tmpl_doc( title: "Allgemeine Geschäftsbedingungen (AGB)", changes: ( [v1.0], [23.06.2023], [erste Fassung], ), doc, ) = Vertragsgegenstand + Der swablab e.V. stellt dem Nutzer #footnote[Es sind stets Personen männlichen und weiblichen Geschlechts gleichermaßen gemeint; aus Gründen der einfacheren Lesbarkeit wird im Folgenden nur die männliche Form verwendet.] Räumlichkeiten, Werkzeug und Maschinen zur entgeltlichen Nutzung zur Verfügung. Mit Unterschrift des Haftungsausschluss bzw. bereits mit Betreten der Werkstatt erkennt der Nutzer die Geltung dieser AGB an. + Der Nutzer ist innerhalb seiner Mitgliedschaft im swablab e.V. oder nach Begleichung einer Tagespauschale berechtigt, während der Öffnungszeiten und entsprechend der allgemeinen Nutzungsbedingungen sowie der ausgehängten Werkstatt-Regeln die zur Verfügung stehenden Einrichtungen des swablab e.V. in dessen Räumlichkeiten zu nutzen. = Geltung der Vertragsbedingungen + Sämtliche Angebote und Leistungen gegenüber dem Nutzer erfolgen ausschließlich aufgrund dieser allgemeinen Geschäftsbedingungen. + Es gelten ferner die Werkstatt-Regeln, die in den Räumlichkeiten des swablab e.V. ausgehängt sind. + Die Vertragsdauer endet mit Ablauf der jeweiligen täglichen Nutzung bzw. mit Kündigung der Mitgliedschaft im swablab e.V. = Gebühren + Der Rechnungsbetrag über die Tagespauschale in Höhe von 9€ (ermäßigt: 5€) für Nichtmitglieder des swablab e.V. sind sofort und vor Beginn der Arbeit zu begleichen. Kosten für Materialkäufe, Workshops, Einweisungen, entgeltliche Veranstaltungen oder alle anderen Waren und Dienstleistungen sind sofort und vor dem Verlassen der Räumlichkeiten zu entrichten. Käufliche Waren bleiben bis zur vollständigen Bezahlung Eigentum des Verkäufers. Aus den Forderungen des Mietverhältnisses oder dem Verkauf von Waren und Dienstleistungen steht dem Vermieter ein Vermieterpfandrecht an den Mietgegenständen zu, die sich in den Vermietungsräumlichkeiten befinden. Der Vermieter beruft sich ggf. auf §§ 562 ff. BGB und weitere Bestimmungen des BGB und kann das Pfandrecht sofort ausüben. + Die Voraussetzungen für gewährte Ermäßigungen (Kinder, Schüler, Auszubildende, Studenten, u.ä.) sind durch geeignete Unterlagen nachzuweisen. + Kosten für Materialkäufe oder alle anderen Waren und Dienstleistungen sind selbstständig in den dafür vorgesehenen Kassen zu entrichten. Preise sind dementsprechend ausgehängt. = Öffnungszeiten / Schließungen + #[Der swablab e.V. behält sich vor, in zumutbarer Weise und zumutbarem Umfang - die Öffnungszeiten zu ändern, - kurzfristige Schließungen im Falle von Mangel an ehrenamtlicher Personalkapazität, - kurzfristige Schließungen im Falle technischer Revisionen oder Reparatur- und Wartungsarbeiten vorzunehmen, tageweise Teilbereiche oder den Betrieb insgesamt anlässlich von speziellen Veranstaltungen nach vorheriger Ankündigung zu schließen.] + Ein Vereinsmitglied des swablab e.V. hat diesbezüglich keinen Anspruch auf Minderung der Mitgliedsbeiträge, da diese Einschränkungen bereits in der Beitragskalkulation zugunsten des Nutzers berücksichtigt sind. = Pflichten des swablab e.V. + Der swablab e.V. stellt die Werkzeuge gegen Entgelt zur Verfügung. Weiteres Werkzeug kann der swablab e.V. auf Anfrage zur Verfügung stellen, ein Anspruch hierauf besteht nicht. + Alle Preise und Konditionen werden dem Nutzer transparent dargestellt und bei Bedarf erläutert. = Pflichten des Mieters + Den Anweisungen des Vorstands des swablab e.V. ist unbedingt und ohne Ausnahme Folge zu leisten. + *Gefahrenübergang* - Das Betreten der Werkstatt geschieht auf eigene Gefahr, ganz gleich von wem und aus welchem Grund die Werkstatt betreten oder benutzt werden. Grundsätzlich und ausnahmslos besteht in den gesamten Räumen Rauchverbot. Die Nutzung bestimmter ausgewiesener Werkzeuge und Maschinen bedarf separater Erlaubnis, welche jeweils durch Unterweisung, Schulung oder Kenntnisnachweis durch den swablab e.V. erteilt wird. Auch nach erfolgter Einweisung verbleibt alle Verantwortung für die sachgemäße und sichere Handhabung des jeweiligen Geräts beim Nutzer. + *Eignung* - Wer nicht die nötigen körperlichen oder geistigen Fähigkeiten besitzt, bestimmte Tätigkeiten auszuführen oder Einrichtungsgegenstände zu bedienen (bspw. durch Einfluss von Alkohol oder anderen Sucht- und Betäubungsmitteln) hat keinen Anspruch auf die Nutzung und kann unter entsprechenden Umständen der Werkstatt verwiesen werden. Menschen mit eingeschränkten Fähigkeiten aufgrund von Alter, Behinderung oder Krankheit müssen dies dem Vermieter bei Vertragsschluss offenlegen und dürfen entsprechende Maschinen nur unter Aufsicht bedienen. + *Sauberkeit* - Der Arbeitsplatz und die Werkzeuge sind in einwandfreiem Zustand und gereinigt nach Nutzung an den dafür vorhergesehenen Lagerplatz zurück zu legen. Muss vom swablab e.V. eine Reinigung oder Entsorgung vorgenommen werden, so werden diese Kosten dem Nutzer in Rechnung gestellt und sind vor Verlassen der Mieträume sofort zu begleichen. + *Herstellungsverbot* - Es ist strengstens untersagt, Gegenstände, die gegen allgemeine ethische und moralische Grundsätze verstoßen (u.a. rassistisch, diskriminierend, Gewalt verherrlichend, eine Religionsgemeinschaft herabsetzend sowie Waffen und deren Zubehör) in den swablab e.V. mitzubringen, zu bearbeiten oder dort zu fertigen. + *Haftpflichtversicherung* - Der Nutzer muss über eine wirksam abgeschlossene Haftpflichtversicherung verfügen. Diese ist dem swablab e.V. auf Verlangen nachzuweisen. = Werkstatteinrichtung + Der Nutzer muss bei vor der Nutzung von Werkzeugen oder Maschinen diese auf Beschädigung prüfen und eventuelle Beschädigungen oder Defekte sofort dem swablab e.V. melden. Der Nutzer kommt für alle durch ihn entstandenen Schäden und Defekte an den Werkzeugen oder Maschinen des swablab e.V. oder auch an seinen eigenen mitgebrachten und benutzten Werkzeugen und Materialien auf. + Das Labelsystem ist unbedingt zu beachten. Weitere Infos dazu sind im Wiki unter https://wiki.swablab.de/de/Labelsystem einsehbar. + Der Nutzer trägt die Kosten für sämtliche durch ihn beschädigten Werkzeuge, Maschinen oder Einrichtungen (Wiederbeschaffungskosten). + Grundsätzlich ist mit dem Eigentum anderer, insbesondere des swablab e.V., sorgfältig und pfleglich umzugehen. + Geliehene Werkzeuge und Maschinen sind ausschließlich im swablab e.V. zu benutzen, außer es wurde schriftlich anders vereinbart. Jeder Diebstahl oder Versuch eines Diebstahls wird sofort zur Anzeige gebracht und mit unverzüglichem Hausverbot belegt. + Der Nutzer hat keinen Anspruch darauf, dass alle Werkzeuge, Maschinen sowie Einrichtungen zu jeder Zeit nutzbar sind. Dies ist beispielsweise bei einem Defekt, Reparaturvorgang oder Nutzung durch andere Mieter der Fall. = Sicherheit + *Arbeitsschutz* - Für ausreichenden Arbeitsschutz und Arbeitskleidung ist der Nutzer selbst verantwortlich. Der swablab e.V. ist nicht verpflichtet, dies zu kontrollieren und kann bei Arbeitsunfällen nicht haftbar gemacht werden. + *Nutzungssicherheit* - Der Einsatz aller Werkzeuge und Maschinen ist nur zum bestimmungsmäßigen Gebrauch zulässig. Bei Unklarheiten in Bezug auf die sichere und sachgemäße Nutzung von Maschinen, Werkzeugen und Einrichtungsgegenständen ist von der Benutzung abzusehen oder müssen sich die entsprechenden Kenntnisse eigenverantwortlich angeeignet werden. + *Brandschutz* - Der Nutzer ist verpflichtet, sich nach den Vorgaben des gesetzlichen Brandschutzes und den gesetzlichen Sicherheitsbestimmungen zu richten und seine Tätigkeit darauf einzustellen. Vorhandene Feuerlöscher sind gekennzeichnet und im Brandfall vom Nutzer zu benutzen. + *Gefahrstoffe* - Austretende Gefahrstoffe und Flüssigkeiten sind unverzüglich wieder zu entfernen und in die vorgesehenen Behälter auf Anweisung einzulagern. Für falsche und unsachgemäße Einlagerungen von Schadstoffen und Flüssigkeiten in die Behälter übernimmt der Nutzer die Kosten einer fachgerechten Entsorgung. = Persönliche Gegenstände + Die Unterbringung persönlicher Gegenstände des Nutzers im swablab e.V. erfolgt auf eigenes Risiko und Verantwortung. Dies gilt auch für den Verbleib von Gegenständen in den für Projekte vorgesehenen Boxen. + Der Einsatz selbst mitgebrachter Werkzeuge und Maschinen sind dem swablab e.V. anzuzeigen. + Mitgebrachte Werkstoffe, Abschnittreste und sonstiger Abfall sind vom Nutzer vollständig mitzunehmen oder in einer entsprechenden Box oder Lagerfläche unterzubringen. Nach Absprache können bestimmte Teile und Materialien an den dafür vorgesehenen Plätzen deponiert werden. Andere Nutzer können diese dann gegen Spende oder Entgelt zur Weiterverarbeitung entnehmen. = Beratung + Der swablab e.V. kann nach seinem Dafürhalten oder auf Wunsch des Nutzers, fachliche und sachkundige Beratung vornehmen. Einen Anspruch oder ein Recht darauf hat der Nutzer jedoch nicht. + Eventuell mündliche oder auch tatkräftige Hilfestellungen durch den swablab e.V. oder dessen Beauftragten erfolgen nach bestem Wissen und Gewissen jedoch unter Ausschluss jeglicher Haftung und Gewährleistung. = Haftung + Der swablab e.V. schließt jede Haftung für Personen- und Sachschäden aus, soweit nicht nachfolgend etwas anderes geregelt ist. Von diesem Haftungsausschluss ausgenommen sind sowohl die Haftung für Schäden aus der Verletzung des Lebens, des Körpers oder der Gesundheit, wenn diese Schäden auf einer fahrlässigen Pflichtverletzung seitens des swablab e.V. beruhen, als auch die Haftung für sonstige Schäden, wenn diese auf einer vorsätzlichen oder grob fahrlässigen Pflichtverletzung oder der leicht fahrlässigen Verletzung wesentlicher Vertragspflichten seitens des swablab e.V. beruhen. Wesentliche Vertragspflichten sind solche, deren Erfüllung zum Erreichen des Vertragszwecks erforderlich sind und auf deren Einhaltung der Nutzer vertrauen darf. + Für mitgebrachte Gegenstände, insbesondere eigener Werkzeuge aber auch Wertgegenstände und Geld, wird keine Haftung übernommen. = Daten des Nutzers + Der swablab e.V. erhebt, speichert, verarbeitet und nutzt personenbezogene Daten, die er unmittelbar von Nutzern direkt oder über die Nutzung seiner Einrichtungen wie auch seiner Internetseiten erhält. + #[Der swablab e.V. versichert, dass sämtliche Daten seiner Nutzer streng vertraulich behandelt werden und unter Beachtung der einschlägigen Datenschutzvorschriften ausschließlich für - die Verwaltung des Nutzungssvertrages, - die Abwicklung der Nutzungsbeiträge, - die Übermittlung von neuen Angeboten und aktuellen Informationen durch den swablab e.V. selbst verwendet werden.] + Der Nutzer ist berechtigt, Auskunft über die gespeicherten Daten und kostenfreie Korrektur oder Löschung nach Vertragsende zu verlangen. + Der swablab e.V. verarbeitet personenbezogene Daten, soweit dies für die Erbringung seiner Leistungen und/oder zum Betrieb der Werkstatt erforderlich ist. Wir weisen darauf hin, dass im Falle der Nutzung der Leistungen auch Daten (Zeitpunkt, Art und Umfang der Nutzung) erhoben und gespeichert werden. Zudem werden Daten über die Teilnahme an Einweisungen oder Kursen erhoben sowie bei Abgabe von Zeugnisunterlagen zur Verifikation von Kenntnissen. Dies dient vor allem dem Nachweis des Vertragsschlusses sowie der Inanspruchnahme der Leistung. Aus steuerlichen Gründen müssen diese Daten 10 Jahre gespeichert werden. + Eine Weitergabe der personenbezogenen Daten an Dritte findet grundsätzlich nicht statt, es sei denn, dass dies für die Erbringung der Leistungen gegenüber dem Nutzer erforderlich ist. Dazu gehören bspw. buchhalterische und/oder steuerrechtliche Gründe (Steuerberater, Finanzamt). + Die Einwilligung zur Verwendung persönlicher Daten kann selbstverständlich jederzeit mit Wirkung für die Zukunft widerrufen werden. + Weitere Informationen zum Datenschutz im Sinne des Artikels 13 der DSGVO können unseren Datenschutzhinweisen entnommen werden. Diese findet man auf unserer Website unter https://swablab.de/docs/mitgliedsantrag.pdf = Schlussbestimmungen + *Nebenabreden* - Mündliche Nebenabreden sind nicht getroffen. Änderungen und/oder Ergänzungen des Vertrages bedürfen der Schriftform, dies gilt auch für Änderungen dieses Schriftformerfordernisses. + *Salvatorische Klausel* - Sollten Teile des Vertrages / der AGB, aktuell oder zukünftig, unwirksam sein oder werden, berührt dies nicht die Wirksamkeit der übrigen Bestimmungen. Es gelten die gesetzlichen Bestimmungen. + *Änderungen der AGB* - Der swablab e.V. ist berechtigt, den Vertragsinhalt einseitig zu ändern oder zu ergänzen, soweit dies aus rechtlichen Gründen erforderlich ist, oder die Änderungen oder Ergänzungen ausschließlich zu Gunsten des Nutzers sind. In allen übrigen Fällen ist eine einseitige Änderung oder Ergänzung der Leistungen und des Vertrags und dieser allgemeinen Geschäftsbedingungen nur zulässig, wenn diese für das Mitglied unter Berücksichtigung der Interessen des swablab e.V. zumutbar ist. Der swablab e.V. wird Ihnen in diesen Fällen eine Änderung oder Ergänzung schriftlich oder per E-Mail wenigstens vier Wochen vor deren Inkrafttreten mitteilen (\"Änderungsmitteilung\"). Sie können einer solchen Änderung oder Ergänzung binnen einer Frist von vier Wochen ab Zugang der Änderungsmitteilung schriftlich oder per E-Mail gegenüber dem swablab e.V., Katharinenstraße 1, 72250 Freudenstadt, an #link("<EMAIL>") zu widersprechen. Im Falle eines unterlassenen Widerspruchs werden die Änderungen oder Ergänzungen wirksam. Auf die Rechtsfolgen eines unterlassenen Widerspruchs wird der swablab e.V. Sie in der Änderungsmitteilung besonders hinweisen.
https://github.com/asibahi/simple-poem-typst
https://raw.githubusercontent.com/asibahi/simple-poem-typst/main/simple%20poem.typ
typst
#set text(dir: rtl, font: "Noto Naskh Arabic") #let ahmed_shawqi =" ريمٌ على القاع بين البان والعلم أحل سفك دمي في الأشهر الحرم رمى القضاء بعيني جؤذر أسدا يا ساكن القاع أدرك ساكن الأجم لما رنا حدثتني النفس قائلة يا ويح جنبك بالسهم المصيب رمي جحدتها وكتمت السهم في كبدي جرح الأحبة عندي غير ذي ألم رزقت أصفح ما في الناس من خلق إذا رزقت التماس الغدر في الشيم يا لائمي في هواه والهوى قدر لو شفك الوجد لم تعذل ولم تلم لقد أنلتك أذنا غير واعية ورب منتصت والقلب في صمم كتبه أحمد شوقي غفر الله له ولوالديه " #let set_poetry(my_lines) = { set align(center) let jb = linebreak(justify: true) let lines = my_lines.trim("\n") .split("\n") .map(line => line.trim(" ")) .filter(body => body.len() != 0) //👇 i need this to get measure to work properly. style(styles => { linebreak() let max_size = lines.map(body => measure(body,styles).width).sorted().last() //👇 and this to get the container size. layout(size => { if size.width > max_size * 2 + 20pt { for (index, line) in lines.enumerate() { if calc.rem(index, 2) == 0 [ #box(width: max_size , line + jb) ] else [ #box(width:20pt, ) #box(width: max_size , line + jb) \ ] } } else { block(width: max_size + 50pt, for (index, line) in lines.enumerate() { if calc.rem(lines.len(), 2) == 1 and index == lines.len() - 1 [ #box(width: max_size , line + jb) ] else if calc.rem(index, 2) == 0 [ #set align(start) #box(width: max_size , line + jb) ] else [ #set align(end) #box(width: max_size , line + jb) \ ] } ) } }) //layout() }) // style() } // let #set_poetry(ahmed_shawqi) = نديم الباذنجان #set_poetry(" كان لسلطان نديم وافي يعيد ما قال بلا اختلاف وقد يزيد في الثنا عليه إذا رأى شيئا حلا لديه وكان مولاه يرى ويعلم ويسمع التنميق لكن يكتم فجلسا يوما على الخوان وجيء في الكل بباذنجان فأكل السلطان منه ما أكل وقال هذا في المذاق كالعسل قال النديم صدق السلطان لا يستوي شهد وباذنجان ") #set text(dir: ltr, font: "IBM Plex Serif") = LTR Usage #set_poetry(" Shall I compare thee to a summer’s day? Thou art more lovely and more temperate. Rough winds do shake the darling buds of May, And summer’s lease hath all too short a date. Sometime too hot the eye of heaven shines, And often is his gold complexion dimmed; And every fair from fair sometime declines, By chance, or nature’s changing course, untrimmed; But thy eternal summer shall not fade, Nor lose possession of that fair thou ow’st, Nor shall death brag thou wand'rest in his shade, When in eternal lines to Time thou grow'st. So long as men can breathe, or eyes can see, So long lives this, and this gives life to thee. ")
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/ea2724-ai_hw/hw1.typ
typst
== HW 1 Due: 2024.03.17 #let ans(it) = [ #pad(1em)[ #text(fill: blue)[ #it ] ] ] === Question 3.7 3.7 给出下列问题的初始状态、目标测试、后继函数和耗散函数. 选择精确得足以实现的形式化. + 只用四种颜色对平面地图染色, 要求每两个相邻的地区不能染成相同的颜色. + 一间屋子里有一只 3 英尺高的猴子, 屋子的房顶上挂着一串香蕉, 离地面 8 英尺. 屋子里有两个可叠放起来、可移动、可攀登的 3 英尺高的箱子. 猴子很想得到香蕉. + 有一个程序, 当送入一个特定文件的输入记录时会输出“不合法的输入记录”. 已知每个记录的处理独立于其它记录. 要求找出哪个记录不合法. + 有三个水壶, 容量分别为 12 加仑、8 加仑和 3 加仑, 还有一个水龙头. 可以把壶装满或者倒空, 从一个壶倒进另一个壶或者倒在地上. 要求量出刚好 1 加仑水. #ans[ + - Initial State: 所有区域未染色 - Goal Test: 所有区域都染色 - Successor Function: 选择一个未染色的区域, 为其染上一种颜色 - Cost Function: 涂色的次数 + - Initial State: 猴子在屋子的地面, 箱子在屋子的地面, 香蕉距离地面 8 英尺 - Goal Test: 猴子站在箱子上, 可以够到香蕉 - Successor Function: 猴子搬动、放下箱子、爬上箱子、爬下箱子、拿起香蕉 - Cost Function: 猴子总用时 + - Initial State: 一个输入记录 - Goal Test: 输入记录合法 - Successor Function: 修改输入记录的某一部分 - Cost Function: 修改的次数 + - Initial State: 三个水壶都是空的 - Goal Test: 一个水壶里有 1 加仑水 - Successor Function: 装满水壶、倒空水壶、从一个壶倒进另一个壶 - Cost Function: 倒水的次数 ] === Question 3.9 3.9 传教士和野人问题通常描述如下:三个传教士和三个野人在河的一边, 还有一条能载一个人或者两个人的船. 找到一个办法让所有的人都渡到河的另一岸, 要求在任何地方野人数都不能多于传教士的人数 (可以只有野人没有传教士). 这个问题在 AI 领域中很著名, 因为它是第一篇从分析的观点探讨问题形式化的论文的主题(Amarel, 1968) + 精确地形式化该问题, 只描述确保该问题有解所必需的特性. 画出该问题的完全状态空间图. + 用一个合适的搜索算法实现和最优地求解该问题. 检查重复状态是个好主意吗? + 这个问题的状态空间如此简单, 你认为为什么人们求解它却很困难? #ans[ + - 状态:$(a,b,c)$, $a$:传教士在此岸的人数, $b$:野人在此岸的人数, $c$:船是否在此岸 (0/1) - Initial State: $(3,3,1)$ - Goal Test: $(0,0,0)$ - Successor Function: $ (x,y,1) -> cases((x-1,y,0), (x,y-1,0), (x-1,y-1,0), (x-2,y,0), (x,y-2,0)) \ (x,y,0) -> cases((x+1,y,1), (x,y+1,1), (x+1,y+1,1), (x+2,y,1), (x,y+2,1)) $ 同时所有$(x,y,c),(x',y',z')$满足$0<=x<=3, 0<=y<=3$, 并且: $ (x=0 or x>=y) and (x=3 or x<=y) $ - Cost Function: 操作次数 + 使用 BFS 对状态进行搜索, 维护一个 $3 times 1$ 的数组记录已经访问过的状态: $ (3,3,1) -> (3,1,0) -> (3,2,1) -> (3,0,0) -> (3,1,1) -> (1,1,0)\ -> (2,2,1) -> (0,2,0) -> (0,3,1) -> (0,1,0) -> ( 1,1,1 ) -> (0,0,0) $ 问题中限制很多, 可以不考虑重复状态 (全部枚举即可). 如果问题中 $3 -> 100$, 检查重复状态是个好主意. + 虽然每一步的限制都足够多而且空间足够简单, 但图的深度很大, 每一步所需要做的判断过于复杂. ]
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/text_formats/text_formats_mix_result.typ
typst
= Heading1 Paragraph with quotes “This is in quotes.”#underline[ ];#underline[“New.”] #strong[Date:] 26.12.2022 \ Date used in paragraph #strong[Date:];#strike[ ];#strike[26.12.2022];#strike[ \ ];#strike[#strong[Topic:];] #strike[Infrastructure];#underline[30.12.2022] #strike[Test];#strike[ \ ];#strong[#strike[Severity:];#underline[Date:];] #strike[High];#underline[25.02.2022];#strike[ \ ] #underline[#strong[Topic:];];#underline[ ];#underline[Infrastructure];#underline[ ];#underline[Test];#underline[ \ ];#underline[#strong[Severity:];];#underline[ ];#underline[High];#underline[ \ ] = Heading3 #emph[emphasis] Some normal#underline[ ];#underline[text];#underline[ ];#underline[New] text Italic #strong[MY TEXT] \ ALREADY HIGH #link("https://typst.app/") = Heading4 #underline[abc];#underline[ ];abc Link in paragraph: #link("https://typst.app/");#underline[ ];#underline[#link("https://another.link/");] = #underline[Heading5] = Heading5
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/056%20-%20Outlaws%20of%20Thunder%20Junction/005_Episode%203%3A%20A%20Train%20to%20Prosperity.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 3: A Train to Prosperity", set_name: "Outlaws of Thunder Junction", story_date: datetime(day: 18, month: 03, year: 2024), author: "<NAME>", doc ) Akul dug his claws into the gravel, watching as two Hellspurs appeared through the thick smoke. Their fists were tightened around the mine overseer's disheveled uniform, and when they shoved the man toward Akul, the overseer collapsed to his knees, face stained with blood and soot. Flames danced in the dragon's eyes, reflecting what was left of the copper mine. "Tell me what you know." The overseer sputtered into the sand, lip quivering. "Graywater hired me to look after the mine. Whatever you're searching for has nothing to do with me, I swear! Please—I won't tell anyone I saw you. I just want to go home." Akul lowered his head and sneered. "If you have nothing to tell me, then I don't see why you're still breathing." The man's eyes widened. "I #emph[did ] hear a rumor about someone stealing something from Graywater. Something important enough that Sterling Company headquarters sent out over two dozen guards to retrieve it!" Akul leaned back, mildly appeased, and clicked a nail against the rocky floor beneath him. "Give me a name." The man shook his head, fearful. "It was some shapeshifting fae from another plane. He had blue face paint and had help escaping—but that's all I know." Akul's gaze snapped to the Hellspurs. "Find him. #emph[Now] ." They nodded before vanishing back through the smoke, leaving the overseer at the dragon's feet. For several excruciating seconds, the man waited in terror. Akul turned to the engulfed mine, attention drifting toward an exit. The overseer's shoulders sagged with relief. He stood, knees quaking, and hooked a finger around his neckerchief to loosen some of the tension. With a wary glance in the opposite direction of the mine, he took one step closer to safety. "Where do you think you're going?" Akul hissed like a growing flame. The overseer froze. He held his hands up, ready to plead, but there wasn't time. Akul whipped the barbed, venomous stinger on the end of his tail into the man's gut, and the light splintered behind the overseer's eyes. By the time he hit the ground, he was already gone. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Oko watched the others from the mezzanine. Kaervek was huddled with Annie and Vraska, deep in conversation. Gisa and Geralf stood on opposite sides of the room, clearly at war with one another. Eriette, Malcolm, and Breeches were holding glasses at the bar. Umezawa sharpened a serrated knife, studying the others in calculated silence, while Tinybones sprawled across the top of the piano, holding a golden pocket watch up to the light for closer inspection. The floorboards creaked behind Oko, and his mouth quirked with amusement. "I know you're there," he said easily. "I've been listening to you breathing for the past five minutes." There was a pause before Kellan appeared from the alcove. He pressed his hands over the railing, shifting nervously. "Sorry. I wasn't trying to sneak up on you." "You'd be doing a terrible job if you were." Kellan's cheeks reddened. "It's just—well, this isn't how I imagined our first meeting." Oko drummed his fingers on the wooden balustrade. "Reality rarely matches fantasy. But in my experience, the most fun happens when you aren't following a plan." He grinned. "Meeting you was an unexpected surprise, and one that I'm grateful for." Kellan brushed a dark curl from his brow, his expression softening. "Really?" "Yes." Oko motioned toward the crew in the lower room. "You'll make a wonderful addition to the team." Kellan chewed on his thoughts a moment too long, but eventually released a sigh. He didn't have the words for whatever was weighing on him. "You came to my rescue when I needed it most." Oko continued to stare down the balcony. "It's something I won't easily forget. Perhaps someday soon, I can return the favor." "I don't need favors," Kellan said slowly. "I just want to get to know you." "You will," Oko promised. He knew how to sound genuine—and besides, he almost meant this one. Kellan looked like he was about to say more when his breath hitched suddenly, and he leaned over the railing, eyes wide with alarm. Oko tensed, ready to summon his magic at the first sign of danger, but when he followed Kellan's gaze to the corner of the room below, the crease in his brow vanished. Ashiok was drifting forward as if being carried by a storm of darkness. Black shadows curled around them, pulsing like a slow heartbeat. Recognition flooded Kellan's face, his concerned expression morphing into outrage. He gripped the wood tightly, knuckles emitting a golden aura. "Easy, kid," Oko said, sensing Kellan was ready to leap off the balcony and begin a brawl. "Whatever history the two of you share doesn't have a place here. Is that understood?" "You don't know what they did—what they're capable of!" "I know what I need to. Everything else makes little difference to me." "Ashiok is dangerous," Kellan insisted. "They attacked my home and manipulated people into doing their bidding. They made <NAME> turn—well, evil! You can't trust them." Oko sniffed dismissively. "I don't need you to trust Ashiok—I need you to trust me. Can you do that?" Kellan stiffened slightly before nodding and letting go of the railing. Oko made it a point to look pleased. "Good. Kellan, I'm sure your mother did an excellent job raising you, but there are things she hasn't taught you. About your powers, about where you come from. Now that we've finally been reunited, I can teach you so much about your #emph[true ] heritage. I have business to discuss with the crew." He moved for the stairs, pausing halfway down. "You coming?" Kellan hesitated, grappling with the guilt clearly radiating from his shoulders. Still, he followed his father downstairs, stopping near one of the larger tables where the rest of the team had gathered. Oko braced for a reaction from Ashiok, but it was Eriette who noticed Kellan first. "Of all the people to run into on Thunder Junction," she said haughtily. She turned her nose up, white hair spilling over her shoulders as she glared at Oko. "If I knew this brat was joining the team, I'd have negotiated a higher fee." Oko's voice was all charm. "If the necromancers can attempt to set aside their differences for the sake of the mission, I'm sure the rest of us can learn to do the same." Kellan scowled. Eriette pursed her lips and shrugged. "Wonderful. Now, getting back to the reason we've all gathered here …" Oko nodded toward Kaervek. "What have you discovered?" Kaervek removed the artifact from his coat, placed it in the center of the table, and folded his arms over his chest. "It's not Thran or Phyrexian, but it's as old, or older. I cannot tell you with precision what ancient place it hails from. It had no response to my magic, and so my knowledge remains limited." "Unsurprising," Umezawa muttered, leaning against one of the pillars. Kaervek's nostrils flared, but he fixed his stare on Oko. "I believe the artifact is more than a key, and perhaps even more dangerous than we can understand. Whoever made it, and wherever it comes from … You could be unleashing another Phyrexia on the Multiverse." "You sound afraid," Vraska said testily. "It is not fear that dwells inside me; it is caution," Kaervek corrected. "I lost centuries because I seized a power I could not control. I am not keen to do it again without study." Ashiok's shadows swirled behind them. "Bertram Graywater will be searching for us and doing everything in his power to find the key. We need to reach the vault before that happens." "We still don't know where Tarnation #emph[is] ," Malcolm pointed out, feathers straightening against his arms. "I know you've asked me to do recon, but there's a lot of desert out there. I'd prefer directions—or at the very least, a map." Gisa's grin was sinister. "How about we torture it out of someone? I bet there's a Hellspur out there who could show us the way!" Geralf scoffed. "You don't have the patience for interrogation." "The only thing I don't have patience for is #emph[you] , brother," she said. "Even your voice grates on me." Vraska waved a hand. "We need to know how to reach the vault—but directions won't matter if we don't know how to use this key." Her eyes landed on Kaervek first, and then Annie. "Tell them what you told me." Annie raised her shoulders. "I know of an Outcaster from the territories who studies ancient magical artifacts. Nolan's his name. He'll do just about anything for a paycheck, and for a few extra coins, you can buy his silence, too." Oko looked around the room. "How soon can we get him here?" "There's a problem," Vraska said, tendrils flicking behind her. "The man in question is currently on a train to Prosperity, escorted by Sterling mercenaries." The shadows at Ashiok's feet shuddered. "Graywater must've gone looking for him for the exact same reason." "But Graywater doesn't have the key anymore," Malcolm pointed out. "He's got no use for an artifact expert." "Wasting his time!" Breeches agreed. Vraska narrowed her eyes. "For all we know, Graywater might put him under lock and key while he tries to get the artifact back." Oko nodded. "We need to get to the Outcaster before he reaches Prosperity." Breeches threw his arms in the air. "CAPTURE AND INTERROGATE!" Gisa looked giddy. Geralf rolled his eyes. Oko turned to Kellan. "You're a former Sterling man. How familiar are you with the guard rotations on the train?" Kellan froze, uncertain. "I—I don't want to do anything illegal." A rumble of dark chuckles spread throughout the room. "I'm only asking for your expertise," Oko said, voice soft as velvet. Kellan cleared his throat, avoiding the stares from the rest of the crew. "I don't want anyone to get hurt. I've already made a mess of things with Ral …" Oko pressed a hand to his heart. "I promise that no innocents will be harmed." Gisa's face fell with disappointment, but everyone else was stoic. "Okay," Kellan said finally. "Tell me what you need to know." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The train sped across the golden desert, sun blazing through the elongated glass windows. Kellan tapped his boot nervously, counting the passengers around him with dread. There had to be at least a hundred people in all the traveling cars combined—maybe more. If anything went wrong … #figure(image("005_Episode 3: A Train to Prosperity/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Oko placed a hand on Kellan's shoulder. "Try not to look so terrified," his father drawled, too low for anyone else to hear. "We're supposed to be blending in." Kellan stilled, but his heart felt like it was about to beat out of his chest. To anyone watching, he looked like any other Sterling guard on their way to Prosperity. With Oko hiding beneath an illusion, he looked like one, too. He seemed to have a much better hold over his illusions now that he was aware of his son's presence. Kellan's eyes flicked toward the door connecting their current railcar to the one behind it. "The guards will be on rotation soon. They'll be heading for the front of the train, which is our opening to head toward the back." Oko's mouth barely moved. "You're certain the Outcaster will be there?" Kellan nodded once. "The overnight coaches are the only place they can put people under armed guard without drawing attention. If Nolan is still on the train, that's where he'll be." Umezawa sat inconspicuously on the other end of the aisle, hat pulled low, arms folded over his chest. Most of his tattoos were hidden beneath layers of fabric, but a few were visible just above his collar. The moment Oko's voice pressed into Kellan's mind, he flinched. He'd never experienced group telepathy before—and he wasn't sure he liked it. #emph["Can everyone hear me?"] Oko asked across the mental link. Umezawa looked up in acknowledgment. Annie's voice sounded next, vivid and clear despite her being over a mile up the ridgeline. #emph["We're here, and we've got eyes on the train."] #emph["Skies are looking clear, too," ] Malcolm announced.#emph[ "Breeches is ready to blow up the bridge on your signal."] #emph["BOOM!"] Breeches shrieked excitedly. #emph["Is that the signal?"] Gisa cut in. Her giggling was bordering on euphoric. #emph["I can hardly stand the wait!"] #emph["Of course that's not the signal," ] Geralf tutted, exasperated. #emph["You're to raise the corpses ] after#emph[ Breeches blows up the bridge and forces the train to stop. We've gone over this a hundred times. Why is it so difficult for you to pay even half a mind to what anyone else says?"] #emph["Corpses?" ] Kellan tried to ask, but no one seemed to hear him over the necromancers' bickering. #emph["Stop telling me what to do!"] Gisa snarled back. #emph["You're not in charge—and the only reason you were even invited on this job was because I allowed you to be."] #emph["Having a stitcher is far more useful than a ghoulcaller. Besides, I'm here for the secrets this 'thunder' can offer my craft," ] Geralf countered.#emph[ "Though at this stage, I'm not entirely sure it's worth having to endure the sound of your voice!"] #emph["Ashiok didn't create a telepathic link for the two of you to argue like children,"] Vraska scolded. #emph["Save it for after the mission. Right now, we need to stick to the plan."] The nearby door opened, and two guards stepped inside. They strolled down the aisle, giving an obligatory nod in recognition of Kellan's and Oko's uniforms, before disappearing through the next walkway. The moment it was clear, Oko stood and moved toward the back of the train, with Kellan and Umezawa following behind him. When they reached the luggage carriage, they slipped past rows of suitcases and leather trunks and paused in front of a locked door. Umezawa pushed the brim of his hat back. "I don't know how anyone can see with these things on," he grumbled before removing a small metal device from his belt. A panel flashed, and several tiny origami shapes appeared along the edges. Umezawa held the piece of equipment up to the handle, and the shapes folded and refolded themselves like paper before burrowing inside the keyhole. He worked quickly, using the device to manipulate the lock as the metal pieces took on the shape of an intricate key. Kellan had never seen anything like it before. #emph["Our window for blowing up this bridge and stopping the train is getting smaller,"] Malcolm noted through the mental link. #emph["How are we doing in there?"] #emph["Give me a minute,"] Umezawa replied coolly. #emph["READY AND WAITING!"] Breeches squawked. #emph["Wait, was ] that #emph[the signal?" ] Gisa asked. #emph["He said to give him a minute!" ] Geralf barked. #emph["How dare you raise your voice to me," ] Gisa spat back. #emph["Don't think our temporary truce will keep me from taking your tongue!"] #emph["Threaten me all you like, but I can just as easily stich your mouth shut—"] #emph["—you ruin everything, and I'm so tired of your constant nagging! If I could—"] #emph["—the most unreliable, self-serving—"] #emph["—irritating, obnoxious—"] #emph["Would the two of you be quiet,"] Malcolm roared. #emph["How is Breeches supposed to hear the signal over all of this noise?"] #emph["SIGNAL!"] Breeches's voice boomed. #emph["No, Gisa—what are you doing? Stop!"] Geralf yelled. The faraway screams carried all the way to the luggage car. Kellan's heart pinched as he watched Oko's brow furrow. Even Umezawa paused at the lock, face paling. #emph["What's going on?"] Oko demanded. #emph["She raised the zombies too early,"] Geralf groaned. Gisa's cackle exploded through the telepathic channel. #emph["You see, dear brother? Doubt me all you want—I will always prove I'm more powerful than you."] #figure(image("005_Episode 3: A Train to Prosperity/02.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) #emph["Oko, you've got guards moving for the back of the train,"] Malcolm said quickly. #emph["You better find somewhere to hide if you want to keep the element of surprise."] "I'm almost done," Umezawa said, twisting at the partially formed key. "I only need to—" The door behind them slammed against the wall, making Kellan jump. A pair of guards loomed in the doorway, trying to make sense of Kellan's and Oko's uniforms. But with Umezawa still perched in front of the locked door, they didn't stand a chance at maintaining their cover. The guards drew their weapons. Oko and Kellan dove for opposite walls, just as a thunder blast burst toward the door frame. Umezawa gave a sharp cry, clutching his shoulder before stumbling for cover behind an oversized suitcase. Kellan threw up a hand and shot a golden vine straight for the guard's weapon. With a sharp tug on his magic, Kellan yanked the rifle from his grip and sent it skittering across the metal floor. He charged the guard with his shoulder, knocking him off balance. Oko moved swiftly, freeing a curved knife from his belt. He reached the second guard in less than a moment and pierced him between the ribs. The guard winced hard before crumpling to the floor. Kellan struggled to pin down the other guard, head moving from side to side, trying to dodge the man's fist. From the corner of the room, Umezawa launched a small metal star through the air. It hit the Sterling guard in the neck, missing Kellan's hand by a mere inch. Kellan released the man, surprised, and watched his eyes fall shut. He spun around just in time to find Umezawa sinking heavily to the floor. Kellan rushed to his side. "He needs a medic. How fast can Geralf get here?" "There's no time for that," Oko argued. "We need to find the Outcaster before the guards realize what's happening." Kellan pulled his face back in confusion. "But—we can't just leave him here. He'll die." "Personally, I'd rather take my chances here than with the necromancer," Umezawa coughed, eyes shuttering. "I don't want to wake up and find my limbs have been sewn on the wrong way." "You see? He's fine," Oko insisted. Umezawa teetered on the edge of consciousness. Kellan frowned. #emph["Umezawa is hurt. We need someone to get him off this train,"] he said to the crew. Beside him, Oko folded his arms. The disapproval on his face was clear. #emph["I'm on my way,"] Annie replied. #emph["What do you want to do about the bridge?"] Oko's jaw tensed. #emph["Take it out."] #emph["BIG BOOM!"] Breeches wailed. The explosion was instant, echoing through the train walls and making the floor shake. Beneath the carriage, the wheels rattled along the tracks before picking up speed. "We aren't slowing down." Kellan frowned. "Why aren't we slowing down?" Oko moved for the window, trying to make out the canyon in the distance, where smoke clouded the sky. "We need to get to the back of the train." Kellan stood, balling his fists. "There are civilians on board. We need to warn them about the bridge—" "We need to finish the mission," Oko interjected, eyes gleaming. "We can check on the passengers after we secure the Outcaster." "But—" Oko clasped a hand to Kellan's shoulder, shaking firmly. "I can't do this alone. I need your help." Kellan's mouth parted, lips forming words that never came. "Alright," he said finally, too worried about disappointing his father to argue any further. "How are we going to get through the door without Umezawa?" Oko motioned above them. "We'll go across the roof. Think you can knock these windows out with your magic?" Kellan formed a hefty golden hammer, swinging it through the windows and shattering them completely. The two of them climbed up the frame and searched the outside of the train for anything to hold on to. They clawed their way up the embellished exterior until they reached the roof. Kellan held his hands out, bracing against the wind. Beyond the overnight cars were the cargo ones. No doubt Gisa and Geralf were back there, staving off Sterling guards with an army of the undead. And Nolan … Kellan pointed to a car. "There. That's the one." Oko frowned. "How do you know?" "Because it's the car they use to transport prisoners." They leapt from one roof to the next, fighting the sway of the train as they made their way to the final overnight car. The smoke from the bridge carried through the air, making Kellan flinch. It wouldn't be long before they ran out of tracks. They needed to hurry and find a way to stop the train before it went over the canyon and took innocent lives with it. A blast of thunder exploded near Kellan's feet. He tripped, falling hard against the unforgiving metal. Pain radiated through his bones. Half a dozen Sterling Company guards appeared, forming a line behind Kellan and Oko. One of them raised their blaster and shot a second burst of energy across the roof. Kellan leapt, taking to the skies for cover just as Oko rolled out of the way. The jump sent Kellan to the next train car but left Oko vulnerable on his own. Panicked, Kellan tried to hurry back just as a series of blasts sent debris ricocheting toward him. He brought his arms up to cover his face. "Father!" Kellan shouted through the chaos. Oko winced—and Kellan did his best not to read into it. They were under fire; this wasn't the time to do anything other than survive. Kellan scrambled forward and grabbed his father by the arms. He launched himself up and away from the next blast, holding tight to Oko before dodging a glowing arrow. They swerved hard before tumbling back to the roof. Oko pulled out his dagger. Kellan moved a hand to summon his own weapons. The guards closed in, surrounding them in a wide circle. The one in the center pointed her thunder rifle at Oko, and Kellan's magic stalled at his fingertips. Concern buzzed through him—for his father, and the innocent people still on the train. What would happen if he couldn't save them? What would happen if he couldn't save his #emph[dad] ? Kellan's shoulders shook, and he redirected his magic to protect Oko. If only one of them could make it out alive … Gray rotted arms closed around the guard's shoulders, and her weapon clattered to the ground. She twisted against the creature, screaming as it pulled her off balance. The rest of the guards began to turn one by one, yelping in alarm at whatever was behind them. A wall of reanimated bodies appeared, scratching and pulling at the Sterling Company guards with a desperate hunger. Panic swept across the rooftops. Some of the guards retreated. Some leapt from the train. Others didn't escape at all. Using the distraction to their advantage, Kellan and Oko forced their way down the nearest ladder, wedging themselves in the open space between the cargo and overnight cars. Oko paused outside the door. "Allow me," he said, shapeshifting into one of the recently fallen guards. He pushed the door open and layered his voice with mock concern. "The ghouls—they're everywhere!" he gasped to the people in the room. Nolan stood in the center, surrounded by four Sterling mercenaries. The guards exchanged wary glances. "They're making their way across the roof! We need everyone with a weapon to help stave them off," Oko added hurriedly. Three of the guards acted quickly, rushing for the door with their thunder rifles. The moment they stepped onto the walkway between the carriages, Kellan's golden vines snared them and tossed them over the side of the train and onto the desert floor below. The final guard hesitated. Oko let his illusion drop, revealing his pointed ears and blue painted face. His grin was wild with mischief. "Don't worry. Odds are, you'll survive the fall. But please—give Graywater my regards." Oko shoved the man hard through the open door, where Kellan's vines did the rest. Oko turned to the Outcaster, smiling brightly. "You must be Nolan." Oko gripped Nolan's arm and nudged him forward. The trio marched back through the various overnight cars, watching as a mixture of ghouls and guards toppled occasionally from the roof. When they reached a bolted door, Kellan lifted the latch and shoved it open. Umezawa was still slumped in the corner of the luggage car. Unconscious, but breathing. With his grip fastened to the Outcaster's forearm, Oko leaned out of the shattered window. #emph["Does anyone know why this train has yet to slow down?" ] he asked the rest of the crew. #emph["The zombies reached the conductor,"] Annie explained, her breathing stilted. #emph["There's no one controlling the train."] "I'll fly to the front and take care of it," Kellan said, moving for the window. "No," Oko ordered, forcing an arm in front of him. "We need to get the Outcaster and Umezawa to safety." "Yes, but the people—" Kellan started. "—will be dealt with later," Oko finished. Kellan clenched his teeth, flustered. "We don't have time to argue about this." "Exactly," Oko said, and tilted his head toward the expanse of desert. "Get ready—our extraction team is here." Annie appeared with Fortune, galloping alongside the train. She tugged the reins, guiding Fortune as close to the tracks as possible. When the gap was barely an arm's length across, Oko stepped back and pushed the Outcaster toward the window. "Y—you expect me to #emph[jump] ?" Nolan sputtered. "If you want to live," Oko replied, helping him onto the frame. Annie grabbed Nolan's outstretched arm and heaved him onto the back of the saddle. He clutched her waist for dear life, burrowing his face into her shoulder. Kellan and Oko each looped an arm beneath Umezawa and lifted him onto the windowsill. Annie moved closer to the tracks once more, closing the gap between her and the window. Kellan steadied himself as he carried the bulk of Umezawa's weight through the opening. Annie looped an arm around Umezawa and pulled hard, forcing him onto the front of the saddle. With a sharp whistle, Annie steered Fortune toward safety and broke into a fearless gallop, kicking up sand behind them. Smoke seeped through the broken window, and Kellan stared in horror at the canyon ahead. The bridge was obliterated. All that was left were the gnarled ends of the train tracks, one on each side of the canyon. Oko stepped onto the ledge. "Where are you going?" Kellan asked, wide-eyed. "There's still people on board!" "There's no time to save them," Oko said with a careless shrug. "We have to jump now, or we're going over the edge with the train." "But you said—" Oko didn't wait for him to finish. He leapt, tumbling across the sand with unsteady grace. The door burst open behind Kellan. One of the guards tumbled inside; a zombie was clutching his neck, teeth searching for flesh. There were more ghouls behind them, their moans growing louder by the second. Kellan had no choice—he leapt and glided to the sand in a panic. The moment he was firmly on his feet, he spun around, watching as the train approached the cliff. He ran on instinct, throwing his hands up in the air as giant gold bursts of energy erupted from his palms. The vines whipped forward, snatching the train by the last carriage—but it wasn't enough to stop it. The momentum of the train fought back, and Kellan felt the tug on his magic burn through him, making his veins scorch. He strained against the weight, digging his heels into the sand as he hung on, desperate. All those people … He couldn't let them die. He #emph[wouldn't] . Kellan threw his head back, and every vein in his body pulsed. His knuckles blazed, and he held the vines like they were rooted inside of him, refusing to let them break. The train screeched, slowing, but the first car was already hanging over the edge. Kellan's boots dragged across the sand, inch by inch. Malcolm's distant shadow moved across the desert, and his voice sounded in Kellan's mind. #emph["The Sterling Company are a few miles out.] #emph[We don't have the numbers to fight off an attack that big. You need to get as far away from that train as you can."] Oko appeared at Kellan's side, forehead creased with urgency. "We need to go!" "You—promised—" Kellan strained. "I won't leave them to die." "You can't save them," Oko argued. "I have to try," Kellan replied, teeth grinding as he pulled hard at the vines. The rumble of the approaching army sounded in the distance. A stampede of hooves and enormous mounts. The Sterling Company was ready for battle. Oko took one step back, then another. A look of pity flashed over his face before quickly shifting to resignation. With a final glance, he turned his back on Kellan and fled for the hills. Kellan gripped his magic vines firm, sweat pooling across his face. Molten heat continued to tear through him, right alongside his hurt. #emph[Oko had left him.] The train teetered at the edge of the cliff, inching farther into the open expanse below. Kellan couldn't fight it for much longer. It was too heavy. His magic was faltering, and the Sterling Company was barely a minute away. Kellan blinked at the salt-sting filling the corners of his eyes just as Fortune appeared several yards away, rearing back as Annie drew her thunder rifle. She pointed it beyond Kellan and released a series of blasts toward the approaching guards. "Umezawa—Nolan—" Kellan started. "They're with the others," she answered. Fortune stamped his feet on the rocks, and Annie waved an arm toward the passengers staring out of the windows, most of them too frozen to move. "Get off the train, #emph[now] !" The people looked at one another in alarm before hurrying for the nearest exits. Their legs trembled with fear, each of them nervously jumping for the desert floor before fleeing as far from the train as possible. Kellan took a ragged breath, feeling his energy start to slip. He blinked hard, forcing himself to direct every ounce of stubbornness he had left toward the magic radiating from his hands. Annie sent a few more blasts of energy behind him, trying to pick off the faster riders and stall for time before the bulk of the army arrived. When the final civilian hit the sand, Annie turned to Kellan and thrust out an arm. "Come on, kid." Kellan released his vines with a gasp, and the train shot over the edge of the cliff, exploding in the distance the moment it hit the ground. The #emph[booms] sounded one after the other as each railcar landed in quick succession, followed by a barrage of rock and debris ricocheting off the canyon walls. Kellan grabbed Annie's hand and heaved himself onto Fortune's back, and they bolted for the ridge, leaving the wreckage and Sterling Company behind.
https://github.com/Wh4rp/OCI-Solutions
https://raw.githubusercontent.com/Wh4rp/OCI-Solutions/main/lib/problem.typ
typst
#let problem( letter: "", title: "", statement: "", input: "", output: "", subtasks: (), examples: (), solution: none, ) = { heading(level: 3, [Problema #letter - #title]) statement heading(level: 4, "Entrada", outlined: false) input heading(level: 4, "Salida", outlined: false) output if subtasks != () { heading(level: 4, "Subtareas y puntajes", outlined: false) for (index, subtask) in subtasks.enumerate(start: 1) { heading(level: 5, outlined: false)[ Subtarea #index (#subtask.score puntos) ] subtask.description } } if examples != () { heading(level: 4, "Ejemplos de entrada y salida", outlined: false) for example in examples { move(dx: 2.5%, dy: 0pt, block( inset: 8pt, stroke: 0.5pt + black, width: 95%, )[ #grid( columns: (50%, 50%), [ #heading(level: 5, "Entrada de ejemplo", outlined: false) #example.input ], [ #heading(level: 5, "Salida de ejemplo", outlined: false) #example.output ] ) ] ) } } heading(level: 4, "Solución") solution pagebreak() }
https://github.com/DamienFlury/summaries
https://raw.githubusercontent.com/DamienFlury/summaries/main/AutoSpr/cheat-sheet/main.typ
typst
#import "@preview/ctheorems:1.1.2": * #show: thmrules #set text(lang: "DE", region: "CH", font: "EB Garamond", size: 9pt) #set par(justify: true) #set heading(numbering: "1.1") #set text(lang: "de") #let theorem = thmbox("theorem", "Satz", fill: rgb("#eeffee")) #let proof = thmproof("proof", "Beweis") #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Beispiel").with(numbering: none) #let info = thmbox("info", "Info", fill: rgb("#aaeeff")) #let highlight(x) = text(fill: orange, $#x$) #let conceal(x) = text(fill: gray, $#x$) #let reduction(body) = box(inset: (x: 1em, y: 1em), fill: rgb("#eeffff"), radius: 0.4em, width: 100%)[ *Reduktion:* Folgende Elemente müssen reduziert werden: #body ] #let given_question(given, question) = block(inset: (1em))[*Gegeben:* #given \ *Fragestellung:* #question] #set page("a4", numbering: "1", margin: 20pt, columns: 3, flipped: true) #counter(page).update(1) #text(size: 24pt, [Automaten und Sprachen]) #outline(indent: auto) = Reguläre Sprachen #let screenshot(text) = { box(fill: luma(220), width: 100%, inset: 2em)[#align(center)[*Screenshot* #if(text != none) {[\ #text]} else {}]] } == Deterministische endliche Automaten (DEA) #definition[ Ein DEA ist ein Quintupel $(Q, Sigma, delta, q_0, F)$, wobei: + $Q$, Beliebige endliche Menge von *Zuständen* + $Sigma$, *Alphabet* (Endliche Menge) + $delta: Q times Sigma -> Q$, *Übergangsfunktion* + $q_0 in Q$, *Startzustand* + $F subset Q$, Menge der *Akzeptierzustände* ] #definition[Sei $a$ ein endlicher Automat, dann ist $L(A)$ die Sprache $ L(A) = {w in Sigma^* | "w überführt A in einen Akzeptierzustand"} $] === Myhill-Nerode Automat Wir müssen für beliebige Wörter herausfinden, mit welchem weiteren Input der Automat in einen Akzeptierzustand übergeht. Das leere Wort $epsilon$ ist speziell, wir benötigen die Sprache $L$ selbst, um zum Akzeptierzustand zu kommen. Beispiel: $ Sigma &= {0, 1} \ L &= {w in Sigma^* | |w|_0 "gerade"} $ #table(columns: (auto, 1fr, auto), table.header([w], [L(w)], [Q]), [$epsilon$], [$L(epsilon) = L$], [$q_0$], [$0$], [$L(0) = {w in Sigma^* | |w|_0 "ungerade"}$], [$q_1$], [$1$], [$L(1) = {w in Sigma^* | |w|_0 "gerade"} = L$], [$q_0$]) === Algorithmus für den Minimalautomaten Wir füllen jeweils nur die untere Hälfte der Tabelle aus: + Tabelle erstellen mit allen Zuständen in den Zeilen und Spalten + Äquivalente Zustände (die Diagonale) mit $equiv$ markieren + Akzeptierzustände von normalen Zuständen unterscheiden mit $times$. + Falls man von einem Zustandspaar $(a, b)$ mit einem Übergang bei einem Paar mit $times$ landet, kann man das Paar $(a, b)$ auch mit $times$ markieren. #image("./assets/minimaler-automat.png") === Pumping Lemma für reguläre Sprachen #theorem[Ist $L$ eine reguläre Sprache, dann gibt es eine Zahl $N$, die Pumping Length, so dass jedes Wort $w in L$ mit $|w| >= N$ in drei Teile $w=x y z$ zerlegt werden kann, so dass: $ |y|> 0 \ |x y| <= N \ x y^k z in L, forall k >= 0 $ ] Um zu beweisen, dass eine Sprache nicht regulär ist, nimmt man an, dass sie regulär ist und führt das Pumping Lemma durch. Gibt es einen Widerspruch, ist die Sprache nicht regulär (Widerspruchsbeweis). #let colMath(x, color) = text(fill: color)[$#x$] #example[$L = {0^n 1^n | n >= 0}$][ + Annahme: $L$ ist regulär + $exists N in NN$, Pumping Length + w = $0^N 1^N$ + Unterteilung $w = colMath(x, #green) colMath(y, #red) colMath(z, #blue)$ #figure(image("./assets/pumping-lemma.png"), caption: [Pumping Lemma]) + Pumpen: nur die Anzahl der 0 wird erhöht, Anzahl 1 bleibt + $colMath(x, #green) colMath(y, #red)^k colMath(z, #blue) in.not L "für" k != 1$, im Widerspruch zum Pumping-Lemma ] == Mengenoperationen #image("./assets/mengenoperationen.png") = Reguläre Operationen und Ausdrücke == Alternative $L = L_1 union L_2 = L(A_1) union L(A_2)$ #image("./assets/alternative.png") == Verkettung $L = L_1 L_2 = L(A_1) L(A_2)$ #image("./assets/verkettung.png") == \*-Operation $ L^* &= {epsilon} union L union L^2 union dots.c\ &= union.big_(k = 0)^infinity L^k $ #image("./assets/star-operation.png") == Reguläre Ausdrücke - Metazeichen `() [] * ? | . \` - `[abc] = a|b|c`, `[^abc] = nicht [abc]` (das ^-Symbol bedeutet innerhalb `[]` "nicht") === Erweiterungen - `{n, m}`: zwischen _n_ und _m_ - `+`: mindestens eines (`{1,}`) - `?`: optional (`{0, 1}`) - `\d` Ziffern, `\s` whitespace, `\w` Wortzeichen (inkl. Ziffern), `[:space:], [:lower:], [:xdigit:]` = Kontextfreie Sprachen == Reguläre Operationen $L_1, L_2$ kontextfreie Sprachen mit Grammatiken $G_i = (V_i, Sigma, R_i, S_i)$. Grammatik für reguläre Operationen: - Neue Startvariable $S_0$ - $V = V_1 union V_2 union {S_0}$ - Geeignet erweiterte Regeln $R$ $=> G = (V, Sigma, R, S_0)$ === Alternative Regeln für $L_1 union L_2$: $R = R_1 union R_2 union {S_0 -> S_1, S_0 -> S_2}$ Im Wesentlichen bleiben die einzelnen Regeln dieselben, es müssen nun einfach alle Regeln der Sprachen $L_1, L_2$ untereinander geschrieben werden. Wichtig ist jedoch, dass wir einen neuen Startzustand konstruieren, den wir mit Regeln in $S_1, S_2$ überführen. === Verkettung Regeln für $L_1 L_2$: $R = R_1 union R_2 union {S_0 -> S_1 S_2}$ === \*-Operation Regeln für $L_1^*$: $R = R_1 union {S_0 -> S_0 S_1, S_0 -> epsilon}$ Diese Regel besagt einfach, dass $S_1$ beliebig oft wiederholt werden kann. #theorem[Die Klasse der kontextfreien Sprachen ist abgeschlossen unter regulären Operationen.] == Reguläre Sprachen sind kontextfrei === Bausteine - Einzelne Buchstaben: - $A -> a$ - $B -> b$ - $...$ - $Z -> z$ - Leeres Wort - empty $-> epsilon$ == Chomsky Normalform === Anforderungen an eine Grammatik + Keine Unit-Rules $A -> B$ + Keine Regeln $A -> epsilon$ ausser wenn nötig $S -> epsilon$ (Startvariable $S$) + Keine Regeln mit mehr als 2 Variablen auf der rechten Seite $=>$ Rechte Seite enthält genau zwei Variablen oder genau ein Terminalsymbol === Transformation in CNF + Neue Startvariable $S_0 -> S$ + $epsilon$-Regeln + Unit-Rules + Verkettungen auflösen #example[ $ S &-> A S A | a B \ A &-> B | S \ B &-> b | epsilon $ *Neue Startvariable:* $ highlight(S_0 &-> S) \ S &-> A S A | a B \ A &-> B | S \ B &-> b | epsilon $ *#sym.epsilon eliminieren:* $ S_0 &-> S \ S &-> A S A | a B | highlight(a) \ A &-> B | S | highlight(epsilon) \ B &-> b $ $ S_0 &-> S \ S &-> A S A | highlight(S A) | highlight(A S) | conceal(S) | a B | a \ A &-> B | S \ B &-> b $ *Unit-Rules:* $ S_0 &-> S \ S &-> A S A | S A | A S | a B | a \ A &-> highlight(b) | S \ B &-> b $ $ S_0 &-> highlight(A S A) | highlight(S A) | highlight(A S) | highlight(a B) | highlight(a) \ S &-> A S A | S A | A S | a B | a \ A &-> highlight(A S A) | highlight(S A) | highlight(A S) | highlight(a B) | highlight(a) | b \ B &-> b $ *Verkettungen, Terminalsymbole:* $ S_0 &-> A highlight(A_1) | S A | A S | a B | a \ S &-> A highlight(A_1) | S A | A S | a B | a \ A &-> A highlight(A_1) | S A | A S | a B | a | b \ B &-> b \ highlight(A_1 &-> S A) $ $ S_0 &-> A A_1 | S A | A S | highlight(U) B | a \ S &-> A A_1 | S A | A S | highlight(U) B | a \ A &-> A A_1 | S A | A S | highlight(U) B | a | b \ B &-> b \ A_1 &-> S A \ highlight(U &-> a) $ ] #definition[Chomsky-Normalform][Eine CFG ist in Chomsky-Normalform (CNF), wenn $S$ auf der rechten Seite nicht vorkommt und jede Regel von der Form $A -> B C$ oder $A -> a$ ist, zusätzlich ist die Regel $S -> epsilon$ erlaubt.] = Nicht kontextfreie Sprachen == Pumping-Lemma für kontextfreie Sprachen #figure(grid(columns: (1fr, 1fr), image("./assets/pumping-lemma-cfg-herleitung.png"), image("./assets/pumping-lemma-cfg-herleitung-2.png") ), caption: [Herleitung Pumping Lemma für CFGs]) #definition[Pumping Lemma für CFL][ Ist $L$ eine CFL, dann gibt es eine Zahl $N$, die Pumping Length, derart, dass jedes Wort $w in L$ mit $|w| >= N$ zerlegt werden kann in fünf Teile $w = u v x y z$ derart, dass: + $|v y| > 0$ + $|v x y| <= N$ + $u v^k x y^k z in L, forall k in NN$ ] Mit dem Pumping-Lemma kann man beweisen, dass eine Sprache _nicht_ kontextfrei ist. #example[${a^n b^n c^n | n >= 0}$ \ + AnnahmeL $L$ kontextfrei + Pumping Length $N$ + Wort: $w = a^N b^N c^N$ + Zerlegungen (mehrere): #image("./assets/pumping-lemma-cfl.png") + Beim Pumpen nimmt die Anzahl der a und b zu, nicht aber die Anzahl der c $=> u v^k x y^k z in.not L, forall k != 1$ + Widerspruch: $L$ nicht kontextfrei ] = Turing-Maschinen == Berechnungsgeschichte #image("./assets/berechnungsgeschichte.png", width:80%) #image("./assets/transition.png", width: 80%) = Entscheidbarkeit Eine Sprache heisst entscheidbar, wenn es einen Entscheider gibt, der prüfen kann, ob ein Wort $w$ in der Sprache liegt. #example[Sei $A$ ein DEA. Dann kann man folgenden Algorithmus $M_A$ mit Input $w$ bauen: + Simuliere $A$ auf $w$ + Falls $A$ in Akzeptierzustand: $q_"accept"$ + Andernfalls: $q_"reject"$ Daraus folgt $L(A) = L(M_A)$, oder $M_A$ ist ein Entscheider für die Sprache $L(A)$.] #theorem[Reguläre Sprachen sind entscheidbar.] #example[Sei $G$ eine CFG. Dann kann man folgenden Algorithmus $M_G$ mit Input $w$ bauen: + Wandle $G$ in Chomsky-Normalform $G'$ um + Wende den CYK-Algorithmus auf $G'$ und Wort $w$ an + Wenn der CYK-Algorithmus das Wort $w$ akzeptiert: $q_"accept"$ + Andernfalls: $q_"reject"$ ] == Defintion Entscheidbarkeit #definition[Entscheider][ Ein Entscheider ist eine Turing Maschine, die auf jedem beliebigen Input anhält. ] #definition[Entscheidbar][Eine Sprache $L$ heisst entscheidbar, wenn es einen Entscheider $M$ gibt mit $L = L(M)$. Man sagt, $M$ entscheidet $L$.] Jedes Problem kann in ein Sprachproblem übersetzt werden: $ L_P = {w in Sigma^* | w "ist Lösung des Problems" P} $ #example[Leerheitsproblem][$ E_"DEA" = {angle.l A angle.r | A "ein DEA und" L(A) = emptyset } $] #example[Gleichheitsproblem][$ italic("EQ")_"CFG" = {angle.l G_1, G_2 angle.r | G_i "CFGs und" L(G_1) = L(G_2)} $] #example[Akzeptanzproblem][$ A_"DEA" = {angle.l A, w angle.r | A "ein DEA, der" w "akzeptiert"} $] #example[Halteproblem][$ italic("HALT")_"TM" = { angle.l M, w angle.r | M "hält auf Input" w} $] #theorem[Halteproblem][Das spezielle Halteproblem $ italic("HALT")epsilon_"TM" \ = {angle.l M angle.r | M "ist eine Turingmaschine und" M "hält auf leerem Band"} $ ist nicht entscheidbar.] #theorem[Allgemeines Halteproblem][Das allgemeine Halteproblem $ italic("HALT")_"TM" \ = {angle.l M, w angle.r | M "ist eine Turingmaschine und" M "hält auf Input" w} $ ist nicht entscheidbar.] Weitere nicht entscheidbare Probleme: - Leerheitsproblem $E_"TM"$ == Satz von Rice Eigenschaften Turing-erkennbarer Sprachen - $italic("REGULAR")$: $L(M)$ ist regulär - $E$: $L(M)$ ist leer #definition[Eine Eigenschaft $P$ Turing-erkennbarer Sprachen heisst nichttrivial, wenn es zwei Turingmaschinen $M_1$ und $M_2$ gibt, mit: $ &L(M_1) "hat Eigenschaft" P \ &L(M_2) "hat Eigenschaft" P "nicht" $] #theorem[Rice][Ist $P$ eine nichttriviale Eigenschaft Turing-erkennbarer Sprachen, dann ist $ P_"TM" = {angle.l M angle.r | L(M) "hat Eigenschaft" P} $ nicht entscheidbar.] = Komplexität == P -- NP == Aufüllrätsel Viele Ausfüllrätsel wie z.B. Sudoku sind exponentiell lösbar. Man versucht dabei einfach jede Möglichkeit und falls eine Möglichkeit nicht zu einer korrekten Lösung führt, machen wir ein Backtracking. Man spricht von einer Nicht-Deterministischen Turing-Maschine, bei welcher wir alle Möglichkeiten durchprobieren müssen. Eine solche Maschine kann aber polynomiell verifiziert werden, in dem man den Pfad durchgeht, welcher verwendet worden ist für die Lösung des Rätsels und prüft, ob dieser in $q_"accept"$ landet. == Reduktion Sudoku #sym.arrow CONSTRAINTS #sym.arrow SAT Sudoku-Regeln werden als logische "Constraints" formuliert. Dabei müssen alle Constraints erfüllt sein. Es gibt Software/Libraries wie python-constraint für diese Probleme. *Allgemein*: Jedes Ausfüllrätsel lässt sich auf CONSTRAINTS = SAT reduzieren. === SAT Eine logische Formel ist in SAT genau dann, wenn sie erfüllt werden kann. Constraints werden miteinander "verundet", diese Formel soll wahr ergeben. $ "SAT" = {phi | phi "erfüllbar"} $ S eine Sprache in NP #sym.arrow.double Es gibt eine nichtdeterministische TM $M$, die $A$ in polynomieller Zeit $O(t(n))$ entscheidet. #sym.arrow.double $A$ kann polynomiell auf SAT reduziert werden: $A scripts(<=)_P "SAT"$ Beschreibe das Finden der Berechnungsgeschichte von $M$ als polynomielles Ausfüllrätsel. == Karp-Katalog === SAT<sat> Das SAT-Problem prüft im Allgemeinen, ob ein Ausdruck `true` wird. Dann ist er _satisfiable_. Es sind folgende Dinge gegeben: - Aussagenlogische Formel === Folgerungen aus P = NP + Für jedes Problem in NP gibt es einen polynomiellen Algorithmus + Es gibt keine "schwierigen" Probleme + Mit Moore's Law lässt sich jedes Problem "lösen" + Es gibt keine sichere Kryptographie === Folgerungen aus P #sym.eq.not NP + NP-vollständige Probleme haben nicht skalierende Lösungen + Moore's Law hilft nicht in NP \\ P === NP-vollständig Eine entscheidbare Sprache B heisst NP-vollständig, wenn sich jede Sprache A in NP polynomiell auf B reduzieren lässt: $ A scripts(<=)_P B, forall A in "NP" $ Wenn ein Problem NP-vollständig ist: - Lösung braucht typischerweise exponentielle Zeit - Korrektheit der Lösung ist leicht (in polynomieller Zeit) zu prüfen - Andernfalls wären Tests schon exponentiell und somit in Software nicht sinnvoll Falls P #sym.eq.not NP, dann können NP-vollständige Probleme nicht in polynomieller Zeit gelöst werden. #reduction[ - Variablen (boolesche Werte) - Aktion, die den Wahrheitszustands einer Variable verändert - (falls vorhanden) Zwischenausdrücke von logischen Formeln - Finaler Logischer Ausdruck zur Erfüllung des Ausgangproblems] SAT eignet sich für Probleme, bei welchen Elemente (Variablen) nur zwei Zustände einnehmen können. Jedes Ausfüllrätsel ist mit SAT beschreibbar. Man kann Wahrheitstabellen bilden. Jedes Problem, das sich auf SAT reduzieren lässt, ist NP-vollständig. === #smallcaps[k-Clique] #given_question[ Graph $G$ (bestimmte Anzahl und Anordnung von Knoten), Zahl $k$ ][ Gibt es $k$ Knoten, die alle miteinander verbunden sind? Diese Knoten bilden eine sogenannte k-CLIQUE. ] #figure(image("./assets/k-clique.png"), caption: [k-Clique]) #reduction[ - Knoten (die miteinander via Kanten verbunden werden) - Kanten - k (Anzahl verbundener Knoten, bzw. Grösse der Clique) - Clique (Was bildet die Clique?)] Eignet sich für Probleme, bei denen möglichst viele Elemente eine Bedingung erfüllen müssen. === #smallcaps[Set-Packing] #given_question[ Eine Familie $(S_i), i in I$ und eine Zahl $k in NN$ ][ Gibt es eine $k$-elementige Teilfamilie $(S_i), i in J$ mit $J subset I$ (also $|J| = k$) derart, dass die Menge der Teilfamilie paarweise disjunkt sind ($S_i sect S_j = emptyset$)? ] #figure(image("./assets/np-complete-set-packing.png"), caption: [SET-PACKING]) #reduction[ - Menge $I$ (Eigenschaft zum Vergleich von Elementen) - Familie $S_i$ (Elemente mit Eigenschaften aus der Menge $I$) - Teilmenge $J$ von $I$ (so dass |J| = k) - Teilfamilie, so dass die enthaltenen Mengen unterscheidbar sind ] === #smallcaps[Vertex-Cover] #given_question[ Graph $G$ und eine Zahl $k$. ][ Gibt es eine Teilmenge von $k$ Vertizes so, dass jede Kante des Graphen ein Ende in dieser Teilmenge hat? Jeder Knoten ausserhalb des Graphen muss dementsprechend eine Kante zur Teilmenge besitzen. ] #figure(image("./assets/np-complete-vertex-cover.png"), caption: smallcaps[Vertex-Cover]) #reduction[ - Knoten des Graphen - Kanten (Verbindung zwischen den Knoten) - $k$ (Anzahl Knoten, so dass jeder andere Knoten in dieser Teilmenge eine Kante besitzt) ] === #smallcaps[Feedback-Node-Set]<feedback-node-set> #given_question[ Gerichteter Graph $G$ und eine Zahl $k$ ][ Gibt es eine endliche Teilmenge von $k$ Vertizes in $G$ so, dass jeder Zyklus#footnote[Ein Zyklus ist ein sich wiederholender Ablauf]<cycle> in $G$ einen Vertex in der Teilmenge enthält? ] #info[Gerichtete Graphen sind eine Klasse von Graphen, die keine Symmetrie zwischen den Knotenpunkten gebildeten Kanten voraussetzen.] #figure(image("./assets/np-complete-feedback-node-set.png"), caption: smallcaps[Feedback-Node-Set]) #reduction[ - gerichteter Graph - Knoten - Kanten - Richtung - Zyklen - $k$ (Anzahl verbindende Knoten) - Node Set (ausgewählte Knoten) ] === #smallcaps[Feedback-Arc-Set] #given_question[ Gerichteter Graph $G$, Zahl $k$ ][ Gibt es eine Teilmenge von $k$ Kanten so, dass jeder Zyklus@cycle in $G$ eine Kante aus der Teilmenge enthält? ] Im Vergleich zum #smallcaps[Feedback-Node-Set] wird im #smallcaps[Feedback-Arc-Set] meist beschrieben, dass ein Vorgang wähernd einer Verschiebung (auf einer Kante) gemacht wird. #figure(image("./assets/np-complete-feedback-arc-set.png"), caption: smallcaps[Feedback-Arc-Set]) #reduction[ - gerichteter Graph - Knoten - Kanten - Richtung - Zyklen - k (Anzahl verbindende Kanten) - Arc Set (ausgewählte Kanten) ] === #smallcaps[Hampath] (Hamiltonischer Pfad) Das #smallcaps[Hampath]-Problem beschreibt die Suche nach einem geschlossenen Pfad in einem gerichteten Graphen, der genau einmal durch jeden Knoten geht. #figure(image("./assets/np-complete-hampath.png"), caption: smallcaps[Hampath]) === #smallcaps[UHampath] Das #smallcaps[UHampath]-Problem beschreibt die Suche nach einem hamiltonischen Pfad in einem *ungerichteten Graphen* zu finden. #info[Bei einem ungerichteten Graphen sind die Verbindungen zwischen den Knoten (Kanten) symmetrisch.] #figure(image("./assets/np-complete-uhampath.png"), caption: smallcaps[UHampath]) === #smallcaps[Set-Covering] #given_question[ endliche Familie endlicher Mengen $\(S_j\)_(1 <= j <= n)$ und eine Zahl $k$ ][ Gibt es eine Unterfamilie bestehend aus $k$ Mengen, die die gleiche Vereinigung hat? Kann man $k$ Teilmengen bilden, welche die Menge $S$ komplett abdecken? ] Ziel ist es, alle Elemente abzudecken. Überschneidungen der Mengen sind möglich. #figure(image("./assets/np-complete-set-covering.png"), caption: smallcaps[Set-Covering]) #reduction[ - Nummerierung von 1 bis $n$ - Familie endlicher Mengen - Unterfamilie bestehend aus $k$ Mengen - Bedingung der beiden Vereinigungen ] === BIP Das BIP-Problem (Binary Integer Programming) beschreibt, dass zu einer ganzzahligen Matrix $C$ und einem ganzzahligen Vektor $d$ ein binärer Vektor $x$ gefunden werden kann mit $C dot x = d$. $ mat(1, 3, 0; 0, 2, 5) dot vec(1, 0, 1) = vec(1, 5) $ #reduction[ - Matrix $C$ - Vektor $d$ - Resultat für die Suche nach dem Vektor $x$ zur Erfüllung der Gleichung $C dot x = d$ ] === 3SAT 3SAT ist eine Variante vom SAT-Problem, wo die aussagenlogische Formel als konjunktive Normalform mit 3 Variablen pro Klausel gegeben ist. Beispiel: $ (x_1 or x_2 or x_3) and (not x_1 or x_2 or not x_3) $ Mit Erfüllungsequivalenz darf jede SAT-Formel in eine 3SAT-Formel umgewandelt werden. Die Reduktion ist identisch zu @sat SAT. === #smallcaps[Vertex-Coloring] Beim $k$-Vertex-Coloring-Problem sind folgende Dinge gegeben: #given_question[ Graph $G$, Anzahl $k$ Farben ][ Kann man die Knoten so mit $k$-Farben einfärben, dass benachbarte Knoten verschiedene Farben haben? ] *Fragestellung:* #figure(image("./assets/np-complete-k-vertex-coloring.png"), caption: smallcaps[k-Vertex-Coloring]) #reduction[ - Vertizes - Kanten - Farben - $k$: Anzahl Farben ] Die verbundenen Vertizes sollen alle verschiedene Farben haben: - Die Farben stellen den (gesuchten) Unterschied zwischen den Vertizes dar (eine unterscheidbare Eigenschaft) - Die Kanten zwischen den Vertizes stellen die Regeln für die unterscheidbaren Objekte dar. Das #smallcaps[Vertex-Coloring]-Problem eignet sich für Probleme, bei denen Elemente, die miteinander in Beziehung stehen, unterschieden werden müssen. === #smallcaps[Clique-Cover] #given_question[ Graph $G$, positive Zahl $k$ ][ Gibt es $k$ Cliquen so, dass jede Ecke in genau einer der Cliquen ist? ] #figure(image("./assets/np-complete-clique-cover.png"), caption: smallcaps[Clique-Cover]) #reduction[ - Vertizes - Kanten - $k$ (Anzahl Vertizes) - Clique (verbund von möglichst vielen Vertizes) - Covering (Bedingung) ] === #smallcaps[Exact-Cover] #given_question[ Eine Familie $\(S_j\)_(1 <= j <= n)$ von Teilmengen einer Menge $U$. ][ Gibt es eine Unterfamilie von Mengen, die disjunkt sind, aber dieselbe Vereinigung haben? Die Unterfamilie $\(S_j_i\)_(1 <= i <= m)$ muss also $S_(j i) sect S_(j k) = 0$ und $union.big_(j=1)^n S_j = union.big_(i = 1)^m S_(j i)$ erfüllen. ] Jedes Element in $U$ soll genau in einer der Teilmengen einer Familie $S$ vorkommen. Die gesuchte Menge bildet eine exakte Überdeckung. Es darf keine Überschneidungen geben, aber alle Elemente sollen abgedeckt werden. #figure(image("./assets/np-complete-exact-cover.png"), caption: smallcaps[Exact-Cover]) #reduction[ - Menge $U$ - Familie $S_j subset U$ - Unterfamilie $S_(j i)$ (so, dass die gleiche Vereinigung wie die Familie $S_j$ erzielt wird) - Bedingung $S_(j i) sect S_(j k) = 0$ - Bedingung $union.big_(j=1)^n S_j = union.big_(i=1)^m S_(j i)$ ] #info[Unterschied Set-Covering, Exact-Cover, Set-Packing][ - In #smallcaps[Set-Covering] und #smallcaps[Set-Packing] kommt eine Zahl $k$ (z.B. maximale Anzahl Allergien) vor, nicht aber in #smallcaps[Exact-Cover]. - In #smallcaps[Set-Covering] dürfen sich die Mengen schneiden, müssen aber auch alles abdecken. In #smallcaps[Set-Packing] dürfen sich die Mengen nicht schneiden, müssen aber auch nicht alles abdecken. - In #smallcaps[Exact-Cover] dürfen sich die Mengen nicht schneiden, müssen alles abdecken, aber es kommt nicht auf ihre Anzahl an. ] === #smallcaps[3D-Matching] #given_question[ Endliche Menge $T$ und Menge $U$ von Tripeln $T^3$. ][ Gibt es eine Teilmenge $W$ von $U$ so, dass $|W| = |T|$ und keine zwei Elemente von $W$ in irgendeiner Koordinate übereinstimmen? ] Für jeden Wert im Tripel $(x, y, z)$ gibt es eine bestimmte Bedeutung abhängig vom Kontext. #figure(image("./assets/np-complete-3d-matching.png"), caption: smallcaps[3D-Matching]) #reduction[ - Menge $T$ (normalerweise eine bestimmte Anzahl $n$ von Elementen) - Tripel aus $T^3$ - Menge $U$ (bestehend aus Kombinationen der Tripel) - Teilmenge $W$ von $U$ so, dass $n = |W| = |T|$ (jedes Tripel muss in jedem Element für $x, y, z$ eindeutig sein) ] #example[ - $T = {0, 1}$ - $U = {(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)}$ - $W = {(1, 0, 1), (0, 1, 0)}$ erfüllt die Bedingung ] === #smallcaps[Steiner-Tree] #given_question[ Ein Graph $G$, eine Teilmenge $R$ von Verizes, eine Gewichtsfunktion und eine positive Zahl $k$. ][ Gibt es einen Baum mit Gewicht $<= k$, dessen Knoten in $R$ enthalten sind? Das Gewicht des Baumes ist die Summe der Gewichte über alle Kanten im Baum. ] #figure(image("./assets/np-complete-steiner-tree.png"), caption: smallcaps[Steiner-Tree]) #reduction[ - Vertizes - Kanten (im Fall X) - Gewichtsfunktion (zum Vergleich der Kanten und Wahl des Baumes) - Knoten in $R$ (bestimmte Auswahl von Vertizes aufgrund einer Bedingug) - maximales Gewicht $k$ (so, dass es sich noch "lohnt") - Baum (der die einzelnen Vertizes schliesslich verbinden soll) ] === #smallcaps[Hitting-Set] #given_question[ Menge von Teilmengen $S_i subset S$ ][ Gibt es eine Menge $H$, die jede Menge in genau einem Punkt trifft $(H subset union.big_(i in J) S_i)$, also $|H sect S_i| = 1$? ] #example[ - Gegeben: $A = {1, 2, bold(3)}, B = {1, 2, bold(4)}, C = {1, 2, bold(5)}$ - Gesucht: $H = {3, 4, 5}$ ] #reduction[ - $i$ (Bedingung/Merkmal zur eindeutigen Auswahl eines Elements) - Menge $S_i$ (Menge von Teilmengen) - Menge $H$ (Resultat mit Bedingung $|H sect S_i| = 1$) ] === #smallcaps[Subset-Sum] #given_question[ Menge $S$ von ganzen Zahlen ][ Kann man eine Teilmenge finden, die als Summe einen bestimmten Wert $t$ hat? ] #reduction[ - Elemente, zwischen denen entschieden werden muss - Menge $S$ von Elementen - bestimmter Wert $t$ - Teilmenge $T$, so dass die Werte der Elemente dem Wert $t$ entspricht: $sum_(x in T) x = t$ ] Der Name "Rucksack"-Problem rührt daher, dass man sich die Zahlen aus $S$ als "Grösse" von Gegenständen vorstellt, und wissen möchte, ob man einen Rucksack der Grösse $t$ exakt füllen kann mit einer Teilmenge von Gegenständen aus $S$. === #smallcaps[Sequencing] #given_question[ Ein Vektor von Laufzeiten von $p$ Jobs, ein Vektor von spätesten Ausführzeiten, ein Strafenvektor und eine positive ganze Zahl $k$. ][ Gibt es eine Permutation der Zahlen $1, ..., p$, sodass die Gesamtstrafe für verspätete Ausführung bei der Ausführung der Jobs nicht grösser ist als $k$? ] Vereinfachte Definition:\ #given_question[ Eine Menge von Jobs, pro Job eine Ausführzeit, Deadline und eine Strafe sowie eine maximale Strafe $k$. Die Jobs müssen sequenziell abgearbeitet werden. Wird ein Job zu spät fertig, muss eine Strafe gezahlt werden. ][ Gibt es eine Reihenfolge von Jobs so, dass die Strafe kleiner gleich $k$ ist? ] #reduction[ - Ausführungszeit von Job - Deadline - Strafe - Permutation/Reihenfolge - Zusammensetzung der Gesamtstrafe ] === #smallcaps[Partition] #given_question[ Eine Folge von $n$ ganzen Zahlen $c_1, c_2, ... c_n$ ][ Kann man die Indizes $1, 2, ..., n$ in zwei Teilmengen $I$ und $overline(I)$ teilen, so dass die Summe der zugehörigen Zahlen $c_i$ identisch ist ($sum_(i in I) c_i = sum_(i in overline(I)) c_i$)? Gibt es zwei disjunktive Teilmengen mit derselben Summe? ] #reduction[ - Indizes $i$ (konkretes Objekt zum Vergleich/zur Aufteilung) - Werte der Vergleichsobjekte $c_i$ - Aufteilung in zwei Teilmengen $I$ und $overline(I)$ so, dass der Wert der entsprechenden Vergleichsobjekte identisch ist ] #example[ Eine Reihe von Wassergläsern ist unterschiedlich gefüllt. Es sollen 2 Behählter gleich voll mit den Gläsern gefüllt werden. Welche Gläser müssen in welche Behälter geleert werden? ] === #smallcaps[Max-Cut] #given_question[ Graph $G$ mit einer Gewichtsfunktion $w : E -> Z$ und eine ganze Zahl $W$. ][ Gibt es eine Teilmenge $S$ der Vertizes, so dass das Gesamtgewicht der Kanten, die $S$ mit seinem Komplement verbinden, so gross wie $W$? ] $ sum_({u,v} in E and u in S and v in.not S) w({u, v}) >= W $ Der Max-Cut eines Graphen ist eine Zerlegung seiner Knotenmenge in zwei Teilmengen, sodass das Gleichgewicht der Zwischen den beiden Teilen verlaufenden Kanten mindestens $W$ wird. #smallcaps[Max-Cut] sucht die maximalen Investitionen, die man in den Sand setzen muss, indem man eine Menge von Verbindungen durchschneidet. #figure(image("./assets/np-complete-max-cut.png"), caption: smallcaps[Max-Cut]) #reduction[ - Vertizes - Kanten - Gewichtsfunktion der Kante (zum Vergleich der Kanten) - Wert $W$ (Ziel, das bei der Wahl der Teilmenge $S$ der Vertizes überstiegen werden sollte) - Gesamtgewicht - Teilmenge $S$ der Vertizes (Trennlinie zwischen zwei Gruppierungen) ] = Turing-Vollständigkeit == Die universelle Turing-Maschine Gibt es eine TM, die jede beliebige TM simulieren kann? <NAME>, Ada Lovelace: Analytical Engine Alan Turing: Es gibt eine Turing-Maschine, die jede beliebige andere Turing-Maschine simulieren kann#footnote[Alan Turing (1936): On Computable Numbers, With an Application to the Entscheidungsproblem]: - Eigenes Band für die Codierung der Übergangsfunktion $delta: Q times Gamma -> Q times Gamma times {L, R}$ - Eigenes Band für den aktuellen Zustand - Arbeitsband - Simulation dieser Maschine auf einer Standard-TM == Programmiersprachen und Turing-Vollständigkeit #definition[ Eine Programmiersprache heisst Turing-vollständig, wenn in ihr jede beliebige Turing-Maschine siumuliert werden kann. ] Frage: Gibt es einen in $A$ geschriebenen Turing-Maschinen-Simulator? == Turing-Vollständigkeit von Programmiersprachen === LOOP Führe ein Programm $P$ genau $x_i$ mal aus: ``` LOOP x_i DO P END ``` Daraus kann eine if-Kontrollstruktur erstellt werden: ``` IF x_i THEN P END ``` wird folgendermassen realisiert: ``` y := 0 LOOP x_i DO y := 1 END LOOP y DO P END ``` === Turing-Vollständigkeit Für Turing-Vollständigkeit wird neben `LOOP` noch eine `GOTO`-Struktur benötigt. = Logik == Prädikate - Aussagen über mathematische Objekte, wahr oder falsch - Funktionen mit booleschen Rückgabewerten: $P$, $Q(n)$, $R(x, y, z)$ == Verknüpfungen - und: $P and Q$ - oder: $P or Q$ - nicht: $not P$ - Implikation $P => Q = not P or Q$ == Distributivgesetze - $P and (Q or R) <=> (P and Q) or (P and R)$ - $P or (Q and R) <=> (P or Q) and (P or R)$ == De Morgan - $not (P and Q) <=> not P or not Q$ - $P => Q <=> (not Q => not P)$ == Quantoren - $forall i in {1, ..., n} (P_i)$ = (Für alle $i$ ist $P_i$ wahr) - $exists i in {1, ..., n} (P_i)$ = (Es gibt ein $i$ derart, dass $P_i$ wahr ist) === Morgan 2.0 "Nicht für alle" = "Es gibt einen Fall, für den nicht" $ not forall i in {1, ..., n}(P_i) \ <=> not (P_1 and dots.c and P_n) <=> not P_1 or dots.c or not P_n <=> exists i in {1, ..., n}(not P_i) $ = Alphabet und Wort - Alphabet: $Sigma$ - Wort: Ein $n$-Tuplel in $Sigma^n = Sigma times dots.c times Sigma$ - Menge aller Wörter: $Sigma^* = {epsilon} union Sigma union Sigma^2 union dots.c = union.big_(k=0)^infinity Sigma^k$ == Wortlänge - $|epsilon| = 0$ - $|01010|_0 = 3$ - $|(1201)^7| = 7 dot |1201| = 28, |w^n| = n dot |w|$ = Beispiele für DEAs: - Durch drei teilbare Zahlen - Wörter mit einer geraden Anzahl $a$ - Bedingungen an einzelne Zeichen, wie: Wörter, die mit einem $a$ beginnen und genau ein $b$ enthalten. = Kontextfreie Grammatik == Grammatik für Klammerausdrücke $ A &-> epsilon \ &-> A A \ &-> (A) $ Oder (Kurzschreibweise): $ A -> epsilon | A A | (A) $ === Beispiel für Ableitung von Klammerausdruck Wort $(()())$ soll abgeleitet werden: $ A -> (A) -> (A A) -> ((A)A) -> ((A)(A)) -> ((epsilon)(A)) -> ((epsilon)(epsilon)) -> (()()) $ == Parse Tree #definition[Zwei Ableitungen eines Wortes $w$ einer kontextfreien Sprache $L(G)$ heissen äquivalent, wenn sie den gleichen Ableitungsbaum haben. Hat eine Sprache Wörter mit verschiedenen Ableitungen, heisst sie mehrdeutig (engl. ambiguous)] Ein Beispiel einer Grammatik, die nicht eindeutige Ableitungen hat, ist: $ G = ({S}, {0, 1}, {S -> 0 S 1 | 1 S 0 | S S | epsilon}, S) $ Ein Ausruck $001011$ produziert verschiedene Parsetrees (siehe @ambiguous-grammar). #figure(placement: auto, grid(columns: (1fr, 1fr), gutter: 1cm, image("./assets/derivation-1.png"), image("./assets/derivation-2.png")), caption: [Nicht eindeutig ableitbare Grammatik])<ambiguous-grammar> Von besonderer praktischer Bedeutung sind jedoch Grammatiken, die immer eindeutig ableitbar sind. Ein Beispiel solch einer Grammatik ist die `expression-term-factor`-Grammatik für einfache arithmetische Ausdrücke. === regex $->$ CFG #example[Grammatik zum regulären Ausdruck `(ab)*|c`: $ "Alternative: " &S -> U | C \ "*-Operation: " &U -> U P | epsilon \ "Verkettung:" &P -> A B \ "a: " &A -> a \ "b: " &B -> b \ "c: " &C -> c $] == Arithmetische Ausdrücke $ "expression" &-> "expression" + "term" \ & -> "term" \ "term" &-> "term" * "factor" \ &-> "factor " \ "factor" &-> ("expression") \ &-> upright(N) \ upright(N) &-> "NZ" \ &-> upright(Z) \ Z &-> 0|1|2|3|4|5|6|7|8|9 $ === Anwendungen der Chomsky-Normalform *Gegeben:* Grammatik $G$ in Chomsky-Normalform #theorem[Ableitung eines Wortes $w in L(G)$ ist immer in $2|w| - 1$ Regelanwendungen möglich.] #proof[ - $|w| - 1$ Regeln der Form $A -> B C$ um aus $S$ ein Wort aus $w$ Variablen zu erzeugen - $|w|$ Regeln der Form $A -> a$, um das Wort $w$ zu erzeugen ] === Deterministisches Parsen *Aufgabe: $S =>^* w$* \ Kann das Wort $w in Sigma^*$ von der Grammatik $G = (V, Sigma, R, S)$ erzeugt werden? *Verallgemeinerte Aufgabe: $A =>^* w$* \ Kann das Wort $w in Sigma^*$ aus der Variablen $A$ in der Grammatik $G = (V, Sigma, R, s)$ abgeleitet werden? *Deterministische Antwort:* \ Gesucht ist ein Programm mit der Signatur ```java boolean ableitbar(Variable a, String w); ``` welches entscheiden kann, ob ein Wort $w$ aus der Variablen $V$ ableitbar ist. === CYK-Ideen + Grammatik $G = (V, Sigma, R, S)$ + Variable $A in V$ + Wort $w in Sigma^*$ *Frage:* Ist $w$ aus $A$ ableitbar? In Zeichen $A =>^* w$ - Spezialfall $w = epsilon$: $A =>^* epsilon <=> A -> epsilon in R$ - Spezialfall $|w| = 1$: $A =>^* w <=> A -> w in R$ - Fall $|w| > 1$: $ A =>^* w => exists cases(A -> B C in R, w = w_1 w_2\, w_i in Sigma^*) "mit" cases(B =>^* w_1, C =>^* w_2) $ === CYK-Algorithmus #[ #show raw.line: it => { show regex("\\$.*\\$"): it => { eval(it.text) } it.body.text } ``` boolean ableitbar(Variable A, String w) { if (w.length() == 0) { return $A -> epsilon in R$; } if (w.length() == 1) { return $A -> w in R$; } foreach Unterteilung $w = w_1 w_2$ { foreach $A -> B C in R$ { if (ableitbar(B, $w_1$) && ableitbar(C, $w_2$)) { return true; } } } return false; } ``` ] == Stack-Automaten #figure(image("./assets/stack-transitions.png"), caption: [Stackübergänge]) $ a, b -> c $ - $a$: vom Input - $b$: vom Stack entfernen (Bedingung) - $c$: auf den Stack #example[${0^n 1^n | n >= 0}$ \ #figure(image("./assets/stackautomat.png"), caption: [Stackautomat]) ] #definition[Stackautomat][ $ P = (Q, Sigma, Gamma, delta, q_0, F) $ + $Q$: Zustände + $Sigma$: Eingabe-Alphabet + $Gamma$: Stack-Alphabet + $delta$: $Q times Sigma_epsilon times Gamma_epsilon -> P(Q times Gamma_epsilon)$, Regeln + $q_0 in Q$: Startzustand + $F subset Q$: Akzeptierzustände Die Regeln hängen ab vom aktuellen Zustand, vom aktuellen Inputzeichen und vom Zeichen, das zuoberst auf dem Stack liegt. $delta$: Funktion mit drei Inputs (aktueller Zustand, Input-Zeichen, oberstes Zeichen auf dem Stack) und gibt ein Tupel zurück mit neuem Zustand und neuem obersten Zeichen auf dem Stack. *Beachte:* - Immer nicht-deterministisch - $Gamma != Sigma$ möglich (z.B. \$-Symbol auf den Stack) ] === Visualisierung eines Stacks #example[ Grammatik: $ S &-> 0 S 1\ &-> epsilon $ Input: 0 0 0 1 1 1 + \$-Symbol auf den Stack (um später zu prüfen, ob der Stack leer ist) + Variable $S$ auf den Stack + Input 0 matcht nicht $->$ Variable $S -> 0 S 1$ (1 auf den Stack, dann $S$, dann 0) + 0 matcht $->$ 0 vom Stack entfernen und weiter + 0 matcht nicht $S -> 0 S 1$ #figure(grid(gutter: 5pt, columns: (1fr, 1fr, 1fr, 1fr, 1fr), image("./assets/stack0.png"), image("./assets/stack1.png"), image("./assets/stack2.png"), image("./assets/stack3.png"), image("./assets/stack4.png"), [1], [2], [3], [4], [5] ), caption: [Stack-Visualisierung]) *Zustandsdiagramm:* #figure(grid(columns: (1fr, 1fr), image("./assets/state-start.png"), image("./assets/state-finish.png")), caption: [Zustandsdiagramm erstellen]) ] === Grammatik #sym.arrow Stackautomat #figure(image("./assets/grammar-to-pda.png"), caption: [CNF zu Stackautomat]) === Backus-Naur-Form (BNF) Grammatik: $ S &-> epsilon \ &-> 0 S 1 $ BNF: \ `<string> ::= '' | 0 <string> 1` #example[Expression-Term-Factor][ ``` <expression> ::= <expression> + <term> | <term> <term> ::= <term> * <factor> | <factor> <factor> ::= ( <expression> ) | <number> <number> ::= <number> <digit> | <digit> <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ``` ] == PDA zu CFG *Variablen* \ Wörter beschreiben Pfade durch den Automaten: Variable $A_(p q)$ = Wörter, die von $p$ nach $q$ führen mit leerem Stack *Regeln* \ Regeln beschreiben, wie sich Wege zerlegen lassen. $ A_(p q) -> A_(p r) A_(r q) $ === Stackautomat standardisieren + Nur ein Akzeptierzustand - $forall q in F$: Übergang in neuen Akzeptierzustand $q_a$ + Stack leeren: - Markierungszeichen zu Beginn auf den Stack - Am Schluss: $epsilon, . -> epsilon$ und dann $epsilon, \$ -> epsilon$ von $q_a$ nach $q'_a$ + Jeder Übergang legt entweder ein Zeichen auf den Stack oder entfernt eines #image("./assets/stack-standard.png") === Regeln $A_(p q)$ wird, falls sich der Stack dazwischen nicht leert, zu folgendem: == Vergleich von Maschinen #definition[Eine TM $M_1$ ist "leistungsfähiger" als eine TM $M_2$, wenn $M_1$ die Maschine $M_2$ simulieren kann $ M_2 <=_S M_1 $ $M_2$ ist simulierbar auf $M_1$.] Beispiele: - $"TM" scripts(<=)_S "Minecraft"$ - $"8-Bit CPU" scripts(<=)_S "Minecraft" scripts(<=)_S "TM"$ == Unendlichkeit Die Mengen $NN$ und $RR$ sind nicht gleich mächtig, da es keine bijektive Abbildung $NN -> RR$ gibt. #definition[Mengen $A$ und $B$ heissen _gleich mächtig_, $A tilde.eq B$, wenn es eine Bijektion $A -> B$ gibt.] #definition[Eine Menge $A$ heisst _unendlich_, wenn sie gleich mächtig wie eine echte Teilmenge ist.] #definition[$A$ heisst _abzählbar unendlich_, wenn $A tilde.eq NN$, d.h. $A$ gleich mächtig wie $N$ ist.] #theorem[Die Potenzmenge $P(A)$ einer abzählbar unendlichen Menge $A$ ist immer _überabzählbar unendlich_.] #theorem[Die Vereinigung von endlich vielen abzählbaren Mengen ist abzählbar. Das kartesische Produkt $A times B$ zweier abzählbaren Mengen $A, B$ ist abzählbar.] *Anwendungen:* - Abzählbar unendlich: $Sigma^*$, Menge aller DEAs/NEAs/PDAs/CFGs - Überabzählbar unendlich: Menge aller Sprachen $P(Sigma^*)$ #figure(grid(columns: (2fr, 1fr), image("./assets/empty-stack-rule.png"), image("./assets/empty-stack-rule-applied.png") ), caption: [Regel, falls der Stack dazwischen nie leer wird]) $ A_(p q) -> a A_(r s) b $ #figure(grid(columns: (2fr, 1fr), image("./assets/stack-rule-2.png"), image("./assets/stack-rule-2-applied.png") ), caption: [Falls der Stack zwischendurch leer wird]) $ A_(p q) -> A_(p r) A_(r q) $ === Grammatik ablesen Ausgangspunkt: Standardisierte Grammatik mit Startzustand $q_0$ und $F = {q_a}$. + Startvariable $A_(q_0, q_a)$ + Regeln: #figure(grid(columns: (1fr ,1fr, 1fr), image("./assets/app_to_empty.png"), image("./assets/apq_to_aarsb.png"), image("./assets/apq_to_aprarq.png"), $A_(p p) -> epsilon$, $A_(p q) -> a A_(r s) b$, $A_(p q) -> A_(p r) A_(r q)$ )) #example[PDA zu CFG][ #grid(columns: (1fr, 1fr), image("./assets/pda-to-cfg-example.png"), [ *Grammatik* $ A_(q_0 q_a) &-> epsilon A_(q_1 q_3) epsilon \ A_(q_1 q_3) &-> 0 A_(q_1 q_3) 1 \ &-> epsilon A_(q_2 q_2) epsilon \ A_(q_2 q_2) &-> epsilon $ *Vereinfachung* $ S_0 &-> S \ S &-> 0 S 1 \ &-> epsilon $ $->$ Grammatik für $L = {0^n 1^n | n >= 0}$ ]) ] #definition[Eine Turing-Maschine ist ein 7-Tupel $M = (Q, Sigma, Gamma, delta, q_0, q_"accept", q_"reject")$, wobei: + $Q$ heisst die Menge der Zustände + $Sigma$ heisst das Inputalphabet, es enthählt das Blank-Zeichen *nicht* #footnote[Wäre das Blank-Zeichen in $Sigma$, könnte man das leere Band nicht vom Input unterscheiden.] + $Gamma$ ist das Bandalphabet, es enthält das Blank-Zeichen und $Sigma subset Gamma$ + $delta: Q times Gamma -> Q times Gamma times {L, R}$ ist die Übergangsfunktion] == Spielregeln + Der Speicher ist unbegrenzt + In jeder Zelle steht genau ein Zeichen + Es ist immer nur eine Speicherzelle einsehbar + Der Inhalt der aktuellen Zelle kann beliebig verändert werden + Bewegung immer nur eine Zelle nach links oder rechts + Kein weiterer Speicher (nur die Zustände eines endlichen Automaten) == Zustandsdiagramm #image("./assets/state-diagram-turing-machine.png", width: 50%) == Von einer TM erkannte Sprache $ L(M) = {w in Sigma^* | M "akzeptiert" w} $ #definition[Ein Entscheider ist eine Turing-Mashchine, die auf jedem Input $w in Sigma^*$ anhält. Eine Sprache heisst entscheidbar, wenn ein Entscheider sie erkennt.] Eine Turing-entscheidbare Sprache ist auch Turing-erkennbar. Die Eigenschaft "Turing-entscheidbar" unterscheidet sich von der Eigenschaft "Turing-erkennbar" nur dadurch, dass bei einer entscheidbaren Sprache die Turing-Maschine auf jedem beliebigen Input anhalten muss, während bei einer nur erkennbaren Sprache einzelne Input-Wörter auch dazu führen können, dass die Turing-Maschine endlos weiterrechnet. == Turing Maschinen und moderne Computer #grid(columns: (1fr, 1fr), [ *Turing Maschine* + Zustände Q + Band, unendlich grosser Speicher + Schreib-/Lesekopf + Anhalten, $q_"accept"$ und $q_"reject"$ + Problemspezifisch ], [ *Moderner Computer* + Zustände der CPU: Statusbits, Registerwerte + Virtueller Speicher: praktisch unbegrenzt + Adress-Register, Programm-Zähler + `exit(EXIT_SUCCESS)`, `exit(EXIT_FAILURE)` + Kann beliebige Programme ausführen ]) == Aufzähler #definition[Aufzähler][Ein Aufzähler ist eine TM, die alle akzeptierbaren Wörter mit einem Drucker ausdruckt.] #definition[Rekursiv aufzählbare Sprache][Eine Sprache $L$ heisst rekursiv aufzählbar, wenn es einen Aufzähler gibt, der sie aufzählt.] Aufzählbare Sprache #sym.arrow.l.r.double Turing-erkennbare Sprache. == Vergleich von Maschinen #definition[Eine TM $M_1$ ist "leistungsfähiger" als eine TM $M_2$, wenn $M_1$ die Maschine $M_2$ simulieren kann $ M_2 <=_S M_1 $ $M_2$ ist simulierbar auf $M_1$.] Beispiele: - $"TM" scripts(<=)_S "Minecraft"$ - $"8-Bit CPU" scripts(<=)_S "Minecraft" scripts(<=)_S "TM"$ == Unendlichkeit Die Mengen $NN$ und $RR$ sind nicht gleich mächtig, da es keine bijektive Abbildung $NN -> RR$ gibt. #definition[Mengen $A$ und $B$ heissen _gleich mächtig_, $A tilde.eq B$, wenn es eine Bijektion $A -> B$ gibt.] #definition[Eine Menge $A$ heisst _unendlich_, wenn sie gleich mächtig wie eine echte Teilmenge ist.] #definition[$A$ heisst _abzählbar unendlich_, wenn $A tilde.eq NN$, d.h. $A$ gleich mächtig wie $N$ ist.] #theorem[Die Potenzmenge $P(A)$ einer abzählbar unendlichen Menge $A$ ist immer _überabzählbar unendlich_.] #theorem[Die Vereinigung von endlich vielen abzählbaren Mengen ist abzählbar. Das kartesische Produkt $A times B$ zweier abzählbaren Mengen $A, B$ ist abzählbar.] *Anwendungen:* - Abzählbar unendlich: $Sigma^*$, Menge aller DEAs/NEAs/PDAs/CFGs - Überabzählbar unendlich: Menge aller Sprachen $P(Sigma^*)$ == Berechenbare Zahlen #definition[Berechenbare Zahl][Eine Zahl $w$ heisst berechenbar, wenn es eine Turingmaschine $M$ gibt, die auf leerem Band startet und auf dem Band nacheinander die Stellen der Zahl ausgibt. Eine Zahl $w$ ist somit berechenbar, wenn es eine Turing-Maschine gibt, die sie berechnet.] #example[ $pi, e, sqrt(2), gamma, phi = (sqrt(5) - 1)/2$ ] === Wieviele berechenbare Zahlen gibt es? _Sind alle reellen Zahlen berechenbar?_ + Es gibt höchstens so viele berechenbare Zahlen wie Turing-Maschinen + Die Menge der Turing-Maschinen ist abzählbar unendlich + Die Menge der reellen Zahlen $RR$ ist überabzählbar unendlich + $=>$ fast alle reelle Zahlen sind nicht berechenbar == Hilberts 10. Problem Gibt es ganzzahlige Lösungen für Polynomgleichungen? $ x^2 - y &= 0\ x^n + y^n &= z^n $ Eine TM, die verschiedene Möglichkeiten ausprobiert, ist hierfür nicht geeginet; falls es keine Lösung gibt, würde die TM nicht anhalten. $=>$ Es bräuchte einen Entscheider. Dieses Problem wurde jedoch 1970 von <NAME> als nicht entscheidbar bewiesen. == Sprachprobleme Ein normales Problem soll zunächst in eine Ja/Nein-Frage übersetzt werden. #example[ Problem: Finden sie eine Lösung der quadratischen Gleichung: $ x^2 - x - 1 = 0 $ Dies ist jedoch nicht wirklich als Sprache formuliert. Wir können folgende Formulierung postieren: Sei $L$ die Sprache bestehend aus Wörtern der Form $ w = upright(a)=a,upright(b)=b,upright(c)=c,upright(x)=x $ wobei $a,b,c,x$ Dezimaldarstellungen von Zahlen sind. Ein Wort gehört genau dann zur Sprache $w$, wenn $a x^2 + b x + c = 0$ gilt. Ist $upright(a)=1, upright(b)=-1, upright(c)=-1, upright(x)=3 in L$? ] #example[ Gegeben ist eine natürliche Zahl $n$, berechne die ersten 10 Stellen der Dezimaldarstellung von $sqrt(n)$. Dies ist wieder kein normales Sprachproblem $->$ Als Entscheidungsproblem mit Ja/Nein-Antwort formulieren: Sind die ersten 10 Stellen der Dezimaldarstellung von $sqrt(2) = 1.414213562$? *Als Sprache formuliert:* Sei $L$ die Sprache bestehend aus Zeichenketten der Form $n,x$ wobei n die Dezimaldarstellung einer natürlichen Zahl ist und $x$ die ersten 10 Stellen einer Dezimalzahl. Gilt $2, 1.414213562 in L$? ] === $epsilon$-Akzeptanzproblem für endliche Automaten *Problem:* Kan der endliche Automat $A$ das leere Wort akzeptieren? *Als Sprachproblem:* Ist die Sprache $L = {angle.l A angle.r | epsilon in L(A)}$ entscheidbar? *Entscheidungsalgorithmus:* + Wandle $A$ in einen DEA um + Ist der Startzustand ein Akzeptierzustand $q_0 in F$? === Gleichheitsproblem für DEAs *Problem:* Akzeptieren die endlichen Automaten $A_1$ und $A_2$ die gleiche Sprache, $L(A_1) = L(A_2)$? *Sprachproblem:* Ist die Sprache $L = {angle.l A_1, A_2 angle.r | L(A_1) = L(A_2)}$ entscheidbar? *Entscheidungsalgorithmus:* + Wandle $A_1$ in einen minimalen Automaten $A'_1$ um + Wandle $A_2$ in einen minimalen Automaten $A'_2$ um + Ist $A'_1 = A'_2$? === Akzeptanzproblem für DEAs *Problem:* Akzeptiert der endliche Automat $A$ das Wort $w$? *Spachproblem:* Ist die Sprache $L = {angle.l A, w angle.r | w in L(A)}$ entscheidbar? *Entscheidungsalgorithmus:* + Wandle A in einen DEA A' um + Simuliere A' mit Hilfe einer TM + Hält die Turing-Maschine im Zustand $q_"accept"$? === Akzeptanzproblem für CFGs *Problem:* Kann das Wort $w$ aus der Grammatik $G$ produziert werden? *Als Sprachproblem:* Ist die Sprache $L = {angle.l G, w angle.r | w in L(G)}$ entscheidbar? *Entscheidungsalgorithmus:* + Kontrollieren, dass $angle.l G angle.r$ wirklich eine Grammatik beschreibt + Grammatik in Chomsky-Normalform bringen + Mit dem CYK-Algorithmus prüfen, ob $w$ aus $G$ produziert werden kann == Nicht entscheidbare Probleme #theorem[Alan Turing][$A_"TM"$ ist nicht entscheidbar.] #proof[Konstruiere aus dem Entscheider $H$ für $A_"TM"$ eine Maschine $D$ mit Input $angle.l M angle.r$. + Lasse $H$ auf Input $angle.l M, angle.l M angle.r angle.r$ laufen + Falls $H$ akzeptiert: $q_"reject"$ + Falls $H$ verwirft: $q_"accept"$ Wende jetzt $D$ auf $angle.l D angle.r$ an:\ $D(angle.l D angle.r) "akzeptiert" <=> D "verwirft" angle.l D angle.r$ \ $D(angle.l D angle.r) "verwirft" <=> D "akzeptiert" angle.l D angle.r$ Widerspruch! ] == Reduktion Berechenbare Abbildung $f: Sigma^* -> Sigma^*$ so, dass $ w in A <=> f(w) in B $ Notation: $f: A <= B$, "$A$ leichter entscheidbar als $B$" Entscheidbarkeit: $B$ entscheidbar, $f : A <= B => A "entscheidbar"$ #proof[$H$ ein Entscheider für $B$, dann ist $H circle.small f$ ein Entscheider für $A$.] Folgerung: $A$ nicht entscheidbar, $A <= B => B$ nicht entscheidbar. === Reduktionsbeispiele In folgenden Beispielen ist $M$ eine Maschine, die ein Wort $w$ entweder akzeptiert oder verwirft. Wie wir bewiesen haben, ist es unmöglich, einen Entscheider für das Akzeptanzproblem $A_"TM"$ zu konstruieren. #example[Reduktion für das spezielle Halteproblem][ Programm $S$: + Führe $M$ auf $w$ aus + $M$ hält in $q_"accept"$: akzeptiere + $M$ hält in $q_"reject"$: Endlosschleife Wenn $H$ ein Entscheider für $italic("HALT")epsilon_"TM"$ wäre, könnte man daraus einen Entscheider für $A_"TM"$ konstruieren: + Konstruiere das Programm $S$ + Wende $H$ auf $angle.l S angle.r$ an ] #example[Reduktion für das Leerheitsproblem $A_"TM" <= E_"TM"$][ Ist die Sprache $L(M)$ leer? $-> overline(E)_"TM"$ ist $L(M) eq.not emptyset$ Programm $S$ mit Input $u$: + $M$ auf $w$ laufen lassen + $M$ akzeptiert $w$: $q_"accept"$ + Andernfalls: $q_"reject"$ $ M "akzeptiert" w <=> S "akzeptiert" L(S) = Sigma^* != emptyset $ Wenn $H$ ein Entscheider für $E_"TM"$ wäre, könnte man daraus einen Entscheider für $A_"TM"$ konstruieren: + Konstruiere das Programm $S$ + Wende $H$ auf $angle.l S angle.r$ an ] #example[Regularitätsproblem $A_"TM" <= italic("REGULAR")_"TM"$][ Ist die Sprache $L(M)$ regulär? Programm $S$ mit Input $u$: + $u in.not {0^n 1^n | n >= 0} -> q_"reject"$ + $M$ auf $w$ laufen lassen + $M$ akzeptiert $w$: $q_"accept"$ + $q_"reject"$ $ &M "akzeptiert" w &&<=> S "akzepiert" {0^n 1^n | n>= 0}, "nicht regulär" \ &M "akzeptiert" w "nicht" &&<=> S "akzeptiert" emptyset, "regulär" $ Wäre $H$ ein Entscheider für $italic("REGULAR"_"TM")$, könnte man daraus einen Entscheider für $A_"TM"$ konstruieren: + Konstruiere das Programm $S$ + Wende $H$ auf $angle.l S angle.r$ an ] === Folgerungen aus P = NP + Für jedes Problem in NP gibt es einen polynomiellen Algorithmus + Es gibt keine "schwierigen" Probleme + Mit Moore's Law lässt sich jedes Problem "lösen" + Es gibt keine sichere Kryptographie === Folgerungen aus P #sym.eq.not NP + NP-vollständige Probleme haben nicht skalierende Lösungen + Moore's Law hilft nicht in NP \\ P === NP-vollständig Eine entscheidbare Sprache B heisst NP-vollständig, wenn sich jede Sprache A in NP polynomiell auf B reduzieren lässt: $ A scripts(<=)_P B, forall A in "NP" $ Wenn ein Problem NP-vollständig ist: - Lösung braucht typischerweise exponentielle Zeit - Korrektheit der Lösung ist leicht (in polynomieller Zeit) zu prüfen - Andernfalls wären Tests schon exponentiell und somit in Software nicht sinnvoll Falls P #sym.eq.not NP, dann können NP-vollständige Probleme nicht in polynomieller Zeit gelöst werden.
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/035.typ
typst
#let date = datetime( year: 2022, month: 9, day: 6, ) #metadata(( title: "使用g++编译cpp20的module文件", subtitle: [c++20], author: "dashuai009", description: "本文简单给出了两个文件,使用了c++20 的module特性,并说明了如何使用g++进行编译。", pubDate: date.display(), ))<frontmatter> #import "../__template/style.typ": conf #show: conf == 简介 <简介> 简单记录一下初次尝试c++20中module特性的过程。包括一个main.cpp和子模块 test\_include.cxx。编译器为gnu的g++12.2。编译环境是wsl2-arch,glibc\>=2.36(g++12.2要求的)。 == demo结构 <demo结构> 两个文件,main.cpp 和 子模块 test\_include.cxx。直接上代码: #quote[ main.cpp ] ```cpp import TestInclude;//引入TestInclude模块 int main(){ TestInclude::push(1);// 这个TestInclude是命名空间的名字,不是模块名!!! TestInclude::push(3); TestInclude::push(2); TestInclude::print(); // std::cout << "error\n"; //美滋滋地把std::cout 隐藏起来, 如果用include这个cout会自动引入 return 0; } ``` #quote[ test\_include.cxx ] ```cpp //本模块定义一个私有的全局vector,对外导出两个接口,push和print module;//这一行不能少! #include<vector> #include<iostream> export module TestInclude; //声明一下模块名字 std::vector<int32_t> staticVec;// export namespace TestInclude{//导出接口外边套一层namespace void push(int32_t x){ staticVec.push_back(x); } void print(){ for (auto x:staticVec){ std::cout << x << ' '; } std::cout << '\n'; } } ``` == 编译运行 <编译运行> 编译命令 `g++ test_include.cxx main.cpp -o o -std=c++20 -fmodules-ts` 执行`./o` 可以如期输出`1 3 2` == 总结 <总结> - 编译命令需要添加`-std=c++20`和`-fmodules-rs`。现在g++编译错误提示还可以,#strike[`-fmodule-ts`我现在还不知道为什么] - main.cpp是找不到std::cout的,这种module的特性应该大有可为!!封装c库? - test\_include.cxx 中手动控制了#strong[模块名];和一个#strong[默认导出的命名空间];同为`TestInclude`,算是强行伪装了rust中文件名即模块名的特点。利用一个默认导出的命名空间可以规范模块导出的接口,这个意义更为重要,估计会出现在很多编码规范中!(或者限制在某一个命名空间中导出,效果类似,个人更倾向上边这种,export个数少) - g++还可以使用`g++ -c -xc++ test_include.cxx -fmodules-ts`单独编译某个模块。会生成`gcm.cache/TestInclude.gcm`和 `test_include.o`的缓存文件,据说可以加快编译速度。emmm期待编译工具链的支持。
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap5/8_simple_resistor_circuits.typ
typst
Other
#import "../../core/core.typ" === Building simple resistor circuits In the course of learning about electricity, you will want to construct your own circuits using resistors and batteries. Some options are available in this matter of circuit assembly, some easier than others. In this section, I will explore a couple of fabrication techniques that will not only help you build the circuits shown in this chapter, but also more advanced circuits. If all we wish to construct is a simple single-battery, single-resistor circuit, we may easily use #emph[alligator clip] jumper wires like this: #image("00444.png") Jumper wires with \"alligator\" style spring clips at each end provide a safe and convenient method of electrically joining components together. If we wanted to build a simple series circuit with one battery and three resistors, the same \"point-to-point\" construction technique using jumper wires could be applied: #image("00445.png") This technique, however, proves impractical for circuits much more complex than this, due to the awkwardness of the jumper wires and the physical fragility of their connections. A more common method of temporary construction for the hobbyist is the #emph[solderless breadboard], a device made of plastic with hundreds of spring-loaded connection sockets joining the inserted ends of components and/or 22-gauge solid wire pieces. A photograph of a real breadboard is shown here, followed by an illustration showing a simple series circuit constructed on one: #image("50042.jpg") #image("00446.png") Underneath each hole in the breadboard face is a metal spring clip, designed to grasp any inserted wire or component lead. These metal spring clips are joined underneath the breadboard face, making connections between inserted leads. The connection pattern joins every five holes along a vertical column (as shown with the long axis of the breadboard situated horizontally): #image("00447.png") Thus, when a wire or component lead is inserted into a hole on the breadboard, there are four more holes in that column providing potential connection points to other wires and/or component leads. The result is an extremely flexible platform for constructing temporary circuits. For example, the three-resistor circuit just shown could also be built on a breadboard like this: #image("00448.png") A parallel circuit is also easy to construct on a solderless breadboard: #image("00449.png") Breadboards have their limitations, though. First and foremost, they are intended for #emph[temporary] construction only. If you pick up a breadboard, turn it upside-down, and shake it, any components plugged into it are sure to loosen, and may fall out of their respective holes. Also, breadboards are limited to fairly low-current (less than 1 amp) circuits. Those spring clips have a small contact area, and thus cannot support high currents without excessive heating. For greater permanence, one might wish to choose soldering or wire-wrapping. These techniques involve fastening the components and wires to some structure providing a secure mechanical location (such as a phenolic or fiberglass board with holes drilled in it, much like a breadboard without the intrinsic spring-clip connections), and then attaching wires to the secured component leads. Soldering is a form of low-temperature welding, using a tin/lead or tin/silver alloy that melts to and electrically bonds copper objects. Wire ends soldered to component leads or to small, copper ring \"pads\" bonded on the surface of the circuit board serve to connect the components together. In wire wrapping, a small-gauge wire is tightly wrapped around component leads rather than soldered to leads or copper pads, the tension of the wrapped wire providing a sound mechanical and electrical junction to connect components together. An example of a #emph[printed circuit board], or #emph[PCB], intended for hobbyist use is shown in this photograph: #image("50039.jpg") This board appears copper-side-up: the side where all the soldering is done. Each hole is ringed with a small layer of copper metal for bonding to the solder. All holes are independent of each other on this particular board, unlike the holes on a solderless breadboard which are connected together in groups of five. Printed circuit boards with the same 5-hole connection pattern as breadboards can be purchased and used for hobby circuit construction, though. Production printed circuit boards have #emph[traces] of copper laid down on the phenolic or fiberglass substrate material to form pre-engineered connection pathways which function as wires in a circuit. An example of such a board is shown here, this unit actually a \"power supply\" circuit designed to take 120 volt alternating current (AC) power from a household wall socket and transform it into low-voltage direct current (DC). A resistor appears on this board, the fifth component counting up from the bottom, located in the middle-right area of the board. #image("50040.jpg") A view of this board\'s underside reveals the copper \"traces\" connecting components together, as well as the silver-colored deposits of solder bonding the component leads to those traces: #image("50041.jpg") A soldered or wire-wrapped circuit is considered permanent: that is, it is unlikely to fall apart accidently. However, these construction techniques are sometimes considered #emph[too] permanent. If anyone wishes to replace a component or change the circuit in any substantial way, they must invest a fair amount of time undoing the connections. Also, both soldering and wire-wrapping require specialized tools which may not be immediately available. An alternative construction technique used throughout the industrial world is that of the #emph[terminal strip]. Terminal strips, alternatively called #emph[barrier strips] or #emph[terminal blocks], are comprised of a length of nonconducting material with several small bars of metal embedded within. Each metal bar has at least one machine screw or other fastener under which a wire or component lead may be secured. Multiple wires fastened by one screw are made electrically common to each other, as are wires fastened to multiple screws on the same bar. The following photograph shows one style of terminal strip, with a few wires attached. #image("50033.jpg") Another, smaller terminal strip is shown in this next photograph. This type, sometimes referred to as a \"European\" style, has recessed screws to help prevent accidental shorting between terminals by a screwdriver or other metal object: #image("50034.jpg") In the following illustration, a single-battery, three-resistor circuit is shown constructed on a terminal strip: #image("00450.png") If the terminal strip uses machine screws to hold the component and wire ends, nothing but a screwdriver is needed to secure new connections or break old connections. Some terminal strips use spring-loaded clips -- similar to a breadboard\'s except for increased ruggedness -- engaged and disengaged using a screwdriver as a push tool (no twisting involved). The electrical connections established by a terminal strip are quite robust, and are considered suitable for both permanent and temporary construction. One of the essential skills for anyone interested in electricity and electronics is to be able to \"translate\" a schematic diagram to a real circuit layout where the components may not be oriented the same way. Schematic diagrams are usually drawn for maximum readability (excepting those few noteworthy examples sketched to create maximum confusion!), but practical circuit construction often demands a different component orientation. Building simple circuits on terminal strips is one way to develop the spatial-reasoning skill of \"stretching\" wires to make the same connection paths. Consider the case of a single-battery, three-resistor parallel circuit constructed on a terminal strip: #image("00451.png") Progressing from a nice, neat, schematic diagram to the real circuit -- especially when the resistors to be connected are physically arranged in a #emph[linear] fashion on the terminal strip -- is not obvious to many, so I\'ll outline the process step-by-step. First, start with the clean schematic diagram and all components secured to the terminal strip, with no connecting wires: #image("00452.png") Next, trace the wire connection from one side of the battery to the first component in the schematic, securing a connecting wire between the same two points on the real circuit. I find it helpful to over-draw the schematic\'s wire with another line to indicate what connections I\'ve made in real life: #image("00453.png") Continue this process, wire by wire, until all connections in the schematic diagram have been accounted for. It might be helpful to regard common wires in a SPICE-like fashion: make all connections to a common wire in the circuit as one step, making sure each and every component with a connection to that wire actually has a connection to that wire before proceeding to the next. For the next step, I\'ll show how the top sides of the remaining two resistors are connected together, being common with the wire secured in the previous step: #image("00454.png") With the top sides of all resistors (as shown in the schematic) connected together, and to the battery\'s positive (+) terminal, all we have to do now is connect the bottom sides together and to the other side of the battery: #image("00455.png") Typically in industry, all wires are labeled with number tags, and electrically common wires bear the same tag number, just as they do in a SPICE simulation. In this case, we could label the wires 1 and 2: #image("00456.png") Another industrial convention is to modify the schematic diagram slightly so as to indicate actual wire connection points on the terminal strip. This demands a labeling system for the strip itself: a \"TB\" number (terminal block number) for the strip, followed by another number representing each metal bar on the strip. #image("00457.png") This way, the schematic may be used as a \"map\" to locate points in a real circuit, regardless of how tangled and complex the connecting wiring may appear to the eyes. This may seem excessive for the simple, three-resistor circuit shown here, but such detail is absolutely necessary for construction and maintenance of large circuits, especially when those circuits may span a great physical distance, using more than one terminal strip located in more than one panel or box. #core.review[ - A #emph[solderless breadboard] is a device used to quickly assemble temporary circuits by plugging wires and components into electrically common spring-clips arranged underneath rows of holes in a plastic board. - #emph[Soldering] is a low-temperature welding process utilizing a lead/tin or tin/silver alloy to bond wires and component leads together, usually with the components secured to a fiberglass board. - #emph[Wire-wrapping] is an alternative to soldering, involving small-gauge wire tightly wrapped around component leads rather than a welded joint to connect components together. - A #emph[terminal strip], also known as a #emph[barrier strip] or #emph[terminal block] is another device used to mount components and wires to build circuits. Screw terminals or heavy spring clips attached to metal bars provide connection points for the wire ends and component leads, these metal bars mounted separately to a piece of nonconducting material such as plastic, bakelite, or ceramic. ]
https://github.com/i-am-wololo/cours
https://raw.githubusercontent.com/i-am-wololo/cours/master/main/cheatsheeti22.typ
typst
#import "./templates.typ": * #show: chshtemplate.with(matiere: "i22") = bases et codage == rappels #table(columns: (auto, auto, auto, auto), "decimale", "binaire", "octal", "hexa", "0", "0", "0", "0", "1", "1", "1", "1", "2", "10", "2", "2", "3", "11", "3", "3", "4", "100", "4", "4", "5", "101", "5", "5", "6", "110", "6", "6", "7", "111", "7", "7", "8", "1000", "10", "8", "9", "1001", "11", "9", "10", "1010", "12", "A", "11", "1011", "13", "B", "12", "1100", "14", "C", "13", "1101", "15", "D", "14", "1110", "16", "E", "15", "1111", "17", "F" ) == rappels logique #table( columns: (auto, auto, auto, auto, auto), $x$, $y$, $x+y$, $x y$, $tilde(x)$, $0$, $0$, $0$, $0$, $1$, $0$, $1$, $1$, $0$, $1$, $1$, $0$, $1$, $0$, $0$, $1$, $1$, $1$, $1$, $0$ ) == Arithmetique tronque a gauche: = logique combinatoire #definition(title:"tableau de Karnaugh")[ il sert a representer l'ensemble des arguments d'une fonction booleenne, a la meme facon qu'un tableau de valeur. cette forme est efficace pour trouver: - la FND d'une fonction - trouver l fonction booleenne ayant le moins de variable et d'operateurs possible: simplification des fonctions booleennes un tableau de karnaugh a pour argument n, qui signifie n nombre d'arguments d'une fonction booleenne ] exemple pour un tableau $n=3$: #table( columns:(auto, auto, auto, auto, auto), [ #align(right+top, "xy") #align(left+bottom, [z] ) ], "00", "01", "11", "10", "0", [$f(0,0,0)$], $f(0,1,0)$, $f(1,1,0)$, $f(1,0,0)$, $1$, $f(0,0,1)$, $f(0,1,1)$, $f(1,1,1)$, $f(1,0,1)$ ) #definition(title:"forme nominal disjonctive (FND)")[ let $n$ variabless, $x_1...x_n$, on appelle monome d'ordre n le produit $y_1,y_2...y_n$ avec $y_i = x_i$ ou $y_i = tilde(x_i)$ pour chaque $i in {1,...,n}$. une fonction est dite sous forme nominal disjonctive si la fonction est une somme de monomes d'ordre n. toute fonctions non nulle de $n$ variables peut s'ecrire de facon unique sous forme nominale disjonctive. ] exemple: soit une fonction $f$ boolenne de 2 arguments dont son tableau de karnaugh est #table( columns: (auto, auto, auto, auto, auto), [ #align(top+right, $x y$) #align(bottom+left, $z$) ], $00$, $01$, $11$, $10$, $0$, $1$, $0$, $1$, $1$, $1$, $0$, $1$, $0$, $0$, ) La FND de $f$ est $f(x,y,z) = tilde(x) tilde(y) tilde(z)+ x y tilde(z) + x tilde(y) tilde(z) + tilde(x)+ y z$ on peut donc simplifier la fonction a $ x y+x tilde(y) = x $ en effet $x y + x tilde(y) = x(y+tilde(y)) = x 1 = x$ = logique sequentielle
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/intake-rebuild/build.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #create-body-entry( title: "Build: Intake Rebuild", type: "build", date: datetime(year: 2024, month: 2, day: 17), author: "<NAME>", witness: "<NAME>", )[ #grid( columns: (1fr, 1fr), gutter: 20pt, [ With the CAD completed, we were able to start working on building the intake. #admonition( type: "note", )[ We didn't have the correct length c-channel until the last 30 minutes of the meeting. This meant we didn't get as much of the build done as we would have liked. ] We got to work on putting the correct spacing on the axle (see the drawing to the right). + We cut the high strength axle down to size + We slid the flex wheels and spacers onto the axle + While adding the flex wheels and spacers we also added in the shaft collar and the 6T sprocket. ], image("./axle.png", width: 80%), ) Once we got the c-channel we needed, we cut it down to size, drilled holes for the high strength axles, and screwed in bearings. See the diagram below for the correct placement. #image("./c-channel.png") During our next meeting we’ll need to drill holes into a high strength axle at the correct places in order to brace the intake correctly, finish the standoff bracing behind the spinning axle, and then mount the intake to the robot. #figure(caption: [Completed axle], image("./top-axle.jpg", width: 90%)) ] #create-body-entry( title: "Build: Intake Rebuild", type: "build", date: datetime(year: 2024, month: 2, day: 23), author: "<NAME>", witness: "Violet Ridge", )[ #grid( columns: (2fr, 3fr), gutter: 20pt, [ The first thing we did this meeting was build the gearbox that the motor attaches to. This gearbox is pretty simple, it just connects the motor to the intake axle with a chain. We mostly finished the intake, but we couldn’t correctly drill the holes in the high strength axle. We decided to mount the intake to the robot regardless, to verify whether our overall design would work or not. ], // placerholder figure(image("./gearbox.png"), caption: [The gearbox for the motor]), ) Right away, we discovered a few problems. The intake wasn't mounted far out enough, and the flex wheels weren't up high enough to bring the flex wheels above the triballs. To solve these problems we decided to mount the intake farther out. This meant we could get the extra reach we needed without changing the original design. We also had to add stops to the bottom of the intake to get it to sit higher. #grid( columns: (1fr, 1fr), gutter: 20pt, // figure( image("./top-partially-assembled.jpg"), caption: [Intake without any bracing], ), figure( image("./top-mounted-partially-assembled.jpg"), caption: [Partially assembled intake mounted to the robot], ), ) Next meeting we'll have to drill high strength axle and complete the bracing on the intake. ] #create-body-entry( title: "Build: Intake Rebuild", type: "build", date: datetime(year: 2024, month: 2, day: 24), author: "<NAME>", witness: "Violet Ridge", )[ #grid( columns: (1fr, 1fr), gutter: 20pt, [ Today we finished the intake. + We got the last part we needed, the high strength axle, and drilled holes in it at the correct length + We "boxed" the c-channel by adding spacers on the inside of it to make it more rigid (see the diagram to the right) + We screwed the axle into the intake #admonition( type: "note", )[ Upon trying out the intake we noticed that the standoff we were using as bracing stopped the triballs from entering the intake, so we had to remove it. ] ], image("./bracing.png", width: 75%), ) Due to the reduced structure integrity caused by removing the standoffs. We decided to add it back in at the mount point of the intake to make it square again. We ran the standoff through high strength pillow bearings, which made the mount functionally the same, just with added structural integrity. #grid( columns: (1fr, 1fr), gutter: 20pt, // figure( caption: [Standoff bracing running through the mount points], image("./mounting.jpg", width: 90%), ), figure( // caption: [Completed intake with triball], image("./top-assembled.jpg", width: 90%), ), ) #admonition(type: "build")[ The intake is complete! We can now move on to testing. ] ]
https://github.com/exAClior/simpl-event-poster
https://raw.githubusercontent.com/exAClior/simpl-event-poster/master/main.typ
typst
#let poster( year: "", website: "", title: "", subtitle: "", date: "", logo: none, locations: none, sponsors: none, page_width: 12in, page_height: 36in, body ) = { // Define color theme let backgroundColor = rgb("#FFFFFF") // White background let primaryColor = rgb("#2C3E50") // Dark Blue for headers and accents let secondaryColor = rgb("#95A5A6") // Light Gray for secondary text let accentColor = rgb("#E74C3C") // Red for highlights // Set the page size and background color set page(width: page_width, height: page_height, margin: 0in, fill: backgroundColor) // Set up basic text styles set text(font: "Arial", size: 24pt, fill: primaryColor) // Header // Header with two-column layout place(top, dx:20pt, dy:30pt)[ #grid(columns:(60%, 25%), rows:(150pt, 150pt), row-gutter: 20pt,column-gutter: 20pt, // fill: accentColor, grid.cell(rowspan:2,colspan:1,image("logo.png", width: 6in)), // need to make this rounder and of different propotion grid.cell(fill:accentColor, text(website, size:30pt)), grid.cell(text(year, size:100pt)), ) ] // event general information: date, location, speakers etc place(center + horizon)[ #box(fill: accentColor,width: 100%, height: 70%, body ) ] // general topics place(center + horizon, dy: 950pt)[ #box(fill: secondaryColor,width: 100%, height: 10%, body ) ] // Sponsor's logos // need to input this manually https://forum.typst.app/t/is-there-a-way-to-retrieve-the-current-file-name-list-files-etc-within-typst/155 let sponsor_logos = () for sponsor_logo in sponsors { // how to use map here? sponsor_logos.push(image("sponsors/" + sponsor_logo, width: 3in)) } place(bottom+center)[ // List sponsor logos #grid( columns: sponsor_logos.len(), align: center + horizon, gutter: 3pt, ..sponsor_logos, ) ] } // Usage example with updated color theme and sponsors #show: poster.with( year: "2024", title: "Your Conference 2023", subtitle: "Exploring New Horizons", date: "July 15-17, 2023", locations: ["Tech City Convention Center"], logo: "logo.png", sponsors: ("sponsor1.svg", "sponsor2.svg", "sponsor3.svg"), website: "https://cn.julialang.org/meetup-website/2024" ) = Event Information I should include event location and time here = Speakers I should include speaker list here = Topics How can I put this in the second section?
https://github.com/codez-py/icd-9
https://raw.githubusercontent.com/codez-py/icd-9/main/report/report.typ
typst
#set page(numbering: "1") #set par(justify: true) #set text(size: 12pt) #set figure(placement: auto) #set table(fill: (rgb("EAF2F5"), none), stroke: rgb("21222C")) #show table.cell.where(y: 0): set text(weight: "bold") #align(center, text(17pt)[ *Indian Dance Forms Classification* ]) #let class_labels = ( "bharatanatyam", "kathak", "kathakali", "kuchipudi", "manipuri", "mohiniyattam", "odissi", "sattriya", "purulia chhau", ) = Introduction Indian classical dance, or ICD, is a reflection of the country's rich cultural legacy. Each dance originates from a distinct state within the nation. Nine distinct dance forms are recognized by #link("https://www.indiaculture.gov.in/dance") [Ministry of Culture, Government of India]. These dance forms include Bharatanatyam, Kathak, Kathhakali, Kuchipudi, Manipuri, Odissi, Sattriya and Chhau. Previous work in the paper “Classification of Indian Dance Forms using Pre-Trained Model-VGG” @biswas2021 was done for the eight dance forms excluding Chhau and employed transfer learning to address this multiclass classification in this project. Images of these eight dance forms that are known in India were classified using pre-trained models like VGG16 and VGG19. The ICD dataset from Kaggle, which included several photos in each of the eight classes was used. = Literature Survey In @samanta2012 the authors used a Computer Vision techniques and SVM to classifiy Indian Classical Dance (ICD). They used a sparse representation based dictionary learning technique. First, represent each frame of a dance video by a pose descriptor based on histogram of oriented optical flow (HOOF), in a hierarchical manner. The pose basis is learned using an on-line dictionary learning technique. Finally each video is represented sparsely as a dance descriptor by pooling pose descriptor of all the frames. In their work, dance videos are classified using support vector machine (SVM) with intersection kernel. An accuracy of 86.67% was achieved while tested their algorithm on their own ICD dataset created from the videos collected from YouTube. In @naik2020 the authors used Deep Learning Convolution Neural Network (CNN) to classify five dance classes namely Bharatanatyam, Odissi, Kathak, Kathakali, Yakshagana, the images of which are collected from the internet using Google Crawler. = Transfer Learning Transfer learning is a machine learning technique where knowledge learned from a task is re-used to boost performance on a related task. It is a popular approach in deep learning as it enables the training of deep neural networks with less data compared to having to create a model from scratch. The process involves unfreezing some layers of the model and then retraining it at a low-learning rate to handle a new dataset. Transfer learning is not a distinct type of machine learning algorithm, but rather a technique or method used whilst training models. By harnessing the ability to reuse existing models and their knowledge of new problems, transfer learning has opened doors to training deep neural networks even with limited data. = VGG 16 VGG-16, or the Visual Geometry Group 16-layer model, is a deep convolutional neural network architecture that was proposed by the Visual Geometry Group at the University of Oxford. It was introduced in the paper titled "Very Deep Convolutional Networks for Large-Scale Image Recognition" by <NAME> and A. Zisserman in 2014 @simonyan2015deep. VGG-16 is a part of the VGG family of models, which also includes VGG-19, VGG-M, and others. == Architecture #figure(image("screenshots/vgg16.png"), caption: "VGG-16 architecture Map") The VGG-16 architecture is characterized by its simplicity and uniformity. It consists of 16 weight layers, including 13 convolutional layers and 3 fully connected layers. The convolutional layers are followed by max-pooling layers, and the fully connected layers are followed by a softmax activation function for classification. The general architecture is as follows: - *Input Layer* (224x224x3): Accepts an RGB image with a resolution of 224x224 pixels. - *Convolutional Layers* (Conv): - The first two layers have 64 filters with a 3x3 kernel and a stride of 1. - The next two layers have 128 filters with a 3x3 kernel and a stride of 1. - The next three layers have 256 filters with a 3x3 kernel and a stride of 1. - The final three layers have 512 filters with a 3x3 kernel and a stride of 1. - *Max-Pooling Layers* (MaxPool): - After every two convolutional layers, max-pooling with a 2x2 window and a stride of 2 is applied. - The goal of the layer of pooling is to sample based on the input dimension. This decreases by this activation the number of parameters. - *Fully Connected Layers* (FC): - There are three fully connected layers, each with 4096 neurons. - The last layer has 1000 neurons, corresponding to the 1000 ImageNet classes. - *Softmax Layer* - The final layer uses the softmax activation function for classification. @vgg16_summary_table shows the output shape and number of parameters for each layer used in VGG16 model. == Key Features: - *Uniform Filter Size* VGG-16 uses a small 3x3 filter size throughout the convolutional layers, providing a uniform receptive field. - *Deep Network* With 16 layers, VGG-16 is considered a deep neural network. The depth contributes to the model's ability to learn hierarchical features. - *Ease of Interpretability* The uniform structure and simplicity of VGG-16 make it easy to interpret and understand compared to more complex architectures. #let vgg16_summary = csv("screenshots/vgg16_layers.csv", delimiter: "|") #figure( caption: "Summary of VGG-16.", table(columns: 3, inset: 7pt, align: horizon, ..vgg16_summary.flatten()), ) <vgg16_summary_table> = Dataset We obtained from Kaggle the ICD dataset @icd_dataset, which included 599 images from 8 distinct classes: Manipuri, Bharatanatyam, Odissi, Kathakali, Kathak, Sattriya, Kuchipudi, and Mohiniyattam. Purulia Chhau, the ninth class of dance, has also been added. Since the majority of the pictures of chhau that are available online are of the purulia form, we only added this subdance form. With the addition of Purulia Chhau a total of 653 images are present in the dataset. #figure( image("screenshots/sample_images.png"), caption: "Dance forms images from the datasets.", ) #figure( table( columns: (auto, auto, auto), inset: 10pt, align: horizon, [], [*Class*], [*Images*], "0", "bharatanatyam", "73", "1", "kathak", "76", "2", "kathakali", "74", "3", "kuchipudi", "76", "4", "manipuri", "84", "5", "mohiniyattam", "70", "6", "odissi", "71", "7", "sattriya", "75", "8", "purulia chhau", "53", ), caption: "Number of images in each class", ) #figure( image("screenshots/bar_classes.png"), caption: "Number of images in each class", ) = Training VGG-16 was pretrained on the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) dataset, a large dataset containing millions of labeled images across thousands of classes. First, the data will be divided into training, testing, and validation samples. The VGG16 model will then be trained using our training set of data. A portion of it will be utilized at the validation stage. Next, using testing samples, we will test the model. #let training_csv = csv("screenshots/training.csv") #figure( caption: "Training VGG16 model.", table(columns: 5, ..training_csv.flatten()), ) = Performance Measurements We further measured the performance of our model using a confusion matrix. The main idea behind this tabular performance measurement is to understand how good our model is when dealing with false-positives and false-negatives. Comparison between the actual and predicted classes helped us to visualize the accuracy of our model. In a confusion matrix, the true positive indicates the values which are predicted correctly predicted as positive whereas the false positive refers to the negative values which are incorrectly predicted as positive values. Similarly, false negative tells us the number of positive values which are predicted as negative by our model and lastly, the true negative refers to the negative values which are correctly predicted as negative. #figure( caption: "Confusion Matrix", table( columns: (auto, auto), inset: 10pt, align: horizon, [*True Positives (TP)*], [*False Negatives (FN)*], [*False Positives (FP)*], [*True Negatives (TN)*], ), ) <sample_confusion_matrix> Accuracy is considered as one of the most important factors to measure the performance. It is the ratio of correctly predicted observation to the total number of observations. Mathematically, $ "Accuracy" = ("TP" + "TN" ) / ("TP" + "FP" + "FN" + "TN" ) $ Next factor is precision. It refers to the ratio of correctly predicted positive values to the total predicted positive values. Mathematically, $ "Precision" = "TP" / ("TP" + "FP") $ Recall indicates to the ratio of correctly predicted positive observations to the all observations in actual class. Mathemat- ically, $ "Recall" = "TP" / ("TP" + "FN") $ Lastly, F1 Score is the weighted average of Precision and Recall. Mathematically, $ "F1 Score" = 2 * ("Recall" * "Precision") / ("Recall" + "Precision") $ @sample_confusion_matrix shows a sample confusion matrix for binary classification. @classification_report shows the parameters of evaluation and @confusion_matrix shows the confusion matrix for the VGG16 model trained and tested on our dataset. #{ let class_report = csv("screenshots/classification_report.csv") let confusion_matrix = csv("screenshots/confusion_matrix.csv") show table.cell.where(x: 0): set text(weight: "bold") let a = figure( caption: "Classification Report", table(columns: 5, inset: 10pt, align: horizon, ..class_report.flatten()), ) let b = figure( caption: "Confusion Matrix", table(columns: 10, inset: 10pt, align: horizon, ..confusion_matrix.flatten()), ) [ #a <classification_report> #b <confusion_matrix> ] } The number of epochs is a hyperparameter. We have implemented our models using 30 epochs for VGG16. The number of times the learning algorithm will work through the entire training data is referred as epoch. We have plotted the train_loss vs val_loss and train_acc vs val_acc for VGG 16 model. #figure( image("screenshots/train_acc.png", width: 80%), caption: [Training accuracy vs validation accuracy for VGG-16.], ) <train_acc_16> #figure( image("screenshots/train_loss.png", width: 80%), caption: [Training loss vs validation loss for VGG-16.], ) <train_loss_16> @train_acc_16 shows the training accuracy vs validation accuracy for different epochs. @train_loss_16 shows the training loss vs validation loss for different epochs. #pagebreak() #bibliography("references.bib", title: "References")
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/diagraph/0.1.2/lib.typ
typst
Apache License 2.0
#let plugin = plugin("diagraph.wasm") #let render(text, engine: "dot", width: auto, height: auto, fit: "contain", background: "transparent") = { let render = plugin.render( bytes(text), bytes(engine), bytes(background) ) if render.at(0) == 1 { return raw(str(render.slice(1))) } if render.at(0) != 0 { panic("First byte of render result must be 0 or 1") } let integer_size = render.at(1) if width != auto or height != auto { return image.decode( render.slice(2 + integer_size * 2), format: "svg", height: height, width: width, fit: fit, ) } /// Decodes a big-endian integer from the given bytes. let big-endian-decode(bytes) = { let result = 0 for byte in array(bytes) { result = result * 256 result = result + byte } return result } /// Returns a `(width, height)` pair corresponding to the dimensions of the SVG stored in the bytes. let get-svg-dimensions(svg) = { let point_width = big-endian-decode(render.slice(2, integer_size + 2)) * 1pt let point_height = big-endian-decode(render.slice(integer_size + 3, integer_size * 2 + 2)) * 1pt return (point_width, point_height) } let initial-dimensions = get-svg-dimensions(render) let svg-text-size = 14pt // Default font size in Graphviz style(styles => { let document-text-size = measure(line(length: 1em), styles).width let (auto-width, auto-height) = initial-dimensions.map(dimension => { dimension / svg-text-size * document-text-size }) let final-width = if width == auto { auto-width } else { width } let final-height = if height == auto { auto-height } else { height } return image.decode( render.slice(2 + integer_size * 2), format: "svg", width: final-width, height: final-height, fit: fit, ) }) } #let raw-render(engine: "dot", width: auto, height: auto, fit: "contain", background: "transparent", raw) = { if (not raw.has("text")) { panic("This function requires a `text` field") } let text = raw.text return render(text, engine: engine, width: width, height: height, fit: fit, background: background) }
https://github.com/EricWay1024/Homological-Algebra-Notes
https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/main.typ
typst
#import "libs/template.typ": * #import "@preview/ctheorems:1.1.2": * #show: thmrules #show: project.with( title: "Homological Algebra", authors: ( "Notes by <NAME>", "Lectures by <NAME>", "Partially Based on Previous Notes by <NAME>" ), // date: "October 24, 2023", date: datetime.today().display("[day padding:none] [month repr:long] [year]"), ) #outline(indent: true) #pagebreak() #heading(numbering: none)[Preface] These notes are mostly based on the University of Oxford course 'C2.2 Homological Algebra' lectured by Prof <NAME> during the 2023-24 Michaelmas term. Portions of the previous notes @notes are reused, along with relevant parts of @weibel, upon which the course is largely based. Another important reference is @rotman, which provides detailed and, at times, meticulous proofs. I have labelled the source of many proofs (whether they are similar or different to the ones presented) for the reader's reference. An overview of these notes follows. @module-recap states without proof some results from *module theory* which we will use later. @cat-theory is a crash course on *category theory*, based on which @ab-cat constructs *abelian categories* in a step-by-step manner. In general, abelian categories serve as the 'stage' for homological algebra, but as we will see, $RMod$, the category of $R$-modules, which is 'concrete' and thus easier to work with, is in fact a sufficient representative of abelian categories. Focusing on $RMod$, we then move on to establish the *module tensor product* (@tp-module), where the *tensor-hom adjunction* emerges as a significant result. We then prove that $RMod$ has *enough projectives and injectives* in @enough-proj-inj, a property crucial to constructing resolutions in $RMod$. @chain-complex then discusses *(co)chain complexes* and their *(co)homology*, which originally arise in algebraic topology but are viewed solely as algebraic entities here; they lead to the definition and several important properties of *resolutions*. With all the tools in hand, in @derived-functor we are able to define our main protagonist, *derived functors*, which are proven to be *homological $delta$-functors*, in some sense a generalisation of (co)homology functors. The two main *derived functors* we study are *$Ext$* and *$Tor$*, induced by $hom$ and tensor products respectively, as defined in @balancing-ext-tor. *$Ext$* and *$Tor$* possess a crucial property of being *balanced*, which requires the introduction of *mapping cones* and *double and total complexes* for proof. Further properties of *$Ext$*, including its *ring structure* and its connection with *module extensions*, are discussed in @ring-ext and @ext-extension, while further properties of *$Tor$*, demonstrated by *flat modules* and the *Universal Coefficient Theorem*, are the topic of @tor-flat. The machinery we build is also applied to construct *Koszul (co)homology* and *group (co)homology* in @koszul and @group-cohomology, respectively. For most of the proofs, I have tried to improve them by filling in more detailed steps by using available references and adding cross-references to previous results in the notes. Two large deviations from the lectures are @ab-cat and @tp-module. A lot more details are supplemented in both sections so as to make them as self-contained as possible. I have also chosen to introduce module tensor products based on @rotman, starting from the universal mapping problem of $R$-biadditive maps, whereas the lectures used the tensor product of vector spaces as an initial motivation. // A current drawback of these notes is the lack of computational examples in later sections, e.g., on *$Ext$* and *$Tor$*. The reader is directed to the aforementioned references for those. Also, I must clarify that I am uncertain about the examinable content while writing these notes. Homological Algebra is admittedly a challenging yet rewarding course. On a personal note, I chose to work on these notes to enhance my own learning. As a learner, I acknowledge that these notes must contain mistakes and improvable parts. Therefore, the reader is welcome to submit issues for any advice on GitHub (https://github.com/EricWay1024/Homological-Algebra-Notes), where these notes are open-sourced and updated#footnote[For anyone interested, I write these notes with Typst, a fairly new but much simpler alternative of LaTeX.]. One can also find a not-so-colourful version of these notes fit for printing by following that link. Finally, I would like to thank Prof <NAME> for delivering the lectures and <NAME> for creating the previous version of these notes. I would also like to thank my friends <NAME> for reading these notes and offering feedback and <NAME> for contributing to the GitHub workflows. #align(right)[ <NAME> ] #pagebreak() #include "ha/0-module.typ" #pagebreak() #include "ha/1-cat.typ" #pagebreak() #include "ha/2-ab.typ" #pagebreak() #include "ha/3-tp.typ" #pagebreak() #include "ha/4-enough.typ" #pagebreak() #include "ha/5-cc.typ" #pagebreak() #include "ha/6-df.typ" #pagebreak() #include "ha/7-balance.typ" #pagebreak() #include "ha/8-ext.typ" #pagebreak() #include "ha/9-tor.typ" #pagebreak() #include "ha/a-kc.typ" #pagebreak() #include "ha/b-ext1.typ" #pagebreak() #include "ha/c-gc.typ" #pagebreak() #include "ha/d-app.typ" #pagebreak() #bibliography("bib.yml", style: "chicago-author-date")
https://github.com/max-niederman/MATH51
https://raw.githubusercontent.com/max-niederman/MATH51/main/lib.typ
typst
#let vname = math.bold #let Proj = math.bold(math.op("Proj")) #let span = math.op("span") #let implies = sym.arrow.r.double #let iff = sym.arrow.r.l.double #let transposeArray = arr => { range(arr.at(0).len()) .map(j => range(arr.len()) .map(i => arr.at(i).at(j))) } #let common(title: "", body) = { set document( author: "<NAME>", title: title, ) set page( numbering: (..nums) => "Niederman " + numbering("1/1", ..nums), number-align: center ) set math.vec(delim: "[") set math.mat(delim: "[") // title block(text(weight: 700, 1.75em, title)) // author block(strong("<NAME>"), below: 2em) body } #let homework(title: "", body) = { show heading: set block(below: 1em) show heading.where(level: 1): it => { pagebreak() it } common(title: title, body) } #let lecture-notes(date: "", body) = { show heading: set block(below: 1em) show heading: set text(size: 0.85em) common( title: "Math 51 Lecture Notes: " + date, body ) }
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/13-harfbuzz/harfbuzz.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/heading.typ": chapter #import "/lib/glossary.typ": tr #show: web-page-template #chapter[ // Text Layout for Programmers: Harfbuzz 文本#tr[layout]编程利器:HarfBuzz ]
https://github.com/ymgyt/techbook
https://raw.githubusercontent.com/ymgyt/techbook/master/programmings/typst/math.md
markdown
# Math ## Usage ``` # ベクトル vec(x,y) # 行列 mat(a,b; c,d) # sin,cos sin (alpha + beta) cos (theta) # 絶対値 abs(a) # 分数 frac(a,b) # 数式にcomment a + b "(コメント)" # 空白をいれる wide ``` ## Symbol * `brace.{l,r}`: 波括弧 * `theta` * `<=>`: 合同 * `plus.minus`: プラスマイナス ## Alignment * `&`をつけるとそこがalignment pointになる * `&&` のように複数もできるっぽい? ```typst $ abs(a) &= n \ abs(a) &< n \ abs(a) &> n $ ```
https://github.com/WannesMalfait/vub-huisstijl-typst
https://raw.githubusercontent.com/WannesMalfait/vub-huisstijl-typst/main/src/lib.typ
typst
MIT License
#import "@preview/cetz:0.3.0" #let vub-orange = cmyk( 0%, 78%, 100%, 0%, ) #let vub-blue = cmyk( 100%, 80%, 16%, 3%, ) #let triangle-height = 27.7mm #let vub-triangle = cetz.canvas({ import cetz.draw: * line( ( 0, 0, ), ( 0, triangle-height, ), ( -10mm, triangle-height, ), close: true, fill: vub-orange, stroke: none, ) }) #let vub-titlepage( title: "Title of the thesis", subtitle: "An optional subtitle", pretitle: "Graduation thesis submitted in partial fulfillment of the requirements for the degree of Master of Science in Mathematics", authors: ("<NAME>",), promotors: ("<NAME>",), faculty: "Sciences and Bio-Engineering Sciences", date: datetime.today().display("[month repr:long] [day], [year]"), ) = { set document( author: authors, title: title, ) set page(margin: ( left: 18mm, top: 20mm, right: 10mm, )) set text(font: ( "TeX Gyre Adventor", "Roboto", )) set par( linebreaks: "optimized", // We adjust it manually spacing: 0pt, ) // First the top part with the vub logo and triangle place( top + left, image( "/assets/vub_logo_cmyk.svg", width: 5.66cm, ), ) place( top + right, vub-triangle, ) // Account for space of triangle v(triangle-height) v(1fr) // Title + author + date h(25mm) pad(x: 29mm)[ #par(leading: 0.3em // Make it a bit more tight )[ #text( size: 9pt, fill: vub-orange, pretitle, ) #v(5mm) #text( size: 24.88pt, fill: vub-blue, strong( upper(title), ), ) ] #v(5mm) #text( size: 17.28pt, fill: vub-blue, subtitle, ) #v(3cm) #text( size: 12pt, fill: vub-orange, authors.join(", "), ) #v(5mm) #text( size: 12pt, fill: vub-blue, date, ) ] v(1fr) // Promotors + faculty h(25mm) pad(x: 29mm)[ #text( size: 10pt, fill: vub-orange, promotors.join(", "), ) #v(5mm) #text( size: 10pt, fill: vub-blue, strong(faculty), ) ] pagebreak(weak: true) }
https://github.com/0xPARC/0xparc-intro-book
https://raw.githubusercontent.com/0xPARC/0xparc-intro-book/main/src/kzg.typ
typst
#import "preamble.typ":* = KZG commitments <kzg> The goal of a _polynomial commitment scheme_ is to have the following API: - Peggy has a secret polynomial $P(X) in FF_q [X]$. - Peggy sends a short "commitment" to the polynomial (like a hash). - This commitment should have the additional property that Peggy should be able to "open" the commitment at any $z in FF_q$. Specifically: - Victor has an input $z in FF_q$ and wants to know $P(z)$. - Peggy knows $P$ so she can compute $P(z)$; she sends the resulting number $y = P(z)$ to Victor. - Peggy can then send a short "proof" convincing Victor that $y$ is the correct value, without having to reveal $P$. The _Kate-Zaverucha-Goldberg (KZG)_ commitment scheme is amazingly efficient because both the commitment and proof lengths are a single point on $E$, encodable in 256 bits, no matter how many coefficients the polynomial has. == The setup Remember the notation $[n] := n dot g in E$ defined in @armor. To set up the KZG commitment scheme, a trusted party needs to pick a secret scalar $s in FF_q$ and publishes $ [s^0], [s^1], ..., [s^M] $ for some large $M$, the maximum degree of a polynomial the scheme needs to support. This means anyone can evaluate $[P(s)]$ for any given polynomial $P$ of degree up to $M$. For example, $ [s^2+8s+6] = [s^2] + 8[s] + 6[1]. $ Meanwhile, the secret scalar $s$ is never revealed to anyone. The setup only needs to be done by a trusted party once for the curve $E$. Then anyone in the world can use the resulting sequence for KZG commitments. #remark[ The trusted party has to delete $s$ after the calculation. If anybody knows the value of $s$, the protocol will be insecure. The trusted party will only publish $[s^0] = [1], [s^1], ..., [s^M]$. This is why we call them "trusted": the security of KZG depends on them not saving the value of $s$. Given the published values, it is (probably) extremely hard to recover $s$ -- this is a case of the discrete logarithm problem. You can make the protocol somewhat more secure by involving several different trusted parties. The first party chooses a random $s_1$, computes $[s_1^0], ..., [s_1^M]$, and then discards $s_1$. The second party chooses $s_2$ and computes $[(s_1 s_2)^0], ..., [(s_1 s_2)^M]$. And so forth. In the end, the value $s$ will be the product of the secrets $s_i$ chosen by the $i$ parties... so the only way they can break secrecy is if all the "trusted parties" collude. ] // #pagebreak() // TODO manual pagebreak for printed easy; stopgap hack == The KZG commitment scheme Peggy has a polynomial $P(X) in FF_p [X]$. To commit to it: #algorithm("Creating a KZG commitment")[ 1. Peggy computes and publishes $[P(s)]$. ] This computation is possible as $[s^i]$ are globally known. Now consider an input $z in FF_p$; Victor wants to know the value of $P(z)$. If Peggy wishes to convince Victor that $P(z) = y$, then: #algorithm("Opening a KZG commitment")[ 1. Peggy does polynomial division to compute $Q(X) in FF_q [X]$ such that $ P(X)-y = (X-z) Q(X). $ 2. Peggy computes and sends Victor $[Q(s)]$, which again she can compute from the globally known $[s^i]$. 3. Victor verifies by checking #eqn[ $ pair([Q(s)], [s]-[z]) = pair([P(s)]-[y], [1]) $ <kzg-verify> ] and accepts if and only if @kzg-verify is true. ] If Peggy is truthful, then @kzg-verify will certainly check out. If $y != P(z)$, then Peggy can't do the polynomial long division described above. So to cheat Victor, she needs to otherwise find an element $ 1/(s-x) ([P(s)]-[y]) in E. $ Since $s$ is a secret nobody knows, there isn't any known way to do this. == Multi-openings <multi-openings> To reveal $P$ at a single value $z$, we did polynomial division to divide $P(X)$ by $X-z$. But there's no reason we have to restrict ourselves to linear polynomials; this would work equally well with higher-degree polynomials, while still using only a single 256-bit curve point for the proof. For example, suppose Peggy wanted to prove that $P(1) = 100$, $P(2) = 400$, ..., $P(9) = 8100$. (We chose these numbers so that $P(X) = 100 X^2$ for $X = 1, dots, 9$.) Evaluating a polynomial at $1, 2, dots, 9$ is essentially the same as dividing by $(X-1)(X-2) dots (X-9)$ and taking the remainder. In other words, if Peggy does a polynomial long division, she will find that $ P(X) = Q(X) ( (X-1)(X-2) dots (X-9) ) + 100 X^2. $ Then Peggy sends $[Q(s)]$ as her proof, and the verification equation is that $ & pair([Q(s)], [(s-1)(s-2) ... (s-9)]) \ & = pair([P(s)] - 100[s^2], [1]). $ The full generality just replaces the $100X^2$ with the polynomial obtained from #cite("https://en.wikipedia.org/wiki/Lagrange_polynomial", "Lagrange interpolation") (there is a unique such polynomial $f$ of degree $n-1$). To spell this out, suppose Peggy wishes to prove to Victor that $P(z_i) = y_i$ for $1 <= i <= n$. #algorithm[Opening a KZG commitment at $n$ values][ 1. By Lagrange interpolation, both parties agree on a polynomial $f(X)$ such that $f(z_i) = y_i$. 2. Peggy does polynomial long division to get $Q(X)$ such that $ P(X) - f(X) = (X-z_1)(X-z_2) ... (X-z_n) dot Q(X). $ 3. Peggy sends the single element $[Q(s)]$ as her proof. 4. Victor verifies $ & pair([Q(s)], [(s-z_1)(s-z_2) ... (s-z_n)]) \ & = pair([P(s)] - [f(s)], [1]). $ ] So one can even open the polynomial $P$ at $1000$ points with a single 256-bit proof. The verification runtime is a single pairing plus however long it takes to compute the Lagrange interpolation $f$. == Root check To make PLONK work, we're going to need a small variant of the multi-opening protocol for KZG commitments (@multi-openings), which we call _root-check_ (not a standard name). Here's the problem statement: #problem[ Suppose one had two polynomials $P_1$ and $P_2$, and Peggy has given commitments $Com(P_1)$ and $Com(P_2)$. Peggy would like to prove to Victor that, say, the equation $P_1(z) = P_2(z)$ for all $z$ in some large finite set $S$. ] Peggy just needs to show is that $P_1-P_2$ is divisible by $Z(X) := product_(z in S) (X-z)$. This can be done by committing the quotient $ H(X) := (P_1(X) - P_2(X)) / Z(X). $ Victor then gives a random challenge $lambda in FF_q$, and then Peggy opens $Com(P_1)$, $Com(P_2)$, and $Com(H)$ at $lambda$. But we can actually do this more generally with _any_ polynomial expression $F$ in place of $P_1 - P_2$, as long as Peggy has a way to prove the values of $F$ are correct. As an artificial example, if Peggy has sent Victor $Com(P_1)$ through $Com(P_6)$, and wants to show that $ P_1(42) + P_2(42) P_3(42)^4 + P_4(42) P_5(42) P_6(42) = 1337, $ she could define $ F(X) := P_1(X) + P_2(X) P_3(X)^4 + P_4(X) P_5(X) P_6(X) - 1337 $ and run the same protocol with this $F$. This means she doesn't have to reveal any $P_i (42)$, which is great! To be fully explicit, here is the algorithm: #algorithm[Root-check][ Assume that $F$ is a polynomial for which Peggy can establish the value of $F$ at any point in $FF_q$. Peggy wants to convince Victor that $F$ vanishes on a given finite set $S subset.eq FF_q$. 1. If she has not already done so, Peggy sends to Victor a commitment $Com(F)$ to $F$.#footnote[ In fact, it is enough for Peggy to have some way to prove to Victor the values of $F$. So for example, if $F$ is a product of two polynomials $F = F_1 F_2$, and Peggy has already sent commitments to $F_1$ and $F_2$, then there is no need for Peggy to commit to $F$. Instead, in Step 5 below, Peggy opens $Com(F_1)$ and $Com(F_2)$ at $lambda$, and that proves to Victor the value of $F(lambda) = F_1 (lambda) F_2 (lambda)$. ] 2. Both parties compute the polynomial $ Z(X) := product_(z in S) (X-z) in FF_q [X]. $ 3. Peggy does polynomial long division to compute $H(X) = F(X) / Z(X)$. 4. Peggy sends $Com(H)$. 5. Victor picks a random challenge $lambda in FF_q$ and asks Peggy to open $Com(H)$ at $lambda$, as well as the value of $F$ at $lambda$. 6. Victor verifies $F(lambda) = Z(lambda) H(lambda)$. ] <root-check>
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_905%20-%20Algebraic%20Topology%201/Assignments/Assignment%202.typ
typst
#import "@preview/commute:0.2.0": node, arr, commutative-diagram #import "@preview/cetz:0.2.2" #import "/Templates/generic.typ": latex, header #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #import "/Templates/assignment.typ": * #show: doc => header(title: "Assignment 2", name: "<NAME>", doc) #show: latex #show: NumberingAfter #show: thmrules #let col(x, clr) = text(fill: clr)[$#x$] #let pb() = { pagebreak(weak: true) } #let bar(el) = $overline(#el)$ #set enum(numbering: "(a)") *Sources consulted* \ Students: <NAME>, Zack \ Texts: Class Notes. = Question == Statement + Suppose $0 -> ZZ -> A -> ZZ -> 0$ is a short exact sequence (of abelian groups). Prove that $A$ is isomorphic to $ZZ plus.circle ZZ$. + We use $ZZ quo 2 ZZ$ to denote the group with two elements. Write down two short exact sequences $ 0 -> ZZ quo 2 ZZ -> A -> ZZ quo 2 ZZ -> 0 \ 0 -> ZZ quo 2 ZZ -> B -> ZZ quo 2 ZZ -> 0 $ such that $A$ is not isomorphic to $B$. == Solution + #v(-3pt) Let us name the morphisms $ZZ ->^f A ->^g ZZ$, then let $x$ be any element of $A$ which maps to $1$ under $g$. We have that $x$ must generate an infinite order subgroup of $A$, as otherwise it would contradict the existence of $g$ since we would have $g(0) = g(n x) = n$. Now we consider the map $ZZ plus.circle ZZ -> A$ given by $h : (a,b) |-> f(a) + b x$. This is clearly a homomorphism, it is injective because $gen(x)$ and $im f$ have zero intersection by construction. To see it is surjective, fix $y in A$, set $m = g(y)$ and consider the element $m x$. We have $g(y - m x) = g(y) - g(m x) = m - m = 0$ so by exactness $y - m x in im f$. Then we for some $a in ZZ$, $y = m x + f(a)$ so $y$ is in the image of $h$. + Consider $A = (ZZ quo 2 ZZ)^2$ and $B = ZZ quo 4 ZZ$. We clearly have these as short exact sequences since the maps $f_1 (x) = (x,0), g_1 (x,y) = y$ and the maps $f_2 (x) = 2 x, g_2 (x) = x mod 2$ make them short exact sequences. It is also clear that $(ZZ quo 2 ZZ)^2 iso.not ZZ quo 4 ZZ$, since $ZZ quo 4 ZZ$ contains an element of order $4$ and $(ZZ quo 2 ZZ)^2$ does not. = Question == Statement + Consider the first $6$ letters in standard LaTeX font: A, B, C, D, E, and F. Viewed as subsets of $RR^2$, which of these letters are homotopy equivalent? No proofs are required. + Prove that if a space $A$ is homotopy equivalent to another space $B$, and $C$ is homotopy equivalent to $D$, then the product spaces $A times C$ and $B times D$ are homotopy equivalent. == Solution + The three homotopy equivalence classes are ${A,D}$, ${C,E,F}$ and ${B}$. + Let $f_1,g_1$ be a homotopy equivalence of $A$ and $B$, in the sense that $f_1 compose g_1 tilde.eq id_B$ and $g_1 compose f_1 tilde.eq id_A$. Similarly let $f_2,g_2$ are a homotopy equivalence of $C$ and $D$. We then have a map $h : A times [0,1] -> A$ with $h(x,0) = g_1 compose f_1$ and $h(x,1) = id_A$, and similarly $p(x,0) = g_2 compose f_2$, $p(x,0) = id_C$. We now define the homotopy $rho : A times C times [0,1] -> A times C$ given by $ rho(x,y,t) = (h(x,t), p(y,t)), $ we have that $ rho(x,y,0) = (h(x,0), p(y,0)) = (g_1 compose f_1 (x), g_2 compose f_2 (y)) = (g_1 times g_2) compose (f_1 times f_2) (x,y) $ as well as $ rho(x,y,1) = (h(x,1), p(y,1)) = (id_A (x), id_C (y)) = id_(A times C) (x,y) $ so $rho$ is a homotopy from $g_1 times g_2 compose f_1 times f_2$ to $id_(A times C)$. We can similarly get a homotopy from $f_1 times f_2 compose g_1 times g_2$ to $id_(B times D)$ and so $A times C$ and $B times D$ are homotopy equivalent. = Question == Statement Prove the second half of Proposition 9.5 in Haynes Miller's notes. Specifically, consider the following commutative diagram of abelian groups in which both rows are exact: #align(center)[#commutative-diagram( node((0, 0), $A_4$), node((0, 1), $A_3$), node((0, 2), $A_2$), node((0, 3), $A_1$), node((0, 4), $A_0$), node((1, 0), $B_4$), node((1, 1), $B_3$), node((1, 2), $B_2$), node((1, 3), $B_1$), node((1, 4), $B_0$), arr($A_4$, $A_3$, $d$), arr($A_3$, $A_2$, $d$), arr($A_2$, $A_1$, $d$), arr($A_1$, $A_0$, $d$), arr($B_4$, $B_3$, $d$), arr($B_3$, $B_2$, $d$), arr($B_2$, $B_1$, $d$), arr($B_1$, $B_0$, $d$), arr($A_4$, $B_4$, $f_4$), arr($A_3$, $B_3$, $f_3$), arr($A_2$, $B_2$, $f_2$), arr($A_1$, $B_1$, $f_1$), arr($A_0$, $B_0$, $f_0$), node-padding: (50pt, 50pt), )] Prove that if $f_4$ is surjective and $f_3$ and $f_1$ are injective, then $f_2$ is injective. == Solution Let $a in A_2$ be such that $f_2 (a) = 0$, then we have by commutativity $(f_1 compose d) (a) = 0$ and so since $f_1$ is injective then $d a = 0$. Thus by exactness we have that $a$ is in the image of $d$ so there is some $b in A_3$ such that $d b = a$. Then we have by commutativity $(d compose f_3) b = 0$. Now we have that $f_3 (b)$ is in the kernel of $d$ so it is also in the image of $d$ so there is some $c in B_4$ such that $d c = f_3 (b)$. Then by surjectivity there is some $x$ such that $f_4 (x) = c$, but since $ f_3 (d x - b) = f_3 (b) - f_3 (b) = 0 $ and so injectivity of $f_3$ gives us that $b = d x$. Finally since $b = d x$ and $a = d b$, so $a = d d x = 0$. = Question == Statement Suppose $X$ is a topological space. + Using problem $2(b)$, explain why $H_m (X times [0,1]) iso H_m (X)$ for all $m in ZZ$. + The cone on $X$, sometimes denoted $C X$, is the quotient of the space $X times [0,1]$ by the subspace $X times {0}$. Prove that $C X$ is homotopy equivalent to a point. + The suspension of $X$, sometimes denoted $S X$, is the quotient of $C X$ by the subspace $X times {1}$. Using the long exact sequence of the pair $(C X, X times {1})$, compute the homology groups of $S X$ in terms of the homology groups of $X$. + Prove, for each $q >= 0$, that the suspension of the $q$-dimensional sphere $S^q$ is homeomorphic to the $(q + 1)$-dimensional sphere $S^(q + 1)$. Here, $S^q$ is the subspace of points in $RR^(q+1)$ that are distance $1$ from the origin, so for example $S^0$ is the disjoint union of two points. == Solution + First note that $[0,1]$ is clearly contractible because its star-shaped. So we have that $[0,1]$ is homotopy equivalent to ${0}$. But then we know that by question $2(b)$, $X times [0,1] iso X times {0} iso X$ and so they have isomorphic homology groups. + Let $f$ be the deformation retraction of $[0,1]$ to ${0}$, then $id_X times f$ is a deformation retraction of $X times [0,1]$ to $X times {0}$. Since this deformation retraction fixes $X times {0}$, we have that $id_X times f$ passes to the quotient $C X$ and so it is a deformation retraction from $C X$ to the image of $X times {0}$ which is a point. + We have the long exact sequence $ ... -> H_(n+1)(C X) -> H_(n+1) (C X, X times {1}) -> H_n (X times {1}) -> H_n (C X) -> ... $ then for $n >= 1$ we have $ 0 -> H_(n+1) (C X, X times {1}) -> H_n (X times {1}) -> 0. $ and so because this is exact we have $ H_(n+1) (C X, X times {1}) iso H_n (X) $ for $n = 0$ we have $ 0 -> H_(1) (C X, X times {1}) -> H_0 (X times {1}) -> H_(0) (C X) -> 0 $ now the map $H_0 (X times {1}) -> H_0 (C X)$ is clearly surjective so we have $H_1 (C X, X times {1}) iso ZZ^(n) quo ZZ$ where $n$ is the number of connected components of $X$. Finally we show that $H_n (C X, X times {1}) iso H_n (S X)$, this is true because we have a neighborhood $X times (1/2,1] seq C X$ which clearly deformation retracts to $X times {1}$, this finishes the proof. + We consider the maps $f: S^q times [0,1] -> S^(q+1)$ and $g : S^(q+1) -> S S^q$ which are given by $ f(x, t) = (2 x dot sqrt(t - t^2),2t-1) wide g(x, x_(q+1)) = cases((x/norm(x),(x_(q+1)+1)/2): x != 0, (y, (x_(q+1)+1)/2): x = 0) $ for any fixed $y in S^q$. It is clear that $f(x,t)$ is continuous, and since $f(x,0) = (0,-1)$ and $f(x,1) = (0,1)$ for all $x$ we have that this map factors as $tilde(f) : S S^q -> S^(q+1)$. For $g$ we trivially have continuity when $x != 0$, but at $x = 0$ we have that $x_(q+1) = plus.minus 1$ so assume WLOG that we have a sequence of points $(x(n), x_(q+1)(n))$ such that $x(n) -> 0$ and $x_(q+1) (n) -> 1$. Then we have $g(0,1) = (y,1)$ and $g(x(n), x_(q+1)(n)) -> (y,1)$ because $x_(q+1)(n) -> 1$ and any such sequence in $S S^q$ converges to $(y,1)$. Thus $g$ is continuous at $(0,1)$ and also trivially at $(0,-1)$. It is also clear that $tilde(f) compose g = id_(S^(q+1))$ and that $g compose tilde(f) = id_(S S^q)$ so the two spaces are homeomorphic. = Question == Statement Consider Theorem 9.1 in Haynes Miller's notes. Miller writes part of the proof of this theorem by constructing a map $diff : H_n (C) -> H_(n-1) (A)$. Prove, using Miller's definition of this map, that the sequence $ H_n (B) ->^(g_n) H_n (C) ->^(diff) H_(n-1) (A) ->^(f_(n-1)) H_(n-1) (B) $ is exact. == Solution Using Miller's argument we can essentially write $ diff c = f_(n-1)^(-1) compose d compose g_n^(-1) c $ where $g_n^(-1)$ makes sense because the result is independent of choice of pre-image and $f_(n-1)^(-1)$ makes sense because $d compose g_n^(-1) c$ lands in its image. Using this we have that $ diff compose g_n = (f_(n-1)^(-1) compose d compose g_(n)^(-1) compose g) = f_(n-1)^(-1) compose d $ but all the elements of $H_(n) (B)$ are classes of cycles so $f_(n-1)^(-1) compose d$ is equal to zero on $H_n (B)$ since $f_(n-1)$ is injective. On the other hand if $diff [x] = 0$ then since $f_(n-1)$ is injective we must have that $d compose g_(n)^(-1) x = 0$, but then we must have that $g_(n)^(-1) x in Z(B_n)$ and thus we have $[g_(n)^(-1) x] in H(B_n)$ which combined with the fact that $g_n ([g_(n)^(-1) x]) = [x]$ gives us $x in im g_n$. Next we have $ f_(n-1) compose diff = f_(n-1) compose (f_(n-1)^(-1) compose d compose g_(n)^(-1)) = d compose g_(n)^(-1) $ which is now $0$ on $H_(n) (A)$ because $g_(n)^(-1) x in Z(B_n)$ for all $x in Z(C_n)$. Next assume that $[y] in ker f_(n-1)$ then by injectivity $[y] = 0$ so $y in B(B_n)$. But then there exists some $[x]$ such that $d [x] = y$, so we have $y = (d compose g_n^(-1)) g_n ([x])$ and so $y in im diff$. = Question == Statement In this exercise, we will define for each topological space $X$ a natural map $k_X : S_n (X) -> S_(n+1) (X times [0,1])$. We will use this natural map to prove that any homotopic maps $f,g : X -> Y$ induce the same map on homology groups. It may help to look at the proof and discussion after Theorem 6.2 in Miller's notes, but keep in mind that he proves something much more general there and our task in this problem will be easier. + Write down explicitly what it means for $k_X$ to be natural. + Using naturality, explain why the element #h(1fr) $ k_(Delta^n) (1_(Delta^n)) in S_(n+1) (Delta^n times [0,1]) $ determines the value of $k_X (sigma)$ for any topological space $X$ and any $n$-simplex $sigma : Delta^n -> X$. + Miller's notes explain how to define $k_(Delta^n) (1_(Delta^n))$ in general, but we'll focus on the cases $n = 0$ and $n = 1$ in this problem. Since $Delta^0$ is a point, note that $k_(Delta^0) (1_(Delta^0))$ is just an element of $S_1 ([0,1])$. We can choose this to be our favorite homeomorphism $Delta^1 -> [0,1]$, which sends $e_0$ to $0$ and $e_1$ to $1$. Consider the case $n = 1$. We seek to define a class $k_(Delta^1) (1_(Delta^1)) in S_2 (Delta^1 times [0,1])$. Recall that $Delta^1$ is homeomorphic to $[0,1]$, so $Delta^1 times [0,1]$ is just the square $[0,1] times [0,1]$. Write down an explicit element in $S_2 ([0,1] times [0,1])$ with boundary the perimeter of the square. You don't need to prove anything about your element in this part, but you should choose it so that it works in part $(d)$. Remember that $S_2 ([0,1] times [0,1])$ is the free abelian group generated by $op("Sing")_2 ([0,1] times [0,1])$-your element in $S_2 ([0,1] times [0,1])$ will not be a generator, but rather a formal sum of generators. + Suppose that $f,g : X -> Y$ are two homotopic maps, connected by a homotopy $ h : X times [0,1] -> Y. $ We seek to define a chain homotopy between $S_* (f)$ and $S_* (g)$, which should be given by some maps $h_n : S_n (X) -> S_(n+1) (Y)$. The map $h$ induces a map $ S_(n+1) (h) : S_(n+1) (X times [0,1]) -> S_(n+1) (Y), $ and we may compose this with $k_X$ to give a map $h_n : S_n (X) -> S_(n+1) (Y)$. Your answer to the previous problem defines $h_1 : S_1 (X) -> S_2 (Y)$. Use naturality to prove the chain homotopy relation $ diff h_1 + h_0 diff = S_1 (f) - S_1 (g). $ #pb() == Solution + Note that $S_n (X)$ and $S_(n+1)(X times [0,1])$ are both functors from $Top$ to $Ab$, with $S_(n+1) (X times [0,1])$ mapping morphisms $f : X -> Y$ to the morphism $(f times id_[0,1])_*$. In that context naturality would mean that for every topological space $X$ we have a map $S_n (X) -> S_(n+1) (X times [0,1])$ such that for every continuous map $f : X -> Y$ we have that the following diagram commutes #align(center)[#commutative-diagram( node((0, 0), $S_(n)(X)$, "a"), node((0, 1), $S_(n+1)(X times [0,1])$, "b"), node((1, 0), $S_(n)(Y)$, "c"), node((1, 1), $S_(n+1)(Y times [0,1])$, "d"), arr("a", "b", $k_X$), arr("a", "c", $f_*$), arr("c", "d", $k_Y$), arr("b", "d", $(f times id_[0,1])_*$), node-padding: (50pt, 50pt), )] where $tilde(f)_*$ is the + Using the naturality diagram, setting $X = Delta^n, Y = X, f = sigma$, we have #align(center)[#commutative-diagram( node((0, 0), $S_(n)(Delta^n)$, "a"), node((0, 1), $S_(n+1)(Delta^n times [0,1])$, "b"), node((1, 0), $S_(n)(X)$, "c"), node((1, 1), $S_(n+1)(X times [0,1])$, "d"), arr("a", "b", $k_(Delta^n)$), arr("a", "c", $sigma_*$), arr("c", "d", $k_X$), arr("b", "d", $(sigma times id_[0,1])_*$), node-padding: (50pt, 50pt), )] Now clearly we have that $sigma_* (1_(Delta^n))$ is in fact equal to $sigma$ as an element of $S_n (X)$. We thus have, since the diagram commutes, $ k_X (sigma) = (sigma times id_[0,1])_* (k_(Delta^n) (1_(Delta^n))) $ Hence $k_X (sigma)$ is fully determined by $k_(Delta^n) (1_(Delta^n))$. + We will set $k_(Delta^1) (1_(Delta^1))$ to be the element $a - b in S_2 (Delta^1 times [0,1])$ described in the following diagram. #align(center)[#cetz.canvas({ import cetz.draw: * merge-path(fill: rgb("#ff413640"), { line((3,0), (0,0), name: "wx") line((0,0), (3,3), name: "xz") line((3,3), (3,0), name: "wz") }) merge-path(fill: rgb("#2ecc4040"), { line((0,0), (3,3), name: "xz") line((0,0), (0,3), name: "yx") line((0,3), (3,3), name: "yz") }) arc((1.1,1.9), start: -45deg, delta: -270deg, radius: 0.3, mark: (end: ">"), name:"a") arc((1.9,1.1), start: 135deg, delta: 270deg, radius: 0.3, mark: (end: ">"), name:"b") content("a.origin", $a$) content("b.origin", $b$) mark((0,0), (1.5,0), symbol: ">", fill:black) mark((0,0), (0,1.5), symbol: ">", fill:black) mark((0,3), (1.5,3), symbol: ">", fill:black) mark((3,0), (3,1.5), symbol: ">", fill:black) mark((0,0), (1.5,1.5), symbol: ">", fill:black) content((1.5,0), $Delta$, anchor: "north", padding: .1) content((1.5,3), $Delta$, anchor: "south", padding: .1) content((0,1.5), $[0,1]$, anchor: "east", padding: .1) content((3,1.5), $[0,1]$, anchor: "west", padding: .1) content((0,0), $x$, anchor: "north-east", padding: .1) content((0,3), $y$, anchor: "south-east", padding: .1) content((3,3), $z$, anchor: "south-west", padding: .1) content((3,0), $w$, anchor: "north-west", padding: .1) })] We record here that $d a = arrow(y z) - arrow(x z) + arrow(x y)$ and $d b = arrow(w z) - arrow(x z) + arrow(x w)$. + We check now that $diff h_1 + h_0 diff = S_1 (f) - S_1 (g)$, applying this to a specific element $sigma in S_1 (X)$ gives us $ diff h_1 sigma + h_0 diff sigma &= f_* sigma - g_* sigma \ diff (h_* (k_X sigma)) + h_* (k_X diff sigma) &= f_* sigma - g_* sigma $ now analyzing the first term on its own, we have $ diff (h_* (k_X sigma)) &= h_* (diff (sigma times id_[0,1])_* (k_(Delta^1) (1_(Delta^n)))) = h_* ((sigma times id_[0,1])_* (diff (a - b))) \ &= h_* (sigma times id_[0,1])_* (arrow(y z) + arrow(x y) - arrow(w z) - arrow(x w)). $ For the second term we have $ h_* (k_X (diff sigma)) &= h_* (k_X (d_1 sigma - d_0 sigma)) \ &= h_* ((d_1 sigma times id_[0,1])_* (k_(Delta^0) (1_(Delta^0))) - (d_0 sigma times id_[0,1])_* (k_(Delta^0) (1_(Delta^0)))) $ Now by identifying $d_0 sigma times id_[0,1]$ with $arrow(x y)$ and $d_1 sigma times id_[0,1]$ with $arrow(w z)$, we get $ h_* (k_X (diff sigma)) &= h_* (sigma times id_[0,1])_* (-arrow(x y) + arrow(w z)). $ Now we get $ diff h_1 sigma + h_0 diff sigma = h_* (sigma times id_[0,1])_* (arrow(y z) - arrow(x w)) $ Finally we have that $f_* sigma = h_* (iota_1)_* sigma$ where $iota_1$ is the inclusion of $Delta^1$ along $arrow(y z)$, and $g_* sigma = h_* (iota_0)_* sigma$ where $iota_0$ is the inclusion along $- arrow(x w)$. Together we get $ f_* sigma = h_* (sigma times id_[0,1])_* (arrow(y z)) \ g_* sigma = h_* (sigma times id_[0,1])_* (arrow(x w)) $ which is exactly what we wanted because then $ f_* sigma - g_* sigma = h_* (sigma times id_[0,1])_* (arrow(y z) - arrow(x w)) $ which finishes the proof.
https://github.com/UntimelyCreation/typst-neat-cv
https://raw.githubusercontent.com/UntimelyCreation/typst-neat-cv/main/src/content/fr/experience.typ
typst
MIT License
#import "../../template.typ": * #cvSection("Expérience professionnelle") #cvEntry( title: [Ingénieur logiciel senior], organisation: [Entreprise ABC], logo: "", date: [2021 - Auj.], location: [France], description: list( [#lorem(20)], [#lorem(20)], ), tags: ("Go", "TypeScript", "React", "PostgreSQL") ) #divider() #cvEntry( title: [Ingénieur logiciel], organisation: [Groupe DEF], logo: "", date: [2018 - 2021], location: [France], description: list( [#lorem(12)], [#lorem(12)], ), tags: ("Python", "PostgreSQL") ) #divider() #cvEntry( title: [Ingénieur logiciel stagiaire], organisation: [Entreprise XYZ], logo: "", date: [Été 2015], location: [France], description: list( [#lorem(16)], [#lorem(16)], ), tags: ("TypeScript", "Angular") )
https://github.com/Tiggax/zakljucna_naloga
https://raw.githubusercontent.com/Tiggax/zakljucna_naloga/main/src/figures/rk4.typ
typst
#import "../additional.typ": todo #import "@preview/cetz:0.2.2": canvas, plot, draw, vector #let plot = canvas( length: 1cm, { let a = 0.1 let b = 1.2 let c = 1 let fn(x) = a* calc.pow((x+ b),2) + c let o_fn(x) = 2*a*x + 2*a*b plot.plot( size: (8,8), //axis-style: "left", x-label: none, y-label: none, x-min: 0.0001, x-max: 10, x-tick-step: none, y-min: 0, y-max: 10, y-tick-step: none, { plot.add( domain: (0,10), x => fn(x) ) plot.annotate( { import draw: * let label_point(x,y, uniq, label, x_label, y_label) = group( name: uniq, { let pos = (x, y) let n_pos = (x + 1.5, o_fn(x)*1.5 + y) circle(pos, radius: .1, fill: red, stroke: red, name: "point") line( pos, n_pos, mark: (end: ">"), fill: red, stroke: red, name: "line" ) content((v => vector.add(v,(0.2,-0.2)), "line.mid"),text(fill: red, label)) line( (0,pos.at(1)), pos, stroke: (dash: "dashed"), name: "y_line" ) line( (pos.at(0), 0), pos, stroke: (dash: "dashed"), name: "x_line" ) content( anchor: "north", padding: .2, "x_line.start", text(x_label) ) content( anchor: "east", "y_line.start", padding: .2, align(right, text(y_label)) ) }) let half = 3 let h = 7 label_point(0,fn(0), "k_1", $k_1$, $t_0$, $y_0$) label_point(half, (fn(half) - .9),"k_2", $k_2$, $t_0 + h/2$, $y_0 + k_1/2$) label_point(half, (fn(half) + 0.9 ),"k_3", $k_3$, $t_0 + h/2$, $y_0 + k_2/2$) label_point(h, (fn(h) - .5),"k_4", $k_4$, $t_0 + h$, $y_0 + k_3$) line((0,fn(0)), (h,7.5), mark: (symbol: "*"), stroke: (paint: green, dash: "dashed"), name: "solution") content( (v => vector.add(v, (-1,0.1)),"solution.end"), text(fill: green)[$(t_1,y^*_1)$] ) } ) } ) } ) #let error(calc_val, true_val) = { return (calc_val - true_val)/ true_val return calc.abs(calc_val / true_val)*100 } #let accuracy(acc_steps) = { import "@preview/oxifmt:0.2.1": strfmt let fmt(x,d: 4,add: [] ) = [#strfmt("{:." + str(d) + "}", x)#add] let fn(x) = calc.exp(x) + x + 1 let o_fn(x,y) = y - x let euler(steps) = { let out = () let p_x = 0.1 let p_y = fn(p_x) for x in range(0, steps).map(x => x * (10/steps) ) { let h = (x - p_x) let y = h * o_fn(p_x,p_y) + p_y out.push(( x: x, y: y, error: (fn(x) - y) )) p_x = x p_y = y } return out } let rk(steps) = { let out = () let p_x = 0.1 let p_y = fn(p_x) for x in range(0,steps).map(x => x * (10/steps) ) { let h = (x - p_x) let k1 = h * o_fn(p_x, p_y) let k2 = h * o_fn(p_x + (h/2), p_y + (k1/2)) let k3 = h * o_fn(p_x + (h/2), p_y + (k2/2)) let k4 = h * o_fn(x, p_y + k3) let y = p_y + (k1 + 2*k2 + 2*k3 + k4)/6 out.push(( x: x, y: y, error: (fn(x) - y) )) p_x = x p_y = y } return out } let euler = euler(acc_steps) let rk = rk(acc_steps) return ( euler: euler, rk4: rk, table: euler .zip(rk) .map(((e,r))=> { let y = fn(e.x) return ( fmt(e.x, d:0), fmt(y), fmt(r.y), fmt(error(r.y, y) * 100, add: [%], d: 2) , fmt(e.y), fmt(error(e.y, y) * 100 , add: [%], d: 2) ) } ) ) } #let rk4_compare(steps) = { import "@preview/cetz:0.2.2": canvas, plot, draw, vector let (euler, rk4) = accuracy(steps) canvas( length: 1cm, { plot.plot( size: (14,8), legend: "legend.inner-north-west", x-min: -1, x-max: 10, x-tick-step: none, y-min: -50, y-max: 500, y-tick-step: none, { plot.add( label: [$y$ solution], style: (stroke: (paint: aqua, thickness: 1.5pt)), domain: (-1,10), x => calc.exp(x) + x + 1 ) plot.add( label: [Euler], mark: "o", mark-size: .15, mark-style: (stroke: green, fill: green), style: (stroke: (thickness: .5pt, paint: green)), euler.map(((x,y,error))=>(x,y)) ) plot.add( label: [Runge-Kutta], mark: "o", mark-size: .15, mark-style: (stroke: red, fill: red), style: (stroke: (thickness: .5pt, paint: red)), rk4.map(((x,y,error))=>(x,y)) ) } ) } ) } #let comparison_table(steps) = { let cells = accuracy(steps).table.flatten() return table( fill: (x,y) => { if y < 2 { return color.mix(teal, white)} if (x == 3 or x == 5) { let val = float(cells.at( x + 6*(y - 2)).children.first().text) / 100 return color.hsv((1 - calc.abs(val))* 90deg, 70%, 100%) } }, columns: 6, table.header( table.cell(rowspan: 2, align: horizon)[x], table.cell(rowspan: 2, align: horizon)[$y(x) = e^x + x + 1$], table.cell(colspan: 2, fill: color.mix(red, white))[RK4], table.cell(colspan: 2, fill: color.mix(green, white))[Euler], $y^*$, [error], $y^*$, [error] ), ..cells ) }
https://github.com/saurabtharu/Internship-repo
https://raw.githubusercontent.com/saurabtharu/Internship-repo/main/Internship%20Report%20-%20typst/chapters/ref-appendix.typ
typst
#import "../template.typ": * #align(center, text(16pt)[ = References <references> ]) \ #bibliography(title:none, style: "american-psychological-association", "../bibliography.bib") #set page(numbering: none) // #pagebreak() /******************************************************************************/ #align(center, text(16pt)[ = Appendices <appendices> ]) \ *#figure( image("report_images/Harbor init.png"), supplement: none, caption: "Initializing Locally Hosted Container Registry" )* \ \ \ *#figure( image("report_images/Locally-hosted-harbor.png"), supplement: none, caption: "Dashboard of Locally Hosted Container Registry" )* *#figure( image("report_images/images-pushed to harbor.png"), supplement: none, caption: "Example of Docker Images Pushed to the Locally Hosted Container Registry" )* \ \ \ *#figure( image("report_images/SSL certificate to website.png"), supplement: none, caption: "Provisioning of SSL Certificate to Website" )* *#figure( image("report_images/k3s cluster management using GUI rancher.png"), supplement: none, caption: "Rancher Dashboard for K3S cluster mangement" )* \ \ \ *#figure( image("report_images/k3s cluster dashboard in rancher.png"), supplement: none, caption: "Rancher UI for a Cluster's Dashboard" )* \ \ \ *#figure( image("report_images/k3s cluster management using CLI.png"), supplement: none, caption: "K3S Cluster Managenemtn using CLI" )*
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/015.%20icad.html.typ
typst
#set page( paper: "a5", margin: (x: 1.8cm, y: 1.5cm), ) #set text( font: "Liberation Serif", size: 10pt, hyphenate: false ) #set par(justify: true) #set quote(block: true) #v(10pt) = Revenge of the Nerds #v(10pt) _May 2002_ #quote(attribution: [<NAME>, co-author of the Java spec])["We were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp."] In the software business there is an ongoing struggle between the pointy-headed academics, and another equally formidable force, the pointy-haired bosses. Everyone knows who the pointy-haired boss is, right? I think most people in the technology world not only recognize this cartoon character, but know the actual person in their company that he is modelled upon. The pointy-haired boss miraculously combines two qualities that are common by themselves, but rarely seen together: #set enum(numbering: "a)") + he knows nothing whatsoever about technology, and + he has very strong opinions about it. Suppose, for example, you need to write a piece of software. The pointy-haired boss has no idea how this software has to work, and can't tell one programming language from another, and yet he knows what language you should write it in. Exactly. He thinks you should write it in Java. Why does he think this? Let's take a look inside the brain of the pointy-haired boss. What he's thinking is something like this. Java is a standard. I know it must be, because I read about it in the press all the time. Since it is a standard, I won't get in trouble for using it. And that also means there will always be lots of Java programmers, so if the programmers working for me now quit, as programmers working for me mysteriously always do, I can easily replace them. Well, this doesn't sound that unreasonable. But it's all based on one unspoken assumption, and that assumption turns out to be false. The pointy-haired boss believes that all programming languages are pretty much equivalent. If that were true, he would be right on target. If languages are all equivalent, sure, use whatever language everyone else is using. But all languages are not equivalent, and I think I can prove this to you without even getting into the differences between them. If you asked the pointy-haired boss in 1992 what language software should be written in, he would have answered with as little hesitation as he does today. Software should be written in C++. But if languages are all equivalent, why should the pointy-haired boss's opinion ever change? In fact, why should the developers of Java have even bothered to create a new language? Presumably, if you create a new language, it's because you think it's better in some way than what people already had. And in fact, Gosling makes it clear in the first Java white paper that Java was designed to fix some problems with C++. So there you have it: languages are not all equivalent. If you follow the trail through the pointy-haired boss's brain to Java and then back through Java's history to its origins, you end up holding an idea that contradicts the assumption you started with. So, who's right? <NAME>, or the pointy-haired boss? Not surprisingly, Gosling is right. Some languages are better, for certain problems, than others. And you know, that raises some interesting questions. Java was designed to be better, for certain problems, than C++. What problems? When is Java better and when is C++? Are there situations where other languages are better than either of them? Once you start considering this question, you have opened a real can of worms. If the pointy-haired boss had to think about the problem in its full complexity, it would make his brain explode. As long as he considers all languages equivalent, all he has to do is choose the one that seems to have the most momentum, and since that is more a question of fashion than technology, even he can probably get the right answer. But if languages vary, he suddenly has to solve two simultaneous equations, trying to find an optimal balance between two things he knows nothing about: the relative suitability of the twenty or so leading languages for the problem he needs to solve, and the odds of finding programmers, libraries, etc. for each. If that's what's on the other side of the door, it is no surprise that the pointy-haired boss doesn't want to open it. The disadvantage of believing that all programming languages are equivalent is that it's not true. But the advantage is that it makes your life a lot simpler. And I think that's the main reason the idea is so widespread. It is a comfortable idea. We know that Java must be pretty good, because it is the cool, new programming language. Or is it? If you look at the world of programming languages from a distance, it looks like Java is the latest thing. (From far enough away, all you can see is the large, flashing billboard paid for by Sun.) But if you look at this world up close, you find that there are degrees of coolness. Within the hacker subculture, there is another language called Perl that is considered a lot cooler than Java. Slashdot, for example, is generated by Perl. I don't think you would find those guys using Java Server Pages. But there is another, newer language, called Python, whose users tend to look down on Perl, and more waiting in the wings. If you look at these languages in order, Java, Perl, Python, you notice an interesting pattern. At least, you notice this pattern if you are a Lisp hacker. Each one is progressively more like Lisp. Python copies even features that many Lisp hackers consider to be mistakes. You could translate simple Lisp programs into Python line for line. It's 2002, and programming languages have almost caught up with 1958. == Catching Up with Math What I mean is that Lisp was first discovered by <NAME> in 1958, and popular programming languages are only now catching up with the ideas he developed then. Now, how could that be true? Isn't computer technology something that changes very rapidly? I mean, in 1958, computers were refrigerator-sized behemoths with the processing power of a wristwatch. How could any technology that old even be relevant, let alone superior to the latest developments? I'll tell you how. It's because Lisp was not really designed to be a programming language, at least not in the sense we mean today. What we mean by a programming language is something we use to tell a computer what to do. McCarthy did eventually intend to develop a programming language in this sense, but the Lisp that we actually ended up with was based on something separate that he did as a theoretical exercise -- an effort to define a more convenient alternative to the Turing Machine. As McCarthy said later, #quote(attribution: [<NAME>])[Another way to show that Lisp was neater than Turing machines was to write a universal Lisp function and show that it is briefer and more comprehensible than the description of a universal Turing machine. This was the Lisp function `eval`..., which computes the value of a Lisp expression... Writing _eval_ required inventing a notation representing Lisp functions as Lisp data, and such a notation was devised for the purposes of the paper with no thought that it would be used to express Lisp programs in practice.] What happened next was that, some time in late 1958, <NAME>, one of McCarthy's grad students, looked at this definition of _eval_ and realized that if he translated it into machine language, the result would be a Lisp interpreter. This was a big surprise at the time. Here is what McCarthy said about it later in an interview: #quote(attribution: [<NAME>])[ <NAME> said, look, why don't I program this `eval`..., and I said to him, ho, ho, you're confusing theory with practice, this eval is intended for reading, not for computing. But he went ahead and did it. That is, he compiled the eval in my paper into [IBM] 704 machine code, fixing bugs, and then advertised this as a Lisp interpreter, which it certainly was. So at that point Lisp had essentially the form that it has today....] Suddenly, in a matter of weeks I think, McCarthy found his theoretical exercise transformed into an actual programming language -- and a more powerful one than he had intended. So the short explanation of why this 1950s language is not obsolete is that it was not technology but math, and math doesn't get stale. The right thing to compare Lisp to is not 1950s hardware, but, say, the Quicksort algorithm, which was discovered in 1960 and is still the fastest general-purpose sort. There is one other language still surviving from the 1950s, Fortran, and it represents the opposite approach to language design. Lisp was a piece of theory that unexpectedly got turned into a programming language. Fortran was developed intentionally as a programming language, but what we would now consider a very low-level one. Fortran I, the language that was developed in 1956, was a very different animal from present-day Fortran. Fortran I was pretty much assembly language with math. In some ways it was less powerful than more recent assembly languages; there were no subroutines, for example, only branches. Present-day Fortran is now arguably closer to Lisp than to Fortran I. Lisp and Fortran were the trunks of two separate evolutionary trees, one rooted in math and one rooted in machine architecture. These two trees have been converging ever since. Lisp started out powerful, and over the next twenty years got fast. So-called mainstream languages started out fast, and over the next forty years gradually got more powerful, until now the most advanced of them are fairly close to Lisp. Close, but they are still missing a few things.... == What Made Lisp Different When it was first developed, Lisp embodied nine new ideas. Some of these we now take for granted, others are only seen in more advanced languages, and two are still unique to Lisp. The nine ideas are, in order of their adoption by the mainstream, #set enum(numbering: "1.") #enum( enum.item[Conditionals. A conditional is an if-then-else construct. We take these for granted now, but Fortran I didn't have them. It had only a conditional goto closely based on the underlying machine instruction.], enum.item[A function type. In Lisp, functions are a data type just like integers or strings. They have a literal representation, can be stored in variables, can be passed as arguments, and so on.], enum.item[Recursion. Lisp was the first programming language to support it.], enum.item[Dynamic typing. In Lisp, all variables are effectively pointers. Values are what have types, not variables, and assigning or binding variables means copying pointers, not what they point to.], enum.item[Garbage-collection.], enum.item[Programs composed of expressions. Lisp programs are trees of expressions, each of which returns a value. This is in contrast to Fortran and most succeeding languages, which distinguish between expressions and statements. It was natural to have this distinction in Fortran I because you could not nest statements. And so while you needed expressions for math to work, there was no point in making anything else return a value, because there could not be anything waiting for it. This limitation went away with the arrival of block-structured languages, but by then it was too late. The distinction between expressions and statements was entrenched. It spread from Fortran into Algol and then to both their descendants.], enum.item[A symbol type. Symbols are effectively pointers to strings stored in a hash table. So you can test equality by comparing a pointer, instead of comparing each character.], enum.item[A notation for code using trees of symbols and constants.], enum.item[The whole language there all the time. There is no real distinction between read-time, compile-time, and runtime. You can compile or run code while reading, read or run code while compiling, and read or compile code at runtime. Running code at read-time lets users reprogram Lisp's syntax; running code at compile-time is the basis of macros; compiling at runtime is the basis of Lisp's use as an extension language in programs like Emacs; and reading at runtime enables programs to communicate using s-expressions, an idea recently reinvented as XML.] ) When Lisp first appeared, these ideas were far removed from ordinary programming practice, which was dictated largely by the hardware available in the late 1950s. Over time, the default language, embodied in a succession of popular languages, has gradually evolved toward Lisp. Ideas 1-5 are now widespread. Number 6 is starting to appear in the mainstream. Python has a form of 7, though there doesn't seem to be any syntax for it. As for number 8, this may be the most interesting of the lot. Ideas 8 and 9 only became part of Lisp by accident, because <NAME> implemented something McCarthy had never intended to be implemented. And yet these ideas turn out to be responsible for both Lisp's strange appearance and its most distinctive features. Lisp looks strange not so much because it has a strange syntax as because it has no syntax; you express programs directly in the parse trees that get built behind the scenes when other languages are parsed, and these trees are made of lists, which are Lisp data structures. Expressing the language in its own data structures turns out to be a very powerful feature. Ideas 8 and 9 together mean that you can write programs that write programs. That may sound like a bizarre idea, but it's an everyday thing in Lisp. The most common way to do it is with something called a _macro_. The term "macro" does not mean in Lisp what it means in other languages. A Lisp macro can be anything from an abbreviation to a compiler for a new language. If you want to really understand Lisp, or just expand your programming horizons, I would learn more about macros. Macros (in the Lisp sense) are still, as far as I know, unique to Lisp. This is partly because in order to have macros you probably have to make your language look as strange as Lisp. It may also be because if you do add that final increment of power, you can no longer claim to have invented a new language, but only a new dialect of Lisp. I mention this mostly as a joke, but it is quite true. If you define a language that has car, cdr, cons, quote, cond, atom, eq, and a notation for functions expressed as lists, then you can build all the rest of Lisp out of it. That is in fact the defining quality of Lisp: it was in order to make this so that McCarthy gave Lisp the shape it has. == Where Languages Matter So suppose Lisp does represent a kind of limit that mainstream languages are approaching asymptotically -- does that mean you should actually use it to write software? How much do you lose by using a less powerful language? Isn't it wiser, sometimes, not to be at the very edge of innovation? And isn't popularity to some extent its own justification? Isn't the pointy-haired boss right, for example, to want to use a language for which he can easily hire programmers? There are, of course, projects where the choice of programming language doesn't matter much. As a rule, the more demanding the application, the more leverage you get from using a powerful language. But plenty of projects are not demanding at all. Most programming probably consists of writing little glue programs, and for little glue programs you can use any language that you're already familiar with and that has good libraries for whatever you need to do. If you just need to feed data from one Windows app to another, sure, use Visual Basic. You can write little glue programs in Lisp too (I use it as a desktop calculator), but the biggest win for languages like Lisp is at the other end of the spectrum, where you need to write sophisticated programs to solve hard problems in the face of fierce competition. A good example is the airline fare search program that ITA Software licenses to Orbitz. These guys entered a market already dominated by two big, entrenched competitors, Travelocity and Expedia, and seem to have just humiliated them technologically. The core of ITA's application is a 200,000 line Common Lisp program that searches many orders of magnitude more possibilities than their competitors, who apparently are still using mainframe-era programming techniques. (Though ITA is also in a sense using a mainframe-era programming language.) I have never seen any of ITA's code, but according to one of their top hackers they use a lot of macros, and I am not surprised to hear it. == Centripetal Forces I'm not saying there is no cost to using uncommon technologies. The pointy-haired boss is not completely mistaken to worry about this. But because he doesn't understand the risks, he tends to magnify them. I can think of three problems that could arise from using less common languages. Your programs might not work well with programs written in other languages. You might have fewer libraries at your disposal. And you might have trouble hiring programmers. How much of a problem is each of these? The importance of the first varies depending on whether you have control over the whole system. If you're writing software that has to run on a remote user's machine on top of a buggy, closed operating system (I mention no names), there may be advantages to writing your application in the same language as the OS. But if you control the whole system and have the source code of all the parts, as ITA presumably does, you can use whatever languages you want. If any incompatibility arises, you can fix it yourself. In server-based applications you can get away with using the most advanced technologies, and I think this is the main cause of what <NAME> calls the "programming language renaissance." This is why we even hear about new languages like Perl and Python. We're not hearing about these languages because people are using them to write Windows apps, but because people are using them on servers. And as software shifts off the desktop and onto servers (a future even Microsoft seems resigned to), there will be less and less pressure to use middle-of-the-road technologies. As for libraries, their importance also depends on the application. For less demanding problems, the availability of libraries can outweigh the intrinsic power of the language. Where is the breakeven point? Hard to say exactly, but wherever it is, it is short of anything you'd be likely to call an application. If a company considers itself to be in the software business, and they're writing an application that will be one of their products, then it will probably involve several hackers and take at least six months to write. In a project of that size, powerful languages probably start to outweigh the convenience of pre-existing libraries. The third worry of the pointy-haired boss, the difficulty of hiring programmers, I think is a red herring. How many hackers do you need to hire, after all? Surely by now we all know that software is best developed by teams of less than ten people. And you shouldn't have trouble hiring hackers on that scale for any language anyone has ever heard of. If you can't find ten Lisp hackers, then your company is probably based in the wrong city for developing software. In fact, choosing a more powerful language probably decreases the size of the team you need, because #set enum(numbering: "a)") + if you use a more powerful language you probably won't need as many hackers, and + hackers who work in more advanced languages are likely to be smarter. I'm not saying that you won't get a lot of pressure to use what are perceived as "standard" technologies. At Viaweb (now Yahoo Store), we raised some eyebrows among VCs and potential acquirers by using Lisp. But we also raised eyebrows by using generic Intel boxes as servers instead of "industrial strength" servers like Suns, for using a then-obscure open-source Unix variant called FreeBSD instead of a real commercial OS like Windows NT, for ignoring a supposed e-commerce standard called SET that no one now even remembers, and so on. You can't let the suits make technical decisions for you. Did it alarm some potential acquirers that we used Lisp? Some, slightly, but if we hadn't used Lisp, we wouldn't have been able to write the software that made them want to buy us. What seemed like an anomaly to them was in fact cause and effect. If you start a startup, don't design your product to please VCs or potential acquirers. Design your product to please the users. If you win the users, everything else will follow. And if you don't, no one will care how comfortingly orthodox your technology choices were. == The Cost of Being Average How much do you lose by using a less powerful language? There is actually some data out there about that. The most convenient measure of power is probably _code size_. The point of high-level languages is to give you bigger abstractions -- bigger bricks, as it were, so you don't need as many to build a wall of a given size. So the more powerful the language, the shorter the program (not simply in characters, of course, but in distinct elements). How does a more powerful language enable you to write shorter programs? One technique you can use, if the language will let you, is something called bottom-up programming. Instead of simply writing your application in the base language, you build on top of the base language a language for writing programs like yours, then write your program in it. The combined code can be much shorter than if you had written your whole program in the base language -- indeed, this is how most compression algorithms work. A bottom-up program should be easier to modify as well, because in many cases the language layer won't have to change at all. Code size is important, because the time it takes to write a program depends mostly on its length. If your program would be three times as long in another language, it will take three times as long to write -- and you can't get around this by hiring more people, because beyond a certain size new hires are actually a net lose. <NAME> described this phenomenon in his famous book _The Mythical Man-Month_, and everything I've seen has tended to confirm what he said. So how much shorter are your programs if you write them in Lisp? Most of the numbers I've heard for Lisp versus C, for example, have been around 7-10x. But a recent article about ITA in _New Architect_ magazine said that "one line of Lisp can replace 20 lines of C," and since this article was full of quotes from ITA's president, I assume they got this number from ITA. If so then we can put some faith in it; ITA's software includes a lot of C and C++ as well as Lisp, so they are speaking from experience. My guess is that these multiples aren't even constant. I think they increase when you face harder problems and also when you have smarter programmers. A really good hacker can squeeze more out of better tools. As one data point on the curve, at any rate, if you were to compete with ITA and chose to write your software in C, they would be able to develop software twenty times faster than you. If you spent a year on a new feature, they'd be able to duplicate it in less than three weeks. Whereas if they spent just three months developing something new, it would be five years before you had it too. And you know what? That's the best-case scenario. When you talk about code-size ratios, you're implicitly assuming that you can actually write the program in the weaker language. But in fact there are limits on what programmers can do. If you're trying to solve a hard problem with a language that's too low-level, you reach a point where there is just too much to keep in your head at once. So when I say it would take ITA's imaginary competitor five years to duplicate something ITA could write in Lisp in three months, I mean five years if nothing goes wrong. In fact, the way things work in most companies, any development project that would take five years is likely never to get finished at all. I admit this is an extreme case. ITA's hackers seem to be unusually smart, and C is a pretty low-level language. But in a competitive market, even a differential of two or three to one would be enough to guarantee that you'd always be behind. == A Recipe This is the kind of possibility that the pointy-haired boss doesn't even want to think about. And so most of them don't. Because, you know, when it comes down to it, the pointy-haired boss doesn't mind if his company gets their ass kicked, so long as no one can prove it's his fault. The safest plan for him personally is to stick close to the center of the herd. Within large organizations, the phrase used to describe this approach is "industry best practice." Its purpose is to shield the pointy-haired boss from responsibility: if he chooses something that is "industry best practice," and the company loses, he can't be blamed. He didn't choose, the industry did. I believe this term was originally used to describe accounting methods and so on. What it means, roughly, is _don't do anything weird_. And in accounting that's probably a good idea. The terms "cutting-edge" and "accounting" do not sound good together. But when you import this criterion into decisions about technology, you start to get the wrong answers. Technology often _should_ be cutting-edge. In programming languages, as <NAME> has pointed out, what "industry best practice" actually gets you is not the best, but merely the average. When a decision causes you to develop software at a fraction of the rate of more aggressive competitors, "best practice" is a misnomer. So here we have two pieces of information that I think are very valuable. In fact, I know it from my own experience. Number 1, languages vary in power. Number 2, most managers deliberately ignore this. Between them, these two facts are literally a recipe for making money. ITA is an example of this recipe in action. If you want to win in a software business, just take on the hardest problem you can find, use the most powerful language you can get, and wait for your competitors' pointy-haired bosses to revert to the mean. #line(length: 100%) == _Appendix: Power_ As an illustration of what I mean about the relative power of programming languages, consider the following problem. We want to write a function that generates accumulators -- a function that takes a number n, and returns a function that takes another number i and returns n incremented by i. _(That's incremented by, not plus. An accumulator has to accumulate.)_ In _Common Lisp_ this would be ```lisp (defun foo (n) (lambda (i) (incf n i))) ``` and in _Perl 5_, ```perl sub foo { my ($n) = @_; sub {$n += shift} } ``` which has more elements than the Lisp version because you have to extract parameters manually in Perl. In Smalltalk the code is slightly longer than in Lisp ```lisp foo: n |s| s := n. ^[:i| s := s+i. ] ``` because although in general lexical variables work, you can't do an assignment to a parameter, so you have to create a new variable s. In Javascript the example is, again, slightly longer, because Javascript retains the distinction between statements and expressions, so you need explicit return statements to return values: ```javascript function foo(n) { return function (i) { return n += i } } ``` (To be fair, Perl also retains this distinction, but deals with it in typical Perl fashion by letting you omit `returns`.) If you try to translate the Lisp/Perl/Smalltalk/Javascript code into Python you run into some limitations. Because Python doesn't fully support lexical variables, you have to create a data structure to hold the value of n. And although Python does have a function data type, there is no literal representation for one (unless the body is only a single expression) so you need to create a named function to return. This is what you end up with: ```python def foo(n): s = [n] def bar(i): s[0] += i return s[0] return bar ``` Python users might legitimately ask why they can't just write ```python def foo(n): return lambda i: return n += i or even def foo(n): lambda i: n += i ``` and my guess is that they probably will, one day. (But if they don't want to wait for Python to evolve the rest of the way into Lisp, they could always just...) In OO languages, you can, to a limited extent, simulate a closure (a function that refers to variables defined in enclosing scopes) by defining a class with one method and a field to replace each variable from an enclosing scope. This makes the programmer do the kind of code analysis that would be done by the compiler in a language with full support for lexical scope, and it won't work if more than one function refers to the same variable, but it is enough in simple cases like this. Python experts seem to agree that this is the preferred way to solve the problem in Python, writing either ```python def foo(n): class acc: def __init__(self, s): self.s = s def inc(self, i): self.s += i return self.s return acc(n).inc ``` or ```python class foo: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n ``` I include these because I wouldn't want Python advocates to say I was misrepresenting the language, but both seem to me more complex than the first version. You're doing the same thing, setting up a separate place to hold the accumulator; it's just a field in an object instead of the head of a list. And the use of these special, reserved field names, especially `__call__`, seems a bit of a hack. In the rivalry between Perl and Python, the claim of the Python hackers seems to be that that Python is a more elegant alternative to Perl, but what this case shows is that power is the ultimate elegance: the Perl program is simpler (has fewer elements), even if the syntax is a bit uglier. How about other languages? In the other languages mentioned in this talk -- Fortran, C, C++, Java, and Visual Basic -- it is not clear whether you can actually solve this problem. <NAME> says that the following code is about as close as you can get in Java: ```java public interface Inttoint { public int call(int i); } public static Inttoint foo(final int n) { return new Inttoint() { int s = n; public int call(int i) { s = s + i; return s; } }; } ``` This falls short of the spec because it only works for integers. After many email exchanges with Java hackers, I would say that writing a properly polymorphic version that behaves like the preceding examples is somewhere between damned awkward and impossible. If anyone wants to write one I'd be very curious to see it, but I personally have timed out. It's not literally true that you can't solve this problem in other languages, of course. The fact that all these languages are Turing-equivalent means that, strictly speaking, you can write any program in any of them. So how would you do it? In the limit case, by writing a Lisp interpreter in the less powerful language. That sounds like a joke, but it happens so often to varying degrees in large programming projects that there is a name for the phenomenon, Greenspun's Tenth Rule: #quote[Any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp.] If you try to solve a hard problem, the question is not whether you will use a powerful enough language, but whether you will (a) use a powerful language, (b) write a de facto interpreter for one, or (c) yourself become a human compiler for one. We see this already begining to happen in the Python example, where we are in effect simulating the code that a compiler would generate to implement a lexical variable. This practice is not only common, but institutionalized. For example, in the OO world you hear a good deal about "patterns". I wonder if these patterns are not sometimes evidence of case (c), the human compiler, at work. When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I'm using abstractions that aren't powerful enough -- often that I'm generating by hand the expansions of some macro that I need to write. == Notes - The IBM 704 CPU was about the size of a refrigerator, but a lot heavier. The CPU weighed 3150 pounds, and the 4K of RAM was in a separate box weighing another 4000 pounds. The Sub-Zero 690, one of the largest household refrigerators, weighs 656 pounds. - <NAME> also wrote the first (digital) computer game, Spacewar, in 1962. - If you want to trick a pointy-haired boss into letting you write software in Lisp, you could try telling him it's XML. - Here is the accumulator generator in other Lisp dialects: Scheme ```lisp (define (foo n) (lambda (i) (set! n (+ n i)) n)) ``` Goo ```lisp (df foo (n) (op incf n _))) ``` Arc ```lisp (def foo (n) [++ n _]) ``` - <NAME>'s sad tale about "industry best practice" at JPL inspired me to address this generally misapplied phrase. - <NAME> found that 16 of the 23 patterns in Design Patterns were "invisible or simpler" in Lisp. - Thanks to the many people who answered my questions about various languages and/or read drafts of this, including <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. They bear no blame for any opinions expressed. #line(length: 100%) == Response Revenge of the Nerds has generated a lot of additional discussion, which I summarize here for anyone interested in going deeper into the issues raised in it. <NAME> wrote that Lisp is only a win for certain classes of project. His mail was so articulate that I will just include it verbatim: #rect[ I think it would seem more persuasive if you limited the scope of where Lisp is supposed to be better. It probably isn't better, for example, in: - communications, interface, format conversion - real-time control - numerically intensive code - operating system implementation - quick little scripts to munge files The above actually constitute a large fraction of all software written. It is better for information processing: running very complex algorithms across complex data sets. It's only recently, in the WWW age, that people actually do a lot of this. Before the rise of the Web, I think only a very small minority of software contained complex algorithms: sorting is about as complex as it got. Can you think of a complex algorithm in FreeBSD? The 50 million lines of code in a Nortel switch probably didn't even contain a sort. It was all about managing hardware and resources and handling failures gracefully. Cisco routers also have millions of lines of software, but not many complex algorithms. The sort of software that ITA wrote is really very rare. 10 years ago, about the only software with really complex algorithms were CAD design & synthesis, and they did use Lisp. That a shift in what kinds of software is being written makes Lisp resurface as excellent choice is a more believable statement than that the vast majority of programmers have been boneheads for 40 years. ] I agree that Lisp might not be the language to use if you wanted to do something really low level, like move bits around, and processor time was worth more to you than programmer time. For that you'd want C or even assembly language. But I think such applications are rare and getting rarer (see Moore's Law). I know of several places using Lisp for real-time applications, including <NAME>' robot R&D lab. I also agree that Lisp might not be the ideal language to use to write code that works closely with programs written in C, but that isn't Lisp's fault. Nor is C the ideal language to use to write programs that work closely with Lisp. I disagree that Lisp is bad for writing quick little scripts. Its interactive nature makes it especially good for that. I also disagree that it is not believable that the vast majority of programmers have been boneheads for 40 years. It seems to me entirely possible. Measured simply by numbers of users, the current leaders in any field of technology (indeed, almost any field at all) will be mostly mediocre. Look at Windows. Technical innovations regularly take decades to spread. Volkswagen started building cars with unibodies in the 1930s. By the 1980s, practically all new cars were designed that way. Was it simply that the vast majority of car designers were boneheads for 40 years? Yep, though I think "conservative" is the preferred euphemism. #line(length: 100%) <NAME> came up with an additional Python solution: ```python def foo(n): def bar(i): bar.s += i return bar.s bar.s = n return bar ``` but I think Python hackers still consider defining a new class to be the canonical solution. #line(length: 100%) Several Python users have written to tell me that the reason you can't write the Lisp/Perl/Smalltalk/Javascript program in Python is that lexical variables in Python aren't mutable, and that "anonymous functions" can only contain a single expression. When I ask why you can't just write ```python def foo(n): lambda i: n += i ``` in Python, I'm not asking what it is in the current definition of Python that prevents this. I know that Python currently imposes these restrictions. What I'm asking is what these restrictions buy you. How does it make Python a better language if you can't change the value of a variable from an outer scope, or put more than one expression in a lambda? What does it buy you to distinguish between expressions and statements? The restriction on what you can say in an anonymous function seems particularly indefensible. In fact, the whole phrase "anonymous function" suggests limited thinking. Would you call a hash table that wasn't the value of a variable an "anonymous hash table?" If functions are a data type in your language, they should be treated just like other data types. A named function should just be a function that happens to be the value of a variable. Restricting what you can put in a function that isn't the value of a variable makes about as much sense as restricting what you can do with a hash table or string that isn't the value of a variable. #line(length: 100%) <NAME> wrote to stress that languages had to be suitable for ordinary programmers, not just super-hackers: #quote(attribution: [<NAME>])[I believe you are thinking of an excellent hacker whose code gets read once in a while by fellow excellent hackers who marvel at his fine algorithms and coding style. They are interested to learn new things and eager to understand everything for the pure pleasure of the intellectual challenge. Unfortunately, that's not the world I (and a lot of other people) live in. My co-workers ... want to get along with my code with minimal effort. So the power of a language becomes related to what an average IT professional can easily digest, which in turn is something that is commonly taught at university courses, explained in easily available books and discussed in popular articles. It boils down to mainstream knowledge about programming, languages, algorithms and patterns. To a degree, you simply have to go with the crowd. Again Python: It implements mainstream concepts in a succinct and elegant way. So, maybe we are back at the point where we need a "powerful" language for the power users, the hackers. And a "powerful" (in a different sense) language for everyday people in everyday companies.] I agree that there is a role for languages designed for novice and less-motivated programmers. The only thing I disagree about is whether "powerful" is the word to use to describe this quality. I think there is already a word for this proposed second sense of "powerful", and it is "accessible." A Ferrari is powerful. A VW Golf is accessible. Why stretch the language to find some metaphorical sense in which you can call the Golf powerful, when there is already a word for the quality you mean? Plus, if you blur the word "powerful" by using it too broadly, you no longer have a name for the very definite quality possessed by the Ferrari. I think it is important that some of us, at least, keep our focus on power in the Ferrari sense. Someone has to, because that is the source of the next generation of "mainstream knowledge". In 1980, university courses and easily available books were advanced if they talked about structured programming. Now they talk about topics like garbage collection and dynamic typing, which would in 1980 have been considered esoteric stuff. #line(length: 100%) <NAME> wrote that I chose an example that was deliberately Lisp-biased. If I had wanted to do that I would have written a macro, not a function. If the example I chose is biased, it is Lisp/Perl/Smalltalk/Javascript biased, because the code is similarly simple in all four (and many others). I was actually surprised at how badly Python did. I had never realized, for example, that a Python lambda-expression couldn't contain the same things as a named function, or that variables from enclosing scopes are visible but not modifiable. Neither Lisp nor Perl nor Smalltalk nor Javascript impose either restriction. I can't see what advantage either restriction brings you. I _can_ see how Python's gradual, ongoing (= incomplete) evolution would have produced them. So Occam's Razor implies that the latter is the reason Python is this way. I.e. these restrictions are bugs, not features. #line(length: 100%) == Accumulator Generator Revenge of the Nerds yielded a collection of canonical solutions to the same problem in a number of languages. The problem: _Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i_. *Note*: + that's number, not integer, + that's incremented by, not plus. C++ ```cpp template<typename T> struct Acc { Acc(T n) : n(n) {} template<typename U> Acc(const Acc<U>& u) : n(u.n) {} template<typename U> T operator()(U i) { return n += i; } T n; }; ``` Dylan ```dylan define function foo (n) method (i) n := n + i end; end function; ``` E ```e def foo (var n) :any { def inc (i) :any { n += i } } ``` Erlang ```erlang foop(N)-> receive {P,I}-> S =N+I, P!S, foop(S) end. foo(N)-> P = spawn(foo,foop,[N]), fun(I)-> P!{self(),I}, receive V->V end end. ``` Haskell ```haskell import IOExts foo n = do r <- newIORef n return (\i -> do modifyIORef r (+i) readIORef r ) ``` JavaScript ```javascript function foo (n) { return function (i) { return n += i } } ``` Lisp Arc ```lisp (def foo (n) [++ n _]) ``` Lisp: Common Lisp ```lisp (defun foo (n) (lambda (i) (incf n i))) ``` Lisp: Goo ```lisp (df foo (n) (op incf n _)) ``` Lisp: Scheme ```lisp (define (foo n) (lambda (i) (set! n (+ n i)) n)) ``` Lua ```lua function foo(n) return function (i) n = n + i return n end end ``` Maple ```maple foo := proc(n) local s; s := n; proc(i) s := s + i end end ``` Mathematica ```mathematica foo = Module[{s=#},s+=# &] & ``` Mozart ```mozart fun {Foo N} A = {NewCell N} in fun {$ B} C D in {Exchange A C D} if {IsInt C} andthen {IsFloat B} then D = {IntToFloat C}+B elseif {IsFloat C} andthen {IsInt B} then D = C+{IntToFloat B} else D = C+B end {Access A} end end ``` NewtonScript ```newtonscript foo := func (n) func (i) n := n + i ; ``` Perl 5 ```perl5 sub foo { my ($n) = @_; sub {$n += shift} } ``` Python ```python class foo: def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n ``` Rebol ```rebol foo: func [ n ] [ func [ i ] [ n: n + i ] ] ``` Ruby ```ruby def foo (n) lambda {|i| n += i } end ``` Smalltalk ```smalltalk foo: n |s| s := n. ^[:i| s := s + i. ] ``` VBScript ```vbscript Class acc Private n Public Default Function inc(i) n = n + i inc = n End Function End Class Function foo(n) Dim bar Set bar = New acc bar(n) Set foo = bar End Function ``` Some languages are not represented here, either because you can't write this program in them (short of Greenspun's Tenth Rule) or because no one has yet sent me the code for that language.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/046%20-%20Streets%20of%20New%20Capenna/001_Episode%201%3A%20Homecoming.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: Homecoming", set_name: "Streets of New Capenna", story_date: datetime(day: 28, month: 03, year: 2022), author: "<NAME>", doc ) = TEMPLE OF THE GODS Victory and betrayal tasted the same—like blood. It filled Elspeth's mouth, spilling out the edges with her shock. She gripped the familiar spear as if she could take it from Heliod's grasp and free herself from its blade. But strength was leaving her fingers faster than life was leaving her body. Ajani roared at a distance, too far to get to them. But what would he do if he could? They were both wounded and weary from the battle with Xenagos, and even if they had not been, there was little point now. Her life had been forfeited from the moment she had made a deal with Erebos, God of the Dead and Heliod's sworn enemy, to bring back her lost love, Daxos. She had already bartered her life. Heliod was merely helping the process along and cementing his vengeance for all her transgressions. "Carry her back to the mortal realm, leonin. Deliver her to Erebos," the god commanded Ajani. With a twist, Heliod withdrew Godsend—the weapon she had found originally as a sword from the heavens and that Heliod had transformed into a spear and made her responsibility, her burden. Without its support, Elspeth collapsed, her knees meeting the hard stone of the Temple of the Gods. She felt the full weight of her mortality, crushing her as her body slowly succumbed to her injuries. "If she dies here, she will disperse to nothingness." Heliod's eyes narrowed, their divine glow dimming with his disdain. Elspeth fought for words. But there were none to be found. She and Ajani had fought their way to Nyx to slay Xenagos and right the wrongs she had caused. They had won. But her victory did not undo her transgressions and had only hardened Heliod's cold displeasure. He had resented her for the mysteries of her powers, for her deals, for slaying a god. Heliod had no warmth for her now. "Elspeth!" Ajani's usual grace gave way to scrambling and jerky movements as he rushed toward her. She pressed her hand against the mortal wound at her middle, as hopeless as it was. Instinct, really. "Ajani," she whispered, trying to lift her head. But it was too heavy. Her body was turning to lead. His arms wrapped around her. The world spun as Ajani carried her through a portal out of the land of the divine and back onto the mortal plane of Theros. Her friend set her down gingerly. "Hang on," Ajani urged, grabbing her hand. "I'm going to find help." Elspeth blinked; each time was slower than the last. Ajani was there and then he wasn't. Her sight was growing hazy, oscillating between blurry and painfully crisp. His absence became more painful by the second. Cold. Come back. She didn't want to die alone, but she no longer had the strength to even call out. Distant cries washed over her. Was a great battle taking place? Or were these echoes of their struggle against Xenagos rattling around her final thoughts? None of it mattered now. Her days of battle were slipping away, pooling beneath her. With the last of her strength, Elspeth turned her gaze skyward. What she was looking for, she didn't know. Maybe she was looking for nothing. A spot of darkness between the stars to focus on. Quiet. Peace. A soft exhale slipped through her lips. She had spent so long searching for a place to rest, to simply be; perhaps death was how she would finally find it. The last thing she saw was a flash of light, cleaving the heavens in two. = MAESTRO'S MUSEUM Sumptuous disorder: both an aesthetic and a way of life in New Capenna. The impossible city indulged itself on strong, gilded lines that soared upward and broke apart into delicate ironwork. The decorations mirrored the waterscapes and fauna of the terraced gardens that were the signatures of Park Heights. If Xander could capture it in the stroke of a brush or pen, he would. But alas, his talents had never lain in the making of landscapes on canvas. #figure(image("001_Episode 1: Homecoming/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) And yet, the town knew his mark as well as those of the most famous creators. He'd painted it in blood enough times. Xander stroked his beard, a slight smirk curling his lips. Those had been fun days, indeed. The days of a younger man, a man whom he had enough distance from now to notice lacked a little~finesse. Editing, as it were. How he wished he could go back and repeat some of those early assassinations. To do them better. If he had the hard-earned skill and control that he possessed now with the body he had then—free of all its old, aching wounds and present ailments—New Capenna would know true fear. But time continued its march, dragging him and New Capenna along with it. The city he'd once prowled was vanishing before his eyes and these days he much preferred the company of canvas and sculpture over blade and mark. It was a wonder, really, that the city still stood. It rose from vast emptiness and long-abandoned townships, a testament to the might—or hubris perhaps—of its long-forgotten founders. The barrier those builders had left behind remained, a last bastion of hope against a great, now forgotten evil. But the danger that New Capenna now faced was not an external threat, but a rot festering within. The fragile alliances that fostered peace between the five families that ruled the city were being strained to a breaking point from which there would likely be no return. Some relationships, once broken, could never be repaired. All Xander could do now was ensure that he and his family were on the side of the victors at the end of it all. A knock on the door interrupted the thoughts he'd been worrying over all evening. Xander drew a pocket watch and checked the time. A few minutes late. Permissible. "Enter." "My apologies," Anhelo said with a bow of his head. He continued without lifting his face; it made him look almost small underneath the chandeliers and overwhelming opulence of the room. "Matters took a little longer than expected to resolve." Concern weighed down his words. "You weren't delayed. You were giving me time to appreciate the new landscaping across the way." Xander motioned to the window. Workers had been out in the terraced gardens he so admired all day, changing flowers like hemlines. The greenery was breathtaking to behold, stitched together with unnatural streams and waterfalls, cascaded down the side of the building opposite the museum. "Even still, it's not—" "It was no trouble," Xander said with a firmer edge at the end of the statement. He did not need Anhelo's prostrations or verbal fumbling. All Xander required of his Deacon was loyalty. Unconditional, unabashed, unyielding loyalty. And that he already held in spades. "Now, stand here, I need to make some modifications to your ensemble before your next assignment." Anhelo crossed the room to a low pedestal, stepping up. Xander did the same, ignoring the cane propped against his desk. The old injuries didn't ache as badly today, which was fortunate since he needed both hands to take Anhelo's measurements. "How is the Mezzio today?" The ribbon slipped between Xander's fingers, still nimble after all this time, as he confirmed the last of the numbers. "How did you know I was in the Mezzio?" Anhelo seemed more amused than disturbed. "What don't I know?" In truth, it was the smell. The oils of the shoeshiners combined with the aromas of the open markets, the incense of the fortune tellers layered atop, and the undernotes of sweat from the dance halls; it was a unique perfume that stuck to clothes and was distinctly the Mezzio. It clung to people as though it were a calling card sent to lure them back to the city's center, whispering sweetly of danger and decadence. Anhelo's mouth tugged up on one side, a trademark smirk that revealed one of his vampiric fangs. "And that is why you run this town." Xander chuckled, setting down his tape and running his fingers over the assortment of pauldrons he'd selected from his collection. Anhelo's attire had been lacking for a few weeks now, and that simply would not do. Moreover, he needed some changes if he was to blend in properly with the rabble of lower levels. #figure(image("001_Episode 1: Homecoming/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Every level of New Capenna held its own~charms, from the lowest rungs of the utilitarian Caldaia, reimagined in its ghastly fashion by Ziatora and her Riveteers, to the bustling midtown of the Mezzio steeped in the crime and opportunity the Cabaretti promised. Xander's favorite level was, by far, his museum in the heavenly expanses of Park Heights. Which was one of the many reasons why he rarely left and Anhelo always came to him. #figure(image("001_Episode 1: Homecoming/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "If only I ran this town," Xander mused, finally settling on an adornment for the shoulder that would clip into a high collar of steel. It was closer to the chin than Anhelo usually preferred. But the Deacon wore his shirts open far too low in Xander's opinion, and when it came to fashion, there were none with a better eye than Xander. "Something is weighing on you." Anhelo kept his eyes forward as Xander settled the pauldron on his shoulder, testing the fit. "Many somethings." "May I ask what they are?" Anhelo's pale eyes searched his face. Expectant, but not demanding. "Where to begin?" Xander had returned to the table, pauldron back in its place among the lineup. He now examined daggers, poison rings, rings that also functioned as brass knuckles, and his personal favorite, silencing cuffs that reduced the sound and flash of magic to almost nothing, the perfect tool for an assassin. "This, I suppose," Xander chose both a cuff and a thought. "The balance of power in this town is shifting." "I've heard the whispers—the Adversary, they call him." "I am less concerned about a shadowy upstart than I am the supply of Halo. The Adversary is a brute and a symptom. Not the problem." Halo—the magical substance that had been sustaining power and life within New Capenna for years—had a dwindling source. Desperation for power made men clumsy and brash. And there was no greater power than Halo. If it were to ever run out, it would surely spell anarchy for New Capenna. "The Adversary is gaining a foothold in the city. He's more than just an upstart." Xander knew all too well the foothold the Adversary was gaining. The man had been slowly siphoning from the Maestro's ranks, promising them a steady supply of Halo in return. Xander hardly minded seeing the disloyal weeded out from under him. But where this Adversary was acquiring the magical substance was a greater mystery. One Xander was determined to solve. "Perhaps so," Xander relented as he clipped the cuff around Anhelo's wrist. "But the Adversary would not gain that power without steady access to Halo." "Do you think he's in league with the Cabaretti? They've been amassing their stockpiles." Anhelo curled and uncurled his fingers, no doubt testing his magic against the bracer. "The Cabaretti demands are high in preparation for their Crescendo. If the Adversary had access to Halo and was working for them, the Cabaretti would have already consumed his supply." Anhelo considered this, and in his silence, Xander continued, "What I am most concerned about, regarding the Cabaretti, is this rumor of their 'new supply' that they plan to unveil during the Crescendo celebrations. That is what I'm going to need you to focus on—gather the information on what this source is by whatever means necessary." "Spying? Sounds like a job for the Obscura, no?" The family Obscura specialized in illusions, distractions, and manipulations. It was a natural inquiry and came off as curious, rather than accusatory, so Xander allowed the affront to his station slide. Very few in the Maestros possessed the rapport with him to inquire so boldly. "For matters involving Halo, I prefer to keep things in house and with the man I trust above all others. No one will know of this task but you." Anhelo's smirk fell. He knew something deeper was amiss, of that Xander could be sure. Anhelo was his right hand, his Deacon, and he hadn't achieved that rank with obliviousness. "There is more you're not telling me." "Isn't there always?" Xander returned to the table of assorted tools, ready to step away from the conversation. For all he trusted Anhelo, information was like Halo itself—just a taste made a man strong and too much made him reckless. "I think this is just the thing to round out your ensemble." He handed Anhelo a ring. "What does it do?" "Look terribly fashionable." Anhelo chuckled alongside him. But Xander's tone quickly became serious once more. "We must stay one step ahead. The powers of New Capenna are shifting, and if we're not careful, our position will slip out from underneath our feet. The Maestros have held onto our influence for far too long to let it go now." "I will not let you down." "See that you don't." Xander stepped aside as Anhelo stepped down from the pedestal. His final outfit was not what Xander would generally approve of, but it was what the Mezzio expected—practical while maintaining just enough flair. Effortlessly fashion-forward. "I hear that the Cabaretti have been relentless in the Mezzio in search of Halo. Return there and see what you can find." Anhelo departed, and rather than returning to his window, Xander headed to the far corner of the room. Behind a curtain was a locked door to which there was only one key, and it was perpetually within a hidden pocket on his person. The small storeroom was cramped with all manner of ancient relics. Statues of winged angels were locked in stony prayer, guarding the texts Xander had killed to collect and protect. These were the last remaining histories of the founding of New Capenna, a time he should remember but that had become murky following his deal. Xander lifted two cotton gloves, donning them before leafing through the first text. He had read these words many times but had yet to give up hope that somewhere in the annals of the past, he just might find the key to their future. #figure(image("001_Episode 1: Homecoming/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) = OFFICE OF GRANDFATHER CABARETTI A lively tune soared to the upper archways of the Vantoleone. The warmth of the brass horns wove together with the trellised flowers that hung like chandeliers. Jinnie's foot tapped lightly against the carpet of Jetmir's office, in time with the thrumming beat and the thumping of patrons' feet as they swung across the dance floor below. "Go and join them." Jetmir chuckled and leaned back in his chair. "These matters can wait. There's a party." "There is always a party." Jinnie grinned and lightly stroked the cat curled in her lap. "But there is only one Crescendo, and I want to ensure that everything is absolutely perfect for it." "There will be another Crescendo next year," he countered playfully. "Assuming the plane doesn't come to its end between now and then and there are still new years to celebrate." Jinnie fought a roll of her eyes. Jetmir always knew just what buttons of hers to push and how to tease. But that was what fathers were supposed to do, even the adoptive kind. "You know what I mean." From where she sat on the opposite side of Jetmir's desk, she could only see the glass ceiling of the Vantoleone and the mirrored figures shining against it. Tonight was a decent celebration, as good as any by Cabaretti standards. But Jinnie wanted everything for the Crescendo to go off without a hitch. It was her foremost priority. "I've received replies from almost every family, save for the Maestros." "And the Adversary." Jinnie waved the notion away, causing the feline in her lap to give her a very offended look. She quickly returned to scratching Muri between her ears. "The Adversary isn't worth inviting. Doing so would be a show of respect he doesn't deserve." "It's sometimes better to show respect before it's due. You never know how a small friend now might become a big ally later." "You actually think he might form a new family?" she asked, incredulous. "I think anything is possible in New Capenna." Jetmir's tone sucked the levity from the air and demanded Jinnie's attention. She had known him for a long time—well before he was the wealthy head of the Cabaretti, and long enough to know when a matter demanded her focus. "He's beginning to amass power, attracting loyalists with promises of riches and Halo." "Those who would betray their existing families because they think having some Halo gives license to start their own are not worth the blood in their veins." Her words were venomous, lacking an ounce of compassion. The only thing traitors were good for was being turned into examples for other would-be turncoats. "I don't disagree." "Besides, the moment the Font is revealed, everything in New Capenna will change and the Cabaretti will be on top." Merely saying so aloud sent a tingle down her spine. The plane was about to undergo a fundamental shift, and she, as someone who'd grown up strong and influential despite neglect and abandonment, would be at its center. "How is the Font?" Jetmir steepled his fingers, claws lightly tapping. The light glinted off his signet ring, one Jinnie had kissed many times. "In hand. No issues," Jinnie was pleased to report. "Everything is just as we would hope, and no one is aware of the Font beyond the inner council of the Cabaretti." "Then the Crescendo will be a celebration for the ages." Jetmir tilted back his head and let out a roar of laughter. He was usually in a good mood. As the grandfather of the Cabaretti, he had every reason to be. Jetmir had ensured the world around him was a celebration, filled with food and drink and dancing. It had never been hard for Jinnie to swear her life to him. "Without doubt." "Now, you should go and rejoin the evening's festivities. We'll discuss the other details later. You're far too lovely to be cooped up in this office all evening." "I could say the same for you." Jinnie leaned down, grabbing her purse. It bore the same crest as Jetmir's ring and the heavy gold bands he wore as ornamentation on his two crescent-shaped horns. Muri hopped from her lap and into the bag. Her other familiar, a dog named Regis, raised his muzzle from his mighty paws and regarded her inquisitively. She stood, and the beast mirrored her movements. Jinnie rounded the desk that was between her and Jetmir, settling her hand on the cashmere scarf around his neck as she leaned forward to kiss his cheek lightly. "I am not lovely. I am an old man." "You are not that old!" She slapped his shoulder playfully. "And everyone knows that you are still the life of every party. It's why everyone wants to be a Cabaretti." "They only think that because I bankroll those parties." Jetmir smirked. She could tell he was jesting. The Cabaretti were the beating heart of the city. They were joy. They were life. They were rhythm and music and sound and color. And soon they would be the ones responsible for giving New Capenna the Font and all the Halo the people could ever dream of. "That is not true, and you know it." She returned to her chair, slinging a bejeweled shawl over her shoulders. Its gossamer threads glistened in the light, looking as though she was wrapped in a spiderweb made of diamonds. "But you're right, I should return. I don't want to leave Kitt or Giada for too long." "Give them my best." Jetmir pushed away from his desk, situating his own sash around his shoulders and taking up his scepter. At its top was the face of a crowned leonin—the symbol of the Cabaretti. #figure(image("001_Episode 1: Homecoming/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Always." Jinnie flashed him a dazzling smile and stepped out the door. Jetmir's office was upstairs from the main hall of the Vantoleone. Viridian curtains imprinted with golden flowers and shapes reminiscent of the peacock feathers that lined the hem of her dress muffled the music below. But the sounds returned in full as Jinnie emerged into the entry that led to the dance floor. Two women lounged on a nearby settee, right where Jinnie had left them. Kitt's furred ears twitched, spinning in Jinnie's direction before her head did. Kitt knew her by footsteps alone. "And how do the preparations for the Crescendo go?" A mere question from Kitt had a lyrical nature to it, as if her voice was always one short breath away from song. "Swimmingly." "Will I have my solo?" Kitt's mouth curled in a grin. "Toots, was there ever any doubt?" Jinnie's attention settled on the teenager next to her dear friend. "And you, Giada, are you excited?" The young woman forced a smile that didn't reach her longing eyes; the almost tortured expression was always odd to Jinnie. Giada wanted for nothing, Jetmir offered her sustenance, shelter, and luxuries. The air around her was filled with the finest perfumes. Her nails were perpetually manicured. Jinnie was always present to ensure no one would ever lay a finger on Giada's short dark hair—currently pinned up with rare feathers. She had everything she could possibly wish for, apart from her leave. "I am," she said. Though the words lacked sincerity. Jinnie knelt before her, scooping up Giada's hands. "Good, because in no time at all, we're going to change the plane." = DEPTHS OF THE CALDAIA <NAME> was on the hunt. Not for prey, but for something that might not exist. For a balance that could finally put to rest the ghosts of Skalla that haunted her every step. She searched for a place—a people—where the constructed and natural worlds were in harmony. But she was quickly learning that New Capenna was likely not that place. Beyond this city was a plane devoid of nature and life, fallen to ruin. Within its walls was a synthetic metropolis of steel. A temple to industry. The motifs found within the architecture were natural enough. Vivien could pick out the shapes of palms in fanned windows; metal had been hammered and polished to be reminiscent of waterfalls. But when there was actual greenery, it was encapsulated in concrete and iron, carefully sculpted and plucked to resemble the zig-zagging patterns found in many of the citizenry's clothing. Nature might exist here, but it wasn't real. This plane was out of alignment, dissonant, and weighted at each pole of synthetic and natural, and she didn't give New Capenna long before it split at the seams. That was always the way of it when the scales tipped too far in one direction. She had entered the city in a central location by way of one of the many trains and headed down from there, away from the soaring spires and sculpted reliefs of angels that looked down upon the city with their vacant eyes. Instead, Vivien had plunged herself into the reddish haze of the lower levels, searching for some long-lost connection to the earth below, hidden deep underneath the smoke and grime. Forgotten roots, but enduring, nevertheless. The well-paved walkways above had given way to suspended streets of steel. Vivien traversed girders with feet as confident as the citizenry. The locals seemed to have no problem scrambling from beam to beam—leaping across sections of open air with only a careful step separating them and certain death. The city above this underbelly was supported by columns shaved into impossible points, balancing on the tips of pyramids beneath. She had seen many impressive places in her travels. But this was certainly a marvel unto itself~so long as she was willing to look past its grave errors in rejecting nature so completely. #figure(image("001_Episode 1: Homecoming/06.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) A raucous uproar erupted from the open doors of a nearby building. Abandoning her initial curiosity—an anvil surrounded by flames on a nearby platform—Vivien leapt from the girder she had been crossing onto one lower that connected to the doors. The light of the room within struck clean lines through the smoke and fog. Vivien slipped inside, her smooth movements going mostly unnoticed. Those who did see her paid no mind. They were too engrossed in the speech. "—are not to take orders from the people sitting in the estates that we built, sipping the Halo that comes from our stores," a voice thundered over the assembled crowd, mostly composed of people in workers' clothing. The source of the declarations was a mighty dragon, perched high above them all. Judging from how the crowd hung on her every word, the dragon was clearly a skilled orator. "The Cabaretti demand too much for this Crescendo without spreading its benefits. The Brokers impose themselves on our streets. And I have no doubt that the Obscura are lurking among us right now, eager to report back to the highest bidders like the lapdogs they are." The masses cheered agreements. Some grumbled grievances alongside the dragon. A curl of smoke escaped her nostrils before she continued, "They would do well to remember not to step on the hands building their cabarets and lounges. A few weak bolts and old beams can make such untimely accidents." "You're not from here." A man bundled in heavy coats, gloves, boots, and a wide-brimmed hat approached, disrupting Vivien's focus. "Neither are you," she appraised. He was nothing like the other workers of the hall and their practical garb. He chuckled. "I am, at least, not wearing clothes from another plane." Vivien straightened away from the wall she'd been leaning on. The stranger's eyes were bright and shining underneath the shade of his hat. Something in the air around him, in the way he held himself, made her skin pucker into gooseflesh. He was different. And while they couldn't be less alike, they shared one distinct kinship. He was also a planeswalker. "Ah, so you see it now, too. Come, let's share a word before the rabble is released from Ziatora's thrall." The man left through the same doors she'd just entered, not looking back once, trusting her to follow. Vivien glanced between him and the dragon, still giving her speech. Between the two, he held more interest in Vivien. "I hadn't been looking for another planeswalker tonight~but you're a far better find than what I came in search of." He stood at the edge of a girder, looking out over the smoke and steel. "How long have you been here?" "Long enough." The noise of the hall faded away as she approached. He began to walk once more, staying one step ahead. Vivien let him lead, one hand ready to reach for her bow in an instant. She didn't come here looking for a fight, but she'd end anyone brazen enough to bring one to her. "Long enough to know there are others here like us?" "Others?" More planeswalkers? Why? She had come here for personal reasons, but it now looked like she had stepped into something deeper than expected. "How much do you know about Halo?" "Little." She had heard it mentioned among the citizenry and surmised it had something to do with the iridescent substance that filled the flutes of the revelers she passed. But Vivien hadn't had enough time to learn more than that. "This plane thrives on it, and it holds immeasurable power. The man I'm currently working for is in the process of acquiring it. But his real goals lie elsewhere." "Which is?" "Curious?" He glanced over his shoulder with a smirk. The sound of metal clanking softly followed his every movement. "Perhaps." Vivien wasn't yet sure if she trusted him or not, but she didn't need trust to glean more information from him. "Good, come along then. Urabrask will be eager to meet you." She didn't move this time when he began walking. "And what is your name?" He paused, then spoke without looking back. "Tezzeret, and I have people waiting for me, so if you could hurry along." Vivien did not hurry. She did not move at all. While she had never met him before, she had certainly heard the name Tezzeret. They'd fought on opposite sides during the War of the Spark, and she always had a sneaking suspicion he had access to the Planar Bridge. Tezzeret wasn't someone to be underestimated. If he was here, then there were deeper currents, indeed. "Well?" He stopped when he realized she wasn't following. "Let's get one thing straight~" Vivien hid her concerns and suspicions behind a mask of determination and crossed the gap between her and Tezzeret in a few long strides. Now, she walked at his side. It was tight on the girder. But she didn't cede any space to him. "You are not one to order me around." Tezzeret huffed in amusement. "Understood." "So, who is Urabrask?" she asked. A friend of Tezzeret would put her even more on guard. "It's complicated." Tezzeret's eyes were distant. He focused on a point somewhere beyond what Vivien could see. She knew that look all too well; it was the look of a man who had stepped between the veil of planes and witnessed all the horrors that were often found between. "It will make more sense once you've met him. But for now, all you need to know is that he is on our side." "And what side is that?" "The side of freedom." = MEZZIO TRAIN STOP Elspeth startled at the transport that whizzed overhead, rattling on suspended tracks that hung a little too low for something so noisy. She blinked several times, eyes still adjusting to the bright lights of New Capenna as compared to the dim train. The city was teeming with people of every shape and size, wearing all manner of strange clothing. #figure(image("001_Episode 1: Homecoming/07.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Buildings towered above her, connected by a maze of rails and walkways, decorated with balconies and ornate designs that spoke of nothing but indulgence. Every ceiling seemed to be another's floor as the city continued to stretch higher and higher, reaching dizzying heights before plunging into the low cloud cover. She adjusted the pack on her shoulder. It contained what meager possessions she could think to bring when she'd planeswalked to this plane. What little she still had to her name after everything she'd been through. Elspeth swallowed the initial sense of disappointment that the city wasn't what she'd been expecting. What expectations could she reasonably carry? None. It was unfair to have preconceived notions while searching for a place that she had long stopped believing existed. "Home," Elspeth murmured, seeing if the word fit New Capenna when said aloud. It was no better. "Ajani said this was it." Her friend had never lied to her and had always given sound council, even when she didn't want to hear it. She had every reason to trust him. If he said this was her home, then surely it must be. She had been searching, dreaming, and longing for this moment for years~ So why had she never felt more out of place? #figure(image("001_Episode 1: Homecoming/08.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #grid( columns: (1fr, 1fr), gutter: 2em, figure(image("001_Episode 1: Homecoming/09.png", height: 40%), caption: [], supplement: none, numbering: none), figure(image("001_Episode 1: Homecoming/10.png", height: 40%), caption: [], supplement: none, numbering: none), )
https://github.com/RolfBremer/in-dexter
https://raw.githubusercontent.com/RolfBremer/in-dexter/main/sample-usage.typ
typst
Apache License 2.0
#import "./in-dexter.typ": * // This typst file demonstrates the usage of the in-dexter package. #set text(lang: "en", font: "Arial", size: 10pt) #set heading(numbering: "1.1") #set page( numbering: "1", footer: align(right)[#context { counter(page).display("1") }], ) // Defining handy names for separate indexes to use with in-dexter in // this document. this is easier as having to type the index parameter // on each entry. #let index2 = index.with(index: "Secondary") #let index3 = index.with(index: "Tertiary") #let indexMath = index.with(index: "Math") // Front Matter #align(center)[ #text(size: 23pt)[in-dexter] #linebreak() #v(1em) #text(size: 16pt)[An index package for Typst] #linebreak() #v(.5em) #text(size: 12pt)[Version 0.6.1 (9.10.2024)] #linebreak() #v(.5em) #text(size: 10pt)[<NAME>, <NAME>] #linebreak() #v(.5em) #text(size: 10pt)[Contributors: \@epsilonhalbe, \@jewelpit, \@sbatial, \@lukasjuhrich, \@ThePuzzlemaker, \@hurzl] #v(4em) ] // Table of Content #outline(indent: true, title: [Content]) = Sample Document to Demonstrate the in-dexter package This document explains how to use the `ìn-dexter` package in typst. It contains several samples of how to use `in-dexter` to effectively index a document. Make sure to look up the typst code of this document to explore, what the package can do. Using the in-dexter package in a typst document consists of some simple steps: + Importing the package `in-dexter`. + Marking the words or phrases to include in an index. + Generating the index page(s) by calling the `make-index()` function. == Importing the Package The in-dexter package is currently available on GitHub in its home repository (https://github.com/RolfBremer/in-dexter). It is still in development and may have breaking changes #index[Breaking Changes] in its next iteration. #index[Iteration]#index[Development] ```typ #import "./in-dexter.typ": * ``` The package is also available via Typst's build-in Package Manager: ```typ #import "@preview/in-dexter:0.6.1": * ``` Note, that the version number of the typst package has to be adapted to get the wanted version. It may take some time for a new version to appear in the typst universe after it is available on GitHub. == Marking of Entries // This marks the start of the range for the Entry-Key "Entries" #index(indexType: indexTypes.Start)[Entries] // This marks the start of the range for the Entry-Key "Entriy-Marker" #index(indexType: indexTypes.Start)[Entry-Marker] We have marked several words to be included in an index page. The markup for the entry stays invisible#index[Invisible]. Its location in the text gets recorded, and later it is shown as a page reference in the index page.#index([Index Page]) ```typ #index[The Entry Phrase] ``` or ```typ #index([The Entry Phrase]) ``` or ```typ #index("The Entry Phrase") ``` Entries marked this way are going to the "Default" Index. If only one index is needed, this is the only way needed to mark entries. In-dexter can support multiple Indexes #index[Multiple Indexes]. To specify the target index for a marking, the index must be addressed. ```typ #index(index: "Secondary")[The Entry Phrase] ``` This is the explicit addressing of the secondary index. It may be useful to define a function for the alternate index, to avoid the explicitness: ```typ #let index2 = index.with(index:"Secondary") #index2[One Entry Phrase] #index2[Another Entry Phrase] ``` === Nested entries Entries can be nested. The `index` function takes multiple arguments - one for each nesting level. ```typ #index("Sample", "medical", "tissue") #index("Sample", "musical", "piano") #index("Sample") ``` #index("Sample", "medical", "tissue") #index("Sample", "musical", "piano") #index("Sample") ==== LaTeX Style index grouping Alternatively or complementing to the grouping syntax above, the "bang style" syntax known from LaTeX can be used: // TODO: Make nice samples ```typ #index("Sample!medical!X-Ray") ``` #index("Sample!medical!X-Ray") They can even be combined: ```typ #index("CombiGroup", "Sample!musical!Chess!") ``` #index("CombiGroup", "Sample!musical!Chess!") Note that the last bang is not handled as a separator, but is part of the entry. To use the bang grouping syntax, the `make-index()` function must be called with the parameter `use-bang-grouping: true`: ```typ #make-index(use-bang-grouping: true) ``` === Entries with display These entries use an explicit display parameter. It is used to display the entry on the index page. It can contain rich content, like math expressions: ```typ #index(display: "Level3", "Aaa-set3!l2!l3") #indexMath(display: [$cal(T)_n$-set], "Aa-set") #indexMath(display: [$cal(T)^n$-set], "Aa-set4") ``` #index(display: "Level3", "Aaa-set3!l2!l3") #indexMath(display: [$cal(T)_n$-set], "Aa-set") #indexMath(display: [$cal(T)^n$-set], "Aa-set4") Note that display may be ignored, if entries with the same entry key are defined beforehand. The first occurance of an entry defines the display of all other entries with that entry key. === Advanced entries Simple math expressions can be used as entry key, like the following sample, where we also provide an initial parameter to put sort the entry unter "t" in the index: ```typ #indexMath(initial: "t")[$t$-tuple] ``` #indexMath(initial: "t")[$t$-tuple] but note, that more complex ones may not be convertible to a string by in-dexter. In such cases it is recommended to use the display parameter instead: ```typ #indexMath(initial: "t", display: [$cal(T)_n$-c], "Tnc") ``` #indexMath(initial: "t", display: [$cal(T)_n$-c], "Tnc") this will put the entry in the "t" section, and uses the key ("Tnc") as sort key within that 't' section. The entry is displayed as `$cal(T)_n$`. The following entry will place the entry in the "D" section, because we have not provided an explicit `initial` parameter, so the section is derived from the keys first letter ("DTN"). ```typ #indexMath(display: [d-$cal(T)_n$], "DTN") ``` #index(display: [d-$cal(T)_n$], "DTN") The index-function to mark entries also accepts a tuple value: ```typ #indexMath(([d-$rho_x$], "RTX")) ``` #indexMath(([d-$rho_x$], "RTX")) The first value of the tuple is interpreted as the `display`, the second as the `key` parameter. // More samples and tests #indexMath(([d-$phi_x^2*sum(d)$], "DPX")) #index(indexType: indexTypes.End)[Entry-Marker] ==== Suppressing the casing for formulas Sometimes, the entry-casing of the `make-index()` function should not apply to an entry. This is often the case for math formulas. The `index()` function therefore has a parameter `apply-casing`, that allows to suppress the application of the entry-casing function for this specific entry. ```typ #index(display: $(n, k)"-representable"$, "nkrepresentable", apply-casing: false) ``` #index(display: $(n, k)"-representable"$, "nkrepresentable", apply-casing: false) Note: If multiple entries have the same key, but different apply-casing flags, the first one wins. ```typ #index(display: $(x, p)"-double"$, "xprepresentable", apply-casing: false) #index(display: $(x, p)"-double"$, "xprepresentable", apply-casing: true) ``` #index(display: $(x, p)"-double"$, "xprepresentable", apply-casing: false) #index(display: $(x, p)"-double"$, "xprepresentable", apply-casing: true) ==== Symbols Symbols can be indexed to be sorted under `"Symbols"`, and be sorted at the top of the index like this ```typ #indexMath(initial: (letter: "Symbols", sort-by: "#"), [$(sigma)$]) ``` #indexMath(initial: (letter: "Symbols", sort-by: "#"), [$(sigma)$]) ==== Formatting Entries #index(fmt: strong, [Formatting Entries]) Entries can be formatted with arbitrary functions that map `content` to `content` ```typ #index(fmt: it => strong(it), [The Entry Phrase]) ``` or shorter ```typ #index(fmt: strong, [The Entry Phrase]) ``` For convenience in-dexter exposes `index-main` which formats the entry bold. It is semantically named to decouple the markup from the actual style. One can decide to have the main entries slanted or color formatted, which makes it clear that the style should not be part of the function name in markup. Naming markup functions according to their purpose (semantically) also eases the burden on the author, because she must not remember the currently valid styles for her intent. Another reason to use semantically markup functions is to have them defined in a central place. Changing the style becomes very easy this way. ```typ #index-main[The Entry Phrase] ``` It is predefined in in-dexter like this: ```typ #let index-main = index.with(fmt: strong) ``` Here we define another semantical index marker, which adds an "ff." to the page number. ```typ #let index-ff = index.with(fmt: it => [#it _ff._]) ``` #let index-ff = index.with(fmt: it => [#it _ff._]) ==== Referencing Ranges and Continuations Up to this point, we used Cardinal Markers#index[Cardinal Markers] to mark the index entries. They are referred to with their single page number from the index page. But `in-dexter` also supports more advanced references to marked entries, like the following: - Ranges of Pages: - 42-46 - 42-46, 52-59 - Single Page Continuation (SPC): - 77f. - 77+ - Multi-Page Continuation (MPC): - 82ff. - 77- - 77++ The Continuation Symbols ("f.", "ff.") symbols can be customized via parameters `spc` and `mpc` to `make-index()`. This Sample uses "+" for _Single Page Continuation_ and "++" for _Multi Page Continuations_. ```typ #make-index( use-bang-grouping: true, use-page-counter: true, sort-order: upper, spc: "+", mpc: "++", ) ``` If `spc` is set to `none`, an explicit numeric range is used, like "42-43". If `mpc` is set to `none`, an explicit numeric range is used, like "42-49". Note that "f." and "ff." are the default symbols for `scp` and `mcp`. ===== Range of Pages To mark a Range of pages for an index entry, one can use the following marker: ```typ #index(indexType: indexTypes.Start)[Entry] // other content here #index(indexType: indexTypes.End)[Entry] ``` Of course, you can shorten this somewhat explicit marker with your own marker, like this: #let index-start = index.with(indexType: indexTypes.Start) #let index-end = index.with(indexType: indexTypes.End) Behavior: - If the markers are on the same resulting page, they are automatically combined to a Cardinal Marker#index[Cardinal Marker] in the generated index page. - If the End-Marker is on the next page following the Start-Marker, the Marker is handled as a Continuation Marker ("f."). If it uses the Continuation Symbol or the page numbers can be configured in a Parameter of `make-index()`. - If there is a Start-Marker, but no End-Marker, the Marker is handled as a Continuation Marker ("ff."). == The Index Page #index[Index Page] To actually create the index page, the `make-index()` function has to be called. Of course, it can be embedded into an appropriately formatted #index[Formatting] environment#index[Environment], like this: ```typ #columns(3)[ #make-index() ] ``` The `make-index()` function accepts an optional array of indexes to include into the index page. The default value, `auto`, takes all entries from all indexes. The following sample only uses the entries of the secondary and tertiary index. See sample output in @combinedIndex. ```typ #columns(3)[ #make-index(indexes: ("Secondary", "Tertiary")) ] ``` === Skipping physical pages If page number 1 is not the first physical page#index-main[physical page] of the document, the parameter ` use-page-counter` of the `make-index()` function can be set to `true`. Default is `false`. In-dexter uses the page counter instead of the physical page number then. = Why Having an Index in Times of Search Functionality? #index(fmt: strong, [Searching vs. Index]) A _hand-picked_#index[Hand Picked] or _handcrafted_#index[Handcrafted] Index in times of search functionality seems a bit old-fashioned#index[Old-fashioned] at the first glance. But such an index allows the author to direct the reader, who is looking for a specific topic#index-main("Topic", "specific") (using index-main), to exactly the right places. Especially in larger documents#index[Large Documents] and books#index[Books] this becomes very useful, since search engines#index[Search Engines]#index3[Engines] may provide#index[Provide] too many locations of specific#index2[specific] words. The index#index[Index] is much more comprehensive,#index[Comprehensive] assuming that the author#index[Authors responsibility] has its content#index[Content] selected well. Authors know best where a certain topic#index("Topic", "certain") is explained#index[Explained] thoroughly#index[Thoroughly] or merely noteworthy #index[Noteworthy] mentioned (using the `index` function). Note, that this document is not necessarily a good example#index2[example] of the index. Here we just need to have as many index entries#index[Entries] as possible to demonstrate#index-ff([Demonstrate]) (using a custom made `index-ff` function) the functionality #index[Functionality] and have a properly#index[Properly] filled#index3[filled] index at the end. Even for symbols like `(ρ)`. #index([$(rho)$], initial: (letter: "Symbols", sort-by: "#"), apply-casing: false) Indexing should work for for any Unicode string like Cyrillic (Скороспелка#index(initial: (letter: "С", sort-by: "Ss"), "Скороспелка")) or German (Ölrückstoßabdämpfung).#index(initial: (letter: "Ö", sort-by: "Oo"), "Ölrückstoßabdämpfung") - though we need to add initials: `#index(initial: (letter: "С", sort-by: "Ss"), "Скороспелка")` or `#index(initial: (letter: "Ö", sort-by: "Oo"), "Ölrückstoßabdämpfung")`. #line(length: 100%, stroke: .1pt + gray) #pagebreak() #set page( numbering: "i", footer: align(right)[#context { counter(page).display("i") }], ) // This marks the end of the range for the Entry-Key "Entries" #index(indexType: indexTypes.End)[Entries] = Index pages In this chapter we emit several index pages for this document. We also switched page numbering to roman numbers#index[Roman Numbers], to demonstrate in-dexters ability to display them, if the option `use-page-counter` has been set to true. // Table of Content from here on #context (outline(title: none, target: selector(heading).after(here()))) == The Default Index page<defaultIndex> Here we generate the Index page in three columns. The default behavior (auto) is to use all indexes together. #index-main[Metadaten!Primäre] #index-main(display: "Joy")[Metadaten!Sekundäre!Fun] #index-main("Metadaten!Tertiäre") // A sample with a raw display text #index(display: `Aberration`, "Aberration") #columns(3)[ #make-index( use-bang-grouping: true, use-page-counter: true, sort-order: upper, range-delimiter: [--] ) ] #pagebreak() == Secondary Index Here we select explicitly only the secondary index. #columns(3)[ #make-index(indexes: "Secondary", use-bang-grouping: true, sort-order: upper) ] #line(length: 100%) == Tertiary Index Here we select explicitly only the tertiary index. #columns(3)[ #make-index( indexes: "Tertiary", use-bang-grouping: true, sort-order: upper, ) ] #line(length: 100%) == Combined Index<combinedIndex> Here we select explicitly secondary and tertiary indexes. #columns(3)[ #make-index( indexes: ("Secondary", "Tertiary"), use-bang-grouping: true, sort-order: upper, ) ] #line(length: 100%) == Combined Index - all lower case Here we select explicitly secondary#index[Secondary Index] and tertiary#index[Tertiary Index] indexes and format them all lower case. #columns(3)[ #make-index( indexes: ("Secondary", "Tertiary"), entry-casing: lower, use-bang-grouping: true, sort-order: upper, ) ] #line(length: 100%) #pagebreak() == Math Index Here we explicitly select only the Math index. #columns(3)[ #make-index( indexes: ("Math"), sort-order: upper, use-bang-grouping: true, ) ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/011_The%20Liberation%20of%20Sea%20Gate.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Liberation of Sea Gate", set_name: "Battle for Zendikar", story_date: datetime(day: 28, month: 10, year: 2015), author: "<NAME>", doc ) #emph[Encamped among the hedrons of Emeria high in the air above Tazeem, <NAME> has sent envoys across the world to gather allies for a desperate last stand against the Eldrazi. The city of Sea Gate, once a beacon of learning and culture, swarms with Eldrazi, but Gideon has chosen it as the site of this battle. Here, he will rally the people of Zendikar and show them that victory over the Eldrazi is within their grasp.] #emph[Allies have come. Drana of House Kalastria brought vampires from Guul Draz. The roguish merfolk <NAME> brought a contingent of "roilmages" whose magic controlled the violence of Zendikar's roil. Warriors and refugees from around the world have united under Gideon's banner. He has assembled the greatest host Zendikar has ever seen.] #emph[But will it be enough?] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) People began scrambling down from the hedrons as soon as the first sliver of sun rose over the distant horizon. It was slow going—the ropes and ladders connecting the hedrons were not meant for the passage of so many people at once. When Gideon reached the ground, he found half an army waiting for him already, gathered from camps that had formed in the hedrons' shadows when space on the hedrons themselves grew too crowded. He shouted, "For Zendikar!" and a deafening roar came in answer. When Gideon had led the survivors from Vorik's camp up into the floating hedrons of Emeria, they had numbered in the dozens—very few dozens, he had thought at the time. And many of them had been injured—some, like Vorik himself, had died of their wounds within days. But in the weeks since, groups of straggling refugees had come, one after another, so gradually that he had barely noticed how large the camp had grown. Healers had been working, with very little rest, to bring as many soldiers as possible back to health so they could fight again. Now Gideon led an army—a ragtag, motley assortment, to be sure, but an army of hundreds, and not just a few hundred. It was truly Zendikar's army, drawn from every part of the world, even frozen Sejiri, which had been nearly deserted #emph[before] the Eldrazi arose. Kor, merfolk, and elves marched alongside humans, and even goblins and vampires had joined the ranks. Gideon smiled as he looked them over. "Gideon's Irregulars," he said to himself, conjuring bittersweet memories of his youth on Theros. He and his friends had been a ragtag, motley assortment as well—a far cry from the rigid soldiery of the Boros on Ravnica. Now, with Gideon at their head, this ragtag army—Zendikar's army—began its march to retake Sea Gate from the Eldrazi. The first Eldrazi they encountered were tiny spawn, scattered across the rocky hillside like grazing sheep. Each one stood at the end of a trail of bone-white dust, the devastation left behind from its feeding. Gideon gave a yell and charged down the hill, and a dozen eager soldiers followed him. His sural swept around, slicing and grabbing at the Eldrazi, while his allies' spears and swords slashed and stabbed at the squirming, tentacled things. Somewhere to his right, far beyond his reach, a soldier screamed. Gideon paused, looking around for the source of the cry, but then more spawn rushed at him. The spawn fell quickly under the initial charge, and the host behind him built up a terrible and exhilarating momentum toward the city, like a wind at Gideon's back. Soon he was running, shouting, waving his weapon in the air like a banner, plunging headlong into another mass of Eldrazi closer to the city. These were larger, and their deaths were not so quick. Weapons cut through bony plates and hacked through writhing tentacles, but Gideon heard more cries of pain rising above the shouts of battle, as sharp bony claws slashed and stabbed, and flesh blistered at the Eldrazi's touch or crumbled into dust. The army kept surging forward, as inexorable as the Eldrazi swarms, cutting through the enemies of Zendikar. Gideon knew only the battle: the irregular rhythms of his sural sweeping and cracking, of Eldrazi attacks clattering against his shield or rebounding from a burst of golden energy that warded his skin. The rhythm of his feet moving, forward and back, but always more forward than back. Closer and closer to the white stone of Sea Gate, to the lighthouse that soon came into view, touching the sky. Forward, ever forward, with Zendikar's army at his back. A jagged tentacle erupted out the back of a merfolk soldier just to Gideon's left. #emph[I could have stopped that] , Gideon thought with a wrench of his gut, but there was no time to dwell on his error. Ever forward. A mass of writhing tentacles topped by a bony head engulfed a trio of soldiers to his right. He sprang to attack it and severed its head with one quick stroke, but all that remained of the three soldiers was dust seeping out through the tentacles. He'd been too slow. No time. Ever forward. A huge, bony hand swept a nearby kor up from the ground and raised him high into the air. Gideon vaulted after him, slashing at the arm and bashing his shield into the Eldrazi's face. The hand contracted, blood spurted out between the fingers, and the monster and the kor fell to the ground together. Forward . . . #figure(image("011_The Liberation of Sea Gate/01.jpg", width: 100%), caption: [Serpentine Spike | Art by <NAME>], supplement: none, numbering: none) So many of the Zendikari were dying. So many men and women, following his lead, were running headlong to their deaths. Suddenly he was back on Theros, a brash young man hurling Heliod's spear at the god of death. And the Zendikari around him, the ragtag army he had fondly compared to his Irregulars, were now dying just as his original Irregulars had, paying for his foolish mistake, his arrogance. The burden of those four deaths would never be lifted from his shoulders. Four. How many hundreds more would he carry after this day? He shook his head to clear it, and realized that his forward press had cut him off from the rest of the army. Slashing a wide arc through the Eldrazi around him, he turned back to his troops. The advancing forces had been brought to a standstill, and now a sea of Eldrazi churned between him and the rest of his army. So many of them were dying. No longer a tight wedge driving toward Sea Gate, the army had spread out, and Eldrazi had wormed their way in among the soldiers. Defensive formations were broken, their offensive charge had ground to a halt, and the soldiers were tired, he realized. How many hours had they been fighting? Most of the day was gone. The Sea Gate lighthouse was still a distant beacon across a teeming field of deadly enemies. And Zendikar's army was faltering—dying. And it was his fault. Munda, the kor leader they called "The Spider," was a few yards off to his right, swinging the complex tangle of ropes that had earned him his nickname. Like Gideon, he had pushed too far ahead of the bulk of the Zendikari forces, and his strength was flagging. Gideon cut a path to stand beside him. "Come on," he said. Munda grunted. "Back to the army," Gideon said. "We need to rally them." Munda cast a glance over his shoulder at the army, at what had once been a coherent front line. "They need more than that," he said. Despite his misgivings, Munda moved in step with Gideon, back to back. The two of them had often ventured out from the camp to hunt Eldrazi, and they fought well together. But more and more Eldrazi pressed themselves into the gaps left by the constant motion of their whirling weapons. #figure(image("011_The Liberation of Sea Gate/02.jpg", width: 100%), caption: [Munda, Ambush Leader | Art by <NAME>oss], supplement: none, numbering: none) "For Zendikar!" Gideon shouted as the ragged line of soldiers parted and enfolded him. The answering cry was heartfelt, no doubt, but it was weak. "To me!" he shouted, and the soldiers began the laborious work of coming back into some semblance of a formation. "We're not going to win this," Munda said. "Not today." Gideon's stomach lurched. Defeat was not an option he was ready to consider. "Another day," Munda said. "If we live to see another day." "Retreat," Gideon said, half to himself. "Retreat!" a soldier near him shouted. It was a kor he'd seen before, a sentry from the camp. Blood ran from her forehead down past her eye, streaking her cheek like tears. "Retreat!" Munda echoed, and the cry passed through the ranks. Gideon felt it almost immediately: What had been a sense of forward momentum, almost a palpable pressure behind him, released, and in its place was a gentle pull as the rear of the army began to fall back. "Retreat!" Gideon shouted, bracing himself to guard the rear of the retreating army. Disciplined troops could maintain formation while moving away from the enemy, protecting themselves as they withdrew. For a few moments it seemed like Zendikar's army might be able to manage such a retreat. Munda stayed close beside him, helping him shield the troops at their backs. But these were not disciplined troops, for the most part. They were tough, fierce, and determined, inured to the hardships of Zendikar and grown accustomed to the horrors of the Eldrazi. But they were tired, and the Eldrazi pursued them relentlessly. And so many of them had died. The ordered retreat turned into a rout. The sense of a tug at his back became a sucking vortex as the ranks behind him dissolved and scattered like dust. "Hold the line!" Gideon shouted, and the pull diminished ever so slightly. The soldiers nearest to him slowed their retreat and closed formation, but it was too late for the rest. Zendikar's army—#emph[his] army—was gone. And that left Gideon, Munda, and a small handful of soldiers to hold back the Eldrazi, like the dam of Sea Gate itself holding back the waters of the Halimar Sea. Somewhere far behind him, a horn was sounding a rallying call. It made no difference to him and the waves of Eldrazi crashing against him. But it gave him a direction, in the absence of an ordered host making their retreat. He kept the horn at his back and torturously made his way back into the hills above the city. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Eventually no more Eldrazi pursued them, and Gideon put his back to Sea Gate and rejoined what was left of his army. At the top of a rise, Tazri stood beneath a ragged banner amid a scattering of soldiers—she had sounded the horn. As Gideon crested the rise and looked around, he saw clusters of soldiers kindling campfires across the hillside below. As the sun touched the horizon, the army of Zendikar was coming back together. Munda clapped him on the shoulder. "We made it in one piece, friend," the kor said. "Well fought," Gideon said. "And I'm glad to see you, Tazri." "That was a disaster, #emph[Commander-General] ," she said, her tone turning the title into an indictment of his failure. Gideon frowned at her for a long moment while Munda held his breath. "All right, then," he said at last. "What did I do wrong?" "Nothing," she said. "That's just it. You did nothing." Gideon felt his face flush. "Nothing? I must have killed dozens. I saved—" His words caught in his throat. #emph[Dozens? Maybe. But not enough.] "You are a hero beyond compare, my friend," Munda said. "My own hooks took down—" "But these people need a commander," Tazri said. "I did what I could. I tried. But they look to you." "I led the charge," he protested, but his heart felt the weight of every death he had been unable to prevent. "That's not the same thing. You led—led from the front, a sterling example for your troops." She scoffed. "And you expected your army to follow you in a headlong charge into the thick of the battle." Gideon frowned at her. "Yes, I expect every soldier in this army to face battle with the rest of us. Nobody's just along for the ride." "You expect every soldier in this army to be another one of #emph[you] ," she said, jabbing her finger at his chest. "Look at them! It's not a thousand Gideons down there." "Fortunately," Munda interjected with a snort. "Yes," Tazri said. "Yes. A thousand Gideons would be a force to be reckoned with, certainly. But what would they do against the flying Eldrazi? The ones in the sea?" Gideon looked down at the army, at the contingents of merfolk and elves, with their harnessed sky eels and flying rays, at the vampires and goblins, at the kor kitesailers and hook-wielders, at the humans from every region of the world. #figure(image("011_The Liberation of Sea Gate/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "A thousand Gideons, waving their whips in the air and shouting 'For Zendikar!' as they charge headlong into the foe. Maybe it could work, if they all shared your invulnerability. Maybe they could overcome the Eldrazi, even Ulamog himself, through sheer stubborn force. But that's not the army you have, #emph[Commander-General] ." "You think I don't know that?" Gideon said, looming over her. "I watched them die. So many of them." Tazri put both her hands on his chest and shoved him away, the gleaming halo around her neck flaring brighter. "And I watched them fight! We are Zendikari, Planeswalker. Every person here grew up in a world that seemed determined to kill us all, even before the Eldrazi came. Every race and culture of our world has come up with ways to fight, ways to deal with whatever threats the world throws at us. And few of them involve headlong charges into annihilation!" Her words felt like a knife in his chest. "You inspire these people," she said. "Vorik saw that. You inspired him, too. Even I've felt it. You trust people to be their best, and you make them #emph[want] to live up to that. But you're not giving them a chance to do it." Gideon threw up his hands. "I don't understand," he said. "What more do they need?" Tazri wheeled back to face him. "A plan!" she said. "A strategy! They need to know how they fit into the army and the overall plan of attack. They need to know that if they do what they do best, they're going to help another part of the army do better. They know what they can do, but you have to figure out how it all fits together and explain it to them." Gideon saw the anguish in her face, heard the confusion in her voice, and suddenly saw her in the midst of the disastrous battle, watching soldiers die and being powerless to help. And he realized that he hadn't just failed his army—he'd also failed his commanders. "Walk with me, Tazri," he said. "Munda, you, too." With two commanders at his side, Commander-General <NAME> strode down the hill into the camps of his army. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Over the next few days, a plan came together. Gideon met with every commander in the army, individually and as a group. He sparred with soldiers, learned what they could do, and rode on the back of a sky eel. Flying scouts—kor with their kitesails, elves and merfolk on their bizarre mounts, and vampires floating by means he didn't understand—brought him constant updates on the movements of the Eldrazi and the status of Sea Gate. Now it was #emph[really] time. Before, he had been certain of victory, secure in his invulnerability and the raw enthusiasm of his army. Now he was confident. He had a plan—the army had a plan, and every soldier could see how each specific set of skills could help secure a victory. They were a single body, and every part knew its role. He knew the lay of the land and where the Eldrazi were most concentrated. Victory wasn't certain, of course, but he knew it was achievable. Every soldier knew it. They no longer fought in the desperate hope of survival, but with a plan for victory. Another dawn broke golden over the sea to the east, and the first rays of sunlight gleamed on spears and helmets across the hillside. The troops were already arrayed in careful formation, ready to march at his command. When he saw the first reddish sliver rise over the horizon, he slashed his sural through the air and shouted, "For Zendikar!" And somehow, even after the slaughter of the previous assault, even with so many soldiers fallen, the army of Zendikar managed an answering shout that rang in his ears. They marched. The front lines were regimented, organized, marching in perfect rhythm to the beat of a merfolk's musical conch-shell drum. Behind them, Gideon knew, goblins scurried and shuffled, elves ranged back and forth with their bows, sky eels and flying rays swept the skies, and a very different group of merfolk, under <NAME>'s command, lurched and contorted themselves in anticipation of working their bizarre roil magic. Order and rhythm mattered in the front, to these soldiers near him, but not to those others. #emph[Different drums for different marchers] , he reminded himself. As the host descended upon the first scattered groups of Eldrazi, Gideon shouted unneeded reminders and the army marched forward in ordered lines. Blades sang and sliced. Eldrazi fell. Injured soldiers drew back, and soldiers from the next rank took their places in the line. Most of the army held back, waiting until they were needed. It was too early for Gideon to commit his more mobile troops. Gideon fought. He killed Eldrazi. He protected the soldiers near him when he could. He held the line so the Eldrazi could not break through. He had insisted, over Tazri's objections, on continuing to lead his army from the very front ranks. The compromise he had agreed to, though, was that he retreated, just a few ranks and only occasionally, to hear a report from a flying scout—to make sure he understood how the entire battle was unfolding. One of those scouts, in the afternoon on the first day, brought an alarming report. She had spotted something in the ocean outside Sea Gate: what looked like an army—a fleet?—of monsters swimming toward the city. No Eldrazi, but serpents, sharks, giant octopi, and even a kraken or two all surged toward Sea Gate like a tidal wave. Gideon would have been concerned, but the scout added that they were leaving bits of aquatic Eldrazi floating in the water behind them like chum. "Allies, then," Gideon said. "At least for now." #figure(image("011_The Liberation of Sea Gate/04.jpg", width: 100%), caption: [Octopus token | Art by Craig J Spearing], supplement: none, numbering: none) The army continued its steady advance, and the lighthouse of Sea Gate came back into view. The sight sparked an excited surge in the troops—Gideon felt the energy build like physical pressure at his back. He felt the excitement as well, but he fought the urge to break ranks and charge forward. Many hours of hard fighting still lay between the army and the walls of Sea Gate. When a scout reported heavy losses on the right flank, Gideon directed more troops there, his orders carried through the host by horn signals. When he heard that a large swarm of flying Eldrazi was approaching from the direction of Halimar, the inland sea, he sent a contingent of eel-riders and archers there to fight them off. He sent goblin forces to fend off a skittering mob of smaller Eldrazi that would have distracted his stronger soldiers from greater threats. The sun began to settle, blood red, into the western horizon, casting the battle against a stunning backdrop of color. Of course, the Eldrazi showed no signs of tiring, and the lengthening shadows didn't seem to impair them at all. Gideon gave an order, echoed on horns, and the front ranks of troops began a careful retreat. Gideon realized that he was holding his breath, and he forced himself to let it out, to trust his troops. This was all part of the plan, and everyone knew it was coming. The ranks of human, kor, merfolk, and elf infantry fell back, and fresh troops advanced into their place—vampire troops. Gideon could feel the tension in the retreating soldiers. Eldrazi in front, vampires behind, and their terrifying bloodchief, Drana, hovering overhead—it felt all too much like being trapped between two enemies. He knew, they all knew, that the vampires fought for Zendikar just as they did. But they also knew that the vampires fed on blood. And the whole army was hungry. But the maneuver went off without incident. The vampires, well rested and unhindered by the darkness, surged forward and tore into the Eldrazi with terrible zeal. Evidently they were able to channel their hunger, their bloodlust, into ferocity in battle. Gideon, and the ranks of soldiers behind him, felt a surge of relief even as the exhaustion of the day's battle washed over them. This was part of the plan where Tazri had overcome Gideon's objections: He rested, ate with the other commanders, and spent the evening discussing plans and strategies. It had been a successful day, and Gideon had to trust that the night would go equally well, even without him fighting on the front line. He even managed to sleep. But as soon as enough sunlight leaked into the eastern sky, he rejoined his troops in the front lines, inspiring the vampires to a fresh surge forward. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The wall of Sea Gate, built to protect the city from beasts and bandits, and largely ruined when the Eldrazi overran it, came into view on the second day. The land that divided the Halimar Sea from the ocean outside narrowed quickly until it met the huge white dam of Sea Gate and its crumbling wall. The Halimar side was a gentle slope down to a quiet beach; while cliffs on the other side stretched down to the churning ocean below. The narrowing land presented a unique challenge, exposing both of the army's flanks to attack from Eldrazi that swam or flew. It also descended sharply to the city entrance, making an ordered march difficult. But the problem that commanded Gideon's attention had nothing to do with the terrain or even the Eldrazi. It was the enormous octopus that had half-climbed the cliff alongside the forces, lifting a gigantic tentacle up to them. More specifically, it was the merfolk who perched on top of the tentacle. His soldiers were looking to him for orders, so he shoved his own bewilderment aside and strode to the cliff edge to meet this merfolk. She was striking: Her cerulean skin glistened with water, large fins striped with indigo rose up from her head like elaborately sculpted hair, and she wore an enormous blue sapphire mounted on her forehead in some sort of headdress or crown. And in one hand she gripped a weapon: a strange forked spear made from what looked like red coral, gracefully curved at the end into twin points. It seemed . . . oddly familiar, somehow. "Well, look at this," she said with a smirk. "Have you brought an army to help me take the city?" "To help—" Gideon stammered. "I am Kiora," the merfolk said. #figure(image("011_The Liberation of Sea Gate/05.jpg", width: 100%), caption: [Kiora, Master of the Depths | Art by Jason Chan], supplement: none, numbering: none) Gideon's gaze met Kiora's dark eyes. "<NAME>," he said. "Commander-general of this army. We #emph[have] come to retake Sea Gate"—he quirked his mouth in a half-smile—"and are happy to accept your help." She gave a harsh laugh and raised her spear. A wave swelled in the sea behind her, revealing the dark shapes of enormous sea creatures—the "fleet" Gideon's scout had told him about. "And I am commander-general of #emph[this] army," she said. "I am the Crashing Wave, the Master of the Depths. I have faced a true god—the false Eldrazi gods will not defeat me where Thassa failed." "Thassa?" Gideon said, eyes wide. #emph[Of course, the bident. ] "You have been to Theros?" Kiora winked at him—an unsettling gesture involving the closing of two separate lids on the same eye. "So I am happy to accept your help, Planeswalker." The wave she had summoned crashed against the great white dam of Sea Gate. The ocean churned as sharks and whales, serpents and krakens, tore into the Eldrazi. "The battle of Sea Gate has begun, <NAME>. Best hurry if you want to keep up." The monstrous tentacle lowered Kiora back down to the ocean, and another enormous wave swelled in the sea beyond. A new surge of Eldrazi, perhaps trying to escape Kiora's waves, was coming at the army, and Gideon shouted orders. The merfolk Planeswalker's "army" was a force of chaos he couldn't direct, but he could adjust his own army's assault to make the best use of it. Horns sounded to spread his orders throughout the host, and he could feel a renewed energy rush through the soldiers around him. Kiora's forces effectively covered his army's flank on one side, making the task of reaching the outer wall of Sea Gate easier—at least in theory. The greatest difficulty, though, was that Eldrazi were constantly streaming #emph[out] of Sea Gate, wandering away in search of whatever passed for greener pastures in their minds, and the terrain channeled them directly into the path of Gideon's army. There could be no more skirting around the greatest concentrations of Eldrazi. They had to face the enemy head-on. He felt the eagerness of his troops. With the walls of Sea Gate in view, they wanted to surge forward, to charge the enemy and sweep them from the land. He recognized the impulse, but held the front line to a slow and steady march. There would be no repeat of their first reckless charge. Forward, ever forward—but so much more slowly. The Eldrazi were a rushing deluge streaming out from the city, and every forward step was hard-won. When another night fell, Drana's vampires filled the front ranks again and tried to maintain their position, but their numbers were too small to hold back the flood. The force of Kiora's aquatic assault seemed to ebb with the night tide as well. The vampires were forced back and back until they reached the camps behind them, and weary soldiers were awakened in the middle of the night to hold the Eldrazi off in the darkness. #figure(image("011_The Liberation of Sea Gate/06.jpg", width: 100%), caption: [Kalastria Nightwatch | Art by <NAME>abaey], supplement: none, numbering: none) The difficult night made for even slower progress the next day. But by the time the sun finished its descent, the army had reached the outer wall of Sea Gate. Cheers went up along the front lines as soldiers touched the stone, laying their hands upon the wall in acts of familiar reverence. For many of them, Sea Gate was home, and even for the rest, the wall represented a milestone on the road to victory. A third of the wall was rubble, and another third was chalky dust, but at least it channeled the Eldrazi's movements somewhat. Taking up defensive positions—even if they were on the wrong side of the wall—helped the vampires hold the Eldrazi back through the night so the other soldiers could rest. And on the next day, the fourth dawn since they began their march, the army of Zendikar surged through the wall and entered Sea Gate. Suddenly, Gideon was fighting a different battle. Instead of the open terrain outside the walls, the two forces met in the streets of the city and fought in twisting alleys and small plazas. Like the outer wall, many of the buildings were at least partially destroyed, but even a shattered husk of a building broke line of sight and formed an obstacle in the army's path. A disciplined march was no longer possible. That meant it was time to let other forces do what they did best. Elf rangers moved quickly and quietly from building to building, scouting ahead so individual squads of soldiers could advance through the city. Skulking goblins squeezed into narrow crevices to root out lurking Eldrazi—and even managed to rescue a few survivors who had been trapped in rubble or hiding in cellars since the fall of the city. Kitesailers and eel-riders dropped volatile alchemical concoctions into larger groups of Eldrazi, creating explosive bursts of consuming flame. Gideon couldn't even measure whether they were advancing or retreating anymore. While squads of soldiers cleared and claimed one block of buildings, the Eldrazi circled around and attacked a different one behind them. Some soldiers had nearly reached the lighthouse, but others were still fighting Eldrazi back at the wall. He wasn't even sure what a retreat would look like, but the Eldrazi were everywhere and his soldiers simply couldn't be. He had to figure something out. He paused for a moment, looking down at a gigantic Eldrazi squirming in its death throes, and felt the stone trembling under his feet. "I need eyes!" he shouted. "What's coming?" A merfolk on a huge eel dipped down near him. "Zendikar!" she cried. "Zendikar has come to fight with us!" "What?" "Trees and stones! The land rises up to destroy the Eldrazi!" Gideon couldn't understand—until he saw the first elemental lumbering past. Its shape was like a giant beast, but its head looked like an ancient oak, with a gaping maw amid the roots, and its legs were massive tangles of wood and vines. Each step shook the stone, and it swept its head back and forth as it moved, throwing Eldrazi to the side. #figure(image("011_The Liberation of Sea Gate/07.jpg", width: 100%), caption: [Woodland Wanderer | Art by Vincent Proce], supplement: none, numbering: none) More elementals came into view, looming over buildings and lumbering down wide streets. They were wood and leaf, vine and branch, boulder and bedrock. And a few streets over, standing between two arched wooden horns atop a towering elemental, he saw an exultant elf, hands and eyes glowing green. Nissa had returned. And she had indeed brought Zendikar with her. Noyan Dar's roilmages had chanted about the world's destructive power: "The world heaves! It shakes! It strives! It destroys or it dies!" And here the world was doing just that, not in the unpredictable and indiscriminate roil, but in the forces of nature embodied in animate forms, marching at Nissa's command. Gideon could feel the tide turn. His soldiers were more inspired and excited than he had ever seen them. Zendikar was a harsh world, and most of these people had grown up with a sense that the world was trying to kill them. But now, in a very concrete sense, the world was fighting alongside them, killing their enemies. Crowds of soldiers were falling in behind the elementals, cheering them on and killing any Eldrazi that escaped the grip of roots and the bludgeoning of stone. "Take me up!" he shouted to the merfolk, still hovering on her eel just overhead. She lowered her eel closer, and Gideon clambered up, first to the roof of a nearby building and then onto the eel's saddle, perched behind the rider. Together they rose above the city, so Gideon could see all the parts of his army working together. While he was working with the commanders to formulate the plan for the attack, he had often returned to the metaphor of a body, with all its parts working in concert. Now he could see the truth of it. The two forces—Zendikar's army, with its soldiers and sea monsters and elementals, and the swarms of Eldrazi—were locked together like two wrestlers. Each of them occupied about half the surface of Sea Gate's dam, with the lighthouse between them. The elementals had helped clear away the Eldrazi that had worked their way past the front lines, so the Zendikari had a solid grip on their half of the city. And the Zendikari had the upper hand. They were going to win! #figure(image("011_The Liberation of Sea Gate/08.jpg", width: 100%), caption: [Outnumber | Art by <NAME>], supplement: none, numbering: none) At Gideon's command, the eel-rider let him down near the lighthouse. He shouted orders, and horns carried them throughout the host. Soldiers marched, kitesailers lifted into the air, scouts slipped among the buildings, and victory drew closer. Beyond the lighthouse, the battle became gradually less intense. Instead of fighting upstream against a flood of Eldrazi leaving the city, the Zendikari were driving the Eldrazi before them out of the city at its other end. The creatures still fought; they seemed as intent as ever on turning the Zendikari into food or dust. But the Zendikari had momentum on their side now. When they paused for the night, Drana's vampire soldiers had little difficulty holding the Eldrazi back. And it was barely noon on the next day when a quiet fell across the city. A moment later, a cheer went up near the wall and spread throughout the troops. His heart pounding, Gideon signaled for an aerial scout's report. "Fighting has stopped, Commander-<NAME>," the elf reported. "I can't see any more Eldrazi within the city walls." Gideon needed to see for himself. "The top of the lighthouse," he said. "Can you get me there?" The elf nodded, and Gideon climbed onto the back of the undulating flying ray. A moment later, he climbed through a window at the top of the lighthouse spire and looked out over Sea Gate. The city was in ruins. Many buildings were dust and rubble, and the streets were littered with the bodies of the dead. The mighty dam itself had held, but he could see patches of dusty corruption here and there on the surface. But Sea Gate was theirs. The army of Zendikar had reclaimed it from the Eldrazi. They had won. A signaler joined him at the top of the tower and blew out his orders on her horn—two strong groups of soldiers gathered at either end of the dam, smaller patrols along the Halimar side to watch against Eldrazi coming from the waters, archers along the oceanside wall. They had claimed Sea Gate, but they still had to defend it. Slowly, other commanders joined him, and eventually Nissa arrived as well—and then Kiora. "I have some questions for you," he told the merfolk Planeswalker, grinning. "I bet you do," she said. Before he could ask them, he heard shouting in the city below. Afraid that the Eldrazi had made another incursion, he rushed to the window. A merfolk in white coral armor that contrasted with her reddish skin was running at full tilt, heading for the lighthouse. "<NAME>?" he said. She was shouting, but he couldn't make out her words. As she entered the lighthouse, he started down the stairs to meet her. Then he finally heard her clearly: "Ulamog!" They met in the middle of the stairway. Panting with exertion, she repeated her warning. "Ulamog is coming!"
https://github.com/jneug/typst-mantys
https://raw.githubusercontent.com/jneug/typst-mantys/main/src/mty.typ
typst
MIT License
// Import dependencies #import "@preview/t4t:0.3.2": * #import "@preview/codelst:2.0.0" #import "@preview/showybox:2.0.1": showybox #import "theme.typ" // ################################# // # Some common utility functions # // ################################# /// Shows #arg[code] as inline #doc("text/raw") text (with #arg(block: false)). /// - #shortex(`#mty.rawi("some inline code")`) /// /// - code (content): String content to be displayed as `raw`. /// - lang (string): Optional language for syntax highlighting. /// -> content #let rawi( code, lang:none ) = raw(block: false, get.text(code), lang:lang) /// Shows #arg[code] as inline #doc("text/raw") text (with #arg(block: false)) and with the given #arg[color]. This /// supports no language argument, since #arg[code] will have a uniform color. /// - #shortex(`#mty.rawc(purple, "some inline code")`) /// /// - color (color): Color for the `raw` text. /// - code (content): String content to be displayed as `raw`. /// -> content #let rawc( color, code ) = text(fill:color, rawi(code)) /// A #doc("layout/block") that is centered in its parent container. /// #example[``` /// #mty.cblock(width:50%)[#lorem(40)] /// ```] /// /// - width (length): Width of the block. /// - ..args (any): Argeuments for #doc("layout/block"). /// - body (content): Content of the block /// -> content #let cblock( width:90%, ..args, body ) = pad( left:(100%-width)/2, right:(100%-width)/2, block(width:100%, spacing: 0pt, ..args, body) ) /// Create a frame around some content. /// #ibox[Uses #package("showybox") and can take any arguments the /// #cmd-[showybox] command can take.] /// #example[``` /// #mty.frame(title:"Some lorem text")[#lorem(10)] /// ```] /// /// ..args (any): Arguments for #package[Showybox]. /// -> content #let frame( ..args ) = showybox( frame: ( border-color: theme.colors.primary, title-color: theme.colors.primary, thickness: .75pt, radius: 4pt, inset: 8pt ), ..args ) /// An alert box to highlight some content. /// #ibox[Uses #package("showybox") and can take any arguments the #cmd-[showybox] command can take.] /// #example[``` /// #mty.alert(color:purple, width:4cm)[#lorem(10)] /// ```] #let alert( color: blue, width: 100%, size: .88em, ..style, body ) = showybox( frame: ( border-color: color, title-color: color, body-color: color.lighten(88%), thickness: (left:2pt, rest:0pt), radius: 0pt, inset: 8pt ), width: width, ..style, text(size:size, fill:color.darken(60%), body) ) /// Places a note in the margin of the page. /// /// - pos (alignment): Either #value(left) or #value(right). /// - gutter (length): Spacing between note and textarea. /// - dy (length): How much to shift the note up or down. /// - body (content): Content of the note. /// -> content #let marginnote( pos: left, gutter: .5em, dy: -1pt, body ) = { style(styles => { let _m = measure(body, styles) if pos.x == left { place(pos, dx: -1*gutter - _m.width, dy:dy, body) } else { place(pos, dx: gutter + _m.width, dy:dy, body) } }) } // persistent state for index entries #let __s_mty_index = state("@mty-index", ()) /// Removes special characters from #arg[term] to make it /// a valid format for the index. /// /// - term (string, content): The term to sanitize. /// -> string #let idx-term( term ) = { get.text(term).replace(regex("[#_()]"), "") } /// Adds #arg[term] to the index. /// /// Each entry can be categorized by setting #arg[kind]. /// @@make-index can be used to generate the index for one kind only. /// /// - term (string, content): An optional term to use, if it differs from #arg[body]. /// - hide (boolean): If #value(true), no content is shown on the page. /// - kind (string): A category for ths term. /// - body (content): The term or label for the entry. /// -> (none, content) #let idx( term: none, hide: false, kind: "term", body ) = locate(loc => { __s_mty_index.update(arr => { arr.push(( term: idx-term(def.if-none(term, body)), body: def.if-none(term, body), kind: kind, loc: loc )) arr }) if not hide { body } }) /// Creates an index from previously set entries. /// /// - kind (string): An optional kind of entries to show. /// - cols (integer): Number of columns to show the entries in. /// - headings (function): Function to generate headings in the index. /// Gets the letter for the new section as an argument: /// #lambda("string", ret:"content") /// - entries (function): A function to format index entries. /// Gets the index term, the label and the location for the entry: /// #lambda("string", "content", "location", ret:"content") /// -> content #let make-index( kind: none, cols: 3, headings: (h) => heading(level:2, numbering:none, outlined:false, h), entries: (term, body, locs) => [ #link(locs.first(), body) #box(width: 1fr, repeat[.]) #{locs.map(loc => link(loc, strong(str(loc.page())))).join([, ])}\ ] ) = locate(loc => { let index = __s_mty_index.final(loc) let terms = (:) let kinds = (kind,).flatten() for idx in index { if is.not-none(kind) and idx.kind not in kinds { continue } let term = idx.term let l = upper(term.first()) let p = idx.loc.page() if l not in terms { terms.insert(l, (:)) } if term in terms.at(l) { if p not in terms.at(l).at(term).pages { terms.at(l).at(term).pages.push(p) terms.at(l).at(term).locs.push(idx.loc) } } else { terms.at(l).insert(term, (term:term, body:idx.body, pages: (p,), locs: (idx.loc,))) } } show heading: it => block([ #block(spacing:0.3em, text(font:("Liberation Sans"), fill:theme.colors.secondary, it.body)) ]) columns(cols, for l in terms.keys().sorted() { headings(l) // for (_, term) in terms.at(l) { for term-key in terms.at(l).keys().sorted() { let term = terms.at(l).at(term-key) entries(term.term, term.body, term.locs) } } ) }) /// Generate a version number from a version string or array. /// The function takes a variable number of arguments and builds /// a version string in _semver_ format: /// - #shortex(`#mty.ver(0,1,1)`) /// - #shortex(`#mty.ver(0,1,"beta-1")`) /// - #shortex(`#mty.ver("1.0.2")`) #let ver( ..args ) = { if args.pos().len() == 1 { [*#args.pos().first()*] } else { [*#args.pos().map(str).join(".")*] } } /// Highlight human names (with first- and lastnames). /// - #shortex(`#mty.name("<NAME>")`) /// - #shortex(`#mty.name("J.", last:"Neugebauer")`) /// /// - name (string): First or full name. /// - last (string): Optional last name. /// -> content #let name( name, last:none ) = { if last == none { let parts = get.text(name).split(" ") last = parts.pop() name = parts.join(" ") } [#name #smallcaps(last)] } /// Show author information. /// - #shortex(`#mty.author("<NAME>")`) /// - #shortex(`#mty.author((name:"<NAME>"))`) /// - #shortex(`#mty.author((name:"<NAME>", email:"<EMAIL>"))`) /// /// - info (string, dictionary): Either a string with an author name or a dictionary with the `name` and `email` keys. /// -> content #let author( info ) = { if type(info) == "string" { return name(info) } else if "email" in info { return [#name(info.name) #link("mailto:" + info.email, rawi("<" + info.email + ">"))] } else { return name(info.name) } } /// Show a date with a given format. /// - #shortex(`#mty.date("2023-09-25")`) /// - #shortex(`#mty.date(datetime.today())`) /// /// - d (datetime, string): Either a date as a string or #dtype("datetime"). /// - format (string): An optional #dtype("datetime") format string. /// -> content #let date( d, format:"[year]-[month]-[day]" ) = { if type(d) == "datetime" { d.display(format) } else { d } } /// Highlights some content with the #mty.primary("primary color"). #let primary = text.with(fill:theme.colors.primary) /// Highlights some content with the #mty.secondary("secondary color"). #let secondary = text.with(fill:theme.colors.secondary) /// Show a package name. /// - #shortex(`#mty.package("codelst")`) /// /// - name (string): Name of the package. #let package( name ) = primary(smallcaps(name)) /// Show a module name. /// - #shortex(`#mty.module("util")`) /// /// - name (string): Name of the module. #let module( name ) = rawc(theme.colors.module, name) /// Creates a #doc("text/link") with an attached footnote showing the #arg[url]. /// - #shortex(`#mty.footlink("https://neugebauer.cc", "neugebauer.cc")`) /// /// - url (string): The url for the link and the footnote. /// - label (string): The label for the link. /// -> content #let footlink( url, label ) = [#link(url, label)#footnote(link(url))] /// Creates a #doc("text/link") to a GitHub repository given in the format /// `user/repository` and shows the url in a footnote. /// - #shortex(`#mty.gitlink("jneug/typst-mantys")`) /// /// - repo (string): Identifier of the repository. /// -> content #let gitlink( repo ) = footlink("https://github.com/" + repo, repo) /// Creates a #doc("text/link") to a Typst package in the Typst package repository /// at #link("https://github.com/typst/packages", "typst/packages"). /// - #shortex(`#mty.pkglink("codelst", (2,0,0))`) /// /// - name (string): Name of the package. /// - version (string): Version string of the package as an array of ints (e.g. (0,0,1)). /// - namespace (string): The namespace to use. Defaults to `preview`. /// -> content #let pkglink( name, version, namespace:"preview" ) = footlink("https://github.com/typst/packages/tree/main/packages/" + namespace + "/" + name + "/" + version.map(str).join("."), package(name + sym.colon + version.map(str).join("."))) // Tests if #arg[value] has a certain label attached. // - #shortex(`#mty.is-a([#raw("some code")<x>], <x>)`) // - #shortex(`#mty.is-a([#raw("some code")<x>], <y>)`) // // - value (content): The content to test. // - label (label): A label to check for. // #let is-a(value, label) = { // return type(value) == "content" and value.has("label") and value.label == label // } /// Adds a label to a content element. /// /// - mark (string, label): A label to attach to the content. /// - elem (content): Content to mark with the label. #let add-mark( mark, elem ) = { if not is.label(mark) { mark = alias.label(mark) } [#elem#mark] } /// Tests if #arg[value] has a certain label attached. /// - #shortex(`#mty.has-mark(<x>, mty.add-mark(<x>, raw("some code")))`) /// - #shortex(`#mty.has-mark(<x>, [#raw("some code")<x>])`) /// - #shortex(`#mty.has-mark(<y>, [#raw("some code")<x>])`) /// /// - mark (string, label): A label to check for. /// - elem (content): The content to test. #let has-mark( mark, elem ) = { if type(mark) != "label" { mark = label(mark) } return type(elem) == "content" and elem.has("label") and elem.label == mark } // Inverse of @@has-mark. #let not-has-mark( mark, elem ) = not has-mark(mark, elem) /// Mark content as an argument. /// >>> mty.mark-arg("my arg").label == <arg> #let mark-arg = add-mark.with(<arg>) /// Test if #arg[value] is an argument created with #cmd-[arg]. /// >>> mty.is-arg(mty.mark-arg("my arg")) #let is-arg = has-mark.with(<arg>) /// Test if #arg[value] is no argument created with #cmd-[arg]. /// >>> mty.not-is-arg("my arg") #let not-is-arg = not-has-mark.with(<arg>) /// Mark content as a body argument. /// >>> mty.mark-body("my body").label == <arg-body> #let mark-body = add-mark.with(<arg-body>) /// Test if #arg[value] is a body argument created with #cmd-[barg]. /// >>> mty.is-body(mty.mark-body("my body")) #let is-body = has-mark.with(<arg-body>) /// Test if #arg[value] is no body argument created with #cmd-[barg]. /// >>> mty.not-is-body("my body") #let not-is-body = not-has-mark.with(<arg-body>) /// Mark content as an argument sink. /// >>> mty.mark-sink("my sink").label == <arg-sink> #let mark-sink = add-mark.with(<arg-sink>) /// Test if #arg[value] is an argument sink created with #cmd-[sarg]. /// >>> mty.is-sink(mty.mark-sink("my sink")) #let is-sink = has-mark.with(<arg-sink>) /// Test if #arg[value] is no argument sink created with #cmd-[sarg]. /// >>> mty.not-is-sink("my sink") /// >>> not mty.not-is-sink(mty.mark-sink("my sink")) #let not-is-sink = not-has-mark.with(<arg-sink>) /// Mark content as a choices argument. #let mark-choices = add-mark.with(<arg-choices>) /// Test if #arg[value] is a choice argument created with #cmd-[choices]. #let is-choices = has-mark.with(<arg-choices>) /// Test if #arg[value] is no choice argument created with #cmd-[choices]. #let not-is-choices = not-has-mark.with(<arg-choices>) /// Mark content as a function argument. /// >>> mty.mark-func("my function").label == <arg-func> #let mark-func = add-mark.with(<arg-func>) /// Test if #arg[value] is a function argument created with #cmd-[func]. /// >>> mty.is-func(mty.mark-func("my function")) #let is-func = has-mark.with(<arg-func>) /// Test if #arg[value] is no function argument created with #cmd-[func]. /// >>> mty.not-is-func("my function") #let not-is-func = not-has-mark.with(<arg-func>) /// Mark content as a lambda argument. #let mark-lambda = add-mark.with(<arg-lambda>) /// Test if #arg[value] is a lambda argument created with #cmd-[lambda]. /// >>> mty.is-lambda(mty.mark-lambda("a lambda")) #let is-lambda = has-mark.with(<arg-lambda>) /// Test if #arg[value] is no lambda argument created with #cmd-[lambda]. /// >>> mty.not-is-lambda("a lambda") /// >>> not mty.not-is-lambda(mty.mark-lambda("a lambda")) #let not-is-lambda = not-has-mark.with(<arg-lambda>) /// Places an invisible marker in the content that can be modified /// with a #var[show] rule. /// #example[``` /// This marker not replaced: #mty.place-marker("foo1") /// /// #show mty.marker("foo1"): "Hello, World!" /// Here be a marker: #mty.place-marker("foo1")\ /// Here be a marker, too: #mty.place-marker("foo2") /// ```] /// /// - name (string): Name of the marker to be referenced later. #let place-marker( name ) = { raw("", lang:"--meta-" + name + "--") } /// Creates a selector for a marker placed via @@place-marker. /// #example[``` /// #show mty.marker("foo1"): "Hello, World!" /// Here be a marker: #mty.place-marker("foo1")\ /// Here be a marker, too: #mty.place-marker("foo2") /// ```] /// /// - name (string): Name of the marker to be referenced. #let marker( name ) = selector(raw.where(lang: "--meta-" + name + "--")) /// Shows sourcecode in a frame. /// #ibox[Uses #package[codelst] to render the code.] /// See @sourcecode-examples for more information on sourcecode and examples. /// /// - ..args (any): Argumente für #cmd-(module:"codelst")[sourcecode] /// -> content #let sourcecode( ..args ) = codelst.sourcecode( frame:none, ..args ) /// Show a reference to a labeled line in a sourcecode. /// #ibox[Uses #package[codelst] to show the reference.] #let lineref = codelst.lineref /// Show an example by evaluating the given raw code with Typst and showing the source and result in a frame. /// /// See section II.2.3 for more information on sourcecode and examples. /// /// - side-by-side (boolean): Shows the source and example in two columns instead of the result beneath the source. /// - scope (dictionary): A scope to pass to #doc("foundations/eval"). /// - mode (string): The evaulation mode: #choices("markup", "code", "math") /// - breakable (boolean): If the frame may brake over multiple pages. /// - example-code (content): A #doc("text/raw") block of Typst code. /// - ..args (content): An optional second positional argument that overwrites the evaluation result. This can be used to show the result of a sourcecode, that can not evaulated directly. #let code-example( side-by-side: false, scope: (:), mode:"markup", breakable: false, example-code, ..args ) = { if is.not-empty(args.named()) { panic("unexpected arguments", args.named().keys().join(", ")) } if args.pos().len() > 1 { panic("unexpected argument") } let code = example-code if not is.raw(code) { code = example-code.children.find(is.raw) } let cont = ( sourcecode(raw(lang:if mode == "code" {"typc"} else {"typ"}, code.text)), ) if not side-by-side { cont.push(line(length: 100%, stroke: .75pt + theme.colors.text)) } // If the result was provided as an argument, use that, // otherwise eval the given example as code or content. if args.pos() != () { cont.push(args.pos().first()) } else { cont.push(eval(mode:mode, scope: scope, code.text)) } frame( breakable: breakable, grid( columns: if side-by-side {(1fr,1fr)} else {(1fr,)}, gutter: 12pt, ..cont ) ) } // ================================= // Regex for detecting values // ================================= #let _re-join( ..parts ) = { return raw(parts.pos().map((r) => if type(r) == "string" {r} else {r.text}).join()) } #let _re-or( ..parts ) = { return _re-join(`(`, parts.pos().map((r) => r.text).join("|"), `)`) } #let _re-numeric = `(\d+(\.\d+)?|\.\d+)` #let _re-units = raw("(" + ("em","cm","mm","in","%","deg").join("|") + ")") #let _re-numeric-unit = _re-join( _re-numeric, `(`, _re-units, `)?` ) #let _re-bool = `(true|false)` #let _re-halign = `(left|right|center)` #let _re-valign = `(top|bottom|horizon)` #let _re-align = _re-or(_re-halign, _re-valign) #let _re-2dalign = _re-join(`(`, _re-halign, `(\s*\+\s*`, _re-valign, `)?`, `|`, _re-valign, `(\s*\+\s*`, _re-halign, `)?`, `)`) #let _re-special = `(auto|none)` #let _re-color-names = _re-or(`black`, `white`, `blue`) #let _re-color = _re-or(_re-color-names) #let _re-stroke = _re-join(_re-numeric-unit, `\s*\+\s*`, _re-color) #let _re-dict = `` #let _re-arr = `` #let _re-values = _re-join( `^`, _re-or(_re-special, _re-numeric-unit, _re-bool, _re-2dalign, _re-color), `$` ) #let re-values = regex(_re-values.text) #let match-value(v) = { if is.str(v) { return v.trim().match(re-values) != none } else { return false } } #let _re-func = `^\(.*\) => .+` #let match-func(v) = { if is.str(v) { return v.trim().match(regex(_re-func.text)) != none } else { return false } }
https://github.com/Servostar/dhbw-abb-typst-template
https://raw.githubusercontent.com/Servostar/dhbw-abb-typst-template/main/src/pages/outline.typ
typst
MIT License
// .--------------------------------------------------------------------------. // | Document Outline | // '--------------------------------------------------------------------------' // Author: <NAME> // Edited: 28.06.2024 // License: MIT // render an outline of figures // with a specific title and filter by a specifc kind of figure // can optionally insert a pagebreak after the outline // NOTE: will not render in case the listing is empty #let render_filtered_outline(title: str, kind: selector) = ( context { let elems = query(figure.where(kind: kind), here()) let count = elems.len() show outline.entry: it => { link(it.element.location())[ #v(12pt, weak: true) #text(weight: "regular", it.body) #box(width: 1fr, it.fill) #[ #it.page] ] } // only show outline if there is something to list if count > 0 { pagebreak(weak: true) outline( title: title, target: figure.where(kind: kind), ) } } ) #let render_figures_outline() = ( context { let title = if (text.lang == "de") { "Abbildungsverzeichnis" } else if text.lang == "en" { "List of Figures" } render_filtered_outline(title: title, kind: image) } ) #let render_table_outline() = ( context { let title = if (text.lang == "de") { "Tabellenverzeichnis" } else if text.lang == "en" { "List of Tables" } render_filtered_outline(title: title, kind: table) } ) #let render_raw_outline() = ( context { let title = if (text.lang == "de") { "Quelltextverzeichnis" } else if text.lang == "en" { "Code Snippets" } render_filtered_outline(title: title, kind: raw) } ) #let render_heading_outline() = ( context { let title = if (text.lang == "de") { "Inhaltsverzeichnis" } else if text.lang == "en" { "Table of Contents" } let header-supplement = if (text.lang == "de") { "Kapitel" } else { "chapter" } pagebreak(weak: true) outline( target: heading.where(supplement: [#header-supplement]), title: title, indent: auto, ) } ) #let render_appendix_outline() = ( context { let supplement = if text.lang == "en" { [Appendix] } else { [Anhang] } if query(heading.where(supplement: supplement)).len() > 0 { let title = if (text.lang == "de") { "Anhangsverzeichnis" } else if text.lang == "en" { "Table of Appendices" } pagebreak(weak: true) outline( target: heading.where(supplement: supplement), title: title, indent: auto, ) } } ) #let new_outline() = { pagebreak(weak: true) show outline.entry.where(level: 1): it => { v(1.5em, weak: true) strong(it) } render_heading_outline() render_figures_outline() render_table_outline() render_raw_outline() render_appendix_outline() }
https://github.com/vmysak/modern-cv-typst
https://raw.githubusercontent.com/vmysak/modern-cv-typst/main/src/definitions/cv-page-styles.typ
typst
Apache License 2.0
#import "../my-config.typ": * #let _page(cvFooter, body) = { let roles = userInfo.roles.join(", ") set document( title: "CV | " + userInfo.fullName + " | " + roles, author: userInfo.fullName, ) set text( font: main-font, lang: "en", size: main-font-size, fill: pal.regular-color, fallback: true, ) set page( paper: "a4", margin: page-margin, footer: cvFooter, footer-descent: 0pt, ) body } #let _modernHeading(body) = { show heading.where(level: 1): it => [ #align(left)[ #box(inset: (top: -5pt))[ #strong[#it.body.text<accent>] #box( width: 1fr, line( length: 100%, stroke: (paint: pal.regular-color, thickness: 1pt), ), ) ] ] ] body } #let _modernBlock(body) = { show <keyValueBlock>: it => ( grid( columns: (3pt, auto), rows: (1), line( end: none, length: (main-font-size + main-font-size / 5) * it.children.len() / 2, angle: 90deg, stroke: (paint: pal.accent-color, thickness: 1pt), ), it, ) ) body } #let _textStyles(body) = { context { show <accent>: it => [ #set text(fill: pal.accent-color) #text[#it] ] show <bold>: it => [ #set text(weight: "bold") #text[#it] ] show <desat>: it => [ #set text(fill: pal.regular-color-desat) #text[#it] ] show <bold-desat>: it => [ #set text(weight: "bold", fill: pal.regular-color-desat) #text[#it] ] body } } #let cvStyle = ( modernHeading: _modernHeading, modernBlock: _modernBlock, textStyles: _textStyles, page: _page, )
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/4-results/study-3.typ
typst
MIT License
#import "../../lib/mod.typ": * #pagebreak(weak: true) == #study.H-3.full.n <s.r.study-3> The results for the two scenarios; #scen.solo-gp.n and #scen.collaborative-gp.n, are presented in @s.r.study-3.solo-global and @s.r.study-3.collaborative-global respectively. These experiments belong to the third contribution of this thesis, which corresponds to the third hypothesis, #study.H-3.box. === Solo Global Planning <s.r.study-3.solo-global> The results of the #scen.solo-gp.n scenario are shown as box plots in @f.solo-box, which clearly shows a reduction in path deviation when the tracking factor is used. The mean path deviation#h(1fr)error#h(1fr)is#h(1fr)reduced#h(1fr)from#h(1fr)1.03#h(1fr)to#h(1fr)0.74#h(1fr)when#h(1fr)the#h(1fr)tracking#h(1fr)factor#h(1fr)is#h(1fr)enabled,#h(1fr)which#h(1fr)is#h(1fr)a #v(-0.65em) #let body = [ // The path adherence is shown in @f.solo-plot, and @f.solo-box, where we can see how the tracking factor has lowered the path-deviation error across the board. $tilde.op#strfmt("{0:.0}", solo-gp-mean-decrease)%$ improvement. @t.solo-stats presents some raw statistics, where it is easy to make out, not only the decrease in mean path deviation error, but also a reduction in variance as shown by the standard deviation. Since the improvement is slightly intangible, the paths driven by the robots are visualized in @f.solo-plot. The blue#sl robot is using the waypoint tracking approach, where the green robot is equipped with path tracking. The figure shows how the tracking factor has kept the green robot much closer to the planned path, which is visualized in grey#swatch(theme.text). This is especially evident in the sharp turns, where the blue robot deviates significantly, both before and after the turn. ] #let fig-deviation = [ #figure( block( clip: true, pad( y: -3.5mm, x: -4mm, image("../../figures/plots/solo-gp-deviation.svg"), ), ), caption: [The paths of the robot with no tracking factors is shown as a blue line #inline-line(stroke: theme.lavender + 2pt), and a robot with tracking factors as a green line #inline-line(stroke: theme.green + 2pt). Underneath the planned path is visualized in grey #inline-line(stroke: theme.text + 2pt).] )<f.solo-plot> ] #let fig = [ #figure( block( clip: true, pad( top: -4mm, bottom: -3.5mm, x: -3.5mm, image("../../figures/plots/solo-gp.svg"), ), ), caption: [Box plots showing the path deviation error when the tracking factor is disabled as "No Tracking"#sl, and enabled as "Tracking"#sg.] )<f.solo-box> ] // No tracking: // │ mean ┆ 1.032871 │ // │ std ┆ 0.108944 │ // │ min ┆ 0.92563 │ // │ 25% ┆ 0.94813 │ // │ 50% ┆ 1.028276 │ // │ 75% ┆ 1.062415 │ // │ max ┆ 1.199902 | // Tracking: // │ mean ┆ 0.739331 │ // │ std ┆ 0.078216 │ // │ min ┆ 0.674259 │ // │ 25% ┆ 0.67759 │ // │ 50% ┆ 0.71177 │ // │ 75% ┆ 0.77322 │ // │ max ┆ 0.859816 │ #let data = ( no-tracking: ( mean: 1.032871, std: 0.108944, min: 0.92563, max: 1.199902 ), tracking: ( mean: 0.739331, std: 0.078216, min: 0.674259, max: 0.859816 ) ) #let tab = [ #figure( { tablec( columns: 3, alignment: (x, y) => (left, center, center).at(x), header: table.header( [Stat], [No Tracking], [With Tracking] ), [*Mean*], [1.03], [0.74], [*Std. Dev.*], [0.11], [0.08], [*Min*], [0.93], [0.67], [*Max*], [1.20], [0.86] ) v(4.5mm) }, caption: [Mean, standard deviation, minimum, and maximum path deviation error for tracking factors disabled in the first column, and enabled in the second.] )<t.solo-stats> ] #grid( columns: (1fr, 73mm), gutter: 1em, body, fig-deviation, fig, v(5mm) + tab, ) === Collaborative Global Planning <s.r.study-3.collaborative-global> // #jens[Effect of tracking factor on ability to avoid each other] // #jens[Waypoint tracking vs path tracking and their effects on collisions vs path adherence.] The results for the #scen.collaborative-gp.n scenario are presented similarly to those of the solo scenario above. The box plots in @f.collaborative-box show the path deviation error for the waypoint tracking approach explained in @s.m.planning.waypoint-tracking, and for the path tracking approach explained in @s.m.planning.path-tracking. For the path tracking approach, two different values for the certainty of the tracking factor are used, see @eq.sigma-t. $ sigma_t = 0.15#h(1em)"and"#h(1em)sigma_t = 0.5 $<eq.sigma-t> // Similar nothions as to the solo scenario Once again the tracking factor has a significant impact on the mean path deviation, this time reducing by $#strfmt("{0:.0}", collaborative-gp-mean-decrease)%$ for the same tracking factor certainty of $sigma_t = 0.15$ versus the pure waypoint tracking approach with no tracking factors at all. Furthermore, with a lower certainty of $sigma_t = 0.5$, the mean path deviation error increases again, essentially matching waypoint tracking in the mean. However, the standard deviation is negligibly lower by $0.02$, as detailed in @t.collaborative-stats. The amount of interrobot collisions for each configuration is also written in @t.collaborative-stats, where it is clear that path tracking has a significant impact. Note that the formation configuration for this scenario includes three spawning spots, where robots are spawned periodically with no accountance for whether an earlier robot has moved from the spawning area. The reason robots get _stuck_ in the beginning, is due to the unpredictable nature of the #acr("RRT*") path-finding algorithm, which sometimes takes a while to find a path. It has been measured to take up to $10$ seconds in some outlier cases. #let fig = [ #figure( block( clip: true, pad( y: -4mm, x: -4mm, image("../../figures/plots/collaborative-gp.svg"), ), ), caption: [Box plots for each of the three configurations: Tracking factors disabled#sl, and for tracking factors enabled, respectively with a certainty of $sigma_t = 0.15$#stl, and $sigma_t = 0.5$#sg.] )<f.collaborative-box> ] // No tracking // │ mean ┆ 1.003978 │ // │ std ┆ 0.230388 │ // │ min ┆ 6.5345e-8 │ // │ 25% ┆ 0.898321 │ // │ 50% ┆ 1.042123 │ // │ 75% ┆ 1.153165 │ // │ max ┆ 1.464897 │ // Sigma 0.15 // │ mean ┆ 0.855876 │ // │ std ┆ 0.247935 │ // │ min ┆ 6.5345e-8 │ // │ 25% ┆ 0.695161 │ // │ 50% ┆ 0.842916 │ // │ 75% ┆ 1.045296 │ // │ max ┆ 1.464897 │ // Sigma 0.5 // │ mean ┆ 0.98681 │ // │ std ┆ 0.212813 │ // │ min ┆ 6.4935e-8 │ // │ 25% ┆ 0.889289 │ // │ 50% ┆ 1.008476 │ // │ 75% ┆ 1.131919 │ // │ max ┆ 1.533094 │ #let tab = [ #figure( { tablec( columns: 4, alignment: (x, y) => (left, center, center, center).at(x), header: table.header( [Stat], [NT], [$bold(sigma_t=0.15)$], [$bold(sigma_t=0.5)$] ), [*Mean*], [1.00], [0.86], [0.99], [*Std. Dev.*], [0.23], [0.25], [0.21], [*Min*], [0.00], [0.00], [0.00], [*Max*], [1.46], [1.46], [1.53], [*Collisions*], [2.8], [11.9], [3.4], ) v(6mm) }, caption: [Mean, standard deviation, min, and max path deviation error for tracking factors disabled in the first column, and enabled in the second and third. The last row contains the mean number of interrobot collisions. NT = No Tracking.] )<t.collaborative-stats> ] #grid( columns: (1fr, 66mm), column-gutter: 1em, fig, v(1.65mm) + tab )
https://github.com/woojiahao/nus
https://raw.githubusercontent.com/woojiahao/nus/main/uts2706/uts2706_finals_raw/main.typ
typst
MIT License
#import "@preview/cetz:0.2.2" #set page(flipped: false, margin: 20pt) #show: columns.with(3, gutter: 4pt) #set text( font: "New Computer Modern Sans", size: 9pt ) #show par: set block(spacing: 5pt) #set par(leading: 3pt) #set list(tight: true) #set block(spacing: 0.5em) #align(center)[ #box(inset: 10pt, stroke: black, [ = UTS2706 Finals Cheatsheet by: #link("https://nus.woojiahao.com")[#underline("Jiahao")] ]) ] #show heading.where(level: 1): it => [ #set text(10pt, weight: "bold") #block([#underline(smallcaps(it.body))]) // #block(smallcaps(it.body)) ] #show heading.where(level: 2): it => [ #set text(10pt, weight: "bold") // #block([#underline(smallcaps(it.body))]) #block(smallcaps(it.body)) ] #show image: it => [ #align(center, it) ] #show table: it => [ #align(center, it) ] = economics study of how people manage their #underline("resources") to create proucts or services to meet their #underline("needs") and enhance their #underline("well-being") $ "economy" subset "society" subset "environment" $ = resources could be classified as... - *natural:* water, mineral, wind, oil, forest, agricultural products, sea, sun light... - *man-made productive:* factories, roads, trucks, airports, ports, highways, machines, pipes... - *human:* knowledge, skills, experiences, special gifts, resilience, health, population - *financial:* foreign currency, bank reserve, cash flow, budget, surplus or deficit - *technology:* R&D ability, status of science and technology, potential of new breakthrough - *social relationship:* friends, family, trust level, social norms = needs observed with Maslow's Hierarchy of Needs (from descending order of importance): 1. *self-actualization:* desire to become the most that one can be 2. *esteem:* respect, self-esteem, status, recognition, strength, freedom 3. *love and belonging:* friendship, intimacy, family, sense of connection 4. *safety needs:* personal security, employment, resources, health, property 5. *physiological needs:* air, water, food, shelter, sleep, clothing, reproduction = well-being refers to the quality of life beyond meeting the basic needs - economic activity is not the only means - well-functioning economy operates to increase well-being of all members *dimensions:* physical, emotional, financial, social, occupational, spiritual, intellectual, environmental *perception:* what is most valued differs from person to person *trade-offs:* decision-makers make trade-offs to achieve goals through scarcity and opportunity cost - involves current and future generations *side effects:* unintended consequence of achieving a goal; characterized with positive and negative externality = traditional economic goals spans from individual to social goals *increasing income/wealth:* measured with Gross Domestic Product (GDP) - higher income $arrow.double$ higher quality of life - necessary to improve well-being of the poor - problems: - limit to growth - cost of expansion: depletion of resource, climate change, extinction of non-human species - "Earth Overshoot Day": date when humanity has exhausted nature's budget for the year #image("traditional_economic_goals.png") *efficiency:* use maximum value of resources to achieve a desired result; producing the maximum value of output from a given set of input - optimizing use of resources - market value used as standard - disproportionate allocation of resources - emphasizing efficiency may result in a group of people who are neglected in other areas of well-being *others:* 1. full employment 2. price stability 3. equitable distribution of income 4. economic freedom 5. balance of trade 6. economic security = economic goals considering well-being not all goals can be achieved at the same time - some goals reinforce each other while others conflict with one another - conflicts include: unintended consequences & conflict of interests - social goals should echo the needs and well-being of individual and beyond *differences from traditional economic goals:* - focuses more on intangible metrics - harder to quantify and achieve with just money *top goals of Singapore:* 1. mental health 2. increasing wealth equity 3. providing equal opportunity *goals:* 1. *satisfaction of basic physical needs:* including nutrition and care adequate for survival, and a comfortable living environment 2. *security:* assurance that one's basic needs will continue to be met throughout all stages of life and security against aggression or unjust persecution 3. *happiness:* adequate opportunity to experience feelings of contentment, pleasure, enjoyment, and peace of mind 4. *ability to realize one's potential:* including physical, intellectual, social, aesthetic, and spiritual potential 5. *a sense of meaning:* purpose to one's life 6. *fairness:* fair and equal treatment by others and within social institutions 7. *freedom:* ability to make personal decisions while not infringing on the freedom of others 8. *participation:* opportunity to participate in the processes in which decisions are made that affect one's society 9. *good social relations:* having satisfying and trustful relaations with friends, family, fellow citizens, and business associates and peaceful relations among larger groups (like nations) 10. *ecological balance:* protecting naturala resources and restoring them to a healthy state = economic activities 1. *resource management:* preserving or improving resources that contribute to the enhancement of well-being 2. *production:* conversion of resources into usable products, either goods or services 3. *distribution:* sharing of products and resources among people 4. *consumption:* process by which goods and services are put to final use by people = basic economic questions 1. what should be produced? 2. how should production take place? 3. from whom should economic activity be undertaken? = spheres of economic activity == core earliest sphere of economic activities; comprised of households, families, and informal community groups - involves raising children, preparing meals, maintaining homes, taking care of the mildly ill, and organizing many activities among family members, friends, and neighbors *key characteristics:* work is not paid and respond to needs and waits (instead of the ability to pay for) *importance:* crucial for maintenance and flourishing of any economy; of important economic and social value (equal to $gt.eq 25%$ of country GDP) *limitations:* unequally assigned between genders (women do majority of unpaid household labor) and limited scales *action:* single action to support those who have provided "free" goods and services in the core sphere == public purpose comprised of the government and NGOs like charities, religious organizations, professional associations, and international institutions *key characteristics:* for an explicit purpose related to the #underline("public good") and NOT for profit *public good:* non-rivalrous and non-excludable *examples:* local police force, national defense, public roads, systems of laws and courts, poverty relief, healthcare and education, protection of environment *strengths:* provides important goods and services and provide jobs *weaknesses:* concerns for efficiency, impersonal ("one size fits all"), concerns for accountability (corruption), low quality of services, focusing on particular groups or communities == business comprised of firms that produce goods and services for profitable sale; makes up the majority of spending *market:* follows three potential definitions 1. markets as places to buy and sell - market is a physical or virtual location where people go to buy and sell things 2. markets defined by product categories - market is the interaction of buyers and sellers defined within the bounds of broad product categories - e.g. real estate or stock market 3. markets as an economic system - economic system that relies on markets to conduct many activities - alternative is planned economy - key characteristic: profit-driven *advantages of market as an economic system:* 1. business efficiency: government creates legislation that places limits on activities that detract from a competitive environment and regulate how businesses treat customers and workers to maximize efficiency; measured in costs and profits 2. increased productivity: increased motivation to earn more money to supply needs 3. innovation for a competitive edge: encouraged to innovate to gain competitive advantaage and increase market share; increases variety of goods and services at lower costs that benefit customers 4. consumer choice 5. flexibility *disadvantages of market as an economic system:* 1. inequality: unequal distribution of resources or income among individuals 2. externalities: negative or positive effects on society due to economic decisions of producers and consumers; negative inclludes polution 3. public goods: public goods may not be provided by private producers as it is unprofitable 4. merit goods: goods that are under-consumed and under-produced due to information failure such as education and health services; under-allocation fo resources for these goods 5. demerit goods: goods thaat are overconsumed and overproduced due to information failure such as cigarettes and junk food; overallocation of resources 6. market failures: free markets that fail to allocate resources in a socially desirable way due to lack of government intervention; such as imperfect information, market imperfections, short-term focus of firms on maximizing profits = institutional requirements for markets what is necessary for markets to run smoothly *institutions:* "connections" in the system; way of structuring human activities based on customs, norms, infrastructure, and laws 1. private property 2. social institutions of trust 3. infrastructure that allows for the flow of goods and information 4. money as a medium of exchange == private property exists both formally, in codes of law, and informally, in social and cultural norms *ownership:* defiend through systems of property rights set out in law and enforced by courts and police == social institutions of trust trust between buyer and seller; measured using World Value Survey, lost wallet experiment, trust game *building trust:* - establishment of direct relationship - reputation - social norms and common codes (ethical and religious) - special legal structures (explicit or implicit contracts) == infrastructure that allows for flow of goods and information physical infrastructure for transportation and storage of goods and for information to flow freely == money as a medium of exchange cash, checks, credit cards, debit cards, and electronic payment systems - money is created or sanctioned by national governments = pro-market vs anti-market incredibly polarized; requires evaluation of market outcomes in a case-by-case basis using the spheres of economic activity *categories:* 1. limited government involvement 2. significaant government involvement 3. provision from nonmarket institutions is necessary = negotiation strategies self interest is the main motivation for human behaviors and negotiation strategies exist to achieve one's goals; barter and trade = complex systems *properties:* 1. complex collective behavior: comprises of large networks of individual components following simple rules without central control or leader - simple rules $arrow$ only participate in the trade when there is net benefit - results in unpredictability 2. signaling and information processing: systems produce and use information and signaals from both internal and external environment - used to tell systems to change and adjust 3. adaptation: systems change their behavior to improve chances of survival or success through evolutionary processes = microeconomic market model comprised of 2 market outcomes: market price & market quantity sold and 2 market players: buyers & sellers - buyers and sellers interact voluntarily in markets to increase own well-being #align(center)[ #image(width: 50%, "microeconomic_market_model.png") ] *types of markets:* #image("market_types.png") == theory of supply represents the relationship between price and quantity supplied *supply schedule:* table distribution of the relationship *supply curve:* plotting the data points of the supply schedule - if price and quantity supplied has positive relationship $arrow$ higher price leads to more coffee supplied - can go from individual to market #image(width: 70%, "supply_price.png") *key distinction:* - change in price $arrow$ change in quantity supplied - nonprice determinant supply $arrow$ change in supply #image("distinction.png") *nonprice determinants of supply:* all result in shifts in the supply curve - available technology of production - input/resource prices - number of sellers - producer expectations about future prices and technologies - prices of related goods and services - changes in physical supply of natural resource == theory of demand relationship between price and quantity demand *(effective) demand:* willingness to buy and ability to pay *demand schedule:* table distribution of the relationship *demand curve:* plotting of demand schedule - inverse relationship $arrow$ lower prices leads to more demand *key distinction:* - change in price $arrow$ change in quantity demanded - nonprice determinants of demand $arrow$ change in demand #image("demand_distinction.png") *nonprice determinants of demand:* changes in demand is a side effect of price changing - tastes and preferences - incomes and/or available assets - availability and prices of related goods and services - substitute goods $arrow$ used in place of another - complementary goods $arrow$ used along with another - consumer expectation about future prices and incomes - number of consumers = theory of market adjustment market forces tend to make $p$ and $q$ towarads the equilibrium point *surplus:* quantity supplied exceeds quantity demanded at a given price - free market $arrow$ sellers adjust price to clear their stock #image(width: 65%, "surplus.png") *shortage:* quantity demanded exceeds quantity supplied at a given price #image(width: 70%, "shortage.png") *equilibrium:* quantity supplied is equal to the quantity demanded, no pressure on prices or quantity to change #image(width: 65%, "equilibrium.png") *critiques:* - adjustment has no time window; markets are independent of one another - dealing with surplus/shortage: price adjustment is not always the solution - forces to combat equilibrating tendency of market forces: - unwillingness/inertia/too costly to adjust - cost of changing prices is high - pricing strategies such as markup pricing, loss-leaders pricing, and price discrimination - government interventions = consumer and producer surplus #image(width: 60%, "fully_annotated.png") *consumer benefits:* consumers obtain "psychic benefits" from their purchases - any consumer considering purchasing aa good or service has a maximum willingness to pay for it *consumer surplus:* difference between consumer's maximum willingness to pay and price - net psychic benefit consumers obtain from their purchases *annotating demand curves:* each point of a demand curve is a consumer's maximum willingness to pay // #image(width: 70%, "consumer_surplus.png") #image("consumer_surplus_annotation.png") *producer benefits:* defined by profits; surplus = profits *annotating supply curves:* supply curves tell us marginal cost of providing each unit *producer surplus:* difference between price and marginal cost // #image(width: 70%, "producer_surplus.png") #image(width: 80%, "producer_surplus_annotated.png") = social efficiency allocation of resoruces that maximizes the net benefits to society; not the same as maximizing well-being; effectively moving towards market equilibrium - ties into welfare economics: estimating social welfare of different scenarios to determine ways to maximize net social benefits - provides understanding when markets work well and when markets fail - goal: total net benefits to society, not distribution; maximizing total benefits, not fairness; market value, not social value == price ceilings maximum allowable price, normally set below market equilibrium price with the goal to help certain groups of consumers by keeping prices low - reduces overaall market efficiency (deadweight loss); increases customer surplus but decreases producer surplus - equity concerns used to justify price ceiling, especially if deadweight losses are relatively minor #image("price_ceiling.png") == price floors minimum allowable price, normally set above market equilibrium price with goal to aid producers - creates deadweight loss; increasing producer surplus but decreasing consumer surplus - economic goals other than (welfare) efficiency used to justify price floors #image("price_floor.png") == welfare analysis 1. identify intervention 2. compare equilibrium price with targeted price 3. compare equilibrium quantity supplied/demanded with resulted one 4. compare total welfare, consumer surplus, and producer surplus 5. analyze if intervention can be justified: - who are affected and to what extent? - consideration of other goals - magnitude of deadweight loss (elasticity of demand/supply curve) === policy inferences from welfare analysis welfare analysis lends support for free markets - intervention generally decreases social welfare - government interventions should be limited to what is absolutely necessary - efficiency sometimes viewed as objective policy goal - focus on efficiency $arrow$ existing distribution of resources is acceptable *support for government intervention:* - maximizing efficiency considers only overall benefits, not allocation of benefits - other goals than economic efficiency like fairness, social justice, sustainability - unregulated market can be inefficient *market failure:* occurs when markets fail to maximize social efficiency - when externalities are present, when consumer behavior is irrational, when some market participants have excessive power, when competition is sufficient - government intervention justified on efficiency grounds in times of market failure = shifts in supply and demand market forces will push the prices and quantities towards the equilibrium when supply and demaand changes in a certain market - when supply curve shifts, equilibrium price and quantity move in opposite directions - when demand curve shifts, equilibrium price and quantity move in same direction - when both shift, one of changes is ambiguous = shortage, scarcity, and inadequacy *shortage:* imbalance between effective demand and supply *scarcity:* general condition - imbalance between what is available and what people should have *inadequacy:* not enough of a good or service at affordable prices for people to meet minimal requirements for well-being = globalization percentage of global economic production traded internationally has increased in recent decades == trade, specialization, and productivity *free trade:* exchange in international markets that is not regulated or restricted by government actions - mercantillism: trade surplus is most desirable - policy implication: promote export and place restrictions on imports to ensure a trade surplus - <NAME>: trade increase productivity - policy implication: less government involvement in the economy and reduction of trade barriers === benefits of free trade 1. efficiency gains from trade: consumption beyond PPF and lower prices for consumers 2. exchange relations giving producers incentive to be productive: efficient allocation of resources and capitals; competition and innovation 3. trade encourages technology transfers across countries 4. trade increases the opportunity for economics of scale to be realize 5. trade encourages peaceful relations among countries: Marshall Plan of USA #image(width: 65%, "economies_of_scale.png") *measures of trade:* sum of imports and exports *measures of conflict:* intensity-weighted sums of conflictive events *reverse relationships:* supports the contention that higher level of trade are associated with lower level of conflict === drawbacks of free trade 1. efficiency: vulnerability and lock-in 2. inequality: income inequality 3. sustainability: production/transportation/pollution exporting; race to the bottom *vulnerability & lock-in:* countries more vulnerable to actions of trading partners - as importer: supplies of commodities; inputs for manufacturing; essential resources - as exporter: markets for what you sell - countries that heavily rely on sales of single/few export goods are vulnerable to: - market/price fluctuations - climate change - protectionism: variety of strategies countries follow to limit volume of trade with their trading partners and protect domestic industries from foreign competition - import substitution: policy to reduce reliance on imports and encourage domestic industry - tariffs: taxes on imported goods; account for significant % of tax revenue in developing countries - quotas: import quantity limits - subsidies: encourage more production - administrative obstacles: raise production standards for limiting trade with countries not meeting them - lock-in: specialization locking a country into a production pattern that becomes inefficient *sustainability:* - negative externalities from production like pollution $arrow$ net benefit of trade is ambiguous - race to the bottom: countries compete for export market or for FDI may lower environmental/labor/social standards to gain a cost advantage - transprotation of goods: contributes to pollution - exporting pollution: reducing domestic manufacturing & associated pollution $arrow$ pollution in the other country instead *political:* winners and losers in a trade - efficiency gains from free trade vs redistribution impacts - globalization affects wage inequality == theory of comparative advantage *opportunity cost:* how much of one good must be given up in order to produce some of the other goods *comparative advantage:* ability to produce some good or service at a lower opportunity cost than other producers *principle of comparative advantage:* a nation should specialize in those goods and services for which it has a comparative advantage over its trading partners, and trade other goods and services *sources of comparative advantage:* 1. quantity and quality of natural resources available 2. demographics: education, age, women's rights 3. rate of capital investment including infrastructure 4. increasing returns to scale and division of labor 5. investment in research & development 6. fluctuations in exchange rate 7. import controls like tariffs, export subsidies, and quotas 8. non-price competitiveness of producers 9. institutions *comparative advantages of Singapore:* - 1965: domestic market oriented - printing & publishing, F&B, manufacturing - 1980s: export oriented - petroleum refining, marine equipment, electronic products and components - 2000s: main value added items - computer, electronic, and optical products, pharmaceutical and biological products, marine equipment, machinery and equipments - 2023: new growth areas - AI and digitization, green and sustainable solutions, precise medicine = historical perspectives on economic behavior == classical economic views of human nature human nature is complex and human motivations are mixed; most people act in self-interest and to their advantage, not social motives - under certain conditions, self-interest does not lead to social welfare maximization - people desire to have self-respect and the respect of the others - may act in certain (good/bad) ways to others == neoclassical model incorporated new insights on marginal utility and subjective nature of value; refines and formalizes classical economic theories - emphasizes mathematical models, market equilibrium, and rational behavior of individuals - taking narrower view of human motiviations - bsed on assumptions like rationality: rational economic man maximizes his utility *axioms of rationality:* 1. completeness: for x and y, an individual either weakly prefer x to y or y to x - individuals are able to rank their preferences 2. transitivity: if an individual prefers x to y, and y to z, then they prefer x to z - individual preferences are consistent *criticisms:* - unsure if it's a descriptive or prescriptive model - whether the assumption of rationality is overly simplified - due to limited information, limited cognitive ability, or self-control - whether the asdsumption of maximizing behavior is correct - human motivation is much more complex == modern perspectives on economic behavior examines people's choice of goals and actions taken to achieve them, including the constraints and influences that affect their choices and actions - evidence-based approach, challenging assumption of rationality - explains irrational behavior #text(size: 9pt)[ #table( columns: (1fr, 1fr), inset: 4pt, align: horizon, table.header( [assumptions], [evidence] ), [individuals have complete preferences for different options], [individuals do not know what they like], [individuals have consistent and stable references], [preferences are context sensitive and easily influenced], [individuals can make choices based on rational preferences], [individuals having difficulties to make good choice] ) ] === systems of thinking 1. automatic (95%): gut reaction - uncontrolled, effortless, associative, fast, unconscious, skilled 2. reflective (5%): conscious thought - controlled, effortful, deductive, slow, self-aware, rule-following === nudge any aspect of the choice architecture that alters people's behavior in a predictable way without forbidding any options or significantly changing their economic incentives - steer individuals towards making better choices for themselves or society without imposing mandates or bans == heuristics & behavioral biases *anchoring effect:* people are inclined to rely on first piece of information they received in the past to judge the value of the product in the future - involved in negotiation and reputation - bias occurs when adjustments are insufficient - anchors serve as nudges *availability heuristic:* people assess likelihood of risks by asking how readily examples come to mind - personal experience, recent events, anecdotes, news - biased assessment of risk can negatively influence responses to crisis, investment, opportunities - overcome by using nudges: increasing fear by reminding them, reducing fear by referring to empirical data, increasing confidence *representativeness:* making a choice based on predictable answers/stereotypes - misperceptions of patterns - ignores base rate information - similarity and frequency sometimes diverge so stereotypes may not be true - hot hand fallacy: believing in "winning streaks" *optimism and overconfidence:* unrealistic optimism with everyone thinking they are above average - results in unfounded risk taking behavior - benefits from nudging back in the right direction *status quo bias:* tend to follow what is the norm - nudging at work with a "default option" *temptations:* dynamically inconsistent behaviors - tempting when more consumed than another - no implications that decisions made are better - lack of appreciation for how much desire and behavior is altered when under "arousal" - resistance: effective planning for the future *social influence:* easily influenced by statements and deeds by others - based on information and social pressure - conformity is a strong force in shaping decisions - social influence is a good nudge == cognitive bias just because individuals do not ALWAYS make rational choices, does not mean rationality should be abandoned - social planners use nduges to induce desirable decisions even if people use only System 1 thinking - using System 2 to make deliberate and informative decisions is beneficial - increases awareness - forces you to slow down - rely on data and empirical data over gut feeling - seek feedback from others and reflect on decision making - allows use of decision-making frameworks
https://github.com/spherinder/ethz-infk-thesis
https://raw.githubusercontent.com/spherinder/ethz-infk-thesis/master/src/dependencies.typ
typst
#import "@preview/glossarium:0.4.2": *
https://github.com/david-davies/typst-prooftree
https://raw.githubusercontent.com/david-davies/typst-prooftree/main/README.md
markdown
MIT License
# Prooftrees This package is for constructing proof trees in the style of natural deduction or the sequent calculus, for `typst` `0.7.0`. Please do open issues for bugs etc :) Features: - Inferences can have arbitrarily many premises. - Inference lines can have left and/or right labels¹ - Configurable² per tree and per line: premise spacing, the line stroke, etc... . - They're proof trees. ¹ The placement of labels is currently very primitive, and requires much user intervention. ² Options are quite limited. ## Usage The user interface is inspired by [bussproof](https://ctan.org/pkg/bussproofs)'s; a tree is constructed by a sequence of 'lines' that state their number of premises. [`src/prooftrees.typ`](src/prooftrees.typ) contains the documentation and the main functions needed. The code for some example trees can be seen in `examples/prooftree_test.typ`. ### Examples A single inference would be: ```typst #import "@preview/prooftrees:0.1.0" #prooftree.tree( prooftree.axi[$A => A$], prooftree.uni[$A => A, B$] ) ``` <picture> <img src="https://github.com/david-davies/typst-prooftree/blob/main/examples/Example1.png" width="30%" /> </picture> A more interesting example: ```typst #import "@preview/prooftrees:0.1.0" #prooftree.tree( prooftree.axi[$B => B$], prooftree.uni[$B => B, A$], prooftree.uni[$B => A, B$], prooftree.axi[$A => A$], prooftree.uni[$A => A, B$], prooftree.bin[$B => A, B$] ) ``` <picture> <img src="https://github.com/david-davies/typst-prooftree/blob/main/examples/Example2.png" width="40%" /> </picture> An n-ary inference can be made: ```typst #import "@preview/prooftrees:0.1.0" #prooftrees.tree( prooftrees.axi(pad(bottom: 2pt, [$P_1$])), prooftrees.axi(pad(bottom: 2pt, [$P_2$])), prooftrees.axi(pad(bottom: 2pt, [$P_3$])), prooftrees.axi(pad(bottom: 2pt, [$P_4$])), prooftrees.axi(pad(bottom: 2pt, [$P_5$])), prooftrees.axi(pad(bottom: 2pt, [$P_6$])), prooftrees.nary(6)[$C$], ) ``` <picture> <img src="https://github.com/david-davies/typst-prooftree/blob/main/examples/Example3.png" width="30%" /> </picture> ## Known Issues: ### Superscripts and subscripts clip with the line The boundaries of blocks containing math do not expand enough for sub/pscripts; I think this is a typst issue. Short-term fix: add manual vspace or padding in the cell. ## Implementation The placement of the line and conclusion is calculated using `measure` on the premises and labels, and doing geometric arithmetic with these values.
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/shape-circle_04.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Radius wins over width and height. // // Error: 23-34 unexpected argument: width // #circle(radius: 10pt, width: 50pt, height: 100pt, fill: eastern)
https://github.com/julyfun/typst-internship-report
https://raw.githubusercontent.com/julyfun/typst-internship-report/main/1.typ
typst
#set text(lang: "zh") #set page( margin: ( top: 2.54cm, bottom: 2.54cm, left: 3.17cm, ), header: [ #set text(fill: gray) #align(center, [*SPEIT 2024 Operational Internship Report*]) #line(length: 100%) ], numbering: "I" ) #set text(12pt, font:("Times New Roman", "Songti SC")) //会自动匹配前面的是英语字体,后面的是中文字体 #show strong: set text(weight: 900) // Songti SC 700 不够粗 #set par(leading: 1.5em) #figure(image("image.png", width: 80%)) // 局部作用域 #[ #set text(28pt, font: ("Times New Roman", "Heiti SC")) #set par(leading: 0.5em) #align(center, [Operational Internship Report\ *认知实习报告* ]) ] \ \ #[ #import "@preview/cuti:0.2.1": show-cn-fakebold #set text(14pt) #show: show-cn-fakebold #show table.cell: it => { if it.x == 0 { strong(it) } else { align(center, underline(it)) } } #set table(stroke: (thickness: 0.5pt, dash: "densely-dashed", paint: gray)) #set text( font: ("Times New Roman", "FZKai-Z03S") ) #table( columns: (1fr, 1.5fr), inset: 10pt, align: horizon, [学号 / Student ID], [ 521260910018 ], [姓名 / Name], [方俊杰], [专业 / Major], [信息工程], [实习单位 / Company], [上海舞肌科技有限公司], [实习职位 / Position], [软件开发实习生], [实习时间 / Duration], [ 2024.6 - 2024.8 ], [校内导师 / SPEIT Tutor], [ 吉宏俊 ], [企业导师 / Enterprise Tutor ], [ 潘韫哲 ], ) ] #pagebreak() #[ #set text(16pt, font: ("Times New Roman", "Heiti SC")) #align(center, [*摘 要*]) ] La téléopération d'un bras robotique consiste à installer des capteurs sur la main humaine et à transmettre des signaux au bras robotique afin qu'il puisse imiter de manière synchrone les mouvements de la main humaine. La téléopération a été largement étudiée et appliquée ces dernières années dans des domaines tels que la médecine, le sauvetage, l’espace et l’apprentissage automatique. La principale motivation de la téléopération est d'utiliser la réaction humaine, la créativité et la précision de la structure mécanique et du contrôle pour permettre aux systèmes robotiques d'effectuer des tâches complexes. Par exemple, la téléopération peut être utilisée pour contrôler à distance des robots chirurgicaux maître-esclave afin de réduire la fatigue chirurgicale des médecins et d'améliorer la précision chirurgicale. La téléopération joue un rôle important dans la collecte de données pour l'apprentissage par imitation, non seulement en fournissant une manipulation précise et fine (manipulation) ; données et fournir des trajectoires naturelles et fluides pour progresser dans l'apprentissage par renforcement des robots humanoïdes. Les systèmes d'exploitation à distance existants présentent de nombreux problèmes, notamment une latence élevée, une grande gigue des terminaux, des risques de collisions et des difficultés d'expansion. Les domaines d'opérations de précision tels que les robots chirurgicaux médicaux ont une tolérance extrêmement faible à la gigue des effecteurs terminaux des bras robotiques. La gigue physiologique peut également provoquer l'échec des opérations à distance. Des retards plus élevés entraîneront des retours opérationnels intempestifs de la part des opérateurs à distance, augmentant ainsi la difficulté ; du fonctionnement de l'opérateur et de la cohérence de la trajectoire ; de plus, la plupart des systèmes sont couplés à un environnement de déploiement spécifique et ne peuvent fonctionner à la fois dans l'environnement virtuel et dans le monde réel, et il est également difficile de migrer les capteurs et la robotique matériel de bras. Cette recherche est basée sur le capteur HTC VIVE Tracker et le bras robotique à six axes Aubo pour fournir une solution de téléopération de bras robotique à faible couplage, à faible latence, à faibles vibrations et hautement évolutive, utilisant le positionnement intérieur laser Lighthouse, l'interpolation en ligne, Des technologies telles que le filtrage et la génération de mouvement résolvent les problèmes mentionnés ci-dessus. #[#set text(14pt, font: ("Times New Roman", "Heiti SC")) *关键词:*] #[#set text(14pt) système temps réel, évitement des collisions, opération à distance] #pagebreak() #outline(title: "目录", indent: 1.5em) #pagebreak() // [正文设置] #set page(numbering: "1") #counter(page).update(1) #counter(figure).update(1) #set par(first-line-indent: 2em) #set heading(numbering: "1.1") #let fakepar=context{box();v(-measure(block()+block()).height)} #show heading: it=>it+fakepar #show figure: it=>it+fakepar #show math.equation.where(block: true): it=>it+fakepar #show heading: it => { set text(font: ("Times New Roman", "Heiti SC")) h(-2em) it v(1em) } #show heading.where(level: 1): it => { set text(font: ("Times New Roman", "Heiti SC")) align(center)[#it.body] } #show figure.caption: it => { set text(10pt) it } // [正文] = 第一章 绪论 == 引言 机械臂的遥操作 (teleoperation) 指在人手上安装传感器并传输信号给即机械臂,使之同步模仿人手动作。遥操作近年来被广泛研究并应用于医学、救援、太空和机器学习等领域。遥操作的主要动机是利用人的反应力、创造力和机械结构和控制的精确性,使机器人系统执行复杂任务。例如,遥操作可用于远程控制主从式手术机器人,以减少医生的手术疲劳和提高手术精度@Tremor;遥操作在模仿学习的数据收集中扮演了重要角色,不仅提供准确且精细的操纵 (manipulation) 数据,而且提供了自然且流畅的轨迹,以推动人形机器人强化学习领域的进步@opentv。 现有的遥操作系统存在许多问题,主要包括延迟高、末端抖动大、易发生碰撞、难以扩展等。医学手术机器人等精细操作领域对机械臂末端执行器的末端抖动容忍度极低,即生理性抖动也可能造成远程操作手术的失败@Tremor;较高的延迟会导致远程操作者的操作反馈不及时,从而增加了操作者的操作难度和轨迹的连贯度;另外,大部分系统与一个特定的部署环境耦合,无法同时在虚拟环境和现实世界中运行,也难以进行传感器和机械臂硬件的迁移。 本研究基于 HTC VIVE Tracker 传感器和遨博 (Aubo) 六轴机械臂,提供一种低耦合、低延迟、低振动、高拓展的机械臂遥操作解决方案,利用了 Lighthouse 激光室内定位、在线插值、滤波、运动生成等技术,解决了上述提到的问题。 // == 本研究主要内容 // 不知道 // = 第二章 相关工作 // == // 不知道 = 第二章 遥操作系统 == 系统概述 本研究旨在开发一个系统流程,实现将人手根部姿态实时、低延迟地迁移至机械臂末端,并减弱生理性抖动,同时保证运动过程中的精确和无碰撞。本系统具备单臂和多臂的灵活性,既支持对单一机械臂进行操作,也可同时接收多个传感器的信息并控制多个机械臂,实现多地远程协作功能。此外,本系统各模块之间独立运行,方便迁移到其他机械臂或传感器硬件平台,并同时支持操作仿真机械臂和现实世界机械臂。 #figure(image("image copy.png", width: 90%), caption: "遥操作系统架构") <sys> 如上图所示,本系统主要由感知硬件、算法和执行器三部分组成。 == 系统硬件 公司配备了多台可供测试的 Aubo I5 型号机械臂,每个机械臂具有六个关节自由度,臂展 1008mm,控制频率为 200Hz。厂商提供了基于 TCP 通信的广播机制,可以 200Hz 频率从控制柜获取机械臂内部信息。我们将两台机械臂以镜像方式安装在同一工作台上,中心距离 1100mm,以模拟多机械臂协作的场景。 手臂末端传感器采用 HTC 公司开发的 VIVE Tracker,包含可佩戴于手腕处的追踪器和两个 Lighthouse 基站。Lighthouse 室内定位技术不需要借助摄像头,而是在追踪器上安装了多个光敏传感器,通过接收基站发射的激光束,计算出追踪器的六自由度姿态。VIVE Tracker 传感器的测量精度为 0.2mm,角度精度为 0.1°,采样率为 90Hz。其拥有较高的定位精度,但输入频率无法直接满足实时控制需求。 == 系统特点 === 低延迟 为了规避碰撞,现有的机械臂遥操作系统大多基于离散的运动规划,由于运动规划所需的时间较久,算法只能以较低频率规划出未来一段时间的连续轨迹(包含多个路点),即使使用 Nvidia GPU 加速的 CuRobo 库,也需要 50ms 以上进行轨迹规划,基于 CPU 的轨迹规划耗时甚至可能超过 3 秒@curobo,引入了较高延迟。本文通过提出一种基于运动学逆解 (Inverse Kinematics, IK) 的在线轨迹规划和插值算法,实现了低延迟的连续轨迹规划,使机械臂末端能够实时追踪人手根部的姿态。尽管运动数据进行了多级 TCP 和 ROS2 Topic 转发,信号传输的总延迟仍为毫秒级,VIVE Tracker 的低延迟位姿捕获也有助于降低遥操作的总延迟。 === 无碰撞 完全基于 IK 运动规划可能导致机械臂发生自碰撞和与物体的碰撞(如其他机械臂和桌面)。设备碰撞可能导致机械臂失控,造成人员伤害和物资损失。本系统包含了碰撞检测模块,能对计算得到的关节角度指令发布前,对未来的运动轨迹进行碰撞检测,仅在碰撞可能发生时调用基于 OMPL 的轨迹规划算法生成无碰撞路点,在保障低延迟的同时,规避与环境物体的碰撞,保障操作者的安全。 === 低振动 在不使用传统轨迹规划算法的情况下,运动学逆解可能导致关节角度的加速度极大或加速度不连贯;同时,操作者手臂末端的生理性抖动也可能传递到机械臂末端,导致机械臂末端的明显抖动。在线插值算法的特性能平滑连接任意多个路点,减弱关节角度加速度的突变,避免关键伺服电机的过载;同时,本算法对传感器的输入噪声进行了频率分析,并采用卡尔曼位置滤波和 $"SO"(3)$ 空间中的低通滤波插值,减弱了抖动噪声成分。 === 任意机械臂和传感器配置 如 @sys 所示,本系统高度模块化,各模块可以通过 TCP 协议、ROS2 Topic 或 TF2 进行通讯,使用者可以根据机械臂的运动学模型文件和传感器通讯接口,快速迁移到其他硬件平台,并支持多传感器-多机械臂配置。本系统同时支持真机运行和虚拟环境运行。在虚拟环境中,可以便利地调试算法的正确性和安全性。 == 系统架构 本系统主要由手部姿态检测模块、标定模块和运动规划模块组成。各模块之间通过 TCP 协议或 ROS2 Topic 以及 TF2 进行通讯,可以部署在不同机器上,解放机器算力需求。例如,本系统的手部姿态检测模块部署在对 VIVE Tracker 传感器驱动更友好的 Windows 10 机器上,而标定模块和运动规划模块则部署在部署 ROS2 框架更便利的 Ubuntu 22.04 机器上,两台机器通过 TCP 协议传输数据。 === 手部姿态检测模块 机械臂遥操作的目标是使机械臂末端姿态与人手根部姿态同步,因此传感器需要捕获人手根部的姿态。我们考虑了使用纯视觉的神经网络方案和使用 HTC VIVE Tracker 的 Lighthouse 室内定位技术方案。 1) MidiaPipe Hands 手部检测器 这是一种基于 MidiaPipe (用于构建跨平台机器学习解决方案) 的实时设备上的手部跟踪解决方案,该方案可以从单张的 RGB 图像中预测人体的手部骨架,并且可以用于 AR/VR 应用,且不需要专用硬件,例如深度传感器@zhang2020mediapipehandsondevicerealtime。 #figure(image("image copy 5.png", width: 50%), caption: "MidiaPipe 手部跟踪效果") <img5> 尽管该方案可以在普通设备上实时运行,但其延时较大且精确度一般,结果抖动较大,不足以直接作为运动规划的目标点。同时,图像坐标系中的手部关键点难以转换为运动规划所需的手根-相机相对位姿,如果使用 PnP 等算法获取手根位姿,会引入额外误差,并且结果依赖于相机内参,拓展性较差。Hand3D@zimmermann2017learningestimate3dhand 提出了将人手 RGB 图像直接转换为手部姿态的方案,但精度仍有限制,对于机械臂末端的精确运动并不适用。 2) 可穿戴的 HTC VIVE Tracker 设备 该设备使用 Lighthouse 激光室内定位技术,可提供毫米级和位置信息和 0.1° 级别的姿态信息,频率高,延迟低。将其穿戴于手腕上,并在 0.3m 范围内以 0.5Hz 左右频率来回运动,其捕获到的原始位置数据可视化如@hand 所示。 #figure(image("image copy 2.png", width: 80%), caption: "VIVE Tracker 捕获的原始手腕位置") <hand> 可以看出,VIVE Tracker 给出的位置轨迹较为平滑。本文采样了多组样本并对其计算 FFT,如@img3 所示。 #figure(image("image copy 3.png", width: 80%), caption: "VIVE Tracker 位置数据(Z 轴)的频谱分析") <img3> 如图所示,图中 0.5Hz 峰值处为固定周期来回摆动造成的较大分量。可见人手的抖动信号没有固定周期,无法通过低通滤波器去除,因此我们采用了卡尔曼滤波器对位置数据进行处理。 卡尔曼滤波可以通过融合观测信号的和状态预测来估计干净信号。在每个时间步骤上,卡尔曼滤波执行预测和更新两个步骤。预测步骤使用状态转移方程来估计下一时刻的状态,而更新步骤则使用观测数据来对预测状态进行校正。 建模时,我们对 VIVE Tracker 给出位置数据的 $X, Y, Z$ 轴分别建立为匀速运动模型。我们有状态 $X = [x, y, z, v_x, v_y, v_z]$,有: $ x_k = x_(k - 1) + v_(x (k - 1)) Delta t \ y_k = y_(k - 1) + v_(y (k - 1)) Delta t \ z_k = z_(k - 1) + v_(z (k - 1)) Delta t \ v_(x(k)) = v_(x (k - 1)) space.quad v_(y(k)) = v_(y (k - 1)) space.quad v_(z(k)) = v_(z (k - 1)) $ 预测步骤:$k$ 时刻的预测值: $ x_k^- = F(tilde(x)_(k - 1)) $ 其中 $tilde(x)_(k - 1)$ 为上一时刻的最优估计值,转移矩阵: $ F = mat( 1, 0, 0, Delta t, 0, 0; 0, 1, 0, 0, Delta t, 0; 0, 0, 1, 0, 0, Delta t; 0, 0, 0, 1, 0, 0; 0, 0, 0, 0, 1, 0; 0, 0, 0, 0, 0, 1; ) $ 先验误差协方差矩阵 $P_k^- = F P_(k - 1) F^T + Q$,其中 $Q$ 为过程噪声矩阵。 更新步骤:计算卡尔曼增益 $K = P_k^- H^T (H P_k^- H^T + R)^(-1)$,其中 $R$ 为观测噪声矩阵,$H$ 为观测矩阵,有: $ H = mat( 1, 0, 0, 0, 0, 0; 0, 1, 0, 0, 0, 0; 0, 0, 1, 0, 0, 0; ) $ 则最优估计值 $tilde(x)_k = x_k^- + K(z_k - H x_k^-)$,其中 $z_k$ 为 $3 times 1$ 的观测向量。 后验误差协方差矩阵 $P_k = (I - K H) P_k^-$。取: $ Q &= mat( 0.1, 0, 0, 0, 0, 0; 0, 0.1, 0, 0, 0, 0; 0, 0, 0.1, 0, 0, 0; 0, 0, 0, 100, 0, 0; 0, 0, 0, 0, 100, 0; 0, 0, 0, 0, 0, 100; ) \ R &= mat( 50, 0, 0; 0, 50, 0; 0, 0, 50; ) $ 在每次获得 VIVE Tracker 的位置数据后进行预测和更新,从而降低原始观测信号的噪声。经过卡尔曼滤波的位置数据 FFT 如@img4 所示: #figure(image("image copy 4.png", width: 80%), caption: "经过卡尔曼滤波后的 VIVE Tracker 位置数据(Z 轴)的频谱分析") <img4> 由于卡尔曼滤波器具有预测功能,本系统还可以启动针对位置的预测,在必要时使机械臂在匀速运动过程中的位置与人手保持高度一致。但该功能会导致对加速度的跟随产生较大延迟,从而在输入位置急加速或急减速时发生超出目标位置的位移,因此预测是可选的。姿态抖动方面,我们使用将输入数据的姿态使用 $"SO"(3)$ 群低通滤波器插值实现@affine。位姿的滤波可以提升运动学逆解的稳定性@opentv。 === 标定模块 标定模块的目标是将 VIVE Tracker 的坐标系与机械臂的基坐标系进行对齐,以便后续运动规划模块能够将人手根部的姿态转换为机械臂末端的姿态。使用者可以将 Tracker 放在特定位置后,通过预定的指令标定四个点,即坐标系原点、x 轴、y 轴和 Tracker 原始数据坐标系到自定义坐标系的旋转矩阵。标定模块会获得 Tracker 原始数据坐标系和自定义坐标系的转换矩阵,从而将手臂末端姿态方便地转换为机械臂末端姿态,并在逆解后传输给运动规划模块。 === 运动规划 在获得目标位姿后,我们通过机器人 KDL 库中基于 LM 算法的运动学逆解@GINSPEC:2524115 获取对应末端姿态所需的六轴关节角度和关节速度。运动规划模块会从一个缓冲队列中获取最近的关节角度-关节速度对,并进行在线插值规划。对于某个关节,假设其目标角度为 $x_"tar"$,目标速度为 $v_"tar"$,同样地我们有当前角度 $x_0$ 和当前速度 $v_0$。目标是在任意一个控制帧中速度 $v$、加速度 $a$ 和加加速度 $j$ (jerk) 不超过限制的情况下,尽快使角度和速度到达目标值。为简化问题,我们认为“尽快”指的是在不超过限制的条件下,以尽可能大的速度到达目标,并设到达目标时的加速度为 $0$。设角度目标差 $d = x_"tar" - x_0$,则每个控制帧所在的关节角度和速度构成 $d-v$ 图中的一个点。 由于速度和加速度限制,对于特定的距离 $d$,我们能算出该距离下的使得到目标角度时加速度可能为 $0$ 的最优速度 $v$。设该关节的速度限制为 $v_"max"$,加速度限制 $a_"max"$,不失一般性,考虑 $d, v > 0$ 的情况。对于目标速度为 $v_"tar"$,在最优速度 $v$ 以 $-a_"max"$ 减速,我们有到达时间: $ Delta t = (v - v_"tar") / a_"max" $ 容易得到: $ d = v_"tar" Delta t + 1 / 2 a_"max" Delta t^2 $ 解得 $v$ 与 $d$ 的关系: $ v = sqrt(v_"tar"^2 + 2 a d) $ 将该值与速度限制 $v_"max"$ 取较小值,有 $v = min(v_"max", sqrt(v_"tar"^2 + 2 a d))$,如@img8 所示。 #figure(image("image copy 8.png", width: 60%), caption: [对于距离 $d$ 可以算出该距离下的最优速度]) <img8> 算法如@algo1 所示,其中 $"f"$ 为固定控制帧率。使用该算法获取初步最优速度后,可根据最优速度和当前速度的差得到最优加速度,从而得到最优加加速度 jerk,并根据上一控制帧的速度和加速度可获取当前控制帧的最优加速度、速度和目标关节角度。 #import "@preview/algorithmic:0.1.0" #import algorithmic: algorithm #figure(caption: "获取最优路点算法" )[ #set align(left) #algorithm({ import algorithmic: * Function("online_intpln_best_v", args: ($x_"0"$, $x_"tar"$, $v_"0"$, $v_"tar"$, $"f"$, $v_"max"$, $a_"max"$), { Cmt[Initialize the search range] Assign[$"d"$][$x_"tar" - x_"0"$] Assign[$"d"_"next control if v unchanged"$][$x_"tar" - ("v"_"0" / "fps" + x_"0")$] Assign[$"d"_"half"$][$"d" + "d"_"next control if v unchanged"$] State[] Assign[$v_"best at half d"$][$"sign"("d"_"half") sqrt(abs(2 "d"_"half" a_"max" + v_"tar"^2))$ limited by $v_"max"$] State[] If(cond: $"sign"(v_"best at half d") != "sign"("d")$, { Return[$"d" times "fps"$] }) Else({ Return[$v_"best at half d"$] }) }) } ) ] <algo1> #figure(image("image copy 6.png", width: 80%), caption: "姿态解算模块和运动规划模块对缓冲区的读写") <img6> 计算出的若干对目标关节角度在透传发布给机械臂之前,将传输给 Moveit2 碰撞检测模块进行自碰撞检测和与物体的碰撞检测。如果发生碰撞,则会调用基于 OMPL 的轨迹规划算法生成若干对无碰撞路点,使机械臂平滑地运动到目标位置。如果触发 OMPL 轨迹规划,机械臂在几百毫秒内非实时地运动到新的目标点。该系统可以在运行时添加新的碰撞体,例如桌面、其他机械臂和操作台上的物体,以适应不同的环境。 = 第三章 实验 == 性能分析 本研究对手部姿态检测模块、标定模块和运动规划模块进行了性能分析。 #set table(stroke: (_, y) => if y == 0 { (bottom: 1pt) }) #show table.cell.where(x: 0): set text(style: "italic") #show table.cell.where(y: 0, x: 0): set text(style: "normal", weight: 900) #figure( table( columns: 4, align: center + horizon, inset: (y: 0.8em), table.header[硬件 / 模块 / 耗时 (ms)][HTC Vive Tracker][Windows 10 \ i7-13790F \ RTX 2060 SUPER][WSL 2 \ Ubuntu 22.04 \ i7-13790F], [Lighthouse 定位], [$< 30$], [/], [/], [标定模块 TF 通信延迟], [/], [/], [$< 0.001$], [TCP 通信延迟], [/], [$< 1$], [$< 1$], [OMPL 轨迹规划], [/], [/], [$120 plus.minus 20$], [在线插值规划], [/], [/], [$< 1$], [碰撞检测], [/], [/], [$0.6 plus.minus 0.1$], [机械臂路点缓存], [/], [/], [$90 plus.minus 30$], ) ) // Table as seen above == 真机实验 本章节将展示本系统在真机执行不同任务的表现,执行机械臂型号为 Aubo I5 机型。 #figure(image("image copy 11.jpg", width: 60%), caption: "手持 VIVE Tracker 控制单一机械臂的位姿") <i11> 如@i11 所示,手持 VIVE Tracker 可对单一机械臂进行末端位姿控制。该任务考验机械臂能否对高速运动或摆动的手臂能否快速准确跟踪,以及碰撞规避和安全性功能。机械臂末端能够实时追踪人手根部的姿态,执行延迟介于 100ms 到 150ms 之间。 #figure(image("image copy 12.png", width: 60%), caption: "穿戴 VIVE Tracker 控制两台机械臂的位姿") <i12> 如@i12 所示,穿戴一台 / 两台 VIVE Tracker 可同时控制两台机械臂的末端位姿。该任务主要考验系统的扩展性、算法延迟的稳定性和两台机械臂合作时的安全性。 #figure(image("image copy 15.png", width: 60%), caption: "穿戴 VIVE Tracker 控制两台机械臂的位姿") <i15> 如@i15 所示,该任务将圆珠笔固定于机械臂末端法兰盘,并穿戴 VIVE Tracker 控制机械臂远程控制圆珠笔在纸上绘制图案。该任务考验了遥操作系统的精度、末端稳定性和易用程度。该任务还将盛水的矿泉水瓶固定在机械臂末端,以放大观察机械臂末端的抖动情况。 #figure( table( columns: (1fr, 0.8fr, 1fr, 2fr), align: center + horizon, inset: (y: 0.8em), table.header[任务][所用系统][所需能力][执行结果], [手持控制], [单传感器-单臂], [末端稳定,执行安全,碰撞规避,快速跟踪], [振动肉眼不可见;跟随的运动频率上限为 $1.5 plus.minus 0.5$Hz,跟随总延迟为 $120 plus.minus 20$ms,轨迹平滑,任意关节速度均不超过 $150degree slash s$。任何条件下,机械臂均不会与桌面发生碰撞。], [穿戴控制双臂], [单/多传感器-双臂], [稳定延迟,多臂安全,高扩展性], [双臂轨迹平滑,无碰撞,可模拟人类双臂合作任务], [写字], [单传感器-单臂], [精确移动,末端稳定,易用], [操作着经过 3 至 4 次热身适应,可在 2 至 3s 内画出简单的图形,圆珠笔末端轨迹稳定], [拿水瓶], [单传感器-单臂], [末端稳定,移动稳定], [手根静止和移动情况下,水面振动与人手持类似], ) ) == 总结 机械臂末端仅有肉眼不可见的轻微振动。当以人手最快速度大于 2Hz 的频率做 0.3m 的往复运动时,机械臂开始出现无法跟随的情况,这主要是由该型号机械臂的加速度限制所致。当手臂以 1Hz 高速运动时,机械臂能快速跟随,轨迹平滑,任意关节速度均不超过给定的 $150degree slash s$。本系统对末端稳定性的优化使得机械臂手持物体不会受到人手自然抖动的明显影响,使得机械臂能以一定精度完成写字、传递物品等日常任务。任何条件下,包括手根放在过低位置或延伸过长时,机械臂均不会与桌面发生碰撞。 由于六轴机械臂的奇异点问题,在某些位姿下,末端位姿的微小运动需要剧烈的关节角度转动才能实现。本系统会检测逆解发生剧烈改变的情况,并在这种情况下进一步限制关节速度,保证了遥操作过程的安全性。 = 第四章 全文总结 == 结论 本系统构建了一套基于机器人逆运动学、在线插补算法和碰撞检测的实时机械臂遥操作系统,通过其低延迟特性,为操作者与机械臂自然、直观的交互提供了可能性,实验结果表明,本系统使得人手和机械臂末端到达目标位置的延迟仅为 $120 plus.minus 20$ms,优于基于离散轨迹规划的算法@curobo,且延迟浮动较小,使得双臂协作任务更加直观高效。传统上,机器人操作需通过编程指定精确地动作轨迹,而该遥操作系统可在操作时执行更灵活复杂的任务,并为机器人模仿学习提供了自然且平滑的轨迹样本。通过引入碰撞检测算法,本系统可以动态地添加碰撞体,在快速追踪的同时保证了运动的无碰撞,从而适应不同环境,在快速跟踪的同时保证了操作者和机械臂的安全性。同时,算法对传感器的观测数据进行了滤波优化,而在线插补算法自然地限制了机械臂关节运动的速度、加速度和加加速度,使得机械臂末端的运动更加平滑,减少了关节电机过载和末端超调振动的风险,使得本系统更适用于手术机器人等对运动稳定性极为敏感的领域。 本系统模块之间低耦合,接口明确,使用者无需修改大量代码就可以在不同的部署环境之间快速迁移,其灵活的配置文件允许用户轻松适配不同的传感器、机器人和末端执行器,降低了用户的使用成本,实现了高度的可定制化,使本遥操作系统成为适应各种复杂环境和任务的理想选择。 == 局限 // 尺寸和 奇异点,抖动问题,延迟饥饿问题,延迟规划问题,无法追踪加速度,超调 // 视觉反馈 // 本系统的目标是以尽可能低的延迟将人手根姿态消除生理性抖动后,无碰撞地迁移到机械臂末端,然而当前方案仍有改进空间。例如,可以引入 RGB-D 相机或 Quest3 等 VR 头显设备检测人手姿态,扩大操作者的灵活运动空间,并提供遥操作手指动作的可能性。此外由于机械臂和人手臂的尺寸不同,且不同的操作者的肩宽、手臂长度也存在天然的差异,给机械臂的动作空间带来了更多要求,例如当前算法下,当人手双臂贴合时,机械双臂可能相距较远或者因为解碰撞而相互避让。较为简单的解决方法是引入手臂尺寸放缩参数,并将操作者的肩宽考虑在内。 操作者使用本系统完成写字等任务时,需要侧身观察机械臂末端的实际位置,以进行闭环调整,操作者往往因为无法同时顾及自身手腕位置和机械臂末端位置而难以流畅操作。该问题同样可以通过引入视觉反馈解决,例如在双臂之间的位置安装摄像头,将实时图像传回操作者的 VR 头显中,使得操作者可以直观地看到机械臂末端的位置,实现如同手臂即机械臂一般的体验。 本系统的多级通信引入了一定延迟,传感器和机械臂的执行延迟难以完全消除,但影响较小。本系统主要可优化的延迟为机械臂的路点缓存,由于 Aubo I5 机械臂防止饥饿的特性,算法必须获得机械臂的路点缓存并发送足够的路点将其填充到指定大小。该步骤不可避免地引入了较大延迟,即发送的数据必须等到其之前的缓存消耗完后才能执行。目前可以通过降低缓存大小缓解延迟问题,但会带来一定不稳定性。未来可以考虑引入动作预测算法,并提高控制频率来减小延迟。 == 未来工作 本系统可用于模仿人手动作,并生产机器人模仿学习的天然数据,这种数据可以使机器人在不断实践中提升自己的表现,让机器人控制更加自主和智能。本系统未来将用于适配舞肌科技的新型灵巧手,以实现更加精细的手部动作迁移。 未来工作将进一步优化系统的延迟,并着重提升操作者的感官反馈,除了引入 VR 头显外,还将在灵巧手和机械臂上安装触觉传感器,并通过振动等方式将触觉信息反馈给操作者,使得操作者能够更加直观地感知机械臂末端的位置和力度。与此同时,可以开发更智能的控制算法,理解操作者的手部移动和获取物体等意图,并通过强化学习算法使得机械臂自主完成抓取等动作,从而减轻操作者的负担,为机器人在不同任务中的应用提供广阔的发展空间。 #bibliography("1.yaml", title: "参考文献")
https://github.com/chendaohan/rust_tutorials
https://raw.githubusercontent.com/chendaohan/rust_tutorials/main/books/8.所有权(owner).typ
typst
#set heading(numbering: "1.") #set text(size: 15pt) 所有的程序都必须和计算机内存打交道,如何从内存中申请空间来存放程序的运行内容,如何在不需要的时候释放这些空间,成了重中之重,也是所有编程语言设计的难点之一。在计算机语言不断演变过程中,出现了多种流派: - 垃圾回收机制(GC),在程序运行时不断寻找不再使用的内存,典型代表:Java、Go - 手动管理内存的分配和释放, 在程序中,通过函数调用的方式来申请和释放内存,典型代表:C++ - 通过所有权来管理内存,编译器在编译时会根据一系列规则进行检查 其中 Rust 选择了第三种,最妙的是,这种检查只发生在编译期,因此对于程序运行期,不会有任何性能上的损失。 = 栈(Stack)与堆(Heap) == 栈 栈按照顺序存储值并以相反顺序取出值,这也被称作后进先出。 栈中的所有数据都必须占用已知且固定大小的内存空间。 #image("images/8.stack.png", width: 50%) == 堆 与栈不同,对于大小未知或者可能变化的数据,我们需要将它存储在堆上。 当向堆上放入数据时,需要请求一定大小的内存空间。操作系统在堆的某处找到一块足够大的空位,把它标记为已使用,并返回一个表示该位置地址的指针, 该过程被称为在堆上分配内存,有时简称为 “分配”(allocating)。 接着,该指针会被推入栈中,因为指针的大小是已知且固定的,在后续使用过程中,你将通过栈中的指针,来获取数据在堆上的实际内存位置,进而访问该数据。 由上可知,堆是一种缺乏组织的数据结构。 #image("images/8.heap.png", width: 70%) == 性能区别 写入方面:入栈比在堆上分配内存要快,因为入栈时操作系统无需分配新的空间,只需要将新数据放入栈顶即可。相比之下,在堆上分配内存则需要更多的工作,这是因为操作系统必须首先找到一块足够存放数据的内存空间,接着做一些记录为下一次分配做准备。 读取方面:得益于 CPU 高速缓存,使得处理器可以减少对内存的访问,高速缓存和内存的访问速度差异在 10 倍以上!栈数据往往可以直接存储在 CPU 高速缓存中,而堆数据只能存储在内存中。访问堆上的数据比访问栈上的数据慢,因为必须先访问栈再通过栈上的指针来访问内存。 因此,处理器处理分配在栈上数据会比在堆上的数据更加高效。 == 所有权与堆栈 当你的代码调用一个函数时,传递给函数的参数(包括可能指向堆上数据的指针和函数的局部变量)依次被压入栈中,当函数调用结束时,这些值将被从栈中按照相反的顺序依次移除。 因为堆上的数据缺乏组织,因此跟踪这些数据何时分配和释放是非常重要的,否则堆上的数据将产生内存泄漏 —— 这些数据将永远无法被回收。这就是 Rust 所有权系统为我们提供的强大保障。 对于其他很多编程语言,你确实无需理解堆栈的原理,但是在 Rust 中,明白堆栈的原理,对于我们理解所有权的工作原理会有很大的帮助。 = 所有权原则 + Rust 中每一个值都被一个变量所拥有,该变量被称为值的所有者 + 一个值同时只能被一个变量所拥有,或者说一个值只能拥有一个所有者 + 当所有者(变量)离开作用域范围时,这个值将被丢弃(drop)