repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis
https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/docs/upgrading%20radius.typ
typst
// #par(justify: true)[ // = Nâng cấp bán kính ổn định của điểm 1-median = NÂNG CẤP BÁN KÍNH ỔN ĐỊNH CỦA ĐIỂM 1-MEDIAN // $ x^2 + y^2 = z^2 $ <eq:pytago> // Xét pt pytago @eq:pytago Trong phần này, đầu tiên, chúng tôi sẽ xác định vấn đề chính của mình trong Mục 4.1. Tiếp theo, chúng tôi giới thiệu các phiên bản quyết định của bài toán và thiết lập mối quan hệ giữa chúng trong Mục 4.2. Cuối cùng, chúng tôi cho thấy rằng các vấn đề quyết định có thể được giải quyết dưới dạng đóng, từ đó đưa ra một phương pháp tiếp cận tổ hợp hiệu quả để giải quyết vấn đề lần lượt trong mục 4.3 và 4.4. *4.1 Công thức* Rõ ràng các biến đổi trong trọng số đỉnh trên cây có thể dẫn đến sự bất ổn định trong vị trí trung vị đã thiết lập. Trong phần này, chúng tôi nhằm mục đích tăng cường độ bền vững của vị trí trung vị bằng cách cải thiện bán kính ổn định $R(w)$. Do tính chất phức tạp của $R(w)$, thay vào đó chúng tôi tập trung vào việc nâng cấp chặn dưới của $R(w)$. Bây giờ, chúng tôi sẽ nghiên cứu chi tiết mô hình Giả sử $v_1 in V $ là một điểm trung vị liên quan đến vecto trọng số $w in RR_n^+$ thỏa mãn điều kiện khối lượng đơn vị (1). Với một ngân sách $B >= 0 $, mục tiêu của chúng tôi là thay đổi các trọng số từ $w$ thành một vecto trọng số $tilde(w) in RR_n^+$ trong giới hạn ngân sách này, đồng thời đảm bảo rằng $v_1$ vẫn là điểm trung vị, với mục tiêu tối đa hóa chặn dưới $underline(R)(tilde(w))$. Ở đây, chúng tôi giả định rằng chi phí thay đổi trọng số từ $w$ thành $tilde(w)$ được đo bằng chuẩn $"L1"$, tức là $norm(w - tilde(w))_1$. Hơn nữa, chúng tôi giả định rằng tổng trọng số không thay đổi, tức là $sum_(i=1) ^n tilde(w) = 1$ và không lệch quá nhiều so với $w$, tức là $tilde(w) in [w-epsilon_0, w + epsilon_0]$, với mọi giá trị $epsilon_0 >0 $. Chúng tôi gọi vấn đề này là nâng cấp bán kính ổn định $"(USR)"$ của điểm trung vị $v_1$ và dữ liệu đầu vào là $w$. Khi đó, mô hình của bài toán $"(USR)"$ có thể được viết lại như sau: $ max quad & underline(R)(tilde(w)) quad quad quad quad quad quad quad quad quad quad quad #text(blue)[(USR-10)]\ "s.t." quad & norm(tilde(w)-w)_1 <= B quad quad quad quad quad quad quad("USR"-10a)\ & v_1 "is 1-median w.r.t" tilde(w) quad quad quad quad quad quad quad ("USR" - 10b)\ & sum^n_(i=1) tilde(w)_i = 1 quad quad quad quad quad quad quad ("USR" -10c)\ & norm(tilde(w)-w)_infinity <= epsilon_0 quad quad quad quad quad quad quad ("USR" - 10d) $ Trong phần còn lại của tiểu mục này, mục tiêu của chúng tôi là đơn giản hóa vấn đề $"USR"$ bằng cách: 1. Viết lại bài toán max thành min 2. Loại bỏ ràng buộc ("USR" - 10b) 3. Thay đổi biến từ vecto trọng số $tilde(w)$ sang vecto thay đổi $x = tilde(w) - w.$ Dựa vào *Định lý 3.1*, bài toán tối ưu hóa $underline(R)(w)$ có thể viết lại dưới dạng một bài toán tối thiểu hóa như sau: $ max_tilde(w) underline(R)(tilde(w)) = max_tilde(w) min_(u in N(v_1)) 1/n (1- 2 angle.l tilde(w), bb(1)_T_u angle.r)= 1/n -2/n min_tilde(w) max_( u in N(v_1)) angle.l tilde(w), bb(1)_T_u angle.r. $ (11) Tiếp theo, ta đặt $w^*$ là nghiệm tối ưu của bài (USR-10), dễ thấy $ max_(u in N(v_1)) angle.l w^*, bb(1)_T_u angle.r <= max_(u in N(v_1)) angle.l tilde(w), bb(1)_T_u angle.r <= 1/2. $ Từ đó, ta thấy rằng $v_1$ là tối ưu đối với $w^*$. Do đó, ràng buộc (USR-10b) là dư thừa và có thể loại bỏ. Cuối cùng, đặt $ x= tilde(w) - w$ là vecto điều chỉnh. Bằng cách đổi biến, loại bỏ điều kiện (USR-10b) và viết lại hàm mục tiêu như (11), bài toán (USR-10) được viết lại như sau: $ min quad & max_(u in N(v_1)) angle.l w + x, bb(1)_T_u angle.r quad quad #text(blue)[(USR-12)]\ "s.t." quad & norm(x)_1 <= B quad quad quad quad quad quad quad "USR-12a"\ & sum^n_(i=1) x_i = 0 quad quad quad quad quad quad quad "USR-12b"\ & x_i in [-epsilon_0; epsilon_0], forall i = 1,...,n quad quad quad quad quad quad quad "USR-12c" $ Trong phần còn lại của bài báo này, chúng tôi sẽ tập trung vào (USR-12) thay vì (USR-10). Bằng cách mở rộng hàm mục tiêu, vấn đề (USR-12) có thể biểu diễn thành một bài toán lập trình tuyến tính với $n$ chiều và có $O(n)$ ràng buộc. Do đó, nó có thể được giải bằng phương pháp đơn hình nổi tiếng. Tuy nhiên, độ phức tạp của phương pháp đơn hình không phải là bậc đa thức, theo Klee và Minty (1972). Mặc dù có các thuật toán thời gian đa thức cho lập trình tuyến tính, ví dụ như Karmarkar (1984), nhưng độ phức tạp thời gian của chúng không phải là tuyến tính theo $n$, do đó có thể chậm đối với các bài toán lập trình tuyến tính, như Megiddo (1984), nhưng những phương pháp này yêu cầu số chiều phải cố định hoặc tăng chậm theo số lượng ràng buộc, điều này không áp dụng trong trường hợp này. Trong phần tiếp theo, chúng tôi đề xuất một phương pháp tổ hợp hiệu quả để giải quyết vấn đề (USR-12) bằng cách tận dụng cấu trúc đặc thù của nó. Để phát triển thuật toán này, chúng tôi sẽ giới thiệu trong các phần tiếp theo..., có thể được giải dưới dạng đóng. Hơn nữa, giải pháp cho vấn đề quyết định có thể được chuyển đổi hiệu quả thành giải pháp cho (USR-12) dựa trên mối quan hệ giữa chúng. == Phiên bản tham số của bài toán nâng cấp bán kính ổn định Giải quyết bài toán (USR-12) thực chất là trả lời câu hỏi: "Giá trị mục tiêu nhỏ nhất có thể đạt được với ngân sách bị giới hạn bởi $B$ là bao nhiêu". Thay vì tập trung vào câu hỏi này, ta có thể khám phá một câu hỏi liên quan chặt chẽ khác: "Với một giá trị mục tiêu $t$ cho trước, ngân sách tối thiểu cần thiết để đạt được giá trị mục tiêu không lớn hơn $t$ là bao nhiêu?". Câu hỏi này có thể được biểu diễn thành bài toán sau: $ min quad & norm(x)_1 quad quad quad quad quad quad #text(blue)[(PUSR-13)]\ "s.t." quad & max_(u in N(v_1)) angle.l w + x, bb(1)_T_u angle.r <= t quad quad quad "PUSR-13a"\ & sum^n_(i=1) x_i = 0 quad quad quad "PUSR-13b"\ & x_i in [-epsilon_0; epsilon_0], forall i = 1,...,n quad quad quad "PUSR-13b" $ Thoạt nhìn, (PUSR-13) được tạo ra từ (USR-12) bằng cách hoán đổi mục tiêu và ràng buộc ngân sách. Trong phần còn lại, độc giả sẽ thấy rằng: -- Giải quyết (PUSR-13) đơn giản hơn so với (USR-12) -- Có một phép biến đổi đơn giản để từ nghiệm của (PUSR-13) suy ra nghiệm của (USR-12). Trực quan, mối liên hệ giữa (USR-12) và (PUSR-13) như sau: nếu ngân sách tối thiểu cần thiết để đạt được giá trị mục tiêu không lớn hơn $t$ không vượt quá $B$, thì việc tăng ngân sách lên $B$ sẽ cho phép giảm $t$ để đạt được giá trị mục tiêu nhỏ nhất của bài toán ban đầu. Nói cách khác, giải quyết bài toán mới này cho phép chúng ta xác định xem $t$ có lớn hơn giá trị mục tiêu nhỏ nhất của bài toán gốc hay không. Do đó, chúng tôi gọi bài toán này là bài toán "phiên bản tham số của nâng cấp bán kính ổn định. (PUSR-13)" Thú vị là, lập luận ngược lại cũng đúng, như được chứng minh trong bổ đề sau đây. Để phát biểu bổ đề, chúng ta hãy giới thiệu một số ký hiệu bổ sung. Gọi $P(x)= max_(u in N(v_1)) angle.l w + x, bb(1)_T_u angle.r $ là hàm mục tiêu của (USR-12). Chúng ta cũng ký hiệu $x^*$ là nghiệm tối ưu và $t^*$ là giá trị mục tiêu tối ưu của (USR-12). Khi đó, $P(x^*)= t^*$. Tiếp theo, gọi $hat(x)(t)$ là nghiệm tối ưu và $beta(t)$ là giá trị mục tiêu tối ưu của (PUSR-13) tương ứng với tham số $t$. Nếu tập hợp nghiệm khả thi của (PUSR-13) rỗng, chúng ta đặt $beta(t)= + infinity$. Rõ ràng bằng $beta(.)$ là một hàm không giảm trên miền của nó. Mối quan hệ giữa $(t,beta(t))$ và $(t^*,B)$ được thiết lập như sau: // == Bổ đề 4.1 *Bổ đề 4.1* $ beta(t) <= B <=> t>= t^* $ *Chứng minh* Nếu $beta(t) <= B$, thì $hat(x)(t)$ là một nghiệm khả thi ứng với (PUSR-13), do đó, $P(hat(x)(t)) >= P(x^*)$. Vì thế, $t >= P(hat(x)(t)) >= P(x^*) = t^*$, trong đó dấu bất đẳng thức đầu tiên xuất phát từ (PUSR-13a). Ta tiến hành chứng minh chiều ngược lại. Giả sử rằng $t >= t^*$. Bởi vì $t^* = P(x^*)$, ta có $P(x^*) <= t$. Điều này cho thấy tính khả thi của $x^*$ đối với (PUSR-13). Do đó, $norm(hat(x)(t))_1 <= norm(x^*)_1$. Tính khả thi của $x^*$ đối với (PUSR-12) ngụ ý rằng $norm(x^*)_1 <= B$. Vì vậy, $beta(t)= norm(hat(x)(t))_1 <= B$. Ta hoàn thành chứng minh. Từ *Bổ đề 4.1*, điều quan trọng cần lưu ý là $beta(t^*) <= B.$ (14). Trong phần tiếp theo, chúng ta sẽ khai thác *Bổ đề 4.1* để dẫn ra một sự chuyển đổi từ $(hat(x)(t), beta(t))$ của (USR-12) sang $(x^*, t^*)$ của (PUSR-13). *Định lý 4.1* _Giá trị hàm mục tiêu $t^*$ của (USR-12) được tính_ $ t^* = inf{t: beta(t) <= B}. $ _và $hat(x)(t^*)$ là nghiệm tối ưu của (USR-12)._ *Chứng minh* Từ 4.1, ta có thể thấy rằng $t^* <= inf{t: beta(t)<= B}$. Nếu $t^* < inf{t: beta(t) <= B}$ thì dễ thấy rằng $beta(t^*) > B$, điều này mâu thuẫn với (14). Vì thế, $t^*= inf{t: beta(t)<= B}$. Từ (14), ta biết rằng $hat(x)t^*$ là nghiệm khả thi của (USR-12). Do đó, $P(hat(x)(t^*)) >= P(x^*) = t^*$. Hơn nữa, tính khả thi của $hat(t^*)$ tương ứng với (PUSR-13a) ngụ ý rằng $t^* >= P(hat(x)(t^*))$. Kết hợp với các điều này cho thấy tính tối ưu của $hat(x)(t^*)$ đối với (USR-12). (chứng minh xong). Từ *Định lý 4.1*, có thể thấy rằng nếu ta có thể giải quyết được (PUSR-13), tức là biết $beta(t)$ và $hat(x)(t)$ với t bất kỳ, thì ta có thể xây dựng một nghiệm tối ưu $x^* = hat(x)(t^*)$, trong đó $t^*$ có thể được tính bằng (15). Trong phần còn lại của tiểu mục này, chúng tôi đề xuất một cách đơn giản hóa (PUSR-13) bằng cách gộp tất cả các phần tử của nghiệm tối ưu có giá trị bằng nhau. Cụ thể, trước hết chúng tôi nhận thấy rằng có tồn tại một nghiệm tối ưu của (PUSR-13) sao cho các phần tử thứ $i$ của nó có giá trị giống nhau đối với các đỉnh $v_i$ thuộc cùng một cây con $T_u$ với $u in N(v_1)$. *Định lý 4.2* _Tồn tại một nghiệm tối ưu $hat(x)(t)$ của (PUSR-13) mà gán cùng một giá trị cho $hat(x)_(i)(t)$ đối với tất cả các đỉnh $v_i$ trong mỗi cây con $T_u$, với $ u in N(v_1)$._ *Chứng minh* Giả sử $hat(x)(t)$ là một nghiệm tối ưu bất kỳ của (PUSR-13). Khi đó, ta có thể đạt được nghiệm tối ưu mong muốn bằng cách, đối với mọi $ u in N(v_1)$, $ hat(x)_(i)(t) = 1/ abs(T_u) sum_(v_i in T_u) hat(x)_(i)(t), quad quad forall v_i in T_u. $ (chứng minh xong) Từ định lý *4.2*, chúng ta nhận thấy rằng thay vì tìm kiếm vecto điều chỉnh tối ưu $hat(x)(t)$, chúng ta có thể tập trung vào tổng trọng chỉnh sửa trên mỗi cây con $T_u_j$. Quan sát này cho phép chúng ta giảm số chiều của bài toán (PUSR-13) từ $n$ xuống $k+1$, trong đó $k$ là bậc của điểm trung vị $v_1$. Giả sử $N(v_1)={u_1,u_2,...,u_k}$, $u_0 = v_1$ và $T_u_O = {v_1}$. Bây giờ chúng ta định nghĩa vecto mới $z in RR_+^(k+1)$ có chặn trên $overline(z) in RR_+^(k+1)$. Tiếp theo, ta đặt $z_0 = x_1$ là phép chỉnh sửa liên quan đến điểm trung vị $v_1$ và $z_0 = epsilon_0$ là giới hạn trên của nó. Đặt $z_j = angle.l x, bb(1)_T_u_j angle.r$ là tổng trọng số chỉnh sửa của cây con $T_u_j$ và $z_j = epsilon_0 abs(T_u_j)$ là chặn trên cho $z_j$, với $j=1,...,k$. Lưu ý rằng, $norm(x)_1 >= norm(z)_1$ và sự bằng nhau xảy ra nếu các giá trị $x_i$ cùng dấu cho các đỉnh $v_i$ thuộc cùng một cây con $T_u_j$. Ký hiệu $gamma_j = angle.l w, bb(1)_T_u_j angle.r$ là tổng trọng số của cây con $T_u_j$ với $j=1,...,k.$ Với các ký hiệu mới, thay vì xem xét bài toán (PUSR-13), người ta có thể tập trung vào bài toán sau, với số chiều nhỏ hơn bằng cách giữ nguyên tất cả các ràng buộc, nhưng thay thế $norm(x)_1$ bằng giới hạn dưới của nó $norm(z)_1:$ $ min quad & sum_(j=0)^k abs(z_j) quad quad quad quad #text(blue)[(PUSR-16)]\ "s.t." quad & max_(j=1,...,k) (gamma_j + z_j) <= t quad quad ("PUSR-16a")\ & sum^k_(j=1) z_j = 0 quad quad ("PUSR-16b")\ & z_j in [-overline(z)_j; overline(z)_j], forall j = 0,1,...,k quad quad ("PUSR-16c") $ Giả sử $hat(z)(t)$ là nghiệm tối ưu của (PUSR-16). Lưu ý rằng $beta(t)$ cũng là giá trị mục tiêu tối ưu của (PUSR-16). Điều quan trọng cần lưu ý là (PUSR-13) và (PUSR-16) "tương đương" theo nghĩa nếu biết $hat(x)(t)$ như được mô tả trong Định lý 4.2, thì ta có thể xây dựng $hat(z)(t)$ và nếu biết $hat(z)(t)$ thì ta có thể tìm ra $hat(x)(t)$ bằng cách $ hat(z)_(j)(t)= sum_(v_i in T_u_j) hat(x)_(i)(t), quad forall j= 0,1,...,k. $ và nếu biết $hat(z)(t)$, chúng ta có thể tìm $hat(x)(t)$ bằng $ hat(x)_i(t) = (hat(z)_(j)(t))/ abs(T_u_j), quad forall v_i in T_u_j, forall j= 0,1,...,k. $ Chúng ta kết thúc phần này với một đặc trưng về tính không rỗng của tập hợp khả thi của (PUSR-16). Gọi $ J <= (t)= {j in {1,...,k}: gamma_j <= t}$ và $J > (t) = {j in {1,...,k}: gamma_j > t}.$ *Mệnh đề 4.1*. _Tập khả thi của (PUSR-16) là không rỗng nếu $ overline(z_0) + sum_(j in J <= (t)) min(overline(z)_j, t- gamma_j) >= sum_(i in J>(t)) (gamma_i- t). $_ *Chứng minh* Nếu tập khả thi của (PUSR-16) không rỗng thì tồn tại một số nghiệm khả thi $z in RR^(k+1)$ thỏa mãn ràng buộc (PUSR-16), nghĩa là $ z_0 + sum_(j in J<=(t)) z_j = - sum_(j in J > (t)) z_j. $ (19) Từ tính khả thi của $z$, không khó để xác minh rằng vế trái của (19) bị chặn trên bởi vế trái của (18) và vế phải của (19) bị chặn dưới bởi vế phải của (18). Do đó, ta thu được (18). Ngược lại, giả sử rằng (18) không thỏa mãn. Bằng cách sử dụng các ước lượng tương tự, ta có thể thu được $ z_0 + sum_(j in J <= (t)) z_j < - sum_(j in J > (t)) z_j. $ Điều này vi phạm ràng buộc (PUSR-16b) và do đó, tập hợp khả thi là rỗng. (chứng minh xong). == 4.3 Giải phiên bản tham số của bài toán nâng cấp bán kính ổn định Trong phần trước, chúng ta đã chứng minh rằng việc giải bài toán mục tiêu (USR-12) có thể được giảm xuống bằng việc giải phiên bản tham số của nó (PUSR-16) bằng cách tìm một nghiệm tối ưu $hat(z)(t)$ và mục tiêu tối ưu $beta(t)$ tương ứng với $t$. Định lý sau đây cung cấp các biểu thức dạng đóng cho cả $hat(z)(t)$ và $beta(t)$. *Định lý 4.3* _Nếu giá trị mục tiêu tối ưu $beta(t)$ là hữu hạn, thì nó có thể được tính dưới dạng biểu thức đóng: $ beta(t) = 2 sum_(i=1)^k [gamma_i -t]_+ $ (20)_ _Trong đó $[alpha]_+ = max(0,alpha)$ với $alpha in RR$. Hơn nữa, một nghiệm tối ưu của (PUSR-16), gọi là $hat(z)(t)$ có thể được chọn bằng cách xem xét hai trường hợp. Nếu $overline(z_0) >= sum_(i=1)^k [gamma_i - t]_+$ thì ta chọn $ hat(z)_(j)(t) = -(gamma_j - t), quad quad j in J > (t) quad (21a) $ $ hat(z)_(j) (t) = 0, quad quad j in J <= (t) quad quad (21b) $ $ hat(z_0)(t)= sum_(j in J > (t)) (gamma_j - t). quad quad (21c) $ Ngược lại, $ hat(z_j)(t)= -(gamma_j -t), quad quad j in J > (t) (22a) $ $ hat(z_j)(t)= min(overline(z_j), underline(t)-gamma_j), quad quad j in J <= (t) (22b) $ $ hat(z_0)(t)=overline(z_0), quad (22c) $ trong đó $underline(t)$ được chọn sao cho $ overline(z_0)+ sum_(j in J <= (t)) min(overline(z_j), underline(t)-gamma_j)= sum_(j in J >(t)) (gamma_j - t). quad (23) $_ *Chứng minh* Chứng minh gồm hai phần, chúng tôi chia thành hai bước. Trong bước đầu tiên, chúng tôi chứng minh rằng $2 sum_(i=1)^k [gamma_j - t]_+$ là cận dưới cho mục tiêu (PUSR-16), tức là $beta(t)>= 2 sum_(i=1)^k [gamma_j - t]_+$. Trong bước thứ hai, chúng tôi chứng minh rằng $2 sum_(i=1)^k [gamma_j-t]_+$ thực sự là giá trị nhỏ nhất của (PUSR-16) bằng cách chứng minh rằng $hat(z)(t)$, được định nghĩa trong (21) hoặc (22), thỏa mãn $norm(hat(z)(t))_1 = 2 sum_(i=1)^k [gamma_j - t]_+.$ *Bước 1.* Trực giác cho thấy, với một giá trị $t$ nào đó, ta cần phải giảm $gamma_j$ với $ j in J <= (t)$ để duy trì phương trình (PUSR-16b). Nói cách khác, $z_j$ nên là số không dương đối với $j in J>(t)$ và nên là số không âm đối với $j in J <= (t)$. Trực giác này thúc đẩy các ước lượng khéo léo sau đây để đạt được một cận dưới chặt chẽ cho hàm mục tiêu: $ norm(z)_1 = sum_(j=0)^k abs(z_j)= abs(z_0)+ sum_(i in J <= (t)) abs(z_i)+ sum_(j in J >(t)) abs(z_i) >= z_0 + sum_(i in J <= (t)) z_j - sum_(i in J > (t)) z_j. $ Bằng điều kiện (PUSR-16b), chúng ta có $z_0 + sum_(i in J <= (t)) z_j = - sum_(i in J >(t)) z_j.$ Do đó, $ norm(z)_1 >= -2 sum_(i in J > (t)) z_j. $ Chú ý rằng với mọi $j in J >(t)$, ta có $-z_j >= gamma_j - t >0$, do đó, $ norm(z)_1 >= 2 sum_(j in J > (t))(gamma_j - t)= 2 sum_(j=1)^k [gamma_j - t]_+. $ Từ ước lượng trên, ta thấy rằng $ 2sum_(j in J > (t))(gamma_j -t )$ là chặn dưới của giá trị mục tiêu của (PUSR-16). *Bước 2.* Ta biết rằng tồn tại một vài vecto khả thi $z$ của (PUSR-16) để mà $ norm(z)_1= 2sum_(j in J >(t))(gamma_j -t). quad quad (24) $ Vecto $z$ có thể được định nghĩa như sau. Đối với tập hợp chỉ số $J > (t)$, chúng ta đặt $ z_j = -(gamma_j - t), quad forall j in J >(t). $ Với $j in {0} union J <= (t)$, mục tiêu của ta là chọn $z_j$ là một số không âm sao cho tổng của chúng bằng $sum_(j in J > (t)) (gamma_j -t)$. Để làm điều này, hãy xem xét hai trường hợp. Nếu $z_0 >= sum_(j in J > (t))(gamma_j -t)$, thì ta có thể đơn giản đặt $ z_0 =sum_(j in J >(t))(gamma_j -t), $ $ z_j =0, quad forall j in J <= (t). $ Ngược lại, ta có $overline(z_0) < sum_(j in J >(t))(gamma_j -t)$. Trong trường hợp này, ta đặt $ z_0 = overline(z_0), $ $ z_j = min (overline(z_j), underline(t)-gamma_j), quad forall j in J <= (t), $ trong đó $underline(t)$ được định nghĩa ở (23). Bây giờ chúng ta chỉ ra sự tồn tại của $underline(t)$. Đặt $phi(t')= overline(z_0) < sum_(j in J >(t))(gamma_j -t)$ và $phi(t)>= sum_(j in J > (t))(gamma_j -t)$ vì mệnh đề 4.1. Do tính liên tục của $phi$ ngụ ý sự tồn tại của $underline(t)$. Cuối cùng, không khó để thấy rằng $z$ là một nghiệm khả thi của (PUSR-16) và thỏa (24). Bằng cách chọn $hat(z)(t)=z$, chúng ta hoàn thành chứng minh. (chứng minh xong) Quan sát rằng với mỗi giá trị cố định của $t$, ta có thể tìm $underline(t)$ trong (23) bằng cách sử dụng tìm kiếm nhị phân vì hàm $z_0 + sum_(j in J <= (t)) min (z_j, . - gamma_j)$ là hàm tuyến tính từng khúc và không giảm. Lưu ý rằng việc đánh giá hàm này tốn chi phi $O(k)$, với $k$ là bậc của $v_1$. Do đó, các bài toán tham số (PUSR-16) có thể được giải quyết trong thời gian $O(k log k)$. Vì phép biến đổi (17) tốn chi phí $O(n)$, bài toán (PUSR-13) có thể được giải trong thời gian $O(n+k log k).$ *Giải bài toán nâng cấp bán kính ổn định* Bây giờ chúng tôi sẽ mô tả một cách tiếp cận tổ hợp để tìm nghiệm tối ưu $w*$ của bài toán nâng cấp bán kính ổn định ban đầu (USR-10) thông qua các phép biến đổi đã được phát triển trong các tiểu mục trước đó. Ta có $w* = w + x^* $, trong đó $x*$ là nghiệm khả thi của (USR-12). Dựa vào định lý 4.1, ta có thể chọn $x*= hat(x)(t*)$. Lưu ý rằng, ta có thể xây dựng $hat(x)(t)$ từ $hat(z)(t)$ cho bất kỳ $t$ nào bằng cách sử dụng Định lý 4.2, phương trình (17), và biểu thức của $hat(z)(t)$ được cho bởi (21) hoặc (22). Về giá trị $t*$, nó có thể được tìm thấy trong thời gian $O(k log k)$, với $k$ là bậc của $v_1$, bằng cách sử dụng tìm kiếm nhị phân vì $t* = inf{t >= 0: beta(t) <= B}$ và hàm $beta(.)$ được xác định trong Định lý 4.3 là hàm tuyến tính từng khúc và giảm dần. Xem Hình 2 để có cái nhìn tổng quan về các phép biến đổi giữa các bài toán và lời giải. #align(center)[ #import "@preview/cetz:0.1.2" #import "@preview/cetz:0.1.2": canvas, plot // #import "@preview/cetz:0.2.2" // #import "@preview/cetz:0.1.2 #canvas(length: 10%, { import cetz.draw: * let (y1, y2, y3, y4) = (3,2,1, 4) let (x1, x2, x3, x4) = (1, 3, 5, 7) let x0 = 0 let r = 0.5 let h =-2 rect((0,0), (2.2, 0.5), name: "p1") rect((6,0), (6.5+2, 0.5), name: "p2") rect((0,h), (2.5, h+0.5), name: "p4") rect((6,h), (6.5+2, h+0.5), name: "p3") line("p1.right", "p2.left", mark: (end: ">"), name: "l1") line("p2.bottom", "p3.top", mark: (end: ">"), name: "l2") line("p3.left", "p4.right", mark: (end: ">"), name: "l3") content("p1.center", [#text(blue)[$("USR"-1) quad "&" quad w^*$]], anchor: none, padding: 0.3) content("p2.center", [#text(blue)[$("USR"-2) quad "&" quad x^*$]], anchor: none, padding: 0.3) content("p3.center", [#text(blue)[$("PUSR"-3) quad "&" quad hat(x)(t)$]], anchor: none, padding: 0.3) content("p4.center", [#text(blue)[$("PUSR"-4) quad "&" quad hat(z)(t)$]], anchor: none, padding: 0.2) content("l1.bottom", [*Loại bỏ ràng buộc median*], anchor: "bottom", padding: 0.2) content("l1.top", [*$x^* = w^* - w$*], anchor: "top", padding: 0.2) content("l2.left", [*Đổi hàm mục tiêu và* *điều kiện ngân sách*], anchor: "left", padding: 0.2) content("l2.right", [*Định lý 3*], anchor: "right", padding: 0.2) content("l3.bottom", [*Định lý 4.2 4.3 & (17)*], anchor: "bottom", padding: 0.2) content("l3.top", [*Giảm chiều*], anchor: "top", padding: 0.2) })] Hình 2. Các phép biến đổi của bốn bài toán nâng cấp. Mỗi hộp chứa một bài toán và nghiệm tối ưu của nó. Mỗi mũi tên đại diện cho phép biến đổi giữa các bài toán cùng với những kết quả chính kết nối chúng. Nhớ rằng việc giải quyết bài toán (PUSR_13) tốn chi phí $O(n + k log k)$ và việc tìm kiếm $t*$ có thể thực hiện trong $O(k log k)$, do đó độ phức tạp tổng thể của việc giải bài toán (USR-10) là $O(n + k log k)$. *Định lý 4.4* _Bài toán nâng cấp cận dưới của bán kính ổn định cho điểm trung vị trên đồ thị cây (USR-10) có thể được giải quyết trong thời gian $O(n + k log k )$, trong đó $n$ là số đỉnh của cây và $k$ là bậc của điểm trung vị $v_1$._ Cuối cùng, ta kết thúc mục này bằng ví dụ minh họa cho những bước chính để giải quyết bài toán (USR-10). *Ví dụ 4.1* Xem xét bài toán (USR-12) với ngân sách $B = 0.36$, mức độ nhiễu $epsilon_0 = 0.05$ và cây có trọng số như hình 1. Đặt $u_0 = v_1$, $u_1 = v_2$ $u_2 = v_3$ và $u_3 = v_4$. Nhớ rằng $gamma_j = angle.l w, bb(1)_T_u_j angle.r $ với $j= 0,1,2,3$, ta có $gamma_1 = 0.33$, $gamma_2 = 0.12$ và $gamma_3 = 0.45$. Hơn nữa $ beta(t)= 2([gamma_1 - t]_+ + [gamma_2 - t]_+ + [gamma_3 - t]_+) $. Bằng (15), ta có $t^*=inf{t: beta(t) <= B}= 0.3$. Trong trường hợp này, ta có $beta(t^*)=B$. Bởi vì $overline(z_0)= epsilon_0 = 0.05 < beta(t^*)/2 =0.18$, ta có thể chọn $hat(z)(t^*)$ dựa vào (22), chú ý rằng $J > (t^*)= {1,3}$, $J <= (t^*)= {2}$ và ta có $ hat(z)(t^*)=(0.05, -0.03, 0.13, -0.15). $ Bằng (17), ta có $ hat(x)(t^*)=(0.05, -0.01, 0.065, -0,05, -0.01, -0,01, 0.065, -0.05, -0.05). $ Dựa vào định lý 4.1, ta có thể chọn $x^* = hat(x)(t^*)$. Bởi vì $w^* = w+x$, ta được $ w^* = (0.15, 0.12, 0.125, 0.1, 0.09, 0.09, 0.125, 0.1, 0.15, 0.05). $ Chặn dưới lớn nhất của bán kính ổn định sau khi được nâng cấp là $underline(R)(w^*)= 0.4/9$. Trọng số đỉnh trên cây được cải thiện như ở hình 3 #import "@preview/cetz:0.1.2": canvas, plot #import "@preview/cetz:0.2.2" #import "@preview/cetz:0.1.2" #align(center)[#canvas(length: 10%, { import cetz.draw: * let y = 2 let x = 4 let y-space = 1 let h=1.4 circle((0*h,3), radius: 0.05,fill:black, name: "v1") content("v1.bottom", $v_1 (0.15)$, anchor: "left", padding: 0.2) circle((-2*h, 2), radius: 0.05, fill: black, name: "v2") content("v2.bottom", $v_2 (0.12)$, anchor: "left", padding: 0.2) circle((-3*h, 1), radius: 0.05,fill:black, name: "v5") content("v5.bottom", $v_5 (0.09)$, anchor: "left", padding: 0.2) circle((-1*h, 1), radius: 0.05,fill:black, name: "v6") content("v6.bottom", $v_6 (0.09)$, anchor: "left", padding: 0.2) circle((0*h, 2), radius: 0.05, fill: black, name: "v3") content("v3.bottom", $v_3 (0.125)$, anchor: "left", padding: 0.2) circle((0*h, 1), radius: 0.05, fill: black, name: "v7") content("v7.bottom", $v_7 (0.125)$, anchor: "left", padding: 0.2) circle((2*h, 2), radius: 0.05, fill: black, name: "v4") content("v4.bottom", $v_4 (0.1)$, anchor: "left", padding: 0.2) circle((1*h, 1), radius: 0.05, fill: black, name: "v8") content("v8.bottom", $v_8 (0.15)$, anchor: "left", padding: 0.2) circle((3*h, 1), radius: 0.05, fill:black, name: "v9") content("v9.bottom", $v_9 (0.05)$, anchor: "left", padding: 0.2) line("v1", "v2") line("v1", "v3") line("v1", "v4") line("v2", "v5") line("v2", "v6") line("v3", "v7") line("v4", "v8") line("v4", "v9") } )] // ]
https://github.com/TechnoElf/mqt-qcec-diff-thesis
https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-thesis/main/content/introduction.typ
typst
= Introduction Quantum computing is poised to revolutionise the way we solve problems. It promises to enable certain kinds of calculations and algorithms that were previously unthinkably inefficient @nielsen2010quantum. The technology enables a kind of probabilistic approach to computation that allows an extremely efficient parallelisation of certain algorithms. One key application of quantum computers is their potential use in chemistry due to their inherent ability to simulate quantum systems @mcardle2020chem. For instance, a circuit structure known as a @vqe is able to solve for the ground state of a given physical quantum system, a task that would be classically impossible within a reasonable time frame @moll2018vqe @peruzzo2014vqe. Similar techniques can be applied to various optimisation problems in other fields @abrams1999eigen @harrow2009linear. A core problem in the field of quantum computing is the transformation of an abstract algorithm to sequence of operations to be executed on real quantum computing hardware. Various factors must be considered in this process, such as the available types of operations and the geometry of the quantum computer. Additionally, it is desirable to transform the algorithm in such a way that it can be executed with minimal noise. A plethora of software tools exist for this purpose, notably the @mqt @wille2024mqthandbook. As these "quantum compilers" become more intricate and more optimisation techniques are employed, it becomes harder to verify that their output implements the same functionality as the original circuit. This makes the development of new compilation methodologies increasingly difficult, as the reliability becomes difficult to prove numerically. To verify the functionality of a compiled quantum circuit, it is therefore necessary to check its equivalence to the original algorithm automatically @viamontes2007equivalence. @mqt provides a tool named @qcec for this purpose @burgholzer2020ecqiskit. This work extends @qcec with a novel variation of the existing verification flow based on @dd[s]. Specifically, an application scheme is developed for the alternating @dd equivalence checker based on algorithms originally intended for solving the @lcs problem (so called "diff" algorithms). This approach thereby exploits the structural similarity that is present in quantum circuits at different stages of compilation. Additionally, a heuristic is developed that can discern, whether or not this new approach can reduce the run time of the state-of-the-art flow for any given pair of circuits. When combined, these new approach results in run time improvements of up to $59%$ in some cases, with an average improvement of $7%$. The remainder of the thesis is structured as follows: In section 2, the concepts required to understand the developed methods will be elaborated. Section 3 will then present the current state of quantum circuit verification schemes. Following this, section 4 will discuss the algorithms themselves and their application to @qcec. Next, section 5 will present the results of applying the new equivalence checking methodology to real-world problems and detail the procedure used to acquire them. Section 6 will discuss the results and draw conclusions from them. Finally, section 7 will judge the impact of this work as a whole and suggest future pathways of exploration.
https://github.com/maucejo/cnam_templates
https://raw.githubusercontent.com/maucejo/cnam_templates/main/src/letters/_reunion.typ
typst
MIT License
#import "../common/_colors.typ": * #import "../common/_utils.typ": * #let cnam-reunion( composante: "cnam", type: "cr", titre: none, redacteur: none, lieu: none, date: none, toc: false, body ) = { let logo-height = 4.08cm let decx = -0.073cm let decy = 0.085cm if composante != "cnam" { logo-height = 10cm decx = 0cm decy = 0cm } set heading(numbering: "1.1.") show heading.where(level: 1): it => { set text(size: 14pt, fill: primary.dark-blue) it v(0.5em) } set text(font: "Crimson Pro", size: 12pt, lang: "fr", ligatures: false) set par(justify: true) let footer = { grid( columns: (1fr, 1fr), align: left, [#context counter(page).at(here()).first()], [#place(right + horizon, dx: -1.25cm, over-title(title: ("Conservatoire national", "des arts et métiers"), size: 12pt, color: primary.dark-blue))] ) } set page( footer: footer, margin: (top: 2cm, bottom: 2cm, left: 1.5cm, right: 1.5cm) ) let surtitre = ("Compte-rendu", "de réunion") if type == "pv" { surtitre = ("Procès", "verbal") } else if type == "odj" { surtitre = ("Ordre", "du jour") lieu = [Ordre du jour] } let en-tete = { grid( columns: (1fr, 1fr), align: (left, right), [#over-title(title: surtitre, size: 20pt, color: primary.dark-blue)], [#place(right, dx: decx, dy: decy, image("../resources/logo/" + composante + ".png", width: logo-height))] ) } place(top, dy: -1.5cm, en-tete) v(2cm) if titre != none { set align(center) set text(size: 18pt, fill: primary.dark-blue) strong(titre) } if date != none { set align(center) emph(date) } if lieu != none { set align(center) strong(lieu) } { set align(center) v(0.5em) line(length: 50%, stroke: 0.5pt + primary.dark-blue) v(0.5em) } if toc { set align(center) set par(leading: 1em) outline(title: "Ordre du jour", depth: 2, indent: true) pagebreak() } if type == "odj" { set enum(spacing: 1.25em) let content = box(width: 85%)[ #body ] move(dx: 7.5%,content) } else { body } if redacteur != none { set align(right) v(2em) [_Compte-rendu rédigé par :_] linebreak() redacteur } }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/codly/0.1.0/README.md
markdown
Apache License 2.0
# Codly: simple and beautiful code blocks for Typst Codly is a package that lets you easily create beautiful code blocks for your Typst documents. It uses the newly added [`raw.line`](https://typst.app/docs/reference/text/raw/#definitions-line) function to work across all languages easily. You can customize the icons, colors, and more to suit your document's theme. By default it has zebra striping, line numbers, for ease of reading. ````typ #let icon(codepoint) = { box( height: 0.8em, baseline: 0.05em, image(codepoint) ) h(0.1em) } #show: codly-init.with() #codly(languages: ( rust: (name: "Rust", icon: icon("brand-python.svg"), color: rgb("#CE412B")), )) ```rust pub fn main() { println!("Hello, world!"); } ``` ```` Which renders to: ![Example](./demo.png) You can find all of the documentation in the [example](https://github.com/Dherse/codly/tree/main/example/main.typ) file. ## Short manual ### Setup To start using codly, you need to initialize codly using a show rule: ```typ #show: codly-init.with() ``` Then you need to congigure codly with your parameters: ```typ #codly( languages: ( rust: (name: "Rust", icon: icon("\u{fa53}"), color: rgb("#CE412B")), ) ) ``` Then you just need to add a code block and it will be automatically displayed correctly: ```` ```rust pub fn main() { println!("Hello, world!"); } ``` ```` ### Disabling To locally disable codly, you can just do the following, you can then later re-enable it using the `codly` configuration function. ```typ #disable-codly() ``` ### Setting an offset If you wish to add an offset to your code block, but without selecting a subset of lines, you can use the `codly-offset` function: ```typ // Sets a 5 line offset #codly-offset(5) ``` ### Selecting a subset of lines If you wish to select a subset of lines, you can use the `codly-range` function. By setting the start to 1 and the end to `none` you can select all lines from the start to the end of the code block. ```typ #codly-range(start: 5, end: 10) ``` ### Disabling line numbers You can configure this with the `codly` function: ```typ #codly( width-numbers: none, ) ``` ### Disabling zebra striping You disable zebra striping by setting the `zebra-color` to white. ```typ #codly( zebra-color: white, ) ``` ### Customize the stroke You can customize the stroke surrounding the figure using the `stroke-width` and `stroke-color` parameters of the `codly` function: ```typ #codly( stroke-width: 1pt, stroke-color: red, ) ``` ### Misc You can also disable the icon, by setting the `display-icon` parameter to `false`: ```typ #codly( display-icon: false, ) ``` Same with the name, whether the block is breakable, the radius, the padding, and the width of the numbers columns.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/data-12.typ
typst
Other
// Test reading XML data. #let data = xml("test/assets/files/data.xml") #test(data, (( tag: "data", attrs: (:), children: ( "\n ", (tag: "hello", attrs: (name: "hi"), children: ("1",)), "\n ", ( tag: "data", attrs: (:), children: ( "\n ", (tag: "hello", attrs: (:), children: ("World",)), "\n ", (tag: "hello", attrs: (:), children: ("World",)), "\n ", ), ), "\n", ), ),))
https://github.com/DVDTSB/ctheorems
https://raw.githubusercontent.com/DVDTSB/ctheorems/main/0.1.0/assets/basic.typ
typst
#import "@preview/ctheorems:0.1.0": * #set page(width: 16cm, height: auto, margin: 1.5cm) #set heading(numbering: "1.1.") #let theorem = thmbox("theorem", "Theorem", fill: rgb( "#E1F5FE"),stroke:rgb("#4FC3F7")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em)) #let example = thmplain("example", "Example", numbering:none) #let proof = thmplain( "proof", "Proof", base: "theorem", bodyfmt: body => [#body #h(1fr) $square$], ).with(numbering:none) = Prime numbers #definition[ A natural number is called a _prime number_ if it is greater than 1 and cannot be written as the product of two smaller natural numbers. ] #example[ The numbers $2$, $3$, and $17$ are prime. #thmref(<cor_largest_prime>)[Corollary] shows that this list is not exhaustive! ] #theorem(name: "Euclid")[ There are infinitely many primes. ] #proof[ Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list, it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since $p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a contradiction. ] #corollary[ There is no largest prime number. <cor_largest_prime> ] #corollary[ There are infinitely many composite numbers. ]
https://github.com/loqusion/typix
https://raw.githubusercontent.com/loqusion/typix/main/docs/api/derivations/common/font-paths-example.md
markdown
MIT License
<!-- markdownlint-disable-file first-line-h1 --> <!-- ANCHOR: buildtypstprojectlocal_example --> ```nix { outputs = { nixpkgs, typix }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { apps.${system}.default = typix.lib.${system}.buildTypstProjectLocal { fontPaths = [ "${pkgs.roboto}/share/fonts/truetype" ]; }; }; } ``` <!-- ANCHOR_END: buildtypstprojectlocal_example --> <!-- ANCHOR: buildtypstproject_example --> ```nix { outputs = { nixpkgs, typix }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { packages.${system}.default = typix.lib.${system}.buildTypstProject { fontPaths = [ "${pkgs.roboto}/share/fonts/truetype" ]; }; }; } ``` <!-- ANCHOR_END: buildtypstproject_example --> <!-- ANCHOR: devshell_example --> ```nix { outputs = { nixpkgs, typix }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { devShells.${system}.default = typix.lib.${system}.devShell { fontPaths = [ "${pkgs.roboto}/share/fonts/truetype" ]; }; }; } ``` <!-- ANCHOR_END: devshell_example --> <!-- ANCHOR: mktypstderivation_example --> ```nix { outputs = { nixpkgs, typix }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { packages.${system}.default = typix.lib.${system}.mkTypstDerivation { fontPaths = [ "${pkgs.roboto}/share/fonts/truetype" ]; }; }; } ``` <!-- ANCHOR_END: mktypstderivation_example --> <!-- ANCHOR: watchtypstproject_example --> ```nix { outputs = { nixpkgs, typix }: let system = "x86_64-linux"; pkgs = nixpkgs.legacyPackages.${system}; in { apps.${system}.default = typix.lib.${system}.watchTypstProject { fontPaths = [ "${pkgs.roboto}/share/fonts/truetype" ]; }; }; } ``` <!-- ANCHOR_END: watchtypstproject_example -->
https://github.com/v411e/optimal-ovgu-thesis
https://raw.githubusercontent.com/v411e/optimal-ovgu-thesis/main/expose.typ
typst
MIT License
#import "components.typ": body-font, sans-font, author-fullname #let oot-expose = ( title: "", author: none, lang: "en", document-type: "", city: "", date: "", organisation: [], body ) => { set document(title: title, author: author-fullname(author)) set page( margin: (left: 30mm, right: 30mm, top: 27mm, bottom: 27mm), numbering: "1", number-align: center, ) block( inset: 0cm )[ #set align(center) #text(2em, weight: 700, "Exposé: " + document-type) #par(leading: 0.6em)[ #text(1.6em, weight: 500, title) ] #text(1.2em, weight: 500)[ #v(0.3em) #author-fullname(author) #v(0.3em) #organisation ] ] v(2em) show par: set block(spacing: 1em) set par( leading: 0.7em, justify: true, first-line-indent: 1em ) set text( font: body-font, size: 10pt, lang: lang ) show heading: set text(size: 11pt) // Remove level 1 headings show heading.where(level: 1): h => [] body }
https://github.com/jinhao-huang/SimplePaper
https://raw.githubusercontent.com/jinhao-huang/SimplePaper/main/examples/example.typ
typst
MIT License
#import "simplepaper.typ": * #show: project.with( title: "SimplePaper 模版使用说明", authors: ( ( name: "张三", organization: [Typst Group], email: "<EMAIL>" ), ( name: "李四", organization: [Rust Group], email: "<EMAIL>" ), ), abstract: "本文详细描述了 SimplePaper 模版的使用方法。", keywords: ( "Typst", "模板", "使用说明", ), ) = 模版简介 SimplePaper#cite(<SimplePaper>) 是 Typst 的模版,用于生成简单的论文。 = 使用说明 使用前确保已经安装了对应的字体!详细字体列表参考 #link("https://github.com/1bitbool/SimplePaper/tree/main")[README] 或模板文件。 = 使用示例 <example> == 特殊标记 <bug1> 你可以 Typst 的语法对文本进行特殊标记,模板设定了几种语法的样式:*突出*、_强调_、引用@example。 == 图片 图片标题默认设置了方正楷体,效果如@img 如果你想要使用其他字体,你可以自行修改模版。 #figure(image("sample.svg"), caption: [ 示例图片 ], )<img> 图片后的文字。 == 表格 #figure( table( columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr), inset: 10pt, align: horizon, [], [周一], [周二],[周三],[周四],[周五], "早上", "编译原理", "操作系统", "计算机网络", "操作系统", "计算机网络", "下午", "数据挖掘", "计算机网络", "操作系统", "计算机网络", "分布式系统" ), caption: "示例表格" ) 表格后的文字。 == 代码 我们为代码添加了如下简单的样式。 ```c #include <stdio.h> int main() { // printf() 中字符串需要引号 printf("Hello, World!"); return 0; } ``` 代码后的文字。 == 列表 下面是有序列表的示例: + 第一项 + 第二项 + 第三项 列表后的文字。 下面是无序列表的示例: - 第一项 - 第二项 - 第三项 无序列表后的文字。 #bibliography("ref.bib")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/pad_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that the pad element doesn't consume the whole region. #set page(height: 6cm) #align(left)[Before] #pad(10pt, image("/assets/files/tiger.jpg")) #align(right)[After]
https://github.com/TheOnlyMrCat/tree-sitter-typst
https://raw.githubusercontent.com/TheOnlyMrCat/tree-sitter-typst/master/README.md
markdown
Apache License 2.0
# tree-sitter-typst [Typst](https://github.com/typst/typst) grammar for [tree-sitter](https://github.com/tree-sitter/tree-sitter). Currently in a very early stage. Most scripting elements are not implemented yet, and the syntax tree doesn't necessarily reflect the true structure of the document. Currently implemented syntax includes: - Text: bold, italic, *inline* raw, links, escape sequences, and special characters - Math: symbols, special characters, strings, functions - Scripting: Simple `let` and `set` rules, function calls, numeric literals, comments. Syntax that is still to be implemented includes: - Most scripting functionality - Lists - Raw blocks ## Installation ### Neovim Install [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter). If you're using a premade config, you probably already have it installed. #### Add the parser Source: <https://github.com/nvim-treesitter/nvim-treesitter#adding-parsers> Add the following lua code to your startup file: ```lua local parser_config = require "nvim-treesitter.parsers".get_parser_configs() parser_config.typst = { install_info = { url = "https://github.com/TheOnlyMrCat/tree-sitter-typst", files = { "src/parser.c", "src/scanner.c" }, generate_requires_npm = false, requires_generate_from_grammar = false, }, filetype = "typst", } ``` After doing this, start `nvim` and run `:TSInstall typst`. You only need to do this once. #### Add queries Source: <https://github.com/nvim-treesitter/nvim-treesitter#highlight> Copy the contents of [`queries/`](https://github.com/TheOnlyMrCat/tree-sitter-typst/tree/master/queries) into `.config/nvim/queries/runscript`. #### Add the filetype Add the following lua code to your startup file: ```lua vim.filetype.add({ extension = { typ = "typst", }, }) ``` Or the equivalent vimscript code. #### Enable tree-sitter syntax highlighting Source: <https://github.com/nvim-treesitter/nvim-treesitter#highlight> *If you're using a premade config, this might already be enabled by default. Check your config's documentation for more details* Add the following lua code to your startup file: ```lua require'nvim-treesitter.configs'.setup { highlight = { -- Replace this with `enable = true` to enable tree-sitter highlighting for all buffers enable = { "typst" }, -- See source link for details on this option additional_vim_regex_highlighting = false, }, } ``` ### Helix Add the following to your `languages.toml` file (usually in `~/.config/helix`): ```toml [[language]] name = "typst" scope = "source.typst" injection-regex = "^typ(st)?$" file-types = ["typ"] roots = [] comment-token = "//" [[grammar]] name = "typst" source = { git = "https://github.com/TheOnlyMrCat/tree-sitter-typst", rev = "e3e26aadc728b768bf4fb04df7735e6f700074ef" } ``` Replace the `rev = ` key with the hash of the latest commit (or tag, if you prefer) from this repository Then copy the contents of [`queries/`](https://github.com/TheOnlyMrCat/tree-sitter-typst/tree/master/queries) into `runtime/queries/typst/` (where `runtime` is the helix runtime directory; `$HOME/.config/helix/runtime` on Linux/Mac, `%appdata%\helix\runtime` on Windows) To find your runtime directory, check the first few lines of output of `hx --health`
https://github.com/tshu-w/CV
https://raw.githubusercontent.com/tshu-w/CV/main/en.typ
typst
#import "tmpl.typ": * #let author = "<NAME>" #show: body => tmpl( author: author, lang: "en", textsize: 10pt, body ) = #author #let sep = [ #h(0.5pt) | #h(0.5pt) ] #fa.fa-envelope(solid: true) #link("mailto:<EMAIL>")[<EMAIL>] #sep #fa.fa-github() #link("https://github.com/tshu-w")[github.com/tshu-w] #sep #fa.fa-location-dot() Beijing, China #h(1fr) #link("https://files.tianshu.me/cv/en.pdf")[Online Version] == Education #entry( tl: [*Institute of Software, Chinese Academy of Sciences*], tr: [Sep 2019 - Jul 2025], dl: [PhD of Computer Science and Technology (transfer from Masters to PhD)], dr: [Beijing, China], )[ - Research Intrest: LLM for Data Intelligence (Entity Resolution, Text2SQL, and Structured Text Retrieval) . - GPA: 3.73/4 (2rd), Honors: Outstanding Student, First-Class Academic Scholarship ] #entry( tl: [*Beijing Jiaotong University*], tr: [Sep 2015 - Jul 2019], dl: [Bachelor of Computer Science and Technology], dr: [Beijing, China], )[ - GPA: 91.2/100 (Top 10%), CET-6: 513 ] == Research Experience #entry( tl: [<NAME> _et al._, "Bridging the Gap between Reality and Ideality of Entity Matching: A Revisting and Benchmark Re­Constrcution", in _Proc. of IJCAI 2022_, pp. 3978–3984. doi: #link("https://doi.org/10.24963/ijcai.2022/552")[10.24963/ijcai.2022/552].], tr: [], )[ - Analyze the erroneous assumptions implied in entity matching benchmarks - Construct the first open entity, imbalanced label, and multimodal benchmarks to mitigate evaluation bias ] #entry( tl: [<NAME> _et al._, "DBCopilot: Scaling Natural Language Querying to Massive Databases", _CoRR_, 2023, doi: #link("https://doi.org/10.48550/arXiv.2312.03463")[10.48550/arXiv.2312.03463].], tr: [Submit to ICDE 2025], )[ - Present a LLM-Copilot collaboration framework for scaling natural language querying to massive databases - Propose a relation-aware, generative joint retrieval approach for schema routing ] #entry( tl: [<NAME> _et al._, "Match, Compare, or Select? An Investigation of Large Language Models for Entity Matching", _CoRR_, 2024, doi: #link("https://doi.org/10.48550/arXiv.2405.16884")[10.48550/arXiv.2405.16884].], tr: [Submit to ACL ARR 2024 February], )[ - Investigate different (proposed) strategies for entity matching with LLMs - Propose a compositional framework for more effective and efficient than single strategies ] #entry( tl: [<NAME> _et al._, "Towards Universal Dense Blocking for Entity Resolution", _CoRR_, 2024, doi: #link("https://doi.org/10.48550/arXiv.2404.14831")[10.48550/arXiv.2404.14831].], tr: [], )[ - Pretrain a universal structured record representation model for dense blocking without domain-specific training ] == Work Experience #entry( tl: [*AI Lab Intern* | _ByteDance_], tr: "Feb 2019 - Aug 2019" )[ Contributed to "Precision Answering" for #link("https://www.toutiao.com")[Toutiao Search] by developing and optimizing key components - Mined top frequent unanswered queries daily using _Spark & Hive_ to support forward mining - Filtered CQA data based on rules, question intent, and answer quality/types using _MapReduce_ - Optimized the answer extraction module's efficiency by over 50% through _dynamic programming_ ] == Honors & Awards #entry( tl: [*International Collegiate Programming Contest(ICPC)Asia Regional Contest*], tr: "2016 - 2018", )[ - Gold Medal #sym.times 2: The 42nd Beijing Site, the 43rd Jiaozuo Site - Silver Medal #sym.times 3: The 42nd Urumqi Site, the 42nd, 43rd East Continent Final Contest - Bronze Medal #sym.times 1: The 41st East Continent Final Contest ] #entry( tl: [*China Collegiate Programming Contest(CCPC)*], tr: "2017 - 2018", )[ - Third place #sym.times 1: The 4th National Invitational Contest Hunan Site - Gold Medal #sym.times 3: The 3rd Qinhuangdao Site, the 4th Guilin Site, and Jilin Site ] == Skills - Research Interests: LLM & Agent, Entity Resolution, Text-to-SQL, Information Retrieval - Expertise: Software development, Data Structures & Algorithms, DevOps, Data Analytics - Programming Languages: Python, C++, C, Bash | SQL, Java, Lua, TypeScript - Software: macOS/Linux, Emacs, Git, Docker, Ray, Spark, #LaTeX - Open Source Contributions: contributed to #link("https://github.com/Lightning-AI/pytorch-lightning")[Pytorch Lightning] (10 commits) and #link("https://github.com/pulls?page=4&q=is%3Apr+author%3Atshu-w")[other 33] repositories. #align(right, text(fill: gray, size: 0.9em)[Last Updated on #datetime.today().display("[month repr:short] [day padding:space], [year]")])
https://github.com/dvdvgt/typst-letter
https://raw.githubusercontent.com/dvdvgt/typst-letter/main/examples/example.typ
typst
MIT License
#import "../din5008-letter.typ": letter #show: letter.with( // sender information sender_name: "<NAME>", sender_address: [ Street, street number\ ZIP, City ], sender_contact: [ 0123456789 * | * <EMAIL> ], // receiver address and name receiver: [ Name Surname\ Street, street number\ ZIP, City ], date: "31.12.2099", subject: lorem(10), greeting: "Dear Name Surname", valediction: "Regards", attachments: [ - CV ], accent: rgb(0, 0, 128) ) #lorem(32) #lorem(128) #lorem(320) #lorem(16)
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/003.%20lwba.html.typ
typst
#set page( paper: "a5", margin: (x: 1.8cm, y: 1.5cm), ) #set text( font: "Liberation Serif", size: 10pt, hyphenate: false ) #set par(justify: true) #v(10pt) = Lisp in Web-Based Applications #v(10pt) _(This is an excerpt of a talk given at BBN Labs in Cambridge, MA, in April 2001.)_ == Any Language You Want One of the reasons to use Lisp in writing Web-based applications is that you *can* use Lisp. When you're writing software that is only going to run on your own servers, you can use whatever language you want. For a long time programmers didn't have a lot of choice about what language to use for writing application programs. Until recently, writing application programs meant writing software to run on desktop computers. In desktop software there was a strong bias toward writing the application in the same language as the operating system. Ten years ago, for all practical purposes, applications were written in C. With Web-based applications, that changes. You control the servers, and you can write your software in any language you want. You can take it for granted now that you have the source code of both your operating system and your compilers. If there does turn out to be any kind of problem between the language and the OS, you can fix it yourself. This new freedom is a double-edged sword, however. Having more choices means that you now have to think about which choice to make. It was easier in the old days. If you were in charge of a software project, and some troublesome person suggested writing the software in a different language from whatever you usually used, you could just tell them that it would be impractical, and that would be the end of it. Now, with server-based applications, everything is changed. You're now subject to market forces in what language you choose. If you try to pretend that nothing has changed, and just use C and C++, like most of our competitors did, you are setting yourself up for a fall. A little startup using a more powerful language will eat your lunch. == Incremental Development There is a certain style of software development associated with Lisp. One of its traditions is incremental development: you start by writing, as quickly as possible, a program that does almost nothing. Then you gradually add features to it, but at every step you have working code. I think this way you get better software, written faster. Everything about Lisp is tuned to this style of programming, because Lisp programmers have worked this way for at least thirty years. The Viaweb editor must be one of the most extreme cases of incremental development. It began with a 120-line program for generating Web sites that I had used in an example in a book that I finished just before we started Viaweb. The Viaweb editor, which eventually grew to be about 25,000 lines of code, grew incrementally from this program. I never once sat down and rewrote the whole thing. I don't think I was ever more than a day or two without running code. The whole development process was one long series of gradual changes. This style of development fits well with the rolling releases that are possible with Web-based software. It's also a faster way to get software written generally. == Interactive Toplevel Lisp's interactive toplevel is a great help in developing software rapidly. But the biggest advantage for us was probably in finding bugs. As I mentioned before, with Web-based applications you have the users' data on your servers and can usually reproduce bugs. When one of the customer support people came to me with a report of a bug in the editor, I would load the code into the Lisp interpreter and log into the user's account. If I was able to reproduce the bug I'd get an actual break loop, telling me exactly what was going wrong. Often I could fix the code and release a fix right away. And when I say right away, I mean while the user was still on the phone. Such fast turnaround on bug fixes put us into an impossibly tempting position. If we could catch and fix a bug while the user was still on the phone, it was very tempting for us to give the user the impression that they were imagining it. And so we sometimes (to their delight) had the customer support people tell the user to just try logging in again and see if they still had the problem. And of course when the user logged back in they'd get the newly released version of the software with the bug fixed, and everything would work fine. I realize this was a bit sneaky of us, but it was also a lot of fun. == Macros for Html Lisp macros were another big win for us. We used them very extensively in the Viaweb editor. It could accurately be described as one big macro. And that gives you an idea of how much we depended on Lisp, because no other language has macros in the sense that Lisp does. One way we used macros was to generate Html. There is a very natural fit between macros and Html, because Html is a prefix notation like Lisp, and Html is recursive like Lisp. So we had macro calls within macro calls, generating the most complicated Html, and it was all still very manageable. == Embedded Languages Another big use for macros was the embedded language we had for describing pages, called Rtml. (We made up various explanations for what Rtml was supposed to stand for, but actually I named it after <NAME>, the other founder of Viaweb, whose username is Rtm.) Every page made by our software was generated by a program written in Rtml. We called these programs templates to make them less frightening, but they were real programs. In fact, they were Lisp programs. Rtml was a combination of macros and the built-in Lisp operators. Users could write their own Rtml templates to describe what they wanted their pages to look like. We had a structure editor for manipulating these templates, a lot like the structure editor they had in Interlisp. Instead of typing free-form text, you cut and pasted bits of code together. This meant that it was impossible to get syntax errors. It also meant that we didn't have to display the parentheses in the underlying s-expressions: we could show structure by indentation. By this means we made the language look a lot less threatening. We also designed Rtml so that there could be no errors at runtime: every Rtml program yielded some kind of Web page, and you could debug it by hacking it until it produced the page you meant it to. Initially we expected our users to be Web consultants, and we expected them to use Rtml a lot. We provided some default templates for section pages and item pages and so on, and the idea was that the users could take them and modify them to make whatever pages they wanted. In fact it turned out that Web consultants didn't like Viaweb. Consultants, as a general rule, like to use products that are too hard for their clients to use, because it guarantees them ongoing employment. Consultants would come to our Web site, which said all over it that our software was so easy to use that it would let anyone make an online store in five minutes, and they'd say, there's no way we're using that. So we didn't get a lot of interest from Web consultants. Instead the users all tended to be end-users, the actual merchants themselves. They loved the idea of being in control of their own Web sites. And this kind of user did not want to do any kind of programming. They just used the default templates. So Rtml didn't end up being the main interface to the program. It ended up playing two roles. First of all, it was an escape valve for the really sophisticated users, who wanted something our built-in templates couldn't provide. Somewhere in the course of doing Viaweb, someone gave me a very useful piece of advice: users always want an upgrade path, even though as a rule they'll never take it. Rtml was our upgrade path. If you wanted to, you could get absolute control over everything on your pages. Only one out of every couple hundred users actually wrote their own templates. And this led to the second advantage of Rtml. By looking at the way these users modified our built-in templates, we knew what we needed to add to them. Eventually we made it our goal that no one should ever have to use Rtml. Our built-in templates should do everything people wanted. In this new approach, Rtml served us as a warning sign that something was missing in our software. The third and biggest win from using Rtml was the advantage we ourselves got from it. Even if we had been the only people who used Rtml, it would have been very much worth while writing the software that way. Having that extra layer of abstraction in our software gave us a big advantage over competitors. It made the design of our software much cleaner, for one thing. Instead of just having bits of actual C or Perl code that generated our Web pages, like our competitors, we had a very high-level language for generating Web pages, and our page styles specified in that. It made the code much cleaner and easier to modify. I've already mentioned that Web-based applications get released as a series of many small modifications. When you do that you want to be able to know how serious any given modification is. By dividing your code into layers, you get a better handle on this. Modifying stuff in lower layers (Rtml itself) was a serious matter to be done rarely, and after much thought. Whereas modifying the top layers (template code) was something you could do quickly without worrying too much about the consequences. Rtml was a very Lispy proposition. It was mostly Lisp macros, to start with. The online editor was, behind the scenes, manipulating s-expressions. And when people ran templates, they got compiled into Lisp functions by calling compile at runtime. Rtml even depended heavily on keyword parameters, which up to that time I had always considered one of the more dubious features of Common Lisp. Because of the way Web-based software gets released, you have to design the software so that it's easy to change. And Rtml itself had to be easy to change, just like any other part of the software. Most of the operators in Rtml were designed to take keyword parameters, and what a help that turned out to be. If I wanted to add another dimension to the behavior of one of the operators, I could just add a new keyword parameter, and everyone's existing templates would continue to work. A few of the Rtml operators didn't take keyword parameters, because I didn't think I'd ever need to change them, and almost every one I ended up kicking myself about later. If I could go back and start over from scratch, one of the things I'd change would be that I'd make every Rtml operator take keyword parameters. We had a couple embedded languages within the editor, in fact. Another one, which we didn't expose directly to the users, was for describing images. Viaweb included an image generator, written in C, that could take a description of an image, create that image, and return its url. We used s-expressions to describe these images as well. == Closures Simulate Subroutines One of the problems with using Web pages as a UI is the inherent statelessness of Web sessions. We got around this by using lexical closures to simulate subroutine-like behavior. If you understand continuations, one way to explain what we did would be to say that we wrote our software in continuation-passing style. When most web-based software generates a link on a page, it tends to be thinking, if the user clicks on this link, I want to call this cgi script with these arguments. When our software generated a link, it could think, if the user clicks on this link, I want to run this piece of code. And the piece of code could be an arbitrary piece of code, possibly (in fact, usually) containing free variables whose value came from the surrounding context. The way we did this was to write a macro that took an initial argument expected to be a closure, followed by a body of code. The code would then get stored in a global hash table under a unique id, and whatever output was generated by the code in the body would appear within a link whose url contained that hash key. If that link was the next one clicked on, our software would find and call the corresponding bit of code, and the chain would continue. Effectively we were writing cgi scripts on the fly, except that they were closures that could refer to the surrounding context. So far this sounds very theoretical, so let me give you an example of where this technique made an obvious difference. One of the things you often want to do in Web-based applications is edit an object with various types of properties. Many of the properties of an object can be represented as form fields or menus. If you're editing an object representing a person, for example, you might get a field, for their name, a menu choice for their title, and so on. Now what happens when some object has a property that is a color? If you use ordinary cgi scripts, where everything has to happen on one form, with an Update button at the bottom, you are going to have a hard time. You could use a text field and make the user type an rgb number into it, but end-users don't like that. Or you could have a menu of possible colors, but then you have to limit the possible colors, or otherwise even to offer just the standard Web colormap, you'd need 256 menu items with barely distinguishable names. What we were able to do, in Viaweb, was display a color as a swatch representing the current value, followed by a button that said "Change." If the user clicked on the Change button they'd go to a page with an imagemap of colors to choose among. And after they chose a color, they'd be back on the page where they were editing the object's properties, with that color changed. This is what I mean about simulating subroutine-like behavior. The software could behave as if it were returning from having chosen a color. It wasn't, of course; it was making a new cgi call that looked like going back up a stack. But by using closures, we could make it look to the user, and to ourselves, as if we were just doing a subroutine call. We could write the code to say, if the user clicks on this link, go to the color selection page, and then come back here. This was just one of the places were we took advantage of this possibility. It made our software visibly more sophisticated than that of our competitors.
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/canvas-renderer.typ
typst
#import "@preview/cetz:0.2.0": draw, chart #import "@preview/cetz:0.2.0" // attributables // exposes a get:function on the module #import "attrs.typ" #import "strokes.typ" #import "piecharts.typ" #import "barcharts.typ" #let canvas-functions = ( line: draw.line, circle: draw.circle, rect: draw.rect, group: draw.group, grid: draw.grid, set-style: draw.set-style, piechart: chart.piechart.with(..piecharts.base) ) let sample-json = ( attrs: ( length: 1cm, ), children: ( ( handler: "line", args: ((0, 0), (5, 5)), kwargs:( ) ) ) ) #let data = ( ( value: 17, label: "a", outset: true, ), ( value: 18, label: "b", outset: true, ), ( value: 30, label: "c", outset: false, ), ) // get the color from the data perhaps. #let canvas-renderer(json) = { json = attrs.transform(json) cetz.canvas(..json.canvas-attrs, { for child in json.children { let handler = child.at("handler") let kwargs = child.at("kwargs", default: (:)) let args = child.at("args", default: ()) let fn = canvas-functions.at(handler) fn(..args, ..kwargs) } }) }
https://github.com/LugsoIn2/typst-htwg-thesis-template
https://raw.githubusercontent.com/LugsoIn2/typst-htwg-thesis-template/main/appendix/appendix_example1.typ
typst
MIT License
#import "../lib/utils.typ": todo = Chap Appendix Ipsum <appendix_example1> #lorem(20) == Nonumy #lorem(500) == Stet clita #lorem(100)
https://github.com/leesum1/brilliant-cv
https://raw.githubusercontent.com/leesum1/brilliant-cv/master/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: [2024], title: [Huawei Software Elite Challenge], issuer: [Second Prize in Hangzhou-Xiamen Region], location: [Hangzhou, Zhejiang], ) #cvHonor( date: [2024], title: [Huawei Embedded Systems Competition - Algorithm Group], issuer: [Semifinalist in Hangzhou-Xiamen Region], location: [Hangzhou, Zhejiang], )
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/print-rough-draft.typ
typst
#let print-rough-draft(json) = { set page(paper: "us-letter", columns: 2, margin: 0.25in, numbering: "1") set text(size: 11pt) set par(leading: 1.5em) grid(columns: 2, column-gutter: 15pt, align(block(fill: white, { text(style: "normal", size: 18pt, weight: "bold", json.title) if json.subtitle { v(-10pt) text(style: "normal", size: 11pt, weight: "bold", json.subtitle, font: "Barlow") } }), left), { align(horizon, block(fill: white, { if 1 == 2 { [hiasd\ ] } })) } ) line(length: 100%, stroke: (dash: "dotted")) for paragraph in json.body { text(paragraph) v(20pt) // u can just place the paragraph like this ? // explicitly set the text // you can use negative lengths // line(length: 50%, stroke: (paint: blue, thickness: 0.5pt, dash: "loosely-dotted")) } } let json = read('/home/kdog3682/2024/abc.json') #show: print-rough-draft(json) // boxes make the content fit inside the rules of inline content // blocks force content to be blocky // align can be functionally declared about anywhere. (takes an alignment) // a color scheme can be placed in.
https://github.com/jakoblistabarth/tud-corporate-design-slides-typst
https://raw.githubusercontent.com/jakoblistabarth/tud-corporate-design-slides-typst/main/tud-slides/template.typ
typst
MIT No Attribution
#import "@preview/polylux:0.3.1": polylux-slide, logic, utils, pause, only #let tud-outer-margin = 17pt #let tud-inner-margin = 60.5pt #let tud-top-margin = 85pt #let tud-bottom-margin = 70pt #let tud-title = state("tud-title", none) #let tud-subtitle = state("tud-sub-title", none) #let tud-short-title = state("tud-short-title", none) #let tud-author = state("tud-author", []) #let tud-short-author = state("tud-short-author", none) #let tud-organizational-unit = state("tud-organizational-unit", none) #let tud-date = state("tud-date", none) #let tud-location-occasion = state("tud-location-occasion", none) #let tud-darkblue = rgb(0, 48, 94) #let tud-lightblue = rgb(0, 106, 179) #let tud-gradient = gradient.linear(tud-darkblue, tud-lightblue, angle: 45deg) #let tud-show-guides = state("tud-show-guides", none) #let tud-date-format = "[month repr:long] [day], [year]" #let tud-slides( title: none, subtitle: none, short-title: none, author: none, short-author: none, organizational-unit: none, lang: "en", date: datetime.today(), location-occasion: none, show-guides: false, body ) = { set document(title: title, author: author) let guides = { set line( stroke: (thickness: .5pt, paint: red, dash: "densely-dotted"), length: 100% ) place(line(start: (0cm, .8cm))) place(line(start: (0cm, 60pt))) place(line(start: (0cm, 2.92cm))) place(line(start: (0cm, 14.23cm))) place(line(start: (0cm, 14.933cm))) place(line(start: (0cm, 15.424cm))) place(line(start: (0cm, 16.22cm))) set line(angle: 90deg) place(line(start: (60.5pt, 0cm))) place(line(start: (790pt, 0cm))) } set page( // seems to correspond to 297mm × 167mm (as in the indesign template) paper: "presentation-16-9", margin: 0pt, foreground: context if (tud-show-guides.get() == true) {guides}, ) set text(font: ("Open Sans"), lang: lang, fill: tud-darkblue) set list(marker: [---]) show figure.caption: set text(size: .6em, fill: luma(150)) tud-date.update(date) tud-title.update(title) tud-subtitle.update(subtitle) tud-short-title.update(title) tud-author.update(author) if (short-author == none) { tud-short-author.update(author) } else { tud-short-author.update(short-author) } tud-organizational-unit.update(organizational-unit) tud-location-occasion.update(location-occasion) tud-show-guides.update(show-guides) body } #let title-slide = { let content = { place( rect(fill: tud-gradient, width: 100%, height: 100%) ) block( width: 100%, fill: white, inset: (x: tud-outer-margin, y: 0.8cm), grid( columns: (1fr, auto), image("logos/TU_Dresden_Logo_blau.svg", height: 1.33cm), image("logos/dresden-concept.svg", height: 1.33cm) ) ) place( block( width: 100%, height: 85%, inset: (x: tud-inner-margin), { set align(left + horizon) set text(fill: rgb(255, 255, 255, 150)) text( weight: "bold", context tud-organizational-unit.get() ) linebreak() context tud-short-author.get() parbreak() text(size: 2.5em, fill: white, weight: "bold", context tud-title.get()) parbreak() context tud-subtitle.get() linebreak() context [ #tud-location-occasion.get() \/\/ #tud-date.get().display(tud-date-format) ] } ) ) } polylux-slide(content) } #let footer = block(width: 100%, height: 100%, fill: white)[ #set text(size: 8pt, fill: luma(150)) #block(width: 100%, inset: (x: tud-outer-margin, top: 34pt), align( horizon, grid( columns: (auto, 1fr, .5fr, auto), gutter: 50pt, pad(left: 18.5pt, image( "logos/TU_Dresden_Logo_blau.svg", height: 22pt ), ), { set block(above: .35em) context [#tud-short-title.get()] parbreak() context [#tud-organizational-unit.get() / #tud-short-author.get()] parbreak() context [#tud-location-occasion.get() \/\/ #tud-date.get().display(tud-date-format)] }, [ Slide #logic.logical-slide.display()/#strong(utils.last-slide-number) ], pad(right: 9pt, image( "logos/dresden-concept.svg", height: 22pt ), ) ) ) ) ] #let slide(body) = { // Content block let wrapped-body = block( width: 100%, height: 100%, inset: (x: tud-inner-margin), )[ #set text(16pt) #set block(above: 1.2em) #body ] set page( margin: ( top: tud-top-margin, bottom: tud-bottom-margin ), footer: footer, footer-descent: 0pt, ) polylux-slide(wrapped-body) } #let fluid-slide(body) = { // Content block let wrapped-body = block( width: 100%, height: 100%, )[ #set text(16pt) #set block(above: 1.2em) #body ] set page( margin: ( bottom: tud-bottom-margin ), footer: footer, footer-descent: 0pt, ) polylux-slide(wrapped-body) } #let section-slide(title: none, subtitle: none) = { // Content block let wrapped-body = block( width: 100%, height: 100%, inset: (x: tud-inner-margin), )[ #set align(horizon) #set text(2.5em, fill: white) #set block(above: .5em) #text(weight: "bold", title) #parbreak() #text(fill: rgb(255, 255, 255, 150), subtitle) ] set page( margin: ( top: tud-top-margin, bottom: tud-bottom-margin ), footer: footer, footer-descent: 0pt, background: { rect(width: 100%, height: 100%, fill: tud-gradient) }, ) polylux-slide(wrapped-body) }
https://github.com/jneug/typst-finite
https://raw.githubusercontent.com/jneug/typst-finite/main/util.typ
typst
MIT License
#import "@preview/t4t:0.3.2": get, def, is, assert, math #import "@preview/cetz:0.1.1": vector, matrix, draw #import draw: util, styles, cmd, coordinate #import util.bezier: cubic-point, cubic-derivative, cubic-through-3points // ================================= // Defaults // ================================= #let default-style = ( state: ( fill: auto, stroke: auto, radius: .6, label: ( text: auto, size: auto, ), ), transition: ( curve: .75, stroke: auto, label: ( text: "", size: 1em, color: auto, pos: .5, dist: .33, angle: auto, ), ), ) // ================================= // Vectors // ================================= /// Set the length of a vector. #let vector-set-len(v, len) = if vector.len(v) == 0 { return v } else { return vector.scale(vector.norm(v), len) } /// Compute a normal for a 2d vector. The normal will be pointing to the right /// of the original vector. #let vector-normal(v) = vector.norm((-v.at(1), v.at(0), 0)) /// Returns a vector for an alignment. #let align-to-vec(a) = { let v = ( ("none": 0, "left": -1, "right": 1).at(repr(get.x-align(a, default: none))), ("none": 0, "top": 1, "bottom": -1).at(repr(get.y-align(a, default: none))), ) return vector.norm(v) } /// Rotates a vector by #arg[angle] degree around the origin. #let vector-rotate(vec, angle) = { let (x, y, ..) = vec return ( calc.cos(angle) * x - calc.sin(angle) * y, calc.sin(angle) * x + calc.cos(angle) * y, ) } // ================================= // Bezier // ================================= /// Compute a normal vector for a point on a cubic bezier curve. #let cubic-normal(a, b, c, d, t) = { let qd = cubic-derivative(a, b, c, d, t) if vector.len(qd) == 0 { return (0, 1, 0) } else { return vector-normal(qd) } } /// Compute the mid point of a quadratic bezier curve. #let mid-point(a, b, c, d) = cubic-point(a, b, c, d, .5) // ================================= // Helpers // ================================= /// Calculate the control point for a transition. #let cubic-pts(a, b, curve: 1) = { if curve == 0 { return (a, b, b, a) } let ab = vector.sub(b, a) let X = vector.add( vector.add( a, vector.scale(ab, .5), ), vector.scale( vector-normal(ab), curve, ), ) return cubic-through-3points(a, X, b) } /// Calculate the direction vector for a transition mark (arrowhead) #let mark-dir(a, b, c, d, scale: 1) = vector-set-len(cubic-derivative(a, b, c, d, 1), scale) /// Calculate the location for a transitions label, based /// on its bezier points. #let label-pt(a, b, c, d, style, loop: false) = { let pos = style.label.at("pos", default: default-style.transition.label.pos) let dist = style.label.at("dist", default: default-style.transition.label.dist) let curve = style.at("curve", default: default-style.transition.curve) let pt = cubic-point(a, b, c, d, pos) let n = cubic-normal(a, b, c, d, pos) if loop and curve < 0 { dist *= -1 } return vector.add( pt, vector.scale(n, dist), ) } /// Calculate start, end and ctrl points for a transition loop. /// /// - start (vector): Center of the state. /// - start-radius (length): Radius of the state. /// - curve (float): Curvature of the transition. /// - anchor (alignment): Anchorpoint on the state #let loop-pts(start, start-radius, anchor: top, curve: 1) = { anchor = vector-set-len(align-to-vec(anchor), start-radius) let end = vector.add( start, vector-rotate(anchor, -22.5deg), ) let start = vector.add( start, vector-rotate(anchor, 22.5deg), ) if curve < 0 { (start, end) = (end, start) } else if curve == 0 { curve = start-radius } let (start, end, c1, c2) = cubic-pts(start, end, curve: curve) if curve < 0 { (c1, c2) = (c2, c1) } let d = vector.scale(vector.sub(c2, c1), curve * 4) c1 = vector.sub(c1, d) c2 = vector.add(c2, d) return (start, end, c1, c2) } /// Calculate start, end and ctrl points for a transition. /// /// - start (vector): Center of the start state. /// - end (vector): Center of the end state. /// - start-radius (length): Radius of the start state. /// - end-radius (length): Radius of the end state. /// - curve (float): Curvature of the transition. #let transition-pts(start, end, start-radius, end-radius, curve: 1, anchor: top) = { // Is it a loop? if start == end { return loop-pts(start, start-radius, curve: curve, anchor: anchor) } else { let (start, end, ctrl1, ctrl2) = cubic-pts(start, end, curve: curve) start = vector.add( start, vector-set-len( vector.sub( ctrl1, start, ), start-radius, ), ) end = vector.add( end, vector-set-len( vector.sub( end, ctrl2, ), -end-radius, ), ) return ( start, end, ctrl1, ctrl2, ) } } /// Fits (text) content inside the available space. /// /// - ctx (dictionary): The canvas context. /// - content (string, content): The content to fit. /// - size (length,auto): The initial text size. /// - min-size (length): The minimal text size to set. #let fit-content(ctx, width, height, content, size: auto, min-size: 6pt) = { let s = def.if-auto(ctx.length, size) let m = (width: 2 * width, height: 2 * height) while (m.height > height or m.width > height) and s > min-size { s = s * .88 m = measure( { set text(s) content }, ctx.typst-style, ) } s = calc.max(min-size, s) { set text(s) content } } /// Prepares the CeTZ context for use with finite #let prepare-ctx(ctx, force: false) = { if force or "finite" not in ctx { // supposed to store state information at some point ctx.insert("finite", (states: ())) // add default state styles to context if "state" not in ctx.style { ctx.style.insert("state", default-style.state) } else { if "label" in ctx.style.state and not is.dict(ctx.style.state.label) { ctx.style.state.label = (text: ctx.style.state.label) } ctx.style.state = styles.resolve(default-style.state, ctx.style.state) } // add default transition styles to context if "transition" not in ctx.style { ctx.style.insert("transition", default-style.transition) } else { if "label" in ctx.style.transition and not is.dict(ctx.style.transition.label) { ctx.style.transition.label = (text: ctx.style.transition.label) } ctx.style.transition = styles.resolve(default-style.transition, ctx.style.transition) } } return ctx } // Changes a transition table from the format (`state`: `inputs`) to (`input`: `states`) or vice versa. #let transpose-table(table) = { let ttable = (:) for (key, values) in table { let new-values = (:) if is.not-none(values) { for (kk, vv) in values { for i in def.as-arr(vv) { if is.not-none(i) { i = str(i) if i not in new-values { new-values.insert(i, (kk,)) } else { new-values.at(i).push(kk) } } } } } ttable.insert(key, new-values) } return ttable } /// Gets a list of all inputs from a transition table. #let get-inputs(table, transpose: true) = { if transpose { table = transpose-table(table) } let inputs = () for (_, values) in table { for (inp, _) in values { if inp not in inputs { inputs.push(str(inp)) } } } return inputs.sorted() } /// Creates a full specification for a finite automaton. #let to-spec(spec, states: auto, initial: auto, final: auto, inputs: auto) = { if "transitions" not in spec { spec = (transitions: spec) } if "states" not in spec { if is.a(states) { states = spec.transitions.keys() } spec.insert("states", states) } if "initial" not in spec { if is.a(initial) { initial = spec.states.first() } spec.insert("initial", initial) } if "final" not in spec { if is.a(final) { final = (spec.states.last(),) } else if is.n(final) { final = () } spec.insert("final", final) } if "inputs" not in spec { if is.a(inputs) { inputs = get-inputs(spec.transitions) } spec.insert("inputs", inputs) } else { spec.inputs = spec.inputs.map(str).sorted() } return spec } // Unused #let calc-bounds(positions) = { let bounds = ( x: positions.first().at(0), y: positions.first().at(1), width: positions.first().at(0), height: positions.first().at(1), ) for (x, y) in positions { bounds.x = calc.min(bounds.x, x) bounds.y = calc.min(bounds.y, y) bounds.width = calc.max(bounds.width, x) bounds.height = calc.max(bounds.height, y) } bounds.width = bounds.width - bounds.x bounds.height = bounds.height - bounds.y return bounds } #let calc-shift(anchor, bounds: none) = { let shift = (x: -.5, y: -.5) if anchor.ends-with("right") { shift.x -= .5 } else if anchor.ends-with("left") { shift.x += .5 } if anchor.starts-with("top") { shift.y -= .5 } else if anchor.starts-with("bottom") { shift.y += .5 } if bounds != none { shift.x *= bounds.width shift.y *= bounds.height } return shift } #let shift-by-anchor(positions, anchor) = { let bounds = calc-bounds(positions.values()) let shift = calc-shift(anchor, bounds: bounds) for (name, pos) in positions { let (x, y) = pos positions.at(name) = (x + shift.x, y + shift.y) } return positions } #let resolve-radius(state, style) = if state in style and "radius" in style.at(state) { return style.at(state).radius } else if "state" in style and "radius" in style.state { return style.state.radius } else { return default-style.state.radius }
https://github.com/matryt/modules-typst
https://raw.githubusercontent.com/matryt/modules-typst/main/fancy-boxes/1.0.0/lib.typ
typst
#let formula(body, number, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#EF8E05"), inset: 8pt, radius: 4pt, [*Formule #number* - #title\ #body] ) } #let remark(body, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#3DA708"), inset: 8pt, radius: 4pt, [*Remarque* - #title\ #body] ) } #let definition(body, number, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#B20000"), inset: 8pt, radius: 4pt, [*Définition #number* - #title\ #body] ) } #let propriete(body, number, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#0063A6"), inset: 8pt, radius: 4pt, [*Propriété #number* - #title\ #body] ) } #let theoreme(body, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#A60086"), inset: 8pt, radius: 4pt, [*Théorème #title*\ #body] ) } #let fast_formula(body, number, title:"") = { set text(fill:white) set align(center) block( fill: rgb("#EF8E05"), inset: 8pt, radius: 4pt, [*Form. #number* (#title): #body] ) }
https://github.com/LauHuiQi0920/3007DataVisualizationTeamCyan
https://raw.githubusercontent.com/LauHuiQi0920/3007DataVisualizationTeamCyan/main/poster/_extensions/poster/typst-template.typ
typst
// 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): block.with( 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 empty(v) = { if type(v) == "string" { // Check for empty string by comparing directly to an empty string v.trim() == "" } 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 } } #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, new_title_block + old_callout.body.children.at(1)) } #show ref: it => locate(loc => { let target = query(it.target, loc).first() if it.at("supplement", default: none) == none { it return } let sup = it.supplement.text.matches(regex("^45127368-afa1-446a-820f-fc64c546b2c5%(.*)")).at(0, default: none) if sup != none { let parent_id = sup.captures.first() let parent_figure = query(label(parent_id), loc).first() let parent_location = parent_figure.location() let counters = numbering( parent_figure.at("numbering"), ..parent_figure.at("counter").at(parent_location)) let subcounter = numbering( target.at("numbering"), ..target.at("counter").at(target.location())) // NOTE there's a nonbreaking space in the block below link(target.location(), [#parent_figure.at("supplement") #counters#subcounter]) } else { it } }) // 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]) + block( inset: 1pt, width: 100%, block(fill: white, width: 100%, inset: 8pt, body))) } #let poster( // The poster's size. size: "'36x24' or '48x36''", // The poster's title. title: "Paper Title", // A string of author names. authors: "<NAME> (separated by commas)", // Department name. departments: "Department Name", // University logo. univ_logo: "Logo Path", // Footer text. // For instance, Name of Conference, Date, Location. // or Course Name, Date, Instructor. footer_text: "Footer Text", // Any URL, like a link to the conference website. footer_url: "Footer URL", // Email IDs of the authors. footer_email_ids: "Email IDs (separated by commas)", // Color of the footer. footer_color: "Hex Color Code", // Text color of the footer. footer_text_color: "Hex Color Code", // DEFAULTS // ======== // For 3-column posters, these are generally good defaults. // Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters. // For 2-column posters, you may need to tweak these values. // See ./examples/example_2_column_18_24.typ for an example. // Any keywords or index terms that you want to highlight at the beginning. keywords: (), // Number of columns in the poster. num_columns: "3", // University logo's scale (in %). univ_logo_scale: "45", // University logo's column size (in in). univ_logo_column_size: "10", // Title and authors' column size (in in). title_column_size: "25", // Poster title's font size (in pt). title_font_size: "48", // Authors' font size (in pt). authors_font_size: "36", // Footer's URL and email font size (in pt). footer_url_font_size: "30", // Footer's text font size (in pt). footer_text_font_size: "40", // The poster's content. body ) = { // Set the body font. set text(font: "Arial", size: 15pt) let sizes = size.split("x") let width = int(sizes.at(0)) * 1in let height = int(sizes.at(1)) * 1in univ_logo_scale = int(univ_logo_scale) * 1% title_font_size = int(title_font_size) * 1pt authors_font_size = int(authors_font_size) * 1pt num_columns = int(num_columns) univ_logo_column_size = int(univ_logo_column_size) * 1in title_column_size = int(title_column_size) * 1in footer_url_font_size = int(footer_url_font_size) * 1pt footer_text_font_size = int(footer_text_font_size) * 1pt // Configure the page. // This poster defaults to 36in x 24in. set page( width: width, height: height, fill: rgb(249, 249, 249), margin: (top: 1in,bottom: 2in, left: 1.5in, right: 1.5in), footer: [ #set align(center) #set text(32pt, white) #block( fill: rgb(170, 55, 52), width: 100%, inset: 20pt, [ //#text(font: "Courier", size: footer_url_font_size, footer_url) //#h(1fr) #text(size: footer_text_font_size, smallcaps(footer_text)) #h(1fr) #text(font: "Courier", size: footer_url_font_size, footer_email_ids) ] ) ] ) // Configure equation numbering and spacing. set math.equation(numbering: "(1)") show math.equation: set block(spacing: 0.65em) // Configure lists. set enum(indent: 10pt, body-indent: 9pt) set list(indent: 10pt, body-indent: 9pt) // Configure headings. //set heading(numbering: "I.A.1.") show heading: it => locate(loc => { // Find out the final number of the heading counter. let levels = counter(heading).at(loc) let deepest = if levels != () { levels.last() } else { 1 } set text(24pt, weight: 400) if it.level == 1 [ // First-level headings are centered smallcaps. #set align(left) #set text(28pt) #set text(weight: 700) #set text (fill: rgb(170, 55, 52)) #show: smallcaps #v(50pt, weak: true) #if it.numbering != none { numbering("I.", deepest) h(7pt, weak: true) } #it.body #v(30pt, weak: true) ] else if it.level == 2 [ // Second-level headings are run-ins. #set text(style: "normal") #set text(20pt) #set text(weight: 700) #v(32pt, weak: true) #if it.numbering != none { numbering("i.", deepest) h(7pt, weak: true) } #it.body #v(10pt, weak: true) ] else [ // Third level headings are run-ins too, but different. #if it.level == 3 { numbering("1)", deepest) [ ] } _#(it.body):_ ] }) // Arranging the logo, title, authors, and department in the header. align(left, grid( rows: 2, columns: (title_column_size, univ_logo_column_size), column-gutter: 40pt, row-gutter: 25pt, block( fill: rgb(170, 55, 52), inset: 25pt, width: 100%, text(fill: rgb(255, 255, 255), title_font_size, title + "\n\n") + text(fill: rgb(255, 255, 255), authors_font_size, strong(text(fill: rgb(171, 255, 255), authors)) + " (" + departments + ") ") ), image(univ_logo, width: univ_logo_scale), ) ) // Start three column mode and configure paragraph properties. show: columns.with(num_columns, gutter: 64pt) set par(justify: true, first-line-indent: 0em) show par: set block(spacing: 0.65em) // Display the keywords. if keywords != () [ #set text(24pt, weight: 400) #show "Keywords": smallcaps *Keywords* --- #keywords.join(", ") ] // Display the poster's contents. body } // Typst custom formats typically consist of a 'typst-template.typ' (which is // the source code for a typst template) and a 'typst-show.typ' which calls the // template's function (forwarding Pandoc metadata values as required) // // This is an example 'typst-show.typ' file (based on the default template // that ships with Quarto). It calls the typst function named 'article' which // is defined in the 'typst-template.typ' file. // // If you are creating or packaging a custom typst template you will likely // want to replace this file and 'typst-template.typ' entirely. You can find // documentation on creating typst templates here and some examples here: // - https://typst.app/docs/tutorial/making-a-template/ // - https://github.com/typst/templates #show: doc => poster( title: [#strong[Mapping Crime in the Los Angeles: A Visual Journey (2020-2024)];], // TODO: use Quarto's normalized metadata. authors: [<NAME>], departments: [Information and Communication Technologies], size: "33x23", // Institution logo. univ_logo: "./imgs/sit-logo.png", // Footer text. // For instance, Name of Conference, Date, Location. // or Course Name, Date, Instructor. footer_text: [Information Visualization 2024], // Any URL, like a link to the conference website. // Emails of the authors. footer_email_ids: [singaporetech.edu.sg], // Color of the footer. footer_color: rgb(205,5,5), // Text color of the footer. // DEFAULTS // ======== // For 3-column posters, these are generally good defaults. // Tested on 36in x 24in, 48in x 36in, and 36in x 48in posters. // For 2-column posters, you may need to tweak these values. // See ./examples/example_2_column_18_24.typ for an example. // Any keywords or index terms that you want to highlight at the beginning. // Number of columns in the poster. // University logo's scale (in %). // University logo's column size (in in). // Title and authors' column size (in in). // Poster title's font size (in pt). // Authors' font size (in pt). // Footer's URL and email font size (in pt). // Footer's text font size (in pt). doc, ) #block( fill: rgb(243, 241, 241), inset: 30pt, width: 100% )[ = Introduction <introduction> Crime in America is a significant concern, impacting the safety and well-being of residents, businesses, and tourism. There has been a sharp rise in motor vehicle thefts, which increased by 25% from 2019 to 2022#footnote[#link("https://www.marketwatch.com/guides/insurance-services/car-theft-statistics/");] ,demonstrating the need for continued efforts to curb the crime rate. #v(1em) Understanding and identifying areas with high crime rates can significantly enhance law enforcement training and preparation. Data consistently shows that neighborhoods such as South Los Angeles remain prevalent with violent crime#footnote[#link("https://www.latimes.com/california/story/2023-10-12/violent-crime-is-down-fear-is-up-why-is-la-perceived-as-dangerous");];. Utilizing past statistical data and quantifiable information to identify hotspots allows law enforcement agencies to allocate resources more efficiently and maximize safety. #v(1em) Examining crime distribution in Los Angeles, a Medium visualization focuses on the University of Southern California’s University Park campus, using blue dots to represent crime incidents #footnote[#link("https://towardsdatascience.com/visualizing-crime-in-los-angeles-14db37572909/");] (@fig-wsj-on-poster). While straightforward, the plot could be refined for better clarity and impact. ] #block( fill: white, // Set the background color inset: 30pt, width: 100% )[ = Previous Visualization #line( start: (0%, 0%), end: (100%, 0%), stroke: 3pt + rgb(170, 55, 52) ) <previous-visualization> #block[ #block[ #figure([ #box(width: 100%,image("imgs/bad_graph.jpeg")) ], caption: figure.caption( position: bottom, [ Crime distribution around USC, published by the Medium. ]), kind: "quarto-float-fig", supplement: "Figure", numbering: "1", ) <fig-wsj-on-poster> ] ] ] #block( inset: 30pt, width: 100% )[ = Strengths <strengths> + Alpha was used on the circles allowing darker spots to appear if overlapped. + A gentle blue color was used, making it easy for users to identify crime-affected spots. The chosen color effectively contrasts with the map's background, enhancing visibility without clashing. + An area with good distribution was picked, as there are clusters displayed on the map. + As the mouse is hovered over the circles, the exact number of crimes is displayed through a tooltip \(@fig-infotip), allowing the user to see the exact number of crimes in that area . #block[ #block[ #figure([ #box(width: 100%,image("imgs/combined.png")) ], caption: figure.caption( position: bottom, [ Crime distribution around USC, published by the Medium. ]), kind: "quarto-float-fig", supplement: "Figure", numbering: "1", ) <fig-infotip> ] ] ] #block( inset: 30pt, width: 100% )[ = Suggested Improvements <suggested-improvements> + #strong[State layer view:] separated with area code, performs better visualization of the crime distribution. A localize view does not represent a crime spread well for meaningful actions. + #strong[Identify type of crime clearly:] A clearer view of top crime should be labeled and display. + #strong[Add missing title and guides:] Title should be used for clear description + #strong[Add missing guides:] Guides should be used to show clear distinction of color shade to total crime count. + #strong[Use a saturation color palette:] Shows a meaningful progression through color space. Saturation palettes shows cold to hot zone allowing human to see intensity of an area. + #strong[Label locations:] Labeling popular city center allow enforcer to see crime distribution and easily identify the areas with high crime rate. + #strong[Add crime types for each area:] Displaying the top 3 crimes in each area allows for better understanding of the crime distribution and provides additional information. ] #block( fill: rgb(243, 241, 241), // Set the background color inset: 30pt, width: 100% )[ = Implementation <implementation> == Data <data> - The data used spans from January 1, 2020, to June 7, 2024, and is sourced from the universal crime data for Los Angeles#footnote[#link("https://data.lacity.org/Public-Safety/Crime-Data-from-2020-to-Present/2nrs-mtv8/data_preview");]. Unlike the subset of data ending in 2021 used in the previous visualization (@fig-wsj-on-poster), this dataset offers a more comprehensive view. Although there are datasets available for the years 2010 to 2019#footnote[#link("https://catalog.data.gov/dataset/crime-data-from-2010-to-2019");], they were not used due to differing formats. == Software <software> We used the Quarto publication framework and the R programming language, along with the following third-party packages: - #strong[#text(rgb(170, 55, 52))[dplyr]] for data manipulation - #strong[#text(rgb(170, 55, 52))[tidyverse]] for data transformation, including #strong[#text(rgb(170, 55, 52))[ggplot2]] for visualization based on the grammar of graphics - #strong[#text(rgb(170, 55, 52))[readxl]] for data import - #strong[#text(rgb(170, 55, 52))[lubridate]] for date and time manipulation - #strong[#text(rgb(170, 55, 52))[DT]] for interactive data tables - #strong[#text(rgb(170, 55, 52))[knitr]] for dynamic document generation - #strong[#text(rgb(170, 55, 52))[pals]] for qualitative color palettes - #strong[#text(rgb(170, 55, 52))[RColorBrewer]] for sequential color palettes ] #block( fill: white, // Set the background color inset: 30pt, width: 100% )[ = Improved Visualization #line( start: (0%, 0%), end: (100%, 0%), stroke: 3pt + rgb(170, 55, 52) ) <improved-visualization> #block[ #block[ #figure([ #box(width: 100%,image("imgs/plot.png")) ], caption: figure.caption( position: bottom, [ Top 3 crimes and total crimes by area. ]), kind: "quarto-float-fig", supplement: "Figure", ) ] ] ] #block( inset: 30pt, width: 100% )[ = Further Suggestions for Interactivity <further-suggestions-for-interactivity> While our visualization was designed for a poster, interactive features were not implemented. However, in an HTML document, these features can be achieved using various R packages. #strong[#text(rgb(170, 55, 52))[ggplot2]] allows for #strong[hover, drag, zoom, and export];, which improves accessibility for people with sight disabilities by enabling zoom to increase text size. #strong[#text(rgb(170, 55, 52))[Shiny]] facilitates the #strong[sorting of graphs] to clearly differentiate categories and provides #strong[dynamic input];, such as displaying the distribution of only robbery crimes throughout the state. Additionally, #strong[#text(rgb(170, 55, 52))[plotly]] offers #strong[customized tooltips] with ggplot2, expands long town names, and shows exact numbers without crowding. By #strong[darkening borders] and adding shadows, plotly highlights areas when hovered, enhancing the overall user experience. ] #block( fill: rgb(250,236,236), // Set the background color inset: 30pt, width: 100% )[ = Conclusion <conclusion> The revised crime visualization for Los Angeles (2020-2024) improves on previous versions by adding area labels, a saturation color palette, and comprehensive guides. Highlighting the top three crime types per area provides deeper insights into local patterns. These enhancements make the visualization more complex yet user-friendly, aiding law enforcement in resource allocation and strategy development, and ultimately contributing to improved community safety. ]
https://github.com/sofianedjerbi/ResumeOld
https://raw.githubusercontent.com/sofianedjerbi/ResumeOld/main/modules/education.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Formation") #let lightbold(str) = text(weight: 501, str) #cvEntry( title: [Magistère de Mathématiques], society: [Institut Fourier], date: [2022 - 2023], location: [Grenoble], description: list( [ #lightbold[Acquis pertinents:] Topologie algébrique, Analyse complexe, Systèmes dynamiques, Théorie des nombres, Analyse fonctionnelle, Théorie des groupes, Modélisation mathématique et simulation numérique, Introduction à la recherche en mathématiques ] ) ) #cvEntry( title: [Magistère d'Informatique], society: [IM²AG], date: [2021 - 2022], location: [Grenoble], description: list( [ #lightbold[Acquis pertinents:] Ingénierie et Architecture Logicielle, Algorithmique et Structures de Données, Systèmes d'Exploitation, Réseaux et Sécurité Informatique, Intelligence Artificielle et Machine Learning, Introduction à la recherche en informatique ] ) ) #cvEntry( title: [Licence Mathématiques-Informatique], society: [Université Grenoble Alpes], date: [2019 - 2022], location: [Grenoble], description: list( [ #lightbold[Acquis pertinents:] C++, C, Python, SQL, Algèbre Linéaire et Géométrie, Analyse Réelle, Bases de Données, Optimisation Continue, Optimisation Discrète, Machine Learning, Théorie des Graphes, Modélisation Mathématique, Complexité et Calculabilité ] ) )
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/3%20-%20PB/Documentazione%20interna/Verbali/24-02-29/24-02-29.typ
typst
#import "/template.typ": * #show: project.with( date: "29/02/24", subTitle: "Meeting post colloquio con Proponente", docType: "verbale", authors: ( "<NAME>", ), timeStart: "17:10", timeEnd: "17:25", ); = Ordine del giorno A seguito dell'incontro con il Proponente, il gruppo ha svolto un meeting interno riguardante: - Considerazioni scaturite dal meeting esterno; - Pianificazione. == Considerazioni scaturite dal meeting esterno Il gruppo: - ha esaminato le osservazioni del Proponente riguardo lo schema ER e ha concordato sul considerarlo come definitivo; - si è ritenuto soddisfatto del mock-up presentato e della discussione avuta con il Proponente, che ha portato a una rivalutazione di alcune funzionalità; - ha esaminato le considerazioni fatte riguardanti architettura e design, e ritiene essenziale anche un riscontro da parte del #cardin, al quale sono stati esposti i dubbi via mail. == Pianificazione Il gruppo ha fatto il punto sulla situazione dello sprint in corso, segnalando un andamento positivo sull'andamento dei lavori. In particolare le task scaturite dall'esito di questo meeting riguardano: + aggiornamento dell'#adr con le nuove considerazioni funzionali individuate, in particolare: - inserimento della lunghezza in metri del lato maggiore del magazzino per lo scaling dell'ambiente a partire da un SVG; - ridimensionare l'ambiente e conseguente scaling di tutti gli elementi del piano; - notificare l'utente della presa in carico dell'operazione di spostamento da parte del sistema con una notifica toast; - possibilità di visualizzare tutti gli spostamenti effettuati dall'utente nella sessione corrente; - possibilità che uno scaffale sia sempre eliminabile anche quando non vuoto: - i prodotti contenuti nello scaffale vengono visualizzati come "non assegnati" nell'apposita lista; - l'utente può assegnare tali prodotti ad altri bin vuoti. - possibilità di modificare gli scaffali anche quando non vuoti nei seguenti casi: - l'utente vuole aumentare le dimensioni di uno scaffale; - l'utente vuole diminuire le dimensioni di uno scaffale e le modifiche apportate non comportano l'eliminazione di bin pieni (requisito desiderabile). - uno scaffale deve avere un numero di colonne uguale in ogni ripiano, ognuna con larghezza omogenea. + implementazione delle modifiche apportate al diagramma ER al database.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/048%20-%20Dominaria%20United/008_Faith%20in%20Birds.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Faith in Birds", set_name: "Dominaria United", story_date: datetime(day: 17, month: 08, year: 2022), author: "<NAME>", doc ) The leonin's fur was the color of sunset over the Great Desert—tawny with winding stripes of chestnut—and it was smooth and pleasant to the touch. The fascia underneath was warm, very warm, which meant the life growing just beneath the skin was healthy and strong. Niambi caressed it with knowing, continuing her delicate examination of the mother-to-be's pregnant belly. Then, she felt a kick. "Oh, that was a strong one," she exclaimed, her attentive human eyes lifting to meet her patient's feline ones. The expecting mother's whiskers quivered happily at the declaration, and the nostrils of her pink tiger nose flared. Her name was Pallar. "Does that mean it's a boy?" Pallar asked, her jowls stretching to a wide simper, exposing a gleaming row of white canines. "Hm. Could be~" Niambi replied coolly. She felt another kick. They both did. Even harder this time. "But girls~ have a bit more tenacity." She winked, and the two of them laughed. "The child will be here any day now. Have you settled on a name yet?" Pallar shook her head bashfully. Niambi gave her belly a brush of her hand. "My daughter was a kicker, too," said Niambi. "Kequia. It means 'fighter.' That's what she was before she was born—a fighter. She was unhappy being stuck in such a tight space. When she arrived, #emph[early] I will add, she gave such a stretch I thought she was ready to run down the street. I knew right then, if she ever put her mind to something, she could never be held back." Pallar smiled. "Her mother's child." As Pallar spoke, she placed her hand on Niambi's and gave it a small squeeze. Her palm was rough—the tiger pads that covered it were calloused from a life spent outdoors, a nomadic existence, as the many refugees had—but her five nimble digits, humanlike, curled delicately. Her sharp claws remained retracted. It was a sign of deep gratitude. "You have been such a friend to the Efravan," Pallar began softly, "when so many of your kind have not. You bring us food and medicines. Provide healing to our wounds. Give us words of hope that we will soon be safe behind the city walls. For that, we are so very grateful." She paused a moment, as her voice began to quiver with emotion. Then, she asked, "Are you not afraid the magistrate will shun you along with us outsiders?" #emph[Outsiders] , Niambi repeated in her mind. The word carried such negative connotation. The Efravan had been wandering the Great Desert for weeks, hoping to escape the conflicts spreading throughout their homeland. The southern nations were at war, and they sought to escape the violence and the bloodshed. The aggressions were sparked by fears of invasion from an evil once thought to have been expelled from Dominaria—the Phyrexians. These outsiders were just trying to survive. Niambi smiled at Pallar's question, then turned her hand over to take it fully in hers. She held it tenderly, allowing the thumb to gently comb over her soft fur. Her other hand remained on Pallar's swollen belly, as she stared into the dark, amber-ringed well of Pallar's watering eyes. "There is no need to worry about me," she replied simply, but paused a moment as if processing a sad thought. Then, she continued, "I still hold sway with him. I still have his ear." Niambi said the words with fervency, trying to convince herself that this were still true. He had not called for her in three days now. "Is it because you can read dreams?" Niambi chuckled softly at the oversimplified notion and to mask her apprehension. "Well, not so much #emph[read] ," she replied. "I find the patterns—connections—hidden within them that become clear in time. Clarity calms the troubled heart. And in these times of trouble, we all need clarity." Pallar's eyes were wide, quivering with tears that beckoned for more. "For instance, in a recent dream, I saw a flock of birds searching for a home over a vast ocean. They were exhausted, having flown for days with no rest until they came upon an island. And on that island was a single tree. They were so thankful to have found a place to rest, but when they came to land on it, they saw it was sick with disease. Deadly insects were ravaging its bark and withering its fruit. With nowhere else to go, all hope seemed lost. But then the smallest of the flock dove into the bevy of branches, where it disappeared." "And what happened?" asked Pallar in a whisper. "Several followed the little bird, and they found it~ eating the insects!" Niambi gave a small laugh. "They all followed suit, devouring every bug until the tree was clear. Now the fruit could grow, and the tree could bloom." "What does it mean?" "The birds are you, and this city is the tree. You are meant to be here because there is something incredible within you." "Really?" asked Pallar, a hopeful gleam in her eye. "What do we have in us?" "Well, I am still working through the pattern. But eventually all eyes will be open to the truth." Pallar's gaze left Niambi's. "#emph[Eventually] ," Pallar muttered with disappointment, as she knew, like Niambi, that time was of the essence. A dangerous, ancient enemy was steadily approaching from over the horizon, one that would destroy anyone and everyone she held dear if they could not get behind the city walls. Niambi gave her hand an encouraging squeeze. "#emph[Eventually] is taking a bit longer than expected but~" "We are ready," came a stern voice from behind them. Niambi turned over her shoulder and Pallar sat up from her relaxed position on her cot to behold a tall figure standing in the doorway of Pallar's makeshift tent. Against the setting sun, the cat ears and pronounced whiskers gave the newcomer away as an Efravan, but more than that, the muscular build and suit of armor showed them to be a strong warrior among the tribe. Niambi knew her. The wilderness had hardened her, made her single-minded. She was fiercely loyal to her people, and their safety was paramount. She stepped forward into the tent, and the shadows on her tough face fell away, exposing the wear of battle. "You took the words right out of my mouth, <NAME>," said Niambi, standing and bowing her head in respect. #figure(image("008_Faith in Birds/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Please, Niambi," Pallar groaned, her mood lifting instantly with her arrival, "we are past pleasantries. You are our family now." "Even still, history looks kindly on descendants of the great Jaeger and Jedit Ojanen, true champions of Jamuraa." Niambi replied with a smile. "Our greatest generals have studied their paths. They forever deserve our deference." Zar moved forward and placed her hands warmly on her shoulders. "And thanks to you, his legacy will be preserved," she said. "Sister," Pallar whispered, beckoning her to come. Zar hurried past Niambi and kneeled beside Pallar, falling into her open arms. With the utmost tenderness, the two touched their foreheads together and purred into one another. They were two inseparable siblings who had endured so many hardships and heartbreaks, the most painful of which came directly from the magistrate. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Three days prior, Niambi held audience with him and the Council of Voices in the Great Chamber to protest a decree handed down to the people of Femeref that forbade them from donating food, medical aid, or the daily necessities one might need to survive in the harsh desert to the Efravan caravan. The Council was comprised of ten people who sat in three levels above the ground in the circular great hall, each seat separated by an ivory pillar. Four of them sat on the first level, three were on the second, two on the first, and across from them, seated upon a raised, embroidered throne of sorts, a hard-faced man of a ripe age and cloudy eyes, was <NAME>. Sidar was the title given to him, as he was one of the highest-ranking generals and military tacticians in Femeref's history. His brilliance in battle came from studying ancient wars and battles throughout Jamuraa, and he held a deep reverence for leaders who overcame insurmountable odds. Scholars, judicial and religious leaders, economists, and army generals, both of human and dwarven birth, made up the Council of Voices. Each member was draped in flowing robes of orange, white, and gold, with textured hoods draping their shoulders. Despite the occasional squabble over the allocation of certain resources and methods for expansion, the group consorted harmoniously, especially on the issue of the Efravan caravan. A throat cleared loudly, calling for attention. "When their supplies run out," began one of the councilors, a hint of arrogance in her voice, "and they understand that we will not replenish them, these tribes will do what they have done for years—just move on." "How is that, <NAME>?" Niambi asked the short-haired, small-faced woman seated at the center of the second level. "How will they #emph[move on] without water or food? There are those who are old and infirm. Pregnant mothers, too." Another figure leaned forward from a rather blithe, comfortable position—his hands clasped over his large belly. His name was <NAME>, and he joined the dialogue. "In the midst of conflict, dear woman, tough decisions must be made," he asserted. "We are unified on ours." "But there is no conflict. We have one common enemy~" "The Phyrexian machine," Jabras exclaimed, nodding vigorously. There came a fearful grumble from the other Council members. Its awakening was felt three weeks ago, as an earthquake in the ground. Femeref scouts returned to the city in a panic with reports that a terrifying mechanical creature of gargantuan size and strength had emerged from beneath the sand, and it was steadily making its way to Femeref. #figure(image("008_Faith in Birds/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) It was on a mission of destruction, and it would reach the walls in just a few days' time. "We are all on the same side," Niambi announced to the members. "Who is to say #emph[that ] is the case?" The third opposing voice, a seasoned one, resonated clearly through the rotunda, although the one who spoke, a man of rough, dark skin and white, braided hair, had his face buried in a large book. The haughtiness in his tone came through just as clear. Niambi stared up at the man, who was seated in the highest row. She almost had to squint to make him out. Though the sunlight was beaming through the many skylights spanning the ceiling, it was blocked by his head, which cast his face in shadow. But several thin, raised scars, laid vertical on his forehead, running into his braids, took Niambi's eye; he was one of the few who kept the more superstitious traditions of the ancients. "I can," Niambi replied firmly, refusing to bend to his airs. "You?" the councilman stung, nonchalantly turning another page in his book. "The outsiders have only been here~ two weeks now. There's no way to know what they're truly capable of." "I apologize," Niambi said sharply, her jaw tightening and eyes narrowing, "but I do not believe I have met you before." "Well, public servants, like yourself, are seldom invited to High Council meetings," the councilman replied, ignoring Niambi's bristles. "Speakers are relegated to their provinces, as you always have been, but our most honorable magistrate, #emph[for some uncertain reason] , urged us to hear your complaint." "To which I, and the #emph[outsiders] , very much appreciate," Niambi fired back with a thin smile. "She is a friend and loyal citizen of Femeref," announced Teshunda heartily. His voice was husky and his phrases terminated with a croak. "I take her counsel very seriously. It has been a great help over these many years, councilman~" "Councilman~?" Niambi urged, almost demanding to know his name. "Awateh." The man slammed his book closed with a sound that echoed through the hall as he spoke. "Grand Historian of Femeref." A tense silence fell over the room, as the historian and Niambi eyed one another. His face was now exposed, and he appeared somewhat familiar. He was nearly the same age as the magistrate; the wrinkled skin about the eyes was similar to his. It was the long, shaggy white beard, however, that struck a chord in her. She had only seen the man up close once—at a burial ceremony for the previous magistrate. His beard was black then. Niambi was a novice-in-training at the time and shadowing a speaker for the ceremony. Speakers played an integral role in reciting the rights and rituals of the dead, ensuring the spirits of those who had passed on were blessed properly and solace was brought to their loved ones. Those who recorded the success of the ceremony, ensuring the rights were upheld, were the historians. Awateh was at that ceremony, tediously documenting what had transpired there. Teshunda cleared his throat, bringing Niambi's focus back to him and severing the line of scrutiny between Niambi and the historian. Then, he spoke, "Historian Awateh brought some disturbing information about the Efravan to my attention." "Oh?" Niambi replied, turning over her shoulder to meet the magistrate's gaze. "The Efravan tribes have had a rather sordid past I'm told," he went on. "They were aligned with Yawgmoth at one time and may be still." Niambi almost let out a laugh at the absurdity of the remark. Teshunda continued, "Believe me, I had the same response: how could a people who had their homelands destroyed by that vile being and his decrepit offspring be consorts with evil?" He paused to take a breath, then, "The answer~" His eyes motioned to the historian. "They just don't know it yet," said Awateh with a smile, rising to his feet. "I don't—understand," said Niambi, appalled that he was entertaining the notion. "Yawgmoth's descendants are many, and they delight in the torture of our world's varied creatures," Awateh began. "Especially those on the outskirts—those of the scattered tribes of Jamuraa. These tribes, you see, have little holding them together; no leader and no homeland to tie themselves to, so it can be assured~" "Assumed~" "#emph[Assured] that many a tribesmen would have wandered off~ alone~ far from the little safety of the group. These individuals would indeed find themselves in such precarious situations, captured in a deadly Phyrexian hold. Their bodies would then be exploited; their innards replaced by such wicked machinery." "Yawgmoth is dead," asserted Niambi. "Basing your decisions on old fears is folly~" "His legacy lives on nonetheless," Awateh replied. He widened his address to the rest of the Council. "Who's to say one of these Efravan, whom you so ardently protect, is not a possessed wanderer who later rejoined the cat tribe? Who's to say there aren't ten of these among them? Twenty? A hundred even?" "You would condemn hundreds for fear of the #emph[possibility ] that one or two among them are sleeper agents? We can root them out #emph[after ] the Efravans are safe." Niambi retorted. "Not if their minds have been wiped," spoke Gbega. "I've been told by numerous, completely credible sources that the enemy can steal your memories. You wouldn't know if you were infected until it was too late!" "The Phyrexians!" Jabras exclaimed. The phrase was again followed by grumbles of the other Council members, which were gradually growing into angry shouts. They were indeed unified in their rebuke. Awateh continued to stoke the fire. "There are Phyrexians out there, hiding in plain sight behind the wall!" he seethed. "And they wear the skin of cats!" "Sleeper agents, Niambi," added Teshunda, slowly standing to his feet, gripping his embroidered, wooden cane. He too had been stirred by Awateh's words. "We cannot take the risk!" Niambi stared back to the magistrate, outraged. "You are all basing your prejudice on rumor and hearsay?!" "Of all people, you should know hearsay is subjective, daughter of Teferi," hissed Awateh. "We speak truth." Niambi gritted her teeth at the attack. Jabras and Gbega both sprang to their feet. "The—Phyrexians!" "WILL YOU SHUT UP!" Niambi shouted. Her voice boomed with the strike of thirty drums at once. It was a power she, as a Speaker, had learned to call upon when addressing large crowds in open spaces. But these were confined quarters, which made the command that more intense. The room immediately fell silent. Niambi looked about the Council, at their angry, scrunched faces. Her eyes climbed the rows until they met an enormous ivory bust of Asmira, the Holy Avenger, affixed to the largest pillar. She was a prophet whose wisdom and guidance had saved the city from destruction in the Mirage War, when the wizard Kaervek tried to conquer Northern Jamuraa. The bust was adorned with a bejeweled hood and royal head-dressing, surrounded by a halo of golden spears. The depiction was breathtaking, as the artist had captured her legendary beauty and fierceness perfectly. Her eyes looked down upon Niambi standing in the middle of that room, amid so much aggression, and they seemed to smile with approval, urging her to continue the fight. Niambi rushed to the foot of the magistrate's seat, falling to one knee. "Magistrate~#emph[Teshunda] , please~ do not be swayed by so much fear! I beg you! Come see the Efravan! Talk to them~ !" "How dare you—how dare you speak to the Council of Voices in that way!" shouted another member of the Council suddenly. "She—she must be removed, magistrate!" asserted a second. "Have her removed now!" The full Council erupted in protest to Niambi's presence, every member stomping their feet and shaking their fists. Niambi leaned into Teshunda, aiming her words directly at his heart. "Remember your dream? The birds. The tree. The pattern is getting clearer. We cannot be on the wrong side of it~" Teshunda raised his hand, silencing her and the irate councilmembers. He took a long moment to consider her before he spoke. "The Council of Voices is united," he said with a forceful tone. "Our decision to protect this city and rebuke those who cluster outside our walls is final and for the greater good." "Teshunda, please don't!" Niambi pleaded. "Guards!" Teshunda averted his eyes as Niambi tried to meet them. "Escort our Esteemed Speaker out. We have other matters to attend to." "Nothing is more pressing than this!" "Out!" Teshunda shouted, driving Niambi back on her heels. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "We made great progress today," said Zar with pride, bringing Niambi back to the present. "The tunnel to the abandoned mine is complete." "Good news," Niambi replied softly, although with a slight reluctance. "But it is my hope the Council will finally realize their error, and we will not have to go that route." "It is easier to ask forgiveness than permission," she quickly responded. Zar spoke simply and pointedly, never wasting a breath. Her eyes narrowed, as he looked upon Pallar's belly. "Especially when there are so many lives on the line." Niambi nodded, hearing her urgency and understanding it. A large part of her was afraid for them and what would happen next—afraid the Phyrexians would murder and devour them; and even more afraid the Council's forces would stop them from making it to the safe place—an abandoned gold mine—she had found for them beyond the wall. The latter was something she dreaded to risk. "I have told the caravan to prepare," Zar went on with a determined vigor. "Only take what we can carry. When night falls and the first stars shine, we will move." "That is the plan," Niambi affirmed. "And your husband?" "Denik has assured me that every warrior has been called to the walls to defend the city. There will be no patrols where we are taking you. He's there now, setting the rest of your stores of food, wood, water~" She paused a moment. "What is it, Niambi?" asked Pallar. Niambi took a breath, then spoke: "I want to meet with the magistrate one last time." Zar's eyes widened with anger and surprise. "Alone this time. I'm sure~ I #emph[believe] speaking with him, sitting down with him, without #emph[certain] voices present, will change his mind~" "You have tried your best to advocate for us too many times already!" Zar shot back at her, rising to her feet. "The Phyrexian machine will be here at tomorrow's sunrise!" "Exactly why I must try again while there is still time. The punishment you face if we are found out will be severe." "The Efravan have faced far worse and survived!" "I know. But I refuse to accept that you—any of you—could be put in prison, your sister left to give birth in a dungeon—without exhausting every effort~" "Phyrexian scum!" came a sudden, distant shout, cutting through their dialogue. It was followed by a bout of laughter—the laughter of several men. Neither Niambi, Zar, or Pallar had to exit to know who was firing the curses. It was the soldiers on the wall. "You'll die before you ever enter this city!" Then, the loud weeping of several elderly Efravan women slowly passing the tent took their attention. Niambi turned her head slightly over her shoulder in acknowledgment, allowing the women's cries to fulfill their full arc. Her heart broke for them. "We will not wait!" Zar roared with frustration, baring her sharp teeth. Her tail whipped the air. "They think we are monsters, Niambi!" Unbeknownst to her and Pallar both, the palms of Niambi's hands began to take on a soft glow, turning the skin from a light blush to a quiet, simmering saffron. The eyes of Asmira flashed in Niambi's mind. "The magistrate will see reason," Niambi pushed. "He will see truth." Pallar, who had been laying on her back on a small grass cot, shifted with extreme uncertainty. "But will he accept it?" she asked. Niambi crossed over to her and placed her glowing hands on her belly. "It is by instinct and faith my people have survived as well," she began. "Since the disappearance of Zhalfir, our ancestors have instilled a nature of wariness in us—an unspoken vigilance to maintain our way of life against the unknown. That is true. But we have not forgotten that hundreds of years before—when Kaervek sought to destroy us all—#emph[faith] in Asmira, our great prophet, who interpreted the visions and dreams of my father, who thought #emph[outside ] of what was deemed the only path forward, brought us victory and life. Faith saved us then, and it will save you now." "Your hands," Pallar whispered, the glaze of worry slowly melting from her eyes, "they feel like the sun." The baby gave another kick but allowed its paw to remain outstretched, to linger in the warmth of Niambi's hand. "Fear," Niambi continued, "is like an icy wind that can turn the kindest heart cold. The magistrate is afraid of what he does not know, but a warm touch from a trusted friend can melt the ice away." "Asmira." Pallar's eyes, brimming with tears, were now back on Niambi. Hope was burning in them. "We know the stories. You're like her, aren't you? You're the one we must put our faith in." Pallar turned to her sister who still had her back to both. Her fists were clenched tight, and he quaked with frustration. "Sister," she said gently. "Let her try one more time." The simple sound of Pallar's voice seemed to calm her. Her shoulders settled. "You have till the moon is at its highest point in the sky," she said with a grumble. "Then we go." Niambi immediately set off. She arrived at the magistrate's home just as the sun was beginning to set. It was a massive structure with a tile roof, surrounded by orchards and gardens of blooming acacia trees. The guards standing outside knew her, she had been to his villa many times for dream interpretation, and they greeted her with a simple nod, which she exchanged. However, as she went to pass them, they crossed their spears in her path. "What are you doing?" Niambi asked. "We are under attack, Esteemed Speaker," the tallest of the two soldiers spoke. "We suggest you return to your home for your safety." "I will be only a moment," Niambi responded. "I come with new—dire news—about the Phyrexian machine approaching. He is expecting me~" "Apologies," spoke the second. "There is no admittance into the estate. We have orders." "Orders~" Niambi began but halted her speech for half a moment, an idea forming. The eyes of the soldiers did not appear hardened; their hearts were not immovable stones. They just needed some convincing. She shifted her focus back to the tall one. "Your name is Esbo, is it not?" "It is," Esbo replied. "Understand, I have not come here only for the sake of the magistrate but out of concern for the subjects of this house—you, in particular." "Me?" Esbo asked with fearful curiosity. Niambi nodded back at him. "Yes—you and your role in the battle to save our city." Her hands had begun to glow. "You see, I was plagued by such terrible dreams last night: I saw a doe trapped in a bed of mud. She called desperately to the fawn she was meant to protect to stay away, promising she would soon be free, and they could leave together. With each step she took, she sank deeper into the quagmire, her window of escape closing—not an escape from the earth meant to swallow her, but from an enormous beast that approached from the shadows. The fawn jumped about the perimeter of the muddy patch, unsure of what to do to save her and unaware of the beast that had its eyes fixed upon him." She paused a moment. "Do you know who you are in my dream, Esbo?" Esbo shook his head with concern. "The fawn," the second solider chimed. Niambi placed her glowing hands upon the hands that gripped the crossed spears. At the same time, the two inhaled, being filled with the light of the sun. "You are the mud," said Niambi. "I am the doe; the magistrate is the fawn I am trying to protect from the danger that will soon fall upon us. I am here to protect our dear magistrate; I only want to share with him the knowledge he needs to know before it is too late. Please, release me." Touched by her words and the sun magic running through them, the guards allowed her through. Slipping through the front doorway, Niambi bounded down a long hall toward a large golden door at the end—the magistrate's chambers. Two servants in white robes were lighting torches along the hall—a young man and a young woman. They greeted her with a nod like the others, but as she passed, seeing the determination in her face, one of them spoke up. "The magistrate is not here, Esteemed Speaker," said the young woman. Niambi halted and turned to them. "No?" she asked, confused as to why the old man was gone at this hour. "The sun is nearly set." "He has not slept in his room for several days now." "He's not slept at all, really," the young man chimed. "Fear of the Phyrexian's return, I suppose." #emph[Fear.] The wheels in Niambi's mind began to turn. Perhaps, it was a pang of conscience—the guilt one might feel if they were to let a nation of innocent people perish—that kept him awake. She couldn't help but feel a bit of satisfaction at the notion. All of them should be ashamed for turning a blind eye to suffering. But then the feeling changed to a fear of her own. If the magistrate was indeed filled with shame, why had he not reversed his decision? His moments of sleeplessness were often triggered by bad dreams from the previous night. If it was this bad, why hadn't he summoned her? Someone else was in his ear. "Where is he now?" Niambi asked. "The Great Chamber," answered the young woman. "That is where he stays now. Even after Council meetings have ended, he remains there~ talking to himself a great deal." "Alone?" asked Niambi. "To start," the man responded. "Then Councilmembers Gbega, Jabras, and Awateh usually join his company." Indeed. "Is it true that Phyrexians are hiding among the cat people outside the walls, Esteemed Speaker?" asked the woman. "There are rumors~" Niambi, burning with fury, rushed toward the door without giving an answer. She exited down the stone steps and entered the street. Where she would have normally found a bustling scene of people heading to and fro, she found it empty—the people sheltered in their homes for fear of the invasion. However, at the end of the street was a single carriage and driver, awaiting a potential fare. She ran to the driver and climbed in. "To the Great Chamber, please," she said, and the driver cracked the reins to set them. A short time later, Niambi arrived at the Great Chamber to find the magistrate seated upon a fountain in the courtyard. The carriage waited in the front. The guards about the perimeter, each one familiar with her gift, having felt her warmth, saw her as a welcomed comfort for the ailing magistrate and did not impede her march toward him. The feeble man was staring into the water, trembling beneath the weight of his heart. "You have not been sleeping, magistrate," said Niambi, as she approached. The magistrate slammed his staff on the stone-tiled ground more to silence her than to stabilize himself. "And #emph[you] have been with them," he scolded, though his breathing was labored, his body hunched over. "You have been consorting with the cat tribes, when you are needed here, with your people, to quiet their spirits and convince them that the danger advancing on our borders is a mild one!" He shot her a daggered glare over his shoulder as he spoke. It was a glare Niambi parried with a stern grimace of her own. "A #emph[mild] one?" said Niambi. "Hundreds will die." "I know~ but~" His resolve seemed to be crumbling in that moment. "But~" "Whose spirit is the one that truly needs quieting?" Niambi asked, studying him. Teshunda's eyes suddenly softened. He turned his face back to the fountain. Niambi could sense a yearning to express some deep truth, a biting anxiety he was holding in, and the need to speak was wafting off him like waves of heat rising from the sand. There was such fear. Her hands began to pulse with soft gold light. "Magistrate, when those of us who love and can love, think on the preciousness of life, something will inevitably rise up to meet us. We love and can love, so we cannot ignore misery or turn a blind eye to suffering, especially when it is right at our doorstep." She placed her hand upon his, and the two of them sat in silence for a long moment. Teshunda turned his face to the heavens. The moon was near its highest point in the sky. "Why have you not been sleeping?" Niambi asked a second time. "The night after you came to Council," Teshunda began after a moment. "I had the same dream about the wandering birds. Except this time~ the tree was me. I saw my arms withered and full of holes. The insects were eating me alive, making their way inside my bones, my heart. I have never felt pain in a dream, but in this one, I could feel everything. It was a pain that lingered when I opened my eyes. It has been inescapable. And the strangest part of it all, in the dream, the little bird who came to me asked if #emph[I] needed its help. I did need its help, desperately. I was dying. But I~ refused. I said, 'I don't know you.' And it flew away. I have not been able to sleep since, Niambi. Tell me what it means." Niambi looked upon him with empathy, saddened by how this champion of Femeref had been sundered by nightmares and cruel gossip. Then a thought came to her. #emph[It's better to ask forgiveness than permission. ] She stared up at the moon with him, sure Zar and her people would be on the move. "I would like you to come somewhere with me," she said softly. "Where?" he asked, looking to her. She turned to him as well and smiled. "To meet your bird." Moments later, when the two of them had settled into the seats of the carriage and the horses were readying to move, Niambi saw the doors to the Great Chamber open. Awateh, Gbega, and Jabras exited. Awateh's book was open, and the three were engaged in fervent conversation, probably deciding which new piece of history they could recite to further quiet the magistrate's conscience. The crack of the reins stole their attention. "Magistrate?!" called Gbega, pointing at the carriage which was now on the move. "Niambi?!" followed Jabras. Niambi straightened. "You'll kill us all!" screamed Awateh, bounding toward his horse. The others quickly followed. The ride to the mine was long, and Niambi kept her hand in the magistrate's the entire time. With the warmth of the sun filling him, Teshunda dozed off to sleep. Niambi was thankful for this. With some welcomed reprieve from his troubled thoughts—a good dream—the old man could look on this situation with more compassionate eyes. The carriage jolted to a stop at the entrance of the mine, stirring the magistrate awake. He looked around, confused, unfamiliar with this section of the city—a secluded place, surrounded by dust and high rocks. He did not panic, however. Niambi's hand was still glowing in his. The sound of a baby's cry stole their attention, bringing it to the dark opening of the mine, where the glow of torchlight was slowly penetrating the blackness. "Is that a child I hear?" Teshunda asked bemusedly. "We can love and do love, dear magistrate," Niambi replied, tears in her eyes. Pallar had had her child. "Let us go meet her." The two of them entered the mine and began a slow trek down the tunnel, Niambi's heart beaming with pride. The plan had worked. The Efravan would live. As they came closer to their destination, the sounds of laughter could be heard, some gentle humming and the vocal hoisting of the last Efravan into safety. Light from the torches on the walls showed figures hugging one another and dancing with joy. "Who are they?" asked Teshunda. "They are a people who needed someone to speak for them because they are not allowed to speak for themselves. They are a people who needed someone to stand up for what is right and good and just, even though it might be hard." Teshunda looked at her. "Who have you brought here?" "Birds in search of rest upon an embittered tree." The magistrate's eyes widened. "Fear is a corrupting emotion that withers the fruit we are meant to give. That is what your dream means. The fruit you are meant to give is~" "Salvation," Teshunda whispered softly. Niambi gave his hand a squeeze. "Mother," came a small voice from the shadows, as a man holding the hand of a teenage girl and a torch approached. "Kequia, my darling girl," Niambi smiled, she and the magistrate meeting them halfway. The young girl was the spitting image of Niambi. She wore a golden headband that pushed her thick tufts of dark curls back. Denik, her father and Niambi's husband, was a handsome man of around fifty years. His hair was dreaded, fixed in a loose bun atop his head and adorned with rings of gold. With a small smile, Niambi brushed a glowing hand on her daughter's cheek, which made her smile. Kequia leaned into the hand, accepting the warmth it provided, just as Pallar's child had done. "And our son, Mabutho?" Niambi asked her husband. "He and his wife are pouring water and giving blankets to~" Denik gasped suddenly, bowing his head. He eyed Niambi. "Why is the magistrate #emph[here] ?" Niambi took the torch from him and placed it in Teshunda's hand. "To see the truth," she said. With a gentle touch to Teshunda's back, she allowed him to now lead the journey around the bend to the dancing Efravan. Almost immediately, he was brought face to face with Zar, who stood holding her crying niece. Pallar stood beside her, one hand on her back and the other resting upon her daughter's head. The revelry ceased in that moment, and all went quiet as they beheld the newcomer in their midst. Teshunda stared at all of them, taking in the scene of mothers hugging their children to them, husbands shielding their wives, the entirety of a forlorn people silently praying for the right to exist. His eyes moved back to Zar, whose face remained hard as stone. The armor on the Efravan's body and the great sword sheathed upon her back told Teshunda all he needed to know about the woman. "You are Ojanen," he said. "Descendant of Jaeger and Jedit, champions of Jamuraa?" "I am," Zar replied firmly, standing taller, allowing the pride of her past to shine out of her. "I revere them," said Teshunda softly. "They were warriors who never wavered in their loyalty to their people, who fought the great fight to the very end. They truly inspired me. #emph[Helped ] me. Leaders like them are the reason I am who I am today." "I can say the same," Zar replied. Teshunda's took in the child cradled in Zar's arm, swaddled in a blanket. His heart seemed to melt at the sight. "And this—is your child?" "#emph[Lark] is her name," Pallar replied. "Like a little bird, she soared into this world, settled upon a dying tree~ meant to do something wonderful." Niambi smiled as she held her own daughter. Her eyes met Pallar's, and the two of them nodded with thankfulness to one another. Teshunda looked back up at Zar, straightening. "Z<NAME>, what will you do when the Phyrexian abomination has been defeated? Where will you go?" "When the threat has passed, we will do what we have always done—move on." "No, you will not," said the magistrate sternly. "The arrival of that machine is only the beginning, and in the wars to come, we will need loyal allies at our side. You will stay here. You will stay here with us." "Magistrate, no! You can't!" came shouts from Awateh, Jabras, and Gbega, who had suddenly entered the mine and were now violently pushing their way through the crowd that had gathered around the magistrate. "Sleeper agents! Sleeper agents are among them!" they shouted together. "Stop," said Teshunda to the Council members, who obeyed immediately. While looking back at Niambi, he spoke again. "We can no longer let our fear corrupt us. If an enemy finds his way in our midst, we must have faith that champions who stand among us will rise up and defeat them." Then, he turned back, taking in the sea of hopeful, tear-filled eyes staring back at him and said, "Welcome to Femeref." #figure(image("008_Faith in Birds/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none)
https://github.com/alberto-lazari/cv
https://raw.githubusercontent.com/alberto-lazari/cv/main/modules_en/skills.typ
typst
#import "/common.typ": * = Skills #skill( type: [Programming Languages], info: ("Java", "Shell", "Ruby", "Kotlin", "Python", "C++", "Ocaml") ) #skill( type: [Technologies], info: ("Ruby on Rails", "Spring Boot", "Git", "Gradle") ) #skill( type: [Interests], info: ("Shell Scripting", "CLI Enthusiast", "FOSS", "Typst") ) #skill( type: [Languages], info: ("Italian (native)", "English (B2)") )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-2DE0.typ
typst
Apache License 2.0
#let data = ( ("COMBINING CYRILLIC LETTER BE", "Mn", 230), ("COMBINING CYRILLIC LETTER VE", "Mn", 230), ("COMBINING CYRILLIC LETTER GHE", "Mn", 230), ("COMBINING CYRILLIC LETTER DE", "Mn", 230), ("COMBINING CYRILLIC LETTER ZHE", "Mn", 230), ("COMBINING CYRILLIC LETTER ZE", "Mn", 230), ("COMBINING CYRILLIC LETTER KA", "Mn", 230), ("COMBINING CYRILLIC LETTER EL", "Mn", 230), ("COMBINING CYRILLIC LETTER EM", "Mn", 230), ("COMBINING CYRILLIC LETTER EN", "Mn", 230), ("COMBINING CYRILLIC LETTER O", "Mn", 230), ("COMBINING CYRILLIC LETTER PE", "Mn", 230), ("COMBINING CYRILLIC LETTER ER", "Mn", 230), ("COMBINING CYRILLIC LETTER ES", "Mn", 230), ("COMBINING CYRILLIC LETTER TE", "Mn", 230), ("COMBINING CYRILLIC LETTER HA", "Mn", 230), ("COMBINING CYRILLIC LETTER TSE", "Mn", 230), ("COMBINING CYRILLIC LETTER CHE", "Mn", 230), ("COMBINING CYRILLIC LETTER SHA", "Mn", 230), ("COMBINING CYRILLIC LETTER SHCHA", "Mn", 230), ("COMBINING CYRILLIC LETTER FITA", "Mn", 230), ("COMBINING CYRILLIC LETTER ES-TE", "Mn", 230), ("COMBINING CYRILLIC LETTER A", "Mn", 230), ("COMBINING CYRILLIC LETTER IE", "Mn", 230), ("COMBINING CYRILLIC LETTER DJERV", "Mn", 230), ("COMBINING CYRILLIC LETTER MONOGRAPH UK", "Mn", 230), ("COMBINING CYRILLIC LETTER YAT", "Mn", 230), ("COMBINING CYRILLIC LETTER YU", "Mn", 230), ("COMBINING CYRILLIC LETTER IOTIFIED A", "Mn", 230), ("COMBINING CYRILLIC LETTER LITTLE YUS", "Mn", 230), ("COMBINING CYRILLIC LETTER BIG YUS", "Mn", 230), ("COMBINING CYRILLIC LETTER IOTIFIED BIG YUS", "Mn", 230), )
https://github.com/EGmux/PCOM-2023.2
https://raw.githubusercontent.com/EGmux/PCOM-2023.2/main/lista2/lista2q1.typ
typst
=== Sabe-se que um sinal $x(t)$ é unicamente determinado por suas amostrar quando a frequência de amostragem é $ω_a = 10000 π$ rad/s. Para que valores de $ω$ garante-se que o espectro de $x(t)$ é nulo? \ Ora se o sinal é unicamente determinado é porque não há interferência da amostragem dos espectros\ do mesmo, consequentemente a frequência do enunciado é a de Nyquist o que implica que é duas vezes a maior frêquência do espectro do sinal #figure( image("../assets/q1fig1.png", width: 80%), caption: [Exemplo de possível espectro], ) <fig-q1fig1> \ Ou seja a cada múltiplo de $5000 π$ rad/s é garantido que o espectro do sinal seja nulo.// TODO: checar gabarito da questão
https://github.com/MrToWy/Bachelorarbeit
https://raw.githubusercontent.com/MrToWy/Bachelorarbeit/master/Chapters/Planung/use-cases.typ
typst
#import "../../Template/customFunctions.typ": * #useCase(1, "Informationen zu Studiengang")[ Der Use Case beschreibt, wie eine studieninteressierte Person einen Überblick über alle Module eines Studienganges erhalten kann. Die Person möchte hierzu ein PDF erhalten, in dem alle Module und deren Eigenschaften aufgelistet sind. ][ Studieninteressierte Person (@studieninteressiertePerson) ][ Der Studiengang ist im System hinterlegt. ][ 1. Die Person besucht die Website der #hsh 2. Der gesuchte Studiengang wird aufgerufen 3. Die Seite des Studiengangs enthält eine Verlinkung zum System StudyModules 4. Die Person klickt im neuen System auf "PDF anzeigen" 5. Das System zeigt das PDF an ]<UseCaseInfoDegree> #useCase(2, "Informationen zu Modul")[ Der Use Case beschreibt, wie eine studierende Person Informationen zu einem bestimmten Modul erhalten kann. Dabei können die angebotenen Module mithilfe einer Filterfunktion oder Suchfunktion durchsucht werden. Zum Beispiel könnte die studierende Person auf der Suche nach einem spannenden Wahlpflichtfach sein. ][ Studierende Person (@student) ][ Der Studiengang ist im System hinterlegt. ][ 1. Die Person besucht die Website der #hsh 2. Der gesuchte Studiengang wird aufgerufen 3. Die Seite des Studiengangs enthält eine Verlinkung zum System StudyModules 4. Im neuen System werden alle Module aufgelistet 5. Die Person filtert nach allen Wahlpflichtfächern 6. Die Person öffnet ein Modul 7. Informationen zum ausgewählten Modul werden in einer modernen Oberfläche angezeigt ]<UseCaseInfoModule> #useCase(3, "Modul bearbeiten")[ Der Use Case beschreibt, wie Informationen eines Moduls verändert werden können. Das System prüft dabei, ob die angegebenen Informationen plausibel sind. Beispielsweise müssen Zeitaufwände und ECTS zusammenpassen. ][ Modulverantwortliche Person (@modulverantwortlicher) ][ Erfolgreich mit einem Account eingeloggt, der das ausgewählte Modul bearbeiten darf ][ 1. User drückt auf "Bearbeiten" 2. System wechselt in den Bearbeitungsmodus 3. User aktualisiert Texte in den Eingabefeldern 4. User drückt auf "Speichern" 5. System prüft, ob Änderungen plausibel sind 6. System wechselt in den Anzeigemodus ]<UseCaseEditModule> #pagebreak() #useCase(4, "Datensatz anlegen")[ Der Use Case beschreibt, wie ein neuer Datensatz angelegt werden kann. Das System prüft dabei, ob die angegebenen Informationen plausibel sind. Ein Datensatz kann zum Beispiel ein Modul sein, ein Teilmodul oder ein Studiengang. Zur Übersichtlichkeit wurde nicht für jede Art ein einzelner Use Case erstellt. ][ Studiengangsverantwortliche Person ][ Erfolgreich mit einem Account eingeloggt, der Datensätze anlegen darf ][ Am Beispiel eines Modules: 1. User drückt auf Module 2. User drückt auf "Hinzufügen" 3. System wechselt in den Bearbeitungsmodus 4. User füllt Eingabefelder 5. User drückt auf "Speichern" 6. System prüft, ob Angaben plausibel sind 7. System zeigt "Modul erfolgreich angelegt" ]<UseCaseCreate> #useCase(5, "Änderungen rückgängig machen")[ Der Use Case beschreibt, wie Änderungen an einem Modul rückgängig gemacht werden können. Damit können sowohl eigene Änderungen, als auch die Änderungen anderer User zurückgesetzt werden. ][ Studiengangsverantwortliche Person ][ Erfolgreich mit einem Account eingeloggt, der Module bearbeiten darf ][ 1. User öffnet Modul 2. User drückt auf "Änderungs-Historie" 3. System zeigt Änderungen 4. User drückt auf "Änderungen rückgängig machen" 5. System zeigt "Änderungen rückgängig gemacht" ]<UCRevertChanges> #useCase(6, "Prüfungsordnung verifizieren")[ Der Use Case beschreibt, wie das System bei der Erstellung der Prüfungsordnung unterstützen kann. Die hierzu erforderliche Tabelle kann im System generiert werden, um zu vergleichen, ob alle Daten korrekt hinterlegt sind. ][ Studiengangsverantwortliche Person ][ Alle Module des Studiengangs angelegt ][ 1. User erstellt die Tabelle manuell 2. User öffnet die generierte Tabelle im System 3. User vergleicht beide Tabellen, um sicherzustellen, dass sie korrekt sind ]<UseCaseTable>
https://github.com/barrel111/readings
https://raw.githubusercontent.com/barrel111/readings/main/problems/algebra%20problems.typ
typst
#import "@local/preamble:0.1.0": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #show: project.with( course: "Algebra", sem: "Summer", title: "Algebra Problems", subtitle: "Aluffi", authors: ("<NAME>",), ) #set enum(indent: 15pt, numbering: "a.") = Preliminaries == Naive Set Theory ~ *Problem 1.2* First, note that for every $a in S$, $a in [a]_tilde$. Since every equivalence class is a subset of $S$, it follows that $S = union.big_(C in cal(P)_tilde) C$. Take two partitions $[a]_tilde$ and $[b]_tilde$. If they are disjoint, we are done. Suppose they aren't. Then $c in [a]_tilde sec [b]_tilde$. By transitivity and symmetry, for any $x in [b]_tilde$, $x tilde b tilde c tilde a$. Thus, $[b]_tilde subset.eq [a].tilde$. By symmetry, $[b]_tilde = [a]_tilde$. Thus, distinct equivalence classes are disjoint. This concludes the proof that equivalence classes form a partition of $S$. *Problem 1.3* Let $cal(P)$ be a partition on $S$. Furthermore, for any $a in S$, define $cal(P)_a$ to be the unique set in the partition containing $a$. Then we can the equivalence relation $tilde_cal(P)$ by $a tilde_cal(P) b$ iff $b in cal(P)_a$. This is reflexive because, trivially, $a in cal(P)_a$. This is also symmetric. Note that as partitions are a collection of disjoint sets, $cal(P)_a sect cal(P)_b != emptyset$ implies that $cal(P)_a = cal(P)_b$. Thus, $a in cal(P)_a = cal(P)_b$. Finally, this is also transitive due to the transitivity and symmetry of set equality. Particularly, note that, as in the previous part, $cal(P)_a = cal(P)_b$ and $cal(P)_b = cal(P)_c$. Thus, $c in cal(P)_c = cal(P)_a$. *Problem 1.6* We first show that $tilde$ is an equivalence relation. It is reflexive because for any $a in RR$, $a - a = 0 in ZZ$. It is symmetric because $ZZ$ is closed under multiplication i.e. $z in ZZ arrow.double.long -z in ZZ$. It is transitive because $ZZ$ is closed under addition, particularly for $a, b, c in RR$, if $a tilde b, b tilde c$ then $c - a = (c - b) + (b - a) in ZZ$. We claim that $RR \/ tilde #h(2pt) tilde.equiv [0, 1)$. Note that any $x, y in [0, 1)$ are such that $x tilde.not y$ as $x - y <= x < 1$. Thus, each element of $[0, 1)$ corresponds to a distinct equivalence class. Next, given any $z in RR$, we claim that there exists $x in [0, 1)$ such that $z in [x]_tilde$. Particularly, take $x = z - floor(z)$. Then $z - x in ZZ$ and $0 <= z - floor(z) < 1$. Note that $approx$ is an equivalence relation for pretty much the same reasons as $tilde$ above. Furthermore, $RR times RR \/ approx tilde.equiv [0, 1) times [0, 1)$ by a similar reasoning to above. == Functions Between Sets *Problem 2.1* There are $n!$ many bijections between a set $S$ and itself, with $abs(S) = n$. We prove this by induction. Let $P(n)$ be the statement that there are $n!$ bijections from $S$ to $S'$ with $|S| = |S'| = n$. $P(1)$ is clearly true as the only bijection (in fact, the only function) from a singleton $S = {s}$ to another singleton $S' = {s'}$ is the function $f: S to S'$ defined by $f(s) = s'$. Assuming $P(k)$ we wish to show that there $P(k + 1)$ holds too. Suppose $S = {s_1, dots, s_k, s_(k + 1)}$. We can categorize bijections by where they map the first element $s_1$. There are $n$ different categories as $|S'| = n$. We then claim that every category has $(n - 1)!$ elements. Consider some category that is defined by the fact that it maps $s_1 arrow.bar s_i'$ for some $s_i' in S'$. Hence, every function $f$ in this category, restricts to a bijection $f|_(S-s_1): S- s_1 to S' - s_i'$. By the induction hypothesis, there are precisely $(n - 1)!$ choices for these restrictions. So every category, has $(n - 1)!$ functions and in total, there are $n(n - 1)! = n!$ many bijections from $S$ to $S'$. So, $P(k + 1)$ holds. By induction, $P(n)$ is true for all $n in NN$. *Problem 2.2* We deal with the forward direction first. Suppose $f:A to B$ has a right inverse $g:B to A$. Then for every $b in B$, $g(b) in A$ is such that $f(g(b)) = b$. Thus, every element of $B$ is the image, under $f$, of at least one element of $A$ i.e. $f$ is surjective. Now, consider the backward direction. If $f$ is surjective then for every $b in B$, the fiber $f^(-1)(b)$ is non-empty. So, define the function $g: B to A$ as follows: for every $b$, pick an element of the fiber $f^(-1)(b)$ and assign it to $g(b)$. Then, note that for every $b in B$, $g(b) in f^(-1)(b)$ implies that $(f compose g)(b) = b$. Thus, $f compose g = id_B$ and $g$ is the right inverse of $f$. *Problem 2.4* This follows from showing: + $tilde.equiv$ is reflexive.\ For any set $A$, $A tilde.equiv A$ as $id_A: A to A$ is a bijection. + $tilde.equiv$ is symmetric.\ Take any sets $A, B$ such that $A tilde.equiv B$. Then there exists a bijection $f: A to B$. Consequently, $f^(-1): B to A$ is a bijection from $B$ to $A$ and $B tilde.equiv A$. + $tilde.equiv$ is transitive.\ Take any sets $A, B, C$ such that $A tilde.equiv B$ and $B tilde.equiv C$. Then, there exists bijections $f: A to B$ and $g: B to C$. Consequently, $h = g compose f: A to C$ is also a bijection since it has inverse $f^(-1) compose g^(-1)$ $ (f^(-1) compose g^(-1)) compose (g compose f) = f^(-1) compose f = id_A, #h(15pt) (g compose f) compose (f^(-1) compose g^(-1)) = g compose g^(-1) = id_C. $ Thus, $A tilde.equiv C$. *Problem 2.5* #definition[A function $f: A to B$ is an _epimorphism_ for all sets $Z$ and all function $alpha', alpha'': B to Z$ $ alpha' compose f = alpha'' compose f implies alpha' = alpha''. $] #prop[A function is surjective iff it is an epimorphism] #proof[We start with the forward direction. Suppose $f: A to B$ is surjective. Then we know that $f$ has a right inverse $g$. So, $ alpha' compose f = alpha'' compose f \ implies alpha' compose f compose g = alpha'' compose f compose g \ implies alpha' = alpha''. $ Now, we consider, the backward direction. Suppose $f: A to B$ is an epimorphism. Pick $b in B$ and define $alpha'_b: B to {0, 1}, alpha''_b: B to {0, 1}$ to be $alpha'_b = bb(1)_B, alpha''_b = bb(1)_(B - b)$. Then, $alpha'(b) != alpha''(b)$ so $alpha' compose f = alpha'' compose f$. For every $x in f^(-1)(B - b)$, $(alpha' compose f)(x) = (alpha'' compose f)(x) = 1$. So, if $x in A$, $(alpha' compose f)(x) != (alpha'' compose f)(x)$ necessarily implies that $x in f^(-1)(b)$. Since $b$ was chosen arbitrarily, this proves that $f$ is surjective.] *Problem 2.9* Suppose $A tilde.equiv A'$ and $B tilde.equiv B'$ with $A sect B = nothing, A' sect B' = emptyset$. Let $g_1: A to A'$ and $g_2: B to B'$ be isomorphisms. Consider the map $f: A union B to A' union B'$ defined by $ f(x) = cases(g_1(x) "if " x in A, g_2(x) "otherwise") $ Then, $f$ is a bijection and hence, $A union B tilde.equiv A' union B'$. *Problem 2.10* We give a combinatorial argument. Note that a function from $A$ to $B$ must map an element of $A$ to one of $|B|$ many elements of $B$. Since this choice has to be made for each of the $|A|$ many elements of $A$, there are a total of $|B|^(|A|)$ functions in $B^A$. *Problem 2.11* Let $cal(P)$ denote the power set of $A$. Consider the map $cal(F): 2^A to cal(P)$ defined by $ cal(F)(f) = {x in A bar f(x) = 1} $ First, we show $cal(F)$ is injective. Suppose $f, g in 2^A$ with $cal(F)(f) = cal(F)(g)$. Then for every $x not in cal(F)(f)$, $f(x) = g(x) = 0$ and for every $x in cal(F)(f)$, $f(x) = g(x) = 1$. Thus, $f = g$. Next, we show that $cal(F)$ is surjective. Consider any $S subset.eq 2^A$. Then $cal(1)_S in 2^A$ and is such that $cal(F)(cal(1)_S) = S$. == Categories *Problem 3.1* For clarity denote by $compose_(sans("C"))$ and $compose_(sans("C")^"op")$ the composition laws for $sans("C")$ and $sans("C")^(op)$ respectively. Consider $f in Hom("C"^(op), A, B)$ and $g in Hom("C"^(op), B, C)$. Then note that $f in Hom("C", B, A)$ and $g in Hom("C", C, B)$. So, there exists $f compose_(sans("C")) g in Hom("C", C, A)$. Then, note that $f compose_(sans("C")) g in Hom("C"^(op), A, C)$ and hence, we can define $compose_(sans("C")^("op"))$ by $ g compose_(sans("C")^"op") f = f compose_(sans("C")) g in Hom(sans("C")^"op", A, C). $ If $1_A in Hom("C", A, A)$, then note that $1_A in Hom("C"^(op), A, A)$ too. So, we take the identity morphism of every object $A$ of $sans("C")^(op)$ to be $1_A in Hom("C"^(op), A, A)$ too. We now prove that composition defined this way satisfies the required properties. #let compose_op = $compose_(sans("C")^(op))$ #let compose_c = $compose_(sans("C"))$ + _associativity_ \ Consider $f in Hom("C"^(op), A, B)$, $g in Hom("C"^(op), B, C)$ and $h in Hom("C"^(op), C, D)$. Then, $ (h #compose_op g) #compose_op f &= f #compose_c (g #compose_c h) \ &= (f #compose_c g) #compose_c h \ &= h #compose_op (g #compose_op f). $ + _identity_ \ Consider for $f in Hom("C"^(op), A, B)$ and $g in Hom("C"^(op), B, A)$ the following facts, $ f #compose_op 1_A = 1_A #compose_c f = f, \ 1_A #compose_op g = g #compose_c 1_A = g. $ + _disjointness_ \ Note that $Hom("C"^(op), A, B) = Hom("C", B, A)$ and $Hom("C"^(op), C, D) = Hom("C", D, C)$. Since $Hom("C", B, A)$ and $Hom("C", D, C)$ are disjoint unless $B = D$ and $A = C$, we have that $Hom("C"^(op), A, B)$ and $Hom("C"^(op), C, D)$ are disjoint unless $A = C$ and $B = D$. *Problem 3.3* #let sanC = $sans("C")$ In Example $3.3$, we construct a category $sanC$ from a set $S$ and a reflexive, transitive relation $tilde$ on $S$. Saying that $1_a$ is an identity means that for every $f in Hom("C", a, b)$ and $g in Hom("C", b, a)$ the following holds $ f compose 1_A = f #h(5pt) "and" #h(5pt) 1_A compose g = g. $ If either $Hom("C", a, b) = emptyset$ or $Hom("C", b, a) = emptyset$ then the corresponding equation holds vacuously. So let us deal with the case where $Hom("C", a, b) != emptyset$ or $Hom("C", b, a) != emptyset$: If $exists f in Hom("C", a, b)$ then it must be $f = (a, b)$. Since $tilde$ is reflexive, we have $1_a = (a, a) in Hom("C", a, a)$. Thus, by the composition law, $ f compose 1_A = (a, b) = f. $ Similarly, if $exists g in Hom("C", b, a)$ then it must be $g = (b, a)$. Again, we have $1_a = (a, a) in Hom("C", a, a)$ and by the composition law, $ 1_A compose g = (b, a) = g. $ *Problem 3.5* We can view Example $3.4$ as a concrete instance of Example $3.3$. In this case, the underlying set is $cal(P)(S)$ with the subset relation $subset.eq$ being used as $tilde$. Note how $subset.eq$ is both reflexive and transitive and hence, meets the same criteria as $tilde$ did for Example $3.3$. Then the description of Example 3.4 precisely corresponds to the construction described in Example 3.3 with the relation being given by $subset.eq$. *Problem 3.6* The category $sans("V")$ is defined by - _objects_: $Obj(sans("V")) = NN$ - _morphisms_: for $n, m in NN$ we define $Hom("V", n, m) = "the set of" m times n "matrices with real entries".$ Furthermore, the identity morphism of $Hom("V", n, n)$ is the $(n times n)$ identity matrix $I_(n times n) in Hom("V", n, n)$. - _composition_: The composition of morphisms is given by matrix multiplication, $ Hom("V", n, m) times Hom("V", m, p) to Hom("V", n, p) \ (A, B) |-> B times A. $ - _identity_: For any object $n in NN$ of $sans(V)$, we take the $(n times n)$ identity matrix $I_(n times n) in Hom("V", n, n)$ to be the identity morphism. Associativity for composition follows from the associativity of matrix multiplication. The identity morphism is the identity with respect to composition by the fact that $A times I_(n times n) = A$ and $I_(n times n) times B = B$ for any $(m times n)$ matrix, $A$, and $(n times m)$ matrix, $B$. Finally, $Hom("V", n, m)$ and $Hom("V", p, q)$ are equal only if $n = p$ and $m = q$ as otherwise, they would contain matrices of different dimension. *Problem 3.7* Let $sanC$ be a cateogry and let $A$ be an object in $sanC$. We define the co-slice category $sanC^A$ as follows. - _objects_: $Obj(sanC^A) = $ all morphisms from $A$ to any object in $sanC$ - _morphisms_: for objects $f_1, f_2$ of $sanC^A$, the morphisms $f_1 to f_2$ are defined to be _commutative diagrams_ #box(width:100%)[#align(center)[ #commutative-diagram( node-padding: (30pt, 50pt), node((0, 0), $Z_1$), node((0, 2), $Z_2$), node((1,1), $A$), arr($A$, $Z_1$, $f_1$), arr($A$, $Z_2$, $f_2$, label-pos: right), arr($Z_1$, $Z_2$, $sigma$, label-pos: left) ) ]] in the ambient category $sanC$. Alternatively, morphisms $f_1 to f_2$ correspond to those morphisms $sigma: Z_1 -> Z_2$ in $sanC$ such that $sigma f_1 = f_2.$ - _composition_: The composition of two morphisms $f_1 -> f_2$ and $f_2 -> f_3$ corresponding to the diagrams \ #box(width:100%)[ #align(center)[ #commutative-diagram( node-padding: (30pt, 50pt), node((0, 0), $Z_1$), node((0, 2), $Z_2$), node((1, 1), $A$), arr($A$, $Z_1$, $f_1$), arr($A$, $Z_2$, $f_2$, label-pos: right), arr($Z_1$, $Z_2$, $sigma_1$) ) #commutative-diagram( node-padding: (30pt, 50pt), node((0, 0), $Z_2$), node((0, 2), $Z_3$), node((1, 1), $A$), arr($A$, $Z_2$, $f_2$), arr($A$, $Z_3$, $f_3$, label-pos: right), arr($Z_2$, $Z_3$, $sigma_2$) )]] is given by the diagram \ #box(width:100%)[ #align(center)[ #commutative-diagram( node-padding: (30pt, 50pt), node((0, 0), $Z_1$), node((0, 2), $Z_3$), node((1, 1), $A$), arr($A$, $Z_1$, $f_1$), arr($A$, $Z_3$, $f_3$, label-pos: right), arr($Z_1$, $Z_3$, $sigma_2 sigma_1$) ) ] ] - _identity_: For any object $f: A -> Z$ of $sans(C)^A$, we define the identity morphism $1_f$ to correspond to the morphism $1_(Z)$ in $sans(C)$--- that is, the identity $1_f$ corresponds to the diagram \ \ #box(width:100%)[ #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge #align(center)[ #diagram( spacing: (10mm, 15mm), node((0, 0), $Z$, name:<Z>), node((0, 1), $A$, name:<A>), edge((0, 0), (0, 0), "->", bend:130deg, $1_Z$), edge(<A>, <Z>, "->", $f$, label-side: left), ) ]] *Problem 3.8* #let setinf = $sans("Set")^oo$ We define the category of _infinite sets_, $setinf$, as follows - _objects_: $Obj(setinf)=$ the collection of all infinite sets, - _morphisms_: For $A, B in Obj(setinf)$, $Hom(sans("Set")^oo, A, B) = B^A$, - _composition_: Composition of morphisms is defined to be the same as the composition of functions, - _identity_: For any object $A$ of $sans("Set")^oo$, the identity is defined to be the identity function on $A$. We may view $sans("Set")^oo$ as a subcategory of $sans("Set")$ since $"Obj"(setinf) subset.eq Obj(sans("Set"))$ and $Hom(setinf, A, B) subset.eq Hom(sans("Set"), A, B)$, for any $A, B in sans("Set")^oo$. In fact, $Hom(setinf, A, B) = Hom(sans("Set"), A, B) = B^A$. This justifies calling $setinf$ a full subcategory of $sans("Set")$. *Problem 3.9* #let Mset = $sans("MSet")$ We define the category of _multisets_, $Mset$ , as follows - _objects_: $Obj(Mset) = $ the collection of all tupples $(A, approx)$ where $A$ is a set and $approx$ is an equivalence relation on $A$, - _morphisms_: For $(A, approx_A), (B, approx_B) in Obj(Mset)$, we define $Hom(Mset, A, B)$ to be the set of all functions $f: A -> B$ such that $a approx_A b ==> f(a) approx_B f(b)$ , - _composition_: Composition of morphisms is defined to be the same as the composition of functions, - _identity_: For any object $(A, approx_A)$ of $Mset$, the identity is defined to be the same as the composition of functions. #let Set = $sans("Set")$ Note that we may view $Set$ as a full subcategory of $Mset$ (or at least, a copy of $Set$). We define a copy of $Set$, $Set'$, as follows - _objects_: $Obj(Set')$ the collection of all tuples $(A, approx)$ where $approx$ is the identity relation on $A$, - _morphisms_: For $(A, approx_A), (B, approx_B) in Obj(Set')$, we define $Hom(Set', A, B) = B^A$. Note that $Hom(Mset, A, B) = B^A$ to as for all functions $f: A -> B$, we have $a approx_A b => a = b => f(a) approx_B f(b).$ - _composition_: Composition of morphisms is defined to be the same as the composition of functions, - _identity_: For any object $(A, approx_A)$ of $Set'$, the identity is defined to be the same as the composition of functions. Clearly, $Set'$ is a full subcategory of $Mset$. *Problem 3.11* + $sans(C)^(A, B)$\ Start from a category $sans(C)$ and two objects $A, B$ of $sans(C)$. We then define a new category $sans(C)_(A, B)$ as follows - _objects_: $Obj(sans(C)^(A, B)) =$ diagrams\ #box(width: 100%)[#align(center)[ #commutative-diagram( node-padding: (50pt, 20pt), node((0, 0), $Z$), node((-1, 1), $A$), node((1, 1), $B$), arr($A$, $Z$, $f$, label-pos: right), arr($B$, $Z$, $g$, label-pos: left), ) ]] in $sans(C)$; - _morphisms_:\ #box(width: 100%)[#align(center)[ #commutative-diagram( node-padding: (40pt, 25pt), node((0, 0), $Z_1$), node((-1, 1), $A$), node((1, 1), $B$), node((0, 2), $Z_2$, "Z2"), node((-1, 3), $A$, "A1"), node((1, 3), $B$, "B1"), node((0, 1), $$, "S"), arr($A$, $Z_1$, $f_1$, label-pos: right), arr("A1", "Z2", $f_2$, label-pos: right), arr($B$, $Z_1$, $g_1$), arr("B1", "Z2", $g_1$), arr("S", "Z2", $$), ) ]] are _commutative diagrams_ #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), node((-1, 2), $A$), node((1, 2), $B$), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), arr($A$, $Z_2$, $f_2$), arr($B$, $Z_2$, $g_2$, label-pos: right), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), ) ] Alternatively, morphisms in $sans(C)_(A, B)$ corresponds to those morphisms $sigma: Z_2 -> Z_1$ in $sans(C)$ such that $f_1 = sigma f_2$ and $g_1 = sigma g_2$. - _composition_: Consider the two morphisms #align(center)[#commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), node((-1, 2), $A$), node((1, 2), $B$), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), arr($A$, $Z_2$, $f_2$), arr($B$, $Z_2$, $g_2$, label-pos: right), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), ) #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_2$), node((0, 1), $Z_3$), node((-1, 2), $A$), node((1, 2), $B$), arr($Z_3$, $Z_2$, $sigma'$, label-pos: right), arr($A$, $Z_3$, $f_3$), arr($B$, $Z_3$, $g_3$, label-pos: right), arr($A$, $Z_2$, $f_2$, curve: -25deg, label-pos: right), arr($B$, $Z_2$, $g_2$, curve: 25deg), ) ] Then, their composition corresponds to the commutative diagram #align(center)[#commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), arr($A$, $Z_2$, $f_2$, curve: -15deg, label-pos: right), arr($B$, $Z_2$, $g_2$, curve: 15deg), arr($A$, $Z_1$, $f_1$, label-pos: right, curve: -25deg), arr($B$, $Z_1$, $g_1$, curve: 25deg), node((0, 3), $Z_3$), node((-1, 5), $A$), node((1, 5), $B$), arr($A$, $Z_3$, $f_3$), arr($B$, $Z_3$, $g_3$, label-pos: right), arr($Z_3$, $Z_2$, $sigma '$, label-pos: right))] That is, the composition of the two morphism corresponds to the following morphism #align(center)[#commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_4$), arr($Z_4$, $Z_1$, $sigma sigma'$, label-pos: right), node((-1, 2), $A$), node((1, 2), $B$), arr($A$, $Z_1$, $f_1$, curve: -20deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 20deg), arr($A$, $Z_4$, $f_3$), arr($B$, $Z_4$, $g_3$, label-pos: right) )] - _identity_: The identity morphism corresponds to the following commutative diagram #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z$, "Z_1"), node((0, 1), $Z$, "Z_2"), node((-1, 2), $A$), node((1, 2), $B$), arr("Z_2", "Z_1", $"id"_Z$, label-pos: right), arr($A$, "Z_2", $f$), arr($B$, "Z_2", $g$, label-pos: right), arr($A$, "Z_1", $f$, curve: -25deg, label-pos: right), arr($B$, "Z_1", $g$, curve: 25deg), ) ] + $italic("Fibered") sans(C)^(A, B)$ \ Start with a given category $sans("C")$ and choose two fixed morphisms $alpha: C -> A, beta: C -> B$ in $sans("C")$ with the same target $C$. We can then consider a category $C^(alpha, beta)$ as follows - _objects_: $Obj(sans(C)^(alpha, beta))$ = commutative diagrams\ #box(width: 100%)[#align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z$), node((-1, 1), $A$), node((1, 1), $B$), node((0, 2), $C$), arr($A$, $Z$, $f$, label-pos: right), arr($B$, $Z$, $g$), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$, label-pos: left), ) ]] in $sans(C)$; - _morphisms_: morphisms correspond to commutative diagrams\ #box(width: 100%)[#align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), node((-1, 2), $A$), node((1, 2), $B$), node((0, 3), $C$), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), arr($A$, $Z_2$, $f_2$, label-pos: right), arr($B$, $Z_2$, $g_2$), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$, label-pos: left), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), ) ]] - _composition_: Consider the two morphisms #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), node((-1, 2), $A$), node((1, 2), $B$), node((0, 3), $C$), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), arr($A$, $Z_2$, $f_2$, label-pos: right), arr($B$, $Z_2$, $g_2$), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), ) #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_2$), node((0, 1), $Z_3$), node((-1, 2), $A$), node((1, 2), $B$), node((0, 3), $C$), arr($A$, $Z_2$, $f_2$, curve: -25deg, label-pos: right), arr($B$, $Z_2$, $g_2$, curve: 25deg), arr($A$, $Z_3$, $f_3$, label-pos: right), arr($B$, $Z_3$, $g_3$), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$), arr($Z_3$, $Z_2$, $sigma'$, label-pos: right), ) ] Then their composition corresponds to the commutative diagram #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), arr($A$, $Z_2$, $f_2$, label-pos: right), arr($B$, $Z_2$, $g_2$), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$), arr($Z_2$, $Z_1$, $sigma$, label-pos: right), node((0, 3), $Z_3$), node((-1, 4), $A$), node((1, 4), $B$), node((0, 5), $C$), arr($A$, $Z_3$, $f_3$, label-pos: 0.65em), arr($B$, $Z_3$, $g_3$, label-pos: right), arr($Z_3$, $Z_2$, $#h(10pt) sigma'$, label-pos: right) ) ] That is, the composition of the two morphism corresponds to the following morphism #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z_1$), node((0, 1), $Z_2$), node((-1, 2), $A$), node((1, 2), $B$), node((0, 3), $C$), arr($A$, $Z_1$, $f_1$, curve: -25deg, label-pos: right), arr($B$, $Z_1$, $g_1$, curve: 25deg), arr($A$, $Z_2$, $f_3$), arr($B$, $Z_2$, $g_3$, label-pos: right), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$), arr($Z_2$, $Z_1$, $sigma sigma'$, label-pos: right), ) ] - _identity_: The identity morphism corresponds to the following commutative diagram #align(center)[ #commutative-diagram( node-padding: (40pt, 30pt), node((0, 0), $Z$, "Z_1"), node((0, 1), $Z$, "Z_2"), node((-1, 2), $A$), node((1, 2), $B$), node((0, 3), $C$), arr($A$, "Z_1", $f$, curve: -25deg, label-pos: right), arr($B$, "Z_1", $g$, curve: 25deg), arr($A$, "Z_2", $f$), arr($B$, "Z_2", $g$, label-pos: right), arr($C$, $A$, $alpha$, label-pos: right), arr($C$, $B$, $beta$), arr("Z_2", "Z_1", $"id"_Z$, label-pos: right), ) ]] == Morphisms *Problem 4.1* We use induction to show that $f_n f_(n - 1) dots.c f_1$ equals $(dots.c ((f_n f_(n - 1)) f_(n - 2)) dots.c f_1)$. The base case $n = 2$ is trivially true as $f_2 f_1 = (f_2 f_1)$. Now, assuming this holds for some $n >= 2$, we wish to show that it holds for $n + 1$ too. Particularly, note that $ f_(n + 1) f_n dots.c f_1 = (f_(n + 1) f_n dots.c f_2) f_1 overbrace(=, "IH") ( dots.c ((f_(n + 1) f_n) f_(n - 1)) dots f_2) f_1 $ Thus, this holds for $n + 1$ too. By induction, it must be true for all $n in NN_(>= 2)$. *Problem 4.2* == Universal Properties *Problem 5.2* *Problem 5.3* *Problem 5.5* *Problem 5.6* *Problem 5.12*
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/src/core/component/glossary.typ
typst
#import "/src/utils.typ" as _utils #let make-glossary( entries: (:), _fonts: (:), ) = { // TODO: perhaps apply the styles only for some parts of the docs in core so those require no resets // reverse the figure styles show figure.caption: emph show figure.caption: set text(fill: black, font: _fonts.serif) heading(level: 1)[Glossar] _utils._pkg.glossarium.print-glossary(entries, show-all: true) }
https://github.com/lcharleux/LCharleux_Teaching_Typst
https://raw.githubusercontent.com/lcharleux/LCharleux_Teaching_Typst/main/src/courses/MECA510-512_Rappels/MECA510-512_Rappels.typ
typst
MIT License
// TEMPLATE IMPORT #import "../../templates/conf.typ": conf, todo, comment, idea, note, important #import "../../templates/drawing.typ": dvec, dpoint, dangle3p, dimension_line, arotz90, arrnumprod, arrsub, anorm, normalize, rotmat2D, dispvcol, arradd, mvec, arrcrossprod, arrdotprod, torseur1, torseur2, torseur6 #import "@preview/unify:0.6.0": num, qty, numrange, qtyrange #import "@preview/cetz:0.2.2" #import "@preview/showybox:2.0.1": showybox #import "@preview/chic-hdr:0.4.0": * #import cetz.draw: * #import "@preview/physica:0.9.3": * #set math.equation(numbering: "(1)") // DOCUMENT SETUP #let course = "MECA510-512: Statique & Cinématique" #let block = "Notions indispensables sur les vecteurs et les torseurs" #let section = "MECA3-FISA" #let teacher = "<NAME>" #let email = "<EMAIL>" #show: doc => conf( course: course, block: block, section: section, teacher: teacher, email:email, doc, ) // #let theorem(body, title: none, footer: none) = showybox( // title: title, // frame: ( // border-color: blue, // title-color: blue.lighten(30%), // body-color: none, // footer-color: blue.lighten(80%), // ), // footer: footer, // )[#body] // MAIN DOCUMENT = Introduction Ce cours est destiné de futurs ingénieurs à coloration mécanique. Il ne s'agit donc pas d'un cours de mathématiques, et notamment, il ne s'agit pas d'algèbre linéaire. Cependant, les vecteurs sont un outil essentiel pour la mécanique, et il est donc nécessaire de rappeler quelques notions de base sur les vecteurs. Si ce qui est présenté ici vous semble trop simple, c'est normal et c'est une bonne nouvelle, et vous pouvez passer à la suite. Ceci dit, ce cours existe car l'expérience montre que les étudiants ont souvent des difficultés avec les vecteurs, et il est donc important de les rappeler. = Formalisme & définitions == Notion de vecteur On considère ainsi qu'un vecteur $#mvec[V]$ est un object mathématique défini par 3 propriétés: / Sa direction: une droite $(D)$, par exemple. / Son sens: le sens de parcours de la droite parmi les deux possibles. / Sa norme: elle quantifie l'intensité du vecteur, est notée $abs(#mvec[V])$ et a une unité qui dépend de ce que représente le vecteur. Par exemple, un champ de vitesse aura une norme en #qty("", "m/s") et une force en #qty("", "N"). Un vecteur de norme 1 sans unité est un vecteur unitaire. == Relations entre vecteurs et points Dans tout le cours, on manipulera des points ($A$, $B$, ... ) et des vecteurs ($#mvec[u]$, $#mvec[AB]$, ...)#footnote[Voir #link("https://fr.wikipedia.org/wiki/Espace_affine")[espaces affines].]. On utilisera largement la propriété que si $B = A + #mvec[u]$, alors $#mvec[AB] = #mvec[u]$. Le vecteur $#mvec[AB]$ est le vecteur qui va de $A$ à $B$ et son unité est le #qty("", "m"). == Espace de travail De même on travaillera dans l'espace réel à 3 dimensions auquel on ajoutera le temps qui sera le même dans tous les référentiels. On sera ainsi dans le cadre de la mécanique classique ou newtonienne. = Opération sur les vecteurs == Addition et relation de Chasles === Addition de vecteurs #align(center)[ #cetz.canvas({ let pcolor = black let A = (0, 0) let B = (5, 0) let C = (2, 4) let D = (7, 4) line(B, D, stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(C, D, stroke: (paint: black, thickness: 1pt, dash: "dashed")) dvec(A, B, label: mvec[u], color: red) dvec(A, C, label: mvec[v], color: blue) dvec(A, D, label: [$#mvec[u] + #mvec[v]$], color: green) })] La somme de deux vecteurs est un vecteur qui représente la diagonale du parallélogramme formé par les deux vecteurs. ==== Relation de Chasles #align(center)[ #cetz.canvas({ let pcolor = black let A = (0, 0) let C = (10, 0) let B = (7, 3) dvec(A, B, label: mvec[AB], color: red, shrink: 4pt) dvec(B, C, label: mvec[BC], color: blue, shrink: 4pt) dvec(A, C, label: [$#mvec[AC]=#mvec[AB]+#mvec[BC]$], color: green, shrink: 4pt) dpoint(A, label: "A", anchor: "north") dpoint(B, label: "B", anchor: "north") dpoint(C, label: "C", anchor: "north") })] Si $A$, $B$ et $C$ sont 3 points, alors ils vérifient la relation de Chasles: $#mvec[AC] = #mvec[AB] + #mvec[AC]$. C'est une relation très utile pour faire apparaître des points dans un calcul. Par exemple, si on cherche le point $C$ tel que $#mvec[AC] = #mvec[AB] + #mvec[BC]$, on peut utiliser la relation de Chasles pour trouver $C$. === Produit vecteur nombre #align(center)[ #cetz.canvas({ dvec((-2.5, 0), (2.5, 0), label: mvec[u], color: red) dvec((-5, -1), (5, -1), label: mvec[2 u], color: green) dvec((1.125, -2), (-1.125, -2), label: mvec[-1/2 u], color: blue, rev: true) })] Le produit d'un vecteur $#mvec[V]$ par un nombre $k$ est un vecteur noté $k#mvec[V]$ et est défini par: / Sa direction: la même que $#mvec[V]$. / Son sens: le même que $#mvec[V]$ si $k > 0$ et opposé si $k < 0$. / Sa norme: $abs(k)#mvec[V]$. On peut ainsi multiplier un vecteur par un nombre pour changer son intensité d'un facteur $k$. Si $k$ est négatif, le sens du vecteur est inversé. Au passage, on peut remarque que même si nous n'avons pas défini l'oppposé d'un vecteur, le produit vecteur nombre permet de le définir. == Produit scalaire #align(center)[ #cetz.canvas({ let pcolor = black let A = (0, 0) let C = (10, 0) let B = (7, 3) let D = (7, 0) line(B, D, stroke: (paint: black, thickness: 1pt)) dvec(A, B, label: mvec[u], color: red, shrink: 0) dvec(A, C, label: mvec[v], color: blue, shrink: 0) dangle3p(D, B, C, right: true, radius: .25) dangle3p(A, B, C, radius: 3, label: $theta$, color: green) dimension_line(A, D, label: [$ norm( #mvec[u]) cos(theta) $], inv: true, offs: 2, ratio: 90%) })] Le produit scalaire de deux vecteurs $#mvec[u]$ et $#mvec[v]$ est un nombre noté $#mvec[u] dot #mvec[v]$ et est défini par: $ #mvec[u] dot #mvec[v] = norm(#mvec[u]) norm(#mvec[v]) cos(theta) $ Où $theta$ est l'angle entre $#mvec[A]$ et $#mvec[B]$. Il a les propriétés suivantes: - Il est commutatif: $#mvec[u] dot #mvec[v] = #mvec[v] dot #mvec[u]$. - Il permet de calculer les angles entre deux vecteurs, ou de projeter un vecteur sur un autre. == Produit vectoriel #align(center)[ #cetz.canvas({ ortho( // x: 35.26deg, // y: 45deg, // z: 0deg, { let pcolor = black let A = (0, 0, 0) let B = (8, 0, 0) let C = (-1, 4, 0) let D = (0, 0, 5) // let D = arrcrossprod(B, C) dvec(A, B, label: mvec[u], color: red, shrink: 0, rotate_label: false) dvec(A, C, label: mvec[v], color: blue, shrink: 0, rotate_label: false) dvec(A, D, label: [$#mvec[u] and #mvec[v]$], color: green, shrink: 0, rotate_label: false) // dangle3p(A, B, C, label: $theta$, radius:2.5, right: false, label-radius: 2, color:yellow) dangle3p(A, B, D, right: true, radius:.75) dangle3p(A, C, D, right: true, radius:.75) dimension_line(A, B, label: [$ norm( #mvec[u])$], inv: true, offs: 2, ratio: 90%) dimension_line(A, C, label: [$ norm( #mvec[v])$], inv: false, offs: 2, ratio: 90%) dpoint(A, label: "A", anchor: "south-west") dpoint(B, label: "B", anchor: "south") dpoint(C, label: "C", anchor: "south") line(B, C, stroke: (paint: black, thickness: 1pt)) }, ) }) ] Le produit vectoriel de deux vecteurs $#mvec[u]$ et $#mvec[v]$ est un vecteur noté $#mvec[u] and #mvec[v]$ et est défini par: / Sa direction: perpendiculaire au plan formé par $#mvec[u]$ et $#mvec[v]$. / Son sens: donné par la règle de la main droite. / Sa norme: $abs(#mvec[u] and #mvec[v]) = abs(#mvec[u]) dot abs(#mvec[v]) dot sin(theta)$ Il a les propriétés suivantes: - Le produit vectoriel est anti-commutatif: $#mvec[u] and #mvec[v] = - #mvec[v] and #mvec[u]$. - La norme du produit vectoriel est maximale lorsque $#mvec[u]$ et $#mvec[v]$ sont orthogonaux. - Le produit vectoriel est nul si $#mvec[u]$ et $#mvec[v]$ sont colinéaires. - Sa norme correspond à 2 fois l'aire du triangle $"ABC"$. == Le produit mixte #align(center)[ #cetz.canvas({ ortho( // x: 35.26deg, // y: 45deg, // z: 0deg, { let A = (0, 0, 0) let B = (0, 0, 6) let C = (3, 1, 0) // let D = (0, 5, 0) let D = arrnumprod( arrcrossprod(B, C), .3) let E = (5,9,3) dpoint(A, label: "A", anchor: "north") dpoint(B, label: "B", anchor: "north") dpoint(C, label: "C", anchor: "north") dpoint(E, label: "D", anchor: "south-west") line(B, C, stroke: (paint: black, thickness: 1pt)) line(C, E, stroke: (paint: black, thickness: 1pt)) line(B, E, stroke: (paint: black, thickness: 1pt)) dvec(A, B, label: mvec[u], color: red, shrink: 0, rotate_label: false) dvec(A, C, label: mvec[v], color: blue, shrink: 0, rotate_label: false) dvec(A, D, label: [$#mvec[u] and #mvec[v]$], color: green, shrink: 0, rotate_label: false) dvec(A, E, label: mvec[w], color: rgb("#343091"), shrink: 0, rotate_label: false) // dangle3p(A, D, E, label: $phi$, radius:4, right: false, label-radius: 4.3, color:yellow) dangle3p(A, B, D, right: true, radius:.75) dangle3p(A, C, D, right: true, radius:.75) }, ) }) ] Le poduit mixte des vecteurs $#mvec[u]$, $#mvec[v]$ et $#mvec[w]$ est noté$( #mvec[u], #mvec[v], #mvec[w] )$ et est défini par: $ ( #mvec[u], #mvec[v], #mvec[w] ) & = (#mvec[u] and #mvec[v]) dot #mvec[w] $ Il a des propriétés similaires au produit vectoriel: - Il est anti-commutatif: $( #mvec[u], #mvec[v], #mvec[w] ) = - ( #mvec[v], #mvec[u], #mvec[w] )$. - Il est nul si $#mvec[u]$, $#mvec[v]$ et $#mvec[w]$ sont coplanaires, c'est donc un outil parfait pour déterminer si 3 vecteurs forment un tétraèdre dégénéré, c'est-à-dire de volume nul. - Sa norme correspond à 6 fois le volume du tétraèdre $"ABCD"$ formé par $#mvec[u]$, $#mvec[v]$ et $#mvec[w]$. - C'est aussi le déterminant de la matrice formée par les 3 vecteurs. = Bases, repères & coordonnées == Bases D'un point de vue mathématique, une base est un ensemble de vecteurs linéairement indépendants qui, en les combinant linéairement permettent de retrouver tout vecteur de l'espace. Nous avons fait l'hypothèse que l'espace est de dimension 3, et nous avons donc besoin de 3 vecteurs $(#mvec[x], #mvec[y], #mvec[z])$ pour construire une base. Tout vecteur $#mvec[v]$ de l'espace peut être défini par une combinaison linéaire de ces 3 vecteurs, c'est-à-dire sous la forme: $ #mvec[v] = a #mvec[x] + b #mvec[y] + c #mvec[z] $ Si les vecteurs de la base sont linéairement indépendants, ce qui dans le cas présent revient à dire que leur produit mixte est non nul: $ ( #mvec[x], #mvec[y], #mvec[z] ) != 0 $ Mathématiquement, nous n'avons pas besoin de plus pour définir une base $cal(B) = (#mvec[x], #mvec[y] #mvec[z])$. Dans la pratique, nous choisirons systématiquement d'aller un peu plus loin en supposant que les bases que nous utilisons sont orthonormées directes, c'est-à-dire que: - Les vecteurs de la base sont unitaires: $norm(#mvec[x]) = norm(#mvec[y]) = norm(#mvec[z]) = 1$ - Ils sont orthogonaux 2 à 2: $#mvec[x] and #mvec[y] = #mvec[y] and #mvec[z] = #mvec[z] and #mvec[x] = 0$ - Ils forment un repère direct: $( #mvec[x], #mvec[y], #mvec[z] ) > 0$. Enfin, surtout dans un contexte cinématiques, nous serons souvent ammenés à utiliser des plusieurs bases, et il sera alors nécessaire de préciser à quelle base appartient un vecteur. Nous choisissons de numéroter les solides de $0$ à $N$ et donc d'attribuers au solide $i$ une base $cal(B)_i = (#mvec[x]_i, #mvec[y]_i, #mvec[z]_i)$. == Coordonnées #let v = ("a", "b", "c") Les coordonnées d'un vecteur $#mvec[v]$ dans une base $cal(B)_i = (#mvec[x]_i, #mvec[y]_i, #mvec[z]_i)$ sont les coefficients $a$, $b$ et $c$ de la combinaison linéaire qui permet d'écrire $#mvec[v]$: $ #mvec[v] = a #mvec[x]_i + b #mvec[y]_i + c #mvec[z]_i $ Dans tout le cours nous utiliserons la notation: $ #mvec[v] = #dispvcol(v, basis:"i") = a #mvec[x]_i + b #mvec[y]_i + c #mvec[z]_i $ Pour indiquer que les coordonnées de $#mvec[v]$ dans la base $cal(B)_i$ sont $(a, b, c)$. La @vector_coordinates[figure] illustre cette notion. #figure( align(center)[ #cetz.canvas({ ortho( x: 20deg, y: 30deg, // z: 0deg, { let O = (0, 0, 0) let x = (3, 0, 0) let y = (0, 3, 0) let z = (0, 0, 3) let vx = (5, 0, 0) let vy = (0, 8, 0) let vz = (0, 0, 13) let vxy = arradd(vx, vy) let v = arradd(vxy, vz) // dpoint(O0, label: [$O_0$], anchor: "north") line(O, (5.2, 0, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(O, (0, 8.2, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(vx, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(vy, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) dvec(O, x, label: [$#mvec[x]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, y, label: [$#mvec[y]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, z, label: [$#mvec[z]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, v, label: [$#mvec[v]$], color: blue, shrink: 4pt, rotate_label: false) dvec(O, arradd(vx, vy), label: [$a #mvec[x]_i + b #mvec[y]_i $], color: red, shrink: 0pt, rotate_label: false) dvec(arradd(vx, vy), v, label: [$c #mvec[z]_i $], color: maroon, shrink: 0pt, rotate_label: false) dimension_line(O, vx, label: [$a$], inv: true, offs: 2, ratio: 90%) dimension_line(O, vy, label: [$b$], inv: false, offs: 4, ratio: 90%) dangle3p(vx, O, vxy, right: true, radius:.5) dangle3p(vy, O, vxy, right: true, radius:.5) dangle3p(vxy, v, O, right: true, radius:.75) }, ) }) ], caption: "Illustration des coordonnées d'un vecteur dans une base.", placement: top, )<vector_coordinates> Les coordonnées d'un vecteur dans une base peuvent se calculer facilement en utilisant le produit scalaire. En effet, si $#mvec[v] = a #mvec[x]_i + b #mvec[y]_i + c #mvec[z]_i $, alors: $ #mvec[v] dot #mvec[x]_i & = (a #mvec[x]_i + b #mvec[y]_i + c #mvec[z]_i) dot #mvec[x]_i \ & = a ( underbrace(#mvec[x]_i dot #mvec[x]_i, 1)) + b ( underbrace(#mvec[y]_i dot #mvec[x]_i, 0)) + c ( underbrace(#mvec[z]_i dot #mvec[x]_i, 0)) \ & = a $ Il suffit dont ce multiplier scalairement un vecteur par chaque vecteur de la base pour obtenir les coordonnées de ce vecteur celle-ci. == Opérations sur les coordonnées des vecteurs On peut réécrire les opérations entre vecteurs et nombres en utilisant les coordonnées des vecteurs dans une même base. On considère 3 vecteurs $#mvec[v]$ et $#mvec[w]$ et $#mvec[u]$ , un nombre $lambda$ et une base $cal(B)$ qui vérifient: #let w = ("d", "e", "f") #let u = ("g", "h", "i") $ #mvec[v] = #dispvcol(v, basis:"i") " ; " #mvec[w] = #dispvcol(w, basis:"i") " et " #mvec[w] = #dispvcol(u, basis:"i") $ === Addition de vecteurs $ #mvec[v] + #mvec[w] = #dispvcol( ($a+d$, $b+e$, $d+f$) , basis:"i") $ === Produit vecteur nombre $ lambda #mvec[v] = #dispvcol( ($lambda a$, $lambda b$, $lambda c$) , basis:"i") $ === Produit scalaire $ #mvec[v] dot #mvec[w] = #dispvcol(v, basis:"i") dot #dispvcol(w, basis:"i") = a d + b e + c f $ === Produit vectoriel $ #mvec[v] and #mvec[w] = #dispvcol(v, basis:"i") and #dispvcol(w, basis:"i") = #dispvcol( ($b f - c e$, $c d - a f$, $a e - b d$) , basis:"i") $ === Produit mixte $ ( #mvec[v], #mvec[w], #mvec[u] ) = #dispvcol(v, basis:"i") dot #dispvcol(w, basis:"i") dot #dispvcol(u, basis:"i") = a e i + b f g + c d h - ( a f h + b d i + c e g ) $ // == Changement de base // A faire == Repères Un repère est une une base $cal(B)_i$ à laquelle on a ajouté un point d'origine $O_i$, on l'écrit alors $cal(R)_i = (O_i, #mvec[x]_i, #mvec[y]_i, #mvec[z]_i)$. Le repère permet de définir les coordonnées de points dans l'espace au travers du vecteur position. Un point $M$ a des coordonnées $(x, y, z)$ dans le repère $cal(R)_i$ si le vecteur position $#mvec[$O_i$ M] = x #mvec[x]_i + y #mvec[y]_i + z #mvec[z]_i$. #figure( align(center)[ #cetz.canvas({ ortho( x: 20deg, y: 30deg, // z: 0deg, { let O = (0, 0, 0) let x = (3, 0, 0) let y = (0, 3, 0) let z = (0, 0, 3) let vx = (5, 0, 0) let vy = (0, 8, 0) let vz = (0, 0, 13) let vxy = arradd(vx, vy) let v = arradd(vxy, vz) line(O, (5.2, 0, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(O, (0, 8.2, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(vx, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) line(vy, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) dvec(O, x, label: [$#mvec[x]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, y, label: [$#mvec[y]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, z, label: [$#mvec[z]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, v, label: [$#mvec[$O_i$ M]$], color: blue, shrink: 4pt, rotate_label: false) dvec(O, arradd(vx, vy), label: [$x #mvec[x]_i + y #mvec[y]_i $], color: red, shrink: 0pt, rotate_label: false) dvec(arradd(vx, vy), v, label: [$z #mvec[z]_i $], color: maroon, shrink: 0pt, rotate_label: false) dimension_line(O, vx, label: [$x$], inv: true, offs: 2, ratio: 90%) dimension_line(O, vy, label: [$y$], inv: false, offs: 4, ratio: 90%) dangle3p(vx, O, vxy, right: true, radius:.5) dangle3p(vy, O, vxy, right: true, radius:.5) dangle3p(vxy, v, O, right: true, radius:.75) dpoint(O, label: [$O_i$], anchor: "north-west") dpoint(v, label: [$M$], anchor: "north-east") }, ) }) ], caption: [Illustration du vecteur position d'un point $M$ dans un repère $cal(R)_i$.], placement: top, )<point_coordinates> = Champs de vecteurs Un champ de vecteur est une fonction qui associe un vecteur $#mvec[v]$ à une position $M$ de l'espace $ #mvec[$O_i$ M]$ et au temps $t$: $ #mvec[v]:= cases(bb(R)^3 times bb(R) arrow.r.long bb(R)^3, (M, t) arrow.r.long.bar #mvec[v] (M, "t") ) $ En mécanique, un champ de vitesse, de force ou de déplacement sont des exemples de champs de vecteurs. Pour les calculer, on a besoin alternativement de caractériser leurs variations par rapport au temps ou à l'espace. On dira d'un champ de vecteur qu'il est: / Constant: si ses coordonnées ne dépendent pas du temps. / Uniforme: si ses coordonnées ne dépendent pas de la position. == Dérivation par rapport au temps === Vision naïve On s'intéresse à un vecteur $#mvec[v]$ qui dépend du temps $t$. On connait ses coordonnées dans base $cal(B)_i$: $ #mvec[v] = #dispvcol(v, basis:"i") $ Par commodité, nous ne ferons pas apparaître explicitement la dépendance en $t$ des coordonnées de $#mvec[v]$. On a donc naturellement envie de définir la dérivée de $#mvec[v]$ par rapport au temps $t$: #let dotv = ($dot(a)$, $dot(b)$, $dot(c)$) $ dv( #mvec[v], t) = #dispvcol(dotv, basis:"i") $ Où $dot(a) = dv(a, t)$. On remarque que la dérivée d'un vecteur par rapport au temps ne semble pas unique. En effet, elle semble dépendre de la base. A titre d'exemple, si on construit une base dont le vecteur $#mvec[v]$ fait partie et que sa norme ne dépend pas du temps, alors la dérivée de $#mvec[v]$ par rapport au temps est nulle de ce point de vue. === Vision plus rigoureuse #figure( align(center)[ #cetz.canvas({ ortho( x: 20deg, y: 30deg, // z: 0deg, { let O = (0, 0, 0) let x = (3, 0, 0) let y = (0, 3, 0) let z = (0, 0, 3) let vx = (5, 0, 0) let vy = (0, 8, 0) let vz = (0, 0, 13) let vxy = arradd(vx, vy) let v = arradd(vxy, vz) let dv = (1, 2, 7) let v2 = arradd(v, dv) // dpoint(O0, label: [$O_0$], anchor: "north") // line(O, (5.2, 0, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) // line(O, (0, 8.2, 0), stroke: (paint: black, thickness: 1pt, dash: "dashed")) // line(vx, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) // line(vy, vxy, stroke: (paint: black, thickness: 1pt, dash: "dashed")) dvec(O, x, label: [$#mvec[x]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, y, label: [$#mvec[y]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, z, label: [$#mvec[z]_i$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O, v, label: [$#mvec[v] (t)$], color: blue, shrink: 4pt, rotate_label: false) dvec(O, v2, label: [$#mvec[v] (t + dd(t))$], color: red, shrink: 4pt, rotate_label: false) dvec(v, v2, label: [$dd(#mvec[v])$], color: maroon , shrink: 4pt, rotate_label: false) // dvec(O, arradd(vx, vy), label: [$a #mvec[x]_i + b #mvec[y]_i $], color: red, shrink: 0pt, rotate_label: false) // dvec(arradd(vx, vy), v, label: [$c #mvec[z]_i $], color: maroon, shrink: 0pt, rotate_label: false) // dimension_line(O, vx, label: [$a$], inv: true, offs: 2, ratio: 90%) // dimension_line(O, vy, label: [$b$], inv: false, offs: 4, ratio: 90%) // dangle3p(vx, O, vxy, right: true, radius:.5) // dangle3p(vy, O, vxy, right: true, radius:.5) // dangle3p(vxy, v, O, right: true, radius:.75) }, ) }) ], caption: "Illustration de la dérivation d'un vecteur dans une base.", placement: top, )<vector_derivative> L'expérience faite ci-dessus montre que la dérivée d'un vecteur par rapport au temps n'est pas unique. En fait, un vecteur peut changer par rapport au temps de 2 façons: / Sa norme peut changer: cette transformation est identique quelle que soit la base depuis laquelle on la considère. / Sa direction peut changer: cette transformation dépend de la base depuis laquelle on la considère. On en conclut que la dérivée d'un vecteur par rapport au temps ne peut être écrite que si on précise par rapport à quelle base on la calcule, ou plus précisément, quelle base on considère comme fixe lors de ce calcul. On définit donc la dérivée d'un vecteur $#mvec[v]$ par rapport au temps $t$ dans la base $cal(B)_i$ comme: $ (dv( #mvec[v], t))_i = #dispvcol(dotv, basis:"i") $ La @vector_derivative[figure] illustre cette notion. On peut en déduire des idées fondamentales pour la suite du cours: - La composante de la dérivée du vecteur qui est colinéaire avec lui même traduit une variation de sa norme. Ainsi, une accélération colinéaire à la vitesse d'un point veut dire qu'il augmente sa vitesse sans en changer la direction si elles sont dans le même sens. - La composante de la dérivée du vecteur qui est perpendiculaire à lui même traduit une variation de sa direction. Ainsi, une accélération perpendiculaire à la vitesse d'un point veut dire qu'il change de direction sans changer la norme de sa vitesse. === Relations entre bases et formule de Bour #let vrot(i, j) = $#mvec( $Omega $ ) ( #i slash #j )$ On a vu que la dérivée d'un vecteur par rapport au temps dépend de la base dans laquelle on la calcule. On peut cependant établir des relations entre les dérivées d'un vecteur dans différentes bases. On considère ainsi 2 bases $cal(B)_i$ et $cal(B)_j$ et un vecteur $#mvec[v]$. La formule de Bour nous permet d'écrire que: $ (dv( #mvec[v], t))_j = (dv( #mvec[v], t))_i + #vrot("i", "j" ) and #mvec[v] $<formule_bour> Le corollaire est que pour un vecteur unitaire dont la norme est de 1 ne varie donc pas, on a: $ (dv( #mvec[x]_i, t))_j = #vrot("i", "j" ) and #mvec[x]_i $<formule_bour_unitaire> Les @formule_bour et @formule_bour_unitaire sont fondamentales pour la cinématique. == Variations par rapport à l'espace === Champ équiprojectif #figure( align(center)[ #cetz.canvas({ let O0 = (-8, 0, 0) let x = (3, 0, 0) let y = (0, 3, 0) let A = (1, 2, 0) let B = (-2.5, 5, 0) let BA = arrsub(A, B) let AB = arrsub(B, A) let lAB = anorm(AB) let u = normalize(BA) let v = arotz90(u) let R = (0, 0, -.35) let VA = arradd(arrnumprod(u, 1.75), arrnumprod(v, -2.5)) let VB = arradd(VA, arrcrossprod(BA, R)) let ua = normalize(VA) let va = arotz90(ua, inv: true) let ub = normalize(VB) let vb = arotz90(ub, inv: true) let Ha = arradd(A, arrnumprod(u, arrdotprod(VA, u))) let Hb = arradd(B, arrnumprod(u, arrdotprod(VB, u))) let construction_line_thickness = 0.5pt // catmull((2, 3), (0, 6), (-4, 4), (-1, 2), tension: .4, stroke: black, close: true, name: "potato", fill: yellow.lighten(50%)) // content((name: "potato", anchor: 10%), anchor: "west", padding: .3)[$(S_1)$] dpoint(A, label: "A", anchor: "west") dpoint(B, label: "B", anchor: "south") dvec(A, arradd(A, VA), color: blue, label: [$#mvec[v] (A)$], rotate_label: false, thickness: 2pt, anchor: "north-west", label_fill: none, anchor_at: 100%) dvec(B, arradd(B, VB), color: blue, label: [$#mvec[v] (B)$], rotate_label: false, thickness: 2pt, anchor: "north", label_fill: none, anchor_at: 100%) dpoint(O0, label: [$O_0$], anchor: "north") dvec(O0, arradd(O0, x), label: [$#mvec[x]_0$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) dvec(O0, arradd(O0, y), label: [$#mvec[y]_0$], color: green, shrink: 0, rotate_label: false, thickness: 1pt) line(A, arradd(A, arrnumprod(va, 10)), stroke: (paint: black, thickness: construction_line_thickness), name: "perpA") line(B, arradd(B, arrnumprod(vb, 10)), stroke: (paint: black, thickness: construction_line_thickness), name: "perpB") line(arradd(A, arrnumprod(u, .5 * lAB)), arradd(B, arrnumprod(u, -.5 * lAB)), stroke: (paint: black, thickness: construction_line_thickness)) intersections("i", "perpA", "perpB") dpoint("i.0", label: $I$, anchor: "north") dangle3p(A, arradd(A, ua), arradd(A, va), right: true, radius: .25) dangle3p(B, arradd(B, ub), arradd(B, vb), right: true, radius: .25) line(arradd(A, VA), Ha, stroke: (paint: black, thickness: construction_line_thickness)) line(arradd(B, VB), Hb, stroke: (paint: black, thickness: construction_line_thickness)) dangle3p(Ha, A, arradd(A, VA), right: true, radius: .25, color: red) dangle3p(Hb, B, arradd(B, VB), right: true, radius: .25, color: red) dimension_line(Ha, A, label: [$l$], inv: true, offs: 2, ratio: 90%, invert_label: true) dimension_line(Hb, B, label: [$l$], inv: true, offs: 2, ratio: 90%, invert_label: true) hide(line("i.0", A, stroke: (paint: black, thickness: 2pt), name : "IA")) line("i.0", arradd(A, VA), stroke: (paint: blue, thickness: .5pt), name : "IA2") hide(line("i.0", B, stroke: (paint: black, thickness: 2pt), name : "IB")) line("i.0", arradd(B, VB), stroke: (paint: blue, thickness: .5pt), name : "IB2") let nv = 5 let pv = 100% / nv for i in range(1, nv) { dvec((name:"IA", anchor:i * pv), (name:"IA2", anchor:i * pv), color: blue, label: none, thickness: .5pt, anchor: "north-west", label_fill: none, anchor_at: 100%) dvec((name:"IB", anchor:i * pv), (name:"IB2", anchor:i * pv), color: blue, label: none, thickness: .5pt, anchor: "north-west", label_fill: none, anchor_at: 100%) } }) ], caption: [Un exemple de champ équiprojectif $#mvec[v]$ dans le plan. Les vecteurs $#mvec[v] (A)$ et $#mvec[v] (B)$ ont la même composante $l$ selon la direction $( "AB" )$. On peut en déduire que vecteur $#mvec[v]$ est nécessairement normal à la droite $(#mvec[v] (A), A)$, le vecteur $#mvec[v] (P)$. Il en va de même pour la droite $(#mvec[v] (B), B)$. Le champ est donc nécessairement nul au point $I$, intersection de ces deux droites. Le champ a donc une forme orthoradiale autour de $I$.], placement: top, )<equiprojective_field> Un champ est équiprojectif vérifie: $ forall A, B: #mvec[v] ("A") dot #mvec[$A B$] = #mvec[v] ("B") dot #mvec[$A B$] $ La @equiprojective_field[figure] illustre cette notion. En mécanique, il faut retenir qu''un champ équiprojectif est le champ de moment d'un torseur. Il est donc intéressant de savoir reconnaître sa forme. = Torseurs == Introduction Un torseur est un objet mathématique qui est défini en tout point $P$ par deux vecteurs: / Une résultante: On la note $#mvec[R]$ et celle-ci ne dépend pas du point $P$. / Un moment: On le note $#mvec[M] (P)$ et celui-ci dépend du point $P$ et qui est un champ équiprojectif. On l'écrit sous la forme: $ torseur1(T: T ) = torseur2(R: #mvec[R], M:#mvec[M] (P) , p:A ) = torseur6(rx: R_x, ry:R_y, rz:R_z, mx:M_x (P), my:M_y (P) , mz: M_z (P), p:P, basis: 0) $ Où: $ #mvec[R] = #dispvcol(($R_x$, $R_y$, $R_z$), basis: 0) $ Et: $ #mvec[M] (P) = #dispvcol(($M_x (P)$, $M_y (P)$, $M_z (P)$), basis: 0) $ Un torseur est un formalisme mathématique qui permet de manipuler les champs de vecteurs équiprojectifs. En mécanique, il existe 4 types de champs équiprojectifs et donc de torseurs: / Le torseur d'action mécanique: Son moment représente le couple engendré par une force. / Le torseur cinématique: Son moment représente les vitesses des points appartenant à des solides indéformables. / Le torseur cinétique : Son moment est celui des quantités de mouvement des solides indéformables. / Le torseur dynamique : Son moment est celui des quantités d'accélération des solides indéformables.
https://github.com/ENIB-Community/ENIB_Typst_Internship_Template
https://raw.githubusercontent.com/ENIB-Community/ENIB_Typst_Internship_Template/main/gls.typ
typst
MIT License
#let enib-gloss = ( ( key: "fintech", short: "Fintech", long: "Financial-Technologies Startup", desc: ["Fintech" est la contraction de "finance" et "technologie", et désigne l'industrie financière où les entreprises utilisent les nouvelles technologies pour proposer des services financiers plus efficaces et économiques à leurs clients.], ), ( key: "devops", short: "DevOps", long: "Dev-Ops", desc: [Le DevOps est une combinaison de deux fonctions généralement traitées séparément : le développement applicatif et les opérations (exécuter le logiciel en production et en faire la maintenance).], ), ( key: "si", short: "SI", long: "Système d'information", ), ( key: "ci", short: "CI", long: "Continuous Integration", desc: [L'intégration continue englobe une série de tâches automatisées telles que des tests ou d'autres actions diverses, qui sont exécutées à intervalles réguliers lors de l'intégration de changements au code source.], ), ( key: "bdd", short: "BDD", long: "Base de données", ), )
https://github.com/shuosc/SHU-Bachelor-Thesis-Typst
https://raw.githubusercontent.com/shuosc/SHU-Bachelor-Thesis-Typst/main/template/cover.typ
typst
Apache License 2.0
// 封面 #import "font.typ": * #import "../contents/info.typ": * #set page(footer: none) // 封面页码置0 #counter(page).update(0) #align(center)[ #v(20pt) #table( columns: (140pt, auto, auto), align: horizon, stroke: none, [], [#image("./images/shu_name.png", width: 120%, height: 9%)], [#image("./images/shu_logo.png", width: 40%)] ) #table( columns: (auto), rows: (auto, auto ,auto), stroke: none, gutter: 9pt, text( font: "Times New Roman", size: font_size.xiaoer, weight: "bold" )[SHANGHAI UNIVERSITY], text( font: songti, size: 36pt, )[毕业论文(设计)], text( font: "Times New Roman", size: font_size.sanhao, weight: "bold" )[UNDERGRADUATE THESIS (PROJECT)] ) #v(60pt) #grid( columns: (65pt, 60%), column-gutter: 1pt, rect(width: 100%, inset: 2pt, stroke: none, text( font: kaiti, size: font_size.xiaoer, weight: "bold", overhang: false, "题 目:" )), rect( width: 100%, inset: 2pt, stroke: ( bottom: 1pt + black ), text( font: kaiti, size: font_size.xiaoer, weight: "medium", bottom-edge: "descender" )[ #title ] ) ) #v(100pt) #let info_value(body) = { rect( width: 100%, inset: 2pt, stroke: ( bottom: 1pt + black ), text( font: songti, size: font_size.xiaoer, weight: "medium", bottom-edge: "descender" )[ #body ] ) } #let info_key(body) = { rect(width: 100%, inset: 2pt, stroke: none, text( font: heiti, size: font_size.xiaoer, weight: "bold", overhang: false, body )) } #grid( columns: (80pt, 180pt), rows : (35pt, 35pt), //gutter: 3pt, // row : (auto ,auto, auto, auto, auto, auto), info_key("学  院"), info_value(college), info_key("专  业"), info_value(major), info_key("学  号"), info_value(student_id), info_key("学生姓名"), info_value(student_name), info_key("指导老师"), info_value(advisor), info_key("起讫日期"), info_value(start_and_end_date) ) ]
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/homework-1/calculus-homework14.typ
typst
#import "../template.typ": * #show: project.with( title: "Calculus Homework #14", authors: (( name: "<NAME> (#47)", email: "<EMAIL>", phone: "3230104585" ),), date: "December 28, 2023", ) 习题 5-3 2,3(2)(4),4(2)(4),5,6,12 习题 5-5 1,3,5,9,10,11,13 习题 5-5 15,17,20,21,22,25,30(1)(3)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/tidy/0.2.0/src/tidy-parse.typ
typst
Apache License 2.0
// Matches Typst docstring for a function declaration. Example: // // // This function does something // // // // param1 (string): This is param1 // // param2 (content, length): This is param2. // // Yes, it really is. // #let something(param1, param2) = { // // } // // The entire block may be indented by any amount, the declaration can either start with `#let` or `let`. The docstring must start with `///` on every line and the function declaration needs to start exactly at the next line. // #let docstring-matcher = regex(`((?:[^\S\r\n]*/{3} ?.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]+)`.text) // #let docstring-matcher = regex(`([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*)\n[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text) #let docstring-matcher = regex(`(?m)^((?:[^\S\r\n]*///.*\n)+)[^\S\r\n]*#?let (\w[\w\d\-_]*)`.text) // The regex explained: // // First capture group: ([^\S\r\n]*///.*(?:\n[^\S\r\n]*///.*)*) // is for the docstring. It may start with any whitespace [^\S\r\n]* // and needs to have /// followed by anything. This is the first line of // the docstring and we treat it separately only in order to be able to // match the very first line in the file (which is otherwise tricky here). // We then match basically the same thing n times: \n[^\S\r\n]*///.*)* // // We then want a linebreak (should also have \r here?), arbitrary whitespace // and the word let or #let: \n[^\S\r\n]*#?let // // Second capture group: (\w[\w\d\-_]*) // Matches the function name (any Typst identifier) // Matches an argument documentation of the form `/// - myparameter (string)`. #let argument-documentation-matcher = regex(`[^\S\r\n]*/{3} - ([.\w\d\-_]+) \(([\w\d\-_ ,]+)\): ?(.*)`.text) /// #set raw(lang: "typc") /// Parse a Typst argument list either at /// - call site, e.g., `f("Timbuktu", value: 23)` or at /// - declaration, e.g. `let f(place, value: 0)`. /// /// This function returns a tuple `(args, count-processed-chars)` where /// `count-processed-chars` is the number of processed characters, i.e., the /// length of the argument list and `args` is a list with an entry for each /// argument. /// /// The entries are lists with either one item if the argument is positional /// or two items if the argument is named. In this case, the first item holds /// the name, the second the value. Names as well as values are returned as /// strings. /// /// This function returns `none`, if the argument list is not properly closed. /// Note, that valid Typst code is expected. /// /// *Example: * Calling this function with the following string /// /// ``` /// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}" /// ``` /// /// and index `9` (which points to the opening parenthesis) yields the result /// ``` /// ( /// ( /// ("p1",), /// ("p2", "3pt"), /// ("p3", "()"), /// ("p4", "(entries: ())"), /// ("p5",), /// ), /// 44, /// ) /// ``` /// /// This function can deal with /// - any number of opening and closing parenthesis /// - string literals /// We don't deal with: /// - commented out code (`//` or `/**/`) /// - raw strings with #raw("``") syntax that contain `"` or `(` or `)` /// /// - text (string): String to parse. /// - index (integer): Position of the opening parenthesis of the argument list. /// -> array #let parse-argument-list(text, index) = { if text.len() <= index or text.at(index) != "(" { return none } if text.len() <= index or text.at(index) != "(" { return ((:), 0) } index += 1 let brace-level = 1 let literal-mode = none // Whether in ".." let arg-strings = () let current-arg = "" let is-named = false // Whether current argument is a named arg let previous-char = none let count-processed-chars = 1 let maybe-split-argument(arg, is-named) = { if is-named { let colon-pos = arg.position(":") return (arg.slice(0, colon-pos).trim(), arg.slice(colon-pos + 1).trim()) } else { return (arg.trim(),) } } for c in text.slice(index) { let ignore-char = false if c == "\"" and previous-char != "\\" { if literal-mode == none { literal-mode = "\"" } else if literal-mode == "\"" { literal-mode = none } } if literal-mode == none { if c == "(" { brace-level += 1 } else if c == ")" { brace-level -= 1 } else if c == "," and brace-level == 1 { arg-strings.push(maybe-split-argument(current-arg, is-named)) current-arg = "" ignore-char = true is-named = false } else if c == ":" and brace-level == 1 { is-named = true } } count-processed-chars += 1 if brace-level == 0 { if current-arg.trim().len() > 0 { arg-strings.push(maybe-split-argument(current-arg, is-named)) } break } if not ignore-char { current-arg += c } previous-char = c } if brace-level > 0 { return none } return (arg-strings, count-processed-chars) } /// This is similar to @@parse-argument-list but focuses on parameter lists /// at the declaration site. /// /// If the argument list is well-formed, a dictionary is returned with /// an entry for each parsed /// argument name. The values are dictionaries that may be empty or /// have an entry for the key `default` containing a string with the parsed /// default value for this argument. /// /// /// /// *Example* \ /// Let us take the string /// ```typc /// "#let func(p1, p2: 3pt, p3: (), p4: (entries: ())) = {...}" /// ``` /// Here, we would call `parse-parameter-list(source-code, 9)` and retrieve /// #pad(x: 1em, ```typc /// ( /// p0: (:), /// p1: (default: "3pt"), /// p2: (default: "()"), /// p4: (default: "(entries: ())"), /// ) /// ```) /// /// - text (string): String to parse. /// - index (integer): Index where the argument list starts. This index should /// point to the character *next* to the function name, i.e., to the /// opening brace `(` of the argument list if there is one (note, that /// function aliases for example produced by `myfunc.where(arg1: 3)` do /// not have an argument list). /// -> none, dictionary #let parse-parameter-list(text, index) = { let result = parse-argument-list(text, index) if result == none { return none } let (arg-strings, count) = result let args = (:) for arg in arg-strings { if arg.len() == 1 { args.insert(arg.at(0), (:)) } else { args.insert(arg.at(0), (default: arg.at(1))) } } return args } // Take the result of `parse-argument-list()` and retrieve a list of positional // and named arguments, respectively. The values are `eval()`ed. #let parse-arg-strings(args) = { let positional-args = () let named-args = (:) for arg in args { if arg.len() == 1 { positional-args.push(eval(arg.at(0))) } else { named-args.insert(arg.at(0), eval(arg.at(1))) } } return (positional-args, named-args) } /// Count the occurences of a single character in a string /// /// - string (string): String to investigate. /// - char (string): Character to count. The string needs to be of length 1. /// - start (integer): Start index. /// - end (end): Start index. If `-1`, the entire string is searched. /// -> integer #let count-occurences(string, char, start: 0, end: -1) = { let count = 0 if end == -1 { end = string.len() } for c in string.slice(start, end) { if c == char { count += 1 } } // let i = 0 // while i < end { // if string.at(i) == char { count += 1} // i += 1 // } count } #let parse-description-and-documented-args(docstring, parse-info, first-line-number: 0) = { let fn-desc = "" let started-args = false let documented-args = () let return-types = none for (line-number, line) in docstring.split("\n").enumerate(start: first-line-number) { // Check if line is a test line -> replace it with a call to #test() if line.starts-with("/// >>> ") { line = "/// #test(`" + line.slice(8) + "`, source-location: (module: \"" line += parse-info.label-prefix + "\", line: " + str(line-number) + "))" } let arg-match = line.match(argument-documentation-matcher) if arg-match == none { let trimmed-line = line.trim().trim("/") if trimmed-line.trim().starts-with("->") { return-types = trimmed-line.trim().slice(2).split(",").map(x => x.trim()) } else { if not started-args { fn-desc += trimmed-line + "\n"} else { documented-args.last().desc += "\n" + trimmed-line } } } else { started-args = true let param-name = arg-match.captures.at(0) let param-types = arg-match.captures.at(1).split(",").map(x => x.trim()) let param-desc = arg-match.captures.at(2) documented-args.push((name: param-name, types: param-types, desc: param-desc)) } } return (fn-desc, documented-args, return-types) } #let parse-variable-docstring(source-code, match, parse-info) = { let docstring = match.captures.at(0) let var-name = match.captures.at(1) let first-line-number = count-occurences(source-code, "\n", end: match.start) + 1 let (var-desc, _, return-types) = parse-description-and-documented-args(docstring, parse-info, first-line-number: first-line-number) let var-specs = ( name: var-name, description: var-desc, ) if return-types != none and return-types.len() > 0 { var-specs.type = return-types.first() } return var-specs } /// Parse a function docstring that has been located in the source code with /// given match. /// /// The return value is a dictionary with the keys /// - `name` (string): the function name. /// - `description` (content): the function description. /// - `args`: A dictionary containing the argument list. /// - `return-types` (array(string)): A list of possible return types. /// /// The entries of the argument list dictionary are /// - `default` (string): the default value for the argument. /// - `description` (content): the argument description. /// - `types` (array(string)): A list of possible argument types. /// Every entry is optional and the dictionary also contains any non-documented /// arguments. /// /// /// /// - source-code (string): The source code containing some documented Typst code. /// - match (match): A regex match that matches a documentation string. The first /// capture group should hold the entire, raw docstring and the second capture /// the function name (excluding the opening parenthesis of the argument list /// if present). /// - parse-info (dictionary): /// -> dictionary #let parse-function-docstring(source-code, match, parse-info) = { let docstring = match.captures.at(0) let fn-name = match.captures.at(1) let first-line-number = count-occurences(source-code, "\n", end: match.start) + 1 let (fn-desc, documented-args, return-types) = parse-description-and-documented-args(docstring, parse-info, first-line-number: first-line-number) let args = parse-parameter-list(source-code, match.end) for arg in documented-args { if arg.name in args { args.at(arg.name).description = arg.desc.trim("\n") args.at(arg.name).types = arg.types } else { assert( false, message: "The parameter \"" + arg.name + "\" does not appear in the argument list of the function \"" + fn-name + "\"" ) } } if parse-info.require-all-parameters { for arg in args { assert( documented-args.find(x => x.name == arg.at(0)) != none, message: "The parameter \"" + arg.at(0) + "\" of the function \"" + fn-name + "\" is not documented. " ) } } return ( name: fn-name, description: fn-desc, args: args, return-types: return-types ) }
https://github.com/maucejo/book_template
https://raw.githubusercontent.com/maucejo/book_template/main/src/_book-environments.typ
typst
MIT License
#import "_book-params.typ": * #let front-matter(body) = { set heading(numbering: none) set page(numbering: "i") states.page-numbering.update("i") states.num-pattern.update(none) counter(page).update(0) body } // Main matter #let main-matter(body) = { set page(numbering: "1/1") states.page-numbering.update("1/1") states.num-heading.update("1") states.num-pattern.update("1.1.") counter(page).update(1) body } // Main matter #let back-matter(body) = { set page(numbering: none) body } // Appendix #let appendix(body) = { set page(numbering: "1/1") // Reset heading counter counter(heading.where(level: 1)).update(0) // Reset heading counter for the table of contents counter(heading).update(0) states.num-heading.update("A") states.num-pattern.update("A.1.") states.isappendix.update(true) body }
https://github.com/elpekenin/access_kb
https://raw.githubusercontent.com/elpekenin/access_kb/main/typst/content/main.typ
typst
#import "@preview/codly:1.0.0": codly-range #import "@preview/glossarium:0.4.2": gls, print-glossary #import "../glossary.typ": entry-list #import "utils.typ": cli, snippet #include "parts/front_page.typ" /// White page #page[ // 0 to not render page number here #counter(page).update(0) ] /// Document overview (sections, glossary, figures, etc) #outline( fill: block(width: 100% - 1.5em)[ #repeat(" . ") ], indent: auto, ) #heading("Listado de acronimos", outlined: false, numbering: none) #print-glossary( // TODO: avoid centered text entry-list, show-all: true, disable-back-references: true, ) #outline( target: figure.where(kind: image), title: [Listado de imágenes], ) #outline( target: figure.where(kind: "snippet"), title: [Listado de código], ) #outline( target: figure.where(kind: "cmd"), title: [Listado de comandos], ) /// Document begins, finally = Resumen #include "parts/summary.typ" = Introducción <introducción> #include "parts/introduction.typ" == Requisitos previos <requisitos-previos> A lo largo del documento se asume cierto conocimiento de programación, así como tener algunos programas instalados. La mayoría son conocidos, pero aquí tenemos una lista con algunos menos populares y enlaces a sus respectivas páginas oficiales/documentación - Rust @rust. Lenguaje de programación - typst @typst. Lenguaje de marcado, parecido a LaTex, con el que se ha compuesto este documento. - WSL @wsl. Herramienta de Windows, similar a una máquina virtual, para tener un entorno Linux = Estado del arte <estado-del-arte> #include "parts/state_of_the_art.typ" = Desarrollo #include "parts/development.typ" == Hardware <hardware> #include "parts/hardware/main.typ" == Firmware <firmware> === Funcionalidad <funcionalidad> La mejor parte de usar una librería tan extendida como lo es QMK es que tenemos muchas facilidades a la hora de escribir el codigo ya que buena parte del trabajo está hecho ya. Esto incluye: - Gestión sobre #gls("usb") para reportar distintos endpoints (teclado, ratón, multimedia) - Drivers para diversos periféricos tales como las pantallas ya comentadas, piezoelectricos para tener feedback sonoro o solenoides para vibración al pulsar las teclas, por nombrar algunos... - Abstracciones para poder usar la misma API en diversos microcontroladores que internamente utilizan código y hardware muy diferente - Documentación extensa y detallada - Servidor ofcial en Discord donde podemos encontrar ayuda === Escaneo de teclas <escaneo-de-teclas> Como se ha comentado en el apartado anterior, vamos a usar registros de desplazamiento, sin embargo QMK tiene soporte para cableado directo, en matrices y usando algunos otros circuitos, como _IO expanders_. Sin embargo este no es el caso para los registros por lo que tendemos que escribir un poco de código para leer su información. === Pantallas <pantallas-1> QMK tiene una API estandarizada (Quantum Painter#cite(<qp>)) para primitivas de dibujo en interfaces gráficas. Aún es "joven" y no soporta demasiadas pantallas, pero hace gran parte del trabajo por nosotros. === Pantalla táctil <pantalla-táctil> QMK también tiene una capa de abstracción#cite(<pointing>) para diversos sensores que permiten mover el cursor, sin embargo todos se basan en medir desplazamientos y no una coordenada como es el caso de la pantalla táctil, por tanto en este caso nos vemos obligados a diseñar una arquitectura de software nueva, para poder trabajar con este otro tipo de datos de entrada. = Desarrollo <desarrollo> == Hardware <hardware-1> === Objetivos <objetivos> Las metas principales a la hora de diseñar el teclado han sido el usar la menor cantidad de pines posible para las tareas "básicas" y el exponer todos los pines restantes así como varias tomas de alimentación. De esta forma, el teclado puede servir como placa de pruebas donde desarrollar drivers para otro hardware y además es modular, ya que nos permite añadir más periféricos (por ejemplo, para sonido) en el futuro sin necesidad de tener que fabricar una nueva PCB. === Distribución <distribución> He optado por una disposición ortolineal, split y (por ahora) QWERTY, reduciendo un par de columnas en el lateral derecho respecto al tamaño habitual, ya que varias de esas teclas raramente se usan, y al tener una forma simétrica es más sencillo de diseñar. #figure( image("../images/layout.png", width: 100%), caption: [Diseño aproximado del teclado], ) === Desarrollo <desarrollo-1> ==== Teclas <teclas> Como ya vimos en la sección 3.2.1 @sec:scanning, el escaneo de teclas se hará mediante registros de desplazamiento de entrada en paralelo y salida en serie, para un mekor tiempo de respuesta vamos a usar componentes SPI en vez de I2C (protocolo más rápido). Podríamos haber usado SN74HC165 que son algo más baratos y fáciles de encontrar, pero vamos a usar SN74HC589ADR2G ya que tienen el mismo funcionamiento pero presentan 7 de las 8 entradas en el mismo lateral del circuito integrado (en vez de 4 en cada lado), por lo que son mucho más sencillos de enrutar. Además, aunque cada mitad del teclado tiene un total de 29 teclas y, por tanto, 4 registros (32 entradas) nos hubieran bastado; vamos a usar un registro por cada fila (5), ya que evitamos tener que enrutar una de las teclas hacía el otro lado del registro y tener algunas conexiones "saltando" de una fila a otra. Realizamos las conexiones de la siguiente manera: - Las entradas que no usamos las conectaremos a tierra para que se lean como '0'. Las teclas se conectan a VCC y (mediante "pulldown") a una entrada. De esta forma leeremos '1' cuando estén pulsadas y '0' cuando no lo estén - La salida serie de cada integrado se conecta a la entrada serie del siguiente. El último se conecta a MISO (entrada SPI del microcontrolador) - Las señales CS, Latch y CLK son comunes a todos los integrados - Como la señal Latch resulta ser la inversa de CS, en vez de usar otro pin, invertimos el voltaje con un MOSFET #figure( image("../images/inverter.png", width: 30%), caption: [MOSFET como inversor], ) #figure( image("../images/piso.png", width: 80%), caption: [SN74HC589ADR2G para una fila], ) ==== Cableado de las pantallas <cableado-de-las-pantallas> Vamos a usar una pantalla en el lado izquierdo (IL91874) y dos en el derecho (ILI9163 e ILI9341), estos dispositivos necesitan de conexión SPI así como pines extra (DC, CS, RST) para ser controlados. Dado que las vamos a conectar al mismo bus, solo necesitamos 3 pines para SPI y puesto que no podemos mandar información a dos pantallas simultáneamente, también pueden usar una línea DC común. Sin embargo las señales de DC y RST deben ser individuales y además la ILI9341 necesita dos señales DC, una para la pantalla y otra para el sensor táctil. Por tanto, también usaremos registros de desplazamiento, en este caso de entrada serie con salidas en paralelo (SN74HC595) y dichas salidas se conectaran a las entradas de control de las pantallas. Como ya teníamos un bus SPI configurado, usar estos registros tan solo supone el uso de otro pin (CS). Sin embargo, como necesitamos cambiar estas señales mientras estamos hablando con las pantallas, no podemos tener las dos cosas en el mismo bus, por lo que usaremos un bus para los registros (escanear teclas y señales de control) y otro bus para las pantallas. Lo mas importante de este diseño es que encadenando suficientes registros podríamos controlar tantas señales de control para diversos dispositivos como queramos, manteniendo mínima la utilización de pines del MCU. == Firmware <firmware-1> === Instalación y configuración de QMK <instalación-y-configuración-de-qmk> Para usar QMK#cite(<qmk>) instalamos su CLI ejecutando ya que se trata de una librería escrita en Python y está disponible en el repositorio de paquetes de Python(pip). Tras esto, descargamos el código fuente con , a este comando le podemos pasar como parámetro nuestro fork del repositorio (en mi caso ), para poder usar git, ya que no tendremos permisos en el repositorio oficial. Este comando también nos instalará los compiladores necesarios y comprobará las udev de nuestro sistema Linux, para que podamos trabajar con los dipositivos sin problema, en caso de que no estén bien configuradas podemos usar copiar el archivo en . Finalmente podemos ejecutar para comprobar el estado de QMK. Para poder hacer debug con he necesitado añadir una línea a dicho archivo: Opcionalmente, podríamos instalar LVGL#cite(<lvgl>) funciones gráficas más complejas en la pantalla LCD, en vez de usar el driver de QMK. Esto se hace con (desde el directorio base de QMK). Seguidamente, usamos el código de jpe#cite(<lvgl-jpe>) para usar esta librería. De momento no he implementado esta librería puesto que añadiría bastante complejidad al código y tampoco vamos a hacer ninguna interfaz especialmente llamativa. Para acelerar el proceso de compilado podemos guardar nuestra configuración (teclado y keymap) y el número de hilos que usará el compilador #cli( ```bash $ qmk config user.keyboard=elpekenin/access $ qmk config user.keymap=default $ qmk config compile.parallel=20 ```, caption: [Personalizar QMK], ) === Driver para pantalla ili9486 <driver-para-pantalla-ili9486> Para hacer pruebas antes de diseñar y fabricar la PCB, he usado un módulo que integra una pantalla, sensor táctil y lector de tarjeta SD. Sin emabargo, QMK no tiene soporte para este modelo concreto de pantalla. Por tanto, usando como base el código#cite(<ili9488>) para otro dispositivo de la misma familia, y con ayuda de los usuarios \@sigprof y \@tzarc he desarrollado un driver#cite(<ili9486-pr>) para la pantalla usada. Los cambios se reducen a dos cosas: - Cambiar la fase de inicialización de la pantalla, que configura valores como el formato en el que se envían los píxeles a mostrar - Puesto que la pantalla contiene un circuito que convierte la línea SPI en una señal paralela de 16 bits que se envía a la pantalla, mediante registros de desplazamiento, tendremos problemas al enviar información de un tamaño que no sea múltiplo de 16, por tanto hacemos un par de cambios al código "normal". === Dibujar por USB <section:dibujar-usb> Lo siguiente que necesitamos resolver es controlar la pantalla desde el ordenador, de forma que podamos dibujar en ella desde nuestro software, para esto usaremos la funcionalidad XAP#cite(<xap>) (aún en desarrollo), que nos proporciona un nuevo endpoint HID#cite(<hid>) sobre el bus USB y un protocolo#cite(<xap-specs>) que podemos extender. Ahora podemos definir nuestros mensajes simplemente creando un archivo #cite(<xap-custom-msg>) Una vez creados los mensajes, añadimos el código#cite(<qp-xap-handlers>) que se ejecuta cuando los recibamos === Mejora algoritmo elipses <mejora-algoritmo-elipses> Durante las pruebas con el script anterior, vi que el algoritmo para dibujar elipses funcionaba regular, por lo que hice un _refactor_ del mismo. Es decir, mantenemos la misma "forma" (atributos que se reciben y valor devuelto), pero la implementación#cite(<ellipse-pr>) es compleamente diferente. Sigue sin ser perfecto, pero parece funcionar mejor. === Driver para sensor XPT2046 <driver-para-sensor-xpt2046> Al igual que hemos necesitado un driver (código que nos permite comunicarnos con el hardware) para dibujar en la pantalla, necesitamos otro para poder leer la posición en la que esta ha sido pulsada. Por desgracia, QMK no tiene ninguna característica parecida, por lo que usaremos el código#cite(<touch-driver>) que he escrito para ello desde 0. Este hardware, al igual que la pantalla, también tiene una particularidad, y es que la función proporcionada por QMK, realmente es un intercambio de información en vez de solo lectura, esto es debido a que SPI es un protocolo síncrono. El problema aparece porque QMK envía todos los bits a 1 -dado que algunos microcontroladores hacen esto por hardware y no se puede cambiar- para poder recibir información, *sin embargo*, el XPT2046 (a diferencia de la mayoria de chips) utiliza esta información que recibe mientras que nos reporta su información para cambiar su configuración. De forma, que en caso de que los 2 últimos bits que enviamos no tengan el valor adecuado, no podremos usar el sensor. Lo bueno es que la solución es tan simple como usar para enviar un byte vacío y recibir la respuesta dejando una configuración conveniente. === Generar imágenes <generar-imágenes> Dado que vamos a usar varios iconos para hacer la interfaz gráfica en la pantalla, he cogido la colección de iconos Material Design Icons#cite(<templarian-mdi>) y he convertido todos sus iconos al formato que utiliza QMK para representar imágenes. Las imágenes originales, scripts usados para la conversión y los archivos en formato QGF#cite(<qgf>) se pueden encontrar en este repositorio#cite(<mdi-qgf>) === Añadir nuestro código <añadir-nuestro-código> Para poder usar nuestros nuevos archivos, no es suficiente con añadir un sino que también debemos indicarle a las herramientas de compilado que "busquen" archivos en la carpeta donde tenemos el código, en este caso la carpeta base del teclado, asi como subcarpeta . También es necesario, no tengo muy claro por qué, añadir los archivos de las imagenes QGF o no podremos usarlos. Este archivo se complica un poco porque no debemos incluir algunos archivos si no están algunas opciones habilitadas, por ejemplo, no debemos añadir las imágenes si no tenemos la opción de usar la pantalla habilitada. Esto lo hacemos con el archivo #cite(<rules-mk>) === Comunicación con el software de PC <comunicación-con-el-software-de-pc> La idea principal del control de la pantalla es que el teclado no dibuje en ella nada, de forma que la controlemos exclusivamente desde el programa desarrollado. De esta manera, lo que haremos será leer el estado del sensor táctil cada 200ms y, en caso de estar pulsado, enviaremos las coordenadas de dicha pulsación. Adicionalmente enviamos otro mensaje como si se hubiera pulsado la posicion (0, 0), donde no hay ninguna lógica, para que se "limpie" la pantalla al acabar una pulsación. El código relevante es: Al igual que hemos dicho antes con añadir o no añadir un archivo a nuestro código según la configuración, debemos hacer lo mismo con bloques de código, usando de forma que no intentemos usar la pantalla táctil o enviar un mensaje XAP si estas características no se han activado. == Software <software> Para poder intercambiar información con el teclado de forma que podamos configurarlo o enviarle información en vez de simplemente escuchar las teclas que se han pulsado, vamos a desarrollar un programa en Tauri#cite(<tauri>) (librería escrita en Rust) ya que permite usar el mismo código en multitud de sistemas operativos gracias a que funciona internamente con un servidor HTML. === Instalación <instalación> Para instalar Rust podemos usar pacman , sin embargo para desarrollar código es preferible usar un script que nos proporciona la comunidad del lenguaje, y que permite cambiar fácilmente la versión del lenguaje con la que compilamos, tan sólo necsitamos ejecutar La comunicación con el teclado se realiza usando la librería hidapi#cite(<hidapi>), a la que accedemos desde Rust gracias al wrapper#cite(<hidapi-rs>) que implementa una "pasarela" a la librería en C. Para instalarla tan solo necesitamos añadirla al archivo de nuestro proyecto Primero instalamos NodeJS con , después clonamos el repositorio#cite(<qmk_xap>), usado de base (y en el que he colaborado) para desarrollar el software. Para instalar las dependencias de JavaScript ejecutamos . Ahora ya podemos correr para lanzar nuestro programa. He tenido que desactivar la opción wgl(libreria de Windows para OpenGL) en VcXsrv para que funcionase === Desarrollo <desarrollo-2> ==== Escuchar nuestros mensajes <escuchar-nuestros-mensajes> Lo primero que vamo a añadir es la capacidad de poder recibir los mensajes que nos llegan desde el teclado, para ello definimos un struct que indique el formato del mensaje, podemos ver algo de código que no es necesario entender, lo importante son los dos `u16` #snippet( ```rust #[derive(BinRead, Debug)] pub struct ReceivedUserBroadcast { pub x: u16, pub y: u16, } impl XAPBroadcast for ReceivedUserBroadcast {} ```, caption: [Definición de mensaje de usuario], ) Acto seguido, hacemos que el _eventloop_ de nuestra aplicación escuche los mensajes, ya que por defecto los ignora. Primero definimos un nuevo evento dentro del listado de tipos de evento #snippet( ```rust pub(crate) enum XAPEvent { HandleUserBroadcast { broadcast: BroadcastRaw, id: Uuid, }, // -- Otros eventos recortados -- } ```, caption: [Definición de nuevo evento], ) Añadimos el código necesario para publicar este nuevo tipo de evento al recibir los mensajes correspondientes #snippet( ```rust match broadcast.broadcast_type() { BroadcastType::User => { event_channel .send(XAPEvent::ReceivedUserBroadcast { id, broadcast }) .expect("failed to send user broadcast event!"); } // -- Otros tipos recortados -- } ```, caption: [Emitir evento al recibir mensaje], ) Y por último hacemos la relación entre este evento la lógica de usuario que se debe ejecutar con ellos. #snippet( ```rust match broadcast.broadcast_type() { // -- Otros eventos recortados -- Ok(XAPEvent::ReceivedUserBroadcast{broadcast, id}) => { user::broadcast_callback(broadcast, id, &state); } } ```, caption: [Manejo del evento], ) Toda la lógica de usuario (personalizable), se puede encontrar en el archivo #cite(<user-rs>) ==== Correr aplicación en segundo plano <correr-aplicación-en-segundo-plano> Dado que todo el contenido de la pantalla, así como su funcionalidad al pulsarla dependen de nuestra aplicación, vamos a hacer todo lo posible para que se mantenga abierta. Para ello hacemos que al pulsar el boton de cerrar, la app se minimice en vez de terminar y le añadimos un _systray_ para tener un icono en la barra de tareas donde podamos volver a ponerla en pantalla #snippet( ```rust let tray_menu = SystemTrayMenu::new() .add_item(CustomMenuItem::new("show".to_string(), "Show")) .add_item(CustomMenuItem::new("hide".to_string(), "Hide")) .add_native_item(SystemTrayMenuItem::Separator) .add_item(CustomMenuItem::new("quit".to_string(), "Quit")); ```, caption: [Creación del _systray_], ) #snippet( ```rust .system_tray(system_tray) .on_system_tray_event(move |app, event| match event { // Al usar click izquierdo SystemTrayEvent::MenuItemClick { id, .. } => { // Segun boton usado match id.as_str() { "hide" => app.get_window("main").unwrap().hide().unwrap(), "quit" => { user::on_close(_state.clone()); std::process::exit(0); }, "show" => app.get_window("main").unwrap().show().unwrap(), _ => {} } }, _ => {} // Otros eventos, no hacemos nada } ) ```, caption: [Añadir _systray_ al programa, con su logica], ) #snippet( ```rust .on_window_event( |event| match event.event() { tauri::WindowEvent::CloseRequested { api, .. } => { event.window().hide().unwrap(); api.prevent_close() }, _ => {} // Otros eventos, no hacemos nada } ) ```, caption: [Interceptar señal de cierre de ventana], ) ==== Indicador de conexión <indicador-de-conexión> Vamos a añadir también un indicador en la pantalla, de forma que Tauri nos haga saber cuando se conecta o desconecta del teclado, evitando que intentemos usar la pantalla cuando no va a funcionar. Editamos el eventlooop y definimos las nuevas funciones #snippet( ```diff match msg { Ok(XAPEvent::Exit) => { info!("received shutdown signal, exiting!"); + user::on_close(state); break 'event_loop; }, Ok(XAPEvent::NewDevice(id)) => { if let Ok(device) = state.lock().get_device(&id){ info!("detected new device - notifying frontend!"); + user::on_device_connection(device); } } ```, caption: [Hooks de usuario], ) ==== Arrancar HomeAssistant <arrancar-homeassistant> Dado que nuestro programa se tiene que comunicar con la domótica de casa, vamos a asegurarnos de que esté ejecutándose, iniciándolo al abrir el programa. Al arrancar la aplicación ejecutamos: #snippet( ```rust pub(crate)fn on_init() { match std::process::Command::new("sh") .arg("-c") .arg(r#"sudo systemctl start docker && cd $HOME/docker && docker compose up -d"#) .output() { Ok(_) => error!("on_init went correctly"), Err(out) => error!("on_init failed due to: {out}") } } ```, caption: [Hook de inicio], ) = Lineas futuras <lineas-futuras> = Anexo I: Instalación de MicroPython <anexo-i-instalación-de-micropython> Durante el desarrollo del proyecto, he probado _MicroPython_#cite(<micropython>) una implementación en C del intérprete de Python que se enfoca a su uso en microcontroladores. Finalmente he descartado usarlo debido a su menor rendimiento y la falta de muchas opciones que vienen hechas en QMK. Sin embargo creo que puede ser una buena alternativa para prácticas de electónica en la universidad, reemplazando a Arduino, puesto que Python es mucho más amigable que C o C++ == Preparar el compilador <preparar-el-compilador> Tras clonar el source de MicroPython , hacemos para compilar el compilador cruzado de MicroPython que nos permitirá convertir el código fuente para ser ejecutado en diferentes arquitecturas. == Compilar para Linux (Opcional) <compilar-para-linux-opcional> Si queremos usar MicroPython en nuestro ordenador para hacer pruebas, en vez de CPython(que es la versión más común), usaremos el compilador que acabamos de construir para compilar el código fuente del intérprete y usarlo en nuestra máquina #cli( ```bash $ cd ports/unix $ make submodules $ make ```, caption: [Compilar MicroPython para Linux], ) #cli( ```bash $ cd build-standard $ ./micropython MicroPython 13dceaa4e on 2022-08-24; linux [GCC 12.2.0] version Use Ctrl-D to exit, Ctrl-E for paste mode >>> ```, caption: [Ejecutar MicroPython en Linux], ) == Compilar para RP2040 <compilar-para-rp2040> Primero instalamos un compilador necesario para la arquitectura del procesador, en mi caso (Arch Linux), el comando es y después añadimos la configuración necesaria para reportar y usar un endpoint HID, siguiendo (y adaptando) #cite(<tusb-rp2>) Definimos en C el módulo #cite(<mod-usb-hid>);, será la macro encargada de añadir el módulo al firmware compilado. También debemos editar un archivo de configuración de compilación para que se añada el nuevo archivo Para poder compilar la versión de RP2040 en Arch he necesitado instalar el paquete Por último, compilamos con #cli( ```bash $ cd ports/rp2 $ make submodules $ make clean $ make ```, caption: [Compilar MicroPython para RP2040], ) Y ya podremos flashear este binario en nuestra placa de desarrollo #bibliography( "../bibliography.yml", title: "Bibliografía", ) = Anexo B. Código fuente del informe (typst). Aquí están adjuntas las primeras líneas del código fuente con el que he generado este documento. #text(size: 8pt)[ #codly-range(start: 1, end: 20); #raw( read("main.typ").split("\n").slice(0, 30).join("\n"), lang: "typst", ) ]
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/README.md
markdown
MIT License
# hydra Hydra is a Typst package allowing you to easily display the heading like elements anywhere in your document. It's primary focus is to provide the reader with a reminder of where they currently are in your document only when it is needed. ## Example ```typst #import "@preview/hydra:0.5.1": hydra #set page(paper: "a7", margin: (y: 4em), numbering: "1", header: context { if calc.odd(here().page()) { align(right, emph(hydra(1))) } else { align(left, emph(hydra(2))) } line(length: 100%) }) #set heading(numbering: "1.1") #show heading.where(level: 1): it => pagebreak(weak: true) + it = Introduction #lorem(50) = Content == First Section #lorem(50) == Second Section #lorem(100) ``` ![ex] ## Documentation For a more in-depth description of hydra's functionality and the reference read its [manual]. ## Contribution For contributing, please take a look [CONTRIBUTING][contrib]. ## Etymology The package name hydra /ˈhaɪdrə/ is a word play headings and headers, inspired by the monster in greek and roman mythology resembling a serpent with many heads. [ex]: examples/example.png [manual]: doc/manual.pdf [contrib]: CONTRIBUTING.md
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Reading/Reconstruction/SIREN.typ
typst
--- order: 2 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "Reading SIREN", lang: "zh", ) #let SDF = math.text("SDF") #let clamp = math.text("clamp") #let Occupancy = math.text("Occupancy") #let NeRF = math.text("NeRF") = SIREN - Implicit Neural Representations with Periodic Activation Functions - 时间:2020.6 == 引言 - 感兴趣的是一类特殊函数: $ F (x, Phi, nabla_x Phi, nabla^2_x Phi, ...) = 0, Phi : x arrow.r.bar Phi(x) $ 目标是学习一个神经网络,该神经网络对 $Phi$ 进行参数化,以将 $x$ 映射到某个感兴趣的量,同时满足上式约束(跨科学领域的各种问题都属于这种形式) - 与替代方案(例如基于离散网格的表示)相比,连续参数化具有多种优势。 + 具有更高的内存效率,从而它的建模不受限于网格分辨率,而是受限于底层网络架构。 + 可微分意味着可以分析计算梯度和高阶导数,例如使用自动微分 + 最后,通过良好的导数,隐式神经表示可以为解决反问题(例如微分方程)提供新的工具 - 因此隐式神经表征引起了人们的兴趣。大多数表示都建立在基于 ReLU 的 MLP 之上,这些架构缺乏表示底层精细细节的能力,并且通常不好表示目标信号的导数。 - 部分原因是 ReLU 的分段线性导致二阶导数处处为零,高阶信息缺失。 - 虽然替代激活函数(例如 tanh 或 softplus)能够表示高阶导数,但我们证明它们的导数通常表现不佳,也无法表示精细细节 - 为了解决这些限制,我们利用具有周期性激活函数的 MLP 来实现隐式神经表示。我们证明,这种方法不仅能够比 ReLU-MLP 或并行工作中提出的位置编码策略更好地表示信号中的细节,而且这些属性也独特地适用于导数,这对于许多应用来说至关重要 - 贡献总结 + 提出周期性激活函数,可以稳健地拟合复杂信号,例如自然图像和 3D 形状及其导数 + 用于训练这些表示并验证可以使用超网络学习这些表示的分布的初始化方案。(利用 hypernetwork 的网络初始化方案) + 应用演示:图像、视频和音频表示;3D 形状重建;求解旨在估计信号的一阶微分方程仅用其梯度进行监督;并求解二阶微分方程 - 这里面比较核心的其实应该是第二点,因为第一点相信很多人都想过,只是因为效果不好导致没人用,现在作者提出好的初始化方案使得这个方法变得可行 == Formulation - 把上面说的那个函数表示为可行集问题 ${C_m (a(x), Phi(x), nabla Phi(x), nabla^2 Phi(x), ...)}_(m=1)^M$,满足 $M$ 个约束,每个都把 $Phi$ 关联到 $a(x)$(?) $ "find" Phi(x) "subject to" C_m (a(x), Phi(x), nabla Phi(x), nabla^2 Phi(x), ...) = 0, ~~~ forall x in Omega_m, m = 1, ..., M $ #note()[ paper 中的 notation 对初学者来说可能有些不适,因为长期以来使用神经网络处理图像数据时,input 大多情况下是图像本身(e.g. matrices with RGB channels);但是这篇 paper 中,我们用神经网络所学是 $Phi$,这里面的 input 是 pixel coordinate(即 $x=(i, j)$),而 $Phi(x)$ 代表着不同 pixel value。$Phi(x)$ 表示对给定的像素位置输入,学出来网络认为这里的值是什么。而 $a(x)$ 表示这个像素位置的 ground truth,所以说每个约束都把 $Phi$ 关联到 $a(x)$,意思是约束神经网络往 $a$ 的方向学。这一点需要格外注意 ] - 损失函数就是在所有约束上的偏差 $ L = int_Omega sum_(m=1)^M bold(1)_(Omega_m) (x) dot norm(C_m (a(x), Phi(x), nabla Phi(x), nabla^2 Phi(x), ...)) dif x $ - 损失函数通过采样 $Omega$ 来强制执行(意思是说通过数据集采样模拟真实模型?),数据集 $D = {(x_i, a(x_i))}$ 是一组坐标 $x_i in Omega$ 以及约束中出现的量 $a(x_i)$ 的样本的元组 $ tilde(L) = sum_(i in D) sum_(m=1)^M norm(C_m (a(x), Phi(x), nabla Phi(x), nabla^2 Phi(x), ...)) $ - 总之就是定义了一套数学语言来描述这么个事情:为了找到比较好的 $Phi(x)$ 值,设计了一个 loss 损失函数,通过最小化这个损失函数,模型可以捕捉输入数据的周期性结构,学习到这个图片的隐式神经表示 === 隐式神经表示的周期性激活函数 - 文章提出的核心 idea,即用 $sin$ 函数来做激活函数 $ Phi(x) = W_n (phi_(n-1) circle phi_(n-2) circle ... circle phi_0) (x) + b_n, ~~~ x_i arrow.r.bar phi_i (x_i) = sin(W_i x_i + b_i) $ - 神经网络设为 $n$ 层 layer ,每层线性层计算操作为 $W_i * x_i + b_i$ ,并添加 $sin$ 操作,注意每个 $sin$ 是带缩放的(这一点好像论文里都没怎么提到,直到后面第一层初始化那里才说,令人费解) - 第 $0$ 到 $n-1$ 层,线性操作 + 激活 (最后层不加激活,避免值域错误) - 有趣的是,SIREN 的任何导数本身就是 SIREN,因为正弦的导数是余弦,即相移正弦。因此,SIREN 的导数继承了 SIREN 的属性,使我们能够用“复杂”信号来监督 SIREN 的任何导数。 - 在实验中发现,当使用涉及 $Phi$ 导数的约束 $C_m$ 来监督 SIREN 时,函数 $Phi$ 仍然表现良好,这对于解决许多问题(包括边值问题 (BVPs))至关重要 - 意思是说 + 即便我们用的是一张图片的 pixel value(零阶)进行的训练,训练之后的 SIREN 也可以“顺便”很好地重构出一阶、二阶导函数的信息 + 反过来,我们也可以用图像的导数图来训练网络,而不是直接用图像本身。而这样的网络依旧可以还原出原图 - 换句话说,SIREN 利用 sin 函数的导数不变性,真正做到了把低阶信息和高阶信息一起学到了,这就让这种隐式神经表示非常强大 === 激活、频率的分布和有原则的初始化方案 #quote()[ 原文的基本思路是:我们希望初始化的方式可以保证无论我们身处于神经网络的哪一层 layer,其 output 的分布都是差不多的,这样的话我们在做 back-propagation 的时候,gradients 就不太可能会 vanish 或者 explode。那么要如何去找这样的初始化方式呢?首先假设我们的 weights 是来自 uniform distribution 的(但是其区间待定),这样在穿过下一个 $sin(dot)$ 之后分布就变成了 $arcsin$ 的。于是,在下一层的时候就是一堆 $arcsin$ distributed 的随机变量的 weighted sum,使用中心极限定理可以推出当 neuron 个数很多的时候,这个 linear combination 是趋近于正太分布的,它的方差也是可计算的。最后我们可以通过这个方差来反推出最一开始那个待定区间的 uniform distribution 是什么。(然后再用那种递归的 argument 就可以说明,每一层我们都这么搞的话,每一层的 output distribution 就都差不多是 invariant 的了。这也是 supplement material 里的那张图想证明的事) ] - 这里加上 supplement 一大堆证明看不太懂,总而言之就是(这里论文好像有笔误?) $ w_i tilde cal(U)(-sqrt(c/n), sqrt(c/n)) $ - 然后建议 $c = 6$,使得每个正弦激活函数的 output distribution 都是正态分布,标准差为 $1$。由于只有少数权重的大小大于 $pi$,因此整个正弦网络的频率增长缓慢 - 至于第一层 - 最后,建议对正弦网络的第一层 sin 缩放权重初始化为 $w_0 = 30$,以便正弦函数 $sin(w_0 dot W x + b)$ 跨越 $[-1, 1]$ 上的多个周期,实验证明很有效 == 实验 - SIREN 这个网络究竟能干什么呢?比如说以 Image experiments 为例 - 模型的输入维度就是 $2 (x, y)$,输出维度就是 $3 ("RGB")$,中间 layer 宽度为超参 - 训练集是一张特定图片,对它的长宽随机采样(比例较小,相当于掩码学习)一些像素点坐标作为输入,然后从图片中取出对应像素值作为 ground truth,这样构成整个训练集,训练网络 - 测试时,把整张图片的所有像素点坐标输入到网络中,得到的输出就是重建的图片,换句话说,就是从被掩码的图像中重建,预测了没看过的像素 - 另外一点则是(前面讲过)SIREN 的训练结合了高阶信息 - SIREN 可以运用于 图像、视频和音频表示,3D 形状重建;求解微分方程等 == 评价 - 实验效果确实还是不错的看起来 - 看了眼知乎上的评价 + 这篇文章的重点是将周期激活应用在 Implicit Neural Representations 上,INR 是以坐标为输入,像素为输入的一种坐标拟合场景,训练过程相当于让网络去记住固定的空间位置代表的是什么像素,当图像中的周期性比较强的时侯,传统的 Relu, tanh 自然不能很好拟合。而 sin 通过对坐标特征进行周期激活后,能很好还原周期信息 + 有人指出在 out-of-sample 上的数据表现很不好;但是冥冥之中觉得论文也许有些更深刻的启示性(跟 Fourier Analysis 的联系?) + 有人说 insight 很足,实验组织也不错,但是试了一下 比 ReLU + Positional Encoding 的效果差,认为能够找出那几个实验支持是核心 + 有人说:如果数据分布都是在 $-pi/2$ 到 $pi/2$ 之间,sin 激活函数跟 sigmoid 没什么区别,特别是用上 BN 的技术,这是完全可以做到的。但是论文里没有用 BN,而是提出了一个适配 sin 的权重初始化技术。普适性不强,也根本没办法迁移到其它工作里去。 + 用 sin 激活和用深一点的 deep relu 表达能力差别不大。关键在于正常的 deep relu 没有加显示的正则它是捕捉不到周期信息的(尽管它的拟合能力理论上能做到这点)。这篇论文用 sin 让网络显式的去做这一点。但是,单单用 sin 还是不够,为了能出效果才需要一个依据 lazy training 的特性、和深度无关的初始化,在这组初始化附近就能完成训练。总结就是这个 sin 策略还是太敏感了。用起来可能不是那么方便 == 论文十问 + 论文试图解决什么问题? - 表征复杂自然信号及其衍生物(图像、波场、视频、声音及其导数),可解决特定方程 + 这是否是一个新的问题? - 不算新吧,已有 ReLU-based MLP 的方法(或者别的激活函数),只是 sin 的好的运用应该还是第一次,好像还被 Hinton 点赞了 - 之前有过一篇 #link("https://openreview.net/forum?id=Sks3zF9eg")[Taming the waves: sine as activation function in deep neural networks],是一篇有一定引用但最终被 ICLR2017 拒绝了的文章,同行评审里面有谈到用这种周期函数作为激活函数的应用任务范围有点太有限了,这篇文章将其拓展到稍微更多的应用场景,但感觉其实还是略局限 + 这篇文章要验证一个什么科学假设? - 证明这种正弦网络非常适合表示复杂的自然信号(隐式神经表示) + 有哪些相关研究?如何归类?谁是这一课题在领域内值得关注的研究员? - 本文提到的相关研究: + Implicit Neural Representations:全连接网络可实现隐式神经表示,可通过符号距离函数、占用函数等训练获得。在外观编码、时间感知拓展和部分级语义分割也有相关变体 + Periodic Nonlinearities(非线性周期):通过单层隐藏网络模拟傅里叶变换,探索了用于简单分类任务的周期性激活神经网络和循环网络。已有余弦激活函数进行图像表示的方法,但是探索导数或本文工作的其他应用。本文探索了具有周期激活函数的 MLP,探索用于隐式神经表示及其衍生物的应用,并提出了原则性初始化和泛化方案 + Neural DE Solvers(微分方程求解器):神经网络求解微分方程已有长久的研究,早期简单的神经网络模型由 MLP 或 radial basis function(RBF) networks 组成,具有很少的隐藏层和 tanh or sigmoid 激活函数。本文表明,常用的基于平滑、非周期激活函数的常用 MLP 即使在密集监督下也不能准确模拟高频信息和高阶导数。神经 ODE 与该主题相关,但本质上非常不同 + 论文中提到的解决方案之关键是什么? - $sin$ 的使用我感觉应该不是特别开创,但之前的工作不一定有效,关键应该就是 $sin$ 的权重如何初始化,论文对此进行了数学上的证明和实验上的验证,得到了一个不错的结果 + 论文中的实验是如何设计的? - 做了一系列实验证明它的 claim + Solving the Poisson Equation + Representing Shapes with Signed Distance Functions,在三维结构重建问题下对比了 ReLU 和 SIREN,可明显的看到 SIREN 相较于 ReLU 重构出更多的结构细节,对物体表面恢复更光滑(图 4) + Solving the Helmholtz and Wave Equations,求解了以绿点为中心,均匀传播的亥姆霍兹方程(图 5),其中只有 SIREN 函数能够很好匹配原始结果,而其他激活函数(rbf, tanh, ReLU)均求解失败 + Learning a Space of Implicit Functions + 用于定量评估的数据集是什么?代码有没有开源? - 数据集 CelebA;代码开源在 #link("https://github.com/vsitzmann/siren")[github.com/vsitzmann/siren], #link("https://github.com/lucidrains/siren-pytorch")[github.com/lucidrains/siren-pytorch] + 论文中的实验及结果有没有很好地支持需要验证的科学假设? - 公式总感觉有点 typo 或者和代码不太相符,但是在各个实验结果上看起来还是不错的,应该算能支持科学假设 + 这篇论文到底有什么贡献? - 提出 sin 激活函数并提供一种行之有效的初始化方法,另外提供了各种应用演示 + 下一步呢?有什么工作可以继续深入? - 好像没法真正嵌入到别的 MLP 工作里去,应用比较受限?可能还得探索。 - 跟 Fourier Analysis 的联系?数学上的分析
https://github.com/flavio20002/cyrcuits
https://raw.githubusercontent.com/flavio20002/cyrcuits/main/example/main.typ
typst
Other
#import "../lib.typ": * #set page(width: auto, height: auto, margin: 0.5cm) #show: doc => cyrcuits( scale: 1, doc, ) ```circuitkz \begin{circuitikz} \draw (0,0) to[battery1,l=$E$] ++ (0,2) to[R,l=$R_1$,f>_=$i_1$] ++ (0,2) to[short,-*] ++ (2,0) coordinate (aux1) to[R,l_=$R_2$,f>_=$i_2$] ++ (0,-4) to[short,*-] ++ (-2,0); \draw (aux1) to[nos,l=$T$] ++ (2,0) coordinate (aux2) to[C,l_=$C$,v^=$v_C$,f>_=$i_C$] ++ (0,-4) to[short] ++ (-2,0); \end{circuitikz} ```
https://github.com/mismorgano/UG-FunctionalAnalyisis-24
https://raw.githubusercontent.com/mismorgano/UG-FunctionalAnalyisis-24/main/tareas/Tarea-06/Tarea-06.typ
typst
#import "../../config.typ": config, exercise, proof, cls, ip, conv #show: doc => config([Tarea 6], doc) 1.52, 1.53, 1.54, 1.55, 1.56, 2.2 y 2.3. #exercise[1.52][Sea $A$ un abierto en un e.n $X$. Muestra que $"con"(A)$ es abierto.] #proof[ Sea $x in conv(A)$ ] #exercise[1.53][¿Es la envolvente convexa de un conjunto cerrado en $RR^2$ cerrado?] #exercise[1.54][Sean $K, C$ subconjuntos de un e.n $X$. + Muestra que si $K, C$ son cerrados, entonces $K + C$ no es necesariamente cerrado. + Muestra que si $K$ es compacto y $C$ es cerrado, entonces $K + C$ es cerrado. ¿ ES $"con"(K union C)$ cerrado? + Muestra que si $K$ es compacto y $C$ es cerrado y acotado, entonces $"con"(K union C)$ es cerrado. ] #exercise[1.55][Sean $A, B$ compactos convexos es un e.B $X$. Muestra que $"conv"(A union B)$ y $A + B$ son compactos. Generaliza esto a un conjunto finito de conjuntos.] #exercise[1.56][Sea $A$ un conjunto totalmente acotado en un e.B $X$. Muestra que $"conv"(A)$ es totalmente acotado. Por lo tanto $"conv"(cls(A))$ es compacto.] #exercise[2.2][Muestra que si $X$ es un e.B finito-dimensional, entonces todo funcional lineal sobre $X$ es continuo en $X$.] #proof[Sea ${e_1, e_2, dots, e_n}$ una base de $X$, dado $x in X$ existen $alpha_1, alpha_2, dots, alpha_n in KK$ tenemos que $ x = sum_(i=1)^n alpha_i e_i, $ luego $ norm(T(x)) $ por lo cual $ T(x) = T(sum_(i=1)^n ip(x, e_i) e_i) = sum_(i=1)^n ip(x, e_i) T(e_i) $] #exercise[2.3][Muestra que si $X$ es un e.B infinito-dimesional, entonces $X$ admite un funcional lineal discontinuo.]
https://github.com/ramojus/typst-template-VU-thesis
https://raw.githubusercontent.com/ramojus/typst-template-VU-thesis/main/README.md
markdown
# [Typst](https://typst.app/) template for VU thesis Currently based on https://mif.vu.lt/lt3/dokumentai/dokumentai/INF/Kursp_mn.pdf. ## Useful links - [Typst documentation](https://typst.app/docs) - [A collection of useful typst projects and libraries](https://github.com/qjcg/awesome-typst) ## Recommended libraries - [typst-tablex](https://github.com/PgBiel/typst-tablex) for more customizable tables - [typst-algorithms](https://github.com/platformer/typst-algorithms) for writing algorithms and adding line numbers to code blocks ## Current problems See https://github.com/ramojus/typst-template-VU-thesis/issues/2
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/meta/bibliography-03.typ
typst
Other
// Error: 15-43 duplicate bibliography keys: arrgh, distress, glacier-melt, issue201, mcintosh_anxiety, netwok, psychology25, quark, restful, sharing, tolkien54 #bibliography(("/works.bib", "/works.bib"))
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/coordinate.typ
typst
Apache License 2.0
#import "./vector.typ" #import "./util.typ" #let resolve-xyz(c) = { // (x: <number> or <none>, y: <number> or <none>, z: <number> or <none>) // (x, y) // (x, y, z) return if type(c) == "array" { vector.as-vec(c) } else { ( c.at("x", default: 0), c.at("y", default: 0), c.at("z", default: 0), ) } } #let resolve-polar(c) = { // (angle: <angle>, radius: <number>) // (angle: <angle>, radius: (x, y)) // (angle, radius) // (angle, (x-radius, y-radius)) let (angle, xr, yr) = if type(c) == "array" { ( c.first(), ..if type(c.last()) == "array" { c.last() } else { (c.last(), c.last()) } ) } else { ( c.angle, ..if type(c.radius) == "array" { c.radius } else { (c.radius, c.radius) } ) } return ( xr * calc.cos(angle), yr * calc.sin(angle), 0 ) } #let resolve-anchor(ctx, c) = { // (name: <string>, anchor: <string> or <none>) // "name.anchor" // "name" let (name, anchor) = if type(c) == "string" { let parts = c.split(".") if parts.len() == 1 { (parts.first(), "default") } else { (parts.slice(0, -1).join("."), parts.last()) } } else { (c.name, c.at("anchor", default: "default")) } // Check if node is known assert(name in ctx.nodes, message: "Unknown element '" + name + "' in elements " + repr(ctx.nodes.keys())) let node = ctx.nodes.at(name) // Check if anchor is known assert(anchor in node.anchors, message: "Unknown anchor '" + anchor + "' in anchors " + repr(node.anchors.keys()) + " for node " + name) return util.revert-transform( ctx.transform, if anchor != none { node.anchors.at(anchor) } else { node.anchors.default } ) } #let resolve-barycentric(ctx, c) = { // dictionary of numbers return vector.scale( c.bary.pairs().fold( vector.new(3), (vec, (k, v)) => { vector.add( vec, vector.scale( resolve-anchor(ctx, k), v ) ) } ), 1 / c.bary.values().sum() ) } #let resolve-relative(resolve, ctx, c) = { // (rel: <coordinate>, update: <bool> or <none>, to: <coordinate>) let update = c.at("update", default: true) c = vector.add( resolve(ctx, c.rel), if "to" in c { resolve(ctx, c.to) } else { ctx.prev.pt } ) if not update { c.insert(0, false) } return c } #let resolve-tangent(resolve, ctx, c) = { // (element: <string>, point: <coordinate>, solution: <integer>) // https://stackoverflow.com/a/69641745/7142815 let (C, P) = (resolve-anchor(ctx, c.element), resolve(ctx, c.point)) // Radius let r = vector.len(vector.sub(resolve-anchor(ctx, c.element + ".top"), C)) // Vector between C and P let D = vector.sub(P, C) // C - P // Distance between C and P let pc = vector.len(D) if pc < r { panic("No tangent solution for element " + c.element + " and point " + repr(c.point)) } // Distance between P and X0 let d = r*r / pc // Distance between X0 and X1(X2) let h = calc.sqrt(r*r - d*d) return if c.solution == 1 { ( C.at(0) + (D.at(0) * d - D.at(1) * h) / pc, C.at(1) + (D.at(1) * d + D.at(0) * h) / pc, 0 ) } else { ( C.at(0) + (D.at(0) * d + D.at(1) * h) / pc, C.at(1) + (D.at(1) * d - D.at(0) * h) / pc, 0 ) } } #let resolve-perpendicular(resolve, ctx, c) = { // (horizontal: <coordinate>, vertical: <coordinate>) // (horizontal, "-|", vertical) // (vertical, "|-", horizontal) let (horizontal, vertical) = if type(c) == "array" { if c.at(1) == "|-" { (c.first(), c.last()) } else { // c.at(1) == "-|" (c.last(), c.first()) } } else { (c.horizontal, c.vertical) }.map(resolve.with(ctx)) return ( horizontal.at(0), vertical.at(1), 0 ) } #let resolve-lerp(resolve, ctx, c) = { // (a: <coordinate>, number: <number>, angle?: <angle>, b: <coordinate>) // (a, number, b) // (a, number, angle, b) let (a, number, angle, b) = if type(c) == "array" { if c.len() == 3 { ( ..c.slice(0, 2), none, // angle c.last() ) } else { c } } else { ( c.a, c.number, c.angle, c.b ) } (a, b) = (a, b).map(resolve.with(ctx)) if angle != none { let (x, y, _) = vector.sub(b,a) b = vector.add( ( calc.cos(angle) * x - calc.sin(angle) * y, calc.sin(angle) * x + calc.cos(angle) * y, 0 ), a, ) } if type(number) == "length" { number = util.resolve-number(ctx, number) / vector.len(vector.sub(b,a)) } return vector.add( vector.scale( a, (1 - number) ), vector.scale( b, number ) ) } #let resolve-function(resolve, ctx, c) = { (c.first())(..c.slice(1).map(resolve.with(ctx))) } // Returns the given coordinate's system name #let resolve-system(c) = { let t = if type(c) == "dictionary" { let keys = c.keys() let len = c.len() if len in (1, 2, 3) and keys.all(k => k in ("x", "y", "z")) { "xyz" } else if len == 2 and keys.all(k => k in ("angle", "radius")) and (type(c.radius) in ("integer", "float", "length") or (type(c.radius) == "array" and c.radius.len() == 2)) { "polar" } else if len == 1 and keys == ("bary",) { "barycentric" } else if len in (1, 2) and keys.all(k => k in ("name", "anchor")) { "anchor" } else if len == 3 and keys.all(k => k in ("element", "point", "solution")) { "tangent" } else if len == 2 and keys.all(k => k in ("horizontal", "vertical")) { "perpendicular" } else if len in (1, 2, 3) and keys.all(k => k in ("rel", "to", "update")) { "relative" } else if len in (3, 4) and keys.all(k => k in ("a", "number", "angle", "b")) { "lerp" } } else if type(c) == "array" { let len = c.len() let types = c.map(type) if len == 0 { "previous" } else if len in (2, 3) and types.all(t => t in ("integer", "float", "length")) { "xyz" } else if len == 2 and types.first() == "angle" { "polar" } else if len == 3 and c.at(1) in ("-|", "|-") { "perpendicular" } else if len in (3, 4) and types.at(1) in ("integer", "float", "length") and (len == 3 or (len == 4 and types.at(2) == "angle")) { "lerp" } else if len >= 2 and types.first() == "function" { "function" } } else if type(c) == "string" { "anchor" } if t == none { panic("Failed to resolve coordinate: " + repr(c)) } return t } #let resolve(ctx, c) = { let t = resolve-system(c) return if t == "xyz" { resolve-xyz(c) } else if t == "previous" { ctx.prev.pt } else if t == "polar" { resolve-polar(c) } else if t == "barycentric" { resolve-barycentric(ctx, c) } else if t == "anchor" { resolve-anchor(ctx, c) } else if t == "tangent" { resolve-tangent(resolve, ctx, c) } else if t == "perpendicular" { resolve-perpendicular(resolve, ctx, c) } else if t == "relative" { resolve-relative(resolve, ctx, c) } else if t == "lerp" { resolve-lerp(resolve, ctx, c) } else if t == "function" { resolve-function(resolve, ctx, c) } else { panic("Failed to resolve coordinate of format: " + repr(c)) }.map(util.resolve-number.with(ctx)) }
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/src/lib.typ
typst
Apache License 2.0
#import "defs/units.typ" #import "defs/prefixes.typ" #import "metro.typ": num, unit, qty, metro-setup, declare-unit, declare-prefix, create-prefix, declare-power, declare-qualifier, metro-reset, num-list, num-product, num-range, qty-list, qty-product, qty-range, complex, ang #let numlist = num-list #let numproduct = num-product #let numrange = num-range #let qtylist = qty-list #let qtyproduct = qty-product #let qtyrange = qty-range
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/link_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Verify that brackets are included in links. https://[::1]:8080/ \ https://example.com/(paren) \ https://example.com/#(((nested))) \
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/数据结构与算法/ADS笔记.typ
typst
--- order: 3 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "高级数据结构与算法分析", lang: "zh", ) = Lecture 1: AVL Trees, Splay Trees, and Amortized Analysis - 看 wyy 讲义,这里不想补笔记了。 - 总结一下摊还分析: + 聚合分析:整体分析最差的情况为什么样 + 核算法:调整*每个操作*的代价,使得总代价比原本大 + 势能法:对*每一步操作*定义一个势能,使得最后总势能比原本大 = Lecture 2: Red-Black Trees and B+ Trees #let sizeof = math.op("sizeof") #let bh = math.op("bh") #let Depth = math.op("Depth") == Red-Black Trees - Target: BST #wrap-content(fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-04-11-04-52.png"))[ - 定义: 1. 每个节点要么是*红的*,要么是*黑的* 2. root 是*黑的* 3. 每个 leaf 是*黑的*(哨兵是*黑的*,因为哨兵才是实际的叶子) 4. 如果一个 node 是*红的*,那么它的两个子节点都是*黑的* 5. 对于每个 node,从该 node 到其所有后代 leaf 的路径上,均包含相同数目的*黑色*节点] - 定义 black-height(node) 为从 node(不含)到所有 leaf 的路径上的*黑色* node 的数目,记为 bh(node) - 引理(树高与节点个数的关系):$h =< 2log_2 (N+1)$ - 引理(黑高与节点个数的关系):For any node $x$, $sizeof(x) ge 2^bh(x) - 1$ (全黑取等) - 引理(黑高与树高的关系):$bh(x) ge h(x)/2$ - Insert - 插入一个节点,它应该是*红色*还是*黑色*?答案是红色,因为插入黑色很容易改变黑高,而插入红色只需要调整即可。我们将插入节点称为 $X$,其父亲节点为 $P$,父亲的父亲为 $G$,叔叔为 $U$。以下均考虑插在左边情况,右边情况对称。 1. 最特殊的情况,如果 $X$ 刚好是 root,那么将其染黑即可 2. 如果 $P$ 是*黑色*,那么不需要调整;接下来考虑 $P$ 为*红色*,那么 $G$ 一定是黑色,根据叔叔 $U$ 的颜色分情况讨论 3. 如果 $U$ 是*红色*,爷爷把 $P$ 和 $U$ 的锅背了(case 1),并且递归下去 4. 如果 $U$ 是*黑色*,根据叔叔和侄子的关系再分类 5. 如果 $U$ 跟 $X$ 是*近叔侄*关系(case 2),那么做一个旋转,化为*远叔侄*关系(case 3) 6. 如果 $U$ 跟 $X$ 是*远叔侄*关系(case 3),撺掇 $P$ 夺取 $G$ 的颜色,并且篡位(旋转) - 可以使用迭代而非递归的方式实现 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-04-11-33-28.png", width: 80%) - Delete - 类似普通二叉查找树的删除 1. 如果是叶子节点,直接删具体怎么删,之后说 2. 如果是单个孩子的节点,用唯一的孩子替换,但是*颜色不变*,即只替换键值(注意因为是 balanced,所以不会出现单分支多于两个节点的情况) 3. 如果左右两边都有孩子,我们用*左子树的最大值*代替要删除的节点(颜色不变) - 也就是说,对于所有非 leaf 的删除,都可以保持颜色不变归结为删除 leaf,现在我们来考虑删除它之后如何保持红黑树的性质。以下均考虑删除左边情况,右边情况对称。 - leaf 如果是*红色*,直接删除,只需要考虑删除黑色 leaf 的情况。从理解的角度考虑(代码上不用这么写),先补偿性地给自己加一个*黑色*,变为“很黑'',现在两边的黑高分别是 $x+1$ 和 $x$。 - 而后,第一种想法是,两边一起甩锅给父亲,减轻压力,再删掉自己的*黑色*,最终两边都是 $x-1$; - 第二种想法是,直接删掉自己这边的“很黑'',为此,从兄弟那边抢一个*黑色*到自己这边,再给右边补偿染黑一个*红色*节点,最终两边都是 $x$。(哪里抢*黑色*呢?一般考虑兄弟的*黑色*旋转过来) 1. 先考虑甩锅,需要看兄弟的颜色,如果是*红色*(case 1)则需要变出一个*黑色*的兄弟来(case 2)。具体操作是,让兄弟把父亲的*黑色*(父亲一定是*黑色*,否则与兄弟也为*红色*违背)抢过来,这样右边黑高了,于是进行左旋。注意到兄弟的孩子一定是*黑色*,这样的操作最后将*黑色*的侄子变成了兄弟,可以继续进行(case 2) 2. 如果兄弟是*黑色*,配合甩锅也要看兄弟孩子的颜色是否有*红色*,如果没有,可以直接甩锅(case 2),然后看是否递归。 3. 如果兄弟的孩子有红色,变换策略,想办法从兄弟那边抢一个*黑色*,要看远侄子(插入和删除都是让远侄子变*红*)是*红色*还是*黑色*,如果远侄子是*黑色*(case 3),那么由于已经过了 case 2,近侄子一定是*红色*,想办法把近侄子的*红色*转移到远侄子身上(case 4) 4. 远侄子是*红色*,让兄弟篡位,通过左旋把兄弟(现在的父亲)变成自己人,把*红色*的远侄子染黑,最后删除自己。 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-04-12-08-19.png", width: 80%) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-12-11-21-19.png", width: 80%) == B+ Trees - 类似的有 B- 树、B - 定义 M 阶 B+ tree(也被称为 $ceil(M / 2)$-$"xxx"$-$M$ tree,如 4 阶又被称作 2-3-4 tree): 1. root 要么是叶子,要么有 $2 wave M$ 个#redt[孩子] 2. 每个 nonleaf 节点(除了 root)有 $ceil(M / 2) wave M$ 个#redt[孩子] 3. 每个 leaf 有同样的深度 4. 每个非根的 leaf 有 $ceil(M / 2) wave M$ 个#redt[键值] #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-11-10-10-05.png", width: 80%) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-14-13-39-08.png", width: 80%) - #redt[思考为什么 root 的下限特别不一样?]因为分裂的时候,root 最多也就分裂成两个节点,因此下限是 2 - 插入 - 根据键值排除一些路径 - 兄弟之间的“互推''(小 trick,不一定要实现) - 分裂操作,可以看 PPT 的动画 #algo(caption: "B+ tree insert")[ ``` Btree Insert (ElementType X, Btree T) { Search from root to leaf for X and find the proper leaf node; Insert X; while (this node has M+1 keys) { split it into 2 nodes with ⌈(M+1)/2⌉ and ⌊(M+1)/2⌋ keys, respectively; if (this node is the root) create a new root with two children; check its parent; } } ``` ] - $T_("insert")(M,N) = O(ceil((M \/ log M) log N ))$ - $T_("find")(M,N) = O(log N)$ - $Depth(M,N) = O(ceil(log_(ceil(M \/ 2)) N))$ - B+ 相对 AVL、Splay、Red-Black 的优势在于 IO 友好 - 删除 - 跟 insert 对应 - 写代码时候发现的几个注意点 - 更新 parent key 值的时候其实只用考虑相邻 parent,无需更新整个路径(一条路径上 key 值是互异的) = Lecture 3: Inverted File Index == 什么是倒排表 - 思考(引入):搜索引擎查询 "Computer Science" 的时候,它如何从茫茫多的数据中找到相关的信息? - solution1: Scan each page for the string "Computer Science",时间复杂度是恐怖的 - solution2: Term-Document Incidence Matrix(稀疏矩阵) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-11-10-53-19.png", width: 80%) - 局限性:对查询语句的位置信息不敏感、只找到文档而没找到文档内的位置信息、matrix 巨大 - 优化:用邻接表记录,维护一个二分图 - solution3: Compact Version - Inverted File Index - 什么是 index,mechanism for locating a given term in a text. - *Inverted file* contains a list of pointers (e.g. the number of a page) to all occurrences of that term in the text. - 之所以叫倒排,是因为之前是 doc 里存 text,现在是从 text 索引 doc #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-11-10-59-10.png", width:80%) - 存 frequency 的好处,取交集时从频率小的开始取 #algo(caption: "倒排表伪代码实现")[ ``` while (read a document D) { while (read a term T in D) { if (Find(Dictionary, T) == false) Insert( Dictionary, T ); Get T's posting list; Insert a node to T's posting list; } } Write the inverted index to disk; ``` ] - 需要考虑的问题:Token analyzer, Vocabulary scanner, Vocabulary insertor, Memory management == 问题处理 - While reading a term - word stemming(词根处理):词缀不重要,合并为词根 - stop words(停用词):像是 a, the, is 这种词,不需要索引 - Vocabulary scanner - solution1: Search trees(B- trees *(?)* , B+ trees, Tries *(?)*) - solution2: Hashing - While not having enough memory #algo(caption: "倒排表考虑 memory")[ ```c BlockCnt = 0; while (read a document D) { while (read a term T in D) { if (out of memory) { Write BlockIndex[BlockCnt] to disk; BlockCnt ++; FreeMemory; } if (Find(Dictionary, T) == false) Insert(Dictionary, T); Get T's posting list; Insert a node to T's posting list; } } for (i = 0; i < BlockCnt; i++) Merge(InvertedIndex, BlockIndex[i]); ``` ] - Distributed indexing - Solution 1: Term-partitioned index - Solution 2: Document-partitioned index - 比较两种方式的优劣,后者可以并行 - Dynamic indexing - 考虑文档被删除或更新的情况 - 维护两个表,固定表大一些(只承受查询),动态表小一些(同时承受查询和爬虫更新),合并搜索结果 - 实际删除太昂贵,一般是标记删除(lazy delete),定期真正删除 - Compression - doc 内不存空格,而是标记断点 - 当 doc 特别大的时候,不存位置信息(太大),而是存增量 - Thresholding - Document,只检索 top $x$ 个 rank 高的 docs - Query,对索引的单词进行频率排序 - 搜索引擎的评估 - 建立索引的效率有多高(How fast does it index) - 检索的速度有多快(How fast does it search) - 理解 query 语言的程度有多高(Expressiveness of query language) - Data Retrieval(响应时间和索引空间) - Information Retrieval(回答集相关性) - 相关性好坏的评估:往往是 Precision 和 Recall 的 trade-off #tbl( columns: 3, [], [Relevant], [Irrelevant], [Retrieved], [$R_R$], [$I_R$], [Not Retrieved], [$R_N$], [$I_N$] ) #align(center)[ $display("Precision" P = R_R / (R_R + I_R))$,返回的结果中有多少是正确的 ] #align(center)[ $display("Recall" R = R_R / (R_R + R_N))$,正确的结果实际被返回了多少 ] = Lecture 4: Leftist Heaps and Skew Heaps == Leftist Heaps - 左倾树,或左偏堆 - order 性质: same as heap - 结构性质: binary tree,but unbalanced - Target : Speed up merging in $O(N)$ - NPL(Null Path Length):从一个节点到一个外部节点(没有两个儿子)的路径长度(对比红黑树的黑高,那个是统计节点个数,这个则是路径长度) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-18-10-06-25.png") #theorem()[ A leftist tree with r nodes on the right path must have at least $2r - 1$ nodes \ (证明用归纳法) ] #corollary()[ 对于有 $N$ 个节点的左偏树,其右路径至多包含 $floor(log(N+1))$ 个节点\ 这启示我们所有操作尽量对右路径上进行 ] - 下面来看 insert 和 merge(insert 可以被视为 merge),首先是递归方法 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-18-10-51-04.png", width: 65%) - 做题一般采用迭代方法,但是递归的代码记一下(程序填空) ```C PriorityQueue Merge( PriorityQueue H1, PriorityQueue H2 ) { if (H1==NULL) return H2; if (H2==NULL) return H1; if (H1->Element > H2->Element) swap(H1, H2); //swap H1 and H2 if (H1->Left == NULL) H1->Left = H2; else { H1->Right = Merge(H1->Right, H2); if (H1->Left->Npl < H1->Right->Npl) SwapChildren(H1); //swap the left child and right child of H1 H1->NPl = H1->Right->Npl + 1; } return H1; } ``` - 然后是迭代方法 1. 切样本(节点及其左子树为一个样本),有 $log N$ 个 2. 选择最小根节点(用两个指针来维护)的样本接在右子树 3. 从右路径最下开始,交换左右子树来维护 NPL #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-18-11-08-29.png", width: 65%) == Skew Heaps - Skew heaps 之于 heaps 就像 splay trees 之于 binary search trees - target: Any $M$ consecutive operations take at most $O(M log N)$ time. - Skew heaps 的 merge 跟 leftist heaps 的 merge 几乎相同,只是少了一个 Npl 的维护与比较,不管三七二十一都要交换左右子树 - 这里 PPT 说什么右路径中除了最大节点之外都交换,其实意思是,有左孩子无右孩子的情况下不交换,避免把优势情况葬送掉,自己画的时候注意一下就是了。 - 跟 leftist heaps 的 merge 一样,skew heaps 的 merge 也有 递归和迭代 两种方法 #note(indent: false)[ 1. Skew heaps have the advantage that no extra space is required to maintain path lengths and no tests are required to determine when to swap children. \ 2. It is an open problem to determine precisely the expected right path length of both leftist and skew heaps. ] - Skew heaps 的重点是 Amortized Analysis - 思考势能函数的选择: - 一个好的势能函数应该有起有伏 - 节点个数?有起无伏 - 右路径上的节点个数?这就跟实际代价差不多,没有摊还的起伏了,而且也不太能算出来 - 右子树中的节点个数?斜堆中不会有“只有右儿子没有左儿子''的情况(交换前,思考为什么),也就不会因为交换而减少 #definition()[ A node p is #redt[heavy] if the number of descendants of p's right subtree is at least half of the number of descendants of p, and #bluet[light] otherwise. Note that the number of descendants of a node includes the node itself. ] - 选择 number of heavy nodes 作为势能函数进行摊还分析 - 设 $l$、$h$ - 实际代价 $H$ 是右路径的总长,也就是 $l + h$ - 重节点一定会变成轻节点,轻节点不一定会变成重节点(两边相等),放缩为一定变为重节点的情况 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-18-11-56-37.png") = Lecture 5: Binomial Queue == Definition - Binomial Queue 是由#redt[一组] heap-ordered trees 组成的(也即 forest)。每个 heap-ordered tree 是一个 binomial tree,每个记作 $B_k$ - $B_k$ 由两个 $B_(k-1)$ 组成,这里约定根节点小的那个作为根节点 - 对 $"size"$ 做一个二项分解,对应到二进制的每一位,确定 $B_k$ 是否存在 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-30-16-22-02.png", width: 80%) #corollary[$B_k$ consists of a root with $k$ children, which are $B_0,B_1,dots,B_(k-1)$. $B_k$ has exactly $2^k$ nodes. The number of nodes at depth $d$ is $display(vec(delim: "[",k, d))$.] == Operations - `FindMin`,最小值在其中一个根节点,最多 $ceil(log N)$ 个,因此 $T_p=O(log N)$ - 我们可以记住并时刻更新最小值,这样就可以 $O(1)$ 找到最小值 - `Merge`,从低到高(保证二项队列按高度排列)合并,每个合并视为 $O(1)$,最多合并 $log N$ 次,因此 $T_p=O(log N)$ - 思考三棵树(合并的两棵和进位上来的那棵)应该合并哪两棵?答案是其实没关系 - 思考为什么每个合并只用 $O(1)$(跟后面子树内部排列有关) - 插入(insert)可以用 `Merge` 实现 - `insert` 的 $H_2$ 只会有一个值,这是它与普通 `merge` 最大的不同 - 向一个空二项队列插入 $N$ 个值的时间复杂度是 $O(N)$,故可以视作平均消耗 $O(1)$ - `DeleteMin` 1. FindMin,找到最小值在 $B_k$ #h(14em) \/\* $O(log N)$ \*\/ 2. Remove $B_k$ from $H$,得到 $H'$ #h(12.7em) \/\* $O(1)$ \*\/ 3. Remove root from $B_k$,并且生成一个包含 $k$ 个树的 $H''$#h(1.5em) \/\* $O(log N)$ \*\/ 4. Merge $H'$ and $H''$#h(18em) \/\* $O(log N)$ \*\/ == Implementation - 思考儿子如何存储:注意到每个节点的儿子数不唯一,用多叉树方式相当于用空间换时间,而 left-child-next-sibling 的方式对空间更友好 - 思考树内部子树的存储顺序(注意不是二项队列的存储顺序):从大到小更好,减少 Merge 找到要插入节点的时间损耗 - 结构声明 ```c typedef struct BinNode *Position; typedef struct Collection *BinQueue; typedef struct BinNode *BinTree; /* missing from p.176 */ struct BinNode { ElementType Element; Position LeftChild; Position NextSibling; }; struct Collection { int CurrentSize; /* total number of nodes */ BinTree TheTrees[MaxTrees]; }; ``` - 树的合并 $T_p = O(1)$ ```c BinTree CombineTrees(BinTree T1, BinTree T2) { // equal-sized T1 and T2 if (T1->Element > T2->Element) // attach the larger to the smaller one return CombineTrees(T2, T1); // insert T2 to the front of the children list of T1 T2->NextSibling = T1->LeftChild; T1->LeftChild = T2; return T1; } ``` - 二项队列的合并 $T_p = O(log N)$ ```c BinQueue Merge(BinQueue H1, BinQueue H2) { BinTree T1, T2, Carry = NULL; int i, j; if (H1->CurrentSize + H2-> CurrentSize > Capacity) ErrorMessage(); H1->CurrentSize += H2-> CurrentSize; for (i=0, j=1; j<= H1->CurrentSize; i++, j*=2) { T1 = H1->TheTrees[i]; T2 = H2->TheTrees[i]; /*current trees */ switch(4*!!Carry + 2*!!T2 + !!T1) { // carry, T2, T1 case 0: /* 000 */ case 1: /* 001 */ break; case 2: /* 010 */ H1->TheTrees[i] = T2; H2->TheTrees[i] = NULL; break; case 4: /* 100 */ H1->TheTrees[i] = Carry; Carry = NULL; break; case 3: /* 011 */ Carry = CombineTrees(T1, T2); H1->TheTrees[i] = H2->TheTrees[i] = NULL; break; case 5: /* 101 */ Carry = CombineTrees(T1, Carry); H1->TheTrees[i] = NULL; break; case 6: /* 110 */ Carry = CombineTrees(T2, Carry); H2->TheTrees[i] = NULL; break; case 7: /* 111 */ H1->TheTrees[i] = Carry; Carry = CombineTrees(T1, T2); H2->TheTrees[i] = NULL; break; } // end switch } // end for-loop return H1; } ``` - DeleteMin $T_p = O(log N)$ ```c ElementType DeleteMin(BinQueue H) { BinQueue DeletedQueue; Position DeletedTree, OldRoot; ElementType MinItem = Infinity; // the minimum item to be returned int i, j, MinTree; // MinTree is the index of the tree with the minimum item if (IsEmpty(H)) {PrintErrorMessage(); return-Infinity;} MinItem = FindMin(H); // Step 1: find the minimum item DeletedTree = H->TheTrees[MinTree]; H->TheTrees[MinTree] = NULL; // step 2: remove the MinTree from H => H' OldRoot = DeletedTree; // Step 3.1: remove the root DeletedTree = DeletedTree->LeftChild; free(OldRoot); DeletedQueue = Initialize(); // Step 3.2: create H'' DeletedQueue->CurrentSize = (1 << MinTree) - 1; // 2^{MinTree} - 1 for (j = MinTree - 1; j >= 0; j--) { DeletedQueue->TheTrees[j] = DeletedTree; DeletedTree = DeletedTree->NextSibling; DeletedQueue->TheTrees[j]->NextSibling = NULL; } // end for-j-loop H->CurrentSize -= DeletedQueue->CurrentSize + 1; H = Merge(H, DeletedQueue); // Step 4: merge H' and H'' return MinItem; } ``` == Analysis - 分析连续 $N$ 次插入的复杂度 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-25-12-08-40.png", width: 80%) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-03-25-12-12-56.png", width: 80%) #figure(caption: "heap复杂度总结", tbl( columns: 5, [], [Binary Heap], [Leftist Heap], [Skew Heap], [Binomial Heap], [Insert], [$O(log n)$], [$O(log n)$], [$O(log n)$], [$O(1)$], [Merge], [$O(n)$], [$O(log n)$], [$O(log n)$], [$O(log n)$], [DeleteMin], [$O(log n)$], [$O(log n)$], [$O(log n)$], [$O(log n)$], [Delete], [$O(log n$)], [$O(log n)$], [], [$O(log n)$], [DecreaseKey], [$O(log n)$], [$O(log n)$], [],[$O(log n)$], [Initialize],[$O(1)$],[$O(1)$],[$O(log n)$],[$O(1)$], ) ) = 过渡回 - 从这里开始,由数据结构部分进入算法分析部分,均为定义+例子的结构,尝试整理 #info(caption: "算法分析部分目录及例子")[ - 不全是 PPT 上的例子(来自 wyy 讲义) - 可能会有重合(同一问题可以被不同方法解决) - Backtracking(回溯法) + 八皇后问题 + The Turnpike Reconstruction Problem 加油站重建问题 + 拼棍子问题(PPT 没有) + Tic-tac-toe 三子棋 - Divide and Conquer(分治法) + 最大子序列和问题 + 归并排序与快速排序 + 逆序对计数 + Closest Points Problem 最近点对问题 + 矩阵乘法(wyy 讲义) - Dynamic Programming(动态规划) + 斐波那契数列和爬楼梯 + 加权独立集合问题 + 0-1 背包问题 + 矩阵乘法计算复杂度估计 + 钢条切割问题,完全平方数的和 + 最长公共子序列,最长回文字符串 + Optimal Binary Search Tree 最优带权二叉搜索树 + AllPairs Shortest Path 单源最短路径和全源最短路径 + Activity Selection Problem 活动选择问题(变体:加权活动选择问题) + 最小化工时调度问题变体 + 旅行商问题 + #link("https://www.cnblogs.com/kangkang-/p/13493001.html", text(fill: gray.darken(40%))[(树的)最小支配集,最小点覆盖,最大独立集]) - Greedy Algorithms + Activity Selection Problem 活动选择问题(变体:活动调度问题) + Huffman Codes 哈夫曼编码 + 任务调度问题(变体:最小化最大延时) + fraction 背包问题 + 稳定匹配问题(不会) - NP-Completeness + P:最短路径问题、欧拉回路问题、2-CNF 可满足性问题 + NP:带负边最短路径无环问题、哈密顿回路问题、3-CNF 可满足性问题 + NPC:clique problem $<->$ Vertex cover problem,\ ~~~~~~~~~~ 哈密顿回路问题 $<->$ 旅行商问题 - Approximation + 最小化工时调度问题贪心近似 + Approximate Bin Packing(Next fit, First fit, Best fit) + 0-1 背包问题的近似解 + The K-center Problem + 旅行商问题的 2-近似 + 顶点覆盖问题的贪心 2-近似 - Local Search + 顶点覆盖问题:Metropolis 算法与模拟退火思想 + 旅行商问题 2-近似解的局部搜索改进 + Hopfield Neural Networks 的稳定构型与最大割问题 - Random Algorithm + 雇佣问题(naive, randomized, randomized-K) + QuickSort 的随机化 - Parallel Algorithm + The Summation Problem + PrefixSums Problem + Merge Problem($->$ Rank Problem) + Maximum Funding(算法一、算法二、算法三、算法四) - External Sorting + 斐波那契初始化 + 多路合并与多相合并 + 缓存并行处理 + 替换选择 ] = Lecture 6: Backtracking == 定义与原理 - 设想,任何问题都可以通过以下方法解决: - 1. 生成所有可能的解 - 2. 检查每个解是否满足条件 - 3. 选择最优解 - 但这样的方法时间复杂度显然太高 - 回溯法(backtracking)是一种解决问题的方法,它是一种暴力搜索的方法,通过不断地试错,寻找问题的解。与枚举法相比,它的核心在于通过剪枝(pruning)来减少搜索空间 - The basic idea is that suppose we have a partial solution $(x_1, dots , x_i)$ where each $x_k in S_k$ for $1 =< k =< i < n$. First we add $x_(i+1) in S_(i+1)$ and check if $(x_1, dots , x_i, x_(i+1))$ satisfies the constrains. If the answer is “yes” we continue to add the next $x$, else we delete $x_i$ and *backtrack* to the previous partial solution $(x_1, dots , x_(i-1))$. == 例子 === 八皇后问题 - Step 1: Construct a game tree - Step 2: Perform a depth-first search (post-order traversal) to examine the paths #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-01-10-57-52.png") === 加油站重建问题 - 给定 $N(N-1)\/2$ 个 distances,重建 $N$ 个加油站的位置,假定 $x_1=0$ #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-01-11-06-00.png") ```c bool Reconstruct (DistType X[], DistSet D, int N, int left, int right){ /* X[1]...X[left-1] and X[right+1]...X[N] are solved */ bool Found = false; if (Is_Empty(D)) return true; /* solved */ D_max = Find_Max(D); /* option 1:X[right] = D_max */ /* check if |D_max-X[i]|∈ D is true for all X[i]'s that have been solved */ bool OK = Check(D_max, N, left, right); /* pruning */ if (OK) {/* add X[right] and update D */ X[right] = D_max; for (i=1; i<left; i++) Delete(|X[right]-X[i]|, D); for (i=right+1; i<=N; i++) Delete(|X[right]-X[i]|, D); Found = Reconstruct(X, D, N, left, right-1); if (!Found) {/* if does not work, undo */ for (i=1; i<left; i++) Insert(|X[right]-X[i]|, D); for (i=right+1; i<=N; i++) Insert(|X[right]-X[i]|, D); } } /* finish checking option 1 */ if (!Found) {/* if option 1 does not work, option 2: X[left] = X[N]-D_maxk */ OK = Check(X[N]-D_max, N, left, right); if (OK) { X[left] = X[N] – D_max; for (i=1; i<left; i++) Delete(|X[left]-X[i]|, D); for (i=right+1; i<=N; i++) Delete(|X[left]-X[i]|, D); Found = Reconstruct (X, D, N, left+1, right); if (!Found) { for (i=1; i<left; i++) Insert(|X[left]-X[i]|, D); for (i=right+1; i<=N; i++) Insert(|X[left]-X[i]|, D); } } /* finish checking option 2 */ } /* finish checking all the options */ return Found; } ``` - Backtracking 的一个模板 ```c bool Backtracking(int i) { Found = false; if (i > N) return true; /* solved with (x1, ..., xN) */ for (each xi ∈ Si) { /* check if satisfies the restriction R */ OK = Check((x1, ..., xi) , R); /* pruning */ if (OK) { Count xi in; Found = Backtracking(i+1); if (!Found) Undo(i); /* recover to (x1, ..., xi-1) */ } if (Found) break; } return Found; } ``` - 考虑如何构建搜索树: #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-01-11-40-24.png") - 两颗同个问题的不同搜索树,上面的倾向于用值域较小的节点构建 - 上面这个剪枝的效率更高;下面这个好像剪枝的概率更高(实际上一般认为相同) - 一般来说认为上面这个更好 === 拼棍子问题 - 给定 $N$ 个棍子,长度分别为 $L_1, L_2, dots, L_N$,尽可能拼出长度较小(也即数量更多)的*等长*棍子 - 思路 - 枚举长度,算出棍子的数量 - 接下来用回溯法尝试是否可拼出这么多根 - 从大到小尝试放入棍子而非从小到大,减少搜索空间(也就是上图的第一棵树) === 三子棋(Tic-tac-toe) - 与之前例子不同,这里要同时考虑两边对手的决策,即 Minimax strategy - 为了决策需要量化棋盘的状态,即评估函数 - 这里的评估函数不用蒙特卡洛,而是简单的分别认为某一方不再下棋,自己有多少种获胜的可能,其差值作为评估函数 - 一边最小化评估函数,一边最大化评估函数 - 剪枝:$alpha-beta$ 剪枝 - 略 = Lecture 7: Divide and Conquer == 定义与原理 - #bluet[Divide]: 把问题分解成多个子问题 - #bluet[Conquer]: 用递归的方式解决每个子问题 - #bluet[Combine]: 把解合并起来 - 其时间复杂度可以这样计算 $ T(N) = a T(N\/b) + F(N) $ == 例子 1. The maximum subsequence sum: $O(N log N)$ 2. Tree traversals: $O(N)$ 3. Mergesort and quicksort: $O(N log N)$ === Closest Points Problem 给定平面上 $N$ 个点,找到最近的点对。最 Naive 的想法是遍历两遍,复杂度为 $O(N^2)$。下面考虑 Divide and Conquer: 对 x 轴砍一刀,分成左右两边,分别找左右两边的最小边,然后需要找横跨切分轴的点对。考虑利用已有信息剪枝,只考虑距离切分轴 $d$ 内的点。同时,对每一个点,只需考虑纵轴上距离 $d$ 内的点。 ```c /* points are all in the strip and sorted by y coordinates */ /* so just scan the lower part strip */ for (i = 0; i < NumPointsInStrip; i++) for (j = i + 1; j < NumPointsInStrip; j++) { if (Dist_y(Pi, Pj) > delta) break; else if (Dist(Pi, Pj) < delta) delta = Dist(Pi, Pj); } // 思考这个问题的代码如何编写 ``` For any $p_i$, at most #redt[$7$] points are considered, i.e. the second for-loop is excuted at most 7 times. == 详细计算时间复杂度 - Details to be ignored: 1. if (N / b) is an integer or not 2. always assume T( n ) = Θ( 1 ) for small n - Three methods for solving recurrences: 1. Substitution method 2. Recursion-tree method 3. Master method - *Substitution method* - Guess, then prove by induction - 一个重点(易错点)在于归纳时需要证明 #bluet[exact form] - 思考如何做足够好的猜测 - *Recursion-tree method* - 边算边猜;一般不用于严格证明,仅是猜测 - 注意 $a^(log_b N)=N^(log_b a)$ #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-08-11-21-55.png") - *Master method*(主方法,也叫求偶法) - 并没有 cover 所有情况,而是以不同角度对三种典型情况直接给出答案 - 角度一:比较根节点和叶子节点的开销 + 根节点开销小 + 开销差不多 + 根节点开销大 $ T(N) = cases( Theta(N^(log_b a)) &"if" f(N) = O(N^(log_b a - epsilon)), Theta(N^(log_b a) log N) &"if" f(N) = Theta(N^(log_b a)), Theta(f(N)) &"if" f(N) = Omega(N^(log_b a + epsilon)) "and" a f(N\/b) =< c f(N) (c < 1) ) $ - 角度二:比较分治与合并的开销,是角度一的推论 + 分治开销小 + 开销差不多 + 分治开销大 $ T(N) = cases( Theta(N^(log_b a)) &"if" a f(N\/b)=K f(N) (K > 1), Theta(f(N)log_b N) &"if" a f(N\/b)=f(N), Theta(f(N)) &"if" a f(N\/b)=kappa f(N) (kappa < 1), ) $ - 注意条件中要求 $=$ 而非数量级上的关系,本质上而言比较了 $N$ 的数量级而难以处理 $log N$,这引出下一个形式 - 角度三:比较任务的个数与任务的规模(较强的形式,涵盖了角度一) $ T(N) = a T(N\/b) + Theta(N^k log^p N) "where" a >= 1, b > 1, p >= 0 $ $ T(N) = cases( O(N^(log_b a)) &"if" a > b^k "(任务大于规模)", O(N^k log^(p+1) N) &"if" a = b^k "(任务等于规模)", O(N^k log^p N) &"if" a < b^k "(任务小于规模)" ) $ = Dynamic Programming - 递归算法的一个问题是,有些子问题会被重复计算,这就是动态规划的出发点 - Solve sub-problems just once and save answers in a table == 例子 === 斐波那契数列 - 原始问题 $T(N) >= F(N)$ - 状态转移方程:$F(N) = F(N-1) + F(N-2)$ - 使用动态规划,而且只需存储*最近的两个值*,$T(N) >= O(N)$ ```C int Fibonacci(int N) { int i, Last, NextToLast, Answer; if (N <= 1) return 1; Last = NextToLast = 1; /* F(0) = F(1) = 1 */ for (i = 2; i <= N; i++) { Answer = Last + NextToLast; /* F(i) = F(i-1) + F(i-2) */ NextToLast = Last; Last = Answer; /* update F(i-1) and F(i-2) */ } /* end-for */ return Answer; } ``` === Ordering Matrix Multiplications $ M_(1 |10 times 20|) * M_(2 |20 times 50|) * M_(3 |50 times 1|) * M_(4 |1 times 100|) $ - 方法一:$50 times 1 times 100 + 20 times 50 times 100 + 10 times 20 times 100 = 125,000$ $ M_(1 |10 times 20|) * (M_(2 |20 times 50|) * (M_(3 |50 times 1|) * M_(4 |1 times 100|))) $ - 方法二:$20 times 50 times 1 + 10 times 20 times 1 + 10 times 1 times 100 = 2,200$ $ (M_(1 |10 times 20|) * (M_(2 |20 times 50|) * M_(3 |50 times 1|))) * M_(4 |1 times 100|) $ - 思考有多少种计算方式,令 $b_n$ 为计算 $M_1 dot M_2 dots.c M_n$ 的不同方式,如何计算 $b_n$? - 令 $M_(i j) = M_i dots.c M_j$, then $M_(1 n) = M_1 dots.c M_n = M_(1 i) dot M_(i+1,n)$ - 因为括号扩在中间的话,最终它还是归属到两边中的某一个 - $=> b_n = sum_(i=1)^(n-1)b_i b_(n-i)$, where $n > 1$ and $b_1 = 1$ - 由卡特兰数的性质 $b_n = O(4^n / (n sqrt(n)))$,这是不可接受的 - 用动态规划算法实现 - 注意到原问题满足最优子结构性质,即最优解包含了子问题的最优解 - 设 $M_(i j)$ 为 $r_(i-1) times r_i$ 的矩阵,$m_(i j)$ 为计算 $M_i dots.c M_j$ 的方式数,那么: - 这样状态数为 $n^2$(思考为什么),每个状态的复杂度为 $O(n)$,因此总复杂度为 $O(n^3)$ $ m_(i j) = cases( 0 &"if" i = j, display(min_(i =< l < j))(m_(i l) + m_(l+1, j) + r_(i-1) r_l r_j) &"if" j < i ) $ - 其状态转移方程为 $F[i][j] = display(min_k) (F[i][k] + F[k+1][j] + r_(i-1) r_k r_j)$ - 这是一种很自然的状态方程,但不适合代码实现。试想,我们要算 $1 wave 4$ 的乘积,其中会用到 $3 wave 4$,但此时 $3 wave 4$ 还没算出来(如果以 i j 作为循环的话) - 另外一种状态转移方程(第一维严格递增,同时显示出问题的规模),更适合代码实现 - 计算 $K+1$ 个矩阵的乘积,最左边为 $i$($k$ 即为原来的 $j-i$),$F[0][i]=0$ $ F[K][i] = display(min_(l=0)^(K-1)) {F[l][i]+F[K-l-1][l+1] + r_(i-1) r_(l+i) r_(i+K)} $ - 或者(即下面代码的实现) $ F[K][i] = display(min_(l=i)^(K+i-1)) {F[l-i][i] + F[K+i-l-1][l+1] + r_(i-1) r_l r_(i+K)} $ ```c /* r contains number of columns for each of the N matrices */ /* r[0] is the number of rows in matrix 1 */ /* Minimum number of multiplications is left in M[1][N] */ void OptMatrix(const long r[], int N, TwoDimArray M) { int i, j, k, L; long ThisM; for (i = 1; i <= N; i++) M[i][i] = 0; for (k = 1; k < N; k++) /* k = j - i */ for (i = 1; i <= N - k; i++) { /* For each position */ j = i + k; M[i][j] = Infinity; for (L = i; L < j; L++) { ThisM = M[i][L] + M[L+1][j] + r[i-1] * r[L] * r[j]; if (ThisM < M[i][j]) /* Update min */ M[i][j] = ThisM; } /* end for-L */ } /* end for-Left */ } ``` === Optimal Binary Search Tree - 给定 $N$ 个词 $w_1 < w_2 < dots < w_N$,以及 $N$ 个概率 $p_0, p_1, dots, p_N$,构建一棵静态二叉搜索树,使得搜索的期望代价 $T(N) = display(sum_(i=1)^N p_i dot (1+d_i))$ 最小 - 确定一个根节点后,其左右子树就确定了(分治法的感觉来了) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-15-11-12-55.png",width:93%) - 依旧是最优子结构问题(左子树与右子树独立) - 思考怎么把它变成非最优子结构问题,比如 + 加一个约束,度数为 2 的节点不超过 $K$ 个 + 相邻节点之间首字母的字典序不能超过 2 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-15-11-22-05.png") === 单源最短路径算法(Bellman_Ford) - $D^k [s][v]$ 表示从 $s$ 到 $v$ 最多经过 $k$ 条边的最短路径 $ D^k [s][v] = min cases( D^(k-1) [s][v], display(min_((w,v)in E)) {D^(k-1)[s][w]+l_(w v)} ) $ - 复杂度 $O(|V| dot |E|)$ - 比较 Dijkstra 的 $O(|E| dot T_(d k) + |V| dot T_(e m))$ === All-Pairs Shortest Path(Floyd-Warshell) - 对所有点对 $(v_i, v_k)~~(i != j)$,找到最短路径 - 方法一,用 $|V|$ 次单源最短路径算法,复杂度 $O(|V|^3)$(works fast on sparse graph) - 方法二,动态规划算法 - $D^k [s][v]$ 表示从 $s$ 到 $v$ 只经过 $1,2,dots, k$ 这些内部顶点的最短路径 $ D^k [s][v] = min cases( D^(k-1) [s][v], D^(k-1)[s][k] + D^(k-1) [k][v], ) $ #fig("/public/assets/Courses/ADS/ads笔记/img-2024-04-15-11-31-20.png") - 跳板的添加顺序不影响最后结果(思考为什么) - 复杂度 $O(N^3)$ ```c /* A[ ] contains the adjacency matrix with A[i][i] = 0 */ /* D[ ] contains the values of the shortest path */ /* N is the number of vertices */ /* A negative cycle exists iff D[i][i] < 0 */ void AllPairs(TwoDimArray A, TwoDimArray D, int N) { int i, j, k; for (i = 0; i < N; i++) /* Initialize D */ for (j = 0; j < N; j++) D[i][j] = A[i][j]; for (k = 0; k < N; k++) /* add one vertex k into the path */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (D[i][k] + D[k][j] < D[i][j]) /* Update shortest path */ D[i][j] = D[i][k] + D[k][j]; } ``` === Product Assembly - 不想写了,写了也不如 wyy 的清晰,转战 wyy 讲义! #hline() - 总结,什么样的问题可以用动态规划? + 满足最优子结构——把子问题的最优解替换进原问题,看看会不会变差(是否会影响原问题的最优解) + 重叠子问题——不同问题调用同一子问题,它的最优解是否相同 - 代码技巧 - 动态规划的 for 顺序很麻烦,可以用*记忆化搜索*的写法,看着是个搜索,但本质还是动态规划 = Greedy Algorithms == 定义 - 优化问题:优化函数和约束条件 - 贪心方法:每一步都根据某种*贪心策略*选择最优局部解,这个解在之后不会被改变 - 什么时候用贪心比较好 + 只有局部最优解等于全局最优解,贪心算法才 work + 但有时即使局部最优解只是全局最优解的近似,全局最优解的求解复杂度太高,就会采用贪心 - 贪心方法的证明: + 正确性(可行解) + 最优性 + 贪心选择性质:根据贪心策略选出的解是否是最优解的一部分(选出的这个解跟其它解相比至少不会变差),即贪心选择总是安全的 + 最优子结构:用贪心策略选择 $a_1$ 之后得到子问题 $S_1$,那么 $a_1$ 和子问题 $S_1$ 的最优解合并是否可以得到原问题的最优解 - 一般贪心方法背后都会有一个臃肿的动态规划方法 - 在动态规划方法中,每个步骤都要进行一次选择,但选择通常依赖于子问题的解。但在贪心算法中,我们总是做出当时看来最佳的选择,然后求解剩下的唯一的子问题 == 例子 === Activity Selection Problem - $n$ 个活动在同一个场地举行,每个活动 $i$ 都有一个开始时间 $s_i$ 和结束时间 $f_i$,只有一个活动可以在同一时间举行(无 overlap),问最多能举行多少个活动 - dp 方法 1: - 记事件 $a_1, a_2, dots, a_n$,其中 $a_i wave a_j$ 记作 $S_(i j)$ $ c_(i j)=cases( 0 ~~~ &"if" S_(i j)=emptyset, max_() {c_(j k)+c_(k j)+1} ~~~ &"if" S_(i j)!=emptyset ) $ - 冗余(计算顺序) - 思考如何 $O(N^2)$ 实现这个方法 - dp 方法 2(一维): $ c_i = cases( 1 ~~~ &"if" i = 1, max{c_(i-1), c_(k(i))+1} ~~~ &"if" i != 1, ) $ - 其中 $c_i$ 表示从 $1$ 到 $i$ 个事件最多能选多少个,$c_(k(i))$ 表示选择了 $a_i$,去掉那些跟它不兼容的事件(结束时间迟于 $a_i$ 的开始时间) - Greedy 方法: - Greedy Rule 1: 选择开始最早的,不太行 - Greedy Rule 2: 选择时间间隔最短的,不太行 - Greedy Rule 3: 选择冲突最少的,不太行 - Greedy Rule 4: 选择结束时间最早的(释放最早),可以 - 正确性证明 - 复杂度: 本身只用 $O(N)$,受制于 $O(N log N)$ 的排序 === Huffman Codes - 定义不想写了 - 算法,用 min-heap 存储出现频率,用贪心策略选择最小的两个,合并成一个,直到只剩一个——$T = O(C log C)$ = NP-Completeness - NPC 问题,回忆 - Euler circuit problem,多项式时间可解 - Hamilton circuit problem,目前多项式时间不可解 - Single-source unweighted shortest-path problem,多项式时间可解 - Single-source unweighted longest-path problem,目前多项式时间不可解 - 停机问题 - 确定性图灵机和非确定性图灵机 - 非确定性图灵机:确保每一步都是对的 - P 问题:确定性图灵机能在多项式时间内解决的问题 - NP(Nondeterministic polynomial-time) 问题:非确定性图灵机能在多项式时间内解决的问题,或确定性图灵机能在多项式时间内验证解的问题 - $"P" subset "NP"$, but $"P" subset.neq "NP"$?这一问题暂时无人能解答 - 把所有 $"NP"$ 问题能归约到的问题集合称为 $"NPH"$ 问题,它们不一定都属于 $"NP"$;如果它又属于 $"NP"$,则称为 $"NPC"$ 问题 - NP-Complete Problems(NPC),是 NP 问题中最难的那一类,所有 NP 问题都可以归约为 NPC 问题 - 证明 NPC 的步骤 1. 证明为 NP 问题 2. 证明多项式归约 $B attach(=<, br: p) A $ 1. 选取两个问题实例 2. 证明 $A_Y -> B_Y$ 3. 证明 $A_N -> B_N <=> B_Y -> A_Y$ - Formal-language Theory - 旅行商问题,简单来说可以这么理解:求图的最短哈密尔顿回路 - 看不懂 - 弃坑,看 wyy 讲义 - 若只看是否多项式可解和是否可解 $"P" <- "NPC",~ "NPH",~ "NP" <- "undecidable"$ = Approximation == 定义 - 对困难的问题,使用近似算法 #definition(title: "近似比")[ 对于优化问题,输入规模为 $n$,给定一个算法 $A$,其解为 $S_A$,最优解为 $S_O$,则 $A$ 的近似比为 $rho(n) = max{S_A/S_O, S_O/S_A}$,我们称 $A$ 是 $rho(n)-"approximation"$ 算法 ] - 近似方案(approximation scheme)的定义 - 比如 $O(n^(2\/epsilon))$ 随着 $epsilon$ 的减少,时间复杂度呈指数级上升;对于这类对于特定的 $epsilon$,时间复杂度在多项式时间的算法我们称为 PTASpolynomial-time approximation scheme) - 而 $O((1\/epsilon)^2 n^3)$,这类算法和 $n$ 以及 $epsilon$ 都呈现多项式的关系,对于这类算法可以对近似比的要求更加严格。对于这类关于 $epsilon$ 和 $n$ 都呈多项式时间复杂度的算法我们称为 FPTAS(*fully* polynomial-time approximation scheme) == 例子 === Approximate Bin Packing - 给定 $n$ 个物品,每个物品的大小 $s_i in (0,1)$,箱子的大小为 $1$,问最少需要多少个箱子 - Next Fit 近似法 ```c void NextFit () { read item1; while (read item2) { if (item2 can be packed in the same bin as item1) place item2 in the bin; else create a new bin for item2; item1 = item2; } /* end-while */ } ``` #theorem()[ Next Fit 算法的近似比为 $rho(n) = 2$,最优解为 $M$ 时,next fit 不会产生大于 $2M-1$ 的解 ] - First Fit 和 Best Fit 近似法 ```c void FirstFit () { while (read item) { scan for the first bin that is large enough for item; if (found) place item in that bin; else create a new bin for item; } /* end-while */ } ``` - Claim: The *first-fit* heuristic leaves at most one bin less than half full - 找第一个满足条件的箱子,可以用 $O(N log N)$ 实现;此外还有类似的 Best Fit 算法(优先恰好满的箱子),也是 $O(N log N)$ #theorem()[ First Fit 算法对最优解为 $M$ 的问题,不会产生大于 $17(M-1)\/10$ 的解,即 $rho(n) = 1.7$,Best Fit 算法也为 $rho(n) = 1.7$(没有证明) ] - 这三种近似方法都是 On-line Algorithms,只能看到当前的物品,不能看到后面的物品,并且不能改变之前的决策 - 可以构造证明,在线算法解决 Bin Packing 问题,近似比为 $rho(n) = 5/3$ - Off-line Algorithms,离线算法 - trouble maker: large items - Solution: 先排个序(降序),然后用 First(best) Fit 算法,近似比为 $rho(n) = 11/9$ == 背包问题 - fractional version: 可以切分 - 可以用贪心算法得到最优解,把所有物品都切碎,然后按价值排序放入(相当于按性价比排序) - 一个性质是,只有一个物品会被切分放入,思考为什么 - 0-1 version(NP-hard) - 可以用动态规划方法解精确解 - 如果我们仍旧用贪心方法求最大价值*或*最大性价比,那么近似比为 $rho(n) = 2$ #proof()[ $ cases(reverse: #true, p_max =< P_"opt" =< P_"frac", p_max =< P_"greedy", P_"frac" =< P_"greedy" + p_max) => P_"opt" \/ P_"greedy" =< 1 + p_"max" \/ P_"greedy" =< 2 $ ] - 01 背包问题的基于价值的动态规划算法 == The K-center Problem - 略 = Local Search == 定义 - Solve problems approximately, aims at a local optimum - #bluet[Local] - 在可行集中定义 neighborhood - 定义目标函数和找到 neighborhoods 中的最优解 - #bluet[Search] - 从一个初始解开始,不断改进,直到找到一个局部最优解 - 局部最优解在无法继续改进时得到 - Neighbor Relation - $S wave S'$: $S'$ 可以由 $S$ 通过一次 *small modification* 得到,把 $S$ 的邻居集合称为 $N(S)$ == 例子 === Vertex cover problem - 给定无向图,找到它的最小顶点子集,使得每条边至少有一个端点在这个子集中(判定问题,是否存在 $|V'|=<K$;生成问题,得到最小顶点子集) - 可行集 $cal(F)S$: 所有顶点的集合 - $"cost"(S)=|S|$ - $S wave S'$: 从 $S$ 中删除一个节点,使得 $S'$ 仍然是一个顶点覆盖 - search: 从 $S=V$ 开始,不断删除一个节点,直到不能再删除为止 - 改进(Metropolis Algorithm),以一定概率允许增加节点 - 模拟退火的思想 ```C SolutionType Metropolis() { Define constants k and T; Start from a feasible solution S ∈ FS ; MinCost = cost(S); while (1) { S’ = Randomly chosen from N(S); CurrentCost = cost(S’); if (CurrentCost < MinCost) { MinCost = CurrentCost; S = S’; } else { With a probability , let S = S’; else break; } } return S; } ``` === Hopfield Neural Networks - 给定带权(整数)无向图,为顶点分配两种状态,权重大于 0 表示这条边希望两个节点有不同状态,权重小于 0 表示希望两个节点有相同状态。权重的绝对值表示希望程度的大小。 #definition()[ - 对边:\ In a configuration $S$, edge $e = (u, v)$ is *good* if $w_e s_u s_v < 0 (w_e < 0 "iff" s_u = s_v)$; otherwise, it is *bad*. - 对顶点 \ satisfied if 以它为顶点的边的分数和 $=< 0$ - 对整个图 \ stable if all nodes are satisfied ] - 该问题只要求满足而不要求最优,因此不讨论局部最优和全局最优(在后面例子中讨论) ```c ConfigType State_flipping() { Start from an arbitrary configuration S; while (!IsStable(S)) { u = GetUnsatisfied(S); s_u = -s_u; } return S; } ``` - 思考,这个算法是否一定会终止? #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-13-11-08-59.png") - 复杂度:$O(w_"max" |E|)$,伪多项式时间算法 === The Maximum Cut Problem - 给定带权(正数)无向图,为顶点分配两种状态,使得链接不同顶点状态的边的权值之和最大 $ w(A,B):=sum_(u in A, v in B) w_(u v) $ - 整个问题其实就是上个问题的特例(权重全为正) - 优化函数:本来是 $max w(A,B)$,转化为上一个问题:好边的权重和(本质是一样的) - 终止条件同 Hopfield Neural Networks 一样,且一定可以终止 - 可行集 $cal(F)S$: any partition $(A,B)$ - $S wave S'$: 交换一个顶点的状态 - 这是一个近似的局部最优解 - 对 $A$ 中的某个特定点,如果把它划到 $B$,它的边权重和为 $sum_(v in A) w_(u v)$,由于是局部最优解,因此不变是最好的,有第一条式子 - 遍历 $A$ 中的 $u$,式子左边对 $u$ 和 $v$ 分别遍历了一遍(比如 $e_(1 2)$ 被计算了两次),于是得到第二条式子,得到了点集 $A$ 内的边权和(可以理解为浪费了)与当前局部最优解之间的 $1\/2$ 关系 - 由于 $A, B$ 地位是均等的,我们对 $B$ 也进行一次这样的操作 - 显然最优解小于等于所有边权和,而这通过刚才的式子又能转化为 $2$ 倍的局部最优解 - by the way,由 $w(A, B) =< w^*(A, B)$,可得到 $w^*(A, B)$ 大于等于总边权的一半 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-13-11-28-31.png") - 虽然是近似算法,但复杂度依旧不是多项式时间 - 考虑提前终止 - 为什么我感觉这里应该是 $epsilon/(|V|) w(A,B)$?但是做题还是按 PPT 来 - 思考第二个 claim 怎么证明(不等式 $(1+1/x)^x >= 2 ~~ (x>=1)$,取 $epsilon$ 使其满足要求,那么每 $n\/epsilon$ 次都至少提升两倍) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-13-11-44-15.png") - 考虑每步找更好的邻居 - 每一步多翻转一个点,要求这个点是当前已经翻转过的基础上再翻转一个点的最好的情况($O(N)$),一直这样翻到 $(A, B)$ 倒置成 $(B, A)$。当然这样翻有可能会发现其中几步还不如原始版本。但没关系,我们选择这 $n-1$ 个邻居中最好的那个跳过去,并且在这 $n-1$ 个邻居都比原始版本差的情况下算法终止 - 思考 K-L flip 跟原本有什么不同 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-13-11-54-15.png") = Randomized Algorithms - 定义略,没啥好说的 == 例子 === The Hiring Problem - 面试和聘用的代价分别为 $C_i$ 和 $C_h$,前者远小于后者,设共有 $N$ 个应聘者,$M$ 个受聘者 - 总代价为 $C = N C_i + M C_h$ - Naive solution:面试每个人,如果他比之前的都好,就聘用他 ```c int Hiring (EventType C[], int N) { /* candidate 0 is a least-qualified dummy candidate */ int Best = 0; int BestQ = the quality of candidate 0; for (i=1; i<=N; i++) { Qi = interview(i); /* Ci */ if (Qi > BestQ) { BestQ = Qi; Best = i; hire(i); /* Ch */ } } return Best; } ``` - 存在情况 candidates come in increasing quality order,$O(N C_i + N C_h)$,即每个人都被雇佣 - 假设 candidates arrive in random order #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-20-10-23-09.png") - 实现上,只需要在开始时进行一个随机,比如,为每个人随机赋一个值,然后按这个值排序 - Online Hiring Algorithm – hire only once - 前 k 个人是练手的,无论怎么样都不会选;然后,只要碰到一个最好的,直接就选了,后面的都不看了 ```c int OnlineHiring ( EventType C[ ], int N, int k ) { int Best = N; int BestQ = -∞; for (i=1; i<=k; i++) { Qi = interview(i); if (Qi > BestQ) BestQ = Qi; } for (i=k+1; i<=N; i++) { Qi = interview(i); if (Qi > BestQ) { Best = i; break; } } return Best; } ``` - 思考这个算法选出真正最好的应聘者的概率,先考虑第 $i$ 个应聘者是最好的可能性,这等价于两个事件 + 最好的应聘者在位置 $i$ + $k+1$ \~ $i-1$ 没有被雇佣,这等价于前 $i-1$ 个人中最好的在前 $k$ 个人当中 - 于是 $Pr(S_i)=k/(N(i-1))$,$Pr(S)=k/N sum_(i=k)^(N-1) 1/i$ - 因此能选到最好的人的概率是 $k/N ln(N/k) =< Pr[S] =< k/N ln((N-1)/(k-1))$,求导,选取 $k=ceil(N/e) "or" floor(N/e)$ === Quicksort - Quick sort 的分析那里,把子问题按照 $N(3/4)^(j+1) =< |S| =< N(3/4)^j$ 的规模分类 - Type j 的子问题最多有 $N \/ N(3/4)^(j+1)$ 那么多,每个都放缩到 $N(3/4)^j$ 的规模,于是这一种子问题的期望总代价为 $O(N)$ - 而总共有 $O(log_(4\/3) N)$ 类子问题,所以总代价为 $O(N log N)$ = Parallel Algorithms - To resolve access conflicts - Exclusive-Read Exclusive-Write (EREW) - Concurrent-Read Exclusive-Write (CREW) - Concurrent-Read Concurrent-Write (CRCW) - Arbitrary rule - Priority rule (P with the smallest number) - Common rule (if all the processors are trying to write the same value) - PRAM(Parallel Random Access Machine) 模型 - WD(Work-Depth) 模型 - Measuring the performance - Work load – total number of operations: $W(n)$ - Worst-case running time: $T(n)$ + $W(n)$ operations and $T(n)$ time + $P(n) = W(n)/T(n)$ processors and $T(n)$ time (on a PRAM) + $W(n)/p$ time using any number of $p =< W(n)/T(n)$ processors (on a PRAM) + $W(n)/p + T(n)$ time using any number of p processors (on a PRAM) - All asymptotically equivalent == 例子 === The summation problem - 输入 $N$ 个数字,输出它们的和 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-10-15-31.png") #algo(caption: "PRAM model")[ ```typ for Pi , 1 ≤ i ≤ n pardo B(0, i) := A( i ) for h = 1 to log n do if i ≤ n/2h B(h, i) := B(h-1, 2i-1) + B(h-1, 2i) else stay idle end for for i = 1: output B(log n, 1); for i > 1: stay idle end for ``` ] - WD presentation #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-10-29-47.png") - $T(N)=log N, W(N)=N$ === Prefix-Sums - 利用 Balanced Binary Trees 并行 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-11-01-21.png") === merge - 利用 Partitioning 并行 - 先做简化,假设 $A, B$ 中对应元素都不同,$n=m$,且都是 $2$ 的次幂 - 先把 Merge 问题转化为 rank 问题 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-11-28-00.png") - 再思考如何解决 rank 问题,三种方法 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-11-35-34.png") - 以及 Parallel Ranking - 思考四种 cases,为什么这样划分是成立的 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-11-41-49.png") === Maximum Funding - 找到最大值的问题 - 串行算法 $T(n)=W(n)=O(N)$ - 并行算法一:这可以由把 The summation problem 中的 "+" 改为 "max",故复杂度为 $T(n)=O(log n), W(n)=O(n)$ - 并行算法二:让它们两两比对 - access conflicts 不用解决(因为都是写 $1$) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-11-58-38.png") - 并行算法三(Doubly-logarithmic Paradigm): - 3.1: 先用 $sqrt(n)$ partition,子问题用串行方法,算出的子问题解用并行算法二。这种方法多套几次 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-12-05-12.png") - 3.2: 先用 $log log n$ partition,子问题用串行方法,$n\/h$ 个子问题用并行算法 3.1 #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-12-11-36.png") - 并行算法四(Random Sampling): - 第一步,$n^(7\/8)$ 个处理器每个随机抽样放到内存中某个位置作为 $B$(可能重复),深度为 $O(1)$,总工作量为 $O(n^(7\/8))$ - 第二步,把 $B$ 分为 $n^(3\/4)$ 个 $n^(1\/8)$ 块,使用并行算法二(两两比对)方法找到每个块的最大值,得到 $C$,深度为 $O(1)$,总工作量为 $O(n^(3\/4) dot (n^(1\/8))^2)=O(n)$ - 第三步,把 $C$ 分为 $n^(1\/2)$ 个 $n^(1\/4)$ 块,使用并行算法二(两两比对)方法找到每个块的最大值,得到 $D$,深度为 $O(1)$,总工作量为 $O(n^(1\/2) dot (n^(1\/4))^2)=O(n)$ - 第四步,对 $D$ 使用并行算法二(两两比对)方法找到最终的最大值,深度为 $O(1)$,总工作量为 $O((n^(1\/2))^2)=O(n)$ - 第五步,以一定机制循环以上四步(所有的 $N$ 个元素和这个选出来的最大数 $M$ 比较,如果更大就丢到一个大小为 $n^(7\/8)$ 的数组中的随机位置。利用刚刚算法再来一遍) #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-12-20-47.png") #fig("/public/assets/Courses/ADS/ads笔记/img-2024-05-27-12-21-02.png") = External Sorting - 不记了 - 总结三个与数据库中外排的区别 + 数据库中只有一个 tape,在 tape 中不断 seek + 数据库中考虑 $b_b$,即一个归并段内多个 block,但 ADS 没有明显地考虑(最后考虑 pipeline 时顺带作用) + 数据库中没有考虑 pipeline 的作用(即把 I/O 分散到计算的过程),因为数据库中认为 CPU 很快,压根就没算内部排序的时间
https://github.com/dainbow/MatGos
https://raw.githubusercontent.com/dainbow/MatGos/master/themes/22.typ
typst
#import "../conf.typ": * = Кривые второго порядка, их геометрические свойства #definition[ Пусть $A, B, C, D, E, F in RR, A^2 + B^2 + C^2 != 0$. *Кривой второго порядка* называется алгебраическая кривая, которая в некоторой прямоугольной декартовой системе координат в $P_2$ задаётся следующим уравнением: #eq[ $A x^2 + 2 B x y + C y^2 + 2 D x + 2 E y + F = 0$ ] ] == Эллипс #definition[ *Эллипсом* называется кривая второго порядка, которая в канонической системе координат $(O, e)$ задаётся следующим уравнением: #eq[ $x^2 / a^2 + y^2 / b^2 = 1, a >= b > 0$ ] - *Вершинами* эллипса называются точки с координатами $vec(plus.minus a, 0), vec(0, plus.minus b)$ в системе $(O, e)$. Число $abs(a)$ называется *длиной большой полуоси* эллипса, число $abs(b)$ -- *длиной малой полуоси* эллипса. - *Фокусным расстоянием* эллипса называется величина $c := sqrt(a^2 - b^2)$. *Фокусами* эллипса называются точки $F_1, F_2 in P_2$ такие, что $F_1 <->_((O, e)) vec(c, 0); F_2 <->_((O, e)) vec(-c, 0)$ - *Эксцентриситетом* эллипса называется величина $epsilon := c / a = sqrt(a^2 - b^2) / a$ - *Директрисами* эллипса называются прямые $d_1, d_2$, задаваемые в системе $(O, e)$ уравнениями $x = plus.minus a / epsilon$ ] #theorem[ Пусть эллипс задан в каноническая системе координат $(O, epsilon); A in P_2; A <->_((O, e)) vec(x, y)$. Тогда #eq[ $A "лежит на эллипсе" <=> A F_1 = abs(a - epsilon x) <=> A F_2 = abs(a + epsilon x)$ ] ] #proof[ Будем доказывать первую эквивалентность, вторая аналогично. Для этого заметим, что выполнены следующие равенства: #eq[ $A F_1^2 - abs(a - epsilon x)^2 = (x - c)^2 + y^2 - abs(a - epsilon x)^2 = b^2 (x^2 / a^2 + y^2 / b^2 - 1)$ ] Значит, $A F_1 = abs(a - epsilon x) <=> x^2 / a^2 + y^2 / b^2 = 1 <=> A$ лежит на эллипсе. ] #theorem[ Пусть эллипс задан в канонической системе координат $(O, e)$. Тогда он является геометрическим местом точек $A in P_2; A <->_((O, e)) vec(x, y)$, таких, что выполнены следующие равенства: #eq[ $(A F_1) / rho(A, d_1) = (A F_2) / rho(A, d_2) = epsilon$ ] ] #proof[ Докажем равенство эксцентриситету лишь первого отношения, для второого аналогично. Заметим, что выполнены следующие равенства: #eq[ $rho(A, d_1) = abs(x - a / epsilon) = 1 / epsilon abs(a - epsilon x)$ ] Значит, $A$ лежит на эллипсе $<=> abs(a - epsilon x) = A F_1 <=> epsilon rho(A, d_1) = A F_1$ ] #theorem[ Пусть эллипс задан в канонической системе координат $(O, e)$. Тогда он является геометрическим местом точек $A in P_2; A <->_((O, e)) vec(x, y)$, таких, что выполнено равенство #eq[ $abs(A F_1) + abs(A F_2) = 2a$ ] ] #proof[ $=>$ Пусть $A$ лежит на эллипсе, тогда #eq[ $A F_1 = a - epsilon x; A F_2 = a + epsilon x => A F_1 + A F_2 = 2a$ ] $arrow.l.double$ Зафиксируем произвольное число $x_0 in RR$ и заметим, что при движении точки $X in P_2; X <->_((O, e)) vec(x_0, 0)$ вдоль прямой $x = x_0$ вверх или вниз величина $X F_1 + X F_2$ строго возрастает. Рассмотрим возможные случаи: + Если $abs(x_0) < a$, то таких точек, что $X F_1 + X F_2 = 2 a$, на прямой $x = x_0$ две. + Если $abs(x_0) = a$, то такая точка, что $X F_1 + X F_2 = 2a$, на прямой $x = x_0$ одна. + Если $abs(x_0) > 0$, то таких точек, что $X F_1 + X F_2 = 2a$, на прямой $x = x_0$ нет. Полученное число точек совпадает с множеством точек эллипса. ] == Гипербола #definition[ *Гиперболой* называется кривая второго порядка, которая в канонической системе координат $(O, e)$ задаётся следующим уравнением: #eq[ $x^2 / a^2 - y^2 / b^2 = 1; quad a, b > 0$ ] - *Вершинами* гиперболы называются точки с координатами $vec(plus.minus a, 0), vec(0, plus.minus b)$ в системе $(O, e)$. Число $abs(a)$ называется *длиной действительной полуоси* гиперболы, число $abs(b)$ -- *длиной мнимой полуоси* гиперболы. - *Фокусным расстоянием* гиперболы называется величина $c := sqrt(a^2 + b^2)$. *Фокусами* гиперболы называются точки $F_1, F_2 in P_2$ такие, что $F_1 <->_((O, e)) vec(c, 0); F_2 <->_((O, e)) vec(-c, 0)$ - *Эксцентриситетом* гиперболы называется величина $epsilon := c / a = sqrt(a^2 + b^2) / a$ - *Директрисами* гиперболы называются прямые $d_1, d_2$, задаваемые в системе $(O, e)$ уравнениями $x = plus.minus a / epsilon$ ] #theorem[ Пусть гипербола задана в канонической системе координат $(O, e); A in P_2; A <->_((O, e)) vec(x, y)$. Тогда #eq[ $A "лежит на гиперболе" <=> A F_1 = abs(a - epsilon x) <=> A F_2 = abs(a + epsilon x)$ ] ] #proof[ Будем доказывать первую эквивалентность, вторая аналогично. Для этого заметим, что выполнены следующие равенства: #eq[ $A F_1^2 - abs(a - epsilon x)^2 = (x - c)^2 + y^2 - abs(a - epsilon x)^2 = b^2 (x^2 / a^2 - y^2 / b^2 - 1)$ ] Значит, $A F_1 = abs(a - epsilon x) <=> x^2 / a^2 - y^2 / b^2 = 1 <=> A$ лежит на гиперболе. ] #theorem[ Пусть гипербола задана в канонической системе координат $(O, e)$. Тогда она является геометрическим местом точек $A in P_2; A <->_((O, e)) vec(x, y)$, таких, что выполнены следующие равенства: #eq[ $(A F_1) / rho(A, d_1) = (A F_2) / rho(A, d_2) = epsilon$ ] ] #proof[ Докажем равенство эксцентриситету лишь первого отношения, для второого аналогично. Заметим, что выполнены следующие равенства: #eq[ $rho(A, d_1) = abs(x - a / epsilon) = 1 / epsilon abs(a - epsilon x)$ ] Значит, $A$ лежит на эллипсе $<=> abs(a - epsilon x) = A F_1 <=> epsilon rho(A, d_1) = A F_1$ ] #theorem[ Пусть гипербола задана в канонической системе координат $(O, e)$. Тогда она является геометрическим местом точек $A in P_2; A <->_((O, e)) vec(x, y)$, таких, что выполнено равенство #eq[ $abs(A F_1 - A F_2) = 2a$ ] ] #proof[ $=>$ БОО пусть $A$ лежит на правой ветви гиперболы. Тогда #eq[ $A F_1 = epsilon x - a and A F_2 = a + epsilon x => abs(A F_1 - A F_2) = 2 a$ ] $arrow.l.double$ Зафиксируем произвольное число $x_0 in RR$ и заметим, что при движении точки $X in P_2; X <->_((O, e)) vec(x_0, 0)$ вдоль прямой $x = x_0$ вверх или вниз величина $abs(X F_1 - X F_2)$ строго убывает. Рассмотрим возможные случаи: + Если $abs(x_0) < a$, то таких точек, что $abs(X F_1 - X F_2) = 2 a$, на прямой $x = x_0$ нет. + Если $abs(x_0) = a$, то такая точка, что $abs(X F_1 - X F_2) = 2a$, на прямой $x = x_0$ одна. + Если $abs(x_0) > 0$, то таких точек, что $abs(X F_1 - X F_2) = 2a$, на прямой $x = x_0$ две. Полученное число точек совпадает с множеством точек эллипса. ] == Парабола #definition[ *Параболой* называется кривая второго порядка, которая в канонической системе координат $(O, e)$ задаётся следующим уравнением: #eq[ $y^2 = 2 p x; quad p > 0$ ] - *Вершиной* параболы называется точка с координатами $vec(0, 0)$ в системе $(O, e)$ - *Фокусом* параболы называется точка $F$ такая, что $F <->_((O, e)) vec(p / 2, 0)$ - *Эксцентриситетом* параболы называется величина $epsilon := 1$ - *Директрисой* параболы называется прямая $d$, задаваемая в системе $(O, e)$ уравнением $x = -p / 2$ ] #theorem[ Пусть парабола задана в канонической системе координат $(O, e); A in P_2; A <->_((O, e)) vec(x, y)$. Тогда #eq[ $A "лежит на параболе" <=> A F = rho(A, d)$ ] ] #proof[ Заметим, что выполнены следующие равенства: #eq[ $A F^2 - rho^2(A, d) = (x - p / 2)^2 + y^2 - (x + p / 2)^2 = y^2 - 2 p x$ ] Значит $A F = rho(A, d) = abs(x + p /2) <=> y^2 = 2 p x <=> A$ лежит на параболе ]
https://github.com/conda-forge/typst-lsp-feedstock
https://raw.githubusercontent.com/conda-forge/typst-lsp-feedstock/main/README.md
markdown
BSD 3-Clause "New" or "Revised" License
About typst-lsp-feedstock ========================= Feedstock license: [BSD-3-Clause](https://github.com/conda-forge/typst-lsp-feedstock/blob/main/LICENSE.txt) Home: https://github.com/nvarner/typst-lsp Package license: Apache-2.0 AND MIT Summary: A brand-new language server for Typst Current build status ==================== <table> <tr> <td>Azure</td> <td> <details> <summary> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main"> </a> </summary> <table> <thead><tr><th>Variant</th><th>Status</th></tr></thead> <tbody><tr> <td>linux_64</td> <td> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main&jobName=linux&configuration=linux%20linux_64_" alt="variant"> </a> </td> </tr><tr> <td>linux_aarch64</td> <td> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main&jobName=linux&configuration=linux%20linux_aarch64_" alt="variant"> </a> </td> </tr><tr> <td>osx_64</td> <td> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main&jobName=osx&configuration=osx%20osx_64_" alt="variant"> </a> </td> </tr><tr> <td>osx_arm64</td> <td> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main&jobName=osx&configuration=osx%20osx_arm64_" alt="variant"> </a> </td> </tr><tr> <td>win_64</td> <td> <a href="https://dev.azure.com/conda-forge/feedstock-builds/_build/latest?definitionId=22585&branchName=main"> <img src="https://dev.azure.com/conda-forge/feedstock-builds/_apis/build/status/typst-lsp-feedstock?branchName=main&jobName=win&configuration=win%20win_64_" alt="variant"> </a> </td> </tr> </tbody> </table> </details> </td> </tr> </table> Current release info ==================== | Name | Downloads | Version | Platforms | | --- | --- | --- | --- | | [![Conda Recipe](https://img.shields.io/badge/recipe-typst--lsp-green.svg)](https://anaconda.org/conda-forge/typst-lsp) | [![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/typst-lsp.svg)](https://anaconda.org/conda-forge/typst-lsp) | [![Conda Version](https://img.shields.io/conda/vn/conda-forge/typst-lsp.svg)](https://anaconda.org/conda-forge/typst-lsp) | [![Conda Platforms](https://img.shields.io/conda/pn/conda-forge/typst-lsp.svg)](https://anaconda.org/conda-forge/typst-lsp) | Installing typst-lsp ==================== Installing `typst-lsp` from the `conda-forge` channel can be achieved by adding `conda-forge` to your channels with: ``` conda config --add channels conda-forge conda config --set channel_priority strict ``` Once the `conda-forge` channel has been enabled, `typst-lsp` can be installed with `conda`: ``` conda install typst-lsp ``` or with `mamba`: ``` mamba install typst-lsp ``` It is possible to list all of the versions of `typst-lsp` available on your platform with `conda`: ``` conda search typst-lsp --channel conda-forge ``` or with `mamba`: ``` mamba search typst-lsp --channel conda-forge ``` Alternatively, `mamba repoquery` may provide more information: ``` # Search all versions available on your platform: mamba repoquery search typst-lsp --channel conda-forge # List packages depending on `typst-lsp`: mamba repoquery whoneeds typst-lsp --channel conda-forge # List dependencies of `typst-lsp`: mamba repoquery depends typst-lsp --channel conda-forge ``` About conda-forge ================= [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) conda-forge is a community-led conda channel of installable packages. In order to provide high-quality builds, the process has been automated into the conda-forge GitHub organization. The conda-forge organization contains one repository for each of the installable packages. Such a repository is known as a *feedstock*. A feedstock is made up of a conda recipe (the instructions on what and how to build the package) and the necessary configurations for automatic building using freely available continuous integration services. Thanks to the awesome service provided by [Azure](https://azure.microsoft.com/en-us/services/devops/), [GitHub](https://github.com/), [CircleCI](https://circleci.com/), [AppVeyor](https://www.appveyor.com/), [Drone](https://cloud.drone.io/welcome), and [TravisCI](https://travis-ci.com/) it is possible to build and upload installable packages to the [conda-forge](https://anaconda.org/conda-forge) [anaconda.org](https://anaconda.org/) channel for Linux, Windows and OSX respectively. To manage the continuous integration and simplify feedstock maintenance [conda-smithy](https://github.com/conda-forge/conda-smithy) has been developed. Using the ``conda-forge.yml`` within this repository, it is possible to re-render all of this feedstock's supporting files (e.g. the CI configuration files) with ``conda smithy rerender``. For more information please check the [conda-forge documentation](https://conda-forge.org/docs/). Terminology =========== **feedstock** - the conda recipe (raw material), supporting scripts and CI configuration. **conda-smithy** - the tool which helps orchestrate the feedstock. Its primary use is in the construction of the CI ``.yml`` files and simplify the management of *many* feedstocks. **conda-forge** - the place where the feedstock and smithy live and work to produce the finished article (built conda distributions) Updating typst-lsp-feedstock ============================ If you would like to improve the typst-lsp recipe or build a new package version, please fork this repository and submit a PR. Upon submission, your changes will be run on the appropriate platforms to give the reviewer an opportunity to confirm that the changes result in a successful build. Once merged, the recipe will be re-built and uploaded automatically to the `conda-forge` channel, whereupon the built conda packages will be available for everybody to install and use from the `conda-forge` channel. Note that all branches in the conda-forge/typst-lsp-feedstock are immediately built and any created packages are uploaded, so PRs should be based on branches in forks and branches in the main repository should only be used to build distinct package versions. In order to produce a uniquely identifiable distribution: * If the version of a package **is not** being increased, please add or increase the [``build/number``](https://docs.conda.io/projects/conda-build/en/latest/resources/define-metadata.html#build-number-and-string). * If the version of a package **is** being increased, please remember to return the [``build/number``](https://docs.conda.io/projects/conda-build/en/latest/resources/define-metadata.html#build-number-and-string) back to 0. Feedstock Maintainers ===================== * [@freundTech](https://github.com/freundTech/)
https://github.com/pku-typst/ichigo
https://raw.githubusercontent.com/pku-typst/ichigo/main/src/model.typ
typst
MIT License
#import "@preview/valkyrie:0.2.1" as z #import "themes.typ": get-theme, THEMES /// Document meta information #let meta-schema = z.dictionary(( course-name: z.string(), serial-str: z.string(), author-info: z.content(), author-names: z.either(z.tuple(), z.string()), )) #let font-schema = z.either(z.string(), z.tuple()) #let theme-schema = z.dictionary(( title: z.dictionary(( whole-page: z.function(), simple: z.function(), )), page-setting: z.dictionary(( header: z.function(), footer: z.function(), )), fonts: z.dictionary(( heading: font-schema, text: font-schema, equation: font-schema, )), )) #let title-style = z.choice(("whole-page", "simple", "none")) #let theme-name = z.choice(THEMES) #let themes-validation(meta) = { let meta = z.parse(meta, meta-schema) for name in THEMES { let theme = get-theme(name) z.parse(theme(meta), theme-schema, scope: (name,)) } return }
https://github.com/lbsekr/provadis-typst-template
https://raw.githubusercontent.com/lbsekr/provadis-typst-template/main/template.typ
typst
#import "@preview/glossarium:0.4.1": print-glossary, make-glossary #show: make-glossary #let code_identifier = "code" #let code(body,caption: "",supplement: "") = { figure( body, kind: code_identifier, caption: caption, supplement: supplement ) } #let Template( language: "de", cover_language: none, title: [Textvorlage für wissenschaftliche Arbeiten Titel und Untertitel der Arbeit], authors: ( ( name: "<NAME>", email: "<EMAIL>", postal: "Hauptstraße 10, D-10341 Hauptstadt", matrikel: "XXXX" ), ), logo: image("img/t-systems.png", width: 180pt, height: 2.06cm, fit: "contain"), abstract: lorem(100), preface: lorem(100), acknowledgement: "Für meine Brudis", document-type: "Wiss. Kurzbericht / WAB / Bachelorarbeit / Masterarbeit", reason: [ Zur Veranstaltung… / zur Erlangung des akademischen Grades \ ’Bachelor of Science’ B.Sc. / ’Master of Science’ M.Sc. \ im Studiengang ’XXX’ ], submitted_to: [ vorgelegt dem Fachbereich Informatik und Wirtschaftsinformatik der \ Provadis School of International Management and Technology \ von \ ], first_appraiser: "Prof. Müller", second_appraiser: "Dr. Kunze", supervisor: "Dr. Peter", bib: none, appendix: (), location: "Berlin", deadline: "15.03.2024", declaration_of_independence: true, // 🇺🇸🇺🇸🇺🇸🇺🇸🦅🦅🦅 confidental_clause: false, glossary_entries: (), abbreviation_entries: (), show_lists_after_content: false, ai_entries: (), body ) = { if(cover_language == none) { cover_language = language } let translations = json("translations.json").at(language) let cover_translations = json("translations.json").at(cover_language) // Main Context context { let glossary-page(heading-text, entries) = { if entries.len() == 0 { return } pagebreak() heading(heading-text, supplement: translations.vorwort, numbering: none, outlined: true, ) print-glossary(entries) } let glossary() = { glossary-page(translations.glossar, glossary_entries) } let abbreviations() = { glossary-page(translations.abkuerzungsverzeichnis, abbreviation_entries) } // Man könnte die ganzen Tables wsl. abstrahieren. Aber kein Bock let table_of_code() = { locate(loc => { if counter(figure.where(kind: code_identifier)).final(loc).at(0) > 0 { context { pagebreak() show outline: set heading( outlined: true, supplement: [#translations.vorwort] ) outline( title: translations.codeausschnittverzeichnis, depth: 3, indent: true, target: figure.where(kind: code_identifier) ) } } }) } let table_of_tables() = { locate(loc => { if counter(figure.where(kind: table)).final(loc).at(0) > 0 { context { pagebreak() show outline: set heading( outlined: true, supplement: [#translations.vorwort] ) outline( title: translations.tabellenverzeichnis, depth: 3, indent: true, target: figure.where(kind: table) ) } } } ) } let table_of_figures() = { locate(loc => { if counter(figure.where(kind: image)).final(loc).at(0) > 0 { context { if show_lists_after_content { pagebreak() } show outline: set heading( outlined: true, supplement: [#translations.vorwort] ) outline( title: translations.abbildungsverzeichnis, depth: 3, indent: true, target: figure.where(kind: image) ) } } }) } let lists = [ #table_of_figures() #table_of_code() #table_of_tables() #glossary() #abbreviations() ] set document(author: authors.map(a => a.name), title: title) set text(font: "Times New Roman", lang: cover_language, weight: 500, size: 12pt,) set heading(numbering: "1.1") show: make-glossary // ------------- // COVER PAGE // ------------- set page( margin: ( top: 2cm, right: 2cm, left: 2cm, bottom: 1cm ) ) place( top, float: false, clearance: 0em, grid( columns: (1fr,1fr), align(left ,image("img/provadis.png", height: 2.06cm)), align(right,logo), ) ) v(11em) align(center, text(1.1em,document-type)) v(1cm) set par(leading: 1em) align(center, text(14pt, weight: 600, title) ) v(2.5cm) set par(justify: true, leading: 1.5em) align(center, text(1.1em, reason), ) v(1cm) set par(justify: true, leading: 1em) align(center, text(1.1em, submitted_to), ) v(2em) set block(spacing: 1em) align( center, grid( ..authors.map(author => align(center)[ #author.name #author.matrikel #author.email #author.postal #{if author.keys().contains("affiliation") { author.affiliation }} ]), ) ) place( bottom + left, grid( columns: (auto, auto), rows: (auto, auto), row-gutter: 15pt, column-gutter: 15pt, [#cover_translations.erstgutachter:], [#first_appraiser], ..({if second_appraiser != none { ( [#cover_translations.zweitgutachter:], [#second_appraiser] ) }} ), [#cover_translations.betreuung:], [#supervisor], [#cover_translations.endeDerBearbeitungsfrist:], [#deadline], v(1em) ) ) // Workaroung um Monate in der ausgewählte Sprache (deutsch,english) anzuzeigen, bis Typst es out-of-the-box unterstüzt // text( // [ // Frankfurt am Main, #translations.meta.monatZeitPrefix #translations.monate.at(datetime.today().display("[month repr:long]")) #datetime.today().display("[year]") // ] // ) // v(.5fr) // set text(lang: language) if type(acknowledgement) == "content" or type(acknowledgement) == "string" { pagebreak() place( center + horizon, text(acknowledgement, style: "italic", size: 14pt) ) } counter(page).update(0) // ----------------- // PRE-AMBEL STUFF // ----------------- set par(justify: true, leading: 1.1em) set page( header: context { let section = "" let here = here() let selector = heading.where(level: 1, supplement: [#translations.vorwort]) .or(heading.where(level: 1, supplement: [#translations.kapitel])) let before = query( selector.before(here, inclusive: false) ) let page_sections = query( selector.after(here) ).filter((it) => it.location().page() == here.page()) if before.len() > 0 and page_sections.len() == 0{ section = before.last().body }else if page_sections.len() > 0 { section = page_sections.first().body } stack( dir: ttb, [#section #h(1fr) #counter(page).display(here.page-numbering())], [#v(4pt)],[#line(length: 100%)] ) }, margin: ( top: 3cm, right: 2cm, left: 3cm, bottom: 2cm ), numbering: "i", number-align: top + right ) // Confidental Clause if confidental_clause == true { context { heading(translations.confidentalClaus, outlined: false, numbering: none,supplement: translations.vorwort) v(1em) text(lang: "de", translations.confidentalClausText) v(5em) line(length: 16em) [#strong(authors.map(author => author.name).join(", ")) #linebreak() #location, den #datetime.today().display("[day].[month].[year]")] pagebreak() } } if type(abstract) == "content" or type(abstract) == "string" { heading(translations.abstract, outlined: false, numbering: none,supplement: translations.vorwort) v(1em) abstract pagebreak() } if type(preface) == "content" or type(preface) == "string" { heading(translations.vorwort, outlined: false, numbering: none,supplement: translations.vorwort) v(1em) preface pagebreak() } if not show_lists_after_content { lists } set block(spacing: .65em) set text(font: "Times New Roman", lang: language, weight: 500, size: 12pt,) show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } show outline: set heading( outlined: false, supplement: translations.vorwort ) context { if abbreviation_entries.len() != 0 and not show_lists_after_content { pagebreak() } outline( depth: 3, indent: true, target: heading.where(supplement: [#translations.kapitel]) .or(heading.where(supplement: [#translations.vorwort])) ) } if appendix.len() > 0 { show outline: set heading( outlined: false, supplement: translations.vorwort ) outline( title: translations.appendix, depth: 3, indent: true, target: heading.where(supplement: [#translations.appendix]), ) } if show_lists_after_content { lists } // Main Body Context context { // Main body counter(page).update(0) set page(numbering: "1") set par(justify: true, leading: 1.1em) set heading(supplement: [#translations.kapitel]) set block(spacing: 1.2em) set heading(supplement: [#translations.kapitel]) show heading: it => block(it,below: 1.1em) body // After Main Body Contexts context { set heading(supplement: [#translations.kapitel]) counter(page).update(0) set page(numbering: "I") if bib != none { if type(bib) == "string" { bibliography(bib) } else { bibliography(..bib) } } pagebreak() set heading(numbering: none) // AI heading(translations.ki.verzeichnis) if ai_entries.len() == 0 { [#translations.ki.unbenutzt] } else { table( columns: (auto, auto, auto), align: horizon, table.header( [*#translations.ki.system*], [*#translations.ki.prompt*], [*#translations.ki.verwendung*], ), ..ai_entries.flatten() ) } // Appendix if appendix.len() > 0 { context { pagebreak() heading(translations.appendix, outlined: false) set heading(numbering: "A") counter(heading).update(0) appendix.join() } } // 🇺🇸🇺🇸🇺🇸🇺🇸🇺🇸🇺🇸🦅🦅🦅🦅🗽🗽🗽🔫🔫🔫 if declaration_of_independence { pagebreak() set page(header: none, numbering: none) set heading(numbering: none) heading("Ehrenwörtliche Erklärung", outlined: false) text(lang: "de", "Hiermit bestätige ich, dass ich die vorliegende Arbeit persönlich und selbständig verfasst und keine anderen als die angegebenen Quellen und Hilfsmittel verwendet habe. Alle Stellen, die wörtlich oder sinngemäß anderen Quellen entnommen wurden, sind als solche kennt-lich gemacht. Die Zeichnungen, Abbildungen und Tabellen in dieser Arbeit sind von mir selbst erstellt oder wurden mit einem entsprechenden Quellennachweis versehen. Diese Arbeit wurde weder in gleicher noch in ähnlicher Form von mir an anderen Hochschulen zur Erlangung eines akademischen Abschlusses eingereicht." ) v(8%) line(length: 50%) [#strong(authors.map(author => author.name).join(", ")) #linebreak() #location, den #datetime.today().display("[day].[month].[year]")] } } } } }
https://github.com/kokkonisd/typst-cross
https://raw.githubusercontent.com/kokkonisd/typst-cross/main/src/preprocessing.typ
typst
The Unlicense
// Process a dictionary and produce cell and clue data. // // The dictionary is expected to come from a TOML file, usually by doing `toml("myfile.toml")`. It // is also expected to have the following structure (in Typst notation): // // ```typst // ( // title: "Title", // author: "Author", // board: "1234\nABCD\nabcd\n####", // clues: ( // across: ( // ( // row: 1, // column: 1, // clue: "This is an across clue", // ) // ), // across: ( // ( // row: 1, // column: 1, // clue: "This is a down clue", // ) // ), // ), // ) // ``` // // Also see the TOML files in `examples/`. // // The cell and clue data produced by this function has the following form (in Typst notation): // ```typst // ( // width: 100, // Width of the board. // height: 80, // Height of the board. // next-cell-number: 42, // Number to mark next clue-starting cell with (internal use mostly). // cells: ( // ( // letter: "A", // Letter contained in the cell. // number: 12, // Number on the top left of the cell (if any). // row: 28, // The cell's row. // column: 3, // The cell's column. // ), // ) // ) // ``` #let _process-data(data) = { let width = data.board.position("\n") let height = data.board.split("\n").filter(n => n.len() > 0).len() data.board.clusters().filter(letter => letter != "\n").enumerate().fold( ( width: width, height: height, next-cell-number: 1, cells: () ), (state, (index, letter)) => { let row = int(index / width) + 1 let column = (index - ((row - 1) * width)) + 1 let next-cell-number = state.next-cell-number let new-cell = (letter: none, number: none, row: row, column: column) if data.clues.across.find(clue => { clue.row == row and clue.column == column }) != none { new-cell.letter = letter new-cell.number = state.next-cell-number next-cell-number = state.next-cell-number + 1 } else if data.clues.down.find(clue => { clue.row == row and clue.column == column }) != none { new-cell.letter = letter new-cell.number = state.next-cell-number next-cell-number = state.next-cell-number + 1 } else { new-cell.letter = letter new-cell.number = none } ( width: width, height: height, next-cell-number: next-cell-number, cells: (..state.cells, new-cell) ) } ) }
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Maths_Expertes_Ex_04_12_2023.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: "Maths Expertes Ex 04 12 2023", authors: ( "<NAME>", ), date: "2 Décembre, 2023", ) #set heading(numbering: "1.1.") === Exercice 17 p 149 <exercice-17-p-149> + On peut écrire $2 lr((3 n plus 2)) minus 3 lr((2 n plus 1)) eq minus 6 n plus 6 n plus 4 minus 3 eq 1$ Donc $2 n plus 1$ et $3 n plus 2$ peuvent s’écrire sous la forme $u lr((3 n plus 2)) plus v lr((2 n plus 1)) eq 1$ avec $u eq 2$ et $v eq minus 3$ des entiers relatifs. D’après le théorème de bézout $3 n plus 2$ et $2 n plus 1$ sont premiers entre eux + On peut écrire $7 n plus 4 minus 7 n plus 3 eq 1$. Donc $7 n plus 4$ et $7 n plus 3$ peuvent s’écrire sous la forme $u lr((7 n plus 4)) plus v lr((7 n plus 3)) eq 1$ avec $u eq 1$ et $v eq minus 1$ des entiers relatifs. D’après le théorème de bézout $7 n plus 4$ et $7 n plus 3$ sont premiers entre eux === Exercice 18 p 149 <exercice-18-p-149> + Si on pose $a eq lr((n plus 2))^2 eq n^2 plus 4 n plus 4$ et $b eq lr((n plus 3)) lr((n plus 1)) eq n^2 plus 4 n plus 3$. $a minus b eq n^2 plus 4 n plus 4 minus n^2 minus 4 n minus 3 eq 1$. D’après le théorème de Bézout $a$ et $b$ sont premiers entre eux car ils peuvent s’écrire sous la forme $u a plus v b eq 1$ avec $u eq 1$ et $b eq minus 1$ === Exercice 19 p 149 <exercice-19-p-149> + On pose $a eq 2 n plus 5$ et $b eq 2 n plus 4$, on obtient $a minus b eq 1$. Donc $a$ et $b$ peuvent s’écrire sous la forme $u a plus v b eq 1$ avec $u eq 1$ et $b eq minus 1$ entiers relatifs. D’après le théorème de Bézout $a$ et $b$ sont premiers entre eux, donc la fraction $frac(2 n plus 5, 2 n plus 4)$ et irréductible.
https://github.com/davystrong/umbra
https://raw.githubusercontent.com/davystrong/umbra/main/gallery/torn-paper.typ
typst
MIT License
#import "@preview/suiji:0.3.0": * #import "@preview/umbra:0.1.0": shadow-path #set page(width: 13cm, height: 8cm, margin: 0.0cm) #let torn-paper( tear-positions: (40%, 45%), alignment: left, paper-colour: rgb("ECEBE9"), mult: 0.4%, seed: auto, approx-steps: 100, ) = { assert(alignment in (left, right, top, bottom)) context { let tear-positions = tear-positions if type(tear-positions) != array { tear-positions = (tear-positions, tear-positions) } else if tear-positions.len() == 1 { tear-positions = tear-positions * 2 } let seed = seed if seed == auto { seed = counter(page).get().at(0) counter(page).step() } let chunk_size = int(calc.round(approx-steps / (tear-positions.len() - 1))) let steps = chunk_size * (tear-positions.len() - 1) let rng = gen-rng-f(seed) let edge0-vals (rng, edge0-vals) = random-f(rng, size: (steps - 1)) edge0-vals = edge0-vals.fold((0%,), (acc, x) => { acc.push(acc.last() + ((x * 2 - 1) * mult)) acc }) edge0-vals = edge0-vals.chunks(chunk_size).zip(tear-positions, tear-positions.slice(1)).map( ((chunk, prev, next)) => { chunk.enumerate().map( ((i, x)) => { let r = i / (chunk.len() - 1) assert(r <= 1) prev + (next - prev) * r + x - chunk.first() * (1 - r) - chunk.last() * r }, ) }, ).flatten() assert(edge0-vals.len() == steps) assert(edge0-vals.first() == tear-positions.first()) assert(edge0-vals.last() == tear-positions.last()) edge0-vals = edge0-vals.enumerate().map(((i, x)) => { (x, i * 100% / (steps - 1)) }) let edge1-vals (rng, edge1-vals) = random-f(rng, size: steps) edge1-vals = edge0-vals.rev().zip(edge1-vals).map((((x, y), r)) => (x + r * 0.2% + 2%, y)) let shadow-vals = edge1-vals shadow-vals.insert(0, shadow-vals.first()) let edge2-vals = edge1-vals edge2-vals.insert(0, (100%, 100%)) edge2-vals.push((100%, 0%)) edge1-vals = edge1-vals + edge0-vals edge0-vals.insert(0, (0%, 0%)) edge0-vals.push((0%, 100%)) if alignment == right { edge0-vals = edge0-vals.map(((x, y)) => (100% - x, y)) edge1-vals = edge1-vals.map(((x, y)) => (100% - x, y)) edge2-vals = edge2-vals.map(((x, y)) => (100% - x, y)) shadow-vals = shadow-vals.map(((x, y)) => (100% - x, y)).rev() } else if alignment == top { edge0-vals = edge0-vals.map(((x, y)) => (y, x)) edge1-vals = edge1-vals.map(((x, y)) => (y, x)) edge2-vals = edge2-vals.map(((x, y)) => (y, x)) shadow-vals = shadow-vals.map(((x, y)) => (y, x)) } else if alignment == bottom { edge0-vals = edge0-vals.map(((x, y)) => (y, 100% - x)) edge1-vals = edge1-vals.map(((x, y)) => (y, 100% - x)) edge2-vals = edge2-vals.map(((x, y)) => (y, 100% - x)) shadow-vals = shadow-vals.map(((x, y)) => (y, 100% - x)) } layout( size => { block( width: 100%, height: 100%, { polygon(fill: paper-colour, stroke: none, ..edge2-vals) polygon(fill: none, stroke: none, ..edge0-vals) place( horizon + left, polygon(fill: white.transparentize(50%), stroke: none, ..edge1-vals), ) place(top + left, shadow-path( ..shadow-vals, shadow-stops: (luma(210), paper-colour), shadow-radius: 0.15cm, )) }, ) }, ) } } #set text(size: 36pt, font: "Indie Flower") #show regex("[a-zA-Z]"): (letter) => { context{ let seed = counter("letters").get().at(0) counter("letters").step() let rng = gen-rng-f(seed) let x let y (rng, (x, y)) = random-f(rng, size: 2) box(move(dx: x * 0.1cm, dy: y * 0.2cm - 0.1cm, letter)) } } #place(horizon + left, [#h(0.8cm) at a quarter to twelve #h(3.3cm) learn what #h(7.7cm) maybe]) #place(torn-paper( tear-positions: (100%, 95%, 86%, 78%, 70%, 50%, 30%, 0%), alignment: right, approx-steps: 250, ))
https://github.com/LEXUGE/poincare
https://raw.githubusercontent.com/LEXUGE/poincare/main/src/templates/simple.typ
typst
MIT License
#import "@preview/ctheorems:1.1.0": * #let simple(title: "", authors: (), disp_content: true, body) = { // Set document metadata set document(author: authors.map(x => x.name), title: title) show: thmrules // Number the headings set heading(numbering: "1.1.") // Break the word at the end of each line set par(justify: true) // Make some vertical spacing for headings show heading: it => [ #v(1em) #it ] // Start title and author section align( center, )[ #block(text(weight: 700, 1.75em, title)) #v(2em) // Display authors #let count = authors.len() #let ncols = calc.min(count, 3) #grid(columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [ #author.name \ #link("mailto:" + author.email) ])) ] if disp_content { outline(fill: none, indent: true) } set math.equation(numbering: "(1.1)") body }
https://github.com/hongjr03/shiroa-page
https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DSA/chapters/9排序.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") = 排序 <排序> == 冒泡排序 <冒泡排序> === 算法描述 冒泡排序是一种简单的排序算法。它重复地遍历要排序的列表,一次比较两个元素,如果它们的顺序错误就把它们交换过来。遍历列表的工作是重复地进行直到没有再需要交换,也就是说该列表已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 === 算法实现 ```c void BubbleSort(Elem R[], int n) { i = n; while (i > 1) { lastExchangeIndex = 1; for (j = 1; j < i; j++) if (R[j + 1].key < R[j].key) { Swap(R[j], R[j + 1]); lastExchangeIndex = j;// 记下进行交换的记录位置 }// if i = lastExchangeIndex;// 本趟进行过交换的 // 最后一个记录的位置 }// while }// BubbleSort ``` === 算法分析 冒泡排序的时间复杂度为 $O(n^2)$,空间复杂度为 $O(1)$。是稳定的排序算法。 == 插入排序 === 算法描述 插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 === 算法实现 ==== 直接插入排序 ```c /* 插入排序 */ void insertionSort(int nums[], int size) { // 外循环:已排序区间为 [0, i-1] for (int i = 1; i < size; i++) { int base = nums[i], j = i - 1; // 内循环:将 base 插入到已排序区间 [0, i-1] 中的正确位置 while (j >= 0 && nums[j] > base) { // 将 nums[j] 向右移动一位 nums[j + 1] = nums[j]; j--; } // 将 base 赋值到正确位置 nums[j + 1] = base; } } ``` 课本上不另外设 `base` 变量,而是用 ```c nums[0] = nums[i]``` 代替。 ```c L.r[0] = L.r[i];// 复制为监视哨 for (j = i - 1; L.r[0].key < L.r[j].key; --j) L.r[j + 1] = L.r[j];// 记录后移 L.r[j + 1] = L.r[0]; // 插入到正确位置 ``` 这里 ```c L.r[0].key < L.r[j].key``` 保证了排序的稳定性。 ==== 二分插入排序 ```cpp /*折半插入排序*/ void insertionBinarySort(std::vector<int> &nums) { int n = nums.size(); // 外循环,已排序区间为 [0, i-1] for (int i = 1; i < n; i++) { int base = nums[i]; int low = 0; int high = i - 1; while (low <= high) { int mid = (low + high) / 2; if (nums[mid] > base) { high = mid - 1; } else { low = mid + 1; } } // 将区间 [low, i-1] 的元素右移,腾出位置给 base for (int j = i; j >= low + 1; j--) { nums[j] = nums[j - 1]; } // 将 base 插入到正确位置 nums[low] = base; } } ``` ==== 希尔排序 和插入排序类似,但是希尔排序会先将数组分成若干个子序列,然后对每个子序列进行插入排序,最后再对整个数组进行插入排序。实现上,将插入排序中的步长 $1$ 替换为 $d$,即可实现希尔排序。 ```cpp void ShellInsert(SqList &L, int dk) { for (i = dk + 1; i <= n; ++i) if (L.r[i].key < L.r[i - dk].key) { L.r[0] = L.r[i];// 暂存在 R[0] for (j = i - dk; j > 0 && (L.r[0].key < L.r[j].key); j -= dk) L.r[j + dk] = L.r[j];// 记录后移,查找插入位置 L.r[j + dk] = L.r[0]; // 插入 }// if }// ShellInsert void ShellSort(SqList &L, int dlta[], int t) { for (k = 0; k < t; ++k) ShellInsert(L, dlta[k]); }// ShellSort ``` === 算法分析 插入排序的时间复杂度为 $O(n^2)$,空间复杂度为 $O(1)$。是稳定的排序算法。 == 快速排序 === 算法描述 快速排序使用分治法策略来把一个序列分为两个子序列。具体算法描述如下: 1. 从数列中挑出一个元素,称为 “基准”(pivot); 2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆放在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; 3. 递归地把小于基准值元素的子数列和大于基准值元素的子数列排序。 === 算法实现 ==== 冒泡排序 / 起泡排序 见冒泡排序。 ==== 快速排序 定了枢轴之后,设左右指针分别指向数组的两端,右指针向左移动,找到第一个小于枢轴的元素,此时将左指针指向的元素赋值给右指针指向的元素,左指针向右移动,找到第一个大于枢轴的元素,此时将右指针指向的元素赋值给左指针指向的元素,直到左右指针相遇,将枢轴元素赋值给左右指针相遇的位置。 其实每次扫描就是找到一对逆序对,然后交换。 然后一趟排序完成后,枢轴元素就在正确的位置上了,返回枢轴的位置,对其左右两部分递归进行排序。 ```c int Partition(RedType R[], int low, int high) { R[0] = R[low]; pivotkey = R[low].key;// 枢轴 while (low < high) { //从表的两端交替地向中间扫描 while (low < high && R[high].key >= pivotkey) --high;//将比枢轴记录小的记录交换到低端 R[low] = R[high]; while (low < high && R[low].key <= pivotkey) ++low;//将比枢轴记录大的记录交换到高端 R[high] = R[low]; } R[low] = R[0]; return low;//枢轴记录到位,返回枢轴位置 }// Partition void QSort(RedType &R[], int low, int high) { // 对记录序列R[low..high]进行快速排序 if (low < high) {// 长度大于1 pivotloc = Partition(R, low, high); // 对 R[s..t] 进行一次划分 QSort(R, low, pivotloc - 1); // 对低子序列递归排序,pivotloc是枢轴位置 QSort(R, pivotloc + 1, high);// 对高子序列递归排序 } }// QSort void QuickSort(SqList &L) { // 对顺序表进行快速排序 QSort(L.r, 1, L.length); }// QuickSort ``` 或者这么写: ```cpp /* 元素交换 */ void swap(vector<int> &nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } /* 哨兵划分 */ int partition(vector<int> &nums, int left, int right) { // 以 nums[left] 为基准数 int i = left, j = right; while (i < j) { while (i < j && nums[j] >= nums[left]) j--;// 从右向左找首个小于基准数的元素 while (i < j && nums[i] <= nums[left]) i++; // 从左向右找首个大于基准数的元素 swap(nums, i, j);// 交换这两个元素 } swap(nums, i, left);// 将基准数交换至两子数组的分界线 return i; // 返回基准数的索引 } /* 快速排序 */ void quickSort(vector<int> &nums, int left, int right) { // 子数组长度为 1 时终止递归 if (left >= right) return; // 哨兵划分 int pivot = partition(nums, left, right); // 递归左子数组、右子数组 quickSort(nums, left, pivot - 1); quickSort(nums, pivot + 1, right); } ``` === 算法分析 - *时间复杂度为 $O(n log n)$、自适应排序*:在平均情况下,哨兵划分的递归层数为 $log n$ ,每层中的总循环数为 $n$ ,总体使用 $O(n log n)$ 时间。在最差情况下,每轮哨兵划分操作都将长度为 $n$ 的数组划分为长度为 $0$ 和 $n - 1$ 的两个子数组,此时递归层数达到 $n$ ,每层中的循环数为 $n$ ,总体使用 $O(n^2)$ 时间。 - *空间复杂度为 $O(n)$、原地排序*:在输入数组完全倒序的情况下,达到最差递归深度 $n$ ,使用 $O(n)$ 栈帧空间。排序操作是在原数组上进行的,未借助额外数组。 - *非稳定排序*:在哨兵划分的最后一步,基准数可能会被交换至相等元素的右侧。 === 算法优化 若待排记录的初始状态为按关键字有序时,快速排序将蜕化为起泡排序,其时间复杂度为 $O(n^2)$。为了避免这种情况,可以采用三数取中法:在待排记录序列中,首、尾、中间三个记录的关键字取中间值作为枢轴记录的关键字。 == 选择排序 === 算法描述 选择排序是一种简单直观的排序算法。它的工作原理如下: 1. 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置; 2. 然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾; 3. 重复第二步,直到所有元素均排序完毕。 === 算法实现 ```c /* 选择排序 */ void selectionSort(vector<int> &nums) { int n = nums.size(); // 外循环:未排序区间为 [i, n-1] for (int i = 0; i < n - 1; i++) { // 内循环:找到未排序区间内的最小元素 int k = i; for (int j = i + 1; j < n; j++) { if (nums[j] < nums[k]) k = j;// 记录最小元素的索引 } // 将该最小元素与未排序区间的首个元素交换 swap(nums[i], nums[k]); } } ``` === 算法分析 选择排序的时间复杂度为 $O(n^2)$,空间复杂度为 $O(1)$。是不稳定的排序算法。 #figure(image("../assets/2024-06-10-15-11-21.png"), caption: "选择排序不稳定示意图") === 树形选择排序 / 锦标赛排序 树形选择排序是选择排序的一种改进,它使用完全二叉树的结构来减少比较次数。每次比较两个元素,将较小的元素放在树的叶子节点,然后向上比较,直到根节点为止。这种排序方法尚有辅助存储空间较多、和“最大值”进行多余的比较等缺点。为了弥补,提出了另一种形式的选择排序——堆排序。 == 堆排序 === 算法描述 堆排序是一种树形选择排序,是对直接选择排序的有效改进。堆排序的基本思想是:将待排序序列构造成一个大顶堆,此时整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余 $n-1$ 个元素重新构造成一个堆,这样会得到 $n-1$ 个元素的次大值。如此反复执行,便能得到一个有序序列。 === 算法实现 ```cpp /* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */ void siftDown(vector<int> &nums, int n, int i) { while (true) { // 判断节点 i, l, r 中值最大的节点,记为 ma int l = 2 * i + 1; int r = 2 * i + 2; int ma = i; if (l < n && nums[l] > nums[ma]) ma = l; if (r < n && nums[r] > nums[ma]) ma = r; // 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出 if (ma == i) { break; } // 交换两节点,和孩子交换 swap(nums[i], nums[ma]); // ma 是交换节点的索引,继续向下堆化 i = ma; } } /* 堆排序 */ void heapSort(vector<int> &nums) { // 建堆操作:堆化除叶节点以外的其他所有节点 // 由于叶节点没有子节点,因此它们天然就是合法的子堆,无须堆化 // 选择倒序遍历,是因为这样能够保证当前节点之下的子树已经是合法的子堆 for (int i = nums.size() / 2 - 1; i >= 0; --i) { siftDown(nums, nums.size(), i); } // 从堆中提取最大元素,循环 n-1 轮 for (int i = nums.size() - 1; i > 0; --i) { // 交换根节点与最右叶节点(交换首元素与尾元素) swap(nums[0], nums[i]); // 以根节点为起点,从顶至底进行堆化 siftDown(nums, i, 0); } } ``` === 算法分析 - *时间复杂度为 $O(n log n)$、非自适应排序*:建堆操作使用 $O(n)$ 时间。从堆中提取最大元素的时间复杂度为 $O(log n)$ ,共循环 $n - 1$ 轮。 - *空间复杂度为 $O(1)$、原地排序*:几个指针变量使用 $O(1)$ 空间。元素交换和堆化操作都是在原数组上进行的。 - *非稳定排序*:在交换堆顶元素和堆底元素时,相等元素的相对位置可能发生变化。 == 归并排序 === 算法描述 归并排序是一种分治算法,采用分治策略将待排序序列分为若干个子序列,分别进行排序,最后再将排好序的子序列合并成一个有序序列。分别排序时其实是将两个有序序列合并成一个有序序列,只需要比较两个序列的首元素,将较小的元素放入新序列中。 #figure(image("../assets/2024-06-10-15-40-24.png"), caption: "归并排序示意图") === 算法实现 归并排序与二叉树后序遍历的递归顺序是一致的。 - *后序遍历*:左子树、右子树、根节点 - *归并排序*:左子序列、右子序列、合并 ```cpp void Merge(RcdType SR[], RcdType &TR[], int i, int m, int n) { // 将有序的记录序列 SR[i..m] 和 SR[m+1..n],归并为有序的//记录序列 TR[i..n] for (j = m + 1, k = i; i <= m && j <= n; ++k) {// 将 SR 中记录由小到大地并入 TR if (SR[i].key <= SR[j].key) TR[k] = SR[i++]; else TR[k] = SR[j++]; } if (i <= m) TR[k..n] = SR[i..m];// 将剩余的 SR[i..m] 复制到 TR if (j <= n) TR[k..n] = SR[j..n];// 将剩余的 SR[j..n] 复制到 TR }// Merge void Msort(RcdType SR[], RcdType &TR1[], int s, int t) { // 将 SR[s..t] 归并排序为 TR1[s..t] if (s = = t) TR1[s] = SR[s]; else { m = (s + t) / 2;// 将 SR[s..t] 平分为 SR[s..m] 和 SR[m+1..t] Msort(SR, TR2, s, m); // 递归地将 SR[s..m] 归并为有序的 TR2[s..m] Msort(SR, TR2, m + 1, t); //递归地 SR[m+1..t] 归并为有序的 TR2[m+1..t] Merge(TR2, TR1, s, m, t); // 将 TR2[s..m] 和 TR2[m+1..t] 归并到 TR1[s..t] } }// Msort void MergeSort(SqList &L) { // 对顺序表 L 作 2-路归并排序 MSort(L.r, L.r, 1, L.length); }// MergeSort ``` 书上的分界点选的是 $floor(m = (s + t) / 2)$,向下取整,然后递归调用时,左子序列是 $[s, m]$,右子序列是 $[m + 1, t]$。 不过书上这个 `Merge` 写得比较抽象,可以换成下面这种写法: ```cpp /* 合并左子数组和右子数组 */ void merge(vector<int> &nums, int left, int mid, int right) { // 左子数组区间为 [left, mid], 右子数组区间为 [mid+1, right] // 创建一个临时数组 tmp,用于存放合并后的结果 vector<int> tmp(right - left + 1); // 初始化左子数组和右子数组的起始索引 int i = left, j = mid + 1, k = 0; // 当左右子数组都还有元素时,进行比较并将较小的元素复制到临时数组中 while (i <= mid && j <= right) { if (nums[i] <= nums[j]) tmp[k++] = nums[i++]; else tmp[k++] = nums[j++]; } // 将左子数组和右子数组的剩余元素复制到临时数组中 while (i <= mid) { tmp[k++] = nums[i++]; } while (j <= right) { tmp[k++] = nums[j++]; } // 将临时数组 tmp 中的元素复制回原数组 nums 的对应区间 for (k = 0; k < tmp.size(); k++) { nums[left + k] = tmp[k]; } } /* 归并排序 */ void mergeSort(vector<int> &nums, int left, int right) { // 终止条件 if (left >= right) return;// 当子数组长度为 1 时终止递归 // 划分阶段 int mid = left + (right - left) / 2;// 计算中点 mergeSort(nums, left, mid); // 递归左子数组 mergeSort(nums, mid + 1, right); // 递归右子数组 // 合并阶段 merge(nums, left, mid, right); } ``` === 算法分析 - *时间复杂度为 $O(n log n)$、非自适应排序*:划分产生高度为 $log n$ 的递归树,每层合并的总操作数量为 $n$ ,因此总体时间复杂度为 $O(n log n)$ 。 - *空间复杂度为 $O(n)$、非原地排序*:递归深度为 $log n$ ,使用 $O(log n)$ 大小的栈帧空间。合并操作需要借助辅助数组实现,使用 $O(n)$ 大小的额外空间。 - *稳定排序*:在合并过程中,相等元素的次序保持不变。 对于链表,归并排序相较于其他排序算法具有显著优势,可以将链表排序任务的空间复杂度优化至 $O(1)$ 。在合并阶段,链表中节点增删操作仅需改变引用(指针)即可实现,因此合并阶段(将两个短有序链表合并为一个长有序链表)无须创建额外链表。 == 基数排序 === 算法描述 基数排序是一种非比较型整数排序算法,其原理是将整数按位数切割成不同的数字,然后按每个位数分别比较。基数排序的实现有两种方式:LSD(Least Significant Digit first)低位优先和 MSD(Most Significant Digit first)高位优先。 在连续的排序轮次中,后一轮排序会覆盖前一轮排序的结果。举例来说,如果第一轮排序结果 $a<b$ ,而第二轮排序结果 $a>b$ ,那么第二轮的结果将取代第一轮的结果。由于数字的高位优先级高于低位,因此应该先排序低位再排序高位。 === 算法实现 书上实现的是链式基数排序。 ```cpp #define MaxDigit 4 #define Radix 10 typedef struct { int keys[MaxDigit];// 关键字,keys[0] 是主位 int next;// 指向下一个结点 } RecType; typedef struct { int head, tail;// 链表的头指针和尾指针 } NodeType; NodeType radix[Radix];// 静态链表 void LSDRadixSort(RecType R[], int n) { // 对 R[1..n] 进行基数排序,最大关键字为 MaxKey for (i = 1; i <= n; ++i) { R[i].next = i + 1; } R[n].next = 0;// 用 R[0].next 作为链表头指针 for (i = 0; i < MaxDigit; ++i) { // 从低位到高位依次对各位关键字进行分配和收集 Distribute(R, i);// 分配 Collect(R);// 收集 } }// LSDRadixSort void Distribute(RecType R[], int i) { // 按第 i 位关键字的大小分配到各个子链表 p = R[0].next; while (p != 0) { j = ord(R[p].keys[i]);// ord 函数返回第 i 位关键字的值 if (radix[j].head == 0) radix[j].head = p; else R[radix[j].tail].next = p; radix[j].tail = p; p = R[p].next; } }// Distribute void Collect(RecType R[]) { // 从各个子链表中收集 i = 0; while (radix[i].head == 0) i++; R[0].next = radix[i].head; p = radix[i].tail; while (i < MaxDigit) { i++; while (i < MaxDigit && radix[i].head == 0) i++; if (i < MaxDigit) { R[p].next = radix[i].head; p = radix[i].tail; } } R[p].next = 0; }// Collect ``` 书上的实现: ```c #define MAX_NUM_OF_KEY 8//关键字项数的最大值 #define RADIX 10 //关键字基数,此时是十进制整数的基数 #define MAX_SPACE 10000 typedef struct { KeysType keys[MAX_NUM_OF_KEY];//关键字 InfoType otheritems; //其他数据项 int next; } SLCell;//静态链表的结点类型 typedef struct { SLCell r[MAX_SPACE]; //静态链表的可利用空间,r[0] 为头结点 int keynum; //记录的当前关键字个数 int recnum; //静态链表的当前长度 } SLList; //静态链表类型 typedef int ArrType[RADIX];//指针数组类型 void Distribute(SLCell &r, int i, ArrType &f, ArrType &e) { //静态链表 L 的 r 域中记录已按 keys[0],…,keys[i-1]) 有序。本算法按第 i 个关键字 keys[i] 建立 RADIX 个子表,使同一子表中记录的 keys[i] 相同.f[0..RADIX-1] 和 e[0..RADIX-1] 分别指向各子表中第一个和最后一个记录。 for (j = 0; j < Radix; ++j) f[j] = 0; //各子表初始化为空表 for (p = r[0].next; p; p = r[p].next) { j = ord(r[p].keys[i]); //ord 将记录中第 i 个关键字映射到 [0..RADIX-1], if (!f[j]) f[j] = p; else r[e[j]].next = p; e[j] = p; //将 p 所指的结点插入第 j 个子表 } }// Distribute void Collect(SLCell &r, int i, ArrType f, ArrType e) { //本算法按 keys[i] 自小至大的将 f[0..RADIX-1] 所指各子表依次链接成一个链表,e[0..RADIX-1] 为各子表的尾指针。 for (j = 0; !f[j]; j = succ(j)); //找第一个非空子表,succ 为求后继函数 r[0].next = f[j]; t = e[j]; //r[0].next 指向第一个非空子表中第一个结点 while (j < RADIX) { for (j = succ(j); j < RADIX - 1 && !f[j]; j = succ(j));//找下一个非空子表 if (f[j]) { r[t].next = f[j]; t = e[j]; } //链接两个非空子表 } r[t].next = 0; //t 指向最后一个非空子表的最后一个结点 }// Collect void RadixSort(SList &L) { // L 是采用静态链表表示的顺序表。对 L 做基数排序,使 //得 L 成为按关键字自小到达的有序静态链表,L.r[0] 为 //头结点。 for (i = 0; i < L.recnum; ++i) L.r[i].next = i + 1; L.r[L.recnum].next = 0;//将 L 改造为静态链表 for (i = 0; i < L.keynum; ++i) { //按最低位优先依次对各关键字进行分配和收集 Distribute(L.r, i, f, e);//第 i 趟分配 Collect(L.r, i, f, e); //第 i 趟收集 } }// RadixSort ``` === 算法分析 时间复杂度 $O(d(n+r d))$。需附设队列首尾指针,则空间复杂度为 $O(r d)$。$r$ 为基数,$d$ 为关键字位数。 == 总结 === 时间性能 平均时间复杂度: - $O(n log n)$:快速排序、归并排序、堆排序 - $O(n^2)$:冒泡排序、直接插入排序、简单选择排序 - $O(d(n+r d))$:基数排序 当待排记录序列按关键字顺序有序时: - 直接插入排序和起泡排序能达到$O(n)$的时间复杂度 - 快速排序的时间性能蜕化为$O(n^2)$。 简单选择排序、堆排序和归并排序的时间性能不随记录序列中关键字的分布而改变。 === 空间性能 - $O(1)$:所有的简单排序方法(包括:直接插入、起泡和简单选择)和堆排序,是原地排序; - $O(n log n)$:快速排序,为递归程序执行过程中,栈所需的辅助空间; - $O(n)$:归并排序,需要一个与待排记录序列等长的辅助数组; - $O(r d)$:链式基数排序,需附设队列首尾指针。 === 稳定性 - 不稳定的排序方法:快速排序、直接选择排序、希尔排序、堆排序; - 稳定的排序方法:冒泡排序、直接插入排序、归并排序、基数排序。 === 时间复杂度下限 基于比较关键字的排序方法的时间复杂度下限为 $O(n log n)$。
https://github.com/sitandr/typst-examples-book
https://raw.githubusercontent.com/sitandr/typst-examples-book/main/src/snippets/special/index.md
markdown
MIT License
# Special documents ## Signature places ```typ #block(width: 150pt)[ #line(length: 100%) #align(center)[Signature] ] ``` ## Presentations See [polylux](../../packages/). ## Forms ### Form with placeholder ```typ #grid( columns: 2, rows: 4, gutter: 1em, [Student:], [#block()#align(bottom)[#line(length: 10em, stroke: 0.5pt)]], [Teacher:], [#block()#align(bottom)[#line(length: 10em, stroke: 0.5pt)]], [ID:], [#block()#align(bottom)[#line(length: 10em, stroke: 0.5pt)]], [School:], [#block()#align(bottom)[#line(length: 10em, stroke: 0.5pt)]], ) ``` ### Interactive > Presentation interactive forms are coming! They are currently under heavy work by @tinger.
https://github.com/storopoli/Bayesian-Statistics
https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/04-bayesian_workflow.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/polylux:0.3.1": * #import themes.clean: * #import "utils.typ": * #import "@preview/cetz:0.1.2" #new-section-slide("Bayesian Workflow") #slide(title: "Recommended References")[ - #cite(<gelman2013bayesian>, form: "prose") - Chapter 6: Model checking - #cite(<mcelreath2020statistical>, form: "prose") - Chapter 4: Geocentric Models - #cite(<gelman2020regression>, form: "prose"): - Chapter 6: Background on regression modeling - Chapter 11: Assumptions, diagnostics, and model evaluation - #cite(<gelmanBayesianWorkflow2020>, form: "prose") - "Workflow Paper" ] #focus-slide(background: julia-purple)[ #align(center)[#image("images/memes/workflow.jpg")] ] #slide(title: "All Models Are Wrong")[ #side-by-side(columns: (4fr, 1fr))[ #align(center + horizon)[#quote( block: true, attribution: [<NAME> @boxScienceStatistics1976], )[ All models are wrong but some are useful ]] ][ #image("images/persons/george_box.jpg") ] ] #slide(title: [Bayesian Workflow #footnote[ based on #cite(<gelmanBayesianWorkflow2020>, form: "prose") ]])[ #v(2em) #align(center)[#cetz.canvas({ import cetz.draw: * set-style( mark: (start: ">", end: ">", fill: black, size: 0.3), stroke: (thickness: 2pt), radius: 3, ) circle((0, 0)) content((0, 0), [#align(center)[Prior \ Elicitation]]) line((3, 0), (7, 0)) content((5, 2), [#align(center)[Prior \ Predictive \ Check]]) circle((10, 0)) content((10, 0), [#align(center)[Model \ Specification]]) line((13, 0), (17, 0)) content((15, 2), [#align(center)[Posterior \ Predictive \ Check]]) circle((20, 0)) content((20, 0), [#align(center)[Posterior \ Inference]]) })] ] #slide(title: [Bayesian Workflow #footnote[ adapted from #link("https://github.com/elizavetasemenova")[<NAME>]. ]])[ - Understand the domain and problem. - Formulate the model mathematically. - Implement model, test, and debug. - Perform prior predictive checks. - Fit the model. - Assess convergence diagnostics. - Perform posterior predictive checks. - Improve the model iteratively: from baseline to complex and computationally efficient models. ] #slide(title: "Actual Bayesian Workflow")[ #figure( image("images/workflow/workflow_overview.svg", height: 80%), caption: [Bayesian workflow by #cite(<gelmanBayesianWorkflow2020>, form: "prose").], ) ] #slide(title: [Not a "new idea"])[ #figure( image("images/workflow/box_loop.png", height: 80%), caption: [Box's Loop from #cite(<boxScienceStatistics1976>, form: "prose") but taken from #cite(<Blei_Workflow2014>, form: "prose").], ) ] #slide(title: "Prior Predictive Check")[ Before we feed data into our model, we need to check all of our priors. #v(1em) In a very simple way, it consists in simulate parameter values based on prior distribution without conditioning on any data or employing any likelihood function. #v(1em) Independent of the level of information specified in the priors, it is always important to perform a prior sensitivity analysis in order to have a deep understanding of the prior influence onto the posterior. ] #slide(title: "Posterior Predictive Check")[ #text(size: 18pt)[ We need to make sure that the posterior distribution of $bold(y)$, namely $bold(tilde(y))$, can capture all the nuances of the real distribution density/mass of $bold(y)$. This procedure is called *posterior predictive check*, and it is generally carried on by a visual inspection #footnote[ we also perform mathematical/exact inspections, see the section on _Model Comparison_. ] of the real density/mass of $bold(y)$ against generated samples of $bold(y)$ by the Bayesian model. The purpose is to compare the histogram of the dependent variable $bold(y)$ against the histograms of simulated dependent variables $bold(y)_"rep"$ by the model after parameter inference. The idea is that the real and simulated histograms blend together and we do not observer any divergences. ] ] #slide(title: "Examples of Posterior Predictive Checks")[ #side-by-side(columns: (1fr, 1fr))[ #figure( image("images/predictive_checks/pp_check_brms.svg", height: 80%), caption: [#text(size: 18pt)[Real versus Simulated Densities]], ) ][ #figure( image("images/predictive_checks/pp_check_brms_ecdf.svg", height: 80%), caption: [#text(size: 18pt)[Real versus Simulated Empirical CDFs]], ) ] ]
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/lectures/2024-09-13.typ
typst
#import "/utils/math.typ": * = Геометрическое определение вероятности Рассматриваем подмножества на $RR^n$, которые имеют конечную меру Пример эксперимента: попадет ли случайная точка в подмножество #figure(image("./geom_prob.svg", height: 5cm)) $ P(A) = mu(A) / mu(Omega)$ #def[ События #defitem[несовместны] --- $A dot B = emptyset$ ] == Св-ва $P(A)$ + $P(A) >= 0 forall A subset Omega$ + $P(Omega) = 1$ + если $A_1$ и $A_2$ несовместны, то $P(A_1 + A_2) = P(A_1) + P(A_2)$ == Задача $x$ --- время прихода Джульеты $y$ --- время прихода Ромео $abs(x - y) < 1\4$ #figure(image("./romeo.svg", height: 5cm)) $ P(overline(A)) = mu(overline(A))/mu(Omega) = (9/16)/1 $ $ P(A) = 1 - 9/16 = 7/16 $ = Частотное (статистическое) определение Пусть опыт проведен $N$ раз, и событие произошло $m_A$ раз. Тогда *частота* события $A$: $nu(A) = m_A/N$ $ P(A) = lim_(N -> oo) m_A/N $ = Аксиоматическое определение Колмагорова Пусть $cal(A)$ --- $sigma$-алгебра событий на пространстве $Omega$. Числ функция $P: cal(A) -> RR^1$ --- вероятность, если: + $forall A in cal(A) P(A) >= 0$ --- аксиома неотрицательности + $P(Omega) = 1$ --- условие нормировки + если $A_1, ..., A_n, ...$ попарно несовместны, то $P(sum_(i=1)^oo A_i = sum_(i=1)^oo P(A_i)$ Число $P(A)$ называется вероятностью соб-я $A$ Тройка $(Omega, cal(A), P)$ --- вероятностное пространство == Свойства $P(A)$ + $P(overline(A)) = 1 - P(A)$ #proof[ $ Omega = A + overline(A) $ $ A dot overline(A) = emptyset $ $ 1 = P(Omega) = P(A + overline(A)) = P(A) + P(overline(A)) $ ] + $P(emptyset) = 1 - P(Omega) = 0$ + $A subset B => P(A) <= P(B)$ #proof[ $ B = A + (B \\ A) $ $ P(B) = P(A + (B \\ A)) = P(A) + underbrace(P(B \\ A), >=0) $ ] + $ forall A: 0 <= P(A) <= 1 $ + Теорема сложения: $P(A + B) = P(A) + P(B) - P(A dot B)$ #proof[ $ A = A Omega = A B + A overline(B) $ $ B = B Omega = A B + overline(A) B $ $ A + B = underbrace( A B + A overline(B) + overline(A) B, "попарно несовместны" ) $ $ P(A) = P(A B) + P(A overline(B)) => P(A) - P(A B) = P(A overline(B)) $ $ P(B) = P(A B) + P(overline(A) B) => P(B) - P(A B) = P(overline(A) B) $ $ P(A + B) = P(A B) + P(A overline(B)) + P(overline(A) B) = P(A B) + P(A) - P(A B) + P(B) - P(A B) = P(A) + P(B) - P(A B) $ ] + Обобщение теоремы сложения: $ P(underbrace(A_1 + A_2, A) + underbrace(A_3, B)) = P(A) + P(B) = P(A_1) + P(A_2) + P(A_3) - P(A_1 A_2) - P(A_1 A_3) - P(A_2 A_3) + P(A_1 A_2 A_3) $ $ P(sum_i A_i) = sum_i P(A_i) - sum_(i < j) P(A_i A_j) + sum_(i < j < k) P(A_i A_j A_k) - ... + (-1)^(n+1)P(A_1 ... A_n) $ = Условная вероятность #figure(image("./cond_prob.svg", height: 5cm)) Переходим из $Omega$ в $B$ Пусть $A, B in Omega$ и $P(B) != 0$, тогда вероятность $A$ при условии $B$: $ P(A|B) = P(A B) / P(B) $ #def[ $A$ и $B$ #defitem[независимые], если $P(A|B) = P(A)$ ] #def[ $A$ и $B$ #defitem[независимые], если $P(A B) = P(A)P(B)$ ] Любые несовместные события зависимы
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/markup/enum.typ
typst
Apache License 2.0
Automatically numbered: + Preparations + Analysis + Conclusions Manually numbered: 2. What is the first step? 5. I am confused. + Moving on ... Multiple lines: + This enum item has multiple lines because the next line is indented. Function call. #enum[First][Second]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/call-06.typ
typst
Other
#let f(x) = x // Error: 2-6 expected function, found content #f[1](2)
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/brainstorm-scoring/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Brainstorm: Scoring Triballs", type: "brainstorm", date: datetime(year: 2023, month: 9, day: 2), author: "<NAME>", witness: "Violet Ridge", ) // TODO: add images // TODO: fill out pros and cons #grid( columns: (1fr, 1.5fr), gutter: 20pt, [ #heading([Extendable Arm]) An extendable arm to capture triballs from the loading zone, and pushing triballs in with a lexan skirt on the robot. #pro-con(pros: [ - Simple to build ], cons: [ - Inefficient motor use ]) ], image("./flaps.svg"), [ #heading([Folding Skirts]) Skirts that can fold outwards, and shovel triballs in. In addition we can add rounded sloped corners on the ends to lift the front of the bot upwards in order to help us get over the barrier. #pro-con(pros: [ - Simplest design - Allows us to go over the barrier - Does not use a motor ], cons: [ - We need to add pneumatic pistons and reservoirs ]) ], image("./hook.svg"), [ #heading([Extendable Net]) An extendable net to go over the triball and pull it inwards. #pro-con(pros: [ - Looks cool - Gladiator style points - Simple design ], cons: [ - Inefficient motor use - May not work ]) ], image("./net.svg"), )
https://github.com/AU-Master-Thesis/thesis
https://raw.githubusercontent.com/AU-Master-Thesis/thesis/main/sections/1-introduction/problem-definition.typ
typst
MIT License
#import "../../lib/mod.typ": * == Problem Definition <intro-problem-definition> // #jonas[No difference from last here. A lot of this is copied directly from the original contract, and thus not relevant anymore. You do not have to spend time on this section.] // // From the original contract: // // 2. Problem Definition & Objectives // // Efficient and safe approaches to multi-agent planning have been studied extensively, with many different approaches and assumptions about the environment and capabilities of the robotic agents. However, none of the existing approaches attempt to be able to operate in changing communication conditions, in a decentralized manner. Morteza[2], 2021, implements a modified A* algorithm that can handle dynamic obstacles in the environment. They also propose an architecture where the path planning optimization is done in a centralized manner on a cloud server. This reduces the number of messages sent between the agents but introduces a single point of failure. Xinjie[3], 2023, uses a game-theoretic approach to do path planning. Here agents cannot communicate with each other and instead have to predict how other agents will move based on the rules that govern the movement of the agents. Similar to how humans navigate in vehicle traffic, where the driver's own assumption/belief about how other drivers will follow the traffic law, is used to predict how other vehicles will move. Aalok[4], 2023, uses Gaussian Belief Propagation to do path planning for multiple agents. It is a decentralized approach using a data structure called a factor graph to model uncertainties about the position and velocity of other agents. // // The objective of this project is to build on top of the work of [4], and extend it to handle cases with limited communication possibilities, challenging environments, and non-holonomic kinematic constraints. The environment will be a static indoor environment at a logistics facility where robots are integrated into a baggage sorting handling system. Instead of extending the original paper's source code, we will reimplement our version of the Gaussian Belief Propagation Planner algorithm from scratch. The intention of the rewrite is not only to try and improve performance but also to get a better understanding of the algorithm, to make it easier to extend it. The implemented solution will be tested in a simulated environment, with common scenarios found at logistic facilities, such as three-way junctions and intersections. // Efficient and safe approaches to multi-agent planning have been studied extensively, with many different approaches and assumptions about the environment and capabilities of the robotic agents. However, none of the existing approaches attempt to be able to operate in changing communication conditions, in a decentralized manner. Morteza@kiadi_synthesized_2021, 2021, implements a modified A\* algorithm that can handle dynamic obstacles in the environment. They also propose an architecture where the path planning optimization is done in a centralized manner on a cloud server. This reduces the number of messages sent between the agents but introduces a single point of failure. Xinjie@liu_learning_2023, 2023, uses a game-theoretic approach to do path planning. Here agents cannot communicate with each other and instead have to predict how other agents will move based on the rules that govern the movement of the agents. Similar to how humans navigate in vehicle traffic, where the driver's own assumption/belief about how other drivers will follow the traffic law, is used to predict how other vehicles will move. Aalok@patwardhan_distributing_2023, 2023, uses Gaussian Belief Propagation to do path planning for multiple agents. It is a decentralized approach using a data structure called a factor graph to model uncertainties about the position and velocity of other agents. // The objective of this project is to build on top of the work of @patwardhan_distributing_2023, and extend it to handle cases with limited communication possibilities#note.k[ehh...], challenging environments, and non-holonomic kinematic constraints#note.k[ehh...]. The environment will be a static indoor environment at a logistics facility where robots are integrated into a baggage sorting handling system. Instead of extending the original paper's source code, we will reimplement our version of the Gaussian Belief Propagation Planner algorithm from scratch. The intention of the rewrite is not only to try and improve performance but also to get a better understanding of the algorithm, to make it easier to extend it. The implemented solution will be tested in a simulated environment, with common scenarios found at logistic facilities, such as three-way junctions and intersections. // #todo[Motivations for why our project is interesting] // - What makes multi robot systems, better/more interesting than single robot systems? // - What challenges does it bring with it? // #todo[formulate a strong and clear definition of what path planning is, and ensure it is consistent with the rest of the document] // - Peer to Peer based // - No need to synchronize the ordering of messages in time // - Modular. New factors can be added to the factor graph to encode different constraints. The underlying problem addressed by this thesis is the inefficiency and limitations in existing multi-agent path planning systems, particularly in complex environments. Current systems often struggle with issues related to collision avoidance, especially in context of multi-agent applications, and effective navigation through constrained and complex spaces. These challenges are exacerbated by the lack of robust, flexible, and extendable simulation frameworks that can accurately reproduce and enhance existing path planning algorithms. Furthermore, in the subfield of #acr("GBP") collaborative planning algorithms, which is still a quite new field, there is lack of automated global planning capabilities. The problem of integrating global planning with #acr("GBP") comes with further challenges, and it is important to consider possible solutions, in such a way that it does not compromise the performance of the system. This thesis seeks to solve these problems by developing a comprehensive solution that enhances the usability, functionality, and scalability of multi-agent path planning systems in the context of #acr("GBP") algorithms. The solution offered by this thesis is the simulation tool #acr("MAGICS"), which is based off of the work done in #gbpplanner, and extends it further. // be implemented in a simulated environment, and evaluated based on a set of predefined metrics.
https://github.com/CodeHex16/documentazione
https://raw.githubusercontent.com/CodeHex16/documentazione/main/1%20-%20Candidatura/Valutazione-Capitolati.typ
typst
#import "../template/documenti.typ" : * #show : doc => documento( titolo: "Incontro conoscitivo iniziale", data: [24/10/2024], presenze: ( "<NAME>","Redattore", "<NAME>","Verificatore" , "<NAME>","Verificatore", "<NAME>"," Verificatore", "<NAME>","Verificatore" ), doc, ) = Valutazione dei capitolati == Scopo del documento Lo scopo del documento #link( "https://www.math.unipd.it/~tullio/IS-1/2024/Progetto/Capitolati.html" )[Pagina Capitolati] == Capitolato scelto
https://github.com/Joelius300/hslu-typst-template
https://raw.githubusercontent.com/Joelius300/hslu-typst-template/main/chapters/03_concept.typ
typst
MIT License
= Ideen und Konzepte Hier geht es um die Fragestellung, wie Sie die formulierten Ziele der Arbeit erreichen wollen. Sie halten z.B. erste, grobe Ideen, skizzenhafte Lösungsansätze fest. Gibt es mehrere Wege, Ansätze um dieses Ziel zu erreichen, begründen Sie hier, warum Sie einen bestimmten Weg einschlagen. Beispiel für ein Softwareprojekt: Erste Gedanken über eine grobe Systemarchitektur. Ist z.B. eine Microservice-Architektur angebracht? Welche Alternativen bestehen, wo gibt es Problempunkte? Die Umsetzung, die Beurteilung der Machbarkeit und die detaillierte Beschreibung der umgesetzten Architektur sind dann Teil der Realisierung. === Abgrenzung zu Kapitel 5: - Besteht ein wesentliches Projektziel darin, für Ihre Kunden z.B. ein Security-Konzept, ein Kommunikations-konzept, ein IT-Fachkonzept oder ein anderes Fach-Konzept zu erstellen, dann wird die Entwicklung dieser (fachlichen) Konzepte unter «Realisierung» beschrieben (sie sind ja der eigentliche Kern Ihrer Arbeit). - Besteht z.B. ein wesentliches Ziel der Arbeit darin, eine passende Software-Architektur zu evaluieren, dann gehören die entsprechenden Beschreibungen ins Kapitel 5. #pagebreak()
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-text-00.typ
typst
Other
// Test classic example. #set text(font: "Roboto") #show "Der Spiegel": smallcaps Die Zeitung Der Spiegel existiert.
https://github.com/morel-olivier/template-typst
https://raw.githubusercontent.com/morel-olivier/template-typst/master/letter/lttr.typ
typst
// NOTE: lttr_data contains all the data to render the letter #let lttr_data = state("letter", none) // NOTE: lttr_max_dy keeps track of the largest offset dy (from the top margin) // of absolutely positioned content (sender and receiver fields) such that we // know how much vertical offset we need to add at the beginning of the letter // content. Note that length does not include the value of // `settings.content_spacing`. #let lttr_max_dy = state("lttr_max_dy", 0cm) #let lttr_update_max_dy(dy) = { locate(loc => { lttr_max_dy.update(x => calc.max(x, dy)) }) } #let lttr_fmt(it) = { if type(it) == array { let ctr = 0 for line in it { lttr_fmt(line) if ctr != it.len() { linebreak() } ctr += 1 } } else { [#it] } } #let lttr_defaults = ( _page: ( margin: ( top: 3cm, bottom: 3cm, left: 25mm, right: 20mm, ), ), _text: ( size: 11pt, ), settings: ( content_spacing: 10mm, justify_content: true, ), sender: ( content: none, fmt: (it) => { lttr_fmt(it.content) }, ), return_to: ( content: none, fmt: (it) => { text(size: 0.8em)[#underline({ lttr_fmt(it.content) })] }, ), remark_zone: ( content: none, fmt: (it) => { set align(it.align) text(size: 0.8em)[ #lttr_fmt(it.content) ] }, ), receiver: ( content: none, fmt: (it) => { lttr_fmt(it.content) }, spacing: 0.65em / 2, // NOTE: half the default spacing between lines ), date_place: ( date: none, place: none, ), horizontal_table: ( content: none, fmt: (header, content) => { set par(leading: 0.4em) text(size: 0.8em)[ #lttr_fmt(header) #linebreak() ] lttr_fmt(content) }, spacing: 10mm, ), title: ( content: none, spacing: 2mm, ), opening: ( content: none, spacing: 2mm, ), closing: ( content: none, spacing: 5mm, ), signature: ( content: none, spacing: 5mm, ) ) #let lttr_format_defaults = ( "DIN-5008-A": ( _page: ( paper: "a4", ), _text: ( lang: "fr", region: "CH", ), settings: ( content_spacing: 8.46mm, ), horizontal_table: ( spacing: 8.46mm, ), sender: ( position: (left: 125mm, top: 32mm), width: 75mm, ), return_to: ( position: (left: 20mm + 5mm, top: 27mm), dimensions: (height: 5mm, width: 85mm - 5mm), ), remark_zone: ( position: (left: 20mm + 5mm, top: 27mm + 5mm), dimensions: (height: 12.7mm, width: 85mm - 5mm), align: top, ), receiver: ( position: (left: 20mm + 5mm, top: 27mm + 17.7mm), dimensions: (height: 27.3mm, width: 85mm - 5mm), align: top, ), indicator_lines: ( show_puncher_mark: true, fold_marks: (87mm, 87mm+105mm), ), date_place: ( align: right, ) ), "DIN-5008-B": ( _page: ( paper: "a4", ), _text: ( lang: "FR" ), settings: ( content_spacing: 8.46mm, ), horizontal_table: ( spacing: 8.46mm, ), sender: ( position: (left: 125mm, top: 50mm), width: 75mm, ), return_to: ( // NOTE: this position overlapps with remark_zone. DIN-5008-B does // not have a dedicated return_to field. If both return_to and // remark_zone have a non-none content, then the remark_zone field // has to be recuced by return_to.dimensions.height position: (left: 20mm + 5mm, top: 45mm), dimensions: (height: 5mm, width: 85mm - 5mm), ), remark_zone: ( position: (left: 20mm + 5mm, top: 45mm), dimensions: (height: 12.7mm + 5mm, width: 85mm - 5mm), align: bottom, ), receiver: ( position: (left: 20mm + 5mm, top: 45mm + 17.7mm), dimensions: (height: 27.3mm, width: 85mm - 5mm), align: top, ), indicator_lines: ( show_puncher_mark: true, fold_marks: (105mm, 105mm + 105mm), ), date_place: ( align: right, ) ), "C5-WINDOW-LEFT": ( _page: ( paper: "a4", ), _text: ( lang: "FR", ), settings: ( content_spacing: 10mm, ), horizontal_table: ( spacing: 10mm, ), sender: ( // NOTE: position.top is the margin.top // NOTE: position.left and width are like DIN5008 position: (left: 125mm, top: 30mm), width: 75mm, ), return_to: ( position: none, ), remark_zone: ( position: none, ), receiver: ( // NOTE: I added a 5mm "padding" on the left here position: (left: 20mm + 5mm, top: 52mm), // NOTE: height = Window_height - (C5_height - Paper_height) // = 45mm - (162mm - 297mm/2) // = 31.5mm // NOTE: width = Window_width - (C5_width - Paper_width) // = 100mm - (229mm - 210mm) // = 81mm dimensions: (height: 31.5mm, width: 81mm), align: horizon, ), indicator_lines: ( fold_marks: (), show_puncher_mark: true, ), date_place: ( align: left, ) ), "C5-WINDOW-RIGHT": ( _page: ( paper: "a4", ), _text: ( lang: "FR", ), settings: ( content_spacing: 10mm, ), horizontal_table: ( spacing: 10mm, ), sender: ( position: none, width: 75mm, ), return_to: ( position: none, ), remark_zone: ( position: none, ), receiver: ( position: (left: 120mm, top: 52mm), dimensions: (height: 31.5mm, width: 80mm), align: horizon, ), indicator_lines: ( fold_marks: (), show_puncher_mark: true, ), date_place: ( align: left, ) ), ) #let lttr_indicator_lines(body) = { locate(loc => { let state = lttr_data.at(loc); if state.indicator_lines != none { if state.indicator_lines.show_puncher_mark { place( dy: 50% - 0.5 * state._page.margin.top + 0.5 * state._page.margin.bottom, dx: 0cm - state._page.margin.left + 9mm, line( length: 0.4cm, stroke: 0.5pt + rgb("#777777") ) ) } if type(state.indicator_lines.fold_marks) == array { for mark in state.indicator_lines.fold_marks { place( dy: mark - state._page.margin.top, dx: 0cm - state._page.margin.left + 9mm, line( length: 0.2cm, stroke: 0.5pt + rgb("#777777") ) ) } } } }) body } #let lttr_horizontal_table( body ) = { locate(loc => { let state = lttr_data.at(loc); if state.horizontal_table.content != none { let content = () let ctr = 0 for entry in state.horizontal_table.content { ctr += 1 content.push({ state.horizontal_table.at("fmt")( entry.first(), entry.last(), ) }) } if ctr > 0 { let column_width = 100% / ctr let columns = () while ctr > 0 { columns.push(column_width) ctr -= 1 } let tbl = table( columns: columns, inset: 0pt, stroke: if state.debug {red} else {none}, align: (left, top), ..content ) let table_rect = rect( outset: 0pt, inset: 0pt, stroke: none, tbl ) let dy = lttr_max_dy.at(loc) + state.horizontal_table.spacing place( dy: dy, { table_rect layout(size => style(styles => { let (height,) = measure( block(width: size.width, table_rect), styles ) lttr_update_max_dy(height + dy) })) } ) } } }) body } #let lttr_closing(body) = { locate(loc => { let state = lttr_data.at(loc); if state.closing.content != none { v(state.closing.spacing) state.closing.content } if state.signature.content != none { v(state.signature.spacing) state.signature.content } }) body } #let lttr_opening(body) = { locate(loc => { let state = lttr_data.at(loc); if state.opening != none { v(state.opening.spacing) state.opening.content } }) body } #let lttr_date_place(body) = { locate(loc => { let state = lttr_data.at(loc); if state.date_place != none { set align(state.date_place.align) state.date_place.place if state.date_place.place != none and state.date_place.date != none { text(", ") } state.date_place.date } }) body } #let lttr_title(body) = { locate(loc => { let state = lttr_data.at(loc); if state.title != none { v(state.title.spacing) text( weight: "bold", size: 1.0em, state.title.content ) } }) body } #let lttr_sender(body) = { locate(loc => { let state = lttr_data.at(loc); let sender_rect = rect( width: state.sender.width, inset: 0pt, outset: 0pt, stroke: if state.debug {blue} else {none}, { state.sender.at("fmt")(state.sender) } ) let sender_position = if state.sender.position != none { state.sender.position } else { (left: state._page.margin.left, top: state._page.margin.top) } let dy = sender_position.top - state._page.margin.top let dx = sender_position.left - state._page.margin.left place( dy: dy, dx: dx, sender_rect ) // TODO: add layout here style(styles => { lttr_update_max_dy(measure(sender_rect, styles).height + dy) }) }) body } #let lttr_receiver_return_to(body) = { locate(loc => { let state = lttr_data.at(loc); if state.return_to.position != none { let dy = state.return_to.position.top - state._page.margin.top let dx = state.return_to.position.left - state._page.margin.left place( dy: dy, dx: dx, rect( width: state.return_to.dimensions.width, height: 5mm, stroke: if state.debug {red} else {none}, inset: (left: 0mm, right: 0mm), outset: 0cm, { state.return_to.at("fmt")(state.return_to) } ) ) } }) body } #let lttr_receiver_remark_zone(body) = { locate(loc => { let state = lttr_data.at(loc); if state.remark_zone.position != none { let dy = state.remark_zone.position.top - state._page.margin.top let dx = state.remark_zone.position.left - state._page.margin.left place( dy: dy, dx: dx, rect( width: state.remark_zone.dimensions.width, height: state.remark_zone.dimensions.height, stroke: if state.debug {green} else {none}, inset: (left: 0mm, right: 0mm), outset: 0pt, { state.remark_zone.at("fmt")(state.remark_zone) } ) ) } }) body } #let lttr_receiver_address(body) = { locate(loc => { let state = lttr_data.at(loc); let receiver_rect = rect( width: state.receiver.dimensions.width, height: state.receiver.dimensions.height, stroke: if state.debug {purple} else {none}, inset: (left: 0mm, right: 0mm, top: 0mm), outset: 0pt, { v(state.receiver.spacing) set align(state.receiver.align) state.receiver.at("fmt")(state.receiver) }, ) let dy = state.receiver.position.top - state._page.margin.top let dx = state.receiver.position.left - state._page.margin.left place( dy: dy, dx: dx, receiver_rect, ) // TODO: add layout here style(styles => { let rect_height = measure(receiver_rect, styles).height lttr_update_max_dy(rect_height + dy) }) }) body } #let lttr_receiver(body) = { show: lttr_receiver_return_to show: lttr_receiver_remark_zone show: lttr_receiver_address body } #let lttr_content_offset(body) = { locate(loc => { let state = lttr_data.at(loc); v(lttr_max_dy.at(loc) + state.settings.content_spacing) set par(justify: state.settings.justify_content) body }) } #let lttr_preamble(body) = { show: lttr_sender show: lttr_receiver show: lttr_horizontal_table show: lttr_indicator_lines show: lttr_content_offset show: lttr_date_place show: lttr_title show: lttr_opening body } #let lttr_init( _page: (:), _text: (:), debug: false, format: "DIN-5008-A", settings: (:), indicator_lines: (:), sender: (:), return_to: (:), remark_zone: (:), receiver: (:), horizontal_table: (:), title: (:), date_place: (:), opening: (:), closing: (:), signature: (:), body, ) = { let format_defaults = lttr_format_defaults.at(format) // Takes an array of dictionaries and merges them where later dictionaries // overwrite the values of the ones before let lttr_deep_dict_merge(dictionaries) = { if dictionaries.len() == 0 { return (:) } else if dictionaries.len() == 1 { return dictionaries.first() } // helper function to deeply merge d1 and d2 (d2 overwrites d1) let deep_merge(d1, d2) = { let keys = (..d1.keys(), ..d2.keys()) for k in keys { if d1.keys().contains(k) and d2.keys().contains(k) { let d1_val = d1.at(k) let d2_val = d2.at(k) if type(d1_val) == dictionary and type(d2_val) == dictionary { // both d1 and d2 contain key k both d1.at(k) and // d2.at(k) are dictionaries, merge them d2.insert(k, deep_merge(d1_val, d2_val)) } } else if d1.keys().contains(k) { // key only exists in d1, add it to d2 d2.insert(k, d1.at(k)) } } return d2 } let result = none for dict in dictionaries { if result == none { result = dict } else { result = deep_merge(result, dict) } } return result } let merge_arg_dicts = (item_name, item) => { if item == none { none } else { lttr_deep_dict_merge(( lttr_defaults.at(item_name, default: (:)), format_defaults.at(item_name, default: (:)), if type(item) != dictionary { (content: item) } else { item } )) } } let data = ( _page: merge_arg_dicts("_page", _page), _text: merge_arg_dicts("_text", _text), closing: merge_arg_dicts("closing", closing), date_place: merge_arg_dicts("date_place", date_place), debug: debug, format: format, horizontal_table: merge_arg_dicts("horizontal_table", horizontal_table), indicator_lines: merge_arg_dicts("indicator_lines", indicator_lines), opening: merge_arg_dicts("opening", opening), receiver: merge_arg_dicts("receiver", receiver), remark_zone: merge_arg_dicts("remark_zone", remark_zone), return_to: merge_arg_dicts("return_to", return_to), sender: merge_arg_dicts("sender", sender), settings: merge_arg_dicts("settings", sender), signature: merge_arg_dicts("signature", signature), title: merge_arg_dicts("title", title), ) // NOTE: This is a special case for DIN-5008-B as described in the format // defaults if data.format == "DIN-5008-B" { if data.return_to.content != none and data.remark_zone.content != none { // we have both return_to and remark_zone, reduce the size of // remark_zone and shift it down data.remark_zone.dimensions.height = data.remark_zone.dimensions.height - data.return_to.dimensions.height data.remark_zone.position.top = data.remark_zone.position.top + data.return_to.dimensions.height } else if data.return_to.content != none { // there is no remark_zone, shift the return_to down data.return_to.position.top = data.receiver.position.top - data.return_to.dimensions.height } } // FIXME: find a better way to (not) set document attributes set page(..data._page) set text(..data._text) lttr_data.update(x => data) body } #let lttr_state() = { locate(loc => { lttr_data.at(loc); }) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-3300.typ
typst
Apache License 2.0
#let data = ( ("SQUARE APAATO", "So", 0), ("SQUARE ARUHUA", "So", 0), ("SQUARE ANPEA", "So", 0), ("SQUARE AARU", "So", 0), ("SQUARE ININGU", "So", 0), ("SQUARE INTI", "So", 0), ("SQUARE UON", "So", 0), ("SQUARE ESUKUUDO", "So", 0), ("SQUARE EEKAA", "So", 0), ("SQUARE ONSU", "So", 0), ("SQUARE OOMU", "So", 0), ("SQUARE KAIRI", "So", 0), ("SQUARE KARATTO", "So", 0), ("SQUARE KARORII", "So", 0), ("SQUARE GARON", "So", 0), ("SQUARE GANMA", "So", 0), ("SQUARE GIGA", "So", 0), ("SQUARE GINII", "So", 0), ("SQUARE KYURII", "So", 0), ("SQUARE GIRUDAA", "So", 0), ("SQUARE KIRO", "So", 0), ("SQUARE KIROGURAMU", "So", 0), ("SQUARE KIROMEETORU", "So", 0), ("SQUARE KIROWATTO", "So", 0), ("SQUARE GURAMU", "So", 0), ("SQUARE GURAMUTON", "So", 0), ("SQUARE KURUZEIRO", "So", 0), ("SQUARE KUROONE", "So", 0), ("SQUARE KEESU", "So", 0), ("SQUARE KORUNA", "So", 0), ("SQUARE KOOPO", "So", 0), ("SQUARE SAIKURU", "So", 0), ("SQUARE SANTIIMU", "So", 0), ("SQUARE SIRINGU", "So", 0), ("SQUARE SENTI", "So", 0), ("SQUARE SENTO", "So", 0), ("SQUARE DAASU", "So", 0), ("SQUARE DESI", "So", 0), ("SQUARE DORU", "So", 0), ("SQUARE TON", "So", 0), ("SQUARE NANO", "So", 0), ("SQUARE NOTTO", "So", 0), ("SQUARE HAITU", "So", 0), ("SQUARE PAASENTO", "So", 0), ("SQUARE PAATU", "So", 0), ("SQUARE BAARERU", "So", 0), ("SQUARE PIASUTORU", "So", 0), ("SQUARE PIKURU", "So", 0), ("SQUARE PIKO", "So", 0), ("SQUARE BIRU", "So", 0), ("SQUARE HUARADDO", "So", 0), ("SQUARE HUIITO", "So", 0), ("SQUARE BUSSYERU", "So", 0), ("SQUARE HURAN", "So", 0), ("SQUARE HEKUTAARU", "So", 0), ("SQUARE PESO", "So", 0), ("SQUARE PENIHI", "So", 0), ("SQUARE HERUTU", "So", 0), ("SQUARE PENSU", "So", 0), ("SQUARE PEEZI", "So", 0), ("SQUARE BEETA", "So", 0), ("SQUARE POINTO", "So", 0), ("SQUARE BORUTO", "So", 0), ("SQUARE HON", "So", 0), ("SQUARE PONDO", "So", 0), ("SQUARE HOORU", "So", 0), ("SQUARE HOON", "So", 0), ("SQUARE MAIKURO", "So", 0), ("SQUARE MAIRU", "So", 0), ("SQUARE MAHHA", "So", 0), ("SQUARE MARUKU", "So", 0), ("SQUARE MANSYON", "So", 0), ("SQUARE MIKURON", "So", 0), ("SQUARE MIRI", "So", 0), ("SQUARE MIRIBAARU", "So", 0), ("SQUARE MEGA", "So", 0), ("SQUARE MEGATON", "So", 0), ("SQUARE MEETORU", "So", 0), ("SQUARE YAADO", "So", 0), ("SQUARE YAARU", "So", 0), ("SQUARE YUAN", "So", 0), ("SQUARE RITTORU", "So", 0), ("SQUARE RIRA", "So", 0), ("SQUARE RUPII", "So", 0), ("SQUARE RUUBURU", "So", 0), ("SQUARE REMU", "So", 0), ("SQUARE RENTOGEN", "So", 0), ("SQUARE WATTO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ZERO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ONE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THREE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOUR", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIVE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIX", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHT", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR ELEVEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWELVE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR THIRTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FOURTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR FIFTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SIXTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR SEVENTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR EIGHTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR NINETEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-ONE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-TWO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-THREE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR HOUR TWENTY-FOUR", "So", 0), ("SQUARE HPA", "So", 0), ("SQUARE DA", "So", 0), ("SQUARE AU", "So", 0), ("SQUARE BAR", "So", 0), ("SQUARE OV", "So", 0), ("SQUARE PC", "So", 0), ("SQUARE DM", "So", 0), ("SQUARE DM SQUARED", "So", 0), ("SQUARE DM CUBED", "So", 0), ("SQUARE IU", "So", 0), ("SQUARE ERA NAME HEISEI", "So", 0), ("SQUARE ERA NAME SYOUWA", "So", 0), ("SQUARE ERA NAME TAISYOU", "So", 0), ("SQUARE ERA NAME MEIZI", "So", 0), ("SQUARE CORPORATION", "So", 0), ("SQUARE PA AMPS", "So", 0), ("SQUARE NA", "So", 0), ("SQUARE MU A", "So", 0), ("SQUARE MA", "So", 0), ("SQUARE KA", "So", 0), ("SQUARE KB", "So", 0), ("SQUARE MB", "So", 0), ("SQUARE GB", "So", 0), ("SQUARE CAL", "So", 0), ("SQUARE KCAL", "So", 0), ("SQUARE PF", "So", 0), ("SQUARE NF", "So", 0), ("SQUARE MU F", "So", 0), ("SQUARE MU G", "So", 0), ("SQUARE MG", "So", 0), ("SQUARE KG", "So", 0), ("SQUARE HZ", "So", 0), ("SQUARE KHZ", "So", 0), ("SQUARE MHZ", "So", 0), ("SQUARE GHZ", "So", 0), ("SQUARE THZ", "So", 0), ("SQUARE MU L", "So", 0), ("SQUARE ML", "So", 0), ("SQUARE DL", "So", 0), ("SQUARE KL", "So", 0), ("SQUARE FM", "So", 0), ("SQUARE NM", "So", 0), ("SQUARE MU M", "So", 0), ("SQUARE MM", "So", 0), ("SQUARE CM", "So", 0), ("SQUARE KM", "So", 0), ("SQUARE MM SQUARED", "So", 0), ("SQUARE CM SQUARED", "So", 0), ("SQUARE M SQUARED", "So", 0), ("SQUARE KM SQUARED", "So", 0), ("SQUARE MM CUBED", "So", 0), ("SQUARE CM CUBED", "So", 0), ("SQUARE M CUBED", "So", 0), ("SQUARE KM CUBED", "So", 0), ("SQUARE M OVER S", "So", 0), ("SQUARE M OVER S SQUARED", "So", 0), ("SQUARE PA", "So", 0), ("SQUARE KPA", "So", 0), ("SQUARE MPA", "So", 0), ("SQUARE GPA", "So", 0), ("SQUARE RAD", "So", 0), ("SQUARE RAD OVER S", "So", 0), ("SQUARE RAD OVER S SQUARED", "So", 0), ("SQUARE PS", "So", 0), ("SQUARE NS", "So", 0), ("SQUARE MU S", "So", 0), ("SQUARE MS", "So", 0), ("SQUARE PV", "So", 0), ("SQUARE NV", "So", 0), ("SQUARE MU V", "So", 0), ("SQUARE MV", "So", 0), ("SQUARE KV", "So", 0), ("SQUARE MV MEGA", "So", 0), ("SQUARE PW", "So", 0), ("SQUARE NW", "So", 0), ("SQUARE MU W", "So", 0), ("SQUARE MW", "So", 0), ("SQUARE KW", "So", 0), ("SQUARE MW MEGA", "So", 0), ("SQUARE K OHM", "So", 0), ("SQUARE M OHM", "So", 0), ("SQUARE AM", "So", 0), ("SQUARE BQ", "So", 0), ("SQUARE CC", "So", 0), ("SQUARE CD", "So", 0), ("SQUARE C OVER KG", "So", 0), ("SQUARE CO", "So", 0), ("SQUARE DB", "So", 0), ("SQUARE GY", "So", 0), ("SQUARE HA", "So", 0), ("SQUARE HP", "So", 0), ("SQUARE IN", "So", 0), ("SQUARE KK", "So", 0), ("SQUARE KM CAPITAL", "So", 0), ("SQUARE KT", "So", 0), ("SQUARE LM", "So", 0), ("SQUARE LN", "So", 0), ("SQUARE LOG", "So", 0), ("SQUARE LX", "So", 0), ("SQUARE MB SMALL", "So", 0), ("SQUARE MIL", "So", 0), ("SQUARE MOL", "So", 0), ("SQUARE PH", "So", 0), ("SQUARE PM", "So", 0), ("SQUARE PPM", "So", 0), ("SQUARE PR", "So", 0), ("SQUARE SR", "So", 0), ("SQUARE SV", "So", 0), ("SQUARE WB", "So", 0), ("SQUARE V OVER M", "So", 0), ("SQUARE A OVER M", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ONE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THREE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOUR", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIVE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIX", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHT", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY ELEVEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWELVE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FOURTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY FIFTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SIXTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY SEVENTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY EIGHTEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY NINETEEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-ONE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-TWO", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-THREE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FOUR", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-FIVE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SIX", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-SEVEN", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-EIGHT", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY TWENTY-NINE", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY", "So", 0), ("IDEOGRAPHIC TELEGRAPH SYMBOL FOR DAY THIRTY-ONE", "So", 0), ("SQUARE GAL", "So", 0), )
https://github.com/nobel-sh/typst-report
https://raw.githubusercontent.com/nobel-sh/typst-report/main/assignment.typ
typst
#let spaced_block(content,space: 2em) = { block(content) v(space) } #let image_block(path, width, margin: 2em) = { v(margin) block(image(path, width: width)) v(margin) } #let render_university_info(info) = { let university = info.university block(university.name) block(university.department) block(university.location) image_block(university.logo, 6cm, margin:1.5em) } #let render_course_info(info)= { let course = info.course let activity = info.activity block(course.code) block(course.title) if "description" in activity { block(activity.title) spaced_block(["#activity.description"]) } else { spaced_block(activity.title) } } #let render_submission_info(info, current_date) = { let student = info.student let tutor = info.tutor block("Submitted by") spaced_block([#student.name (#student.roll_no)]) block("Submitted to") block(tutor.name) if "post" in tutor { block(tutor.post) } spaced_block(tutor.department, space: 1.5em) block("Submission Date") spaced_block(current_date) } #let assignment(body) = { let info = toml("config.toml") let current_date = if "date" in info { info.date } else { datetime.today().display("[month repr:long] [day], [year]") } set document( author: info.student.name, title: info.activity.title, ) set heading(numbering: "1.") // Front page set align(center) set text(weight: "bold", size: 14pt) render_university_info(info) render_course_info(info) render_submission_info(info, current_date) pagebreak() // Table of Content set text(weight: "regular") show outline.entry.where(level: 1): body => { v(8pt) strong(body) } set outline( title:{ text("Table of Contents") v(1em) }) set text(size: 12pt) outline(depth:3, indent: 2em, fill: repeat([-])) pagebreak() body } // Misc items #let note(body) = { block( fill: luma(240), inset: 8pt, radius: 4pt, [*Note:* #body] ) } #let todo(body) = { text( fill: red, weight: "bold", [TODO: #body] ) }
https://github.com/mintjesba/JIE-Typst-Template
https://raw.githubusercontent.com/mintjesba/JIE-Typst-Template/main/README.md
markdown
# JIE-Typst-Template An UNOFFICIAL [Typst](https://typst.app/) template for Journal of Industrial Ecology submissions. **Not authorised by JIE** but follows the Word template. ## Instructions for use - Copy the files to your own device or folder. - Replace the arguments by the relevant information. Keep them in the correct format (i.e. in content blocks `[]` for most, arrays of content blocks `()` for some). - To see a mock-up of the submission in article format change the `show-as-article` variable to `true`. ## Fonts This template uses three fonts (one for the submission style, two for the article style) that are included in the Typst web app. These can also be downloaded for free. 1. [Liberation Serif](https://www.dafont.com/liberation-serif.font) for the submission style. 2. [Noto Sans](https://fonts.google.com/noto/specimen/Noto+Sans) for the article style main text and headers. 3. [DM Sans](https://fonts.google.com/specimen/DM+Sans) for some article style headers.
https://github.com/GYPpro/Java-coures-report
https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/.VSCodeCounter/2023-12-15_05-15-05/diff-details.md
markdown
# Diff Details Date : 2023-12-15 05:15:05 Directory d:\\Desktop\\Document\\Coding\\JAVA\\Rep\\Java-coures-report Total : 62 files, 4962 codes, 13 comments, 1260 blanks, all 6235 lines [Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details ## Files | filename | language | code | comment | blank | total | | :--- | :--- | ---: | ---: | ---: | ---: | | [Report/0.typ](/Report/0.typ) | Typst | 48 | 4 | 9 | 61 | | [Report/1.typ](/Report/1.typ) | Typst | 84 | 2 | 23 | 109 | | [Report/10.typ](/Report/10.typ) | Typst | 550 | 4 | 155 | 709 | | [Report/11.typ](/Report/11.typ) | Typst | 1,068 | 17 | 150 | 1,235 | | [Report/2.typ](/Report/2.typ) | Typst | 116 | 2 | 23 | 141 | | [Report/3.typ](/Report/3.typ) | Typst | 306 | 2 | 49 | 357 | | [Report/4.typ](/Report/4.typ) | Typst | 172 | 5 | 38 | 215 | | [Report/5.typ](/Report/5.typ) | Typst | 133 | 2 | 39 | 174 | | [Report/6.typ](/Report/6.typ) | Typst | 736 | 2 | 123 | 861 | | [Report/7.typ](/Report/7.typ) | Typst | 210 | 13 | 45 | 268 | | [Report/8.typ](/Report/8.typ) | Typst | 209 | 5 | 49 | 263 | | [Report/9.typ](/Report/9.typ) | Typst | 384 | 3 | 82 | 469 | | [Report/Java语言 实验报告模板 2023-10-8-20231214155905.typ](/Report/Java%E8%AF%AD%E8%A8%80%20%E5%AE%9E%E9%AA%8C%E6%8A%A5%E5%91%8A%E6%A8%A1%E6%9D%BF%202023-10-8-20231214155905.typ) | Typst | 497 | 1 | 263 | 761 | | [Report/最小费用最大流问题-20231215032417.typ](/Report/%E6%9C%80%E5%B0%8F%E8%B4%B9%E7%94%A8%E6%9C%80%E5%A4%A7%E6%B5%81%E9%97%AE%E9%A2%98-20231215032417.typ) | Typst | 323 | 1 | 205 | 529 | | [rubbish/myIO.java](/rubbish/myIO.java) | Java | 3 | 0 | 2 | 5 | | [sis10/Test.java](/sis10/Test.java) | Java | 18 | 0 | 5 | 23 | | [sis10/myLinearEntire.java](/sis10/myLinearEntire.java) | Java | 41 | 0 | 18 | 59 | | [sis10/myLinearLib.java](/sis10/myLinearLib.java) | Java | 197 | 34 | 13 | 244 | | [sis10/myLinearSpace.java](/sis10/myLinearSpace.java) | Java | 111 | 4 | 18 | 133 | | [sis10/myMatrix.java](/sis10/myMatrix.java) | Java | 267 | 4 | 24 | 295 | | [sis10/myPolynomial.java](/sis10/myPolynomial.java) | Java | 131 | 4 | 21 | 156 | | [sis10/myRealNum.java](/sis10/myRealNum.java) | Java | 58 | 3 | 15 | 76 | | [sis2/Test.java](/sis2/Test.java) | Java | 0 | -15 | -1 | -16 | | [sis4/regularExp.java](/sis4/regularExp.java) | Java | 0 | 0 | 1 | 1 | | [sis6/Test.java](/sis6/Test.java) | Java | -24 | -5 | -5 | -34 | | [sis6/segTree.h](/sis6/segTree.h) | C++ | 102 | 12 | 10 | 124 | | [sis6/segTree.java](/sis6/segTree.java) | Java | -100 | -3 | -14 | -117 | | [sis7/Test.java](/sis7/Test.java) | Java | 24 | 5 | 5 | 34 | | [sis7/maxFlow.java](/sis7/maxFlow.java) | Java | -96 | 0 | -13 | -109 | | [sis7/minCost.java](/sis7/minCost.java) | Java | -139 | 0 | -19 | -158 | | [sis7/segTree.java](/sis7/segTree.java) | Java | 100 | 3 | 14 | 117 | | [sis7/solution.java](/sis7/solution.java) | Java | -26 | -1 | -3 | -30 | | [sis8/Bed.java](/sis8/Bed.java) | Java | -13 | 0 | -4 | -17 | | [sis8/City.java](/sis8/City.java) | Java | -21 | 0 | -7 | -28 | | [sis8/Constants.java](/sis8/Constants.java) | Java | -10 | 0 | -4 | -14 | | [sis8/Hospital.java](/sis8/Hospital.java) | Java | -49 | 0 | -20 | -69 | | [sis8/Main.java](/sis8/Main.java) | Java | -32 | 0 | -6 | -38 | | [sis8/MoveTarget.java](/sis8/MoveTarget.java) | Java | -28 | 0 | -9 | -37 | | [sis8/MyPanel.java](/sis8/MyPanel.java) | Java | -78 | -2 | -15 | -95 | | [sis8/Person.java](/sis8/Person.java) | Java | -145 | -6 | -39 | -190 | | [sis8/PersonPool.java](/sis8/PersonPool.java) | Java | -38 | -10 | -9 | -57 | | [sis8/Point.java](/sis8/Point.java) | Java | -21 | 0 | -7 | -28 | | [sis8/maxFlow.java](/sis8/maxFlow.java) | Java | 96 | 0 | 13 | 109 | | [sis8/minCost.java](/sis8/minCost.java) | Java | 139 | 0 | 19 | 158 | | [sis8/solution.java](/sis8/solution.java) | Java | 26 | 1 | 3 | 30 | | [sis9/Bed.java](/sis9/Bed.java) | Java | 13 | 0 | 4 | 17 | | [sis9/City.java](/sis9/City.java) | Java | 21 | 0 | 7 | 28 | | [sis9/Constants.java](/sis9/Constants.java) | Java | 10 | 0 | 4 | 14 | | [sis9/Hospital.java](/sis9/Hospital.java) | Java | 49 | 0 | 19 | 68 | | [sis9/Main.java](/sis9/Main.java) | Java | 32 | 0 | 6 | 38 | | [sis9/MoveTarget.java](/sis9/MoveTarget.java) | Java | 28 | 0 | 9 | 37 | | [sis9/MyPanel.java](/sis9/MyPanel.java) | Java | 78 | 2 | 15 | 95 | | [sis9/Person.java](/sis9/Person.java) | Java | 145 | 0 | 36 | 181 | | [sis9/PersonPool.java](/sis9/PersonPool.java) | Java | 38 | 0 | 9 | 47 | | [sis9/Point.java](/sis9/Point.java) | Java | 21 | 0 | 7 | 28 | | [sis9/Test.java](/sis9/Test.java) | Java | -12 | -34 | -5 | -51 | | [sis9/myLinearEntire.java](/sis9/myLinearEntire.java) | Java | -41 | 0 | -18 | -59 | | [sis9/myLinearLib.java](/sis9/myLinearLib.java) | Java | -189 | -34 | -14 | -237 | | [sis9/myLinearSpace.java](/sis9/myLinearSpace.java) | Java | -111 | -4 | -18 | -133 | | [sis9/myMatrix.java](/sis9/myMatrix.java) | Java | -267 | -4 | -24 | -295 | | [sis9/myPolynomial.java](/sis9/myPolynomial.java) | Java | -128 | -4 | -21 | -153 | | [sis9/myRealNum.java](/sis9/myRealNum.java) | Java | -54 | 0 | -15 | -69 | [Summary](results.md) / [Details](details.md) / [Diff Summary](diff.md) / Diff Details
https://github.com/0xmycf/typst-template
https://raw.githubusercontent.com/0xmycf/typst-template/main/readme.md
markdown
# Template for Typst documents [Learn more about Typst](https://github.com/typst/typst) Usage: 1. Download the Prelude file into your project directory or add a git submodule to it. ```curl -o Prelude.typ https://raw.githubusercontent.com/0xmycf/typst-template/main/Prelude.typ``` 2. Create your main File and import the Prelude ```typ #import "./Prelude.typ": applyStyle, citep ``` 3. Configure the Document: ```typ #show: doc => applyStyle( author: "<NAME>" // def is mycf , title: "Title of your Document" // def is Template , bibPath: "Path to your bibliography" // def ./bib.bib , lang: "en" // def is de , doc ) ``` ## Notes - Currently I only support one author. Adding more authors should be straight forward (switch a String to a List). - `citep` is an inline citation function like citep in latex. Its defined as follows: ```#let citep(..keys) = cite(..keys, brackets: false)``` - test.typ shows a test file, test.pdf is the corresponding rendered pdf file. - The TOC is broken. I don't know if this is an typst issue or how i configured it. The page counter displays the wrong numbers for the toc and bibliography. - font families that are used are (in that order): ```typ font: ( "KPRoman" , "EBGaramond" , "Courier New" , "Times New Roman" , "FiraCode" , "Noto Sans CJK TC" , "Adobe Kaiti Std" ) ```
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/super_script/super_script_updated.typ
typst
First#super[updated text] Normal text Second#super[super text]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-10B40.typ
typst
Apache License 2.0
#let data = ( ("INSCRIPTIONAL PARTHIAN LETTER ALEPH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER BETH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER GIMEL", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER DALETH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER HE", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER WAW", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER ZAYIN", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER HETH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER TETH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER YODH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER KAPH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER LAMEDH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER MEM", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER NUN", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER SAMEKH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER AYIN", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER PE", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER SADHE", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER QOPH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER RESH", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER SHIN", "Lo", 0), ("INSCRIPTIONAL PARTHIAN LETTER TAW", "Lo", 0), (), (), ("INSCRIPTIONAL PARTHIAN NUMBER ONE", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER TWO", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER THREE", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER FOUR", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER TEN", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER TWENTY", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER ONE HUNDRED", "No", 0), ("INSCRIPTIONAL PARTHIAN NUMBER ONE THOUSAND", "No", 0), )
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/049%20-%20The%20Brothers'%20War/008_Chapter%204%3A%20The%20Dark.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Chapter 4: The Dark", set_name: "The Brothers' War", story_date: datetime(day: 25, month: 10, year: 2022), author: "<NAME>", doc ) #emph[Bathed in hallowed light, the infidels looked upon the impurities of their souls and despaired.] #emph[—The Book of Tal] #emph[Dearest Elspeth,] #emph[It is quite natural to forget. Survival lies in the forgetting. To remember all things in perfect order requires so much attention and energy. Too much. That is the object of this missive to you—to alleviate the burden of either forgetting or remembering, as each robs you of the benefits of the other. Instead, let these words remain close to your heart.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Sleep had not come easy to Elspeth since she arrived on Dominaria almost a week ago. She had rested, taken time to bathe in this lonely tower's facilities, and meditated by reciting her old knightly vows. But not even the steady patter of rain could usher her through the gate of dreams. To fill the listless hours between dusk and dawn, she'd drill in the grand hall of the tower, moving through the battle stances she'd learned as a squire in Valeron. When she'd first arrived on the plane, the hall was empty, allowing her all the space she wanted to swing her sword. But in a matter of days, the hall had become increasingly crowded with Saheeli's metal soldiers. Elspeth accepted command of this mechanical garrison at Teferi's request. It made sense—she had the most battlefield experience of any Planeswalker in the tower. Still, these constructs were poor substitutes for real knights. What did they know of wounds suffered in another's defense, of prayers uttered on another's behalf to~ well, #emph[some] divine being? Nothing. Steel only knew steel. Elspeth positioned the spade-shaped blade of one of the soldiers, a construct that resembled an armored, bipedal beetle. Then she settled into first guard, holding a buckler she'd wrenched off one of the soldiers' arms. #emph[First guard to second. ] She swung a backhand sweep from the left, her blade clanging against her silent adversary, then returning up to her temple. #emph[Second guard to third. ] Elspeth swung again, bringing her sword back down, the blade so close to her ear that she heard it sing. #emph[Third guard to fourth] . Arcing her sword high once more, she tapped the metal soldier's head. #emph[Fourth guard to fifth. ] Finally, she brought her sword down in a hard chop, sweeping the point of her blade behind her. #emph[Acceptable. Now do it again.] One~ two~ three~ four~ five. #emph[Again. Faster.] One, two, three, four, five. #emph[Not fast enough! Do it again!] Onetwothree— Elspeth stumbled, her sword falling from her grasp and clattering onto the floor. Exasperated, she threw the buckler as hard as she could across the room. There was once a time when she didn't have to think about #emph[how] to fight. The motions were grafted onto her muscles, engraved into her bones. No extra thought necessary, no hesitation conceded. But after all her experiences on New Capenna, her movements had felt sluggish, her sword arm shaky. "Your trinket," said a soaked Wrenn, stepping in from the rain. Seven, the dryad's partner tree, also dripping wet, held Elspeth's shield out for her. "Thank you," Elspeth said curtly. She took the buckler and retrieved her sword, then resumed her stance opposite the metal soldier to start the sequence again. Wrenn hovered, watching her. "Is there something you need?" Elspeth asked. "You inhabit two melodies. How is this possible?" "What do you mean?" "Every being is part of a song," said Wrenn. "A melody that contributes to the whole. But you—there are two melodies in you. One is a single note, constant and unerring. The other is cleft, an aria throttled midway." "I~" she began. "You must be mistaken." "There is no mistake. It is as if you live two separate lives. One in light, one in shadow." "You're wrong," snapped Elspeth, slamming her sword back into its scabbard. "Very well," Wrenn said, Seven obliging by stepping away to give Elspeth space. Elspeth grimaced. She hadn't meant to be so short, but she disliked the way the dryad proclaimed things about her, as if a handful of days was enough to dissect her soul. "Wrenn, forgive me. I—" "Hold," said Wrenn. "There's a disturbance in the rain's rhythm. Someone is outside." Elspeth unsheathed her sword and approached the massive entrance at the front of the tower. She rued the existence of such an open throughway into the tower's interior. A drawbridge would have been tactically superior. A barbican with a moat even better still. Anything to bar the way of an advancing army. "Can you tell how many?" Elspeth asked. "Two. Human in size." Two people was no invasion force. Nevertheless, Elspeth erred on the side of vigilance. "Wake the others, Wrenn. I'll investigate." "We will go out together. I suspect the noise will act as a suitable alarm." Elspeth and Wrenn marched into the rain past the courtyard, down the shallow scalloped stairs and onto the stone pathway which had been reclaimed by the grass and dirt. "Show yourself!" Elspeth yelled. "Who is out there?" No answer. If there was danger, Elspeth didn't want to take any chances. "Stay close to me, Wrenn," said Elspeth, casting a light spell onto her shield. Then, with the tip of her sword, she scratched a circle around Wrenn and herself, speaking a word of power. At the first sign of aggression, she could empower the circle to ward against any hostile magic. She shined her shield out into the darkness, revealing two figures approaching. They stepped forward without weapons drawn, without a threatening gait. Not only that, but Elspeth could feel the presence of magic—evidenced by the faint green glow surrounding the figures—as well as the subtle tug of Planeswalker sparks. But were they friends or foes? Elspeth held her sword fast. She'd be ready either way. When the figures were only a few feet from the circle, one of them—a woman with fiery red hair—raised her hand and called out: "Are you Elspeth?" #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Solid. Constant. Loyal. Commitment in a squire is commendable, especially when skill is lacking. More than once, you chided Aran on his handling of a blade. You knew that he could never be a true knight of Bant. Strong of arm, good for a few well-placed sword blows in an arena. But a member of the Sigiled caste? He'd never be worthy.] #emph[You let him take to the battlefield anyway. No wonder he fell, the boy playing at being a man. When you brought him back with your healing magic, he looked upon you as a hidden goddess. ] You've given us hope#emph[, he told you when you visited his recovery bed. ] I trust you#emph[. And why not? Mentors do not forsake their charges when they need guidance the most.] #emph[But you did. You cast down your sword, discarded your armor, denied your duty. These days, he spends his mornings hobbling down the pretty garden paths of the monastery he serves at. The pain that racks his body is nothing compared to the emptiness in his soul. He has finally learned your true lesson: ] Do not hope. It is not for you. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) <NAME> and <NAME> walked into the light. Two more people on the list of those who knew more about Elspeth than she did about them, thanks to Ajani. She and Wrenn welcomed them into the tower, allowing them to dry off and get their bearings. To their credit, they were kind, exuding as much warmth as anyone had ever shown her. But they were not her friends, as much as they seemed to desire it. Perhaps in time, but that time had not yet come. So, Elspeth smiled. She smiled, said nothing, and after handing them off to a bleary-eyed Kaya for a debriefing session, didn't look back to wave goodbye. She had her duties, after all, which didn't include sitting in meetings sipping tea. As she exited the tower, it was abuzz with activity, much of it localized to the grand hall where a team of servant automatons shined and polished the ranks of mechanical warriors. Outside, the downpour from earlier had relented enough for Elspeth to journey to the watchtowers located along the perimeter of the vale, the remnants of an ancient defense grid. She'd been carrying out upgrades over the past few days on behalf of Saheeli, who was happy to have the extra help so she could concentrate on working with Teferi, Kaya, and the Temporal Anchor. The job suited Elspeth just fine. Being away from the noises and discussions at the tower let her ruminate upon everything that had happened to her in short succession—clawing her way up from Theros's Underworld, finding her home plane, losing Ajani. No. Not simply losing him. #emph[He's one of them—a Phyrexian] , Teferi had said. #emph[I'm sorry.] Pushing the thought from her mind, Elspeth slung her sack over her shoulder and scaled the rocky outcropping at the foot of the watchtower. She rested briefly when she reached the stone rungs carved into the side of the tower itself, then climbed all the way up and over the railing onto a small ledge at the very top. At the center of the covered platform were the remnants of a turret that once fired harpoon-like projectiles at any intruders within range. Now only its base remained, a heap of crumbling stone. Elspeth pulled a steel-clad cylinder from her sack, then turned to give a couple of swift kicks to the old turret, toppling it easily. She set Saheeli's cylinder in its place and inserted a small yellow crystal into a depression on its top. In a matter of moments, the cylinder rolled over of its own accord and unfolded itself twice over, forming a tripod base and a short barrel from which bolts of energy could discharge. "That's it," she said to herself, and sat back against the wall of the turret chamber. She closed her eyes, breathed in the cold air, and cleared her mind. Out of habit, she began to recite the Prayer of Asha, Bant's guardian angel. "Stray not into sin," Elspeth began. Then she stopped. No matter how hard she practiced, no matter how many mantras Elspeth recited, Asha had no obligation to heed her. Elspeth had thrown away her oath when she deserted Alara. Then what of her other patron, Heliod? A petty tyrant, a malefactor and murderer unworthy of her devotion, now deservedly chained to a rock in Theros's Underworld. Other gods waited in the wings—Serra right here on Dominaria, to name one—all promising favor for faith. And that was the problem. #emph[What faith do I have to give? Everything I love is gone. Everyone gone. Nothing to believe in.] Then she remembered that wasn't altogether true. There were some left. Koth was alive. Vivien had proven herself a true friend. And then there was Giada. She wondered if Giada could see her now, somehow. If there was any chance~ "You told me that I had everything I ever needed," Elspeth said quietly. "But the Phyrexians—all they do is take. Take, and twist, and destroy until there's nothing left of you but hate and despair. And I hate them so much for what they did to Ajani. You said my failures don't define me, but when I lay my head down to sleep, all I see are those I wasn't able to protect." If Giada heard her, she didn't answer. Elspeth didn't expect she would. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[How much would you give up for love? Ask Daxos of Meletis, as he has given up everything. Who he was, what he stood for, that which he adored—none of these are within his grasp any longer. For him, there is only Heliod, his fallen lord whose punishment did not relieve Daxos of his duty. By day, he is forced to carry out the sun's will, his restored life an eternal yoke. But at night, in his dreams, he wanders unshackled, calling out your name into Erebos's infinite meadows of six-petaled asphodel made of the sharpest glass. As the edges slice his legs, causing them to weep blood, he pauses to feel the pain, for in his waking life, he feels nothing at all.] #emph[Once a moon, his mind is further freed to traverse deeper into Kruphix's realm. And what do his oracle eyes show him? They bring him to you—a facsimile to be sure, but real enough for Daxos—standing atop the multi-headed corpse of Polukranos, the World Eater, its black blood still fresh upon your hands.] #emph["Why do ] you#emph[ deserve a life without suffering?" he demands to know. You answer by mocking his tears, then thrust your blade through his chest, into his heart.] #emph[Daxos wakes up soon after and prepares for the dawn.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The rain returned just as Elspeth arrived back at the tower. She made her way past the glares of silent metal warriors back to her room but stopped short when she heard voices coming from the corridor outside her door. Peering around the corner, she recognized two people seated on the hallway floor. Chandra. Jodah. A jug of wine between them. "She was so mad," said Chandra. "Threatened to drown me! I didn't even burn the whole forest down! Just one teensy-weensy part of it. I mean, trees grow back~ eventually. Oh, and don't tell Nissa any of this." "Drowning. She stole that threat from me," said Jodah. "Ah, Jaya. Always good at destroying. Not quite as adept at creation." He took a long drink from the jug. "Heavens, you didn't taste her cooking, did you?" "Ugh." Chandra yanked the jug from Jodah and gulped down several mouthfuls. "Don't get me started on the quiche." Jodah burst out laughing. "She made the quiche? #emph[Again?!] " "After that, eggs were forbidden within five miles of Keral Keep. I'm not kidding—we paid a priest from Zinara to cast a ward to keep chickens away from the place." "Let me have one turn on Saheeli's time machine, and I'd go back~" An abrupt sullenness gripped him, and he remained silent for a while before speaking again. "I'd go back and eat the whole damn thing." Elspeth watched as Chandra placed her arm around Jodah's shoulder and held him tight, futilely attempting to prevent her own tears from flowing. It wasn't necessary to know who this Jaya person was to appreciate what she meant to Chandra and Jodah. The closest of friends. Now, while they were distracted, Elspeth made her move. She hoped to appear in a flash, walk by, get to her door, and disappear behind it before Chandra or Jodah could realize she was there. Such a silly expectation. "Elspeth!" Chandra called out, wiping the last of her tears on her sleeve. "Hey, care to join us? Believe me, you'd be doing us a favor." Elspeth turned away from the door handle and mustered a half-smile. "No thank you. I need to study the area map, make sure that everything's accounted for." "Study?" asked Chandra. "What are you talking about?" "Elspeth has been developing defensive actions in case we get attacked," said Jodah. "It's quite a bold strategy, if I do say so myself." Bold? She wasn't so sure. #emph[Desperate] seemed more accurate. In addition to setting up the watchtowers, she'd been working with Jodah, Kaya, and Saheeli on measures to take in the event of an assault on the tower. It would happen eventually—that was certain. So, it was imperative to have a plan in place. Even a plan that had a remote chance of succeeding was better than having none. "Thanks." She pressed down on the latch and felt the catch on her door give way. "Anyway, I'm sorry to interrupt." "Wait," said Jodah, suddenly serious. "I know things have been~ odd for you here." He motioned to the empty space on the opposite side of the hallway. "You're among friends. Please." There was something about Jodah that she couldn't deny—a strange familiarity that she couldn't peg but nevertheless pulled at her. Perhaps it was as simple as his kindness to her when she arrived at the tower, the mere act of telling her that she was welcome no matter what, that whatever difficulties she was having, she had the space to deal with them as she needed. For that, Elspeth could relent. She pulled her door shut and sat down on the floor across from him. "I'm sorry about your friend," she said. "With all this madness happening, it must be difficult to mourn." "We're not mourning," said Chandra, offering Elspeth some wine. "We're celebrating who she was. That's the way Jaya would have wanted it." Elspeth pushed the jug away. "I didn't know her." "Then tell us about someone you did know," Chandra said. "Someone gone too soon." Elspeth thought about the names. There were many. Some she couldn't bear to consider dead. Others whose fate she didn't know. And still others in the murky in-between. One name emerged from the recesses of her mind, one she hadn't uttered since before Heliod struck her down. "I knew a man," she said. "An artificer from Urborg who fought beside me on New Phyrexia. He was exasperating and pretentious." She couldn't help but smile when she thought of him. "But he was also brilliant and brave and loyal—the kind of person who would venture across planes on the shoddiest of information because he thought his friends were in trouble." "Venser," said Jodah, taking the wine and gulping some down. "You knew him?" "Long ago, when he was very young and I was~ somewhat younger. I'm ashamed to say that I punched him in the face for circumstances that weren't his fault. I told him I was sorry, but that didn't make it right. I wish he were here to tell his idiotic jokes. I'd even pretend to laugh." "You'd think after decades of fighting~ so much death~ I'd be used to loss," said Elspeth. "But I can't escape the names of those who fell to save me. Of those whose blood is on my hands because of my failure. Their ghosts haunt my dreams." "Well, it's been centuries for me, and I'm only barely hanging on." "Centuries?" "Did no one?~" Jodah straightened himself up and cleared his throat. "You are in the presence of a four-thousand-year-old man. I know, I know—I don't look a day over twenty-five hundred." Twenty-five hundred? He didn't look older than twenty-five! "How is this possible?" "Oh, you know—the usual. A very, very, very long story that we don't have time for and that I don't have the patience to tell." Jodah looked at her wistfully. "In my time, I've lost people I've cherished. So many now. Like you, I can close my eyes and still see them." "So, it doesn't get easier." "No," he said. "Not if you let yourself love." Chandra wrested the wine jug away from Jodah and raised it. "This is a celebration, right? So, we toast! To Venser! To Jaya! To Gideon and~" Her mouth hung open with the final name, one that Elspeth didn't even have to guess. #emph[Ajani.] "It's okay," said Elspeth. "You can say it." "No. No, it's not," said Chandra. "We're going to save him. And after we do, we're going to torch every single one of those Phyrexian bastards on any plane we find them on. You have my word on that." Elspeth nodded and took the wine jug from Chandra. "To Venser, Jaya, and Gideon. To the ones we've lost and to the courageous yet to fall. Until all have found their place." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Can constructs dream? Calix, if he knew the word "dream," would tell you that he can. But what does the marionette dream of when his strings are cut, when the hands that direct his actions are taken away? The answer is simple. He dreams about his quarry dictated by Klothys, his life consumed with the pursuit of <NAME>. Plane to plane. Haunt to haunt. He will never stop chasing you—not when he is awake, not when he is asleep.] #emph[You see, Calix must sleep to regain his strength, and when he sleeps, he dreams. He dreams of the battles you've fought, studying every move you used against him to devise the perfect counter. The man who is not a man can aspire to that—being perfect, realizing his purpose. But he is more than a puppet, you see. He also fears his own success. Once he has you, once he drags you back to share Heliod's doom as fate dictates, what is left for him? What is the essence of Calix once his aims are fulfilled?] #emph[He knows the answer and is terrified of it. Not even an agent of fate can evade destiny.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The Phyrexian attack came in the dead of night. Elspeth was still fastening the straps of her armor as she ran through the hallways of the tower. Every other second, an explosion rang out, reverberating off the walls so each crash sounded like it was right on top of her. Reaching the door to Saheeli's workshop, she burst in without announcing herself. The Temporal Anchor hissed and rattled. Saheeli darted back and forth, bending and twisting parts of her machine with her metalsmithing abilities to keep one step ahead of it shaking itself apart. Casting a violet haze onto the entire scene was Kaya, struggling to maintain her ghostform magic over herself and the coffin-shaped chamber that housed Teferi. "We're under attack!" Elspeth shouted. "Please tell me you've gotten what you need." "Not yet," Saheeli said, barely catching her breath. "But Teferi's so close. If we shut down now, we won't get another chance at going back. Please~ We just need a little longer." It was happening. Elspeth closed her eyes, and for a moment, all sound drifted away. She remembered what she said to Teferi: #emph[If the Phyrexians are still on this plane, it's only a matter of time before they find this place. You will need someone to defend you if that happens—if they track us down. ] Now they'd done just that. She tightened her buckler onto her arm and unfastened the snap that held her sword in its scabbard. She felt for the small flask of Halo slipped into her belt pouch. Then she took a breath. #emph[It's time.] "Bar the door when I leave," she ordered, then ran back the way she came, faint shouts and clatter accenting every deafening boom. When she arrived in the grand hall, Wrenn and Nissa were already there, watching out one of the cathedral-like windows at the watchtower turrets firing bolts of blue-white energy at a dark shape floating below the storm clouds. "What is that?" Elspeth asked. "A skyship," said Jodah, stepping out of a magical portal and into the chamber. "Look there, our thopters." The thopters—visible only by their running lights—streaked into view headed toward the skyship. Everyone watched as the thopters buzzed around the shadow like so many gnats, flinging explosive charges that only succeeded in revealing what they were dealing with. Not so much a ship as a floating monstrosity of tapered horns and jagged spikes, the vessel kept itself aloft by sails that resembled scaly, bat-like wings. Slowly, it changed its trajectory to aim its keel downward, aligning with the central tower. The turret fire intensified as the ship descended, only for the watchtowers to stop firing one by one. "The defense grid," Jodah said, his voice hollow. The ship lowered itself onto the ground to rest on a set of spines spreading out from its hull like the legs of a giant insect. Elspeth had seen enough. "They're on their way," she said. "Wrenn and Nissa, protect Teferi at all costs." Among the soldiers, she eyed a pair of mechanical dromedaries, filigree steeds built by Saheeli for this exact moment. "Jodah, are you ready?" Jodah shot Elspeth a look. "I suppose it's too late to ask for your plan to be a tad less bold." "You had your chance," Elspeth said. "Now we ride out to meet them. Buy time for Teferi." They mounted up and armed themselves with powerstone lances, also prepared by Saheeli. Jodah was right to have doubts. In a siege, the defenders' advantage came from their walls. Doctrine called for them to hunker down inside the main structure, set up archers or other ranged units to attack from a distance, and break any attack through attrition. But there were two problems with that in this scenario. First, the tower was no castle—its open nature made it impossible to defend against intrusion if the enemy swarmed it. And second, the Phyrexians weren't a normal army. Their morale would not be broken by a failed assault. Somewhere out in the darkness, they were sneaking and scheming. What Elspeth had to do was trick them into obeying the rules of conventional warfare by providing an irresistible chance to sow discord and spread fear. "Arise!" screamed Elspeth. All at once, the hundred or so mechanical soldiers stomped to life, swinging their sharpened arms in unison like a set of thresher blades. Behind their ranks, a group of ten clay-covered brutes raised their arms into a boxing stance, readying their fists to smash any foes that Elspeth directed them at. The constructs' unblinking eyes, all trained on Elspeth, pulsated with a soft golden light. "Assemble!" The company marched in perfect time out of the chamber and into the courtyard, forming three concave arcs end to end. "March!" The soldiers advanced and fanned out, descending the central steps and stopping at the far end of the main pathway. The clay statues stayed behind in the courtyard to absorb any enemies that got past the front line. Everything was set. #figure(image("008_Chapter 4: The Dark/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Now we have to hurry," she said to Jodah. The two rode double-time around the southern side of the tower, keeping close to the wall until they reached a predetermined vantage point from which to monitor the siege line. Elspeth gripped her lance, her heart racing. "Saheeli said these lances only have one shot," she reminded Jodah. "We have to make it count." "Artificers," he grumbled. "Would it hurt them to make these fantastic inventions usable more than once?" Elspeth opened her mouth to say something, but a noise stole her attention. The sound came like whispers, followed the quiet slurp of things slithering through the mud. Then came the flapping of wings and a low, thunderous rumble that roared into an ear-piercing shriek—a Phyrexian battle cry. The army coalesced at the very edge of the tower's light, bending the membrane of the dark until it tore open. The front ranks bristled with humanoid warriors armored in black plate metal, their arm clusters tapering into blades, serrated edges, and needle-like spearpoints. Behind them strode mounted units—or what Elspeth first thought were knights on giant lupine creatures. But they moved too swiftly, navigated the slippery terrain much too well to have been steed and rider; each mounted foe was a single being, rider and mount fused together. For all their fearsome numbers and weapons, the Phyrexian ground troops did not chill Elspeth as much as what she saw next. The night sky moved, and winged knights dipped into the light. They were hideous, their bodies made of black sickle-shaped blades bound together by strands of sinew. While some maintained a vaguely human shape, others either replaced their bottom halves with a clutch of spider legs or eschewed legs altogether in favor of a spiked ball they could use to ram enemies from above. "Dammit," said Elspeth. She hadn't counted on aerial troops, but it was too late to adjust plans; the advancing horde marched ever closer to their siege line. The mounted Phyrexians broke out into a gallop, flowing around the flanks of the main body. It was a simple strategy, but effective: a pincer maneuver to smash the defenders between waves of metal beasts. "Wait for it." "Elspeth, it's now or never." She knew, but it was vital to make every part of the plan count. A second longer could mean more enemies caught in their trap. #emph[Steady, steady. ] The writhing mass had nearly reached the siege line. One more moment, and they'd be on top of the tower defenders. "Do it now, Jodah!" With a motion of his hand and the utterance of a single mystic syllable, Jodah unwove the phantasmal terrain spell he'd cast the previous day, revealing the staked trench that spanned from the far northern end of the tower complex all the way to the spot where Elspeth and Jodah had stationed themselves. Too late to stop their forward momentum, the Phyrexian vanguard speared themselves on a crisscross lattice of sharpened logs. With another word of power, Jodah caused the entire barricade to erupt into flame, thrusting the enemy into disarray. The first rows of Phyrexian infantry met the same fate as the riders, which at first buoyed Elspeth's hopes. But with no hesitation, the next row used the flaming bodies of their brethren as handholds to climb over the barricade to the other side. The fliers followed, advancing up to the front ranks to carry otherwise pinned fighters safely over to the flames. Luckily, they had one more trick in store. "Let's go!" shouted Elspeth. She spurred her mount down a path perpendicular to the invasion force, then turned sharply toward the horde in a flanking charge. She raised her lance, its tip glowing white-hot from the powerstone set into it, to signal Jodah to begin his own charge. As she galloped toward the Phyrexians, she set her lance to point toward the enemy and guided her thumb onto a crystal inset on the shaft. So far, Saheeli had more than proven her genius. But now was the time that Elspeth needed the artificer to outmatch anything she'd created before. Elspeth pressed the crystal when she was mere yards away from the Phyrexian line. A burning sensation overcame her hand as the lance's powerstone grew intolerably bright. Then it shattered, its pent-up power erupting as a band of energy that streaked across the battlefield to connect to its mated pair—the powerstone in Jodah's lance. Elspeth spurred her steed onward, gaining as much speed as she could before ramming into the horde, the energy band ripping through the Phyrexians like a scythe through wheat. She continued to drive forward, not daring to slow down for fear of an enemy blade getting past her greaves or a grasping hand catching hold and pulling her down from her saddle. Elspeth reached the other side of the throng, decimated Phyrexians in her wake. She wheeled around, waited for the all-clear from Jodah on the other side of the field, and then stormed back into the fray to cleave her way through more of the enemy. She took a moment to look over her shoulder at the siege line. The automatons were holding their own, swarming small clusters of enemies and shredding them before they could counterattack. The few Phyrexians that had broken through the front line made the mistake of attacking the clay statues directly, resulting in their limbs being stuck inside the statues' malleable exteriors. Elspeth had turned her attention back to finishing off more of the Phyrexian infantry when she caught sight of a winged knight swooping down from above. She deflected the blow away from her head, but it still succeeded in toppling her mount into the dirt. She pushed herself up from the sodden earth, only for a heavy metal boot to kick her in the stomach, whipping her onto her back. As her attacker trudged toward her, raising its axe-like arm to deliver a killing blow, Elspeth saw that no head rested on its neck. Instead, it seemed to see and sense through a flesh-stripped skull embedded into its torso. That was just the right distance for a swift kick of her own. It reeled backward, giving Elspeth enough time to spin back onto her feet and draw her sword, unleashing a pulse of white light—pure Halo—that caused her adversary to stagger back, blinded. Her opening clear, Elspeth batted away the axe head and thrust her sword clean through its midsection. She pushed the Phyrexian's body off her blade with her foot and looked up over the chaos to see the enemy reeling and disorganized. Now was the time to press the advantage. "Charge!" she screamed, her voice ringing out over the din. Upon hearing the command word, the metal legion defending the keep turned into aggressors, charging over the flaming barricade and onto the battlefield. Though not spooked, the remaining Phyrexians fell back to re-establish a siege line. Those that came within reach of Elspeth fell to her swings like they were dummies made of rags and sackcloth. She wasn't the only one to perceive this—the Phyrexians began to backpedal at Elspeth's approach. She gave them no quarter as she fought across the battlefield, parrying away blade and claw looking for Jodah. She spotted him pinned down against the barricade by two more flying Phyrexians. Gripping her sword in both hands, Elspeth broke into a charge and uttered a spell. A moment later, a helix of light surrounded her body, launching her high enough to cut down one of Jodah's attackers. She swiveled upon landing in front of the other Phyrexian, arcing her blade upward to slice it out of the air. "They're waning," said Jodah. Elspeth surveyed the battlefield. The last of the winged Phyrexians had been tackled to the ground by clay statues and pulled apart. Mechanical soldiers pursued the remaining Phyrexian infantry into the muck and battered them down. High above their heads, thopter squadrons chased teams of skirges, blasting them out of the sky. Victory was firmly in hand. Elspeth turned and embraced Jodah, her knees giving ever so slightly from the sudden wave of fatigue that washed over her. All she wanted was to sleep, to dream of lands with possibility and then wake up to fight for a new day. None of it was to be. "By Urza's salty breeches~" said Jodah, his shoulders going slack. Elspeth let go of him and turned around. There, framed by the billow of green-black clouds, the silhouette of the Phyrexian skyship shuddered and began to move—to grow, to unfold like a beast arising from a long rest. Several more gargantuan legs sprouted from the bottom of the skyship's hull, raising its body higher than the top of the tower. Blood-red arcane sigils became visible upon its black form, symbols Elspeth knew by sight even if she couldn't read them. It was the language of Phyrexia, emblazoned on the behemoth to proclaim the coming of a new order. It began to move forward, quaking the ground step by colossal step. "We can't let that thing near the tower," said Elspeth. "Agreed," said Jodah, ardent resolve replacing his earlier cheer. "But I need to know—how much do you believe in your own power?" "What?" He reached into his robe and pulled out a small leather pouch he wore around his neck. He took it off and held it out for Elspeth to see. "What is this?" she asked. "Something Jaya cooked up," he said. Jaya—the friend he and Chandra wept for. "You are powerful, Elspeth. Not because of the strength in your sword arm, and #emph[not ] because you are a Planeswalker. It's deeper—your desire for connection, to be the hand that thrusts itself into the flames to rescue another. To have peace, family, a home. To belong." How did he know these things about her? A week prior, they'd never met, never even known each other existed. But like Wrenn, he'd stripped away her various masks with little effort. No, she wasn't a knight of Bant, nor was she Heliod's champion or New Capenna's vengeance. She was only what was left: <NAME>. "I~ I don't understand." "I told you—I've been around a good long while. And in my time, I've dealt with many mages, some with more affinity for certain magic than others. Looking at you~ It's like gazing at a white-hot sun trying to hide itself. No more hiding, Elspeth." He closed his hand around the pouch, gripping it tightly. "A final gift from Jaya to Phyrexia. Chandra would be the natural choice, but the very first thing I learned about magic is that fire and light are not so distant. You can help me cast it." "What must I do?" she asked. "Follow my lead." They wrangled Jodah's steed, jumped on, and sped toward the Phyrexian beast. As they drew closer to it, it felt like they and the entire world were shrinking under the monster's oppressive shadow. The elation she'd felt only minutes before had evaporated away. What were they to it but specks of dirt? What could she and Jodah do to even slow it down? They continued riding until they were nearly underneath it. Jodah hopped off the saddle and extended his hand to help Elspeth get down. The red glow from the Phyrexian sigils dimly illuminated the spot of muddy, slimy earth where they stood. Gazing up at the monstrosity, Jodah spread his arms and rose into the air, his robes billowing in the grimy wind. He began to recite words in a language Elspeth couldn't understand. As she listened, a flood of images began to infiltrate her mind—a beautiful dark-haired woman; Jodah looking no older than he did now; the sound of shattering glass; and then #emph[fire] . "Let go," he said, his voice tapped into her mind. "Let go of your anger, your pain. Let go of your ghosts—they will haunt you, but allow their pleas to fall unheard for now. Stretch your consciousness past them, past the ground, past the sky, past all the boundaries of your waking life." Elspeth did as Jodah instructed. She closed her eyes and recalled the rolling plains of Bant, the golden grain fields of the Guardian Way outside of Meletis on Theros. No, not just imagination—somehow, she was there, in both places at once. Farther, farther she reached, so far that she could feel herself slipping—she was no longer so much Elspeth alone, as she'd become #emph[everything] . Her eyes shot open, and she found herself at the heart of a torrent of energy surging through every part of her body. "Now bring it all back inside you," Jodah said. "Root it as deeply as you can until you can no longer contain it." Elspeth willed the storm into her heart, into her soul. The scorching energy began to tear her apart. "Focus, Elspeth! Choose one thing—the one thing in your life that gives you strength, gives you purpose. Channel your entire being into it!" #emph[Ajani.] Part of her wanted to consider him dead and gone. At least he'd be at peace. But another part of her needed him here, needed there to be a chance of saving him like Chandra insisted. Because he was the one—that one person in her life who could give her hope, lend her strength. #emph[Home is duty. Family is those you choose to defend. You have always had everything you ever needed. ] Now Elspeth understood what Giada was trying to tell her, what Teferi beseeched her to do that first night after arriving on Dominaria. Her duty wasn't only to protect others; she needed to allow herself to be protected by those whom she loved. Her family. To trust them. Just like Ajani trusted her to rescue him. She would do it. She would bring him back. She would believe. A column of radiance poured out of her, blasting upward toward the sky, surging over Jodah in scintillating coils of power. She was connected to him, to Jaya's spell, her energy igniting a maelstrom of swirling, brilliant light around them both. She and Jodah were consumed by the blaze, becoming one with the storm. United, they willed themselves to expand wider and taller than the Phyrexian behemoth, melting it into slag and ichor before vaporizing it in a glorious whirlwind. Then the light vanished. She dropped to her knees, once again <NAME>. The ground against her palms was warm and dry, cracked. She craned her neck upward, seeing no trace of the giant Phyrexian beast. The cool, soothing rain fell onto her face. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Names are but labels that soothe us into thinking we have knowledge, and by extension, control. New Capenna? Old Capenna? No matter. You must understand, dearest, that your masters in the asylum were in pain, too. They were not "Phyrexians" so much as they were your neighbors, your families who found salvation in the oil, who desired to be reborn as voracious membranes, lashing villi, and flailing flagella bound in perfect metal.] #emph[You didn't know this, and neither did Boy.] #emph[Remember Boy? Oh, he had a name. You never asked him; it's too late to know what it was. You devised quite the plan, you two, hatched amid the baleful ravings of your jailers. You thought you could hide among the cadavers, tuck yourselves into blankets of flesh and offal and wait until those remains were tossed onto the rot-heaps outside of your prison. What you did not know was that your captors loved that gore. That the reek of viscera was a cloying incense, obliterating their memories of fresh wildflowers, baking bread, the salt of the ocean. Their old names, the things they loved.] #emph[That is how they caught you: You hid exactly where they would look. They chained you with every intention of grafting strips of your flesh onto their bones. Thanks to your Planeswalker spark, you escaped, but Boy wasn't as fortunate.] #emph[You can imagine how they reacted. Understand that he was not dreaming when his fate befell him. What they did, they did smiling, and afterward, there was no Boy left. ] #emph[Only Phyrexia.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) "Elspeth!" she heard Jodah call out. Searching around, she found him sprawled on the ground barely able to move. "I can't believe that worked," he said, his breath labored. Elspeth pulled Jodah up to his feet, allowing him to lean on her, and together, they shared a moment of silence gazing back at the tower, its gentle blue glow calling them back home. "You did it," he said. "We did it," said Elspeth, her arm around Jodah's shoulder. "You, me, and Jaya." "I wish you could have met her. She would have liked you. Or hated you. Bit of a coin flip, really." He smiled. "I know she'd be impressed either way." Suddenly, bright, blue-white flashes brightened the sky by the tower, followed soon after by thunderous peals. For a moment, Elspeth thought lightning had struck the tower or its environs. But she couldn't trace any fork back up to the clouds. No, the blasts were coming from ground level. "The tower is under attack," said Elspeth, her stomach sinking. "This army, this creature—they were a distraction." "Yes," Elspeth heard someone say behind her. Turning, she saw a young woman wearing a set of robes like those worn by Jodah and Teferi. In addition to the shades of red, blue, and gold, the woman's garb added one key variation: a circular star chart motif emblazoned on her breastplate bisected by a solid line—the seal of Phyrexia." "Rona," Jodah said. "I can't say that it's good to see you again, but—" Rona raised her glaive and sent an explosion of azure lightning at Elspeth and Jodah, launching them backward into the mud. Elspeth's world tossed and swerved like a capsizing ship. She groped for her sword, and finding its hilt, pushed herself up in time to see Rona standing over a weak and helpless Jodah. "This is for the trouble you caused me in Yavimaya," she said as she plunged the point of her glaive into his gut, eliciting a sickening rasp from Jodah's throat. "No!" Elspeth screamed. She scrambled to her feet, fatigue weighing upon her like a titan pressing down on her shoulders. Even though Rona looked more human than the enemies Elspeth faced earlier, she was much worse a monstrosity. She had willingly given up her soul for the Phyrexian promise of power. Elspeth stepped back, making sure to keep Jodah's body in view. She could barely stand. Jodah's spell had left her near collapse, unable to collect herself enough to cast spells or planeswalk. All she had in the moment was her sword, which she could barely lift. With uncanny quickness, Rona leaped forward, swinging her glaive at Elspeth's midsection, an attack that should have been easy to parry. But all Elspeth could do was flail her shield arm out to bat the glaive away. Rona went in for a second lunge that Elspeth barely dodged. "I won't surrender," said Elspeth. Rona beamed. "Good." She was playing with Elspeth as a torture master would tease a prisoner with the faintest hope of freedom. #emph[Cooperate and everything will be fine. ] Elspeth took stock of the distance between her and Rona. Rona had reach along with every other advantage in this duel save for one. Elspeth knew the dance. #emph[Trust] , she told herself, and with that, she held up her buckler as high as she could and crouched into first guard position. Gathering every shred of strength she had left, she held it all in reserve, waiting for one more opening. Rona gave it to her. She callously stepped forward, unleashing a flurry of swings meant more to intimidate Elspeth than land a killing blow. At the end of the display, Rona spun into a head-level thrust. Elspeth summoned her remaining vigor to block Rona's strike with her buckler, knowing that the shield wasn't any match for a direct blow. The spearpoint pierced the buckler, punching through the flesh and bone of Elspeth's forearm. Screaming through the pain, Elspeth heaved her left arm downward—#emph[fifth guard to second—] wrenching the glaive free from Rona's hands and burying her sword deep into Rona's shoulder. Both went down, Rona in a heap and Elspeth onto her knees. She looked over at Jodah lying motionless. #emph[Not too late] , she thought, her head swimming. #emph[Halo] ~ With her free hand, she felt for her belt pouch. If any life remained in Jodah, Halo could save him. "Tirel. I never expected to actually see you again." Elspeth gritted her teeth. That voice—Tezzeret. She looked up to see him approaching out of the dark. He knelt between Rona and her, close enough for her to wrap her hands around his throat—one last act of defiance—but her body refused to obey. Seizing her impaled arm, Tezzeret dislodged Rona's glaive with a single jerk. Then he turned to Rona to check her wound oozing blood and black glistening oil. "She's still alive. Pity. Next time, aim for the neck." "And you, Tezzeret?" said Elspeth. She clutched her wounded arm to her chest. "Still nothing but a pathetic lapdog." She expected him to lash out like she'd witnessed in her prior interactions with him on New Phyrexia. But instead, Tezzeret merely shook his head, pointing back at the flashing detonations back at the tower. "I didn't have time to disarm that side of your defenses. #emph[Tsk, tsk.] Messy." He took hold of Rona's collar and stood up. "Whatever efforts your cohort are engaged in will be stopped and destroyed before morning. There's no avoiding it. But you need not share their fate. I suggest you take this opportunity to find somewhere remote and disappear." "I'm going to stop your Phyrexian masters. And then I'm going to kill you." "Hmm," he said, hoisting Rona up onto his shoulder and picking up her glaive. "If you're thinking of striking out at me now, I'd advise against it. In your weakened state, I would assuredly win. Besides, tending to your dying companion is a better use of time, don't you think?" "Why? Why are you sparing me?" "Small cracks, Tirel," he said. "That's how even the mightiest edifice begins to crumble." He bowed his head in what Elspeth could only guess was a twisted gesture of respect. "May this be the last time our paths cross." Then he walked back into the dark. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Exquisite ends are the most beautiful. So let this missive end with unctuous splendor, with tooth and edge, undulating muscle and slick ichor. It truly is a sight, your Phyrexia. A land where nightmares can have nightmares. The grand cenobite—she has the sweetest of them all. Such horrors to tease from her mind and such visions to implant starting with you, the fearsome lady in white who has defied even death to have her vengeance.] #emph[There are so many things to say, dearest, but the most appropriate is this: Thank you. There is a new purpose for my work, all because of you. So, when you are alone in the dark, remember that there is one among the countless planes that has you in mind. You will always have your most dedicated admirer close by.] #emph[Yours, always,] #emph[Ashiok]
https://github.com/rabotaem-incorporated/calculus-notes-2course
https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/05-complex-functions/06-residues.typ
typst
#import "../../utils/core.typ": * == Вычеты #ticket[Вычеты. Определения и свойства.] #def[ $a != oo$ --- изолированная особая точка $f$. Вычетами называются $ res_(z = a) f := c_(-1)&, quad "где" f(z) = sum_(n = -oo)^oo c_n (z - a)^n,\ res_(z = oo) f := -c_(-1)&, quad "где" f(z) = sum_(n = -oo)^oo c_n z^n. $ В бесконечности вычет существует всегда. ] #props[ 1. Если $f in H(0 < abs(z - a) < R)$ и $0 < r < R$, то $ res_(z = a) f = 1/(2 pi i) integral_(abs(z - a) = r) f(z) dif z. $ ] #proof[ Считаем $a = 0$. $ integral_(abs(z) = r) f(z) dif z = integral_(abs(z) = r) sum_(n = -oo)^oo c_n z^n dif z. $ Параметризуем, $z = r dot e^(i t)$, $dif z = r e^(i t) dot i dif t$. $ integral_(abs(z) = r) sum_(n = -oo)^oo c_n z^n dif z = i integral_0^(2 pi) sum_(n = -oo)^oo c_n (r e^(i t))^n r e^(i t) dif t = i integral_0^(2 pi) sum_(n = -oo)^oo c_n r^(n + 1) e^(i (n + 1) t) dif t. $ Сумма абсолютно сходится, так как ряд лежит строго внутри кольца сходимости (у нас, правда, есть еще лишний множитель $e^(i t)$, но он не влияет на абсолютную сходимость). Тогда можем менять местами сумму и интеграл. $ i integral_0^(2 pi) sum_(n = -oo)^oo c_n r^(n + 1) e^(i (n + 1) t) dif t = sum_(n = -oo)^oo c_n r^(n + 1) i integral_0^(2 pi) e^(i (n + 1) t) dif t. $ Этот интеграл считается: $ integral_0^(2 pi) e^(i (n + 1) t) dif t = cases( lr(e^(i (n + 1) t)/(i(n + 1)) |)_(0)^(2 pi) = 0\, quad &"при" n != -1, 2 pi\, &"при" n = -1 ). $ ] #props[ 2. Если $a$ полюс порядка $<= m$, то $ res_(z = a) f = 1/(m - 1)! dot lim_(z -> a) dif^(m - 1)/(dif z^(m - 1)) ((z - a)^m f(z)). $ В частности, для полюса первого порядка $ res_(z = a) f = lim_(z -> a) (z - a) f(z). $ ] #proof[ Считаем $a = 0$. Так как это полюс, $ f(z) = sum_(n = -m)^oo c_n z^n. $ Посмотрим на $ g(z) := z^m f(z) = sum_(n = 0)^oo c_(n - m) z^n. $ Нужен коэффициент при $z^(m - 1)$ в этом ряде. Это просто формула Тейлора. Доопределим $g(z)$ в нуле, и выпишем коэффициент: $ c_(-1) = (g^((m - 1))(0))/(m - 1)! = 1/(m - 1)! lim_(z -> 0) ((dif^(m-1))/(dif z^(m-1)) z^m f(z)). $ Так как доопределенная $g$ голоморфна, в окрестности нуля можно сколько угодно брать производные и менять их местами с пределами. ] #props[ 3. Пусть $f(z) = g(z)/h(z)$, где $g, h$ --- голоморфные в окрестности $a$, и $g(a) != 0$, $h(a) = 0$, $h'(a) != 0$. Тогда $ res_(z = a) f = (g(a))/(h'(a)). $ ] #proof[ $ res_(z = a) f = lim_(z -> a) (z - a) f(z) = lim_(z -> a) (z - a)/(h(z) - h(a)) dot g(z) = lim_(z -> a) 1/(h'(a)) dot g(z) = g(a)/(h'(a)). $ ] #props[ 4. Если $lim_(z -> oo) f(z) = A$, то $res_(z = oo) f = lim_(z -> oo) z dot (A - f(z))$. ] #proof[ По определению знаем $res_(z = oo) f = -c_(-1)$. Ряд Лорана для устранимой точки $oo$ выглядит как $ f(z) = sum_(n = -oo)^0 c_n z^n = A + sum_(n = 1)^oo c_(-n)/z^n. $ Тогда $ z dot (A - f(z)) = -sum_(n = 1)^oo c_(-n)/(z^n) dot z = -sum_(n = 1)^oo c_(-n)/z^(n - 1) --> -c_(-1). $ ] #props[ 5. $ -res_(z = oo) f = res_(z = 0) 1/(z^2) dot f(1/z). $ ] #proof[ $f(z) = sum_(n = -oo)^oo c_n z^n$, и $ 1/z^2 f(1/z) = 1/z^2 sum_(n = -oo)^oo c_n/z^n = sum_(n = -oo)^oo c_n/z^(n + 2). $ Тогда $ res_(z = 0) 1/z^2 f(1/z) = -res_(z = oo) f = c_(-1). $ ] #ticket[Теорема о вычетах. Сумма вычетов. Пример.] #th(name: "Коши о вычетах")[ $f$ --- голоморфна в $Omega$, за исключением конечного числа особых точек, $K subset Omega$ --- компакт, граница $K$ состоит из конечного числа непересекающихся закмнутых простых кусочно-гладких кривых, и особые точки $f$ не лежат на границе $K$. Тогда $ integral_(diff K) f(z) dif z = 2 pi i sum_(a in Int K \ "особая") res_(z = a) f. $ ] #proof[ Окружаем особые точки кругами $B_r (a)$ так, чтобы $overline(B)_r (a) subset K$ и $overline(B)_r (a) sect overline(B)_r (b) = nothing$ для различных особых точек $f$. $tilde(K) := K without Union B_r (a)$ --- компакт, как замкнутое подмножество компакта, и $f$ голоморфна в $tilde(K)$. Тогда по теореме Коши $ 0 = integral_(diff tilde(K)) f(z) dif z = integral_(diff K) f(z) dif z - sum_(a in Int K \ "особая") integral_(abs(z - a) = r) f(z) dif z. $ Про каждую особую точку $a$ можно сказать, что $ integral_(abs(z - a) = r) f(z) dif z = 2 pi i res_(z = a) f, $ поэтому подставив это в предыдущее равенство, получим утверждение теоремы: $ integral_(diff K) f(z) dif z - 2 pi i sum_(a in Int K \ "особая") res_(z = a) f = 0. $ ] #follow[ Пусть $f$ голоморфна в $CC$ за исключением конечного числа особых точек. Тогда $ sum_(a in CC \ "особая" \ "или " oo) res_(z = a) f = 0. $ ] #proof[ Пусть $a_1, a_2, ..., a_n$ --- особые точки. Тогда возьмем $R > abs(a_1), abs(a_2), ..., abs(a_n)$. Можно посчитать интеграл по окружности $abs(z) = R$ (обходя против часовой стрелки) двумя способами, во-первых, по теореме Коши: $ integral_(abs(z) = R) f(z) dif z = 2 pi i sum_(k = 1)^n res_(z = a_k) f. $ А во вторых, в кольце $abs(z) > R$ можно разложить $f$ в ряд Лорана, и тогда $ integral_(abs(z) = R) f(z) dif z = 2 pi i c_(-1) = -2 pi i res_(z = oo) f. $ При вычитании этих равенств получается утверждение теоремы. ] #example[ Посчитаем $ integral_(abs(z) = 4) z^2/(e^z + 1) dif z. $ По теореме Коши о вычетах, $ integral_(abs(z) = 4) z^2/(e^z + 1) dif z = 2 pi i sum res. $ Где у этой функции особые точки? Когда $e^z + 1 = 0$, то есть в $z = pi i + 2 pi i k$. Какие из этих точек попали в кольцо $abs(z) < 4$? Только $z = pi i$ и $z = -pi i$. #figure[#image("../../images/integral-contour-1.svg", width: 7cm)] Тогда $ integral_(abs(z) = 4) z^2/(e^z + 1) dif z = 2 pi i (res_(z = pi i) + res_(z = -pi i)). $ Нули $e^z + 1$ имеют кратность 1, потому что производная равна $e^z$, и в 0 никогда не обращаются. Значит $pi i$ и $-pi i$ --- полюсы первого порядка, и можно вычислить вычеты по простой формуле $res = g/h'$: $ res_(z = pi i) f &= z^2/(e^z + 1)' = (pi i)^2/(e^(pi i)) = pi^2\ res_(z = -pi i) f &= z^2/(e^z + 1)' = (-pi i)^2/(e^(-pi i)) = pi^2. $ Подставляем, $ integral_(abs(z) = 4) z^2/(e^z + 1) dif z = 2 pi i (res_(z = pi i) + res_(z = -pi i)) = 2 pi i (pi^2 + pi^2) = 4 pi^3 i. $ Этот интеграл был не очень интересным, потому что интегралы каких-то функций по окружности считать странно. Попробуем посчитать что-нибудь более интересное. ] #ticket[Полтора способа для вычисления интеграла $(dif x)/(x^(2n) + 1)$.] #example[ Вычислим $ I := integral_0^oo (dif x)/(1 + x^(2n)). $ Пусть $f(z) = 1/(1 + z^(2n))$. Это четная функция --- $f(z) = f(-z)$, и поэтому можно вычислить не интеграл по лучу, а по всей вещественной прямой: $ I = 1/2 integral_RR f(x) dif x. $ Только прямая --- странный контур, --- поэтому мы посчитаем интеграл по полуокружности, а потом перейдем к пределу. Пусть $ Gamma_R = [-R; R] union underbrace((diff B_R (0) sect {z: Im z > 0}), C_R). $ #figure[ #image("../../images/integral-contour-2.svg", width: 8cm) ] Тогда $ integral_(Gamma_R) f(z) dif z = 2 pi i res f. $ Какие у этой функции особые точки? Это те, в которых обнуляется знаменатель, то есть $z^(2n) = -1$, или $z = e^(i phi)$, где $2 n phi = pi + 2 pi k$. Среди них нам нужны лишь те, что лежат в верхней полуплоскости. Это $ a_k = e^(i phi_k), "где" phi_k = (pi + 2 pi k)/(2n), "при" k = 0, 1, ..., n - 1. $ Все эти полюса имеют порядок 1, так как производная знаменателя не обращается в нуль. Считаем вычеты: $ res_(z = a_k) f = lr(1/(1 + z^(2n))' |)_(z = a_k) = 1/(2n a_k^(2n - 1)) = a_k/(2n dot underbrace(a_k^(2n), -1)) = -e^(i phi_k)/(2n). $ Значит $ integral_(Gamma_R) f(z) dif z = 2 pi i sum_(k = 0)^(n - 1) res_(z = a_k) f = cancel(2) pi i sum_(k = 0)^(n - 1) (-e^(i phi_k)/(cancel(2)n)). $ Это можно досчитать как сумму геометрической прогресии. Мы знаем, что $ integral_(Gamma_R) f(z) dif z = integral_(-R)^R f(x) dif x + integral_(C_R) f(z) dif z. $ Оценим второй интеграл. $ abs(integral_(C_R) (dif z)/(1 + z^(2n))) <= pi R dot max_(abs(z) = R) 1/abs(1 + z^(2n)). $ Оценим знаменатель: $abs(z^(2n) + 1) >= abs(z^(2n)) - 1$, поэтому $ abs(integral_(C_R) (dif z)/(1 + z^(2n))) <= (pi R)/(R^(2n) - 1) -->_(R -> +oo) 0. $ Значит в пределе этот интеграл $0$, и $ I = 1/2 integral_(Gamma_R) f(z) dif z = 1/2 dot 2 pi i dot sum_(k=0)^(n - 1) -e^((i (2 π k + π))/(2 n))/n = (2 pi i e^((i π)/(2 n)))/((-1 + e^((i π)/n)) n). $ Или как-то так, если я правильно посчитал геометрическую прогрессию. Но это не важно, можно считать даже меньше. #line(length: 100%) Альтернативный способ. Пусть теперь мы считаем интеграл по контуру сектора окружности величины $alpha$, то есть $ Gamma_R = text(#green, [0; R]) union text(#blue, underbrace({R dot e^(i phi): 0 <= phi <= alpha}, C_R)) union text(#purple, [R dot e^(i alpha); 0]). $ Найдем такое $alpha$, что на отрезке $[0; R dot e^(i alpha)]$ функция $f$ совпадает с $1/(1 + x^(2n))$: $ f(t e^(i alpha)) = 1/(1 + t^(2n) e^(2n i alpha)) = 1/(1 + t^(2n)) $ при $e^(2n i alpha) = 1$, то есть, например, при $alpha = pi / n$. Тогда особая точка в этой области всего одна: $z = e^(i pi/(2 n))$. #figure[ #image("../../images/integral-contour-3.svg", width: 8cm) ] $ integral_(Gamma_R) f(z) dif z = 2 pi i res f. $ Интеграл есть $ integral_(Gamma_R) f(z) dif z = integral_0^R f(x) dif x + integral_(C_R) f(z) dif z + integral_(R dot e^(i pi/n))^0 f(z) dif z. $ Первый интеграл сходится к $I$, второй интеграл сходится к 0, как мы показали в предыдущем решении, а третий интеграл сходится к $I dot -e^((pi i)/n)$, так как мы просто подставляем $z = t e^(i pi/n)$ в интеграл и разворачиваем отрезок. Через вычеты, интеграл равен $ integral_(Gamma_R) f(z) dif z = 2 pi i res f = 2 pi i (-e^(i pi/(2n))/(2n)). $ Отсюда $ I (1 - e^((i π)/(n))) = -2 pi i dot e^((i π)/(2n))/(2n) ==> I = ((pi i)/n) e^((i π)/(2n))/(e^((i π)/(n)) - 1) = pi/n dot i/(e^((pi i)/(2n)) - e^((-pi i)/(2n))) = pi/(2n) dot 1/(sin((pi)/(2n))). $ ] #ticket[Лемма Жордана. Вычисление интеграла $(cos lambda x)/(x^2 + 1) dif x$.] #lemma(name: "Жордана")[ $C_(R_n) := {z in CC : abs(z) = R_n, Im z > 0}$, и $R_n --> oo$. Пусть $M_(R_n) := max_(z in C_(R_n)) abs(f(z)) --> 0$, и $lambda > 0$. Тогда $ integral_(C_(R_n)) f(z) dot e^(i lambda z) dif z --> 0. $ ] #proof[ Параметризуем $z = R_n dot e^(i t)$, $dif z = R_n e^(i t) i dif t$. $ abs(integral_(C_(R_n)) f(z) e^(i lambda z) dif z) = abs(integral_0^pi f(R_n e^(i t)) R_n e^(i t) i e^(i lambda R_n e^(i t)) dif t) <= R_n dot M_(R_n) dot integral_0^pi abs(e^(i lambda R_n e^(i t))) dif t. $ Посчитаем штуку под интегралом: $ abs(e^(i lambda R_n e^(i t))) = abs(e^(i lambda R_n (cos t + i sin t))) = abs(e^(i lambda R_n cos t) dot e^(-lambda R_n sin t)) = e^(-lambda R_n sin t). $ Тогда $ abs(integral_(C_(R_n)) f(z) e^(i lambda z) dif z) <= R_n dot M_(R_n) dot integral_0^pi e^(-lambda R_n sin t) dif t = 2 R_n dot M_(R_n) dot integral_0^(pi/2) e^(-lambda R_n sin t) dif t $ так как функция под интегралом симметрична относительно $pi / 2$. Оценим синус снизу как $(2t) / pi$, то есть отрезочком между $(0, 0)$ и $(pi/2, 1)$: #figure[ #image("../../images/sine-approx.svg", width: 8cm) ] $ abs(integral_(C_(R_n)) f(z) e^(i lambda z) dif z) <= 2 R_n dot M_(R_n) dot integral_0^(pi/2) e^(-lambda R_n sin t) dif t <= 2 R_n dot M_(R_n) dot integral_0^(pi/2) e^(-2 lambda R_n t / pi) dif t. $ Такой интеграл берется: $ 2 R_n dot M_(R_n) dot integral_0^(pi/2) e^(-2 lambda R_n t / pi) dif t = lr(2 R_n M_(R_n) e^(-lambda R_n (2t) / pi)/(-lambda R_n 2/pi) |)_(t = 0)^(t = pi/2) = M_(R_n) (pi/lambda - pi/lambda e^(-lambda R_n)) --> 0. $ ] #example[ Посчитаем $ I := integral_0^(+oo) (cos x)/(1 + x^2) dif x = 1/2 integral_RR (cos x)/(1 + x^2) dif x. $ Здесь нам будет очень сильно мешать косинус, если мы поробуем сделать ту же самую штуку с полуокружностью: косинус будет вести себя как экспонента, и мы не сможем оценить его сверху. Однако, $ I = 1/2 Re integral_RR (e^(i x))/(1 + x^2) dif x. $ И вот такую штуку, оказывается, вычислить можно. Положим $ f(z) = e^(i z)/(1 + z^2). $ и проинтегрируем по $ Gamma_R = [-R; R] union C_R, $ где $C_R$ --- верхняя полуоружность. #figure[ #image("../../images/integral-contour-4.svg", width: 7cm) ] Особая точка в полуокружности одна: $z = i$, и это полюс первого порядка, поэтому $ integral_(Gamma_R) f(z) dif z = 2 pi i res_(z = i) f = 2 pi i lr(e^(i z)/(1 + z^2)' |)_(z = i) = 2 pi i e^(-1)/(2i) = pi/e. $ А сам интеграл есть сумма $ integral_(Gamma_R) f(z) dif z = integral_(-R)^R e^(i z)/(1 + z^2). dif x + integral_(C_R) e^(i z)/(1 + z^2). dif z. $ По лемме Жордана, так как $ max_(abs(z) = R) abs(1/(1 + z^2)) <= 1/(R^2 - 1) --> 0, $ то второй интеграл сходится к 0. Тогда $ integral_(RR) f(z) dif z = pi/e = 2I, $ откуда $ I = pi/(2e). $ ] #ticket[Лемма о полувычете. Интеграл в смысле главного значения. Вычисление интеграла $(sin x)/x$.] #def[ _Главное значение интеграла_, $ "v.p." integral_a^b f(x) dif x "или" "p.v." integral_a^b f(x) dif x $ это доопределение интеграла для функции, у которой существует проблема в точке $c$. Обычно, если мы очень хотим посчитать интеграл от функции с особенностью, то мы рассматриваем интеграл как сумму несобственных интегралов, то есть $ integral_a^b f(x) dif x = lim_(eps -> 0+) integral_a^(c - eps) f(x) dif x + lim_(eps -> 0+) integral_(c + eps)^b f(x) dif x, $ но эта сумма не обязана сходиться. Мы вводим новый интеграл, который иногда сходится, когда не сходится обычный несобственный: $ "v.p." integral_a^b f(x) dif x = lim_(eps -> 0+) (integral_a^(c - eps) f(x) dif x + integral_(c + eps)^b f(x) dif x). $ Если у интеграла есть несколько проблем, то мы делим область определения по непроблемным точкам, и считаем главные значения интегралов по каждому кусочку. ] #example[ $ "v.p." integral_(-1)^1 (dif x)/x = lim_(eps -> 0+) (integral_eps^1 (dif x) / x + integral_(-1)^(-eps) (dif x)/x) = 0. $ ] #props[ 1. Если существует несобственный интеграл $integral_a^b$, то существует и $"v.p." integral_a^b$, и они равны. 2. $"v.p." integral_a^b$ линеен. 3. Аддитивность по множеству, но резать по особым точкам нельзя. ] #lemma(name: "о полувычете")[ Пусть $f$ голоморфна в проколотой окрестности $a$, и $a$ --- полюс *первого* порядка. Пусть $ C_eps = {z in CC: abs(z - a) = eps "и " alpha < arg(z - a) < beta}. $ Тогда $ lim_(eps -> 0+) integral_(C_eps) f(z) dif z = (beta - alpha) i res_(z = a) f. $ ] #proof[ Пусть $a = 0$. Разложим $f$ в ряд Лорана: $f(z) = g(z) + c/z$, где $g(z)$ --- правильная часть, а $c/z$ --- главная. $g$ голоморфна в окрестности $a$, и поэтому $abs(g(z)) <= M$ в окрестности. Тогда $ integral_(C_eps) f(z) dif z = integral_(C_eps) g(z) dif z + integral_(C_eps) c/z dif z. $ Первый интеграл подпирается сверху: $ abs(integral_(C_eps) g(z) dif z) <= M dot (beta - alpha) eps --> 0, $ поэтому надо посчитать второй. Параметризуем $z = eps e^(i t)$, $dif z = eps e^(i t) i dif t$: $ integral_(C_eps) c/z dif z = integral_alpha^beta c/(eps e^(i t)) eps e^(i t) i dif t = i c integral_alpha^beta dif t = i c (beta - alpha). $ Что и требовалось. ] #example[ Пусть $ I = integral_0^(+oo) (sin x)/x dif x = 1/2 integral_RR (sin x)/x dif x = 1/2 integral_RR (Im e^(i x))/x dif x = 1/2 "v.p." integral_RR (Im e^(i x))/x dif x. $ В таком интеграле можно вытащить мнимую часть из под знака интеграла, и тогда $ I = 1/2 Im ("v.p." integral_RR (e^(i x))/x dif x). $ Посмотрим на следующую область $ Gamma_(R, eps) = text(#green, [-R; -eps]) union text(#blue, underbrace({z: abs(z) = eps, 0 < arg(z) < pi}, C_eps)) union text(#purple, [eps; R]) union text(#orange, underbrace({z: abs(z) = R, 0 < arg(z) < pi}, C_R)). $ #figure[ #image("../../images/integral-contour-5.svg", width: 10cm) ] Тогда $ integral_(Gamma_(R, eps)) e^(i z)/z dif z = 0, $ так как внутри этого контура нет особых точек. С другой стороны, это сумма следующих интегралов: $ integral_(Gamma_(R, eps)) e^(i z)/z dif z = underbrace( integral_(-R)^(-eps) e^(i x)/x dif x + integral_(eps)^R e^(i x)/x dif x, --> "v.p." integral_RR (e^(i x))/x dif x ) + underbrace(integral_(C_eps) e^(i z)/z dif z, --> -pi i res = -pi i) + underbrace(integral_(C_R) e^(i z)/z dif z, --> 0). $ В третьем интеграле вычет равен $1$, так как можно разложить $e^(i x)$ в ряд как $1 + x + ...$, и коэффициент при минус первом члене ряда будет равен $1$. Знак минус там из-за того, что контур обходится по часовой стрелке. Значит по лемме о полувычете, третий интеграл равен $-pi i$. Четвертый интеграл сходится к 0 по Лемме Жордана, так как максимум модуля не больше $abs(1/z) = 1/R --> 0$. Значит, $ "v.p." integral_RR (e^(i x))/x dif x = pi i. $ и $ I = 1/2 Im (pi i) = pi/2. $ ] #ticket[Вычисление интеграла $x^(p - 1)/(1 + x)$.] #example[ Когда-то, когда мы говорили про $Gamma$-функцию, мы замяли этот интеграл под ковер. Сейчас мы его возьмем: $ I = integral_0^(+oo) x^(p - 1)/(1 + x) dif x = integral_0^(+oo) e^((p - 1) Ln z)/(1 + z) dif z $ где $0 < p < 1$. Рассмотрим следующий контур: #figure[ #image("../../images/integral-contour-6.png", width: 10cm) ] $ Gamma_R = [eps; R] union diff B_R (0) union [R e^(2pi i); eps e^(2 pi i)] union diff B_eps (0). $ В нем одна особая точка: $z = -1$, когда обнуляется знаменатель, и это полюс первого порядка (точки где у логарифма проблемы мы выкинули). Тогда $ integral_(Gamma_R) e^((p - 1) Ln z)/(1 + z) dif z = 2 pi i res_(z = -1) e^((p - 1) Ln z)/(1 + z) = 2 pi i e^((p - 1) Ln (-1)) = 2 pi i e^(i pi (p - 1)). $ Вычет просто считается как первый член ряда Тейлора (значение в точке), так как мы поделили его на $z + 1$. С другой стороны, этот интеграл равен $ integral_(Gamma_R) e^((p - 1) Ln z)/(1 + z) dif z = integral_(eps)^R e^((p - 1) Ln z)/(1 + z) dif z + integral_(C_R) e^((p - 1) Ln z)/(1 + z) dif z + integral_(R e^(2pi i))^(eps e^(2pi i)) e^((p - 1) Ln z)/(1 + z) dif z + integral_(C_eps) e^((p - 1) Ln z)/(1 + z) dif z. $ Первый интеграл сходится к $I$. Третий интеграл это $ integral_(R e^(2pi i))^(eps^(2pi i)) e^((p - 1) Ln z)/(1 + z) dif z = -integral_eps^R e^((p - 1) (Ln z + 2pi i))/(1 + z) dif z = -e^(2pi i (p - 1)) I. $ Второй интеграл оцениваем: $ abs(integral_(C_R) e^((p - 1) Ln z)/(1 + z) dif z) <= 2pi R max_(abs(z) = R) abs(e^((p - 1) Ln z)/(1 + z)) <= 2pi R dot (R^(p - 1))/(R - 1) = 2pi R^p/(R - 1) --> 0. $ Последний интеграл оцениваем также: $ abs(integral_(C_eps) e^((p - 1) Ln z)/(1 + z) dif z) <= 2pi eps max_(abs(z) = eps) abs(e^((p - 1) Ln z)/(1 + z)) <= 2pi eps dot (eps^(p - 1))/(1 - eps) = 2pi eps^p/(1 - eps) --> 0. $ Значит, $ I - e^(2pi i (p - 1)) I = 2pi i e^(i pi (p - 1)) ==> I = 2 pi i e^((p - 1) pi i)/(1 - e^(2pi i (p - 1))) newline(=) -2pi i 1/ (e^(pi i (1 - p)) - e^(-pi i (1 - p))) = -pi/(sin(pi (p - 1))) = pi/sin(pi p). $ ] #ticket[Две теоремы о разложении мероморфной функции в сумму.] #th[ $f$ мероморфна в $CC$, $a_1$, $a_2$, ..., $a_n$ --- ее полюсы. В $oo$ устранимая особая точка или полюс. Тогда $ f(z) = sum_(k = 1)^n G_k (z) + G(z), $ где $G_k (z)$ --- главная часть ряда Лорана в $a_k$, а $G(z)$ --- правильная часть ряда Лорана в $oo$. В частности, $f$ --- рациональная функция. В частности, такая мероморфная функция полностью опеределяется своими особыми точками. ] #proof[ Пусть $g(z) := f(z) - G(z) - sum_(k = 1)^n G_k (z)$. У нее $a_j$ --- устранимая особая точка, потому что $G$ в $a_j$ голоморфна, все $G_k$ где $j != k$ голоморфны, и надо понять лишь $f(z) - G_j (z)$ --- это функция у которой главная часть ряда Лорана нулевая. Бесконечность тоже голомофная. Тогда $g(z)$ голоморфна в $overline(CC)$, и по теореме Лиувилля она постоянна. Пусть она равна $C$. Тогда $ lim_(z -> oo) ((f(z) - G(z)) - sum_(k = 1)^n G_k (z)) = C, $ но в сумме все слагаемые стремяться к нулю, и $f(z) - G(z)$ в ряде Лорана имеет нулевую правильную часть. Значит $C = 0$. ] #th[ Пусть $a_1$, $a_2$, $a_3$, ... --- полюсы мероморфной $f$, и имеются $R_n --> +oo$ такие, что $M_(R_n) = max_(abs(z) = R_n) abs(f(z)) --> 0$. Тогда $ f(z) = lim_(n -> oo) sum_(k: abs(a_k) < R_n) G_k (z), $ если $z != a_j$. ] #proof[ Пусть $ I_n = integral_(abs(zeta) = R_n) f(zeta)/(zeta - z) dif zeta = 2 pi i sum res f(zeta)/(zeta - z). $ Докажем следующее: $ res_(zeta = a_k) f(zeta)/(zeta - z) = res_(zeta = a_k) (f(zeta) - G_k (zeta))/(zeta - z) + res_(zeta = a_k) (G_k (zeta))/(zeta - z) =^? -G_k (z). $ Поймем, $ integral_(abs(zeta) = R) (G_k (zeta))/(zeta - z) dif zeta = 2pi i (res_(zeta = z) (G_k (zeta))/(zeta - z) + res_(zeta = a_k) (G_k (zeta))/(zeta - z)), $ потому что у этой функции особые точки --- это особые точки $G_k$, и $z$ (и эти точки не совпадают). Первый вычет это значение в $z$, то есть $G_k (z)$. Оценим интеграл, $ abs(integral_(abs(zeta) = R) (G_k (zeta))/(zeta - z) dif zeta) <= 2pi R max_(abs(zeta) = R) abs((G_k (zeta))/(zeta - z)) = 2 pi R dot O(1/R^2) --> 0. $ Значит $ -G_k (z) = res_(zeta = a_k) (G_k (zeta))/(zeta - z). $ Ну а $ (f (zeta) - G_k (zeta))/(zeta - z) $ имеет устранимую особую точку в $a_k$, потому что $f - G_k$ голоморфна в окрестности $a_k$, и $zeta - z$ не обращается в нуль, из-за чего её вычет равен $0$. Значит $ res_(zeta = a_k) f(zeta)/(zeta - z) = -G_k (z). $ Доказали промежуточные равенства. Наконец, $ 0 <-- I_n = 2 pi i sum res f(zeta)/(zeta - z) = 2 pi i (res_(zeta = z) f(zeta)/(zeta - z) + sum_(k: abs(a_k) < R_n) res_(zeta = a_k) f(zeta)/(zeta - z)) newline(=) 2 pi i (f(z) - sum_(k: abs(a_k) < R_n) G_k (z)) ==> f(z) = lim_(n -> oo) sum_(k: abs(a_k) < R_n) G_k (z). $ Почему $I_n$ стремится к $0$? Потому что $ abs(I_n) <= 2 pi R_n max_(abs(zeta) = R_n) abs(f(zeta)/(zeta - z)) <= 2 pi R_n M_(R_n)/(R_n - abs(z)) --> 0. $ ] #ticket[Разложение котангенса в ряд.] #example[ Положим $f(z) = (ctg z) / z$ и подставим в теорему (почему $(ctg z) / z$ стремиться к $0$? написано в следующем билете, но храбров, кажется, перепутал порядок билетов, поэтому я перепутаю порядок примеров), $ (ctg z)/z = lim_(n -> oo) sum_(k: abs(a_k) < R_n) G_k (z). $ Особые точки $(ctg z)/z = (cos z)/(z sin z)$ --- корни знаменателя, где $0$ --- полюс второго порядка, и $pi k$ --- полюсы первого. Поэтому $ G_k (z) = res/(z - a_k) $ в полюсе первого порядка, и $ res_(z = pi k) (cos z)/(z sin z) = res_(z = pi k) ((cos z)/z)/(sin z) = lr(((cos z)/z) / (sin z)' |)_(z = pi k) = 1/(pi k). $ А $ (ctg z) / z = (cos z) / (z sin z) = (1 - O(z^2))/(z (z + O(z^3))) = 1/z^2 (1 - O(z^2)) (1 + O(z^2))^(-1) = (1 - O(z^2))^2/z^2 = 1/z^2 + O(1) $ Поэтому $ G_0 (z) = 1/z^2, $ Мы поняли, что $ (ctg z)/z = 1/(z^2) + sum_(k = 1)^oo (1/(pi k) dot 1/(z - pi k) + 1/(-pi k) dot 1/(z + pi k)) = 1/z^2 + sum_(k = 1)^oo 2/(z^2 - pi^2 k^2). $ Значит, $ ctg z = 1/z + sum_(k = 1)^oo (2 z)/(z^2 - pi^2 k^2). $ Это отличный ряд, который сходится во всех точках! ] #ticket[Оценка котангенса на окружностях и разложение синуса в бесконечное произведение.] #lemma[ $ctg z$ ограничен на окружностях $abs(z) = pi (n + 1/2)$. ] #proof[ $abs(ctg z)$ --- четная функция, поэтому достаточно смотреть на нее на $Re z >= 0$. Еще $abs(ctg(z))$ --- $pi$-периодическая. Сдвинем все в полосу $0 <= Re z <= pi$. Как? сами разберитесь, я это писать не буду. #figure(caption: [автору этой картинки крайне повезло, что я не знаю, как в vscode открыть git blame, потому что прикреплять в конспект png, тем более $424 times 424$ пикселя --- преступление])[ #image("../../images/ctg-limited.png", width: 10cm) ] Короче, потому говорим что на жопе у нас значения модуля котангенса не достигаются, потом говорим что из симметрии котангенса относительно $pi / 2$ можно не рассматривать все что ниже пояса, и затем надо разделить все остальное на трусы и все что выше, и тогда так как трусы --- компакт, то нам непрерывная функция ограничена, а в остальном стакане ${0 <= Re z <= pi "и " Im z >= 2}$ надо считать, $ abs(ctg z) = abs((cos z)/(sin z)) = abs((e^(i z) + e^(-i z))/(e^(i z) - e^(-i z))) = abs((e^y + e^(-y))/(e^y - e^(-y))) = abs((1 + e^(-2y))/(1 - e^(-2y))) <= (1 + e^(-4))/(1 - e^(-4)). $ $ #image("../../images/HUH.png") $ ] #follow[ Для фукнции $f(z) = (ctg z)/z$ на окружностях $pi (n + 1/2)$, $M_(R_n) --> 0$. ] #example[ Попробуем понять что-то про синус. Знаем $ (ln (sin z))' = ctg z, space (ln (sin z)/z)' = ctg z - 1/z, $ и, рассмотрев интеграл по любому пути из $0$ в $z$, $ ln (sin z)/z = integral_0^z (ctg w - 1/w) dif w = integral_0^z sum_(k = 1)^oo (2w)/(w^2 - k^2 pi^2) dif w =^? sum_(k = 1)^oo integral_0^z (2w)/(w^2 - k^2 pi^2) dif w newline(=) sum_(k = 1)^oo lr(ln(w^2 - pi^2 k^2) |)_0^z = sum_(k = 1)^oo ln ((z^2 - pi^2 k^2)/(-pi^2 k^2)) = sum_(k = 1)^oo ln(1 - z^2/(pi^2 k^2)). $ Осталось объяснить, почему можно: 1. Менять местами сумму с интегралом? Потому что у нас есть честная равномерная сходимость: $ abs(2w/(w^2 - pi^2 k^2)) <= 2R/(pi^2 k^2 - R^2) $ 2. Не думать об аргументе логарифма? Ну, да, можно не думать, очев. Ладно, давайте засунем наш ряд в экспоненту, и получим, $ sin z = z dot product_(k = 1)^oo (1 - z^2/(pi^2 k^2)). $ Это _разложение синуса в бесконечное произведение_ бывает полезно. ] #ticket[Вычисление сумм рядов (общая схема). Пример с рядом из обратных квадратов.] #example[ Давайте суммировать ряды --- что-то, что раньше мы почти не умели. Мы рассмотрим вот такой ряд, но идея будет работать и для многих других, $ sum_(n = 1)^oo 1/n^2. $ В общем случае, мы хотим смотреть на сумму как на сумму вычетов в каком-то комплексном интеграле. Сумма ищется по всем натуральным числам. У какой функции полюсы тоже находятся в натуральных числах? $ctg (pi z)$, например. И если мы считаем сумму голоморфной $f(n)$ в окрестности $z = n$, то так удачно получается, что $ res_(z = n) ctg(pi z) dot f(z) = lr((cos (pi z) dot f(z))/(sin (pi z))' |)_(z = n) = f(n)/pi. $ И, если мы суммируем по всем натуральным числам, то это как раз сумма вычетов в комплексном интеграле. То есть, $ integral_(abs(z) = n+1/2) ctg(pi z) f(z) dif z = 2 pi i (sum_(k = -n)^n (f(k))/pi + res_"остальные\nточки\nкруга" f(z)). $ Возвращаемся к $1/n^2$. Посчитаем интеграл по окружности $abs(z) = n+1/2$. Тогда полюсы у подынтегральной функцией в точках $k in ZZ$, и вычеты в $k$ и в $-k$ равны, поэтому $ integral_(abs(z) = n+1/2) ctg(pi z)/z^2 dif z = 2pi i (2/pi sum_(k=1)^n 1/k^2 + res_(z = 0) ctg(pi z)/z^2). $ Оценим интеграл, пользуясь ограниченностью котангенса: $ abs(integral_(abs(z) = n + 1/2) ctg(pi z)/z^2 dif z) <= 2pi (n + 1/2) M/(n+1/2)^2 -->_(n -> +oo) 0. $ Перейдя к пределу, $ sum_(k=1)^oo 1/k^2 = - pi/2 dot res_(z = 0) ctg(pi z)/z^2. $ Чтобы найти вычет, нужен коэффициент при $z$ у $ctg(pi z)$. Пишем ряды: $ #box(width: 30pt) ctg(pi z) = cos(pi z)/sin(pi z) = (1-(pi z)^2/2 + O(z^4))/(pi z (1 - (pi z)^2/6 + O(z^4))) newline(=) 1/(pi z) (1-(pi z)^2/2 + O(z^4)) dot (1 + (pi z)^2/6 + O(z^4)) = 1/(pi z) (1 - pi^2/3 z^2 + O(z^4)). $ воспользовавшишь тем, что до второго члена ряды делить легко: $ 1/(1+t + O(t^2)) = 1 - t + O(t^2). $ Значит, $ sum_(k=1)^oo 1/k^2 = - pi/2 dot res_(z = 0) ctg(pi z)/z^2 = (-pi/2) dot (-pi/3) = pi^2/6. $ ] #example[ Рассмотрим ряд $ sum_(k=1)^oo (-1)^k/k^2. $ Здесь подойдет функция $ 1/(sin pi z) dot 1/(z^2). $ Смотрим на вычеты: $ res_(z = n) 1/(sin pi z) dot 1/z^2 = lr(1/z^2 / (sin pi z)'|)_(z = n) = lr(1/z^2 / (pi cos pi z)|)_(z = n) = (-1)^n / (pi n^2). $ Считаем интеграл, $ 1/(2 pi i) integral 1/(sin pi z) 1/z^2 dif z = 2/pi sum_(k = 1)^n (-1)^k/k^2 + res_(z = 0). $ Как обычно оцениваем интеграл, сделайте сами: $ abs(integral 1/(sin pi z) 1/z^2 dif z) --> 0 $ Надо проверить, что $1/(sin pi z)$ ограничен на окружности $abs(z) = n + 1/2$. Давайте поверим в это наслово. Нужен коэффициент при $z$ у $1/(sin pi z)$: $ 1/(sin pi z) = 1/(pi z) dot 1/(1 - (pi z)^2/6 + O(z^4)) = (1 + (pi z)^2/6 + O(z^4))/(pi z). $ Отсюда, $ 2/pi sum_(k = 1)^n (-1)^k/k^2 = -res_(z = 0) = -pi/6 ==> sum_(k = 1)^n (-1)^k/k^2 = -pi^2/12. $ Для очень большого числа рядов этот метод подойдет. Но, вот для обратных кубов, скажем, нет, потому что это нечетная функция и вычеты друг друга сократят. А все четные степени посчитаются, хотя при больших степенях возиться с рядами придется больше. ] #ticket[Теорема о числе нулей и полюсов.] #th[ $f equiv.not 0$ --- мероморфна в $Omega$, $C$ --- простой замкнутый контур в $Omega$, не проходящий через нули и полюсы $f$. Тогда $ 1/(2pi i) integral_C (f'(z))/(f(z)) dif z = Nn_f - Pp_f, $ где $Nn_f$ --- количество нулей $f$, которые попали внутрь контура, с учетом кратности, и $Pp_f$ --- количество полюсов $f$, которые попали внутрь контура, с учетом порядка. ] #notice[ В контуре обязательно конечное число нулей и полюсов. В противном случае, так как внутренность контура (с его границей) --- компакт, можно найти сходящуюся последовательность из нулей или полюсов, внутри или на гранцице контура. Тогда в случае с нулями, по теореме о единственности, функция --- тождественный $0$, а в случае с полюсами, в предельной точке нет мероморфности (так как это не изолированная особая точка). ] #proof[ Считаем, $ 1/(2pi i) integral_C (f'(z))/(f(z)) dif z = sum res f'/f. $ Особые точки $f'/f$ --- нули и полюсы $f$. Пусть $a$ --- такая точка. Тогда и в нуле, и в полюсе, можно сказать $ f(z) = (z - a)^m g(z), $ где $g(a) != 0$, и $g$ голоморфна в окрестности $a$. В нуле $m$ --- кратность, а в полюсе $-m$ --- порядок полюса. Можно посчитать производную, $ f'(z) = m (z - a)^(m - 1) g(z) + (z - a)^m g'(z). $ Получается наша функция, это $ (f'(z))/f(z) = m/(z - a) + (g'(z))/g(z), $ и второе слагаемое голоморфное, потому что знаменатель не обнуляется в точке $a$. Значит вычет в точке $a$ равен $m$. Просуммировав по всем особым точкам, получим ровно $Nn_f - Pp_f$. ] #follow(plural: true)[ 1. Если $f in H(Omega)$, $C$ --- простой замкнутый контур, не проходящий через нули, то $ 1/(2pi i) integral_C (f'(z))/(f(z)) dif z = Nn_f. $ 2. Если $f in H(Omega)$, $C$ --- простой замкнутый контур, не проходящий через нули, то $ Nn_f = 1/(2 pi) Delta_C arg f, $ где $Delta_C arg_f$ --- изменение $arg f$ при движении по контуру. ] #proof[ 1. Очевидно. 2. $Ln f$ --- первообразная вдоль пути $C$ у $f'/f$, с параметризацией $gamma: [a, b] --> C$. То есть $ integral (f'(z))/(f(z)) dif z = lr(size: #2em, Ln f(gamma(t)) |)_(t = a)^(t = b) = lr(size: #2em, space (ln abs(f(gamma(t))) + i arg f(gamma(t))) |)_(t = a)^(t = b) = lr(size: #2em, i arg f(gamma(t)) |)_(t = a)^(t = b) = i Delta_C arg f. $ ] #ticket[Теорема Руше. Пример локализации корней.] #th(name: "Руше")[ $f, g in H(Omega)$, $C$ --- простой замкнутый контур в $Omega$, и $abs(f) > abs(g)$ на $C$. В частности, на контуре $abs(f) > 0$. Тогда количество нулей внутри $C$ (с учетом кратности) у функций $f$ и $f + g$ одинаково. ] #proof[ Надо доказать $Nn_f = Nn_(f + g)$, или $ 1/(2pi) Delta_C arg f = 1/(2pi) Delta_C arg (f + g). $ Оказывается, $ arg(f + g) = arg f dot (1 + g/f) = arg f + arg (1 + g/f). $ Надо доказать, что у $Delta_C arg(1 + g/f) = 0$. А мы знаем, что $abs(g/f) < 1$ на контуре. Поэтому $1 + g(z)/f(z)$ лежит на в круге $abs(w - 1) < 1$. Ну, двигаясь в таком круге по замкнутому контуру, мы точно полный оборот не сделаем. Значит, это и правда $0$. #TODO[картинка] ] #example[ Докажем, что уравнение $z + e^(-z) = lambda$ при $lambda > 1$ в правой полуплоскости имеет ровно одно решение. Проверим условие теоремы Руше в правом полукруге с центром в нуле. #TODO[картинка] Положим $f = z - lambda$, $g(z) = e^(-z)$. На мнимой оси $ abs(f(i y)) = abs(i y - lambda) = sqrt(y^2 + lambda^2) > lambda > 1, abs(g(i y)) = abs(e^(-i y)) = 1. $ На половинке окружности $ abs(f(R e^(i t))) = abs(R e^(i t) - lambda) >= R - lambda,\ abs(g(R e^(i t))) = abs(e^(-R e^(i t))) = abs(e^(-R cos t - i R sin t)) = e^(-R cos t) <= 1. $ Если $R > lambda + 1$, то нужное неравенство верно. Значит, по теореме Руше, количество нулей у $f + g$ равно количеству нулей в $f$, то есть 1. ] #exercise[ Вывести основную теорему алгебры из теоремы Руше. Указание: надо рассмотреть $f(z) = z^n$, а $g(z)$ --- все остальное. ]
https://github.com/ammar-ahmed22/compile-typst-example
https://raw.githubusercontent.com/ammar-ahmed22/compile-typst-example/main/src/quadratics.typ
typst
= Quadratics Quadratics are polynomials of degree 2. They are also known as parabolas. == Roots To find the roots of quadratic, the quadratic equation can be used: $ x = (-b plus.minus sqrt(b^2 - 4 a c)) / (2 a) $ where, $a$, $b$, and $c$ are the constants of the function, $f(x) = a x^2 + b x + c$.
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/171.%20re.html.typ
typst
re.html The Refragmentation January 2016One advantage of being old is that you can see change happen in your lifetime. A lot of the change I've seen is fragmentation. US politics is much more polarized than it used to be. Culturally we have ever less common ground. The creative class flocks to a handful of happy cities, abandoning the rest. And increasing economic inequality means the spread between rich and poor is growing too. I'd like to propose a hypothesis: that all these trends are instances of the same phenomenon. And moreover, that the cause is not some force that's pulling us apart, but rather the erosion of forces that had been pushing us together.Worse still, for those who worry about these trends, the forces that were pushing us together were an anomaly, a one-time combination of circumstances that's unlikely to be repeated — and indeed, that we would not want to repeat.The two forces were war (above all World War II), and the rise of large corporations.The effects of World War II were both economic and social. Economically, it decreased variation in income. Like all modern armed forces, America's were socialist economically. From each according to his ability, to each according to his need. More or less. Higher ranking members of the military got more (as higher ranking members of socialist societies always do), but what they got was fixed according to their rank. And the flattening effect wasn't limited to those under arms, because the US economy was conscripted too. Between 1942 and 1945 all wages were set by the National War Labor Board. Like the military, they defaulted to flatness. And this national standardization of wages was so pervasive that its effects could still be seen years after the war ended. [1]Business owners weren't supposed to be making money either. FDR said "not a single war millionaire" would be permitted. To ensure that, any increase in a company's profits over prewar levels was taxed at 85%. And when what was left after corporate taxes reached individuals, it was taxed again at a marginal rate of 93%. [2]Socially too the war tended to decrease variation. Over 16 million men and women from all sorts of different backgrounds were brought together in a way of life that was literally uniform. Service rates for men born in the early 1920s approached 80%. And working toward a common goal, often under stress, brought them still closer together.Though strictly speaking World War II lasted less than 4 years for the US, its effects lasted longer. Wars make central governments more powerful, and World War II was an extreme case of this. In the US, as in all the other Allied countries, the federal government was slow to give up the new powers it had acquired. Indeed, in some respects the war didn't end in 1945; the enemy just switched to the Soviet Union. In tax rates, federal power, defense spending, conscription, and nationalism, the decades after the war looked more like wartime than prewar peacetime. [3] And the social effects lasted too. The kid pulled into the army from behind a mule team in West Virginia didn't simply go back to the farm afterward. Something else was waiting for him, something that looked a lot like the army.If total war was the big political story of the 20th century, the big economic story was the rise of a new kind of company. And this too tended to produce both social and economic cohesion. [4]The 20th century was the century of the big, national corporation. General Electric, General Foods, General Motors. Developments in finance, communications, transportation, and manufacturing enabled a new type of company whose goal was above all scale. Version 1 of this world was low-res: a Duplo world of a few giant companies dominating each big market. [5]The late 19th and early 20th centuries had been a time of consolidation, led especially by <NAME>. Thousands of companies run by their founders were merged into a couple hundred giant ones run by professional managers. Economies of scale ruled the day. It seemed to people at the time that this was the final state of things. <NAME> said in 1880 The day of combination is here to stay. Individualism has gone, never to return. He turned out to be mistaken, but he seemed right for the next hundred years.The consolidation that began in the late 19th century continued for most of the 20th. By the end of World War II, as <NAME> writes, "the major sectors of the economy were either organized as government-backed cartels or dominated by a few oligopolistic corporations."For consumers this new world meant the same choices everywhere, but only a few of them. When I grew up there were only 2 or 3 of most things, and since they were all aiming at the middle of the market there wasn't much to differentiate them.One of the most important instances of this phenomenon was in TV. Here there were 3 choices: NBC, CBS, and ABC. Plus public TV for eggheads and communists. The programs that the 3 networks offered were indistinguishable. In fact, here there was a triple pressure toward the center. If one show did try something daring, local affiliates in conservative markets would make them stop. Plus since TVs were expensive, whole families watched the same shows together, so they had to be suitable for everyone.And not only did everyone get the same thing, they got it at the same time. It's difficult to imagine now, but every night tens of millions of families would sit down together in front of their TV set watching the same show, at the same time, as their next door neighbors. What happens now with the Super Bowl used to happen every night. We were literally in sync. [6]In a way mid-century TV culture was good. The view it gave of the world was like you'd find in a children's book, and it probably had something of the effect that (parents hope) children's books have in making people behave better. But, like children's books, TV was also misleading. Dangerously misleading, for adults. In his autobiography, <NAME> talks of seeing gruesome images that had just come in from Vietnam and thinking, we can't show these to families while they're having dinner.I know how pervasive the common culture was, because I tried to opt out of it, and it was practically impossible to find alternatives. When I was 13 I realized, more from internal evidence than any outside source, that the ideas we were being fed on TV were crap, and I stopped watching it. [7] But it wasn't just TV. It seemed like everything around me was crap. The politicians all saying the same things, the consumer brands making almost identical products with different labels stuck on to indicate how prestigious they were meant to be, the balloon-frame houses with fake "colonial" skins, the cars with several feet of gratuitous metal on each end that started to fall apart after a couple years, the "red delicious" apples that were red but only nominally apples. And in retrospect, it was crap. [8]But when I went looking for alternatives to fill this void, I found practically nothing. There was no Internet then. The only place to look was in the chain bookstore in our local shopping mall. [9] There I found a copy of The Atlantic. I wish I could say it became a gateway into a wider world, but in fact I found it boring and incomprehensible. Like a kid tasting whisky for the first time and pretending to like it, I preserved that magazine as carefully as if it had been a book. I'm sure I still have it somewhere. But though it was evidence that there was, somewhere, a world that wasn't red delicious, I didn't find it till college.It wasn't just as consumers that the big companies made us similar. They did as employers too. Within companies there were powerful forces pushing people toward a single model of how to look and act. IBM was particularly notorious for this, but they were only a little more extreme than other big companies. And the models of how to look and act varied little between companies. Meaning everyone within this world was expected to seem more or less the same. And not just those in the corporate world, but also everyone who aspired to it — which in the middle of the 20th century meant most people who weren't already in it. For most of the 20th century, working-class people tried hard to look middle class. You can see it in old photos. Few adults aspired to look dangerous in 1950.But the rise of national corporations didn't just compress us culturally. It compressed us economically too, and on both ends.Along with giant national corporations, we got giant national labor unions. And in the mid 20th century the corporations cut deals with the unions where they paid over market price for labor. Partly because the unions were monopolies. [10] Partly because, as components of oligopolies themselves, the corporations knew they could safely pass the cost on to their customers, because their competitors would have to as well. And partly because in mid-century most of the giant companies were still focused on finding new ways to milk economies of scale. Just as startups rightly pay AWS a premium over the cost of running their own servers so they can focus on growth, many of the big national corporations were willing to pay a premium for labor. [11]As well as pushing incomes up from the bottom, by overpaying unions, the big companies of the 20th century also pushed incomes down at the top, by underpaying their top management. Economist <NAME> wrote in 1967 that "There are few corporations in which it would be suggested that executive salaries are at a maximum." [12]To some extent this was an illusion. Much of the de facto pay of executives never showed up on their income tax returns, because it took the form of perks. The higher the rate of income tax, the more pressure there was to pay employees upstream of it. (In the UK, where taxes were even higher than in the US, companies would even pay their kids' private school tuitions.) One of the most valuable things the big companies of the mid 20th century gave their employees was job security, and this too didn't show up in tax returns or income statistics. So the nature of employment in these organizations tended to yield falsely low numbers about economic inequality. But even accounting for that, the big companies paid their best people less than market price. There was no market; the expectation was that you'd work for the same company for decades if not your whole career. [13]Your work was so illiquid there was little chance of getting market price. But that same illiquidity also encouraged you not to seek it. If the company promised to employ you till you retired and give you a pension afterward, you didn't want to extract as much from it this year as you could. You needed to take care of the company so it could take care of you. Especially when you'd been working with the same group of people for decades. If you tried to squeeze the company for more money, you were squeezing the organization that was going to take care of them. Plus if you didn't put the company first you wouldn't be promoted, and if you couldn't switch ladders, promotion on this one was the only way up. [14]To someone who'd spent several formative years in the armed forces, this situation didn't seem as strange as it does to us now. From their point of view, as big company executives, they were high-ranking officers. They got paid a lot more than privates. They got to have expense account lunches at the best restaurants and fly around on the company's Gulfstreams. It probably didn't occur to most of them to ask if they were being paid market price.The ultimate way to get market price is to work for yourself, by starting your own company. That seems obvious to any ambitious person now. But in the mid 20th century it was an alien concept. Not because starting one's own company seemed too ambitious, but because it didn't seem ambitious enough. Even as late as the 1970s, when I grew up, the ambitious plan was to get lots of education at prestigious institutions, and then join some other prestigious institution and work one's way up the hierarchy. Your prestige was the prestige of the institution you belonged to. People did start their own businesses of course, but educated people rarely did, because in those days there was practically zero concept of starting what we now call a startup: a business that starts small and grows big. That was much harder to do in the mid 20th century. Starting one's own business meant starting a business that would start small and stay small. Which in those days of big companies often meant scurrying around trying to avoid being trampled by elephants. It was more prestigious to be one of the executive class riding the elephant.By the 1970s, no one stopped to wonder where the big prestigious companies had come from in the first place. It seemed like they'd always been there, like the chemical elements. And indeed, there was a double wall between ambitious kids in the 20th century and the origins of the big companies. Many of the big companies were roll-ups that didn't have clear founders. And when they did, the founders didn't seem like us. Nearly all of them had been uneducated, in the sense of not having been to college. They were what Shakespeare called rude mechanicals. College trained one to be a member of the professional classes. Its graduates didn't expect to do the sort of grubby menial work that <NAME> or <NAME> started out doing. [15]And in the 20th century there were more and more college graduates. They increased from about 2% of the population in 1900 to about 25% in 2000. In the middle of the century our two big forces intersect, in the form of the GI Bill, which sent 2.2 million World War II veterans to college. Few thought of it in these terms, but the result of making college the canonical path for the ambitious was a world in which it was socially acceptable to work for <NAME>, but not to be <NAME>. [16]I remember this world well. I came of age just as it was starting to break up. In my childhood it was still dominant. Not quite so dominant as it had been. We could see from old TV shows and yearbooks and the way adults acted that people in the 1950s and 60s had been even more conformist than us. The mid-century model was already starting to get old. But that was not how we saw it at the time. We would at most have said that one could be a bit more daring in 1975 than 1965. And indeed, things hadn't changed much yet.But change was coming soon. And when the Duplo economy started to disintegrate, it disintegrated in several different ways at once. Vertically integrated companies literally dis-integrated because it was more efficient to. Incumbents faced new competitors as (a) markets went global and (b) technical innovation started to trump economies of scale, turning size from an asset into a liability. Smaller companies were increasingly able to survive as formerly narrow channels to consumers broadened. Markets themselves started to change faster, as whole new categories of products appeared. And last but not least, the federal government, which had previously smiled upon <NAME>'s world as the natural state of things, began to realize it wasn't the last word after all.What <NAME> was to the horizontal axis, <NAME> was to the vertical. He wanted to do everything himself. The giant plant he built at River Rouge between 1917 and 1928 literally took in iron ore at one end and sent cars out the other. 100,000 people worked there. At the time it seemed the future. But that is not how car companies operate today. Now much of the design and manufacturing happens in a long supply chain, whose products the car companies ultimately assemble and sell. The reason car companies operate this way is that it works better. Each company in the supply chain focuses on what they know best. And they each have to do it well or they can be swapped out for another supplier.Why didn't <NAME> realize that networks of cooperating companies work better than a single big company? One reason is that supplier networks take a while to evolve. In 1917, doing everything himself seemed to Ford the only way to get the scale he needed. And the second reason is that if you want to solve a problem using a network of cooperating companies, you have to be able to coordinate their efforts, and you can do that much better with computers. Computers reduce the transaction costs that Coase argued are the raison d'etre of corporations. That is a fundamental change.In the early 20th century, big companies were synonymous with efficiency. In the late 20th century they were synonymous with inefficiency. To some extent this was because the companies themselves had become sclerotic. But it was also because our standards were higher.It wasn't just within existing industries that change occurred. The industries themselves changed. It became possible to make lots of new things, and sometimes the existing companies weren't the ones who did it best.Microcomputers are a classic example. The market was pioneered by upstarts like Apple. When it got big enough, IBM decided it was worth paying attention to. At the time IBM completely dominated the computer industry. They assumed that all they had to do, now that this market was ripe, was to reach out and pick it. Most people at the time would have agreed with them. But what happened next illustrated how much more complicated the world had become. IBM did launch a microcomputer. Though quite successful, it did not crush Apple. But even more importantly, IBM itself ended up being supplanted by a supplier coming in from the side — from software, which didn't even seem to be the same business. IBM's big mistake was to accept a non-exclusive license for DOS. It must have seemed a safe move at the time. No other computer manufacturer had ever been able to outsell them. What difference did it make if other manufacturers could offer DOS too? The result of that miscalculation was an explosion of inexpensive PC clones. Microsoft now owned the PC standard, and the customer. And the microcomputer business ended up being Apple vs Microsoft.Basically, Apple bumped IBM and then Microsoft stole its wallet. That sort of thing did not happen to big companies in mid-century. But it was going to happen increasingly often in the future.Change happened mostly by itself in the computer business. In other industries, legal obstacles had to be removed first. Many of the mid-century oligopolies had been anointed by the federal government with policies (and in wartime, large orders) that kept out competitors. This didn't seem as dubious to government officials at the time as it sounds to us. They felt a two-party system ensured sufficient competition in politics. It ought to work for business too.Gradually the government realized that anti-competitive policies were doing more harm than good, and during the Carter administration it started to remove them. The word used for this process was misleadingly narrow: deregulation. What was really happening was de-oligopolization. It happened to one industry after another. Two of the most visible to consumers were air travel and long-distance phone service, which both became dramatically cheaper after deregulation.Deregulation also contributed to the wave of hostile takeovers in the 1980s. In the old days the only limit on the inefficiency of companies, short of actual bankruptcy, was the inefficiency of their competitors. Now companies had to face absolute rather than relative standards. Any public company that didn't generate sufficient returns on its assets risked having its management replaced with one that would. Often the new managers did this by breaking companies up into components that were more valuable separately. [17]Version 1 of the national economy consisted of a few big blocks whose relationships were negotiated in back rooms by a handful of executives, politicians, regulators, and labor leaders. Version 2 was higher resolution: there were more companies, of more different sizes, making more different things, and their relationships changed faster. In this world there were still plenty of back room negotiations, but more was left to market forces. Which further accelerated the fragmentation.It's a little misleading to talk of versions when describing a gradual process, but not as misleading as it might seem. There was a lot of change in a few decades, and what we ended up with was qualitatively different. The companies in the S&P 500 in 1958 had been there an average of 61 years. By 2012 that number was 18 years. [18]The breakup of the Duplo economy happened simultaneously with the spread of computing power. To what extent were computers a precondition? It would take a book to answer that. Obviously the spread of computing power was a precondition for the rise of startups. I suspect it was for most of what happened in finance too. But was it a precondition for globalization or the LBO wave? I don't know, but I wouldn't discount the possibility. It may be that the refragmentation was driven by computers in the way the industrial revolution was driven by steam engines. Whether or not computers were a precondition, they have certainly accelerated it.The new fluidity of companies changed people's relationships with their employers. Why climb a corporate ladder that might be yanked out from under you? Ambitious people started to think of a career less as climbing a single ladder than as a series of jobs that might be at different companies. More movement (or even potential movement) between companies introduced more competition in salaries. Plus as companies became smaller it became easier to estimate how much an employee contributed to the company's revenue. Both changes drove salaries toward market price. And since people vary dramatically in productivity, paying market price meant salaries started to diverge.By no coincidence it was in the early 1980s that the term "yuppie" was coined. That word is not much used now, because the phenomenon it describes is so taken for granted, but at the time it was a label for something novel. Yuppies were young professionals who made lots of money. To someone in their twenties today, this wouldn't seem worth naming. Why wouldn't young professionals make lots of money? But until the 1980s, being underpaid early in your career was part of what it meant to be a professional. Young professionals were paying their dues, working their way up the ladder. The rewards would come later. What was novel about yuppies was that they wanted market price for the work they were doing now.The first yuppies did not work for startups. That was still in the future. Nor did they work for big companies. They were professionals working in fields like law, finance, and consulting. But their example rapidly inspired their peers. Once they saw that new BMW 325i, they wanted one too.Underpaying people at the beginning of their career only works if everyone does it. Once some employer breaks ranks, everyone else has to, or they can't get good people. And once started this process spreads through the whole economy, because at the beginnings of people's careers they can easily switch not merely employers but industries.But not all young professionals benefitted. You had to produce to get paid a lot. It was no coincidence that the first yuppies worked in fields where it was easy to measure that.More generally, an idea was returning whose name sounds old-fashioned precisely because it was so rare for so long: that you could make your fortune. As in the past there were multiple ways to do it. Some made their fortunes by creating wealth, and others by playing zero-sum games. But once it became possible to make one's fortune, the ambitious had to decide whether or not to. A physicist who chose physics over Wall Street in 1990 was making a sacrifice that a physicist in 1960 didn't have to think about.The idea even flowed back into big companies. CEOs of big companies make more now than they used to, and I think much of the reason is prestige. In 1960, corporate CEOs had immense prestige. They were the winners of the only economic game in town. But if they made as little now as they did then, in real dollar terms, they'd seem like small fry compared to professional athletes and whiz kids making millions from startups and hedge funds. They don't like that idea, so now they try to get as much as they can, which is more than they had been getting. [19]Meanwhile a similar fragmentation was happening at the other end of the economic scale. As big companies' oligopolies became less secure, they were less able to pass costs on to customers and thus less willing to overpay for labor. And as the Duplo world of a few big blocks fragmented into many companies of different sizes — some of them overseas — it became harder for unions to enforce their monopolies. As a result workers' wages also tended toward market price. Which (inevitably, if unions had been doing their job) tended to be lower. Perhaps dramatically so, if automation had decreased the need for some kind of work.And just as the mid-century model induced social as well as economic cohesion, its breakup brought social as well as economic fragmentation. People started to dress and act differently. Those who would later be called the "creative class" became more mobile. People who didn't care much for religion felt less pressure to go to church for appearances' sake, while those who liked it a lot opted for increasingly colorful forms. Some switched from meat loaf to tofu, and others to Hot Pockets. Some switched from driving Ford sedans to driving small imported cars, and others to driving SUVs. Kids who went to private schools or wished they did started to dress "preppy," and kids who wanted to seem rebellious made a conscious effort to look disreputable. In a hundred ways people spread apart. [20]Almost four decades later, fragmentation is still increasing. Has it been net good or bad? I don't know; the question may be unanswerable. Not entirely bad though. We take for granted the forms of fragmentation we like, and worry only about the ones we don't. But as someone who caught the tail end of mid-century conformism, I can tell you it was no utopia. [21]My goal here is not to say whether fragmentation has been good or bad, just to explain why it's happening. With the centripetal forces of total war and 20th century oligopoly mostly gone, what will happen next? And more specifically, is it possible to reverse some of the fragmentation we've seen?If it is, it will have to happen piecemeal. You can't reproduce mid-century cohesion the way it was originally produced. It would be insane to go to war just to induce more national unity. And once you understand the degree to which the economic history of the 20th century was a low-res version 1, it's clear you can't reproduce that either.20th century cohesion was something that happened at least in a sense naturally. The war was due mostly to external forces, and the Duplo economy was an evolutionary phase. If you want cohesion now, you'd have to induce it deliberately. And it's not obvious how. I suspect the best we'll be able to do is address the symptoms of fragmentation. But that may be enough.The form of fragmentation people worry most about lately is economic inequality, and if you want to eliminate that you're up against a truly formidable headwind that has been in operation since the stone age. Technology.Technology is a lever. It magnifies work. And the lever not only grows increasingly long, but the rate at which it grows is itself increasing.Which in turn means the variation in the amount of wealth people can create has not only been increasing, but accelerating. The unusual conditions that prevailed in the mid 20th century masked this underlying trend. The ambitious had little choice but to join large organizations that made them march in step with lots of other people — literally in the case of the armed forces, figuratively in the case of big corporations. Even if the big corporations had wanted to pay people proportionate to their value, they couldn't have figured out how. But that constraint has gone now. Ever since it started to erode in the 1970s, we've seen the underlying forces at work again. [22]Not everyone who gets rich now does it by creating wealth, certainly. But a significant number do, and the Baumol Effect means all their peers get dragged along too. [23] And as long as it's possible to get rich by creating wealth, the default tendency will be for economic inequality to increase. Even if you eliminate all the other ways to get rich. You can mitigate this with subsidies at the bottom and taxes at the top, but unless taxes are high enough to discourage people from creating wealth, you're always going to be fighting a losing battle against increasing variation in productivity. [24]That form of fragmentation, like the others, is here to stay. Or rather, back to stay. Nothing is forever, but the tendency toward fragmentation should be more forever than most things, precisely because it's not due to any particular cause. It's simply a reversion to the mean. When Rockefeller said individualism was gone, he was right for a hundred years. It's back now, and that's likely to be true for longer.I worry that if we don't acknowledge this, we're headed for trouble. If we think 20th century cohesion disappeared because of few policy tweaks, we'll be deluded into thinking we can get it back (minus the bad parts, somehow) with a few countertweaks. And then we'll waste our time trying to eliminate fragmentation, when we'd be better off thinking about how to mitigate its consequences. Notes[1] <NAME>, writing in 1975, said the wage differentials prevailing at the end of World War II had become so embedded that they "were regarded as 'just' even after the egalitarian pressures of World War II had disappeared. Basically, the same differentials exist to this day, thirty years later." But Goldin and Margo think market forces in the postwar period also helped preserve the wartime compression of wages — specifically increased demand for unskilled workers, and oversupply of educated ones.(Oddly enough, the American custom of having employers pay for health insurance derives from efforts by businesses to circumvent NWLB wage controls in order to attract workers.)[2] As always, tax rates don't tell the whole story. There were lots of exemptions, especially for individuals. And in World War II the tax codes were so new that the government had little acquired immunity to tax avoidance. If the rich paid high taxes during the war it was more because they wanted to than because they had to.After the war, federal tax receipts as a percentage of GDP were about the same as they are now. In fact, for the entire period since the war, tax receipts have stayed close to 18% of GDP, despite dramatic changes in tax rates. The lowest point occurred when marginal income tax rates were highest: 14.1% in 1950. Looking at the data, it's hard to avoid the conclusion that tax rates have had little effect on what people actually paid.[3] Though in fact the decade preceding the war had been a time of unprecedented federal power, in response to the Depression. Which is not entirely a coincidence, because the Depression was one of the causes of the war. In many ways the New Deal was a sort of dress rehearsal for the measures the federal government took during wartime. The wartime versions were much more drastic and more pervasive though. As <NAME> wrote, "for many Americans the decisive change in their experiences came not with the New Deal but with World War II."[4] I don't know enough about the origins of the world wars to say, but it's not inconceivable they were connected to the rise of big corporations. If that were the case, 20th century cohesion would have a single cause.[5] More precisely, there was a bimodal economy consisting, in Galbraith's words, of "the world of the technically dynamic, massively capitalized and highly organized corporations on the one hand and the hundreds of thousands of small and traditional proprietors on the other." Money, prestige, and power were concentrated in the former, and there was near zero crossover.[6] I wonder how much of the decline in families eating together was due to the decline in families watching TV together afterward.[7] I know when this happened because it was the season Dallas premiered. Everyone else was talking about what was happening on Dallas, and I had no idea what they meant.[8] I didn't realize it till I started doing research for this essay, but the meretriciousness of the products I grew up with is a well-known byproduct of oligopoly. When companies can't compete on price, they compete on tailfins.[9] Monroeville Mall was at the time of its completion in 1969 the largest in the country. In the late 1970s the movie Dawn of the Dead was shot there. Apparently the mall was not just the location of the movie, but its inspiration; the crowds of shoppers drifting through this huge mall reminded George Romero of zombies. My first job was scooping ice cream in the Baskin-Robbins.[10] Labor unions were exempted from antitrust laws by the Clayton Antitrust Act in 1914 on the grounds that a person's work is not "a commodity or article of commerce." I wonder if that means service companies are also exempt.[11] The relationships between unions and unionized companies can even be symbiotic, because unions will exert political pressure to protect their hosts. According to <NAME>, when politicians tried to attack the A&P supermarket chain because it was putting local grocery stores out of business, "A&P successfully defended itself by allowing the unionization of its workforce in 1938, thereby gaining organized labor as a constituency." I've seen this phenomenon myself: hotel unions are responsible for more of the political pressure against Airbnb than hotel companies.[12] Galbraith was clearly puzzled that corporate executives would work so hard to make money for other people (the shareholders) instead of themselves. He devoted much of The New Industrial State to trying to figure this out.His theory was that professionalism had replaced money as a motive, and that modern corporate executives were, like (good) scientists, motivated less by financial rewards than by the desire to do good work and thereby earn the respect of their peers. There is something in this, though I think lack of movement between companies combined with self-interest explains much of observed behavior.[13] Galbraith (p. 94) says a 1952 study of the 800 highest paid executives at 300 big corporations found that three quarters of them had been with their company for more than 20 years.[14] It seems likely that in the first third of the 20th century executive salaries were low partly because companies then were more dependent on banks, who would have disapproved if executives got too much. This was certainly true in the beginning. The first big company CEOs were <NAME>'s hired hands.Companies didn't start to finance themselves with retained earnings till the 1920s. Till then they had to pay out their earnings in dividends, and so depended on banks for capital for expansion. Bankers continued to sit on corporate boards till the Glass-Steagall act in 1933.By mid-century big companies funded 3/4 of their growth from earnings. But the early years of bank dependence, reinforced by the financial controls of World War II, must have had a big effect on social conventions about executive salaries. So it may be that the lack of movement between companies was as much the effect of low salaries as the cause.Incidentally, the switch in the 1920s to financing growth with retained earnings was one cause of the 1929 crash. The banks now had to find someone else to lend to, so they made more margin loans.[15] Even now it's hard to get them to. One of the things I find hardest to get into the heads of would-be startup founders is how important it is to do certain kinds of menial work early in the life of a company. Doing things that don't scale is to how <NAME> got started as a high-fiber diet is to the traditional peasant's diet: they had no choice but to do the right thing, while we have to make a conscious effort.[16] Founders weren't celebrated in the press when I was a kid. "Our founder" meant a photograph of a severe-looking man with a walrus mustache and a wing collar who had died decades ago. The thing to be when I was a kid was an executive. If you weren't around then it's hard to grasp the cachet that term had. The fancy version of everything was called the "executive" model.[17] The wave of hostile takeovers in the 1980s was enabled by a combination of circumstances: court decisions striking down state anti-takeover laws, starting with the Supreme Court's 1982 decision in Edgar v. MITE Corp.; the Reagan administration's comparatively sympathetic attitude toward takeovers; the Depository Institutions Act of 1982, which allowed banks and savings and loans to buy corporate bonds; a new SEC rule issued in 1982 (rule 415) that made it possible to bring corporate bonds to market faster; the creation of the junk bond business by <NAME>; a vogue for conglomerates in the preceding period that caused many companies to be combined that never should have been; a decade of inflation that left many public companies trading below the value of their assets; and not least, the increasing complacency of managements.[18] <NAME>. "Creative Destruction Whips through Corporate America." Innosight, February 2012.[19] CEOs of big companies may be overpaid. I don't know enough about big companies to say. But it is certainly not impossible for a CEO to make 200x as much difference to a company's revenues as the average employee. Look at what <NAME> did for Apple when he came back as CEO. It would have been a good deal for the board to give him 95% of the company. Apple's market cap the day Steve came back in July 1997 was 1.73 billion. 5% of Apple now (January 2016) would be worth about 30 billion. And it would not be if Steve hadn't come back; Apple probably wouldn't even exist anymore.Merely including Steve in the sample might be enough to answer the question of whether public company CEOs in the aggregate are overpaid. And that is not as facile a trick as it might seem, because the broader your holdings, the more the aggregate is what you care about.[20] The late 1960s were famous for social upheaval. But that was more rebellion (which can happen in any era if people are provoked sufficiently) than fragmentation. You're not seeing fragmentation unless you see people breaking off to both left and right.[21] Globally the trend has been in the other direction. While the US is becoming more fragmented, the world as a whole is becoming less fragmented, and mostly in good ways.[22] There were a handful of ways to make a fortune in the mid 20th century. The main one was drilling for oil, which was open to newcomers because it was not something big companies could dominate through economies of scale. How did individuals accumulate large fortunes in an era of such high taxes? Giant tax loopholes defended by two of the most powerful men in Congress, <NAME> and <NAME>.But becoming a Texas oilman was not in 1950 something one could aspire to the way starting a startup or going to work on Wall Street were in 2000, because (a) there was a strong local component and (b) success depended so much on luck.[23] The Baumol Effect induced by startups is very visible in Silicon Valley. Google will pay people millions of dollars a year to keep them from leaving to start or join startups.[24] I'm not claiming variation in productivity is the only cause of economic inequality in the US. But it's a significant cause, and it will become as big a cause as it needs to, in the sense that if you ban other ways to get rich, people who want to get rich will use this route instead.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this. Max also told me about several valuable sources.BibliographyAllen, <NAME>. The Big Change. Harper, 1952.Averitt, Robert. The Dual Economy. Norton, 1968.Badger, Anthony. The New Deal. Hill and Wang, 1989.Bainbridge, John. The Super-Americans. Doubleday, 1961.Beatty, <NAME>. Broadway, 2001.Brinkley, Douglas. Wheels for the World. Viking, 2003.Brownleee, <NAME>. Federal Taxation in America. Cambridge, 1996.Chandler, Alfred. The Visible Hand. Harvard, 1977.Chernow, Ron. The House of Morgan. Simon & Schuster, 1990.Chernow, Ron. Titan: The Life of <NAME>. Random House, 1998.Galbraith, John. The New Industrial State. <NAME>, 1967.Goldin, Claudia and <NAME>. "The Great Compression: The Wage Structure in the United States at Mid-Century." NBER Working Paper 3817, 1991.Gordon, John. An Empire of Wealth. HarperCollins, 2004.Klein, Maury. The Genesis of Industrial America, 1870-1920. Cambridge, 2007.Lind, Michael. Land of Promise. HarperCollins, 2012.Mickelthwaite, John, and <NAME>. The Company. Modern Library, 2003.Nasaw, David. <NAME>. Penguin, 2006.Sobel, Robert. The Age of Giant Corporations. Praeger, 1993.Thurow, Lester. Generating Inequality: Mechanisms of Distribution. Basic Books, 1975.Witte, John. The Politics and Development of the Federal Income Tax. Wisconsin, 1985.Related:Too Many Elite American Men Are Obsessed With Work and Wealth
https://github.com/Myriad-Dreamin/shiroa
https://raw.githubusercontent.com/Myriad-Dreamin/shiroa/main/github-pages/docs/guide/get-started.typ
typst
Apache License 2.0
#import "/github-pages/docs/book.typ": book-page #show: book-page.with(title: "Get Started") = Creating a Book Once you have the `shiroa` CLI tool installed, you can use it to create and render a book. == Initializing a book The `shiroa init` command will create a new directory containing an empty book for you to get started. Give it the name of the directory that you want to create: ```sh shiroa init my-first-book ``` It will ask a few questions before generating the book. After answering the questions, you can change the current directory into the new book: ```sh cd my-first-book ``` There are several ways to render a book, but one of the easiest methods is to use the `serve` command, which will build your book and start a local webserver: ```sh shiroa serve ``` // The `--open` option will open your default web browser to view your new book. // You can leave the server running even while you edit the content of the book, and `shiroa` will automatically rebuild the output *and* automatically refresh your web browser. Check out the `shiroa help` for more information about other `shiroa` commands and CLI options. == Anatomy of a book A book is built from several files which define the settings and layout of the book. === `book.typ` If you are familiar with `mdbook`, the `book.typ` file is similar to the `book.toml` with `summary.md` file. The book source file is the main file located at `src/book.typ`. This file contains a list of all the chapters in the book. Before a chapter can be viewed, it must be added to this list. Here's a basic summary file with a few chapters: ```typ #import "@preview/shiroa:0.1.1": * #show: book #book-meta( // put metadata of your book like book.toml of mdbook title: "shiroa", description: "shiroa Documentation", repository: "https://github.com/Myriad-Dreamin/shiroa", authors: ("Myriad-Dreamin", "7mile"), language: "en", summary: [ // this field works like summary.md of mdbook = Introduction - #chapter("guide/installation.typ", section: "1.1")[Installation] - #chapter("guide/get-started.typ", section: "1.2")[Get Started] - #chapter(none, section: "1.2.1")[Drafting chapter] ] ) ``` Try opening up `src/book.typ` in your editor and adding a few chapters. // If any of the chapter files do not exist, `shiroa` will automatically create them for you. // For more details on other formatting options for the summary file, check out the [Summary chapter](../format/summary.typ). === Source files The content of your book is all contained in the `src` directory. Each chapter is a separate Typst file. Typically, each chapter starts with a level 1 heading with the title of the chapter. ```typ = My First Chapter Fill out your content here. ``` The precise layout of the files is up to you. The organization of the files will correspond to the HTML files generated, so keep in mind that the file layout is part of the URL of each chapter. // While the `shiroa serve` command is running, you can open any of the chapter files and start editing them. // Each time you save the file, `shiroa` will rebuild the book and refresh your web browser. // Check out the #link("https://rust-lang.github.io/myriad-dreamin/shiroa/format/typst.html")[Typst chapter] for more information on formatting the content of your chapters. All other files in the `src` directory will be included in the output. So if you have images or other static files, just include them somewhere in the `src` directory. == Publishing a book Once you've written your book, you may want to host it somewhere for others to view. The first step is to build the output of the book. This can be done with the `shiroa build` command in the same directory where the `book.toml` file is located: ```sh shiroa build ``` This will generate a directory named `book` which contains the HTML content of your book. You can then place this directory on any web server to host it. // For more information about publishing and deploying, check out the [Continuous Integration chapter](../continuous-integration.typ) for more.
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/examples/composition.typ
typst
MIT License
#import "../src/quill.typ": * #import tequila as tq #quantum-circuit( ..tq.graph-state((0, 1), (1,2)), ..tq.build(y: 3, tq.p($pi$, 0), tq.cx(0, (1, 2)), ), ..tq.graph-state(x: 6, y: 2, invert: true, (0, 1), (0, 2)), gategroup(x: 1, 3, 3), gategroup(x: 1, y: 3, 3, 3), gategroup(x: 6, y: 2, 3, 3), slice(x: 5) )
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Anhang/04_Projektdokumentation/01_reviews.typ
typst
=== Review-Meeting Protokolle <appendixReviews>
https://github.com/donabe8898/typst-thesis-template
https://raw.githubusercontent.com/donabe8898/typst-thesis-template/main/lib/macro.typ
typst
Apache License 2.0
// custom #let bl(it) = text(weight: "bold")[#it] #let lt(it) = text(font: "Latin Modern Roman")[#it] #let sm(it) = { set text(size: 0.8em) it } #let latex = text( font: "Latin Modern Roman", [L#h(-0.35em)#text(size: 0.725em, baseline: -0.25em)[A]#h(-0.125em)T#h(-0.175em)#text(baseline: 0.225em)[E]#h(-0.125em)X] ) #let ul(it) = box(stroke: (bottom: 0.1em), inset: 0pt, outset: (bottom: 0.25em))[#it]
https://github.com/GeorgeMuscat/secret
https://raw.githubusercontent.com/GeorgeMuscat/secret/main/lib.typ
typst
MIT License
A simple package to keep your secrets. #let redact(text, fill: black, height: 1em) = { box(rect(fill: fill, height: height)[#hide(text)]) } Example: - Unredacted text - Redacted #redact("text")
https://github.com/brainworkup/neurotyp-adult
https://raw.githubusercontent.com/brainworkup/neurotyp-adult/main/_extensions/neurotyp-adult/typst-template.typ
typst
MIT License
#let report( title: "NEUROCOGNITIVE EXAMINATION", author: "<NAME>, Ph.D.", name: [], doe: [], patient: [], date: none, cols: 1, paper: "a4", margin: (x: 25mm, y: 30mm), lang: "en", region: "US", font: (), body-font: ("Libertinus Serif"), sans-font: ("Libertinus Sans"), fontsize: 11pt, sectionnumbering: none, doc, ) = { // Metadata set document(title: title, author: author) // Set page size, margins, and header. set page( paper: paper, margin: margin, header: locate(loc => if [#loc.page()] == [1] { [] } else { [ #set par(leading: 0.65em) #set text(9pt) #smallcaps[ *CONFIDENTIAL* \ #name \ #doe ] ] }), numbering: "1", number-align: center, columns: cols, ) // align headers show heading.where(level: 0): set align(center) show heading.where(level: 1): set align(left) // Set paragraph justification and leading. set par(justify: true) // set par(leading: 1em) set par(linebreaks: "optimized") // Set text and body font family. set text(font: body-font, size: fontsize, lang: lang, region: region) show math.equation: set text(weight: 400) // Set heading numbering. set heading(numbering: sectionnumbering) // Set heading font. show heading: set text(font: sans-font, weight: "semibold") // Set run-in subheadings, starting at level 4. show heading: it => { if it.level > 3 { parbreak() text(1em, style: "italic", weight: "regular", it.body + ":") } else { it } } show link: set text(font: body-font, fill: rgb(4, 1, 23), weight: 450) show link: underline // Logo block(figure(image("src/img/logo.png"))) // block(figure(image("src/img/bwu_logo.png"))) // Title row. align(center)[ #block(text(font: sans-font, weight: 600, 1.75em, title)) #v(0em, weak: true) ] if date != none { align(center)[#block(inset: 1em)[ #date ]] } if cols == 1 { doc } else { columns(cols, doc) } }
https://github.com/peterpf/modern-typst-resume
https://raw.githubusercontent.com/peterpf/modern-typst-resume/main/README.md
markdown
The Unlicense
# A modern typst CV template [![say thanks](https://img.shields.io/badge/Say%20Thanks-👍-1EAEDB.svg)](https://github.com/peterpf/modern-typst-resume/stargazers) A customizable resume/CV template focusing on clean and concise presentation, with a touch of color. **This template is available on [typst Universe](https://typst.app/universe/package/modern-resume)!** ## Requirements To compile this project you need the following: - [typst](https://github.com/typst/typst) - [Roboto font family](https://fonts.google.com/specimen/Roboto) ## Compiling Build the document once with ```bash typst compile main.typ ``` Build the document whenever you save changes by running ```bash typst watch main.typ ``` ## Usage The following code provides a minimum working example: ```typst #import "@preview/modern-resume": * #show: modern-resume.with( author: "<NAME>", job-title: "Data Scientist", bio: lorem(5), avatar: image("avatar.png"), contact-options: ( email: link("mailto:<EMAIL>")[<EMAIL>], mobile: "+43 1234 5678", location: "Austria", linkedin: link("https://www.linkedin.com/in/jdoe")[linkedin/jdoe], github: link("https://github.com/jdoe")[github.com/jdoe], website: link("https://jdoe.dev")[jdoe.dev], ), ) == Education #experience-edu( title: "Master's degree", subtitle: "University of Sciences", task-description: [ - Short summary of the most important courses - Explanation of master thesis topic ], date-from: "10/2021", date-to: "07/2023", ) // More content goes here ``` See [main.typ](./main.typ) for a full example that showcases all available elements. ## Output examples Example outputs for different color palettes: | Default colors | Pink colors | |:----------------:|:-------------:| |![Default colors](./docs/images/demo-navy-dark.png) | ![Pink colors](./docs/images/demo-pink.png)| ## Customization Note: customization is currently only supported when cloning the template locally. Allowing customization via a "Typst universe"-installed template is a feature that is actively worked on. The template allows you to make it yours by defining a custom color palette. Customize the color theme by changing the values of the `color` dictionary in [lib.typ](lib.typ). For example: - The default color palette: ```typst #let colors = ( primary: rgb("#313C4E"), secondary: rgb("#222A33"), accent-color: rgb("#449399"), text-primary: black, text-secondary: rgb("#7C7C7C"), text-tertiary: white, ) ``` - A pink color palette: ```typst #let colors = ( primary: rgb("#e755e0"), secondary: rgb("#ad00c2"), accent-color: rgb("#00d032"), text-primary: black, text-secondary: rgb("#7C7C7C"), text-tertiary: white, ) ``` ## Elements This section introduces the visual elements that are part of this template. ### Pills Import this element from the template module with `pill`. ![pills](docs/images/pills.png) ```typst #pill("German (native)") #pill("English (C1)") ``` ![pills filled](docs/images/pills-filled.png) ```typst #pill("Teamwork", fill: true) #pill("Critical thinking", fill: true) ``` ### Educational/work experience Import the elements from the template module with `experience-edu` and `experience-work` respectively. ![educational experience](docs/images/educational-experience.png) ```typst #experience-edu( title: "Master's degree", subtitle: "University of Sciences", task-description: [ - Short summary of the most important courses - Explanation of master thesis topic ], date-from: "10/2021", date-to: "07/2023", ) ``` ![work experience](docs/images/work-experience.png) ```typst #experience-work( title: "Full Stack Software Engineer", subtitle: [#link("https://www.google.com")[Some IT Company]], facility-description: "Company operating in sector XY", task-description: [ - Short summary of your responsibilities ], date-from: "09/2018", date-to: "07/2021", ) ``` ### Project Import this element from the template module with `project`. ![project](docs/images/project.png) ```typst #project( title: "Project 2", subtitle: "Data Visualization, Data Engineering", description: [ - #lorem(20) ], date-from: "08/2022", date-to: "09/2022", ) ``` ## Contributing I'm grateful for any improvements and suggestions. ## Acknowledgements This project would not be what it is without: - [Font Awesome Free](https://github.com/FortAwesome/Font-Awesome/) | providing the icons
https://github.com/ClassicConor/UoKCSYear1ExamNotes2024
https://raw.githubusercontent.com/ClassicConor/UoKCSYear1ExamNotes2024/master/HCI%20(With%20Exam%20Answers)/HCI%202023%20Paper/HCI%202023%20Answers.typ
typst
= HCI Exam 2023 - Answers to the questions <hci-exam-2023---answers-to-the-questions> == Question 1 <question-1> #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 1) + What is a micro-interaction? Name any two of the four components of a micro-interaction. Give one example of a micro-interaction in an interface. ] ] A micro-interaction is a small, contained product moment that revolves around a single use case. The four components of a micro-interaction are: trigger, rules, feedback, and loops. An example of a micro-interaction is the heart icon on Instagram that changes color when you double tap it. #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 2) + What are the problems with using a red circle to indicate "stop", which changes to a green circle when it is safe for the user to proceed with their action? ] ] The problem with using a red circle to indicate "stop" is that it is not universally understood. In some cultures, red is associated with danger, while in others, it is associated with luck. This can lead to confusion and misinterpretation of the message. Additionally, color blindness can make it difficult for some users to distinguish between red and green, further complicating the message. The use of color alone to convey meaning can also be problematic, as it relies on the user’s ability to perceive color accurately. This can be challenging for users with visual impairments or in situations where the lighting is poor. #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 3) + What is the difference between menu depth and menu breadth? Which is better to use to present menu choices to users, and why? ] ] Menu depth refers to the number of layers in a menu hierarchy, while menu breadth refers to the number of choices at each level. A shallow menu with a large breadth is generally better for presenting menu choices to users, as it allows users to quickly access the information they need without having to navigate through multiple levels of the menu. A deep menu with a small breadth can be overwhelming and confusing for users, as it requires them to remember the hierarchy and navigate through multiple levels to find the desired information. A shallow menu with a large breadth is more user-friendly and intuitive, as it minimizes the cognitive load on users and allows them to easily find the information they are looking for. #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 4) + With regard to human memory, what is a retrieval cue? Give two examples of retrieval cues used in interface design ] ] A retrieval cue is a stimulus that helps trigger the recall of information stored in memory. Two examples of retrieval cues used in interface design are: Icons: Icons are visual cues that represent specific actions or concepts. For example, a magnifying glass icon is commonly used to represent the search function. Color coding: Color coding is a visual cue that uses different colors to represent different categories or types of information. For example, red is often used to indicate errors or warnings, while green is used to indicate success or completion. == Question 2 <question-2> === a <a> One method of preventing errors in design is to use a forcing function. Forcing functions can be especially useful in safety-critical systems. In interface design, we distinguish between three types of forcing functions. For each of the following scenarios, identify and name the type of forcing function being used #quote(block: true)[ #block[ #set enum(numbering: "(i)", start: 1) + Dialog window appears asking if you want to save your work before closing a document with unsaved changes. ] ] The type of forcing function being used in this scenario is a lock-in forcing function. A lock-in forcing function prevents the user from taking an action until a specific condition is met. In this case, the user is prevented from closing the document until they have saved their work. #quote(block: true)[ #block[ #set enum(numbering: "(i)", start: 2) + ATM forces you to take your card first before releasing your money ] ] The type of forcing function being used in this scenario is an interlock forcing function. An interlock forcing function forces the user to take actions in a specific order in order to prevent errors. In this case, the user is prevented from taking their money until they have taken their card. #quote(block: true)[ #block[ #set enum(numbering: "(i)", start: 3) + When paying for an item purchased online, you cannot complete the payment until you’ve entered the one-time security code ] ] The type of forcing function being used in this scenario is a lock-out forcing function. A lock-out forcing function prevents the user from taking an action until a specific condition is met. In this case, the user is prevented from completing the payment until they have entered the one-time security code. #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 2) + We distinguish between two types of user errors: slips and mistakes. Slips are unconscious errors – right intention, but wrong action.In no more than one sentence, identify which type of user is more prne to "slips", and why ] ] Users who are more experienced with a system are more prone to slips, as they may rely on automatic or habitual actions rather than conscious thought when interacting with the system. The familiarity with the system can lead to slips, as users may perform the wrong action unintentionally due to muscle memory or routine. We distinguish between two types of user errors: slips and mistakes. Slips are unconscious errors – right intention, but wrong action. In no more than one sentence, identify which type of user is more prone to "slips", and why. Another example of a slip is when a user types the wrong password due to muscle memory or habit, even though they know the correct password. On the other hand, mistakes are conscious errors – wrong intention, wrong action. === c - Your team has been given the task of re-designing a website for users to book flights. The first screen allows the user to select their departure and arrival city, and their travel dates before searching for available flights <c---your-team-has-been-given-the-task-of-re-designing-a-website-for-users-to-book-flights.-the-first-screen-allows-the-user-to-select-their-departure-and-arrival-city-and-their-travel-dates-before-searching-for-available-flights> #quote(block: true)[ #block[ #set enum(numbering: "(i)", start: 1) + Identify two ways your team can design this first screen that will prevent the user from making "slips" when specifying their flight requirements. ] ] The first way to reduce slips within the system is by adjusting the size of the various input options on to be larger, or much clearer. If the buttons on the website were very small and without even spacing, it would likely be much easier for the user to accidentely click on the wrong button, simply because everything’s so close together. The second way to reduce slips within the system is by using vivid colours for both the text and the buttons. If the text and buttons were all the same colour, it would be much easier for the user to accidentally click on the wrong button, as they would all blend in together. #quote(block: true)[ #block[ #set enum(numbering: "(i)", start: 2) + One of the phases of human-centred design is prototyping. Your team would like to make use of the lo-fi prototyping technique. Give three advantages of using lo-fi prototyping. ] ] The first advantage is that it’s significantly cheaper to produce, as a lo-fi prototype could even include paper sketches. This also means that the tools which are required in order to create a lo-fi prototype are much lesser; you don’t necessarily need the most expensive specialised equipment or software, as you can often create a lofi prototype with the equipment around you. The second advantage is that the average amount of time required to make a lo-fi prototype is significantly less than a hi-fi prototype, meaning that a designer can go through multiple more iterations of the same technology. This would allow different designs and interfaces to receive feedback much more rapidly. The third advantage is that lo-fi designs can be more accessible to team members from a wide variety of disciplines. Hi-fi prototypes may only be edited by people who know how to code, or who know how a specific piece of design software such as Figma works, which may limit the number of people who are able to provide feedback and work on it. == Question 3 <question-3> You are part of a design team that has been tasked with designing a digital touchscreen thermostat. \> (a) Sketch an interface design for this system with appropriate annotations. The thermostat system should display the current temperature and allow the user to: \> \> - Set their preferred room temperature \> - Switch between showing the temperature in Celsius (⁰C) or Fahrenheit (⁰F). \> - Switch the heating on for a fixed duration. \> THERE ARE NO OTHER FUNCTIONS OR FEATURES. \[insert image here\] #quote(block: true)[ #block[ #set enum(numbering: "(a)", start: 2) + For each feature that you have designed, identify a design principle that you have used and explain (in no more than one sentence each) how the feature implements the design principle. ] ] \[insert features here\]
https://github.com/darioglasl/Arbeiten-Vorlage-Typst
https://raw.githubusercontent.com/darioglasl/Arbeiten-Vorlage-Typst/main/Helpers/code-snippets.typ
typst
// https://typst.app/docs/reference/text/raw/ // https://github.com/typst/typst/issues/344 #let code( caption: none, // content of caption bubble (string, none) bgcolor: rgb("#f2f3f5"), // back ground color (color) strokecolor: 1pt + rgb(27, 41, 52), // frame color (color) hlcolor: auto, // color to use for highlighted lines (auto, color) width: 100%, radius: 3pt, inset: 5pt, numbers: false, // show line numbers (boolean) stepnumber: 1, // only number lines divisible by stepnumber (integer) numberfirstline: false, // if the firstline isn't divisible by stepnumber, force it to be numbered anyway (boolean) numberstyle: auto, // style function to apply to line numbers (auto, style) firstnumber: 1, // number of the first line (integer) highlight: none, // line numbers to highlight (none, array of integer) content ) = { if type(hlcolor) == "auto" { hlcolor = bgcolor.darken(10%) } if type(highlight) == "none" { highlight = () } block( width: width, fill: bgcolor, stroke: strokecolor, radius: radius, inset: inset, clip: false, { // Draw the caption bubble if a caption was set if caption != none { style(styles => { let caption_block = block(width: auto, inset: inset, radius: radius, fill: bgcolor, stroke: strokecolor, h(.5em) + caption + h(.5em)) place( top + left, dx: 0em, dy: -(measure(caption_block, styles).height / 2 + inset), caption_block ) }) // skip some vertical space to avoid the caption overlapping with // the beginning of the content v(.6em) } let (columns, align, make_row) = { if numbers { // line numbering requested if type(numberstyle) == "auto" { numberstyle = text.with(size: .7em) } ( ( auto, 1fr ), ( right + horizon, left ), e => { let (i, l) = e let n = i + firstnumber let n_str = if (calc.rem(n, stepnumber) == 0) or (numberfirstline and i == 0) { numberstyle(str(n)) } else { none } (n_str + h(.5em), raw(lang: content.lang, l)) } ) } else { ( ( 1fr, ), ( left, ), e => { let (i, l) = e raw( lang:content.lang, l) } ) } } table( stroke:none, columns: columns, rows: (auto,), gutter: 0pt, inset: 2pt, align: (col, _) => align.at(col), fill: (c, row) => if (row / 2 + firstnumber) in highlight { hlcolor } else { none }, ..content .text .split("\n") .enumerate() .map(make_row) .flatten() .map(c => if c.has("text") and c.text == "" { v(1em) } else { c }) ) } ) } // --- Beispiel ----------------------------------- // #import "Helpers/code-snippets.typ": code // #figure( // code( // stepnumber:1, // numberfirstline: true, // numbers: true, // // caption: "Code: example.py", // // highlight: (1, 5) // )[```java // class HelloWorld { // public static void main(String[] args) { // System.out.println("Hello, World!"); // } // } // ```], // caption: [example.py], // kind: "Code Fragment", // supplement: [Code Fragment] // )
https://github.com/ssotoen/gridlock
https://raw.githubusercontent.com/ssotoen/gridlock/main/src/lib.typ
typst
The Unlicense
/// This function deals with the floating figures in your document. /// You don’t need to call it manually. /// /// Unfortunately we can’t use ```typc layout()``` here since that messes with the floating. /// This means that figures wider than the line width are measured before they are shrunk down to fit, /// which results in inaccurate measurements. /// To solve this problem, the compiler will remind you to manually set the width of these figures. /// /// - it (content): The figure. /// /// -> content #let float-adjustment(it) = context { let body-size = measure(it.body).height if it.kind == image { layout(size => { let container-width = size.width let body-width = measure(it.body).width if body-width > container-width { // TODO: v0.12 might introduce a warning function. could be more appropriate panic("Make sure none your figures are wider than " + str(container-width/1pt) + "pt.") } }) } let caption-size = measure(it.caption).height let height = body-size if it.caption != none { height = body-size + figure.gap.to-absolute() + caption-size } let line-height = text.top-edge let padding = line-height while height > padding { padding += line-height } set place(clearance: padding - height + line-height) it h(line-height) } /// Sets up the basic layout of the document. /// If you want to change the line height, you need to adjust the vertical margins so that the text area is an exact multiple of the line height. /// This is necessary because otherwise, floating figures won’t line up with the first/last line on the page. /// /// To change an element’s line height, use its ```typ top-edge``` property: \ /// ```typ #show heading: set text(top-edge: 18pt)```. /// /// Note that inline math is wrapped in a ```typc box()``` to ensure a consistent line height. /// As a side effect, these formulas cannot be broken across lines. /// /// - paper (string): The paper size. /// /// - margin (dictionary): The margins. /// To calculate the correct margins, find out how many lines fit on the page and multiply them with the line height. /// That’s the height of the text area. /// Subtract this from the page height (default: 841.89~pt) and you get the total height of the vertical margins. /// Split this up between top and bottom as you like. /// /// Example for Typst’s default settings (A4 paper, margins 2.5/21 × the page’s shorter edge) with a 13~pt line height: /// $ /// "lines per page" &= ("page height" - 2 × "vertical margin") / "line height" \ /// &= (841.89 - 2 × 595.28 × 2.5 class("binary", slash) 21) / 13 \ /// &= 53.85… "pt" \ \ \ /// "new vertical margin" &= "page height" - "lines per page" × "line height" \ /// &= 841.89 - 53 × 13 \ /// &= 152.89 "pt" /// $ /// /// For even margins, simply divide by 2 and you get 76.445~pt (the package’s default setting). /// You could also, for example, make the bottom margin twice as high as the top margin by setting ```typc (bottom: 101.89pt, top: 51pt)```. /// /// - font-size (length): The font size of the body text. /// /// - line-height (length): The distance between lines of body text. /// /// -> content #let gridlock( paper: "a4", margin: (y: 76.445pt), font-size: 11pt, line-height: 13pt, body, ) = { set page( paper: paper, margin: margin, ) set text( size: font-size, top-edge: line-height ) set par( leading: 0pt, first-line-indent: line-height, justify: true, spacing: 0pt, ) set block(spacing: 0pt) show quote.where(block: true): set block(spacing: line-height) show heading: set text(top-edge: 1.2em) show footnote.entry: set text(top-edge: 0.8em) show math.equation.where(block: false): it => box(height: line-height, it) show figure.where(placement: top): float-adjustment show figure.where(placement: bottom): float-adjustment show figure.where(placement: auto): float-adjustment body } /// This function aligns blocks to the grid. /// It measures the size of its argument, calculates the appropriate spacing, /// and applies it using the ```typc pad()``` function. /// /// Some elements are aligned automatically and do *not* need to be wrapped in ```typc lock()```: /// / block quotes: These have their spacing set to the line height. /// If you want to change the spacing, do ```typc #show quote.where(block: true): set block(spacing: 26pt)```. /// / lists (numbered, bulleted, term): These simply have their spacing set to 0~pt. /// If you want to change their spacing, use a show rule like with block quotes. /// / figures with the `placement` argument (floating figures): These are handled automatically with a show rule. /// Note that you *do* need to wrap non-floating figures in ```typc lock()```. /// /// - body (content): The bock to be aligned. /// /// -> content #let lock(body) = context[#layout(size => [ #let (height,) = measure( block(width: size.width, body), ) #let line-height = text.top-edge #let padding = line-height #while height > padding { padding += line-height } #let pos = here().position().y #if pos == page.margin.top [ #pad(bottom: (padding + line-height - height), body) ] else [ #pad(y: (padding - height + (2 * line-height)) / 2, body) ] ])]
https://github.com/OCamlPro/ppaqse-lang
https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/Ada.typ
typst
#import "defs.typ": * #import "links.typ": * #language( name: "Ada", introduction: [ Le langage Ada a été créé à la fin des années 70 au sein de l'équipe CII-<NAME> dirigé par <NAME> en réponse à un cahier des charges du département de la Défense des États-Unis. Le principe fût de créer un langage spécifiquement dédié aux systèmes temps réels ou embarqués requérant un haut niveau de sûreté. Le langage est standardisé pour la première fois en 1983 #cite(<ada1983>) sous le nom d'_Ada83_. La dernière norme ISO _Ada 2022_ a été publiée en 2023 #cite(<ada2023>). Notons que la norme _Ada 2012_ est librement téléchargeable #cite(<ada2012>). ], paradigme: [ Ada est un langage de programmation #paradigme[objet] et #paradigme[impératif]. Depuis la norme _Ada 2012_, le paradigme #paradigme[contrat] a été ajouté au langage. ], numerique: [ La langage #Ada a la particularité d'être très rigoureux sur l'utilisation des types arithmétiques. Il n'y a pas de conversion implicite et le compilateur va adapter la représentation des valeurs en fonction de la précision demandée: ```ada with Ada.Text_IO; use Ada.Text_IO; procedure Custom_Floating_Types is type T3 is digits 3; type T15 is digits 15; type T18 is digits 18; begin Put_Line ("T3 requires " & Integer'Image (T3'Size) & " bits"); Put_Line ("T15 requires " & Integer'Image (T15'Size) & " bits"); Put_Line ("T18 requires " & Integer'Image (T18'Size) & " bits"); end Custom_Floating_Types; ``` Ici, le programe affichera: ``` T3 requires 32 bits T15 requires 64 bits T18 requires 128 bits ``` Par ailleurs, le compilateur va automatiquement vérifier les potentiels débordements. Dans l'exemple suivant, on ajoute 5 à la valeur maximale d'un entier: ```ada procedure Main is A : Integer := Integer'Last; B : Integer; begin B := A + 5; -- This operation will overflow, eg. it -- will raise an exception at run time. end Main; ``` et la compilation indiquera le débordement: ``` main.adb:5:11: warning: value not in range of type "Standard.Integer" [enabled by default] main.adb:5:11: warning: Constraint_Error will be raised at run time [enabled by default] ``` Ces vérifications sont également faites sur les sous-types définis par l'utilisateur. Cela ne signifie pas qu'il ne peut pas y avoir de débordement car les contrôles sont faits à des points particuliers du programme et un débordement peut se produire dans un calcul intermédiaire entre deux points de contrôle. Toutefois, l'hygiène du langage permet de réduire significativement les erreurs de calculs. Pour un contrôle plus poussé des erreurs de calculs, il est nécessaire de passer par #spark qui permet de garantir statiquement des propriétés sur les calculs effectués. Enfin, il existe aussi des implémentations #Ada pour #mpfr et #gmp afin de réaliser des calculs dynamiques. ], assurances: [ Par sa conception même, le langage #Ada est conçu pour offir un haut niveau de garanties et une grande part des erreurs de programmation peuvent être évitées en utilisant les mécanismes intrinsèques du langage. Naturellement, il est toujours possible d'avoir des erreurs mais l'espace dans lequel celles-ci peuvent vivre est plus étroit que le fossé permis par le C. Par ailleurs, cet espace est adressé par les analyses statiques disponibles. ], runtime: [ Les outils d'analyse statique (corrects) pour #Ada sont: - #codepeer (ou GNAT SAS) ; - #polyspace ; - #spark Toolset. Un comparatif (non exhaustif) des trois outils est donné dans la @ada-static. #figure( table( columns: (auto, auto, auto, auto), [*Erreur*], [*CodePeer*], [*Polyspace*], [*SPARK Toolset*], [*Division par 0*], [✓], [✓], [✓], [*Débordement de tampon*], [✓], [✓], [✓], [*Déréférencement de NULL*], [✓], [?], [], [*Dangling pointer*], [], [], [], [*Data race*], [✓], [], [], [*Interblocage*], [], [], [], [*Vulnérabilités de sécurité*], [], [], [], [*Dépassement d'entier*], [✓], [✓], [✓], [*Arithmétique flottante*], [], [], [], [*Code mort*], [✓], [✓], [], [*Initialisation*], [✓], [✓], [], [*Flot de données*], [], [], [], [*Contrôle de flôt*], [], [], [], [*Flôt de signaux*], [], [], [], [*Non-interférence*], [], [], [], [*Fuites mémoire*], [], [], [], [*Double `free`*], [], [✓], [], [*Coercions avec perte*], [], [], [], [*Mémoire superflue*], [], [], [], [*Arguments variadiques*], [], [], [], [*Chaînes de caractères*], [], [], [], [*Contrôle d'API*], [], [], [], ), caption: "Comparatif des outils d'analyse statique pour le langage Ada", ) <ada-static> ], wcet: [ Les outils #rapidtime et #aiT cités dans la partie C supportent explicitement #Ada. ], pile: [ Les outils analysant l'exécutable peuvent le faire tout autant pour les programmes #Ada. Pour les outils ciblant spécifiquement #Ada, il y #gnatstack et #gnat. Pour le second, les options suivantes permettent de contrôler l'usage de la pile: - `-fstack-usage` qui produit une estimation de la taille maximale de la pile par fonction. - `-Wstack-usage=BYTES` qui produit un message d'avertissement pour les fonctions qui pourraient nécessiter plus de `BYTES` octets sur la pile. ], intrinseque: [ *Typage* Le langage Ada dispose d'un système de typage riche et statiquement vérifié par le compilateur. Contrairement aux langages comme C ou C++, Ada est _fortement typé_ au sens qu'il ne fait pas de conversions implicites entre des types différents. Par exemple l'expression `2 * 2.0` produira une erreur de compilation car le type de `2` est `Integer` et le type de `2.0` est `Float`. En plus des habituels types scalaires (entiers, flottants, ...), des enregistrements et des énumérations, le langage dispose de l'abstraction de type et d'un système de sous-typage. Il est possible de construire un nouveau type à partir d'un autre type via la syntaxe `type New_type is new Old_type`. Par exemple, le programme suivant: ```ada procedure Foo is type Kilos is new Float; type Joules is new Float; X : Kilos; Y : constant Joules := 10.0; begin X := Y; end Foo; ``` ne compilera pas car bien que `X` et `Y` aient la même représentation mémoire (des flottants), ils ne sont pas du même type. *Sous-typage* Ada dispose également d'une particularité qui lui permet de définir des sous-types arbitraires. Par exemple, si l'on veut un compteur dont on sait que les valeurs vont de 1 à 10, on peut définir le type correspondant : ```ada subtype Counter is Integer range 1 .. 10; ``` *Contrats* Depuis la norme Ada 2012, il est possible d'ajouter explicitement des _contrats_ sous forme de préconditions, postconditions et d'invariants. Par exemple la fonction suivante implémente la racine carrée entière qui n'est définie que pour les entiers positifs. ```ada function Isqrt (X : Integer) return Integer with Pre => X >= 0, Post => X = Isqrt'Result * Isqrt'Result is Z, Y : Integer := 0; begin if X = 0 or X = 1 then return X; else Z := X / 2; Y := (Z + X / Z) / 2; while Y < Z loop Z := Y; Y := (Z + X / Z) / 2; end loop; return Z; end if; end Isqrt; ``` Compilé avec l'option `-gnata` du compilateur #gnat, on obtiendra une erreur à l'exécution si on appelle cette fonction avec une valeur négative. On peut également spécifier des invariants pour des types dans les interfaces des _packages_. Par exemple, pour une implémentation des intervalles fermés, on peut garantir que l'unique représentant de l'intervalle vide est donné par le couple d'entiers `(0, -1)`. ```ada package Intervals is type Interval is private with Type_Invariant => Check (Interval); function Make (L : Integer; U : Integer) return Interval; function Inter (I : Interval; J : Interval) return Interval; function Check (I : Interval) return Boolean; private type Interval is record Lower : Integer; Upper : Integer; end record; end Intervals; package body Intervals is function Make (L : Integer; U : Integer) return Interval is (if U < L then (0, -1) else (L, U)); function Min (X : Integer; Y : Integer) return Integer is (if X <= Y then X else Y); function Max (X : Integer; Y : Integer) return Integer is (if X <= Y then Y else X); function Inter (I : Interval; J : Interval) return Interval is Make (Max (I.Lower, J.Lower), Min (I.Upper, J.Upper)); function Check (I : Interval) return Boolean is (I.Lower <= I.Upper or (I.Lower = 0 and I.Upper = -1)); end Intervals; ``` La fonction `Check`, dont l'implémentation n'est pas exposée dans l'interface, s'assure que le seul intervalle vide est l'intervalle `[0, -1]`. *Concurrence* Le langage Ada intègre dans sa norme des bibliothèques pour la programmation concurrentielle. Le concept de _tâche_ permet d'exécuter des applications en parallèle en faisant abstraction de leur implémentation. Une tâche peut ainsi être exécutée via un thread système ou un noyau dédié. Il est également possible de donner des propriétés aux tâches et de les synchroniser comme avec l'exemple du @ada-concurrence. Dans cet exemple, la procédure `Hello_World` crée deux tâches `T1` et `T2` qui décrémentent un compteur partagé `Counter` jusqu'à ce qu'il atteigne 1. #figure( placement: none, ```ada with Ada.Text_IO; Use Ada.Text_IO; procedure Hello_World is protected Counter is procedure Decr(X : out Integer); function Get return Integer; private Local : Integer := 20; end Counter; protected body Counter is procedure Decr(X : out Integer) is begin X := Local; Local := Local - 1; end Decr; function Get return Integer is begin return Local; end Get; end Counter; task T1; task T2; task body T1 is X : Integer; begin loop Counter.Decr(X); Put_Line ("Task 1: " & Integer'Image (X)); exit when Counter.Get <= 1; end loop; end T1; task body T2 is X : Integer; begin loop Counter.Decr(X); Put_Line ("Task 2: " & Integer'Image (X)); exit when Counter.Get <= 1; end loop; end T2; begin null; end Hello_World; ```, caption: "Exemple de programmation concurrentielle en Ada", ) <ada-concurrence> *Temps réel* Le profile _Ravenscar_ est un sous-ensemble du langage Ada conçu pour les systèmes temps réel. Il a fait l'objet d'une standardisation dans _Ada 2005_. En réduisant les fonctionnalités liées aux multi-tâches, ce profile facilite en outre la vérification automatique des programmes. ], tests: [ Les différents outils de tests recensés pour #Ada sont inddiqués dans la @ada-test. #figure( table( columns: (auto, auto, auto, auto, auto), [*Outil*], [*Tests*], [*Generation*], [*Gestion*], [_*mocking*_], [*#aunit*], [U], [+], [✓], [], [*#adatest95*], [UI], [++], [✓], [], [*#avhen*], [U], [+], [✓], [], [*#ldra*], [UIC], [+], [✓], [], [*#vectorcastAda*], [UC], [++], [✓], [✓], [*#rtrt*], [UIC], [], [], [], ), caption: [Comparaison des outils de tests pour le langage #Ada], ) <ada-test> #aunit et #avhen sont des implémentations xUnit pour #Ada. Les fonctionnalités sont toujours les mêmes et permettent de décrire des suites de tests unitaires avec un systèmes d'assertion et du _tooling_ simplifiant la tâche. Comme pour les autres implémentations xUnit, un rapport au format JUnit est généré. #adatest95 et #ldra (TBrun) sont des outils commerciaux de génération de tests unitaire et d'intégration. Ils offrent un support pour l'automatisation et sont conformes aux exigences de test dans les standards de sûreté. #vectorcastAda est la version adaptée à #Ada de l'outil de génération de tests #vectorcast. Il permet de générer des tests unitaires, d'intégration et propose un support pour le _mocking_. Contrairement à #adatest95 et #ldra qui ne supportent que Ada95, #vectorcastAda supporte également les normes Ada 2005 et Ada 2012. L'outil semble spécialisé dans l'avionique et est conforme aux exigences de la DO-178B. #rtrt est un outil commercial de test unitaire et d'intégration pour les systèmes temps réel. Il procède par instrumentation du code source et génère des rapports de couverture de code. Il permet également de faire du profilage mais les informations sur la génération, la gestion et le _mocking_ ne sont pas clairement documentées. ], parsers: [ #let aflex = link("https://github.com/Ada-France/aflex", "AFlex") #let ayacc = link("https://github.com/Ada-France/ayacc", "AYacc") #Ada est rarement employé pour l'écriture de compilateurs et il y a peu de support dans ce domaine. Il y a un équivalent de Lex/Yacc avec #aflex/#ayacc fournis par l'association Ada-France. #cocor permet également de générer des analyseurs syntaxiques pour #Ada. ], compilation: [ Parmi tous les compilateurs Ada, nous listons uniquement ceux qui semblent maintenus et de qualité industrielle. #figure( table( columns: (auto, auto, auto, auto), [*Compilateur*], [*Plateformes*], [*Licence*], [ *Normes*#footnote[ Nous ne considérons ici que les trois normes ISO Ada95, Ada 2005 et Ada 2012. ] ], [#ptcdobjada], [Toutes], [Propriétaire], [95, 2005, 2012], [GCC #gnat], [Toutes], [GPLv3+], [95, 2005, 2012], [#gnatpro], [Toutes], [Propriétaire], [95, 2005, 2012], [#gnatllvm], [Toutes], [GPLv3+], [?], [#gaoc], [Windows, Linux], [Proprietaire], [], [#ptcapexada], [Linux], [Propriétaire], [], [#janusada], [Windows], [Propriétaire], [95, 2005, 2012], ) ) Les compilateurs #gnat, #gnatpro et #janusada proposent également un mode Ada83 mais ne donnent pas de garantie quant au respect de ce standard. Le langage Ada a une longue tradition de validation des compilateurs. Ce processus de validation a fait l'objet en 1999 d'une norme ISO#cite(<adaconformity>). L'_Ada Conformity Assessment Authority_ (abrégée _ACAA_) est actuellement l'autorité en charge de produire un jeu de tests (_Ada Conformity Assessment Test Suite_) validant la conformité d'un compilateur avec les normes Ada. Elle propose la validation pour les normes Ada83 et Ada95 à travers des laboratoires tiers indépendants. En plus de cette validation, certains compilateurs ont fait l'objet de certifications pour la sûreté ou la sécurité. Ansi #gnatpro dispose des certifications de sûreté : - DO-178C ; - EN-50128 ; - ECSS-E-ST-40C ; - ECSS-Q-ST-80C ; - _ISO 26262_ ainsi que des certifications de sécurité: - DO-326A/ED-202A ; - DO-365A/ED-203A. ], debug: [ Tous les débugueurs basés sur l'analyse binaire (#gdb, #lldb, ...) sont compatibles avec #Ada. ], packages: [ #let alire = link("https://alire.ada.dev/", "Alire") #alire (_Ada LIbrary REpository_) est un dépôt de bibliothèques Ada près à l'emploi. L'installation se fait via l'outil `alr` à la manière de `cargo` pour #Rust ou `opam` pour #OCaml. L'outil dispose d'environ 460 _crates_. Techniquement, les gestionnaires de paquets agnostiques peuvent également gérer les bibliothèques #Ada mais aucun support spéficique n'est recensé au delà des paquets `alire` et `gnat` pour #nix. ], formel: [ #spark est la partie formelle du langage #Ada qui lui ajoute la possibilité d'ajouter des propriétés sur le code (à la manière des contrats d'Ada 2012) et de les vérifier statiquement en les déchargeant sur des démonstrateurs SMT (#z3, #cvc4 et #altergo). ], communaute: [ La communauté #Ada est structurée autour d'organismes qui promeuvent l'utilisation du langage dans la recherche et l'industrie. - *Ada Europe* est une organisation internationale promouvant l'utilisation d'Ada dans la recherche #cite(<adaeurope>). - *Ada Resource Association* (ARA) est une association qui promeut l'utilisation d'Ada dans l'industrie #cite(<adaic>). - *Ada - France* est une association loi 1901 regroupant des utilisateurs francophones d'#Ada #cite(<adafrance>). - *The AdaCore blog* est un blog d'actualité autour du langage Ada maintenu par l'entreprise AdaCore#cite(<adacoreblog>). ], metaprog: [ Il n'y a pas de support connu pour la méta-programmation en #Ada. ], derivation: [ Il n'y a pas de support connu pour la dérivation en #Ada. ], adherence: [ Le langage Ada peut être utilisé dans un contexte de programmation _bare metal_. - _GNAT FSF_ permet l'utilisation de _runtime_ personnalisé, - _GNAT Pro_ est livré avec plusieurs _runtime_: - _Standard Run-Time_ pour les OS classiques (Linux, Windows, VxWorks et RTEMS), - _Embedded Run-Time_ pour les systèmes _bare metal_ avec le support des tâches, - _Light Run-Time_ pour développer des applications certifiables sur des machines ayant peu de ressources; - _GreenHills Ada Optimizing Compiler_ fournit plusieurs implémentations de _runtime_ pour des cîbles différentes #cite(<greenhillscompiler>), - _PTC_ distribue un _runtime_ pour _PTC ObjectAda_ pour VxWorks et LynxOS sur PowerPC. - _PTC ApexAda_ propose également un _runtime_ dans un contexte _bare metal_ pour l'architecture Intel X86-64 #cite(<apexada>). Notons enfin qu'une des forces du langage est qu'en proposant dans sa norme une API pour la programmation concurrentielle et temps-réel, il permet de cibler plusieurs plateformes ou runtimes différents sans avoir à modifier le code source. ], interfacage: [ Ada peut être interfacé avec de nombreux langages. Les bibliothèques standards contiennent des interfaces pour les langages C, C++, COBOL et FORTRAN. L'exemple ci-dessous est issu du standard d'Ada 2012: ```ada --Calling the C Library Function strcpy with Interfaces.C; procedure Test is package C renames Interfaces.C; use type C.char_array; procedure Strcpy (Target : out C.char_array; Source : in C.char_array) with Import => True, Convention => C, External_Name => "strcpy"; Chars1 : C.char_array(1..20); Chars2 : C.char_array(1..20); begin Chars2(1..6) := "qwert" & C.nul; Strcpy(Chars1, Chars2); -- Now Chars1(1..6) = "qwert" & C.Nul end Test; ``` Certains compilateurs proposent également d'écrire directement de l'assembleur dans du code Ada. Pour ce faire, il faut inclure la bibliothèque `System.Machine_Code` dont le contenu n'est pas normalisé par le standard. Par exemple, le compilateur #gnat propose une interface similaire à celle proposée par #gcc en langage C: ```ada with System.Machine_Code; use System.Machine_Code; procedure Foo is begin Asm(); end Foo; ``` ], critique: [ #Ada ayant été conçu pour les systèmes critique, il est naturellement utilisé dans ce domaine. D'abord présent dans un cadre militaire, #Ada est utilisé, autre autres#cite(<adaprojectsummary>), dans les domaines du spatial, de l'aéronautique et du ferroviaire : - dans les lanceurs Ariane 4, 5 et 6; - le système de transmission voie-machine (TVM) développé par le groupe CSEE et utilisé sur les lignes ferroviaires TGV, le tunnel sous la manche, la High Speed 1 au Royaume-Uni ou encore la LGV 1 en Belgique. - Le pilote automatique pour la ligne 14 du métro parisien dans le cadre du projet METEOR (Métro Est Ouest Rapide) #cite(<meteorproject>). - La majorité des logiciels embarqués du Boeing 777 sont écrits en Ada. ] )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/content_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test font switch. #let here = text.with(font: "Noto Sans") $#here[f] := #here[Hi there]$.
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/mark-cap-offsets/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #import "/src/marks.typ": * #context align(center, MARKS.get().values().map(mark => { let e = 2.5 diagram(edge( (0,0), (1,0), marks: (mark, mark), extrude: (-e,0,+e) )) }).join(linebreak()))
https://github.com/Student-Smart-Printing-Service-HCMUT/ssps-docs
https://raw.githubusercontent.com/Student-Smart-Printing-Service-HCMUT/ssps-docs/main/contents/categories/task1/1.3.typ
typst
Apache License 2.0
#pagebreak() == Use Case Diagram === _Whole System_ _Draw a use case diagram for whole System_ #figure(caption: [Use Case Diagram for the Whole System], image("../../images/UC_Whole_System.png") ) #pagebreak() === _Use case Order Printing Job_ #figure(caption: [Use Case Diagram for Order Printing Job], image("../../images/UC_Order_Print.png") ) *Order Printing Job scenario* #table( columns: (auto, auto), inset: 10pt, align: horizon, [*Use Case Name*], [*Order Printing Job*], [Actors], [Student, Payment Service Provider.], [Brief Description], [Sinh viên thực hiện chức năng Order print để đặt in tài liệu trong hệ thống.], [Preconditions], [Sinh viên đã đăng nhập vào hệ thống và có tài liệu cần in.], [Postconditions], [Sinh viên đã đặt in tài liệu thành công và được lên lịch in trong hệ thống.], [Trigger], [Sinh viên nhấn nút Order print và chọn tài liệu cần in.], [Normal Flow], [ 1. Sau khi sinh viên hoàn tất việc upload file, hệ thống sẽ lưu file trên cloud storage là MinIo. 2. Hệ thống sẽ lưu thông tin về các cài đặt in của file cùng với một vài thông tin khác của file(tên, kích cỡ,...) thành metadata. 3. Thông tin metadata của file sẽ được dùng để truy xuất ngược lại file ở MinIo khi sinh viên tiến hành preview file hoặc remove file.\ 4. Hệ thống sẽ tiến hành tạo model cho metadata bằng Prisma ORM. 5. Model của metadata sẽ được lưu vào database là Postgres. 7. Sau khi lưu thành công, hệ thống sẽ trả về cho sinh viên một đường dẫn để sinh viên có thể preview file. 8. Sinh viên có thể xóa file nếu muốn. 9. Sau khi sinh viên hoàn tất việc chọn file, hệ thống sẽ tiến hành tính toán số lượng coins mà sinh viên phải trả cho đơn hàng. 10. Khi sinh viên xác nhận hoàn tất đơn hàng, hệ thống sẽ thực hiện hai việc: 10a. Update thông tin về số lượng coins thông qua model người dùng. 10b. Tạo model cho đơn hàng bằng Prisma ORM. Model này sẽ bao gồm các thông tin mà sinh viên đã cài đặt cho đơn hàng (số lượng bản in, màu sắc, giấy,..). 11. Hệ thống sẽ lưu model của đơn hàng vào database là Postgres. 12. Hệ thống sẽ trả về cho sinh viên một đường dẫn để sinh viên có thể xem lại thông tin đơn hàng. ], [Exceptional flow], [*Ở bước 10a*, Nếu csố lượng coins mới của sinh viên không đủ, đơn hàng sẽ không được đặt và thông báo hiển thị cho sinh viên, sinh viên có thể chọn đến trang nạp tiền để nạp thêm tiền vào tài khoản và quay lại bước 10.], [Alternative flow], [*Ở bước 8*, Nếu sinh viên xác nhận xóa tài liệu sau khi nó tải lên, họ có thể xóa tài liệu đó và tải lên một tài liệu khác.], [Includes], [Upload Document, Preview Document, Remove Document, Specify Printing Option, Checkout, Confirm Order, Set Location, Payment, Schedule Print.] ) #figure(caption: [Order Printing Job scenario], table() ) #linebreak() === _Use case Login Service_ #figure(caption: [Use Case Diagram for Login Service], image("../../images/UC_Login_Service.png") )
https://github.com/Wh4rp/Presentacion-Typst
https://raw.githubusercontent.com/Wh4rp/Presentacion-Typst/master/README.md
markdown
# Typst: ¿el reemplazo de LaTeX? Presentación hecha en [Typst](https://typst.app/) junto con el modulo de [typst-slides](https://github.com/andreasKroepelin/typst-slides) para el ciclo de charlas de [Open Source UC](https://github.com/open-source-uc). ## Compilar Primero debes instalar el CLI de [Typst](https://github.com/typst/typst#installation) y luego ejecutar: ```bash typst compile main.pdf ``` ## Carpetas - `comparacion/`: Contiene la presentación de comparación entre Typst y LaTex. - `ejemplos/`: Contiene los códigos de ejemplos que se muestran en la presentación. - `modulos/`: Contiene la presentación de los módulos de Typst. - `slides.typ`: Modulo de slides para Typst. - `preview-typ.typ`: Modulo creado por mi que sirve para previsualizar el código de Typst junto con su compilación. - `src/`: assets de la presentación.
https://github.com/xrarch/books
https://raw.githubusercontent.com/xrarch/books/main/xr17032handbook/titlepage.typ
typst
#page([ #image("coverideasmaller.png", fit: "stretch", width: 100%, height: 100%) ], margin: ( top: 0cm, bottom: 0cm, left: 0cm, right: 0cm, )) #pagebreak() *XR/station Project* \ *XR/17032 Architecture Handbook* \ _Revision 1.0, October 26, 2021_ \ _Revision 2.0, December 10, 2023_
https://github.com/a-mhamdi/graduation-report
https://raw.githubusercontent.com/a-mhamdi/graduation-report/main/Typst/en-Report/chaps/chpt1.typ
typst
MIT License
/* --------------------------------- DO NOT EDIT -------------------------------- */ #import "../Class.typ": * #show: report.with(isAbstract: false) #set page(header: none) #figure(chap(chap1, numbering: "1."), kind: "chapter", supplement: "Chapter") <chp:chap1> // Chapter 1 #set page(header: smallcaps(title) + h(1fr) + emph(chap1) + line(length: 100%)) #set heading(outlined: true, numbering: "1.") /* ------------------------------------------------------------------------------ */ == Introduction #lorem(32) == Section 1 #lorem(16) === Subsection 1.1 #lorem(64) === Subsection 1.2 #lorem(64) == Section 2 #lorem(16) === Subsection 2.1 #lorem(64) === Subsection 2.2 #lorem(64) == Conclusion #lorem(32)
https://github.com/123marvin123/typst-docker
https://raw.githubusercontent.com/123marvin123/typst-docker/master/README.md
markdown
Apache License 2.0
# Typst Docker Image This is a (unofficial) Docker Image for a bare-bones distribution of [Typst](https://github.com/typst/typst). It is based on Debian and only contains a pre-compiled version of the Typst-CLI. ❗️*Please note*: **There are no additional fonts installed**. Take a look at the section "Using Installed Host System Fonts" or use the built-in fonts in the pre-compiled binary. ## ⚒️ Running the image ```bash docker run --name typst -v $(PWD):/root -it 123marvin123/typst ``` **In the docker environment, you can use the `typst` command like usual. E.g. `typst compile thesis.typ`.** *Please note that we will not provide a `latest` tag until Typst has arrived at a stable state without major breaking changes with each release.* ## 🈂️ Using Installed Host System Fonts The base image of Debian does not contain any additional fonts. This means, you can either use the few built-in fonts that are embedded in the Typst executable, or mount your system's font directory into the docker container. This can be accomplished in two ways: ### Mount system fonts to `/usr/share/fonts` E.g. on macOS: ```bash docker run --name typst -it -v /System/Library/Fonts:/usr/share/fonts:ro 123marvin123/typst ``` This will allow Typst to see the read-only mounted fonts from your host system without having to modify anything. ### Mount system fonts to anywhere Instead of mounting to `/usr/share/fonts`, you can mount the folder to anywhere (e.g. `/root/fonts`) and then modify the environment variable `TYPST_FONT_PATHS`. Using this technique, you can also mount more than one folder: E.g. on macOS: ```bash docker run --name typst -it -v /System/Library/Fonts:/root/fonts:ro --env TYPST_FONT_PATHS=/root/fonts 123marvin123/typst ``` This only has to be done once you create the container.
https://github.com/jassielof/cv
https://raw.githubusercontent.com/jassielof/cv/main/README.md
markdown
# CV ## Issues when porting to Typst - The LaTeX dash for a date range is not similar, it's more generic. - Find a way to import awesome fonts for icons in Typst.
https://github.com/MattiaOldani/Informatica-Teorica
https://raw.githubusercontent.com/MattiaOldani/Informatica-Teorica/master/capitoli/calcolabilità/06_dati_NN.typ
typst
#import "../alias.typ": * #import "@preview/lemmify:0.1.5": * #let (theorem, lemma, corollary, remark, proposition, example, proof, rules: thm-rules) = default-theorems( "thm-group", lang: "it", ) #show: thm-rules #show thm-selector("thm-group", subgroup: "theorem"): it => block( it, stroke: red + 1pt, inset: 1em, breakable: true, ) #show thm-selector("thm-group", subgroup: "proof"): it => block( it, stroke: green + 1pt, inset: 1em, breakable: true, ) = $dati tilde NN$ Ci serve trovare una legge che: + associ biunivocamente dati a numeri e viceversa; + consenta di operare direttamente sui numeri per operare sui corrispondenti dati, ovvero abbia delle primitive per lavorare il numero che "riflettano" il risultato sul dato senza ripassare per il dato stesso; + ci consenta di dire, senza perdita di generalità, che i nostri programmi lavorano sui numeri. == Funzione coppia di Cantor La *funzione coppia di Cantor* è la funzione $ cantor() : NN times NN arrow.long NN^+. $ Questa funzione sfrutta due "sotto-funzioni" $ cantorsin: NN^+ arrow.long NN, quad cantordes: NN^+ arrow.long NN $ tali che: $ cantor(x,y) = n, \ cantorsin (n) = x, \ cantordes (n) = y. $ Vediamo una rappresentazione grafica della funzione di Cantor. #v(12pt) #figure( image("assets/cantor-01.svg", width: 50%), ) #v(12pt) Come vediamo, $cantor(x,y)$ rappresenta il valore all'incrocio tra la $x$-esima riga e la $y$-esima colonna. La tabella viene riempita _diagonale per diagonale_ (non principale). Il procedimento è il seguente: + sia $x=0$; + partendo dalla cella $(x,0)$ si enumerano le celle della diagonale identificata da $(x,0)$ e da $(0,x)$; + si incrementa $x$ di $1$ e si ripete dal punto $2$. La funzione deve essere sia iniettiva sia suriettiva, quindi: - non posso avere celle con lo stesso numero (iniettività); - ogni numero in $NN^+$ deve comparire (surriettività). Entrambe le proprietà sono soddisfatte, in quanto numeriamo in maniera incrementale e ogni numero prima o poi compare in una cella, quindi ho una coppia che lo genera. === Forma analitica della funzione coppia Cerchiamo di formalizzare la costruzione di questi numeri, dato che non è molto comodo costruire ogni volta la tabella. Notiamo che vale la seguente relazione: $ cantor(x,y) = cantor(x+y,0) + y. $ #v(12pt) #figure( image("assets/cantor-02.svg", width: 40%), ) #v(12pt) In questo modo il calcolo della funzione coppia si riduce al calcolo di $cantor(x+y,0)$. Chiamiamo $x+ y = z$ e con la prossima immagine osserviamo un'altra proprietà. #v(12pt) #figure( image("assets/cantor-03.svg", width: 15%), ) #v(12pt) Ogni cella $cantor(z,0)$ la si può calcolare come la somma di $z$ e $cantor(z-1,0)$: $ cantor(z,0) &= z + cantor(z-1,0) = \ &= z + (z-1) + cantor(z-2,0) = \ &= z + (z-1) + dots + 1 + cantor(0,0) = \ &= z + (z-1) + dots + 1 + 1 = \ &= sum_(i=1)^z i + 1 = frac(z(z+1),2) + 1. $ Questa forma è molto più compatta ed evita il calcolo di tutti i singoli $cantor(z,0)$. Mettiamo insieme le due proprietà per ottenere la formula analitica della funzione coppia: $ cantor(x,y) = cantor(x+y,0) + y = frac((x+y)(x+y+1), 2) + y + 1. $ === Forma analitica di sin e des Vogliamo fare lo stesso per $cantorsin$ e $cantordes$, per poter computare l'inversa della funzione di Cantor dato $n$. Grazie alle osservazioni precedenti, sappiamo che: $ n = y + cantor(gamma,0) space & arrow.long.double space y = n - cantor(gamma,0), \ gamma = x + y space & arrow.long.double space x = gamma - y. $ Trovando il valore $gamma$ possiamo anche trovare i valori di $x$ e $y$. Notiamo come $gamma$ sia il "punto di attacco" della diagonale che contiene $n$, quindi: $ gamma = max{z in NN bar.v cantor(z,0) lt.eq n}, $ perché tra tutti i punti di attacco $cantor(z,0)$ voglio esattamente la diagonale che contiene $n$. Risolviamo quindi la disequazione: $ cantor(z,0) lt.eq n & arrow.long.double frac(z(z+1),2) + 1 lt.eq n \ & arrow.long.double z^2 + z - 2n + 2 lt.eq 0 \ & arrow.long.double z_(1,2) = frac(-1 plus.minus sqrt(1 + 8n - 8), 2) \ & arrow.long.double frac(-1 - sqrt(8n - 7), 2) lt.eq z lt.eq frac(-1 + sqrt(8n - 7), 2). $ Come valore di $gamma$ scegliamo $ gamma = floor(frac(-1 + sqrt(8n - 7), 2)). $ Ora che abbiamo $gamma$, possiamo definire le funzioni $cantorsin$ e $cantordes$ in questo modo: $ cantordes(n) = y = n - cantor(gamma,0) = n - frac(gamma (gamma + 1), 2) - 1, \ cantorsin(n) = x = gamma - y. $ === $NN times NN tilde NN$ Grazie alla funzione coppia di Cantor, possiamo dimostrare un risultato importante. #theorem(numbering: none)[ $NN times NN tilde NN^+$. ] #proof[ \ La funzione di Cantor è una funzione biiettiva tra l'insieme $NN times NN$ e l'insieme $NN^+$, quindi i due insiemi sono isomorfi. ] Estendiamo adesso il risultato all'interno insieme $NN$, ovvero: #theorem(numbering: none)[ $NN times NN tilde NN$. ] #proof[ \ Definiamo la funzione $ [,]: NN times NN arrow.long NN $ tale che $ [x,y] = cantor(x,y) - 1. $ Questa funzione è anch'essa biiettiva, quindi i due insiemi sono isomorfi. ] Grazie a questi risultati si può dimostrare anche che $QQ tilde NN$, infatti i numeri razionali li possiamo rappresentare come coppie $("num", "den")$ e, in generale, tutte le tuple sono isomorfe a $NN$, basta iterare in qualche modo la funzione coppia di Cantor. == Dimostrazione $dati tilde NN$ È intuibile come i risultati ottenuti fino a questo punto ci permettono di dire che ogni dato è trasformabile in un numero, che può essere soggetto a trasformazioni e manipolazioni matematiche. Tuttavia, la dimostrazione _formale_ non verrà fatta, anche se verranno fatti esempi di alcune strutture dati che possono essere trasformate in un numero tramite la funzione coppia di Cantor. Vedremo come ogni struttura dati verrà manipolata e trasformata in una coppia $(x,y)$ per poterla applicare alla funzione coppia. == Applicazione alle strutture dati Le *liste* sono le strutture dati più utilizzate nei programmi. In generale non ne è nota la grandezza, di conseguenza dobbiamo trovare un modo, soprattutto durante la applicazione di $cantorsin$ e $cantordes$, per capire quando abbiamo esaurito gli elementi della lista. Codifichiamo la lista $[x_1, dots, x_n]$ con: $ cantor(x_1, dots, x_n) = cantor(x_1, cantor(x_2, cantor(dots cantor(x_n, 0) dots))) . $ Ad esempio, la codifica della lista $M = [1,2,5]$ risulta essere: $ cantor(1,2,5) &= cantor(1, cantor(2, cantor(5,0))) \ &= cantor(1, cantor(2,16)) \ &= cantor(1, 188) \ &= 18144. $ Per decodificare la lista $M$, applichiamo le funzioni $cantorsin$ e $cantordes$ al risultato precedente. Alla prima iterazione otterremo il primo elemento della lista e la restante parte ancora da decodificare. _Quando ci fermiamo?_ Durante la creazione della codifica di $M$ abbiamo inserito un _"tappo"_, ovvero la prima iterazione della funzione coppia $cantor(x_n, 0)$. Questo ci indica che quando $cantordes(M)$ sarà uguale a $0$, ci dovremo fermare. _Cosa succede se abbiamo uno $0$ nella lista?_ Non ci sono problemi: il controllo avviene sulla funzione $cantordes$, che restituisce la _somma parziale_ e non sulla funzione $cantorsin$, che restituisce i valori della lista. Possiamo anche pensare delle implementazioni di queste funzioni. Assumiamo che: - $0$ codifichi la lista nulla; - esistano delle routine per $cantor()$, $cantorsin$ e $cantordes$. #v(12pt) #grid( columns: (1fr, 1fr), align(center)[ Codifica ```python def encode(numbers: list[int]) -> int: k = 0 for i in range(n,0,-1): xi = numbers[i] k = <xi,k> return k ``` ], align(center)[ Decodifica ```python def decode(n: int) -> list[int]: numbers = [] while True: left, n = sin(n), des(n) numbers.append(left) if n == 0: break return numbers ``` ], ) #v(12pt) Un metodo molto utile delle liste è quello che ritorna la sua *lunghezza*: #align(center)[ ```python def length(n: int) -> int: return 0 if n == 0 else 1 + length(des(n)) ``` ] Infine, definiamo la funzione *proiezione* come: $ op(pi)(t,n) = cases(-1 quad & text("se") t > op("length")(n) or t lt.eq 0 \ x_t & text("altrimenti")) $ e la sua implementazione: #align(center)[ ```python def proj(t: int, n: int) -> int: if t <= 0 or t > length(n): return -1 else: if t == 1: return sin(n) else: return proj(t-1, des(n)) ``` ] Per gli *array* il discorso è più semplice, in quanto la dimensione è nota a priori. Di conseguenza, non necessitiamo di un carattere di fine sequenza. Dunque avremo che l'array ${x_1, dots, x_n}$ viene codificato con: $ {x_1, dots, x_n} = cantor(x_1, cantor(dots, cantor(x_(n-1), x_n)) dots ). $ Per quanto riguarda *matrici* l'approccio utilizzato codifica singolarmente le righe e successivamente codifica i risultati ottenuti come se fossero un array di dimensione uguale al numero di righe. #set math.mat(delim: "[") Ad esempio, la matrice: $ mat(x_11, x_12, x_13; x_21, x_22, x_23; x_31, x_32, x_33) $ viene codificata in: $ mat(x_11, x_12, x_13; x_21, x_22, x_23; x_31, x_32, x_33) = cantor(cantor(x_11, x_12, x_13), cantor(x_21, x_22, x_23), cantor(x_31, x_32, x_33)). $ Consideriamo il seguente grafo. #v(12pt) #figure( image("assets/grafo.svg", width: 25%), ) #v(12pt) I *grafi* sono rappresentati principalmente in due modi: - *liste di adiacenza dei vertici*: per ogni vertice si ha una lista che contiene gli identificatori dei vertici collegati direttamente con esso. Il grafo precedente ha $ {1:[2,3,4], 2:[1,3], 3:[1,2,4], 4:[1,3]} $ come lista di adiacenza, e la sua codifica si calcola come: $ cantor(cantor(2,3,4),cantor(1,3),cantor(1,2,4),cantor(1,3)). $ Questa soluzione esegue prima la codifica di ogni lista di adiacenza e poi la codifica dei risultati del passo precedente. - *matrice di adiacenza*: per ogni cella $m_(i j)$ della matrice $|V| times |V|$, dove $V$ è l'insieme dei vertici, si ha: $ m_(i,j) = cases(1 & quad "se esiste un arco dal vertice " i " al vertice " j, 0 & quad "altrimenti"). $ Essendo questa una matrice, la andiamo a codificare come già descritto. == Applicazione ai dati reali Una volta visto come codificare le principali strutture dati, è facile trovare delle vie per codificare qualsiasi tipo di dato in un numero. Vediamo alcuni esempi. Dato un *testo*, possiamo ottenere la sua codifica nel seguente modo: + trasformiamo il testo in una lista di numeri tramite la codifica ASCII dei singoli caratteri; + sfruttiamo l'idea dietro la codifica delle liste per codificare quanto ottenuto. Per esempio: $ "ciao" = [99, 105, 97, 111] = cantor(99, cantor(105, cantor(97, cantor(111, 0)))). $ Potremmo chiederci: - _Il codificatore proposto è un buon compressore?_ \ No, si vede facilmente che il numero ottenuto tramite la funzione coppia (o la sua concatenazione) sia generalmente molto grande, e che i bit necessari a rappresentarlo crescano esponenzialmente sulla lunghezza dell'input. Ne segue che questo è un *pessimo modo per comprimere messaggi*. - _Il codificatore proposto è un buon sistema crittografico?_ \ La natura stessa del processo garantisce la possibilità di trovare un modo per decifrare in modo analitico, di conseguenza chiunque potrebbe, in poco tempo, decifrare il mio messaggio. Inoltre, questo metodo è molto sensibile agli errori. Dato un *suono*, possiamo _campionare_ il suo segnale elettrico a intervalli di tempo regolari e codificare la sequenza dei valori campionati tramite liste o array. Per codificare le *immagini* esistono diverse tecniche, ma la più usata è la *bitmap*: ogni pixel contiene la codifica numerica di un colore, quindi posso codificare separatamente ogni pixel e poi codificare i singoli risultati insieme tramite liste o array. Abbiamo mostrato come i dati possano essere sostituiti da delle codifiche numeriche ad essi associate.\ Di conseguenza, possiamo sostituire tutte le funzioni $f: dati arrow.long dati_bot$ con delle funzioni $f': NN arrow NN_bot$. In altre parole, l'universo dei problemi per i quali cerchiamo una soluzione automatica è rappresentabile dall'insieme $NN_bot^NN.$
https://github.com/AOx0/expo-nosql
https://raw.githubusercontent.com/AOx0/expo-nosql/main/book/src/theme-gallery/default.typ
typst
MIT License
#import "../../../slides.typ": * #show: slides.with( authors: ("Author A", "Author B"), short-authors: "Short author", title: "Title", short-title: "Short title", subtitle: "Subtitle", date: "Date", ) #slide(theme-variant: "title slide") #new-section("section name") #slide(title: "Slide title")[ A slide ] #slide(theme-variant: "wake up")[ Wake up! ]