repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Jollywatt/typst-wordometer
https://raw.githubusercontent.com/Jollywatt/typst-wordometer/master/src/lib.typ
typst
MIT License
#let dictionary-sum(a, b) = { let c = (:) for k in a.keys() + b.keys() { c.insert(k, a.at(k, default: 0) + b.at(k, default: 0)) } c } /// Get a basic word count from a string. /// /// Returns a dictionary with keys: /// - `characters`: Number of non-whitespace characters. /// - `words`: Number of words, defined by `regex("\b[\w'’]+\b")`. /// - `sentences`: Number of sentences, defined by `regex("\w+\s*[.?!]")`. /// /// - string (string): /// -> dictionary #let string-word-count(string) = ( characters: string.replace(regex("\s+"), "").clusters().len(), words: string.matches(regex("\b[\w'’.,\-]+\b")).len(), sentences: string.matches(regex("\w+\s*[.?!]")).len(), ) /// Simplify an array of content by concatenating adjacent text elements. /// /// Doesn't preserve content exactly; `smartquote`s are replaced with `'` or /// `"`. This is used on `sequence` elements because it improves word counts for /// cases like "Digby's", which should count as one word. /// /// For example, the content #rect[Qu'est-ce *que* c'est !?] is structured as: /// /// #[Qu'est-ce *que* c'est !?].children /// /// This function simplifies this to: /// /// #wordometer.concat-adjacent-text([Qu'est-ce *que* c'est !?].children) /// /// - children (array): Array of content to simplify. #let concat-adjacent-text(children) = { if children.len() == 0 { return () } let squashed = (children.at(0),) let as-text(el) = { let fn = repr(el.func()) if fn == "text" { el.text } else if fn == "space" { " " } else if fn in "linebreak" { "\n" } else if fn in "parbreak" { "\n\n" } else if fn in "pagebreak" { "\n\n\n\n" } else if fn == "smartquote" { if el.double { "\"" } else { "'" } } } let last-text = as-text(squashed.at(-1)) for child in children.slice(1) { // don't squash labelled sequences. the label should be // preserved because it might be used to exclude elements let has-label = child.at("label", default: none) != none if has-label { squashed.push(child) last-text = none continue } let this-text = as-text(child) let merge-with-last = last-text != none and this-text != none if merge-with-last { // squash into last element last-text = last-text + this-text squashed.at(-1) = text(last-text) } else { // add new element last-text = this-text squashed.push(child) } } squashed } #let IGNORED_ELEMENTS = ( "bibliography", "cite", "display", "equation", "h", "hide", "image", "line", "linebreak", "locate", "metadata", "pagebreak", "parbreak", "path", "polygon", "ref", "repeat", "smartquote", "space", "style", "update", "v", ) #let parse-basic-where-selector(selector) = { let match = repr(selector).match(regex("^([\w]+)\.where(.*)$")) if match == none { panic("Only `element.where(key: value, ..)` selectors are supported.") } let (element-fn, fields) = match.captures (element-fn: element-fn, fields: eval(fields)) } #let interpret-exclude-patterns(exclude) = { exclude.map(element-fn => { if type(element-fn) in (str, label, dictionary) { element-fn } else if type(element-fn) == function { repr(element-fn) } else if type(element-fn) == selector { parse-basic-where-selector(element-fn) } else { panic("Exclude patterns must be element functions, strings, or labels; got:", element-fn) } }) } /// Traverse a content tree and apply a function to textual leaf nodes. /// /// Descends into elements until reaching a textual element (`text` or `raw`) /// and calls `f` on the contained text, returning a (nested) array of all the /// return values. /// /// - f (function): Unary function to pass text to. /// - content (content): Content element to traverse. /// - exclude (array): Content to skip while traversing the tree, specified by: /// - name, e.g., `"heading"` /// - function, e.g., `heading` /// - selector, e.g., `heading.where(level: 1)` (only basic `where` selectors /// are supported) /// - label, e.g., `<no-wc>` /// Default value includes equations and elements without child content or /// text: /// #wordometer.IGNORED_ELEMENTS.sorted().map(repr).map(raw).join([, ], /// last: [, and ]). /// /// To exclude figures, but include figure captions, pass the name /// `"figure-body"` (which is not a real element). To include figure bodies, /// but exclude their captions, pass the name `"caption"`. #let map-tree(f, content, exclude: IGNORED_ELEMENTS) = { if content == none { return none } let exclude = interpret-exclude-patterns(exclude) let map-subtree = map-tree.with(f, exclude: exclude) let fn = repr(content.func()) let fields = content.fields().keys() let exclude-selectors = exclude.filter(e => type(e) == dictionary and "element-fn" in e) for (element-fn, fields) in exclude-selectors { // panic(exclude-selectors, content) if fn == element-fn { // If all fields in the selector match the element, exclude it if not fields.pairs().any(((key, value)) => content.at(key, default: value) != value) { return none } } } if fn in exclude { none // check if element has a label that is excluded } else if content.at("label", default: none) in exclude { none } else if fn in ("text", "raw") { f(content.text) } else if "children" in fields { let children = content.children if fn == "sequence" { // don't do this for, e.g., grid or stack elements children = concat-adjacent-text(children) } children .map(map-subtree) .filter(x => x != none) } else if fn == "figure" { ( if "figure-body" not in exclude { map-subtree(content.body) }, if "caption" in content.fields() { map-subtree(content.caption) }, ) .filter(x => x != none) } else if fn == "styled" { map-subtree(content.child) } else if "body" in fields { map-subtree(content.body) } else { none } } /// Extract plain text from content /// /// This is a quick-and-dirty conversion which does not preserve styling or /// layout and which may introduces superfluous spaces. /// - content (content): Content to extract plain text from. /// - ..options ( ): Additional named arguments: /// - `exclude`: Content to exclude (see `map-tree()`). Can be an array of /// element functions, element function names, or labels. #let extract-text(content, ..options) = { let out = (map-tree(x => x, content, ..options),).flatten().join(" ") out + "" // ensures none becomes empty string } /// Get word count statistics of a content element. /// /// Returns a results dictionary, not the content passed to it. (See /// `string-word-count()`). /// /// - content (content): /// -> dictionary /// - exclude (array): Content to exclude from word count (see `map-tree()`). /// Can be an array of element functions, element function names, or labels. /// - counter (fn): A function that accepts a string and returns a dictionary of /// counts. /// /// For example, to count vowels, you might do: /// /// ```typ /// #word-count-of([ABCDEFG], counter: s => ( /// vowels: lower(s).matches(regex("[aeiou]")).len(), /// )) /// ``` /// - method (string): The algorithm to use. Can be: /// - `"stringify"`: Convert the content into one big string, then perform the /// word count. /// - `"bubble"`: Traverse the content tree performing word counts at each /// textual leaf node, then "bubble" the results back up (i.e., sum them). /// Performance and results may vary by method! #let word-count-of( content, exclude: (), counter: string-word-count, method: "stringify", ) = { let exclude = IGNORED_ELEMENTS + (exclude,).flatten() let options = ("bubble", "stringify") assert(method in options, message: "Unknown choice " + repr(method) + ". Options are " + repr(options) + ".") if method == "bubble" { (map-tree(counter, content, exclude: exclude),) .filter(x => x != none) .flatten() .fold(counter(""), dictionary-sum) } else if method == "stringify" { counter(extract-text(content, exclude: exclude)) } } /// Simultaneously take a word count of some content and insert it into that /// content. /// /// It works by first passing in some dummy results to `fn`, performing a word /// count on the content returned, and finally returning the result of passing /// the word count retults to `fn`. This happens once --- it doesn't keep /// looping until convergence or anything! /// /// For example: /// ```typst /// #word-count-callback(stats => [There are #stats.words words]) /// ``` /// /// - fn (function): A function accepting a dictionary and returning content to /// perform the word count on. /// - ..options ( ): Additional named arguments: /// - `exclude`: Content to exclude from word count (see `map-tree()`). Can be /// an array of element functions, element function names, or labels. /// - `counter`: A function that accepts a string and returns a dictionary of /// counts. /// - `method`: Content traversal method to use (see `word-count-of()`). /// -> content #let word-count-callback(fn, ..options) = { let preview-content = [#fn(string-word-count(""))] let stats = word-count-of(preview-content, ..options) fn(stats) } #let total-words = context state("total-words").final() #let total-characters = context state("total-characters").final() /// Get word count statistics of the given content and store the results in /// global state. Should only be used once in the document. /// /// #set raw(lang: "typ") /// /// The results are accessible anywhere in the document with `#total-words` and /// `#total-characters`, which are shortcuts for the final values of states of /// the same name (e.g., `#context state("total-words").final()`) /// /// - content (content): /// Content to word count. /// - ..options ( ): Additional named arguments: /// - `exclude`: Content to exclude from word count (see `map-tree()`). Can be /// an array of element functions, element function names, or labels. /// - `counter`: A function that accepts a string and returns a dictionary of /// counts. /// - `method`: Content traversal method to use (see `word-count-of()`). /// -> content #let word-count-global(content, ..options) = { let stats = word-count-of(content, ..options) state("total-words").update(stats.words) state("total-characters").update(stats.characters) content } /// Perform a word count on content. /// /// Master function which accepts content (calling `word-count-global()`) or a /// callback function (calling `word-count-callback()`). /// /// - arg (content, fn): /// Can be: /// #set raw(lang: "typ") /// - `content`: A word count is performed for the content and the results are /// accessible through `#total-words` and `#total-characters`. This uses a /// global state, so should only be used once in a document (e.g., via a /// document show rule: `#show: word-count`). /// - `function`: A callback function accepting a dictionary of word count /// results and returning content to be word counted. For example: /// ```typ /// #word-count(total => [This sentence contains #total.characters letters.]) /// ``` /// - ..options ( ): Additional named arguments: /// - `exclude`: Content to exclude from word count (see `map-tree()`). Can be /// an array of element functions, element function names, or labels. /// - `counter`: A function that accepts a string and returns a dictionary of /// counts. /// - `method`: Content traversal method to use (see `word-count-of()`). /// /// -> dictionary #let word-count(arg, ..options) = { if type(arg) == function { word-count-callback(arg, ..options) } else { word-count-global(arg, ..options) } }
https://github.com/jens-hj/ds-exam-notes
https://raw.githubusercontent.com/jens-hj/ds-exam-notes/main/catppuccin.typ
typst
#let catppuccin = ( latte: ( rosewater: color.rgb(220, 138, 120), flamingo: color.rgb(221, 120, 120), pink: color.rgb(234, 118, 203), mauve: color.rgb(136, 57, 239), red: color.rgb(210, 15, 57), maroon: color.rgb(230, 69, 83), peach: color.rgb(254, 100, 11), yellow: color.rgb(223, 142, 29), green: color.rgb(64, 160, 43), teal: color.rgb(23, 146, 153), sky: color.rgb(4, 165, 229), sapphire: color.rgb(32, 159, 181), blue: color.rgb(30, 102, 245), lavender: color.rgb(114, 135, 253), text: color.rgb(76, 79, 105), subtext1: color.rgb(92, 95, 119), subtext0: color.rgb(108, 111, 133), overlay2: color.rgb(124, 127, 147), overlay1: color.rgb(140, 143, 161), overlay0: color.rgb(156, 160, 176), surface2: color.rgb(172, 176, 190), surface1: color.rgb(188, 192, 204), surface0: color.rgb(204, 208, 218), base: color.rgb(239, 241, 245), mantle: color.rgb(230, 233, 239), crust: color.rgb(220, 224, 232), ), frappe: ( rosewater: color.rgb(242, 213, 207), flamingo: color.rgb(238, 190, 190), pink: color.rgb(244, 184, 228), mauve: color.rgb(202, 158, 230), red: color.rgb(231, 130, 132), maroon: color.rgb(234, 153, 156), peach: color.rgb(239, 159, 118), yellow: color.rgb(229, 200, 144), green: color.rgb(166, 209, 137), teal: color.rgb(129, 200, 190), sky: color.rgb(153, 209, 219), sapphire: color.rgb(133, 193, 220), blue: color.rgb(140, 170, 238), lavender: color.rgb(186, 187, 241), text: color.rgb(198, 208, 245), subtext1: color.rgb(181, 191, 226), subtext0: color.rgb(165, 173, 206), overlay2: color.rgb(148, 156, 187), overlay1: color.rgb(131, 139, 167), overlay0: color.rgb(115, 121, 148), surface2: color.rgb(98, 104, 128), surface1: color.rgb(81, 87, 109), surface0: color.rgb(65, 69, 89), base: color.rgb(48, 52, 70), mantle: color.rgb(41, 44, 60), crust: color.rgb(35, 38, 52), ), macchiato: ( rosewater: color.rgb(244, 219, 214), flamingo: color.rgb(240, 198, 198), pink: color.rgb(245, 189, 230), mauve: color.rgb(198, 160, 246), red: color.rgb(237, 135, 150), maroon: color.rgb(238, 153, 160), peach: color.rgb(245, 169, 127), yellow: color.rgb(238, 212, 159), green: color.rgb(166, 218, 149), teal: color.rgb(139, 213, 202), sky: color.rgb(145, 215, 227), sapphire: color.rgb(125, 196, 228), blue: color.rgb(138, 173, 244), lavender: color.rgb(183, 189, 248), text: color.rgb(202, 211, 245), subtext1: color.rgb(184, 192, 224), subtext0: color.rgb(165, 173, 203), overlay2: color.rgb(147, 154, 183), overlay1: color.rgb(128, 135, 162), overlay0: color.rgb(110, 115, 141), surface2: color.rgb(91, 96, 120), surface1: color.rgb(73, 77, 100), surface0: color.rgb(54, 58, 79), base: color.rgb(36, 39, 58), mantle: color.rgb(30, 32, 48), crust: color.rgb(24, 25, 38), ), mocha: ( rosewater: color.rgb(245, 224, 220), flamingo: color.rgb(242, 205, 205), pink: color.rgb(245, 194, 231), mauve: color.rgb(203, 166, 247), red: color.rgb(243, 139, 168), maroon: color.rgb(235, 160, 172), peach: color.rgb(250, 179, 135), yellow: color.rgb(249, 226, 175), green: color.rgb(166, 227, 161), teal: color.rgb(148, 226, 213), sky: color.rgb(137, 220, 235), sapphire: color.rgb(116, 199, 236), blue: color.rgb(137, 180, 250), lavender: color.rgb(180, 190, 254), text: color.rgb(205, 214, 244), subtext1: color.rgb(186, 194, 222), subtext0: color.rgb(166, 173, 200), overlay2: color.rgb(147, 153, 178), overlay1: color.rgb(127, 132, 156), overlay0: color.rgb(108, 112, 134), surface2: color.rgb(88, 91, 112), surface1: color.rgb(69, 71, 90), surface0: color.rgb(49, 50, 68), base: color.rgb(30, 30, 46), mantle: color.rgb(24, 24, 37), crust: color.rgb(17, 17, 27), ), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0B00.typ
typst
Apache License 2.0
#let data = ( (), ("ORIYA SIGN CANDRABINDU", "Mn", 0), ("ORIYA SIGN ANUSVARA", "Mc", 0), ("ORIYA SIGN VISARGA", "Mc", 0), (), ("ORIYA LETTER A", "Lo", 0), ("ORIYA LETTER AA", "Lo", 0), ("ORIYA LETTER I", "Lo", 0), ("ORIYA LETTER II", "Lo", 0), ("ORIYA LETTER U", "Lo", 0), ("ORIYA LETTER UU", "Lo", 0), ("ORIYA LETTER VOCALIC R", "Lo", 0), ("ORIYA LETTER VOCALIC L", "Lo", 0), (), (), ("ORIYA LETTER E", "Lo", 0), ("ORIYA LETTER AI", "Lo", 0), (), (), ("ORIYA LETTER O", "Lo", 0), ("ORIYA LETTER AU", "Lo", 0), ("ORIYA LETTER KA", "Lo", 0), ("ORIYA LETTER KHA", "Lo", 0), ("ORIYA LETTER GA", "Lo", 0), ("ORIYA LETTER GHA", "Lo", 0), ("ORIYA LETTER NGA", "Lo", 0), ("ORIYA LETTER CA", "Lo", 0), ("ORIYA LETTER CHA", "Lo", 0), ("ORIYA LETTER JA", "Lo", 0), ("ORIYA LETTER JHA", "Lo", 0), ("ORIYA LETTER NYA", "Lo", 0), ("ORIYA LETTER TTA", "Lo", 0), ("ORIYA LETTER TTHA", "Lo", 0), ("ORIYA LETTER DDA", "Lo", 0), ("ORIYA LETTER DDHA", "Lo", 0), ("ORIYA LETTER NNA", "Lo", 0), ("ORIYA LETTER TA", "Lo", 0), ("ORIYA LETTER THA", "Lo", 0), ("ORIYA LETTER DA", "Lo", 0), ("ORIYA LETTER DHA", "Lo", 0), ("ORIYA LETTER NA", "Lo", 0), (), ("ORIYA LETTER PA", "Lo", 0), ("ORIYA LETTER PHA", "Lo", 0), ("ORIYA LETTER BA", "Lo", 0), ("ORIYA LETTER BHA", "Lo", 0), ("ORIYA LETTER MA", "Lo", 0), ("ORIYA LETTER YA", "Lo", 0), ("ORIYA LETTER RA", "Lo", 0), (), ("ORIYA LETTER LA", "Lo", 0), ("ORIYA LETTER LLA", "Lo", 0), (), ("ORIYA LETTER VA", "Lo", 0), ("ORIYA LETTER SHA", "Lo", 0), ("ORIYA LETTER SSA", "Lo", 0), ("ORIYA LETTER SA", "Lo", 0), ("ORIYA LETTER HA", "Lo", 0), (), (), ("ORIYA SIGN NUKTA", "Mn", 7), ("ORIYA SIGN AVAGRAHA", "Lo", 0), ("ORIYA VOWEL SIGN AA", "Mc", 0), ("ORIYA VOWEL SIGN I", "Mn", 0), ("ORIYA VOWEL SIGN II", "Mc", 0), ("ORIYA VOWEL SIGN U", "Mn", 0), ("ORIYA VOWEL SIGN UU", "Mn", 0), ("ORIYA VOWEL SIGN VOCALIC R", "Mn", 0), ("ORIYA VOWEL SIGN VOCALIC RR", "Mn", 0), (), (), ("ORIYA VOWEL SIGN E", "Mc", 0), ("ORIYA VOWEL SIGN AI", "Mc", 0), (), (), ("ORIYA VOWEL SIGN O", "Mc", 0), ("ORIYA VOWEL SIGN AU", "Mc", 0), ("ORIYA SIGN VIRAMA", "Mn", 9), (), (), (), (), (), (), (), ("ORIYA SIGN OVERLINE", "Mn", 0), ("ORIYA AI LENGTH MARK", "Mn", 0), ("ORIYA AU LENGTH MARK", "Mc", 0), (), (), (), (), ("ORIYA LETTER RRA", "Lo", 0), ("ORIYA LETTER RHA", "Lo", 0), (), ("ORIYA LETTER YYA", "Lo", 0), ("ORIYA LETTER VOCALIC RR", "Lo", 0), ("ORIYA LETTER VOCALIC LL", "Lo", 0), ("ORIYA VOWEL SIGN VOCALIC L", "Mn", 0), ("ORIYA VOWEL SIGN VOCALIC LL", "Mn", 0), (), (), ("ORIYA DIGIT ZERO", "Nd", 0), ("ORIYA DIGIT ONE", "Nd", 0), ("ORIYA DIGIT TWO", "Nd", 0), ("ORIYA DIGIT THREE", "Nd", 0), ("ORIYA DIGIT FOUR", "Nd", 0), ("ORIYA DIGIT FIVE", "Nd", 0), ("ORIYA DIGIT SIX", "Nd", 0), ("ORIYA DIGIT SEVEN", "Nd", 0), ("ORIYA DIGIT EIGHT", "Nd", 0), ("ORIYA DIGIT NINE", "Nd", 0), ("ORIYA ISSHAR", "So", 0), ("ORIYA LETTER WA", "Lo", 0), ("ORIYA FRACTION ONE QUARTER", "No", 0), ("ORIYA FRACTION ONE HALF", "No", 0), ("ORIYA FRACTION THREE QUARTERS", "No", 0), ("ORIYA FRACTION ONE SIXTEENTH", "No", 0), ("ORIYA FRACTION ONE EIGHTH", "No", 0), ("ORIYA FRACTION THREE SIXTEENTHS", "No", 0), )
https://github.com/jneug/typst-mantys
https://raw.githubusercontent.com/jneug/typst-mantys/main/README.md
markdown
MIT License
# Mantys (v0.1.4) > **MAN**uals for **TY**p**S**t Template for documenting [typst](https://github.com/typst/typst) packages and templates. ## Usage Just import the package at the beginning of your manual: ```typst #import "@preview/mantys:0.1.4": * ``` Mantys supports **Typst 0.11.0** and newer. ## Writing basics A basic template for a manual could look like this: ```typst #import "@local/mantys:0.1.4": * #import "your-package.typ" #show: mantys.with( name: "your-package-name", title: [A title for the manual], subtitle: [A subtitle for the manual], info: [A short descriptive text for the package.], authors: "<NAME>", url: "https://github.com/repository/url", version: "0.0.1", date: "date-of-release", abstract: [ A few paragraphs of text to describe the package. ], example-imports: (your-package: your-package) ) // end of preamble # About #lorem(50) # Usage #lorem(50) # Available commands #lorem(50) ``` Use `#command(name, ..args)[description]` to describe commands and `#argument(name, ...)[description]` for arguments: ```typst #command("headline", arg[color], arg(size:1.8em), sarg[other-args], barg[body])[ Renders a prominent headline using #doc("meta/heading"). #argument("color", type:"color")[ The color of the headline will be used as the background of a #doc("layout/block") element containing the headline. ] #argument("size", default:1.8em)[ The text size for the headline. ] #argument("sarg", is-sink:true)[ Other options will get passed directly to #doc("meta/heading"). ] #argument("body", type:"content")[ The text for the headline. ] The headline is shown as a prominent colored block to highlight important news articles in the newsletter: #example[``` #headline(blue, size: 2em, level: 3)[ #lorem(8) ] ```] ] ``` The result might look something like this: ![Example for a headline command with Mantys](docs/assets/headline-example.png) For a full reference of available commands read [the manual](docs/mantys-manual.pdf). ## Changelog ### Version 0.1.5 - Fixed `#cmdref` not showing command name (by @freundTech). - Made colors of datatype blocks look closer to the Typst website (by @tingerrr). ### Version 0.1.4 - Fix missing links in outline (@tingerrr). - Fixed problem when evaluating default values with Tidy. ### Version 0.1.3 - Fix for some datatypes not being displayed properly (thanks to @tingerrr). - Fix for imbalanced outline columns (thanks again to @tingerrr). ### Version 0.1.2 - Added [hydra](https://typst.app/universe/package/hydra) for better detection of headings in page headers (thanks to @tingerrr for the suggestion). - Fixed problem with multiple quotes around default string values in tidy docs. - Fixed datatypes linking to wrong documentation urls. ### Version 0.1.1 - Added template files for submission to _Typst Universe_. ### Version 0.1.0 - Refactorings and some style changes - Updated manual. - Restructuring of package repository. ### Version 0.0.4 - Added integration with [tidy](https://github.com/Mc-Zen/tidy). - Fixed issue with types in argument boxes. - `#lambda` now uses `#dtype` #### Breaking changes - Adapted `scope` argument for `eval` in examples. - `#example()`, `#side-by-side()` and `#shortex()` now support the `scope` and `mode` argument. - The option `example-imports` was replaced by `examples-scope`. ### Version 0.0.3 - It is now possible to load a packages' `typst.toml` file directly into `#mantys`: ```typst #show: mantys.with( ..toml("typst.toml") ) ``` - Added some dependencies: - [jneug/typst-tools4typst](https://github.com/jneug/typst-tools4typst) for some common utilities, - [jneug/typst-codelst](https://github.com/jneug/typst-codelst) for rendering examples and source code, - [Pablo-Gonzalez-Calderon/showybox-package](https://github.com/Pablo-Gonzalez-Calderon/showybox-package) for adding frames to different areas of a manual (like examples). - Redesign of some elements: - Argument display in command descriptions, - Alert boxes. - Added `#version(since:(), until:())` command to add version markers to commands. - Styles moved to a separate `theme.typ` file to allow easy customization of colors and styles. - Added `#func()`, `#lambda()` and `#symbol()` commands, to handle special cases for values. - Fixes and code improvements. ### Version 0.0.2 - Some major updates to the core commands and styles. ### Version 0.0.1 - Initial release.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/chronos/0.1.0/src/participant.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "consts.typ": * #let PAR-SPECIALS = "?[]" #let SHAPES = ( "participant", "actor", "boundary", "control", "entity", "database", "collections", "queue", "custom" ) #let _par( name, display-name: auto, from-start: true, invisible: false, shape: "participant", color: rgb("#E2E2F0"), custom-image: none, show-bottom: true, show-top: true, ) = { return (( type: "par", name: name, display-name: if display-name == auto {name} else {display-name}, from-start: from-start, invisible: invisible, shape: shape, color: color, custom-image: custom-image, show-bottom: show-bottom, show-top: show-top ),) } #let _exists(participants, name) = { if name == "?" or name == "[" or name == "]" { return true } for p in participants { if name == p.name { return true } } return false } #let get-size(par) = { if par.invisible { return (width: 0pt, height: 0pt) } let m = measure(box(par.display-name)) let w = m.width let h = m.height let (shape-w, shape-h) = ( participant: (w + PAR-PAD.last() * 2, h + PAR-PAD.first() * 2), actor: (ACTOR-WIDTH * 1pt, ACTOR-WIDTH * 2pt + SYM-GAP * 1pt + h), boundary: (BOUNDARY-HEIGHT * 2pt, BOUNDARY-HEIGHT * 1pt + SYM-GAP * 1pt + h), control: (CONTROL-HEIGHT * 1pt, CONTROL-HEIGHT * 1pt + SYM-GAP * 1pt + h), entity: (ENTITY-HEIGHT * 1pt, ENTITY-HEIGHT * 1pt + 2pt + SYM-GAP * 1pt + h), database: (DATABASE-WIDTH * 1pt, DATABASE-WIDTH * 4pt / 3 + SYM-GAP * 1pt + h), collections: ( w + COLLECTIONS-PAD.last() * 2 + calc.abs(COLLECTIONS-DX) * 1pt, h + COLLECTIONS-PAD.first() * 2 + calc.abs(COLLECTIONS-DY) * 1pt, ), queue: ( w + QUEUE-PAD.last() * 2 + 3 * (h + QUEUE-PAD.first() * 2) / 4, h + QUEUE-PAD.first() * 2 ), custom: ( measure(par.custom-image).width, measure(par.custom-image).height + SYM-GAP * 1pt + h ) ).at(par.shape) return ( width: calc.max(w, shape-w), height: calc.max(h, shape-h) ) } #let _render-participant(x, y, p, m, bottom) = { let w = m.width / 1pt let h = m.height / 1pt let x0 = x - w / 2 - PAR-PAD.last() / 1pt let x1 = x + w / 2 + PAR-PAD.last() / 1pt let y0 = y + h + PAR-PAD.first() / 1pt * 2 if bottom { y0 = y } let y1 = y0 - h - PAR-PAD.first() / 1pt * 2 draw.rect( (x0, y0), (x1, y1), radius: 2pt, fill: p.color, stroke: black + .5pt ) draw.content( ((x0 + x1) / 2, (y0 + y1) / 2), p.display-name, anchor: "center" ) } #let _render-actor(x, y, p, m, bottom) = { let w2 = ACTOR-WIDTH / 2 let head-r = ACTOR-WIDTH / 4 let height = ACTOR-WIDTH * 2 let arms-y = height * 0.375 let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + height + SYM-GAP} draw.circle( (x, y0 - head-r), radius: head-r, fill: p.color, stroke: black + .5pt ) draw.line((x, y0 - head-r * 2), (x, y0 - height + w2), stroke: black + .5pt) draw.line((x - w2, y0 - arms-y), (x + w2, y0 - arms-y), stroke: black + .5pt) draw.line((x - w2, y0 - height), (x, y0 - height + w2), (x + w2, y0 - height), stroke: black + .5pt) draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let _render-boundary(x, y, p, m, bottom) = { let circle-r = BOUNDARY-HEIGHT / 2 let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + BOUNDARY-HEIGHT + SYM-GAP} let x0 = x - BOUNDARY-HEIGHT let y1 = y0 - circle-r let y2 = y0 - BOUNDARY-HEIGHT draw.circle( (x + circle-r, y1), radius: circle-r, fill: p.color, stroke: black + .5pt ) draw.line( (x0, y0), (x0, y2), stroke: black + .5pt ) draw.line( (x0, y1), (x, y1), stroke: black + .5pt ) draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let _render-control(x, y, p, m, bottom) = { let r = CONTROL-HEIGHT / 2 let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + CONTROL-HEIGHT + SYM-GAP} draw.circle( (x, y0 - r), radius: r, fill: p.color, stroke: black + .5pt ) draw.mark((x, y0), (x - r / 2, y0), symbol: "stealth", fill: black) draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let _render-entity(x, y, p, m, bottom) = { let r = ENTITY-HEIGHT / 2 let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + ENTITY-HEIGHT + SYM-GAP} let y1 = y0 - ENTITY-HEIGHT - 1.5 draw.circle( (x, y0 - r), radius: r, fill: p.color, stroke: black + .5pt ) draw.line( (x - r, y1), (x + r, y1), stroke: black + .5pt ) draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let _render-database(x, y, p, m, bottom) = { let height = DATABASE-WIDTH * 4 / 3 let rx = DATABASE-WIDTH / 2 let ry = rx / 2 let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + height + SYM-GAP} let y1 = y0 - height draw.merge-path( close: true, fill: p.color, stroke: black + .5pt, { draw.bezier((x - rx, y0 - ry), (x, y0), (x - rx, y0 - ry/2), (x - rx/2, y0)) draw.bezier((), (x + rx, y0 - ry), (x + rx/2, y0), (x + rx, y0 - ry/2)) draw.line((), (x + rx, y1 + ry)) draw.bezier((), (x, y1), (x + rx, y1 + ry/2), (x + rx/2, y1)) draw.bezier((), (x - rx, y1 + ry), (x - rx/2, y1), (x - rx, y1 + ry/2)) } ) draw.merge-path( stroke: black + .5pt, { draw.bezier((x - rx, y0 - ry), (x, y0 - ry*2), (x - rx, y0 - 3*ry/2), (x - rx/2, y0 - ry*2)) draw.bezier((), (x + rx, y0 - ry), (x + rx/2, y0 - ry*2), (x + rx, y0 - 3*ry/2)) } ) draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let _render-collections(x, y, p, m, bottom) = { let w = m.width / 1pt let h = m.height / 1pt let dx = COLLECTIONS-DX let dy = COLLECTIONS-DY let total-w = w + PAR-PAD.last() * 2 / 1pt + calc.abs(dx) let total-h = h + PAR-PAD.first() * 2 / 1pt + calc.abs(dy) let x0 = x - total-w / 2 let x1 = x0 + calc.abs(dx) let x3 = x0 + total-w let x2 = x3 - calc.abs(dx) let y0 = if bottom {y} else {y + total-h} let y1 = y0 - calc.abs(dy) let y3 = y0 - total-h let y2 = y3 + calc.abs(dy) let r1 = (x1, y0, x3, y2) let r2 = (x0, y1, x2, y3) if dx < 0 { r1.at(0) = x0 r1.at(2) = x2 r2.at(0) = x1 r2.at(2) = x3 } if dy < 0 { r1.at(1) = y1 r1.at(3) = y3 r2.at(1) = y0 r2.at(3) = y2 } draw.rect( (r1.at(0), r1.at(1)), (r1.at(2), r1.at(3)), fill: p.color, stroke: black + .5pt ) draw.rect( (r2.at(0), r2.at(1)), (r2.at(2), r2.at(3)), fill: p.color, stroke: black + .5pt ) draw.content( ((r2.at(0) + r2.at(2)) / 2, (r2.at(1) + r2.at(3)) / 2), p.display-name, anchor: "center" ) } #let _render-queue(x, y, p, m, bottom) = { let w = (m.width + QUEUE-PAD.last() * 2) / 1pt let h = (m.height + QUEUE-PAD.first() * 2) / 1pt let total-h = h let ry = total-h / 2 let rx = ry / 2 let total-w = w + 3 + 3 * rx let x0 = x - total-w / 2 let y0 = if bottom {y} else {y + total-h} let y1 = y0 - total-h let x-left = x0 + rx let x-right = x-left + w + rx draw.merge-path( close: true, fill: p.color, stroke: black + .5pt, { draw.bezier((x-right, y0), (x-right + rx, y0 - ry), (x-right + rx/2, y0), (x-right + rx, y0 - ry/2)) draw.bezier((), (x-right, y1), (x-right + rx, y1 + ry/2), (x-right + rx/2, y1)) draw.line((), (x-left, y1)) draw.bezier((), (x-left - rx, y0 - ry), (x-left - rx/2, y1), (x-left - rx, y1 + ry/2)) draw.bezier((), (x-left, y0), (x-left - rx, y0 - ry/2), (x-left - rx/2, y0)) } ) draw.merge-path( stroke: black + .5pt, { draw.bezier((x-right, y0), (x-right - rx, y0 - ry), (x-right - rx/2, y0), (x-right - rx, y0 - ry/2)) draw.bezier((), (x-right, y1), (x-right - rx, y1 + ry/2), (x-right - rx/2, y1)) } ) draw.content( ((x-left + x-right - rx) / 2, y0 - ry), p.display-name, anchor: "center" ) } #let _render-custom(x, y, p, m, bottom) = { let image-m = measure(p.custom-image) let y0 = if bottom {y - m.height / 1pt - SYM-GAP} else {y + m.height / 1pt + image-m.height / 1pt + SYM-GAP} draw.content((x - image-m.width / 2pt, y0), p.custom-image, anchor: "north-west") draw.content( (x, y), p.display-name, anchor: if bottom {"north"} else {"south"} ) } #let render(x-pos, p, y: 0, bottom: false) = { let m = measure(box(p.display-name)) let func = ( participant: _render-participant, actor: _render-actor, boundary: _render-boundary, control: _render-control, entity: _render-entity, database: _render-database, collections: _render-collections, queue: _render-queue, custom: _render-custom, ).at(p.shape) func(x-pos.at(p.i), y, p, m, bottom) }
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/brainstorm-drivetrain-sensors.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Brainstorm: Drivetrain Sensors", type: "brainstorm", date: datetime(year: 2023, month: 7, day: 28), author: "<NAME>", witness: "Violet Ridge", ) In order to be able to implement absolute positioning on our robot we will need sensors. These sensors need to be able to do three things: - track our movement forwards and backwards - track our movement side to side - track our rotation #admonition( type: "note", [ Tracking side to side movement is not required unless the robot can strafe, but it helps majorly reduce error over time, so we've decided it would be beneficial. ], ) We came up with three configurations of sensors that would give us odometry capabilities: #grid( columns: (1fr, 1fr), gutter: 20pt, [ = GPS Sensor This configuration uses a single GPS sensor to find our position on the field. This sensor works by finding a pattern similar to a QR code on the edge of the field. #pro-con(pros: [ - Only needs 1 sensor - Doesn't take up much room ], cons: [ - Very noisy - Very expensive - Not all fields support it ]) ], image("/assets/drivetrain/sensor-configs/gps.svg"), [ = Three Tracking Wheels This configuration involved three passive wheels, attached to optical shaft encoders. 2 of the wheels are in parallel to each other, and 1 wheel is perpendicular to the two parallel ones. The parallel wheels track forwards and backwards movement, and can also calculate rotation based on their offset from each other. The perpendicular wheel tracks side to side movement. #admonition( type: "note", [ VEX offers two types of sensors that track rotational movement: the V5 rotation sensor, and the V4 optical shaft encoder. However the V5 sensors are much more expensive, and the V4 sensors are 4 times more accurate due to their larger encoder disc, so we did not consider using the V5 sensors. ], ) #pro-con(pros: [ - Very accurate - Doesn't drift easily ], cons: [ - Takes up a lot of room ]) ], figure( caption: "The wheels can be positioned anywhere on the orange lines without adjusting distances in the code.", image("/assets/drivetrain/sensor-configs/3-tracking-wheels.svg"), ), [ = Two Tracking Wheels and IMU This configuration uses two passive tracking wheels, and 1 IMU (inertial sensor) to track rotation. This setup is identical to the previous one, except the IMU replaces one of the parallel tracking wheels. #pro-con(pros: [ - Takes up less space - Very accurate ], cons: [ - The IMU can drift ]) ], image("/assets/drivetrain/sensor-configs/2-tracking-wheel-imu.svg"), [ = Integrated Motor Encoders This configuration uses the integrated motor encoders as a replacement to tracking wheels. #admonition( type: "warning", [Our drivetrain does not have a perpendicular motor, so this configuration does not support tracking side to side.], ) #pro-con(pros: [ - Does not need any addition sensors ], cons: [ - No side to side tracking - Motor encoders are much less accurate than tracking wheels - Has to compensate for slop in gears, unless directly driven ]) ], image("/assets/drivetrain/sensor-configs/ime.svg"), )
https://github.com/FrightenedFoxCN/cetz-cd
https://raw.githubusercontent.com/FrightenedFoxCN/cetz-cd/main/src/parser.typ
typst
#import "arrows.typ": * #let to-table(str) = { str.split(";") .map(s => s.trim(" ").split("&")) } #let is-direction(str) = { resolve-arrow-string(str) != none } #let possible-styles = ( "->", // ordinary arrow "=>", // double line "-", // single line with no head "=", // double line with no head "-->", // single line dashed "==>", // double line dashed "--", // single line dashed with no head "==", // double line dashed with no head ) #let parse-arrow-info(str) = { let args = str.split(",").map(a => a.trim()) let direction-arg = args.find(is-direction) if direction-arg == none { panic("Direction string not found!") } let style-arg = args.find(a => a in possible-styles) let style = "->" if style-arg != none { style = style-arg } let text-arg = args.find(a => a.starts-with("$")) let text = [] if text-arg != none { // completeness test if not text-arg.ends-with("$") { panic("Unclosed $ sign detected!") } text = eval(text-arg) } let swapped = "swapped" in args let bent-arg = args.find(a => a.starts-with("bent:")) let bent = 0 if bent-arg != none { bent = eval(bent-arg.split(":").last()) } let offset-arg = args.find(a => a.starts-with("offset:")) let offset = 0 if offset-arg != none { offset = eval(offset-arg.split(":").last()) } return arr( direction-arg, style: style, text: text, swapped: swapped, bent: bent, offset: offset ) } #let parse-item(item) = { let math-item = item.matches(regex(`\$(?<mathitem>.*?)\$`.text)) if math-item != () { math-item = eval("$" + math-item.first().captures.first() + "$") } else { return ("", ()) } let arrows = () let arrow-info = item.matches(regex(`ar\[(?<arrowinfo>.*?)\]`.text)) if arrow-info != () { for arrow in arrow-info { arrows.push(parse-arrow-info(arrow.captures.first())) } } (math-item, arrows) } #let parser(str) = { let table = to-table(str) let table-content = () let table-arrows = () for lines in table { let line-content = () let line-arrows = () for item in lines { let (content, arrows) = parse-item(item) line-content.push(content) line-arrows.push(arrows) } table-content.push(line-content) table-arrows.push(line-arrows) } (table-content, table-arrows) }
https://github.com/rabotaem-incorporated/algebra-conspect-1course
https://raw.githubusercontent.com/rabotaem-incorporated/algebra-conspect-1course/master/sections/01-number-theory/10-chinese-rem-th.typ
typst
Other
#import "../../utils/core.typ": * == Китайская теорема об остатках #th[ Пусть $m_1 bot m_2, space.quad a_1, a_2 in ZZ$, тогда: + $exists x_0 in ZZ$: $cases( x_0 equiv_(m_1) a_1, x_0 equiv_(m_2) a_2 )$ + Пусть $x_0$ удовлетворяет системе выше, тогда: $x in ZZ$, где $x$ удовлетворяет системе выше $<==> x equiv_(m_1 m_2) x_0$ ] #proof[ + $x_0 = a_1 + k m_1 = a_2 + l m_2 ==> k m_1 - l m_2 = a_2 - a_1$ --- линейное диофантово уравнение с двумя неизвестными $k, l$ $m_1 bot m_2 ==>$ у него есть решение $(k_0, l_0)$ $x_0 = a_1 + k_0 m_1$ --- искомое + "$arrow.l.double$": $x equiv_(m_1m_2) x_0 ==> cases( x equiv_(m_1) x_0, x equiv_(m_2) x_0 ) ==> cases( x equiv_(m_1) a_1, x equiv_(m_2) a_2 )$ "$arrow.r.double$": $x$ удовлетворяет системе из теоремы $==> cases( x equiv_(m_1) x_0, x equiv_(m_2) x_0 ) ==> cases( m_1 divides (x - x_0), m_2 divides (x - x_0) ) limits(==>)^(m_1 bot m_2) m_1 m_2 divides (x - x_0)$ ] #def[ Пусть $R, S$ --- кольца с единицей. Отображение $phi: R -> S$ называется изоморфизмом колец, если: $phi$ биекция. + $forall r_1, r_2: space phi(r_1 + r_2) = phi(r_1) + phi(r_2)$ + $forall r_1, r_2: space phi(r_1 r_2) = phi(r_1) phi(r_2)$ ] #pr[ Пусть $m_1 bot m_2$, тогда существует изоморфизм: $factor(ZZ, m_1 m_2) -> factor(ZZ, m_1 ZZ) times factor(ZZ, m_2 ZZ)$ $[a]_(m_1m_2) |-> ([a]_(m_1), [a]_(m_2))$ ] #proof[ Проверим корректность: "при подстановке одинаковых классов": Пусть $[a]_(m_1m_2) = [a']_(m_1m_2) ==>$ $a equiv_(m_1m_2) a' ==>$ $cases( a equiv_(m_1) a', a equiv_(m_2) a' ) ==> ([a]_(m_1), [a]_(m_2)) = ([a']_(m_1), [a']_(m_2))$ "сложения": $phi([a]_(m_1m_2) + [b]_(m_1m_2)) = phi([a + b]_(m_1m_2)) = ([a + b]_(m_1), [a + b]_(m_2)) = $ $([a]_(m_1), [a]_(m_2)) + ([b]_(m_1), [b]_(m_2)) = phi([a]_(m_1m_2)) + phi([b]_(m_1m_2))$ "умножения": $phi([a]_(m_1m_2) dot.c [b]_(m_1m_2)) = phi([a dot.c b]_(m_1m_2)) = ([a dot.c b]_(m_1), [a dot.c b]_(m_2)) = $ $([a]_(m_1), [a]_(m_2)) dot.c ([b]_(m_1), [b]_(m_2)) = phi([a]_(m_1m_2)) dot.c phi([b]_(m_1m_2))$ Проверим биективность, инъективность и сюръективность: $phi$ --- отображение между конечными равномощными множествами, поэтому оно биективно $<==>$ оно сюръективно $<==>$ оно инъективно. Действительно, если $phi: A -> B, space |A| = |B| < oo$ инъективно, то полный прообраз любого элемента из $B$ состоит из не более чем одного элемента из $A$ (определение инъективности). А если сложить количества прообразов у всех элементов из $B$, то должно получиться в точности $|A|$, так как каждый прообраз --- чей-то образ. Но тогда каждый прообраз состоит из в точности одного элемента, т. е. $phi$ --- биекция. Аналогично можно рассуждать и про сюрьективное отображение. По китайской теореме об остатках $forall a_1, a_2 in ZZ space exists a in ZZ: cases( a equiv_(m_1) a_1, a equiv_(m_2) a_2 )$ Таким образом $phi$ --- биекция. ]
https://github.com/appare45/Typst-template
https://raw.githubusercontent.com/appare45/Typst-template/main/readme.md
markdown
# Typst-template macでビルド可能なGitHub Actions付きTypest Template [![Build](https://github.com/appare45/Typst-template/actions/workflows/build.yaml/badge.svg)](https://github.com/appare45/Typst-template/actions/workflows/build.yaml) ## Credit クレジットを設定する必要がある。 クレジットは`.env`より提供される。 ``` CREDIT=appare45 ``` ## Build ### Dockerを使う場合 ```bash docker compose up build ``` ### Typstをそのまま使う場合 ```bash typst compile --input CREDIT="appare45" file.typ ``` ## Watch ### Dockerを使う場合 この場合は`./file.typ`のみがコンパイルされるため、複数ファイルをwatchする必要がある場合は`./file.typ`に`#include`を使う ```bash docker compose watch ``` 終了時は ```bash docker kill typst ``` ### Typstをそのまま使う場合 ```bash typst watch --input CREDIT="appare45" file.typ ```
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/169.%20bias.html.typ
typst
bias.html A Way to Detect Bias October 2015This will come as a surprise to a lot of people, but in some cases it's possible to detect bias in a selection process without knowing anything about the applicant pool. Which is exciting because among other things it means third parties can use this technique to detect bias whether those doing the selecting want them to or not.You can use this technique whenever (a) you have at least a random sample of the applicants that were selected, (b) their subsequent performance is measured, and (c) the groups of applicants you're comparing have roughly equal distribution of ability.How does it work? Think about what it means to be biased. What it means for a selection process to be biased against applicants of type x is that it's harder for them to make it through. Which means applicants of type x have to be better to get selected than applicants not of type x. [1] Which means applicants of type x who do make it through the selection process will outperform other successful applicants. And if the performance of all the successful applicants is measured, you'll know if they do.Of course, the test you use to measure performance must be a valid one. And in particular it must not be invalidated by the bias you're trying to measure. But there are some domains where performance can be measured, and in those detecting bias is straightforward. Want to know if the selection process was biased against some type of applicant? Check whether they outperform the others. This is not just a heuristic for detecting bias. It's what bias means.For example, many suspect that venture capital firms are biased against female founders. This would be easy to detect: among their portfolio companies, do startups with female founders outperform those without? A couple months ago, one VC firm (almost certainly unintentionally) published a study showing bias of this type. First Round Capital found that among its portfolio companies, startups with female founders outperformed those without by 63%. [2]The reason I began by saying that this technique would come as a surprise to many people is that we so rarely see analyses of this type. I'm sure it will come as a surprise to First Round that they performed one. I doubt anyone there realized that by limiting their sample to their own portfolio, they were producing a study not of startup trends but of their own biases when selecting companies.I predict we'll see this technique used more in the future. The information needed to conduct such studies is increasingly available. Data about who applies for things is usually closely guarded by the organizations selecting them, but nowadays data about who gets selected is often publicly available to anyone who takes the trouble to aggregate it. Notes[1] This technique wouldn't work if the selection process looked for different things from different types of applicants—for example, if an employer hired men based on their ability but women based on their appearance.[2] As <NAME> points out, First Round excluded their most successful investment, Uber, from the study. And while it makes sense to exclude outliers from some types of studies, studies of returns from startup investing, which is all about hitting outliers, are not one of them. Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this.Arabic TranslationSwedish Translation
https://github.com/jonathan-iksjssen/jx-style
https://raw.githubusercontent.com/jonathan-iksjssen/jx-style/main/0.2.0/irgot.typ
typst
#let coll = ( "red": ( "bg": rgb("#FEF2F2"), "tx": rgb("#450A0A"), "ac": rgb("#DC2626"), "la": rgb("#FECACA"), "da": rgb("#991B1B") ), "scarlet": ( "bg": rgb("#FFF5F0"), "tx": rgb("#440F09"), "ac": rgb("#E33F19"), "la": rgb("#FED1BA"), "da": rgb("#9A2817") ), "orange": ( "bg": rgb("#FFF7ED"), "tx": rgb("#431407"), "ac": rgb("#EA580C"), "la": rgb("#FED7AA"), "da": rgb("#9A3412") ), "amber": ( "bg": rgb("#FFFBEB"), "tx": rgb("#451A03"), "ac": rgb("#D97706"), "la": rgb("#FDE68A"), "da": rgb("#92400E") ), "yellow": ( "bg": rgb("#FEFCE8"), "tx": rgb("#422006"), "ac": rgb("#CA8A04"), "la": rgb("#FEF08A"), "da": rgb("#854D0E") ), "altyellow": ( "bg": rgb("#FEFeE8"), "tx": rgb("#423006"), "ac": rgb("#caa204"), "la": rgb("#fef88a"), "da": rgb("#85610e") ), "pear": ( "bg": rgb("#FBFDE8"), "tx": rgb("#2E2F06"), "ac": rgb("#98A309"), "la": rgb("#ECF994"), "da": rgb("#626210") ), "lime": ( "bg": rgb("#F7FEE7"), "tx": rgb("#1A2E05"), "ac": rgb("#65A30D"), "la": rgb("#D9F99D"), "da": rgb("#3F6212") ), "limegreen": ( "bg": rgb("#F5FEEB"), "tx": rgb("#132E0B"), "ac": rgb("#4BA321"), "la": rgb("#CFF8AE"), "da": rgb("#31631D") ), "midgreen": ( "bg": rgb("#F4FEEE"), "tx": rgb("#102E0E"), "ac": rgb("#43A72E"), "la": rgb("#CAF8B7"), "da": rgb("#2B6423") ), "pregreen": ( "bg": rgb("#F2FEF1"), "tx": rgb("#0B2E12"), "ac": rgb("#2DA53C"), "la": rgb("#C3F8C4"), "da": rgb("#21652C") ), "green": ( "bg": rgb("#F0FDF4"), "tx": rgb("#052E16"), "ac": rgb("#16A34A"), "la": rgb("#BBF7D0"), "da": rgb("#166534") ), "postgreen": ( "bg": rgb("#EEFDF5"), "tx": rgb("#042D1C"), "ac": rgb("#0E9D5A"), "la": rgb("#B1F5D0"), "da": rgb("#0E623D") ), "emerald": ( "bg": rgb("#ECFDF5"), "tx": rgb("#022C22"), "ac": rgb("#059669"), "la": rgb("#A7F3D0"), "da": rgb("#065F46") ), "teal": ( "bg": rgb("#F0FDFA"), "tx": rgb("#042F2E"), "ac": rgb("#0D9488"), "la": rgb("#99F6E4"), "da": rgb("#115E59") ), "cyan": ( "bg": rgb("#F0FDFA"), "tx": rgb("#083344"), "ac": rgb("#0891B2"), "la": rgb("#A5F3FC"), "da": rgb("#155E75") ), "sky": ( "bg": rgb("#F0F9FF"), "tx": rgb("#082F49"), "ac": rgb("#0284C7"), "la": rgb("#BAE6FD"), "da": rgb("#075985") ), "blue": ( "bg": rgb("#EFF6FF"), "tx": rgb("#172554"), "ac": rgb("#2563EB"), "la": rgb("#BFDBFE"), "da": rgb("#1E40AF") ), "midblue": ( "bg": rgb("#EFF4FF"), "tx": rgb("#1B2050"), "ac": rgb("#3A55E8"), "la": rgb("#C3D7FE"), "da": rgb("#2B38A9") ), "indigo": ( "bg": rgb("#EEF2FF"), "tx": rgb("#1E1B4B"), "ac": rgb("#4F46E5"), "la": rgb("#C7D2FE"), "da": rgb("#3730A3") ), "violet": ( "bg": rgb("#F5F3FF"), "tx": rgb("#2E1065"), "ac": rgb("#7C3AED"), "la": rgb("#DDD6FE"), "da": rgb("#5B21B6") ), "purple": ( "bg": rgb("#FAF5FF"), "tx": rgb("#3B0764"), "ac": rgb("#9333EA"), "la": rgb("#E9D5FF"), "da": rgb("#6B21A8") ), "magenta": ( "bg": rgb("#FDF4FF"), "tx": rgb("#4A044E"), "ac": rgb("#C026D3"), "la": rgb("#F5D0FE"), "da": rgb("#86198F") ), "fuschia": ( "bg": rgb("#FDF3FC"), "tx": rgb("#4D0639"), "ac": rgb("#CE27A5"), "la": rgb("#F8D0F3"), "da": rgb("#92186E") ), "pink": ( "bg": rgb("#FDF2F8"), "tx": rgb("#500724"), "ac": rgb("#DB2777"), "la": rgb("#FBCFE8"), "da": rgb("#9D174D") ), "rose": ( "bg": rgb("#FFF1F2"), "tx": rgb("#4C0519"), "ac": rgb("#E11D48"), "la": rgb("#FECDD3"), "da": rgb("#9F1239") ), "warmgrey": ( "bg": rgb("#FCFCF8"), "tx": rgb("#19130D"), "ac": rgb("#6A6459"), "la": rgb("#E1DDD8"), "da": rgb("#352E28") ), "white": ( "bg": rgb("#ffffff"), "tx": rgb("#000000"), "ac": rgb("#525252"), "la": rgb("#D4D4D4"), "da": rgb("#262626") ), "grey": ( "bg": rgb("#FAFAFA"), "tx": rgb("#0A0A0A"), "ac": rgb("#525252"), "la": rgb("#D4D4D4"), "da": rgb("#262626") ), "lightgrey": ( "bg": rgb("#FAFAFA"), "tx": rgb("#0A0A0A"), "ac": rgb("#777777"), "la": rgb("#D4D4D4"), "da": rgb("#444444") ), "greengrey": ( "bg": rgb("#F9FCF8"), "tx": rgb("#0D1910"), "ac": rgb("#596A5B"), "la": rgb("#DBE1D8"), "da": rgb("#28352A") ), "bluegrey": ( "bg": rgb("#F8FAFC"), "tx": rgb("#020617"), "ac": rgb("#475569"), "la": rgb("#CBD5E1"), "da": rgb("#1E293B") ), "brown": ( "bg": rgb("#EFEBE9"), "tx": rgb("#3E2723"), "ac": rgb("#795548"), "la": rgb("#CCB7B0"), "da": rgb("#4E342E") ), "pine": ( "bg": rgb("#EFEBE9"), "tx": rgb("#17312B"), "ac": rgb("#478D6A"), "la": rgb("#a7c59a"), "da": rgb("#225443") ), "bluepine": ( "bg": rgb("#EFEBE9"), "tx": rgb("#272a3c"), "ac": rgb("#6e78b2"), "la": rgb("#b2bbe7"), "da": rgb("#40466b") ), "redpine": ( "bg": rgb("#EFEBE9"), "tx": rgb("#311010"), "ac": rgb("#bf545c"), "la": rgb("#e9aab1"), "da": rgb("#611E1E") ), "orangepine": ( "bg": rgb("#EFEBE9"), "tx": rgb("#361409"), "ac": rgb("#a84a1b"), "la": rgb("#efa789"), "da": rgb("#682c10") ), "copper": ( "bg": rgb("#FAF2F0"), "tx": rgb("#27120E"), "ac": rgb("#9D4A39"), "la": rgb("#E5BFB8"), "da": rgb("#5A2A20") ), "gold": ( "bg": rgb("#F6F1E2"), "tx": rgb("#2C200E"), "ac": rgb("#A68036"), "la": rgb("#E5D7AE"), "da": rgb("#60481F") ), "rosegold": ( "bg": rgb("#f4e6e8"), "tx": rgb("#3a1319"), "ac": rgb("#A5525F"), "la": rgb("#D5ABB2"), "da": rgb("#68343B") ), "herald": ( "bg": rgb("#f8ece1"), "tx": rgb("#353542"), "ac": rgb("#355eb4"), "la": rgb("#eac879"), "da": rgb("#7f1e33") ), "sti": ( "bg": rgb("#FDFDFD"), "tx": rgb("#00074E"), "ac": rgb("#CA8D3C"), "la": rgb("#F5DE80"), "da": rgb("#09398B") ), "rosépine-dawn": ( "bg": rgb("#faf4ed"), "tx": rgb("#232136"), "ac": rgb("#d7827e"), "la": rgb("#ebbcba"), "da": rgb("#286983") ), "aroallo": ( "bg": rgb("#F5FAED"), "tx": rgb("#11572C"), "ac": rgb("#D17F14"), "la": rgb("#F0D854"), "da": rgb("#4B8624") ), "aro": ( "bg": rgb("#F5FAED"), "tx": rgb("#252525"), "ac": rgb("#4B8624"), "la": rgb("#C9C9C9"), "da": rgb("#11572C") ), "aroace": ( "bg": rgb("#F5FAED"), "tx": rgb("#431407"), "ac": rgb("#D97706"), "la": rgb("#A5F3FC"), "da": rgb("#0369A1") ), "bi": ( "bg": rgb("#FDF2F8"), "tx": rgb("#1E1B4B"), "ac": rgb("#9C26B4"), "la": rgb("#FBCFE8"), "da": rgb("#3730A3") ), "defgreen": ( "bg": rgb("#F6F8F1"), "tx": rgb("#0E0E25"), "ac": rgb("#288F56"), "la": rgb("#B4F2B9"), "da": rgb("#38378F") ), "uc": ( "bg": rgb("#F8FCFA"), "tx": rgb("#001812"), "ac": rgb("#059669"), "la": rgb("#A7F3D0"), "da": rgb("#065F46") ), "solarised-l": ( "bg": rgb("#fdf6e3"), "tx": rgb("#002b36"), "ac": rgb("#2aa198"), "la": rgb("#C1C5BB"), "da": rgb("#206492") ), "nord-light": ( "bg": rgb("#ECEFF4"), "tx": rgb("#2E3440"), "ac": rgb("#88C0D0"), "la": rgb("#D8DEE9"), "da": rgb("#4C566A") ), "default": ( "bg": rgb("#f0f4ff"), "tx": rgb("#070733"), "ac": rgb("#5567cf"), "la": rgb("#bccbf2"), "da": rgb("#1a1681") ), "altdark": ( "bg": rgb("#272736"), "tx": rgb("#f8ece1"), "ac": rgb("#a9a8ee"), "la": rgb("#484764"), "da": rgb("#C8BCA1") ), "dark": ( "bg": rgb("#1E1E2A"), "tx": rgb("#F7EFE7"), "ac": rgb("#d66087"), "la": rgb("#363575"), "da": rgb("#949dec") ), "ocean": ( "bg": rgb("#0b0c13"), "tx": rgb("#E6EAFC"), "ac": rgb("#6D5CFF"), "la": rgb("#393182"), "da": rgb("#AAA3FE") ), "bluewood": ( "bg": rgb("#171729"), "tx": rgb("#d8d8d8"), "ac": rgb("#6f90dc"), "la": rgb("#354ba5"), "da": rgb("#87b7e1") ), "darker": ( "bg": rgb("#111114"), "tx": rgb("#f8f5f2"), "ac": rgb("#d66087"), "la": rgb("#363575"), "da": rgb("#94aaec") ), "darkerer": ( "bg": rgb("#080814"), "tx": rgb("#d0d0d0"), "ac": rgb("#5f70dc"), "la": rgb("#252b65"), "da": rgb("#909ee9") ), "rosépine": ( "bg": rgb("#191724"), "tx": rgb("#e0def4"), "ac": rgb("#9ccfd8"), "la": rgb("#403d52"), "da": rgb("#ebbcba") ), "rosépine-moon": ( "bg": rgb("#232136"), "tx": rgb("#e0def4"), "ac": rgb("#9ccfd8"), "la": rgb("#44415a"), "da": rgb("#ea9a97") ), "solarised-d": ( "bg": rgb("#002b36"), "tx": rgb("#fdf6e3"), "ac": rgb("#2aa198"), "la": rgb("#206492"), "da": rgb("#C1C5BB") ), "nord-dark": ( "bg": rgb("#2E3440"), "tx": rgb("#ECEFF4"), "ac": rgb("#88C0D0"), "la": rgb("#4C566A"), "da": rgb("#D8DEE9") ), "ayu-custom": ( "bg": rgb("#0D1017"), "tx": rgb("#d5d4ce"), "ac": rgb("#6668d8"), "la": rgb("#282565"), "da": rgb("#7f9cdf") ), "days-of-week": ( "monday": rgb("#93C5FD50"), "tuesday": rgb("#FCA5A550"), "wednesday": rgb("#86EFAC50"), "thursday": rgb("#FDE04750"), "friday": rgb("#67E8F950"), "saturday": rgb("#F0ABFC50"), "sunday": rgb("#D4D4D450") ) ) #set text(font: "Iosevka SS14", size: 16pt) #set par(leading: 0em) #for i in coll.keys() { if(i == "days-of-week") {continue;} box(inset: 1em)[#i]; h(1fr) for k in coll.at(i).keys() { box(rect(width: 0.75in, fill: coll.at(i).at(k)), stroke: 2pt + black) } linebreak(); }
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/ref.typ
typst
// Test references. --- ref-basic --- #set heading(numbering: "1.") = Introduction <intro> See @setup. == Setup <setup> As seen in @intro, we proceed. --- ref-label-missing --- // Error: 1-5 label `<foo>` does not exist in the document @foo --- ref-label-duplicate --- = First <foo> = Second <foo> // Error: 1-5 label `<foo>` occurs multiple times in the document @foo --- ref-supplements --- #set heading(numbering: "1.", supplement: [Chapter]) #set math.equation(numbering: "(1)", supplement: [Eq.]) = Intro #figure( image("/assets/images/cylinder.svg", height: 1cm), caption: [A cylinder.], supplement: "Fig", ) <fig1> #figure( image("/assets/images/tiger.jpg", height: 1cm), caption: [A tiger.], supplement: "Tig", ) <fig2> $ A = 1 $ <eq1> #set math.equation(supplement: none) $ A = 1 $ <eq2> @fig1, @fig2, @eq1, (@eq2) #set ref(supplement: none) @fig1, @fig2, @eq1, @eq2 --- ref-ambiguous --- // Test ambiguous reference. = Introduction <arrgh> // Error: 1-7 label occurs in the document and its bibliography @arrgh #bibliography("/assets/bib/works.bib") --- issue-4536-non-whitespace-before-ref --- // Test reference with non-whitespace before it. #figure[] <1> #test([(#ref(<1>))], [(@1)])
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/transform-03.typ
typst
Other
// Test setting scaling origin. #let r = rect(width: 100pt, height: 10pt, fill: red) #set page(height: 65pt) #box(scale(r, x: 50%, y: 200%, origin: left + top)) #box(scale(r, x: 50%, origin: center)) #box(scale(r, x: 50%, y: 200%, origin: right + bottom))
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/cpp/lectures/main.typ
typst
#import "/utils/template.typ": conf #import "/utils/datestamp.typ": datestamp #show: body => conf( title: "C++", subtitle: "Лекции", author: "<NAME>, БПИ233", year: [2024--2025], body, ) #datestamp("2024-09-13") #include "./2024-09-13.typ" #datestamp("2024-09-20") #include "2024-09-20.typ" #datestamp("2024-09-27") #include "2024-09-27.typ" #datestamp("2024-10-04") #include "2024-10-04.typ" #datestamp("2024-10-11") #include "2024-10-11.typ" #datestamp("2024-10-18") #include "2024-10-18.typ"
https://github.com/swaits/typst-collection
https://raw.githubusercontent.com/swaits/typst-collection/main/glossy/0.1.0/README.md
markdown
MIT License
# Glossy This package provides utilities to manage and render glossaries within documents. It includes functions to define and use glossary terms, track their usage, and generate a glossary list with references to where terms are used in the document. ![image of sample output](thumbnail.png) ## Motivation Glossy is heavily inspired by [glossarium](https://typst.app/universe/package/glossarium), with a few key different goals: 1. Provide a simple interface which allows for complete control over glossary display. To do this, `glossy`'s `#glossary()` function accepts a theme parameter. The goal here is to separate presentation and logic. 1. Simplify the user interface as much as possible. Glossy has exactly two exports, `init-glossary` and `glossary`. 1. Double-down on `glossy`'s excellent `@term` reference approach, completely eliminating the need to make any calls to `gls()` and friends. 1. Mimic established patterns and best practices. For example, `glossy`'s `#glossary()` function is intentionally similar (in naming and parameters) to `typst`'s built-int `#bibliography`, to the degree possible. 1. Simplify the implementation. The `glossy` code is significantly shorter and easier to understand. ## Features - Define glossary terms with short and long forms, descriptions, and grouping. - Automatically tracks term usage in the document, making references simple through @labels. - Supports modifiers to adjust how terms are displayed (capitalize, pluralize, etc.). - Generates a formatted glossary section with backlinks to term occurrences in the document. - Easily customizable themes for rendering glossary sections, groups, and entries. ## Usage ### Import the package ```typst #import "@preview/glossy:0.1.0": * ``` ### Defining Glossary Terms Use the `init-glossary` function to initialize glossary entries and process document content: ```typst #let myGlossary = ( ( key: "html", short: "HTML", long: "Hypertext Markup Language", description: "A standard language for creating web pages", group: "Web" ), ( key: "css", short: "CSS", long: "Cascading Style Sheets", description: "A stylesheet language used for describing the presentation of a document", group: "Web" ), ( key: "tps", short: "TPS", long: "test procedure specification" ), // Add more entries as needed ) #show: init-glossary.with(myGlossary) // Your document content here, where glossary terms are used. ``` Note that you could also load glossary entries from a data file using [#yaml()](https://typst.app/docs/reference/data-loading/yaml/), [#json()](https://typst.app/docs/reference/data-loading/json/), or [similar](https://typst.app/docs/reference/data-loading/). ### Using Glossary Terms in Your Document Use glossary terms within your text using the `@reference` functionality in typst. For example, `@html` and `@css` are used in the following text: ```typst In modern web development, languages like @html and @css are essential. Now make sure I get your @tps:short reports by 2pm! ``` ... which should output: ```text In modern web development, languages like Hypertext Markup Language (HTML) and Cascading Style Sheets (CSS) are essential. Now make sure I get your TPS reports by 2pm! ``` You can control how each term is displayed using the following modifiers: - **cap**: Capitalizes the term. - **pl**: Uses the plural form of the term. - **both**: Displays both the long and short forms (e.g., "Long Form (Short Form)"). - **short**: Displays only the short form. - **long**: Displays only the long form. Each modifier is separated by a colon (':') character. Examples: | **Input** | **Output** | | ----------------------- | -------------------------------------------- | | `@tps` (first use) | "technical procedure specification (TPS)" | | `@tps` (subsequent use) | "TPS" | | `@tps:short` | "TPS" | | `@tps:long` | "technical procedure specification (TPS)" | | `@tps:both` | "technical procedure specification (TPS)" | | `@tps:long:cap` | "Technical procedure specification" | | `@tps:long:pl` | "technical procedure specifications" | | `@tps:short:pl` | "TPSes" | | `@tps:both:pl:cap` | "Technical procedure specifications (TPSes)" | Combine modifiers in any way you like. But know that if you combine any of `short`, `long`, and/or `both`, only one will be used. ### Generating the Glossary To display the glossary in your document, use the `glossary` function. Customize the title and specify a theme if desired: ```typst #glossary(title: "Web Development Glossary", theme: my-theme, groups: ("Web")) ``` ### Themes Customize the appearance of the glossary using themes. Each theme defines how sections, groups, and entries are displayed. - **section**: This is a main glossary section. It contains multiple glossary groups. - **group**: A group within the main glossary section. Contains multiple entries. Can be `none`. - **entry**: A single entry within a group. This is the actual term, and can include any of the fields in entry. Contains the following fields: - `key`: The term key. (always present and unique) - `short`: The short form of the term. (always present) - `long`: The long form. (can be `none`) - `description`: The description or definition. (can be `none`) - `pages`: Pages with links to term usage in doc. (always present) Example of a minimal theme: ```typst #let my-theme = ( section: (title, body) => { heading(level: 1, title) body }, group: (name, body) => { if name != none and name != "" { heading(level: 2, name) } body }, entry: (entry, i, n) => { // i is the entry's index, n is total number of entries let output = [#entry.short] if entry.long != none { output = [#output -- #entry.long] } if entry.description != none { output = [#output: #entry.description] } block( grid( columns: (auto, 1fr, auto), output, repeat([#h(0.25em) . #h(0.25em)]), entry.pages, ) ) } ) ``` ## License This project is licensed under the MIT License.
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/figures/06-automated-modularization/algorithms.typ
typst
#import "@preview/cetz:0.2.2" #let algorithms = yaml("/bibliography/literature-review.yml").at("categories").at("algorithms") #let total = algorithms.values().sum().len() #let data = ( ([Clustering#linebreak()algorithms#v(8em)], algorithms.at("clustering").len()), ([Other algorithms], algorithms.at("other").len()), ([#h(5em)Evolutionary\ #h(5em)algorithms#v(2em)], algorithms.at("evolutionary").len()), ([#h(6em)Graph algorithms], algorithms.at("graph").len()), ) #cetz.canvas(length: .75cm, { import cetz.chart import cetz.draw: * let colors = ( cmyk(0%, 75%, 79%, 0%), cmyk(23%, 26%, 0%, 28%), cmyk(65%, 0%, 2%, 35%), cmyk(34%, 0%, 60%, 18%), ) chart.piechart( data, clockwise: false, value-key: 1, label-key: 0, radius: 3, slice-style: colors, inner-radius: 1, inner-label: (content: (value, label) => [#text(size: 10pt, white, str(calc.round(100 * value / total, digits: 0)) + "%")], radius: 110%), outer-label: (content: (value, label) => [#label], radius: 120%)) })
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis
https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/docs/chapter1.typ
typst
// #include "../tools/multi-section-ref.typ" // #import "../tools/macros.typ": eqref #include "../tools/multi-section-ref.typ" #import "../tools/macros.typ": eqref #import "../typst-orange.typ": theorem, proof, lemma, proposition, corollary, example // Nhớ đánh số trang và footnote // Canh đều toàn văn bản //#set align() //nhớ thêm tích Hamdamard //LỜI CẢM ƠN // //PHẦN MỞ ĐẦU // 1. LÝ DO CHỌN ĐỀ TÀI // 2. MỤC TIÊU CHỌN ĐỀ TÀI // 3. ĐỐI TƯỢNG VÀ PHẠM VI NGHIÊN CỨU // 4. PP NGHIÊN CỨU // 5. ĐÓNG GÓP ĐỀ TÀI // 6. CẤU TRÚC ĐỀ TÀI // #set math.equation(numbering: "(1)") // #import "../typst-orange.typ": chapter // #set page(numbering: "1") // #set page(header: [ // _Luận văn - Nguyễn Đặng Ngọc Ngân_ // #h(1fr) // Trường Đại học Cần Thơ // ]) // = #text(orange)[*CHƯƠNG 1: KIẾN THỨC CHUẨN BỊ*] = KIẾN THỨC CHUẨN BỊ == LÝ THUYẾT ĐỒ THỊ // === Đồ thị // @alizadehBudgetconstrainedInverseMedian2020a // == #text(orange)[1. LÝ THUYẾT ĐỒ THỊ] // === #text(orange)[1.1 ĐỒ THỊ] === Khái niệm đồ thị Trong thực tế, việc biểu diễn các đối tượng và mối quan hệ giữa chúng là vô cùng quan trọng, phục vụ cho nhiều mục đích trong các lĩnh vực khác nhau. Ví dụ, trong mạng xã hội, để nghiên cứu mối quan hệ của các cá nhân với nhau, chúng ta cần một công cụ có thể mô hình hóa các kết nối này một cách trực quan và hiệu quả. Đồ thị là công cụ hữu ích để thực hiện việc này. Ngoài mạng xã hội, đồ thị còn được ứng dụng rộng rãi trong nhiều lĩnh vực khác. Ví dụ, trong giao thông, đồ thị giúp mô phỏng các điểm đến và các tuyến đường kết nối, từ đó tối ưu hóa hành trình di chuyển, giảm thiểu tắc nghẽn và tiết kiệm thời gian. Trong quản lý chuỗi cung ứng, đồ thị có thể hỗ trợ việc theo dõi quá trình vận chuyển hàng hóa giữa các nhà kho và điểm giao nhận, từ đó tối ưu hóa quy trình, giảm chi phí và cải thiện hiệu suất. Nhờ khả năng trực quan hóa mối quan hệ giữa các đối tượng, đồ thị đã trở thành một công cụ quan trọng trong việc phân tích và giải quyết các vấn đề phức tạp trong đời sống thực tế, từ nghiên cứu mạng xã hội đến quản lý giao thông và chuỗi cung ứng. Tóm lại, đồ thị là gì? Đồ thị $G$ trong lý thuyết đồ thị là một cấu trúc toán học được sử dụng để mô tả mối quan hệ giữa các đối tượng. Một đồ thị (graph) $G$ là một bộ ba $(V(G),E(G),psi_G)$ bao gồm một tập khác rỗng $V(G)$ các đỉnh (vertices) của $G$, một tập $E(G)$ các cạnh (edges) của $G$, và một hàm liên thuộc (incidence function) $psi_G$ đặt tương ứng mỗi cạnh với một cặp đỉnh không theo thứ tự (hai đỉnh không nhất thiết phải khác nhau). Nếu $e$ là một cạnh và $u,v$ là hai đỉnh sao cho $psi_G(e) = u v$, thì ta nói $e$ nối $u$ và $v$; các đỉnh $u$ và $v$ được gọi là các điểm đầu mút (ends) của $e$. Ví dụ, ta xét đồ thị $G=(V(G),E(G),psi_G)$ với $V(G)={v_1,v_2,v_3,v_4,v_5}, E(G)={e_1,e_2,e_3,e_4,e_5,e_6}$ và $psi_G$ được xác định bởi $psi_G(e_1)=v_1v_2, psi_G(e_2)=v_2v_3, psi_G(e_3)= v_2v_4, psi_G(e_4)=v_1v_5, psi_G(e_5)=v_3v_5, psi_G(e_6)=v_1v_4$. Hình bên dưới là một biểu diễn hình học của đồ thị $G$. #import "@preview/cetz:0.1.2": canvas, plot #import "@preview/cetz:0.1.2" // #import "@preview/cetz:0.2.2" #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((2, 1), radius: 0.05,fill:black, name: "v3") content("v3.right", $v_3$, anchor: "bottom", padding: 0.2) circle((-1, 0), radius: 0.05,fill:black, name: "v4") content("v4.bottom", $v_4$, anchor: "left", padding: 0.2) circle((-3, 1), radius: 0.05, fill: black, name: "v5") content("v5.bottom", $v_5$, anchor: "right", padding: 0.2) //circle((0*h, 1), radius: 0.05, fill: black, name: "v7") //content("v7.bottom", $v_7 (0.06)$, anchor: "left", padding: 0.2) //circle((2*h, 2), radius: 0.05, fill: black, name: "v4") //content("v4.bottom", $v_4 (0.15)$, anchor: "left", padding: 0.2) //circle((1*h, 1), radius: 0.05, fill: black, name: "v8") //content("v8.bottom", $v_8 (0.2)$, anchor: "left", padding: 0.2) //circle((3*h, 1), radius: 0.05, fill:black, name: "v9") //content("v9.bottom", $v_9 (0.1)$, anchor: "left", padding: 0.2) line("v1", "v2", name: "v1v2") content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.2) line("v2", "v3", name: "v2v3") content("v2v3.top", $e_2$, anchor: "top", padding: 0.7) line("v2", "v4", name: "v2v4") content("v2v4.top", $e_3$, anchor: "top", padding: 0.9) line("v5", "v1", name: "v5v1") content("v5v1.top", $e_4$, anchor: "top", padding: 1.1) line("v3", "v5", name: "v3v5") content("v3v5.top", $e_5$, anchor: "top", padding: 0.1) line("v4", "v1", name: "v4v1") content("v4v1.top", $e_6$, anchor: "top", padding: 1.4) // line("v4", "v8") // line("v4", "v9") } )] #align(center)[#text(orange)[*Hình 1.1*] Minh họa biểu diễn hình học của một đồ thị] Ví dụ: Trong một đồ thị, các đỉnh có thể biểu thị cho các cá nhân, trong khi các cạnh biểu thị cho mối quan hệ bạn bè giữa các cá nhân đó. Trong hệ thống giao thông, các thành phố được biểu diễn bằng cách đỉnh và các tuyến đường nối giữa chúng là các cạnh. // //#align(center)[ // #import "@preview/bob-draw:0.1.0": * // #show raw.where(lang: "bob"): it => render(it) // #render( // ``` // 1 2 3 // *------*--------* // 4 / 5 / / // *------* * 6 // \ / // \ / // *---------* 8 // 7 // ```, // width: 40%, // )] //#align(center)[#text(orange)[*Hình 1.1*] Minh họa biểu diễn hình học của một đồ thị] Đồ thị vô hướng (undirected graph) là một loại đồ thị trong đó các cạnh không có hướng. Điều này có nghĩa là nếu có một cạnh giữa hai đỉnh $u$ và $v$ thì cạnh này có thể được đi từ $u$ đến $v$ và ngược lại có thể đi từ $v$ đến $u$ . Nói cách khác, mối quan hệ giữa các đỉnh là hai chiều và không có sự phân biệt về hướng. Hình 1.1 bên trên là đồ thị vô hướng. Trong khi đó, đồ thị có hướng (directed graph) là một loại đồ thị trong đó mỗi cạnh có hướng. Điều này có nghĩa là mỗi cạnh được biểu diễn bởi một cặp đỉnh có thứ tự, chỉ định hướng đi từ đỉnh đầu đến đỉnh cuối. Trong đồ thị có hướng, nếu có cạnh từ đỉnh $u$ đến đỉnh $v$ thì không nhất thiết phải có cạnh từ đỉnh $v$ đến đỉnh $u$. Hình bên dưới là một ví dụ của đồ thị có hướng. #import "@preview/cetz:0.1.2": canvas, plot #import "@preview/cetz:0.2.2" #import "@preview/cetz:0.1.2" #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((2, 1), radius: 0.05,fill:black, name: "v3") content("v3.right", $v_3$, anchor: "bottom", padding: 0.2) circle((-1, 0), radius: 0.05,fill:black, name: "v4") content("v4.bottom", $v_4$, anchor: "left", padding: 0.2) circle((-3, 1), radius: 0.05, fill: black, name: "v5") content("v5.bottom", $v_5$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2", mark:(end: ">", fill: orange)) content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.2) line("v2", "v3", name: "v2v3", mark:(end: ">", fill: orange)) content("v2v3.top", $e_2$, anchor: "top", padding: 0.7) line("v2", "v4", name: "v2v4", mark:(end: ">", fill: orange)) content("v2v4.top", $e_3$, anchor: "top", padding: 0.9) line("v5", "v1", name: "v5v1", mark:(end: ">", fill: orange)) content("v5v1.top", $e_4$, anchor: "top", padding: 1.1) line("v3", "v5", name: "v3v5", mark: (end: ">", fill: orange)) content("v3v5.top", $e_5$, anchor: "top", padding: 0.1) line("v4", "v1", name: "v4v1", mark:(end: ">", fill: orange)) content("v4v1.top", $e_6$, anchor: "top", padding: 1.4) // line("v4", "v8") // line("v4", "v9") } )] #align(center)[#text(orange)[*Hình 1.2*] Đồ thị có hướng] Đồ thị có trọng số (Weighted Graph) là loại đồ thị trong đó các đỉnh và các cạnh được gán các giá trị trọng số. Trọng số của đỉnh thường biểu thị các yếu tố như dân số, tài nguyên hoặc mức độ quan trọng của điểm đó, trong khi trọng số của cạnh thường đại diện cho khoảng cách, chi phí hoặc thời gian di chuyển giữa các điểm. Ví dụ, trong một đồ thị biểu diễn các điểm dân cư, mỗi đỉnh có thể gán với trọng số biểu thị dân số tại khu vực đó, còn mỗi cạnh có trọng số thể hiện khoảng cách giữa hai điểm dân cư. #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1 (5)$, anchor: "left", padding: 0.2) circle((-3, 1.5), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2 (2)$, anchor: "right", padding: 0.2) circle((3, 1.5), radius: 0.05, fill: black, name: "v3") content("v3.right", $v_3 (3)$, anchor: "right", padding: 0.2) circle((2, 5), radius: 0.05, fill: black, name: "v4") content("v4.right", $v_4 (1)$, anchor: "right", padding: 0.2) circle((-2, 5), radius: 0.05, fill: black, name: "v5") content("v5.right", $v_5 (7)$, anchor: "right", padding: 0.2) circle((0, 5), radius: 0.05, fill: black, name: "v6") content("v6.right", $v_6 (2)$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") content("v1v2.top", $3$, anchor: "top", padding: 0.5) line("v1", "v3", name: "v1v3") content("v1v3.top", $3$, anchor: "top", padding: 0.5) line("v1", "v5", name: "v1v5") content("v1v5.top", $2$, anchor: "top", padding: 0.7) line("v1", "v4", name: "v1v4") content("v1v4.top", $2$, anchor: "top", padding: 0.5) line("v1", "v6", name: "v1v6") content("v1v6.right", $1$, anchor: "right", padding: 0.1) } )] #align(center)[#text(orange)[*Hình 1.3*] Đồ thị có trọng số] Đồ thị không có trọng số(Unweighted Graph): Các cạnh và các đỉnh không có trọng số. Hình 1.1 và 1.2 là hai đồ không có trọng số. Đồ thị liên thông(Connected Graph): Từ một đỉnh bất kỳ, ta có thể đi đến tất cả các đỉnh khác thông qua các cạnh. (Ví dụ minh họa) #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.top", $v_1$, anchor: "top", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((3, 3), radius: 0.05, fill: black, name: "v3") content("v3.left", $v_3$, anchor: "left", padding: 0.2) circle((-3, 0), radius: 0.05, fill: black, name: "v4") content("v4.right", $v_4$, anchor: "right", padding: 0.2) circle((3, 0), radius: 0.05, fill: black, name: "v5") content("v5.left", $v_5$, anchor: "left", padding: 0.2) // circle((0, 5), radius: 0.05, fill: black, name: "v6") // content("v6.right", $v_6 (2)$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") //content("v1v2.top", $3$, anchor: "top", padding: 0.5) line("v1", "v3", name: "v1v3") // content("v1v3.top", $3$, anchor: "top", padding: 0.5) line("v2", "v4", name: "v1v4") // content("v1v5.top", $2$, anchor: "top", padding: 0.7) line("v1", "v4", name: "v1v4") // content("v1v4.top", $2$, anchor: "top", padding: 0.5) line("v1", "v5", name: "v1v5") // content("v1v6.right", $1$, anchor: "right", padding: 0.1) line("v3", "v5", name: "v3v5") line("v4", "v5", name: "v4v5") } )] #align(center)[#text(orange)[*Hình 1.4*] Đồ thị liên thông] 4. Đồ thị không liên thông(Disconnected Graph): Tồn tại ít nhất một đỉnh, mà từ đỉnh đó ta không thể đi đến một số đỉnh khác. Hình bên dưới là đồ thị không liên thông vì tồn tại đỉnh $v_4$ mà từ đỉnh này ta không thể đi đến các đỉnh còn lại của đồ thị. #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.top", $v_1$, anchor: "top", padding: 0.2) // circle((-3, 3), radius: 0.05, fill: black, name: "v2") // content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((3, 3), radius: 0.05, fill: black, name: "v3") content("v3.left", $v_3$, anchor: "left", padding: 0.2) circle((-3, 0), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((3, 0), radius: 0.05, fill: black, name: "v4") content("v4.left", $v_4$, anchor: "left", padding: 0.2) // circle((0, 5), radius: 0.05, fill: black, name: "v6") // content("v6.right", $v_6 (2)$, anchor: "right", padding: 0.2) //line("v1", "v2", name: "v1v2") //content("v1v2.top", $3$, anchor: "top", padding: 0.5) //line("v1", "v3", name: "v1v3") // content("v1v3.top", $3$, anchor: "top", padding: 0.5) // line("v2", "v4", name: "v1v4") // content("v1v5.top", $2$, anchor: "top", padding: 0.7) line("v1", "v2", name: "v1v2") // content("v1v4.top", $2$, anchor: "top", padding: 0.5) line("v1", "v3", name: "v1v3") // content("v1v6.right", $1$, anchor: "right", padding: 0.1) //line("v3", "v5", name: "v3v5") line("v2", "v3", name: "v2v3") } )] #align(center)[#text(orange)[*Hình 1.4*] Đồ thị không liên thông] // ==== #text(orange)[1.1.2 Một số khái niệm liên quan] === Một số khái niệm liên quan (a) Nếu $u$ là một điểm đầu mút của cạnh $e$ thì ta nói $u$ và $e$ _liên thuộc(incident)_ với nhau. #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.left", $u$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") content("v1v2.top", $e$, anchor: "top", padding: 0.1) } )] #align(center)[#text(orange)[*Hình 1.5*] $u$ và $e$ liên thuộc nhau] (b) Hai đỉnh liên thuộc với cùng một cạnh được gọi là hai đỉnh _liền kề(adjacent)_. Trong Hình 1.5, $u$ và $v$ cùng liên thuộc cạnh $e$ nên $u$ và $v$ là hai đỉnh liền kề. (c) Hai cạnh liên thuộc với cùng một đỉnh được gọi là hai cạnh _liền kề_. Hình 1.6, rõ ràng ta có thể thấy $e_1$ và $e_2$ cùng liên thuộc đỉnh $u$ nên $e_1, e_2$ là hai cạnh liền kề. #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.left", $u$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v$, anchor: "right", padding: 0.2) circle((0, 0), radius: 0.05, fill: black, name: "v3") content("v3.right", $z$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") content("v1v2.top", $e_1$, anchor: "top", padding: 0.1) line("v1", "v3", name: "v1v3") content("v1v3.right", $e_2$, anchor: "right", padding: 0.1) } )] #align(center)[#text(orange)[*Hình 1.6*] $e_1$ và $e_2$ liền kề nhau] (d) Một cạnh có hai điểm đầu mút trùng nhau được gọi là một _vòng(loop)_. (Vẽ hình minh hoa) (e) Hai hay nhiều cạnh mà có hai đầu mút giống nhau được gọi là _các cạnh song song(parallel edges)_ hay còn được gọi là _các cạnh bội(multiple edges)_. // (e) Hai hay nhiều cạnh mà có hai đầu mút giống nhau được gọi là _các cạnh song song(parallel edges)_ hay còn được gọi là _các cạnh bội(multiple edges)_. #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "u") content("u.left", $u$, anchor: "left", padding: 0.2) circle((-3, 3), radius: 0.05, fill: black, name: "v") content("v.right", $v$, anchor: "right", padding: 0.2) circle((0, 0), radius: 0.05, fill: black, name: "z") content("z.right", $z$, anchor: "right", padding: 0.2) line("u", "v", name: "v1v2") content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.1) bezier("u","v", (-1.5,2), name: "be1") content("be1.top", $e_4$, anchor: "top", padding: 0.2) line("u", "z", name: "v1v3") content("v1v3.right", $e_2$, anchor: "right", padding: 0.1) line("v", "z", name: "v2v3") content("v2v3.left", $e_3$, anchor: "left", padding: 1) bezier("z","v", (-4,-3), name: "be2") content("be2.right", $e_5$, anchor: "right", padding: 2.7) } )] #align(center)[#text(orange)[*Hình 1.8*] Minh họa các cạnh bội] (f) Đồ thị hữu hạn (_finite graph_) là đồ thị có cả tập hợp cạnh và tập hợp đỉnh đều hữu hạn. Các hình được đề cập bên trên đều là đồ thị hữu hạn. (g) Đơn đồ thị (_simple graph_) là một đồ thị không có vòng và không có cạnh song song. Hình 1.3 là một ví dụ của đơn đồ thị. (h) Đồ thị tầm thường (_trivial graph_) là đồ thị chỉ có một đỉnh và không có cạnh. (i) Đồ thị rỗng (_empty graph_) là đồ thị không có cạnh. // ==== #text(orange)[1.1.3 Bậc và đường đi] === Đồ thị con Đồ thị con (_subgraph_) đề cập đến một đồ thị được tạo thành từ một phần của đồ thị lớn hơn. Cụ thể đồ thị $H$ là một đồ thị con của $G$ (ký hiệu H $subset.eq$ G) nếu $ V(H) subset.eq V(G), E(H) subset.eq E(G)$ và $psi_H$ là giới hạn của $psi_G$ trên $E(H)$. Có nhiều loại đồ thị con như: (a) _Đồ thị con thực sự (proper subgraph)_: $H subset.eq G$ nhưng $H eq.not G$. Khi đó, ta ký hiệu $H subset G$. (b) _Đồ thị con bao trùm (spanning subgraph)_: $V(H)= V(G)$. (c) _Đồ thị con cảm sinh (induced subgraph)_: là một loại đồ thị con đặc biệt được tạo ra từ một tập hợp con của các đỉnh trong đồ thị gốc, cùng với tất cả các cạnh mà các đỉnh này nối với nhau trong đồ thị gốc. Đồ thị con của $G$ cảm sinh bởi $V'$ được ký hiệu $G[V']$. Để hiểu rõ hơn về định nghĩa đồ thị con cảm sinh, ta xét ví dụ sau: Cho đồ thị $G$ như hình bên dưới, $V'= {v_1, v_2, v_3}$, khi đó đồ thị con của $G$ cảm sinh bởi $V'$ được xác định như sau: #align(left)[#canvas(length: 7%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1$, anchor: "left", padding: 0.2) content("v1.bottom", $(G)$, anchor: "top", padding: 2) circle((-3, 1.5), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((3, 1.5), radius: 0.05, fill: black, name: "v3") content("v3.right", $v_3$, anchor: "right", padding: 0.2) circle((2, 5), radius: 0.05, fill: black, name: "v4") content("v4.right", $v_4$, anchor: "right", padding: 0.2) circle((-2, 5), radius: 0.05, fill: black, name: "v5") content("v5.right", $v_5 $, anchor: "right", padding: 0.2) circle((0, 5), radius: 0.05, fill: black, name: "v6") content("v6.right", $v_6 $, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") // content("v1v2.top", $3$, anchor: "top", padding: 0.5) line("v1", "v3", name: "v1v3") // content("v1v3.top", $3$, anchor: "top", padding: 0.5) line("v1", "v5", name: "v1v5") // content("v1v5.top", $2$, anchor: "top", padding: 0.7) line("v1", "v4", name: "v1v4") // content("v1v4.top", $2$, anchor: "top", padding: 0.5) line("v1", "v6", name: "v1v6") // content("v1v6.right", $1$, anchor: "right", padding: 0.1) } )] #align(right)[#canvas(length: 7%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1$, anchor: "left", padding: 0.2) content("v1.bottom", $(G[V'])$, anchor: "top", padding: 2) circle((-3, 1.5), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((3, 1.5), radius: 0.05, fill: black, name: "v3") content("v3.right", $v_3$, anchor: "right", padding: 0.2) // circle((2, 5), radius: 0.05, fill: black, name: "v4") // content("v4.right", $v_4 (1)$, anchor: "right", padding: 0.2) // circle((-2, 5), radius: 0.05, fill: black, name: "v5") // content("v5.right", $v_5 (7)$, anchor: "right", padding: 0.2) // circle((0, 5), radius: 0.05, fill: black, name: "v6") // content("v6.right", $v_6 (2)$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") // content("v1v2.top", $3$, anchor: "top", padding: 0.5) line("v1", "v3", name: "v1v3") // content("v1v3.top", $3$, anchor: "top", padding: 0.5) // line("v1", "v5", name: "v1v5") // content("v1v5.top", $2$, anchor: "top", padding: 0.7) // line("v1", "v4", name: "v1v4") // content("v1v4.top", $2$, anchor: "top", padding: 0.5) // line("v1", "v6", name: "v1v6") // content("v1v6.right", $1$, anchor: "right", padding: 0.1) } )] #align(center)[#text(orange)[*Hình 1.10*] Minh họa đồ thị cảm sinh] === Bậc của đỉnh Bậc (_Degree_) của đỉnh $v$ trong $G$ là số cạnh của $G$ liên thuộc với $v$, mỗi vòng được tính là hai cạnh. Ký hiệu: $d(v)$. Bậc của đỉnh mang ý nghĩa quan trọng trong nhiều ứng dụng thực tế. Chẳng hạn, trong mạng xã hội, bậc của một đỉnh biểu thị số lượng kết nối của một người dùng, chẳng hạn như số lượng bạn bè hoặc người theo dõi. Những đỉnh có bậc cao thường đại diện cho những cá nhân có sức ảnh hưởng lớn, do họ có nhiều kết nối và tương tác với các thành viên khác trong mạng lưới. Điều này giúp phản ánh mức độ quan trọng hoặc tầm ảnh hưởng của người dùng trong cộng đồng, từ đó hỗ trợ các nền tảng đánh giá mức độ tương tác hoặc xác định người dùng nổi bật. Với đồ thị $G$ như Hình 1.11, ta có $d(v_1)=4, d(v_2)=4, d(v_3)=4, d(v_4)=2, d(v_5)=2$ và $d(v_6)=0$. #align(center)[ #canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.left", $v_1$, anchor: "bottom", padding: 0.3) circle((-3, 3), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((0, 0), radius: 0.05, fill: black, name: "v3") content("v3.bottom", $v_3$, anchor: "top", padding: 0.1) circle((-3, 0), radius: 0.05, fill: black, name: "v4") content("v4.right", $v_4$, anchor: "right", padding: 0.2) circle((3, 1.5), radius: 0.05, fill: black, name: "v5") content("v5.right", $v_5$, anchor: "left", padding: 0.2) circle((6, 1.5), radius: 0.05, fill: black, name: "v6") content("v6.right", $v_6$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.1) bezier("v1","v2", (-1.5,2), name: "be1") content("be1.top", $e_4$, anchor: "top", padding: 0.2) line("v1", "v3", name: "v1v3") content("v1v3.right", $e_2$, anchor: "right", padding: 0.1) line("v2", "v3", name: "v2v3") content("v2v3.left", $e_3$, anchor: "left", padding: 1) line("v2", "v4", name: "v2v4") content("v2v4.left", $e_5$, anchor: "left", padding: 0.1) line("v4", "v3", name: "v4v3") content("v4v3.bottom", $e_6$, anchor: "bottom", padding: 0.1) line("v1", "v5", name: "v1v5") content("v1v5.bottom", $e_7$, anchor: "bottom", padding: 0.5) line("v3", "v5", name: "v3v5") content("v3v5.bottom", $e_8$, anchor: "bottom", padding: 0.4) } )] #align(center)[#text(orange)[*Hình 1.11*] Minh họa bậc của đỉnh] // #figure( // caption: [Một hình XXX] // )[ // #canvas(length: 10%, { // import cetz.draw: * // let y = 2 // let x = 4 // let y-space = 1 // let h=1.4 // circle((0*h,3), radius: 0.05,fill:black, name: "v1") // content("v1.left", $v_1$, anchor: "bottom", padding: 0.3) // circle((-3, 3), radius: 0.05, fill: black, name: "v2") // content("v2.right", $v_2$, anchor: "right", padding: 0.2) // circle((0, 0), radius: 0.05, fill: black, name: "v3") // content("v3.bottom", $v_3$, anchor: "top", padding: 0.1) // circle((-3, 0), radius: 0.05, fill: black, name: "v4") // content("v4.right", $v_4$, anchor: "right", padding: 0.2) // circle((3, 1.5), radius: 0.05, fill: black, name: "v5") // content("v5.right", $v_5$, anchor: "left", padding: 0.2) // circle((6, 1.5), radius: 0.05, fill: black, name: "v6") // content("v6.right", $v_6$, anchor: "right", padding: 0.2) // line("v1", "v2", name: "v1v2") // content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.1) // bezier("v1","v2", (-1.5,2), name: "be1") // content("be1.top", $e_4$, anchor: "top", padding: 0.2) // line("v1", "v3", name: "v1v3") // content("v1v3.right", $e_2$, anchor: "right", padding: 0.1) // line("v2", "v3", name: "v2v3") // content("v2v3.left", $e_3$, anchor: "left", padding: 1) // line("v2", "v4", name: "v2v4") // content("v2v4.left", $e_5$, anchor: "left", padding: 0.1) // line("v4", "v3", name: "v4v3") // content("v4v3.bottom", $e_6$, anchor: "bottom", padding: 0.1) // line("v1", "v5", name: "v1v5") // content("v1v5.bottom", $e_7$, anchor: "bottom", padding: 0.5) // line("v3", "v5", name: "v3v5") // content("v3v5.bottom", $e_8$, anchor: "bottom", padding: 0.4) // } // ) // ] #text(orange)[*Định lý 1.1*] _Tổng bậc của tất cả các đỉnh trong một đồ thị bằng hai lần số cạnh của đồ thị đó_ // #theorem("Euclid")[ // Tổng bậc của tất cả các đỉnh trong một đồ thị bằng hai lần số cạnh của đồ thị đó // ] === Đường đi, chu trình và tính liên thông Đường đi (_walk_) trong $G$ là một dãy khác rỗng hữu hạn gồm các đỉnh và các cạnh xen kẽ nhau. Nếu các cạnh của đường đi đôi một khác nhau thì đường đi đó được gọi là _đường đi đơn (trail)_. Trong khi đó, nếu các đỉnh của đường đi đôi một khác nhau thì được gọi là đường đi sơ cấp (_path_). Chu trình (_closed walk_) là một đường đi có chiều dài dương và có đỉnh đầu và đỉnh cuối trùng nhau. _Chu trình đơn (closed trail)_ là một chu trình có các cạnh đôi một khác nhau. _Chu trình sơ cấp (cycle)_ là một chu trình đơn có các đỉnh đôi một khác nhau ngoại trừ đỉnh đầu và đỉnh cuối. Đối với đồ thị có trọng số, _độ dài đường đi (length)_ bằng tổng trọng số cạnh của đường đi đó. (Ví dụ minh họa) Tính liên thông trên đồ thị là một khái niệm liên quan đến khả năng kết nối giữa các đỉnh trong một đồ thị. Một đồ thị được gọi là _liên thông_ nếu tồn tại một đường đi giữa mọi cặp đỉnh. Cụ thể (a) _Đồ thị vô hướng liên thông_: Là đồ thị trong đó mỗi cặp đỉnh bất kỳ, ta có thể tìm được một đường đi giữa chúng. Điều này có nghĩa là không có đỉnh nào bị tách rời khỏi phần còn lại của đồ thị. (b) _Đồ thị có hướng liên thông mạnh_: Là đồ thị có hướng, trong đó tồn tại đường đi từ bất kỳ đỉnh nào đến bất kỳ đỉnh khác. Điều này yêu cầu cả hai chiều đường đi phải tồn tại giữa hai đỉnh. (c) _Đồ thị có hướng liên thông yếu_: Nếu ta bỏ qua hướng của các cạnh (xem như cạnh vô hướng) và đồ thị trở thành liên thông. Tính liên thông là một yếu tố quan trọng để phân tích cấu trúc của đồ thị và áp dụng trong nhiều bài toán như mạng lưới giao thông, thiết kế mạng máy tính, hoặc giải quyết các bài toán về tối ưu hóa. // ==== #text(orange)[1.1.4 Đồ thị cây] Trong phần tiếp theo, chúng ta sẽ đi sâu vào nghiên cứu đồ thị cây cùng với những tính chất đặc biệt của nó. Đồ thị cây là một trường hợp đặc biệt của đồ thị, mang trong mình cấu trúc đơn giản nhưng lại vô cùng mạnh mẽ và có tính ứng dụng rộng rãi trong nhiều lĩnh vực. === Đồ thị cây Đồ thị cây (_tree graph_) là đồ thị liên thông và không chứa chu trình sơ cấp. #align(center)[ #canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,2), radius: 0.05,fill:black, name: "v1") content("v1.left", $v_1$, anchor: "bottom", padding: 0.3) circle((-2, 2), radius: 0.05, fill: black, name: "v2") content("v2.right", $v_2$, anchor: "right", padding: 0.2) circle((0, 0), radius: 0.05, fill: black, name: "v3") content("v3.bottom", $v_3$, anchor: "top", padding: 0.1) circle((-2, 0), radius: 0.05, fill: black, name: "v4") content("v4.right", $v_4$, anchor: "right", padding: 0.2) circle((2, 1), radius: 0.05, fill: black, name: "v5") content("v5.right", $v_5$, anchor: "left", padding: 0.2) circle((4, 1), radius: 0.05, fill: black, name: "v6") content("v6.right", $v_6$, anchor: "right", padding: 0.2) circle((6, 2), radius: 0.05, fill: black, name: "v7") content("v7.right", $v_7$, anchor: "right", padding: 0.2) circle((6, 0), radius: 0.05, fill: black, name: "v8") content("v8.right", $v_8$, anchor: "right", padding: 0.2) line("v1", "v2", name: "v1v2") // content("v1v2.bottom", $e_1$, anchor: "bottom", padding: 0.1) // bezier("v1","v2", (-1.5,2), name: "be1") // content("be1.top", $e_4$, anchor: "top", padding: 0.2) // line("v1", "v3", name: "v1v3") // content("v1v3.right", $e_2$, anchor: "right", padding: 0.1) // line("v2", "v3", name: "v2v3") // content("v2v3.left", $e_3$, anchor: "left", padding: 1) // line("v2", "v4", name: "v2v4") // content("v2v4.left", $e_5$, anchor: "left", padding: 0.1) line("v4", "v3", name: "v4v3") content("v4v3.bottom", $e_6$, anchor: "bottom", padding: 0.1) line("v1", "v5", name: "v1v5") content("v1v5.bottom", $e_7$, anchor: "bottom", padding: 0.5) line("v3", "v5", name: "v3v5") content("v3v5.bottom", $e_8$, anchor: "bottom", padding: 0.4) line("v6", "v5", name: "v6v5") // content("v6v5.bottom", $e_8$, anchor: "bottom", padding: 0.4) line("v6", "v7", name: "v6v7") line("v6", "v8", name: "v6v8") } )] #align(center)[#text(orange)[*Hình 1.12*] Minh họa đồ thị cây] Đồ thị cây có những đặc điểm nổi bật sau: (a) Nếu $T$ là đồ thị cây có $n$ đỉnh thì luôn có đúng $n-1$ cạnh. (b) Trong một cây, hai đỉnh bất kỳ được nối với nhau bằng một đường đi sơ cấp duy nhất. (c) Mỗi cây với mỗi đỉnh $n >= 2$ thì có ít nhất hai đỉnh bậc một. Những đỉnh bậc một này thường được gọi là _lá_, và chúng đóng vai trò quan trọng trong việc xác định cấu trúc và tính chất của cây. // #text(orange)[*Định lý 1.2*] _Trong một cây, hai đỉnh bất kỳ được nối với nhau bằng một đường đi sơ cấp duy nhất._ // #text(orange)[*Chứng minh*] // Ta sẽ chứng minh bằng phản chứng. Cho _G_ là một cây và giả sử rằng trong _G_ có hai đường đi sơ cấp khác nhau từ _u_ đến _v_ là $P_1$ và $P_2$. Vì $P_1 != P_2$ nên tồn tại một cạnh $e=x y $ của $P_1$ không phải là cạnh của $P_2$. Rõ ràng đồ thị $(P_1 union P_2) - e$ liên thông, xem hình(....). Do đó, nó chứa một đường đi sơ cấp $P$ đi từ $x$ đến $y$. Khi đó $ P + e$ là một chu trình sơ cấp trong $G$, mâu thuẫn với giả thiết $G$ là một cây. $square.stroked.medium$ // Lá (leaf) là các đỉnh (node) trong cây có bậc (degree) bằng 1. Nói cách khác, một đỉnh là lá nếu nó chỉ kết nối với đúng một đỉnh khác trong cây. // (Ví dụ minh họa) //ĐN kỹ lại a ( nên sài N^1 như trong bài báo) Với hai điểm $x$ và $y$ gọi $P(x,y)$ là đường đi nối $x$ và $y$. #lemma[ Đặt $a,x,y$ và $z$ là bốn điểm phân biệt nằm trên cây $T$ sao cho $z in P(x,y)$ thì $z in P(a,x)$ hoặc $z in P(a,y)$ ] #text(orange)[*Chứng minh*] Theo giả thiết, ta có $z in P(x,y)$. Ta giả sử $ z in.not P(a,x)$ và $z in.not P(a,y)$ (như hình vẽ) (vẽ hình minh họa). Bởi vì đường đi kết nối $x$ và $y$ đi qua $a$ nhưng không chứa $z$, trong khi đó đường đi $P(x,y)$ chứa $z$. Vì vậy, tồn tại hai con đường nối $x$ và $y$ và điều này mâu thuẫn với tính chất của đồ thị cây. $ quad square.stroked.medium$ Tiếp theo đây, ta sẽ giới thiệu một định lý quan trọng trên đồ thị cây, được phát biểu bởi @dearing1976convex. Định lý này thường được sử dụng để giải quyết các bài toán tối ưu trong lý thuyết đồ thị. Đặt $f_1(x,a) eq.triple d(x,a)$ là hàm khoảng cách từ một điểm $x$ bất kỳ đến một điểm cố định $a$ trên đồ thị cây. //ĐN a // #text(orange)[*Định lý 1.2*] _Tổng bậc của tất cả các đỉnh trong một đồ thị bằng hai lần số cạnh của đồ thị đó_ // Hàm khoảng cách trên đồ thị cây là hàm lồi //Coi kĩ lại chứng minh. #theorem[ $f_1(x,a)$ là hàm lồi khi và chỉ khi $T$ là đồ thị cây ] . #proof[Ta sẽ tiến hành chứng minh hai chiều. Giả sử, $T$ là đồ thị cây. Chọn $y,z$ bất kỳ nằm trên cây $T$, $0<lambda<1$ và $x in P(y,z)$. Để chứng minh $f_1(x,a)$ là hàm lồi, ta cần chứng minh $d(x,a) <= lambda d(y,a) + (1-lambda) d(z,a)$ hoặc ta có thể chứng minh bất đẳng thức sau: $ d(x,a) d(y,z) <= d(x,z) d(y,a) + d(x,y) d(z,a) $ <eq:distance-1> // #eqref(<eq:distance-1>) // (Cách trích dẫn @eq:distance-a ) Vì $x in P(y,z)$ nên theo *Bổ đề 1.2.2*, ta có $x in P(y,a)$ hoặc $x in P(z,a)$. Mặt khác, vì $x in P(y,z)$ nên $ d(x,a)d(y,z)=d(x,a)[d(y,x)+d(x,z)]=d(x,a)d(y,x)+d(x,a)d(x,z) $. <eq:distance-2> Giả sử, $x in P(z,a)$ ta có: $ d(x,a)=d(z,a)-d(z,x) $ <eq:distance-3> Hơn nữa, $ d(x,a)=d(y,x)-d(a,y) <= d(a,y)+d(y,x) $ <eq:distance-4> Thay #eqref(<eq:distance-3>) và #eqref(<eq:distance-4>) vào #eqref(<eq:distance-2>) ta được #eqref(<eq:distance-1>). Trường hợp $x in P(y,a)$ cũng được chứng minh tương tự. Tiếp theo, đặt $f_1(x,a)$ là hàm lồi trên tập các điểm thuộc đồ thị $T$ và giả sử rằng $T$ không phải là cây. Nói cách khác, tồn tại một chu trình $C$ của $T$ có độ dài ngắn nhất, giả sử là $l$, trong tất cả các chu trình của $T$. Bởi vì $C$ là một chu trình ngắn nhất trong $T$, nên ta có thể chọn $x,y,z$ và $a$ trong $C$ sao cho $d(a,x)=d(y,z)=l/2$, $d(a,y)=d(x,y)=d(z,a)=d(x,z)=l/4$ và $d(x,z)=1/2 d(y,z)$. Khi đó $f_1(x,a)=(l/2) > (1/2)f_1(y,a) + (1/2)f_1(z,a)=l/4 $, điều này mâu thuẫn với giả thiết $f_1(x,a)$ là hàm lồi. Vậy $T$ là đồ thị cây.] // (Có thể thêm bổ đề 3) // -Nghiệm cục bộ cũng là nghiệm toàn cục => trên cây giải hiệu quả.... // (Có thể chứng minh thêm nghiệm cục bộ là nghiệm toàn cục) === Độ phức tạp tính toán
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/documents/xlospec/titlepage.typ
typst
*XR/station Project* \ *XLO File Format Specification* \ _Revision 1.0, May 29, 2024_ _Revision 2.0, June 26, 2024_
https://github.com/antonWetzel/Masterarbeit
https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/einleitung.typ
typst
#import "setup.typ": * = Einleitung <einleitung> == Motivation Größere Gebiete wie Teile von Wäldern können mit 3D-Scanners abgetastet werden. Dabei wird entweder vom Boden aus ein Waldgebiet abgetastet oder der Scanner ist an einem Flugzeug oder einer Drohne befestigt, womit der gewünschte Bereich abgeflogen wird. Dabei entsteht eine Punktwolke, bei der für jeden Punkt mindestens die dreidimensionale Position bekannt ist. Aus den Punkten sind relevante Informationen aber nicht direkt ersichtlich. Eine manuelle Weiterverarbeitung ist durch die großen Datenmengen unrealistisch, weshalb automatisierte Methoden benötigt werden. Vor der Analyse müssen die Punktwolken zuerst in die einzelnen Bäume unterteilt werden. Danach können für jeden Baum die gewünschten Eigenschaften berechnet werden. Dazu gehört die Höhe vom Stamm, der Krone und dem gesamten Baum und der Durchmesser vom Stamm bei Brusthöhe und der Baumkrone. Eine Visualisierung der Punktwolke und der berechneten Daten ermöglicht einen Überblick über das gescannte Waldgebiet. Ein Beispiel für so eine Visualisierung ist in @einleitung_beispiel gegeben. Es sind die Punkte vom Datensatz zu sehen, welche basierend auf der relativen Höhe im Baum eingefärbt sind. Dadurch ist der Boden in Gelb und zu den Baumspitzen hin ändert sich die Farbe der Punkte zu Rot. #figure(caption: [Waldgebiet mit den Punkten basierend auf der relativen Höhe im Baum eingefärbt.], image("../images/auto-crop/br06-uls.png", width: 90%)) <einleitung_beispiel> == Themenbeschreibung Das Ziel dieser Arbeit ist eine Erforschung des Ablaufs von einem Scan von einem Waldgebiet bis zur Analyse der Daten mit zugehöriger interaktiven Visualisierung der Ergebnisse. Als Eingabe wird der Datensatz vom Waldgebiet benötigt. Dabei wird davon ausgegangen, dass ein Datensatz eine ungeordnete Menge von Punkten enthält, für die nur die Position im dreidimensionalen Raum bekannt ist. Je nach Scanner können die Punkte im Datensatz entsprechend der räumlichen Verteilung geordnet sein oder weitere Eigenschaften wie die Farbe der abgetasteten Oberfläche enthalten. Weil nur die Position bei der Analyse betrachtet wird, kann die Auswertung auch für Datensätze durchgeführt werden, welche keine weiteren Informationen enthalten. Für die Analyse der Daten muss die Menge der Punkte zuerst in einzelne Bäume unterteilt werden. Dafür wird für jeden Baum ein Segment bestimmt, welches alle zugehörigen Punkte enthält. Danach können die einzelnen Bäume ausgewertet werden. Durch die Beschränkung auf Waldgebiete kann die Segmentierung und die folgende Auswertung auf Bäume spezialisiert werden. Bei der Auswertung werden charakteristische Eigenschaften für die Bäume, aber auch für die einzelnen Punkte im Baum bestimmt. Für Bäume werden Eigenschaften bestimmt, welche den ganzen Baum beschreiben. Für Punkte werden die Eigenschaften für die lokale Umgebung berechnet. Die Visualisierung präsentiert die berechneten Ergebnisse. Für die Bäume und die Punkte werden die Daten mit den berechneten Eigenschaften dargestellt und können interaktiv inspiziert werden. Dabei werden die Punkte vom gesamten Datensatz, einzelne Segmente mit den Punkten oder eine triangulierte Oberfläche angezeigt. == Struktur der Arbeit #let section(index, name) = { v(0.2em) strong([Abschnitt #numbering("1.1", index): #name]) } #section(1, [Einleitung]) In der Einleitung wird die Motivation für die Arbeit erklärt, das Thema definiert und die Struktur der Arbeit vorgestellt. #section(2, [Stand der Technik]) Der Stand der Technik beschäftigt sich mit wissenschaftlichen und technischen Arbeiten zugehörigen zum Thema. Dazu gehört die Aufnahme und Verarbeitung von Punktdaten und die Analyse von Bäumen mit den Daten. #section(3, [Segmentierung von Waldgebieten]) Die Segmentierung erklärt den verwendeten Algorithmus für die Unterteilung von einer Punktwolke von einem Waldgebiet in mehrere Punktwolken für jeweils einen Baum. Von den Baumspitzen aus wird die Position der Bäume berechnet und die Punkte werden dem nächsten Baum zugeordnet. #section(4, [Visualisierung]) Im Abschnitt Visualisierung wird die Methodik erklärt, um die Punktwolken oder einzelne Segmente mit allen gegebenen und berechneten Daten in Echtzeit zu rendern. Dafür wird das Anzeigen von einzelnen Punkten, Detailstufen und die Visualisierung von den Tiefeninformationen erklärt. #section(5, [Triangulierung]) Bei der Triangulierung wird für die Punktwolke von einem Baum ein geeignetes Dreiecksnetz für die Oberfläche vom Baum gesucht. Mit dem Dreiecksnetz und den Punkten kann für den Baum ein dreidimensionales Mesh erstellt werden. #section(6, [Analyse von Bäumen]) Bei der Analyse werden mit der Punktwolke von einem Baum die charakteristischen Eigenschaften für den Baum und einzelne Punkte berechnet. Für den Baum wird der Durchmesser vom Stamm und der Krone abgeschätzt und die Höhe vom Stamm, der Krone und dem gesamten Baum bestimmt. Für die einzelnen Punkte wird die relative Höhe im Baum, die lokale Krümmung und die benötigten Eigenschaften für die Visualisierung berechnet. #section(7, [Implementierung]) Das Softwareprojekt mit der technischen Umsetzung der Algorithmen wird in der Implementierung vorgestellt. Dafür wird die Bedienung und die Struktur vom Programm erklärt. Für den Import wird der Ablauf und das verwendete Dateiformat vorgestellt und für die Visualisierung werden die verwendeten Algorithmen für das Anzeigen von Punkten, Segmenten und Detailstufen ausgeführt. #section(8, [Auswertung]) Bei der Auswertung werden die in der Arbeit vorgestellten Methoden analysiert. Dafür werden die benutzten Datensätze vorgestellt, mit denen der Ablauf bis zur Visualisierung getestet wurde. Für die charakteristischen Eigenschaften der Bäume werden die berechneten Werte mit den gemessenen Werten im Datensatz verglichen. #section(9, [Fazit]) Im Fazit werden die Ergebnisse der Auswertung eingeordnet und mögliche Verbesserungen angesprochen und weitere Verarbeitungsschritte der berechneten Daten vorgestellt. #section(10, [Appendix]) Im Appendix werden benutzte Begriffe und Datenstrukturen erklärt und die verwendeten Systemeigenschaften und Messdaten für die Auswertung gelistet.
https://github.com/Rhinemann/mage-hack
https://raw.githubusercontent.com/Rhinemann/mage-hack/main/src/chapters/Assets.typ
typst
#import "../templates/interior_template.typ": * #show: chapter.with(chapter_name: "Assets") = Assets #show: columns.with(2, gutter: 1em) A conveniently prepared spell, a friend in the right office or a perfectly practiced gunplay trick, mages are a crafty bunch, able to find advantages in the moment or prepare for virtually any situation using their numerous unusual skills and magickal powers. These beneficial circumstances are represented through assets. Assets are narratively significant traits that improve your chances of influencing a story to your benefit. Giving an object a die rating by creating an asset means that this object is a significant part of the story. Most objects in the game are color, setting, or flavor rather than an asset; if it's something that exists in the story, something the Storyteller or players are using as part of their description, then it should be a part of narrating the outcome of a test or contest, but it doesn't confer any more dice. #block(breakable: false)[ == Using assets During play, a player can add as many of their fictionally appropriate assets to a dice pool as they'd like. Since they spent a #spec_c.pp to create the asset, there's no need to spend another to use it. ] Assets belong to the character of the player that created them, and by default can't be included in anyone else's pool. An asset created to help another character belongs to that character and can't be used by the creator's character. Spend an additional #spec_c.pp to declare an asset to be open and usable by any character in the scene, including GMCs. Assets --- also called temporary assets when they need to be distinguished from signature assets --- last until the end of the scene, unless something in the story makes them no longer relevant, or they're stepped down or eliminated. The player may spend an additional #spec_c.pp to keep the asset around through to the end of the session. #block(breakable: false)[ == Creating Assets There are several ways for players to create assets during play: ] - A player can spend a #spec_c.pp and create a #spec_c.d6 asset with a name they come up with. - Some SFX allow for stunts—assets that start with a #spec_c.d8 die rating. - A player can create an asset greater than #spec_c.d6 and without spending a #spec_c.pp by making a test. - When the narrative situation calls for it, the Storyteller may declare that a #spec_c.d6 asset is created for free as part of a successful test that wasn't made explicitly to create an asset. #block(breakable: false)[ === Test-Created Assets To create an asset by attempting a test, a player declares what their character does to create the asset and assembles an appropriate dice pool. The Storyteller rolls to set the difficulty, usually with something basic like #spec_c.d6#spec_c.d6. ] The effect die of the test becomes the die rating of the asset. The Storyteller may set a cap on the size of assets created this way by setting the difficulty dice to that die rating. The asset created may not be larger than this die cap. #block(breakable: false)[ === Clues As Assets Anytime a PC wants to get a read on somebody, case a scene, spot something out of the ordinary, or generally just use their senses, they're creating an asset. ] The Storyteller usually calls for the roll, though it's just as valid for a player to ask for it. The difficulty for an asset test is set by rolling a straight #spec_c.d6#spec_c.d6 --- unless the Storyteller decides otherwise. A player's dice pool for the test is assembled from appropriate traits. With a successful test, the PC gains some crucial information. If the PC spends a #spec_c.pp after succeeding at the test, they can bank the asset until they need it, give it to another character, or keep it for longer. With a failed test, the PC doesn't gain any useful advantage. If there are complications, they generally represent the consequences of poking around places trying to find stuff out. #block(breakable: false)[ == Signature Assets Signature assets are assets that have become permanent traits for a character, playing an ongoing and essential part in their story. Usually, they cover anything that gives you an advantage and isn't covered by your other trait sets. ] Note that your signature assets do not include all of your character's gear or other advantages. When something is an asset, it just means that it's so important to your character's story that you gain an extra die when using it. Most signature assets break down into one of five categories: items, creatures, places, people, and rotes. Example signature assets for each category are listed below. *Things* are the most common form of signature asset, including items or equipment that you own, carry, or have access to. Examples include #smallcaps[Magic Carpet], #smallcaps[1971 Dodge Challenger], #smallcaps[Universal Translator], #smallcaps[My Family's Heirloom Sword], #smallcaps[Handheld Medical Scanner], #smallcaps[Chainsaw], #smallcaps[Laser Pistol], etc. *Creatures* include pets, mounts, animal companions, familiars, and the like. Examples include #smallcaps[Armored Warhorse], #smallcaps[Well-Trained Bloodhound], #smallcaps[My Cat Snowball], #smallcaps[Ornery Camel], #smallcaps[Baby Dragon], #smallcaps[Tamed Pterodactyl], #smallcaps[Pocket Monster], etc. *Places* represent advantages gained from being in or having knowledge of a certain location. Examples include #smallcaps[Seaside Hideout], #smallcaps[Private Library], #smallcaps[Special Forces Bar], #smallcaps[Pocket Dimension], #smallcaps[Hidden Glade], #smallcaps[PANIC ROOM], #smallcaps[MY Queen's Palace], #smallcaps[My Uncle's Army Surplus Store], #smallcaps[Satellite Hq], etc. *People* are minor GMCs who can be relied upon to help you, at least occasionally. Examples include #smallcaps[My Squire], #smallcaps[Robot Bodyguard], #smallcaps[Mob Informant], #smallcaps[Hairy Alien Co-Pilot], #smallcaps[Kid Sidekick], #smallcaps[Psychic Little Sister], #smallcaps[Wizard Mentor], #smallcaps[Fence Who Doesn't Ask Questions], etc. *Rotes* are magickal effects that were practiced to the point of expertise and come naturally. Examples include #smallcaps[Creo Fulmen], #smallcaps[Videte Per Materiam], #smallcaps[Telekinesis], #smallcaps[Intellego Magica], #smallcaps[Aurelius' Minor Combat Adjustments], etc. #block(breakable: false)[ === Using Signature Assets A signature asset belongs to a PC and is recorded on their character file --- it doesn't need to be created during play and it gives the player an extra die to include in their dice pools when they can justify their use. Unlike skills or attributes, signature assets are about things a PC has or people they know, not about qualities innate to them. These assets are a great way to further reveal a PC's personality as a means of representing heirlooms, signature rotes or unique weapons or special relationships. ] Signature assets can be temporarily knocked out, eliminated, rendered unusable, or damaged during play; but as they're a featured element of the PC's character file, the player can recover the signature asset between sessions or by spending a #spec_c.pp at the beginning of the next scene (with some narrative justification for getting it back/fixed). #block(breakable: false)[ === Rating Signature Assets Signature assets begin with a #spec_c.d6 die rating but can be stepped up during play. They aren't tied to a distinction, attribute, or skill, but may complement any one of those traits. The die rating of your signature asset represents how much the asset can help you, as well as your own bond with it. ] - #spec_c.d6 Something helpful and everyday, or that you've grown accustomed to. - #spec_c.d8 Something special and interesting, or that you have a strong connection to. - #spec_c.d10 Something rare and potent, or that you are defined by. - #spec_c.d12 Something truly unique and powerful, or that transcends even your innate abilities. #block(breakable: false)[ === Signature Assets And SFX Some assets may be as simple as a die rating, but on some players can unlock SFX. There are no default SFX for signature assets, so a conversation with a Storyteller about appropriate options should be had before an SFX is added. ] #block(breakable: false)[ === Sharing Signature Assets A signature asset is made up of two things: your connection to something, and the something you're connected to. The die rating belongs to your connection, not to the thing itself. You and another character might both possess a signature asset, but at different die ratings. ] Signature assets cannot be shared between PCs; if someone “borrows” a signature asset from a character (picking up the other character's heirloom sword, driving their custom sports car or referencing their grimoire), the borrower must spend a #spec_c.pp to create an asset as normal to get any benefit from the asset borrowed, and the asset is rated at #spec_c.d6 like any other #spec_c.pp created asset. #block(breakable: false)[ === Dropping Signature Assets At any point during the scene a player can choose to lose a signature asset narratively justifying it. In that case you gain XP equal to the price of the signature asset lost. ]
https://github.com/kmitsutani/jnsarticle-typ
https://raw.githubusercontent.com/kmitsutani/jnsarticle-typ/main/sample_propagator.typ
typst
MIT No Attribution
#import "jnsarticle.typ": main, appendix, thebibliography #import "@preview/physica:0.9.3": * #show: main.with( title: [伝搬関数と$T$-積], authors: [三ツ谷和也], abstract: [ 散乱過程では一般に複数の粒子が複雑に相互作用しながら伝播していくことが予想される. しかし近接相互作用のみを仮定するならば相互作用と相互作用の間で 自由な粒子の伝播を考えることができる. したがって自由粒子の伝播振幅について考察しておくことは散乱を考えるうえで基礎となるだろう. 本節では自由粒子の伝搬振幅について考察する. また時間に依存する複数の演算子の積を考えるときに便利になる$T$-積 という記法についても紹介する. ], ) #let evobw(t) = $e^(i hat(H)_0 #t)$ #let evofw(t) = $e^(-i hat(H)_0 #t)$ #let covmes(k) = $d tilde(bold(k))$ #let fprop = $Delta_"F"$ #let fpropf = $tilde{Delta}_"F"$ #let Ek = $E_(bold(k))$ #let cuhc = $C^((+))$ #let clhc = $C^((-))$ = 自由Klein-Gordon場の伝搬振幅 時刻 $x^0$ に空間座標 $bold(x)$ 自由Klein-Gordon場(以下KG場)が生成し, しかる後時刻 $y^0$ に空間座標 $bold(y)$ で消滅する(すなわち$y^0 > x^0$ を仮定する)という現象 の確率振幅を考えたい. そのために今まで用いてきた運動量固有状態の生成消滅演算子のフーリエ変換 $ hat(a)_(bold(x)) &= sum_(bold(p)) hat(a)_(bold(p)) e^(+i bold(p)bold(x)) hat(a)^dagger_(bold(x)) &= sum_(bold(p)) hat(a)^dagger_(bold(p)) e^(-i bold(p)bold(x)) $ を考える.ただしここで$bold(x)$および$bold(p)$は離散的な値をとるとした. これらは $ hat(x) a^dagger_(bold(x))ket(0) &= bold(x) ket(bold(x)) hat(a)_(bold(x^prime))hat(a)^dagger_(bold(x))ket(0) &= delta_(bold(x)^prime, bold(x)) ket(0) $ のように位置の固有状態に対する生成消滅演算子として機能する footnote( 位置の固有状態になることの計算は簡単だが一息に暗算するには少し長いかもしれないので 導出を一応以下に記しておく. $ hat(x) a^dagger_(bold(x))ket(0) = hat(x) sum_(bold(y), bold(p)) ketbra(bold(y))a^dagger_(bold(p))e^(-i bold(p)bold(x)) ket(0) = sum_(bold(y),bold(p)) y ket(y) braket(bold(y))(bold(p)) e^(-i bold(p)bold(x)) = sum_(bold(y),bold(p)) y ket(y) e^(+i bold(p)(y)) e^(-i bold(p)bold(x)) $ 最後の式で$bold(p)$に関する和をとれば$delta_(bold(x), bold(y))$ が出てくるのであとは自明である. ). これらの生成消滅演算子を用いれば上記の事象の確率振幅は $ c(x^0;bold(x) arrow.r y^0;bold(y)) & prop mel( evobw(y^0) hat(a)_(bold(y)) evofw((y^0 - x^0)) hat(a)^dagger_(bold(x)) evofw(x^0) , 0, 0) $ となる. 振幅を右から順に読んでいけば基準時刻$t=0$に真空を用意してそれを時刻$x^0$まで時間発展させ その時刻で固有値$bold(x)$の位置の固有状態を生成し, さらに時刻$y^0$まで状態を発展させたのちに固有値$bold(y)$の位置の固有状態を消滅させ, 時刻$y^0$まで時間発展させた真空$exp(-i hat(H)_0 y^0)ket(0)$に 共役なブラベクトル$bra(0)exp(+i hat(H)_0 y^0)$を作用させて振幅を計算するということをしている. subsection(ファインマンプロパゲーター) 上式において時刻$x^0$から$y^0$までの時間発展の部分を分離して書き位置の固有状態の生成消滅演算子を 運動量の生成消滅演算子の和で書き直すと $ c(x^0;bold(x) arrow.r y^0;bold(y)) ∝ mel( evobw(y^0) (sum_(bold(q)) hat(a)_(bold(q)) e^(+i bold(q)bold(y))) evofw(y^0) evobw(x^0) (sum_(bold(p)) hat(a)^dagger_(bold(p)) e^(-i bold(p)bold(x))) evofw(x^0) , 0, 0) $ 以下に再掲する式(I$.86$)および式(I$.87$) $ &(text(I.)86) e^(i hat(H)_0 (t-t_0))a_(bold(k))e^(-i hat(H)_0 (t-t_0)) = a(bold(k))e^(-i k _0 (t-t_0)) &(text(I.)87) e^(i hat(H)_0 (t-t_0))a^dagger_(bold(k))e^(-i hat(H)_0(t-t_0)) = a^dagger(bold(k))e^(+i k _0(t-t_0)) $ を意識して少し計算すると footnote( 式(I.86-87)より $ e^(+i hat(H)_0y^0)hat(a)_(bold(q))e^(-i hat(H)_0 y^0)e^(+i bold(q)bold(y)) =hat(a)e^(-i q y ) $ および $ e^(-i hat(H)_0x^0)hat(a)_(bold(p))^dagger e^(+i hat(H)_0x^0) e^(+i bold(p)bold(x)) =hat(a)^dagger e^(-i p x) $ となることを踏まえ, $ phi(x)=integral covmes(k) (hat(a)_(bold(k))e^(-i k x) + hat(a)^dagger_(bold(k))e^(+i k x)) $ であったことを思い出し最後に連続極限をとるときに 離散的な場合の交換関係$[a_(bold(q)), a^dagger_(bold(p))] = delta_(bold(q), bold(p))$ と連続的な場合の交換関係 $[a_(bold(q)), a^dagger_(bold(p))] = (2pi)^3 2E_(bold(p))delta(bold(q) - bold(p))$ の違いを吸収する規格化因子 $ [(2pi)^3 E_(bold(p))]^(-1) [(2pi)^3 E_(bold(q))]^(-1) $ が出てくることを考慮する. ) 上式で運動量を連続にした極限は $ mel(phi(y)phi(x), 0, 0) $ と等しくなることがわかる (ただし振幅として等しいというだけでブラケットに挟まれている演算子が等しいというわけではない). 上では $y^0 > x^0$ を仮定したがより一般には上の形の積からは $x^0 > y^0$ の場合の 粒子の伝播の情報も取り出せる. ただしその時は $ket(0)$ に先に $phi(y)$ を作用させなくてはならないので $ mel(phi(x)phi(y), 0, 0) $ が対応する振幅である. したがってKG場二つを使用して記述できる粒子の伝播の情報は $ fprop(x, y) = i [ theta(x^0 > y^0) mel(phi(x)phi(y), 0, 0) + theta(y^0 > x^0) mel(phi(y)phi(x), 0, 0) ] $ に含まれる.ここで慣習に合わせて全体に虚数単位$i$をかけた. 式(ref(FeynmanPropagator))であらわされる量を ファインマンプロパゲーター(Feynman propagator) または日本語でファインマン伝播関数という. また「ファインマン」を省略してプロパゲーターや伝播関数とも呼ぶ. 後述するように数学的には伝播関数は運動方程式を生成する微分演算子 (今の場合KG演算子$D^"KG"=(□ + m^2)$)のグリーン関数としての性質も持つため 単にグリーン関数と呼ばれることもある (のちにみるように上で虚数単位を付与したことによって $fprop$がグリーン関数に厳密に一致する). 系が一様な場合は伝播関数は$x$と$y$の相対的な位置関係のみに依存する. これを見るために上のファインマン伝播関数をより明示的な表式に書き換える. $ mel(phi(x)phi(y), 0, 0) &= mel( integral covmes(p) covmes(q) a_(bold(p)) e^(-i p x) a^dagger_(bold(q)) e^(+i q x) , 0, 0) &= mel( integral covmes(p) covmes(q) [a^dagger_(bold(q))a_(bold(p)) + (2pi)^3 E_(bold(p))delta^3(bold(q)-bold(p))] e^(-i p x+i q y ) , 0, 0) &= mel( integral covmes(p) e^(-i p(x-y)) , 0, 0) $ $mel(phi(y)phi(x), 0, 0)$はこれのエルミート共役なので結局 $ fprop(x,y) = integral covmes(p) [ theta(x^0-y^0) e^(-i p(x-y)) + theta(y^0-x^0) e^(+i p(x-y)) ] $ となり$fprop(x,y)$は$x$と$y$の相対的な位置$x-y$のみに依存することがわかる. そのため以下では$fprop$を一変数関数とみなし $fprop(x-y)$や$fprop(x)$のように書く. subsection(ファンマンプロパゲーターがグリーン関数であることの確認) 上でも述べたように伝播関数は場の従う運動方程式(今の場合Klein-Gordon演算子)の グリーン関数にもなっている.すなわち $ (□ + m^2)fprop(x) = delta^4(x) $ である.これは重要な性質なので以下で確認する. まず一階微分を計算する. $ partial_mu fprop(x) &= partial_mu i mel(theta(x_0)phi(x)phi(0) + theta(-x_0)phi(0)phi(x), 0, 0) &= i mel( partial_mu [ ( phi(x)phi(0)theta(x_0) + phi(y)phi(x)theta(-x_0) ) ] , 0, 0) &= i mel( partial_mu phi(x) phi(0) theta(x_0) + phi(x)phi(0) partial_mu (x_0) , 0, 0) &" " + i mel( phi(0) partial_mu phi(x) theta(-x_0) + phi(x)phi(0) partial_mu (-x_0) , 0, 0) $ ここで $partial_mu theta(x_0) = delta_(mu,0) delta(x_0), partial_mu theta(-x_0) = -delta_(mu,0) delta(x_0)$ に注意すると上の微分は $ partial_mu fprop(x) &=i mel( partial_mu phi(x) phi(0) theta(x_0) +phi(0) partial_mu phi(x) theta(-x_0) , 0, 0) &" " + i mel( phi(x)phi(0) delta(x_0) - phi(x)phi(0) delta(x_0)delta_(mu,0) , 0, 0) $ ここで第二項は$delta(x_0)$の存在により場の演算子の同時刻交換関係となり落ちる. 次にもう一回微分してダランベルシアンの作用を計算すると $ partial^mu partial_mu fprop(x) &= i mel( [□ phi(x)] phi(0) theta(x_0) + phi(0) [□ phi(x)] theta(-x_0) , 0, 0) &" " + i mel( (dot(phi)(x) phi(0) -phi(0) dot(phi)(x)) delta(x_0) , 0, 0) $ 第二項に同時刻交換関係$[phi(x),dot(phi)(y)]=i delta(bold(x)-bold(y))$を課せば 質量項の寄与も含めて最終的に次のようになる. $ (□ + m^2)fprop(x) &= i mel( [ (□ + m^2) phi(x) ] phi(0) theta(x_0) + phi(0) [ (□ + m^2) phi(x) ] theta(x_0) , 0, 0) &" " + i mel( (dot(phi)(x) phi(0) -phi(0) dot(phi)(x)) delta(x_0) , 0, 0) &= i times (-i delta^3(bold(x))) delta(x_0) = delta^4(x) $ したがって$fprop$がKlein-Gordon方程式のグリーン関数であることが分かった. また上の計算から明らかなようにファインマン伝播関数を定義するときに乗じた 虚数単位のおかげでファンマン伝播関数がグリーン関数に係数も混みで一致することがわかる. subsection(ファインマンプロパゲーターのフーリエ変換) 一番初めに相互作用と相互作用の間に自由伝播を考えることができると述べた. 一般に相互作用があると粒子のエネルギー運動量は変化し, また別の量子数での自由伝播を行うことになる. しかし一粒子のエネルギー運動量が変化するからと言って エネルギー運動量保存則が破れるわけではなく, 相互作用にかかわった粒子全体でエネルギー運動量が保存するように 相互作用のプロセスは行われる. 相互作用を考える際には 伝播関数のうちそのようなエネルギー運動量保存が成立する ような制約条件を付けて振幅を計算する. その目的のためには時空間内の伝搬と直感的につながる利点を捨ててでも 運動量表示で扱うほうが簡単である. 一方でファインマンプロパゲーターのフーリエ変換は 階段関数のフーリエ変換が自明でないためfootnote( $d/(d t) theta(plus.minus t) = delta(t)$および $delta(t) = integral (d omega)/(2pi) e^(-i omega t)$ を利用して最終的に複素積分を用いて階段関数のフーリエ変換を与えるという方法はある (例えば坂本cite(SakamotoQFT1)の11.4を見よ). そちらのほうが計算の行数は少なくなるかもしれないが 運動量表示の伝播関数の極の位置について考えることは物理的に意義があると思うので テキスト同様の手法で計算する. )難しい. そこで先ほど確認したKlein-Gordon方程式のグリーン関数との等価性を利用する. Klein-Gordon方程式をフーリエ変換し運動量表示にすると $fprop(x)$のフーリエ変換$fpropf(k)$は以下の方程式を満たす $ (-k^2 + m^2) fpropf (k) = 1 $ となる. これは簡単に解けて $ fpropf(k) &= (-1)/(k^2 - m^2) &= (-1)/(k_0^2 - E_(bold(k))^2) $ となる.ここで$E_(bold(k)) = sqrt(m^2 + bold(k)^2)$は on-shellの場合に三次元運動量$p$の粒子が持つエネルギーである. この$fpropf(k)$の逆フーリエ変換(以下でフーリエ変換を与える演算子を$hat(F)$と置く) $ (hat(F)^(-1) fpropf)(x) = integral (d^4 k)/((2pi)^4) e^(-i k x) (-1)/(k_0^2 - Ek^2) = integral d^3bold(k) e^(i bold(k)bold(x)) integral d k_0 (-e^(-i k _0t))/(k_0^2 - Ek^2) $ が$fprop(x)$に一致するならば整合的なのであるが 表式から明らかなように$fpropf(k)$は実軸上で発散している. 実解析の範囲で積分が収束するかは定かでないので以下の処方をとる. begin(enumerate) item $k_0$-積分の被積分関数を$k_0 in bb(R)$ から$z in bb(C)$ に解析接続する. item $E_(bold(k)) arrow.r E_(bold(k)) + i gamma$ の置き換えを行う. item 実軸を含む複素平面上の閉経路で$z$-積分を行うことにより実軸上の積分値を求める item 得られた値の$gamma arrow.r 0$の極限をとる. end(enumerate) 結局のところ収束が確認できない積分を積分と極限のおおらかな交換によって計算するということである. そのため数学的には正当性が薄いのであるが上の手続きには物理的な解釈を与えることができる. エネルギー固有値に$E_(bold(k))+i gamma$のように虚部を持たせることは 不安定粒子や外部への散逸が存在する系にを記述するために行われることがある footnote( 歴史上はおそらく原子核の$alpha$崩壊を記述するためにGamovが用いた処方が初である. エネルギー固有値が虚部を持つことはハミルトニアンのエルミート性に反するように思われる. しかし状態空間のほうに二乗可積でないようなものが含まれているときには ハミルトニアンがエルミートでもエネルギー固有値は虚部を持ちうるらしいcite(Hatano2017). 二乗可積ではない状態というものは珍しいものではなく 自由粒子の位置の固有状態や運動量固有状態がそうである. そのオブザーバブル表示をとれる連続スペクトルを持つオブザーバブルの固有状態はすべてそうである. ). 特に不安定粒子を例にとると時間発展が $exp(-i(E_(bold(k))+i gamma)t)=exp(-i E_(bold(k))t)times exp(-gamma t)$ となるためおおむね$abs(gamma)^(-1)$の時間で指数関数的に状態の振幅が消失 ($gamma < 0$なら発散)してしまう. 一方で$abs(gamma) << E_(bold(k))$の極限では崩壊までの間に十分な数の平面波が含まれており 近似的に安定粒子として扱える. つまり上の処理においては$abs(gamma) << E_(bold(k))$ が成立する程度の準安定な粒子と完全な安定粒子の 物理的性質が連続的につながっていると信じて極限と積分を交換しているといえる. 上の方針で計算を進めていくにあたり複素積分に移行することを意識して $fpropf(k)$の逆フーリエ変換を $ (hat(F)^(-1)fpropf)(x) &= i integral covmes(k) (2Ek) e^(+i bold(k)bold(x)) (1)/(2pi i) integral d k_0 (-e^(-i k _0 t))/(k_0^2 - Ek^2) &= i integral covmes(k) (2Ek) e^(+i bold(k)bold(x)) (1)/(2pi i) integral d k_0 f(k_0; Ek, t) $ の形に分解しておく. ここで$f(k_0; omega, t) = (-e^(-i k _0t))/(k_0^2 - omega^2)$と置いた. 上の処方を施すにあたり$e^(-i k _0t)$を解析接続した$e^(-i z t)$の肩の符号について考える. $-i (Re z + i Im z)t = -i(Re z )t + (Im z) t$なので $t > 0$の時は$Im z < 0$すなわち下半面の無限遠で $e^(-i z t)$の項は 指数関数的に$0$に落ちる. 逆に$-t$の時は上半面の無限遠で指数項は指数関数的に$0$に落ちる. 複素平面の上半面にある半円の半径無限大の極限をとった反時計周りの閉経路$cuhc$および 下半面での時計回り閉経路を$clhc$と書くことにする. そうすると先ほどの$e^(-i z t)$に関する考察から $ integral.cont_(clhc) d z (dots) &= lim_(R arrow.r +infinity) [ integral_(-R)^(+R)d z(dots) + integral_("下半円") d z (dots) ] = integral_(-infinity)^(infinity) d k_0 (dots)" "(t>0) integral.cont_(cuhc) d z (dots) &= lim_(R arrow.r +infinity) [ integral_(-R)^(+R)d z (dots) + integral_("上半円") d z (dots) ] = integral_(-infinity)^(infinity) d k_0 (dots)" "(t<0) $ が成立する. したがって$f(k_0; omega, t)$を解析接続し, $k_0 in bb(R) arrow.r z in bb(C)$の 置き換えを行うと $ (1)/(2pi i) integral d z (-e^(-i z t))/((z-omega_(+))(z-omega_(-))) &= theta(t) [ (1)/(2 pi i) integral.cont_(clhc) d z (-e^(-i z t))/((z-omega_(+))(z-omega_(-))) ] &" "+ theta(-t) [ (1)/(2 pi i) integral.cont_(cuhc) d z (-e^(-i z t))/((z-omega_(+))(z-omega_(-))) ] $ となるfootnote( 実は極のずらし方には本文で採用したもの以外にもバリエーションがある. それは「実部の正負に関係なく両方上(下)半面にずらす」というものである. しかし式(ref(decomposition_of_timeintegral)) を見ればわかるようにそのようなケースでは$theta(t)$あるいは $theta(-t)$のどちらかが落ちる. $t$の大小だけで遷移が禁止されるような条件は特になくこれは物理的に 不自然な状況である. したがってこのようなケースは今考えているケースにはふさわしくない. ). 上式で$omega_plus.minus=plus.minus(Ek+i gamma)$と置いた. 以下では留数定理を用いて積分を評価していくので$omega_plus.minus$における 留数を計算しておく. すると$z=omega_plus.minus$における留数$R_+, R_-$はそれぞれ $ R_+ &= "Res" (omega_+; f) = (- e^(-i (Ek+i gamma) t))/(omega_+ - omega_-) = (- e^(-i Ek t +gamma t))/(2(Ek + i gamma)) R_- &= "Res" (omega_-; f) = (- e^(-i (-Ek -i gamma) t))/(omega_- - omega_+) = ( e^(+i Ek t -gamma t))/(2(Ek + i gamma)) $ となる. $gamma>0$の時$clhc$積分は$z=omega_-$の留数を $cuhc$積分は$z=omega_+$の留数を拾う. 一方$gamma <0$の時は$clhc$積分は$z=omega_+$の留数を拾い $cuhc$積分は$k^0=omega_-$の留数を拾う. footnote( $clhc$は時計回りに回しているので留数に$-1$をかけたものが出てくる. ) $ (z"-積分") &= theta(t) (-R_-) + theta(-t) R_+ = theta(t) (-e^(+i Ek t -gamma t))/(2(Ek + i gamma)) + theta(-t) (- e^(-i Ek t +gamma t))/(2(Ek + i gamma)) " " (gamma > 0) &= theta(t) (-R_+) + theta(-t)R_- = theta(t) (e^(-i Ek t +gamma t))/(2(Ek + i gamma)) + theta(-t) ( e^(+i Ek t +gamma t))/(2(Ek + i gamma)) " " (gamma < 0) $ となる.ここで$gamma$に依存する因子を見ると $z$-積分は$gamma$が正の場合と負の場合それぞれで以下のような構造をしている. $ (dots) theta(t) e^(-abs(gamma) t) + (dots) theta(-t)e^(+abs(gamma) t) &" " (gamma > 0) (dots) theta(t) e^(-abs(gamma) t) + (dots) theta(-t)e^(+abs(gamma) t) &" " (gamma < 0) $ $theta(t)$を持つ項は$t arrow.r + infinity$の極限を考えうる. 同様に$theta(-t)$を持つ項は$t arrow.r - infinity$の極限を考えうる. 上式を見ると$gamma$の符号がどちらの場合でも 無限の未来と無限の将来で伝搬振幅が指数関数的に落ち物理的直観と整合的である. したがって無限の未来および過去での漸近的挙動を根拠に$gamma$の符号を決めることはできない. ここで$gamma$の符号を$sigma$とすると 式(ref(gamma_pos))および式(ref(gamma_neg))は $ integral d z (-e^(-i z t))/((z - omega_+)(z - omega_-)) = - sigma [ theta(t) (e^(+i sigma (Ek t +i gamma) t))/(2(Ek + i gamma)) + theta(-t) (e^(-i sigma (Ek +i gamma) t))/(2(Ek + i gamma)) ] $ となる.したがって$fpropf(k)$の逆フーリエ変換は $ lim_(gamma arrow.r 0^(sigma)) hat(F)^(-1)(fpropf (; gamma))(x) = -i sigma integral covmes(k) 2Ek e^(i bold(k)bold(x)) ( theta(t) (e^(+i sigma Ek t))/(2Ek) +theta(-t) (e^(-i sigma Ek t))/(2Ek) ) $ となる.ここで$e^(i bold(k)bold(x))e^(i Ek t)$の項に関しては $bold(k)arrow.r-bold(k)$の変数変換を行うと 積分範囲を $(+infinity, -infinity)arrow.r (-infinity, +infinity)$に反転する操作から $(-1)^3$の因子が,積分要素から$(-1)^3$の因子が出てくるので結局 被積分関数に$bold(k)arrow.r-bold(k)$を施しただけの結果と同じになるので $ integral covmes(k) e^(i bold(k)bold(x)) e^(i Ek t) = integral covmes(k) e^(-i bold(k)bold(x))e^(i E_(-bold(k)) t) = integral covmes(k) e^(i k x) $ とできる.つまり指数の肩に関しては$k_0=Ek$の符号だけ見ればよい. その結果 $ fprop^sigma (x) = -i sigma integral d^3 tilde(bold(k)) ( theta(t)e^(i sigma k x) + theta(t)e^(-i sigma k x) ) $ が求まる. グリーン関数との等価性を利用してフーリエ変換の逆変換として出てきた この$fprop^sigma (x)$は最初のほうで時空の一様性からの帰結を 確認するためにあらわに書き下した$fprop$の表式 (ref(exp_expansion_fprop)) $ fprop(x,y) = i integral covmes(p) [ theta(x^0-y^0) e^(-i p(x-y)) + theta(y^0-x^0) e^(+i p(x-y)) ] $ と比較すると$sigma=-1$の時に元のファインマンプロパゲーターと 一致することがわかる. footnote( それでは元の式と突き合わせるまで棄却する理由が生まれなかった $sigma=+1$の時の解は何だったのであろうか. 単にフーリエ変換しただけのものを逆フーリエ変換しているだけであったら このような分岐は生まれなかったように思う. ). これらの結果をまとめるとファインマンプロパゲーターのフーリエ変換は 微小パラメータ$epsilon >0$を用いて $ fpropf(k) = (-1)/((k_0-Ek+i epsilon)(k_0+Ek-i epsilon)) = (-1)/(k^2-m^2 +2i epsilon Ek) + O(epsilon^2) $ となる.$Ek eq.gt 0$であることを考えれば$2epsilon Ek arrow.r epsilon$ という置き換えをしても同じであり, $ fpropf(k) = (-1)/(k^2-m^2+i epsilon) $ と書ける.上では計算の正当化のために一応微小パラメータに物理的意味付けを与えたが これ以降は$epsilon$は単なる微小パラメータと考える. なお極限と積分の交換より重要なことは footnote( そもそも積分経路の上に極があるのでちょっとずらしますというのがやはり(数学的には)だいぶひどい. というわけで数学的なことは忘れて一応「逆フーリエ変換」が求まって実験とあう(らしい) ことのみを頼みとしなくてはならない. ) この運動量空間でのプロパゲーターが実空間でのプロパゲーターと(逆)フーリエ変換で つながっているということであり 上のように書かれた 運動量空間でのファインマンプロパゲーターにおいて$epsilon$の符号には注意していかなくてはならない. 例えば計量の符号が変わって$eta^(mu nu) = "diag" (-1, 1,1,1)$ となることとがあるかもしれない. その時でも$k_0^2$ の符号と $i epsilon$の符号がそろうようにしなくてはならない. subsection($T$-積および$T^(*)$-積) 上述の議論を敷衍して時空の複数の点で生成消滅が起きるような事象の振幅も考えることができる. 例えば$4$つの場の演算子が含まれるような生成消滅現象の振幅$cal(A)^((4))$は $ cal(A)^((4))(x_1, x_2, x_3, x_4) &= sum_(P in P_4) bra(0) theta(t_(P(1)) - t_(P(2)))theta(t_(P(2))-t_(P(3)))theta(t_(P(3))-t_(P(4))) \ &times phi(x_(P(1)))phi(x_(P(2)))phi(x_(P(3)))phi(x_(P(4))) ket(0) $ と書ける.ここで$P_4$は$(1,2,3,4)$に対する入れ替えすべてからなる集合である. 和の記法を使って書いても煩わしい表式であるがこれをさらにあらわに書くとなると 実際に書き下すのが現実的ではないくらいに項数が多くなる. 実際項数は生成消滅イベントの数を$N$とすると$N!$個になる. そこで以下のような$T$-積と呼ばれる記法を導入する. $T$-積とは場の演算子の積が並んでいるという文脈において 記号$T$の後ろに並んでいる演算子を時刻が後のものが左に来るように並べ替える記法のことである. 例えば$T$の後に演算子が二つ並んでいる例では $ T phi(x)phi(y) = theta(x^0 > y^0) phi(x)phi(y) + theta(y^0 > x^0) phi(y)phi(x) $ である. この記法を用いるとファインマンプロパゲーターは $ fprop(x-y) = i mel("T" phi(x)phi(y), 0, 0) $ とコンパクトに書ける. ここで導入した$T$-積は時間にかかわる操作を含んでおり時間微分を考える際に注意が必要である. 例えば$partial_(x^0)T A(x)B(y)$を考えると$T$-積をあらわに展開した時の 時間に関する階段関数にも作用するので $partial_(x^0)T A(x)B(y) eq.not T dot(A(x))B(y)$ である. 一方でのちにみるように$T$-積の中で時間微分が発生した時, $T$-積の左側に微分演算子を出してそういった階段関数への寄与も考慮することにしておいたほうが 有用である(ことがわかるらしいのでそこで定義してほしかった). そのために$T$積の並べ替えの規則に加えて$T$-積の中で時間微分が 発生した時にはその時間微分を$T$-積の左側に書き直すという規則を追加したものを $T^(*)$-積または 共変的時間順序積(Covariant time-ordered product)という. 例えば $ T^(*)dot(phi)(x)dot(phi)(y) arrow.r (partial)/(partial x^0) (partial)/(partial y^0) T phi(x)phi(y) $ などとなる. 以降の節では$T$-積の定義を$T^*$-積の定義で上書きする. ファインマンプロパゲーターは時間微分を含まないのでこの変更の影響を受けず 引き続き式(ref(fprop_by_T))の形で書ける.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.1.1/src/marks.typ
typst
Apache License 2.0
#import "@preview/cetz:0.1.2" #import "utils.typ": * /// Calculate cap offset of round-style arrow cap /// /// - r (length): Radius of curvature of arrow cap. /// - θ (angle): Angle made at the the arrow's vertex, from the central stroke /// line to the arrow's edge. /// - y (length): Lateral offset from the central stroke line. #let round-arrow-cap-offset(r, θ, y) = { r*(calc.sin(θ) - calc.sqrt(1 - calc.pow(calc.cos(θ) - calc.abs(y)/r, 2))) } #let CAP_OFFSETS = ( "head": y => round-arrow-cap-offset(8, 30deg, y), "hook": y => -2, "hook'": y => -2, "hooks": y => -2, "tail": y => -3 - round-arrow-cap-offset(8, 30deg, y), "twohead": y => round-arrow-cap-offset(8, 30deg, y) - 2, "twotail": y => -3 - round-arrow-cap-offset(8, 30deg, y) - 2, ) #let parse-arrow-shorthand(str) = { let caps = ( "": (none, none), ">": ("tail", "head"), ">>": ("twotail", "twohead"), "<": ("head", "tail"), "<<": ("twohead", "twotail"), "|": ("bar", "bar"), ) let lines = ( "-": (:), "=": (double: true), "--": (dash: "dashed"), "..": (dash: "dotted"), ) let cap-selector = "(|<|>|<<|>>|hook[s']?|harpoon'?|\|)" let line-selector = "(-|=|--|==|::|\.\.)" let match = str.match(regex("^" + cap-selector + line-selector + cap-selector + "$")) if match == none { panic("Failed to parse", str) } let (from, line, to) = match.captures ( marks: ( if from in caps { caps.at(from).at(0) } else { from }, if to in caps { caps.at(to).at(1) } else { to }, ), ..lines.at(line), ) } #let draw-arrow-cap(p, θ, stroke, kind) = { let flip = +1 if kind.at(-1) == "'" { flip = -1 kind = kind.slice(0, -1) } if kind == "harpoon" { let sharpness = 30deg cetz.draw.arc( p, radius: 8*stroke.thickness, start: θ + flip*(90deg + sharpness), delta: flip*40deg, stroke: (thickness: stroke.thickness, paint: stroke.paint, cap: "round"), ) } else if kind == "head" { draw-arrow-cap(p, θ, stroke, "harpoon") draw-arrow-cap(p, θ, stroke, "harpoon'") } else if kind == "tail" { p = vector.add(p, vector-polar(stroke.thickness*CAP_OFFSETS.at(kind)(0), θ)) draw-arrow-cap(p, θ + 180deg, stroke, "head") } else if kind in ("twohead", "twotail") { let subkind = if kind == "twohead" { "head" } else { "tail" } p = cetz.vector.sub(p, vector-polar(-1*stroke.thickness, θ)) draw-arrow-cap(p, θ, stroke, subkind) p = cetz.vector.sub(p, vector-polar(+3*stroke.thickness, θ)) draw-arrow-cap(p, θ, stroke, subkind) } else if kind == "hook" { p = vector.add(p, vector-polar(stroke.thickness*CAP_OFFSETS.at("hook")(0), θ)) cetz.draw.arc( p, radius: 2.5*stroke.thickness, start: θ + flip*90deg, delta: -flip*180deg, stroke: ( thickness: stroke.thickness, paint: stroke.paint, cap: "round", ), ) } else if kind == "hooks" { draw-arrow-cap(p, θ, stroke, "hook") draw-arrow-cap(p, θ, stroke, "hook'") } else if kind == "bar" { let v = vector-polar(4.5*stroke.thickness, θ + 90deg) cetz.draw.line( (to: p, rel: v), (to: p, rel: vector.scale(v, -1)), stroke: ( paint: stroke.paint, thickness: stroke.thickness, cap: "round", ), ) } else { panic("unknown arrow kind:", kind) } }
https://github.com/elenev/elenev.github.io
https://raw.githubusercontent.com/elenev/elenev.github.io/main/README.md
markdown
# Academic Personal Website This README contains a brief description of my website for anyone who may want to use it as a template for their own. In creating this website, my goal was to create a simple, clean, and professional website, which is easy to maintain. Given that both the website and my PDF CV contain some of the same information, I wanted to make it easy to update both simultaneously. ## Tools - **[Quarto](https://quarto.org)**: I used Quarto because it allows me to write in markdown, interweave code output, and contains pretty tempates. If you use VS Code, you can install the Quarto extension for a better experience, e.g., to preview the website without using the command line. - **[Julia](https://julialang.org)**: I used Julia to process the data (stored in YAML format) and generate markdown content. Quarto also works with R, Python, and ObservableJS, all of which should be capable of parsing YAML into dictionaries and then looping over the data to generate content. I used Julia because it's my favorite language -- it's fast, elegant, and has an excellent dependency management system. - **[Typst](https://github.com/typst/typst)**: I used Typst to create a PDF version of my CV from the same YAML-formatted data as the website. Typst is a modern alternative to LaTeX with much faster compile times, clean syntax, and a powerful and fairly intuitive programming language for creating templates. Note: Typst has an excellent [Overleaf-style web app](https://typst.app/) with a live preview, autocomplete, syntax highlighting, and nice error messages. But it's hard to integrate a web app into a GitHub Pages workflow, so I use the CLI (command-line interface) in the production environment. I did my original development in the web app, so if you want to do extensive customizations, I suggest you sign up for an account and use the web app too. ## Quick Start 1. Install Quarto 1.5 or later, a recent version of Julia (use `juliaup` to make your life easier), and the Typst CLI. 2. Clone the repository. Set up your own local and remote on Github. Delete my `CNAME` file to avoid conflicts with your own custom domain. 3. Edit the `cv/cv.yml` file to include your own information. If you use VS Code with the `yaml-language-server` extension, the provided `cv/cv.json` schema will help with autocompletion. 4. Edit the top of the `index.qmd` file to include your own name, photo, social media links, and other info. Save any additional files (e.g. photo) in the `resources` folder. 5. Edit `_quarto.yml` to customize the navigation bar links, Twitter card, Google Analytics, etc. 6. Run `typst compile cv/main.typ` to generate a PDF version of your CV. Once you're happy with the result, move the PDF to `resources/cv.pdf`. 7. Run `quarto preview` or use the GUI interface in VS Code to generate the website and make sure everything looks right. 8. Run `quarto publish gh-pages` to publish the site to GitHub Pages. This will create/update a separate branch called `gh-pages` in your repository. You can configure `Pages` settings to serve the website from that repository. This keeps your `main` branch clean from the generated files. ## Customization - You can change the order of sections in the website CV by editing `CV.qmd`. - You can change the order of sections in the PDF CV by editing `cv/main.typ`. - You can change the scheme, colors, and other styling by editing `styles.css`, `_quarto.yml`, and `theme-dark.scss`. - If you want to fine-tune the display of generated content and don't want to learn Julia, you should be able to use generative AI (e.g., ChatGPT, GitHub Copilot) to translate my Julia code into the Quarto-compatible language of your choice, e.g., Python. The loops in `index.qmd` and `CV.qmd` are fairly simple and should be easy to translate. The code to parse the YAML data and print publications, etc. is in `common.jl` and is a bit more involved.
https://github.com/AHaliq/DependentTypeTheoryReport
https://raw.githubusercontent.com/AHaliq/DependentTypeTheoryReport/main/chapters/chapter4/index.typ
typst
#import "../../preamble/dtt.typ": * #import "../../preamble/catt.typ": * #import "@preview/curryst:0.3.0": rule, proof-tree #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #import "@preview/cetz:0.2.2" = Homotopy Type Theory (HoTT) $ {c in Tm(Gamma. Id(U,A,B), C) | upright("elim") } iso {star} $ $Id$ eliminates to a term of $C gap a gap b gap p$. But what do we want $C$ to be semantically for $Id(UU,A,B)$? Naively we would want an isomorphism or bimaps between the two types. We also want a stronger condition where the isomorphism is unique. This implies the identifications themselves are isomorphic to the isomorphisms / bimaps. This structure is an example of univalence: $ "univalence"_U: Id(U,A,B) gap ~ gap (C gap A gap B gap p) $ But this is too strong a condition that only $HProp$ a subtype of $UU$ can satisfy. Thus instead of $~ = iso$, it is weakened it to Voevodsky's definition of equivalence; $~ = equiv$. _A subtype is a type along with a witness of its inclusion. i.e. $HProp = (A: UU) times "isHProp"(A)$, we will leave the witness implicit_ == Definition #grid(columns: (auto, 1fr), align: (right, left), [ prop univalence #figure(cetz.canvas({ import cetz.draw: * scale(x: 60%, y: 60%) circle((0,0), name: "L") circle((3,0), name: "R") circle((1.5,0), radius: (3,2), name: "HProp") fill(black) circle((0,0), radius: 0.15, name: "a1") circle((3,0), radius: 0.15, name: "b1") fill(black) content("L.north", [$A$], anchor: "south") content("R.north", [$B$], anchor: "south") content("HProp.north", $HProp$, anchor: "south") stroke(black) stroke((paint: purple, dash: "dashed")) line("a1.east", "b1.west", name: "line1", mark: (end: ">", start: ">")) })) ], figure(table(columns: 3, align: (right, left, left), [], [Prop. Univalence], [Full Univalence], $U$, $HProp$, $UU$, $C gap A gap B gap p$, $A iso B$, $A equiv B$, $"elim"$, $(&subst gap id gap p,\ &subst gap id gap (sym gap p))$, $idtoequiv$, $"intro"$, $isotoid$, $ua$ )) ) #grid(columns: (1fr, 1fr), align: (left, left), [ #figure(table(columns: 2, align: (right, left), [type], [definition], $A iso B$, $Sigma((f,g): A <-> B, "areIso"(f,g))$, $A <-> B$, $(A -> B) times (B -> A)$, $"areIso"(f,g)$, $Id(A -> A, g comp f, id) times Id(B -> B, f comp g, id)$, )) ], [ #figure(table(columns: 2, align: (right, left), [type], [definition], $A equiv B$, $Sigma(f : A -> B, "isEquiv"(f))$, $"isEquiv"(f)$, $Pi(b : B, "isContr"("fib"(f,b)))$, $"isContr"(X)$, $Sigma(x : X, Pi(y : X, Id(X,x,y)))$, $"fib"(f,b)$, $Sigma(a : A, Id(B,f gap a, b))$ )) ] ) #figure(table(columns: 5, align: (right + horizon,center + horizon, center + horizon, center + horizon, center + horizon), [type],[fibre], [contractible], [contractible fibre], [univalence], [], figure(cetz.canvas({ import cetz.draw: * scale(x: 60%, y: 60%) circle((0,0), radius:(1,1.5), name: "L") circle((3,0), radius:(1,1.5), name: "R") fill(black) circle((0,1), radius: 0.15, name: "a1") circle((0,0.25), radius: 0.15, name: "a2") circle((0,-0.5), radius: 0.15, name: "a3") circle((0,-1.2), radius: 0.15, name: "a4") circle((2.75,0.8), radius: 0.15, name: "b1") circle((2.75,0), radius: 0.15, name: "b2") circle((2.75,-0.8), radius: 0.15, name: "b3") circle((3.75,0), radius: 0.15, name: "b4") circle((3.2,-1), radius: 0.15, name: "b5") fill(black) content("L.north", [$A$], anchor: "south") content("R.north", [$B$], anchor: "south") stroke(black) stroke((paint: gray, dash: "dotted")) line("a1.east", "b1.west", name: "line1", mark: (end: ">")) content("line1.mid", $f$, anchor: "south") line("a2.east", "b2.west", name: "line2", mark: (end: ">")) line("a3.east", "b3.west", name: "line3", mark: (end: ">")) stroke((paint: purple, dash: "solid")) line("b1.east", "b4.north", name: "line4", mark: (end: ">")) line("b2.east", "b4.west", name: "line5", mark: (end: ">")) line("b3.east", "b4.south", name: "line6", mark: (end: ">")) })), figure(cetz.canvas({ import cetz.draw: * scale(x: 60%, y: 60%) circle((0,0), radius:(1.5,1.5), name: "X") content("X.north", $X$, anchor: "south") fill(black) circle((0,0.75), radius: 0.15, name: "x1") content("x1.east", $x$, anchor: "west") circle((-0.75,-0.5), radius: 0.15, name: "x2") circle((0,-0.75), radius: 0.15, name: "x3") circle((0.75,-0.5), radius: 0.15, name: "x4") stroke((paint: purple, dash: "solid")) line("x1.south", "x2.north", name: "line1", mark: (end: ">")) line("x1.south", "x3.north", name: "line1", mark: (end: ">")) line("x1.south", "x4.north", name: "line1", mark: (end: ">")) })), figure(cetz.canvas({ import cetz.draw: * scale(x: 60%, y: 60%) circle((0,0), radius:(1,1.5), name: "L") circle((3,0), radius:(1,1.5), name: "R") fill(black) circle((0,0.8), radius: 0.15, name: "a1") fill(purple) stroke(purple) circle((0,0), radius: 0.15, name: "a2") fill(black) stroke(black) circle((0,-0.8), radius: 0.15, name: "a3") circle((2.75,0.8), radius: 0.15, name: "b1") circle((2.75,0), radius: 0.15, name: "b2") circle((2.75,-0.8), radius: 0.15, name: "b3") circle((3.75,0), radius: 0.15, name: "b4") fill(black) content("L.north", [$A$], anchor: "south") content("R.north", [$B$], anchor: "south") stroke(black) stroke((paint: gray, dash: "dotted")) line("a1.east", "b1.west", name: "line1", mark: (end: ">")) content("line1.mid", $f$, anchor: "south") line("a2.east", "b2.west", name: "line2", mark: (end: ">")) line("a3.east", "b3.west", name: "line3", mark: (end: ">")) stroke((paint: black, dash: "solid")) line("b1.east", "b4.north", name: "line4", mark: (end: ">")) line("b2.east", "b4.west", name: "line5", mark: (end: ">")) line("b3.east", "b4.south", name: "line6", mark: (end: ">")) stroke((paint: purple, dash: "solid")) line("a2.north", "a1.south", mark: (end: ">")) line("a2.south", "a3.north", mark: (end: ">")) line("line5.25%", "line4.25%", mark: (end: ">")) line("line5.25%", "line6.25%", mark: (end: ">")) })), figure(cetz.canvas({ import cetz.draw: * scale(x: 60%, y: 60%) circle((0,0), radius:(1,1.5), name: "L") circle((3,0), radius:(1,1.5), name: "R") circle((1.5,0), radius: (3,2.5), name: "UU") circle((0,0), radius: (0.3,0.5), name: "a1") circle((-0.2,0.5), radius: (0.3,0.5), name: "a2") circle((0,-0.7), radius: (0.3,0.5), name: "a3") circle((3,0), radius: (0.3,0.5), name: "b1") circle((2.7,0.8), radius: (0.3,0.5), name: "b2") circle((3.1,-0.5), radius: (0.3,0.5), name: "b3") fill(black) content("L.north", [$A$], anchor: "south") content("R.north", [$B$], anchor: "south") content("UU.north", $UU$, anchor: "south") stroke(black) stroke((paint: purple, dash: "dashed")) line("a1.east", "b1.west", name: "line1", mark: (end: ">")) line("a2.east", "b2.west", name: "line2", mark: (end: ">")) line("a3.east", "b3.west", name: "line3", mark: (end: ">")) })) )) Intuitively, in prop univalence $|A| = |B|$ but in full unvalence fibres create _covers_ of the terms such that $|"covers"(A)| = |"covers"(B)|$ such that $ "isEquiv"(f) : HProp \ "isEquiv"(f) <-> "isIso"(f) $ == Semantic Consequences / H Levels: h levels describe at which point are identifications contractible $ "hasHLevel" gap 0 gap A &= "isContr"(A) \ "hasHLevel" gap (succ gap n) gap A &= (a gap b : A) -> h gap n gap Id(A,a,b) $ #figure(table(columns: 2, align: (right, left), [h level], [structure], $0$, [truth values], $1$, [propositions], $2$, [sets], $3$, [groupoids], $n$, [$n-2$-groupoids] )) / Higher Inductive Types: inductive types with h levels greater than 2 are higher inductive types such as Interval, Suspensions, Set Truncations / Synthetic Homotopy Theory: with equality corresponding to paths, and having higher inductive types, we can define homotopical structures such as the unit circle, torus, etc. This effectivity is due the "all quotient-type constructions / *colimits* in HoTT exhibit effectivity / *descent*" In modern mathematics we often ask what is the map between instances of a structure. Univalence does this by its relation $~$; $iso$ or $equiv$. This is called the *structure identity principle (SIP)*. == Metatheoretic Consequnces / Cubical Type Theory - $ua$ in full univalence breaks canonicity as the empty context has a term - we fix this by giving a judgemental structure (reverse internalization?) to propositional equality - the judgemental are intervals $bb(I)$, thus judgementally we have congruence thus cubical type theory. - $Id$ now is an internalization of the judgemental structure $Gamma, bb(I) hy M : A$
https://github.com/Dav1com/minerva-report-fcfm
https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/template/main.typ
typst
MIT No Attribution
#import "@preview/minerva-report-fcfm:0.3.0" as minerva #import "meta.typ" as meta #show: minerva.informe.with( meta, showrules: true, ) //#minerva.resumen[ // Aquí iría el resumen del informe //] #outline() = Escribiendo simples parrafos Typst se parece mucho a Markdown y secuencias de carácteres especiales puedes dar estilo al texto, por ejemplo, puedes usar negrite *abc*, itálica _oooo_ y monoespaciado `typst watch main.typ`. Un parrafo nuevo se hace simplemente dejando una línea en blanco. == El símbolo igual `=` se usa para crear un título En LaTeX se usa `\` para utilizar comandos, en Typst usamos `#`, hay muchas utilidades como emoji #emoji.face.happy, funciones de cálculo #calc.binom(10, 4), y conversiones de tiempo #duration(days: 5).minutes() = Elementos Los documentos en Typst se forman uniendo contenido, el contenido se obtiene llamando _element functions_, a continuación las más importantes == Ecuaciones Las ecuaciones dentro de línea se hacen con símbolos peso `$`, así: $sqrt(epsilon/phi + c/d)$ Y en su propia línea con `$ x $`, los espacios son importantes: $ sqrt(epsilon/phi + c/d) $ == Figuras y referencias Una figura se introduce con `figure`: #figure( caption: "Una tabla dentro de una figura.", table(columns: 2)[nombre][tiempo][Viajar a la U][30 minutos] ) <mi-tabla> A la tabla le agregamos `<mi-tabla>` para poder referenciarlar con @mi-tabla = Necesitas más ayuda? La documentación de typst es muy buena explicando los conceptos claves para usarlo. - Puedes partir leyendo el tutorial: https://typst.app/docs/tutorial/ - Si tienes expericiencia en LaTeX, entonces la guía para usuarios de LaTeX es un buen punto de partida: https://typst.app/docs/guides/guide-for-latex-users/ - Para consultas específicas, está el servidor de Discord de Typst: https://discord.gg/2uDybryKPe = Show rules y Utilidades El template incluye algunas show rules opcionales y utilidades generales, más documentación en el #link("https://github.com/Dav1com/minerva-report-fcfm/blob/master/README.md")[README.md]. == Obteniendo Ayuda Puedes ver que existe un módulo `minerva.rules` con una función `formato-numeros-es`, pero qué hace exactamente? para eso están las funciones `help`! Todos los módulos del template tienen esta funciíón y sirve para obtener documentación sobre una función en específico: #minerva.rules.help("formato-numeros-es")
https://github.com/adam-zhang-lcps/papers
https://raw.githubusercontent.com/adam-zhang-lcps/papers/main/bridge-to-government-apush.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#set page( paper: "us-letter", margin: 1in, header: context if counter(page).get().first() > 1 { // HACK: There's probably a better way to do this… align(right, str(counter(page).get().first() - 1)) }, ) #set text(font: "Liberation Serif", size: 12pt) #set par(leading: 1.3em, first-line-indent: 0.5in) #set page(numbering: none) #v(30%) #align(center)[NATIONAL SECURITY AGENCY (BRIDGE TO GOVERNMENT)] #v(20%) #align(center)[ <NAME> AP US History #datetime(year: 2024, month: 06, day: 04).display("[month repr:long] [day], [year]") ] #pagebreak() Although it existed in earlier forms, the NSA in its modern form was formed in 1952 following a directive from President Truman. The goal of the various incarnations of the agency before its formal inception was to obtain information on foreign communication, especially during wartime, to support national intelligence. This primarily took the form of various types of crypt-analysis and code-breaking, especially during both World Wars. Following both global wars and the NSA's formal establishment, the mission of the NSA turned to providing global "signals intelligence" @Britannica2024NationalSecurityAgency, the interception of signals in communication, to support national security @NSASignalsIntelligenceOverview. The NSA is currently among one of the largest and most-funded defense agencies. While exact funding is unknown, as the NSA falls under the "black budget" of the Department of Defense, estimates resulting from the Snowden leak in 2013 place the budget at the time around \$7 billion @GellmanMiller2023BlackBudget. The number of employees is also not publicly disclosed, but is estimated to be around 30--40 thousand. The modern-day responsibilities of the NSA mirror its original responsibilities, though its horizons have expanded; it is now responsible for global monitoring and aggregation of data for national intelligence, as well as protecting US information systems @NSAAbout. Information provided by the NSA is extremely valuable in protecting US national security, and the NSA fills a unique role in digital signals intelligence (compared to other organizations such as the CIA). NSA services help in combating terrorism and other violent crime, especially after the advent of the September 11 attacks. However, the NSA has also come under repeated scrutiny for extending its powers beyond reason and invading personal privacy. The most notable case was the leaks by <NAME>, a former contractor, in 2013, which revealed the existence of many secret mass surveillance programs in use by the NSA that collected large amounts of personal data on American citizens @Britannica2024EdwardShowden. This has raised heated debate on where the balance between national intelligence and individual privacy lies. An article from _The New York Times_ provides a recent example of this debate, detailing how the NSA purchases information from "data brokers". Commercial data brokers collect information about citizens from multiple sources---such as ISPs and online platforms---and then sell that data to other entities. By purchasing data from these brokers, the NSA can skirt the requirement of a search warrant to collect information about a single person. While the article details how the NSA emphasizes that it attempts to minimize the data collected on American individuals, it also provides the viewpoints of those who oppose surveillance of this nature, who argue that it should be illegal for the government to purchase data that would need a search warrant to obtain in other ways @Savage2024NSAInternetData. #set bibliography(style: "chicago-fullnotes") #show bibliography: it => { show heading: it => { set align(center) set text(weight: "regular", size: 12pt) it v(2em) } set par(first-line-indent: 0in) pagebreak() it } #bibliography("refs.bib")
https://github.com/ntjess/wrap-it
https://raw.githubusercontent.com/ntjess/wrap-it/main/docs/readme.typ
typst
The Unlicense
#import "@preview/showman:0.1.0" #import "@preview/wrap-it:0.1.0" #show: showman.formatter.template.with( eval-kwargs: ( scope: (wrap-it: wrap-it), eval-prefix: " #let wrap-content(..args) = output(wrap-it.wrap-content(..args)) #let wrap-top-bottom(..args) = output(wrap-it.wrap-top-bottom(..args)) ", ) ) #let showman-config = ( page-size: (width: 4.1in, height: auto), eval-kwargs: ( scope: (wrap-it: wrap-it), unpack-modules: true, eval-prefix: " #let wrap-content(..args) = output(wrap-it.wrap-content(..args)) #let wrap-top-bottom(..args) = output(wrap-it.wrap-top-bottom(..args)) ", ) ) #show <example-output>: set text(font: "") #show link: it => { set text(fill: blue) underline(it) } #set page(height: auto) = Wrap-It: Wrapping text around figures & content Until https://github.com/typst/typst/issues/553 is resolved, `typst` doesn't natively support wrapping text around figures or other content. However, you can use `wrap-it` to mimic much of this functionality: - Wrapping images left or right of their text - Specifying margins - And more Detailed descriptions of each parameter are available in the #link("https://github.com/ntjess/wrap-it/blob/main/docs/manual.pdf")[wrap-it documentation]. = Installation The easiest method is to import `wrap-it: wrap-content` from the `@preview` package: ```typ #import "@preview/wrap-it:0.1.0": wrap-content ``` = Sample use: == Vanilla ```globalexample #set par(justify: true) #let fig = figure( rect(fill: teal, radius: 0.5em, width: 8em), caption: [A figure], ) #let body = lorem(40) #wrap-content(fig, body) ``` == Changing alignment and margin ```globalexample #wrap-content( fig, body, align: bottom + right, column-gutter: 2em ) ``` == Uniform margin around the image The easiest way to get a uniform, highly-customizable margin is through boxing your image: ```globalexample #let boxed = box(fig, inset: 0.5em) #wrap-content(boxed)[ #lorem(40) ] ``` == Wrapping two images in the same paragraph ```globalexample #let fig2 = figure( rect(fill: lime, radius: 0.5em), caption: [Another figure], ) #wrap-top-bottom(boxed, fig2, lorem(60)) ```
https://github.com/VZkxr/Typst
https://raw.githubusercontent.com/VZkxr/Typst/master/Seminario/Proyecto%20Final/codly-0.2.1/codly.typ
typst
#let __codly-enabled = state("codly-enabled", false) #let __codly-offset = state("codly-offset", 0) #let __codly-range = state("codly-range", none) #let __codly-languages = state("codly-languages", (:)) #let __codly-display-names = state("codly-display-names", true) #let __codly-display-icons = state("codly-display-icons", true) #let __codly-default-color = state("codly-default-color", rgb("#283593")) #let __codly-radius = state("codly-radius", 0.32em) #let __codly-padding = state("codly-padding", 0.32em) #let __codly-fill = state("codly-fill", white) #let __codly-zebra-color = state("codly-zebra-color", luma(240)) #let __codly-stroke-width = state("codly-stroke-width", none) #let __codly-stroke-color = state("codly-stroke-color", luma(240)) #let __codly-numbers-format = state("codly-numbers-format", text) #let __codly-breakable = state("codly-breakable", true) #let __codly-enable-numbers = state("codly-enable-numbers", true) // Default language-block style #let default-language-block(name, icon, color, loc) = { let radius = __codly-radius.at(loc) let padding = __codly-padding.at(loc) let stroke-width = __codly-stroke-width.at(loc) let color = if color == none { __codly-default-color.at(loc) } else { color } box( radius: radius, fill: color.lighten(60%), inset: padding, stroke: stroke-width + color, outset: 0pt, icon + name, ) } #let __codly-language-block = state("codly-language-block", default-language-block) // Lets you set a line number offset. #let codly-offset(offset: 0) = { __codly-offset.update(offset) } // Lets you set a range of line numbers to highlight. #let codly-range( start: 1, end: none, ) = { __codly-range.update((start, end)) } // Disables codly. #let disable-codly() = { __codly-enabled.update(false) } // Configures codly. #let codly( // The list of languages, allows setting a display name and an icon, // it should be a dict of the form: // `<language-name>: (name: <display-name>, icon: <icon-content>, color: <color>)` languages: none, // Whether to display the language name. display-name: none, // Whether to display the language icon. display-icon: none, // The default color for a language not in the list. // Only used if `display-icon` or `display-name` is `true`. default-color: none, // Radius of a code block. radius: none, // Padding of a code block. padding: none, // Fill color of lines. // If zebra color is enabled, this is just for odd lines. fill: none, // The zebra color to use or `none` to disable. zebra-color: none, // The stroke width to use to surround the code block. // Set to `none` to disable. stroke-width: none, // The stroke color to use to surround the code block. stroke-color: none, // Whether to enable line numbers. enable-numbers: none, // Format of the line numbers. // This is a function applied to the text of every line number. numbers-format: none, // A function that takes 3 positional parameters: // - name // - icon // - color // It returns the content for the language block. language-block: none, // Whether this code block is breakable. breakable: none, ) = { // Enable codly __codly-enabled.update(true) if languages != none { assert(type(languages) == type((:)), message: "codly: `languages` must be a dict") __codly-languages.update(languages) } if display-name != none { assert(type(display-name) == bool, message: "codly: `display-name` must be a dict") __codly-display-names.update(display-name) } if display-icon != none { assert(type(display-icon) == bool, message: "codly: `display-icon` must be a dict") __codly-display-icons.update(display-icon) } if default-color != none { assert( type(default-color) == color or type(default-color) == gradient or type(default-color) == pattern, message: "codly: `default-color` must be a color or a gradient or a pattern" ) __codly-default-color.update(default-color) } if radius != none { assert( type(radius) == type(1pt + 0.32em), message: "codly: `radius` must be a length" ) __codly-radius.update(radius) } if padding != none { assert( type(padding) == type(1pt + 0.32em), message: "codly: `padding` must be a length" ) __codly-padding.update(padding) } if fill != none { assert( type(fill) == color or type(fill) == gradient or type(fill) == pattern, message: "codly: `fill` must be a color or a gradient or a pattern" ) __codly-fill.update(fill) } if zebra-color != none { assert( zebra-color == none or type(zebra-color) == color or type(zebra-color) == gradient or type(zebra-color) == pattern, message: "codly: `zebra-color` must be none, a color, a gradient, or a pattern" ) __codly-zebra-color.update(zebra-color) } if stroke-width != none { assert( type(stroke-width) == type(1pt + 0.1em), message: "codly: `stroke-width` must be a length" ) __codly-stroke-width.update(stroke-width) } if stroke-color != none { assert( stroke-color == none or type(stroke-color) == color or type(stroke-color) == gradient or type(stroke-color) == pattern, message: "codly: `stroke-color` must be none, a color, a gradient, or a pattern" ) __codly-stroke-color.update(stroke-color) } if enable-numbers != none { assert( type(enable-numbers) == bool, message: "codly: `enable-numbers` must be a bool" ) __codly-enable-numbers.update(enable-numbers) } if numbers-format != none { assert( type(numbers-format) == function, message: "codly: `numbers-format` must be a function" ) __codly-numbers-format.update((_) => numbers-format) } if breakable != none { assert( type(breakable) == bool, message: "codly: `breakable` must be a bool" ) __codly-breakable.update(breakable) } if language-block != none { assert( type(language-block) == function, message: "codly: `language-block` must be a function" ) __codly-language-block.update(language-block) } } #let codly-init( body, ) = { show raw.where(block: true): it => locate(loc => { let range = __codly-range.at(loc) let in_range(line) = { if range == none { true } else if range.at(1) == none { line >= range.at(0) } else { line >= range.at(0) and line <= range.at(1) } } if __codly-enabled.at(loc) != true { return it } let languages = __codly-languages.at(loc) let display-names = __codly-display-names.at(loc) let display-icons = __codly-display-icons.at(loc) let language-block = __codly-language-block.at(loc) let default-color = __codly-default-color.at(loc) let radius = __codly-radius.at(loc) let offset = __codly-offset.at(loc) let stroke-width = __codly-stroke-width.at(loc) let stroke-color = __codly-stroke-color.at(loc) let zebra-color = __codly-zebra-color.at(loc) let numbers-format = __codly-numbers-format.at(loc) let padding = __codly-padding.at(loc) let breakable = __codly-breakable.at(loc) let fill = __codly-fill.at(loc) let enable-numbers = __codly-enable-numbers.at(loc) let start = if range == none { 1 } else { range.at(0) }; let stroke = if stroke-width == 0pt or stroke-width == none or stroke-color == none { none } else { stroke-width + stroke-color }; let items = () for (i, line) in it.lines.enumerate() { if not in_range(line.number) { continue } // Always push the formatted line number if enable-numbers { items.push(numbers-format(str(line.number + offset))) } // The language block (icon + name) let language-block = if line.number != start or display-names != true and display-icons != true { items.push(line) continue } else if it.lang == none { items.push(line) continue } else if it.lang in languages { let lang = languages.at(it.lang); let name = if display-names { lang.name } else { [] } let icon = if display-icons { lang.icon } else { [] } (language-block)(name, icon, lang.color, loc) } else if display-names { (language-block)(it.lang, [], default-color, loc) } // Push the line and the language block in a grid for alignment items.push(style(styles => grid( columns: (1fr, measure(language-block, styles).width + 2 * padding), line, place(right + horizon, language-block), ))) } block( breakable: breakable, clip: true, width: 100%, radius: radius, stroke: stroke-color + stroke-width, if enable-numbers { table( columns: (auto, 1fr), inset: padding * 1.5, stroke: none, align: left + horizon, fill: (x, y) => if zebra-color != none and calc.rem(y, 2) == 0 { zebra-color } else { fill }, ..items, ) } else { table( columns: (1fr,), inset: padding * 1.5, stroke: none, align: left + horizon, fill: (x, y) => if zebra-color != none and calc.rem(y, 2) == 0 { zebra-color } else { fill }, ..items, ) } ) codly-offset() codly-range(start: 1, end: none) }) body }
https://github.com/Misterio77/typst-nix
https://raw.githubusercontent.com/Misterio77/typst-nix/main/example/main.typ
typst
#import "@preview/gentle-clues:0.9.0": tip #tip[ Hi there! #lorem(30) ] #set text(font: "Fira Sans") I like Fira. #image("tux.png", width: 50%) #let info(data) = [Nix is #data.nix, Guix is #data.guix] #info(json("data.json"))
https://github.com/fenjalien/cirCeTZ
https://raw.githubusercontent.com/fenjalien/cirCeTZ/main/components.typ
typst
Apache License 2.0
#import "../typst-canvas/draw.typ": * #import "parts.typ" #import "utils.typ": anchors #let geographical-anchors(pts) = { assert(type(pts) == "array" and pts.len() == 8, message: "Invalid format for geographical anchor positions " + repr(pts)) let headings = ("west", "north west", "north", "north east", "east", "south east", "south", "south west") for i in range(0, 8) { anchor(headings.at(i), pts.at(i)) } } /// Resistive bipoles /// Short circuit /// type: path-style /// nodename: shortshape /// class: default #let short = { line((-0.5, 0), (0.5, 0)) anchors(( north: (0,0), south: (0,0), label: (0,0), annotation: (0,0), )) } /// Resistor /// type: path-style /// nodename: resistorshape /// Aliases: american resistor /// Class: resistors #let R = { let step = 1/6 let height = 5/14 let sgn = -1 line( (-0.5, 0), (rel: (step/2, height/2)), ..for _ in range(5) { ((rel: (step, height * sgn)),) sgn *= -1 }, (0.5, 0), fill: none ) anchors(( north: (0, height/2), south: (0, -height/2), label: (0, height), annotation: "south" )) } // Capacitors and inductors // Diodes and such // Sources and generators /// American Current Source /// type: path-style, fillable /// nodename: isourceAMshape /// aliases: american current source /// class: sources #let isourceAM = { circle((0,0), radius: 0.5, name: "c") line(((-0.3, 0)), (rel: (0.6, 0)), mark-end: ">", fill: black) anchors(( north: (0, 0.5), south: (0, -0.5), label: (0, 0.7), annotation: (0, -0.7), )) } /// Arrows /// Arrow for current and voltage /// type: node #let currarrow = { line( (0.05, 0), (-0.05, -0.05), (-0.05, 0.05), close: true, fill: black ) anchors(( north: (0, 0.05), south: (0, -0.05), east: (0.05, 0), west: (-0.05, 0), )) } /// Terminal shapes /// Unconnected terminal /// type: node #let ocirc = { circle((0, 0), radius: 0.05, stroke: black) anchors(( north: (0, 0.05), south: (0, -0.05), east: (0.05, 0), west: (-0.05, 0), )) } /// Connected terminal /// type: node #let circ = { fill(black) ocirc } /// Diamond-square terminal /// type: node #let diamondpole = { fill(black) anchors(( north: (0, 0.05), south: (0, -0.05), east: (0.05, 0), west: (-0.05, 0), )) line( "north", "east", "south", "west", close: true ) } /// Square-shape terminal /// type: node #let squarepole = { fill(black) rect( (-0.05, -0.05), (0.05, 0.05) ) anchors(( north: (0, 0.05), south: (0, -0.05), east: (0.05, 0), west: (-0.05, 0), )) } /// Amplifiers /// Operational amplifier #let op-amp = { line( (0.8, 0), (-0.8, -1), (-0.8, 1), close: true ) anchors(( north: (0, 1), south: (0, -1), east: (1, 0), west: (-1, 0), )) } /// Logic gates /// AND gate /// type: node, fillable #let and-gate = { parts.and-gate-body parts.logic-gate-legs } /// NAND gate /// type: node, fillable #let nand-gate = { parts.and-gate-body parts.not-circle // circle((rel: (0.1, 0), to: "bout"), radius: 0.1) // anchor("bout", (rel: (0.1, 0))) parts.logic-gate-legs } /// OR gate /// type: node, fillable #let or-gate = { parts.or-gate-body parts.logic-gate-legs } /// NOR gate /// type: node, fillable #let nor-gate = { parts.or-gate-body parts.not-circle parts.logic-gate-legs } /// XOR gate /// type: node, fillable #let xor-gate = { parts.or-gate-body parts.logic-gate-legs parts.xor-bar } /// XNOR gate /// type: node, fillable #let xnor-gate = { parts.or-gate-body parts.not-circle parts.logic-gate-legs parts.xor-bar } #let path = ( // Resistive bipoles "short": short, "R": R, // Sources and generators "isourceAM": isourceAM, ) #let node = ( // Arrows "currarrow": currarrow, //Terminal Shapes "circ": circ, "ocirc": ocirc, "diamondpole": diamondpole, "squarepole": squarepole, // Amplifiers "op amp": op-amp, // Logic gates "and gate": and-gate, "nand gate": nand-gate, "or gate": or-gate, "nor gate": nor-gate, "xor gate": xor-gate, "xnor gate": xnor-gate )
https://github.com/cathblatter/ins-poster-typst
https://raw.githubusercontent.com/cathblatter/ins-poster-typst/main/_extensions/ins-poster-typst/typst-template.typ
typst
// This is an example typst template (based on the default template that ships // with Quarto). It defines a typst function named 'article' which provides // various customization options. This function is called from the // 'typst-show.typ' file (which maps Pandoc metadata function arguments) // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-show.typ' entirely. You can find // documentation on creating typst templates and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #let poster( // The poster's size. size: "'36x24' or '48x36''", // The poster's title. title: "Paper Title", subtitle: "Paper subtitle", // A string of author names. authors: "<NAME> (separated by commas)", // Department name. departments: "Department Name", // header color // Footer text. // For instance, Name of Conference, Date, Location. // or Course Name, Date, Instructor. footer_text: "Footer Text", // Any URL, like a link to the conference website. footer_url: "Footer URL", // Email IDs of the authors. footer_email_ids: "Email IDs (separated by commas)", // Color of the footer. footer_color: "Hex Color Code", // DEFAULTS // ======== // For 3-column posters, these are generally good defaults. // Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters. // For 2-column posters, you may need to tweak these values. // See ./examples/example_2_column_18_24.typ for an example. // Any keywords or index terms that you want to highlight at the beginning. keywords: (), // Number of columns in the poster. num_columns: "1", // University logo's scale (in %). univ_logo_scale: "100", // University logo's column size (in in). univ_logo_column_size: "4", // Title and authors' column size (in in). title_column_size: "20", // Poster title's font size (in pt). title_font_size: "68", // Authors' font size (in pt). authors_font_size: "40", // Footer's URL and email font size (in pt). footer_url_font_size: "30", // Footer's text font size (in pt). footer_text_font_size: "40", body ) = { // configure page display to match unibasel poster size // portrait mode, A0 set page( paper: "a0", columns: 1, margin: ( top: 5in, left: 1.8in, right: 1.8in, bottom: 2in), header: align(center, rect(fill: rgb(165, 215, 210), width: 120%, height: 100%, grid(rows: 1, columns: (7%, 20%, 50%, 19%), fill: rgb(165, 215, 210), grid.cell( align: right + horizon, colspan: 2, inset: 30pt, image("./logos/logo-unibas-left-en.png") ), grid.cell( align: right + horizon, colspan: 2, inset: 30pt, image("./logos/logo-ins-right.png", width: 25%) ) ) ) ), header-ascent: 10%, footer: align(center, rect(fill: none, // rgb(210, 5, 55), width: 120%, height: 100%, stroke: none, inset: 30pt)[ #text(footer_email_ids) ] ), footer-descent: 20%, ) // configure text sizes and numbering according to University of Basel // styleguide set text(font: "Arial", size: 44pt) set heading(numbering: none) show heading.where(level: 1): set text(size: 54pt, weight: "bold") show heading.where(level: 2): set text(size: 50pt, weight: "bold") show heading.where(level: 3): set text(size: 46pt, weight: "bold") align(center, block(width: 100%, inset: 20pt, fill: none, ( text(title + "\n", size: 72pt, font: "Georgia", weight: "bold") + text(subtitle + "\n", size: 64pt, font: "Georgia", weight: "bold") + text(authors, size: 54pt, font: "Georgia") + text("\n(" + departments + ")", size: 38pt, font: "Georgia") ) ) ) // Display the poster's contents. body }
https://github.com/TheOnlyMrCat/tree-sitter-typst
https://raw.githubusercontent.com/TheOnlyMrCat/tree-sitter-typst/master/test/corpus/markup.typ
typst
Apache License 2.0
============ Basic markup ============ Lorem ipsum dolor sit amet _yes I'm typing this out instead of using the builtin function_, consecteur adispicing elit \ *And now some bold text after a linebreak*. // This is a comment /* These are /* nested */ block comments */ `Inline raw text` also works. --- (source_file (content_inner (em_content) (special_punct) (bold_content) (line_comment) (block_comment (block_comment)) (raw_content)))
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/literature-review/gherkin.typ
typst
#import "/components/glossary.typ": gls == Gherkin <sec-gherkin> Gherkin is a #gls("dsl") widely used in #gls("bdd") (@sec-bdd) to describe software requirements in a human-readable format. This section explores the key features, benefits, and challenges of using Gherkin, focusing on its applications in defining requirements and facilitating user acceptance testing. Gherkin is a valuable tool for defining requirements and facilitating user acceptance testing in BDD projects. Its human-readable format, collaboration benefits, and testability make it a popular choice among development teams. By effectively leveraging Gherkin, organizations can improve the quality and efficiency of their software development processes @bib-gherkin. === Key Features of Gherkin - *Domain-Specific Language*: Gherkin uses plain English keywords (`Given`, `When`, `Then`) to define scenarios and their expected outcomes. - *Scenario-Based Approach*: Gherkin emphasizes a scenario-based approach, focusing on the behavior of the system from the user's perspective. - *Collaboration*: Gherkin fosters collaboration between stakeholders by providing a shared language for discussing requirements. - *Testability*: The structured format of Gherkin makes it well-suited for automated testing, enabling continuous verification of system behavior. === Benefits of Using Gherkin - *Improved Communication*: Gherkin provides a common language for stakeholders, including business analysts, developers, and testers, to discuss and understand requirements. - *Enhanced Collaboration*: By focusing on the system's behavior, Gherkin promotes collaboration between technical and non-technical team members. - *Early Validation*: Gherkin-based tests can be executed early in the development process, ensuring that the system meets the specified requirements. - *Living Documentation*: Gherkin scenarios can serve as living documentation, providing a clear and up-to-date record of the system's intended behavior. === Gherkin in Practice Gherkin has been successfully adopted in various development methodologies and projects, including Agile, DevOps, and #gls("tdd") (@sec-tdd). It is commonly used to: - Define user stories and acceptance criteria. - Create executable specifications for automated testing. - Facilitate communication between stakeholders. - Improve the overall quality and reliability of software systems.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/003%20-%20Gatecrash/003_The%20Absolution%20of%20the%20Guildpact.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "The Absolution of the Guildpact", set_name: "Gatecrash", story_date: datetime(day: 16, month: 01, year: 2013), author: "<NAME>", doc ) <NAME> leaned back in his chair and rubbed the white stubble of his chin while he watched the crowd file in and the people take their places in front of the stage. Gorev was grizzled in every sense of the word—his face, his clothing, his demeanor. He had been a Wojek, and even though he was many years into his retirement, he would tell you he was #emph[still] a Wojek. No one knew exactly how old Gorev was, as Boros magic could sustain a Wojek's life far beyond the average person. In spite of his age, gray hair, and weathered features, Gorev still looked like he could wrestle a drunken ogre out of a bar or knock out a Rakdos spiker. His wrists were as thick as most men's calves and his arms were covered in scars. He had a face that looked like you could hit it with a wooden plank and not leave a mark... well, at least not a new mark. Besides, Gorev's face had been hit by things #emph[much] harder than a plank. #figure(image("003_The Absolution of the Guildpact/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Next to Gorev sat his nephew, <NAME>ya, a newly minted Wojek fresh from the academy, clean shaven and always at attention. His uniform was a wrinkle-free masterpiece with everything that could gleam in the sunlight polished to a high-gloss—boots, buttons, brass. A smart fellow, Pel worked hard to get into the Wojek corps and become an exemplary investigator. He was recently assigned a partner and began his beat across the Tenth District. Pel recounted every incident, from a tipped apple cart to a drunken brawl, to his uncle Gorev, with youthful enthusiasm, hoping for a nod of approval, some sage advice, or a story from the old days. It was the anniversary of the end of the #emph[Guildpact] , the magical contract between the ten guilds of Ravnica that held for over 10,000 years. The play presented a condensed version of the events that led to the end of the #emph[Guildpact] . Gorev remembered those days well. The play started with a scene showing the hero, <NAME>, striding across the stage to a roar of cheers and applause. Then the scenery shifted, using a bit of magic and some good set design, simulating rooftops and scenes of murders for Agrus to investigate. The audience was drawn in to how Agrus Kos began to solve the mystery that led to such tumultuous events. #figure(image("003_The Absolution of the Guildpact/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) After a while, Pel leaned over to his uncle. "How did the guilds operate back then? What was it like under the #emph[Guildpact] ?" "Ravnica was a lot different back then. The guilds ruled. What they said was law and everyone knew it. If you lived in a district under a guild's protection you followed its rules. If you were unguilded, like my folks, you lived on the outskirts of the districts carving out a living as best you could. But most Ravnicans were eager to join one. Most wanted structure, protection, and a sense of belonging. That's why I joined the Wojeks. I liked what the Boros stood for back then." Gorev leaned back. His physical eyes watched the play, but inwardly Gorev relived a memory of the Boros of old, the days of Razia and the angels of Sunhome. Legions of Wojeks, swiftblades, and skyknights assembled within the massive hall, gleaming steel reflecting the sun, presenting their undying loyalty to their angelic leader—their parun. Gorev was one of them, beholding his angelic commander, bathing in her fierce, sublime gaze. #figure(image("003_The Absolution of the Guildpact/03.jpg", width: 100%), caption: [Razia, Boros Archangel | Art by Donato Giancola], supplement: none, numbering: none) "What did the Boros stand for back then?" The question pulled Gorev out of the memory. After a pause, Gorev said, "They stood for the #emph[Guildpact] . They stood for 10,000 years of order on Ravnica." They watched the play for some time, but what Gorev said stayed in Pel's mind. Pel had heard the tales told late at night around the hearth. Friends of his father's would stay late and talk about the old times and, at the odd family gathering, Pel would often overhear two elderly relatives talking about the legends of the death of Razia, the destruction of Prahv, or the shattering of the #emph[Guildpact] . But his uncle, who was a Boros and a Wojek, never talked of the matter as long as Pel could remember. On the stage, Agrus Kos faced Szadek, the former guildmaster of the Dimir. The audience began to boo and hiss at the vampire. The actor hissed back at the audience. This got a chuckle and some more boos from the crowd. Gorev leaned over to Pel again. "That's why the Boros are more important now than ever before. Now there is no #emph[Guildpact] to uphold the law and stop creatures like him from gaining power. I don't care what the face of the Dimir is now, they are always going to be causing trouble. You have to follow the subtle leads, you have to think differently and make sure you study magic that is off the books and manuals. That's where the deeper layers of the Dimir are—off the books." #figure(image("003_The Absolution of the Guildpact/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Pel nodded. The Boros manuals about the Dimir were thorough, but the feeling at the academy was that the information was always outdated. They always felt three steps behind, or just plain lost in the woods. The play reached its climax but Gorev was focused on his nephew. He looked at Pel with a sense of duty, a feeling of urgency. "Think of it, Pel. Szadek and that Azorius psychopath destroyed #emph[the law] . They destroyed everything that kept Ravnica in balance for 10,000 years. You grew up in the aftermath so you don't know any other way, but for us who lived in those times it felt like the end of the world... hell, it was the end of the world. I'm amazed that the guilds held together as well as they did." Gorev put his hand on Pel's shoulder. "It's up to you now. Your vigilance, your passion must outweigh their desire to destroy and control. That's why this play is a tragedy—it's not a triumph of Kos and the Boros over Szadek and Augustin—it's a tragedy. It is the destruction of the greatest creation ever put on paper. The greatest spell ever cast." Gorev's words trailed off but his eyes gave the final message. Pel knew the real fight for Ravnica lay strewn throughout the Undercity, where the Dimir lay out of sight, pulling their invisible puppet strings to organize their next attack. He knew he had to get reassigned from topside duty to really strike at the root of Ravnica's problem. #emph[The Absolution of the Guildpact] may have just been a play, but for one Wojek in the audience it contained a message that would shape a life's work.
https://github.com/JarKz/math_analysis_with_typst
https://raw.githubusercontent.com/JarKz/math_analysis_with_typst/main/groups/second.typ
typst
MIT License
= Вторая группа вопросов 1. *Понятие первообразной функции, теорема об общем виде первообразных функций. Понятие неопределенного интеграла.* *Определение.* Фукнция $F(x)$ в данном промежутке называется _первообразной функцией_ для функции $f(x)$ или интегралом от $f(x)$, если во всем этом промежутке $f(x)$ является производной для функции $F(x)$ или, что то же, $f(x)d x$ служит для $F(x)$ дифференциалом $ F prime (x) = f(x) "или" d F(x) = f(x) d x. $ *Теорема.* Если в некотором (конечном или бесконечном, замкнутом или нет) промежутке $X$ функция $F(x)$ есть первообразная для функции $f(x)$, то и функция $F(x) + C$, где $C$ – любая постоянная, также будет первообразной. Обратно, _каждая_ функция, первообразная для $f(x)$ в промежутке $X$, может быть представлена в этой форме. В силу этого _выражение_ $F(x) + C$, где $C$ – произвольная постоянная, представляет собой _общий вид_ функции, которая имеет производную $f(x)$ или дифференциал $f(x) d x$. Это выражение называется *неопределённым интегралом* $f(x)$ и обозрачается символом $ integral f(x) d x, $ в котором неявным образом уже заключена произвольная постоянная. Произведение $f(x) d x$ называется *подинтегральным выражением*, а функция $f(x)$ – *подинтегральной функцией*. 2. *Основные свойства неопределенного интеграла.* 1. $d integral f(x) d x = f(x) d x,$ т.е. знаки $d$ и $integral$, когда помещен перед вторым, взаимно сокращаются. 2. Так как $F(x)$ есть первообразная функция для $F prime (x)$, то имеем $ integral F prime (x) d x = F(x) + C, $ что может быть переписано так: $ integral d F(x) = F(x) + C. $ Отсюда видим, что знаки $d$ и $integral$, стоящие перед $F(x)$, сокращаются и тогда, когда $d$ стоит после $integral$, но только к $F(x)$ нужно прибавить произвольную постоянную. 3. Если $a$ – постоянная ($a eq.not 0$), то $ integral a dot f(x) d x = a dot integral f(x) d x. $ 4. $integral [f(x) plus.minus g(x)] d x = integral f(x) d x plus.minus integral g(x) d x.$ 5. Если $ integral f(t) d t = F(t) + C, $ то $ integral f(a x + b) d x = 1/a dot F(a x + b) + C prime. $ 3. *Вычисление неопределенных интегралов с помощью замены переменной.* *Замечание.* Если известно, что $ integral g(t) d t = G(t) + C, $ то тогда $ integral g(omega(x)) omega prime (x) d x = G(omega(x)) + C, $ где $t = omega(x)$ и $d t = omega prime (x) d x$. 4. *вычисление неопределенных интегралов с помощью интегрирования по частям.* Пусть $u = f(x)$ и $v = g(x)$ будут две функции от $x$, имеющие непрерывные производные $u prime = f prime (x)$ и $v prime = g prime (x)$. Тогда, по правилу дифференцирования произведениея $d(u dot v) = u dot d v+ v dot d u$ или $u dot d v = d(u dot v) - v dot d u$. Для выражения $d(u dot v)$ первообразной, очевидно, будет $u dot v$; поэтому имеет место формула $ integral u dot d v = u dot v - integral v dot d u. $ Эта формула выражает _правило интегрирования по частям_. Она приводит интегрирование выражения $u dot d v = u dot v prime d x$ к интегрированию выражения $v dot d u = v dot u prime d x$. 5. *Интегрирование целой рациональной функции и простейших рациональных дробей.* Всего 4 типа простых дробей: 1. $A/(x - a)$, 2. $limits(A/(x - a)^k)_(k=2,3,...)$, 3. $(M x + N)/(x^2 + p x + q)$, 4. $limits((M x + N)/(x^2 + p x + q)^m)_(m=2,3,...)$, где $A, M, N, a, p, q$ – вещественные числа; кроме того, по отношению к дробям вида 3 и 4 предполагается, что трехчлен $x^2 + p x + q$ не имеет вещественных корней, так что $ (p^2)/4 - q < 0 "или" q - (p^2)/4 > 0. $ Дроби вида 1 и 2 интегрируются подобным образом: $ A integral (d x)/(x - a) = A ln|x - a| + C, $ $ A integral (d x)/(x - a)^k = - A/(k - 1) 1/(x - a)^(k - 1) + C. $ #align(alignment.center, strong(text("Дальше чисто математический текст, поймут лишь немногие. Если сложно – пропускайте."))) #line(length: 100%) Что же касается дробей вида 3 и 4, то их интегрирование облегчается следующей подстановкой. Выделим из выражения $x^2 + p x + q$ полный квадрат двучлена $ x^2 + p x + q = x^2 + 2 dot p/2 dot x + (p/2)^2 + [q - (p/2)^2] = (x + p/2)^2 + (q - (p^2)/4). $ Последнее выражение в скобках, по предположению, есть число положительное, его можно положить равным $a^2$, если взять $ a = +sqrt(q - (p^2)/4). $ Теперь прибегнем к подстановке $ x + p/2 = t, d x = d t, $ $ x^2 + p x + q = t^2 + a^2, M x + N = M t + (n - (M p)/2). $ В случае 3 будем иметь $ integral (M x + N)/(x^2 + p x + q) d x = integral (M t + (n - (M p)/2))/(t^2 - a^2) d t = M/2 integral (2t d t)/(t^2 + a^2) + (N - (M p)/2) integral (d t)/(t^2 + a^2) = $ $ M/2 ln(t^2 + a^2) + 1/a (N - (M p)/2) "arctg" t/a + C, $ или, возвращаясь к $x$ и подставляя вместо $a$ его значение: $ integral (M x + N)/(x^2 + p x + q) d x = M/2 ln(x^2 + p x + q) + (2N - M p)/sqrt(4q - p^2) "arctg" (2x + p)/sqrt(4q - p^2) + C. $ Для случая 4 та же подстановка даст $ integral (M x + n)/(x^2 + p x + q)^m d x = integral (M t + (N - (M p)/2))/(t^2 + a^2)^m d t = M/2 integral (2 t d t)/(t^2 + a^2)^m + (N - (M p)/2) integral (d t)/(t^2 + a^2)^m. $ Первый из интегралов справа легко вычисляется подстановкой $t^2 + a^2 = u, 2 t d t = d u$ $ integral (2 t d t)/(t^2 + a^2)^m = integral (d u)/u^m = - 1/(m - 1) 1/u^(m - 1) + C = - 1/(m - 1) 1/(t^2 + a^2)^(m - 1) + C. $ Второй же из интегралов справа; при любом $m$, может быть вычислен по рекуррентной формуле. Затем останется лишь положить в результате $t = (2x + p)/2$, чтобы вернуться к переменной $x$. #line(length: 100%) 6. *Представление правильной рациональной дроби в виде суммы простейших рациональных дробей. Метод неопределенных коэффициентов.* Каждая правильная дробь $ P(x)/(Q(x)) $ может быть представлена в виде суммы конечного числа простых дробей. #align(alignment.center, strong(text("Предположения"))) #line(length: 100%) 1. Рассмотрим какой-нибудь линейный множитель $x - a$, входящий в разложение знаменателя с показателем $k >= 1$, так что $ Q(x) = (x - a)^k Q_1 (x), $ где многочлен $Q_1$ уже на $x - a$ не делится. Тогда _данная правильная дробь_ $ P(x)/(Q(x)) = (P(x))/((x - a)^k Q_1 (x)) $ _может быть представлена в виде суммы правильных дробей_ $ A/(x - a)^k + (P_1(x))/((x - a)^(k - 1) Q_1(x)), $ из которых первая является *простой*, а знаменатель второй содержит множитель $x - a$ в более низкой степени чем раньше. 2. Пусть теперь $x^2 + p x + q$ будет какой-нибудь из квадратичных мноижтелей, входящих в разложение знаменателя с показателем $m >= 1$, так что на этот раз можно положить $ Q(x) = (x^2 + p x + q)^m Q_1(x), $ где многочлен $Q_1$ на трехчлен $x^2 + p x + q$ не делится. Тогда _данная правильная дробь_ $ (P(x))/(Q(x)) = (P(x))/((x^2 + p x + q)^m Q_1(x)), $ _может быть представлена в виде суммы правильных дробей_ $ (M x + N)/(x^2 + p x + q)^m + (P_1(x))/((x^2 + p x + q)^(m - 1) Q_1(x)), $ из которых первая уже будет *простой*, а вторая содержит в знаменателе упомянутый трехчлен снова – в низшей степени. #line(length: 100%) *Метод неопределенных коэффициентов.* Зная _форму_ разложения дроби $P/Q$, пишут его с _буквенными коэффициентами_ в числителях справа. Общим знаменателем всех простых дробей, очевидно, будет $Q$; складывая их, получим правильную дробь. Если отбросить теперь слева и справа знаенатель $Q$, то придем к равенству двух многочленов $(n - 1)$-й степени, тождественному относительно $x$. Коэффициентами при различных степенях многочлена справа будут линейные однородные многочлены относительно $n$ коэффициентов, обозначенных буквами; приравнивая их соответствующим численным коэффициентам многочлена $P$, получим, наконец, систему $n$ линейных уравнений, из которых буквенные коэффициенты и определятся. Ввиду того, что упомянутая система никогда не может оказаться *противоречивой*. Пример: Пусть дана дробь $(2x^2 + 2 x + 13)/((x - 2)(x^2 + 1)^2)$. Согласно общей теореме, для нее имеется разложение $ (2x^2 + 2 x + 13)/((x - 2)(x^2 + 1)^2) = A/(x - 2) + (B x + C)/(x^2 + 1) + (D x + E)/(x^2 + 1)^2. $ Коэффициенты $A, B, C, D$ определим, исходя из тождества $ 2x^2 + 2x + 13 = A(x^2 + 1)^2 + (B x + C)(x^2 + 1)(x - 2) + (D x + E)(x - 2). $ Приравнивая коэффициенты при одинаковых степенях $x$ слева и справа, придем к системе из пяти уравнений $ cases() $ 7. *Теорема об интегрировании рациональных функций.* 8. *Вычисление интегралов типа $integral R(x, root(n, (a*x + b)/(c*x + d)) d x$.* 9. *Вычисление интегралов типа $integral R(x, root(n, a x^2 + b x + c) d x$.* 10. *Вычисление интегралов типа $integral R(x, sin(x), cos(x)) d x$.* 11. *Интегрирование биномиальных дифференциалов.* 12. *Задачи геометрии и физики, приводящие к понятию определенного интеграла.* 13. *Понятие определенного интеграла. Необходимое условие интегрируемости.* 14. *Суммы Дарбу и их свойства.* 15. *Критерий существования интеграла Римана.* 16. *Некоторые классы интегрируемых функций.* 17. *Интегрируемость суммы, произведения интегрируемых функций, модуля и сужения интегрируемой функции.* 18. *Свойства линейности, аддитивности, ориентированности интеграла Римана.* 19. *Свойство монотонности интеграла. Первая теорема о "среднем".* 20. *Вторая теорема о "среднем".* 21. *Формула Ньютона – Лейбница. Существование первообразных.* 22. *Замена переменных в определенном интеграле.* 23. *Интегрирование по частям в определенном интеграле.* 24. *Формула Тейлора с остаточным членом в форме определенного интеграла.* 25. *Вычисление площадей криволинейной трапеции и криволинейного сектора.* 26. *Вычисление объёмов некоторых тел.* 27. *Длина дуги кривой.* 28. *Площадь поверхности вращения.*
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/unterrichtsplanung/methoden.typ
typst
Other
#import "/src/template.typ": * == #ix("Methoden", "Methode", "Unterrichtsmethode") #def("Methode")[ "#ix("Unterrichtsmethoden", "Methode", "Unterrichtsmethode") sind die Formen und Verfahren, mit deren Hilfe sich Lehrer und Schüler die sie umgebende natürliche und gesellschaftliche Wirklichkeit unter dem institutionellen Rahmenbedingungen der Schule aneignen.“#en[@Meyer2007_Unterrichtsvorbereitung[S. 44]] ] #ix("Methode", "Unterrichtsmethode") und #ix("Sozialformen", "Sozialform") sind voneinander abzugrenzen. Die #ix("Methoden", "Methode", "Unterrichtsmethode") des Unterrichts können bestimmte #ix("Sozialformen", "Sozialform") voraussetzen, allein mit #ix("Sozialform") kann jedoch keine inhaltliche Auseinandersetzung stattfinden. Ein Inhalt kann nur #ix("methodisch", "Methode", "Unterrichtsmethode") erarbeitet werden. Während #ix("Sozialformen", "Sozialform") also den sozialen Aspekt -- wer arbeitet, die "soziale Instanz" -- besprechen, besprechen #ix("Methoden", "Methode") die Form der Erarbeitung, die die soziale Instanz ausführt. Methoden bilden also das "Wie?" des Unterrichts und finden auf drei verschiedenen Ebenen statt:#en[Vgl. @Meyer2007_Unterrichtsvorbereitung[S. 45 ff]] #grid(column-gutter: 2em, row-gutter: 1em, columns: 3, strong[Makroebene], strong[Mesoebene], strong[Mikroebene], [ In der Makroebene der Methoden wird die grundlegende Art und Weise des Unterrichts festgelegt. Sie können sich über mehrere Unterrichtsstunden und Unterrichtseinheiten erstrecken. Darunter können zum Beispiel folgende Formen fallen: - gemeinsamer Unterricht - Freiarbeit - Lehrgänge - Projektarbeit - Marktplatzarbeit ], [ Zu der Mesoebene gehören Methoden, die zu den "historisch gewachsene[n] feste[n] Formen methodischen Handelns"#en[@Meyer2007_Unterrichtsvorbereitung[S. 46]] gehören. Sie werden durch ihre Sozial-, Handlungs-, Zeit- und Raumdimension charakterisiert. Darunter fallen z.B. folgende philosophische Methoden: - Schaubild - Dilemmadiskussion - Gedankenexperiment - Inquiry ], [ Unter "Mikromethodik" versteht man die Inszenierungstechniken des Unterrichts und #ix("Operatoren", "Operator"). Sie bilden kleinste Verhaltensweisen und Strukturen des Unterrichts. Darunter fallen: - Blickkontakt - Antworten - Fragen - Vormachen, Zeigen ]) Die philosophischen Makromethoden, mit denen philosophiert wird, können dabei nach #ix("Rohbeck", "<NAME>") und #ix("Martens", "<NAME>") in je unterschiedliche Kategorien eingeteilt werden. Einiges überschneidet sich, in beiden Einteilungen kommen die Phänomenologie, Hermeneutik, Dialektik und Analytik als eigene #ix("Kategorie", "Kategorien, sokratisch-aristotelisch") bzw. #ix("Denkrichtung", "Denkstil", "Denkrichtung") vor. #ix("Martens", "<NAME>") hat im Gegensatz zu #ix("Rohbeck", "<NAME>") noch die Spekulation, Rohbeck im Gegensatz zu Martens den #ix("Konstruktivismus") und die #ix("Dekonstruktion"). #table(columns: (50% - 1em, 50% - 1em), stroke: none, column-gutter: 2em, [*#ix("sokratisch-aristotelische Kategorien", "Kategorien, sokratisch-aristotelisch")*\ nach #ix("Martens", "<NAME>")] + ens[Vgl. @Martens2003_MethodenPU[S. 48-58]][Vgl. @Steenblock2002_EPhiD[S. 134-136]][Vgl. @Runtenberg2016_EPhiD[S. 79 f]], [*#ix("Denkrichtungen", "Denkrichtung", "Denkstil")*\ nach #ix("Rohbeck", "<NAME>")] + ens[Vgl. @Rohbeck2008_EPhiD[S. 77-88]][Vgl. @Steenblock2002_EPhiD[S. 133 f]][Vgl. @Runtenberg2016_EPhiD[S. 77 f]], [ + _phänomenologische Methoden:_ differenzierte und umfassende Beschreibung der eigenen Wahrnehmung + _hermeneutische Methoden:_ bewusst machen des eigenen Vorverständnis und sammeln anderer Deutungsmuster + _analytische Methoden:_ zentrale Argumente und Begriffe herausstellen und prüfen + _dialektische Methoden:_ in einem Dialog das Problem zu einem Dilemma machen und Pro und Contra beschreiben + _spekulative Methoden:_ Phantasien, neue Einfälle und Ideen spielerisch erproben #ix("Martens'", "<NAME>") sokratisch-aristotelische Kategorien richten sich auf die Philosophie als Dialog und im Bezug auf das Individuum. ], [ + analytische Philosophie + Konstruktivismus + Phänomenologie + Dialektik + Hermeneutik + Dekonstruktion #ix("Rohbecks", "Rohbeck, Johannes") #ix("Denkrichtungen", "Denkrichtung", "Denkstil") versuchen aus den Ansätzen der Arbeitsweisen der größten philosophischen Strömungen inhaltliche Richtungen für den Philosophieunterricht zu transformieren. Die Methoden der Philosophie werden damit durch *#ix("Transformation")* die Methoden des Philosophieunterrichts. ]) #def("Methodenvielfalt")[ #ix("Methodenvielfalt") ist der Reichtum an Inszinierungstechniken des Unterrichts. ] Für #ix("Methodenvielfalt"), also das Nutzen verschiedener Methoden, sprechen einige Gründe: 1. *philosophisch:* Die Philosophie ist #ix("heterogen", "Heterogenität der Philosophie"), d.h. vielfältig, sie selbst deckt viele Bereiche ab und macht sich verschiedene Methoden zu Nutze, daher sollte der Philosophieunterricht dementsprechend heterogen sein. 2. *pädagogisch:* Die SuS sind #ix("heterogen", "Heterogenität der SuS"), d.h. sie haben unterschiedliche Persönlichkeiten und Interessen. Verschiedene Methoden können unterschiedlich gut für verschiedene SuS funktionieren. 3. *didaktisch:* Zugriff auf die Philosophie → dafür sorgen, dass die SuS verschiedene Zugangsmöglichkeiten zur Philosophie haben, weil beide #ix("heterogen", "Heterogenität der SuS", "Heterogenität der Philosophie") sind. Es folgen einige Beispiele für Methoden des Philosophieunterrichts. #orange-list-with-body[*#ix("Gedankenexperiment")* #h(1fr) #ix("Partnerarbeit"), #ix("Frontalvortrag")][ In einem #ix("Gedankenexperiment") wird eine fiktive Situation angenommen und mit einer Fragestellung untersucht. 1. *Einbettung:* Die Grundannahmen des Gedankenexperiments werden dargelegt. 2. *Problematisierung/Fragestellung:* Es wird eine Fragestellung für die Situation entwickelt. 3. *Beantwortung der Fragestellung:* Das Experiment wird durchgeführt und die Fragestellung gemäß der gegebenen Prämissen beantwortet. #ix("<NAME>", "<NAME>") nimmt für das #ix("Gedankenexperiment") an, dass es auf drei #ix("didaktischen Niveaustufen", "Stufen, didaktisch") durchgeführt werden könne:#en[Vgl. @Engels2004_Gedankenexperiment[S. 186 ff]] 1. *Alles gegeben, Interpretation:* Das Gedankenexperiment wird von den SuS gelesen, interpretiert und kritisiert. Die Funktion des ausgewählten #ix("Gedankenexperiments", "Gedankenexperiment") soll klar werden und. Die These, die durch das #ix("Gedankenexperiment") vom Autor vertreten wird, soll kritisch geprüft werden. Sind die Mittel des #ix("Gedankenexperiments", "Gedankenexperiment") wirklich genug, um das zu zeigen, was der Autor zeigen will? 2. *Prämissen gegeben, selbständige Durchführung:* Ein #ix("Gedankenexperiment") wird selbständig mit gegebenen Prämissen duchgeführt. Es wird eine Situation vorgegeben, die SuS sollen anhand einer Aufgabenstellung eine Problemstellung in dieser Situation beantworten. 3. *Nichts gegeben, eigenes Gedankenexperiment:* Ohne vorhergehende Grundlegungen wird ein eigenes #ix("Gedankenexperiment") konstruiert, eine Problemstellung ausgesucht und der Versuch durchgeführt. ][*#ix("sokratisches Gespräch", "sokratisches Gespräch", "Gespräch, sokratisch")* #h(1fr) #ix("Frontalvortrag")][ Das sokratische Gespräch bezeichnet eine Methode, die mittels der #ix("Mäeutik")#en[Es handelt sich um die sogenannte "#ix("Hebammenkunst")".#todo[Kleine Erläuterung der Hebammenkunst.]] ein manipulatives Gespräch in einem öffentlichen Raum führt, um zu einem der folgenden drei Ergebnisse zu kommen: vollständige *Begriffsklärung*, Erlangen neuer *Erkenntnis* oder *#ix("Aporie")*. ][*#ix("neosokratisches Gespräch", "neosokratisches Gespräch", "Gespräch, neosokratisch")* #h(1fr) Gruppenarbeit #todo[Belege für das neosokratische Gespräch bei <NAME> fehlen.]][ #ix("<NAME>", "<NAME>") lehnt das #ix("neosokratische Gespräch", "Gespräch, neosokratisch", "neosokratisches Gespräch") an die ursprüngliche Methode des #ix("sokratischen Gesprächs", "Gespräch, sokratisch", "sokratisches Gespräch") an, im Gegensatz dazu soll sie jedoch nicht manipulativ und für die Teilnehmer gleichberechtigt sein. An einem Tag gibt ein Teilnehmer der Gesprächsgruppe ein Beispiel, worüber die Gruppe diskutieren soll. Es wird über den Tag verteilt so lange diskutiert, bis ein *gemeinsamer Konsens* gefunden wurde. Zusätzlich finden #ix("Meta-", "Metagespräch") und Strategiegespräche statt. ][*#ix("Inquiry")* #h(1fr) #ix("Gruppenarbeit")][ Neben dem #ix("neosokratischen Gespräch", "neosokratisches Gespräch", "Gespräch, neosokratisch") ist die Inquiry ebenfalls eine Gesprächsmethode für Gruppen. Ausgehend von einem gegebenen Stimulus wird gemeinsam eine Fragestellung erarbeitet, die dann zusammen in der Gruppe beantwortet wird. Im Gegensatz zum #ix("neosokratisches Gespräch", "neosokratisches Gespräch", "Gespräch, neosokratisch") muss *kein gemeinsamer Konsens* erreicht werden. Die Inquiry eignet sich ebenfalls für kurze Gespräche von 45 bis 90 Minuten. Die Inquiry besteht aus 7 Phasen:#en[Vgl. @Klager2011_Inquiry[S. 44 ff]] 1. *Geben des Stimulus:* Die Lehrkraft gibt einen Stimulus, der die SuS dazu anregen soll, ein philosophisches Problembewusstsein zu entwickeln. 2. *Stellen philosophischer Fragen:* Die SuS stellen philosophische Frage, deren Kriterien#en[Kriterien für erkenntnisleitende Fragen laut dem MÜK S. 2: offen und problematisch, präzise, beantwortbar, systematisch und verknüpft.] vorher festgelegt wurden. 3. *Sammeln der Fragen:* Die Lehrkraft sammelt die gestellten Fragen. 4. *Auswahl einer Frage:* Eine Frage wird für die folgende Diskussion ausgewählt, z.B. durch das Zufallsprinzip oder durch eine Mehrheitsabstimmung. 5. *Denkzeit:* Die SuS erhalten Denkzeit um sich schriftlich zur Frage zu Positionieren und eine erste Begründung anzuführen. 6. *Untersuchung:* Aus den SuS wird eine Antwort zufällig ausgewählt, die für alle sichtbar von der Lehrkraft festgehalten und dann Ausgangspunkt der Diskussion wird. Es wird so lange über die Antwort, ihre Gründe und Implikationen sowie die Bedeutung der darin vorkommenden Wörter diskutiert, bis ein gemeinsamer Konsens erreicht wurde oder alle SuS den Gründen für die Zustimmung oder Ablehnung der Antwort zustimmen können. 7. *Metagespräch und Evaluation:* Wird Schritt 6. beendet und keine neue Fragestellung ausgewählt, kommt es zu einem Metagespräch und einer Evaluation der Ergebnisse der Diskussion. Dazu bekommen die SuS wieder Denkzeit. Die Ergebnisse werden schriftlich festgehalten. ][*#ix("Diskussion")* #h(1fr) #ix("Gruppenarbeit"), #ix("Unterrichtsgespräch")][ ][*#ix("Standbild")* #h(1fr) #ix("Einzelarbeit"), #ix("Partnerarbeit"), #ix("Gruppenarbeit")][ ][*#ix("Collage")* #h(1fr) #ix("Einzelarbeit"), #ix("Partnerarbeit"), #ix("Gruppenarbeit")][ ][*#ix("kreatives Schreiben")* #h(1fr) #ix("Einzalarbeit")][ ][*#ix("Essay")* #h(1fr) #ix("Einzalarbeit")][ ][*#ix("Textarbeit")* #h(1fr) #ix("Einzalarbeit")][ Textarbeit kann auf verschiedene Arten angewandt verwden. Neben einfachem Lesen des Textes (mittels verschiedener Methoden wie *#ix("SQ3R")*) gibt es noch weitere Möglichkeiten, philosophische Texte zu bearbeiten. Die *#ix("produktionsorientierte Didaktik", "Didaktik, produktionsorientiert", "Produktionsorientierung")* bietet hier einen anderen Blick auf die Arbeit mit Texten:#en[Vgl. @Runtenberg2016_EPhiD[S. 48 ff.]] 1. ein Text ist ein handwerkliches Produkt 2. Lesende sind Koproduzenten, durch Lesen und Verstehen wird etwas Neues geschaffen 3. Textverstehen ist ein kreativer, d.h. eine Art von problemlösender, Prozess #ix("Produktionsorientiert-didaktiktische Pfade", "Didaktik, produktionsorientiert", "Produktionsorientierung") versetzen die SuS in die Rolle von Produzenten: zu einem bestimmten Medium (nicht nur für Text), soll etwas neues von den SuS hergestellt werden. Darunter fallen: - einen Text zu Ende schreiben - einen Gegentext verfassen - einen Text transformieren - einen freien Text zu einem Thema verfassen - ... Diese Verfahren sollen dabei in drei Schritten stattfinden: 1. das Produkt herstellen, 2. das Vor- und Gegenüberstellen in einer #ix("Lerngruppe") und 3. Rückbezug auf den Originaltext. Denkbare Methoden sind: + *Visualisierung von Texten:* Umschlagbilder/Cover zum Text werden erstellt, wichtige Textstellen werden als Bild illustriert. + *Rezeption eines modifizierten Textes:* Die Lehrkraft modifiziert (durch z.B. Auslassungen wichtiger Wörter/Sätze für die Argumentation) die Texte, was die SuS dazu bringt, zum Verständnis die Textvorlage intensiv lesen zu müssen. + *produktive Veränderung eines Originaltextes:* Der Originaltext wird von den SuS transformiert, etwa indem er für eine andere Zeit geschrieben wird, an einen speziellen Adressaten, der Stil verändert, eine aktualisierte oder Gegenfasstung geschrieben wird. ] #task(key: "methoden-martens")[Methoden nach Martens][ Nennen und erläutern Sie die fünf von Martens zusammengestellten Methoden des integrativen (sokratisch-aristotelischen) Methodenparadigmas. ][ - *phänomenologische Methode*: Die phänomenologische Methode steht für den Ausgangspunkt einer philosophischen Untersuchung beginnend von einer anschaulichen, sinnlichen Erfahrung oder einem erfahrenen Bruch in der Umwelt oder Gesellschaft. Wahrnehmungen werden umfassend und differenziert beschrieben. - *hermeneutische Methode*: Die vorherigen ins Spiel gebrachten Erfahrungen oder verschiedener Lehrmeinungen werden nun gedeutet, die genaue Vorstellung und Interpretation, wie diese zu verstehen sind, werden erforscht und offengelegt. - *analytische Methode*: Es kommt zu einer begrifflichen und argumentativen Differenzierung der ausformulierten Deutungen der unterschiedlichen Positionen. Sie werden untersucht und analysiert, Grundannahmen werden hervorgehoben und argumentativ abgewogen. Widersprüche werden aufgedeckt, Definitionen geprüft. - *dialektische Methode*: Die analysierten Positionen werden zugespitzt und Dialogangebote wahrgenommen, um Pro und Contra der Positionen hervorzuheben und zu diskutieren. - *spekulative Methode*: Die spekulative Methode ist das Einbeziehen von und das Arbeiten mit kreativen und spekulativen Einfällen und Hypothesen. ] #task(key: "martens-vs-rohbeck")[Methodengruppen nach Martens und Rohbeck][ Vergleichen Sie die fünf Methodengruppen von Martens (in Anlehnung an Aristoteles) mit den sechs Denkstilen von Rohbeck. ][ Martens orientiert sich an der philosophischen Vorgehensweise von Sokrates und Aristoteles, woraus die Methodenschlange entsteht. Rohbeck dagegen versucht die gängigen Strömungen der Philosophie in praktisch anwendbare Verfahren zu transformieren. Beide teilen sich hermeneutsische, phänomenologische, dialektische und analytische Ansätze. Im Gegensatz zu Martens bezieht Rohbeck jedoch auch Konstruktivismus und Dekonstruktion ein, während Martens die spekulative Methode verwendet. Rohbeck hat eine besondere Sichtweise auf die Zusammenhänge zwischen den einzelnen Methoden: Martens betrachtet diese getrennt, wenn auch kombinierbar, Rohbeck hingegen sieht einige von anderen abhängig bzw. eng miteinander verknüpft: analytische Philosophie und Konstruktivismus, da beide sich um eine möglichst eindeutige Sprache bemühen und Argumente betrachten; Hermeneutik und Dekonstruktion, da beide den Sinn eines Textes erst im Leser erzeugt sehen; Hermeneutik und Phänomenologie, da beide versuchen, Prozesse des Verstehens und Deutens transparent zu machen; und schließlich Dialektik und Phänomenologie, da beide versuchen, die scheinbaren Selbstverständlichkeiten des Lebens aufzudecken. ] #task[Märchen und Fabeln][ Notieren Sie Chancen und Grenzen des Philosophierens mit Märchen und Fabeln. ][ Märchen können als Motivation für den Einstieg in den Unterricht benutzt werden. Bei der Auseinadersetzung können sie als Auflockerung oder Veranschaulichung eines philosophischen Problems verwendet werden. Zum Abschluss eines Themas können Märchen benutzt werden, um auf eine kreative Art und Weise philosophieren zu üben. Unabhängig vom Zeitpunkt können sie als selbständige Texte mit Sichten aufspezielle philosophische Probleme benutzt werden. Es ist jedoch nicht zu vergessen, dass Märchen irrationale Geschichten sind und unrealistische Hoffnungen vermitteln können. Außerdem können Märchen grausam sein, was der Zielgruppe entsprechend berücksichtigt werden sollte. ] #task[Neosokratisches Gespräch vs. Inquiry][ Vergleichen Sie das Neosokratische Gespräch mit der Inquiry. ][ ] #todo[Lösungsvorschlag erstellen.]
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/texts.typ
typst
#import "/utilsMenlive.typ": * #let h_st = ( "Izvedí iz temnícy dúšu mojú, ispovídatisja ímeni tvojemú.", "Mené ždút právednicy, dóndeže vozdási mňi.", "Iz hlubiný vozvách k tebí Hóspodi, Hóspodi uslýši hlas moj.", "Da búdut úši tvojí vnémľušči hlásu molénija mojehó.", "Ašče bezzakónija nazriši Hóspodi, Hóspodi kto postojít, jáko u tebé očiščénije jesť.", "Imené rádi tvojehó poterpích ťa Hóspodi, poterpí dušá mojá vo slóvo tvojé, upová dušá mojá na Hóspoda.", "Ot stráži útrenija do nóšči, ot stráži útrénija da upovájet Isrájiľ na Hóspoda.", "Jáko u Hóspoda mílosť i mnóhoje u ného izbavlénije, i toj izbávit isrájiľa ot vsich bezzakónij jehó.", "Chvalíte Hóspoda vsi jazýcy, pochvalíte jehó vsi ľúdije.", "Jáko utverdísja mílosť jehó na nás, i ístina Hospódňa prebyvájet vo vík.", ) #let s_st = ( "-1": ( "Pomjanú ímja tvojé vo vsjákom róďi i róďi.", "Slýši dščí i vížď, i prikloní úcho tvojé.", "Licú tvojemú pomóľatsja bohátiji ľúdstiji.", ), "0": ( "Hospóď vocarísja, v ľipótu oblečésja.", "Íbo utverdí vselénnuju, jáže ne podvížitsja.", "Dómu tvojemú podobájet svjatýňa Hóspodi, v dolhotú dníj.", ), "6": ( "Blažéni, jáže izbrál i prijál jesí Hóspodi.", "Dúšy ích vo blahích vodvorjátsja.", "", ), "x": ( "K tebí vozvedóch óči mojí, živúščemu na nebesí. Sé jáko óči ráb v rukú hospódij svojích, jáko óči rabýni v rukú hospoží svojejá: táko óči náši ko Hóspodu Bóhu nášemu, dóndeže uščédrit ný.", "Pomíluj nás Hóspodi, pomíluj nás, jáko po mnóhu ispólnichomsja uničižénija: naipáče napólnisja dušá náša ponošénija hobzújuščich i uničižénija hórdych.", ) ) #let p_st = "Presvjatája Bohoródice spasí nás." #let n_st = "Presvjatája Tróice Bóže náš, sláva tebí." #let typs = ( "0": ( "Kanón voskrésnyj", "Kanón krestovoskresnyj", "Kanón presvjaťíj Bohoródici" ), "1": ( "Kanón umilíteľnyj", "Kanón bezplótnym" ), "2": ( "<NAME>", "Kanón svjatómu velíkomu proróku Joánnu predtéči" ), "3": ( "Kanón čestnómu i životvorjáščemu krestú", "<NAME>" ), "4": ( "Kanón svjatým apóstolom", "Kanón vo svjatých otcú nášemu Nikoláju čudotvórcu" ), "5": ( "Kanón čéstnómu i životvorjáščemu krestú", "<NAME>" ), "6": ( "Kanón svjatým múčenikom, i svjatítelem, i prepodóbnym i usópšym", "Kanón usópšym" ) ) #let pripivy = ( "0": ( ("Sláva Hóspodi svjatómu voskreséniju tvojemú."), ("Sláva Hóspodi krestú tvojemú i voskreséniju."), // FIXME: chcek correct translation ("Presvjatája Bohoródice, spasi nás.") // FIXME: chcek correct translation ), "6": () ) #let sd_st = ( "Voskresní Hóspodi Bóže mój, da voznesétsja ruká tvojá, ne zabúdi ubóhich tvojích do koncá.", "Ispovímsja tebí Hóspodi vsím sérdcem mojím, povím vsjá čudesá tvojá.", ) #let ch_st = ( "Sotvoríti v ních súd napísan, sláva sijá búdet vsím prepodóbnym jehó.", "Chvalíte Bóha vo svjatých jehó, chvalíte jehó v utverždéniji síly jehó.", "Chvalíte jehó na sílach jehó, * chvalíte jehó po mnóžestvu velíčestvija jehó.", "Chvalíte jehó v hlási trúbňim, * chvalíte jehó v psaltíri i húsľich.", "Chvalíte jehó v tympáňi i líci, * chvalíte jehó v strúnach i orháňi.", "Chvalíte jehó v kymváľich dobrohlásnych, chvalíte jehó v kymváľich vosklicánija, * vsjákoje dychánije da chvalít Hóspoda.", "Voskresní Hóspodi Bóže mój, da voznesétsja ruká tvojá, ne zabúdi ubóhich tvojích do koncá.", "Ispovímsja tebí Hóspodi, vsím sérdcem mojím, povím vsjá čudesá tvojá.", ) #let su_st = ( "x": ( "Ispólnichomsja zaútra mílosti tvojejá Hóspodi, i vozrádovachomsja i vozveselíchomsja, vo vsjá dní náša vozveselíchomsja, za dní, v ňáže smiríl ný jesí, ľíta, v ňáže víďichom zlája: i prízri na rabý tvojá, i na ďilá tvojá, i nastávi sýny ích.", "I búdi svítlosť Hóspoda Bóha nášeho na nás, i ďilá rúk nášich isprávi na nás, i ďílo rúk nášich isprávi.", ), "6": ( "Blažéni, jáže izbrál i prijál jesí Hóspodi.", "Dúšy ích vo blahích vodvorjátsja.", "I pámjať ích v ród i ród.", ) ) #let b_st = ( "Blažéni níščiji Dúchom, jáko ťích jésť cárstvo nebésnoje.", "Blažéni pláčuščiji, jáko tíji uťíšatsja.", "Blažéni krótcyji, jáko tíji nasľíďat zémľu.", "Blaženi alčuščiji i žažduščiji pravdy, jako tiji nasyťatsja.", "Blaženi milostiviji, jako tiji pomilovani budut.", "Blažéni čístiji sérdcem, jáko tíji Bóha úzrjat.", "Blažéni mirotvórcy, jáko tíji Sýnove Bóžiji narekútsja.", "Blažéni izhnáni právdy rádi, jáko ťích jésť cárstvo nebésnoje.", "Blažéni jesté, jehdá ponósjat vám, i iždenút, i rekút vsják zól hlahól na vý lžúšče mené rádi.", "Rádujtesja i veselítesja, jáko mzdá váša mnóha na nebesích.", ) #let translation = ( "MINEA_OBS": "Minea obščaja", "M_BOHORODICKA": "Presvjatij Bohorodicy", "M_PROROK_JEDEN": "Proroku jedinomu", "M_APOSTOL_JEDEN": "Apostolu jedínomu", "HLAS": "Hlas", "Ne": "Neďiľa", "Po": "Poneďiľňik", "Ut": "Vtórnik", "Sr": "Sréda", "St": "Četvertók", "Pi": "Pjatók", "So": "Subbóta", "M": "Mala večérňa", "V": "Večérňa", "P": "Povečérije", "N": "Polúnóščnica", "U": "Utréňa", "L": "Litúrhija", "I": "Izobrazíteľnaja", "So_V": "v subbótu véčera", "So_N": "v subbótu nóšči", "Ne_V": "v neďíľu véčera", "Ne_N": "v neďíľu nóšči", "Po_V": "v poneďíľnik véčera", "Po_N": "v poneďíľnik nóšči", "Ut_V": "vo vtórnik véčera", "Ut_N": "vo vtórnik nóšči", "Sr_V": "v srédu véčera", "Sr_N": "v srédu nóšči", "St_V": "v četvertók véčera", "St_N": "v četvertók nóšči", "Pi_V": "v pjatók véčera", "Pi_N": "v pjatók nóšči", "HOSPODI_VOZVACH": "Hóspodi vozzvách", "STICHOVNI": "Stichíry na stichovňi", "TROPAR": "Tropár", "PIESEN": "Písň", "SIDALEN": "Sidálen", "SIDALENY": "Sidálny", "SIDALEN_PO": "Po stichoslóviji", "YPAKOJ": "Ipakoí", "STEPENNY": "Stepénny", "ANTIFON": "Antifón", "PROKIMEN": "Prokímen", "STICH": "Stích", "ALLILUJA": "Allilúia", "KANON": "Kanón", "KONDAK_IKOS": "Kondák i Ikos", "CHVALITE": "Stichíry na chvalítech", "BLAZENNA": "Blažénna", "TROPAR_KONDAK": "Tropár i Kondák", "HV_MINEA": "Taže stichiry Svjataho 3 iz Minei ili iz Obščiny.", "HV_NOTE": "Sláva: Svjatomu ili Prazdniku, I nýňi: Bohorodičen, ašče nebudet Sláva: I nýňi: Bohorodičen", "HV_N_NOTE": "Bohorodičen po Ústavu", "T_NOTE": "Sláva: Svjatomu; I nýňi: Bohorodičen voskresen" )
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/whats-font.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ## What is a font? == 字体是什么? // From a computer's perspective, a font is a database. It's a related collection of *tables* - lists of information. Some of the information is global, in the sense that it refers to the font as a whole, and some of the information refers to individual glyphs within the font. A simplified schematic representation of a font file would look like this: 从计算机的视角来看,字体就是一个由一系列互相关联的*数据表*组成的数据库。这些数据表中分别储存着各种各样的信息。其中有些信息是全局性的,也就是负责描述这个字体的整体情况;另外一些信息则可能是关于字体中的某个特定#tr[glyph]的。字体内部组织结构的简化版示意图如下: #figure( placement: none, caption: [字体内部的组织结构], kind: image, )[#include "schemtic.typ"] // In other words, most of the information in a font is not the little black shapes that you look at; they're *easy*. The computer is much more concerned with details about how the font is formatted, the glyphs that it supports, the heights, widths and sidebearings of those glyphs, how to lay them out relative to other glyphs, and what clever things in terms of kerns, ligatures and so on need to be applied. Each of these pieces of information is stored inside a table, which is laid out in a binary (non-human-readable) representation inside your OTF file. 换句话说,字体中除了用于显示的那些黑色图形之外还有大量其他信息。图形#tr[outline]信息处理起来其实非常简单,计算机其实更关心那些控制这些图形如何正确显示的其他信息。比如,字体支持哪些#tr[glyph],它们有多高,多宽,左右#tr[sidebearing]是多少,在显示多个#tr[glyph]时应该如何关联它们,在#tr[kern]方面需要有哪些智能处理,#tr[ligature]和其他高级特性应该如何应用等等。所有这些零碎信息都储存在数据表中,最终被组织为一个(人类不可读的)二进制格式,也就是你看到的 OTF 文件。
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/02-concepts/dimension/dim-1.typ
typst
Other
#import "/lib/draw.typ": * #import "/lib/glossary.typ": tr #import "/template/lang.typ": armenian #let start = (0, 0) #let end = (300, 200) #let base = (125, 75) #let up = 125 #let down = 45 #let width = 136 #let line-color = gray.darken(30%) #let lt = (base.at(0), base.at(1) + up) #let rb = (base.at(0) + width, base.at(1) - down) #let graph = with-unit((ux, uy) => { // mesh(start, end, (50, 50), stroke: 1 * ux + gray) rect( lt, end: rb, stroke: 1.4 * ux + line-color, ) let line-stroke = 1 * ux + line-color segment( (0, base.at(1)), (end.at(0), base.at(1)), stroke: line-stroke, ) point(base, radius: 3.5) txt([#tr[baseline]], (0, base.at(1)), size: 12 * ux, anchor: "lb", dy: 2) let arrow-y = base.at(1) - down - 15 let arrow-length = 40 arrow( (base.at(0) + width - arrow-length, arrow-y), (base.at(0) + width, arrow-y), stroke: line-stroke, head-scale: 3, ) arrow( (base.at(0) + arrow-length, arrow-y), (base.at(0), arrow-y), stroke: line-stroke, head-scale: 3, ) txt(tr[horizontal advance], (base.at(0) + width / 2, arrow-y), size: 12 * ux) txt(armenian[խ], base, size: 150 * ux, anchor: "lb", dx: 2) }) #canvas(end, start: start, width: 55%, graph)
https://github.com/Origami404/kaoyan-shuxueyi
https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/微积分/05-中值定理.typ
typst
#import "../template.typ": sectionline, gray_table, colored #let dx = $dif x$ = 中值定理 #set list(marker: ([★], [⤥], [›])) == 定理本体 - 普通定理 - 最值定理: 闭连, 闭区间内必有最值 - 介值定理: 闭连, 闭区间内必能取到最值之间的任意一个值 - 零点存在: 闭连, $f(a) f(b) < 0$, 零点存在 - 微分中值 - 费马: 极值点 $and$ 可导 $==>$ $f'(x_0) = 0$ - *罗尔*: 闭连开导, $f(a) = f(b) ==> exists xi in (a, b): f'(xi) = 0$ - *拉中*: 闭连开导, $exists xi in (a, b): (f(a) - f(b)) / (a - b) = f'(xi)$ - *柯西*: 闭连开导, $exists xi in (a, b): (f(a) - f(b)) / (g(a) - g(b)) = (f'(xi)) / (g'(xi))$ - 积分中值 - 普通形式: 闭连, $exists xi in [a, b]: integral^b_a f(x) dx = f(xi)(b - a)$ - 加强形式: $xi$ 在开区间里, 需要先对变限函数用拉中证了才能用 - 二重形式: 闭区域 $D$ 内连续, 则存在 $(xi, eta) in D$ 使得 $integral.double_D f dif sigma = f(xi, eta) S$, $S$ 为 $D$ 的面积 - 证明 - 罗尔证明: 闭连 $->$ 有最值; $f(a) = f(b)$ $->$ 最值不在端点, 在区间内; 然后费马引理立得 - 拉中证明: 令 $h(x) = f(x) - (f(a) - f(b)) / (a - b)$, 然后对 $h$ 罗尔 - 柯西证明: 令 $h(x) = f(x) - (f(a) - f(b)) / (g(a) - g(b))$, 然后对 $h$ 罗尔 == 技巧 - 可用中值定理做的极限 - 在极限中很明显有两个同样形式的函数相减, 并且有个参数在变 - 比如 $arctan sqrt(n) - arctan sqrt(n + 1)$, 可以固定 $n$ 取函数 $h(x) = arctan sqrt(n + t)$ - 然后拉中取导数后代回原极限, 并把 $n$ 拉到极限处后忽略引入的 $xi$ 即可 - 待证明的式子比较复杂 - 尽可能尝试全部丢一边变成 $dots.c = 0$, 然后积分左边的式子观察原函数, 并对原函数用罗尔 - 常用观察技巧 - $f + xi f' -> x f(x)$ - $f + lambda f' -> e^(lambda x) f(x)$ - $f f' -> f^2(x)$ - 待证明的式子里有两个中值出来的东西 - 两个参数具有轮换对称性或要求不相同: 用*相同的函数, 不同的区间*做中值, 然后拼起来 - 若否: 把两个中值出来的东西丢两边, 用*不同的函数, 相同的区间*做中值, 然后拼起来 #pagebreak()
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_fisica/scambiatori_calore.typ
typst
#import "@preview/cetz:0.2.2": plot, canvas = Scambiatori di Calore <scambiatori-di-calore> == Temperatura Media Logaritmica <temperatura-media-logaritmica> === Caso Controcorrente e capacità termiche uguali ipotesi: - *Controcorrente* - $C_"caldo" = C_"freddo"$ $ Delta T_"ml" = Delta T_"ingresso" = Delta T_"uscita" $ === Tutti gli altri casi $ Delta T_"ml" = (Delta T_1 - Delta T_2) / ln((Delta T_1) / (Delta T_2)) $ dove: - $Delta T_1:$ differenza di temperatura tra le due linee da una parte del grafico. \ #h(13.5cm) (@scamb_graph) - $Delta T_2:$ differenza di temperatura tra le due linee dall'altra parte del grafico (@scamb_graph). #figure(image("/immagini/scamb_graph_temp.png", height: 6cm), caption: "Valido tranne nel caso di capacità termiche uguali per le due parti dello scambiatore." )<scamb_graph> == Potenza termica scambiata dal fluido freddo <potenza-terminca-scambiata-dal-fluido-freddo> *fluido freddo:* $ dot(Q) = dot(m) dot.op c_(p f) dot.op lr((T_(f u) - T_(f i))) \ \ C = dot(m) dot c_(p f) $ $f u$: fluido Freddo-Uscita\ $f i$: fluido Freddo-Ingresso\ $C:$ capacità termica\ \ *fluido caldo:* $ dot(Q) = dot(m) dot.op c_(p c) dot.op lr((T_(c u) - T_(c i))) $ $c u$: fluido Caldo-Uscita\ $c i$: fluido Caldo-Ingresso == Bilancio $ dot(Q)_"freddo" = - dot(Q)_"caldo" $ \*Nota: freddo e caldo sono riferiti ai liquidi delle due parti dello scambiatore. == Coefficiente globale di scambio <coefficiente-globale-di-scambio> $ U_(t o t) = frac(dot(Q), S dot Delta T_(m l)) med med med med lr([W / (m^2 K)]) $
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter3/intro.typ
typst
#import "../../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" #code( "tree src/raft", "Raft算法", ```zsh src/raft ├── log.rs # 定义了Raft中的Log ├── message.rs # 定义了Raft中Node之间交互的信息 ├── mod.rs ├── node.rs # 定义了Node(Leader, Follower, Candidate)以及其行为 ├── state.rs # 定义了Raft中的状态机 └── testscripts └── ... ```, ) == Raft介绍 Raft共识算法是一种分布式一致性算法,它的设计目标是提供一种易于理解的一致性算法。Raft算法分为三个部分:领导选举、日志复制和安全性。具体的实现可以参考Raft论文#footnote("Raft Paper:" + link("https://raft.github.io/raft.pdf")) #footnote("Raft Thesis:" + link("https://web.stanford.edu/~ouster/cgi-bin/papers/OngaroPhD.pdf")) #footnote("Raft 官网:" + link("https://raft.github.io"))。 Raft有三个特点: + 线性一致性(强一致性):一旦一个数据被Client提交,那么所有的Client都能读到这个数据。(就是永远看不到过时的数据) + 容错性:知道大多数节点在运行,就可以保证系统正常运行。 + 持久性:只要大多数节点在运行,那么写入就不会丢失。 Raft算法通过选举一个Leader来完成Client的请求以及将数据复制到其他节点。请求一旦被大多数节点所确认后就会执行。如果Leader挂了,那么会重新选举一个Leader。在一个集群中,需要至少有三个节点来保证系统的正常运行。 有一点需要说明,Raft并不提供水平扩展。当Client有一个请求时,只能由单一的Leader来处理,这个Leader很快就会称为系统的瓶颈。而且每一个节点会存储整个数据集完整的副本。 系统通常会将数据分片到多个Raft集群中,并在它们之间使用分布式事务协议来处理这个问题。不过与现在的这一章关系不大。 === Raft中日志与状态机 Raft维护了Client提交的任意写命令的有序Log。Raft通过将Log复制到大多数节点来达成共识。如果能共识成功,就认为Log是已经提交的,并且在提交之前的Log都是不可变的。 当Log已经提交以后,Raft就可以将Log中存储的命令应用到节点本地的状态机。每个Log中包含了index、term以及命令。 - index: Log的索引,表示这个entry在Log中的位置。 - term:当前entry被Leader创建的时候的任期。 - 命令:会被应用在状态机的命令。 注意,_通过index和term可以*确定*一个entry_。 #tbl("Log可视化")[ #show raw.where(block: false): it => { it } #table( columns: 3, stroke: none, table.hline(), table.header([Index], [Term], [Command(命令)]), table.hline(stroke: 0.5pt), [1], [1], [`None`], [2], [1], [`CREATE TABLE table (id INT PRIMARY KEY, value STRING)`], [3], [1], [`INSERT INTO table VALUES (1, "foo")`], [4], [2], [`None`], [5], [2], [`UPDATE table SET value = 'bar' WHERE id = 1`], [6], [2], [`DELETE FROM table WHERE id = 1`], table.hline(), ) ]<log_example> 状态机必须是确定的,只有这样,才能所有的节点达到相同的状态。Raft将会在所有节点上独立的,以相同的顺序应用相同的命令。但是如果命令具有非确定性行为(比如随机数生成、与外部通信),会产生分歧。 === Leader选举 在Raft中,每一个节点都处于三个身份中的一个: + Leader:处理所有的Client请求,以及将Log复制到其他节点。 + Follower:只是简单的响应Leader的请求。可能并不知道Leader是谁。 + Candidate:在想要选举Leader时,节点会变成Candidate。 Raft算法都依赖一个单一的保证:在任何时候都只能有一个有效的Leader(旧的、已经被替换掉的可能仍然认为自己是Leader,但是不起作用)。Raft通过领导者选举机制来强制保证这一点。 Raft将时间划分为term,term与时间一样,是一个严格单调递增的值。在一个term内只能有一个Leader,而且不会改变。每一个节点会存储当前已知的最后term。并且在节点直接发送信息的时候会附带当前term(如果收到大于当前term的会变成Follower,收到小于当前term的会忽略)。 可以把在Leader选举过程分成两个部分: + 谁想成为Leader + 如何给想成为Leader的Node投票 如果Follower在选举超时时间内没有收到Leader的心跳信息,会变成Candidate并且开始选举Leader。如果一个节点与Leader失联(可能是网络环境等原因),那么他会不断的自行选举,直到网络恢复。因为他不断的自行选举,他的term会变得非常大,一旦恢复以后会大于集群中的其他节点,此时会在其任期内进行选举,也就是扰乱了当前的领导者(本来集群正常运行,每一个突然收到了特别大的term信息的节点,都会变成Follower,然后整个集群被迫重新开始选举),为了解决这个问题,提出了PreVote(Raft+ 每个节点刚开始的时候都是Follower,并且都是不知道谁是Leader。如果收到来自当前或者更大term的Leader发来的信息,会变成知道Leader是谁的Follower。否则,在等待一段时间(根据定义的选举超时时间)后,会变成Candidate并且开始选举Leader。 Candidate会将自己的term号+1,并且向其他节点发送投票请求。收到请问投票的信息后,节点开始相应投票。每个节点只能投一次票,先到先得,并且有一个隐藏的语义是:Candidate会投给自己一票。 当Candidate收到大多数节点(>50%)的投票后,就会变成Leader。然后向其他节点发送心跳信息,以断言并且保持自己的Leader身份。所有节点在收到Leader的心跳信息后,会变成Follower(无论当时投票给了谁)。Leader还会定期发送心跳信息,以保持自己的Leader身份,新Leader还会一个空item,以便安全提前前面term的item(Raft paper 5.4.2)。 有成功就会有失败,可能因为平局或者多数节点失联,在选举超时时间内没有选出Leader。这时候会重新开始选举(term+1),直到选出Leader。 为了避免多次平局,Raft引入了随机化的选举超时时间。这样可以避免多个节点在同一时间内开始选举(Raft paper 5.2)。 如果Follower在选举超时时间内没有收到Leader的心跳信息,会变成Candidate并且开始选举Leader。如果一个节点与Leader失联(可能是网络环境等原因),那么他会不断的自行选举,直到网络恢复。因为他不断的自行选举,他的term会变得非常大,一旦恢复以后会大于集群中的其他节点,此时会在其任期内进行选举,也就是扰乱了当前的领导者(本来集群正常运行,每一个突然收到了特别大的term信息的节点,都会变成Follower,然后整个集群被迫重新开始选举),为了解决这个问题,提出了PreVote(Raft thesis 4.2.3)。不过这就属于Raft的优化问题了,会在我的另外一本书中讨论。 === 日志复制与共识 当Leader收到了来自Client的写请求的时候,会将这个请求追加到其本地的Log中,然后将这个请求发送给其他节点。其他节点会尝试将收到的item也追加到自己的Log中,并且向Leader发送相应信息。 一旦大多数节点确认了追加操作,Leader就会提交提交这个item,并且应用到本地状态机,然后将结果返回给Client。 然后在下一个心跳的时候,告诉其他节点这个item已经提交了,其他节点也会将这个item提交并且应用到本地状态机。关于这个的正确性不是必须的(因为其成为Leader,它们也会提交并且应用该item,否则也没必要应用它)。 Follower也有可能比不会应用这个item,可能因为落后于Leader、日志出现了分歧等(Raft paper 5.3节)等情况。 Leader发送给其他Node的Append中包含了item的index以及term,index+term(如@log_example 所示),如果两个item拥有相同的index+term,那么这两个item是相同的,并且之前的item也是相同的(Raft Paper 5.3)。 如果Follower收到了index+term不匹配的item,会拒绝这个item。当Leader收到了拒绝信息,会尝试找一个与Follower的日志相同的点,然后将这个点之后的item发送给Follower。这样可以保证Follower的日志与Leader的日志相同。 Leader会通过发送一个只包含index+term的信息来探测这一点,也就是逐个较小index来探测,直到Follower相应匹配。然后发送这个点之后的item(Raft paper 5.3)。 Leader的心跳信息也会包含last_index以及term,如果Follower的日志落后于Leader,会在给心跳的返回信息中说明,Leader会像上面一样发送日志。 === Client 的请求 Client会将请求提交给本地的Raft节点。但是就像上面提到的,它们仅仅在Leader上处理,所以Followers会将请求转发给Leader(Raft thesis 6.2)。 关于写请求,会被Leader追加到Log中,然后发送给其他节点。一旦大多数节点确认了这个请求,Leader就会提交这个请求,并且应用到本地状态机。一旦应用到状态机中,Leader会通过日志查找的写请求的结果,并且返回给Client。确定性的错误(外键违规)会返回给客户端,非确定性的错误(IO错位)会直接使节点崩溃(这样就可以避免副本状态产生分歧)。 关于读请求,仅在Leader上处理,不需要Raft的日志的复制。但是为了确保强一致性,Leader会在处理读请求的时候,会通过一次心跳来避免脏读(避免其他地方选举出来了新的Leader而导致的Leader身份失效)。一旦可以确认Leader的身份,Leader就会将读取结果返回给Client。
https://github.com/felsenhower/kbs-typst
https://raw.githubusercontent.com/felsenhower/kbs-typst/master/examples/08.typ
typst
MIT License
Typst ist einfacher @mädje22 und schneller @haug22 als LaTeX. #bibliography("bibliography.yml")
https://github.com/QuadnucYard/cpp-coursework-template
https://raw.githubusercontent.com/QuadnucYard/cpp-coursework-template/main/msgbox.typ
typst
#import "template.typ": codify #import "@preview/showybox:2.0.1": showybox #let __msgbox(body, title, code, frame) = { let content = showybox(frame: frame, title: strong(title), breakable: true, body) if code { codify(content) } else { content } } #let wrong-answer(body, title: "Typical wrong answers", code: true) = { __msgbox(body, title, code, ( border-color: red.darken(20%), title-color: red.lighten(10%), body-color: red.lighten(95%), footer-color: red.lighten(80%), )) } #let warning(body, title: "Warning", code: true) = { __msgbox(body, title, code, ( border-color: yellow.darken(20%), title-color: yellow.darken(10%), body-color: yellow.lighten(95%), footer-color: yellow.lighten(80%), )) } #let tip(code: true, title: "Tip", body) = { __msgbox(body, title, code, ( border-color: blue, title-color: blue.lighten(30%), body-color: blue.lighten(95%), footer-color: blue.lighten(80%), )) } #let info(code: true, title: "Info", body) = { __msgbox(body, title, code, ( border-color: gray, title-color: gray.lighten(30%), body-color: gray.lighten(95%), footer-color: gray.lighten(80%), )) } #let note(code: true, title: "Note", body) = { __msgbox(body, title, code, ( border-color: green, title-color: green.lighten(20%), body-color: green.lighten(95%), footer-color: green.lighten(80%), )) } #let study-case(first, second) = { let cnt = counter("study-case") cnt.step() block(width: 100%, fill: maroon.lighten(80%), inset: 8pt, radius: (top: 4pt), { strong([Case #cnt.display()]) h(1em) first }) block(width: 100%, fill: olive.lighten(80%), inset: 8pt, radius: (bottom: 4pt), above: 0pt, { strong([Analysis #cnt.display()]) h(1em) second }) }
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/组合数学/课后习题.typ
typst
#import "../../lib.typ": * = 课后习题 == 第1章:鸽巢原理<ch1> === $P_22,6.$ #showybox( title: [ 证明:从1,2,…,200 中任取100 个整数,其中之一小于16,那么必有两个数,一个能被另一个整除。 ])[ 首先,将整数1至200按照$1*2^n,3*2^n,5*2^n,…,197,199$的形式分成100个抽屉,从1到200中任取100个,其中有一数a小于16,假设没有两个构成整除关系,首先按抽屉原理,这100个数必须为每个抽屉中仅取且必取1个数,否则假设不成立,所以: - 当a为小于16的奇数时(比如15),显然有数与其构成整数关系(比如抽屉15*11=165)结论成立; - 当此数为$1*2^n$时,显然$n≤3$,考虑抽屉$3*2^(n_1),9*2^(n_2),27*2^(n_3),81*2^(n_4)$,显然若不存在整除关系,则$n_4 <n_3<n_2<n_1<3$,即四个数只能在0、1、2三个数中选择,此时产生矛盾,必存在两数整除关系; - 更一般的,当此数为非2的幂的偶数时,可写成$b*2^n$,b为奇数,且$1<b≤7,n≤2$,考虑抽屉$3b*2^(n_1),9b*2^(n_2),27b*2^(n_3)$(因$b≤7,27b<200$), $n_3<n_2<n_1<2$,即三个数只能在0、1两个数中选择,此时产生矛盾。 综上,假设不成立,必存在两数整除关系。 ] === $P_23,15.$ #showybox( breakable: true, title: [ 证明:从1,2,… ,2n 中任选n +1个整数,则其中必有两个数,它们的最大公因子 为 1 ] )[ 1. 构造配对 将集合${1,2,3,#sym.dots.h,2n}$中的数两两配对,形成n对: $ (1,2),(3,4),#sym.dots.h,(2n-1,2n) $ 每一对中的两个数都是连续的奇数和偶数。 2. 应用鸽巢原理 - 我们有 n 对,每对包含两个数。 - 任取n + 1个数,根据鸽巢原理,至少有一对中的两个数被选中。 3. 分析被选中的两数 - 设这对被选中的数为 $(2k - 1, 2k)$ ,其中 k 为正整数, $1 ≤ k ≤ n$ 。 - 这两个数是连续的奇数和偶数,即 2k - 1 和 2k 。 - 由于 2k - 1 是奇数, 2k 是偶数,它们的最大公因子为: $ gcd(2k - 1, 2k) = gcd(2k - 1, 2k - (2k - 1)) = gcd(2k - 1, 1) = 1 $ 因此,这两个数互质。 根据上述分析,无论从 $1, 2, ……, 2n$ 中选取哪 $n + 1$ 个数,必定存在至少一对连续的奇数和偶数,这对数的最大公因子为 1。因此,在所选的 $n + 1$ 个数中,必有两个数互质。 综上所述, 从集合 $1, 2, ……, 2n$ 中任取 n + 1 个整数,必存在两个数的最大公因子为 1。 ] === $P_23,26.$ #showybox( title: [ 证明:在任意给出的n+1(n≥2)个正整数中必有两个数,它们的差能被 n 整除. ] )[ 1. 考虑数的模 n 余数 任何一个正整数 a 都可以表示为: $a = q * n + r$ 其中, q 是商, r 是余数,且 $0 ≤ r < n$ 。 因此,每个正整数在除以 n 后,其余数 r 只能取 $0, 1, 2, ……, n-1$ 这 n 个可能的值。 2. 应用鸽巢原理 - 我们有 n + 1 个正整数,每个数在除以 n 后有 n 种可能的余数。 - 根据鸽巢原理,当我们有 n + 1 个“鸽子”放入 n 个“鸽巢”中时,至少有一个“鸽巢”中有至少两只“鸽子”。 在这里,“鸽子”代表 n + 1 个正整数,“鸽巢”代表余数 $0, 1, 2, ……, n-1$ 。 3. 得出结论 根据鸽巢原理,至少存在两个不同的正整数 a 和 b ,使得它们在除以 n 后的余数相同。即:$a #sym.eq.triple b (mod n)$ 这意味着:$a-b #sym.eq.triple 0 (mod n)$ $#sym.arrow.r.double$ n 整除 (a-b) 因此,这两个数的差 a - b 能被 n 整除。 综上所述, 该命题得证。 ] == 第2章:排列组合<ch2> === $P_48,3.$ #showybox( title: [ 12个人围坐在圆桌旁,其中一个拒绝与另一个相邻,问有多少种安排方法? ] )[ 对于12个人围坐在圆桌上的排列,总的不同排列数为:$(12 - 1)! = 11!$ 如果A和B必须相邻,可以将A和B视为一个整体(记为AB或BA),这样就有11个“单位”需要排列。这些排列数为:$(11 - 1)! × 2 = 10! × 2$ 要得到A和B不相邻的排列数,只需从总排列数中减去A和B相邻的排列数:$11! - 2 × 10! = 10! × (11 - 2) = 9 × 10!$ 所以,A和B不相邻的不同排列数为 $9 × 10!$ 种。 ] === $P_48,4.$ #showybox( title: [ 有颜色不同的四盏灯. + 把它们按不同的次序全部挂在灯竿上表示信号,共有多少种不同的信号? + 每次使用一盏、二盏、三盏或四盏灯按一定的次序挂在灯竿上表示信号,   共有多少种不同的信号? + 在(2)中,如果信号与灯的次序无关,共有多少种不同的信号? ] )[ (1) 对于4盏不同颜色的灯,全部挂上灯竿的排列数为4的全排列数:$4! =4×3×2×1=24$ ][ (2) 使用k盏灯的排列数为 $P^k_4 = 4!/(4-k)!$,其中 k = 1, 2, 3, 4。 - 当 k = 1 时,使用1盏灯的排列数为 $P^1_4 = 4!/(4-1)! = 4$; - 当 k = 2 时,使用2盏灯的排列数为 $P^2_4 = 4!/(4-2)! = 12$; - 当 k = 3 时,使用3盏灯的排列数为 $P^3_4 = 4!/(4-3)! = 24$; - 当 k = 4 时,使用4盏灯的排列数为 $P^4_4 = 4!/(4-4)! = 24$。 共有4+12+24+24=64种不同的信号。 ][ (3) 使用k盏灯的排列数为 $C^k_4 = 4!/((4-k)!k!)$,其中 k = 1, 2, 3, 4。 - 当 k = 1 时,使用1盏灯的排列数为 $C^1_4 = 4!/((4-1)!1!) = 4$; - 当 k = 2 时,使用2盏灯的排列数为 $C^2_4 = 4!/((4-2)!2!) = 6$; - 当 k = 3 时,使用3盏灯的排列数为 $C^3_4 = 4!/((4-3)!3!) = 4$; - 当 k = 4 时,使用4盏灯的排列数为 $C^4_4 = 4!/((4-4)!4!) = 1$。 共有4+6+4+1=15种不同的信号。 ] === $P_49,6.$ #showybox( title: [ 把q个负号和p个正号排在一条直线上,使得没有两个负号相邻,证明不同的排法有$vec(p+1,q)$种  ] )[ 1. 先排列 p 个正号,形成 p+1 个间隙 2. 从这 p+1 个间隙中选择 q 个放置负号,确保负号不相邻。 3. 不同的排法数为 $vec(p+1,q)$ 。 ] === $P_49,13.$ #showybox( title: [ 计数从$(0,0)$点到$(n,n)$点的不穿过直线 $y = x$ 的非降路径数. ] )[ 从可以先从$(0,0)$到达$(0, 1)$或者$(1, 0)$,这两个点到$(n,n)$而不穿过$y=x$的非降落路径数是相等的。于是可以考虑从$(1,0)$到$(n,n)$不穿过直线$y=x$的非降落路径数,由于不穿过$y=x$,那么必定是要经过点$(n, n-1)$。 从$(1,0)$到$(n,n-1)$的非降落路径数为:$C_(2n-2)^(n-1)$。 从$(1, 0)$到$(n, n-1)$穿过直线$y=x$的非降落路径和从$(0, 1)$到$(n, n-1)$的非降落路径是对称的等于:$C_(2n-2)^(n)$ 于是从点$(0, 0)$点到$(n, n)$点的不穿过直线$y=x$的非降落路径数为: $ 2 times (C_(2n-2)^(n-1) - C_(2n-2)^(n)) = 2 times ((2n-2)!/(n!(n-1)!) - (2n-2)!/(n!(n-2)!)) = 2 times (2n-2)!/(n!(n-1)!) = 2/n C_(2n-2)^(n-1) $ ] === $P_50,23.$ #showybox( title: [ $5$ 封不同的信用通信通道传送,在两封信之间至少要放$3$个空格,一共要加入$15$个空格,问有多少种方法? ] )[ $5$封信一共有$A_5^5=120$种排列,$5$封信之间有$4$个间隔,每个间隔至少要放$3$个空格,共$12$个空格,剩下$15-12=3$个空格可以放在$4$个间隔的任意位置,等价于$x_1+x_2+x_3+x_4=3$的整数解个数,即$C_(3+4-1)^(4-1)=C_6^3=20$种方法。所以一共有$120*20=2400$种方法。 ]
https://github.com/madhank93/typst-resume-template
https://raw.githubusercontent.com/madhank93/typst-resume-template/main/templates/template.typ
typst
// #let font_color = rgb("#2A2D31") #let font_color = rgb("#28282B") #let font_color_headings = rgb("#1B1212") // Utility functions #let justify_align(left_body, right_body) = { block[ #left_body #box(width: 1fr)[#align(right)[#right_body]] ] } #let title_section(title) = { set text(size: 14pt, weight: "semibold", fill: font_color_headings) align(left)[ #smallcaps[#title] #line(length: 100%, stroke: (paint: gray, thickness: 1pt)) ] } // Component functions #let name_component(firstname, lastname) = { align(center)[ #pad(bottom: 5pt)[ #block[ #set text(size: 25pt, style: "normal", fill: font_color_headings) #text(weight: "light")[#firstname] #text(weight: "light")[#lastname] ] ] ] } #let positions_component(positions) = { set text(size: 9pt, weight: "regular", ligatures: false) align(center)[ #smallcaps[#positions.join(text[#" "#sym.dot.c#" "])] ] } #let contacts_component(contact_info) = { set box(height: 11pt) set text(size: 11pt) let icons = ( phone: box(image("../assets/icons/phone-solid.svg")), email: box(image("../assets/icons/envelope-solid.svg")), portfolio: box(image("../assets/icons/globe-solid.svg")), linkedin: box(image("../assets/icons/linkedin.svg")), github: box(image("../assets/icons/github.svg")), medium: box(image("../assets/icons/medium.svg")) ) let links = ( phone: "", email: "mailto:", portfolio: "https://www.", linkedin: "https://www.linkedin.com/in/", github: "https://github.com/", medium: "https://medium.com/@" ) let separator = box(width: 5pt) align(center)[ #block[ #align(horizon)[ #for (key, value) in contact_info { icons.at(key) separator box[#link(links.at(key) + value)[#value]] separator } ] ] ] } #let section_content(title, content) = { set block(above: 0.7em, below: 0.7em) set pad(top: 5pt) title_section(title) content } #let work_experience_component(experience_details) = { for (_, work) in experience_details { pad[ #if (work.company != "" and work.location != "") [ #justify_align[ #set text(size: 11pt, style: "normal", weight: "semibold", fill: font_color_headings) #work.company ][ #set text(size: 11pt, style: "normal", weight: "semibold", fill: font_color_headings) #work.location ] ] #justify_align[ #set text(size: 9pt, style: "italic", weight: "semibold", fill: font_color_headings) #work.title ][ #set text(size: 9pt, style: "normal", weight: "semibold", fill: font_color_headings) #work.duration ] ] set text(size: 10pt, style: "normal") set par(leading: 0.65em) work.work_summary } } // Main resume function #let resume(author: (:), body) = { // Global settings set text(font: ("Roboto"), lang: "en", size: 10pt, fill: font_color, fallback: false) set page(paper: "a4", margin: (left: 0.30in, right: 0.30in, top: 0.20in, bottom: 0.20in)) set list(indent: 5pt) show par: set block(above: 0.75em, below: 0.75em) set par(justify: true) set heading(numbering: none, outlined: false) // Components name_component(author.firstname, author.lastname) positions_component(author.positions) contacts_component(author.contact) section_content("professional summary", author.professional_summary) section_content("work experience", work_experience_component(author.experience_details)) section_content("certifications", author.certifications) section_content("skills", author.skills) section_content("education", author.education) }
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs
https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task2/2.1.typ
typst
Apache License 2.0
#pagebreak() = System modelling == Activity diagram _Draw an activity diagram to capture the business process between systems and the stakeholders in Task Assignment module_ #figure(caption: [Activity diagram for Order Printing], image("../../images/Activity_Diagram.png") ) #pagebreak() *Activity Diagram for Upload Document* #figure(caption: [Activity diagram for Upload File], image("../../images/ActDia_UploadFile.png") ) #pagebreak() *Activity Diagram for Page Setting* #figure(caption: [Activity diagram for Page Setting], image("../../images/ActDia_PageSetting.png") ) #pagebreak() *Activity Diagram for Confirm Order* #figure(caption: [Activity diagram for Confirm Order], image("../../images/ActDia_ConfirmOrder.png") ) *Mô tả:* #block(inset:(left:1cm))[ - Sau khi đăng nhập, sinh viên sẽ ở trang Home page. - Lúc này sinh viên có thể chọn vào button “Order Printing” để thực hiện đặt in tài liệu. - Sinh viên sẽ được di chuyển đến trang OrderPrinting, sinh viên có thể Upload file cần in lên. Sinh viên có thể upfile lên hệ thống, hệ thống sẽ kiểm ra loại doctype của tài liệu và size file <= 100MB. Nếu thỏa điều kiện thì sinh viên Upload file thành công, nếu không thành công hệ thống sẽ thông báo để sinh viên Upload lại. - Sau khi Upload file thành công, sinh viên có thể chọn file đó và remove file, hệ thống sẽ cho phép sinh viên Upload file khác sau khi remove file. - Tiếp theo sinh viên sẽ thiết lập những thông số in bao gồm: Number of copies, Option Layout (Potrait layout Landscape layout), OptionPages (All Pages, Odd pages only, Even pages Only, Specific pages), Pages per sheet, Optinal Pages side (One sides, Both sides), etc. - Sau khi đã thiết lập những thông số in, sinh viên click vào button "Confirm" thì hệ thống đưa sinh viên đến trang List of uploads & configured document. - Tại trang này, sinh viên có thể tiếp tục Thêm tài liệu in, Chọn tài liệu và xóa, Thông tin giá tiền đơn hàng, Button "Order" để tiến hành quá trình thanh toán và sinh viên được di chuyển đến trang Confirm order. - Ở trang Confirm Order, sinh viên tiếp tục chọn Date để giao in, Location để giao và Thanh toán đơn hàng bằng coin. - Nếu số dư coin trong tài khoản sinh viên còn dư, sinh viên sẽ được phép thanh toán và sinh viên chọn Order Now hệ thống sẽ thông báo đơn hàng đã được đặt thành công và sinh viên được di chuyển đến trang Home page. - Nếu số dư coin trong tài khoản sinh viên không đủ, sinh viên sẽ không được phép thanh toán và hệ thống sẽ thông báo cho sinh viên, sinh viên có thể di chuyển đến trang nạp thêm coin để thanh toán. - Sau khi click vào Order Now, sinh viên được chyển về Home page, để theo dõi trạng thái (status) khi in. Và lúc này hệ thống sẽ gửi một Trigger Update data set order print đến hệ thống, và gửi Request and Update order đến SPSO. - Sau khi nhận được request order, SPSO sẽ chuẩn bị máy in và giấy, Click vào Print order để máy in (Printer) in tài liệu và gửi Trigger Update status process lên hệ thống. - Sau khi có tài liệu, sinh viên theo dõi trạng thái (Done) in tài liệu có thể đến địa điểm đã confirm để nhận tài liệu. ]
https://github.com/x14ngch3n/CV
https://raw.githubusercontent.com/x14ngch3n/CV/main/template.typ
typst
#import "fonts/fontawesome.typ": * // top-level template #let cv( doc ) = { set text(size: 10pt, font: "TeX Gyre Pagella") set page(margin: (x: 1.2cm, y: 1.2cm)) set par(justify: true) set align(left) set strong(delta: 250) set list(indent: 0pt) show link: url => underline(url) show heading.where(level: 1): title => align(center, text( size: 24pt, smallcaps(title) ) ) show heading.where(level: 2): title => { v(8pt) + text( size: 14pt, color.navy, smallcaps(title), ) + v(-10pt) + line(length: 100%, stroke: color.navy + 0.8pt) } doc } #let timestamp() = { align(right+bottom, text(8pt, fill: gray, [Powered by Typst | Last Modified: #datetime.today().display()]) ) } #let entry(title: none, start: (none, none), end: (none, none), desc) = { if end != (none, none) { strong(title) h(1fr) [#datetime(year: start.at(0), month: start.at(1), day: 1).display("[year]/[month]") - ] if end == (0, 0) { [now] } else { [#datetime(year: end.at(0), month: end.at(1), day: 1).display("[year]/[month]")] } } else if start != (none, none) { title h(1fr) [#datetime(year: start.at(0), month: start.at(1), day: 1).display("[year]/[month]")] } else { align(left, [$dot$] + title) } if desc != [] { v(-4pt) align(left, desc) } v(-4pt) } #let pdflink(url) = { link(url)[#fa[#pdf]] } #let githublink(url) = { link(url)[#fa[#github]] } #let websitelink(url) = { link(url)[#fa[#globe]] } #let codelink(url) = { link(url)[#fa[#code]] } #let LaTeX = { [L];box(move( dx: -4.2pt, dy: -1.2pt, box(scale(65%)[A]) ));box(move( dx: -5.7pt, dy: 0pt, [T] ));box(move( dx: -7.0pt, dy: 2.7pt, box(scale(100%)[E]) ));box(move( dx: -8.0pt, dy: 0pt, [X] ));h(-8.0pt) } #let cpp = { [C];box(move( dx: -2.5pt, dy:-0.5pt, box(scale(50%)[#strong[++]]) ));h(-6pt) } #let ccpp = { [C/] + cpp }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/xarrow/0.1.0/README.md
markdown
Apache License 2.0
# typst-xarrow Variable-length arrows in Typst, fitting the width of a given content. ## Usage This library mainly provides the `xarrow` functions. This function takes one positional argument, which is the content to display on top of the arrow. Additionnaly, the library provides the following arrow styles: - `xarrowHook` using arrow `sym.arrow.hook`; - `xarrowDouble` using arrow `sym.arrow.double.long`; - `xarrowHead` using arrow `sym.arrow.twohead`; - `xarrowSquiggly` using arrow `sym.arrow.long.squiggly`; - `xarrowDashed` using arrow `sym.arrow.dashed`. These names use camlCase in order to be simply called from math mode. This may change in the future, if it becomes possible to have the function names reflect the name of the symbols themselves. ### Example ``` #import "@preview/xarrow:0.1.0": xarrow, xarrowSquiggly $ a xarrow(QQ\, 1 + 1^4) b \ c xarrowSquiggly("super mmmmmmmmm") d $ ``` ## Customisation The `xarrow` function has several named arguments which serve to create new arrow designs: - `sym`, the base symbol arrow to use; - `margins`, the spacing on each side of the `body` argument. - `sections`, a tuple describing how the symbol is divided by the function. This takes two ratios, which cut the symbol in three parts. The central part is repeated. This is the parameter that has to be tweaked if observing artefacts. - `reducible`, a boolean telling whether the symbol can be shorter than the original if the given body is too narrow. - `partial_repeats`, a boolean telling whether the central part of the symbol can be partially repeated at the end in order to match the exact desired width. This has to be disabled when the repeated part has a clear period (like the squiggly arrow). For the exact default values and customisation examples (using the `with` method), please refer to the source file.
https://github.com/maucejo/cnam_templates
https://raw.githubusercontent.com/maucejo/cnam_templates/main/src/letters/_convention.typ
typst
MIT License
#import "../common/_colors.typ": * #import "../common/_utils.typ": * #let cnam-convention( composante: "cnam", convention: none, titre: none, partenaires: none, lieu: none, date: none, toc: false, body ) = { let logo-height = 4.08cm let decx = -0.073cm let decy = 0.085cm if composante != "cnam" { logo-height = 10cm decx = 0cm decy = 0cm } set heading(numbering: "1.1.") show heading.where(level: 1): it => { set text(size: 14pt, fill: primary.dark-blue) it v(0.5em) } set text(font: "Crimson Pro", size: 12pt, lang: "fr", ligatures: false) set par(justify: true) let footer = { grid( columns: (1fr, 1fr), align: left, [#context counter(page).at(here()).first()], [#place(right + horizon, dx: -1.25cm, block(over-title(title: ("Conservatoire national", "des arts et métiers"), size: 12pt, color: primary.dark-blue)))] ) } set page( footer: footer, margin: (top: 2cm, bottom: 2cm, left: 1.5cm, right: 1.5cm) ) let en-tete = { grid( columns: (1fr, 1fr), align: (left, right), [#over-title(title: ("Convention", convention), size: 20pt, color: primary.dark-blue)], [#place(right, dx: decx, dy: decy, image("../resources/logo/" + composante + ".png", width: logo-height))] ) } place(top, dy: -1.5cm, en-tete) v(2cm) if titre != none { set align(center) set text(size: 18pt, fill: primary.dark-blue) strong(titre) } if date != none { set align(center) emph(date) } if lieu != none { set align(center) strong(lieu) } v(2em) if toc { set align(center) set par(leading: 1em) outline(title: "Ordre du jour", depth: 2, indent: true) pagebreak() } body }
https://github.com/Tetragramm/flying-circus-typst-template
https://raw.githubusercontent.com/Tetragramm/flying-circus-typst-template/main/template/Main.typ
typst
MIT License
#import "@preview/flyingcircus:3.2.0" : * #import "@preview/cetz:0.3.1" #let title = "Sample Flying Circus Book" #let author = "Tetragramm" #show: FlyingCircus.with( Title: title, Author: author, CoverImg: image("images/Cover.png"), Dedication: [Look strange? You probably don't have the fonts installed. Download the fonts from #link("https://github.com/Tetragramm/flying-circus-typst-template/archive/refs/heads/Fonts.zip")[HERE]. Install them on your computer, upload them to the Typst web-app (anywhere in the project is fine) or use the Typst command line option --font-path to include them.], ) #FCPlane( read("Basic Biplane_stats.json"), Nickname: "Bring home the bacon!", Img: image("images/Bergziegel_image.jpg"), )[ _This text is where the description of the plane goes. Formatting is pretty simple. This is italic._ #underline[Words get underlined.] Leave an *empty* line or it will be the same paragraph + numbered list + Sub-Lists! + Things! But you can have multiple lines for an item by indenting the next one, or just one long line. - Sub-items! - Unnumbered list Break the column where you want it with `#colbreak()` Images can be added by doing `#image(path)`. The FC functions do fancy stuff though, and may override some arguments when you pass an image into them using an argument. Find the full documentation for Typst on the website #link("https://typst.app/docs")[#text(fill: blue)[HERE]] ] //If we don't want all our planes at the top level of the table of contents. EX: if we want // - Intro // - Story // - Planes // - First Plane // We break the page, and create a HiddenHeading, that doesn't show up in the document (Or a normal heading, if that's what you need) //Then we set the heading offset to one so everything after that is indented one level in the table of contents. #pagebreak() #HiddenHeading[= Vehicles] #set heading(offset: 1) //Parameters #FCVehicleSimple(read("Sample Vehicle_stats.json"))[#lorem(120)] //We wrap this in a text box so that we can set a special rule to apply #text[ //Set it so that the headings are offset by a large amount, so they don't show up in the table of contents. #set heading(offset: 10) // #FCWeapon( (Name: "Rifle/Carbine", Cells: (Hits: 1, Damage: 2, AP: 1, Range: "Extreme"), Price: "Scrip", Tags: "Manual"), Img: image("images/Rifle.png"), )[ Note that you can set the text in the cell boxes to whatever you want. ] #FCWeapon(( Name: "Machine-Gun (MG)", Cells: (Hits: 4, Damage: 2, AP: 1, "Ammo Count": 10), Price: "2þ", Tags: "Rapid Fire, Jam 1/2", ))[ Note that you can set the text in the cell boxes to whatever you want using the dictionary. ] ] #FCVehicleFancy( read("Sample Vehicle_stats.json"), Img: image("images/Wandelburg.jpg"), TextVOffset: 6.2in, BoxText: ("Role": "Fast Bomber", "First Flight": "1601", "Strengths": "Fastest Bomber"), BoxAnchor: "north-east", )[ The project to build the first armoured attack vehicle in the Gotha Empire spanned nearly three decades. Largely considered a low priority during the war with the UWF, the fierce fighting against the Macchi Republics suddenly accelerated the project, which went from concept sketch to deployment in six short months. This development was accompanied by intense secrecy: the project was code-named “Wandering Castle”, which gave the impression it was a Leviathan-building enterprise. Used for the first time in the Battle of Reggiane in 1593, the Type 1 reflects the idea that the tank ought to be a sort of mobile form of the concrete pillboxes coming into use at the time. Though suffering frequent breakdowns, plagued with difficulties getting its main gun on target, and very vulnerable in the mountains, it was successful enough that it soon became the most-produced tank of the war. After the first six months the official name of the vehicle was changed from its codename to “Self-Propelled Assault Vehicle Type 1”, known by the acronym “SbRd-AnZg Ausf I”. This development was ignored by everyone outside of official communications. ][#lorem(100)] #FCVehicleFancy(read("Sample Vehicle_stats.json"))[][#lorem(100)] #let ship_stats = ( Name: "<NAME>", Speed: 5, Handling: 15, Hardness: 9, Soak: 0, Strengths: "-", Weaknesses: "-", Weapons: ( (Name: "x2 Light Howitzer", Fore: "x1", Left: "x2", Right: "x2", Rear: "x1"), (Name: "x6 Pom-Pom Gun", Fore: "x2", Left: "x3", Right: "x3", Rear: "x2", Up: "x6"), (Name: "x2 WMG", Left: "x1", Right: "x1"), ), DamageStates: ("", "-1 Speed", "-3 Guns", "-1 Speed", "-3 Guns", "Sinking"), ) #set heading(offset: 0) #FCShip( Img: image("images/Macchi Frigate.png"), Ship: ship_stats, )[ Though remembered for large bombardment ships and airship tenders, the majority of the Seeheer was in fact these mid-sized frigates. These ships were designed for patrolling the seas for enemy airships and to escort Macchi cargo ships along the coast. They proved a deadly threat to landing barge attacks in the Caproni islands, as it was found their anti- aircraft guns were also effective against surface targets. ][ 160 crew ] #HiddenHeading[= Playbooks] #set heading(offset: 1) #FCPlaybook( //Obvious Name: "<NAME>", //Gotta go Somewhere Subhead: "Industrial Town", //This is the left column of the first page, all the character questions. Character: [ #block( )[ #set par(justify: true) _The Old World might be gone, but many of its technological wonders persist, and to keep them going, those towns that can still support industry work double-hard. Many people, be they refugees from the old cities or poor folks from across the world, come to these places in hopes of steady work. They'll find it, more often than not, but that labour is frequently backbreaking and the compensation paltry. Compared to that, who wouldn't want to take to the skies?_ ] #FCPSection("Name")[Choose, or write your own] _<NAME>, Gunter, Hans, Hermann, Jan, Klaus, <NAME>_ _Bertha, Emma, Gertrud, Hilda, Ilse, Ingrid, <NAME>_ #h(1fr)_Moser, Scheffler, Hamann, Muller, Schmidt, Weber, Becker, Bauer_ Age Range: _Youth (16-22), Adult (23-30)_ #FCPSection("Current Residence", "Choose, or write your own") _Choose a town from another playbook, though it is far behind you now._ #FCPSection("People", "Choose all that apply") _Städter, Himmilvolk, Rishonim, or any other._ #FCPSection("Expectations", "Tell the table or write it out") This is an archetypical image of a Worker. What resonates with you? What doesn't? - _Masculine, feminine, or nonbinary._ - _Responsible, organized, hardworking, never complains. Always tired._ - _Worn, sore, gone to seed. Hands rough, stained, often scarred._ - _Simple, drab, cheap clothing, hard-wearing enough for the job ahead._ //These let you choose where to stretch the page. The empty space gets put into these in proportion to the number. 2fr is twice as big as 1fr #v(1fr) #FCPSection("Character History")[Choose all that apply] #v(1fr) I was taught to fly by... #columns(2, gutter: 0pt)[ - ...an expensive training course. - ...an instructor when I was conscripted. #colbreak() - ...a family member, passing it on. - ...nobody, I'm just winging it. ] #v(1fr) I left my home because... #columns(3, gutter: 0pt)[ - ...jobs dried up. - ...I got hurt and fired. #colbreak() - ...it was killing me. - ...I want something better. #colbreak() - ...they learned I was queer. - ...I broke the law. ] #v(1fr) I fly so I can make some money and so I can... #columns(2, gutter: 0pt)[ - ...make sure my kids have it better. - ...do something with my life. - ...maybe retire, ever. - ...pay off some serious debts. #colbreak() - ...finally get on that adventure. - ...break free of my obligations. - ...escape the town I've been stuck in. - ...find a reason to keep going. ] ], //Top part of the right page Questions: [ #FCPSection("Questions")[Write your answers, and speak them] - What were you, before you were another anonymous worker? - #underline[Take 2 Personal Moves] from another playbook (or 1 Student move) to represent this origin, or two additional Worker moves if this is all you've ever known. - What was your dream job, as a child? What job did you actually end up working? - Where are your family staying, if not with you? #v(1fr) #FCPSection("Trust")[Ask and record answers] You trust everyone. They're your co-workers, you're not here for drama. #v(1fr) ], //This is the starting assets, burdens, ect. //Note that we set the default marker and gutter size instead of specifying for each one, like we did above. //This can save a lot of typing, if your use is consistent. Starting: [ #set list(marker: [○]) #set columns(gutter: 0pt) #KochFont(size: 18pt)[Start With...] #FCPSection("Assets")[Choose 3] #columns(2)[ - A plane large enough to carry your family. - A simple, robust sidearm. - A membership in a large union. #colbreak() - Two co-workers with special skills. - A house somewhere relatively safe. - A set of solid boots. ] #FCPSection("Dependents")[Choose 2] #columns(2)[ - A spouse without meaningful income. - A parent, now old and infirm. - A number of small children. #colbreak() - A sibling, unable to work. - A close friend, disabled. - An apprentice, learning your trade. ] #FCPSection("Planes")[Choose 1, or a plane worth up to 15þ] #columns(2)[ - <NAME> MB (Used) - König-Werke Adler-N (Used) #colbreak() - Kreuzer Skorpion (Used) - <NAME> A (Used) ] #FCPSection("Familiar Vices")[Choose 3] #columns(4)[ - Drinking - Opiates #colbreak() - Tobacco - Cannabis #colbreak() - Music - Bickering #colbreak() - Reading - Sleeping ] ], //This does in fact do magic, literally and figuratively, so you can use whatever stat names your playbook has, like witches do. One of these shows Wild, as an example. Stats: [ #FCPStatTable("Jobber", "Let's get paid and go home.", (Hard: "+1", Keen: "+1", Calm: "+1", Daring: "+1")) #FCPStatTable( "New Lease on Life", "Beats going back to the mines!", (Hard: "+2", Keen: "-1", Calm: "-1", Daring: "+2", Wild: "-"), ) #colbreak() #FCPStatTable("Worn Down", "Just punching the clock.", (Hard: "+2", Keen: "+2", Calm: "+2", Daring: "-4")) #FCPStatTable("Safety Inspector", "No point taking extra risks.", (Hard: "-2", Keen: "+2", Calm: "+4", Daring: "-2")) ], //This is defining them so the circles show up right. It does not check to make sure they're the same as the StatTables. StatNames: ("Hard", "Keen", "Calm", "Daring"), //This shows two useful things. //place lets you just stick stuff on top of other stuff. Just define the position, either relative to here, or use float: true to set things absolute. //Also define a small function. This is a less verbose way of doing things that you repeat a lot. Triggers: [ #place(dx: 1.6cm, dy: -0.3cm)[_Start with 3 Stress_] #let dotfill() = { box(width: 1fr, repeat[.]) } #FCPSection("Triggers")[] - If you took a life#dotfill() 1 Stress - If there was combat#dotfill() 1 Stress - If your plane got shot#dotfill() 1 Stress - If you were wounded#dotfill() 2 Stress - If a comrade was wounded#dotfill() 2 Stress - If your plane stopped working#dotfill() 2 Stress - If you had to wingwalk#dotfill() 1 Stress - If the job got out of hand#dotfill() 2 Stress ], //Vents. Vents: [ #FCPSection("Vents")[] - Complain about your circumstances to a comrade. - Buy something nice for yourself. - Complain about pay to a comrade. - Stir up trouble with the employees. - Deliberately trigger End of Night by maxing out your Vice track. ], //The last move goes here. Intimacy: [ #FCPSection("Intimacy Move")[Start with this Move] *Share the Burden*: _When you are intimate with comrades_, the Stress of all the characters participating can be freely redistributed between them. If there are any NPC participants, 1 Stress is also removed from each PC. _If you use this move in the air_, 1 additional Stress is removed from each character. ], //This is the whole right column. Useful thing is the use of place and stack at the bottom to make the Mastery Progress tracker. //Also showing how to do one-off markers in lists, like a filled in bubble. Moves: [ #FCPSection("Personal Moves")[Take Breadwinner and choose 3 more] - Breadwinner: Instead of personal upkeep, you have two Dependents. Write their names, and mark 1 on one and 2 on the other. Each Routine, during Expenses, choose to pay 0, 1, or 2 Thaler for each Dependent. If you pay 0, erase one mark. If you pay 2, mark their track and describe what special thing you do for them to make their lives easier. A Dependent at 2 Marks removes 1 Stress per routine. A Dependent losing a Mark gives 1 Stress, and at 0 Marks they cause 2 Stress per routine. #stack( dir: ltr, spacing: 0.5em, box(width: 30%, stroke: (bottom: 1pt))[#circle(radius: 5pt, stroke: none)], circle(radius: 5pt), circle(radius: 5pt), circle(radius: 10pt, stroke: none), box(width: 30%, stroke: (bottom: 1pt))[#circle(radius: 5pt, stroke: none)], circle(radius: 5pt), circle(radius: 5pt), ) #FCPRule() #[ #set list(marker: "●", spacing: 1em) - *There for You*: _When you Get Real_, your target always loses 1 extra Stress. #set list(marker: "○") - *Get it Done*: Each Routine, hold 3. Spend that hold to score a partial hit on any roll, without rolling first. - *Time Out*: _When you intervene in a dispute_, #underline[roll +Calm]. On a hit, the conflict cannot escalate to violence. 16+, everyone names a compromise they would be willing to make. - *Hard Drinking*: You may reroll two dice in the End of Night roll. - *Old Reliable*: After 3 Routines in the same plane, without it being modified or upgraded, the plane gains +8 Toughness and +3 Reliability. This is once per plane, and the bonus is removed if the plane is modified. - *No Drama*: The first time each Routine that somebody Vents with you as the victim, instead of Stress you take 2 XP directly. - *Open Mind*: _When you perform a Move Exchange_, both sides can learn as many moves as they have XP for from one another, instead of just 1. Other playbook moves cost 1 less XP to learn, and this character can teach any move they've learned. - *Domestic Bliss*: While you have 0 Stress, take +1 ongoing to all rolls outside of air combat. ] #FCPRule() #FCPSection("Other Moves & Notes")[Start with 1 Mastery Move and 3þ] All your XP costs are doubled. #place(bottom + right)[ #stack( dir: ltr, spacing: 0.2em, KochFont[Other Progress], circle(radius: 6pt), circle(radius: 6pt), circle(radius: 6pt), circle(radius: 6pt), ) #stack( dir: ltr, spacing: 0.2em, KochFont[Mastery Progress], circle(radius: 6pt), circle(radius: 6pt), circle(radius: 6pt), circle(radius: 6pt), circle(radius: 6pt), ) ] ], ) #let BraunYA = ( Name: "<NAME> Post Runner", Nickname: "Precious Lifelines", Price: 17, Used: 8, Upkeep: 1, Speeds: [23 - 15 - 12 - 8], Handling: 90, Structure: 21, Notes: [1 Crew. 2 Engines. Low radiator. Small cargo space. 20 Fuel Uses.], ) #FCShortNPC( BraunYA, img: image("images/Bergziegel_image.jpg"), img_scale: 1.5, img_shift_dx: -10%, img_shift_dy: -10%, )[Undoubtedly the most common sort of aircraft in the skies of Himmilgard are post runners, a ragtag mixture of disarmed obsolete fighters and purpose-built mail planes like this one.] #let AirDestroyer = ( Name: "Jörmungandr-class Air Destroyer", Nickname: "Ship of the Line", Speed: 12, Lift: 60, Handling: 40, Toughness: 100, Notes: [Luftane. 100-250 crew. x6 Engines. Armoured Skin 2, Armour 4/5+.\ x8 Flak Cannons. Large number of machine gun turrets.\ Pushes Weather Flak against attackers.], ) #FCShortAirship( AirDestroyer, )[The most common form of Air Destroyer in the war, forming the basis of the Gotha Empire's zeppelin fleet. A warlord repairing a downed Jörmungandr can threaten an entire region.]
https://github.com/Br0kenSmi1e/MyDFT
https://raw.githubusercontent.com/Br0kenSmi1e/MyDFT/main/notes/theory.typ
typst
MIT License
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #set math.equation(numbering: "(1)", supplement: [Eq.]) #align(center)[= Density Functional Theory in a Nutshell] == Introduction The goal of Density Functional Theory (DFT) is to solve ground states of many-body systems, mainly focused on electronic systems. Suppose we got $N$ electrons flying around in an external potential field. When simulating the realistic materials (e.g., crystals or molecules), this potential is usually taken as the Coulomb interaction between electrons and nucleus. Thus, the Hamiltonian of the system is of the form $ H = T + U_(e e) + U_("ext"), $ where $T$ is the kinetic energy term of the electrons, $U_(e e)$ is the interaction between electrons, and $U_("ext")$ is the external potential field where these electrons live. What needs to be pointed out is that the first two terms $tilde(H)=T+U_(e e)$ is universal for all $N$-electron systems, i.e., $tilde(H)$ has exactly the same form for all $N$-electron problems. == Density The state of this system is described by the wave-function $ |Psi angle.r = Psi(x_1,x_2,dots.h.c,x_N), $ where $x_k$ is the spatial coordinate of the _$k$-th particle_. #footnote[Technically, electrons are identical particle. So actually, we cannot label them.] This wave function has permutation symmetry. $ Psi(x_1,dots.h.c,x_k,dots.h.c,x_N) = -Psi(x_k,dots.h.c,x_1,dots.h.c,x_N) ", for " k > 1. $ The number density $n(x)$, by definition, is the expectation of particle number at a specific position $x$. Thus, we have $ n(x) &= angle.l Psi|sum_(k=1)^(N)delta(x_k-x)|Psi angle.r\ &= integral d x_1 dots.h.c d x_N sum_(k=1)^(N)delta(x_k-x) |Psi(x_1,dots.h.c,x_N)|^2\ ("the integral of " delta"-function is trivial")&= sum_(k=1)^(N) integral d x_1 dots.h.c d x_N integral d x_k delta(x_k-x) |Psi(x_1,dots.h.c,x_k,dots.h.c,x_N)|^2\ (|Psi|^2 "does not change under permutation")&= sum_(k=1)^(N) integral d x_1 dots.h.c d x_N |Psi(x,dots.h.c,x_1,dots.h.c,x_N)|^2\ &= N integral d x_2 dots.h.c d x_N |Psi(x,x_2,dots.h.c,x_N)|^2. $<density> == External Potential Suppose the given potential is $v(x)$, then the external potential energy is, can be computed in a similar way of the definition of the density function #footnote[See Appendix for detailed computation.], $ angle.l Psi|U_("ext")|Psi angle.r &= angle.l Psi|sum_(k=1)^N v(x_k)|Psi angle.r = integral d x v(x) n(x). $ Thus, the external energy term is a functional of the density, $ U_("ext") = U_("ext")[n]. $ == Hohenberg-Kohn Theorem [#text(red)[ToAdd]: a more concrete and more mathematical description of the correspondence.] Suppose $|Psi angle.r$ is the ground state of Hamiltonian $ H = tilde(H) + sum_(k=1)^N v(x_k), $ and $|Psi' angle.r$ is the ground state of Hamiltonian $ H = tilde(H) + sum_(k=1)^N v'(x_k). $ By the definition of ground state #footnote[Energy expectation of all other states is no less than the ground state energy] , we have, $ angle.l Psi'|H|Psi' angle.r >= angle.l Psi|H|Psi angle.r\ arrow.r.double angle.l Psi'|tilde(H)|Psi' angle.r + integral d x v(x)n'(x) >= angle.l Psi|tilde(H)|Psi angle.r + integral d x v(x)n(x). $ If the two states, $|Psi angle.r$ and $|Psi' angle.r$, gives the same density, i.e., $n(x) = n'(x)$. Then we would have $ angle.l Psi'|tilde(H)|Psi' angle.r >= angle.l Psi|tilde(H)|Psi angle.r . $ Similarly for $H'$, we have $ angle.l Psi|H'|Psi angle.r >= angle.l Psi'|H'|Psi' angle.r \ arrow.double.r angle.l Psi|tilde(H)|Psi angle.r+integral d x v'(x)n(x) >= angle.l Psi'|tilde(H)|Psi' angle.r+integral d x v'(x)n'(x)\ arrow.double.r angle.l Psi|tilde(H)|Psi angle.r >= angle.l Psi'|tilde(H)|Psi' angle.r. $ Again, the derivation in the last step is based on the assumption $n(x)=n'(x)$. Combine this two inequalities, we know that if two (ground) states lead to the same density, then they lead to the same universal energy term eexpectation. In other words, the value of universal term *can* be determined by the density. Thus, it is a functional of the density $ tilde(H) = tilde(H)[n]. $ == Non-Interacting Electronic Gas Discussing the non-interacting model here seems a little bit werid. But this is actually the preparation for the next part. For non-interacting electrons, their Hamiltonian is of the form $ H_("non") = T + U_("ext"). $ So solving this system is minimizing the functional #footnote[Whether the kinetic energy $T$ can be written as a functional of the density $n(x)$ remains unproven.] $ E[n] = T[n] + integral d x v(x)n(x), $ which gives a variational equation $ frac(delta T,delta n)+v(x)=0. $<non_eq> In another point of view, since there is no interaction between the electrons, we are actually solving $N$ *independent* single-body Schrödinger equation $ (-frac(1,2)nabla^2+v(x))phi.alt_k (x)=epsilon_k phi.alt_k (x). $ And the density is given by $ n(x) = sum_k f_k |phi.alt_k (x)|^2, $ where $f_k$ is the occupation number of orbital $k$. Although this expression seems a little different from @density, they are the same. It actually serves as a good practice for the reader to check that this two expression leads to the same result for non-interacting electrons. (_Hint: wave-functions of different orbitals are orthogonal._) == Kohn-Sham Equation From the Hohenberg-Kohn theorem, a general form of the energy functional is #footnote[Again, whether the kinetic energy $T$ and interation $U_(e e)$ can be separately written as functional of density $n$ remains unproven.] $ E[n] = T[n] + U_(e e)[n] + U_("ext")[n], $ and minimizing this functional gives a variational equation $ frac(delta T, delta n) + frac(delta U_(e e), delta n) + v(x)=0. $<inter_eq> Compare @inter_eq with @non_eq, and we can find out that they are of the same form $ frac(delta T, delta n) + v_("eff") (x) = 0, $ with the definition $ v_("eff") (x) = v(x) + frac(delta U_(e e), delta n). $ Thus, we can introduce a *non-interacting* model living in the effective potential $v_("eff") (x)$. And the ground state of this model is exactly the ground state of the original interacting system. Because they are solutions of the same variational equation. // It is worth emphasizing that this consistency only holds at ground state. == Coulomb Interaction: An Example The Coulomb energy of the system can be written as $ U_("lr") = frac(1,2) integral d x d x' frac(n(x)n(x'),|x-x'|), $ where the one-half factor is due to the double counting. Now suppose we got two density $n(x)$ and $tilde(n)(x)=n(x)+eta(x)$, the differential is $ U_("lr")[tilde(n)]-U_("lr")[n] &= frac(1,2) integral d x d x' frac(tilde(n)(x)tilde(n)(x')-n(x)n(x'),|x-x'|)\ &= frac(1,2) integral d x d x' frac(n(x)eta(x')+n(x')eta(x)+O(eta^2),|x-x'|)\ &= integral d x d x' frac(n(x')eta(x),|x-x'|) + O(eta^2)\ &= integral d x eta(x) integral d x' frac(n(x'),|x-x'|) + O(eta^2). $ Thus, the variational is $ frac(delta U_("lr"),delta n) = v_("lr") (x) = integral d x' frac(n(x'),|x-x'|). $ Besides the long-range Coulomb interaction, the are also other interactions between electrons, such as exchange terms and correlation terms (denoted as $U_("xc")$). == Solving the Kohn-Sham Equation The Kohn-Sham equation is can be solved through a self consistent loop: First, insert a trial density $n_"trial" (x)$ into the effective potential $v_("eff") (x)$. Then solve the eigen-states ${phi.alt_k (x)}$ of the Kohn-Sham equation. Finally, update the density from the solution ${phi.alt_k (x)}$ and go over this process again. This process can be described by the following flow chart. #align(center)[ #import fletcher.shapes: diamond #diagram( node-stroke: 1pt, edge-stroke: 1pt, node((0,0), [Initial Guess of Density]), edge("-|>"), node((0,1), [Solve K-S Eq.], corner-radius: 8pt), edge("r,d", "-|>"), node((1,2), [Get New Density], corner-radius: 8pt), edge("d,l", "-|>"), node((0,3), align(center)[Converge?], shape: diamond), edge((0,3),(0,2),"t","-|>", [No], label-pos: 0.5), node((0,4.5), [Final Answer]), edge((0,4.5),(0,4),"t","<|-", [Yes], label-pos: 0.7) )]
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/style.typ
typst
#let include_section(path, heading_increase: 0) = { let content = include(path); let updated = content.children.map(it => if not it.func() == heading { it } else [ #heading(level: it.level + heading_increase, it.body) #it.at("label", default: none) ] ) for c in updated { c } } #let sa_title_page(data) = { counter(page).update(0) grid( columns: 2, gutter: 1fr, move(dy: 0.4cm, image("static/ifs_logo.png", height: 2cm)), image("static/ost_logo.svg", height: 3cm) ) v(2.5cm) align(center)[ #text(30pt, data.title, weight: "bold") #v(-1.5em) #text(20pt, data.description) #v(0.5cm) #set text(size: 14pt) #data.organization #v(1cm) #data.thesis, #data.term #v(1cm) #v(4cm) #let ecell(ct) = rect(stroke: none, width: 100%)[ #align(left)[#ct] ] #let grid_cols = (1fr, 1fr) #grid( columns: grid_cols, rows: (auto, auto, auto), ecell()[*Authors:*], ecell()[#data.authors], ecell()[*Advisor:*], ecell()[#data.advisor], ecell()[*Project Partner:*], ecell()[#data.partner] ) #if (data.external-co-examiner != []) { v(-16pt) grid( columns: grid_cols, rows: (auto), ecell()[*External Co-Examiner:*], ecell()[#data.external-co-examiner] ) } #if (data.internal-co-examiner != []) { v(-16pt) grid( columns: grid_cols, rows: (auto), ecell()[*Internal Co-Examiner:*], ecell()[#data.internal-co-examiner] ) } ] pagebreak() } #let sa_text_style = ( font: "Linux Libertine", size: 12pt ) #let sa_header_style = (numbering: "1.") #let part-counter = counter("part") #let part(it) = locate(loc => { part-counter.step() pagebreak() v(.5cm) let part-label = label("part_" + it) let number = part-counter.at(loc).at(0) + 1 let part-name = locate(loc => [Part #numbering("I", number) - #it]) hide(heading("- Part " + it, outlined: false, numbering: none, bookmarked: true) + v(-1em)) text(size: 20pt, weight: "bold", [#part-name #part-label]) metadata((is-part: true, label: part-label, location: loc)) v(1cm) }) #let sa_heading1_show(it) = text(size: 14pt, it) #let sa_heading2_show(it) = { text(size: 13pt, it) } #let sa_heading3_show(it) = { block(text(size: 12pt, it)) } #let sa_heading4_show(it) = { block(text(size: 12pt, style: "italic", it.body)) } #let ht-first = state("page-first-section", []) #let ht-last = state("page-last-section", []) // inspired by https://stackoverflow.com/questions/76363935/typst-header-that-changes-from-page-to-page-based-on-state #let get-last-heading() = { locate(loc => [ #let first-heading = query(heading.where(level: 1, outlined: true), loc).find(h => h.location().page() == loc.page()) #let last-heading = query(heading.where(level: 1, outlined: true), loc).rev().find(h => h.location().page() == loc.page()) #{ if not first-heading == none { ht-first.update([ #counter(heading).at(first-heading.location()).at(0). #first-heading.body ]) ht-last.update([ #counter(heading).at(last-heading.location()).at(0). #last-heading.body ]) ht-first.display() } else { ht-last.display() }} ]) } #let sa_header(metadata) = { [#metadata.title #h(1fr) #get-last-heading()] } #let sa_footer(metadata) = locate(loc => { // reset footnote numbering after each page. Subject change in a future // typst release counter(footnote).update(_ => 0) if counter(page).at(loc).first() > 0 { grid( columns: (1fr, 1fr), align(left)[#metadata.authors-short], align(right)[Page #counter(page).display("1 of 1", both: true)] ) } }) #let sa_page_style(metadata) = ( header: sa_header(metadata), footer: sa_footer(metadata) ) #let sa_table_of_contents() = { align(center, text(size: 15pt, [*Table of Contents*])) show outline.entry.where(level: 1): it => { v(12pt, weak: true); it } locate(loc => { let parts = query(metadata, loc) .filter(d => type(d.value) == dictionary) .filter(d => d.value.keys().contains("is-part")) for part in parts { text(weight: "bold", query(part.value.label, part.value.location).at(0)) let next = parts.at(parts.position(p => p == part) + 1, default: none) let selector = selector(heading) .after(part.value.label) if (next != none) { selector = selector.before(next.value.label) } outline(title: none, indent: auto, depth: 2, target: selector) } }) } #let sa_bibliography() = { pagebreak() heading(level: 1, [Bibliography]) bibliography( "bibliography.bib", title: none, style: "ieee" ) } #let sa_list_of_figures() = { pagebreak() heading(level: 1, [List of Figures]) v(1em) outline( title: none, target: figure.where(kind: image), ) } #let sa_list_of_tables() = { pagebreak() heading(level: 1, [List of Tables]) outline( title: none, target: figure.where(kind: "table") ) } #let sa_list_of_listings() = { pagebreak() heading(level: 1, [List of Code Listings]) outline( title: none, target: figure.where(kind: raw) ) } #let sa_disclaimer() = [ #pagebreak() #set page(header: none, footer: none) #align(center)[ #text(weight: "bold", size: 1.5em, "Disclaimer") ] Parts of this paper were rephrased using the following tools: - GitHub Copilot #footnote("https://github.com/features/copilot/") - Grammarly #footnote("https://www.grammarly.com/") ]
https://github.com/imkochelorov/ITMO
https://raw.githubusercontent.com/imkochelorov/ITMO/main/src/algorithms/s2/template.typ
typst
#let project(title: "", authors: (), date: none, body) = { set document(author: authors, title: title) set page(numbering: none, number-align: center) align(center)[ #block(text(weight: 700, 1.75em, title)) #v(1em, weak: true) #date ] pad( top: 0.5em, bottom: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center, strong(author))), ), ) body }
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/sustech-graduated-thesis/pages/abstract-en.typ
typst
Apache License 2.0
#import "@preview/pinit:0.1.3": pin, pinit-place #import "../utils/style.typ": 字号, 字体 #import "../utils/indent.typ": fake-par #import "../utils/double-underline.typ": double-underline #import "../utils/custom-tablex.typ": gridx, colspanx // #import "../utils/invisible-heading.typ": invisible-heading // 研究生英文摘要页 #let abstract-en( // documentclass 传入的参数 doctype: "master", degree: "academic", anonymous: false, twoside: false, fonts: (:), info: (:), // 其他参数 keywords: (), outline-title: "ABSTRACT", outlined: true, abstract-title-weight: "regular", stoke-width: 0.5pt, info-value-align: center, info-inset: (x: 0pt, bottom: 0pt), info-key-width: 74pt, grid-inset: 0pt, column-gutter: 2pt, row-gutter: 10pt, anonymous-info-keys: ("author-en", "supervisor-en", "supervisor-ii-en"), leading: 1.27em, spacing: 1.27em, body, ) = { // 1. 默认参数 fonts = 字体 + fonts info = ( title-en: "SUSTech Thesis Template for Typst", author-en: "<NAME>", department-en: "XX Department", major-en: "XX Major", supervisor-en: "<NAME>", ) + info // 2. 对参数进行处理 // 2.1 如果是字符串,则使用换行符将标题分隔为列表 if type(info.title-en) == str { info.title-en = info.title-en.split("\n") } // 3. 内置辅助函数 let info-key(body) = { rect( inset: info-inset, stroke: none, text(font: fonts.楷体, size: 字号.四号, body), ) } let info-value(key, body) = { set align(info-value-align) rect( width: 100%, inset: info-inset, stroke: (bottom: stoke-width + black), text( font: fonts.楷体, size: 字号.四号, bottom-edge: "descender", if (anonymous and (key in anonymous-info-keys)) { "█████" } else { body }, ), ) } // 4. 正式渲染 pagebreak(weak: true, to: if twoside { "odd" }) [ #set text(font: fonts.楷体, size: 字号.四号) #set par(leading: leading, justify: true) #show par: set block(spacing: spacing) // 标记一个不可见的标题用于目录生成 // #invisible-heading(level: 1, outlined: outlined, outline-title) #align(center)[ #set text(size: 字号.小二, weight: "bold") #v(8pt) #double-underline((if not anonymous { "南京大学" }) + "研究生毕业论文英文摘要首页用纸") #v(-5pt) ] #gridx( columns: (56pt, auto, auto, 1fr), inset: grid-inset, column-gutter: column-gutter, row-gutter: row-gutter, info-key[#pin("title-en")THESIS:], colspanx(3, info-value("", " ")), colspanx(4, info-value("", " ")), colspanx(3, info-key[SPECIALIZATION:]), info-value("major-en", info.major-en), colspanx(3, info-key[POSTGRADUATE:]), info-value("author-en", info.author-en), colspanx(2, info-key[MENTOR:]), colspanx(2, info-value("supervisor-en", info.supervisor-en + if info.supervisor-ii-en != "" { h(1em) + info.supervisor-ii-en })), ) // 用了很 hack 的方法来实现不规则表格长标题换行... #pinit-place("title-en", { set text(font: fonts.楷体, size: 字号.四号) set par(leading: 1.3em) h(58pt) + (("",)+ info.title-en).intersperse(" ").sum() }) #v(3pt) #align(center, text(font: fonts.黑体, size: 字号.小三, weight: abstract-title-weight, "ABSTRACT")) #v(-5pt) #set text(font: fonts.楷体, size: 字号.小四) #[ #set par(first-line-indent: 2em) #fake-par #body ] #v(10pt) KEYWORDS: #(("",)+ keywords.intersperse("; ")).sum() ] }
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/for.typ
typst
// Test for loops. --- for-loop-basic --- // Empty array. #for x in () [Nope] // Dictionary is traversed in insertion order. // Should output `Name: Typst. Age: 2.`. #for (k, v) in (Name: "Typst", Age: 2) [ #k: #v. ] // Block body. // Should output `[1st, 2nd, 3rd, 4th]`. #{ "[" for v in (1, 2, 3, 4) { if v > 1 [, ] [#v] if v == 1 [st] if v == 2 [nd] if v == 3 [rd] if v >= 4 [th] } "]" } // Content block body. // Should output `2345`. #for v in (1, 2, 3, 4, 5, 6, 7) [#if v >= 2 and v <= 5 { repr(v) }] // Map captured arguments. #let f1(..args) = args.pos().map(repr) #let f2(..args) = args.named().pairs().map(p => repr(p.first()) + ": " + repr(p.last())) #let f(..args) = (f1(..args) + f2(..args)).join(", ") #f(1, a: 2) --- for-loop-integrated --- #let out = () // Values of array. #for v in (1, 2, 3) { out += (v,) } // Indices and values of array. #for (i, v) in ("1", "2", "3").enumerate() { test(repr(i + 1), v) } // Pairs of dictionary. #for v in (a: 4, b: 5) { out += (v,) } // Keys and values of dictionary. #for (k, v) in (a: 6, b: 7) { out += (k,) out += (v,) } #test(out, (1, 2, 3, ("a", 4), ("b", 5), "a", 6, "b", 7)) // Grapheme clusters of string. #let first = true #let joined = for c in "abc👩‍👩‍👦‍👦" { if not first { ", " } first = false c } #test(joined, "a, b, c, 👩‍👩‍👦‍👦") // Return value. #test(for v in "" [], none) #test(type(for v in "1" []), content) --- for-loop-over-bool --- // Uniterable expression. // Error: 11-15 cannot loop over boolean #for v in true {} --- for-loop-over-string --- // Keys and values of strings. // Error: 6-12 cannot destructure values of string #for (k, v) in "hi" { dont-care } --- for-loop-destructuring-without-parentheses --- // Destructuring without parentheses. // Error: 7-8 unexpected comma // Hint: 7-8 destructuring patterns must be wrapped in parentheses #for k, v in (a: 4, b: 5) { dont-care } --- for-loop-destructuring-half --- // Error: 7-8 unexpected comma // Hint: 7-8 destructuring patterns must be wrapped in parentheses #for k, in () {} --- for-loop-incomplete --- // Error: 5 expected pattern #for // Error: 5 expected pattern #for// // Error: 6 expected pattern #{for} // Error: 7 expected keyword `in` #for v // Error: 10 expected expression #for v in // Error: 15 expected block #for v in iter // Error: 5 expected pattern #for v in iter {} // Error: 7-10 expected pattern, found string // Error: 16 expected block A#for "v" thing // Error: 6-9 expected pattern, found string #for "v" in iter {} // Error: 7 expected keyword `in` #for a + b in iter {}
https://github.com/daskol/mpl-typst
https://raw.githubusercontent.com/daskol/mpl-typst/main/README.md
markdown
MIT License
![Linting and testing][1] ![Nightly][2] [1]: https://github.com/daskol/typst-mpl-backend/actions/workflows/on-push.yml/badge.svg [2]: https://github.com/daskol/typst-mpl-backend/actions/workflows/on-schedule.yml/badge.svg # Typst Matplotlib Backend *Typst backend for matplotlib (Python visualization library).* ## Overview At the moment, Typst supports main vector and raster image formats. Namely, images in PNG, JPEG, GIF, or SVG format can be easily emplaced in a document with Typst. However, it is **not possible** to keep metadata and annotations. These are mandatory in order to allow a reader to select and interact with vector content (e.g. text) on images. Although SVG can contain text metadata in principle, Typst does not support this feature at the moment but still it is able to render SVG as a vector content. This package solves this problem for `matplotlib` users. Basically, this project implements a custom render (or backend) for `matplotlib` which generates `typ`-file containing Typst markup. Generated markup file can be later included in the original markup so that the resulting PDF will have interactable content. Matplotlib exploits exactly the same strategy in order to generate PGF-files &mdash; a LaTeX markup itself &mdash; which can be included into LaTeX markup directly. ## Usage In order to render image with `mpl_typst` one can import `mpl_typst.as_default` module in order to use `mpl_typst` backend by default. ```python import mpl_typst.as_default ``` Or one can configure it manually. ```python import matplotlib import mpl_typst mpl.use('module://mpl_typst') ``` Also, it is possible to use rendering context as usual to override backend. ```python import matplotlib as mpl import mpl_typst with mpl.rc_context({'backend': 'module://mpl_typst'}): # or mpl_typst.BACKEND ... ``` Next, you can save your figure to `typ` as usual. ```python fig, ax = plt.subplots() ... fig.savefig('line-plot-simple.typ') ``` As soon as you get a `typ`-file you can included it directly to `figure` function and adjust figure time. ```typst #figure( include "line-plot-simple.typ", kind: image, caption: [Simple line plot], placement: top, ) <line-plot-simple> ```
https://github.com/juicebox-systems/ceremony
https://raw.githubusercontent.com/juicebox-systems/ceremony/main/instructions/routines.typ
typst
MIT License
// This module contains a bunch of reusable steps for `ceremony.typ`. #import "debug.typ": debug_level, debug_text #import "model.typ": /* */ assert_card, /* */ assert_card_reader, /* */ assert_component_loaded, /* */ assert_dvd_drive, /* */ assert_hsm_mode, /* */ boot_dvd, /* */ dvd_drive, /* */ realm_dvd, /* */ set_card_reader, /* */ set_card_reader_connected, /* */ set_component_loaded, /* */ set_computer_on, /* */ set_computer_plugged_in, /* */ set_dvd_drive, /* */ set_hsm_installed, /* */ set_hsm_mode /* */ #import "presentation.typ": /* */ blank, /* */ blank_entrust_esn, /* */ blank_entrust_serial_long, /* */ blanks, /* */ checkbox, /* */ keys, /* */ labeled_blank_bag_id, /* */ morse_code, /* */ outpath, /* */ radio, /* */ ref_step, /* */ step, /* */ todo /* */ #let boot_into_windows() = step(time: "1m50s", [ Boot into Windows: - Plug the power cord into the back of the computer. - Press the "power button" on the front of the computer. - Boot the computer into the pre-installed Windows OS. #set_computer_plugged_in(true) #set_computer_on(true) #assert_dvd_drive( none, message: boot_dvd + " can't be in the drive", ) ]) #let boot_into_dvd(uefi_setup: false) = { let start = ( [ Plug the power cord into the back of the computer. #set_computer_plugged_in(true) ], [ Press the "power button" on the front of the computer. #set_computer_on(true) ], ) let end = ( [ The computer should boot into the bootloader on the #boot_dvd. ], [ Press #keys("Enter") at the GRUB menu to boot into Linux. #assert_dvd_drive(boot_dvd) ], ) if uefi_setup {( step(time: "30s", [ Determine the current date and 24-hour time in UTC. This will be used to set the system time. #radio( [Pacific Standard Time (UTC−08:00)], [Pacific Daylight Time (UTC−07:00)], ) #blanks( [Local Date (`MM/DD/YYYY`)], [Local Time (`HH:MM`, from analog clock)], [UTC Date (`MM/DD/YYYY`)], [UTC Time (`HH:MM`)] ) ]), step(time: "3m40s", [ Configure UEFI and boot into the #boot_dvd: #enum( ..start, [ Tap #keys("F1") repeatedly during boot to enter the UEFI setup. ], [ Press #keys("Enter") to dismiss the help dialog. ], // Time & Date [ Press #keys("Right") to enter the #outpath[`Main`] settings. ], [ Press #keys("Down"), then #keys("Enter") to enter the #outpath[`Main`][`System Time & Date`] settings. ], [ Set the time and date to UTC. Use the arrows and #keys("Enter") to navigate, and #keys("+") and #keys("-") to adjust the time. Use the time and date calculated in the previous step, adjusted for the minutes that have since passed. ], [ Press #keys("Up") repeatedly until highlighting the back arrow, then #keys("Enter"), then #keys("Left") to return to the main menu. ], // Secure Boot [ Press #keys("Down") several times, then #keys("Right") to enter the #outpath[`Security`] settings. ], [ Press #keys("Down") several times, then #keys("Enter") to enter the #outpath[`Security`][`Secure Boot`] settings. ], [ Press #keys("Enter"), then #keys("Up"), then #keys("Enter") to disable Secure Boot. (The Linux kernel would refuse to load the vendor's HSM driver with Secure Boot enabled.) ], [ Press #keys("Up"), then #keys("Enter"), then #keys("Left") to return to the main menu. ], // Boot Priority [ Press #keys("Down"), then #keys("Right") to enter #outpath[`Startup`] settings. ], [ Press #keys("Enter") to enter the #outpath[`Startup`][`Boot Priority Order`] settings. ], [ Except for the SATA DVD-RW drive, press #keys("x") on each device to exclude it from the boot order. (Skip the DVD-RW drive with #keys("Down"). You can also un-exclude something with #keys("x").) ], [ Press #keys("F10"), then #keys("Enter") to save the changes and reboot. ], ..end ) ]), )} else { step(time: "40s", [ Boot into the #boot_dvd: #list( ..start, ..end, ) ]) } } #let power_off(os: "linux") = step(time: "20s", [ Power off the computer: #if os == "linux" [ - ```sh ceremony computer shutdown ``` ] else if os == "windows" [ - Press and release the "power button" on the front of the computer. ] else { panic("unrecognized os") } - Wait for the computer to turn off. - Unplug the power cord from the back of the computer. - Wait a few seconds. #set_computer_on(false) #set_computer_plugged_in(false) ]) #let eject_dvd() = step(time: "10s", [ #dvd_drive.display(previous => [ Eject the #previous by pressing the button and remove it from the DVD drive. #set_dvd_drive(from: previous, to: none) ]) ]) #let load_dvd(next) = step(time: "10s", [ #assert(next != none) #dvd_drive.display(previous => [ #if previous == none [ Insert the #next into the DVD drive. ] else [ Eject the #previous by pressing the button and insert the #next into the DVD drive. ] #set_dvd_drive(from: previous, to: next) ]) ]) #let unpack_hsm(first: false) = { // HSM factory packaging notes (based on loaner): // - Outermost box was brown cardboard. (For the newer HSMs, they've shipped // multiple in one outer box.) // - Inside that, packing list included "Item: NC4035E-B" and "Serial Numbers: // 46-X19142". // - Then there's a clear plastic bag with a sticker that says the date, // customer, PO and order numbers and a second "WIP Completion / Picking // Label" with "Serial Nbr: 46X19142". // - Inside that, there's a white NCipher-branded plastic bag that's somewhat // tamper-evident. // - Inside that, there's a white box with an Entrust nShield-branded sleeve. // On the end is a label that includes a checkbox for "nC4035E-000", a // checkbox for "Base" (vs "Mid" or "High"), a serial number "46-X19142 A". // - Inside that is an Installation Guide, the module (which came with the // half-height plate attached) in an antistatic bag, and a white box. // - Inside the white box is a card reader, wrapped in clear plastic. // - On the side of the module there's a white sticker that says "S/N: // 46-X19142 A" and "Model: nC4035E-000" // - On the end of the module there's a "REV" label with "06" written in // marker. let smoosh = v(-0.4em) // layout hack let open_shipping_box = [ Inspect the outer shipping box: #smoosh #checkbox[The box does not appear tampered with.] #smoosh Open the outer shipping box, remove its contents, and put away the box and any extra padding. ] let factory_checks = [ Inspect the white plastic bag containing this HSM: #checkbox[ The text says "NCIPHER: AN ENTRUST DATACARD COMPANY", with the first "N" enclosed in a circle. ] #smoosh #checkbox[The bag is sealed and does not appear tampered with.] Use scissors to open the end of the bag at the dashed line. Remove the bag and put it away. Inspect the box sleeve: #checkbox[ The text says "ENTRUST: SECURING A WORLD IN MOTION" with the hexagonal "E" logo and "nShield: Hardware Security Modules". ] #smoosh #checkbox[The box sleeve does not appear tampered with.] Remove the box sleeve and put it away. Inspect the box: #checkbox[The box does not appear tampered with.] Inspect the sticker at the end of the box: #checkbox[The top text says "ENTRUST: nShield Solo XC".] #smoosh #checkbox[Only the `nC4035E-000 nShield Solo XC F3` model is checked.] #smoosh #checkbox[Only the `Base` speed is checked.] #smoosh #checkbox[The serial number matches an unused HSM listed in @materials.] ] ( if first {( step(time: "2m", [ This step will process the HSM packaging. #checkbox[The HSM is in factory packaging.] #open_shipping_box #factory_checks Serial number: #blank_entrust_serial_long ]), )} else {( step(time: "1m", [ #radio( [ *The HSM is in factory packaging.* #radio( [The outer shipping box was opened earlier in the ceremony.], [ The outer shipping box was not opened earlier in the ceremony. #open_shipping_box ], ) #factory_checks ], [ *The HSM is in an antistatic bag within a tamper-evident bag.* #checkbox[The tamper-evident bag does not appear tampered with.] #smoosh #checkbox[ The serial number and bag ID match an unused HSM listed in @materials. ] ] ) Serial number: #blank_entrust_serial_long ]), )}, step(time: "1m", [ Unpack and inspect the HSM. Retain the antistatic bag and put away the other packaging. #checkbox[The HSM does not appear tampered with.] Inspect the sticker on the side of the HSM: #checkbox[ The serial number (#outpath[`S/N`]) matches that of the previous step. ] #checkbox[The model is `nC4035E-000`.] ]), step(time: "10s", [ Set the mode switch and jumpers on the HSM: #checkbox[ Set the outside-facing physical switch to `O` (the middle position). ] #checkbox[ Ensure both override jumper switches are set to off. ] ]), step(time: "1m30s", [ #if first [ Note: To fit different computer cases, the HSM may have a low-profile PCI bracket or a full-height PCI bracket attached. Due to a misalignment, the HSM is physically unable to fit into this particular computer when it has either bracket attached, so it will be used without a bracket. ] #radio( [ The HSM currently has no PCI bracket. ], [ The HSM currently has a low-profile or full-height PCI bracket. Remove the two screws holding the bracket from the HSM, then remove the bracket. Put away the bracket and the screws. ] ) ]), step(time: "1m", [ Insert the HSM (without an attached bracket) into the PCIe x16 slot in the computer. #set_hsm_installed(true) ]), if first { step(time: "1m", [ Unpack the card reader. Put away the packaging. #checkbox[ The card reader is etched with "ENTRUST" text and the hexagonal "E" logo. ] #checkbox[ The card reader does not appear tampered with. ] ]) } else { step(time: "1m", [ #radio( [ This HSM did not come with a card reader. ], [ This HSM came with a card reader. Place the new card reader in a tamper-evident bag for storage. #labeled_blank_bag_id ] ) ]) }, step(time: "15s", [ #if first [ While bracing the HSM, plug the card reader into the HSM's external port. ] else [ While bracing the HSM, plug the existing card reader into the HSM's external port. ] #assert_card_reader(none) #set_card_reader_connected(true) ]), ) } // The body of the `restart_hsm()` step. This is also used as a bullet point // when activating the codesafe feature. #let _restart_hsm_inner(mode) = [ Restart the HSM in #mode mode: #if mode == "initialization" [ ```sh ceremony hsm restart --mode initialization ``` ] else if mode == "maintenance" [ ```sh ceremony hsm restart --mode maintenance ``` ] else if mode == "operational" [ ```sh ceremony hsm restart ``` ] else [ #panic("unsupported HSM mode") ] This command should take about 55 seconds. #set_hsm_mode(mode) ] #let restart_hsm(mode) = step(time: "55s", _restart_hsm_inner(mode)) #let erase_hsm() = ( restart_hsm("initialization"), step(time: "30s", [ Initialize the HSM with a new module key: ```sh ceremony hsm erase ``` #checkbox[ The output includes the line `Initialising Unit 1 (SetNSOPerms)`. ] #checkbox[ #outpath[`Module Key Info`][`HKM[0] is`] shows 20 random-looking bytes in hex. ] This command should take less than 1 second. This key is temporary, as creating or joining a Security World later will generate a new module key. #assert_hsm_mode("initialization") #assert_component_loaded("secworld", true) ]) ) #let install_secworld() = step(time: "1m20s", [ Install Entrust's tools, daemons, and driver: ```sh ceremony vendor install secworld ``` This command takes about 80 seconds. #set_component_loaded("secworld", true) ]) #let install_codesafe() = step(time: "10s", [ Install Entrust's compiler, libraries, and header files: ```sh ceremony vendor install codesafe ``` This command should take about 10 seconds. #set_component_loaded("codesafe", true) ]) #let restore_realm_dvd_files() = step(time: "30s", [ Copy the files from the #realm_dvd: ```sh ceremony realm-dvd restore ``` #assert_dvd_drive(realm_dvd) #set_component_loaded("entrust_init", true) #set_component_loaded("sar_files", true) #set_component_loaded("simple_keys", true) ]) #let initialize_hsm(i) = { let esn_step = label("hsm_" + str(i) + "_esn") let activate_codesafe() = [ Activate the SEE (CodeSafe) feature on the HSM: - ```sh ceremony feature activate features/SEEUE_❰ESN❱.txt ``` // Note: This command doesn't work immediately after a firmware flash, // until a KNSO is generated. This command takes about 55 seconds. It has a side effect of leaving the HSM in operational mode. // Features can probably be enabled from other modes, but we happen to // always run it in initialization mode. #assert_hsm_mode("initialization") #assert_component_loaded("secworld", true) #set_hsm_mode("operational") - #_restart_hsm_inner("initialization") - ```sh ceremony feature info ``` #checkbox[`SEE Activation (EU+10)` is activated (shows `Y`).] #assert_component_loaded("secworld", true) ] ( install_secworld(), step(time: "1m40s", label: esn_step, [ Print HSM info: ```sh ceremony hsm info ``` ESN (#outpath[`Module #1`][`serial number`]): #blank_entrust_esn #checkbox[The ESN matches the HSM listed in @materials.] #blank[Firmware version (#outpath[`Module #1`][`version`])] #checkbox[ #outpath[`Module #1`][`product name`] shows all of `nC3025E/nC4035E/nC4335N`. ] #assert_component_loaded("secworld", true) ]), restart_hsm("maintenance"), step(time: "3m", [ Update/overwrite the HSM firmware to version 13.3.1: ```sh ceremony vendor mount firmware ceremony firmware write ceremony vendor unmount firmware ``` These commands should take about 3 minutes if starting from the same version and may take several more minutes if starting from an earlier version. #assert_hsm_mode("maintenance") #assert_component_loaded("secworld", true) ]), step(time: "30s", [ Wait until the HSM is done: ```sh ceremony hsm info ``` #checkbox[ #outpath[`Module #1`][`enquiry reply flags`] shows `none` (not `Offline`). ] #checkbox[ #outpath[`Module #1`][`hardware status`] shows `OK`. ] #checkbox[ The HSM LED is blinking in the repeated #morse_code("--") pattern. ] Wait and re-run the command until these conditions are satisfied. #assert_component_loaded("secworld", true) ]), power_off(), boot_into_dvd(), install_secworld(), step(time: "30s", [ Wait until the HSM is ready: ```sh ceremony hsm info ``` #checkbox[ #outpath[`Module #1`][`enquiry reply flags`] shows `none` (not `Offline`). ] #checkbox[ #outpath[`Module #1`][`mode`] shows `uninitialized`. ] #checkbox[ #outpath[`Module #1`][`serial number`] matches #ref_step(esn_step). ] #checkbox[ #outpath[`Module #1`][`version`] shows `13.3.1`. ] #checkbox[ #outpath[`Module #1`][`hardware status`] shows `OK`. ] #checkbox[ The HSM LED is blinking in the repeated #morse_code("-.-") pattern. ] Wait and re-run the command until these conditions are satisfied. If the module does not appear at all, check `dmesg` for the error `nfp_open: device ❰...❱ failed to open with error: -5`. Powering the computer off and on should resolve this. While this problem is somewhat anticipated, use an _exception sheet_ the first time it occurs. #assert_component_loaded("secworld", true) ]), erase_hsm(), step(time: "2m", [ #assert_component_loaded("secworld", true) Check which features have been activated on the HSM: ```sh ceremony feature info ``` #blank[Active features (excluding SEE)] #if i == 0 [ #checkbox[`SEE Activation (EU+10)` is not activated (shows `N`).] ] else [ #radio( [ `SEE Activation (EU+10)` is already activated (shows `Y`). ], [ `SEE Activation (EU+10)` is not activated (shows `N`). #activate_codesafe() ], ) ] ]), if i == 0 { step(time: "0s", activate_codesafe()) } else { () } ) } #let destroy(card) = ( step(time: "30s", [ Erase the #card smartcard: ```sh ceremony smartcard erase ``` This command takes about 30 seconds. #assert_card(card) #assert_component_loaded("secworld", true) ]), step(time: "2m", [ Remove the #card smartcard from the card reader and physically destroy it. Use a rotary tool to grind the smartcard electronics into a powder. Use scissors to shred the remaining plastic. #set_card_reader(from: card, to: none) ]), ) #let enroll_hsm_and_init_nvram(leave_acs_in_reader: false) = ( step(time: "0s", [ Place the ACS smartcard in the card reader. #set_card_reader(from: none, to: "ACS") ]), step(time: "50s", [ Enroll the HSM in the Security World: ```sh ceremony hsm join-world ``` This command takes about 22 seconds and reads from the ACS smartcard. #checkbox[ The output `hknso` matches the one recorded in #ref_step(<create_world>). ] #assert_card("ACS") #assert_hsm_mode("initialization") #assert_component_loaded("secworld", true) #assert_component_loaded("simple_keys", true) ]), restart_hsm("operational"), step(time: "40s", [ Print the signing key hash from the ACL of a key: ```sh ceremony realm print-acl noise ``` #checkbox[ #outpath[`key simple,jbox-noise exists`...][`Permission Group 2`][`Requires Cert`][`hash`] matches the signing key hash in #ref_step(<signing_key_hash>). ] #assert_component_loaded("entrust_init", true) #assert_component_loaded("simple_keys", true) #assert_component_loaded("secworld", true) // probably ]), step(time: "50s", [ Initialize this HSM's NVRAM file, providing the same signing key hash as the previous step for its ACL: ```sh ceremony realm create-nvram-file --signing-key-hash ❰HASH❱ ``` #checkbox[ #outpath[`Permission Group 2`][`Requires Cert`][`hash`] matches the signing key hash in #ref_step(<signing_key_hash>). ] This command takes about 1 second and reads from the ACS smartcard. #assert_card("ACS") #assert_hsm_mode("operational") #assert_component_loaded("entrust_init", true) #assert_component_loaded("secworld", true) ]), if leave_acs_in_reader { () } else { step(time: "30s", [ Remove the ACS smartcard from the card reader and place it visibly in the stand. #set_card_reader(from: "ACS", to: none) ]) } ) #let store_hsm() = ( step(time: "0s", [ Unplug the card reader from the HSM. #assert_card_reader(none) #set_card_reader_connected(false) ]), step(time: "2m", [ Remove the HSM from the computer. Insert it into an antistatic bag and then insert that into a tamper-evident bag (for transport to the production environment). #labeled_blank_bag_id #set_hsm_installed(false) ]), )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/007%20-%20Theros/007_I%20Iroan.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "I Iroan", set_name: "Theros", story_date: datetime(day: 06, month: 11, year: 2013), author: "<NAME>", doc ) #figure(image("007_I Iroan/01.jpg", width: 100%), caption: [Priest of Iroas | Art by Clint Cearley], supplement: none, numbering: none) #set align(center) ing , elegant Muses of star-dappled Nyx#linebreak() The joyous name of Him, glory-crowned,#linebreak() Who raises victor's pennant o'er battle ground,#linebreak() Bestows His love on th' highest of poleis,#linebreak() Bold Akros, paragon preeminent#linebreak() In war, in peace eternal vigilant.#linebreak() The Kolophon's apex blazes higher#linebreak() Than sun-spear Khrusor's sacred fire#linebreak() And Purphoros's forge; Keranan bolt#linebreak() Of prophecy its epic ramparts smote.#linebreak() Yet, eclipsing all, Thine aegis gleams,#linebreak() Philomachos, who shields the deme. #figure(image("007_I Iroan/02.jpg", width: 100%), caption: [Arena Athlete | Art by Jason Chan], supplement: none, numbering: none) Brows bent, we pray, as Thou Anax#linebreak() Endowed, in holy tournaments,#linebreak() The wreath of mortal excellence,#linebreak() Now bless Thy child, Pandamator.#linebreak() Athlete superb, famed pankratist,#linebreak() Euphoric in victory rose-kissed.#linebreak() O tetrapteric-helmed, spear-shaking#linebreak() Fame's epitome, bright-shining#linebreak() Hoplite's lord, Iroas, hegemon.#linebreak() Enthusiasts, eyes bright, oiled skin,#linebreak() Thy happy youth, physiques aglow,#linebreak() Gymnastic offertory show.#linebreak() Akroan heir, the weighty pallium#linebreak() Of honor lies, god's panoply,#linebreak() On your character. Let all see#linebreak() Humility, not hubris, as befits#linebreak() Your family, Stratians, throne;#linebreak() Or fall to grim Erebos, disowned.#linebreak() Th'empyrial heights where Nymosyne,#linebreak() Arissa, Lanathos, so many#linebreak() Strove, whose phalanxes monsters slew#linebreak() And kakomancers sent below,#linebreak() Echo sweet paeans. In agora raise#linebreak() Kylix and pause in reverent praise. #figure(image("007_I Iroan/03.jpg", width: 100%), caption: [Temple of Triumph | Art by <NAME>], supplement: none, numbering: none)
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/main/ch5_the_others.typ
typst
MIT License
= The others (_not the movie_) == Useful stuff for citation This is to cite stuff in-line `#cite(<bla-bla>)` #sym.arrow @REF:3 @REF:1. Now for brief foot citations you can put citations in a footnote: `#footnote[#cite(<bla-bla>)]` #sym.arrow look down!#footnote[#cite(<REF:1>)] See https://typst.app/docs/reference/model/cite/ for more citation styles.// For fully-detailed citation we do it like dis `footfullcite{bla-bla}` #sym.arrow look // down\footfullcite{REF:1} and another one for fun\footfullcite{REF:3}. // To cite the author only we do dis `citeauthor{bla-bla}` #sym.arrow \citeauthor{REF:1}; // the only year god only knows why we could use it but here we go `citeyear{bla-bla}` #sym.arrow \citeyear{REF:1}. This is just a normal footnote.#footnote[I'm just a normal footnote minding my own business] == Useful stuff chemical formulae - The first style: CHEM FORMULA HERE - The second style: CHEM FORMULA HERE - The third style: CHEM FORMULA HERE // \begin{itemize} // \item The first style:\newline~\newline // \ce{Na2SO4 ->[H2O] Na+ + SO4^2-} // \ce{(2Na+,SO4^2- ) + (Ba^2+, 2Cl- ) -> BaSO4 v + 2NaCl} // ~\newline~\newline // \item The second style:\newline~\newline // \begin{chemmath} // Na_{2}SO_{4} // \reactrarrow{0pt}{1.5cm}{\ChemForm{H_2O}}{} // Na^{+} + SO_{4}^{2-} // \end{chemmath} // \begin{chemmath} // (2 Na^{+},SO_{4}^{2-}) + (Ba^{2+},2 Cl^{-}) // \reactrarrow{0pt}{1cm}{}{} // BaSO_{4} + 2 NaCl // \end{chemmath} // ~\newline~\newline // \item The third style:\newline~\newline // \schemestart // \chemfig{Na_2SO_4} // \arrow{->[\footnotesize\chemfig{H_2O}]} // \chemfig{Na^+}\+\chemfig{SO_2^{-}} // \schemestop // \schemestart // (2\chemfig{Na^+}, \chemfig{SO_4^{2-}}) // \+ // (\chemfig{Ba^{2+}}, 2\chemfig{Cl^{-}}) // \arrow(.mid east--.mid west) // \chemname[1pt]{\chemfig{BaSO_4}}{\chemfig{-[,0.75]-[5,.3,,,-stealth]}}\+2\chemfig{NaCl} // \schemestop // \end{itemize} #lorem(100) #pagebreak() just an empty page...
https://github.com/pluttan/asmlearning
https://raw.githubusercontent.com/pluttan/asmlearning/master/lab2/lab2.typ
typst
#import "@docs/bmstu:1.0.0":* #show: student_work.with( caf_name: "Компьютерные системы и сети", faculty_name: "Информатика и системы управления", work_type: "лабораторной работе", work_num: "2", discipline_name: "Машинно-зависимые языки и основы компиляции", theme: "Программирование целочисленных вычислений", author: (group: "ИУ6-42Б", nwa: "<NAME>"), adviser: (nwa: "<NAME>"), city: "Москва", table_of_contents: true, ) = Ввод чисел Перед выполнением лабораторной работы, следует подумать об организации ввода-вывода. В предыдущей лабораторной уже описывалось как организовать ввод строк, поэтому задача сводится только к их обработке, но для начала напишем входную процедуру которая будет принимать ввод и отдавать его функции по обработке. == Процедура ```asm geti``` #img(image("flow/geti.svg", width:24%), [Схема алгоритма для ```asm geti```]) #let input = parserasm(read("input.asm")) #code(funcstr(input, "geti:"), "asm", [Функция ```asm geti```]) Следует немного описать функцию. На вход мы передаем значения в регистрах. Для начала процедура организует вывод приглашения на ввод, из предыдущей лабораторной мы уже знаем как оно организовывается. Ссылка на первую букву приглашения будем просить ввести через регистр ```asm ebx```, количество букв через ```asm eax```. После этого будем читать введенные пользователем данные, поэтому нам нужна так же ссылка на буфер для хранения этих данных, запросим ее в регистр ```asm edx``` и длина этого буфера в регистре ```asm ecx```. Так как буквы по определению занимают больше места чем числа в памяти дополнительной памяти для обработки нам не нужно. Поэтому возвращать процедура ничего не будет, а будет только записывать в буфер число введенное пользователем. После ввода числа пользователь нажимает на enter (LF) и число записывается по одной цифре в память. Теперь нам необходимо достать каждую цифру, вычесть из нее код числа $0$ (```asm sub eax, '0'```) и сложить эту цифру с предыдущими, умноженными на 10. Для этого напишем новую процедуру, которая будет брать адрес строки в ```asm edx``` и длину этой строки в ```asm ecx``` и после преобразования этой строки в число класть это числа регистр ```asm eax```. Потом мы просто запишем число из ```asm eax``` в буфер, вернем все регистры из стека и выйдем из процедуры ```asm geti```. #pagebreak() == Процедура ```asm stoi``` #img(image("flow/stoi.svg", width:35%), [Схема алгоритма для ```asm stoi```]) === Начало Итак, вот начало процедуры преобразования строки в число: #code(funcstr(input, "stoi:"), "asm", [Процедура ```asm stoi``` (начало)]) В стек загружаем все использованные в процедуре регистры, чтобы их не потерять после окончания выполнения. Готовим регистры для цикла ```asm eax```, как регистр для арифметических операций, будет содержать в себе все число, что мы получили, поэтому перемещаем в него 0. Так как мы будем производить умножение, чтобы не потерять адрес, куда в последствии необходимо сохранить число переместим его в регистр адреса ```asm esi```. Для умножения получившегося числа на 10 используем регистр ```asm ebx```(например пользователь ввел ```asm '10'``` мы обработали и поместили в ```asm eax``` $1$ и после обработки $0$ нам необходимо сделать 2 операции, чтобы получить исходное число: умножить ```asm eax``` на $10$ и прибавить $0$). Регистр ```asm edx``` будем так же использовать как временный буфер для текущей цифры. Стоит сказать, что все цифры и знак минус входят в ACSII, поэтому будут занимать лишь 1 байт. Перед началом цикла прочтем 1 байт в ```asm dl``` (младший байт ```asm edx```). Если 1 байт оказался с минусом, то число отрицательно, это необходимо запомнить. Создадим метку, в которой положим в стек число 1, как уведомление о том, что необходимо вернуть дополнительный код числа. После этого переходим к циклу. #code(funcstr(input, ".stoiminus:"), "asm", [Если число отрицательно кладем в стек 1]) Если же число положительное положим 0 и перейдем к циклу. Но перед циклом необходимо написать обработчик одной цифры. Цифра эта будет занимать 1 байт, поэтому процедура будет брать только регистр ```asm dl``` и работать дальше с ним. === Процедура ```asm ctoi``` #img(image("flow/ctoi.svg", width:24%), [Схема алгоритма для ```asm ctoi```]) #code(funcstr(input, "ctoi:"), "asm", [Процедура ```asm ctoi```]) Итак, мы получили число, которое должно соответствовать коду от 0 до 9 в таблице ASCII, если это так, то вычитаем из этого числа ```asm '0'``` и получаем цифру, иначе просто вернем число без изменений. Можно было бы написать обработчик, который при нахождении подобного числа завершал программу, или писал ошибку в stderr, но я думаю, что и такая простая проверка подойдет для выполнения данных лабораторных. В любом случае можно подобное реализовать, просто поменяв метки перехода в конец процедуры на метки реализации вывода ошибки. И так, мы получили цифру, теперь необходимо выйти из процедуры: #code(funcstr(input, ".ctoie:"), "asm", [Процедура ```asm ctoi``` (выход)]) Вернемся к реализации цикла. === Цикл #code(funcstr(input, ".stoil:"), "asm", [Процедура ```asm stoi``` (цикл)]) Для начала переместим в ```asm dl``` новую цифру. Стоит отметить, что если число положительное, то на первой итерации цикла мы просто второй раз обратимся к тому же адресу памяти, к какому обращались, когда проверяли число на отрицательность, иначе мы обратимся к следующему байту, который идет после минуса. После этого выполним операцию инкремента (добавления единицы) в регистр с адресом, для того, чтобы в следующей итерации цикла взять новое, еще не обработанное число. Проверим то число, которое мы только что взяли, не является ли оно завершением строки (LF). В следующих лабораторных работах, когда появится необходимость вводить числа через пробел сюда же добавим и проверку на символ пробела. Если в ```asm dl``` символ пробела, то выходим из цикла. Теперь необходимо вызвать функцию ```asm ctoi``` и после ее выполнения в ```asm dl``` наконец будет цифра введенного числа. Добавим эту цифру в конец ```asm eax```. Для этого, как описывалось ранее умножим ```asm esx``` на 10, не забыв, что при этой операции используется ```asm edx``` (поэтому, чтобы не потерять цифру уберем ее в стек). После умножения достаем цифру из стека и складываем с получившимся числом. При вводе пользователь мог занять весь буфер огромным числом, поэтому символ LF мог и не поместиться в буфер, поэтому добавим в цикл проверку на конец буфера. После этого снова переходим к метке цикла и начинается новая итерация. === Окончание Когда цикл завершит свою работу мы переходим к метке ```asm stoie```. #code(funcstr(input, ".stoie:"), "asm", [Процедура ```asm stoi``` (конец 1)]) Тут нам длина буфера уже не важна, ведь он уже прочитан. Поэтому заносим в регистр ```asm ecx``` флаг минуса, который лежит наверху стека. Теперь когда у нас есть модуль числа можно и запросить его дополнительный код, если это необходимо. Проверяем ```asm ecx``` и если там лежит 1 переходим к метке для умножения ```asm eax``` на $-1$, иначе в конец. #code(funcstr(input, ".stoiaddm:"), "asm", [Преобразуем число в отрицательное]) Регистр ```asm edx``` уже не нужен, флаг тоже, поэтому просто перемещаем $-1$ в ```asm ecx``` и умножаем ```asm eax``` на ```asm ecx```. После чего перемещаемся в конец. Стоит отметить, что подобная операция эквивалентна ```asm not eax```,```asm add eax, 1```. Возвращаем все регистры, как они были, кроме ```asm eax```, в котором ответ и выходим из процедуры ```asm stoi```. #code(funcstr(input, ".stoiend:"), "asm", [Процедура ```asm stoi``` (конец 2)]) Как уже было сказано ранее, после выполнения этой процедуры продолжится выполнение ```asm geti```, которая положит значение ```asm eax``` в буфер пользователя и, вернув все регистры в их начальное состояние завершится. = Вывод чисел После выполнения арифмeтических операций программа должна вывести пользователю результат выполнения перед ее завершением. Для этого напишем еще несколько процедур, которые теперь будут обратно преобразовывать число в строку. Тут мы для удобства будем пользоваться все той же памятью в которой лежит число и просто впоследствии сохраним туда строку. Но для использования иного буфера необходимо поменять лишь несколько строк. == Процедура ```asm outi``` #img(image("flow/outi.svg", width:24%), [Схема алгоритма для ```asm outi```]) #let output = parserasm(read("output.asm")) #code(funcstr(output, "outi:"), "asm", [Процедура ```asm outi```]) Вот первая процедура, она все так же выдает строку, которую мы передаем в ```asm ecx```. Длина этой строки лежит в ```asm edx```. В ```asm eax``` лежит ссылка на буфер. Длину буфера предполагаем достаточной, что бы вывести все число целиком. Процедура начинает свое выполнение опять с сохранения всех регистров в стек. Затем мы вызываем прерывывание на вывод предложения перед числом, после этого готовим регистры и выполняем процедуру ```asm itos```, которая преобразует данное нам число в строку и сама сохраняет эту строку в память, где было число. И после выполнения процедуры преобразования мы снова организуем вывод только для числа. Затем достаем из стека значения регистров и завершаем процедуру. #pagebreak() == Процедура ```asm itos``` Теперь давайте подробнее разберем процедуру ```asm itos```. #img(image("flow/itos.svg", width:50%), [Схема алгоритма для ```asm itos```]) === Начало #code(funcstr(output, "itos:"), "asm", [Процедура ```asm itos``` (Начало)]) Опять убираем все используемые регистры в стек. Перемещаем полученный адрес числа в ```asm esi```. После чего получаем само число по этому адресу. Его записываем в регистр ```asm eax```.В регистр ```asm ebx``` записываем основание системы счисления, так же как мы делали на вводе, но тут использоваться оно будет для деления. Если само число меньше нуля то необходимо перед циклом сразу убрать в память ```asm '-'```. Иначе просто переходим к циклу. #code(funcstr(output, ".itosminus:"), "asm", [Добавляем минус в буфер]) Добавляем минус в буфер, прибавляем единицу в адрес, что бы этот минус не затерся последней цифрой числа (ведь при делении на 10 мы первой получим именно последнюю цифру). После этого берем само число по модулю, т.е. преобразуем его дополнительный код в нормальный. Потом так же переходим в цикл. === Цикл #code(funcstr(output, ".itosl:"), "asm", [Процедура ```asm itos``` (Цикл)]) Тут мы будем использовать беззнаковое деление (так как со знаком мы уже разобрались, само число по модулю). При выполнении операции ```asm div``` результат деления попадает ```asm eax```, что позволяет нам не делать никаких других логических преобразований, регистр и так с каждой итерацией цикла будет уменьшаться на 10, т.е. на одну цифру. Эта цифра будет остатком от деления на 10 и будет храниться в ```asm edx```, прибавляя к этому регистру ```asm '0'``` получим ASCII код этой цифры, которую и сохраним в памяти. Мы знаем что этот код занимает лишь байт, поэтому он весь поместился в ```asm dl```. После записи в текущий байт переместимся на следующий, иначе число затрется. Когда будет последняя итерация в ```asm eax``` останется только одна цифра, после деления на 10 она перенесется в остаток, а с сам регистр останется 0, поэтому когда это произойдет мы выйдем из цикла. И переходим снова на метку цикла, чтобы начать новую итерацию. === Окончание #code(funcstr(output, ".itose:"), "asm", [Процедура ```asm itos``` (Конец)]) В конце возвращаем значения регистров на свои места. Берем начальный адрес и вычитаем его из конечного, таким образом, получая длину всей строки. Эту длину запишем в ```asm ecx```. А теперь немного подробнее посмотрим на проблему которую я упоминал ранее. При делении числа на 10 мы получаем последнюю его цифру, таким образом число $1234$ будет записано нами в памяти как ```asm '4321'``` ($-1234$ #sym.arrow ```asm '-4321'```). Для решения этой проблемы напишем еще одну процедуру, которую назовем ```asm reverse```. Вызовем ее, вернем значения в оставшиеся регистры и завершим процедуру ```asm itos```. #pagebreak() == Процедура ```asm reverse``` #img(image("flow/reverse.svg", width:25.5%), [Схема алгоритма для ```asm reverse```]) #code(funcstr(output, "reverse:"), "asm", [Процедура ```asm reverse``` (Начало)]) В ```asm eax``` передадим адрес числа, а в ```asm ecx``` количество цифр в числе. Суть алгоритма заключается в том, что ```asm ebx``` указывает на начало, а ```asm edx``` на конец числа, и при каждой итерации они меняют значения друг друга на противоположные, таким образом за половину числа мы поменяем ровно все значения. (```asm ebx``` и ```asm edx``` указывают на начало и конец, как палочка в буквах). Оба регистра это адреса, но указывают они на байты, поэтому для сохранения самих значений будем использовать только ```asm al```. Первым делом берем первый символ и проверяем не минус ли он. Напишем обработчик для этого случая: #code(funcstr(output, ".reverseminus:"), "asm", [Обрабатываем минус]) Просто смещаем регистр указывающий на начало на 1 и входим в цикл. #code(funcstr(output, ".reversel:"), "asm", [Процедура ```asm reverse``` (Цикл)]) В цикле мы проверяем, чтобы ```asm ebx``` был строго меньше ```asm edx``` (если больше -- число четное, если равен -- число нечетное). Потом перемещаем текущие значения в свободные регистры и, меняя их местами, сразу записываем обратно. Дальше мы увеличиваем ```asm ebx``` и уменьшаем ```asm edx```, "двигая" их друг к другу. #code(funcstr(output, ".reversee:"), "asm", [Процедура ```asm reverse``` (Конец)]) В конце возвращаем все регистры на место и выходим из процедуры. = Выполнение лабораторной работы == Задание Вычислить целочисленное выражение: $ f = (a-c)^2 + 2 times a times c^3/(k^2+1) $ == Цель работы Изучение форматов машинных команд, команд целочисленной арифметики ассемблера и программирование целочисленных вычислений. == Выполнение === Работа с данными Проинициализируем все сообщения пользователю. Зарезервируем 12 байт для каждого из переменных. 12 байт потому что минимальное число типа целочисленное $−2 147 483 648$ (оно же максимальное по количеству знаков, их 11), добавляя еще знак переноса получаем максимальное значение в 12 байт. #let lab2 = parserasm(read("lab2.asm")) #code(funcstr(lab2, "section .data")+funcstr(lab2, "section .bss"), "asm", [Выделяем и инициализируем необходимые данные]) Я сразу разбил выполнение программы на блоки, первый из которых получение данных. === Получение данных #img(image("flow/getack.svg", width:70%), [Схема алгоритма для ```asm getack```]) #code(funcstr(lab2, "getack:"), "asm", [Запрашиваем данные на ввод]) Для этого просто перемещаем приглашение пользователю, длину приглашения, ссылку на буфер для данных и длину буфера в нужные регистры и вызываем ```asm geti```. Проделываем эту процедуру 3 раза и получаем в памяти 3 числа, готовых к обработке. Все выполнения арифметических операций будет в```asm calc``` переходим в нее, когда значения успешно введены. === Вычисление значения функции #img(image("flow/calc.svg", width:21%), [Схема алгоритма для ```asm getack```]) Перепишем задание и разобъем его на шаги. $ f = (a-c)^2 + 2 times a times c^3/(k^2+1) $ 1. $a-c$ 2. $(a-c)^2$ 3. $2 times a$ 4. $c^3$ 5. $k^2$ 6. $k^2+1$ 7. $2 times a times c^3$ 8. $2 times a times c^3\/(k^2+1)$ 9. $(a-c)^2 + 2 times a times c^3\/(k^2+1)$ #code(funcstr(lab2, "calc:"), "asm", [Вычисляем значение функции]) В начале сохраним в стеке значение `a`, оно нам понадобится для шага 3. Выполним шаг 1 и запишем значение в ```asm eax```. После чего умножим этот регистр сам на себя. Итак, в ```asm eax``` лежит значение шага 2, оно нам не нужно до 10 шага, поэтому уберем его в стек, предварительно достав от туда `a`. Умножим ```asm eax``` на 2 и поместим значение в стек, оно нам не понадобится до 7 шага. Переместим значение `c` в ```asm eax``` и умножим ```asm eax``` на `c` два раза. Куб `c` нам так же не понадобится до 7 шага, тоже уберем в стек. Умножим `k` саму на себя и прибавим к ней единицу. Таким образом мы сделали все простейшие операции, осталось только вынуть из стека все значения, которые у нас получились. $c^3$ #sym.arrow ```asm eax```; $2 times a$ #sym.arrow ```asm ebx```. Умножаем ```asm eax``` на ```asm ebx``` и получаем ответ на 7 шаг. Для 8 шага необходимо подготовить регистр ```asm edx```. При делении используется расширенная версия регистра ```asm eax```: ```asm edx:eax```, поэтому если в ```asm edx``` у нас нет расширения для ```asm eax```, то необходимо заполнить ```asm edx``` нулями, если число положительно и единицами, если число отрицательно. Для этого перед делением вызовем ```asm cdq```. После этого просто делим со знаком весь результат 7 шага на $k^2+1$. В стеке осталось лежать только $(a-c)^2$, достаем и это значение, суммируем с результатом деления и получаем целочисленный ответ. Осталось только вывести ответ и завершить программу. === Вывод и завершение #img(image("flow/outandexit.svg", width:20%), [Схема алгоритма для ```asm getack```]) #code(funcstr(lab2, "outandex:"), "asm", [Вывод и выход]) Перемещаем получившееся значение в память, а ссылку указываем в регистр. После этого указываем сообщение перед выводом и вызываем вывод. После того, как вывод отработает остается только вызвать завершение программы. === Компиляция Ввод, вывод и код лабораторной я разнес в отдельные файлы, которые и назвал ```sh input.asm```, ```sh output.asm``` и ```sh lab2.asm```. Поэтому компилировать их будем тоже отдельно, а после этого соберем. Вот, что необходимо ввести в терминал, для компиляции и сборки всех 3 файлов: #code("mod=lab2/lab2 # Название ассемблерного файла без расширения nasm -f elf -o $mod.o $mod.asm nasm -f elf -o lab2/input.o lab2/input.asm nasm -f elf -o lab2/output.o lab2/output.asm ld -m elf_i386 -o $mod $mod.o lab2/input.o lab2/output.o", "sh", "Команда в терминале") == Отладка Отладим все выполнение, заодно посмотрим как работают операции ввода-вывода. === Отладка ввода Первой процедурой посмотрим выполнение ```asm stoi```, так как простейший ввод и вывод был показан в предыдущей лабораторной работе. Введем при запросе `a` большое отрицательное число: $-123477790$. #grid( columns:2, gutter:10pt, img(image("img/1.png", width: 90%), "Запуск"), img(image("img/2.png", width: 90%), "Сохраняем регистры") ) #grid( columns:2, gutter:10pt, img(image("img/3.png", width: 90%),"Переносим 1-ый символ"), img(image("img/4.png", width: 90%),"Обрабатываем минус") ) #grid( columns:2, gutter:10pt, img(image("img/5.png", width: 90%),"Заходим в цикл"), img(image("img/6.png", width: 90%),[Заходим в ```asm ctoi```]) ) #grid( columns:2, gutter:10pt, img(image("img/7.png", width: 90%), [Выходим из ```asm ctoi```]), img(image("img/8.png", width: 90%), "Готовим цифру") ) #grid( columns:2, gutter:10pt, img(image("img/9.png", width: 90%),[Добавляем к ```asm eax```]), img(image("img/10.png", width: 90%),[Добавляем 2-ую цифру]) ) #grid( columns:2, gutter:10pt, img(image("img/11.png", width: 90%),[Добавляем 3-ую цифру]), img(image("img/12.png", width: 90%),[Добавляем 4-ую цифру]) ) #grid( columns:2, gutter:10pt, img(image("img/13.png", width: 90%), [Добавляем 5-ую цифру]), img(image("img/14.png", width: 90%), [Добавляем 6-ую цифру]) ) #grid( columns:2, gutter:10pt, img(image("img/15.png", width: 90%),[Добавляем 7-ую цифру]), img(image("img/16.png", width: 90%),[Добавляем 8-ую цифру]) ) #grid( columns:2, gutter:10pt, img(image("img/17.png", width: 90%),[Добавляем 9-ую цифру]), img(image("img/18.png", width: 90%),[Инвертируем и выходим]) ) Более подробно о работе этой функции я расписал в части 1.2, поэтому тут приведу только скриншоты с подписями. В конечном итоге мы получили ответ в регистре ```asm eax``` теперь переносим его в память и смотрим как он отображается в памяти: #img(image("img/19.png", width: 60%),[Память программы], f:(i)=>{i.display()}) === Отладка арифметических операций Для проверки ```asm calc``` необходимы числа поменьше, поэтому перезапустим программу и с помощью команды ```sh break calc``` установим точку останова уже непосредственно перед арифметическими операциями. В качестве переменных будем использовать $a=1; c=-13; k=5$. $ f = (1 - (-13))^2 + 2 times 1 times (-13)^3/(5^2+1) = 14^2 + 2 times -2197/26 = \ = 196 + (-4394)/26 = 196-169 = 27 $ При выполнении деления перед умножением в результате мы получили бы $-84,5$, остаток отброшен и результат был бы неверен. #grid( columns:2, gutter:10pt, img(image("img/21.png", width: 90%),"Готовим отладчик"), img(image("img/22.png", width: 90%),[Значения в регистрах]) ) #grid( columns:2, gutter:10pt, img(image("img/23.png", width: 90%), [```asm sub eax, ebx```]), img(image("img/24.png", width: 90%),[```asm mul eax```]) ) #grid( columns:2, gutter:10pt, img(image("img/25.png", width: 90%),[Возвращаем `a`]), img(image("img/26.png", width: 90%),[```asm mov edx, 2```]) ) #grid( columns:2, gutter:10pt, img(image("img/27.png", width: 90%),[```asm mul edx```]), img(image("img/28.png", width: 90%),[```asm mov eax, ebx```]) ) #grid( columns:2, gutter:10pt, img(image("img/29.png", width: 90%),[```asm mul ebx```]), img(image("img/30.png", width: 90%),[```asm mul ebx```]) ) #grid( columns:2, gutter:10pt, img(image("img/31.png", width: 90%),[```asm mov eax, ecx```]), img(image("img/32.png", width: 90%),[```asm mul ecx```]) ) #grid( columns:2, gutter:10pt, img(image("img/33.png", width: 90%),[```asm add eax, 1```]), img(image("img/34.png", width: 90%),[```asm mov ecx, eax```]) ) #grid( columns:2, gutter:10pt, img(image("img/35.png", width: 90%),[```asm pop eax```]), img(image("img/36.png", width: 90%),[```asm pop ebx```]) ) #grid( columns:2, gutter:10pt, img(image("img/37.png", width: 90%),[```asm mul ebx```]), img(image("img/38.png", width: 90%),[```asm cdq```]) ) #grid( columns:2, gutter:10pt, img(image("img/39.png", width: 90%),[```asm idiv ecx```]), img(image("img/40.png", width: 90%),[```asm pop ecx```]) ) #img(image("img/41.png", width: 50%),[```asm add eax, ecx```], f:(i)=>{i.display()}) Выше приведен полный арифметический разбор всех операций, а в отладчике просто наглядно видно какие значения лежат в регистрах. Теперь напишем пару простых тестов, которые покажут правильность выполнения программы. Запускать их будем вызывая саму программу, не используя отладку. $ a=1; c=13; k=5\ f = (1 - 13))^2 + 2 times 1 times 13^3/(5^2+1) = 12^2 + 2 times 2197/26 = \ = 144 + (4394)/26 = 144+169 = 313 $ #img(image("img/72.png", width: 40%),[Тест 1], f:(i)=>{i.display()}) $ a=13; c=-13; k=25\ f = (13 - (-13))^2 + 2 times 13 times (-13)^3/(25^2+1) = 26^2 + 26 times -2197/626 = \ = 676 + (-57122)/626 = 676 - 91 = 585 $ #img(image("img/73.png", width: 40%),[Тест 2], f:(i)=>{i.display()}) $ a=1; c=-1000; k=0\ f = (1 - (-1000))^2 + 2 times 1 times (-1000)^3/(0^2+1) = 1001^2 + 2 times (-1000000000) =\ =1002001 - 2000000000 = -1998997999 $ #img(image("img/74.png", width: 40%),[Тест 3], f:(i)=>{i.display()}) === Отладка вывода Мы получили ответ к задаче и осталось его только вывести. Так как адреса памяти все равно дают мало представления о том, как процедура выполняется для ```asm reverse``` в основном приведу только значения, хранящиеся в памяти до и после. #grid( columns:2, gutter:10pt, img(image("img/42.png", width: 90%),[Переходим к ```asm outandex```]), img(image("img/43.png", width: 90%),[Вызываем ```asm outi```]) ) #grid( columns:2, gutter:10pt, img(image("img/44.png", width: 90%),[Выводим строку перед числом]), img(image("img/46.png", width: 90%),[Вызываем ```asm itos```]) ) #grid( columns:2, gutter:10pt, img(image("img/47.png", width: 90%),[Обрабатываем 1 цифру]), img(image("img/48.png", width: 90%),[Обрабатываем 2 цифру]) ) #grid( columns:2, gutter:10pt, img(image("img/49.png", width: 90%),[Конец ```asm itos```]), img(image("img/50.png", width: 90%),[Вызываем ```asm reverse```]) ) #grid( columns:2, gutter:10pt, img(image("img/51.png", width: 90%),[Входим в цикл]), img(image("img/52.png", width: 90%),[Проверяем условие]) ) #grid( columns:2, gutter:10pt, img(image("img/53.png", width: 90%),[Память до цикла]), img(image("img/54.png", width: 90%),[Память после цикла]) ) #grid( columns:2, gutter:10pt, img(image("img/55.png", width: 90%),[Завершаем ```asm itos```]), img(image("img/56.png", width: 90%),[Готовим число к выводу]) ) #grid( columns:2, gutter:10pt, img(image("img/57.png", width: 90%),[Выведенный ответ]), img(image("img/58.png", width: 90%),[Программа завершилась]) ) #pagebreak() === Дизассемблирование кода и расшифоровка команд Запустим утилиту ```sh objdump```: ```sh objdump -d $mod```. Посмотрим на код в двочином (для удобства шеснадцатеричном) виде. #grid( columns:2, gutter:10pt, img(image("img/59.png", width: 90%),[```asm _start``` и ```asm getack```]), img(image("img/60.png", width: 90%),[```asm calc```]) ) #grid( columns:2, gutter:10pt, img(image("img/61.png", width: 90%),[```asm outandex```]), img(image("img/62.png", width: 88%),[```asm geti```]) ) #grid( columns:2, gutter:10pt, img(image("img/63.png", width: 90%),[```asm ctoi```, ```asm ctoie``` и ```asm stoi```]), img(image("img/64.png", width: 90%),[```asm stoiminus```, ```asm stoil``` и ```asm stoie```]) ) #grid( columns:2, gutter:10pt, img(image("img/65.png", width: 90%),[```asm stoiaddm```, ```asm stoiend``` и ```asm outi```]), img(image("img/66.png", width: 90%),[```asm itos```, ```asm itosminus``` и ```asm itosl```]) ) #grid( columns:2, gutter:10pt, img(image("img/67.png", width: 90%),[```asm itose```, ```asm reverse``` и ```asm reverseminus```]), img(image("img/68.png", width: 90%),[```asm reversel``` и ```asm reversee```]) ) Для разбора команды возьмем команду ```asm mov```. При компиляции языком ассемблера команда ```asm mov``` может быть заменена на множество команд: это зависит от операндов. Приведем таблицу команды ```asm mov```. Стоит отметить, что в данной таблице не указаны перемещения из/в системные (отладочные) регистры. #pagebreak() #table( columns: 3, inset: 10pt, align: horizon, [`89 /r`], [`10001000 | modregr/m`], [```asm mov r/m8, r8```], [`89 /r`], [`10001001 | modregr/m`], [```asm mov r/m16, r16```], [`89 /r`], [`10001001 | modregr/m`], [```asm mov r/m32, r32```], [`8A /r`], [`10001010 | modregr/m`], [```asm mov r8, r/m8```], [`8B /r`], [`10001011 | modregr/m`], [```asm mov r16, r/m16```], [`8B /r`], [`10001011 | modregr/m`], [```asm mov r32, r/m32```], [`8C /r`], [`10001100 | mod0sregr/m`], [```asm mov r/m16(32), sreg```], [`8E /r`], [`10001110 | mod0sregr/m`], [```asm mov sreg, r/m16(32)```], [`A0`], [`10100000 | off_low8/16bit | off_high8/16bit`], [```asm mov al, moffs8```], [`A1`], [`10100001 | off_low8/16bit | off_high8/16bit`], [```asm mov ax, moffs16```], [`A1`], [`10100001 | off_low8/16bit | off_high8/16bit`], [```asm mov eax, moffs32```], [`A2`], [`10100010 | off_low8/16bit | off_high8/16bit`], [```asm mov r8, imm8```], [`A3`], [`10100011 | off_low8/16bit | off_high8/16bit`], [```asm mov r16, imm16```], [`A3`], [`10100011 | off_low8/16bit | off_high8/16bit`], [```asm mov r32, imm32```], [`B0 + rb`], [`10110reg | data8bit `], [```asm mov r8, imm8```], [`B8 + rw`], [`10111reg | data16bit`], [```asm mov r16, imm16```], [`B8 + rd`], [`10111reg | data16bit`], [```asm mov r32, imm32```], [`C6 /0`], [`11000110 | mod000r/m`], [```asm mov r/m8, imm8```], [`C7 /0`], [`11000111 | mod000r/m`], [```asm mov r/m16, imm16```], [`C7 /0`], [`11000111 | mod000r/m`], [```asm mov r/m32, imm32```], ) Для расшифровки возьмем 3 команды ```asm mov```. Перемещение адреса в регистр, перемещение регистра в регистр, перемещение в адрес, в указанный в регистре, значения другого регистра. ==== Перемещение адреса в регистр #img(image("img/69.png", width: 70%),[```asm mov edx, k```], f:(i)=>{i.display()}) Адрес определяется в процессе копиляции, поэтому является константой. Формально для процессора мы перемещаем обычный длинный литерал. О том, что этот литерал -- адрес в оперативной памяти помнит только программист. Выпишем шеснадцатеричный код и переведем его в двоичный: ``` ba 3c a0 04 08 = 1011 1010 0011 1100 1010 0000 0000 0010 0000 0100= = 10111 010 0111100101000000000001000000100``` Эта команда подходит под шаблон `B8 + rd`, поэтому будем разбирать из него. Сама команда ```asm mov``` записана как `10111` потом идет регистр ```asm edx``` -- `010`. После записан `imm32` -- наш адрес. ==== Перемещение из регистра в регистр #img(image("img/70.png", width: 70%),[```asm mov ecx, eax```], f:(i)=>{i.display()}) ``` 89 с1 = 1000 1001 1100 0001 = 100010 01 11 000 001``` Где `100010` -- код ассемблерной команды ```asm mov```. `01` -- первое число записи означает направление, в данном случае из регистра, второе указывают на то, что операнды четырех байтовые. `11` -- указывает на то, что операнды - регистры. Далее идут номера самих регистров ```asm 000 = eax```, ```asm 001 = ecx```. ==== Перемещение из регистра в адрес в регистре #img(image("img/71.png", width: 70%),[```asm mov [ebx], eax```], f:(i)=>{i.display()}) ``` 89 03 = 1000 1001 0000 0011 = 100010 01 00 000 011``` Где `100010` -- код ассемблерной команды ```asm mov```. `01` -- первое число записи означает направление, в данном случае из регистра, второе указывают на то, что операнды четырех байтовые. `00` -- указывает на то, что смещение в команде 0 байт, это и отличает эту команду от предыдущей, т.к. теперь мы интерпретируем принимающий регистр как адрес в оперативной памяти, в который мы записываем ```asm eax``` без смещения. Далее идут номера самих регистров ```asm 000 = eax```, ```asm 011 = ebx```. == Вывод В процессе выполнения лабораторной работы были созданы, отлажены и дизассемблированны библеотеки ввода-вывода на ассемблере. Были проделаны арифметические операции, использован стек и оперативная память. Все арифметические операции были так же отлажены и дизассемблированны. Был показан механизм определения команд ассемблера на основе двоичного кода. == Контрольные вопросы 1. *Что такое машинная команда? Какие форматы имеют машинные команды процессора IA32? Чем различаются эти форматы?* Машинная команда – элементарная инструкция, задаваемая машине; ```asm mov <регистр, память>, <регистр, память, непосредственное значение> (нельзя из памяти в память)```, ```asm add <регистр, память>, <регистр, память> (нельзя память, память)```, ```asm sub <регистр, память>, <регистр, память> (нельзя память, память)```, ```asm imul <регистр, память, непосредственное значение>```, ```asm idiv <регистр, память, непосредственное значение>```. 2. *Назовите мнемоники основных команд целочисленной арифметики. Какие форматы для них можно использовать?* Мнемоники целочисленных команд: ```asm adc```, ```asm add```, ```asm sub```, ```asm sbb```, ```asm inc```, ```asm dec```, ```asm mul```, ```asm imul```, ```asm div```, ```asm idiv```;```asm adc (add) <регистр, память>, <регистр, память>```, ```asm sbb (sub) <регистр, память>, <регистр, память> ```, ```asm mul (imul) <регистр, память, непосредственное значение>```, ```asm div (idiv) <регистр, память, непосредственное значение>```. 3. *Сформулируйте основные правила построения линейной программы вычисления заданного выражения.* Нужно в секции неинициализированных данных объявить нужные переменные; выполнить системные команды ввода данных и из буфера получить символы, преобразовать их в численные значения; дальше, используя целочисленные машинные команды написать часть программы, отвечающей за вычисление; преобразовать полученное число в символьное представление, используя системную команду, вывести результат. 4. *Почему ввод-вывод на языке ассемблера не программируют с использованием соответствующих машинных команд? Какая библиотека используется для организации ввода вывода в данной лабораторной?* Для ввода-вывода используют системные команды ```asm syscall```, перед этим пишется ```asm mov rax, 0```; ```asm mov rsi, 0```; ```asm mov rdx, <размер буфера>```; ```asm mov rdi, <адрес буфера> (для ввода строки)```; ```asm mov rax, 1```; ```asm mov rsi, 1```; ```asm mov rdx, <размер буфера>```; ```asm mov rdi <адрес буфера> (для вывода строки)```. 5. *Расскажите, какие операции используют при организации ввода-вывода.* Используются команды пересылки данных и системная команда ```asm syscall```.
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/test.typ
typst
#let page-setup() = { return // you can return functions ... that allow absolute placement // you can use anchoring systems } #let margin = 0.5in #set page(margin: 0.5in, paper: "us-letter") #{ let width = 20pt let green-square = square(width, green) place(dx: -0.5in, dy: -0.5in, green-square) layout(x => { place(dx: x.width + margin - width, dy: -margin, green-square) }) let b = [aaa] rect(width: 256pt, height: auto, fill: yellow.lighten(60%)) } // if you return the value ... it doesnt display on the page
https://github.com/cdotwang/SCMB_report_template
https://raw.githubusercontent.com/cdotwang/SCMB_report_template/main/progress_report_template.typ
typst
#set page( paper: "a4", margin: (x: 3cm, y: 2cm), numbering: "1", ) // set the page size, margin and numbering #set text(size: 11pt, font: "New Computer Modern") // set the text size and font #set heading(numbering: "1.1. ") // set the heading numbering #show heading: set block(above: 2em, below: 1em) // set the space above and below the heading #set par(justify: true) // set the paragraph justification #show par: set block(above: 1.5em, below: 1em) // set the space above and below the paragraph #set list(indent: 1.5em) // set the list indentation #show figure.caption: set text(size: 0.85em) // set the text size in caption, make it smaller #set figure(gap: 1.5em) // set the gap between the figure and the caption #set math.equation(numbering: "(1)") // set the equation numbering #align(center, text(24pt)[Progress Report]) #align(center, text(24pt)[SCMB-Group Debye Institute]) #align(center, text(14pt)[Your name]) #align(center, text(14pt)[#datetime.today().display("[month repr:long] [day padding:none], [year]")])\ = Starting date, ending date Starting date: I don't know \ End date: #datetime.today().display() = Progress since last update If you want to make a fancy subheading. == #box(fill: yellow, radius: 0.3em, outset: 0.4em)[Fancy subheading] #lorem(5) - #lorem(5) - #lorem(5) This is an inline equation $x = y$. And this is a block equation: $ x = y $ Starting and ending the equation with at least one space lifts it into a block equation. $ x = (-b plus.minus sqrt(b^2 - 4 a c)) / (2 a) $ If you want to use LaTeX equation, #import "@preview/mitex:0.2.2": * #mitex(` x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} `) This is @figure_label. #figure( rect(fill: aqua, stroke: 0.1em, width: 16em, height: 9em)[#align(horizon)[An image]], // normally this would be a path to an image file // image("path/to/image.png") caption: [This is an image.], )<figure_label> And this is @table_label. #figure( table( columns: 3, align: center, [1], [2], [3], [A], [B], [C], ), caption: [This is a table.], )<table_label> // for more: https://typst.app/docs/reference/model/table/ = Immediate plans #lorem(5) = Literature #lorem(5) // #cite(<paper>) or use @ = PhD progress == Education, Conferences and Workshops #lorem(5) *Completed* - #lorem(5) *Planned* - #lorem(5) == Teaching Duties #lorem(5). = Group Contributions #lorem(5). = Submitted/Published articles #lorem(5). = Prizes/Awards/Scholarships #lorem(5). = Data Management #lorem(5). // #bibliography("your.bib", style: "american-physics-society")
https://github.com/Misaka19986/typst-template
https://raw.githubusercontent.com/Misaka19986/typst-template/main/source.typ
typst
/* set page */ #set page( header: align(right, text(9pt, weight: "thin", )[A template created by ririka]), width: 21cm, height: 29.7cm, numbering: "-1-" ) /* set heading */ #set heading(numbering: "1.") /* set body font */ #set text(14pt, font: ("Noto Serif CJK SC", "JetBrains Mono")) /* set retraction */ #set par(justify: true, first-line-indent: 2em) #show heading: it => { it par()[#text(size:0.5em)[#h(0.0em)]] } /* set figure */ #show figure.caption: set text(12pt, style: "italic") /* title */ #align(center, text( 32pt, weight: "bold", )[A useful and important research for the title]) #align(center, text( 16pt, weight: "thin", )[ririka, unknown university]) #line(length: 100%) /* text body */ = Expression This is a math expression. #align(center, $F_n = F_(n - 1) + F_(n - 2)$) = Table This is a table. #let col = 10 #let nums = range(1, col + 1) #let fib(n) = { if n <= 1 {return n} let a = 0 let b = 1 for i in range(2, n + 1){ let temp = a + b a = b b = temp } return b } #align(center, figure(table( columns: col, ..nums.map(n => $F_#n$), ..nums.map(n => str(fib(n))) ),caption: "Fib")) = Grid This is a grid with rect #set rect( inset: 8pt, fill: rgb("e4e5ea"), width: auto ) #align(center, grid( columns: 3, rows: (auto, 60pt), gutter: 3pt, rect[this is a grid], rect[1/3 remains], rect[2/3 remains], rect(height: 100%)[fixed height] )) = Code block *Style 1* #align(center, text( [```C /* A C program sample */ #include <stdio.h> int main(){ int a = 1; int b = 2; printf("res:%d\n", a+b); return 0; } ```] ))\ Use the block directly, but the statement which right follows the block will lose it's retraction. So use a '\\' to fix that. *Style 2* #align(center, table( columns: 1, )[ ```c /* A C program sample */ #include <stdio.h> int main(){ int a = 1; int b = 2; printf("res:%d\n", a+b); return 0; } ```])\ Use the 'table' to add a frame for the code. *Style 3* #show raw: it => block( fill: rgb("#1d2433"), inset: 10pt, radius: 5pt, text(fill: rgb("#a2aabc"), it), ) #align(center, text( )[```c /* A C program sample */ #include <stdio.h> int main(){ int a = 1; int b = 2; printf("res:%d\n", a+b); return 0; } ```])\ Use 'show' to change the style.
https://github.com/NwaitDev/Typst-Accessibility-Template
https://raw.githubusercontent.com/NwaitDev/Typst-Accessibility-Template/main/article_template.typ
typst
#import "Components/title.typ": print_title #import "Components/authors.typ": print_authors #import "Components/abstract.typ": print_abstract #let article_template( title:"", subtitle:"", authors:(), abstract:none, cols:1, fontsize: 12pt, doc,) = [ #set math.equation(numbering: "(1)") #set page( paper: "a4", margin: (x: 1.8cm, y: 1.5cm), background: image("Images/bg_img.jpg") ) #set text( font: "DejaVu Sans", size: fontsize, spacing: 120%, ligatures: false, ) #set heading( level: 1, numbering: "1.a.i" ) #set par( justify: true, //default value false leading: 0.65em, //default value 65em linebreaks: "optimized", // default value "optimized" first-line-indent: 0em, //default value 0em hanging-indent: 0em //default value 0em ) #show "Typst" : [#box( baseline: 0.35em, image( "Images/typst.png", alt: "Typst", height: 1.2em, ) )] #print_title(title,subtitle) #print_authors(authors) #if abstract != none { print_abstract(abstract) } #show: rest => columns(cols, rest) #doc ] //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ #show: doc => article_template( title: [Titre de l'article], subtitle:[Ceci en est le sous-titre], doc, ) This is some text in Typst and I hope it's going to lead me somewhere.
https://github.com/rowanc1/typst-book
https://raw.githubusercontent.com/rowanc1/typst-book/main/template.typ
typst
MIT License
#import "book.typ": * #show: template.with( title: "[-doc.title-]", [# if doc.subtitle #] subtitle: "[-doc.subtitle-]", [# endif #] ) [-IMPORTS-] [-CONTENT-] [# if doc.bibtex #] #{ show bibliography: set text(8pt) bibliography("[-doc.bibtex-]", title: text(10pt, "References"), style: "apa") } [# endif #]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/linebreak_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test overlong word that is not directly after a hard break. This is a spaceexceedinglylongy.
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/src/types.typ
typst
Other
#import "base-type.typ": base-type #import "assertions.typ": one-of #import "types/array.typ": array #import "types/dictionary.typ": dictionary #import "types/logical.typ": either #import "types/number.typ": number, integer, floating-point #import "types/sink.typ": sink #import "types/string.typ": string, ip, email #import "types/tuple.typ": tuple #let alignment = base-type.with(name: "alignment", types: (alignment,)) #let angle = base-type.with(name: "angle", types: (angle,)) #let any = base-type.with(name: "any") #let boolean = base-type.with(name: "bool", types: (bool,)) #let bytes = base-type.with(name: "bytes", types: (bytes,)) #let color = base-type.with(name: "color", types: (color,)) #let content = base-type.with(name: "content", types: (content, str, symbol)) #let date = base-type.with(name: "date", types: (datetime,)) #let direction = base-type.with(name: "direction", types: (direction,)) #let function = base-type.with(name: "function", types: (function,)) #let fraction = base-type.with(name: "fraction", types: (fraction,)) #let gradient = base-type.with(name: "gradient", types: (gradient,)) #let label = base-type.with(name: "label", types: (label,)) #let length = base-type.with(name: "length", types: (length,)) #let location = base-type.with(name: "location", types: (location,)) #let plugin = base-type.with(name: "plugin", types: (plugin,)) #let ratio = base-type.with(name: "ratio", types: (ratio,)) #let regex = base-type.with(name: "regex", types: (regex,)) #let relative = base-type.with( name: "relative", types: (relative, ratio, length), ) #let selector = base-type.with(name: "selector", types: (selector,)) #let stroke = base-type.with(name: "stroke", types: (stroke,)) #let symbol = base-type.with(name: "symbol", types: (symbol,)) #let version = base-type.with(name: "version", types: (version,)) #let choice(list, assertions: (), ..args) = base-type( name: "enum", ..args, assertions: (one-of(list), ..assertions), ) + ( choices: list, )
https://github.com/ecrax/packages
https://raw.githubusercontent.com/ecrax/packages/main/local/island/0.1.0/template/main.typ
typst
#import "@local/island:0.1.0": * #import "@preview/splash:0.3.0": tailwind #import "@preview/big-todo:0.2.0": * #show: island.with( lang: "de", title: "Test Island", authors: ((name: "<NAME>", matnr: "11158198"),), bibliography: bibliography("refs.bib"), ) // ================================================================= = Thema #blurb[ Das Thema *Alltagsprodukt mit Filmgenre/Stil* ist zwar generell recht abstrakt, lässt sich aber schnell durch die zur Auswahl stehenden Gegenstände eingrenzen. Ich habe mich dazu entschieden, ein Stück Holz als Parfüm darzustellen. Eine Herausforderung war es hier, Duftnoten mit einem Filmgenre zu verbinden. Insgesamt lässt sich das Endprodukt am ehesten bei den Genres Romantik und _(Contemporary)_-Fantasy einordnen. ] == Ideenfindung #col[ Zu Beginn der Ideenfindung habe ich mir ein paar Gedanken zu den einzelnen Assoziationen und Inspirationen, die ich mit dem Thema verbinde, gemacht. Mit dem Holz selber, aber auch mit dem Parfüm verbinde ich eine gewisse Natürlichkeit. Das Holz ist ein Naturprodukt und das Parfüm soll einen natürlichen Duft haben. Außerdem verbinde ich mit dem Parfüm auch eine gewisse Eleganz und Schönheit. @hahnWebdesignHandbuchZur2020 ]
https://github.com/Quaternijkon/QUAD
https://raw.githubusercontent.com/Quaternijkon/QUAD/main/main.typ
typst
#import "/config.typ": * #import "@preview/suiji:0.3.0": * #import "lib.typ":* #show: init // #show strong: alert #show strong: alert // #show strong: it=>{ // set text(fill: rgb("#EA4335")) // [#it] // } #show emph: it => { let colors = ( rgb("#4285F4"), rgb("#34A853"), rgb("#FBBC05"), rgb("#EA4335"), ) let i=1; let rng = gen-rng(it.body.text.len()); let index_pre = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); for c in it.body.text{ let rng = gen-rng(i); let index_cur = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); let cnt=100; while index_cur == index_pre and cnt>0{ let rng = gen-rng(cnt); index_cur = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); cnt -= 1; } let color = colors.at(index_cur); set text(fill: color) [#c] index_pre = index_cur; i += 1; } // for i in range(it.body.text.len()){ // let rng = gen-rng(i); // let index = integers(rng, low: 0, high: 4, size: none, endpoint: false).at(1); // let color = colors.at(index); // let char = it.body.text.at(i); // set text(fill: color) // [#char] // } } #show: slides #include "/content.typ"
https://github.com/TGM-HIT/typst-diploma-thesis
https://raw.githubusercontent.com/TGM-HIT/typst-diploma-thesis/main/template/chapters/retrospektive.typ
typst
MIT License
#import "../lib.typ": * = Retrospektive Kurz vor dem Ende wird der Verlauf des Projekts analysiert und geprüft, ob die Ziele erreicht und die Probleme gelöst wurden. Es wird auch auf Schwierigkeiten eingegangen, welche erst während der Arbeit zum Vorschein kamen und es können Verbesserungsvorschläge und Erkenntnisse vorgetragen werden. Außerdem kann auch auf den weiteren Verlauf in der Zukunft eingegangen werden.
https://github.com/deadManAlive/ui-thesis-typst-template
https://raw.githubusercontent.com/deadManAlive/ui-thesis-typst-template/master/primer/auth.typ
typst
#import "../config.typ": cfg #let auth = [ #set align(center) = Halaman Pernyataan Orisinalitas #v(6em) *Skripsi ini adalah hasil karya saya sendiri, \ dan semua sumber baik yang dikutip maupun dirujuk \ telah saya nyatakan dengan benar.* #v(6em) #table( columns: 3, align: (left, left + horizon, left + horizon), stroke: none, [Nama], [:], [#cfg.name], [NPM], [:], [#cfg.npm], [ #v(1em) Tanda Tangan #v(1em) ], [:], [......], [Tanggal], [:], [#cfg.time] ) ]
https://github.com/dantevi-other/kththesis-typst
https://raw.githubusercontent.com/dantevi-other/kththesis-typst/main/README.md
markdown
MIT License
# kththesis-typst A Typst template for writing a thesis at KTH, based on the original LaTeX template.
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/graph/mod.typ
typst
Apache License 2.0
#import "/src/book.typ" #import "/typ/templates/page.typ" #import "../mod.typ": code, exec-code
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap3/10_electric_shock_data.typ
typst
Other
=== Electric shock data The table of electric currents and their various bodily effects was obtained from online (Internet) sources: the safety page of Massachusetts Institute of Technology (website: #link("http://web.mit.edu/safety")[\[\*\]]), and a safety handbook published by Cooper Bussmann, Inc (website: #link("http://www.bussmann.com/")[\[\*\]]). In the Bussmann handbook, the table is appropriately entitled #emph[Deleterious Effects of Electric Shock], and credited to a Mr. <NAME>. Further research revealed Dalziel to be both a scientific pioneer and an authority on the effects of electricity on the human body. The table found in the Bussmann handbook differs slightly from the one available from MIT: for the DC threshold of perception (men), the MIT table gives 5.2 mA while the Bussmann table gives a slightly greater figure of 6.2 mA. Also, for the \"unable to let go\" 60 Hz AC threshold (men), the MIT table gives 20 mA while the Bussmann table gives a lesser figure of 16 mA. As I have yet to obtain a primary copy of Dalziel\'s research, the figures cited here are conservative: I have listed the lowest values in my table where any data sources differ. These differences, of course, are academic. The point here is that relatively small magnitudes of electric current through the body can be harmful if not lethal. Data regarding the electrical resistance of body contact points was taken from a safety page (document 16.1) from the Lawrence Livermore National Laboratory (website #link("http://www-ais.llnl.gov/")[\[\*\]]), citing <NAME> as the data source. Lee\'s work was listed here in a document entitled \"Human Electrical Sheet,\" composed while he was an IEEE Fellow at E.I. duPont de Nemours & Co., and also in an article entitled \"Electrical Safety in Industrial Plants\" found in the June 1971 issue of #emph[IEEE Spectrum] magazine. For the morbidly curious, <NAME>\'s experimentation conducted at the University of California (Berkeley) began with a state grant to investigate the bodily effects of sub-lethal electric current. His testing method was as follows: healthy male and female volunteer subjects were asked to hold a copper wire in one hand and place their other hand on a round, brass plate. A voltage was then applied between the wire and the plate, causing electrons to flow through the subject\'s arms and chest. The current was stopped, then resumed at a higher level. The goal here was to see how much current the subject could tolerate and still keep their hand pressed against the brass plate. When this threshold was reached, laboratory assistants forcefully held the subject\'s hand in contact with the plate and the current was again increased. The subject was asked to release the wire they were holding, to see at what current level involuntary muscle contraction (tetanus) prevented them from doing so. For each subject the experiment was conducted using DC and also AC at various frequencies. Over two dozen human volunteers were tested, and later studies on heart fibrillation were conducted using animal subjects.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/chronos/0.1.0/src/renderer.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": canvas, draw #import "utils.typ": get-participants-i, get-style #import "group.typ" #import "participant.typ" #import participant: PAR-SPECIALS #import "sequence.typ" #import "separator.typ" #import "sync.typ" #import "consts.typ": * #import "note.typ" as note: get-note-box #let DEBUG-INVISIBLE = false #let get-columns-width(participants, elements) = { participants = participants.map(p => { p.insert("lifeline-lvl", 0) p.insert("max-lifelines", 0) p }) let pars-i = get-participants-i(participants) let cells = () // Unwrap syncs let i = 0 while i < elements.len() { let elmt = elements.at(i) if elmt.type == "sync" { elements = elements.slice(0, i + 1) + elmt.elmts + elements.slice(i + 1) } i += 1 } // Compute max lifeline levels for elmt in elements { if elmt.type == "seq" { let com = if elmt.comment == none {""} else {elmt.comment} let i1 = pars-i.at(elmt.p1) let i2 = pars-i.at(elmt.p2) cells.push( ( elmt: elmt, i1: calc.min(i1, i2), i2: calc.max(i1, i2), cell: box(com, inset: 3pt) ) ) if elmt.disable-src or elmt.destroy-src { let p = participants.at(i1) p.lifeline-lvl -= 1 participants.at(i1) = p } if elmt.disable-dst { let p = participants.at(i2) p.lifeline-lvl -= 1 participants.at(i2) = p } if elmt.enable-dst { let p = participants.at(i2) p.lifeline-lvl += 1 p.max-lifelines = calc.max(p.max-lifelines, p.lifeline-lvl) participants.at(i2) = p } } else if elmt.type == "evt" { let par-name = elmt.participant let i = pars-i.at(par-name) let par = participants.at(i) if elmt.event == "disable" or elmt.event == "destroy" { par.lifeline-lvl -= 1 } else if elmt.event == "enable" { par.lifeline-lvl += 1 par.max-lifelines = calc.max(par.max-lifelines, par.lifeline-lvl) } participants.at(i) = par } else if elmt.type == "note" { let (p1, p2) = (none, none) let cell = none if elmt.side == "left" { p1 = "[" p2 = elmt.pos cell = get-note-box(elmt) } else if elmt.side == "right" { p1 = elmt.pos p2 = "]" cell = get-note-box(elmt) } else if elmt.side == "over" { if elmt.aligned-with != none { let box1 = get-note-box(elmt) let box2 = get-note-box(elmt.aligned-with) let m1 = measure(box1) let m2 = measure(box2) cell = box(width: (m1.width + m2.width) / 2, height: calc.max(m1.height, m2.height)) p1 = elmt.pos p2 = elmt.aligned-with.pos } } if p1 != none and p2 != none and cell != none { let i1 = pars-i.at(p1) let i2 = pars-i.at(p2) cells.push( ( elmt: elmt, i1: calc.min(i1, i2), i2: calc.max(i1, i2), cell: cell ) ) } } } // Compute column widths // Compute minimum widths for participant names and shapes let widths = () for i in range(participants.len() - 1) { let p1 = participants.at(i) let p2 = participants.at(i + 1) let m1 = participant.get-size(p1) let m2 = participant.get-size(p2) let w1 = m1.width let w2 = m2.width widths.push(w1 / 2pt + w2 / 2pt + PAR-SPACE) } // Compute minimum width for over notes for n in elements.filter(e => (e.type == "note" and e.side == "over" and type(e.pos) == str)) { let m = note.get-size(n) let i = pars-i.at(n.pos) if i < widths.len() { widths.at(i) = calc.max( widths.at(i), m.width / 2 + NOTE-GAP ) } if i > 0 { widths.at(i - 1) = calc.max( widths.at(i - 1), m.width / 2 + NOTE-GAP ) } } // Compute minimum width for simple sequences (spanning 1 column) for cell in cells.filter(c => c.i2 - c.i1 == 1) { let m = measure(cell.cell) widths.at(cell.i1) = calc.max( widths.at(cell.i1), m.width / 1pt + COMMENT-PAD ) } // Compute minimum width for self sequences for cell in cells.filter(c => c.elmt.type == "seq" and c.i1 == c.i2) { let m = measure(cell.cell) let i = cell.i1 if cell.elmt.flip { i -= 1 } if 0 <= i and i < widths.len() { widths.at(i) = calc.max( widths.at(i), m.width / 1pt + COMMENT-PAD ) } } // Compute remaining widths for longer sequences (spanning multiple columns) let multicol-cells = cells.filter(c => c.i2 - c.i1 > 1) multicol-cells = multicol-cells.sorted(key: c => { c.i1 * 1000 + c.i2 }) for cell in multicol-cells { let m = measure(cell.cell) widths.at(cell.i2 - 1) = calc.max( widths.at(cell.i2 - 1), m.width / 1pt + COMMENT-PAD - widths.slice(cell.i1, cell.i2 - 1).sum() ) } // Add lifeline widths for (i, w) in widths.enumerate() { let p1 = participants.at(i) let p2 = participants.at(i + 1) let w = w + p1.max-lifelines * LIFELINE-W / 2 if p2.max-lifelines != 0 { w += LIFELINE-W / 2 } widths.at(i) = w } return widths } #let render(participants, elements) = context canvas(length: 1pt, { let shapes = () let pars-i = get-participants-i(participants) let widths = get-columns-width(participants, elements) // Compute each column's X position let x-pos = (0,) for width in widths { x-pos.push(x-pos.last() + width) } let draw-seq = sequence.render.with(pars-i, x-pos, participants) let draw-group = group.render.with() let draw-sep = separator.render.with(x-pos) let draw-par = participant.render.with(x-pos) let draw-note = note.render.with(pars-i, x-pos) let draw-sync = sync.render.with(pars-i, x-pos, participants) // Draw participants (start) for p in participants { if p.from-start and not p.invisible and p.show-top { shapes += draw-par(p) } } let y = 0 let groups = () let lifelines = participants.map(_ => ( level: 0, lines: () )) // Draw elemnts for elmt in elements { // Sequences if elmt.type == "seq" { let shps (y, lifelines, shps) = draw-seq(elmt, y, lifelines) shapes += shps // Groups (start) -> reserve space for labels + store position } else if elmt.type == "grp" { y -= Y-SPACE let m = measure( box( elmt.name, inset: (left: 5pt, right: 5pt, top: 3pt, bottom: 3pt), ) ) groups = groups.map(g => { if g.at(1).min-i == elmt.min-i { g.at(2) += 1 } if g.at(1).max-i == elmt.max-i { g.at(3) += 1 } g }) groups.push((y, elmt, 0, 0)) y -= m.height / 1pt // Groups (end) -> actual drawing } else if elmt.type == "grp-end" { y -= Y-SPACE let (start-y, group, start-lvl, end-lvl) = groups.pop() let x0 = x-pos.at(group.min-i) - start-lvl * 10 - 20 let x1 = x-pos.at(group.max-i) + end-lvl * 10 + 20 shapes += draw-group(x0, x1, start-y, y, group) // Separator } else if elmt.type == "sep" { let shps (y, shps) = draw-sep(elmt, y) shapes += shps // Gap } else if elmt.type == "gap" { y -= elmt.size // Event } else if elmt.type == "evt" { let par-name = elmt.participant let i = pars-i.at(par-name) let par = participants.at(i) let line = lifelines.at(i) if elmt.event == "disable" { line.level -= 1 line.lines.push(("disable", y)) } else if elmt.event == "destroy" { line.lines.push(("destroy", y)) } else if elmt.event == "enable" { line.level += 1 line.lines.push(("enable", y, elmt.lifeline-style)) } else if elmt.event == "create" { y -= CREATE-OFFSET shapes += participant.render(x-pos, par, y: y) line.lines.push(("create", y)) } lifelines.at(i) = line // Note } else if elmt.type == "note" { if not elmt.linked { if not elmt.aligned { y -= Y-SPACE } let shps (y, shps) = draw-note(elmt, y, lifelines) shapes += shps } // Synched sequences } else if elmt.type == "sync" { let shps (y, lifelines, shps) = draw-sync(elmt, y, lifelines) shapes += shps } } y -= Y-SPACE // Draw vertical lines + lifelines + end participants shapes += draw.on-layer(-1, { if DEBUG-INVISIBLE { for p in participants.filter(p => p.invisible) { let color = if p.name.starts-with("?") {green} else if p.name.ends-with("?") {red} else {blue} let x = x-pos.at(p.i) draw.line( (x, 0), (x, y), stroke: (paint: color, dash: "dotted") ) draw.content( (x, 0), p.display-name, anchor: "west", angle: 90deg ) } } for p in participants.filter(p => not p.invisible) { let x = x-pos.at(p.i) // Draw vertical line let last-y = 0 let rects = () let destructions = () let lines = () // Compute lifeline rectangles + destruction positions for line in lifelines.at(p.i).lines { let event = line.first() if event == "create" { last-y = line.at(1) } else if event == "enable" { if lines.len() == 0 { draw.line( (x, last-y), (x, line.at(1)), stroke: ( dash: "dashed", paint: gray.darken(40%), thickness: .5pt ) ) } lines.push(line) } else if event == "disable" or event == "destroy" { let lvl = 0 if lines.len() != 0 { let l = lines.pop() lvl = lines.len() rects.push(( x + lvl * LIFELINE-W / 2, l.at(1), line.at(1), l.at(2) )) last-y = line.at(1) } if event == "destroy" { destructions.push((x + lvl * LIFELINE-W / 2, line.at(1))) } } } draw.line( (x, last-y), (x, y), stroke: ( dash: "dashed", paint: gray.darken(40%), thickness: .5pt ) ) // Draw lifeline rectangles (reverse for bottom to top) for rect in rects.rev() { let (cx, y0, y1, style) = rect let style = get-style("lifeline", style) draw.rect( (cx - LIFELINE-W / 2, y0), (cx + LIFELINE-W / 2, y1), ..style ) } // Draw lifeline destructions for dest in destructions { let (cx, cy) = dest draw.line((cx - 8, cy - 8), (cx + 8, cy + 8), stroke: COL-DESTRUCTION + 2pt) draw.line((cx - 8, cy + 8), (cx + 8, cy - 8), stroke: COL-DESTRUCTION + 2pt) } // Draw participants (end) if p.show-bottom { draw-par(p, y: y, bottom: true) } } }) shapes })
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/place-float-auto_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 2-34 floating placement must be `auto`, `top`, or `bottom` // #place(right, float: true)[Hello]
https://github.com/cliarie/resume
https://raw.githubusercontent.com/cliarie/resume/main/src.typ
typst
#import "style.typ": * #show: project #let title_items = ( link("mailto:<EMAIL>"), link("https://linkedin.com/in/cliarie")[#fab("linkedin") cliarie], link("https://github.com/cliarie")[#fab("github-alt") cliarie], ) // Title row. #align(center)[ #block(text(weight: 700, size: 1.5em)[<NAME>]) #title_items.join([#h(0.5em)•#h(0.5em)]) ] = Education #entry[ == University of Illinois, Urbana Champaign Mathematics and Computer Science, B.S. \ ][ *Expected Graduation:* May 2026\ *Grade:* 4.0/4.0\ ] *Relevant Coursework:* Systems Programming · *Distributed Systems* · Computer Architecture · Computer System Organization · Data Structures · Competitive Algorithmic Programming · Abstract Linear Algebra · Discrete Math · Complex Analysis · Real Analysis · Probability Theory = Experience #entry[ == Parasol Lab \@ UIUC _Researcher_ ][Aug 2024 - Present] - Working under Professor <NAME> to develop a distributed, open-source *C++* library for robot task and motion planning, optimizing the C++ STL for *parallel* and *distributed* execution. Focusing on enhancing performance and scalability across *multi-core systems*, improving efficiency in complex robotic tasks. #entry[ == CME Group _Software Engineer Intern_ ][May 2024 - Aug 2024] - Implemented a new feature for the market data simulator NR to allow for realistic market data generation. - Aggregated CAML-wrapped SBE binary marketdata and encoded/decoded messages with SBE/iLinkBinary protocols to maintain an orderbook and skew marketdata effectively; simulated traders with self prevention ids to place orders in NR. - Streamed marketdata with *Kafka* and *Cloud* *Pub/Sub* and handled concurrency with a *ring buffer* to reduce contention. - Reconciled incoming marketdata by keeping track of TOB orders and variable tick size instruments and increments. - Utilized *Java* and Spring Boot for backend development, ran Cucumber and Mockito for integration testing and creating Mock servers and gateway endpoints, and *GKE GCP* for *cloud containerization and deployment*. #entry[ == AMD --- Disruption Lab _Software Engineer_ ][Jan 2024 - May 2024] - Optimized AMD Mic performance by efficiently categorizing and removing unwanted noise leveraging DL algorithms. - Constructed state-of-the-art audio separation model Sepformer in PyTorch on *AWS Sagemaker* to handle sources of different noise scales with reverberation and background noise. - Ported PyTorch models into *ONNX* to run on AMD hardware. // #entry[ // == ACM \@ UIUC // _Software Engineer_ // ][Aug 2023 - May 2024] // - Developed a resume book for companies to filter and network with students in Association for Computing Machinery. // - Handled login flow and backend, and linked and stored user information in AWS database with Boto3. // - Designed profile cards for each registered student displaying degree, skills, graduation year, etc. #entry[ == A*Star _Software Engineer, Machine Learning Engineer_ ][Aug 2023 - Jan 2024] - Allowed operators to use natural language to query unstructured information in a knowledge base of financial information for an AI Fintech startup. - Enabled efficient context formation in conversations and the ability to recall past conversations with no context loss by constructing novel knowledge graphs; cross tested loss and accuracy by implementing LLMs for the same task. - Implemented accurate detection of pages with useful tabular data and PDF parsing by leveraging GPT-4 and *Azure*. #entry[ == UC Santa Barbara Vision Research Lab _Computer Vision Research Engineer_ ][Jun 2023 - Aug 2023] - Conducted biomedical image analysis of distinguishing viral pneumonia COVID-19 from other forms of viral pneumonia through deep learning multi-class image classification. - Innovated novel two layer stacked ensemble method incorporating transfer learning, hyperparameter tuning, image preprocessing, and ensemble learning that achieved 21.37% improved accuracy to baseline ResNet50. // #entry[ // == Lynbrook Mobile App // _Lead Developer_ // ][Apr 2022 - Aug 2023] // - Led mobile app development team and integrated school, student organization, faculty, and sports events onto the app. // - Liaised between student body, faculty, school board, and development team and handled requests from all clients to keep app prevalent to the student body; app assists 40 school-wide events, 20+ clubs, and serves 1.9k users annually. // - Worked with React Native and TypeScript, led team of 5 developers, and trained 3 underclassmen. = Projects #entry[ == Exchange Simulator _C++ · CMake_ ][] - Built a stock exchange simulator in C++ following NASDAQ ITCH protocol optimizing *low latency* and *high throughput*. - Ensured *thread safety* and minimized contention by using lock-free SPMC queue and atomic operations. - Optimized matching engine to constant time order operations with no overhead and near constant best prices order search with good CPU cache locality by using preallocated data structures. // #entry[ // == SnackSafe App // _React · NextJS · Supabase_ // ][] // - Developed a lightweight web app that generates suitable restaurants for people with dietary restrictions. // - Populated restaurant data such as description, hours, distance, initial reviews, etc. in database using Yelp API. // - Implemented login flow using Supabase's Google OAuth Provider save their allergen preferences. // #entry[ // == Gradient Boosting on Identifying Age-Related Conditions // _Python · TensorFlow_ // ][] // - Analyzed a dataset of over fifty anonymized health characteristics linked to three age-related conditions to predict patients’ conditions for the InVitro Cell Research Company. // - Leveraged gradient boosting (CatBoost, LightBoost, XGBM) to build ML model and handled dataset imbalances. = Technical Skills #let TeX = style(styles => { set text(font: "New Computer Modern") let e = measure("E", styles) let T = "T" let E = text(1em, baseline: e.height * 0.31, "E") let X = "X" box(T + h(-0.15em) + E + h(-0.125em) + X) }) #let LaTeX = style(styles => { set text(font: "New Computer Modern") let a-size = 0.66em let l = measure("L", styles) let a = measure(text(a-size, "A"), styles) let L = "L" let A = box(scale(x: 105%, text(a-size, baseline: a.height - l.height, "A"))) box(L + h(-a.width * 0.67) + A + h(-a.width * 0.25) + TeX) }) *Languages and Frameworks:* C++ · Java · Python · C · Go · MIPS Assembly · SQL · Typescript · Verilog · Spring Boot · React *Development Tools and Platforms:* Git · CMake · Kubernetes · Docker · Kafka · RabbitMQ · Maven · JUnit · Mockito *Cloud Tools:* GKE/GCP · AWS · Supabase · Firebase · PyTorch · ONNX · Azure · Sagemaker
https://github.com/f14-bertolotti/bedlam
https://raw.githubusercontent.com/f14-bertolotti/bedlam/main/src/probability-theory/main.typ
typst
#import "../measure-theory/introduction.typ" : sigma-algebra-product, measure, measure-space #import "../theme.typ": example, definition, comment = Probability Theory #let probability-space = ( tag : link(<probability-space>)[probability space] ) #definition("Probability Space")[ $(Omega, Sigma, p)$ is said a *probability space* iff. 1. $(Omega, Sigma, p)$ is a #measure-space.tag. 2. $p(Omega) = 1$. ]<probability-space> Intuitively, #sym.Omega represents the set of all possible outcomes, it is also known as *sample space*. #sym.Sigma represents the set of all possible events. These are nothing more than set of outcomes. It is also known as *event space*. $p$ is a #measure.tag on the event space, it is also known as *probability function*. It maps events to their likelihood. #example("Fair Die")[ Consider the #probability-space.tag $(Omega, Sigma, p)$, where: 1. $Omega = {1, 2, 3, 4, 5, 6}$ is the sample space, representing the possible outcomes of rolling a standard six-sided die. 2. $Sigma = 2^Omega$ is the event space. 3. $p: Sigma --> [0, 1]$ is the probability #measure.tag function, defined as $P(E) = (|E|)/6$ for any event $E in Sigma$. For example, consider the event $A = {1, 2, 3}$, which represents rolling a 1, 2, or 3. This event is an element of $Sigma$. The probability of event $A$ occurring is $p(A) = (|A|)/6 = 3/6 = 1/2$. ] #let coupling = ( tag : link(<coupling>)[coupling] ) #definition("Coupling")[ Let $(Omega_1, Sigma_1, mu_1)$ and $(Omega_2, Sigma_2, mu_2)$ be #text[#probability-space.tag]s. A *coupling* is a #probability-space.tag $(Omega_1 times Omega_2, Sigma_1 #sigma-algebra-product.sym Sigma_2, gamma)$ such that: 1. $forall E in Sigma_1: gamma(E times Omega_2)=mu_1(E)$. #comment[The left marginal of $gamma$ is $mu_1$]. 2. $forall E in Sigma_2: gamma(Omega_1 times E)=mu_2(E)$. #comment[The right marginal of $gamma$ is $mu_2$]. ]<coupling> #example("Coupling a Dice and a Coin")[ Consider a #probability-space.tag $cal(F)_1 = (Omega_1={1,2,3,4}, Sigma_1=2^(Omega_1), p_1 = A |-> (|A|)/4)$ #comment[(The #probability-space.tag corresponding to a 4 sided die)]. Further, consider a #probability-space.tag $cal(F)_2=(Omega_2={1,2}, Sigma_2=2^(Omega_2), p_2=A |-> (|A|)/2)$ #comment[(The #probability-space.tag corresponding to a coin)]. We can define a #probability-space.tag $cal(F)=(Omega_1 times Omega_2, Sigma_1 times.circle Sigma_2, p)$ by #coupling.tag $cal(F)_1$ and $cal(F)_2$. Here, sample space and event space are already decided, we need to provide only a proper #measure.tag $p$. Such a #measure.tag can be built by providing a #coupling.tag table: $ mat( p , {1} , {2} , {3} , {4} , p_1; {1} , 1/4 , 0 , 1/4 , 0 , 1/2; {2} , 0 , 1/4 , 0 , 1/4 , 1/2; p_2 , 1/4 , 1/4 , 1/4 , 1/4 , 1; ) $ On the top row, we have the possible singleton events from $cal(F)_1$. On the left column, we have the possible singleton event from $cal(F)_2$. The last row and column corresponds to marginal distributions. These marginals match $p_2$ and $p_1$ as required by the definition of #coupling.tag. The central body of this matrix represents join probabilities of the die and coin. For example, $p({1} times {3})=1/4$. Note that we could fill this matrix in such a way that we have a #probability-space.tag but not a #coupling.tag by breaking the marginal axioms. Retrieving event probabilities from singleton events is only matter of applying traditional probability rules. ]
https://github.com/alejandrgaspar/pub-analyzer
https://raw.githubusercontent.com/alejandrgaspar/pub-analyzer/main/docs/acknowledgement.md
markdown
MIT License
# Acknowledgements ## Projects we use Pub Analyzer is the result of the work of many people, not just the author and the contributors of the project. Behind there is a lot of effort from big projects that make all this possible. That is why we want to recognize them in this section and we also invite you to support them. ### <a href="https://openalex.org/" target="_blank">OpenAlex</a> The collection and the accuracy of the information are fundamental characteristics for Pub Analyzer. This is possible thanks to OpenAlex, which is our main source of information and which provides a well-documented API that we use in our application. From Pub Analyzer we are eternally grateful to [OurResearch](https://ourresearch.org/){target=_blank} for their great work with OpenAlex. If this project has benefited you, it is largely thanks to them, so we ask you to consider writing a [testimonial](https://forms.monday.com/forms/4d5ad5a8e6a72ae31987a29118f1d437){target=_blank} and thanking them on our behalf. ### <a href="https://docs.pydantic.dev/" target="_blank">Pydantic</a> Pydantic is the fundamental piece to manage all the data we receive from OpenAlex. It allows us to validate large amounts of information and export it in JSON format.This library has become essential in practically any python project that requires validating data. ### <a href="https://textual.textualize.io/" target="_blank">Textual</a> If you had wondered how Pub Analyzer displayed such complex graphical interfaces in the Terminal, well this is thanks to Textual. The terminal is an environment that was clearly not intended to deploy this type of project, but the folks at [Textualize](https://www.textualize.io/) have made this possible. ### <a href="https://typst.app/" target="_blank">Typst</a> Exporting PDF reports is probably one of the features I'm most proud of in Pub Analyzer. Typically, this feature is implemented in other applications using dependencies installed on the system. Pub Analyzer took another approach, using the Typst compiler built into the package, to export the reports. This, in addition to allowing us to be a cross-platform package with batteries included, allows users to later customize their reports using the Typst syntax. ## Sponsors ### <a href="http://siabuc.ucol.mx/rebuc/" target="_blank">ReBUC</a> <figure> <a href="http://siabuc.ucol.mx/rebuc/" target="_blank" title="ReBUC"><img src="/assets/img/sponsors/rebuc.png" alt="ReBUC" width="275"></a> </figure>
https://github.com/npikall/vienna-tech
https://raw.githubusercontent.com/npikall/vienna-tech/main/template/appendix.typ
typst
The Unlicense
#import "@preview/vienna-tech:0.1.1": * Ein möglicher Anhang sollte direkt nach dem Literaturverzeichnis ohne Seitenumbruch angeführt werden. Jede Anhangüberschrift wird wie eine normale Überschrift eingeleitet, jedoch gibt es keine Nummerierung. Es empfiehlt sich den Anhang bzw. alle Kapitel in einer eigenen Datei zu schreiben und diese dann in die Hauptdatei einzubinden. Dies kann durch den Befehl `#include` erfolgen. = Allgemeine Hinweise == Anhang: Schreiben einer wissenschaftlichen Arbeit === Tipps: Schreiben einer wissenschaftlichen Arbeit mit Typst Generell stellt sich für uns das Problem, nun mit Typst einfach und rasch eine wissenschaftliche Arbeit zu schreiben. Den Inhalt nimmt uns Typst leider nicht ab, dafür sind wir selbst verantwortlich. Jedoch können wir uns bei Typst auf einige Vorteile verlassen, die wir hier näher betrachten möchten. Vorweg sei die konsistente Formatierung genannt, die kurz Kompilationsdauer und die äußerst intuitive Bedienung. Weiters wollen wir uns mit generellen Anforderungen an wissenschaftliche Arbeiten beschäftigen. Die Erstellung der Gliederung und des Aufbaus einer wissenschaftlichen Arbeit sind meist der erste Schritt für jede Autorin bzw. jeden Autor. Danach beschäftigt uns der Inhalt, denn jeder dieser Punkte bei der Gliederung will auch mit sinnvollem Inhalt gefüllt sein. Ausreichendes Datenmaterial (Zahlen, Daten, Fakten) sollte dann gesammelt werden oder sein. Gute Bilder, ansprechende Diagramme und aussagekräftige Tabellen helfen jeder Leserin und jedem Leser bei der Erfassung des wissenschaftlichen Inhalts. === Vorgehensweise: Gliederung und Aufbau Meist ist der erste Schritt einer wissenschaftlichen Arbeit die Erstellung einer Gliederung der Arbeit (entspricht meist grob dem Inhaltsverzeichnis). Diese wird dann mit den Betreuern der Arbeit besprochen. Die folgende Aufzählung zeigt so eine sinnvolle Gliederung einer wissenschaftlichen Arbeit: - Titelblock mit Abstract + Einleitung + Problemstellung, Motivation + Vorgehensweise + Definitionen und Abgrenzungen + Hauptteil (eigene Arbeiten inkl. Ergebnisse) + Zusammenfassung und Schlussfolgerungen (Bewertung und Ausblick) - Literaturverzeichnis und Anhang Nach der Gliederung des Dokuments ist auch die Inhaltliche Strukturierung wichtig. Dabei kann man sich an die sog. _IMRaD-Struktur_ halten. Diese steht für Introduction, Methods, Results and Discussion. + Einleitung: Wozu wird die Arbeit verfasst? - Was ist das Thema? - Grund der Erforderlichkeit der Arbeit + Methoden: Wie wurde die Arbeit durchgeführt? - Was wurde erforscht? (Materialien, Nobilität, Geräusche,...) - Wie wurde erforscht? (gesammelte Daten) - Wie wurde analysiert? (statistische Tests) + Ergebnisse: Was ist in der Arbeit herausgekommen? - Ergebnissteil soll Methodenteil spiegeln - alles aus dem Methodenteil sollte im Ergebnisteil wiederzufinden sein + Diskussion: Na und was bedeutet das jetzt? - Interpretation der Ergebnisse - Reflexion möglicher Schwächen - breitere Implikationen (z.b. für die Praxis) - Ausblick auf weitere Forschung
https://github.com/Isaac-Fate/booxtyp
https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/cover.typ
typst
Apache License 2.0
#import "colors.typ": color-schema #let cover( title, image-content, authors: (), bar-color: color-schema.orange.primary, ) = { // Set page set page(margin: (x: 0pt, y: 0pt)) // Cover image set image(width: 100%, height: 40%) image-content // Remove the whitespace between the image and the rectangle v(-14pt) // Rectangle rect(width: 100%, height: 10%, fill: bar-color) block(inset: 12pt)[ // Book title #text(weight: "extrabold", size: 32pt)[ #title ] // Some space #v(12pt) // Authors #text(weight: "bold", size: 16pt, fill: color-schema.gray.primary)[ #authors.join(v(0pt)) ] ] // Reset page counter counter(page).update(0) }
https://github.com/imatpot/typst-ascii-ipa
https://raw.githubusercontent.com/imatpot/typst-ascii-ipa/main/src/lib/converters/sil.typ
typst
MIT License
// https://help.keyman.com/keyboard/sil_ipa/1.8.7/sil_ipa // https://en.wikipedia.org/wiki/Comparison_of_ASCII_encodings_of_the_International_Phonetic_Alphabet #let sil-unicode = ( ("!", "ǃ"), ("!<", "ǀ"), ("!=", "ǂ"), ("!>", "ǁ"), ("#!", "ꜞ"), ("##!", "ꜟ"), ("#&", "͡"), ("#<", "ꜜ"), ("#<<", "↘"), ("#=", "͜"), ("#>", "ꜛ"), ("#>>", "↗"), ("$", "̩"), ("$$", "̯"), ("$$$", "̰"), ("$$$$", "̢"), ("%", "̥"), ("%%", "̬"), ("%%%", "̤"), ("%%%%", "̡"), ("*", "̈"), ("**", "̽"), ("***", "̆"), ("****", "̇"), ("*****", "̐"), ("+", "̟"), ("++", "̝"), ("+++", "̘"), ("++++", "̹"), (".", "."), (".<", "|"), (".=", "‖"), (":", "ː"), ("::", "ˑ"), (":::", "ːː"), ("=>", "→"), ("?<", "ʕ"), ("?=", "ʔ"), ("@", "̊"), ("@&", "͜"), ("@0", "̏"), ("@1", "̀"), ("@12", "᷅"), ("@13", "̌"), ("@131", "᷈"), ("@2", "̄"), ("@21", "᷆"), ("@23", "᷄"), ("@3", "́"), ("@31", "̂"), ("@313", "᷉"), ("@32", "᷇"), ("@4", "̋"), ("@@", "̍"), ("B=", "ʙ"), ("E<", "œ"), ("E=", "ɘ"), ("E>", "ɶ"), ("G=", "ɢ"), ("G>", "ʛ"), ("H=", "ʜ"), ("H>", "ɧ"), ("I=", "ɨ"), ("L<", "ʎ"), ("L=", "ʟ"), ("L>", "ɺ"), ("N=", "ɴ"), ("O<", "ɞ"), ("O=", "ɵ"), ("O>", "ɤ"), ("Q<", "ʢ"), ("Q=", "ʡ"), ("R<", "ɻ"), ("R=", "ʀ"), ("R>", "ʁ"), ("U=", "ʉ"), ("[[", "ʽ"), ("[[[", "˞"), ("]]", "ʼ"), ("]]]", "̚"), ("]]]]", "ʻ"), ("_", "̠"), ("__", "̞"), ("___", "̙"), ("____", "̜"), ("_____", "̧"), ("a<", "æ"), ("a=", "ɑ"), ("a>", "ɐ"), ("b", "b"), ("b=", "β"), ("b>", "ɓ"), ("c", "c"), ("c<", "ɕ"), ("c=", "ç"), ("d", "d"), ("d<", "ɖ"), ("d=", "ð"), ("d>", "ɗ"), ("e", "e"), ("e<", "ɛ"), ("e=", "ə"), ("e>", "ɜ"), ("f", "f"), ("f=", "ɸ"), ("g<", "ɡ"), ("g=", "ɣ"), ("g>", "ɠ"), ("h", "h"), ("h<", "ɦ"), ("h=", "ɥ"), ("h>", "ħ"), ("i", "i"), ("i=", "ɪ"), ("j", "j"), ("j<", "ʝ"), ("j=", "ɟ"), ("j>", "ʄ"), ("k", "k"), ("l", "l"), ("l<", "ɭ"), ("l=", "ɬ"), ("l>", "ɮ"), ("m", "m"), ("m>", "ɱ"), ("n", "n"), ("n<", "ɳ"), ("n=", "ɲ"), ("n>", "ŋ"), ("o", "o"), ("o<", "ɔ"), ("o=", "ɒ"), ("o>", "ø"), ("p", "p"), ("p=", "ʘ"), ("q", "q"), ("r", "r"), ("r<", "ɽ"), ("r=", "ɹ"), ("r>", "ɾ"), ("s", "s"), ("s<", "ʂ"), ("s=", "ʃ"), ("s>", "σ"), ("t", "t"), ("t<", "ʈ"), ("t=", "θ"), ("u", "u"), ("u<", "ʊ"), ("u=", "ɯ"), ("u>", "ʌ"), ("v", "v"), ("v<", "ⱱ"), ("v=", "ʋ"), ("w", "w"), ("w=", "ʍ"), ("w>", "ɰ"), ("x", "x"), ("x=", "χ"), ("y", "y"), ("y<", "ɥ"), ("y=", "ʏ"), ("z", "z"), ("z<", "ʐ"), ("z=", "ʒ"), ("z>", "ʑ"), ("{", "̪"), ("{{", "̺"), ("{{{", "̻"), ("{{{{", "̼"), ("{{{{{", "̣"), ("}", "ˈ"), ("}}", "ˌ"), ("}}}", "͈"), ("}}}}", "᷂"), ("~", "̃"), ("~~", "̴"), ).sorted( key: (pair) => -pair.at(0).len() ) #let sil-tones = ( "&": ( ("0", "꜖"), ("1", "꜕"), ("2", "꜔"), ("3", "꜓"), ("4", "꜒"), ), "#": ( ("0", "˩"), ("1", "˨"), ("2", "˧"), ("3", "˦"), ("4", "˥"), ), ) #let sil-superscript = ( ("-", "⁻"), ("0", "⁰"), ("1", "¹"), ("2", "²"), ("3", "³"), ("4", "⁴"), ("5", "⁵"), ("6", "⁶"), ("7", "⁷"), ("8", "⁸"), ("9", "⁹"), ("a", "ᵃ"), ("b", "ᵇ"), ("c", "ᶜ"), ("d", "ᵈ"), ("e", "ᵉ"), ("f", "ᶠ"), ("g", "ᵍ"), ("h", "ʰ"), ("i", "ⁱ"), ("j", "ʲ"), ("k", "ᵏ"), ("l", "ˡ"), ("m", "ᵐ"), ("n", "ⁿ"), ("o", "ᵒ"), ("p", "ᵖ"), ("q", "𐞥"), ("r", "ʳ"), ("s", "ˢ"), ("t", "ᵗ"), ("u", "ᵘ"), ("v", "ᵛ"), ("w", "ʷ"), ("x", "ˣ"), ("y", "ʸ"), ("z", "ᶻ"), ("¡", "ꜞ"), ("æ", "𐞃"), ("ç", "ᶜ̧"), ("ð", "ᶞ"), ("ø", "𐞢"), ("ħ", "𐞕"), ("ŋ", "ᵑ"), ("œ", "ꟹ"), ("ǀ", "𐞶"), ("ǁ", "𐞷"), ("ǂ", "𐞸"), ("ǃ", "ꜝ"), ("ɐ", "ᵄ"), ("ɑ", "ᵅ"), ("ɒ", "ᶛ"), ("ɓ", "𐞅"), ("ɔ", "ᵓ"), ("ɖ", "𐞋"), ("ɗ", "𐞌"), ("ɘ", "𐞎"), ("ə", "ᵊ"), ("ɛ", "ᵋ"), ("ɜ", "ᶟ"), ("ɞ", "𐞏"), ("ɟ", "ᶡ"), ("ɠ", "𐞓"), ("ɢ", "𐞒"), ("ɣ", "ˠ"), ("ɤ", "𐞑"), ("ɦ", "ʱ"), ("ɨ", "ᶤ"), ("ɪ", "ᶦ"), ("ɬ", "𐞛"), ("ɭ", "ᶩ"), ("ɮ", "𐞞"), ("ɯ", "ᵚ"), ("ɰ", "ᶭ"), ("ɱ", "ᶬ"), ("ɲ", "ᶮ"), ("ɳ", "ᶯ"), ("ɴ", "ᶰ"), ("ɵ", "ᶱ"), ("ɶ", "𐞣"), ("ɸ", "ᶲ"), ("ɹ", "ʴ"), ("ɺ", "𐞦"), ("ɻ", "ʵ"), ("ɽ", "𐞨"), ("ɾ", "𐞩"), ("ʀ", "𐞪"), ("ʁ", "ʶ"), ("ʂ", "ᶳ"), ("ʃ", "ᶴ"), ("ʄ", "𐞘"), ("ʈ", "𐞯"), ("ʉ", "ᶶ"), ("ʊ", "ᶷ"), ("ʋ", "ᶹ"), ("ʌ", "ᶺ"), ("ʎ", "𐞠"), ("ʏ", "𐞲"), ("ʐ", "ᶼ"), ("ʒ", "ᶾ"), ("ʔ", "ˀ"), ("ʕ", "ˤ"), ("ʘ", "𐞵"), ("ʙ", "𐞄"), ("ʛ", "𐞔"), ("ʜ", "𐞖"), ("ʝ", "ᶨ"), ("ʟ", "ᶫ"), ("ʡ", "𐞳"), ("ʢ", "𐞴"), ("ʣ", "𐞇"), ("ʤ", "𐞊"), ("ʦ", "𐞬"), ("ʧ", "𐞮"), ("ː", "𐞁"), ("ˑ", "𐞂"), ("β", "ᵝ"), ("θ", "ᶿ"), ("χ", "ᵡ"), ("ᵻ", "ᶧ"), ("ᶑ", "𐞍"), ("ⱱ", "𐞰"), ("ꞎ", "𐞝"), ("ꭦ", "𐞈"), ("ꭧ", "𐞭"), ("𝼄", "𐞜"), ("𝼅", "𐞟"), ("𝼆", "𐞡"), ("𝼈", "𐞧"), ("𝼊", "𐞹"), ) #let sil-subscript = ( ("0", "₀"), ("1", "₁"), ("2", "₂"), ("3", "₃"), ("4", "₄"), ("5", "₅"), ("6", "₆"), ("7", "₇"), ("8", "₈"), ("9", "₉"), ) #let sil-retroflex = ( ("a", "ᶏ"), ("ɑ", "ᶐ"), ("ɗ", "ᶑ"), ("e", "ᶒ"), ("ɛ", "ᶓ"), ("ɜ", "ᶔ"), ("ə", "ᶕ"), ("i", "ᶖ"), ("ɔ", "ᶗ"), ("ʃ", "ᶘ"), ("u", "ᶙ"), ("ʒ", "ᶚ"), ) #let sil-palatal = ( ("b", "ᶀ"), ("d", "ᶁ"), ("f", "ᶂ"), ("ɡ", "ᶃ"), ("k", "ᶄ"), ("l", "ᶅ"), ("m", "ᶆ"), ("n", "ᶇ"), ("p", "ᶈ"), ("r", "ᶉ"), ("s", "ᶊ"), ("ʃ", "ᶋ"), ("v", "ᶌ"), ("x", "ᶍ"), ("z", "ᶎ"), ) #let sil-velar-pharyngeal = ( ("b", "ᵬ"), ("d", "ᵭ"), ("f", "ᵮ"), ("l", "ɫ"), ("m", "ᵯ"), ("n", "ᵰ"), ("p", "ᵱ"), ("r", "ᵲ"), ("ɾ", "ᵳ"), ("s", "ᵴ"), ("z", "ᵵ"), ("z", "ᵶ"), ) #let parse-retroflex(text, reverse: false) = { if reverse { for (normal, retroflex) in sil-retroflex { text = text.replace(retroflex, normal + "̢") } } else { for (normal, retroflex) in sil-retroflex { text = text.replace(normal + "̢", retroflex) } } return text } #let parse-palatal(text, reverse: false) = { if reverse { for (normal, palatal) in sil-palatal { text = text.replace(palatal, normal + "̡") } } else { for (normal, palatal) in sil-palatal { text = text.replace(normal + "̡", palatal) } } return text } #let parse-velar-pharyngeal(text, reverse: false) = { if reverse { for (normal, velar-pharyngeal) in sil-velar-pharyngeal { text = text.replace(velar-pharyngeal, normal + "̴") } } else { for (normal, velar-pharyngeal) in sil-velar-pharyngeal { text = text.replace(normal + "̴", velar-pharyngeal) } } return text } #let parse-tones(text, reverse: false) = { let left-tones = sil-tones.at("&") let right-tones = sil-tones.at("#") let (from, to) = if reverse { (1, 0) } else { (0, 1) } let get-tone-regex(tones, prefix) = { return if reverse { regex("((" + tones.map(tone => tone.at(1)).join("|") + "){1, 3})") } else { regex(prefix + "([0-4]{1, 3})") } } let left-tone-regex = get-tone-regex(left-tones, "&") let right-tone-regex = get-tone-regex(right-tones, "#") let match-tones(text, regex) = { return text .matches(regex) .dedup(key: (match) => match.text) .sorted(key: (match) => -match.captures.at(0).len()) // Avoid partial matches } let left-matches = match-tones(text, left-tone-regex) let right-matches = match-tones(text, right-tone-regex) let replace-matches(text, matches, tones, prefix) = { for match in matches { let replacement = match.captures.at(0) for tone in tones { replacement = replacement.replace(tone.at(from), tone.at(to)) } if reverse { replacement = prefix + replacement } text = text.replace(match.text, replacement) } return text } text = replace-matches(text, left-matches, left-tones, "&") text = replace-matches(text, right-matches, right-tones, "#") return text } #let parse-subscript(text, reverse: false) = { if reverse { for (normal, sub) in sil-subscript { text = text.replace(sub, normal + "̠") } } else { for (normal, sub) in sil-subscript { text = text.replace(normal + "̠", sub) } } return text } #let parse-superscript(text, reverse: false) = { if reverse { for (normal, super) in sil-superscript { text = text.replace(super, normal + "^") } } else { for (normal, super) in sil-superscript { text = text.replace(normal + "^", super) } } return text } #let convert-sil(text, reverse: false) = { let run-parsers(text) = { text = parse-retroflex(text, reverse: reverse) text = parse-palatal(text, reverse: reverse) text = parse-velar-pharyngeal(text, reverse: reverse) text = parse-subscript(text, reverse: reverse) text = parse-tones(text, reverse: reverse) // requires all previous parsers to run first text = parse-superscript(text, reverse: reverse) return text } if reverse { text = run-parsers(text) } let (from, to) = if reverse { (1, 0) } else { (0, 1) } for pair in sil-unicode { text = text.replace(pair.at(from), pair.at(to)) } if not reverse { text = run-parsers(text) } return text }
https://github.com/arthurcadore/typst-intelbras
https://raw.githubusercontent.com/arthurcadore/typst-intelbras/main/reports/example-confidential-ptbr.typ
typst
MIT License
#import "../templates/report-confidential-ptbr.typ": * #import "@preview/codelst:2.0.1": sourcecode #show: doc => report( title: "Relatório de Teste de API Intelbras", subtitle: "ITB Redes Empresariais - Projetos Especiais", authors: "<NAME>", date: "02 de Maio de 2023", doc, ) = Objetivo #lorem(10) == Objetivo1 #lorem(40) == Objetivo2 #lorem(40) = Testes aplicados #lorem(10) #figure( figure( image("../pictures/example.png"), numbering: none, caption: [Descrição da imagem de exemplo] ), caption: figure.caption([Elaborada pelo Autor], position: top) ) Código correspondente a imagem acima: #sourcecode[```matlab close all; clear all; clc; % Defining the font size for the plots. set(0, 'DefaultAxesFontSize', 20); % Defining the signals amplitude. A_modulating = 1; A_carrier = 1; % Defining the signals frequency f_modulating = 10000; f_carrier = 150000; % modulator sensibility for frequency variation (Hz/volts) k_f = 150000; % Delta variable, correponding to max frequency variation. d_f = k_f*A_modulating; % Beta variable, correspondig to percentage of frequency variation about the frequency of the modulating. b = d_f/f_modulating; % Defining the period and frequency of sampling: fs = 50*f_carrier; Ts = 1/fs; T = 1/f_modulating; % Defining the sinal period. t_inicial = 0; t_final = 2; % "t" vector, correspondig to the time period of analysis, on time domain. t = [t_inicial:Ts:t_final]; % Defining carrier and modulating signals (for plot purpuses). carrier_signal = A_carrier * cos(2*pi*f_carrier*t); modulating_singal = A_modulating *cos(2*pi*f_modulating*t); % Creating the FM modulated signal: phase_argument = 2*pi*k_f*cumsum(modulating_singal)*Ts; modulated_signal = A_carrier * cos(2*pi*f_carrier*t + phase_argument); ```] == Teste 1 #lorem(40) == Teste 2 #lorem(40) = Resultados obtidos #lorem(10) == Resultado 1 #lorem(40) == Resultado 2 #lorem(40) === Seção 1 do resultado 2 === Seção 2 do resultado 2 = Conclusão #lorem(40) = Referências Bibliográficas: Para o desenvolvimento deste relatório, foi utilizado os seguintes materiais de referência: - #link("http://asdasdadsasdadasd.com")[Nome do link] - #link("http://asdasdadsasdadasd.com")[Nome do link] - #link("http://asdasdadsasdadasd.com")[Nome do link] - #link("http://asdasdadsasdadasd.com")[Nome do link]
https://github.com/Jacobgarm/typst_linalg
https://raw.githubusercontent.com/Jacobgarm/typst_linalg/master/pkg/lib.typ
typst
The Unlicense
#let p = plugin("./linalg.wasm") #let mat_bytes(m) = bytes(m.rows.map(row => row.map(item => item.text.replace("−","-")).join(",")).join(";")) #let bytes_mat(b) = math.mat(..str(b).split(";").map(row_s => row_s.split(",").map(entry_s => float(entry_s)))) #let vec_bytes(v) = bytes(v.map(item => str(item).replace("−","-")).join(",")) #let bytes_vec(b) = str(b).split(",").map(entry_s => float(entry_s)) #let num_bytes(n) = bytes(str(n).replace("−","-")) #let bytes_num(b) = float(str(b)) #let add(m1, m2) = bytes_mat(p.add(mat_bytes(m1), mat_bytes(m2))) #let sub(m1, m2) = bytes_mat(p.sub(mat_bytes(m1), mat_bytes(m2))) #let mul(m1, m2) = bytes_mat(p.mul(mat_bytes(m1), mat_bytes(m2))) #let mul_vec(m, v) = bytes_vec(p.mul_vec(mat_bytes(m), vec_bytes(v))) #let rowswap(m, r1, r2) = bytes_mat(p.rowswap(mat_bytes(m), num_bytes(r1), num_bytes(r2))) #let REF(m) = bytes_mat(p.REF(mat_bytes(m))) #let RREF(m) = bytes_mat(p.RREF(mat_bytes(m))) #let inverse(m) = bytes_mat(p.inverse(mat_bytes(m))) #let exp(m) = bytes_mat(p.exp(mat_bytes(m))) #let pow(m, i) = bytes_mat(p.pow(mat_bytes(m), num_bytes(i))) #let det(m) = bytes_num(p.det(mat_bytes(m))) #let trace(m) = bytes_num(p.trace(mat_bytes(m)))
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-3200.typ
typst
Apache License 2.0
#let data = ( ("PARENTHESIZED HANGUL KIYEOK", "So", 0), ("PARENTHESIZED HANGUL NIEUN", "So", 0), ("PARENTHESIZED HANGUL TIKEUT", "So", 0), ("PARENTHESIZED HANGUL RIEUL", "So", 0), ("PARENTHESIZED HANGUL MIEUM", "So", 0), ("PARENTHESIZED HANGUL PIEUP", "So", 0), ("PARENTHESIZED HANGUL SIOS", "So", 0), ("PARENTHESIZED HANGUL IEUNG", "So", 0), ("PARENTHESIZED HANGUL CIEUC", "So", 0), ("PARENTHESIZED HANGUL CHIEUCH", "So", 0), ("PARENTHESIZED HANGUL KHIEUKH", "So", 0), ("PARENTHESIZED HANGUL THIEUTH", "So", 0), ("PARENTHESIZED HANGUL PHIEUPH", "So", 0), ("PARENTHESIZED HANGUL HIEUH", "So", 0), ("PARENTHESIZED HANGUL KIYEOK A", "So", 0), ("PARENTHESIZED HANGUL NIEUN A", "So", 0), ("PARENTHESIZED HANGUL TIKEUT A", "So", 0), ("PARENTHESIZED HANGUL RIEUL A", "So", 0), ("PARENTHESIZED HANGUL MIEUM A", "So", 0), ("PARENTHESIZED HANGUL PIEUP A", "So", 0), ("PARENTHESIZED HANGUL SIOS A", "So", 0), ("PARENTHESIZED HANGUL IEUNG A", "So", 0), ("PARENTHESIZED HANGUL CIEUC A", "So", 0), ("PARENTHESIZED HANGUL CHIEUCH A", "So", 0), ("PARENTHESIZED HANGUL KHIEUKH A", "So", 0), ("PARENTHESIZED HANGUL THIEUTH A", "So", 0), ("PARENTHESIZED HANGUL PHIEUPH A", "So", 0), ("PARENTHESIZED HANGUL HIEUH A", "So", 0), ("PARENTHESIZED HANGUL CIEUC U", "So", 0), ("PARENTHESIZED KOREAN CHARACTER OJEON", "So", 0), ("PARENTHESIZED KOREAN CHARACTER O HU", "So", 0), (), ("PARENTHESIZED IDEOGRAPH ONE", "No", 0), ("PARENTHESIZED IDEOGRAPH TWO", "No", 0), ("PARENTHESIZED IDEOGRAPH THREE", "No", 0), ("PARENTHESIZED IDEOGRAPH FOUR", "No", 0), ("PARENTHESIZED IDEOGRAPH FIVE", "No", 0), ("PARENTHESIZED IDEOGRAPH SIX", "No", 0), ("PARENTHESIZED IDEOGRAPH SEVEN", "No", 0), ("PARENTHESIZED IDEOGRAPH EIGHT", "No", 0), ("PARENTHESIZED IDEOGRAPH NINE", "No", 0), ("PARENTHESIZED IDEOGRAPH TEN", "No", 0), ("PARENTHESIZED IDEOGRAPH MOON", "So", 0), ("PARENTHESIZED IDEOGRAPH FIRE", "So", 0), ("PARENTHESIZED IDEOGRAPH WATER", "So", 0), ("PARENTHESIZED IDEOGRAPH WOOD", "So", 0), ("PARENTHESIZED IDEOGRAPH METAL", "So", 0), ("PARENTHESIZED IDEOGRAPH EARTH", "So", 0), ("PARENTHESIZED IDEOGRAPH SUN", "So", 0), ("PARENTHESIZED IDEOGRAPH STOCK", "So", 0), ("PARENTHESIZED IDEOGRAPH HAVE", "So", 0), ("PARENTHESIZED IDEOGRAPH SOCIETY", "So", 0), ("PARENTHESIZED IDEOGRAPH NAME", "So", 0), ("PARENTHESIZED IDEOGRAPH SPECIAL", "So", 0), ("PARENTHESIZED IDEOGRAPH FINANCIAL", "So", 0), ("PARENTHESIZED IDEOGRAPH CONGRATULATION", "So", 0), ("PARENTHESIZED IDEOGRAPH LABOR", "So", 0), ("PARENTHESIZED IDEOGRAPH REPRESENT", "So", 0), ("PARENTHESIZED IDEOGRAPH CALL", "So", 0), ("PARENTHESIZED IDEOGRAPH STUDY", "So", 0), ("PARENTHESIZED IDEOGRAPH SUPERVISE", "So", 0), ("PARENTHESIZED IDEOGRAPH ENTERPRISE", "So", 0), ("PARENTHESIZED IDEOGRAPH RESOURCE", "So", 0), ("PARENTHESIZED IDEOGRAPH ALLIANCE", "So", 0), ("PARENTHESIZED IDEOGRAPH FESTIVAL", "So", 0), ("PARENTHESIZED IDEOGRAPH REST", "So", 0), ("PARENTHESIZED IDEOGRAPH SELF", "So", 0), ("PARENTHESIZED IDEOGRAPH REACH", "So", 0), ("CIRCLED IDEOGRAPH QUESTION", "So", 0), ("CIRCLED IDEOGRAPH KINDERGARTEN", "So", 0), ("CIRCLED IDEOGRAPH SCHOOL", "So", 0), ("CIRCLED IDEOGRAPH KOTO", "So", 0), ("CIRCLED NUMBER TEN ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER TWENTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER THIRTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER FORTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER FIFTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER SIXTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER SEVENTY ON BLACK SQUARE", "No", 0), ("CIRCLED NUMBER EIGHTY ON BLACK SQUARE", "No", 0), ("PARTNERSHIP SIGN", "So", 0), ("CIRCLED NUMBER TWENTY ONE", "No", 0), ("CIRCLED NUMBER TWENTY TWO", "No", 0), ("CIRCLED NUMBER TWENTY THREE", "No", 0), ("CIRCLED NUMBER TWENTY FOUR", "No", 0), ("CIRCLED NUMBER TWENTY FIVE", "No", 0), ("CIRCLED NUMBER TWENTY SIX", "No", 0), ("CIRCLED NUMBER TWENTY SEVEN", "No", 0), ("CIRCLED NUMBER TWENTY EIGHT", "No", 0), ("CIRCLED NUMBER TWENTY NINE", "No", 0), ("CIRCLED NUMBER THIRTY", "No", 0), ("CIRCLED NUMBER THIRTY ONE", "No", 0), ("CIRCLED NUMBER THIRTY TWO", "No", 0), ("CIRCLED NUMBER THIRTY THREE", "No", 0), ("CIRCLED NUMBER THIRTY FOUR", "No", 0), ("CIRCLED NUMBER THIRTY FIVE", "No", 0), ("<NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED <NAME>", "So", 0), ("CIRCLED HANGUL KIYEOK A", "So", 0), ("CIRCLED HANGUL NIEUN A", "So", 0), ("CIRCLED HANGUL TIKEUT A", "So", 0), ("CIRCLED HANGUL RIEUL A", "So", 0), ("CIRCLED HANGUL MIEUM A", "So", 0), ("CIRCLED HANGUL PIEUP A", "So", 0), ("CIRCLED HANGUL SIOS A", "So", 0), ("CIRCLED HANGUL IEUNG A", "So", 0), ("CIRCLED HANGUL CIEUC A", "So", 0), ("CIRCLED HANGUL CHIEUCH A", "So", 0), ("CIRCLED HANGUL KHIEUKH A", "So", 0), ("CIRCLED HANGUL THIEUTH A", "So", 0), ("CIRCLED HANGUL PHIEUPH A", "So", 0), ("CIRCLED HANGUL HIEUH A", "So", 0), ("CIRCLED KOREAN CHARACTER CHAMKO", "So", 0), ("CIRCLED KOREAN CHARACTER JUEUI", "So", 0), ("CIRCLED HANGUL IEUNG U", "So", 0), ("KOREAN STANDARD SYMBOL", "So", 0), ("CIRCLED IDEOGRAPH ONE", "No", 0), ("CIRCLED IDEOGRAPH TWO", "No", 0), ("CIRCLED IDEOGRAPH THREE", "No", 0), ("CIRCLED IDEOGRAPH FOUR", "No", 0), ("CIRCLED IDEOGRAPH FIVE", "No", 0), ("CIRCLED IDEOGRAPH SIX", "No", 0), ("CIRCLED IDEOGRAPH SEVEN", "No", 0), ("CIRCLED IDEOGRAPH EIGHT", "No", 0), ("CIRCLED IDEOGRAPH NINE", "No", 0), ("CIRCLED IDEOGRAPH TEN", "No", 0), ("CIRCLED IDEOGRAPH MOON", "So", 0), ("CIRCLED IDEOGRAPH FIRE", "So", 0), ("CIRCLED IDEOGRAPH WATER", "So", 0), ("CIRCLED IDEOGRAPH WOOD", "So", 0), ("CIRCLED IDEOGRAPH METAL", "So", 0), ("CIRCLED IDEOGRAPH EARTH", "So", 0), ("CIRCLED IDEOGRAPH SUN", "So", 0), ("CIRCLED IDEOGRAPH STOCK", "So", 0), ("CIRCLED IDEOGRAPH HAVE", "So", 0), ("CIRCLED IDEOGRAPH SOCIETY", "So", 0), ("CIRCLED IDEOGRAPH NAME", "So", 0), ("CIRCLED IDEOGRAPH SPECIAL", "So", 0), ("CIRCLED IDEOGRAPH FINANCIAL", "So", 0), ("CIRCLED IDEOGRAPH CONGRATULATION", "So", 0), ("CIRCLED IDEOGRAPH LABOR", "So", 0), ("CIRCLED IDEOGRAPH SECRET", "So", 0), ("CIRCLED IDEOGRAPH MALE", "So", 0), ("CIRCLED IDEOGRAPH FEMALE", "So", 0), ("CIRCLED IDEOGRAPH SUITABLE", "So", 0), ("CIRCLED IDEOGRAPH EXCELLENT", "So", 0), ("CIRCLED IDEOGRAPH PRINT", "So", 0), ("CIRCLED IDEOGRAPH ATTENTION", "So", 0), ("CIRCLED IDEOGRAPH ITEM", "So", 0), ("CIRCLED IDEOGRAPH REST", "So", 0), ("CIRCLED IDEOGRAPH COPY", "So", 0), ("CIRCLED IDEOGRAPH CORRECT", "So", 0), ("CIRCLED IDEOGRAPH HIGH", "So", 0), ("CIRCLED IDEOGRAPH CENTRE", "So", 0), ("CIRCLED IDEOGRAPH LOW", "So", 0), ("CIRCLED IDEOGRAPH LEFT", "So", 0), ("CIRCLED IDEOGRAPH RIGHT", "So", 0), ("CIRCLED IDEOGRAPH MEDICINE", "So", 0), ("CIRCLED IDEOGRAPH RELIGION", "So", 0), ("CIRCLED IDEOGRAPH STUDY", "So", 0), ("CIRCLED IDEOGRAPH SUPERVISE", "So", 0), ("CIRCLED IDEOGRAPH ENTERPRISE", "So", 0), ("CIRCLED IDEOGRAPH RESOURCE", "So", 0), ("CIRCLED IDEOGRAPH ALLIANCE", "So", 0), ("CIRCLED IDEOGRAPH NIGHT", "So", 0), ("CIRCLED NUMBER THIRTY SIX", "No", 0), ("CIRCLED NUMBER THIRTY SEVEN", "No", 0), ("CIRCLED NUMBER THIRTY EIGHT", "No", 0), ("CIRCLED NUMBER THIRTY NINE", "No", 0), ("CIRCLED NUMBER FORTY", "No", 0), ("CIRCLED NUMBER FORTY ONE", "No", 0), ("CIRCLED NUMBER FORTY TWO", "No", 0), ("CIRCLED NUMBER FORTY THREE", "No", 0), ("CIRCLED NUMBER FORTY FOUR", "No", 0), ("CIRCLED NUMBER FORTY FIVE", "No", 0), ("CIRCLED NUMBER FORTY SIX", "No", 0), ("CIRCLED NUMBER FORTY SEVEN", "No", 0), ("CIRCLED NUMBER FORTY EIGHT", "No", 0), ("CIRCLED NUMBER FORTY NINE", "No", 0), ("CIRCLED NUMBER FIFTY", "No", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR JANUARY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR FEBRUARY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR MARCH", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR APRIL", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR MAY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR JUNE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR JULY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR AUGUST", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR SEPTEMBER", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR OCTOBER", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR NOVEMBER", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DECEMBER", "So", 0), ("SQUARE HG", "So", 0), ("SQUARE ERG", "So", 0), ("SQUARE EV", "So", 0), ("LIMITED LIABILITY SIGN", "So", 0), ("CIRCLED KATAKANA A", "So", 0), ("CIRCLED KATAKANA I", "So", 0), ("CIRCLED KATAKANA U", "So", 0), ("CIRCLED KATAKANA E", "So", 0), ("CIRCLED KATAKANA O", "So", 0), ("CIRCLED KATAKANA KA", "So", 0), ("CIRCLED KATAKANA KI", "So", 0), ("CIRCLED KATAKANA KU", "So", 0), ("CIRCLED KATAKANA KE", "So", 0), ("CIRCLED KATAKANA KO", "So", 0), ("CIRCLED KATAKANA SA", "So", 0), ("CIRCLED KATAKANA SI", "So", 0), ("CIRCLED KATAKANA SU", "So", 0), ("CIRCLED KATAKANA SE", "So", 0), ("CIRCLED KATAKANA SO", "So", 0), ("CIRCLED KATAKANA TA", "So", 0), ("CIRCLED KATAKANA TI", "So", 0), ("CIRCLED KATAKANA TU", "So", 0), ("CIRCLED KATAKANA TE", "So", 0), ("CIRCLED KATAKANA TO", "So", 0), ("CIRCLED KATAKANA NA", "So", 0), ("CIRCLED KATAKANA NI", "So", 0), ("CIRCLED KATAKANA NU", "So", 0), ("CIRCLED KATAKANA NE", "So", 0), ("CIRCLED KATAKANA NO", "So", 0), ("CIRCLED KATAKANA HA", "So", 0), ("CIRCLED KATAKANA HI", "So", 0), ("CIRCLED KATAKANA HU", "So", 0), ("CIRCLED KATAKANA HE", "So", 0), ("CIRCLED KATAKANA HO", "So", 0), ("CIRCLED KATAKANA MA", "So", 0), ("CIRCLED KATAKANA MI", "So", 0), ("CIRCLED KATAKANA MU", "So", 0), ("CIRCLED KATAKANA ME", "So", 0), ("CIRCLED KATAKANA MO", "So", 0), ("CIRCLED KATAKANA YA", "So", 0), ("CIRCLED KATAKANA YU", "So", 0), ("CIRCLED KATAKANA YO", "So", 0), ("CIRCLED KATAKANA RA", "So", 0), ("CIRCLED KATAKANA RI", "So", 0), ("CIRCLED KATAKANA RU", "So", 0), ("CIRCLED KATAKANA RE", "So", 0), ("CIRCLED KATAKANA RO", "So", 0), ("CIRCLED KATAKANA WA", "So", 0), ("CIRCLED KATAKANA WI", "So", 0), ("CIRCLED KATAKANA WE", "So", 0), ("CIRCLED KATAKANA WO", "So", 0), ("SQUARE ERA NAME REIWA", "So", 0), )
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/tests/assertations/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 10pt) #include "/src/rounding.typ" #include "/src/formatting.typ" #include "/src/num.typ" #include "/src/parsing.typ"
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/lib/unitfmt.typ
typst
MIT License
#let KiB(bytes) = bytes / 1024 #let MiB(bytes, decimals: 2) = { let value = bytes / 1024 / 1024 $#value "MiB"$ } #let GiB(bytes) = bytes / 1024 / 1024 / 1024 #let KB(bytes) = bytes / 1000 #let MB(bytes) = bytes / 1000 / 1000 #let GB(bytes) = bytes / 1000 / 1000 / 1000
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/cli/build.typ
typst
Apache License 2.0
#import "/github-pages/docs/book.typ": book-page #show: book-page.with(title: "CLI Build Command") = The build command The build command is used to render your book: ```bash shiroa build ``` It will try to parse your `book.typ` file to understand the structure and metadata of your book and fetch the corresponding files. Note that files mentioned in `book.typ` but not present will be created. The rendered output will maintain the same directory structure as the source for convenience. Large books will therefore remain structured when rendered. == Specify a directory The `build` command can take a directory as an argument to use as the book's root instead of the current working directory. ```bash shiroa build path/to/book ``` === --workspace, -w *Note:* The workspace is a _typst-specific_ command. The `--workspace` option specifies the root directory of typst source files, which is like the `--root` option of `typst-cli`. It is interpreted relative to *current work directory of `shiroa` process*. For example. When a book is created with the main file `book-project1/book.typ`, and you want to access a template file with path `common/book-template.typ`, please build it with following command: ```bash shiroa build -w . book-project1 ``` Then you can access the template with the absolute path in typst: ```typ #import "/common/book-template.typ": * ``` === --dest-dir, -d The `--dest-dir` (`-d`) option allows you to change the output directory for the book. Relative paths are interpreted relative to the book's root directory. If not specified it will default to the value of the `build.build-dir` key in `book.toml`, or to `./book`. === --path-to-root When your website's root is not exact serving the book, use `--path-to-root` to specify the path to the root of the book site. For example, if you own `myriad-dreamin.github.io` and have mounted the book to `/shiroa/`, you can access `https://myriad-dreamin.github.io/shiroa/cli/main.html` to get the generated content of `cli/main.typ`. ```bash shiroa build --path-to-root /shiroa/ book-project1 ``` // #line(length: 100%) // todo: copy all rest files // ***Note:*** *The build command copies all files (excluding files with `.typ` extension) from the source directory into the build directory.*
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/components/pro-con.typ
typst
The Unlicense
#import "../colors.typ": * #import "/utils.typ" #let pro-con = utils.make-pro-con((pros, cons) => { let cell = rect.with( width: 100%, inset: 5pt, ) grid( columns: (1fr, 1fr), column-gutter: 4pt, cell( fill: green, radius: (top: 1.5pt), )[*Pros*], cell( fill: red, radius: (top: 1.5pt), )[*Cons*], cell( fill: green.lighten(80%), radius: (bottom: 1.5pt), pros, ), cell( fill: red.lighten(80%), radius: (bottom: 1.5pt), cons, ), ) })
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/akatisty/akatistMikulas.typ
typst
#import "/style.typ": * #import "/styleAkatist.typ": * = Akatist k sv. Mikulášovi Divotvorcovi #align(horizon + center)[#primText[ #text(50pt)[Akatist k \ sv. Mikulášovi\ Divotvorcovi] ]] #let akatist = ( ( "index": 1, "kondak": [Predivný a slávny divotvorca, svätiteľ Mikuláš. Počas života si sa páčil Bohu všetkým, čo si konal. Dnes ťa oslavujeme s láskou ako toho, kto neprestáva vylievať na svet milosti z drahocenného a nevyčerpateľného mora Božích zázrakov. Ako toho, ktorý odvážne stojí pred Pánom, ťa prosíme, osloboď nás od všetkých nástrah, aby sme k tebe volali: Raduj sa, svätý Mikuláš, veľký divotvorca.], "zvolanie": [Raduj sa, svätý Mikuláš, veľký divotvorca.], "ikos": [Podľa prirodzenosti si bol človekom, svätý divotvorca Mikuláš, ale dobrým ovocím tvojej duše si sa pripodobnil anjelom. Preto ti všetci spievame:], "prosby": ( [Raduj sa, že si si od detstva čistotu zachoval.], [Raduj sa, že si sa posvätiť milosťou celkom dal.], [Raduj sa, že z tvojho počatia rodičia jasali.], [Raduj sa, že silou ducha si od detstva oplýval.], [Raduj sa, úrodná záhrada v krajine prísľubu.], [Raduj sa, kvet, ktorý Boh svojou pravicou zasadil.], [Raduj sa, úrodná ratolesť Kristovho viniča.], [Raduj sa, zázračný, svieži strom v kráľovstve Ježiša.], [Raduj sa, lebo si ľalia z nebeskej záhrady.], [Raduj sa, lebo si Kristovou vôňou svet naplnil.], [Raduj sa, lebo vieš utíšiť plačúce stvorenia.], [Raduj sa, lebo ty napĺňaš človeka radosťou.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 2, "kondak": [Pohľad na to, ako sa rozlieva myro tvojho milosrdenstva, bohomúdry Mikuláš, osvecuje naše duše a telá. Hľadíme na teba ako na toho, z ktorého vyteká životodarné myro, lebo z Božej milosti zosielaš na veriacich zázraky ako dážď a napájaš ich, aby spievali Bohu: Aleluja.], "zvolanie": none, "ikos": [V Nicei si spolu so svätými otcami bránil kresťanskú vieru v Svätú Trojicu. Vyznal si Božieho Syna ako rovného Otcovi, jednopodstatného a jednorodeného, čím si odsúdil nemúdreho Ária. Preto ťa veriaci takto uctievajú:], "prosby": ( [Raduj sa, lebo si pevný stĺp úprimnej zbožnosti.], [Raduj sa, lebo si bezpečným úkrytom veriacich.], [Raduj sa, lebo si pevnosťou viery, čo obstojí.], [Raduj sa, lebo si príbytok Presvätej Trojice.], [Raduj sa, lebo si hlásal Otca rovného so Synom.], [Raduj sa, lebo si Ária z koncilu odohnal.], [Raduj sa, lebo si krása svätých otcov preslávna.], [Raduj sa, lebo si dobrý a premúdry v Pánovi.], [Raduj sa, že tvoje slová sú ohnivé plamene.], [Raduj sa, že tvoje ovečky dobre sú vedené.], [Raduj sa, že pre tvoj príklad sme pevnejší vo viere.], [Raduj sa, že si nás naučil vzoprieť sa heréze.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 3, "kondak": [Bohonosný otče Mikuláš! Mocou, ktorú ti dal Boh, si utrel každú slzu z tváre tých, ktorí boli ťažko trápení. Kŕmil si hladných, oslobodzoval ľudí z morských hlbín, chorým si podal liek a všemožne si pomáhal tým, ktorí spievali Bohu: Aleluja.], "zvolanie": none, "ikos": [Skutočne, otče Mikuláš, nebo je miesto, kde sa ti patrí spievať oslavnú pieseň. Nie je to zem, lebo kto z ľudí je schopný vyjadriť veľkosť tvojej svätosti? Premožení príkladom tvojej lásky ti takto spievame:], "prosby": ( [Raduj sa, obraz pre baránkov a pre ich pastierov.], [Raduj sa, lebo si očistil vieru od nevery.], [Raduj sa, že v tebe bohaté čnosti sú schované.], [Raduj sa, lebo si prečistá komnata svätyne.], [Raduj sa, príjemný, žiarivý svietnik, čo nehasne.], [Raduj sa, svetlo bez poškvrny, zlatisto žiariace.], [Raduj sa, lebo si dôstojný spoločník anjelov.], [Raduj sa, lebo si pre ľudí učiteľ vo viere.], [Raduj sa, pravidlo, čo pravú moc viery dosvedčí.], [Raduj sa, lebo si obrazom duchovnej nežnosti.], [Raduj sa, lebo nám pomáhaš bez vášní v tele žiť.], [Raduj sa, lebo nás nebeskou rosou vieš osviežiť.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 4, "kondak": [Moja myseľ sa zmieta ako v búrke a nemôže pochopiť, ako sa dajú s dostatočnou úctou a dôstojnosťou osláviť tvoje zázraky, svätý Mikuláš. Nikto ich nemôže zrátať a vymenovať, aj keby sa o to pokúsil mnohými jazykmi. Preto Bohu, ktorý sa v tebe predivne oslávil, túžime s bázňou spievať: Aleluja.], "zvolanie": none, "ikos": [Zvesť o tvojich veľkých zázrakoch, bohomúdry Mikuláš, sa šírila do ďalekých krajín. Boží Duch ťa na krídlach milosti niesol k núdznym, aby si nachádzal postihnutých biedou a rýchlo zachraňoval všetkých, ktorí k tebe volajú:], "prosby": ( [Raduj sa, lebo nás zo smútku k slobode vyvádzaš.], [Raduj sa, lebo nám milosť za milosťou rozdávaš.], [Raduj sa, lebo vieš odhaliť ukryté nástrahy.], [Raduj sa, lebo ty si mnohé dobrá v nás zasadil.], [Raduj sa, útecha tých, ktorí sa v núdzi zmietajú.], [Raduj sa, trestajúci tých, čo nástrahy chystajú.], [Raduj sa, bezodné údolie Pánových zázrakov.], [Raduj sa, premocné svedectvo Kristovho zákona.], [Raduj sa, sila a opora tých, ktorí padajú.], [Raduj sa, posila tých, ktorí pre pravdu strádajú.], [Raduj sa, že každé klamstvo sa pri tebe odhalí.], [Raduj sa, že dielo pravdy sa pri tebe podarí.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 5, "kondak": [Ako hviezda, ktorá ukazuje smer, si sa kedysi zjavil pútnikom na mori, ktorým v búrke hrozila smrť, ak by si im neprišiel na pomoc. Zabránil si vo vyčíňaní démonom, ktorí už lietali nad loďou a chceli ju potopiť, a vyhnal si ich. Veriacich si naučil, aby Bohu, ktorý ich tvojím prostredníctvom zachránil, spievali: Aleluja.], "zvolanie": none, "ikos": [Bol si veľmi milosrdný k chudobným, svätý Mikuláš. Keď si sa dozvedel, že sa tri dievčatá pre chudobu rozhodli pre nemravný život, tajne si v noci vhodil ich otcovi cez okno tri mešce zlata. Aj samotného otca si ochránil od smrteľného hriechu. Preto od mnohých počúvaš velebenie:], "prosby": ( [Raduj sa, truhlica milosrdenstva a dobroty.], [Raduj sa, bezpečný úkryt pre smutných a nešťastných.], [Raduj sa, pokrm a útecha tých, čo si ťa ctia.], [Raduj sa, dostatok chleba pre tých, čo hladní žalostia.], [Raduj sa, bohatstvo od Pána pre všetkých chudobných.], [Raduj sa, pomoc, čo nemešká s nádejou pre núdznych.], [Raduj sa, odpoveď pre tých, čo úprimne hľadajú.], [Raduj sa, starostlivá ruka pre tých, čo strádajú.], [Raduj sa, pre sestry prečistá záchrana pred hriechom.], [Raduj sa, úprimný ochranca nebeskej čistoty.], [Raduj sa, nádej pre každého, kto je bez nádeje.], [Raduj sa, útecha človeku, ktorému ťažko je.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 6, "kondak": [Celý svet ťa oslavuje, slávny Mikuláš, ako rýchleho zástancu v trápení, lebo si mnohokrát pomáhal tým, ktorí putovali po zemi, i tým, ktorí sa plavili po mori, upozorňoval si ich na nástrahy, chránil si pred nešťastím tých, ktorí spievajú Bohu: Aleluja.], "zvolanie": none, "ikos": [Žiaril si svetlom života, priniesol si oslobodenie trom veliteľom, ktorí mali byť neprávom zabití, a vzývali ťa, <NAME>. Vo sne si sa zjavil kráľovi a vyľakal ho tak, že ich prikázal pustiť na slobodu bez ujmy. Preto ti spolu s nimi s vďakou voláme:], "prosby": ( [Raduj sa, lebo rád prídeš na úprimné volanie.], [Raduj sa, lebo dáš slobodu tam, kde jej pre smrť niet.], [Raduj sa, lebo nás chrániš pred jazykom, čo škodí.], [Raduj sa, lebo múr hriechu v nás dokážeš rozdrobiť.], [Raduj sa, že ako pavúčiu sieť ničíš klamanie.], [Raduj sa, že slávne povýšiš pravdivé poznanie.], [Raduj sa, lebo z pút slobodu prinášaš nevinným.], [Raduj sa, lebo aj mŕtvych vieš oživiť v Pánovi.], [Raduj sa, lebo nám zjavuješ pravdivé poklady.], [Raduj sa, lebo vieš zatemniť nástrahy nepravdy.], [Raduj sa, že nesieš nevinným od trestu slobodu.], [Raduj sa, že svetlom života potešíš každého.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 7, "kondak": [Zjavil si sa ako myro ľúbeznej vône, aby si rozohnal nepríjemné pachy herézy. Keď si slúžil ako pastier v meste Myra, celý svet si napĺňal voňavým olejom svojich čností. Odožeň od nás zápach hriechu, ktorý sa protiví Bohu, aby sme mu spievali príjemnú pieseň: Aleluja.], "zvolanie": none, "ikos": [Otec Mikuláš, si pre nás ako nový Noe, ktorý svojím riadením rozháňa búrku všetkých krutých bied. Prinášaš Božie stíšenie tým, ktorí ťa velebia:], "prosby": ( [Raduj sa, pokojný prístav pre zmietaných búrkami.], [Raduj sa, bezpečná ochrana topiacich sa v mori.], [Raduj sa, kapitán pútnikov na plavbách po vodách.], [Raduj sa, lebo si nepokoj zázračne utíšil.], [Raduj sa, sprievodca zmietaných silnými víchrami.], [Raduj sa, teplo pre mrznúcich, ochrana pred chladom.], [Raduj sa, svetlo pre tých, ktorí sú vo tme trápenia.], [Raduj sa, svietnik, čo osvetlí temnotu súženia.], [Raduj sa, že z hriechu dvíhaš a slobodu daruješ.], [Raduj sa, že diabla do hĺbky pekelnej zhadzuješ.], [Raduj sa, že s tebou na Božiu milosť sa môžeme spoliehať.], [Raduj sa, že s tebou pred Božím hnevom sa niet čo báť.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 8, "kondak": [Predivný zázrak prejavuje svätá Cirkev tým, ktorí sa k tebe obracajú, svätiteľ Mikuláš, lebo keď prinášame hoci aj malú modlitbu, dostávame uzdravenie od veľkých bied a chorôb. Po Bohu a Bohorodičke si to ty, na koho sa spoliehame. Vďační za teba spievame Bohu vo viere: Aleluja.], "zvolanie": none, "ikos": [Skutočne si pomocou pre každého v každom čase, svätý Mikuláš. Zhromaždil si všetkých, ktorí sa k tebe utiekajú. Stal si sa osloboditeľom, živiteľom, lekárom pre každého človeka na zemi. Tým nás povzbudzuješ, aby sme ti spievali:], "prosby": ( [Raduj sa, lebo si prameň, čo chorobu vylieči.], [Raduj sa, lebo si pomocou pre ťažko trpiacich.], [Raduj sa, zornica, pre toho, kto v hriechu zablúdil.], [Raduj sa, nebeská rosa pre páľavou zmorených.], [Raduj sa, že všetkých zmätených povedieš k poriadku.], [Raduj sa, že všetkých prosiacich privádzaš k dostatku.], [Raduj sa, že často odpovieš skôr, ako prosíme.], [Raduj sa, že starcom šedivým pridávaš na sile.], [Raduj sa, že k pravde navraciaš tých, čo sú na scestí.], [Raduj sa, že ničíš zárodky ničivej závisti.], [Raduj sa, že verne vysluhuješ Božie tajomstvá.], [Raduj sa, že vedieš k náprave mravnosti života.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 9, "kondak": [Zástanca náš, Mikuláš, utíš búrku našich bolestí. Požehnaj nás uzdravením, ktoré poteší duše a rozveselí srdcia tých, ktorí k tebe úprimne volajú o pomoc, na teba sa obracajú a Bohu spievajú: Aleluja!], "zvolanie": none, "ikos": [Vieme, bohomúdry otče Mikuláš, že bezbožní a ľahkovážni krasorečníci sú zahanbení pred tebou, lebo si rúhačov Ária a Sabélia, ktorí nesprávne chápali Svätú Trojicu, premohol a nás si upevnil v pravej viere. Preto si ťa vážime a spievame:], "prosby": ( [Raduj sa, štít, ktorý nás chráni pre Božie kráľovstvo.], [Raduj sa, meč, ktorý roztína neprávosť a klamstvo.], [Raduj sa, premúdry učiteľ Božieho zákona.], [Raduj sa, odvážny ničiteľ nesprávnych učení.], [Raduj sa, lebo si rebrík, čo Pán k nebu vyzdvihol.], [Raduj sa, lebo si plášť, ktorý úbohých prikrýva.], [Raduj sa, lebo si nemúdrych poučil slovami.], [Raduj sa, lebo si lenivých povzbudil čnosťami.], [Raduj sa, veď žiariš nádherou Božieho zákona.], [Raduj sa, jasný lúč ospravedlnenia od Pána.], [Raduj sa, veď svojím učením chrániš od herézy.], [Raduj sa, veď k nebu vedieš nás do Božej veleby.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 10, "kondak": [V túžbe spasiť svoju dušu si, otče Mikuláš, úplne podrobil svoje telo duchu, najprv mlčaním a bojom s pokušením, potom si k uvažovaniu o Bohu pripojil aj konanie a tak si získal dokonalosť. Preto sa dnes bez strachu rozprávaš s Bohom a anjelmi, a neustále spievaš: Aleluja.], "zvolanie": none, "ikos": [Svätiteľ Mikuláš, si ochranným múrom pre tých, ktorí oslavujú tvoje zázraky, a pre tých, ktorí sa k tebe utiekajú. Preto aj nás, chudobných na čnosti, zachráň od biedy, nástrah a všetkých trápení, aby sme ťa s láskou velebili:], "prosby": ( [Raduj sa, lebo nás pred večnou chudobou vystríhaš.], [Raduj sa, lebo nás nebeským bohatstvom zahŕňaš.], [Raduj sa, lebo si útechou túžiacich po pravde.], [Raduj sa, lebo si nápojom smädných po živote.], [Raduj sa, lebo nás chrániš pred spormi a vojnami.], [Raduj sa, lebo z nás zhadzuješ otrocké okovy.], [Raduj sa, lebo si zástanca v biede a trápení.], [Raduj sa, lebo si záchranca vo všetkých nástrahách.], [Raduj sa, lebo si zachránil mnohých od zhynutia.], [Raduj sa, lebo si zachránil mnohých od prekliatia.], [Raduj sa, lebo máš záľubu v záchrane hriešnikov.], [Raduj sa, lebo rád k životu privádzaš kajúcich.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 11, "kondak": [Každou myšlienkou, slovom i skutkom si väčšmi ako všetci ostatní prinášal slávu Presvätej Trojici, otče Mikuláš. Otázky viery si riešil obdivuhodnou skúsenosťou. Vierou, nádejou a láskou si nás učil spievať Bohu, jedinému v Trojici: Aleluja!], "zvolanie": none, "ikos": [Hľadíme na teba, Bohom oslávený otče Mikuláš, ako na nehasnúci jasný lúč pre tých, ktorí prebývajú v temnote, lebo s anjelskými zbormi sa rozprávaš o nestvorenom trojsvätom Svetle a osvecuješ duše veriacich, ktoré ti spievajú:], "prosby": ( [Raduj sa, lebo si svetlo, čo žiaru má od Svätej Trojice.], [Raduj sa, lebo si úsvitom Slnka, čo nehasne.], [Raduj sa, lebo si svieca, čo svetlo má od Pána.], [Raduj sa, lebo si uhasil bezbožné plamene.], [Raduj sa, žiarivý hlásateľ pravého učenia.], [Raduj sa, žiarivý apoštol Nového zákona.], [Raduj sa, blesk, ktorý spaľuje bludy a herézy.], [Raduj sa, hrom, ktorý vyľaká zvodcov a nečestných.], [Raduj sa, premúdry učiteľ pravého poznania.], [Raduj sa, pokorný nositeľ tajomnej múdrosti.], [Raduj sa, odvážny ničiteľ modlárskej úcty k stvoreniu.], [Raduj sa, poslušný služobník, oddaný Trojici.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 12, "kondak": [Vieme, že ťa Boh obdaril milosťou, preto radostne slávime tvoju pamiatku, otče Mikuláš, a s nádejou sa obraciame na tvoj príhovor. Nemožno zrátať tvoje slávne diela. Je ich ako piesku v mori a hviezd na nebi. V údive nad tvojím životom spievame Bohu: Aleluja!], "zvolanie": none, "ikos": [Oslavujeme tvoje zázraky, všechválny otče Mikuláš. Velebíme ťa, lebo v tebe sa predivne oslávil Boh, slávny vo Svätej Trojici. Aj keby sme ti zložili nespočítateľne mnoho hymnov a piesní, nespravili by sme nič, čo by sa vyrovnalo tvojim zázrakom. Pri pohľade na nich k tebe voláme:], "prosby": ( [Raduj sa, nebeského Kráľa a Pána služobník.], [Raduj sa, večného Božieho oltára spoločník.], [Raduj sa, pomocník veriacich uprostred trápenia.], [Raduj sa, chvála a česť všetkých skutočných kresťanov.], [Raduj sa, lebo máš meno, čo víťazstvu rovná sa.], [Raduj sa, lebo si nositeľ venca pre víťaza.], [Raduj sa, lebo si zrkadlo dobrého konania.], [Raduj sa, lebo si bezpečím pre tých, čo prosia ťa.], [Raduj sa, lebo si nádejou tam, kde jej takmer niet.], [Raduj sa, lebo si pomocou na ceste za spásou.], [Raduj sa, lebo nás pred cestou do pekla vystríhaš.], [Raduj sa, lebo nás k večnému životu sprevádzaš.], [Raduj sa, svätý Mikuláš, veľký divotvorca.], ) ), ( "index": 13, "kondak": [Presvätý a predivný otče Mikuláš, útecha všetkých trápených. Prijmi našu chválu, aby sme boli zachránení od večných múk. Pros Pána, aby sme mu spolu s tebou spievali: Aleluja.], "zvolanie": none, "ikos": none, "prosby": none, "modlitba": "Ctihodný otec Mikuláš! Pastier a učiteľ všetkých, ktorí k tebe prichádzajú s vierou! Zástanca tých, ktorí sa k tebe utiekajú a vrúcnou modlitbou ťa prosia o ochranu. Ponáhľaj sa a ochráň Kristovo stádo pred vlkmi, ktorí ho trhajú. Svojimi modlitbami našu krajinu i každého človeka v nej ochráň od hladu, pohrôm, zemetrasenia, povodní, krupobitia, ohňa, meča, vpádu nepriateľa a náhlej smrti. Ako si sa zľutoval nad tromi mužmi vo väzení a zachránil si ich od kráľovho hnevu a trestu smrti, tak sa zmiluj aj nad nami, ktorí mysľou, slovom i skutkom prebývame v tme hriechov. Zachráň nás pred Božím hnevom a večným trestom. Nech nám na tvoj príhovor <NAME> Kristus daruje bezhriešny a pokojný život. Nech nie sme odsúdení s tými, čo stoja po Kristovej ľavici, ale dovoľ nám stáť po Božej pravici, aby sme boli uznaní za hodných vojsť do kráľovstva Božej slávy, kde budeme naveky chváliť a zvelebovať Božie meno." ) ); #akatistGenerate(akatist)
https://github.com/Sepax/Typst
https://raw.githubusercontent.com/Sepax/Typst/main/DIT323/Assignments/A2/main.typ
typst
#import "template.typ": * #show: template.with( title: [Finite automata and formal languages #linebreak() Assignment 2], short_title: "DIT084", description: [ DIT323 (Finite automata and formal languages)\ at Gothenburg University ], authors: ((name: "<NAME>"),), lof: false, lot: false, lol: false, paper_size: "a4", cols: 1, text_font: "XCharter", code_font: "Cascadia Mono", accent: "#000000", // black ) = _Answer:_ The language comprises of words formed by the letters a, b, and c, and it is mandatory for the words to have at least one c or two a's. _Motivation:_ #automaton((S0: (S1: "a", S2: "c"), S1: (S1: "b,c", S2: "a"), S2: (S2: "a,b,c"))) _Looking at the automaton, we can see that any word must contain atlease one c or two a's._ = == _Answer:_ See text file `2-1.txt` _Motivation:_ - *s0* is the start state and also the state when no 'b' has been encountered yet. On seeing an 'a', it remains in s0 because the string "bba" cannot start with 'a'. On seeing a 'b', it moves to *s1*. - *s1* is the state after seeing a 'b'. On seeing another 'b', it moves to *s2* (as we now have "bb"). On seeing an 'a', it goes back to s0 because the string "bba" cannot start with "ba". - *s2* is the state after seeing "bb". On seeing an 'a', it moves to *s3* (as we now have "bba"). On seeing a 'b', it stays in *s2* because we're still in the middle of seeing a sequence of 'b's. - *s3* is the trap state. Once the DFA sees the string "bba", it moves to *s3* and stays there on any input. This is because the string already contains "bba", so any further input cannot change this. _The DFA accepts a string if and only if it is not in *s3* at the end of the string. This is because being in *s3* means that the string contains "bba", and we want to accept exactly those strings that do not contain "bba"._ #pagebreak() == _Answer:_ See text file `2-2.txt` _Motivation:_ - *s0* is the start state and also the state for an even number of 'a's. If it sees an 'a', it moves to *s1* (indicating that it has now seen an odd number of 'a's). If it sees a 'b', it stays in *s0* because 'b' does not affect the count of 'a's. - *s1* is the state for an odd number of 'a's. If it sees an 'a', it moves back to *s0* (indicating that it has now seen an even number of 'a's). If it sees a 'b', it stays in *s1* because 'b' does not affect the count of 'a's. _The DFA accepts a string if and only if it is in s0 at the end of the string. This is because being in *s0* means that the string contains an even number of 'a's, and we want to accept exactly those strings._ == _Answer:_ See text file `2.3.txt` _Motivation:_ Given two DFAs $A_1 = (Q_1,Sigma, delta_1,q_01,F_1)$ and $A_2 = (Q_2,Sigma, delta_2,q_02,F_2)$ with the same alphabet, we can construct a DFA $A_1 times.circle A_2$ that satisfies the following property: $ L(A_1 times.circle A_2) = L(A_1) sect L(A_2) $ Construction: $ A_1 times.circle A_2 = (Q_1 times Q_2,Sigma, delta,(q_01,q_02),F_1 times F_2) $ where $ delta((s_1,s_2), a) = (delta_1(s_1,a),delta_2(s_2,a)) $ = == _Answer:_ See text file `3-1.txt` _Motivation:_ Given two DFAs $A_1 = (Q_1,Sigma, delta_1,q_01,F_1)$ and $A_2 = (Q_2,Sigma, delta_2,q_02,F_2)$ with the same alphabet, we can construct a DFA $A_1 plus.circle A_2$ that satisfies the following property: $ L(A_1 plus.circle A_2) = L(A_1) union L(A_2) $ Construction: $ A_1 plus.circle A_2 = (Q_1 times Q_2,Sigma, delta,(q_01,q_02),F_1 union F_2) $ where $ delta((s_1,s_2), a) = (delta_1(s_1,a),delta_2(s_2,a)) $ *Important:* this also applies for NFAs. == _Answer:_ See text file `3-2.txt` _Motivation:_ First we omitted the inaccessable states in the NFA, and then we construced the DFA with subset construction. The DFA is constructed by creating a state for each subset of the states of the NFA.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-16A70.typ
typst
Apache License 2.0
#let data = ( ("TANGSA LETTER OZ", "Lo", 0), ("TANGSA LETTER OC", "Lo", 0), ("TANGSA LETTER OQ", "Lo", 0), ("TANGSA LETTER OX", "Lo", 0), ("TANGSA LETTER AZ", "Lo", 0), ("TANGSA LETTER AC", "Lo", 0), ("TANGSA LETTER AQ", "Lo", 0), ("TANGSA LETTER AX", "Lo", 0), ("TANGSA LETTER VZ", "Lo", 0), ("TANGSA LETTER VC", "Lo", 0), ("TANGSA LETTER VQ", "Lo", 0), ("TANGSA LETTER VX", "Lo", 0), ("TANGSA LETTER EZ", "Lo", 0), ("TANGSA LETTER EC", "Lo", 0), ("TANGSA LETTER EQ", "Lo", 0), ("TANGSA LETTER EX", "Lo", 0), ("TANGSA LETTER IZ", "Lo", 0), ("TANGSA LETTER IC", "Lo", 0), ("TANGSA LETTER IQ", "Lo", 0), ("TANGSA LETTER IX", "Lo", 0), ("TANGSA LETTER UZ", "Lo", 0), ("TANGSA LETTER UC", "Lo", 0), ("TANGSA LETTER UQ", "Lo", 0), ("TANGSA LETTER UX", "Lo", 0), ("TANGSA LETTER AWZ", "Lo", 0), ("TANGSA LETTER AWC", "Lo", 0), ("TANGSA LETTER AWQ", "Lo", 0), ("TANGSA LETTER AWX", "Lo", 0), ("TANGSA LETTER UIZ", "Lo", 0), ("TANGSA LETTER UIC", "Lo", 0), ("TANGSA LETTER UIQ", "Lo", 0), ("TANGSA LETTER UIX", "Lo", 0), ("TANGSA LETTER FINAL NG", "Lo", 0), ("TANGSA LETTER LONG UEX", "Lo", 0), ("TANGSA LETTER SHORT UEZ", "Lo", 0), ("TANGSA LETTER SHORT AWX", "Lo", 0), ("TANGSA LETTER UEC", "Lo", 0), ("TANGSA LETTER UEZ", "Lo", 0), ("TANGSA LETTER UEQ", "Lo", 0), ("TANGSA LETTER UEX", "Lo", 0), ("TANGSA LETTER UIUZ", "Lo", 0), ("TANGSA LETTER UIUC", "Lo", 0), ("TANGSA LETTER UIUQ", "Lo", 0), ("TANGSA LETTER UIUX", "Lo", 0), ("TANGSA LETTER MZ", "Lo", 0), ("TANGSA LETTER MC", "Lo", 0), ("TANGSA LETTER MQ", "Lo", 0), ("TANGSA LETTER MX", "Lo", 0), ("TANGSA LETTER KA", "Lo", 0), ("TANGSA LETTER KHA", "Lo", 0), ("TANGSA LETTER GA", "Lo", 0), ("TANGSA LETTER NGA", "Lo", 0), ("TANGSA LETTER SA", "Lo", 0), ("TANGSA LETTER YA", "Lo", 0), ("TANGSA LETTER WA", "Lo", 0), ("TANGSA LETTER PA", "Lo", 0), ("TANGSA LETTER NYA", "Lo", 0), ("TANGSA LETTER PHA", "Lo", 0), ("TANGSA LETTER BA", "Lo", 0), ("TANGSA LETTER MA", "Lo", 0), ("TANGSA LETTER NA", "Lo", 0), ("TANGSA LETTER HA", "Lo", 0), ("TANGSA LETTER LA", "Lo", 0), ("TANGSA LETTER HTA", "Lo", 0), ("TANGSA LETTER TA", "Lo", 0), ("TANGSA LETTER DA", "Lo", 0), ("TANGSA LETTER RA", "Lo", 0), ("TANGSA LETTER NHA", "Lo", 0), ("TANGSA LETTER SHA", "Lo", 0), ("TANGSA LETTER CA", "Lo", 0), ("TANGSA LETTER TSA", "Lo", 0), ("TANGSA LETTER GHA", "Lo", 0), ("TANGSA LETTER HTTA", "Lo", 0), ("TANGSA LETTER THA", "Lo", 0), ("TANGSA LETTER XA", "Lo", 0), ("TANGSA LETTER FA", "Lo", 0), ("TANGSA LETTER DHA", "Lo", 0), ("TANGSA LETTER CHA", "Lo", 0), ("TANGSA LETTER ZA", "Lo", 0), (), ("TANGSA DIGIT ZERO", "Nd", 0), ("TANGSA DIGIT ONE", "Nd", 0), ("TANGSA DIGIT TWO", "Nd", 0), ("TANGSA DIGIT THREE", "Nd", 0), ("TANGSA DIGIT FOUR", "Nd", 0), ("TANGSA DIGIT FIVE", "Nd", 0), ("TANGSA DIGIT SIX", "Nd", 0), ("TANGSA DIGIT SEVEN", "Nd", 0), ("TANGSA DIGIT EIGHT", "Nd", 0), ("TANGSA DIGIT NINE", "Nd", 0), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/minerva-report-fcfm/0.1.0/template/main.typ
typst
Apache License 2.0
#import "@preview/minerva-report-fcfm:0.1.0" as minerva #import "meta.typ" as meta #show: minerva.report.with( meta, showrules: true, ) //#minerva.abstract[ //] #outline() = Escribiendo simples parrafos Typst toma bastante de Markdown y secuencias de carácteres especiales puedes dar estilo al texto, por ejemplo, puedes usar negrite *abc*, itálica _oooo_ y monoespaciado `typst watch main.typ`. Un parrafo nuevo se hace simplemente con 2 saltos de línea. == El símbolo igual `=` se usa para crear un heading En LaTeX se usa `\` para utilizar comandos, en Typst usamos `#`, hay muchas utilidades como emoji #emoji.face.happy = Elementos == Ecuaciones Las ecuaciones dentro de línea se hacen con símbolos peso `$`, así: $sqrt(epsilon/phi + c/d)$ Y en su propia línea con `$ x $`, los espacios son importantes: $ sqrt(epsilon/phi + c/d) $ == Figuras y referencias Una figura se introduce con `figure`: #figure( caption: "Una tabla dentro de una figura.", table(columns: 2)[nombre][tiempo][Viajar a la U][30 minutos] ) <mi-tabla> A la tabla le agregamos `<mi-tabla>` para poder referenciarlar con @mi-tabla = Necesitas más ayuda? La documentación de typst es muy buena explicando los conceptos claves para usarlo. - Puedes partir leyendo el tutorial: https://typst.app/docs/tutorial/ - Si tienes expericiencia en LaTeX, entonces la guía para usuarios de LaTeX es un buen punto de partida: https://typst.app/docs/guides/guide-for-latex-users/ - Para consultas específicas, está el servidor de Discord de Typst: https://discord.gg/2uDybryKPe
https://github.com/hu-hicoder/embedded-rust-seminar
https://raw.githubusercontent.com/hu-hicoder/embedded-rust-seminar/main/chapter1/chapter1.typ
typst
#import "@preview/touying:0.4.2": * #import "@preview/pinit:0.1.3": * #import "@preview/sourcerer:0.2.1": code #set text(font: "Noto Sans JP", lang: "ja") #let set_link(url) = link(url)[#text(olive)[[link]]] // Themes: default, simple, metropolis, dewdrop, university, aqua #let s = themes.metropolis.register(aspect-ratio: "16-9") #let s = (s.methods.info)( self: s, title: [組み込みRust講習会], subtitle: [Rust編], author: [JIJINBEI], date: datetime.today(), institution: [HiCoder], ) #let (init, slides, touying-outline, alert, speaker-note) = utils.methods(s) #show: init #show strong: alert #let (slide, empty-slide, title-slide, focus-slide) = utils.slides(s) #show: slides = はじめに 組み込みRust講習会へようこそ #h(1em) #box(stroke: black, inset: 0.7em)[この講習会を開いた理由] - 組み込みRustが難しくて私の学習が進まないので、一緒に学べる仲間を作りたい - Rustの普及 - ソフト、競プロだけをやるな!!ハードもやれ!! = 目標 #grid( columns: (70%, 30%), column-gutter: 2%, [ - Rustの基本的な文法を理解する - 難解な所有権、ライフタイムの概念を理解する - 「基礎からわかる組み込みRust」や組み込みRustの公式ドキュメントを難なく読めるようになる ], figure( image("image/embedded_rust_book.jpg"), ), ) = Rustとは == Rustとは - Mozillaが開発したプログラミング言語 - Rustは最も愛されている言語として7年目を迎え、87%の開発者が使い続けたいと答えている。 #set_link("https://survey.stackoverflow.co/2022/#most-loved-dreaded-and-wanted-language-love-dread") - 最近のオープンソースはすべてRustで書かれていると言っても過言ではない#footnote[このスライドもRust製のTypstで作成] == Rustが好まれている理由 #absolute-place( dx: 65%, dy: 40%, image("image/Rust.png", height: 50%) ) - 安全性 - 型安全性 - メモリ安全性 - *所有権* - *ライフタイム* - 処理速度の速さ - 並行処理 - 所有権によるデータ競合の防止 - バージョンやパッケージ管理 - cargo - テストがしやすい = 変数 == 変数 `let`で変数の定義 #code( lang: "rust", ```rust fn main() { let x = 5; println!("The value of x is: {}", x); x = 6; // ERROR println!("The value of x is: {}", x); } ```, ) 変数を可変するには、`mut`を使う #code( lang: "rust", ```rust fn main() { let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); } ```, ) = データ型 == データ型(数値) - Rustは静的型付け言語 #grid( columns: (50%, 50%), figure( table( columns: 3, [大きさ],[符号付き],[符号なし], [8-bit],[i8],[u8], [16-bit],[i16],[u16], [32-bit],[i32],[u32], [64-bit],[i64],[u64], [arch],[isize],[usize], ), caption: [整数型] ), figure( table( columns: 2, [大きさ],[浮動小数点], [32-bit],[f32], [64-bit],[f64], ), caption: [浮動小数点型] ) ) ほかには`char`型(`a`, `b`, `c` ...)や`bool`型(`true`, `false`)などがある = 配列 == 配列 - 配列は同じ型の要素を持つ #code( lang: "rust", ```rust fn main() { let a: [i32; 5] = [1, 2, 3, 4, 5]; } ```, ) `i32`が5つの要素を持つ配列`a`を定義で配列の長さは変更できない #pagebreak() 文字列は文字(`char`)の配列 文字列は、主に`&str`型と`String`型がある #code( lang: "rust", ```rust fn main() { let world: &str = "world!"; println!("Hello, {}", world); } ```, ) #code( lang: "rust", ```rust fn main() { let mut world: String = String::from("world"); world.push_str("!"); println!("Hello, {}", world); } ```, ) `String`型は配列の長さを変更できる `String`はデータの書き込み、`&str`はデータの読み込みを行うときに使うとよい = 関数、制御フロー 省略 = 構造体とメソット #code( lang: "rust", ```rust #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50 }; println!( "The area of the rectangle is {} square pixels.", rect1.area() ); } ``` ) 関連するデータと機能を1つの単位にまとめることで、コードの体系化と再利用性が向上する `new`メソットで構造体を生成する書きかたが一般的 #code( lang: "rust", ```rust impl Rectangle { fn new(width: u32, height: u32) -> Self { Rectangle { width, height } } } fn main() { let rect1 = Rectangle::new(30, 50); } ``` ) = ジェネリック プログラムを抽象化すると、コードの再利用性が高まり、可読性が向上する #code( lang: "rust", ```rust struct Point<T> { x: T, y: T, } fn main() { let integer = Point { x: 5, y: 10 }; let float = Point { x: 1.0, y: 4.0 }; } ``` ) ジェネリック`<T>`を用いることで、`i32`型や`f64`型などの複数型を受け取ることができる#footnote[ ジェネリックが用いられている標準ライブラリの例: `Option<T>`, `Result<T, E>` この型はエラーを扱うときに用いられる型 ] = トレイト トレイトは、複数の型で共有される振る舞い(メソッド)を定義するインターフェースのような機能 以下の例では、`Summary`トレイトを定義し、`NewsArticle`と`Tweet`構造体に`Summary`トレイトを実装している #code( lang: "rust", ```rust pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {} ({})", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) } } fn main() { let tweet = Tweet { username: String::from("horse_ebooks"), content: String::from( "of course, as you probably already know, people", ), reply: false, retweet: false, }; println!("1 new tweet: {}", tweet.summarize()); } ``` ) = 所有権とライフタイム == 所有権の不便な例 Rustのキモいところ #code( lang: "rust", ```rust fn main() { let s1 = String::from("hello"); let s2 = s1; // println!("{}, world!", s1); // ERROR println!("{}, world!", s2); } ```, ) #code( lang: "rust", ```rust fn main() { let s = String::from("hello"); takes_ownership(s); // println!("{}", s); // ERROR } fn takes_ownership(some_string: String) { println!("{}", some_string); } ```, ) == 所有権のルール 公式ドキュメントにかかれている所有権規則 - *各値は、所有者と呼ばれる変数と対応している。* - *いかなる時も所有者は一つである。* - *所有者がスコープから外れたら、値は破棄される。* - *変数をアサインする(`let x = y`)際や、関数に引数を値渡しする(`foo(x)`)際は、所有権が移動(move)* 参照規則 - *任意のタイミングで、一つの可変参照か不変な参照いくつでものどちらかを行える。* - *参照は常に有効でなければならない。* - *同義) 生存期間の長いものが、短いものを参照してはいけない* #h(1em) #align(center)[????????] == ヒープとスタック 所有権を理解するためには、ヒープとスタックを理解する必要がある #grid( columns: (80%, 20%), [ - TEXT領域 - 機械語に翻訳されたプログラム - DATA領域 - 初期値 - global変数, 静的変数 - *HEAP領域* - 寿命がある値(可変長) - `malloc()`でヒープ領域を確保し、`free()`でメモリの開放 - *STACK領域* - stack(下から積み上げ)をしていく寿命がある値(固定長) - 関数の引数、ローカル変数 - 配列の場合、ヒープ領域を参照するポインタ ], figure( image("image/Memory.svg"), ), ) == バイナリを見る Rustのバイナリを見てよう #code( lang: "terminal", ```bash $ objdump -S binary_file $ objdump -h binary_file ``` ) `.text`や`.rodata`や`.bss`(heapに対応?)がある == 所有権のイメージ 所有権は、*変数にメモリの解放をする責任を持たせる* #box(stroke: black, inset: 0.5em)[知っておくこと] - *値と変数の意味は異なる* - 値は具体的なデータで、変数は値の名前 - スコープの領域が展開されると、スタックは下から積み上げられ、ヒープで値を確保される - 所有権を持っている変数たちは、スコープの外で、ヒープのメモリは解放され、スタックはポップされる - &で値を参照したら返さないといけない(*借用*) イラストで理解しよう!! == 文字列の実態 `String`の実態はポインタ、長さ、容量の3つの要素とヒープ上の文字列(値) `&str`の実態はポインタと長さの2つの要素とヒープ上の文字列 $=>$ スタック領域のデータは固定長に落ちている == 所有権のイメージ(値と変数) #grid( columns: (50%, 50%), gutter: 2%, code( lang: "rust", ```rust fn main() { let s1 = String::from("hello world"); let s2 = s1; } ``` ), figure( image("image/variable_value.svg"), ), ) s1とs2は、同じ値を指している s2がs1の後に使えないのは、値を持っている所有権がs2に移動しているから == 所有権のイメージ(スコープ1) #code( lang: "rust", ```rust fn main() { let x = String::from("hello"); func(); } fn func() { let s1 = String::from("world"); } ``` ) #grid( columns: (33%, 33%, 33%), gutter: 2%, figure( image("image/scope_free1.svg"), ), figure( image("image/scope_free2.svg"), ), figure( image("image/scope_free3.svg"), ) ) funcのスコープの外で所有権を持っている`s1`が破棄される == 所有権のイメージ(スコープ2) #code( lang: "rust", ```rust fn main() { let x = String::from("hello"); let s2 = func(); } fn func() -> String { let s1 = String::from("world"); s1 } ``` ) #grid( columns: (50%, 50%), gutter: 2%, figure( image("image/scope1.svg"), ), figure( image("image/scope2.svg"), ) ) == 所有権のイメージ(所有権の移動) #code( lang: "rust", ```rust fn main() { let x = String::from("hello world"); func(x); } fn func(s: String) { println!("{}", s); } ``` ) #grid( columns: (33%, 33%, 33%), gutter: 2%, figure( image("image/move1.svg"), ), figure( image("image/move2.svg"), ), figure( image("image/move3.svg"), ) ) 引数に所有権を渡すと、所有権が移動する このあと、`x`を使うことができない == 所有権のイメージ(借用) #grid( columns: (50%, 50%), gutter: 2%, code( lang: "rust", ```rust fn main() { let x = String::from("hello world"); func(&x); } fn func(f: &str) { println!("{}", f); } ``` ), figure( image("image/reference.svg"), ), ) - `f`は`x`の値を借りている - `f`のほうが寿命が短いので、`x`を参照できる - `func(&x)`のあとで`x`は、メモリを解放されていないので使うことができる - 参照している間に、`x`を変更することはできない == では、こちらはどうなる? #code( lang: "rust", ```rust fn main() { let x = f(); } fn f() -> Vec<String> { let mut v = vec![String::from("hello")]; let a: String = String::from("!!"); v.push(a); v } ``` ) #code( lang: "rust", ```rust fn main() { let x = f(); } fn f() -> Vec<&str> { let v = vec!["hello", "world"]; let a: &str = "!!"; v.push(a); v } ``` ) #pagebreak() それではこちらはどうなる? #code( lang: "rust", ```rust fn main() { let s = "hello"; let x = f(s); } fn f(s: &str) -> Vec<&str> { let mut v = vec!["hello"]; v.push(s); v } ``` ) = 参照 - まず参照は危険という認識が必要 - 参照先を書き換えると、そのデータを利用している他の参照にも影響がある 可変な参照を行うには、 #code( lang: "rust", ```rust fn main() { let mut s = String::from("hello"); change(&mut s); } fn change(some_string: &mut String) { some_string.push_str(", world"); } ``` ) 制約として、可変な参照は1つのスコープ内で1つしか持てない == ライフタイム - `x`のほうが`f`よりも長く生存している - `func`あとに`x`を使えるか使えないかは - heapのメモリが解放されているかどうか - 所有権を持っているかどうか *ライフタイム*(その参照が有効になるスコープ)が自然にわかる #code( lang: "rust", ```rust { let r; { let x = 5; r = &x; } println!("r: {}", r); // ERROR } ``` ) == メモリ安全性 ヒープ領域が`free`されると、スタック領域にあるポインタが無効になる 所有権では絶対に以下の問題が起こらない - ダンダリングポインタ:メモリ領域の無効な場所を指し示しているポインタ - 2重freeが起こると、メモリの破壊が起こる == 問題1 通る? #code( lang: "rust", ```rust fn main() { let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.clear(); println!("The first element is: {}", first); } ``` ) #pause - vの要素への参照を保持したまま、vの内容をクリアしている - 無効な参照を引き起こす可能性があるため、コンパイラによってエラーとして検出される == 問題2 #code( lang: "rust", ```rust fn add_to_slice(slice: &[str], new_item: &str) { slice.push(new_item); } fn main() { let mut words = vec!["hello", "world"]; let slice = &mut words[..]; add_to_slice(slice, "!"); } ``` ) #pause `&[str]`は`push`というメソッドを持っていない もっていたとしても、所有権を借りている身で`words`の配列の長さを変更することはできない == 問題3 #code( lang: "rust", ```rust fn get_slice_length(slice: &[str]) -> usize { slice.len() } fn main() { let words = vec!["hello", "world"]; let slice = &words[..]; println!("Slice length: {}", get_slice_length(slice)); } ``` ) #pause `&[str]`で参照渡しをしており、データの所有権を移動していない データの長さを取得している(非加工)ので、問題ない == 問題4 #code( lang: "rust", ```rust struct Person { name: String, age: u32, } fn main() { let p = Person { name: String::from("Alice"), age: 30, }; let name = p.name; println!("The person's age is: {}", p.age); println!("The person's name is: {}", p.name); } ``` ) #pause 構造体の一部のフィールド(name)を移動させると、元の構造体全体が部分的に移動した状態になり、移動されたフィールドにアクセスできなくなる = $+alpha$ 追加でしゃべりたいこと - `Result`と`Option`の使い方 - `ptr`と`len`の万能さ - 配列のスライス - 文字列の抽出 - `Copy`しないことのメモリ効率 - `'static`, `const`のデータは`.rodata`にある - `let x = 5; let y = x;`は`Copy`なので注意 - Rustはバッファオーバーフロー攻撃がないメモリ安全 - 型安全性 // - 並列処理と所有権 = 参考文献 - The Rust Programming Language 日本語版 #set_link("https://doc.rust-jp.rs/book-ja/") - コードをたくさん引用しました。ありがとうございます。 - 【Rust入門】宮乃やみさんにRustの所有権とライフタイムを絶対理解させる #set_link("https://www.youtube.com/watch?v=lG7YbM2AfU8") - 所有権の世界一わかりやすい説明
https://github.com/Wybxc/typst-packages
https://raw.githubusercontent.com/Wybxc/typst-packages/master/packages/local/simple-chinese/0.1.0/lib.typ
typst
#let project(title: "", authors: (), date: none, body) = { set document(author: authors, title: title) set page(numbering: "1 / 1", number-align: end) set text( font: ("Inria Serif", "FZNewShuSong-Z10", "Source Han Serif SC"), weight: "medium", lang: "zh", ) set heading(numbering: "1 ") show heading: it => { set text(font: ("Inria Serif", "Source Han Serif SC")) set par(justify: true, first-line-indent: 0em) if it.level == 1 [ #v(1em) #align(center)[ #counter(heading).display() #text(it.body) #v(1em, weak: true) ] ] else [ #strong(it.body) ] } show emph: it => { set text(font: "AR PL UKai") it.body } show strong: it => { set text(font: "Source Han Sans SC", weight: "medium") it.body } show raw: set text(font: ("Monaspace Neon", "Sarasa Mono SC")) show math.equation: set text( font: ("New Computer Modern Math", "FZNewShuSong-Z10", "Source Han Serif SC"), ) set list(indent: 2em) set enum(indent: 2em) set par(justify: true, first-line-indent: 2em) // Title row. align(center)[ #block(text( font: ("Inria Serif", "Source Han Serif SC"), weight: "bold", 2em, title, )) #v(1.5em, weak: true) #text(weight: "semibold", date) ] // Author information. pad(bottom: 0.25em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..authors.map(author => align(center, author)), )) // Main body. body } #let new-par = { $ $ v(-1.65em) }
https://github.com/lucas-bublitz/tUDESC
https://raw.githubusercontent.com/lucas-bublitz/tUDESC/main/main.typ
typst
Creative Commons Zero v1.0 Universal
//tUDESC é um delo para trabalhos acadêmicos da UDESC, //sua utilização é livre e gratuita. #import "macros.typ": * #import "template.typ": udesc #let config = ( abstract: [pipoca], title : [Manual de Trabalho Acadêmico da UDESC], authors : "é", epigraph : none, congratulations : none, ) //Chamamento da função udesc para todo o documento. //Essa função aplica o modelo. #show: doc => udesc( config, doc ) = 0000 == ----------
https://github.com/smorad/um_cisc_7026
https://raw.githubusercontent.com/smorad/um_cisc_7026/main/lecture_5_classification.typ
typst
#import "@preview/polylux:0.3.1": * #import themes.university: * #import "@preview/cetz:0.2.2": canvas, draw, plot #import "common.typ": * #import "@preview/algorithmic:0.1.0" #import algorithmic: algorithm // FUTURE TODO: Remove event space, only sample space // FUTURE TODO: Fix bounds for probs (0, 1) or [0, 1] #set math.vec(delim: "[") #set math.mat(delim: "[") #let ag = ( [Review], [Torch optimization coding], [Classification task], [Probability review], [Define model $f$], [Define loss function $cal(L)$], [Find $bold(theta)$ that minimize $cal(L)$], [Coding] ) #show: university-theme.with( aspect-ratio: "16-9", short-title: "CISC 7026: Introduction to Deep Learning", short-author: "<NAME>", short-date: "Lecture 5: Classification" ) #title-slide( // Section time: 34 mins at leisurely pace title: [Classification], subtitle: "CISC 7026: Introduction to Deep Learning", institution-name: "University of Macau", //logo: image("logo.jpg", width: 25%) ) #slide(title: [Admin])[ We will have a make-up lecture later on for the missed lecture #pause Assignment 1 grades were released on moodle #pause The scores were very good, with a mean of approximately 90/100 #pause I am still grading quiz 2, but I had a look at the responses to question 4 ] #slide(title: [Admin])[ Some requests from students: #pause + More coding, less theory #pause + More math/theory #pause + Too easy, go faster #pause + Speak slower #pause + Course is too hard #pause + Course is perfect #pause + Move captions to top of screen #pause + Upload powerpoint before lecture #pause There are conflicting student needs ] #slide(title: [Admin])[ https://github.com/smorad/um_cisc_7026 ] //11:30 #aslide(ag, none) #aslide(ag, 0) #sslide[ Last time, we reviewed derivatives #pause $ f'(x) = d / (d x) f = (d f) / (d x) = lim_(h -> 0) (f(x + h) - f(x)) / h $ #pause and gradients #pause $ gradient_(bold(x)) f(mat(x_1, x_2, dots, x_n)^top) = mat((partial f) / (partial x_1), (partial f) / (partial x_2), dots, (partial f) / (partial x_n))^top $ ] #sslide[ Gradients are important in deep learning for two reasons: #pause $ bold("Reason 1:") f(bold(x)) "has critical points at" gradient_bold(x) f(bold(x)) = 0 $ #pause #cimage("figures/lecture_5/saddle.png") #pause With optimization, we attempt to find minima of loss functions ] #sslide[ Gradients are important in deep learning for two reasons: #pause *Reason 2:* For problems without analytical solutions, the gradient (slope) is necessary for gradient descent #pause #cimage("figures/lecture_4/gradient_descent_3d.png", height: 60%) ] #sslide[ First, we derived the solution to linear regression #pause $ cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i=1)^n ( f(bold(x)_[i], bold(theta)) - bold(y)_[i] )^2 $ #pause $ cal(L)(bold(X), bold(Y), bold(theta)) = ( bold(Y) - bold(X)_D bold(theta) )^top ( bold(Y) - bold(X)_D bold(theta) ) $ #pause $ cal(L)(bold(X), bold(Y), bold(theta)) = underbrace(underbrace(( bold(Y) - bold(X)_D bold(theta) )^top, "Linear function of " theta quad) underbrace(( bold(Y) - bold(X)_D bold(theta) ), "Linear function of " theta), "Quadratic function of " theta) $ ] #sslide[ #side-by-side[A quadratic function has a single critical point, which must be a global minimum][#cimage("figures/lecture_4/quadratic_parameter_space.png", height: 100%)] ] #sslide[ We found the analytical solution for linear regression by finding where the gradient was zero and solving for $bold(theta)$ #pause $ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = 0 $ #pause $ bold(theta) = (bold(X)_D^top bold(X)_D)^(-1) bold(X)_D^top bold(Y) $ #pause Which solves $ argmin_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) $ ] #sslide[ For neural networks, the square error loss is no longer quadratic #pause #side-by-side[$ cal(L)(x, y, bold(theta)) = (f(x, bold(theta)) - y)^2 $][Loss function] #pause #side-by-side[$ f(x, bold(theta)) = sigma(theta_0 + theta_1 x) $][Neural network model] #pause Now, we plug the model $f$ into the loss function #pause $ cal(L)(x, y, bold(theta)) = (sigma(theta_0 + theta_1 x) - y)^2 $ #pause $ cal(L)(x, y, bold(theta)) = underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta) underbrace((sigma(theta_0 + theta_1 x) - y), "Nonlinear function of" theta) $ #pause There is no analytical solution for $bold(theta)$ ] #sslide[ Instead, we found the parameters of a neural network through gradient descent #pause Gradient descent is an optimization method for differentiable functions #pause We went over both the intuition and mathematical definitions ] #sslide[ #side-by-side[ #cimage("figures/lecture_4/lightning.jpg", height: 100%) #pause ][ #cimage("figures/lecture_4/hiking_slope.jpg", height: 100%) ] ] #sslide[ #cimage("figures/lecture_4/parameter_space.png", height: 100%) ] #sslide[ The gradient descent algorithm: #algorithm({ import algorithmic: * Function("Gradient Descent", args: ($bold(X)$, $bold(Y)$, $cal(L)$, $t$, $alpha$), { Cmt[Randomly initialize parameters] Assign[$bold(theta)$][$cal(N)(0, 1)$] For(cond: $i in 1 dots t$, { Cmt[Compute the gradient of the loss] Assign[$bold(J)$][$gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta))$] Cmt[Update the parameters using the negative gradient] Assign[$bold(theta)$][$bold(theta) - alpha bold(J)$] }) Return[$bold(theta)$] }) }) ] #sslide[ We derived the $gradient_bold(theta) cal(L)$ for deep neural networks using the chain rule #pause $ gradient_bold(theta) cal(L)(bold(X), bold(Y), bold(theta)) = sum_(i = 1)^n 2 ( f(bold(x)_[i], bold(theta)) - bold(y)_[i]) #redm[$gradient_bold(theta) f(bold(x)_[i], bold(theta))$] $ #pause $ #redm[$gradient_(bold(theta)) f(bold(x), bold(theta))$] = gradient_(bold(phi), bold(psi), dots, bold(xi)) f(bold(x), mat(bold(phi), bold(psi), dots, bold(xi))^top) = vec( gradient_bold(phi) f_1(bold(x), bold(phi)), gradient_(bold(psi)) f_2(bold(z)_1, bold(psi)), dots.v, #redm[$gradient_(bold(xi)) f_(ell)(bold(z)_(ell - 1), bold(xi))$] ) $ #pause $ #redm[$gradient_(bold(xi)) f_ell (bold(z)_(ell - 1), bold(xi))$] = (sigma(bold(xi)^top overline(bold(z))_(ell - 1)) dot.circle (1 - sigma(bold(xi)^top overline(bold(z))_(ell - 1)))) overline(bold(z))_(ell - 1)^top $ ] #sslide[ We ran into issues computing the gradient of a layer because of the Heaviside step function #pause We replaced it with a differentiable (soft) approximation called the sigmoid function #pause #side-by-side[#cimage("figures/lecture_4/heaviside.svg")][#cimage("figures/lecture_4/sigmoid.svg")][ $ sigma(z) = 1 / (1 + e^(-z)) $] ] #sslide[ In `jax`, we compute the gradient using the `jax.grad` function #pause ```python import jax def L(theta, X, Y): ... # Create a new function that is the gradient of L # Then compute gradient of L for given inputs J = jax.grad(L)(X, Y, theta) # Update parameters alpha = 0.0001 theta = theta - alpha * J ``` ] #sslide[ In `torch`, we backpropagate through a graph of operations ```python import torch optimizer = torch.optim.SGD(lr=0.0001) def L(model, X, Y): ... # Pytorch will record a graph of all operations # Everytime you do theta @ x, it stores inputs and outputs loss = L(X, Y, model) # compute loss # Traverse the graph backward and compute the gradient loss.backward() # Sets .grad attribute on each parameter optimizer.step() # Update the parameters using .grad optimizer.zero_grad() # Set .grad to zero, DO NOT FORGET!! ``` ] #aslide(ag, 1) #aslide(ag, 2) // 30:00 #sslide[ First, a video of one application of gradient descent https://youtu.be/kGDO2e_qiyI?si=ZopZKy-6WQ4B0csX #pause #v(1em) Time for some interactive coding https://colab.research.google.com/drive/1W8WVZ8n_9yJCcOqkPVURp_wJUx3EQc5w ] // ~60:00 #aslide(ag, 1) #aslide(ag, 2) #sslide[ Many problems in ML can be reduced to *regression* or *classification* #pause *Regression* asks how many #pause - How long will I live? #pause - How much rain will there be tomorrow? #pause - How far away is this object? #pause *Classification* asks which one #pause - Is this a dog or muffin? #pause - Will it rain tomorrow? Yes or no? #pause - What color is this object? #pause So far, we only looked at regression. Now, let us look at classification ] #slide[ *Task:* Given a picture of clothes, predict the text description #pause $X: bb(Z)_(0,255)^(32 times 32) #image("figures/lecture_5/classify_input.svg", width: 80%)$ #pause $Y : & {"T-shirt, Trouser, Pullover, Dress, Coat,"\ & "Sandal, Shirt, Sneaker, Bag, Ankle boot"}$ #pause *Approach:* Learn $bold(theta)$ that produce *conditional probabilities* #pause $ f(bold(x), bold(theta)) = P(bold(y) | bold(x)) = P(vec("T-Shirt", "Trouser", dots.v) mid(|) #image("figures/lecture_5/shirt.png", height: 20%)) = vec(0.2, 0.01, dots.v) $ ] #aslide(ag, 2) #aslide(ag, 3) #slide[ Classification tasks require *probability theory*, so let us review #pause In probability, we have *experiments* and *outcomes* #pause An experiment yields one of many possible outcomes #pause #side-by-side[Experiment][Outcome] #pause #side-by-side[Flip a coin][Heads] #pause #side-by-side[Walk outside][Rain] #pause #side-by-side[Grab clothing from closest][Coat] ] #slide[ The *sample space* $S$ defines all possible outcomes for an experiment #pause #side-by-side[Experiment][Sample Space $S$] #pause #side-by-side[Flip a coin][$ S = {"heads", "tails"} $] #pause #side-by-side[Walk outside][$ S = {"rain", "sun", "wind", "cloud"} $] #pause #side-by-side[Take clothing from closet][$ S = {"T-shirt", "Trouser", "Pullover", "Dress", \ "Coat", "Sandal", "Shirt", "Sneaker", "Bag", \ "Ankle boot"} $] ] #slide[ An *event* $E$ is a specific subset of the sample space #pause #side-by-side[Experiment][Sample Space][Event] #pause #side-by-side[Flip a coin][$ S = {"heads", "tails"} $][$ E = {"heads"} $] #pause #side-by-side[Walk outside][$ S = {"rain", "sun", "wind", "cloud"} $][$ E = {"rain", "wind"} $] #pause #side-by-side[Take from closet][$ { "T-shirt", "Trouser", \ "Pullover", "Dress", \ "Coat", "Sandal", "Shirt", \ "Sneaker", "Bag", "Ankle boot"} $][$ E = {"Shirt", "T-Shirt", "Coat"} $] ] #slide[ The *probability* measures how likely an event is to occur #pause The probability must be between 0 (never occurs) and 1 (always occurs) #pause $ 0 <= P(E) <= 1 $ #pause #side-by-side[Experiment][Probabilities] #pause #side-by-side[Flip a coin][$ P("heads") = 0.5 $] #pause #side-by-side[Walk outside][$ P("rain") = 0.15 $] #pause #side-by-side[Take from closet][$ P("Shirt") = 0.1 $] ] #slide[ When we define $P$ as a function, we call it a *distribution* #pause $ P: E |-> (0, 1) $ #pause The probabilities (distribution) over the sample space $S$ must sum to one #pause $ sum_(x in S) P(x) = 1 $ #pause #side-by-side[Flip a coin][$ {P("heads") = 0.5, P("tails") = 0.5} $] #pause //#side-by-side[Walk outside][$ {P("rain") = 0.15, P("sun") = 0.5, P("sun_and_rain") = 0.05, \ P("wind") = 0.1, dots } $] #pause #side-by-side[Take clothing from closet][$ {P("T-shirt") = 0.1, P("Trouser") = 0.08, \ P("Pullover") = 0.12, dots } $] ] #slide[ The distribution is a function, so we can plot it #cimage("figures/lecture_5/pmf.jpg", width: 100%) ] #slide[ Events can overlap with each other #pause - Disjoint events #pause - Conditionally dependent events ] #slide[ Two events $A, B$ are *disjoint* if either $A$ occurs or $B$ occurs, *but not both* #pause With disjoint events, $P(A sect B) = 0$ #pause #side-by-side[Flip a coin][ $P("Heads") = 0.5, P("Tails") = 0.5$ $P("Heads" sect "Tails") = 0$ ] #pause Be careful! #side-by-side[Walk outside][ $P("Rain") = 0.1, P("Cloud") = 0.2$ $P("Rain" sect "Cloud") != 0$ ] ] #slide[ If $A, B$ are not disjoint, they are *conditionally dependent* #pause // Event $A$ is *conditionally dependent* on $B$ if $B$ occuring tells us about the probability of $A$ #pause $ P("cloud") = 0.2, P("rain") = 0.1 $ #pause $ P("rain" | "cloud") = 0.5 $ #pause $ P(A | B) = P(A sect B) / P(B) $ #pause #side-by-side[Walk outside][ $P("Rain" sect "Cloud") = 0.1 \ P("Cloud") = 0.2$ $P("Rain" | "Cloud") = 0.1 / 0.2 = 0.5$ ] ] #slide[ *Task:* Given a picture of clothes, predict the text description #pause $X: bb(Z)_(0,255)^(32 times 32) #image("figures/lecture_5/classify_input.svg", width: 80%)$ #pause $Y : & {"T-shirt, Trouser, Pullover, Dress, Coat,"\ & "Sandal, Shirt, Sneaker, Bag, Ankle boot"}$ #pause *Approach:* Learn $bold(theta)$ that produce *conditional probabilities* #pause $ f(bold(x), bold(theta)) = P(bold(y) | bold(x)) = P(vec("T-Shirt", "Trouser", dots.v) mid(|) #image("figures/lecture_5/shirt.png", height: 20%)) = vec(0.2, 0.01, dots.v) $ ] #aslide(ag, 3) #aslide(ag, 4) #slide[ We will again start with a multivariate linear model #pause $ f(bold(x), bold(theta)) = bold(theta)^top overline(bold(x)) $ #pause We want our model to predict the probability of each outcome #pause *Question:* What is the function signature of $f$? #pause *Answer:* $f: bb(R)^(d_x) times Theta |-> bb(R)^(d_y)$ #pause *Question:* Can we use this model to predict probabilities? #pause *Answer:* No! Because probabilities must be $in (0, 1)$ and sum to one //*Question:* What is the range/co-domain of $f$? #pause //*Answer:* $[-oo, oo]$ #pause //However, the probabilities must sum to one #pause //We introduce the *softmax* operator to ensure all probabilities sum to 1 #pause ] #slide[ How can we represent a probability distribution for a neural network? #pause $ bold(v) = { vec(v_1, dots.v, v_(d_y)) mid(|) quad sum_(i=1)^(d_y) v_i = 1; quad v_i in (0, 1) } $ #pause There is special notation for this vector, called the *simplex* #pause $ Delta^(d_y - 1) $ ] #slide[ The simplex $Delta^k$ is an $k - 1$-dimensional triangle in $k$-dimensional space #pause #cimage("figures/lecture_5/simplex.svg", height: 70%) It has only $k - 1$ free variables, because $x_(k) = 1 - sum_(i=1)^(k - 1) x_i$ ] // 96:00 #slide[ $ f: bb(R)^(d_x) times Theta |-> bb(R)^(d_y) $ #pause So we need a function that maps to the simplex #pause $ g: bb(R)^(d_y) |-> Delta^(d_y - 1) $ #pause Then, we can combine $f$ and $g$ $ g(f): bb(R)^(d_x) times Theta |-> Delta^(d_y - 1) $ ] #slide[ We need a function $g$ $ g: bb(R)^(d_y) |-> Delta^(d_y - 1) $ #pause There are many functions that can do this #pause One example is dividing by the $L_1$ norm: $ g(bold(x)) = bold(x) / (sum_(i=1)^(d_y) x_i) $ #pause In deep learning we often use the *softmax* function. When combined with the classification loss the gradient is linear, making learning faster ] #slide[ The softmax function maps real numbers to the simplex (probabilities) $ "softmax": bb(R)^k |-> Delta^(k - 1) $ #pause $ "softmax"(vec(x_1, dots.v, x_k)) = (e^(bold(x))) / (sum_(i=1)^k e^(x_i)) = vec( e^(x_1) / (e^(x_1) + e^(x_2) + dots e^(x_k)), e^(x_2) / (e^(x_1) + e^(x_2) + dots e^(x_k)), dots.v, e^(x_k) / (e^(x_1) + e^(x_2) + dots e^(x_k)), ) $ #pause If we attach it to our linear model, we can output probabilities! $ f(bold(x), bold(theta)) = "softmax"(bold(theta)^top bold(x)) $ ] #slide[ And naturally, we can use the same method for a deep neural network $ f_1(bold(x), bold(phi)) = sigma(bold(phi)^top overline(bold(x))) \ dots.v \ f_ell (bold(x), bold(xi)) = "softmax"(bold(xi)^top overline(bold(x))) $ #pause Now, our neural network can output probabilities $ f(bold(x), bold(theta)) = vec( P("Ankle boot" | #image("figures/lecture_5/shirt.png", height: 10%)), P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%)), dots.v ) = vec(0.25, 0.08, dots.v) $ ] #slide[ *Question:* Why do we output probabilities instead of a binary values $ f(bold(x), bold(theta)) = vec( P("Shirt" | #image("figures/lecture_5/shirt.png", height: 10%)), P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%)), dots.v ) = vec(0.25, 0.08, dots.v); quad f(bold(x), bold(theta)) = vec( 1, 0, dots.v ) $ #pause *Answer 1:* Outputting probabilities results in differentiable functions #pause *Answer 2:* We report uncertainty, which is useful in many applications ] #slide[ #cimage("figures/lecture_5/fashion_mnist_probs.png", height: 80%) ] #aslide(ag, 4) #aslide(ag, 5) #slide[ We consider the label $bold(y)_[i]$ as a conditional distribution $ P(bold(y)_[i] | bold(x)_[i]) = vec( P("Shirt" | #image("figures/lecture_5/shirt.png", height: 10%)), P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%)) ) = vec(1, 0) $ #pause Our neural network also outputs some distribution $ f(bold(x)_[i], bold(theta)) = vec( P("Shirt" | #image("figures/lecture_5/shirt.png", height: 10%)), P("Bag" | #image("figures/lecture_5/shirt.png", height: 10%)) ) = vec(0.6, 0.4) $ #pause What loss function should we use for classification? ] #slide[ $ f(bold(x)_[i], bold(theta)) = vec(0.6, 0.4); quad bold(y)_[i] = vec(1, 0) $ #pause We could use the square error like linear regression #pause $ (0.6 - 1)^2 + (0.4 - 0)^2 $ #pause This can work, but in reality it does not work well #pause Instead, we use the *cross-entropy loss* #pause Let us derive it ] #slide[ We can model $f(bold(x), bold(theta))$ and $bold(y)$ as probability distributions #pause How do we measure the difference between probability distributions? #pause We use the *Kullback-Leibler Divergence (KL)* #pause #cimage("figures/lecture_5/forwardkl.png", height: 50%) ] #slide[ #cimage("figures/lecture_5/forwardkl.png", height: 50%) $ "KL"(P, Q) = sum_i P(i) log P(i) / Q(i) $ ] #slide[ First, write down KL-divergence $ "KL"(P, Q) = sum_i P(i) log P(i) / Q(i) $ #pause Plug in our two distributions $P = f$ and $Q = bold(y)$ $ "KL"(P(bold(y) | bold(x)), f(bold(x), bold(theta))) = sum_(i=1)^(d_y) P(y_i | bold(x)) log P(y_i | bold(x)) / f(bold(x), bold(theta))_i $ ] #slide[ $ "KL"(P(bold(y) | bold(x)), f(bold(x), bold(theta))) = sum_(i=1)^(d_y) P(y_i | bold(x)) log P(y_i | bold(x)) / f(bold(x), bold(theta))_i $ #pause Rewrite the logarithm using the sum rule of logarithms $ "KL"(P(bold(y) | bold(x)), f(bold(x), bold(theta))) = sum_(i=1)^(d_y) P(y_i | bold(x)) (log P(y_i | bold(x)) - log f(bold(x), bold(theta))_i ) $ ] #slide[ $ "KL"(P(bold(y) | bold(x)), f(bold(x), bold(theta))) = sum_(i=1)^(d_y) P(y_i | bold(x)) (log P(y_i | bold(x)) - log f(bold(x), bold(theta))_i ) $ #pause Split the sum into two parts $ = sum_(i=1)^(d_y) P(y_i | bold(x)) log P(y_i | bold(x)) - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i $ ] #slide[ $ = sum_(i=1)^(d_y) P(y_i | bold(x)) log P(y_i | bold(x)) - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i $ #pause The first term is constant, and we will minimize the loss. So $argmin_bold(theta) cal(L) + k = argmin_bold(theta) cal(L)$. Therefore, we can ignore the first term. $ = - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i $ #pause This is the loss for a classification task! We call this the *cross-entropy* loss function ] // 114:00 #slide[ *Example:* #pause $ cal(L)(bold(x), bold(y), bold(theta))= - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i; quad f(bold(x), bold(theta)) = vec(0.6, 0.4); quad bold(y) = vec(1, 0) $ #pause $ = - [ P(y_1 | bold(x)) log f(bold(x), bold(theta))_1 + P(y_2 | bold(x)) log f(bold(x), bold(theta))_2 ] $ #pause $ = - [ 1 dot log 0.6 + 0 dot log 0.4 ] $ #pause $ = - [ -0.22 ] $ #pause $ = 0.22 $ ] #slide[ $ cal(L)(bold(x), bold(y), bold(theta)) = - sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i $ By minimizing the loss, we make $f(bold(x), bold(theta)) = P(bold(y) | bold(x))$ #pause $ argmin_theta cal(L)(bold(x), bold(y), bold(theta)) = argmin_theta [- sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i ] $ #pause $ f(bold(x), bold(theta)) = P(bold(y) | bold(x)) = P(vec("boot", "dress", dots.v) mid(|) #image("figures/lecture_5/shirt.png", height: 20%)) $ ] #slide[ Our loss was just for a single image #pause $ cal(L)(bold(x), bold(y), bold(theta)) = [- sum_(i=1)^(d_y) P(y_i | bold(x)) log f(bold(x), bold(theta))_i ] $ #pause Find $bold(theta)$ that minimize the loss over the whole dataset #pause $ cal(L)(bold(x), bold(y), bold(theta)) = [- sum_(j=1)^n sum_(i=1)^(d_y) P(y_([j], i) | bold(x)_[j]) log f(bold(x)_[j], bold(theta))_i ] $ ] #aslide(ag, 5) #aslide(ag, 6) #sslide[ Find $bold(theta)$ just like before, using gradient descent #pause The gradients are the same as before except the last layer #pause I will not derive any more gradients, but the softmax gradient nearly identical to the sigmoid function gradient #pause $ gradient_bold(theta) "softmax"(bold(z)) = "softmax"(bold(z)) dot.circle (1 - "softmax"(bold(z))) $ #pause This is because softmax is a multi-class generalization of the sigmoid function ] #aslide(ag, 5) // 120:00 #focus-slide[Relax] #aslide(ag, 6) #sslide[ You have everything you need to solve deep learning tasks! + Regression #pause + Classification #pause Every interesting task (chatbot, self driving car, etc): #pause + Construct a deep neural network #pause + Compute regression or classification loss #pause + Optimize with gradient descent #pause The rest of this course will examine neural network architectures ] #sslide[ https://colab.research.google.com/drive/1BGMIE2CjlLJOH-D2r9AariPDVgxjWlqG?usp=sharing ] #sslide[ Homework 3 is released, you have two weeks to complete it #pause https://colab.research.google.com/drive/1LainS20p6c3YVRFM4XgHRBODh6dvAaT2?usp=sharing#scrollTo=q8pJST5xFt-p ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cheda-seu-thesis/0.2.0/seu-thesis/lib.typ
typst
Apache License 2.0
#import "templates/bachelor.typ": bachelor-conf, thanks, appendix #import "templates/degree.typ": degree-conf
https://github.com/Slyde-R/not-jku-thesis-template
https://raw.githubusercontent.com/Slyde-R/not-jku-thesis-template/main/template/content/DataCollection.typ
typst
MIT No Attribution
#import "../utils.typ": todo, silentheading, flex-caption = Data Collection #todo[Replace this chapter!] This chapter details the data collection process used to investigate feline manipulation tactics and their impact on human behavior. The study utilized a combination of observational methods, surveys, and interviews to gather comprehensive data on feline behaviors and human responses. This multi-method approach was designed to provide a well-rounded understanding of how cats influence their human companions. == Observational Study === Procedure Observations were conducted in participants' homes to capture naturalistic interactions between cats and their human caregivers. The study took place over a six-week period, during which various behaviors were recorded to understand manipulation tactics @Horwitz2010. === Data Collection Tools - *Video Recording:* Cameras were placed in key areas of the home to capture feline behaviors unobtrusively. Video recordings allowed for detailed analysis of vocalizations, body language, and attention-seeking actions @Serpell2017. - *Field Notes:* Observers took detailed notes to complement video recordings. These notes provided context and insights into behaviors that were not always captured on camera @Turner2017. === Focus Areas - *Vocalizations:* Different types of vocalizations, such as meows, purrs, and chirps, were documented. Observers noted the frequency, pitch, and context of these vocalizations @McComb2009. - *Body Language:* Behaviors such as kneading, tail positioning, and eye contact were observed and categorized. Attention was given to how these behaviors were used to elicit specific responses from humans @Bradshaw2012. - *Attention-Seeking Behaviors:* Actions like climbing on furniture, rubbing against humans, and bringing objects were recorded to assess their effectiveness in gaining attention or achieving desired outcomes @Odendaal2000. == Surveys === Design Surveys were developed to collect quantitative data on human perceptions of feline behavior and its effects. The survey included questions on: - *Frequency of Behaviors:* How often participants observed specific manipulation tactics. - *Effectiveness:* How effective participants believed these behaviors were in achieving certain outcomes, such as getting fed or receiving attention. - *Impact on Routines and Emotions:* How these behaviors affected participants' daily routines and emotional states. === Distribution Surveys were distributed to human participants through both electronic and paper formats. The survey was designed to be accessible and easy to complete. Follow-up reminders were sent to ensure a high response rate and comprehensive data collection @Serpell2017. === Analysis Survey responses were analyzed to identify trends and patterns in human perceptions of feline manipulation. The data provided insights into the frequency of specific behaviors and their perceived effectiveness in influencing human behavior @Turner2017. == Interviews === Procedure In-depth interviews were conducted with a subset of survey participants to gather qualitative insights into their experiences. Interviews were semi-structured, allowing for exploration of specific instances and personal reflections @Bradshaw2012. === Topics Covered - *Instances of Manipulation:* Participants described notable examples where their cats' behaviors led to specific outcomes. - *Emotional Responses:* Participants discussed their emotional reactions to their cats' manipulative tactics. - *Behavioral Changes:* Insights were gathered on how participants' routines and attitudes towards their cats were affected @Horwitz2010. === Data Collection Interviews were recorded and transcribed for analysis. The transcriptions were coded to identify common themes and patterns related to feline manipulation tactics and their impact on human behavior @Odendaal2000.