repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/sabitov-kirill/comp-arch-conspect
https://raw.githubusercontent.com/sabitov-kirill/comp-arch-conspect/master/questions/5_chipsets.typ
typst
#heading[Организация чипсетов.] #emph[Организация чипсетов (двухмостовая архитектура и ее развитие, UMA/NUMA).] == Развитие двухмостовой архитектуры #import "/commons.typ": imagebox #imagebox("dvu_most.png", label: [Пример двухмостовой архитектуры с различной реализацией шин CPU и контроллерами памяти], height: 150pt) В двухмостовой архитектуре, в зависимости от конкретной реализации, процессоры либо каждый по отдельности подключены к северному мосту, либо подключены через общую шину (обычное подключение идёт через шину FSB - front side bus). Северный мост в свою очередь соединён с южным мостом *Основные идеи двухмостовой архитектуры*: + Вся быстрая периферия (все быстрые устройства, с которыми нужно работать процессору) подключается к северному мосту. Например, контроллеры RAM. + Все медленные устройства подключаются к южному мосту. Например, внешние жёсткие диски, USB устройства, различные устройства, которые могут быть подключены с помощью шины PCI-Express. *Основные недостатки двухмостовой архитектуры:* + В общем случае внешним устройствам для того, чтобы взаимодействовать с оперативной памятью, нужно _реализовывать запросы через процессор_. Шина между процессором и северным мостом становится так называемым узким местом (bottleneck). Однако, данный недостаток в некоторых реализациях был компенсирован с помощью DMA (Direct memory access). Данный подход несёт в себе идею предоставления устройствам переферии прямой доступ к оперативной памяти без отправки запросов в процессор. + В общем случае двухмостовой архитектуры существует всего _один канал доступа к оперативной памяти_. Таким образом, например, нескольким ядрам процессора приходится поочередно отправлять запросы к оперативной памяти, что уменьшает производительность. Однако, данный недостаток в некоторых реализациях был компенсирован выносом контроллера оперативной памяти из северного моста наружу и добавлением нескольких контроллеров оперативной памяти. Таким образом, появилась возможность к различным модулям оперативной памяти обращаться параллельно, увеличив производительность. #imagebox("dvu_next.png", height: 230pt, label: [Пример двумостовой архитектуры с контроллером памяти и _PCI-E_ на кристале процессора.]) Впоследствии было замечено, что PCI-E устройства также достаточно быстрые и взаимодействие с ними через южный мост снижает производительность. Например, через PCI-E можно подключать дорогостоющие видеокарты или быстрые SDD-диски. Поэтому контроллер для взаимодествия с устройствами по шине PCI-E был перенесён на северный мост, а впоследствии на кристалл процессора. После чего было замечено, что память становится все быстрее и работать с ней нужно все больше, поэтому контроллер памяти с северного моста был перенесён на кристалл процессора. Таким образом, на кристалле процессора находятся контроллеры для взаимодествия с самой быстрой периферией (RAM и PCI-E), северный мост потерял надобность и был удален. #imagebox("system_on_crystallpng.png", height: 150pt, label: [Приблизительная архитектура современных портативных девайсов _*(SoC)*_.]) После чего пришла эра портативной электроники. Графические ускорители было решено расположить также на кристале процессора. Таким образом, конечным этапом развития двухмостовой архитектуры является Soc (System on crystal). Эта архитектура подразумевает под собой расположение всех контроллеров периферии на кристале процессора. Этот подход является типичным практический для всей портативной электроники. == Модели разделения памяти в мультипроцессорах (UMA/NUMA) === UMA (Uniform Unix Access / Однородный доступ к памяти) #grid(columns: (auto, 130pt), column-gutter: 20pt, [ Система UMA (Uniform Memory Access) - это архитектура с общей памятью для многопроцессорных систем. В этой модели используется единственная память, к которой обращаются все процессоры представленной многопроцессорной системы с помощью межсоединительной сети. Каждый процессор имеет равное время доступа к памяти (задержка) и скорость доступа. Он может использовать либо одну шину, несколько шин или коммутатор. Данный подход хорошо показывает себя в работе, если количество вычислительных ядер находится в среднем диапазоне. Однако, при большом количестве вычислительных ядер данный подход показывает себя хуже, поскольку контролировать запросы к общей памяти в такой ситуации становится весьма затруднительно. ], imagebox("UMA.png")) === NUMA (Non-Uniform Memory Access / Неоднородный доступ к памяти) NUMA также является многопроцессорной моделью, в которой каждый процессор связан с выделенной памятью. Однако эти небольшие части памяти объединяются в единое адресное пространство. Время доступа к памяти зависит от расстояния, на котором расположен процессор, что означает изменение времени доступа к памяти. Это позволяет получить доступ к любой ячейке памяти, используя физический адрес, однако время доступа при этом получается неоднородным. #imagebox("NUMA.png", label: [У каждого процессора есть "своя" оперативная память, наиболее близкая к нему. Чтобы обращаться с другой памятью, нужно идти к другим процессорам, таким образом время доступа получается неоднородное]) Данный подход хорошо показывает себя при большом количестве вычислителей, каждый из которых реализует независимые вычисления. Хорошим примером являются удалённые сервера. Сервер разделяется на блоки, каждый из которых является практически независимым. Таким образом одновременно работает множество независимых процессов.
https://github.com/taooceros/CV
https://raw.githubusercontent.com/taooceros/CV/main/modules_en/community.typ
typst
// Imports #import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry #let metadata = toml("../metadata.toml") #let cvSection = cvSection.with(metadata: metadata) #let cvEntry = cvEntry.with(metadata: metadata) #cvSection("Community Service") #cvEntry( title: [Housing Department], society: [Math Tutor], date: [Sep 2023 - Present], location: [University of Wisconsin-Madison], description: [ - Assumed a role within the Housing Advisor team, offering academic support to (mostly first year) residents' mathematical needs. ], ) #cvEntry( title: [Combinatorics (Math 475)], society: [Math Grader], date: [Sep 2023 - Dec 2023], location: [University of Wisconsin-Madison], description: [ - Graded weekly homework assignments. ], ) #cvEntry( title: [Discrete Math (Math 240)], society: [Math Grader], date: [Jan 2023 - May 2023], location: [University of Wisconsin-Madison], description: [ ], ) #cvEntry( title: [Introduction to Artificial Intelligence (CS 540)], society: [Peer Mentor], date: [Sep 2022 - Dec 2022], location: [University of Wisconsin-Madison], description: [ - Hosted regular office hours for a class of more than 300 students. - Explained students the mathematical basis behind AI Algorithms, and helped students to implement various AI algorithms (PCA, CNN, Q-Learning, etc.) in Python. ], )
https://github.com/mem-courses/linear-algebra
https://raw.githubusercontent.com/mem-courses/linear-algebra/main/note/2.行列式.typ
typst
#import "../template.typ": * #show: project.with( title: "Linear Algebra #2", authors: ( (name: "<NAME>", email: "<EMAIL>", phone: "3230104585"), ), date: "October 28, 2023", ) = 行列式 设 $bold(A) = (a_(i,j))_(n times n)$ 是数域 $PP$ 上的 $n$ 阶方阵,则它的行列式定义为: #set math.mat(delim: "|") $ |bold(A)| = mat( a_11,a_12,dots.c,a_(1 n); a_21,a_22,dots.c,a_(2 n); dots.v,dots.v,dots.down,dots.v; a_(n 1),a_(n 2),dots.c,a_(n n); ) = sum_(j_1 j_2 dots.c j_n) (-1)^tau(j_1 j_2 dots.c j_n) a_(1 j_1) a_(2 j_2) dots.c a_(n j_n) $ == 行列式的性质 #def[性质1]$|bold(A)| = |bold(A)^T|$;(在行列式中,行与列的地位一样) #def[性质2.1]交换矩阵的两行(列)改变行列式的符号(#bb[互换]); #def[性质2.2]把某行(列)乘以非零的 $c$ 倍,行列式的值也乘以 $c$(#bb[倍乘]); #def[性质2.3]把某行(列)的 $c$ 倍加到另一行(列)上,不改变行列式的值(#bb[倍加]); #warn[ #def[易错点] 1. 把矩阵的第一行放到最后一行,实际上发生了 $n-1$ 次交换.故应乘以 $(-1)^(n-1)$ 的系数. 2. $|k bold(A)| = k^n bold(A)$ 而不是 $k bold(A)$.同理 $|-bold(A)| = (-1)^n |bold(A)|$ 而不是 $-|bold(A)|$! ] == 行列式的展开 === 主子式 设 $bold(A) = (a_(i j))_(m times n)$,在 $bold(A)$ 中选取 $k$ 行 $(i_1,i_2,dots,i_k)$,选取 $k$ 列 $(j_1,j_2,dots,j_k)$,取位于交叉位置的 $k^2$ 个元素,按照原来的位置构成的 $k$ 阶行列式称为矩阵 $bold(A)$ 的 $k$ 阶 *主子式*,记为 $N=D display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k))$. === 余子式与代数余子式 在 $bold(A) = (a_(i j))_(n times n)$ 中,划掉元素 $a_(i j)$ 所在的第 $i$ 行和第 $j$ 列,余下的位置按原来的位置构成 $n-1$ 阶行列式称为元素 $a_(i j)$ 的#bb[余子式],记为 $M_(i j)$. 再记 $A_(i j) = (-1)^(i+j) M_(i j)$ 称为元素 $a_(i j)$ 的#bb[代数余子式]. 类似的,对于矩阵的 $k$ 阶子式 $N$,定义去掉其所在的 $k$ 行 $k$ 列后,余下元素按照原来位置组成的 $n-k$ 阶行列式,称为 $N$ 的#bb[余子式],记为 $M=M display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k))$.类似的有,$N$ 的#bb[代数余子式],记为 $A=A display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k)) = (-1)^(i_1+i_2+dots.c+i_k+j_1+j_2+dots.c+j_k) M display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k))$. === 行列式按某一行或某一列展开 按照行展开有: $ a_(i 1)A_(j 1) + a_(i 2)A_(j 2) + dots.c + a_(i n)A_(j n) = cases(D\,quad& i=j,0\,quad& i!=j) $ 按照列展开有 $ a_(1 i)A_(1 j) + a_(2 i)A_(2 j) + dots.c + a_(n i)A_(n j) = cases(D\,quad& i=j,0\,quad& i!=j) $ #note[在后文证明伴随矩阵($bold(A)^*$)相关性质的时候会用到.] === Laplace 定理 对于任取 $n$ 阶方阵 $bold(A)$,任取其中 $k$ 行(列),则由这 $k$ 行(列)构成的一切 $k$ 阶子式 $N_1,N_2,dots,N_t$(其中 $t=C_n^k$)与他们所对应的代数余子式 $A_1,A_2,dots,A_t$ 相乘的和等于 $|bold(A)|$.即: $ |bold(A)| = sum_(1<=j_1<j_2<dots.c<j_k<=n) D display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k)) A display(vec(i_1 i_2 dots.c i_k, j_1 j_2 dots.c j_k)) $ == Cramer 法则 在线性方程组中,如果 $m=n$,且系数矩阵行列式 $D!=0$,则线性方程组有唯一解,且可用行列式表示为: $ x_1 = D_1/D,sp x_2 = D_2/D,dots,sp x_n=D_n/D\ "其中 " D_j = mat( a_11,dots.c,a_(1,j-1),b_1,a_(1,j+1),dots.c,a_(1 n); a_21,dots.c,a_(2,j-1),b_2,a_(2,j+1),dots.c,a_(2 n); dots.v,,dots.v,dots.v,dots.v,,dots.v; a_(n 1),dots.c,a_(n,j-1),b_n,a_(n,j+1),dots.c,a_(n n); ) quad (j=1,2,dots,n) $ == 特殊类型的行列式 === 关于主对角线的上(下)三角行列式 $ mat( a_11,a_12,dots.c,a_(1 n); " ",a_22,dots.c,a_(2 n); " ",,dots.down,dots.v; " ",,,a_(n n); ) = mat( a_11,,,; a_21,a_22,,; dots.v,dots.v,dots.down,; a_(n 1),a_(n 2),dots.c,a_(n n); ) = mat( a_11,,; " ",a_22,,; " ",,dots.down,; " ",,,a_(n n); ) = a_11 a_(22) dots.c a_(n n) $ === 关于次对角线的上(下)三角行列式 $ mat( " ",,,a_(1 n); " ",,a_(2,n-1),a_(2 n); " ",dots.up,dots.v,dots.v; a_(n 1),dots.c,a_(n,n-1),a_(n n); ) = mat( a_11,dots.c,a_(1,n-1),a_(1 n); a_21,dots.c,a_(2,n-1),; dots.v,dots.up,,; a_(n 1),,,; ) = mat( " ",,,a_(1 n); " ",,a_(2,n-1),; " ",dots.up,,; a_(n 1),,,; ) = (-1)^(n(n-1)/2) a_11 a_(22) dots.c a_(n n) $ #warn[注意不要忘记乘以 $(-1)^(n(n-1)/2)$ 的系数.] === Vandermonde 行列式 $ D(a_1,a_2,dots.c,a_n) = mat( 1,1,dots.c,1; a_1,a_2,dots.c,a_n; a_1^2,a_2^2,dots.c,a_n^2; dots.v,dots.v,,dots.v; a_1^(n-1),a_2^(n-1),dots.c,a_n^(n-1) ) = product_(1<=i<j<=n) (a_j - a_i) $ #note[ 有时可以通过对整行(列)作乘法将矩阵调整到 Vandermonde 矩阵的形式. #def[易错]注意到是 $1$ 的行(列)在最上面(最左边),否则需要乘以左右翻转矩阵带来的系数 $(-1)^(n(n-1)/2)$. ] === “箭形”行列式 $ D_n &= mat( x_1,1,1,dots.c,1; 1,x_2,0,dots.c,0; 1,0,x_3,dots.c,0; dots.v,dots.v,dots.v,,dots.v; 1,0,0,dots.c,x_n; ) = product_(i=2)^n x_i mat( x_1,1/x_2,1/x_3,dots.c,1/x_n; 1,1,0,dots.c,0; 1,0,1,dots.c,0; dots.v,dots.v,dots.v,,dots.v; 1,0,0,dots.c,1; )\ &= product_(i=2)^n x_i mat( x_1-sum_(i=2)^n 1/(x_i),1/x_2,1/x_3,dots.c,1/x_n; 0,1,0,dots.c,0; 0,0,1,dots.c,0; dots.v,dots.v,dots.v,,dots.v; 0,0,0,dots.c,1; ) = (product_(i=2)^n x_i)(x_1-sum_(i=2)^n 1/(x_i)) $ === “两三角形”行列式 对角线上方元素均为 $a$,下方元素均为 $b$,对角线上元素全为 $x_1,x_2,dots.c,x_n$ 的矩阵的行列式. ==== $a=b$ 的情况 将第 $i=2,3,dots.c,n$ 行都减去第一行得 $ D_n = mat( x_1,a,a,dots.c,a; a-x_1,x_2-a,0,dots.c,0; a-x_1,0,x_3-a,dots.c,0; dots.v,dots.v,dots.v,,dots.v; a-x_1,0,0,dots.c,x_n-a; ) $ 即化成了箭形行列式,所以: $ D_n = (product_(i=2)^n (x_i-a)) (x_1 - a(a-x_1)sum_(i=2)^n 1/(x_i-a)) $ ==== $a!=b$ 或对角线上元素全相等的情况. $ D_n &= mat( x_1,a,a,dots.c,a; b,x_2,a,dots.c,a; b,b,x_3,dots.c,a; dots.v,dots.v,dots.v,,dots.v; b,b,b,dots.c,x_n; ) = mat( x_1,a,a,dots.c,a; b,x_2,a,dots.c,a; b,b,x_3,dots.c,a; dots.v,dots.v,dots.v,,dots.v; b,b,b,dots.c,b; ) + mat( x_1,a,a,dots.c,0; b,x_2,a,dots.c,0; b,b,x_3,dots.c,0; dots.v,dots.v,dots.v,,dots.v; b,b,b,dots.c,x_n-b; )\ &= b product_(i=1)^(n-1) (x_i-a) + (x_n-b) D_(n-1) $ 如果 $a=b$ 且 $x_1=x_2=dots.c=x_n$,这里也可用数列递推的方法计算. 否则可同理得到 $D_n = display(a product_(i=1)^(n-1) (x_i-b) + (x_n-a) D_(n-1))$.两式联立可得 $ D_n = 1/(a-b) (a product_(i=1)^n (x_i-b) - b product_(i=1)^n (x_j - a)) $ === 特殊的分块矩阵 $ D_(s+t) = mat(bold(A_(s times s)),bold(O);bold(C_(t times s)),bold(B_(t times t))) = mat(bold(A_(s times s)),bold(C_(s times t));bold(O),bold(B_(t times t))) = |bold(A_(s times s))| |bold(B_(t times t))|\ D_(s+t) = mat(bold(O),bold(A_(s times s));bold(B_(t times t)),bold(C_(t times s))) = mat(bold(C_(s times t)),bold(A_(s times s));bold(B_(t times t)),bold(O)) = (-1)^(s times t) |bold(A_(s times s))| |bold(B_(t times t))| $ 可以由 Laplace 定理得到. == 求行列式的一些技巧 === 递推法 $ "eg. " D_n = mat( a,b,0,0,dots.c,0,0; c,a,b,0,dots.c,0,0; 0,c,a,b,dots.c,0,0; 0,0,c,a,dots.c,0,0; dots.v,dots.v,dots.v,dots.v,,dots.v,dots.v; 0,0,0,0,dots.c,a,b; 0,0,0,0,dots.c,c,a; ) $ 按照第一列 Laplace 展开可以得到 $D_n = a D_(n -1) - b c D_(n-2)$.根据#bb[特征方程法]可以求得递推式,或可考虑#bb[归纳证明]. === 累加法 $ "eg. " D_n = mat( 1,2,3,dots.c,n-2,n-1,n; 1,-1,0,dots.c,0,0,0; 0,2,-2,dots.c,0,0,0; dots.v,dots.v,dots.v,,dots.v,dots.v,dots.v; 0,0,0,dots.c,2-n,n-2,0; 0,0,0,dots.c,0,1-n,n-1; ) $ 可以将每一列都累加到第一列,这样第一列仅有第一个元素为 $display(n(n+1)/2)$,其余项皆为 $0$.重复此过程,每次可以使问题降低一个维度,最后得到 $display(D_n = (-1)^(n-1) (n+1)!/2)$. 对于整行(列)元素和相同的矩阵也可以类比此方法. #set math.mat(delim: "(")
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/028.%20gh.html.typ
typst
gh.html Great Hackers Want to start a startup? Get funded by Y Combinator. July 2004(This essay is derived from a talk at Oscon 2004.) A few months ago I finished a new book, and in reviews I keep noticing words like "provocative'' and "controversial.'' To say nothing of "idiotic.''I didn't mean to make the book controversial. I was trying to make it efficient. I didn't want to waste people's time telling them things they already knew. It's more efficient just to give them the diffs. But I suppose that's bound to yield an alarming book.EdisonsThere's no controversy about which idea is most controversial: the suggestion that variation in wealth might not be as big a problem as we think.I didn't say in the book that variation in wealth was in itself a good thing. I said in some situations it might be a sign of good things. A throbbing headache is not a good thing, but it can be a sign of a good thing-- for example, that you're recovering consciousness after being hit on the head.Variation in wealth can be a sign of variation in productivity. (In a society of one, they're identical.) And that is almost certainly a good thing: if your society has no variation in productivity, it's probably not because everyone is Thomas Edison. It's probably because you have no Thomas Edisons.In a low-tech society you don't see much variation in productivity. If you have a tribe of nomads collecting sticks for a fire, how much more productive is the best stick gatherer going to be than the worst? A factor of two? Whereas when you hand people a complex tool like a computer, the variation in what they can do with it is enormous.That's not a new idea. <NAME> wrote about it in 1974, and the study he quoted was published in 1968. But I think he underestimated the variation between programmers. He wrote about productivity in lines of code: the best programmers can solve a given problem in a tenth the time. But what if the problem isn't given? In programming, as in many fields, the hard part isn't solving problems, but deciding what problems to solve. Imagination is hard to measure, but in practice it dominates the kind of productivity that's measured in lines of code.Productivity varies in any field, but there are few in which it varies so much. The variation between programmers is so great that it becomes a difference in kind. I don't think this is something intrinsic to programming, though. In every field, technology magnifies differences in productivity. I think what's happening in programming is just that we have a lot of technological leverage. But in every field the lever is getting longer, so the variation we see is something that more and more fields will see as time goes on. And the success of companies, and countries, will depend increasingly on how they deal with it.If variation in productivity increases with technology, then the contribution of the most productive individuals will not only be disproportionately large, but will actually grow with time. When you reach the point where 90% of a group's output is created by 1% of its members, you lose big if something (whether Viking raids, or central planning) drags their productivity down to the average.If we want to get the most out of them, we need to understand these especially productive people. What motivates them? What do they need to do their jobs? How do you recognize them? How do you get them to come and work for you? And then of course there's the question, how do you become one?More than MoneyI know a handful of super-hackers, so I sat down and thought about what they have in common. Their defining quality is probably that they really love to program. Ordinary programmers write code to pay the bills. Great hackers think of it as something they do for fun, and which they're delighted to find people will pay them for.Great programmers are sometimes said to be indifferent to money. This isn't quite true. It is true that all they really care about is doing interesting work. But if you make enough money, you get to work on whatever you want, and for that reason hackers are attracted by the idea of making really large amounts of money. But as long as they still have to show up for work every day, they care more about what they do there than how much they get paid for it.Economically, this is a fact of the greatest importance, because it means you don't have to pay great hackers anything like what they're worth. A great programmer might be ten or a hundred times as productive as an ordinary one, but he'll consider himself lucky to get paid three times as much. As I'll explain later, this is partly because great hackers don't know how good they are. But it's also because money is not the main thing they want.What do hackers want? Like all craftsmen, hackers like good tools. In fact, that's an understatement. Good hackers find it unbearable to use bad tools. They'll simply refuse to work on projects with the wrong infrastructure.At a startup I once worked for, one of the things pinned up on our bulletin board was an ad from IBM. It was a picture of an AS400, and the headline read, I think, "hackers despise it.'' [1]When you decide what infrastructure to use for a project, you're not just making a technical decision. You're also making a social decision, and this may be the more important of the two. For example, if your company wants to write some software, it might seem a prudent choice to write it in Java. But when you choose a language, you're also choosing a community. The programmers you'll be able to hire to work on a Java project won't be as smart as the ones you could get to work on a project written in Python. And the quality of your hackers probably matters more than the language you choose. Though, frankly, the fact that good hackers prefer Python to Java should tell you something about the relative merits of those languages.Business types prefer the most popular languages because they view languages as standards. They don't want to bet the company on Betamax. The thing about languages, though, is that they're not just standards. If you have to move bits over a network, by all means use TCP/IP. But a programming language isn't just a format. A programming language is a medium of expression.I've read that Java has just overtaken Cobol as the most popular language. As a standard, you couldn't wish for more. But as a medium of expression, you could do a lot better. Of all the great programmers I can think of, I know of only one who would voluntarily program in Java. And of all the great programmers I can think of who don't work for Sun, on Java, I know of zero.Great hackers also generally insist on using open source software. Not just because it's better, but because it gives them more control. Good hackers insist on control. This is part of what makes them good hackers: when something's broken, they need to fix it. You want them to feel this way about the software they're writing for you. You shouldn't be surprised when they feel the same way about the operating system.A couple years ago a venture capitalist friend told me about a new startup he was involved with. It sounded promising. But the next time I talked to him, he said they'd decided to build their software on Windows NT, and had just hired a very experienced NT developer to be their chief technical officer. When I heard this, I thought, these guys are doomed. One, the CTO couldn't be a first rate hacker, because to become an eminent NT developer he would have had to use NT voluntarily, multiple times, and I couldn't imagine a great hacker doing that; and two, even if he was good, he'd have a hard time hiring anyone good to work for him if the project had to be built on NT. [2]The Final FrontierAfter software, the most important tool to a hacker is probably his office. Big companies think the function of office space is to express rank. But hackers use their offices for more than that: they use their office as a place to think in. And if you're a technology company, their thoughts are your product. So making hackers work in a noisy, distracting environment is like having a paint factory where the air is full of soot.The cartoon strip Dilbert has a lot to say about cubicles, and with good reason. All the hackers I know despise them. The mere prospect of being interrupted is enough to prevent hackers from working on hard problems. If you want to get real work done in an office with cubicles, you have two options: work at home, or come in early or late or on a weekend, when no one else is there. Don't companies realize this is a sign that something is broken? An office environment is supposed to be something that helps you work, not something you work despite.Companies like Cisco are proud that everyone there has a cubicle, even the CEO. But they're not so advanced as they think; obviously they still view office space as a badge of rank. Note too that Cisco is famous for doing very little product development in house. They get new technology by buying the startups that created it-- where presumably the hackers did have somewhere quiet to work.One big company that understands what hackers need is Microsoft. I once saw a recruiting ad for Microsoft with a big picture of a door. Work for us, the premise was, and we'll give you a place to work where you can actually get work done. And you know, Microsoft is remarkable among big companies in that they are able to develop software in house. Not well, perhaps, but well enough.If companies want hackers to be productive, they should look at what they do at home. At home, hackers can arrange things themselves so they can get the most done. And when they work at home, hackers don't work in noisy, open spaces; they work in rooms with doors. They work in cosy, neighborhoody places with people around and somewhere to walk when they need to mull something over, instead of in glass boxes set in acres of parking lots. They have a sofa they can take a nap on when they feel tired, instead of sitting in a coma at their desk, pretending to work. There's no crew of people with vacuum cleaners that roars through every evening during the prime hacking hours. There are no meetings or, God forbid, corporate retreats or team-building exercises. And when you look at what they're doing on that computer, you'll find it reinforces what I said earlier about tools. They may have to use Java and Windows at work, but at home, where they can choose for themselves, you're more likely to find them using Perl and Linux.Indeed, these statistics about Cobol or Java being the most popular language can be misleading. What we ought to look at, if we want to know what tools are best, is what hackers choose when they can choose freely-- that is, in projects of their own. When you ask that question, you find that open source operating systems already have a dominant market share, and the number one language is probably Perl.InterestingAlong with good tools, hackers want interesting projects. What makes a project interesting? Well, obviously overtly sexy applications like stealth planes or special effects software would be interesting to work on. But any application can be interesting if it poses novel technical challenges. So it's hard to predict which problems hackers will like, because some become interesting only when the people working on them discover a new kind of solution. Before ITA (who wrote the software inside Orbitz), the people working on airline fare searches probably thought it was one of the most boring applications imaginable. But ITA made it interesting by redefining the problem in a more ambitious way.I think the same thing happened at Google. When Google was founded, the conventional wisdom among the so-called portals was that search was boring and unimportant. But the guys at Google didn't think search was boring, and that's why they do it so well.This is an area where managers can make a difference. Like a parent saying to a child, I bet you can't clean up your whole room in ten minutes, a good manager can sometimes redefine a problem as a more interesting one. <NAME> seems to be particularly good at this, in part simply by having high standards. There were a lot of small, inexpensive computers before the Mac. He redefined the problem as: make one that's beautiful. And that probably drove the developers harder than any carrot or stick could.They certainly delivered. When the Mac first appeared, you didn't even have to turn it on to know it would be good; you could tell from the case. A few weeks ago I was walking along the street in Cambridge, and in someone's trash I saw what appeared to be a Mac carrying case. I looked inside, and there was a Mac SE. I carried it home and plugged it in, and it booted. The happy Macintosh face, and then the finder. My God, it was so simple. It was just like ... Google.Hackers like to work for people with high standards. But it's not enough just to be exacting. You have to insist on the right things. Which usually means that you have to be a hacker yourself. I've seen occasional articles about how to manage programmers. Really there should be two articles: one about what to do if you are yourself a programmer, and one about what to do if you're not. And the second could probably be condensed into two words: give up.The problem is not so much the day to day management. Really good hackers are practically self-managing. The problem is, if you're not a hacker, you can't tell who the good hackers are. A similar problem explains why American cars are so ugly. I call it the design paradox. You might think that you could make your products beautiful just by hiring a great designer to design them. But if you yourself don't have good taste, how are you going to recognize a good designer? By definition you can't tell from his portfolio. And you can't go by the awards he's won or the jobs he's had, because in design, as in most fields, those tend to be driven by fashion and schmoozing, with actual ability a distant third. There's no way around it: you can't manage a process intended to produce beautiful things without knowing what beautiful is. American cars are ugly because American car companies are run by people with bad taste.Many people in this country think of taste as something elusive, or even frivolous. It is neither. To drive design, a manager must be the most demanding user of a company's products. And if you have really good taste, you can, as <NAME> does, make satisfying you the kind of problem that good people like to work on.Nasty Little ProblemsIt's pretty easy to say what kinds of problems are not interesting: those where instead of solving a few big, clear, problems, you have to solve a lot of nasty little ones. One of the worst kinds of projects is writing an interface to a piece of software that's full of bugs. Another is when you have to customize something for an individual client's complex and ill-defined needs. To hackers these kinds of projects are the death of a thousand cuts.The distinguishing feature of nasty little problems is that you don't learn anything from them. Writing a compiler is interesting because it teaches you what a compiler is. But writing an interface to a buggy piece of software doesn't teach you anything, because the bugs are random. [3] So it's not just fastidiousness that makes good hackers avoid nasty little problems. It's more a question of self-preservation. Working on nasty little problems makes you stupid. Good hackers avoid it for the same reason models avoid cheeseburgers.Of course some problems inherently have this character. And because of supply and demand, they pay especially well. So a company that found a way to get great hackers to work on tedious problems would be very successful. How would you do it?One place this happens is in startups. At our startup we had <NAME> working as a system administrator. That's like having the Rolling Stones play at a bar mitzvah. You can't hire that kind of talent. But people will do any amount of drudgery for companies of which they're the founders. [4]Bigger companies solve the problem by partitioning the company. They get smart people to work for them by establishing a separate R&D department where employees don't have to work directly on customers' nasty little problems. [5] In this model, the research department functions like a mine. They produce new ideas; maybe the rest of the company will be able to use them.You may not have to go to this extreme. Bottom-up programming suggests another way to partition the company: have the smart people work as toolmakers. If your company makes software to do x, have one group that builds tools for writing software of that type, and another that uses these tools to write the applications. This way you might be able to get smart people to write 99% of your code, but still keep them almost as insulated from users as they would be in a traditional research department. The toolmakers would have users, but they'd only be the company's own developers. [6]If Microsoft used this approach, their software wouldn't be so full of security holes, because the less smart people writing the actual applications wouldn't be doing low-level stuff like allocating memory. Instead of writing Word directly in C, they'd be plugging together big Lego blocks of Word-language. (Duplo, I believe, is the technical term.)ClumpingAlong with interesting problems, what good hackers like is other good hackers. Great hackers tend to clump together-- sometimes spectacularly so, as at Xerox Parc. So you won't attract good hackers in linear proportion to how good an environment you create for them. The tendency to clump means it's more like the square of the environment. So it's winner take all. At any given time, there are only about ten or twenty places where hackers most want to work, and if you aren't one of them, you won't just have fewer great hackers, you'll have zero.Having great hackers is not, by itself, enough to make a company successful. It works well for Google and ITA, which are two of the hot spots right now, but it didn't help Thinking Machines or Xerox. Sun had a good run for a while, but their business model is a down elevator. In that situation, even the best hackers can't save you.I think, though, that all other things being equal, a company that can attract great hackers will have a huge advantage. There are people who would disagree with this. When we were making the rounds of venture capital firms in the 1990s, several told us that software companies didn't win by writing great software, but through brand, and dominating channels, and doing the right deals.They really seemed to believe this, and I think I know why. I think what a lot of VCs are looking for, at least unconsciously, is the next Microsoft. And of course if Microsoft is your model, you shouldn't be looking for companies that hope to win by writing great software. But VCs are mistaken to look for the next Microsoft, because no startup can be the next Microsoft unless some other company is prepared to bend over at just the right moment and be the next IBM.It's a mistake to use Microsoft as a model, because their whole culture derives from that one lucky break. Microsoft is a bad data point. If you throw them out, you find that good products do tend to win in the market. What VCs should be looking for is the next Apple, or the next Google.I think <NAME> knows this. What worries him about Google is not the power of their brand, but the fact that they have better hackers. [7] RecognitionSo who are the great hackers? How do you know when you meet one? That turns out to be very hard. Even hackers can't tell. I'm pretty sure now that my friend <NAME> is a great hacker. You may have read on Slashdot how he made his own Segway. The remarkable thing about this project was that he wrote all the software in one day (in Python, incidentally).For Trevor, that's par for the course. But when I first met him, I thought he was a complete idiot. He was standing in <NAME>'s office babbling at him about something or other, and I remember standing behind him making frantic gestures at Robert to shoo this nut out of his office so we could go to lunch. Robert says he misjudged Trevor at first too. Apparently when Robert first met him, Trevor had just begun a new scheme that involved writing down everything about every aspect of his life on a stack of index cards, which he carried with him everywhere. He'd also just arrived from Canada, and had a strong Canadian accent and a mullet.The problem is compounded by the fact that hackers, despite their reputation for social obliviousness, sometimes put a good deal of effort into seeming smart. When I was in grad school I used to hang around the MIT AI Lab occasionally. It was kind of intimidating at first. Everyone there spoke so fast. But after a while I learned the trick of speaking fast. You don't have to think any faster; just use twice as many words to say everything. With this amount of noise in the signal, it's hard to tell good hackers when you meet them. I can't tell, even now. You also can't tell from their resumes. It seems like the only way to judge a hacker is to work with him on something.And this is the reason that high-tech areas only happen around universities. The active ingredient here is not so much the professors as the students. Startups grow up around universities because universities bring together promising young people and make them work on the same projects. The smart ones learn who the other smart ones are, and together they cook up new projects of their own.Because you can't tell a great hacker except by working with him, hackers themselves can't tell how good they are. This is true to a degree in most fields. I've found that people who are great at something are not so much convinced of their own greatness as mystified at why everyone else seems so incompetent. But it's particularly hard for hackers to know how good they are, because it's hard to compare their work. This is easier in most other fields. In the hundred meters, you know in 10 seconds who's fastest. Even in math there seems to be a general consensus about which problems are hard to solve, and what constitutes a good solution. But hacking is like writing. Who can say which of two novels is better? Certainly not the authors.With hackers, at least, other hackers can tell. That's because, unlike novelists, hackers collaborate on projects. When you get to hit a few difficult problems over the net at someone, you learn pretty quickly how hard they hit them back. But hackers can't watch themselves at work. So if you ask a great hacker how good he is, he's almost certain to reply, I don't know. He's not just being modest. He really doesn't know.And none of us know, except about people we've actually worked with. Which puts us in a weird situation: we don't know who our heroes should be. The hackers who become famous tend to become famous by random accidents of PR. Occasionally I need to give an example of a great hacker, and I never know who to use. The first names that come to mind always tend to be people I know personally, but it seems lame to use them. So, I think, maybe I should say <NAME>, or <NAME>, or <NAME>, or someone famous like that. But I have no idea if these guys are great hackers. I've never worked with them on anything.If there is a Michael Jordan of hacking, no one knows, including him.CultivationFinally, the question the hackers have all been wondering about: how do you become a great hacker? I don't know if it's possible to make yourself into one. But it's certainly possible to do things that make you stupid, and if you can make yourself stupid, you can probably make yourself smart too.The key to being a good hacker may be to work on what you like. When I think about the great hackers I know, one thing they have in common is the extreme difficulty of making them work on anything they don't want to. I don't know if this is cause or effect; it may be both.To do something well you have to love it. So to the extent you can preserve hacking as something you love, you're likely to do it well. Try to keep the sense of wonder you had about programming at age 14. If you're worried that your current job is rotting your brain, it probably is.The best hackers tend to be smart, of course, but that's true in a lot of fields. Is there some quality that's unique to hackers? I asked some friends, and the number one thing they mentioned was curiosity. I'd always supposed that all smart people were curious-- that curiosity was simply the first derivative of knowledge. But apparently hackers are particularly curious, especially about how things work. That makes sense, because programs are in effect giant descriptions of how things work.Several friends mentioned hackers' ability to concentrate-- their ability, as one put it, to "tune out everything outside their own heads.'' I've certainly noticed this. And I've heard several hackers say that after drinking even half a beer they can't program at all. So maybe hacking does require some special ability to focus. Perhaps great hackers can load a large amount of context into their head, so that when they look at a line of code, they see not just that line but the whole program around it. <NAME> wrote that <NAME>'s success as a basketball player was due partly to his extraordinary peripheral vision. "Perfect'' eyesight means about 47 degrees of vertical peripheral vision. <NAME> had 70; he could see the basket when he was looking at the floor. Maybe great hackers have some similar inborn ability. (I cheat by using a very dense language, which shrinks the court.)This could explain the disconnect over cubicles. Maybe the people in charge of facilities, not having any concentration to shatter, have no idea that working in a cubicle feels to a hacker like having one's brain in a blender. (Whereas Bill, if the rumors of autism are true, knows all too well.)One difference I've noticed between great hackers and smart people in general is that hackers are more politically incorrect. To the extent there is a secret handshake among good hackers, it's when they know one another well enough to express opinions that would get them stoned to death by the general public. And I can see why political incorrectness would be a useful quality in programming. Programs are very complex and, at least in the hands of good programmers, very fluid. In such situations it's helpful to have a habit of questioning assumptions.Can you cultivate these qualities? I don't know. But you can at least not repress them. So here is my best shot at a recipe. If it is possible to make yourself into a great hacker, the way to do it may be to make the following deal with yourself: you never have to work on boring projects (unless your family will starve otherwise), and in return, you'll never allow yourself to do a half-assed job. All the great hackers I know seem to have made that deal, though perhaps none of them had any choice in the matter.Notes [1] In fairness, I have to say that IBM makes decent hardware. I wrote this on an IBM laptop.[2] They did turn out to be doomed. They shut down a few months later.[3] I think this is what people mean when they talk about the "meaning of life." On the face of it, this seems an odd idea. Life isn't an expression; how could it have meaning? But it can have a quality that feels a lot like meaning. In a project like a compiler, you have to solve a lot of problems, but the problems all fall into a pattern, as in a signal. Whereas when the problems you have to solve are random, they seem like noise. [4] Einstein at one point worked designing refrigerators. (He had equity.)[5] It's hard to say exactly what constitutes research in the computer world, but as a first approximation, it's software that doesn't have users.I don't think it's publication that makes the best hackers want to work in research departments. I think it's mainly not having to have a three hour meeting with a product manager about problems integrating the Korean version of Word 13.27 with the talking paperclip.[6] Something similar has been happening for a long time in the construction industry. When you had a house built a couple hundred years ago, the local builders built everything in it. But increasingly what builders do is assemble components designed and manufactured by someone else. This has, like the arrival of desktop publishing, given people the freedom to experiment in disastrous ways, but it is certainly more efficient.[7] Google is much more dangerous to Microsoft than Netscape was. Probably more dangerous than any other company has ever been. Not least because they're determined to fight. On their job listing page, they say that one of their "core values'' is "Don't be evil.'' From a company selling soybean oil or mining equipment, such a statement would merely be eccentric. But I think all of us in the computer world recognize who that is a declaration of war on.Thanks to <NAME>, <NAME>, and <NAME> for reading earlier versions of this talk.Audio of talkThe Python ParadoxJapanese TranslationRussian TranslationItalian TranslationSpanish Translation If you liked this, you may also like Hackers & Painters.
https://github.com/PhilipNelson5/Resume-Typst
https://raw.githubusercontent.com/PhilipNelson5/Resume-Typst/main/README.md
markdown
Apache License 2.0
# Typst CV Template <p align="center"> <a href="LICENSE"> <img alt="Apache-2 License" src="https://img.shields.io/badge/license-Apache%202-brightgreen"/> </a> </p> A no-frills curriculum vitae (CV) template for [Typst](https://github.com/typst/typst) that uses a YAML file for data input in order to version control CV data easily. This is based on the [popular template on Reddit](https://web.archive.org/https://old.reddit.com/r/jobs/comments/7y8k6p/im_an_exrecruiter_for_some_of_the_top_companies/) by [u/SheetsGiggles](https://web.archive.org/https://old.reddit.com/user/SheetsGiggles) and the recommendations of the [r/EngineeringResumes wiki](https://web.archive.org/https://old.reddit.com/r/EngineeringResumes/comments/m2cc65/new_and_improved_wiki). ## Demo See [**example CV**](https://github.com/jskherman/cv.typ/releases/latest/download/example.pdf) and [@jskherman's CV](https://go.jskherman.com/cv): <div align="center"> <img src="https://github.com/jskherman/cv.typ/assets/68434444/1e2f786d-b214-4c72-a5e4-24fba0f1c05c" alt="Sample CV Page 1" style="float: left; width: 49%; height: auto;"> <img src="https://github.com/jskherman/cv.typ/assets/68434444/f864e4b8-ee17-4808-b7f2-93643dcdd078" alt="Sample CV Page 2" style="float: left; width: 49%; height: auto;"> </div> ## Usage `cv.typ` is intended to be used by importing the `cv.typ` file from a "content" file (see [`example.typ`](example.typ) as an example). In this content file, call the functions which apply document styles, show CV components, and load CV data from a YAML file (see [`example.yml`](example.yml) as an example). Inside the content file you can modify several style variables and even override existing function implementations to your own needs and preferences. ### With [Typst CLI](https://github.com/typst/typst) (Recommended) The recommended usage with Typst CLI is by adding this `cv.typ` repository as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules). This way, upstream changes can be pulled easily. ``` <your-cv-repo>/ ├── cv.typ/ // git submodule | └── cv.typ ├── <your-cv-content>.typ // #import "cv.typ/cv.typ": * └── <your-cv-data>.yml ``` 1. Add [jskherman/cv.typ](https://github.com/jskherman/cv.typ) as git submodule. into your CV's repo. ``` git submodule add https://github.com/jskherman/cv.typ ``` 2. Copy and rename `example.typ` and `example.yml` to your CV's repo root directory. Use these files as template/starting point for your CV. 3. Run the following to command to automatically recompile your CV file on changes. ```bash typst watch <your-cv-content>.typ ``` Take a look at the [example setup](https://github.com/jskherman/cv.typ-example-repo) for ideas on how to get started. It includes a GitHub action workflow to compile the Typst files to PDF and upload it to Cloudflare R2. ### With [typst.app](https://typst.app) 1. Upload the [`cv.typ`](cv.typ), [`utils.typ`](utils.typ), [`example.typ`](example.typ). and [`example.yml`](example.yml) files to your Typst project. You may rename `example.typ` and `example.yml`. 2. Use `example.typ` and `example.yml` (or whatever the names after you rename it) as a template/starting point for your CV.
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/components/TypstLocal/thms/example.typ
typst
#import "lib.typ": * #show: thmrules.with(qed-symbol: $square$) #set page(width: 16cm, height: auto, margin: 1.5cm) #set heading(numbering: "1.1.") = Prime numbers = First level heading #theorem(footer: [The showybox allowes you add footer for boxes, useful when giving some explanation.])[#lorem(20)] <thm1> = Another first level heading #theorem(lorem(20)) <thm2> == Second level heading #definition[The counter will be reset after the first level of heading changes, i.e. counting within one chapter(can be changed)).] #theorem(title: [#text(fill: green, "This is another title")])[Now the counter increases by 1 for type `Theorem`.] #corollary(title: [a title], [Another body!], footer: [As well as footer!])[Corollary counter based on theorem(can be changed).] #lemma[#lorem(20)] #proof[By default the `Proof` will not count itself.\ And the `Proof` box will have a square at the right bottom corner.] #example()[By default the `example` will not count itself.] @thm1 (Use the label name to refer) @thm2
https://github.com/ntjess/toolbox
https://raw.githubusercontent.com/ntjess/toolbox/main/cetz-plus/arrow.typ
typst
#import "@preview/cetz:0.2.0" #import cetz.draw: * #let _cetz-anchor = anchor #let arrow-default-style = ( body-size: (5, 2), head-size: (4, 2), direction: ltr, ) #let arrow(pt, name: none, anchor: none, ..style) = { get-ctx(ctx => { move-to(pt) let style = resolve( ctx.style, merge: style.named(), root: "arrow", base: arrow-default-style ) let dir-rotation-map = ( ltr: 0deg, rtl: 180deg, ttb: 90deg, btt: -90deg, ) let angle = dir-rotation-map.at(repr(style.direction)) rotate(angle) if style.direction in (ttb, btt) { // Swap width and height style.body-size = style.body-size.rev() style.head-size = style.head-size.rev() } let (body-w, body-h) = style.body-size let (head-w, head-h) = style.head-size head-w += body-w let p = ( body-north-west: (0, body-h/2), body-south-west: (0, -body-h/2), body-south-east: (body-w, -body-h/2), body-north-east: (body-w, body-h/2), head-north: (body-w, head-h), head-south: (body-w, -head-h), tip: (head-w, 0), base: (0,0), body-west: (0,0), body-east: (body-w, 0), ) p.body-south = vector.lerp(p.body-south-west, p.body-south-east, 0.5) p.body-north = vector.lerp(p.body-north-west, p.body-north-east, 0.5) group(name: name, anchor: anchor, { merge-path(..style, { line((0,0), p.body-north-west, p.body-north-east, p.head-north, p.tip, name: "arrow-top") line((), p.head-south, p.body-south-east, p.body-south-west, (0,0), name: "arrow-bottom") }) on-layer(-1, { // Put in groups so anchors automatically align with rotation group(name: "body", { rect(p.body-north-east, p.body-south-west, stroke: none, fill: none) }) group(name: "head", { line(p.head-south, p.head-north, p.tip, name: "head", stroke: none, fill: none) }) }) for name in ("tip", "base") { _cetz-anchor(name, p.at(name)) } for name in ("body", "head") { for-each-anchor(name, anchor => { _cetz-anchor(name + "-" + anchor, name + "." + anchor) }) } }) }) } // Sample usage: /* #cetz.canvas({ cetz.draw.content((), [hello world]) arrow((), head-size: (6, 3), body-size: (6, 2), name: "arrow", anchor: "south", direction: rtl) for-each-anchor("arrow", anchor => { anchor = anchor.replace("-", "\n") content((), angle: -45deg, box(fill: rgb("#fff6"), inset: 0.1em, text(size: 8pt, anchor))) }) circle("arrow.tip", radius: 0.1) }) */
https://github.com/tingerrr/chiral-thesis-fhe
https://raw.githubusercontent.com/tingerrr/chiral-thesis-fhe/main/tests/core/authors/test.typ
typst
#import "/src/core/authors.typ" #set page(height: 1cm, width: 1cm) // // parsing // #import authors: parse-title, parse-name, parse-author // title #let prof = ( main: "Prof.", suffix: none, ) #let dr = ( rer-nat: ( main: "Dr.", suffix: "rer. nat.", ), sc-nat: ( main: "Dr.", suffix: "sc. nat.", ), ) #assert.eq(parse-title("Prof."), prof) #assert.eq(parse-title("Dr. rer. nat."), dr.rer-nat) #assert.eq(parse-title("Dr. sc. nat."), dr.sc-nat) // single name #assert.eq(parse-name("Frank"), (first: ("Frank",), last: ())) // first and last #let turing = ( first: ("Alan",), last: ("Turing",), ) #assert.eq(parse-name("<NAME>"), turing) #assert.eq(parse-name("<NAME>"), turing) // first, second and last single #let dumbledore = ( first: ("Albus", "Percival", "Wulfric", "Brian"), last: ("Dumbledore",), ) #assert.eq(parse-name("<NAME> <NAME>"), dumbledore) #assert.eq(parse-name("Dumbledore, <NAME>"), dumbledore) // last mutliple #let scott-moncrieff = ( first: ("Charles", "Kenneth"), last: ("Scott", "Moncrieff"), ) #let lloyd-webber = ( first: ("Andrew",), last: ("Lloyd", "Webber",), ) #assert.eq(parse-name("<NAME>, <NAME>"), scott-moncrieff) #assert.eq(parse-name("<NAME>, Andrew"), lloyd-webber) // abbreviations #let knuth = ( first: ("Donald", "E."), last: ("Knuth",), ) #assert.eq(parse-name("<NAME>"), knuth) #assert.eq(parse-name("<NAME>."), knuth) // author #let tingerrr = ( titles: ( ( main: "B.", suffix: "Sc.", ), ), name: ( first: ("tingerrr",), last: (), ), email: "<EMAIL>", ) #assert.eq(parse-author("B. Sc. tingerrr <<EMAIL>>"), tingerrr) #let kpj = ( titles: ( (main: "Prof.", suffix: none), (main: "Dr.", suffix: "rer. nat."), (main: "Dr.", suffix: "sc. nat."), ), name: ( first: ("Klaus", "Peter"), last: ("Jantke",), ), email: none, ) #assert.eq(parse-author("B. Sc. tingerrr <<EMAIL>>"), tingerrr) #assert.eq(parse-author("Prof. Dr. rer. nat. Dr. sc. nat. <NAME>"), kpj) // // formatting // #import authors: format-title, format-name, format-author // title #assert.eq(format-title(prof), "Prof.") #assert.eq(format-title(dr.rer-nat), "Dr. rer. nat.") #assert.eq(format-title(dr.sc-nat), "Dr. sc. nat.") // name #assert.eq(format-name(turing), "<NAME>") #assert.eq(format-name(knuth), "<NAME>") // comma format #assert.eq(format-name(dumbledore, last-first: true), "Dumbledore, <NAME>") // name abbreviation #assert.eq(format-name(scott-moncrieff, abbreviate: true), "<NAME>") #assert.eq(format-name(knuth, abbreviate: true), "<NAME>") // author #assert.eq(format-author(tingerrr, link: false), "<NAME> <<EMAIL>>") #assert.eq(format-author(kpj, link: false), "Prof. Dr. rer. nat. Dr. sc. nat. <NAME>")
https://github.com/AJMC2002/opt-methods
https://raw.githubusercontent.com/AJMC2002/opt-methods/main/minimization-2/report/Москера_лр2.typ
typst
#set page( paper: "a4", margin: (x: 1in, y: 1in), ) #set text(size: 12pt) #set align(center) #image("fefu_logo.jpg", width: 4%) #text( size: 10pt, [ МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ И НАУКИ РОССИЙСКОЙ ФЕДЕРАЦИИ Федеральное государственное автономное образовательное учреждение высшего образования *«Дальневосточный федеральный университет»* (ДВФУ) ]) #v(0.5fr) #line(length: 100%, stroke: 2pt) #v(0.5fr) *ИНСТИТУТ МАТЕМАТИКИ И КОМПЬЮТЕРНЫХ ТЕХНОЛОГИЙ* #v(1fr) *Департамент математического и компьютерного моделирования* #v(1fr) *ЛАБОРАТОРНАЯ РАБОТА №2* По основной образовательной программе подготовки бакалавров направлению 01.03.02 Прикладная математика и информатика профиль «Системное программирование» #v(1fr) #grid( columns: (1fr,1fr), [], [ #set align(left) Студент группы Б9121-02.03.01сцт <NAME> <NAME> «24» декабря 2023 г. #v(24pt) Преподаватель кандидат физико-математических наук #underline(" ") #text(size: 10pt, "(подпись)") <NAME> «#underline(" ")» #underline(" ") 2023 г. ] ) #v(1fr) г. Владивосток 2023 #v(1fr) #pagebreak() #set align(left) #set par( first-line-indent: 0em, justify: true, ) = Постановка задачи Найти минимум функции $RR^n$ $ f(x)=1/2 x^T A x + b x $ с условием $||x-x_0|| <= r$. = Исходные данные $A$ --- произвольная симметрическая, невырожденная матрица, $A in RR ^ (4 times 4)$ $b$ --- произвольный ненулевой вектор, $b in RR^4$ $x_0$ --- произвольный начальный ненулевой вектор, $x in RR^4$ $r$ --- радиус сферы $ A = mat( 8.917471161017044, -5.881235445212047, -3.748113781121384, 3.0726928964843987 ; -5.881235445212047, -9.040202112715473, -6.772212260246581, 2.309845893033086 ; -3.748113781121384, -6.772212260246581, 7.126513709691746, 4.664488504098735 ; 3.0726928964843987, 2.309845893033086, 4.664488504098735, 5.724519936137147 ) $ Чтобы сгенерировать симметричную матрицу $A$, генерируется случайная временная матрица $A_("temp")$ так, что $A = 1/2 (A_("temp") + A_("temp")^T)$. #grid( columns: (1fr,1fr), align(center)[$ b = vec( -1.0034508506027269, 8.494875723462954, 3.3273150949612385, 1.977512900042199 ) $], align(center)[$ x_0 = vec( 9.902751075372013, -9.113925983068228, -1.288098758917016, -5.869546741009071 ) $], ) $ r = 5.0 $ = Решение Найдём функцию Лагранжа: $ L(x,y) = 1/2 x^T A x + b x + y(||x-x_0||^2-r^2) $ Найдём точки минимума. Для этого возьмём частную производную по и приравняем её к нулю: $ (diff L)/(diff x) = A x + b + 2 y (x-x_0) = 0 $ Рассмотрим два случая: 1. _Пусть $y=0$._ $A x+b=0$, тогда $x_*=-A^(-1) b$, где $x_*$ --- «подозрительная» на минимум точка. $ x_* = vec( 0.6147706419264252, -6.822929360179975e-2, 0.4621409715178318, -1.024464312324732 ) $ $ f(x_*) = -0.8423471280686472 $ Проверим, подходит ли данная точка под условие $||x-x_0||<=r$. $ lr(|| vec( 0.6147706419264252, -6.822929360179975e-2, 0.4621409715178318, -1.024464312324732 ) - vec( 9.902751075372013, -9.113925983068228, -1.288098758917016, -5.869546741009071 ) ||) = 13.95096312032364 $ $ ||x-x_0||=13.95096312032364 <= r=5.0 $ Условие не выполняется. Таким образом, найденная точка не подходит под ограничения и не будет рассматриваться при выборе итогового ответа. 2. _Пусть $y>0$_ Преобразуем $L'_x$ и получим следующую систему уравнений из пяти уравнений: $ cases( (A+2 I y)x+(b-2 y x_0) = 0, ||x-x_0||^2 - r^2 = 0 ) $ Для нахождения точек, подозрительных на оптимум, воспользуемся методом Ньютона: $ x_(k+1) = x_k - f'^(-1)(x_k) - f(x_k) $ где $x_k$ --- пятимерный вектор неизвестных, составленный из элементов вектора $x$ и $y$. $f(x_k)$ --- левая часть данной системы, $f'(x_k)$ --- матрица Якоби данной системы уравнений. $ f'(x) = J = mat( A+2 I y, 2(x-x_0); 2(x-x_0)^T, 0 ) $ Метод Ньютона будем запускать на нескольких начальных приближениях, т.к. функция может иметь несколько оптимальных точек. За начальное приближение берётся восемь точек: #grid( columns: (1fr, 1fr), [ $ x_1 = vec( -6.5898083421499445, 0.7592215884645075, -4.226682137443012, -6.119390680278865, 8.627489224405448 ) $ $ x_2 = vec( -2.6100865251413534, 5.99242760986122, -8.74927058223387, -5.95634448776172, 3.0078855539858225 ) $ $ x_3 = vec( 1.3960738579100074, 6.462717315110776, -5.392336641442533, 9.741069773234269, 9.188512682496391 ) $ $ x_4 = vec( 7.2108095713692295, 6.869197562738942, -9.983988083646999, 4.03945099928122, 4.600615303013031 ) $ ], [ $ x_5 = vec( -7.598796223848999, 6.843339272245674, -9.182634429570456, -3.1893765108104084, 9.206199154867335 ) $ $ x_6 = vec( 6.178983466733086, 2.1890780465770114, 4.1797457469462955, -0.2392934769547459, 1.816814793169577 ) $ $ x_7 = vec( -2.292605667486429, -6.746023009212916, -4.696646180855078, 7.4200281278856375, 9.377417885952877 ) $ $ x_8 = vec( 4.611794059659715, 6.079254454194263, 7.7980462506833135, 7.846995291838499, 2.9922584062467177 ) $ ] ) Условие для выхода из цикла: $ ||x_(k+1)-x_k|| <= epsilon, $ где $epsilon = 10^(-6)$. В результате получаем несколько точек $x_i$, подозрительных на оптимум: #table( columns: (auto, 1fr, auto, auto, auto), align: center + horizon, $ bold(i) $, [*Начальное \ приближение*], $ bold(x_i) $, $ bold(y_i) $, $ bold(f(x_i)) $, "1", $ vec( -6.5898083, 0.7592215, -4.2266821, -6.1193906, 8.6274892 ) $, $ vec( 6.061015807963965, -11.876589956638057, -2.111750020911596, -4.480174039784763 ) $, $ 15.2331403 $, $ -138.21816218494826 $, "2", $ vec( -2.6100865, 5.9924276, -8.7492705, -5.9563444, 3.0078855 ) $, $ vec( 14.7481665631942, -8.998465898153777, -2.3565551605286443, -6.475367374443787 ) $, $ -17.7870006 $, $ 1311.2159918285604 $, "3", $ vec( 1.3960738, 6.4627173, -5.3923366, 9.7410697, 9.1885126 ) $, $ vec( 6.758203006065774, -13.175068797262252, 11.216595144120248, -21.872915990532427 ) $, $ -1.0726899 $, $ 1419.4616874561702 $, "4", $ vec( 7.2108095, 6.8691975, -9.9839880, 4.0394509, 4.6006153 ) $, $ vec( -12.799489605395173, 3.9115356629638285, 0.763414232449291, 4.53999352717738 ) $, $ -4.2064018 $, $ 969.446868112623 $, "5", $ vec( -7.5987962, 6.8433392, -9.1826344, -3.1893765, 9.2061991 ) $, $ vec( 6.791822024079396, -13.204440097576258, 11.234563811710583, -21.91831889661696 ) $, $ -1.0673031 $, $ 1426.0002410148386 $, "6", $ vec( 6.1789834, 2.1890780, 4.1797457, -0.2392934, 1.8168147 ) $, $ vec( -3.091764331166946, -4.569631582300696, 5.951991972588306, -8.570411385348269 ) $, $ -2.6509415 $, $ 355.862001464922 $, "7", $ vec( -2.2926056, -6.7460230, -4.6966461, 7.4200281, 9.3774178 ) $, $ vec( 6.061015807964309, -11.876589956638353, -2.1117500209120843, -4.4801740397843695 ) $, $ 15.2331403 $, $ -138.21816218496198 $, "8", $ vec( 4.6117940, 6.0792544, 7.7980462, 7.8469952, 2.9922584 ) $, $ vec( -36.51834885388397, 24.63354895348917, -11.913823909519436, 36.57261085272549 ) $, $ -8.0068537 $, $ 9408.243073065663 $ ) Выясним, в какой из данных точек функция принимает минимальное значение. Отбросим результаты, полученные при $y<0$, и получим, что минимальное значение функции $f(x)$ при заданных ограничениях достигается в точке: $ x_("min") = vec( 6.061015807963965, -11.876589956638057, -2.111750020911596, -4.480174039784763 ) $ Минимальное значение функции: $ f_("min")(x) = -138.21816218494826 $ = Приложения (Я.П.: Haskell) Весь исходный код этого приложения можно найти по адресу https://github.com/AJMC2002/opt-methods/tree/main. == Зависимости - base ^>=4.17.2.0 - massiv >= 1.0.4 && < 1.1 - parallel >= 3.2.2 && < 3.3 - random >= 1.2.1 && < 1.3 - minimization2 --- пользовательская библиотека с алгоритмами, используемыми для этой работы. == Библиотека ```haskell -- lib/Minimization.hs module Minimization (Minimization (..), mkMinimization) where import Control.Parallel.Strategies (NFData) import Data.Massiv.Array as A import Function (Functions (..), mkFunctions) import Utils (identity, inverse, split, zeros) import Prelude as P data Minimization r e = Minimization { getFunctions :: Functions r e , yIsZero :: Vector r e , yIsGreaterThanZero :: Vector r e -> Vector r e } mkMinimization :: ( NumericFloat r e , Manifest r e , Load r Ix1 e , Load r Ix2 e , Ord e , Prim e , Show e , NFData e ) => Matrix r e -> Vector r e -> Vector r e -> e -> e -> Minimization r e mkMinimization matA vecB vecX0 r epsilon = Minimization { getFunctions = functions , yIsZero = yIsZero' n functions , yIsGreaterThanZero = yIsGreaterThanZero' n matA epsilon functions } where Sz2 n _ = size matA functions = mkFunctions matA vecB vecX0 r yIsZero' :: (NumericFloat r e, Load r Ix1 e) => Int -> Functions r e -> Vector r e yIsZero' n functions = fPrimeInv functions $ zeros $ Sz1 n yIsGreaterThanZero' :: forall r e. ( NumericFloat r e , Manifest r e , Load r Ix1 e , Load r Ix2 e , Prim e , Ord e , Show e , NFData e ) => Int -> Matrix r e -> e -> Functions r e -> Vector r e -> Vector r e yIsGreaterThanZero' n matA epsilon functions vecXk0 = computeP $ recur vecXk0 (0 :: Int) where recur :: Vector r e -> Int -> Vector r e recur xk k | k >= 10000 || normL2 (xkNext !-! xk) <= epsilon = xk | otherwise = recur xkNext (k + 1) where (x, y) = split xk xkNext = xk !-! computeP (inverse fPrimeXk !>< fXk) fXk = computeP @P $ concat' 1 [up, down] where up = lagrangePrimeX functions x y down = singleton $ g functions x fPrimeXk = computeP @P $ concat' 2 [up, down] where up = computeP @P $ concat' 1 [upL, upR] down = computeP @P $ concat' 1 [downL, downR] upL = matA !+! ((2 * y) *. identity n) upR = resize' (Sz2 n 1) $ gPrime functions x downL = resize' (Sz2 1 n) $ gPrime functions x downR = singleton 0 ``` == Бинарный ```haskell -- exe/Main.hs module Main where import Control.Parallel.Strategies (parMap, rpar) import Data.Massiv.Array as A import Function (Functions (..)) import Minimization (Minimization (..), mkMinimization) import System.IO import System.Random qualified as R import Utils (split) import Prelude as P main :: IO () main = let -- Initial values salt = 190902 gen1 = R.mkStdGen salt gen2 = snd $ R.split gen1 gen3 = snd $ R.split gen2 rng = (-10 :: Double, 10) comp = ParN 0 dim = 4 tempA = computeP $ uniformRangeArray gen1 rng comp (Sz2 dim dim) :: Matrix P Double matA = (tempA !+! computeP (transpose tempA)) ./ 2 -- this generates a symmetric matrix vecB = computeP $ uniformRangeArray gen2 rng comp (Sz1 dim) vecX0 = computeP $ uniformRangeArray gen3 rng comp (Sz dim) r = 5 epsilon = 1.0e-6 minimization = mkMinimization matA vecB vecX0 r epsilon funs = getFunctions minimization -- Part 1 | When y = 0 vecXSus = yIsZero minimization -- podozritel'niy fSus = f funs vecXSus distanceToCentre = normL2 (vecXSus !-! vecX0) isInSphere = distanceToCentre <= r -- Part 2 | When y > 0 numPoints = 8 gs = P.tail $ P.take (numPoints + 1) $ iterate (snd . R.split) gen3 xy0s = P.map ( \g -> let xy' = computeP @P $ uniformRangeArray g rng comp (Sz1 dim + 1) xy = makeArray @P (ParN 0) (Sz1 dim + 1) (\i -> if i == dim then abs (xy' ! i) else xy' ! i) in xy ) gs xySols = parMap rpar (split . yIsGreaterThanZero minimization) xy0s fXY = parMap rpar (f funs . fst) xySols in do handle <- openFile "output.txt" WriteMode hPutStrLn handle "A" hPrint handle matA hPutStrLn handle "b" hPrint handle vecB hPutStrLn handle "x0" hPrint handle vecX0 hPutStrLn handle "r" hPrint handle r hPutStrLn handle "** y = 0 **" hPutStrLn handle "Solution" hPrint handle vecXSus hPutStrLn handle "Minimal value" hPrint handle fSus hPutStrLn handle "Distance to centre" hPrint handle distanceToCentre hPutStrLn handle "Is in sphere?" hPrint handle isInSphere hPutStrLn handle "** y > 0 **" hPutStrLn handle "Initial vectors" hPrint handle xy0s hPutStrLn handle "Solutions" hPrint handle xySols hPutStrLn handle "Minimal values" hPrint handle fXY hClose handle ```
https://github.com/lonkaars/typst-metalogo
https://raw.githubusercontent.com/lonkaars/typst-metalogo/master/metalogo.typ
typst
MIT License
// TODO: base should *actually* be lowered by 0.5ex, but Typst does not yet // have an ex unit, only em. See https://github.com/typst/typst/issues/2405 #let baseline-drop = 0.22em #let TeX = [#box(baseline: baseline-drop)[T#h(-.1667em)#box(baseline: baseline-drop)[E]#h(-.125em)X]] #let Xe = [#box(baseline: baseline-drop)[X#h(-.1667em)#box(baseline: baseline-drop)[#scale(x: -100%)[E]]#h(-.125em)]] #let LaTeX = [#box(baseline: baseline-drop)[L#h(-.33em)#box(baseline: -0.2em)[#text(0.7em)[A]]#h(-.15em)#TeX]] #let XeTeX = [#box(baseline: baseline-drop)[#Xe#TeX]] #let XeLaTeX = [#box(baseline: baseline-drop)[#Xe#LaTeX]] #let LuaLaTeX = [#box(baseline: baseline-drop)[Lua#LaTeX]]
https://github.com/Pablo-Gonzalez-Calderon/apuntes-botanica
https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/apuntes-botanica/main/src/months/november.typ
typst
Other
#import "../template.typ": new-class, examplebox, obsbox, figure-box, gloss #import "@preview/showybox:2.0.1": * #import "@preview/tablex:0.0.4": * #let clase-17-18 = [ #new-class(new-page: true, "Reproducción en plantas II", "06 de noviembre de 2023") #gloss(size: 21em)[ / Placentación: Disposición de los óvulos en el ovario. / Dehiscencia: Apertura de la antera para la liberación del polen. / Primordio marginal: Primordio seminal se origina en los margenes foliares. Asociado a *placentación marginal.* / Primordio parietal: Primordio seminal se origina en las paredes foliares. Asociado a *placentación parietal.* / Sifonogamia: Proceso que permite la transferencia de gametos masculinos a los femeninos en las plantas, mediante la extensión del tubo polínico. / Verticilo: Conjunto de piezas o elementos florales de un mismo nudo. / Pieza o elemento: Cada uno de los antófilos de la flor. / Coalescencia: Unión de las piezas de un mismo verticilo. / Adnación: Unión de elementos de distintos verticilos. ] Vamos a continuar hablando de la reproducción de las Antófitas. Recordemos que la parte femenina se denomina _gineceo,_ compuesto por los elementos denominados _carpelos,_ los cuales pueden estar en cantidades variadas, pudiendo formar un solo pistilo o tantos pistilos como carpelos haya. #grid( columns: (1fr, 1fr), [ Ahora pondremos foco en la estructura alrededor del ovario. #figure-box()[ $ "Ovario" arrow& "Fruto" \ "Primordios seminales" arrow& "Semilla" $ ] *Un carpelo puede tener un solo primordio seminal o varios primordios seminales,* por lo que no se puede determinar el número de semillas en base a solo el número de carpelos o el número de lóculos: varía de planta en planta. #examplebox()[ Un caso sencillo es el durazno, el cual posee un solo carpelo, el cual da origen a una sola semilla (posee un solo primordio seminal). Pero no todas las plantas que generan semillas tendrán el mismo comportamiento. ] ], figure( caption: "Placentación parietal (izquierda) y marginal (derecha).", image("../figures/fig_placentacion.svg") ) ) Podemos visualizar los carpelos como hojas "unidas consigo mismas" por los márgenes foliares. Aquí, si el primordio seminal se genera en la zona de unión de los márgenes, se denomina *primordio marginal,* mientras que si se genera en las paredes de la hoja se llamará *primordio parietal*; ambos términos asociados a una *placentación marginal* y una *placentación parietal.* Existen más tipos de placentación, pero no serán relevantes para el curso. = Estructura del primordio seminal #grid( columns: (1fr, 1fr), [ El primordio está formado a partir de la parte femenina de la flor. Es una estructura *diploide,* cuya función es formar una espora, pues pertenece a un esporofito. Se conecta mediante el *funículo* a la placenta, a través del cual se puede nutrir (pasa un haz de xilema y de floema). Más adelante, cuando sea necesario que se libere la semilla, se tendrá que cortar este "cordón". Al interior del primordio seminal hay un tejido que se denomina *nucela* (megaesporangio) encargado de la formación de una espora, la cual, posteriormente, será responsable de la formación del gametofito. ], figure( caption: "Partes del primordio seminal", image("../figures/fig_primordio_seminal.svg") ) ) #figure-box()[ $ "Primordio seminal" arrow.long limits("Nucela")_"(megaesporangio)" limits(arrow.long)^("tiene") limits("Esporocito")_"(solo 1, llamado \n célula madre de \n la megaespora)" limits(arrow.long)^("meiosis") "4 esporas" $ ] Sin embargo, la nucela no está al descubierto, sino que está cubierta por una capa del primordio llamada *tegumentos,* los cuales posteriormente darán origen a la *testa* (cáscara). Adicionalmente, existe una zona que _no_ está cubierta por los tegumentos, denominada *micropilo,* cuyas funciones son principalmente dos: + Permitir la fecundación, al dejar pasar el espermio + Permitir la germinación de la semilla #obsbox()[ Es importante recordar que la nucela no generará directamente el óvulo, sino que generará esporas que darán origen a gametofitos, los cuales sí formarán al óvulo. ] /* INFORMACIÓN DEL LABORATORIO + CÁPSULA */ = Morfología floral#footnote("Buena parte de esta información fue extraída de la guía de laboratorio de Morfología Floral, cuyos autores son los profesores del curso de Botánica") Las flores consisten en un eje o *pedicelo,* el cual en su extremo más alejado se ensancha, dando origen al *tálamo* o *receptáculo floral,* sobre el cual se encuentran unas estructuras denominadas *verticilos florales.* Desde el más externo (más alejado del óvulo) al más interno (más cercano al óvulo) los verticilos florales son: + *Cáliz:* Verticilo constituido por hojas modificadas denominadas *sépalos.* + *Corola:* Conjunto de hojas modificadas denominadas *pétalos.* + *Androceo:* Formado por las estructuras reproductivas masculinas, es decir, los *estambres.* + *Gineceo:* Constituido por las estructuras reproductivas femeninas, es decir, los *carpelos*, en cuyo interior estarán los óvulos. #obsbox()[ El cáliz y la corola constituyen el *perianto,* el cual, no obstante, puede no siempre estar presente. Cuando los elementos de ambos, caliz y corola, son similares en fisonomía, se debe hablar de *perigonio*, el cual está formado por los *tépalos.* ][ Los verticilos florales fundamentales son el androceo y el gineceo, mientras que los accesorios son el cáliz y la corona. ] == Androceo Como se mencionó en clases anteriores, los estambres están formados por *filamento* y *antera*, siendo esta última constituida por dos *tecas,* las cuales, a su vez, poseen dos *sacos polínicos* cada una. Al interior de los sacos polínicos se formarán los *granos de polen o microsporas.* Los estambres pueden estar tanto *libres* (separados unos de los otros), como estar unidos por los filamentos (*monoadelfos*) o por las anteras (*sinantéreos*). == Gineceo Como se mencionó en clases pasadas, los carpelos pueden estar libres (*apocárpico*) o fusionados (*sincárpico*). En el gineceo, se hallan principalmente tres estructuras: el *ovario* o cuerpo hueco, encargado de contener uno o más *rudimentos o primordios seminales;* el *estilo*, resultado de la elongación de las paredes del ovario; y el *estigma* o extremo distal del estilo, donde será retenido el polen durante el proceso de polinización. Además, recordemos que los rudimentos seminales están adheridos a las paredes internas del ovario a través de la *placenta.* Finalmente, según la posición del ovario, las flores se pueden clasificar en *flores hipóginas* cuando el ovario es súpero, y *flores epiginas* cuando el ovario es ínfero. #obsbox()[ En algunos casos el ovario puede estar "en medio", lo cual se denomina ovario semiínfero, característico de *flores periginias.* Se preferirá no usar esta denominación. ] == Ontogenia de la flor Recordemos que las flores tienen su origen en un ápice reproductivo que resulta de la transformación de un ápice vegetativo de posición terminal o bien axilar. Cuando un meristema apical va a producir el primordio floral, termina su posibilidad de crecimiento ilimitado, y propicia la producción de un mayor número de apéndices laterales que darán origen a todas las estructuras del primordio floral. Durante la iniciación del estado reproductivo, se observa que el eje meristemático se elonga rápidamente y, posteriormente, se aplasta su ápice, dando término a la organización túnica-corpus. La formación sucesiva de los verticilos florales ocurre por divisiones periclinales y anticlinales de células del meristema transformado. La formación de los sépalos, pétalos y carpelos es parecida a la que se observa en los primordios foliares, siendo diferente la formación de los estambres por ocurrir en éstos un gran crecimiento intercalar que da origen al filamento. La iniciación de los elementos florales se caracteriza por un aumento del índice mitótico de las células que componen estos meristemas. La anatomía interna de los sépalos es similar a la de las hojas, sin embargo, los pétalos y sépalos coloreados presentan una estructura más simple, con células epidérmicas de paredes muy delgadas, un sistema vascular pobremente desarrollado y sin esclerénquima. El mesófilo está constituido por un parénquima muy esponjoso cuyas células contienen cromoplastos y/o pigmentos antocianos en sus vacuolas. == Clasificación morfológica floral Las flores pueden clasificarse según el número de elementos que constituyen sus verticilos, siendo: + *Trímeras:* Elementos en grupos de 3 o múltiplos de 3. Característico de _Monocotiledóneas._ + *Tetrámeras:* Elementos en grupos de 4 o múltiplos de 4. + *Pentámeras:* Elementos en grupos de 5 o múltiplos de 5. #obsbox()[ Las _Dicotiledóneas_ se caracterizan por ser tanto tetrámeras como pentámeras. ] Por otro lado, las flores también pueden clasificarse por sus relaciones de simetría, es decir, la distribución espacial de las partes que las componen: + *Simetría bilateral:* Se observa en flores *zigomorfas* ($%$), donde solo una línea que pasa por el centro de la flor la puede dividir en dos partes iguales. + *Simetría radiada:* Se observa en flores *actinomorfas* ($*$), donde cualquier dirección o línea que pasa por el centro de la flor la divide en dos partes iguales. + *Asimetría:* Las flores asimétricas son aquellas que no poseen ningún plano de simetría. == Clasificación de inflorescencias Cuando las flores están agrupadas en el extremo distal del eje, forman una inflorescencia, las cuales pueden ser: + *Inflorescencias racemosas:* Aquellas que poseen un eje principal que mantiene en su extremo meristema apical y que predomina sobre todas las ramas laterales. Poseen *crecimiento ilimitado y desarrollo acrópeto.* + *Racimo:* Eje indefinido de cuyos lados se desarrollan acrópetamente flores sobre el pedicelo. El racimo compuesto forma una inflorescencia llamada *panícula.* + *Espiga:* Es similar al racimo, pero con la diferencia de que las flores que la constituyen no poseen pedicelos. + *Espádice:* Es parecido a la espiga, con la diferencia de que el eje central está notablemente engrosado. También se conocen como inflorescencias racemosas a aquellas en las cuales los ejes laterales son de igual desarrollo que el eje principal. En este caso, este eje no se diferencia claramente de los laterales. Se distinguen: + *Umbela:* Todos los ejes florales arrancan de un mismo punto y, generalmente, son de igual longitud, formando una especie de "paraguas". Pueden ser simples o compuestas. + *Capítulo o cabezuela:* El eje principal posee numerosas flores sésiles acumuladas en su extremo superior relativamente engrosado y, a menudo, ensanchado en forma de un receptáculo disciforme. + *Inflorescencias cimosas:* Aquellas que poseen un eje que termina en una flor, siendo también denominadas inflorescencias definidas, con desarrollo *basípeto.* + *Escorpioidea:* Las flores laterales se disponen hacia un mismo lado. Las rama lateral puede a su vez producir sucesivas ramas bajo la principal. + *Bípara:* Produce dos ramas laterales (una a cada lado) bajo la flor del eje principal. Las ramas laterales pueden a su vez producir sucesivos pares de ramas bajo la principal. == Resumen coalescencias Las uniones de las piezas de un mismo verticilo se nombran según la siguiente tabla resumen: #align(center, tablex( align: center + horizon, columns: (100pt, 100pt, 100pt), [],[*Unidos*], [*Separados*], [*Sépalos*], [Gamopétalos], [Dialisépalos], [*Pétalos*], [Gamopétalos], [Dialipétalos], [*Carpelos*], [Sincárpico], [Apocárpico], rowspanx(2)[*Estambres*], [Monoadelfo \ (por estambres)], rowspanx(2)[Libres], [Sinantéreo \ (por anteras)] )) = Fórmulas florales Son una manera esquemática de representar la estructura de una flor. Para ello se utilizan los siguientes símbolos convencionales: - $*$ = Flor actinomorfa (simetría radial) - $%$ = Flor zigomorfa (simetría bilateral) #block(width: 140pt, above: .65em)[ - $P$ = Perigonio - $K$ = Cáliz #place( right + horizon, align(horizon)[ #text(size: 2em, "}") Perianto ] ) ] - $C$ = Corola - $A$ = Androceo - $G$ = Gineceo - $()$ = Unión de elementos de un mismo verticilo (coalescencia) - $[]$ = Unión de los elementos de verticilos diferentes (adnación) El número de piezas o elementos que componen un verticilo se indican con un número. Cuando este es muy grande, se representa mediante el signo $oo$. La posición del ovario se determina con una línea bajo el número de carpelos cuando este es súpero (flor hipógina) ; o sobre el número de carpelos cuando este es ínfero (flor epigina). #examplebox()[ Las especies de la familia _Lamiaceae_ poseen la siguiente fórmula floral: $ % K (5) [C (5) A 5] G (underline(2)) $ ] = Generación alternante en las Angiospermas (continuación) + La generación dominante es la *esporofítica* + Se forman _dos_ tipos de esporas (*heterosporas*): una espora femenina o *ginospora* (_megasporas_) y una espora masculina o *androspora* (_microsporas_). + El embrión no se desarrolla inmediatamente. Entra en latencia, pues se forma la semilla (espermatófitas). + Generan polen, el cual corresponde a gametos masculinos _sésiles_ (no poseen flagelo), moviéndose a través del tubo polínico gracias a la *sifonogamia.* #obsbox()[ La heterosporía también aparece en las Coníferas, las que son heterosporíficas desde antes que las angiospermas. ] En el caso de las esporas masculinas, las esporas se encuentran al interior del grano de polen, donde, también, se formará el gameto masculino. Es importante mencionar que antes de la fecundación es necesario el proceso de *polinización.* = Formación de gametos masculinos #figure( caption: "Ilustración de la formación de los gametos masculinos", image("../figures/fig_formacion_gameto_masculino.svg", height: 5.5cm) ) == Microesporogénesis #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) #text(red)[Esporofito #sym.arrow Esporas] #sym.arrow Gametofitos #sym.arrow Gametos #sym.arrow Esporofito ]) Es el proceso de formación de las esporas masculinas (_microsporas_). Este proceso toma lugar dentro de los sacos polínicos, siendo estos los *esporangios* (microsporangios). Dentro de los sacos polínicos estarán los *esporocitos*, los cuales generarán esporas por meiosis recubiertas con una *capa protectora,* denominada *exina.* Estas esporas se conocen comúnmente como polen. #figure( caption: "Estructuras que preceden a los sacos polínicos", figure-box(width: 60%, align: center, align(center)[ Estambre #sym.arrow.long Antera #sym.arrow.long 2 Tecas #sym.arrow.long 2 Sacos polínicos ]) ) El grano de polen se caracteriza por ser *unicelular* y *haploide* al momento de ser formado. == Microgametogénesis #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) Esporofito #sym.arrow Esporas #sym.arrow #text(red)[Gametofitos #sym.arrow Gametos] #sym.arrow Esporofito ]) Ahora, dentro del grano de polen, la espora se divide en dos, dejando de ser una espora (pues ahora es pluricelular), constituyendo un *microgametofito.* Dentro del microgametofito, una de las células se denomina *célula vegetativa* (célula del tubo polínico), y la otra se denomina *célula generativa.* Finalmente, el microgametofito deberá formar los gametos. Para ello, la célula generativa se dividirá en dos, dando origen a dos gametos. Así, *dentro del grano de polen habrán 2 gametos masculinos y una célula vegetativa. * = Formación de gametos femeninos #figure( caption: "Ilustración de la formación de los gametos femeninos", image("../figures/fig_formacion_gameto_femenino.svg", height: 6cm) ) == Megaesporogénesis #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) #text(red)[Esporofito #sym.arrow Esporas] #sym.arrow Gametofitos #sym.arrow Gametos #sym.arrow Esporofito ]) Es el proceso de formación de las esporas femeninas (_megasporas_). Este proceso toma lugar dentro de la nucela, siendo esta el *esporangio* (megasporangio). Dentro de la nucela *solo hay un esporocito,* el cual, por tanto, originará por meiosis a las únicas 4 esporas femeninas del primordio. #figure-box(align(center)[ Ovario #sym.arrow.long Primordio seminal #sym.arrow.long Nucela ]) De las 4 megasporas del primordio, solo 1 sobrevive: las otras 3 esporas "mueren". Esta espora sobreviviente será la única encargada de formar el megagametofito. == Megagametogénesis #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) Esporofito #sym.arrow Esporas #sym.arrow #text(red)[Gametofitos #sym.arrow Gametos] #sym.arrow Esporofito ]) La espora sobreviviente, a través de varias mitosis sucesivas, va a generar el megagametofito. Este gametofito estará *formado por 3 células en cada uno de sus dos extremos, y una gran célula central con dos núcleos* (7 células, 8 núcleos), y a veces se le denomina *saco embrionario.* Recordemos que todo este proceso ocurre dentro del primordio seminal, pues la espora nunca sale de él, tomando el lugar de la nucela (generalmente). A las tres células del extremo superior se les denomina *antípodas,* mientras que a las células laterales del extremo inferior se les denomina *sinérgidas,* y a la célula central del extremo inferior se le llama *óvulo.* Por su parte, a la célula con dos núcleos, se le denomina *célula de los núcleos polares.* Ahora la parte femenina está lista para ser fecundada, esperando a que lleguen los gametos masculinos a través de la polinización. = Polinización #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) Esporofito #sym.arrow Esporas #sym.arrow Gametofitos #sym.arrow Gametos #sym.arrow.dotted #text(red)[Polinización] #sym.arrow.dotted Fecundación #sym.arrow Esporofito ]) Una vez formado los microgametofitos, la planta debe ser polinizada para que puedan encontrarse los gametos masculino y femenino para dar lugar a la fecundación y a la formación de un nuevo esporofito. La polinización ocurre principalmente gracias a la acción de polinizadores, los cuales pasan por varias flores, transportando el polen. Existen, no obstante, plantas que no necesariamente dependen de polinizadores, usando el viento como medio de polinización. Esto último, sin embargo, implica la producción masiva de polen para mantener las probabilidades de éxito. Los principales tipos de polinización: + *Anemófila:* Por viento. + *Ornitófila:* Por aves o pájaros + *Entomófila:* Por insectos. Además, en las flores hermafroditas existe el problema de una potencial *autogamia* (fecundación de la planta sobre sí misma), por lo que las plantas hermafroditas han desarrollado mecanismos que favorecen la *alogamia*. == Mecanismos que favorecen la alogamia === Incompatibilidad homogenética Existe un gen de autoesterilidad con múltiples alelos, causando que granos de polen que poseen el gen de autoesterilidad de la misma planta no desarrollen el tubo polínico y no haya fecundación. === Dicogamia Los estambres y el pistilo en una misma flor alcanzan la madurez para la polinización en épocas distintas. Dependiendo de qué se desarrolla primero, se pueden clasificar la maduración como: + *Protandria:* Si maduran primero los estambres + *Protoginia:* Si madura primero el pistilo #examplebox()[ En los paltos primero se desarrolla la parte masculina y, posteriormente, la parte femenina, causando que primero se libere el polen al ambiente y, luego, se pueda recibir el polen y producir la fecundación. ] === Heterostilia Existen distintas morfologías florales donde las longitudes del estilo y de los filamentos varía. Así, las plantas con filamentos largos y estilo corto tenderán a polinizar a las plantas con filamentos cortos y estilos largos. === Flores con separación de sexos Existen plantas que presentan las flores masculinas separadas de las flores femeninas, ya sea en la misma planta, o entre plantas. Se clasifican como: + *Especies monoicas:* Si las flores masculinas y femeninas están en el mismo individuo. + *Especies dioicas:* Si las flores masculinas están en diferentes individuos que las flores femeninas. == Mecanismos de atracción de polinizadores El principal atractivo que poseen las flores para los polinizadores, es el néctar, el cual les permite alimentarse. Sin embargo, existen otros mecanismos, como el color de la flor o el olor de la flor, que permiten atraer específicos tipos de polinizadores a la flor. El néctar se produce en los *nectarios,* los cuales producen agua y azúcar, por lo que están conectados con el xilema y el floema. Reciben diversos nombre según su localización. Existen también los nectarios extraflorales, principalmente útiles para atraer hormigas que defiendan a la planta de herbívoros. Finalmente, también es útil para algunas plantas agrupar numerosas flores en una inflorescencia para hacerse más llamativas a los polinizadores. ] #let clase-19-20 = [ #new-class(new-page: true, "Reproducción en plantas III", "13 de noviembre de 2023") Ya hemos visto la morfología de la flor, la formación de esporas y gametos, y la unión de los cigotos. Ahora, vamos a ahondar aún más en el proceso previo a la fecundación y posterior a la formación de los gametos: la polinización. = Polinización #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) Esporofito #sym.arrow Esporas #sym.arrow Gametofitos #sym.arrow Gametos #sym.arrow.dotted #text(red)[Polinización] #sym.arrow.dotted Fecundación #sym.arrow Esporofito ]) Consiste en el mecanismo mediante el cual lo granos de polen "salen" hacia el órgano reproductivo femenino en la flor. La forma más conocida de polinización son los insectos, pero también ocurren polinizaciones vía aves o a través del viento. Todas estas formas de polinización determinan las distintas formas en las que las plantas se desarrollan. Para atraer polinizadores, las plantas elaboran una "recompensa": el néctar, una mezcla de agua con azúcar. Esta recompensa se puede producir y entregar de diversas formas, dependiendo de las necesidades de la planta. Finalmente, como tanto la planta como el polinizador se ven beneficiados, ocurre los que se denomina como *mutualismo de la polinización.* #figure-box()[ $ "Polinización" limits(arrow.long)^"Permite"_"la" limits("Fecundación cruzada")_"(alogamia)" $ ] == Polinización anemófila + Flores pequeñas y poco llamativas + Corola poco desarrollada o ausente + Son monoicos o dioicos + Ausencia de colores vistosos + Estambres muy desarrollados (filamento largo y abundante producción de polen) + Estigmas con gran superficie para captar el polen que llegue (viene no-dirigido) + Ausencia de nectarios == Polinización ornitófila + Las flores son tubulares + Flores de tamaño medio a grande + Generalmente con corolas de color rojo (las aves se atraen por la vista, y los insectos por el olor). + Con mucha secreción de néctar. == Polinización entomófila La polinización por insectos variará dependiendo del tipo de insecto que se esté intentando atraer. Por ejemplo, pueden haber adaptaciones que limitan la polinización a ciertos insectos, como las mariposas; o adaptaciones morfológicas que favorecen la adhesión del polen a insectos, como abejorros. = Fecundación y germinación #figure-box(align(center)[ #align(center, text(size: 1.2em, weight: 900, "Generación alternada")) Esporofito #sym.arrow Esporas #sym.arrow Gametofitos #sym.arrow Gametos #sym.arrow.dotted Polinización #sym.arrow.dotted #text(red)[Fecundación #sym.arrow Esporofito] ]) Una vez que llega el grano de polen al estigma comienza la *germinación,* la cual corresponde a la *alargación y desarrollo del tubo polínico* para depositar el espermio en el óvulo, lo cual se conoce como *sifonogamia.* Recordemos que para fecundar al óvulo, el tubo polínico deberá pasar entre los tegumentos hasta el óvulo, el cual se halla entre las sinergidas. Puede darse el caso de que algunos primordios seminales no sean fecundados, causando que hayan *primordios seminales abortados.* Para que se fecunden todos los primordios, en el peor de los casos es necesario un grano de polen por cada primordio seminal. En el grupo de plantas con flores, o Angiospermas, ocurre un proceso llamado como *doble fecundación,* en el cual uno de los gametos masculinos (n) de los dos que vienen en el grano de polen se une al óvulo (n), generando al cigoto (2n) y, consecuentemente, al embrión; mientras que el otro gameto masculino (n) junto con la célula de núcleos polares (2n) forma el *endosperma* o *endospermio* (3n). #obsbox()[ La sifonogamia está presente en Angiospermas y Coníferas. ] Luego de la fecundación, ocurrirán tanto el desarrollo de la semilla como el desarrollo del fruto. Donde estaba el megagametofito ahora estará tanto el embrión como el endospermo (rodeándolo). Y toda esta estructura quedará cubierta por la *testa*, la cual tendrá una cicatriz en donde estaba unida a la placenta ---es decir, el *funículo*---, denominada *hilo.* #figure( caption: "Primordio seminal luego de la fecundación. Ahora es una semilla.", image("../figures/fig_fecundacion.svg", height: 5.5cm) ) #obsbox()[ El megagametofito no se transformó en nada. Lo que sí se transformó fueron los tegumentos (no cambió su material genético). ][ No todas las flores generarán frutos. Las flores masculinas o las no fecundadas no generan frutos. ] En la semilla, *el micropilo seguirá presente,* pero ahora su función no será permitir la fecundación, sino que permitir que salga la radícula hacia el exterior. == Cariopsis del maíz La cariopsis es un fruto y semilla a la vez, pues la pared del fruto queda adherida a la semilla. Por ello, se forma una estructura denominada *complejo pericarpio-testa,* donde la pared del fruto queda unida a la pared de la semilla. #grid( columns: (1fr, 1fr), [ == Gramíneas El maíz es una *Gramínea,* las cuales se caracterizan por poseer una cariopsis, es decir, ser una semilla unida al fruto (testa + pericarpio). Las gramíneas son *monocotiledóneas* por lo que poseen, lógicamente, un solo cotiledón o *escutelo* en la semilla, el cual está unido a un *eje embrionario,* cuya parte superior (*plúmula*) formará el tallo, y cuya parte inferior (*radícola*) formará la raíz. Cubriendo al eje embrionario en la parte superior se encuentra un "capuchón" llamado *coleoptilo,* el cual protegerá al brote que saldrá de la tierra Por su parte, cubriendo el eje embrionario en la parte inferior se encuentra otro "capuchón" que se abre antes, llamado *coleorriza.* ], figure( caption: "Estructuras de las gramíneas", image("../figures/fig_graminea.svg", height: 7cm) ) ) #grid( columns: (1.5fr, 1fr), [ = Morfología interna de la semilla: El Embrión El embrión forma una *plántula,* la cual posee uno o dos cotiledones, dependiendo de si es monocotiledónea o dicotiledónea. Además, se halla la plúmula en la punta superior, y la radícula en la punta inferior. Entre los cotiledones y la plúmula, se encuentra una parte del eje embrionario llamado *epicotilo,* mientras que la parte del eje embrionario entre los cotiledones y la radícula se conoce como *hipocotilo.* Si primero se desarrolla el epicotilo, los cotiledones quedan debajo de la tierra, y la *germinación es hipogea.* Por su parte, si primero se desarrolla el hipocotilo, los cotiledones salen de la tierra, y la *germianción es epigea.* ], figure( caption: "Estructuras del embrión", image("../figures/fig_embrion.svg") ) ) = Origen, clasificación y características morfológicas de los frutos == Origen Solamente las plantas con flores podrán dar origen a frutos, los cuales pueden tener diversos orígenes, dependiendo de si se forman a partir de un ovario o varios ovarios, y si hay estructuras acompañantes que constituyen el fruto: - El desarrollo del ovario (en soledad) produce *frutos simples.* - El desarrollo del oOvario acompañado de otras estructuras complejas (como el tálamo) producen *frutos complejos.* - El desarrollo de los ovarios de muchas flores que permanecen juntas producen *infrutescencias.* #obsbox()[ Tanto los frutos simples como los frutos complejos provienen de _una sola_ flor. Las infrutescencias no. ] #examplebox()[ Ejemplo de una infrutescencia es la piña. ] Además, dentro de estas clasificaciones, también habrán subcategorías presentes. Por ejemplo, para los frutos simples: #{ set text(size: 1.3em) $ "Simples" cases(limits("Secos")_"(Pericarpio delgado (<carnosos))" cases(limits("Dehiscente")_"(Se abre cuando madura)" arrow "La semilla es\nunidad de dispersión", limits("Indehiscente")_"(No se abre al madurar)" arrow "El fruto es la\nunidad de dispersión"), limits("Carnosos")_"(Pericarpio engrosado)") $ } Cuando el ovario se convierte en un fruto el carpelo va a transformarse en el *pericarpio,* mientras que *los sépalos, los pétalos, el estambre, el estilo y el estigma* desaparecen (se caen) en la mayoría de las veces. El pericarpio posee 3 capas: la capa externa se denomina *epicarpio* o exocarpio; la capa media o *mesocarpio* que es la parte carnosa de la fruta, y corresponde al mesófilo del carpelo; y la capa interna o *endocarpio* que no requiere de tanta modificación. #figure( caption: "Ilustración que representa las estructuras que se caen (punteadas) y en qué se transforman las estructuras persistentes. Imagen extraída de la guía 8 de laboratorio, cuyos autores son los profesores del curso de Botánica.", image("../figures/fig_transformacion_ovario.png") ) == Clasificación Los frutos pueden clasificarse a grandes rasgos como: #{ set text(size: 1.3em) $ "De una flor"& cases("Simples" cases("Secos" cases("Dehiscente" cases("Silicua", "Folículo", "Legumbre", "Cápsula"), "Indehiscente" cases("Nuez", "Arquenio", "Cariopsis", "Sámara", "Lomento seco")), "Carnosos" cases("Drupa", "Baya", "Hesperidio")), "Complejos" cases("Pomo", "Pepónida", "Polidrupa", "Eterio", "Cinorrodón")) \ "De varias flores"& cases("Sicono", "Sorosis") $ } Y, además, pueden analizarse bajo las siguientes características: - N° de carpelos - N° de lóculos - N° de aberturas (dehiscente) - N° de semillas === Definiciones grupales principales Para no tener que definir cada uno de los grupos de clasificación antes de llegar a los extremos del diagrama anterior, se definirán los macro-grupos en los que se puede clasificar un fruto: / F. simples: Son aquellos que provienen de un solo ovario, sin ninguna estructura acompañante (como el tálamo, por ejemplo). / F. simples y secos: Cuando el fruto madura, este es duro y seco. / F. simples y carnosos: Cuando el fruto madura, el pericarpio es carnoso y blando, pudiendo distinguirse sus tres capas: epicarpio, mesocarpio y endocarpio. == Frutos simples, secos y dehiscentes Los frutos dehiscentes se caracterizan por *abrirse al madurar.* Se subdividen en 4. === Folículo - Se abre solo por una sutura. - Tiene muchas semillas. - Proviene de un ovario monocarpelar y súpero. #obsbox()[ Es requisito que el ovario sea súpero, pues si fuera ínfimo estaría junto al tálamo, causando que, al madurar, el fruto sería complejo, pues parte del fruto no sería netamente del ovario. Existen excepciones, pero son mínimas. ] === Legumbre - Se abre por la sutura ventral y por el nervio dorsal (dos aberturas). - Tiene muchas semillas. - Proviene de un ovario monocarpelar y súpero. === Silícua - Se abre por dos suturas. - Tiene muchas semillas. - Proviene de un ovario bicarpelar separado por un tabique (*replo*) y súpero. === Cápsula - Se abre por varios lados. - Tiene muchas semillas. - Proviene de un ovario multicarpelar, sincárpico y súpero. #figure-box()[ $ "Legumbre & Lomento" arrow& "Leguminosas "(italic("Fabaceae"))\ limits("Silícua")_"(replo -- tabique)" arrow& italic("Brassicaceae")\ "Cipsela" arrow& "Compuestas" (italic("Asteraceae"))\ "Hesperidio" arrow& "Cítricos "italic("(Rutaceae)")\ "Drupa" arrow& "Frutos de carozo "(italic("Rosaceae (Prunoideae)")) $ ] == Fruto simples, secos e indehiscentes Los frutos indehiscentes se caracterizan por *no abrirse al madurar.* Se subdividen en 5. === Aquenio - Tiene una semilla no adherida al pericarpio. - Proviene de un ovario monocarpelar súpero (y, a veces, puede presentarse como ínfero). === Cipsela - Tiene una semilla no adherida al pericarpio. - Proviene de un ovario bicarpelar ínfero. - Posee una estructura denominada *pappus* #obsbox()[ El papus es una modificación del cáliz que suele estar compuesto por pelos simples o plumosos, cerdas o escamas, y su función principal es permitir o asistir a la planta en la diseminación o dispersión aérea de los frutos y, por ende, de las semillas. ] === Sámara - Tiene una semilla (monospermo). - Proviene de un ovario monocarpelar y súpero. - Posee una prolongación en forma de ala (permite la dispersión por viento o *anemocoria*) A veces dos sámaras quedan unidas por el tálamo, causando que se vean "dos alas" juntas. Esta estructura se denomina *bisámara.* === Cariopsis - Tiene una semilla. - Proviene de un ovario monocarpelar y súpero. - Posee la testa de la semilla adnada al pericarpio. === Nuez - Tiene una semilla. - Proviene de un ovario multicarpelar y súpero (algunas veces puede ser ínfero). - Tiene solo un carpelo desarrollado (los demás abortan). - Posee un pericarpio muy duro. #obsbox()[ En el *Nogal*, el fruto (nuez) posee un endocarpio leñoso, pero la cobertura externa que proviene del cáliz y del pericarpio es carnosa, constituyendo lo que se conoce como *pseudodrupa* ] === Lomento - Tiene muchas semillas (polispermo). - Proviene de un ovario monocarpelar y súpero == Frutos simples y carnosos === Bayas - Tiene una o varias semillas. - Proviene de un ovario generalmente con varios carpelos unidos y súpero. - Presenta un epicarpio delgado, un mesocarpio grueso, y un endocarpio membranoso. === Hesperidio - Tiene varias semillas. - Proviene de un ovario sincárpico, multicarpelar y súpero. - Presenta un epicarpio glandular, un mesocarpio esponjoso, y un endocarpio tapizado de células jugosas. - Característico de los cítricos. En cada lóculo hay "un gajo de la fruta" (un gajo de naranja, limón etc.). === Drupa - Tiene una semilla. - Proviene de un ovario monocarpelar y súpero. - Presenta un epicarpio delgado, un mesocarpio grueso y un endocarpio duro y leñoso. ] #let clase-21-22 = [ #new-class(new-page: true, "Reproducción en plantas IV y Taxonomía I", "20 de noviembre de 2023") = Origen, clasificación y características morfológicas de los frutos (continuación) == Frutos complejos Son aquellos que provienen de una sola flor, pero en los cuales, aparte del ovario, también lo constituyen otras estructuras florales. Pueden provenir tanto de ovarios súperos como ovarios ínferos (con talamos convexos y cóncavos, respectivamente). Así como también pueden provenir de flores apocárpicas como flores sincárpicas. #obsbox()[ Las flores apocárpicas *siempre* van a formar frutos complejos. Las sincárpicas no necesariamente; solo lo harán cuando se encuentren en una flor epigina. #align( center, grid( columns: (1fr, 1fr), [ $ "Apocárpicas" \ arrow.b $ $ 1.& "Polidrupa"\ 2.& "Eterio" \ 3.& "Cinorrodón" $ ], [ $ "Sincárpicas" \ arrow.b $ $ 1.& "Pomo" \ 2.& "Pepónido" \ 3.& cancel("Cipsela") $ ] ) ) ][ La polidrupa y el eterio provienen de flores hipóginas, mientras que el cinorrodón proviene de flores epiginas. ] #figure-box()[ $ "Pomos" arrow "Pomáceas" arrow "Maloideae" arrow "Rosaceae" \ "Pepónidos" arrow "Curcubitaceae" $ ] === Pomo + Tiene muchas semillas. + Proviene de un ovario ínfero multicarpelar. + Presenta pericarpio coriáceo y un *tálamo muy desarrollado.* === Pepónido + Tiene varias semillas. + Proviene de un ovario ínfero, con varios carpelos. + Presenta un mesocarpio desarrollado y un epicarpio y tálamo fusionados. === Polidrupa + Proviene de una flor de gineceo apocárpico, multicarpelar y con ovario súpero. + Los carpelos están dispuestos en un tálamo, cada uno de ellos formando una pequeña drupa. #figure-box( columns( 3, [ $ "(Fruto falso)" \ "Polidrupa" \ arrow.b \ "(Frutos verdaderos)" \ "Drupas" $ #colbreak() $ "(Fruto falso)" \ "Eterio" \ arrow.b \ "(Frutos verdaderos)" \ limits("Aquenios")_"(superficie del tálamo)" $ #colbreak() $ "(Fruto falso)" \ "Cinorrodón" \ arrow.b \ "(Frutos verdaderos)" \ limits("Aquenios")_"(interior del tálamo)" $ ] ) ) === Eterio + Proviene de una flor de gineceo apocárpico, con varios carpelos y ovario súpero. + Los carpelos están dispuestos en un tálamo desarrollado y *carnoso,* cada uno de ellos formando un pequeño aquenio. === Cinorrodón + Proviene de una flor del gineceo apocárpico, con varios carpelos y ovario ínfero. + Los carpelos están dispuestos al _interior_ de un tálamo, engrosado en la madurez. + Cada ovario forma un aquenio. == Infrutescencias Si bien hasta ahora hemos visto frutos que provienen de una sola flor. También existen frutos que se originan a partir de muchas flores, siendo estos el *sicono* y la *sorosis.* === Sicono + Formado por *múltiples frutos pequeños.* + Los frutos están dispuestos en un receptáculo ahuecado y piriforme. + Los frutos verdaderos son aquenios. La morfología del sicono, con forma de cápsula hueca, se debe a que, en su parte inferior, se hallaban las flores femeninas, y en la parte superior las partes masculinas. Ocurriendo una fecundación interna, donde solo las flores femeninas darán origen a los frutos verdaderos (i.e. los aquenios). === Sorosis + Formado por varios *frutos concrescentes.* + Los frutos están dispuestos sobre un eje central. + Posee flores trímeras (y, por consecuencia, tricarpelares). + Los frutos verdaderos son bayas. A diferencia del sicono, en la sorosis las flores no van en el interior, sino que van en la parte externa. Cada flor va a originar un fruto verdadero: una baya. A medida que crecen los frutos, quedarán unidos los unos con los otros, formando frutas como la piña. == Relación maduración fruto-semilla Junto con la maduración del fruto, en el interior del ovario, ocurrirán numerosas transformaciones en los primordios seminales para poder dar origen a lo que denominamos como semilla. Este proceso de desarrollo de la semilla ocurre después de la polinización, de la sifonogamia y de la fecundación. Recordemos además, que en las plantas con flores ocurre el proceso de doble fecundación: $ "Gameto masculino" + "Gameto femenino" arrow.long limits("Embrión (2n)")_"(esporofito)" \ "Gameto masculino" + "Célula de núcleos polares" arrow.long limits("Endosperma (3n)")_"(material nutritivo)" $ Y, adicional a lo anterior, los tegumentos se modifican para formar la *cáscara de la semilla* (también llamada *testa* o *episperma*). De esta forma, el conjunto embrión, endosperma y testa forma la *semilla,* donde cada parte de ella posee un origen distinto. Finalmente, es común observar que "no hay" endosperma cuando la semilla germina. Esto ocurre debido a que este fue absorbido por el embrión (semillas *exalbuminosas*). Igualmente, pueden darse casos donde no es absorbido todo el endosperma (semillas *albuminosas*). = Taxonomía y Evolución de Angiospermas == El nombre científico Es la forma correcta de nominar a las especies. Corresponde a un *binomio* (dos palabras), que generalmente corresponden a un *sustantivo* y un *adjetivo*. #align(center)[ Almendro: _Prunus_ (del ciruelo) _dulcis_ (dulce) ] El *sustantivo* corresponde al nombre del *género* (conjunto de especies), categoría sistemática creada para incluir aquellas especies que presentan gran afinidad filogenética y morfológica. El nombre específico (o *epíteto*) corresponde a un *adjetivo* que caracteriza a la especie, que es el conjunto de individuos morfológicamente y genéticamente semejantes. #obsbox()[ Si bien el epíteto no puede repetirse dentro del mismo género, sí puede repetirse entre distintos géneros. ] == Categorías taxonómicas Son conjuntos de entidades emparentadas entre sí. Centrífugamente, de menor a mayor grado de agrupación de individuos, se halla, la *especie*, el *género*, la *familia*, el *orden* y la *clase,* por ejemplo. Las categorías taxonómicas pueden dividirse en *supraespecíficas* e *infraespecíficas*. Las primeras son *uninominales,* mientras que las segundas son *trinominales* y solamente incluye a las subespecies. Las categorías supraespecíficas e infraespecíficas son son: + Reino + División (_-phyta_) + Clase( _-opsida_) + Subclase (_-idae_) + Clado (_terminación libre_) + Orden (_-ales_) + Familia _(-aceae_) + Subfamilia _(-ideae_) + Tribu( _-eae_) + Género + Sección + #text(red, "Especie") (binomial) + Subespecie (tronomial) == Reino _Plantae_ Se encuentra separado en 9 grandes grupos o divisiones: _Bryophyta, Lycophyta, Arthrophyta, Pteridophyta, Cycadophyta, Ginkgophyta, Coniferophyta, Gnetophyta_ y _Anthophyta_ == División _Anthophyta_ (o _Magnoliophyta_) Nos enfocaremos en una de las divisiones del reino _Plantae_: la División _Anthophyta_. Estas son plantas con flores, frutos, semillas (espermatófitas), haces vasculares (traqueófitas), generan embrión (embriófitas) y tienen tubo polínico (sifonógamas). #obsbox()[ Estos caracteres no son todos únicos de las angiospermas. Los que sí son únicos son la presencia de flores, frutos y la doble fecundación. ] Dentro de la división, existen 2 clases: + _Liliopsida_: Monocotiledóneas (trímeras) + _Magnoliopsida_: Dicotiledóneas (pentámeras y tetrámeras) En este sentido, surge el término *sinapomorfía,* que alude a los caracteres derivados o más nuevos que han aparecido en los individuos más recientes. Con la aparición de más sinapomorfías, pueden aparecer nuevos clados. Algunas de las principales diferencias evolutivas en los caracteres de las _Anthophytas_ se encuentran en la siguiente tabla: #table( align: center+horizon, columns: (1.5fr, 1fr, 1fr), [Criterio], [*Carácter más primitivo*], [*Carácter más evolucionado*], [Corola], [Muchos pétalos], [Pentámera o tetrámera], [Disposición de los elementos florales], [Helicoidal], [Verticilada], [Perianto], [No diferenciado], [Diferenciado en cáliz y corola], [Flores], [Actinomorfas, hermafroditas e hipóginas], [Zigomorfas, unisexuales y epiginas], [Elementos florales], [Separados], [Unidos], [Estambres], [Sin filamento y anteras anchas], [Diferenciados en filamento y anteras], [Polen], [Uniaperturado], [Poliaperturado], [Exina], [Lisa], [Esculpida], [Carpelos], [Libres], [Soldados], [Fruto], [Dehiscente], [Indehiscente], [Germinación], [Epigea], [Hipogea], ) == Sistema de clasificación APG (1988) Un grupo de taxónomos realizó un análisis filogenético basado en las relaciones de parentesco entre las especies. Se utiliza la cladística para establecer las relaciones evolutivas basándose en las propiedades derivadas compartidas (*sinapomorfias*). Se basa en el análisis cladístico de secuencias de ADN de tres genes: dos cloroplásticos y uno ribosómico sin desechar evidencias morfológicas. Debido a este análisis se vio que las dicotiledóneas *no* son una clase como tal, pues no poseen suficientes similitudes para conformar un grupo grande en sí. De esta forma, las Angiospermas se pueden dividir en 4 clados: #box()[ + Monocotiledóneas (pérdida de un cotiledón) + Eudicotiledóneas #sym.arrow 97% de las antiguas Dicotiledóneas + Angiospermas basales + Magnolidas ] #align(center, tablex( align:center+horizon, columns: 5, [*Clase*], [Monocotiledóneas], [Ang. basales], [Magnolidas], [Eudicotiledóneas], rowspanx(2)[*Aperturas en el polen*], [1 apertura], [1 apertura], [1 apertura], [3 aperturas], colspanx(3)[Monosurcado], [Tricolpadas] )) #obsbox()[ Es importante saber que los colpos son horizontales y los surcos son horizontales ] Con la nueva clasificación, el 97% de las antiguas Dicotiledóneas son ahora Eudicotiledóneas. Por su parte, el 3% restante se divide entre Angiospermas basales y Magnolidas. = Clados de la división Anthophyta == Monocotiledóneas Poseen las siguientes características: + Polen monoaperturado + Embrión con un cotiledón + Flores trímeras + Sin leño (crecimiento secundario) + Hojas con nervadura paralela + Raíces homorrizas == Angiospermas basales (o primitivas) Presentan rasgos de ambos grupos, Monocotiledóneas y Eudicotiledóneas: + Polen monoaperturado + Flores trímeras. + Comprende los órdenes - _Ambobrellales_ - _Nynpheales_ - _Austrobaileyales_ == Magnólidas Presentan varios caracteres primitivos, y otros no tanto: + Polen monoaperturado (monocolpado) + Nervadura reticulada + Carpelos libres + Predominio de gineceos apocárpicos con numerosos carpelos + Disposición helicoidal de las piezas florales en un número variable + Perianto petaloide grande o reducido + Numerosos estambres + Estambres sin diferenciar + Plantas leñosas (principalmente) y herbáceas + Flores hermafroditas o unisexuales, actinomorfas y dialipétalas #obsbox()[ Dentro de este clado, estudiaremos el orden _Magnoliales_ y la familia _Magnoliaceae._ ] === Familia _Magnoliaceae_ Formada por 12 géneros y cerca de 220 especies. Su distribución está centrada en regiones templadas y tropicales de la tierra. Son especies con valor ornamental, y su fórmula floral es: #figure-box(align:center, width: 50%)[ $ upright(* P oo space A oo space G underline(oo)) $ ] == Eudicotiledóneas Son las más evolucionadas: + Polen triaperturado + Embrión con dos cotiledones + Flores tetrámeras o pentámeras + Hojas con nervación reticulada. ] #let clase-23-24 = [ #new-class(new-page: true, "Taxonomía II", "27 de noviembre de 2023") Recordemos rápidamente la siguiente clasificación de las Angiospermas: #align(center, table( align: start, columns: 1, [*Clados*], [ + Angiospermas basales (no veremos ninguna familia) + Mangólidas --- (Magnoliales --- Magnoliaceae) + Monocotiledóneas + Eudicotiledóneas ] )) Ahora veremos, en el clado Eudicotiledónea, las familias _Brassicaceae_, _Rosaceae_, _Fabaceae_, _Apiaceae_, entre otras. = _Brassicales_. Familia _Brassicaceae_ #figure-box(width: 40%, align: center)[ $ upright(* K 4 space C 4 space A 2+4 space G(underline(2))) $ ] Se encuentran en todos los continentes, formada por 380 géneros y cerca de 3000 especies. Prefieren climas templados y son ampliamente usadas para la alimentación. Sus principales características son: + Tetrámeras, con flores generalmente en forma de cruz. + Poseen *replo,* un tabique ubicado dentro del ovario que permite separar el ovario en dos lóculos, el cual perdura con la maduración. + Tienen reducción de 2 estambres en un verticilo externo, y 4 estambres en un verticilo interno. Así, *el androceo consta de dos verticilos florales.* = _Rosales_. Familia _Rosaceae_ #figure-box(width: 40%, align: center)[ $ upright(* K 5 space C 5 space A - space G-) $ ] Formada por 122 géneros y cerca de 3370 especies, tienen importancia agronómica con especies frutales y ornamentales. Son plantas herbáceas arbustivas y arbóreas. Lo que varía entre las subfamilias es principalmente la parte femenina (i.e. el gineceo). Por ello, las subfamilias generarán distintos frutos. El resto de las estructuras permanece relativamente constante. #tablex( columns: (1fr, 1fr, 1fr), colspanx(3)[#align(center)[*Familia Rosaceae* \ $ upright(* K 5 space C 5 space A - space G -) $]], [*Subfamilia*], [*Fórmula floral*], [*Fruto*], [_Spiraeoideae_], [$ upright(* K 5 space C 5 space A 10 space G underline(5)) $], [Folículo, Polifolículo#footnote("El fruto verdadero es el folículo, pues el que viene del ovario. El polifolículo es un fruto falso."), o Cápsula], [_Rosoideae_], [$ upright(* K 5 space C 5 space A oo space G overline(underline(10 \- oo))) $], [Flor hipogina: eterio o polidrupa. Flor epigina: cinorrodón.], [_Maloideae_], [$ upright(* K 5 space C 5 space A 10 \- oo space G (overline(5))) $], [Pomo], [_Prunoideae_], [$ upright(* K 5 space C 5 space A 10 \- oo space G (underline(1))) $], [Drupa, con endocarpio leñoso (carozo)], ) = _Fabales_ (ex-Leguminosas). Familia _Fabaceae_ Formada por 700 género y cerca de 17000 especies, con presencia en todo el mundo. Tiene importancia agronómica en la alimentación humana. Al igual que los _Rosales_, se divide en subfamilias. Sin embargo, mientras que en los Rosales el gineceo era el que variaba, en las Fabaceas el gineceo es lo único constante (los frutos son muy similares). #tablex( columns: (1fr, 1fr), colspanx(2)[#align(center)[*Fabaceas* $ upright(*%K - space C - space A - space G (underline(1))) $ Los frutos son o legumbres o lomentos]], [*Subfamilia*], [*Fórmula floral*], [_Mimosoideae_], [$ upright(* K (5) space C 5 space A 10 \- oo space G (underline(1))) $], [_Papilionoideae_], [$ upright(% K (5) space C 5 space A (9)+1 space G (underline(1))) $], [_Caesalpinioideae_], [$ upright(% K (5) space C 5 space A 10 space G (underline(1))) $], ) == _Mimosoideae_ + Posee hojas bipinnaticompuestas. + Es *"poliada",* lo que implica que se dispersa todo el polen en conjunto, == _Papilionoideae_ Se hallan las legumbres que comemos cotidianamente. Se caracterizan por: + Tener pétalos desiguales: Un estandarte, unas alas y una quilla. + Son *diadelfos*, porque posee 9 estambres unidos por el filamento y 1 estambre libre o separado. + Consumimos sus semillas, no sus frutos. + Ejemplos son las lentejas, los garbanzos, las arvejas, los porotos, etc. = Apiales. Familia _Apiaceae_ #figure-box(width: 40%, align: center)[ $ upright(* K 5 space C 5 space A 5 space G (overline(2))) $ ] Se caracterizan porque: + Sus flores se encuentran en una *umbela,* la cual puede ser simple o compuesta. + Su fruto se denomina como *esquizocarpo,* el cual contiene a dos frutos verdaderos: 2 mericarpos. + Decimos que el mericarpo es un aquenio, pues está formado a partir de un solo carpelo, es indehiscente y tiene una sola semilla. + Como el esquizocarpo está formado por dos aquenio, lo denominamos como *diaquenio.* #obsbox()[ Todos los esquizocarpos son bicarpelares en la familia _Apiaceae._ ] #line(length: 100%) Seguiremos con los órdenes de las eudicotiledóneas y las monocotiledóneas Los órdenes y familias - Orden Lamiales --- _Lamiaceae_ - Orden Solanales --- _Solanaceae_ - Orden Asterales --- _Asteraceae_ están muy emparentados entre sí y forman la Subclase _Asteridae,_ y el clado Asteridias. Por su parte, en las Monocotiledóneas, verenmos el Orden Poales --- _Poaceae_ (Gramíneas). = _Lamiales_. Familia _Lamiaceae_ (ex-Labiatae) #figure-box(width: 40%, align: center)[ $ upright(% K (5) space [C(5) space A 4] space G (underline(2))) $ ] Su nombre antiguo se debía a que las caracterizaba el ser flores bilabiadas. Sus características son: + Poseen flores bilabiadas: la corola es tubular, con una parte superior de 2 pétalos e inferior de 3 pétalos. + Tiene 4 estambres (perdió un estambre evolutivamente). + Cada flor forma 4 frutos, similares a pequeñas nueces, y se llaman *núculas.* Pese a que tiene 2 carpelos que están unidos formando el pistilo, dentro del ovario hay 2 tabiques, en lugar de 1, causando que hayan 4 lóculos, con 1 primordio seminal cada uno. Además, cada uno de estos lóculos dará origen a un fruto simple, seco e indehiscente (núculas). + El cáliz es persistente (se cae la corola, pero permanece el cáliz) y posee 5 sépalos. En su fondo, se hallan los 4 frutos mencionados previamente. + Tiene tallos cuadrangulares, pues se forma colénquima en 4 sectores que dan la forma cuadrada al tallo. + La mayoría de ellas son aromáticas. + Las hojas son opuestas. #obsbox()[ Las lamiaceas poseen sus flores como espigas de *verticilastros* (tres flores sobre una bráctea), como racimo o como panícula (racimo de racimos). ] = _Solanales_. Familia _Solanaceae_ #figure-box(width: 40%, align: center)[ $ upright(* K (5) space [C(5) space A 5] space G (underline(2))) $ ] Su fórmula floral es muy similar a las de las _Lamiaceae_. Sus características son: + Frutos carnosos (*bayas*) o secos (*cápsulas*) + Mientras que las _Lamiaceae_ eran usadas como condimentos, estas son directamente alimentos. = _Asterales_. Familia _Asteraceae_ #figure-box(width: 45%, align: center, body-style:(align: center))[ Flor ligulada o tubular hermafrodita: $ upright(*% K 0\- oo space [C(5) space A (5)] space G (overline(2))) $ Flor ligulada femenina: $ upright(% K 0\- oo space C(5) space A 0 space G (overline(2))) $ ] + Las flores se disponen en *capítulos.* + Ovario ínfero. + Cáliz modificado en una estructura denominada *vilano* o *pappus,* la cual ayuda a la dispersión del fruto. + El fruto es una *cipsela.* + Los estambres son sinantéreos (se unen por las anteras). + Las flores maduran desde afuera del receptáculo o tálamo hacia adentro. + El capítulo está protegido por un conjunto de brácteas llamadas *involucro,* el cual *no es un sépalo,* pues está protegiendo a todas las flores, no a una flor en particular. + Las flores serán *actinomorfas* si se trata de una flor *tubular*, o *zigomorfas* si son *liguladas.* + Las flores son hermafroditas, pero *a veces las flores liguladas son femeninas unisexuales.* Además, _pueden_ ser estériles, causando que su función pase a ser simplemente atraer polinizadores. #tablex( columns: (1fr, 1fr, 1fr), [], colspanx(2)[*Familia Asteraceae*], [], [_Cichoroideae_], [_Asteroideae_], [Fórmula floral], [$ upright(% K 0\- oo space [C(5) space A (5)] space G (overline(2))) $], [Capítulos discoídeos: $ upright(* K \- oo space [C(5) space A (5)] space G (overline(2))) $ Capítulos radiados: $ upright(% K 0 \- oo space C(5) space A 0 space G (overline(2))) \ upright(* K 0 \- oo space [C(5) space A (5)] space G (overline(2))) $], [Capítulos], [Ligulados], [Solo tubulares (discoideos) o tubulares y liguladas (radiados)], [Flores], [Necesariamente hermafroditas], [Flores hermafroditas y _pueden_ haber unisexuales] ) = Poales. Familia _Poaceae_ - Son plantas herbáceas o plantas perennes. - Anemófilas, por lo que no requieren llamar la atención. - Nervadura paralela en sus hojas. - Flores trímeras. - Granos de polen monocolpado. - Las flores se denominan *antecios,* las cuales tienen un gineceo con 1 ovario y 3 estigmas, un androceo con 3 estambres (a veces 6), una corola con 2 *lodículas* (pétalos), y un cáliz con 1 *pálea* (sépalo). - Protegiendo al antecio, se halla la *lema*, la cual posee una *arista*. - Al conjunto de antecios se le llama *espiguilla,* la cual está protegida por brácteas llamadas *glumas.* - El fruto es una cariopsis. ]
https://github.com/usami-k/technote
https://raw.githubusercontent.com/usami-k/technote/main/2024/swift-testing-practice/swift-testing-practice.typ
typst
Creative Commons Attribution 4.0 International
#import "@preview/touying:0.5.2": * #import themes.metropolis: * #show: metropolis-theme.with( aspect-ratio: "16-9", footer: utils.display-current-heading(level: 1), config-info( title: [Swift Testingを活用する], author: [宇佐見公輔], date: [2024-10-18], institution: [株式会社ゆめみ], logo: [#image("images/Profile_NFT.jpeg", height: 35%)], ), ) #set text(font: "Explex35", size: 26pt) #show math.equation: set text(font: "STIX Two Math") #show raw: set text(font: "0xProto") #show link: it => underline(text(blue, it)) #title-slide() == 自己紹介 - 宇佐見公輔 - 株式会社ゆめみ - iOSテックリード - 50歳になりました - 節目なので、健康診断でMRIとかCTスキャンとか == 最近のアウトプット - Swift Testing - #set text(gray, size: 24pt); 関モバ \#5 - 3次元回転とクォータニオン / Accelerate - #set text(gray, size: 24pt); iOSDCポスターセッション / Mobile Act OSAKA 13 - iOSアプリ開発の知識 - #set text(gray, size: 24pt); iOSDCパンフレット記事 - Apple Vision ProのUI / フォーカス操作 - #set text(gray, size: 24pt); 関モバ \#4 / YUMEMI.grow Mobile \#15 = Swift Testingとは Swift用の単体テストフレームワーク - Swift公式のGitHubリポジトリで公開されている - https://github.com/swiftlang/swift-testing - Xcode 16に統合された - XCTestとの関係 - 従来のXCTestに比べて、Swiftの機能をより活用 - XCTestと同じプロジェクトで混在可能 == Swift Testingの構成要素 - テスト関数 - `@Test` 属性 - 期待値の確認 - `#expect` マクロ - テストスイート - `@Suite` 属性 - トレイト - `TestTrait` / `SuiteTrait` = テスト関数 == テスト関数定義:XCTest ```swift import XCTest class FoodTruckTests: XCTestCase { func testEngineWorks() { // ... } } ``` - `XCTestCase` のサブクラス内で定義する必要がある - メソッド名を `test` 始まりで命名する必要がある == テスト関数定義:Swift Testing ```swift import Testing struct FoodTruckTests { @Test func engineWorks() { // ... } } ``` - テスト関数はどこで定義してもよい - メソッドに `@Test` 属性をつければテスト関数になる = 期待値の確認 ```swift // XCTest func testEngineWorks() throws { XCTAssertNotNil(engine.parts.first) XCTAssertGreaterThan(engine.batteryLevel, 0) XCTAssertTrue(engine.isRunning) } ``` ```swift // Swift Testing @Test func engineWorks() throws { try #require(engine.parts.first != nil) #expect(engine.batteryLevel > 0) #expect(engine.isRunning) } ``` == Xcode上の表示 `#expect` マクロはテスト失敗時の結果をきれいに表示する #image("images/running-tests-and-interpreting-results-debug-expanded-gap-results@2x.png", height: 80%) = テストスイート ```swift @Suite struct FoodTruckTests { @Test func engineWorks() { // ... } } ``` - テスト関数を含む型が、自動的にテストスイートになる - 後述するトレイトを使う場合は `@Suite` 属性を指定する == Swiftの機能の活用 ```swift final class FoodTruckTests { init() async throws { // ... } } ``` - 専用の `setUp` の代わりに、通常の `init` が使える - `actor` や `@MainActor` なども使える = トレイト テスト関数やテストスイートの振る舞いを指定する - テスト関数のタイムアウト時間を指定する例 ```swift @Test(.timeLimit(.seconds(30)) func serveLargeOrder() { // ... } ``` == 用意されているトレイト - `.enabled` / `.disabled` - `.timeLimit` - `.serialized` - `.tags` - `.bug` - `.isRecursive` = Swift Testingの機能 Swift Testingならではの機能をいくつか紹介 - エラーのテスト - パラメトライズテスト - テストの並列実行 = エラーのテスト ```swift var order = PizzaToppings(bases: [.calzone, .deepCrust]) #expect(throws: PizzaToppings.Error.outOfRange) { try order.add(topping: .mozarella, toPizzasIn: -1..<0) } ``` - 自前で `do` 〜 `catch` するテスト実装が不要に - throwされなければテスト失敗になってくれる - 自前でテスト実装したときにやりがちなミス == エラーのテストのカスタマイズ ```swift #expect { FoodTruck.shared.engine.batteryLevel = 0 try FoodTruck.shared.engine.start() } throws: { error in return error == EngineFailureError.batteryDied || error == EngineFailureError.stillCharging } ``` - 単純な等価判定では都合が悪い場合は `errorMatcher` を実装 - エラーが `Equatable` でない場合など = パラメトライズテスト ```swift enum Food { case burger, iceCream, burrito, noodleBowl, kebab } @Test(arguments: [ Food.burger, .iceCream, .burrito, .noodleBowl, .kebab ]) func foodAvailable(_ food: Food) async throws { let foodTruck = FoodTruck(selling: food) #expect(await foodTruck.cook(food)) } ``` == Xcode上の表示 #grid( columns: 2, [ #image("images/running-tests-and-interpreting-results-parameterized-input@2x.png") ], [ Xcodeのテストナビゲータで、パラメータごとに分かれて表示される - それぞれのテスト結果がわかる - 特定パラメータだけで実行できる ], ) = テストの並列実行 - デフォルトで、テストは並列実行される - テスト関数 - パラメトライズテストの場合、各テストが並列実行 - テストスイート - 各テスト関数やサブスイートが並列実行 == テストの直列実行 グローバルな状態を操作するテストは並列実行だと困る ```swift @Suite(.serialized) struct FoodTruckTests { @Test func refill() { ... } @Test func startEngine() async throws { ... } } ``` - `.serialized` トレイトで並列でなく直列実行にできる == 複数テストスイートの直列実行 ```swift @Suite(.serialized) struct MultipleTests {} extension MultipleTests { struct FoodTruckTests { ... } } extension MultipleTests { struct OtherTests { ... } } ``` - サブスイートも直列実行にできる - なお、`.serialized` トレイトはサブスイートにも適用される = まとめ - Swift Testingの構成要素 - テスト関数、期待値の確認、テストスイート、トレイト - Swift Testingの機能 - エラーのテスト - パラメトライズテスト - テストの並列実行
https://github.com/piepert/philodidaktik-hro-phf-ifp
https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/unterrichtsplanung/main.typ
typst
Other
#import "/src/template.typ": * = #ix("Unterrichtsplanung") #author[<NAME>] #include "sozialformen.typ" #include "methoden.typ" #include "medien.typ" #include "modelle.typ" #include "kurzentwurf.typ" // #include "jahres_und_sequenzplanung.typ"
https://github.com/HPDell/touying-brandred-uobristol
https://raw.githubusercontent.com/HPDell/touying-brandred-uobristol/main/examples/example.typ
typst
MIT License
#import "../lib.typ": * #show: uobristol-theme.with( aspect-ratio: "16-9", footer: self => self.info.institution, config-info( title: [Title], subtitle: [Subtitle], author: [Authors], date: datetime.today(), institution: [Institution], logo: emoji.city, ), ) #title-slide() #outline-slide([Outline]) = First Section A slide without a title but with some *important* information. === Heading of level next to the "slide level" If the "slide level" is 2, the level-2 heading will be renderred as a new slide, and the level-3 heading will be shown as a special heading. ==== Other headings are renderred as normal Headings of levels greater than $"slide level" + 1$ are shown as normal. === Highlight The `highlight` is changed to show text like #highlight[this]. --- === Tables The lines of tables are shown with the primary color. #table( columns: (1fr, ) * 3, align: center, inset: .5em, table.header[*Column1*][*Column2*][*Column2*], [Content], [Content], [Content], [Content], [Content], [Content], ) == A long long long long long long long long long long long long long long long long long long long long long long long long Title A slide with equation: $ x_(n+1) = (x_n + a/x_n) / 2 $ #lorem(200) = Second Section #focus-slide[ Wake up! ] == Simple Animation We can use `#pause` to #pause display something later. #meanwhile Meanwhile, #pause we can also use `#meanwhile` to display other content synchronously. #speaker-note[ + This is a speaker note. + You won't see it unless you use `#let s = (s.math.show-notes-on-second-screen)(self: s, right)` ] #show: appendix = Appendix Please pay attention to the current slide number.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/babel/0.1.1/assets/logo.typ
typst
Apache License 2.0
#set page( width: auto, height: auto, margin: 0.0em, fill: none ) if "standalone" in sys.inputs and sys.inputs.at("standalone")=="true" #let logo(transparentize: 0%) = box( fill: eastern.transparentize(transparentize), height: 1.5em, width: 1.5em, radius: 0.25em, )[ #align(center + horizon, image("tower-of-babel.svg", height: 66%)) ] #if "standalone" in sys.inputs and sys.inputs.at("standalone")=="true" { logo() }
https://github.com/pauladam94/curryst
https://raw.githubusercontent.com/pauladam94/curryst/main/examples/math-formula.typ
typst
MIT License
#import "../curryst.typ": rule, proof-tree #set document(date: none) #set page(width: auto, height: auto, margin: 0.5cm, fill: white) Consider the following tree: $ Pi quad = quad #proof-tree( rule( $phi$, $Pi_1$, $Pi_2$, ) ) $ $Pi$ constitutes a derivation of $phi$.
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/MATLAB/touying/docs/i18n/zh/docusaurus-plugin-content-docs/current/dynamic/equation.md
markdown
--- sidebar_position: 3 --- # 数学公式动画 Touying 还提供了一个独特且十分有用的功能,即数学公式动画,它让你可以方便地在数学公式里使用 `pause` 和 `meanwhile`。 ## 简单动画 让我们先来看一个例子: ```typst #slide[ Touying equation with pause: #touying-equation(` f(x) &= pause x^2 + 2x + 1 \ &= pause (x + 1)^2 \ `) #meanwhile Touying equation is very simple. ] ``` ![image](https://github.com/touying-typ/touying/assets/34951714/d176e61f-c0da-4c2a-a1bf-52621be5adb2) 我们使用 `touying-equation` 函数来实现在数学公式文本内部使用 `pause` 和 `meanwhile`(事实上,你也能用 `#pause` 或者 `#pause;`)。 正如你料想的一样,数学公式会分步显示,这很适合给让演讲者演示自己的数学公式推理思路。 :::warning[警告] 虽然 `touying-equation` 函数很便利,但是您需要时刻注意,`touying-equation` 并不会做复杂的语法分析,只是单纯地正则表达式分割字符串,因此您不应在 `display(..)` 这类函数内部使用 `pause` 或 `meanwhile`! ::: ## 复杂动画 事实上,我们也可以在 `touying-equation` 内部使用 `only`、`uncover` 和 `alternatives`,只是需要一点技巧: ```typst #slide(repeat: 3, self => [ #let (uncover, only, alternatives) = utils.methods(self) #touying-equation(scope: (uncover: uncover), ` f(x) &= pause x^2 + 2x + uncover("3-", 1) \ &= pause (x + 1)^2 \ `) ]) ``` ![image](https://github.com/touying-typ/touying/assets/34951714/f2df14a2-6424-4c53-81f7-1595aa330660) 我们可以在 `touying-equation` 的 `scope` 参数中将我们需要用到的函数传递进去,例如这里的 `uncover`。 ## 参数 `touying-equation` 的函数定义为 ```typst #let touying-equation(block: true, numbering: none, supplement: auto, scope: (:), body) = { .. } ``` 因此,我们可以像使用普通数学公式一样,为 `touying-equation` 传入 `block`、`numbering` 和 `supplement` 参数。
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/construct-09.typ
typst
Other
// Test conversion to string. #test(str(123), "123") #test(str(50.14), "50.14") #test(str(10 / 3).len() > 10, true)
https://github.com/MaxAtoms/T-705-ASDS
https://raw.githubusercontent.com/MaxAtoms/T-705-ASDS/main/template.typ
typst
#let example(number: "", body) = { strong("Example "+number) linebreak() body } #let note(body) = { [ #strong("Note") #linebreak() #body ] } #let exercise(number, body) = { strong("Exercise "+number) linebreak() body } #let project( title: none, header-title: none, subtitle: none, university: none, faculty: none, semester: none, lecturer: none, author: none, email: none, body ) = { set text(size: 11pt) set par(justify: true) show link: underline show link: set text(fill: rgb(40,40,220)) // headings show heading: it => context { let num-style = it.numbering if num-style == none { return it } let num = text(weight: "thin", numbering(num-style, ..counter(heading).at(here()))+[ \u{200b}]) let x-offset = -1 * measure(num).width pad(left: x-offset, par(hanging-indent: -1 * x-offset, text(fill: black.lighten(25%), num) + [] + text(fill: black, it.body))) } // title page [ #set text(size: 1.25em) #v(.8fr) #text(size: 2.5em, fill: black, strong(title)) \ #v(0em) #text(size: 1.5em, fill: black.lighten(25%), subtitle) #semester\ #university\ #faculty\ #text(size: 0.6em, upper(strong("Lecturer")))\ #lecturer #text(size: 0.6em, upper(strong("Author")))\ #author\ #email #datetime.today().display("[year]-[month]-[day]") #v(0.1fr) ] // page setup set page( margin: (top: 2.5cm, bottom: 2.5cm, right: 4cm), header: [ #set text(size: 0.75em) #table(columns: (1fr, auto, 1fr), align: bottom, stroke: none, inset: 0pt, [ #header-title ], [], [ #show: align.with(top + right) #semester ]) ] + v(-0.5em) + line(length: 100%, stroke: black), footer: { set text(size: 0.75em) line(length: 100%, stroke: black) v(-0.5em) table(columns: (1fr, auto, 1fr), align: top, stroke: none, inset: 0pt, [], align(center, context { str(counter(page).display()) [ \/ ] str(counter(page).final().last()) }), [] ) } ) // table setup set table( stroke: none, ) set heading(numbering: "1.") counter(page).update(1) body }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/030%20-%20Amonkhet/002_Trust.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Trust", set_name: "Amonkhet", story_date: datetime(day: 05, month: 04, year: 2017), author: "<NAME>", doc ) #figure(image("002_Trust/01.png", width: 100%), caption: [], supplement: none, numbering: none) #emph[Five Planeswalkers have come to Amonkhet to slay a dragon. As the Gatewatch, they had sworn an oath to protect the Multiverse from the threats that spanned the Blind Eternities, and the dragon Planeswalker <NAME> was perhaps the greatest such threat. So they came to Amonkhet—a world of blasted sand and terrible monsters, exactly the hellscape they had expected. Until a god appeared, saved them from sandwurms, and led them in the direction of a city. What kind of city could prosper under Bolas's reign? And what kind of god could live under his oppressive claw?] #figure(image("002_Trust/02.png", height: 40%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Gods? Here?] Gideon had been prepared for many possibilities in the planar lair of <NAME>. To see gods wading amidst the horrors of the desert had not been among them. Were they the pawns of Bolas—was he so powerful that he could wield divine forces as his agents? Or were they an immortal force of opposition to Bolas and his power on this world, hunted by the monstrous agents of the dragon? Either possibility would lend weight to Ajani's warning about the sheer power of the dragon Planeswalker. He paused in the slog through the shifting desert sand and rubbed his temples. Jace and Chandra were engaged in some light-hearted banter, egged on with the occasional sarcastic remark from Liliana, and the noise was starting to worm its way behind his eyes and put pressure on his brain. Or perhaps it was the dry heat and the harsh, unrelenting sunlight. He scowled at Liliana's back as she walked past him, smirking at the success of her efforts to agitate Chandra and fluster Jace. She had pulled them out of the fire on Innistrad, no doubt. But since then she had been nothing but contrary and mocking. She had no sense of what it meant to be part of a team. She was just along for the ride. #emph[And why not?] he thought. #emph[We're all in this for our own reasons. It's so damn ] messy—#emph[all of us, all our emotions and drives and goals.] He felt a cool hand on his arm, and he took a deep breath before looking down to smile at Nissa. The pressure on his brain eased a little, and without a word he and the elf resumed their trek through the sand. #figure(image("002_Trust/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) The shimmering dome they'd seen from afar was close now. Sand piled up around it, blown by storms against the magical barrier. Worse, the wall was lined with . . . "More zombies!" Liliana exclaimed. She sounded much more cheerful about it than Gideon felt. The desiccated creatures stood motionless in the sand, peering into the city beneath the dome. He quickened his steps to catch up to the others. "Liliana, you get the zombies out of the way, then I'll try to break through the dome." Jace arched an eyebrow at him. "Uh, that's my suggestion, anyway. Other ideas?" Gideon reminded himself that he wasn't the general of this little Planeswalker army. Jace, at least, expected to have a say in leadership decisions. And Liliana would do whatever she wanted in any case. "It might be possible to simply break through," Jace said. "But given the things we've seen in this desert, I suspect that barrier is very strong. Assuming it's meant to keep sandwurms out and not to keep people in." "Do you think you can find a way to bypass the magic?" Gideon asked. "Of course I can. But I'll know more when I actually have a chance to examine it." Jace looked over his shoulder at Nissa, then his eyes glimmered with blue light, suggesting he had just begun a telepathic conversation with Nissa that Gideon was not privy to. #emph[Messy,] Gideon thought again. What was #emph[not] messy was their work as a team once they reached the shimmering magical veil. Liliana and Chandra cleared a path through the zombies, Jace and Nissa put their heads together and cast a spell, and a hole a little wider than Jace's outstretched arms opened to admit them. Gideon was the first one to step through the hole and enter a city that once again defied all his expectations of what Bolas's lair would be. #figure(image("002_Trust/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) He stood at the outskirts of town, where lush fields stretching off to his left abutted a sprawl of majestic stone buildings, wide streets, and slender obelisks. He couldn't see the god whose path they had followed here, but the Gatewatch's arrival had attracted attention: perhaps a dozen people, gathered in clumps at a safe or respectful distance, watched them carefully. "Hello!" Gideon said, holding up a palm and stepping forward with a broad smile, even as his mind raced, trying to think of what he could tell these people about himself and his friends. #emph[And about Liliana,] he thought. #emph[How do I explain the way she commands the zombies with a wave of her hand?] His greeting was answered, not by one of the people nearby, but with a flap of wings in the air above him. Looking up, he saw a winged man, with a crane-like head atop an otherwise human body—an aven, he supposed, though without the hawk- or owl-like features of the ones he'd known on Bant so many years ago. Rather than alight and address him, though, the aven flew past him to the iridescent wall they'd passed through. Jace was still holding the passage open for Nissa, and Liliana's attention was still focused on keeping the desert zombies from following them into the city. All three of them started in surprise when the aven squawked at them, "What are you doing?" He landed right beside Jace and nudged him with the butt of his staff—a staff topped with a pair of horns much like the ones still visible on the horizon, by the second sun. "Get out of the way so I can repair—" Before he could finish his sentence, Jace let his hands fall to his sides, and the hole he had opened in the magical wall sealed itself back up. "—the Hekma," the aven finished. He looked at Jace, blinked slowly, then let his long beak bob down and back up again as he took the stranger all in, from his pale skin and strange blue tattoos to his equally strange, equally blue boots. The aven took a step backward, then gave each of them a similar examination, lingering particularly on Chandra's red hair and Nissa's glowing green eyes. "Hello," Gideon said again. He had to work harder to force a smile this time, given the aven's horned staff. "What are you #emph[wearing] ?" the aven said. #figure(image("002_Trust/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Liliana laughed out loud, and Gideon shot her a frown. "#emph[Let me handle this,] " Jace whispered in his mind, while he stepped forward to address the aven. "Trust me," he said, "clothes like this are the height of fashion in . . . " He frowned. ". . . In the district of Sef?" As a rule, Gideon wished Jace wouldn't go prying into other people's heads. In this circumstance, though, it was a gift, allowing him to say exactly what the aven expected him to say. "What were you doing in the desert?" the aven said. "And what did you do to the Hekma?" Jace turned and looked at the iridescent barrier. "Really? You haven't learned this technique yet . . . vizier of the . . . Hekma Guard that you are? Well, of course, that's why I'm here in the . . . Nitin district, to teach you. With Kefnet. Of course." "P—perhaps I—" the aven stammered. "Perhaps you should summon Temmet," Jace said. "He'll know what to do." The aven nodded quickly, then spread his wings and flapped toward the heart of the city. "Who's Temmet?" Chandra said. "Some sort of authority figure," Jace said. "I'm sure you'll love him." Chandra snorted. "Listen," Jace continued. "This is tricky. Vizier Eknet there had absolutely no conception of a place other than this city. That's why I told him we're from another district. We didn't cross the desert from somewhere else—as far as these people know, there is nowhere else. Let alone an infinite expanse of other places." "Well, maybe it's time to open their eyes," Chandra said. Gideon shook his head. "No. We shouldn't draw attention to ourselves any more than we need to, at least until we know what we're up against. Coming in and upsetting their entire view of the world is not going to help us find and fight Bolas." "And our friend Eknet is already suspicious," Jace added. "I didn't pry deep enough to be sure what he's suspicious of, exactly." "What about Bolas?" Liliana said. "I didn't see anything about Bolas," Jace said. "Not in his immediate thoughts." Nissa pointed in the direction the aven had flown off. "That must be Temmet," she said. "Can't be," Chandra said. "He's what, like fourteen?" "Shh," Gideon hissed, turning to face the approaching figure. He was young—probably closer to sixteen, Gideon figured—but he carried himself with poise and confidence. #emph[And the balance of a well-trained soldier,] Gideon thought. #emph[Or maybe a dancer,] he amended. #figure(image("002_Trust/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "Hello," Gideon said, mustering what little friendly cheer he had left. And for the third time he was mostly ignored, as the young man turned his attention—as young men often did—to Liliana. "Good morning," he said with a small bow. "I am Temmet. <NAME> said . . . Well, what he said didn't make very much sense." Gideon and Jace shared a look. "#emph[Best I could do,] " Jace said in Gideon's mind. "#emph[Not good enough,] " Gideon growled back, though he wasn't sure Jace was still listening. "#emph[This is about to get bad.] " Liliana returned Temmet's bow and began slowly winding him around her little finger. "No," she said, "we had some trouble explaining to him the particular nature of our circumstance. I'm so grateful you've come to help sort this out." The young man's chest puffed out ever so slightly, but despite Liliana's flattery, his voice was tight with suspicion. "Of course. What is the problem?" "We have been out in the desert for some time," she said, "on a special mission for the Horned One." She gave the slightest nod in the direction of the great horns looming above the cityscape. Temmet's eyes grew wide, and he spun to look at the horns. "May his return come quickly," he said under his breath, as if by reflex. #emph[His return?] Gideon thought. #emph[So he's not here. Did Liliana lie to us?] "Things here seem to have changed somewhat in our absence," she continued. "Would you be so kind as to be our guide into the city?" "And may we be found worthy," Temmet said, frowning at her. Liliana tilted her head at the apparent non sequitur, but Jace stepped in, repeating the young man's words. "Apologies," he added. "The sun has befuddled our brains." "#emph[It's something they say,] " Jace's voice whispered in Gideon's mind. "#emph[Whenever Bolas is mentioned. Play along.] " "Yes," Liliana said. "All the more reason we could use the assistance of such a knowledgeable and important young man as our guide." Gideon saw suspicion in the young man's eyes.#emph[ This is all wrong,] he thought. #emph[Any second now, he'll call for our arrest.] At last, Temmet nodded. "Of course. But I believe you will find things haven't changed as much as you think. All things are ordered as the God-Pharaoh—may his return come quickly—" He repeated the formula pointedly this time, and paused to make sure they responded. "And may we be found worthy," Jace muttered, and the others followed. "—commanded before his departure, so we will be prepared." "I'm very glad to hear that," Liliana said with a smile. #figure(image("002_Trust/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Temmet led them down broad, straight avenues past square homes, tall obelisks, and massive monuments that often defied gravity. Wide canals carried water from a huge river he saw in the distance, and verdant gardens flourished in defiance of the desert beyond the magical barrier. The city had the atmosphere of a park, smelling of fresh water and sun-warmed stone. Always on the horizon, the twin curving horns of <NAME>—the so-called God-Pharaoh—stood as a reminder of Gideon's purpose here, with the smaller second sun hovering perpetually, impossibly, just to the left of the horns. The people of the city were a diverse lot. Besides humans and more aven, he spotted ram-headed folk similar to the minotaurs of Theros, jackal-headed people, and serpentine folk with cobra heads and no legs. What most caught Gideon's attention, though, was their activity. He saw no shops, no artisans at work, no one performing manual labor of any kind. Instead, they were engaged in combat drills, athletic training, and study—the work of soldiers—and always in groups of about a dozen. Everyone appeared to be at the height of physical fitness. #emph[Is that what Temmet meant when he spoke of being prepared for the God-Pharaoh's return?] Gideon wondered. "What are they training for?" Chandra blurted as they passed a group of people paired off in wrestling matches. Temmet followed her gaze. "I believe those initiates are preparing for the Trial of Strength," he said. He nodded appreciatively. "I suspect Rhonas will find most of them worthy." With a stern glance, Gideon cut Chandra off before she asked another question. Temmet's answer made it clear he expected the strangers to know what the people were doing. Then, finally, Gideon saw laborers—of a sort. Temmet was saying something about the majestic monument they were building, but Gideon's attention was focused on the figures hauling a large block of red sandstone toward the ongoing construction. Wrapped head to toe in white linen, the figures were shriveled enough to convince him that they could not be alive. #emph[More zombies?] he thought, imagining the delight that Liliana must have been feeling. #emph[Mummies, dried out and preserved?] Indeed, Liliana couldn't keep the enjoyment from her voice as she observed, "I have always been impressed with such a wise use of the dead." "Indeed!" Temmet exclaimed. "The Anointed perform all the work here, so the living need do nothing but train. What system could be more perfect?" "I can't imagine a better one," Liliana said, shooting a grin over her shoulder at Gideon. #figure(image("002_Trust/08.jpg", width: 100%), caption: [Art by <NAME>t], supplement: none, numbering: none) They turned down an avenue, and once again Gideon found himself in the presence of a god. Even before he saw her, he felt all his unease and anxiety melt away and a calm settle on his heart, accompanied by a warm shiver that started in his spine and awakened every nerve in his body. Compared to the horizon-walking gods of Theros, or even to the godlike Eldrazi titans, the cat-headed god was small, but she towered over the people around her, whose heads didn't reach to her knees. She wore white and gold and held an enormous golden bow. At first, Gideon thought her feline face was a mask made from gold, but then the pale blue eyes blinked, and then the mouth bent into a warm smile and the god knelt to the ground. The god . . .  Knelt. Gathered before her were a group of young children, no more than ten. Each one held a staff in both hands and stood in a combat stance. The god ever so gently tapped one child's foot—yes, his stance was too wide. "Oketra will know what to do with you," Temmet said, starting down the avenue toward the god. His voice suggested a threat, but Gideon could feel no threat in her presence. #figure(image("002_Trust/09.jpg", width: 100%), caption: [Art by Chase Stone], supplement: none, numbering: none) In his youth, Gideon had once encountered the sun god, Heliod, who had put a hand on the young man's shoulder and invited him to become the sun god's champion. But that hadn't been Heliod's true form—his divinity was veiled, his statue reduced. Gideon hadn't even recognized him until he compared the man's likeness to that of a statue of the god. This god was different. Even if this towering body was not her true form, her divinity was in no way veiled. Gideon felt it in every nerve; it shimmered at the edge of his vision as he gazed at her, and rang in his ears when she spoke. As Temmet led them closer, Gideon could see the adoration and devotion on the faces of the people around the god—the training children, the older ones supervising the exercise, and the others who appeared to have gathered just to be in the presence of the god. #emph[If I could feel such devotion again]  . . . He shook his head. #emph[How could I trust a god again?] The mission Heliod had set before him had led to the death of Gideon's closest friends, his Irregulars. The god of death, Erebos, had destroyed them with a flick of the wrist, punishing Gideon's hubris. The idea of putting his trust in such a divine being ever again felt like a betrayal of their memory. Then she looked at him. Reflexively, gladly, he opened himself to her gaze and she #emph[saw] him. Still on one knee, she reached toward him and placed one finger on his chest. "You're one of mine, <NAME>," she said. She held him transfixed with her gaze while he felt his spirit burn with an incandescent glow. There was nothing else, nowhere else, no one else in all the endless planes of the Multiverse in that moment but himself and the god—Oketra, he knew her name as she knew his, his original name. She was unity, order, solidarity; she was hearts joined in common purpose and bodies working in cooperative action. Nothing about her was messy. She was precisely what she should be and it was good and right that she should be here, now, with him. Then she looked away and he almost lost his balance. She cast her gaze over his companions and her smooth golden brow furrowed ever so slightly. "The rest of you, your fate has not been decided. Not yet." She was finished. With perfect, smooth grace she rose to her feet, and as one Gideon and all the people around her fell to the ground and worshiped her—not out of fear or obligation, but because love for her swelled in their hearts. #figure(image("002_Trust/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) She walked away then, and the sunbaked air felt cold. Gideon stood and watched her until she rounded a corner and he couldn't see her any more. Then he stared in wonder at a towering temple he hadn't seen before, carved in her divine likeness, until Chandra shoved him. Temmet was speaking to him now, no longer to Liliana, and for the first time the young man was smiling at him. Gideon tried to remember what Temmet had been saying, but he kept talking: ". . . two rooms nearby that have just become available. I apologize that we do not have more space at the moment. Follow me, please." Gideon's head was swimming. They had come here to slay a dragon, and instead they had met a god. Jace and Liliana and Ajani had described <NAME> as the most wicked of villains, and this was his home that he supposedly made, but he could not have made #emph[her.] Not if he was as evil as they said. Temmet led them to a nearby building. He pointed out a sort of mess hall or refectory inside, encouraging them to join the other residents for meals there. Then he led them up a long set of stone stairs outside, leading to an overhanging balcony that ran the length of the building. He opened two doors and gestured at the cozy rooms inside. "I trust you will be comfortable here." Liliana swept into one of the rooms and closed the door without a word. Jace, Nissa, and Chandra went into the other, Jace protesting loudly. Gideon, still half-dazed, stayed on the balcony, looking out over the city. His heart leaped at the sight of Oketra walking down the street. The people parted to let her pass, but some of them threw flowers at her feet while others shouted her name. For a second time, Gideon watched until she entered her temple and the great doors closed to block his view. #figure(image("002_Trust/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) He lingered there, enjoying the view of the city, the light of both suns shimmering on the river and the canals, and the iridescent haze of the protective dome, the Hekma. The great horns on the horizon, next to the second sun, were the most prominent reminder of the apparently absent <NAME>, but from this vantage he could see other expressions of the same two-horned symbol: a carving at the top of an obelisk, the negative space between two halves of a huge monument, even a row of them along the outside of the balustrade he was leaning on. He couldn't reconcile the city's obvious devotion to their God-Pharaoh with what he had been told of the dragon Planeswalker—and what he had encountered in Oketra. "Heya, Gids." Chandra emerged from the room and stood beside him at the railing. With a smile, he clapped a hand on her shoulder and they looked out over the city together. She pulled away and looked up at him with a grin. "So—what did she call you?" "Kytheon," he said. "<NAME>." The name felt unfamiliar in his own mouth. "That . . . was my name. On Theros. A long time ago." "Kytheon, Gideon. Not too far off." "No. People on Bant heard it wrong or couldn't say it right and it just sort of stuck. Gideon's my name now." "Nah, Gids is your name, as far as I'm concerned." Gideon laughed, shaking his head, and turned back to the city. Chandra's voice was suddenly more serious. "So what #emph[is] a god, actually?" He blinked, and she rushed ahead. "I mean, are they like angels? Or Eldrazi? Or just really big people? Liliana said that she and Bolas were like gods once—are they Planeswalkers?" Gideon frowned. He hadn't seen evidence of any gods on Kaladesh, at least not like the ones on Theros, so he supposed it made sense that she would ask the question. But it was still a hard question to answer. He leaned on the balustrade and scratched at a sideburn. "Nissa used to talk about the soul of Zendikar," he mused. "She used to talk #emph[to] it, yeah. I think she misses it. Was that a god?" "Maybe, sort of. I'm not sure. I think gods are part of the fabric of a plane, sort of like that. But they embody an aspect of the plane, like the sun or the harvest. Only they're also #emph[people.] They think, they talk . . . " He paused, thinking again of his experience with Heliod. "And on Theros, at least, they can be just as petty, vindictive, and whimsical as humans. And care even less for the value of human life." "You think the cat-god is different." "I'm pretty sure she is." She laughed. "I don't know, the gods of Theros sound a lot like cats." "Oketra is . . . she embodies an #emph[ideal,] not something like the sun. She is solidarity—she's all about working together, being part of something bigger than yourself." Chandra turned around and leaned her elbows on the balustrade, looking back at the rooms where their companions were arguing about the sleeping arrangements. "Well, that part I understand at least." Gideon nodded. That's what the Gatewatch was—an acknowledgement that being a Planeswalker meant more to them than exerting their power and following their whims across the Multiverse. "But if gods are part of the plane," Chandra went on, "and Bolas made this plane like Liliana said, I guess I still don't get how you can be so keen on the cat-god." "Didn't you feel anything? When we met her?" "I'm pretty sure that was a special moment between you two." Their eyes met, then she looked away and Gideon was struck once again by how complicated, how confusing, how messy people could be. #figure(image("002_Trust/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Shouts in the street below grabbed his attention. He scanned the cityscape, looking for the source of the agitation—so seemingly out of place in this tranquil and lovely city. The other Planeswalkers joined them on the balcony. It was Nissa who finally pointed out the origin of the commotion. A lone human figure, a woman, was running through the crowd toward them, pushing people and what Temmet had called the Anointed out of her way, causing as much chaos as she could. Behind her, a gang of soldiers (including a towering minotaur) were gaining on her despite the disruption. Most of the shouts were coming from the woman, but at this distance Gideon couldn't make out the words. Chandra was already starting down the stairs. "We have to help her!" Gideon leaped after her and blocked her path. "Hold on, hothead." She didn't, but instead ducked under one of his outstretched arms. He spun and caught her around the waist. "Remember what I said about not drawing attention to ourselves?" She kicked his shin and he set her down gently. "But she's in #emph[trouble,] " she said. "Probably for good reason. We don't know. It doesn't make sense to jeopardize our mission when we don't even know what's going on." The woman was close now, but her pursuers were gaining on her. "It's all a lie!" she shouted as she ran. "The trials are a lie! The gods lie! The hours are a lie! Free yourselves!" Gideon put a hand on Chandra's shoulder before she could start down the stairs again. He yanked his hand away when her shoulder grew suddenly hot. "Do you hear her?" Chandra said. "She's a freedom fighter!" "We're not on Kaladesh anymore," Gideon said gently. "No, we're in #emph[<NAME>'s house!] " One of the pursuers managed to hook a curved staff around the woman's foot, and she sprawled on the ground. In an instant, the soldiers were on her, holding her arms and hauling her to her feet. "You'll see!" she shouted. "The return will bring only devastation and ruin!" Then the minotaur's hand clamped over her mouth and her shouting ceased. #figure(image("002_Trust/13.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) To her credit, Chandra stayed on the stairs, though Gideon could feel the heat of her anger coming off her in waves. "We should have helped her," she muttered. "Look," Gideon said, putting himself in her line of sight. "We'll ask some questions. Quietly. We'll figure out what's going on, what lies she was talking about, and we'll help her if that turns out to be the right thing to do. I promise." "And what if your precious cat-god is the one lying?" "She's not." "So much for asking questions. Seems you already know the truth." "I don't know about the woman, or the trials, or the hours. But there is no deception in Oketra." "You seem very sure of that," Jace said, joining them on the stairs. "Don't you agree?" Gideon said. "Surely you were reading her mind the whole time." Jace shook his head. "I make it a practice to avoid peeking into brains that are . . . bigger than mine, unless it proves necessary." "Chandra is right, Fearless Leader," Liliana said with a smirk. "The only gods I've ever known of were Planeswalkers with pretensions of divinity. Full of lies." Gideon pushed past them, back up the stairs. "You don't know what you're talking about," he said. "None of you." He stopped short on the top stair, face to face with young Temmet. "I'm sorry for the disturbance," Temmet said. "An unfortunate incident." Chandra was beside the young man in a flash, and she grabbed his shoulder and wheeled him to face her. "Unfortunate incident? What was that about? What did she do?" #emph[So much for asking questions quietly,] Gideon thought. Temmet shrugged. "She proved herself unworthy of life among us." "What does that mean?" Chandra demanded. Gideon saw Temmet's eyes narrow, suspicion returning to his gaze. Clearly, Chandra should have understood this—which meant that it was not an uncommon occurrence. "I'm afraid I don't know the exact nature of her crime," Temmet said. "But those were viziers of Bontu pursuing her, and if I'm not mistaken, her crop was supposed to undertake the trial of Bontu today. Perhaps there was an incident at the temple." He shook his head. "And her crop showed such promise." Gideon steered Chandra away from the young man. "Thank you," he said to Temmet. "I think we should rest now." "Indeed," Temmet said. Gideon led Chandra into their room, and the others followed. "Now what?" Nissa said. "I don't know what to make of any of this." "We have a lot to sort out," Gideon said. "Her #emph[crop,] " Liliana said. "As if they were meant to be #emph[harvested] ?" Jace nodded. "He was thinking of a group of about a dozen people, who've been working together for a long time. They went through three trials together, whatever that means." Chandra flopped face-down on one of the three beds in the room. "Rest does seem like a good idea," Nissa said. She sat on a different bed. "Right," Gideon said. "We'll sort it all out in the morning." "Whatever you say, General, sir," Liliana said. She swept out the door and into the neighboring room. "Am I the only one wondering why Liliana gets a whole room to herself?" Jace said. Gideon shrugged and sat down in a corner, leaving the third bed for Jace. #figure(image("002_Trust/14.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Sleep eluded Gideon as he tried to think through the tangled mess of it all—the revolt on Kaladesh, Tezzeret and his planar bridge, <NAME> and the plane he supposedly made, the return of the God-Pharaoh, the lies of the hours. He always thought better when he was moving around, so he left the room quietly and wandered through the city in the weird half-light of the second sun. He found Oketra outside her temple, just as the larger sun broke above the horizon. "What are you seeking, <NAME>?" she asked him, kneeling again. #emph[Answers,] he thought. #emph[Meaning. Stability. Faith.] "You," he said.
https://github.com/ludwig-austermann/typst-din-5008-letter
https://raw.githubusercontent.com/ludwig-austermann/typst-din-5008-letter/main/lib/default-blocks.typ
typst
MIT License
#let betreff(content, styling: (:), extras: (:)) = { //set align(center) set text(styling.theme-color) strong(content) } #let teilbetreff(content, level: 1, styling: (:), extras: (:)) = { set text(styling.theme-color, styling.text-params.size) if level == 1 { strong(content + ". ") } else { text(weight: "regular", style: "italic", content + ". ") } } #let bezugszeichen(heading, content, styling: (:), extras: (:)) = { text(size: styling.text-params.size - 2pt, heading) linebreak() text(size: styling.text-params.size, content) } #let salutation(wordings: (:), styling: (:), extras: (:)) = { wordings.salutation + "," } #let closing(wordings: (:), styling: (:), extras: (:), signature: none) = { wordings.closing linebreak() if signature == none and styling.handsigned { linebreak(); linebreak() } if signature != none { signature } [@name] } #let pagenumber(wordings: (:), styling: (:), extras: (:)) = { set align(right) locate(loc => { text(styling.theme-color)[#loc.page()] text(gray.darken(50%), " / " + str(counter(page).final(loc).at(0))) }) } #let header(title, wordings: (:), styling: (:), extras: (:)) = locate(loc => if loc.page() > 1 { set text(styling.text-params.size - 2pt, styling.theme-color) set align(horizon) title h(1fr) [@date] }) #let attachments(items, wordings: (:), styling: (:), extras: (:)) = if items != () { set align(left) text(styling.theme-color, strong(wordings.attachments)) linebreak() list(..items) } #let postscriptum(content, wordings: (:), styling: (:), extras: (:)) = { grid(columns: 2, column-gutter: 0.5em, [PS:], content) }
https://github.com/kokkonisd/typst-phd-template
https://raw.githubusercontent.com/kokkonisd/typst-phd-template/main/src/report.typ
typst
The Unlicense
// TEMPLATE FOR PHD REPORTS. #import "colors.typ": * #import "common.typ": * #import "fonts.typ": * #import "logos.typ": * // Define an author group. // // An author group can be anything, from a very specific single-member group (e.g. "PhD student") // to a broader multi-member group (e.g. "External committee"). // // Parameters: // - group-title: the title of the group. // - members: the members of the group. The expected type is an array of author dictionaries, // containing at least the name of the author, and optionally the organization and the email of // the author. // - size: the size of the authors. #let _author-group(group-title: none, members: none, size: none) = box[ #set text(size: size) #stack( dir: ttb, spacing: 8pt, [*#group-title*], // Put all the members under the same group title. stack( dir: ltr, spacing: 20pt, ..for member in members { ( stack( dir: ttb, spacing: 5pt, member.name, if "organization" in member { member.organization }, if "email" in member { link("mailto:" + member.email) }, ), ) } ), ) ] // Define the front page of the report. // // The front page is not numbered and contains the title and subtitle of the report, the date, some // logos and every person that must be mentioned on it (the authors, supervisors, committee // members, ...). // // Parameters: // - title: the title of the report. // - title-size: the size of the title. // - subtitle: the subtitle of the report. // - subtitle-size: the size of the subtitle. // - date: the date of the report. // - date-size: the size of the date. // - authors: the authors and other people that should be mentioned in the front page. The expected // type is an array of rows, where each row can contain one or more groups (with one or more // members). See default arguments in `report-setup()`. // - authors-size: the size of the authors. // - logos: the logos to put in the front page. The expected type is `image()`, not `str`. // - logos-size: the size of the logos. #let _report-front-page( title: none, title-size: none, subtitle: none, subtitle-size: none, date: none, date-size: none, authors: (), authors-size: none, logos: (), logos-size: none, ) = block(width: 100%, height: 100%)[ #set align(center + horizon) // Title/subtitle/date block. #stack( dir: ttb, spacing: 15pt, text(size: title-size)[*#title*], text(size: subtitle-size)[#subtitle], text(size: date-size)[#date.display("[day padding:zero]/[month padding:zero]/[year]")], stack( dir: ltr, spacing: 15pt, ..for logo in logos { ( image(logo.path, height: logos-size), ) } ), ) #v(2cm) // List out the authors. #stack( dir: ttb, spacing: 30pt, // There may be multiple rows of authors. ..for author-row in authors { ( stack( dir: ltr, spacing: 20pt, // Stack the author groups of a given row horizontally. ..for author-group in author-row { ( _author-group( group-title: author-group.group, members: author-group.members, size: authors-size, ), ) } ), ) } ) ] // Define the footer of the report. // // Parameters: // - title: the title of the report. // - subtitle: the subtitle of the report. #let _page-footer(title: none, subtitle: none) = block(width: 100%, height: 100%)[ #set align(horizon) #grid( columns: (1fr, 50pt), [ #set align(left) #set text(weight: "regular", style: "italic") #title #if subtitle != none [ --- #subtitle ] ], [ #set align(right) #context counter(page).display("1 / 1", both: true) ], ) ] // Define the signature page of the report. // // Sometimes reports need to be signed, so this function generates a blank signature page. // // Parameters: // - signature: the title of the signature (e.g. "Signature of the thesis supervisor"). #let _signature-page(signature: none) = block(width: 100%, height: 100%)[ #set align(center + horizon) #box[ #set align(left) #stack( dir: ttb, spacing: 10pt, [*#signature*], [Name:], [Date:], [Signature:], ) ] ] // Set up a report. // // This should be called at the very beginning of the report file. // // Parameters: // - title: the title of the report. // - title-size: the size of the title. // - subtitle: the subtitle of the report. // - subtitle-size: the size of the subtitle. // - date: the date of the report. The expected type is `datetime()`, not `str`. // - date-size: the size of the date. // - authors: the authors and other people that need to appear in the front page of the report. For // the expected type, see the default value below. // - authors-size: the size of the authors. // - logos: the logos to appear on the front page of the report. The expected type is `image()`, // not `str`. // - logos-size: the size of the logos. // - signature: the title of the signature, if one is needed. If `none`, no signature page will be // generated. // - toc: the table of contents (if `none`, the default one will be used). // - bibliography: the bibliography to be used in the report. #let report-setup( title: "Report title", title-size: 40pt, subtitle: "Report subtitle", subtitle-size: 25pt, date: datetime.today(), date-size: 16pt, authors: ( ( ( group: "PhD student", members: ( ( name: "<NAME>", organization: "Default organization", email: "<EMAIL>" ), ), ), ), ( ( group: "Supervisor", members: ( ( name: "<NAME>", organization: "Default organization", email: "<EMAIL>" ), ), ), ( group: "Co-supervisor", members: ( ( name: "Default co-supervisor", organization: "Default organization", email: "<EMAIL>" ), ), ), ), ( ( group: "External committee", members: ( ( name: "Default committee member 1", organization: "Default organization", email: "<EMAIL>" ), ( name: "Default committee member 2", organization: "Default organization", email: "<EMAIL>" ), ) ), ), ), authors-size: 12pt, logos: ( LOGO_CEA_LIST, LOGO_UNIVERSITE_PARIS_SACLAY, LOGO_IP_PARIS, ), logos-size: 60pt, signature: "Signature of the thesis supervisor", toc: none, bibliography: none, doc, ) = { // Main page/font formatting. set page(numbering: "1") set text( font: MAIN_FONT, size: 11pt ) set heading(numbering: "1.") set par(justify: true) show link: set text(fill: blue) show link: underline set list(marker: ([•], [--])) set enum(numbering: "1.a.") // Disable numbering for the first few pages. set page(numbering: none) // Start with the front page. _report-front-page( title: title, title-size: title-size, subtitle: subtitle, subtitle-size: subtitle-size, date: date, date-size: date-size, authors: authors, authors-size: authors-size, logos: logos, logos-size: logos-size, ) // Add the signature page if needed. if signature != none { _signature-page(signature: signature) } // Re-apply numbering from now on, and add the footer. set page( numbering: "1", footer: _page-footer(title: title, subtitle: subtitle), ) // Add the table of contents. if toc != none { toc } else { outline() } pagebreak() doc // Add the bibliography (if it exists). if bibliography != none { pagebreak() bibliography } }
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/basis.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Linear combinations of vectors == [TEXT] Basis <sec-basis> #memo(title: [Memorize: Basis for $RR^n$, "buy two get one free"])[ Suppose you have a bunch of vectors in $RR^n$. Any two of the following imply the third: 1. There are exactly $n$ vectors. 2. The vectors are linearly independent. 3. The vectors are span all of $RR^n$. Moreover, if item 1 is true, the following fourth item works too: 4. The determinant of the $n times n$ matrix with the vectors as column vectors is nonzero. ] This means for dimension, you can often trust your hunches, and they'll be right. For example, you might have the feeling that any good quiz question for $T : RR^2 -> RR^2$ needs to end up having $2$ given equations. You'd be right. More examples of correct hunches implied by the result above: - In $RR^n$, at least $n+1$ vectors are never linearly independent. - In $RR^n$, at most $n-1$ vectors are never spanning. (So a basis is always $n$ vectors exactly.) - Also, if you have exactly $n$ vectors in $RR^n$, and they're linearly independent, then they're a basis. - Also, if you have exactly $n$ vectors in $RR^n$, and they're spanning, then they're a basis. - Most usefully, they're spanning if and only if the $n times n$ matrix whose columns are the vectors has *nonzero determinant*. #todo[Explain why the determinant is true. (Reason: for $n=3$, not being spanning in $RR^3$ means the parallelepiped has volume zero --- the trick from PSet 1. Same idea for $n > 3$ with hypervolumes.) ] The determinant thing matters: the determinant is doing a _lot_ of work for you. When $n = 2$ the determinant is unnecessary, because you can just use "slope": it's obvious that $vec(1,2)$ and $vec(100,200)$ have a dependence. But for $n >= 3$ *you can't eyeball it*#footnote[Though if you have a set of _exactly two_ vectors, they're dependent if and only if they're multiples, even in $RR^n$. Which you _can_ eyeball; so if you're trying to tell whether a span of two vectors in $RR^3$ is a line or plane, that's easy. (Even more stupidly, a single vector is linearly dependent only when it's the zero vector.)]: e.g., $bf(v)_1 = vec(1,3,4)$, $bf(v)_2 = vec(10,1,11)$ and $bf(v)_3 = vec(-9,10,1)$ might look like unrelated small numbers, but surprisingly it turns out that #eqn[ $ 109 bf(v)_1 - 37 bf(v)_2 - 29 bf(v)_3 =0. $ <big-coeff> ] Without "slope", you cannot notice these dependences by sight for $n >= 3$, so use the determinant. == [RECIPE] Describing the span of several vectors #recipe(title: [Recipe for describing the span of vectors in $RR^2$])[ - *0-D case*: Are all the vectors the zero vector $vec(0,0)$? If so the span is just a single *point*. - *1-D case*: Are all the vectors pointing the same direction (i.e. multiples of each other)? If so, and there is at least one nonzero vector, the span is a *line* in the common direction of the vectors. - *2-D case*: Are there two (nonzero) vectors not pointing in the same direction (equivalently, are linearly independent)? If so, the span is *all of $RR^2$*. ] - Example: the span of the vectors $vec(3,6)$, $vec(10,20)$, $vec(100,200)$, $vec(5000, 10000)$ consists of the multiples of $vec(1,2)$. - Example: The span of $vec(420, 321)$ and $vec(666, 5)$ is all of $RR^2$. Because the two vectors are not multiples of each other, they are linearly independent. (Alternatively, calculate $det(mat(420, 666; 321, 5)) = 420 dot 5 - 321 dot 666 = -211686 != 0$.) Hence they are a basis of $RR^2$ and the span is all of $RR^2$. #recipe(title: [Recipe for describing the span of vectors in $RR^3$])[ - *0-D case:* Are all the vectors the zero vector $vec(0,0,0)$? If so the span is just a single *point*. - *1-D case*: Are all the vectors pointing the same direction (i.e. multiples of each other)? If so, and there is at least one nonzero vector, the span is a *line* in the common direction of the vectors. - *2-D case*: Is there more than one direction present, but you can't find three vectors which are linearly independent? If so, the span is a *plane*. - *3-D case*: Are there three vectors among them which are linearly independent from each other? If so, the span is *all of $RR^3$*. ] - Example: the span of the vectors $vec(3,6,9)$, $vec(10,20,30)$ and $vec(100,200,300)$ consists of the multiples of $vec(1,2,3)$. - Example: Following @big-coeff, the span of the $vec(1,3,4)$, $vec(10,1,11)$ and $vec(-9,10,1)$ is a plane. This follows by process of elimination: we know $d = 0$ and $d = 1$ don't apply here (none of these vectors are zero or are multiples of each other) and we can rule out $d = 3$ because we can calculate the determinant $ det(mat(1,10,-9;3,1,10;4,11,1)) = 0 $ to see that our three vectors are _not_ linearly independent. (Again, I want to emphasize that actually finding an explicit dependence --- that is, extracting @big-coeff --- is annoying. You should take the determinant instead, since you only care _whether or not_ there is a dependence, not what the coefficients actually are.) - Example: The span of $vec(3,42,18)$, $vec(1, 53, 17)$, $vec(71,91,13)$ in $RR^3$. As we mentioned above (@big-coeff), you shouldn't eyeball three or more dimensions; if you get three vectors in $RR^3$ and want to know if they are linearly independent or not, you should always take the determinant. The audience picked some very large numbers for me so I got a chance to show off my amazing mental arithmetic skills, but the point is that $ det(mat(3,1,71; 42,53,91; 18,17,13)) = "ugly arithmetic" = -18522 != 0. $ So the three vectors are linearly independent, and hence a basis of $RR^3$. So the span is all of $RR^3$. == Systems of equations == [RECIPE] Number of solutions to a square system of linear equations == [EXER] Exercises #exer[ Take your birthday and write it in eight-digit $Y_1 Y_2 Y_3 Y_4$-$M_1 M_2$-$D_1 D_2$ format. Consider the two vectors $ bf(v)_1 = vec(M_1 M_2, D_1 D_2) " and " bf(v)_2 = vec(Y_1 Y_2, Y_3 Y_4). $ For example, if your birthday was May 17, 1994 you would take $bf(v)_1 = vec(5, 17)$ and $bf(v)_2 = vec(19, 94)$. - Determine the span of those two vectors in $RR^2$. - Find a current or former K-pop idol who gets a different answer from you when they use their birthday. ] <exer-basis-birthday> #exer[ In $RR^5$, consider the vector $bf(v) = angle.l 1,2,3,4,5 angle.r$. What's the maximum number of linearly independent vectors one can find which are all perpendicular to $bf(v)$? ]
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S5/MAT3/docs/4-FormeExponentielle/logarithme-complexe.typ
typst
#import "/_settings/typst/template-note.typ": conf #show: doc => conf( title: [ Logarithmes complexes ], lesson: "MAT3", chapter: "4 - Forme Exponentielle", definition: "Le document aborde le logarithme complexe, expliquant que la fonction exponentielle n'est pas bijective, ce qui entraîne l'existence d'une infinité de solutions pour les logarithmes complexes. Il présente également la forme exponentielle du logarithme et introduit la notion de détermination principale, qui est une solution unique avec une partie imaginaire dans un intervalle donné.", col: 1, doc, ) = Logarithme complexe == Propriétés du logarithme complexe La fonction exponentielle complexe n'est pas bijective, donc elle ne peut pas être inversée sur tout l'espace des nombres complexes. Cependant, pour tout nombre complexe non nul $w$, l'équation $e^z = w$ admet une infinité de solutions. On appelle toute solution $z$ un logarithme complexe de $w$. == Exemple Prenons $w = 1$. Alors $z = 0$ est un logarithme complexe de $w$, et aussi $z = 2 pi j$ car $e^(2 pi j) = 1$. Plus généralement, tous les logarithmes complexes de $w = 1$ sont $z = 2 pi k j$ pour $k ∈ Z$. = Logarithme complexe sous forme exponentielle Si $w = "RE"^(j theta)$ est sous forme exponentielle, un logarithme complexe de $w$ est $z = ln(r) + j theta$ car $e^z = w$. Tous les logarithmes complexes de $w ≠ 0$ sont donc équivalents modulo $2 pi j$. == Détermination principale du logarithme La détermination principale du logarithme de $w ≠ 0$, notée $"Log"(w)$, est l'unique solution de $e^z = w$ dont la partie imaginaire est dans $] -π, π]$. Pour calculer $"Log"(w)$, on écrit $w$ sous forme exponentielle en utilisant son argument principal. == Exemple Pour $w = j - √3$, on a $w = 2e^(5pi/6 j)$ et $"Log"(w) = ln(2) + 5π/6 j$.
https://github.com/Duolei-Wang/modern-sustech-thesis
https://raw.githubusercontent.com/Duolei-Wang/modern-sustech-thesis/main/template/configs/commitment.typ
typst
MIT License
#import "font.typ" as fonts #let commitment( isCN: true ) = { let title = [title] let pars = ([], []) let title-CN = [诚信承诺书] let content-CN = ( [1. 本人郑重承诺所呈交的毕业设计(论文),是在导师的指导下, 独立进行研究工作所取得的成果,所有数据、图片资料均真实可靠。], [2. 除文中已经注明引用的内容外,本论文不包含任何其他人或集体已经发表或撰写过的作品或成果。对本论文的研究作出重要贡献的个人和集体,均已在文中以明确的方式标明。], [3. 本人承诺在毕业论文(设计)选题和研究内容过程中没有抄袭他人研究成果和伪造相关数据等行为。], [4. 在毕业论文(设计)中对侵犯任何方面知识产权的行为,由本人承担相应的法律责任。], ) let title-EN = [COMMITMENT OF HONESTY] let content-EN = ( [1. I solemnly promise that the paper presented comes from my independent research work under my supervisor's supervision. All statistics and images are real and reliable.], [2. Except for the annotated reference, the paper contents no other published work or achievement by person or group. All people making important contributions to the study of the paper have been indicated clearly in the paper.], [3. I promise that I did not plagiarize other people's research achievement or forge related data in the process of designing topic and research content.], [4. If there is violation of any intellectual property right, I will take legal responsibility myself.], ) if(isCN){ title = title-CN pars = content-CN }else{ title = title-EN pars = content-EN } set text( font: fonts.SongTi, weight: "medium", size: fonts.No4, ) align(center)[ #text( font: fonts.HeiTi, size: fonts.No2, weight: "bold" )[ #title ] ] linebreak(justify: true) linebreak(justify: true) set par( leading: 1.5em, justify: true, ) for i in pars{ par()[#i] linebreak(justify: true) } align(right)[ #if(isCN){ box( width: 10em, baseline: 8em, )[ #align(left)[ 作者签名: #linebreak() 日#h(2em)期: ] ] }else{ box( width: 10em, baseline: 8em, )[ #align(left)[ Signature: #linebreak() Ddate: ] ] } ] }
https://github.com/citation-js/plugin-hayagriva
https://raw.githubusercontent.com/citation-js/plugin-hayagriva/main/README.md
markdown
MIT License
Citation.js plugin for the [Hayagriva](https://github.com/typst/hayagriva) YAML format (v0.1.1) used in [Typst](https://typst.app/). [![NPM version](https://img.shields.io/npm/v/@citation-js/plugin-hayagriva.svg)](https://npmjs.org/package/@citation-js/plugin-hayagriva) [![Codecov](https://img.shields.io/codecov/c/gh/citation-js/plugin-hayagriva)](https://app.codecov.io/gh/citation-js/plugin-hayagriva) [![NPM total downloads](https://img.shields.io/npm/dt/@citation-js/plugin-hayagriva.svg)](https://npmcharts.com/compare/@citation-js%2Fplugin-hayagriva?minimal=true) ![License](https://img.shields.io/npm/l/@citation-js/plugin-hayagriva.svg) ## Install ```js npm install @citation-js/plugin-hayagriva ``` ## Use Install the plugin by `require`-ing it: ```js require('@citation-js/plugin-hayagriva') ``` ## Formats Formats and other features added by this plugin. ### Input Because Hayagriva has no distinguishing characteristics (compared to other bibliographical formats) that can be expected to occur in (nearly) all records, types have to be indicates manually: ```js const input = `citation-js: type: article title: "Citation.js: a format-independent, modular bibliography tool for the browser and command line" author: Willighagen, <NAME>. date: 2019-08-12 doi: 10.7717/peerj-cs.214 serial-number: e214 parent: type: periodical title: value: PeerJ Computer Science verbatim: true volume: 5 issn: 2376-5992` Cite(input, { forceType: '@hayagriva/file' }) { title: 'Citation.js: a format-independent, modular bibliography tool for the browser and command line', author: [{ family: 'Willighagen', given: '<NAME>.' }], issued: [{ 'date-parts': [[2019, 8, 12]] }], volume: 5, DOI: '10.7717/peerj-cs.214', number: 'e214', ISSN: '2376-5992', type: 'article-journal', 'container-title': '<span class="nocase">PeerJ Computer Science</span>', 'citation-key': 'citation-js' } ``` ### Output ```js Cite(...).format('hayagriva', { asObject: false /* or true */ }) ``` ## License The code and most other contents in this repository is [licensed MIT](LICENSE). `test/input.yml` contains [examples from the Hayagriva repository](https://github.com/typst/hayagriva/blob/v0.1.1/tests/basic.yml), dual-licensed under [MIT](https://github.com/typst/hayagriva/blob/v0.1.1/LICENSE-MIT).
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/size.typ
typst
--- math-size --- // Test forcing math size $a/b, display(a/b), display(a)/display(b), inline(a/b), script(a/b), sscript(a/b) \ mono(script(a/b)), script(mono(a/b))\ script(a^b, cramped: #true), script(a^b, cramped: #false)$ --- issue-3658-math-size --- $ #rect[$1/2$] $ $#rect[$1/2$]$
https://github.com/Big-Ouden/ensiie_rapport
https://raw.githubusercontent.com/Big-Ouden/ensiie_rapport/main/0.1.5/template/report.typ
typst
#import "@preview/isc-hei-report:0.1.5" : * #let doc_language = "fr" // Or en/de #show: project.with( title: "Rapport de projet pour la filière ISC", sub-title: "Avec une mise en page avec `Typst`", course-name: "101.1 Programmation impérative", course-supervisor : "Prof. <NAME>", semester: "Semestre de printemps", academic-year : "2023-2024", cover-image: image("figs/cover_image_placeholder.png"), cover-image-height: 8cm, // Default value = 10cm cover-image-caption: "KNN graph -- Inspired by _<NAME>_", authors: ( "<NAME>", "<NAME>", "<NAME>" ), logo: image("figs/isc_logo.svg"), date: "21 juin 2024", language: doc_language, // Or en/de if required version: "Using template 0.1.5 $omega$" ) //// If using acronyms #import "@preview/acrostiche:0.3.1": * #include "acronyms.typ" // Let's get started = Introduction Écrire un rapport est un exercice autant *de fond que de forme*. Dans ce contexte, nous proposons dans ce document de quoi simplifier la rédaction de la forme sans avoir -- à priori -- d'avis sur le fond, ceci dans le contexte de la filière ISC#footnote[Voici d'ailleurs comment mettre une note de bas de page https://isc.hevs.ch]. Il convient tout d'abord pour présenter le contenu de se rendre compte que ce système de mise en page permet d'utiliser une forme de _markdown_ comme entrée. Le _markdown_ est une manière de formatter des fichiers textes afin de pouvoir les transformer avec un programme afin de les afficher dans différents formats, comme PDF ou encore sous forme de page web. Le langage _markdown_ utilise différents types de balises permettant de faire du *gras*, de _l'italique_ ou encore du _*gras et de l'italique*_. Il est également possible de faire des listes, des tableaux, des images, des liens hypertextes, des notes de bas de page, des équations mathématiques comme $x^2 = 3$, des blocs de code comme par exemple `def hello()` et encore bien d'autres choses. Vous trouverez ici de la documentation sur la manière d'utiliser le langage `markdown` pour écrire des documents ici : https://www.markdownguide.org/basic-syntax/. Vous trouverez également une version spécifique sur l'écriture de documents en Typst ici https://typst.app/docs/guides/markdown-guide/. En plus des choses simples montrées ci-dessus, le `markdown` simplifie la création de listes avec des nombres comme suit : + Un élément + Un autre élément de liste + Encore d'autres éléments si nécessaire Des choses plus exotiques, comme mettre du #todo[texte mis en évidence] sont également possibles, tout comme les références à d'autres parties, comme dans le @intro[point]. == Insertion de code Nous pouvons également avoir du `code brut directement en ligne` mais cela peut également être fait avec du code Scala comme par exemple dans ```scala def foo(x: Int)```. Cela n'empêche pas d'avoir des blocs de code joliment mis en forme également. Ainsi, lorsque l'on souhaite avoir du code inséré dans une figure, on peut également utiliser le package `sourcecode` qui rajoute notamment les numéros de ligne. En complément avec une `figure`, il est possible d'avoir une _légende_, un numéro de figure ainsi que du code centré : #figure( code()[ ```scala def foo(val a : Any) : Int = { a match : case a: Int => 12 case _ => 42 } ```], caption: "Un tout petit listing en `Scala`" ) On peut si on le souhaite également avoir des blocs de code plus long si nécessaire, sur plusieurs pages : #figure( code()[ ```scala object ImageProcessingApp_Animation extends App { val imageFile = "./res/grace_hopper.jpg" val org = new ImageGraphics(imageFile, "Original", -200, 0) val dest2 = new ImageGraphics(imageFile, "Threshold", 200, 0) var direction: Int = 1 var i = 1 while (true) { if (i == 255 || i == 0) direction *= -1 i = i + direction dest2.setPixelsBW(ImageFilters_Solution.threshold(org.getPixelsBW(), i)) } } ```], caption: "Un autre exemple de code, plus long" ) === Insérer du code à partir d'un fichiers Il est tout à fait possible de mettre du code qui provient d'un fichier comme ci-dessous : #let code_sample = read("code_examples/example.scala") #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file `example.scala`" ) == Insertion d'images Une image vaut souvent mieux que mille mots ! Il est possible d'ajouter des images, bien entendu. La syntaxe est relativement simple comme vous pouvez le voir dans l'exemple ci-dessous: #figure( image("figs/pixelize.png", height: 4cm), caption: [<NAME>, informaticienne américaine] ) <fig_engineer> Pour le reste, voici un texte pour voir de quoi il retourne. Vous allez réaliser une fonction appelée _mean_ qui va appliquer un filtre de moyenne à l'image. Ce filtre a pour but de flouter l'image et d'enlever ainsi ses aspérités. Le principe est le suivant : la valeur d'un pixel est remplacée par la moyenne des pixels se trouvant dans une zone carrée de 3 par 3 pixels autour du pixel. Si on veut calculer la nouvelle valeur du pixel situé à la position $(x,y)$ selon la figure @fig_engineer, sa nouvelle valeur sera la moyenne des 9 valeurs affichées. La dérivée doit se calculer selon les deux axes. Le calcul est très simple : la dérivée selon `x` du pixel situé en $(x,y)$ vaut la valeur du pixel de droite $(x+1, y)$ moins la valeur du pixel de gauche $(x-1,y)$. Dans le cas de la figure, la dérivée selon $x$ vaut $D_x=234-255=-21$. De même, on peut calculer la dérivée selon $y$. Elle correspond au pixel du dessous $(x,y+1)$ moins le pixel $(x,y-1)$ du dessus. Dans le cas de la @fig_engineer, la dérivée selon $y$ vaut $D_y = 230-127 = 103$. La norme de la dérivée est calculée selon le théorème de Pythagore : $ D = sqrt(D_x^ 2 +D_y^2) $ On peut également avoir des notations plus complexes : $ sum_(n=1)^(infinity) 2^(-n) = 1 "ou encore" integral_(x = 0)^3 x^2 dif x $ #showybox( title: "Stokes' theorem", frame: ( border-color: blue, title-color: blue.lighten(30%), body-color: blue.lighten(95%), footer-color: blue.lighten(80%) ), // footer: "Information extracted from a well-known public encyclopedia" )[ Let $Sigma$ be a smooth oriented surface in $RR^3$ with boundary $diff Sigma equiv Gamma$. If a vector field $bold(F)(x,y,z)=(F_x (x,y,z), F_y (x,y,z), F_z (x,y,z))$ is defined and has continuous first order partial derivatives in a region containing $Sigma$, then $ integral.double_Sigma (bold(nabla) times bold(F)) dot bold(Sigma) = integral.cont_(diff Sigma) bold(F) dot dif bold(Gamma) $ ] #pagebreak() == Des tables Il est possible d'insérer des tables simples : #figure( table( align: left, columns: 4, stroke: none, [*Monday*], [11.5], [13.0], [4.0], [*Tuesday*], [8.0], [14.5], [5.0], [*Wednesday*], [9.0], [18.5], [13.0], ), caption: "Une table simple" ) Des tables plus compliquées sont également possible. La page https://typst.app/docs/guides/table-guide/ donne d'ailleurs de bonnes informations. #set table(stroke: (x, y) => ( left: if x > 0 { 0.8pt }, top: if y > 0 { 1.5pt }, )) #figure( table( // Table with 3 columns and 3 rows // There are 3 columns, the first one is twice as large as the two others columns: (2fr, 1fr, 1fr), align: center + horizon, table.header[*Technique*][*Advantage*][*Drawback*], [Diegetic], [Immersive], [May be contrived], [Extradiegetic], [Breaks immersion], [Obstrusive], [Omitted], [Fosters engagement], [May fracture audience], ), caption: [Une table plus complexe], ) == Citer ses sources Il est important de citer les sources que l'on utilise. Par exemple, les deux travaux @mui_nasa_dod09, @mui_hybrid_06 et @mudry:133438 sont deux papiers très intéressants à lire et dont les références complètes se trouvent dans la bibliographie à la fin de ce document. Il est également d'utiliser des acronymes comme par exemple [#acr("USB")] == Le filtre de Sobel Une autre méthode pour extraire les contours à l'intérieur d'une image est d'utiliser #link("https://fr.wikipedia.org/wiki/Détection_de_contours")[l'algorithme de Sobel] Cette méthode est très similaire à celle de la dérivée, mais un peu plus compliquée et donne de meilleurs résultats. Pour l'exemple, la valeur du filtre de Sobel selon _x_ vaudrait : $ S_x= 100 + 2 dot 234 + 84 -128-2 dot 255-123=-109 $ De même la valeur du filtre de Sobel selon _y_ vaudrait: $ S_y= 123+2 dot 230+84-128-2 dot 127-100 $ Comme auparavant, la norme du filtre de Sobel se calcule selon Pythagore et vaut pour cet exemple : $ S = sqrt(S_x^2+S_y^2) = sqrt(109^2+185^2) =214.47 $ == Problématique <intro> #lorem(20) == Plan du travail #lorem(40) #pagebreak() = Conclusion #lorem(500) #pagebreak() #bibliography("bibliography.bib", full: false, style: "ieee") #pagebreak() // Include the appendix in the TOC but without numeration #set heading(numbering: none, outlined : true) // The appendix page #place(center + horizon, [ #set text(size:18pt) = #i18n(doc_language, "appendix-title") ] ) // From now on, do not number the sections and remove from general outline #set heading(numbering: none, outlined : false) #pagebreak() // Table of acronyms #print-index(title: [#i18n(doc_language, "acronym-table-title") #move(dy:-10pt, line(length: 100%, stroke: 0.5pt))]) // Table of figures #pagebreak() #outline( title: i18n(doc_language, "figure-table-title"), depth: 1, indent: true, target: figure.where(kind: image, numbering:"1")) // Table of listings #pagebreak() #outline( title: i18n(doc_language, "listing-table-title"), depth: 1, indent: true, target: figure.where(kind: raw)) // Including code #pagebreak() = #i18n(doc_language, "appendix-code-name") #let code_sample = read("code_examples/example.scala") #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file example.scala" ) #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file example.scala" ) #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file example.scala" ) #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file example.scala" ) #figure( code()[ #raw(code_sample, lang: "scala") ], caption: "Code included from the file example.scala" ) // This is the end !
https://github.com/nath-roset/suiviProjetHekzamGUI
https://raw.githubusercontent.com/nath-roset/suiviProjetHekzamGUI/master/typ%20sources/template.typ
typst
Apache License 2.0
#import "@preview/cheq:0.1.0": checklist #let base( left_header: [ #datetime.today().display("[day]/[month]/[year]") ], right_header: none, title: none, subtitle: none, version: [], authors:(), doc ) = { set document( //basic doc settings author: "<NAME>", title: [#title], date: datetime.today() ) set page( //page rules paper:"a4", margin: (x:2cm, y:3cm), ) set par( // paragraph rules justify: true ) set text( font : "Noto Sans", size: 12pt, fallback: true, lang:"en", region: "US", ) show raw : it =>{ // verbatim/code rules set text( font: "JetBrainsMono NF", size: 12pt, ) [#it] } v(1fr) // front cover rules // Set colors let main-color = "#2CDE85" //Qt Neon Green let primary-color = rgb(main-color) // alpha = 100% // change alpha of primary color let alpha = 60% let secondary-color = color.mix(color.rgb(100%, 100%, 100%, alpha), primary-color, space:rgb) // decorations at top left place(top + left, dx: -35%, dy: -28%, circle(radius: 150pt, fill: primary-color)) place(top + left, dx: -5%, dy: 0%, circle(radius: 75pt, fill: secondary-color)) //logo in the top-right let logo = image("logo-UT3.png",width: 6cm) place(top + right, dy:-5%, logo) // decorations at bottom right place(bottom +right, dx: 48%, dy: 40%, circle(radius: 200pt, fill: secondary-color)) text( size : 18pt, hyphenate: false, align(center)[ // title rules #heading(numbering: none)[ #title ] #parbreak() #heading(level :2)[#subtitle #if version != []{ [ \- _V_ #emph[#version]] } ] #parbreak() *Supervisor* : <NAME> - Associate Professor at Paul Sabatier University - Researcher at IRIT ] ) v(1fr) let count = authors.len() let ncols = calc.min(count, 4) grid( columns: (1fr,) * ncols, column-gutter: 10pt, rows: (1em, 1em), row-gutter: 20pt, align: center, ..authors.map(author => [ #set text(size: 10pt) #set par(justify:false) *#author.name* ]), ..authors.map(author => [ #set text(size: 10pt, hyphenate: false) #author.affiliation #author.email ]) ) counter(page).update(0) set page( numbering:"1/1", header: [ //header rules #set text( font: "Noto Sans Mono", size: 10pt ) #left_header #h(1fr) #right_header ], ) set outline( depth: 2, indent: true, ) set heading( // headings rules numbering: (..nums) => { let level = nums.pos().len() // only level 1 and 2 are numbered let pattern = if level == 1 { "I." } else if level == 2 { "I.1." } if pattern != none { numbering(pattern, ..nums) } } ) set table( //table rules fill: (x,y) => if y == 0 { gray.lighten(40%) }, ) show link : it => { //external links rules set text( fill: blue.darken(30%), ) underline[#it] } show: checklist.with( //checklist rules unchecked: sym.ballot, checked: sym.ballot.x ) show heading : it =>{ if it.level > 2 { set text( // fill: rgb("#2CBEC0"), ) [#it] } else { [#it] } } pagebreak(weak: true) doc } // highlight paths differently from verbatim text #let dirpath(body) = { set text(fill: rgb("#AA0000")) raw(body) }
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Personal%20Notes/DeepLearning/CompiledNotes.typ
typst
#import "../../template.typ": * #show: template.with( title: [Dive into Deep Learning Book], authors: ( ( name: "<NAME>" ), ), description: [Notes Based on the book Dive into Deep Learning at #link("d2l.ai") & supplemental reading orvideos] ) #include "Modules/Introduction.typ"
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/compiler/bindings.typ
typst
Apache License 2.0
#import "/docs/cookery/book.typ": * #show: book-page.with(title: "Compiler in Wasm (Web)") #let snippet-source = "https://github.com/Myriad-Dreamin/typst.ts/blob/main/packages/typst.ts/src/contrib/snippet.mts" #let snippet-lib = link(snippet-source)[`snippet`] #include "../claim.typ" The most simple examples always work with #snippet-lib utility library, an all-in-one library with simplified API interfaces: ```ts import { $typst } from '@myriaddreamin/typst.ts/dist/esm/contrib/snippet.mjs'; console.log((await $typst.svg({ mainContent: 'Hello, typst!' })).length); // :-> 7317 ``` Please check #cross-link("/guide/all-in-one.typ")[All-in-one (Simplified) Library for Browsers] for more details. Quick example for the harder way to serverless compiler: ```ts import { createTypstCompiler } from '@myriaddreamin/typst.ts'; const mainFilePath = '/main.typ'; const cc /* compiler */ = createTypstCompiler(); await cc.init(); cc.addSource(mainFilePath, 'Hello, typst!'); await cc.compile({ mainFilePath }); ``` Note: For #link("https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking")[_tree-shaking_], you should import it with longer path: In *ES Module* path: ```ts import { createTypstCompiler } from '@myriaddreamin/typst.ts/dist/esm/compiler.mjs'; ``` Or in *CommonJS* path: ```ts const { createTypstCompiler } = require('@myriaddreamin/typst.ts/dist/cjs/compiler.cjs'); ``` == Add or remove source/binary files You can also use the `{map,unmap,reset}Shadow` function to manipulate any text or binary file data for typst compiler. They will shadow the file access from provided access model directly in memory. The `mapShadow(path: string, content: Uint8Array): void;` resembles `addSource(path: string, source: string): void;`, but retrieves some binary data without guessing the underlying encoding. Example usage: ```ts const encoder = new TextEncoder(); // add a json file (utf8) compiler.mapShadow('/assets/data.json', encoder.encode(jsonData)); // remove a json file compiler.unmapShadow('/assets/data.json'); // clean up all shadow files (Note: this function will also clean all files added by `addSource`) compiler.resetShadow(); // add an image file const pngData = await fetch(...).arrayBuffer(); compiler.mapShadow('/assets/tiger.png', new Uint8Array(pngData)); ``` == Specify output format Export document as #link("https://github.com/Myriad-Dreamin/typst.ts/blob/main/docs/proposals/8-vector-representation-for-rendering.typ")[_Vector Format_] which can then load to the renderer to render the document. ```ts const artifactData = await compiler.compile({ mainFilePath: '/main.typ', // the default value of format field: // format: 'vector', }); ``` == Specify extra initialization options You must specify the extra init options when calling the `init` function. For example, to load the wasm module from a custom path: ```js await cc.init({ getModule: () => '/path/to/typst_ts_web_compiler_bg.wasm', }); ```
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/config.typ
typst
#let theme = ( primary: red, primary_light: red.lighten(75%), primary_trans: red.transparentize(75%), secondary: blue, secondary_light: blue.lighten(75%), secondary_trans: blue.transparentize(75%), tertiary: yellow.darken(15%), tertiary_light: yellow.lighten(75%), tertiary_trans: yellow.transparentize(75%), fg: black, fg_light: black.lighten(50%), fg_trans: black.transparentize(50%), bg_light: black.lighten(90%), bg_trans: black.transparentize(90%), success: green.lighten(25%), success_light: green.lighten(75%), success_trans: green.transparentize(75%) ) #let config(doc) = { set text( lang: "de", font: "Noto Sans", hyphenate: true ) set par(justify: true) show figure: set par(justify: false) set outline( indent: true, depth: 2, title: "", ) show outline: columns.with(2) set footnote.entry(separator: none) show math.equation.where(block: true): set align(start) show math.equation: set text(font: "Fira Math") set heading(numbering: (..nums) => { if nums.pos().len() <= 2 { numbering("1.1", ..nums) } else { none } }) show heading.where(level: 4): set heading(outlined: false) show heading: h => { set text(font: "Noto Serif", size: 20pt) set block(above: 12pt, below: 12pt) set par(justify: false) block({ if h.numbering == none { text(h.body) } else if h.level <= 2 { let c = counter(heading).display(h.numbering) set text(weight: "light") text(c, weight: "black") text(" ") text(h.body) } else if h.level == 3 { text( h.body, weight: "black", size: 11pt ) } else { text( h.body, size: 11pt, weight: "light", font: "Noto Sans", style: "italic" ) } if h.has("label") { let refs = query(ref.where(target: h.label)) if refs.len() != 0 { text(" ") let target = refs.first().location() link(target, sym.arrow.t.stop) } } }) } show raw: set text(font: "Noto Sans Mono") show raw.where(block: false): set text(size: 11pt) show raw.where(block: true): it => { set par(justify: false) block( stroke: rgb(0, 0, 0, 20%), radius: 4pt, above: 8pt, below: 8pt, table( columns: 1fr, stroke: none, fill: (_, y) => if calc.odd(y) { rgb(0, 0, 0, 5%) }, inset: (x: 8pt, y: 6pt), ..it.lines.map(l => if l.text.len() == 0 {hide("a")} else {l}) ) ) } show bibliography: set par(justify: false) doc }
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/patterns/weeks/week12.typ
typst
#import "../../utils.typ": * #subsection("Singleton (Boxing and Killing)") #set text(size: 14pt) Problem | Guarantee that a resource exists *exactly once* and can be globally accessed.\ Context | - one instance - globally accessible - subclassing should be possible - extending must not break code - lazy or eager loading possible #set text(size: 11pt) // images // ```java public class Singleton { private static class InstanceHolder { // Singleton will be instantiated as soon as the // ClassLoader instantiates the overlying class. private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return InstanceHolder.INSTANCE; } protected Singleton() { } // allow subclassing } ``` #columns(2, [ #text(green)[Benefits] - controlled access to sole instance - reduced name space - premits variable number of instances - -> can also be a dualton, tripleton, etc. - more flexible than class operations -> static etc. #colbreak() #text(red)[Liabilities] - introduces global state - clients might be interfering - no polymorphism - hard to test - requires mock implementations - multithreading makes access harder - use rust... ]) #subsubsection([Registry]) #set text(size: 14pt) Problem | This solves the issue of testability with a singleton by providing a registry to allow different singletons to replace each other. E.g. poor mans polymorphism.\ #set text(size: 11pt) // images #align( center, [#image("../../Screenshots/2023_12_08_04_57_16.png", width: 50%)], ) #align( center, [#image("../../Screenshots/2023_12_08_05_03_00.png", width: 100%)], ) #columns(2, [ #text(green)[Benefits] - better testing via singleton plymorphism #colbreak() #text(red)[Liabilities] - IPC style registering - type leads to runtime error ]) #subsubsection([Monostate(Killing)]) *Problem* | Given code that uses a singleton, you need to remove the singleton for your tests...\ *Solution* | Wrap the singleton access into monostate, which can either return the singleton, or a stub.\ ```lang // this is a regular monostate public class Monostate { private static int x; private static int y; public int getX() { return x; } public int getY() { return y; } } // this can instead be used to access the singleton OR a stub: public interface Monostate { int getX(); int getY(); } public class MonostateImpl implements Monostate { public int getX() { return Singleton.getInstance().getX(); } public int getY() { return Singleton.getInstance().getY(); } } public class MonostateMockImpl implements Monostate { private static MockSingleton = new MockSingleton(); public int getX() { return MockSingleton.getX(); } public int getY() { return MockSingleton.getY(); } } // both can now be used ``` compared to regular singleton #columns(2, [ #text(green)[Benefits] - testing, polymorphism #colbreak() #text(red)[Liabilities] ]) regular monostate #columns(2, [ #text(green)[Benefits] - transparency -> no need to know about monostate - well defined creation and destruction for static members #colbreak() #text(red)[Liabilities] - monostate objects are real -> use memory - monostate can lead to unexpected behavior -> static data - monostate data is always allocated - monostate may not use internal state -> non static state ]) #subsubsection([Killing]) #set text(size: 14pt) Problem | A framework uses a singleton, we therefore need a way to circumvent the singleton in order to test the code.\ #align( center, [#image("../../Screenshots/2023_12_08_05_05_17.png", width: 100%)], ) #text(red)[Solution with monostate pattern combined!] #set text(size: 11pt) #align( center, [#image("../../Screenshots/2023_12_08_05_31_53.png", width: 100%)], ) #subsubsection([Service Locator]) #set text(size: 14pt) #align( center, [#image("../../Screenshots/2023_12_08_05_38_11.png", width: 100%)], ) Problem | Same as singleton. Global functionality.\ Context | However, here we would like to *not use* singletons, instead we pick the functionality from the singleton and use this instead, hence *services*.\ Participants: - Provider/ServiceLocator: Registry Singleton that provides all service finders - Finder: ServiceFinder that provides a service implementation - Service: Service that does something... #set text(size: 11pt) - Implement the ServiceLocator as a Singleton «Registry» - Holds the concrete finder implementations - ServiceLocator returns finder instances, which are used to locate the underlying services - Both, finder and service are exposed by interfaces only - Also known as dynamic ServiceLocator or *Provider* // images #align( center, [#image("../../Screenshots/2023_12_08_05_44_20.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_12_08_05_44_31.png", width: 100%)], ) #columns( 2, [ #text(green)[Benefits] - only a single singleton is used - all others are polymorphic with interfaces - services can be exchanged even at runtime #colbreak() #text(red)[Liabilities] - clients still rely on a static reference to ServiceLocator (tight coupling) - hence ServiceLocator can't be removed - can be removed with dependency injection ], )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/def_use/import_alias_both.typ
typst
Apache License 2.0
#import "base.typ" #base #import "base.typ" as foo: x as foo #base, #foo
https://github.com/rxt1077/it610
https://raw.githubusercontent.com/rxt1077/it610/master/markup/slides/cloud.typ
typst
#import "/templates/slides.typ": * #show: university-theme.with( short-title: [Cloud] ) #title-slide( title: [Cloud Computing] ) #alternate( title: [What is it?], image: licensed-image( file: "/images/cloud.svg", license: "CC BY-SA 4.0", title: [FSFE There is no cloud postcard en.svg], url: "https://upload.wikimedia.org/wikipedia/commons/f/f5/FSFE_There_is_no_cloud_postcard_en.svg", author: [<NAME>, FSFE], author-url: "https://fsfe.org/contribute/spreadtheword.html#nocloud", ), text: [ - A silly catchphrase with a disheartening origin - Technically it can be IaaS, SaaS, PaaS - Is it new? - Why virtualize? Why not just rent servers? ], ) #focus-slide([What's good about it?]) #matrix-slide(columns: 3, rows: 2, [Redundancy], [Scalability], [Co-Location], [Lower Bandwidth Costs], [Lower Building Costs], [Lower Staffing Costs] ) #focus-slide([What's bad about it?]) #matrix-slide(columns: 1, rows: 3, [Recurring Costs], [Loss of Physical Control], [Security Concerns] ) #slide( title: [How does it work?], [ \ #side-by-side[ *Virtual Machines* \ \ - VirtualBox, QEMU, VMware, #link("https://aws.amazon.com/ec2/nitro/")[AWS Nitro], etc. - What are they? - How do they work? - Why use them? ][ *Containers* \ \ - Docker, etc. - What are they? - How do they work? - Why use them? ]] ) #slide( title: [Who does it?], side-by-side[ #v(1fr) - #link("https://aws.amazon.com")[Amazon Web Services] - #link("https://azure.microsoft.com/en-us")[Microsoft Azure] - #link("https://cloud.google.com/products/compute")[Google Compute Engine] - Most PaaS and SaaS runs on one of these #v(1fr) ][ #v(1fr) #grid( columns: (1fr, 1fr), rows: (1fr, 1fr), gutter: 20pt, align(horizon, image("/images/aws.svg", width: 100%)), align(horizon, image("/images/azure.svg", width: 100%)), grid.cell( colspan: 2, align(center)[ #image("/images/gce.svg", height: 90%) #text(size: 8pt, [AWS, Azure, and GCE logos are used under fair use]) ] ) ) #v(1fr) ] ) #alternate( title: [Want to try it at home?], image: licensed-image( file: "/images/messy-servers.jpg", license: "CC BY 2.0", title: [servers], url: "https://www.flickr.com/photos/40987321@N02/5580348753", author: [hisperati], author-url: "https://www.flickr.com/photos/40987321@N02", ), text: [ - #link("https://www.reddit.com/r/homelab/")[/r/homelab] - Server hardware is #link("https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313.TR0.TRC0.A0.H0.Xr710.TRS5&_nkw=r710&_sacat=0")[CHEAP] (data centers refresh often) - Virtualization Platforms - #link("https://www.proxmox.com/en/")[Proxmox] - #link("https://www.vmware.com/products/cloud-infrastructure/esxi-and-esx")[ESXi] - #link("https://www.xenserver.com/")[XenServer] - You will learn a lot - You may also scare your family members and pets with loud noises and heavy computers! - What is in the "bare metal" of a virtualization server? Memory and processor cores. The more the merrier. ], ) #alternate( title: [What can AWS do for you?], image: licensed-image( file: "/images/aws-funny.png", license: "FAIRUSE", title: [AWS in a Nutshell], url: "https://www.reddit.com/r/ProgrammerHumor/comments/9ym7mj/aws_in_a_nutshell/", ), text: [ - Network architecture as code (subnets, VPCs, internet gateways, NAT gateways, load balancers, etc). - Tons of services: S3 storage, RDS database, ECS containers, EC2 compute, IAM identity and access... - Deploy _quickly_ - Scale _quickly_ - Unique products: spot instances, AMI sharing, mechanical turk #emoji.face ] ) #alternate( title: [How do you deploy to AWS?], image: licensed-image( file: "/images/aws-funny2.jpg", license: "FAIRUSE", title: [Using AWS], url: "https://www.reddit.com/r/ProgrammerHumor/comments/w4eo12/using_aws/", ), text: [ From least favorite to most favorite: \ \ + AWS Web Console / Instance Management + AWS Command Line and scripts + AWS Command Line and Ansible/Vagrant + #link("https://www.terraform.io/")[Terraform] and Provisioning Scripts + Terraform and Ansible \ #link("https://thenewstack.io/hashicorp-abandons-open-source-for-business-source-license/")[Terraform licensing issue?] ], )
https://github.com/bsp0109/ieee-typst-template
https://raw.githubusercontent.com/bsp0109/ieee-typst-template/main/conference.typ
typst
#import "template.typ": * #show: ieee.with( title: "Test", abstract: [ ], authors: ( ( name: "Name", department: [Dept of Affiliation], organization: [Affiliation], location: [City, Country], email: "<EMAIL>" ), ( name: "Name", department: [Dept of Affiliation], organization: [Affiliation], location: [City, Country], email: "<EMAIL>" ), ), index-terms: ("A", "B", "C", "D"), bibliography-file: "refs.bib", ) = Introduction = Theoretical Framework = Methodological Framework = Result Analysis = Recommendations and Conclusions
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/let.typ
typst
// Test let bindings. --- let-basic --- // Automatically initialized with none. #let x #test(x, none) // Manually initialized with one. #let z = 1 #test(z, 1) // Syntax sugar for function definitions. #let fill = conifer #let f(body) = rect(width: 2cm, fill: fill, inset: 5pt, body) #f[Hi!] --- let-termination --- // Termination. // Terminated by line break. #let v1 = 1 One // Terminated by semicolon. #let v2 = 2; Two // Terminated by semicolon and line break. #let v3 = 3; Three #test(v1, 1) #test(v2, 2) #test(v3, 3) --- let-valid-idents --- // Test what constitutes a valid Typst identifier. #let name = 1 #test(name, 1) #let name_ = 1 #test(name_, 1) #let name-2 = 1 #test(name-2, 1) #let name_2 = 1 #test(name_2, 1) #let __name = 1 #test(__name, 1) #let ůñıćóðė = 1 #test(ůñıćóðė, 1) --- let-binding-keyword-in-markup --- // Error: 6-8 expected pattern, found keyword `as` // Hint: 6-8 keyword `as` is not allowed as an identifier; try `as_` instead #let as = 1 + 2 --- let-binding-keyword-in-code --- #{ // Error: 7-9 expected pattern, found keyword `as` // Hint: 7-9 keyword `as` is not allowed as an identifier; try `as_` instead let as = 10 } --- let-ident-parenthesized --- // Test parenthesised assignments. #let (a) = (1, 2) --- let-incomplete --- // Error: 5 expected pattern #let // Error: 6 expected pattern #{let} // Error: 6-9 expected pattern, found string #let "v" // Error: 7 expected semicolon or line break #let v 1 // Error: 9 expected expression #let v = // Error: 6-9 expected pattern, found string #let "v" = 1 // Terminated because expression ends. // Error: 12 expected semicolon or line break #let v4 = 4 Four // Terminated by semicolon even though we are in a paren group. // Error: 18 expected expression // Error: 11-12 unclosed delimiter #let v5 = (1, 2 + ; Five // Error: 9-13 expected pattern, found boolean #let (..true) = false --- underscore-invalid --- #let _ = 4 #for _ in range(2) [] // Error: 2-3 unexpected underscore #_ // Error: 8-9 expected expression, found underscore #lorem(_) // Error: 3-4 expected expression, found underscore #(_,) // Error: 3-4 expected expression, found underscore #{_} // Error: 8-9 expected expression, found underscore #{ 1 + _ } --- let-function-incomplete --- // Error: 13 expected equals sign #let func(x) // Error: 15 expected expression #let func(x) = --- let-function-parenthesized --- // This is not yet parsed in the ideal way. // Error: 12 expected equals sign #let (func)(x) --- let-function-parenthesized-with-init --- // These errors aren't great. // Error: 12 expected equals sign // Error: 15-15 expected semicolon or line break #let (func)(x) = 3 --- let-with-no-init-group --- // This was unintentionally allowed ... // Error: 9 expected equals sign #let (a) --- let-with-no-init-destructuring --- // ... where this wasn't. // Error: 12 expected equals sign #let (a, b) --- issue-4027-let-binding-with-keyword-context --- // Error: 6-13 expected pattern, found keyword `context` // Hint: 6-13 keyword `context` is not allowed as an identifier; try `context_` instead #let context = 5 --- issue-4027-let-binding-with-keyword-let --- // Error: 6-9 expected pattern, found keyword `let` // Hint: 6-9 keyword `let` is not allowed as an identifier; try `let_` instead #let let = 5 --- issue-4027-let-binding-with-destructured-keywords --- // Error: 7-14 expected pattern, found keyword `context` // Hint: 7-14 keyword `context` is not allowed as an identifier; try `context_` instead // Error: 21-24 expected pattern, found keyword `let` // Hint: 21-24 keyword `let` is not allowed as an identifier; try `let_` instead #let (context, foo, let) = (5, 6, 7)
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/计算方法B/code/hw2/hw2.typ
typst
#import "../../../template.typ": * #show: note.with( title: "作业2", author: "YHTQ", date: datetime.today().display(), logo: none, withOutlined : false, withTitle : false, withHeadingNumbering: false ) = 2 注意到 $norm(x + y) = norm(x) + norm(y)$ 等价于柯西不等式: $ inner(x, y) <= norm(x) norm(y) $ 取等,显然当且仅当 $x, y$ 线性相关且 $inner(x, y) = x^T y >= 0$ = 3 $ norm(A)_F^2 = sum_(i j) a_(i j)^2 = sum_j (sum_i a_(i j)^2) = sum_j norm(a_i)^2_2 $ = 4 #let bc = autoRVecNF(i => $beta_#i$, $n$) #let abc = autoRVecNF(i => $A beta_#i$, $n$) #let nf(A) = $norm(#A)_f$ #let nf2(A) = $norm(#A)_f^2$ #let n2(A) = $norm(#A)_2$ #let n22(A) = $norm(#A)_2^2$ 设 $B = bc$,则: $ nf2(A B) = nf2(abc) = sum_j n2(A beta_j) <= sum_j n22(A) n22(beta_j) = n22(A) sum_j n22(beta_j) \ = n22(A) nf2(B) $ 开方即得 $nf(A B) <= n2(A) nf(B)$\ 另一方面,有: $ nf(A B) = nf((A B)^T) = nf(B^T A^T) <= n2(B^T) nf(A^T) = n2(B) nf(A) $ 就是第二个不等式 = 8 #let suma = sumf() #let summ = sumf(lower: $m$) 考虑形式幂级数: $ suma A^n $ 断言它收敛,事实上使用柯西准则: $ norm(summ A^n) <= summ norm(A^n) <= summ norm(A)^n -> 0 $ 因此一定收敛。设其和为 $B$,则: $ B (I - A) = (suma A^n)(I - A) = I $ 表明 $B$ 就是 $I-A$ 的逆,并且: $ norm(B) = norm(suma A^n) <= suma norm(A^n) <= suma norm(A)^n = 1/(1 - norm(A)) $ 证毕 = 11 == 1. #empty $ A = mat(375, 374;752, 750)\ mat(1, 0;-2, 1) A = mat(375, 374;2, 2)\ mat(1, 0;-1, 1/2) A = mat(375, 374;1, 1)\ mat(375, -187;-1, 1/2) A = mat(1, 0;1, 1)\ mat(375, -187;-376, 187.5) A = mat(1, 0;0, 1)\ $ $kappa_infinity A = norm(A) norm(Inv(A)) = 1502 * 188.5 = #(1502 * 188.5) $ == 2. #let b1 = -376 + 187.5 * 375 / 187 #let b1s = repr(-376 + 187.5 * 375 / 187) 等式变为: $ x = Inv(A) b $ 取 $b = vec(1, 375/187)$,则: $ x = vec(0, b1s) $ 做微扰: $ Inv(A) (b + vec(epsilon_1, epsilon_2)) = vec(375 epsilon_1 - 187 epsilon_2, b1 - 376 epsilon_1 + 187.5 epsilon_2) $ $epsilon_1, epsilon_2$ 很小时,$b$ 变化量很小,但: $ norm(delta x)/norm(x) >= abs(375 epsilon_1 - 187 epsilon_2)/b1s = abs(#repr(375 / b1) epsilon_1 - #repr(187 / b1) epsilon_2) >= 1 $ == 3. #empty #let c1 = 374 * 752 / 375 - 750 #let c1s = repr(c1) 取 $x = vec(374/375, -1)$,则: $ A x = vec(0, c1s)\ A (x + vec(epsilon_1, epsilon_2)) = vec( 375 epsilon_1 + 374 epsilon_2, c1s + 752 epsilon_1 + 750 epsilon_2) $ $epsilon_1, epsilon_2$ 很小时,$x$ 变化量很小,但: $ norm(delta b)/norm(b) >= abs(375 epsilon_1 + 374 epsilon_2)/(c1s) = abs(#repr(375 / c1) epsilon_1 + #repr(374 / c1) epsilon_2) $
https://github.com/El-Naizin/cv
https://raw.githubusercontent.com/El-Naizin/cv/main/modules/projects.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Projects & Associations") #cvEntry( title: [Volunteer Data Analyst], society: [ABC Nonprofit Organization], date: [2019 - Present], location: [New York, NY], description: list( [Analyze donor and fundraising data to identify trends and opportunities for growth], [Create data visualizations and dashboards to communicate insights to the board of directors], [Collaborate with other volunteers to develop and implement data-driven strategies], [Provide regular data analysis reports to the board of directors and executive leadership] ) )
https://github.com/nahdiasma2/lab3
https://raw.githubusercontent.com/nahdiasma2/lab3/main/Lab3.typ
typst
#import "Class.typ": * #show: ieee.with( title: [#text(smallcaps("Lab #3: Web Application with Genie"))], /* abstract: [ #lorem(10). ], */ authors: ( ( name: "<NAME>", department: [Senior-lecturer, Dept. of EE], organization: [ISET Bizerte --- Tunisia], profile: "a-mhamdi", ), ( name: "<NAME>", department: [Dept. of EE], organization: [ISET Bizerte --- Tunisia], profile: "saadaiheb5", ), ( name: "<NAME>", department: [Dept. of EE], organization: [ISET Bizerte --- Tunisia], profile: "nahdiasma2", ), ) // index-terms: (""), // bibliography-file: "Biblio.bib", ) = Introduction In this lab, we will using *Genie* framework in Julia to control some paramaters of a sine wave, given some adjustble parameters.for that we gonna need to employ julia REPL as in fig1 #figure( image("Images/REPL.png", width: 100%, fit: "contain"), caption: "Julia REPL" ) <fig:repl> = Application In this lab we gonna need two support programme to add , change and generate some sine parametre in GenieFramework beside following the steps underneath . #rect(fill: green)[The first programme "app.jl"] #let code=read("../Codes/web-app/app.jl") #raw(code, lang: "julia") #rect(fill: green)[the second programme is "app jl .html"] #let code=read("../Codes/web-app/app.jl.html") #raw(code, lang: "html") #rect(fill: red)[First step:GenieFramework] - copy the path of web app ```julia julia> cd("C:\\Users\\doctor\\Desktop\\infodev\\Codes\\web-app") ``` - Openning Genie in julia REPL ```julia julia> using GenieFramework julia> Genie.loadapp() # Load app ``` #figure( image("Images\GENIE.PNG", width: 70%), caption: [ Genie oppening ], ) - Gettin GenieFramework link(http://127.0.0.1:8000) by typing this code in julia ```julia julia> up() # Start server``` - copy the link in the browser to get the graphical interface as in figure 3 #figure( image("Images/FIRST.png", width: 80%), caption: "Genie gaphical interface ", ) #rect(fill: red)[Second step:Adjust the phase] - adding the phase to "app.jl" ```julia using GenieFramework @genietools @app begin @in N::Int32 = 1000 @in amp::Float32 = 0.25 @in freq::Int32 = 1 @in ph ::Float32 = 0 @out my_sine = PlotData() @onchange N, amp, freq,ph , begin x = range(0, 1, length=N) y = amp*sin.(2*π*freq*x.+ph) my_sine = PlotData(x=x, y=y, plot=StipplePlotly.Charts.PLOT_TYPE_LINE) end end @page("/", "app.jl.html") ``` - adding phase to "app jl.html " ```julia <div class="st-col col-12 col-sm st-module"> <p><b>phase</b></p> <q-slider v-model="freq" :min="-3.14" :max="3.14" :step="0.314" :label="true"> </q-slider> </div> ``` - the result in genie graphical interface : #figure( image("Images/PHASE.png", width: 80%), caption: "Adding phase parameter", ) #rect(fill: red)[third step:Adjust the offset] - adding the offset to "app.jl" ```julia using GenieFramework @genietools @app begin @in N::Int32 = 1000 @in amp::Float32 = 0.25 @in freq::Int32 = 1 @in ph ::Float32 = 0 @in off::Float32 = 0 @out my_sine = PlotData() @onchange N, amp, freq,ph , begin x = range(0, 1, length=N) y = amp*sin.(2*π*freq*x.+ph).+off my_sine = PlotData(x=x, y=y, plot=StipplePlotly.Charts.PLOT_TYPE_LINE) end end @page("/", "app.jl.html") ``` - adding offset to "app jl.html " ```julia <div class="st-col col-12 col-sm st-module"> <p><b>offset</b></p> <q-slider v-model="freq" :min="-0.5" :max="1" :step="0.1" :label="true"> </q-slider> </div> ``` - the result in genie graphical interface : #figure( image("Images/offset.png", width: 80%), caption: "Adding the offset parameter", )
https://github.com/Hofer-Julian/typst_reproducer
https://raw.githubusercontent.com/Hofer-Julian/typst_reproducer/main/reproducer.typ
typst
#box( height: 20pt, image("calendar.svg") ) #line(length: 100%, stroke: (paint:rgb("#cbd5e1"), dash: "dashed")) #box( height: 20pt, image("calendar.svg") )
https://github.com/furkan/cv
https://raw.githubusercontent.com/furkan/cv/main/modules/projects.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Projects") #cvEntry( title: [<NAME>], society: [], date: [2019 - Present], location: [], description: list( [A Telegram bot that keeps track of debts between a group of people. The code is open sourced and shared on my GitHub account. Initially, I used to run my instance on the cloud. After a few years, I made the project footprint smaller, added containerization, and started hosting my instance on a Raspberry PI Zero at home. The bot is named after two lovely cats who were once housemates of mine.] ) ) #cvEntry( title: [School Projects], society: [METU EEE], date: [2018 - 2020], location: [], description: list( [#text(weight: "bold")[Autonomous Cat Feeding System:] An integrated system of cameras, object detection and recognition models, and a web interface. ], [#text(weight: "bold")[Mouse Tracker:] A Kalman Filter software, developed with C and LabVIEW and running on an FPGA, that tracks and predicts the movement of the mouse. ], [#text(weight: "bold")[Ball & Beam:] A PID controller designed to control the position of a ball on a beam. (Arduino) ], [#text(weight: "bold")[Fake Quidditch:] An FPGA game that is coded with Verilog, displayed with the VGA interface, and controlled with analog buttons. ], [#text(weight: "bold")[Optical Wireless Communication System, Photophone:] An analog system that takes an input audio signal, transmits that through air via light, to be played out at the other end by a speaker. ], [#text(weight: "bold")[Wireless Fire Detection System:] An analog system in which various LEDs indicate the position of the highest temperature among spaced out sensors. ], [#text(weight: "bold")[Single-Axis Solar Tracking System:] An analog system in which a servo motor rotates a panel to where it faces the brightest light. ], ) )
https://github.com/saYmd-moe/note-for-statistical-mechanics
https://raw.githubusercontent.com/saYmd-moe/note-for-statistical-mechanics/main/contents/PartII/Chp06.typ
typst
#import "../../template.typ": * == 近独立子系的统计应用 === 二能级系统与负温度 $cal(H)$ 中的核自旋数量子数 $j = 1\/2$ 的粒子。有两个能级:$epsilon_1 = -mu cal(H) equiv -epsilon, quad epsilon_2 = mu cal(H) equiv epsilon$,其子系配分函数、内能和熵均可计算:$ Z = sum_lambda g_lambda e^(-beta epsilon_lambda) = e^(beta epsilon) + e^(-beta epsilon)\ U = macron(E) = -N diff/(diff beta) ln Z = - epsilon (e^(beta epsilon) - e^(- beta epsilon))/(e^(beta epsilon) + e^(-beta epsilon))\ S = N k (ln Z - beta diff/(diff beta) ln Z) = N k [ln(e^(beta epsilon) + e^(-beta epsilon)) - beta epsilon (e^(beta epsilon) - e^(- beta epsilon))/(e^(beta epsilon) + e^(-beta epsilon))] $温度与熵之间存在关系 $display(1/T = ((diff S)/(diff macron(E)))_(N,V))$,为了方便表示 $1\/T$,我们对 $S$ 进行改写,首先有:$ macron(a)_1 = N e^(beta epsilon)/(e^(beta epsilon) + e^(-beta epsilon)), quad macron(a)_2 = N e^(-beta epsilon)/(e^(beta epsilon) + e^(-beta epsilon)) $又有:$ macron(E) = (macron(a)_2 - macron(a)_1) epsilon\ N = macron(a)_1 + macron(a)_2 $解得:$ macron(a)_1 = 1/2 (N - macron(E)/epsilon), quad macron(a)_2 = 1/2 (N + macron(E)/epsilon) $于是系统总量子态数:$ W(macron(a)_1, macron(a)_2) = N!/(macron(a)_1 ! macron(a)_2 !) = N!/([1/2 (N - macron(E)/epsilon)]! [1/2 (N + macron(E)/epsilon)]!) $由_Boltzmann_关系:$ S = k ln W &approx k {N ln N - 1/2 (N - macron(E)/epsilon) ln [1/2 (N - macron(E)/epsilon)] \ &- 1/2 (N + macron(E)/epsilon) ln [1/2 (N + macron(E)/epsilon)]} $于是温度有:$ 1/T = ((diff S)/(diff macron(E)))_N = k/(2 epsilon) ln (N-macron(E)/epsilon)/(N+ macron(E)/epsilon) $由上式可以看出:$macron(E) lt 0 arrow.double T gt 0; quad macron(E) gt 0 arrow.double T lt 0.$ - 关于负温度的结论 + 处于负温度的系统,能量高于处于正温度的系统 + 负温度比正温度更热 + $plus.minus infinity$ 是相同的温度 + $beta$ 越小,系统越热 - 负温度出现的条件 + 粒子能级有上限 + 负温度系统必须与正温度系统隔绝;或者内部平衡弛豫时间小于系统于外界之间的弛豫时间 === 热辐射理论 $ cases( display(#[波动观点])cases( display(#[经典统计理论:_Rayleigh-Jeans_ 公式]), display(#[量子统计理论:_Plank_ 量子理论]) ), display(#[粒子观点:_Einstein_ 光子气理论]) ) $ ==== 经典理论 将空窖中的电磁场分解为无穷多*简正模*,每个简正振动相当于一个简谐振子。即将空窖中的辐射场等效为无穷多个简谐振子组成的系统,对该系统使用统计方法处理。考察简谐振子时,从相空间转到波矢量是很有益的,考虑满足周期性边界条件的波矢:$ bold(k)=(2 pi)/(L)(n_1,n_2,dots.c) , quad k_i = (2 pi)/L_i n_i $每组 $(n_1,n_2,dots.c)$ 与偏振方向 $p$ 共同确定一种单色平面波 $(bold(k),p)$。每一个波矢在波矢空间中占据体积 $(2pi\/L)^r$,$r$ 是自由度的数目。假设 $r = 3$,波矢在 $k$ 到 $k + dif k$ 区间内的总波矢数为:#v(1.25em)$ D(k) dif k = (#pin(1) 4pi k^2#pin(2) dif k #pin(3))/(#pin(4) (2 pi \/ L)^3 #pin(5))=V/(2 pi^2) k^2 dif k $#v(2.5em) #pinit-highlight-equation-from((1, 3), 2, height: 1em, pos: top, fill: rgb(0, 180, 255))[ $(k,k+dif k)$ 区间波矢空间体积,是一个球壳 ] #pinit-highlight-equation-from((4, 5), 5, height: 1.5em, pos: bottom, fill: rgb(150, 90, 170))[ 单个波矢在波矢空间占据的体积 ] 现在从波矢空间转到我们关心的频率空间中,由色散关系 $omega = c k$:$ D^*(omega) dif omega = #pin(10) 2 times #pin(20) V/(2 pi^2 c^3) omega^2 dif omega = V/( pi^2 c^3) omega^2 dif omega $#v(3.5em) #pinit-highlight-equation-from((10, 20), 20, height: 2.5em, pos: bottom, fill: green)[ 正反两个偏振方向引起的修正因子 ] 随后就可以计算 $dif omega$ 区间内的能量了:$ U_omega dif omega = epsilon_(bold(k),p)^r (omega) D^* (omega) dif omega = V/(pi^2 c^3) k T omega^2 dif omega $<Rayleigh-Jeans-formula>该式即为_Rayleigh-Jeans_公式,其中 $epsilon_(bold(k),p)^r$ 为单个单色平面波的能量,包含两个平方项(分别来自电场 $cal(E)$ 和磁场 $cal(H)$),由能量均分定理:$display(macron(epsilon)_(bold(k),p)^r = k T)$。对所有频率积分得到总能量:$ U = integral_0^(infinity) U_omega dif omega = V/(pi^2 c^3) k T integral_0^(infinity) omega^2 dif omega = infinity $这是由于能量均分定律的使用导致内能密度发散,为了解决这个问题,我们需要 _Plank_的量子理论。 ==== _Plank_的波动观点 对能量进行量子化,将谐振子的能量看作最小能量的整数倍:$ epsilon arrow epsilon_(bold(k),p)^r = n_(bold(k),p)^r h nu quad (n_(bold(k),p)^r=0,1,2,dots.c) $平均能量现在由子系配分函数给出 $macron(epsilon)=macron(E)\/N=- diff/(diff beta) ln Z$:$ Z = sum_n e^(-beta epsilon_n) = sum_n e^(-beta n h nu) = 1/(1-e^(-beta h nu)) \ macron(epsilon) = - diff/(diff beta) ln Z = (h nu)/(e^(beta h nu)-1) $当简谐振子能量不连续时,能量均分定理 $macron(epsilon)=k T$不成立,此时振子的平均能量与频率有关。此时 $dif omega$ 区间内的能量为:$ U_omega dif omega = macron(epsilon)(omega) D^*(omega) dif omega = V/(pi^2 c^3) (h nu)/(e^(beta h nu)-1) omega^2 dif omega = V/(pi^2 c^3) (hbar omega^3)/(e^(beta hbar omega)-1) dif omega $<Plank-formula>该式即为_Plank_公式,进而计算辐射场总能量$ U &= integral_0^(infinity) U_omega dif omega = V/(pi^2 c^3) integral_0^(infinity) (hbar omega^3)/(e^(beta hbar omega)-1) dif omega attach(=,t: x equiv beta hbar omega) V/(pi^2 beta^4 c^3 hbar^3) integral_0^(infinity) (x^3)/(e^x - 1) dif x \ &= (pi^2 k^4 V)/(15 hbar^3 c^3) T^4 = a T^4 $其中有积分式 $display(integral_0^(infinity) (x^3)/(e^x - 1) dif x = pi^4/15)$。另外有_Wien_位移定律 $display((hbar omega_max)/(k T) approx 2.822)$。 ==== _Bose_的粒子观点(光子气) 将热辐射场看作是由大量全同光子组成的,光子的自旋($s = 1$),是_Bose_子。与_Plank_的波动观点通过_de Broglie_关系($bold(p) = hbar bold(k), quad epsilon=hbar omega=c p$)相联系。光子可以被空窖的壁面吸收/发射,所以光子数不守恒,化学势为零 $alpha = -beta mu = 0$,于是平衡态的光子气满足最概然分布:$ macron(a)_lambda = g_lambda/(e^(beta epsilon_lambda)-1) $光子气在 $(omega,omega + dif omega)$ 频率间隔内的能量为:$ macron(E)(omega)dif omega = sum_(dif omega) macron(a_lambda) epsilon_lambda = sum_(dif omega) (g_lambda epsilon_lambda)/(e^(beta epsilon_lambda) - 1) = (sum_(dif omega) g_lambda) (hbar omega)/(e^(hbar omega\/k T)-1) $<energy>令 $D(omega) dif omega$ 表示频率间隔 $(omega,omega+dif omega)$ 内的光子状态数,$D(omega)$ 代表光子的态密度,对于宏观体积 $V$ 来说,光子频率(及其动量)可以看作是连续变化的,因此可以使用积分代替求和:$ D(omega) dif omega = sum_(dif omega) g_lambda = 2 times limits(integral)_(dif omega) (dif omega^(*))/h^3 = 2 V/h^3 4 pi p^2 dif p = (V)/(pi^2 c^3) omega^2 dif omega $因子 $2$ 同样是来源于两个不同的偏振方向。代回 @energy 中,可得:$ macron(E)(omega) dif omega = V/(pi^2 c^3) (hbar omega^3)/(e^(hbar omega\/k T)-1) dif omega $与_Plank_的波动观点得到的_Plank_公式 @Plank-formula 相同。对于光子气我们还可以使用_Bose_子系的巨配分函数研究它的其他热力学性质:$ ln Xi &= - sum_lambda g_lambda ln(1-e^(-alpha-beta epsilon_lambda)) = - sum_lambda g_lambda ln(1-e^(-beta epsilon_lambda)) \ &= - integral_0^(infinity) ln(1-e^(-beta hbar omega)) D(omega) dif omega \ &= - V/(pi^2 c^3) integral_0^(infinity) omega^2 ln(1-e^(-beta hbar omega)) dif omega \ &= V/(pi^2 hbar^3 c^3) (k T)^3 integral_0^(infinity) x^2 ln(1-e^(-x)) dif x $其中 $x equiv beta hbar omega$,使用分部积分: #v(1.5em)$ ln Xi &= - V/(pi^2 hbar^3 c^3) (k T)^3 quad 1/3{#pin(1) [x^3 ln(1- #pin(2) e^(-x))]_0^infinity #pin(3) - #pin(4) integral_0^infinity (x^3 #pin(5))/(e^x - 1) dif x #pin(6)} \ #v(3.5em) &=- (pi^2 V)/(45) ((k T)/(hbar c))^3 $ #pinit-highlight-equation-from((1, 3), 2, height: 1.5em, pos: bottom, fill: rgb(0, 180, 255))[ $=0$ ] #pinit-highlight-equation-from((4, 6), 5, height: 2.5em, pos: top, fill: rgb(150, 90, 170))[ $=pi^4\/15$ ] 然后很快啊,就能写出其他热力学量了:$ cases( display(U = - diff/(diff beta) ln Xi = (pi^2 V k^4)/(15 hbar^3 c^3) T^4), display(p = 1/beta diff/(diff V) ln Xi = (pi^2 k^4)/(45 hbar^3 c^3) T^4 = U/(3V)), display(S = k (ln Xi - beta diff/(diff beta) ln Xi) = (4 pi^2 V k^4)/(45 hbar^3 c^3)T^3), display(#[辐射通量密度:]J = 1/4 U c = (pi^2 k^4)/(60 hbar^3 c^2) T^4 = sigma T^4) ) $ === 固体热容理论 #align(center)[ #table( columns: (auto, auto, auto,auto), inset: 10pt, align: center, [*模型*],[*系统组成*],[*能级连续性*],[*频率*], [经典模型],[系统由 $N$ 个原子,可以看作 $3 N$ 个独立简谐振子],[能级连续变化,服从能量均分定律],[不考虑], [_Einstein_模型],[与经典模型的假设相同],[量子化的能量$epsilon = (n+1/2)hbar omega$],[所有振子频率相同], [_Debye_模型],[将固体看作连续弹性介质,由 $3 N$ 个独立平面波组成],[量子化的能量$epsilon_i = (n_i +1/2)hbar omega$],[不同简正振动的频率不同,有色散关系 $omega = c_i k$,横波与纵波的声速 $c_i$ 不同], )] ==== 经典模型 $N$ 个原子分别在各自平衡位置作微小简谐振动,共有 $3N$ 个振动自由度。固体微观总能量为:$ E = sum_(i=1)^(3N) epsilon_i + E_0 $其中 $epsilon_i$ 为第 $i$ 个振动自由度的能量,有经典形式:$ epsilon_i = p_i^2/(2m) + 1/2 m omega^2 q_i^2 $$E_0$是固体结合能,只与体积有关。根据能量均分定理:$ macron(E) = 3 N k T + E_0\ C_V = ((diff macron(E))/(diff T))_V = 3 N k $<Dulong-Petit-Relation>@Dulong-Petit-Relation 也叫做 _Dulong-Petit_关系。 ==== _Einstein_的量子理论 辐射场的_Rayleigh-Jeans_公式 @Rayleigh-Jeans-formula 不发散是由于能量均分定理在低温下不适用,由此对上述经典系统的假设进行量子化处理,取量子化的振子能量:$ epsilon_n = (n+1/2)hbar omega, quad (n = 0,1,2,dots.c) $每个振动自由度都看作是一个子系,_Einstein_模型是一个近独立的定域子系,使用_Maxwell-Boltzmann_分布计算子系配分函数:$ Z = sum_(n=0)^(infinity) e^(-beta epsilon_n) = sum_(n=0)^(infinity) e^(-beta (n+1\/2) hbar omega) = e^(-beta hbar omega\/2) sum_(n=0)^(infinity) e^(-beta hbar omega n) = (e^(-beta hbar omega\/2))/(1-e^(-beta hbar omega)) $于是每个振动自由度的平均能量:$ macron(epsilon) = - diff/(diff beta) ln Z = 1/2 hbar omega + (hbar omega)/(e^(hbar omega\/k T)-1) $总能量:$ E = 3N macron(epsilon) = (3 N hbar omega)/(e^(hbar omega\/k T)-1) + E_0 $其中固体结合能 $E_0 = 3N hbar omega \/2$,于是固体热容为:$ C_V = ((diff macron(E))/(diff T))_V = 3 N k ((hbar omega)/(k T))^2 e^(hbar omega\/k T)/(e^(hbar omega\/k T)-1)^2 $<Einstein-CV-formula>令 $x equiv hbar omega \/ k T = theta_V\/T$,代入 @Einstein-CV-formula,有:$ C_V = 3 N k (x^2 e^x)/(e^x - 1)^2 $ 这就是 _Einstein_固体热容公式。当温度足够高($hbar omega \/ k T lt.double 1$)时,该公式退化为经典统计的结果 $C_V = 3 N k$;当温度足够低($hbar omega \/ k T gt.double 1$)时,固体热容随温度趋于零而趋于零,这也是热力学第三定律(绝对零度不可能达到)。 ==== _Debye_理论 把固体看作连续的介质,其中可以传播弹性波,弹性波可以分解为不同的简正模,将简正模作为子系使用 _Maxwell-Boltzmann_分布进行研究,_Einstein_的量子理论将每个振子的频率都看作相同的,_Debye_理论则考虑不同简正模的频率不同。与辐射场的电磁波相比,弹性波有两点不同: + 电磁波是横波,弹性波是既有横波也有纵波。$c_t, quad c_l$分别代表横波与纵波的传播速度; + 空窖中的辐射场有无穷大多的自由度,而 $N$ 个原子的固体振动总自由度为 $3 N$。所以存在*截止频率(_Debye_ 频率)* $omega_D$。 首先计算频率为 $omega$ 的简正模的平均能量,与 _Einstein_ 的量子理论相同,使用 _Maxwell-Boltzmann_ 分布计算子系配分函数:$ Z = sum_(n=0)^(infinity) e^(-beta epsilon_n) = (e^(-beta hbar omega \/2))/(1-e^(-beta hbar omega)) $于是频率为 $omega$ 的振子的平均能量为:$ macron(epsilon) (omega) = - diff/(diff beta) ln Z = 1/2 hbar omega + (hbar omega)/(e^(hbar omega\/k T) - 1) $<debye-ave-energy> 由于每个振子都在不同频率下振动,总能量等于每个频率 $omega$ 下的振子数量乘上该频率下的平均能量再求和,为了计算频率在 $(omega,omega+dif omega)$ 区间内的振动自由度,我们首先转到波矢空间中,即 $(k,k+dif k)$区间内的波矢个数:$ D(k) dif k = (4 pi k^2 dif k)/((2 pi)/L)^3 = V/(2 pi^2) k^2 dif k $三维空间中横波有两个偏振方向,纵波只有一个,$c_t, quad c_l$分别代表横波与纵波的传播速度,由色散关系 $omega = c_t k, quad omega = c_l k$,得到:$ D^*(omega) dif omega = 2 times V/(2pi^2) 1/c_t^3 omega^2 dif omega + V/(2pi^2) 1/c_l^3 omega^2 dif omega = V/(2pi^2) (2/c_t^3 + 1/c_l^3) omega^2 dif omega = B omega^2 dif omega $<debye-density>其中$ B equiv V/(2pi^2) (2/c_t^3 + 1/c_l^3) $所有原子的振动自由度为 $3 N$,所以存在一个截止频率 $omega_D$ 使得:$ 3 N = integral_0^omega_D D^*(omega) dif omega = integral_0^omega_D B omega^2 dif omega = B/3 omega_D^3 \ arrow.double omega_D = ((9 N)/B)^(1\/3) $现在我们就可以使用平均能量 @debye-ave-energy 和态密度 @debye-density 计算固体的总能量了:$ macron(E) = integral_0^omega_D macron(epsilon) (omega) D^*(omega) dif omega = B integral_0^omega_D (hbar omega^3)/(e^(hbar omega\/ k T)-1) dif omega + E_0(V) $令 $y equiv hbar omega\/k T,quad x equiv hbar omega_D \/ k T = theta_D \/ T$,其中 $theta_D = hbar omega_D \/ k$ 称为 _Debye_温度,代入上式,注意到$B = 9N\/omega_D^3$ 有:$ macron(E) &= B ((k T)/hbar)^4 hbar integral_0^x y^3/(e^y - 1) dif y + E_0(V) \ &= 3 N k T 3/x^3 integral_0^x y^3/(e^y - 1) dif y + E_0(V) \ &= 3 N k T C(x) + E_0(V) $其中 $C(x)$ 是一个无量纲的函数,称为 _Debye_函数,同时也是 $T$ 的函数,于是热容有:$ C_V = ((diff macron(E))/(diff T))_V = 12 N k C(x) - (9 N k x)/(e^x - 1) $考虑两种极限情况: + *高温极限* $(T gt.double theta_D)$ 此时退化为经典统计 + *低温极限* $(T lt.double theta_D)$ 有 *_Debye_ $T^3$定律*,即 $display(C_V/(3 N k) approx (4 pi^4)/(5) T^3/theta_D prop T^3)$ 在足够低的温度下,起主要贡献的是低频(长波长)简正模,当波长满足 $lambda gt.double a$($a$ 为晶格常数)时可以看作连续弹性介质。 === 非简并理想气体 理想气体是非定域系统,我们考虑满足非简并条件 $e^alpha gt.double 1$,其热力学量可以使用子系配分函数表示如下:$ cases( display(macron(N) &= e^(-alpha) Z), display(macron(E) &= -N diff/(diff beta) ln Z), display(macron(Y)_l &= - N/beta diff/(diff y_l) ln Z), display(S &= N k (ln Z - beta diff/(diff beta) ln Z) - k ln N!), display(mu &= - k T ln Z/N) ) $理想气体分子的能量可以表示为四部分之和,分别是分子的平动、转动、振动和束缚电子运动的能量:$ epsilon_lambda = epsilon^t + epsilon^r + epsilon^v + epsilon^e $同样,分子的配分函数也可以表示为四项配分函数相乘:$ Z &= sum_lambda g_lambda e^(-beta epsilon_lambda)\ &= (sum g^t e^(-beta epsilon^t))(sum g^r e^(-beta epsilon^r))(sum g^v e^(-beta epsilon^v))(sum g^e e^(-beta epsilon^e))\ &= Z^t Z^r Z^v Z^e $ ==== 单原子分子理想气体 对于单原子分子,能量仅有平动和束缚电子运动能量。首先考虑平动,在宏观体积下假设平动能级满足能级准连续 $Delta epsilon^t \/ k T lt.double 1$,因此平动配分函数中的求和可以转化为子相空间中对子相体积元的积分,注意到平动能量 $epsilon^t = (p_x^2 + p_y^2 +p_z^2)\/2m$:$ Z^t &= sum_lambda g_lambda^t e^(-beta epsilon_lambda^t)= integral (dif omega^t)/h^3 e^(-beta epsilon^t)\ &= 1/h^3 integral.triple dif x dif y dif z integral.triple dif p_x dif p_y dif p_z e^(-(p_x^2+p_y^2+p_z^2)\/2 m k T) \ &= V/h^3 (2 pi m k T)^(3\/2) $<gas-partition-function>对于束缚电子运动能量的配分函数,由于束缚电子基态能级 $epsilon_0^e$ 与第一激发能级 $epsilon_1^e$ 之间能量差远大于 $k T$,所以束缚电子运动能量的配分函数可以只取基态能级:$ Z^e = sum_lambda g_lambda^e e^(-beta epsilon_lambda^e) approx g_0^e e^(-beta epsilon_0^e) $于是便可计算平动和束缚电子运动的平均能量和热容:$ macron(epsilon^t) = - diff/(diff beta) ln Z^t = 3/2 k T&, quad C_V^t = N (dif macron(epsilon^t))/(dif T) = 3/2 N k\ macron(epsilon^e) = - diff/(diff beta) ln Z^e = epsilon_0^e&, quad C_V^e = N (dif macron(epsilon^e))/(dif T) = 0\ macron(epsilon) = macron(epsilon^t) + macron(epsilon^e) = 3/2 N k T + epsilon_0^e&, quad C_V = C_V^t + C_V^e = 3/2 N k $同样可以计算其他热力学量,取电子基态能量为能量零点 $epsilon_0^e = 0$:$ p &= N/beta diff/(diff V) ln Z = N/beta diff/(diff V) ln Z^t \ &= N/beta 1/V = (N k T)/V = n k T\ S &= N k (ln Z - beta diff/(diff beta) ln Z) - k ln N! \ &= 3/2 N k ln T + N k ln V/N + 3/2 N k {5/3 + ln [g_0^e ((2 pi m k)/(h^2))]}\ mu &=- k T ln Z/N = - k T ln{((2 pi m k T)^(3\/2)g_0^e)/(n h^3)}\ &= -k T ln{((2 pi m)^(3\/2)(k T)^(5\/2) g_0^e)/(p h ^3)} $<single-atom-gas-thermo> ==== 双原子分子理想气体 只需添加转动和振动部分的配分函数,平动和束缚电子运动的能量与单原子的情况相同。 首先考虑转动部分,由量子力学,双原子分子的转动能力和简并度分别为:$ epsilon_lambda^r = h^2/(8 pi^2 I) lambda (lambda+1) quad (lambda = 0,1,2,dots.c)\ g_lambda^r = 2 lambda +1 quad (lambda = 0,1,2,dots.c) $于是可以写出转动配分函数:$ Z^r = sum_(lambda=0)^(infinity) (2 lambda +1) e^(-lambda (lambda+1) theta_r\/T) $其中 $display(theta_r equiv h^2/(2 I k))$,称为*转动特征温度*。现在考虑两种极限情况:#v(1.5em) + *高温极限($T gt.double theta_r$):*此时满足经典极限条件,配分函数中对于量子态的求和可以用子相体积的积分代替,有经典表达式:$ epsilon^r = 1/(2 I) (p_theta^2 + 1/(sin^2 theta) p_phi.alt^2) $$ Z^r &= 1/h^2 integral_0^pi dif theta integral_0^(2 pi) dif phi.alt integral_(-infinity)^(+infinity) e^(-beta p_theta^2\/2I) dif p_theta integral_(-infinity)^(+infinity) e^(-beta p_phi.alt^2\/2I sin^2 theta) dif p_phi.alt\ &= 1/h^2 2 pi ((2 pi I)/beta) integral_0^pi sin theta dif theta \ &= (8 pi^2 I)/(h^2 beta) $于是平均转动能量:$ macron(epsilon^r) = - diff/(diff beta) ln Z = 1/beta = k T\ C_V^r = N (diff macron(epsilon^r))/(diff T) = N k $ + *低温极限($T lt.double theta_r$):* 保留前两项,有:$ Z^r = sum_(lambda=0)^(infinity)(2lambda + 1) e^(-lambda(lambda+1)/theta_r\/T) approx 1 + 3 e^(-2 theta_r\/T)\ ln Z^r = ln(1 + 3 e^(-2 theta_r\/T)) approx 3 e^(-2 theta_r\/T) $进而:$ macron(epsilon^r) = -diff/(diff beta) ln Z^r = 6 k theta_r e^(-2 theta_r\/T)\ C_V = N (diff macron(epsilon^r))/(diff T) = 12 N k (theta_r/T)^2 e^(-2 theta_r\/T) $ #h(2em)下面讨论振动配分函数,同样先给出量子力学形式:$ epsilon_n^v = (n+1/2) hbar omega quad (n = 0,1,2,dots.c)\ g_n^v = 1 quad (n = 0,1,2,dots.c) $振动配分函数为:$ Z^v = sum_n e^(-(n + 1\/2)hbar omega \/ k T) = (e^(-hbar omega\/2 k T))/(1-e^(-hbar omega\/k T)) $于是平均振动能量和热容:$ macron(epsilon^v) = -diff/(diff beta) ln Z^v = (hbar omega)/(e^(hbar omega\/k T) - 1) + 1/2 hbar omega \ C_V^v = N (diff macron(epsilon^v))/(diff T) = ((hbar omega)/(k T))^2 (e^(hbar omega\/k T))/(e^(hbar omega\/k T)-1)^2 = (x^2 e^x)/(e^x - 1)^2 $其中 $x equiv hbar omega\/k T = theta_v \/ T$,$theta_v equiv hbar omega\/k$ 称为*振动特征温度*。可以看到表达式与_Plank_理论下的辐射场能量相同,因为二者使用的都是简谐振子的模型。 ==== 多原子分子理想气体 #text(red)[\#TODO多原子分子理想气体的计算] === 弱简并理想气体 相较于非简并条件 $e^(alpha) gt.double 1$,弱简并条件为 $e^alpha > 1$。 ==== 弱简并理想_Bose_气体 将分子看作质点,忽略内部结构,考虑自旋 $s = 0$ 的_Bose_子;注意到宏观体积下有能级准连续 $Delta epsilon lt.double k T$,用相体积积分代替简并度求和求其巨配分函数:$ ln Xi &= -sum_lambda g_lambda ln(1-e^(-alpha-beta epsilon_lambda))\ &=- integral (dif omega)/h^3 ln(1-e^(-alpha-beta epsilon)) $其中能量 $epsilon = (p_x^2 + p_y^2 + p_z^2)\/2m=p^2\/2m$,我们有*态密度*,粒子能量区间 $(epsilon,epsilon dif epsilon)$ 内的量子态数量为 $D(epsilon) dif epsilon$,有:$ D(epsilon)dif epsilon &= integral (dif omega)/h^3 = 1/h^3 integral.triple dif x dif y dif z integral.triple dif p_x dif p_y dif p_z \ &= V/h^3 4 pi p^2 dif p = (2 pi V)/h^3 (2m)^(3\/2) epsilon^(1\/2) dif epsilon $带回上式中,我们令 $x equiv beta epsilon$,于是巨配分函数有:$ ln Xi &= - (2 pi V)/h^3 (2m)^(3\/2) integral_0^(infinity) ln(1-e^(-alpha-beta epsilon)) epsilon^(1\/2) dif epsilon\ &= - (2 pi V)/h^3 ((2m)/beta)^(3\/2) integral_0^(infinity) ln(1-e^(-alpha-x)) x^(1\/2) dif x\ $积分部分可以看作是 $alpha$ 的函数 $F(alpha) equiv integral_0^(infinity) ln(1-e^(-alpha-x)) x^(1\/2) dif x$,有热力学量:$ cases( display(macron(N) &= - diff/(diff alpha) ln Xi = (2 pi V)/h^3 ((2m)/beta)^(3\/2) F'(alpha) = V/lambda_T^3 g_(3\/2)(z)), display(U &= - diff/(diff beta) ln Xi = (3/2 1/beta) (2 pi V)/(h^3) F(alpha) = (- F(alpha)/(F'(alpha))) 3/2 N k T = 3/2 k T V/lambda_T^3 g_(5\/2)(z)), display(p &= 1/beta diff/(diff V) ln Xi = -(2pi)/h^3 ((2m)/beta)^(3\/2) F(alpha) = (-F(alpha)/(F(alpha))) (N k T)/V = 1/(beta lambda_T^3)g_(5\/2)(z)), ) $<bose-gas>其中热波长 $lambda_T equiv h\/(2 pi m k T)^(1\/2)$,逸度 (_fugacity_) $z equiv e^(-alpha)$ 。取一阶小量近似( #text(red)[\#TODO过程略])可以得到:$ U = 3/2 N k T (1 - (n lambda^3)/(4 sqrt(2))) \ p = n k T (1 - (n lambda^3)/(4 sqrt(2))) $ ==== 弱简并理想_Fermi_气体 计算过程与弱简并理想_Bose_气体相同,直接给出结果:$ U = 3/2 N k T (1 + (n lambda^3)/(4 sqrt(2))) \ p = n k T (1 + (n lambda^3)/(4 sqrt(2))) $ ==== 统计关联 对比上述两个结果,我们可以看到$ U/(3/2 N k T) = (p V)/(N k T) = approx (1 plus.minus (n lambda^3)/(4 sqrt(2))) quad cases( display(-\, quad)#[弱简并理想_Bose_气体], display(+\, quad)#[弱简并理想_Fermi_气体] ) $ #colorbox( title: [统计关联], color: "blue", radius: 5pt, width: auto )[ #set list(indent: .5em) - 弱简并条件下 $e^alpha gt 1$,气体内能与体积也有关系; - 修正项 $display(plus.minus (n lambda^3)/(4 sqrt(2)))$ 是粒子的全同性导致的,全同粒子波函数相互交叠产生*统计关联*; - 可以将附加项等效为势能(与体积和距离有关) - 弱简并理想_Bose_气体统计关联表现为吸引力($-$);弱简并理想_Fermi_气体统计关联表现为排斥力($+$)。 ] === 强简并理想气体 上面已经讨论过非简并 ($e^alpha gt.double 1$)和弱简并 ($e^alpha gt 1$)的情况,现在讨论强简并条件 ($e^alpha gt.tilde 1$) 下的理想气体。 ==== 强简并理想_Bose_气体与_Bose-Einstein_凝聚 由 @bose-gas :$ N = V/(lambda_T^3) g_(3\/2)(z) = V/h^3 (2 pi m k T)^(3\/2) g_(3\/2)(z)\ g_(3\/2)(z) equiv sum_(lambda = 1)^(infinity) z^lambda/lambda^(3\/2) = z + 1/2^(3\/2) z^2 + 1/3^(3\/2) z^3 + dots.c $级数 $g_(3\/2)(z)$ 存在最大值 $g_(3\/2)(1)=gamma(3\/2)$,给定 $N, V$,当温度 $T$ 下降时该级数会增加,必存在一个温度 $T_c$ 使得:$ N = V/h^3 (2 pi m k T_c)^(3\/2) g_(3\/2)(1) $即:$ T_c = h^2/(2 pi m k)[n/(g_(3\/2)(1))]^(2\/3) $当温度低于 $T_c$ 时等式不成立,这是由于对弱简并理想_Bose_气体的计算中从能级求和到相体积元的近似中有 $D(0) = 0$,忽略掉了基态能级 $epsilon_0 = 0$ 的贡献,当 $T lt T_c$ 时处于基态的粒子数量无法忽略(产生凝聚现象)。我们只需要将基态 $epsilon=0$ 的这一项作为修正加回来就可以了:$ ln Xi &= - sum_lambda g_lambda ln (1- e^(-alpha-beta epsilon_lambda))\ &= -ln(1-e^(-alpha)) - sum_(epsilon_lambda gt.eq epsilon_1) g_lambda ln(1-e^(-alpha-beta epsilon_lambda))\ &= -ln(1-e^(-alpha)) - integral_(epsilon_1)^(infinity) ln(1-e^(-alpha-beta epsilon)) dif epsilon\ &= -ln(1-e^(-alpha)) - integral_(0)^(infinity) ln(1-e^(-alpha-beta epsilon)) dif epsilon\ &= -ln(1-z) + V/lambda_T^3 g_(5\/2) (z) $逸度 $z equiv e^(-alpha)$,热波长 $lambda_T = h\/sqrt(2 pi m k T)$,总粒子数有:$ &N = - diff/(diff alpha) ln Xi = z diff/(diff z)ln Xi = macron(N_0) + macron(N)_(op("exc"))\ &macron(N_0) = - z diff/(diff z) ln(1-z) = z/(1-z)\ &macron(N)_(op("exc")) = V/lambda_T^3 g_(3\/2)(z) = V/h^3 (2 pi m k T)^(3\/2) g_(3\/2)(z) $其中 $macron(N)_0$ 和 $macron(N)_(op("exc"))$ 分别为基态和所有激发态上占据的粒子数。 #grid( columns: 2, gutter: 5pt, box(width: 100%)[ 当 $T lt.eq T_c$ 时,有:$ cases( display(N_op("exc")/N = (T/T_c)^(3\/2)), display(N_0/N = 1 - (T/T_c)^(3\/2)) ) $如右图所示,_BEC_ 的能量、动量、熵和压强均为 $0$。实际上是从非零动量态转变到零动量态,是一种动量空间中的“凝聚”;_BEC_发生凝聚的相互作用力来源于量子统计效应。 ], box(width: 100%)[ #figure( image("../../assets/figures/BEC.svg",width: 80%), caption: [*_Bose-Einstein_凝聚*:当 $T lt T_c$ 时会在基态上凝聚宏观量级的粒子] ) ] ) ==== 强简并理想_Fermi_气体(金属中的自由电子气) 强简并理想_Fermi_气体满足 $e^alpha lt.double 1$,我们来研究金属中的自由电子气体,这种电子气满足:自旋 $s = 1\/2$,无外磁场时两个取向的能量相等,所以计算态密度 $D(epsilon)$ 时记得乘上因子 $2$。计算巨配分函数$ ln Xi &= (sum_lambda g_lambda) ln(1+e^(-alpha-beta epsilon_lambda)) = integral (dif omega)/h^3 ln(1+e^(-alpha-beta epsilon_lambda)) \ &= integral_0^infinity D(epsilon) ln(1+e^(-alpha-beta epsilon_lambda)) dif epsilon\ &= (4 pi V)/h^3 (2m)^(3\/2) integral_0^infinity ln(1+e^(-alpha-beta epsilon_lambda)) epsilon^(1\/2) dif epsilon $热力学量使用_Fermi_分布函数 $f_lambda = macron(a_lambda)\/g_lambda = sum_lambda 1\/(e^(alpha+beta epsilon_lambda)+1)$ 来表示:$ N = - diff/(diff alpha) ln Xi = sum_lambda 1/(e^(alpha+beta epsilon_lambda)+1) = sum_lambda f_lambda = integral_0^infinity f(epsilon) D(epsilon) dif epsilon\ U = - diff/(diff beta) ln Xi = sum_lambda epsilon_lambda/(e^(alpha+beta epsilon_lambda)+1) = sum_lambda epsilon_lambda f_lambda = integral_0^infinity epsilon f(epsilon) D(epsilon) dif epsilon\ $我们重点考虑 $T = 0 K$ 时电子气的性质,令 $mu(0)$ 为 $T = 0 K$ 时电子气的化学势能,有:$ f(epsilon) = 1/(e^((epsilon - mu)\/k T) + 1) = cases( display(1\, quad epsilon lt mu(0)), display(0\, quad epsilon gt mu(0)) ) $#text(red)[即 $mu(0)$ 是 $T=0K$ 时电子可占据的最大能级,我们把 $mu(0)$ 叫做_Fermi_能级],记作 $epsilon_F = mu_0$。通过重整化可以确定_Fermi_能级:$ N &= integral_0^infinity f(epsilon) D(epsilon) dif epsilon = integral_0^(epsilon_F) D(epsilon) dif epsilon\ &= integral_0^(epsilon_F) 2 times (2 pi V)/h^3 (2m)^(3\/2) epsilon^(1\/2) dif epsilon\ $进而得到:$ (8 pi V)/3 ((2m)/h^2)^(3\/2) epsilon_F^(3\/2) = N $另外定义*费米动量* $p_F$ 满足 $epsilon_F = p_F^2\/2m$,于是得到:$ epsilon_F = h^2/(2m) (3 pi^2 n)^(2\/3)\ p_F = hbar (3 pi ^2 n)^(1\/3) $有 $T=0K$ 时电子气体的内能:$ U(0) = integral_0^infinity epsilon f(epsilon) D(epsilon) dif epsilon = (4 pi V)/h^3 (2m)^(3\/2) integral_0^epsilon_F epsilon^(3\/2) dif epsilon = 3/5 N epsilon_F $对于非相对论性粒子,压强满足:$ p(0) = 2/3 U(0)/V = 2/5 n epsilon_F $ $T > 0K$ 时 #text(red)[\#TODO]
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/README.md
markdown
Apache License 2.0
# [Metro](https://github.com/fenjalien/metro) The Metro package aims to be a port of the Latex package siunitx. It allows easy typesetting of numbers and units with options. This package is very early in development and many features are missing, so any feature requests or bug reports are welcome! Metro’s name comes from Metrology, the study scientific study of measurement. **Bug reports, feature requests, and PRs are welcome!** ## Usage Requires Typst v0.11.0+. Use Typst's package manager: ``` #import "@preview/metro:0.3.0": * ``` You can also download the `src` folder and import `lib.typ` and import: ``` #import "src/lib.typ": * ``` See the manual for more detailed information: [manual.pdf](https://github.com/fenjalien/metro/releases/latest/download/manual.pdf) ## Future Features (in no particular order) - [x] Angles - [x] Complex numbers - [x] Ranges, lists and products - [ ] table extensions? - [ ] Number parsing - [ ] Uncertainties - [x] Exponents - [x] Number post-processing - [x] rounding - [x] exponent modes
https://github.com/coljac/typst-dnd5e
https://raw.githubusercontent.com/coljac/typst-dnd5e/main/example/example.typ
typst
MIT License
#import "lib.typ": * #show: dndmodule.with( title: "A Date with Destiny", subtitle: "A one-shot adventure for 4 players of levels 1-4 - with dinosaurs", author: "<NAME>", cover: image("img/party.png", height: 100%), paper: "a4", logo: image("img/GenericLogo.png", width: 13%), fancy_author: true ) #outline(title: "Table of Contents\n") #colbreak() #heading(outlined: false, level: 1)[Credits] *Designer* <NAME> *Template* <NAME> *Illustrations* Some artists #lorem(25) #pagebreak() = Adventure awaits! #dnd#super("TM") is a role playing game. #lorem(180) OK! == A location #lorem(233) == A hook #lorem(233) === This person #lorem(45) === That person #lorem(85) #dndtab("Random occurences", [*d10*], [*Result*], [1], [A tingling in the extremities], [2-8], [Nothing interesting occurs], [10], [All the PCs burst into flame]) #lorem(150) *And now we want a page with a big image at the top.* #pagewithfig(top, image("img/dragongold.png", width: 120%))[ And here it is. #lorem(100) = More things! #lorem(204) #lorem(115) ] #pagewithfig(bottom, image("img/swordtorn.png", width: 120%))[ And more here! #breakoutbox("Look here!")[#lorem(44)] #lorem(390) ] // #lorem(402) #breakoutbox("Something to note")[#lorem(133)] #lorem(300) #statbox(( name: "Monster", description: [Large monstrosity, neutral evil], ac: [20 (natural armor)], hp: [29 (1d10 + 33)], speed: [10ft, climb 10ft.], stats: (STR: 13, DEX: 14, CON: 18, INT: 5, WIS: 4, CHA: 7), skillblock: ( Skills: [Perception +6, Stealth +5], Senses: [darkvision 60ft, passive Perception 13], Languages: [-], Challenge: [5 (1800 XP)] ), traits: ( ("Scary Appearance", [While the monster is being ferocious, enemies are at -2 to all WIS saving throws.]), ("Reaching Tentacles", [The monster has six slimy tentacles. Each tentacle can be attacked (AC 20; 10 hit points; immune to psychic damage). Destroying a tentacle makes the monster angry.]) ), Actions: ( ("Multiattack", [While the monster remains alive, it is a thorn in the party's side.]), ("Saliva", [If a character is eaten by the monster, it takes 1d10 saliva damage per round.]), ("Tentacle squeeze", [If the monster has captured an enemy, it can squeeze them for 1d12 crushing damage.]) ) )) == A monster #lorem(200) = Spells #spell(( name: "<NAME>", spell_type: [2nd level evocation], properties: ( ("Casting time", [Special]), ("Range", [Self]), ("Duration", [Until long rest]), ("Components", [V, S]), ), description: [Your legs start dancing, and you dance compulsively, and in an experimental fashion. #lorem(20)] ) ) #spell(( name: "<NAME>", spell_type: [2nd level evocation], properties: ( ("Casting time", [Special]), ("Range", [Self]), ("Duration", [Until long rest]), ("Components", [V, S]), ), description: [Your legs start dancing, and you dance compulsively, and in an experimental fashion. #lorem(20)] ) )
https://github.com/JanEhehalt/typst-demo
https://raw.githubusercontent.com/JanEhehalt/typst-demo/main/main.typ
typst
//#import "@preview/exzellenz-tum-thesis:0.1.0": exzellenz-tum-thesis #import "utils.typ": inwriting, draft, todo #import "glossary.typ": glossary #import "@preview/glossarium:0.2.6": make-glossary, print-glossary, gls, glspl #show: make-glossary // Global Settings // #set text(lang: "en", size: 12pt) #set text(ligatures: false) #set text(font: "Times New Roman") // Set numbering mode #set page(numbering: "1") #set math.equation(numbering: "(1)") #set heading(numbering: "1.1") // Set fonts #set text(font: "Times New Roman") #show raw: set text(font: "Times New Roman") #show math.equation: set text(font: "Times New Roman") // Set font size #show heading.where(level: 3): set text(size: 1.05em) #show heading.where(level: 4): set text(size: 1.0em) #show figure: set text(size: 0.9em) // Set spacing #set par(leading: 0.9em, first-line-indent: 1.8em, justify: true) #show par: set block(spacing: 1em) #set table(inset: 6.5pt) #show table: set par(justify: false) #show figure: it => [#v(1em) #it #v(1em)] #show heading.where(level: 1): set block(above: 1.95em, below: 1em) #show heading.where(level: 2): set block(above: 1.85em, below: 1em) #show heading.where(level: 3): set block(above: 1.75em, below: 1em) #show heading.where(level: 4): set block(above: 1.55em, below: 1em) // Pagebreak before level 1 headings #show heading.where(level: 1): it => [ #pagebreak(weak: true) #it ] // Names for headings #set heading(supplement: it => { if (it.has("level")) { if it.level == 1 [Part] else if it.level == 2 [Chapter] else [Section] } else { [ERROR, this should not happen] } }) // Set citation style #set cite(style: "alphanumeric") // Table stroke #set table(stroke: 0.5pt + black) // show reference targets in brackets #show ref: it => { let el = it.element if el != none and el.func() == heading { [#it (#el.body)] } else [#it] } // color links and references //#show ref: set text(fill: color.blue) //#show link: set text(fill: color.blue) // style table-of-contents #show outline.entry.where( level: 1 ): it => { strong(it) } // Draft Settings // #show cite: set text(fill: black) if inwriting #show footnote: set text(fill: black) if inwriting #set cite(style: "chicago-author-date") if inwriting // ------ Deckblatt ------ #include "Deckblatt.typ" // ------ Content ------ // Table of contents. #outline( title: { text(1.3em, weight: 700, "Content") v(10mm) }, indent: 2em, depth: 3 ) #pagebreak(weak: false) // --- Chapters --- #include "Chapter_Introduction.typ" // --- Appendixes --- // restart page numbering using roman numbers //#set page(numbering: "i") //#counter(page).update(1) #include("Chapter_Appendix.typ") // List of Acronyms. #heading(numbering: none)[List of Acronyms] #print-glossary(glossary) // List of figures. #heading(numbering: none)[List of Figures] #outline( title: none, target: figure.where(kind: image), ) // List of tables. #heading(numbering: none)[List of Tables] #outline( title: none, target: figure.where(kind: table) ) // KI Verzeichnis #heading(numbering: none)[KI-Verzeichnis] #include "KI-Verzeichnis.typ" // --- Bibliography --- #set par(leading: 0.7em, first-line-indent: 0em, justify: true) #bibliography("items.bib", style: "ieee")
https://github.com/ahxt/typst-TMLR
https://raw.githubusercontent.com/ahxt/typst-TMLR/main/tmlr.typ
typst
// The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let tiny = 5pt #let scriptsize = 7pt #let footnotesize = 8pt #let small = 9pt #let normalsize = 10pt #let large = 12pt #let Large = 14.4pt #let LARGE = 17.28pt #let huge = 20.74pt #let Huge = 24.88pt #let tmlr( title: "", abstract: [], authors: (), body, type: "accepted", month: "05", year: "2023", bibliography-file: none, ) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set page(paper: "us-letter", numbering: "1", number-align: center, header-ascent: 14pt, header: locate(loc => { set text(size: normalsize) let header_text = "Published in Transactions on Machine Learning Research" if type == "preprint" { header_text = "Preprint" } if type == "accepted" { header_text = "Published in Transactions on Machine Learning Research" } if type == "submission" { header_text = "Under review as submission to TMLR" } grid( columns: (1fr), align(left, header_text), v(4pt), line(length: 100%, stroke: 0.6pt) ) }), // On the first page, the footer should contain the page number. footer-descent: 12pt, footer: locate(loc => { let i = counter(page).at(loc).first() if i == 1 { align(center, text(size: scriptsize, [#i])) } }) ) set text(font: "New Computer Modern", lang: "en") show math.equation: set text(weight: 400) set heading(numbering: "1.1 ") show heading: it => { // Create the heading numbering. let number = if it.numbering != none { counter(heading).display(it.numbering) h(7pt, weak: true) } // Level 1 headings are centered and smallcaps. // The other ones are run-in. set text(size: large, weight: 1000, font: "New Computer Modern Sans") set align(left) smallcaps[ #v(24pt, weak: true) #number #it.body #v(large, weak: true) ] } // Configure citation and bibliography styles. set bibliography(style: "icml.csl", title: "References") // institute-of-electrical-and-electronics-engineers // springer-basic // alphanumeric // icml.csl // Title row. v(30pt) align(left)[ #block(text(weight: 1000, size: LARGE, font: "New Computer Modern Sans", title)) #v(1em, weak: true) ] v(35pt, weak: true) // Author information. pad( top: 0.5em, bottom: 0.8em, // x: 2em, grid( columns: (1fr), gutter: 2em, ..authors.map(author => align(left)[ *#author.name* #h(1fr) #emph(author.email) \ #emph(author.affiliation) ]), ), ) // Main body. set par(justify: true) align(center, text(size: large, font: "New Computer Modern Sans", weight: 1000, [Abstract])) // align(center)[ // #heading(outlined: false, numbering: none, text(1.2em, [Abstract])) // ] pad( top: 0.1em, bottom: 0.8em, x: 3em, y: 3em, abstract ) body // Display the bibliography, if any is given. if bibliography-file != none { // show bibliography: set text(8.5pt) // show bibliography: pad.with(x: 0.5pt) bibliography(bibliography-file) } }
https://github.com/dogeystamp/typst-templates
https://raw.githubusercontent.com/dogeystamp/typst-templates/master/libs.typ
typst
The Unlicense
#import "/templates/main.typ": settings, font #import "@preview/unify:0.5.0": num, qty, unit // percentage error quantity // (because both unify and metro currently can't parse percentages) #let pq(nb, un, pe) = { return $(num(nb) plus.minus qty(pe, "%")) unit(un)$ } // chemistry #import "@preview/whalogen:0.1.0": ce // this used to be an alias to styled tablex #let tablef = table.with( align: center + horizon, stroke: (x: none, y: 0.1em), inset: (y: 0.75em) ) #let appendices(body) = { // https://github.com/typst/typst/issues/806 pagebreak() counter(heading).update(0) counter("appendices").update(1) text(size: 18pt, weight: "black", "Appendices", font: font ) v(8pt) line(length: 100%, stroke: 1pt + rgb("#555555")) v(5%, weak: true) set heading(numbering: (..nums) => { let vals = nums.pos() let value = "ABCDEFGHIJ".at(vals.at(0) - 1) if vals.len() == 1 { if settings.lang == "fr" { return "Appendice " + value + ":" } else if settings.lang == "en" { return "Appendix " + value + ":" } } else { return value + "." + nums.pos().slice(1).map(str).join(".") } }) set heading(supplement: "Appendice") if settings.lang == "fr" set heading(supplement: "Appendix") if settings.lang == "en" body } #let numbered_eq = (body) => { set math.equation(numbering: "(1)") body } // theorems, definitions, example environments #import "@preview/ctheorems:1.1.2": * // use `#show: thmrules` at the beginning of documents #let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee")) #let corollary = thmplain( "corollary", "Corollary", base: "theorem", titlefmt: strong ) #let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em, bottom: 1em), stroke: 1pt + black) #let example = thmbox("example", "Example").with(numbering: none) #let proof = thmproof("proof", "Proof")
https://github.com/gabrielluizep/typst-ifsc
https://raw.githubusercontent.com/gabrielluizep/typst-ifsc/main/README.md
markdown
Creative Commons Zero v1.0 Universal
<p align="center"> <img src="assets/ifsc-v.png" width="100px" align="center"> </p> --- # typst-ifsc Repositório arquivado em favor da metodologia de templates do Typst. Agora é possível importalos com a função `import` (e.g `#import "@preview/klaro-ifsc-sj:0.1.0": *`). Códigos distribuídos em: - [klaro-ifsc-sj](https://github.com/gabrielluizep/cyan-ifsc-sj) (Relatório) - [cyan-ifsc-sj](https://github.com/gabrielluizep/cyan-ifsc-sj) (Apresentações)
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/qr/src/qr.typ
typst
#let lib = plugin("qr.wasm") /// Create a QR code from the given data. /// /// Arguments: /// - format: The format of the image. Must be one of "png" or "svg". Default: "svg". /// - margin: The margin around the QR code in units of modules. Default: 4. /// - fill: The color of the QR code. Default: black. /// - image-args: Additional arguments to pass to the image constructor. /// - data: The data to encode. Must be of type array, bytes, or string. /// /// Returns: The QR code as an image. #let create( format: "svg", margin: 4, fill: black, ..image-args, data ) = { if margin == none { margin = 0 } // We can only pass byte arrays to the WASM module. // To keep things simple, we limit it to one byte. assert(0 <= margin and margin <= 255, message: "margin must be between 0 and 255") assert(format in ("png", "svg"), message: "format must be either \"png\" or \"svg\"") assert(type(fill) == color, message: "fill must be a color") let qr-args = ( bytes(data), bytes((margin,)), bytes(rgb(fill).components().map(ratio => int(ratio/100% * 255))) ) let image-data = if format == "png" { lib.png(..qr-args) } else { str(lib.svg(..qr-args)) } image.decode( image-data, format: format, ..image-args ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.5.2/tests/edge-loops/test.typ
typst
Apache License 2.0
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #diagram( node((0,0), [Loop], shape: circle, fill: eastern), edge((0,0), "->", (0,0), bend: 120deg, layer: 2, loop-angle: 0deg), edge((0,0), "->", (0,0), bend: 120deg, layer: 2, loop-angle: 90deg), edge((0,0), "->", (0,0), bend: 120deg, layer: 2, loop-angle: 180deg), edge((0,0), "->", (0,0), bend: 120deg, layer: 2, loop-angle: 270deg), node((1,0), [Boop], shape: circle, fill: orange.mix(red)), edge((), (), "->", bend: 120deg, layer: 2, loop-angle: -135deg), edge((), (), "->", bend: 120deg, layer: 2, loop-angle: -45deg), edge((), (), "->", bend: 120deg, layer: 2, loop-angle: +45deg), edge((), (), "->", bend: 120deg, layer: 2, loop-angle: +135deg), )
https://github.com/luiswirth/numpde-slides
https://raw.githubusercontent.com/luiswirth/numpde-slides/main/src/week01.typ
typst
#import "setup.typ": * #show: this-template #let pathemph(a, b) = [ #text(fill: white.darken(60%))[#a]#b ] #titleslide("01") #pagebreak() #githubref #pagebreak() = Important links #v(1cm) NPDE Repo https://gitlab.math.ethz.ch/ralfh/NPDERepo \ CPP reference: https://en.cppreference.com/ \ Eigen documentation https://eigen.tuxfamily.org \ LehrFEM++ docs https://craffael.github.io/lehrfempp/ \ ( LehrFEM++ repo https://github.com/craffael/LehrFEMpp ) \ #pagebreak() = Setup / Problem 0-1 #v(1cm) We'll be now basically solving Problem 0-1 from the homework PDF. \ Which is setting up the lecture repository. Use a unix operating system: Linux or MacOS. There is no Code Expert, you'll have to solve the exercises locally on your computer. #pagebreak() == SSH setup #v(1cm) Check if you already have an SSH key already. \ ```sh ls ~/.ssh ``` Look for a filename that begins with `id`. #v(1cm) If you don't already have one: \ Generate a SSH public-private-keypair and add it to the SSH agent. ```sh ssh-keygen -t ed25519 -C "<EMAIL>" eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 ``` #v(1.0cm) Add #emph[public] key (named `id_*.pub`) to #link("gitlab.math.ethz.ch"). #pagebreak() = Cloning and CMake #v(1cm) Clone the NumPDE repository from the D-MATH GitLab. ```sh git clone <EMAIL>:ralfh/NPDERepo.git ``` Run CMake. ```sh cd NPDERepo mkdir build cmake -B build ``` #v(0.5cm) ...This will take a while, because the hunter package manager now fetches all dependencies (LehrFEM++, boost, GoogleTest, etc.) and builds them. In the meantime... #pagebreak() == Structure of NPDERepo: Source Code #v(1cm) We basically only care about the #pathemph(`NPDERepo/`, `homework`) folder. \ This is where we find the source code for all code problems. In each specific problem folder, there are these directories - #pathemph(`NPDERepo/homework/`, `<problem>/template`) - #pathemph(`NPDERepo/homework/`, `<problem>/mysolution`) - #pathemph(`NPDERepo/homework/`, `<problem>/mastersolution`) Only modify `mysolution`, nothing else. #pagebreak() == Structure of NPDERepo: Build Folder #v(0.3cm) For compiling and executing we use the #pathemph(`NPDERepo/`, `build`) folder. There we also find a #pathemph(`NPDERepo/build/`, `homework`) folder, which mirrors the structure of the source code homework folder. Inside we can compile a specific problem. \ e.g. - ```sh make DebuggingWithGDB_mastersolution``` - ```sh make DebuggingWithGDB_mysolution``` - ```sh make DebuggingWithGDB_test_mysolution``` The executables are then found in the corresponding problem build folder. \ e.g. - #pathemph(`NPDERepo/build/homework/`, `DebuggingWithGDB/DebuggingWithGDB_mastersolution`) - #pathemph(`NPDERepo/build/homework/`, `DebuggingWithGDB/DebuggingWithGDB_mysolution`) - #pathemph(`NPDERepo/build/homework/`, `DebuggingWithGDB/DebuggingWithGDB_test_mysolution`) #pagebreak() == VSCode setup #v(1cm) Extensions needed - C++ - clangd - CMake - CMake Tools - CodeLLDB #v(1cm) Let's edit the .gitignore. We should ignore the cache files generated by clangd and others. \ Add this line ``` .cache/ ``` #pagebreak() == Can we commit and push? #v(1cm) No. We don't have rights to push on this repository. \ Solution: Your own fork (remote copy of repository with you own). Usually this is really easy: Fork button in GitLab. \ But unfortunatly students have no right to create repository on D-MATH GitLab. \ The fork button is grayed out. We need to create the fork manually... #pagebreak() == Forking repository (manually) #v(1cm) Create new repository under #link("gitlab.ethz.ch/<nethz>/NPDERepo"). Setup original repository as `upstream` and your fork as `origin`. ```sh git remote -m origin upstream git remote add origin <EMAIL>:<nethz>/NPDERepo.git git push --set-upstream origin ``` #pagebreak() == Using your fork #v(1cm) Create and switch to your own branch. ```sh git switch -c <nethz> ``` Only commit on your own branch. Do not modify master branch. If there's a change on the original repository, then Bring you branch up-to-date with upstream. ```sh git stash git switch master git fetch upstream git rebase upstream/master git switch <nethz> git rebase master git stash apply ```
https://github.com/SillyFreak/tu-wien-software-engineering-notes
https://raw.githubusercontent.com/SillyFreak/tu-wien-software-engineering-notes/main/optimizing-compilers/oc/lattices.typ
typst
#import "@preview/commute:0.2.0": node, arr, commutative-diagram #let Carrier = $cal(C)$ #let Lattice(carrier) = $accent(carrier, hat)$ // TODO manual kerning for calligraphy letters #let FL = $cal("F")#h(-0.22em)cal("L")$ #let rel = $subset.eq.sq$ #let meet = $sect.sq$ #let Meet = $sect.sq.big$ #let join = $union.sq$ #let Join = $union.sq.big$ $ Lattice(Carrier) = (Carrier, rel, meet, join, bot, top) \ Meet {c_1, ..., c_k} = c_1 meet ... meet c_k \ Join {c_1, ..., c_k} = c_1 join ... join c_k $ #let hasse-boolean = commutative-diagram( node-padding: (28pt, 28pt), // arr-clearance: 1em, node((0, 0), [$t$]), node((1, 0), [$f$]), arr((1, 0), (0, 0), []), ) #figure( caption: [Hasse diagram of $Lattice(BB)$], hasse-boolean ) #let hasse-boolean-inv = commutative-diagram( node-padding: (28pt, 28pt), // arr-clearance: 1em, node((0, 0), [$f$]), node((1, 0), [$t$]), arr((1, 0), (0, 0), []), ) #figure( caption: [Hasse diagram of $Lattice(BB_or)$], hasse-boolean-inv ) #let hasse-flat-boolean = commutative-diagram( node-padding: (28pt, 28pt), arr-clearance: 1em, node((0, 1), [$top$]), node((1, 0), [$f$]), node((1, 2), [$t$]), node((2, 1), [$bot$]), arr((2, 1), (1, 0), []), arr((2, 1), (1, 2), []), arr((1, 0), (0, 1), []), arr((1, 2), (0, 1), []), ) #figure( caption: [Hasse diagram of $FL_BB$], hasse-flat-boolean ) #let hasse-flat-integers(breadth) = { let min = -breadth let count = breadth*2 + 1 let middle = breadth + 1 let right = count + 1 commutative-diagram( node-padding: (20pt, 28pt), // arr-clearance: 0.5em, node((0, middle), [$top$]), node((1, 0), [$...$]), ..range(0, count).map((i) => ( node((1, i+1), [$#(min + i)$]), arr((1, i+1), (0, middle), []), arr((2, middle), (1, i+1), []), )).flatten(), node((1, right), [$...$]), node((2, middle), [$bot$]), ) } #figure( caption: [Hasse diagram of $FL_ZZ$], hasse-flat-integers(2) ) #figure( caption: [Hasse diagram of $FL_ZZ$], hasse-flat-integers(3) )
https://github.com/GYPpro/DS-Course-Report
https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Rep/20.typ
typst
#import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx #import "@preview/codelst:2.0.1": sourcecode // Display inline code in a small box // that retains the correct baseline. #set text(font:("Times New Roman","Source Han Serif SC")) #show raw: set text( font: ("consolas", "Source Han Serif SC") ) #set page( paper: "a4", ) #set text( font:("Times New Roman","Source Han Serif SC"), style:"normal", weight: "regular", size: 13pt, ) #let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()] #set math.equation(numbering: "(1)") #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) #set math.equation(numbering: "(1)") /*----*/ #pagebreak() #[ #set text( font:("Times New Roman","Source Han Serif SC"), style:"normal", weight:"regular", size: 22pt, ) #[ #set align( left+horizon ) #heading(outlined: false,level: 1)[附录与参考资料] #smallcaps[Appendix and References] #line(start: (0pt,11pt),end:(300pt,11pt)) #[ ] ] ] // = 附录与参考资料 #set page( paper:"a4", number-align: right, margin: (x:2.54cm,y:4cm), header: [ #set text( size: 25pt, font: "KaiTi", ) #align( bottom + center, [ #strong[暨南大学本科实验报告专用纸(附页)] ] ) #line(start: (0pt,-5pt),end:(453pt,-5pt)) ] ) #pagebreak() == 生成每份报告基础格式的python代码: ```py import os def load_typ_file(rep_dir): typ_file_path = os.path.join(rep_dir, 'template.typ') with open(typ_file_path, 'r') as file: typ_content = file.read() return typ_content def read_dev_files(dev_dir): file_data = {} for subdir, _, files in os.walk(dev_dir): for file_name in files: if file_name.endswith(('.cpp', '.h', '.hpp')): file_path = os.path.join(subdir, file_name) with open(file_path, 'r') as file: content = file.read() file_data[file_path] = content return file_data def read_dev_files(dev_dir): all_data = {} for subdir, _, files in os.walk(dev_dir): subdir_data = {} for file_name in files: if file_name.endswith(('.cpp', '.h', '.hpp')): file_path = os.path.join(subdir, file_name) with open(file_path, 'r') as file: content = file.read() subdir_data[file_name] = content if subdir_data: all_data[subdir] = subdir_data return all_data import re def split_text(text): pattern = r'/\*.*\*/' matches = re.findall(pattern, text, re.DOTALL) if matches: last_match = matches[-1] remaining_text = text.replace(last_match, '', 1) last_match = last_match.replace("/*","") last_match = last_match.replace("*/","") return remaining_text, last_match else: return text,"" s = ''' rowspanx(8)[STL风格的\ 泛型的\ 基础数据结构\ 容器实现],[1],[基于双向链表的`linkedList`], (),[2],[基于增长数组的`vector`], (),[3],[基于块状数组的`dataBlock`], (),[4],[实现基于循环增长数组的`deque`], (),[5],[基于`vector`实现`stack`], (),[10],[基于R-BTree实现`set`], (),[11],[基于R-BTree实现`map`], (),[15],[基于Heap实现`priority_queue`], rowspanx(4)[基础树/图结构],[6],[树上dfs(基础信息)], (),[7],[图上bfs(最短路)], (),[8],[二叉树三序遍历], (),[9],[R-BTree的基本实现], rowspanx(4)[特殊结构\ 及其应用],[12],[字典树`Trie`], (),[13],[线段树`segTree`], (),[14],[堆`Heap`], (),[16],[霍夫曼树`Huffman-tree`], rowspanx(3)[在算法中应用],[17],[算数表达式求值(栈)], (),[18],[括号匹配(栈)], (),[19],[高精度计算], ''' t = s.split("\n"); m = {}; for x in t: text = "rowspanx(8)[STL风格的\\ 泛型的\\ 基础数据结构\\ 容器实现],[1],[基于双向链表的`linkedList`]" # 定义正则表达式模式 pattern = re.compile(r'\[([^\]]+)\]') matches = pattern.findall(x) m[int(matches[-2])] = matches[-1]; # print(matches) m rep_dir = 'Rep' dev_dir = 'Dev' # Load Rep/0.typ file template = load_typ_file(rep_dir) # print(f"Loaded 0.typ content:\n{typ_content}") # Read files in Dev subdirectories file_data = read_dev_files(dev_dir) # Print the loaded file names and content (for demonstration purposes) for file_path, sub_paths in file_data.items(): print(f"File: {file_path}") MAINCODE = "" COMMENTS = "" for sub_path,text in sub_paths.items(): code,comment = split_text(text); MAINCODE += "== `" + sub_path + "`\n" MAINCODE += "#sourcecode[```cpp\n" + code + "\n```]\n" if len(comment) > 0 : COMMENTS += "```\n" + comment + "\n```\n" subdir_name = os.path.basename(file_path); nt = template nt = nt.replace("MAINCODE",MAINCODE); nt = nt.replace("TESTCASES",COMMENTS); nt = nt.replace("maintitle",m[int(subdir_name)]) nt = nt.replace("INDEXS",subdir_name); # print(m[int(subdir_name)]) # if(int(subdir_name) <= 18): # continue rep_file_path = os.path.join(rep_dir, f"{subdir_name}.typ") f = open(rep_file_path,'w') f.write(nt) # print(rep_file_path); # print(f"Content:\n{content}") # print('-' * 80) ``` == 渲染报告用typst模板: ```typc #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx #import "@preview/codelst:2.0.1": sourcecode // Display inline code in a small box // that retains the correct baseline. #set text(font:("Times New Roman","Source Han Serif SC")) #show raw: set text( font: ("consolas", "Source Han Serif SC") ) #set page( paper: "a4", ) #set text( font:("Times New Roman","Source Han Serif SC"), style:"normal", weight: "regular", size: 13pt, ) #let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()] #set math.equation(numbering: "(1)") #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt, ) #set math.equation(numbering: "(1)") #set page( paper:"a4", number-align: right, margin: (x:2.54cm,y:4cm), header: [ #set text( size: 25pt, font: "KaiTi", ) #align( bottom + center, [ #strong[暨南大学本科实验报告专用纸(附页)] ] ) #line(start: (0pt,-5pt),end:(453pt,-5pt)) ] ) /*----*/ = maintitle \ #text( font:"KaiTi", size: 15pt )[ 课程名称#underline[#text(" 数据结构 ")]成绩评定#underline[#text(" ")]\ 实验项目名称#underline[#text(" ") maintitle #text(" ")]指导老师#underline[#text(" 干晓聪 ")]\ 实验项目编号#underline[#text(" INDEXS ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\ 学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\ 学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\ 实验时间#underline[#text(" 2024年6月13日上午 ")]#text("~")#underline[#text(" 2024年7月13日中午 ")]\ ] #set heading( numbering: "1.1." ) = 实验目的 = 实验环境 计算机:PC X64 操作系统:Windows + Ubuntu20.0LTS 编程语言:C++:GCC std20 IDE:Visual Studio Code = 程序原理 \ #pagebreak() = 程序代码 MAINCODE = 测试数据与运行结果 运行上述`_PRIV_TEST.cpp`测试代码中的正确性测试模块,得到以下内容: TESTCASES 可以看出,代码运行结果与预期相符,可以认为代码正确性无误。 ``` == 用作参考的RB_tree实现(CPP STL) ```cpp #ifndef RBTREE_MAP_HPP #define RBTREE_MAP_HPP #include <cassert> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <stack> #include <utility> #include <vector> template <typename Key, typename Value, typename Compare = std::less<Key> > class RBTreeMap { private: using USize = size_t; Compare compare = Compare(); public: struct Entry { Key key; Value value; bool operator==(const Entry &rhs) const noexcept { return this->key == rhs.key && this->value == rhs.value; } bool operator!=(const Entry &rhs) const noexcept { return this->key != rhs.key || this->value != rhs.value; } }; private: struct Node { using Ptr = std::shared_ptr<Node>; using Provider = const std::function<Ptr(void)> &; using Consumer = const std::function<void(const Ptr &)> &; enum { RED, BLACK } color = RED; enum Direction { LEFT = -1, ROOT = 0, RIGHT = 1 }; Key key; Value value{}; Ptr parent = nullptr; Ptr left = nullptr; Ptr right = nullptr; explicit Node(Key k) : key(std::move(k)) {} explicit Node(Key k, Value v) : key(std::move(k)), value(std::move(v)) {} ~Node() = default; inline bool isLeaf() const noexcept { return this->left == nullptr && this->right == nullptr; } inline bool isRoot() const noexcept { return this->parent == nullptr; } inline bool isRed() const noexcept { return this->color == RED; } inline bool isBlack() const noexcept { return this->color == BLACK; } inline Direction direction() const noexcept { if (this->parent != nullptr) { if (this == this->parent->left.get()) { return Direction::LEFT; } else { return Direction::RIGHT; } } else { return Direction::ROOT; } } inline Ptr &sibling() const noexcept { assert(!this->isRoot()); if (this->direction() == LEFT) { return this->parent->right; } else { return this->parent->left; } } inline bool hasSibling() const noexcept { return !this->isRoot() && this->sibling() != nullptr; } inline Ptr &uncle() const noexcept { assert(this->parent != nullptr); return parent->sibling(); } inline bool hasUncle() const noexcept { return !this->isRoot() && this->parent->hasSibling(); } inline Ptr &grandParent() const noexcept { assert(this->parent != nullptr); return this->parent->parent; } inline bool hasGrandParent() const noexcept { return !this->isRoot() && this->parent->parent != nullptr; } inline void release() noexcept { // avoid memory leak caused by circular reference this->parent = nullptr; if (this->left != nullptr) { this->left->release(); } if (this->right != nullptr) { this->right->release(); } } inline Entry entry() const { return Entry{key, value}; } static Ptr from(const Key &k) { return std::make_shared<Node>(Node(k)); } static Ptr from(const Key &k, const Value &v) { return std::make_shared<Node>(Node(k, v)); } }; using NodePtr = typename Node::Ptr; using ConstNodePtr = const NodePtr &; using Direction = typename Node::Direction; using NodeProvider = typename Node::Provider; using NodeConsumer = typename Node::Consumer; NodePtr root = nullptr; USize count = 0; using K = const Key &; using V = const Value &; public: using EntryList = std::vector<Entry>; using KeyValueConsumer = const std::function<void(K, V)> &; using MutKeyValueConsumer = const std::function<void(K, Value &)> &; using KeyValueFilter = const std::function<bool(K, V)> &; class NoSuchMappingException : protected std::exception { private: const char *message; public: explicit NoSuchMappingException(const char *msg) : message(msg) {} const char *what() const noexcept override { return message; } }; RBTreeMap() noexcept = default; ~RBTreeMap() noexcept { // Unlinking circular references to avoid memory leak this->clear(); } /** * Returns the number of entries in this map. * @return size_t */ inline USize size() const noexcept { return this->count; } /** * Returns true if this collection contains no elements. * @return bool */ inline bool empty() const noexcept { return this->count == 0; } /** * Removes all of the elements from this map. */ void clear() noexcept { if (this->root != nullptr) { this->root->release(); this->root = nullptr; } this->count = 0; } Value get(K key) const { if (this->root == nullptr) { throw NoSuchMappingException("Invalid key"); } else { NodePtr node = this->getNode(this->root, key); if (node != nullptr) { return node->value; } else { throw NoSuchMappingException("Invalid key"); } } } Value &getOrDefault(K key) { if (this->root == nullptr) { this->root = Node::from(key); this->root->color = Node::BLACK; this->count += 1; return this->root->value; } else { return this ->getNodeOrProvide(this->root, key, [&key]() { return Node::from(key); }) ->value; } } bool contains(K key) const { return this->getNode(this->root, key) != nullptr; } void insert(K key, V value) { if (this->root == nullptr) { this->root = Node::from(key, value); this->root->color = Node::BLACK; this->count += 1; } else { this->insert(this->root, key, value); } } bool insertIfAbsent(K key, V value) { USize sizeBeforeInsertion = this->size(); if (this->root == nullptr) { this->root = Node::from(key, value); this->root->color = Node::BLACK; this->count += 1; } else { this->insert(this->root, key, value, false); } return this->size() > sizeBeforeInsertion; } Value &getOrInsert(K key, V value) { if (this->root == nullptr) { this->root = Node::from(key, value); this->root->color = Node::BLACK; this->count += 1; return root->value; } else { NodePtr node = getNodeOrProvide(this->root, key, [&]() { return Node::from(key, value); }); return node->value; } } Value operator[](K key) const { return this->get(key); } Value &operator[](K key) { return this->getOrDefault(key); } bool remove(K key) { if (this->root == nullptr) { return false; } else { return this->remove(this->root, key, [](ConstNodePtr) {}); } } Value getAndRemove(K key) { Value result; NodeConsumer action = [&](ConstNodePtr node) { result = node->value; }; if (root == nullptr) { throw NoSuchMappingException("Invalid key"); } else { if (remove(this->root, key, action)) { return result; } else { throw NoSuchMappingException("Invalid key"); } } } Entry getCeilingEntry(K key) const { if (this->root == nullptr) { throw NoSuchMappingException("No ceiling entry in this map"); } NodePtr node = this->root; while (node != nullptr) { if (key == node->key) { return node->entry(); } if (compare(key, node->key)) { /* key < node->key */ if (node->left != nullptr) { node = node->left; } else { return node->entry(); } } else { /* key > node->key */ if (node->right != nullptr) { node = node->right; } else { while (node->direction() == Direction::RIGHT) { if (node != nullptr) { node = node->parent; } else { throw NoSuchMappingException( "No ceiling entry exists in this map"); } } if (node->parent == nullptr) { throw NoSuchMappingException("No ceiling entry exists in this map"); } return node->parent->entry(); } } } throw NoSuchMappingException("No ceiling entry in this map"); } Entry getFloorEntry(K key) const { if (this->root == nullptr) { throw NoSuchMappingException("No floor entry exists in this map"); } NodePtr node = this->root; while (node != nullptr) { if (key == node->key) { return node->entry(); } if (compare(key, node->key)) { /* key < node->key */ if (node->left != nullptr) { node = node->left; } else { while (node->direction() == Direction::LEFT) { if (node != nullptr) { node = node->parent; } else { throw NoSuchMappingException("No floor entry exists in this map"); } } if (node->parent == nullptr) { throw NoSuchMappingException("No floor entry exists in this map"); } return node->parent->entry(); } } else { /* key > node->key */ if (node->right != nullptr) { node = node->right; } else { return node->entry(); } } } throw NoSuchMappingException("No floor entry exists in this map"); } Entry getHigherEntry(K key) { if (this->root == nullptr) { throw NoSuchMappingException("No higher entry exists in this map"); } NodePtr node = this->root; while (node != nullptr) { if (compare(key, node->key)) { /* key < node->key */ if (node->left != nullptr) { node = node->left; } else { return node->entry(); } } else { /* key >= node->key */ if (node->right != nullptr) { node = node->right; } else { while (node->direction() == Direction::RIGHT) { if (node != nullptr) { node = node->parent; } else { throw NoSuchMappingException( "No higher entry exists in this map"); } } if (node->parent == nullptr) { throw NoSuchMappingException("No higher entry exists in this map"); } return node->parent->entry(); } } } throw NoSuchMappingException("No higher entry exists in this map"); } Entry getLowerEntry(K key) const { if (this->root == nullptr) { throw NoSuchMappingException("No lower entry exists in this map"); } NodePtr node = this->root; while (node != nullptr) { if (compare(key, node->key) || key == node->key) { /* key <= node->key */ if (node->left != nullptr) { node = node->left; } else { while (node->direction() == Direction::LEFT) { if (node != nullptr) { node = node->parent; } else { throw NoSuchMappingException("No lower entry exists in this map"); } } if (node->parent == nullptr) { throw NoSuchMappingException("No lower entry exists in this map"); } return node->parent->entry(); } } else { /* key > node->key */ if (node->right != nullptr) { node = node->right; } else { return node->entry(); } } } throw NoSuchMappingException("No lower entry exists in this map"); } void removeAll(KeyValueFilter filter) { std::vector<Key> keys; this->inorderTraversal([&](ConstNodePtr node) { if (filter(node->key, node->value)) { keys.push_back(node->key); } }); for (const Key &key : keys) { this->remove(key); } } void forEach(KeyValueConsumer action) const { this->inorderTraversal( [&](ConstNodePtr node) { action(node->key, node->value); }); } void forEachMut(MutKeyValueConsumer action) { this->inorderTraversal( [&](ConstNodePtr node) { action(node->key, node->value); }); } EntryList toEntryList() const { EntryList entryList; this->inorderTraversal( [&](ConstNodePtr node) { entryList.push_back(node->entry()); }); return entryList; } private: static void maintainRelationship(ConstNodePtr node) { if (node->left != nullptr) { node->left->parent = node; } if (node->right != nullptr) { node->right->parent = node; } } static void swapNode(NodePtr &lhs, NodePtr &rhs) { std::swap(lhs->key, rhs->key); std::swap(lhs->value, rhs->value); std::swap(lhs, rhs); } void rotateLeft(ConstNodePtr node) { assert(node != nullptr && node->right != nullptr); // clang-format on NodePtr parent = node->parent; Direction direction = node->direction(); NodePtr successor = node->right; node->right = successor->left; successor->left = node; maintainRelationship(node); maintainRelationship(successor); switch (direction) { case Direction::ROOT: this->root = successor; break; case Direction::LEFT: parent->left = successor; break; case Direction::RIGHT: parent->right = successor; break; } successor->parent = parent; } void rotateRight(ConstNodePtr node) { assert(node != nullptr && node->left != nullptr); // clang-format on NodePtr parent = node->parent; Direction direction = node->direction(); NodePtr successor = node->left; node->left = successor->right; successor->right = node; maintainRelationship(node); maintainRelationship(successor); switch (direction) { case Direction::ROOT: this->root = successor; break; case Direction::LEFT: parent->left = successor; break; case Direction::RIGHT: parent->right = successor; break; } successor->parent = parent; } inline void rotateSameDirection(ConstNodePtr node, Direction direction) { assert(direction != Direction::ROOT); if (direction == Direction::LEFT) { rotateLeft(node); } else { rotateRight(node); } } inline void rotateOppositeDirection(ConstNodePtr node, Direction direction) { assert(direction != Direction::ROOT); if (direction == Direction::LEFT) { rotateRight(node); } else { rotateLeft(node); } } void maintainAfterInsert(NodePtr node) { assert(node != nullptr); if (node->isRoot()) { // Case 1: Current node is root (RED) // No need to fix. assert(node->isRed()); return; } if (node->parent->isBlack()) { // Case 2: Parent is BLACK // No need to fix. return; } if (node->parent->isRoot()) { // clang-format off // Case 3: Parent is root and is RED // Paint parent to BLACK. // <P> [P] // | ====> | // <N> <N> // p.s. // `<X>` is a RED node; // `[X]` is a BLACK node (or NIL); // `{X}` is either a RED node or a BLACK node; // clang-format on assert(node->parent->isRed()); node->parent->color = Node::BLACK; return; } if (node->hasUncle() && node->uncle()->isRed()) { // clang-format off // Case 4: Both parent and uncle are RED // Paint parent and uncle to BLACK; // Paint grandparent to RED. // [G] <G> // / \ / \ // <P> <U> ====> [P] [U] // / / // <N> <N> // clang-format on assert(node->parent->isRed()); node->parent->color = Node::BLACK; node->uncle()->color = Node::BLACK; node->grandParent()->color = Node::RED; maintainAfterInsert(node->grandParent()); return; } if (!node->hasUncle() || node->uncle()->isBlack()) { // Case 5 & 6: Parent is RED and Uncle is BLACK // p.s. NIL nodes are also considered BLACK assert(!node->isRoot()); if (node->direction() != node->parent->direction()) { // clang-format off // Case 5: Current node is the opposite direction as parent // Step 1. If node is a LEFT child, perform l-rotate to parent; // If node is a RIGHT child, perform r-rotate to parent. // Step 2. Goto Case 6. // [G] [G] // / \ rotate(P) / \ // <P> [U] ========> <N> [U] // \ / // <N> <P> // clang-format on // Step 1: Rotation NodePtr parent = node->parent; if (node->direction() == Direction::LEFT) { rotateRight(node->parent); } else /* node->direction() == Direction::RIGHT */ { rotateLeft(node->parent); } node = parent; // Step 2: vvv } // clang-format off // Case 6: Current node is the same direction as parent // Step 1. If node is a LEFT child, perform r-rotate to grandparent; // If node is a RIGHT child, perform l-rotate to grandparent. // Step 2. Paint parent (before rotate) to BLACK; // Paint grandparent (before rotate) to RED. // [G] <P> [P] // / \ rotate(G) / \ repaint / \ // <P> [U] ========> <N> [G] ======> <N> <G> // / \ \ // <N> [U] [U] // clang-format on assert(node->grandParent() != nullptr); // Step 1 if (node->parent->direction() == Direction::LEFT) { rotateRight(node->grandParent()); } else { rotateLeft(node->grandParent()); } // Step 2 node->parent->color = Node::BLACK; node->sibling()->color = Node::RED; return; } } NodePtr getNodeOrProvide(NodePtr &node, K key, NodeProvider provide) { assert(node != nullptr); if (key == node->key) { return node; } assert(key != node->key); NodePtr result; if (compare(key, node->key)) { /* key < node->key */ if (node->left == nullptr) { result = node->left = provide(); node->left->parent = node; maintainAfterInsert(node->left); this->count += 1; } else { result = getNodeOrProvide(node->left, key, provide); } } else { /* key > node->key */ if (node->right == nullptr) { result = node->right = provide(); node->right->parent = node; maintainAfterInsert(node->right); this->count += 1; } else { result = getNodeOrProvide(node->right, key, provide); } } return result; } NodePtr getNode(ConstNodePtr node, K key) const { assert(node != nullptr); if (key == node->key) { return node; } if (compare(key, node->key)) { /* key < node->key */ return node->left == nullptr ? nullptr : getNode(node->left, key); } else { /* key > node->key */ return node->right == nullptr ? nullptr : getNode(node->right, key); } } void insert(NodePtr &node, K key, V value, bool replace = true) { assert(node != nullptr); if (key == node->key) { if (replace) { node->value = value; } return; } assert(key != node->key); if (compare(key, node->key)) { /* key < node->key */ if (node->left == nullptr) { node->left = Node::from(key, value); node->left->parent = node; maintainAfterInsert(node->left); this->count += 1; } else { insert(node->left, key, value, replace); } } else { /* key > node->key */ if (node->right == nullptr) { node->right = Node::from(key, value); node->right->parent = node; maintainAfterInsert(node->right); this->count += 1; } else { insert(node->right, key, value, replace); } } } void maintainAfterRemove(ConstNodePtr node) { if (node->isRoot()) { return; } assert(node->isBlack() && node->hasSibling()); Direction direction = node->direction(); NodePtr sibling = node->sibling(); if (sibling->isRed()) { ConstNodePtr parent = node->parent; assert(parent != nullptr && parent->isBlack()); assert(sibling->left != nullptr && sibling->left->isBlack()); assert(sibling->right != nullptr && sibling->right->isBlack()); rotateSameDirection(node->parent, direction); sibling->color = Node::BLACK; parent->color = Node::RED; sibling = node->sibling(); } NodePtr closeNephew = direction == Direction::LEFT ? sibling->left : sibling->right; NodePtr distantNephew = direction == Direction::LEFT ? sibling->right : sibling->left; bool closeNephewIsBlack = closeNephew == nullptr || closeNephew->isBlack(); bool distantNephewIsBlack = distantNephew == nullptr || distantNephew->isBlack(); assert(sibling->isBlack()); if (closeNephewIsBlack && distantNephewIsBlack) { if (node->parent->isRed()) { // clang-format off // Case 2: Sibling and nephews are BLACK, parent is RED // Swap the color of P and S // <P> [P] // / \ / \ // [N] [S] ====> [N] <S> // / \ / \ // [C] [D] [C] [D] // clang-format on sibling->color = Node::RED; node->parent->color = Node::BLACK; return; } else { // clang-format off // Case 3: Sibling, parent and nephews are all black // Step 1. Paint S to RED // Step 2. Recursively maintain P // [P] [P] // / \ / \ // [N] [S] ====> [N] <S> // / \ / \ // [C] [D] [C] [D] // clang-format on sibling->color = Node::RED; maintainAfterRemove(node->parent); return; } } else { if (closeNephew != nullptr && closeNephew->isRed()) { // Step 1 rotateOppositeDirection(sibling, direction); // Step 2 closeNephew->color = Node::BLACK; sibling->color = Node::RED; // Update sibling and nephews after rotation sibling = node->sibling(); closeNephew = direction == Direction::LEFT ? sibling->left : sibling->right; distantNephew = direction == Direction::LEFT ? sibling->right : sibling->left; // Step 3: vvv } assert(closeNephew == nullptr || closeNephew->isBlack()); assert(distantNephew->isRed()); // Step 1 rotateSameDirection(node->parent, direction); // Step 2 sibling->color = node->parent->color; node->parent->color = Node::BLACK; if (distantNephew != nullptr) { distantNephew->color = Node::BLACK; } return; } } bool remove(NodePtr node, K key, NodeConsumer action) { assert(node != nullptr); if (key != node->key) { if (compare(key, node->key)) { /* key < node->key */ NodePtr &left = node->left; if (left != nullptr && remove(left, key, action)) { maintainRelationship(node); return true; } else { return false; } } else { /* key > node->key */ NodePtr &right = node->right; if (right != nullptr && remove(right, key, action)) { maintainRelationship(node); return true; } else { return false; } } } assert(key == node->key); action(node); if (this->size() == 1) { // Current node is the only node of the tree this->clear(); return true; } if (node->left != nullptr && node->right != nullptr) { // clang-format off // Case 1: If the node is strictly internal // Step 1. Find the successor S with the smallest key // and its parent P on the right subtree. // Step 2. Swap the data (key and value) of S and N, // S is the node that will be deleted in place of N. // Step 3. N = S, goto Case 2, 3 // | | // N S // / \ / \ // L .. swap(N, S) L .. // | =========> | // P P // / \ / \ // S .. N .. // clang-format on // Step 1 NodePtr successor = node->right; NodePtr parent = node; while (successor->left != nullptr) { parent = successor; successor = parent->left; } // Step 2 swapNode(node, successor); maintainRelationship(parent); // Step 3: vvv } if (node->isLeaf()) { // Current node must not be the root assert(node->parent != nullptr); // Case 2: Current node is a leaf // Step 1. Unlink and remove it. // Step 2. If N is BLACK, maintain N; // If N is RED, do nothing. // The maintain operation won't change the node itself, // so we can perform maintain operation before unlink the node. if (node->isBlack()) { maintainAfterRemove(node); } if (node->direction() == Direction::LEFT) { node->parent->left = nullptr; } else /* node->direction() == Direction::RIGHT */ { node->parent->right = nullptr; } } else /* !node->isLeaf() */ { assert(node->left == nullptr || node->right == nullptr); // Case 3: Current node has a single left or right child // Step 1. Replace N with its child // Step 2. If N is BLACK, maintain N NodePtr parent = node->parent; NodePtr replacement = (node->left != nullptr ? node->left : node->right); switch (node->direction()) { case Direction::ROOT: this->root = replacement; break; case Direction::LEFT: parent->left = replacement; break; case Direction::RIGHT: parent->right = replacement; break; } if (!node->isRoot()) { replacement->parent = parent; } if (node->isBlack()) { if (replacement->isRed()) { replacement->color = Node::BLACK; } else { maintainAfterRemove(replacement); } } } this->count -= 1; return true; } void inorderTraversal(NodeConsumer action) const { if (this->root == nullptr) { return; } std::stack<NodePtr> stack; NodePtr node = this->root; while (node != nullptr || !stack.empty()) { while (node != nullptr) { stack.push(node); node = node->left; } if (!stack.empty()) { node = stack.top(); stack.pop(); action(node); node = node->right; } } } }; #endif // RBTREE_MAP_HPP ```
https://github.com/Quaternijkon/notebook
https://raw.githubusercontent.com/Quaternijkon/notebook/main/content/数据结构与算法/.chapter-数据结构/链表/反转链表.typ
typst
#import "../../../../lib.typ":* === #Title( title: [反转链表], reflink: "https://leetcode.cn/problems/reverse-linked-list/description/", level: 1, )<反转链表> #note( title: [ 反转链表 ], description: [ 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 ], examples: ([ 输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1] ],[ 输入:head = [1,2] 输出:[2,1] ],[ 输入:head = [] 输出:[] ] ), tips: [ 链表中节点的数目范围是 [0, 5000] -5000 <= Node.val <= 5000 ], solutions: ( (name:[迭代], text:[ 考虑遍历链表,并在访问各节点时修改 `next` 引用指向,算法流程见注释。 ],code:[ ```cpp class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *cur = head, *pre = nullptr; while(cur != nullptr) { ListNode* tmp = cur->next; // 暂存后继节点 cur.next cur->next = pre; // 修改 next 引用指向 pre = cur; // pre 暂存 cur cur = tmp; // cur 访问下一节点 } return pre; } }; ``` ]),( name:[递归], text:[ 考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 `next` 引用指向。 `recur(cur, pre)` 递归函数: + 终止条件:当 `cur` 为空,则返回尾节点 `pre` (即反转链表的头节点); + 递归后继节点,记录返回值(即反转链表的头节点)为 `res` ; + 修改当前节点 `cur` 引用指向前驱节点 `pre` ; + 返回反转链表的头节点 `res` ; `reverseList(head)` 函数: 调用并返回 `recur(head, null)` 。传入 `null` 是因为反转链表后, `head` 节点指向 `null` ; ],code:[ ```cpp class Solution { public: ListNode* reverseList(ListNode* head) { return recur(head, nullptr); // 调用递归并返回 } private: ListNode* recur(ListNode* cur, ListNode* pre) { if (cur == nullptr) return pre; // 终止条件 ListNode* res = recur(cur->next, cur); // 递归后继节点 cur->next = pre; // 修改节点引用指向 return res; // 返回反转链表的头节点 } }; ``` ] ), ), gain:none, )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cumcm-muban/0.1.0/README.md
markdown
Apache License 2.0
cumcm-muban 是一个为高教社杯全国大学生数学建模竞赛设计的 Typst 模板。 ## 使用方法 你可以在 Typst 网页应用中使用此模板,只需在仪表板上点击 “Start from template”,然后搜索 cumcm-muban。 另外,你也可以使用 CLI 命令来启动这个项目。 ``` typst init @preview/cumcm-muban ``` Typst 将会创建一个新的目录,其中包含了所有你开始所需要的文件。 ## 配置 此模板导出了 cumcm 函数,包含以下命名参数: - title: 论文的标题 - problem-chosen: 选择的题目 - team-number: 团队的编号 - college-name: 高校的名称 - member: 团队成员的姓名 - advisor: 指导教师的姓名 - date: 竞赛开始的时间 - cover-display: 是否显示封面以及编号页 - abstract: 摘要内容包裹在 `[]` 中 - keywords: 关键字内容包裹在 `()` 中,使用逗号分隔 该函数还接受一个位置参数 `body`,用于论文的正文内容。 该模板将在显示规则中使用`cumcm`函数进行示例调用来初始化您的项目。如果您想要将现有项目更改为使用此模板,您可以在文件顶部添加一个类似于以下的显示规则: ```typ #import "@preview/cumcm-muban:0.1.0": * #show: thmrules #show: cumcm.with( title: "全国大学生数学建模竞赛 Typst 模板", problem-chosen: "A", team-number: "1234", college-name: " ", member: ( A: " ", B: " ", C: " ", ), advisor: " ", date: datetime(year: 2023, month: 9, day: 8), cover-display: true, abstract: [], keywords: ("Typst", "模板", "数学建模"), ) // 在下面填写你的内容。 ``` ## 模板预览 | 封面 | 编号页 | 正文 | |:---:|:---:|:---:| | ![Cover-1](https://github.com/a-kkiri/CUMCM-typst-template/blob/38309b04a9edc039def0f7a093eaa640989ccee8/figures/p1.jpg?raw=true) | ![Cover-2](https://github.com/a-kkiri/CUMCM-typst-template/blob/38309b04a9edc039def0f7a093eaa640989ccee8/figures/p2.jpg?raw=true)| ![Content](https://github.com/a-kkiri/CUMCM-typst-template/blob/38309b04a9edc039def0f7a093eaa640989ccee8/figures/p4.jpg?raw=true)| ## ⚠️注意 > 本模板需要中易以及 TimesNewRoman 系列字体,请到 [CUMCM-typst-template/fonts.zip](https://github.com/a-kkiri/CUMCM-typst-template/blob/main/fonts.zip?raw=true) 下载。
https://github.com/flechonn/interface-typst
https://raw.githubusercontent.com/flechonn/interface-typst/main/BD/TYPST/utilities.typ
typst
// GLOBAL SHEET TEMPLATE #set text( font: "Inria Serif", size: 10pt, ) #set page( paper: "a4", ) // SHEET HEADING TEMPLATE #let title(doc) = [ #set text(16pt) #doc ] #let header(doc) = [ #set align(center) #set text(12pt, weight: "bold") #show "author" : [Author] #show "date" : [Date] #show "duration" : [Duration] #doc ] #let modality(doc) = [ #set text(10pt, weight: "regular") #set align(start) #set par(justify: true) #doc ] #let lines(doc) = [ #line(length: 100%) #doc ] // SHEET CONTENT (EXERCISES) TEMPLATE #let main_meta(doc) = [ #set text(12pt, weight: "bold") #show "title" : [Exercise :] #show "bonus" : [(Bonus)] #show "duration" : [] #show "points" : [] #doc ] #let meta(doc) = [ #set text(font: "Inria Serif", 8pt, weight: "bold") #show "difficulty" : [Difficulty :] #show "author" : [Author :] #show "references" : [References :] #show "language" : [Language :] #show "material" : [Material :] #show "name" : [File name :] #doc ] #let exercise(doc) = [ #set text(font: "Inria Serif", 11pt, weight: "regular") #doc ] #let solution_header(doc) = [ #set text(font: "Inria Serif", 12pt, weight: "bold") #show "solution" : [Solution :] #doc ] #let solution(doc) = [ #set text(font: "Inria Serif", 11pt, weight: "regular") #doc ]
https://github.com/max-niederman/MTH311
https://raw.githubusercontent.com/max-niederman/MTH311/main/hw/4.typ
typst
#import "../lib.typ": * #show: homework.with(title: "Math 311 Homework 4") = 3.3.1 (b) Take $epsilon > 0$ as given and let $delta = min{epsilon/12, 6}$. Now, suppose we have $x$ such that $ abs(x - 3) < delta "." $ From its definition, we have $delta <= epsilon/12$. Therefore, we have $abs(x - 3) <= epsilon/12$. Multiplying both sides by twelve yields $12abs(x - 3) <= epsilon$. We will now show that $abs(x + 3) < 12$. Again, from the definition of $delta$, we have $delta <= 6$. And from the premise that $abs(x - 3) < delta$, we know that $ -delta < x - 3 &< delta \ -6 < x - 3 &< 6 quad \ 0 < x + 3 &< 12 \ abs(x + 3) &< 12 $ Therefore, we can substitute $abs(x + 3)$ for $epsilon$ to get $ abs(x + 3) abs(x - 3) &< epsilon \ abs(x^2 - 9) &< epsilon \ abs((x^2 + 1) - (3^2 - 1)) &< epsilon \ abs(f(x) - f(3)) &< epsilon "." $ Therefore, $f$ is continuous at $x_0 = 3$ by definition. #sym.qed = 3.3.2 (d) Consider any $x_0 in [0, oo)$. Let $epsilon > 0$ be given and define $delta = epsilon sqrt(x_0)$. Then for any $x in [0, oo)$ such that $ 0 < abs(x - x_0) < delta "," $ we have $x != x_0$ and $abs(x - x_0) < epsilon sqrt(x_0)$. Adding $epsilon sqrt(x)$ to the right side of the inequality yields $abs(x - x_0) < epsilon(sqrt(x) + sqrt(x_0))$. Square roots of real numbers are nonnegative, so we have $ abs(x - x_0) < epsilon abs(sqrt(x) + sqrt(x_0)) "." $ Now we factor the left-hand side of the inequality as a difference of squares: $ abs(sqrt(x) + sqrt(x_0)) abs(sqrt(x) - sqrt(x_0)) < epsilon abs(sqrt(x) + sqrt(x_0)) "." $ Note that either + $x_0 = 0$, in which case $x > 0$ (since $x in [0, oo)$ and $x != x_0$) and we have $sqrt(x) + sqrt(x_0) > 0$, or + $x_0 > 0$, in which case $sqrt(x_0) > 0$ and $sqrt(x) >= 0$, so we also have $sqrt(x) + sqrt(x_0) > 0$. Therefore, we can divide both sides of the inequality by $abs(sqrt(x) + sqrt(x_0))$ to get $ abs(sqrt(x) - sqrt(x_0)) < epsilon "." $ So, by definition, the square root is continuous at any $x_0 in [0, oo)$. #sym.qed = 3.3.3 (b) The domain of $f$ is $RR$, which contains all its limiting points. Therefore, $f$ is continuous at some point $x_0 in RR$ if and only if $ lim_(x->x_0) f(x) = f(x_0) "." $ At $x_0 = 0$, we have by L'hôpital's rule that $ lim_(x->x_0) f(x) =& lim_(x->x_0) abs((sin x) / x) \ =& lim_(x->x_0) (cos x) / 1 \ =& lim_(x->x_0) (cos x) / 1 \ =& lim_(x->x_0) cos x $ And since $cos$ is continuous at $x_0 = 0$, we have $ lim_(x->x_0) f(x) = cos 0 = 1 = f(0) "." $ Therefore, $f$ is continuous at $x_0 = 0$. For any $x_0 != 0$, we know that $ lim_(x -> x_0) x = x_0 != 0 "," $ so we can apply Theorem 3.3.3 to find that the quotient of $sin x$ and $x$ is continuous at $x_0$: #lemma[ _Lemma_: If any function $f : D -> RR$ is continuous at $x_0 in D$, the function $ f_a (x) = abs(f(x)) $ is also continuous at $x_0$. _Proof_: Let $epsilon > 0$ be given. Then, because $f$ is continuous at $x_0$, there exists $delta > 0$ such that for any $x in D$, $ abs(x - x_0) < delta "implies" abs(f(x) - f(x_0)) < epsilon "." $ And by the reverse triangle inequality, we have $ abs(abs(f(x)) - abs(f(x_0))) <= abs(f(x) - f(x_0)) < epsilon "." $ Therefore, $f_a$ is continuous at $x_0$ by definition. #sym.qed ] Applying the lemma, we find that $abs((sin x)/x)$ is also continuous at $x_0$. Therefore, $f$ is continuous everywhere on $RR$. = 3.3.3 (c) $f$ is not continuous at $x_0 = 0$, because the left and right limits of $f$ at $x_0 = 0$ are not equal: From the left, we have $ lim_(x->0^-) f(x) =& lim_(x->0^-) (sin x) / abs(x) \ =& lim_(x->0^-) (sin x) / (-x) \ =& lim_(x->0^-) (cos x) / (-1) \ =& -1 "." $ But from the right, we have $ lim_(x->0^+) f(x) =& lim_(x->0^+) (sin x) / abs(x) \ =& lim_(x->0^+) (sin x) / x \ =& lim_(x->0^-) (cos x) / 1 \ =& 1 "." $ Everywhere else (if $x_0 != 0$), we know that $ lim_(x -> x_0) abs(x) != 0 "," $ so we can apply Theorem 3.3.3 to find that the quotient of $sin x$ and $abs(x)$ is continuous at $x_0$. Therefore, $f$ is continuous everywhere on $RR$ except at $x_0 = 0$. = 3.3.5 (a) Suppose that $f$ is continuous at any $x_0 in RR$. === Case 1: $x_0 in QQ$ Then $f(x_0) = 1$. For any $n in NN$, we know by the density of the irrationals that there exists $a_n in QQ^c$ such that $ x_0 - 1/n < a_n < x_0 "." $ Consider such a sequence ${a_n}$. By the squeeze theorem, $a_n --> x_0$. And since $f$ is continuous at $x_0$, we have $f(a_n) --> f(x_0)$. However, $f(a_n) = -1$ for all $n in NN$ because $a_n$ is irrational. Therefore, $f(x_0) = -1$, which is a contradiction. === Case 2: $x_0 in QQ^c$ Then $f(x_0) = -1$. For any $n in NN$, we know by the density of the rationals that there exists $a_n in QQ$ such that $ x_0 - 1/n < a_n < x_0 "." $ Consider such a sequence ${a_n}$. By the squeeze theorem, $a_n --> x_0$. And since $f$ is continuous at $x_0$, we have $f(a_n) --> f(x_0)$. However, $f(a_n) = 1$ for all $n in NN$ because $a_n$ is rational. Therefore, $f(x_0) = 1$, which is a contradiction. Hence, $f$ is not continuous at any $x_0 in RR$. #sym.qed = 3.3.5 (b) === Case 1: $x_0 = 0$ Note that, for any $x in RR$, we have $abs(f(x)) <= abs(x)$. This is because + If $x in QQ$, then $f(x) = x$ so $abs(f(x)) = abs(x) <= abs(x)$. + If $x in.not QQ$, then $f(x) = 0$ so $abs(f(x)) = 0 <= abs(x)$. Now suppose $epsilon > 0$ is given, and let $delta = epsilon$. Then for any $x in RR$ such that $abs(x - 0) < delta = epsilon$, we have $ abs(f(x) - f(0)) = abs(f(x)) <= abs(x) < epsilon "." $ So by definition $f$ is continuous at $x_0 = 0$. === Case 2: $x_0 != 0$ and $x_0 in QQ$ Then $f(x_0) = x_0 != 0$. In the same way as for the last problem, we can find a sequence ${a_n}$ consisting of elements of $QQ^c$ such that $a_n --> x_0$. Now suppose by contradiction that $f$ is continuous at $x_0$. Then $f(a_n) --> f(x_0)$. But $f(a_n) = 0$ for all $n in NN$ because $a_n$ is irrational, so $f(x_0) = 0$, which is a contradiction. === Case 3: $x_0 != 0$ and $x_0 in QQ^c$ Then $f(x_0) = 0$. In the same way as for the last problem, we can find a sequence ${a_n}$ consisting of elements of $QQ$ such that $a_n --> x_0$. Now suppose by contradiction that $f$ is continuous at $x_0$. Then $f(a_n) --> f(x_0)$. But $f(a_n) = a_n$ for all $n in NN$ because $a_n$ is rational, so $a_n --> f(x_0)$. Therefore, $f(x_0) = x_0 != 0$, which is a contradiction. Hence, $f$ is continuous only at $x_0 = 0$. #sym.qed = 3.3.10 Let $x in RR$ be given. For any $n in NN$, we know by the density of the rationals that there exists $x_n in QQ$ such that $ x - 1/n < x_n < x "." $ Consider such a sequence ${x_n}$. By the squeeze theorem, $x_n --> x$. Both $f$ and $g$ are continuous at $x$, so $ f(x_n) &--> f(x) \ g(x_n) &--> g(x) "." $ And because $x_n$ is rational, we have $f(x_n) = g(x_n)$. That is, the sequences are identical, and therefore converge to the same value, $f(x) = g(x)$. #sym.qed = 3.4.1 #lemma[ _Lemma_: For any $x in RR$, the constant function $f : D -> RR$ given by $f(x) = gamma$ is continuous on $D$. _Proof_: Let $c in D$ and $epsilon > 0$ be given, and define $delta = 1$. Then for any $x in D$ such that $abs(x - c) < delta$, we have $ abs(f(x) - f(c)) = abs(gamma - gamma) = 0 < epsilon "." $ #sym.qed ] Consider the function $f_gamma : D -> RR$ defined by $ f_gamma (x) = f(x) - gamma "." $ Note that $f_gamma$ is continuous on $D$ by Theorem 3.3.3 (considering $gamma$ as a constant function $D -> RR$). We have that $f(c) > gamma$, so subtracting $gamma$ from both sides gives $f_gamma (c) < 0$. Now we can apply Lemma 3.4.3 to find that there exists $delta > 0$ such that $f_gamma (x) > 0$ for every $x in D$ such that $abs(x - c) < delta$. Now consider any $x in (c - delta, c + delta) sect D$. Then $ c - delta < x <& c + delta \ -delta < x - c <& delta \ abs(x - c) <& delta "." $ Implying that $f_gamma (x) > 0$. Finally, adding $gamma$ to both sides gives $f(x) > gamma$. #sym.qed = 3.4.2 Consider the function $f - g : [a, b] -> RR$ defined by $ (f - g)(x) = f(x) - g(x) "." $ Since $f$ and $g$ are continuous on $[a, b]$, we can apply Theorem 3.3.3 to find that $f - g = f + (-1)g$ is continous on $[a, b]$ also. We know that $f(a) > g(a)$ and $f(b) < g(b)$, so $ f(a) &> g(a) &wide f(b) &< g(b) \ f(a) - g(a) &> 0 &wide f(b) - g(b) &< 0 \ (f - g)(a) &> 0 &wide (f - g)(b) &< 0 \ $ Therefore, by the Intermediate Value Theorem, there exists $x_0 in (a, b)$ such that $(f - g)(x_0) = 0$. That is, $f(x_0) - g(x_0) = 0$. So $f(x_0) = g(x_0)$. #sym.qed = 3.4.3 #lemma[ _Lemma_: The identity function $id : RR -> RR$ is continuous. _Proof_: Let $c in RR$ and $epsilon > 0$ be given. Define $delta = epsilon$. Then for any $x in RR$ such that $abs(x - c) < delta$, we have $ abs(id(x) - id(c)) = abs(x - c) < delta = epsilon "." $ Therefore, $id$ is continuous at any $c in RR$. #sym.qed ] Consider the identity and cosine functions on $RR$, denoted by $id$ and $cos$, respectively. Note that - $id(0) = 0 < 1 = cos(0)$ and - $id(pi) = pi > -1 = cos(pi)$. Both the identity and cosine functions are continuous on $RR$, so we can apply the solution to the last problem to find that there exists $x in (0, pi)$ such that $id(x) = cos(x)$. That is, there exists $x in RR$ such that $x = cos(x)$. #sym.qed = 3.4.5 == 3.4.5 (a) Consider the sequence ${x_n}$ defined by $ x_1 &= a \ x_(n+1) &= f(x_n) "." $ We will now show that either the sequence is convergent and the limit is a fixed point, or it "crosses the diagonal" on the graph of $f$ and the point where it crosses is a fixed point. === Case 1: ${x_n}$ Increasing The sequence ${x_n}$ is bounded above by $b$, so if it is increasing then by the Monotone Convergence Theorem it converges to some $x in [a, b]$. By the continuity of $f$, we have $ x_n &--> x \ f(x_n) &--> f(x) "." $ Now consider the subsequence skipping the first element, ${x_(n+1)}$. By definition, $x_(n+1) = f(x_n)$, so this is the same as the sequence ${f(x_n)}$. Subsequences of a convergent sequence converge to the same limit, so $ f(x_n) --> x "." $ The limit of a sequence is unique, so $f(x) = x$. === Case 2: ${x_n}$ Non-Increasing Then there exists $N in NN$ such that $x_N > x_(N+1)$. That is, $x_N > f(x_N)$. If $f(a) = a$, then we are done. Otherwise, we have $a < f(a)$. As in the last problem, we apply the solution to Exercise 3.4.2 to find $x in [a, x_N]$ such that $ id(x) = f(x) "." $ That is, $f(x) = x$. #sym.qed == 3.4.5 (b) By part (a), we know that $f$ has at least one fixed point. Now let $x, y in [a, b]$ be two fixed points of $f$, and suppose by contradiction that $x != y$. Then by the premise, we have $ abs(f(x) - f(y)) < abs(x - y) "." $ Substituting $x$ for $f(x)$ and $y$ for $f(y)$, we have $ abs(x - y) < abs(x - y) "." $ Which is a contradiction. Therefore, $x = y$ and $f$ has exactly one fixed point. #sym.qed
https://github.com/horaoen/note
https://raw.githubusercontent.com/horaoen/note/main/README.md
markdown
Apache License 2.0
# note personal note writting by typst using my [typst-template(typstempl)](https://www.github.com/horaoen/typstempl)
https://github.com/TypstApp-team/typst
https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/layout/grid-5.typ
typst
Apache License 2.0
--- // Test that trailing linebreak doesn't overflow the region. #set page(height: 2cm) #grid[ Hello \ Hello \ Hello \ World ] --- // Test that broken cell expands vertically. #set page(height: 2.25cm) #grid( columns: 2, gutter: 10pt, align(bottom)[A], [ Top #align(bottom)[ Bottom \ Bottom \ #v(0pt) Top ] ], align(top)[B], )
https://github.com/marnym/typst-watch.nvim
https://raw.githubusercontent.com/marnym/typst-watch.nvim/main/README.md
markdown
MIT License
# typst-watch.nvim **typst-watch.nvim** is a plugin that makes your [typst](https://typst.app/) workflow easier. ## Requirements - Neovim >= `0.10.0` - [typst](https://github.com/typst/typst) ## Features - Searches for `main.typ`, and starts `typst watch main.typ` - If a different main file is used, the compilation process can be launched with: `:TypstWatch filename` or `:TypstWatch` for the current file - The compiled document can be opened with `:TypstPreview` - Notifies the user of the compilation result ## Installation ### [lazy.nvim](https://github.com/folke/lazy.nvim) ```lua { "marnym/typst-watch.nvim", opts = {}, -- specify options here ft = "typst", -- for lazy loading } ``` ## Configuration The following options are available in **typst-watch.nvim**: ``` lua { -- Command that opens the compiled document. preview_cmd = {"xdg-open",}, -- or open on macOS } ```
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/lib/utils/utils.typ
typst
Other
#import "./make-hero.typ": make-hero #import "./make-prob-meta.typ": make-prob-meta #import "./make-prob-overview.typ": make-prob-overview #import "./make-problem.typ": make-problem #import "./problem.typ": problem
https://github.com/chaosarium/typst-templates
https://raw.githubusercontent.com/chaosarium/typst-templates/main/notebook/components/envs.typ
typst
// Proof environment #let proof(body) = block(spacing: 11.5pt, { emph[Proof.] [ ] + body h(1fr) box(scale(160%, origin: bottom + right, sym.square.stroked)) }) // components #let blockquote(body) = { rect( stroke: (left: black + 2pt), inset: (x: 8pt, y: 6pt), outset: -2pt, body, ) }
https://github.com/Stautaffly/typ
https://raw.githubusercontent.com/Stautaffly/typ/main/note/笔记.typ
typst
#import "note-model.typ": * #show: project.with( course: "数学分析第一卷", title: "一元微积分", authors: (( name: "o(* ̄▽ ̄*)o", email: "", phone: "" ),), date: "January 24, 2024", ) = 连续与极限 == 数列 #dy[数列是一个映射$NN -> RR$]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/circuiteria/0.1.0/doc/example.typ
typst
Apache License 2.0
#import "@preview/cetz:0.2.2": draw #import "../src/circuit.typ": circuit #import "../src/util.typ" #let example-preamble = "import \"../src/lib.typ\": *;" #let example-scope = ( draw: draw ) #let example(src, show-src: true, vertical: false, fill: true) = { src = src.text let full-src = example-preamble + src let body = eval(full-src, scope: example-scope) let img = circuit(length: 2em, body) block(width: 100%, align(center, box( stroke: black + 1pt, radius: .5em, fill: if fill {util.colors.yellow.lighten(80%)} else {none}, if show-src { let src-block = align(left, raw(src, lang: "typc")) table( columns: if vertical {1} else {2}, inset: 1em, align: horizon + center, stroke: none, img, if vertical {table.hline()} else {table.vline()}, src-block ) } else { table( inset: 1em, img ) } ) ) ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/genealotree/0.1.0/examples/example.typ
typst
Apache License 2.0
#import "@preview/genealotree:0.1.0": * #set page(width: auto, height: auto, margin: 1cm) #let geneal-example = genealogy-init() #let geneal-example = add-persons( geneal-example, ( "I1": (sex: "m", phenos: ("ill",)), "I2": (sex: "f"), "II1": (sex: "f", phenos: ("ill",)), "II1*": (sex: "m"), "II2": (sex: "f"), "II3": (sex: "f", phenos: ("ill",)), "II3*": (sex: "m"), "III1": (sex: "f", phenos: ("ill",)), "III1*": (sex: "m"), "III2": (sex: "f"), "III3": (sex: "m", phenos: ("ill",)), "III4": (sex: "f"), "IV1": (sex: "m"), "IV2": (sex: "m", phenos: ("ill",)), "IV3": (sex: "f", phenos: ("ill",)), ) ) #let geneal-example = add-unions( geneal-example, (("I1", "I2"), ("II1", "II2", "II3")), (("II1", "II1*"), ("III1",)), (("II3", "II3*"), ("III2", "III3", "III4")), (("III1", "III1*"), ("IV1", "IV2", "IV3")) ) #canvas(length: 0.4cm, { // Draw the tree draw-tree(geneal-example) })
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-17.typ
typst
Other
// Error: 10-16 zero to the power of zero is undefined #calc.pow(0, 0)
https://github.com/GabrielDTB/basalt-backlinks
https://raw.githubusercontent.com/GabrielDTB/basalt-backlinks/main/src/exports.typ
typst
MIT License
#import "backlinks.typ": generate, get
https://github.com/typst-doc-cn/awesome-typst-cn
https://raw.githubusercontent.com/typst-doc-cn/awesome-typst-cn/main/README.md
markdown
Creative Commons Zero v1.0 Universal
<p align=center> <b>该项目已与 <a href="https://github.com/qjcg/awesome-typst/blob/main/README_ZH.md">qjcg/awesome-typst</a> 合并</b> </p>
https://github.com/jiamingluuu/mata35-notes
https://raw.githubusercontent.com/jiamingluuu/mata35-notes/main/notes.typ
typst
#set page(paper: "a4") #set text(11pt) #set heading(numbering: "1.") #set par(justify: true) #set rect(width: 100%, radius: 8pt, fill: rgb("#f2f2f2"), stroke: 1pt, inset: 12pt) #align(left, text(27pt)[ #v(79.4pt) *MATA35 Course Notes* ]) #v(2cm) #align(left, [ #h(1cm) *Instructor*: Dr. <NAME>\ #h(1cm) *Author*: <NAME>\ ]) #v(7cm) // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() #move(dy: 1em, [ © <NAME>, 2024\ All rights reserved. For question, error correcting, or any other issue regarding the notes, please email #align(center, [<EMAIL>]) ]) // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() #move(dy: 45em, [ The Notes (_MATA35 Course Notes_) is made solely by the author (<NAME>), students in MATA35H3 - Winter 2024 session may read The Note as reference. If you encounter any gaffes, omissions, snafus, kludges, typos, mathos, grammaros, thinkos, brain farts, poor design decisions, historical inaccuracies, anachronisms, inconsistencies, exaggerations, dithering, blather, distortions, oversimplifications, redundancy, logorrhea, nonsense, garbage, cruft, junk, and outright lies, *all of which are entirely JiaYan Lu’s liabilities.* Please feel free to contact with JiaYan once you find mistake in this notes, any help or advise is greatly appreciated. Students who read the notes should know the followings: + Contents out of the scope of The Notes may appear on assessments. + Lectures and tutorials are always the primary resources that students should refer to. Reading The Notes should always for reviewing purposes. + The Notes is created for academic use, sending this notes to third party for beneficial purposes is prohibited. ]) git push -u origin main #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() #move(dx: 2cm, [#align(left, [_<NAME> once told me (<NAME>) that as a kid,\ ~~~~~he remembered being stuck on a jigsaw puzzle.\ ~~~~~His brother, who was passing by, said to him:\ ~~~~~*"You know: I could tell you something."*\ ~~~~~That's all his brother said.\ ~~~~~Yet that was enough hint to help Claude solve the puzzle.\ ~~~~~The great thing about this hint... \ ~~~~~is that you can always give it to yourself!\ ~~~~~I advise you, when you're stuck on a hard problem,\ ~~~~~to imagine a little birdie or an older version of yourself whispering\ ~~~~~"... I could tell you something..."\ #move(dx: 8cm, dy: 10pt, [------Manuel Blum])_] )]) // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() #outline(indent: auto) #pagebreak() #set page(numbering: "1") = Preliminaries Definition is essential. Without giving a precise, clear definition of objects, it is impossible to have an academic conversation or develop rigorous concepts. However, the imperfection of reality imposes restriction on our ability of giving objects definitions: _we cannot give everything a definition_. Our journey begins as such. == Sets *Definition.* A _set_ is a "collection" of objects. #footnote[This clearly, is not a definition ------ it defines set using another notion, "collection". We may ask ourself: What is a collection? What is an objects? We can continue this Socratic-styled interrogation and use up words eventually. Therefore, we will take the definition of sets for granted.] *Definition.* Objects that are comprise the set are _element_. If $X$ is a set, we denote $x$ is an element of $X$ as $x in X$. We may describe a set by either listing all the elements of the set, for example $ F = {"apple", "banana", "orange"}, $ or characterizing the properties of the elements in the set, for example $ A = {x in RR: x < 1}. $ #rect( [_Remark._ We can also use _interval_ notation to describe sets of real numbers. For any $a, b in RR, a < b$, $ (a, b) &= {x in RR: a < x < b}\ [a, b] &= {x in RR: a <= x <= b}\ (a, b] &= {x in RR: a < x <= b}\ [a, b) &= {x in RR: a <= x < b}. $ Particularly, $(a, b)$ is called an _open interval_ and $[a, b]$ is called a _closed interval_.] ) *Definition.* Given two sets $X, Y$, $X$ is a _subset_ of $Y$, written as $X subset.eq Y$, if for every element $x in X$, $x in Y$. *Definition.* The _complement_ of a set $X subset.eq Y$, denoted by $X^c$, is given by $ X^c = {x in Y: x in.not X} $ == Functions Naively speaking, function is a black box that gives an output for every input. We often write $f: X -> Y$ to denote $f$ is a function maps elements in $X$ to some element in $Y$, where $X$ is called the domain and $Y$ is a called the codomain (aka. range) of $f$. There are some functions you may get familiar with: === Polynomials *Definition.* A _polynomial_ is function of the form $ p(x) = a_0 + a_1x + a_2 x^2 + ... + a_n x^n $ for some natural number $n$. Each of $a_0, a_1, ..., a_n$ are called the _coefficients_ of the polynomial $p$. The highest degree of monomial with non-zero coefficient is called the _degree_ of the polynomial, denoted by $deg(p)$. *Definition.* Given a polynomial $p: RR -> RR$, a real number $r$ is called the _root_ of $p$ if $p(r) = 0$. *Example.* $f(x) = x^2 + 5x - 6$ is a polynomial if degree 2. It has roots $x = -6, 1$. Moreover, I want to emphasis on the root finding problem of polynomials in degree 2, that is, of the form $p(x) = a x^2 + b x + c$, where $a, b, c in RR$ with $a eq.not 0$. There are three ways of finding the root of $p(x)$ that we should know: + *Quadratic Formula.* Let the discriminant $Delta = b^2 - 4 a c$. If $Delta > 0$, then the root $r$ of $p(x)$ satisfies: $ r = (-b plus.minus sqrt(Delta))/(2a). $ When $Delta > 0$, $p(x)$ has two distinct roots, on the contrary of $Delta = 0$, $p(x)$ has one repeated root. + *Complete the Square.* Write the polynomial into the form $p(x) = a(x + alpha)^2 + beta$. The root is given by $ r = plus.minus beta/a - alpha. $ + *Factorization.* Write the the polynomial in the form of $p(x) = a(x - alpha)(x - beta).$ Then the roots are given by $r = alpha, beta$. === Trigonometric Functions Trigonometric functions are defined using the unite circle $S^1 = {(x, y) in RR^2: x^2 + y^2 = 1}$. #figure( image("img/trig_func.png", width: 35%), caption: [Definition of $sin(theta)$ and $cos(theta)$ on unite circle $S^1$.] ) Let $p = (x, y)$ be a point on the unit circle $S^1$. The line goes through $p$ and the origin forms an angle $theta$. We define $cos(theta) equiv x$ and $sin(theta) equiv y$. There are some basic trigonometric identities you should familiar with, check *Appendix 3.2* for details. #rect[ _Remark._ Analytically, the identity of trigonometric functions relies on Euler's formula with _imaginary unit_ $i = sqrt(-1)$: $ e^(i x) = cos(x) + i sin(x). $ It follows that $ sin(x) = (e^(i x) - e^(- i x))/ 2, quad cos(x) = (e^(i x) + e^(-i x))/ 2. $ ] == Limits *Definition.* Let $f: A -> RR, x |-> f(x)$ be a function with $a in RR$ be a limit point of $A$. Given $ell in RR$, we write $ lim_(x -> a)f(x) = ell $ if and only if $ forall epsilon > 0, exists delta > 0, s.t. 0 < |x - a| < delta => |f(x) - ell | < epsilon. $ #rect([_Remark._ - The limit point $a$ does not necessarily be in the domain $A$ of $f$. Considering the example $ lim_(x -> 1) (x^2 - 1)/(x-1) = 2. $ The function $f(x) = (x^2 - 1)/(x-1)$ has domain $A = {x: x in RR - {1}}$, we can immediately see the fact that $1 in.not A$ but the it is a valid limit point of $f$. - FYI, we may seen this definition as "if $x$ is infinitesimally approaching to $a$, then $f(x)$ is infinitesimally approaching to $ell$." However, this definition leads to the _Second Mathematical Crisis_.]) *Proposition.* Basic limit properties. Let $f, g: A -> RR$ be two functions, let $a in RR$ be a limit point. If $ lim_(x -> a)f(x) = ell, lim_(x -> a)g(x) = m $ then we have - $lim_(x -> a) f(x) plus.minus g(x) = ell plus.minus m$, - $lim_(x -> a) f(x)g(x) = ell m$, - $lim_(x -> a) f(x) / g(x) = ell / m$. // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() = Integration _\* The continuous version of summation._ Given a linear function, can easily compute its underline area, which is just trapezoid or triangle. #figure( image("img/linear_function.png", width: 40%), caption: [A linear function $f(x)=x$] ) Problem of area finding arises when the function of interest is no longer linear: what if we want to find the underline area of an sinusoid, or an exponential function? *Motivation.* Consider a function $f: [a, b] -> RR$ defined on a closed interval $[a, b]$, where $a < b$. We define the _signed area_ $A$ of $f$ by the following: - area above the $x$-axis are positive, and - area below the $x$-axis are negative. #figure( image("img/integral_example.png", width:40%), caption: [Signed area of $f(x)$.] ) We write $ A = integral^b_a f(x) dif x. $ The symbol $integral$ is meaning for "integration", and $dif x$, also known as _differential_, is used to reminding us $x$ is the variable we are integrating with. Irrigorously speaking, we may seen $dif x$ as an infinitesimal increment of $x$. #rect[ _Remark._ Integration and differentiation are inverse to each other. Consider a function $f(x)$, it is always feasible#super[$dagger$] to have $ f(x) = integral [frac(dif, dif x)f(x)] dif x. $ $(dagger)$ Unless $f$ is not differentiable for all points on its domain. ] *Definition.* Define $i in {1, ..., n}$, $Delta x = (b-a)/n$, and for every $x^*_i in [x_i, x_i + Delta x]$, the infinite integral of $f$ can be approximated by _Riemann sum_: $ integral^b_a f(x) dif x approx sum^n_(i=1) f(x^*_i) Delta x. $ As $n -> infinity$, we can accurately calculate the definite integral of $f$, that is $ integral^b_a f(x) dif x = lim_(n->infinity) sum^n_(i=1) f(x^*_i) Delta x. $ #rect[ _Remark._ This formula characterized the intuition of _Riemann integral_: we can approximate the value of the indefinite integral of a given function $f$ by chopping the underline area of $f$ into $n$ small rectangles, sumYan up the area of each rectangle gives the approximation. The more rectangles we chopped, the more accurate the approximation we have. ] *Definition.* Given a function $f: RR arrow.r RR$, we call $ F(x) equiv integral f(x) dif x $ the _antiderivative_ of $f$. *Example.* Given $f(x) = sin(x)$, $ F(x) = -cos(x) + c $ is the antiderivative of $f$, where $c in RR$ is an arbitrary constant. We can verify this fact by computing $F'(x)$. *Proposition (Properties of Integration).* - For arbitrary continuous function $f, g: RR -> RR$, $ integral f(x) + g(x) dif x = integral f(x) dif x + integral g(x) dif x. $ - For arbitrary continuous function $f: RR -> RR$ and scalar $a in RR$, $ integral a f(x) dif x = a integral f(x) dif x. $ - For arbitrary integrable function $f: RR -> RR$, interval $[a, b] subset.eq RR$, $c in [a, b]$, $ integral_a^b f(x) dif x = integral_a^c f(x) dif x + integral_c^b f(x) dif x. $ *Example.* Consider $f(x) = e^(-x)$ and $g(x) = 6x^2$. We can see that $ integral f(x) + 2g(x) dif x &= integral e^(-x) + 12 x^2 dif x \ &= -e^(-x) + 4x^3 + c, $ and $ integral f(x) dif x + 2 integral g(x) dif x &= integral e^(-x) dif x + 2 integral 6x^2 dif x \ &= -e^(-x) + c_1 + 2 times 2 x^3 + c_2 \ &= -e^(-x) + 4 x^3 + c $ *Theorem (Fundamental Theorem of Calculus).* If $f: [a, b] -> RR$ is continuous over $[a, b]$ and $F$ is an antiderivative of $f$, then $ integral^a_b f(x) dif x = F(b) - F(a). $ == Initial Value Problem (IVP) _\* Solve the undetermined constant $c$ with given constraint(s)._ *Example.* What is the antiderivative of $f(x) = 1/(2x) + sec^2(pi x)$, with $F(1) = 0$? Step 1: Find the antiderivative of $f$. $ F(x) &= integral f(x) dif x \ &= integral 1/(2x) + sec^2(pi x) dif x\ &= 1/2 ln(x) + 1/pi tan(pi x) + c $ Step 2: Solve $c$ with the given constraint $F(1) = 0$. $ F(1) &= 0\ 1/2 ln(1) + 1/pi tan(pi) + c &= 0\ c &= 0 $ Combining results above, we have $ F(x) = 1/2 ln(x) + 1/pi tan(pi x) $ == Integration Techniques === U-Substitution *Theorem (U-Substitution).* Let $f: [a, b] -> RR$ and $G: [alpha, beta] -> RR$, by carefully choosing a function $u(x)$, we can write the definite integral of $f$ in terms of $G$ and $u$, that is: $ integral^b_a f(x) dif x = integral^alpha_beta G(u)/(u'(x)) dif u. $ *Example.* Consider $ integral_0^(pi/3) tan(x) dif x. $ We will compute this definite integral step by step: + *Choose an appropriate $u(x):$* Let $u(x) = cos(x)$. + *Compute write $f(x)$ in terms of $G(u) / (u'(x)):$* $ G(u) / (u'(x)) = 1/u.$ + *Find the changed upper and lower bound of definite integral:* $alpha = u(0) = 1, beta = u(pi/3) = 1/2.$ + *Compute the definite integral* by putting all together: $ integral_0^(pi/3) tan(x) dif x &= integral_0^(pi/3) tan(x) dif x \ &= integral_0^(pi/3) sin(x)/cos(x) dif x \ &= integral_(1/2)^1 1/u dif u \ &= [ ln|u| ]^0_(1/2)\ &= ln(1) - ln(1/2)\ &= ln(2) $ === Integration By Parts *Theorem (Integration By Parts).* Sometime is simply written "by parts" for shorthand. $ integral^b_a u(x)v'(x) dif x = [u(x)v(x)]^b_a - integral^b_a u'(x)v(x) dif x. $ #rect([ _Remark._ To apply integration by parts, we need to select appropriate $u(x)$ and $v'(x)$ before we actually begin applying the formula. Sometime it may seem hard to have an idea of assign which to which in the first place, but there's a general rule: #align(center)[ inverse trigs --------- logs --------- polys --------- trigs/exps ] Functions on the right are likely to be selected as $v'(x)$, in which we are going to integrate with, in the later calculation; whereas functions on the left are likely to be selected as $u(x)$, in which we are going to differentiate. The intuition behind is because inverse functions and logarithmic functions, like $arctan(dot) "and" ln(dot)$, are hard to integrates, you are encouraged to try to find the antiderivative of those by yourself (either by applying u-sub or by parts is doable) and it will be an excellent exercise. But the key is that, once we differentiate them, they become a fraction which we can seek techniques already learnt to find a solution. ]) *Example.* Compute the integral by using integration by parts $ integral x arctan(x) dif x. $ By applying the technique introduced above, define: $ u(x) = arctan(x), v'(x) = x, $ and it follows that $ u'(x) = 1/(1+x^2), v(x) = 1/2 x^2. $ By substituting the result into the formula of integration by parts gives: $ integral x arctan(x) dif x &= 1/2 x^2 arctan(x) - 1/2 integral x^2 / (1 + x^2) dif x \ &= 1/2 x^2 arctan(x) - 1/2 integral (1 + x^2 - 1) / (1 + x^2) dif x \ &= 1/2 x^2 arctan(x) - 1/2 integral 1 - 1/(1 + x^2) dif x \ &= 1/2 x^2 arctan(x) - 1/2 x + 1/2 arctan(x) + c $ *Example.* Compute the indefinite integral $ I = integral e^x sin(x) dif x. $ Since trigonometric and exponential functions are interchangeably selected as $u(x)$, so we are going to do one case here, the remaining is left as exercise. Define $ u(x) = e^x, v'(x) = sin(x), $ therefore we have $ u'(x) = e^x, v(x) = -cos(x) $ which follows that $ I = -e^x cos(x) + integral e^x cos(x) dif x. $ Furthermore, apply by parts twice, with $u(x) = e^x, v'(x) = cos(x)$, we have $ I &= -e^x cos(x) + e^x sin(x) - integral e^x sin(x) dif x + c\ I &= -e^x cos(x) + e^x sin(x) - I + c\ 2I &= e^x sin(x) - e^x cos(x) + c\ I &= 1/2 e^x sin(x) - 1/2 e^x cos(x) + c $ === Tabular Method Sometime we find it is hard to solve an integral with applying integration by one or two times. In this case, we can draw a table to assist us, to make the computation procedure more clear and well-organized. *Example.* Compute the following integral: $ integral x^4 sin(x) dif x $ We have seen this pattern quite a lot as we have some intuition that thinking this can be solved by applying integration by parts. As the general trend of choosing $u(x)$ and $v'(x)$, let's define $ u(x) = x^4, v'(x) = sin(x). $ Then, we can draw a table to trace the computation steps while we are doing by parts: #figure( image("img/tabular-method.png", width: 25%), caption: [Tabular Method] ) Firstly make a table contains three columns, where - the first column indicates the sign in front to the integration we have on each stage, - the second column indicates the $u(x)$ in each stage of the integration we have, - the third column indicates the $v'(x)$ in each stage of the integration we have. Then, by multiplying each term as the red arrows indicate, we end up with $ integral x^4 sin(x) dif x &= underbrace(+,"Sign") space underbrace(x^4, u(x)) times underbrace((-cos(x)), v'(x))\ &quad quad - space 4x^3 times (-sin(x))\ &quad quad + space 12x^2 times cos(x)\ &quad quad - space 24x times sin(x) + c\ &= -x^4cos(x) + 4x^3sin(x) + 12x^2cos(x) - 24 x sin(x) - 24cos(x) + c. $ === Partial Fraction Decomposition (PFD) Sometimes, it is easier to deal with two or three simple, separated fractions than to deal with one complicated fraction. For example $ 2 / (x^2 - 1) $ can be written as $ - 1/(x-1) + 1/(x+1) $ as you can verify. // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() = Matrix Operations == Eigenvalues and Eigenvectors = Multi-Variable Calculus = Regression Analysis = Differential Equations (DE) == First Order DE == Second Order DE == Stability of DE Solutions = Non-linear System of Equations // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() = Appendix == Commonly Used Integration Formula *Basic Integration Rules* #align(center, table( columns: 2, align: horizon, inset: 10pt, [$ f(x) $], [$ integral f(x) dif x $], [$ x^n, n eq.not 1 $], [$ 1/(n+1) x^(n+1) + c $], [$ 1/x $], [$ ln(x) + c $], [$ e^(a x) $], [$ 1/a e^(a x) + c $], [$ sin(x) $], [$ -cos(x) + c $], [$ cos(x) $], [$ sin(x) + c $], [$ sec^2(x) $], [$ tan(x) + c $], [$ sec(x)tan(x) $], [$ sec(x) + c$], [$ csc^2(x) $], [$ -cot(x) + c $], [$ csc(x)cot(x) $], [$-csc(x) + c $], [$ 1/(x^2 + a^2) $], [$ 1/a arctan(x/a) + c $], )) // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- #pagebreak() == Trigonometric Identities $ sin(-x) = -sin(x)\ cos(-x) = cos(x)\ sin^2(x) + cos^2(x) = 1\ sin(x plus.minus y) = sin(x)cos(y) plus.minus cos(x)sin(y)\ cos(x plus.minus y) = cos(x)cos(y) minus.plus sin(x)sin(y)\ sin(2x) = 2sin(x)cos(x)\ cos(2x) = cos^2(x) - sin^2(x)\ tan(x) = sin(x)/cos(x)\ sec(x) = 1/cos(x)\ csc(x) = 1/sin(x)\ 1+tan^2(x) = sec^2(x) $
https://github.com/matte1/rules_typst
https://raw.githubusercontent.com/matte1/rules_typst/main/examples/example.typ
typst
$ A = pi r^2 $ $ "area" = pi dot "radius"^2 $ $ cal(A) := { x in RR | x "is natural" } $ #let x = 5 $ #x < 17 $ #figure( image("examples/smile.svg", width: 80%), caption: [ Smile you have an image! ], ) #figure( image("examples/frown.svg", width: 80%), caption: [ Smile you have an image! ], )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-34.typ
typst
Other
// Test the `zip` method. #test(().zip(()), ()) #test((1,).zip(()), ()) #test((1,).zip((2,)), ((1, 2),)) #test((1, 2).zip((3, 4)), ((1, 3), (2, 4))) #test((1, 2, 3, 4).zip((5, 6)), ((1, 5), (2, 6))) #test(((1, 2), 3).zip((4, 5)), (((1, 2), 4), (3, 5))) #test((1, "hi").zip((true, false)), ((1, true), ("hi", false)))
https://github.com/mismorgano/UG-DifferentialGeometry23
https://raw.githubusercontent.com/mismorgano/UG-DifferentialGeometry23/main/Tareas/Tarea-02/Tarea-02.typ
typst
#let title = [ Geometria Diferencial\ Tarea 2 ] #let author = [ <NAME> ] #let book = [ Differential Geometry of Curves and Surfaces ] #let v = $bold(v)$ #let w = $bold(w)$ #let u = $bold(u)$ #let cross = $times$ #set text(12pt, font: "New Computer Modern") #set enum(numbering: "a)") #set math.equation(numbering: "(1)", supplement: [Eq.]) #align(center, text(17pt)[ *#title*\ #author ]) Del libro *#book*. = Problemas == Problema 1 Dados los vectores $#v!= 0$ y $#w$, muestra que existe un vector $#u$ tal que $#u cross #v = #w$ si y solo si $#v$ es perpendicular a $#w$. ¿Este vector queda determinado de manera unica? Sino, ¿Cual es la solución mas general? *Demostración:* Supongamos primero que existe $#u in RR^3$ tal que $#u cross #v = #w$, entonces se cumple que $(#u cross #v) dot #v = 0$, es decir $#w dot #v = 0$. Para la implicación contraria tenemos que $#v dot #w = 0$ y supongamos que existe $#u in RR^3$ tal que $#u cross #v = #w$, entonces se debe cumplir que $ w_1 = u_2v_3 - u_3v_2, quad w_2 = u_3v_1 -u_1v_3, quad w_3 = u_1v_2 - u_2v_1, $ lo cual lo podemos ver como $ A := mat( 0, v_3, -v_2; -v_3, 0, v_1; v_2, -v_1, 0 ) dot vec(u_1, u_2, u_3) = vec(w_1, w_2, w_3). $ Notemos que $det(A) = 0$, entonces el sistema tiene infinitas soluciones o no tiene solución.tenmos los siguientes casos: #enum[_Las tres entradas de $v$ son distintas de cero,_ En este caso se cumple que $det(A) != 0$ y por tanto existe solución y ademas es unica.][_Una entrdad de $v$ es cero._ Sin perdida de generalidad sea $v_1=0$. En este caso tenemos que $ w_1 = u_2v_3 - u_3v_2, quad w_2 = -u_1v_3, quad w_3 = u_1v_2, $ y por tanto $u_1 = w_3/v_2 = -w_2/v_3$ ][_Dos entradas de $v$ son cero._ Sin perdida de generalidad sean $v_1 = 0$, $v_2=0$. Tenemos que $ w_1 = u_2v_3, quad w_2 = -u_1v_3, quad w_3 = 0$, lo cual implica que $u_1 = -w_2/v_3$ y $u_2 = w_1/v_3$ y $u_3 = t$, $t in RR$, por lo cual $u$ no es unico, ademas se debe cumplir que $w_3 = 0$, por lo que $u$ no siempre existe. ] == Problema 2 Sean $u(t) = (u_1(t), u_2(t), u_3(t))$ y $v(t) = (v_1(t), v_2(t), v_3(t))$ funciones diferenciables del intervalo Las derivadas $u'(t)$ y $v'(t)$ satisfacen las condiciones $ u'(t) = a u(t) + b v(t), quad v'(t) = c u(t) -a v(t), $ donde $a, b, c$ son constantes. Muestra que $u(t) cross v(t)$ es un vector constante. *Demostración:* Para ver que $u(t) cross v(t)$ es constante probaremos que $d/(d t) (u(t) cross v(t))$ es igual a cero. Recordemos que $ d/(d t) (u(t) cross v(t)) = (d u(t))/(d t) cross v(t) + u(t) cross (d v)/(d t), $ usando las hipotesis tenemos que $ d/(d t) (u(t) cross v(t)) = (a u(t) + b v(t)) cross v(t) + u(t) cross (c u(t) -a v(t)), $ por un lado tenemos que $ (a u(t) + b v(t)) cross v(t) &= a u(t) cross v(t) + b v(t) cross v(t) \ &= a u(t) cross v(t), $ y por otro lado tenemos que $ u(t) cross (c u(t) - a v(t)) &= -(c u(t) - a v(t)) cross u(t) = (a v(t) - c u(t)) cross u(t) \ &= a v(t) cross u(t) - c u(t) cross u(t) \ &= a v(t) cross u(t). $ De lo anterior obtenemos que $ d/(d t) (u(t) cross v(t)) = a u(t) cross v(t) + a v(t) cross u(t) = a u(t) cross v(t)- a u(t) cross v(t) = bold(0), $ como queremos. == Problema 3 Encuentra todos los vectores unitarios que son perpendiculares al vector $(2, 2, 1)$ y paralelos al plano determinado por los puntos $(0, 0, 0)$, $(1, -2, 1)$, $(-1, 1, 1)$. *Solución:* Sea $ a x + b y + c z +d = 0$ la ecuación del plano, entonces al sustituir los puntos que lo determinan obtenemos que $d =0$, $a - 2b +c = 0$ y $-a + b + c = 0$ lo cual implica que $2c = b$ y que $2a = 3b$, haciendo $c=1$, obtenemos $b=2$, $a=3$, entonces la ecuación del plano es $ 3x+2y+z = 0, $ su vector normal es $n = (3, 2, 1)$. Supongamos $v =(x, y, z)$ es perpendicular a $(2, 2, 1)$ y además es paralelo al plano, entonces es ortogonal al vector normal, por lo cual se cumplir que $ 2x + 2y+z = 0 quad "y" quad 3x + 2y +z = 0. $ De lo anterior tenemos que $x=0$ y que $z = -2y$, se sigue que $v = (0, y, -2y)$, para que $v$ sea unitario debemos normalizarlo por su norma, la cual vale: $ norm(v) = sqrt(y^2 + 4y^2) = sqrt(5)abs(y), $ es decir $v = 1/sqrt(5)(0, y/abs(y), -2y/abs(y))$, si $y>0$ entonces $v=(0, 1/sqrt(5), -2/sqrt(5))$ y si $y<0$ obtenemos $v = (0, -1/sqrt(5), 2/sqrt(5))$.
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/compiler/weeks/week1.typ
typst
#import "../../utils.typ": * #section("The 3 architectures") - system languages - byte code languages - runtime languages #subsection("System languages") Compiler -> Machine code\ byte code languages -> compiler -> byte code -> JIT(just in time) compiler -> runtime\ runtime languages -> JIT compiler -> runtime #section("Compiler architecture") - #text(red, size: 15pt)[lexer] (lexical analysis) - input: written code from programmer - output: terminalsymbols/_tokens_ - #text(red, size: 15pt)[parser] (syntax analysis) - output: syntax tree - #text(red, size: 15pt)[semantic checker] (semantic analysis) - output: temporary view - #text(red, size: 15pt)[optimization] (optional) - output: temporary view - #text(red, size: 15pt)[code generation] - machine code / byte code etc, depends on language architecture - #text(red, size: 15pt)[temporary view] (intermediate representation) - defines code as data structure -> machine code #section("Runtime") #align(center, [#image("../../Screenshots/2023_09_18_08_43_01.png", width: 30%)]) - #text(red, size: 15pt)[loader] - loads machine code into memory, starts execution - #text(red, size: 15pt)[Interpreter] - reads instructions and emulates this software - #text(red, size: 15pt)[JIT (Just In Time) Compiler] - translates code into hardware instructions - this is the entire reason why js is cross platform. A JIT exists for every platform. - #text(red, size: 15pt)[Hardware instruction -> native instruction] - instruction supported natively on hardware - #text(red, size: 15pt)[metadata, heap + stack] - handlings of infos, objects, lifetimes etc - #text(red, size: 15pt)[Garbage Collection] - automatic freeing of memory (evil) #section("Syntax and Semantic") - #text(red, size: 15pt)[Syntax] - defines forms and rules for language - defined by - amount of tokens/terminalsymbols - amount of non-terminal symbols (tokens that have multiple meanings -> result of a production) - amount of productions (syntax rule) - start symbol - #text(red, size: 15pt)[Semantic] - defines meaning of program #section("EBNF (Extended Backus-Naur Form)") This is the grammar definition language.\ It can be used to create things like calculators or syntax rules for programming languages.\ #columns(2, [ #align( center, [#image("../../Screenshots/2023_09_18_09_08_39.png", width: 100%)], ) #colbreak() #align(center, [#text(red, size: 15pt)[Rules for EBNF]]) #align( center, [#image("../../Screenshots/2023_09_18_09_09_15.png", width: 100%)], ) ]) - #text( teal, size: 12pt, )[Original Backus Naur form with := instead of = and without repeatable tokens] - #text( teal, size: 12pt, )[ISO Version with semicolon at the end -> something = \[ "(" something ")" \]]; - #text(teal, size: 12pt)[ABNF -> Augmented Backus Naur Form]; Special cases:\ - """ -> this is considered to be a token/terminalsymbol - "A" | .. | "Z" -> is considered to be a symbol between A and Z - _*Whitespaces are ignored*_ - unless syntax considers them -> python F\# - Comments are also ignored #subsection("Example Grammar for calculator") ```rs // standard grammar for calculator // made with original Backus Naur Form -> this version has no repeatable tokens // exp := term | exp + term | exp - term // term := factor | factor * term | factor / term | factor % term // factor := number | ( exp ) ``` compared to a simpler example: (not a full calculator) #columns( 2, [ #image("../../Screenshots/2023_09_18_09_22_56.png", width: 70%) #colbreak() Here the optional parts are marked with {} which makes the grammar smaller, however it also makes it harder to read imo.\ ], ) #subsection("Ambiguous Syntax") #columns( 2, [ #align( center, [#image("../../Screenshots/2023_09_18_09_41_40.png", width: 100%)], ) The issue is that there is no clear rule which expression to evaluate first.\ Here one would have to change the first expression to number in order to fix this issue. #colbreak() #align( center, [#image("../../Screenshots/2023_09_18_09_42_10.png", width: 100%)], ) ], )
https://github.com/xplosionmind/cv
https://raw.githubusercontent.com/xplosionmind/cv/main/cv.typ
typst
#import "/template/cv.typ": * // Load CV data from YAML #let cvdata = yaml("cv.yml") #let uservars = ( headingfont: "Chivo", bodyfont: "Garamond Libre", // Set font for body fontsize: 10pt, // 10-12pt linespacing: 5pt, showAddress: false, showNumber: false, ) #let cvinit(doc) = { doc = setrules(uservars, doc) doc = showrules(uservars, doc) doc } // Content #show: doc => cvinit(doc) #cvheading(cvdata, uservars) #cveducation(cvdata) #cvwork(cvdata) #cvaffiliations(cvdata) #cvprojects(cvdata) #cvawards(cvdata) #cvcertificates(cvdata) #cvpublications(cvdata) #cvskills(cvdata) #cvreferences(cvdata) #endnote
https://github.com/augustebaum/epfl-thesis-typst
https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/main/ch3_math.typ
typst
MIT License
= Mathematics In this chapter we will see some examples of mathematics. #lorem(100) == Very important formulas #lorem(100) $ d / (d t) vec(P_0, P_1, P_T, delim: "[") = vec( P_1 / tau_(1 0) + P_T / tau_T - P_0 / tau_"ex", - P_1 / tau_(1 0) - P_T / tau_"isc" + P_0 / tau_"ex", P_1 / tau_"isc" - P_T / tau_T, , delim: "[", ) $ #lorem(70) a hopefully inline math equation: $h = 3$ #lorem(30) $ macron(I_f)(arrow(r)) = gamma(arrow(r)) ( 1 - (tau_T P_T^"eq" (1-exp (-((T_p - t_p)) / (tau_T)))) / (1 - exp (-((T_p - t_p)) / (tau_T) + k_2 t_p)) times ((exp (k_2 t_p )-1)) / (t_p) ) $ #lorem(100)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/conchord/0.1.0/README.md
markdown
Apache License 2.0
# Conchord `conchord` (concise chord) is a [typst](https://github.com/typst/typst) package to write lyrics with chords and generate colorful fretboard diagram (aka chord diagram). It is inspired by [chordx](https://github.com/ljgago/typst-chords) package and my previous tiny project for generating chord diagrams svgs. # Overview `conchord` makes it easy to add new chords, both for diagrams and lyrics. Unlike [chordx](https://github.com/ljgago/typst-chords), you don't need to think about layout and pass lots of arrays for drawing barres. Just pass a string with holded frets and it will work: ```ts #import "@preview/conchord:0.1.0": new-chordgen, overchord #let chord = new-chordgen() #box(chord("x32010", name: "C")) #box(chord("x33222", name: "F#m/C#")) #box(chord("x,9,7,8,9,9")) ``` ![](examples/simple.png) > `x` means closed string, `0` is open, other number is a fret. In case of frets larger than `9` frets should be separated with commas, otherwise you can list them without any separators. > Chord diagram works like a usual block, so to put them into one line you need to wrap them into boxes. In real code it is recommended to create a wrapper function to customize box margins etc (see larger example below). It is easy to customize the colors and styles of chords with `colors` argument and `show` rules for text. You can also put `!` and `*` marks in the end of the string to force diagram generation. `!` forces barre, `*` removes it: ```ts #let custom-chord = new-chordgen(string-number: 3, colors: (shadow-barre: orange, grid: gray.darken(30%), hold: red, barre: purple) ) #set text(fill: purple) #box(custom-chord("320", name: "C")) #box(custom-chord("2,4,4,*", name: "Bm")) #box(custom-chord("2,2,2, *")) #box(custom-chord("x,3,2, !")) ``` ![](examples/crazy.png) > NOTE: be careful when using **!**, if barre cannot be used, it will result into nonsense. For lyrics, you don't need to add chord to word and specify the number of char in words (unlike [chordx](https://github.com/ljgago/typst-chords)). Simply add `#overchord` to the place you want a chord. Compose with native Typst stylistic things for non-plain look (you don't need to dig into [chordx](https://github.com/ljgago/typst-chords)'s custom arguments): ```ts #let och(it) = overchord(strong(it)) === #raw("[Verse 1]") #och[Em] Another head #och[C] hangs lowly \ #och[G] Child is slowly #och[D] taken ... ``` > Complete example of lyrics with chords (see [full source](examples/zombie.typ)): ![](examples/zombie.png) # Features I was quite amazed with general idea of [chordx](https://github.com/ljgago/typst-chords), but a bit frustated with implementation, so I decided to quickly rewrite my old js code to typst. I use `cetz` there, so code is quite clean. > Note: This package doesn't use any peice of [chordx](https://github.com/ljgago/typst-chords), only the general idea is used. Brief comparison may be seen there, some concepts explained below: ![](examples/compare.png) ## Think about frets, not layout Write frets for chord as you hold it, like a string like "123456" (see examples above). You don't need to think about layouting and substracting frets, `conchord` does it for you. > NOTE: I can't guarantee that will be the best chord layout. Moreover, the logic is quite simple: e.g., barre can't be multiple and can't be put anwhere except first bar in the image. However, surprisingly, it works well in almost all of the common cases, so the exceptions are really rare. If you need to create something too _custom/complex_ ~~(but not _concise_)~~, maybe it is worth to try [chordx](https://github.com/ljgago/typst-chords). You can also try using core function `render-chord` for more manual control, but it is still limited by one barre starting from one (but that barre may be shifted). If you think that feature should be supported, you can create issue there. ## Shadow barre Some chord generators put barre only where it _ought to_ be (any less will not hold some strings). Others put it where it can be (sometimes maximal size, sometimes some other logic). I use simple barre where it **ought to** be, and add _shadow barre_ where it **could** maximally be. You can easily disable it by either setting `use-shadow-barre: false` on `new-chordgen` (only necessary part of barre rendered) or by setting color of `shadow-barre` the same as `barre` (maximal possible barre). ## Name auto-scaling Chord name font size is _reduced_ for _large_ chord names, so the name fits well into chord diagram (see example above). That makes it much more pretty to stack several chords together. To achieve chordx-like behaviour, you can always use `#figure(chord("…"), caption: …)`. ## Easier chords for lyrics Just add chord labels above lyrics in arbitrary place, don't think about what letter exactly it should be located. By default it aligns the chord label to the left, so it produces pretty results out-of-box. You can pass other alignments to `alignment` argument, or use the chords stright inside words. The command is _much_ simplier than chordx (of course, it is a trade-off): ```ts #let overchord(body, align: start, height: 1em, width: -0.25em) = box(place(align, body), height: 1em + height, width: width) ``` Feel free to use it for your purposes outside of the package. It takes on default `-0.25em` width to remove one adjacent space, so - To make it work on monospace/other special fonts, you will need to adjust `width` argument. The problem is that I can't `measure` space, but maybe that will be eventually fixed. - To add chord inside word, you have to add _one_ space, like `wo #chord[Am]rd`. ## Colors Customize the colors of chord elements. `new-chordgen` accepts the `colors` dictionary with following possible fields: - `grid`: color of grid, default is `gray.darken(20%)` - `open`: color of circles for open strings, default is `black` - `muted`: color of crosses for muted strings, default is `black` - `hold`: color of holded positions, default is `#5d6eaf` - `barre`: color of main barre part, default is `#5d6eaf` - `shadow-barre`: color of "unnecessary" barre part, default is `#5d6eaf.lighten(30%)` ## Assertions Currently [chordx](https://github.com/ljgago/typst-chords) has almost no checks inside for correctness of passed chords. `conchord` currently checks for - Number of passed&parsed frets equal to set string-number - Only numbers and `x` passed as frets - All frets fitting in the diagram
https://github.com/antran22/typst-cv-builder
https://raw.githubusercontent.com/antran22/typst-cv-builder/main/lib/resume/header.typ
typst
MIT License
#import "../common.typ": * #import "./components.typ": * #import "@preview/cmarker:0.1.0" #let ResumeProfileEntry(title: "", type: "", url: "") = { stack(dir: ltr, spacing: 0pt)[ #set text(size: 9pt) #ICONS.at(type) #box(width: 0pt) #if url != "" { link(url, title) } else { text(title) } ] } #let ResumeHeader( basic_info: (:), positions: (), profile-picture: image, colored-headers: true, language: "en", ) = { let Name = { align(right)[ #pad(bottom: 5pt)[ #block[ #set text( size: 24pt, style: "normal", font: (display-font), ) #text(fill: accent-color, weight: "bold")[#basic_info.first_name] #text(weight: "bold")[#basic_info.last_name] ] ] ] } let Positions = { set text( accent-color, size: 9pt, weight: "regular", ) align(right)[ #smallcaps[ #positions.join( text[#" "#sym.dot.c#" "], ) ] ] } let Contacts = { let separator = box(width: 2pt) align(right)[ #set text( size: 8pt, weight: "regular", style: "normal", ) #block( align( horizon, stack( dir: ltr, spacing: 2em, ResumeProfileEntry( type: "phone", title: basic_info.phone, url: "tel:" + basic_info.phone ), ResumeProfileEntry( type: "email", title: basic_info.email, url: "mailto:" + basic_info.email ), ResumeProfileEntry( type: "location", title: basic_info.address, ), ) ) ), #v(8pt) #block( align( horizon, stack( dir: ltr, spacing: 2em, ..basic_info.profiles.map(cont => { [ #ResumeProfileEntry( title: cont.username, type: cont.icon, url: cont.url.href, ) ] }) ) ) ) ] } let Profiles = { align(right)[ #set text( size: 8pt, weight: "regular", style: "normal", ) ] } grid( columns: (2cm, 1fr), rows: (2cm), align(left + horizon)[ #block( clip: true, stroke: 1pt, radius: 2cm, width: 2cm, height: 2cm, profile-picture ) ], [ #Name #Positions #pad(top: 5pt, [#Contacts]) #pad(top: 5pt, [#Profiles]) ], ) }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/094.%20cities.html.typ
typst
cities.html Cities and Ambition May 2008 Great cities attract ambitious people. You can sense it when you walk around one. In a hundred subtle ways, the city sends you a message: you could do more; you should try harder.The surprising thing is how different these messages can be. New York tells you, above all: you should make more money. There are other messages too, of course. You should be hipper. You should be better looking. But the clearest message is that you should be richer.What I like about Boston (or rather Cambridge) is that the message there is: you should be smarter. You really should get around to reading all those books you've been meaning to.When you ask what message a city sends, you sometimes get surprising answers. As much as they respect brains in Silicon Valley, the message the Valley sends is: you should be more powerful.That's not quite the same message New York sends. Power matters in New York too of course, but New York is pretty impressed by a billion dollars even if you merely inherited it. In Silicon Valley no one would care except a few real estate agents. What matters in Silicon Valley is how much effect you have on the world. The reason people there care about Larry and Sergey is not their wealth but the fact that they control Google, which affects practically everyone._____How much does it matter what message a city sends? Empirically, the answer seems to be: a lot. You might think that if you had enough strength of mind to do great things, you'd be able to transcend your environment. Where you live should make at most a couple percent difference. But if you look at the historical evidence, it seems to matter more than that. Most people who did great things were clumped together in a few places where that sort of thing was done at the time.You can see how powerful cities are from something I wrote about earlier: the case of the Milanese Leonardo. Practically every fifteenth century Italian painter you've heard of was from Florence, even though Milan was just as big. People in Florence weren't genetically different, so you have to assume there was someone born in Milan with as much natural ability as Leonardo. What happened to him?If even someone with the same natural ability as Leonardo couldn't beat the force of environment, do you suppose you can?I don't. I'm fairly stubborn, but I wouldn't try to fight this force. I'd rather use it. So I've thought a lot about where to live.I'd always imagined Berkeley would be the ideal place — that it would basically be Cambridge with good weather. But when I finally tried living there a couple years ago, it turned out not to be. The message Berkeley sends is: you should live better. Life in Berkeley is very civilized. It's probably the place in America where someone from Northern Europe would feel most at home. But it's not humming with ambition.In retrospect it shouldn't have been surprising that a place so pleasant would attract people interested above all in quality of life. Cambridge with good weather, it turns out, is not Cambridge. The people you find in Cambridge are not there by accident. You have to make sacrifices to live there. It's expensive and somewhat grubby, and the weather's often bad. So the kind of people you find in Cambridge are the kind of people who want to live where the smartest people are, even if that means living in an expensive, grubby place with bad weather.As of this writing, Cambridge seems to be the intellectual capital of the world. I realize that seems a preposterous claim. What makes it true is that it's more preposterous to claim about anywhere else. American universities currently seem to be the best, judging from the flow of ambitious students. And what US city has a stronger claim? New York? A fair number of smart people, but diluted by a much larger number of neanderthals in suits. The Bay Area has a lot of smart people too, but again, diluted; there are two great universities, but they're far apart. Harvard and MIT are practically adjacent by West Coast standards, and they're surrounded by about 20 other colleges and universities. [1]Cambridge as a result feels like a town whose main industry is ideas, while New York's is finance and Silicon Valley's is startups._____When you talk about cities in the sense we are, what you're really talking about is collections of people. For a long time cities were the only large collections of people, so you could use the two ideas interchangeably. But we can see how much things are changing from the examples I've mentioned. New York is a classic great city. But Cambridge is just part of a city, and Silicon Valley is not even that. (San Jose is not, as it sometimes claims, the capital of Silicon Valley. It's just 178 square miles at one end of it.)Maybe the Internet will change things further. Maybe one day the most important community you belong to will be a virtual one, and it won't matter where you live physically. But I wouldn't bet on it. The physical world is very high bandwidth, and some of the ways cities send you messages are quite subtle.One of the exhilarating things about coming back to Cambridge every spring is walking through the streets at dusk, when you can see into the houses. When you walk through Palo Alto in the evening, you see nothing but the blue glow of TVs. In Cambridge you see shelves full of promising-looking books. Palo Alto was probably much like Cambridge in 1960, but you'd never guess now that there was a university nearby. Now it's just one of the richer neighborhoods in Silicon Valley. [2]A city speaks to you mostly by accident — in things you see through windows, in conversations you overhear. It's not something you have to seek out, but something you can't turn off. One of the occupational hazards of living in Cambridge is overhearing the conversations of people who use interrogative intonation in declarative sentences. But on average I'll take Cambridge conversations over New York or Silicon Valley ones.A friend who moved to Silicon Valley in the late 90s said the worst thing about living there was the low quality of the eavesdropping. At the time I thought she was being deliberately eccentric. Sure, it can be interesting to eavesdrop on people, but is good quality eavesdropping so important that it would affect where you chose to live? Now I understand what she meant. The conversations you overhear tell you what sort of people you're among._____No matter how determined you are, it's hard not to be influenced by the people around you. It's not so much that you do whatever a city expects of you, but that you get discouraged when no one around you cares about the same things you do.There's an imbalance between encouragement and discouragement like that between gaining and losing money. Most people overvalue negative amounts of money: they'll work much harder to avoid losing a dollar than to gain one. Similarly, although there are plenty of people strong enough to resist doing something just because that's what one is supposed to do where they happen to be, there are few strong enough to keep working on something no one around them cares about.Because ambitions are to some extent incompatible and admiration is a zero-sum game, each city tends to focus on one type of ambition. The reason Cambridge is the intellectual capital is not just that there's a concentration of smart people there, but that there's nothing else people there care about more. Professors in New York and the Bay area are second class citizens — till they start hedge funds or startups respectively.This suggests an answer to a question people in New York have wondered about since the Bubble: whether New York could grow into a startup hub to rival Silicon Valley. One reason that's unlikely is that someone starting a startup in New York would feel like a second class citizen. [3] There's already something else people in New York admire more.In the long term, that could be a bad thing for New York. The power of an important new technology does eventually convert to money. So by caring more about money and less about power than Silicon Valley, New York is recognizing the same thing, but slower. [4] And in fact it has been losing to Silicon Valley at its own game: the ratio of New York to California residents in the Forbes 400 has decreased from 1.45 (81:56) when the list was first published in 1982 to .83 (73:88) in 2007._____Not all cities send a message. Only those that are centers for some type of ambition do. And it can be hard to tell exactly what message a city sends without living there. I understand the messages of New York, Cambridge, and Silicon Valley because I've lived for several years in each of them. DC and LA seem to send messages too, but I haven't spent long enough in either to say for sure what they are.The big thing in LA seems to be fame. There's an A List of people who are most in demand right now, and what's most admired is to be on it, or friends with those who are. Beneath that, the message is much like New York's, though perhaps with more emphasis on physical attractiveness.In DC the message seems to be that the most important thing is who you know. You want to be an insider. In practice this seems to work much as in LA. There's an A List and you want to be on it or close to those who are. The only difference is how the A List is selected. And even that is not that different.At the moment, San Francisco's message seems to be the same as Berkeley's: you should live better. But this will change if enough startups choose SF over the Valley. During the Bubble that was a predictor of failure — a self-indulgent choice, like buying expensive office furniture. Even now I'm suspicious when startups choose SF. But if enough good ones do, it stops being a self-indulgent choice, because the center of gravity of Silicon Valley will shift there.I haven't found anything like Cambridge for intellectual ambition. Oxford and Cambridge (England) feel like Ithaca or Hanover: the message is there, but not as strong.Paris was once a great intellectual center. If you went there in 1300, it might have sent the message Cambridge does now. But I tried living there for a bit last year, and the ambitions of the inhabitants are not intellectual ones. The message Paris sends now is: do things with style. I liked that, actually. Paris is the only city I've lived in where people genuinely cared about art. In America only a few rich people buy original art, and even the more sophisticated ones rarely get past judging it by the brand name of the artist. But looking through windows at dusk in Paris you can see that people there actually care what paintings look like. Visually, Paris has the best eavesdropping I know. [5]There's one more message I've heard from cities: in London you can still (barely) hear the message that one should be more aristocratic. If you listen for it you can also hear it in Paris, New York, and Boston. But this message is everywhere very faint. It would have been strong 100 years ago, but now I probably wouldn't have picked it up at all if I hadn't deliberately tuned in to that wavelength to see if there was any signal left._____So far the complete list of messages I've picked up from cities is: wealth, style, hipness, physical attractiveness, fame, political power, economic power, intelligence, social class, and quality of life.My immediate reaction to this list is that it makes me slightly queasy. I'd always considered ambition a good thing, but I realize now that was because I'd always implicitly understood it to mean ambition in the areas I cared about. When you list everything ambitious people are ambitious about, it's not so pretty.On closer examination I see a couple things on the list that are surprising in the light of history. For example, physical attractiveness wouldn't have been there 100 years ago (though it might have been 2400 years ago). It has always mattered for women, but in the late twentieth century it seems to have started to matter for men as well. I'm not sure why — probably some combination of the increasing power of women, the increasing influence of actors as models, and the fact that so many people work in offices now: you can't show off by wearing clothes too fancy to wear in a factory, so you have to show off with your body instead.Hipness is another thing you wouldn't have seen on the list 100 years ago. Or wouldn't you? What it means is to know what's what. So maybe it has simply replaced the component of social class that consisted of being "au fait." That could explain why hipness seems particularly admired in London: it's version 2 of the traditional English delight in obscure codes that only insiders understand.Economic power would have been on the list 100 years ago, but what we mean by it is changing. It used to mean the control of vast human and material resources. But increasingly it means the ability to direct the course of technology, and some of the people in a position to do that are not even rich — leaders of important open source projects, for example. The Captains of Industry of times past had laboratories full of clever people cooking up new technologies for them. The new breed are themselves those people.As this force gets more attention, another is dropping off the list: social class. I think the two changes are related. Economic power, wealth, and social class are just names for the same thing at different stages in its life: economic power converts to wealth, and wealth to social class. So the focus of admiration is simply shifting upstream._____Does anyone who wants to do great work have to live in a great city? No; all great cities inspire some sort of ambition, but they aren't the only places that do. For some kinds of work, all you need is a handful of talented colleagues.What cities provide is an audience, and a funnel for peers. These aren't so critical in something like math or physics, where no audience matters except your peers, and judging ability is sufficiently straightforward that hiring and admissions committees can do it reliably. In a field like math or physics all you need is a department with the right colleagues in it. It could be anywhere — in Los Alamos, New Mexico, for example.It's in fields like the arts or writing or technology that the larger environment matters. In these the best practitioners aren't conveniently collected in a few top university departments and research labs — partly because talent is harder to judge, and partly because people pay for these things, so one doesn't need to rely on teaching or research funding to support oneself. It's in these more chaotic fields that it helps most to be in a great city: you need the encouragement of feeling that people around you care about the kind of work you do, and since you have to find peers for yourself, you need the much larger intake mechanism of a great city.You don't have to live in a great city your whole life to benefit from it. The critical years seem to be the early and middle ones of your career. Clearly you don't have to grow up in a great city. Nor does it seem to matter if you go to college in one. To most college students a world of a few thousand people seems big enough. Plus in college you don't yet have to face the hardest kind of work — discovering new problems to solve.It's when you move on to the next and much harder step that it helps most to be in a place where you can find peers and encouragement. You seem to be able to leave, if you want, once you've found both. The Impressionists show the typical pattern: they were born all over France (Pissarro was born in the Carribbean) and died all over France, but what defined them were the years they spent together in Paris._____Unless you're sure what you want to do and where the leading center for it is, your best bet is probably to try living in several places when you're young. You can never tell what message a city sends till you live there, or even whether it still sends one. Often your information will be wrong: I tried living in Florence when I was 25, thinking it would be an art center, but it turned out I was 450 years too late.Even when a city is still a live center of ambition, you won't know for sure whether its message will resonate with you till you hear it. When I moved to New York, I was very excited at first. It's an exciting place. So it took me quite a while to realize I just wasn't like the people there. I kept searching for the Cambridge of New York. It turned out it was way, way uptown: an hour uptown by air.Some people know at 16 what sort of work they're going to do, but in most ambitious kids, ambition seems to precede anything specific to be ambitious about. They know they want to do something great. They just haven't decided yet whether they're going to be a rock star or a brain surgeon. There's nothing wrong with that. But it means if you have this most common type of ambition, you'll probably have to figure out where to live by trial and error. You'll probably have to find the city where you feel at home to know what sort of ambition you have.Notes[1] This is one of the advantages of not having the universities in your country controlled by the government. When governments decide how to allocate resources, political deal-making causes things to be spread out geographically. No central goverment would put its two best universities in the same town, unless it was the capital (which would cause other problems). But scholars seem to like to cluster together as much as people in any other field, and when given the freedom to they derive the same advantages from it.[2] There are still a few old professors in Palo Alto, but one by one they die and their houses are transformed by developers into McMansions and sold to VPs of Bus Dev.[3] How many times have you read about startup founders who continued to live inexpensively as their companies took off? Who continued to dress in jeans and t-shirts, to drive the old car they had in grad school, and so on? If you did that in New York, people would treat you like shit. If you walk into a fancy restaurant in San Francisco wearing a jeans and a t-shirt, they're nice to you; who knows who you might be? Not in New York.One sign of a city's potential as a technology center is the number of restaurants that still require jackets for men. According to Zagat's there are none in San Francisco, LA, Boston, or Seattle, 4 in DC, 6 in Chicago, 8 in London, 13 in New York, and 20 in Paris.(Zagat's lists the Ritz Carlton Dining Room in SF as requiring jackets but I couldn't believe it, so I called to check and in fact they don't. Apparently there's only one restaurant left on the entire West Coast that still requires jackets: The French Laundry in Napa Valley.)[4] Ideas are one step upstream from economic power, so it's conceivable that intellectual centers like Cambridge will one day have an edge over Silicon Valley like the one the Valley has over New York.This seems unlikely at the moment; if anything Boston is falling further and further behind. The only reason I even mention the possibility is that the path from ideas to startups has recently been getting smoother. It's a lot easier now for a couple of hackers with no business experience to start a startup than it was 10 years ago. If you extrapolate another 20 years, maybe the balance of power will start to shift back. I wouldn't bet on it, but I wouldn't bet against it either.[5] If Paris is where people care most about art, why is New York the center of gravity of the art business? Because in the twentieth century, art as brand split apart from art as stuff. New York is where the richest buyers are, but all they demand from art is brand, and since you can base brand on anything with a sufficiently identifiable style, you may as well use the local stuff.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.Italian TranslationPortuguese TranslationChinese TranslationKorean Translation
https://github.com/eeeem460/typst
https://raw.githubusercontent.com/eeeem460/typst/main/grundy/main.typ
typst
// プリアンブル全体の参考元:https://github.com/sahasatvik/typst-theorems/blob/main/differential_calculus.typ #import "@preview/ctheorems:1.1.2": * #show: thmrules.with(qed-symbol: $square$) // Define theorem environments // 以下、日本語に変更してnumberingを消した。 // 番号なしにする場合 // #let theorem = thmbox("theorem", "定理", fill: rgb("#e8e8f8")).with(numbering: none) #let theorem = thmbox("theorem", "定理", fill: rgb("#e8e8f8")) #let lemma = thmbox( "theorem", // Lemmas use the same counter as Theorems "補題", fill: rgb("#efe6ff"), ) #let corollary = thmbox( "theorem", "系", base: "theorem", // Corollaries are 'attached' to Theorems fill: rgb("#f8e8e8"), ) #let definition = thmbox( "theorem", // Theorem と同じ番号 "定義", fill: rgb("#e8f8e8"), ) #let exercise = thmbox( "exercise", "演習", stroke: rgb("#ffaaaa") + 1pt, base: none, // Unattached: count globally ).with(numbering: "I") // Use Roman numerals // Examples and remarks are not numbered #let example = thmbox("example", "例") #let remark = thmplain("remark", "注意", inset: 0em) // Proofs are attached to theorems, although they are not numbered #let proof = thmproof("proof", "証明", base: "theorem") #let solution = thmplain("solution", "解", base: "exercise", inset: 0em) // #show strong: set text(fill: blue) // Mapping arrow #let mapsto = $arrow.r.bar$ // Operators #let len = (x) => $op(l) (#x)$ // #let mex = (x) => $op("mex") {#x}$ #let mex = (x) => $op("mex") #x$ #let blue(term, color: blue) = { text(color, box[#term]) } // Template // projectの参考元:https://github.com/stepney141/my_typst_template/blob/main/%E3%83%AA%E3%82%A2%E3%83%9A%E3%83%BB%E3%83%AC%E3%83%9D%E3%83%BC%E3%83%88%E7%94%A8/template.typ #let project(title: "", author: "", body) = { set document(author: author, title: title) // フォントの設定 set text(font: ( "Nimbus Roman", // "Hiragino Mincho ProN", // "MS Mincho", "Noto Serif CJK JP", ), size: 11pt, lang: "ja") // 見出しの番号 set heading(numbering: "1.1.") // 行間と字下げ set par(leading: 0.8em, first-line-indent: 1em, justify: true) // 見出しの隙間を調整 show heading: it => [ #v(2em) #it #v(1em) ] // ページ数 set page(numbering: "1 / 1") // タイトルと著者 align(center)[ #block(text(weight: 700, 1.75em, title)) #v(1em) #block(text(1em, author)) #v(1em) ] // 目次 // outline(fill: none, indent: true) body } // ***** start document ***** // #show: project.with(title: "不偏ゲームとGrundy数", author: "えおえお (𝕏 : @eoeo_sub)") #show: project.with(title: "不偏ゲームとGrundy数") 以下、主に将来の自分へ向けたメモであり、@sato (石取りゲームの数学、佐藤文広)を参考にしてまとめる。 // #blue[気になる点があればご連絡いただけると幸いです。] // 目次 #outline(fill: none, indent: true) = 不偏ゲーム *不偏ゲーム*とは以下の性質を満たすゲームである。 - 先手と後手の2人で交互に手を進める。 - 同一局面で選択できる手は先手と後手で等しい。 // - ゲームの終了局面が与えられている。 - どの局面からも有限回の手数で必ず終了局面に到達する。 有名な不偏ゲームとしてはNimが挙げられ、これは後ほど例として取り上げる。 一方で、不偏ゲームではないゲームの例としてオセロが挙げられる。 これは、オセロはある局面で打てる手が先手と後手で異なるためである。 #pagebreak() = 不偏ゲームの数学的な定義 <sec_def> #definition( "不偏ゲーム" )[ (@sato, p. 22) $cal(P)$ を空でない集合、$cal(R)$ を写像 $cal(R) : cal(P) -> 2^cal(P)$ とする。 // さらに、$O$ を $X$ の空でない部分集合で $f(O) = emptyset$ を満たすものとする。 このとき、組 $cal(A) = (cal(P), cal(R))$ のことを*不偏ゲーム*という。 さらに、$cal(P)$ の元を *$cal(A)$ の局面*、$cal(R)$ を*$cal(A)$のルール*という。 また、$cal(R) (P)$ の元を*局面 $P$ の後続局面*という。 // 、$O$を*終了局面の集合*という。 ] #remark[ $2^X$ は $X$ のべき集合である。 ] 以下、@sec_def では $cal(A) = (cal(P), cal(R))$ を不偏ゲームとする。 さらに、本記事では不偏ゲームには有限回の手で終了するという条件を課す。 #definition( "ゲームの進行", )[ (@sato, p. 23) $n > 0$ を自然数とする。$P_1, dots, P_n in cal(P)$ が $P_(i + 1) in cal(R)(P_i) space (i = 1, dots, n - 1)$ を満たすとき、列 $(P_1, dots, P_n)$ は *$P_1$ から始まる長さ $n$ のゲーム列*であるという。 一つの局面 $P$ からなる列 $(P)$ も長さ 1 のゲーム列であるとみなす。 ] #definition("有限性条件")[ (@sato, p. 23) 次を満たすとき、$cal(A)$ を*有限型の不偏ゲーム*という。 - ある $n_0 in NN$ が存在して、$cal(A)$ の長さ $n_0$ 以上のゲーム列が存在しない。 すなわち、$cal(A)$ のゲーム列の長さは有界である。 ] 以下、本記事では有限型の不偏ゲームのみを扱う。 #definition("局面の長さ")[ (@sato, p. 23) 局面 $P in cal(P)$ に対して、$l(P)$ を $P$ から始まるゲーム列の長さの最大値とする。 // また、$P in cal(E)$ に対しては、$l(P) = 1$ と定めることにする。 $len(P)$ は不偏ゲームの有限性条件から一意に定まる。$l(P)$ を*局面 $P$ の長さ* という。 ] #definition( "終了局面" )[ (@sato, p.23) 局面 $P$ が $cal(R)(P) = emptyset$ を満たすとき、$P$ を*終了局面*という。 終了局面全体の集合を $cal(E)$ とおく: $ cal(E) := { P in cal(P) | cal(R)(P) = emptyset} $ $cal(A)$ の有限性から、$cal(E) eq.not emptyset$ となることが分かる。また、$P in cal(E)$ に対して $l(P) = 1$ が成り立つ。 ] #pagebreak() = 不偏ゲームの勝敗 不偏ゲームの勝敗を考える。 #definition( "不偏ゲームの勝敗", )[ (@sato, 補題2.4) $cal(A) = (cal(P), cal(R))$ を不偏ゲームとする。 再帰的に $cal(G)$ と $cal(S)$ を定義する: $ cal(G) &:= cal(E) union { P in cal(P) | forall Q in cal(R)(P), thin Q in cal(S) } \ cal(S) &:= { P in cal(P) | exists Q in cal(R)(P), thin Q in cal(G) } $ $cal(G)$ の元を*後手必勝局面*、$cal(S)$ の元を*先手必勝局面*という。 局面の長さが小さい順に考えることで、任意の $P in cal(P)$ が $P in cal(G) union cal(S)$ となることが分かる。さらに、$cal(P) = cal(G) union.sq cal(S)$ となることも分かる。 #blue[これちゃんと再帰的に定義できてますかね?] ] <df_win_lose> #remark[ @sato では @df_win_lose を定義ではなく補題として与えている。 ] #remark[ 上の定義で定まる勝敗を考えたゲームを*正規形*の不偏ゲームという。本記事では正規形の不偏ゲームのみを扱う。 ] 不偏ゲームの勝敗を直観的に説明する。 - 不偏ゲームの勝敗は、交互に手を打ってこれ以上手を進められなくなった方の負け、というルールのことである。 - 後手必勝局面とは、その局面で手番のものが負けという意味である。つまり、その局面を渡したものが勝ちである。 - 先手必勝局面とは、その局面で手番のものが勝ちという意味である。つまり、その局面を渡したものが負けである。 後手必勝であるか先手必勝であるかは、以下のように順に定まっていく。 - ( $l(P) = 1$ ) これ以上手が打てない終了局面は後手必勝である。( $cal(E) subset cal(G)$ のこと。) - ( $l(P) = 2$ ) 後手必勝局面である終了局面に、一手で進められる局面は先手必勝局面である。 - ( $l(P) >= 3$ ) 後続局面がすべて先手必勝局面であるような局面は後手必勝であり、後続局面に後手必勝局面が存在するような局面は先手必勝である。 すなわち、先手必勝局面からはある手を選び続けることで、 (先手必勝)$->$(後手必勝)$->$(先手必勝)$->$(後手必勝)$-> dots ->$(先手必勝)$->$(終了局面) となるゲーム列を必ず構成することができる。なぜなら、先手必勝局面からは必ず後手必勝局面を選択でき、 後手必勝局面では先手必勝となる局面しか選択できないからである。 #pagebreak() = 不偏ゲームの例 <game_ex> #example( "一山Nim", )[ $n$ 個の石が積み上げられている山が一つある。このとき、二人で交互に山から好きなだけ石を取り合う。 先に石を取ることができなくなった方の負けである。このゲームを *一山Nim* という。 一山Nimを不偏ゲームの定義にもとづいて集合論の言葉で述べる。 局面全体の集合を $cal(P) = {0, 1, dots, n}$ とおき、ルール$cal(R) : cal(P) -> 2^cal(P)$ を $ cal(R)(0) &= emptyset, quad \ cal(R)(i) &= {0, dots, i - 1} quad (0 < i <= n) $ と定める。このとき、組 $(cal(P), cal(R))$ は一山Nimを表す有限型の不偏ゲームである。 局面 $i$ は山に $i$ 個の石が残っている局面を表している。 さらに、後手必勝局面全体の集合 $cal(G)$ と先手必勝局面全体の集合 $cal(S)$ は、 $ cal(G) &= { 0 } \ cal(S) &= {1, dots, n} $ である。なぜなら、定義より終了局面 $0$ は後手必勝局面であり、任意の局面 $i > 0$ に対して、$i$ からは後手必勝局面 $0 in cal(R)(i)$ に遷移できるからである。 これを表にすると、 #align(center)[ #figure(table( columns: 9, inset: 8pt, $i$, [0], [1], [2], [3], [4], [5], [6], [$dots$], [$cal(G) \/ cal(S)$], $cal(G)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(S)$, $dots$, )) <table1> ] となる。 上の表で、$cal(G)$ は後手必勝局面、$cal(S)$ は先手必勝局面という意味である。 競技プログラミングでは、このような先後の必勝判定を bool 型の配列で行うことがある。 その際には、局面の長さが小さい順に判定を行えばよい。 ] <one_nim> #example( "制限一山Nim", )[ 一山Nimで一度に取ることができる石の数を $3$ 個以下に制限に制限したものを 制限一山Nimという。 制限一山Nimをモデル化する。 局面全体の集合は一山Nimと変わらず $cal(P) = {0, 1, dots, n}$ とおく。 ルール $cal(R) : cal(P) -> 2^cal(P)$ を $ cal(R)(i) = { max(0, i - j) | 1 <= j <= 3 } quad (0 <= i <= n) $ と定める。このとき、組 $(cal(P), cal(R))$ は制限一山Nimを表す有限型の不偏ゲームである。 さらに、 $ cal(G) := { i in cal(P) | i equiv 0 thin (mod 4) } \ cal(S) := { i in cal(P) | i equiv.not 0 thin (mod 4) } $ であることが分かる。これは帰納法、つまり以下の表を $i$ が小さい順に埋めることで分かる。 #{ set align(center) table( columns: 12, inset: 8pt, $i$, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [$dots$], [$cal(G) \/ cal(S)$], $cal(G)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(G)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(G)$, $cal(S)$, $dots$, ) } // 一度に山からとることができる石の数が異なっても同様に考えられる。 ] <st_nim> #example( "一般化された一山Nim", )[ 一山Nimで一度に取ることができる石の数を $2$ 個 か $3$ 個のどちらか一方に制限に制限したものを考える。 局面全体の集合は一山Nimと変わらず $cal(P) = {0, 1, dots, n}$ とおく。 ルール $cal(R) : cal(P) -> 2^cal(P)$ を $ cal(R)(i) &= { max(0, i - j) | j = 2 or j = 3 } quad (0 <= i <= n) $ と定める。このとき、やはり組 $(cal(P), cal(R))$ は有限型の不偏ゲームである。 終了局面全体の集合は$cal(E) = {0, 1}$ であることに注意されたい。 さらに、 $ cal(G) := { i in cal(P) | i equiv 0 thin (mod 5) or i equiv 1 thin (mod 5) } \ cal(S) := { i in cal(P) | i equiv 2 thin (mod 5) or i equiv 3 thin (mod 5) or i equiv 4 thin (mod 5) } $ であることが分かる。これも帰納法、つまり以下の表を $i$ が小さい順に埋めることで分かる。 #{ set align(center) table( columns: 13, inset: 8pt, $i$, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [$dots$], [$cal(G) \/ cal(S)$], $cal(G)$, $cal(G)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(G)$, $cal(G)$, $cal(S)$, $cal(S)$, $cal(S)$, $cal(G)$, $dots$, ) } ] <gen_nim> = Grundy数 不偏ゲームの局面に対してGrundy数を定義する。 #definition( "Grundy数", )[ (@sato, pp. 34-35) $cal(A) = (cal(P), cal(R))$ を不偏ゲームとする。 局面 $P in cal(P)$ の*Grundy数* $g(P)$ を次で再帰的に定義する。 $ g(P) := mex({ g(Q) | Q in cal(R)(P) }) $ ただし、$A subset NN$ に対して、$mex(A) := min (NN without A)$ である。 特に終了局面 $P in cal(E)$ に対して、$g(P) = mex(emptyset) = 0$ である。 ] Grundy数を用いて不偏ゲームの必勝判定を行うことができる。 #theorem("Grundy数による必勝判定")[ (@sato, 定理3.1) 不偏ゲーム $cal(A) = (cal(P), cal(R))$ の後手必勝局面全体の集合を$cal(G)$、先手必勝局面全体の集合を $cal(S)$ とする。 このとき、 $ cal(G) = { P in cal(P) | g(P) eq 0 } \ cal(S) = { P in cal(P) | g(P) eq.not 0 } $ が成立する。 ] 証明は $"mex"$ の性質そのものである。 #blue[証明は読まなくて良いです。] #proof[ $A := { P in cal(P) | g(P) eq 0 }$ 、$B := { P in cal(P) | g(P) eq.not 0 }$ とおく。 $cal(P) = A union.sq B = cal(G) union.sq cal(S)$ であるから $A subset cal(G)$ と $B subset cal(S)$ を示せばよい。 局面の長さによる帰納法で示す。定義から、 $ cal(G) = cal(E) union { P in cal(P) | forall Q in cal(R)(P), thin Q in cal(S) } \ cal(S) = { P in cal(P) | exists Q in cal(R)(P), thin Q in cal(G) } $ だった。 - $cal(E) subset A$ について、$cal(E) subset cal(G)$ となることは良い。 - 長さ $k$ 以下の局面 $P in cal(P)$ に対して、$P in A$ ならば $P in cal(G)$ であり、 $P in B$ ならば $P in cal(S)$ が成り立つと仮定する。 - このとき、$P in cal(P)$ を長さ $k + 1$ の局面とする。 - まず、$P in A$ だったとする。$g(P) = 0$ であるので、$P$ の任意の後続局面 $Q in cal(R)(P)$ に対して、$g(Q) eq.not 0$ をみたす。これは $"mex"$ の定義から従う。$l(Q) <= k$ であるので帰納法の仮定から、$Q in cal(S)$ である。したがって、$P in cal(G)$ となる。 - 次に、$P in B$ だったとする。$g(P) eq.not 0$ であるので、$P$ のある後続局面 $Q in cal(R)(P)$ が存在して、 $g(Q) = 0$ をみたす。これも$"mex"$ の定義による。$l(Q) <= k$ であるので、帰納法の仮定から、 $Q in cal(G)$ である。したがって、$P in cal(S)$ となる。 ] = Grundy数の例 <sec_ex_grundy> 不偏ゲームの例としてあげた3つのゲームのGrundy数を計算する。この節で求めるGrundy数の表と @game_ex で計算した表とを比べると、 $cal(G)$ が $g(i) eq.not 0$ と、$cal(S)$ が $g(i) eq 0$ と、 それぞれ対応していることを確かめられる。 #example( "一山Nim", )[ 一山Nimの局面全体の集合は $cal(P) = {0, 1, dots, n}$ 、ルール$cal(R) : cal(P) -> 2^cal(P)$ は $ cal(R)(i) = {j | 0 <= j < i} quad (0 <= i <= n) $ // $ // cal(R)(0) &= emptyset, quad \ // cal(R)(i) &= {0, dots, i - 1} quad (0 < i <= n) // $ だった。 局面の長さが小さい順に、すなわち、 $i$ について昇順にGrundy数を計算して表にすると、 #{ set align(center) table( columns: 9, inset: 8pt, $i$, $0$, $1$, $2$, $3$, $4$, $5$, $6$, $dots$, $g(i)$, $0$, $1$, $2$, $3$, $4$, $5$, $6$, $dots$, ) } となる。 一般に $g(i) = i$ であることが分かる。 ] #example( "制限一山Nim", )[ 制限一山Nimの局面全体の集合は $cal(P) = {0, 1, dots, n}$ 、 ルール $cal(R) : cal(P) -> 2^cal(P)$ は $ cal(R)(i) = { max(0, i - j) in cal(P) | 1 <= j <= 3 } quad (0 <= i <= n) $ と定めた。 局面の長さが小さい順に、すなわち、 $i$ について昇順にGrundy数を計算して表にすると、 #{ set align(center) table( columns: 12, inset: 8pt, $i$, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [$dots$], [$g(i)$], $0$, $1$, $2$, $3$, $0$, $1$, $2$, $3$, $0$, $1$, $dots$, ) } となる。 帰納的に $g(i) = (i mod 4)$ であることが分かる。 ただし、$i mod 4$ は $i$ を $4$ で割ったあまりである。 // 一度に山からとることができる石の数が異なっても同様に考えられる。 ] #example( "一般化された一山Nim", )[ @gen_nim では一山Nimで一度に取ることができる石の数を $2$ 個 か $3$ 個のどちらか一方に制限に制限したものを考えた。 局面全体の集合 $cal(P) = {0, 1, dots, n}$ として、ルール $cal(R) : cal(P) -> 2^cal(P)$ は $ cal(R)(i) &= { max(0, i - j) | j = 2 or j = 3 } quad (0 <= i <= n) $ と定めた。 局面の長さが小さい順にすなわち、 $i$ について昇順にGrundy数を計算して表にすると、 #{ set align(center) table( columns: 13, inset: 8pt, $i$, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [$dots$], [g(i)], $0$, $0$, $1$, $1$, $2$, $0$, $0$, $1$, $1$, $2$, $0$, $dots$, ) } となる。このあとのGrundy数も $0,0,1,1,2$ と繰り返しになることが帰納的に分かる。 すなわち、 $ g(i) = cases( 0 quad (i equiv 0,1) \ 1 quad (i equiv 2,3) \ 2 quad (i equiv 4) ) $ となる。 一般に、一般化された一山Nimにおいて、取ることができる石の数の集合が有限集合である場合は、Grundy数は周期をもつことが分かる(@sato, 定理5.3)。 ] 以上の3つの例、それぞれを @game_ex で計算した表と比べると、 $cal(G)$ が $g(i) eq.not 0$ と、$cal(S)$ が $g(i) eq 0$ と、それぞれ対応しているのが分かる。 このことから分かるように、単純なゲームの必勝判定をしたいだけであればGrundy数を計算する必要はない。 単に @game_ex で行ったように局面が後手必勝であるか先手必勝であるかの二通りで判定していけばよいからである。 しかし、Grundy数は局面の勝敗以上の情報を含んでいる。 @game_sum で述べるように、複数のゲームを組み合わせた際にその威力が発揮される。 = ゲームの和 <game_sum> 二つの不偏ゲームを独立に行うゲームを二つの*不偏ゲームの和*という。 このとき、もとの二つのゲームのどちらか一方のみを一手進めることを、ゲームの和の一手として定める。 集合論の言葉でより正確に表現しよう。 #definition( "不偏ゲームの和", )[ (@sato, pp. 39-40) $cal(A)_1 = (cal(P)_1, cal(R)_1)$ と $cal(A)_2 = (cal(P)_2, cal(R)_2)$ をそれぞれ不偏ゲームとする。 このとき、$cal(R)_1 times cal(R)_2 : cal(P)_1 times cal(P)_2 -> 2^(cal(P)_1) times 2^(cal(P)_2)$ を $P_1 in cal(P)_1, thin P_2 in cal(P)_2$ に対して、 $ cal(R)_1 times cal(R)_2(P_1, P_2) = {(Q_1, P_2) | Q_1 in cal(R)_1(P_1)} union {(P_1, Q_2) | Q_2 in cal(R)_2(P_2)} $ と定める。このとき、不偏ゲーム $(cal(P)_1 times cal(P)_2, cal(R)_1 times cal(R)_2)$ のことを、 $cal(A)_1 + cal(A)_2$ と表して、*$cal(A)_1$ と $cal(A)_2$ の和*という。 ] すなわち、ゲームの和 $cal(A)_1 + cal(A)_2$ の局面全体の集合は直積 $cal(P)_1 times cal(P)_2$ である。 また、局面 $(P_1, P_2)$ の後続局面は $P_1$ か $P_2$ のどちらか一方を進めた局面である。 不偏ゲームの和について結合法則が成り立つ。 すなわち、$cal(A)_1, cal(A)_2, cal(A)_3$ を不偏ゲームとすると、 $ (cal(A)_1 + cal(A)_2) + cal(A)_3 = cal(A)_1 + (cal(A)_2 + cal(A)_3) $ が成り立つ。 不偏ゲームの和のGrundy数はそれぞれの不偏ゲームの排他的論理和で表される、という驚くべき定理が成り立つ。 #theorem( "ゲームの和のGrundy数", )[ (@sato, 定理3.4) $cal(A)_1 = (cal(P)_1, cal(R)_1), thin cal(A)_2 = (cal(P)_2, cal(R)_2)$ を不偏ゲームとする。$cal(A)_1$ と $cal(A)_2$ のGrundy数をそれぞれ $g_(cal(A)_1)$ と $g_cal(A)_2$ で表す。また、和 $cal(A)_1 + cal(A)_2$ のGrundy数を $g_(cal(A)_1 + cal(A)_2)$ と定める。 このとき、局面 $P_1 in cal(P)_1, thin P_2 in cal(P)_2$ に対して、 $ g_(cal(A)_1 + cal(A)_2)(P_1, P_2) = g_(cal(A)_1)(P_1) plus.circle g_cal(A)_2(P_2) $ が成立する。ただし、$plus.circle$ は各ビットごとの排他的論理和である。 ] <thm_sum_grundy> 証明は @sato に詳しい。 #pagebreak() = ゲームの和のGrundy数の例 最後に具体的なゲームの和のGrundy数を求める。 #example[ 一山Nim $cal(A)_1$(@one_nim)と制限一山Nim $cal(A)_2$(@st_nim)と一般化された一山Nim $cal(A)_3$ (@gen_nim) の和 $cal(A)_1 + cal(A)_2 + cal(A)_3$ を考える。それぞれの山の石の数は等しく $n$ 個であるとする。直観的には3つの山を並べて、選択可能な一手は「一つの山を選び、その山で許されている数の石をとること」だと考えればよい。 $cal(P)_n = {0, 1, dots, n}$ とおく。$cal(A)_1 + cal(A)_2 + cal(A)_3$ の局面全体の集合は $(cal(P)_n)^3 = cal(P)_n times cal(P)_n times cal(P)_n$ である。さらに、ルール $cal(R) : (cal(P)_n)^3 -> 2^((cal(P)_n)^3)$ は $ cal(R)(i, j, k) = {(i', j, k)| 0 <= i' < i} union {(i, max(0, j - s), k) | 1 <= s <= 3} \ union {(i, j, max(0, k - t)) | t = 2 or t = 3} quad ((i, j, k) in (cal(P)_n)^3) $ である。和 $cal(A)_1 + cal(A)_2 + cal(A)_3$ のGrundy数 $g_(cal(A)_1 + cal(A)_2 + cal(A)_3)$ は @thm_sum_grundy と @sec_ex_grundy の計算から $ g_(cal(A)_1 + cal(A)_2 + cal(A)_3)(i, j, k) = i plus.circle (j mod 4) plus.circle a_k $ となる。ただし、$a_k$ は $ a_k = cases( 0 quad (k equiv 0,1) \ 1 quad (k equiv 2,3) \ 2 quad (k equiv 4) ) $ と定める。 ] 競技プログラミングにおいて、非常に大きい自然数 $n$ に対して、$n$ 個のゲームの和を考えることがある。 ゲームの和の局面全体の個数はとても大きいので、grundy数を直接計算するには膨大な計算が必要となる。 しかし、@thm_sum_grundy を用いることで小ない計算回数でゲーム和のGrundy数を求めることができる。すなわち、和をとる前のゲームのgrundy数を計算して、それからゲームの和のgrundy数を求めることができる。 #bibliography("references.bib")
https://github.com/cspr-rad/kairos-spec
https://raw.githubusercontent.com/cspr-rad/kairos-spec/main/design/main.typ
typst
#let title = [ Kairos: Zero-knowledge Casper Transaction Scaling ] #let time_format = "[weekday] [month repr:long] [day padding:none], [year]" #set page(paper: "a4", numbering: "1", margin: (x: 3.2cm, y: 4.0cm)) #set heading(numbering: "1.") #set text( // font: "Linux Libertine", size: 12pt, ) #show link: underline #align( center, text( 21pt, )[ *#title* Design #align( center, text( 12pt, )[ <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> ], ) #datetime.today().display(time_format) ], ) #outline(title: "Contents", indent: auto) #pagebreak() = Architecture <architecture> To give the reader an idea of what a system defined in the previous sections might look like, this section proposes a possible architecture. The features and requirements described previously suggest two core components in the system. A CLI and an L2 node implementing the client-server pattern. The L2 node should not be monolithic but rather obey the principle of separation of concerns to allow for easier extensibility and replacement of components in the future. Therefore, the L2 node unifies various other components described in more detail in the following @architecture-components and exposes them through a single API. #figure(image("components_diagram.svg", width: 100%), caption: [ Components diagram ]) <components-diagram-figure> == Architecture Components <architecture-components> === Client CLI <cli> The client CLI's user interface (UI) is comprised of commands allowing users to deposit, transfer, and withdraw funds allocated in their L2 account. Once a user executes any of the commands, the client delegates the bulk of the work to the L2 node (@l2-node). Moreover, the client CLI can be used to verify past state changes and to query account balances and transfers. // Web UI is now post-version 0.1 // == Web UI // // Note: The integration with Casper's L1 wallet shouldn't be difficult. There is an SDK in Typescript, which compiles to Javascript, and hence the small number of interactions we require with the L1 wallet will be implementable in anything else that compiles to or uses Javascript, whether that be Elm, Yesod, Typescript, Purescript.. // Proposal: If the L2 server is implemented in Haskell, we could use Yesod. Otherwise our preferred choice would be Elm. === L2 Node <l2-node> As constrained in the requirements document, the L2 node is centralized. The detailed reasoning behind this decision, potential dangers, and our methods for dealing with these dangers are explained in @centralized-L2. The L2 node is the interface through which external clients (@cli) can submit deposits, transfers, or withdrawals of funds. Moreover, it is connected to a data store (@data-store) to persist the account balances, whose state representation #footnote[The state representation is the Merkle root, see @glossary.] is maintained on-chain. State transitions of the account balances are verified and executed on-chain, requiring the node to create respective transactions on L1 using the L1's software development kit (SDK). These transactions, in turn, call the respective endpoints of smart contracts described in @contracts to do so. To execute batch transfers the node utilizes a proving system provided by the Prover service (@prover). For deposits and withdrawals, the node creates according Merkle tree updates of the account balances @merkle-tree-updates. // @Mark: Do we want to build the L2 server in Haskell or in Rust? // Pros: // - Easier to test, and better test tooling // - Clients can be generated from APIs such as Servant, ensuring correctness of server/client interactions // - Yesod framework can be used for Web UI // // Cons: // - Some data types have to be reimplemented from Rust, since Casper's L1 is in Rust // - Rust is a bit faster // - There might be some data type sharing between the Risc0, smart contract and L2 server code === Prover <prover> The Prover is a separate service that exposes a _batchProve_ and a _batchVerify_ endpoint, mainly used by the L2 node (@l2-node) to prove batches of transfers. Under the hood, the Prover uses a zero-knowledge proving system that computes the account balances resulting from the transfers within a batch and a proof of correct computation. === Data Store <data-store> The data store is a persistent storage that stores the performed transfers and the account balances whose state representation is stored on the blockchain. To achieve more failsafe and reliable availability of the data, it is replicated sufficiently often by so-called standbys (replicas). In the case of failure, standbys can be used as new primary stores (@data-redundancy). === L1 State/ Verifier Contract <contracts> The L1 State and Verifier Contracts are responsible for verifying and performing updates of the Merkle root of account balances. They can be two separate contracts or a single contract with several endpoints. A state update only happens if the updated state was verified successfully beforehand. The contracts are called by the L2 node by creating according transactions and submitting them to an L1 node. For the Merkle tree root to have an initial value, the State Contract will be initialized with a deposit. This initial deposit then becomes the balance of the system. // TODO: Where does the ZK verification happen? // This document currently silently assumes verification _can_ happen within the verifying smart contract. Is this the case? Answering that question will require a deep-dive into Risc0 or whicheven ZK prover we end up picking. // // Old notes: // Within the casper-node, if the ZK verification code doesn't fit into a smart contract? If it does, then within the same smart contract, or a dedicated one? // Deep-dive into Risc0: What does verification require? How much data and computation? // - Can this be integrated into a smart contract? // - If so, should we use a separation ZK verification smart contract, or include it in the Validium start contract? // - If not, how can we integrate this with the Casper node? == APIs The following section proposes a possible API of the previously described components. === Client CLI #table( columns: (auto, auto, auto, auto), [Name], [Arguments], [Return Value], [Description], [get_balance], [accountId: AccountID], [balance: UnsignedINT], [Returns a user's L2 account balance. The UnsignedINT type should be a type that allows for safe money computations (Read @safe-money)], [transfer], [sender: AccountID, recipient: AccountID, amount: UnsignedINT, token_id: TokenID, nonce: Nonce, key_pair: KeyPair], [transferId: TransferID], [Creates, signs and submits an L2 transfer to the L2 node. A cryptographic nonce should be used in order to prevent replay attacks.], [getTransfer], [transferId: TransferID], [transfer: TransferState], [Returns the status of a given transfer: Cancelled, ZKP in progress, batch proof in progress, or "posted on L1 with blockhash X"], [deposit], [depositor: AccountID, amount: UnsignedINT, token_id: TokenID, key_pair: KeyPair], [transaction: Transaction], [Creates an L1 deposit transaction, by first asking the L2 node to create an according L1 transaction for us, afterward signing it on the client-side and then submitting it to L1 through the L2 node], [withdraw], [withdrawer: AccountID, amount: UnsignedINT, token_id: TokenID key_pair: KeyPair], [transaction: Transaction], [Creates an L1 withdraw transaction, by first asking the L2 node to create an according L1 transaction for us, afterward signing it on the client-side and then submitting it to L1 through the L2 node], [verify], [proof: Proof, public_inputs: PublicInputs], [result: VerifyResult], [Returns whether a proof is legitimate or not], ) === L2 Node <l2-node-api> #table( columns: (auto, auto, auto, auto), [Name], [Arguments], [Return Value], [Description], [get_balance], [accountId: AccountID], [balance: UnsignedINT], [Returns a user's L2 account balance. The UnsignedINT type should be a type that allows for safe money computations (Read @safe-money)], [transfer], [sender: AccountID, recipient: AccountID, amount: UnsignedINT, token_id: TokenID, nonce: Nonce, signature: Signature, sender_pub_key: PubKey], [transferId: TransferID], [Schedules an L2 transfer, and returns a transfer-ID], [getTransfer], [transferId: TransferID], [transfer: TransferState], [Returns the status of a given transfer: Cancelled, ZKP in progress, batch proof in progress, or "posted on L1 with blockhash X"], [deposit], [depositor: AccountID, amount: UnsignedINT, token_id: TokenID], [transaction: Transaction], [Creates an L1 deposit transaction containing an according Merkle tree root update and accompanying metadata needed to verify the update based on the depositor's account ID and the amount. The returned transaction is an L1 transaction that has to be signed by the depositor on the client-side.], [withdraw], [withdrawer: AccountID, amount: UnsignedINT, token_id: TokenID], [transaction: Transaction], [Creates an L1 withdraw transaction containing an according Merkle tree root update and accompanying metadata needed to verify the update based on the withdrawer's account ID and the amount. The returned transaction is an L1 transaction that has to be signed by the withdrawer on the client-side.], [submitTransaction], [signedTransaction: SignedTransaction], [submitResult: SubmitResult], [Forwards a signed L1 transaction and submits it to the L1 for execution.], [verify], [proof: Proof, public_inputs: PublicInputs], [result: VerifyResult], [Returns whether a proof is legitimate or not], ) === L1 State/ Verifier Contract <contracts-api> #table( columns: (auto, auto, auto, auto), [Name], [Arguments], [Return Value], [Description], [verify_deposit], [depositor: AccountID, amount: UnsignedINT, token_id: TokenID, updated_account_balances: MerkleRootHash, update_metadata: MerkleRootUpdateMetadata, signature: Signature], [], [- Verifies that the transaction contains the same amount of tokens used to update the account balance\ - Moves the amount from the depositor's L1 account to the account owned by the system\ - Verifies the depositor's signature\ - Verifies the new Merkle root given the public inputs and metadata\ - Updates the system's on-chain state on successful verification ], [verify_withdraw], [withdrawer: AccountID, amount: UnsignedINT, tokenId: TokenID, updated_account_balances: MerkleRootHash, update_metadata: MerkleRootUpdateMetadata, signature: Signature], [], [- Verifies that the transaction moves the same amount of tokens used to update the account balance\ - Moves the amount from the account owned by the system to the withdrawer's L1 account\ - Verifies the withdrawer's signature\ - Verifies the new Merkle root given the public inputs and metadata\ - Updates the system's on-chain state on successful verification ], [verify_transfers], [proof: Proof, publicInputs: PublicInputs], [], [- Verifies that the proof computed from performing batch transfers on the L2 is valid\ - Updates the system's on-chain state on successful verification ], ) == Component Interaction Figures 2 and 3 show sequence diagrams for processing a user's deposit and transfer requests, respectively. === Deposit Sequence Diagram Depositing funds to user `Bob`'s account is divided into three phases, which are modelled in the following sequence diagrams. In the first phase (@deposit-client-submit) users submit their deposit requests through the client CLI to the L2 node. The L2 node creates an L1 transaction (_Deploy_) containing the according Merkle root update and the update metadata, which can be used to verify that the update was done correctly. More precisely, the _Deploy_ contains a _Session_ that executes the validation of the Merkle tree update, performs the state transition and transfer the funds from the user's L1 account (purse) to the systems L1 account. This _Deploy_ needs to be signed by the user before submitting, this is achieved by making use of the L1's SDK on the client-side. After submitting, the L1 smart contracts take care of validating the new Merkle root, updating the system's state, and transferring the funds (@deposit-deploy-execution). Lastly (@deposit-notify), the L2 node gets notified after the _Deploy_ was processed successfully. The node then commits the updated state to the data store. After sufficient time has passed, the user can query its account balance using the client CLI. #page(flipped: true)[ #figure( image("deposit_sequence_diagram_client_submit.svg", width: 100%), caption: [ Deposit: User submits a deposit to L2 which gets forwarded to L1. ], ) <deposit-client-submit> ] #page(flipped: true)[ #figure( image("deposit_sequence_diagram_deploy_execution.svg", width: 100%), caption: [ Deposit: Execution of the _Deploy_ on L1. ], ) <deposit-deploy-execution> ] #page(flipped: true)[ #figure( image("deposit_sequence_diagram_notify_l2.svg", width: 100%), caption: [ Deposit: Notifying the L2 after succcessfull on-chain execution. ], ) <deposit-notify> ] === Transaction Sequence Diagram Transfering funds from user `Bob` to a user `Alice` can be divided into four phases, which are modelled in the following sequence diagrams. In the first phase (@transfer-submit) users submit their transfer requests through the client CLI to the L2 node. The L2 node accumulates the transfer requests and checks for independence. In addition, the L2 node will check that the batch proof which is going to be computed next, a valid nonce. After `t` seconds or `n` transactions (@transfer-prove), the L2 node batches the transfers, creates a proof of computation, and the according _Deploy_ which will execute the validation and the state transition on-chain. After submitting, the L1 smart contracts take care of first validating the proof and updating the state (@transfer-execute). Lastly (@transfer-notify), the L2 node gets notified when the _Deploy_ was executed successfully. The node then commits the updated state to the data store. After sufficient time has passed, the users can query their account balances using the client CLI #page(flipped: true)[ #figure( image("transfer_sequence_diagram_client_submit.svg", width: 100%), caption: [ Transfer: User submits a transfer to L2. ], ) <transfer-submit> ] #page(flipped: true)[ #figure( image("transfer_sequence_diagram_l2_prove_deploy.svg", width: 100%), caption: [ Transfer: Proving and submitting the proof. ], ) <transfer-prove> ] #page(flipped: true)[ #figure( image("transfer_sequence_diagram_deploy_execution.svg", width: 100%), caption: [ Transfer: Execution of the _Deploy_ on L1. ], ) <transfer-execute> ] #page(flipped: true)[ #figure( image("transfer_sequence_diagram_notify_l2.svg", width: 100%), caption: [ Transfer: Notifying the L2 after succcessfull on-chain execution. ], ) <transfer-notify> ] = Glossary <glossary> / Validium: Please refer to @validium and @validium-vs-rollup / L1: The Casper blockchain as it currently runs. / L2: A layer built on top of the Casper blockchain, which leverages Casper's consensus algorithm and existing infrastructure for security purposes while adding scaling and/or privacy benefits / Nonce/ Kairos counter: A mechanism that prevents the usage of L2 transactions more than once without the user's permission. It is added to each L2 transaction, which is verified by the batch proof and L1 smart contract. For an in-depth explanation, see @uniqueness. / Zero knowledge proof (ZKP): Is a proof generated by person A which proves to person B that A is in possession of certain information X without revealing X itself to B. These ZKPs provide some of the most exciting ways to build L2s with privacy controls and scalability. @zkp / Merkle trees: Are a cryptographic concept to generate a hash given a dataset. It allows for efficient and secure verification of the contents of large data strutures. @merkle-tree #bibliography("bibliography.yml")
https://github.com/cadojo/resume
https://raw.githubusercontent.com/cadojo/resume/main/README.md
markdown
# Technical Resume My professional resume, generated with [Typst](https://typst.org)!
https://github.com/heloineto/utfpr-tcc-template
https://raw.githubusercontent.com/heloineto/utfpr-tcc-template/main/template/acknowledgment-page.typ
typst
#let acknowledgment-page(body) = { align(center, text(weight: "bold", "AGRADECIMENTOS")) v(30pt) text(weight: "regular")[ #set align(left) #set par( justify: true, first-line-indent: 1.25cm, leading: 1em ) #body ] pagebreak() }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/valkyrie/0.2.0/src/types/string.typ
typst
Apache License 2.0
#import "../base-type.typ": base-type #import "../assertions-util.typ": assert-base-type #import "../ctx.typ": z-ctx #import "../assertions-util.typ": * #import "../assertions/string.typ": matches /// Valkyrie schema generator for strings /// /// -> schema #let string = base-type.with(name: "string", types: (str,)) #let email = string.with( name: "email", assertions: ( matches( regex("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{2,3}){1,2}$"), message: (self, it) => "Must be an email address", ), ), ); #let ip = string.with( name: "ip", assertions: ( matches( regex("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"), message: (self, it) => "Must be a valid IP address", ), ), );
https://github.com/herbhuang/utdallas-thesis-template-typst
https://raw.githubusercontent.com/herbhuang/utdallas-thesis-template-typst/main/layout/disclaimer.typ
typst
MIT License
#let disclaimer( title: "", degree: "", author: "", submissionDate: datetime, ) = { set page( margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: none, number-align: center, ) let body-font = "New Computer Modern" let sans-font = "New Computer Modern Sans" set text( font: body-font, size: 12pt, lang: "en" ) set par(leading: 1em) // --- Disclaimer --- v(75%) text("I confirm that this " + degree + "’s thesis is my own work and I have documented all sources and material used.") v(15mm) grid( columns: 2, gutter: 1fr, "Munich, " + submissionDate.display("[day].[month].[year]"), author ) }
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/PianoDiProgetto/sections/ConsuntivoSprint/NonoSprint.typ
typst
MIT License
#import "../../const.typ": Re_cost, Am_cost, An_cost, Ve_cost, Pr_cost, Pt_cost #import "../../functions.typ": rendicontazioneOreAPosteriori, rendicontazioneCostiAPosteriori, glossary ==== Nono consuntivo *Inizio*: Venerdì 16/02/2024 *Fine*: Giovedì 22/02/2024 #rendicontazioneOreAPosteriori(sprintNumber: "09") #rendicontazioneCostiAPosteriori(sprintNumber: "09") ===== Analisi a posteriori La retrospettiva ha evidenziato come il preventivo del totale delle ore sia stato rispettato. Tuttavia, si possono notare alcune differenze nell'ammontare delle ore di alcuni ruoli. In particolare, il ruolo del Verificatore è quello che si è discostato di più rispetto al preventivo, con un totale delle ore inferiore. Questo non risulta particolarmente preoccupante. Infatti, si spiega con il fatto che le modifiche e integrazioni apportate ai documenti sono state minori rispetto a #glossary[sprint] passati. Si nota invece l'accuratezza del preventivo per il ruolo di Progettista; nonostante questo sia stato utilizzato per la prima volta, con l'inizio della stesura della _Specifica Tecnica_, esso risulta esser stato stimato con precisione, indice di una maturata consapevolezza nella pianificazione delle attività. Con un leggero superamento le ore da Analista preventivate hanno permesso di rispettare la pianificazione e di completare la correzione dell'_Analisi dei Requisiti v1.0_, secondo le indicazioni ricevute nella prima revisione #glossary[RTB]. Con la fine delle lezioni il team non ha più avuto modo di incontrarsi fisicamente; questo ha portato alla potenziale manifestazione del rischio RC1. Una strategia che si è rivelata efficace nell'inibire questo rischio è stata la scelta di svolgere gli #glossary("stand-up meeting") remoti con una frequenza di due volte a settimana, il che, insieme al meeting interno settimanale, ha permesso di tenere sotto controllo l'avanzamento delle attività e di discutere tempestivamente eventuali problematiche. Lo svolgimento di tali meeting infrasettimanali si è rivelato un impegno sostenibile per il gruppo e quindi una pratica da mantenere anche in futuro. ===== Aggiornamento della pianificazione e gestione dei rischi Il gruppo ha preso coscienza del fatto che il preventivo per questo #glossary[sprint] considerava fin troppe poche ore rispetto a quelle che si potevano impiegare a livello di risorse e che sono di fatto necessarie per completare le attività pianificate per la revisione #glossary[PB] entro le scadenze stabilite; di conseguenza, nell'ottica di arginare il rischio RP3, vengono aggiornati i preventivi successivi in modo da aumentare le ore di lavoro. In particolare, poiché questi primi #glossary[sprint] nel periodo antecedente la revisione #glossary[PB] richiedono principalmente attività di progettazione, si prevede un aumento delle ore per il ruolo di Progettista, che sarà ricoperto da più membri del gruppo rispetto allo #glossary("sprint") precedente. La decisione viene inoltre motivata dal fatto che per questa attività è importante il confronto e la condivisione di idee tra più membri.
https://github.com/antonWetzel/Masterarbeit
https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/packages/todo.typ
typst
#let todo(body, prefix: [To-do]) = { set text(size: 0pt) figure(kind: "todo", supplement: "", outlined: true, caption: body)[ #pad(0.5cm, block( fill: orange, inset: 5pt, radius: 3pt, stroke: black, width: 90%, text(size: 11pt, prefix + [: ] + body), )) ] } #let todo-inline(body, prefix: [To-do]) = { set text(size: 0pt) box({ set text(size: 0pt) figure(kind: "todo", supplement: "", outlined: true, caption: body, rect( fill: orange, height: auto, inset: 1pt, radius: 1pt, stroke: black, text(size: 11pt, prefix + [: ] + body), )) }) } #let todo-image(body: [Bild], height: 20%) = { block( fill: orange, inset: 5pt, radius: 3pt, stroke: black, width: 100%, height: height, body ) } #let todo-outline = () => locate(loc => { let x = query(figure.where(kind: "todo"), loc) if x != () { outline(title: [To-dos], target: figure.where(kind: "todo")) pagebreak() } })
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/math/spacing.typ
typst
// Test spacing in math formulas. --- math-spacing-basic --- // Test spacing cases. $ä, +, c, (, )$ \ $=), (+), {times}$ \ $⟧<⟦, abs(-), [=$ \ $a=b, a==b$ \ $-a, +a$ \ $a not b$ \ $a+b, a*b$ \ $sum x, sum(x)$ \ $sum product x$ \ $f(x), zeta(x), "frac"(x)$ \ $a+dots.c+b$ $f(x) sin(y)$ --- math-spacing-kept-spaces --- // Test ignored vs non-ignored spaces. $f (x), f(x)$ \ $[a|b], [a | b]$ \ $a"is"b, a "is" b$ --- math-spacing-predefined --- // Test predefined spacings. $a thin b, a med b, a thick b, a quad b$ \ $a = thin b$ \ $a - b equiv c quad (mod 2)$ --- math-spacing-set-comprehension --- // Test spacing for set comprehension. #set page(width: auto) $ { x in RR | x "is natural" and x < 10 } $ --- math-spacing-decorated --- // Test spacing for operators with decorations and modifiers on them #set page(width: auto) $a equiv b + c - d => e log 5 op("ln") 6$ \ $a cancel(equiv) b overline(+) c arrow(-) d hat(=>) e cancel(log) 5 dot(op("ln")) 6$ \ $a overbrace(equiv) b underline(+) c grave(-) d underbracket(=>) e circle(log) 5 caron(op("ln")) 6$ \ \ $a attach(equiv, tl: a, tr: b) b attach(limits(+), t: a, b: b) c tilde(-) d breve(=>) e attach(limits(log), t: a, b: b) 5 attach(op("ln"), tr: a, bl: b) 6$ --- math-spacing-weak --- // Test weak spacing $integral f(x) dif x$, // Not weak $integral f(x) thin dif x$, // Both are weak, collide $integral f(x) #h(0.166em, weak: true)dif x$ --- math-spacing-ignorant --- // Test spacing with ignorant elements $#metadata(none) "text"$ \ $#place(dx: 5em)[Placed] "text"$ \ // Operator spacing $#counter("test").update(3) + b$ \ $#place(dx: 5em)[a] + b$ // Validate that ignorant elements are layouted #context test(counter("test").get(), (3,)) --- issue-1052-math-number-spacing --- // Test spacing after numbers in math. $ 10degree \ 10 degree \ 10.1degree \ 10.1 degree $
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/slides/theory/commit.typ
typst
#import "@preview/touying:0.5.2": * #import themes.university: * #import "@preview/numbly:0.1.0": numbly #import "@preview/fletcher:0.5.1" as fletcher: node, edge #let fletcher-diagram = touying-reducer.with(reduce: fletcher.diagram, cover: fletcher.hide) #import "../components/gh-button.typ": gh_button #import "../components/git-graph.typ": branch_indicator, commit_node, connect_nodes, branch #block(breakable:false, [ A commit is a snapshot of the code at a given time, generally having these attributes: - hash unique identifier - message describing the changes made - author (email and name), co-authors - date and time of the commit Each #link("https://git-scm.com/docs/git-commit")[commit] is linked to the previous one, and differs from it in the changes made. This cycle of changes and commits is the basis of Git. #align(center)[ #fletcher-diagram( node-stroke: .1em, node-fill: gradient.linear(rgb("#448C95").lighten(20%), rgb("#176B87").lighten(20%), rgb("#04364A").lighten(20%)), spacing: 4em, node-shape: rect, node((0,0), "working \n directory", width: auto ), edge((0,0), (0,0), label:[ #set text(style: "italic") #h(25pt) local changes],label-anchor:"north-west", "--|>", bend: 130deg), edge((0,0), (1,0), `git add`, "-|>", bend: -40deg), node((1,0), "staging \n index", width: auto), edge((1,0), (2,0), `git commit`, "-|>", bend: -40deg), node((2,0), "commit \n history", width: auto,), edge((2,0),(2,1), (0,1), (0,0), label-side:left, label:[ #set text(style: "italic") back to working directory without changes], "--|>", bend: 50deg) ) ] ] ) --- Inside our machine git conceptually uses several states to correctly version our files. @git-changes #align(center,image("../img/local-repo.png", width: 90%)) --- States: - *Untracked*: The file exists in the working directory, but Git is not yet monitoring it, it may be actively ignored. - *Tracked*: All other files, whether they are *Unmodified*, *Modified* or *Staged*. - *Unmodified*: The file has been modified since the last version was committed. - *Modified*: Conversely, the file has been modified since the last committed version (even a newly created file with text in a new repository). Some editors list files in this state under the name _changes_. - *Staged*: The file, or rather a version of it, is brought into the staging area. The staging area is an intermediate area preceding a commit. The collection of files in this state is also called _staged changes_. --- Actions: - *Commit*: As we said commit represents a step, in which all files are at a certain version. Suppose, for example, that we need to correct a book: it might be a good strategy to group all the corrections of a chapter within a commit: i.e. at each step of task completion. It is of course possible to manipulate (partially) these commits and travel between them, we will see how later. - *Edit the file*: At each commit all included files will be read by git as *Unmodified* and this "cycle" will start again. Editing a file, or creating it, means bringing it into the *Modified* state. - *Stage the file*: The *current* version of the file on which this action is performed is brought to the *staged* state, further changes on the same file will bring a *new version* of the file into the *modified* state. This is why we generally perform this operation and a *commit immediately afterwards*. - *Add/Remove the file*: It is of course possible to add or remove files from the working directory, to get a new file versioned by git you use the same command you use to get it from *modified* to *staged*, i.e. `git add <file_name>`. However, when you remove a previously versioned file, git will automatically notice and handle it.
https://github.com/CodingThrust/Templates
https://raw.githubusercontent.com/CodingThrust/Templates/main/README.md
markdown
# Templates ## Note taking - [Typst Example](typst) ## Poster - [Google Slides (Version 1.0)](https://docs.google.com/presentation/d/1-hjb7gsEo3X1DCsjS74DnK8gi5zSaxSwLLsqiro7jLc/edit?usp=sharing) ## Slides - [Google Slides (Dark v1.0)](https://docs.google.com/presentation/d/1Wt4WZOTX8c_ZpDMFx16zGgvPOfdXkbwxaprW4xNe9ko/edit?usp=sharing) - [Website: Invert Image Colors](https://pinetools.com/invert-image-colors) - [Reveal (Dark v1.0)](reveal/template1.md) - [Typst Template for HKUST(GZ)](https://github.com/exAClior/touying-simpl-hkustgz)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/line-03.typ
typst
Other
// Error: 14-26 expected relative length, found angle #line(start: (3deg, 10pt), length: 5cm)
https://github.com/OrangeX4/typst-pinit
https://raw.githubusercontent.com/OrangeX4/typst-pinit/main/pinit-fletcher.typ
typst
MIT License
#import "pinit-core.typ": * /// Draw a connecting line or arc in an arrow diagram. /// /// Example: /// /// ```typc /// #import "@preview/fletcher:0.5.1" /// Con#pin(1)#h(4em)#pin(2)nect /// /// #pinit-fletcher-edge( /// fletcher, 1, end: 2, (1, 0), [bend], bend: -20deg, "<->", /// decorations: fletcher.cetz.decorations.wave.with(amplitude: .1), /// ) /// ``` /// /// - fletcher (module): The Fletcher module. You can import it with something like `#import "@preview/fletcher:0.5.1"` /// /// - start (pin): The starting pin of the edge. It is assumed that the pin is at the *origin point (0, 0)* of the edge. /// /// - end (pin): The ending pin of the edge. If not provided, the edge will use default values for the width and height. /// /// - start-dx (length): The x-offset of the starting pin. You should use pt units. /// /// - start-dy (length): The y-offset of the starting pin. You should use pt units. /// /// - end-dx (length): The x-offset of the ending pin. You should use pt units. /// /// - end-dy (length): The y-offset of the ending pin. You should use pt units. /// /// - width-scale (percent): The width scale of the edge. The default value is 100%. /// /// If you set the width scale to 50%, the width of the edge will be half of the default width. Then you can use `"r,r"` which is equivalent to single `"r"`. /// /// - height-scale (percent): The height scale of the edge. The default value is 100%. /// /// - default-width (length): The default width of the edge. The default value is 30pt, which will only be used if the end pin is not provided or the width is 0pt or 0em. /// /// - default-height (length): The default height of the edge. The default value is 30pt, which will only be used if the end pin is not provided or the height is 0pt or 0em. /// /// /// ====================================================================== /// /// The following are the options for the `fletcher.edge` function. Source: [Jollywatt/typst-fletcher](https://github.com/Jollywatt/typst-fletcher) /// /// ====================================================================== /// /// - ..args (any): An edge's positional arguments may specify: /// - the edge's #param[edge][vertices], each specified with a CeTZ-style coordinate /// - the #param[edge][label] content /// - arrow #param[edge][marks], like `"=>"` or `"<<-|-o"` /// - other style flags, like `"double"` or `"wave"` /// /// Vertex coordinates must come first, and are optional: /// /// ```typc /// edge(from, to, ..) // explicit start and end nodes /// edge(to, ..) == edge(auto, to, ..) // start snaps to previous node /// edge(..) == edge(auto, auto, ..) // snaps to previous and next nodes /// edge(from, v1, v2, ..vs, to, ..) // a multi-segmented edge /// edge(from, "->", to) // for two vertices, the marks style can come in between /// ``` /// /// All vertices except the start point can be shorthand relative coordinate /// string containing the characters /// ${#"lrudtbnesw".clusters().map(raw).join($, $)}$ or commas. /// /// If given as positional arguments, an edge's #param[edge][marks] and /// #param[edge][label] are disambiguated by guessing based on the types. For /// example, the following are equivalent: /// /// ```typc /// edge((0,0), (1,0), $f$, "->") /// edge((0,0), (1,0), "->", $f$) /// edge((0,0), (1,0), $f$, marks: "->") /// edge((0,0), (1,0), "->", label: $f$) /// edge((0,0), (1,0), label: $f$, marks: "->") /// ``` /// /// Additionally, some common options are given flags that may be given as /// string positional arguments. These are /// #fletcher.EDGE_FLAGS.keys().map(repr).map(raw).join([, ], last: [, and ]). /// For example, the following are equivalent: /// /// ```typc /// edge((0,0), (1,0), $f$, "wave", "crossing") /// edge((0,0), (1,0), $f$, decorations: "wave", crossing: true) /// ``` /// /// - vertices (array): Array of (at least two) coordinates for the edge. /// /// Vertices can also be specified as leading positional arguments, but if so, /// the `vertices` option must be empty. If the number of vertices is greater /// than two, #param[edge][kind] defaults to `"poly"`. /// /// - kind (string): The kind of the edge, one of `"line"`, `"arc"`, or `"poly"`. /// This is chosen automatically based on the presence of other options /// (#param[edge][bend] implies `"arc"`, #param[edge][corner] or additional /// vertices implies `"poly"`). /// /// - corner (none, left, right): Whether to create a right-angled corner, /// turning `left` or `right`. /// (Bending right means the corner sticks out to the left, and vice versa.) /// /// #diagram( /// node((0,1), `from`), /// node((1,0), `to`), /// edge((0,1), (1,0), `right`, "->", corner: right), /// edge((0,1), (1,0), `left`, "->", corner: left), /// ) /// /// - bend (angle): Edge curvature. If `0deg`, the connector is a straight line; /// positive angles bend clockwise. /// /// #diagram(debug: 0, { /// node((0,0), $A$) /// node((1,1), $B$) /// let N = 4 /// range(N + 1) /// .map(x => (x/N - 0.5)*2*100deg) /// .map(θ => edge((0,0), (1,1), θ, bend: θ, ">->", label-side: center)) /// .join() /// }) /// /// - label (content): Content for the edge label. See the /// #param[edge][label-pos] and #param[edge][label-side] options to control /// the position (and #param[edge][label-sep] and #param[edge][label-anchor] /// for finer control). /// /// - label-side (left, right, center): Which side of the edge to place the /// label on, viewed as you walk along it from base to tip. /// /// If `center`, then the label is placed directly on the edge and /// #param[edge][label-fill] defaults to `true`. When `auto`, a value of /// `left` or `right` is automatically chosen so that the label is: /// - roughly above the connector, in the case of straight lines; or /// - on the outside of the curve, in the case of arcs. /// /// - label-pos (number): Position of the label along the connector, from the /// start to end (from `0` to `1`). /// /// #stack( /// dir: ltr, /// spacing: 1fr, /// ..(0, 0.25, 0.5, 0.75, 1).map(p => fletcher.diagram( /// cell-size: 1cm, /// edge((0,0), (1,0), p, "->", label-pos: p)) /// ), /// ) /// /// - label-sep (length): Separation between the connector and the label anchor. /// /// With the default anchor (automatically set to `"south"` in this case): /// /// #diagram( /// debug: 2, /// cell-size: 8mm, /// { /// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() { /// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s) /// } /// }) /// /// With #param[edge][label-anchor] set to `"center"`: /// /// #diagram( /// debug: 2, /// cell-size: 8mm, /// { /// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() { /// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s, label-anchor: "center") /// } /// }) /// /// Set #param[diagram][debug] to `2` or higher to see label anchors and /// outlines as seen here. /// /// Default: #the-param[diagram][label-sep] /// /// - label-angle (angle, left, right, top, bottom, auto): Angle to rotate the /// label (counterclockwise). /// /// If a direction is given, the label is rotated so that the edge travels in /// that direction relative to the label. If `auto`, the best of `right` or /// `left` is chosen. /// /// #for angle in (0deg, 90deg, auto, right, top, left) { /// diagram(edge((0,1), (2,0), "->", [#angle], label-angle: angle)) /// } /// /// - label-anchor (anchor): The CeTZ-style anchor point of the label to use for /// placement (e.g., `"north-east"` or `"center"`). If `auto`, the best anchor /// is chosen based on #param[edge][label-side], #param[edge][label-angle], /// and the edge's direction. /// /// - label-fill (bool, paint): The background fill for the label. If `true`, /// defaults to the value of #param[edge][crossing-fill]. If `false` or /// `none`, no fill is used. If `auto`, then defaults to `true` if the label /// is covering the edge (#param[edge][label-side]`: center`). /// /// - label-size (auto, length): The default text size to apply to edge labels. /// /// Default: #the-param[diagram][label-size] /// /// - label-wrapper (auto, function): Callback function accepting a node /// dictionary and returning the label content. This is used to add a label /// background (see #param[edge][crossing-fill]), and can be used to adjust /// the label's padding, outline, and so on. /// /// #example(``` /// diagram(edge($f$, label-wrapper: e => /// circle(e.label, fill: e.label-fill))) /// ```) /// /// Default: #the-param[diagram][label-wrapper] /// /// - stroke (stroke): Stroke style of the edge. Arrows/marks scale with the /// stroke thickness (and with #param[edge][mark-scale]). /// /// - dash (string): The stroke's dash style. This is also set by some mark /// styles. For example, setting `marks: "<..>"` applies `dash: "dotted"`. /// /// - decorations (none, string, function): Apply a CeTZ path decoration to the /// stroke. Preset options are `"wave"`, `"zigzag"`, and `"coil"` (which may /// also be passed as convenience positional arguments), but a decoration /// function may also be specified. /// /// #example(``` /// diagram( /// $ /// A edge("wave") & /// B edge("zigzag") & /// C edge("coil") & D \ /// alpha &&& omega /// $, /// edge((0,1), (3,1), "<->", decorations: /// cetz.decorations.wave /// .with(amplitude: .4) /// ) /// ) /// ```) /// /// - marks (array): The marks (arrowheads) to draw along an edge's stroke. This /// may be: /// /// - A shorthand string such as `"->"` or `"hook'-/->>"`. Specifically, /// shorthand strings are of the form $M_1 L M_2$ or $M_1 L M_2 L M_3$, etc, /// where /// /// $ M_i in #`fletcher.MARKS` = #context math.mat(..fletcher.MARKS.get().keys().map(i => $#raw(lang: none, i),$).chunks(6), delim: "{") $ /// is a mark name and /// $ L in #`fletcher.LINE_ALIASES` = {#fletcher.LINE_ALIASES.keys().map(raw.with(lang: none)).join($,$)} $ /// is the line style. /// /// - An array of marks, where each mark is specified by name of as a _mark /// object_ (dictionary of parameters with a `draw` entry). /// /// Shorthands are expanded into other arguments. For example, /// `edge(p1, p2, "=>")` is short for `edge(p1, p2, marks: (none, "head"), "double")`, or more precisely, the result of `edge(p1, p2, ..fletcher.interpret-marks-arg("=>"))`. /// /// #table( /// columns: (1fr, 4fr), /// align: (center + horizon, horizon), /// [Result], [Value of `marks`], /// ..( /// "->", /// ">>-->", /// "<=>", /// "==>", /// "->>-", /// "x-/-@", /// "|..|", /// "hook->>", /// "hook'->>", /// "||-*-harpoon'", /// ("X", (inherit: "head", size: 15, sharpness: 40deg),), ((inherit: /// "circle", pos: 0.5, fill: auto),), /// ).map(arg => ( /// fletcher.diagram(edge((0,0), (1,0), marks: arg, stroke: 0.8pt)), /// raw(repr(arg)), /// )).join() /// ) /// /// - mark-scale (percent): Scale factor for marks or arrowheads, relative to /// the #param[edge][stroke] thickness. See also #the-param[diagram][mark-scale]. /// /// #diagram( /// label-sep: 10pt, /// edge-stroke: 1pt, /// for i in range(3) { /// let s = (1 + i/2)*100% /// edge((2*i,0), (2*i + 1,0), label: s, "->", mark-scale: s) /// } /// ) /// /// Note that the default arrowheads scale automatically with double and /// triple strokes: /// /// #diagram( /// label-sep: 10pt, /// edge-stroke: 1pt, /// for (i, s) in ("->", "=>", "==>").enumerate() { /// edge((2*i,0), (2*i + 1,0), s, label: raw(s, lang: none)) /// } /// ) /// /// - extrude (array): Draw a separate stroke for each extrusion offset to /// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples /// of the stroke's thickness) or lengths. /// /// #diagram({ /// ( /// (0,), /// (-1.5,+1.5), /// (-2,0,+2), /// (-.5em,), /// (0, 5pt,), /// ).enumerate().map(((i, e)) => { /// edge( /// (2*i, 0), (2*i + 1, 0), [#e], "|->", /// extrude: e, stroke: 1pt, label-sep: 1em) /// }).join() /// }) /// /// Notice how the ends of the line need to shift a little depending on the /// mark. This offset is computed with `cap-offset()`. /// /// See also #the-param[node][extrude]. /// /// - crossing (bool): If `true`, draws a backdrop of color /// #param[edge][crossing-fill] to give the illusion of lines crossing each /// other. /// /// #diagram({ /// edge((0,1), (1,0), stroke: 1pt) /// edge((0,0), (1,1), stroke: 1pt) /// edge((2,1), (3,0), stroke: 1pt) /// edge((2,0), (3,1), stroke: 1pt, crossing: true) /// }) /// /// You can also pass `"crossing"` as a positional argument as a shorthand for /// `crossing: true`. /// /// - crossing-thickness (number): Thickness of the "crossing" background stroke /// (applicable if #param[edge][crossing] is `true`) in multiples of the /// normal stroke's thickness. /// /// #diagram({ /// (1, 2, 4, 8).enumerate().map(((i, x)) => { /// edge((2*i, 1), (2*i + 1, 0), stroke: 1pt, label-sep: 1em) /// edge((2*i, 0), (2*i + 1, 1), raw(str(x)), stroke: 1pt, label-sep: /// 2pt, label-pos: 0.3, crossing: true, crossing-thickness: x) /// }).join() /// }) /// /// Default: #the-param[diagram][crossing-thickness] /// /// - crossing-fill (paint): Color to use behind connectors or labels to give /// the illusion of crossing over other objects. /// /// #let cross(x, fill) = { /// edge((2*x + 0,1), (2*x + 1,0), stroke: 1pt) /// edge((2*x + 0,0), (2*x + 1,1), $f$, stroke: 1pt, crossing: true, crossing-fill: fill, label-fill: true) /// } /// #diagram(crossing-thickness: 5, { /// cross(0, white) /// cross(1, blue.lighten(50%)) /// }) /// /// Default: #the-param[diagram][crossing-fill] /// /// - corner-radius (length, none): Radius of rounded corners for edges with /// multiple segments. Note that `none` is distinct from `0pt`. /// /// #for (i, r) in (none, 0pt, 5pt).enumerate() { /// if i > 0 { h(1fr) } /// fletcher.diagram( /// edge-stroke: 1pt, /// edge((3*i, 0), "r,t,rd,r", "=>", raw(repr(r)), label-pos: 0.6, corner-radius: r) /// ) /// } /// /// This length specifies the corner radius for right-angled bends. The actual /// radius is smaller for acute angles and larger for obtuse angles to balance /// things visually. (Trust me, it looks naff otherwise!) /// /// Default: #the-param[diagram][edge-corner-radius] /// /// - shift (length, number, pair): Amount to shift the edge sideways by, /// perpendicular to its direction. A pair `(from, to)` controls the shifts at /// each end of the edge independently, and a single shift `s` is short for /// `(s, s)`. Shifts can absolute lengths (e.g., `5pt`) or coordinate /// differences (e.g., `0.1`). /// /// #diagram( /// node((0,0), $A$), node((1,0), $B$), /// edge((0,0), (1,0), "->", `3pt`, shift: 3pt), /// edge((0,0), (1,0), "->", `-3pt`, shift: -3pt, label-side: right), /// ) /// /// If an edge has many vertices, the shifts only affect the first and last /// segments of the edge. /// /// #example(``` /// diagram( /// node-fill: luma(70%), /// node((0,0), [Hello]), /// edge("u,r,d", "->"), /// edge("u,r,d", "-->", shift: 8pt), /// node((1,0), [World]), /// ) /// ```) /// /// - snap-to (pair): The nodes the start and end of an edge should snap to. /// Each node can be a position or node #param[node][name], or `none` to disable /// snapping. See also #the-param[node][snap]. /// /// By default, an edge's first and last #param[edge][vertices] snap to nearby /// nodes. This option can be used in case automatic snapping fails (if there /// are many nodes close together, for example.) /// /// - layer (number): Layer on which to draw the edge. /// /// Objects on a higher `layer` are drawn on top of objects on a lower /// `layer`. Objects on the same layer are drawn in the order they are passed /// to `diagram()`. /// /// - post (function): Callback function to intercept `cetz` objects before they /// are drawn to the canvas. /// /// This can be used to hide elements without affecting layout (for use with /// #link("https://github.com/touying-typ/touying")[Touying], for example). /// The `hide()` function also helps for this purpose. /// #let pinit-fletcher-edge( fletcher, start, end: none, start-dx: 0pt, start-dy: 0pt, end-dx: 0pt, end-dy: 0pt, width-scale: 100%, height-scale: 100%, default-width: 30pt, default-height: 30pt, // fletcher.edge arguments ..args, vertices: (), label: none, label-side: auto, label-pos: 0.5, label-sep: auto, label-angle: 0deg, label-anchor: auto, label-fill: auto, label-size: auto, label-wrapper: auto, stroke: auto, dash: none, decorations: none, extrude: (0,), shift: 0pt, kind: auto, bend: 0deg, corner: none, corner-radius: auto, marks: (), mark-scale: 100%, crossing: false, crossing-thickness: auto, crossing-fill: auto, snap-to: (auto, auto), layer: 0, post: x => x, ) = { // fletcher.edge arguments let fletcher-edge-args = ( vertices: vertices, label: label, label-side: label-side, label-pos: label-pos, label-sep: label-sep, label-angle: label-angle, label-anchor: label-anchor, label-fill: label-fill, label-size: label-size, label-wrapper: label-wrapper, stroke: stroke, dash: dash, decorations: decorations, extrude: extrude, shift: shift, kind: kind, bend: bend, corner: corner, corner-radius: corner-radius, marks: marks, mark-scale: mark-scale, crossing: crossing, crossing-thickness: crossing-thickness, crossing-fill: crossing-fill, snap-to: snap-to, layer: layer, post: post, ) pinit( start, ..( if end != none { (end,) } else { () } ), callback: (start-pos, ..other-pos) => { // calculate width and height let width = default-width let height = default-height let start-x = start-pos.x + start-dx let start-y = start-pos.y + start-dy if other-pos.pos().len() > 0 { let end-pos = other-pos.pos().at(0) let end-x = end-pos.x + end-dx let end-y = end-pos.y + end-dy width = calc.abs(start-x - end-x) height = calc.abs(start-y - end-y) width *= width-scale height *= height-scale if width == 0pt or width == 0em { width = default-width } if height == 0pt or height == 0em { height = default-height } } let origin-id = repr(start) + repr(start-dx) + repr(start-dy) + "-origin" // place the diagram directly to get the origin offset absolute-place( dx: start-x, dy: start-y, hide( fletcher.diagram( spacing: (width, height), node-inset: 0pt, fletcher.node((0, 0), pin(origin-id)), fletcher.edge(..args, ..fletcher-edge-args), ), ), ) // place the diagram again with the correct offset pinit( origin-id, callback: origin-pos => { absolute-place( dx: 2 * start-x - origin-pos.x, dy: 2 * start-y - origin-pos.y, fletcher.diagram( spacing: (width, height), node-inset: 0pt, fletcher.node((0, 0), none), fletcher.edge(..args, ..fletcher-edge-args), ), ) }, ) }, ) }
https://github.com/dismint/docmint
https://raw.githubusercontent.com/dismint/docmint/main/comptheory/pset3.typ
typst
#import "template.typ": * #show: template.with( title: "PSET 3", subtitle: "18.404", pset: true, toc: false, ) #set math.vec(delim: "[") = Problem 1 Consider that we have the language: $ L = { angle.l M, w angle.r | w "makes a left move at the leftmost position on" M } $ Now we show how to reduce $A_(T M)$ to $A_L$. Assume that $A_L$ decides the language $L$. Given $angle.l M, w angle.r$, we can construct a reduction with $A_(T M)$ as follows: For convenience, I have called making a left move at the leftmost position an "illegal left move". + If $M$ makes any illegal left moves, then we can simply take them out. I work with the assumption that illegal left moves result in the head staying in its current position. Thus any time we make an illegal left move, we can replace in $M$ by not moving the head, or if we assert that a Turing Machine must move its head, we can turn it into a insignificant move to the right, then the left to achieve the same result. We know have a modified $M$ that does not make any illegal left moves. + Next, take any accepting states in $M$ and replace them with state transitions that move the head all the way to the left, after which they make an illegal move. To note where the head is, we can use a special character so that this sequence of moves can recognize how far it needs to go so we don't move infinitely to the left. + We can then run $A_L$ on this modified $M$ and $w$. If $A_L$ accepts, then we know that $M$ makes an illegal left move, meaning that it must have accepted in the original $M$, and so we can also accept. If $A_L$ rejects, then we know that $M$ does not make an illegal left move, and thus we can reject since it does not reach an accepting state on the original $M$ Thus we have shown that $A_(T M)$ reduces to $A_L$, and with the contradiction of $A_(T M)$ being decidable, $A_L$ is undecidable. = Problem 2 == (a) === Forward Direction *If $A$ is Turing-recognizable, then $A <=_m A_(T M)$* Let us find a mapping function $f$ such that $A <=_m A_(T M)$. Given $A$, we can construct $A_(T M)$ as follows: + We have input $s$ to $A$ + Since $A$ is Turing-recognizable, it must be the case that we can construct $M_A$ such that $L(M_A) = A$ + Then, we can map this to input $angle.l M_A, s angle.r$, which we can feed into $A_(T M)$ If $s$ is in $A$, then $M_A$ will accept, and thus $A_(T M)$ will accept. If $s$ is not in $A$, then $M_A$ will reject, and thus $A_(T M)$ will reject. === Reverse Direction *If $A <=_m A_(T M)$, then $A$ is Turing-recognizable* If the left hand side is true, that means there exists some function $f$ such that it can map $A$ to $A_(T M)$. We can then use this to make a machine that recognizes $A$ as follows: + Given input $s$ to $A$, we can map this to $angle.l M, s angle.r$ using $f$ + We can then run $A_(T M)$ on this input + If $A_(T M)$ accepts, then we know that $s$ is in $A$, and thus we can accept. If $A_(T M)$ rejects, then we know that $s$ is not in $A$, and thus we can reject. We can consider this overall construction as a new machine $M$ that recognizes $A$, and thus $A$ is Turing-recognizable, since $A_(T M)$ itself is Turing-recognizable. == (b) === Forward Direction *If $A$ is decidable, then $A <=_m 0^*1^*$* Because $A$ is decidable, it is quite easy to make a mapping function. + Given input $s$ for $A$, first check it with the finite time decider whether it is in $A$ or not. + If it is in $A$, then we can map it to $01$. If it is not in $A$, then we can map it to $10$. Thus it must be the case that all inputs in the language $A$ are also in $0^*1^*$, and all inputs not in the language $A$ are not in $0^*1^*$ since we manually check with the decider. === Reverse Direction *If $A <=_m 0^*1^*$, then $A$ is decidable* If the left hand side is true, that means there exists some function $f$ such that it can map $A$ to $0^*1^*$. We can then use this to make a machine that decides $A$ as follows: + Given input $s$ to $A$, we can map this to $f(s)$ + We can then check if $f(s)$ is in $0^*1^*$. This is decidable since the right side is a regular expression, and all regular expressions are decidable. Thus we have shown that $A$ is decidable, since we can construct a decider for it using the fact that regular expressions are always decidable. This doesn't always mean that $A$ is a regular language, as we showed in $5.4$ however. = Problem 3 == (a) Let us create a decider for this language. Assume all inputs are CFGs, otherwise trivially reject them. I propose the following decider $D$, that tells whether a CFG $G$ contains an infinite, non-empty loop: + Make a graph with all the non-terminals of $G$ as nodes. For each rule that maps $A -> B$ in $G$, add a directed edge from $A$ to $B$ + Find all cycles in the graph that we create. There are ways for us to bound this, but worst case we must process $O(n)$ such possibilities, where $n$ is the number of non-terminals. + The presence of a cycle means that $G$ contains an infinite loop. However, if the loop consists of empty terminals only, then it is possible that the language is finite. Thus we must check every loop, and if one exists that has a non-empty terminal, then we can accept. If all loops are empty, then we can reject. + There are simpler ways to do this, for example we can simplify $G$ such that it only contains non-empty terminals, so that we can create this decider by simply finding whether any cycle exists in the graph. However for simplicity I have provided a general solution. Then, we can use this decider for the original language. If $D$ rejects a CFG, then we know that it does not contain an infinite, non-empty loop, and thus we can accept. If $D$ accepts a CFG, then we know that it contains an infinite, non-empty loop, and thus we can reject. This is done in a finite amount of time as these graph algorithms have a known time complexity and bound. == (b) We will use a reduction from $overline(H)$ (the complement of the Halting language) to show that it is not the case that this language is Turing-recognizable. Recall that the complement of the Halting language is not Turing-recognizable. Assume that a recognizer $R$ *does* exist for this finite language. Given $angle.l M, w angle.r$, we can construct a reduction to use the recognizer to make a recognizer for $overline(H)$ as follows: + We will start by constructing a machine that simulates $M$ with input $w$. This machine will take in as input how many steps it should run for. Suppose the input is $x$. If the $M$ halts after $x$ steps, then accept $x$. Otherwise, reject $x$. + This language is infinite if $M$ halts, since any $x$ greater than the number of steps it takes for $w$ to halt on $M$ will also be accepted. If $M$ does not halt, then the language is finite since it contains $epsilon$ + Feed this machine into $R$ and see if it is finite. If it is, then we know that $M$ does not halt on $w$, and thus we can accept. If it is infinite, then we know that $M$ halts on $w$, and thus we can reject. Thus we have shown that we reach a contradiction if we assume that this language is Turing-recognizable, and thus it is not the case that this language is Turing-recognizable. = Problem 4 Let us use the reduction from PCP as suggested. Let us assume that we have a decider for the DISJOINT language. I will show how we can reduce PCP to DISJOINT and use the decider to make PCP decidable as well. Using the formulation given on the PSET, we can construct a way to transform a PCP instance to a DISJOINT instance. I will discuss why the approach works. Below is a summary of what this looks like: $ P = {vec(t_1, b_1), vec(t_2, b_2), ..., vec(t_k, b_k)}\ G: T -> t_1 T a_1 | t_2 T a_2 | ... | t_k T a_k | t_1 a_1 | t_2 a_2 | ... | t_k a_k\ H: B -> b_1 B a_1 | b_2 B a_2 | ... | b_k B a_k | b_1 a_1 | b_2 a_2 | ... | b_k a_k\ $ The key here lies in the new terminals $a_i$ that are introduced. The first and back half of $G$ and $H$ are nearly identical, except the first half allows for further building through repeated non-terminals, while the back half are all terminals. Let us think about what happens when either $G$ or $H$ fully produce a string. The first half will either be a string of $t_i$ or $b_i$, while the second half will be a string of $a_i$ In other words, the first half of the string generates the actual string that is produces from the dominoes, while the back half of each string essentially encodes which set of dominoes from the original $P$ were used. It would not be enough for the two CFGs to produce the end result strings, because we must also ensure that they are tiled using the same set of dominoes. The last encoding ensures that not only are the two strings equal, but that they were matched using a set of dominoes from $P$ by the rules that PCP defines. Thus, now that we have this transformation, we can compare the two grammars on $R$. If $R$ accepts, then we know that there does not exist a matching and thus we can reject. If $R$ rejects, then we know that there exists a matching and thus we can accept. This is a decider for PCP, and thus we have shown that the DISJOINT language is undecidable since this forces PCP to be decidable as well, which we know is not the case. = Problem 5 == (a) The key insight to make here is that the length of the tape is finite along with the fact that it is read only. This means that there are a finite set of possible configurations of the machine. Suppose there are $q$ states, and that the length of the tape is $n$. The only things to keep track of are: + The current state of the machine + The position of the first head + The position of the second head This means that there are $q n^2$ possible configurations of the machine. We can then construct a decider for this language as follows: + Given input $angle.l M, w angle.r$, make a machine $M'$ that simulates $M$ on $w$ for $q n^2$ steps + If $M$ halts, then $M'$ will halt in $q n^2$ steps. If $M$ does not halt, then $M'$ will not halt in $q n^2$ steps. + Thus after $q n^2$ steps, we will accept if we reached an accept state, and reject if we did not (either we got rejected or there was an infinite loop) Thus we have shown that this language is decidable as we can create a decider for the language. == (b) We can use a reduction similar to what we saw in class. For this question, we will reduce from $E_(T M)$ using the following steps: + Given $M$ for $E_(T M)$, we construct a new machine $M'$ that recognizes all accepting computation histories of $M$. We do this with the encoding discussed in class with '\#' delimiters. + We can use one pointer head at the $i$-th configuration, and the other pointer head at the $i+1$-th configuration. We can then use the pointer heads to check whether each step of the configuration is a valid one by $M$ + Now that we have $M'$, we feed it into the $D$, the decider for $E_"2DFA"$. If $D$ accepts then it must be the case that $M$ is also empty, and thus we can accept. If $D$ rejects, then it must be the case that $M$ is not empty, and thus we can reject. Thus we have shown that this language is decidable as we have reduced from $E_(T M)$, which we know is undecidable. Therefore it must be the case that this language is undecidable as well. = Problem 6 == Code / Output Unfortunately lines `12` and `15` are relatively long so they don't render on the PSET as one line. However, if you copy paste it will yield the correct text. This program prints itself exactly, including the quotes, so the output would be the exact same as this code block below. ```python # 18.404 PSET 3 Q6 sq = "'" dq = '"' nl = '\n' bs = '\\' f1 = "def f(s, s1, s2, s3):" f2 = " print(s+'1 = '+dq+s1+dq+nl+s+'2 = '+dq+s2+dq+nl+s+'3 = '+dq+s3+dq)" f3 = " print(s1+nl+s2+nl+s3)" def f(s, s1, s2, s3): print(s+'1 = '+dq+s1+dq+nl+s+'2 = '+dq+s2+dq+nl+s+'3 = '+dq+s3+dq) print(s1+nl+s2+nl+s3) p1 = "print('# 18.404 PSET 3 Q6'+nl+'sq = '+dq+sq+dq+nl+'dq = '+sq+dq+sq+nl+'nl = '+sq+bs+'n'+sq+nl+'bs = '+sq+bs+bs+sq)" p2 = "f('f', f1, f2, f3)" p3 = "f('p', p1, p2, p3)" print('# 18.404 PSET 3 Q6'+nl+'sq = '+dq+sq+dq+nl+'dq = '+sq+dq+sq+nl+'nl = '+sq+bs+'n'+sq+nl+'bs = '+sq+bs+bs+sq) f('f', f1, f2, f3) f('p', p1, p2, p3) ```
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/dialogue.typ
typst
#import "@preview/tablex:0.0.7": gridx, vlinex #let bold-name(name) = { align(left)[*#name*] } #let dialogue-item(name, content) = { let grid = gridx( inset: 10pt, columns: (80pt, 1fr), bold-name(name), vlinex(stroke: black + 0.1pt), content ) [#grid] v(20pt) } #let dialogue-runner-deprecated(items) = locate(loc => { for item in items { [#loc.position()] if loc.position().y > 100pt { pagebreak() } dialoguer(item, content) } }) #let dialogue-runner(items) = { for item in abc { dialogue-item(..item) } } #let str-split(s, r) = { return s.split(regex(r)).filter(x => x.len() > 0) }
https://github.com/zenor0/simple-neat-typst-cv
https://raw.githubusercontent.com/zenor0/simple-neat-typst-cv/master/cv/utils/set-cv.typ
typst
MIT License
#import "packages.typ": show-cn-fakebold #import "fonts.typ": font_lib, size_lib #let set-cv(bilingual-bib: true, doc) = { set page(paper: "a4", margin: (top: 1cm, bottom: 1cm, left: 1cm, right: 1cm)) set text(font: font_lib.main, size: size_lib.小五, weight: "regular", lang: "zh") // set par(first-line-indent: 2em, leading: 15pt, justify: true) set par(first-line-indent: 2em, justify: true) show par: set block(spacing: 15pt) show raw.where(block: false): it => box( inset: (x:1pt, y:1pt), box( fill: luma(240), inset: (x: 2pt), outset: (y: 3pt), radius: 3pt )[#text(font: font_lib.main, fill: luma(100))[#it]]) // show: show-cn-fakebold doc }
https://github.com/JCGoran/typst-cv-template
https://raw.githubusercontent.com/JCGoran/typst-cv-template/master/example.typ
typst
// main imports from the template #import "template.typ": conf, date, show_skills // import details about a person as a typst dictionary // you can also define it here, I just find it easier to keep this constant, // and change the content if needed #let details = toml("cv_params.toml") // don't forget this #show: doc => conf(details, doc) // headers are overloaded via show rules so they appear nicer = Work Experience == Software Engineer #date([Jan 2023 -- present]) === Company Foo // so are list items - #lorem(100) == Junior Software Engineer// no date here === Company Bar - #lorem(30) - #lorem(10) - #lorem(50) - #link("https://github.com/JCGoran")[links] have a consistent color with the rest of the document = Education == Master in Philosophy #date([2015 -- 2017]) #lorem(40) = Skills // `show_skills` takes a dictionary as input and outputs a table-looking item #show_skills( ( "Programming Languages": ("Python", "C++", "Rust", "Typst (does that count?)"), "Technologies": ("GitHub Actions", "GitLab CI", "Others"), "Lipsum": lorem(12).split(), ), ) = Other - #lorem(50) - #lorem(100) - #lorem(35)
https://github.com/SidneyLYZhang/learnTypst
https://raw.githubusercontent.com/SidneyLYZhang/learnTypst/main/Documentation/Sources/001_writing-in-typst.typ
typst
#set text(font:("Consolas", "Source Han Sans SC")) #set text(lang: "zh") #show emph: text.with(font: ("Linux Libertine","STKaiti")) #show link: text.with(fill: blue) = 用Typst写作 让我们开始吧!假设你被分派写一篇大学的技术报告。它将包含一些段落、数学公式、标题和图表。为了处理这项工作,你在Typst应用程序上创建了一个新项目。创建完成后,你会被带到编辑器界面,在那里会看到两个面板:一个源面板,用来编写你的文档;一个预览面板,用来看到渲染后的文档。 #align(center, image("images/1-writing-app.png", width: 70%)) 你已经对报告的角度有了一个很好的想法。那么让我们开始写引言。在编辑面板中输入一些文本。你会注意到文本立即出现在预览页面上。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst In this report, we will explore the various factors that influence fluid dynamics in glaciers and how they contribute to the formation and behaviour of these natural structures.``` #align(center, image("images/1-right-yulan.png")) ]) #emph[在本教程中,我们将展示像这样的代码示例。就像在应用程序中一样,第一个面板包含标记,第二个面板显示预览。我们缩小了页面以适应示例,这样你就可以看到发生了什么。] 下一步是添加标题并强调一些文本。Typst 使用简单的标记来完成最常见的格式化任务。要添加标题,请输入 ``` =``` 字符;要用斜体强调一些文本,请将其置于 ``` _下划线_``` 之间。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst = Introduction In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers and how they contribute to the formation and behaviour of these natural structures.``` #align(center, image("images/1-right-yulan-2.png")) ]) 太简单了!要添加一个新的段落,就在两行文本之间添加一行空白。如果那个段落需要一个副标题,就输入 `==` 而不是 `=` 。等号的数量决定了标题的嵌套级别。 现在,我们要列出几个影响冰川动力学的情况。为此,我们使用编号列表。对于每个列表项,我们在行的开头输入一个 `+` 字符。Typst会自动为每个项编号。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst + The climate + The topography + The geology``` #align(center, image("images/1-right-yulan-3.png")) ]) 如果我们想要添加带项符号的列表,我们会使用 `-` 符号而不是 `+` 符号。我们也可以嵌套列表:例如,我们可以通过缩进来为上面的列表的第一个项目添加一个子列表。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst + The climate - Temperature - Precipitation + The topography + The geology``` #align(center, image("images/1-right-yulan-4.png")) ]) == 添加图片 如果你认为你的报告会因为一张图片更出色,让我们来添加一张吧。Typst支持PNG、JPEG、GIF和SVG格式的图片。要把你项目中的一个图片文件添加进来,首先点击左侧边栏中的盒子图标来打开文件面板。在这里,你可以看到你项目中的所有文件。目前只有一个:你正在写的主Typst文件。要上传另一个文件,点击右上角带有箭头的按钮。这会打开一个上传对话框,你可以从中选择电脑中的文件进行上传。为你的报告选择一张图片。 #align(center, image("images/1-writing-upload.png", width: 90%)) 我们之前已经看到,特定的符号(称为标记)在Typst中有着特定的含义。我们可以使用 `=`,`-`,`+`,和 `_` 来创建标题、列表和强调文本。但是,如果我们想要将文档中的每一个想要插入的内容都使用一个特殊的符号,很快就会变得难以理解且不易操作。出于这个原因,Typst只保留标记符号来处理最常见的情况。其他所有内容都是通过函数插入的。为了使图片出现在页面上,我们使用Typst的 #link("https://typst.app/docs/reference/visualize/image/")[`image`] 函数。 #box(height: 150pt, columns(2, gutter: 11pt)[ ```typst #image("glacier.jpg")``` #align(center, image("images/1-right-yulan-5.png")) ]) 一般来说,一个函数会为给定的_参数集_产生一些输出。当你在标记中使用函数时,你需要提供参数,Typst会将函数的_返回值_插入到文档中。在我们的情况下,`image`函数需要提供一个参数:图片文件的路径。在标记中使用函数时,我们首先需要输入`#`字符,紧接着输入函数的名称。然后,我们将参数用括号括起来。Typst可以识别参数列表中的许多不同类型的数据。我们的文件路径是一个#link("https://typst.app/docs/reference/foundations/str/")[短字符串],因此我们需要将其用双引号括起来。 插入的图片使用了整个页面的宽度。要更改该宽度,可以将`width`参数传递给`image`函数。这是一个命名参数,因此应该以`name: value`对的形式指定。如果有多个参数,它们应该用逗号分隔,所以我们需要在路径后面先添加一个逗号。 #box(height: 90pt, columns(2, gutter: 11pt)[ ```typst #image("glacier.jpg", width: 70%)``` #align(center, image("images/1-right-yulan-6.png")) ]) 宽度参数( `width` )是一个 #link("https://typst.app/docs/reference/layout/relative/")[相对长度] 。在本例中,我们指定了一个百分比值,这意味着图像将占据页面宽度的 `70%` 。同样地,我们也可以指定绝对值,例如 `1cm` 或 `0.7in` 。 就像文本一样,图片默认是左对齐的。但它缺少一个标题。通过使用 #link("https://typst.app/docs/reference/model/figure/")[`figure`] 函数,我们可以解决这个问题。这个函数接受作为位置参数的图片内容和一个可选的标题作为命名参数。 在 `figure` 函数的参数列表中,Typst已经进入了代码模式。这意味着,现在你需要去掉图片函数调用前的井号。井号仅在标记中需要(用于区分文本与函数调用)。 标题可以包含任意的标记。要向函数提供标记,我们将其包围在方括号内。这种结构被称为 _内容块_ 。 #box(height: 100pt, columns(2, gutter: 11pt)[ ```typst #figure( image("glacier.jpg", width: 70%), caption: [ _Glaciers_ form an important part of the earth's climate system. ], )``` #align(center, image("images/1-right-yulan-7.png")) ]) 你继续撰写报告,现在想要引用图表。要做到这一点,首先为图表添加标签。标签能唯一标识文档中的元素。在 #link("https://typst.app/docs/reference/model/figure/")[`figure`] 后面添加一个名字,用角度括号括起来即可。然后,在你的文本中,你可以通过写一个 `@` 符号后跟那个名字来引用图表。标题和方程式也可以被标记以使其可被引用。 #box(height: 170pt, columns(2, gutter: 11pt)[ ```typst Glaciers as the one shown in @glaciers will cease to exist if we don't take action soon! #figure( image("glacier.jpg", width: 70%), caption: [ _Glaciers_ form an important part of the earth's climate system. ], ) <glaciers>``` #align(center, image("images/1-right-yulan-8.png")) ]) #align( center, align( left, block( width: 90%, [ *信息 INFO* \ \ 到目前为止,我们已经将内容块(方括号内的标记)和字符串(双引号内的文本)传递给我们的函数。两者似乎都包含文本。那么它们有什么区别呢?\ 内容块可以包含文本,但也可以包含任何其他类型的标记、函数调用等,而字符串实际上只是一系列字符,除此之外别无他物。\ 例如, `image` 函数期望一个指向图像文件的路径。它将无法通过传递一段文本或其他图像作为路径参数来获取图像。这就是为什么在这里只允许字符串的原因。相反,字符串在任何需要内容的地方都是有效的,因为文本是一种有效的内容类型。\ ], fill: aqua, stroke : blue, radius: 8pt, inset: 18pt ) ) ) == 添加参考文献 在撰写报告时,你需要支持你的论点。您可以使用 #link("https://typst.app/docs/reference/model/bibliography/")[`bibliography`] 函数向文档添加参考文献。此函数期望一个指向参考文献文件的路径。 Typst原生的参考文献格式是 #link("https://github.com/typst/hayagriva/blob/main/docs/file-format.md")[`Hayagriva`] ,但是为了兼容性,您也可以使用 BibLaTeX 文件。由于您的同学已经进行了文献调研并向您发送了一个 `.bib` 文件,因此您将使用该文件。通过文件面板上传文件以在Typst中访问它。 一旦文档中包含参考文献,您就可以开始引用它。引用的语法与参考标签相同。一旦您第一次引用某个来源,它就会出现在文档的参考文献部分。Typst支持不同的引用和参考文献样式。有关更多详细信息,请参阅 #link("https://typst.app/docs/reference/model/bibliography/#parameters-style")[参考文献] 。 #box(height: 80pt, columns(2, gutter: 11pt)[ ```typst = Methods We follow the glacier melting models established in @glacier-melt. #bibliography("works.bib")``` #align(center, image("images/1-right-yulan-9.png")) ]) == 数学 在详细阐述了方法部分之后,论文的核心部分便展现在读者眼前:你的方程式。Typst 旨在实现数学排版功能,并采用自身独特的数学符号体系。我们从一个简单的方程式开始。为了指示 Typst 准备接收数学表达式,我们用 `$` 符号将其包围起来: #box(height: 45pt, columns(2, gutter: 11pt)[ ```typst The equation $Q = rho A v + C$ defines the glacial flow rate.``` #align(center, image("images/1-right-yulan-10.png")) ]) 这个方程式是内嵌式排版的,与周围的文本在同一行中显示。如果您希望将其单独显示在新的一行,则需要在方程式前后各输入一个空格: #box(height: 60pt, columns(2, gutter: 11pt)[ ```typst The flow rate of a glacier is defined by the following equation: $ Q = rho A v + C $``` #align(center, image("images/1-right-yulan-11.png")) ]) 我们可以发现,Typst 对单个字母 `Q`、`A`、`v` 和 `C` 原样显示,而将 `rho` 转译为了希腊字母。数学模式会始终原样显示单个字母。然而,多个字母会被解释为符号、变量或函数名。若要表示单个字母之间的乘法,只需在它们之间加入空格。 如果你想要表示由多个字母组成的变量,可以将它们用引号括起来: #box(height: 60pt, columns(2, gutter: 11pt)[ ```typst The flow rate of a glacier is given by the following equation: $ Q = rho A v + "time offset" $``` #align(center, image("images/1-right-yulan-12.png")) ]) 在你的论文中,你还需要一个求和公式。我们可以使用 `sum` 符号,然后在下标和上标中指定求和的范围。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst Total displaced soil by glacial flow: $ 7.32 beta + sum_(i=0)^nabla Q_i / 2 $``` #align(center, image("images/1-right-yulan-13.png")) ]) 要为符号或变量添加下标,请输入 `_` 字符,然后输入下标内容。同样,使用 `^` 字符可添加上标。如果你的下标或上标由多个元素组成,必须将它们括在圆括号内。 上述示例还向我们展示了如何插入分数:只需在分子和分母之间放置一个 `\` 字符,Typst就会自动将其转换为分数。括号会被智能解析,因此你可以像在计算器中那样输入表达式,Typst会将带括号的子表达式替换为适当的符号表示。 #box(height: 70pt, columns(2, gutter: 11pt)[ ```typst Total displaced soil by glacial flow: $ 7.32 beta + sum_(i=0)^nabla (Q_i (a_i - epsilon)) / 2 $``` #align(center, image("images/1-right-yulan-14.png")) ]) 并非所有数学结构都有特殊语法。相反,我们使用函数,就像之前见过的 `image` 函数一样。例如,要插入列向量,我们可以使用 #link("https://typst.app/docs/reference/math/vec/")[`vec`] 函数。在数学模式下,函数调用不需要以 `#` 字符开头。 #box(height: 55pt, columns(2, gutter: 11pt)[ ```typst $ v := vec(x_1, x_2, x_3) $``` #align(center, image("images/1-right-yulan-15.png")) ]) 某些函数仅在数学模式下可用。例如,#link("https://typst.app/docs/reference/math/variants/#functions-cal")[`cal`] 函数用于排版常用于表示集合的花体字母。#link("https://typst.app/docs/reference/math/")[参考手册的数学部分]提供了数学模式下所有可用函数的完整列表。 还有一点值得注意:许多符号,如箭头,都有很多变体。你可以通过在符号名称后附加一个点和修饰符名称来选择这些变体。 #box(height: 50pt, columns(2, gutter: 11pt)[ ```typst $ a arrow.squiggly b $``` #align(center, image("images/1-right-yulan-16.png")) ]) 这种表示法在标记模式下也可用,但符号名称前必须加上 `#sym` 。请参阅#link("https://typst.app/docs/reference/symbols/sym/")[符号部分]以获取所有可用符号的列表。 == 回顾 现在你已经了解了如何在 Typst 中编写基本文档。你学会了如何强调文本、编写列表、插入图像、对齐内容以及排版数学表达式。你还学习了Typst的函数。Typst还允许你在文档中插入许多其他类型的内容,如#link("https://typst.app/docs/reference/model/table/")[表格(tables)]、#link("https://typst.app/docs/reference/visualize/")[图形(shapes)]和#link("https://typst.app/docs/reference/text/raw/")[代码块]。你可以浏览#link("https://typst.app/docs/reference/")[参考手册]以了解更多这些功能和其他特性。 目前,你已完成报告的编写。你已经通过点击右上角的下载按钮保存了PDF文件。然而,你认为报告看起来可能有点过于朴素。在下一节中,我们将学习如何自定义文档的外观。
https://github.com/tfachada/thesist
https://raw.githubusercontent.com/tfachada/thesist/main/template/Chapters/0-Quick-guide.typ
typst
MIT License
// It's recommended to always import these! #import "@preview/thesist:0.2.0": flex-caption, subfigure-grid #import "@preview/glossarium:0.5.0": gls, glspl // Optionally import more packages, depending on the chapter's needs. In the case of this chapter, we will use these: #import "@preview/codly:1.0.0": * #import "@preview/lovelace:0.3.0": * // Check Typst Universe to look for new packages you might need, and always read their description page to know how to handle them. = A quick guide to using this template == About this chapter This chapter is a tutorial on how to use this template's features. This is _not_ about Typst itself, but rather about how to make full and correct use of this thesis package. If you're reading this just from the PDF, please look at the code too. This is a new paragraph. You already saw the `import` statements and the `//comments` in the code, right? Let's move on, then! == Figures This is a simple image call: #figure( image("../Images/0-Quick-guide/andromeda.jpg", width: 80%), caption: [An image] )<example_simple_image> In order to index @example_simple_image, we need to *always* wrap it in a `figure()` call and give it a `caption`. Indexing all the image calls in the thesis is mandatory! *Note:* If you want to draw images using Typst packages like #link("https://typst.app/universe/package/cetz")[CeTZ], you can still index them as if they were normal images, by wrapping them in a `figure()` call. You may have to manually specify that figure's `kind` parameter as `image` (_no quotation marks_), but Typst usually detects that automatically. === Flexible captions The first function of this thesis package that will be presented here is `flex-caption`. Consider the following picture: #figure( image("../Images/0-Quick-guide/andromeda.jpg", width: 80%), caption: flex-caption( [This is a very long picture caption that goes into detail about some things. #lorem(20)], [A short version of the caption] ) )<example_flex_caption> Look now at the image index back at the beginning of the thesis, and see the caption @example_flex_caption has in there. Instead of it being cluttered with this long caption, it has the short version in there. Might be useful! === Tables Tables also have to be indexed. Although they are not figures in the usual sense of the word, from a coding point of view they are when they are indexed with the `figure` function. #figure( table( columns: 2, [*First name*], [*Last name*], [Foo], [Bar], [Bar], [Foo], ), caption: [A table] ) Typst automatically detects that this is a different type of `picture`, and as such calls it "Table" instead of "Figure" and numbers it differently. === Code snippets Like tables, code figures will be automatically interpreted as their own type - in this case, `raw`. You can either call one in the traditional way, like this: #figure( caption: [A piece of code], ``` pub fn main() { println!("Hello, world!"); } ``` ) Or use an imported package which function call will be interpreted by `figure` as a `raw`. An example of such a package is #link("https://typst.app/universe/package/codly")[`codly`]: // Notice that the content block can go either inside #figure() or right after it. // Pick whichever form you prefer. What's important is that #figure() affects that block by making it numbered. #figure( caption: [A fancy piece of code] )[ // This show rule would normally be at the top of the document, but putting it here to prevent it from affecting other examples #show: codly-init.with() #codly( languages: ( rust: ( name: "Rust", //icon: text(font: "tabler-icons", "\u{fa53}"), color: rgb("#CE412B") ), ) ) ```rust pub fn main() { println!("Hello, world!"); } ``` ] *Note:* This is just an example. To know how to use a certain package to its full extent, including any that is used in this guide, be sure to read its documentation. === Algorithms Depending on what your thesis is about, you might want to display and index algorithms. Algorithm pictures are not native to Typst and were specified in this package for your convenience. Since they are custom, they are not detected automatically, and as such you need to specify its `kind` parameter _with quotation marks_ (you need them because it's not a default type). You can either define an algorithm with `raw text`: #figure( kind: "algorithm", caption: [A simple algorithm], [ ``` 1: Do stuff 2: Do more stuff 3: Stuff <- stuff ... N: You get stuff ``` ] ) Or use a package like #link("https://typst.app/universe/package/lovelace")[`lovelace`] to make it fancier: #figure( kind: "algorithm", caption: [A very smart algorithm] )[ #pseudocode-list[ + do something + do something else + *while* still something to do + do even more + *if* not done yet *then* + wait a bit + resume working + *else* + go home + *end* + *end* ] ] === Subfigures Subfigures are implemented in this template via the function `subfigure-grid`. This is a slightly modified version of the `grid` function of the #link("https://typst.app/universe/package/subpar")[`subpar`] package for subfigures. The modifications allow it to work with the numbering used by figures in this thesis. This is `subfigure-grid` in action: #subfigure-grid( in-appendix: false, figure( image("../Images/0-Quick-guide/andromeda.jpg", width: 90%), caption: [An image on the left.] ), <sub-left-example>, figure( image("../Images/0-Quick-guide/andromeda.jpg", width: 90%), caption: [An image on the right.#v(1em)] ), <sub-right-example>, align: top, columns: (1fr, 1fr), caption: [A figure composed of two subfigures], label: <subfigure-grid-example>, ) Above in @subfigure-grid-example, we see a figure which is composed of two other figures, namely @sub-left-example and @sub-right-example. *Important note:* Subfigures are still an experimental feature. As such, there are two things to keep an eye for if you use them: - If the subfigures or their captions aren't positioned in the way you want, try messing with the `align` parameter and `#v()` spacers above or below text. This was done in @subfigure-grid-example. - Subfigure grids, contrary to other figures, don't show up with the correct numbering by default (check this template's homepage for more details on why). As such, you will have to manually specify whether the figure is inside an appendix or not, with the `in-appendix` argument. == A note about equations Like figures, equations also need to be centered and numbered. #linebreak() This is wrong: $E = m c^2$ // don't do this! This is also wrong: #align(center, $E = m c^2$) // don't do this! This is right: $ E = m c^2 $ == Using the Glossary This template's Glossary feature is implemented by default with the #link("https://typst.app/universe/package/glossarium")[`glossarium`] package. To reference glossary entries, you use the `#gls()` and `#glspl()` commands, depending on whether you want to write the singular or the plural form. Some example references are #gls("mu_0"), #glspl("potato"), #glspl("dm") and #gls("ist"). The latter two become just #glspl("dm") and #gls("ist") after their first usage. Glossary entries are set up in the `Glossary.typ` file, which guides you on how to manage entries. == Using the Bibliography Simply reference the bibliography items in the same way you would do for figures. Like this: @Madje_Typst Paste LaTeX-style references in `refs.bib`, or switch to a `.yaml` file based on Typst's native format if you want. == Afterword You can keep this file in the project while removing it from `main.typ` if you want to keep it as a reference. Keep in mind that this template may receive new features in the future; this will be influenced, in part, by the evolution of both the package ecosystem and Typst itself. You can always check for updates and update the package in your document. Instructions will be given on the template's changelog if you need to take any extra steps besides just changing the version in your import statements. *Feel free to contribute to this package's repository if you so wish.*
https://github.com/emfeltham/Typst.jl
https://raw.githubusercontent.com/emfeltham/Typst.jl/main/exampletable.typ
typst
MIT License
#import"@preview/tablex:0.0.8": tablex, gridx, hlinex, vlinex, colspanx, rowspanx, cellx #let col1width = 12em #let coliwidth = auto #figure( kind: table, gridx( columns: (col1width, coliwidth, coliwidth, coliwidth, ), rows: (0.2em, 1.5em), align: center + horizon, hlinex(y: 0, stroke: 0.05em), cellx(x: 0, y: 0, colspan: 4)[], hlinex(y: 1, stroke: 0.05em), cellx(x: 1, y: 1)[(1)], cellx(x: 2, y: 1)[(2)], cellx(x: 3, y: 1)[(3)], hlinex(start: 1, y: 2, stroke: 0.05em), cellx(x: 0, y: 6, align: left)[Z], cellx(x: 2, y: 6)[2.5#super[$+$]], cellx(x: 2, y: 7)[(0.289)], cellx(x: 3, y: 6)[-0.222], cellx(x: 3, y: 7)[(0.208)], cellx(x: 0, y: 4, align: left)[X], cellx(x: 1, y: 4)[2.5#super[$+$]], cellx(x: 1, y: 5)[(0.289)], cellx(x: 3, y: 4)[2.722], cellx(x: 3, y: 5)[(0.487)], cellx(x: 0, y: 2, align: left)[(Intercept)], cellx(x: 1, y: 2)[-0.667], cellx(x: 1, y: 3)[(0.624)], cellx(x: 2, y: 2)[-8.167], cellx(x: 2, y: 3)[(1.462)], cellx(x: 3, y: 2)[0.0], cellx(x: 3, y: 3)[(NaN)], hlinex(start: 1, y: 8, stroke: 0.05em), cellx(x: 0, y: 8, align: left)[N], cellx(x: 0, y: 12, align: left)[BIC], cellx(x: 0, y: 9, align: left)[$R^2$], cellx(x: 0, y: 11, align: left)[AIC], cellx(x: 0, y: 10, align: left)[Adjusted $R^2$], cellx(x: 1, y: 8)[3], cellx(x: 1, y: 12)[3.138], cellx(x: 1, y: 9)[0.987], cellx(x: 1, y: 11)[5.843], cellx(x: 1, y: 10)[0.974], cellx(x: 2, y: 8)[3], cellx(x: 2, y: 12)[3.138], cellx(x: 2, y: 9)[0.987], cellx(x: 2, y: 11)[5.843], cellx(x: 2, y: 10)[0.974], cellx(x: 3, y: 8)[3], cellx(x: 3, y: 12)[3.138], cellx(x: 3, y: 9)[0.987], cellx(x: 3, y: 11)[5.843], cellx(x: 3, y: 10)[0.974], hlinex(y: 13, stroke: 0.1em), cellx(y: 13, colspan: 4, align: left)[_Note:_ $#super[+]p<0.10$; $#super[$star.op$]p<0.05$; $#super[$star.op star.op$]p<0.01$, $#super[$star.op star.op star.op$]p<0.001$] ), caption: [Models of Y.] )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-A9E0.typ
typst
Apache License 2.0
#let data = ( ("MYANMAR LETTER SHAN GHA", "Lo", 0), ("MYANMAR LETTER SHAN CHA", "Lo", 0), ("MYANMAR LETTER SHAN JHA", "Lo", 0), ("MYANMAR LETTER SHAN NNA", "Lo", 0), ("MYANMAR LETTER SHAN BHA", "Lo", 0), ("MYANMAR SIGN SHAN SAW", "Mn", 0), ("MYANMAR MODIFIER LETTER SHAN REDUPLICATION", "Lm", 0), ("MYANMAR LETTER TAI LAING NYA", "Lo", 0), ("MYANMAR LETTER TAI LAING FA", "Lo", 0), ("MYANMAR LETTER TAI LAING GA", "Lo", 0), ("MYANMAR LETTER TAI LAING GHA", "Lo", 0), ("MYANMAR LETTER TAI LAING JA", "Lo", 0), ("MYANMAR LETTER TAI LAING JHA", "Lo", 0), ("MYANMAR LETTER TAI LAING DDA", "Lo", 0), ("MYANMAR LETTER TAI LAING DDHA", "Lo", 0), ("MYANMAR LETTER TAI LAING NNA", "Lo", 0), ("MYANMAR TAI LAING DIGIT ZERO", "Nd", 0), ("MYANMAR TAI LAING DIGIT ONE", "Nd", 0), ("MYANMAR TAI LAING DIGIT TWO", "Nd", 0), ("MYANMAR TAI LAING DIGIT THREE", "Nd", 0), ("MYANMAR TAI LAING DIGIT FOUR", "Nd", 0), ("MYANMAR TAI LAING DIGIT FIVE", "Nd", 0), ("MYANMAR TAI LAING DIGIT SIX", "Nd", 0), ("MYANMAR TAI LAING DIGIT SEVEN", "Nd", 0), ("MYANMAR TAI LAING DIGIT EIGHT", "Nd", 0), ("MYANMAR TAI LAING DIGIT NINE", "Nd", 0), ("MYANMAR LETTER TAI LAING LLA", "Lo", 0), ("MYANMAR LETTER TAI LAING DA", "Lo", 0), ("MYANMAR LETTER TAI LAING DHA", "Lo", 0), ("MYANMAR LETTER TAI LAING BA", "Lo", 0), ("MYANMAR LETTER TAI LAING BHA", "Lo", 0), )