repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/saffronner/15122-notes
https://raw.githubusercontent.com/saffronner/15122-notes/main/main.typ
typst
// START PREAMBLE /////////////////////////////////////////////////// #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #set page( numbering: "1 / 1", paper: "us-letter" ) #show raw.where(block: true): it => { v(-0.6em) it } // END PREAMBLE ///////////////////////////////////////////////////// #{ set text(size:18pt) align(center, [*15-122: Principles of Imperative Computation*]) } #outline(indent: 1em) #pagebreak() = Things to look out for - runtime errors - div/mod by 0 - array index out of bounds/not allocated - undefined behavior - dereferencing `NULL` pointer (error in C0) - common logic errors - is your variable for an index or a value at an index? = Syntax == Ints - signed modular arithmetica and fixed-len bit vectors - C0: 32 bit/8 hex digits/4 bytes - check if your language truncates int div toward 0. probably. - bitwise operations - (`&`) and - (`^`) exclusive or - (`|`) or - (`~`) negation - (`<<`) left shift; fills with 0s - (`>>`) right shift; copies highest bit to fill. like division by 2 except truncation toward $-infinity$ == Arrays - note that the following are equivalent #{ show raw.where(block: true): it => { v(0.6em) // this should be the inverse of whatever is at the top. uh. there should be a better way to do this via resetting _something_ to 0. hm. it } table(columns: (auto, auto), ```c for (int i = 0; i < 100; i++) { // ... } ```, ```c int i = 0; while (i < 100) { // ... i++; } ``` ) } - C0 arrays - `int[] A = alloc_array(int, 10);` - allocates default type (i.e. 0 for `int` arrays) - be wary of aliasing == `typedef` - used in structs often TODO - the type of a function describes the number, position, and type of input params and its output type ```c typedef int hash_string_fn(string s); hash_string_fn* F = &hash_string; ``` == Structs - aggregates differently-typed data - struct declarations are thus: ```c struct img_header { pixel_t[] data; int width; int height; } ``` - `data`, `width`, and `height` are called fields - struct allocations return the allocated pointer ```c struct img_header* IMG = alloc(struct img_header); ``` - write to fields using arrow notation, a syntactic sugar ```c IMG->width = 1; /* or */ (*IMG).width = 1; ``` - `*IMG` is called dereferencing == Pointers/Memory Allocation - not just structs: can allocate memory to arbitrary types - `void *malloc(size_t size)`: reserve `size` bytes of memory, return this pointer ```c int* int_ptr = malloc(sizeof(int)); ``` - `void free(void *p)` your pointers - `NULL` pointer (`0x00000000`) - an "invalid address" - cannot be dereferenced === Generic Pointers - the void pointer `void*` can point to any address and can be casted to from any address ```c int* ip = alloc(int); void* p1 = (void*)ip; void* p2 = (void*)alloc(string); void* p3 = (void*)alloc(struct produce); void* p4 = (void*)alloc(int**); ``` - we may convert them back as well ```c int* x = (int*)p1; string x = *(string*)p2; ``` - generic functions may also exist (see `typedef` section) ```c (*F)("hello") ``` === Address-of - `&foo` grabs the address of `foo` == C Preprocessor Language - common built-in libraries: ```C #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <limits.h> ``` - custom libraries use quotation marks instead of angle brackets - constants are simply substituted; they do not follow order of operations ```C #ifdef DEBUG printf("debugging time\n"); #else #define INT_MIN (-1 ^ 0x7FFFFFFF) #endif ``` - macro functions also exist (out of scope of notes) = Conceptual Topics == Big O/Sorting/Searching - asymptotic complexity measures for algorithms - $f in O(g) "if" exists c in RR, n_0 in NN "s.t." forall n >= n_0, f(n) <= c dot g(n)$ - merge/quick sort and binsearch are all "divide and conquer" methods - selection sort ```c /** sorts A in range [lo, hi) */ void selection_sort(int[] A, int lo, int hi) { for (int i = lo; i < hi; i++) { int min = find_min_idx(A, i, hi); // search linearly swap(A, i, min); } } ``` - $O(n^2)$ - in-place - not stable - quicksort ```c int partition(int[] A, int lo, int piv, int hi) //@requires 0 <= lo <= pi < hi <= \length(A); //@ensures lo <= \result < hi //@ensures A[\result] >= all elements from A[lo, \result) //@ensures A[\result] <= all elements from A[\result+1, hi) ; void quicksort(int[] A, int lo, int hi) { if (hi - lo <= 1) { return; } int piv = ...; // random index int mid = partition(A, lo, piv, hi); quicksort(A, lo, mid); quicksort(A, mid + 1, hi); return; } ``` - method: - pick arbitrary "pivot" element - partition array into smaller than pivot elements/larger than pivot elements - recursively sort left and right of pivot until partitions are 1 large - $O(n log n)$ because average $log n$ times partitioned, $n$ copies to do each partition. - in-place (needs a clever partition algo to still be efficient) - not stable - mergesort ```c void mergesort(int[] A, int lo, int hi) { if (hi - lo <= 1) { return; } int mid = lo + (hi - lo) / 2; mergesort(A, lo, mid); mergesort(A, mid, hi); merge(A, lo, mid, hi); return; } ``` - method: - divide array in half - sort halves recursively via merging the divided parts - $O(n log n)$ because $log n$ divisions, merging requires $n$ operations per level - not in-place - binary search ```c int binsearch(int x, int[] A, int n) { int lo = 0; int hi = n; while (lo < hi) { int mid = lo + (hi-lo) / 2; if (A[mid] == x) { return mid; } else if (A[mid] < x) { lo = mid + 1; } else { hi = mid; } } return -1; } ``` - $O(log n)$ == Amortization <amortization> - used in unbounded arrays (see the dedicated #underline[#link(<UBAs>)[section]]) == C's Memory Model - TODO see `14-generic.pdf` = Data Structures == Linked Lists - insertion/deletion in $O(1)$ - access in $O(n)$ - basic C0 implementation via a recursive type: ```c typedef struct list_node list; struct list_node { elem data; // arbitrary (pointer to) element type list* next; }; ``` - For the implementation of stacks, we can reuse linked linked lists are often `NULL`-terminated. i.e., we point to the beginning `list_node` and know we have reached the end when we reach `NULL`. so for such a `list* example = ...`, we have: #figure( diagram( // debug: true, spacing: 0em, // small column gaps, large row spacing cell-size: (2em, 1.5em), node-inset: 0em, node((0,0), [data]), node((1,0), [next]), node((3,0), [data]), node((4,0), [next]), node((6,0), [data]), node((7,0), [next]), node((9,0), [data]), node((10,0), [next]), node((0,1), $3$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((3,1), $8$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((4,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((6,1), $4$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((7,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((9,1), $1$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((10,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), edge((1,1), (3,1), "-|>", snap-to: (none,auto)), edge((4,1), (6,1), "-|>", snap-to: (none,auto)), edge((7,1), (9,1), "-|>", snap-to: (none,auto)), edge((10,1), (11,1), "-||", snap-to: (none,auto)), node(enclose: ((0,1), (1,1)), name: <start>), node(enclose: ((0,3), (1,3)), [example], name: <variable>), edge(<variable>, <start>, "-|>") ), caption: [`NULL`-terminated linked list] ) - this is also called a "concrete type" (as apposed to abstract) because instead of having an implementation/interface divide, there is no abstraction. e.g. we directly use `data` and `next` - linked lists may also use "dummy nodes" that we keep track of to build different data structures - note that recursive types must be under pointers (or arrays). if we had `int data`, we have potentially infinite memory to allocate. - circularity is bad - tortoise and hare algorithm: start tortoise (travels one node at a time) at `list[0]`, hare (travels two nodes at a time) at `list[1]`. if hare catches tortoise before it reaches the end, we have a circle. == Stacks & Queues - stacks (FIFO) can simply implemented with a `NULL`-terminated linked list - queues (LIFO) will keep track of the back as well == Unbounded Arrays <UBAs> - access in $O(1)$ - insertion/deletion also in $O(1)$, amortized - implemented via an array that resizes (e.g. doubles when three-fourths full and halves when a fourth full or so) - see the #underline[#link(<amortization>)[section]] on amortization == Hash Tables - used to implement dictionaries, aka associative arrays or maps. hash tables will result in - $O(1)$ insertion/deletion average (hashing), amortized (bucket resizing) - $O(1)$ lookup average (no resizing needed) - a dictionary will map all its keys to entries or all its keys to values - entires include keys, values don't - implementation #figure( diagram( // debug: true, spacing: 0em, // small column gaps, large row spacing cell-size: (2em, 1.5em), node-inset: 0em, node((0,0), [m=7], width: 2.5em), node((0,6), [0]), node((3,1), [6]), node((3,3), [13]), node((6,3), [23]), node((9,3), [3]), node((3,5), [8]), node((3,6), [30]), node((6,6), [17]), node((1,0), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,2), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,4), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,5), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((1,6), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((3,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((3,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((3,5), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((3,6), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((4,1), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((4,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((4,5), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((4,6), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((6,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((6,6), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((7,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((7,6), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((9,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), node((10,3), $$, stroke: 1pt, shape: rect, width: 2em, height: 1.5em), edge((1,1), (3,1), "-|>", snap-to: (none,auto)), edge((4,1), (5,1), "-||", snap-to: (none,auto)), edge((1,3), (3,3), "-|>", snap-to: (none,auto)), edge((4,3), (6,3), "-|>", snap-to: (none,auto)), edge((7,3), (9,3), "-|>", snap-to: (none,auto)), edge((10,3), (11,3), "-||", snap-to: (none,auto)), edge((1,5), (3,5), "-|>", snap-to: (none,auto)), edge((4,5), (5,5), "-||", snap-to: (none,auto)), edge((1,6), (3,6), "-|>", snap-to: (none,auto)), edge((4,6), (6,6), "-|>", snap-to: (none,auto)), edge((7,6), (8,6), "-||", snap-to: (none,auto)), ), caption: [hash table with separate chaining, `hash(i) = i % 10`] ) - use an array of $m$-many "buckets" - a hash function converts your key into a int - store entries at `array[hash(key) % m]` - if hash collisions occur - separate chaining: each array element is either `NULL` or a chain of entries (with the same hash) - linear probing: search linearly for unused space in array - quadratic probing: search quadratically for unused space in array - chains will (on average) be $n\/m$ long with $n$ entries and $m$ buckets ($n\/m$ called the load factor) - we want a good hash function, possibly tailored specifically to our input data, to preserve even distribution of which keys are placed in bucket - linear congruential generator: $((a dot x) + c) mod d$. choose $d= 2^32$. choose $c,d$ coprime. eg: ```c /** from c0 random library */ int rand (rand_t gen) { gen->seed = gen->seed * 1664525 + 1013904223; return gen->seed; } ``` - fine for hashing ints for a hashmap, but bad for cryptography - pseudo-random is good for debugging---reproducable hashes if given same seed - searching through too-long chains will cause time complexity to not be linear again. so when load factor is too large, increase (e.g. double) $m$: preserves constant complexity via amortization == Trees == Binary Search Trees - like hash maps, also used to implement dictionaries - $O(h)$ insertion/deletion (not covered)/lookup worst case needs to be balanced to be usable - invariants - ordering invariant == AVL Trees - $O(log n)$ insertion/deletion/lookup - invariants - ordering invariant - balance aka height invariant: at any node in the tree, the heights of the left/right subtrees differ by at most 1. - restore via rotations == Priority Queues via Heaps - $O(log n)$ push/pop, $O(1)$ peek - built on binary tree. highest priority is at root node - invariants - Min-heap ordering invariant (alternative 1): The key of each node in the tree is less than or equal to all of its children’s keys. - Min-heap ordering invariant (alternative 2): The key of each node in the tree except for the root is greater than or equal to its parent’s key - shape invariant: fill tree by level, left to right - push: place new node via shape invariant. then sift it up to fix ordering invariant - pop: swap root with last in shape invariant and delete it. then sift new root node down #pagebreak() = Appendix == Library Examples === Self-Sorting Array ```c /* * An interface to self-sorting arrays * * 15-122 Principles of Imperative Computation */ #use <util> #use <string> #use <conio> /************************************************************************/ /************************* BEGIN IMPLEMENTATION *************************/ // Implementation-side type struct ssa_header { string[] data; // sorted int length; // = \length(data) }; typedef struct ssa_header ssa; // Internal debugging function that prints an SSA without checking contracts // (useful to debug representation invariant issues) void ssa_print_unsafe(ssa* A) { int len = A->length; printf("SSA length=%d; data=[", len); for (int i = 0; i < len; i++) //@loop_invariant 0 <= i && i <= len; { printf("%s", A->data[i]); if (i < len-1) printf(", "); } printf("]"); } // Auxiliary functions void swap(string[] D, int i, int j) //@requires 0 <= i && i < \length(D); //@requires 0 <= j && j < \length(D); { string tmp = D[i]; D[i] = D[j]; D[j] = tmp; } bool is_array_expected_length(string[] A, int length) { //@assert \length(A) == length; return true; } bool ssa_sorted(ssa* A) //@requires A != NULL && is_array_expected_length(A->data, A->length); { for (int i=0; i < A->length - 1; i++) //@loop_invariant 0 <= i; if (string_compare(A->data[i], A->data[i+1]) > 0) return false; return true; } // Representation invariant bool is_ssa(ssa* A) { return A != NULL && is_array_expected_length(A->data, A->length) && ssa_sorted(A); } // Internal debugging function that prints an SSA // (useful to spot bugs that do not invalidate the representation invariant) void ssa_print_internal(ssa* A) //@requires is_ssa(A); { ssa_print_unsafe(A); } // Implementation of exported functions int ssa_len(ssa* A) //@requires is_ssa(A); //@ensures \result >= 0; //@ensures \result == \length(A->data); { return A->length; } string ssa_get(ssa* A, int i) //@requires is_ssa(A); //@requires 0 <= i && i < ssa_len(A); { return A->data[i]; } void ssa_set(ssa* A, int i, string x) //@requires is_ssa(A); //@requires 0 <= i && i < ssa_len(A); //@ensures is_ssa(A); { A->data[i] = x; // Move x up the array if needed for (int j=i; j < A->length-1 && string_compare(A->data[j],A->data[j+1]) > 0; j++) //@loop_invariant i <= j; swap(A->data, j, j+1); // Move x down the array if needed for (int j=i; j > 0 && string_compare(A->data[j],A->data[j-1]) < 0; j--) //@loop_invariant 0 <= j && j <= i; swap(A->data, j, j-1); } ssa* ssa_new(int size) //@requires 0 <= size; //@ensures is_ssa(\result); //@ensures ssa_len(\result) == size; { ssa* A = alloc(ssa); A->data = alloc_array(string, size); A->length = size; return A; } // Client-facing print function (does not reveal implementation details) void ssa_print(ssa* A) //@requires is_ssa(A); { int len = A->length; printf("SSA: ["); for (int i = 0; i < len; i++) //@loop_invariant 0 <= i && i <= len; { printf("%s", A->data[i]); if (i < len-1) printf(", "); } printf("]"); } // Client type typedef ssa* ssa_t; /************************** END IMPLEMENTATION **************************/ /************************************************************************/ /************************************************************************/ /******************************* Interface ******************************/ // typedef ______* ssa_t; int ssa_len(ssa_t A) /*@requires A != NULL; @*/ /*@ensures \result >= 0; @*/ ; ssa_t ssa_new(int size) /*@requires 0 <= size; @*/ /*@ensures \result != NULL; @*/ /*@ensures ssa_len(\result) == size; @*/ ; string ssa_get(ssa_t A, int i) /*@requires A != NULL; @*/ /*@requires 0 <= i && i < ssa_len(A); @*/ ; void ssa_set(ssa_t A, int i, string x) /*@requires A != NULL; @*/ /*@requires 0 <= i && i < ssa_len(A); @*/ ; // Bonus function void ssa_print(ssa_t A) /*@requires A != NULL; @*/ ; ``` === Pixel ```C /*************************** Implementation ***************************/ typedef int[] pixel; pixel make_pixel(int alpha, int red, int green, int blue) //Not including other contracts here as this is part of assignment //@ensures \length(\result) == 4; { pixel p = alloc_array(int, 4); p[0] = alpha; p[1] = red; p[2] = green; p[3] = blue; return p; } pixel red() { return make_pixel(255, 255, 0, 0); } pixel green() { return make_pixel(255, 0, 255, 0); } pixel blue() { return make_pixel(255, 0, 0, 255); } pixel white() { return make_pixel(255, 255, 255, 255);} int get_alpha(pixel p) //@requires \length(p) == 4; //Not including other contracts here as this is part of assignment { return p[0]; } int get_red(pixel p) //@requires \length(p) == 4; //Not including other contracts here as this is part of assignment { return p[1]; } int get_green(pixel p) //@requires \length(p) == 4; //Not including other contracts here as this is part of assignment { return p[2]; } int get_blue(pixel p) //@requires \length(p) == 4; //Not including other contracts here as this is part of assignment { return p[3]; } // Client type typedef pixel pixel_t; /**************************** Interface ****************************/ // typedef ____ pixel_t; pixel_t make_pixel(int alpha, int red, int green, int blue) // contract omitted -- assignment ; int get_alpha(pixel_t p) // contracts omitted -- assignment ; int get_red(pixel_t p) // contracts omitted -- assignment ; int get_blue(pixel_t p) // contracts omitted -- assignment ; int get_green(pixel_t p) // contracts omitted -- assignment ; ``` === Queue ```c /* * Queues * * 15-122 Principles of Imperative Computation */ #use <conio> /************************************************************************/ /************************* BEGIN IMPLEMENTATION *************************/ /* Aux structure of linked lists */ typedef struct list_node list; struct list_node { string data; list* next; }; bool is_acyclic(list* start) { if (start == NULL) return true; list* h = start->next; // hare list* t = start; // tortoise while (h != t) { if (h == NULL || h->next == NULL) return true; h = h->next->next; //@assert t != NULL; // hare is faster and hits NULL quicker t = t->next; } //@assert h == t; return false; } /* is_segment(start, end) will diverge if list is circular! */ // Recursive version bool is_segment(list* start, list* end) { if (start == NULL) return false; if (start == end) return true; return is_segment(start->next, end); } // Iterative version using a while loop bool is_segmentB(list* start, list* end) { list* l = start; while (l != NULL) { if (l == end) return true; l = l->next; } return false; } // Iterative version using a for loop bool is_segmentC(list* start, list* end) { for (list* p = start; p != NULL; p = p->next) { if (p == end) return true; } return false; } // Will run for ever if the segment is circular void print_segment(list* start, list* end) //requires start != NULL; { for (list* p = start; p != end; p = p->next) { printf("%s", p->data); if (p != end) printf("->"); } } /* Queues */ typedef struct queue_header queue; struct queue_header { list* front; list* back; }; void queue_print_unsafe(queue* Q) { printf("[front] "); print_segment(Q->front, Q->back); printf(" [back]"); } bool is_queue(queue* Q) { return Q != NULL && is_acyclic(Q->front) && is_segment(Q->front, Q->back); } void print_queue_internal(queue* Q) //@requires is_queue(Q); { queue_print_unsafe(Q); } bool queue_empty(queue* Q) //@requires is_queue(Q); { return Q->front == Q->back; } queue* queue_new() //@ensures is_queue(\result); //@ensures queue_empty(\result); { queue* Q = alloc(queue); list* l = alloc(list); Q->front = l; Q->back = l; return Q; } void enq(queue* Q, string s) //@requires is_queue(Q); //@ensures is_queue(Q); //@ensures !queue_empty(Q); { list* l = alloc(list); Q->back->data = s; Q->back->next = l; Q->back = l; } string deq(queue* Q) //@requires is_queue(Q); //@requires !queue_empty(Q); //@ensures is_queue(Q); { string s = Q->front->data; Q->front = Q->front->next; return s; } void queue_print(queue* Q) //@requires is_queue(Q); { printf("FRONT: "); for (list* l = Q->front; l != Q->back; l = l->next) { printf("%s", l->data); if (l->next != Q->back) printf(" << "); } printf(" :BACK"); } // Client type typedef queue* queue_t; /************************** END IMPLEMENTATION **************************/ /************************************************************************/ /************************************************************************/ /******************************* Interface ******************************/ // typedef ______* queue_t; bool queue_empty(queue_t Q) /* O(1) */ /*@requires Q != NULL; @*/ ; queue_t queue_new() /* O(1) */ /*@ensures \result != NULL; @*/ /*@ensures queue_empty(\result); @*/ ; void enq(queue_t Q, string e) /* O(1) */ /*@requires Q != NULL; @*/ /*@ensures !queue_empty(Q); @*/ ; string deq(queue_t Q) /* O(1) */ /*@requires Q != NULL; @*/ /*@requires !queue_empty(Q); @*/ ; void queue_print(queue_t Q) /* O(n) */ /*@requires Q != NULL; @*/ ; ``` === Stack ```c /* * Stacks * * 15-122 Principles of Imperative Computation */ #use <conio> /************************************************************************/ /************************* BEGIN IMPLEMENTATION *************************/ /* Aux structure of linked lists */ typedef struct list_node list; struct list_node { string data; list* next; }; bool is_acyclic(list* start) { if (start == NULL) return true; list* h = start->next; // hare list* t = start; // tortoise while (h != t) { if (h == NULL || h->next == NULL) return true; h = h->next->next; //@assert t != NULL; // hare is faster and hits NULL quicker t = t->next; } //@assert h == t; return false; } /* is_segment(start, end) will diverge if list is circular! */ bool is_segment(list* start, list* end) { if (start == NULL) return false; if (start == end) return true; return is_segment(start->next, end); } // Will run for ever if the segment is circular void print_segment(list* start, list* end) //requires start != NULL; { for (list* p = start; p != end; p = p->next) { printf("%s", p->data); if (p != end) printf("->"); } } /* Stacks */ typedef struct stack_header stack; struct stack_header { list* top; list* floor; }; void stack_print_unsafe(stack* S) { printf("[top] "); print_segment(S->top, S->floor); } bool is_stack(stack* S) { return S != NULL && is_acyclic(S->top) && is_segment(S->top, S->floor); } void stack_print_internal(stack* S) //@requires is_stack(S); { stack_print_unsafe(S); } bool stack_empty(stack* S) //@requires is_stack(S); { return S->top == S->floor; } stack* stack_new() //@ensures is_stack(\result); //@ensures stack_empty(\result); { stack* S = alloc(stack); list* l = alloc(list); S->top = l; S->floor = l; return S; } void push(stack* S, string x) //@requires is_stack(S); //@ensures is_stack(S); //@ensures !stack_empty(S); { list* l = alloc(list); l->data = x; l->next = S->top; S->top = l; } string pop(stack* S) //@requires is_stack(S); //@requires !stack_empty(S); //@ensures is_stack(S); { string e = S->top->data; S->top = S->top->next; return e; } void stack_print(stack* S) //@requires is_stack(S); { printf("TOP: "); for (list* l = S->top; l != S->floor; l = l->next) { printf("%s", l->data); if (l->next != S->floor) printf(" | "); } } // Client type typedef stack* stack_t; /************************** END IMPLEMENTATION **************************/ /************************************************************************/ /************************************************************************/ /******************************* Interface ******************************/ // typedef ______* stack_t; bool stack_empty(stack_t S) /* O(1) */ /*@requires S != NULL; @*/ ; stack_t stack_new() /* O(1) */ /*@ensures \result != NULL; @*/ /*@ensures stack_empty(\result); @*/ ; void push(stack_t S, string x) /* O(1) */ /*@requires S != NULL; @*/ /*@ensures !stack_empty(S); @*/ ; string pop(stack_t S) /* O(1) */ /*@requires S != NULL; @*/ /*@requires !stack_empty(S); @*/ ; void stack_print(stack_t S) /* O(n) */ /*@requires S != NULL; @*/ ; ``` === Generic Dictionaries ```c /* * Generic dictionaries, implemented with separate chaining * * 15-122 Principles of Imperative Computation */ #use <util> #use <conio> /************************************************************************/ /**************************** Client Interface **************************/ typedef void* entry; typedef void* key; typedef key entry_key_fn(entry x) // Supplied by client /*@requires x != NULL; @*/ ; typedef int key_hash_fn(key k); // Supplied by client typedef bool key_equiv_fn(key k1, key k2); // Supplied by client /************************* End Client Interface *************************/ /************************************************************************/ /************************************************************************/ /************************* BEGIN IMPLEMENTATION *************************/ typedef struct chain_node chain; struct chain_node { entry data; // != NULL; contains both key and value chain* next; }; typedef struct hdict_header hdict; struct hdict_header { int size; // 0 <= size chain*[] table; // \length(table) == capacity int capacity; // 0 < capacity entry_key_fn* key; // != NULL key_hash_fn* hash; // != NULL key_equiv_fn* equiv; // != NULL }; bool is_table_expected_length(chain*[] table, int length) { //@assert \length(table) == length; return true; } bool is_hdict(hdict* H) { return H != NULL && H->capacity > 0 && H->size >= 0 && H->key != NULL && H->hash != NULL && H->equiv != NULL && is_table_expected_length(H->table, H->capacity); /* && there aren't entries with the same key */ /* && the number of entries matches the size */ /* && every entry in H->table[i] hashes to i */ /* && ... */ } int index_of_key(hdict* H, key k) //@requires is_hdict(H); //@ensures 0 <= \result && \result < H->capacity; { return abs((*H->hash)(k) % H->capacity); } key entry_key(hdict* H, entry x) //@requires is_hdict(H) && x != NULL; { return (*H->key)(x); } bool key_equiv(hdict* H, key k1, key k2) //@requires is_hdict(H); { return (*H->equiv)(k1, k2); } hdict* hdict_new(int capacity, entry_key_fn* entry_key, key_hash_fn* hash, key_equiv_fn* equiv) //@requires capacity > 0; //@requires entry_key != NULL && hash != NULL && equiv != NULL; //@ensures is_hdict(\result); { hdict* H = alloc(hdict); H->size = 0; H->capacity = capacity; H->table = alloc_array(chain*, capacity); H->key = entry_key; H->hash = hash; H->equiv = equiv; return H; } entry hdict_lookup(hdict* H, key k) //@requires is_hdict(H); //@ensures \result == NULL || key_equiv(H, entry_key(H, \result), k); { int i = index_of_key(H, k); for (chain* p = H->table[i]; p != NULL; p = p->next) { if (key_equiv(H, entry_key(H, p->data), k)) return p->data; } return NULL; } void hdict_insert(hdict* H, entry x) //@requires is_hdict(H); //@requires x != NULL; //@ensures is_hdict(H); //@ensures hdict_lookup(H, entry_key(H, x)) == x; { key k = entry_key(H, x); int i = index_of_key(H, k); for (chain* p = H->table[i]; p != NULL; p = p->next) { //@assert p->data != NULL; // From preconditions -- operational reasoning! if (key_equiv(H, entry_key(H, p->data), k)) { p->data = x; return; } } // prepend new entry chain* p = alloc(chain); p->data = x; p->next = H->table[i]; H->table[i] = p; (H->size)++; } // Statistics int chain_length(chain* p) { int i = 0; while (p != NULL) { i++; p = p->next; } return i; } // report the distribution stats for the hashtable void hdict_stats(hdict* H) //@requires is_hdict(H); { int max = 0; int[] A = alloc_array(int, 11); for(int i = 0; i < H->capacity; i++) { int j = chain_length(H->table[i]); if (j > 9) A[10]++; else A[j]++; if (j > max) max = j; } printf("Hash table distribution: how many chains have size...\n"); for(int i = 0; i < 10; i++) { printf("...%d: %d\n", i, A[i]); } printf("...10+: %d\n", A[10]); printf("Longest chain: %d\n", max); } // Client-side type typedef hdict* hdict_t; /************************** END IMPLEMENTATION **************************/ /************************************************************************/ /************************************************************************/ /*************************** Library Interface **************************/ // typedef ______* hdict_t; hdict_t hdict_new(int capacity, entry_key_fn* entry_key, key_hash_fn* hash, key_equiv_fn* equiv) /*@requires capacity > 0; @*/ /*@requires entry_key != NULL && hash != NULL && equiv != NULL; @*/ /*@ensures \result != NULL; @*/ ; entry hdict_lookup(hdict_t H, key k) /*@requires H != NULL; @*/ ; void hdict_insert(hdict_t H, entry x) /*@requires H != NULL && x != NULL; @*/ ; ```
https://github.com/FrightenedFoxCN/typst-langpack
https://raw.githubusercontent.com/FrightenedFoxCN/typst-langpack/main/bilingural.typ
typst
#let find-paragraph(body) = { let res = () let s = "" for i in body.children { if i.has("text") { s += i.text } if i == parbreak() { if (s != "") { res.push(s) } s = "" } } res.push(s) return res } #let parse-word(sentence) = { // not sure how split work with regex // sentence.split(regex("(?:\\{.+\\})|\\W")) sentence = sentence.split() let res = () let left-bracket = 0 let inside-bracket = false let component = "" for (idx, val) in sentence.enumerate() { if val.contains("{") { left-bracket = idx let (l, r) = val.split("{") if l != "" { res.push(l) } component += r inside-bracket = true } else if val.contains("}") { assert(inside-bracket, message: "Brackets don't match!") // FIXME: when "{" and "}" are in the same word and don't match... let (l, r) = val.split("}") component += " " component += l res.push(component) component = "" inside-bracket = false if r != "" { res.push(r) } } else if not inside-bracket { if val.contains("-") { let (l, r) = val.split("-") res.push(l) res.push("") res.push(r) } else { res.push(val) } } else { component += " " component += val component += " " } } return res } #let align-words(paras) = { for i in paras.first().zip(paras.last()) { box(height: 20pt, inset: 0.2em)[#align(center)[#i.first() \ #i.last()]] } } #let replace-paragraph(paras) = { paras = paras.map(parse-word) align-words(paras) } #let bilingural(cont) = { let para = find-paragraph(cont) para = para.chunks(2) for i in para { replace-paragraph(i) parbreak() } }
https://github.com/OverflowCat/typecharts
https://raw.githubusercontent.com/OverflowCat/typecharts/neko/example.typ
typst
#import "lib.typ": render, evalRender #import "themes.typ": vintageTheme, romaTheme #render(( width: 390, height: 280, ), ( xAxis: ( type: "category", boundaryGap: false, ), yAxis: ( type: "value" ), series: ( data: (114, 514, 191, 98, 10), type: "line", areaStyle: () ) ), theme: vintageTheme) #let str = ```json {toolbox: { show: false }, color:["#80FFA5","#00DDFF","#37A2FF","#FF0087","#FFBF00"],tooltip:{trigger:"axis",axisPointer:{type:"cross",label:{backgroundColor:"#6a7985"}}},legend:{data:["Line 1","Line 2","Line 3","Line 4","Line 5"]},grid:{left:"3%",right:"4%",bottom:"3%",containLabel:true},xAxis:[{type:"category",boundaryGap:false,data:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]}],yAxis:[{type:"value"}],series:[{name:"Line 1",type:"line",stack:"Total",smooth:true,lineStyle:{width:0},showSymbol:false,areaStyle:{opacity:.8,color:new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgb(128, 255, 165)"},{offset:1,color:"rgb(1, 191, 236)"}])},emphasis:{focus:"series"},data:[140,232,101,264,90,340,250]},{name:"Line 2",type:"line",stack:"Total",smooth:true,lineStyle:{width:0},showSymbol:false,areaStyle:{opacity:.8,color:new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgb(0, 221, 255)"},{offset:1,color:"rgb(77, 119, 255)"}])},emphasis:{focus:"series"},data:[120,282,111,234,220,340,310]},{name:"Line 3",type:"line",stack:"Total",smooth:true,lineStyle:{width:0},showSymbol:false,areaStyle:{opacity:.8,color:new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgb(55, 162, 255)"},{offset:1,color:"rgb(116, 21, 219)"}])},emphasis:{focus:"series"},data:[320,132,201,334,190,130,220]},{name:"Line 4",type:"line",stack:"Total",smooth:true,lineStyle:{width:0},showSymbol:false,areaStyle:{opacity:.8,color:new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgb(255, 0, 135)"},{offset:1,color:"rgb(135, 0, 157)"}])},emphasis:{focus:"series"},data:[220,402,231,134,190,230,120]},{name:"Line 5",type:"line",stack:"Total",smooth:true,lineStyle:{width:0},showSymbol:false,label:{show:true,position:"top"},areaStyle:{opacity:.8,color:new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:"rgb(255, 191, 0)"},{offset:1,color:"rgb(224, 62, 76)"}])},emphasis:{focus:"series"},data:[220,302,181,234,210,290,150]}]} ``` #evalRender((), str.text) #render(( width: 600, height: 400, ), ( series: ( ( type: "bar", name: "Apples", data: (108, 26, 39, 24), itemStyle: (borderWidth: 2, borderColor: "black"), ), ( data: (23, 40, 60, 70), itemStyle: (borderColor: "black", borderWidth: 2), name: "Oranges", type: "bar", ), ( itemStyle: (borderColor: "black", borderWidth: 2), name: "Bananas", type: "bar", data: (129, 40, 40, 50), ), ( name: "Pears", type: "bar", data: (40, 60, 50, 89), itemStyle: (borderWidth: 2, borderColor: "black"), ), ), xAxis: ( axisLabel: (color: "black"), axisTick: (color: "black"), data: ("Q1", "Q2", "Q3", "Q4"), axisLine: (color: "black"), ), yAxis: ( axisLabel: (color: "black"), splitLine: (lineStyle: (type: "dashed", color: "black")), axisLine: (color: "black"), axisTick: (color: "black"), ), color: ("white", "black", "white", "white"), legend: ("show": true), aria: ( decal: ( decals: ( (dashArrayY: 0, color: "black", dashArrayX: 0), (color: "black", dashArrayY: 0, dashArrayX: 0), ( dashArrayX: (1, 0), symbolSize: 1, rotation: calc.pi / 6, dashArrayY: (2, 5), color: "black", ), ( dashArrayX: ((8, 8), (0, 8, 8, 0)), symbolSize: 0.8, dashArrayY: (6, 0), symbol: "circle", color: "black", ), ), "show": true, ), ), )) #let aqiOption = () // Too long #render((width: 600, height: 400), aqiOption)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.1/template/code/README.md
markdown
Apache License 2.0
# code/ This is where you should add any code files you want to display in your thesis. You can then include the code into your thesis with a combination of the [`read`][read] and [`raw`][raw] functions: ```typst #let code = read("relative/path/to/code/filename.jl") #raw(code, lang:"julia") ``` If you place the `raw` call into a [`figure`][figure], you will get a numbered code listing that you can reference. [read]: https://typst.app/docs/reference/data-loading/read/ [raw]: https://typst.app/docs/reference/text/raw/ [figure]: https://typst.app/docs/reference/model/figure/
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/050%20-%20Phyrexia%3A%20All%20Will%20Be%20One/001_Cinders.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Cinders", set_name: "Phyrexia: All Will Be One", story_date: datetime(day: 12, month: 01, year: 2023), author: "<NAME>", doc ) Neyali looked over her resistance cell and took inventory of what she saw. Mentally, she noted whose shields were chipped or dimmed and whose swords were pitted or cracked. As she did, she took stock of her allies, too: which of them limped, which of them could no longer favor their dominant arm, whose breath rattled wetly as they walked through the wasteland on the edges of the Quiet Furnace. #figure(image("001_Cinders/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Saheena, an old Vulshok woman, back straight despite age, walked with a stiff pride, a son at each shoulder. She had only one eye now due to a recent skirmish. Dried blood still dappled her throat. Elham, the Auriok woman who had led before Neyali, stomped behind them with more bags than she needed to bear, freeing her comrades to move unencumbered. They had so little resources and what they had, regardless of its form, was shared without reservation. Neyali vowed to herself that she'd do her best to find them what respite she could. It wasn't long ago when she'd been alone, wandering the ruins of Mirrex with her firebird Otharri, looking for some sign—#emph[any] sign, no matter how small or improbable—that there were others who had survived the Phyrexian massacre of her village. Now, people depended on her. #emph[Trusted] her. Neyali wondered if the honor would ever stop feeling so heavy. She was startled from her brooding by Otharri's clarion scream. At the firebird's screech, Neyali's cellmates closed ranks, a perfect synchronous motion, tensing immediately for an ambush. None came. There was no sign of encroaching Phyrexians, no telltale scratch of skitterling claws on stone, no moan of steam from a Goliath. Nothing at all. But Otharri wouldn't have risked giving away their location if it wasn't important. Pulse hammering in her throat, Neyali looked over her people again, desperate to understand what she had missed. It hit her then. "Reyana," whispered Neyali. Neyali launched into motion before any of her cohorts could answer, racing back down the red-lit corridor, Otharri in pursuit overhead. Reyana had taken the role of rear guard as she always did, but she wasn't there. Neyali ran through the possibilities in her head. Had Reyana been jumped by one of the scrapchiefs? If she had, the rest of them should have been enveloped by Phyrexians. It made no sense that they'd have stopped at Reyana, never mind the fact that Urabrask, by all accounts, had insisted the Mirrans be left alone. Hot steam gusted from the rightmost wall, revealing the presence of a narrow passage she'd missed before: a crack in the metal surface, barely large enough to fit a humanoid figure. Through the gap, Neyali saw a familiar silhouette. It was Reyana, inching backward toward a ledge, an ocean of magma burning orange below. In front of her, an imposing humanoid figure, its left arm transmuted into an oversized scythe, the gold of its original skin almost entirely obscured by iron pleats. It'd been a woman once, Auriok. On the ground, Reyana's weapons: forgotten, abandoned. In her face, an expression Neyali had never seen her childhood friend wear, a desperate hopelessness like her heart had broken irreparably. "You are finally ready to be made perfect," said the aspirant in a woman's voice, low and halfway familiar. It reached for Reyana then, an arm outstretched: a strange tenderness in the gesture, and to Neyali's surprise, Reyana choked back a sob. A less impulsive woman might have waited for reinforcement or at the very least, a better understanding of the circumstances. But for better or worse, Neyali was a creature of instinct, as much flame as her firebirds. So forward, she went, hands balled into fists. Her gauntlets shone in that scorching light. She bellowed a challenge, one echoed a heartbeat by Otharri a second later, the firebird rushing past Neyali in a tremor of glowing wings. He tore at the aspirant's face as it turned. The Phyrexian raised its bladed arm to cleave the phoenix in half, and Neyali ducked low and swung up, smashing into where the soft bones of a wrist should have resided. Metal shattered and rained over her. The aspirant—an older Auriok woman, halfway familiar, no doubt tall when she'd been flesh, taller still after compleation—staggered but did not scream, only gazed back at Reyana. "There will be no more fear when the soft flesh is made perfect." Neyali did not slow. She gripped the aspirant by its ruined arm, torqued herself into position to ram an elbow into its chest, the whole of her weight thrown into the motion. She ran them both to the edge, letting go at the last second. The Phyrexian fell without so much as a cry. "Neyali—" "Are you alright?" Neyali rushed back to her friend and looked her over for injuries. One cut was all the Phyrexians needed. A single drip of glistening oil, and they'd have to race time to return to their encampment, find Reyana the healing she needed before phyresis became irreversible. "Were you contaminated? Did it have oil? Show me—" "Neyali—" The Vulshok woman clasped Reyana's head in her hands. "Your eyes. Let me see your eyes." "I'm fine. I promise you." Reyana closed her hands over Neyali's own. And it was her friend again, not the husk she'd been before, animation returned to her broad expressive features. She smiled, exhausted but warmly. "She did nothing to me." "Why didn't you fight back? What happened to your weapons?" The light fled her face again. "Neyali, she was my mother." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The rookery glistened with the candle-glow light of resting firebirds, their flames dimmed as they crooned and murmured to one another, giving a blue-green cast to the moving shadows. It was a smaller space than Neyali would have wanted for them. Had she the luxury, she would have built them something sturdier, something designed to hold generations of firebirds. It wouldn't be so ramshackle, with platforms and nesting boxes cobbled from better things than scrap metal. Neyali tickled Otharri under his feathered jaw. "One day," she promised her friend. His mate slumbered beside him, their chicks nestled into her side. "We will build you a rookery on the cinders of Urabrask's Forge, and your chicks will grow up there, warm and happy, as will their chicks and the generation that follows theirs." In answer, Otharri flapped his wings and pressed his cheek into Neyali's palm, his neck stretched, his manner pleased and indolent. Neyali scratched his plumage obligingly before turning to regard Reyana as the Auriok woman busied herself with her own birds. They'd been lucky. For all the recent chaos—more and more, there were stories of unrest among the priests, rumors that Urabrask was planning something titanic—that had befallen the resistance of late, the firebirds had had a good mating season. The females were all with clutches, a rarity. If even half the eggs survived, it would change so much. "How are your charges?" said Neyali, picking her way past the dozing firebirds to Reyana's side. "Childless," said Reyana, her tone flat. She stepped aside then to reveal what her tall frame had been hiding: a nest of shattered eggs, oozing a phosphorescent yolk. It was a mercy that there were no traces of the lost chick, and that the mother was young enough to be indifferent to her offspring, more preoccupied with courting the attention of a neighboring male. "What happened?" said Neyali, wincing. The last thing she wanted for her friend was another tragedy. "Skitterlings, maybe," said Reyana, still with that hollow tone of voice as she sifted through the shards. "Wouldn't be surprised if it were rats. Regardless, it doesn't matter. The clutch is dead. Just like my mother." Neyali swallowed. "If I had known—" "You couldn't have. I didn't know. Not until she was there, asking me to join her." "I could have asked you," said Neyali, unable to shake the certainty that she had failed horrifically and a terrible price would need to be paid. "I could have thought first before acting. We might have been able to save her. We might have been able to do #emph[something] ." Her voice cracked at the last word. "She wouldn't have been happy," said Reyana, making eye contact with Neyali. Her voice softened. "My mother—she was a timid woman. Glass rather than steel. Everything frightened her. Everything was a portent of death or worse. You could see it in her eyes: how much she wanted it all to just#emph[ stop] ." Reyana swallowed audibly. "I used to wish she'd just die," said Reyana, with a terrible dignity. "Not because I was tired of her wailing, or even that I resented the fact she beat me. I wanted—" Neyali gaped at her friend. "She #emph[beat ] you?" "Not with any malice. I think it was because she needed an outlet. Some way to mitigate the enormous pressures she was facing. It needed #emph[expression] , or she would have exploded." "Still, it was cruel—" "I loved her, you understand," said Reyana and Neyali heard a rebuke in those quietly spoken words. "I still do. Anyway, I thought it'd be easier for her to simply not exist in this world. I wanted her torment to end. Does that make me a bad daughter?" "No," said Neyali, hands closing and reopening, like she could wring the right words from the air. "You're not. I understand completely. The Phyrexians have taken so much from us. It's why we fight. What befell your mother, we can make sure it won't happen to anyone else." Reyana inhaled, her breath shivering. "What if Phyrexia is right?" "Don't joke like that," said Neyali. "I know we say what they've done is a sin, a violation of the soul. But you should have seen my mother, Neyali. She was calm. She has never been calm. I've never seen her enjoy a day of peace. Even in her sleep, she would mumble and weep and moan. The version that I met today—she was at rest. I think—" Horror flowed through Neyali. She could see where the end of the sentence laid and the thought of it being spoken aloud, of Reyana giving breath to those words, made Neyali want to scream. For one guilty moment, she found herself wishing Reyana #emph[had] been infected by glistening oil, so she could blame this terrifying perspective on Phyrexian corruption. Because the alternative was so much worse: this thought Reyana had arrived at such conclusions all on her own. "The peace," said Neyali very carefully, "that the Phyrexians feel is a false one. Born of a loss of self. That thing wasn't your mother. Not any longer. At best, it was a puppet. A lie made steel and flesh." "Is that so?" Neyali nodded. "Each of their aspirants are a lure. Meant to entice, meant to convince those who remain that phyresis is the only logical option. They're there to break our hearts and spirits. And for whatever it's worth," her voice gentled, "I think you endured that encounter with more grace than I could have. Personally, I'd have gone mad with grief." "Who says I haven't?" Neyali clapped a hand around her friend's right shoulder. "If you have, know you'll have company as we go laughing in the dark. I made you a promise when we met. I won't abandon you. No matter what happens, I'll always be at your side." Only later, as Neyali crawled into her cot, did she realize that Reyana had not spoken her half of their usual call and response, and fell asleep worrying about what that meant. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Neyali woke the next morning to a young Vulshok boy—the oldest of Saheena's sons, he had her eyes and the build, Neyali was told, of a father long vanished—clearing his throat. She jerked upright into a sitting position, rubbing the heel of a palm into her right eye. Either age was catching up, or she was getting too comfortable with the idea that there were people she could trust. Neyali fervently hoped it was the former. Complacency meant death. "What is it?" The wretchedness in the boy's expression grew. He handed her a note. "It's Reyana," he said miserably. "She's gone." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Gone, as it turned out, meant a note in her cot and her belongings untouched. It was as if she had simply chosen to walk away for a moment. None of their rations had been touched. Were it not for the note and were Neyali a more optimistic person, she might have chosen to believe Reyana was somewhere close. But Neyali knew enough of their world that she could not allow herself that illusion. She turned the note over, hoping for clues. #emph[Meet me at the Salvage Complex.] Why would Reyana go there? Neyali wondered if it was a trap, if Reyana had been taken against her will then forced to write the note, enticing Neyali to her own capture. But for such a possibility to be true, there would need to have been more signs of conflict, some indication that Phyrexians had broken through the camp's defenses. Neyali pushed down on the little voice that whispered, #emph[maybe, she went willingly.] "The goblin rules there, doesn't he?" said Elham, the white of her hair made even more incandescent by the white-gold flecks in her skin. "I think so," said Neyali, the note pocketed again. She restlessly checked her equipment: her armor for faults, her gloves for rust. Otharri watched from his perch. Neyali had seen Slobad once before, but only from afar: a monstrously large goblin, his limbs swollen with black steel. "Is he a Furnace Boss?" asked Saheena's youngest. What was his #emph[name] ? To Neyali's shame, she could not remember it, not with the panic hammering at her ribs. "No." said Elham. "He's waste disposal. Urabrask sends obsolete Phyrexians to him for repurposing." Nothing went to waste in the Furnace Layer. What could not be used was reduced to components, taken apart and rebuilt so it could be of worth again. "What would he want with Reyana then?" Neyali demanded in frustration. "Labor?" said the Auriok woman. Saheena and her youngest came around the corner, the blood gone, her eye bandaged. "He can't run his complex alone." Neyali nodded. Easier this than introspection. Simpler to name your adversary and then go straight into looking for a fight. She slammed her fist into her open palm, grinned toothily at her cellmates. "Right," said Neyali. "I'm going to find Reyana. No one is obligated to join me on this mission. Reyana is my friend, and—" "She is family to us, too," said Elham, slinging her battleax on her shoulder, her stance allowing no objection. Her calf shone with polished gold; a simple enough prosthetic, well-articulated and better made. "I might be making a mistake." "We've all lost someone," said Saheena, voice tightening. Her sons looked away, their expressions clouding. Everyone in the cell knew the story: they were the last remnants of a massive family, teeming with aunts and uncles. "If we're lucky, we can be sure that Reyana won't be in their number." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The cell mobilized within an hour. Most headed eastward, bearing the main bulk of their supplies away to a neighboring camp, the firebirds in accompaniment. Only Otharri remained with Neyali, unwilling to be parted from his friend. After stiff farewells, what remained of Neyali's cell, whittled to the bravest and most stubborn, set off in the direction of the Salvage Complex. The route there was not as treacherous as some: the tunnels leading to the compound were far from the main arteries of the Furnace Layer, wrapping around its very edges. Though it didn't intersect with any of the forges, the road was long. and that alone brought risks of unwanted encounters. But none materialized. The road stayed empty, and unnervingly so. Almost as if the way had been cleared on purpose. Like something waited for them. Their nerve might had broken if not for the Mirran encampments they found enroute: one nestled in what might have once been the ruins of a factory, or the disemboweled belly of an overgrown Goliath, twisted spires of black steel rising like broken ribs; one at the back of a mezzanine teeming with unused assembly lines; the last in a graveyard of bizarre crumbling structures. In each camp, Neyali and her crew learned the same thing: that loved ones had gone missing, with no signs that they'd been taken by force. #emph[She went willingly] , insisted that little voice again, which Neyali found growingly difficult to ignore, but before she could reconsider her loyalties, they arrived at the outcropping above the Salvage Complex. Once, it might have been a prison compound. Deformed cages rose in unsteady towers, the bars mangled, bulging in places, as if whatever had been inside was desperate to escape. Many were occupied by slumped figures: captured Mirrans, waiting their anointment with glistening oil. Machinery snaked in between the enclosures, coiling over them in a parody of vegetal life. What had Neyali's attention was the pit at the very center of the Salvage Complex, an inverted ziggurat veined with enormous black pipes. Each level teemed with impossible contraptions, moving parts whose purpose Neyali couldn't decipher. And bodies, she realized. Countless Phyrexian bodies, made to kneel before they were husked of their metal, the flesh left behind. There were rows upon rows of them, like a silent audience staring down at the platform at the very base. A single figure occupied the narrow wedge of metal. Neyali felt her heart jump: it was Reyana, shackled and prone. "Watch the skies for me, beloved," whispered Neyali, pressing a kiss to Otharri's cheek. With a twitch of her arm, she sent the firebird in the air. Neyali turned her attention then to her comrades. "There's every chance in the world that this is a trap and I am a fool, but Reyana is my friend. I promised us I would not abandon her. I intend to keep that promise. But none of you made the same foolish vow. There will be no judgment, no censure if you choose to leave. If you walk away now, you walk away with honor." The gathered Mirrans exchanged looks, but no one spoke until Saheena at last said in a bored voice: "Do you want to waste time or should we begin checking the perimeter?" #figure(image("001_Cinders/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) They made three full circuits of the Salvage Complex before Neyali gave up. For all intents and purposes, the location was unguarded. Their air-purity detector revealed no telltale increase in toxic particles: the usual sign of hidden Phyrexians. It was empty, save for Reyana and that assembly of corpses. "What now?" said Elham after they returned to their original vantage point. She stared down at where Reyana was, distraught. #emph[I don't know] , Neyali wanted to say, only she could not. They were relying on her. #emph[Elham ] was looking to her, waiting for her orders. The woman had been a hero, a mentor, and she had trusted Neyali to take over when she stepped down. Neyali swallowed hard. "I'm going down on my own." That startled Elham. "It's reckless." "It's strategic," Neyali countered. "If we missed something, if this really is a trap, the focus will be on me, giving the rest of you time to retaliate." "What if it turns out that we're outnumbered?" "Then you run." "#emph[Neyali] —" "You have my orders," said Neyali, hoping they would only hear her authority, not the tremble in her voice. She knew what her bravado might mean. Compleation. Often Neyali wondered how much of the original remained after phyresis had set in. If enough of a mind remained to scream endlessly at what the body was made to do. If she would scream, too. "An honor guard," snarled Saheena, coming up from her right, stubborn as iron. "Fine." Neyali snapped. "Three of you. With me. The rest of you. To your stations." The Mirrans saluted her, dispersing save for the Vulshok matriarch and her two sons, who looked so agonizingly young in the wash of red light. In tight formation, they followed her down to the pit: Saheena serving as vanguard, her sons flanking Neyali. Much like their journey to the Salvage Complex, their expedition to Reyana was without incident. The dead Phyrexians remained inert, statue-like, for all that Neyali was certain that at any minute, they would leap at the four of them, a howling mass of maimed flesh. Nothing came. They stepped onto the platform. It swayed under their weight, though not enough to raise concern. Reyana did not respond. She laid there instead, faced away, her breathing shallow and irregular. "Reyana," whispered Neyali, coming to her knees beside her friend. With care, she turned Reyana over onto her back. The Auriok, despite her stillness, was awake: eyes open, fixed on nothing, expression clouded with the same misery Neyali had seen that night before her friend walked away into the dark. "Reyana," said Neyali again, like her friend's name was a spell. "It's me. We're going to get you out of this." The Auriok woman blinked once, lashes long and black as oil. Her gaze focused. The agony in her expression strengthened. "I'm sorry, Neyali. I was just so exhausted." #figure(image("001_Cinders/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Neyali shook her head. "Nothing to be forgiven. We're #emph[family] —" said Neyali, the first time she had ever put the sentiment to words, her voice thick with emotion. Her attention was riveted by the chains knotted around Reyana's wrists and arms: they were of unusual design, sleeker than what the Phyrexians often used, less like oxidized sinew, more beautiful. "And family stays together." "I'm sorry," Reyana said again in lieu of an answer, her fingers brushing Neyali's, running up her forearms: something contemplative in the movements, as though she was evaluating her friend or more precisely, a decision she represented. "I truly am." The air quickened. A sheen of red-orange light traveled up Reyana's arms, over her restraints, up and across Neyali's knuckles. The latter jerked backward, instinctive. A split second later, the light darkened and corporealized into a knot of chains, landing on the platform with a thunk. Reyana, no longer bound, sat up placidly, blinking at her cellmates like they were strangers. "I knew it," snarled the matriarch. "#emph[Traitor] ." "What did they promise you, Reyana?" Neyali bayed, furious that her fears—that little voice, the one that had whispered time and again, #emph[she went willingly] —were proven right. Neyali scanned her surroundings. Too late for them to run, but the four of them could still buy the rest of their cell time. She just had to give the signal, make sure the rest knew to eschew last-minute heroics. Her gaze rose to the smoke-choked sky; Otharri was nowhere to be seen. Had he been caught? No. Impossible. The only way Phyrexia would have Otharri was as a corpse, and that wasn't going to happen without a fight that'd echo through the Furnace Layer. There was a reason the Mirrans saw phoenixes as a symbol of hope, and the Phyrexians saw phoenixes as an omen of death. He was there somewhere in the smog, Neyali was sure. #emph[Go far] , she willed the firebird. #emph[Run. Lead the others to safety. Don't let them get you.] "Peace!" shrieked Reyana, tottering onto her feet. She wept as she spoke, each word sobbed. "We're not all like you. I don't want to die afraid, Neyali. I don't want a life like my mother's. I want it to stop. Don't you understand? I want this to end. I want the perfect peace that my mother was given. Slobad—he promised me that there will be peace. That I will be reunited with the people I love and long for and miss." "And you will be," came a new voice from behind Neyali, a voice surprisingly normal given its origins. She whirled around to see Slobad on the edge of the pit. Neyali had seen him once before, but only from afar, and thought little of him then: just another Phyrexian horror in an army of millions. Now, she was close enough to wince at the full truth of him. His small, goblin form was embedded in a massive construct of cables and sheafs of metal plating, one shoulder bearing an epaulet adorned with a triptych of shrieking goblin heads, and Neyali could #emph[see] where Slobad's limbs had been shorn off, where they'd been amputated at the joint and soldered to the exoskeleton of his golem-like Phyrexian body. #figure(image("001_Cinders/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "We're not your enemy," he said. "Out there, the world is hard and cold and it takes everything. Friends, family. But here? We're safe. We're family. We have all the people who we love, huh?" Slobad looked down at his massive hand and then at the quartet. "You're Neyali." Her companions took position, weapons at the ready. #emph[Death before compleation] , Neyali thought. "I have no fear of you." "Why should you? Nothing cruel here, huh? We don't want to hurt any of you. We just want you to be reunited with the ones you loved," said Slobad softly. "The Mirrans look to you for leadership. Will you not guide them home to those who love them?" "Father?" whimpered one of the younger Vulshok, his spear clattering from his hands. An aspirant stood beside Slobad: a Vulshok man, antlered, almost entirely robed in steel. "Stay focused," she warned her allies. "Don't falter." "I offer you a choice. You four," said Slobad. "For the rest of the Mirrans in hiding." Neyali felt her heart sink. Slobad #emph[knew] . "We're with you, no matter what you decide," said Saheena quietly. "Tell us to die with you, and we shall. To the end, Neyali." There was a hairline crack in her voice's calm, and Neyali wondered if she had vowed those same words to the partner she thought dead, who stood there now above them, or at least, the shell of him. "We're with you to the end." Neyali looked back to where Reyana was. She was on her knees, hands twisted together in prayer, rocking in place. She was weeping: tears, not oil, and it was so much worse than if Reyana had been corrupted. Knowing Reyana had #emph[chosen ] this. Knowing she had elected to be bait. Neyali, the damn fool that she was, had walked straight into the trap, even though every instinct had begged her to do otherwise. But she could salvage this. "Why should we trust you?" said Neyali. "How do I know you won't take all of us, anyway? Urabrask gave his orders. Aren't you supposed to have better things to do than harm us?" "Harm? Why would I harm you, huh? I don't want to. I only want to help you." Neyali swallowed hard, glancing at those she had led to ruin. "Let these three go then, if you believe that." "Done." "Neyali—" "#emph[Go] ." said Neyali. "Before he changes his mind." She could feel the Vulshok elder tense, her sons tremble: a whimper bitten back by one, a hiss of frustration swallowed by the other. Then, Saheena nodded, almost imperceptibly. The three filed past Neyali. True to his word, Slobad and his minions did nothing, only watched with their foundry-bright eyes. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It was a mercy on Slobad's part, Neyali decided, that she was placed in a cage far above where Reyana would accept the glistening oil. From this vantage, Neyali could almost pretend her friend was a stranger, a traitor whom she shared no ties with. #emph[At least the rest of the cell is safe] , Neyali thought to herself, holding to the words like a lifeline. #emph[At least Otharri is safe.] She would hold onto that for as long as she could. With luck, when the time came, it'd be what slowed her enough for a resistance fighter to cut her down. To Neyali's surprise, it was not a priest who came to begin Reyana's transformation but Slobad himself. There was a tenderness in how the goblin bade Neyali's friend to go to her knees, a grace in how she sank down, the bronze circle of her face raised as though to receive a blessing. Neyali averted her eyes, unable to bear the sight. #emph[At least the rest of the cell is safe] , Neyali said to herself again. #emph[At least Otharri is safe.] She heard a gentle click then: talons coming to rest on the bars above her head. The firebird trilled a series of low notes in greeting, beak nudged through the slats. "What are you doing here?" whispered Neyali, trying and failing to keep the relief from her voice. "You have to go." The firebird fixed one incredulous eye on her and inhaled. "I am one person. It's not worth it. You—" Neyali laughed deliriously, unable to stop herself, struck by her own hypocrisy. All this happened because of one person. She had given everything to save Reyana, believing that yes, that one life could be that important. Otharri breathed out. The sulfurous air went from filthy orange to an incandescent white-blue as the firebird's flames incinerated the bars. Ash, still limned in gold, flaked away in the breeze. He dove away to the next cage, doing the same over and over, while an alarm rose through the Salvage Complex. Otharri sang a defiant call to arms. And Neyali answered with a glad cry of her own. "This—" she boomed. Magic leaped from her to each Mirran Otharri freed, a slick of fire that clung to their skin. Neyali looked down to where Slobad waited, his sledgehammer in hand. "Is not where we die." If they moved quickly enough across the towering structures, there would be no chance that the Phyrexians would catch up. What few were crawling up the cages were kept at bay by Otharri's fire. Neyali searched for Reyana amid the chaos and found her behind, looking up at the clamor. Despite everything, she still reached out a hand, a final attempt. Reyana turned away. That was that then. Neyali swallowed. What she would have given for time to argue with Reyana, time to insist there was no reason to surrender, that Reyana had to fight. But they'd each made their decisions. Their paths were now separate. Neyali saluted her once friend. In the distance, she could see her cell—not just those who had chosen to follow Neyali on this quixotic mission, but all of them—charging into the Salvage Complex to clear a path for their escape. Later, she would have time to grieve. Now, she had to lead her people away. #figure(image("001_Cinders/05.jpg", width: 100%), caption: [Art by: <NAME>awan], supplement: none, numbering: none)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/grid-5-00.typ
typst
Other
// Test that trailing linebreak doesn't overflow the region. #set page(height: 2cm) #grid[ Hello \ Hello \ Hello \ World ]
https://github.com/Wh4rp/Presentacion-Typst
https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/ejemplos/8_modulo-fabuloso.typ
typst
#let faboloso(term, color: blue) = { text(color, box[||| #term |||]) }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/def_use/base2.typ
typst
Apache License 2.0
#import "base.typ": * #let y = 2;
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fh-joanneum-iit-thesis/1.2.2/template/chapters/2-intro.typ
typst
Apache License 2.0
#import "global.typ": * = Introduction #v(1em) #quote( [Privacy matters; privacy is what allows us to determine who we are and who we want to be. I don't want to live in a world where there's no privacy, and therefore no room for intellectual exploration and creativity.], [<NAME>], ) #v(1em) #lorem(25) #todo( [ Describe the kind of problem at hand? The problem is relevant in which context? What does not work well at the moment? What do people need? Describe the background, the prerequisites for your work. Optionally, add terms and definitions whenever they might not be clear to a fellow student. ], ) == Problem Statement #lorem(25) #todo( [ What is the overall problem? Give examples. Motivate! Compared to existing solutions for the problem at hand, why does someone need a better, faster, and somewhat different solution? ], ) == Research Questions #lorem(25) #todo([ Focus on one or two main research questions and detail on them. ]) == Hypothesis #lorem(25) #todo( [ State a hypothesis – a rough idea – of how you think a solution might look like. Explain, how to possibly solve a given problem. ], ) #pagebreak() == Method #lorem(25) #todo( [ Describe your structured, academic approach to find — and evaluate — a solution. When you needed (large) data sets for you work, explain how you collected and filtered raw data. For the validation (see Section Evaluation 6) you want to describe the criteria for objective measurement. ], ) #todo( [ #v(3cm) Note the so called "*<NAME>*": At the end of one chapter you might sum up the content. Then you give an outlook on the next chapter. For example, at the end of the introduction you might start the text with: _The remainder of the thesis is structured as follows:_ _The implementation is presented in @implementation (including the backend @backend and the frontend @frontend). The evaluation ... ..._ ], ) #todo( [ #v(3cm) *Hints for footnotes in Typst*: As shown in #footnote[Visit https://typst.app/docs for more details on formatting the document using typst. Note, _typst_ is written in the *Rust* programming language.] we migth discuss the alternatives. *Hints for formatting in Typst*: + You can use built-in styles: + with underscore (\_) to _emphasise_ text + forward dash (\`) for `monospaced` text + asterisk (\*) for *strong* (bold) text You can create and use your own (custom) formatting macros: + check out the custom style (see in file `lib.typ`): + `#textit` for #textit([italic]) text + `#textbf` for #textbf([bold face]) text ], )
https://github.com/levinion/typst-dlut-templates
https://raw.githubusercontent.com/levinion/typst-dlut-templates/main/examples/thesis/thesis.typ
typst
MIT License
#import "../../templates/thesis/main.typ":thesis,three_line_table,equa,bold #show: thesis.with( faculty: lorem(3), major: lorem(3), name: lorem(3), id: lorem(3), sup: lorem(3), rev: lorem(3), date: lorem(3), chinese_abstract: [ “摘要”是摘要部分的标题,不可省略。 标题“摘要”选用模板中的样式所定义的“标题1”,再居中;或者手动设置成字体:黑体,居中,字号:小三,1.5倍行距,段后11磅,段前为0。 摘要是毕业论文(设计)的缩影,文字要简练、明确。内容要包括目的、方法、结果和结论。单位采用国际标准计量单位制,除特别情况外,数字一律用阿拉伯数码。文中不允许出现插图。重要的表格可以写入。 摘要正文选用模板中的样式所定义的“正文”,每段落首行缩进2个汉字;或者手动设置成每段落首行缩进2个汉字,字体:宋体,字号:小四,行距:多倍行距 1.25,间距:段前、段后均为0行,取消网格对齐选项。 摘要篇幅以一页为限,字数限500字以内。 摘要正文后,列出3-5个关键词。“关键词:”是关键词部分的引导,不可省略。关键词请尽量用《汉语主题词表》等词表提供的规范词。 关键词与摘要之间空一行。关键词词间用分号间隔,末尾不加标点,3-5个;黑体,小四,加粗。关键词整体字数限制在一行。 ], chinese_keywords: ("写作规范", "排版格式", "毕业论文(设计)"), english_abstract: [ 外文摘要要求用英文书写,内容应与“中文摘要”对应。使用第三人称,最好采用现在时态编写。 “Abstract”不可省略。标题“Abstract”选用模板中的样式所定义的“标题1”,再居中;或者手动设置成字体:Times NewRoman,居中,字号:小三,多倍行距1.5倍行距,段后11磅,段前为0行。 标题“Abstract”上方是论文的英文题目,字体:Times New Roman,居中,字号:小三,行距:多倍行距1.25,间距:段前、段后均为0行,取消网格对齐选项。 Abstract正文选用设置成每段落首行缩进2字,字体:Times New Roman,字号:小四,行距:多倍行距1.25,间距:段前、段后均为0行,取消网格对齐选项。 Key words与摘要正文之间空一行。Key words与中文“关键词”一致。词间用分号间隔,末尾不加标点,3-5个;Times NewRoman,小四,加粗。 ], english_keywords: ("Write Criterion","Typeset Format","Graduation Project (Thesis)"), intro: [ 理工文科所有专业本科生的毕业论文(设计)都应有“引言”的内容。如果引言部分省略,该部分内容在正文中单独成章,标题改为文献综述,用足够的文字叙述。从引言开始,是正文的起始页,页码从1开始顺序编排。 针对做毕业设计:说明毕业设计的方案理解,阐述设计方法和设计依据,讨论对设计重点的理解和解决思路。 针对做毕业论文:说明论文的主题和选题的范围;对本论文研究主要范围内已有文献的评述;说明本论文所要解决的问题。建议与相关历史回顾、前人工作的文献评论、理论分析等相结合。 注意:是否如实引用前人结果反映的是学术道德问题,应明确写出同行相近的和已取得的成果,避免抄袭之嫌。注意不要与摘要内容雷同。 书写格式说明: 标题“引言”选用模板中的样式所定义的“引言”;或者手动设置成字体:黑体,居中,字号:小三,1.5倍行距,段后1行,段前为0行。 引言的字数在3000字左右(毕业设计类引言可适当调整为800字左右)。引言正文选用模板中的样式所定义的“正文”,每段落首行缩进2字;或者手动设置成每段落首行缩进2字,宋体,小四,多倍行距 1.25,段前、段后均为0行,取消网格对齐选项。 ], conclusion:[ 结论是理论分析和实验结果的逻辑发展,是整篇论文的归宿。结论是在理论分析、试验结果的基础上,经过分析、推理、判断、归纳的过程而形成的总观点。结论必须完整、准确、鲜明、并突出与前人不同的新见解。 书写格式说明: 标题“结论”选用模板中的样式所定义的“结论”,或者手动设置成字体:黑体,居中,字号:小三,1.5倍行距,段后1行,段前为0行。 结论正文选用模板中的样式所定义的“正文”,每段落首行缩进2字;或者手动设置成每段落首行缩进2字,字体:宋体,字号:小四,行距:多倍行距 1.25,间距:段前、段后均为0行。 ], bib: bibliography("./ref.bib", full: true), changelog: [ 修改是论文写作过程中不可或缺的重要步骤,是提高论文质量的有效环节。修改的过程其实就是“去伪存真”、去糟粕取精华使论文不断“升华”的过程。 以下内容要求填写到毕业论文(设计)修改记录中: 一、毕业论文(设计)题目修改(没有可删除,序号依次递增) 原题目: 修稿后题目: 二、指导教师变更(没有可删除,序号依次递增) 原指导教师: 变更后指导教师: 三、校外毕业论文(设计)时间节点记录(没有可删除,序号依次递增) 本人于xxxx年x月申请到xxxxxx大学做毕业论文(设计),校外指导教师为:xxxxxx,校内指导教师为:xxxxxx。xxxx年x月x日回到学校。 四、毕业论文(设计)内容重要修改记录(不可缺少) 包括:指导教师要求的重大修改,评阅教师要求的修改,答辩委员会提出的修改意见以及检测后的修改记录等。 五、毕业论文(设计)外文翻译修改记录(不可缺少) 六、毕业论文(设计)正式检测重复比(不可缺少) 修改记录正文选用模板中的样式所定义的“正文”,每段落首行缩进2字;字体:宋体,字号:小四,行距:多倍行距 1.25,间距:段前、段后均为0行。 ], thanks: [ 毕业论文(设计)致谢中不得书写与毕业论文(设计)工作无关的人和事,对指导老师的致谢要实事求是。 对其他在本研究工作中提出建议和给予帮助的老师和同学,应在论文中做明确的说明并表示谢意。 这部分内容不可省略。 书写格式说明: 标题“致谢”选用模板中的样式所定义的“致谢”;或者手动设置成字体:黑体,居中,字号:小三,1.5倍行距,段后1行,段前为0行。 致谢正文选用模板中的样式所定义的“正文”,每段落首行缩进2字;或者手动设置成每段落首行缩进2字,字体:宋体,字号:小四,行距:多倍行距 1.25,间距:段前、段后均为0行。 ] ) = 正文格式说明 正文是毕业论文(设计)的主体,#bold[是毕业论文或工程设计说明书的核心部分。要求学生运用所学的数学、自然科学、工程基础和专业知识解决复杂问题的能力,能够针对问题设计解决方案,在设计环节中体现创新意识,并考虑社会、健康、安全、法律、文化、环境以及社会可持续发展等因素;]要着重反映毕业设计或论文的工作,要突出毕业设计的设计过程、设计依据及解决问题的方法;毕业论文重点要突出研究的新见解,例如新思想、新观点、新规律、新研究方法以及新结果等。 #bold[正文 (含引言或文献综述部分)内容应包括以下方面: 本研究内容的总体方案设计与选择论证; 本研究内容硬件与软件的设计计算,实验装置与测试方法等; 本研究内容试验方案设计的可行性、有效性、技术经济分析等,试验数据结果的处理与分析论证以及理论计算结果的分析与展望等; 本研究内容的理论分析。对本研究内容及成果应进行较全面、客观的理论阐述,应着重指出本研究内容中的创新、改进与实际应用。理论分析中,应将他人研究成果单独书写并注明出处,不得将其与本人提出的理论分析混淆在一起。对于将其他领域的理论、结果引用到本研究领域者,应说明该理论的出处,并论述引用的可行性与有效性。 自然科学的论文应推理正确,结论清晰,无科学性错误。 管理和人文学科的论文应包括对研究问题的论述和系统分析,比较研究,模型或方案设计,案例论证或实证分析,模型运行的结果或建议,改进措施等。] 正文要求论点正确,推理严谨,数据可靠,文字精练,条理分明,文字图表规范、清晰和整齐,在论文的行文上,要注意语句通顺,达到科技论文所必须具备的“正确、准确、明确”的要求。计算单位采用国务院颁布的《统一公制计量单位中文名称方案》中规定和名称。各类单位、符号必须在论文中统一使用,外文字母必须注意大小写,正斜体。简化字采用正式公布过的,不能自造和误写。利用别人研究成果必须附加说明。引用前人材料必须引证原著文字。在论文的行文上,要注意语句通顺,达到科技论文所必须具备的“正确、准确、明确”的要求。 == 论文格式基本要求 // should not use "+" because of confusing indent 论文格式基本要求: (1) 纸 型:A4纸。 (2) 打印要求:双面打印(除封面、任务书、原创性声明、关于使用授权的声明、中英文摘要等单面打印外,其余部分要求双面打印)。 (3) 页边距:上3.5cm,下2.5cm,左2.5cm、右2.5cm。 (4) 页 眉:2.5cm,页脚:2cm,左侧装订。 (5) 字 体:正文全部宋体、小四。 (6) 行 距:多倍行距:1.25,段前、段后均为0,取消网格对齐选项。 == 论文页眉页脚的编排 一律用阿拉伯数字连续编页码。页码应由正文首页开始,作为第1页。封面不编入页码。将摘要、Abstract、目录等前置部分单独编排页码。页码必须标注在每页页脚底部居中位置,宋体,小五。 页眉,宋体,五号,居中。填写内容是“毕业论文(设计)中文题目”。 模板中已经将字体和字号要求自动设置为缺省值,只需双击页面中页眉位置,按要求将填写内容替换即可。 = 图表及公式的格式说明 == 图的格式说明 === 图的格式示例 图在正文中的格式示例如@example 所示。 #figure(image("./images/example.png", width: 40%), caption: [示例图片]) <example> 表、图序号后面,同样适当留空(汉字状态敲两次空格键)。 @example 显示了论文模板中所定义的样式选择方法。使用鼠标选择相应的样式,对应的文字格式就发生相应改变。 == 表的格式说明 === 表的格式示例 表在正文中的常用格式如表2.1至表2.3所示,请参考使用。 物流的概念和范围如表2.1表述。 表、图序号与后面文字同样应当适当留空(两次空格键)。 #three_line_table( columns:(30%,auto), ( ("本质","过程"), ("途径或方法","规划、实施、控制"), ("目标","效率、成本效益"), ("活动或作业","流动与储存"), ("处理对象","原材料、在制品、产成品、相关信息"), ("范围","从原点(供应商)到终点(最终顾客)"), ("目的或目标","适应顾客的需求(产品、功能、数量、质量、时间、价格)"), ), caption: [物流的概念和范围], ) 美国广义物流后(勤)协会给出的定义如下:“为了符合顾客的要求,从原点到消费点对原材料、在制品、产成品与相关信息的流动和储存的效率成本效益进行规划、实施和控制的过程”。由此可见,物流不是作为一种具体技术和方法来研究的,而是一个过程或管理。 == 公式的格式说明 === 公式的格式示例 由于一般的文献资料中所给出的载荷和抗力的统计参数主要为变异系数,为便于讨论,定义公式形式如下: #equa[ $ "LRI"= 1\/sqrt(1+(mu_R/mu_s)^2 (sigma_R/sigma_S)^2) $ ] 其中,μR和μS分别为抗力和载荷效应的均值,……。
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/common/kode.typ
typst
#import "@preview/pinit:0.2.0": * #import "@preview/showybox:2.0.1": showybox #import "style.typ": phantom #let kode-default-filename = state("kode-default-filename", hide[a]) #let kode( filename: context kode-default-filename.get(), font-size: .7em, width: 35em, o: none, escape-mode: "comment", status: "success", nextBody: [], body, ) = { show: block.with(inset: -.1em) set text( font: "Liberation Mono", size: font-size, ) //? HACKY way to make filename pinnable. let anchor-hack = hide[#text(size: 0em)[~]] let output-content = if o != none { o = [#o#anchor-hack] show: pad.with(x: -1em, y: -.65em) if status == "success" { showybox( title: [#anchor-hack#[Output#pin("o-title")]#anchor-hack], width: auto, shadow: (offset: 3pt), frame: (title-color: green.lighten(60%), body-color: green.lighten(80%)), title-style: (color: black, align: center), o, ) } else if status == "compile" { showybox( title: [#anchor-hack#[Compile-time error#pin("o-title")]#anchor-hack], width: auto, shadow: (offset: 3pt), frame: (title-color: red.lighten(60%), body-color: red.lighten(80%)), title-style: (color: black, align: center), o, ) } else if status == "runtime" { showybox( title: [#anchor-hack#[Runtime error#pin("o-title")]#anchor-hack], width: auto, shadow: (offset: 3pt), frame: (title-color: red.lighten(60%), body-color: red.lighten(80%)), title-style: (color: black, align: center), o, ) } } else { "" } let kode-content = { let body = { show raw.line: it => { show regex("#pin\(.*?\)"): it => pin(eval(it.text.slice(5, it.text.len() - 1))) if escape-mode == "comment" { show regex("(/\*|\*/)"): none it } else { it } } body } if filename != none { show: showybox.with( shadow: (offset: 3pt), width: auto, title: [ #anchor-hack#filename#anchor-hack #if status == "success" { place(right + horizon)[ #rect(fill: green, radius: .32em)[ #text(font: "Segoe UI Symbol")[#sym.checkmark] #place(dx: 50% + .24em, pin("kode-status")) ] ] } else if status == "compile" or status == "runtime" { place(right + horizon)[ #rect(fill: red, radius: .32em)[ #text(font: "Segoe UI Symbol")[#sym.times] #place(dx: 50% + .24em, pin("kode-status")) ] ] } ], title-style: (color: white, align: center + horizon), footer: output-content, ) body } else { show: showybox.with(shadow: (offset: 3pt), width: auto, footer: output-content) body } } kode-content nextBody } #let kode-content(body) = text(fill: black, rect(fill: blue.lighten(40%).transparentize(20%), radius: .36em, body)) #let err-content(body) = text(fill: black, rect(fill: red.transparentize(20%), radius: .36em, body)) #let kode-arrow-to-left(..args, start, end) = pinit-arrow( start-dx: -4pt, start-dy: -4pt, end-dx: 4pt, end-dy: -4pt, start, end, ..args, ) #let kode-arrow-to-right(..args, start, end) = pinit-arrow( start-dx: 4pt, start-dy: -4pt, end-dx: -4pt, end-dy: -4pt, start, end, ..args, ) #let kode-to(..args, target, body) = pinit-point-to( pin-dx: -5pt, body-dx: -10pt, body-dy: 0pt, ..args.named(), (target,), kode-content(body), ) #let kode-to-straight(..args, target, body) = pinit-point-to( pin-dx: 3pt, pin-dy: -4pt, body-dx: 3pt, body-dy: -12pt, offset-dx: 64pt, offset-dy: -4pt, ..args.named(), (target,), kode-content(body), ) #let kode-to-bottom(..args, target, body) = pinit-point-to( pin-dx: -16pt, body-dx: -25%, offset-dx: -16pt, offset-dy: 55pt, ..args.named(), (target,), kode-content(body), ) #let kode-to-red(..args, target, body) = pinit-point-to( pin-dx: -5pt, body-dx: -10pt, body-dy: 0pt, ..args.named(), (target,), err-content(body), ) #let kode-to-red-bottom(..args, target, body) = pinit-point-to( pin-dx: -16pt, body-dx: -25%, offset-dx: -16pt, offset-dy: 55pt, ..args.named(), (target,), err-content(body), ) #let kode-to-red-straight(..args, target, body) = pinit-point-to( pin-dx: 3pt, pin-dy: -4pt, body-dx: 3pt, body-dy: -12pt, offset-dx: 64pt, offset-dy: -4pt, ..args.named(), (target,), err-content(body), ) #let kode-hl(..args, st, ed) = pinit-highlight( fill: green.transparentize(75%), dx: -.2em, dy: -.9em, extended-width: .4em, extended-height: 1.2em, ..args.named(), st, ed, ) #let kode-hl-red(..args, st, ed) = pinit-highlight( fill: red.transparentize(75%), dx: -.2em, dy: -.9em, extended-width: .4em, extended-height: 1.2em, ..args.named(), st, ed, )
https://github.com/lyzynec/orr-go-brr
https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/lib.typ
typst
#let project( title: "", author: "", body) = { set document(author: author, title: title) set text(font: "Linux Libertine", lang: "en") set page(numbering: "1") set heading(numbering: "1.A.1") show heading.where(level: 1): it =>[ #block(it.body) ] show heading.where(level: 2): it =>[ #block(it.body) ] show heading.where(level: 4): it =>[ #block(it.body + ":") ] set math.mat(delim: "[") set math.vec(delim: "[") align(center)[#block(text(weight: 700, 1.75em, title))] body } #let week(body) = { context heading(level: 1)[Week #{counter(heading).get().at(0) + 1}] body } #let knowledge(body) = { heading(level: 2)[Knowledge (I remember and understand)] body } #let skills(body) = { heading(level: 2)[Skills (I can use the knowledge to solve a problem)] body } #let question(name: [], body) = { heading(level: 3)[#name] body } #let part(name: [], body) = { box(width: 100%, stroke: 1pt, inset: 7.5pt)[ #heading(level: 4)[#name] #body ] }
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/5数组和广义表.typ
typst
#import "../template.typ": * #import "@preview/pinit:0.1.4": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #import "/book.typ": book-page #show: book-page.with(title: "数组和广义表 | DSA") = 数组和广义表 <数组和广义表> == 数组 #note_block[ *行序为主序*: 二维数组$A$中任一元素 $a_(i,j)$ 的存储位置 $ "LOC"(i,j) = #pin(1)"LOC"(0,0)#pin(2) + (b_2×i+j)×L $ // #pinit-point-from(2)[基地址] #pinit-highlight(1, 2) #pinit-place(1, dy: 6pt)[ #set text(size: 8pt) 基地址 ] 扩展到 $n$ 维数组: $ "LOC"(j_1,j_2, dots, j_n) = "LOC"(0,0, dots, 0) + sum_(i=1)^(n) c_i×j_i $ 其中,$c_n = L$,$c_(i-1) = b_i × c_i$,$1 < i <= n$。 称为 $n$ 维数组的映象函数。数组元素的存储位置是其下标的线性函数。 ] === 矩阵的压缩存储 #definition[ *稀疏矩阵*:矩阵中大部分元素为零,只有少数元素非零。 ] 而稀疏矩阵又分为: - *特殊矩阵*:如三角矩阵,对角矩阵。 - *随机稀疏矩阵*:非零元在矩阵中随机出现。 对于随机稀疏矩阵,有三种压缩存储方法: + 三元组顺序表 + 行逻辑联接的顺序表 + 十字链表 ==== 三元组顺序表 核心思想是将矩阵中的非零元素的行、列、值三个信息存储在一个三元组中,只存储非零元素。然后用一个顺序表存储这些三元组。 ```c typedef struct { int i, j; // 非零元素的行和列 ElemType e; // 非零元素的值 } Triple; typedef struct { // 书上是 union,大错特错 Triple data[MAXSIZE + 1]; // 非零元素三元组表,data[0] 未用 int mu, nu, tu; // 矩阵的行数、列数和非零元素个数 } TSMatrix; ``` 求转置矩阵虽然只要交换行列号,但是简单的交换会导致非零元素的行列号不再有序,因此需要先按列号排序。具体步骤如下: + 确定每一行的第一个非零元在转置矩阵的顺序表中的位置 + 从第一个非零元开始,按列号递增的顺序存储非零元素 ```c Status FastTransposeSMatrix(TSMatrix M, TSMatrix &T) { T.mu = M.nu; T.nu = M.mu; T.tu = M.tu; if (T.tu) { int num[M.nu + 1] = {0}; // 存储每一列的非零元素个数 for (int t = 1; t <= M.tu; t++) { num[M.data[t].j]++; } int cpot[M.nu + 1] = {0, 1}; // 存储每一列第一个非零元在 T 中的位置 for (int col = 2; col <= M.nu; col++) { cpot[col] = cpot[col - 1] + num[col - 1]; } for (int p = 1; p <= M.tu; p++) { int col = M.data[p].j; int q = cpot[col]; T.data[q].i = M.data[p].j; T.data[q].j = M.data[p].i; T.data[q].e = M.data[p].e; cpot[col]++; // 下一个非零元素的位置 } } return OK; } ``` 复杂度:$O(n + t)$,其中 $n$ 为矩阵的列数,$t$ 为非零元素个数。 ==== 行逻辑联接的顺序表 在三元组顺序表的基础上,增加一个一维数组 `rpos`,存储每一行的第一个非零元在三元组表中的位置。这样就可以实现按行快速访问非零元素。 ```c typedef struct { Triple data[MAXSIZE + 1]; int rpos[MAXRC + 1]; // 每一行的第一个非零元在三元组表中的位置 int mu, nu, tu; } RLSMatrix; ``` 原来矩阵相乘是这样的: ```c for (i = 1; i <= m1; ++i) for (j = 1; j <= n2; ++j) { Q[i][j] = 0; for (k = 1; k <= n1; ++k) Q[i][j] += M[i][k] * N[k][j]; } ``` 复杂度为 $O(n^3)$。而两个稀疏矩阵相乘则可以优化为: ```c Status MultSMat(RLSMatrix M, RLSMatrix N, RLSMatrix &Q) { if (M.nu != N.mu) return ERROR; Q.mu = M.mu; Q.nu = N.nu; Q.tu = 0; if (M.tu * N.tu != 0) { for (int arow = 1; arow <= M.mu; arow++) { int tpot = 0; int brow = arow + 1; if (arow < M.mu) brow = M.rpos[arow + 1]; for (int ccol = 1; ccol <= N.nu; ccol++) { int trow = arow; int tcol = ccol; int sum = 0; // 两个矩阵的行列号都不超过自己的行列数 while (trow < brow && M.data[trow].i <= arow) { while (tcol < N.nu && N.data[tcol].i <= M.data[trow].j) { // 两个矩阵的行列号相等,相乘 if (N.data[tcol].i == M.data[trow].j) { sum += M.data[trow].e * N.data[tcol].e; tcol++; } } trow++; } // 如果和不为 0,存储到 Q 中 if (sum != 0) { Q.tu++; if (Q.tu > MAXSIZE) return ERROR; Q.data[Q.tu].i = arow; Q.data[Q.tu].j = ccol; Q.data[Q.tu].e = sum; } } } } return OK; } ``` 这样的时间复杂度是 $O(n^2)$。 == 广义表 #definition[ *广义表*:广义表是线性表的推广,是n个元素的有限序列,每个元素都可以是原子元素,也可以是另一个广义表。也称其为列表。 ] 广义表的结构:#box(table(columns: (4em, 3em, 3em), rows: 2em, align: center + horizon, [Tag=1], [HP], [TP])) 或 #box(table(columns: (4em, 3em), rows: 2em, align: center + horizon, [Tag=0], [Data])) *结构特点*: - 广义表中的数据元素有相对次序; - 广义表的长度定义为最外层包含的元素个数; - 广义表的深度定义为广义表中括号的层数。原子的深度为 0,空表的深度为 1。 - 广义表可以共享。 - 广义表可以是一个递归的表,这时候深度是无限的。 - 任何一个非空广义表都可以分解为一个表头和一个表尾,其中表头是一个元素,表尾是一个广义表。 #image("../assets/2024-06-23-20-17-12.png", width: 80%) === 求广义表的深度 将广义表分解成 $h$ 个子表,子表的深度最大值加 1 即为广义表的深度。 ```c int Depth(GList L) { if (!L) return 1; if (L->tag == 0) return 0; int max = 0; for (GList p = L; p; p = p->tp) { int dep = Depth(p->hp); if (dep > max) max = dep; } return max + 1; } ``` === 复制广义表 一对确定的表头和表尾可唯一确定一个广义表,因此复制广义表的关键是复制表头和表尾。 ```c GList Copy(GList L) { if (!L) return NULL; GList p = (GList) malloc(sizeof(GLNode)); if (!p) exit(OVERFLOW); if (L->tag == 0) { p->tag = 0; p->hp = L->hp; } else { p->tag = 1; p->hp = Copy(L->hp); p->tp = Copy(L->tp); } return p; } ```
https://github.com/alerque/polytype
https://raw.githubusercontent.com/alerque/polytype/master/content/page-geometry.md
markdown
+++ title = "Page Geometry 101" description = "Pick a paper and some margins" extra.typesetters = [ "sile", "typst", "xelatex", "groff", "pagedjs" ] extra.typesetter_args = { groff = "-P-pA7" } +++ An A7 page with 1cm margins and 1cm paragraph indentation.
https://github.com/peng1999/typst-pyrunner
https://raw.githubusercontent.com/peng1999/typst-pyrunner/main/README.md
markdown
MIT License
# Typst Python Runner Plugin Run python code in [typst](https://typst.app) using [RustPython](https://github.com/RustPython/RustPython). ````typst #import "@preview/pyrunner:0.2.0" as py #let compiled = py.compile( ```python def find_emails(string): import re return re.findall(r"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b", string) def sum_all(*array): return sum(array) ```) #let txt = "My email address is <EMAIL> and my friend's email address is <EMAIL>." #py.call(compiled, "find_emails", txt) #py.call(compiled, "sum_all", 1, 2, 3) ```` Block mode is also available. ````typst #let code = ``` f'{a+b=}' ``` #py.block(code, globals: (a: 1, b: 2)) #py.block(code, globals: (a: "1", b: "2")) ```` The result will be `a+b=3` and `a+b='12'`. ## Current limitations Due to restrictions of typst and its plugin system, some Python function will not work as expected: - File and network IO will always raise an exception. - `datatime.now` will always return 1970-01-01. Also, there is no way to import third-party modules. Only bundled stdlib modules are available. We might find a way to lift this restriction, so feel free to submit an issue if you want this functionality. ## API ### `block` Run Python code block and get its result. #### Arguments - `code` : string | raw content - The Python code to run. - `globals` : dict (named optional) - The global variables to bring into scope. #### Returns The last expression of the code block. ### `compile` Compile Python code to bytecode. #### Arguments - `code` : string | raw content - The Python code to compile. #### Returns The bytecode representation in `bytes`. ### `call` Call a python function with arguments. #### Arguments - `compiled` : bytes - The bytecode representation of Python code. - `fn_name` : string - The name of the function to be called. - `..args` : any - The arguments to pass to the function. #### Returns The result of the function call. ## Build from source Install [`wasi-stub`][]. You should use a slightly modified one. See [the related issue](https://github.com/astrale-sharp/wasm-minimal-protocol/issues/22#issuecomment-1827379467). [`wasi-stub`]: https://github.com/astrale-sharp/wasm-minimal-protocol <!-- ``` cargo install --git https://github.com/astrale-sharp/wasm-minimal-protocol.git wasi-stub ```--> Build pyrunner. ``` rustup target add wasm32-wasi cargo build --target wasm32-wasi make pkg/typst-pyrunner.wasm ``` Add to local package. ``` mkdir -p ~/.local/share/typst/packages/local/pyrunner/0.0.1 cp pkg/* ~/.local/share/typst/packages/local/pyrunner/0.0.1 ```
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/references/redefine.typ
typst
Apache License 2.0
#let /* ident after */ x = 1; #let y = { x + x; } #let f(y) = x + y; #let x = x; #let f = x;
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.2.0/src/intersection.typ
typst
Apache License 2.0
#import "vector.typ" #import "util.typ" /// Check for line-line intersection and return point or none /// /// - a (vector): Line 1 point 1 /// - b (vector): Line 1 point 2 /// - c (vector): Line 2 point 1 /// - d (vector): Line 2 point 2 /// - ray (bool): treat both lines as infinite /// -> (vector,none) #let line-line(a, b, c, d, ray: false) = { let lli8(x1, y1, x2, y2, x3, y3, x4, y4) = { let nx = (x1*y2 - y1*x2)*(x3 - x4)-(x1 - x2)*(x3*y4 - y3*x4) let ny = (x1*y2 - y1*x2)*(y3 - y4)-(y1 - y2)*(x3*y4 - y3*x4) let d = (x1 - x2)*(y3 - y4)-(y1 - y2)*(x3 - x4) if d == 0 { return none } return (nx / d, ny / d, 0) } let pt = lli8(a.at(0), a.at(1), b.at(0), b.at(1), c.at(0), c.at(1), d.at(0), d.at(1)) if pt != none { let on-line(pt, a, b) = { let (x, y, ..) = pt let epsilon = util.float-epsilon let mx = calc.min(a.at(0), b.at(0)) - epsilon let my = calc.min(a.at(1), b.at(1)) - epsilon let Mx = calc.max(a.at(0), b.at(0)) + epsilon let My = calc.max(a.at(1), b.at(1)) + epsilon return mx <= x and Mx >= x and my <= y and My >= y } if ray or (on-line(pt, a, b) and on-line(pt, c, d)) { return pt } } } // Check for line-cubic bezier intersection #let line-cubic(la, lb, s, e, c1, c2) = { import "/src/bezier.typ": line-cubic-intersections as line-cubic return line-cubic(la, lb, s, e, c1, c2) } // Check for line-linestrip intersection #let line-linestrip(la, lb, v) = { let pts = () for i in range(0, v.len() - 1) { let pt = line-line(la, lb, v.at(i), v.at(i + 1)) if pt != none { pts.push(pt) } } return pts } /// Check for line-path intersection in 2D /// /// - la (vector): Line start /// - lb (vector): Line end /// - path (path): Path #let line-path(la, lb, path) = { let segment(s) = { let (k, ..v) = s if k == "line" { return line-linestrip(la, lb, v) } else if k == "cubic" { return line-cubic(la, lb, ..v) } else { return () } } let pts = () for s in path.at("segments", default: ()) { pts += segment(s) } return pts } /// Check for path-path intersection in 2D /// /// - a (path): Path a /// - b (path): Path b /// - samples (int): Number of samples to use for bezier curves /// -> array List of vectors #let path-path(a, b, samples: 8) = { import "bezier.typ": cubic-point // Convert segment to vertices by sampling curves let linearize-segment(s) = { let t = s.at(0) if t == "line" { return s.slice(1) } else if t == "cubic" { return range(samples + 1).map( t => cubic-point(..s.slice(1), t/samples) ) } } let pts = () for s in a.at("segments", default: ()) { let sv = linearize-segment(s) for ai in range(0, sv.len() - 1) { pts += line-path(sv.at(ai), sv.at(ai + 1), b) } } return pts }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/024%20-%20Shadows%20over%20Innistrad/007_Promises%20Old%20and%20New.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Promises Old and New", set_name: "Shadows Over Innistrad", story_date: datetime(day: 13, month: 04, year: 2016), author: "<NAME>", doc ) #emph[When Jace went to Markov Manor, he was hoping to find the vampire Planeswalker Sorin. What he found, however, was a manor in ruins, twisted into impossible shapes, its inhabitants embedded in the masonry. For Jace, it meant the start of a new mystery. But what he didn't know was that he had just missed Sorin, and that this declaration in stone was meant for the ancient vampire.] #emph[Sorin's past has come back to haunt him. Though shunned by his own kind, he hopes to gather the aid of the vampires to confront the threat that has come to Innistrad. His search has brought him to the remote estate of the powerful Olivia Voldaren.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) A hundred or more pairs of eyes watched him from behind elegant masks as he made his way across the ballroom. Another person might have felt like a mouse among a host of owls in such company, but not him. He strode beneath the vaulted ceiling, his footfalls echoing so that they broke through the hiss of whispers that all spoke the same name. "<NAME>," came a musical voice above the whispers, a voice both feminine and sarcastic, a voice that formed the syllables of his name in such a way that it gave Sorin the impression it was the punchline of a joke long in the telling. But that didn't matter. What did matter was that it was a familiar voice, and that it belonged to the person he had come here to see. "It seems I have interrupted quite a party," Sorin said, sweeping a hand in a wide arc before bringing it to rest on his chest in a theatrical play at humility. "For that, I'm sorry. But please, Olivia, reveal yourself. We must talk." He scanned the room where so many vampires had gathered to partake in the lavish festivities prepared by their host. Sorin had attended dozens, if not hundreds of such events, but not for over a thousand years. At last, one of the vampires lowered her mask, a porcelain thing built in mockery of Avacyn's heron. She tossed it aside, and with as much effort as it took to blink, she rose into the air, a demonstration of the power that flowed in her ancient blood. #figure(image("007_Promises Old and New/01.jpg", width: 100%), caption: [<NAME> | Art by <NAME>], supplement: none, numbering: none) "I fail to imagine what it is we have to have to discuss, #emph[lord of Innistrad] ," Olivia said, bowing at the waist. It was her turn to wield theatrics in mock respect, and around the ballroom, laughter broke out. Sorin ignored the jape. This was her house, after all, and she could have her fun. He simply returned her gaze, looking up at her pale face, which was framed by thick red curls. He knew this game. She would appear as his superior. It was a performance she had practiced many times, but he was not one of these neonates who fell over themselves to garner her favor, and he would tolerate it only for as long as he could. "The scion of <NAME> is not welcome here," she continued. Then she gestured toward no one in particular. "Show him out." Without hesitation, half a dozen vampires emerged from the gathered celebrants. One of them drew a thin duelist's blade from its scabbard. "<NAME> asked you to leave," he said. "You don't belong here." That was all he would tolerate. Sorin's own sword flicked out in a succession of flashes that left five of his escorts writhing on the ground, curls of black vapor billowing from deep wounds. Only one remained—the duelist—but Sorin looked past him to Olivia to make sure she was taking this in. She was. Then he raised his hand, and as the duelist lunged for him, Sorin curled his fingers into a fist, and suddenly, his assailant's body burst apart in a scattering of ashes. #figure(image("007_Promises Old and New/02.jpg", width: 100%), caption: [Vindicate Judge Promo | Art by Karla Ortiz], supplement: none, numbering: none) The room fell silent. He had their attention. More importantly, he had hers. Sheathing his sword, he stepped forward. There was a reason for his visit, and however rotten it tasted to Sorin, he said, "I have come for your help." Olivia's mouth widened into a smile until her lips parted to reveal teeth that had meant the end of countless human lives across the centuries. She floated down to him, her movements so smooth that the red liquid in her glass barely rippled. Despite the elegance of her gown, she was barefoot, just as she had been in Sorin's memory—ever the indulgent recluse. And now, as she drew close, her toes glided inches above the polished stone floor. Olivia looked Sorin over, tilting her head to one side then the other, as though trying to discern Sorin's meaning on her own. "My help? And here I was convinced that this would be an unpleasant visit." Sorin knew she would relish this, but he was growing impatient. "Well, at least this will be a memorable party," she said, punctuating her remark by raising her glass and tipping its contents into her mouth. Then Sorin was forced to sidestep as Oliva moved past him. The crowd of masked revelers parted before the Voldaren progenitor, who nonchalantly waved a hand, an invitation for Sorin to follow. The pair of ancient vampires made their way through a succession of rooms that were each filled with party guests. #figure(image("007_Promises Old and New/03.jpg", width: 100%), caption: [Vampire Noble | Art by <NAME> Lee], supplement: none, numbering: none) In a dim study, Sorin observed a handful of vampires huddled at one end of the chamber where a weak whimper, barely strong enough to garner attention, rose from their center. One of the vampires faced Sorin and, blood running down his chin, hissed his irritation at the intrusion. Beyond him, Sorin glimpsed an outstretched arm with ribbons of red running down its length. #figure(image("007_Promises Old and New/04.jpg", width: 100%), caption: [Vampiric Fury | Art by <NAME>], supplement: none, numbering: none) Beyond the study, Olivia led Sorin into an enormous dining room—a long, cavernous hall with a dozen chandeliers spaced out over the expanse of an elegant table hewn of black wood. Around it, even more of Olivia's guests were gathered, feasting on the decadent foods and drinking their fill. It was a room Sorin remembered well from his visits here, and he knew that Olivia had taken him the long way here. She'd wanted him to see the feeding, wanted to flaunt it. She must have thought it would get under his skin. How little she understood. "Out," Olivia said. Though it came off less a command and more as a playful suggestion, the feasters obeyed all the same. With their departure went the sounds of celebration. By the time Olivia and Sorin took their seats at the end of the table, the room was quiet. "Why here, <NAME>?" Olivia asked. "Why not go beg on your own doorstep?" "I take it you haven't heard." At this, Olivia raised an eyebrow. "My grandfather's manor is no more." Olivia laughed, and it was less melodic than Sorin had expected. "You find this news amusing?" he said. "The news isn't amusing," Olivia said. "The messenger, however..." With an easy grace, she collapsed into the cushioned back of her chair. "If Markov Manor is in ruins, then look to Avacyn, your own creation. She's already destroyed Castle Falkenrath and scattered that bloodline. Your creature is on a rampage. Frankly, the fact that I didn't tear you to pieces myself when you sullied my house is a mark of my generosity." "I'm going to let that go, Olivia, because I need you to listen carefully to what I'm going to say." He rose from his seat and leaned on his knuckles. "I have just come from Markov Manor. Know this—it did not meet the same end as Castle Falkenrath. I came to you because the ruin of Markov Manor marks the beginning of something terrible for this world." #figure(image("007_Promises Old and New/05.jpg", width: 100%), caption: [Merciless Resolve | Art by Chase Stone], supplement: none, numbering: none) "Something terrible for you, you mean." Why not both? It was indeed terrible for him. But that didn't preclude danger to all of Innistrad. He never intended for it to come to this, and his thoughts drifted back to another age. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Sorin's consciousness had been spread out across the weeks he'd been down here. Or was it months? Years? He couldn't be certain, but in the midst of his trance, a spot of white found him. It cut through all the layers of his awareness, growing closer with each moment, until finally, it touched him. And then, in the span of a heartbeat, the wayward parts of his mind scrambled over each other to find their correct places in his being. The rush was almost too great for him bear. Something had gone wrong. Something had pulled him prematurely from his restoration.] #emph[When his eyes fluttered open, Sorin found himself sitting on the stone floor of a modest sanctuary. Slowly, he rose to his feet, a task that took more effort than it should have. He was still weakened and depleted, and as he gathered himself on unsteady legs, he noticed a dark stain that stretched out across the sanctuary floor—a permanent black shadow in the shape of an angel, a testament to the magnitude of his recent exertion, his creation.] #emph[Then the white light once again strobed in Sorin's head, and with the fog of the trance lifted, Sorin recognized it for what it was—the signature of another Planeswalker arriving on Innistrad, drawn to his Helvault.] #emph[Recovery would have to wait. Innistrad was his, and visitors could remain only at his pleasure. He must discover their intent. If it came to it, fighting a duel in his current state would be far from ideal, but a threat to his plane was unacceptable. Even diminished as he was, he was still more formidable than most, and besides, this time he would have help. In a burst of inky black smoke, <NAME> set off to discover who would dare intrude on his plane.] #emph[Another burst of smoke, and Sorin materialized in the shade of a gnarled tree whose twisting branches ended in clusters of red leaves. From his vantage, the curtain of gray clouds served as a backdrop against which a rough, angular, monolithic chunk of silver rested upon a promontory at the edge of a sheer cliff. In the dim light, the silver mass appeared almost black. The Helvault—it had come from the plane's silver moon, and it had taken great effort for Sorin to bring it here.] #figure(image("007_Promises Old and New/06.jpg", width: 100%), caption: [Helvault | Art by <NAME>], supplement: none, numbering: none) #emph[As he watched, a figure emerged from behind it. A woman, pale, with white hair that fell around her face in a messy array. As she came around, her fingertips brushed the Helvault's rough surface. She wore simple, drab garb, with a length of red cloth wound around a forearm serving as her only accent.] #emph[Sorin knew her immediately.] #emph[The lithomancer.] #emph[Nahiri.] #emph[She was a kor from Zendikar whom he'd known millennia ago. They had traveled together for a time, but not for many years, and the sight of her here on Innistrad struck Sorin as an oddity. In all their travels, he'd never brought her here. Their last encounter had been on her home plane, and because of the nature of their parting, he never thought he'd see her again.] #emph[And yet, here she was.] #emph[At the moment, Nahiri seemed captivated by the Helvault, so Sorin approached in silence. If anyone would appreciate what he had accomplished, it would be her.] #emph["You'll have to forgive my rudimentary attempt at shaping stone, young one," he said, standing behind her. At his words, Nahiri spun around. Her face broke into a wide smile as she stumbled over her first few attempts at a response until at last, the words burst from her lips.] #emph["My friend! You're alive!"] #emph["And why would I be otherwise?" He manipulated the muscles of his face to form a smile, and reached out to place a hand on her shoulder.] #emph["You never came." She covered his hand with one of her own. "On Zendikar, when I activated the signal from the Eye of Ugin, you never responded. I feared that—"] #emph[Sorin withdrew his hand. "The Eldrazi have broken free of their bonds?"] #emph["They did, yes."] #emph[A caustic bitterness rose in Sorin's throat. "Where is Ugin?" He asked.] #emph["He didn't come either," Nahiri said, looking up at Sorin. "But I handled it. On my own. With all the strength I could muster, I managed to reseal the titans' prison." She spoke with a confidence that Sorin didn't remember. There was power in her that hadn't been there when they had known each other thousands of years ago. And suddenly, standing there with Nahiri, Sorin became keenly aware of his own weakened state.] #emph["When the task was done, I came to find you," Nahiri continued, "I had to know if you still lived. And here you are." After a moment, Nahiri's smile slowly faded. "So where were you? Sorin, why didn't you respond to the signal?"] #emph["It never reached me," he said.] #emph["How is that possible?"] #emph["Hmm." Sorin extended his arm past Nahiri and pressed his hand against the surface of the Helvault. "You dedicated yourself to watch over the imprisoned Eldrazi, and it became clear to me that my plane was in dire need of its own protection, particularly in my absence. This Helvault is half of what I created to serve as such protection. It's not inconceivable that your signal from the Eye was unable to break through the magic that protects this plane."] #emph[Nahiri shook her head. "Did you know at the time that that would happen?"] #emph["It did not occur to me," Sorin replied. It was true, but he sensed an accusatory tone in her question, and he found himself weighing his words. "Though I see now that it was a possibility."] #emph["A possibility? You risked my plane, and more." There was hurt in her voice. "You abandoned me."] #emph[Sorin waved away the kor's concerns. "I was simply taking the appropriate precautions to protect my plane. I hardly think—"] #emph["We had an agreement, you and I." Nahiri's voice had suddenly shifted. It was icy, devoid of any of the warmth from only a moment ago.] #emph[A sharp hiss escaped between Sorin's teeth, and Nahiri stepped toward, only for him to turn his back to her.] #emph["Don't dismiss this," she said. "I was willing to jeopardize my home by luring the Eldrazi to it. I promised to chain myself to Zendikar to watch over them as their warden. I spent millennia with those monsters. Do you know what that's like?" As she spoke, the ground began to rumble. "All you had to do was come when I needed you."] #emph["Don't presume to own my actions, young one," Sorin replied, batting Nahiri's hand aside. "I am obligated to nothing. I owe you nothing! When your Planeswalker spark first ignited, it was I who discovered you. I could have ended you there, but I spared you." He rounded on her, and suddenly his face was only inches from hers. In a whisper, he continued, "I took you under my wing, and molded you into what you are. If you find it necessary to pester someone, go find Ugin. I have no patience for it."] #emph[The earth lurched violently, and for an instant, Sorin had to fight to keep from stumbling.] #emph[Beneath Nahiri's feet, a column of bedrock pushed through the soil to carry her into the air. "I'm not going anywhere."] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sorin picked up a crystal glass to inspect the ruby contents within. A thin film had begun to form across its surface. Between two pale fingers, Sorin twisted the delicate stem of the glass so that the film gave way and the liquid sloshed freely. He raised the glass so that the light of the chandelier filtered through it, and he watched shapes of red light stretch out over the nearby place settings on the table. "Do you know why I created Avacyn, Olivia?" Sorin said at last. At the mention of that name, the smirk dissolved from Olivia's face, and Sorin took some amount of pleasure in that. "I created her to be this world's protector." Olivia clicked her tongue as Sorin sniffed at the blood in the glass before setting it back on the table. "A protector," she mocked. "You dare come to my house and disturb my guests with this absurdity?" It was her turn to rise from her chair. "We haven't spoken since your treachery—since you shamed your grandfather's noble name. The fact that you sit here across from me at my own table is a shame that I will have to bear. But if you think I will tolerate your attempt at playing hero—" "Are you finished?" Sorin interrupted. He wasn't here to justify himself. Not to her. But he was here to explain some things. "It is indeed true that our gift of longevity is too often paired with shortsightedness, but there are people who are greater threats than our overzealous grazing." Olivia drained the remaining blood from her glass. "One of these people," Sorin continued, "has come here, and she threatens our entire world. I can't allow that." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Sorin lifted his gaze to where Nahiri loomed over him from the height of her granite pillar. All around them and between them, a field of stones floated in the air, defying gravity in favor of a more powerful master. They were an obedient army waiting for her command. Even as the wind whipped through Sorin's hair and tugged at the leather of his long coat, the myriad stones hung motionless in the air, and it seemed to Sorin as though the entire plane was holding its breath. There was no doubting the power that Nahiri now wielded, the power that had matured with her. Stone did not simply obey her command. It was part of her, and through it, she could reach across all of Innistrad and leave his plane in ruins.] #emph[The only stone that remained beyond Nahiri's influence seemed to be the Helvault, so Sorin had put his back to it to keep from being assailed from all sides. If he had been at full strength, he would have made short work of this whelp. But his energy was still spent, and as he leaned on his sword to keep from collapsing, he cursed himself.] #emph[With a sound like snapping bones, Sorin watched as Nahiri's pillar rumbled into motion, carrying the lithomancer slowly toward him. The stones parted before her, and as she passed an elongated slab, she plunged her hand into it as easily as reaching into a pond. After a moment, the whole stone grew red, and then shattered into a million pieces until all that remained was a fully formed sword in Nahiri's grasp. The blade still glowed, fresh from its stone-forge, and Sorin found himself facing off against its white-hot point.] #figure(image("007_Promises Old and New/07.jpg", width: 100%), caption: [Art by UDON], supplement: none, numbering: none) #emph["Sorin," Nahiri said in a voice that carried through all the stones so that it seemed to come from everywhere at once, "you will fulfill your promise. You will return with me to Zendikar. You will help me check our containment measures, and ensure that the Eldrazi are secure. Only then can you slink away."] #emph[Sorin spat.] #emph[Then he felt it.] #emph[His eyes tracked up past Nahiri's sword and the end it promised, to the dark cloudscape that churned above them. He did feel it, and as he watched, a spear of light punched through the gray. The clouds retreated, and a silvery comet tore through the gap.] #emph[Avacyn. His Avacyn. She had come to protect Innistrad from a planar threat—just as he had made her to do.] #emph[At first, Nahiri didn't seem to notice. And when she did, it was only with enough time to meet the archangel who came barreling into her with enough force to carry both figures off the stone column. Sorin watched as they tore a deep gouge in the earth where they fell. And with them, the countless suspended stones clattered back to the ground.] #emph[When at last the two figures stopped tumbling, it was Avacyn who recovered first. She raised her spear, and light bloomed along its twin points, growing in intensity until it became almost too bright to behold.] #figure(image("007_Promises Old and New/08.jpg", width: 100%), caption: [Avacyn, Angel of Hope | Art by Jason Chan], supplement: none, numbering: none) #emph[Sorin strained against the brilliance. He watched as Nahiri was swallowed up in the earth, just as the archangel drove her spear through empty space. As the points bit into the exposed bedrock, the surface burst in spray of broken stone and dust, and Avacyn was forced to protect her face with her arms.] #emph[From where he stood, it took Sorin a moment to realize what was happening, but through the dust he saw Nahiri raining down blows with her still-glowing sword. The blade cut through the air, leaving trails of orange light as it went. Sparks leapt off of Avacyn's spear as she deflected the onslaught. But the blows were too many, and too fierce. Soon, Avacyn was in retreat. She tried to fly, but Nahiri rose up above her on another column of stone, forcing the archangel back to the ground with her unrelenting attack.] #emph[Nahiri would destroy Avacyn. The thought welled in Sorin more like a glimpse of reality than one possibility among many. No! Creating Avacyn had taken too much out of Sorin to let Nahiri end her here.] #emph[With what strength he could find, he threw himself forward. "Enough!" he rasped, and when Nahiri's sword arced down again, it clanged against Sorin's own weapon. "Enough," he said again. For a moment, the two Planeswalkers remained face to face, with blade pressing against blade. Sorin studied her. Her eyes were fixed on Avacyn, and in those eyes Sorin recognized confusion.] #emph["What is this, Sorin?" Nahiri said through clenched teeth. "How did you bring an angel under your thrall? Who is she?] #emph["The other half," Sorin replied. He lashed out with his off hand to grab Nahiri's sword. The hot blade hissed as his fingers closed around its sharpness, and as Nahiri struggled to free it, Sorin brought the point of his blade up to her throat. Streaks of sweat had cut through the mud that clung to her skin, and her features had taken on a severe quality. Or perhaps it was just defeat. Nahiri released her grip on her hilt, and Sorin tossed the blade aside.] #emph[Behind him, Sorin felt Avacyn approach, and he held up a hand to stay her spear. Then, to his former protégé, he said, "For what it's worth, I never wanted this, young one."] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Sorin?" Olivia said. Hearing his name only made Sorin aware of the silence that had swelled to fill the room in the long moments since he had last spoken. "Sorin," Olivia said again. "Who is this threat? Or rather, what did you do?" "Too much. Not enough," he said, staring down the length of the black banquet table. His mind was still replaying the events that had played out centuries ago. "Come now, Sorin. You can't decide to become cryptic at the best part." Sorin turned to her, but said nothing, even as that smirk of hers found its way back onto her face. "I must admit that you have piqued my interest. Anything that can get under your skin is most captivating. But you came to me, Sorin. So tell me, what I can do for you?" In an instant, the fog of the past evaporated. "Summon the might of your bloodline, Olivia. The remnants of the Markovs are already mustering. Together, our combined host can confront this threat." "Why should I? Why I shouldn't I throw in with this...threat? Illuminate me, how do I benefit from—" She stopped mid-sentence, and suddenly broke into a laugh that seemed at odds with her melodious voice. Her eyes flashed with a frenzied glee that Sorin recognized as a look meant for prey. "Oh, Sorin," she said as regained her composure. "I will help you. But first you will help me."
https://github.com/HiiGHoVuTi/requin
https://raw.githubusercontent.com/HiiGHoVuTi/requin/main/graph/col_arr.typ
typst
#import "../lib.typ" : * #show heading: heading_fct Soit $G = (V,E)$ un graphe, on dit que $x : E --> {1,2,...,k}$ est une _$k$-coloration des aretes_ si pour tout $ (x,y),(y,z) in E$, on a $c(x,y) != c(y,z)$. On note $Delta(G) = max_(v in V) deg v$ #question(0)[ Donner un graphe à plus de 3 sommets tel que $chi'(G) = Delta(G)$ et un autre tel que $chi'(G) = Delta(G)+1$ ] #question(1)[ Montrer que $chi'(G)>= Delta(G)$ ] Soit $G$ un graphe et $c$ une $k$-coloration de $G$. Pour deux couleurs $alpha$ et $beta$ et un sommet $x in V$, on note $x : alpha\/beta$ le plus long chemin commençant en $x$ et alternant en couleur entre $alpha$ et $beta$. On dit qu’un sommet $x$ _utilise_ une couleur $c$ si $c$ est la colorisation d’une des arêtes connectées à $x$. #question(1)[ Montrer que pour $x in V$ un nœud et $alpha$, $beta$ deux couleurs, $x : alpha\/beta$ est unique. ] === Le théorème de Vizing On souhaite montrer le *théorème de Vizing* : que pour tout graphe, $chi'(G) in {Delta(G), Delta(G)+1}$ #question(1)[ Montrer que pour tout graphe à moins de $4$ aretes, $chi'(G) in {Delta(G), Delta(G)+1}$ ] On démontre par récurrence sur le nombre d'arete que pour tout graphe $G = (N, E)$ on a $chi'(G) <= Delta(G) + 1$. On fait l'hérédité, soit $G$ un graphe à $n+1$ aretes. On pose $G' = (V,E')$ le graphe $G$ ou on retire une arete $(a,b) in E$, et $c$ une $Delta(G')+1$ coloration. On considère $alpha$ une couleur non utillisé par le sommet $a$ et $beta$ une couleur non utillisé par le sommet $b$. #question(3)[ Montrer que si $b$ n’est pas dans le chemin $a: alpha \/ beta$ (dans $G'$) alors $G$ est $Delta(G) + 1$ coloriable. ] #question(4)[ Montrer que si $b$ est dans le chemin $a: alpha \/ beta$ (dans $G'$) alors $G$ est $Delta(G) + 1$ coloriable. En déduire le théorème. ] === Cas particulier On dit qu'un graphe est de _classe 1_ si $chi'(G) = Delta(G)$ et de _classe 2_ sinon. #question(0)[ Montrer que le cycle à $n$ sommets est de classe $1$ ssi $n$ est pair. ] #question(1)[ Montrer que les graphe grilles $(V,E)$ avec $V = {(a,b) : a<= x : b <= y }$ et $E = {((a,b),(a+1,b)) : a< x : b <= y } union {((a,b),(a,b+1)) : a<= x : b < y }$ sont de classe 1. ] #question(1)[ Montrer que $chi' (G) = 1$ ssi $G$ est un couplage. ] #question(3)[ Montrer que les graphes biparti sont de classe 1. ] #correct[ (pas une correction, seulement l'idée) Par récurrence sur $Delta(G)$ : on choisi tout un sommet de degrée $Delta(G)$ et on colorie avec une couleur un de ses segment. On fait ça pour chaque sommet de degré $Delta(G)$ (itérativement et tant qu'il en reste, en effet une fois colorié cela peut faire baisser le degrée d'une autre arete). Une situation pose problème : si on est un sommet de degrée $Delta(G)$ qui est relié que à des sommet déjà traité. Dans ce cas, on prend un de sommets, et à la manière des chemins alternant, inverse les sommets coloré / non coloré. Ce processus marche car le grapeh est bi-parti et que les cycle sont forcément de taille pair. ] // TODO(Coda): NP complétude
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z016.typ
typst
Vypočuj, Pane, moju spravodlivú žiadosť, \* všimni si moju prosbu pokornú. Nakloň sluch k mojej modlitbe, \* čo plynie z perí úprimných. Nech z tvojej tváre vyjde rozsudok o mne; \* tvoje oči vidia, čo je správne. Skúmaj moje srdce i v noci ma navštív, \* skúšaj ma ohňom a nenájdeš vo mne neprávosť. Moje ústa nehrešia, ako robia ľudia zvyčajne. \* Podľa slov tvojich perí vyhýbam sa cestám násilníkov. Pevne drž moje kroky na svojich chodníkoch, \* aby moje nohy nezakolísali. K tebe, Bože, volám, lebo ty ma vyslyšíš. \* Nakloň ku mne sluch a vypočuj moje slová. Ukáž svoje predivné milosrdenstvo, \* ty, čo pred protivníkmi pravicou zachraňuješ dôverujúcich v teba. Chráň ma ako zrenicu oka, skry ma v tôni svojich perutí \* pred bezbožnými, čo ma sužujú. Obkľučujú ma nepriatelia, \* zatvárajú si bezcitné srdcia, ich ústa spupne hovoria. Už pristupujú a už ma zvierajú, \* očami sliedia, ako by ma na zem zrazili. Sú ako lev pripravený na korisť, \* ako levíča, čo čupí v úkryte. Povstaň, Pane, predíď ich a zraz, \* svojím mečom mi zachráň život pred bezbožným, svojou rukou pred smrteľníkmi, Pane, \* pred smrteľníkmi, ktorým sa podiel života končí na zemi. Zo svojich zásob im naplň žalúdok, \* nech sa nasýtia ich synovia a čo nezjedia, nech prenechajú svojim deťom. Ja však v spravodlivosti uzriem tvoju tvár \* a až raz vstanem zo sna, nasýtim sa pohľadom na teba.
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/02-measure-theory/03-measure-cont.typ
typst
#import "../../utils/core.typ": * == Продолжение меры #def(label: "def-submeasure")[ $nu: 2^X --> [0; +oo]$ --- _субмера_, если: 1. $nu nothing = 0$ 2. Если $A subset B$, то $nu A <= nu B$ (монотонность). 3. $nu(Union_(n=1)^oo A_n) <= sum_(n=1)^oo nu A_n$ (счетная полуаддитивность). ] #def(label: "def-complete-measure")[ $mu$ -- мера на $Aa$, тогда $mu$ --- полная, если $forall A in Aa$ и $forall B subset A$ и $mu A = 0$, то $B in Aa$. ] #notice[$mu B = 0$.] #def(label: "def-measurable")[ $nu$ --- субмера. Множество $E$ --- $nu$-измеримое, если $forall A$ $ nu A = nu(A sect E) + nu(A without E) $ ] #notice(label: "def-measurable'")[ Достаточно неравенства $nu A >= nu (A sect E) + nu (A without E)$. ] #notice(label: "measurable-union")[ Если $E_1, E_2, ..., E_n$ --- $nu$-измеримые, то $nu (A sect usb_(k = 1)^n E_k) = sum_(k = 1)^n nu(A sect E_k)$. ] #proof[ $ nu(A sect usb_(k = 1)^n E_k) = nu(usb_(k = 1)^n (A sect E_k)) = nu underbrace((usb_(k = 1)^n (A sect E_k) without E_n), usb_(k = 1)^(n - 1) A sect E_k) + nu underbrace((usb_(k = 1)^n (A sect E_k) sect E_n), A sect E_n). $ ] #th(name: "Каратеодори", label: "caratheodory")[ Если $nu$ --- субмера#rf("def-submeasure"), то $nu$-измеримые#rf("def-measurable") множества образуют $sigma$-алгебру#rf("def-salgebra") $Aa$ и сужение $nu$ на $Aa$ --- полная мера#rf("def-complete-measure"). ] #proof[ Положим $Aa = {A | A "является" nu"-измеримым"}$. 1. Если $nu E = 0$, то $E in Aa$: $ nu(underbrace(A sect E, subset E)) + nu(underbrace(A without E, subset A)) <= nu E + nu A = nu A. $ 2. $Aa$ --- симметричная структура#rf("def-symm-system"). $A sect E = A without (X without E)$, $A without E = A sect (X without E)$. Значит, взяв дополнение от множества, мы останемся в структуре. 3. Докажем, что если $E$ и $F in Aa$, то $E union F in Aa$. Рассмотрим произвольное $A$: $ nu A =^rf("def-measurable") nu(A sect E) + nu(A without E) &= nu(A sect E) + nu((A without E) sect F) + nu(underbrace((A without E) without F, A without (E union F))) >=\ &>= nu(A sect (E union F)) + nu(A without (E union F)). $ Значит по замечанию#rf("def-measurable'"), $E union F$ $nu$-измеримы. 4. Итого, это алгебра#rf("def-algebra"). Докажем, что это $sigma$-алгебра: 5. Докажем, что если $E_1, E_2, ... in Aa$, то $usb_(n=1)^oo E_n in Aa$. $E := usb_(n=1)^oo E_n$. Для произвольного $A$: $ nu A =^rf("def-measurable") nu(A sect usb_(k=1)^n E_k) + nu(A without usb_(k=1)^n E_k) = sum_(k=1)^n nu(A sect E_k) + nu(A without usb_(k=1)^n E_k) >= \ >= sum_(k=1)^n nu(A sect E_k) + nu(A without E) --> sum_(k=1)^oo nu(A sect E_k) + nu(A without E) >=_(#[счетная \ полуадд.])^rf("def-measurable") nu(A sect E) + nu(A without E). $ 6. В определении#rf("def-salgebra") $sigma$-алгебры надо доказать для любого объединения, а не только для дизъюнктного. Но мы знаем, что в полукольце любое объединение можно переделать в дизъюнктное#rf("semiring-disjoint-union"). Значит $Aa$ --- $sigma$-алгебра. 7. Остается доказать, что сужение $nu$ на $Aa$ --- это мера. Подставим $A = X$ в замечание 2#rf("measurable-union") и получим, что $nu$ --- это объем#rf("def-measure", "volume") на $Aa$. Объем и счетная полуаддитивность#rf("measure-semiadditive") --- мера. ] #def(label: "def-external-measure")[ Пусть $mu$ --- мера на полукольце $Pp$. _Внешняя мера (порожденная $mu$)_ $mu^*$: $ mu^* A := inf { sum_(k = 1)^oo mu P_k : P_k in Pp and A subset Union_(k = 1)^oo P_k }. $ Если такого покрытия не существует, считаем $mu^* A = +oo$. ] #notice[ Можно рассматривать только дизъюнктные наборы $P_k$, так как $ Union_(n = 1)^oo P_n =^rf("semiring-disjoint-union") usb_(n = 1)^oo usb_(k = 1)^m_n Q_(n k), $ где $Q_(n k) subset P_n$, то есть $usb_(k = 1)^m_n Q_(n k) subset P_n$. Тогда $ sum_(k = 1)^(m_n) mu Q_(n k) <= mu P_n ==> sum_(n = 1)^oo sum_(k = 1)^(m_n) mu Q_(n k) <= sum_(n = 1)^oo mu P_n. $ ] #notice[ Если $Pp$ --- $sigma$-алгебра#rf("def-salgebra"), то $mu^* A = inf{mu B: B in Pp and A subset B}$. ] #th(label: "ext-measure-is-submeasure")[ Пусть $mu$ --- мера на полукольце $Pp$. Тогда $mu^*$ --- субмера, совпадающая с $mu$ на полукольце. ] #proof[ 1. Поймем, что $mu$ и $mu^*$ совпадают на $Pp$. Пусть $A in Pp$, $P_1 = A$, $P_2 = P_3 = ... = nothing$, тогда $mu^* A <= mu A$, так как $ sum_(k=1)^oo mu P_k >=_(#[счетная \ полуадд.])^rf("measure-semiadditive") mu A ==> mu^* A >= mu A $ 2. Покажем, что $mu^*$ --- субмера#rf("def-submeasure"). Надо доказать 3 свойства: - $mu^* nothing = 0$. - $#[Если] A subset B, #[то] mu^* A <= mu^* B$. - Счетная полуаддитивность: $A = Union_(n=1)^oo A_n ==> mu^* A <= sum_(n=1)^oo mu^* A_n$. Первое свойство очевидно. Второе верно, так как любое покрытие $B$ будет и покрытием $A$. Доказательство счетной полуаддитивности: рассмотрим $A_n$ и возьмем такие $P_(n k)$, что $A_n subset Union_(k = 1)^oo P_(n k)$ и $sum_(k = 1)^oo mu P_(n k) < mu^* A_n + eps / 2^n$. Пусть $A = Union_(n = 1)^oo A_n subset Union_(n = 1)^oo Union_(k = 1)^oo P_(n k)$. Тогда $ mu^* A <= sum_(n = 1)^oo underbrace(sum_(k = 1)^oo mu P_(n k), < mu^* A_n + eps / 2^n) < sum_(n = 1)^oo (mu^* A_n + eps / 2^n) = sum_(n = 1)^oo mu^* A_n + eps. $ Устремив $eps$ к 0, получим требуемое. ] #def(label: "def-standard-continuation")[ Пусть $mu_0$ --- мера на полукольце $Pp$. _Стандартное продолжение_ $mu_0^*$ --- внешняя мера, порожденная $mu_0$ и суженная на $sigma$-алгебру $mu_0^*$-измеримых множеств. Получается полная мера на некоторой $sigma$-алгебре. ] #th(label: "standard-continuation-correctness")[ Это действительно продолжение. То есть элементы из полукольца $Pp$ будут $mu^*$-измеримыми. (здесь $mu^*$ --- это $mu_0^*$ из определения) ] #proof[ Надо доказать, что если $E in Pp$, то $forall A space mu^* A >= mu^* (A sect E) + mu^*(A without E)$#rf("def-measurable'"). Рассмотрим случаи. 1. $A in Pp$, тогда $A without E = usb_(k=1)^n Q_k ==> A = (A sect E) union.sq usb_(k=1)^n Q_k$. $ mu^* A = mu A = underbrace(mu(A sect E), mu^* (A sect E)) + underbrace(sum_(k=1)^n mu Q_k, >= mu^* (A without E)) >= mu^* (A sect E) + mu^*(A without E). $ 2. $A in.not Pp$. Eсли $mu^* A = +oo$, то очевидно, поэтому считаем, что конечно. Берем покрытие $A subset Union_(k=1)^oo P_k, space P_k in Pp$ и $sum_(k=1)^oo mu P_k < mu^* A + epsilon$. Знаем, что $mu P_k >= mu^* (P_k sect E) + mu^*(P_k without E)$#rf("def-measurable'") (уже в полукольце), поэтому $ epsilon + mu^* A > sum_(k=1)^oo mu P_k >= sum_(k=1)^oo mu^*(P_k sect E) + sum_(k=1)^oo mu^* (P_k without E) >=^rf("measure-semiadditive") \ >=^rf("measure-semiadditive") mu^* (Union_(k=1)^oo (P_k sect E)) + mu^* (Union_(k=1)^oo (P_k without E)) >= mu^*(A sect E) + mu^* (A without E) $ ] #notice[Далее мы не будем разделять "меру" и "продолжение меры".] #notice[$mu A = inf {sum_(k = 1)^oo mu P_k : P_k in Pp and A subset Union_(k = 1)^oo P_k}$.] #notice[Если применить стандартное продолжение к стандартному продолжению, не получится ничего нового.] #exercise[Доказать. _Указание: пусть $mu_0$ --- исходная мера, $mu$ --- стандартное продолжение. Доказать, что $mu_0^* = mu^*$._] #notice[Можно ли продолжить на более широкую $sigma$-алгебру? Можно, но непонятно зачем.] #def(label: "def-sfinite")[ $mu$ --- мера на $Pp$. $mu$ --- _$sigma$-конечная_ мера, если существуют $P_k in Pp:$ $mu P_k < +oo$ и $X = Union_(k=1)^oo P_k$ ] #notice[Можно ли по-другому продолжить $mu$ на $sigma$-алгебру $mu^*$-измеримых множеств? Если $mu$ --- $sigma$-конечная, то нет. Доказательство далее.] #notice[Обязательно ли полная мера должна быть задана на $sigma$-алгебре $mu^*$-измеримых множеств? Если исходная $mu$ --- $sigma$-конечная мера, то да. Доказательство сложное.] #th(label: "external-measure-through-semiring")[ Пусть $mu^*$ --- внешняя мера#rf("def-external-measure"), порожденная мерой $mu$, заданной на полукольце $Pp$. Если $mu^* A < +oo$, то существуют $ B_(n k) in Pp: C_n := Union_(k=1)^oo B_(n k) space #[и] space C := sect.big_(n=1)^oo C_n, space A subset C and mu^* A = mu C $ ] #proof[ По определению#rf("def-external-measure"), $ mu^* A = inf{sum_(k=1)^oo mu P_k: P_k in P space and space A subset Union_(k=1)^oo P_k}. $ Возьмем такие $B_(n k)$, что $B_(n k) in Pp, A subset Union_(k=1)^oo B_(n k)$ и $ mu^* A + 1/n >sum_(k=1)^oo mu B_(n k) >= mu C_n >= mu C = mu^* C >= mu^* A, $ где $C_n supset A ==> C_n supset C supset A$ и $mu^* A <= mu C < mu^* A + 1/n ==> mu^* A = mu C$. ] #follow(label: "measurable-is-borel-plus-zero")[ $mu$ --- стандартное продолжение#rf("def-standard-continuation") с полукольца $Pp$. Пусть $A$ --- измеримо#rf("def-measurable") относительно $mu$ и $mu A < +oo$. Тогда $A = B union.sq e$, где $B in Bb(Pp)$#rf("borel-set") и $mu e = 0$. ] #proof[ Возьмем $C$ из теоремы#rf("external-measure-through-semiring"), $C in Bb(Pp)$. $mu(C without A) = mu C - mu A = 0$. Применим теорему#rf("external-measure-through-semiring") еще раз, к множеству $C without A$. Найдется $e_1 supset C without A$, такое что $e_1 in Bb(Pp)$ и $mu e_1 = mu(C without A) = 0$. Рассмотрим $B := C without e_1 in Bb(Pp)$. Тогда $B subset A$. Рассмотрим $e = A without B$. Это то что надо: $e subset C without B subset e_1$. Тогда $mu e <= mu e_1 = 0$. Значит $mu e = 0$. ] /* #proof[ $A_n = A sect P_n$. $ mu A_n <= mu P_n < +oo ==> A_n = B_n union.sq e_n = usb B_n union.sq usb e_n. $ ] */ #th(name: "единственность продолжения", label: "standard-continuation-unique")[ Пусть $mu$ --- стандартное продолжение#rf("def-standard-continuation") меры на $sigma$-алгебру $Aa$ с полукольца $Pp$, $mu$ --- $sigma$-конечная#rf("def-sfinite") мера. А $nu$ --- другая мера на $Aa$, совпадающая с $mu$ на $Pp$. Тогда $mu A = nu A space forall A in Aa$. ] #proof[ Пусть $A in Aa$ и $A subset Union_(n = 1)^oo A_n$, где $A_n in Pp$. $ nu A <= sum_(k=1)^oo nu A_k =^"совпадение\nна полукольце" sum_(k=1)^oo mu A_k ==>\ ==> nu A <= inf{sum_(n=1)^oo mu A_n: A_n in Pp and A subset Union A_n} =^rf("def-external-measure") mu A ==> nu A <= mu A. $ Возьмем $P in Pp$. Из написанного выше, справедливы следующие неравенства: - $nu(P sect A) + nu(P without A) = nu P = mu P = mu(P sect A) + mu(P without A)$ - $nu(P sect A) <= mu(P sect A)$ - $nu(P without A) <= mu(P without A)$ Если $mu P < +oo$, то тут равенства. Тогда получается, что $ nu(P sect A) = mu(P sect A) space forall P in Pp: mu P < +oo. $ $mu$ --- $sigma$-конечная#rf("def-sfinite"), поэтому $X = usb_(n=1)^oo P_n: P_n in Pp$ и $mu P_n < +oo$. Имеем, $ A = A sect X = usb_(n=1)^oo A sect P_n. $ И воспользовавшись выведенным равенством выше, $ mu(A sect P_n) = nu(A sect P_n) ==> underbrace(sum_(n=1)^oo mu(A sect P_n), mu A) = underbrace(sum_(n=1)^oo nu(A sect P_n), nu A) ==> mu A = nu A. $ ]
https://github.com/catg-umag/inach-workshop-2024
https://raw.githubusercontent.com/catg-umag/inach-workshop-2024/main/document/catgconf.typ
typst
#import "@preview/octique:0.1.0": * #let catg-colors = ( red: rgb("ee273f"), blue: rgb("1889c6"), green: rgb("0aa55b"), yellow: rgb("f8a216"), ) #let conf( title: none, authors: (), date: "", doc, ) = { set document( title: title, author: authors, ) set text(font: "Lato", lang: "es", size: 10pt) set par(justify: true) show raw: set text(font: ("Hack", "mono")) set page( paper: "us-letter", margin: (top: 2cm, right: 2cm, bottom: 2cm, left: 2cm), numbering: "1 of 1", footer-descent: 20%, header: { context { if (counter(page).get().first() <= 2) { [] } else { set text(fill: gray, size: 0.9em) grid( columns: (1fr, 1fr), align: (left, right), title, [ #emph(authors.join(" & ")) #if (date != "") { [| #emph(date)] } ], ) } } }, footer: context { if (counter(page).get().first() <= 2) { [] } else { set text(fill: gray, size: 0.9em) align( right, stack( dir: ltr, rect(fill: catg-colors.red, width: 2.5cm, height: 0.15cm), rect(fill: catg-colors.blue, width: 2.5cm, height: 0.15cm), rect(fill: catg-colors.green, width: 2.5cm, height: 0.15cm), rect(fill: catg-colors.yellow, width: 2.5cm, height: 0.15cm), ), ) align(center, counter(page).display("1 / 1", both: true)) } }, ) // Heading set heading(numbering: "1.1 ") show heading: it => { set text( size: if it.level == 1 { 1em } else { 0.9em }, weight: "regular", fill: catg-colors.blue, ) block( above: 1.5em, inset: (bottom: 0.3em), [ #if (it.numbering != none) [ #counter(heading).display(it.numbering) | #h(0.3em) ] #it.body ], ) } // Caption show figure.caption: c => [ #set text(size: 0.9em) #text(weight: "bold")[ #c.supplement.text #c.counter.display(c.numbering). ] #c.body ] // Table show table.cell: set text(size: 0.9em) show table.cell.where(y: 0): set text(fill: white) let frame(stroke) = ( (x, y) => ( left: if x == 0 { stroke } else { 0pt }, right: stroke, top: if y < 2 { stroke } else { 0pt }, bottom: stroke, ) ) set table( stroke: frame(rgb("#418dc0") + 0.7pt), fill: (_, y) => if y == 0 { rgb("#418dc0") }, ) show link: set text(fill: rgb("#144e6e")) show figure: set block(spacing: 1.5em) doc } #let cmd(content) = { show: box.with( fill: rgb("#ebf3f4"), inset: (x: 3pt), outset: (y: 3pt), radius: 2pt, ) content } #let pill(content, fill: gray) = { set text(weight: "regular", size: 8pt) show: box.with(fill: fill, inset: (x: 0.4em, y: 0.3em), outset: 1pt, radius: 4pt) content } #let github-pill(repo) = { set text(fill: white) show link: this => text(this, fill: white) pill( link("https://github.com/" + repo)[ #grid( columns: 2, column-gutter: 5pt, align: horizon, octique("mark-github", color: white, width: 0.85em), repo, ) ], fill: rgb("#687fa8"), ) } #let doi-pill(doi) = { set text(fill: white) show link: this => text(this, fill: white) pill( link("https://doi.org/" + doi)[ #grid( columns: 2, column-gutter: 5pt, align: horizon, octique("log", color: white, width: 0.85em), doi, ) ], fill: rgb("#9d6dc5"), ) }
https://github.com/8LWXpg/typst-ansi-render
https://raw.githubusercontent.com/8LWXpg/typst-ansi-render/master/ansi-render.typ
typst
MIT License
// add your theme here! #let terminal-themes = ( // vscode terminal theme vscode: ( black: rgb("#000000"), red: rgb("#CD3131"), green: rgb("#0DBC79"), yellow: rgb("#E5E510"), blue: rgb("#2472C8"), magenta: rgb("#BC3FBC"), cyan: rgb("#11A8CD"), white: rgb("#E5E5E5"), gray: rgb("#666666"), bright-red: rgb("#D64C4C"), bright-green: rgb("#23D18B"), bright-yellow: rgb("#F5F543"), bright-blue: rgb("#3B8EEA"), bright-magenta: rgb("#D670D6"), bright-cyan: rgb("#29B8DB"), bright-white: rgb("#E5E5E5"), default-fg: rgb("#E5E5E5"), // white default-bg: rgb("#000000"), // black ), // vscode light theme vscode-light: ( black: rgb("#F8F8F8"), red: rgb("#CD3131"), green: rgb("#00BC00"), yellow: rgb("#949800"), blue: rgb("#0451A5"), magenta: rgb("#BC05BC"), cyan: rgb("#0598BC"), white: rgb("#555555"), gray: rgb("#666666"), bright-red: rgb("#CD3131"), bright-green: rgb("#14CE14"), bright-yellow: rgb("#B5BA00"), bright-blue: rgb("#0451A5"), bright-magenta: rgb("#BC05BC"), bright-cyan: rgb("#0598BC"), bright-white: rgb("#A5A5A5"), default-fg: rgb("#A5A5A5"), // white default-bg: rgb("#F8F8F8"), // black ), // putty terminal theme putty: ( black: rgb("#000000"), red: rgb("#BB0000"), green: rgb("#00BB00"), yellow: rgb("#BBBB00"), blue: rgb("#0000BB"), magenta: rgb("#BB00BB"), cyan: rgb("#00BBBB"), white: rgb("#BBBBBB"), gray: rgb("#555555"), bright-red: rgb("#FF0000"), bright-green: rgb("#00FF00"), bright-yellow: rgb("#FFFF00"), bright-blue: rgb("#0000FF"), bright-magenta: rgb("#FF00FF"), bright-cyan: rgb("#00FFFF"), bright-white: rgb("#FFFFFF"), default-fg: rgb("#BBBBBB"), // white default-bg: rgb("#000000"), // black ), // themes from Windows Terminal campbell: ( black: rgb("#0C0C0C"), red: rgb("#C50F1F"), green: rgb("#13A10E"), yellow: rgb("#C19C00"), blue: rgb("#0037DA"), magenta: rgb("#881798"), cyan: rgb("#3A96DD"), white: rgb("#CCCCCC"), gray: rgb("#767676"), bright-red: rgb("#E74856"), bright-green: rgb("#16C60C"), bright-yellow: rgb("#F9F1A5"), bright-blue: rgb("#3B78FF"), bright-magenta: rgb("#B4009E"), bright-cyan: rgb("#61D6D6"), bright-white: rgb("#F2F2F2"), default-fg: rgb("#CCCCCC"), default-bg: rgb("#0C0C0C"), ), campbell-powershell: ( black: rgb("#0C0C0C"), red: rgb("#C50F1F"), green: rgb("#13A10E"), yellow: rgb("#C19C00"), blue: rgb("#0037DA"), magenta: rgb("#881798"), cyan: rgb("#3A96DD"), white: rgb("#CCCCCC"), gray: rgb("#767676"), bright-red: rgb("#E74856"), bright-green: rgb("#16C60C"), bright-yellow: rgb("#F9F1A5"), bright-blue: rgb("#3B78FF"), bright-magenta: rgb("#B4009E"), bright-cyan: rgb("#61D6D6"), bright-white: rgb("#F2F2F2"), default-fg: rgb("#CCCCCC"), default-bg: rgb("#012456"), ), vintage: ( black: rgb("#000000"), red: rgb("#800000"), green: rgb("#008000"), yellow: rgb("#808000"), blue: rgb("#000080"), magenta: rgb("#800080"), cyan: rgb("#008080"), white: rgb("#C0C0C0"), gray: rgb("#808080"), bright-red: rgb("#FF0000"), bright-green: rgb("#00FF00"), bright-yellow: rgb("#FFFF00"), bright-blue: rgb("#0000FF"), bright-magenta: rgb("#FF00FF"), bright-cyan: rgb("#00FFFF"), bright-white: rgb("#FFFFFF"), default-fg: rgb("#C0C0C0"), default-bg: rgb("#000000"), ), one-half-dark: ( black: rgb("#282C34"), red: rgb("#E06C75"), green: rgb("#98C379"), yellow: rgb("#E5C07B"), blue: rgb("#61AFEF"), magenta: rgb("#C678DD"), cyan: rgb("#56B6C2"), white: rgb("#DCDFE4"), gray: rgb("#5A6374"), bright-red: rgb("#E06C75"), bright-green: rgb("#98C379"), bright-yellow: rgb("#E5C07B"), bright-blue: rgb("#61AFEF"), bright-magenta: rgb("#C678DD"), bright-cyan: rgb("#56B6C2"), bright-white: rgb("#DCDFE4"), default-fg: rgb("#DCDFE4"), default-bg: rgb("#282C34"), ), one-half-light: ( black: rgb("#383A42"), red: rgb("#E45649"), green: rgb("#50A14F"), yellow: rgb("#C18301"), blue: rgb("#0184BC"), magenta: rgb("#A626A4"), cyan: rgb("#0997B3"), white: rgb("#FAFAFA"), gray: rgb("#4F525D"), bright-red: rgb("#DF6C75"), bright-green: rgb("#98C379"), bright-yellow: rgb("#E4C07A"), bright-blue: rgb("#61AFEF"), bright-magenta: rgb("#C577DD"), bright-cyan: rgb("#56B5C1"), bright-white: rgb("#FFFFFF"), default-fg: rgb("#383A42"), default-bg: rgb("#FAFAFA"), ), solarized-dark: ( black: rgb("#002B36"), red: rgb("#DC322F"), green: rgb("#859900"), yellow: rgb("#B58900"), blue: rgb("#268BD2"), magenta: rgb("#D33682"), cyan: rgb("#2AA198"), white: rgb("#EEE8D5"), gray: rgb("#073642"), bright-red: rgb("#CB4B16"), bright-green: rgb("#586E75"), bright-yellow: rgb("#657B83"), bright-blue: rgb("#839496"), bright-magenta: rgb("#6C71C4"), bright-cyan: rgb("#93A1A1"), bright-white: rgb("#FDF6E3"), default-fg: rgb("#839496"), default-bg: rgb("#002B36"), ), solarized-light: ( black: rgb("#002B36"), red: rgb("#DC322F"), green: rgb("#859900"), yellow: rgb("#B58900"), blue: rgb("#268BD2"), magenta: rgb("#D33682"), cyan: rgb("#2AA198"), white: rgb("#EEE8D5"), gray: rgb("#073642"), bright-red: rgb("#CB4B16"), bright-green: rgb("#586E75"), bright-yellow: rgb("#657B83"), bright-blue: rgb("#839496"), bright-magenta: rgb("#6C71C4"), bright-cyan: rgb("#93A1A1"), bright-white: rgb("#FDF6E3"), default-fg: rgb("#657B83"), default-bg: rgb("#FDF6E3"), ), tango-dark: ( black: rgb("#000000"), red: rgb("#CC0000"), green: rgb("#4E9A06"), yellow: rgb("#C4A000"), blue: rgb("#3465A4"), magenta: rgb("#75507B"), cyan: rgb("#06989A"), white: rgb("#D3D7CF"), gray: rgb("#555753"), bright-red: rgb("#EF2929"), bright-green: rgb("#8AE234"), bright-yellow: rgb("#FCE94F"), bright-blue: rgb("#729FCF"), bright-magenta: rgb("#AD7FA8"), bright-cyan: rgb("#34E2E2"), bright-white: rgb("#EEEEEC"), default-fg: rgb("#D3D7CF"), default-bg: rgb("#000000"), ), tango-light: ( black: rgb("#000000"), red: rgb("#CC0000"), green: rgb("#4E9A06"), yellow: rgb("#C4A000"), blue: rgb("#3465A4"), magenta: rgb("#75507B"), cyan: rgb("#06989A"), white: rgb("#D3D7CF"), gray: rgb("#555753"), bright-red: rgb("#EF2929"), bright-green: rgb("#8AE234"), bright-yellow: rgb("#FCE94F"), bright-blue: rgb("#729FCF"), bright-magenta: rgb("#AD7FA8"), bright-cyan: rgb("#34E2E2"), bright-white: rgb("#EEEEEC"), default-fg: rgb("#555753"), default-bg: rgb("#FFFFFF"), ), gruvbox-dark: ( black: rgb("#282828"), red: rgb("#cc241d"), green: rgb("#98971a"), yellow: rgb("#d79921"), blue: rgb("#458588"), magenta: rgb("#b16286"), cyan: rgb("#689d6a"), white: rgb("#ebdbb2"), gray: rgb("#928374"), bright-red: rgb("#fb4934"), bright-green: rgb("#b8bb26"), bright-yellow: rgb("#fabd2f"), bright-blue: rgb("#83a598"), bright-magenta: rgb("#d3869b"), bright-cyan: rgb("#8ec07c"), bright-white: rgb("#ebdbb2"), default-fg: rgb("#ebdbb2"), default-bg: rgb("#282828"), ), gruvbox-light: ( black: rgb("#3c3836"), red: rgb("#cc241d"), green: rgb("#98971a"), yellow: rgb("#d79921"), blue: rgb("#458588"), magenta: rgb("#b16286"), cyan: rgb("#689d6a"), white: rgb("#fbf1c7"), gray: rgb("#7c6f64"), bright-red: rgb("#9d0006"), bright-green: rgb("#79740e"), bright-yellow: rgb("#b57614"), bright-blue: rgb("#076678"), bright-magenta: rgb("#8f3f71"), bright-cyan: rgb("#427b58"), bright-white: rgb("#fbf1c7"), default-fg: rgb("#3c3836"), default-bg: rgb("#fbf1c7"), ), ) // ansi rendering function #let ansi-render( body, font: "Cascadia Code", size: 1em, width: auto, height: auto, breakable: true, radius: 0pt, inset: 0pt, outset: 0pt, spacing: 1.2em, above: 1.2em, below: 1.2em, clip: false, bold-is-bright: false, theme: terminal-themes.vscode-light, ) = { // dict with text style let match-text = ( "1": (weight: "bold"), "3": (style: "italic"), "23": (style: "normal"), "30": (fill: theme.black), "31": (fill: theme.red), "32": (fill: theme.green), "33": (fill: theme.yellow), "34": (fill: theme.blue), "35": (fill: theme.magenta), "36": (fill: theme.cyan), "37": (fill: theme.white), "39": (fill: theme.default-fg), "90": (fill: theme.gray), "91": (fill: theme.bright-red), "92": (fill: theme.bright-green), "93": (fill: theme.bright-yellow), "94": (fill: theme.bright-blue), "95": (fill: theme.bright-magenta), "96": (fill: theme.bright-cyan), "97": (fill: theme.bright-white), "default": (weight: "regular", style: "normal", fill: theme.default-fg), ) // dict with background style let match-bg = ( "40": (fill: theme.black), "41": (fill: theme.red), "42": (fill: theme.green), "43": (fill: theme.yellow), "44": (fill: theme.blue), "45": (fill: theme.magenta), "46": (fill: theme.cyan), "47": (fill: theme.white), "49": (fill: theme.default-bg), "100": (fill: theme.gray), "101": (fill: theme.bright-red), "102": (fill: theme.bright-green), "103": (fill: theme.bright-yellow), "104": (fill: theme.bright-blue), "105": (fill: theme.bright-magenta), "106": (fill: theme.bright-cyan), "107": (fill: theme.bright-white), "default": (fill: theme.default-bg), ) // match for regex parsed options // input: array of options in string inside escape sequence // return: a dict with text and background style let match-options(opt) = { // parse 38;5 48;5 let parse-8bit-color(num) = { num = int(num) let colors = (0, 95, 135, 175, 215, 255) if num <= 7 { match-text.at(str(num + 30)) } else if num <= 15 { match-text.at(str(num + 82)) } else if num <= 231 { num -= 16 (fill: rgb( colors.at(int(num / 36)), colors.at(calc.rem(int(num / 6), 6)), colors.at(calc.rem(num, 6)), )) } else { num -= 232 (fill: rgb(8 + 10 * num, 8 + 10 * num, 8 + 10 * num)) } } let (opt-text, opt-bg) = ((:), (:)) let (ul, ol, rev, last) = (none, none, none, none) let count = 0 let color = (0, 0, 0) // match options for i in opt { if last == "382" or last == "482" { color.at(count) = int(i) count += 1 if count == 3 { if last == "382" { opt-text += (fill: rgb(..color)) } else { opt-bg += (fill: rgb(..color)) } count = 0 last = none } continue } else if last == "385" { opt-text += parse-8bit-color(i) last = none continue } else if last == "485" { opt-bg += parse-8bit-color(i) last = none continue } else if i == "0" { opt-text += match-text.default opt-bg += match-bg.default ul = false ol = false rev = false } else if i in match-bg.keys() { opt-bg += match-bg.at(i) } else if i in match-text.keys() { opt-text += match-text.at(i) } else if i == "4" { ul = true } else if i == "24" { ul = false } else if i == "53" { ol = true } else if i == "55" { ol = false } else if i == "7" { rev = true } else if i == "27" { rev = false } else if i == "38" or i == "48" { last = i continue } else if i == "2" or i == "5" { if last == "38" or last == "48" { last += i count = 0 continue } } last = none } (text: opt-text, bg: opt-bg, ul: ul, ol: ol, rev: rev) } // parse escape sequence // return: array of (str, options) // str is split by newline let parse-option(body) = { let arr = () let cur = 0 for map in body.matches(regex("\x1b\[([0-9;]*)m([^\x1b]*)")) { // loop through all matches let str = map.captures.at(1) // split the string by newline and preserve newline let split = str.split("\n") for (k, v) in split.enumerate() { if k != split.len() - 1 { v = v + "\n" } let temp = (v, ()) for option in map.captures.at(0).split(";") { temp.at(1).push(option) } arr.push(temp) } cur += 1 } arr } // prevent set from outside of the function set box( width: auto, height: auto, baseline: 0pt, fill: none, stroke: none, radius: 0pt, inset: 0pt, outset: 0pt, clip: false, ) // settings show raw: if font == none { text.with(top-edge: "ascender", bottom-edge: "descender") } else { text.with(font: font, top-edge: "ascender", bottom-edge: "descender") } set text(..(match-text.default), size: size) set par(leading: 0em) show: block.with( ..(match-bg.default), width: width, height: height, breakable: breakable, radius: radius, inset: inset, outset: outset, spacing: spacing, above: above, below: below, clip: clip, ) // current option let option = ( text: match-text.default, bg: match-bg.default, ul: false, ol: false, rev: false, ) // workaround for rendering first line without escape sequence body = "\u{1b}[0m" + body // workaround for one trailing newline consumed by raw if body.ends-with("\n") { body = body + "\n" } for (str, opt) in parse-option(body) { let m = match-options(opt) option.text += m.text option.bg += m.bg if m.rev != none { option.rev = m.rev } if option.rev { (option.text.fill, option.bg.fill) = (option.bg.fill, option.text.fill) } if option.text.weight == "bold" and bold-is-bright { option.text.fill = if option.text.fill == theme.black { theme.gray } else if option.text.fill == theme.red { theme.bright-red } else if option.text.fill == theme.green { theme.bright-green } else if option.text.fill == theme.yellow { theme.bright-yellow } else if option.text.fill == theme.blue { theme.bright-blue } else if option.text.fill == theme.magenta { theme.bright-magenta } else if option.text.fill == theme.cyan { theme.bright-cyan } else if option.text.fill == theme.white { theme.bright-white } else { option.text.fill } } if m.ul != none { option.ul = m.ul } if m.ol != none { option.ol = m.ol } // slightly reduce pdf size by removing default box fill if option.bg.fill == theme.default-bg { option.bg.fill = none } if option.text.fill == none { option.text.fill = theme.default-bg } // workaround for trailing whitespace with under/overline str = str.replace(regex("([ \t]+)$"), m => m.captures.at(0) + "\u{200b}") { show: box.with(..option.bg) set text(..option.text) show: c => if option.ul { underline(c) } else { c } show: c => if option.ol { overline(c) } else { c } raw(str) } // fill trailing newlines let s = str.find(regex("\n+$")) if s != none { linebreak() * s.len() } } }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/019%20-%20Magic%20Origins/003_Jace’s Origin: Absent Minds.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Jace’s Origin: Absent Minds", set_name: "Magic Origins", story_date: datetime(day: 24, month: 06, year: 2015), author: "<NAME>", doc ) #grid( columns: (1fr, 1fr), gutter: 2em, figure(image("003_Jace’s Origin: Absent Minds/01.png", width: 100%), caption: [], supplement: none, numbering: none), figure(image("003_Jace’s Origin: Absent Minds/02.png", width: 100%), caption: [], supplement: none, numbering: none), ) = Vryn Jace paused at the foot of the last flight of stairs. His family lived most of the way up the mage-ring the locals called Silmot’s Crossing, among the collection of apartments where the poorest mana miners on the ring made their home. He and his family had to pay to take the rickety lifts or trudge up twenty-three flights of stairs every time they returned home. Money was scarce, so Jace took the stairs. Twenty-two flights of stairs behind him. One to go. #figure(image("003_Jace’s Origin: Absent Minds/03.jpg", width: 100%), caption: [Art by Chase Stone], supplement: none, numbering: none) Now that he was this close, he hesitated. He was going to be in trouble, probably as soon as he opened the door, even though he still didn’t think he’d done anything wrong.   #emph[Lack-witted idiot.]   A big lug shoved past him from behind.   Jace couldn’t help but agree with the sentiment.   #emph[I swear, that Beleren kid] …   Jace finally reached the top of the stairs. He took a deep breath and stepped into the apartment.   Home.   Sure enough, there was his father, sitting at the kitchen table, frowning. <NAME>, grubby and balding, regarded Jace with little more than weariness.   #emph[I wish he was normal.]   His father’s thoughts traced a familiar path.   "I got a sending from school."   Jace wasn’t surprised the news had beaten him home. Illusions didn’t have to climb stairs, and he hadn’t exactly hurried. His father gestured for him to sit.   "Mind telling me what happened?"   Jace sat. He shrugged and stared at the table.   "You don’t want to be expelled, do you? Education is your ticket out of here, to a better life."   #emph[A better life than mine] . It always came back to that.   "I know," said Jace.   #emph[You don’t act like it] .   "I just need to know whether you did this. I want to hear it from you."   Jace kept staring at the table.   He’d taken a mana dynamics test full of questions he didn’t know how to begin to answer. He thought he’d studied, thought he’d been prepared, but as he stared at the test, he drew a complete blank. Then the answers just…came to him. He knew the formulas. He showed his work. He answered perfectly, and he knew it.   Thing was, he’d been right the first time—he had been prepared for the test—but they were trick questions. He wasn’t supposed to know the answers. He was supposed to get as close as he could, to show what he knew, but he knew too much.   "I don’t know," he said.   "You #emph[don’t know] ? What the hell does that mean? Did you cheat or not?"   "No," said Jace. "I just…knew the answers."   "They’re saying you solved a six-node mana-pressure equation in your #emph[head] . If that’s true, you should be supervising a regulator team, not taking lessons."   Jace shrugged again. "Maybe I should be."   Too far. His father pounded the table with a fist.   "Go to your room. We’ll talk about this when your mother gets home."   Jace stood and turned to the door.   "Where do you think you’re going?"   #emph[Why is it never easy with you?]   "Out," said Jace. And he ran, before his father could stop him.   He ran up the stairs this time, around the curve of the ring, all the way to its apex, above even the monitoring station, pressing through the crowd. Their thoughts, loud and sullen, mingled with his own. He climbed a ladder to an access hatch—one that civilians on the ring weren’t even supposed to know about—and stepped out onto the roof of the massive structure he called home.   #figure(image("003_Jace’s Origin: Absent Minds/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   He stood hundreds of feet above the valley floor on the angled, rusty plates that made up the ring’s outer shell. The wind whipped at his cloak, and he pulled his scarf up around his head. Here, far from the inhabited portions of the ring, he could think without interruption. Other peoples’ thoughts were distant echoes; he couldn’t hear anything but the whistling of the wind.   Towering above him was the hoop of the guide ring, easily forty feet across but miniscule in comparison to the ring itself. He walked carefully down the curved plating and sat near the edge on the windward side. Vertigo overtook him and he savored it, one feeling at least that he could be sure was his own. It happened, occasionally, that people fell, and usually somebody caught them. Usually.   The line of mage-rings stretched away into the distance, following a gentle curve. Three rings down, they joined with another and merged into one channel: Silmot’s Crossing. The nearby rings had picked up the name as well. Past the Crossing, that gentle curve continued, cutting across the silvery ribbon of the Sparrow River, following a different set of currents entirely.   Behind him, somewhere, were the enormous mana collection stations that channeled energy into the ring network. And out there, ahead of him, past the horizon, were the Core States, sitting in the middle of the ring network, gathering all the energy of an entire continent for use by the mage elite—unless the Separatists had hijacked the stream again. The ringers theoretically owed their allegiance to the Ampryn League, but they never knew who was working the receivers at any given time, and they didn’t really care. As long as the mana kept moving, nobody would bother them.   The guide ring above him began to crackle with flickers of energy—intermittently at first, then more vigorously. Jace was in luck. He smiled and reached into his pack, where he’d stashed some meat pies in anticipation of being sent to bed without eating. #emph[Dinner and a show.]   Over the roar of the wind came the faint sound of bells ringing far below. It was about to begin. He took a bite of a lukewarm meat pie. Not bad.   As he chewed, the guide ring—smaller and more sensitive than the primary—reacted to an incoming mana pulse. All the ringers on second shift scrambled to action far beneath him. In the monitoring station, supervisors gauged the strength of the incoming pulse and assigned ring mages to points all around the ring to stabilize the mana stream.   #figure(image("003_Jace’s Origin: Absent Minds/05.jpg", width: 100%), caption: [Art by Jung Park], supplement: none, numbering: none)   No doubt the coordinators in the monitoring station were furiously calculating mana pressure equations. Their ring had twelve mana control nodes, each crewed by half a dozen ring mages, and each mana pulse had its own pressure and spin and internal dynamics. Even with guidance tables, the math would be exponentially more difficult than what was on his test, but the supervisors knew how to do it.   Jace took another bite of his pie. What if someone asked #emph[him] to solve it? Would he find that he somehow knew this too? He chewed, contemplating. Perhaps. Probably. It seemed so.   In a flash, the air below him filled with shimmering, white-blue energy. The mana stream arced through the center of the ring, fluctuating as the ring mages channeled magic into the mana nodes to achieve a consistent pressure.   It was a vison. A masterpiece.   The ring groaned and creaked as the stream locked into place, the raw power of the mana stream anchored to the physical structure of the ring.   #emph[There’s the freak.]   The biting thought was the only warning Jace got.   He scrambled to his feet and spun, but he was too late. Three of his schoolmates stood between him and the access hatch.   #figure(image("003_Jace’s Origin: Absent Minds/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   "<NAME>," said the largest of the three, his booming voice overpowering the wind. His name was Tuck. At fourteen, he was a year older than Jace, a head taller, and built like a loading dock.   The other two were Caden, a crater-faced kid who made Tuck look brilliant, and Jillet, an angry young woman who had more sway over Caden and Tuck than either of the two toughs realized. Once, when they were in primary school, she’d shoved Jace down a flight of stairs.   "I was just leaving," Jace said, moving to slip between Tuck and Jill.   Jill shoved him back into place.   "Don’t be rude," said Tuck. "We just want to enjoy the view with you."   "I need to get home," said Jace. He moved to step around the trio entirely, but Tuck shot out a meaty arm and grabbed him by the shoulder.   "Let’s chat," said Tuck. "The instructor thinks you’re a cheater, but you aren’t, are you?"   Jace tried to shrug out of Tuck’s grip, but he didn’t dare lay a hand on the larger boy.   "You’re worse than a cheater," said Tuck. "You’re a freak."   The bones in Jace’s shoulder ground together under Tuck’s hand.   "A stuck-up, know-it-all freak."   Tuck continued to squeeze. Jace stared at the ground, unable to move any farther.   "Fine," said Jace. "Whatever."   "Say it," said Tuck. He was grinning.   "I’m a freak," whispered Jace.   Tuck pulled him closer.   "I’m sorry," he said. "I couldn’t quite hear you. Caden, could you hear him?"   "Not a peep," said Caden.   "I’m a freak," said Jace, louder this time.   "See, boys?" said Jill. "I told you the freak knew he was a freak."   "Well," said Tuck, "what do we do with a freak?"   He punched Jace in the stomach, hard. Jace sank to all fours…and peered inside the jagged, tangled corridors of Tuck’s mind.   "It must have been very frightening," said Jace, speaking into the rusted plating.   "What did you say?" Tuck hauled Jace to his feet.   "I said that it must have been very frightening."   Tuck stopped grinning. "What?"   "Waiting for him to come home," said Jace.   "Who?" asked Jill.   "Knowing he was drunk," said Jace. "Knowing he was going to hit you again."   "Shut up," snarled Tuck. He grabbed Jace by the throat.   "You’d pretend to be asleep," wheezed Jace. "You had your little knife, tucked into bed with you. And every time…"   "Shut up!" yelled Tuck. He squeezed.   "Every time…y-you told yourself…you were going to fight back." Jace’s vision began to dim. Through Tuck’s eyes, he looked blurred.   "Tuck?" said Caden.   "But you never did," whispered Jace.   #emph[Shut up! ] Tuck shoved Jace, sending him skidding across the slick, cold plating of the mage-ring’s roof—toward the edge.   Jace scrabbled at the plating, trying to stop his momentum, but there was nothing to hang on to. Jace went over, caught one hand on the edge of the roof, and hung there. His feet dangled in empty air and his fingers went instantly numb.   Wind whistled.   Below him, the mana stream hummed. If he fell in, he didn’t know what would happen. The mana potential of hundreds of acres of territory, captured and channeled into a single beam…he’d probably be vaporized.   His fingers trembled.   He got his other hand up, but the ledge was an overhang. He had no leverage. He was going to need help.   Tuck’s face loomed above him, a mask of rage and pain.   "Nobody knows about that," he hissed. "#emph[Nobody] . Not since the bastard died."   "Tuck, he’s gonna fall," said Caden.   Cramps shot up and down Jace’s arm. His grip was giving out.   "You want him digging around in your head? Telling Jilly here the things you say about her when she’s not around?"   "Excuse me?" said Jill.   "Shut #emph[up] , Tuck!" said Caden.   "Now you know how I feel." Tuck looked down at Jace. His eyes were wild. "Never again, Beleren."   He raised a boot.   #emph[Help me] .   Jace’s perspective lurched. He was looking down at himself, down at Tuck, out of Caden’s eyes.   Caden’s hand moved. Jace moved it. He didn’t know how or why or what Caden was seeing right now. He didn’t really care.   #figure(image("003_Jace’s Origin: Absent Minds/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   With Caden under his control, Jace grabbed Tuck’s shoulder and yanked him back from the edge, then stiffly offered himself a hand.   How small he looked, hanging desperately above the crackling stream of mana. How vulnerable he looked. He hated it.   Back in his own head, Jace grabbed Caden’s hand and hauled himself up.   He stood there, shaking, the plating solid under his feet. He only half-believed he was still alive. He looked to his three schoolmates.   Caden swayed on his feet, his eyes crackling with blue energy. Tuck was red-faced, furious. Jill’s eyes were wide.   The glow in Caden’s eyes faded. His eyes rolled back in his head, and he hit the plating with a thud.   Jace ran past Jill and Tuck’s horrified faces, past the void of Caden’s mind, down the stairs, and away—anywhere, anywhere but here.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   Jace had made up his mind.   All his belongings were packed into a small bag that sat beside him on the bed. There wasn’t much in it—a few changes of clothes, a journal, some dried meat. Now all he was waiting for was nightfall.   There was a knock at the door of his room.   It had been a day and a half, and he’d ventured out only long enough to take care of necessities. His mother left food at his door occasionally, but so far she’d had the decency not to try to talk to him. His father had tried, at first, until Jace had worn him down.   "Go away," said Jace. "I said I don’t want to talk about it."   From in his room, he could almost forget about the rest of the world. He brushed the edges of other minds—his parents, neighbors, the occasional wind mage—but from this distance he could only feel impressions, not fully formed thoughts.   "Jace," his mother said through the door. "I’m worried about you."   She was close, close enough that he could read her if he wanted. He didn’t. He didn’t want to see inside anyone’s mind ever again. He didn’t want to unearth their darkest secrets, didn’t want to control them or manipulate them, and above all didn’t want to see himself through their eyes—small, awkward, vulnerable.   "Fine," he said. "Come in."   She opened the door a crack and smiled at him. Without hearing her thoughts, he couldn’t tell whether the smile was genuine or forced. He couldn’t tell much of anything.   She sat down next to him on his bed, glancing at his packed bag but saying nothing. <NAME> was a healer, on call for emergencies. She had the tender patience of one who had seen far worse, but understood that all pain is real.   "What did they tell you?" he asked.   "I’d rather hear it from you."   "Tuck tried to kill me," said Jace. "Did they mention that?"   She shook her head.   "They were beating me up again," he said. "I didn’t know what to do so I…I don’t know. I just…figured out a secret of Tuck’s and started talking."   "He says you read his mind."   Jace hugged his knees. "I don’t know how I do it," he said. "I…hear people thinking. Sometimes I don’t even know if it’s them or me thinking."   "You’re a telepath?" said his mother. She sat up straight.   Jace could see the wheels turning. He wanted to know what she was thinking, but he held back. He could wait.   "You’re a telepath." This time it was a statement rather than a question. "My son the quick learner, the boy who always knew when his mother needed a hug, needed his love. My son the telepath." She was smiling.   "You don’t think I’m a freak?"   She shook her head. "I think you are perfect and I love you, no matter what."   Jace knew that was true, though whether by his abilities or not, he couldn’t say.   "How’s Caden?" asked Jace. "Have you heard?"   His mother’s lips pursed. "He’s still out," she said. "The healers aren’t quite sure what to do."   "I didn’t mean to hurt him," Jace said.   "I know."   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   Jace walked out into the common room, rubbing his eyes. His breakfast sat on the table, cold.   After the conversation with his mother, he’d decided to stay a little while longer and see if matters improved. Occasionally he ventured out of his room, sharing tense, quiet mealtimes with his parents. But he and his father hardly spoke to each other, and he didn’t dare leave the apartment. It had been three days.   He wolfed down three greasy sausages and half a plate of cold eggs before he noticed that his parents were both standing in the common room waiting for him. His father radiated impatience, his mother concern.   Jace smoothed his hair self-consciously and turned. "What’s going on?"   Jace’s father opened his mouth, but his mother spoke first. "There’s someone here to see you," she said. "Someone who can help."   Jace looked around.   "Out on the observation deck," said his father. "He can’t fit in here."   Jace resisted the urge to peek into his father’s mind, to learn what sort of helper they’d found who couldn’t fit inside their apartment. He still caught glimpses into his parents’ thoughts without meaning to, and the ghosts of impressions from passersby. But he hadn’t done anything on purpose since the accident, and he tried not to do anything at all.   "Who is he?"   "He’s an arbiter," Jace’s father said. "His job is to negotiate an end to the war. But he’s also a…a mage, um, like you. He knows how to…."   "He knows how to help you control your abilities," said Jace’s mother.   The other kids were in school, at least, so they weren’t there to stare at him as Jace and his parents made their way to the observation deck. But by now everyone in Silmot’s Crossing had probably heard about what happened. As they climbed, people stared at him, or hurried away, or whispered to each other behind their hands.   #emph[As though that would stop me.]   They didn’t hate him. They were afraid of him. And they should be, shouldn’t they? He’d dug around in Tuck’s memories just to find a way to hurt him, and when Jace's life was on the line he’d rammed his way into Caden’s head without hesitation.   He and his parents climbed the final set of steps to the observation deck, a section of ring with one open wall and a set of railings. Standing there, resting on its haunches, was a sphinx.   #figure(image("003_Jace’s Origin: Absent Minds/08.jpg", width: 100%), caption: [Art by Slawomir Maniak], supplement: none, numbering: none)   He towered above Jace with a regal, bearded face, enormous paws, and an elaborate mantle of gold and mirrored silver, his feathered wings folded behind him.   #emph["My name is Alhammarret. And you, <NAME>, are a mind mage of unusual talent."]   This thought, Jace knew with certainty, was not his own.   "How did you…?"   #emph["Respond in kind, please, if you can,"] said the booming voice in his head.   #emph["Like this?"] thought Jace.   #emph["Precisely."]   #emph["A ‘mind mage?’"] thought Jace. #emph["But doesn’t a mage cast spells? I don’t know any spells."]   #emph["What you do is spellcasting,"] said Alhammarret. #emph["You intuited the spells involved, rather than being taught."]   #emph["So if I’m casting spells, then] …#emph[you’re here to make me stop?"]   Alhammarret smiled. #emph["No. I want to train you, so you do not have to."]   #emph["Train me where?" ] Jace glanced back at his parents. #emph["Here?"]   #emph["No,"] said Alhammarret. #emph["The chance to train a promising mind mage is rare, but not so rare that I can abandon my other duties. You would come with me, as my apprentice."]   #emph["For how long?"]   #emph["Years."]   The suspicious looks, the whispers, the fear. He could leave it all behind—along with his parents’ love and support.   #emph["Do they know what you’re proposing?"] he asked.   #emph["I’ve spoken with them about it, yes. They want what’s best for you. And in this case, what’s best is to get you out of this provincial backwater so you can grow to your true potential. Yours is a rare gift. Don’t squander it here."]   Jace looked back at his parents again. His mother nodded encouragement. His father at least must be relieved. #emph[Education is your ticket out of here.]   Jace didn’t bother turning back to Alhammarret.   "I’m ready," he said.   After Jace had gathered his things and said his goodbyes, Alhammarret settled down and nodded for Jace to climb onto his back. Jace climbed up and braced his legs against the silver mantle, hoping that was what it was for.   Jace looked down at his parents and the gathered crowd. Tuck and Jill were there, hard-eyed. Already, the people of Silmot’s Crossing looked small and distant.   "I’ll come back," he said to his parents. "I promise."   He looked Tuck in the eyes. #emph["And if you harm my family, I’ll take your mind apart, one squalid little memory at a time."]   Tuck flinched.   Jace’s parents waved. Alhammarret stood, stretched, and launched himself from the observation deck.   Flight! He’d taken a few tumbles in the clutches of a wind mage, but this was nothing like that. They soared above the landscape, heading away from the trail of mage-rings in a direction Jace had never bothered to think about. His home of thirteen years receded, became a speck, and vanished into the distance.   #emph["That was unkind,"] said Alhammarret.   Jace winced.   "You…?" He stopped. Alhammarret hadn’t given him leave to speak normally and, in any case, the wind made spoken conversation impossible. #emph["You heard that?"]   #emph["Of course,"] said Alhammarret. #emph["This is something you must adjust to. Up to now, you have been, in effect, the only mind mage in existence. You’ve never had to consider the implications of dealing with another telepath."]   #emph["I’ll keep that in mind," ] said Jace.   #emph["I will train you to control your powers. I will help you hone them, to accomplish feats of telepathy you never dreamed possible, to glean deeply hidden information…and to do all this without hurting anyone. If you use these abilities to inflict intentional harm, that will be the end of your training…and possibly, depending on the severity of the harm, your life. Do you understand?"]   #emph["Fully,"] said Jace. #emph["I was just trying to scare him."]   #emph["Tread that path carefully,"] said the sphinx. #emph["In time, you will become more terrifying than you can imagine. And fear, once inspired, can seldom be eased."]   They flew on in silence for a time. The landscape beneath them had shifted, high steppe giving way to rolling fields and broad, shallow marshes. Only the trails of mage-rings, dozens of miles apart, seemed familiar.   #emph["This is Separatist territory, isn’t it?"] asked Jace.   #emph["These lands are claimed by the Trovians, yes. ‘Separatist’ is a politically charged term."]   #emph["And you’re an arbiter?"]   #emph["I am,"] said Alhammarret. #emph["So why is the war still going?"]   Jace flushed. That was going to be his next question. Mind mage!   #emph["The war is a generation old,"] said Alhammarret. #emph["The arbiters negotiate a peace every few years, when both sides are exhausted enough to want it. Then one side breaks the truce, and the war continues. We don’t even bother with permanent peace anymore—it’s simpler, and fairer, if both sides know from the outset when hostilities will resume."]   #emph["Why not let one side win?"] asked Jace.   #emph["The Ampryn] #emph[and the Trovians fight for control of the Core,"] the sphinx said. #emph["But only one of them holds it at any given time, and that side reaps the benefits of the mage-ring network. So why are the mage-rings unharmed? Why, when the Ampryn] #emph[hold the Core, do the Trovians not destroy the mage-rings to deny the Ampryn] #emph[their power source?"]   Jace had never thought about that. #emph["Because…Because they think they can take the Core, and they want the mage-rings intact for their own use when they do."]   #emph["Precisely,"] said Alhammarret. #emph["And as long as each side thinks it can win, that balance holds, and the mage-rings stand. Cities are abandoned intact rather than leveled. Roads and bridges are given up, to be recaptured later. If that ever changes—if either side finds itself in existential danger—then it will destroy everything as it retreats, to deny it to the other. Civilization on Vryn might take centuries to recover—if it ever did."]   Jace felt a sudden rush of vertigo.   #emph["That," ] said Alhammarret, #emph["not mere loss of life, is what the arbiters seek to prevent. As usual, matters are not as simple as they seem."]   They stopped at night, and Alhammarret arranged lodgings in the effectively neutral confines of a mage-ring. It was different than Jace’s home ring—bigger, and recently repaired. Neither side wanted to harm the rings, but collateral damage was inevitable.   After a few days, they reached their destination, a wall of rock that rose above the rolling plain. Alhammarret flew higher, his powerful wings pumping. He alighted on a broad landing platform, shook his wings, and knelt so Jace could dismount.   #emph["Welcome home, <NAME>."]   Home#emph[. ] Jace hoped this could be home.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   Jace paused at the foot of the last flight of stairs.   He’d spent two years as the sphinx’s apprentice, learning the full abilities—and limitations—of his own mind. At fifteen, he was taller, and smarter, and more powerful than he had been before. He could peel the military secrets from a sleeping guard’s mind without learning anything about the man’s family, could cloud thoughts and change minds without causing any damage at all. He hoped his parents would be proud. Although honing his telepathy had been the primary focus of his training, Alhammarret hadn’t neglected other disciplines of magic, and Jace had grown into a talented illusionist.   He’d expected, at first, that his training would consist mainly of going to negotiations and learning what he could from the ambassadors’ minds. And he did accompany Alhammarret to talks, and the sphinx did ask him, afterward, what he’d learned from the negotiators’ thoughts—which was never anything interesting. Jace asked early in his training why either side even consented to parley with a telepath.   #emph["To keep each other honest,"] the sphinx explained with a twinkle in his eye. #emph["They learned long ago not to send anyone who knew anything they didn’t want spoken aloud."]   There were long hours studying magical theory in the sphinx’s library; mental sparring sessions out on the landing pad; and a constant battery of questions, challenges, quizzes, and tests. There were puzzle boxes and ciphers, visitors real and illusionary, even the occasional trap. And Jace could not read Alhammarret in the slightest. For the first time in his life, Jace was truly challenged by his studies. He’d even blacked out during illusion training at one point, his own illusions overwhelming his mind with their insistence of reality.     #figure(image("003_Jace’s Origin: Absent Minds/09.jpg", width: 100%), caption: [], supplement: none, numbering: none)   Art by <NAME>   A few months ago, Alhammarret had started sending Jace out to gather information. Alhammarret called them "training missions," but they were quite real. Under cover of darkness and cloaked by illusions, Jace would sneak into a camp of one of the opposing sides. There, whether through telepathy or mundane sleuthing, he would learn about the army’s battle plans, and return to report to Alhammarret.   He’d protested at first, but the information they learned from these missions helped Alhammarret keep the peace. Often, just mentioning battle plans at a joint meeting was enough to keep the front quiet for a month or two.   Finally, with Alhammarret’s guidance, Jace was using his abilities to help people. And his most recent mission had gone particularly well.   He climbed up the steps and entered Alhammarret’s study.   Alhammarret gazed out the great circular window. He didn’t turn when Jace entered. They seldom bothered with eye contact, and sometimes spoke to each other from different rooms, though Jace’s range was still much more limited than the sphinx’s.   #emph["Welcome back," ] said Alhammarret. #emph["What have you learned?"]   Jace could not read Alhammarret’s mind, and, out of courtesy, Alhammarret did not read his without invitation, except when they were practicing mental defenses. Jace was no longer helpless, but his mentor could still blast through his mental blocks without effort.   By way of answer, Jace opened up a particular set of memories to Alhammarret’s scrutiny. Jace had learned from a high-ranking Separatist officer of Trovian designs for a surprise springtime offensive. They planned to cross the Rime Marshes before the thaw and drive for the Ampryn Core. It would be a brutal campaign for both sides, bringing the fighting to previously untouched civilian territories and potentially breaking the Ampryn stranglehold on the Core States. And Jace had learned of it without letting the Trovians know who he was or what he had gleaned from them. #figure(image("003_Jace’s Origin: Absent Minds/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   #emph["Excellent work,"] said Alhammarret.#emph[ "I expect the look on the Trovian ambassador’s face when I mention this at the next negotiation will be…gratifying."]   The sphinx turned and padded down the curved steps, past Jace. #emph["Come,"] he said. #emph["I want to review the maps while your memory is fresh, and mark their exact routes."]   The room looked nothing like the paltry library in Silmot’s Crossing, with its collection of dog-eared mana dynamics manuals, outdated history books, and the occasional work of badly written fiction. There were no books here, but racks of crystalline spheres. Alhammarret’s great paws couldn’t turn pages, and his library contained more information than could be held in an entire mage-ring full of books.   Alhammarret worked several great pedals, like a pipe-organ’s, and aligned one of the data-spheres with the projector. A map of the Rime Marshes sprang into being in the center of the library.   Jace painted illusions onto the map, showing the planned troop movements. As he did so, his mind wandered.   Unquestionably, he was growing more powerful. He’d had to fight his way out of the Trovian camp, but he’d cleaned up after himself. He’d gotten everything he went for, nobody who’d seen him was going to remember him, and he hadn’t done any permanent damage. Even a few months ago, that kind of operation would have been beyond him. Soon enough, he’d be a better mind mage than….   The sphinx was distracted, pulling up more maps and plotting Jace’s information on them, following the Trovian army’s path into the heartland.   Jace had not tested Alhammarret’s defenses in a long time.   He’d be caught, of course. Alhammarret always knew when Jace tried to read him. Jace could argue, reasonably, that it was part of his training—judging when a target’s defenses were down.   He looked inside Alhammarret’s mind.   The sphinx’s thoughts were immense and powerful, a buffeting cyclone of mental force. Jace’s brief explorations had always run up against it like a wall. This time, though, with effort, he was able to slip into the wind….   #emph[A flood of sensations, of memories, overtook him.]   #emph[He was looking down at himself, practicing illusions, concentrating hard to control a few wisps of light and sound. He looked so young.]   #emph[Something was wrong. Blue-white energy crackled in his eyes. The illusions swirled around him faster and faster.]   #emph[And then]   #emph[he began]   #emph[to fade….]   #emph[Within the swirling illusions, Jace vanished entirely.]   #figure(image("003_Jace’s Origin: Absent Minds/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   #emph[Alhammarret reached out with a tendril of Æther, into the void between worlds ] (plural!)#emph[, and pulled the boy back.]   #emph[Planeswalker.]   #emph[Jace stirred. He sat up. He asked what had happened.]   #emph[And Alhammarret wiped the incident from the young man’s mind.]   The library. His own eyes. The real Alhammarret regarded him, eyes shrewd.   #emph["Jace?"]   #emph["There,"] said Jace, illuminating a section of the map. #emph["Sorry."]   #emph["You’re exhausted,"] said Alhammarret. #emph["No more bravado. Rest."]   Jace went to his room and shut the door with no intention of opening it. Alhammarret would know. If he didn’t already. How long until he wiped Jace’s memory again? Had this happened before? Was there any way to know?   #emph[Planeswalker.]   Whatever that was, Alhammarret seemed to think Jace was one. That there were worlds beyond Vryn. That Jace could travel to them.   He tried. Nothing happened.   He’d awakened as a planeswalker, drifted out into the Æther. But if he couldn’t remember it…how could he do it again?   Alhammarret had his best interests at heart. Someday the old sphinx surely planned to tell him, to apologize for the deception, to explain that Jace simply hadn’t been ready. Even purely out of self-interest, Alhammarret had to covet a planeswalker apprentice.   As long as this information was in Jace’s head, Alhammarret could read it. And if Alhammarret could read it, he would wipe Jace’s mind again, and Jace would lose his chance of ever learning the truth. He had to defend his mind. But any departure from his usual behavior would draw suspicion, and suspicion would draw scrutiny, and scrutiny would reveal his secret.   He pulled a piece of paper out of his desk and began to write—in a small, cramped hand that the sphinx might not be able to read even if he found it—what he had seen, and how he had seen it. He included as many details as he could, and warned himself what would happen if Alhammarret found out. When he was done, he wrote the date on the top, folded the paper carefully, and hid it in his desk drawer.   Then, slowly and very, very carefully, Jace made himself forget what he had seen, forget writing it down, forget forgetting.   He had a headache.   He found the paper several times over the next few weeks. Each time, he was furious. Each time, he wondered what to do. And each time, to keep it from Alhammarret, he removed his memory of finding it.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   It was the Ampryn camp this time.   They stood on ceremony. Avoiding soldiers on drill was like sneaking past a statue. Peek in one mind, learn the patrol schedule, and you could walk right in.   There were more soldiers than he expected—too many for a lowly command post. Someone important was visiting.   That meant more risk. He should return to Alhammarret at once, and try another time.   But it also meant more information, didn’t it?   He peered into a few more soldiers’ minds until he found his new quarry. A general was visiting the front, a grizzled and decorated veteran of the war. The general had brought two squads of elite guards with him, and two of them guarded the door of the general’s tent at all times.   Under cover of darkness, while the lamps in the tent were still lit, Jace stepped over the sleeping forms of the two door guards. #figure(image("003_Jace’s Origin: Absent Minds/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   There were three people in the tent. Jace sent two into the arms of sleep and turned to the general, who opened his mouth to yell for guards. No sound came out.   "Hello, General," said Jace. "This will only take a moment."   He dove in.   The general was a strong-willed man, resistant to Jace’s probing to some degree, but he was not a mind mage, nor any kind of magic-user. Jace broke through his natural defenses and saw…   #emph[The entire Trovian battle plan for the coming campaign hovered before him, an illusory map that matched the contours of the land to the smallest detail. Their plan was audacious…and without proper countermeasures, it was going to work.]   #emph["You’re sure this is genuine?" the general asked.]   #emph["Positive," said the hooded figure. "Has our source ever misled you before?"]   #emph["No," he said. "Nor the renegades, I’m sure."]   #emph["Of course," said the figure. "When your business is information, reputation is everything."]   #emph["Of course," he said.]   #emph[The hooded man—boy, really, lanky and cocksure—knew much more than he was willing to tell…like the identity of this source. For the good of the Ampryn, he ought to seize the young man, torture the name of this source out of him, and….]   #emph["It wouldn’t do any good," said the kid. "He doesn’t tell me much." The boy’s eyes glinted beneath the hood.]   #emph["Fine," he said. "Take your payment and go. And tell your source there’s more where that came from, any time he has intel."]   #emph["I’ll tell him," said the kid. He pocketed the money and turned, and the general caught a glimpse of his face….]   Dimly, from the outside world, Jace heard yelling. He’d taken too long.   He was trapped. Trapped in a mind, trapped in a memory, frozen, staring at his own face behind that damned hood, in a conversation whose entire context was a mystery to him.   He #emph[pulled…]   …and he was out.   The general slumped in front of him, eyes vacant.   Running footsteps. The tent flap opened. Jace turned.   Three guards. He waved a hand, and illusions swarmed around them.   The general was breathing, but his mind was blank.   #emph[I’m sorry.]   Jace dove out of the tent and ran into the night, and kept running until he could go no farther.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   When Jace returned to Alhammarret’s lair, he went straight to his room and packed his things. He didn’t know where he was going. He didn’t care.   While he was packing, he found a note, in his own handwriting, warning him of Alhammarret’s duplicity, revealing his own nature.   One more outrage. One more lie.   Jace scribbled another few lines on the paper, crammed it in his pocket, and wiped his memory of it again. Maybe he’d get to keep that one.   He kept his thoughts locked up as tightly as he could. If Alhammarret wanted to know what was on his mind, the sphinx would have to break it open.   He checked the library and the study. Empty.   He could leave. He wanted no part of the sphinx’s games anymore.   But he had to know.   He headed up to the landing pad. Alhammarret was there, sitting on his haunches, waiting for him.   #emph["Welcome back," ] said Alhammarret. #emph["What have you learned?"]   "You tell me," said Jace. He spoke, having no desire to give the sphinx the slightest opening. He raised every mental defense he knew of.   #emph["Ah,"] said Alhammarret. #emph["I take it you’ve learned something that displeased you."] The sphinx’s voice in his head was louder now, insistent.   "Not at all," said Jace. "But it’s been a while since we practiced mental combat, hasn’t it?"   #emph["It has. You are more powerful now. You could hurt yourself."]   "Hurt you, you mean?"   #emph["Unlikely,"] said the sphinx.   "And what if I fell into the hands of an enemy mind mage? We can’t be the only ones, can we? Test me. Help me find my limits. Pry the information out of me."   Alhammarret stood up, and the full force of his mind hit Jace like a storm front.   #figure(image("003_Jace’s Origin: Absent Minds/13.jpg", width: 100%), caption: [Art by Yan Li], supplement: none, numbering: none)   Jace had expected it to feel like an invasion, an alien force. But it was an overwhelming presence, a rush of thought and sensation enveloping his own. Alhammarret could rip Jace's mind apart. But to do that, he had to read it, and when he read it, Jace could do the same. Finally, he saw the true shape of the last two years, saw the perilous edge he’d been dangling from all this time.   Alhammarret had played him. He’d used Jace as a go-between, to gather information, deliver it, and learn more just in the delivery. And every time, he’d wiped Jace’s memory of it, taken the money for himself, and kept the war going. If your business was negotiating peace, where was the profit in actually achieving it?   Now Alhammarret knew everything, and settled into the recesses of Jace’s mind to wipe out the offending memories, to salvage this useful asset if he could. And destroy it if he couldn’t.   Jace struck first.   The sphinx was more powerful. But here, in Jace’s head, he was also vulnerable, provided Jace was willing to damage his own mind in the process. And Alhammarret was too arrogant and too cowardly to consider that possibility.   Jace felt himself falling backward, upward, outward. He could not remember his home, his mother’s face, or the sound of his own name. But the sphinx had it worse.   Alhammarret had forgotten how to breathe.   He slumped forward, gasping for breath, and the outline of his head was the last thing the planeswalker saw before he broke   into   pieces   and   #emph[walked…]   #figure(image("003_Jace’s Origin: Absent Minds/14.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)   = Ravnica   He hit the ground, hard, on his back. It was bright. And loud. And busy.   He had a headache.   The shapes moving around him resolved themselves into people, and the sounds into voices, and the headache into thoughts that were not his own.   "Watch it," said a voice, as its owner stepped around him.   #emph[Ought to report you to the Boros for reckless teleportation.]   Boros?   "Outta the way!" yelled another voice, and he looked up just in time to roll out of the path of a cart pulled by some kind of woolly, hooved beast with wide, sweeping horns.   #emph[Came out of nowhere. Some poor Izzet experimental subject, probably.]   He scrambled to his feet. People were staring at him. He looked as bad as he felt, sweaty and pale and filthy. He pulled his scarf up around his face and dashed to the side of the road.   #emph[I’m not an experimental subject. I’m…I’m…]   #emph[I’m in trouble.]   #emph[Fine. Table that.]   He walked as fast as he could without seeming to hurry. He reached out, carefully, into the minds around him. It was a cacophony, a mad tangle of voices, and half of them weren’t even human.   #emph[Vagrant. Thief. Poor kid. Wretch.]   His headache was getting worse.   Still, he was able to snatch scraps of meaning from the din. This was the garment district, and his clothes—#emph[ringer garb] , some buried part of him said—looked like rags by comparison. Some holiday called Rauck-Chauv was coming up soon. A group known as "Orzhov" seemed to own this area, or politically control it, or somewhere in between. Hundreds of minds, and not one of them was thinking about anything outside the city. Was that strange? Maybe city folk were like that.   He spotted at least two distinct law enforcement agencies, and stayed out of their sight as much as possible. He needed to get somewhere where he’d draw less attention. He seized on the seediest, grimiest thoughts, the minds that wore the clothes that looked most like his, and followed them like a thread.   In ten minutes he was somewhere else, a district where the alleys were narrower and the shadows darker, and everyone was focused on their own business.   He walked on, mindful of ambush, reaching out to the minds around him for any scrap of information that could help him.   At last, cradled like a treasure within the mind of a filthy, hungry girl, he found it:   #emph[<NAME>.]   She took in strays. But where?   #emph[Ovitzia] .   Good enough.   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   The door swung open to reveal a statuesque woman with long, pointed ears, elegant garb, and milk-white eyes. Her thoughts were labyrinthine, hidden deep beneath the surface.   #emph[She’s beautiful.]   "If you’ve come only to admire me," she said, "I’m afraid I haven’t the time."   "You’re a mind reader?" he said. He immediately regretted it.   The elf smiled. "No. You’re a teenager."   He flushed, and just for a moment, he saw himself through her eyes: filthy, awkward, bleary-eyed, and readable as a book.   "I’m from…" #emph[out of town] , he almost said, but he still had no idea what that meant here, "another district. I need a place to stay. I heard you take in people like me."   "Sometimes. What’s your name?"   He flickered through the thoughts around him, digging for a local name that wouldn’t sound conspicuous.   "Berrim," he said, after just slightly too long, plucking the name from the mind of a passing servant. "My name is Berrim."   It seemed a harmless lie, and far better than admitting the truth. For all he knew, it was true.   "Come in…Berrim," said Emmara. "Let’s see about getting you some new clothes."   #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em)   He was safe. He was clean. He was fed. He finally had some time to think. Could he remember anything at all?   He traced illusions in the air, random shapes to help him think. Blobs, and lines, and rings.   #emph[Silmot’s Crossing] .   The thought bubbled up from nowhere, accompanied by the image of a towering, ring-shaped construction. The only way he was sure it was his own was that there wasn’t anybody else around to have it.   A shape coalesced in front of him—an elongated ring, open at the bottom, with a circle floating in the middle. He had no idea what it meant, if it meant anything at all.   #emph[Jace.]   #emph[My name is <NAME>.]   So there was something in there, waiting for him to dig it out.   #emph[And who is <NAME>? Is he a good man? Is he kind?]   He willed away the shape and sat, alone, farther from home than he’d even known was possible.   He’d have to wait and see.   #figure(image("003_Jace’s Origin: Absent Minds/15.png", width: 100%), caption: [Art by Jaime Jones], supplement: none, numbering: none)
https://github.com/grnin/Zusammenfassungen
https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/13_Meltdown.typ
typst
// Compiled with Typst 0.11.1 #import "../template_zusammenf.typ": * #import "@preview/wrap-it:0.1.0": wrap-content /* #show: project.with( authors: ("<NAME>", "<NAME>"), fach: "BSys2", fach-long: "Betriebssysteme 2", semester: "FS24", tableofcontents: (enabled: true), language: "de" ) */ = Meltdown Meltdown ist eine _HW-Sicherheitslücke_, mit der der _gesamte physische Hauptspeicher ausgelesen_ werden kann. Insbesondere kann damit ein Prozess alle geheimen Informationen _anderer_ Prozesse lesen. Folgende _Eigenschaften_ müssen für diese Sicherheitslücke gegeben sein: Der Prozessor muss dazu gebracht werden können: 1. aus dem _geschützten Speicher_ an Adresse $a$ das Byte $m_a$ zu _lesen_ 2. die Information $m_a$ in irgendeiner Form $f_a$ _zwischenzuspeichern_ 3. _binäre Fragen_ der Form "$f_a eq.quest i$" zu beantworten 4. Von $i = 0$ bis $i = 255$ _iterieren_: $f_a eq.quest i$ 5. Über alle $a$ _iterieren_ == Performance-Optimierungen in realen Systemen Moderne HW und OS verwenden zahlreiche und nicht immer intuitive "Tricks" für Performance-Optimierung: #link(<md-caches>)[_Caches_], #link(<md-O3E>)[_Out-of-Order Execution_], #link(<md-speck>)[_Spekulative Ausführung_], #link(<md-mapping>)[_Mapping_ des gesamten physischen Speichers in jeden virtuellen Adressraum]. === Mapping des Speichers in jeden virtuellen Adressraum <md-mapping> Virtueller Speicher soll Prozesse gegeneinander schützen. Deshalb hat jeder Prozess seinen eigenen virtuellen Adressraum. _Kontext-Wechsel_ sind jedoch relativ _teuer_. Deshalb arbeitet das OS aus _Performance-Gründen_ im _Kontext des Prozesses_. Der OS-Kernel wechselt den Kontext _nicht_, sondern _mappt alle Kernel-Daten_ in den Adressraum.\ Die Page-Table ist so konfiguriert, dass _nur das OS_ auf diese Teile _zugreifen_ darf. Da das OS auf _alle Prozesse_ zugreifen können muss, mappt der OS-Kernel den _gesamten physischen Hauptspeicher_ in jeden virtuellen Adressraum. === Out-of-Order Execution (O3E) <md-O3E> Moderne Prozessoren führen Befehle aus, wenn alle benötigten Daten zur Verfügung stehen #hinweis[(Solange das Endergebnis dadurch nicht beeinträchtigt wird)]. Dadurch kann sich _die Reihenfolge der Befehle ändern_. ==== Spekulative Ausführung <md-speck> Out-of-Order Execution wird auch dann _vorgenommen_, wenn der Befehl später _gar nicht ausgeführt_ wird. Erfordert prozessor-internen Zustand neben den Registern - _wesentliche Voraussetzung für Geschwindigkeit_ moderner Prozessoren. Wenn der Wert dann nicht gebraucht wird, wird er wieder _verworfen_ #hinweis[(z.B. Befehle nach conditional jumps)]. Beim Zugriff auf eine Adresse, für die keine Berechtigung besteht, liest das OS den Wert zwar, gibt ihn aber nicht an den Prozess weiter. Schritt 1 ist damit erfüllt, da durch spekulative Ausführung auf jeglichen Speicher zugegriffen werden kann. #pagebreak() ==== Seiteneffekte von Out-of-Order Execution <md-caches> Der _Cache weiss nicht_, ob ein Wert _spekulativ_ angefordert wurde. Wird also trotzdem in den Cache geschrieben. Dieser kann vom Prozess nicht ausgelesen werden, da die MMU entscheidet, ob der Cache die Daten an ihn weitergeben darf. ```c char dummy_array[4069 * 256]; // page size * char size char * sec_addr = 0x1234; char sec_data = *sec_addr; // Exception, no permission char dummy = dummy_array[sec_data]; // speculative ``` Schritt 2 ist damit erfüllt, da im Cache $m_a$ als Teil des Tags gespeichert wird. #hinweis[(`dummy_array` + `sec_data` #sym.arrow `sec_data` = Tag - `dummy_array`).] === Cache auslesen Jedoch kann _die Zeit gemessen_ werden, die ein Speicherzugriff benötigt: _Lange Zugriffszeit:_ Adresse war nicht im Cache _Kurze Zugriffszeit:_ Adresse war im Cache. Dies nennt man auch _Timing Side Channel Attack_. Mit der Assembly-Instruktion ```asm clflush p``` werden alle Zeilen, die die Adresse `p` enthalten gelöscht. Das ermöglicht "Flush & Reload": Über das gesammte Array iterieren und `clflush` ausführen, damit wird sichergestellt dass das gesamte Array nicht im Cache ist. Schritt 3 ist somit auch erfüllt: Die Zugriffszeit verrät, ob $f_a$ im Cache. == Tests von Meltdown Verschiedene CPUs #hinweis[(Intel, einige ARMs, keine AMDs)] und verschiedene OS #hinweis[(Linux, Windows 10)] sind betroffen. _Geschwindigkeit_ bis zu 500 KB pro Sekunde bei 0.02% Fehlerrate. So schnell können "sichere" Daten ausgelesen werden. #hinweis[(1 GB in 35min mit 210KB Fehlern)] == Einsatz von Meltdown Meltdown kann zum Beispiel zum _Auslesen von Passwörtern_ aus dem Browser via Malware oder für _Zugriff auf andere Dockerimages_ auf dem gleichen Host verwendet werden. Kann jedoch _nicht_ aus einer VM heraus auf den Host oder auf geschlossene Systeme zugreifen. Nachweis des Einsatzes ist sehr schwierig, die Attacke hinterlässt quasi _keine Spuren_. _AMD und ARM sind nicht betroffen_, vermutlich weil sie die Zugriff-Checks anders durchführen. == Gegenmassnahmen _Kernel page-table isolation "KAISER":_ verschiedene Page Tables für Kernel- bzw. User-Mode. Der _Impact auf die Performance_ ist auf Linux-Systemen sehr unterschiedlich, kaum messbar bei Computerspielen, 5% beim Kompilieren, bis zu 20% bei Datenbanken und _30% bei weiteren Anwendungen_. == Spectre Angriff, der das gleiche Ziel hat wie Meltdown, nämlich Speicherbereiche anderer Prozesse zu lesen. Verwendet jedoch einen anderen Mechanismus: _Branch Prediction mit spekulativer Ausführung_. Moderne Prozessoren _lernen_ über die Zeit, _ob ein bedingter Sprung erfolgt_ oder nicht. Muss der Prozessor noch auf die Sprungbedingung warten, kann er schon _spekulativ den Zweig ausführen, den er für wahrscheinlicher hält_. === Angriffsfläche von Branch Prediction Branch Prediction wird nicht per Prozess _unterschieden_. Alle Prozesse, die auf dem selben Prozessor laufen, verwenden die _selben Vorhersagen_. Ein Angreifer kann damit den Branch Predictor _für einen anderen Prozess "trainieren"_. Der _Opfer-Prozess_ muss zur Kooperation _"gezwungen"_ werden, indem im verworfenen Branch auf Speicher zugegriffen wird. Spectre ist _nicht besonders leicht zu fassen_, aber auch _nicht besonders leicht zu implementieren_. === Fazit HW-Probleme können teilweise durch SW _kompensiert_ werden, Designentscheidungen können _weitreichende Konsequenzen_ haben.
https://github.com/N3M0-dev/Notes
https://raw.githubusercontent.com/N3M0-dev/Notes/main/CS/Digit_Logic/Note_DDaCA/Ch_2/ch2.typ
typst
#import "@local/note_template:0.0.1": * #import "@local/tbl:0.0.4" #show: tbl.template.with(tab: "|") #set par(justify: true) #set outline(indent: auto) #set page(numbering: "1", number-align: center) #set heading(numbering: "1.1") #frontmatter( title: "Chapter 2: Combinational Logic Design", subtitle: "Note of Digital Design and Computer Architecture", authors: ("Nemo",), date: "2023 Oct 10 - "+str(datetime.today().display("[year] [month repr:short] [day padding:none]")) ) #outline() #pagebreak() = Introduction In digital electronics, a circuit is a network that processes discrete-valued variables. A circuit can be viewed as a blackbox with: - one or more input terminals - one or more output terminals - a functional specification describing the relationship between inputs and outputs - a timing specification describing the delay between inputs changing and outputs responding Digital circuits are classified as _combinational_ or _sequential_. A combinational circuit's outputs depend only on the current inputs, while sequential circuit's output depend both current and previous inputs. That is to say, combinational circuits are _memoryless_, but sequential circuits have _memory_. Note that there may be several different _implementation_ for one single function. #theorem()[ Rules of _combinational composition_: A circuit is combinational if it consists of interconnected circuit elements such that: - Every circuit element is itself combinational. - Every node of the cricuit is either designated as an input to the circuit or connects to *exactly one* output terminal of a circuit element. - The circuit contains no cyclic paths: every path through the circuit visits each cricuit node at most once. ] #note()[The rules of combinational composition is not a necessary condition of one circuit to be combinational. That is to say, some circuits can still be combinational despite that they disobey the rules. However that does not implies that the rule is useless, by following the rules, the circuit we disign are sure to be combinational. Just note that the disobeying the rules dose not mean the circuit is not combinational.] = Boolean Equations == Terminology The _complement_ of a variable $A$ is its inverse $overline(A)$. The variable or its complement is called a _literal_. We call $A$ the _true form_ of the variable and $overline(A)$ the _complementary form_; "ture form" only means that there is no line over the letter "A" and do not imply the variable $A$ is TRUE. The AND of one or more literals is called a _product_ or an _implicant_, like $A B, A overline(B) thin overline(C)$. A _minterm_ is a product involving all the inputs to the function. e.g. $A B overline(C)$ is a minterm for a function of three variables A, B and C, but $A B$ is not. The OR or one or more literals is called a _sum_, a _maxterm_ is a a sum involving all of the inputs to the function. == Sum-of-Products Form A truth table of N inputs contains $2^N$ rows. Each row in a truth table is associated with a minterm that is TRUE for that row, e.g.: #show: tbl.template.with(align: center, tab: "|", mode: "math") ```tbl C | C | C | C | C. A | B | Y | "minterm" | "minterm name" _ 0 | 0 | 0 | upright(overline(A) thin overline(B)) | m_0 0 | 1 | 1 | upright(overline(A) B) | m_1 1 | 0 | 0 | upright(A overline(B)) | m_2 1 | 1 | 1 | upright(A B) | m_4 ``` We can wirte a Boolean equation for any truth table by summing each of the minterms for which the output, Y, is TRUE. Take the table above as an example: ```tbl C | C | C | C | C C | C | C | C | C Ck(gray) | Ck(gray) | Ck(gray)o(red) | Ck(gray) | Ck(gray) C | C | C | C | C Ck(gray) | Ck(gray) | Ck(gray)o(red) | Ck(gray) | Ck(gray) C | C | C | C | C. A | B | Y | "minterm" | "minterm name" _ 0 | 0 | 0 | upright(overline(A) thin overline(B)) | m_0 0 | 1 | 1 | upright(overline(A) B) | m_1 1 | 0 | 0 | upright(A overline(B)) | m_2 1 | 1 | 1 | upright(A B) | m_4 ``` So, $Y=m_1 + m_4=overline(A) B+ A B$. This can be also written in the sigma notation: $F(A,B)=sum(m_1,m_3)$ or even simpler, $sum(1,3)$ == Product-of-Sums Form An alternitive way of expressing Boolean functionsis the product-of-sums canonical form. Each row of the turth table corresponds to a maxterm that is false for that row. Then we can wirte a Boolean equation for the truth table as the AND of each of the maxterm for which the output is FALSE. = Boolean Algebra == Axioms $ B=0 "if" B eq.not 1\ overline(0)=1\ 0 dot 0 = 0\ 1 dot 1 = 1\ 1 dot 0 = 0 dot 1 = 0 $ == Theorem of One Variable #theorem(( [ The identity theorem: For any Boolean variable $B$, $B "AND" 1 = B$.\ (Dual: $B "OR" 0 = B$) ],[ The null element theorem: For any Boolean variable $B$, $B "AND" 0 = 0$, so "0" is called the null element for the AND operation.\ (Dual: "1" is the null element for OR operation.) ],[ Idempotency: A variable AND itself is equal to just itself.\ (Dual: A variable OR itself is equal to just itself.) ],[ Involution: $overline(overline(B))=B$, complementing a variable twice results in the original variable.\ (mathematical definition for involution: In mathematics, an involution, involutory function, or self-inverse function is a function f that is its own inverse.) ],[ The complement theorem: $B dot overline(B)=0$, a variable AND its complement is always 0.\ (Dual: $B + overline(B)=1$,a variable OR its complement is always 1.) ] )) == Theorem of Several Variables #theorem(( [ Commutativity and associativity: $B dot C=C dot B, B + C = C + B\ (B dot C) dot D = B dot (C dot D), (B+C)+D=B+(C+D)$ ],[ Distributivity: $B dot C + B dot D = B dot (C+D)\ (B+C) dot (B+D)=B+C dot D$\ Note that the second equation does not hold in triditional algebra. ],[ Covering: $B dot (B+C) = B, B + (B dot C) = B$ ],[ Consensus: $B C + overline(B) D + C D = B C + overline(B) D\ (B+C) dot (overline(B)+D) dot (C+D) = (B+C) dot (overline(B)+D)$ ],[ De Morgan's Theorem: $overline(B_0 dot B_1 dot B_2 dots)=overline(B_0)+overline(B_1)+overline(B_3)+ dots\ overline(B_0+B_1+B_2+dots)=overline(B_0) dot overline(B_1) dot overline(B_3)dots$ ] )) #note()[ When trying to prove these theorems, note that the null element is the crucial clue to the solution. ] According to the De Morgan's Theorem, we have the following equivalence: #figure( image("NAND_NOR_dual.png",width: 50%) ) The inversion circle is called a _bubble_, and it has several properties: - Pushing the bubble from the output to the input changes the body of the gate (AND $->$ OR or OR $->$ AND) and vice versa. - Pushing a bubble form the output to the inputs puts bubbles on all the gate inputs. - Pushing all the bubbles form the input to the output puts a bubble on the output. == The Truth Behind It All Proving the theorems are easy because that they only contain finit numebr of variables. We can simply list all the possible values of the variables, this method is called _perfect induction_. == Simplifying Equations / e.g. 1 : Minimize equation $overline(A) thin overline(B) thin overline(C) + A thin overline(B) thin overline(C) + A overline(B) C$\ Upon first sight, I'll try to simplify the expression to $overline(B) thin overline(C) + A overline(B) C$ or $overline(A) thin overline(B) thin overline(C) + A thin overline(B)$ and I'm stuck here. It seems that we can either combine the first two or the last two and no more, because the miniterm $A thin overline(B) thin overline(C)$ is used to either form $overline(B) thin overline(C)$ or $A thin overline(B)$. We call this situation $overline(B) thin overline(C)$ and $A thin overline(B)$ _share_ the miniterm $A thin overline(B) thin overline(C)$. Now the magic! Remember the *_Idempotency Theorem_* ? We can duplicant terms as many times as we want! It's an important feature of Boolean algebra. So actually we can minimize the expression to $overline(B) thin overline(C) + A thin overline(B)$. Amazing! = Form Logic to Gates A schematic is a diagram of a digital circuit showing the elements and the wires that connect them together, like the figure below, which is the implementation of the function: $ Y= overline(A) thin overline(B) thin overline(C) + A thin overline(B) thin overline(C) + A overline(B) C $ #figure( image("Schematic_eg.png",width: 50%) ) To ensure consistency, readability, we make these following rules: - Inputs on left or top - Outputs on right or bottom - Whenever possible, gates should flow from left to right - Straight wires - Wires connect at a T junction - A dot where wires cross indicates a connection - Wires cross without a dot make no connection The style of the schematic above is called a _programmable logic array (PLA)_ bacause the NOT gates, AND gates, and OR gates are arrayed in a systematic fashion. #let is_null(body)={ if body==[] or body==""{return true} else{return false} } #let eg(name: [],body) = { if not is_null(name){ [e.g. #name] par(first-line-indent: 1em,hanging-indent: 1em)[#body] } else[ / e.g. : #body ] } #eg(name: [Multiple-output circuits])[ _Priority Circuit_ : For input $A_0, A_1, A_2, A_3$, let's say they have weights equal to their subscripts. ($A_3$ have the greatest weight 3, and $A_0$ have the weight 0) There corresponding output are $Y_0, Y_1, Y_2, Y_3$. When $A_3=1$ then $Y_3=1$ regardless whatever the other variables. The output is determined by the input and there weight. How to implement it then? We can list the truth table.The X in the table stands for the value does matter. Though that we can indeed use the sum of product method to work out the Boolean equation, but it's acutally easier to derive them from the function descirption. We simply miss out the variables that does matter (marked X in the table). $ Y_0&=overline(A_3) thin overline(A_2) thin overline(A_1) A_0\ Y_1&=overline(A_3) thin overline(A_2) A_1\ Y_2&=overline(A_3) A_2\ Y_3&=A_3 $ #show: tbl.template.with(align: center, tab: "|", mode: "math") ```tbl C C C C | C C C C. A_3 | A_2 | A_1 | A_0 | Y_3 | Y_2 | Y_1 | Y_0 _ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 0 | 0 | 1 | X | 0 | 0 | 1 | 0 0 | 1 | X | X | 0 | 1 | 0 | 0 1 | X | X | X | 1 | 0 | 0 | 0 ``` ] = Multilevel Combinational Logic In previous sections we have the Sum-of-Products form, which is called two level logic for it contians two levels of logic AND and then OR. IRL, usually there are multiple levels of logic, and they tend to use less hardware than there two level conterparts. Bubble pushing is especiall helpful in analyzing and designing multilevel circuits. == Hardware Reduction Quote from book:(easy to understand) #figure( image("hr_1.png",width:80%) ) #figure( image("hr_2.png",width:50%) ) == Bubble Pushing = X's and Z's Boolean algebra is limited to 1's and 0's ,but IRL there may be illegal and floating values. === Illegal Value: X The symbol X indicates that the circuit node has an unknown or illegal value. This is commonly coursed by a node is being driven to both 0 and 1 at the same time. This is called contention. === Floating Value: Z The symbol Z indicates that a node is being driven neither HIGH nor LOW. The node is said to be floading, high impedance, or high Z. This can be coursed by forget to connect votage to the inputs or assume that an unconneted input is the same as 0. = Karnaugh Maps _Karnough maps_ (or _K-maps_) are a great graphical method for simplifying Boolean equations. K-maps work well for equations up to 4 variables. The order of the variables is in the form of Grey Code. Pules for fingding a minimized equation from a K-map are as follows: - Use the fewest circles necessary to cover all the 1's - All the squares in each circle must contain 1's - Each circle must span a rectangular block that is a power of 2 - Each circle should be as large as possible - A circle may warp around the edges of the K-map - A 1 in a K-map may be circled multiple times if doing so alllows fewer circles to be used The circles in the K-map each represent a prime implicant, and only the variables that have either true form or complementary form (NOT BOTH) in the circle appear in the prime implicant. That is to say, the variables that have both true form and complementary form in the circle are eliminated. == Don't cares X's can also be helpful in the K-maps, they can either be circuled or not, just make sure that the fewest circules are used. = Combinational Building Blocks Combinational logic is often grouped into larger building blocks to build a more complex systems. This is acutally the process of abstraction, we hide the lower part of logic gate details and just focus on the inputs and outputs. == Multiplexers Multiplexers are among the most commonly used combinational circuits. They choose an output from among several possible inputs based on the value of a _select_ signal. A multiplexer is sometimes affectionately called a _mux_. === 2:1 Multiplexer Multiplexer is actually a selector that outputs the votage of the selected input. It can be used as a _lookup table_. === Wider Multiplexers There are some wider multiplexers that accept more than one select signals and more inputs, to be exact, there are $n$ select signals and $2^n$ inputs. == Decoder A decoder has $N$ inputs and $2^n$ outputs, it asserts exactly noe of its outputs depending on the inputs combination. The outputs are called _one-hot_ because exactly one is "Hot" (HIGH) at a given time.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/045.%20opensource.html.typ
typst
opensource.html What Business Can Learn from Open Source August 2005(This essay is derived from a talk at Oscon 2005.)Lately companies have been paying more attention to open source. Ten years ago there seemed a real danger Microsoft would extend its monopoly to servers. It seems safe to say now that open source has prevented that. A recent survey found 52% of companies are replacing Windows servers with Linux servers. [1]More significant, I think, is which 52% they are. At this point, anyone proposing to run Windows on servers should be prepared to explain what they know about servers that Google, Yahoo, and Amazon don't.But the biggest thing business has to learn from open source is not about Linux or Firefox, but about the forces that produced them. Ultimately these will affect a lot more than what software you use.We may be able to get a fix on these underlying forces by triangulating from open source and blogging. As you've probably noticed, they have a lot in common.Like open source, blogging is something people do themselves, for free, because they enjoy it. Like open source hackers, bloggers compete with people working for money, and often win. The method of ensuring quality is also the same: Darwinian. Companies ensure quality through rules to prevent employees from screwing up. But you don't need that when the audience can communicate with one another. People just produce whatever they want; the good stuff spreads, and the bad gets ignored. And in both cases, feedback from the audience improves the best work.Another thing blogging and open source have in common is the Web. People have always been willing to do great work for free, but before the Web it was harder to reach an audience or collaborate on projects.AmateursI think the most important of the new principles business has to learn is that people work a lot harder on stuff they like. Well, that's news to no one. So how can I claim business has to learn it? When I say business doesn't know this, I mean the structure of business doesn't reflect it.Business still reflects an older model, exemplified by the French word for working: travailler. It has an English cousin, travail, and what it means is torture. [2]This turns out not to be the last word on work, however. As societies get richer, they learn something about work that's a lot like what they learn about diet. We know now that the healthiest diet is the one our peasant ancestors were forced to eat because they were poor. Like rich food, idleness only seems desirable when you don't get enough of it. I think we were designed to work, just as we were designed to eat a certain amount of fiber, and we feel bad if we don't.There's a name for people who work for the love of it: amateurs. The word now has such bad connotations that we forget its etymology, though it's staring us in the face. "Amateur" was originally rather a complimentary word. But the thing to be in the twentieth century was professional, which amateurs, by definition, are not.That's why the business world was so surprised by one lesson from open source: that people working for love often surpass those working for money. Users don't switch from Explorer to Firefox because they want to hack the source. They switch because it's a better browser.It's not that Microsoft isn't trying. They know controlling the browser is one of the keys to retaining their monopoly. The problem is the same they face in operating systems: they can't pay people enough to build something better than a group of inspired hackers will build for free.I suspect professionalism was always overrated-- not just in the literal sense of working for money, but also connotations like formality and detachment. Inconceivable as it would have seemed in, say, 1970, I think professionalism was largely a fashion, driven by conditions that happened to exist in the twentieth century.One of the most powerful of those was the existence of "channels." Revealingly, the same term was used for both products and information: there were distribution channels, and TV and radio channels.It was the narrowness of such channels that made professionals seem so superior to amateurs. There were only a few jobs as professional journalists, for example, so competition ensured the average journalist was fairly good. Whereas anyone can express opinions about current events in a bar. And so the average person expressing his opinions in a bar sounds like an idiot compared to a journalist writing about the subject.On the Web, the barrier for publishing your ideas is even lower. You don't have to buy a drink, and they even let kids in. Millions of people are publishing online, and the average level of what they're writing, as you might expect, is not very good. This has led some in the media to conclude that blogs don't present much of a threat-- that blogs are just a fad.Actually, the fad is the word "blog," at least the way the print media now use it. What they mean by "blogger" is not someone who publishes in a weblog format, but anyone who publishes online. That's going to become a problem as the Web becomes the default medium for publication. So I'd like to suggest an alternative word for someone who publishes online. How about "writer?"Those in the print media who dismiss the writing online because of its low average quality are missing an important point: no one reads the average blog. In the old world of channels, it meant something to talk about average quality, because that's what you were getting whether you liked it or not. But now you can read any writer you want. So the average quality of writing online isn't what the print media are competing against. They're competing against the best writing online. And, like Microsoft, they're losing.I know that from my own experience as a reader. Though most print publications are online, I probably read two or three articles on individual people's sites for every one I read on the site of a newspaper or magazine.And when I read, say, New York Times stories, I never reach them through the Times front page. Most I find through aggregators like Google News or Slashdot or Delicious. Aggregators show how much better you can do than the channel. The New York Times front page is a list of articles written by people who work for the New York Times. Delicious is a list of articles that are interesting. And it's only now that you can see the two side by side that you notice how little overlap there is.Most articles in the print media are boring. For example, the president notices that a majority of voters now think invading Iraq was a mistake, so he makes an address to the nation to drum up support. Where is the man bites dog in that? I didn't hear the speech, but I could probably tell you exactly what he said. A speech like that is, in the most literal sense, not news: there is nothing new in it. [3]Nor is there anything new, except the names and places, in most "news" about things going wrong. A child is abducted; there's a tornado; a ferry sinks; someone gets bitten by a shark; a small plane crashes. And what do you learn about the world from these stories? Absolutely nothing. They're outlying data points; what makes them gripping also makes them irrelevant.As in software, when professionals produce such crap, it's not surprising if amateurs can do better. Live by the channel, die by the channel: if you depend on an oligopoly, you sink into bad habits that are hard to overcome when you suddenly get competition. [4]WorkplacesAnother thing blogs and open source software have in common is that they're often made by people working at home. That may not seem surprising. But it should be. It's the architectural equivalent of a home-made aircraft shooting down an F-18. Companies spend millions to build office buildings for a single purpose: to be a place to work. And yet people working in their own homes, which aren't even designed to be workplaces, end up being more productive.This proves something a lot of us have suspected. The average office is a miserable place to get work done. And a lot of what makes offices bad are the very qualities we associate with professionalism. The sterility of offices is supposed to suggest efficiency. But suggesting efficiency is a different thing from actually being efficient.The atmosphere of the average workplace is to productivity what flames painted on the side of a car are to speed. And it's not just the way offices look that's bleak. The way people act is just as bad.Things are different in a startup. Often as not a startup begins in an apartment. Instead of matching beige cubicles they have an assortment of furniture they bought used. They work odd hours, wearing the most casual of clothing. They look at whatever they want online without worrying whether it's "work safe." The cheery, bland language of the office is replaced by wicked humor. And you know what? The company at this stage is probably the most productive it's ever going to be.Maybe it's not a coincidence. Maybe some aspects of professionalism are actually a net lose.To me the most demoralizing aspect of the traditional office is that you're supposed to be there at certain times. There are usually a few people in a company who really have to, but the reason most employees work fixed hours is that the company can't measure their productivity.The basic idea behind office hours is that if you can't make people work, you can at least prevent them from having fun. If employees have to be in the building a certain number of hours a day, and are forbidden to do non-work things while there, then they must be working. In theory. In practice they spend a lot of their time in a no-man's land, where they're neither working nor having fun.If you could measure how much work people did, many companies wouldn't need any fixed workday. You could just say: this is what you have to do. Do it whenever you like, wherever you like. If your work requires you to talk to other people in the company, then you may need to be here a certain amount. Otherwise we don't care.That may seem utopian, but it's what we told people who came to work for our company. There were no fixed office hours. I never showed up before 11 in the morning. But we weren't saying this to be benevolent. We were saying: if you work here we expect you to get a lot done. Don't try to fool us just by being here a lot.The problem with the facetime model is not just that it's demoralizing, but that the people pretending to work interrupt the ones actually working. I'm convinced the facetime model is the main reason large organizations have so many meetings. Per capita, large organizations accomplish very little. And yet all those people have to be on site at least eight hours a day. When so much time goes in one end and so little achievement comes out the other, something has to give. And meetings are the main mechanism for taking up the slack.For one year I worked at a regular nine to five job, and I remember well the strange, cozy feeling that comes over one during meetings. I was very aware, because of the novelty, that I was being paid for programming. It seemed just amazing, as if there was a machine on my desk that spat out a dollar bill every two minutes no matter what I did. Even while I was in the bathroom! But because the imaginary machine was always running, I felt I always ought to be working. And so meetings felt wonderfully relaxing. They counted as work, just like programming, but they were so much easier. All you had to do was sit and look attentive.Meetings are like an opiate with a network effect. So is email, on a smaller scale. And in addition to the direct cost in time, there's the cost in fragmentation-- breaking people's day up into bits too small to be useful.You can see how dependent you've become on something by removing it suddenly. So for big companies I propose the following experiment. Set aside one day where meetings are forbidden-- where everyone has to sit at their desk all day and work without interruption on things they can do without talking to anyone else. Some amount of communication is necessary in most jobs, but I'm sure many employees could find eight hours worth of stuff they could do by themselves. You could call it "Work Day."The other problem with pretend work is that it often looks better than real work. When I'm writing or hacking I spend as much time just thinking as I do actually typing. Half the time I'm sitting drinking a cup of tea, or walking around the neighborhood. This is a critical phase-- this is where ideas come from-- and yet I'd feel guilty doing this in most offices, with everyone else looking busy.It's hard to see how bad some practice is till you have something to compare it to. And that's one reason open source, and even blogging in some cases, are so important. They show us what real work looks like.We're funding eight new startups at the moment. A friend asked what they were doing for office space, and seemed surprised when I said we expected them to work out of whatever apartments they found to live in. But we didn't propose that to save money. We did it because we want their software to be good. Working in crappy informal spaces is one of the things startups do right without realizing it. As soon as you get into an office, work and life start to drift apart.That is one of the key tenets of professionalism. Work and life are supposed to be separate. But that part, I'm convinced, is a mistake.Bottom-UpThe third big lesson we can learn from open source and blogging is that ideas can bubble up from the bottom, instead of flowing down from the top. Open source and blogging both work bottom-up: people make what they want, and the best stuff prevails.Does this sound familiar? It's the principle of a market economy. Ironically, though open source and blogs are done for free, those worlds resemble market economies, while most companies, for all their talk about the value of free markets, are run internally like communist states.There are two forces that together steer design: ideas about what to do next, and the enforcement of quality. In the channel era, both flowed down from the top. For example, newspaper editors assigned stories to reporters, then edited what they wrote.Open source and blogging show us things don't have to work that way. Ideas and even the enforcement of quality can flow bottom-up. And in both cases the results are not merely acceptable, but better. For example, open source software is more reliable precisely because it's open source; anyone can find mistakes.The same happens with writing. As we got close to publication, I found I was very worried about the essays in Hackers & Painters that hadn't been online. Once an essay has had a couple thousand page views I feel reasonably confident about it. But these had had literally orders of magnitude less scrutiny. It felt like releasing software without testing it.That's what all publishing used to be like. If you got ten people to read a manuscript, you were lucky. But I'd become so used to publishing online that the old method now seemed alarmingly unreliable, like navigating by dead reckoning once you'd gotten used to a GPS.The other thing I like about publishing online is that you can write what you want and publish when you want. Earlier this year I wrote something that seemed suitable for a magazine, so I sent it to an editor I know. As I was waiting to hear back, I found to my surprise that I was hoping they'd reject it. Then I could put it online right away. If they accepted it, it wouldn't be read by anyone for months, and in the meantime I'd have to fight word-by-word to save it from being mangled by some twenty five year old copy editor. [5]Many employees would like to build great things for the companies they work for, but more often than not management won't let them. How many of us have heard stories of employees going to management and saying, please let us build this thing to make money for you-- and the company saying no? The most famous example is probably <NAME>, who originally wanted to build microcomputers for his then-employer, HP. And they turned him down. On the blunderometer, this episode ranks with IBM accepting a non-exclusive license for DOS. But I think this happens all the time. We just don't hear about it usually, because to prove yourself right you have to quit and start your own company, like Wozniak did.StartupsSo these, I think, are the three big lessons open source and blogging have to teach business: (1) that people work harder on stuff they like, (2) that the standard office environment is very unproductive, and (3) that bottom-up often works better than top-down.I can imagine managers at this point saying: what is this guy talking about? What good does it do me to know that my programmers would be more productive working at home on their own projects? I need their asses in here working on version 3.2 of our software, or we're never going to make the release date.And it's true, the benefit that specific manager could derive from the forces I've described is near zero. When I say business can learn from open source, I don't mean any specific business can. I mean business can learn about new conditions the same way a gene pool does. I'm not claiming companies can get smarter, just that dumb ones will die.So what will business look like when it has assimilated the lessons of open source and blogging? I think the big obstacle preventing us from seeing the future of business is the assumption that people working for you have to be employees. But think about what's going on underneath: the company has some money, and they pay it to the employee in the hope that he'll make something worth more than they paid him. Well, there are other ways to arrange that relationship. Instead of paying the guy money as a salary, why not give it to him as investment? Then instead of coming to your office to work on your projects, he can work wherever he wants on projects of his own.Because few of us know any alternative, we have no idea how much better we could do than the traditional employer-employee relationship. Such customs evolve with glacial slowness. Our employer-employee relationship still retains a big chunk of master-servant DNA. [6]I dislike being on either end of it. I'll work my ass off for a customer, but I resent being told what to do by a boss. And being a boss is also horribly frustrating; half the time it's easier just to do stuff yourself than to get someone else to do it for you. I'd rather do almost anything than give or receive a performance review.On top of its unpromising origins, employment has accumulated a lot of cruft over the years. The list of what you can't ask in job interviews is now so long that for convenience I assume it's infinite. Within the office you now have to walk on eggshells lest anyone say or do something that makes the company prey to a lawsuit. And God help you if you fire anyone.Nothing shows more clearly that employment is not an ordinary economic relationship than companies being sued for firing people. In any purely economic relationship you're free to do what you want. If you want to stop buying steel pipe from one supplier and start buying it from another, you don't have to explain why. No one can accuse you of unjustly switching pipe suppliers. Justice implies some kind of paternal obligation that isn't there in transactions between equals.Most of the legal restrictions on employers are intended to protect employees. But you can't have action without an equal and opposite reaction. You can't expect employers to have some kind of paternal responsibility toward employees without putting employees in the position of children. And that seems a bad road to go down.Next time you're in a moderately large city, drop by the main post office and watch the body language of the people working there. They have the same sullen resentment as children made to do something they don't want to. Their union has exacted pay increases and work restrictions that would have been the envy of previous generations of postal workers, and yet they don't seem any happier for it. It's demoralizing to be on the receiving end of a paternalistic relationship, no matter how cozy the terms. Just ask any teenager.I see the disadvantages of the employer-employee relationship because I've been on both sides of a better one: the investor-founder relationship. I wouldn't claim it's painless. When I was running a startup, the thought of our investors used to keep me up at night. And now that I'm an investor, the thought of our startups keeps me up at night. All the pain of whatever problem you're trying to solve is still there. But the pain hurts less when it isn't mixed with resentment.I had the misfortune to participate in what amounted to a controlled experiment to prove that. After Yahoo bought our startup I went to work for them. I was doing exactly the same work, except with bosses. And to my horror I started acting like a child. The situation pushed buttons I'd forgotten I had.The big advantage of investment over employment, as the examples of open source and blogging suggest, is that people working on projects of their own are enormously more productive. And a startup is a project of one's own in two senses, both of them important: it's creatively one's own, and also economically ones's own.Google is a rare example of a big company in tune with the forces I've described. They've tried hard to make their offices less sterile than the usual cube farm. They give employees who do great work large grants of stock to simulate the rewards of a startup. They even let hackers spend 20% of their time on their own projects.Why not let people spend 100% of their time on their own projects, and instead of trying to approximate the value of what they create, give them the actual market value? Impossible? That is in fact what venture capitalists do.So am I claiming that no one is going to be an employee anymore-- that everyone should go and start a startup? Of course not. But more people could do it than do it now. At the moment, even the smartest students leave school thinking they have to get a job. Actually what they need to do is make something valuable. A job is one way to do that, but the more ambitious ones will ordinarily be better off taking money from an investor than an employer.Hackers tend to think business is for MBAs. But business administration is not what you're doing in a startup. What you're doing is business creation. And the first phase of that is mostly product creation-- that is, hacking. That's the hard part. It's a lot harder to create something people love than to take something people love and figure out how to make money from it.Another thing that keeps people away from starting startups is the risk. Someone with kids and a mortgage should think twice before doing it. But most young hackers have neither.And as the example of open source and blogging suggests, you'll enjoy it more, even if you fail. You'll be working on your own thing, instead of going to some office and doing what you're told. There may be more pain in your own company, but it won't hurt as much.That may be the greatest effect, in the long run, of the forces underlying open source and blogging: finally ditching the old paternalistic employer-employee relationship, and replacing it with a purely economic one, between equals. Notes[1] Survey by Forrester Research reported in the cover story of Business Week, 31 Jan 2005. Apparently someone believed you have to replace the actual server in order to switch the operating system.[2] It derives from the late Latin tripalium, a torture device so called because it consisted of three stakes. I don't know how the stakes were used. "Travel" has the same root.[3] It would be much bigger news, in that sense, if the president faced unscripted questions by giving a press conference.[4] One measure of the incompetence of newspapers is that so many still make you register to read stories. I have yet to find a blog that tried that.[5] They accepted the article, but I took so long to send them the final version that by the time I did the section of the magazine they'd accepted it for had disappeared in a reorganization.[6] The word "boss" is derived from the Dutch baas, meaning "master."Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this.French TranslationRussian TranslationJapanese TranslationSpanish TranslationArabic Translation
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/031%20-%20Hour%20of%20Devastation/002_Feast.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Feast", set_name: "Hour of Devastation", story_date: datetime(day: 14, month: 06, year: 2017), author: "<NAME>", doc ) #emph["And so the Hour of Revelation broke upon the land, and the promised time arrived when all questions would be answered. And lo, the Gate to the Afterlife opened, and from behind its gleaming walls, the true visage of the coming tide poured forth."] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Liliana moved her foot back from the lapping crimson of the Luxa River. Razaketh's taunts rang in her ears, and she sighed. #emph[I'm too old for this nonsense.] She rolled out her shoulders and pulled her hair back. What Liliana felt in that moment was neither fear nor excitement. It was anticipation. All things considered, the first two demons had been easy to defeat. Surprise and the suddenness of her attacks had played to her favor. How fortunate that she had the best backup in the Multiverse. #emph[Jace? Can you hear me? ] Distantly in her mind, she heard a response. #emph[Lili? Where are you! We're coming! The crowd] #emph[—] #emph[—] #emph[was too large, I know. I'm on the bank of the river, before the gate. Jace, it's Razaketh, he's] #emph[—] "Where are you, #emph[crone] ?" The demon's voice again boomed out. Around her, the remaining crowd murmured. Those who hadn't run away stood rooted to the spot, trembling in fear and uncertain of what was going on. Liliana furrowed her brow. She knew he'd be the type to toy with her. She wouldn't allow herself to be baited into action that easily. "Liliana, I know you're here . . ." She slinked among the lingering people, her eyes following the dark figure gliding in lazy circles high above the river. Razaketh flew to the open gate and scanned the crowd. Liliana felt her hand twitch. She looked down in surprise. The movement of her hand had been . . . involuntary. Liliana held her right hand up to her face, a wave of dread crashing into her chest. Her own fingers waved back at her. Liliana made a loud noise of disgust and shook her hand out. It was a scare tactic, that's all. #emph[She ] refused to feel fear. Liliana purposefully thrust the same hand down toward the left side of her dress, toward the Chain Veil. The demon upon the gate laughed. "There you are." His words sent a chill down her neck. Out of the corner of her eye, Liliana saw the rest of the Gatewatch arrive. They looked worse for wear, bodies bruised from the melee of the arena. Jace moved toward Liliana's side, but she threw up a cautionary hand. The four others stopped around her, all gazing up at the demon. "I do not know the extent of his abilities," Liliana whispered, her voice urgent and low. "But he's powerful. We should . . ." Liliana abruptly stopped speaking. The demon lowered his wings. His words—smooth, steady, #emph[calm—] #emph[poured over the crowd] . #emph["] #emph[Come to me] #emph[."] As soon as his words hit her ears, Liliana felt her shoulders draw back and her face fall slack. The labyrinth of tattoos that covered her skin alit with the demon's call, and she screamed in the privacy of her mind as, without urging or permission, her body waded forward into the river of blood. #figure(image("002_Feast/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) In her long life, Liliana had withstood a number of tortures. She had fought, lost, aged, willfully signed away her soul, and more. But nothing was as unbearable or enraging as a loss of control. She had thought she knew the repercussions when she formed those contracts with her demons decades before, but Liliana had never truly envisioned the outcome. Rage wasn't an emotion Liliana liked to experience with any frequency. It was a too-hot bath, an uncontrolled flame, an itchy dress that never felt like her own. But as the demon Razaketh urged her body onward, Liliana bore her rage as a banner. She reveled in its churning fury and fought and tugged with all the might of her mind to seize control of herself. But it was to no avail. No matter how much she mentally fought, her hate never reached her face. Her anger never pulled at her muscles. Liliana had no control over the one thing that was ever actually #emph[hers] . #emph[Damn it all to the depths of the hells!] She railed and screamed in her own mind, but the tether between her will and her limbs remained severed. #emph[Chandra and Nissa reached out to pull Liliana's wandering body back, and a flare of necromantic energy pushed back their hands. The two women recoiled back, hands withdrawn before the decay and rot seized them.] #emph[In Liliana's head, she could hear Jace yelling, and in her ears Gideon's voice echoed, but her attention remained fixed on Razaketh before her.] #emph[Go to him] was the only command her body knew. The Chain Veil remained tucked away, the demon too close, her allies unable to halt the urge to wade forward. She wanted to tear the demon's eyes out and swallow them whole. Liliana screamed obscenity after obscenity in her mind, hoping that her cascade of curses would make the demon relinquish his hold. But the hold stayed. Liliana waded into the blood of the Luxa. It felt hot, viscous, utterly vile. Her body kept walking, wading deeper and deeper into the river. To her hips. To her waist. To her sternum. Liliana's thoughts turned from raging protest to an endless scream. She felt her leg graze something dead under the water. A fish floated past her shoulder. The river was full of freshly dead wildlife, all choked by the blood of Razaketh's ritual. Nothing living survived in the blood mire. Jace's voice faded in her mind. She was too far out, too deep in the river. Liliana took a breath and felt her head dip below the surface. The liquid was cloying and thick, its temperature hot against her skin. Her heart beat fast and frightened. #emph[I will not be afraid. He is weaker than I am, and I can survive this.] A voice creaked through her mind: "#emph[You can only survive this if you ] #strong[kill] #strong[him] #strong[.] #emph["] The Raven Man. Liliana screamed. #emph[Get out! Not now! I do not want to hear from you!] #emph["You are only free if you kill each of your demons, Liliana. Only then will I leave you be."] Liliana didn't have time to think that over. She was running out of air. With growing urgency, she wanted to inhale, even though she knew she would just drown on mouthfuls of blood, but the demon's control of her body overrode her impulses even for breath. Just as she was sure she'd lose consciousness, her body swam itself to the surface, and she gasped for air. She had crossed the river and crawled onto the opposite bank. She looked up, blinking through sticking eyelashes, to the base of the Necropolis just beyond the Gate to the Afterlife. Razaketh stood above her on a stone platform, his face as smug and obnoxious as Liliana remembered. A part of her felt foolish. No other demon wielded this sort of control over her body. How could she fight someone who could maneuver her like a puppet? What kind of tactic could she use to #emph[fight] #emph[that] ? Razaketh looked down. His face was reptilian and unreadable, but he seemed pleased all the same to encounter his contractor. Where Kothophed and Griselbrand were distant, Razaketh was #emph[playful] . "What a delightful surprise," the demon purred. He motioned with his hand for Liliana to rise from the silt, and without hesitation, her body did it for her, kneeling in the muck. Her dress stuck to her sides, and the blood began to crust in the heat of the sun. Liliana could feel that this position would cramp her feet, but she was unable to shift or move. She instead focused on her breath, heaving in a rhythm not her own, and tried to tame her panic into determination. The demon stepped forward and studied his subject. "Old age never suited you." Razaketh leered with a reptilian smile. Liliana wanted to rip the look from his face. "I'm glad you've been reaping the benefits of our deal," the demon said, eyeing the blood on Liliana's dress. "I do apologize for the mess I've made. A dear friend left an assignment for me to fulfill." Razaketh looked to the second sun. "You were very fortunate to arrive when you did. You get to see the show! I'm excited to see it myself. It is a surprise for me, too, you know." If Liliana could have jumped she would have. A little patter of rain suddenly chimed in the back of her mind— #emph[Liliana! We see you. We're coming!] Never had Liliana been so relieved to hear Jace in her head. Razaketh hadn't seemed to notice, and she was briefly thankful for not being in control of the expression on her face. Oblivious, the demon continued to toy with her. "I apologize for the forcefulness, Liliana, but I love a dog who comes when she is called. And you're a good dog, aren't you?" He held out a lazy finger and tapped it. Liliana felt her head nod. Her muscles strained and cramped as she tried to resist the urge, but her head tipped forward . . . then back . . . forward . . . then back. Razaketh smiled, putting his hand down. "Good." He went quiet and considered her for a moment. A smug look pulled at the scales of his face as he thought over his next command. "#emph[Bark.] #emph["] "Woof," Liliana replied in a tone that could ice over the sun. Razaketh made a small noise of displeasure. "You really ought to read contracts before you sign them, you know. People hide all #emph[sorts ] of nasty clauses into them. The other co-authors were so straightforward, but I like a little flair in my dealings." Razaketh tipped his chin, and without warning, Liliana's right hand balled into a fist and rushed toward her own face. It halted a hair's width from her left eye. Her face was frozen in the emotionless expression of obedience, but internally she squirmed. Satisfied with his demonstration, Razaketh silently urged Liliana to put her fist down. As her body obeyed, Liliana's mind reached back down the river, assessing how many dead things remained choked and buried in the blood behind her. Razaketh straightened himself and puffed his chest. "Now then, crone, tell me what you came here for." Liliana's jaw popped with returned agency. She shifted it from side to side. The rest of her was still out of reach, but at least her words were again #emph[hers.] She made them count. "You have five more minutes to live," Liliana said, voice dripping with resolution. "You will watch me as I kill you." Razaketh laughed. "Five minutes. How precise." Liliana's expression didn't change. "I'm a very punctual person." "I doubt that." "I killed Kothophed and Griselbrand," Liliana replied with a ghost of a smile. "It was easy." Razaketh scoffed. "They were idiots." Liliana smiled. "You're not wrong." The demon considered her. "I won't kill you. But I could maim you," Razaketh mused, toying with a knife at his hip. "I could have you do it yourself." Liliana tipped her chin. "Four minutes." Razaketh laughed. Jace's voice appeared in Liliana's mind once more. #emph[Don't move.] Internally, Liliana sighed. #emph[Is that a joke?] A pause. #emph[Maybe] #emph[.] Liliana's attention returned to the demon standing tall over her. An awkward silence ensued. "Did you really have nothing more than an idle, empty threat? I'm almost disappointed." Razaketh made a show of shaking his head. Jace's voice suddenly bloomed again in Liliana's mind, laced with panic. #emph[Wait, Chandra, don't rush ahead] — "Four minutes is a bit long, isn't it?" Liliana said aloud with a coy smile. The demon scowled. Liliana grinned. "How about . . . now?" From somewhere behind Razaketh's head, a jet of fire engulfed the demon. Razaketh screamed. Relief flooded Liliana as control of her body returned. She rushed to her feet, the blood of the river still dripping down her dress, and looked to the source of the fire. Chandra funneled a blaze at Razaketh's screeching body, leaving the demon writhing, his tail whipping wildly as he tried to fight his way through the fire. The demon unfurled his wings and launched into the air. He barreled down at Chandra at full speed and rammed into her side, knocking the pyromancer into the side of the Necropolis with a bruising #emph[thud] . Liliana reached a hand back toward the river, drawing on her powers, but Razaketh turned back on her with a snarl. "I don't think so," the demon roared, and Liliana felt her shoulder dislocate itself. Her scream was immediate, half pain and half fury, and then she felt her voice forcibly vanish. Razaketh stood, hand out and brow furrowed, again seizing control. A sudden whip of sand, rock, and reeds barreled into the side of the concentrating demon. A massive elemental emerged, its body forming from the banks of the river. As it rose, rivulets of well water untouched by the blood spell cascaded from it. With Razaketh's concentration broken, Liliana again shuddered with returned control. She wasted no time popping her shoulder back into place with a groan, then once more thrust her hand toward the river, dark energy rippling through her as she wove her spell. Injured and surprised, Razaketh scratched and clawed to get away from the elemental and back into the sky. Behind him, Nissa helped Chandra to her feet, keeping an eye on her elemental. As Razaketh ripped a massive chunk of earth from the elemental's torso, he thrust a clawed hand at Liliana to regain control. The exertion only half-worked—Liliana's legs gave out, but her body remained her own. The elemental battered the demon again, and Razaketh turned his full fury on the creature. He ripped off clumps of mud and tore reeds from its sides. He growled and spat and broke a crack in its side with his tail. As he raised a fist to deliver the final blow, he was bathed in flames once again—Chandra, standing once more, let loose a flurry of fireballs at the demon. Liliana felt her right side go limp, and she fell to the ground. Razaketh had one hand trained toward her, the other pinning Nissa's elemental to the ground. Liliana panted against the earth and felt the sand in her teeth. In the distance, she saw the elemental hit the ground. Nissa had retreated behind another part of the Necropolis—she was clearly having trouble maintaining enough mana to keep the elemental active. Razaketh had flown up now and was dodging Chandra's flames with ease. #emph[Jace! ] Liliana yelled in her mind. But as the word formed in her mind, she halted. Her breath had stopped. She tried to suck in air, but her diaphragm was completely still. Liliana tried again but found herself unable to #emph[breathe] #emph[.] Razaketh landed in front of her, facing away from Liliana, taunting Chandra. Liliana saw Chandra in the distance behind him taking aim at the demon. She realized that Chandra was unable to see her lying on the ground. Liliana couldn't breathe. She couldn't move. And the pyromancer was taking aim at the demon standing directly above her. #emph[JACE!] Jace's voice reappeared in her mind, frantic and distracted. #emph[Gideon on your left!] Liliana twitched as she felt an invisible hand grab her shoulder. Jace must have camouflaged Gideon to help him get closer to her position. She watched as Gideon's sural flashed into view, carving three thick lines in Razaketh's back. The demon howled in pain, and Liliana coughed and inhaled a deep and desperate breath speckled with sand. She sat up on her elbows and caught her breath between gasps. Gideon's voice growled in her ear. "Make it fast." "I intend to," Liliana croaked. She felt bright, unfamiliar magic envelop the area around her. Gideon had extended his invulnerability, creating a safe barrier between her and the demon. A moment later, the air around her was engulfed in flames. Liliana could see Gideon crouching above her now, wreathing his magic around the two of them, a golden dome shielding them from the inferno. Razaketh stumbled forward through the flames, flailing widely before being tackled by a second elemental. The elemental pinned the demon to the ground, and Razaketh roared, his skin blistering from Chandra's pyromantic bombardment. Liliana stood. She walked forward with Gideon standing at her back, still maintaining his shielding invulnerability. Liliana sensed a third twinge of magic—Jace must have made them invisible to Razaketh's eye. #emph[Jace,] #emph[I need you to interrupt his control over me.] Jace's voice resounded with frustration. #emph[What do you think I've been trying to do for the last ten minutes?] She didn't have time for this. #emph[Drop the invisibility and focus on that while he's distracted!] Razaketh's eyes went unfocused. #emph[Got him, move fast, ] Jace said, his mental voice full of strain. "Forward, Gideon!" Liliana asserted. Liliana walked forward into the wall of flames, blood dripping from her body and sizzling as it hit the ground. Gideon's hand went to her shoulder to strengthen the magic that protected the two of them. Behind the barrier of invulnerability, the heat of the inferno came across as pleasantly warm. Comfortable, almost. Liliana squinted her eyes against the light and made out the shape of Razaketh in front of her, wrestling with Nissa's massive elemental of sand and water, his flesh dark and singed by the conflagration around him. Liliana pulled the Chain Veil from her dress. #emph[You don't need that, ] Jace said in her mind, #emph[it will only hurt you] #emph[—] Liliana scowled at Jace's interjection. But then again . . . he was right. She didn't need it for this. Let the demon witness what terror she could wield all on her own. Liliana slipped the veil back into her dress. If the situation became dire she could always pull it back out, but for now she wanted to test her own abilities. The dying demon before her made her feel particularly #emph[indulgent] . "Razaketh," Liliana called. The demon was blistered and pinned to the banks of the river. His face was burned, melting, and wrinkled: a grimace of rage. Liliana held her head high, peering down at Razaketh in a way she hoped he could #emph[feel] . "Watch me as I kill you." She held out her hands and reached her power toward the river. The river boiled and churned with movement. Razaketh's eyes went wide. #emph[Do it now!] #emph[ ] Jace yelled in Liliana's mind. Nearby, he flickered into view, dropping his veil as his mental voice strained#emph[ ] with effort. Liliana looked at him with a start—the mind mage had snuck up closer than she thought. As Jace grimaced, Liliana felt a twitch in her hand as Razaketh struggled to reassert control. With a flick of her wrist, a menagerie of death spilled up and out of the river of blood. Fish, turtles, snakes, hippopotamuses, shorebirds, and drowned antelopes rose out of the crimson Luxa in a writhing mass. Their mouths gaped, their teeth flashed, and they hurled themselves out of the river and toward the charred body of the demon. Liliana moved the mass as she would move her own body. Her control resided over each fin, claw, and tooth that burst up from the thick blood of the river. She felt immense: boundless, magnified, and distributed through waves of risen flesh. She wasn't sure where she ended and the hundreds of dead began. For a fleeting moment, Liliana remembered what it was like to wield godlike power. The demon struggled to pull himself out from under the grip of Nissa's elemental. With a roar and a twist, he broke free and stretched his wings—torn like aged canvas on a rotting frame—and launched into the air again. Liliana sent a burst of necromantic energy at him, and he convulsed as he fell to the ground. Immediately, the morass of undead set upon the demon, fangs and teeth and horns tearing at flesh. Chandra, Gideon, and Nissa turned away from the carnage. But next to Liliana, Jace remained transfixed, unable to look away. Liliana felt him brush against the side of her mind with a cautious touch, asking for an invitation to peer in. Liliana welcomed his mental gaze. #emph[Look Jace, ] she thought, #emph[at what I plan to do next.] Distantly, Liliana heard Jace gag with revulsion behind her. He immediately retreated from her mind, but Liliana didn't care. She was busy. Razaketh howled in pain and was suddenly, violently tugged toward the river. Liliana twisted her hand, and another two dozen crocodiles bellowed and dragged their corpses out onto the bank. His leg trapped in the jaws of one of the beasts, Razaketh tried to rise and crawl away from the river, but it was too late. Liliana released her hold on the other creatures and poured her energy and mind into the bodies of the crocodiles. Strong muscles and sharp teeth. An undead hunger for the flesh of the living. With her consciousness divided among the two dozen dead crocodiles in front of her, she gnashed her teeth and attacked. Her two dozen bellies hungered, and her two dozen jaws opened wide. Without hesitation or humanity, her two dozen selves consumed the last of the demon Razaketh. She feasted, and he #emph[screamed] . The crocodiles dragged the remains of the demon into the river of blood, splashing crimson arcs into the air as their tails violently slapped the surface of the water. They crowded and shoved and dug their teeth into the demon's flesh. Liliana could #emph[feel ] herself getting full. Her two dozen jaws latched onto limbs and spun circles to rip them off clean. Her two dozen mouths spat out blood and devoured the charred flesh. There would be nothing left to stumble back to life. She laughed, and the crocodiles bellowed in tandem. Amonkhet's curse would not get #emph[this ] corpse. While her savage, divided mind ate the demon alive, her own teeth gently ground in subconscious tandem. She laughed and dimly heard Jace heaving behind her. #emph[Liliana, that's enough] #emph[,] Jace pleaded.#emph[ Liliana, he's dead. Please stop.] Liliana swallowed in her own body and tasted nothing. She was panting with exertion. And smiling from ear to ear. She felt sated, relieved, and deliciously monstrous. She didn't want to stop. #emph[Lili, enough.] Liliana lowered her hand and retreated from the bodies of the crocodiles. They lurched, and a moment later, swam upriver of their own reanimated volition. The Curse of Wandering had taken hold. She had done it! Liliana giggled and fell exhausted on the sand. No wine was as sweet as independence, no victory as satisfying as self-governance. Liliana was not a sentimental person, but lying on the bank of the River, staring at the glimmering blue of the Hekma, she found herself feeling as if it was all actually possible. As if she #emph[could ] be free of the control of others and the things that she despised. The assistance of the Gatewatch had provided the means to her end. Just as planned! The wind picked up, and a hot breeze blew her hair out of her face. She saw Jace out of the corner of her eye. He was standing next to her, staring down with an unreadable expression. Liliana could smell his vomit on the ground behind him. "I did it, Jace." Liliana giggled again. "I #emph[ate ] him." Jace was, pointedly, not answering. "The other two demons were a lot easier. They couldn't do to me what he did. And now there's just one more. And then I get myself to myself again." Exhaustion had set in. Liliana knew she wasn't making much sense. She sat up with effort. "Did you throw up?" she asked through tired breath. Jace didn't respond. Gideon, Nissa, and Chandra approached cautiously. They had stood to the side, watching Liliana's revenge from a distance, and walked forward now, battered from the conflict. "Thank you all for your assistance," Liliana said with a breathy, grateful smile. Gideon crossed his arms. "We did what had to be done. Our focus needs now to be on the arrival of Bolas." "Yes," she said, fixing back her hair with a ribbon from her dress. "First, a moment to catch our breath." "We don't have time for rest," Nissa said with uncharacteristic perturbance. "From what I can sense, the bloodspell Razaketh cast has begun a chain reaction of sorceries. 'The Hours' that herald <NAME>'s return needed to be set in motion by the demon." Liliana stood on shaky legs. None of the others offered to help her up. "We'll be better prepared to face him with Razaketh out of the way," Liliana said. "I agree," Gideon said, "but we intervened to #emph[save you] , despite your deception about the demon's presence." "And it worked out well, didn't it?" Liliana countered. Chandra held out her hands to slow the conversation. "We don't have time to argue about what happened. We need to split up and prevent further loss of life." "I . . . agree," Nissa said. She looked at Jace and fell quiet as the two engaged in a silent, mental conversation. In the lull, Gideon took charge. "We need to rally and conserve our strength. If we can, we'll want to ambush <NAME> when he arrives. Let's catch him by surprise instead of the other way around." Gideon looked pointedly at Liliana. Liliana rolled her eyes. She felt no shame for how she took down the demon. Yet she couldn't deny the coldness with which the others regarded her. Gideon was poorly trying to hide a frown. Chandra's mouth was drawn into a stressed, thin line. Nissa openly scowled. Jace seemed most distant of all. "Let us seek a better vantage to prepare for <NAME>'s arrival," Gideon said. They turned and walked back toward the gate, crossing the threshold back into Naktamun. Only Jace lingered behind, looking at Liliana with an inscrutable expression. "Don't look at me like that," Liliana said. Jace didn't blink. "I'm not going to stand by if you lose it like that again." "It was necessary." Liliana shrugged. Jace shook his head. "It was overkill." Liliana scoffed with a smile. "I did what I needed to." She turned, tugging her hair tight and away from her face, and left to join the others. Jace stood for a moment longer. He looked to the stain of blood on the banks of the Luxa and, despite the heat of the afternoon and the sheen of sweat on his forehead, he shivered.
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/typ/embedded-typst/lib.typ
typst
Apache License 2.0
#let typst = plugin("/assets/artifacts/embedded_typst.wasm") #let separator = "\n\n\n\n\n\n\n\n" #let allocate-fonts(data) = (kind: "font", hash: none, data: data) #let create-font-ref(data) = { let data = read(data, encoding: none) let fingerprint = typst.allocate_data(bytes("font"), data) let data = str(typst.encode_base64(data)) (kind: "font", hash: str(fingerprint), data: data) } #let default-fonts() = ( "/assets/typst-fonts/LinLibertine_R.ttf", "/assets/typst-fonts/LinLibertine_RB.ttf", "/assets/typst-fonts/LinLibertine_RBI.ttf", "/assets/typst-fonts/LinLibertine_RI.ttf", "/assets/typst-fonts/NewCMMath-Book.otf", "/assets/typst-fonts/NewCMMath-Regular.otf", "/assets/typst-fonts/NewCM10-Regular.otf", "/assets/typst-fonts/NewCM10-Bold.otf", "/assets/typst-fonts/NewCM10-Italic.otf", "/assets/typst-fonts/NewCM10-BoldItalic.otf", "/assets/typst-fonts/DejaVuSansMono.ttf", "/assets/typst-fonts/DejaVuSansMono-Bold.ttf", "/assets/typst-fonts/DejaVuSansMono-Oblique.ttf", "/assets/typst-fonts/DejaVuSansMono-BoldOblique.ttf", ).map(create-font-ref) #let default-cjk-fonts() = ( "/assets/fonts/SourceHanSerifSC-Regular.otf", "/assets/fonts/SourceHanSerifSC-Bold.otf", ).map(create-font-ref) #let resolve-context(fonts) = { bytes(json.encode((data: (..fonts,)))) } #let make-partial-ref(fonts) = { (fonts.map(e => (kind: e.kind, hash: e.hash)),) } #let _svg-doc(code, fonts) = { // Pass only hash references at first time let partial-ctx = resolve-context(..make-partial-ref(fonts)) let (header, ..pages) = str(typst.svg(partial-ctx, code)).split(separator) // In case of cache miss if not header.starts-with("code-trapped") { return (header, pages) } // Pass full data let full-ctx = resolve-context(fonts) let (header, ..pages) = str(typst.svg(full-ctx, code)).split(separator) (header, pages) } #let svg-doc(code, fonts: none) = { let code = bytes(if type(code) == str { code } else { code.text }) if fonts == none { fonts = default-fonts() } let (header, pages) = _svg-doc(code, fonts) (header: json.decode(header), pages: pages) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix-alignment_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test alternating explicit alignment in a matrix. $ mat( "a" & "a a a" & "a a"; "a a" & "a a" & "a"; "a a a" & "a" & "a a a"; ) $
https://github.com/WinstonMDP/math
https://raw.githubusercontent.com/WinstonMDP/math/main/exers/5.typ
typst
#import "../cfg.typ": * #show: cfg $ "Prove that" a^(x_1) a^(x_2) = a^(x_1 + x_2) $ $lim_(QQ in.rev r -> x_1 + x_2) a^r = a^(x_1 + x_2)$ $all(epsilon > 0) ex(delta > 0) all(r_1\, r_2 in QQ): 0 < abs((x_1 + x_2) - (r_1 + r_2)) < delta -> abs(a^(x_1 + x_2) - a^(r_1 + r_2)) < epsilon$ $all(epsilon > 0) ex(delta > 0) all(r_1\, r_2 in QQ): 0 < abs(x_1 - r_1) < delta -> 0 < abs(x_2 - r_2) < delta -> abs(a^(x_1) - a^(r_1)), abs(a^(x_2) - a^(r_2))< epsilon$ $all(epsilon > 0) ex(delta > 0) all(r_1\, r_2 in QQ): 0 < abs(x_1 - r_1) < delta -> 0 < abs(x_2 - r_2) < delta -> abs(a^(x_1) a^(x_2) - a^(r_1 + r_2)) < epsilon (a^(x_1) + a^(x_2) + epsilon)$ $all(epsilon > 0) ex(delta > 0) all(r_1\, r_2 in QQ): 0 < abs(x_1 - r_1) < delta -> 0 < abs(x_2 - r_2) < delta -> abs(a^(x_1) a^(x_2) - a^(r_1 + r_2)) < epsilon$ I'm proving that $all(epsilon > 0): abs(a^(x_1) a^(x_2) - a^(x_1 + x_2)) < epsilon$ $ex(delta > 0) all(r_1\, r_2 in QQ): 0 < abs((x_1 + x_2) - (r_1 + r_2)) < delta -> abs(a^(x_1 + x_2) - a^(r_1 + r_2)) < epsilon/2$ $ex(delta' > 0) all(r_1\, r_2 in QQ): 0 < abs(x_1 - r_1) < delta' -> 0 < abs(x_2 - r_2) < delta' -> abs(a^(x_1) a^(x_2) - a^(r_1 + r_2)) < epsilon/2$ $ex(r_1\, r_2) in QQ: 0 < abs(x_1 - r_1), abs(x_2 - r_2) < min(delta, delta')/2$ $0 < abs((x_1 + x_2) - (r_1 + r_2)) < min(delta, delta')$
https://github.com/El-Naizin/cv
https://raw.githubusercontent.com/El-Naizin/cv/main/modules_en/skills.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #set par( leading: 100pt, ) #cvSection("Skills") #cvSkill( type: [Languages], info: [Fluent English #hBar() Fluent French #hBar() Learning German] ) #v(7pt) #cvSkill( type: [Tech Stack], info: [Rust #hBar() Python #hBar() C/C++ #hBar() Java #hBar() And More] ) #v(7pt) #cvSkill( type: [Misc.], info: [Latex #hBar() Typst #hBar() VIM #hBar() Proficient with Linux, MacOS and Windows] ) #v(7pt) #cvSkill( type: [Personal Interests], info: [Swimming #hBar() Operating Systems #hBar() Cooking and Baking] )
https://github.com/stepbrobd/cv
https://raw.githubusercontent.com/stepbrobd/cv/master/cv.typ
typst
MIT License
#let cv(address: none, contact: none, links: none, body) = [ #set document(author: contact.name, title: contact.name) #set text(font: "New Computer Modern", lang: "en", size: 10pt) #show link: underline #set page( paper: "us-letter", margin: (x: 1in, y: 1in), header: locate( loc => if [#loc.page()] == [1] [ #h(1fr) #text( gray, )[#datetime.today().display("[month repr:short]. [day padding:none], [year]")] ] else [ #h(1fr) #text(gray)[#contact.name] ], ), footer: [ #h(1fr) #text(gray)[#counter(page).display("1/1", both: true)] ], ) #align( center, )[ #block(heading(level: 1, upper(contact.name))) #block( text[ #address.line1, #address.line2, #address.city, #address.state #address.zip ], ) #block( text[ #link("mailto:" + contact.email)[#contact.email] #h(10%) #link("tel:" + contact.phone)[#contact.phone] ], ) #grid(for i in range(links.len()) { link(links.at(i).url)[#links.at(i).display] + h(10%) } + h(-10%)) ] #body ] #let section(name: none, body) = [ #heading(level: 2, upper(name)) #line(length: 100%) #body ] #let interests(body) = [ #body ] #let education(institution: none, degree: none, attended: none, location: none, body) = [ #heading(level: 3, [#institution #h(1fr) #degree]) #text(attended + h(1fr) + location) #body ] #let employment(position: none, company: none, worked: none, body) = [ #heading( level: 3, [#position, #company #h(1fr) #text(size: 10pt, weight: "regular", worked)], ) #body ] #let project(name: none, display: none, url: none, body) = [ #heading( level: 3, [#name #h(1fr) #link(url)[#text(size: 10pt, weight: "regular", display)]], ) #body ] #let publications(path: none, bold: none) = [ #show bold: name => text(weight: "bold", name) #bibliography(title: none, style: "ieee", full: true, path) ]
https://github.com/LuSterM1126/MySQL_COA
https://raw.githubusercontent.com/LuSterM1126/MySQL_COA/main/COA.typ
typst
// #import "@preview/fuzzy-cnoi-statement:0.1.0": *; // #import "fuzzy-cnoi-statement/template.typ": *; #set text(font: ("Consolas", "Microsoft YaHei")) #set par(first-line-indent: 4em) #let trans(cn, en) = [#strong([#cn (#emph([#en]))])] #let indent = h(2em) // #set heading(numbering: "1.") #set par(first-line-indent: 2em) #let fake-par = style(styles => { let b = par[#box()] let t = measure(b + b, styles); b v(-t.height) }) #show heading: it => { it fake-par } = 计算机组成 == 简单计算机模型 === CPU 基本组成 1. 基本知识:负责提取程序指令,并对指令进行译码,然后按程序规定的顺序对正确的数据执行各种操作 2. 基本组成: 1. 数据通道:它由存储单元 #[(寄存器)] 和算数逻辑单元 #[(对数据执行各种操作)] 所组成的网络。这些组件通过总线 #[(传递数据的电子线路)] 连接起来,并利用时钟来控制事件。 2. 控制单元:该模块负责对各种操作进行排序并保证各种正确的数据适时地出现在所需的地方。 ==== _Register_ - 寄存器 - 寄存器 是一种存储二进制数据的硬件设备,位于处理器的内部,因此处理器可以快速访问寄存器中存储的各种信息。 - 计算机通常处理的是一些存储在寄存器中,具有固定大小的二进制字的数据。 - 可以向寄存器写入或读取信息,信息也可以在不同的寄存器中传递。寄存器的编址方式与存储器不同,寄存器是由 CPU 内部的控制单元进行编址和处理。 - 现代计算机系统中由各种不同类型的专用寄存器,或者只能存储数据,只能存放地址或各种控制信息。还有一些通用寄存器,可以在不同时刻存储不同信息。 ==== _ALU_ - 算术逻辑单元 - 算术逻辑单元 在程序执行过程中用于进行逻辑运算。ALU 的各种操作存储会影响状态寄存器的某些数据位的数值。通过控制单元发出的信号,控制 ALU 执行各种运算。 ==== _Control Unit_ - 控制单元 - 控制单元 负责监视所有指令的执行和各种信息的传送过程。 - 控制单元负责从内存提取指令,对这些指令进行译码,确保数据适时出现在正确的位置。 - 控制单元还负责通知 ALU 应该使用哪个寄存器,执行哪些中断服务程序,以及对所需执行的各种操作接通 ALU 中的正确电路。 === _Bus_ - 总线 - 总线 是一组导电线路的组合,它作为一个共享和公用的数据通道将系统内各个子系统连接在一起。 - 总线可以实现 *点对点* #[(*_point-to-point_*)] 的方式连接两个特定设备,或者将总线用作一条 *公用通道* #[(*_common pathway_*)] 来连接多个设备,作为 *多点总线* 使用。 - 系统总线:指 CPU、主存、I/O 设备各大部件之间的信息传输线 - 典型系统总线: 1. *数据总线 #[(_data bus_)]*:用于数据传递的总线,数据总线传递的是必须在计算机的不 同位置之间移动的实际信息。 2. *控制总线 #[(_control line_)]*:计算机通过控制总线指示哪个设备允许使用总线,以及 使用总线的目的。 > 控制总线也传递有关总线请求、终端和时钟同步信号的相应信号。 3. *地址总线 #[(_address line_)]*:指出数据读写的位置 - 由于总线传递的信息类型不同,使用设备不同,因此总线还能细分成不同种类。 1. 处理器 - 内存总线 是长度较短的高速总线,这种总线连接处理器和与机器匹配的内存系统,并最大限度地扩充数据传递的带宽。 2. I/O 总线 通常比处理器 - 内存总线长,可以连接带宽不同的各种设备,兼容多种不同的体系结构。 3. 主板总线 可将主板上的所有部件连接在一起,让所有设备共享一条总线。 ==== 总线结构 1. 单总线结构:将 CPU、主存、I/O 设备 #[(通过 I/O 接口)] 都挂在一组总线上,允许 I/O 设备之间、I/O 设备与 CPU 之间或 I/O 设备与主存之间直接交换信息。这种结构简单,便于扩充,但所有的传输度通过这组共享总线,易造成计算机系统的瓶颈。 2. 多总线结构:双总线结构的特点是将速度较低的 I/O 设备从单总线上分离出来,形成主存总线与 I/O 总线分开的结构。 ==== 总线控制 1. 总线判优控制 - 在任意时刻,只能有一个设备使用总线。这种共享总线的方式可能会引起通信上的瓶颈。更通 常的情况下,各种设备分为 *主设备* 和 *从设备*。主设备是最初启动的设备,从设备是 响应主设备请求的设备。 - 对于配备不止一个主控设备的系统,则需要 *总线仲裁* #[(*_bus arbitration_*)] 机制。总线仲裁机制时必须为某些主控设备设定一种优先级别,同时又保证各个主控设备都有机会使用 总线。常用的总线仲裁方案有 4 种: 1. 菊花链仲裁方式 2. 集中式平行仲裁方式 3. 采用自选择的分配式仲裁方式 4. 采用冲突检测的分配式仲裁方式 2. 总线通信控制 - 各种信息的传递都发生在一个 *总线周期* #[(*_bus cycle_*)] 中,总线周期是完成总线信息传送所需的时钟脉冲间的时间间隔。 - *同步总线* #[(*_synchronous_*)]:由时钟控制,各种事件只有在时钟脉冲到来时才会发生,也就是事件发生的顺序由时钟脉冲来控制。这种通信的优点是规定明确统一,模块间的配合简单一致;缺点是主、从设备间的配合属于强制性同步,具有局限性。 - *异步总线* #[(*_asynchronous_*)]:各种控制线都是使用异步总线来负责协调计算机的各种操作,采用较为复杂的 *握手协议* #[(*_handshaking protocol_*)] 来强制实现与计算机其他操作的同步。 === Clock - 时钟 - 每台计算机中都有一个内部时钟,用来控制指令的执行速度;时钟也用来对系统中的各个部件的操作进行协调和同步。 - CPU 的每条指令执行都是使用固定的时钟脉冲数目。因此计算机采用* 时钟周期* #[(*_clock cycle_*)] 数目来量度系统指令的性能。 === I/O 输入/输出子系统 - 输入 / 输出是指各种外围设备和主存储器 #[(内存)] 之间的数据交换。通过输入设备可以将数据输入计算机系统;而输出设备则从计算机中获取信息。 - 输入输出设备通常不直接与 CPU 相连,而是采用某种 *接口* #[(*_interface_*)] 来处理数据交换。接口负责系统总线和各外围设备之间的信号转换,将信号变成总线和外设都可以接受的形式。 - CPU 通过输入输出寄存器与外设进行交流,这种数据的交换通常有两种工作方式。 1. 在 内存交换的输入输出 #[(*_memory-mapped I/O_*)] 方式中,接口中的寄存器地址就在内存地址的分配表中。在这种方式下,CPU 对 I/O 设备的访问和 CPU 对内存的访问是完全相同的。这种转换方式的速度很快,却需要占用系统的内存空间。 2. 在 指令实现的输入输出 #[(*_instruction based I/O_*)] 方式中,CPU 需要有专用的指令来实现输入和输出操作。尽管不占用内存空间,但需要一些特殊的 I/O 指令,也就是只有那些可以执行特殊指令的 CPU 才可以使用这种输入输出方式。 === 存储器组成和寻址方式 - 存储器的地址几乎都是采用无符号整数来表示。正常情况下,存储器采用的是 *按字节编址* #[(*_byte-addressable_*)] 的方式,也就是说每个字节都有一个唯一的地址。计算机的存储器也可以采用 *按字编址* #[(*_word-addressable_*)] 的方式,即每个机器字都具有一个自己的唯一地址。 - 如果计算机系统采用按字节编址的体系结构,并且指令系统的结构字大于一个字节,就会出现 *字节对齐* #[(*_alignment_*)] 的问题。在这种情况下,访问所查询的地址时无需从某个自然对齐的边界线开始。 - 存储器由随机访问存储器 #[(RAM)] 芯片构成。存储器通常使用符号 L × W #[(长度 × 宽度)] 来表示。长度表示字的个数,宽度表示字的大小。 - 主存储器通常使用的 RAM 芯片数目大于 1,通常利用多块芯片来构成一个满足一定大小要求的单一存储器模块。 - 单一共享存储器模块可能会引起存储器访问上的顺序问题。存储器交叉存储技术 #[(*_memory interleaving_*)],即从多个存储器模块中分离存储器单元的技术。 === Interrupt - 中断 - 中断:反应负责处理计算机中各个部件与处理器之间相互作用的概念。中断就是改变系统正常执行流程的各种事件。多种原因可以触发中断: 1. I/O 请求 2. 出现算术错误 #[(除以 0)] 3. 算数下溢或上溢 4. 硬件故障 5. 用户定义的中断点 #[(程序调试)] 6. 页面错误 7. 非法指令 #[(通常由于指针问题引起)] 8. ... - 执行各种中断的操作称为中断处理,不同中断类型的中断处理方法各有不同。但是这些操作都是由中断来操作的,因为这些过程都需要改变程序执行的正常流程。 - 由用户或系统发出的中断请求可以是 *屏蔽中断* #[(*_maskable_*)] #[(可以被禁止或忽略)] 或 *非屏蔽中断* #[(*_nonmaskable_*)] #[(高优先级别的中断,不能被禁止,必须响应)]。 - 中断可以出现在指令中或指令之间,可以是同步中断,即与程序的执行同步出现;也可以是异步中断,即随意产生中断。中断处理可能会导致程序的终止执行,或者当中断处理完毕后程序会继续执行。 \ == MARIE === 寄存器和总线 - CPU 中的 ALU 部件负责执行所有进程 #[(算数运算、逻辑判断等)]。执行程序时,寄存器保存各种暂存的数值。在寻多情况下,计算机对寄存器的引用都隐含在指令中。 - 在 MARIE 中,有 7 种寄存器; 1. AC:累加器 #[(*_accumulator_*)],用来保存数据值。它是一个 通用寄存器 #[(*_general purpose register_*)],作用是保存 CPU 需要处理的数据。 2. MAR:存储器地址寄存器 #[(*_memory address register_*)],用来保存被引用数据的存储器地址。 3. MBR:存储器缓冲寄存器 #[(*_memory buffer register_*)],用来保存刚从寄存器中读取或者将要写入存储器的数据。 4. PC:程序计数器 #[(*_program counter_*)],用来保存程序将要执行的下一条指令的地址。 5. IR:指令寄存器 #[(*_instruction register_*)],用来保存将要执行的下一条指令。 6. InREG:输入寄存器 #[(*_input register_*)],用来保存来自输入设备的数据。 7. OutREG:输出寄存器 #[(*_output register_*)],用来保存要输出到输出设备的数据。 - MAR、MBR、PC 和 IR 寄存器用来保存一些专用信息,并且不能用作上述规定之外的其他目的。另外,还有一个 标志寄存器 #[(*_flag register_*)],用来保存指示各种状态或条件的信息。 - MARIE 需要利用总线来将各种数据或指令传入和移出寄存器。在 MARIE 中,使用一条公共总线,每个设备都被连接到这条公用总线。 - 在 MAR 和存储器之间设计一条通信路线,MAR 通过这条电路为存储器的地址线提供输入,指示 CPU 要读写的存储器单元的位置。 - 从 MBR 到 ALU 还有一条特殊的通道,允许 MBR 中的数据也可以应用在各种算数运算中。同时,各种信息也可以从 AC 流经 ALU 再流回 AC,而不需要经过公用总线。 - 采取这三条额外通道的好处是,在同一个时钟周期内,既可以将信息放置在公用总线,又可以同时将数据放置到这些额外的数据通道上。 ==== 指令系统体系结构 - 计算机的 指令系统体系结构 #[(*_instruction set architecture ISA_*)] 详细规定了计算机可以执行的每条指令及其格式。从本质上来说 ISA 是计算机软件和硬件之间的接口。 1. Load X 将地址为 X 的存储单元中的值存入 AC 2. Store X 将 AC 中的值存到地址 X 中 3. Add X AC -= X 中的值 4. Subt X AC -= X 中的值 5. Input 从键盘输入一个值到 AC 中 6. Output 将 AC 中的值输出 7. Halt 终止程序 8. Skipcond 一定条件下跳过下一条指令 9. Jump X 将 X 的值存入 PC - 指令由 操作码 和 地址 构成。大多数 ISA 由处理数据、移动数据和控制程序的执行序列的指令组成。 - 计算机的输入和输出是比较复杂的操作。现代计算机都是采用 ASCII 编码字符的方式进行输入和输出操作,先以字符形式读入,再转换成相应数值后,才能被存放再寄存器 AC 中。 \ === 指令的执行过程 ==== 取址 - 译码 - 执行周期 - 取址 - 译码 - 执行 #[(*_fetch-decode-execute_*)] 表示计算机运行程序时所遵循的步骤。CPU 首先提取一条指令,即将指令从主存储器转移到指令存储器上;接着对指令进行译码,即确定指令的操作码以及提取执行该指令所需的数据;然后执行该指令。 ==== 中断和输入 / 输出 - 输入寄存器保持由输入设备传送到计算机的数据;输出寄存器保持准备传送到输出设备的各种信息。 - 在 MARIE 中,使用 *中断控制的输入输出* #[(*_interrupt-drive I/O_*)] 解决冲突。当 CPU 要执行输入或输出指令时,首先通知相应的 I/O 设备,然后处理其他的任务直至 I/O 设备准备就绪。此时,I/O 设备会向 CPU 发送一个中断请求信号。随后 CPU 会响应和处理这个中断请求。完成输入输出操作后,CPU 会继续正常的取址 - 译码 - 执行周期。 - 通常情况下,输入或输出设备使用一个特殊寄存器来发送中断信号。通过在这个寄存器中设置某个特殊的二进制位来表示有一个中断请求产生。若 CPU 发现中断位,就会执行中断处理任务。CPU 处理中断服务程序,也是对各种中断指令执行正常的取址 - 译码 - 执行周期,直至所有中断程序运行完毕。 - CPU 执行中断服务程序后,必须严格返回到原始程序的运行位置。因此它会先存储 PC 中的内容,CPU 的所有寄存器中的内容以及原始程序中原有的各种状态条件,使其能够严格恢复到原始程序运行的真实环境。 == 存储器 === 存储器分类 - 计算机的快速发展使得 CPU 的设计不断改进,而要求与之配套的存储器必须在速度上与之匹配。然而存储器的发展已经成为一个瓶颈,但由于采用了 高速缓存存储器的技术,所以改进主存储器的任务不再尤为紧迫。 - 高速缓存存储器是一种小容量、高速度,同时也是高价格的存储器。高速缓存的作用是在频繁存取数据的过程中充当一个缓冲器。 - 尽管存储器类型繁多,但大部分计算机系统都使用两种基本类型的存储器:随机存储器 #[(*_random access memory RAM_*)] 和只读存储器 #[(*_read only memory ROM_*)]。RAM 更合适的名字是 *读写 #[(*_read-write_*)] 存储器*。同时 *RAM* 也就是主存储器。 1. 按存储介质分类 > 存储介质是指能寄存 #[0 1] 两种代码并能区别两种状态的物质或元器件 1. 半导体存储器 2. 磁表面存储器 3. 磁芯存储器 4. 光盘存储器 2. 按存取方式分类 1. 随机存储器 #[(*_Random Access Memory, RAM_*)]:RAM 是一种可读 / 写的存储器,其特点是任何一个存储单元的内容都可随机存取,而且存储时间与存储单元的物理位置无关。 2. 只读存储器 #[(*_Read Only Memory, ROM_*)]:只读存储器是能对其存储的内容读出,而不能对其写入的存储器。这种存储器一旦存入了原始信息,在程序执行过程中,只能将内部信息读出,而不能随意重新写入新的信息去修改原始信息。 3. 串行访问存储器:对存储单元进行读 / 写操作时,需按其物理位置的先后顺序寻找地址。显然这种存储器由于信息所在位置不同,使得读 / 写时间均不相同。 === 存储器的层次结构 #image("屏幕截图 2024-03-14 185936.png") - 通常存储器的速度很快,单位信息犓的成本也就越高。通过采用存储器的分层组织结构体,是不同层次的存储器具有不同的访问速度 #[(存取速度)] 和存储容量。存储器分层结构系统的基本类型包括:寄存器、高速缓存、主存储器和辅助存储器。 - 现代计算机一般都具有一个数目较小的高速存储器系统,称为 高速缓存。高速缓存用来暂存一些存储器单元频繁使用的数据。这种高速缓存会被连接到一个容量较大的主存储器。通常主存储器速度中等,然后再使用一个容量非常大的辅助存储器作为机器存储器系统的补充。采用这种存储器分层结构的组织方式,可以提高对存储器系统的有效访问速度,而且只需使用少量快速的芯片。 - CPU 不能直接访问辅存,辅存只能与主存交换信息,因此辅存的速度比主存慢得多。 \ #image("屏幕截图 2024-03-14 191305.png") - 在讨论存储器层次结构时,会涉及一些术语: - 命中 #[(*_hit_*)]:CPU 请求的数据就暂存在要访问的存储器层中。通常,只是在存储器的较高层才会关心命中率的问题。 - 缺失 #[(*_miss_*)]:CPU 请求的数据不在要访问的存储器层。 - 命中率 #[(*_hit rate_*)]:访问某个特定的存储器层时,CPU 找到所需数据的百分比。 - 未命中率 #[(*_miss rate_*)]:在某个特定的存储器层中,CPU 取得所请求的信息所需要的时间。 - 未命中惩罚 #[(miss penalty)]:CPU处理一次缺失时间所需要的时间,其中包括利用新的数据取代上层存储器的某个数据块所需要的时间,再加上将所需数据传递给处理器所需要的附加时间。 - 通常情况下,处理一次未命中事件所花费的时间比处理一次命中事件所需的时间更多。 - 对于任何给定数据,处理器首先将访问数据的请求传送给存储器中速度最快、规模最小的存储器层。通常是高速缓存存储器,而不是寄存器,原因是寄存器通常用于更专用的用途。若在高速缓存中找到所需的数据,这些数据会很快地被装入 CPU 的寄存器中;若数据没有暂存在高速缓存中,那么访问数据的请求就会被传送到下一个较低层次的存储器系统,继续搜索数据。 - 核心思想是,较低层的存储器系统会响应较高层的存储器对位于存储单元 X 处的访问请求。同时,这些低层存储器也会将位于地址 X-1,X-2... 处的数据送出,也就是将整个数据块返回给较高层的存储器系统。 ==== 引用的局部性 1. 时间局部性 #[(*_Temporal locality_*)]:对于最近引用过的内容,很可能在不久的将来再次被访问 2. 空间局部性 #[(*_Spatial locality_*)]:对于最近引用过的内存位置,很可能在不久的将来引用其附近的内存位置 3. 顺序局部性 #[(*_Sequential locality_*)]:访问存储器的指令倾向于按顺序执行 - 这种局部性的原理使系统有机会使用少量速度非常快的存储器来有效加速对系统中主要存储器的访问。通常,在任意给定时刻计算机系统只需要访问整个存储空间中的某一个非常小的部分,而且存放该位置的数值常常被重复读取。 - 利用这种方式组织的存储器系统可以将大量的信息存储在一个巨大的、低成本的存储器中。 === 高速缓存存储器 - 高速缓存存储器的基本工作原理,计算机系统会将那些频繁使用的数据复制到高速缓存存储器中,而不是通过直接访问主存储器来重新获取数据。 - 计算机与人不同,没有办法得知哪些数据使最有可能被计算机访问读取的。因此,计算机需要使用局部性原理,在访问主存储器时会将整个数据块从主存储器中复制到高速缓存存储器。 - 高速缓存对这种新数据块的定位操作取决于两个因素:高速缓存的映射策略和高速缓存的大小。高速缓存的大小会直接影响到是否有足够的空间存放新的数据块。 - 对于不同的计算机,高速缓存存储器的容量有很大的差别。通常个人计算机的第二级 #[(_L2_)] 高速缓存的大小为 256KB 或 512KB;而第一级 #[(_L1_)] 高速缓存要小一些,通常为 8KB 或 16KB。L1 高速缓存通常集成在微处理器中,而 L2 高速缓存则位于 CPU 和主存储器中。因此 L1 高速缓存要比 L2 高速缓存的速度快。 - 使用高速缓存存储器的目的是为了加快存储器的访问速度。高速缓存将最近使用过的数据存放在靠近 CPU 的地方,而不是将这些数据存放到主存储器中。通常主存储器由 DRAM 组成,高速缓存由 SRAM 构成,比主存储器的访问速度快得多。 - 高速缓存存储器不是通过地址进行访问,而是按照内容进行存取。基于这种原因,高速缓存存储器也被称为 按内容寻址的存储器 #[(*_content addressable memory_*)],简称为 CAM。在大部分高速缓存映射策略的方案中,都必须检查或搜索高速缓存的入口,以确定所需的数值是否放置高速缓存中。 \ \ ==== 高速缓存的映射模式 - 在访问数据或指令时,CPU 首先会生成一个主存储器地址。此时,若要访问的数据已经被复制到高速缓存中,那么这个数据在高速缓存中的地址与主存储器中的地址不同。CPU会采用某种特殊的映射模式,将主存储器的地址转换为一个对应的高速缓存存储器的位置。 - 可以通过对主存储器地址的各个位规定某些特殊意义来实现地址的转换。首先将地址的二进制位分成不同组,称为域。根据映射模式的不同,分成多个地址域。如何使用地址域取决于采用的特定的映射模式。高速缓存的映射模式决定了数据最初被复制到高速缓存存储器中时的存放位置。 \ - 主存储器和高速缓存的存储空间都会被划分称相同大小的子块,不同系统的存储块大小可能不一样。当生成一个存储器的地址时,CPU 首先会搜索高速缓存存储器,查找所需的数据字是否已经暂存于高速缓存中。如果在高速缓存未找到,那么 CPU 会把主存储器中该字所在的位置的整个块装入高速缓存存储器中。因为访问高速缓存字要比访问主存储器字的速度快得多,所以高速缓存存储器可以加快计算机对存储器的总访问时间。 - 使用主存储器地址的各个地址域:CPU 使用主存储器地址的其中一个域,对暂存在高速缓存中的域请求数据,直接给出数据在高速缓存中的位置,这种情况称为 高速缓存命中 #[(*_Cache hit_*)];而 CPU 对没有暂存在高速缓存中的请求数据,会指示出数据将要存放在高速缓存中的位置,这种情况称为 #strong([高速缓存缺失]) #[(*_Cache miss_*)]。 \ - 接下来,CPU 会通过高速缓存块的一个有效位 #[(*_valid bit_*)],来验证所引用的高速缓冲块的合法性。若要引用的高速缓存块不正确,则产生了一次高速缓存缺失,必须访问主存储器。反之引用正确,可能会产生一次高速缓存命中。 - CPU 随后要将属于该高速缓存块的标记与主存储器地址的 标记域 #[(*_tag field_*)] 进行比较。标记是主存储器地址中的一组特殊二进制位,用来标识数据块的身份。标记与对应的数据块会一起存放到高速缓存中,若标记匹配,则产生了一次高速缓存命中。 - 在此基础上,还需要再高速缓存块中定位找出所要求的数据字的存放位置。这项工作可以通过使用主存储器地址中一个称为 字域 #[(*_word field_*)] 的字地址来完成。字域代表数据字的块内地址,所有的高速缓存映射模式都要求有一个字域。最后,地址中剩余的字段由特定的映射模式来决定。 1. 直接映射的高速缓存 - 直接映射的高速缓存采用模块方式来指定高速缓存和主存储器之间的映射关系。因为主存储器块比高速缓存块要多得多,所有很明显主存储器中的块要通过竞争才能获取高速缓存中的对应位置。 - 直接映射方式是将主存储器中的块 X 映射到高速缓存的块 Y,对应的模量为 N。其中 N 是高速缓存中所划分的存储空间的块的总数。对于高速缓存存储器的第 0 块而言,主存储器中的第 0 块、第 N 块、第 2N 块,都需要竞争映射到第 0 块。 - 当每个数据块被复制到高速缓存时,它们的身份就已经由 标记 #[(*_tag_*)] 确定了,因此计算机可以在任意时刻得知,实际是哪一个数据块驻留在当前高速缓存块中。因此高速缓存中实际存储的信息要比从主存储器复制的信息多。 - 为了实现直接映射功能,二进制的主存储器地址被划分为了 #strong([标记、块、字]) 三个不同域。每个域的大小取决于主存储器和高速缓存存储器的物理特性。#strong([字]) 域,又称为 #strong([偏移量]) #[(*_offset_*)] 域,用来唯一识别以及确定来自某个指定数据块的一个数据字。因此,字域必须具有合适长度的数据位。同样,#strong([块]) 域必须选择一个唯一的高速缓存块。 剩下的字段为 #strong([标记]) 域。在复制主存储器中的数据块到高速缓存时,标记会随着数据块一起被存储到高速缓存中,并可以通过标记唯一识别和确定数据块。#[(标记确定数据块位置,偏移域确定数据块中的数据位置)] 2. 全关联高速缓存 - 直接映射的高速缓存方案成本比其他方案低,原因是直接映射方式不需要进行任何的搜索操作。主存储器中的每个数据块都映射到高速缓存的指定的存储位置。当主存储器地址被转换为某个高速缓存地址时,CPU 只需检查地址的块域位,就能准确得知需要到高速缓存中的具体位置。 - 假设不为主存储器中的数据块唯一指定在高速缓存中的位置,而是允许主存储器中的数据块块域存放到高速缓存的任意位置。这种情况下,要找到存储器映射的数据块的唯一方法时搜索全部高速缓存。这样一来,整个高速缓存需要按照 #strong([关联存储器]) #[(*_associative memory_*)] 的模式构建,以便 CPU 可以对这种高速缓存存储器执行平行搜索。也就是说,单一的搜索操作必须将所请求的标记与存放在高速缓存中所有的标记进行比对,以确定是否存储有高速缓存中。 - 使用关联映射方式时,需要将主存储器的地址划分为标记域和字域两部分。当要在高速缓存中搜索某个特定的主存储器数据块时,CPU 会将改主存储器地址的标记域与高速缓存中存放的所有合法标记域进行比对。若没有一个标记匹配,表明产生了一个高速缓存缺失,且数据块必须从主存储器中复制到高速缓存中。 - 对于直接映射方式,若一个已被占用的高速缓存单元需要存放新的数据块,则必须移除当前数据块。若数据块的内容已被修改过,则必须将其重新写入主存储器中;否则直接覆盖原来的数据块。对于全关联映射方式,若高速缓存已经装满,则需要一种置换算法来决定将从高速缓存中丢弃哪个数据块。被丢弃的数据块被称为 *牺牲块* #[(*_victim block_*)]。 3. 组关联高速缓存 - 由于直接关联和全关联方案存在许多问题与限制,则有了组关联高速缓存。N 路的组关联高速缓存映射 #[(*_N-way set associative Cache mapping_*)],是上面两种方法的某种组合形式。首先,组关联映射方式类似于直接映射高速缓存。使用地址将主存储器中的数据块映射到高速缓存中的某个在指定存储单元。 - 它与直接映射方式的区别是:这种方式不是将数据块映射到高速缓存的某一个空间块,而是映射到由几个高速缓存块组成的某个块组中。同一个高速缓存中的所有组大小必须相同。一个八路的组关联高速缓存中,每组包含 8 个高速缓存块。由此可见,直接映射的高速缓存是一种特殊形式的 N 路组关联高速缓存,每个组中只有 1 个高速缓存块。 - 在组关联高速缓存的映射方式中,主存储器地址分为三部分:标记域、字域和组域。标记域和字域与直接映射中的作用相同;而组域,与块域类似,表示主存储器中的数据块会被映射到高速缓存中的块组。 \ ==== 置换策略 - 在直接映射方式中,若多个主存储器的块竞争某一个高速缓冲块,则会将现有的数据块从高速缓存这种踢出,为新的数据块预留空间。这一过程称为 *置换* #[(*_replacement_*)] - 对于直接映射方式,不需要使用置换策略,因为每个新的数据块对应的映射位置是固定的。但对于全关联高速缓存和组关联高速缓存,需要使用置换策略。当采用全关联映射方式时,主存储器块的映射所对应的可能是任何一个高速缓存块。当采用 N 路组关联映射方式时,主存储器中的数据块可以映射到某个指定高速缓存块组中的任意一块。决定置换哪个高速缓存块的算法称为 *置换策略* #[(*_replacement policy_*)]。 \ - 对于置换策略,希望保留高速缓存存储器中将要使用的数据块,丢弃在某段时间内不需要使用的高速缓存块。最佳置换算法的基本思想是,替换掉未来最长时间段内不再使用的高速缓存块。显然,使用最佳算法可以保证最低的高速缓存缺失率。但是,无法从每个程序的单次运行过程中预测未来,因此最佳算法只能作为评估其他算法优劣的量度方式。 1. 考虑时间局部性,推测最近没有被使用过的数据,且在未来短时间内也不太可能被使用。可以为每个高速缓存块分配一个时间标签,记录它上次被访问的时间,选择最近最少被使用的高速缓存块。这种算法称为 *最近最少被使用算法* #[(*_least recently used_*)]。但是这种算法要求系统保留每个高速缓存块的历史访问记录,需要高速缓存有相当大的存储空间,同时会减慢高速缓存的速度。 2. *先进先出* #[(*_FIFO_*)] 是另一种策略,利用这种策略,存放在高速缓存中时间最长的块将会被移除,而不管它在最近何时被使用过。 3. 另一种策略是 *随机选择* #[(*_random_*)]。LRU 和 FIFO 会遇到 *简并引用* #[(*_degenerate reference_*)] 的问题,这时会产生对某个高速缓存块的 *重复操作* #[(*_thrash_*)],即不停重复地将一个数据块移出再移回高速缓存。对于随机选择算法,虽然它不会出现对某个块的重复操作,但有时会把即将需要的数据块移出高速缓存,会降低高速缓存的平均性能。 - 算法的选择通常取决于计算机系统的使用方式。对于所有情况来说,不存在最好的、单一的、实用的算法。 \ ==== 高速缓存的写策略 - 除了要选择进行置换的牺牲块外,还必须对高速缓存的 *脏块* #[(*_dirty block_*)] 进行处理。高速缓存中的脏块是指已经被修改过的数据块。当处理器写入主存储器时,数据可能也会被写入高速缓存中,原因是处理器可能很快会再次读这些数据。若修改了某个高速缓存块的数据,*高速缓存的 写策略* #[(*_write policy_*)] 会决定何时更新对应的主存储器数据块来保证数据的一致性。 1. *写通 #[(*_write through_*)] 策略* - 写通策略是指在每次写操作时,处理器会同时更新高速缓存和主存储器中对应的数据块。写通策略速度比较慢,但可以保证高速缓存和主存储器中数据一致。 - 写通策略的明显缺点是,每次进行高速缓存的写操作都伴随着一次主存储器的写操作,减慢了系统速度。若所有的访问都是写操作,那么存储器系统的速度会减慢到主存储器的访问速度。但实际操作中,大多数存储器的访问都是读操作,因此可以忽略写通策略带来的影响。 2. *回写 #[(*_write back_*)] 策略* - 当只有某个高速缓存块被选择作为牺牲块而必须从高速缓存中移除时,处理器才更新主存储器中对应的数据块。通常,回写策略的速度比写通策略块,因为对于存储器的访问次数减少了。 - 回写策略的缺点是,主存储器和高速缓存的对应单元在某些时刻存放着不同数值。若某个进程在回写操作完成前中断或崩溃,会导致高速缓存中的数据丢失。 \ === 虚拟存储器 - 高速缓存允许计算机从一个较小规模但速度较快的的高速缓存器中,频繁访问使用过的数据。这种分层组织结构所固有的另一个另一个重要概念是 *虚拟存储器* #[(*_virtual memory_*)]。 - 虚拟存储器使用硬盘作为 RAM 存储器的扩充,增加了进程可以使用的有效空间。大多数主存储器的容量较小,通常没有足够的存储空间来并发地运行多种应用程序。 - 使用虚拟存储器,计算机可以寻址比实际主存储器更多的空间。计算机使用硬盘驱动器保持额外的主存储器空间。硬盘上这部分区域被称为 *页文件* #[(*_page file_*)],因为这些页文件在硬盘上保存主存储器的信息块。 - 实现虚拟存储器最常用的方法是使用主存储器的 *分页机制* #[(*_paging_*)],这种方法是将主存储器划分成固定大小的块,并且程序也被划分成相同大小的块。通常,程序块会根据需要被存放到存储器中,没有必要将程序的连续块也存储到主存储器的连续块中。 - 在高速缓存中,主存储器的地址应该转换为高速缓存的位置;在虚拟存储器中也是如此,每个虚拟地址都必须转换为物理地址。 \ - 分页实现虚拟存储器的术语: 1. *虚拟地址* #[(*_virtual address_*)]:进程所使用的逻辑地址或程序地址。只要 CPU 生成一个地址,就总对应虚拟地址空间。 2. *物理地址* #[(*_physical address_*)]:物理存储器的实际地址。 3. *映射* #[(*_mapping_*)]:一种地址变换机制,通过映射可以将虚拟地址转换为物理地址,类似于高速缓存映射。 4. *页帧* #[(*_page frame_*)]:由主存储器分成的相等大小的信息块或数据块。 5. *页* #[(*_page_*)]:由虚拟存储器 #[(逻辑地址空间)] 划分的信息块或数据块。每页的大小与一个页帧相同。在硬盘上存储虚拟页以供进程使用。 6. *分页* #[(*_paging_*)]:将一个虚拟页从硬盘复制到主存储器的某个页帧的过程。 7. *存储碎片* #[(*_fragmentation_*)]:不能使用的存储器单元。 8. *缺页* #[(*_page fault_*)]:当一个请求页在主存储器中没有找到所发生的事件,必须将请求页从硬盘复制到存储器。 - 因为主存储器和虚拟存储器都被划分为相同大小的页,所以可以把程序进程的地址空间的一些片段移动到主存储器中,但不需要将这些内容连续存储。也不必立即将所有进程全部装入主存储器中;虚拟存储器允许存储器中只需存在特定片段即可运行程序,暂时不用的程序部分会存储在硬盘上的页文件中。 \ ==== 分页 分页的基本思想: - 按照固定大小的信息块 #[(页帧)] 为各个进程分配物理存储空间,并且通过将信息写入页表 #strong([#emph([(page table)])]) 的方式跟踪记录进程的不同页的存放位置。每个进程都有自己的页表,页表通常驻留在主存储器中,页表存储该进程的每个虚拟页的物理位置。 - 若当前进程某些页不在主存储器中,则页表会通过设置一个 #strong([有效位]) #strong([#emph([(valid bit)])]) 为 0 来指示;若当前进程在主存储器中,则该页的有效位设置为 1。因此每个页表的入口目录都由 #strong([有效位和帧数]) 组成。 \ - 通常页表中还会附加一些其他内容,以便传递更多信息。 1. 修正位 #strong([(#emph([dirty bit]) 或 #emph([modify bit]))]) 来指示页中内容是否已经发生改变,这样可以使处理器在进行返回页内容到硬盘的操作时更有效率 2. 使用位 #strong([#emph([usage bit])]) 来指示页的使用情况。只要处理器访问过某一页,设置该位为 1,一定时间周期后重新设置为 0。若某段时间间隔内未使用该页,系统可能把该页从主存储器移除,放到磁盘上。这样可以让系统释放该页占用的存储空间给其他进程需要使用的另外一页。 - 虚拟存储器中页的大小于物理存储器的页帧相同。程序进程的存储空间分为固定大小的页,当把程序的最后一页复制到存储器时,可能产生潜在的 #strong([内部碎片 #emph([(internal fragementation)])]) 现象。进程可能不需要占用整个页帧,但是又没有其他的进程使用该页帧的剩余部分。 - 若进程本身的全部内容需要占用的空间小于一个整页,而在复制到存储器时必须占用一个完整的页帧,这是就会产生存储碎片。对于某个特定的分页,内部碎片会导致一些未使用的存储空间。 \ 分页的工作原理: - 当某个进程生成了一个虚拟地址时,存储系统必须动态地将虚拟地址转换成数据实际驻留的存储器的物理地址 - 为了实现这种地址之间的转换,可以把虚拟地址分成两个部分:#strong([页域 #emph([(page field)])]) 和 #strong([偏移量域 #emph([(offset field)])])。偏移量表示要使用的数据在页内的位置。这种地址转换过程类似于高速缓存映射算法中将主存储器划分为不同域的过程。 - 要访问给定虚拟地址的数据,系统要执行以下步骤: 1. 从虚拟地址中提取页码和偏移量 2. 通过访问页表将页码转换为对应的物理页帧数 1. 在表中查找页码 #[(使用虚拟地址的页码作为索引)],并检验有效位。 - 若有效位为 0,则表示系统产生了一个缺页事件。此时,操作系统必须介入: 1. 在磁盘上查找所使用的页 2. 寻找一个空的页帧 #([(若主存储器已满,则必须从主存储器中移除一个牺牲页,然后将内容复制到硬盘,同时修改牺牲页的有效位)]) 3. 把要使用的页复制到主存储器的空页帧 4. 更新页表 #[(新装入的虚拟页在页表中必须有自己的页帧数有效位)] 5. 重新执行引起缺页事件的程序进程 - 若有效位为 1,则表示查找的页已经在主存储器中 1. 使用实际帧数代替虚拟页码 2. 对于给定的虚拟页,访问对应的物理页帧中位于对应偏移量的数据。具体的物理地址是 #strong([页帧 + 偏移量]) - 若发生缺页事件,同时分配给进程的主存储器已满,则必须选择一个牺牲页。选择牺牲页需要用到置换算法,与高速缓存中使用的置换算法非常类似。 ==== 使用分页的有效存取时间 在分析高速缓存时,引用了有效存取时间的表示方法。使用虚拟存储器时,同样需要地址有效存取时间。 - 处理器每次访问存储器,都必须执行两次对物理存储器的访问操作。一次是引用页表,另一次是访问要请求的实际数据。 - 通过将最近的页查询数据值存放到一个被称为 #strong([转换旁视缓冲器 (#emph([translation look-aside buffer, TLB]))]) 可以加速页表的查询时间。每个 TLB 的入口目录都由一个虚拟页的页码和对应的物理页帧的帧数组成。 - 处理器通常使用关联高速存储来实现 TLB,并且虚拟页码和物理帧数对可以映射到 TLB 高速缓存的任何位置。当使用 TLB 时,一个地址的查询有如下步骤: 1. 从虚拟地址中提取页码 2. 从虚拟地址中提取偏移量 3. 在 TLB 中搜索虚拟页码 4. 若在 TLB 中找到虚拟页码和物理页帧数对,则将偏移量加上物理页帧数,并直接访问相应的存储单元 5. 若发生一个 TLB 缺失,处理器就从页表中获取所需要的帧数。若该页已经位于存储器中,就利用偏移量加上物理帧数生成对应的物理地址 6. 若请求的页不在存储器中,就会生成一个缺页错误。在出现缺页事件时,需要操作系统介入,重启存储器访问操作。 ==== 分页和虚拟存储器的优缺点 - 通过分页和增加一次额外的存储器引用来实现虚拟存储器。通过使用 TLB 高速缓存来存放页表的入口目录,可以减少分页的部分损失。但即使在 TLB 有很高的命中率,这一进程仍然会在地址转换上造成重大开销。 - 使用虚拟存储器和分页的另一个缺点是,需要消耗额外的系统资源,即需要额外的存储器空间存放页表。在极端情况下,页表会占用很大比例的物理存储器。 - 虚拟存储器允许系统运行虚拟地址空间比实际物理存储器空间大的程序。实质上,虚拟存储器允许进程可以和该进程自身共享物理存储器。 - 由于每个程序需要的物理存储器空间较小,因此虚拟存储器可以同时运行更多的程序。这使得系统能够处理总的地址空间远超过系统物理存储器空间的容量,提高了 CPU 的使用率和系统处理能力。 - 从操作系统的角度看,使用固定大小的页帧和页面简化了存储器空间的分配和地址的安排问题;而且分页也允许操作系统以每页为基础实现特定的任务保护 === 分段 分页是目前计算机系统最常用的方法,但不是唯一方法。某些系统使用实现虚拟存储器的第二种方法是 #strong([分段 (#emph([segmentation]))])。 - 与分页不同,分段并不把虚拟地址空间划分为相等的、大小固定的页面以及同时将虚拟地址物理地址空间划分为相同大小的页帧,而是将虚拟地址空间划分为多个长度个边的逻辑单元,称为 #strong([段 (#emph([segment]))])。 - 物理存储器不再进行实际的空间分割或分区。当需要将某个段复制到物理存储器时,操作系统会自动查找足够大的自由存储空间来存储整个段。每个段都有一个表示该段在存储器中位置的 #strong([基地址 #emph([(base address)])]),还有一个指示段的大小的 #strong([界限 #emph([(bound limit)])])。 - 每个程序都是由若干个段组成。每个程序也都有一个相应的 #strong([段表 #emph([(segment table)])]),而不是页表。段表中所包含的时每个段的基地址和界限对的集合。 - 只提供段号和段内偏移量,就可以进行存储器的访问。系统还要进行错误校验以确保偏移量在允许的界限之内。若偏移量允许,再将该段的基地址值 (可在段表中找到) 与偏移量相加,得到实际的物理地址。由于分段使用的是逻辑存储空间块,所以使用分段更容易实现存储空间的保护和共享。 - 与分页一样,分段也会产生存储碎片。分页产生内部碎片现象,原因子啊与处理器将一个完整的页帧配置给并不需要占用整个页帧的程序。 - 此外,分段会造成 #strong([外部碎片 #emph([(external fragmentation)])]) 现象。在进行分段配置和解除分段处理时,存储器中的自由空间块会变得残缺。最后导致存储器中留下许多长度较小的自由空间块,并且这些空间块的大小不足以存放一个程序的进程。 - 外部碎片和内部碎片的区别是: - 对于外部碎片,存储器上总的空间足够分配给一个程序进程使用,但这个空间并不连续,上面存在着大量容量小、无法使用的碎片。 - 对于内部碎片,由于系统将过多的存储空间分配给了某个并不需要如此大空间的程序进程,所以无法使用多余的空间。 - 为解决外部碎片,系统可以使用某种类型的 #strong([碎片收集 (#emph([garbage collection]))]) 技术。这种处理技术只是对存储空间上已经占用的信息块进行重新配置,将小空间碎片组合称较大的可利用的自由空间块。 ==== 分页和分段的组合方式 分页与分段的机制并不相同。 - 分页是基于一个纯粹的物理值:即程序地址和主存储器地址都被划分为相同大小的物理空间块。而分段是将程序的逻辑地址部分划分为长度可变的不同分区。使用分段,用户可以知道段的大小和界限;使用分页,用户并不知道存储空间的具体划分。 - 相对来说,分页技术更容易管理。当所有元素都具有相同大小时,分配空间、释放空间、空间交换和重新部署等操作都较为方便。 - 但一般情况下分页的数目比分段数目少,意味着分页技术需要更多的系统开销,主要指页面记录和页面转换所占用的资源。分页消除了外部碎片问题,而分段可以避免内部碎片问题。 - 通常,系统组合使用两种方法。在组合方式中,虚拟地址空间被分割称一些长度可变的段,而这些段也被划分成许多固定大小的页面。主存储器的物理空间也划分为相同大小的帧。 - 每个段都有一个页表,每个程序有多个页表。系统的物理地址被划分为三个域:段域,指示系统对应的页表;页码,用作进入页表的偏移量;页内的偏移量。 === 主存储器 - 若要从存储器读出某一信息字时,首先由 CPU 将该字的地址送到 MAR,经地址总线送至主存,然后发出读命令。主存接到读命令后,得知需将该地址单元的内容读出,便完成读操作,将内容读至数据总线上。 - 若要向主存写入一个信息字时,首先 CPU 将该字所在主存单元的地址经 MAR 送到地址总线,并将信息字送入 MDR,然后向主存发出写命令,主存接到写命令后,数据总线上的信息写入对应地址线指出的主存单元中。 - 主存中存储单元地址的分配:主存各存储单元的空间位置是由单元地址号来表示的,而地址总线使用来指出存储单元地址号的,根据该地址可读出或写入一个存储字。通常计算机可以按字寻址也可按字节寻址。 ==== 随机存取存储器 - RAM - 在计算机执行程序时,RAM 用来存放程序或数据。但是,RAM 是一种易失性的存储器。当存储器系统掉电时,RAM 中所存储的信息会丢失。现代计算机一般采用两种类型的存储器芯片来构建大规模 RAM 存储器:静态随机存储器 #[(*_SRAM_*)] 和动态随机存储器 #[(*_DRAM_*)]. - 动态 RAM 由一个小电容构建。由于电容会泄漏电荷,所以 DRAM 每隔几毫秒充电才能保存数据。相比之下,静态 RAM 技术只要供电不断,就可以维持它所保存的数据。SRAM 的速度比 DRAM 更快也更贵。使用 DRAM 的原因是因为 DRAM 的存储密度更高,消耗的功耗更低,比 SRAM 产热更少。 - 因此通常使用两种技术的组合形式:DRAM 作为主存储器,SRAM 作为高速缓存存储器。所有 DRAM 的基本操作都是相同的,但 DRAM 还是可以分成许多类型;SRAM 也是一样, ==== 只读存储器 - 按照 ROM 的原始定义,一旦注入原始信息即不能改变,但随着用户的需要,总希望能随意修改 ROM 内的原始信息。因此出现了 PROM,EPROM 和 EEPROM 等类型。 - ROM - 大部分计算机系统还使用一定数目的 ROM 存储器来存放一些运行计算机系统所需要的关键信息,比如启动计算机系统所需要的程序。ROM 属于非易失性的存储器,可以长久保存它所存放的数据,在电源关闭后还可以保存其中的信息。 - 有 5 种类型不同的基本 ROM 存储器:ROM、PROM、EPROM、EEPROM 和闪存 #[(*_flash memory_*)]。 - PROM 称为 #strong([可编程只读存储器]),它是 ROM 一种改进类型,用户可以使用专门的设备对其进行编程。由于 ROM 采用的是硬连线,PROM 存储器中有许多熔断丝,可以通过烧断的方法进行编程;但是一旦编程完成,PROM 中的数据和指令都不能再更改。 - EPROM 为可擦除 PROM,是一种可重复编程的可编程存储器。要对 EPROM 进行再编程,首先需要将整块芯片的原有信息擦除干净。 - EEPROM 是电可擦除 PROM,它克服了 EPROM 的许多缺点,而且一次可只擦除芯片上某些部分的信息,例如一次只擦除一个字节。 - 闪存本质也是一种 EEPROM,但是闪存的优点可以按块来擦写数据,不限于一个字节,因此,其擦写速度比 EEPROM 快。 \ ==== 存储器与 CPU 的连接 1. 存储容量的扩展:由于存储芯片的容量总是有限的,很难满足实际的需要,因此必须将若干存储芯片连载一起才能组成足够容量的存储器,称为存储容量的扩展,通常由位扩展和字扩展。 1. 位扩展:增加存储字长 2. 字扩展:增加存储器字的数量 3. 字、位扩展:既增加存储器字的数量,又增加存储字长。 2. 存储器与 CPU 的连接:存储芯片与 CPU 芯片相连时,要注意片与片之间的地址线、数据线和控制线的连接。 1. 地址线的连接 - 存储芯片的容量不同,其地址线数也不同,CPU 的地址线数往往比存储芯片的地址线数多。通常将 CPU 地址线的低位与存储芯片的地址线相连。CPU 地址线的高位或在存储芯片扩充时用,或其他用途。 2. 数据线的连接 - CPU 数据线数与存储芯片的数据线数也不一定相等。此时,必须对存储芯片扩位,使其数据位数与 CPU 的数据线数相等。 3. 读/写命令线的连接 - CPU 读/写命令线一般可直接与存储芯片的读/写控制端相连,通常高电平为读,低电平为写。有些 CPU 的读/写命令线是分开的,此时 CPU 的读命令线应与存储芯片允许读控制端相连,而写命令线与存储芯片的允许写控制端相连。 4. 选择存储芯片: - 通常选用 ROM 存放系统程序、标准子程序和各类常数等。RAM 则是为用户编程而设置的。 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ = 指令系统体系结构 计算机指令由操作码和操作数组成。操作码指定要执行的操作类型,操作数指出数据所处的寄存器和内存单元 == 指令格式 - 计算机的每条指令都有一个操作码和 0 个或多个操作数。随着体系结构的不同,机器指令使用的二进制数的位数可能不同,每条指令允许使用的操作数的个数不同,指令的类型和指令处理的操作数的类型也可能不同。具体区别如下: + 操作数在 CPU 中的存储方式 #[(数据可以存储在堆栈结构或寄存器中)] + 指令直接作用的操作数的数目 + 操作数的位置 + 操作 #[(操作类型,并且指出指令是否可以访问存储器)] + 操作数的类型和长度 #[(操作数可能是地址、数字或字符)] === 指令系统的设计 - 在设计计算机的体系结构时,必须首先确定计算机指令系统的格式。各种计算机系统设计中所选择的指令体系结构通常由很大差别,原因时不同的体系结构必须配备不同的指令系统。 - 指令系统体系结构 #emph()[ISA] 的效能可以用以下几个因素衡量: + 程序执行指令时占用内存空间的大小 + 指令系统的复杂程度,主要指指令执行所需要的译码数量和指令所执行的任务的复杂性 + 指令的长度 + 指令系统中指令的总数目 - 设计指令系统时需要考虑的问题: - 指令一般越短越好,较短的指令占用较少的内存空间,并且提取指令的速度也会更快。但是,采用短指令会限制指令的数量。因为指令的数量收到指令中能够进行编码的二进制数的位数限制。同样,短指令也会限制操作数的大小和数量 - 固定长度的指令的译码相对比较容易,但浪费空间 - 存储器的组成形式会影响指令的格式 - 固定长度的指令系统并不表示必须使用固定数量的操作数。可以设计一个指令总长度固定的指令系统体系结构,但允许操作数域的位数根据需要改变。这种指令系统体系结构称为 #strong([扩展操作码 (#emph([expanding opcode]))]) - 存在多种不同类型的寻址方式,例如直接寻址和间接寻址 - 若机器的字由多个字节组成,需要考虑组成字的字节按照怎样的次序存储到按字节编址的机器存储器中。 - 设计的体系结构需要多少个寄存器且这些寄存器该如何安排?操作数如何存放在 CPU 中? ==== 小端和大端的位序问题 #strong([位端 (#emph([endian]))]) 指的是计算机体系结构中的 #strong([位序 (#emph([byte order]))]),或者说指计算机中存储一个多字节数据元素时,各个字节的排列方式。 - 当今所有的计算机体系结构都是按字节编址,因此必须对存储多余单一字节的信息的方法制定一个标准。 - 小端:存储多字节数据时,将最低位的字节首先存放到低位地址,然后将最高位的字节存放到高位地址。这样,位于较低地址的字节时数据的最低位。采用这种方式的机器称为 #strong([小端 (#emph([little endian]))]) 机器。 - 大端:存储多字节数据时,将最低位的字节首先存放到高位地址,然后将最高位的字节存放到地位地址。采用这种方式的机器称为 #strong([大端 (#emph([big endian]))]) 机器。 ==== CPU 的内部存储机制:堆栈和寄存器 当存储器的位序确定之后,需要决定 CPU 存储数据的方式。CPU 的数据存储方式时区分不同指令系统体系结构 (ISA) 的最基本方法。 1. 堆栈体系结构 2. 累加器体系结构 3. 通用寄存器 (GPR) 体系结构 - #strong([堆栈体系结构 (#emph([stack architecture]))]) 的计算机使用一个堆栈来执行各种指令,而且指令的操作数隐含地存放在堆栈的顶部。按照堆栈体系结构设计的机器通常具有好的编码密度和一个简单的估值模型。但是由于不能对堆栈进行随机访问,使得采用堆栈结构的机器难以进行高效率地编码。 - #strong([累加器体系结构 (#emph([Accmulator architecture]))]) 的计算机,将其中一个操作数隐含在累加器中,这样可以最大限度地降低机器的内部复杂性,而且允许使用非常短的指令。但是由于累加器只能临时存储,所以这类机器对存储器的访问非常频繁。 - #strong([通用寄存器体系结构 (#emph([general purpose architecture]))]) 的计算机,采用多个通用寄存器组。这些寄存器组的访问速度比存储器快得多,非常方便编译器处理,并且可以十分有效和高效使用。\ 通用寄存器体系结构可以根据指令的操作数所处位置分成三种类型。 1. #strong([存储器-存储器 (#emph([memory-memory]))]) 体系结构可以有两或三个操作数位于存储器内,允许有一条执行某种操作而不需要任何操作数的指令存放在某个寄存器中。 2. #strong([寄存器-存储器 (#emph([register-memory]))]) 体系结构采用混合方式,其中至少有一个操作数在寄存器中和一个操作数在存储器中。 3. #strong([装入-存储 (#emph([load-store]))]) 式体系结构需要在任何对数据的操作执行前,先将数据装入寄存器中。 ==== 操作数的数目和指令长度 描述计算机体系结构的传统方法是指定每条指令中所包含的操作数,或者说地址的最大数目。 - 在现代计算机体系结构中,指令的构成有两种方式: + #strong([固定长度 (#emph([fixed length]))]) :使用这种格式的指令系统会浪费一些存储空间,但是指令执行的速度快。在采用 #strong([指令层次 (#emph([instruction-level]))]) 的流水线结构时,固定长度的指令系统的性能更好 + #strong([可变长度 (#emph([variable length]))]) :这种指令系统的译码会比较复杂,但是可以节省空间 - 最常用的指令格式包括有零个、一个、两个或三个操作数。通常情况下,算术运算或逻辑运算需要两个操作数。若把累加器作为一个隐含的操作数,则可以把两个数的操作按照一个操作数指令来执行;若把结果地址作为第三个操作数,那么也可以扩展到三个操作数指令。 - 常用指令格式: - 只有操作码 (0 地址) - 操作码 + 1 个地址 (通常只有一个存储器地址) - 操作码 + 2 个地址 (通常是两个寄存器地址,或者寄存器和存储器的组合) - 操作码 + 3 个地址 (通常是三个寄存器地址,或者寄存器和存储器的组合) - 不带操作数的机器指令必须使用堆栈来执行在逻辑上需要操作数的操作,堆栈中所有数据插入和删除都必须从堆栈顶部进行。由于没有采用通用寄存器,基于堆栈的体系结构将操作数放在堆栈的顶部,CPU 可以访问堆栈顶部的数据。 - 在基于堆栈的计算机体系结构中,大部分机器指令都只包含操作码。但是,有些特殊指令,往往带有一个单一的操作数。堆栈结构需要一个 #trans([入栈], [push]) 和 #trans([出栈], [pop]) 指令。这两个指令都需要一个操作数。Push X 指令表示将地址为 X 的存储器单元内的数据值放到堆栈中。Pop X 指令表示移走堆栈顶部的元素并将其放到地址为 X 的存储器单元中。堆栈体系结构中,只有某些特定的指令才允许访问存储器,其他全部指令必须使用堆栈作为指令执行所要求的操作数。 ==== 扩展操作码 #trans([扩展操作码], [expanding code]) 代表了一种折衷的方案,即要求有尽可能多的操作码的数目,也要求采用尽可能短的操作码,所设计的指令长度也较短。 - 其设计的基本思想是:选用短操作码,而当有需要时可以有某种方法将操作码加长。若使用短的操作码,就留给操作数大量的指令位,意味着每条指令可以有两到三个操作数;若不需要操作数,则指令所有位都可以作为操作码,生成许多独特的指令。 === 指令类型 大多数的计算机指令都对数据执行操作,但是也有些指令操作对象不是数据。计算机指令有以下几种类型: - 数据移动 - 算术运算 - 布尔逻辑运算 - 位操作 (移位和循环换位) - 输入 / 输出 - 控制转移 - 数据移动指令是最常用的指令。数据常常从存储器被移到寄存器,从存储器移到寄存器,以及从寄存器移到存储器等。许多计算机有多种不同的数据移动指令,其具体应用取决于数据来源和移动目的。某些计算机体系结构,会限制将数据从存储器移出或将数据移入存储器的指令,以加快系统运行速度。 - 算术运算指令包括有正数和浮点运算的各种指令。许多机器还对不同大小的数据提供有不同的算术运算指令。与数据移动指令一样,有时计算机会位用户设计多种不同的算术运算指令,以满足操作数为寄存器和以不同寻址方式访问存储器的 各种组合方式的需求。 - 位操作指令用来在某个特定的数据字中对一些单独的数据位进行置位和复位操作。位操作指令包括了各种算术移位指令、逻辑移位指令和循环移位指令。算术移位指令将二进制数进行乘以 2 或除以 2 的操作,但并不移动最左边的符号位。循环移位指令只是简单地执行将移出的各个为在相反方向依次移进来。 - 控制指令包括 #trans([分支转移], [branch])、#trans([跳过], [skip])和 #trans([进程调用], [procedure call])等。分支转移分为条件转移和无条件转移。跳过指令实际上是没有指定地址的分支转移指令。因为不需要操作数,跳过指令通常使用地址域的二进制位来指定一些不同环境。进程调用时一些特殊的分支转移指令,它们会自动存储程序返回的地址。不同机器可能采用不同方法存储返回地址。 === 寻址 与寻址有关的两个最重要问题是:可以进行编址的数据类型和各种各样的寻址方式 ==== 数据类型 - 数字数据由整数数值和浮点数值组成。整数有带符号整数和无符号整数,并且可以声明为不同长度的整数。计算机的指令系统中有一些特殊指令,可以用来处理可变长度的数字数据。 - 非数字数据包括字符串、布尔数值和指针。字符串指令一般有复制、移动、搜索或修改等操作。指针实际就是存储器中的存储单元的地址。指令系统中采用这种方式的操作数实际上都是指针;对于使用指针的指令,操作数本质上就是一个地址,且比必须当成一个地址处理。 ==== 寻址方式 寻址方式是指定指令中操作数的的位置的方法。一种寻址方式所指定的内容可以是一个常数、一个寄存器或是存储器中的一个存储单元,可以直接使用;\ 有些寻址方式指出的就是实际操作数的位置,需要访问后使用。从动态的角度来看,实际操作数的位置称为操作数的 #trans([有效地址], [effective address]) 1. 立即寻址 - #trans([立即寻址], [immediate addressing]) 是指在指令中操作码后的数值会被立即引用,也就是说要操作的数据本身是指令的一部分。 - 立即寻址方式的执行速度非常快,因为要加载的数据就包含在指令中;但是由于编译时要加载的数值是固定的,因此这种寻址方式不灵活。 2. 直接寻址 - #trans([直接寻址], [direct addressing]) 是指在指令中直接指定要引用的数值的存储器地址。 - 直接寻址方式的操作也很快,尽管要加载的数值不包含在指令中,但这种直接的地址访问非常快。直接寻址比立即寻址要灵活,要加载的数值放在给定地址的存储单元,且数值是可变的。 3. 寄存器寻址 - #trans([寄存器寻址], [register addressing]) 方式中,是采用一个寄存器,而不是存储器来指定操作数。这种方式与直接寻址类似,不同的是指令的地址域包含的是一个寄存器的引用,而不是某个存储器的地址。 4. 间接寻址 - #trans([间接寻址], [indirect addressing]) 是一种非常有效的寻址方式,使用起来非常灵活。在间接寻址方式中,地址域中的二进制数用来在指定一个存储器地址,该地址中的内容被用作一个指针。操作数的有效地址是通过访问这个存储器地址来获取的。 - 作为间接寻址方式的一种变化形式,操作数域的二进制位也可以用来指定一个寄存器,而不是存储器。这种方式称为 #trans([寄存器间接寻址], [register indirect addressing]),除了采用一个寄存器来代替存储器作为指针外,工作原理与间接须知方式完全相同。 5. 变址寻址和基址寻址 - 在 #trans([变址寻址], [indexed addressing]) 方式中,一个变址寄存器 (显式指定或隐式指定) 用来存储一个 #trans([偏移量], [offset]),或称为 #trans([位移量], [displacement])。将这个偏移量与操作数相加,就产生了指令所要求的数据的有效地址。 6. 堆栈寻址 - 若使用 #trans([堆栈寻址], [stack addressing]),则操作数就假定放在堆栈中 7. 其他寻址方式 基于最基本的寻址方式,还可以生成许多变化。 1. #trans([间接变址寻址], [indirect indexed addressing]) 方式,即同时采用间接寻址和变址寻址。 2. #trans([偏移量寻址], [offset addressing]) 方式,即先将一个偏移量加到某个特定基址寄存器中,然后再与指定的操作数相加,得到所使用的实际操作数的有效地址。 3. #trans([自动增量], [auto-increment]) 寻址方式和 #trans([自动减量], [auto-decrement]) 寻址方式,可以对所使用的地址寄存器中的内容进行自增或自减操作 === 指令流水线 从概念上来说,计算机使用时钟脉冲来精确控制各个操作步骤的顺序执行。但是,有时还可以使用一些额外的脉冲来控制某个操作步骤中一些小细节。有些 CPU 会将取指-译码-执行周期分成一些小步骤,其中某些小步骤可以并行执行。这种时间上的交替可以加快 CPU 的执行速度,这种方法称为 #trans([流水线], [pipeline]) - 假设将计算机的取指-译码-执行周期分解为小步骤 1. 取指令 2. 操作码译码 3. 计算操作数的有效地址 4. 取操作数 5. 执行指令 6. 存储结果 - 计算机流水线中的每个步骤完成指令的一部分功能,这其中每一个步骤都称为 #trans([流水线级], [pipeline stage])。将流水线逐级连接起来,就构成了一条指令执行的管道。 - 指令从流水线管道的一端进入,通过不同级的流水线作业,从管道另一端出来。流水线分级的目的是要对通过流水线的每一级所花费的时间进行均衡控制。也就是要使经过每级流水线所花的时间基本一致。若时间不平衡,那么较快的流水线级需要等待较慢的流水线级。 - 从某种意义上来说,可以认为流水线的级数越多,计算机运行的速度就越快。将数据从存储器移动到寄存器涉及固定的开销。流水线的控制逻辑的数量和大小也会与流水线级数的增加成正比。这无疑会减慢系统的总执行速度。 - 另外,还存在几种条件导致 #trans([流水线冲突], [pipeline conflict]),这些情况会阻碍计算机实现每个时钟周期执行一条指令的目标 1. #trans([资源冲突], [resource conflict]) 是指令集并行执行过程中要考虑的主要问题。例如,若计算机要将某个数值存放到存储器中,同时又正在从存储器中提取另一条指令,这两个操作都需要访问内存。通常,解决冲突的方法是让存储指令继续执行,强制让取指的指令等待;或者通过使用两条独立的通道解决。 2. #trans([数据关联], [data dependency]) 是指当一条指令的执行尚未结束时,后面某条指令却要求改指令执行结果作为其操作数。解决方法: 1. 技术上添加专门的硬件来检测某条指令的源操作数是否是流水线上游的指令的目标操作数。这些硬件通过再流水线中插入一个简短的延迟 (通常是加入一条不执行操作的 no-op 指令),让计算机有足够的时间来解决这些冲突。 2. 可以利用专门的硬件来检测这类冲突,并且引导数据经过存在于流水线各级之间的某些特殊通道。这样可以减少指令访问其操作数所需的时间。有些计算机体系结构采用编译器处理这种冲突,特殊设计的编译器会对各种指令进行重新排序。 3. 程序员可以使用分支转移语句改变程序的执行流程,但会对流水线造成重大影响。当遇到分支指令时,由于分支的条件可能依赖于运行时的数据,无法在译码阶段准确确定分支的目标地址。许多计算机体系结构设计 #trans([分支预测], [branch prediction]) 结构,利用合理的逻辑来对下一条指令做出最优预测。 - 从本质上来说,分支预测结构主要是预测条件分支转移的结果。编译器试图通过重新安排机器代码的方式来产生一个延迟的 #trans([分支转移], [delayed branch]) 操作,以解决分支问题。 - 一种方法是对程序进行重新排序,并在程序中插入一些有用的指令或 no-op 指令,以保持流水线始终处于饱和状态 - 另一种方法是,对某个已知的条件分支转移的两条分支通道都开始执行取指操作,并将这些结果存储起来,等待这条分支语句的实际执行 = 计算机系统中数据表示方法 == 位置编码系统 - #trans([位置编码系统], [positional numbering systems]) 包含的基本思想是,任意数字的值都可以通过表示成某个 #trans([基数], [radix]) 的乘幂形式。这种计数体系也称为 #trans([权重编码系统], [weighted numbering system]) == 补码体系 - 在十进制数中的减法运算,可以通过加上减数与全 $9$ 组成的数字的差,再加回一个进位的方法来实现。这种方法称为求减数的 #trans([十进制反码], [diminished radix complement]) === 反码 - 在基数为 $10$ 的计数体系中,一个数的 #trans([反码], [one's complement]) 通过将基数减去 $1$,即十进制中为 $9$,再减去该基数。对于更一般的形式,若已知基为 _r_,有 _d_ 位数字,那么数字 _N_ 的反码定义为 $(r ^ d - 1) - N$。 - 在二进制数的体系中也有相同的操作。构成二进制数的反码更加简单,即将所有的 $1$ 转换为 $0$,所有的 $0$ 转换为 $1$。 - 反码表示法的主要缺点是由两种 _0_的表示法:$00000000$ 和 $11111111$。因此采用一种更有效的补码表示法 === 补码 - $2$ 的补码是 #trans([补码], [radix complement]) 体系的一个特例。假设在基数为 _r_ 的计数体系中,数 _N_ 由 _d_ 位数字组成。若 _N_ 不为 $0$,数 _N_ 的补码定义为 $r ^ d - N$;若 _N_ 为 $0$,数 _N_ 的补码定义为 $0$ 。 - 补码其实是反码加 $1$ 。这样简化了加法和减法运算,因为减数在开始时就进行了加 $1$ 操作。所以在减法的运算过程中就不会再有高低两端的进位问题,只需简单地舍弃所有与最高位有关的进位。 - 若两个正数相加,可能产生溢出,结果为负数;若两个负数相加,也可能产生溢出,结果为正数。\ #strong([检测溢出条件的简单法则]):若进入符号位和移出符号位的进位相等,则没有溢出发生;若不同,就产生溢出,也就是出现错误 \ \ == 数的定点表示和浮点表示 在计算机中,小数点不用专门的器件表示,而是按约定的方式标出,共有两种方式表示小数点的存在,即定点表示和浮点表示。 === 定点表示 小数点固定在某一位置的数为定点数。 - 当小数点位于数符和第一数值位之间时,机器内的数为纯小数;当小数点位于数值位之后时,机器内的整数为纯整数。采用定点数的机器称为定点机。 - 数值部分的位数 n 决定了定点机中数的表示范围。若机器数采用原码,小数的表示范围为 $dash.en(1 dash.en 2 ^ n) #sym.tilde.op (1 dash.en 2 ^ n)$,整数的表示范围为 $dash.en(2 ^ n dash.en 1) #sym.tilde.op (2 ^ n dash.en 1)$ - 在定点机中,由于小数点的位置固定不变,因此当机器处理的数不是纯小数或纯整数时,必须乘上一个比例因子,否则会产生“溢出” === 浮点表示 实际上计算机中处理的数不一定时纯小数或纯整数,它们都不能用定点数表示,因此使用浮点数;浮点数即小数点的位置可以浮动的数 通常,浮点数被表示成 $N = S times r ^ j$ 式中,$S$ 为尾数(可正可负),$j$ 为阶码(可正可负),$r$ 是基数。 为了提高数据精度以及便于浮点数的比较,在计算机中规定浮点数的尾数用纯小数形式。此外,将尾数最高位为 $1$ 的浮点数称为规格化数,浮点数表示成规格化形式后,精度最高。 1. 浮点数的表示形式 - 浮点数由阶码 $j$ 和尾数 $S$ 两部分组成。阶码是整数,阶符和阶码的尾数 $m$ 合起来反应浮点数的表示范围即小数点的实际位置;尾数是整数,其位数 $n$ 反应浮点数的精度;尾数的符号 $S$ 代表浮点数的正负 2. 浮点数的表示范围 - 以通式 $N = S times r ^ j$ 为例,设浮点数阶码的数值位取 $m$ 位,尾数的数值位取 $n$ 为,其最大正数为 $2 ^ ((2 ^ m dash.en 1)) times (1 dash.en 2 ^ (dash.en n))$,最小正数为 $2 ^ (dash.en(2 ^ m dash.en 1)) times 2 ^ (dash.en n)$;最小负数为 $dash.en 2 ^ ((2 ^ m dash.en 1)) times (1 dash.en 2 ^ (dash.en n))$,最大负数为 $dash.en 2 ^ (dash.en(2 ^ m dash.en 1)) times 2 ^ (dash.en n)$。 - 当浮点数阶码大于最大阶码时,称为上溢,此时机器停止运算,进行中断溢出处理;当浮点数阶码小于最小阶码时,称为下溢,此时机器通常将尾数强置为零,继续运行。 == 定点运算 === 乘法运算 ==== 原码一位乘运算 - 运算规则: 1. 乘积的符号位由两原码符号位异或运算结果决定 2. 乘积的数值部分由两数绝对值相乘 以小数为例:\ #indent#indent $[x]_原 = x_0.x_1x_2···x_n$ #indent $[y]_原 = y_0.y_1y_2···y_n$\ #indent#indent $[x]_原 times [y]_原 = x_0 xor y_0.(0.x_1x_2···x_n) times (0.y_1y_2···y_n)$\ 可得递推公式,其中 $z_0 = 0$,$(0.x_1x_2···x_n) times (0.y_1y_2···y_n) = z_n$ $ z_i = 2 ^ (dash.en 1) times (y_(n dash.en i + 1) times x + z_(i dash.en 1)) $ ==== 补码乘法 1. 补码一位乘运算规则\ 设被乘数 $[x]_补 = x_0.x_1x_2···x_n$\ 设乘数 $[y]_补 = y_0.y_1y_2···y_n$ 1. 设被乘数 $x$ 符号任意,乘数 $y$ 符号为正,则 $ [x]_补 times [y]_补 = [x]_补 = [x]_补 times y = 2 ^(n + 1) times y + x times y = [x]_补 times y $ 可得递推公式,其中 $z_0 = 0$,$[x times y]_补 = [z_n]_补$ $ [z_i]_补 = 2 ^ (-1) times (y_(n dash.en i + 1) times [x]_补 + [z_(i dash.en 1)]_补) $ 2. 设被乘数 $x$ 符号任意,乘数 $y$ 符号为负,则 $ y = [y]_补 dash.en 2 = 1.y_1y_2···y_n dash.en 2 = 0.y_1y_2···y_n dash.en 1 $$ x times y = x(0.y_1y_2···y_n dash.en 1) = x(0.y_1y_2···y_n) dash.en x $$ [x times y]_补 = [x times (0.y_1y_2···y_n)]_补 + [dash.en x]_补 = [x]_补 times (0.y_1y_2···y_n) + [dash.en x]_补 $可得递推公式,其中 $z_0 = 0$,$[x times y]_补 = [z_n]_补 + [dash.en x]_补$ $ [z_i]_补 = 2 ^ (-1) times (y_(n dash.en i + 1) times [x]_补 + [z_(i dash.en 1)]_补) $ 3. 被乘数 $x$ 和 乘数 $y$ 符号均为任意\ 按补码乘法规则,其基本算法可用一个统一的公式表示为 $ [x times y]_补 = [x]_补 times (0.y_1y_2···y_n) + [dash.en x]_补 times y_0 $在 $mod 2$ 的前提下,易证 $[dash.en x]_补 = dash.en[x]_补$\ 可得递推公式,其中 $z_0 = 0, y_(n + 1) = 0$,$[x times y]_补 = [z_n]_补 + (y_1 - y_0) times [x]_补$ $ [z_i]_补 = 2 ^ (dash.en 1) times ([z_(i dash.en 1)]_补 + (y_(n dash.en i + 2) dash.en y_(n dash.en i + 1)) times [x]_补) $ === 除法运算 ==== 原码除法 - 运算规则: 1. 原码除法和原码乘法一样,符号位单独处理 2. 乘积的数值部分由两数绝对值相除求得 3. 小数定点除法对被除数和除数由一定的约束,即必须满足:$0 < |#[被除数]| < |#[除数]|$ 以小数为例:\ #indent#indent $[x]_原 = x_0.x_1x_2···x_n$ #indent $[y]_原 = y_0.y_1y_2···y_n$\ #indent#indent $[x / y]_原 = (x_0 xor y_0).(0.x_1x_2···x_n) / (0.y_1y_2···y_n)$ - 恢复余数法:当余数为负时,需加上除数,将其恢复成原来的余数;当余数为正时,左移一位继续进行除法,直至商位数与操作数相同 - 加减交替法:当余数 $R_i #sym.gt 0$,商上 $1$,做 $2R_i - y^*$ 操作;当余数 $R_i #sym.lt 0$,商上 $0$,做 $2R_i + y^*$ 操作 - 总结:$n$ 位小数的除法共上商 $n + 1$ 次(第一位商判断是否溢出),左移 $n$ 次 ==== 补码除法 加减交替法: - 运算规则: 1. 比较被除数和除数的大小\ 补码除法的操作数均为补码,其符号又是任意的,因此要比较被除数 $[x]_补$ 和除数 $[y]_补$ 的大小。比较算法可以归纳为两种: 1. 当被除数与除数同号时,做减法,若得到的余数与除数同号,表示够减 2. 当被除数与除数异号时,做加法,若得到的余数与除数异号,表示够减 2. 商值的确定 1. $[R_i]_补$ 与 $[y]_补$ 同号时,上商 $1$,$[R_(i + 1)]_补 = 2 times [R_i]_补 + [dash.en y]_补$ 2. $[R_i]_补$ 与 $[y]_补$ 异号时,上商 $0$,$[R_(i + 1)]_补 = 2 times [R_i]_补 + [y]_补$ - 总结:$n$ 位小数的补码除法共上商 $n + 1$ 次(末位恒置 $1$),第一位商判断是否溢出,左移 $n$ 次
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2018/WS-06.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [DING Ning], [CHN], [3439], [2], [ZHU Yuling], [MAC], [3412], [3], [LIU Shiwen], [CHN], [3347], [4], [CHEN Meng], [CHN], [3307], [5], [WANG Manyu], [CHN], [3248], [6], [CHEN Xingtong], [CHN], [3158], [7], [ITO Mima], [JPN], [3144], [8], [SUN Yingsha], [CHN], [3144], [9], [ISHIKAWA Kasumi], [JPN], [3143], [10], [MU Zi], [CHN], [3126], [11], [WU Yang], [CHN], [3094], [12], [FENG Yalan], [CHN], [3056], [13], [GU Yuting], [CHN], [3030], [14], [FENG Tianwei], [SGP], [3029], [15], [HIRANO Miu], [JPN], [2966], [16], [WEN Jia], [CHN], [2958], [17], [HU Limei], [CHN], [2945], [18], [CHENG I-Ching], [TPE], [2944], [19], [HE Zhuojia], [CHN], [2939], [20], [DOO Hoi Kem], [HKG], [2938], [21], [CHEN Ke], [CHN], [2936], [22], [SHIBATA Saki], [JPN], [2934], [23], [JEON Jihee], [KOR], [2931], [24], [POLCANOVA Sofia], [AUT], [2921], [25], [#text(gray, "LI Xiaodan")], [CHN], [2903], [26], [LI Qian], [POL], [2895], [27], [SUH Hyo Won], [KOR], [2883], [28], [SAMARA Elizabeta], [ROU], [2875], [29], [KIM Song I], [PRK], [2874], [30], [KATO Miyu], [JPN], [2867], [31], [WANG Yidi], [CHN], [2863], [32], [SZOCS Bernadette], [ROU], [2860], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [ZHANG Qiang], [CHN], [2854], [34], [HASHIMOTO Honoka], [JPN], [2850], [35], [GU Ruochen], [CHN], [2849], [36], [CHE Xiaoxi], [CHN], [2845], [37], [SOLJA Petrissa], [GER], [2835], [38], [ZHANG Mo], [CAN], [2832], [39], [ZHANG Rui], [CHN], [2831], [40], [NAGASAKI Miyu], [JPN], [2829], [41], [HAN Ying], [GER], [2827], [42], [SHI Xunyao], [CHN], [2822], [43], [EERLAND Britt], [NED], [2816], [44], [SAWETTABUT Suthasini], [THA], [2815], [45], [SHAN Xiaona], [GER], [2814], [46], [YANG Xiaoxin], [MON], [2804], [47], [HU Melek], [TUR], [2804], [48], [EKHOLM Matilda], [SWE], [2803], [49], [CHA Hyo Sim], [PRK], [2803], [50], [#text(gray, "KIM Kyungah")], [KOR], [2794], [51], [HAYATA Hina], [JPN], [2792], [52], [SATO Hitomi], [JPN], [2787], [53], [YU Fu], [POR], [2786], [54], [ANDO Minami], [JPN], [2778], [55], [SOO Wai Yam Minnie], [HKG], [2777], [56], [KIM Nam Hae], [PRK], [2775], [57], [CHOI Hyojoo], [KOR], [2767], [58], [SUN Mingyang], [CHN], [2765], [59], [#text(gray, "TIE Yana")], [HKG], [2764], [60], [LEE Ho Ching], [HKG], [2762], [61], [#text(gray, "SHENG Dandan")], [CHN], [2754], [62], [LIU Xi], [CHN], [2753], [63], [XIAO Maria], [ESP], [2750], [64], [LEE Eunhye], [KOR], [2749], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [LI Jie], [NED], [2748], [66], [ZENG Jian], [SGP], [2745], [67], [NI Xia Lian], [LUX], [2739], [68], [LI Jiao], [NED], [2738], [69], [LIU Jia], [AUT], [2736], [70], [MORI Sakura], [JPN], [2736], [71], [LANG Kristin], [GER], [2735], [72], [MITTELHAM Nina], [GER], [2730], [73], [POTA Georgina], [HUN], [2723], [74], [WU Yue], [USA], [2718], [75], [BALAZOVA Barbora], [SVK], [2715], [76], [#text(gray, "JIANG Huajun")], [HKG], [2714], [77], [HAPONOVA Hanna], [UKR], [2712], [78], [LIU Gaoyang], [CHN], [2712], [79], [HAMAMOTO Yui], [JPN], [2709], [80], [LEE Zion], [KOR], [2706], [81], [LI Fen], [SWE], [2706], [82], [LI Jiayi], [CHN], [2694], [83], [<NAME>aki], [JPN], [2693], [84], [MATSUZAWA Marina], [JPN], [2687], [85], [<NAME>], [CZE], [2687], [86], [<NAME>], [JPN], [2679], [87], [<NAME>], [KOR], [2679], [88], [<NAME>], [SLO], [2678], [89], [<NAME>], [JPN], [2674], [90], [<NAME>], [UKR], [2669], [91], [<NAME>], [CHN], [2659], [92], [<NAME>], [KOR], [2658], [93], [ZH<NAME>ofia-Xuan], [ESP], [2649], [94], [<NAME>], [PUR], [2649], [95], [KIM Youjin], [KOR], [2648], [96], [<NAME>], [JPN], [2647], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [ZHOU Yihan], [SGP], [2641], [98], [HUANG Yi-Hua], [TPE], [2640], [99], [MIKHAILOVA Polina], [RUS], [2632], [100], [#text(gray, "<NAME>")], [PRK], [2630], [101], [YOO Eunchong], [KOR], [2629], [102], [ODO Satsuki], [JPN], [2625], [103], [#text(gray, "SONG Maeum")], [KOR], [2622], [104], [LIN Ye], [SGP], [2621], [105], [<NAME>], [JPN], [2621], [106], [<NAME>], [ESP], [2620], [107], [ZHANG Lily], [USA], [2618], [108], [YU Mengyu], [SGP], [2617], [109], [#text(gray, "VACENOVSKA Iveta")], [CZE], [2610], [110], [VOROBEVA Olga], [RUS], [2607], [111], [#text(gray, "CHOI Moonyoung")], [KOR], [2607], [112], [<NAME>], [POL], [2606], [113], [<NAME>], [IND], [2606], [114], [<NAME>-Yu], [TPE], [2602], [115], [<NAME>], [JPN], [2598], [116], [<NAME>], [ROU], [2591], [117], [NG Wing Nam], [HKG], [2591], [118], [PASKAUSKIENE Ruta], [LTU], [2585], [119], [PROKHOROVA Yulia], [RUS], [2585], [120], [<NAME>], [HUN], [2581], [121], [LIN Chia-Hui], [TPE], [2567], [122], [SABITOVA Valentina], [RUS], [2566], [123], [SO Eka], [JPN], [2565], [124], [CHOE Hyon Hwa], [PRK], [2565], [125], [<NAME>], [JPN], [2561], [126], [<NAME>], [CRO], [2561], [127], [<NAME>], [TPE], [2556], [128], [NOSKOVA Yana], [RUS], [2554], ) )
https://github.com/SkytAsul/fletchart
https://raw.githubusercontent.com/SkytAsul/fletchart/main/examples/logical.typ
typst
#import "../src/lib.typ" as fletchart #import fletchart.logical: fc-logical, fc-if, fc-process, fc-begin, fc-end, fc-io, fc-predefined-process #fc-logical({ fc-begin[Thing] fc-if([Condition ?], { fc-io[Some IO] }, { [A random process] ```python print("Hello world") ``` fc-if([Another condition ?], yes-label: "valid", { fc-predefined-process()[Predefined\ process] }, no-label: "invalid", { fc-end(fill: color.red)[Alright bye] }) }, extrude: (0, 2)) fc-end[Followup and end] }, if-yes-label: "Yas", if-no-label: "Non", debug: true)
https://github.com/typst-community/mantodea
https://raw.githubusercontent.com/typst-community/mantodea/main/src/author.typ
typst
MIT License
#import "/src/_pkg.typ" #import "/src/_valid.typ" /// The marks used in `author` for automatic mark numbering. /// /// Can be used to add new or alter existing marks, marks come in the form of /// arbitrary content which is placed as a superscript. #let marks = state("__mantodea:author:marks", ( marks: (:), current-auto: 0, )) /// Display a person with the given options. /// /// - short (int): The shortness level. /// - `0`: do not shorten any names /// - `1`: shorten middle names /// - `2`: shorten middle and first names /// - ..first (str): The first and middle names. /// - last (str, array): The last names. /// -> content #let name( short: 1, ..first, last, _validate: true, ) = { if _validate { import _valid as z _ = z.parse(first, z.sink(positional: z.array(z.string())), scope: ("first",)) _ = z.parse(last, z.array(z.string(), pre-transform: z.coerce.array), scope: ("last",)) _ = z.parse(short, z.integer(min: 0, max: 2), scope: ("short",)) } first = first.pos() if type(first) == str { first = (first,) } if type(last) == str { last = (last,) } let short = if first != () { let shorten(name) = name.clusters().first() + "." let (first, ..middle) = first if short > 0 { middle = middle.map(shorten) } if short > 1 { first = shorten(first) } (first, ..middle).join(" ") } if short != none { short [ ] } smallcaps(last.join(" ")) } /// Show full author information, see also `name`. /// /// - short (int): The shortness level. /// - `0`: do not shorten any names /// - `1`: shorten middle names /// - `2`: shorten middle and first names /// - label (label, none): The label to use for email attribution, see `email`. /// - email (str, content, none): The email to attribute the user to. /// - ..first (str): The first and middle names. /// - last (str, array): The last names. /// -> content #let author( short: 1, label: none, email: none, ..first, last, _validate: true, ) = { if _validate { import _valid as z _ = z.parse(first, z.sink(positional: z.array(z.string())), scope: ("first",)) _ = z.parse(last, z.array(z.string(), pre-transform: z.coerce.array), scope: ("last",)) _ = z.parse(short, z.integer(min: 0, max: 2), scope: ("short",)) _ = z.parse(email, z.content(optional: true), scope: ("email",)) _ = z.parse(label, z.label(optional: true), scope: ("label",)) } name(..first, last, short: short, _validate: false) if label != none { context super(marks.final().marks.at(str(label))) } if email != none { [ ] link("mailto:" + email, "<" + email + ">") } } /// Display an email attribution, i.e. a mark that can be linked to from /// `author`. /// /// - mark (content, auto): A symbol used for attribution, the linked authors /// will have this displayed as a super script. Uses `*` numbering if `auto`. /// - label (label): The label to use in `author` for automatic attribution. /// - body (str, content): The body to attribute the authors to, this is often /// a generic email pattern such as `"<<EMAIL>"`, but doesn't /// have to be. /// -> content #let email( mark: auto, label, body, _validate: true, ) = { if _validate { import _valid as z _ = z.parse(body, z.content(optional: true), scope: ("body",)) _ = z.parse(mark, z.either(z.content(optional: true), z.auto_()), scope: ("mark",)) _ = z.parse(label, z.label(optional: true), scope: ("label",)) } if mark == auto { marks.update(m => { m.current-auto += 1; m.marks.insert(str(label), numbering("*", m.current-auto)) m }) } else { marks.update(m => { m.marks.insert(str(label), mark) m }) } context super(marks.final().marks.at(str(label))) body }
https://github.com/tiankaima/typst-notes
https://raw.githubusercontent.com/tiankaima/typst-notes/master/333aba-optimization/main.typ
typst
#set text( font: "Source Han Serif SC", size: 10pt, ) #align( center, text(20pt)[ 2023秋 运筹学 笔记 & 作业 ], ) #align( center, text(12pt)[ 马天开 PB21000030 ], ) #align( center, text(12pt)[ 上次修改:#datetime.today().display("[year]-[month]-[day]") ], ) #set math.equation(numbering: "(1)") #outline(depth: 1) #pagebreak() = 第一次书面作业 ```txt 1.1 1.2 2.1 2.2 2.3 2.4 2.5 ``` == Q1.1 === 问题 考虑稀疏优化问题,我们已经直观地讨论了在 $italic(l)_0,italic(l)_1,italic(l)_2$ 三种范数下问题的解的可能形式.针对一般的$italic(l)_p$范数”: $ norm(x)_p := (sum_(i=1)^n abs(x_i)^p)^(1 / p), quad 0<p<2 $ 我们考虑优化问题: $ min norm(x)_p, quad "s.t." A x = b $ 试着用几何直观的方式来说明当$p in (0,2)$取何值时,问题的解可能具有稀疏性。 === 答案 如下图所示,绘制了题目中要求的$p in (0,2)$中六个参数点,由这样的几何直观,可以说明,当$p in (0,1]$时,问题的解可能具有稀疏性。 #align(center, image("./imgs/1.jpg", width: 60%)) == Q1.2 === 问题 给定一个函数$f(x):RR^n -> RR$及其一个局部最优点$x^*$,则该点沿任何方向$d in RR^n$也是局部最优的,即$0$为函数$Phi(alpha):=f(x^*+alpha d)$的一个局部最优解。反之,如果$x^*$沿任何方向$d in RR^n$都是局部最优解,则$x^*$是否是$f(x)$的一个局部最优解?若是,请给出证明;若不是,请给出反例。 === 答案 不成立,考虑一个沿任何径向均是局部最优解的函数,使其沿切向无穷震荡,即可构造出反例。 $ f(r,theta) = cases( r^2 dot.c sin(1/theta) quad& theta != 0, 0 quad& theta = 0 ) $ == Q2.1 === 问题 说明矩阵$F$范数不是算子范数(即它不可能被任何一种向量范数所诱导)。提示:算子范数需要满足某些必要条件,只需找到一个$F$范数不满足的必要条件即可。 === 答案 考虑最简单的$I_n$,在任何算子范数意义下,$norm(I_n):= max_(norm(x)=1)norm(I_n dot.c x) eq.triple 1$,但在矩阵$F$范数意义下,$norm(I_n):= n != 1$,因此矩阵$F$范数不是算子范数。 == Q2.2 === 问题 证明:矩阵 $A$ 的 $2$ 范数等于其最大奇异值,即 $ norm(A)_2 = max_(norm(x)_2=1) norm(A x)_2 = sqrt(lambda_max) $ === 答案 $ norm(A x)_2 = sqrt((A x)^T (A x)) = sqrt(x^T (A^T A) x) $ 同时注意到$A^T A$是半正定矩阵(因为$x^T A^T A x>=0$,特征值满足$lambda_1 >= dots.c >= lambda_n >= 0$),对应的特征向量$alpha_1 dots.c alpha_n$构成$RR^n$的一组标准正交基,那么设$x=sum_(i=1)^n k_i alpha_i$,因为$norm(x)=1$,所以有$sum_(i=1)^n k_i^2=1$ 带入上式,有 $ A^T A x = A^T A dot.c (sum_(i=1)^n k_i alpha_i) = sum_(i=1)^n k_i A^T A alpha_i = sum_(i=1)^n k_i lambda_i alpha_i $ 则 $ x^T A^T A x = sum_(i=1)^n k_i^2 lambda_i <= max_i lambda_i $ 因此 $ sqrt((A x)^T (A x)) <= sqrt(lambda_max) $ 显然当$x=alpha_1$时,等号成立,因此 $ norm(A x)_2 = max_(norm(x)_2=1) norm(A x)_2 = sqrt((A x)^T (A x)) = sqrt(lambda_max) $ == Q2.3 证明如下有关矩阵范数的不等式: $ & (a) quad norm(A B)_F <= norm(A)_2 norm(B)_F \ & (b) quad abs(angle.l A "," B angle.r) <= norm(A)_2 norm(B)_* \ $ == 答案 === (a) 对$A^T A$进行正交对角化: $ A^T A = Q Lambda Q^T $ 在此基础上, $ norm(A B)_F^2 = tr((A B)^T(A B)) = tr(B^T A^T A B) = tr(B^T Q Lambda Q^T B) = tr(Q^T B B^T Q Lambda) = tr(Z Z^T Lambda) $ 其中$Z:=Q^T B$ 根据$tr$的定义,容易看出上式小于等于$sum_(i=1)^n lambda_i z_i^2$,其中$lambda_i$是$Lambda$的对角元(其最大值为$A$的2-范数的平方,最大奇异值),而$z_i^2$是$Z Z^T$的第$i$个对角元($Q$是正交矩阵,因此$Z Z^T$的对角元最大值为$B$的F-范数的平方),因此有 $ norm(A B)_F^2<=norm(A)_2^2 norm(B)_F^2 $ === (b) 对$B$进行SVD分解: $ B = U Sigma V^T $ 带入内积定义: $ angle.l A , B angle.r = tr(A B^T) = tr(A^T U Sigma V^T) = tr(V^T A^T U Sigma) $ 设$Z:=V^T A^T U$,则 $ angle.l A , B angle.r = tr(Z dot.c Sigma) $ 同样按照上面的证明思路,上式小于等于$sum_(i=1)^n z_i sigma_i$,其中$z_i$是$Z$的第$i$个对角元(在正交变化下保证2-范数不变),而$sigma_i$是$Sigma$的第$i$个对角元(其最大值为$B$的核范数),因此有 $ angle.l A , B angle.r <= norm(A)_2 norm(B)_* $ == Q2.4 === 问题 设矩阵$A$为 $ A = mat( I, B; B^T, I; ) $ 其中$norm(B)_2 < 1$,$I$为单位矩阵。证明$A$可逆且 $ norm(A)_2 norm(A^(-1))_2 = (1+norm(B)_2) / (1-norm(B)_2) $ === 答案 $ A^(-1) = 1 / abs(I-B B^T) mat( I, -B; -B^T, I; ) $ 实在是没什么思路,sorry,后面会补上的。 == Q2.5 === 问题 计算下面矩阵变量函数的导数 - $f(X) = a^T X b$ - $f(X) = tr(X^T A X)$ - $f(X) = ln(det(X)), det(X)>0$ === 答案 - $nabla f(X) = a b^T$ - $nabla f(X) = (A + A^T)X$ - $nabla f(X) = X^(-T)$
https://github.com/UriMtzF/uaemex-typst-template
https://raw.githubusercontent.com/UriMtzF/uaemex-typst-template/main/README.md
markdown
Apache License 2.0
# uaemex-typst-template A simple template for UAEMéx ingeneering documents
https://github.com/VanillaViking/epm-task4-reflection
https://raw.githubusercontent.com/VanillaViking/epm-task4-reflection/master/task4.typ
typst
#import "@preview/wordometer:0.1.1": word-count, total-words #align(center, text(20pt)[ *Task 4 - Post Project Evalutation* ]) #align(center, text(17pt)[ Engineering Project Management ]) #align(center, text(14pt)[ <NAME> - 14259321 ]) #set heading(numbering: "1.a") #show link: underline #show link: set text(blue) #show cite: set text(maroon) #show: word-count #outline() #pagebreak() // describe situation // what you expected // what was outcome // your actions, learning // things you would do differently based on learning // future actions with suitable references // // associate with assessment task 2 // did the factos pay a role? // did you implement any of these learnings // what was your role in influencing = Introduction In assignment 2, we investigated a variety of projects both successful and unsuccessful and examined the major factors that impacted it's ultimate outcome. With the conclusion of asssignment 3, we have an opportunity to reflect and evaluate what factors relate to our scenario. Overall, I believe that the project went smoothly, as most of our team members were proactive about finishing the work in a timely manner. I believe that the project is likely to be successful due to the clear objective and goal from the beginning. The requirements are unlikely to change throughout the course of the project, providing additional stability and stakeholder satisfaction. The development of the smart-bin project is also predicted to cost approximately \$180,000 AUD, which is a relatively inexpensive cost, making the project is less sensitive to budget overruns. = Communication == Relation to Task 2 In assignment task 2, I analysed how companies like SpaceX and Dyson were affected by their method and quality of commiunication to their stakeholders. SpaceX's falcon 1 project suffered many initial setbacks, which would normally discourage shareholders and sponsors from offering further support. However, SpaceX managed to instill confidence in stakeholders despite this, by showing tangible progress with each failed launch attempt. They were able to retain many customers thanks to their strong communication and marketing skills. On the other hand, Dyson's Electric Car project suffered from a lack of proper communication with the stakeholders. They were promised the car would meet the requirements however, infrequent communication of technical and financial difficulties left the stakeholders, employees and the public in the dark about the true progress of the car, breaking their trust in the project's success, which contributed to the failure of the project. In assignment 3, we came across several situations where communication with the stakeholder was crucially important to ensure that our deliverable met their standards. For the most part, we maintained frequent communication with our tutor about the different parts of our report, and worked to implement any feedback that was requested. However, we made some assumptions about the activity plan and network diagram that we didn't get a chance to discuss with the tutor. == Situation Description We had recently finished up our Work Breakdown Structure diagram, and had a discussion with the tutor about it. At the time, we felt confident that we implemented the feedback well and our diagram was perfect, so we agreed that we will not need another meeting with the tutor for a while. We moved on to making the activity plan and network diagram for the report, however, some of the tasks in the activity plan did not relate to the WBS. This was a crucial mistake, as the activity plan should include all work packages in the WBS. The activity plan being correct is also important for the validity of the network diagram and gantt chart, which could have implications for the rest of the project report. We discovered this fatal flaw very late in the process, which caused a significant amount of frustration within the team. Upon realizing the mistake, our group convened an emergency meeting to reassess our approach. We identified the and re-evaluated our activity plan and network diagram. Despite the time constraints, we redistributed tasks to correct the errors and ensure that the revised proposal was as accurate and detailed as possible. This involved late nights and additional meetings to synchronize our efforts and incorporate last-minute feedback from our tutor. == Expectations and Actual Outcomes Initially, I expected our group work to be smooth and well-coordinated. We had clear roles, and everyone seemed committed to meeting deadlines and contributing effectively. I anticipated that our final proposal would be well-received due to our thorough planning and teamwork. However, the actual outcome diverged significantly from these expectations. The lack of timely feedback on our activity plan and network diagram meant that our foundational assumptions were flawed, causing delays and necessitating significant revisions. == Actions Taken My role for the project was to create the network diagram as well as gantt chart for the scheduling section of the project. I was unaware of the problems with the activity plan, therefore I copied the activities from it to create my network diagram. The other members in the group also failed to recognise this issue, and we continued to work on the tasks we were assigned nonetheless. In retrospect, the lack of action from any group member to briefly reach out to the tutor or teaching staff caused the situation to go unnoticed until very late. I personally was in charge of the emergency meeting and kept meeting minutes and notes so that everyone could be kept accountable for their parts. I also volunteered to fix the network diagram and gantt chart. Looking back, I was too eager to get started on the diagrams. I should have communicated with my team, or read the lecture notes before commencing, to get a better idea of the requirements for my part. This could have potentially uncovered the flaws that we missed, saving us time and effort later on. I also was not involved too deeply in the parts of other team members, which caused me to have a shallow understanding of their parts. If I had a more thorough understanding of the whole project, I might have been able to spot the issue earlier. == Learning for the Experience This incident underscored the importance of seeking regular feedback throughout the course of a project. It significantly improves the quality of the project by identifying and correcting issues early, ensuring higher quality outcomes. Regular feedback fosters open communication, keeping all team members aligned and aware of project progress and expectations. This continuous exchange of information facilitates learning and growth, as team members can learn from their mistakes and successes, enhancing their skills and performance over time. Additionally, it ensures stakeholder satisfaction by keeping them informed and involved, thereby meeting their needs and expectations and reducing the risk of project rejection or dissatisfaction. == Future Actions To ensure that such issues are not encountered in the future, a routine for seeking feedback at critical milestones must be established. Scheduling regular meetings, such as daily stand-ups, weekly reviews, or bi-weekly retrospectives, facilitates consistent discussions on progress, issues, and next steps. Documenting feedback and the subsequent actions taken further aids in tracking progress and maintaining accountability. It is crucial to follow up on feedback, acting on the insights shared and communicating any resulting changes or improvements, demonstrating that feedback is valued and taken seriously. In order to do this, the team must make sure that everyone is involved when acknowledging feedback and no single person takes the entire blame @feedbackfollow. Furthermore, our group was excellent at meeting deadlines. All members would often finish their tasks ahead of schedule. This was crucial as it allowed us to be able to spend more time on fixing the parts of our report which were unsatisfactory. I learned that it is important to put in place a bit of buffer time in schedules to accommodate potential revisions and unforeseen issues. This helps manage risks effectively and ensures smoother project execution @buffertime. = Final Statement In conclusion, I believe that our group was successful in ideating and planning a smart-bin project. We were able to learn from previous projects that we researched in assignment 2, and approach the group project with awareness of important factors that will dictate the success of the project. Attached below is the team's analysis of our performance. #figure( image("task4matrix.png", width: 80%), caption: [Team Analysis], ) <ta> #bibliography("ref.bib", style: "apa") #pagebreak() = Appendix #figure( image("actionappendix.png", width: 60%), caption: [My role & actions within the team: meeting minutes], ) <ta> #figure( image("newactivities.png", width: 60%), caption: [My actions within the team: updating the activity plan], ) <ta>
https://github.com/Akelio-zhang/cv-typst
https://raw.githubusercontent.com/Akelio-zhang/cv-typst/main/README.md
markdown
## Structure - cv.typ: Content of the CV. - meta.typ: CV template code. - justfile: Recipe file for building. ## Features - [x] Support both Chinese and English in one file. Default to Chinese. - [x] Support hiding some sections for conciseness. Default to display all. ## Generation - Upload cv.typ and meta.typ to [typst](https://typst.app/), and use web app to generate. - Using [just](https://github.com/casey/just), with arguments: - `la`: Choose between Chinese (zh) or English (en). - `output`: Choose between concise or full for output. - Examples: - `just` generates a concise PDF file in Chinese. - `just compile-all` generates all types of PDF files. - `just compile en full` generates a full PDF file in English. - Using `bash` ```bash echo '#let render_mode = (la: "zh", output: "concise")' > f.typ && sed 1d cv.typ >> f.typ && typst compile f.typ cv.pdf && rm f.typ ``` ![cv.png](cv.png)) ## Reference - [typst](https://typst.app/docs/) - [conditional render](https://typst.app/docs/reference/scripting/#conditionals) - [chicv](https://github.com/skyzh/chicv) - [just](https://just.systems/man/zh/) ## FAQ - Why font seems not work? A: check with `typst fonts`.
https://github.com/cwreed/cv
https://raw.githubusercontent.com/cwreed/cv/main/src/metadata.typ
typst
#let firstName = "Connor" #let lastName = "Reed" #let personalInfo = ( github: "cwreed", email: "<EMAIL>", linkedin: "connor-reed", ) #let choiceColor = "clay" #let profilePhoto = "" #let varDisplayLogo = false #let varEntrySocietyFirst = true
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/heading-04.typ
typst
Other
// Edge cases. #set heading(numbering: "1.") = Not in heading =Nope
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/examples/university.typ
typst
#import "../lib.typ": s, pause, meanwhile, utils, states, pdfpc, themes #let s = themes.university.register(s, aspect-ratio: "16-9") #let s = (s.methods.info)( self: s, title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], ) #let (init, slides, touying-outline, alert) = utils.methods(s) #show: init #let (slide, title-slide, focus-slide, matrix-slide) = utils.slides(s) #show: slides.with(title-slide: false) #title-slide(authors: ("Author A", "Author B")) = The Section == Slide Title #slide[ #lorem(40) ] #slide(subtitle: emph[What is the problem?])[ #lorem(40) ] #focus-slide[ *Another variant with primary color in background...* ] #matrix-slide[ left ][ middle ][ right ] #matrix-slide(columns: 1)[ top ][ bottom ] #matrix-slide(columns: (1fr, 2fr, 1fr), ..(lorem(8),) * 9)
https://github.com/jamesrswift/pixel-pipeline
https://raw.githubusercontent.com/jamesrswift/pixel-pipeline/main/src/package.typ
typst
The Unlicense
#let package = toml("../typst.toml").package
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/spread-02.typ
typst
Other
// Test doing things with arguments. #{ let save(..args) = { test(type(args), "arguments") test(repr(args), "(three: true, 1, 2)") } save(1, 2, three: true) }
https://github.com/MilanR312/ugent_typst_template
https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/template/appendices.typ
typst
MIT License
// add links to appendices here if needed
https://github.com/ParadiseOS/ParadiseDocs
https://raw.githubusercontent.com/ParadiseOS/ParadiseDocs/main/RCOS/Proposals/main.typ
typst
MIT License
#import "template.typ": * #show: project.with( title: "Paradise OS", authors: ( "<NAME>", "<NAME>", "<NAME>", ), date: $bold("Spring 2024 - Version 0.1.0")$, ) = Overview == Vision ParadiseOS is an x86, 32-bit, multi-core, general-purpose operating system. ParadiseOS is designed to redefine the developer experience in the digital realm. Imagine a seamless fusion of performance and elegance, while navigating through tasks feels like a stroll through a virtual paradise. With a sleek and intuitive VGA terminal interface which boasts 16 colors and 256 extended ascii characters. Harnessing the power of Docker allowing for effortless set up and unparalleled portability, ParadiseOS aims to be a beacon of innovation, transforming the current mundane developer experience into a captivating one. ParadiseOS envisions a future where the operating system isn't just a tool but an immersive gateway to a developers utopia. == Stack - C - x86 Assembly - QEMU - Shell - Docker - GNU Make = Goals + A functioning, bootable OS + A working terminal + A lottery scheduler + Memory Management (Virtual Memory and Paging) + Semi-Working File System (Definitely not) = Milestones #set enum(numbering: "I.a.") + January - Get the OS to boot - Basic Kernel - Handling Interupts + Initialize a simple Global Descriptor Table and Interrupt Descriptor Table - Research + Designing Memory, Scheduler, and File System + February - Functional Terminal + Implement basic I/O + Have very basic functionality working - Kernel Enhancements + Expand kernel functionality for improved system support - Memory Management + Developing initial page tables and handling basic page faults + Begin implementing virtual memory and paging - Research + March - Begin work on File System + Define the basic structure + Groundwork of essential file operations - Begin Implementing a basic lottery scheduler + Develop task scheduling algorithms to allocate CPU time among processes - Research + April - Begin working on final presentations/poster - Wrap up any unfinished work - Documentation - Release version 0.1 = Team <NAME> - Taking RCOS for credit, Coordinator <NAME> - Taking RCOS for credit, Mentor <NAME> - Taking RCOS for credit, Member
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/056%20-%20Outlaws%20of%20Thunder%20Junction/004_Blood%20Is%20Thicker%20than%20Venom.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Blood Is Thicker than Venom", set_name: "Outlaws of Thunder Junction", story_date: datetime(day: 14, month: 03, year: 2024), author: "<NAME>", doc ) It's dark, the bedroom overlooking Saddlebrush lit by candlelight and the glow of the moon, when Annie Flash leaves a stranger's bed. Everything about the moment hangs in the in-between, where familiarity can no longer be feigned. It seems appropriate for a moment like this to be overstuffed with shadows. As she redresses, another sits up in bed. "You ain't gotta run outta here." #emph[Ain't gotta] is a separate sentiment from #emph[shouldn't] . And while Annie supposes she doesn't have to leave, she should, and she is. "Sorry, Jordan. I got my own bed to keep warm." The fringe on her boots, beaded with bone and turquoise, rattles when she tugs them on. The shadow cocks its head. "Jody. Name's Jody." "Oh, right. Sorry." Annie ain't sorry, same as she didn't forget Jody's name or any detail of the sad backstory he'd whittled her. <NAME>, who'd left his old life behind a year earlier when the only woman he'd ever loved died slow and painful in their bed. Annie rises, tossing her braid over her shoulder. "S'alright." The shadow leans closer. "I'm just saying—your bed could probably survive without you for one night." Neither Jody nor his shadow sees Annie wince, too good at keeping her cool to tip her hand. But the phrasing of his invitation makes her stomach gurgle. She needs to get home, and quick. "I hope you didn't get the wrong idea," Annie laments. She reaches over to the bedside table to grab her thunder blaster—a piddling little thing compared to what she used to carry, but a weapon, nonetheless. "I'm not lookin' for anything except what I got." Tucking the blaster into its holster at her thigh, she glances at Jody's face. He's handsome, with silver curls and dark green eyes, full lips and stubble—but there's never been a man handsome enough to hold her attention. Of all the lies Annie might tell, that's one truth. Jody raises an eyebrow and leans back, resting against his pillows and folding his hands over his bare stomach. "I'm not, either." She gives him a once-over at the unexpected rebuff. "Oh?" "I had my great love. I'm just passin' the time." He shrugs. "Don't mean you can't sleep with your head on my chest. We're still #emph[people] ." Jody has the audacity to wink when he adds, "Even if I don't wanna be your boyfriend." "Hmm." She considers the offer. She #emph[knows] she can't stay, and for more reasons than one. Like how she's needed elsewhere. Or how she'd have to lose her fool mind to fall asleep vulnerable to a stranger. Still. It ain't the worst thing in the world to imagine how things might be different if she could say yes. If her life was the kind of life that'd let her spend the night with nice, handsome widowers with warm, rough hands. Ah, hell. No use fantasizing. It is what it is. "I'll see you around, Joey." She tips her hat at him before getting gone. Behind her, she swears the shadow chuckles. Down the stairs and outside into the belly of Saddlebrush's main square, the moonlight is brighter than in Jody's dusty bedroom. The glimmer casts a fog on the sleeping town, hollowed except for Annie herself. For a moment, she pretends she's the only one in the world, just her and the dark and the moon and the shadows the three of them make. The moment passes. Annie catches movement in the distance, a slithering shadow crawling through her periphery. Her head jerks in the direction of the dunes stretched out on the outskirts of town, and her mismatched eyes narrow to make out the shape more clearly. But there's nothing. Whatever Annie thought she saw, it's either gone or never was. The dunes are as still and empty as the rest of this place. Unease makes her teeth gnash. She considers using her gift, the sight of her golden right eye, to search the dunes more closely. Frustrated with herself for even considering it, she turns away and storms in the direction of home. There's nothing out there. Her paranoia's getting worse, always thinking there's some boogeyman lurking around the corner. Course, in her defense, there usually is. At least there #emph[has] been, up till now. And even if Saddlebrush #emph[looks] abandoned, there's no knowing who's hiding in the darkened windows and doorways. She needs to get home. Jody might get to be a person, but Annie is a weapon. She can't get dull. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Home is a long enough walk that Annie's thighs are well burning by the time it comes into view. Her left leg—always actin' up—gives a particularly pointed twitch as she starts toward her front door. The badlands farm hasn't been home for long, but it's something. Maybe someday she'll call this place home and mean it. "Hey, you," she drawls as she approaches the barn. All her life, Annie's been around animals, learning how to tame one creature or another, but none of 'em have ever stumped her quite like Fortune. She ain't sure where he came from or what he is, but she knows he's hers and she's his. Built like an eighteen-hand stallion, with a coat as red as clay and horns curled up from his skull, Fortune has dark eyes like twin canyons. "You holdin' down the fort?" she asks, blunt nails scratching a greeting down his neck. The question is rhetorical, and it ain't. Annie don't expect Fortune to take care of the farm while she's gone. And #emph[yet] . He nickers, stomping one foot and tilting his head to look in her eyes more closely. "Don't start. I wasn't gone that long." He huffs, shaking his head until her hand falls away. "Besides, I can take care of myself. Don't have a fit. You're getting more paranoid than I am." Fortune slowly leans his head back as if offended. Fair enough. "Alright, alright. I'm sorry." Annie sighs and glances up at the farmhouse. Even though she don't make the conscious decision to check, her eyes go straight to one window in particular. She's not surprised to see there's a yellow light glowing inside. Despite the lateness of the hour, a shadow shifts in the room beyond the curtains. "He been awake this whole time?" Fortune bobs his head. "Alright. I'll take it from here. You get some sleep." She swats at his side. "We gotta head into town again tomorrow, and I don't need you wandering off under me. It's easy enough for you to get turned around when you're in your best state." Offended again, Fortune turns and trots away from her. Annie chuckles and mumbles, "I love you, too," before heading inside. There's a kind of too-quiet in the house that makes the hair on Annie's nape stand, even though she knows it don't mean nothing. The house is always this quiet. It ain't like the badlands themselves, where even in the latest hour there are critters skittering beyond view, trilling and squawking at each other. It ain't like Saddlebrush after dark, neither, where there's still life behind every doorway, even if it's snoring. Nah, there ain't much life left in Annie's home. Place feels like a tomb when the hour creeps late enough. The thought makes her want to cry, but she don't let herself. No time for it, anyway. Down the hall, her fingers tighten around a door handle, steeling herself for what's inside. A deep breath in. Pushing it out slow between her teeth. Tommy is in bed when she walks in his room, awake and staring out the window. He don't bother looking at her when she walks in. That ain't nothing new, though. Her nephew does a whole lot of not looking at her these days. Annie can't say she blames him. Face gaunt, brown skin two shades paler than it oughta be, black hair gone oily and thin at the sides, Tommy ain't nothing like he was when he first moved in with her. When Annie first got him involved in her life and all the trouble that came with it … Now, a layer of sweat coats every inch of him she can see. Even still, he's shivering hard enough to rattle his teeth, knuckles white as he grips the sides of his bed. She wonders if he's trying to hold himself still or stay quiet. Neither's working. While he shakes, a low groan emits from his chest, a rattling behind his ribcage that makes her wanna scream and yank her own hair out. "The pain bad tonight?" she asks, taking off her hat and setting it down on the chair next to his bed. The chair she sleeps in more nights than she does her own room. Tommy winces, as if the sound of her voice makes the pain worse, and nods. Refusing to notice the quiet way he contorts his energy away from her, Annie makes her way to the standing cabinet in the corner. Inside, there's a shelf of bandages, antiseptic, herbal remedies, and—what she's after—a bottle of swirling blue smoke, the strongest pain reliever this side of the Multiverse. They're down to a quarter of the bottle. She sighs and curls her hand around the neck, carrying it over to Tommy's bedside. That's why she'll be headed into town in the morning. A quarter of a bottle should still get them through a week or so, but Annie never risks getting this close to empty without a backup. She'd gone into town that morning for the same reason, but the alchemist was sold out—said the newest shipment would arrive at dawn. So, Annie will, too. "Here." She holds the bottle under his nose and uncorks it, watching as Tommy inhales deep, dragging the blue smoke into his lungs. Once he's gotten a full breath, she pushes the cork back in tight, careful not to let any extra escape. He shudders, maybe in relief, maybe in disgust at her proximity to him, and his eyes slide closed. Annie takes up her post at his bedside. She stays there all night. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) When the sun rises, casting the world beyond her window in a pale blue fog, Annie gives up the ruse of sleeping. Head overfull and throbbing, she gives Tommy one last look over—he's finally deep asleep after fitful bouts of pain all night—before padding down the hall toward her own room. Annie got even less sleep than her nephew did, but she doesn't have the luxury of passing out at dawn. As soon as the thought crosses her mind, she silently curses herself. How callous, to think of his suffering as a #emph[luxury] . She blames the sleep deprivation. The air in her bedroom is hot and stale, and Annie cracks a window to let in the morning. She doesn't know the last time she was in here longer than it took to get dressed. For all the newness of the farmhouse, all the ways it hasn't yet settled into feeling like a home, there's nowhere that's as starkly clear as Annie's room. It may as well belong to a ghost. She glances at the perfectly made bed, undisturbed for days on end, before sliding into her closet to change. After changing, Annie takes care to undo her long braid, comb out her tresses, and rebraid them carefully. Into each section, she weaves a strand of beaded leather, pops of blue and white appearing in her dark hair like flowers blooming from soil. She considers herself in her mirror, head tilting at her own reflection, studying the sun-weathered lines etched at the corners of her mismatched eyes. With a sigh, Annie turns away and heads outside. As soon as she opens the front door, she comes up short. She would've tumbled down the porch steps if she were any less observant. There's a basket waiting on her stoop that sure as sin wasn't there the night before, an unassuming tan wicker crate, like someone'd been on their way to a picnic and gotten turned around at her doorstep. Annie glances around the front field of the property like she might actually spot them, some stranger wandering around in her yard, looking for their basket. Of course, there's no one there. And when Annie lifts the lid of the crate to check its contents, she finds exactly the sort of thing she might've expected for a picnic—a loaf of still-warm bread, a jar of honey, another of fruit preserves, some cured meat. If this #emph[wasn't] abandoned by a lost picnicker, it must've been left as a gift. Maybe Jody stopped by to try and woo her with snacks. (Of all the half-baked proposals she's been on the receiving end of in her time, that idea ain't too shabby.) She shuffles the basket inside, leaving it tucked just in the doorway, and tries to convince herself to feel fine about it all. But she can't shake the tangle of knots her stomach has become. It ain't that Jody showed up and left something for her that's a problem—it's that Annie was up all night and still didn't hear no one creepin' up on the house. That's pure careless right there. And carelessness is one thing Annie can't afford. Not again. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Two fresh bottles of blue smoke acquired, Annie heads out onto Saddlebrush's main square, sights set on the stable where she'd left Fortune. It's been long past an hour since she first rose for the day, but the rest of the plane is just beginning to rise, curtains opening and dogs barking and kids being tossed outside to scuffle before breakfast. A thick layer of dew clings to everything, and the sun's rays catch in droplets like a thousand little prisms casting rainbow-tinted shadows. A smile, meant just for herself, tugs at the corner of Annie's mouth. "Now, I didn't even know you could do that," croons a familiar voice, halting her. She raises one thick, dark eyebrow and turns her head to Jody. He's smirking at her, arms crossed over his chest—no longer bare, but hidden behind a black button-down. "Do what?" "Smile." Annie'd like to wring his neck. "Don't read too much into it. It's a nice day out is all. You ain't the one put the smile on my face, Joey." Undeterred, Jody's smirk only gets wilier. "You were pretty happy last night." "Last night was fine until you started gettin' clingy." Annie shrugs. "And then, the picnic basket? Really? If you think I'm the kinda woman who'd crawl back into your bed for a nice loaf of bread …" The confusion on Jody's face has Annie's words shriveling up. She frowns. He could be feigning ignorance, but what good would that serve him? A courtship ain't gonna work if no one knows who's doing the courting. "You didn't leave food on my doorstep this morning?" "Annie, I enjoyed your company a great deal. But I enjoy my sleep even more." Jody chuckles, something so fond in his expression that it makes her suspicious. "And I most definitely do not bake bread. S'probably just somebody else in town. You've been the subject of a lot of whisper-tree gossiping, you know." Annie's nose crinkles. "I certainly did not." And she don't like it one bit. #emph[What kind of things must they be saying? What story have they twisted about where she comes from and the things she's done?] "People 'round here are worried about y'all, out there all alone. I'd guess somebody decided they needed to offer an olive branch—so to speak." #emph[Oh.] Well … that sure is different than she was expecting. Annie swallows. For the second time that morning, her stomach winds itself up into a tangled nest. But this time, it don't exactly feel like nerves. It's something else. Something she ain't felt in a long time, and don't know how to look straight at. Not that she gets a chance, anyway. Before Annie can respond to Jody's words, the main square breaks into a chorus of screams. Her head snaps back, eyes searching the direction of the chaos, already gripping her blaster and yanking it free of its holster. Townsfolk are running in her direction, parents snatching babies off the street, couples pushing at each other to speed the other up. Behind them, something massive slinks closer. Jody's hand connects with Annie's sternum, nearly knocking the wind out of her as he pulls her into the general store. A crowd floods in with them, threatening to force Annie to the back. With her free hand, she grips Jody's wrist and jerks it away, sorta hoping it hurts when she does. She don't need no one to rescue her, and most surely not him. Pushing past bodies, Annie don't stop throwing elbows until she reaches the front windows, looking out into the now abandoned main square. #emph[Almost ] abandoned. Abandoned by people, anyway. Sliding on its gold-plated belly, skin like thick armor, an enormous rattlewurm slithers through the streets of Saddlebrush. It opens and closes its mouth, flashing giant teeth. Annie's hand tightens around her weapon, muscles tensing for a fight she doesn't want but won't back down from. #figure(image("004_Blood Is Thicker than Venom/01.png", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) No fight comes, though. The monster, unable to find food out in the open, continues on its path, slinking through the square and out on the other side of the buildings, back into the sand dunes it came from. The sand dunes. Annie remembers the shadow from the night before, and her throat clenches. If she'd have listened to her instincts last night, if she'd bothered to investigate further, this wouldn't have happened today. But it's fine, right? It don't sound like anyone got hurt. Jody's pushing through people to get to her, but Annie is the first one to slip back outside. She quickens, an almost imperceptible tremble in her weak left leg as it struggles to keep up with the pace set by her right, impatient to get to the stables. When she does reach them, she heaves a sigh of relief, breath mingling with the scent of manure and hay. Fortune watches her from his stall, expression grim, and snorts out a greeting. "Didn't like that," Annie mumbles, gently palming his face. "Spooked you, too?" Another snort. He shoves his head into her hand, and she runs her fingertip along the ridges of one horn. In many ways, Fortune is her only companion. Something happening to him would be unbearable. But he's fine. Everything is fine. Annie need not carry the burden of guilt for not investigating the rattlewurm sooner. This time, her inaction came without any consequence. As soon as she has the thought, a child screams from outside the barn doors. Nothing needs to be exchanged between Fortune and her—already on the same page, they move in sync, heading out of the stable and back into the square. The crowds have begun to return, townsfolk migrating out into the center of the courtyard. All around her, people check on their neighbors, look for their friends, and exchange embraces as the adrenaline begins to fade. Annie's chest tightens. She ignores it. Near the center of the crowds, one cloister has formed, a gaggle surrounding a little girl—the girl screaming her head off. She can't be more than nine, thin as a whip and pale as moonlight. Her boney body rattles. A boy, maybe a decade older, holds her. They've the same upturned nose and smattering of freckles. To the onlookers, he explains, "I thought I yanked her away quick enough, but it—it got to her." A wave of sympathetic mumbling rolls over the crowd. "Knew this was gonna happen." "Was only a matter of time." "Thing's been getting closer for days." "Poor Mira." "Poor Bo." Annie knows the conversation that ain't hers. Still, she looks to the boy—Bo—and asks, "Why ain't anybody just killed the thing?" Bo's lips part. She watches him struggle to come up with an answer. When nothing comes, someone offers, "How would we do that? It's … it's huge." "Everything dies." Annie runs her thumb along the handle of her blaster. Mira gives another squeal of pain. Annie hardly knows what she's doing before she's doing it, reaching into the pocket of her jacket and pulling out the fresh bottles of blue smoke. She uncorks it, stepping forward to press it beneath Mira's nose. "Take a breath," she instructs. The girl does, shaking all the while. Even as Annie watches her, it ain't just her she's seeing. This never would've happened if she'd listened to her gut and taken care of the problem the night before. Her molars grind together. Fortune knocks his head into her shoulder, but she won't meet his eyes. When she recorks and puts away the bottle, Annie says, "I'll do it." "What?" "I'll kill the thing." Another whisper sweeps across the square, this time more frenzied. Bo holds Mira tighter. "I'll come with you. I want to help. She's my sister—I, I have to help." Others nod, calling out to volunteer. Annie ignores the burning in her throat. Voice gruff, she says, "Fine. We leave from the badlands at dawn sharp tomorrow." Too aware of the grateful stares, Annie grabs Fortune's reins and gets the hell out of there. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Now, that was a plum stupid decision. The longer the day drags on, the more Annie starts to wonder what got inside her head. That rattlewurm is a big problem, but not hers. She can keep her own safe—mostly—and she don't offer up her services lightly. Yet here she is, the night before, packing up a rucksack to take into the dunes the next morning. She tosses in the cured meats from the mystery picnic basket. Truth be told, she knows exactly why she did this. 'Cause she was lookin' at Mira, but she was seeing Tommy. She was staring at that girl, envenomed by the snake, and thinking about her nephew, and the chronic pain he's carrying from her own careless, stupid mistake. It ain't like killing this thing is gonna make things right between her and Tommy. But there's some part of her that sees Akul's face, the vicious Hellspur leader who put Tommy's life on the line because of Annie's misstep. Maybe if she kills this monster, she can kill the part of Akul that's been haunting her since that night. Plum stupid. But too late to back out. Her pacing is interrupted by a low groan from down the hall. Annie doesn't hesitate, dropping what she's doing and moving toward her nephew's room. Her hands are already reaching for the blue smoke bottle in the cupboard before she asks, "Pain flaring up?" But when she offers the bottle to him, he tilts his head away, upper lip curling as if disgusted. "You don't want medicine?" "No," he grits out. Annie frowns, trying to find the unspoken explanation hidden on her nephew's face. "Tired … all the time." His knuckles go bone-white as he struggles to make words happen. One of the effects of the blue smoke is the fatigue that comes with it. It's supposed to be a perk, helping people sleep despite the pain, something Tommy couldn't do without it. It shouldn't take her by surprise that he'd get sick of it and wanna taper off. He's all but lived in this room since they moved to the farmhouse. But it still makes her queasy. "Alright." She don't argue, even if she'd like to. Tommy's grown, and she's already proven she shouldn't make his choices for him. As she puts the bottle away, she says, "I ain't gonna be around tomorrow. Agreed to take care of a rattlewurm that's terrorizing Saddlebrush." Tommy doesn't respond. Annie busies herself with tidying the contents of the cabinet. She don't shake easily, but Tommy manages to do it without trying. "Heading out with some wannabe cowboys at first light. Not sure when I'll be home. Before the day's end, though." He still don't say anything. Finally, Annie forces herself to close the cabinet and turn back. His face is set like stone, expression unreadable. When the silence drags on, Annie sets her shoulders and sees herself out. She can't be sure if it's the pain in his body or the anger in his heart that's got Tommy as twisted up as he is. Either way, it all comes back to her. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Now, what in the world is your old ass doin' here?" are the first words out of Annie's mouth the next day when she steps onto her porch and finds Jody waiting with Bo and the others. The widower grins, unbothered. "Sorry, I musta got confused when I saw you were leading the troops—this ain't an outing for the senior center?" Despite herself, Annie cracks the briefest hint of a smile. "Now, I'll remind you, papaw, only one of us has a blaster on 'em right now." His grin widens. "Alright, alright. I'm just here to see off the departing heroes is all." The term #emph[departing heroes] makes her wanna roll her eyes all the way out of her skull, but she reckons that was his intention. Before she can retort, the door opens behind her. And when Annie turns, anything she might've had to say vanishes. Tommy stands there, a walking stick tucked under his arm. He's pale, breath uneven, but he's up. "You," Tommy growls, pointing a knobby finger at Bo. "Me?" Bo's already pale cheeks lose any hint of color they had. "You come back with my aunt. Or you don't come back. You hear me?" "Um—no, I mean, yes, totally, understood. I won't let anything happen to her—and if I do, I will, um, I will lie down and die." "Good." Tommy lowers his arm. Annie don't know what to do with all that. She coulda predicted the morning going a hundred different ways and never seen that coming. The affection—gruff as it was—has been gone from her relationship with Tommy for a long time. It makes her want to weep to feel it again. #emph[And]  … being doted on in front of a bunch of strangers makes her wanna peel her skin off. "Let's get," she finally barks, turning to gather Fortune and get the show on the road. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It takes less than an hour for Annie to decide Bo is the most endearing and annoying person she's ever met. The boy should #emph[not] be out in the dunes hunting rattlewurms. And he seems to know that, cause he's nervous enough that he can't stop talking. By sunrise, Annie knows the kid's life story. "So, our parents died a few months ago. I mean—our dad died seven years ago, actually, but our mom died earlier this year. Anyway. So, that happened. So, I guess, we're orphans. Or—I don't know, I'm not a kid anymore, I don't think I can be an orphan. And I guess Mira isn't really an orphan either, cause I'm taking care of her. Anyway, it's just us. You know, we're all we've got. Well—okay, us and the people in town, you know. They all helped our mom when we first got here, and then they helped us when she died. I don't know how we would've done it if we were actually #emph[alone] . I mean, nobody can be seriously alone, right? Nobody can survive like that." #emph[Nobody, huh?] Her people have shared Bo's sentiment since time immemorial. In the homeland that gave her life, everybody was family and family was everything. Hearing Bo talk about the way people in Saddlebrush stepped up to take care of him and his sister—that's the way it woulda been back home. Youngins were everyone's responsibility. #emph[Everyone] was everyone's responsibility. That was the life Annie had known for a long time. And then it wasn't. Now, that part of her past feels like a dream she can't grasp the details of but can't shake off neither. She thinks of the basket of food on her counter. The press of Jody's hand on her sternum. To lose something as sacred as one's people is to die a little. She couldn't dare hope to feel anything like that again. The hope might be big enough to swallow her if she did. As the rising sun paints the landscape, Annie pushes aside her thoughts to squint at the horizon. Movement shifts in the distance. If she didn't know what to look for, she might not notice it at all. It #emph[still] could be nothing. Her grip tightens on her blaster, expression grim. She can't risk getting closer without knowing for sure what's over there. "This might look a little strange from the outside," she warns Bo. "Just keep quiet and trust there's things going on you can't see. Understood?" "Uh—uh, yes? Sure." That settled, Annie faces the direction of the indecipherable movement, and taps into her enhanced vision. Her other senses dull. Although nothing happens on the outside, on the inside Annie is hurtled through space. Suddenly, she's a hundred yards away, standing atop a sandy mountain, looking down at shimmering scales. The rattlewurm burrows into the earth, disappearing almost entirely before popping free on the other side of a small dune. Nearby, there's an opening in the sand, the entrance to the creature's lair. "Got you," she whispers, and her blaster grows warm in her hand, tethering her to her body. Seconds from pulling back, Annie hesitates at a flash of bronze in her periphery. She watches, heart climbing into her mouth, as another rattlewurm emerges. This one is considerably smaller. It gives a cautious wiggle of its head, peeking out at its … parent. The bigger rattlewurm shimmies, beckoning until the baby joins her. The two of them slide through the sand together, scales rubbing the warming earth. Her heart, trapped at the back of her mouth, begins to pound harder. No one is meant to survive alone. And anyone backed into a corner will do what they've gotta do to beat the odds and make it out alive. The rattlewurm isn't Akul. Annie can't get revenge for Tommy's pain by slaughtering the creature who hurt Mira. Back in her body, Annie realizes what she needs to do. "You find it?" Bo asks. "I did. Just up ahead." She snaps her blaster back into its holster. "Now, this is what we're gonna do …" Annie might've expected anger from the people of Saddlebrush, for her deciding to let the rattlewurm and its baby live, for corralling them deeper into the dunes where prey was more plentiful and people scarcer instead of exterminating them the way she'd promised. Not for the first time, the townsfolk take her by surprise by eagerly embracing a solution that doesn't involve bloodshed. It's nightfall when Annie returns home, sore from a day well spent. She smiles when she says goodbye to the others, watching them ride off together. Fortune nudges her, nickering like laughter. She kisses the side of his face, then sends him into the barn. Inside, she's still smiling when she hangs up her jacket. "Success?" Tommy's voice comes from around the corner, and Annie turns toward it. He looks even better. He's standing in the hallway, hand curled around the top of his cane. Freshly showered? "In its own way. There's some good people in this town, Tommy. I think we really might be able to build ourselves a life here. I …" He winces. Pain, but what kind? Her eyes search him over again. This time, she notes the bag at his feet. "You goin' somewhere?" "Was just waiting so I could say goodbye." "I—" She narrows her eyes at him, clasping her hands in front of herself. "No. Where are you going?" "Home, auntie." "This is your—" "#emph[Home] ." He emphasizes, eyes burning with a fire Tommy ain't had since he started on the blue smoke. "Back to our people." A masochistic silence hangs between them, begging to be shattered. Tommy acquiesces. "I'm glad you're settling in here. But this #emph[ain't] home. I dunno how to be part of this life you're talking about. And I need …" He looks at the floor. "I need #emph[real] medicine." Annie would have to be cruel beyond measure to fault him. It doesn't stop the way her chest threatens to come open at the seams. "I understand." She nods. "But you can't go off in the dark on your own, at least stay until—" "I've made arrangements. Jody, actually, helped me figure out a plan. He's a nice guy." A nice guy whose neck Annie's gonna snap the next time she sees him. "Okay." She swallows. "Well … thank you for waiting. It was kind of you, considering." "Considering?" Tommy frowns. "How much you must hate me." "Haseya …" Her breath catches in her throat as Tommy uses her #emph[real] name, her Atiin name, the name her people gave to her. He steps forward and pulls her into an embrace. Annie would weep if she could breathe at all. He whispers, "I couldn't hate you. I love you. This just … isn't where I'm supposed to be." Is it where #emph[she's] supposed to be? She don't know. She hopes, if she lets herself forgive her mistakes, if she leans in and builds something here, maybe it can be. And maybe she's wrong again. "I better head out." Tommy brushes his thumb against her face before picking up his bag. There's still a tremor in every moment, a clear thread of pain, but he's better than she's seen him in a long time. He knows what he's doing. "This isn't goodbye forever." He darkens the farmhouse doorway. "We'll see each other again." "Blood can run, but it ends up right where it started," she agrees. "Till then." As Tommy's shadow grows longer and longer down the path leading away from their home before finally disappearing, Annie becomes aware of a quiet truth. It settles like lead into her gut, suffocating the tangled knots of hope and fear, washing them all clean. There's a good chance she #emph[can] build the community she's been missing. These people can be her people; this life can be her life. But when she comes home at night, it's always gonna be Annie Flash and her ghosts.
https://github.com/alikindsys/aula
https://raw.githubusercontent.com/alikindsys/aula/master/Core/base.typ
typst
#import "packages.typ": chic-hdr, gentle-clues, gloss-awe, oxifmt, tablem, tablex #import chic-hdr: * #import gentle-clues: * #import tablem: tablem #import tablex: tablex, hlinex #import gloss-awe: * #let aula( materia: [], glossary: (), doc ) = { set heading(numbering: "1.") show ref: it => { set text(blue) let fields = it.fields() let keys = fields.keys() link(it.target, [#underline([#it.supplement])]) } set page( paper: "a4", // ABNT margin: (bottom: 2.0cm, right: 2.0cm ,left: 3.0cm, top: 3.0cm), columns: 2 ) set text( font: "Bree Serif", lang: "por", region: "br", size: 12pt ) set par( justify: false, linebreaks: "optimized" ) // set quote(block: true) show figure.where(kind: "jkrb_glossary"): it => [#link(<glossar>)[#it.body]] show: chic.with( chic-header( left-side: emph(chic-heading-name(fill:true)), right-side: smallcaps(materia) ), chic-footer( left-side: strong("Grupo de Estudos do Bloco Vermelho"), right-side: chic-page-number() ), chic-separator(1pt) ) doc [ = Glossário <glossar> Essa secção contém o glossário automáticamente gerado. ] make-glossary(glossary) } #let color-table(rgb, rest) = { let original = color.oklab(rgb).components() let darker = color.oklab(80%, original.at(1), original.at(2),100%) let lighter = color.oklab(90%,original.at(1), original.at(2),100%) let func = tablem.with( render: (columns: auto, ..args) => { tablex( columns: columns, auto-lines: false, align: center + horizon, map-rows: (row, cells) => cells.map(c => if row != 0 { (..c, fill: if calc.odd(row) { darker } else { lighter } ) } else { (..c, fill: color.luma(80%)) } ), ..args ) } ) func(rest) } #let pt_abstract(title: auto, ..args) = abstract( title: if (title != auto) { title } else {"Resumo"}, ..args ) #let pt_info(title: auto, ..args) = info( title: if (title != auto) { title } else {"Informação"}, ..args ) #let pt_question(title: auto, ..args) = question( title: if (title != auto) { title } else {"Pergunta"}, ..args ) #let pt_memo(title: auto, ..args) = memo( title: if (title != auto) { title } else {"Memorizar"}, ..args ) #let pt_task(title: auto, ..args) = task( title: if (title != auto) { title } else {"Tarefa"}, ..args ) #let pt_step(title: auto, ..args) = task( title: if (title != auto) { title } else {"Passo-a-passo"}, ..args ) #let pt_conclusion(title: auto, ..args) = conclusion( title: if (title != auto) { title } else {"Conclusão"}, ..args ) #let pt_tip(title: auto, ..args) = tip( title: if (title != auto) { title } else {"Dica"}, ..args ) #let pt_success(title: auto, ..args) = success( title: if (title != auto) { title } else {"Sucesso"}, ..args ) #let pt_warning(title: auto, ..args) = warning( title: if (title != auto) { title } else {"Advertência"}, ..args ) #let pt_error(title: auto, ..args) = error( title: if (title != auto) { title } else {"Erro"}, ..args ) #let pt_example(title: auto, ..args) = example( title: if (title != auto) { title } else {"Exemplo"}, ..args ) #let pt_quote(title: auto, ..args) = example( title: if (title != auto) { title } else {"Citação"}, ..args ) #let attn(it) = { text(red, it) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/all-in-one-node.typ
typst
Apache License 2.0
#import "/docs/cookery/book.typ": * #show: book-page.with(title: "All-in-one Library for Node.js") #include "claim.typ" The compiler and renderer are integrated into a same node library for simpler and cleaner APIs, since there is no urgent need to tree-shake the components in node.js applications. == Creating a Compiler Creates a new compiler with default arguments: ```ts const compiler = NodeCompiler.create(); ``` Creates a new compiler with custom arguments: ```ts const compiler = NodeCompiler.create({ workspace: '/path/to/workspace', }); ``` == Caution: Cleaning Global Cache Please evict the global compilation cache periodically to avoid memory leak: ```ts // A suggested `max_age` value for regular non-watch tools is `10`. // A suggested `max_age` value for regular watch tools is `30`. NodeCompiler.evictCache(10); ``` If you have some ideas about how to improve the cache eviction strategy, please let us know. == Compiling out a document instance by compile arguments With an intermediate document content: ```ts const docs = await compiler.compile({ mainFileContent: 'Hello, typst!', }); ``` With a file path: ```ts const docs = await compiler.compile({ mainFilePath: '/path/to/main-file.typ', }); ``` With extra `sys.inputs`: ```ts const docs = await compiler.compile({ mainFileContent: '#sys.inputs', inputs: { 'theme': 'dark', }, }); ``` == Compilation Get output in various format: ```ts // As a raw document object: compiler.compile({ mainFileContent }); // As a precompiled vector-format document. compiler.vector({ mainFileContent }); // As PDF. compiler.pdf({ mainFileContent }); // As SVG that suitable for SVG viewers. compiler.plainSvg({ mainFileContent }); // As SVG that only fits for web browsers but contains more features, like text selection. compiler.svg({ mainFileContent }); ``` == Querying Query the document instance by some selector, such as a typst label: ```ts compiler.query({ mainFileContent }, { selector: '<some-label>' }); ``` == Adding/Removing in-memory shadow files Add extra *binary input files*: ```ts compiler.mapShadow('/assets/tiger.png', /* Node's Buffer Type */ pngData); ``` Add some extra *input file*: ```ts await $typst.addSource('/template.typ', templateContent); ``` Relationship between `addSource` and `mapShadow`. The `addSource` function will `mapShadow` the content of the file by encoding it internally: ```ts // add a json file (utf8) compiler.mapShadow('/template.typ', (new TextEncoder()).encode(templateContent)); // same as above ``` Remove a shadow source or binary file: ```ts compiler.unmapShadow('/assets/data.json'); ``` Clean up all shadow files for underlying access model: ```ts compiler.resetShadow(); ``` Note: this function will also clean all files added by `addSource`. == Settings: Configuring fonts. Order of `fontArgs` is important. The precedence is: - The former elements of `fontArgs` have higher precedence. - The latter elements of `fontArgs` have lower precedence. - System fonts. - Default embedded fonts. Load fonts from some directory: ```ts const compiler = NodeCompiler.create({ fontArgs: [ { fontPaths: ['assets/fonts'] }, ] }); ``` Load fonts by some blob: ```ts const compiler = NodeCompiler.create({ fontArgs: [ // Node Buffer { fontBlobs: [someFontBlob] }, ] }); ```
https://github.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides
https://raw.githubusercontent.com/gabrielrovesti/UniPD-Swiss-Knife-Notes-Slides/main/Notes/Typst/unipd-doc.typ
typst
MIT License
#let notes() = doc => { set text(font: "Arial") doc } #let unipd-doc(title: none, subtitle: none, author: none, date: none) = doc => { let unipd-red = rgb(180, 27, 33) set page(numbering: "1") set list(marker: ([•], [◦], [--])) set heading(numbering: "1.1.") show heading.where(level: 1): it => { set text(fill: unipd-red) it } align(center, { v(10em) figure(image("images/unipd-logo.png", width: 40%)) v(3em) text(size: 25pt, weight: "bold", fill: unipd-red, smallcaps(title)) v(5pt) text(size: 18pt, weight: "bold", fill: unipd-red, subtitle) parbreak() set text(size: 18pt) author parbreak() date pagebreak() }) // For normal TOC appearance // show outline.entry: it => { // set text(weight: "regular") // it // } show outline.entry.where(level: 1): it => { v(1em, weak: true) strong(it) } outline( title: "Table of contents", indent: 2em, ) pagebreak() outline(title: "Figures", target: figure.where(kind: image)) outline(title: "List of Tables", target: figure.where(kind: table)) pagebreak() doc }
https://github.com/tomeichlersmith/zen-zine
https://raw.githubusercontent.com/tomeichlersmith/zen-zine/main/template/main.typ
typst
MIT License
#import "@preview/zen-zine:0.1.0": zine #set document(author: "Tom", title: "Zen Zine Example") #set text(font: "Linux Libertine", lang: "en") #let my_eight_pages = ( range(8).map( number => [ #pad(2em, text(10em, align(center, str(number)))) ] ) ) // provide your content pages in order and they // are placed into the zine template positions. // the content is wrapped before movement so that // padding and alignment are respected. #zine( // draw_border: true, // zine_page_margin: 8pt, // digital: false contents: my_eight_pages )
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2008/MS-09.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [<NAME>], [CHN], [3283], [2], [WANG Hao], [CHN], [3123], [3], [MA Long], [CHN], [3095], [4], [WANG Liqin], [CHN], [3027], [5], [CHEN Qi], [CHN], [2819], [6], [<NAME>], [GER], [2809], [7], [SAMSONOV Vladimir], [BLR], [2788], [8], [OH Sangeun], [KOR], [2781], [9], [<NAME>], [KOR], [2743], [10], [<NAME>], [SWE], [2711], [11], [HAO Shuai], [CHN], [2693], [12], [ZHANG Jike], [CHN], [2683], [13], [LI Ching], [HKG], [2653], [14], [<NAME>], [AUT], [2647], [15], [KAN Yo], [JPN], [2642], [16], [<NAME>], [ROU], [2633], [17], [KO Lai Chak], [HKG], [2630], [18], [LEE Jungwoo], [KOR], [2613], [19], [HOU Yingchao], [CHN], [2610], [20], [OVTCHAROV Dimitrij], [GER], [2605], [21], [<NAME>], [KOR], [2579], [22], [YOON Jaeyoung], [KOR], [2577], [23], [SCHLAGER Werner], [AUT], [2564], [24], [JIANG Tianyi], [HKG], [2559], [25], [YOSHIDA Kaii], [JPN], [2531], [26], [KIM Hyok Bong], [PRK], [2531], [27], [QIU Yike], [CHN], [2528], [28], [MAZE Michael], [DEN], [2526], [29], [GAO Ning], [SGP], [2523], [30], [XU Xin], [CHN], [2518], [31], [LI Ping], [QAT], [2513], [32], [TANG Peng], [HKG], [2512], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [CHEN Weixing], [AUT], [2510], [34], [GERELL Par], [SWE], [2506], [35], [KREANGA Kalinikos], [GRE], [2504], [36], [LEE Jungsam], [KOR], [2486], [37], [MONTEIRO Thiago], [BRA], [2466], [38], [TAN Ruiwu], [CRO], [2466], [39], [CHEUNG Yuk], [HKG], [2463], [40], [MIZUTANI Jun], [JPN], [2454], [41], [BLASZCZYK Lucjan], [POL], [2451], [42], [HAN Jimin], [KOR], [2449], [43], [KIM Junghoon], [KOR], [2436], [44], [CHIANG Hung-Chieh], [TPE], [2434], [45], [<NAME>], [CRO], [2432], [46], [TUGWELL Finn], [DEN], [2431], [47], [<NAME>], [SLO], [2425], [48], [KONG Linghui], [CHN], [2423], [49], [CHUANG Chih-Yuan], [TPE], [2422], [50], [<NAME>], [GER], [2421], [51], [GIONIS Panagiotis], [GRE], [2419], [52], [#text(gray, "ROSSKOPF Jorg")], [GER], [2417], [53], [<NAME>], [CRO], [2405], [54], [WALDNER Jan-Ove], [SWE], [2403], [55], [<NAME>], [KOR], [2402], [56], [TAKAKIWA Taku], [JPN], [2401], [57], [RUBTSOV Igor], [RUS], [2385], [58], [JANG Song Man], [PRK], [2382], [59], [LIN Ju], [DOM], [2379], [60], [#text(gray, "XU Hui")], [CHN], [2376], [61], [LEUNG Chu Yan], [HKG], [2375], [62], [WU Chih-Chi], [TPE], [2374], [63], [WANG Zengyi], [POL], [2373], [64], [FEGERL Stefan], [AUT], [2358], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [<NAME>], [FRA], [2354], [66], [<NAME>], [IND], [2346], [67], [<NAME>], [TPE], [2342], [68], [<NAME>], [ITA], [2341], [69], [<NAME>], [POL], [2335], [70], [<NAME>], [POL], [2335], [71], [<NAME>], [CZE], [2334], [72], [#text(gray, "<NAME>")], [NED], [2328], [73], [<NAME>], [SGP], [2326], [74], [<NAME>], [ESP], [2325], [75], [<NAME>], [SVK], [2316], [76], [LIVENTSOV Alexey], [RUS], [2315], [77], [KARAKASEVIC Aleksandar], [SRB], [2309], [78], [SHMYREV Maxim], [RUS], [2308], [79], [<NAME>], [ITA], [2307], [80], [<NAME>], [ROU], [2307], [81], [#text(gray, "<NAME>")], [SWE], [2303], [82], [<NAME>], [KOR], [2299], [83], [KISHIKAWA Seiya], [JPN], [2296], [84], [ZH<NAME>], [CHN], [2292], [85], [<NAME>], [KOR], [2285], [86], [<NAME>], [GER], [2279], [87], [<NAME>], [CZE], [2278], [88], [<NAME>], [PRK], [2276], [89], [SMIRNOV Alexey], [RUS], [2275], [90], [<NAME>], [POR], [2275], [91], [<NAME>], [JPN], [2271], [92], [<NAME>], [JPN], [2251], [93], [<NAME>], [ROU], [2250], [94], [<NAME>], [CHN], [2248], [95], [<NAME>], [BEL], [2247], [96], [<NAME>], [SGP], [2239], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [<NAME>], [DEN], [2237], [98], [MATSUDAIRA Kenta], [JPN], [2233], [99], [<NAME>], [UKR], [2227], [100], [<NAME>], [RUS], [2227], [101], [<NAME>], [NGR], [2226], [102], [<NAME>], [AUT], [2226], [103], [<NAME>], [TPE], [2225], [104], [<NAME>], [TPE], [2225], [105], [PERSSON Jon], [SWE], [2224], [106], [<NAME>], [BLR], [2222], [107], [ERLANDSEN Geir], [NOR], [2221], [108], [<NAME>], [POR], [2220], [109], [#text(gray, "<NAME>")], [JPN], [2213], [110], [<NAME>], [LAT], [2212], [111], [<NAME>], [HUN], [2209], [112], [<NAME>], [ESP], [2199], [113], [<NAME>], [SVK], [2198], [114], [<NAME>], [SVK], [2197], [115], [<NAME>], [SGP], [2194], [116], [<NAME>], [RUS], [2191], [117], [<NAME>], [SRB], [2191], [118], [<NAME>], [SWE], [2190], [119], [MEROTOHUN Monday], [NGR], [2190], [120], [<NAME>], [CZE], [2189], [121], [<NAME>], [HUN], [2186], [122], [<NAME>], [EGY], [2181], [123], [LEGOUT Christophe], [FRA], [2177], [124], [MONTEIRO Joao], [POR], [2174], [125], [MONRAD Martin], [DEN], [2174], [126], [<NAME>], [CZE], [2170], [127], [NEKHVEDOVICH Vitaly], [BLR], [2170], [128], [#text(gray, "<NAME>")], [BEL], [2166], ) )
https://github.com/SillyFreak/typst-stack-pointer
https://raw.githubusercontent.com/SillyFreak/typst-stack-pointer/main/README.md
markdown
MIT License
# Stack Pointer Stack Pointer is a library for visualizing the execution of (imperative) computer programs, particularly in terms of effects on the call stack: stack frames and local variables therein. Stack Pointer lets you represent an example program (e.g. a C or Java program) using typst code with minimal hassle, and get the execution state of that program at different points in time. ## Getting Started To add this package to your project, use this: ```typ #import "@preview/stack-pointer:0.1.0": * #execute(...) ``` For example, the following C program ```c int main() { int x = foo(); return 0; } int foo() { return 0; } ``` would be represented by the following Typst code: ```typ #let steps = execute({ let foo() = func("foo", 6, l => { l(0) l(1); retval(0) }) let main() = func("main", 1, l => { l(0) l(1) let (x, ..rest) = foo(); rest l(1, push("x", x)) l(2) }) main(); l(none) }) ``` The `steps` variable now contains an array, where each element corresponds to one of the mentioned lines of code. ## Usage See the [manual](docs/manual.pdf) for details. Take a look at [this complete example](gallery/sum.pdf) of using Stack Pointer together with [Polylux](https://polylux.dev/book/).
https://github.com/Zuttergutao/Typstdocs-Zh-CN-
https://raw.githubusercontent.com/Zuttergutao/Typstdocs-Zh-CN-/main/Classified/Abstract.typ
typst
// 前言 #[ #set page(header:none,numbering:none) #set align(center) #text(weight:700,size:28pt)[前言] #set align(left) 此文档是我在#link("https://typst.app/")[学习Typst时],翻译官方manual时的一些记录。目前,全文已经翻译完了,但是请时刻关注翻译的版本与官网的版本。因为有一定的翻译滞后性以及官网更新的频繁,所以可能出现有些功能不能使用。之后的工作就是好好优化一下页面的排版。#parbreak() 粗略地制作了文档的封面,该封面是仿照《一份(不太)简短的LaTeX 2e介绍》制作的,在此感谢。#parbreak() 目前来说Typst很对我的胃口,但是还是存在着很多的问题,但我相信随着更新与发展,typst一定会越来越好用。#parbreak() 欢迎加入#link("https://typst.cn/#/")[typst中文社区:https://typst.cn]! #set align(right) Casea #parbreak() 2023.04.22 ] #pagebreak()
https://github.com/duskmoon314/THU_AMA
https://raw.githubusercontent.com/duskmoon314/THU_AMA/main/README.md
markdown
Creative Commons Attribution 4.0 International
# THU_AMA: 应用近世代数笔记 本仓库是我于清华大学应用近世代数课上记录的笔记的简单整理,以 CC-BY 4.0 协议开放。 ## 背景 我于 2023 年春季学期在「应用近世代数」课上使用 LaTeX 记录了约 2500 行的笔记,主要包括课上所讲的定理、证明、例题等内容。 2024 年春季,应同学邀请,我将笔记转换为 [Typst](https://typst.app) 格式并基于 [`typst-book`](https://github.com/Myriad-Dreamin/typst-book) 生成 web 页面以供阅读。 笔记内容依赖 Typst 的 web app 进行转换,可能存在大量的细节问题,欢迎提出 issue。 ## 阅读 [Github Pages](https://duskmoon314.github.io/THU_AMA/) ## 本地构建 本项目依赖 `typst` 和 `typst-book`,请先安装这两个工具。 ```bash typst-book build ``` 也可以使用 typst 构建 PDF 版本: ```bash typst c ebook.typ ```
https://github.com/JeyRunner/tuda-typst-templates
https://raw.githubusercontent.com/JeyRunner/tuda-typst-templates/main/templates/tudapub/tudapub.typ
typst
MIT License
#import "tudacolors.typ": tuda_colors #import "common/outline.typ": * #import "common/props.typ": * #import "common/tudapub_title_page.typ": * #import "common/thesis_statement_pursuant.typ": * #import "util.typ": * #import "@preview/i-figured:0.2.3" // This function gets your whole document as its `body` and formats it. #let tudapub( title: [Title], title_german: [Title German], // Adds an abstract page after the title page with the corresponding content. // E.g. abstract: [My abstract text...] abstract: none, // "master" or "bachelor" thesis thesis_type: "master", // The code of the accentcolor. // A list of all available accentcolors is in the list tuda_colors accentcolor: "9c", // Size of the main text font fontsize: 10.909pt, //11pt, // Currently just a4 is supported paper: "a4", // Author name as text, e.g "<NAME>" author: "<NAME>", // Date of submission as string date_of_submission: datetime( year: 2023, month: 10, day: 4, ), location: "Darmstadt", // array of the names of the reviewers reviewer_names: ("SuperSupervisor 1", "SuperSupervisor 2"), // language for correct hyphenation language: "eng", // Set the margins of the content pages. // The title page is not affected by this. // Some example margins are defined in 'common/props.typ': // - tud_page_margin_small // same as title page margin // - tud_page_margin_big // E.g. margin: ( // top: 30mm, // left: 31.5mm, // right: 31.5mm, // bottom: 56mm // ), margin: tud_page_margin_big, // tuda logo - has to be a svg. E.g. image("PATH/TO/LOGO") logo_tuda: none, // e.g. image("logos/tuda_logo.svg") // optional sub-logo of an institute. // E.g. image("logos/iasLogo.jpeg") logo_institute: none, // How to set the size of the optional sub-logo // either "width": use tud_logo_width*(2/3) // or "height": use tud_logo_height*(2/3) logo_institute_sizeing_type: "width", // Move the optional sub-logo horizontally logo_institute_offset_right: 0mm, // An additional white box with content e.g. the institute, ... below the tud logo. // Disable it by setting its value to none. // E.g. logo_sub_content_text: [ Institute A \ filed of study: \ B] logo_sub_content_text: [ field of study: \ Some Field of Study \ \ Institute A ], // The bibliography created with the bibliography(...) function. // When this is not none a references section will appear at the end of the document. // E.g. bib: bibliography("my_references.bib") bib: none, // Add an English translation to the "Erklärung zur Abschlussarbeit". thesis_statement_pursuant_include_english_translation: false, // Which pages to insert // Pages can be disabled individually. show_pages: ( title_page: true, outline_table_of_contents: true, // "Erklärung zur Abschlussarbeit" thesis_statement_pursuant: true ), // Insert additional pages directly after the title page. // E.g. additional_pages_after_title_page: [ // = Notes // #pagebreak() // = Another Page // ] additional_pages_after_title_page: none, // Insert additional pages directly after the title page. // E.g. additional_pages_after_title_page: [ // = Notes // #pagebreak() // = Another Page // ] additional_pages_before_outline_table_of_contents: none, // Insert additional pages directly after the title page. // E.g. additional_pages_after_title_page: [ // = Notes // #pagebreak() // = Another Page // ] additional_pages_after_outline_table_of_contents: none, // For headings with a height level than this number no number will be shown. // The heading with the lowest level has level 1. // Note that the numbers of the first two levels will always be shown. heading_numbering_max_level: 3, // In the outline the max heading level will be shown. // The heading with the lowest level has level 1. outline_table_of_contents_max_level: 3, // Set space above the heading to zero if it's the first element on a page. // This is currently implemented as a hack (check the y pos of the heading). // Thus when you experience compilation problems (slow, no convergence) set this to false. reduce_heading_space_when_first_on_page: true, // How the table of contents outline is displayed. // Either "adapted": use the default typst outline and adapt the style // or "rewritten": use own custom outline implementation which better reproduces the look of the original latex template. // Note that this may be less stable than "adapted", thus when you notice visual problems with the outline switch to "adapted". outline_table_of_contents_style: "rewritten", // Use own rewritten footnote display implementation. // This may be less stable than the built-in footnote display impl. // Thus when having problems with the rendering of footnote disable this option. footnote_rewritten_fix_alignment: true, // When footnote_rewritten_fix_alignment is true, add a hanging intent to multiline footnotes. footnote_rewritten_fix_alignment_hanging_indent: true, // Use 'Roboto Slab' instead of 'Robot' font for figure captions. figure_caption_font_roboto_slab: true, // Figures have the numbering <chapter-nr>.<figure-nr> figure_numbering_per_chapter: true, // Equations have the numbering <chapter-nr>.<equation-nr> // @todo This seems to increase the equation number in steps of 2 instead of one equation_numbering_per_chapter: false, // content. body ) = style(styles => { // checks //assert(tuda_colors.keys().contains(accentcolor), "accentcolor unknown") //assert.eq(paper, "a4", "currently just a4 is supported as paper size") //[#paper] // vars let accentcolor_rgb = tuda_colors.at(accentcolor) let heading_2_line_spacing = 5.2pt let heading_2_margin_before = 12pt let heading_3_margin_before = 12pt // Set document metadata. set document( title: title, author: author ) // Set the default body font. set par( justify: true, //leading: 4.7pt//0.42em//4.7pt // line spacing leading: 4.8pt//0.42em//4.7pt // line spacing ) show par: set block(below: 1.1em) // was 1.2em set text( font: "XCharter", size: fontsize, fallback: false, lang: language, kerning: true, ligatures: false, //spacing: 92% // to make it look like the latex template //spacing: 84% // to make it look like the latex template spacing: 91% // to make it look like the latex template ) if paper != "a4" { panic("currently just a4 as paper is supported") } /////////////////////////////////////// // page setup // with header and footer let header = box(//fill: white, grid( rows: auto, rect( fill: color.rgb(accentcolor_rgb), width: 100%, height: 4mm //- 0.05mm ), v(1.4mm + 0.25mm), // should be 1.4mm according to guidelines line(length: 100%, stroke: 1.2pt) //+ 0.1pt) // should be 1.2pt according to guidelines )) let footer = grid( rows: auto, v(0mm), line(length: 100%, stroke: 0.6pt), // should be 1.6pt according to guidelines v(2.5mm), text( font: "Roboto", stretch: 100%, fallback: false, weight: "regular", size: 10pt )[ #set align(right) // context needed for page counter for typst >= 0.11.0 #context [ #let counter_disp = counter(page).display() //#hide(counter_disp) //#counter_disp #locate(loc => { let after_table_of_contents = query(selector(<__after_table_of_contents>).before(loc), loc).len() >= 1 if after_table_of_contents {counter_disp} else {hide(counter_disp)} }) ] ] ) let header_height = measure(header, styles).height let footer_height = measure(footer, styles).height // inner page margins (from header to text and text to footer) let inner_page_margin_top = 22pt //0pt//20pt //3mm let inner_page_margin_bottom = 30pt // title page has different margins let margin_title_page = tud_page_margin_title_page //////////////////////////// // content page setup let content_page_margin_full_top = margin.top + inner_page_margin_top + 1*header_height /////////////////////////////////////// // headings set heading(numbering: "1.1") // default heading (handle cases with level >= 3 < 5) show heading: it => locate(loc => { if it.level > 5 { panic("Just heading with a level < 4 are supported.") } let heading_font_size = { if it.level <= 3 {11.9pt} else {10.9pt} } // change heading margin depending on its the first on the page let (heading_margin_before, is_first_on_page) = get-spacing-zero-if-first-on-page( heading_3_margin_before, loc, content_page_margin_full_top, enable: reduce_heading_space_when_first_on_page ) set text( font: "Roboto", fallback: false, weight: "bold", size: heading_font_size ) block(breakable: false, inset: 0pt, outset: 0pt)[ #stack( v(heading_margin_before), block[ #if it.level <= heading_numbering_max_level and it.outlined and it.numbering != none { counter(heading).display(it.numbering) h(0.3em) } #it.body ], v(10pt) ) ] }) // heading level 5 show heading.where(level: 5): it => { par()[] set text( font: "Roboto", fallback: false, weight: "bold", size: fontsize ) it.body + [: ] h(1mm) } // heading level 1 show heading.where( level: 1 ): it => { // heading font style set text( font: "Roboto", fallback: false, weight: "bold", size: 20.6pt, //height: ) [#pagebreak(weak: true)] block(breakable: false, inset: 0pt, outset: 0pt, fill: none)[ #stack( v(20mm), block[ //\ \ //#v(50pt) #if it.outlined and it.numbering != none { counter(heading).display(it.numbering) h(4pt) } #it.body ], v(13pt), line(length: 100%, stroke: tud_heading_line_thin_stroke), v(32pt) ) ] // rest figure/equation numbers for each chapter // -> manual reimplementation of the i-figured.reset-counters(...) function // -> fixes: heading page is wrong due to pagebreak if figure_numbering_per_chapter { for kind in (image, table, raw) { counter(figure.where(kind: i-figured._prefix + repr(kind))).update(0) } } if equation_numbering_per_chapter { counter(math.equation).update(0) } } // rest figure numbers for each chapter // -> not working together with pagebreak of heading level 1 // -> heading page is wrong //show heading: it => if figure_numbering_per_chapter { // i-figured.reset-counters.with()(it) // } else {it} // heading level 2 show heading.where( level: 2 ): it => locate(loc => { // change heading margin depending if its the first on the page let (heading_margin_before, is_first_on_page) = get-spacing-zero-if-first-on-page( heading_2_margin_before, loc, content_page_margin_full_top, enable: reduce_heading_space_when_first_on_page ) set text( font: "Roboto", fallback: false, weight: "bold", size: 14.3pt ) //set block(below: 0.5em, above: 2em) block( breakable: false, inset: 0pt, outset: 0pt, fill: none, //above: heading_margin_before, //below: 0.6em //+ 10pt )[ #stack( v(heading_margin_before), line(length: 100%, stroke: tud_heading_line_thin_stroke), v(heading_2_line_spacing), block[ #if it.outlined and it.numbering != none { counter(heading).display(it.numbering) h(2pt) } #it.body //[is_first_on_page: #is_first_on_page] //#loc.position() #content_page_margin_full_top ], v(heading_2_line_spacing), line(length: 100%, stroke: tud_heading_line_thin_stroke), v(10pt) ) ] }) /////////////////////////////////////// // Configure equation numbering and spacing. set math.equation(numbering: "(1.1.1)") show math.equation: set block(spacing: 0.65em) // equation numbering per chapter show math.equation.where(block: true): it => { if equation_numbering_per_chapter { // @todo this seems to increase the equation number in steps of 2 instead of one i-figured.show-equation(only-labeled: false, it) } else {it} } // Configure figures. let figure_caption_font = "Roboto" if figure_caption_font_roboto_slab { figure_caption_font = ("Roboto Slab", "Roboto") } show figure.caption: set text( font: figure_caption_font, ligatures: false, stretch: 100%, fallback: false, weight: "regular" ) // figure numbering per Chapter show figure: it => { if figure_numbering_per_chapter { i-figured.show-figure(it) } else {it} } // configure footnotes set footnote.entry( separator: line(length: 40%, stroke: 0.5pt) ) show footnote.entry: it => { if footnote_rewritten_fix_alignment { let loc = it.note.location() let it_counter_arr = counter(footnote).at(loc) let idx_str = numbering(it.note.numbering, ..it_counter_arr) //[#it.fields()] stack(dir: ltr, h(5pt), super(idx_str), { // optional add indent to multi-line footnote if footnote_rewritten_fix_alignment_hanging_indent { par(hanging-indent: 5pt)[#it.note.body] } else { it.note.body } } ) } else { // if not footnote_rewritten_fix_alignment keep as is it } } /////////////////////////////////////// // Display font checks check-font-exists("Roboto") check-font-exists("XCharter") /////////////////////////////////////// // Display the title page set page( paper: paper, numbering: "1", margin: ( left: margin_title_page.left, //15mm, right: margin_title_page.right, //15mm, // top: inner + margin.top + header_height top: margin_title_page.top + inner_page_margin_top + header_height, // 15mm bottom: margin_title_page.bottom //+ 0*inner_page_margin_bottom + footer_height //20mm ), // header header: header, // don't move header up -> so that upper side is at 15mm from top header-ascent: inner_page_margin_top,//0%, // footer footer: none,//footer, footer-descent: 0mm //inner_page_margin_bottom ) // make image paths relative to this dir of this .typ file let make-path-rel-parent(path) = { if not path == none and not path.starts-with("/") and not path.starts-with("./") and path.starts-with("") { return "../" + path } else {return path} } if show_pages.title_page { tudpub-make-title-page( title: title, title_german: title_german, thesis_type: thesis_type, accentcolor: accentcolor, language: language, author: author, date_of_submission: date_of_submission, location: location, reviewer_names: reviewer_names, logo_tuda: logo_tuda, logo_institute: logo_institute, logo_institute_sizeing_type: logo_institute_sizeing_type, logo_institute_offset_right: logo_institute_offset_right, logo_sub_content_text: logo_sub_content_text ) } /////////////////////////////////////// // Content pages // body has different margins than title page // @todo some bug seems to insert an empty page at the end when content (title page) appears before this second 'set page' set page( margin: ( left: margin.left, //15mm, right: margin.right, //15mm, top: margin.top + inner_page_margin_top + 1*header_height, // 15mm bottom: margin.bottom + inner_page_margin_bottom + footer_height //20mm ), // header header: header, // don't move header up -> so that upper side is at 15mm from top header-ascent: inner_page_margin_top,//0%, // footer footer: footer, footer-descent: inner_page_margin_bottom //footer_height // @todo ) // disable heading outlined for outline set heading(outlined: false) // additional_pages_after_title_page pagebreak(weak: true) additional_pages_after_title_page /////////////////////////////////////// // "Erklärung zur Abschlussarbeit" and abstract if show_pages.thesis_statement_pursuant { tudapub-get-thesis-statement-pursuant( date: date_of_submission, author: author, location: location, include-english-translation: thesis_statement_pursuant_include_english_translation ) } if abstract != none [ = Abstract #abstract ] /////////////////////////////////////// // Display the table of contents // additional_pages_before_outline_table_of_contents pagebreak(weak: true) additional_pages_before_outline_table_of_contents //page()[ if show_pages.outline_table_of_contents [ #tudapub-make-outline-table-of-contents( outline_table_of_contents_style: outline_table_of_contents_style, heading_numbering_max_level: outline_table_of_contents_max_level ) ] // mark start of body //box[#figure(none) <__after_table_of_contents>] [#metadata("After Table of Contents") <__after_table_of_contents>] //[abc] // restart page counter counter(page).update(1) // restart heading counter counter(heading).update(0) // additional_pages_after_outline_table_of_contents pagebreak(weak: true) additional_pages_after_outline_table_of_contents // enable heading outlined for body set heading(outlined: true) // Display the paper's contents. body /////////////////////////////////////// // references if bib != none [ #set heading(outlined: false) //#set text(font: "XCharter") //#set heading(outlined: false) //#bibliography(bibliography_path, style: "ieee", ..bibliography_params_dict) #set bibliography(style: "ieee") #bib ] })
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-算法/动态规划/买卖股票的最佳时机 II.typ
typst
#import "../../../../lib.typ":* === #Title( title: [买卖股票的最佳时机 II], reflink: "https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/", level: 2 )<买卖股票的最佳时机II> #note( title: [ 买卖股票的最佳时机 II ], description: [ 给你一个整数数组 `prices`,其中 `prices[i]` 表示某支股票第 `i` 天的价格。 在每一天,你可以决定是否购买和/或出售股票。你在任何时候 *最多* 只能持有 *一股* 股票。你也可以先购买,然后在 *同一天* 出售。 返回你能获得的 *最大* 利润。 ], examples: ([ 输入:prices = [7,1,5,3,6,4] 输出:7 解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3。 最大总利润为 4 + 3 = 7 。 ],[ 输入:prices = [1,2,3,4,5] 输出:4 解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。 最大总利润为 4 。 ],[ 输入:prices = [7,6,4,3,1] 输出:0 解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0。 ] ), tips: [ 1 <= prices.length <= $3 * 10^4$ 0 <= prices[i] <= $10^4$ ], solutions: ( ( name:[动态规划], text:[ 这是一个经典的动态规划问题,可以通过动态规划的方法来求解。我们定义一个二维数组 `dp`,其中: - `dp[i][0]` 表示在第 `i` 天不持有股票的最大利润。 - `dp[i][1]` 表示在第 `i` 天持有股票的最大利润。 *状态转移方程* - `dp[i][0]` 可以通过以下两种情况得到: 1. 前一天也不持有股票,`dp[i-1][0]` 2. 前一天持有股票,并在今天卖出了,`dp[i-1][1] + prices[i]` 所以,`dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])` - `dp[i][1]` 可以通过以下两种情况得到: 1. 前一天也持有股票,`dp[i-1][1]` 2. 前一天不持有股票,并在今天买入了,`dp[i-1][0] - prices[i]` 所以,`dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])` *初始条件* - `dp[0][0] = 0`:第一天不持有股票,利润为0 - `dp[0][1] = -prices[0]`:第一天持有股票,利润为负的股票价格 *最终结果* 我们需要返回在最后一天不持有股票的最大利润,即 `dp[n-1][0]`。 ],code:[ ```cpp class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n == 0) return 0; int dp[n][2]; dp[0][0] = 0; dp[0][1] = -prices[0]; for (int i = 1; i < n; i++) { dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); } return dp[n-1][0]; } }; ``` ]),( name:[贪心算法], text:[ *对于单独交易日*:设今天价格 $p_1$、明天价格 $p_2$,则今天买入、明天卖出可赚取金额 $p_2−p_1$(负值代表亏损)。 *对于连续上涨交易日*:设此上涨交易日股票价格分别为 $p_1$, $p_2$, ..., $p_n$,则第一天买最后一天卖收益最大,即 $p_n−p_1$;等价于每天都买卖,即 $p_n−p_1=(p_2−p_1)+(p_3−p_2)+...+(p_n−p_(n-1))$。 *对于连续下降交易日*:则不买卖收益最大,即不会亏钱。 *算法流程* 遍历整个股票交易日价格列表 price,并执行贪心策略:所有上涨交易日都买卖(赚到所有利润),所有下降交易日都不买卖(永不亏钱)。 + 设 `tmp` 为第 $i-1$ 日买入与第 $i$ 日卖出赚取的利润,即 `tmp = prices[i] - prices[i - 1]`; + 当该天利润为正 $"tmp" > 0$,则将利润加入总利润 `profit` ;当利润为 0 或为负,则直接跳过; + 遍历完成后,返回总利润 `profit`。 #figure( image("./img/solution1.png") ) ], code:[ ```cpp class Solution { public: int maxProfit(vector<int>& prices) { int profit = 0; for (int i = 1; i < prices.size(); i++) { int tmp = prices[i] - prices[i - 1]; if (tmp > 0) profit += tmp; } return profit; } }; ``` ] ) ), gain:none, )
https://github.com/QuadnucYard/crossregex-typ
https://raw.githubusercontent.com/QuadnucYard/crossregex-typ/main/examples/standard-filled.typ
typst
MIT License
#import "../src/lib.typ": crossregex #crossregex( 7, constraints: ( `.*H.*H.*`, `(DI|NS|TH|OM)*`, `F.*[AO].*[AO].*`, `(O|RHH|MM)*`, `.*`, `C*MC(CCC|MM)*`, `[^C]*[^R]*III.*`, `(...?)\1*`, `([^X]|XCC)*`, `(RR|HHH)*.?`, `N.*X.X.X.*E`, `R*D*M*`, `.(C|HH)*`, `.*G.*V.*H.*`, `[CR]*`, `.*XEXM*`, `.*DD.*CCM.*`, `.*XHCR.*X.*`, `.*(.)(.)(.)(.)\4\3\2\1.*`, `.*(IN|SE|HI)`, `[^C]*MMM[^C]*`, `.*(.)C\1X\1.*`, `[CEIMU]*OH[AEMOR]*`, `(RX|[^R])*`, `[^M]*M[^M]*`, `(S|MM|HHH)*`, `.*SE.*UE.*`, `.*LR.*RL.*`, `.*OXR.*`, `([^EMC]|EM)*`, `(HHX|[^HX])*`, `.*PRR.*DDC.*`, `.*`, `[AM]*CM(RC)*R?`, `([^MC]|MM|CC)*`, `(E|CR|MN)*`, `P+(..)\1.*`, `[CHMNOR]*I[CHMNOR]*`, `(ND|ET|IN)[^X]*`, ), answer: ( "NHPEH S", "DIOM--TH", "FH NX PH", "MMOMMMMRHH", " C E MCRX M", "CMCCc?MMMMMM", "HRXRMciIIiX S", "OREOREOREORE", "VCXCCOHMXCC", "RRRRHHHRRU", "NCX X X E", "RRdDdddd", "GCChhhh", ), )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/bone-resume/0.1.0/template/main.typ
typst
Apache License 2.0
#import emoji: star #import "@preview/bone-resume:0.1.0": resume-init, resume-section #show: resume-init.with( author: "张三", footer: [Powered by #link( "https://github.com/typst/packages/tree/main/packages/preview/bone-resume", )[BoneResume]], ) #stack(dir: ltr, spacing: 1fr, text(24pt)[*张三*], stack( spacing: 0.75em, [微信: weixin], [电话: 188 8888 8888], [邮箱: #link("mailto:<EMAIL>")[<EMAIL>]], ), stack( spacing: 0.75em, [GitHub: #link("https://github.com/zrr1999")[github.com/zrr1999]], [个人主页: #link("https://www.bone6.top")[www.bone6.top]], ), move(dy: -2em, box(height: 84pt, width: 60pt))) #v(-5em) = 教育背景 西安电子科技大学 #h(2cm) 智能科学与技术专业(学士) #h(1fr) 2018.09-2022.07\ 西安电子科技大学 #h(2cm) 计算机科学与技术专业(在读硕士) #h(1fr) 2022.09-2025.07 = 开源贡献 #resume-section( link("https://github.com/PaddlePaddle/CINN")[PaddlePaddle/CINN], "针对神经网络的编译器基础设施", )[ 添加了 argmax, sort, gather, gather_nd, scatter_nd 等算子, 实现了 CSE Pass 和 ReverseComputeInline 原语以及参与了一些单元测试补全,具体内容见 #link( "https://github.com/PaddlePaddle/CINN/pulls?q=is%3Apr+author%3Azrr1999+is%3Aclosed", )[相关 PR]。 ] #resume-section( link("https://github.com/PaddlePaddle/Paddle")[PaddlePaddle/Paddle], "高性能单机、分布式训练和跨平台部署框架", )[ 添加了 remainder\_, sparse_transpose, sparse_sum 三个算子, 实现了 TensorRT onehot 算子转换功能,以及修复了一些bug,具体内容见 #link( "https://github.com/PaddlePaddle/Paddle/pulls?q=is%3Apr+author%3Azrr1999+is%3Aclosed", )[相关 PR]。 ] = 实习经历 #resume-section( [#link("https://github.com/PaddlePaddle/PaddleSOT")[百度飞桨框架开发-动转静小组](线上实习)], "2023.07.01-2023.10.31", )[ 主要工作是参与 #link("https://github.com/PaddlePaddle/PaddleSOT")[PaddleSOT] 的开发,主要贡献包括: + 添加注册优先级机制并重构模拟变量机制。 + 优化字节码模拟执行报错信息和`GitHub Actions`日志信息。 + 实现 `VariableStack` 并添加子图打断的`Python3.11`支持。 ] #resume-section( [#link("https://github.com/PaddlePaddle/Paddle")[百度飞桨框架开发-PIR项目](线上实习)], "2023.11.01-2024.05.31", )[ 主要工作是参与 #link("https://github.com/PaddlePaddle/Paddle")[Paddle] 中 PIR 组件的开发,主要贡献包括: + Python API 适配升级。 + API 类型检查的生成机制实现。 + 添加 `InvalidType` 错误类型。 ] = 个人技能 #let stars(num) = { for _ in range(num) { [#emoji.star] } } #let level(num, desc: none) = { if desc == none { if num < 3 { desc = "了解" } else if num < 5 { desc = "掌握" } else if num < 7 { desc = "熟练" } else { desc = "精通" } } // [(#desc) #stars(num)] [#desc] } #grid( columns: (60pt, 1fr, auto), rows: auto, gutter: 6pt, "Python", [有丰富的大型开源项目开发经验,熟悉字节码等机制并有实际项目经验 ], level(8), "C/C++", [有较为丰富的大型开源项目开发经验,擅长编写高性能算子], level(5), "CUDA", [有一定的的大型开源项目算子开发经验], level(4), "JS/TS", [有多项前端或全栈小型项目开发经验,获得若干奖项], level(4), "Rust", [有局部修改其他开源项目的经历,了解基本的工具链], level(3), "Typst", [对 Typst 语言的实现原理有过了解,修复过官方示例中小错误], level(3), "LaTeX", [在本科期间,作为主要编写文档的工具使用至少三年], level(3), )
https://github.com/8LWXpg/typst-ansi-render
https://raw.githubusercontent.com/8LWXpg/typst-ansi-render/master/README.md
markdown
MIT License
# ANSI Escape Sequence Renderer <a href="https://github.com/8LWXpg/typst-ansi-render/tags" style="text-decoration: none;"> <img alt="GitHub manifest version (path)" src="https://img.shields.io/github/v/tag/8LWXpg/typst-ansi-render"> </a> <a href="https://github.com/8LWXpg/typst-ansi-render" style="text-decoration: none;"> <img src="https://img.shields.io/github/stars/8LWXpg/typst-ansi-render?style=flat" alt="GitHub Repo stars"> </a> <a href="https://github.com/8LWXpg/typst-ansi-render/blob/master/LICENSE" style="text-decoration: none;"> <img alt="GitHub" src="https://img.shields.io/github/license/8LWXpg/typst-ansi-render"> </a> <a href="https://github.com/typst/packages/tree/main/packages/preview/ansi-render" style="text-decoration: none;"> <img alt="typst package" src="https://img.shields.io/badge/typst-package-239dad"> </a> This script provides a simple way to render text with ANSI escape sequences. Package `ansi-render` provides a function `ansi-render`, and a dictionary of themes `terminal-themes`. contribution is welcomed! ## Usage ```typst #import "@preview/ansi-render:0.6.1": * #ansi-render( string, font: string or none, size: length, width: auto or relative length, height: auto or relative length, breakable: boolean, radius: relative length or dictionary, inset: relative length or dictionary, outset: relative length or dictionary, spacing: relative length or fraction, above: relative length or fraction, below: relative length or fraction, clip: boolean, bold-is-bright: boolean, theme: terminal-themes.theme, ) ``` ### Parameters - `string` - string with ANSI escape sequences - `font` - font name or none, default is `Cascadia Code`, set to `none` to use the same font as `raw` - `size` - font size, default is `1em` - `bold-is-bright` - boolean, whether bold text is rendered with bright colors, default is `false` - `theme` - theme, default is `vscode-light` - parameters from [`block`](https://typst.app/docs/reference/layout/block/) function with the same default value, only affects outmost block layout: - `width` - `height` - `breakable` - `radius` - `inset` - `outset` - `spacing` - `above` - `below` - `clip` ## Themes see [themes](https://github.com/8LWXpg/typst-ansi-render/blob/master/test/themes.pdf) ## Demo see [demo.typ](https://github.com/8LWXpg/typst-ansi-render/blob/master/test/demo.typ) [demo.pdf](https://github.com/8LWXpg/typst-ansi-render/blob/master/test/demo.pdf) ```typst #ansi-render( "\u{1b}[38;2;255;0;0mThis text is red.\u{1b}[0m \u{1b}[48;2;0;255;0mThis background is green.\u{1b}[0m \u{1b}[38;2;255;255;255m\u{1b}[48;2;0;0;255mThis text is white on a blue background.\u{1b}[0m \u{1b}[1mThis text is bold.\u{1b}[0m \u{1b}[4mThis text is underlined.\u{1b}[0m \u{1b}[38;2;255;165;0m\u{1b}[48;2;255;255;0mThis text is orange on a yellow background.\u{1b}[0m", inset: 5pt, radius: 3pt, theme: terminal-themes.vscode ) ``` ![1.png](https://github.com/8LWXpg/typst-ansi-render/blob/master/img/1.png) ```typst #ansi-render( "\u{1b}[38;5;196mRed text\u{1b}[0m \u{1b}[48;5;27mBlue background\u{1b}[0m \u{1b}[38;5;226;48;5;18mYellow text on blue background\u{1b}[0m \u{1b}[7mInverted text\u{1b}[0m \u{1b}[38;5;208;48;5;237mOrange text on gray background\u{1b}[0m \u{1b}[38;5;39;48;5;208mBlue text on orange background\u{1b}[0m \u{1b}[38;5;255;48;5;0mWhite text on black background\u{1b}[0m", inset: 5pt, radius: 3pt, theme: terminal-themes.vscode ) ``` ![2.png](https://github.com/8LWXpg/typst-ansi-render/blob/master/img/2.png) ```typst #ansi-render( "\u{1b}[31;1mHello \u{1b}[7mWorld\u{1b}[0m \u{1b}[53;4;36mOver and \u{1b}[35m Under! \u{1b}[7;90mreverse\u{1b}[101m and \u{1b}[94;27mreverse", inset: 5pt, radius: 3pt, theme: terminal-themes.vscode ) ``` ![3.png](https://github.com/8LWXpg/typst-ansi-render/blob/master/img/3.png) ```typst // uses the font that supports ligatures #ansi-render(read("./test/test.txt"), inset: 5pt, radius: 3pt, font: "Cascadia Code", theme: terminal-themes.putty) ``` ![4.png](https://github.com/8LWXpg/typst-ansi-render/blob/master/img/4.png)
https://github.com/liuguangxi/fractusist
https://raw.githubusercontent.com/liuguangxi/fractusist/main/tests/test-peano-curve.typ
typst
MIT License
#set document(date: none) #import "/src/lib.typ": * #set page(margin: 1cm) = n = 1 #align(center)[ #peano-curve(1, step-size: 40) ] = n = 2 #align(center)[ #peano-curve(2, step-size: 10, stroke-style: blue + 4pt) ] = n = 3 #align(center)[ #peano-curve(4, step-size: 5, stroke-style: stroke(paint: gray, thickness: 2pt, cap: "square")) ] #pagebreak(weak: true) = n = 4 #align(center)[ #peano-curve(4, step-size: 6, stroke-style: stroke(paint: gradient.radial(..color.map.crest), thickness: 4pt, cap: "square")) ] #pagebreak(weak: true)
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/ARO/docs/TE/TE1.typ
typst
#import "/_settings/typst/template-te.typ": * #show: resume.with( "Résumé ARO", "<NAME>", cols: 2 ) == Taille mot mémoire La taille d'un mot mémoire est forcément un multiple de $8$. C'est pourquoi nous pouvons appliquer le tableau suivant : #image("/_src/img/docs/image.png") == Gestion des adresses En fonction de la taille de la mémoire nous aurons une taille d'adresses variables, le tableau suivant représente les possibilités : #image("/_src/img/docs/image2.png") == Calculer la mémoire === Calculer adresse de fin $ "Adr.Fin" = "Adr.Deb" + "Taille" - 1 $ === Calculer adresse de début $ "Adr.Deb" = "Adr.Fin" - "Taille" + 1 $ === Calculer la taille $ "Taille" = "Adr.Fin" - "Adr.Deb" + 1 $ ==== Autre formule $ "Taille" = 1 << log_2(2^n) $ $n =$ le nombre de bits alloué à la zone mémoire Exemple : $2"KB" = 2^10 * 2^1 = 2^11$ donc $n = 11$ == Saut inconditionnel #image("/_src/img/docs/image copy 9.png") L'opcode pour un saut inconditionnel prends 5 bits et le reste est alloué pour donner l'adresse de la prochaine instruction à exécuter. === Calcul de l'adresse de saut Pour calculer l'adresse de saut il suffit d'utiliser la formule suivante : $ "Adr" = "PC" + "extension_16bits"("offset"_11 * 2) + 4 $ #table( columns: (0.5fr, 1fr), [*Code d'instruction*], [*Incrément*], "Adr", "Adresse finale du saut", "PC", "Adresse de l'instruction courante", "Extension 16 bits", "Extension de l'adresse de saut en y ajoutant la valeur du bit de signe", "Offset","Correspond à l'instruction moins les 5 bits de l'opcode", "4", "Valeur en fixe à ajouter à l'adresse de saut" ) == Saut conditionnel #image("/_src/img/docs/image copy 10.png") Pour calculer l'adresse de saut il suffit d'utiliser la formule suivante *attention elle est légèrement différente de celle pour le saut inconditionnel* : $ "Adr" = "PC" + "extension_16bits"("offset"_8 * 2) + 4 $ #colbreak() == Instructions #table( align: center + horizon, columns: (0.5fr, 1fr), rows: 10pt, [*Mnemonic*],[*Instruction*], "ADC","Add with Carry", "ADD","Add", "AND","AND", "ASR","Arithmetic Shift Right", "B","Uncoditional Branch", "Bxx","Conditional Branch", "BIC","Bit Clear", "BL","Branch and Link", "BX","Branch and Exchange", "CMN","Compare NOT", "CMP","Compare", "EOR","XOR", "LDMIA","Load Multiple", "LDR","Load Word", "LDRB","Load Byte", "LDRH","Load Halfword", "LSL","Logical Shift Left", "LDSB","Load Sign-Extended Byte", "LDSH","Load Sign-Extended Halfword", "LSR","Logical Shift Right", "MOV","Move Register", "MUL","Multiply", "MVN","Move NOT(Register)", "NEG","Negate (" + $*-1$ + ")", "ORR","OR", "POP","Pop Register", "PUSH","Push Register", "ROR","Rotate Right", "SBC","Subtract with Carry", "STMIA","Store Multiple", "STR","Store Word", "STRB","Store Byte", "STRH","Store Halfword", "SWI","Software Interrupt", "SUB","Subtract", "TST","Test Bits", ) #table( columns: (1fr, 1fr, 1fr), [*Décimal*], [*Héxadécimal*], [*Binaire*], "0", "0", "0000", "1", "1", "0001", "2", "2", "0010", "3", "3", "0011", "4", "4", "0100", "5", "5", "0101", "6", "6", "0110", "7", "7", "0111", "8", "8", "1000", "9", "9", "1001", "10", "A", "1010", "11", "B", "1011", "12", "C", "1100", "13", "D", "1101", "14", "E", "1110", "15", "F", "1111" ) == Incrémenter le PC #table( columns: (1fr, 1fr), [*Code d'instruction*], [*Incrément*], "8 bits = 1 byte", "1", "16 bits = 2 bytes", "2", "32 bits = 4 bytes", "4", ) #colbreak() == Registres spéciaux #table( columns: (0.5fr, 1fr), [*Registre*], [*Objectif*], "R13 / R5", "Stack Pointer (SP) " + sym.arrow + " Stocke la position dans la pile de stockage (interruptions chaînées)", "R14 / R6", "Link Register (LR) " + sym.arrow + "Garde l’adresse de retour (appel de fct, interruption)", "R15 / R7", "Program Counter (PC) " + sym.arrow + "Stocke l’adresse de la prochaine instruction", ) Lors d'une interruption on stocke la valeur actuelle du PC dans le LR et on met la valeur de l'adresse de l'interruption dans le PC. == Puissance de 2 #table( columns: (1fr, 1fr), [*Puissance de 2*], [*Résultat*], $2^0$, "1", $2^1$, "2", $2^2$, "4", $2^3$, "8", $2^4$, "16", $2^5$, "32", $2^6$, "64", $2^7$, "128", $2^8$, "256", $2^9$, "512", )
https://github.com/hzkonor/bubble-template
https://raw.githubusercontent.com/hzkonor/bubble-template/main/template.typ
typst
// main project #let bubble( title: "", subtitle: none, author: "", affiliation: none, year: none, class: none, other: none, date: datetime.today().display(), logo: none, main-color: "E94845", alpha: 60%, color-words: (), body, ) = { set document(author: author, title: title) // Save heading and body font families in variables. let body-font = "Source Sans Pro" let title-font = "Barlow" // Set colors let primary-color = rgb(main-color) // alpha = 100% // change alpha of primary color let secondary-color = color.mix(color.rgb(100%, 100%, 100%, alpha), primary-color, space:rgb) // highlight important words show regex(if color-words.len() == 0 { "$ " } else { color-words.join("|") }): text.with(fill: primary-color) //customize look of figure set figure.caption(separator: [ --- ], position: top) //customize inline raw code show raw.where(block: false) : it => h(0.5em) + box(fill: primary-color.lighten(90%), outset: 0.2em, it) + h(0.5em) // Set body font family. set text(font: body-font, 12pt) show heading: set text(font: title-font, fill: primary-color) //heading numbering set heading(numbering: (..nums) => { let level = nums.pos().len() // only level 1 and 2 are numbered let pattern = if level == 1 { "I." } else if level == 2 { "I.1." } if pattern != none { numbering(pattern, ..nums) } }) // add space for heading show heading.where(level:1): it => it + v(0.5em) // Set link style show link: it => underline(text(fill: primary-color, it)) //numbered list colored set enum(indent: 1em, numbering: n => [#text(fill: primary-color, numbering("1.", n))]) //unordered list colored set list(indent: 1em, marker: n => [#text(fill: primary-color, "•")]) // display of outline entries show outline.entry: it => text(size: 12pt, weight: "regular",it) // Title page. // Logo at top right if given if logo != none { set image(width: 6cm) place(top + right, logo) } // decorations at top left place(top + left, dx: -35%, dy: -28%, circle(radius: 150pt, fill: primary-color)) place(top + left, dx: -10%, circle(radius: 75pt, fill: secondary-color)) // decorations at bottom right place(bottom +right, dx: 40%, dy: 30%, circle(radius: 150pt, fill: secondary-color)) v(2fr) align(center, text(font: title-font, 3em, weight: 700, title)) v(2em, weak: true) if subtitle != none { align(center, text(font: title-font, 2em, weight: 700, subtitle)) v(2em, weak: true) } align(center, text(1.1em, date)) v(2fr) // Author and other information. align(center)[ #if author != "" {strong(author); linebreak();} #if affiliation != none {affiliation; linebreak();} #if year != none {year; linebreak();} #if class != none {emph(class); linebreak();} #if other != none {emph(other.join(linebreak())); linebreak();} ] pagebreak() // Table of contents. set page( numbering: "1 / 1", number-align: center, ) // Main body. set page( header: [#emph()[#title #h(1fr) #author]] ) set par(justify: true) body } //useful functions //set block-quote #let blockquote = rect.with(stroke: (left: 2.5pt + luma(170)), inset: (left: 1em)) // use primary-color and secondary-color in main #let primary-color = rgb("E94845") #let secondary-color = rgb(255, 80, 69, 60%)
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/布局/规模/scale.typ
typst
#image("image.png"); #image("image2.png"); #image("image3.png");
https://github.com/Ombrelin/adv-java
https://raw.githubusercontent.com/Ombrelin/adv-java/master/Slides/6-prog-reseau.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/sourcerer:0.2.1": code #import themes.clean: * #show: clean-theme.with( logo: image("images/efrei.jpg"), footer: [<NAME>, EFREI Paris], short-title: [EFREI LSI L3 ALSI62-CTP : Java Avancé], color: rgb("#EB6237") ) #title-slide( title: [Java Avancé], subtitle: [Cours 6 : Programmation Réseau], authors: ([<NAME>]), date: [15 Février 2024], ) #new-section-slide("Introduction") #slide(title: "Socket")[ *Thread* : flux d'entrée/sortie réseau. - Même interface que les autres entrées/sortie (fichiers, console) - Utilise les couches réseau TCP ou UDP pour communiquer avec d'autres machines - Le cours couvre le cas des sockets TCP ] #slide(title: "Socket Java")[ Modèle client-serveur. Classes : - `ServerSocket` : se lie à un port sur la machine serveur - `Socket` : se connecte à un port sur une IP `ServerSocket.accept` bloque jusqu'à la connexion d'un client et retourne une `Socket` ouverte vers le client à chaque connexion. ] #slide(title: "Coté Serveur")[ Attente d'un client et ouverture des flux : #code( lang: "Java", ```java final var serverSocket = new ServerSocket(3000); final var socket = serverSocket.accept(); final var streamFromClient = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); final var streamToClient = new PrintWriter(socket.getOutputStream(), true); ```) ] #slide(title: "Coté Client")[ Connexion au serveur et ouverture des flux : #code( lang: "Java", ```java final var clientSocket = new Socket(3000, "localhost"); final var streamFromClient = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()) ); final var streamToClient = new PrintWriter( clientSocket.getOutputStream(), true ); ```) ] #slide(title: "Socket et threads")[ `println` et `readLine` sont bloquants : - Un `println` côté client bloque jusqu'au prochain `readLine` côté serveur - Un `readLine` côté client bloque jusqu'au prochain `println` côté serveur Et vice-versa. _Il faut utiliser des threads !_ ] #slide(title: "Exemple : serveur de chat")[ #code( lang: "Java", ```java public class ChatServer { private final int port; private final List<PrintWriter> connectedClients; public ChatServer(int port) { this.port = port; this.connectedClients = new ArrayList<>(); } public void start() { final var serverSocket = new ServerSocket(port); while (true) { final var client = serverSocket.accept(); connectedClients.add( new PrintWriter(client.getOutputStream(),true) ); new Thread(() -> listenForMessage(connectedClient)) .start(); } } private void listenForMessage(Socket client) { final BufferedReader messages = new BufferedReader( new InputStreamReader(client.getInputStream()) ); while (true) { final var message = messages.readLine(); for (final var connectedClient : connectedClients) { connectedClient.println(messageFromClient); } } } ``` ) ] #slide(title: "Exemple : client de chat")[ #code( lang: "Java", ```java public class ChatServer { private final int port; private final String address; private BufferedReader messagesFromServerStream; private PrintWriter messagesToServerStream, output; public ChatClient(int port,String address,PrintWriter out){ this.port = port; this.address = address; this.output = out; } public void connect() { final var socket = new Socket(address, port); messagesFromServerStream = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); messagesToServerStream = new PrintWriter( socket.getOutputStream(), true ); new Thread(this::listenForMessages).start(); } private void listenForMessages(){ while (true){ final var message = messagesFromServerStream.readLine(); output.println(message); } } public void sendMessage(String message){ messagesToServerStream.println(message); } } ``` ) ]
https://github.com/jverzani/CalculusWithJuliaNotes.jl
https://raw.githubusercontent.com/jverzani/CalculusWithJuliaNotes.jl/main/quarto/test.typ
typst
MIT License
// Some definitions presupposed by pandoc's typst output. #let blockquote(body) = [ #set text( size: 0.92em ) #block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body] ] #let horizontalrule = [ #line(start: (25%,0%), end: (75%,0%)) ] #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #show terms: it => { it.children .map(child => [ #strong[#child.term] #block(inset: (left: 1.5em, top: -0.4em))[#child.description] ]) .join() } // Some quarto-specific definitions. #show raw.where(block: true): set block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt ) #let block_with_new_content(old_block, new_content) = { let d = (:) let fields = old_block.fields() fields.remove("body") if fields.at("below", default: none) != none { // TODO: this is a hack because below is a "synthesized element" // according to the experts in the typst discord... fields.below = fields.below.amount } return block.with(..fields)(new_content) } #let unescape-eval(str) = { return eval(str.replace("\\", "")) } #let empty(v) = { if type(v) == "string" { // two dollar signs here because we're technically inside // a Pandoc template :grimace: v.matches(regex("^\\s*$")).at(0, default: none) != none } else if type(v) == "content" { if v.at("text", default: none) != none { return empty(v.text) } for child in v.at("children", default: ()) { if not empty(child) { return false } } return true } } // Subfloats // This is a technique that we adapted from https://github.com/tingerrr/subpar/ #let quartosubfloatcounter = counter("quartosubfloatcounter") #let quarto_super( kind: str, caption: none, label: none, supplement: str, position: none, subrefnumbering: "1a", subcapnumbering: "(a)", body, ) = { context { let figcounter = counter(figure.where(kind: kind)) let n-super = figcounter.get().first() + 1 set figure.caption(position: position) [#figure( kind: kind, supplement: supplement, caption: caption, { show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1)) show figure.where(kind: kind): set figure.caption(position: position) show figure: it => { let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1) show figure.caption: it => { num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug? [ ] it.body } quartosubfloatcounter.step() it counter(figure.where(kind: it.kind)).update(n => n - 1) } quartosubfloatcounter.update(0) body } )#label] } } // callout rendering // this is a figure show rule because callouts are crossreferenceable #show figure: it => { if type(it.kind) != "string" { return it } let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none) if kind_match == none { return it } let kind = kind_match.captures.at(0, default: "other") kind = upper(kind.first()) + kind.slice(1) // now we pull apart the callout and reassemble it with the crossref name and counter // when we cleanup pandoc's emitted code to avoid spaces this will have to change let old_callout = it.body.children.at(1).body.children.at(1) let old_title_block = old_callout.body.children.at(0) let old_title = old_title_block.body.body.children.at(2) // TODO use custom separator if available let new_title = if empty(old_title) { [#kind #it.counter.display()] } else { [#kind #it.counter.display(): #old_title] } let new_title_block = block_with_new_content( old_title_block, block_with_new_content( old_title_block.body, old_title_block.body.body.children.at(0) + old_title_block.body.body.children.at(1) + new_title)) block_with_new_content(old_callout, block(below: 0pt, new_title_block) + old_callout.body.children.at(1)) } // 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead #let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black) = { block( breakable: false, fill: background_color, stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"), width: 100%, radius: 2pt, block( inset: 1pt, width: 100%, below: 0pt, block( fill: background_color, width: 100%, inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) + if(body != []){ block( inset: 1pt, width: 100%, block(fill: white, width: 100%, inset: 8pt, body)) } ) } #let article( title: none, subtitle: none, authors: none, date: none, abstract: none, abstract-title: none, cols: 1, margin: (x: 1.25in, y: 1.25in), paper: "us-letter", lang: "en", region: "US", font: "linux libertine", fontsize: 11pt, title-size: 1.5em, subtitle-size: 1.25em, heading-family: "linux libertine", heading-weight: "bold", heading-style: "normal", heading-color: black, heading-line-height: 0.65em, sectionnumbering: none, toc: false, toc_title: none, toc_depth: none, toc_indent: 1.5em, doc, ) = { set page( paper: paper, margin: margin, numbering: "1", ) set par(justify: true) set text(lang: lang, region: region, font: font, size: fontsize) set heading(numbering: sectionnumbering) if title != none { align(center)[#block(inset: 2em)[ #set par(leading: heading-line-height) #if (heading-family != none or heading-weight != "bold" or heading-style != "normal" or heading-color != black or heading-decoration == "underline" or heading-background-color != none) { set text(font: heading-family, weight: heading-weight, style: heading-style, fill: heading-color) text(size: title-size)[#title] if subtitle != none { parbreak() text(size: subtitle-size)[#subtitle] } } else { text(weight: "bold", size: title-size)[#title] if subtitle != none { parbreak() text(weight: "bold", size: subtitle-size)[#subtitle] } } ]] } if authors != none { let count = authors.len() let ncols = calc.min(count, 3) grid( columns: (1fr,) * ncols, row-gutter: 1.5em, ..authors.map(author => align(center)[ #author.name \ #author.affiliation \ #author.email ] ) ) } if date != none { align(center)[#block(inset: 1em)[ #date ]] } if abstract != none { block(inset: 2em)[ #text(weight: "semibold")[#abstract-title] #h(1em) #abstract ] } if toc { let title = if toc_title == none { auto } else { toc_title } block(above: 0em, below: 2em)[ #outline( title: toc_title, depth: toc_depth, indent: toc_indent ); ] } if cols == 1 { doc } else { columns(cols, doc) } } #set table( inset: 6pt, stroke: none ) #show: doc => article( toc_title: [Table of contents], toc_depth: 3, cols: 1, doc, ) #block[ #heading( level: 1 , numbering: none , [ Preface ] ) ] #figure([ #box(image("misc/logo.png")) ], caption: figure.caption( position: bottom, [ Calculus with Julia ]), kind: "quarto-float-fig", supplement: "Figure", ) #horizontalrule This is a set of notes for learning #link("http://en.wikipedia.org/wiki/Calculus")[calculus] using the #link("https://julialang.org")[`Julia`] language. `Julia` is an open-source programming language with an easy to learn syntax that is well suited for this task. Read "#link("./misc/getting_started_with_julia.html")[Getting started with Julia];" to learn how to install and customize `Julia` for following along with these notes. Read "#link("./misc/julia_interfaces.html")[Julia interfaces];" to review different ways to interact with a `Julia` installation. Since the mid 90s there has been a push to teach calculus using many different points of view. The #link("http://www.math.harvard.edu/~knill/pedagogy/harvardcalculus/")[Harvard] style rule of four says that as much as possible the conversation should include a graphical, numerical, algebraic, and verbal component. These notes use the programming language #link("http://julialang.org")[Julia] to illustrate the graphical, numerical, and, at times, the algebraic aspects of calculus. There are many examples of integrating a computer algebra system (such as `Mathematica`, `Maple`, or `Sage`) into the calculus conversation. Computer algebra systems can be magical. The popular #link("http://www.wolframalpha.com/")[WolframAlpha] website calls the full power of `Mathematica` while allowing an informal syntax that is flexible enough to be used as a backend for Apple’s Siri feature. ("Siri what is the graph of x squared minus 4?") For learning purposes, computer algebra systems model very well the algebraic/symbolic treatment of the material while providing means to illustrate the numeric aspects. These notes are a bit different in that `Julia` is primarily used for the numeric style of computing and the algebraic/symbolic treatment is added on. Doing the symbolic treatment by hand can be very beneficial while learning, and computer algebra systems make those exercises seem kind of redundant, as the finished product can be produced much more easily. Our real goal is to get at the concepts using technology as much as possible without getting bogged down in the mechanics of the computer language. We feel `Julia` has a very natural syntax that makes the initial start up not so much more difficult than using a calculator, but with a language that has a tremendous upside. The notes restrict themselves to a reduced set of computational concepts. This set is sufficient for working many of the problems in calculus, but do not cover thoroughly many aspects of programming. (Those who are interested can go off on their own and `Julia` provides a rich opportunity to do so.) Within this restricted set, are operators that make many of the computations of calculus reduce to a function call of the form `action(function, arguments...)`. With a small collection of actions that can be composed, many of the problems associated with introductory calculus can be attacked. These notes are presented in pages covering a fairly focused concept, in a spirit similar to a section of a book. Just like a book, there are try-it-yourself questions at the end of each page. All have a limited number of self-graded answers. These notes borrow ideas from many sources, for example #cite(<Strang>, form: "prose");, #cite(<Knill>, form: "prose");, #cite(<Schey>, form: "prose");, #cite(<Thomas>, form: "prose");, #cite(<RogawskiAdams>, form: "prose");, several Wikipedia pages, and other sources. These notes are accompanied by a `Julia` package `CalculusWithJulia` that provides some simple functions to streamline some common tasks and loads some useful packages that will be used repeatedly. These notes are presented as a Quarto book. To learn more about Quarto books visit #link("https://quarto.org/docs/books");. To #emph[contribute] – say by suggesting additional topics, correcting a mistake, or fixing a typo – click the "Edit this page" link and join the list of #link("https://github.com/jverzani/CalculusWithJuliaNotes.jl/graphs/contributors")[contributors];. Thanks to all contributors and a #emph[very] special thanks to `@fangliu-tju` for their careful and most-appreciated proofreading. = Running Julia <running-julia> `Julia` is installed quite easily with the `juliaup` utility. There are some brief installation notes in the overview of `Julia` commands. To run `Julia` through the web (though in a resource-constrained manner), these links resolve to `binder.org` instances: - #link("https://mybinder.org/v2/gh/jverzani/CalculusWithJuliaBinder.jl/main?labpath=blank-notebook.ipynb")[#box(image("test_files/mediabag/badge_logo.svg"))] (Image without SymPy) - #link("https://mybinder.org/v2/gh/jverzani/CalculusWithJuliaBinder.jl/sympy?labpath=blank-notebook.ipynb")[#box(image("test_files/mediabag/badge_logo.svg"))] (Image with SymPy, longer to load) #horizontalrule Calculus with Julia version #strong[?meta:version];, produced on #strong[?meta:date];.
https://github.com/jonathan-iksjssen/jx-style
https://raw.githubusercontent.com/jonathan-iksjssen/jx-style/main/0.1.0/debug.typ
typst
#import "@jx/jx-style:0.1.0": * #show: docu.with(debug:true, colsc: "red", )
https://github.com/Daillusorisch/HYSeminarAssignment
https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/template/template.typ
typst
#import "utils/style.typ": * #import "utils/indent.typ": * #import "components/doc.typ": doc #import "components/cover.typ": cover #import "components/declaration.typ": declaration #import "components/front-matter.typ": front-matter #import "components/abstract-zh.typ": abstract-zh #import "components/abstract-en.typ": abstract-en #import "components/outline.typ": outline-page #import "components/main-matter.typ": main-matter #import "components/tlt.typ": tlt #import "components/acknowledgement.typ": acknowledgement #import "components/appendix.typ": appendix #let thesis( title: "", author: "", student-id: "", major: "", school: "", supervisor: "", date: "", ) = { ( doc: (..args) => { doc( info: ( title: title, author: author, ), ..args, ) }, cover: () => { cover( title: title, author: author, student-id: student-id, major: major, school: school, supervisor: supervisor, date: date ) }, declaration: (..args) => { declaration(..args) }, front-matter: (..args) => { front-matter(..args) }, abstract-zh: ( keywords: (), content ) => { abstract-zh( keywords: keywords )[#content] }, abstract-en: ( keywords: (), content ) => { abstract-en( keywords: keywords )[#content] }, outline-page: (..args) => { outline-page(..args) }, main-matter: (..args) => { main-matter(..args) } ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E100.typ
typst
Apache License 2.0
#let data = ( ("NYIAKENG PUACHUE HMONG LETTER MA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER TSA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NTA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER TA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER HA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER XA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NKA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER CA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER LA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER SA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER ZA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NCA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NTSA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER KA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER DA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NYA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NRA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER VA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NTXA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER TXA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER FA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER RA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER QA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER YA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NQA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER PA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER XYA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NPA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER DLA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER NPLA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER HAH", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER MLA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER PLA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER GA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER RRA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER A", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER AA", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER I", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER U", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER O", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER OO", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER E", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER EE", "Lo", 0), ("NYIAKENG PUACHUE HMONG LETTER W", "Lo", 0), (), (), (), ("<NAME>ONG TONE-B", "Mn", 230), ("<NAME> HMONG TONE-M", "Mn", 230), ("<NAME> HMONG TONE-J", "Mn", 230), ("<NAME> HMONG TONE-V", "Mn", 230), ("<NAME> HMONG TONE-S", "Mn", 230), ("<NAME> HMONG TONE-G", "Mn", 230), ("<NAME>ONG TONE-D", "Mn", 230), ("NYIAKENG PUACHUE HMONG SIGN FOR PERSON", "Lm", 0), ("NYIAKENG PUACHUE HMONG SIGN FOR THING", "Lm", 0), ("NYIAKENG PUACHUE HMONG SIGN FOR LOCATION", "Lm", 0), ("NYIAKENG PUACHUE HMONG SIGN FOR ANIMAL", "Lm", 0), ("NYIAKENG PUACHUE HMONG SIGN FOR INVERTEBRATE", "Lm", 0), ("NYIAKENG PUACHUE HMONG SIGN XW XW", "Lm", 0), ("NYIAKENG PUACHUE HMONG SYLLABLE LENGTHENER", "Lm", 0), (), (), ("NYIAKENG PUACHUE HMONG DIGIT ZERO", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT ONE", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT TWO", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT THREE", "Nd", 0), ("<NAME> HMONG DIGIT FOUR", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT FIVE", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT SIX", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT SEVEN", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT EIGHT", "Nd", 0), ("NYIAKENG PUACHUE HMONG DIGIT NINE", "Nd", 0), (), (), (), (), ("NYIAKENG PUACHUE HMONG LOGOGRAM NYAJ", "Lo", 0), ("NYIAKENG PUACHUE HMONG CIRCLED CA", "So", 0), )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/docs/tinymist/guide/completion.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book-page.with(title: "Guide: Completion") == Using LSP-Based Completion LSP will serve completion if you enter _trigger characters_ in the editor. Currently, the trigger characters are: + any valid identifier character, like ```js 'a'``` or ```js 'Z'```. + ```js '#'```, ```js '('```, ```js '<'```, ```js '.'```, ```js ':'```, ```js '/'```, ```js '"'```, ```js '@'```, which is configured by LSP server. #pro-tip[ === VSCode: Besides, you can trigger the completion manually by pressing ```js Ctrl+Space``` in the editor. If ```js Ctrl+Space``` doesn't work, please check your IME settings or keybindings. ] When an item is selected, it will be commited if some character is typed. 1. press ```js Esc``` to avoid commit. 1. press ```js Enter``` to commit one. 2. press ```js '.'``` to commit one for those that can interact with the dot operator. 3. press ```js ';'``` to commit one in code mode. 4. press ```js ','``` to commit one in list. === Label Completion The LSP will keep watching and compiling your documents to get available labels for completion. Thus, if it takes a long time to compile your document, there will be an expected delay after each editing labels in document. A frequently asked question is how to completing labels in sub files when writing in a multiple-file project. By default, you will not get labels from other files, e.g. bibiliography configured in other files. This is because the "main file" will be tracked when your are switching the focused files. Hence, the solution is to set up the main file correctly for the multi-file project. #pro-tip[ === VSCode: See #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/vscode#working-with-multiple-file-projects")[VS Code: Working with Multiple File Projects]. ] #pro-tip[ === Neovim: See #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/neovim#working-with-multiple-file-projects")[Heovim: Working with Multiple File Projects]. ] #pro-tip[ === Helix: See #link("https://github.com/Myriad-Dreamin/tinymist/tree/main/editors/helix#working-with-multiple-file-projects")[Helix: Working with Multiple File Projects]. ] == Using Snippet-Based Completion #pro-tip[ === VSCode: We suggest to use snippet extensions powered by TextMate Scopes. For example, #link("https://github.com/OrangeX4/OrangeX4-HyperSnips")[HyperSnips] provides context-sensitive snippet completion. ]
https://github.com/mriganksagar/cv
https://raw.githubusercontent.com/mriganksagar/cv/main/modules/projects.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Projects") #cvEntry( title: "Torrent Downloader", society: [Designer/Developer], date: [2023 - Present], description: list( [Developed a torrent client as a functional static site, enabling torrent downloads directly through the browser without backend processing or additional installations.], [Leveraged React.js, Vite Framework to create a seamless and efficient application with Webtorrent.js to power the Torrent client.], [Utilised ShadCn and Tanstack UI libraries with Tailwind to craft a highly responsive and visually appealing user interface.] ) )
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/docs-shiroa/g-exam-doc/page2.typ
typst
MIT License
#import "mod.typ": * #show: book-page.with(title: "Página 2") = Página 2 == Prueba de página 1 #lorem(200) == Prueba de página 2 #lorem(200) *Ejemplo*: ```typ = Página 2 == Prueba de pagina 1 #lorem(200) == Prueba de página 2 #lorem(200) ```
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_240329/content.typ
typst
MIT License
#import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro #import "functions.typ": glossary, team #let participants = csv("participants.csv") = Partecipanti / Inizio incontro: #inizio_incontro / Fine incontro: #fine_incontro / Luogo incontro: #luogo_incontro #table( columns: (3fr, 1fr), [*Nome*], [*Durata presenza*], ..participants.flatten() ) = Sintesi Elaborazione Incontro == Nuovi ruoli Vengono stabiliti i seguenti i nuovi incarichi relativi allo sprint corrente: - <NAME>: Verificatore; - <NAME>: Progettista; - <NAME>: Programmatore, Verificatore; - <NAME>: Amministratore, Progettista, Verificatore; - <NAME>: Analista; - <NAME>: Responsabile, Verificatore. == Conclusione _Manuale Utente v1.0_ L'incontro si è aperto discutendo dello stato di completamento del _Manuale Utente_, che è necessario terminare e revisionare interamente entro la fine dello sprint corrente; la stesura del documento può dirsi terminata, se non che occorre aggiungere qualche dettaglio in più: - Nella sezione riguardante l'installazione del prodotto software, occorre specificare la procedura da seguire per ottenere ed impostare: - API key del servizio utilizzato per simulare percorsi realistici per le biciclette elettriche; - API key del webhook Discord utilizzato per impostare un canale testuale come ente di ricezione delle notifiche che denotano il superamento di soglie predeterminate sui dati simulati; - Aggiungere una breve sezione riguardante la componente di allarmi e relative notifiche menzionata sopra; - Corredare le descrizioni testuali di screenshot che aiutino l'utente a comprendere meglio la funzionalità in esame. <NAME> si occupa del primo punto, mentre <NAME> si occupa degli ultimi due punti. == Conclusione _Piano di Qualifica v2.0_ Anche il _Piano di Qualifica_ deve essere terminato inserendo i dati pertinenti allo sprint corrente al termine dello stesso e aggiornando i grafici di conseguenza; occorre, inoltre, fare una breve analisi dell'andamento delle metriche negli sprint 9-15 (periodo pre-PB), confrontandolo anche con l'andamento nel periodo precedente, e riportarla sotto i grafici (se ne occupa <NAME>). Infine, dato che le modifiche apportate all'_Analisi dei Requisiti_ sono state riportate anche all'interno dei test di accettazione e di sistema, è necessario revisionarli ulteriormente e modificarne lo stato di soddisfacimento, una volta eseguiti in presenza della Proponente. == Conclusione _Specifica Tecnica v1.0_ e _Analisi dei Requisiti v2.0_ La _Specifica Tecnica_ è già stata terminata, occorre semplicemente assicurarsi che lo stato di soddisfacimento dei vari requisiti funzionali, di vincolo e di qualità riportati nella sezione conclusiva dedicata al tracciamento sia aggiornato rispetto a quanto sviluppato nel MVP; questa mansione viene assegnata a Simone Caregnato. Allo stesso modo anche l'_Analisi dei Requisiti_ è conclusa, occorre tuttavia aggiornare alcuni diagrammi UML dei casi d'uso e se ne occupa Matteo Rango. Una volta svolto quanto descritto, i due documenti saranno pronti per essere sottoposti alla valutazione del Prof. Cardin in occasione della PB imminente. Similmente, anche il resto della documentazione richiesta per la seconda parte della PB verrà terminato e revisionato a fondo prima di ottenere l'approvazione finale del Responsabile che ne sancirà anche lo "scatto" di versione. #pagebreak() == Validazione del prodotto software come MVP In vista della presentazione programmata verso la fine dello sprint corrente (il 02/04/24 in sede Sync Lab a Padova), occorre poter garantire che il prodotto sia aderente ai requisiti definiti e che l'interfaccia risulti chiara e comprensibile, oltre che esteticamente gradevole (se ne occupano <NAME> e <NAME>). Scopo della presentazione è esporre le funzionalità implementate all'interno del prodotto software ed eseguire i test di accettazione, in modo da poter ottenere la validazione di quest'ultimo come MVP da parte della Proponente.
https://github.com/rdboyes/resume
https://raw.githubusercontent.com/rdboyes/resume/main/modules_en/certificates.typ
typst
// Imports #import "@preview/brilliant-cv:2.0.2": cvSection, cvHonor #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvHonor = cvHonor.with(metadata: metadata) #cvSection("Certificates") #cvHonor( date: [2022], title: [AWS Certified Security], issuer: [Amazon Web Services (AWS)], ) #cvHonor( date: [2017], title: [Applied Data Science with Python], issuer: [Coursera], )
https://github.com/pauladam94/curryst
https://raw.githubusercontent.com/pauladam94/curryst/main/examples/natural-deduction.typ
typst
MIT License
#import "../curryst.typ": rule, proof-tree #set document(date: none) #set page(width: auto, height: auto, margin: 0.5cm, fill: white) #let ax = rule.with(name: [ax]) #let and-el = rule.with(name: $and_e^ell$) #let and-er = rule.with(name: $and_e^r$) #let impl-i = rule.with(name: $scripts(->)_i$) #let impl-e = rule.with(name: $scripts(->)_e$) #let not-i = rule.with(name: $not_i$) #let not-e = rule.with(name: $not_e$) #proof-tree( impl-i( $tack (p -> q) -> not (p and not q)$, not-i( $p -> q tack not (p and not q)$, not-e( $ underbrace(p -> q\, p and not q, Gamma) tack bot $, impl-e( $Gamma tack q$, ax($Gamma tack p -> q$), and-el( $Gamma tack p$, ax($Gamma tack p and not q$), ), ), and-er( $Gamma tack not q$, ax($Gamma tack p and not q$), ), ), ), ) )
https://github.com/Ombrelin/adv-java
https://raw.githubusercontent.com/Ombrelin/adv-java/master/Slides/projet.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/sourcerer:0.2.1": code #import themes.clean: * #show: clean-theme.with( logo: image("images/efrei.jpg"), footer: [<NAME>, EFREI Paris], short-title: [EFREI LSI L3 ALSI62-CTP : Java Avancé], color: rgb("#EB6237") ) #title-slide( title: [Java Avancé], subtitle: [Projet], authors: ([<NAME>]), date: [19 Janvier 2024], ) #slide(title: [Concept])[ - Coder un Monopoly - Simulation des règles du domaine - Jeu en réseau ] #slide(title: [Notation])[ - 5 Livrables - 4 points par Livrables - 2 points complétion des fonctionnalités - 2 points qualité de code (tests unitaires, qualité logicielle, fonctionnalités du langage) #text("Livrable Bonus : + 2 sur la note d'examen", style: "italic") ] #slide(title: [Planning])[ #table(columns: (auto, auto), inset: 8pt, align: horizon, [*Date*],[*Sujet*], [Vendredi 19 Janvier 2024],[Démarrage du projet], [Dimanche 4 Février 2024],[Date limite de rendu du livrable 1], [Dimanche 18 Février 2024],[Date limite de rendu du livrable 2], [Dimanche 3 Mars 2024],[Date limite de rendu du livrable 3], [Dimanche 17 Mars 2024],[Date limite de rendu du livrable 4], [Dimanche 31 Mars 2024],[Date limite de rendu du livrable 5], [Dimanche 14 Avril 2024],[Date limite de rendu du livrable 6 (bonus)], ) ] #slide(title: [Modalités])[ - Tests d'intégration fournis - Spécification du projet - Condition nécessaire mais pas suffisante pour valider un livrable - Revue de code - Chaque livrable fait l'objet d'une revue de code par l'enseignant - Noté après application des recommendations de la revue ] #slide(title: [Démarrage du projet])[ 1. Créer un compte GitLab 2. Trouver son binôme 3. Communiquer le binôme à l'enseignant par email (<EMAIL>) 4. Forker le projet sur GitLab 5. Ajouter l'enseignant sur le dépôt GitLab 6. Cloner son dépôt 7. Créer son module ] #slide(title: [Processus de livraison])[ 1. Créer une branche `dev/livrable-x` 2. Mettre à jour sa branche de dev : Fusionner `template/livrable-x` de mon dépôt dans `dev/livrable-x` de votre dépôt 3. Coder pour faire passer les tests d'intégration, commiter 4. Pull request `dev/livrable-x` -> `master` (Assignee = enseignant) 5. Je fais la revue, propose des améliorations 6. Vous implémentez les améliorations suggérées, puis je valide la fusion ] #focus-slide(background: rgb("#EB6237"))[ Des questions ? ] #focus-slide(background: rgb("#EB6237"))[ Description du template du projet ] #slide(title: [Livrable 1 : Jets de dés, plateau, déplacement])[ #side-by-side[ - Les joueurs ne peuvent que passer leur tour - Les joueurs se déplacent par jet de dés - Données du plateau dans un fichier CSV de ressources ][ #figure(image("./images/board.png", width:68%)) ] ] #focus-slide(background: rgb("#EB6237"))[ Présentation des tests d'intégration] #focus-slide(background: rgb("#EB6237"))[ Go ! Lancez vous pour le setup du projet]
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/cancel.typ
typst
// Tests the cancel() function. --- math-cancel-inline --- // Inline $a + 5 + cancel(x) + b - cancel(x)$ $c + (a dot.c cancel(b dot.c c))/(cancel(b dot.c c))$ --- math-cancel-display --- // Display #set page(width: auto) $ a + b + cancel(b + c) - cancel(b) - cancel(c) - 5 + cancel(6) - cancel(6) $ $ e + (a dot.c cancel((b + c + d)))/(cancel(b + c + d)) $ --- math-cancel-inverted --- // Inverted $a + cancel(x, inverted: #true) - cancel(x, inverted: #true) + 10 + cancel(y) - cancel(y)$ $ x + cancel("abcdefg", inverted: #true) $ --- math-cancel-cross --- // Cross $a + cancel(b + c + d, cross: #true, stroke: #red) + e$ $ a + cancel(b + c + d, cross: #true) + e $ --- math-cancel-customized --- // Resized and styled #set page(width: 200pt, height: auto) $a + cancel(x, length: #200%) - cancel(x, length: #50%, stroke: #(red + 1.1pt))$ $ b + cancel(x, length: #150%) - cancel(a + b + c, length: #50%, stroke: #(blue + 1.2pt)) $ --- math-cancel-angle-absolute --- // Specifying cancel line angle with an absolute angle $cancel(x, angle: #0deg) + cancel(x, angle: #45deg) + cancel(x, angle: #90deg) + cancel(x, angle: #135deg)$ --- math-cancel-angle-func --- // Specifying cancel line angle with a function $x + cancel(y, angle: #{angle => angle + 90deg}) - cancel(z, angle: #(angle => angle + 135deg))$ $ e + cancel((j + e)/(f + e)) - cancel((j + e)/(f + e), angle: #(angle => angle + 30deg)) $
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/polygon-01.typ
typst
Other
// Error: 10-17 point array must contain exactly two entries #polygon((50pt,))
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/os/lectures/2024-09-09.typ
typst
#import "/utils/math.typ": * #def[ #defitem[Квант времени] --- время, пока программа работает подряд (без передачи управления другим программам) ] Раньше клавиатура и дисплей стали независимы, потом превратились в терминалы, которые выводили данные во время выполнения программы Появилась возможность *отладки* Появляются *файловые системы* (много пользователей могут работать на одном устройстве хранения данных) Программа обычно считается частями: всё программу хранить в оперативной памяти не обязательно Появляется концепция *виртуальной памяти*: абстракция, иллюзия большой оперативной памяти Появилась идея *обратной совместимости*, *полной совместимости*, *линеек устройств* (от слабых компьютеров до мейнфреймов) Популярные линейки: - IBM - PDP Обратная совместимость имеет преимущества, но и заставляет "тащить" за собой недостатки В опр момент IBM решили, что баги в системе править не будут, так как возникают новые баги === 4-ый период (1980 -- 2005) - 1980 год --- развитие больших интегральных схем: весь процессор мог быть на одном кристалле - Первые персональные ЭВМ - Дружественное программное обеспечение: программы пишутся для удобства пользователей - Резкая деградация ОС: пропадает мультипроцессорность, защита памяти и т.д. - Из-за роста мощности (в 90-е) деградация ОС прекращается - Переосмысление роли сетей: из оборонки в пользовательские - Сетевые и распределенные ОС Сетевая ОС --- пользователь явно использует возможности сети Распределенная ОС --- пользователь неявно использует возможности сети, используется абстракция Период широкого использования ЭВМ в быту, в образовании, на производстве === 5-ый период (2005 -- ??) - Появление многоядерных процессоров - Мобильные компьютеры - Высокопроизводительные вычислительные системы - Облачные технологии - Виртуализация выполнения программ: выполнение программы на любом из компьютеров распределительной сети Период глобальной компьютеризации == Основные функции ОС - Планирование заданий и использование процессора - Обеспечение программ средствами коммуникации и синхронизации (межпроцессорные коммуникации) - Управление памятью - Управление файловой системой - Управление вводом-выводом - Обеспечение безопасности Дальше в курсе будем изучать, как эти функции выполняются по отдельности и совместно = Архитектурные особенности построения ОС == Внутреннее строение ОС - Монолитное ядро: - Каждая процедура может вызывать каждую - Все процедуры работают в привилегированном режиме - Ядро совпадает со всей операционной системой (вся ОС всегда сидит в оперативной памяти) - Точки входа в ядро --- системные вызовы - #table( columns: 2, table.header([*+*, *-*]), [ - Быстродействие ], [ - Нужно много памяти - Невозможность модификации без полной перекомпиляции ] ) - Многоуровневая (Layered) система: - Процедура уровня $K$ может вызывать только процедуры уровня $K - 1$ - [Почти] все уровни работают в привилигировнном режиме - Ядро [почти] совпадает со всей операционной системой - Точка входа --- верхний уровнеь - #table( columns: 2, table.header([*+*, *-*]), [ - Легкая отладка (при удачном проектировании) ], [ - Медленно - Нужно много памяти - Невозможность модификации без полной перекомпиляции ] ) - Микроядерная (microkernel) архитектура: - Функции микроядра: - взаимодействие между программами - планирование испльзования процессора - ... - Микроядро --- лишь малая часть ОС - Остальное --- отдельные программы-"менеджеры", раб в пользовательском режиме - Всё общение через микроядро - #table( columns: 2, table.header([*+*], [*-*]), [ - Только ядро --- "особенное" - Легче отлаживать и заменять компоненты ], [ - Ядро перезагружено --- bottleneck - Всё очень-очень медленно работает ] ) - Виртуальные машины - У каждого пользователя своя копия hardware - Пример: - Реальное hardware - Реальная ОС - Виртуальное hardware - Linux - Пользователь 1 - Виртуальное hardware - Windows 11 - Пользователь 1 - Виртуальное hardware - MS-DOS - Пользователь 1 - #table( columns: 2, table.header([*+*], [*-*]), [ - Удобно ], [ - Медленно из-за многоуровневости ] ) - Экзоядерная (новая микроядерная) архитектура: - Функции экзоядра: - взаимодействие между программами - выделение и высвобождение физических ресурсов - контроль прав доступа - Весь остальной функционал выкидывается в библиотеки Подходы *не* используются в чистом виде = Понятие процесса. Операции над процессами == Процесс Термины "программа" и "задание" были придуманы для статических объектов Для динамических объектов будем использовать "процесс" Процесс характеризует совокупность: - набора исполняющихся команд - ассоциированных с ним ресурсов - текущего момента его выполнения (контекст) Процесс $eq.not$ программа, которая исполняется тк: - одна программа может использовать несколько процессов - один процесс может использовать несколько программ - процесс может исполнять код, которого не было в программе == Состояние процесса // TODO: diagram состояние процесса Процесс сам состояния не меняет, его переводит ОС, совершая "операцию"
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Integral.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Integral", authors: ( "<NAME>", ), date: "10 Août, 2024", ) #set heading(numbering: "1.1.") = The Integral (AntiDerivative) <the-integral-antiderivative> == Definition <definition> Theorem: \ If F a antiderivative of f then F+C is the most general antiderivative Ex: \ $f (x) = c o s (x)$ \ $F (x) = s i n x + c$ \ Ex: \ $f (x) = x^n , n eq.not - 1$ \ Power Chain Rule : \ $F = frac(x^(n + 1), n + 1) + C$ \ Ex: \ n=-1 : $f (x) = 1 / x$ \ $F (x) = l n lr(|x|) + c$ == Links <links> - #link("http://www.lrcb.ch/litterature/integrales.pdf")[Identities] - #link("https://tutorial.math.lamar.edu/Classes/CalcII/IntTechIntro.aspx")[Techniques] - #link("https://tutorial.math.lamar.edu/Problems/CalcII/IntTechIntro.aspx")[Nice Exercices] - #link("Maths.pdf")[Maths]
https://github.com/adelhult/typst-hs-test-packages
https://raw.githubusercontent.com/adelhult/typst-hs-test-packages/main/test/counter-examples/spread_dict.typ
typst
MIT License
#let d = (a: true, b: false) #let nd = (: ..d)
https://github.com/cronokirby/paper-graphical-framework-for-cryptographic-games
https://raw.githubusercontent.com/cronokirby/paper-graphical-framework-for-cryptographic-games/main/model.typ
typst
#import "paper.typ" #import paper: theorem, lemma, claim, definition Hello? == Circuits #definition(title: "Pseudo-Category of Raw Circuits")[ The objects of $bold("RawCirc")$ are $NN$. The morphisms $bold("RawCirc")(m, n)$ are circuits with $m$ inputs and $n$ outputs, defined inductively, as one of: - $mono(0), mono(1), bot : 0 -> 1$, - $not : 1 -> 1$, - $and : 2 -> 1$, - $triangle.filled.small.l: 1 -> 2$, - $multimap : 1 -> 0$, - $arrows.tb : 2 -> 2$, - $f gt.tri g : m -> n$, given $f : m -> k, g : k -> n$, - $f times.circle g : m + m' -> n + n'$, given $f : m -> n, g : m' -> n'$. ] ? == Randomized Circuits == Efficient Randomized Circuits == Adversaries
https://github.com/francescoalemanno/gotypst
https://raw.githubusercontent.com/francescoalemanno/gotypst/main/README.md
markdown
Apache License 2.0
# gotypst [![Go Report Card](https://goreportcard.com/badge/github.com/francescoalemanno/gotypst)](https://goreportcard.com/report/github.com/francescoalemanno/gotypst) [![API Reference](https://img.shields.io/badge/docs-API_Reference-blue)](https://pkg.go.dev/github.com/francescoalemanno/gotypst) gotypst is a Go package that compiles Typst code into a PDF. It provides an easy-to-use function to pass Typst markup as bytes and receive the compiled PDF as bytes. This can be used to integrate Typst into Go projects, automate PDF generation, or add Typst support to your web services. Features - Convert Typst code into PDF on the fly - Flexible options for customization - Simple, minimal interface ## example ```go package main import ( "fmt" "github.com/francescoalemanno/gotypst" ) func main() { bts, err := gotypst.PDF([]byte("= hello")) if err!=nil { return } fmt.Println(bts) } ```
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/177.%20sun.html.typ
typst
sun.html General and Surprising September 2017The most valuable insights are both general and surprising. F = ma for example. But general and surprising is a hard combination to achieve. That territory tends to be picked clean, precisely because those insights are so valuable.Ordinarily, the best that people can do is one without the other: either surprising without being general (e.g. gossip), or general without being surprising (e.g. platitudes).Where things get interesting is the moderately valuable insights. You get those from small additions of whichever quality was missing. The more common case is a small addition of generality: a piece of gossip that's more than just gossip, because it teaches something interesting about the world. But another less common approach is to focus on the most general ideas and see if you can find something new to say about them. Because these start out so general, you only need a small delta of novelty to produce a useful insight.A small delta of novelty is all you'll be able to get most of the time. Which means if you take this route, your ideas will seem a lot like ones that already exist. Sometimes you'll find you've merely rediscovered an idea that did already exist. But don't be discouraged. Remember the huge multiplier that kicks in when you do manage to think of something even a little new.Corollary: the more general the ideas you're talking about, the less you should worry about repeating yourself. If you write enough, it's inevitable you will. Your brain is much the same from year to year and so are the stimuli that hit it. I feel slightly bad when I find I've said something close to what I've said before, as if I were plagiarizing myself. But rationally one shouldn't. You won't say something exactly the same way the second time, and that variation increases the chance you'll get that tiny but critical delta of novelty.And of course, ideas beget ideas. (That sounds familiar.) An idea with a small amount of novelty could lead to one with more. But only if you keep going. So it's doubly important not to let yourself be discouraged by people who say there's not much new about something you've discovered. "Not much new" is a real achievement when you're talking about the most general ideas. It's not true that there's nothing new under the sun. There are some domains where there's almost nothing new. But there's a big difference between nothing and almost nothing, when it's multiplied by the area under the sun. Thanks to <NAME>, <NAME>, and <NAME> for reading drafts of this.Japanese Translation
https://github.com/Seanwanq/Typst-Course-Report-Template
https://raw.githubusercontent.com/Seanwanq/Typst-Course-Report-Template/main/template.typ
typst
#let subfigure( body, pos: bottom + center, dx: 0%, dy: 0%, caption: "", numbering: "(a)", separator: "", lbl: none, supplement: none, ) = { let fig = figure( body, caption: none, kind: "subfigure", supplement: none, numbering: numbering, outlined: false, ) let number = locate( loc => { let fc = query(selector(figure).before(loc), loc).last().counter.display(numbering) return fc }, ) if caption != "" and separator == none { separator = ":" } caption = [#set text(12pt); #supplement #number#separator #caption] return [ #fig #lbl \ #place(pos, dx: dx, dy: dy, caption) ] } #let CodeFrame(lang: none, body) = { body place(right + top, dx: -0.3em, dy: 0.3em)[ #block( stroke: rgb("#B8B8B8") + 0.5pt, fill: rgb("#DEDADA8E"), radius: 3.3pt, inset: 0.1em, )[ #raw(lang) ] ] } #let FigureBlock(captionAlign: "l", body) = { show figure.caption: it => [ #if captionAlign == "l" [ #align(left)[ #v(0.5em) Figure #it.counter.display(it.numbering): #it.body #v(10pt) ] ] else if captionAlign == "c" [ #align(center)[ #v(0.5em) Figure #it.counter.display(it.numbering): #it.body #v(10pt) ] ] else if captionAlign == "r" [ #align(right)[ #v(0.5em) Figure #it.counter.display(it.numbering): #it.body #v(10pt) ] ] ] body } // For indent fixing. #let ForceParaBreak() = { par()[#text(size: 0.5em)[#h(0.0em)]] } #let MSTemplate( reportName: "", authorName: "", professor: "", date: "", courseName: "", IsComplexEquationNumberingOn: true, ShowProfessorName: true, body, ) = [ #set page(paper: "a4", header: locate(loc => { if counter(page).at(loc).first() > 1 [ _#courseName _ - #reportName #h(1fr) #counter(page).at(loc).first() \ #v(-5pt) #set line(stroke: 0.35pt) #line(length: 100%) ] }), footer: locate(loc => { if counter(page).at(loc).first() == 1 [ #align(center)[1] ] else [ #set line(stroke: 0.35pt) #line(length: 100%) #v(-5pt) #h(1fr) _#authorName _ ] })) #set text(size: 12pt, font: "New Computer Modern") #set par(justify: true, linebreaks: "optimized", first-line-indent: 1.5em) #set enum(numbering: "1.a.i.") // #show enum.where(tight: false): it => { // it.children // .enumerate() // .map(((n,item)) => block(below: 1.6em, above: 1.6em)[#h(1.5em)#numbering("1.", n + 1) #item.body]) // .join() // } #set list() // #show list.where(tight: false): it => { // it.children // .enumerate() // .map(((n,item)) => block(below: 1.6em, above: 1.6em)[#h(1.5em)• #h(.25em) #item.body]) // .join() // } #set heading(numbering: "1.1.1.") #set figure(numbering: "1.a") #set ref(supplement: it => { if it.func() == heading { "Sec." } else if it.func() == math.equation { "Eq." } else if it.func() == figure { "Fig." } }) #show heading.where(level: 1): it => block(width: 100%, breakable: false)[ #if IsComplexEquationNumberingOn == true [ #counter(math.equation).update(0) ] #set align(center) #set text(size: 12pt) #v(-5pt) \ #counter(heading).display("1"). #it.body \ #v(0.5em) ] #show math.equation:it => { if it.has("label") { if IsComplexEquationNumberingOn == true { math.equation(block: true, numbering: it => { locate(loc => { let count = counter(heading.where(level: 1)).at(loc).last() numbering("(1.1)", count, it) }) }, it) } else { math.equation(block: true, numbering: "(1.1)", it) } } else { it } } #show ref: it => { let el = it.element if el != none and el.func() == math.equation [ #link( el.location(), )[ #text( font: "New Computer Modern", size: 12pt, )[ Eq. #if IsComplexEquationNumberingOn == true [ #numbering( "(1.1)", counter(heading.where(level: 1)).at(el.location()).last(), counter(math.equation).at(el.location()).at(0) + 1, ) ] else [ #numbering("(1.1)", counter(math.equation).at(el.location()).at(0) + 1) ] ] ] ] else if el != none and el.func() == figure and el.kind == "subfigure" { locate( loc => { let q = query(figure.where(outlined: true).before(it.target), loc).last() ref(q.label) set ref(supplement: none) it }, ) } else if el != none and el.func() == figure and el.kind == "code" { set ref(supplement: "Listing") it } else if el != none and el.func() == figure and el.kind == table { set ref(supplement: "Table") it } else { it } } #show figure: it => { if it.kind != "subfigure" and it.kind != "code" { locate(loc => { let q = query(figure.where(kind: "subfigure").after(loc), loc) if q.len() != 0 { q.first().counter.update(0) } }) it } else if it.kind == "code" [ #it #par()[#text(size: 0.5em)[#h(0.0em)]] ] else { it } } #show figure.where(kind: table): set figure.caption(position: top) #show heading: it => { if it.level == 2 { text(size: 12pt)[ #par()[#text(size: 0.5em)[#h(0.0em)]] #v(0em) #h(-1.5em + 5pt) #counter(heading).display("1.1.") #it.body. ] } else if it.level > 2 { text(size: 12pt)[ #par()[#text(size: 0.5em)[#h(0.0em)]] #v(0em) #h(-1.5em + 5pt) #emph[#counter(heading).display("1.1.1.") #it.body.] ] } else { it } } #show par: it => [ #set block(above: 0.8em, below: 0.8em) #it ] #show link: set text(font: "Cascadia Code", size: 10pt) #show link: it => { if type(it.dest) == str { underline(it) } else { it } } #align(center)[ #block(breakable: true)[ #set line(stroke: 0.35pt) #smallcaps(text()[University of Utrecht]) \ #v(1pt) #line(length: 100%) #v(-2pt) #text(size: 21.5pt, weight: "semibold")[#reportName] \ #v(2pt) #text()[ Student name: _#authorName _ ] #v(-2pt) #line(length: 100%) #v(-3pt) #if ShowProfessorName == true [ Course: _#courseName _ - Professor: _#professor _ \ ] else [ Course: _#courseName _ \ ] Due date: _#date _ ] ] #body ]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/215.%20getideas.html.typ
typst
getideas.html How to Get New Ideas January 2023(Someone fed my essays into GPT to make something that could answer questions based on them, then asked it where good ideas come from. The answer was ok, but not what I would have said. This is what I would have said.)The way to get new ideas is to notice anomalies: what seems strange, or missing, or broken? You can see anomalies in everyday life (much of standup comedy is based on this), but the best place to look for them is at the frontiers of knowledge.Knowledge grows fractally. From a distance its edges look smooth, but when you learn enough to get close to one, you'll notice it's full of gaps. These gaps will seem obvious; it will seem inexplicable that no one has tried x or wondered about y. In the best case, exploring such gaps yields whole new fractal buds.
https://github.com/sses7757/sustech-graduated-thesis
https://raw.githubusercontent.com/sses7757/sustech-graduated-thesis/main/sustech-graduated-thesis/pages/acknowledgement.typ
typst
Apache License 2.0
// 致谢页 #let acknowledgement( // documentclass 传入参数 anonymous: false, twoside: false, // 其他参数 title: "致谢", outlined: true, body, ) = { if (not anonymous) { [ #heading(level: 1, numbering: none, outlined: outlined, title) #body ] } }
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/exercise/exercise.typ
typst
MIT License
#import "solutions.typ" #import "grading.typ" #import "../util/marks.typ" #import "../util/typst.typ" #import "../util/util.typ" #import "../core/document.typ" #import "../theme.typ" // ================================= // Validation schema // ================================= #import "../util/types.typ" as t #let _grading-schema = t.dictionary( (expectations: t.array()), default: (expectations: ()), ) #let _sub-exercise-schema = t.dictionary(( id: t.string(), number: t.integer(), grading: t.constant(_grading-schema), solutions: t.constant(t.array()), )) #let _exercise-schema = t.dictionary( ( id: t.string(optional: true), number: t.integer(), display-number: t.integer(optional: true), title: t.string(optional: true), icons: t.array(t.content(), default: (), pre-transform: t.coerce.array), use: t.boolean(default: true), header: t.boolean(default: true), pagebreak: t.boolean(default: false), label: t.label( optional: true, pre-transform: (_, it) => if it != none and type(it) == str { label(it) } else { it }, ), // grading: t.array( // optional: true, // pre-transform: (..) => (), // ), grading: t.constant(_grading-schema), solutions: t.constant(t.array()), sub-exercises: t.constant(t.array()), ), post-transform: (_, it) => { if it.id == none { it.id = "ex" + str(it.number) } if it.display-number == none and it.use { it.display-number = it.number } it }, aliases: ( "titel": "title", "no": "number", "nummer": "number", "nr": "number", "angezeigte-nummer": "display-number", "icon": "icons", "symbol": "icons", "symbole": "icons", "anzeigen": "use", "nutzen": "use", "ueberschrift": "header", "neue-seite": "pagebreak", ), ) // ================================= // States and counters // ================================= #let _counter-exercises = counter("schule.exercises") #let _state-exercises = state("schule.exercises", (:)) #let get-exercises(final: true) = { if final { return _state-exercises.final() } else { return _state-exercises.get() } } #let get-exercise(id, final: true) = { get-exercises(final: final).at(id, default: none) } #let get-current-exercise() = { let exercises = get-exercises(final: false) if exercises != (:) { return exercises.values().last() } else { return none } } #let get-current-sub-exercise() = { let exercises = get-exercises(final: false) if exercises != (:) { let ex = exercises.values().last() if ex.sub-exercises != () { return ex.sub-exercises.last() } } return none } #let update-exercises(update-func) = { _state-exercises.update(update-func) } #let update-exercise(id, func) = { update-exercises(exercises => { if id in exercises { exercises.at(id) = update-func(exercises.at(id)) } exercises }) } #let update-current-exercise(update-func) = { update-exercises(exercises => { if exercises != (:) { let id = exercises.keys().last() let ex = exercises.at(id) exercises.at(id) = update-func(ex) } exercises }) } #let update-sub-exercise(id, sub-ex, update-func) = { update-exercises(exercises => { if id in exercises { let ex = exercises.at(id) if ex.sub-exercises.len() >= sub-ex { ex.sub-exercises.at(sub-ex - 1) = update-func(ex.sub-exercises.at(sub-ex - 1)) } exercises.at(id) = ex } exercises }) } #let update-current-sub-exercise(update-func) = { update-exercises(exercises => { if exercises != (:) { let (id, ex) = exercises.pairs().last() if ex.sub-exercises != () { let sub-ex = ex.sub-exercises.pop() ex.sub-exercises.push(update-func(sub-ex)) } exercises.at(id) = ex } exercises }) } #let _get_next-exercise-number() = { query(selector(<exercise>).before(here())).len() + 1 } #let in-exercise() = marks.in-env("exercise") #let in-sub-exercise() = marks.in-env("sub-exercise") // ================================ // = Point utilities = // ================================ #let points-format-join(points, sep: [#h(.1em)+#h(.1em)], prefix: "(", suffix: ")") = { align( right, emph(prefix + points.map(str).join(sep) + suffix), ) } #let points-format-total(points, prefix: "(", suffix: ")") = { align(right, prefix + grading.display-points(points.sum()) + suffix) } #let points-format-margin(points) = { util.marginnote( position: top + right, gutter: .64em, block( stroke: .6pt + theme.muted, fill: theme.bg.muted, inset: .2em, radius: 10%, grading.display-points( points.sum(), singular: "P", plural: "P", ), ), ) } // ================================= // Content functions // ================================= // TODO: use points format function ? #let exercise( ..args, body, ) = { _counter-exercises.step() context { let ex-data = args.named() ex-data.insert( "number", _counter-exercises.get().first(), ) ex-data = t.parse( ex-data, _exercise-schema, ) if ex-data.use { ex-data.display-number = _get_next-exercise-number() } if ex-data.use { marks.place-meta(<exercise>, data: ex-data) update-exercises(exercises => { exercises.insert(ex-data.id, ex-data) exercises }) let ic = [] if ex-data.icons != () { ic = util.marginnote( offset: .2em, text(size: .88em, theme.secondary, (ex-data.icons,).flatten().join()), ) } if ex-data.pagebreak { pagebreak() } heading(level: 2)[ // Icons #ic // Numbering Aufgabe #numbering("1", ex-data.display-number) // Title #if ex-data.title != none [ #h(1.28em) #text(theme.text.default, ex-data.title) ] // Points #h(1fr) #text( theme.secondary, .88em, context { grading.display-total(get-exercise(ex-data.id)) }, ) ] if ex-data.label != auto { marks.place-reference( ex-data.label, "exercise", "Aufgabe", ) } else { marks.place-reference( label("ex" + str(ex-data.display-number)), "exercise", "Aufgabe", ) } marks.env-open("exercise") body marks.env-close("exercise") document.use-value( "solutions", opt => { if opt == "after" { solutions.display-solutions-block(get-current-exercise()) } }, ) } } } #let sub-exercise( use: true, points-format: points => none, ..args, body, ) = { if use { _counter-exercises.step(level: 2) marks.env-open("sub-exercise") context { let no = _counter-exercises.get().at(1) update-current-exercise(ex => { let sub-ex = t.parse( ( id: ex.id + "-" + str(no), number: no, display-number: numbering("a)", no), solutions: (), ), _sub-exercise-schema, ) ex.sub-exercises.push(sub-ex) ex }) } _counter-exercises.display((ex-no, sub-ex-no, ..) => { enum( numbering: "a)", start: sub-ex-no, tight: false, spacing: auto, { marks.place-reference( label("ex" + str(ex-no) + "." + str(sub-ex-no)), "sub-exercise", "Teilaufgabe", numbering: "1.a", ) [#body<sub-exercise>] }, ) }) marks.env-close("sub-exercise") context grading.display-points-list(get-current-sub-exercise(), format: points-format) } } #let _counter-tasks = counter("schule.tasks") /// Horizontal angeordnete Aufzählungsliste (z.B. für Unteraufgaben). /// #example[``` /// #tasks[ /// + Eins /// + Zwei /// + Drei /// + Vier /// + Fünf /// ] /// #tasks(cols: 4, numbering:"(a)")[ /// + Eins /// + Zwei /// + Drei /// + Vier /// + Fünf /// ] /// ```] /// /// - cols (int): Anzahl Spalten. /// - gutter (length): Abstand zwischen zwei Spalten. /// - numbering (string): Nummernformat für die Einträge. /// - aub-numbering (string): Nummernformat für die Einträge in Teilaufgaben. /// - body (content): Inhalt mit einer Aufzählungsliste. /// -> content #let tasks( cols: 3, gutter: 4%, width: 1fr, numbering: "a)", sub-numbering: "(1)", body, ) = { _counter-tasks.update(0) grid( columns: (width,) * cols, gutter: gutter, ..body.children.filter(c => c.func() in (enum.item, list.item)).map(it => { _counter-tasks.step() context if in-sub-exercise() { _counter-tasks.display(sub-numbering) } else { _counter-tasks.display(numbering) } h(.5em) it.body }), ) } #let solution(body) = { context { if in-sub-exercise() { update-current-sub-exercise(sub-ex => { sub-ex.solutions.push(body) sub-ex }) } else { update-current-exercise(ex => { ex.solutions.push(body) ex }) } } document.use-value( "solutions", opt => { if opt == "here" { solutions.display-solution(body) } }, ) } #let expectation(text, points) = { context { if in-sub-exercise() { update-current-sub-exercise(sub-ex => { sub-ex.grading.expectations.push(( text: text, points: points, )) sub-ex }) } else { update-current-exercise(ex => { ex.grading.expectations.push(( text: text, points: points, )) ex }) } } }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/control-flow-for-content.typ
typst
Apache License 2.0
#for i #for i in #for i in range(1) #for i in range(1) [] #for i in [] #for i in []; 1 #for i in range(1) []; 1 #for i in range(1) []1 #for i in range(1) []a #for i in range(1) [] 1 #for i in range(1) [] a #for i in range(1) [] #for i in range(1) []; [] #for i in range(1) [] [] 1
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/031%20-%20Hour%20of%20Devastation/003_Hour%20of%20Glory.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Hour of Glory", set_name: "Hour of Devastation", story_date: datetime(day: 21, month: 06, year: 2017), author: "<NAME>", doc ) #emph["And as the Luxa, the lifeblood of Naktamun, turned to the foul blood of the great shadow Razaketh, the Hours turned to that of Glory—the promised time when the gods themselves would prove their worth before the God-Pharaoh."] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[In the beginning, there was nothing but darkness: a churning ocean of uncertainty.] #emph[Then the great God-Pharaoh awoke and rose, a shining golden sun, and shed light upon the unformed world. With the unfurling of his wings, he split sky from earth; with his first breath, he formed water and air; with a sweep of his tail, he carved mountains and crumbled stone into sand. And thus, the God-Pharaoh sifted order from chaos, and the world took shape, raw and young and new.] #emph[The God-Pharaoh then gazed upon the barren, quiet world and planted the seeds of life. And so the denizens of Amonkhet were born, birthed from the dreams of the dragon-creator. But unlike their creator, they were soft, vulnerable, frail—and mortal. And the shadows of the world, the remnants of that black ocean, seized those that died, twisting them into undeath, a threat and plague to the living.] #emph[And so the great God-Pharaoh forged the gods.] #emph[He drew upon the fabric of the world itself, weaving the mana of Amonkhet into five forms, each to embody a virtue of himself. And thus, the immortals of Amonkhet came into being. Born of the God-Pharaoh's will and stronger than his dream-children, the gods were tasked with protecting his mortal flocks from the whims of shadow, shepherding them toward a glorious death instead.] #emph[For the God-Pharaoh knew of a realm beyond this world. A place only reachable by passing through death. And though he knew the hardships of this world were many, and shadows gripped at the edges of all that dwelled there. He knew that his children could prevail, grow, learn, and become worthy. For the afterlife was a gift too precious to be given lightly; his children needed to prove themselves deserving of its glory.] #emph[And so the God-Pharaoh gifted his children the Trials. And each god was honored with the task of teaching, training, and leading the mortals on the path to life eternal.] #emph[And once all was in place, the God-Pharaoh left Naktamun to pave the way to eternity, giving time for his children to learn, strive, and achieve their destinies before joining him in the great afterlife. He left his children in the care of his gods and set the second sun in motion to mark the time of his return.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("003_Hour of Glory/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) All this Rhonas knew to be true. It rang with certainty through the very fiber of his being, as interwoven a part of him as the leylines of mana that tied him to the world. It ran through the bodies of his brethren, each god-sibling tangible proof of the God-Pharaoh's benevolence and divinity. He knew his part in the God-Pharaoh's plan. Thus, for years he challenged the mortals in his care, helping the denizens of Naktamun hone their bodies and seize true strength, all in the visage of himself and his God-Pharaoh. And so, when the second sun finally came to rest between the horns as prophesied, Rhonas rejoiced, emerging from his temple and his Trial. And he came to stand before the Gate to the Afterlife to welcome their creator, the progenitor of all things, the God-Pharaoh returned. What he found, however, was not what he expected. As he joined his sister Hazoret at the banks of the Luxa, Rhonas felt an uncharacteristic chill permeate his scales. Demonic magic clung heavy in the air, humid and thick, while the copper smell of blood saturated all. Rhonas gazed at the water turned red, then toward the other gods as they arrived. Oketra, fleet of foot, came to stand next to Hazoret. Kefnet, ever proud, floated down and landed beside Rhonas, while Bontu strode up, quiet and aloof. The five stood before the crimson shores of the Luxa, basked in the mirrored crimson light of the second sun. #figure(image("003_Hour of Glory/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) It had been many years since all five had gathered in one place. Each god served a purpose in the God-Pharaoh's grand design, guiding mortals through their own Trials, watching over the city in their own way. Rhonas had worked the closest with Hazoret, the two striking out into the desert on occasion to hunt down any great threat that strayed too close to the city. He had not stood in the presence of the others in some time. Yet here they were now, all five standing before the gate. At their feet, many mortals bowed their heads in deference or gazed up in awe, bathed for the first time in the presence of all five divinities at once. And still, the God-Pharaoh did not arrive. Rhonas's tongue flicked out, sampling the air, searching for some sign—mundane or magical. The promised Hour of Revelation had come and gone, but no answers had been revealed. Whatever spell the now-absent demon had unleashed still wound through the air, its effects churning and unresolved, and Rhonas brought his staff to bear, his instincts whispering of danger. #strong[Look. The Luxa. ] Hazoret's voice reverberated in his mind, and Rhonas's gaze shifted to the river. The blood, coagulating at standstill just moments ago, had resumed its flow through the gate, rushing with increasing speed as it coursed beyond. In the past, Rhonas had seen the Gate to the Afterlife crack open as part of the daily passage of worthy dead to the beyond. This, however, was the first time he had witnessed it's doors thrown wide. Yet he saw no sign of the promised paradise beyond the open portal—only the Necropolis, large and imposing, housing all the dead awaiting the God-Pharaoh's return. Within moments, all that remained of the mighty Luxa was a few rivulets of red, coagulating droplets of blood clinging to stones at the bottom of the riverbed. The acrid bite of the demonic spell reverberated through Rhonas's very being, and he sensed old magics unraveling and unbinding. As the magical pressure in the air grew thick and almost unbearable, the blood of the river seemed to seep #emph[into] the stone foundation of the Necropolis, running up the grooves and markings on the statues lining the sides of the building. A blast of fetid air burst from the monolithic structure, and a sudden crack rang out. Rhonas watched as three of the massive statues—no, #emph[sarcophagi] —along the side of the building cracked open, their stone facades crumbling in a cloud of dust. A blue light flashed, and three enormous figures stepped forward from their slumber, awakened by the demon's spell. #figure(image("003_Hour of Glory/03.jpg", width: 100%), caption: [Art by Grzegorz Rutowski], supplement: none, numbering: none) A wave of cries and shouts rippled from the mortals assembled at the gods' feet, while the gods recoiled at the sight and the #emph[presence] of the towering figures. The three stood taller even than the gods themselves, their humanoid bodies ending with monstrous heads bearing the shapes of insects—one a scorpion; one a creature with a spindly, locust-like form; and one with the azure carapace of a scarab where its face should have been. #figure(image("003_Hour of Glory/04.jpg", width: 100%), caption: [Art by Grzegorz Rutkowski], supplement: none, numbering: none) There was no question in Rhonas's mind: these three were immortals. Whereas the presence of his siblings glowed like a warm flame, these gods emanated shadow, a heavy weight of darkness and despair that washed over all present, mortal and god alike. #figure(image("003_Hour of Glory/05.jpg", width: 100%), caption: [Art by Grzegorz Rutkowski], supplement: none, numbering: none) For the first time in his existence, Rhonas felt unsure. Nothing in the prophecies, nothing in his memories of the God-Pharaoh spoke of these three. The mortals at his feet murmured, and a few let out panicked screams as the scorpion god lumbered through the gate, its massive strides sending tremors rumbling through the ground. To his right, Hazoret took a step forward, spear at the ready, but Rhonas held out his staff to stay her fervor. #emph[Is this a foe, or a test?] "#strong[I am Rhonas, God of Strength. Who are you, and why have you awakened during this Hour of Glory?] " Rhonas's voice boomed. The scorpion god did not respond, but turned its insectoid head toward Rhonas. Upon closer examination, the god appeared even more grotesque than Rhonas had initially thought. Its body was a coil of sinew and muscle coated by dark exoskeleton, with hands that ended in sharp claws. Its head looked like a massive scorpion #emph[perched ] on the humanoid body, its hardened carapace gilded and adorned with blue orbs that Rhonas could only assume were its eyes. #figure(image("003_Hour of Glory/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) The immortal seemed to regard Rhonas. No words came forth from its mandibles, but a low chittering noise started and grew in volume. Rhonas gripped his staff tighter as the scorpion tail arched over the god's head. A wave of panic rippled through the mortals at Rhonas's feet, and he felt a rush of their prayers and supplication. Rhonas pointed his staff toward the scorpion god, matching the display of aggression with one of his own. "#strong[Whether you are a harbinger of our God-Pharaoh's return or an interloper conspiring against the Hours, you shall proceed no further.] " The scorpion god took another earth-shaking step forward. Rhonas shifted his grip on his staff as his feet moved into a practiced, centered stance. Around him, his brothers and sisters stood at the ready, bodies tense, eyes on Rhonas. Rhonas's tongue again flicked out into the air. "#strong[You shall not defy a god of Amonkhet. We stand guard over this city and its people. If you are my Trial, then I will defeat you and prove myself worthy!] " Without warning, the scorpion god charged toward Rhonas, its chittering spiking in volume. Sand flew as the immortal moved with surprising speed, scorpion tail tensed. It dashed into striking distance, clawed hands swiping at Rhonas. But Rhonas was ready, sidestepping the charging god and striking at it with his staff. The metal smashed against the other god's back, a resounding strike against its carapace that would have reduced lesser beings to dust. The immortal seemed to shrug off the assault as it spun around, mandibles clacking and tail twitching in anticipation. It sprang at Rhonas again, claws raking at his eyes. Rhonas raised his staff to parry, and the scorpion god's claws clanged against the metal of his weapon. Rhonas felt his knees bend and his feet break the earth beneath him under the force of the blow. Rhonas struggled, pushing up against the larger god. Fighting something bigger than himself was unusual, but not wholly new. The deserts hid sandwurms, monstrosities, and far more terrifying beasts, and he had occasionally tussled with a foe whose stature exceeded his own. But fighting something #emph[stronger ] than him? Than the God of Strength? Rhonas shouted in fury and #emph[pushed] , muscles screaming as he shoved the scorpion god back. The ground shook with each of its steps as it stumbled. Rhonas took advantage of its loss of balance, drawing mana and channeling a spell of vigor. Power coursed through his limbs and he swung at the scorpion god with all his might. His blow caught it in the chest, and the immortal went flying across the expanse, landing with a crash just beyond the gate. Rhonas heard the mortals cheer and shout praises behind him as the scorpion god slowly clambered to its feet. Rhonas's stoic face hid from the rejoicing mortals the growing dread in his heart. #emph[That spell never failed to end a fight before.] The scorpion god again crossed the threshold of the gate. This time, it did not charge. Instead, it cut a sweeping path, keeping its distance but stalking and circling closer to Rhonas. The chittering never ceased, droning at a mind-numbing volume and frequency. Rhonas tried to block it out, countering with an incantation he muttered low under his breath. This scorpion god was clearly a Trial of the Hour of Glory. It had to be. Nothing else had challenged Rhonas's strength like this before. Nothing had sustained his attacks and lived. Rhonas's eyes flickered to the two looming shapes still beyond the gate. #emph[Perhaps those gods would test the others in different ways] . After all, the gods could not prove their worth if they were not also faced, as the mortals were, with struggles beyond what they had ever encountered before. A smile crept across his face as he continued his incantation. #emph[Blessed be the strength and wisdom of the God-Pharaoh, ] he thought. #emph[It is an honor to prove my worth against such a formidable foe.] Rhonas touched his staff, uttering the final words of his incantation. A sickly green glow pulsed, seeming to come from #emph[within ] the metal. It shimmered across the length of the staff, then coalesced in the bladed end of the weapon, settling into a soft viridian light. Rhonas began to walk, a counter circle to the scorpion god's sweeping path. "#strong[You are indeed strong] ," Rhonas said. "#strong[But you shall not triumph today.] " This time, Rhonas charged in, dashing toward the scorpion god with serpentine speed. He parried a strike from the scorpion tail, then spun close and landed a blow with his elbow, catching the scorpion god in the ribs. His staff left streaking trails of green light as he swung, striking fast instead of hard, testing the strength of the scorpion god's carapace, leaving slashing cuts and scratches on the impossibly hard shell, deflecting and dodging the scorpion god's strikes. As the two brawled, the scorpion god's movements seemed to slow. The strikes from its claws and tail became sluggish. Too late, it looked at Rhonas's staff with dawning recognition. Rhonas grinned and bared his fangs as he drove the blade end of his staff into the immortal's shoulder, cracking the carapace just enough, the scorpion god now too slow to stop or dodge the assault. The biting glow of magical poison, venom powerful enough to slay most living things, pulsed as it seeped in through the wound, numbing and eating away at the scorpion god from the inside. Rhonas pulled his staff back, and the scorpion god fell to its knees, still chittering weakly. The roar of the people reverberated in his ears and he felt a rush of relief and warmth from his fellow gods. Rhonas regarded the monstrosity brought low, then turned back toward his brothers and sisters and the gathered mortals. He opened his mouth to speak. #figure(image("003_Hour of Glory/07.jpg", width: 100%), caption: [Rhonas the Indomitable | Art by Chase Stone], supplement: none, numbering: none) The words never made it past his throat. A sudden rush of motion behind him caught Rhonas by surprise. Sharp claws dug into his arms, and he barely registered that the scorpion god had grappled him from behind before an impossible pain split through his mind. #figure(image("003_Hour of Glory/08.png", height: 40%), caption: [], supplement: none, numbering: none) #emph[Time halted.] #emph[Rhonas looked down, surprised to see ] himself#emph[ standing on the banks of the Luxa. Behind him, the scorpion god loomed, a dark shape that somehow exuded and ] glowed #emph[darkness, claws gripping Rhonas's body.] #emph[That was when Rhonas saw the scorpion tail, arched over the god, piercing his own skull.] #strong[I . . . am slain.] #emph[The realization crept through him even as he felt the ichor of the scorpion god's sting drip down his spine, seeping into his mind and soul, severing his physical ties to his divinity and corroding the magic that connected his body to his immortality. Rhonas watched, seized by horror and fascination, as death consumed him. He felt the poison gnaw at his heart and fray the knot of leylines and magic and physical strength that resided in his core.] #emph[Yet as the poison destroyed the links anchoring him to the world, it also unbound the magical threads placed there by another force.] #emph[And Rhonas suddenly remembered the truth.] #emph[The memories began as a trickle, then flooded through him as the tangled dam of magic unraveled. And Rhonas's very spirit recoiled as the true events and nature of the God-Pharaoh revealed itself, a crushing tidal wave sweeping away everything he had believed for the past sixty years.] #emph[The great lie of the God-Pharaoh. The dragon, not a creator but a merciless destroyer. The great trespasser, slayer of mortals and corrupter of gods. The cruel inversion of the world's most sacred rite, the twisting of a glorious honor into a constant churn and murder of mortal champions. The sudden remembrance that gods were not crafted in the dragon's image; they were born of Amonkhet, originally eight in number, pillars of the plane and guardians of the living. And the great pretender corrupted it all.] #emph[Rhonas wept.] #emph[And as he wept, his tears turned from heartbreak to rage, and Rhonas spat the foul name, his dying heart filled with fury and pain.] #strong[<NAME>.] #emph[As darkness crept in on the edges of his vision and he felt the last ties of his spirit to his physical form disintegrate, Rhonas looked upon the gruesome visage of the god behind him. And though his bodily eyes already filmed over with a milky white, he ] saw#emph[ the god's true nature—the tiniest flickers of flame in its heart, surrounded by utter darkness, the original light and soul of his brother buried beneath vile corruption. This god was once one of the original eight, corrupted and repurposed to become a slayer of the very siblings he once held most dear.] #emph["Brother,"] #emph[Rhonas whispered.] #emph[Rhonas felt the scorpion's stinger retract, felt his muscles spasm and tense, felt the quickening approach of death. And his heart broke: for his three lost siblings, for the mortals who perished, for those he guided in supplication to a foul falsehood.] #emph[And the Strength of the World faded, his immortal light sputtering in the consuming shadows.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The assembled gods and mortals cried out in anguish as the scorpion tail pierced Rhonas's head. That sliver of time, but a blink and a breath, seemed to stretch across eternity, the frozen image of the barbed tail buried deep in Rhonas's skull burned into the souls of all present. Then the abomination god retracted its tail, and black ichor spilled forth as Rhonas stumbled and fell to the earth, body convulsing, then lay still. The scorpion god, with nary a pause or even a look, turned toward the other gods and walked forward, tail arced high. All bedlam erupted. Mortals screamed as they turned and fled. The other gods scrambled for their weapons as the scorpion god marched toward them, relentless, unstoppable. That's when the four gods felt a #emph[lurch] in the world, a pull on the very fabric of their beings. Behind the scorpion god, Rhonas clung to his staff, leaning on it to struggle upright, bent on his knees and bleeding from the wound in his skull. Verdant energy rippled across his body and channeled into his staff. With the last of his strength, Rhonas pulled taut the remaining leylines that wove throughout his being, warping the very air around him. An anguished final shout tore ragged from his throat. "#strong[Death to the God-Pharaoh, foul trespasser and destroyer!] " With a guttural cry and final exertion, Rhonas launched his staff through the air, pushing the last of his power into the weapon. #figure(image("003_Hour of Glory/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) As Rhonas collapsed, his life extinguished, the invisible strands of leylines and mana tied to him snapped, sending ripples of force blasting out across all life in Naktamun. Mortals doubled over in shock as the god perished, and even the other gods stumbled and recoiled where they stood. They watched as Rhonas's staff, carrying the final vestiges of their brother's power, flew through the air, his final spell transforming the weapon into a living monstrous serpent, fangs bared and laced with death as it struck at the scorpion god. The scorpion god fell to the ground, ensnared by the serpent. The god's tail swung wildly, trying to stab the snake as the two wrestled for control. The four gods stared, stunned into stillness. Around them, the cries of fear and panic swelled as mortals continued to flee from the gate. The cry of her children shook Oketra from her shock. She turned to her siblings, tears welling in her eyes, her voice rough and uncertain as her usual grace evaporated. "#strong[The Hours have gone awry. We must protect the mortals.] " Her words stirred her siblings into motion. Hazoret turned toward Oketra, brows crinkled in confusion. "#strong[Rhonas. He said . . . he blasphemed our God-Pharaoh."] Oketra nodded. She too had heard Rhonas's final words, and though they could not possibly be true, doubt nibbled at the edges of her heart even as faint fragments of thoughts flitted just at the periphery of her memory. A growing buzz pulled her attention back beyond the gate. The second of the insect gods had spread its arms, and a swarm of locusts poured forth from its hands. Oketra watched in horror as the dark cloud flooded into the sky and across the Hekma—and began eating through the magical barrier. #figure(image("003_Hour of Glory/10.jpg", width: 100%), caption: [Art by Daniel Ljunggren], supplement: none, numbering: none) "#strong[What is it doing?!] " Kefnet cried out. A shiver of realization and recognition ran down Oketra's spine as she remembered the words of prophecy. #emph[And at that time,] #emph[the God-Pharaoh will tear down the Hekma.] Oketra spoke, her voice a muted whisper. "#strong[The Hour of Promise has begun.] " A horrific rending sound erupted before them. The scorpion god stood from the ground, two halves of the giant snake held in each hand. Slowly, it opened its claws and let the pieces fall to the ground. Its azure eyes stared cold and piercing at the gods, and it again resumed its ceaseless approach. Oketra notched an arrow to her bow, mouth drawn in a steely line, her broken heart hardening with sharp resolve. And the scorpion god stalked closer, while behind it, the other two gods crossed the threshold of the gate into the city of Naktamun. Above them all, between the great horns in the distance, the second sun cast its red glow across the land, a ceaseless eye watching the unfolding of the Hours.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/element_where.typ
typst
Apache License 2.0
// contains: caption #figure.where(/* range 0..1 */)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/transform_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test setting rotation origin. #rotate(10deg, origin: top + left, image("/assets/files/tiger.jpg", width: 50%) )
https://github.com/matchy233/typst-chi-cv-template
https://raw.githubusercontent.com/matchy233/typst-chi-cv-template/main/src/lib.typ
typst
MIT License
/* * Package entry point */ #import "./chicv.typ": *
https://github.com/AlvaroRamirez01/Analisis_de_Algoritmos_2024-1
https://raw.githubusercontent.com/AlvaroRamirez01/Analisis_de_Algoritmos_2024-1/master/Tarea_03_Justificacion_de_Algoritmos/main.typ
typst
#import "conf.typ": * #import "@preview/algorithmic:0.1.0" #import algorithmic: * #show: doc => conf( materia: "Análisis de Algoritmos", tarea: "Tarea 03: Justificación de algoritmos", profesor: ( nombre: "<NAME>", sexo: "F", ), ayudantes: ( "<NAME>", "<NAME>" ), alumnos: ( ( nombre: "<NAME>", cuenta: "316276355", email: "<EMAIL>" ), ), fecha: datetime.today(), encabezado: "Problema a desarrollar", doc, ) #let colors = (black, gray, silver, white, navy, blue, aqua, teal, eastern, purple, fuchsia, maroon, red, orange, yellow, olive, green, lime) #text(11pt)[ #par(justify: true)[ #set enum(numbering: "a)") = Problema 1 Considerar los siguientes problemas: - Problema $alpha$: Calcular el producto de los elementos en el arreglo de números enteros $A[a..b]$. - Problema $beta$: Calcular la suma de los primeros n múltiplos de 3. - Problema $gamma$: Calcular la suma de los números impares en el arreglo de números enteros $A[a..b]$. Elegir *dos* de los problemas anteriores, α o β o γ y ... + Proporcionar un algoritmo recursivo (código) que solucione el problema, indicando PreCondiciones y PostCondiciones + Demostrar que el algoritmo propuesto es correcto usando inducción matemática. + Calcular el tiempo de ejecución del algoritmo dado. #solucion(color:blue)[ *Problema $alpha$* *a) Proporcionar un algoritmo recursivo (código) que solucione el problema, indicando PreCondiciones y PostCondiciones* *Precondicion:* El arreglo no debe ser null y debe tener al menos un elemento. ```haskell productoElementos :: [Int] -> Int productoElementos [x] = x -- Caso base, cuando el arreglo tiene un elemento productoElementos (x:xs) = x * productoElementos xs -- Parte recursiva ``` *Postcondicion:* El resultado es el producto de todos los elementos del arreglo, el arreglo sigue siendo no null. *b) Demostrar que el algoritmo propuesto es correcto usando inducción matemática.* *Demostración* *Por Demostrar:* La función productoElementos devuelve el producto de todos los elementos de la lista $x\s$ para cualquier lista no vacía $x\s$. *Caso base:* Cuando $x\s$ es una lista con un solo elemento. En este caso, al ser un único elemento en la lista, se cumple que el producto de todos los elementos de la lista es el elemento mismo, entonces se regresa el elemento. *Hipótesis de inducción:* Supongamos que la función productoElementos devuelve el producto de todos los elementos de la lista $x\s$ de longitud k. *Paso inductivo:* Ahora demostraremos que la función productoElementos devuelve el producto de todos los elementos de la lista $y\s$ de longitud k+1. La función productoElementos ys podemos verla como una función que tiene un arreglo de tamaño $k+1$ y se representa de la siguiente forma $[y_1, y_2, y_3, ...,y_k,y_(k+1)]$, asi mismo, podemos expresarla de la siguiente forma $[y_1, y_2, y_3, ...,y_k] ++ [y_(k+1)]$. Una vez expresada de esta forma, podemos ver que la función productoElementos $[y_1, y_2, y_3, ...,y_k]$ es equivalente a la función productoElementos $x\s$ de longitud k, por lo que podemos aplicar la hipótesis de inducción y sabemos que la función productoElementos $[y_1, y_2, y_3, ...,y_k]$ devuelve el producto de todos los elementos de la lista $y\s$ de longitud k. Nos queda el otro extremo donde esta el elemento $y_(k+1)$, cuando se le pasa como argumento a la función _productoElementos [$y_(k+1)$]_ podemos ver que se le esta pasando un único elemento, entonces caen en nuestro caso base y esto nos devuelve el mismo elemento. Entonces podemos multiplicar los resultados generados por las funciones _productoElementos [$y_(k+1)$]_ y _productoElementos [$y_1, y_2, y_3, ...,y_k]$_ y obtenemos el producto de todos los elementos de la lista $y\s$ de longitud k+1, los cuales se expresarían de la siguiente forma. #align(center)[ productoElementos $y\s = (y_1 * y_2 * ... * y_k) * y_(k+1)$ ] Por lo tanto, hemos demostrado por inducción matemática que el código es correcto, ya que cumple con la hipótesis inductiva para todas las listas no vacías. *c) Calcular el tiempo de ejecución del algoritmo dado.* El tiempo de ejecución del código que calcula el producto de todos los elementos de una lista utilizando recursion depende de la longitud de la lista. En este caso, la función _productoElementos_ se implementa de manera recursiva, y la cantidad de operaciones realizadas es directamente proporcional al tamaño de la lista. Cada llamada recursiva reduce la longitud de la lista en 1. Por lo tanto, si tienes una lista de longitud $n$, la función realizará $n - 1$ llamadas recursivas. Cada llamada implica una multiplicación y una operación de acceso a la lista, lo que significa que en total se realizarán aproximadamente $2 * (n - 1)$ operaciones aritméticas y de acceso a la lista. Entonces, *la complejidad de tiempo para este código es $O(n)$*, donde $n$ es la longitud de la lista. Esto significa que el tiempo de ejecución aumenta linealmente con el tamaño de la lista. *Problema $beta$* *a) Proporcionar un algoritmo recursivo (código) que solucione el problema, indicando PreCondiciones y PostCondiciones* *Precondicion:* $n$ debe de ser mayor o igual a 1 y el resultado de la operación debe ser mayor o igual a 3. ```haskell sumaPrimerosN :: Int -> Int sumaPrimerosN 1 = 3 -- Caso base, cuando n es igual a 1 sumaPrimerosN n = n * 3 + sumaPrimerosN (n - 1) -- Parte recursiva ``` *Postcondicion:* El resultado es la suma de los primeros $n$ múltiplos de 3 y el resultado sigue siendo mayor o igual a 3. *b) Demostrar que el algoritmo propuesto es correcto usando inducción matemática.* *Demostración* *Por Demostrar:* La función _sumaPrimerosN_ devuelve la suma de los primeros $n$ múltiplos de 3 para cualquier número $n$ mayor o igual a 1. *Caso Base:* Cuando $n=1$. Para el caso base, consideramos $n=1$. La función _sumaPrimerosN 1_ debe devolver 3, lo cual es correcto según la definición de la función y porque 3 es el primer numero múltiplo de 3. Por lo tanto, el código cumple con la base de inducción. *Hipótesis de inducción:* Suponemos que la función _sumaPrimerosN_ devuelve la suma de los primeros $n$ múltiplos de 3 para cualquier número $n$ mayor o igual a 1. *Paso inductivo:* Ahora demostraremos para $n+1$. Ahora, queremos demostrar que la hipótesis inductiva también es válida para $n+1$. Cuando el código se le pasa como parámetros $n+1$, en la primera iteración tenemos la siguiente operación: `(n+1)*3 + sumaPrimerosN n` Por hipótesis de inducción sabemos que para el caso _sumaPrimerosN n_ se cumple, ya que en esa segunda llamada recursiva $n$ se esta multiplicando por 3 y esto hace que el resultado de esa operación siga cumpliendo que es un múltiplo de 3, asi seguimos hasta llegar al caso base donde también se cumple esta propiedad. Entonces el resultado que nos queda es: `(n+1)*3 + n*3 + (n-1)*3+ ... + 3` Como podemos observar, el código cumple con el paso inductivo y la hipótesis, por lo tanto la función _sumaPrimerosN_ devuelve la suma de los primeros $n$ múltiplos de 3 para cualquier número $n$ mayor o igual a 1. *c) Calcular el tiempo de ejecución del algoritmo dado.* La función `sumaPrimerosN` se implementa de manera recursiva y realiza llamadas recursivas hasta que `n` llega a 1. En cada ciclo se realiza la multiplicación del parámetro n por 3 y se hace la llamada recursiva con un elemento menos como parámetro. Por lo tanto, el tiempo de ejecución sería proporcional a `n`. *El tiempo de ejecución sería O(n)*. ] = Problema 2 Considera los siguientes problemas: + Problema Evaluación de Polinomios. El Algoritmo Horner evalúa, en el punto x = xo, el polinomio $P_n (x)=a_0 + a_1 x + a_2 x^2 + ... + a_n x^n$ + Problema Búsqueda Binaria. Dado un arreglo de enteros $A[a..b]$, ordenado en forma ascendente, determinar si el elemento x ∈ A e indicar la posición donde se encuentra, si está. Dados los códigos para los problemas de A y B, mostrados abajo, demostrar usando la Técnica del Invariante del ciclo, que los algoritmos (códigos) son correctos. ` Procedure H (A:Array of integers ; x0: Integer) var i, total : Integer; total ← 0 ; for i = n - 1 to 0 by -1 do total ← A[i] + total * x0; Return total end Horner ` // #algorithm({ // import algorithmic: * // Function("Binary-Search", args: ("A", "n", "v"), { // Cmt[Initialize the search range] // Assign[$l$][$1$] // Assign[$r$][$n$] // State[] // While(cond: $l <= r$, { // Assign([mid], FnI[floor][$(l + r)/2$]) // If(cond: $A ["mid"] < v$, { // Assign[$l$][$m + 1$] // }) // ElsIf(cond: [$A ["mid"] > v$], { // Assign[$r$][$m - 1$] // }) // Else({ // Return[$m$] // }) // }) // Return[*null*] // }) // }) ` BinarySearch(var A:Atype; a,b:integer; x:keytype; var pos:integer):boolean // PreCondicion: a<=b+1 and A[a]<=...<=A[b] var i,j,mid:integer; found: boolean; begin i=a; j=b; found=false; while ( (i!=j+1) and (not found) ) do mid=(i+j) div 2; if (x = A[mid]) then found=true; elseif (x < A[mid]) then j=mid-1; else i=mid+1; end_if; end_while; if found then pos=mid; else pos=j; end_if; return found; end BinarySearch // PostC: (found implica: a<=pos<=b and A[pos] = x) and (not found implica: a-1 <= pos <= b and (for all k a<=k<=pos, A[k]<x) and (for all f pos+1<=k<=b, x<A[k])) ` #solucion(color:green)[ *a) Problema Evaluación de Polinomios (Algoritmo Horner).* Para realizar una demostración por invariante de ciclo vamos a necesitar definir una invariante de ciclo y verificar como es su funcionamiento o alteración en 3 etapas del código: inicializacion, mantenimiento y terminación, a continuación explicaremos como vamos a tomar la invariante y su verificación. *Invariante de Ciclo:* En cada iteración del ciclo, `total` contiene la suma de los términos evaluados hasta ese punto, multiplicados por `x0` correspondiente según la posición en el arreglo `A`. Ahora veremos las etapas en donde nuestra invariante sera verificada que tenga los valores esperados. *1. Inicialización:* Antes de que comience el ciclo, `total` se inicializa en 0, lo cual es coherente con el invariante de ciclo ya que no hemos evaluado ningún término aún. *2. Mantenimiento:* Supongamos que el invariante de ciclo es cierto al inicio de una iteración dada del ciclo ya que total la inicializamos en 0. En esa iteración, se evalúa el término `A[i]`, donde $i = n-1$ y se suma a `total * x0`. El resultado se almacena nuevamente en `total`. El invariante de ciclo se mantiene porque `total` ahora contiene la suma de los términos evaluados hasta ese punto, multiplicados por `x0`. Además, `i` se decrement en 1, por lo que en la siguiente iteración se evaluará el siguiente término en el polinomio $n-2$ y asi en otros ciclos. Por lo tanto, el invariante de ciclo se mantiene. *3. Terminación:* Cuando el ciclo termina (es decir, cuando `i` llega a 0), el invariante de ciclo garantiza que `total` contiene la suma de todos los términos evaluados, multiplicados por `x0` según la posición en el arreglo `A`. Esto es exactamente lo que se espera del algoritmo de evaluación del polinomio en forma de Horner. Por lo tanto, hemos demostrado que el algoritmo es correcto utilizando la Técnica del Invariante del Ciclo. ] = Problema Opcional. Para los problemas elegidos en el Ejercicio I + Proporcionar un algoritmo iterativo (código) que solucione el problema, indicando PreCondiciones y PostCondiciones + Demuestra que el algoritmo es correcto usando la técnica del Invariante del ciclo (loop invariant). + Determinar el desempeño computacional del algoritmo dado. #solucion(color:purple)[ *a) Proporcionar un algoritmo iterativo (código) que solucione el problema, indicando PreCondiciones y PostCondiciones* *Problema $alpha$* *Precondicion:* La lista no debe ser null y debe tener al menos un elemento. ```python def productoElementos(lista): if len(lista) == 1: # Lista con un solo elemento acumulador = lista[0] return acumulador else: acumulador = lista[0] for i in range(1, len(lista)): acumulador *= lista[i] return acumulador ``` *Postcondicion:* El resultado es el producto de todos los elementos de la lista, la lista sigue siendo no null. *problema $beta$* *Precondicion:* $n$ debe de ser mayor o igual a 1 y el resultado de la operación debe ser mayor o igual a 3. ```python def sumaPrimerosN(n): acumulador = 0 for i in range(1, n+1): acumulador += i*3 return acumulador ``` *Postcondicion:* El resultado es la suma de los primeros $n$ múltiplos de 3 y el resultado sigue siendo mayor o igual a 3. *b) Demuestra que el algoritmo es correcto usando la técnica del Invariante del ciclo (loop invariant).* *Problema $alpha$* Para realizar una demostración por invariante de ciclo vamos a necesitar definir una invariante de ciclo y verificar como es su funcionamiento o alteración en 3 etapas del código: inicializacion, mantenimiento y terminación, a continuación explicaremos como vamos a tomar la invariante y su verificación. *Invariante de Ciclo: * La invariante que vamos a elegir es que el acumulador contiene el producto de todos los elementos de la lista hasta el momento de la iteración. Ahora veremos las etapas en donde nuestra invariante sera verificada que tenga los valores esperados. *1. Inicialización:* Antes de que comience el ciclo, el acumulador se inicializa en 0, lo cual es coherente con el invariante de ciclo ya que no hemos evaluado ningún término aún. *2. Mantenimiento:* En nuestro algoritmo tenemos 2 casos que contemplar, el caso cuando `A` solo tiene un elemento y el caso cuando `A` tiene n elementos. *Caso cuando A solo tiene un elemento:* En este caso, el acumulador se inicializa con el primer elemento de la lista, por lo que el invariante de ciclo se mantiene y como no hay mas elementos en la lista por los cuales multiplicar, el ciclo termina y se regresa el acumulador. *Caso cuando A tiene n elementos:* En este caso, el acumulador se inicializa con el primer elemento de la lista, por lo que el invariante de ciclo se mantiene. En la siguiente iteración, el acumulador se multiplica por el siguiente elemento de la lista, por lo que el invariante de ciclo se mantiene. Esto se repite hasta que se termina de recorrer la lista, por lo que el invariante de ciclo se mantiene y como ya no hay mas elementos que recorrer, el ciclo termina y se regresa el acumulador. *3. Terminación:* Aquí podemos verificar que el acumulador contiene el producto de todos los elementos de la lista, y este es distinto de 0 como lo era en la etapa de inicializacion, por lo que el invariante de ciclo se mantiene. Por lo tanto, hemos demostrado que el algoritmo es correcto utilizando la Técnica del Invariante del Ciclo. *problema $beta$* Para realizar una demostración por invariante de ciclo vamos a necesitar definir una invariante de ciclo y verificar como es su funcionamiento o alteración en 3 etapas del código: inicializacion, mantenimiento y terminación, a continuación explicaremos como vamos a tomar la invariante y su verificación. *Invariante de Ciclo:* La invariante que vamos a elegir es que el acumulador contiene la suma de los primeros $n$ múltiplos de 3 hasta el momento de la iteración. Ahora veremos las etapas en donde nuestra invariante sera verificada que tenga los valores esperados. *1. Inicialización:* La variable acumulador se inicializa en 0, lo cual es coherente con el invariante de ciclo ya que no hemos evaluado ningún término aún. *2. Mantenimiento:* Durante el ciclo `for` que va de $1$ hasta $n+1$, el acumulador ira sumando las multiplicaciones de la variable `i` por 3, esto es valido porque cualquier numero multiplicado por 3 es multiplo del 3, por lo que el invariante de ciclo se mantiene en cuanto a su funcion propuesta, estos ciclos se repiten $n+1$ veces. *3. Terminación:* Verificamos el invariante de ciclo, el acumulador ahora contiene la suma de los primeros $n$ múltiplos de 3, y este debe ser mayor o igual a 3, vemos que el acumulador igualmente es distinto de 0 a como lo era en la etapa de inicializacion, por lo que el invariante de ciclo se mantiene. Por lo tanto, hemos demostrado que el algoritmo es correcto utilizando la Técnica del Invariante del Ciclo. *c) Determinar el desempeño computacional del algoritmo dado.* *Problema $alpha$* El tiempo de ejecución de este algoritmo está dominado por el bucle `for` que recorre la lista. El bucle realiza una multiplicación por cada elemento de la lista, lo que implica que el tiempo de ejecución es lineal con respecto al tamaño de la lista `n`. Entonces la complejidad en tiempo seria de $O(n)$. *problema $beta$* El tiempo de ejecución de este algoritmo está dominado por el bucle `for` que va desde $1$ hasta $n+1$. El bucle realiza una multiplicación y luego una suma por cada iteración, lo que implica que el tiempo de ejecución es lineal con respecto al tamaño de la lista `n`. Entonces la complejidad en tiempo seria de $O(n)$. ] ] ] /* == Primera pregunta #lorem(40) #for c in colors { solucion(color: c)[ Este es el color #c #lorem(40)s ] } */
https://github.com/elteammate/typst-shell-escape
https://raw.githubusercontent.com/elteammate/typst-shell-escape/main/example-ls.typ
typst
#import "shell-escape.typ": * #raw( exec-command("ls -la .").stdout, block: true, )
https://github.com/dainbow/FunctionalAnalysis2
https://raw.githubusercontent.com/dainbow/FunctionalAnalysis2/main/themes/6.typ
typst
#import "../conf.typ": * = Компактные операторы == Свойства компактных операторов #definition[ Оператор $A$ называется *компактным*, если #eq[ $forall M subset.eq E_1 "- ограниченное" => A(M) subset.eq E_2 "- предкомпакт (вполне ограниченное)"$ ] Множество компактных операторов обозначается как $cal(K)(E_1, E_2)$. ] #proposition[ Имеют место следующие утверждения: + $dim E_1 < oo => cal(L)(E_1, E_2) = cal(K)(E_1, E_2)$ + $dim E_2 < oo => cal(L)(E_1, E_2) = cal(K)(E_1, E_2)$ ] #proof[ Достаточно понимать, что в конечномерном пространстве любое ограниченное множество вполне ограниченно. + Коль скоро $dim "Im" A <= dim E_1 < oo$, то образ любого ограниченного множества оказывается ограниченным множеством в подпространстве $"Im" A$ конечной размерности. + Сразу следует из исходного заявления в доказательстве. ] #note[ Пусть $R$ -- кольцо, $I$ -- подгруппа $(R, +)$. Тогда $I$ называется *левосторонним идеалом*, если $I$ обладает свойством *поглощения слева*: #eq[ $forall r in R : forall a in I : space r a in I$ ] Аналогично определяется *правосторонний идеал*. Ну и *двухсторонний идеал*, если он является и левосторонним, и правосторонним. ] #proposition[ Пусть $E_1 = E_2 = E$. Тогда $cal(K)(E) subset.eq cal(L)(E)$ -- двухсторонний идеал. ] #proof[ + $cal(K)(E)$ является подгруппой по сложению. Пусть $A, B in cal(K)(E)$. Тогда $A + B in cal(K)(E) <=> (A + B)(B(0, 1))$ -- предкомпакт. Это эквивалентно тому, что из любой ограниченной последовательности в этом множество можно выделить сходящуюся подпоследовательность. Действительно, рассмотрим ограниченную последовательность $seq(y) subset.eq (A + B)(B(0,1))$. В силу определения, её элементы распишутся так: #eq[ $forall n in NN : y_n = A x_n + B x_n; space x_n in B(0, 1)$ ] Так как $A in cal(K)(E)$, то из $A x_n$ можно выделить сходящуюся подпоследовательность $A x_n_k$. Аналогично, уже из $B x_n_k$ можно выделить сходящуюся подподпоследовательность $B x_n_k_l$, причём предыдущая сходимость никуда не денется. + $cal(K)(E)$ поглощает элементы $cal(L)(E)$. Пусть $A in cal(K)(E)$ и $B in cal(L)(E)$. Тогда $A B in cal(K)(E)$ -- ибо $B(B(0, 1))$ тоже ограниченной множество. Для $B A$ сложнее, но мы можем воспользоваться приёмом предыдущего пункта. Рассмотрим ограниченную последовательность $seq(y) subset.eq B A(B(0, 1))$. Тогда $y_n = B A x_n, x_n in B(0, 1)$. В силу компактности оператора $A$, можно из $A x_n$ выделить сходящуюся подпоследовательность $A x_n_k$. Так как оператор $B$ непрерывен, сходимость в образе сохранится, а значит нужная подпоследовательность $y_n_k = B A x_n_k$ найдена. ] #proposition[ Если $dim E = oo$, то тождественный оператор $I in.not cal(K)(E)$. ] #proof[ Действительно, по теореме Рисса мы знаем, что замкнутый единичный шар в таком пространстве не компактен, а значит $B(0, 1) = I(B(0, 1))$ не может быть предкомпактом. ] #corollary[ Если $dim E = oo, A in cal(K)(E)$, то $A^(-1) in.not cal(L)(E)$. ] #proof[ Предположим противное. Тогда $I = A A^(-1) in cal(K)(E)$, чего не может быть. ] #proposition[ Если $A in cal(K)(E_1, E_2)$, E_2 - банахово и $x_n weak x_0 in E_1$, то $A x_n -> A x_0$. ] #proof[ Пусть $x_n weak x_0$. Тогда $seq(x)$ -- ограниченная, а значит $seq(A x)$ -- предкомпакт. Более того, из слабой сходимости аргументов и непрерывности $A$ следует слабая сходимость $A x_n weak A x_0$. Далее, предположим противное. Пусть не сходится. Тогда $exists epsilon exists A x_n_k, norm(A x_n_k - A x_0) > epsilon$. Заметим, что $seq(x)$ предкомпакт, а значит из $x_n_k$ можно выделить сходящуюся подпоследовательность $A x_n_k_l -> y$. Так как отделена от $A x_0$, то $y != A x_0$ Из сходимости следует слабая, то есть $A x_n_k_l weak y$, но в то же время $A x_n_k_l weak A x_0 != y$. Противоречие. ] #theorem[ Пусть $E_2$ -- банахово пространство, $A_n in cal(K)(E_1, E_2), A in cal(L)(E_1, E_2)$, причём $lim_(n -> oo) A_n = A$. Тогда $A in cal(K)(E_1, E_2)$. ] #proof[ В силу банаховости $E_2$ для компактности оператора $A$ достаточно проверить, что $A(B(0, 1))$ является вполне ограниченным множеством. Идея состоит в том, чтобы взять достаточно близкий оператор $A_n$, взять соответствующую ему $epsilon$-сеть и заявить, что она подойдёт к $A$: - $forall epsilon > 0 : exists n_0 in NN : space norm(A - A_n_0) < epsilon$ - $forall epsilon > 0 : exists seq(idx: t, end: T, y) subset.eq E : forall x in B(0, 1) : exists s : space norm(A_n_0 x - y_s) < epsilon$ Зафиксиоуем $epsilon > 0, n_0 in NN$ и $seq(idx: t, end: T, y) subset.eq E$ согласно утверждениям выше. Тогда: #eq[ $forall x in B(0, 1) : exists y_s : space norm(A x - y_s) <= norm(A x - A_n_0 x) + norm(A_n_0 x - y_s) < 2 epsilon$ ] Стало быть, $seq(idx: t, end: T, y)$ -- это конечная $2 epsilon$-сеть для $A(B(0, 1))$, то есть образ вполне ограничен. ] == Свойства собственных значений компактного оператора. #theorem[ Пусть $lambda in CC without {0}$. Тогда $dim "Ker" A_lambda < oo$. Где $A$ -- компактный, а $lambda$ -- его СЗ. ] #proof[ Утверждение теоремы эквивалентно тому, что единичная сфера в пространстве $"Ker" A_lambda$ компактна. Это будет доказано, если мы покажем, как выделить из любой последовательности сходящуюся подпоследовательность. Пусть $seq(x) subset.eq S(0,1) subset.eq "Ker" A_lambda$. Отсюда $norm(x_n) = 1$ и $A x_n = lambda x_n$. Более того, $seq(x)$ -- ограниченное множество, а значит $seq(A x)$ -- предкомпакт. Стало быть, существует сходящаяся подпоследовательность $lim_(k -> oo) A x_n_k = y$. В силу того, что мы можем раскрыть образ через $x_n_k$, получим следующее: #eq[ $lim_(k -> oo) lambda x_n_k = y <=> lim_(k -> oo) x_n_k = y / lambda$ ] Однако, это ещё не все. Нам также нужно показать, что $y in "Ker" A_lambda$ -- принадлежит рассматриваемому подпространству. Для этого мы применим оператор $A$ к обеим частям предела: #eq[ $lim_(k -> oo) A x_n_k = y = 1 / lambda A y <=> A y = lambda y <=> y in "Ker" A_lambda$ ] ] #theorem[ Для любого $delta > 0$ вне любого круга ${abs(lambda) <= delta}$ может лежать лишь конечное число собственных значений компактного оператора $A$. ] #proof[ Проведём доказательство в частном случае $E = H$ -- гильбертово пространство, и $A$ -- компактный самосопряжённый оператор. Предположим противное. Тогда, должна существовать $delta_0 > 0$ и хотя бы счётное число $seq(lambda)$ собственных значений вне этого круга. Пусть $e_n$ -- нормированный собственный вектор для значения $lambda_n$. Тогда $seq(e)$ -- ограниченное множество, а значит $seq(A e)$ -- предкомпакт. Однако, в то же время верно неравенство (здесь мы используем ортогональность собственных векторов для теоремы Пифагора, это свойство самосопряжённого оператора): #eq[ $forall n != m : norm(A e_n - A e_m)^2 = norm(lambda_n e_n - lambda_m e_m)^2 = lambda_n^2 + lambda_m^2 > 2delta_0^2$ ] Получили явное противоречие с вполне ограниченностью. ] #proposition[ Если $lambda in sigma(A) without {0}$, то $lambda in sigma_p (A)$. ] #proof[ По критерию принадлежности спектру, существует нормированная последовательность $seq(x)$, для которой есть предел $lim_(n -> oo) A_lambda x_n = 0$. Так как $seq(x)$ -- ограниченное множество, то в силу компактности $A$ можно выделить сходящуюся последовательность $lim_(k -> oo) A x_n_k = y$. Тогда, мы в то же время имеем равенство #eq[ $lim_(k -> oo)A x_n_k = lim_(k -> oo) lambda x_n_k = y$ ] В силу непрерывности оператора $A$, его можно применить к последнему равенсту: #eq[ $lim_(k -> oo) lambda A x_n_k = lambda y = A y <=> y in "Ker" A_lambda$ ] Важно отметить, что $y != 0$. Это следует из упомянутого предела $lim lambda x_n_k = y$. Стало быть, $lambda in sigma_p(A)$. ] == Теорема Фредгольма для компактных самосопряжённых операторов #proposition( "Лемма об инвариантности", )[ Пусть $M subset.eq H$ -- подпространство, инвариантное относительно самосопряжённого оператора $A$ (то есть $A M subset.eq M$). Тогда $M^bot$ тоже инвариантно относительно $A$. ] #proof[ Пусть $x in M$. В силу условия, $A x in M$. Вопрос состоит в том, чтобы из $y in M^bot$ показать верность $A y in M^bot$. Проверим это явно: #eq[ $forall x in M : (x, A y) = (A x, y) = 0 => A y in M^bot$ ] ] #proposition[ Для компактного самосопряжённого оператора верно: #eq[ $forall lambda != 0: ["Im" A_lambda] = "Im" A_lambda$ ] Иначе говоря, образ $A_lambda$ замкнут. ] #proof[ Применим лемму об инвариантности. Заметим, что $M = "Ker" A_lambda$ инвариантен относительно $A$, а значит и $M^bot = ["Im" A_lambda]$ также инвариантно. Обозначим $tilde(A) := A|_(["Im" A_lambda])$. Это тоже компактный самосопряжённый оператор, действующий из $["Im" A_lambda]$ в само себя (благодаря инвариантности). Заметим, что у $tilde(A)$ нет собственных векторов, соответствующих $lambda$, так как они все лежат в $"Ker" A_lambda$. Отсюда получаем, что $lambda in.not {0} union sigma_p (tilde(A))$. Следовательно $lambda in.not sigma (tilde(A))$. Значит оператор $tilde(A)_lambda$ обратим. То есть, по определению обратимости, $tilde(A)_lambda$ биекция на $["Im" A_lambda]$, в частности сюръекция. Значит $"Im" tilde(A)_lambda = ["Im" A_lambda]$. Распишем #eq[ $tilde(A)_lambda = tilde(A) - lambda I = A|_(["Im" A_lambda]) - lambda I|_(["Im" A_lambda]) = (A - lambda I)|_(["Im" A_lambda]) = tilde(A_lambda)$ ] Отсюда $["Im" A_lambda] = "Im" tilde(A_lambda) = A_lambda (["Im" A_lambda]) subset "Im" A_lambda$ А значит $["Im" A_lambda] = "Im" A_lambda$ ] #theorem[ Пусть $H$ -- гильбертово пространство над $CC$, $A$ -- компактный самосопряжённый оператор и $lambda in CC without {0}$. Тогда #eq[ $H = "Im" A_lambda plus.circle "Ker" A_lambda$ ] ] #proof[ Очевидно из комбинации теоремы Фредгольма для самосопряжённых операторов и утверждения о замкнутости образа компактного самосопряжённого оператора. ] == Теорема Гильберта-Шмидта #proposition[ Если $A != 0$, то у этого оператора существует собственное значение $lambda != 0$. ] #proof[ Коль скоро $A != 0$ и мы рассматриваем компактный оператор, то $norm(A) != 0$. Коль скоро $A$ -- самосопряжённый оператор, то можно воспользоваться теоремой о норме, по ней $norm(A) = max(abs(m_-), abs(m_+))$. Так как $m_-, m_+ in sigma(A)$, то хотя бы одно из этих чисел ненулевое и является собственным значением, что и требовалось. ] #theorem( "Гильберта - Шмидта", )[ Пусть $H$ -- сепарабельное гильбертово пространство над полем $CC$, $A$ -- компактный самосопряжённый оператор. Тогда в $H$ найдётся ортонормированный базис, состоящий из собственных векторов оператора $A$. ] #proof[ Построим нужный базис явным образом. Для этого упорядочим все собственные значения оператора $A$ по модулю, причём включим в этот ряд копии этих значений столько раз, сколько соответствует размерности их собственного подпространства (в силу теоремы о конечности размерности собственных подпространств, это возможно). Получим ряд: #eq[ $abs(lambda_1) >= abs(lambda_2) >= abs(lambda_3) >= ...$ ] Пусть $v_n$ -- нормированный собственный вектор, соответствующий $lambda_n$ (для равных СЗ берём ортонормированные вектора базиса подпространства). Образуем ортонормированную систему $seq(e)$, полученную перенумерованием вектором $v_n$ и добавлением собственных векторов, соответствующих $lambda = 0$ (конечно, если оно является СЗ). Так как мы находимся в сепарабельном пространстве, то для того, чтобы эта система была базисом, достаточно доказать её полноту. Обозначим $M = [angle.l seq(e) angle.r]$. Коль скоро это подпространство, можно применить теорему о проекции: #eq[ $M plus.circle M^bot = H$ ] Стало быть, $M = H <=> M^bot = {0}$. Покажем, что $M^bot$ инвариантно относительно $A$. В силу самосопряжённости $A$, достаточно это доказать для просто $M$ (лемма об инвариантности). Введём дополнительное обозначение $L := angle.l seq(e) angle.r$. Тогда $A L subset.eq L$ тривиальным образом. При этом оператор $A$ компактен, а значит непрерывен, то есть #eq[ $A M = A([L]) subset.eq [A L] subset.eq [L] = M$ ] Исследуем $tilde(A) := A|_(M^bot)$. Возможно 2 случая: - $tilde(A) = 0$. Этот факт можно записать следующим образом: #eq[ $forall x in M^bot : space tilde(A) x = 0 => x in "Ker" tilde(A)$ ] Стало быть, $M^bot subset.eq "Ker" tilde(A)$. Но так как мы рассмотрели сужение на $M^bot$, то по определению $M$ мы оставили $"Ker" A without {0}$ за бортом, то есть $"Ker" tilde(A) = {0} = M^bot$. - $tilde(A) != 0$. Предположим противное: $M^bot != {0}$. По доказанной выше лемме, у $tilde(A)$ существует ненулевое СЗ $lambda$. Обозначим за $e$ -- соответствующий нормированный собственный вектор, то есть $tilde(A)e = lambda e$, но ведь тогда и $A e = lambda e$. Получили противоречие с определением $M$. ]
https://github.com/gongke6642/tuling
https://raw.githubusercontent.com/gongke6642/tuling/main/基础/arguments/1.typ
typst
#image("1.png", width: 25%) = 捕获函数的参数。 = == 论点沉没 与内置函数一样,自定义函数也可以采用可变数量的参数。您可以指定一个参数接收器,它将所有多余的参数收集为..sink。结果sink值是类型arguments。它公开了访问位置参数和命名参数的方法。 #image("2.png") = == 传播 与参数接收器相反,您可以使用运算符将​​参数、数组和字典传播到函数调用中..spread: #image("3.png") = == 构造函数 构建可传播的论据。 该函数的行为类似于.let args(..sink) = sink #image("4.png") #image("5.png") = #image("6.png") = == named 以字典形式返回捕获的命名参数。 #image("7.png")
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/enum-align-02.typ
typst
Other
// Number align option should not be affected by the context #set align(center) #set enum(number-align: start) 4. c 8. d 16. e\ f 2. f\ g 32. g 64. h