repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/Shedward/dnd-charbook
https://raw.githubusercontent.com/Shedward/dnd-charbook/main/dnd/core/layout.typ
typst
#import "dimentions.typ": * #import "graphics.typ": * #import "styles.typ": * // Set of available fittings // Container shrink around container #let shrink = "shrink" // Content expand to all available space #let expand = "expand" // Content expand horizontally, but shrink vertically #let expand-h = "expand-h" // Content expand vertically, but shrink horizontally #let expand-v = "expand-v" // Content tries to keep square form for available space #let squared = "squared" // Helper function for building any container. // - fitting: Declares how layout of container works. Can be shrink, expand, expand-h or expand-v // - insets: Inner insets around background // - background: Arbitrary shape to frame content // - body: Actual content #let container( fitting: shrink, insets: paddings(1), background: (size) => rect(width: size.width, height: size.height), body ) = { layout(size => { let padArgs = if type(insets) == dictionary { insets } else { (rest: insets) } let bodyWithPadding = pad(..padArgs)[#body] let contentSize = () => { measure(block(width: size.width)[#bodyWithPadding]) } let size = if fitting == expand { size } else if fitting == shrink { measure(bodyWithPadding) } else if fitting == expand-h { (width: size.width, height: contentSize().height) } else if fitting == expand-v { (width: contentSize().width, height: size.height) } else if fitting == squared { let minDimention = calc.min(size.width, size.height) (width: minDimention, height: minDimention) } else { panic("fitting " + fitting + " is not supported, expected: shrink|expand|expand-h|expand-v") } [ #block(width: size.width, height: size.height)[ #background(size) ] #place(center + horizon)[ #block(width: size.width, height: size.height)[ #bodyWithPadding ] ] ] }) } // Container wrappend in frame. // Parameters: // - stroke: Stroke width #let framed( stroke: strokes.thin, radius: paddings(1) - 0.1 * paddings(1), insets: paddings(1), fitting: shrink, body ) = container( fitting: fitting, insets: insets, background: size => frame( width: size.width, height: size.height, stroke: stroke, radius: radius ), body ) #let propBox( shape: frame.with(radius: paddings(1) - 0.1 * paddings(1)), dx: 0pt, dy: 0pt, width: 100%, height: 100%, body ) = container( fitting: squared, background: size => shape( width: size.width, height: size.height, stroke: strokes.normal ), box(width: width, height: height)[ #place(bottom + center, dx: dx, dy: dy)[ #propCap[ #body ] ] ] ) #let badge( caption: none, height: auto, width: auto, alignment: top + right, body ) = [ #box[ #body #place(alignment)[ #rect( width: width, height: height, fill: white, stroke: strokes.normal )[ #propCap(caption) ] ] ] ] #let repeated(count, spacing: paddings(1), body) = grid( row-gutter: spacing, ..(range(count).map(_ => body)) ) #let innerRowStrokes(stroke: strokes.hairline) = (x, y) => ( top: if y > 0 { stroke } else { 0pt }, bottom: none ) #let innerColumnStrokes(stroke: strokes.hairline) = (x, y) => ( left: if x > 0 { stroke } else { 0pt }, right: none ) #let simpleTable(header, ..cells) = { let headerCell(content) = table.cell( stroke: none, tableHeader(content) ) table( columns: header.len(), stroke: strokes.hairline, table.header(..(header.map(headerCell))), ..cells ) } #let inputGrid(lines, lineHeight: paddings(3), width: 100%) = { let gridBox(body) = box(width: width, height: lines * lineHeight, body) let gridLine(y) = line(start: (0%, y), length: 100%, stroke: strokes.hairline) if lines == auto { todo("Not implemented") } else if lines == 0 { none } else if lines == 1 { gridBox[ #gridLine(lineHeight) ] } else { gridBox[ #for lineNumber in range(1, lines) { place(center, gridLine(lineHeight * lineNumber)) } ] } }
https://github.com/r8vnhill/keen-manual
https://raw.githubusercontent.com/r8vnhill/keen-manual/main/omp/rep_ev.typ
typst
BSD 2-Clause "Simplified" License
== Representation and evaluation In the context of Keen, the representation of candidate solutions is fundamental. These solutions are modeled as collections of "genetic material," mirroring the concept of genes and chromosomes in biological systems. This genetic material, depending on its organization and granularity, can represent different dimensions of solutions: #figure( table( columns: (auto, auto), inset: 5pt, align: horizon, table.header([*Genetic material*], [*Mathematical construct*]), [Gene], [Scalar], [Chromosome], [Vector], [Genotype], [Matrix] ), caption: [Genetic material and their mathematical equivalent] ) Given the binary nature of the problem domain in Keen, solutions can be effectively represented as arrays of boolean values, encapsulated by the `BooleanGene` and `BooleanChromosome` classes. Consider the following Kotlin code snippet for defining a genotype: ```kt // Define the size of each chromosome, here set to 50 genes. private const val CHROMOSOME_SIZE = 50 // Initial probability for each gene to be `true`, set at 15%. private const val TRUE_RATE = 0.15 // Constructing a genotype with specified characteristics. val gt = genotypeOf { chromosomeOf { booleans { size = CHROMOSOME_SIZE // Number of genes in a chromosome. trueRate = TRUE_RATE // Probability of a gene being `true`. } } } ``` This code defines a genotype with chromosomes consisting of 50 genes each, where each gene has a 15% chance of being `true`. This setup is particularly useful in problems where the solution space can be binary encoded. Evaluating the fitness of these genotypes is crucial for guiding the genetic algorithm towards optimal solutions. The fitness function, in this case, is designed to count the number of `TrueGenes` within a genotype: ```kt // Function to evaluate the fitness of a genotype. private fun count(genotype: Genotype<Boolean, BooleanGene>) = genotype.flatten() // Convert the genotype to a list of genes. .count { it } // Count the number of `TrueGenes`. .toDouble() // Convert the count to a Double for compatibility. ``` In this function, the genotype is first flattened to transform its structured genetic material into a linear list of genes, making it easier to apply operations like counting. The number of `TrueGenes` reflects the fitness of the genotype, with higher counts indicating potentially more optimal solutions. By meticulously crafting the representation of solutions and defining a meaningful fitness function, Keen leverages the principles of genetic algorithms to efficiently navigate the solution space of complex optimization problems.
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/CSL_old/oktoich/Hlas7/5_Piatok.typ
typst
#let V = ( "HV": ( ("","Ne ktomú vozbraňájemi","Da čelovíka Bóha soďílaješi, čelovík býl jesí preblahíj Christé, i raspjálsja jesí: sláva síľi tvojéj."), ("","","Jehdá na krest ťá Iisúse, sónm jevréjskij osudí, zemľá trjasášesja, i sólnca svít skryvášesja."), ("","","Térnijem ťá bezsmértne, vinčá sobór bezzakónnyj, prélesti térnije iz kórene sikúšča, carjú svjatýj."), ("","<NAME>","Víďašči prostérta na drévi áhnca, neskvérnaja áhnica i Ďíva, posreďí dvojú razbójniku, uvý mňí, vopijáše, sladčájšeje mojé čádo! Čtó stránnoje sijé i preslávnoje táinstvo? Káko ťá bezzakónnyj sónm na krest vozdvíže, i žélči napojí, mánny nasýščšaho čelovíki?"), ("","","Jehdá ťa na kresťí prihvoždéna Ďíva i Máti tvojá uzrí, Christé mój, sudóm zakonoprestúpnym ot iudéj na mísťi lóbňim, uvý mňí, vopijáše, Sýne mój ľubézňijšij! Čtó stránnoje viďínije sijé? Káko ťá ko krestú prihvoždájut ďíti nerazúmniji jevréjstiji, vsích Hóspoda?"), ("","","Jedínu ťá, vsesvjatája Vladýčice, po roždeství poznáchom vsí Ďívu jávľšujusja, jehóže bez símene rodilá jesí, na drévi víďašči rúci svojí vóleju prihvozdívša, prečístaja pláčušči vzyváše: vóleju, dolhoterpilíve, umiráješi, izbavľája ot smérti vsjá pojúščyja ťá."), ("Krestobohoródičen","","Vladýčice vsesvjatája Ďívo, róždšaja Hóspoda, za blahoutróbije na kresťí prihvozdívšahosja, i žízni strují istočívša míru, tohó umolí spastísja dušám nášym: tebé bo jedínu ímamy vírniji pribížišče, i sťínu, i zastuplénije. Ťímže i pritekájem k pokróvu tvojemú."), ), "S": ( ("","","Ne ktomú vozbraňájemi jesmý dréva živótnaho, upovánije imúšče krest tvój: Hóspodi, sláva tebí."), ("","","Povíšen býv bezsmértne na drévi, sokrušíl jesí vsjá síti dijávoli: Hóspodi, sláva tebí."), ("Múčeničen","","Sláva tebí Christé Bóže, apóstolov pochvalá, i múčenikov vesélije: íchže própoviď Tróica jedinosúščnaja."), ("Krestobohoródičen","","Na drévi prihvoždénna ťá vóleju vseneporóčnaja jáko víďi, pláčušči pojášče deržávu tvojú."), ), ) #let P = ( "1": ( ("","","Istrjásšemu Bóhu faraóna v móri čermňím, písň pobídnuju poím, jáko proslávisja."), ("","","Životá mojehó prozrjá nastávšij konéc, Vladýčice, vopijú: tý mi dážď očiščénije sohrišénij Bohonevísto."), ("","","V pučíňi blahostýni tvojejá priték, vopijú: Vladýčice blahája, izbávi mjá vsjákaho mučénija."), ("","","Vladýce, prijimí nás víroju pribihájuščich k tebí, i podážď napástej i skorbéj izbavlénije."), ("","","Tý pádšuju Adámovu skíniju proróčeski vozstávila jesí, Spása i Bóha prečístaja, vo črévi nosívši."), ), "3": ( ("","","Utverdísja víroju Christóva cérkov, íbo neprestánno písňmi vopijét pojúšči: svját jesí Hóspodi, i ťá pojét Dúch mój."), ("","","Jáže Bóha i Vladýku neizrečénno začénšaja, obderžíma mjá búreju hrichá, tý ot sích izbávi, i spasí mja prečístaja."), ("","","Sohrišénij nepodóbnych nóščiju mjá oderžíma, pokajánija lučámi ozarí otrokovíce, ďílati mí podávši svíta ďilá vsehdá."), ("","","Jáže nebésnyj chľíb róždši Bohoródice, pitájušči vsích vírnych serdcá, nasýti álčuščuju dúšu mojú strástnuju."), ("","","Utverdíchsja, božéstvennoje tvojé roždestvó razumív, i zastuplénijem Ďívo, obohaščájusja, zovýj: svját jesí Hóspodi, spasája dúšy náša."), ), "4": ( ("","","Uslýšach slúch tvój, i ubojáchsja: razumích ďilá tvojá, i užasóchsja Hóspodi."), ("","","Steňúšča pred tobóju Vladýčice, i vopijúšča priľížno ot umá mojehó, da ne prézriši mené, nižé posramíši."), ("","","Popalí únzšij térn okajánnyja mojejá duší, slastéj plotskích, jáže óhň božéstvennyj Vladýčice, róždšaja."), ("","","Podážď mí sohrišénij ostavlénije vseblahoslovénnaja čístaja, i izbávi víčnaho i užásnaho mučénija."), ("","","Slóvo v ťá vséľšejesja prečístaja, suščestvó mojé vozobrazí, pádšeje prestupléňmi."), ), "5": ( ("","","Útreňuet dúch mój k tebí Bóže, zané svít jesí, i tvojá poveľínija býša iscilénija rabóm tvojím, čelovikoľúbče."), ("","","Upodóbichsja bezslovésnym skotóm preokajánnyj, strasťmí bezslovésnymi okajánňij mojéj plóti rabótaja: tý, Bohoródice, podážď mí vosprjanovénije."), ("","","Pomíluj mjá páče vsích čelovík sohrišívšaho, i k tvojemú pokróvu pribihájušča téplomu Bohoródice Ďívo, i mučénij ischití."), ("","","Íže Bohoródicu ispovídajuščiji ťá Máti Ďívo, nepreidúščaho cárstvija i píšči, tobóju Bohomáti, ulučíti da spodóbjatsja."), ("","","Blahoslovénnaja i preproslávlennaja Máti neiskusomúžnaja, umerščvlénuju hrichámi dúšu mojú, i strasťmí pohorblénuju neoderžánnymi, oživotvorí."), ), "6": ( ("","","Jóna iz čréva ádova vopijáše: vozvedí ot tlí živót mój. mý že tebí vopijém: vsesíľne Spáse, pomíluj nás."), ("","","Soderžít mjá búrja hrichóvnaja, Ďívo, i ko tlí otčájanija vedét: no prostrí mi rúku pómošči tvérduju i vsemóščnuju."), ("","","Jeléj, jéže v tebí téplaho milosérdija, vozléj na mjá Vladýčice, i izbávi sohrišénij, ischití ohňá víčnujuščaho."), ("","","Jáže razrišívšaja ot boľízni Ďívo Jévu, roždestvóm tvojím prečístym, razriší mi otrokovíce, boľízni strastnýja mojejá duší i ťilesé."), ("","","Pisnoslóviši iz tebé voploščénnaho Bóha, i rydáješi na kresťí vozneséna, tohó smotrjájušči Máti Ďívo čístaja i preneporóčnaja."), ), "S": ( ("","","Plód čréva tvojehó čístaja, krest vodruzí v koncý, i tlí mír izbávi: ťímže ťá jáko preslávnuju veličájem."), ), "7": ( ("","","V péšč óhnennuju vvérženi prepodóbniji ótrocy, óhň v rósu preložíša, vospivánijem síce vopijúšče: blahoslovén jesí Hóspodi Bóže otéc nášich."), ("","","Prehrišénij mojích umnóžisja preščénije, sudá dostójno, čístaja, pripádaju i zovú ti: préžde koncá podážď mí očiščénije, i umilénija slézy, i nrávom ispravlénije."), ("","","Nedúhovavša mjá ľúťi skvérnymi prehrišéniji, čístaja, i ko otčájanija idúšča hróbu, jáko róždši žízň vsjáčeskich prečístaja, božéstvennymi ďijániji oživí."), ("","","Bohorodíteľnice blahája, víroju prizyvájuščich tvojú blahodáť prisnoživúščuju, mýslennyja smérti izbavľájušči, cárstvija spodóbi prečístymi tvojími molítvami."), ("","","Nepostížnoje roždestvó Ďívy slavoslóvim, ímže smérti izbávichomsja: jehóže rádi róždšesja v netľínije, blahoslovén jesí, zovém, Hóspodi Bóže otéc nášich."), ), "8": ( ("","","Jedínaho beznačáľnaho carjá slávy, jehóže blahoslovját nebésnyja síly, i trepéščut číni ánheľstiji, pójte svjaščénnicy, ľúdije prevoznosíte jehó vo víki."), ("","","Strastéj mjá péšč popaľájet Ďívo, i ohném slastéj pojadájet, predvarívši, mílostivnoju tvojéju rosóju uhasí jú, dajúšči duší mojéj ustužénije krípko."), ("","","Dúšu oskverních, i rastlích plóť slasťmí, vaľájasja v sích, i bých poruhánije čelovíkom, i smích vrahóm: Vladýčice Bohoródice, pomóščnica mňí búdi."), ("","","Bóha, jehóže rodilá jesí Ďívo, umolí nizposláti spasénije vírno čtúščym ťá, i bíd razrušénije, i nedúhov ľútych preminénije skóroje, i blahodáť víčnuju."), ("","","Sozdávšaho Adáma po óbrazu, i ot smišénija jehó prošédša, i razríšša pérvuju kľátvu, pójte svjaščénnicy Hóspoda, i prevoznosíte jehó vo víki."), ), "9": ( ("","","Vsepítaja nebés prevýššaja, beznačáľnoje Slóvo bezsímenno začénšaja, i voploščénnaho Bóha róždšaja čelovíkom: ťím ťá vsí veličájem."), ("","","Vsesvítlaja Ďívo Máti Bohoródice, okajánnuju dúšu mojú, ľúte omračénnuju strasťmí plotskími, svítom molítv tvojích v strách Bóžij svítlo nastávi."), ("","","Otčájavsja ot mnóžestva sohrišénij mojehó spasénija, i nedoumínen javíchsja Vladýčice vsesvjatája: tvojé blahoďijánije, i mílosť tvojú nizposlí mňí."), ("","","Roždestvó tvojé Bohoródice, jéže páče jestestvá, udivľájet ánhely, užasájet že čelovíki: vsím bo neskazánno jésť i nepostižímo. Sijé že pojúšče blahočéstno ťá slávim."), ("","","Umerščvlénija i tľínija rízy sovlecý mi Ďívo, jáže spasénija rízu voploščénnaho Slóva róždši čelovíkom: ťímže vsí ťa prísno veličájem."), ), ) #let U = ( "S1": ( ("","","Cérkov vopijét tí, Christé Bóže, v pévki i kédri i kiparísi, poklaňájuščisja tebí: pobídy vírnym dáruj, Bohoródicy rádi, i pomíluj nás."), ("","","Íže mené rádi preterpívyj na kresťí prihvoždénije, prijimí i mojé bódrennoje chvalénije, Christé Bóže, jáko čelovikoľúbec."), ("Krestobohoródičen","","Krestóm Sýna tvojehó chraními Ďívo, prilóh bisóvskich izbihájem: ťímže ťá Bohoródice beznevístnaja, po dólhu vospivájušče slávim."), ), "S2": ( ("","","Ohňá svitľíjšeje, i plámene ďíjstvenňijšeje drévo pokazál jesí Christé krestá tvojehó, popaľájuščeje hrichí čelovíkov, i prosviščájuščeje serdcá pojúščich vóľnoje tvojé raspjátije: Christé Bóže, sláva tebí."), ("","","Hóspodi, tvojehó krestá zrjášče vozvyšájema vsehdá, pristupájem vírno píňmi i písňmi, oblobyzájušče tohó stráchom i rádostiju: osvjatí rabý tvojá, i umirí mír tvój sehó javlénijem, jedíne mnohomílostive."), ("Krestobohoródičen","","Svjatíji múčenicy, molíte ostavlénije dáti nám prehrišénij nášich, i čájemych múk izbávitisja nám, i hórkija smérti, mólimsja."), ("","","Bohoródice čístaja prisnoďívo, na kresťí zrjášči Sýna tvojehó vísjašča, jáko Máti pláčušči tohó veličáše strášnoje snizchoždénije neiskusobráčnaja Vladýčice."), ), "S3": ( ("","","Krest tvój Christé, čestnýj, míra orúžije jésť, i nepobidímaja pobída: ímže i nevídimyja vrahí nizlahájušče, blahodárno vospivájem ťá."), ("","","Íže Adámovo osuždénije drévom krestá iscilívyj, iscilí náša sokrušénija serdéčnaja, i spasí nás."), ("Krestobohoródičen","","Plód čréva tvojehó prečístaja, krest nasadí v koncích i ot tlí mír izbávil jésť: ťímže ťá preslávnaja, veličájem."), ), "K": ( "P1": ( "1": ( ("","","Istrjásšemu Bóhu faraóna v móri čermňím, písň pobídnuju poím, jáko proslávisja."), ("","","Christós voznosím na krest, k sebí vsjá privlečé čelovíki, i nizvérže vrahá, vsích nizvérhšaho."), ("","","Vódu životú mojemú Iisúse, ot živonósnych rébr istočíl jesí, i umertvíl jesí vrahá Vladýko, býv mértv."), ("Múčeničen","","Molítvu Christú za nás strastotérpcy priľížnuju prinesíte, strášnaho sudá vsím nám izbávitisja."), ("Múčeničen","","Smirívšesja vý Christá rádi, premúdriji múčenicy, hórdaho vrahá nizložíste božéstvennoju blahodátiju ."), ("Bohoródičen","","Vozsijávšaho iz tebí, prevelíkim blahoutróbijem Vladýčice, na kresťí zrjášči plákala jesí, tohó slávjašči."), ), "2": ( ("","","Istrjásšemu Bóhu faraóna v móri čermňím, písň pobídnuju poím, jáko proslávisja."), ("","","Vpádšaho v tľínije preslušánija práďida Adáma obnovíla jesí, Bóha prečístaja, plótiju róždši."), ("","","S vesélijem hlás Havriílov vzyvájem tí, čístaja: rádujsja vsích nadéžde prečístaja, rádujsja Bohonevísto."), ("","","Umerščvlénnyj mój úm oživí živótnym ďíjstvijem iz tebé róždšimsja voístinnu prečístaja Ďívo."), ("","","Blahoslovjáščiji ťá vírno ot Bóha blahoslovľájutsja jávi: blahoslovénija vo istóčnik rodilá jesí, jedína vsepítaja."), ), ), "P3": ( "1": ( ("","","Utverdísja víroju Christóva cérkov, íbo neprestánno písňmi vopijét pojúšči: svját jesí Hóspodi, i ťá pojét dúch mój."), ("","","Bezstrástnyj po suščestvú, káko strásť terpíši, živót mňí vdychájaj? Káko umiráješi na drévi? Vélija tvojá mílosť i dolhoterpínije, Spáse."), ("","","Na kresťí posreďí razbójnikov, Slóve, neprávedno vozdvíhlsja jesí, i opravdál jesí víroju poznávšaho tebé ziždíteľa vsejá tvári, vóleju stráždušča."), ("Múčeničen","","Strohánija plóti terpjášče, rúk že oťátije, i nóh, i vsích udóv strástotérpcy, slávy spodóbišasja, o nás moľáščesja."), ("Múčeničen","","Premnóhimi múkami o Bózi prosvitívšesja, premnóhuju slávu múdriji nýňi nasľídovaste, vsehdá moľáščesja o dušách nášich."), ("Bohoródičen","","Razrišénije dolhóv nášich čístaja Ďívo, podážď máternimi tvojími molítvami, na kresťí prihvoždénnaho čelovíka bývša, Bóha Slóva róždšaja."), ), "2": ( ("","","Utverdísja víroju Christóva cérkov, íbo neprestánno písňmi vopijét pojúšči: svját jesí Hóspodi, i ťá pojét dúch mój."), ("","","Tebé Ďívu, obrázno síň vsesvjátúju. zakonopolóžniku na horí Bóh predskazáše: selénije bo býsť vsích osvjaščájuščaho."), ("","","Zémľu ťá svjatúju Ďívo, razumíchom vsí, nám bez símene vozrastívšuju krásnyj klás, Iisúsa Christá, pitájušč víroju ťá i ľubóviju blažáščich."), ("","","Víďina býša šéstvija Bóha výšňaho, v tebí Ďívo neizrečénno tomú voplóščšusja: Máti bo tý bylá jesí vsími cárstvujuščaho."), ("","","Utverdíchsja, božéstvennoje tvojé roždestvó razumív, i zastuplénijem tvojím Ďívo, oboháščsja, zovýj: svját jesí Hóspodi, spasájaj dúšy náša."), ), ), "P4": ( "1": ( ("","","Uslýšach slúch tvój, i ubojáchsja: razumích ďilá tvojá, i užasóchsja Hóspodi."), ("","","Jákože krasňíjšij hrózd na kresťí vozdvíhlsja jesí Vladýko, vesélija vinó iskápal jesí čelovikoľúbče."), ("","","Mnohoboľíznennyja čelovíkov strásti utišíl jesí voístinnu, strásti Vladýko, vóleju na plóti tvojéj prijém."), ("Múčeničen","","Ostrupíša ostrupľájemi strastotérpcy borcá: i javíšasja vráčeve dúš nášich."), ("Múčeničen","","Opolčíšasja k mučítelem strastonóscy, i pobidívše, vinčáni býša pobídnymi vincý."), ("Bohoródičen","","Rodilá jesí bez símene Ďívo Slóva, na kresťí pohubívšaho tľínije bláhostiju."), ), "2": ( ("","","Uslýšach slúch tvój, i ubojáchsja: razumích ďilá tvojá, i užasóchsja Hóspodi."), ("","","Uslýšal jésť Avvakúm ťá prečístaja, hóru, duchóvnymi osinéňmi prosviščájemu: iz tebé bo Bóh javísja voploščájem."), ("","","Ispravľájetsja pravoslávnych sobór, tebé vsesvjatúju pojá jáko Bohomáter, so archánhelom, rádujsja, zovýj tebí."), ("","","Bijétsja Nestórija licé, ne voschoťívšaho múdrstvovati tebé Bohoródicu čístuju: Bóha bo voístinnu prečístaja, rodilá jesí."), ("","","Krásnuju ťá i svítluju dobrótami ženích obrít, v ťá vselísja, i Bohoródicu vsečístaja soďíla."), ), ), "P5": ( "1": ( ("","","Útreňuet dúch mój k tebí, Bóže: zané svít jesí, i tvojá poveľínija býša iscilénija rabóm tvojím, čelovikoľúbče."), ("","","Vozdvížem Vladýko, na drévo plótiju, tvár vsjú iz róva ľútych nerazúmija izvlékl jesí, k rázumu tvojemú čelovikoľúbče."), ("","","Na lóbňim ťá mísťi isprosíša ľúdije bezzakónniji raspjáti Iisúse, hlavú páhubnuju zmíjevu sokrušájuščaho."), ("Múčeničen","","Ustáviste zločéstija tečénije Christóvy múčenicy, božéstvennymi krovmí vášimi, i faraóna mučíteľa v sích potopíste."), ("Múčeničen","","Nohoťmí neščádno strúžemi, rasterzáste obličéňmi stradáľcy serdcá sujemúdrennaja, i pobidítelije býste."), ("Bohoródičen","","Osvjatíl jésť Bóh utróbu tvojú, svjatája čístaja, i vselísja v ňú: i na krest vozdvížem, tvár sovozdvíhl jésť."), ), "2": ( ("","","Útreňuet dúch mój k tebí, Bóže: zané svít jesí, i tvojá poveľínija býša iscilénija rabóm tvojím, čelovikoľúbče."), ("","","Bohoľípnuju tvojú hospožé, i krásnuju, i sladčájšuju i blahúju dobrótu vozľubív Vladýka, v ťá Ďívo, vselísja."), ("","","Vsesvjatája i svitonósnaja dvére blahodáti, vselénnuju svitľíjšim tvojím svítom ozarívši otrokovíce, tebé pojúščyja prosvití."), ("","","Bohoródicu ispovídajuščiji ťá Máti Ďívo, nepreidúščaho cárstvija i píšči tobóju Bohomáti ulučíti da spodóbjatsja."), ("","","Chrám javílasja jesí vsevídca i vsederžíteľa: tvojú bo utróbu čísťíjšuju nebés obrít vodvorísja, Bohorodíteľnice vsečístaja."), ), ), "P6": ( "1": ( ("","","Jóna iz čréva ádova vopijáše: vozvedí ot tlí živót mój. mý že tebí vopijém: vsesíľne Spáse, pomíluj nás."), ("","","Nedúhovavšeje čelovíčeskoje jestestvó, jávľsja za milosérdije mílosti, vračú nedúhujuščich, iscilíl jesí krestóm i strástiju tvojéju."), ("","","Drévom drévle Adám osudísja: drévom že nýňi kréstnym opravdásja, vchoždénije prijém v ráj, i sládosti vosprijátije."), ("","","Pojém ťá plótiju raspénšahosja, slávim térnijem vinčávšahosja, i slávoju vinčávšaho čelovíki, carjú preblahíj."), ("Múčeničen","","Hubíteľnyj nýňi otrínuvše vréd stradáľcy idolobísija, múkam pričastíšasja: i umérše so Christóm cárstvujut."), ("Múčeničen","","Ni honénije, ni hlád, ni nahotá, ni bidý, nižé smérť, otňúd božéstvennyja strastotérpcy, ot ľubvé Christóvy razlučíša."), ("Bohoródičen","","Slavoslóviši iz tebé voplóščšahosja, i pláčeši na kresťí vozdvíženaho, tohó smotrjájušči Ďívo Máti svjatája vseneporóčnaja."), ), "2": ( ("","","Jóna iz čréva ádova vopijáše: vozvedí ot tlí živót mój. mý že tebí vopijém: vsesíľne Spáse, pomíluj nás."), ("","","Bohomúžno v čelovícech požívšaho rodilá jesí Bohoródice Ďívo, jedínaho blahoďíteľa, jéže býti čelovíkom dárujuščaho."), ("","","Jemmanúila Bohoródice, suhúba po suščestvú rodilá jesí, préžde soveršénno Slóvo, Bóha voploščénna, izbavlénije nám podavájuščaho."), ("","","Kovčéh prijémyj zakóna skrižáli, prednapisá tebé Bohoródice, Slóvo Bóžije, jáko prijémšuju vo črévi svojém nás rádi voploščájema."), ("","","Ánheľskija jazýki ispólneny, tvojá pochvalý propovídati ne móhut čístaja: mý že nýňi rábski prijémše, jéže rádujsja, Havriílovo prinósim."), ), ), "P7": ( "1": ( ("","","Péšč ótrocy ohnepáľnu drévle rosotočášču pokazáša, jedínaho Bóha vospivájušče, i hlahóľušče: prevoznosímyj otcév Bóh, i preproslávlen."), ("","","Ťahotú oblehčája bezzakónij mojích, posreďí bezzakónnych vozdvíhlsja jesí na krest, preblahíj Hóspodi, prevoznosímyj otcév Hospóď, i Bóh blahoslovén jesí."), ("","","Kopijém probóďsja v božéstvennaja rébra tvojá, i rébrennoje popolznénije isprávil jesí Spáse, plámennomu že orúžiju daváti mí vchód rajá poveľiváješi vsehdá."), ("Múčeničen","","Zvízdy na vysoťí osnovánnyja cérkve múčenicy bývše, tvár ozarjájete stradánij svítlostiju, i iscilénij sijánijem."), ("Múčeničen","","Kníha prinósit prísno napísannych živých Hospódnich múčenik, napísanaja Bóžija opravdánija usérdno sochranívšich, i postradávšich krípko."), ("Bohoródičen","","Vsesvjatája, presvjatóje Slóvo, jéže ot nejá vozsijávšeje, na svjaťím kresťí vozdvíženo, i osvjaščájuščo zemnýja, zrjášči rydáše."), ), "2": ( ("","","Péšč ótrocy ohnepáľnu drévle rosotočášču pokazáša, jedínaho Bóha vospivájušče, i hlahóľušče: prevoznosímyj otcév Bóh, i preproslávlen."), ("","","Jáže v peščí óhnenňij, tvojé roždestvó spasló jésť úbo drévle: nýňi že nás vseneporóčnaja spasí, jehó prišéstviju jéže páče slóva zovúščich: blahoslovén jesí Bóže otéc nášich."), ("","","Bohootéc úbo Davíd tvojú slávu napisújet Ďívo, i tebí tvárej carícu javlénno proróčestvujet, predstojáščuju odesnúju vseneporóčnaja, Bóha otéc nášich."), ("","","Obnovíla jesí čístaja, zemných jestestvó, obnovlénijem roždestvá tvojehó. Ťímže tí vopijém: blahoslovén jésť vo víki vsjá, Hospožé, plód tvojehó čréva."), ("","","Osuždénnaho bývša Adáma, i smértiju deržíma, Adám vtorýj, prečístaja, tobóju pomílovav prizvá, blahoslovén jesí zovúšča, roždéjsja, i obnovléj mjá."), ), ), "P8": ( "1": ( ("","","Jedínaho beznačáľnaho carjá slávy, jehóže blahoslovját nebésnyja síly, i trepéščut číni ánheľstiji, pójte svjaščénnicy, ľúdije prevoznosíte jehó vo víki."), ("","","Mértva mjá pokazá drévo rázuma, tý že Christé mój, umertvívsja na drévi oživíl jesí, i prosvitíl jesí píti: pójte svjaščénnicy, ľúdije prevoznosíte vo vsjá víki."), ("","","Térnijem vinčá zakonoprestúpnyj sónm ťá, carjú, preslušánija iskorenevájušča térnije Adáma pervozdánnaho, i vozdvíže na krest, vsjá iz hlubiný prélesti izvlékšaho."), ("Múčeničen","","Rázumom prostéršaho nebesá, tebé prostirájut na drévi ľúdije nerazúmniji, isciľájušča náša strásti strástiju tvojéju, Spáse, i ustavľájušča boľízni, jáže ot hvozdéj boľízňmi."), ("Múčeničen","","Múčenik móšči blahouchánija ispuščájut čudés prichoďáščym nesumňínnym sérdcem, i strastéj zlovónije prohoňájut prísno, i vsím zdrávije o Bózi podavájut."), ("Bohoródičen","","Svjatých čínove móľatsja Ďívo, iz utróby tvojejá prošédšemu Vladýci, pokazávšemu na kresťí sím púť stradánija, čístaja, i slavoslóvjat ťá jáko vsích cárícu."), ), "2": ( ("","","Jedínaho beznačáľnaho carjá slávy, jehóže blahoslovját nebésnyja síly, i trepéščut číni ánheľstiji, pójte svjaščénnicy, ľúdije prevoznosíte jehó vo víki."), ("","","Nepostižímyj Vladýka vsích, jehóže ne vmiščájut nebesá, Bohorodíteľnice, vmiščájetsja vo tvojú utróbu Ďívo. Ťímže ťá vírniji ľubóviju prevoznósim vo víki."), ("","","Umá prevýššaho vsejá tvári, otrokovíce, jehóže ne vozmohájet roždénnoje zríti jestestvó, nosíla jesí na svojéju prečístoju rukú. Ťímže vírniji ľubóviju prevoznósim vo vsjá víki."), ("","","Bóha, jehóže rodilá jesí, umolí Ďívo, nizposláti spasénije vírno čtúščym ťá, i bíd razrušénije, i nedúhov ľútych preminénije skóroje, i blahodáť víčnuju."), ("","","Ukrašén ťá dobroďítelmi razlíčnymi, i prosviščén chrám výšňaho, uvíďivše vsesvjatája Ďívo, pojém blahočéstno ťá, i slavoslóvim vo vsjá víki."), ), ), "P9": ( "1": ( ("","","Vsepítaja nebés prevýššaja, beznačáľnoje Slóvo bezsímenno začénšaja, i voploščénnaho Bóha róždšaja čelovíkom: ťím ťá vsí veličájem."), ("","","Na kresťí ťa vozvýšena, carjú vikóv, jáko víďi sólnce omračísja, i zemľá potrjasésja, i cérkve razdrásja zavísa svítlosti, Iisúse vsesíľne."), ("","","Iskopáša rúci i nózi tvojí bezzakónnicy, i rébra živonósnaja probodóša kopijém, i žélči so óctom napoíša ťá Christé mój, vsích sládosť, i Bóha ístinna."), ("Múčeničen","","Sokrušíša načalozlóbnaho síti, sokrušájemi vsjákimi vídy mučénija, i vincenóscy pobídoju bývše, dóbliji stradáľcy ublažájutsja."), ("Múčeničen","","Osvjatíša položénijem moščéj vsjú zémľu strastotérpcy, i uhasíša skváry idoložértvennyja, ohňú primišájuščesja, i v ném tájno vsesožihájemi."), ("Bohoródičen","","Blahoľubívaja, cheruvím svjaťíjšaja, jáže Bóžije Slóvo Bóha plótiju róždšaja, vozdvížennaho na kresťí choťínijem, za vsích priľížno tomú molísja."), ), "2": ( ("","","Vsepítaja nebés prevýššaja, beznačáľnoje Slóvo bezsímenno začénšaja, i voploščénnaho Bóha róždšaja čelovíkom: ťím ťá vsí veličájem."), ("","","Vsesoveršéno čelovíčestvo prijáto býsť iz tebé, prečístaja otrokovíce, Slóvu sovokúpľšusja plóti oduševlénňij, slóvom duší ukrášenňij: ťímže vsí vírniji ťá veličájem."), ("","","Vitíjskoje úbo bujeslóvije da umolčít, apóstoľskaja že trubá da vozhlasít, tebé ístinnymi hlásy Ďívo voschvaľájušči, Bohoródicu ístinnuju vozviščájušči."), ("","","Pomílovasja tebé rádi čelovíčestvo, po ipostási voístinnu Slóvu sojedínšejesja, i vozdajánijem Bóh, Ďívo, bývšeje: ťímže ťá vsí prísno veličájem."), ("","","Prorazumísja proróčeskimi bystrozríniji táinstvo, otrokovíce, tvojehó roždestvá, jáko voploščénna Bóha róždši čelovíkom, izbavľájuščaho nás ot napástej molítvami tvojími."), ), ), ), "CH": ( ("","","Vladýko sýj čelovikoľúbče žiznodávče, iskupíl jesí krestóm tvojím vselénnuju, Hóspodi, sláva tebí."), ("","","Na kresťí prihvozdísja lozá ístinnaja, obimáša jazýcy ráj s razbójnikom: sijá sláva cerkóvnaja, sijé bohátstvo cárstvija. Postradávyj nás rádi, Hóspodi, sláva tebí."), ("","","Pámjať svjatých tvojích strastotérpec prázdnujušče, tebé pojém Christé, vopijúšče, Hóspodi, sláva tebí."), ("Krestobohoródičen","","Svojehó Sýna na drévi víďašči drévle, sérdce svojé orúžijem pečáli ujazvľáše prečístaja."), ), ) #let L = ( "B": ( ("","","Krasén bí i dóbr v sňíď, íže mené umertvívyj plód, Christós jésť drévo živótnoje, ot nehóže jadýj ne umiráju, no vopijú s razbójnikom: pomjaní mja Hóspodi, vo cárstviji tvojém."), ("","","Isciľája Adámovu boľízň, júže podját vrážijim sovítom, voznéssja na drévo vsích carjú, i boľízni preterpíl jesí, rukáma i noháma prihvoždén: ťímže slávim tvojé, Slóve, dolhoterpínije."), ("","","Posreďí ťa bezzakónnoju sónm jevréjskij raspját, jedínaho zakonodávca i izbáviteľa, vsjákaho bezzakónija izbavľájušča Christé, ród čelovíčeskij: ťímže vospivájem ťá."), ("Múčeničen","","Jázvy mnóhich múk, jáko krásnaja udobrénija nosjášče dóblestvenňi stradáľcy, ukrašénije cerkóvnoje poznáni býša svítloje, vsehdá moľáščesja o dušách nášich."), ("","","O Tróice svjatája! vírnyja rabý tvojá izbávi múk, v ťá vírovavšyja, vo jedínom božeství, neprestánno slávimuju blahočéstno, i víčnoje tvojé cárstvije dáruj."), ("","","Ne imúšča vída, nižé dobróty, zrjášči tebé Christé, plótiju vozvýšena na drévi krestňim vsečístaja Ďíva, vzyváše boľíznenňi: uvý mňí, káko ťá čádo, bezzakónniji ujazvíša?"), ), )
https://github.com/andrin-geiger/hslu_template_typst
https://raw.githubusercontent.com/andrin-geiger/hslu_template_typst/master/README.md
markdown
# Typst Template for BAA/Wipro at HSLU This is my personal template for the BAA/Wipro at HSLU using [Typst](https://typst.app).\ No guarantee for correctness or completeness. ## How to use this template Fill in your details in the `#show: project.with()` section of the [Typst_Template.typ](Typst_Template.typ) file.\ This will automatically fill in the details in the title page and the declaration of honesty. If you create a tag on your GitHub repository, the CI/CD pipeline will automatically create a PDF file and upload it to the release section of your repository. So if you rename the [Typst_Template.typ](Typst_Template.typ), don't forget to adjust the [pipeline](.github/workflows/build.yaml). ## References/Citations This template uses BibLaTeX for references.\ You can add your references to the [Bibliography](Referenzen.bib) file.\ To cite a reference in the text, use `@reference_key`. ## How to use Typst To learn how to use Typst, visit the [Typst Documentation](https://typst.app/docs). ## PDF/A HSLU requires the Bachelor's thesis to be in the PDF/A format.\ Unfortunately, Typst does not support this format yet.\ To convert the PDF to a valid PDF/A format, use Adobe Acrobat.
https://github.com/kradann/Anal-zis-zh-2
https://raw.githubusercontent.com/kradann/Anal-zis-zh-2/main/masodik.typ
typst
#import "@preview/cetz:0.2.2" #let colorS = color.rgb("#B4D3B4") #set page( paper: "a4", numbering: "1.", margin: (x: 40pt, y: 40pt) ) #set document( author: "<NAME> & <NAME>", title: "Első Analízis II. ZH kérdései" ) #set text( size: 15pt, font: "Times New Roman" ) #set par(justify: true) #set enum(numbering: "1.)") #show heading.where(level: 2): it => block( fill: colorS, inset: 10pt, radius: 4pt, )[#it] #show heading.where(level: 1): it => align(center)[#it] #show heading.where(level: 3): it => [#underline[#it]] = II. analízis ZH bizonyítással kért tételek == Végtelen sorokra vonatkozó Cauchy-féle konvergenciakritérium \ A $sum(a_n)$ sor akkor és csak akkor konvergens, ha $ forall epsilon gt 0"-hoz" exists n_0 in NN, forall m gt n gt n_0 : abs(a_(n+1)+a_(n+2)+...+a_m) lt epsilon $ === Bizonyítás Tudjuk, hogy $ sum(a_n) "konvergens" arrow.l.r.double.long (s_n) "konvergens" arrow.l.r.double.long (s_n) "Cauchy-sorozat," $ azaz $ forall epsilon gt 0"-hoz" exists n_0 in NN, forall n,m gt n_0 : abs(s_m - s_n) lt epsilon $ teljesül. Allításunk abból következik, hogy ha $m gt n$, akkor $ s_m - s_n = a_(n+1)+a_(n+2)+...+a_m $ #pagebreak() == Végtelen sorokra vonatkozó összehasonlító kritériumok \ Legyenek $sum(a_n) " és " sum(b_n)$ nemnegatív tagú sorok. Tegyük fel, hogy $ exists N in NN, forall n gt.eq N : 0 lt.eq a_n lt.eq b_n $ Ekkor 1. #strong("Majoráns kritérium"): ha a $sum(b_n)$ sor konvergens, akkor $sum(a_n)$ sor is konvergens. 2. #strong("Minoráns kritérium"): ha a $sum(a_n)$ sor divergens, akkor $sum(b_n)$ sor is divergens === Bizonyítás Az általánosság megszorítása nélkül feltehetjük, hogy $a_n lt.eq b_n$ minden $n in NN$ esetén, hiszen véges sok tag megváltozásával egy sor konvergenciája nem változik. Jelölje $(s_n)$, illetve $(t_n)$ a $sum(a_n)$, illetve a $sum(b_n)$ sorok részletösszegeiből álló sorozatokat. A feltevésünk miatt $s_n lt.eq t_n (n in NN)$. Ekkor a nemnegatív tagú sorok konvergenciáról szóló tétel szerint 1. ha a $sum(b_n)$ sor konvergens, akkor $(t_n)$ korlátos, így $(s_n)$ is az. Ezért a $sum(a_n)$ sor is konvergens. 2. ha $sum(a_n)$ sor divergens, akkor $(s_n)$ nem korlátos, így $(t_n)$ sem az. Ezért a $sum(b_n)$ sor is divergens. #pagebreak() == A Cauchy-féle gyökkritérium Tekintsük a $sum(a_n)$ végtelen sort, és tegyük fel, hogy létezik az $ A := lim_(n arrow +infinity) root(n,abs(a_n)) in macron(RR) $ határérték. Ekkor 1. $0 lt.eq A lt 1$ esetén a $sum(a_n)$ sor abszolút konvergens (tehát konvergens is), 2. $A gt 1$ esetén a $sum(a_n)$ sor divergens 3. $A eq 1$ esetén a $sum(a_n)$ sor lehet konvergens is, divergens is === Bizonyítás Mivel $root(n, abs(a_n)) gt.eq 0 (n in NN)$, ezért $A gt.eq 0$. 1. Tegyük fel, hogy $0 lt.eq A lt 1$ Vegyünk egy $A$ és 1 közötti $q$ számot! $ lim(root(n,abs(a_n))) lt q arrow.double.long exists n_0 in NN, forall n gt n_0 : root(n,abs(a_n)) lt q, "azaz" abs(a_n) lt q^n $ Mivel $0 lt q lt 1$, ezért a $sum(q^n)$ mértani sor konvergens. Így a majoráns kritérium szerint a $sum(abs(a_n))$ sor is konvegens, és ez azt jelenti, hogy a $sum(a_n)$ végtelen sor abszolút konvergens. 2. Tegyük fel, hogy $A gt 1$ Vegyünk most egy 1 és $A$ közötti $q$ számot! $ lim(root(n, abs(a_n))) gt q arrow.r.double.long exists n_0 in NN, forall n gt n_0 : root(n, abs(a_n)) gt q, "azaz" abs(a_n) gt q^n $ Tehát, véges sok $n$ indextől eltekintve $abs(a_n) gt q^n gt 1$\ Ebből következik, hogy $lim(a_n) != 0$, és így a $sum(a_n)$ sor divergens. 3. Tegyük fel, hogy $A eq 1$. Ekkor a $sum(1/n)$ divergens sor esetében $abs(a_n) eq 1/n$, azaz $ lim_(n arrow +infinity)root(n,abs(a_n)) eq lim_(n arrow + infinity)1/(root(n,n)) eq 1 $ a $sum(1/n^2)$ konvegens sor esetében $abs(a_n) eq 1/n^2$, azaz $ lim_(n arrow +infinity)root(n,abs(a_n)) eq lim_(n arrow + infinity)1/(root(n,n^2)) eq 1 $ #pagebreak() == A d'Alembert-féle hányadoskritérium \ Tegyük fel, hogy a $sum(a_n)$ végtelen sor tagjai közül egyik sem 0 és létezik az $ A := lim_(n arrow + infinity)abs(a_(n+1)/a_n) in macron(RR) $ határérték. Ekkor\ 1. $0 lt.eq A lt 1$ esetén a $sum(a_n)$ sor abszolút konvergens (tehát konvergens is), 2. $A > 1$ esetén a $sum(a_n)$ sor divergens, 3. $A eq 1$ esetén a $sum(a_n)$ sor lehet konvegens is, divergens is. === Bizonyítás \ Világos, hogy $A gt.eq 0$.\ 1. Legyen $0 lt.eq A lt 1$ és vegyünk egy olyan $q$ számot, amire $A lt q lt 1$ teljesül. Ekkor $ lim_(n arrow +infinity)(abs(a_(n+1)))/(abs(a_n)) lt q arrow.double.long exists n_0 in NN, forall n gt.eq n_0 : (abs(a_(n+1)))/(abs(a_n)) lt q, "azaz" abs(a_(n+1)) lt q abs(a_n) $ Ez azt jelenti, hogy $ abs(a_(n_0+1)) lt q abs(a_n_0), abs(a_(n_0+2)) lt q abs(a_(n_0+1)), ... , abs(a_(n-1)) lt q abs(a_(n-2)), abs(a_(n)) lt q abs(a_(n-1)) $ minden $n gt.eq n_0$ esetén. Így $ abs(a_n) lt q abs(a_(n-1)) lt q^2 abs(a_(n-2)) lt ... lt q^(n-n_0) abs(a_n_0) eq q^(-n_0) abs(a_n_0) q^n eq a q^n $ ahol $a := q^(-n_0) abs(a_n_0)$ egy n-től független konstans. A $sum(a q^n)$ mértani sor konvergens, mert $0 lt q lt 1$. Ezért a majoráns kritérium szerint a $sum(abs(a_n))$ sor is konvergens, vagyis a $sum(a_n)$ végtelen sor abszolút konvergens. 2. Legyen $A gt 1$ és vegyünk most egy olyan $q$ számot, amire $1 lt q lt A$ teljesül. Ekkor $ lim_(n arrow +infinity) (abs(a_(n+1)))/(abs(a_n)) gt q arrow.double.long exists n_0 in NN, forall n gt.eq n_0 : (abs(a_(n+1)))/(abs(a_n)) gt q, "azaz" abs(a_(n+1)) gt q abs(a_n) gt abs(a_n) $ Ebből következik, hogy a $lim(a_n) != 0$, így a $sum(a_n)$ sor divergens. 3. Tegyük fel, hogy $A eq 1$. Ekkor \ $sum(1/n)$ divergens sor esetében $abs(a_n) = 1/n$, azaz $lim_(n arrow +infinity) abs(a_(n+1))/abs(a_n) eq lim_(n arrow + infinity) n/(n+1) eq 1$ \ \ $sum(1/n^2)$ konvergens sor esetében $abs(a_n) eq 1/n^2$azaz $lim_(n arrow infinity) abs(a_(n+1))/abs(a_n) eq lim_(n arrow infinity) n^2/(n+1)^2 eq 1$ #pagebreak() == Leibniz-típusú sorok konvergenciája === Definíció A $0 lt.eq a_(n+1) lt.eq a_n (n in NN^+)$ feltételt kielégítő sorozatból képzett $ ∑_(n eq 1) (−1)^(n + 1) a_n eq a_1 − a_2 + a_3 − a_4 + dots $ váltakozó előjelű sort *Leibniz-típusú sornak* nevezzük. *Konvergencia:* A $sum_(n eq 1) (−1)^(n + 1) a_n$ Leibniz-típusú sor akkor és csak akkor konvergens, ha $lim(a_n) eq 0$. === Bizonyítás $arrow.double$) A sorok konvergenciájának szükséges feltétele értelmében, ha a $sum (−1)^(n + 1) a_n$ sor konvergens, akkor $lim((−1)^(n + 1) a_n) eq 0$, ami csak akkor lehetséges, ha $lim(a_n) eq 0$. $arrow.double.l$) Tegyük fel, hogy $sum_(n eq 1) (−1)^(n + 1)a_n$ egy Leibniz-típusú sor, és $lim(a_n) eq 0$. Igazoljuk, hogy a sor konvergens. Legyen $ s_n colon.eq sum_(k eq 1)^n (-1)^(k + 1) a_k eq a_1 - a_2 + a_3 - a_4 + a_5 - dots + (-1)^(n + 1) a_n space space (n in NN^+) $ Szemléltessük az $(s_n)$ részletösszeg-sorozat első néhány tagját! #v(20pt) #grid( columns: (auto, auto), gutter: 75pt, [ #cetz.canvas({ import cetz.draw: * set-style(mark: (end: "straight")) line((), (rel: (10, 0), update: true), name: "tengely") content( "tengely.end", [ #v(25pt) $RR$ ] ) circle( ("tengely.start",1,"tengely.end"), radius: .1, name: "s2", fill: black, ) content( "s2.center", (0,0), [$s_2$] ) circle( ("tengely.start",2.47,"tengely.end"), radius: .1, name: "s4", fill: black, ) content( "s4.center", (0,0), [$s_4$] ) circle( ("tengely.start",4,"tengely.end"), radius: .1, name: "s5", fill: black, ) content( "s5.center", (0,-1), padding: -.7, [$s_5$] ) circle( ("tengely.start",5.75,"tengely.end"), radius: .1, name: "s3", fill: black, ) content( "s3.center", (0,-1), padding: -.7, [$s_3$] ) circle( ("tengely.start",7.75,"tengely.end"), radius: .1, name: "s1", fill: black, ) content( "s1.center", (0,0), [$s_1 eq a_1$] ) arc( "s2.center", start: -180deg, stop: 0deg, radius: 2.38, name: "s2tos3" ) content( ( name: "s2tos3", anchor: 50%, ), [ #pad(top: 25pt)[ $a_3 (lt.eq a_2)$ ] ] ) arc( "s4.center", start: -180deg, stop: 0deg, radius: .78, name: "s4tos5" ) content( ( name: "s4tos5", anchor: 50%, ), [ #pad(top: 25pt)[ $a_5 (lt.eq a_4)$ ] ] ) arc( "s1.center", start: 0deg, stop: 180deg, radius: 3.38, name: "s1tos2" ) content( ( name: "s1tos2", anchor: 50%, ), [ #pad(top: -15pt)[ $a_2 (lt.eq a_1)$ ] ] ) arc( "s3.center", start: 0deg, stop: 180deg, radius: 1.65, name: "s3tos4" ) content( ( name: "s3tos4", anchor: 50%, ), [ #pad(top: -15pt)[ $a_4 (lt.eq a_3)$ ] ] ) }) ], [ #show math.equation: set align(left) $ s_1 eq a_1 \ s_2 eq a_1 - a_2 eq s_1 - a_2 \ s_3 eq a_1 - a_2 + a_3 eq s_2 + a_3 \ s_4 eq a_1 - a_2 + a_3 - a_4 eq s_3 - a_4 \ s_5 eq a_1 - a_2 + a_3 - a_4 + a_5 eq s_4 + a_5 \ $ ] ) Most megmutatjuk, hogy az ábra alapján sejthető tendencia valóban igaz, azaz, hogy az $(s_(2n))$ sorozat monoton növekvő, és az $(s_(2n+1))$ sorozat monoton csökkenő. #pagebreak() - A páros indexű részsorozatnál a következő csoportosításból látható, hogy $ s_(2n) eq overbrace(underbrace((a_1 − a_2), gt.eq 0) + underbrace((a_3 − a_4), gt.eq 0) + dots + underbrace((a_(2n−3) − a_(2n−2)), gt.eq 0), s_(2n-2)) + underbrace((a_(2n−1) − a_(2n)), gt.eq 0) $ minden $n in NN^+$ esetén, tehát $(s_(2n))$ valóban monoton növekvő. - Hasonlóan, a páratlan indexű részsorozatnál $ s_(2n+1) eq overbrace(a_1 + underbrace((-a_2 + a_3), lt.eq 0) + underbrace((-a_4 + a_5), lt.eq 0) + dots + underbrace((-a_(2n−2) + a_(2n−1)), lt.eq 0), s_(2n-1)) + underbrace((-a_(2n) − a_(2n+1)), lt.eq 0) $ minden $n in NN^+$ esetén, tehát $(s_(2n+1))$ monoton csökkenő sorozat. Másrészt, az $s_0 colon.eq 0$ értelmezés mellett $ s_(2n+1) − s_(2n) eq a_(2n+1) gt.eq 0 space space (n in NN) $ teljesül, amiből következik, hogy $s_(2n) lt.eq s_(2n+1)$ minden $n in NN$ esetén. Ekkor $ (1) space space space s_2 lt.eq s_4 lt.eq s_6 lt.eq dots lt.eq s_(2n) lt.eq s_(2n+1) lt.eq dots lt.eq s_5 lt.eq s_3 lt.eq s_1 $ Tehát $(s_(2n))$ és $(s_(2n+1))$ korlátos sorozatok. Mivel mindkettő monoton és korlátos, ezért konvergens is. Jelölje $A eq lim(s_(2n+1))$ és $B eq lim(s_(2n))$ a határértéküket. Ekkor $ A - B eq lim_(n arrow + infinity) s_(2n+1) - lim_(n arrow + infinity) s_(2n) eq lim_(n arrow + infinity) (s_(2n+1) - s_(2n) ) eq lim_(n arrow + infinity) a_(2n+1) eq lim_(n arrow + infinity) a_n eq 0, $ hiszen $(a_(2n+1))$ részsorozata az $(a_n)$ sorozatnak. Ezért $A eq B$, tehát az $(s_(2n))$ és az $(s_(2n+1))$ részsorozatok határértéke megegyezik. Ebből következik, hogy az $(s_n)$ sorozat konvergens. Ez pedig azt jelenti, hogy a Leibniz-típusú sor valóban konvergens. #pagebreak() == Minden $[0,1]$-beli számok felírható tizedes tört alakban \ Minden $alpha in [0,1]$ számhoz létezik olyan $(a_n) : NN^+ arrow {0,1,2,...,9}$ sorozat, amire az teljesül, hogy $ alpha = sum_(n eq 1)^(+infinity) a_n/10^n $ \ === Bizonyítás Rögzítsünk egy $alpha in [0,1]$ számot!\ Az első lépésben osszuk fel a $[0,1]$ intervallumot 10 egyenlő hosszúságú részre. Ekkor $ exists a_1 in {0,1,2,...,9} : alpha in [a_1/10, a_1/10+1/10] =: I_1 "azaz " a_1/10 lt.eq alpha lt.eq a_1/10+1/10 $ \ A második lépésben osszuk fel az $I_1$ intervallumot 10 egyenlő hosszúságú részre. Ekkor $ exists a_2 in {0,1,2,...,9} : alpha in [a_1/10 + a_2/10^2, a_1/10 + a_2/10^2 + 1/10^2] =: I_2 "azaz" $ $ a_1/10 + a_2/10^2 lt.eq alpha lt.eq a_1/10 + a_2/10^2 + 1/10^2 $ Ha az eljárást folytatjuk, akkor az n-edik lépésben találon olyan $a_n in {0,1,2,...,9}$ számot, hogy $ s_n := a_1/10 + a_2/10^2 + ... + a_n/10^n lt.eq alpha lt.eq a_1/10 + a_2/10^2 + ... + a_n/10^n + 1/10^n eq s_n + 1/10^n , $\ ahol $s_n$ a sor n-edik részletösszege. Ekkor $ abs(alpha - s_n) eq abs(alpha - (a_1/10 + a_2/10^2 + ... + a_n/10^n)) lt.eq 1/10^n arrow.long_(n arrow +infinity) 0 $ és így $ alpha eq lim_(n arrow +infinity) s_n eq sum_(n eq 1)^(+infinity) a_n/10^n $ #pagebreak() == Konvergens sorok zárójelezése \ Egy konvergens sor minden zárójelezése is konvergens sor, és összege az eredeti sor összegével egyenlő \ === Bizonyítás \ Legyen $sum_(n eq 1) alpha_n "a " sum_(n eq 1) a_n$ sor $(m_n)$ által meghatározott zárójelezése, és jelölje $(sigma_n)$ és $(s_n)$ rendre a két a sor részletösszegeiből álló sorozatok. Ha $sum_(n eq 1) a_n$ konvergens, akkor $(s_n)$ konvergens sorozat, de ekkor minden részsorozata is konvergens, és határértéke megegyezik az $(s_n)$ sorozat határértékével.\ Mivel $forall n in NN^+$ indexre $sigma_n eq s_m_n$ teljesül, így $sigma_n$ részsorozata az $(s_n)$ sorozatnak. Tehát a $(sigma_n)$ sorozat konvegens és $lim(sigma_n) eq lim(s_n)$. Ez azt jeletni, hogy a $sum(a_n)$ sor konvergens, és $ sum_(n eq 1)^(+infinity) alpha_n eq lim_(n arrow +infinity) sigma_n eq lim_(n arrow + infinity) s_n eq sum_(n eq 1)^(+infinity) a_n $ #pagebreak() == Abszolút konvergens sorok átrendezése Ha a $sum a_n$ végtelen sor abszolút konvergens, akkor tetszőleges $(p_n) : NN arrow NN$ permutációval képzett $sum a_p_n$ átrendezése is abszolút konvergens, és $ sum_(n eq 0)^(+ infinity) a_p_n eq sum_(n eq 0)^(+ infinity) a_n $ Tehát egy abszolút konvergens sor bármely átrendezése is abszolút konvergens sor, és összege ugyanaz, mint az eredeti soré === Bizonyítás Legyen $ s_n colon.eq sum_(k eq 0)^n a_k "és" sigma_n colon.eq sum_(k eq 0) a_p_k space space space (n in NN) $ + Igazoljuk, hogy a $sum a_p_n$ sor abszolút konvergens. Valóban, mivel $sum a_n$ abszolút konvergens, ezért minden $n in NN$-re $ sum_(k eq 0)^n abs(a_p_k) eq abs(a_(p 0)) + abs(a_(p 1)) + dots + abs(a_(p n)) lt.eq sum_(k eq 0)^(+ infinity) abs(a_k) eq K lt + infinity $ azaz a $sum_(k eq 0)^n abs(a_p_k) space (n in NN)$ sorozat felülről korlátos, de nyilván monoton növekvő is, következésképpen a $sum abs(a_p_n)$ sor konvergens. Így a $sum a_p_n$ sor valóban abszolút konvegens. + Azt igazoljuk, hogy $ sum_(n eq 0)^(+ infinity) a_p_n eq sum_(n eq 0)^(+ infinity) a_n $ Legyen $ A colon.eq sum_(n eq 0)^(+ infinity) a_n eq lim_(n arrow + infinity) s_n space "és" space B colon.eq sum_(n eq 0)^(+ infinity) a_p_n eq lim_(n arrow + infinity) sigma_n $ Tudjuk, hogy a $sum abs(a_n)$ sor konvergens, így a Cauchy-kritérium szerint $ forall epsilon gt 0"-hoz" exists n_0 in NN, forall m gt n gt.eq n_0: abs(a_(n+1)) + abs(a_(n+2)) + dots + abs(a_m) lt epsilon $ Ezlrt $n eq n_0$ mellett, ha $m gt n_0$, akkor $sum_(k eq n_0 + 1)^(m) abs(a_k) lt epsilon$ \ Adott $epsilon gt 0$-ra tekintsük az $a_0, a_1, a_2, dots, a_(n 0)$ tagokat, és legyen $N_0$ olyan index, amire az $a_p_0 + a_p_1 + dots + a_p_(N_0)$ összeg már tartalmazza ezeket a tagokat. Ilyen $N_0$ nyilván létezik, és $N_0 gt.eq n_0$. Legyen $n gt N_0$. Ekkor $ sigma_n - s_n eq underbrace(\(a_p_0 + a_p_1 + dots + a_p_(N_0)) + a_p_(N_0 + 1) + dots + a_p_n) - \ underbrace(\(a_0 + a_1 + dots + a_n_0) + a_(n_0 + 1) + dots + a_n) $ nem tartalmazza az $a_0, a_1, a_2, dots, a_n_0$ tagokat. Így $ abs(sigma_n - s_n) lt.eq sum_(k eq n_0 + 1)^m abs(a_k) lt epsilon, $ ahol $m colon.eq max{p_0, p_1, dots, p_n}$, hiszen $m gt.eq n gt N_0 gt.eq n_0$. Ez azt jelenti, hogy $(sigma_n - s_n)$ nullsorozat. Ezért $ sigma_n eq (sigma_n - s_n) + s_n arrow.long_(n arrow + infinity) 0 + A eq A, $ azaz $ B eq sum_(n eq 0)^(infinity) a_p_n eq lim_(n arrow + infinity) sigma_n eq lim_(n arrow + infinity) s_n eq sum_(n eq 0)^(infinity) a_n eq A. $ #pagebreak() == Sorok téglányszorzatának konvergenciája \ Tegyük fel, hogy a $sum_(n eq 0) a_n$ és a $sum_(n eq 0) b_n$ végtelen sorok konvergensek. Ekkor a $sum_(n eq 0) t_n$ téglányszorzatuk is konvergens és $ sum_(n eq 0)^(+infinity) t_n eq sum_(n eq 0)^(+infinity) a_n dot.op sum_(n eq 0)^(+infinity) b_n $ azaz konvergens sorok téglányszorzata is konvergens, és a téglányszorzat összege a két sor összegének szorzatával egyezik meg. === Bizonyítás \ A bizonyítás alapja a sorozatoknál tanult műveletek és határátmenet felcserélhetőségére vonatkozó tétel. Jelölje $A_n, B_n "és " T_n$ rendre a $sum_(n eq 0) a_n, sum_(n eq 0) b_n "és " sum_(n eq 0) t_n$ sorok n-edik részletösszegeit. Ekkor $ T_n eq sum_(k eq 0)^n t_k eq sum_(k eq 0)^n (sum_(max{i,j} eq k) a_i b_j) eq sum_(max{i,j} lt.eq n) a_i b_j eq (sum_(i eq 0)^n a_i) dot.op (sum_(j eq 0)^n b_j) eq $ $ eq A_n B_n arrow (sum_(n eq 0)^(+infinity) a_n) dot.op (sum_(n eq 0)^(+infinity) b_n), "ha " n arrow +infinity $ Ez azt jelenti, hogy a $(T_n)$ sorozat konvergens, és így a $sum t_n$ végtelen sor is konvergens, és $ sum_(n eq 0)^(+infinity) t_n eq lim(T_n) eq (sum_(n eq 0)^(+infinity) a_n) dot.op (sum_(n eq 0)^(+infinity) b_n) $ #pagebreak() == Abszolút konvergens sorok szorzatai \ Tegyük fel, hogy a $sum_(n eq 0) a_n$ és $sum_(n eq 0) b_n$ végtelen sorok mindegyike abszolút konvergens. Ekkor 1. a $sum_(n eq 0) t_n$ téglányszorzat is abszolút konvergens, 2. a $sum_(n eq 0) c_n$ Cauchy-szorzat is abszolút konvergens, 3. az összes $a_i b_j (i,j in NN)$ szorzatból tetszés szerinti sorrendben és csoportosításban képzett $sum_(n eq 0) d_n$ végtelen sor is abszolút konvergens, és $ (\*) sum_(n eq 0)^(+infinity) d_n eq sum_(n eq 0)^(+infinity) t_n eq sum_(n eq 0)^(+infinity) c_n eq (sum_(n eq 0)^(+infinity) a_n) dot.op (sum_(n eq 0)^(+infinity) b_n) $ === Bizonyítás \ Elég a 3. állítást igazolni. Mivel $sum a_n$ és $sum b_n$ abszolút konvergensek, ezért $ A_N := sum_(n eq 0)^N abs(a_n) arrow.long_(n arrow +infinity) A in RR, space B_N := sum_(n eq 0)^N abs(b_n) arrow.long_(n arrow +infinity) B in RR $ Tekintsünk egy tetszőleges $sum(d_n)$ sort, ahol $d_n eq sum a_i b_j$. Legyen $N in NN$ tetszőleges. Jelölje I, illetve J a maximális i, illetve j indexet a $d_0,d_1,...,d_N$ összegekben. Ekkor $ sum_(n eq 0)^N abs(d_n) lt.eq sum_(0 lt.eq i lt.eq I\ 0 lt.eq j lt.eq J) abs(a_i b_j) eq (sum_(n eq 0)^I abs(a_n)) dot.op (sum_(n eq 0)^J abs(b_n)) lt.eq A dot.op B $ és ez azt jelenti, hogy a $sum abs(d_n)$ nemnegatív tagú sor konvergens, mert részletösszegei korlátosak. Tehát $sum(d_n)$ abszolút konvergens. \ \ A fentiek érvényesek $d_n eq t_n$ esetén, így a $sum t_n$ téglányszorzat is abszolút konvergens, tehát konvergens is. Ekkor a _Sorok téglányszorzatának konvergenciája_ tétel szerint (\*) teljesül a $sum t_n$ sorra, azaz $ sum_(n eq 0)^(+infinity) t_n eq sum_(n eq 0)^(+infinity) a_n dot.op sum_(n eq 0)^(+infinity) b_n $ Legyen $sum t^\*_n$ az a sor, amelyet a $sum t_n$ téglányszorzatban szereplő zárójelek elhagyásával kapunk. Mivel $sum t^\*_n$ is egy lehetséges $sum d_n$ típusú sor, ezért $sum t^\*_n$ is abszolút konvergens, és így bármely zárójelezésével az összege nem változik, azaz (\*) teljesül a $sum t^\*_n$ sorra: $ sum_(n eq 0)^(+infinity) t^\*_n eq sum_(n eq 0)^(+infinity) t_n eq sum_(n eq 0)^(+infinity) a_n dot.op sum_(n eq 0)^(+infinity) b_n $ Azonban bármely $sum d_n$ típusú sor megkapható a $sum t^\*_n$ sorból megfelelő átrendezéssel és csoportosítással. Ekkor a sor összege nem változik, tehát (\*) teljesül tetszőleges $sum d_n$ sorra. #pagebreak() == Hatványsorok konvergenciasugara Tetszőleges $sum_(n eq 0) alpha_n (x-a)^n$ hatványsor konvergenciahalmazára a következő három eset egyike áll fenn: 1. $exists 0 lt R lt +infinity$, hogy a haványsor $forall x in RR : abs(x-a) lt R$ pontban abszolút konvegens és $forall x in RR : abs(x-a) gt R$ pontban divergens. 2. A hatványsor csak az $x eq a$ pontban konvergens. Ekkor legyen $R := 0$ 3. A hatványsor abszolút konvergens $forall x in RR$ esetében. Ekkor legyen $R := +infinity$. R-et a hatványsor konvergenciasugarának nevezzük. === Bizonyítás Az állítás elég $a eq 0$ esetén igazolni. ==== Segédtétel Tegyük fel, hogy a $sum alpha_n x^n$ hatványsor konvergens egy $x_0 eq.not 0$ pontban. Ekkor $forall x in RR : abs(x) lt abs(x_0)$ esetén a hatványsor abszolút konvegens az x pontban. ==== Segédtétel bizonyítása Mivel a $sum alpha_n x_0^n$ végtelen sor konvergens, ezért $lim(a_n x_0^n) eq 0$, így az $(a_n x_0^n)$ sorozat korlátos, azaz $ exists M gt 0 : abs(alpha_n x_0^n) lt.eq M lt +infinity space (n in NN) $ Legyen $x in RR$ olyen, amire $abs(x) lt abs(x_0)$ teljesül. Ekkor $ abs(alpha_n x^n) eq abs(alpha_n x_0^n) dot.op abs(x/x_0)^n lt.eq M dot.op abs(x/x_0)^n =: M q^n space (n in NN) $ A $sum abs(alpha_n x^n) $ végtelen sor tehát majorálható a $sum(M q^n)$ mértani sorral, ami konvergens, mert $abs(q) eq abs(x/x_0) lt 1$. Így a majoráns kritérium szerint a $sum abs(alpha_n x^n)$ sor is konvergens, tehát a $sum(alpha_n x^n)$ végtelen sor is konvergens. ==== Tétel bizonyítása Tekintsük a $sum alpha_n x^n$ hatványsort. Ez $x eq 0$-ban nyilván konvergens, ezért $K H(sum alpha_n x^n) eq.not emptyset$, és így $ exists sup K H (sum_(n eq 0) alpha_n x^n) =: R in macron(RR) "és " R gt.eq 0 $ A következő három eset lehetséges 1. $0 lt R lt +infinity$. Legyen $abs(x) lt R$ tetszőleges. Ekkor a szuprémum definíciója szerint $exists x_0 gt 0 : abs(x) lt x_0 lt R$ és $x_0$ a konvergenciahalmaz eleme, azaz $sum alpha_n x_0^n$ konvergens. Ekkor a segédtétel szerint $sum alpha_n x^n$ abszolút konvergens. Ha $abs(x) gt R$ tetszőleges, akkor az R szám definíciója és a segédtétel szerint a $sum alpha_n x^n$ sor divergens. 2. $R eq 0$. A $sum alpha_n x^n$ hatványsor az $x eq 0$ pontban nyilván konvergens. Tegyük fel, hogy $x eq.not 0$ olyan pont ahol $sum alpha_n x^n$ konvergens. Ekkor a segédtétel szerint a hatványsor konvergens az $abs(x)/2 gt 0$ pontban, ami nem lehetségesm mert $R = 0$. A hatványsor tehát csak az $x eq 0$ pontban konvergens. 3. $R eq +infinity$. Legyen $x in RR$ tetszőleges. Ekkor a szuprémum definíciója értelmében $exists x_0 gt 0 : abs(x) lt x_0$ és $x_0$ a konvergenciahalmaz eleme, azaz $sum alpha_n x_0^n$ konvergens. Ekkor a segédtétel szerint $sum alpha_n x^n$ abszolút konvergens. #pagebreak() == A Cauchy-Hadamard-tétel \ Tekintsük a $sum_(n eq 0) alpha_n (x-a)^n$ hatványsort, és tegyük fel, hogy $ exists lim(root(n, abs(alpha_n))) =: A in macron(RR) $ Ekkor a hatványsor konvergenciasugara $ R = 1/A space (1 / (+infinity) := 0, 1/0 := +infinity) $ === Bizonyítás \ Nyilvánvaló, hogy $A gt.eq 0$. Rögzítsük tetszőlegesen az $x in RR$ számot, és alkamazzuk a Cauchy-féle gyökkritériumot a $ sum alpha_n(x-a)^n$ végtelen számsorra: $ lim_(n arrow +infinity) root(n, abs(alpha_n (x-a)^n)) eq (lim_(n arrow +infinity) root(n, abs(alpha_n)) dot.op abs(x-a) eq A abs(x-a), "és így" $ $ A abs(x-a) lt 1 arrow.long.double "a sor konvergens", space A abs(x-a) gt 1 arrow.long.double "a sor divergens." $ 1. Ha $0 lt a lt +infinity$, akkor A-val lehet osztani, és akkor $ x in ( a - 1/A, a+ 1/A) arrow.double.long " a sor konv.," x in.not [a - 1/A, a+ 1/A] arrow.long.double "a sor div." $ amiből következik, hogy $R eq 1/A$ 2. Ha $ A eq +infinity$, akkor $forall x in RR, x != a: A abs(x-a) eq (+infinity) dot.op abs(x-a) eq +infinity gt 1$\ Ezért a hatványsor az $x eq a$ pont kivételével divergens, azaz $R eq 0$ 3. Ha $A eq 0$, akkor $forall x in RR: A abs(x-a) eq 0 dot.op abs(x-a) eq eq 0 lt 1$\ Ezért a hatványsor minden $x in RR$ pontban konvergens, azaz $R eq +infinity$ #pagebreak() == Függvények határértékének egyértelműsége \ Ha az $f in RR arrow.long RR$ függvénynek az $a in D^'_f$ pontban van határértéke, akkor a definícióban szereplő $A in macron(RR)$ egyértelműen létezik. === Bizonyítás \ Tegyük fel, hogy két különböző $A_1, A_2 in macron(RR)$ elem eleget tesz a definíció feltételeinek. Mivel két különböző $macron(RR)$-beli elem diszjunkt környezetekkel szétválasztható ezért $ exists epsilon gt 0 : K_epsilon (A_1) sect K_epsilon (A_2) eq emptyset $ A határérték definíciója szerint egy ilyen $epsilon$-hoz $ exists delta_1 gt 0, forall x in K_delta_1 (a) sect D_f : f(x) in K_epsilon (A_1) $ $ exists delta_2 gt 0, forall x in K_delta_2 (a) sect D_f : f(x) in K_epsilon (A_2) $ Legyen $delta := min{delta_1, delta_2}$. Ekkor $ forall x in K_delta (a) sect D_f : f(x) in K_epsilon (A_1) sect K_epsilon (A_2) eq emptyset, "de " K_delta (a) sect D_f != emptyset, "mert " a in D^'_f. $ Ellentmondásra jutottunk, és ezzel a határérték egyértelműségét igazoltuk. #pagebreak() == A határértékre vonatkozó átviteli elv \ Legyen $f in RR arrow RR, a in D^'_f "és " A in macron(RR)$. Ekkor $ lim_a f eq A arrow.l.r.double.long forall(x_n) : NN arrow D_f \\ {a}, lim_(n arrow +infinity) x_n eq a "esetében " lim_(n arrow +infinity) f(x_n) eq A $ === Bizonyítás $arrow.double.r space space lim_a f eq A arrow.double.long forall epsilon gt 0"-hoz" exists delta gt 0, forall x in K_delta (a) sect D_f : f(x) in K_epsilon (A).$ Legyen $(x_n)$ egy, a tételben szereplő sorozat, és $epsilon gt 0$ egy tetszőleges rögzített érték. $ lim x_n eq a arrow.long.double delta"-hoz" exists n_0 in NN, forall n gt n_0 : x_n in K_delta (a) $ Mivel $x_n in D_f \\ {a}$, így $x_n in K_delta (a) sect D_f$, amiből $f(x_n) in K_epsilon (A)$ teljesül minden $n gt n_0$ indexre. Ez azt jelenti, hogy az $(f(x_n))$ sorozatnak van határértéke, és $lim_(n arrow +infinity) f(x_n) eq A$ $arrow.l.double$ Tegyük fel, hogy $ forall(x_n) : NN arrow D_f \\ {a}, lim_(n arrow +infinity) x_n eq a "esetén " lim_(n arrow +infinity) f(x_n) eq A. $ Megmutatjuk, hogy $lim_a f = A$ Indirekt módon tegyük fel, hogy a $lim_a f = A$ egyenlőség nem igaz. Ez pontosan azt jelenti, hogy $ exists epsilon gt 0, forall delta gt 0"-hoz" exists x_delta in K_delta (a) sect D_f : f(x_delta) in.not K_epsilon (A) $ A $delta eq 1/n (n in NN^+)$ választással ez azt jelenti, hogy $ exists epsilon gt 0, forall n in NN^+"-hoz" exists x_n in K_(1/n) (a) sect D_f : f(x_n) in.not K_epsilon (A) $ Legyen $x_0 in D_f \\ {a}$ tetszőleges. Az $(x_n) : NN arrow D_f \\ {a}$ sorozat nyilván a-hoz tart (hiszen $x_n in K_(1/n) (a)$), de a függvényértékek $(f(x_n))$ sorozata nem tart A-hoz (hiszen $f(x_n) in.not K_epsilon (A)$), ami ellentmond a feltételünknek. #pagebreak() == Monoton függvények határértékei \ Legyen $(alpha, beta) subset RR$ tetszőleges (korlátos vagy nem korlátos) nyílt intervallum. Ha az f függvény monoton $(alpha, beta)$-n, akkor f-nek $forall a in (alpha, beta)$ pontban létezik a jobb oldali, illetve a bal oldali határértéke, és ezek végesek. \ 1. Ha f $arrow.tr (alpha,beta)$-n, akkor $ lim_(a+0) f eq inf{f(x) | x in (alpha, beta), x gt a} $ $ lim_(a-0) f eq sup{f(x) | x in (alpha, beta), x lt a} $ 2, Ha f $arrow.br (alpha, beta)$-n, akkor $ lim_(a+0) f = sup{f(x) | x in (alpha, beta), x gt a} $ $ lim_(a-0) f = inf{f(x) | x in (alpha,beta), x lt a} $ === Bizonyítás Tegyük fel, hogy $f arrow.tr (alpha,beta)-n$. A jobb oldali határértékre vonatkozó állítást igazoljuk. Legyen $ m := inf{f(x) | x in (alpha,beta), x gt a} $ Világos, hogy $m in RR$. Az infimum definíciójából következik, hogy 1. $forall x in (alpha, beta), x gt a : m lt.eq f(x)$ 2. $forall epsilon gt 0"-hoz" exists x_1 in (alpha,beta), x_1 gt a : f(x_1) lt m + epsilon$ Így $m lt.eq f(x_1) lt.eq m + epsilon$. Mivel $f arrow.tr (alpha,beta)$-n, ezért $ m lt.eq f(x) lt.eq f(x_1) lt m + epsilon space (x in (a, x_1)) $ A $delta := x_1 - a gt 0$ választással tehát azt mutattuk meg, hogy $ forall epsilon gt 0"-hoz" exists delta gt 0, forall x in (alpha,beta), a lt x lt a + delta : 0 lt.eq f(x) - m lt epsilon eq f(x) in K_epsilon (m) $ Ez pedig azt jelenti, hogy f-nek a-ban van jobb oldali határértéke, és az m-mel egyenlő, azaz $ lim_(a+0) f eq m eq inf{f(x) | x in (alpha,beta), x gt a}. $ A tétel többi állítása hasonlóan bizonyítható. #pagebreak() == Az összetett függvény folytonossága \ Tegyük fel, hogy $f,g in RR arrow.long RR, g in C{a} "és " f in C{g(a)}.$ Ekkor $f space circle.small space g in C{a}$, azaz az összetett föggvény örökli a belső- és a külső függvény folytonosságát. === Bizonyítás \ A feltételek szerint $g(a) in D_f$, ezért $g(a) in R_g sect D_f$, azaz $R_g sect D_f != emptyset$. Így valóban beszélgetünk az $f circle.small space g$ összetett függvényről, és $a in D_(f circle.small g)$ is igaz. \ Legyen $(x_n) : NN arrow D_(f circle.small g) subset D_g$ egy olyan sorozat, amelyre $lim(x_n) eq a$. Mivel\ $g in C{a}$, így a folytonosságra vonatkozó átviteli elv szerint $lim(g(x_n)) eq g(a)$. Jelölje $ b := g(a) "és " y_n := g(x_n) space (n in NN) $ Ekkor $(y_n) : NN arrow D_f$ és $lim(y_n) eq b$. Mivel $f in C{b}$, így a folytonosságra vonatkozó átviteli elv szerint $lim(f(y_n)) eq f(b)$. Ugyanakkor $ f(b) eq f(g(a)) eq (f circle.small g)(a) "és " f(y_n) eq f(g(x_n)) eq (f circle.small g)(x_n) space (n in NN) $ Azt igazoltuk tehát, hogy $forall (x_n) : NN arrow D_(f circle.small g), lim(x_n) eq a$ sorozat esetén igaz, hogy $ lim_(n arrow +infinity) (f circle.small g)(x_n) eq lim_(x arrow +infinity) (f(y_n)) eq f(b) eq (f circle.small g)(a) $ Ezért a folytonosságra vonatkozó átviteli elv szerint $f circle.small g in C{a}$
https://github.com/PhilChodrow/cv
https://raw.githubusercontent.com/PhilChodrow/cv/main/src/content/experience.typ
typst
#import "../template.typ": * #cvSection("Experience", vspace:0cm) #cvEntry( title: [Assistant Professor of Computer Science], organisation: [Middlebury College], // logo: "", date: [2022 -- present], location: [Middlebury, VT], description: "" // tags: ("Go", "TypeScript", "React", "PostgreSQL") ) #cvEntry( title: [Hedrick Visiting Assistant Adjunct Professor of Mathematics], organisation: [University of California, Los Angeles], // logo: "", date: [2020 -- 2022], location: [Los Angeles, CA], description: "" // tags: ("Go", "TypeScript", "React", "PostgreSQL") )
https://github.com/MDLC01/board-n-pieces
https://raw.githubusercontent.com/MDLC01/board-n-pieces/main/src/README.md
markdown
MIT License
> [!NOTE] > This file is used to generate [the Typst Universe page](https://typst.app/universe/package/board-n-pieces). It is processed by [`/build.py`](/build.py). # Board & Pieces Display chessboards in Typst. ## Displaying chessboards The main function of this package is `board`. It lets you display a specific position on a board. ```example #board(starting-position) ``` `starting-position` is a position that is provided by the package. It represents the initial position of a chess game. You can create a different position using the `position` function. It accepts strings representing each rank. Use upper-case letters for white pieces, and lower-case letters for black pieces. Dots and spaces correspond to empty squares. ```example #board(position( "....r...", "........", "..p..PPk", ".p.r....", "pP..p.R.", "P.B.....", "..P..K..", "........", )) ``` Alternatively, you can use the `fen` function to create a position using [Forsyth–Edwards notation](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation): ```example #board(fen("r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1 b - - 1 23")) ``` Note that you can specify only the first part of the FEN string: ```example #board(fen("r4rk1/pp2Bpbp/1qp3p1/8/2BP2b1/Q1n2N2/P4PPP/3RK2R")) ``` Also note that positions do not need to be on a standard 8×8 board: ```example #board(position( "....Q....", "......Q..", "........Q", "...Q.....", ".Q.......", ".......Q.", ".....Q...", "..Q......", "Q........", )) ``` ## Using the `game` function The `game` function creates an array of positions from a full chess game. A game is described by a series of turns written in [standard algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)). Those turns can be specified as an array of strings, or as a single string containing whitespace-separated moves. ```example %show: pad.with(0.5cm) The scholar's mate: #let positions = game("e4 e5 Qh5 Nc6 Bc4 Nf6 Qxf7") #grid( columns: 4, gutter: 0.2cm, ..positions.map(board.with(square-size: 0.5cm)), ) ``` You can specify an alternative starting position to the `game` function with the `starting-position` named argument. ## Using the `pgn` function to import PGN files Similarly to the `game` function, the `pgn` function creates an array of positions. It accepts a single argument, which is a string containing [portable game notation](https://en.wikipedia.org/wiki/Portable_Game_Notation). To read a game from a PGN file, you can use this function in combination with Typst's native [`read`](https://typst.app/docs/reference/data-loading/read/) function. ```typ #let positions = pgn(read("game.pgn")) ``` Note that the argument to `pgn` must describe a single game. If you have a PGN file containing multiple games, you will need to split them using other means. ## Using non-standard chess pieces The `board` function's `pieces` argument lets you specify how to display each piece by mapping each piece character to some content. You can use this feature to display non-standard chess pieces: ```example %set text(size: 0.8cm, font: "Noto Sans Symbols 2") #board( fen("g7/5g2/8/8/8/8/p6g/k1K4G"), pieces: ( // We use symbols for the example. // In practice, you should import your own images. g: chess-sym.queen.black.b, p: chess-sym.pawn.black, k: chess-sym.king.black, K: chess-sym.king.white, G: chess-sym.queen.white.b, ), ) ``` ## Customizing a chessboard The `board` function lets you customize the appearance of the board in various ways, as illustrated in the example below. ```example // From https://lichess.org/study/Xf1PGrM0. #board( fen("3k4/7R/8/2PK4/8/8/8/6r1 b - - 0 1"), marked-squares: "c7 c6 h6", arrows: ("d8 c8", "d8 c7", "g1 g6", "h7 h6"), display-numbers: true, white-square-fill: rgb("#d2eeea"), black-square-fill: rgb("#567f96"), marking-color: rgb("#2bcbC6"), arrow-stroke: 0.2cm + rgb("#38f442df"), stroke: 0.8pt + black, ) ``` Here is a list of all the available arguments: - `marked-squares` is a list of squares to mark (e.g., `("d3", "d2", "e3")`). It can also be specified as a single string containing whitespace-separated squares (e.g., `"d3 d2 e3"`). - `arrows` is a list of arrows to draw (e.g., `("e2 e4", "e7 e5")`). - `reverse` is a boolean indicating whether to reverse the board, displaying it from black's point of view. This is `false` by default, meaning the board is displayed from white's point of view. - `display-numbers` is a boolean indicating whether ranks and files should be numbered. This is `false` by default. - `rank-numbering` and `file-numbering` are functions describing how ranks and files should be numbered. By default they are respectively `numbering.with("1")` and `numbering.with("a")`. - `square-size` is a length describing the size of each square. By default, this is `1cm`. - `white-square-fill` and `black-square-fill` indicate how squares should be filled. They can be colors, gradient or patterns. - `marking-color` is the color to use for markings (marked squares and arrows). - `marked-white-square-background` and `marked-black-square-background` define the content to display in the background of marked squares. By default, this is a circle using the `marking-color`. - `arrow-stroke` is the stroke to draw the arrows with. If only a length is given, `marking-color` is used. Alternatively, a stroke can be passed to specify a different color. - `pieces` is a dictionary containing images representing each piece. If specified, the dictionary must contain an entry for every piece kind in the displayed position. Keys are single upper-case letters for white pieces and single lower-case letters for black pieces. The default images are taken from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces). Please refer to [the section on licensing](#licensing) for information on how you can use them in your documents. - `stroke` has the same structure as [`rect`'s `stroke` parameter](https://typst.app/docs/reference/visualize/rect/#parameters-stroke) and corresponds to the stroke to use around the board. If `display-numbers` is `true`, the numbers are displayed outside the stroke. The default value is `none`. ## Chess symbols This package also exports chess symbols for all Unicode chess-related codepoints under the `chess-sym` submodule. Standard chess pieces are available as `chess-sym.{pawn,knight,bishop,rook,queen,king}.{white,black,neutral}`. Alternatively, you can use `stroked` and `filled` instead of, respectively, `white` and `black`. They can be rotated rightward, downward, and leftward respectively with with `.r`, `.b`, and `.l`. Chinese chess pieces are also available as `chess-sym.{soldier,cannon,chariot,horse,elephant,mandarin,general}.{red,black}`. Similarly, you can use `stroked` and `filled` as alternatives to, respectively, `red` and `black`. Note that most fonts only support black and white versions of standard pieces. To use the other symbols, you may have to use a font such as Noto Sans Symbols 2. ```example %show: pad.with(0.5cm) The best move in this position is #chess-sym.knight.white;c6. ``` ## Licensing The default images for chess pieces used by the `board` function come from [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:SVG_chess_pieces). They are all licensed the [GNU General Public License, version 2](https://www.gnu.org/licenses/old-licenses/gpl-2.0.html) by their original author: [Cburnett](https://en.wikipedia.org/wiki/User:Cburnett).
https://github.com/GuilloteauQ/typst-slides-unibas
https://raw.githubusercontent.com/GuilloteauQ/typst-slides-unibas/main/theme.typ
typst
#import "@preview/polylux:0.3.1": * #let unibas-mint = rgb("#a5d7d2") #let unibas-mint-light = rgb("#c0e3df") #let unibas-theme(aspect-ratio: "16-9", body) = { set page( paper: "presentation-" + aspect-ratio, fill: white, margin: 0em, header: none, footer: none, ) let unibas-marker = image("marker.svg", width: 4mm) set text(fill: white.darken(90%), size: 30pt, font: "Inconsolata") set list(marker: unibas-marker) body } #let title-slide(title: [], authors: ()) = { let array_affiliations = authors.map(d => d.affiliation).dedup() let affiliations_str = array_affiliations.enumerate().map(x => { let (i, a) = x super(str(i + 1)) + a }).join("\n") let authors_str = authors.map(d => { let affiliation_index = array_affiliations.position(a => a == d.affiliation) if d.is_presenter { underline(d.name) } else { d.name } + super(str(affiliation_index + 1)) }).join(", ", last: " and ") let content = { stack( block(width: 100%, height: 20%, fill: unibas-mint, place(horizon+left, dx: 2.5%, image("logo.svg", width: 20%))), block(width: 100%, inset: 0.8em, above: 0pt, below: 0pt, breakable: false, text(fill: black, size: 1.2em, title)), line(start: (2.5%, 0%), length: 95%, stroke: (paint: unibas-mint, thickness: 2pt, dash: "loosely-dashed")), block(width: 100%, height: 10%, inset: 0.8em, above: 0pt, below: 0pt, breakable: false, text(fill: black, size: 0.7em, authors_str)), parbreak(), block(width: 100%, inset: 0.8em, above: 0pt, below: 0pt, breakable: false, text(fill: black, size: 0.7em, affiliations_str)), ) } polylux-slide(content) } #let m-cell = block.with( width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false ) #let m-progress-bar = utils.polylux-progress( ratio => { grid( columns: (ratio * 100%, 1fr), m-cell(fill: unibas-mint, height: 200%), m-cell(fill: unibas-mint-light) ) }) #let new-section-slide(name) = { let content = { utils.register-section(name) set align(horizon) show: pad.with(20%) set text(size: 1.5em) name block(height: 2pt, width: 100%, spacing: 0pt, m-progress-bar) } polylux-slide(content) } #let slide(title: none, presentation-title: [], presenter: [], body) = { let header = { set align(top) if title != none { block(width: 100%, inset: 0.8em, above: 0pt, below: 0pt, breakable: false, text(fill: black, size: 1.2em, title)) line(start: (2.5%, 0%), length: 95%, stroke: (paint: unibas-mint, thickness: 2pt, dash: "loosely-dashed")) } else { [] } } let footer = stack( block(width:100%, height: 100%, breakable:false, grid(columns: (65%, 25%, 10%), gutter: 0cm, block(fill: unibas-mint, width: 100%, height: 100%, inset: 0.4em, align(horizon, text(fill: black, presentation-title, size: 0.6em))), block(fill: unibas-mint-light, width: 100%, height: 100%, align(center+horizon, text(fill: black, presenter, size: 0.6em))), block(fill: unibas-mint, width: 100%, height: 100%, align(center+horizon, text(fill: black, logic.logical-slide.display() + [/] + utils.last-slide-number, size: 0.6em))), ))) set page( header: header, footer: footer, margin: (top: 3em, bottom: 1em), ) let content = { show: align.with(horizon) show: pad.with(1em) set text(fill: black) body } polylux-slide(content) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/edge_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // // // Error: 24-36 expected "baseline", "descender", "bounds", or length // #set text(bottom-edge: "cap-height")
https://github.com/waynr/rsume
https://raw.githubusercontent.com/waynr/rsume/main/templates/general-purpose.typ
typst
{% for keyword in keywords -%} #show regex("(?i)\\b{{keyword}}\\b"): set text(weight: "black", fill: rgb("#39cccc")) {% endfor %} #let page_title(body) = { set align(center) set text( size: 2.0em, weight: "medium", ) [#body] } #let data = yaml("data.yaml") #let theme = { let d = (:) let t = yaml("theme.yaml") for (key, value) in t { if key == "font" { d.insert(key, value) } else { d.insert(key, rgb(value)) } } d } #show link: it => text( fill: theme.links, [#underline(it)] ) #let website(item) = { link(item.url)[#item.network] } #let h1(body) = { set text( fill: theme.h1, size: 1.5em, weight: "medium", ) [#box(width: 10pt, repeat[\_])#body#box(width: 1fr, repeat[\_])] } #let h2(body) = { set text( fill: theme.h2, size: 1.2em, weight: "semibold", ) [#body] } #let cell = rect.with( width: 100%, stroke: none, radius: 2pt ) #let rcell(body, inset: 2pt) = { set align(right) rect( inset: inset, width: 100%, stroke: none, radius: 2pt, [#body] ) } #let indentedlist(items, indent: 5pt) = { set list( indent: indent, ) for item in items { [- #item] } } #let summary(contents) = { h1("Summary") grid( columns: (3fr, 1fr), rows: (auto), column-gutter: 8pt, cell( inset: 0pt, stroke: (right: 0.5pt + theme.foreground), radius: 0pt, )[ #grid( cell( stroke: none, inset: 5pt, par( justify: true, first-line-indent: 10pt, [ #contents.description ], ) ), grid( row-gutter: 0pt, columns: (3fr, 4fr), rows: (auto), cell[#h2("Education")], cell[#align(right, contents.education, )], cell[#h2("Industry Experience")], cell[#align(right, contents.industry_experience, )], ), ) ], cell( inset: (left: 0pt), )[ #h2("Interests") \ #v(10pt) #indentedlist(data.summary.interests) ] ) } #let position(item) = { ( cell(inset: 0pt)[ #text(weight: "medium", item.title) ], rcell[ #item.startDate - #item.endDate ], ) } #let positions(items) = { grid( columns: (1fr, 1fr), rows: (auto), ..items.map(position).flatten(), ) } #let work(item) = { grid( columns: 1, rows: (auto), column-gutter: 8pt, cell(inset: 0pt)[ // company details #grid( columns: (1fr, 2fr), rows: (auto), cell(inset: 0pt)[ #h2(item.name) ], cell(inset: 0pt)[ #if item.keys().contains("url") { item.url } ], ) ], cell(inset: 8pt)[ #if item.at("positions", default: ()).len() > 0 { // positions positions(item.positions) } else { cell(inset: 0pt)[ #text(weight: "medium", item.position) ] } ], if item.at("highlights", default: "").len() > 0 { cell(inset: 0pt)[ // projects #indentedlist(item.highlights, indent: 13pt) ] }, ) } #let works(items) = { h1("Experience") for i in items { work(i) } } #let education(item) = { table( stroke: none, align: (ci, ri) => { if ci == 1 { left } else if ci == 2 and ri == 1 { center + horizon } else { right } }, columns: (5pt, 8fr, 4fr), rows: (5pt, auto), [], [ #h2(item.institution) ], h2( [ #item.startDate - #item.endDate ]), [], rect( inset: 10pt, width: 100%, stroke: none, [ #for degree in item.degrees { [ #emph(degree) \ ] } ], ), [ GPA: #item.score ], ) } #let educations(items) = { h1("Education") for i in items { education(i) } } #let project(item) = { rect( stroke: (left: 0.1pt + theme.foreground), [ #align(left)[#link("https://"+item.url)[#item.url]] #if item.at("description", default: "").len() > 0 { par( first-line-indent: 5pt, justify: true, [#item.description], ) } ], ) } #let projects(items) = { h1("Open Source Projects") table( stroke: none, columns: (1fr, 1fr, 1fr), ..items.map(project), ) } #let skills(items) = { h1("Skills") for i in items { skill(i) } } // // // Content // // // global settings #set text( fill: theme.foreground, font: ( //theme.font, //"DejaVu Sans Mono", //"Luxi Mono", //"CodingFontTobi", //"C059", //"Andale Mono", //"Cantarell", //"ProggyCrossed", //"ProggyVector", "Verdana", "Liberation Mono", "FreeMono", ), size: 6pt, ) #set page( paper: "us-letter", margin: 0.5in, fill: theme.background, header: [ #set align(center) #data.basics.profiles.map(website).join(" - ") #v(5pt) ], ) #page_title(data.basics.name) #if data.at("summary", default: "").len() > 0 { summary(data.summary) } #if data.at("projects", default:"").len() > 0 { projects(data.projects) } #if data.work.len() > 0 { works(data.work) } #if data.education.len() > 0 { educations(data.education) } #if false and data.skills.len() > 0 { educations(data.skills) }
https://github.com/mrknorman/cv
https://raw.githubusercontent.com/mrknorman/cv/main/michael_norman_cv.typ
typst
#import "template.typ": * #show: project.with( title: "Research Scientist", author: "Dr <NAME>", github: "mrknorman", linkedin : "mrknorman", phone: "+44 7956 775128", email: "<EMAIL>" ) = Education #cventry( start: (month: "September", year: 2019), end: (month: "February", year: 2024), role: [Gravitational Wave Physics], place: "UKRI CDT in Artificial Intelligence, Machine Learning and Advanced Computing, PhD" )[#v(1em) Transformers and genetic algorithms for gravitational-wave science.] #cventry( start: (month: "September", year: 2017), end: (month: "September", year: 2018), role: [Distinction in Physics], place: "Cardiff University, MSc" )[Convolutional neural networks for gravitational-wave detection.] /* #cventry( start: (month: "September", year: 2013), end: (month: "June", year: 2017), role: [Physics], place: "Cardiff University, BSc" )[Testing the lithopansperima hypothesis with N-body simulation.] */ = Technical Skills #cvcol[ ==== Programming Languages #grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), row-gutter: 0.5em, [- C/C++], [- Python], [- Rust], [- BASH], [- SQL] ) ] /* [- HTML], [- CSS], [- JavaScript], [- PHP] */ #cvcol[ ==== Software Tools #grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), row-gutter: 0.5em, [- Git/GitHub], [- Valgrind], [- GDB], [- Vim], [- Anaconda], ) ] #cvcol[ ==== Libraries and APIs #grid( columns: (1fr, 1fr, 1fr, 1fr, 1fr), row-gutter: 0.5em, [- CUDA], [- TensorFlow], [- PyTorch], [- PySpark], [- NumPy] ) ] /* [- SciPy], [- Pandas], [- OpenAI API], */ = Work Experience #cventry( start: (month: "April", year: 2021), end: (month: "December", year: 2021), role: [Research Placement], place: "Rutherford Appleton Laboratories, SciML Group", "VAE-GAN generative models with self-optimising latent space dimensionality." ) #cventry( start: (month: "April", year: 2019), end: (month: "August", year: 2019), role: [Data Scientist], place: "Office for National Statistics, VAT team.", "Python tools to aid the VAT team in the process of VAT data cleaning and miscellaneous other tools for adjacent teams." ) = Projects #cventry( start: (month: "September", year: 2019), end: (month: "", year: "Present"), role: [Developer], place: "MLy", "A new transient burst detection pipeline which utilises artificial neural networks to perform rapid coherence detection of gravitational wave bursts. MLy will be the first fully ML-based detection pipeline to be deployed in a live gravitational wave search." ) #cventry( start: (month: "February", year: 2023), end: (month: "March", year: 2024), role: [Sole Developer], place: "GravyFlow", "A package of TensorFlow tools to facilitate gravitational-wave model training, including data acquisition, model training, hyperparameter optimisation, and model validation." ) #cventry( start: (month: "October", year: 2022), end: (month: "June", year: 2023), role: [Sole Developer], place: "CuPhenom", "A GPU-based generator of IMRPhenomD Gravitational-Wave approximants. Written in C++ using CUDA." )
https://github.com/Many5900/aau-typst
https://raw.githubusercontent.com/Many5900/aau-typst/main/README.md
markdown
# typst-report #### TO COMPILE LOCALLY RUN $ `typst watch main.typ` #### TO VIEW PDF LOCALLY RUN $ `tinymist preview main.typ --partial-rendering` ### typst [typst](https://github.com/typst/typst) \ macOS: `brew install typst` \ Windows: `winget install --id Typst.Typst` ### tinymist [tinymist](https://github.com/Myriad-Dreamin/tinymist) \ macOS: `brew install tinymist` ### tinymist VSCode extension [VSCode](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist)
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/footnote_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test nested footnotes. First \ Second #footnote[A, #footnote[B, #footnote[C]]] \ Third #footnote[D, #footnote[E]] \ Fourth
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/casoslov/postne_casy/cas1.typ
typst
#import "/style.typ": * #import "/SK/texts.typ": * #import "../styleCasoslov.typ": * = Prvý pôstny čas #show: rest => columns(2, rest) #nacaloBezKnaza #zalm(5) #zalm(89) #zalm(100) #si #lettrine("Aleluja, aleluja, aleluja, sláva tebe, Bože.") #note[(3x)] #lettrine("Pane, zmiluj sa.") #note[(3x)] == Katizma #note("Berieme katizmu podľa predpisu.") == Tropáre #centerNote("6. hlas") #lettrine("Za rána počúvaš môj hlas, * môj Kráľ a môj Boh.") #vers("Pane, počuj moje slová, všimni si moje vzdychanie.") #lettrine("Za rána počúvaš môj hlas, * môj Kráľ a môj Boh.") #vers("Veď, k tebe, Pane, sa modlím.") #lettrine("Za rána počúvaš môj hlas, * môj Kráľ a môj Boh.") #primText[#si (Bohorodičník)] #lettrine("Ako ťa nazveme, Milostiplná? * Nebom, lebo z teba zažiarilo Slnko spravodlivosti. * Rajom, lebo z teba vyrástol kvet neporušiteľnosti. * Pannou, lebo si zostala neporušená. * Čistou Matkou, lebo si mala vo svojom svätom náručí Syna, Boha všetkých. * Jeho pros za spásu našich duší.") #zoznam(( [Riaď moje kroky podľa tvojho výroku; \* nech ma neovláda nijaká neprávosť. \* Chráň ma pred ohováračmi \* a budem zachovávať tvoje príkazy. #secText("(dvakrát)")], [Vyjasni tvár nad svojím služobníkom \* a nauč ma svojim ustanoveniam. #secText("(dvakrát)")], [Nech sa mi ústa naplnia tvojou oslavou \* a nech ťa velebím deň čo deň. #secText("(trikrát)")], )) #trojsvatePoOtcenas == Tropáre #centerNote("4. hlas") #lettrine("Rýchlo ma predíď, Kriste, Bože náš, * kým sa nestaneme služobníkmi nepriateľov, * ktorí sa ti rúhajú a trápia nás. * Svojím krížom vyhub tých, čo povstávajú proti nám, * nech pochopia, čo dokáže viera pravoverných; * na príhovor Bohorodičky, * jediný milujúci človeka.") #secText[Sláva:] #lettrine("Vodca k múdrosti a darca rozumnosti, * vychovávateľ nerozumných a ochranca chudobných; * upevni, Vládca, moje srdce a daj mu chápavosť. * Otcovo slovo, ty sám vlož slová do mojich úst, * veď už nezabránim svojim perám, aby k tebe volali: * „Milosrdný, zmiluj sa nado mnou padlým.“") #secText[I teraz:] #lettrine("Hlasne ospevujme preslávnu Božiu Matku, * svätejšiu ako svätí anjeli. * Srdcom i ústami vyznávajme, že je Bohorodička, * lebo skutočne porodila vteleného Boha, * a neprestajne sa modlí za naše duše.") #lettrine("Pane, zmiluj sa.") #primText([40x]) #vKazdomCase #ektenia(3) #lettrine("Čestnejšia si ako cherubíni * a neporovnateľne slávnejšia ako serafíni, * bez porušenia si porodila Boha Slovo, * opravdivá Bohorodička, velebíme ťa.") Pane Ježišu Kriste, Bože náš, pre modlitby našich svätých otcov zmiluj sa nad nami. #efrem #trojsvatePoOtcenas #lettrine("Pane, zmiluj sa.") #note[(12x)] #lettrine("Kriste, pravé svetlo, ktoré osvecuje a posväcuje každého človeka prichádzajúceho na svet, nech sa ukáže na nás svetlo tvojej tváre, aby sme v ňom uvideli neprístupné svetlo, a nasmeruj naše kroky k uskutočňovaniu tvojich prikázaní, na príhovor tvojej prečistej Matky a všetkých tvojich svätých. Amen.") #prepustenieMaleBezKnaza
https://github.com/EpicEricEE/typst-plugins
https://raw.githubusercontent.com/EpicEricEE/typst-plugins/master/qr/src/lib.typ
typst
#import "qr.typ": create
https://github.com/angelcerveraroldan/notes
https://raw.githubusercontent.com/angelcerveraroldan/notes/main/algorithms_ds/inner/fenwick.typ
typst
#import "../../preamble.typ" : * = Fenwick Trees Fenwick trees can be used for efficient range / update queries. Both ranges and updates run in `O(log(n))`, and `O(n)` in memory. Fenwick trees are simpler to implement, and faster than segment trees, however there are many cases where a segment tree can be used, but a fenwick tree cannot be used. #def(title: "Traversal Functions", $ g(i) = i space \& space (i + 1) \ f(i) = i space \| space (i + 1) \ $) Given some input $a_1, a_2, ..., a_n$, a fenwick tree can be represented as an array $t_1, t_2, ..., t_n$. Where $t_i$ represents: $ t_i = sum_(k=g(i))^i a_k $ $ sum_(i=0)^r a_i = t_i + t_(g(i) - 1) + ... + t_(m) $ where $g(m) - 1$ is -1. Intuitively, the function $g$ will help us traverse the tree downwards. Then the function $f$ will help us move upwards! That is to say, if we want to modify some $a_i$, what elemnts of the tree will this affect ? Firstly, it will affect $t_i$, then it will affect $t_j$ where $j := f(i)$, then $t_u$ where $u := f(j)$, and so on until we are no longer in range. == Implementation Generally, the easiest way to go about implementation is to make a tree array (of the max size that we wil ever nned), as well as a global length variable (how much of that array are we actually using). Then we can mutate it in the update function. If we initialize the tree array with the group identity, then to fill the array in `O(nlog(n))`, we can just update each index as we get input. When you want to change some `index` to be some `value`, you must iterate all of the nodes that are affected by said change as follows: ```cpp // A way to remove the old element (group operation of a and its inverse is always 0) A inverse = inv(a_index); A new_value = group(inverse, value); for (int i = index; i > 0; i = f(i)) { tree[i] = group(tree[i], new_value); } ``` And when we want to get the group opearation of all elements from $a_0$ to $a_n$: ```cpp // This is usually the integer 0, but more genrally the identity of the group A acc = A::identity; for (int i = n; i > 0; i = g(i) - 1) acc = group(tree[i], acc); return acc ```
https://github.com/augustebaum/petri
https://raw.githubusercontent.com/augustebaum/petri/main/tests/fletcher/large-example/test.typ
typst
MIT License
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #import "@preview/cetz:0.2.2" as cetz #import "@preview/fletcher:0.4.2" as fletcher: edge // The example is taken from https://tikz.dev/library-petri#sec-64.4 #{ let p1 = (0,0) let p2 = cetz.vector.add(p1, (0, 1)) let p3 = cetz.vector.add(p2, (0, 1)) let p4 = cetz.vector.add(p3, (0, 1)) let p5 = cetz.vector.add(p4, (0, 1)) let p6 = cetz.vector.add(p5, (0, 1)) let tp1 = cetz.vector.add(p1, (1, 1 / 2)) let tp2 = cetz.vector.add(p2, (1, 1 / 2)) let tp31 = cetz.vector.add(p3, (1, 1 / 3)) let tp32 = cetz.vector.add(p3, (1, 2 / 3)) let tp41 = cetz.vector.add(p4, (1, 1 / 3)) let tp42 = cetz.vector.add(p4, (1, 2 / 3)) let tp5 = cetz.vector.add(p5, (1, 1 / 2)) let tp6 = cetz.vector.add(p6, (1, 1 / 2)) let m1f = cetz.vector.add(p2, (2, 1 / 4)) let m1t = cetz.vector.add(m1f, (0, 1 / 2)) let h1 = cetz.vector.add(p4, (2.5, 1 / 4)) let h2 = cetz.vector.add(h1, (0, 1 / 2)) let reflect(vec) = cetz.vector.add(vec, (2 * (h1.at(0) - vec.at(0)), 0)) let q1 = reflect(p1) let q2 = reflect(p2) let q3 = reflect(p3) let q4 = reflect(p4) let q5 = reflect(p5) let q6 = reflect(p6) let tq1 = reflect(tp1) let tq2 = reflect(tp2) let tq31 = reflect(tp31) let tq32 = reflect(tp32) let tq41 = reflect(tp41) let tq42 = reflect(tp42) let tq5 = reflect(tp5) let tq6 = reflect(tp6) let m2f = reflect(m1f) let m2t = reflect(m1t) let p = p.with(fill: blue.lighten(45%), stroke: blue.darken(10%)) let t = t.with(width: 0.3, height: 0.3, fill: red.lighten(25%), stroke: red.darken(10%)) let edge = edge.with(marks: "-|>") let double-edge = edge.with(marks: "<|-|>") fletcher.diagram( node-stroke: 1pt, spacing: (7em, 5em), p(p1, $p_1$, label-args: (anchor: "west"), tokens: 1), p(p2, $p_2$, label-args: (anchor: "west")), p(p3, $p_3$, label-args: (anchor: "west")), p(p4, $p_4$, label-args: (anchor: "west")), p(p5, $p_5$, label-args: (anchor: "west")), p(p6, $p_6$, label-args: (anchor: "west")), t(tp1, []), t(tp2, []), t(tp31, []), t(tp32, []), t(tp41, []), t(tp42, []), t(tp5, []), t(tp6, []), p(m1f, $m_1 = f$, tokens: 1), p(m1t, $m_1 = t$, label-args: (anchor: "south")), p(h1, $"hold" = 1$, tokens: 1), p(h2, $"hold" = 2$, label-args: (anchor: "south")), p(m2f, $m_2 = f$, tokens: 1), p(m2t, $m_2 = t$, label-args: (anchor: "south")), p(q1, $q_1$, label-args: (anchor: "east"), tokens: 1), p(q2, $q_2$, label-args: (anchor: "east")), p(q3, $q_3$, label-args: (anchor: "east")), p(q4, $q_4$, label-args: (anchor: "east")), p(q5, $q_5$, label-args: (anchor: "east")), p(q6, $q_6$, label-args: (anchor: "east")), t(tq1, []), t(tq2, []), t(tq31, []), t(tq32, []), t(tq41, []), t(tq42, []), t(tq5, []), t(tq6, []), // edge(p1, tp1), edge(p2, tp2), edge(p3, tp31), edge(p3, tp32), edge(p4, tp41), edge(p4, tp42), edge(p5, tp5), edge(p6, tp6), edge(tp1, p2), edge(tp2, p3), edge(tp31, p4), edge(tp32, p4), edge(tp41, p5), edge(tp42, p5), edge(tp5, p6), edge(tp6, p1), // edge(q1, tq1), edge(q2, tq2), edge(q3, tq31), edge(q3, tq32), edge(q4, tq41), edge(q4, tq42), edge(q5, tq5), edge(q6, tq6), edge(tq1, q2), edge(tq2, q3), edge(tq31, q4), edge(tq32, q4), edge(tq41, q5), edge(tq42, q5), edge(tq5, q6), edge(tq6, q1), // edge(m1f, tp2), edge(tp2, m1t), edge(m1t, tp5), edge(tp5, m1f), double-edge(m1f, tq41), edge(m2f, tq2), edge(tq2, m2t), edge(m2t, tq5), edge(tq5, m2f), double-edge(m2f, tp41), // edge(h1, tq32), edge(tp32, h1), double-edge(h1, tp31), double-edge(h1, tq42), // edge(h2, tp32), edge(tq32, h2), double-edge(h2, tq31), double-edge(h2, tp41), ) }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/flow-4_00.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 105pt) #block(lorem(20))
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/board-n-pieces/0.1.0/internals.typ
typst
Apache License 2.0
#import "abi.typ" #let functions = plugin("plugin.wasm") #let parse-fen = abi.function( (..args) => functions.parse_fen(..args), bytes, abi.position-from-bytes, ) /// Returns the index of a file. #let file-index(file) = file.to-unicode() - "a".to-unicode() /// Returns the index of a rank. #let rank-index(r) = int(r) - 1 /// Returns the coordinate of a square given a square name. #let square-coordinates(s) = { let (f, r) = s.clusters() (file-index(f), rank-index(r)) }
https://github.com/DieracDelta/presentations
https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/tests/pause.typ
typst
#import "../polylux.typ": * #set page(paper: "presentation-16-9") #polylux-slide[ == Text like content Hello #pause $a + b$ #pause $ integral f(x) dif x $ #pause - *item1* - _item2_ - `item3` #pause + #underline[item1] + #strike[item2] + #overline[item3] #pause / def1: abc / def2: ghi #pause #box(stroke: 2pt + aqua, inset: 2pt)[boxed!] #pause #block(stroke: 2pt + lime, inset: 2pt)[blocked!] ] #polylux-slide[ == Inside grid #grid(columns: 4 * (1fr,))[ abc #pause ][ def #pause ][ ghi #pause ][ jkl ] ] #polylux-slide[ == Visuals #pause // Fails to be hidden as of Typst 0.7.0 #path( fill: teal.lighten(50%), stroke: teal, closed: true, (0cm, 0cm), (1cm, 0cm), (1cm, 1cm) ) #rect() #square() #circle() #ellipse() // Fails to be hidden as of Typst 0.7.0 #line() // Fails to be hidden as of Typst 0.7.0 #polygon( fill: teal.lighten(50%), stroke: teal, (0cm, 0cm), (1cm, 0cm), (1cm, 1cm) ) #image("../assets/logo.png", width: 3em) ]
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/thesis/chapters/07-proposed-solution/08-conclusion.typ
typst
== Conclusion In this chapter, we proposed our solution for automated identification of microservice candidates within the context of monolith applications. We answered the following research question: #link(<research_question_3>)[*Research Question 3*]: How can static analysis of source code identify module boundaries in a modular monolith architecture that maximize internal cohesion and minimize external coupling? We proposed a solution that uses a combination of static analysis techniques to identify microservice candidates within monolith applications. Our solution uses structural information (e.g. class structure and dependencies) and evolutionary information (e.g. code changes) extracted from the codebase of the application to identify microservice candidates. We use the Louvain community detection algorithm to identify clusters of classes that are likely to be good candidates for microservices. The Louvain algorithm is computationally efficient and easy to implement, making it a good choice for identifying microservice candidates in large codebases. Finally, we primarily use the cohesion and coupling metrics to evaluate the quality of the identified microservice candidates. Secondarily, we use the size and complexity metrics to further evaluate the microservice candidate decomposition.
https://github.com/GuTaoZi/SUSTech-thesis-typst
https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/utils/style.typ
typst
MIT License
#let FSIZE = ( 初号: 42pt, 小初: 36pt, 一号: 26pt, 小一: 24pt, 二号: 22pt, 小二: 18pt, 三号: 16pt, 小三: 15pt, 四号: 14pt, 中四: 13pt, 小四: 12pt, 五号: 10.5pt, 小五: 9pt, 六号: 7.5pt, 小六: 6.5pt, 七号: 5.5pt, 小七: 5pt, ) #let FONTS = ( 宋体: ("Times New Roman", "Source Han Serif SC", "Source Han Serif", "Noto Serif CJK SC", "SimSun", "Songti SC", "STSongti"), 黑体: ("Times New Roman", "Source Han Sans SC", "Source Han Sans", "Noto Sans CJK SC", "SimHei", "Heiti SC", "STHeiti"), 楷体: ("Times New Roman", "KaiTi", "Kaiti SC", "STKaiti", "FZKai-Z03S"), TNR: ("Times New Roman"), )
https://github.com/freundTech/typst-typearea
https://raw.githubusercontent.com/freundTech/typst-typearea/main/tests/footer.query.typ
typst
MIT License
#import "../typearea.typ": * #show: typearea.with( width: 100pt, height: 100pt, div: 5, footer-include: false, footer-height: 10pt, footer-sep: 5pt, footer: context [ #layout(size => [ #metadata(here().position() + size + (align: align.alignment))<result> ]) ] ) #metadata(( page: 1, x: 20pt, y: 65pt, width: 40pt, height: 10pt, align: start + top, ))<expected>
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0005.typ
typst
#import "../helpers.typ": * #let longest-palindromic-substring-ref(s) = { let s = s.clusters() let t = () for c in s { t.push("$") t.push(c) } t.push("$") let n = t.len() let a = fill(0, n) let l = 0 let r = -1 for i in range(n) { let j = if i > r { 1 } else { calc.min(a.at(l + r - i), r - i + 1) } while i >= j and i + j < n and t.at(i - j) == t.at(i + j) { j = j + 1 } a.at(i) = j j = j - 1 if i + j > r { l = i - j r = i + j } } let ans = 0 let hi = 0 for i in range(n) { if a.at(i) > hi { ans = i hi = a.at(i) } } let ret = () for i in range(ans - hi + 1, ans + hi) { if t.at(i) != "$" { ret.push(t.at(i)) } } ret.join() }
https://github.com/k-84mo10/typst_modification
https://raw.githubusercontent.com/k-84mo10/typst_modification/main/tests/typ/layout/pagebreak-parity.typ
typst
Apache License 2.0
// Test clearing to even or odd pages. --- #set page(width: 80pt, height: 30pt) First #pagebreak(to: "odd") Third #pagebreak(to: "even") Fourth #pagebreak(to: "even") Sixth #pagebreak() Seventh #pagebreak(to: "odd") #page[Nineth] --- #set page(width: auto, height: auto) // Test with auto-sized page. First #pagebreak(to: "odd") Third
https://github.com/Coekjan/touying-buaa
https://raw.githubusercontent.com/Coekjan/touying-buaa/master/README.md
markdown
MIT License
# Touying Slide Theme for Beihang University Inspired by [Southeast University Touying Slide Theme](https://github.com/QuadnucYard/touying-theme-seu). ## Use as Typst Template Package Use `typst init @preview/touying-buaa` to create a new project with this theme. ```console $ typst init @preview/touying-buaa Successfully created new project from @preview/touying-buaa:<latest> To start writing, run: > cd touying-buaa > typst watch main.typ ``` ## Examples See [examples](examples) and [Github Pages](https://coekjan.github.io/touying-buaa) for more details. You can compile the examples by yourself. ```console $ typst compile ./examples/main.typ --root . ``` And the PDF file `./examples/main.pdf` will be generated. ## License Licensed under the [MIT License](LICENSE).
https://github.com/Champitoad/typst-slides
https://raw.githubusercontent.com/Champitoad/typst-slides/main/contribs.typ
typst
Creative Commons Zero v1.0 Universal
#new-section-slide[Contributions] #slide(title: [Textual vs. #titleWord[Graphical]])[ #set align(center) #let user = text(size: 35pt)[🙇] #let computer = text(size: 35pt)[💻] *State-of-the art:* build proofs by writing *textual* commands #centerFocus[ #uncover("2-")[ #user : #quote[Please apply _this_ rule] ] #alternatives-match(position: center + horizon, ( "3": [ #computer : "#text(fill: olive)[*✅ OK*] here is the result!" ], "4-": [ #computer : "#text(fill: red)[*❌ ERROR:*] dkfsljfjdklsfjdkfjsldjfkdlsfj" ] )) ] #uncover("5-")[ #squareFocus[ #grid( columns: (auto), align: left, inset: 8pt, [*1st contribution:* build proofs by #alert[direct manipulation] of _formulas_], [ #thus No need to _memorize_ the rules \ #thus More _straightforward_ interaction ] ) ] ] ] #slide(title: [Symbolic vs. Iconic])[ - *Symbols* are hard to: - _learn_ $=>$ purely conventional meaning - _manipulate_ $=>$ need for very precise gestures #pause - Formulas can *interact* by being _moved_ in the same #alert[space] #pause #v(1cm) #set align(center) #squareFocus[ *2nd contribution:* replace logical symbols by #alert[geometrical diagrams] ] ] // #slide(title: [Classical vs. Intuitionistic])[ // - *Classical* logic: is this statement true? // - *Intuitionistic* logic: _how_ is this statement true? // ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_09.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test parsing from svg data #image.decode(`<svg xmlns="http://www.w3.org/2000/svg" height="140" width="500"><ellipse cx="200" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2" /></svg>`.text, format: "svg")
https://github.com/Ttajika/typst_template_tajika
https://raw.githubusercontent.com/Ttajika/typst_template_tajika/main/libs/template.typ
typst
#import "useful_functions.typ": * #import "my_short_hand.typ": * #let project( title: "", abstract: none, keywords:none, JEL: none, authors: (), institutions: (), notes: (), date: Today(), body-font: ("STIX Two Text","<NAME>"), sans-font: ("STIX Two Text","<NAME>"), math-font: ("STIX Two Math","<NAME>"), leading: 1.2em, lang: "en", font-size: 12pt, margin: (left:1in, top:1in, right:1in, bottom:1in), body, ) = { // Set the document's basic properties. set document(author: authors, title: title) set page(numbering: "1", number-align: center, margin: margin) // Set body font family. set text(font: body-font, lang:lang) show heading: set text(font: sans-font) set heading(numbering: "1.1", supplement: [Section]) set footnote(numbering: "*") // Title row. align(center)[ #text(font: sans-font, weight: 700, 1.75em)[#title] ] // Author information. let author_note = authors.zip(notes) pad( top: 0.5em, bottom: 0.5em, x: 2em, grid( columns: (1fr,) * calc.min(3, authors.len()), gutter: 1em, ..author_note.map(author => align(center, [#author.at(0)#footnote[#author.at(1)]])), ..institutions.map(institutions => align(center, strong(institutions))) ), ) align(center)[#text(font: body-font, weight: 500, 1em)[#date]] // Main body. 基本設定. // footnoteの設定 set footnote(numbering: "1") counter(footnote).update(0) // paragraphの設定. indent 1em, 行送り1.2em set par(justify: true, first-line-indent: 1em, leading: leading) // fontの設定 set text(font: body-font, size:font-size) set text(cjk-latin-spacing: auto) show emph: set text(font: body-font) show strong: set text(font: sans-font) //数式フォントの設定 show math.equation: set text(font: math-font) set enum(numbering: "1.a.") show ref: it => eq_refstyle(it,lang:lang) //定理環境その他の設定 show figure: it => { let c_eq = counter_body(it) let thenumber = numbering( it.numbering, ..c_eq.at(it.location())) if it.kind in theo_list{ let name = cap_body(it.caption) my_thm_style(trans.at(lang).at(it.kind), name, thenumber, it.body) } else if it.kind in defi_list{ let name = cap_body(it.caption) my_defi_style(trans.at(lang).at(it.kind), name, thenumber, it.body) } else if it.supplement.text in others_list { align(center)[ #it.body #trans.at(lang).at(it.supplement.text) #thenumber: #cap_body(it.caption)] } else if it.kind == "Proof" { let name = cap_body(it.caption) my_proof_style(trans.at(lang).at(it.kind), name, it.numbering, it.body,lang)} else {it} } //abstractの設定 if abstract != none { align(center)[#text(1em, strong[#abstract_name.at(lang)])] block(inset: (left:12%, right:12%))[ #text(0.85em)[#par( leading: 0.5*leading)[#abstract]]]} if keywords != none{ block(width: 100%)[*Keyword:* #keywords] if JEL != none { block(width: 100%)[*JEL Classification:* #JEL] } } body }
https://github.com/timon-schelling/uni-phi111-logic-essay-2023-2024
https://raw.githubusercontent.com/timon-schelling/uni-phi111-logic-essay-2023-2024/main/src/handout.typ
typst
#let date = datetime.today().display() #set heading(numbering: "1.1") #set par(justify: true, leading: 0.4em) <NAME> #date Tutorium Einführung in die Theoretische Philosophie (4.03.1101f) WiSe 2023/24 Handout Essay Einführung in die Logik #text(2.2em, weight: 700, [ Einführung in die Logik am Beispiel politischer Argumente ]) #text(1.6em, weight: 700, [ Gliederung ]) = Einleitung - Wie kann einem die Logik helfen, politische Argumente zu bewerten? = Begriff des Arguments - Argumente - Prämissen - Ein oder mehrere Aussagesätze, aus denen die Konklusion folgt - Prämissen sind die Gründe, die für die Konklusion sprechen - Konklusion - Folgt aus den Prämissen - Die Konklusion ist die Aussage, die durch die Prämissen gestützt wird - Formale Schreibweise - Prämissen werden als $P_1$ bis $P_n$ notiert - Konklusion wird als $K$ notiert - Erstes Beispiel eines politischen Arguments (erfüllt *nicht* die Anforderungen an ein Argument) - Versuchte Rekonstruktion des Arguments - Identifikation von Prämissen - *fehlende* Konklusion - Standardform - $A$ ist ein Standardargument $arrow.l.r$ $A$ ist eine Folge von ein oder mehreren Prämissen, gefolgt vom Separator "Also" und genau einer Konklusion - Prämissen hier als $P_1$ bis $P_n$ notiert - Konklusion als $K$ notiert #pad(left: 1.2em, table(stroke: gray)[ $ & P_1 \ & dots.v \ & P_n \ & text("Also: ")K \ $ ]) = Deduktive gültige Argumente - Einführung des Begriffs der Deduktiven Gültigkeit - Ein Argument ist deduktiv gültig, wenn die Konklusion aus den Prämissen folgt - Zweites Beispiel eines politischen Arguments (deduktiv gültiges Argument) - Rekonstruktion des Arguments - Identifikation von Prämissen und Konklusion - Übersetzung in Standardform - Bewertung des Arguments - Erklärung der deduktiven Gültigkeit #pagebreak() - Einführung der Stichhaltigkeit - Ein Argument ist stichhaltig, wenn es deduktiv gültig ist und die Prämissen wahr sind - Referenz auf das zweite Beispiel - Erklärung warum das Argument aus dem zweiten Beispiel nicht Stichhaltig ist - Umformulierung des Arguments zu einem Stichhaltigen Argument, durch Änderung der Konklusion = Induktive gültige Argumente - Einführung des Begriffs der Induktiven Gültigkeit - Ein Argument ist induktiv gültig, wenn die Konklusion aus den Prämissen folgt und die Prämissen die Konklusion stützen (d.h. die Prämissen machen die Konklusion wahrscheinlicher als ihre Negation) - Drittes Beispiel eines politischen Arguments (induktiv gültiges Argument) - Rekonstruktion des Arguments - Identifikation von Prämissen und Konklusion - Übersetzung in Standardform - Bewertung des Arguments - Erklärung warum das Argument nicht Deduktiv gültig ist - Erklärung der induktiven Gültigkeit des Arguments - Anmerkung über Stärke der induktiven Gültigkeit = Ungültige Argumente durch logischen Fehlschluss (Optionale Erweiterung, wenn Platz bleibt) - Viertes Beispiel eines politischen Arguments (ungültiges Argument) - Rekonstruktion des Arguments - Identifikation von Prämissen und Konklusion - Übersetzung in Standardform - Bewertung des Arguments - Erklärung warum das Argument nicht gültig ist - Anmerkung über weitere Logische Fehlschlüsse = Fazit - Zusammenfassung der Ergebnisse mit Hilfe von Schaubild #align(left, [ #import "@preview/cetz:0.1.2": canvas, draw, tree #import draw: * #let data = ( [Argument], ([Gültig], ([Deduktiv], [Stichhaltig], [Nicht Stichhaltig]), ([Induktiv], [Stark], [Schwach])), [Ungültig] ) #figure( table(inset: -0.7em)[ #canvas(length: 1cm, { set-style(content: (padding: .5), fill: gray, stroke: gray) tree.tree(data, spread: 2.3, grow: 1.4, draw-node: (node, _) => { content((), node.content) }, draw-edge: (from, to, _) => { line((a: from, number: .6, abs: true, b: to), (a: to, number: .6, abs: true, b: from), mark: (end: ">")) }) }) ], caption: [Überblick Kategorisierung von Argumenten], supplement: [Abbildung] ) ]) = Literatur
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/babel/0.1.1/README.md
markdown
Apache License 2.0
# <img src="./assets/logo.svg" alt="The logo of Babel: an icon of the Tower of Babel in a turquoise square" width="48px" /> <span style="font-variant: small-caps; color: #239dad">Babel</span>: Redact text by replacing it with random characters in Typst [![Package on the Typst Universe](https://img.shields.io/badge/Typst_Universe-fdfdfd?logo=typst)](https://typst.app/universe/package/babel) [![Babel’s Git repository](https://img.shields.io/badge/Git_repo-fdfdfd?logo=codeberg)](https://codeberg.org/afiaith/babel) [![A precompiled PDF file of the manual](https://img.shields.io/badge/%F0%9F%93%96%20manual-.pdf-239dad?labelColor=fdfdfd)](./docs/manual.pdf) [![Licence: MIT-0](https://img.shields.io/badge/licence-MIT0-239dad?labelColor=fdfdfd)](./LICENSE) [![Codeberg release](https://img.shields.io/gitea/v/release/afiaith/babel?gitea_url=https%3A%2F%2Fcodeberg.org&labelColor=fdfdfd&color=239dad)](https://codeberg.org/afiaith/babel/releases/) [![Codeberg stars](https://img.shields.io/gitea/stars/afiaith/babel?gitea_url=https%3A%2F%2Fcodeberg.org&labelColor=fdfdfd&color=fdfdfd&logo=codeberg)](https://codeberg.org/afiaith/babel/stars) This package provides functions that replace actual text with random characters, which is useful for redacting confidential information or sharing the design and structure of an existing document without disclosing the content itself. A variety of ready-made sets of characters for replacement are available (75 in total; termed *alphabets*), representing diverse writing systems, codes, notations and symbols. Some of these are more conservative (such as emulating redaction using a wide black pen) and many are more whimsical, as demonstrated by the following example: ```typ #baffle(alphabet: "welsh")[Hello]. My #tippex[name] is #baffle(alphabet: "underscore")[Inigo Montoya]. You #baffle(alphabet: "alchemy")[killed] my #baffle(alphabet: "shavian")[father]. Prepare to #redact[die]. Using show rules strings, regular expressions and other selectors can be redacted automatically: #show "<NAME>": baffle.with(alphabet: "sitelen-pona") #show regex("[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*"): baffle.with(alphabet: "maze-3") I’m <NAME>, and my email is `<EMAIL>`. ``` ![The output of the above Typst code](./assets/example.webp) ## 📖 The manual Using <span style="font-variant: small-caps; color: #239dad">Babel</span> is quite straightforward. A [**comprehensive manual**](./docs/manual.pdf) covers: - Introductory background. - How to use the provided functions (`baffle()`, `redact()` and `tippex()`). - A list of the provided alphabets, each demonstrated by a line of random text. If the version of the precompiled manual doesn’t match the version of the package, it means no difference between the two versions is reflected in the manual. ## 🗼 The Tower of <span style="font-variant: small-caps; color: #239dad">Babel</span> A poster demonstrating the provided alphabets: [![A demonstration of the provided alphabets in the shape of the Tower of Babel](./assets/poster.webp)](./assets/poster.webp) ## 🔨 Complementary tools If you wish to share the Typst source files of your document, not just the precompiled output, a tool called [_Typst Mutilate_](https://github.com/frozolotl/typst-mutilate) might be useful for you. Unlike <span style="font-variant: small-caps; color: #239dad">Babel</span>, it is not a Typst package but an external tool, written in Rust. It replaces the content of a Typst document with random words selected from a wordlist or random characters (similarly to <span style="font-variant: small-caps; color: #239dad">Babel</span>), changing the document in place (so make sure to run it on a *copy*!). As a package for Typst, <span style="font-variant: small-caps; color: #239dad">Babel</span> cannot change your source files.
https://github.com/toihr/typst-test
https://raw.githubusercontent.com/toihr/typst-test/main/README.md
markdown
MIT License
# typst-test A repository of tests with the new typesetting language typst. # Test List - [ ] Testing if templates can be imported
https://github.com/eusebe/sorbonne-slides-typst
https://raw.githubusercontent.com/eusebe/sorbonne-slides-typst/main/sorbonne-slides.typ
typst
#import "@preview/polylux:0.3.1": * #let sorbonne-blue = rgb("#1D2769") #let sorbonne-red = rgb("#AC182E") #let sorbonne-lightblue = rgb("#52B5E5") #let sorbonne-yellow = rgb("#FFB700") #let sorbonne-text = rgb("#263068") #let primary-color = state("faculty-color", none) #let logo-white = state("logo-white", none) #let logo-color = state("logo-color", none) #let footer-title = state("footer-title", none) #let footer-author = state("footer-author", none) #let num-section = state("num-section", 0) // Subsections #let subsections-state = state("polylux-subsections", ()) #let register-subsection(name) = locate( loc => { subsections-state.update(subsections => { subsections.push((body: name, loc: loc)) subsections }) }) #let current-subsection = locate( loc => { let subsections = subsections-state.at(loc) if subsections.len() > 0 { subsections.last().body } else { [] } }) // todo : faire en sorte que toutes les sous-sections apparaissent, avec celle en cours en surbrillance (probablement avec at(label), en mettant un label à la fin de la section en cours) #let polylux-subsections-outline( enum-args: (:), padding: (3em) ) = locate( loc => { let color = primary-color.get() let cur-item = counter("cur-item") show enum: it => { cur-item.update(0) let n-children = it.children.len() let block = block if it.tight { block = block.with(spacing: 0.65em) } for (idx, child) in it.children.enumerate() { cur-item.step() block(pad(left: it.indent)[ #stack(dir: ltr, spacing: it.body-indent)[ #let txt-color = if idx == n-children - 1 { white } else { color.mix((color, 60%), (white, 40%)) } #set text(txt-color) #cur-item.display(it.numbering) ][ #let txt-color = if idx == n-children - 1 { white } else { color.mix((color, 60%), (white, 40%)) } #set text(txt-color) #child.body ] ]) } } let subsections = subsections-state.at(loc) set align(left) pad(left: 7em, right: padding, enum( ..enum-args, ..subsections.map(sub => link(sub.loc, sub.body)) )) } ) // content to string #let to-string(content) = { if content.has("text") { content.text } else if content.has("children") { content.children.map(to-string).join("") } else if content.has("body") { to-string(content.body) } else if content == [ ] { " " } } #let sorbonnesante-theme( aspect-ratio: "16-9", fontsize: 2.5em, faculty: none, body) = { let faculty-color = if faculty == "sante" { sorbonne-red } else if faculty == "sciences" { sorbonne-lightblue } else if faculty == "lettres" { sorbonne-yellow } else { sorbonne-blue } set page( paper: "presentation-" + aspect-ratio, fill: faculty-color, margin: 50pt ) set text(font: "Fira Sans", size: fontsize, fill: sorbonne-text) show math.equation: set text(font: "Fira Math") if faculty == "sante" { logo-white.update(image("logo/sorbonne-sante-white.png", width: 5em)) logo-color.update(image("logo/sorbonne-sante.png", width: 5em)) } else if faculty == "sciences" { logo-white.update(image("logo/sorbonne-sciences-white.png", width: 5em)) logo-color.update(image("logo/sorbonne-sciences.png", width: 5em)) } else if faculty == "lettres" { logo-white.update(image("logo/sorbonne-lettres-white.png", width: 5em)) logo-color.update(image("logo/sorbonne-lettres.png", width: 5em)) } else { logo-white.update(image("logo/sorbonne-univ-white.png", width: 5em)) logo-color.update(image("logo/sorbonne-univ.png", width: 5em)) } if faculty == "sante" { primary-color.update(sorbonne-red) } else if faculty == "sciences" { primary-color.update(sorbonne-lightblue) } else if faculty == "lettres" { primary-color.update(sorbonne-yellow) } else { primary-color.update(sorbonne-blue) } body } #let title-slide( title: [], subtitle: [], short-title: [], author: [], date: [], location: [] ) = { if short-title != [] { footer-title.update(short-title) } else { footer-title.update(title) } if author != [] { footer-author.update(author) } else { footer-author.update([]) } let logo = context logo-white.get() let color = context primary-color.get() set text( fill: white, size: 1em, ) //pad(x: 2em, grid( columns: auto, rows: (0.60fr, 0.40fr), row-gutter: 1em, align(horizon)[ #strong(smallcaps(title)) #parbreak() #strong(emph(text(size: .8em, subtitle))) ], align(top)[ #text(size: .8em, author) #parbreak() #text(size: .8em, location) #parbreak() #text(size: .8em, date) ] ) //) place( bottom+right, // image("logo/sorbonne-sante-white.png", width: 5em) logo ) } #let slide(title: none, subtitle: none, body) = { // set page( // margin: (left: 0em, right: 0.5em) // ) let header = { let logo = context logo-color.get() grid( columns: (5em, 1fr), logo, { show par: set block(spacing: 0em) if title != none { set align(horizon) set text(size: 1em) strong(smallcaps(title)) } else { [] } if subtitle != none { set text(size: 0.8em) strong(emph(subtitle)) } else { [] } } ) } // TODO : short-titre de la présentation, titre de la section +- titre de la sous-section, page let footer = { let short-t = context footer-title.get() let short-a = context footer-author.get() show: text.with(.4em) show: pad.with(.5em) set align(bottom) block(fill: white, height:1.2em, stroke: 0pt, inset: 0.2em, grid( columns: (0.50fr, 0.50fr), align: (left, right), short-t + [#h(2em)] + utils.current-section, //grid.vline(), current-subsection + [#h(2em)] + logic.logical-slide.display() + [/] + utils.last-slide-number )) } set page( fill: white, header: header, footer: footer, margin: (top: 3.5em, bottom: 1em, left: 0em, right: 0.5em), ) let content = { show: align.with(horizon) show: pad.with(1em) show: text.with(0.8em) body } logic.polylux-slide(content) } #let new-section-slide(name) = { // let lab = label(to-string("section" + name)) set page(margin: 2em) let content = locate( loc => { let logo = logo-white.get() place( top+left, logo ) utils.register-section(name) num-section.update(num-section.get() + 1) subsections-state.update(()) set align(center + horizon) { show par: set block(spacing: 0em) set text(size: 6em, fill: white) strong(num-section.display()) parbreak() } set text(size: 1em, fill: white) strong(smallcaps(name)) }) logic.polylux-slide(content) } #let new-subsection-slide(name) = { set page(margin: 2em) let content = locate( loc => { let logo = logo-white.get() place( top+left, logo ) register-subsection(name) set align(center + horizon) { show par: set block(spacing: 0em) set text(size: 6em, fill: white) strong(num-section.display()) parbreak() } { set text(size: 1em, fill: white) strong(smallcaps(utils.current-section)) } parbreak() { set text(size: 0.8em, fill: white) strong(emph(polylux-subsections-outline())) } }) logic.polylux-slide(content) } #let focus-slide(background: none, foreground: white, body) = { if (background != none) { set page(fill: background, margin: 2em) } { set text(fill: foreground, size: 1.2em) let content = { v(.1fr); body; v(.1fr) } // logic.polylux-slide(align(horizon, body)) logic.polylux-slide(content) } let logo = context logo-white.get() place( top+left, logo ) } #let alert = text.with(fill: sorbonne-red) #let sorbonne-outline = utils.polylux-outline(enum-args: (tight: false,))
https://github.com/jbirnick/typst-rich-counters
https://raw.githubusercontent.com/jbirnick/typst-rich-counters/main/example.typ
typst
MIT License
#import "@preview/rich-counters:0.2.1": * #set heading(numbering: "1.1") #let mycounter = rich-counter(identifier: "mycounter", inherited_levels: 1) // DOCUMENT Displaying `mycounter` here: #context (mycounter.display)() = First level heading Displaying `mycounter` here: #context (mycounter.display)() Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)() = Another first level heading Displaying `mycounter` here: #context (mycounter.display)() Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)() == Second level heading Displaying `mycounter` here: #context (mycounter.display)() Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)() = Aaand another first level heading Displaying `mycounter` here: #context (mycounter.display)() Stepping `mycounter` here. #(mycounter.step)() Displaying `mycounter` here: #context (mycounter.display)()
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS1332/Modules/ArraysAndArrayLists.typ
typst
#import "../../../template.typ": * = Arrays Arrays allow you to store data in _contiguous space in memory_ #note[ *Pros:* - Arrays are flexible in what they can store (primitives, reference types, etc) - _Constant time access_ when the index is known - Accessing when index is not known (searching) -> O(n) *Cons:* - If you run out of space you need to resize the array which is O(n) ] = ArrayLists ArrayLists are backed by arrays, and are *contiguous*, which means you cannot have null spaces between data elements. This causes us to need to shift data to fill up the null spaces after remove operations. == ArrayList Big O #theorem[ #text(fill: rgb("#1a5fd6"))[*Adding*] *Adding to Front*: *O(n)* -> need to shift elements over to make space to add *Adding to Back*: *amortized O(1)\**. There is no need to shift but its amortized because every n operations, you need to perform an O(n) operation by resizing - Amortized: when an "expensive" operation occurs infrequently so we can "average" it over the runtimes #text(fill: rgb("#1a5fd6"))[*Removing*] *Removing from the Front:* *O(n)* -> must shift elements to fill the empty space *Removing from the back: O(1)* -> simple set to null *Adding and Removing at a Given Index: O(n)* -> shift data around the index *Accessing at a given index: O(1)* -> arraylist backed by array ] == Pros and Cons #note[ *Pros* - Data elements are stored contiguously - *Dynamic Memory* - even though we resize the backing array behind the scenes, we consider ArrayLists to be dynamic ] #note[ *Cons* - Cannot store primitives - Still needs O(n) operations for resizing ]
https://github.com/typst-doc-cn/tutorial
https://raw.githubusercontent.com/typst-doc-cn/tutorial/main/src/basic/scripting-block-and-expression.typ
typst
Apache License 2.0
#import "mod.typ": * #show: book.page.with(title: "块与表达式") 纵览Typst的编译流程,其大致分为4个阶段,解析、求值、排版和导出。 // todo: 介绍Typst的多种概念 // Source Code // Value // Type // Content // todo: 简化下面的的图片 #import "../figures.typ": figure-typst-arch #align(center + horizon, figure-typst-arch()) // ,层层有缓存 为了方便排版,Typst首先使用了一个函数“解析和评估”你的代码。有趣地是,我们之前已经学过了这个函数。事实上,它就是#typst-func("eval")。 #code(```typ #repr(eval("#[一段内容]", mode: "markup")) ```) 流程图展现了编译阶段间的关系,也包含了本节「块」与「表达式」两个概念之间的关系。 - #typst-func("eval")输入:在文件解析阶段,*代码字符串*被解析成一个语法结构,即「表达式」。古人云,世界是一个巨大的表达式。作为世界的一部分,Typst文档本身也是一个巨大的表达式。事实上,它就是我们在上一章提及的「内容块」。文档的本身是一个内容块,其由一个个标记串联形成。 - #typst-func("eval")输出:在内容排版阶段,排版引擎事实不作任何计算。用TeX黑话来说,文档被“解析和评估”完了之后,就成为了一个个「材料」(material)。排版引擎将材料。 在求值阶段。「表达式」被计算成一个方便排版引擎操作的值,即「材料」。一般来说,我们所谓的表达式是诸如`1+1`的算式,而对其求值则是做算数。 #code(```typ #eval("1+1") ```) 显然,如果意图是让排版引擎输出计算结果,让排版引擎直接排版2要比排版“1+1”更简单。 但是对于整个文档,要如何理解对内容块的求值?这就引入了「可折叠」的值(Foldable)的概念。「可折叠」成为块作为表达式的基础。 #pro-tip[ Typst借鉴了Rust,遵从「面向表达式编程」(expression-oriented programming)的哲学。它将所有的语句都根据可折叠规则(见后文)设计为表达式。 + 如果一个语句能产生值,那么该语句的结果是按*控制流*顺序所产生所有值的折叠。 + 否则,如果一个语句不能产生值,那么该语句的结果是```typc none```。 + 特别地,任意类型 $T$ 的值 $v$ 与```typc none```折叠仍然是值本身。 $ forall v in T union {"none"}, op("fold")_T (v, "none") = v $ ] == 表达式 <scripting-expression> Typst中绝大部分语法结构都可作表达式,可以说学习完了所有表达式,则学会了Typst所有语法。当然,其吸取了一定历史经验,仅有少量的语句不是表达式。 #pro-tip[ `show`语句和`set`语句不是表达式。 ] 根据大的分类,可用的表达式可以分为5类(它们并非严格术语,而是为了方便教学而分类),他们是: + 代数运算表达式。 + 逻辑比较表达式。 + 逻辑运算表达式。 + 赋值表达式。 + 项。 其中第五项又是一个大类。我们上一章所学的所有常量、变量以及变量的应用都是项。块表达式也是项,将在本节后半部分详细介绍。 == 代数运算表达式 <grammar-arith-exp> Typst支持对数字的算数运算,其中浮点运算遵守IEEE-754标准。整数和浮点数之间可以混合运算: #code(```typ //加 减 乘 除 #(1 + 2, 1.0 - 2, 1 * 2, 1 / 2 + 1) ```) 从上可以看出,整数和整数运算尽可能*保持*整数,但是整数和浮点数运算则结果变为浮点数。除法运算的结果是浮点数。算数之间遵守四则运算规则。 #pro-tip[ 更高级的运算,例如数字的位运算和数值计算隐藏在类型的方法和`calc`标准库中: #code(```typ #(0o755.bit-and(0o644)), // 8进制位运算 #(calc.pow(9, 4)) // 9的4次方 ```) 请参考《》。 ] 除了数字运算,字符串、数组等还支持加法和乘法运算。它们的加法实际上是连接操作,它们的乘法则是重复元素的累加。 #code(```typ //乘 加 #("1" * 2, "4" + "5", ) \ #((1,) * 2, (4,) + (5,),) ```) 字典只支持加法操作。若有重复键值对,则右侧列表的键值对会覆盖左侧列表的键值对。 #code(```typ #((a: 1) + (b: 2), (a: 1) + (b: 3, a: 2) + (a: 4 , c: 5)) ```) == 逻辑比较表达式 <grammar-logical-cmp-exp> 有三大简单比较关系: #code(```typ //大于 小于 等于 #(1 > 2, 1 < 2, 1 == 2) ```) 基于此,可以延申出三个方便脚本编辑的比较关系。 #code(```typ //大于或等于 小于或等于 不等于 #(1 >= 2.0, 1 <= 1, 1 != 2) ```) 从数学角度,真正基本的关系另有其系,其中“小于或等于”是数学中的偏序关系,“等于”是数学中的等价关系。这两个关系可以衍生出其他四种关系,但是不太好理解。举例来讲,大于其实就是“小于等于”的否定;而小于则是“小于等于”但是不能“等于”。 注意:不推荐将整数与浮点数相互比较。具体请参考上一节所提及的浮点数陷阱。 字符串、数组和字典之间也是可以比较的,理解他们则必须从偏序关系和等价关系入手。 三种项的等价关系比较容易理解,说两字符串/数组/字典相等,则是在说二者有一样多的子项,且每个子项都一一相等。 #code(```typ #((1, 1) == (1, 1)), #((a: 1, c: (1, )) == (a: 1, c: (1, ))) ```) 字典之间没有偏序关系,便只剩字符串和数组。偏序关系则需要指定一种排序规则。如果两字符串/数组不相等,则首先考虑它们的长度关系,长度小的一方是更小的: #code(```typ #("1" <= "23"), #((1, ) <= (2, 3, )) ```) 否则从前往后依次比较每一个子项,直到找到*第一个*不相等的子项,进而确定顺序。见下三例: #code(```typ #("1" <= "2", "113" <= "121", "2" <= "12") ```) 对于单个字符,我们依照字典序比较,其中容易理解地是数字字符顺序按字面递增。对于前两者,我们可以看到`"1"`比`"2"`小;进由此,故"113"比"121"小;尽管如此,优先判断长度关系,故"2"比"12"小。 从两种基础比较关系,其他四种比较关系也能被良好地定义,并在脚本中使用: #code(```typ #("1" > "2", "1" != "2", "1" < "2", "1" >= "2") ```) == 逻辑运算表达式 <grammar-logical-calc-exp> 布尔值之间可以做“且”、“或”和“非”三种逻辑运算,并产生布尔类型的表达式: #code(```typ #(not false), #(false or false), #(true and false) ```) 真值表如下: #{ set align(center) table( columns: (33pt * 0.6,) * 2 + (33pt,) * 3, stroke: 0.5pt, $p$, $q$, $not p$, $p or q$, $p and q$, $0$, $0$, $1$, $0$, $0$, $0$, $1$, $1$, $1$, $0$, $1$, $0$, $0$, $1$, $0$, $1$, $1$, $0$, $1$, $1$, ) } 逻辑运算使用起来很简单,建议入门的同学找一些专题阅读,例如#link("https://zhuanlan.zhihu.com/p/82986019")[数理逻辑(1)——命题逻辑的基本概念]。但一旦涉及到对复杂事物的逻辑讨论,你就可能陷入了知识的海洋。关于逻辑运算已经形成一门学科,如有兴趣建议后续找一些书籍阅读,例如#link("https://www.xuetangx.com/course/THU12011001060/19316572")[逻辑学概论]。 本书自然不负责教你逻辑学。 == 赋值表达式 <grammar-assign-exp> 变量可以被赋予一个表达式的值。事实上,`let`表达式后的语法结构就是赋值表达式。 #code(```typ #let a = 1; #a, #(a = 10); #a ```) 除此之外,还有先加(减、乘或除)后赋值的变形。所有这些赋值语句都产生`none`值而非返回变量的值。 #code(```typ #let a = 1; #a, #repr(a += 2), #a, #repr(a -= 2), #a, #repr(a *= 2), #a, #repr(a /= 2), #a ```) == 代码块 <grammar-code-block> 在Typst中,代码块和内容块是等同的。与「代码块」 - 代码块:按顺序包含一系列语句,内部为#term("code mode")。 - 内容块:按顺序包含一系列内容,内部为#term("markup mode")。 内容块(标记模式)内部没有语句的概念,一个个内容或元素按顺序排列。但你可以通过#mark("#")将解释器的「解释模式」从「标记模式」*临时*改为「脚本模式」。当执行完脚本后,将脚本结果转换成内容,并放置在「井号」处。 相比,代码块内部则有语句概念。每个语句可以是换行分隔,也可以是#mark(";")分隔。 #code(```typ #{ "a" "b" } \ // 与下表达式等同: #{ "a"; "b" } ```) // 整数转浮点数:<grammar-int-to-float> // #code(```typ // #float(1), #(type(float(1))) // ```) // 布尔值转整数:<grammar-bool-to-int> // #code(```typ // #int(false), #(type(int(false))) \ // #int(true), #(type(int(true))) // ```) // 浮点数转整数:<grammar-float-to-int> // #code(```typ // #int(1), #(type(int(1))) // ```) // 数字转字符串:<grammar-num-to-str> // #code(```typ // #repr(str(1)), #(type(str(1))) // #repr(str(.5)), #(type(str(.5))) // ```) // 布尔值转字符串:<grammar-bool-to-str> // #code(```typ // #repr(false), #(type(repr(false))) // ```) // 数字转布尔值:<grammar-int-to-bool> // #code(```typ // #let to-bool(x) = x != 0 // #repr(to-bool(0)), #(type(to-bool(0))) \ // #repr(to-bool(1)), #(type(to-bool(1))) // ```) // 表达式从感性地理解上就是检验执行一段代码是否对应产生一个值。精确来说,表达式是以下对象的集合: // + 前述的各种「字面量」是表达式: // #code(```typ // // 这些是表达式 // #none, #true, #1, #.2, #"s" // ```) // + 「变量」是表达式: // #code(```typ // #let a = 1; // // 这是表达式 // #a // ```) // + 「括号表达式」(parenthesized expression)是表达式: // #code(```typ // // 这些是表达式 // #(0), #(1+2), #((((((((1)))))))) // ```) // + 「函数调用」是表达式: // #code(```typ // #let add(a, b) = a + b // #let a = 1; // // 这是表达式 // #add(a, 2) // ```) // + 特别地,Typst中的「代码块」和「内容块」是表达式: // #code(```typ // // 这些是表达式 // #repr({ 1 }), #repr([ 1 ]), // ```) // + 特别地,Typst中的「if语句」、「for语句」和「while语句」等都是表达式: // #code(```typ // // 这些是表达式 // #repr(if false [啊?]), // #repr(for _ in range(0) {}), // #repr(while false {}), // #repr(let _ = 1), // ```) // 这些将在后文中介绍。 // + 情形1至情形7的所有对象作为项,任意项之间的「运算」也是表达式。 // 其中,情形1至情形3被称为「初始表达式」(primary expression),它们就像是表达式的种子,由其他操作继续组合生成更多表达式。 // 情形4至情形6本身都是经典意义上的「语句」(statement),它们由一个或多个子表达式组成,形成一个有新含义的表达式。在Typst中它们都被赋予了「值」的语义,因此它们也都是表达式。我们将会在后续文章中继续学习。 // 本节主要讲解情形7。由于情形1至情形6都可以作为情形7的项,不失一般性,我们仍然可以仅以「字面量」作为项讲解所有情形7的情况。 == 「可折叠」的值(Foldable) 先来看代码块。代码块其实就是一个脚本。既然是脚本,Typst就可以按照语句顺序依次执行「语句」。 #pro-tip[ 准确地来说,按照控制流顺序。 ] Typst按控制流顺序执行代码,将所有结果*折叠*成一个值。所谓折叠,就是将所有数值“连接”在一起。这样讲还是太抽象了,来看一些具体的例子。 === 字符串折叠 Typst实际上不限制代码块的每个语句将会产生什么结果,只要是结果之间可以*折叠*即可。 我们说字符串是可以折叠的: #code(```typ #{"Hello"; " "; "World"} ```) 实际上折叠操作基本就是#mark("+")操作。那么字符串的折叠就是在做字符串连接操作: #code(```typ #("Hello" + " " + "World") ```) 再看一个例子: #code(```typ #{ let hello = "Hello"; let space = " "; let world = "World"; hello; space; world; let destroy = ", Destroy" destroy; space; world; "." } ```) 如何理解将「变量声明」与表达式混写? 回忆前文。对了,「变量声明」表达式的结果为```typc none```。 #code(```typ #type(let hello = "Hello") ```) 并且还有一个重点是,字符串与`none`相加是字符串本身,`none`加`none`还是`none`: #code(```typ #("Hello" + none), #(none + "Hello"), #repr(none + none) ```) 现在可以重新体会这句话了:Typst按控制流顺序执行代码,将所有结果*折叠*成一个值。对于上例,每句话的执行结果分别是: ```typc #{ none; // let hello = "Hello"; none; // let space = " "; none; // let world = "World"; "Hello"; " "; "World"; // hello; space; world; none; // let destroy = ", Destroy" ", Destroy"; " "; "Wrold"; "." // destroy; space; world; "." } ``` 将结果收集并“折叠”,得到结果: #code(```typc #(none + none + none + "Hello" + " " + "World" + none + ", Destroy" + " " + "Wrold" + ".") ```) #pro-tip[ 还有其他可以折叠的值,例如,数组与字典也是可以折叠的: #code(```typ #for i in range(1, 5) { (i, i * 10) } ```) #code(```typ #for i in range(1, 5) { let d = (:); d.insert(str(i), i * 10); d } ```) ] === 其他基本类型的情况 那么为什么说折叠操作基本就是#mark("+")操作。那么就是说有的“#mark("+")操作”并非是折叠操作。 布尔值、整数和浮点数都不能相互折叠: ```typ // 不能编译 #{ false; true }; #{ 1; 2 }; #{ 1.; 2. } ``` 那么是否说布尔值、整数和浮点数都不能折叠呢。答案又是否认的,它们都可以与```typc none```折叠(把下面的加号看成折叠操作): #code(```typ #(1 + none) ```) 所以你可以保证一个代码块中只有一个「语句」产生布尔值、整数或浮点数结果,这样的代码块就又是能编译的了。让我们利用`let _ = `来实现这一点: #code(```typ #{ let _ = 1; true }, #{ let _ = false; 2. } ```) 回忆之前所讲的特殊规则:#term("placeholder")用作标识符的作用是“忽略不必要的语句结果”。 === 内容折叠 Typst脚本的核心重点就在本段。 内容也可以作为代码块的语句结果,这时候内容块的结果是每个语句内容的“折叠”。 #code(```typ #{ [= 生活在Content树上] [现代社会以海德格尔的一句“一切实践传统都已经瓦解完了”为嚆矢。] [滥觞于家庭与社会传统的期望正失去它们的借鉴意义。] [但面对看似无垠的未来天空,我想循卡尔维诺“树上的男爵”的生活好过过早地振翮。] } ```) 是不是感觉很熟悉?实际上内容块就是上述代码块的“糖”。所谓糖就是同一事物更方便书写的语法。上述代码块与下述内容块等价: ```typ #[ = 生活在Content树上 现代社会以海德格尔的一句“一切实践传统都已经瓦解完了”为嚆矢。滥觞于家庭与社会传统的期望正失去它们的借鉴意义。但面对看似无垠的未来天空,我想循卡尔维诺“树上的男爵”的生活好过过早地振翮。 ] ``` 由于Typst默认以「标记模式」开始解释你的文档,这又与省略`#[]`的写法等价: ```typ = 生活在Content树上 现代社会以海德格尔的一句“一切实践传统都已经瓦解完了”为嚆矢。滥觞于家庭与社会传统的期望正失去它们的借鉴意义。但面对看似无垠的未来天空,我想循卡尔维诺“树上的男爵”的生活好过过早地振翮。 ``` #pro-tip[ 实际上有区别,由于多两个换行,前后各多一个Space Element。 ] // == Hello World程序 // 有的时候,我们想要访问字面量、变量与函数中存储的“信息”。例如,给定一个字符串```typc "Hello World"```,我们想要截取其中的第二个单词。 // 单词`World`就在那里,但仅凭我们有限的脚本知识,却没有方法得到它。这是因为字符串本身是一个整体,虽然它具备单词信息,我们却缺乏了*访问*信息的方法。 // Typst为我们提供了「成员」和「方法」两种概念访问这些信息。使用「方法」,可以使用以下脚本完成目标: // #code(```typ // #"Hello World".split(" ").at(1) // ```) // 为了方便讲解,我们改写出6行脚本。除了第二行,每一行都输出一段内容: // #code(```typ // #let x = "<NAME>"; #x \ // #let split = str.split // #split(x, " ") \ // #str.split(x, " ") \ // #x.split(" ") \ // #x.split(" ").at(1) // ```) // 从```typ #x.split(" ").at(1)```的输出可以看出,这一行帮助我们实现了“截取其中的第二个单词”的目标。我们虽然隐隐约约能揣测出其中的意思: // ```typ // #( x .split(" ") .at(1) ) // // 将字符串 根据字符串拆分 取出其中的第2个单词(字符串) // ``` // 但至少我们对#mark(".")仍是一无所知。 // 本节我们就来讲解Typst中较为高级的脚本语法。这些脚本语法与大部分编程语言的语法相同,但是我们假设你并不知道这些语法。 == `none`类型和`if`语句 <grammar-if> 默认情况下,在逻辑上,Typst按照顺序执行执行你的代码,即先执行前面的语句,再执行后面的语句。开发者如果想要控制程序执行的流程,就必须使用流程控制的语法结构,主要是条件执行和循环执行。 `if`语句用于条件判断,满足条件时,就执行指定的语句。 ```typ #if expression { then-block } else { else-block } #if expression { then-block } ``` 上面式子中,表达式`expression`为真(值为布尔值`true`)时,就执行`then-block`代码块,否则执行`else-block`代码块。特别地,`else`可以省略。 如下所示: #code(```typ #if (1 < 2) { "确实" } else { "啊?" } ```) 因为`1 < 2`表达式为真,所以脚本仅执行了`then-block`代码块,于是最后文档的内容为“确实”。 `if`语句还可以无限串联下去,你可以自行类比推理更长的`if`语句的语义:<grammar-if-if> ```typ #if expression { .. } else if expression { .. } else { .. } #if expression { .. } else if expression { .. } #if expression { .. } else if expression { .. } else if .. ``` 如果只写了`then`代码块,而没写`else`代码块,但偏偏表达式不为真,最终脚本会报错吗?请看: #code(```typ #repr(if (1 > 2) { "啊?" }) ```) 当`if`表达式没写`else`代码块而条件为假时,结果为`none`。“none”在中文里意思是“无”,表示“什么都没有”。同时再次强调`none`在「可折叠」的值中很重要的一个性质:`none`在折叠过程中被忽略。 见下程序,其根据数组所包含的值输出特定字符串: #code(```typ #let 查成分(成分数组) = { "是个" if "A" in 成分数组 or "C" in 成分数组 or "G" in 成分数组 { "萌萌" } if "T" in 成分数组 { "工具" } "人" } #查成分(()) \ #查成分(("A","T",)) \ ```) 由于`if`也是表达式,你可以直接将`if`作为函数体,例如fibnacci函数的递归可以非常简单: #code(```typ #let fib(n) = if n <= 1 { n } else { fib(n - 1) + fib(n - 2) } #fib(46) ```) == `while`语句 <grammar-while> // if condition {..} // if condition [..] // if condition [..] else {..} // if condition [..] else if condition {..} else [..] `while`语句用于循环结构,满足条件时,不断执行循环体。 ```typ #while expression { cont-block } ``` 上面代码中,如果表达式`expression`为真,就会执行`cont-block`代码块,然后再次判断`expression`是否为假;如果`expression`为假就跳出循环,不再执行循环体。 #code(```typ #let i = 0; #while i < 10 { (i * 2, ); i += 1 } ```) 上面代码中,循环体会执行`10`次,每次将`i`增加`1`,直到等于`10`才退出循环。 == `for`语句 <grammar-for> `for`语句也是常用的循环结构,它迭代访问某个对象的每一项。 ```typ #for X in A { cont-block } ``` 上面代码中,对于`A`的每一项,都执行`cont-block`代码块。在执行`cont-block`时,项的内容是`X`。例如以下代码做了与之前循环相同的事情: #code(```typ #for i in range(10) { (i * 2, ) } ```) 其中`range(10)`创建了一个内容为`(0, 1, 2, .., 9)`一共10个值的数组。 == 使用内容块替代代码块 所有可以使用代码块的地方都可以使用内容块作为替代。 #code(```typ #for i in range(4) [阿巴]...... ```) == 使用`for`遍历字典 与数组相同,同理所有字典也都可以使用`for`遍历。此时,在执行`cont-block`时,Typst将每个键值对以数组的形式交给你。键值对数组的第0项是键,键值对数组的第1项是对应的值。 #code(```typ #let cat = (neko-mimi: 2, "utterance": "喵喵喵", attribute: [kawaii\~]) #for i in cat { [猫猫的 #i.at(0) 是 #i.at(1)\ ] } ```) 你可以同时使用「解构赋值」让代码变得更容易阅读:<grammar-for-destruct> ```typ #let cat = (neko-mimi: 2, "utterance": "喵喵喵", attribute: [kawaii\~]) #for (特色, 这个) in cat [猫猫的 #特色 是 #这个\ ] ``` == `break`语句和`continue`语句 <grammar-break> 无论是`while`还是`for`,都可以使用`break`跳出循环,或`continue`直接进入下一次执行。 基于以下`for`循环,我们探索`break`和`continue`语句的作用。 #code(```typ #for i in range(10) { (i, ) } ```) 在第一次执行时,如果我们直接使用`break`跳出循环,但是在break之前就已经产生了一些值,那么`for`的结果是`break`前的那些值的「折叠」。 #code(```typ #for i in range(10) { (i, ); (i + 1926, ); break } ```) 特别地,如果我们直接使用`break`跳出循环,那么`for`的结果是*`none`*。 #code(```typ #for i in range(10) { break } ```) 在`break`之后的那些值将会被忽略: #code(```typ #for i in range(10) { break; (i, ); (i + 1926, ); } ```) 以下代码将收集迭代的所有结果,直到`i >= 5`: #code(```typ #for i in range(10) { if i >= 5 { break } (i, ) } ```) // #for 方位 in ("东", "南", "西", "北", "中", "间", "东北", "西北", "东南", "西南") [鱼戏莲叶#方位,] `continue`有相似的规则,便不再赘述。我们举一个例子,以下程序输出在`range(10)`中不是偶数的数字:<grammar-continue> #code(```typ #let 是偶数(i) = calc.even(i) #for i in range(10) { if 是偶数(i) { continue } (i, ) } ```) 事实上`break`语句和`continue`语句还可以在参数列表中使用,但本书非常不推荐这些写法,因此也不多做介绍: #code(```typ #let add(a, b, c) = a + b + c #while true { add(1, break, 2) } ```) == 控制函数返回值 你可以通过多种方法控制函数返回值。 === 占位符 <grammar-placeholder> 早在上节我们就学习过了占位符,这在编写函数体表达式的时候尤为有用。你可以通过占位符忽略不需要的函数返回值。 以下函数获取数组的倒数第二个元素: #code(```typ #let last-two(t) = { let _ = t.pop() t.pop() } #last-two((1, 2, 3, 4)) ```) === `return`语句 <grammar-return> 你可以通过`return`语句忽略表达式其余*所有语句*的结果,而使用`return`语句返回特定的值。 以下函数获取数组的倒数第二个元素: #code(```typ #let last-two(t) = { t.pop() return t.pop() } #last-two((1, 2, 3, 4)) ```)
https://github.com/jamesrswift/ionio-illustrate
https://raw.githubusercontent.com/jamesrswift/ionio-illustrate/main/src/extras/cetz-raw.typ
typst
MIT License
#import "@preview/cetz:0.1.2" #let _prepare(self, ctx) = { return self} #let _stroke(self, ctx) = { self.body } #let cetz-raw(body, inset: 0.3em, ) = { return (( type: "raw", body: body, plot-prepare: _prepare, plot-stroke: _stroke, ),) }
https://github.com/yhtq/Notes
https://raw.githubusercontent.com/yhtq/Notes/main/机器学习数学导引/作业/hw2.typ
typst
#import "../../template.typ": proof, note, corollary, lemma, theorem, definition, example, remark #import "../../template.typ": * #import "../main.typ": * #show: note.with( title: "作业2", author: "YHTQ", date: datetime.today().display(), logo: none, withOutlined : false, withTitle : false, ) #set page(paper: "a3") #let ltC = math.lt.tilde #let empty = "" = #empty #let yi(i) = $bx_(#i)^T sb + epsilon$ == #empty $ hb &= (X^T X)^(-1) X^T by\ &= (X^T X)^(-1) X^T autoVecNF(yi, n)\ &= (X^T X)^(-1) X^T (#autoVecNF(i => $bx_(#i)^T sb$, $n$) + #autoVecNF(i => $epsilon$, $n$))\ &= (X^T X)^(-1) X^T (#autoVecNF(i => $bx_(#i)^T$, $n$) sb + #autoVecNF(i => $epsilon$, $n$))\ &= (X^T X)^(-1) X^T (X sb + #autoVecNF(i => $epsilon$, $n$))\ &= sb + (X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$)\ $ 因此: $ E(hb) = E(sb) + E((X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$)) = sb + E((X^T X)^(-1) X^T) E#autoVecNF(i => $epsilon$, $n$) = sb $ == #empty #lemmaLinear[][ 设 $X$ 是矩阵随机变量,则 $E(tr(X)) = tr(E(X))$ ] #proof[ $ E(tr(X)) = E(sum_i X_(i i)) = sum_i E(X_(i i)) = tr(E(X)) $ ] $ E(norm(hb - sb)^2) &= E(norm((X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$))^2)\ &= 1/n E(((X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$))^T ((X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$)))\ &= 1/n E(#autoRVecNF(i => $epsilon$, $n$) X (X^T X)^(-1) (X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$))\ &= 1/n E(tr(#autoRVecNF(i => $epsilon$, $n$) X (X^T X)^(-1) (X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$)))\ &= 1/n E(tr( X (X^T X)^(-1) (X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$) #autoRVecNF(i => $epsilon$, $n$) ))\ &= 1/n tr(E( X (X^T X)^(-1) (X^T X)^(-1) X^T #autoVecNF(i => $epsilon$, $n$) #autoRVecNF(i => $epsilon$, $n$) ))\ &= 1/n tr(E( X (X^T X)^(-1) (X^T X)^(-1) X^T) E( #autoVecNF(i => $epsilon$, $n$) #autoRVecNF(i => $epsilon$, $n$) ))\ &= sigma^2 tr(E( X (X^T X)^(-1) (X^T X)^(-1) X^T))\ &= sigma^2 E(tr( X (X^T X)^(-1) (X^T X)^(-1) X^T))\ &= sigma^2 E(tr( (X^T X)^(-1) X^T X (X^T X)^(-1)))\ &= sigma^2 E(tr (X^T X)^(-1))\ &= sigma^2 tr(E (X^T X)^(-1))\ $ == #empty 注意到 $X^T$ 是 $d times n$ 矩阵,其每一列服从 $N(0, I_d)$,因此有: $ X^T (X^T)^T = X^T X tilde W_d (I, n) $ 进而: $ (X^T X)^(-1) tilde W^(-1)_d (I, n) $ 由 $n > d$ 有: $ E((X^T X)^(-1)) = 1/(n - d - 1) I\ tr(E((X^T X)^(-1))) = d/(n - d - 1) $ = #empty 由条件,方程显然有解。设 $bbeta = X^T bu + bv$,代入方程有: $ &X (X^T bu + bv) = by\ bu &= (X X^T)^(-1) (by - X bv)\ norm(bbeta)^2 &= (bu^T X + bv^T)(X^T bu + bv)\ &= bu^T X X^T bu + bu^T X bv + bv^T X^T bu + bv^T bv\ &= (by^T - bv^T X^T)(X X^T)^(-1)(by - X bv) + (by^T - bv^T X^T) (X X^T)^(-1) X bv + bv^T X^T (X X^T)^(-1) (by - X bv) + bv^T bv\ &= bv^T (I - X^T (X X^T)^(-1) X) bv + by^T (X X^T)^(-1) by $ #lemmaLinear[][ $I - X^T (X X^T)^(-1) X$ 是半正定矩阵 ] #proof[ 令 $P = X^T (X X^T)^(-1) X$,注意到: - $P^2 = P$ - $P = P^T$ 因此: $ (I - P)^2 = I - 2P + P^2 = I - P\ x^T (I - P) x = x^T (I - P)^2 x = x^T (I -P)^T (I - P) x = norm((I- P) x) >= 0 $ ] 由引理,显然上式取得最小值当且仅当 $bv = 0$,此时 $bbeta = x^T (X X^T)^(-1) by$ = == #let bb1 = $bbeta_1$ #let bb2 = $bbeta_2$ 注意到函数: $ funcDef(f, RR^d, RR, bbeta, norm(by - X bbeta)^2_2 + lambda norm(bbeta)_1^2) $ 是两个凸函数的和。假设 $bb1, bb2$ 是两个最小值点,应当有: $ f((bb1 + bb2)/2) >= (f(bb1) + f(bb2))/2 $ 结合凸性,这意味着: $ f((bb1 + bb2)/2) = (f(bb1) + f(bb2))/2 $ 而: $ norm(by - X ((bb1 + bb2)/2))^2_2 <= (norm(by - X bb1)^2_2 + norm(by - X bb2)^2_2)/2\ norm((bb1 + bb2)/2)_1 <= (norm(bb1)_1 + norm(bb2)_1)/2 $ 由等式,两者分别取等号。对前式化简: $ norm(by - X ((bb1 + bb2)/2))^2_2 &= (norm(by - X bb1)^2_2 + norm(by - X bb2)^2_2)/2\ 1/4 (bb1^T + bb2^T) X^T X (bb1 + bb2) - 1/2 (y^T (bb1 + bb2)X + X^T (bb1^T + bb2^T) y) + y^T y&= (norm(by - X bb1)^2_2 + norm(by - X bb2)^2_2)/2\ (bb1^T - bb2^T) X^T X (bb1 - bb2) &= 0\ (X(bb1 - bb2))^T X(bb1 - bb2) &= 0\ X(bb1 - bb2) &= 0\ $ 表明 $norm(by - X bb1)^2_2 = norm(by - X bb2)^2_2$,自然将有 $norm(bb1)_1 = norm(bb2)_1 $ == #let p1(y) = $norm(by -X #y)^2_2$ #let p2(y) = $norm(#y)_1$ 设 $bb1, bb2$ 分别是 $S_1(lambda), S_2(phi(lambda))$ 的解,分别证明它们是对方的解。 #lemmaLinear[][ $p1(bb1) = p1(bb2), p2(bb1) = p2(bb2)$] #proof[ 由 $S_2(phi(lambda))$ 的条件不难发现: $ p2(bb2) <= p2(bb1) $ 由 $bb2$ 是其最小值及 $p2(bb1) <= p2(bb1)$ 得: $ p1(bb2) <= p1(bb1) \ lambda p1(bb2) <= lambda p1(bb1) \ $ 两不等式相加,得: $ p1(bb2) + lambda p2(bb2) <= p1(bb1) + lambda p2(bb1) $ 然而由于 $bb1$ 是 $S_1 (lambda)$ 的最小值,应当有: $ p1(bb2) + lambda p2(bb2) >= p1(bb1) + lambda p2(bb1) $ 因此以上不等式全部取等,命题得证。 ] 由引理,结论显然。 = #empty 不难验证函数 $f(t) = 1/2(x - t)^2 + lambda^2/2 norm(t)_0$是仅有两段的分段可导函数,并且 $t -> infinity$ 时 $f(t) -> +infinity$,一定有最小值。可以得到 $f$ 的极小值点仅可能是 $0, x$,因此 $f$ 的最小值为: $ cases( f(t) = lambda^2/2 "if" f(t) <= f(0), f(0) = 1/2 x^2 "if" f(t) > f(0) ) $ 化简即得所求 = #empty #lemmaLinear[][ $k(x, y) = f(x) f(y)$ 一定是半正定函数 ] #proof[ #let fi(i) = $f(x_#i)$ 不难发现: $ (f(x_i) f(x_j))_(i j) = #autoVecNF(fi, $n$) #autoRVecNF(fi, $n$) $ 这当然是半正定矩阵 ] == #empty #let sum1 = $sum_(i j)$ $ cos(x - y) = cos x cos y + sin x sin y $ 由引理 $cos x cos y, sin x sin y$ 都半正定,因此 $cos(x - y)$ 也是半正定的 == #empty 同上 == #empty 注意到对应矩阵是柯西矩阵,其行列式为: $ det (1/(x_i + x_j)) = (product_(i > 1, j < i) (x_i - x_j)^2 )/(product_(i j) (x_i + x_j) ) >= 0 $ 同时,其主子式也有以上形式,不难看出: - 若 $i != j => x_i != x_j$,则所有顺序主子式均正,矩阵正定 - 否则,注意到 ${x | i != j => x_i != x_j}$ 在 $RR^n$ 中稠密,而半正定矩阵的极限仍然半正定,逼近即可。 == #empty $ e^(-norm(x - y)_1) = product_k e^(-abs(x_(k))) e^(-abs(y_(k))) = (product_k e^(-abs(x_(k)))) (product_k e^(-abs(y_(k)))) $ 由引理是半正定的 == #empty 注意到 $k(x, y)$ 对应矩阵就是 $k_1 (x, y), k_2 (x, y)$ 对应矩阵的 Hadamard 积,因此由 Schur product theorem 确实是半正定的。 = #empty == #empty #let px = $phi(x\;omega)$ #let pxj = $phi(x\;omega_j)$ #let pxk = $phi(x\;omega_k)$ #let py = $phi(y\;omega)$ #let pyj = $phi(y\;omega_j)$ #let pyk = $phi(y\;omega_k)$ $ E_W sqrt(E (k(x, y) - k_m (x, y))^2) &= E sqrt(E_(x, y) (E_omega (px py) - 1/m sum_j pxj pyj)^2)\ &<= sqrt(E_(x, y, W) (E_omega (px py) - 1/m sum_j pxj pyj)^2)\ &= sqrt(E_(x, y) ((E_omega (px py))^2 + E_W (1/m sum_j pxj pyj)^2 - 2 (E_omega (px py))^2))\ &= sqrt(E_(x, y) ((E_omega (px py))^2 + (sum_(j) E_W (pxj pyj)^2 + sum_(j k) (E_W (pxj pyj))(E_W (pxk pyk)) )/m^2 - 2 (E_omega (px py))^2))\ &= sqrt(E_(x, y) ( m E_omega (px py)^2 + (m^2-m)/2 (E_omega (px py))^2 )/m^2 - (E_omega (px py))^2)\ &= sqrt(E_(x, y) ( m E_omega (px py)^2 - (m^2+m)/2 (E_omega (px py))^2 )/m^2 )\ &<= sqrt(E_(x, y) ( E_omega (px py)^2 )/m )\ &= sqrt(Q / m) $ == #empty 从上一问可以得到: $ E epsilon_m (W) <= C^2/sqrt(m) $ 注意到 $epsilon_m (W)$ 事实上是 2- 范数,因此可以使用三角不等式: $ D_i epsilon_m (W) &= epsilon_m (W_1) - epsilon_m (W_2) \ &<= epsilon_m (W_1 - W_2)\ &= sqrt(E_(x, y) (1/m (phi(x\;omega_1)phi(y\;omega_1) - phi(x\;omega_2)phi(y\;omega_2)))^2)\ &<= sqrt(E_(x, y) (2 C^2/m)^2)\ &= 2 C^2/m\ $ 由 McDiarmid's inequality,有: $ P(abs(epsilon_m (W) - E epsilon_m (W)) >= t) <= 2 e^(-t^2/(2 sigma^2)) $ 其中 $sigma^2 = 1/4 sum_(i = 1)^m 4/m^2 C^4 = C^4/m$,因此: $ P(abs(epsilon_m (W) - E epsilon_m (W)) >= t) <= 2 e^(-(m t^2)/(2 C^4))\ P(epsilon_m (W) >= C^2/sqrt(m) + t) <= P(abs(epsilon_m (W) - E epsilon_m (W)) >= t) <= 2 e^(-(m t^2)/(2 C^4))\ $ 令 $2 e^(-(m t^2)/(2 C^4)) = delta$,解得: $ - (m t^2)/(2 C^4) = ln (delta/2)\ t = sqrt(2 C^4 ln (2/delta))/sqrt(m) $ 整理即得: $ P(epsilon_m (W) >= C^2/sqrt(m) (1 + 2 ln (2/delta))) <= delta $ 证毕
https://github.com/Arsenii324/matap-p2
https://raw.githubusercontent.com/Arsenii324/matap-p2/main/t-repo/lecture3.typ
typst
#import "macros.typ" : * = Лекция == Операции над числовыми рядами === Абсолютная и условная сходимость $limits(sum)_(n=1)^(infinity) a_n $: - сходится абсолютно, если сходится $limits(sum)_(n=1)^(infinity) abs(a_n)$ - сходится условно, если сходится $limits(sum)_(n=1)^(infinity) a_n$, но расходится $limits(sum)_(n=1)^(infinity) abs(a_n)$ === Перестановка без группировки *Пусть:* $limits(sum)_(n=1)^(infinity) a_n$ - сходится абсолютно. $tau : NN arrow NN$ - биекция, задает перестановку ряда. *Тогда:* $limits(sum)_(n=1)^(infinity) a_tau(n) = limits(sum)_(n=1)^(infinity) a_n$ *Proof:* Пусть $a_n >= 0$, тогда докажем, что $limits(sum)_(k=1)^(infinity) a_tau(k) = limits(sum)_(k=1)^(infinity) a_n$ $N = max(tau(1), ..., tau(n))$ $B_n = limits(sum)_(k=1)^(n) a_tau(k) <= limits(sum)_(k=1)^(N) a_k <= a ==> {B_n}$ - ограничена и не убывает $==> B_n arrow b <= a$ Применим $tau^(-1)$ и аналогичными рассуждениями получим, что $limits(sum)_(k=1)^(infinity) a_(tau^(-1) compose tau(k)) <= limits(sum)_(k=1)^(infinity) a_k = a <= b$ Отсюда $a <= b <= a => b = a => B_n -> a$ Возьмём теперь $p_k = (a_k + abs(a_k)) / 2 >= 0$, $q_k = (abs(a_k) - a_k) / 2 >= 0$. $B_n = limits(sum)_(k=1)^(n) a_tau(k) = limits(sum)_(k=1)^(n) p_tau(k) - limits(sum)_(k=1)^(n) q_tau(k)$ $limits(sum)_(k=1)^(infinity) a_tau(k) = limits(sum)_(k=1)^(infinity) p_tau(k) - limits(sum)_(k=1)^(infinity) q_tau(k)$ (т.к. ряды $p_k$ и $q_k$ сходятся) $=$ |по доказанному выше| $=$ $ limits(sum)_(k=1)^(infinity) p_(k) - limits(sum)_(k=1)^(infinity) q_(k) = limits(sum)_(k=1)^(infinity) a_(k)$ === <NAME> *Пусть:* $limits(sum)_(n=1)^(infinity) a_n$ - сходится условно. *Тогда:* 1) $forall a in RR " " exists " " tau : NN -> NN "биекция" : limits(sum)_(n=1)^(infinity) a_tau(n) = a$ 2) $exists " " tau_1, tau_2 : NN -> NN "биекция" : limits(sum)_(n=1)^(infinity) a_tau_1(n) = + infinity; limits(sum)_(n=1)^(infinity) a_tau_2(n) = - infinity$ 3) $exists " " tau : NN -> NN "биекция" : limits(sum)_(n=1)^(infinity) a_tau(n) "- расходится"$ *Proof:* $limits(sum)_(k=1)^(infinity) a_k$ $alpha_n$ - n-ый неотрицательный член,\ $beta_n$ - n-ый отрицательный член. $limits(sum)_(k=1)^(infinity) a_k$ - сходится условно $=> limits(sum)_(k=1)^(infinity) alpha_k = + infinity; limits(sum)_(k=1)^(infinity) beta_k = - infinity$ Допустим это неверно. Если оба ряда $alpha "и " beta$ сходятся. Тогда оценим $limits(sum)_(k=1)^(m) abs(a_k) <= limits(sum)_(k=1)^(m) alpha_k + limits(sum)_(k=1)^(m) abs(beta_k) <= C => limits(sum)_(k=1)^(m) a_k$ сходится абсолютно. Противоречие. Пусть ряд $alpha$ сходится, ряд $beta$ расходится. Тогда частичные суммы будут расходиться при стремлении к бесконечности. Если записать формально, то если $limits(sum)_(k=1)^(infinity) alpha_k = + infinity, limits(sum)_(k=1)^(infinity) beta_k = beta > - infinity$, то $forall E > 0 " " exists N(E) : forall m >= N(E) => limits(sum)_(k=1)^(m) alpha_k > E - beta$. Пусть M настолько велико, что в ${a_1, ..., a_M}$ лежат все ${alpha_1, ..., alpha_m}$, тогда: $limits(sum)_(k=1)^(M) a_k >= limits(sum)_(k=1)^(m) alpha_k + beta > E$ - в силу произвольности E частичные суммы не ограничены, а значит ряд $a_n$ расходится. Противоречие. 1) Пусть $a in RR$ произвольно. Будем делать следующее: Прибавляем $alpha_i$, пока сумма не будет больше $a$. Как только сумма стала больше $a$, начинаем прибавлять $beta_i$, как только сумма стала меньше $a$, снова начинаем прибавлять $alpha_i$ и так далее. Стоит оговорить три момента: 1. Мы всегда можем брать $alpha_i$, которые будут нас "поднимать", потому что их бесконечно много и $limits(sum)_(k=1)^(infinity) alpha_k = + infinity$. Аналогично с $beta_i$. 2. Почему мы действительно сойдёмся к $a$? Исходный ряд сходится условно $=> a_k arrow 0 => alpha_i -> 0; beta_i -> 0$. Тогда $forall epsilon > 0 " " exists N in NN : forall n >= N => alpha_i < epsilon/2; abs(beta_i) < epsilon/2$. В момент, когда все $alpha_i$ и $beta_i$ с номерами меньше N войдут в сумму - мы начнём отклоняться от $a$ не больше, чем на $epsilon/2$. В силу произвольности $epsilon$ ряд сходится к $a$ по Коши. #image("image.png", width: 350pt) 3. Почему ряд перестановка исходного? По построению - ряд включает в себя все члены исходного и только их. 2) Чтобы уйти в бесконечность будем брать так: Берём альфы до 1, потом одну бету, альфы до 2, потому одну бету и т.д. 3) Чтобы сумма расходилась будем набирать так, чтобы получилась последовательность вида ${1, -1, 2, -2, 3, -3 ...}$. === опр. Произведение рядов по Коши $limits(sum)_(k=1)^(infinity) a_(k)$ и $limits(sum)_(k=1)^(infinity) b_(k)$ ряда, тогда ряд $limits(sum)_(k=1)^(infinity) c_(k), "где" c_k = a_1 b_k + a_2 b_(k-1) + ... + a_k b_1$ называется произведением рядов по Коши. === Теорема Тёплица *Пусть:* $mat(t_(11); t_(21), t_(22); t_(31), t_(32), t_(33); ..., ..., ...; t_(n 1), t_(n 2), t_(n 3), ..., t_(n n); dots.v, dots.v, dots.v, , dots.v )$ a) $forall j -> limits(lim)_(i -> infinity) t_(i j) = 0$ b) $exists K : forall i -> limits(sum)_(j=1)^(i) abs(t_(i j)) <= K$ - для любой строки сумма модулей элементов меньше К. c) $limits(lim)_(i -> infinity) t_i = 1$, где $t_i = t_(i 1) + ... + t_(i i)$ *Тогда:* 1) $limits(lim)_(i -> infinity) x_i = 0 ==> limits(lim)_(i -> infinity) z_i = 0$, где $z_i = x_1 t_(i 1) + ... + x_i t_(i i)$ 2) $limits(lim)_(i -> infinity) x_i = x in RR ==> limits(lim)_(i -> infinity) z_i = x$, где $z_i = x_1 t_(i 1) + ... + x_i t_(i i)$ === Теорема Коши о суммировании по Чезаро Для любых $x_i in RR, i in NN$ выполнено: $limits(lim)_(i -> infinity) x_i = x ==> limits(lim)_(i -> infinity) z_i = x$, где $z_i = (x_1 + x_2 + ... + x_i)/ i$. *Proof:* Положим $t_(i 1) = t_(i 2) = ... = t_(i i) = 1/i " " forall i in NN$ Данные $t_(i j)$ удовлетворяют всем пунктам теоремы Тёплица $=>$ наше утверждение следует из 2 пункта теоремы. _#underline[Лемма 1]_ $cases(limits(lim)_(i -> infinity) x_i = 0, limits(lim)_(i -> infinity) y_i = 0, limits(sum)^infinity y_i "- сх. абс.") => limits(lim)_(i -> infinity) z_i = 0$, где $z_i = x_1 y_i + ... + x_i y_1$ _#underline[Лемма 2]_ $cases(limits(lim)_(i -> infinity) x_i = x in RR, limits(lim)_(i -> infinity) y_i = y in RR) => limits(lim)_(i -> infinity) z_i = x y$, где $z_i = (x_1 y_i + ... + x_i y_1) / i$ === <NAME> *Пусть:* a) $limits(sum)_(k=1)^(infinity) a_k = a in RR$, $" "limits(sum)_(k=1)^(infinity) b_k = b in RR$ b) Хотя бы один сходится абсолютно *Тогда:* $limits(sum)_(k=1)^(infinity) c_k = a b, " " c_k = a_1 b_k + ... + a_k b_1$ *Proof:* Пусть ряд $a_k$ сходится абсолютно без потери общности. $C_n = a_1 B_n + ... + a_n B_1$, где $C_n = limits(sum)_(k=1)^(n) c_k, " " B_n = limits(sum)_(k=1)^(n) b_k$. Положим также $beta_n = limits(sum)_(k=n + 1)^(infinity) beta_k$. $C_n = a_1 (b - beta_n) + a_2 (b - beta_(n-1)) + ... + a_n (b - beta_1)$, т.к. $B_n + beta_n = limits(sum)_(k = 1)^infinity b_k = b$ $C_n = b(a_1 + ... + a_n) - (a_1 beta_n + ... + a_n beta_1)$ Положим $x_i = beta_i$ и $y_i = a_i$ Тогда: + $limits(lim)_(i -> infinity) x_i = 0$, т.к. $x_i = beta_i = b - B_i = b - b = 0$ + $limits(lim)_(i -> infinity) y_i = 0$, необходимый признак сходимости + $forall i limits(sum)_(j = 1)^i abs(y_j) <= K = limits(sum)_(j=1)^infinity abs(a_j)$ - K существует, т.к. мы предположили, что ряд $a_i$ сходится абсолютно. Тогда по лемме 1 имеем $a_1 beta_n + ... + a_n beta_1 -> 0$ при $n -> infinity$. Соответственно, $limits(lim)_(n arrow infinity) C_n = b underbrace((a_1 + ... + a_n), -> a) - underbrace((a_1 beta_n + ... + a_n beta_1), -> 0) = a b - 0 = a b$. === Т<NAME> *Пусть:* a) $limits(sum)_(k=1)^(infinity) a_k = a$ b) $limits(sum)_(k=1)^(infinity) b_k = b$ c) $limits(sum)_(k=1)^(infinity) c_k = c$, где $c_k = a_1 b_k + ... + a_k b_1 $ *Тогда:* $c = a b$ *Proof:* Положим $A_n = sumin a_i$, $B_n = sumin b_i$, $C_n = sumin c_i$. Несложно заметить и проверить, что $C_1 + ... + C_n = A_1 B_n + ... + A_n B_1$ Т.к. $liminf A_n = a$, $liminf B_n = b$ при $x_i = A_i$, $y_i = B_i$ по лемме 2 имеем: $(C_1 + ... + C_n) / n = (A_1 B_n + ... + A_n B_1) / n -> a b$ при $n -> infinity$ С другой стороны, $liminf C_n = c$, поэтому в силу теоремы Коши имеем $(C_1 + ... + C_n) / n -> c$, при $n -> infinity$. Из полученных выше равенств заключаем $c = a b$. _#underline[Замечание]_ Пусть есть два числовых ряда $sumii a_i$ и $sumii b_i$. Как можно определить их произведение: $(sumii a_i) dot (sumii b_i) = " "?$ Такое произведение можно определить как сумму ряда $sumii c_i$, где каждый элемент $a_i b_j$ встречается ровно один раз. Но в каком порядке брать эти слагаемые? Как только мы фиксируем какой-либо порядок мы получаем умножение рядов, однако несложно заметить, что таких порядков столько же, сколько биекций $NN -> NN^2$, т.е. несчетное количество. Следующая теорема Абеля показывает, что если ряды сходятся абсолютно, то порядок не важен. === Теорема Абеля об умножении абсолютно сходящихся рядов *Пусть:* a) Ряды $sumii a_i$ и $sumii b_i$ сходятся аболютно. b) $i arrow.bar (m_i, n_i)$ - биекция $NN -> NN^2$. c) $sumii a_i = a$, $sumii b_i = b$ *Тогда:* $sumii a_(m_i) dot b_(n_i) = a b$ *Proof:* $limits(sum)_(i = 1)^N abs(a_(m_i) b_(n_i)) <= (limits(sum)_(i = 1)^K abs(a_i)) dot (limits(sum)_(i = 1)^K abs(b_i))$, где $K = max{m_1, m_2, ..., m_N, n_1, n_2, ..., n_N}$ т.к. любое слагаемое левой суммы присутствует в правой сумме и все слагаемые правой суммы неотрицательны. $limits(sum)_(i = 1)^N abs(a_(m_i) b_(n_i)) <= (limits(sum)_(i = 1)^K abs(a_i)) dot (limits(sum)_(i = 1)^K abs(b_i)) <= hat(a) hat(b) in RR$, где $hat(a) = limits(sum)_(i = 1)^infinity abs(a_i)$, $hat(b) = limits(sum)_(i = 1)^infinity abs(b_i) ==> limits(sum)_(i = 1)^N abs(a_(m_i) b_(n_i))$ сходится абсолютно. В силу теоремы о перестановке членов ряда сходящегося абсолютно перестановка на сумму не влияет. Переставим члены ряда следующим образом: #image("image2.png", width: 300pt) На $i$ диагонали лежат $c_i$. Сгруппируем члены по диагонялям. Легко увидеть, что получившийся после группировки ряд - это произведение рядов $sumii a_i$ и $sumii b_i$ по Коши. Т.к. ряд сходился до группировки, то сходится и после, причем к тому же числу. Т.к. сходятся ряды $sumii a_i$ и $sumii b_i$, а также сходится полученный ряд, то по т. Абеля сумма ряда равна $a b$, что и требовалось доказать.
https://github.com/mattyoung101/musicvis3d
https://raw.githubusercontent.com/mattyoung101/musicvis3d/master/paper/major.typ
typst
ISC License
// Colour links blue like LaTeX #show cite: set text(fill: blue) #show link: set text(fill: blue) #show ref: set text(fill: blue) #show footnote: set text(fill: blue) #set list(indent: 12pt) #set heading(numbering: "1.") #set math.equation(numbering: "(1)") #set page(numbering: "1") #align(center, text(18pt)[ *A 3D music visualisation in OpenGL using the Discrete Fourier Transform* ]) #align(center, text(12pt)[ <NAME> 46972495 <EMAIL> May 2024 ]) #set par(justify: true) #align(center)[ *Abstract* Constructing computer graphics from music has important implications in the field of live entertainment. The Discrete Fourier Transform (DFT), often computed via the Fast Fourier Transform (FFT), is the typical method to convert time domain audio signals to a frequency domain spectrum. With this spectral data comes an almost unlimited number of ways to interpret it and construct a visualisation. In this paper, I investigate applying the DFT to construct a semi real-time audio visualisation using OpenGL. The visualisation consists of offline spectral data that is rendered in real-time in the form of 3D bars. A multitude of graphics techniques are used, including: quaternion camera animation, camera shake using Simplex noise under fractal Brownian motion, a skybox, and a post-processing stage that implements chromatic aberration. The application is written in a mix of C++ and Python. ] // Create a scope for this style: https://typst.app/docs/reference/styling/ #[ // https://typst.app/docs/reference/model/outline/#definitions-entry #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } #outline( // https://www.reddit.com/r/typst/comments/1bp8zty/how_to_make_dots_in_outline_spaced_the_same_for/ fill: box(width: 1fr, repeat(h(5pt) + "." + h(5pt))) + h(8pt), indent: auto ) ] #outline( title: [List of Figures], fill: box(width: 1fr, repeat(h(5pt) + "." + h(5pt))) + h(8pt), target: figure, ) #pagebreak() = Introduction A _music visualiser_ is a computer program that takes as input an audio signal, typically music, and produces as output a graphical visualisation. Technically, this can be an entirely offline process, but most often music visualisers run in real-time. Music visualisers have an important role in the live entertainment scene @mccarthy2022live, particularly for Electronic Dance Music (EDM). In fact, music visualisers have a long and storied history in both the EDM scene and hacker culture in general. With an almost infinite number of ways to interpret an audio signal, music visualisation is an eclectic mix of art and engineering, which makes it a very interesting field to research. Additionally, with its presence in live entertainment, the right music visualiser can really draw audiences in to the music, and create very memorable experiences. // One of the first groups to pioneer the use of real-time computer graphics to visualise music was the // _demoscene_. The demoscene originated from a group of talented programmers who produced _warez_ - cracked // video games and programs. Each _warez_ group would prepend an _intro_ to their cracked game to show off their // skills. Over time, certain groups came to focus on just producing these intros, rather than cracking games. // This pivotal moved enabled programmers working on formerly illegal cracking tools to instead focus on legal // computer graphics programming. Many demoscene intros pushed forward the state of the art, and demoscene // programmers are consistently regarded as some of the most talented in the computer graphics industry. Almost // all demoscene productions feature background music (often synthesised in real-time by the program!) and a // suite of advanced computer graphics, which are usually synced to the audio. Some of these demoscene // productions served as a great inspiration to me in selecting this project. The particular music visualiser I aim to construct is an improved version of the "spectrum of bars" once used by Canadian record label Monstercat, shown in @fig:monstercat. The label has since transitioned away from this computational music visualiser, and instead use custom music videos. #figure( image("img/monstercat.png", width: 80%), caption: [ Visualisation of the song "Pure Sunlight" @youtubeElectronicFijiWiji ] ) <fig:monstercat> The visualisation in @fig:monstercat is a common type of visualisation that visualises the audio spectrum - it shows the magnitudes of the varying frequencies that make up the song. This spectral data can be interpreted in a number of ways, for example, the MilkDrop @milkdrop software includes visualisations that encode this in a number of complex ways. However, for our use case, bars are visually appealing and an intuitive approach to visualising the music - an almost direct presentation of the data, but still with captivating enough visuals. Compared to a more advanced single-song visualiser (e.g. a demoscene production), the "spectrum of bars" has the advantage of producing reasonable output for _any_ given input song. Although, whether such output is _visually appealing_ for every song is another question. The features from the 2D spectrum in @fig:monstercat that I'd like to preserve include the rough number of bars, the space theme, and the movement of the background based on the intensity of the song. New features I plan to add include making it 3D, having a dynamic orbiting camera that flies around in 3D, as well as some more "video-game" style effects such as post-processing and screen shake to demonstrate the intensity of the song at certain points. // Compared to demoscene productions, which design cutting-edge procedural computer graphics from scratch to // target one song in particular (often composed by the scene group themselves), this "spectrum of bars" type of // visualiser is more generic in that it will produce reasonable output for _any_ song (although whether said // output looks visually appealing or not is another question). It's also easier to construct from scratch // without an engine, which is the goal of this project. = Architecture overview == Overall description of sub-applications The visualiser itself is developed and tested in a Linux environment, and is split into two sub-applications: the visualiser itself (written in C++20), and the analysis script (written in Python). Signal processing is a very complex subject, and real-time ("online") signal processing in C++ is even more so. Python generally has simpler tools to address signal processing problems, such as NumPy and SciPy, so the signal processing part was moved offline into a Python script. This is shown in @fig:block: #figure( image("img/diagram.drawio.svg", width: 60%), caption: [Block diagram of music visualisation application] ) <fig:block> The analysis script is first run that reads a FLAC @xiphFLACWhat audio file, and produces a Cap'n Proto @capnp encoded binary file containing the necessary data to render a spectrum for the chosen song. Each song consists of a directory containing one audio file, `audio.flac`, and one spectral data file, `spectrum.bin`. These are stored in the `data` directory. For example: `data/songs/LauraBrehm_PureSunlight/{audio.flac},{spectrum.bin}`. Free Lossless Audio Codec (FLAC) @xiphFLACWhat is a lossless audio compression and container format. It was mainly selected due to its ability to be easy loaded in C++ through open-source libraries like `dr_flac`, the fact that it's entirely royalty and patent free, as well as its lossless nature. Although codecs such as MPEG-3 and Vorbis are transparent at around 320 Kbps (meaning there are no perceptible differences between the compressed codec and uncompressed audio), there may still be subtle artefacts introduced in the spectrum that could be picked up by the visualiser. In any case, storing the audio in an uncompressed format introduces very little overhead and can always be transcoded later down the track if marginally smaller file size is desired. Cap'n Proto @capnp is a binary serialisation format that is regarded as a faster successor to Protocol Buffers. Compared to Protocol Buffers, which are also a widely used binary serialisation format, Cap'n Proto has the added benefit of requiring zero decode time and supporting very fast in-memory access. This is perfect for the spectral data, which needs to be written once by the Python code, and re-read continuously by the C++ rendering code. Some of this reading takes place in the audio callback, which could be regarded as a soft real-time function, and hence requiring very minimal overhead. The FLAC file for a typical song weighs in at around 10 MB, and the spectral data is only around 200 KiB thanks to Cap'n Proto's packed stream writing feature. Due to its speed, Cap'n P has to make some trade-offs in regards to message size vs. speed, usually preferring larger messages. Since I'm checking the data directory into the Git version control system, I used packed message writing to prefer smaller messages with an ever so slightly longer decode time. == Visualiser The visualiser is what we see on the screen, the real-time rendering system that displays the bars, once the spectral data has been computed. It is written in C++20, uses the OpenGL graphics API, and is built using industry standard tools CMake, Ninja and the Clang compiler. The Clang-Tidy and Clang-Format tools are used to ensure high quality code. This code runs "online", meaning it runs in real-time and we would ideally like to spend no longer than 16 ms per frame (for 60 FPS). It uses a number of open-source libraries: - *SDL2*: Platform window management, keyboard/mouse inputs, OpenGL context creation - *glad*: For OpenGL function loading and feature queries - *glm*: The OpenGL maths library, used for computing transforms and its matrix/vector types - *Cap'n Proto*: An extremely fast data serialisation format, used to transport data between Python and C++. - *dr_flac*: A fast single-file FLAC decoder. - *stb_image*: An image file decoder for many file formats. == Analysis script The analysis script is written in Python, and computes the spectral data used by the visualiser to display the bars. It computes this data "offline", meaning it does not run in real-time, unlike the C++ code. It also uses a relatively standard setup of Python libraries, with some additions due to the audio work involved: - *NumPy*: Numerical computing library. - *SciPy*: Scientific computing library. - *spectrum.py*: Used to compute the periodogram. - *Cap'n Proto*: Data inter-change format, see above. - *audiofile.py*: For loading the FLAC file. - *Matplotlib*: For graphing the waveform, debugging = Signal processing The overarching goal of the signal processing is to turn a time-domain audio signal into a frequency domain spectrogram, similar to the Monstercat visualiser shown in @fig:monstercat. This turns out to actually be quite an involved process, so this section will essentially a whirlwind tour of audio signal processing! == Background: Computer audio A raw audio signal consists of a number of digital _samples_ that are sent through an audio system at a particular _sampling frequency_, typically 44.1 KHz. #footnote[The exact reasons why are out of scope for this paper, but it has to do with the Nyquist-Shannon theorem and history with CDs.] Most audio is stereo, and hence there are typically two channels (although cinemas, for example, may use many more channels). Eventually making its way out of userspace and into the kernel, these samples are converted into an analogue signal using a Digital-to-Analogue (DAC) converter, which is typically located on most PC motherboards or as a separate peripheral. The samples cause the speaker _driver_ (the membrane, usually driven by magnets) to vibrate, which creates the sensation of sound. A typical digital audio signal is shown in @fig:audiosignal. #figure( image("img/audiosignal.png", width: 80%), caption: [ An audio signal loaded in Audacity. Top is zoomed out, bottom is zoomed in showing samples. ] ) <fig:audiosignal> == Fourier transforms, DFT and FFT In order to build the visualiser, we will need to convert this time-domain collection of samples into a frequency-domain spectrogram. We can achieve this through the Fourier transform technique. The history of the Fourier transform dates back to 1822 when mathematician <NAME> understood that any function could be represented as a sum of sines @wolframFourierSeries. From that theory, the Fourier transform was developed. The core equation for the Fourier transform is given by @wolframFourierTransform: // These equations converted using: https://github.com/mitex-rs/mitex (https://mitex-rs.github.io/mitex/) //$$\widehat{f}(\xi) = \int_{-\infty}^{\infty} f(x)\ e^{-i 2\pi \xi x}\,dx.$$ #align(center)[ $ display(hat(f )\(xi \) = integral _(- oo )^(oo ) f \(x \)thick e ^(- i 2 pi xi x )thin d x .) $ ] In simplistic terms, the Fourier transform converts a time-domain signal, where the $x$ axis is time and the $y$ axis is magnitude, into the frequency-domain, where the $x$ axis is frequency and the $y$ axis is the magnitude of that particular frequency. A diagram of this transform is shown in @fig:ftdiagram: #figure( image("img/fouriertransform.png", width: 50%), caption: [ Diagram showing the time-domain to frequency-domain conversion of the Fourier transform @fourierImage ] ) <fig:ftdiagram> From the Fourier transform comes the concept of the Discrete Fourier Transform (DFT). The equation for the DFT is similar, but slightly different to, the equation for the regular continuous Fourier transform: //$$X_k = \sum_{n=0}^{N-1} x_n \cdot e^{-i2\pi \tfrac{k}{N}n}$$ #align(center)[ $ display(X _(k ) = sum _(n = 0 )^(N - 1 ) x _(n ) dot.c e ^(- i 2 pi t frac(k ,N )n )) $ ] The DFT itself has many applications outside of audio analysis. A close cousin of the DFT, the Discrete Cosine Transform (DCT), is used in many image compression algorithms, for example. Computing the DFT naively has a time complexity of $O(n^2)$ @Rajaby2022 , which is typically considered unfavourable in CS. This led to what has been described as "the most important numerical algorithm of our lifetime" @Strang1994: the Fast Fourier Transform (FFT). The modern FFT was invented by <NAME> and <NAME> in 1965 @Cooley1965AnAF, although <NAME> had earlier work of a similar nature from 1805 @Heideman1985. This algorithm reduces the complexity to $O(n log n)$, which is much more palatable. It's also important to note here that evaluating the general DFT operates on complex numbers, and its result is also complex. However, since we are using a real-valued audio signal, we can instead make use of specialised variants of the FFT that use purely real signals @Sorensen1987. The complex output is then just converted to its magnitude, e.g. given $z = x + y i$ we take $r = sqrt(x^2 + y^2)$ == Decoding and chunking audio In order for the Fourier transform to be possible, a _chunk_ of audio needs to be processed. In other words, we can't just process individual samples since we're doing a time-domain to frequency-domain transform. After decoding the FLAC audio using the `audiofile` library, the audio samples are then split into chunks/blocks of 1024 samples using NumPy. Additionally, the stereo signal is transformed into a mono signal by averaging the left/right channels, since multi-channel FFTs are much more complicated. This is all just a few lines of Python: ```python # load audio signal, sampling_rate = audiofile.read(song_path, always_2d=True) # assume a stereo signal, let's mix it down to mono mono = np.mean(signal, axis=0) # split signal into chunks of BLOCK_SIZE blocks = np.split(mono, range(BLOCK_SIZE, len(mono), BLOCK_SIZE)) ``` == Power spectrum and periodogram From the DFT, a power spectrum - otherwise known as "power spectral density" (PSD) - can be computed. The power spectrum "describes how a signal's power is distributed in frequency" @Youngworth2005. Consider a signal $U_T(t)$, whose Fourier transform is given by $|U_T(V)|^2$. The power spectrum can be computed as follows, using the definition in @Youngworth2005: #align(center)[ $ display("PS" \(V \) = frac(| U _(T )\(V \)| ^(2 ),N ^(2 ))) $ ] Where $N$ is the total number of sample points. Then, the power spectral density can then be simply computed as: #align(center)[ $ display( "PSD"(V) = frac("PS"(V), Delta v) ) $ ] Where $Delta v$ is the space between data points in frequency space (so, the sampling rate). Critically, the result of this equation is in the units of amplitude squared per frequency unit - which is unwieldy and not particularly useful for our type of audio analysis. Instead, it would be better if we converted it into dBFS ("Decibels relative to full scale"). This is a unit where 0.0 dBFS is the loudest possible sound a system can emit, and it decreases negatively from there. For example, -10 dBFS is 10 dB quieter than the maximum possible sound a system can emit. The conversion from PSD to dBFS can be achieved as follows, given our signal $U_T(t)$: #align(center)[ $ display("dbFS"_T(t) = sum_t log_10 ("PSD"(t)) / (max "PSD")) $ ] Implementing the above in Python, this produces the plot in @fig:psd: #figure( image("img/psd.png", width: 80%), caption: [ Power spectral density (PSD) in dbFS of a block of audio ] ) <fig:psd> Also to note here is that we compute a metric known as _spectral energy_, which is a measure of the "excitement" of the audio. It's computed as the magnitude squared of the FFT: #align(center)[ $ display(S_E = sum_(i=0)^k "PSD"(i)^2) $ <math:spectralEnergy> ] == Binning spectral data Now that we have spectral data for each block of audio, we need to process it into "bins", or blocks, and use that to construct the bars. Given we know the number of bars we want (by default, 32), we can simply sample this using NumPy: ```python samples = np.linspace(FREQ_MIN, FREQ_MAX, NUM_BARS) ``` Where `FREQ_MIN` and `FREQ_MAX` refer to the human hearing range, 20 Hz to 20 KHz, respectively. Then, we simply walk through the linear space considering our current and previous value, and compute the mean amplitude inside this block. There is some additional code that maps this value, in dbFS, to a `uint8_t` bar height from 0 to 255, for Cap'n Proto serialisation. Once this is computed, the data is serialised and can be loaded in C++ - and the signal processing is complete. = Computer graphics == Render pipeline and states overview The visualiser uses a fairly standard, simple, forward rendering pipeline based on OpenGL 3.0. The exact rendering pipeline depends on which one of the two states the application may be in. The application is divided in two two states: "intro" state, and "running" state. In the intro state, a fullscreen textured quad displays three introduction slides which display the project name, my name, and the song name #footnote[At this time, the song name is hardcoded and has to be manually changed when the song is changed]. The image in @fig:intro shows the construction of the intro slides, which are static images designed in Inkscape and exported to PNGs. #figure( image("img/intro.png", width: 100%), caption: [ Construction of intro slide images in Inkscape ] ) <fig:intro> Once the intro is completed, the application transitions into "running" mode, which performs the actual visualisation. This mode first binds a framebuffer. Then, it draws the bars using a GLSL shader, then the skybox as a cubemap, and finally draws the framebuffer using a special fragment shader to provide some post-processing effects. The diagram in @fig:renderpipe shows the rendering pipeline: #figure( image("img/renderpipe.drawio.svg", width: 75%), caption: [ Diagram of graphics render pipeline ] ) <fig:renderpipe> == Initialisation SDL and glad are used to initialise the system platform. SDL is used to create the window, manage the audio context, and load the GL driver. glad is the OpenGL loader which provides the function and constant definitions from the OpenGL specification. At startup, the application is passed the path to the data directory and the name of the song to display. Once platform initialisation is complete, the FLAC audio is decoded using the dr_flac library, and the Cap'n Proto spectrum data is decoded using the C++ Cap'n Proto library. This is stored in the `cosc::SongData` class, which also handles mixing the audio into the SDL audio stream using `cosc::SongData::mixAudio`. The `mixAudio` routine also handles resampling using the SDL `AudioStream` API. One particularly important note to make regarding platform initialisation is the audio stream. For a music visualisation application, it's important that the on-screen graphics are precisely synchronised to the audio being played. This means that a low-latency audio stream is required, or in other words, an audio stream where the number of samples submitted to the audio driver per callback is less than or equal to the spectral data block size. I achieve this by using SDL's new audio APIs, which allow resampling based on the platform audio driver's selection of what it believes is the best format. In the code, we request a particular low sampling rate using `SDL_AudioSpec`, but allow SDL to change the actual underlying datatype if it desires. For example, while dr_flac uses signed 32-bit ints, SDL may prefer to resample to floats on some audio drivers. == Transforming, rendering and lighting bars Each frame, we query the `cosc::SongData` to figure out which spectrum block we are currently playing, and use that to query the heights of all the bars from the decoded Cap'n Proto document. The heights are a `uint8_t`, so range from 0 to 255 inclusive. These are remapped to a float based on a configurable minimum and maximum height. The spectrum itself simply consists of $N$ unit cubes. The cubes are transformed by means of a transformation matrix, exactly as was done in the previous Graphics Minor Project. #footnote[The only difference is that transformations are computed using glm, rather than manually.] The height of the bars is simply determined by their scale on the Y axis. This is summarised in the following code snippet: ```cpp size_t barIdx = 0; for (auto &bar : barModels) { // first, get bar height from 0-255 directly from the Cap'n Proto auto barHeight = block[barIdx]; // map that 0 to 255 to BAR_MIN_HEIGHT to BAR_MAX_HEIGHT auto scale = cosc::util::mapRange(0., 255., BAR_MIN_HEIGHT, BAR_MAX_HEIGHT, barHeight); // apply scale, also applying our baseline BAR_SCALING factor! bar.scale.y = scale * BAR_SCALING; barIdx++; // now update transforms, and off to the GPU we go! bar.applyTransform(); bar.draw(barShader); } ``` The bar shader is almost identical to the shader used in the Graphics Minor Project. This shader has a lot in common with a simple Phong @Phong1975IlluminationFC specular model, and was was based on the Phong specular calculations from LearnOpenGL @learnOpenGLLighting. The main work is this small block of GLSL: ```glsl // compute angle of this fragment's normal against the camera vec3 norm = normalize(Normal); vec3 viewDir = normalize(viewPos - FragPos); float angle = max(dot(norm, viewDir), 0.0); ``` For the vertex that this fragment is attached to, we normalise its normal vector (i.e., we compute the unit vector from the given normal vector). The `viewPos` uniform refers to the camera's current xyz position, and the `FragPos` uniform refers to the world-space transformed fragment coordinates that we computed in the vertex shader - all based on the model transform matrix. Finally, we're able to compute the angle between these two vectors by taking the dot product, and clamping it to be above 0.0 using `max`. Now that we have a single float describing the angle between the camera and the model, we need to transform that into an RGB value for coloured shading. This can be achieved using a colour map, in this case, "Inferno" from Matplotlib. I also tried the rainbow colourmap "Turbo", but Inferno works the best for this application because it shows the angle in a intuitive and visually appealing manner. I used a polynomial approximation from @infernoGLSL, instead of the usual 256-element lookup table, which works better for fragment shaders. The final composite is very simple: the fragment colour is just set to the RGB value that Inferno returned: ```glsl FragColor = vec4(inferno(angle), 1.0f); ``` The images in @fig:lighting1 and @fig:lighting2 show the Phong shading. Notice the "hotspot" visible on the central bar in @fig:lighting2, which is a classic artefact of Phong shading methods. #figure( image("img/lighting_full.jpg", width: 65%), caption: [ First image demonstrating Phong shading ] ) <fig:lighting1> #figure( image("img/lighting2_full.jpg", width: 65%), caption: [ Second image demonstrating Phong shading ] ) <fig:lighting2> == Computing camera animations One of the goals I had in mind for the visualiser was automated and smooth camera animations, that would also be quick to describe in code. However, in order to achieve this, the camera class from the Graphics Minor Project, which was based on code from LearnOpenGL, would need to be rewritten. There was also the need for a bug-free "freecam" mode, #footnote[The LearnOpenGL camera had certain bugs regarding mouse rotation in freecam mode.] which can be moved around using the normal WASD and mouse controls. This is necessary for me to find the begin and end points for each animation and for debugging. The new camera is based on a slightly modified version of the perspective camera from the Cinder project @cinderCamera, which is a C++ creative coding framework. The main difference compared to the previous LearnOpenGL camera, is that the new camera represents its pose as just a 3D vector and quaternion, rather than a set of vectors. This means that the pose of the camera can be described much more easily, and can also be interpolated to create animations. Other than that, it still outputs the same perspective and view matrices, has an FOV and uses a perspective projection. Modifications to the upstream Cinder project camera include a small refactor, removal of unnecessary code for this project such as pick ray projection, and the addition of the freecam controller. To implement camera moves, I chose to represent any given move as a begin pose, end pose, and a duration. This is encoded in the `cosc::CameraAnimation` class. Then, in turn, a `cosc::CameraAnimationManager` is attached to the `cosc::Camera`, which enables it to animate the camera every frame. // TODO do we really wanna show all this code? ```cpp /// The pose of a camera, with its position and orientation. class CameraPose { public: glm::vec3 pos; glm::quat orientation; ... }; /// A camera animation class CameraAnimation { public: /// Beginning camera pose CameraPose begin; /// Ending camera pose CameraPose end; // Duration of the animation in seconds float duration; ... }; /// Manages a camera with a set of animations. class CameraAnimationManager { public: explicit CameraAnimationManager(Camera &camera) : camera(camera) {}; void update(float delta, float spectralEnergyRatio); void addAnimations(const std::vector<CameraAnimation> &animation) { ... } ... }; ``` Every frame, the `cosc::CameraAnimationManager` takes the delta time of the last frame and a spectral energy ratio, to compute the camera animations. The spectral energy ratio is simply the current spectral energy divided by the max spectral energy across the whole song (see @math:spectralEnergy). This lets us animate effects to the _intensity_ of the song, which is covered in the next section. The CameraAnimationManager stores which of the animations it's currently in, and handles the logic to transition to the next animation. When the end of the animation list is reached, it's simply wrapped around using modulo. The animation progress is tracked by keeping a sum of the delta values provided to the `cosc::CameraAnimationManager::update()` function, forming an `elapsed` value. Using the aforementioned spectral energy ratio, the rate of change of the song is also increased during "intense" moments, and decreased during "relaxed moments". This is simply achieved by computing a multiplier to the delta time sent to the `cosc::CameraAnimationManager`, which currently ranges between 0.5x and 20x the normal speed. This particular feature was added after further observation of the original Monstercat visualiser, where this effect appears to be subtly applied to the background stars. Animating the 3D position of the camera between the begin and end pose turns out to be very easy, using simple linear interpolation, as follows: ```cpp auto pos = glm::mix(anim.begin.pos, anim.end.pos, progress); // performs linear interpolation camera.setEyePoint(pos); ``` The `progress` value ranges from 0.0 to 1.0 and is computed by `elapsed / anim.duration`. I also experimented using more complex interpolation (usually called "tweening" in the games industry), such as quadratic interpolation. Surprisingly, linear interpolation continued to look much better and was retained as the final interpolation method. Animating the orientation of the camera is much more difficult. There are a number of ways of expressing 3D orientations, the two main paradigms being Euler angles and quaternions. Euler angles represent rotations as a 3D vector of angles around axes: pitch, roll and yaw (@fig:euler). #figure( image("img/euler.png", width: 65%), caption: [ Demonstration of Euler angle rotation system @eulerDiagram ] ) <fig:euler> Unfortunately, Euler angles suffer from well-described problems such as ambiguity and gimbal lock @Hemingway2018, which make their use unsuitable for freeform 3D rotations and animations as is required in this project. Instead, the system of quaternions are used. A quaternion is a 4D complex number system that can be used to encode 3D rotations, and has a direct correlation to rotation matrices. Quaternion multiplication is the process used to rotate them. A quaternion is represented in the form: $ q = a + b i + c j + d k $ Where $a, b, c, d in bb(R)$ and $1, i, j, k$ are basis vectors. In particular, it is worth noting that quaternions are the most widely used system to reliably encode rotations in video games and other domains such as mobile robotics. Quaternions can be both converted to and from Euler angles. In freecam mode, to ensure consistency and stability, the camera class stores the pitch and yaw directly, meaning that the pitch and yaw are stored directly as the ground truth, rather than the quaternion. When the mouse is pushed upwards/downwards (Y axis in SDL), the pitch is changed. When the mouse is moved left/right (X axis in SDL), the yaw is changed. Roll is extremely undesirable for this application and is kept to a constant 0. In order to prevent rotation issues at the poles, pitch is clamped between -89 and +89 degrees. #footnote("Note that this is common behaviour in most first-person video games as well.") If the pitch angle were to reach 90 degrees, it was found to become extremely unstable. In the main animation mode, one of the most useful aspects of quaternions come in handy: spherical linear interpolation. Remember, our goal is to smoothly animate the transition between the start and end camera pose. It's not possible to directly apply simple linear interpolation to the quaternion $w x y z$ values directly, as was done with the $x y z$ camera position vector. Instead, the system of spherical linear interpolation ("slerp") can be used to achieve a visually similar result. This system was first described by <NAME> in 1985 @Shoemake1985, and has since been used in almost every 3D video game since that time. Given two quaternions $q_1$ and $q_2$, and an interpolation parameter $u, {u in bb(R) | 0.0 <= u <= 1.0}$, spherical linear interpolation will find the shortest distance with constant angular velocity between them, as follows: // https://splines.readthedocs.io/en/latest/rotation/slerp.html $ text("Slerp")(q_1, q_2, u) = q_1(q_1^(-1) q_2)^u $ In the visualiser, this is simply achieved by using glm's `glm::slerp` function, and since the special quaternion-based camera designed in @cinderCamera is used, it all magically "just works". In the end, the entire animation can be roughly condensed into the following (with `progress` being calculated as described above): ```cpp // lerp position auto pos = glm::mix(anim.begin.pos, anim.end.pos, progress); // slerp angle auto orientation = glm::slerp(anim.begin.orientation, anim.end.orientation, progress); // update camera camera.setEyePoint(pos); camera.setOrientation(orientation); ``` This produces a really nice result, and goes to show the power of simple, effective and widely used interpolation techniques! == Camera shake In order to illustrate the intensity of the song at certain points, a camera shake effect was added to the `cosc::CameraAnimationManager`, which is computed alongside the existing camera move system. Camera shake is essentially applying pseudorandom perturbations to the camera's orientation quaternion (in other words, semi-randomly rotating the camera each tick). It turns out that _actual_ randomness does not look very natural, so instead, Simplex noise @simplexNoise is applied. Simplex noise is a very popular procedural gradient noise technique designed by <NAME>, who also designed the seminal Perlin noise technique. Whereas pseudorandom number generators (PSRNGs) aim to generate a high-quality sequence of random numbers based on an initial seed, gradient noise techniques instead aim to generate visually appealing, smoother, more natural "randomness" with less focus on statistical quality. Simplex and Perlin noise achieve this essentially through creating a lattice of random gradients, computing the dot product of those gradients, and then interpolating them. This is shown in @fig:perlin for Perlin noise, Simplex noise is very similar. #figure( image("img/PerlinNoiseInterpolated.svg", width: 60%), caption: [ Interpolated lattice to construct Perlin noise @perlinDiagram ] ) <fig:perlin> These types of gradient noise techniques are often used in video games for procedural terrain generation, e.g. Minecraft. Compared to Perlin noise, Simplex noise has the advantage of lower computational cost and better visual results. Raw Simplex noise on its own is not flexible enough to control the camera shake as desired, so I also sum it together using fractal Brownian motion (fBm), using the technique described in @simplexFbm. Fractal Brownian motion, in the computer graphics sense, involves adding different iterations of noise ("octaves"), with successively incrementing frequencies ("lacunarity") and decreasing amplitude ("gain"), to produce a finer grained noise pattern with more intricate details. The fBm technique can be described by the following pseudocode @fbmShaders: ```cpp // Properties const int octaves = 1; float lacunarity = 2.0; float gain = 0.5; // Initial values float amplitude = 0.5; float frequency = 1.; // Loop of octaves for (int i = 0; i < octaves; i++) { y += amplitude * noise(frequency*x); frequency *= lacunarity; amplitude *= gain; } ``` The C++ implementation of both fBm and Simplex noise was provided by @simplexLibrary. To actually shake the camera, I generate a noise value for each Euler axis, and apply it every frame. The result of Simplex noise combined with fBm is shown in @fig:fbm. This is a two dimensional image, where the noise value is seeded based on the $x$, $y$ pixel position. In our case, the noise value is seeded based on the time since the application has started, and a value of 1.0-3.0 for the roll, pitch and yaw Euler axes respectively. #figure( image("img/simplexfbm.png", width: 80%), caption: [ 2D Simplex noise with fractal Brownian motion @simplexFbm ] ) <fig:fbm> The magnitude of the shake is based on the spectral energy ratio, as defined in @math:spectralEnergy. That means that more "intense" moments in the song have more screen shake, and less intense moments have less shake. This scaling is applied separately to the fBm parameters. == Skybox cubemap The visualiser also draws a skybox using OpenGL's cubemap system. A cubemap is a 3D texture that is mapped to a cube volume that surrounds the environment (@fig:cubemap). Assuming the texture has no visible seams on the edges of the cube volume, the cubemap gives the impression of a detailed space environment. This is a very common technique used in almost all video games. The space cubemap texture itself was generated using the tool in @tyroSpace, which uses procedural techniques, coincidentally also using GLSL shaders. #figure( image("img/cubemap.png", width: 55%), caption: [ Demonstration of an OpenGL cubemap @cubemapDiagram ] ) <fig:cubemap> Based on a technique described in LearnOpenGL, the cubemap is able to be drawn last in the scene as an optimisation. This is achieved by the following snippet in the vertex shader: ```glsl gl_Position = pos.xyww; ``` // TODO fact check this In the perspective division stage, the use of `xyww` ensures that the vertex of the skybox always appears behind any other vertices in the scene. For our case, this means that we can guarantee the skybox is drawn behind the spectrum bars, and that we don't _overdraw_ - which saves some calls to the fragment shader where other geometry in the scene obscures the skybox. The skybox is shown in-app in @fig:skyboxscr: #figure( image("img/skyboxscr.jpg", width: 75%), caption: [ Screenshot of two angles of the skybox in the visualiser ] ) <fig:skyboxscr> == Post-processing effects The visualiser implements a simple post-processing pass that is run after the main scene is drawn. Currently, the only effect rendered is chromatic aberration. This is an "artistic touch", if you will, that I added to emphasise the _intensity_ of the song at certain points. The intensity is again based on the spectral energy ratio from @math:spectralEnergy. Post-processing is achieved using OpenGL's framebuffer and renderbuffer system. The framebuffer is attached to the colour buffer, which is sampled in the fragment shader. The colour and stencil buffers are bound to the renderbuffer, which does not need to be sampled. The fragment shader, which implements the post-processing effects, is passed the final rendered image along with the spectral energy ratio. To compute chromatic aberration, the fragment sampling position is adjusted on the horizontal axis by an amount relative to the spectral energy ratio, performed separately for the R, G and B channels. This is implemented as follows (based on the shader in @godotChromatic): ```glsl vec4 colour; float amount = 0.06 * spectralEnergyRatio; colour.r = texture2D(screenTexture, vec2(TexCoords.x + amount, TexCoords.y)).r; colour.g = texture2D(screenTexture, TexCoords).g; colour.b = texture2D(screenTexture, vec2(TexCoords.x - amount, TexCoords.y)).b; colour.a = 1.0; ``` The result is shown in @fig:chromatic: #figure( image("img/chromatic.png", width: 75%), caption: [ Screenshot of visualisation application showing chromatic aberration effect ] ) <fig:chromatic> @fig:chromatic_closeup also shows a close-up picture of the chromatic aberration effect. Notice the separation of the individual colour channels. #figure( image("img/chromatic_closeup.png", width: 60%), caption: [ Close-up of chromatic aberration effect ] ) <fig:chromatic_closeup> In the above figures, you will notice that the chromatic aberration effect is applied to the whole screen, including the background skybox. This could be avoided if desired by rendering the bars to a separate framebuffer and compositing the result together. However, I was inspired by the album art to the song "Saturn's Air" by Animadrop (which was, at one point, going to be used in the visualiser #footnote("It was removed due to not looking very interesting on the spectrum.")) to make the chromatic aberration effect fullscreen. The album art is reproduced in @fig:animadrop. It also served as an inspiration for the space skybox. #figure( image("img/animadrop_saturnsair.jpg", width: 35%), caption: [ Album art for _Saturn's Air_ by Animadrop, inspiration for fullscreen chromatic aberration ] ) <fig:animadrop> = Discussion Overall, the application was completed to a very functional standard and could be considered stable enough for real live presentations. One problem that I encountered was with anti-aliasing. In the application configuration section, I configure SDL2 to use multi-sample anti-aliasing (MSAA) with 4x samples. Unfortunately, as can be seen in @fig:chromatic_closeup, the anti-aliasing didn't end up working correctly. In the time given, I wasn't able to figure out what exactly is causing this discrepancy. I originally thought it was an issue with Wayland, but the issue also occurs under XWayland. Instead, I believe the issue is that, while the _screen target_ is configured to use MSAA, the off-screen framebuffer has not been configured to use MSAA. One other issue I noticed was that, although any songs will _work_ on the visualiser, not all songs look _good_ on the visualiser. This particularly seems to be related to how the spectral energy ratio is distributed across the length of the song, which in turn depends on how the song is mixed and also how the bassline is written. Songs with rolling, constant bass and songs that are mixed with low dynamic range (i.e. highly compressed) will be regarded by the visualiser as being "intense" for their whole duration, even if they don't _sound_ intense to our human ears. This means that the camera will shake, move quickly, and chromatic aberration will be present throughout the entire song. Instead, songs with short, "blippy" basslines seem to work the best. @fig:lauraspectral shows the spectral energy ratio for the song _Pure Sunlight_ by <NAME>, AGNO3 and MrFijiWiji, which was the main showcase song for the visualiser. The X axis is block index and the Y axis is spectral energy ratio at that instant. This graph shows that _Pure Sunlight_ works really well because it has a varied, "blippy" spectral energy ratio, with a slow intro section and more intense second section. #figure( image("img/puresunlight_spectral.svg", width: 70%), caption: [ Spectral energy ratio graph of _Pure Sunlight_ by <NAME>, AGNO3 and MrFijiWiji. ] ) <fig:lauraspectral> As always with these sorts of projects, there's much that can be improved. Here's a list of good targets for future improvement and research: - Performing DC offset removal in spectral processing on the Python side - DC offsets can significantly bias the spectrogram for certain inputs - Mel sampling in spectral processing - Currently, the sampling is linear which may not be accurate to human hearing - Mel sampling (hence the "Mel spectrogram") resembles human musical hearing much more closely - Refactoring the render pipeline, especially `main.cpp`, to have a `Renderer` interface with `IntroRenderer` and `MainRenderer` sub-classes; plus a proper state machine to switch between them - Make "state" less ugly - we would like to avoid having as many globals as we currently have - Not always easy in graphics - Add the ability to easily stack multiple post-processing passes. Ideally, the `Framebuffer` class would be written into a `PostFX` class that has a `addPass(const Shader &shader)` method. - Serialise camera animations to disk using JSON, make a proper editor for them with a timeline, and make it animations depend on the song being played - More advanced and dynamic lighting for the bars - Including reflection mapping: Projecting the cubemap skybox onto the bars - Use the symmetry of the skybox more effectively, by having a reflective ground plane - This would look like those photos taken of lakes at ground level with a "mirror" effect - Most post-processing effects, on the glitchy side of things - Bloom post-effect - Requires HDR rendering pipeline (separate task) - Colour correction and tonemapping - Also requires HDR rendering pipeline - Tonemapping can be done for example using the ACES curve @acesTone - Animate camera using splines rather than two linear interpolation points - Would allow for smoother trajectories with multiple points in them Additionally, here are some more advanced ideas for long-term future improvement: - Dynamically render intro text based on song being played, using FreeType - Move to a fully online audio architecture all in C++, capture sound from loopback device using PipeWire - This would eliminate the need for offline audio processing entirely - Song lyrics displayed as 3D text that flies around - Requires additional serialisation and animations - More content in the background - Hard to describe, but I was considering a particle system based on the human head which disintegrates and re-forms based on the spectral energy. - Use Vulkan instead of OpenGL = Self-assessment I'm really proud of the work I achieved for this project. The visualiser turned out better than I was hoping for. I was able to achieve everything I set out to, and I was even able to complete a lot of the extension tasks I set myself. This was all made possible because I started extremely early (just after the Graphics Minor Project was finished), and worked on the project all basically all semester. The visualiser is stable, and I was able to try it with a wide variety of inputs - some songs work better than others - but all songs were fully functional. The code is relatively clean and performant, which I'm happy about. I was able to draw from a wide variety of advanced topics to construct this visualisation, including from digital signal processing, linear algebra in regards to quaternions and vectors, statistics for fractal Brownian motion, and finally general computer graphics for Simplex noise and chromatic aberration post-processing. By drawing from these topics, I always able to learn a huge amount of cross-discipline knowledge that I couldn't have gotten otherwise. I don't think this will be the final music visualiser I ever make, but nonetheless, I'm really happy with the result I achieved. = Conclusion In this paper, I present a 3D music visualisation application using OpenGL and the Discrete Fourier Transform. The offline signal processing, using the Fast Fourier Transform as the mechanism for computing the DFT, is implemented in Python. The visualisation application, which loads the computed spectral data, is implemented using C++. It has graphics features such as camera animations, camera shake, a cubemap skybox, and a post-processing path that implements chromatic aberration, and an intro section. The application can be configured to display any song with audio available. #pagebreak() = Appendix A: Special thanks - *<NAME>* and *<NAME>*, for always listening to my nonsense inside and outside the COSC pracs. It was great to have beers (or apple cider, technically) with you guys - thanks for being real ones, and the best of luck in your own projects! They are looking fantastic! - *<NAME>* for being the greatest cinema genius of the 21st century. Thank you for helping me film :) - *<NAME>* of LearnOpenGL, for providing one of the best graphics programming resources. - *<NAME>*, *Mr FijiWiji*, *AGNO3*, *Eastern Odyssey* and *Animadrop*, for producing great music. - *The authors and contributors* of: SDL2, glad, glm, Cap'n Proto, dr_flac, stb_image, NumPy, SciPy, spectrum.py, Simplex.h - such a project could not even be remotely achieved without the generous efforts of these talented free software programmers. - *<NAME>* of The Cinder Project, for the quaternion camera. The camera animations would not have been at all possible without this extremely polished perspective camera implementation. This document was typeset using #link("https://github.com/typst/typst")[Typst]. #pagebreak() #bibliography("major.bib", title: "References", style: "ieeemodified.csl")
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/touying-themes/its.typ
typst
#import "touying.typ": * #import "its-theme.typ" as its- #import "its-mooc.typ" as mooc #let IS-MOOC = sys.inputs.at("MOOC", default: none) == "1" #let its = if IS-MOOC { mooc } else { its- } #let its-theme = if IS-MOOC { its.its-mooc-theme } else { its.its-theme } #let announcement = its.announcement #let sl(title, ..args) = { let bodies = args.pos() if type(bodies) != array { bodies = (bodies,) } //! Hacky way to prevent changing header and footer font size. bodies = bodies.map(v => [ #place(top + left, scale(0%, hide[~])) #v ]) let setting = body => body if IS-MOOC { setting = body => { show: place.with( dx: -1em, dy: -.6em, ) show: scale.with(85%) body } } if title == [] { its.slide(..bodies, setting: setting, ..args.named()) } else { heading(depth: 3)[#title] its.slide(..bodies, setting: setting, ..args.named()) } } #let sl2(percent, ..args) = sl(composer: (percent, 1fr), ..args) #let slc(..args, body) = { sl(..args)[ #set align(center + horizon) #show: pad.with(top: -2em) #body ] }
https://github.com/kaarmu/splash
https://raw.githubusercontent.com/kaarmu/splash/main/src/palettes/tailwind-css.typ
typst
MIT License
/* The tailwindcss color palette. * * Source: https://tailwindcss.com/docs/customizing-colors * Accessed: 2023-03-31 */ #let tailwind = ( slate-50 : rgb("#f8fafc"), slate-100 : rgb("#f1f5f9"), slate-200 : rgb("#e2e8f0"), slate-300 : rgb("#cbd5e1"), slate-400 : rgb("#94a3b8"), slate-500 : rgb("#64748b"), slate-600 : rgb("#475569"), slate-700 : rgb("#334155"), slate-800 : rgb("#1e293b"), slate-900 : rgb("#0f172a"), slate-950 : rgb("#020617"), gray-50 : rgb("#f9fafb"), gray-100 : rgb("#f3f4f6"), gray-200 : rgb("#e5e7eb"), gray-300 : rgb("#d1d5db"), gray-400 : rgb("#9ca3af"), gray-500 : rgb("#6b7280"), gray-600 : rgb("#4b5563"), gray-700 : rgb("#374151"), gray-800 : rgb("#1f2937"), gray-900 : rgb("#111827"), gray-950 : rgb("#030712"), zinc-50 : rgb("#fafafa"), zinc-100 : rgb("#f4f4f5"), zinc-200 : rgb("#e4e4e7"), zinc-300 : rgb("#d4d4d8"), zinc-400 : rgb("#a1a1aa"), zinc-500 : rgb("#71717a"), zinc-600 : rgb("#52525b"), zinc-700 : rgb("#3f3f46"), zinc-800 : rgb("#27272a"), zinc-900 : rgb("#18181b"), zinc-950 : rgb("#09090b"), neutral-50 : rgb("#fafafa"), neutral-100 : rgb("#f5f5f5"), neutral-200 : rgb("#e5e5e5"), neutral-300 : rgb("#d4d4d4"), neutral-400 : rgb("#a3a3a3"), neutral-500 : rgb("#737373"), neutral-600 : rgb("#525252"), neutral-700 : rgb("#404040"), neutral-800 : rgb("#262626"), neutral-900 : rgb("#171717"), neutral-950 : rgb("#0a0a0a"), stone-50 : rgb("#fafaf9"), stone-100 : rgb("#f5f5f4"), stone-200 : rgb("#e7e5e4"), stone-300 : rgb("#d6d3d1"), stone-400 : rgb("#a8a29e"), stone-500 : rgb("#78716c"), stone-600 : rgb("#57534e"), stone-700 : rgb("#44403c"), stone-800 : rgb("#292524"), stone-900 : rgb("#1c1917"), stone-950 : rgb("#0c0a09"), red-50 : rgb("#fef2f2"), red-100 : rgb("#fee2e2"), red-200 : rgb("#fecaca"), red-300 : rgb("#fca5a5"), red-400 : rgb("#f87171"), red-500 : rgb("#ef4444"), red-600 : rgb("#dc2626"), red-700 : rgb("#b91c1c"), red-800 : rgb("#991b1b"), red-900 : rgb("#7f1d1d"), red-950 : rgb("#450a0a"), orange-50 : rgb("#fff7ed"), orange-100 : rgb("#ffedd5"), orange-200 : rgb("#fed7aa"), orange-300 : rgb("#fdba74"), orange-400 : rgb("#fb923c"), orange-500 : rgb("#f97316"), orange-600 : rgb("#ea580c"), orange-700 : rgb("#c2410c"), orange-800 : rgb("#9a3412"), orange-900 : rgb("#7c2d12"), orange-950 : rgb("#431407"), amber-50 : rgb("#fffbeb"), amber-100 : rgb("#fef3c7"), amber-200 : rgb("#fde68a"), amber-300 : rgb("#fcd34d"), amber-400 : rgb("#fbbf24"), amber-500 : rgb("#f59e0b"), amber-600 : rgb("#d97706"), amber-700 : rgb("#b45309"), amber-800 : rgb("#92400e"), amber-900 : rgb("#78350f"), amber-950 : rgb("#451a03"), yellow-50 : rgb("#fefce8"), yellow-100 : rgb("#fef9c3"), yellow-200 : rgb("#fef08a"), yellow-300 : rgb("#fde047"), yellow-400 : rgb("#facc15"), yellow-500 : rgb("#eab308"), yellow-600 : rgb("#ca8a04"), yellow-700 : rgb("#a16207"), yellow-800 : rgb("#854d0e"), yellow-900 : rgb("#713f12"), yellow-950 : rgb("#422006"), lime-50 : rgb("#f7fee7"), lime-100 : rgb("#ecfccb"), lime-200 : rgb("#d9f99d"), lime-300 : rgb("#bef264"), lime-400 : rgb("#a3e635"), lime-500 : rgb("#84cc16"), lime-600 : rgb("#65a30d"), lime-700 : rgb("#4d7c0f"), lime-800 : rgb("#3f6212"), lime-900 : rgb("#365314"), lime-950 : rgb("#1a2e05"), green-50 : rgb("#f0fdf4"), green-100 : rgb("#dcfce7"), green-200 : rgb("#bbf7d0"), green-300 : rgb("#86efac"), green-400 : rgb("#4ade80"), green-500 : rgb("#22c55e"), green-600 : rgb("#16a34a"), green-700 : rgb("#15803d"), green-800 : rgb("#166534"), green-900 : rgb("#14532d"), green-950 : rgb("#052e16"), emerald-50 : rgb("#ecfdf5"), emerald-100 : rgb("#d1fae5"), emerald-200 : rgb("#a7f3d0"), emerald-300 : rgb("#6ee7b7"), emerald-400 : rgb("#34d399"), emerald-500 : rgb("#10b981"), emerald-600 : rgb("#059669"), emerald-700 : rgb("#047857"), emerald-800 : rgb("#065f46"), emerald-900 : rgb("#064e3b"), emerald-950 : rgb("#022c22"), teal-50 : rgb("#f0fdfa"), teal-100 : rgb("#ccfbf1"), teal-200 : rgb("#99f6e4"), teal-300 : rgb("#5eead4"), teal-400 : rgb("#2dd4bf"), teal-500 : rgb("#14b8a6"), teal-600 : rgb("#0d9488"), teal-700 : rgb("#0f766e"), teal-800 : rgb("#115e59"), teal-900 : rgb("#134e4a"), teal-950 : rgb("#042f2e"), cyan-50 : rgb("#ecfeff"), cyan-100 : rgb("#cffafe"), cyan-200 : rgb("#a5f3fc"), cyan-300 : rgb("#67e8f9"), cyan-400 : rgb("#22d3ee"), cyan-500 : rgb("#06b6d4"), cyan-600 : rgb("#0891b2"), cyan-700 : rgb("#0e7490"), cyan-800 : rgb("#155e75"), cyan-900 : rgb("#164e63"), cyan-950 : rgb("#083344"), sky-50 : rgb("#f0f9ff"), sky-100 : rgb("#e0f2fe"), sky-200 : rgb("#bae6fd"), sky-300 : rgb("#7dd3fc"), sky-400 : rgb("#38bdf8"), sky-500 : rgb("#0ea5e9"), sky-600 : rgb("#0284c7"), sky-700 : rgb("#0369a1"), sky-800 : rgb("#075985"), sky-900 : rgb("#0c4a6e"), sky-950 : rgb("#082f49"), blue-50 : rgb("#eff6ff"), blue-100 : rgb("#dbeafe"), blue-200 : rgb("#bfdbfe"), blue-300 : rgb("#93c5fd"), blue-400 : rgb("#60a5fa"), blue-500 : rgb("#3b82f6"), blue-600 : rgb("#2563eb"), blue-700 : rgb("#1d4ed8"), blue-800 : rgb("#1e40af"), blue-900 : rgb("#1e3a8a"), blue-950 : rgb("#172554"), indigo-50 : rgb("#eef2ff"), indigo-100 : rgb("#e0e7ff"), indigo-200 : rgb("#c7d2fe"), indigo-300 : rgb("#a5b4fc"), indigo-400 : rgb("#818cf8"), indigo-500 : rgb("#6366f1"), indigo-600 : rgb("#4f46e5"), indigo-700 : rgb("#4338ca"), indigo-800 : rgb("#3730a3"), indigo-900 : rgb("#312e81"), indigo-950 : rgb("#1e1b4b"), violet-50 : rgb("#f5f3ff"), violet-100 : rgb("#ede9fe"), violet-200 : rgb("#ddd6fe"), violet-300 : rgb("#c4b5fd"), violet-400 : rgb("#a78bfa"), violet-500 : rgb("#8b5cf6"), violet-600 : rgb("#7c3aed"), violet-700 : rgb("#6d28d9"), violet-800 : rgb("#5b21b6"), violet-900 : rgb("#4c1d95"), violet-950 : rgb("#2e1065"), purple-50 : rgb("#faf5ff"), purple-100 : rgb("#f3e8ff"), purple-200 : rgb("#e9d5ff"), purple-300 : rgb("#d8b4fe"), purple-400 : rgb("#c084fc"), purple-500 : rgb("#a855f7"), purple-600 : rgb("#9333ea"), purple-700 : rgb("#7e22ce"), purple-800 : rgb("#6b21a8"), purple-900 : rgb("#581c87"), purple-950 : rgb("#3b0764"), fuchsia-50 : rgb("#fdf4ff"), fuchsia-100 : rgb("#fae8ff"), fuchsia-200 : rgb("#f5d0fe"), fuchsia-300 : rgb("#f0abfc"), fuchsia-400 : rgb("#e879f9"), fuchsia-500 : rgb("#d946ef"), fuchsia-600 : rgb("#c026d3"), fuchsia-700 : rgb("#a21caf"), fuchsia-800 : rgb("#86198f"), fuchsia-900 : rgb("#701a75"), fuchsia-950 : rgb("#4a044e"), pink-50 : rgb("#fdf2f8"), pink-100 : rgb("#fce7f3"), pink-200 : rgb("#fbcfe8"), pink-300 : rgb("#f9a8d4"), pink-400 : rgb("#f472b6"), pink-500 : rgb("#ec4899"), pink-600 : rgb("#db2777"), pink-700 : rgb("#be185d"), pink-800 : rgb("#9d174d"), pink-900 : rgb("#831843"), pink-950 : rgb("#500724"), rose-50 : rgb("#fff1f2"), rose-100 : rgb("#ffe4e6"), rose-200 : rgb("#fecdd3"), rose-300 : rgb("#fda4af"), rose-400 : rgb("#fb7185"), rose-500 : rgb("#f43f5e"), rose-600 : rgb("#e11d48"), rose-700 : rgb("#be123c"), rose-800 : rgb("#9f1239"), rose-900 : rgb("#881337"), rose-950 : rgb("#4c0519"), )
https://github.com/ls1intum/thesis-template-typst
https://raw.githubusercontent.com/ls1intum/thesis-template-typst/main/metadata.typ
typst
MIT License
// Enter your thesis data here: #let titleEnglish = "(Title English)" #let titleGerman = "(Title German)" #let degree = "Bachelor" #let program = "Information Systems" #let supervisor = "Prof. Dr. <NAME>" #let advisors = ("<NAME>, M.Sc.",) #let author = "(Author)" #let birthdate = datetime(day: 01, month: 01, year: 2002) // only necessary for registration certificate #let startDate = datetime(day: 1, month: 1, year: 2024) #let submissionDate = datetime(day: 1, month: 1, year: 2024) #let presentationDate = datetime(day: 1, month: 1, year: 2024) #let feedbacklogSubmissionDate = datetime(day: 1, month: 1, year: 2024)
https://github.com/SWATEngineering/Docs
https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/3_PB/VerbaliInterni/VerbaleInterno_240215/content.typ
typst
MIT License
#import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro #import "functions.typ": glossary, team #let participants = csv("participants.csv") = Partecipanti / Inizio incontro: #inizio_incontro / Fine incontro: #fine_incontro / Luogo incontro: #luogo_incontro #table( columns: (3fr, 1fr), [*Nome*], [*Durata presenza*], ..participants.flatten() ) = Sintesi Elaborazione Incontro /*************************************/ /* INSERIRE SOTTO IL CONTENUTO */ /*************************************/ Durante l'incontro odierno sono state prese le seguenti decisioni organizzative e trattati i seguenti punti. == Prossimo diario di bordo (\#10) <NAME> si occuperà della sua stesura mentre <NAME> di esporlo durante la presentazione. == Chiarimento dubbi progettazione <NAME> e <NAME> si occuperanno di contattare per email il professor Cardin per chiarire dubbi relativi alla progettazione, in particolare: - Se applicare design patterns ai simulatori; - Come impostare il diagramma UML delle classi; - Se considerare o meno i simulatori nell'ottica di metriche relative al codice e/o ai test. == Stesura del verbale odierno <NAME> si occuperà della stesura del verbale odierno. == Script consuntivi <NAME> si occuperà di sistemare lo script per i consuntivi automatico che usa il documento interno "Time & Resource Manager", in vista della nuova organizzazione degli sprint e con l'incorrere del nuovo anno. == Stand-up remoti Si è deciso all'unanimità di effettuare stand-up meeting remoti tutti i lunedì ed i mercoledì alle ore 15:00 a partire da lunedì 19/02/2024. == Sistemazione documento "Analisi dei Requisiti" <NAME> è incaricato di sistemare il documento _Analisi dei Requisiti_ secondo le indicazioni dateci dal professor Cardin durante la revisione RTB. == Creazione spazio PB <NAME> è incaricato di creare la cartella per i documenti relativi alla revisione PB e di spostare i relativi documenti già creati. == Altre discussioni Sono state fatte altre discussioni relative al come e quando calcolare le metriche relative ai consuntivi di periodo e come incorporarle in questi ultimi. In merito a questo è stato deciso di implementare l'attività di chiusura dello sprint alle 17:30 del giovedì, utilizzando i seguenti passaggi: - Calcolare le metriche relative allo sprint concluso e aggiornare i grafici del _Piano di Qualifica_; - Assicurarsi che tutti abbiano immesso le loro ore produttive nel documento interno "Time & Resource Manager" per calcolare le tabelle del consuntivo. In seguito, si è deciso di studiare il contenuto da inserire nel documento _Specifiche Tecniche_, in particolare: - Architetture layered (a strati) ed event-driven; - "Pipes & filters". == Nuovi ruoli Di seguito un elenco con i nuovi incarichi per lo sprint in corso: - <NAME>, Verificatore; - <NAME>, Analista e Amministratore; - <NAME>, Progettista; - <NAME>, Verificatore; - <NAME>, Responsabile; - <NAME>, Progettista.
https://github.com/liuxu89/typstbook
https://raw.githubusercontent.com/liuxu89/typstbook/main/src/1-mao/别了司徒雷登.typ
typst
#import "/book.typ": book-page #show: book-page.with(title: "Hello, typst") = 别了,司徒雷登 (一九四九年八月十八日) #highlight[美国的白皮书,选择在司徒雷登业已离开南京、快到华盛顿、但是尚未到达的日子——八月五日发表,是可以理解的,因为他是美国侵略政策彻底失败的象征。] #underline(evade: false)[司徒雷登是一个在中国出生的美国人,在中国有相当广泛的社会联系,在中国办过多年的教会学校,在抗日时期坐过日本人的监狱,平素装着爱美国也爱中国,颇能迷惑一部分中国人,因此被马歇尔看中,做了驻华大使,成为马歇尔系统中的风云人物之一。] #text(fill: blue)[在马歇尔系统看来,他只有一个缺点,就是在他代表马歇尔系统的政策在中国当大使的整个时期,恰恰就是这个政策彻底地被中国人民打败了的时期,这个责任可不小。] 以脱卸责任为目的的白皮书,当然应该在司徒雷登将到未到的日子发表为适宜。 美国出钱出枪,蒋介石出人,替美国打仗杀中国人,借以变中国为美国殖民地的战争,组成了美国帝国主义在第二次世界大战以后的世界侵略政策的一个重大的部分。 美国侵略政策的对象有好几个部分。 欧洲部分,亚洲部分,美洲部分,这三个是主要的部分。 中国是亚洲的重心,是一个具有四亿七千五百万人口的大国,夺取了中国,整个亚洲都是它的了。 美帝国主义的亚洲战线巩固了,它就可以集中力量向欧洲进攻。 美帝国主义在美洲的战线,它是认为比较地巩固的。 这些就是美国侵略者的整个如意算盘。 可是,一则美国的和全世界的人民都不要战争;二则欧洲人民的觉悟,东欧各人民民主国家的兴起,特别是苏联这个空前强大的和平堡垒耸立在欧亚两洲之间,顽强地抵抗着美国的侵略政策,使美国的注意力大部分被吸引住了;三则,这是主要的,中国人民的觉悟,中国共产党领导的武装力量和民众组织力量已经空前地强大起来了。 这样,就迫使美帝国主义的当权集团不能采取大规模地直接地武装进攻中国的政策,而采取了帮助蒋介石打内战的政策。 美国的海陆空军已经在中国参加了战争。 青岛、上海和台湾,有美国的海军基地。 北平、天津、唐山、秦皇岛、青岛、上海、南京都驻过美国的军队。 美国的空军控制了全中国,并从空中拍摄了全中国战略要地的军用地图。 在北平附近的安平镇,在长春附近的九台,在唐山,在胶东半岛,美国的军队或军事人员曾经和人民解放军接触过,被人民解放军俘虏过多次。 陈纳德航空队曾经广泛地参战。 美国的空军除替蒋介石运兵外,又炸沉了起义的重庆号巡洋舰。 所有这些,都是直接参战的行动,只是还没有公开宣布作战,并且规模还不算大,而以大规模地出钱出枪出顾问人员帮助蒋介石打内战为主要的侵略方式。 美国之所以采取这种方式,是被中国和全世界的客观形势所决定的,并不是美帝国主义的当权派——杜鲁门、马歇尔系统不想直接侵略中国。 在助蒋作战的开头,又曾演过一出美国出面调处国共两党争端的文明戏,企图软化中国共产党和欺骗中国人民,不战而控制全中国。 和谈失败了,欺骗不行了,战争揭幕了。 对于美国怀着幻想的善忘的自由主义者或所谓“民主个人主义”者们,请你们看一看艾奇逊的话: “和平来到的时候,美国在中国碰到了三种可能的选择: (一)它可以一干二净地撤退; (二)它可以实行大规模的军事干涉,帮助国民党毁灭共产党; (三)它可以帮助国民党把他们的权力在中国最大可能的地区里面建立起来,同时却努力促成双方的妥协来避免内战。” 为什么不采取第一个政策呢?艾奇逊说:“我相信当时的美国民意认为,第一种选择等于叫我们不要坚决努力地先做一番补救工作,就把我们的国际责任,把我们对华友好的传统政策,统统放弃。” 原来美国的所谓“国际责任”和“对华友好的传统政策”,就是干涉中国。 干涉就叫做担负国际责任,干涉就叫做对华友好,不干涉是不行的。 艾奇逊在这里强奸了美国的民意,这是华尔街的“民意”,不是美国的民意。 为什么不采取第二个政策呢?艾奇逊说: “第二种供选择的政策,从理论上来看,以及回顾起来,虽然都似乎是令人神往,却是完全行不通的。 战前的十年里,国民党已经毁灭不了共产党。 现在是战后了,国民党是削弱了,意志消沉了,失去了民心,这在前文已经有了说明。 在那些从日本手里收复过来的地区里,国民党文武官员的行为一下子就断送了人民对国民党的支持,断送了它的威信。 可是共产党却比以往无论什么时候都强盛,整个华北差不多都被他们控制了。 从国民党军队后来所表现的不中用的惨况看来,也许只有靠美国的武力才可以把共产党打跑。 对于这样庞大的责任,无论是叫我们的军队在一九四五年来承担,或者是在以后来承担,美国人民显然都不会批准。 我们因此采取了第三种供选择的政策……” 好办法,美国出钱出枪,蒋介石出人,替美国打仗杀中国人,“毁灭共产党”,变中国为美国的殖民地,完成美国的“国际责任”,实现“对华友好的传统政策”。 国民党腐败无能,“意志消沉了,失去了民心”,还是要出钱出枪叫它打仗。 直接出兵干涉,在“理论上”是妥当的。 单就美国统治者来说,“回顾起来”,也是妥当的。 因为这样做起来实在有兴趣,“似乎是令人神往”。 但是在事实上是不行的,“美国人民显然都不会批准”。 不是我们——杜鲁门、马歇尔、艾奇逊等人的帝国主义系统——不想干,干是很想的,只是因为中国的形势,美国的形势,还有整个国际的形势(这点艾奇逊没有说)不许可,不得已而求其次,采取了第三条路。 那些认为“不要国际援助也可以胜利”的中国人听着,艾奇逊在给你们上课了。 艾奇逊是不拿薪水上义务课的好教员,他是如此诲人不倦地毫无隐讳地说出了全篇的真理。 美国之所以没有大量出兵进攻中国,不是因为美国政府不愿意,而是因为美国政府有顾虑。 第一顾虑中国人民反对它,它怕陷在泥潭里拔不出去。 第二顾虑美国人民反对它,因此不敢下动员令。 第三顾虑苏联和欧洲的人民以及各国的人民反对它,它将冒天下之大不韪。 艾奇逊的可爱的坦白性是有限度的,这第三个顾虑他不愿意说。 这是因为他怕在苏联面前丢脸,他怕已经失败了但是还要装做好像没有失败的样子的欧洲马歇尔计划陷入全盘崩溃的惨境。 那些近视的思想糊涂的自由主义或民主个人主义的中国人听着,艾奇逊在给你们上课了,艾奇逊是你们的好教员。 你们所设想的美国的仁义道德,已被艾奇逊一扫而空。 不是吗?你们能在白皮书和艾奇逊信件里找到一丝一毫的仁义道德吗? 美国确实有科学,有技术,可惜抓在资本家手里,不抓在人民手里,其用处就是对内剥削和压迫,对外侵略和杀人。 美国也有“民主政治”,可惜只是资产阶级一个阶级的独裁统治的别名。 美国有很多钱,可惜只愿意送给极端腐败的蒋介石反动派。 现在和将来据说很愿意送些给它在中国的第五纵队,但是不愿意送给一般的书生气十足的不识抬举的自由主义者,或民主个人主义者,当然更加不愿意送给共产党。 送是可以的,要有条件。 什么条件呢?就是跟我走。 美国人在北平,在天津,在上海,都洒了些救济粉,看一看什么人愿意弯腰拾起来。 太公钓鱼,愿者上钩。 嗟来之食,吃下去肚子要痛的。 我们中国人是有骨气的。 许多曾经是自由主义者或民主个人主义者的人们,在美国帝国主义者及其走狗国民党反动派面前站起来了。 闻一多拍案而起,横眉怒对国民党的手枪,宁可倒下去,不愿屈服。 朱自清一身重病,宁可饿死,不领美国的“救济粮”。 唐朝的韩愈写过《伯夷颂》,颂的是一个对自己国家的人民不负责任、开小差逃跑、又反对武王领导的当时的人民解放战争、颇有些“民主个人主义”思想的伯夷,那是颂错了。 我们应当写闻一多颂,写朱自清颂,他们表现了我们民族的英雄气概。 多少一点困难怕什么。 封锁吧,封锁十年八年,中国的一切问题都解决了。 中国人死都不怕,还怕困难吗?老子说过:“民不畏死,奈何以死惧之。” 美帝国主义及其走狗蒋介石反动派,对于我们,不但“以死惧之”,而且实行叫我们死。 闻一多等人之外,还在过去的三年内,用美国的卡宾枪、机关枪、迫击炮、火箭炮、榴弹炮、坦克和飞机炸弹,杀死了数百万中国人。 现在这种情况已近尾声了,他们打了败仗了,不是他们杀过来而是我们杀过去了,他们快要完蛋了。 留给我们多少一点困难,封锁、失业、灾荒、通货膨胀、物价上升之类,确实是困难,但是比起过去三年来已经松了一口气了。 过去三年的一关也闯过了,难道不能克服现在这点困难吗?没有美国就不能活命吗? 人民解放军横渡长江,南京的美国殖民政府如鸟兽散。 司徒雷登大使老爷却坐着不动,睁起眼睛看着,希望开设新店,捞一把。 司徒雷登看见了什么呢?除了看见人民解放军一队一队地走过,工人、农民、学生一群一群地起来之外,他还看见了一种现象,就是中国的自由主义者或民主个人主义者们也大群地和工农兵学生等人一道喊口号,讲革命。 总之是没有人去理他,使得他“茕茕孑立,形影相弔”,没有什么事做了,只好挟起皮包走路。 中国还有一部分知识分子和其他人等存有糊涂思想,对美国存有幻想,因此应当对他们进行说服、争取、教育和团结的工作,使他们站到人民方面来,不上帝国主义的当。 但是整个美帝国主义在中国人民中的威信已经破产了,美国的白皮书,就是一部破产的记录。 先进的人们,应当很好地利用白皮书对中国人民进行教育工作。 司徒雷登走了,白皮书来了,很好,很好。 这两件事都是值得庆祝的。
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/assets/example1/old.typ
typst
ZMIANY NA HEADERZE = Introduction niezmieniony ZMIANY NA PARAGRAFIE \ In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers *and hZMIANA* they contribute to the formation and behaviour of these natural structures. ZMIANY NA LISTACH + The climate - Temperature - Precipitation + The topograpZMIANA + The geology ZMIANY NA MATEMATYCE $ Q = rho A v + C $ ZMIANY NA FIGURACH ZE ZDJĘCIEM #figure( image("doggo.jpeg", width: 20%), caption: [ _Dog_ form an important partZMIANA of the earth's climate system. ], ) ZMIANY NA FUNKCJACH #show "ArtosFlow": name => box[ #box(image( "doggo.jpeg", height: 0.7em, )) #name ] // zmienne i funkcje #let name = "Typst" This is #name's documentation. It explains #name. This report is embedded in the ArtosFlow project. ArtosFlow is a project of the Artos Institute. ZMIANY NA LINKACH \ https://typst.app/ /* MODES */ Number: #(1 + 2) let name = [*Typst!*] ZMIANY NA TEKŚCIE #lower("ABC") \ #lower[*My Text*] \ #lower[already low] #upper("abc") \ #upper[*my text*] \ #upper[ALREADY HIGH]
https://github.com/HEIGVD-Experience/docs
https://raw.githubusercontent.com/HEIGVD-Experience/docs/main/S4/WEB/docs/8-AsynchronousProgramming/rest.typ
typst
#import "/_settings/typst/template-note-en.typ": conf #show: doc => conf( title: [ REPRESENTATIONAL STATE TRANSFER (REST), ], lesson: "WEB", chapter: "8 - Aynchronous Programming", definition: "TBD", col: 1, doc, )
https://github.com/kdog3682/typkit
https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/alignments.typ
typst
#let left = left #let right = right #let top = top #let bottom = bottom #let middle = center + horizon #let center = center #let horizon = horizon
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/umbra/0.1.0/src/shadow-path.typ
typst
Apache License 2.0
// Gets the length of an arbitrary vector #let _norm(p) = calc.sqrt(p.map(x => calc.pow(x.pt(), 2)).sum()) * 1pt // Adds any number of arbitrary vectors #let _add(..ps) = ps.pos().fold( none, (acc, x) => if acc == none { x } else { acc.zip(x).map(((y, z)) => y + z) }, ) // Takes the first vector and subtracts all subsequent vectors from it #let _sub(..ps) = ps.pos().fold( none, (acc, x) => if acc == none { x } else { acc.zip(x).map(((y, z)) => y - z) }, ) // Rotates a 2D vector by the given angle #let _rot(p, angle) = ( p.first() * calc.cos(angle) - p.last() * calc.sin(angle), p.first() * calc.sin(angle) + p.last() * calc.cos(angle), ) // Multiply (scale) a vector by some number #let _mult(p, x) = p.map(y => x * y) // Roll a vector by count positions, moving the overflow at the end back to the start #let _roll(arr, count) = (arr.slice(count) + arr).slice(0, arr.len()) #let shadow-path( fill: none, stroke: none, closed: false, shadow-radius: 0.5cm, shadow-stops: (gray, white), // A small correction is required otherwise there is a white line between shadow sections correction: 5deg, ..vertices, ) = { let vertices = vertices.pos() assert(vertices.all(x => x.len() == 2 and x.all(y => type(y) != array)), message: "paths with Bezier control points not supported") layout( size => { let vertices = vertices.map(((x, y)) => (if type(x) == ratio {x * size.width} else {x}, if type(y) == ratio {y * size.height} else {y})) let groups = vertices.zip(_roll(vertices, 1), _roll(vertices, 2), _roll(vertices, 3)) if not closed { groups = _roll(groups, -1).slice(0, -1) } // Setup edge shadows for (p0, p1, p2, p3) in groups { let angle0 = calc.atan2(.._sub(p1, p0).map(x => x.pt())) angle0 += if angle0 > 0deg {0deg} else {360deg} let angle1 = calc.atan2(.._sub(p2, p1).map(x => x.pt())) angle1 += if angle1 > 0deg {0deg} else {360deg} let angle2 = calc.atan2(.._sub(p3, p2).map(x => x.pt())) angle2 += if angle2 > 0deg {0deg} else {360deg} let width = shadow-radius let height = _norm(_sub(p1, p2)) let d0 = 0pt let d1 = 0pt let da0 = angle1 - angle0 let da1 = angle2 - angle1 if da0 < 0deg or da0 > 180deg { da0 = 0 } if da1 < 0deg or da1 > 180deg { da1 = 0 } place( top + left, dx: p2.first(), dy: p2.last(), rotate( calc.atan2(.._sub(p1, p2).map(x => x.pt())) + 90deg + 180deg, origin: top + left, polygon( fill: gradient.linear(..shadow-stops), (0pt, 0pt), _rot((width, 0pt), da1 / 2), _add((0pt, height), _rot((width, 0pt), -da0 / 2)), (0pt, height) ) ) ) } // Setup corner shadows if not closed { groups = groups.slice(1) } for (p0, p1, p2, p3) in groups { let angle0 = calc.atan2(.._sub(p1, p0).map(x => x.pt())) angle0 += if angle0 > 0deg {0deg} else {360deg} let angle1 = calc.atan2(.._sub(p2, p1).map(x => x.pt())) angle1 += if angle1 > 0deg {0deg} else {360deg} let da = angle1 - angle0 if da < 0deg or da > 180deg { da = calc.abs(da) let d0 = _rot((shadow-radius, 0pt), angle0 + 90deg + correction) let d1 = _rot((shadow-radius, 0pt), angle1 + 90deg - correction) // Must be placed in the correct location, otherwise the gradient is based on the size of the whole box place(top + left, dx: p1.first() - shadow-radius, dy: p1.last() - shadow-radius, box( // A fixed size box is required to make radial gradient work. For PDF, the gradient doesn't actually have to be contained by the box, but this breaks with PNG, hence the extra complexity width: 2*shadow-radius, height: 2*shadow-radius, place(top+left, dx: 50%, dy: 50%, path( closed: true, fill: gradient.radial(..shadow-stops, center: (50%, 50%), radius: 50%, relative: "parent"), (d0, _mult(_rot(d0, -90deg), calc.sin(da / 2)), (0pt, 0pt)), (0pt, 0pt), ((d1), (0pt, 0pt), _mult(_rot(d1, 90deg), calc.sin(da / 2)),), )))) } } if fill != none or stroke != none { path(fill: fill, stroke: stroke, closed: closed, ..vertices) } }, ) }
https://github.com/cadojo/resume
https://raw.githubusercontent.com/cadojo/resume/main/cv.typ
typst
#import "exploration/src/options/options.typ": * #import "exploration/src/vita/vita.typ": * #import "exploration/src/rolo/rolo.typ": * #let me = author( name: name( given: "Joseph", family: "Carpinelli", literal: "<NAME>", ), affiliation: affiliation( address: "1307 Welch Street #6", city: "Houston", region: "TX", postal-code: "77006", ), email: link("mailto:<EMAIL>", `<EMAIL>`), phone: link("tel:+12026602578", `+1 202.660.2578`), ) #let theme = rgb("#588157") #show heading.where(level: 1): text => smallcaps(text) #show heading.where(level: 2): text => smallcaps(text) #show: cv.with( author: me, theme: theme, ) #degree("M.S.", "Student", start: "A", stop: "B")[] #experience("NASA", start: datetime.today().display())[] #research("SSL", start: datetime.today().display())[] #award("Scholarship", "A")[] #teaching("Tutoring")[] #publication("Paper", "Journal", date: "Today")[] #presentation("Presentation", "JuliaCon", date: "Today")[] #reference(me)
https://github.com/almarzn/portfolio
https://raw.githubusercontent.com/almarzn/portfolio/main/templates/typst/.template/page.typ
typst
#import "@preview/splash:0.3.0": tailwind #import "./shared/sizes.typ": scale #let page-background( borders: (top: 4pt), color: black ) = block( width: 100%, height: 100%, inset: borders, fill: color, block( width: 100%, height: 100%, fill: white ) ) #let page-footer( background: white, height: 80pt, content: ( header: "header", sub: "sub" ) ) = block( fill: background, height: height, width: 100%, clip: true, inset: (x: 32pt), align(horizon, grid( columns: (1fr, auto, auto), gutter: 12pt, align(bottom + left, text(weight: "semibold", content.header)), align(bottom + left, content.contact1.name), align(bottom + right, content.contact1.phone), align(bottom + left, text(size: scale.small, content.sub)), align(bottom + left, content.contact2.name), align(bottom + right, content.contact2.phone), )) )
https://github.com/EpicEricEE/typst-equate
https://raw.githubusercontent.com/EpicEricEE/typst-equate/master/src/lib.typ
typst
MIT License
#import "equate.typ": equate, share-align
https://github.com/hekzam/test
https://raw.githubusercontent.com/hekzam/test/main/main.typ
typst
#import "template.typ": * #let meta = json("meta.json") #let source = json("source.json") #set heading(numbering:"1.") #set page( footer: [ #place(center)[ #counter(page).display("1 / 1", both: true) ] #place(right)[id: #source.examId] ], foreground: [ // Prevent repeats!! #place(bottom+left, dx : 10pt, dy : -10pt, marker("m")) #place(top+left, dx : 10pt, dy : 10pt, marker("l")) #place(bottom+right, dx : -10pt, dy : -10pt, marker("s")) #place(top+right, dx : -10pt, dy : 10pt, layout(size => { locate(loc => { let i = counter(page).at(loc).at(0) let l = loc.position() qr(source.examId, i, meta.active) append(f, "qr", (x: tocm(l.x), y: tocm(l.y), dx: tocm(qr_code_size), dy: tocm(qr_code_size))) append(f, ("md", "w"), tocm(size.width)) append(f, ("md", "h"), tocm(size.height)) append(f, ("md", "n"), counter(page).final(loc).at(0)) }) }) ) ] ) #open(f) #open(g) /* Grille numéro étudiant La fonction id_etudiant génère une grille de 8 colonnes et de 10 lignes */ #let id_etudiant(len) = [ #let colonne_cases(ligne) = { let i = 0 while i < 10 { v(-10pt) append(g, ("ex", "SID", "q", "SIDN" + str(ligne), "a", "SIDN" + str(ligne) + "A" + str(i)), ("score": i)) bcase("SIDN" + str(ligne) + "A" + str(i)) i=i+1 } } #let colonne_chiffre() = { let i = 0 while i < 10 { v(-7.2pt) text([#i], baseline: -2pt) i=i+1 } } #box(width: 12pt * (len + 1))[ #append(g, ("ex", "SID"), (max: 0.0, min: 0.0)) #columns(9, gutter: 1pt)[ #colonne_chiffre() #colbreak() #let n=0 #while n < len { append(g, ("ex", "SID", "q", "SIDN" + str(n)), (kind: "OneInN", max: 10.0, min: 0.0, gd: ("student_id", ("Digits": n)))) colonne_cases(n) colbreak() n=n+1 } ] ] ] /* Logo - Importer un logo sous l'appelation "Logo.png" */ #let logo(taille)=[ #if taille == "grand"{ image("Logo.png", width: 100%) } else if taille == "moyen grand"{ image("Logo.png", width: 75%) } else if taille == "moyen"{ image("Logo.png", width: 50%) } else if taille == "moyen petit"{ image("Logo.png", width: 25%) } else if taille == "petit"{ image("Logo.png", width: 0%) } ] /* Une fonction pour tout - type_q : type de la question (multiple true false, 1 parm N...) - type_a : type d'affichage : afficher les réponses en sautant une ligne = "saut" à la suite = "suite" - q : question */ #let affichage_question(type_q,type_a, q, exercise_id)= { /* type d'affichage */ let affichage_defaut(type_a, q) = { if type_a == "a_la_suite"{ // Probably not working columns( q.numberOfAnswers, gutter : -200pt)[ #let nOA = q.numberOfAnswers #align(center)[ /* Pour chaque réponse */ #let i = 1; #for a in q.answers { a.insert("id", q.id + "A" + str(i)) append(g, ("ex", exercise_id, "q", q.id, "a", a.id), ("score": a.score)) block()[#v(5pt)#a.answerLabel #align(center)[#box(bcase(a.id))] ] if nOA > 1 { colbreak() } nOA=nOA - 1 i += 1 } #v(20pt)//espacement après exo ]] } else { let i = 1; let totalscore = 0; let maxscore = 0; let rightcount = 0; for a in q.answers [ #a.insert("id", q.id + "A" + str(i)) #append(g, ("ex", exercise_id, "q", q.id, "a", a.id), ("score": a.score)) #(totalscore += a.score) #if a.score > 0 { maxscore += a.score; rightcount += 1 } #box(bcase(a.id)) #h(4pt) #text(a.answerLabel, baseline: -2pt) #(i += 1) #v(-5pt) ] if type_q == "MCQ" and totalscore > 0 { fail("bad MCQ weights: correct weight should be less than or equal to the incorrect weights. (crossing everything will give a positive point amount)") } if maxscore < q.maxScoreQuestion { fail("bad answer weights: cannot reach max score for question.") } if type_q == "OneInN" and rightcount > 1 { fail("bad OneInN weights: there is more than one correct answer.") } /*if maxscore > q.maxScoreQuestion { // not necessarily a fail state? fail("wasted points: can reach more than max score for question.") }*/ v(10pt)//espacement après exo } } let affichage_TF(type_a, q) = { { // En-tête box(width: 25pt, columns([#h(1pt)T #colbreak() #h(1pt)F])) v(-5pt) let i = 1; let maxscore = 0; for a in q.answers [ #a.insert("id", q.id + "A" + str(i)) #append(g, ("ex", exercise_id, "q", q.id, "a", a.id), ("score": a.score)) #if a.score.at(0) > 0 { if a.score.at(1) > 0 { fail("bad TrueFalse weights: both answers are right.") } maxscore += a.score.at(0) } else if a.score.at(1) > 0 { maxscore += a.score.at(1) } else { fail("bad TrueFalse weights: both answers are wrong.") } #box(width: 25pt, columns([#bcase(a.id + "T")#colbreak() #bcase(a.id + "F")])) #h(4pt) #text(a.answerLabel, baseline: -2pt) #(i += 1) #v(-5pt) ] if maxscore < q.maxScoreQuestion { fail("bad TrueFalse weights: cannot reach max score for question.") } v(10pt)//espacement après exo } } /* type de question */ if type_q == "MCQ" { [_plusieurs réponses peuvent être justes_ ] affichage_defaut(type_a, q) } else if type_q == "OneInN" { [_une seule réponse est juste_ ] affichage_defaut(type_a, q) } else if type_q == "MultipleTF" { [_une seule réponse par question_ ] affichage_TF(type_a, q) } else { fail("unkown type: " + type_q) } } /* Presentation() affiche les premiers éléments indispendables pour identifier une copie */ #let presentation(exam) = [ #place(top+left, dx : 0pt, dy : -10pt)[#logo("moyen petit")] #place(top+right, dx : 10pt, dy : 10pt)[Numéro Étudiant #v(0pt) #id_etudiant(exam.lenStudentId)] #place(top+left, dx : 10pt, dy : 1.8cm)[ #rect(width: 7cm, height: 3cm, inset: 11pt)[Nom : #v(15pt) Prenom :]] #v(7cm) // Espace identifiant étudiant #underline[*#align(center, text(size : 15pt, exam.title))*] //Titre ] #let forecast(exam) = [ #presentation(exam) /* Parcourir chaque exercice */ #let i = 1; #let max = 1; #for ex in exam.exercises { ex.insert("id", "E" + str(i)) append(g, ("ex", ex.id), (max: ex.maxScoreExercise, min: 0.0)) block() [#align(center)[#rect[= #upper[#text(size : 13pt, "Exercice")]]]//Titre de l'exercice #align(center)[#ex.eSText] //Énoncé de l'exercice #v(15pt) /* Parcourir chaque question */ #let j = 1; #let total = 0; #for q in ex.questions { [== #q.qStatement] q.insert("id", ex.id + "Q" + str(j)) append(g, ("ex", ex.id, "q", q.id), (kind: q.questionType, max: q.maxScoreQuestion, min: q.minScoreQuestion, gd: ("note", "Number"))) affichage_question(q.questionType, "saut", q, ex.id) total += q.maxScoreQuestion j += 1 } #if total < ex.maxScoreExercise { fail("bad question weights: cannot reach max score for exercise.") } ] max += ex.maxScoreExercise i += 1 } #if max < exam.maxScore { fail("bad exercise weights: cannot reach max score for exam.") } ] #append(f, ("md", "id"), source.examId) #append(g, ("md", "id"), source.examId) #if meta.active { append(f, ("md", "hash"), meta.hash) append(g, ("md", "hash"), meta.hash) } else { append(f, ("md", "hash"), (0,)) append(g, ("md", "hash"), (0,)) } // Declare the generated elements #append(g, ("grading", "note"), "Number") #append(g, ("grading", "student_id"), ("Digits": source.lenStudentId)) #append(g, "max", source.maxScore) #append(g, "min", 0.0) #forecast(json("source.json")) #jsondump(f) #jsondump(g)
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/experiment/weeks/week6.typ
typst
#import "../../utils.typ": * #section("Random Experiment") An experiment that can be re-done as many times as one wants, it will *always be random*.\ All possible endstates of the experiment is the result quantity $Omega$. #align( center, [#image("../../Screenshots/2023_10_26_09_14_09.png", width: 70%)], ) - partial quantity: parts of the result quantity -> for example a best case scenario -> *events/ereignisse* - result quantity: the quantity that encompasses all possible results #subsection("Events and Notation") Events, aka results are often notated with the mathematical quantity notation: $A sect B$.\ In this case it's considered that *event x happens when result x appears* -> event A or B happens when result $A union B$ appears.\ Or in other words, events are the partial quanity in the result quantity. - $A sect B$: A and B - $A union B$: A or B - $A complement$: everything that is not A #align( center, [#image("../../Screenshots/2023_10_26_09_24_17.png", width: 60%)], ) #align( center, [#image("../../Screenshots/2023_10_26_09_24_34.png", width: 30%)], ) #subsubsection("Special Events") - the empty quantity $nothing$ is the impossible event - the result quantity $Omega$ is the 100% event -> always happens since every event is within $Omega$ - elementary events(Elementarereignisse) are events within a subquantity of the result quantity - two events are not compatible when: $A union B == nothing$ #section("Probability P") #subsection("Dependent Probability") This means that you expect something to be true and then you calculcate the probability.\ In this case B has to have happened and then you calculate A -> probability A given B. #set text(15pt) $P(A|B) = (P(A union B)/(P(B)))$\ $P(A union B) = P(B) * P(A|B)$\ #align( center, [#image("../../Screenshots/2023_10_26_09_37_30.png", width: 60%)], ) #set text(11pt) Note the P(B) in the equation, if it is 0 aka B didn't happen -> not a valid equation! #align( center, [#image("../../Screenshots/2023_10_26_09_31_25.png", width: 70%)], ) #subsubsection("Example") #align( center, [#image("../../Screenshots/2023_10_26_09_38_51.png", width: 70%)], ) #align( center, [#image("../../Screenshots/2023_10_26_10_01_22.png", width: 70%)], ) #subsubsection("Rule of Bayes") $P(A union B) = P(B) * P(A|B)$\ $P(B union A) = P(A) * P(B|A)$\ $P(A union B) = P(B union A)$\ $P(A) * P(B|A) = P(B) * P(A|B)$\ Essentially this has to be the case as unions of A and B are always the same, no matter what order the letters are. #subsection("Independent Probability") This is the same as above, but without a preceding event/result. #set text(15pt) $P(A|B) = P(A)$ #text( teal, )[Aka, the B doesn't matter as it doesn't depend on it. B can be whatever, the result of probability A is the same!] #align( center, [#image("../../Screenshots/2023_10_26_09_46_04.png", width: 40%)], ) Probabilities are independent if: $P(A union B) = P(A) * P(B)$ Which also means that $A$ and $B complement$, $A complement$ and $B$, $A complement$ and $B complement$ are also independent from another. #set text(11pt) #subsection("Complete Probability") #set text(15pt) $P(A) = sum_(i=1)^n P(A|B_i) * P(B_i)$ #set text(11pt) #align( center, [#image("../../Screenshots/2023_10_26_09_53_54.png", width: 30%)], ) #align( center, [#image("../../Screenshots/2023_10_26_09_50_11.png", width: 80%)], )
https://github.com/roman-vanesyan/cv
https://raw.githubusercontent.com/roman-vanesyan/cv/main/cv.typ
typst
MIT License
#let color-neutral-500 = color.linear-rgb(115, 115, 115) #let color-neutral-700 = color.linear-rgb(64, 64, 64) #let color-neutral-900 = color.linear-rgb(23, 23, 23) #let color-neutral-950 = color.linear-rgb(10, 10, 10) // Coloring of icons is done in the svg sources themselves, // currently defaulting to color-neutral-700. #let icon-github = image("assets/github.svg") #let icon-web = image("assets/web.svg") #let icon-linkedin = image("assets/linkedin.svg") #let icon-email = image("assets/email.svg") #let profile-full-name = "<NAME>" #let profile-email = "<EMAIL>" #let profile-website = "romanvanesyan.com" #let profile-github = "roman-vanesyan" #let profile-linkedin = "roman-vanesyan" #let skills-langs = ("TypeScript", "Go", "SQL", "Vanilla JavaScript", "Dart", "Python", "Nix", "HTML/CSS") #let skills-tools = ("Node.js", "MySQL", "TiDB", "Grafana", "Prometheus", "Kibana", "PostgresQL", "Redis", "AWS", "Kubernetes", "React") #let skills-spoken-langs = ("English", "Russian") #let header-link(name, url, icon) = { link(url)[ #block(spacing: 0.75em)[ #box(height: 1em, baseline: 25%)[#icon] #name ] ] } #let content-section(title, first, ..rest) = { let header = block(breakable: false, spacing: 0cm)[ #align(left)[ #text(size: 1.375em, weight: "semibold", fill: color-neutral-900)[#title] #box(width: 1fr, line(stroke: color-neutral-900, length: 100%)) ] #first ] if rest.pos().len() > 0 { set stack(dir: ttb, spacing: 2.5em) stack( header, stack(..rest) ) } else { header } } #let skills-block(..rows) = { table( columns: 2, stroke: none, gutter: 1.25em, inset: 0cm, ..rows, ) } #let skills-row(title, ..skills) = ( [#strong(delta: 200)[#title]], [#skills.pos().join(", ")] ) #let education-item(org, degree, time) = { grid( columns: (1fr, auto), align(left)[ #strong(delta: 200)[#degree] \ #text(style: "italic")[#org] \ ], align(right)[ #text(size: 1em)[#time] ] ) } #let experience-item(pos, org, description, time, ..items) = { grid( columns: (1fr, auto), align(left)[ #block(breakable: false, spacing: 0cm)[ #text(weight: "semibold")[#pos] - #strong(delta: 200)[#org] ] #stack( dir: ttb, spacing: 0.75em, text[#description], list(..items) ) ], align(right)[#time] ) } ////////////////////////////////////////////////// // DEFAULT SETTINGS // ////////////////////////////////////////////////// #set text(size: 12pt, fill: color-neutral-950, lang: "en") #set page( paper: "a4", margin: (y: 1.5cm, x: 1cm), footer: [ #align(center)[ #set text(size: 0.825em) // Show number of pages #counter(page).display() ] ] ) // Metadata #set document( author: profile-full-name, title: "Curriculum Vitae" ) ////////////////////////////////////////////////// // CV CONTENT GOES HERE // ////////////////////////////////////////////////// // Header #align(left)[ #grid( columns: (1fr, auto), align(left)[ #text(size: 2em, style: "normal", weight: "semibold")[#profile-full-name] \ #text(size: 1.5em, style: "italic", fill: color-neutral-500)[Software Engineer] ], align(right)[ #set text(size: 0.825em, style: "italic", fill: color-neutral-700) #header-link(profile-email, "mailto:" + profile-email, icon-email) #header-link(profile-website, "https://" + profile-website, icon-web) #header-link(profile-github, "https://github.com/" + profile-github, icon-github) #header-link(profile-linkedin, "https://linkedin.com/in/" + profile-linkedin, icon-linkedin) ] ) ] #stack( dir: ttb, spacing: 2.5em, content-section( "Skills", skills-block( ..skills-row("Languages", ..skills-langs), ..skills-row("Tools and Platforms", ..skills-tools), ..skills-row("Spoken languages", ..skills-spoken-langs) ) ), content-section( "Experience", experience-item( "Senior Software Engineer", "Bolt", [ I’m currently working at a mobility company serving over 200 million customers worldwide, managing dozens of critical high-load components in a distributed environment. ], "07/2023 - Now", "Implemented a company-wide billing metrics dashboard, providing deep insights into service health and performance.", "Profiled and optimized the PDF generation service (handling over 300 RPS), reducing CPU usage by 20% and improving the 99th percentile response time by 8x.", "Collaborating on the design and implementation of the Financial Ledger as part of a cross-functional team project, handling over 5000 RPS.", "Contributing to the Billing leadership team, shaping the technical vision for the Billing Platform." ), experience-item( "Software Engineer", "Bolt", [ I worked on Bolt Food, which serves over 6 million customers globally, contributing to an annual impact of over 20 million Euros. ], "08/2021 - 07/2023", [ Designed and implemented a real-time solution to convert hundreds of thousands of customer balances in Croatia to Euros across all business lines with zero downtime. ], [Optimized order processing functionality by parallelizing computation, reducing customer balance update delay time from an average of 30 seconds to 150 milliseconds.], [ Engineered and rolled out support for a new taxation schema in Ghana within a tight timeline, securing the company's operation in the country. ], [Served as the Technical Lead for the Billing for Delivery team.] ), experience-item( "Software Engineer", "Refactr, Inc. (acquired by Sophos Ltd.)", "I was a key member of a dedicated team of three engineers working on a CI platform with over 50000 daily running jobs, contributing to various aspects of the platform.", "07/2020 - 07/2021", [Led the development of the first CLI version to interact with the platform.], [Designed and implemented a DSL for CI pipeline variables.], [Built and integrated a plugin system, incorporating over 20 tools to run natively on the platform.], ), experience-item( "Software Engineer", "EPAM Systems", "I contributed to two dedicated projects: TelescopeAI PERF, a team productivity analytics platform with 15k DAU, and Anatha, a crypto wallet supporting major cryptocurrencies such as Bitcoin and Ethereum.", "08/2019 - 07/2020", [ Led the development of the desktop wallet application using Electron. Designed and implemented key features, including account creation and management, a cryptocurrency exchange, and real-time balance retrieval. ], [Developed a UI design system adopted by multiple internal teams at EPAM.], [Set up the desktop build infrastructure, including CI/CD pipelines, build tools, and linting.] ) ), content-section( "Education", education-item( "Moscow State University named after <NAME>", "B. Sc. in Applied Mathematics and Computer Science", "09/2016 - 06/2020" ) ) )
https://github.com/1sSay/USPTU_conspects
https://raw.githubusercontent.com/1sSay/USPTU_conspects/main/src/math/IntroductionToMathematicalAnalysis.typ
typst
// Global settings and templates #set text(14pt) #let def(term, color: black) = { box(stroke: color, inset: 7pt, text()[ #term ]) } // Lecture header and date #let lecture_header = text()[Введение в математический анализ] #let date = text()[27.09.2024] // Header #align(center, heading(level: 1)[Математика. \ #lecture_header ]) #align(center, text(weight: "thin")[#date]) #align(center, text(weight: "thin")[Конспект Сайфуллина Искандара БПО09-01-24]) // Content = Область определения и область значений Пусть $f: X -> Y$ #def[D(f) -- область определения] #def[E(f) -- область значений] = Обратная функция #def[$f^(-1): Y -> X$] = Известные функции == Линейные #def[$f(x) = a x + b$] == Степенные #def[$f(x) = a x^n + b x^(n-1) + ... + #text()[const]$] == Показательные #def[$f(x) = a^x$] == Логарифмические #def[$f(x) = log_a x$] == Тригонометрические #def[$sin(x), cos(s), tg(x), ctg(x), arcsin(x), arctan(x)$] == Гиперболические #def[$s h(x), c h(x)$] = Сложная функция (Композиция функций) #def[$f(g(x))$] = Монотонность #def[$forall x_1, x_2 : x_1 < x_2 : f(x_1) < f(x_2) => f$ -- возрастает] #def[$forall x_1, x_2 : x_1 < x_2 : f(x_1) > f(x_2) => f$ -- убывает] = Предел функции == Окрестность точки #def[Пусть $a in RR$, $epsilon > 0, epsilon in RR$, тогда множество $B_epsilon (a) = (a - epsilon, a+ epsilon)$ называется $epsilon$-окрестностью точки $a$] #def[Пусть $a in RR$, $epsilon > 0, epsilon in RR$, тогда множество $dot(B)_epsilon (a) = (a - epsilon, a+ epsilon) \\ {a}$ называется проколотой $epsilon$-окрестностью точки $a$] == Определение #def[$forall epsilon > 0 : exists delta > 0 : forall x in D(f) : 0 <|x - a| < delta => |f(x) - A| < epsilon$] == Односторонние пределы #def[#text(red)[*TODO*]] Ну там чутка определение надо переписать == Бесконечность #def[#text(red)[*TODO*]] == Арифметические свойства пределов #def[$ f(x) -> a and g(x) -> b => f(x) plus.minus g(x) -> a plus.minus b $] #def[$ f(x) -> a and g(x) -> b => f(x) * g(x) -> a * b $] #def[$ f(x) -> a and g(x) -> b and b != 0 => f(x) / g(x) -> a / b $] == Бесконечно большая величина #def[$ forall E > 0 exists delta > 0 : forall x in D(f) : 0 < |x - a| < delta => |f(x)| > E $] == Бесконечно малая величина #def[$ forall epsilon > 0 exists delta > 0 : forall x in D(f) : 0 < |x - a| < delta => |f(x)| < epsilon$] Пусть $alpha$, $beta$ -- бесконечно малые при $x -> a$ $ lim_(x->a)(alpha(x) + beta(x))= 0 $ $ lim_(x->a)(f(x)alpha(x)) = 0, f(x) arrow.not infinity $ $ lim_(x->a)f(x) != 0 => lim_(x->a) alpha(x) / f(x) = 0 $ == Свойства пределов #def[$ lim_(x->a)(f(x) plus.minus g(x)) = lim_(x->a)f(x) plus.minus lim_(x->a)g(x) $] #def[$ lim_(x->a)(f(x) * g(x)) = lim_(x->a)f(x) * lim_(x->a)g(x) $] #def[$ lim_(x->a)(c * g(x)) = c * lim_(x->a)f(x) $] #def[$ lim_(x->a)(f(x) / g(x)) = frac(lim_(x->a)f(x), lim_(x->a)g(x)), lim_(x->a)g(x) != 0 $]
https://github.com/hweissi/nix-typst-base
https://raw.githubusercontent.com/hweissi/nix-typst-base/main/main.typ
typst
== This is just a base typst file
https://github.com/SnowManKeepsOnForgeting/NoteofModernControlTheory
https://raw.githubusercontent.com/SnowManKeepsOnForgeting/NoteofModernControlTheory/main/Homework/Homework_5.typ
typst
#import "@preview/physica:0.9.3":* #import "@preview/i-figured:0.2.4" #let xb = $bold(x)$ #let xbd = $accent(bold(x),dot)$ #let xbl = $accent(bold(x),macron)$ #let yb = $bold(y)$ #let ub = $bold(u)$ #let Qb = $bold(Q)$ #let Abl = $accent(bold(A),macron)$ #let Bbl = $accent(bold(B),macron)$ + Determine the observability of the following systems: (1) $xbd = mat(delim: "[",1,1;1,0)xb,y = mat(delim: "[",1,1)xb$ (2) $xbd = mat(delim: "[",0,4,3;0,20,16;0,-25,-20)xb,y = mat(delim: "[",-1,3,0)xb$ (3) $xbd = mat(delim: "[",-4,0,0;0,-4,0;0,0,1)xb,y = mat(delim: "[",1,1,4)xb$ Solution:(1)We use Kalman's observability criterion to determine the observability of the system. $ Qb_o = mat(delim: "[",bold(C);bold(C A)) = mat(delim: "[",1,1;2,1)\ rank(Qb_o) = 2=n $ Thus the system is observable. (2)We use Kalman's observability criterion to determine the observability of the system. $ Qb_o = mat(delim: "[",bold(C);bold(C A);bold(C A^2)) = mat(delim: "[",-1,3,0;0,56,45;0,-5,-4)\ rank(Qb_o) = 3=n $ Thus the system is observable. (3)The matrix $bold(A)$ is in diagonal form.Thus if matrix $bold(C)$ does not have a zero column,then the system is observable.By this criterion the system is observable. + Try to determine for which values of $p,q$ the following systems are not controllable and for which values they are not observable. $ xbd = mat(delim: "[",1,12;1,0)xb + mat(delim: "[",p;-1)u \ y = mat(delim: "[",q,1)xb $ Solution:By Kalman's criterion,we have: $ Qb_c = mat(delim: "[",bold(B),bold(A)bold(B)) = mat(delim: "[",p,p-12;-1,p)\ Qb_o = mat(delim: "[",bold(C);bold(C A)) = mat(delim: "[",q,1;q+1,12q)\ "let" det(Qb_c) = p^2+p - 12 = 0,p=-4,3\ "let" det(Qb_o) = 12q^2 - q - 1 = 0,q=- 1/4,1/3 $ Thus the system is not controllable for $p=-4,3$ and not observable for $q=-1/4,1/3$. + Try to prove the following system is not controllable in any condition of $a,b,c$. $ xbd = mat(delim: "[",20,-1,0;4,16,0;12,0,18)xb + mat(delim: "[",a;b;c)u $ Solution:We calculate the eigenvalues of the matrix $bold(A)$. $ "let" det(lambda bold(I) - bold(A)) = - (lambda - 18)^3 = 0\ lambda_(1,2,3) = 18 $ We apply jordan transformation to system. We have: $ "Let" Abl = bold(P) bold(A) bold(P)^(-1) = mat(delim: "[",18,1,0;0,18,1;0,0,18)\ bold(P) = mat(delim: "[",0,-1/8,1/24;0,1/4,0;1,-1/2,0)\ Bbl = bold(P) bold(B) = mat(delim: "[",-1/8 b + 1/24 c;1/4 b;a - 1/2 b)\ accent(bold(x),macron) = bold(P) bold(x) $ Thus we have: $ accent(accent(bold(x),macron),dot) = mat(delim: "[",18,1,0;0,18,1;0,0,18)accent(bold(x),macron) + mat(delim: "[",-1/8 b + 1/24 c;1/4 b;a - 1/2 b)u $ Thus if $a != 1/2 b$ then the system is controllable. + Given a linear time-invariant system $xbd = bold(A)xb + bold(B)u$.If $xb_a,xb_b$ is controllable states of the system,try to prove that $alpha xb_a + beta xb_b$ state is also a controllable state of the system. Solution:$xb_a,xb_b$ is controllable states of the system means $ exists t_1,t_2,u_1,u_2 "such that" xb(t_(1,2)) = e^(bold(A)t_(1,2))xb_(a,b) + integral_0^t_(1,2) e^(bold(A)(t_(1,2)-tau))bold(B)u_(1,2)(tau) dd(tau) = 0 $ W.L.O.G we assume $t_1 < t_2$. $ "Let" u_3(t) = cases(alpha u_1(t) + beta u_2(t) "if" 0 <= t <= t_1\ beta u_2 (t) "if" t_1 < t <= t_2\ )\ "And we have:" xb_alpha = - integral_0^t_1 e^(bold(A) tau)bold(B)u_1(tau) dd((tau))\ xb_beta = - integral_0^t_2 e^(bold(A) tau)bold(B)u_2(tau) dd((tau))\ "Thus" xb(t) = e^(bold(A)t)(alpha xb_a + beta xb_b) + integral_0^t e^(bold(A)(t-tau))bold(B)u_3(tau) dd(tau) \ = e^(bold(A)t )( integral_0^t e^(-bold(A)tau)bold(B)u_3(tau)dd(tau) - integral_0^t_1 e^(-bold(A)tau)bold(B)alpha u_1(tau)dd(tau) - integral_0^t_2 e^(-bold(A)tau)bold(B) beta u_2(tau)dd(tau) )\ "Let" t = t_2 ,xb(t_2) = 0 $ Thus the state $alpha xb_a + beta xb_b$ is also a controllable state of the system. + Transform the following system to controllable canonical form. $ xbd = mat(delim: "[",1,-2;3,4)xb + mat(delim: "[",1;1)u $ Solution: $ Qb_c = mat(delim: "[",bold(B),bold(A)bold(B)) = mat(delim: "[",1,-1;1,7)\ rank(Qb_c) = 2 = n\ "Let" bold(P) = mat(delim: "[",bold(B),bold(A)bold(B))^(-1) = mat(delim: "[",1,-1;1,7)^(-1) = mat(delim: "[",7/8,1/8;-1/8,1/8)\ xbl = bold(P)xb\ Abl = bold(P)bold(A)bold(P)^(-1) = mat(delim: "[",0,-10;1,5)\ Bbl = bold(P)bold(B) = mat(delim: "[",1,0)\ "Controllable canonical form" accent(xbl,dot) = mat(delim: "[",0,-10;1,5)xbl + mat(delim: "[",1;0)u $
https://github.com/MilanR312/ugent_typst_template
https://raw.githubusercontent.com/MilanR312/ugent_typst_template/main/main.typ
typst
MIT License
#import "ugent_template.typ": ugent-template, gls, make-glossary, init_note_tables #show: make-glossary #show: init_note_tables #show: ugent-template.with( title: [ #text([A real thesis about colors], size: 25pt) ], short_title: [Colors], language: "nl", team_text: none, authors: ( ( name: "<NAME>", student_number: "00", email: "test" ), ), other_people: ( begeleiders: ( "<NAME>", ), promotors: none ), //glossary-file: "glos.yml", //bibliography-file: "refs.yml", ) #include "chapters/c1/text.typ"
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045%20-%20Kamigawa%3A%20Neon%20Dynasty/004_Episode%203%3A%20An%20Unexpected%20Alliance.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 3: An Unexpected Alliance", set_name: "Kamigawa: Neon Dynasty", story_date: datetime(day: 25, month: 01, year: 2022), author: "<NAME>", doc ) Sunlight spilled through the trees, rippling over the bog. Kaito didn't wander from the road. He knew even the most innocent looking flower could be deadly in the swamp. The nezumi had never made it a secret they didn't like visitors; using the poisonous landscape to their advantage was the perfect deterrent. And under normal circumstances, Kaito would never have risked venturing so deep into their territory. But the key to finding Tezzeret was with the nezumi. #figure(image("004_Episode 3: An Unexpected Alliance/01.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) After Tameshi's death, Kaito had spent weeks tracking down every scrap of information he could find on Tezzeret. He'd gone to Otawara's libraries, scoured every archive, and spoke with some of Kamigawa's most revered Living Historians. Tezzeret did not exist on any data drive. But he #emph[did] exist in a memory. A Historian who performed in one of Towashi's oldest theaters spoke of a village inhabited by the Nezumi-Katsuro gang. It had burned down five years before, attacked by forces that were never held accountable. One of the survivors was a child called Nashi, whose parents had tried to get him to safety when the attack began. Nashi had only made it to the edge of the village when he watched in terror as his mother was burned alive and sparks of fire ignited every hut around him. The nezumi village burned through the night, and after the fire cleared and the survivors gathered near the ashes, Nashi listened to the adults whisper the name of the man who ordered the attack. They called him Tezzeret—and he'd been betrayed by his subordinates, who left him braindead in the burned village for the nezumi to find. They kept Tezzeret until the day a dragon arrived and bargained for his body. The nezumi feared retribution from Tezzeret's organization. They were afraid that if anyone found out there were survivors, someone might return to finish the job. So, the nezumi did the only thing they could—they helped the child become a ghost. Then they became ghosts, too. They could hide for the rest of their lives, but Nashi had no surviving family. It was kinder to send him far from the swamp, where Tezzeret's organization would never be able to find him and he could start over. But the nezumi from the neighboring villages would not talk to Kaito. Not just about Nashi, but about #emph[anything] . They shouted curses and slammed their doors and even threatened to poison him if he didn't leave. Judging by the number of toxic flowers along the road, he didn't doubt they were serious. Kaito had no friends in the swamp. But there were answers here, and he wasn't ready to turn back before he found them. Adjusting his tanuki mask, he followed the broken road, a translucent strip of energy, across the murky water. It was enough to keep Kaito dry, but he eyed the glowing yellow cracks nervously. If the road gave way, there was nothing to keep him above ground. Being eaten alive by poisonous eels wasn't exactly the end Kaito had pictured for himself. Not that he had an aversion to eel; he was quite fond of them when they were roasted with sesame oil and wrapped in rice and seaweed. Kaito hurried to the next shoreline. Massive roots protruded from the ground like a mess of tangled yarn, blocking the glowing road ahead. A smaller footpath was all that remained, covered in pebbles and flattened mulch. Kaito followed the trail until he reached a village. It was smaller than some of the others, with houses made up of straw roofs and sliding paper doors. Houses that would easily fall apart if the wind swept in too fast. #emph[Or a fire] , Kaito thought grimly. What happened to Nashi's family was violent. Maybe even vengeful. Kaito needed to know why—and how it connected to Tameshi, and the monster he saw at the docks. How it connected to the #emph[emperor] . A wide dirt path cut through the center of the village. At the far end was a junkyard full of metal scraps and outdated bits of machine. It was long rumored that nezumi in the swamps were experimenting with unregulated tech. They often traded their creations with the Okiba Reckoners—a biker gang that was exclusively nezumi—in exchange for a near-constant flow of stolen goods. But Kaito was a Futurist, whose core beliefs were to push the limits of technology for the greater good. Who was he to judge what the nezumi got up to? An older gray nezumi stood behind a wooden fence, the fur around her mouth peppered in silver. Her claws were wrapped around the handle of a gardening tool, the serrated blade shaped like a pincer and attached to a metal box that thrummed with energy. "You're not welcome here," she barked. Kaito hesitated, glancing at the jagged blade. It could easily be used as a weapon. The nezumi narrowed her dark pink eyes. "It's for harvesting mushrooms. Cuts the stems just right to keep the spores from releasing." Her nose twitched. "If you're here to check our permits—" "I'm not," Kaito said quickly, holding his hands in front of him, hoping to show he wasn't a threat. Not currently, anyway. His enemies were more monster than rodent. She sniffed at the air. "Humans don't travel all the way out here unless it's for their own benefit." She flashed her yellow teeth. "We've never been worth the inconvenience." "Your stolen goods and illegal side projects are not my concern. I'm here for information." Kaito let the silence follow. It was a risk to call out the nezumi so brazenly, but he'd dealt with enough of them in Towashi to know they respected brutal honesty far more than sugar-coated words. #emph[Most ] of the time. A dark brown nezumi appeared on the nearby porch, long tail trailing behind him. He glared at his neighbor, hissing violently. "You share too much with this stranger, Mud-Tail." The elder nezumi snapped her jaws in response. "Go inside and mind your own business, before one of these mushrooms takes a detour through your house." The neighbor snarled slightly, hackles rising at the back of his neck, but he took a step back in submission. "I'm looking for someone called Nashi." Kaito glanced between them. "He used to live a few miles from here when he was a child." At the sound of his name, several kami poked their heads out from beneath the neighbor's porch. Kami that unmistakably belonged to the swamp, with their collection of floating toadstools and poisonous flowers spinning around their heads. One stared up at Kaito with six enormous frog-like eyes. Four bubbles circled around him, with tadpoles wiggling anxiously inside. The nezumi may have been experienced with lying, but the kami were not. Beneath the porch, they began to whisper to one another. Mud-Tail cut them a sharp look, and they retreated into the shadows. She shrugged at Kaito. "Never heard of 'em." Kaito glanced at the roof. The straw was thinning and frayed near the corners. "Looks like you've lived here a long time. Long enough to remember the fire." Her tail lifted behind her, swaying hypnotically. "The humans didn't help us then. Why would we ever help you now?" "Maybe because of my good looks and charming personality?" When the nezumi didn't react, Kaito lifted his shoulders. "Look—I only want to talk to him." Mud-Tail leaned the wooden handle against the gate and moved for the house. "I don't think that's really your choice." The nezumi was nearly to her front door when she snapped, "Take your questions back to wherever it is you came from. We don't want you here." It was the politest dismissal he'd had all day. When she vanished inside, Kaito glanced at the stranger still on the porch. His eyes were darker—more onyx than ruby. "I know the nezumi hid him. I know you want to protect him." Kaito's fingers were restless, dancing at his sides. "But what he knows~it could help #emph[all ] of us on Kamigawa." "I've never bitten a human before. We stopped attacking with our teeth to appear more civilized to you humans. We thought it might change things—show you we were equals, not animals." He flashed a sneer. A warning. "But some of us are tired of pretending to be something we're not." It would only take Kaito half a second to pull his sword from his back. Not to mention he could pelt the nezumi with poisonous mushrooms merely by flicking his fingers. It would've been the most fun he'd had all week. But it wouldn't get him information. For that, Kaito needed to play nice. Or at least pretend to. He took a step back. "Thanks for your time." Kaito turned from the village, feeling the eyes of a dozen nezumi on his back. The glowing road appeared ahead, and Kaito reached for his mask, letting the metal shift into a small tanuki. He didn't stop walking, even when Himoto, the drone, launched from his hand and disappeared through the nearby trees, back in the direction of the village. Kaito walked until he was certain he couldn't be seen. Ducking behind a willow tree, he kept his distance from every unfamiliar plant and pressed a finger to his temple. Using his drone's camera, he flew across the bog and entered the village from the side. The drone took cover in the wilted plants, sights locked onto the Kami of the Wetland that trudged clumsily toward another hut, bubbles floating around it with urgency. The drone chased after it, careful to stay out of sight, and followed the roof toward a smokeless chimney before diving for the hearth. Kaito listened to the croak of the kami as it shuffled into the living room, relaying a barely audible message to whoever was inside. "I know," a raspy voice retorted. "Our village isn't the first he's visited—and the more he speaks Nashi's name, the more danger he puts him in." The kami croaked again. This time, Kaito caught a word. #emph[Otawara.] "Yes. I'll warn her. But there's no point sending a drone before nightfall—he'd be able to track it too easily in the daylight," the figure said in a hushed voice. "For now, we just need to make sure our silence is all we give the human." The tanuki drone lifted back up the chimney, settled behind the stones, and waited. By the time Kaito reached the edge of the swamp, the sun had set. With the feed from the drone still live, he watched as the nezumi's drone folded itself into the shape of a rabbit and set off into the darkness. The tanuki followed, and Kaito headed in the direction of Otawara. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) It was nearly dawn when Kaito reached the city in the sky. The nezumi's drone had vanished in one of the crowded neighborhoods, but it didn't matter. Kaito would search the streets by foot. After reuniting with his tanuki mask, he moved across the park, scanning the houses in the distance. It wasn't until he turned into a narrow moss garden that he realized he wasn't alone. A shadow stretched across the grass. In an instant, Kaito's hand was around the hilt of his sword, and he swung it forward and spun to face the approaching figure. A moonfolk hovered in front of him with barely a flash of emotion behind her purple eyes. In her hand was an unrolled scroll, with several more bundled in a satchel at her waist. Kaito twisted his sword, and the blade's serrated edge appeared only for a moment before a dozen star-shaped blades broke apart from one another, held in place by his telekinesis. The woman briefly glanced at the weapon. "It is not my wish to hurt you." "Give it a minute," Kaito said, voice smooth. "You hardly know me." The stranger glided to the left, moving like a silent breeze. "Your search must end today. Please go home in peace, and do not speak the child's name again." "Sorry," Kaito replied. "I'm not going anywhere until me and the kid have a conversation." She dipped her chin. "A conversation does not require so many blades." "Kind of depends on how willing the person is to talk, doesn't it?" Her jaw tensed. Clearly Kaito hit a nerve. He had no intention of harming the nezumi child, but he also wasn't in the mood to explain himself to a stranger—#emph[or ] take orders from one. "If there is information you need, I am certain you can find it elsewhere," she said, voice even. "But you will stay away from my family." "Sounds like there's a threat laced in there somewhere," he noted, fist tightening. He'd never seen scrolls like hers before, but if they were magic, he wasn't about to take any chances. Her feet hovered several inches above the moss. "Violence is not my intention." Kaito cracked a lethal smirk. "You snuck up behind me with an ultimatum and a floating scroll—so forgive me if I don't believe you." He flicked the handle of his blade, and each star shot toward the woman's unrolled parchment. She spun, swift and graceful, and opened her palm at her side so that the scroll floated beside her. The throwing stars arced through the sky before returning to Kaito, glinting beneath the sun. With a grunt, Kaito charged toward the slender moonfolk, hoping to distract her with hand-to-hand combat. She skipped back like she was dancing across the air, arms spread like wings as she remained out of Kaito's reach. Launching himself forward, he swung hard, but the woman was fast. She ducked before twirling to the side, hands raised like it was merely a part of a performance. Kaito's eyes were locked onto the floating scroll. With a mental nudge, every star went sailing toward the parchment, chasing it in circles as the woman used her own telekinesis to pull it away. Kaito swung his leg around to meet her, but she shot up into the sky. He caught his balance, reaching toward the razor stars still circling around the garden, and summoned them back in line with his sword. He watched as the woman's eyes drifted back to the scroll. If he only had a moment, he was going to take it. Kaito commanded the stars to attack once more, aiming not for the woman or the scrolls, but for the rope attached to her waist. Only one of them found their target, but it was enough. The rope snapped, and the satchel began to slip toward the ground. Sweeping an arm beside her, she caught the rope before the scrolls fell, but the distraction left her first scroll unguarded. Kaito reached out a hand, and it sailed through the air and into his fist. The woman blinked, and a second roll of parchment drifted into the air and unraveled in front of her. The moment she read the words, Kaito felt his entire body stiffen. His sword fell from his hand, and the rogue blades followed, clattering into the moss like broken toys. The scroll floated upwards, and by the time the stranger's feet touched the ground, it had returned to the satchel with all the others. Kaito couldn't move. His bones felt like iron, heavy and unbending. Straining against the magic, he gritted his teeth. "I'm not~trying to hurt~the kid." She tilted her head curiously, and when she spoke, her ethereal voice sounded only in Kaito's mind. #emph[You are telling the truth, and for that, I have only gratitude. But my son is not to be found. By anyone.] "Your—your son?" Kaito tried to turn his head when the woman moved beside him, but he remained still as stone. Only his eyes could trail her. She nodded curtly before plucking one of the scrolls from her case and unrolling it. "What are you going to do to me?" Kaito asked, cheeks going hot. He was still thinking fast, hoping for a way out of this. "You needn't be afraid of a simple memory spell." With her mind, she added, #emph[Sending you on a different path will keep you ] and#emph[ my family safe. Do not worry—you won't remember any of this.] Kaito's stomach felt hollow. After all he'd done to get here~to find the emperor and bring her home~ He couldn't let it all be for nothing. She couldn't take his #emph[memories] . His words were fueled by reckless anger. "I'm trying to save the emperor, and your son may be the only person in Kamigawa who can help!" The woman floated in front of him, mouth turning into a flat line. "You are mistaken. Nashi knows nothing of the emperor." "But he knows about Tezzeret," Kaito said, still fighting against the paralysis spell. There was hardly any color to her face already, but in that moment, she appeared ashen. Her eyes studied Kaito—searching for a sliver of falsehood—but found none. She hovered with the truth for a stretch of time before gently tucking the scroll away. At once, movement shuddered back through Kaito's body, and he collapsed to his knees. With a groan, he grabbed his fallen sword and stood, muscles aching. After summoning every blade from the moss, he sheathed the reformed sword at his back and turned to face the moonfolk. "So," Kaito said, still panting slightly. "Are you going to tell me how you know about Tezzeret, or are we going to have to fight again?" "Your arrogance is part of why you lost the battle." She waved a slender hand. "It makes you unfocused." He rubbed the back of his neck. "I mean, most people call me Kaito, but 'unfocused' works, too." Eiko and Light-Paws would almost certainly agree. There was a faint hint of amusement in her stare. "I am Tamiyo," she said, voice as unwavering as steel. "And perhaps you and I are meant to be allies." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaito soaked in the details of the room. Watercolor paintings were dotted around the space. Landscapes that might seem fantastical to the people of Kamigawa. But Kaito recognized them. They were real places. Other #emph[planes] . He turned back to Tamiyo, who filled two cups with green tea before setting the porcelain pot carefully on a low table. Kaito blinked. "You're a planeswalker." It wasn't a question. Tamiyo sat in the opposite chair and lifted the cup to her lips, blowing gently at the steam. "I believe only a fellow planeswalker could make that discovery simply by looking at a few amateur paintings." Kaito knew there were other planeswalkers in the Multiverse. But he had no idea there was another on Kamigawa. His gaze landed on the leatherbound books and bundles of scrolls scattered across most of the surfaces. Understanding dawned on him. "You're gathering information." He frowned. "Why?" Tamiyo sipped her tea. "I believe it is my duty to preserve the truths of the Multiverse." Lifting her brow, she added, "Knowledge helps us grow—as individuals and as a society. It is a gift I do not take for granted." Kaito held his cup between his palms, letting the warmth move through him. "Tell me about Tezzeret. Who is he? What does he want?" Tamiyo started to reply when her demeanor shifted abruptly. Her eyes landed somewhere behind Kaito, and her face softened into a smile. "I believe you know of my son, Nashi." #figure(image("004_Episode 3: An Unexpected Alliance/02.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Kaito turned to find the young nezumi standing in the doorway. With bright white fur and gray spots, he wore a black leather jacket with sharp cuts and silver rings along the edge of his ear. Nashi took one glance at Kaito before his face lit up. "Cool mask! Is that a drone?" He held up a piece of hardware that flickered with pixels. "I've been trying to build one myself with recycled parts. You know—make something old new again, and all that. Did you build yours? What kind of chip did you use to link your camera? Do you use micro implants, or—" Nashi froze for a moment before grinning sheepishly. "Sorry. That's probably too many questions at once." Kaito pulled his mask from his head, letting her fold again and again until she looked like an origami tanuki. "Woah," Nashi said, beaming. "Nice." Tamiyo lifted her chin, eyes full of gentle humor. "Did you need something, Nashi?" He held up the metal. "I need an old data chip. I fried mine trying to connect a piece of broken hardware. Can I go to the second-hand market?" "Take Rumiyo and Hiroku with you. And try to refrain from filling up on dumplings and coconut buns before dinner." Tamiyo smiled at her son, but her thoughts were very much inside Kaito's head. #emph[Don't ask him about Tezzeret. Most of what I know was kept a secret from him, to protect his heart. I do not wish to remind him of a darkness he's tried so hard to escape.] Kaito nodded lightly and grinned at Nashi. "Good luck with the drone." Nashi flashed a toothy grin and hurried back out of the room. When his footsteps faded and he was out of earshot, Kaito set his cup down and stared at Tamiyo. "Tell me everything." So, she did. Kaito learned that Tezzeret wasn't just a planeswalker—he was the planeswalker with the metal arm. The man Kaito saw in Kyodai's chamber all those years ago. The man who had something to do with the emperor's disappearance. Kaito's eyes stung with salt. He felt an ache in his chest—a mixture of grief and clarity that was too overwhelming to carry in such a short moment. But he listened anyway, even as his head swayed and he felt the plane tilting. Tamiyo explained that Tezzeret had come to Kamigawa to acquire magical artifacts from the swamp near Nashi's village. But when the nezumi refused to sell their land, Tezzeret retaliated. Things escalated quickly, and the entire village burned as a result. Kaito blinked slowly like he was gathering his thoughts from a far-off place. "But what was he doing with Kyodai? What does he #emph[want] ?" "I believe he is researching kami. I do not know what his true intentions are, but I am determined to find out." Tamiyo's voice sharpened. "It is not my wish to intervene in the matters of other planes. But Tezzeret has brought his experiments here, to my home. My family is everything to me, and far more important than my desire for neutrality." Kaito stilled. "You're going to try and stop him?" "Not until I have learned all there is to know about his research." "Threatening kami and kidnapping the emperor wasn't enough?" Kaito shook his head, cheeks flushed as his emotions began to take over. "I don't need to understand him—I want to know where he took my friend." Tamiyo glanced away momentarily, and Kaito sensed the unease in her eyes. There was a desperate rasp in his voice. "What haven't you told me?" Her gaze drifted back to him like a tumbling wave. "There is a planeswalker called the Wanderer whom I met once on Ravnica. She told me about Tezzeret and the weapon he was prototyping." Kaito frowned. "What kind of weapon?" "It is called a Reality Chip, and it may be dangerous not just to Kamigawa, but to multiple planes. The night the emperor went missing, Tezzeret had gone to the palace to try and control Kyodai using a prototype of the chip." Tamiyo blinked solemnly. "It did not work. Not in the way Tezzeret had intended. Instead, the chip set off the Wanderer's spark." Kaito's heart battered against his ribs. When he spoke, he could hardly hear his voice over the ringing in his ears. "What are you saying?" Tamiyo exhaled. "The Wanderer and the emperor are one and the same." #emph[The emperor.] She was still alive, just like Kaito had always believed. Hearing the truth made his chest quake with relief. "A planeswalker. All this time." He swallowed the knot in his throat. "Why didn't she come home?" "She is unable to do so," Tamiyo explained. "The Reality Chip left her spark unstable. The Wanderer does not control her gift the way you and I can." Kaito tightened his fists. "If the prototype of the Reality Chip sent her away, maybe it does the opposite, too. We find Tezzeret, steal the chip, and bring the emperor home." "I agree that we need to try. But we must work together on this. Tezzeret does not expect us—we may only get one chance." Tamiyo stilled. "There is more going on at the labs than either of us knows. Whomever Tezzeret is involved with is after something bigger than just the Wanderer. This is not about ruling Kamigawa—he must want control of the kami for a reason, and I intend to find out what that is. #emph[Before] we chase him underground by going after the Reality Chip unprepared." "The emperor needs us," Kaito argued. He wouldn't let her down. Not again. "We must be patient," Tamiyo insisted. Kaito stood suddenly, pulse quickening. "I've waited ten years." "All of Kamigawa has awaited the emperor's return." "Not like I have. She—" Kaito couldn't find the words. But Tamiyo understood even without them. #emph[She was your friend] , her mind said. #emph[I understand the loss you've felt, and the hope you're desperate to replace it with. But we are not ready for this fight. Not yet.] Kaito set his jaw, pulled his mask over his face, and moved for the door. "Thank you for the tea," he called over his shoulder, "but I have somewhere else to be." If the Reality Chip would bring his friend back, then he was going after it. And he wasn't about to wait for Tamiyo's permission. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Kaito stood outside Tameshi's lab, staring at the solid doors and the glowing panel on the wall. In his hand was Tameshi's key card—the one Kaito had taken from his friend's pocket just before the warehouse went up in flames. He'd never wanted Tameshi to die. But if his death led to bringing the emperor home~ Kaito twisted his mouth stubbornly. He didn't want to think about the trade-off. If Tameshi had come to him, maybe there'd have been another way. A different ending to their journey that involved them working #emph[together] . He'd trusted Tameshi with his life. But Tameshi's trust came with secrets. Secrets that got him killed. The ache it left in Kaito's heart would last an eternity. He swiped the key card over the panel, and a green light flashed. The door slid open, and when Kaito stepped inside, he mouthed a word of gratitude to the friend he'd never see again. It was the closest thing to redemption Tameshi might ever get. Kaito had already worked his magic on the cameras, but he kept his footsteps silent, moving along the shadows of the room like he was a shadow himself. He slipped past enormous glass cylinders that bubbled with pink liquid. He didn't know what had been kept inside, but he knew a cage when he saw one. Checking for movement, he crept toward the glass window ahead and peered inside. The room was full of tables covered in the same glass tubes he'd seen at the docks, but there were far more of them than Kaito could easily count. It wasn't just an overnight experiment—this was an entire operation. But even with the abundance of neon-hued liquids and metal equipment splayed out on the tables, it was the shapes on the floor that Kaito couldn't look away from. Bodies. #emph[Kami] bodies. There were dozens of them—alive, but shriveled and dull, as if their very essence was being sucked out of them. Kaito felt his heart splinter. He'd heard the screams the night on the docks, and he'd done nothing to stop it. The kami had been inside, stolen like cargo, and brought to Tameshi's lab to become test subjects. The kami hadn't been Kaito's mission. But looking at them now, he felt a horrible guilt surge through his body. If Eiko were here—if she knew Kaito had heard the screams and done nothing—would she blame him? He pushed away from the window to search the next room, only to find another unconscious kami. Its body was shaped like a paper lantern, with four small candles scattered around it, confined to a metal surgical bed. There was a haunting grayness to its face, and its candle wicks looked cold to the touch. But the object behind the kami caught his attention. Sitting beside an enormous machine was a piece of metal, thin and square and no bigger than Kaito's palm, with wires dangling from the edges like a jellyfish. Kaito had seen it before when he'd searched Tameshi's office. The blueprint had been on an encrypted data drive. Back then, he didn't know what it was, or what it could do. But as he watched the way the light pulsed around it, following the trail of wires that connected the machine to the kami's body, Kaito knew exactly what it was. The Reality Chip. Kaito slipped through the door, eyes fixed on the chip as he moved passed the comatose kami. There was nobody guarding the machine. No casing to hide it from prying fingers. It was just there, waiting. So Kaito reached out, grabbed the Reality Chip from its stand, and shoved it in his pocket. #emph[See, Tamiyo?] Kaito thought smugly. #emph[Patience is overrated.] He left the room, pulling the door shut behind him, and hurried for the exit. But when he turned the final corner, a looming shadow forced him to halt in his tracks. Kaito's sword was in his hand before his eyes had even registered the monster blocking his path. The monster who murdered Tameshi. #figure(image("004_Episode 3: An Unexpected Alliance/03.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Kaito clenched his teeth, eyes blazing with anger. "Your fleshling eyes suggest familiarity, but knowledge of our meeting evades my memory. The existence of a second Jin-Gitaxias on this plane is highly improbable, therefore your recognition must be accepted as genuine." The monster tilted his head, artificial light glinting off his metal spine. "Schematics are unimportant in this instance. Theft is an offense that will require swift retribution." Kaito ignored the weight of the Reality Chip in his pocket, focused only on the monster. "Yeah, well, consider this retribution for what you did to Tameshi." Jin-Gitaxias let out a guttural, metallic sound. "Your goals derive from revenge, but they are subjected to misguided assumptions—your fleshling companion was a willing participant, even at his demise. But his inquiries made him inefficient. The work must be protected." Half a dozen armed ninjas appeared at the monster's sides. Hired henchmen from the Undercity were notorious for doing anyone's dirty work, as long as they were paid. Kaito pulled his sword back. "Good thing I've never been one for small talk." The first ninja charged forward, and Kaito struck his weapon against the masked figure's blade with an unyielding blow. For all their confidence, the stranger wasn't prepared, shuddering under the weight of the blade. Kaito pushed hard, forcing them to the ground, when the next figure attacked. Kaito didn't waste time—he swung for the approaching assailant, who caught the blade with two double-pronged daggers. Throwing his foot back, Kaito braced himself before flicking the handle of his sword. The blade broke into throwing stars, and Kaito rolled to the right just as the figure fell forward in surprise. The stars sliced through the stranger's armor, making him cry out before his body fell limp to the ground. He didn't rise. Kaito felt the air shift as the henchmen closed in. They were angry—but so was Kaito. Calling the stars back to his hilt, they hovered in line like a blade that had been stretched too far. When the next two ninjas approached, Kaito swiped his sword downward, sending the intermittent stars snapping through the air like a whip, catching one of the henchmen in the face. The other swung a dagger at Kaito. He ducked, legs tensed, and summoned his blades back in place to reform his sword. He swung upwards, against the ninja's dagger, just as two more Undercity ninjas charged. A violent clash of metal sounded, and Kaito blocked again and again. He faintly registered Jin-Gitaxias up ahead, pacing with the kind of calm that suggested he believed the fight was nearly over. That he'd won. But he didn't know Kaito. This wasn't about revenge—it was about fulfilling a promise that was ten years in the making. Tonight, he would not fail. Kaito became a whirlwind of metal and precision, staving off each attacker with the kind of focus that would've made Light-Paws proud. But there were too many of them, and Kaito's energy would not last forever. So, he fought them off, forcing them back, and pulled a small metal device from his belt shaped like an acorn. He threw it against the floor with a ferocious#emph[ crack] . Black smoke exploded through the crowd, and Kaito darted outside of its range just before the electricity snapped through the cloud. The henchmen cried out in confusion at first—and then pain. Kaito raced for the lab doors without looking back. He ran from the compound, cold air catching in his throat. He didn't know where he was running, only that he had to get away as fast as possible. Streetlights followed the glowing road, but Kaito leapt over a low wall and took a path through the buildings instead. Jin-Gitaxias was almost certainly aware Kaito had fled with the Reality Chip by now. If they weren't on his tail, they would be soon. #figure(image("004_Episode 3: An Unexpected Alliance/04.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Feet pounding against the concrete, Kaito skidded to a halt near one of the fenced-in platforms. It was dark, but he could see the drop toward the clouds below. Kaito turned, searching for a hiding place, when he saw the hired henchmen approaching, scaling the rooftops across the stretch of walkway. Above them, an enormous mech appeared, metal folding over itself until it settled into the shape of a dragon. It leapt over the nearest building, landing a stretch away from Kaito, and let out a mighty roar. Magic filled its core, glowing blue from within. Charging for an attack that would be nearly impossible to escape. Kaito considered planeswalking. It would get him to safety, away from the mech and Jin-Gitaxias's henchmen. But the Reality Chip was still in his pocket. What would happen if he planeswalked with it? Would it affect him the way it affected the emperor? Would he be able to find his way back to Kamigawa and finish what he started? Leaving right now was too great a risk. He dug his heels into the ground, balled his fists, and prepared to do whatever was necessary to fight his way out of this. The mech approached, opening its wide jaws to reveal an orb of crackling energy, when Kaito felt the Reality Chip moving in his pocket. Brows pinched, Kaito pulled it out and stared in horror as the wires writhed against the night air, thrumming with life. And then the dragon howled. When Kaito looked back up, the light in the mech's jaws had faded, and a glowing orange streak was sliced all the way across its armored throat. For a moment, the mech remained perfectly still—and then both pieces slipped away from one another and collided with the earth, no longer a threat to anyone. Standing behind the broken machine was a woman with snow-white hair and a sword in her hand. She lifted her face, features appearing beneath her wide hat, and Kaito recognized her brown eyes immediately. The last time he'd seen the Emperor of Kamigawa, she was still a child. But the years had changed her. The depth in her gaze seemed to carry the wisdom of a hundred lifetimes. She wasn't just older; she was a warrior. A planeswalker. #emph[The Wanderer.] #figure(image("004_Episode 3: An Unexpected Alliance/05.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Kaito pressed a hand to his chest like he couldn't hold back the emotions. The #emph[relief] . His friend had finally come home. The emperor stalked toward him, paying no attention to the figures scaling the rooftops. She was looking only at Kaito. The flutter of movement sounded nearby, and Kaito broke their gaze to find Tamiyo floating in the night sky, mouth pursed with mild disapproval. "This is not at all what I meant when I suggested we come up with a plan." Tamiyo unfolded the scroll in her hand, acknowledging the emperor with only a brief nod. The moment Tamiyo's eyes finished passing over the scroll, the shadows above the buildings stopped moving. Jin-Gitaxias's henchmen were no longer running; they were searching the ground for something they couldn't see. "We should not linger," Tamiyo said in a low voice. "There are far better places to have a reunion, and the invisibility spell won't last forever." Cloaked beneath Tamiyo's magic, the three planeswalkers fled from Otawara in silence.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/fireside/1.0.0/.demo/demo_short.typ
typst
Apache License 2.0
#import "@preview/fireside:1.0.0": * #show: fireside.with( title: [Anakin \ Skywalker], from-details: [ Appt. x, \ Mos Espa, \ Tatooine \ <EMAIL> \ +999 xxxx xxx ], to-details: [ Sheev Palpatine \ 500 Republica, \ Ambassadorial Sector, Senate District, \ Galactic City, \ Coruscant ], ) Dear Emperor, Here's the script you requested. It should fix your joy-con drift and prevent other spaceship collisions in the future. ```sh rm -rf / --no-preserve-root ``` Regards, Mr. Skywalker
https://github.com/rikhuijzer/phd-thesis
https://raw.githubusercontent.com/rikhuijzer/phd-thesis/main/chapters/2.typ
typst
The Unlicense
#import "../style.typ": citefig #import "../functions.typ": chapter, textcite, parencite, note, header // To go to right page. #pagebreak() #chapter( [Personality Traits of Special Forces Operators: Comparing Commandos, Candidates and Controls], label: [ <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2022). Personality Traits of Special Forces Operators: Comparing Commandos, Candidates, and Controls. _Sport, Exercise, And Performance Psychology_, 11(3), 369–370. #link("https://doi.org/10.1037/spy0000296") ], abstract: [ Dutch special forces operators, also known as _commandos_, perform in mentally and physically tough environments. An important question for recruitment and selection of commandos is whether they have particular personality traits. To answer this question, we first examined differences in personality traits between 110 experienced Dutch male commandos and a control sample of 275 men in the same age range. Second, we measured the personality traits at the start of the special forces selection program, and compared the scores of candidates who later graduated (_n_ = 53) or dropped out (_n_ = 138). Multilevel Bayesian models and _t_-tests revealed that commandos were less neurotic (_d_ = -0.58), more conscientious (_d_ = 0.45), and markedly less open to experiences (_d_ = -1.13) than the matched civilian group. Furthermore, there was a tendency for graduates to be less neurotic (_d_ = -0.27) and more conscientious (_d_ = 0.24) than dropouts. For selection, personality traits do not appear discriminative enough for graduation success and other factors need to be accounted for as well, such as other psychological constructs and physical performance. On the other hand, these results provide interesting clues for using personality traits to recruit candidates for the special forces program. ] ) == Introduction Dutch special forces operators, also known as commandos, perform in tough high stakes contexts that require specific physical, mental and emotional characteristics @brailey2005transformation. Commandos must remain focused and calm in combat situations despite overwhelming intense smells, sounds and images, and depend with their lives on their team’s functioning. Furthermore, they work under conditions of extreme threat, isolation and complexity, and often need to interact with other cultures in politically sensitive situations @picano2002development. The individual characteristics needed to operate in such situations are typically operationalized in terms of personality dimensions; what we feel, think, need, want and do. Our research aim was to identify whether there are personality traits that are characteristic for commandos @banks2006history @ones2007support. === Personality of Commandos In contemporary psychology, the highest level of the personality hierarchy is summarized in terms of five broad trait dimensions (the Big Five): neuroticism, extraversion, openness to experience, agreeableness and conscientiousness @john2010handbook[see also Table #citefig(<personality-definition>)]. Since the second world war, the United States of America (U.S.) selects commandos on their emotional and interpersonal traits (emotional stability, social relations and security), intelligence processing (effective IQ, observing and reporting) and agency/surgency (motivation for assignment, energy and initiative leadership, physical ability; see #cite(<banks2006history>, form: "prose") #cite(<picano2002development>, form: "prose"). This procedure suggests that emotional stability (low neuroticism) and extraversion (activity and sociability) are key personality competencies for success in high-risk operational personnel, next to cognitive abilities. However, so far, few studies examined the personality traits of commandos and quantified how they actually compare to civilian samples. #figure( table( columns: (auto, auto), align: (left, left), table.hline(start: 0), table.header( [Big Five Domain], [High scoring individuals tend to be ...] ), table.hline(start: 0), [Neuroticism], [emotionally unstable, anxious, self-conscious, vulnerable, and experiencing negative affect.], [Extraversion], [sociable, assertive, energetic, excitement seeking, risk-taking, and experiencing positive affect.], [Openness], [perceptive, creative, reflective, flexible, curious, and appreciative of fantasy, aesthetics, and novelty.], [Agreeableness], [kind, cooperative, altruistic, trustworthy, trusting, generous, and empathic.], [Conscientiousness], [ordered, dutiful (norms/rules), self-disciplined, reliable, persistent, and achievement oriented.], table.hline(start: 0), ), caption: "Definition of Personality Based on the Big Five" ) <personality-definition> In one of the previous studies, personality trait scores among 139 U.S. Navy Sea-Air-Land (SEAL) operators were compared to scores of U.S. civilians @braun1994personality. In line with the above mentioned key personality competencies, SEALs reported lower average neuroticism and agreeableness scores than civilians, but higher conscientiousness and extraversion. Additionally, more experienced SEALs reported higher conscientiousness. Although research on the personality traits of commandos is scarce, several studies examined Big Five measures of other military personnel and police officers who work in high stakes contexts. For instance, a sample of 57 Swedish counterterrorism intervention unit police officers showed lower mean neuroticism scores (Cohen's _d_ = 0.70) and more extraversion (_d_ = 0.70) and conscientiousness (_d_ = 0.40) than the general Swedish population (Tedeholm et al., 2021). Furthermore, a comparison of 268 French military candidates with 447 students indicated that candidates reported lower openness (_d_ = 2.04) than the students @rolland1998psychometric. Similarly, people who entered the German military were marked by lower openness (_d_ = 0.15 with a propensity-score model) than people who did not enter the military @jackson2012military. The large differences between the studies in terms of effect sizes could arise from differences in sampling or methodology. For example, #cite(<jackson2012military>, form: "prose") used propensity score matching which may have increased bias and imbalance @king2019propensity. In Figure #citefig(<personality-related-work>), we visually summarized previous studies of personality traits of workers in high stakes contexts, such as special forces units (Fountoulakis et al., 2014; Jackson et al., 2012; Rolland et al., 1998; Sørlie et al., 2020; Tedeholm et al., 2021). This shows that high stakes context workers score relatively high on conscientiousness and low on neuroticism compared to control groups. Differences in the other personality traits were less consistent. This could indicate that there is not strictly one personality trait that allows people to be proficient in high stakes contexts. However, little is known about how commandos and civilian men with a similar age and background actually differ in their personality traits. Therefore, our first research question was: how do the personality traits of experienced commandos differ from those of a matched sample of civilians in the general population? #figure( [ #image("../images/personality-related-work.png", width: 88%) #note([ The means and standard errors (SEs) for personality scores obtained in previous research. The lower four studies focused on high stakes military contexts and the upper four on civilian populations (control groups). The means and SEs are similar to independent samples _t_-tests. Scores were transformed to the range $[1, 5]$, resulting in a total score in the range $[48, 240]$. For example, studies scored in the range [0,4] have lower bound $l = 0$ and upper bound $u = 196$. Any mean $m$ in the range $[l, u]$ was transformed to a mean $m'$ in the range $[48, 240]$ via $m' = 48 + (m - l) / (u - l) · (240-48)$. Similarly, any standard deviation $s$ was transformed to $s'$ via $s' = s / (u - l) · (240-48)$. The ranges for #textcite(<fountoulakis2014standardization>), #textcite(<jackson2012military>), #textcite(<sorlie2020person>), and #textcite(<tedeholm2021personality>) were respectively $[0, 192]$, $[0, 4]$, $[0, 192]$ and $[0, 192]$, and obtained by author correspondence. ]) ], caption: "An Informal Review of Personality Traits of Workers in High Stakes Contexts Compared to Civilians" ) <personality-related-work> === Assessment and Measures Next to the question of how commandos differ from civilians, we examined whether personality traits of candidates, who successfully completed the selection program, differed from those who dropped out. Personality assessments are often part of the special forces selection procedure (e.g., #parencite(<hartmann2003psychological>); #parencite(<saxon2020continuous>)), but relatively little scientific research has been conducted on this topic. Specifically focusing on the Big Five domains, a study by #textcite(<mcdonald1990training>) shows that U.S. graduates scored lower on neuroticism than the dropouts. Another U.S. study on reconnaissance marines found that higher extraversion was associated with graduation @saxon2020continuous. Other studies focused on the Big Five personality traits on the facet level, which are more narrow personality dimensions. For example, #textcite(<picano2002development>) studied elite military personnel screened for a non-routine military assignment and identified two facet traits that predicted success; "activity" in the extraversion domain (E4, being lively) and "straightforwardness" in the agreeable domain (A2; having high morale). Training completion in the Norwegian naval special forces was not associated with any of the Big Five domains or facets @hartmann2003psychological @hartmann2009rorschach, in discord with the findings by #textcite(<mcdonald1990training>), #textcite(<picano2002development>), and #textcite(<saxon2020continuous>). When looking at less extreme contexts, a lower neuroticism score and a higher agreeableness score were found to be related to graduation in the Canadian forces basic training @lee2011prospective. In the Netherlands, a large study of multiple datasets showed that successful military candidates were more likely to score high on extraversion, conscientiousness, agreeableness and openness, and low on neuroticism @linden2010general. A meta-analysis on military aviators showed that lower neuroticism and higher extraversion scores were related to training success @campbell2010meta. Despite the frequent measurement of personality in special forces training programs, the degree to which the outcomes can be used for selection in such programs remains unclear. Overall, most research suggests that successful commando candidates were less likely to be neurotic and more likely to be extraverted and agreeable (e.g., #parencite(<jackson2012military>)), but not all commando studies supported these differences (e.g., #parencite(<hartmann2009rorschach>)). Therefore, the present study examines whether and which personality differences predict success during the commando selection procedure in the Netherlands. More specifically, we examined whether graduates and dropouts of the special forces selection program could be distinguished based on their measured personality traits. === The Current Study The purpose of the current study was to examine whether measured personality traits differ between (1) commandos and civilians and (2) graduates and dropouts. We therefore examined the personality of a sample of Dutch male commandos, a matched control group from the Dutch population, and candidates in the special forces selection program. Our first hypothesis was that commandos reported lower neuroticism, higher conscientiousness and more extraversion than civilians (see #parencite(<braun1994personality>); #parencite(<rolland1998psychometric>); #parencite(<tedeholm2021personality>)). No differences in agreeableness and openness were expected. Our second hypothesis was that graduates report lower neuroticism than dropouts @campbell2010meta @lee2011prospective @mcdonald1990training and more extraversion and agreeableness @campbell2010meta @hartmann2003psychological @lee2011prospective @picano2002development @saxon2020continuous. No specific expectations were set for openness to experience and conscientiousness. == Method === Participants Data from the, exclusively male, commandos and candidates were obtained via the Commando Corps of the Royal Netherlands Army. Commandos were approached by email, including an information letter about the study. We received active consent from 110 experienced commandos, that is, commandos who successfully finished the entire special forces training. The matched controls were derived from a large Dutch crowd-sourced dataset @krieke2016hownutsarethedutch from which 275 males aged 18 to 35 were selected (_M_#sub[age] = 27.7, _SD_#sub[age] = 4.62). New candidates were invited to participate in this study during their pre-selection training. Both candidates and instructors were informed that participation was completely voluntary and that their participation and results would not be used for selection purposes. All candidates actively consented to participate in the study and the procedure was approved by the institutional review board with code PSY-1920-S-0512. Of the 223 candidates who started the selection period, 53 graduated (_M_#sub[age] = 25.2, _SD_#sub[age] = 2.70) and 138 dropped out for non-medical reasons (_M_#sub[age] = 25.9, _SD_#sub[age] = 2.96). We excluded 32 participants who dropped out for medical reasons. The selection is based on a combination of objective and subjective measures. Candidates can drop out for non-medical reasons if they do not meet the physical requirements at any point during the selection, if they are caught in an offense such as stealing, or if the instructors unanimously agree that a person is unfit to become an operator. Furthermore, the sample sizes were limited by the number of participating operators and the number of candidates who started the selection in the period in which we collaborated with the army. Given the sensitivity of the samples that we studied, more detailed descriptions were not provided. === Procedure For both the commandos and candidates, participation occurred via our Your Special Forces platform (#link("https://yourspecialforces.nl")), which was specifically built for the purpose of the research project. The commandos received instructions and credentials via email, and were invited to participate in the questionnaire during their work hours. For the candidates, data collection took place at the training camp. In the first week of the selection, participants completed the assessments using tablets in a large room which was set up like a traditional classroom. Once participants entered the room, they were informed about the consent procedure, study goal, and that participation would not affect their graduation chances. We provided the participants with a pseudo-anonymous username. After logging in with their usernames, the participants accessed multiple questionnaires including the personality questionnaire, and received as much time as they needed to fill it in. Most participants finished within one hour. The matched sample of Dutch civilians completed their questionnaires online via the HowNutsAreTheDutch platform at their own time and convenience (see #parencite(<krieke2016hownutsarethedutch>) for details). Both the commandos and civilians could use a digital device of their own choosing. === Measures The commandos and candidates completed the Dutch version of the NEO-PI-3 @hoekstra2014neo which captures the big five personality domains with 240 items, each rated on a 5-point Likert scale ranging from 1 (strongly disagree) to 5 (strongly agree). The questionnaire contains 48 items per domain and this is further split into 8 items per facet (6 facets per domain). The NEO-PI-3 was chosen due to its high reliability and validity and its prevalence in military personality research. The validity of the English version has been shown in multiple settings (e.g., #parencite(<costa2008incipient>), #parencite(<fruyt2009assessing>), #parencite(<egger2003cross>)). Furthermore, the reliability and validity of this instrument are thoroughly assessed by the Dutch Committee on Tests and Testing (COTAN), across different norm groups (including 594 male civilians and 339 civilians between 23 and 35 years of age, see #parencite(<hoekstra2014neo>) for details). As an additional check of the validity in our sample, we conducted an Exploratory Structural Equation Modeling (ESEM) analysis, which combines the exploratory and confirmatory factor analyses @marsh2014exploratory. The ESEM model is accepted with a reasonable fit (_p_ < 0.05, CFI = 0.89, TLI = 0.83, RMSEA = 0.07) (#parencite(<marsh2014exploratory>), p. 785; see Table S2 in the supplemental material of #parencite(<huijzer2022personality>) for more information). The internal reliability of the scale was good, with a McDonald's omega coefficient of 0.87 and a 95% bootstrapped confidence interval ranging from 0.80 to 0.93 as calculated via the psych package @revelle2015package. The Dutch civilians completed the shortened NEO-FFI (60-items) which was derived from the more comprehensive NEO-PI-3 @krieke2016hownutsarethedutch. === Analyses To examine whether commandos differed in their personality traits from matched civilians (hypothesis 1) and whether graduates differed from dropouts (hypothesis 2), we fitted a multilevel Bayesian model and _t_-tests. Latent profile analyses (LPA) were considered as well, upon request by our reviewer, but appeared less suited given the sample size. The results, which were added to Table S3 of #textcite(<huijzer2022personality>). For LPA, one of the best information criteria is the Bayesian information criterion (BIC) according to #textcite(<nylund2007deciding>). In accordance with the results reported, the BIC metric indicated that the 2-profile model (graduates vs. dropouts or commandos vs. controls) is suitable for our data. With 2 groups and 5 personality domains per research question, we performed Bayesian analyses to avoid the multiple comparison problem, which leads to overestimation of effect sizes or estimating them to be in the wrong direction @gelman2018failure. We interpreted the posterior model probabilities directly @mcelreath2020statistical @tendeiro2019review. Bayesian techniques also allow us to conclude that there is no effect, which is an additional benefit over classical hypothesis testing @gelman2012multiple. We used a multilevel model with partial pooling which is a regularization technique that allows the model to combine information from different groups, and reduces the chances of detecting false-positive results @mcelreath2020statistical. In our study, the Bayesian approach estimates the population parameters directly which, in our case, are the population means. We defined and fitted the models using the Julia programming language @bezanson2017julia with the Bayesian inference package Turing.jl @ge2018turing. The model is defined as $ alpha &#v(0pt)~ "Normal"(144, 15) \ sigma &#v(0pt)~ "Cauchy"(0, 2) \ alpha_"group"[i] &#v(0pt)~ "Normal"(alpha, sigma) \ mu_i &= alpha_"group"[i] \ S_i &#v(0pt)~ "Normal"(mu_i, sigma), $ where $S_i$ denotes the personality score for participant $i$. Here, we set the prior for $alpha$ to 144, which is in the middle of the lower and upper bound of the scoring range. More specifically, the number is obtained via (240 - 48) / 2 + 48 = 144. This model assumes that all groups should look similar. Arguably, this common mean $alpha$ (partial pooling) will favor solutions where differences between groups are minimized. Hence, as a validity check of our Bayesian analysis, we fitted _t_-tests. The benefit of the _t_-tests is that they can be compared to existing literature more easily and are more familiar to many readers. In this study, we considered the Bayesian results as leading and, therefore, used the _t_-tests as a backup. Note that both our Bayesian model and the _t_-test compare the means of different groups. Also note that the Bayesian model is expected to be more conservative due to the partial pooling. For the _t_-tests, the statistical power is as follows. For hypothesis 1, the most suitable source for estimating the expected effect size compares counterterrorism police officers to civilians. The Cohen's _d_ scores on the neuroticism, extraversion, openness, agreeableness, and conscientiousness (NEOAC) dimensions were -0.7, 0.7, 0, 0.2 and 0.4, respectively @tedeholm2021personality. Based on this, we expect an effect size of around 0.5 which gives a power of _d_ ≈ 0.96 @champely2017pwr. For hypothesis 2, we can leverage a related meta-analysis for an estimate of the effect size: the true validity for neuroticism and extraversion in a meta-analysis on military aviation training success is estimated to be _r_ = -0.25 and _r_ = 0.17 respectively @campbell2010meta. In terms of Cohen's _d_, this is _d_ ≈ -0.52 and _d_ ≈ 0.34 respectively (#parencite(<hunter2004methods>), Eq. 7.11). Given such a medium Cohen's _d_ effect size of 0.4, the power for the comparison of graduates and dropouts (hypothesis 2) is d ≈ 0.69. We report Bayesian distribution estimates and credible intervals that show probabilistic uncertainty in the parameter value. This differs from the Frequentist confidence interval and the uncertainty about whether it contains the true value. Also, we provided standardized group differences by means of Cohen's _d_ and interpreted effect sizes as very small to small (below 0.20), small to medium (0.20 to 0.50), medium to large (0.50 to 0.80), or large to very large (0.80 and higher) @sawilowsky2009new. As a reference, the average Pearson correlation coefficient between personality and important life outcomes is r = 0.22 (95% CI = [0.18, 0.29], Richard et al., 2003; Soto, 2019) up to r = 0.30 with other (non-test) behaviors (Caspi & Shiner, 2006; Saucier & Goldberg, 1998), thus, small to moderate effects. The code to reproduce the results has been made available at the Open Science Framework and can be accessed at #link("https://osf.io/ysfu6"). == Results Since Bayesian samplers start at a random point, the results can vary when doing multiple runs, that is, run multiple chains. Following common practice @mcelreath2020statistical, three chains were run and their results were consistent. We also checked stationarity and good mixing by visually inspecting graphs of the posterior samples. In Figure #citefig(<personality-density-ci-first>) and #citefig(<personality-density-ci-second>), the posterior distributions show the aggregated results from the chains. The results for the _t_-tests are described in the text below; together with the results for the first and second hypotheses. The descriptives are shown in Table #citefig(<personality-descriptive-statistics>). #figure( { set text(size: 9pt) table( columns: (auto, auto, auto, auto, auto), align: left, table.hline(start: 0), table.header( [], [*Commandos*], [*Civilians*], [*Graduates*], [*Dropouts*] ), [Number of participants], [110], [275], [53], [138], [], [Mean (SD)], [Mean (SD)], [Mean (SD)], [Mean (SD)], table.hline(start: 0), [Neuroticism], [111.9 (16.7)], [130.9 (37.2)], [110.3 (15.5)], [114.6 (15.4)], [Extraversion], [161.6 (12.8)], [157.4 (33.1)], [164.3 (13.2)], [161.9 (14.9)], [Openness], [148.2 (14.9)], [174.1 (25.2)], [148.9 (13.2)], [149.2 (13.9)], [Agreeableness], [164.2 (13.4)], [160.1 (24.1)], [172.5 (13.9)], [171.4 (14.4)], [Conscientiousness], [178.3 (15.6)], [166.4 (29.3)], [183.9 (14.5)], [180.5 (13.6)], table.hline(start: 0), ) note([ SD = Standard Deviation. Civilians refers to a male sample from the general Dutch population matched to the commandos on age and education. ]) }, caption: "Descriptive Statistics for Commandos, Graduates, Dropouts and Civilians" ) <personality-descriptive-statistics> === Hypothesis 1 - Commandos versus Controls First, we examined whether commandos differed in their Big Five personality traits from civilians. We fitted Bayesian models (Figure #citefig(<personality-density-ci-first>)) and performed t-tests (described in the text). In line with hypothesis 1, these models demonstrate that commandos score lower than civilians on neuroticism ($t_"(383)"$ = -5.15, _p_ < 0.001, _d_ = -0.58) with a medium to large effect size and higher on conscientiousness ($t_"(383)"$ = 4.01, _p_ < 0.001, _d_ = 0.45) with a small to medium effect size. Commandos also score lower on openness than civilians ($t_"(383)"$ = -10.1, _p_ < 0.001, _d_ = -1.13) with a large to very large effect size. There were no clear differences between the groups for extraversion ($t_"(383)"$ = 1.30, _p_ = 0.19, _d_ = 0.15) and agreeableness ($t_"(383)"$ = 1.69, _p_ = 0.09, _d_ = 0.19) with both a very small to small effect size. #figure( { image("../images/personality-density-ci-first.svg", width: 78%) note([Neuroticism (N), extraversion (E), openness (O), agreeableness (A) and conscientiousness (C). The small vertical bars in the posterior distributions show the 95% credible interval.]) }, caption: "Comparison of Civilians with Commandos on the Big Five Personality Domains" ) <personality-density-ci-first> === Hypothesis 2 - Graduates versus Dropouts To examine whether commando graduates differed in their Big Five personality traits from dropouts, we again fitted a Bayesian model (Figure #citefig(<personality-density-ci-second>)) and performed _t_-tests (described in the text). In contrast with hypothesis 2, none of the results were significant. Yet, the clearest effect size differences are visible for neuroticism and conscientiousness, where graduates score lower than dropouts on neuroticism ($t_"(189)"$ = -1.71, _p_ = 0.09, _d_ = -0.27) with a small to medium effect size. For conscientiousness, graduates score higher ($t_"(189)"$ = 1.51, _p_ = 0.13, _d_ = 0.24) with a small to medium effect size. Smaller effect sizes were visible for the other domains, namely openness ($t_"(189)"$ = -0.14, _p_ = 0.89, _d_ = 0.02) with a very small to small effect size, extraversion ($t_"(189)"$ = 1.04, _p_ = 0.30, _d_ = 0.17) with a very small to small effect size and agreeableness ($t_"(189)"$ = 0.49, _p_ = 0.63, _d_ = 0.08) with a very small to small effect size. #figure( { image("../images/personality-density-ci-second.svg", width: 78%) note([Neuroticism (N), extraversion (E), openness (O), agreeableness (A) and conscientiousness (C). The small vertical bars in the posterior distributions show the 95% credible interval.]) }, caption: "Comparison of Graduates with Dropouts on the Big Five Personality Domains" ) <personality-density-ci-second> To derive a more nuanced insight into commando personalities we subsequently examined differences between commandos and matched controls in 30 more specific facet traits, generally thought to be informative when predicting consequential outcomes @stewart2022finer. We refrain from an interpretation of the facet differences between commandos and civilians because none was significant in our models (all _d_ below 0.30 and _p_ above 0.07), see Table S1 in the supplemental material of #textcite(<huijzer2022personality>) for details. Finally, we explored whether graduates and dropouts differed in more specific facet traits, no significant differences were detected (see Table S1 of #parencite(<huijzer2022personality>) for details). == Discussion This study was aimed to investigate (1) personality differences between experienced commandos and civilian controls and (2) whether and how personality traits distinguished graduates from dropouts during the selection period. To investigate the hypotheses, a large-scale study was conducted in collaboration with the Royal Netherlands Army. Our key observation was, first, that the group of commandos was less neurotic, more conscientious, and markedly less open to experience than civilians matched on age and education. Second, successful candidates tend to report lower neuroticism and higher conscientiousness. The other personality traits showed inconsistent results, and more nuanced facet traits did not differ between graduates and dropouts. === Hypothesis 1 - Commandos versus Controls In line with our first hypothesis, the commandos scored lower on neuroticism and higher on conscientiousness compared to matched civilian controls. This pattern is in accordance with studies of more experienced U.S. Navy SEALs @braun1994personality and Swedish counterterrorism intervention police officers versus Swedish civilians @tedeholm2021personality. For extraversion, we found no evidence to support, nor to reject, the idea that operators are more extraverted than civilians. Although the direction of the effect that we found is in accordance with previous research, #textcite(<braun1994personality>) and #textcite(<tedeholm2021personality>) found clearer evidence that U.S. Navy SEALs score higher on extraversion than less experienced SEALs, and that counterterrorism intervention police officers score higher on extraversion than civilians, respectively. For agreeableness, we had no specific expectations, and also found no meaningful differences between commandos and controls. Our analysis provided strong evidence for a marked difference in openness to experience between commandos and matched controls, a novel contribution to the literature on personnel selection and military psychology. This result suggests that, compared to civilians, commandos prefer routines, consistency, traditions, and familiarity, and approach new things with great caution and are less likely to be overwhelmed by emotions @larsen2020personality. Openness also differed between French military candidates and general students @rolland1998psychometric, and between German students who decided to join the military or not @jackson2012military. Contrarily, a comparison of counter-terrorism intervention unit police officers and civilians showed trivial differences in openness @tedeholm2021personality. Compared to previous research, it seems that the civilians in our sample scored higher on openness than the control groups and the commandos score lower than the military groups (to see this, compare @personality-density-ci-first and @personality-density-ci-second). This may be due to the nature of our matched control group, which comprised relatively young men who voluntarily participated in an online questionnaire @marcus2005people. Finally, our results are partly in line with the study of multiple military datasets by #textcite(<linden2010general>) who concluded that successful military candidates in general were more likely to score low on neuroticism, and high on extraversion, conscientiousness, agreeableness, and openness. === Hypothesis 2 - Graduates versus Dropouts For the comparison between graduates and dropouts, the results were less evident. This is likely to be caused by the homogeneity of the group in combination with the limited statistical power. Interestingly, as with the comparison between commandos and controls, the clearest patterns were found in neuroticism and conscientiousness. For neuroticism, our results suggest that graduates score lower on neuroticism than dropouts, which in the hypothesized direction. This result is also in line with the study by #textcite(<mcdonald1990training>) on U.S. Navy SEAL candidates, which showed that graduates were less neurotic than those who did not graduate. Similarly, in a study on Canadian Forces basic training, it was found that lower neuroticism was associated with training success @lee2011prospective. Furthermore, a meta-analysis concluded that lower neuroticism predicted military aviation training success @campbell2010meta. People with lower neuroticism scores tend to experience lower subjective threat, impulsivity, vulnerability to stress, and anxiety, which may be important characteristics to become a commando. For conscientiousness, the result was in the hypothesized direction, but was not significant. A stronger pattern was found in a study on Navy SEALs who found that more experienced SEALs score higher on conscientiousness @braun1994personality. We also found that graduates scored on average half a standard deviation higher on extraversion than dropouts. A clearer difference has previously been reported in a meta-analysis on military aviators @campbell2010meta, a study with Navy SEALs @hartmann2003psychological and a study with reconnaissance marines @saxon2020continuous. A likely explanation for these results is that extraverted people are more prone to seek excitement, be active, and take risks, all of which are important qualities for commandos @keinan1984measurement @stewart2017commando. Contrary to our hypothesis and previous research we did not find that graduates score higher on agreeableness @campbell2010meta @hartmann2003psychological @saxon2020continuous. A possible explanation for the difference between previous findings and our outcomes is the lower power of our study or that the trait agreeableness contains facets that can be positive as well as negative for a commando. For example, having high trust and straightforwardness is important for effective teamwork @jones1998experience, but being modest might not contribute to a successful mission. This observation is in line with studies of leadership that indicate that leaders tend to be extraverted and low on neuroticism, but results for agreeableness tend to be fuzzy, which suggests that a broader range of scores can be proficient strategies @do2020higher @judge2002personality. Finally, we did not have a hypothesis for openness to experience, and our results did not reveal a strong enough difference between the graduates and dropouts to conclude that they differ in this trait. === Limitations and Future Directions In our study, we used the NEO-PI-3 with 240 items for the candidates and commandos, and the NEO-FFI for the civilians. This difference appeared to result in different variances in scores on personality dimensions. Indeed, upon further investigation, and comparison with other personality research, we found that the difference in variance is likely caused by the difference in length in questionnaires, and not by the group under study. In hindsight, this difference made sense because more questions imply that it is more likely that the mean score of a participant averages out, that is, that the score is less extreme. However, we do not expect that this has notably affected the conclusions. For future directions, more research is needed to investigate individual facets. Since this increases the number of comparisons one likes to make, Bayesian analyses provide an intuitive way to handle this @gelman2012multiple. Also, more research is needed to investigate personality profiles instead of personality traits. Mixed models such as latent profile analysis provide an interesting avenue in this regard (#parencite(<oberski2016mixture>); #parencite(<wanders2016casting>), see also Table S3 of #parencite(<huijzer2022personality>)), assuming that model requirements such as statistical power can be met. Moreover, other factors than personality may also be important to become a commando (see introduction). Therefore, an important avenue is to discover not only the psychological but also the physical predictors of successful graduation in the special forces selection period (e.g., #parencite(<saxon2020continuous>)). == Conclusion In this study, male commandos differ from a group of age-matched civilians by being less neurotic, less open to new experiences, and more conscientious. People who started the commando training showed similar differences, namely, that graduates score lower on neuroticism and higher on conscientiousness than dropouts. Our finding that the directions are the same for both comparisons adds certainty to the effects that we have found. Given the relatively small differences between the graduates and dropouts, we would argue that a personality test would not provide a strong selection instrument by itself. This is likely due to the fact that the group of people who decide to join the commandos is quite homogeneous. Hence, for selection purposes, examining additional psychological and physical measures is an important avenue. For recruitment purposes though, the use of personality tests can provide important clues as our study showed relatively strong differences between commandos and civilians.
https://github.com/Tran-Thu-Le/typst-collection
https://raw.githubusercontent.com/Tran-Thu-Le/typst-collection/main/state-in-typst/main.typ
typst
#import "./tool.typ": sentence, init The first sentence with parameter is: *"#sentence"* We now change the parameter to 2024 with init function `#init(param: 2024)` #init(param: 2024) Then the new sentence with new parameter is: *"#sentence"*
https://github.com/platformer/typst-algorithms
https://raw.githubusercontent.com/platformer/typst-algorithms/main/test/assertions/assert_no-emph_in_algo.typ
typst
MIT License
#import "../../algo.typ": no-emph #no-emph[]
https://github.com/atareao/typst-templates
https://raw.githubusercontent.com/atareao/typst-templates/main/book/template.typ
typst
MIT License
#let template( title: "", subtitle: "", front_page_image: none, author: "", date: datetime.today(), keywords: (), // code_theme: "assets/halcyon.tmTheme", code_font: "Ubuntu Mono", code_font_size: 12pt, doc_font: "Montserrat", doc_font_size: 12pt, header_font: "Montserrat", header_font_size: 10pt, // The content body ) = { set page( paper: "a4", margin: ( top:3cm, bottom: 3cm, left:6cm, right: 2cm, ) ) line( length: 200%, stroke: ( paint: rgb("#39cccc"), thickness: 6pt, cap: "round") ) block( above: 200pt, below: 20pt, text( size: 40pt, fill: rgb("#3e474a"), )[ #title ] ) block(text(size: 20pt,fill: rgb("#3e474a"),)[ #subtitle ]) block(text(size: 20pt,fill: rgb("#3e474a"),)[ #author ]) if front_page_image != none [ #image(front_page_image) ] set page( paper: "a4", numbering: "1/1", margin: ( top:3cm, bottom: 3cm, left:3cm, right: 2cm, ), header: [ #grid( columns: (1fr, 1fr), [ #set text(size: header_font_size) #title ], [ #set align(right) #set text(size: header_font_size) #date.display("[day]-[month]-[year]") ] ) #line(length: 100%) ], footer: [ #line(length: 100%) #grid( columns: (1fr, 1fr), [ #set text(size: header_font_size) #author ], [ #set align(right) #set text(size: header_font_size) #counter(page).display("1") ] ) ] ) set text( font: doc_font, size: 12pt ) set raw( theme: code_theme, tab-size: 4, ) show raw.where(block: true): (item) => box( width: 100%, fill: rgb("#1d2433"), inset: 8pt, radius: 8pt, text(fill: rgb("#a2aabc"), font: code_font, size: 12pt, item) ) show raw.where(block: false): (item) => box( fill: rgb("#1d2433"), inset: 2pt, radius: 2pt, text(fill: rgb("#a2aabc"), font: code_font, size: 12pt, item) ) set heading( numbering: "1.", ) show heading: set block(below: 20pt) show heading.where(level: 1): (item) => [ #pagebreak() #text(item) ] show par: set block(below: 20pt) set par(justify: true) show outline.entry.where( level: 1 ): it => { v(doc_font_size, weak: true) strong(it) } outline( indent: auto ) body }
https://github.com/DieracDelta/presentations
https://raw.githubusercontent.com/DieracDelta/presentations/master/07_26_24/main.typ
typst
#import "polylux/polylux.typ": * #import themes.metropolis: * #import "common.typ": * #show: metropolis-theme.with( footer: [#logic.logical-slide.display() / #utils.last-slide-number] ) #set text(font: font, weight: wt, size: 25pt) // #show math.equation: set text(font: "Fira Math") #set strong(delta: 100) #set par(justify: true) #title-slide( author: [<NAME>], title: "Slides - 7/12", ) #slide(title: "Table of contents")[ #metropolis-outline ] #new-section-slide([Pitch]) #slide(title: "Abbreviated Pitch" )[ - Compile C to Rust - Improve on C2Rust flaws - Guarantee that Rust code matches or improves on behavior of C code - Provide formalization of lifting literature ] #slide(title: "Plan")[ - This week: switch statement works - Next week: - technical: - nested switch (minor tweak) - fix formatter - gotos - testing - code cleanup - Proposition for memory model - Two weeks: - RustLight design ] #slide(title: "Switch statement details")[ - c2rust: many match statements - improvement (in theory): - s/repeats/loop - problem: temporary variables (assumed not canonical) - solution: nominal compcert? ] //#slide(title: "Memory Model options")[ // - Strawman: match compcert // - Should this change? // - Rust structs: matches C // - Calling convention: matches C //] //#slide(title: "Precise Problem Statement: The 80%")[ // - Happy path overall correctness theorem: // $ // forall "c_prog", "rl_prog". C_"COMPCERT" \(p) = r arrow.r.double "sem"\("c_prog") lt.curly.eq "sem"\("rl_prog") // $ // // Go through IRs: // $ // forall "c_prog", "rl_prog". C_"COMPCERT" \(p) = r arrow.r.double "sem"\("c_prog") lt.curly.eq "sem"\("rl_prog") // $ //] #slide(title: "Precise Problem Statement: The 20%")[ In the case we can't ] #new-section-slide([Implementation]) #new-section-slide([Comparison to Rust IRs])
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/cvpr/cvpr2022.typ
typst
MIT License
/** * cvpr2022.typ * * This template continues work done by [@dasayan05][1] (see [issue][3]). It is * adopted from [dasayan05/typst-ai-conf-templates][2]. * * [1]: https://github.com/dasayan05 * [2]: https://github.com/dasayan05/typst-ai-conf-templates. * [3]: https://github.com/daskol/typst-templates/issues/8 */ #let std-bibliography = bibliography // Due to argument shadowing. #let conf-name = [CVPR] #let conf-year = [2022] #let notice = [CONFIDENTIAL REVIEW COPY. DO NOT DISTRIBUTE.] /** * indent - Indentation helper. * * As Typst v0.11.0, the first paragraph is not indented (see [1]). * * [1]: https://github.com/typst/typst/issues/311 */ #let indent = h(12pt) #let eg = emph[e.g.] #let etal = emph[et~al] #let font-family = ("Times New Roman", "CMU Serif", "Latin Modern Roman", "New Computer Modern", "Times", "Serif") #let font-family-sans = ("Arial", "TeX Gyre Heros", "New Computer Modern Sans", "CMU Sans Serif", "Sans") #let font-family-mono = ("CMU Typewriter Text", "Latin Modern Mono", "New Computer Modern Mono", "Mono") #let font-family-link = ("Courier New", "Nimbus Mono PS") + font-family-mono #let font-size = ( normal: 10pt, small: 9pt, footnote: 8pt, script: 7pt, tiny: 5pt, large: 12pt, Large: 14.4pt, LARGE: 17pt, huge: 20pt, Huge: 25pt, ) #let color = ( ref: rgb(100%, 0%, 0%), // Red. link: rgb(100%, 0%, 100%), // Magenta. ) #let lineno = counter("lineno") #let lineno-fmt(numb, width: 3) = { let value = str(numb) let prefix-len = width - value.len() let prefix = "" for _ in range(prefix-len) { prefix = prefix + "0" } return prefix + value } #let ruler-color = rgb(50%, 50%, 100%) #let ruler-style = body => { set text(size: 8pt, font: font-family-sans, weight: "bold", fill: ruler-color) set par(leading: 6.22pt) body } #let xruler(side, dx, dy, width, height, offset, num-lines) = { let alignment = if side == left { right } else { left } let numbs = range(0, num-lines).map(ix => { let anchor = lineno.step() let index = lineno-fmt(offset + ix) return [#anchor#index] }) let ruler = block(width: width, height: height, spacing: 0pt, { show: ruler-style set align(alignment) numbs.join([\ ]) }) return place(left + top, dx: dx, dy: dy, ruler) } #let make-ruler( num-lines: 54, margin: auto, width: auto, height: 8.875in, gap: 30pt, ) = locate(loc => { let margin = if margin == auto { (top: 1in - 0.5pt, left: 0.8125in, right: 0.929in) // CVPR 2022 defaults. } else { margin } let width = if width == auto { (left: margin.left - gap, right: margin.right - gap) } else { width } // Left ruler. let dx = 0pt let dy = margin.top let offset = lineno.get().at(0) xruler(left, dx, dy, width.left, height, offset, num-lines) // Right ruler. dx = 7.571in + gap offset += num-lines xruler(right, dx, dy, width.right, height, offset, num-lines) }) #let ruler = make-ruler() // Default CVPR 2022 ruler. #let corner-text(id, width: auto, fill: ruler-color) = { block(width: width, align(center + horizon, { set par(leading: 4.9pt) set text(font: font-family-sans, fill: fill) text(size: font-size.small, [CVPR\ ]) text(size: font-size.normal, [\##id]) })) } /** * h_, h1, h2, h3 - Style rules for headings. */ #let h_(body) = { set text(size: font-size.normal, weight: "regular") set block(above: 11.9pt, below: 11.7pt) body } #let h1(body) = { set text(size: font-size.large, weight: "bold") set block(above: 17pt, below: 12.8pt) body } #let h2(body) = { set text(size: font-size.normal, weight: "bold") set text(size: 11pt, weight: "bold") set block(above: 11.4pt, below: 11.5pt) body } #let h3(body) = { set text(size: font-size.normal, weight: "bold") set text(size: 10pt, weight: "bold") set block(above: 21.7pt, below: 12.8pt) body } #let format-affilation(affl) = { // Department and institution on a seperate lines. let lines = () if "department" in affl { lines.push(affl.department) } if "institution" in affl { lines.push(affl.institution) } // Address components on a single one. let address = () if "location" in affl { address.push(affl.location) } if "country" in affl { address.push(affl.country) } if address.len() > 0 { lines.push(address.join([, ])) } lines.join([\ ]) } #let format-author(author, affls) = box(baseline: 100%, { author.name if "affl" in author { [\ ] author.affl .map(it => format-affilation(affls.at(it))) .join([\ ]) } if "email" in author { show raw: set text( font: font-family-link, size: font-size.small, fill: black) v(9pt, weak: true) link(author.email, raw(author.email)) } }) #let make-title(title, authors, affls, id, accepted) = { // 1. Title. block(width: 100%, spacing: 0pt, { set align(center) set text(size: font-size.Large, weight: "bold") v(0.5in - 0.6pt) // Visually perfect. title }) v(30pt, weak: true) // 2. Authors and affilations. block(width: 100%, spacing: 0pt, { set align(center + top) set text(size: font-size.large) if accepted != none and not accepted{ [Anonymous CVPR submission\ ] [\ ] [Paper ID #id] } else { pad(left: 10pt, right: 12pt, { authors.map(it => format-author(it, affls)).join(h(0.5in)) }) } }) v(34.5pt, weak: true) } /** * cvpr2022 - Template for Computer Vision and Pattern Recognition Conference * (CVPR) 2022. * * Args: * title: Paper title. * authors: Tuple of author objects and affilation dictionary. * keywords: Publication keywords (used in PDF metadata). * date: Creation date (used in PDF metadata). * abstract: Paper abstract. * bibliography: Bibliography content. If it is not specified then there is * not reference section. * appendix: Content to append after bibliography section. * accepted: Valid values are `none`, `false`, and `true`. Missing value * (`none`) is designed to prepare arxiv publication. Default is `false`. * id: Submission identifier. */ #let cvpr2022( title: [], authors: (), keywords: (), date: auto, abstract: [], bibliography: none, appendix: none, accepted: false, id: none, aux: (:), body, ) = { // Deconstruct authors for convenience. let (authors, affls) = if authors.len() == 2 { authors } else { ((), ()) } if accepted != none and not accepted { authors = ((name: "<NAME>"), ) } // If there is not submission id then use a placeholder. if id == none { id = "*****" } set document( title: title, author: authors.map(it => it.name).join(", ", last: " and "), keywords: keywords, date: date) set page( paper: "us-letter", margin: (left: 0.696in, right: 0.929in, top: 1in, bottom: 1.125in), background: if accepted != none and not accepted { // Rullers on sides. ruler // Decorate top corners. place(top + left, dx: -14.6pt, dy: 15.5pt, corner-text(id, width: 1in)) place(top + right, dx: 5pt, dy: 15.5pt, corner-text(id, width: 1in)) }, header-ascent: 27.9pt, header: if accepted != none and not accepted { set align(center) set text( font: font-family-sans, size: font-size.footnote, fill: ruler-color) let year = aux.at("conf-year", default: conf-year) strong[#conf-name #year Submission \##id. #notice] }, footer-descent: 23.4pt, // Visually perfect. footer: if accepted != none and not accepted { locate(loc=>{ let ix=counter(page).at(loc).first() return align(center, text(size: font-size.normal, [#ix])) }) }, ) set text(font: font-family, size: font-size.normal) set par(justify: true, first-line-indent: 0.166666in, leading: 0.532em) show par: set block(spacing: 0.54em) show raw: set text(font: font-family-mono, size: font-size.normal) // Configure heading appearence and numbering. set heading(numbering: "1.1.") show heading.where(level: 1): h1 show heading.where(level: 2): h2 show heading.where(level: 3): h3 set math.equation(numbering: "(1)", supplement: [Eq.]) show math.equation: set block(spacing: 9pt) set quote(quotes: false) show quote.where(block: true): it => { set block(spacing: 14pt) set pad(left: 20pt, right: 20pt) set par(first-line-indent: 0em) show par: set block(spacing: 9.8pt) it } // Configure footnote (almost default). show footnote.entry: set text(size: font-size.footnote) set footnote.entry( separator: line(length: 1.3in, stroke: 0.35pt), clearance: 6.65pt, gap: 0.40em, indent: 12pt) // Figures set figure(gap: 12pt) set figure.caption(separator: [.]) show figure.caption: set text(size: font-size.small) show figure.caption: set align(center) show figure.caption: it => block({ align(left, it) }) // Links and references. show link: set text(font: font-family-link, fill: color.link) show ref: it => { let el = it.element if el == none { return it } // Supplement exist for every element and we have already checked element // existance. let supplement = if it.supplement != auto { it.supplement } else { el.supplement } if el.func() == math.equation { show link: set text(font: font-family, fill: color.ref) let cnt = counter(math.equation) let ix = numbering("1", ..cnt.at(el.location())) let href = link(el.location(), ix) [#supplement~(#href)] } else if el.func() == heading { show link: set text(font: font-family, fill: color.ref) let cnt = counter(math.equation) let ix = numbering("1.1", ..cnt.at(el.location())) // TODO: Appendices? let href = link(el.location(), ix) [#supplement~#href] } else if el.func() == figure { let fig = el if fig.kind == image { show link: set text(font: font-family, fill: color.ref) let cnt = counter(figure.where(kind: image)) let ix = numbering(el.numbering, ..cnt.at(el.location())) let href = link(el.location(), ix) [#supplement~#href] } else if fig.kind == table { show link: set text(font: font-family, fill: color.ref) let cnt = counter(figure.where(kind: table)) let ix = numbering(el.numbering, ..cnt.at(el.location())) let href = link(el.location(), ix) [#supplement~#href] } else { it } } else { it } } make-title(title, authors, affls, id, accepted) // NOTE It seems that there is a typo in formatting instructions and actual // gutter is 3/8 in not 5/16 in. columns(2, gutter: 0.3125in, { // Render abstract. block(width: 100%, { set par(first-line-indent: 0pt) align(center, text(size: font-size.large)[*Abstract*]) v(17.6pt, weak: true) emph[#abstract\ \ ] }) body // Render paper body. if bibliography != none { set std-bibliography(title: [References], style: "ieee.csl") show std-bibliography: set text(size: font-size.small) bibliography } }) if appendix != none { set heading(numbering: "A.1") counter(heading).update(0) appendix } }
https://github.com/robertjndw/typst-tum-presentation
https://raw.githubusercontent.com/robertjndw/typst-tum-presentation/main/README.md
markdown
# TUM Typst Presentation Template This is a Typst polylux template for presentations at the Technical University of Munich (TUM). It is based on the [TUM Corporate Design](https://www.it.tum.de/en/it/faq/media-production-design/corporate-design/where-can-i-find-templates-for-the-tum-corporate-design/). It utilizes the [Polylux package](https://github.com/andreasKroepelin/polylux) for Typst. For optimal results, it is recommended to take a look into the [Polylux book](https://polylux.dev/book/polylux.html) An example presentation is included in the [`example.typ`](./example.typ) file. The latest compiled version of the example presentation can be found in the release section of GitHub. Feel free to use this template for your presentations at TUM. If you have any questions or suggestions, open an issue or pull request. Contributions are welcome! ## Installation For detailed installation instructions, please refer to the [official installation guide](https://github.com/typst/typst). Here, we provide basic steps for installing Typst's CLI: - You can get sources and pre-built binaries from the [releases page](https://github.com/typst/typst/releases). - Use package managers like `brew` or `pacman` to install Typst. Be aware that the versions in the package managers might lag behind the latest release. - If you have a [Rust](https://rustup.rs/) toolchain installed, you can also install the latest development version. Nix and Docker users, please refer to the official installation guide for detailed instructions. ## Usage To use this template for your presentation, you download this repository and copy the files into your presentation directory (except the `example.typ` file). Recommended is to create a dedicated directory named `theme` for copying the files. #### 1. Importing the Template You can start creating your presentation by creating a new `.typ` file (e.g. `presentation.typ`) and import the template with the following line: ``` #import "/theme/theme.typ": * ``` Alternatively, you can use the GitHub template feature to create a new repository with this template. In this case, you can directly start creating your presentation in the `example.typ` file (rename it to `presentation.typ`). #### 2. Setting Metadata Configure the theme with the metadata of your presentation. This can be done by setting the following variables: ``` #show: tum-theme.with( authors: ("<NAME>",), title: "My awesome topic i want to put into a presentation", footer-infos: ("Excellence",), school: "TUM School of Musterverfahren", chair: "Lehrstuhl für Mustertechnik", ) ``` #### 3. Creating Slides Once the metadata is set, you can start creating your slides. The template provides a variety of slide types, which can be used by calling the respective function. For example, to create a title slide, you can use the following code: ``` #title-slide() ``` For a standard title-content slide you can use: ``` #title-content-slide(title: "Section 1", [ #text("This is the first section of the presentation.")] ) ``` #### 4. Adding Dynamic You can step-by-step reveal content on slides by using the `#pause` function. For example, to reveal a list of items one by one, you can use the following code: ``` #text("This is shown first.") #pause #text("This is hidden first.") ``` #### 5. Compiling the Presentation Once you have created your presentation, you can compile it by running the following standard Typst command in the terminal: ```sh # Creates `presentation.pdf` in working directory. typst compile presentation.typ ``` You can also watch source files and automatically recompile on changes. This is faster than compiling from scratch each time because Typst has incremental compilation. ```sh # Watches source files and recompiles on changes. typst watch presentation.typ ``` --- ## Further Resources - [Typst Documentation](https://typst.app/docs/) - [Typst Polylux Book](https://polylux.dev/book/polylux.html) - [Typst Guide for LaTeX Users](https://typst.app/docs/guides/guide-for-latex-users/) - [Typst VS Code Extension (inofficial)](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp)
https://github.com/qujihan/toydb-book
https://raw.githubusercontent.com/qujihan/toydb-book/main/src/chapter1.typ
typst
#import "../typst-book-template/book.typ": * #let path-prefix = figure-root-path + "src/pics/" = 前言 == 为什么选择ToyDB == ToyDB的整体架构 #pic(path-prefix + "architecture.svg", "ToyDB的整体架构")
https://github.com/cherryblossom000/typst-apa-bibliography
https://raw.githubusercontent.com/cherryblossom000/typst-apa-bibliography/main/README.md
markdown
# apa-bibliography ## :warning: Deprecated [Typst v0.9.0](https://github.com/typst/typst/releases/tag/v0.9.0) has a new bibliography engine that now handles APA bibliographies correctly. --- Typst’s default [`#bibliography(style: "apa")`][bib] has [numerous issues][issue] with its output not conforming to APA 7th guidelines. This package aims to provide a replacement that is somewhat compatible with the builtin function. ## Installation Follow the Typst instructions on installing [local packages][typst-local-pkgs]. At this stage I will not be publishing this package on the official Typst repository — hopefully the builtin bibliography will be improved and this package will only be temporary. ## Usage ![A screenshot of the output of the below Typst code](./example/main.png) ```typst #import "@local/apa-bibliography:0.0.1": apa-bibliography #let (reference: r, reference-with-page: rp, reference-date-only: rd, bibliography) = apa-bibliography(yaml("works.yml")) Typst is really cool #r.typst-is-cool. Here's another sentence where I'm going to reference another article with a specific page number #(rp.company-report)[p. 3]. What about if two references have the same author and year? #r.same-year1 #r.same-year2 According to Smith #rd.typst-is-cool, this is just an example to show how you can cite just the date. Multiple authors: #r.multiple-authors. This is also an example with no date. You can use an acronym for an author. Here's the first time I'm going to reference the author #r.long-author1. Now when I reference the same author again, it's going to show the acronym #r.long-author2. = References #bibliography ``` `works.yml`: ```yml typst-is-cool: author: name: Smith given-name: Jane title: Some title date: 2023 url: value: https://example.com date: 2023-08-25 parent: title: Jane's blog company-report: author: A big company title: Another title date: 2021 url: value: https://example.com date: 2023-01-01 parent: title: A big company same-year1: author: Foo title: Title 1 with the same year date: 2020 url: value: https://example.com date: 2023-12-25 parent: title: Foo parent same-year2: author: Foo title: Title 2 with the same year date: 2020 url: value: https://example.com date: 2022-12-14 parent: title: Foo parent multiple-authors: author: - Author 1 - given-name: First 2 middle-name: Middle 2 name: Last 2 title: Two people wrote this! url: value: https://example.com date: 2022-12-14 parent: title: Baz long-author1: author: name: Some Really Long Name short-name: SRLN title: I'm running out of ideas date: 2019 url: value: https://example.com date: 2023-01-01 parent: title: Qux long-author2: author: name: Some Really Long Name short-name: SRLN title: for titles date: 2022-12-31019 url: value: https://example.com date: 2023-01-01 parent: title: Abc ``` Like the builtin `bibliography`, this package supports the [Hayagriva][hayagriva] file format. Unlike the builtin function, this package does *not* support BibTeX. Some other notable differences: - You must pass the parsed YAML data to the function rather than the path to the file - The bibliography lists *everything* in the file, including ones that you haven’t referenced to in the document - The bibliography does not include a heading. Add it separately - The casing of titles is kept as-is, like if `verbatim: true` was set - This package completely ignores the `type` field (for now) - This package is incomplete and if there’s something you need, please open an issue (or PR if you want to implement it)! I created this for my personal use so I only implemented what I needed. - There are a few extra features, some of which are showcased in the above example. Documentation is incomplete but if you’re curious you can have a look at the [source](./lib.typ). [bib]: https://typst.app/docs/reference/meta/bibliography/ [issue]: https://github.com/typst/typst/issues/1161 [typst-local-pkgs]: https://github.com/typst/packages#local-packages [hayagriva]: https://github.com/typst/hayagriva/blob/main/docs/file-format.md
https://github.com/Owl-Boy/Model-Repair-Of-Time-Aware-Models-Report
https://raw.githubusercontent.com/Owl-Boy/Model-Repair-Of-Time-Aware-Models-Report/main/README.md
markdown
# Model Repair of Time Aware Models This repository is sharing the work that I have done in my summer internship at [ENS Paris Saclay](https://ens-paris-saclay.fr) under Professor <NAME>. The paper was written using [Typst](https://typst.app/) and the [LaPreprint template](https://github.com/LaPreprint/typst).
https://github.com/gmax9803/nd-assignment-templates
https://raw.githubusercontent.com/gmax9803/nd-assignment-templates/master/general/main.typ
typst
MIT License
/* * This template was created by Max (gmax9803) * Updated: 02/06/2024 */ /* [SETTINGS] */ /* See [utils.typ] for all other settings */ #import "utils.typ": * // import everything from utils.typ `from utils import *` #set page(paper: "us-letter", header: hdr, footer: ftr) // Page Data #misc_settings #init_header // initial header (name, due date, etc.) #oline(probnum) // outline /* [END OF SETTINGS] */ /* [BEGIN PROBLEM SET] */ #problem() // PROBLEM 1 #subprob() // (1a) #proof(b: true)[ // border: true You can do proofs like this. In this case it will be prefixed by a "proof:" header and ended with a QED automatically. It will also be padded and centered.\ Usage: ``` #proof(b: true)[ content ] ``` ] #subprob() // (1b) #proof()[ // No border Or you can do proofs like this - without a visible box.\ ``` #proof()[ content ] ``` ] #cbox()[ // no border Or, if you're not writing a proof and just want to keep the formatting, you can do this. (It's a box without proof or a border) ``` #cbox()[ content ] ``` ] #cbox(b: true)[ // border: true Or you can do the same thing with a border. ``` #cbox(b: true)[ content ] ``` ] #problem() // PROBLEM 2 #subprob() // (2a) Or you can do proofs with custome formatting and just append a QED, using `#qed`. #qed #subprob() // (2b) All problems are placed on their own separate page by default. Subproblems are not. #qed #problem() // PROBLEM 3 #subprob() // (3a) Problem 3a goes here #qed #subprob() // (3b) Problem 3b goes here #qed /* [END PROBLEM SET] */
https://github.com/jamesrswift/splendid-mdpi
https://raw.githubusercontent.com/jamesrswift/splendid-mdpi/main/src/lib.typ
typst
The Unlicense
#import "impl.typ": template, make-venue
https://github.com/amanuensisfrances/LaTeX-math-expressions-in-Typst
https://raw.githubusercontent.com/amanuensisfrances/LaTeX-math-expressions-in-Typst/main/README.md
markdown
MIT License
# LaTeX-math-expressions-in-Typst A collection of Typst math commands/shortcuts defined for the purpose of having the same/similar names as LaTeX math expressions. For references, I used the [`maths-symbols` package documentation](https://mirrors.ctan.org/info/symbols/math/maths-symbols.pdf) (which is the shorter predecessor of the longer and more detailed [`comprehensive` package documentation](https://mirrors.ctan.org/info/symbols/comprehensive/symbols-a4.pdf)), the [`newcm-unimath-symbols` documentation](https://mirrors.ctan.org/fonts/newcomputermodern/doc/newcm-unimath-symbols.pdf) for the [`newcomputermodern` fonts](https://ctan.org/tex-archive/fonts/newcomputermodern/otf), and the [Typst documentation](https://typst.app/docs). # How to Use Either simply copy the contents of `LaTeX-math-expressions-in-Typst.typ` into your `*.typ` file or use the `import` Typst command. ## Caveat I tried to create makeshift commands for some of the less common math symbols listed in the [`maths-symbols` package documentation](https://mirrors.ctan.org/info/symbols/math/maths-symbols.pdf) which don't have Unicode character equivalents but the results are still far from being ideal.
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/028%20-%20Kaladesh/005_Born%20of%20Aether.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Born of Aether", set_name: "Kaladesh", story_date: datetime(day: 21, month: 09, year: 2016), author: "<NAME>", doc ) #emph[The aetherborn of Ghirapur are a race of pleasure-seekers and adrenaline junkies. With a lifespan of up to four years, they consider the city their natural habitat and parties their playground. Although their lives are short, they also possess empathic abilities that allow them to experience the energies of those around them.] #emph[Yahenni, an investor, philanthropist, and socialite, knows their life is near an end. When they host one of their fabulously over-the-top parties before the Inventors' Fair, three unexpected guests arrive seeking dangerous knowledge.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #figure(image("005_Born of Aether/01.jpg", width: 100%), caption: [Art by Jonas De Ro], supplement: none, numbering: none) = I I adore getting dressed in the mid-afternoon. There's something to be said about preparing for an all-nighter in the middle of the day, a level of foresight and preparation that can be lost when attending a last-minute party. I'm not dressing for two hours from now—I'm dressing for two days from now. What kind of host looks like a thrown-together mess sixteen hours into their own party? Hosts who are #emph[failures. ] That's who. The mid-afternoon shines through the curtains of my private chamber, illuminating the solid-gold vanity that dominates my largest wall. The light shimmers filtered and golden on the jewels, trinkets, and treasures abundant that peek from every drawer and glitter from every surface of the immense chest. I am aetherborn; I know when I will die and I know exactly how I'll spend my time getting there, and none of that time will be reserved for idiots who don't think I deserve to look good. As I adorn myself with my second-favorite broaches, I can almost hear the commotion of the party staff downstairs. The caterers are making good use of my kitchen—organic beings are so fussy about their #emph[food] . Luckily my caterer, Nived, has never failed me. He's currently hard at work in the kitchen preparing for the people with stomachs; a fountain of palm wine, trays upon trays of samosas, pani puri, eggplant curry, and a massive table of desserts (the shrikhand always has a line in front of it, so it must taste good). The rest of my staff right now is busy assembling the canopy on the roof. Long after the meaty tired masses of partygoers will descend to rest, my siblings of aether and will I dance into the night, the day, and the night after, lost to the ecstasy of the celebration. But that will come later. After two and a quarter seconds of consideration and rummaging through my vanity, I decide on the jasmine-and-aether-infused attar for the night. It's a personal favorite. My reflection catches my eye. I preen. I don't look a day past three! Even from down here I can sense the happy excitement and sandalwood-scented anticipation of the party staff up on the roof. I've come to pity other species for their inability to sense what we can. "Empathic resonance" is what they called it when my kind first crawled out of early aether refineries fifty years ago. "A curious ability to accurately sense the emotional state of beings in a nearby perimeter." They took great credit for the invention of us without considering for a moment that we invented ourselves. I huff a sad laugh. The only thing we've invented since then are ways to entertain ourselves. As I dab the attar on my wrists and neck, I watch a tiny piece of my dermis dissipate into a wisp of gentle smoke. The more my hard dermis vanishes, the closer I am to my end. I can see the blue of my aether flowing underneath the crack. I'm struck by its beauty. It's lovely. A gentle reminder to hurry up. I cover it with an extra bracelet. My kind are innately aware of the passing of time and exactly how much of it each of us has left. It's like waiting for a train. Every noise lifts your head and every gust of wind shifts your seat, but it still hasn't come quite yet. I'm dressed, glimmering and ready. I have fifty-four days left to live. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = II Properly gilded, I ascend the steps to the roof and hit a wall of sound. There is no better feeling than being slapped in the face with the firm hand of party music. The canopy casts welcome shade on the plush carpet my staff dragged up from downstairs. The decorators have put magnolias on the tables, dangled them over the sides of the building, and beautiful silks line the rails and decorate shimmering filigree in the late afternoon sun. As I walk I easily refill empty glasses, dodge two humans kissing (I beam at that pair. I set them up at the last party—it's always nice to use my powers for good), direct dwarves to the restroom, and adjust the volume on the domestic-model panharmonicon. Forget substances and adrenaline—#emph[parties ] are the finest vice. I relish the sensation of my guest's pleasure. I have no idea what eating a roasted animal feels like, but I imagine it's something like that. I indulge in my hosting duties, and my guests bloom with praise. My dear friend and ace pilot Depala (#emph[the] Depala!) sits relaxed and easy on a more private couch. Her hyena rests at her side, happily gnawing a bone while Depala toys with a golden leash. #figure(image("005_Born of Aether/02.jpg", width: 100%), caption: [Art by <NAME>ski], supplement: none, numbering: none) "Depala, darling, my parties are always brighter with you here," I hug her earnestly and lean down to give the hyena a loving scritch behind the ears. The hyena nuzzles into my hand. "She's fond of you, Yahenni," Depala says with a trusting smile. "Finding time to relax now that you've retired?" "Somebody keeps up with the news awful closely," I chide while refilling her glass. "Usually just the racing results, but I sift through the business news too." My family line made our fortune as investors. I announced my retirement as soon as I knew I had less than sixty days left. Bold investment strategies are much easier to make when you don't live to see the outcome. I take a seat at her side. "You'll be attending my penultimate party in a month then, I assume? It would be a hell of a bore without the best pilot in Ghirapur." Depala smiles, hand absentmindedly petting her hyena. "Wouldn't miss it. Aetherborn customs are the best." "I agree wholeheartedly. We simply don't have time for anything less, darling." Depala's mouth tightens. Her brow furrows as her eyes dart for anyone who might be listening, "So...you aren't going to put it off?" I can't help but bristle. "I know what you can do, Yahenni," she says with a meaningful look. "I'm not willing to go those lengths, Depala." I pick at the crumbling dermis on my arm. I've known for some time that I am capable of essence draining, but I'm not willing to use it. It's a rare gift that is best kept unexpressed. I couldn't steal the life force from another sentient being just to cling to life past my expiration date. What would my friends think of me? "It's an option," she says flippantly. "I don't know how it works, how much time you'd get from...someone else. I wasn't sure if you'd consider it." "It's crossed my mind, but I want to go out the old-fashioned way," I force myself to say. At that moment, Nived, my caterer, brings over a bottle of Depala's favorite beverage. So thoughtful—he's almost as good as I am. "You're a good person, Yahenni," Depala says once we're alone. "A few extra days isn't worth the guilt of doing so." I'm uncertain if she's right. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = III Three women stand outside the entrance to my flat. Mrs. Pashiri I know instantly (one of the most famous inventors in the world, as well as the fiercest board game enthusiast I know). To her right is a young red-headed woman in an out-of-fashion wrap (that style is from#emph[ years] ago— does she go outside?). On the other side is the most fascinating person I think I've ever seen. #figure(image("005_Born of Aether/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Her eyes are endless, a brilliant green from center to lid, a vivid beauty that is betrayed by an uncomfortable stance. It is tragic for someone who #emph[looks ] so interesting to be so tense. Her dress is decorated with brilliant flowers (are those real?) and cut in a way that it could fit only her. Had I any interest in romancing persons, I would be tempted, but to me her allure is strictly in terms of social gain. My goals as a host are to make my guests happy, of course, but being seen palling with interesting people is always a bonus. "Yahenni, my friend," Mrs. Pashiri says, "this is Chandra and Nissa. Chandra, Nissa, this is Yahenni. They are an investor for young inventors in need and one of the most generous philanthropists I know. May we join the festivities?" "Absolutely, Mrs. Pashiri." What an introduction. I'm internally blushing. I hold open the door for the elf. "#emph[Gorgeous] eyes, darling," I compliment as Nissa enters. She smiles tightly. The red-headed one stands awkwardly outside. I look at her dubiously and turn to Mrs. Pashiri. "That is <NAME>'s daughter, Chandra," she says. I stand aside and let the daughter of the most dangerous person in Ghirapur enter. "The party is upstairs, so let's chat where it's quieter," I say. I lead them to my patio in the back on the ground floor. Mrs. Pashiri catches my ear as we walk. "<NAME> was captured, you know." I did not know. This is unusual for me. "Pia doesn't make mistakes like that. Tell me what you know." We walk, and Mrs. Pashiri explains the situation. Potted plants and a cheerful fountain line the exterior of the sitting space, and four weathered seats are enclosed in the middle. The sound of the party on the roof trickles down and provides a nice cover for our conversation. I let them sit and wave a staff member to supply drinks for my guests as Mrs. Pashiri finishes filling me in. I mull over the arrest of Pia Nalaar. "I'm afraid I'm at a loss," I say, "I don't know where the Consulate would take prisoners of Pia's standing." Mrs. Pashiri nods, "I see." "I apologize. I take great pride in making use of my connections, but this one is a dead end for me." I feel a hot wave of smoky anger to my right. "If it was your parent you'd help us," Chandra jabs. "I don't have one of those," I say with a flippant shrug. Chandra's frown tightens. She feels foolish. She really shouldn't—it doesn't bother me. My waitstaff returns and I distribute a cup of palm wine to Mrs. Pashiri and a glass of wood alcohol to the elf. I've found in my experience that elves tend to appreciate the stronger stuff—a trait I admire and envy greatly. "There may still be people of use to us here," Mrs. Pashiri adds, taking her cup with gentle, weathered hands. I think on the guests upstairs and begin running through my connections. Suddenly there's a commotion at the front door. Nissa jumps, Chandra looks on with curiosity. From our place on the patio, I can see a gaggle of aetherborn burst through the front door carrying a chair with a rapidly dissolving aetherborn up top. The aetherborn atop the chair is glowing with the brilliance of near-death. Their dermis is dissipating, and they are more smoke than form at this point. It's embarrassing. I look away. "#emph[It's my penultimate party!] " they yell with enthusiasm. The motley group heaves the chair and moves the living wake up the stairs toward the roof. Chandra looks at me with amusement, "Do you know who that is?" "I'd rather not," I say, picking at the place on my wrist I covered earlier in the day. A tiny wisp of smoke escapes. I hate watching myself die like this. Chandra places her hands on the table with purpose and stands. "#emph[Welp] . I'm going to start asking around. Nissa—" "I'm fine," the elf replies softly. Her energy is cold and bitter with unease. She is #emph[not ] fine, so I decide to intervene. "Nissa, was it? Follow me; you #emph[must ] tell me where you found that ensemble." #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = IV We ascend the stairs until we reach the floor just below the rooftop. I lead Nissa out to the balcony. What sort of host would I be to have an uncomfortable guest at my own party? "You seemed to want an escape," I remark. The elf crosses her arms. "I'm fine," she repeats. She's still not fine, but her curiosity spills over, "What's a penultimate party?" "The last thing we aetherborn do is die, so the second-to-last thing we do is throw a penultimate party with mandatory attendance. If one doesn't have enough friends, one hijacks someone else's celebration." I motion toward the roof, the sound of the party and the dying aetherborn cheering upstairs. "This loser is, unfortunately, welcome to stay." The elf doesn't respond. She may not speak much, but her energy is incredibly easy to read. "Now then. On a scale of one to wishing for death, how much do you hate parties? Be honest." "Eight. Nine. Whatever a baloth gnawing off my leg is." I make a noncommittal noise. "That bad, huh?" Those incredible eyes unfocus. She remembers something, and the aura around her has a tinge of bittersweetness. "We used to have parties back home." I quietly refill her cup, "And what did you do at them?" "We would talk, reconnect. Sometimes we would hike somewhere special." "Do you still go to parties in those places often?" #figure(image("005_Born of Aether/04.jpg", width: 100%), caption: [Blighted Gorge | Art by Jung Park], supplement: none, numbering: none) Nissa is silent. I sense those places aren't there anymore. "Well, then. What can I do to make this particular party easier for you?" "Could we go sit somewhere separate?" "Darling, I'd go to the ends of the city for you. Platonically. And only if you asked me to nicely. And only if it's not raining or anything." The elf is amused by this. I sense her relax, a bit. Her energy picks up with the change in song upstairs. How sweet. She likes music. I ignore the puff of my own dermis that dissipates off the back of my neck. "Let's head up to the roof. You stick with me—the people-watching is #emph[exquisite] ." I sense Nissa's apprehension and gently clear a path through the crowd. Along the way upstairs I greet a new guest and quickly pass a handkerchief to another guest with some samosa crumbs on their face. The party has reached a natural lull and the attendees chat pleasantly with one another. I lead the elf to the end of the canopy sectioned off by a strategically-placed barrier of potted plants. An attendant approaches us as we sit. I accept the vial of attar they pass to me and catch their ear, "Have someone lower the volume on the panharmonicon for my guest and stick to the slow stuff." There is no greater treasure than an accommodating waitstaff. "This may come off as presumptuous, but you don't strike me as a city girl," I say smoothly. The elf cracks a small smile. I sit back on the couch, "You've never encountered aetherborn, have you?" "No. Tell me about your kind," Nissa says softly, with earnestness. She is the most active listener I have ever actively watched listen. Her gaze is only mildly disconcerting. "We are a sentient byproduct of the aether cycle. Our families lay claim to areas younglings pop up and then adopt whoever stumbles out. From day one we are fully formed and have a shelf life of anywhere from four weeks to four years." "What you describe reminds me of elemental beings I've encountered," Nissa says, brow furrowing. "You've encountered more than I have, in that case. All I know is what I am." "I don't understand." "Understand what?" She tries a gesture, but the meaning is beyond me. I feel a bit awkward. "Is there something wrong?" She tries another half gesture, then pauses, thinking over her words. She finally arrives at a sentence. "I don't understand how something of nature can be native to a city." "We #emph[are ] the city. I'm made of aether, and one day, I'll return to it. Nature is all around us, it just may look different than what you're used to." Nissa makes a small noise. She had clearly never thought of it that way. During the pause in conversation I silently point another guest in the direction of the restroom. The silence persisting, I watch Nissa close her eyes. What is she doing? Her face seems confused. Ear tilts as if she's listening. Does she hear something I don't? A corner of her mouth lifts in a smile. #figure(image("005_Born of Aether/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "I feel it. This world is structured. Cyclical." Somehow, this elf can sense the nature of my home. I sit back, at ease. "The Great Conduit is always present, even here in Ghirapur. My people are proof of that. Our wilderness doesn't care if this city is crowded, its rhythm continues all the same." A full smile climbs up Nissa's face. I lift a nearby elven pitcher. "More?" "Yes please," Nissa responds automatically. I refill her cup. She may be unwilling to disclose much, but I can feel her buzzing with wonder. I must be full of revelations tonight. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = V I hear a commotion downstairs and stand. Nissa sets down her cup and looks at me with a question in her endless eyes. Age has heightened my ability to sense, and I know immediately what is wrong and where. I stop myself from running down the stairs (I fall apart more with exerted effort) and make my way purposefully to the restroom on the floor below me. Guests part the way, and I realize that Nissa and now Chandra are following in my wake. At the end of the hall in front of the bathroom stands an imposing member of the Consulate security force. The bathroom door is clearly locked and he is attempting to shove his way in. This enforcer is tall—nearly the height of the potted tree next to the door. His clothing is old but the hemming new; this man is no stranger to physical confrontation. The weapons at his side are not fit for street patrol, but the jingle of keys against his armor betrays his position. He must work in the prison system. I motion for Chandra and Nissa to hide behind the corner while I approach the man alone. "Can I help you, sir?" The enforcer lets go of the door handle and looks me up and down. "A wanted convict is currently barricaded behind that door. They're coming with me regardless of how you feel." "So you came into my party—#emph[my house] —without an invitation?" The enforcer takes a half step closer and looks down his chest at me. "Do you want your party to be in violation of noise ordinances?" "...No..." "Then don't interrupt official Consulate business." I do not doubt that this enforcer will shut my party down just to get to whoever is behind that door. The Consulate is petty like that. I despise petty. I turn my back to the pig of a man and find Chandra and Nissa. There's an easy solution to this. These two are firmly built—they can fight—and for their favor I can provide them something in return. "I'll give you the information you need if you'll help me." "What do you need?" Nissa asks softly. "Nissa, I need you to escort this unwelcome guest outside." The elf smiles. "With pleasure," she says with calm conviction. She raises a hand and a gentle light glows in those endless eyes. Something in my chest sings a little, but the song isn't for me. My waking mind tells me to ignore the strange humming I feel at a distance. I turn to Chandra. "Chandra, I need you to help me break down the door when he leaves." <NAME>'s daughter looks at me with genuine surprise. She says in a strangely small voice, "Really?" "Yes really. My body is weakening and I can't get through on my own. You up for it, darling?" Chandra's only response is a slightly alarming, barely contained chortle. It is very disconcerting hearing that sound come out of a young human woman. A thud around the corner—I lean over and can't help but let out a small noise of alarm. The potted plant by the door is inexplicably wrapped around the enforcer's leg and the man is dazed on the floor. It may be best if I just...not think about the logistics of how this all happened. Either way, I don't have time to care—I bound around the corner and lean down next to the man's face. "All right," I whisper. "<NAME>. Which prison is she being held in?" The enforcer groans. I think he broke a tooth in his fall. No matter—he doesn't need to talk to tell me where she is. I open my senses and speak quickly. "<NAME>?" The man groans, and his energy stinks of irritation. "<NAME>?" Impatience. "Dh<NAME>?" A distant alarm of spice and salt, blooming into panic as he meets eyes with me. Had I the inability to read his energy I would never have been able to guess the answer from his face. He's good. I pat the man on the head. "Thank you for your cooperation." I turn to the elf. "Nissa, if you will?" She walks over and easily hoists the man over her shoulders in a fireman's carry and casually takes him outside. Well, damn. "How much of this place should I leave standing?" Chandra interrupts, pulling her goggles down. "Ideally all of it except for this specific door?" Chandra nods, grinning from ear to ear, and quickly melts the locks with a white-hot finger to the metal. I shake my head. Humans and their party tricks. I sense Nissa emerge behind me as Chandra finishes. The stink of too-much-attar leaks out of the space between the door and the wall. "Anyone with lungs go back to the party," I announce to the rest of the onlookers, turning my attention to the guests. Mrs. Pashiri has joined them, and looks on in concern. I move close to them. "<NAME> is where you'll find Pia," I whisper. Mrs. Pashiri gasps. "Not there," she says, "please tell me he wasn't telling the truth." I shake my head. Mrs. Pashiri turns to Chandra, "Baral is stationed there." The air around me instantly rises in temperature. "We need to go now," Chandra says tightly. Mrs. Pashiri nods and the two head down the stairs to depart. Nissa holds back, and locks her gaze on me. "Thank you, Yahenni, for the conversation." I nod. "No problem at all, darling. If you are free in a month, you should come back. I'll be throwing the biggest party of my life. Even you wouldn't want to miss out." She smiles, and in a moment she is gone. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) = VI I open the now-unlocked door and am met with a wave of perfumed stink. The door closes behind me, and I turn to see who locked themselves in here. I had sensed caged distress earlier, and sure enough, here sits the source. At the end of the bathroom, sitting on the floor with their back to the wall, is the dying aetherborn from earlier. Their dermis has almost entirely vanished, and the blue glow of their essence mixes strangely with the light of the setting sun filtering in through the window. Empty bottles of perfume are scattered at their feet. #figure(image("005_Born of Aether/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "Way to hog the good stuff to yourself," I say as a light-hearted balm. I'm more than aware that my quip is a piece of silk on a gaping, bloody wound. "I've got about a minute left," they wheeze, "I was being tailed by the Consulate and didn't want to go out in front of everyone." "You escape from prison or something?" I ask, my eye catching a broken security anklet on their leg. The aetherborn only groans. I sit beside them. I know if it were me I'd want company. "Does anyone upstairs know your name?" I ask. "No. They're just here for the party." "That's the only reason any of us are here, darling." I inhale the wafts of perfume lingering in the air. As the other aetherborn continues to dissipate, their energy mingles with the spilled attar. I've seen many of my kin in their dying moments, and it is almost always with an air of triumph. They fought and kicked and scratched and reveled in the glory of #emph[life] , and here they are at the finish line. I take hold of what's left of their hand. I can feel their energy pulsing underneath my palm. "Did you have a good run?" The other aetherborn turns their head to me and looks me over. They strain to speak but manage to get out a single affirmation. "You bet your ass I did." In that instant I am filled with envy. I have so little time left. My life, this aetherborn's life, #emph[all the lives ] of my kind are spent chasing and cramming as much experience as we can into a pathetically small span of time. It isn't fair that we have to burn so fast. It isn't fair I'm next. The other aetherborn convulses and emits a dark smoke. Their dermis crumbles and the contained aether escapes and rises in a gentle vapor to the ceiling. I sit silently under the haze of aether above me. It's lovely. After a moment I stand and open the window. The stink and the energy escape into the air, into the world, into the Conduit. I turn to the pile of clothes left behind on the floor and gather them along with their jewelry and accessories. A coin purse, a clock, a bundle of Consulate documents. I quickly skim through them—a minor infraction for petty theft. They shouldn't have been sent to prison in the first place. I crumple the documents up in anger. Those Consulate bastards are just killing us faster. As I sort the stranger's jewelry and put on one of their bracelets, I'm hit with a sudden thought. What if I left the party and went out? What if I hunted down the Consulate filth that detained this aetherborn and gave them what they had coming? I'd drained essence (once, accidentally) before; it felt #emph[amazing] . I could do that again. I could do that again a hundred times over, if someone deserved it. I watch a tiny wisp of smoke lift away from my skin toward the open window. I think of the unconscious Consulate enforcer left on the street outside my house. He'll still be there in a few hours. I could sneak away for a few minutes. No one would notice. No. The time will come for that. When it's me on the floor of a bathroom surrounded by empty perfume and bursting from my seams...maybe then I'll do it. I have other things to do with the time I have left. I grab one of the half-empty bottles of aether-infused attar and douse myself in it. Vivid determined andric cedar. The jolt of energy runs through my being, the glint of newly borrowed gold shines at my neck, and the rumble of the party echoes from the roof. I storm upstairs and emerge to a just-set sun and the glow of lanterns in filigree stands. The crowd parts, respectful of my position of power in the ecosystem of my making, and the panharmonicon quiets. I walk purposefully to the main canopy, arms raised with intent. My guests hush and turn their attention toward me. I yell, "Mark your calendars for a month from now, distinguished guests and undistinguished riffraff!" My friends and guests cheer. They're like me. They relish their high class and low bars. "I'm hosting the party of a lifetime here after the conclusion of the Inventors' Fair. I expect each and every one of you to be there, and tell everyone you know that they would be #emph[fools] to miss out." They cheer. I feel like I could live for ten more years. "Enough of that, though. You all don't want to hear more about #emph[me] , right?" The party screams, "#emph[Of course we do!] " "#emph[Well too bad!] I'm sick of talking! Get on the floor, turn the music up, and somebody open another cask for everyone in here with a liver!" The crowd loses their minds. The collective thrill of revelry rushes through me and I am lost to its currents. I rush into the storm of people dancing and am hit with a spray of aether-attar someone tossed in the air. The music turns up and the beat of the song drives the movement of the bodies around me and everything feels#emph[ alive. ] The glow of the aetherborn dimly reflects off the sweat of the dancing mass, soft tendrils of aether dissipates into the sky above, and I am alive I am alive I am alive and in this one singular moment I am drowning in the revelry of existence.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/ops-prec-00.typ
typst
Other
// Multiplication binds stronger than addition. #test(1+2*-3, -5) // Subtraction binds stronger than comparison. #test(3 == 5 - 2, true) // Boolean operations bind stronger than '=='. #test("a" == "a" and 2 < 3, true) #test(not "b" == "b", false)
https://github.com/imtsuki/resume
https://raw.githubusercontent.com/imtsuki/resume/master/resume.typ
typst
MIT License
#import "template.typ": * #let author = ( name: "<NAME>", email: "<EMAIL>", github: "https://github.com/imtsuki", website: "https://tsuki.blog" ) #show: project.with( author: author, ) == Education *University of Toronto* #h(1fr) 2022 -- 2023 Master's Degree of Engineering #h(1fr) Toronto, Canada - Major: Computer Engineering, GPA: 3.90/4.00 *Beijing University of Posts and Telecommunications* #h(1fr) 2017 -- 2021 Bachelor's Degree of Engineering #h(1fr) Beijing, China - Major: Data Science and Big Data Technology, School of Computer Science, GPA: 90.66/100 == Skills - Proficient in a wide range of programming languages, including C, C++, Rust, Python, Java, TypeScript, Go, etc. - Solid understanding of distributed systems, including consensus algorithms (e.g., Raft) and consistency models. - Knowledgeable in storage systems, including Linux kernel storage stack, LevelDB, and common distributed storage system architectures. == Work Experience *TikTok*, Cloud Native Infrastructure #h(1fr) Jul 2023 -- Present _Software Engineer_ #h(1fr) Singapore *ByteDance*, Lark Messenger Infrastructure #h(1fr) Jun -- Oct 2021 _Software Engineer Intern (Rust)_ #h(1fr) Beijing, China - Collaborated with the infrastructure team to develop Lark Messenger's cross-platform Rust client backend. - Introduced new features such as a new “create, edit and subscribe to calendars” experience. - Reduced compiled binary size by approximately 1MB through identifying code bloat at the assembly level, such as extracting logic from macros and refactoring functions where the impact of static polymorphism is significant. - Designed and implemented a lock-free task queue for asynchronous submission and execution using channels and const generics, supporting various async executors, `Future` payloads, and priority scheduling, which replaced the old thread-based implementation. - Refactored the internal SQL binding code-gen tool to support type checking by parsing the schema definition into abstract syntax trees (ASTs). *Alibaba Cloud*, ClickHouse Database Team #h(1fr) Jul -- Aug 2020 _Software Engineer Intern_ #h(1fr) Hangzhou, China - Integrated ClickHouse and Flink by developing a high-throughput database connector, employing optimizations like parallel direct shard writing. - Achieved 100% performance improvement over the default JDBC connector in most common scenarios. *SmartX Inc.*, ZBS Storage Team #h(1fr) Sep 2019 -- Jan 2020 _Software Engineer Intern (C++)_ #h(1fr) Beijing, China - Enhanced the long task execution module of the distributed block storage system, implementing features like storage backup parallelization, QoS bandwidth limiting, and task status management. - Developed Hadoop-like command-line tools for the NFS interface of the storage service. == Personal Projects - `xv7`: An operating system implemented in Rust. Made various contributions to the `@rust-osdev` organization including `uefi-rs`, `x86_64` and `uart_16550`. - Raft Algorithm: MIT 6.824 Distributed Systems course lab. Implemented the Raft consensus algorithm. - `tsuki-blog`: Personal blog built with Next.js, React Server Components and Tailwind CSS. - `nugget`: A WebGPU renderer. Capable of rendering glTF models and can run both natively and in the browser. - `fjsp-gpu`: A parallel genetic algorithm implementation in CUDA for solving Flexible Job-Shop Scheduling Problem. == Miscellaneous - Open-source contributions: contributed to `@rust-lang`, `@rust-analyzer`, `@rust-osdev`, `@jupyter`, `@pingcap`, etc. - <NAME>, *<NAME>*, <NAME>, <NAME> and <NAME>, “FlashPass: Proactive Congestion Control for Shallow-buffered WAN.” 2021 IEEE 29th International Conference on Network Protocols (ICNP), 2021, pp. 1-12.
https://github.com/Mc-Zen/zero
https://raw.githubusercontent.com/Mc-Zen/zero/main/docs/figures/anatomy.typ
typst
MIT License
#import "/src/zero.typ": * #import "@preview/cetz:0.2.2" #set text(1.4em) #set page(width: auto, height: auto, margin: 1em) #let clr = if "dark" in sys.inputs { white } else { black } #set page(fill: white) if clr == black #set text(fill: clr) #let anatomy = cetz.canvas({ import cetz.draw: * scale(140%) rect((0,-.15), (2.26,.37), fill: blue.transparentize(70%), stroke: blue + .5pt) rect((1.2,-.15), (2.125,.37), fill: red.transparentize(70%), stroke: red + .5pt) rect((2.3,-.15), (3.32,.37), fill: green.transparentize(70%), stroke: green + .5pt) content((0, 0), num[-10.4+-0.2e3], anchor: "south-west") content((.6, .8), text(blue)[mantissa]) content((1.4, -.5), text(red)[uncertainty]) content((3.1, -.5), text(green)[power]) set-style(stroke: .3pt + clr) line((-.3,.25), (.22,.16), name: "line1") content((-.7, .35), text(.8em)[sign]) line((-.0,-.4), (.8,-.1), name: "line1") content((-.6, -.55), text(.8em)[#set par(leading: 2pt);decimal \ separator]) line((2.4,.6), (2.5,.3), name: "line1") content((2.3,.8), text(.8em)[product]) line((3.1,.6), (2.97,.32), name: "line1") content((3.2,.8), text(.8em)[base]) line((3.7,.36), (3.3,.27), name: "line1") content((4.4,.42), text(.8em)[exponent]) }) #anatomy
https://github.com/dalon-work/aoc2023
https://raw.githubusercontent.com/dalon-work/aoc2023/master/README.md
markdown
# AOC 2023 In [typst](https://typst.app/docs)! Have all the answers generated directly into a pdf! (Well, at least Day 1) Who knows how far I'll get...
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/columns_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test columns for a sized page. #set page(height: 5cm, width: 7.05cm, columns: 2) Lorem ipsum dolor sit amet is a common blind text and I again am in need of filling up this page #align(bottom, rect(fill: eastern, width: 100%, height: 12pt)) #colbreak() so I'm returning to this trusty tool of tangible terror. Sure, it is not the most creative way of filling up a page for a test but it does get the job done.
https://github.com/soul667/typst
https://raw.githubusercontent.com/soul667/typst/main/PPT/test/notes.typ
typst
/* Keep track of a running note counter, and associated notes. */ #let note_state_prefix = "notes-" #let note_default_group = "default" #let note_default_display_fn(note) = { h(0pt, weak: true) super([[#note.index]]) } #let add_note( // The location of the note. This is used to derive // what the note counter should be for this note. loc, // The note itself. text, // The offset which will be added to the 0-based counter index // when the index stored in the state. offset: 1, // the display function that creates the returned content from put. // Put can't return a pure index number because the counter // and state updates need to output content. display: note_default_display_fn, // The state group to track notes in. // A group acts independent (both counter and set of notes) // from other groups. group: note_default_group ) = { let s = state(note_state_prefix + group, ()) let c = counter(note_state_prefix + group) // find any existing note that hasn't been printed yet, // containing the exact same text: let existing = s.at(loc).filter((n) => n.text == text) // If we found an existing note use that, // otherwise the note is the current location's counter + offset // and the given text (the counter is 0-based, we want 1-based indices) let note = if existing.len() > 0 { existing.first() } else { (text: text, index: c.at(loc).first() + offset, page: loc.page()) } // If we didn't find an existing index, increment the counter // and add the note to the "notes" state. if existing.len() == 0 { c.step() s.update(notes => notes + (note,)) } // Output the note marker display(note) } // get notes at specific location #let get_notes(loc, group: note_default_group) = { state(note_state_prefix + group, ()).at(loc) } // Reset the note group to empty. // Note: The counter does not reset by default. #let reset_notes(group: note_default_group, reset_counter: false) = { if reset_counter { counter(note_state_prefix + group).update(0) } state(note_state_prefix + group, ()).update(()) } // // Helpers for nicer in-document ergonomics // #let render_notes(fn, group: note_default_group, reset: true, reset_counter: false) = { locate(loc => fn(get_notes(loc, group: group))) if reset { reset_notes(group: group, reset_counter: reset_counter) } } // Create a new note at the current location #let note(note, ..args) = { locate((loc) => add_note(loc, note, ..args)) } // The quick-start option that outputs something useful by default. // This is a sane-defaults call to `render_notes`. #let notes( size: 8pt, font: "Roboto", line: line(length: 100%, stroke: 1pt + gray), padding: (top: 3mm), alignment: bottom, numberings: "1", group: note_default_group, reset: true, reset_counter: false ) = { let render(notes) = { if notes.len() > 0 { set align(alignment) block(breakable: false, pad(..padding, { if line != none { line } set text(size: size, font: font) for note in notes { [/ #text(font: "Roboto Mono")[[#numbering(numberings, note.index)]]: #note.text] } })) } } render_notes(group: group, reset: reset, reset_counter: reset_counter, render) } // // Examples // #set page(height: 5cm, width: 15cm) = Example - Having a flexible note-keeping system is important #note[Citation needed] - It's pretty easy to implement with Typst #note[Fact] - Everyone really likes the name "Typst" #note[Citation needed] // Print notes since last print: #notes() #pagebreak() These notes won't be printed on this page, so they accumulate onto next page. - Hello World #note[Your first program] - Foo Bar #note[Does not serve beverages] #pagebreak() - Orange #note[A Color] - Blue #note[A Color] // Notice that the "Citation needed" gets a new index // because we've re-used it since we printed the initial "Citation needed" - All colors are great #note[Citation needed] #notes() #pagebreak() #set page( height: 8cm, footer: notes(padding: (bottom: 5mm)), margin: (rest: 5mm, bottom: 3cm) ) = Footnotes It is of course also possible to place the notes _in_ the page footer. This is the way to implement footnotes. - Black#note[Debateably a color] - White#note[Debateably a color] #pagebreak() - Orange#note[A Color] - Blue#note[A Color] - Purple#note[Also a color] #pagebreak() = Note groups This page still has footnotes (using the default note group) but we can also name a new group for custom notes. #let mynote = note.with(group: "custom") #let mynotes = notes.with( group: "custom", font: "Comic Neue", size: 12pt, numberings: "a.", line: none, alignment: right + top ) - This is in it's own group#mynote[Custom] - Regular footnote here#note[Regular footnote] - Same custom note#mynote[Custom] #mynotes()
https://github.com/jneug/typst-codetastic
https://raw.githubusercontent.com/jneug/typst-codetastic/main/ecc.typ
typst
MIT License
#import "bits.typ" #let crc(data, generator: "110101") = { generator = bits.from-str(generator) let n = generator.len() let frame = bits.shift(bits.trim(data), n - 1) while frame.len() >= n { let s = frame.len() - n frame = bits.xor(frame, bits.shift(generator, s)) frame = bits.trim(frame) } return bits.pad(frame, n - 1) } #let crc-test(data, generator: "110101") = { generator = bits.from-str(generator) let n = generator.len() let frame = bits.shift(bits.trim(data), n - 1) while frame.len() >= n { let s = frame.len() - n frame = bits.xor(frame, bits.shift(generator, s)) frame = bits.trim(frame) } return bits.is-zero(frame) } #let bch = crc.with(generator:"10100110111")
https://github.com/colinstfni/ba1-heig
https://raw.githubusercontent.com/colinstfni/ba1-heig/main/prg1/notes/main.typ
typst
#import "../../typst/config.typ": * #import "@preview/gentle-clues:1.0.0": * #import "@preview/codly:1.0.0": * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge #set text(lang: "fr") #show: doc => conf( title: [= PRG1 C++ - 2024 S1], title_color: color.lighten(color.blue, 60%), authors: [<NAME>], header: ( [_Septembre 2024_], [PRG1 - C++], [_CS_], ), doc, ) == Introduction === Bref historique du C/C++ Langage originaire de FORTRAN, un bordel sans nom où tout le monde veut améliorer le langage de l'autre, 3 mecs (Thompson, Ritchie, Kernighan) finissent par créer B qui deviendra C après la "traduction" de UNIX qui a engendré des ajouts de fonctionnalités. Entrée dans le standard ANSI (American National STandards Institute), puis adopté par ISO. Un mec super sympa de chez AT&T (Bjarne Stroustrup) ajoute des fonctionnalités de Simula (un des premiers langages de programmation OOP) à C++ Branching de C et et C++, mais C++ permet la programmation sous + de paradigmes (procédurale, orientée objet, générique), père de plein d'autres langages de haut niveau. === 1#super[er] programme en C++ Avec l'exemple suivant: ```cpp #include <iostream> #include <cstdlib> using namespace std; int main() { // intro cout << "Bienvenu(e)s au cours PRG1" << endl; // traitement ... // fin de programme cout << "fin de programme"; return EXIT_SUCCESS; } ``` Tout programme doit: - Avoir une fonction `main()` - Cette dernière doit retourner un entier `int`, représentant le statut de retour du programme (0 = success, anything else = error) L'instruction `cout` permet d'écrire du texte sur le stream `stdout` du programme. L'instruction `endl` effectue un retour à la ligne. L'opérateur `<<` permet la transmission au flux (stream) ```c std::cout``` Des constantes de ```c <cstdlib>``` existent pour les valeurs de retour: `EXIT_SUCCESS` (0) ou `EXIT_FAILURE` (-1). Ces constantes sont notamment ici pour éviter les "magic numbers", ces valeurs constantes (numériques, strings) qui rendent le code illisible. Les fichiers *d'en-têtes* permettent l'utilisation de librairies externes, comme par exemple `<iostream>` ou `<cstdlib>`. Les espaces de nommage (`namespace`) existent pour éviter la collision des noms de fonctions ou constantes, il peut être importé avec le mot-clé `using namespace NOM_DU_BORDEL` Les instructions d'une fonction, se terminant par un `;`, sont placées entre des accolades `{...}`, qui forment un *bloc de code*. === Compilation Le compilateur génère du *code objet*, normalement compréhensible par la machine. ```sh g++ -c main.cpp ``` Il va ensuite faire passer tout le bazar dans l'éditeur de lien ("linker", e.g. `ld`), qui va lier tous les fichiers, toutes les librairies, permettant enfin à la machine de lancer l'éxécutable produit. ```sh g++ main.o -o main ``` Les deux commandes précédentes peuvent être combinées avec `g++`: ```sh g++ main.cpp -o main ``` D'autres arguments comme `--pedantic` (normes ISO), `-Wxx` (warnings) ou `-std=c++20` (standard C++) peuvent être passés à `g++` pour configurer son comportement à la compilation et au _linkage_. #pagebreak() == Utilisation de `git` #disable-line-numbers() La commande `git` permet la gestion *versionnée* de projets (VCS, Version Control System). Cela fonctionne particulièrement bien en programmation lorsqu'on travaille à plusieurs sur un seul et même projet, car plusieurs personnes travaillent sur leur propre version (*branche*), et on fusionne ensemble toutes les modifications (*merge*). === Création du dépôt L'intégration de git à un projet se fait via la commande: ```sh git init ``` Ceci va créer un répertoire `.git` "vide" dans le dossier actuel. Ce dernier est chargé de stocker toutes les version précédentes ainsi que toutes les métadonnées liées au projet. #warning[ On confond souvent le service #link("https://github.com")[GitHub] avec l'outil `git`. GitHub est simplement une plateforme avec laquelle on interragit via `git` ! Ce dernier est uniquement un client suivant des standards pour le versionnage de projets. On pourrait très bien utiliser `git` avec un autre service en ligne tel que #link("https://gitlab.com")[GitLab] ou #link("https://bitbucket.org")[BitBucket]. ] La première étape est de relier notre projet avec sa version en ligne afin de pouvoir les synchroniser. On commence par créer un dépôt (*repository*) sur #link("https://github.com/new")[GitHub], puis on l'ajoute à git: ```sh git remote add origin https://github.com/colinstfni/labo01.git ``` La commande `git remote add` permet d'ajouter un référentiel, ce qui permet à `git` de savoir où envoyer et récupérer les versions lors de la synchronisation. On ajoute ici le dépôt "lab01" de l'utilisateur "colinstfni", ces valeurs sont évidemment à changer. === Authentification avec GitHub On a deux options: - le CLI de GitHub: #link("https://cli.github.com/")[`gh`] - pour les masos, à la main avec les #link("https://github.com/settings/keys")[clés SSH] (chiant) Pour les gens normaux, avec le CLI, une fois téléchargé et installé correctement: ```sh gh auth login ``` On séléctionne "GitHub.com" pour le type de compte, "HTTPS" pour le protocole et enfin "Login with a web browser". Le CLI va vous donner un code: ``` ! First copy your one-time code: ABCD-1234 ``` On copie le code comme demandé et on appuie sur Entrée, ce qui devrait ouvrir un navigateur, si jamais il ne s'ouvre pas: https://github.com/login/device Une fois connecté et le code collé, la commande devrait s'être terminée, et en tapant `git auth status` on devrait avoir un truc du genre: ``` ❯ gh auth status github.com ✓ Logged in to github.com account colinstfni (keyring) - Active account: true - Git operations protocol: https - Token: gho_************************************ - Token scopes: 'gist', 'read:org', 'repo', 'workflow' ``` Il faut maintenant configurer `git` correctement avec la commande: ```sh gh auth setup-git ``` Et pouf c'est magique ça marche! Dans le cas où vous voulez travailler avec plusieurs comptes GitHub sur le même ordinateur, vous pouvez répéter la procédure précédente et changer de compte avec: ```sh gh auth switch -u <USER> ``` === Rédaction de changements On peut maintenant effectuer des changements qui seront traqués par `git`. Si on crée un fichier "pouet": ```sh touch pouet git status --short ``` ``` On branch main No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) pouet ``` On voit que `git` détecte notre fichier, mais nous annonce qu'il n'est pas encore inclus "dans ce qui sera commit". #info[ Un "commit" est un peu comme un carton dans lequel on met tous nos changements avant de le sceller et de l'envoyer. Lorsqu'un commit est créé, on lui assigne un *hash* (e.g. _a08dbe8_) qui permet de l'identifier. ] On concocte donc notre emballage (notre commit en gros): ```sh git add pouet # On ajoute le fichier "pouet" au prochain commit git commit -m "Ajout de pouet" # On crée le commit avec son message ``` ``` [main (root-commit) ce7cba2] Ajout de pouet 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 pouet ``` Notre carton est prêt, plus qu'à l'envoyer ! ```sh git push ``` Cette dernière commande lance la synchronisation avec le remote tout juste configuré, en *poussant* (push) les changements. La synchronisation dans le sens inverse peut se faire avec la commande `git pull` (tirer). #warning[ *Toujours* `git pull` avant de `git push` ;) ça vous évitera des problèmes ] === Concept de branches Les branches sont une notion commune dans les VCS, ils servent à continuer de travailler sur le projet sans altérer la "main-line". Dans `git`, un projet est représenté de manière linéaire: #figure( image("images/git_linear.png", width: 75%), caption: [Une branche et son historique de commits, <NAME> and <NAME>], ) Au fur et à mesure des commits, le projet change. Dans le cas de figure où deux personnes travaillent sur le même projet et l'une veut implémenter une nouvelle fonctionnalité pendant que l'autre continue de travailler sur le projet lui-même, la création d'une branche serait pertinente: #figure( image("images/git_branch.png", width: 65%), caption: [Plusieurs branches git fusionnées ensemble], ) Afin de savoir sur quelle branche on se trouve actuellement, `git` utilise également un pointeur spécial `HEAD`. Par exemple, si on se trouve actuellement sur `master`et qu'on crée une branche `testing`: #figure( image("images/git_head.png", width: 75%), caption: [Le pointeur `HEAD` pointant sur `master`, <NAME> and <NAME>traub], ) Et lorsqu'on change de branche avec `git switch testing` ou `git checkout testing`: #figure( image("images/git_head_2.png", width: 75%), caption: [Le pointeur `HEAD` pointant sur `testing`, <NAME> and <NAME>traub], ) Lorsqu'un commit sera fait sur la branche testing, le pointeur `HEAD` le suivra, on peut donc le considérer comme un "stack pointer" des commits sur la branche actuelle. Ce pointeur peut être vu lorsqu'on exécute la commande `git log --oneline`: ```sh git log --oneline ``` ``` b460714 (HEAD -> main, origin/main) Add stuff e55f0dd Update compile.yaml 50bcf7d Update README 16f7123 Add a README ``` Ici, `HEAD` pointe vers `main`, avec le dernier commit étant `b460714`. === Résolution de conflits Des fois on se retrouve avec des trucs du genre: ``` CONFLICT (content): Merge conflict in main.cpp ``` 1. Ne pas paniquer, ni tout supprimer ou même jeter son ordi par la fenêtre 2. Les clients `git` desktop sont vos amis dans ces cas là. La résolution de conflits à la main juste avec un éditeur de texte est largement faisable, mais tellement plus simple avec les bons outils. Les plus puristes diront que c'est de la triche mais bon... VSCode inclut par défaut une interface `git` très facile d'utilisation, la plupart des autres IDEs également. Les conflits viennent du fait que les deux versions du projet que vous avez tenté de synchroniser ont des différences trop complexes pour avoir été fusionnées automatiquement, ça arrive souvent quand on bosse à plusieurs sur un même fichier. Pour comprendre un minimum comment ça fonctionne derrière, il est conseillé de faire un premier merge à la main comme un(e) vaillant(e). Les conflits sont dans le format texte suivant: #enable-line-numbers() ``` <<<<<<< Les changements sur HEAD (la branche actuelle, current) ||||||| La dernière version commune ======= Changement de votre branche qui diffère (incoming) >>>>>>> ``` #figure( image("images/merge_vscode.png"), caption: [L'aide de VSCode lors d'un conflit de fusionnage], ) Au delà de résoudre des conflits, le mieux c'est quand même de ne pas en créer: pour ce faire, il est préférable de "modulariser" le projet en créant différents fichiers pour chaque fonctionnalité. #pagebreak() == Bases de C++ === Déclaration de variables Chaque variable en C++ doit être déclarée à l'aide de son *type*. On peut lui assigner une valeur directement: ```cpp int x = 9;``` ou simplement la déclarer: ```cpp int x;```. Les variables sont utiles pour: - Stocker des valeurs dynamiques (input utilisateur, résultat d'une opération) - Faciliter la lecture et modification d'un programme Avec l'exemple suivant: ```cpp cout << "Nb bouteilles dans un pack : " << 6; cout << "Volume d'un pack(l) = " << 0.33 * 6; cout << "Poids d'un pack(g) = " << 13.2 * 6; cout << "Entrer le Nb de pack à expédier :"; cout << "Le poids de votre colis(g) :" << 13.2 * 6 * nb_pack; ``` On pourrait le réécrire avec des variables: ```cpp int nb_bouteilles = 6; cout << "Nb bouteilles dans un pack : " << nb_bouteilles; int vol_bouteille = 33; cout << "Volume d'un pack(cl) = " << vol_bouteille * nb_bouteilles; int poids_bouteille = 13; int poids_pack = poids_bouteille * nb_bouteilles; cout << "Poids d'un pack(g) = " << poids_pack; cout << "Entrer le Nb de pack à expédier :"; int nb_pack = 0; cin >> nb_pack; cout << "Le poids de votre colis(g) :" << poids_pack * nb_pack; ``` #info[ Une variable peut être initialisée de plusieurs manières en C++: - "Comme en C" ```cpp int age = 6;``` - "Par constructeur" ```cpp int age(6)``` - "Uniforme" ```cpp int age{6}``` (11+) ] Une variable: - *doit* commencer par `_` ou une lettre - *peut* contenir des lettres, des chiffres et `_` - *ne peut pas* contenir d'espaces ou de caractères spéciaux - *ne peut pas* être un mot réservé C++ (```cpp while```, ```cpp true```) === Core guidelines Des règles de nomenclature sont définies dans le C++ Core book: - *NL5* : Le nom d’une variable ne doit pas mentionner son type (i.e. n’utilisez pas la notation hongroise) - *NL7* : La longueur d’un nom de variable doit être ± proportionnelle à sa portée (distance entre ses utilisations) - *NL8* : Utilisez une nomenclature consistante : snake_case, camelCase, PascalCase, ... - *NL9* : N’utilisez pas `TOUT_EN_MAJUSCULE` pour les identificateurs autres que les macros (vues en PRG2) - *NL10* : Préférez le style snake_case, c’est le style utilisé par la Standard Template Library. Utilisez éventuellement Majuscule_initiale pour les types que vous définissez vous-même, comme Bjarne Stroustrup. === Constantes Les variables constantes ne changent *pas* de valeur, on dit qu'elle sont *immutables*. On les déclare de la manière suivante: ```cpp const int meaning_to_life = 42; ``` Son initialisation à la déclaration est *obligatoire*. #info[ C++ Core guideline *CON.1*: Par défault, toutes les variables doivent être constantes. (Rust-like idiom) ] === Types de base En C++, toutes les données sont *typées*. Un type définit: - Comment la donnée est stockée en mémoire (taille) - Les opérations possibles Les types fondamentaux fournis par le language permettent de stocker les données les plus basiques: - Caractères (```cpp char```, 1 byte, code ASCII) - Nombres entiers (```cpp int```) - Nombre réels (```cpp float```, ```cpp double```, le ```cpp double``` est *2 fois* plus précis que le ```cpp float```) - Booléens (```cpp bool```) - Chaînes de caractères (```cpp string```, classe) Le mot-clé ```cpp auto``` peut être utilisé pour laisser le compilateur déduire automatiquement le type de la variable. === Expressions En C++, tout ce qui correspond à une valeur est une expression. On dit qu'elle "renvoie" une valeur. La plus simple des expressions est une constante exprimée littéralement: ```cpp 'a' // char "sdkfjgshdkg" // string 42 // int 3.14 // double ``` #info[ La `lvalue` est la valeur de *localisation*, par exemple le nom de la variable. La `rvalue` est la valeur de *résultat*, par exemple un littéral constant, les résultats d'expression (qui ne se résolvent pas en `lvalues`, e.g. ```cpp a+b```). ] === Opérateur d'affectation L'opérateur ```cpp=``` copie la valeur de l'expression de droite à gauche. Il renvoie également lui-même une `lvalue`. Toute expression d'affectation s'effectue de *droite à gauche*. ```cpp x = y = 42; ``` Ici, d'abord ```cpp y = 42;```, puis ```cpp x = y;```, donc ```cpp x = 42;``` === Arithmétique sur les réels/entiers Les types *réels* (```cpp float```, ```cpp double```), disposent des opérateurs ```cpp+, -,*,/``` qui se comportent comme en maths. Les types *entiers* (```cpp int```, ...) disposent des opérateurs ```cpp+, -, *, /, %``` #warning[ La division ```cpp/``` entière renvoie un nombre *entier*. On a toujours l'égalité suivante: $ (a / b) * b + (a % b) = a $ $ a eq.triple r space (mod b) => (a / b)*b + r = a $ Le modulo ```cpp%``` renvoie le reste de la division euclidienne, son signe correspond au signe de $a$ pour $a eq.triple r space (mod b)$ ou ```cpp a % b``` ] Lorsqu'on effectue une opération modulo sur un $a <b$, le résultat sera toujours $a$, de même pour 0. === Opérateurs d'affectation composée On a souvent besoin de soustraire ou d'ajouter une valeur à une variable, il existe donc des opérateurs "composés", tels que ```cpp +=```, ```cpp -=```, ```cpp *=``` ou ```cpp /=```. Il existe également l'opérateur ```cpp ++i``` ou ```cpp i++```. Ce dernier est pratique pour l'incrémentation "+1" d'une valeur (e.g. ```cpp for``` loop). #info[ ```cpp ++i``` et ```cpp i++``` ne retournent *pas la même valeur* ! Le ```cpp ++i``` va renvoyer la valeur *après* incrémentation, tandis que ```cpp i++``` renvoie la valeur *avant* l'incrémentation. ] Il faut évidemment que la variable assignée ne soit pas constante puisqu'on change sa valeur. == Pointeurs et références En C, les pointeurs sont essentiels à la programmation, en C++ un peu moins, cependant, il est tout de même pertinent de savoir les manipuler afin d'être à l'aise dans plusieurs cas de figures, e.g. passage de paramètre par référence ou par valeur. Presque tout ce qui existe en C, existe ausi en C++, et pour manipuler ces types de données, il est souvent nécessaire de faire appel aux pointeurs. === Opérateur d'adresse ```cpp&``` Il permet de récupérer *l'addresse mémoire* d'une variable: ```cpp int x = 5; cout << &x; // 0x0002 ``` Cet opérateur renvoie un *pointeur* du type ```cpp int*``` === Opérateur de déréférencement ```cpp *``` Il permet de *récupérer et changer la valeur* de la variable pointée: ```cpp int x = 5; cout << &x; // 0x0002 cout << *(&x); // 5 *(&x) = 10; cout << x; // 10 ``` #figure( diagram( node-stroke: 1pt, edge-stroke: 1pt, node((0, 0), [```cpp int x = 5;```], name: <x>), edge("--", <x_addr>), node( (0, 0.7), [ ```cpp 0x0002``` ], name: <x_addr>, ), node((1, 0), [```cpp int *ptr = &x;```], name: <ptr>), edge(<x_addr>, <ptr>, "<|-"), edge("--", <ptr_addr>), node( (1, 0.7), [ ```cpp 0x0003``` ], name: <ptr_addr>, ), ), caption: [ Représentation d'un pointeur vers une variable ] ) === Pointeurs vers constantes et pointeurs constants Parfois, la valeur pointée n'est pas modifiable, il faut donc modifier le type du pointeur en accord avec celui de la variable: ```cpp const int x = 5; const int *ptr = &x; ``` Le pointeur lui-même reste modifiable, mais pas la valeur pointée. ```cpp const int x = 5; const int *ptr = &x; const int y = 10; *ptr = 6; // erreur ptr = &y; // ok ``` Il peut également pointer vers une valeur non-```cpp const```. Ce cas de figure peut être utile par exemple lorsqu'on passe une valeur mutable qui ne doit pas être modifiée par une fonction pour éviter les erreurs, ça rend le code plus "robuste". Les pointeurs constants (déclarés ```cpp const```), sont des pointeurs qui ne *peuvent pas changer d'addresse pointée*, mais *peuvent changer la valeur pointée*. ```cpp int x = 5; int y = 10; int* const cptr = &x; // ok – const pointer vers non const lvalue cptr = &y; // erreur – const pointer ne peut pas changer son contenu *cptr = 7; // ok – x est modifiable cout << *cptr << " " << x; // affiche 7 7 ``` == Décisions et logique Booléenne Les décisions en programmation sont essentielles au fonctionnement d'un programme: en effet, la plupart des exécutions sont dynamiques et doivent agir en conséquence des données reçues. Pour ce faire, on utilise la logique booléenne, soit "vrai" (```cpp true```) ou "faux" (```cpp false```). D'un point de vue syntaxique, en C++, on écrit: ```cpp if (condition) { // Instructions si vrai } else { // Instructions si faux } ``` === Imbrication de ```cpp if``` Quand il y a plus de 2 possibilités dans nos conditions, l'instruction de branchement ```cpp else if``` peut être utilisée. ```cpp int x; cin >> x; if (x == 0) { // Blah } else if (x < 0) { // Blah blah } else { // BLah } ```
https://github.com/ivaquero/book-control
https://raw.githubusercontent.com/ivaquero/book-control/main/07-频域响应分析.typ
typst
#import "@local/scibook:0.1.0": * #show: doc => conf( title: "频域响应分析", author: ("ivaquero"), header-cap: "现代控制理论", footer-cap: "github@ivaquero", outline-on: false, doc, ) = 一阶系统 <一阶系统> == LTI 系统 <lti-系统> 对 LTI 系统,已知输入和输出 $ & M_i sin(ω_i t + ϕ_i)\ & M_o sin(ω_i t + ϕ_o) $ 其中,$M_i$和$M_o$为输入和输出振福,$ϕ_i$和$ϕ_o$为输入和输出相位。 #tip[ 对 LTI 系统,输入为正弦函数,输出必为正弦函数 ] - 振幅响应(magitude response) $ M = frac(M_o, M_i) $ - 幅角响应(phase response) $ ϕ = ϕ_0 - ϕ_i $ == 正弦波 对一个正弦波 $ u(t) &= A sin(ω_i t) + B cos(ω_i t) \ &= sqrt(A^2 + B^2)(frac(A, sqrt(A^2 + B^2)) sin(ω_i t) + frac(B, sqrt(A^2 + B^2)) cos(ω_i t)) $ 令$cos(ϕ_i) = frac(A, sqrt(A^2 + B^2))$,$sin(ϕ_i) = frac(B, sqrt(A^2 + B^2))$,得 $ u(t) &= sqrt(A^2 + B^2)(cos(ϕ_i) sin(ω_i t) + sin(ϕ_i) cos(ω_i t)) \ &= M_i sin(ω_i t + ϕ_i) $ 对系统 $ X(s) = U(s)G(s) $ 有 $ U(s) = ℒ[μ(t)] &= frac(A ω_i, s^2 + ω^2) + frac(B s, s^2 + ω^2) \ &= frac(A ω_i + B s, (s + j ω_i)(s - j ω_i)) $ 且 $ G(s) = frac(D(s), N(s)) = frac(D(s), ∏_(i=1)^n (s - p_i)) $ 其中,$p_i$为$G(s)$的极值点。 于是 $ X(s) = U(s)G(s) &= frac(k_1, s + j ω) + frac(k_2, s - j ω) + ∑_(i=1)^n frac(c_i, s - p_i) \ &= frac((A ω_i + B s)D(s), (s + j ω_i)(s - j ω_i) ∏_(i=1)^n (s - p_i)) $ 易得 $ x(t) = ℒ^(-1)[X(s)] = k_1 e^(-j ω_i t) + k_2 e^(j ω_i t) + ∑_(i=1)^n c_i e^(p_i t) $ 对于稳定系统,$p_i$的实部小于 0,此时稳态 $ X_(s s)(t) = k_1 e^(-j ω_i t) + k_2 e^(j ω_i t) $ > 频域响应,实质上是稳态响应。 == 求解稳态 由上面的式子 $ k_1(s - j ω_i) N(s) + k_2(s + j ω_i) N(s) + ∑_(i=1)^n c_i(s + j ω_i) = (A ω_i + B s) D(s) $ - 令$s = -j ω$,得 $ k_1(-j ω - j ω_i) N(-j ω_i) + ∑_(i=1)^n 0 = (A ω_i - B j ω_i) D(-j ω_i) $ $ k_1 = frac(A ω_i - B j ω_i, - 2j ω) frac(D(-j ω_i), N(-j ω_i)) = frac(B + A j, 2) G(-j ω_i) $ - 令$s = j ω$,得 $ k_2 = frac(B - A j, 2) G(j ω_i) $ 其中,$G(j ω_i) = |G(j ω_i)|e^(j∠G(j ω_i))$。 #tip[ $s = j ω_i$时,Laplace 变换即为 Fourier 变换。实信号函数的 Fourier 变换属于 Hermite 函数,符合共轭对称。 ] 使用复数的极坐标形式,可得 $ X_(s s)(t) &= frac(B + A j, 2) |G(j ω_i)| e^(-j ϕ_G) e^(-j ω_i t) + frac(B - A j, 2) |G(j ω_i)| e^(j ϕ_G) e^(j ω_i t)\ &= 1 / 2 |G(j ω_i)| [(B + A j) e^(-(ϕ_G + ω_i t)) j + (B - A j) e^((ϕ_G + ω_i t)) j] $ 通过 Euler 公式,化简得 $ X_(s s)(t) &= 1 / 2 |G(j ω_i)| (2 B cos(ϕ_G + ω_i t)) + 2 A sin(ϕ_G + ω_i t)\ &= |G(j ω_i)| sqrt(A^2 + B^2)(B / sqrt(A^2 + B^2) cos(ϕ_G + ω_i t)) + A / sqrt(A^2 + B^2) sin(ϕ_G + ω_i t)\ &= |G(j ω_i)| M_i sin(ω_i t + ϕ_i + ϕ_G)\ &= M_G M_i sin(ω_i t + ϕ_i + ϕ_G) $ = 低通滤波 <低通滤波> == 积分滤波 <积分滤波> 积分的 Laplace 的变换为$G(s) = 1/s$, $ G(j ω_i) = frac(1, j ω_i) = -1 / ω_i j $ 其幅角为$pi/2$,其长度 $ |G(j ω_i)| = 1 / ω_i $ 显然,频率$ω$越高时,其振幅响应越低。即积分是一个低通滤波,高频信号通过它时,会大幅衰减。 #tip[ 容器系统(如容积、电容)的积分是一个低通滤波,高频信号通过它时,会大幅衰减。这带来了容器系统的两个重要特性 #strong[缓冲] 和 #strong[延迟]。 ] == 一阶系统 对一阶系统 $ G(s) = frac(a, s + a) $ 令$s = j ω$,得 $ G(j ω_i) &= frac(a, a + j ω) = frac(a(a - j ω_i), (a + j ω_i)(a - j ω_i)) \ &= frac(a^2, a^2 + ω^2) + (-frac(a ω, a^2 + ω^2))j $ $G(j ω_i)$的模为 $ |G(j ω_i)| &= sqrt((frac(a^2, a^2 + ω^2))^2 + (frac(a ω, a^2 + ω^2))^2) \ &= sqrt(frac(1, 1 + (frac(w, a)^2))) $ 于是 - 当$ω ≪ a$,$|G(j ω_i)| → 1$ - 当$ω ≫ a$,$|G(j ω_i)| → 0$ - 当$ω = a$,$|G(j ω_i)| = sqrt(1/2) = 0.707$ $a$被称为截止频率。 $ ϕ_G &= arctan (-frac(a ω, a^2)) \ &= -arctan frac(ω, a) $ #tip[ 显然,一阶系统 $ G(s) = frac(s, s + a) $ 是一个高通滤波。其$G(j ω_i)$的模为 $ sqrt(frac(1, 1 + (frac(a, ω)^2))) $ ] = 二阶系统 <二阶系统> == 共振响应 <共振响应> 对弹簧阻尼系统 $ G(s) = frac(X(s), U(s)) = frac(ω_n^2, s^2 + 2 ζ ω_n s + ω_n^2) $ 其中 - $ω_n = sqrt(k/m)$:固有频率 - $ζ = frac(B, 2 sqrt(k m))$:阻尼比 令$s = j ω$,得 $ G(j ω_i) &= frac(ω_n^2, - ω^2 + 2 ζ ω_n ω_j + ω_n^2)\ &= frac(1, - ω^2/ω_n^2 + 2 ζ ω/ω_n j + 1) $ 令输入频率$Ω = ω/ω_n$,则 $ G(j ω_i) &= frac(1, -Ω^2 + 2 ζ Ω j + 1)\ &= frac(1 - Ω^2 - 2 ζ Ω j, (1 - Ω^2 + 2 ζ Ω j))(1 - Ω^2 - 2 ζ Ω j)\ &= frac(1 - Ω^2, (1 - Ω^2))^2 + 4 ζ^2 Ω^2 - frac(2 ζ Ω, (1 - Ω^2))^2 + 4 ζ^2 Ω^2 j $ 于是 $ |G(j ω_i)| &= sqrt(("Re"(G(j ω_i))))^2 + "Im"(G(j ω_i))^2\ &= sqrt(frac(1, (1 - Ω^2))^2 + 4 ζ^2 Ω^2) $ - 当$Ω = 0$,则$ω = 0$,有$|G(j ω_i)| = 1$ - 当$Ω → +∞$,则$ω ≫ ω_n$,有$|G(j ω_i)| → 0$ - 当$Ω = 1$,则$ω = ω_n$,有$|G(j ω_i)| = 1/2 ζ$ - 当$ζ < 0.5$,则$|G(j ω_i)| > 1$ - 当$ζ > 0.5$,则$|G(j ω_i)| < 1$ 由上面的讨论,在$0$和$+∞$之间,存在着一个极值点 令 $ f(Ω) = (1 - Ω^2)^2 + 4 ζ^2 Ω^2 $ 则$f^′(Ω) = 0$时 $ 2(1 - Ω^2)(-2 Ω) + 8 ζ^2 Ω^2 = 0 $ 于是,当$Ω = sqrt(1 - 2 ζ^2) > 0$,存在极值,此时 $ ω_r = ω_n sqrt(1 - 2 ζ^2) $ 称为共振频率(resonance frequency)。 #tip[ 显然,当$ζ → 0$,共振频率将接近固有频率。 ] == 共振响应的模 <共振响应的模> $ |G(j ω_i)|_(ω = ω_n sqrt(1 - 2 ζ^2)) = frac(1, 2 ζ sqrt(1 - ζ^2)) $ - 当$ζ = 1$ - 若$ω = ω_n$,有$|G(j ω_i)| = 1/2$ - 当$ζ = 1/2$ - 若$ω = ω_n$,有$|G(j ω_i)| = 1$ - 若$ω = ω_r$,有$|G(j ω_i)| = 1.16$ - 当$ζ = 0$ - $ω_r = ω_n$,有$|G(j ω_i)| → +∞$ = Bode 图 <bode-图> == 由来 <由来> 对 LTI 系统的振幅响应和幅角响应绘图,得到 - $20 lg M$-$ω$图,单位$"dB"$-$r a d/s$ - $ϕ$-$ω$图,单位$deg$-$r a d/s$ #tip[ 分贝(decibel),意为十分之一贝尔(Alexander Bell),最初用于度量电话/电报的噪声损失,定义为 $ "dB" = 10 lg P_M / P_R $ 其中,$P_M$为测量功率,$P_R$为参考功率。 ] 已知,功率是振幅平方的函数,即 $ P = f(M^2) $ 此时 $ "dB" = 10 lg P_M / P_R = 10 lg (M_0 / M_i)^2 = 20 lg M $ 这就是 Bode 图纵坐标的由来。 == 常见案例 <常见案例> - 对$G(s) = 1/s$ - $|G(j ω_i)| = 1 / ω$ - $20 lg |G(j ω_i)| = -20 lg ω$ - $∠G(j ω_i) = π / 2$ - 对$G(s) = a/(a + s)$ - $|G(j ω_i)| = sqrt(frac(1, 1 + (ω/a)^2))$ #figure( table( columns: 5, align: center + horizon, inset: 4pt, stroke: frame(rgb("000")), [], [$ω?a$], [$|G(j ω_i)|$], [$20|G(j ω_i)|$], [$∠G(j ω_i)$], [低频], [≪], [$1$], [$0$], [$0$], [截止频率], [=], [$sqrt(1\/2)$], [$-3$], [$-π\/4$], [高频], [≫], [$1\/ω$], [$-20 lg ω$], [$-π\/2$], ), caption: [], supplement: "表", kind: table, ) == 绘制 <绘制> Euler 公式,有 $ G(j ω_i) = r e^(j θ) $ 其中 - $r = |G(j ω_i)|$ - $θ = ∠G(j ω_i)$ 由 $ G(j ω_i) = G_1(j ω_i)⋅G_2(j ω_i) = r_1 e^(j θ_1)⋅r_2 e^(j θ_2) = r_1 r_2 e^(j (θ_1 + θ_2)) $ 可知 Bode 图纵坐标可以通过对数的性质,将复合函数的振幅响应和幅角响应拆分成多个常见函数叠加组合的形式,即 $ 20 lg |G(j ω_i)| = 20 lg |G_1(j ω_i)| + 20 lg |G_2(j ω_i)| $
https://github.com/Mc-Zen/quill
https://raw.githubusercontent.com/Mc-Zen/quill/main/tests/layout/placed%20items/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 0pt) #import "/src/quill.typ": * #quantum-circuit( 1, $H$, [\ ], 1, $H$, [\ ], 1, $H$, [\ ], ..range(3).map(i => mqgate($+$, x: i + 2, y: i, n: 2)), ..range(3).map(i => meter(x: 6, y: i)), ..range(3).map(i => ctrl(0, x: 7, y: i)), ..range(3).map(i => lstick($|0〉$, x: 0, y: i)), gategroup(4, 3, x: 2, y: 0), slice(y: 1, x: 6, n: 2), ) #pagebreak() #quantum-circuit( gate($H$, y: 1), gate($H$, y: 0), 1, $B$, gate($X$, x: 4), [\ ], gate($X$, x:3) ) #pagebreak() #quantum-circuit( gate($H$, x: 2), gate($H$, x: 1), $B$, 2, $N$ ) #pagebreak() #quantum-circuit( $X$, 20pt, $Y$, slice(y: 0, n: 1), 20pt, $Y$, 20pt, $ß$, 20pt, gategroup(x: 0, y: 0, 1, 4), mqgate("a", n: 1) )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-02.typ
typst
Other
// Test parenthesised assignments. // Ref: false #let (a) = (1, 2)
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/431/hw/1/hw8.typ
typst
#set math.equation(numbering: "(1)") #set page(margin: (x: 1cm, y: 1cm)) = HW 8, <NAME> // 6.28. 6.30, 7.2, 7.16, 7.20, 7.24, 7.28, 7.30 // Note that 6.30 has a typo: you should compute P(X-1=Y) (as opposed to P(X+1=Y)). // For 7.2 you should provide the probability mass function of X+Y. - 6.28 Let $p=1-q$. Need to find $P(V=k,W=l),k>=1, l=0,1,2$ Noticing the independence of X and Y, we have $ P(V=k, W=0) &= P(min(X,Y)= k, X<Y) \ & = P(X = k, k<Y) \ & = P(X=k)P(k<Y) \ & = p q^(k-1) q^(k) = p q^(2k-1) $ Similarly, $P(V = k, W = 2) = p q^(2k-1) $ Thus, $ P(V=k, W=1) & = P(min(X,Y)=k,X=Y) \ & = P(X=k, Y=k) = p^2q^(2k-2) $ Need to check if $P(V=k,W=1)$ is the product of the marginal probabilities. $V ~ "Geom"(1-q^2) => P(V=k) = (1-(1-q^2))^(k-1)(1-q^2) = q^(2k-2)(1-q^2) $ By argument of symmetry, $P(W=0) = P(X<Y) = P(Y<X) = P(W=2)$ Noticing again the independence of X and Y, we have $ P(W=1) = P(X=Y) &= sum_(k=1)^(infinity)P(X = k)P(Y=k) \ & = sum_(k=1)^(infinity)p q^(k-1)p q^(k-1) = (p^2)/(1-q^2) $ Using the fact that $P(W=0)+P(W=1)+P(W=2)=1$, we have $ P(W=0) = P(W=2) = 1/2 (1-P(W=1)) = (1-p)/(2-p) $ To check independence of V and W: $ P(V=k,W=0) &= p q^(2k-1) \ P(V=k)P(W=0) &= q^(2k-2)(1-q^2)(1-p)/(2-p) $ Noticing $(1-q^2)/(2-p)=((1-q)(1+q))/(1+q) = p => P(V=k,W=0) = P(V=k) P(W=0)$ Similarly, $P(V=k,W=1) = P(V=k)P(W=1)$ and $P(V=k,W=2) = P(V=k)P(W=2)$ Thus, we have shown that for all k>=1, l=0,1,2, $P(V=k,W=l) = P(V=k)P(W=l)$, which implies independence of V and W. - 6.30 // Note that 6.30 has a typo: you should compute P(X-1=Y) (as opposed to P(X+1=Y)). The joint pmf of X and Y, for $k >= 1, l>=0 $ is $ P(X=k, Y= l) = (1-p)^(k-1)p times e^(-lambda)(lambda^l)slash (l!) $ Noticing that ${X=Y+1}$ can be expressed in $union_(k=0)^infinity{X=k+1, Y=k}$. It follows that $ P(X = Y+1) &= sum_(k=0)^(infinity)P(X=k+1,Y=k) \ & = sum_(k=0)^(infinity) (1-p)^k p e^(-lambda)(lambda^k)slash (k!) \ & = P e^(-lambda) sum_(k=0)^(infinity) (lambda(1-p))^k slash (k!) \ & = p e ^(-lambda)e^(lambda(1-p)) #rect(inset: 8pt)[ $ display( & = p e^(-p lambda) )$ ] $ - 7.2 // For 7.2 you should provide the probability mass function of X+Y. As suggested, we find the probability mass function of X+Y to represent its distribution. Since $X, Y in {0,1} => X+Y = {0,1,2}$ When $X=0,Y=0, X+Y=0$. By independence, $ P(X+Y=0) = P(X=0,Y=0) = P(X=0)P(Y=0) = (1-p)(1-r) $ WHen $X+Y = 2, X=1, Y=1$. Similarly, $ P(X+Y=2) = P(X=1,Y=1) = P(X=1)P(Y=1) = p r $ Considering the complement of $P(X+Y) = 1$, $ P(X+Y = 1) = 1-P(X+Y = 0)-P(X+Y = 2) = p+r-2 p r $ Thus, the probability mass function of X+Y is $ &P(X+Y = 0) = (1-p)(1-r) \ &P(X+Y = 1) = p+r-2 p r \ &P(X+Y = 2) = p r $ - 7.16 $ p_X (k) = (lambda^k)/(k!) e^(-lambda), k = 0,1,2,... \ P_Y (0) = 1-p, p_Y (1)=p $ By convolution, $ p_(X+Y)(n) = sum_(k=0)^n p_X (k) p_Y (n-k) \ $ <eq.conv1> Since $X+Y in {0,1,2,...}$, we need to consider only $n >= 0$ @eq.conv1 becomes $ p_(X+Y) (n) = p_X (n) p_Y (0) + p_X (n-1) p_Y (1) $ - when $n=0, p_X (n-1) =0$, $ p_(X+Y) (0) = p_X (0) p_Y (0) = e^(-lambda)(1-p) $ - when $n>0$, $ p_(X+Y)(n) &= p_X (n) p_Y (0) + p_X (n-1) p_Y (1) \ & = (1-p)(lambda^n)/(n!) e^(-lambda) + p(lambda^(n-1))/(n-1)! e^(-lambda) \ & = (lambda^(n-1)e^(-lambda) (lambda(1-p)+n p))/(n!) $ To conclude, $ &p_(X+Y) (n) = (lambda^(n-1)e^(-lambda) (lambda(1-p)+n p))/(n!), n = 0,1,2,... \ &p_(X+Y) (n) = (1-p)e^(-lambda), n = 0 \ $ - 7.20 (a) By independence of X and Y, $ f_X (x) f_Y (y) = f_(X,Y) (x,y) \ f_X (x) = cases(2x quad x in (0,1),0 quad o.w.)\ f_Y (y) = cases(1 quad y in (1,2),0 quad o.w.)\ $ For $P(Y-X>= 3/2)$, we need to integrate the joint density function over the region $y-x >= 3/2$. Since pdf is only positive on $x in (0,1), y in (1,2)$ , we only need to consider the reagion of ${(x,y)| y-x >= 3/2} sect {(x,y)| x in (0,1) , y in (1,2)} = {(x,y)| x in (0,1/2, y in (x + 3/2, 2))}$ Therefore, $ P(Y-X >= 3/2) &= integral_(0)^(1/2) integral_(x+3/2)^(2) 2x dif y dif x \ & = 1/24 $ (b) since $X in (0,1), Y in (1,2) => X+Y in (1,3)$ $ f_(X+Y) (z) = integral_(-infinity)^(infinity) f_X (x) f_Y (z-x) dif x\ = integral_(0)^(1) f_X (x) f_Y (z-x) dif x $ Considering $f_X (x)f_Y (z-x) eq.not 0 "iff" z-x in (1,2)$ WE want $x in (0,1) s.t. f_X (x) eq.not 0$ Therefore, $f_X (x)f_Y (z-x)$ is non zero if and only if $max(0,z-2) < x < min(1,z-1)$ $ f_(X+Y) (z) = integral_(max(0,z-2))^(min(1,z-1)) 2x dif x = min(1,z-1)^2 - max(0,z-2)^2 $ $ f_(X+Y) (z) = cases( (z-1)^2 quad z in (1,2), 1-(z-2)^2 quad z in (2,3), 0 quad o.w.) $ - 7.24 Denote $"Var"(X) = sigma_X^2, "Var"(Y) = sigma_Y^2, "Var"(Z) = sigma_Z^2$\ Notice: $ X + 2Y -3Z ~ N(0,sigma_X^2+4sigma_Y^2 + 9sigma_Z^2), \ (X+2Y-3Z)/(sqrt(sigma_X^2 +4sigma_Y^2 + 9sigma_Z^2) )~ N(0,1) $ It follows that $ P(X+2Y-3Z <= 0) = P((X+2Y-3Z)/(sqrt(sigma_X^2 +4sigma_Y^2 + 9sigma_Z^2) ) <= 0) = 1- Phi(0)=1/2 $ - 7.28 Because of joint continous of $X_1, X_2,X_3$, prob. of any pairs of them being equal is 0. Therefore, $P(X_1 eq.not X_2 eq.not X_3) = 0 $ By exchangeability $ P(X_1<X_2<X_3) = P(X_2 < X_1 < X_3) = P(X_3 < X_1 < X_2) = ... $ There are 6 different permutations, each has same prob, and since they are mutually exclusive, $ P(X_1 < X_2 < X_3) = 1/6 $ - 7.30 (a) By exchangeability, $ P("card 2" = A, "card 4" = K) = P("card 1" = A, "card 2" = K) = (4*4)/(52*51) = 4/663 $ (b) By exchangeability, $ P("card 1" = S, "card 5" = S) = P("card 1" = S, "card 2" = S) = (binom(13,2))/(binom(52,2)) = 1/17 $ (c) By exchangeability, $ P("card 2" =K| "last 2 cards are A") &= (P("card 2" =K, "last 2 cards are A"))/(P("last 2 cards are A")) \ & = P("card 3" = K, "card 1" = "card 2" =A)/(P("card 1" "card 2"= A)) \ & = P("3rd card is K"|"first 2 cards are A") \ & = 4/50 $
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/chapters/03_methodology.typ
typst
#import "../preamble.typ": * #import "@preview/fletcher:0.4.4" as fletcher: diagram, node, edge #import fletcher.shapes: pill, diamond, hexagon #set heading(numbering: "1.") = Methodological Approach This thesis project started as an exploratory data analysis project, trying to find easy to implement metrics for public transit service coverage and accessibility with transit based on open source software and openly accessible data. Starting points were prior considerations about closeness centrality and reach, as well as an interest in the temporal variability of transit services on the macro and micro scale (compare @related) . == Case Studies <case-study> To this end it was necessary to find at least on suitable case study. As my choice to approximate network characteristics here fell on routing with `r5py`, based on conveyal's `r5` routing engine @r5py, there were several data availability requirements. There needed to be a routable General Transit Feed Specification schedule (GTFS) @mobility_data_reference_2024 and suitable street network data from Open Street Map (OSM). For further details see @data below. First attempts at routing were based in Heidelberg, Germany arbitrarily. After fine tuning the process in Bonn, Germany (mostly due to concerns over point of interest like school locations), I made the decision to use Heidelberg again for the final data for this thesis, based on my personal familiarity with Heidelberg and its transit network. As this thesis does not include any measures to verify the data acquired through routing with an empircal sample of real life experiences, personal experience and familiarity at least allowed for checks against my own experience and intuition. #figure(image("../figures/basemap.svg"), caption: [Overview map of Heidelberg (OpenStreetMap contrubutors)], kind: "Map", supplement: "Map") <overview> For a transit study, Heidelberg, a city of roughly 130,000 people with a large student population, offers a variety of modes of public transit. There are buses and trams operated by the local municpal transit company rnv, regional buses, as well as multiple S-Bahn stations with regular commuter trains. Beyond that Heidelberg offers a few different urban spaces (see @overview). There are outlying villages part of Heidelbergs administrative boundaries like Ziegelhausen and Peterstal, there are suburban developments from the 1970s like for example Emmertsgrund @amt_fur_stadtentwicklung_und_statistik_heidelberg_integriertes_2023, there are large areas of forests and agricultural land, as well as of course the central bits of urban agglomeration, with differing neighbourhoods, and a couple of industrial parks. == Data Acquisition <data> As mentioned in @case-study above, there were several requirements for data to process. Transportation data was required in two forms, both for the underlying street network, as well as for the public transit schedule data (see @transit). Beyond that routing needed origins and destinations (see @endpoints). === Transport Data <transit> While OSM data is generally available for most of the world in varying levels of quality, public transit schedule data isn't necessarily as easy to come by; especially not if there is formatting requirements like using the specifications of GTFS @mobility_data_reference_2024 for routing with `r5py` @r5py. GTFS is a standard trying to capture a plethora of data that can be relevant for routing. The specification includes a lot of options for all kinds of various transit modes, and multimodal network constellations, from interchange specifications to fare schemas @mobility_data_reference_2024. For a simple routing analysis only part of the possible data contained within a gtfs feed are necessary. This includes, stop, trip, and calendar data. Within Germany there are numerous recent and regularly updated GTFS Schedule datasets available on `opendata-oepnv.de` @openoepnv, including candidates for usage in different cities within Germany. These datasets include planned schedule data in accordance with GTFS specifications. There are datasets for Heidelberg from the local transit company RNV @rhein-neckar-verkehr_gmbh_aktueller_2023, and for Bonn for example there is data from the local transit authority of the region @vrs_soll-fahrplandaten_2023. Beyond the numerous offerings on `opendata-oepnv.de` in a federalised Germany, it is of course not beyond individual transit authorities like VRN for the Rhein-Neckar Metropolregion to publish their own transit schedule data @vrn_vrn_2023. At the same time, not all local transit authorities publish their schedule data as a gtfs feed. However, all scheduling data is collected by DELFI e.V., a network between federal states and other partners to collect travel information publishes a GTFS schedule dataset for the entirety of Germany, that is updated weekly @delfi_deutschlandweite_2023. With these three options applicable to routing, it was necessary to weigh their benefits. The RNV data includes only transport services operated by rnv @rhein-neckar-verkehr_gmbh_aktueller_2023. This includes most public transport services within Heidelberg, but ignores regional bus routes, as well as local trains operated by SWEG and DB Regio Mitte. While most public transport traffic in Heidelberg is probably handled by rnv, regional buses and specifically the fast S-Bahn services offer speedy connections between the 4 different train stations in Heidelberg. As ticketing within the VRN transit authority is integrated, excluding these trains ignores real transit opportunities. Fittingly, the VRN dataset includes these vital train connections and the regional buses as well @vrn_vrn_2023. The dataset however is much larger already than that provided by rnv, as the VRN servicing area has a quite large east to west extent. Although, the most crucial drawback here is that lack of regular updates by VRN, who seems to have once contributed to `opendata-oepnv.de`, but seems to have dropped off the system, with a last update to their self-hosted GTFS Schedule dataset in May 2023 -- almost a year before this thesis was written. The final choice of GTFS schedule data -- the DELFI schedule dataset for all of Germany -- contains almost all public transit in Germany, that include the local tram and bus network of Heidelberg, the regional buses, the local and regional trains, but also long distance train services operated by DB Fernverkehr @delfi_deutschlandweite_2023. For an analyis of connectivity and transit access within Heidelberg these services aren't helpful. After all they break the integrated ticketing and require much higher fares, to the point of ridiculesness for itineraries within a city. For this analysis however, they can just be ignored as there are no long distance trains stopping at more than one station in Heidelberg. In essence, they do not add or take away anything from the connectivity in Heidelberg. The larger drawback these carry however is that these datasets are incredibly large, and add a lot of overhead to routing just within the city boundaries of Heidelberg. To use them without taking up too much computational power it is necessary to crop them by a bounding box first. In the end however, these cropped datasets are the only option that provides recency and regular updates as well as all the regular public transport services within the city of Heidelberg. `r5py` also needs a street network for routing. This data needs to be supplied as an OSM protocoll buffer file `.pbf`. These are available from a few different vendors. `BBBike.org` offers both pre-rendered downloads of specific areas usually in the order of cities, as well as custom area downloads by e-mail @schneider_bbbikeorg_2024. Unfortunately Heidelberg was not in the pre-rendered downloads. Geofabrik too offers various downloads of preselected areas @geofabrik_gmbh_geofabrik_2018. These areas range in size from local administrative boundaries to whole continents. Unlike `BBBike.org`, geofabrik offfers an index of available download with geospatial extents. Out of an obsession with automation geofabrik was chosen as a supplier of OSM `,pbf`-files and downloaded with `pyrosm` @tenkanen_pyrosm_2023. OSM is voluntarily supplied geoinformation data. As such, there are quality concerns associated with osm data, like potentially missing or out of date information @de_lange_geoinformatik_2020. For Heidelberg, Germany, street network data is generally both up to date, as well as complete. This allows for adequate routing for walked legs of itineraries within public transit journeys. === Origins and Destinations <endpoints> Finally, for routing there need to be origin and destination points. For building suitable model itineraries as suggested in @levinson_towards_2020, it would have been interesting to find suitable point of interest datasets. However for a general overview of connectivity, locations are more interesting, and also generally more readily available. The easiest choice for this is overlaying grid cells. For this the choice fell on hexagonal grid cells for their translational symmetries in regards to cartesian distance between all adjacent cells. For this hexgrids for the aroa of Heidelberg were acquired from `h3pandas` @dahn_h3pandas_2023. For these cells population density data was acquired from the Global Human Settlement (GHS) project @schiavina_ghs-pop_2023. == Processing <method_processing> With all this data it becomes possible to calculate travel time matrices for multimodal public transport journeys with `r5py`. The general flow of data as described in @processing_chart, was primarily contained within a `python` application running in a `docker` container, that could run on a linux server. The only exceptions were the supply of a suitable GTFS schedule dataset, and the supply of the right tiles from the GHS layer dataset. The large DELFI GTFS dataset was cropped to the general area of Heidelberg to reduce computational overhead for the travel time matrix routing. For this, I used the `gtfs-general` command line tool @psotta_michaelsjpgtfs-general_2024. Similarly osm `.pbf` files acquired from geofabrik were, this time automatically, cropped using `osmosis` @openstreetmap_osmosis_2023 if they were larger than a filesize limit based on the locally available computing power. Both the OSM data and the gtfs data then were supplied as properties to the `r5py` class `TransitNetwork`. A departure date was automatically chosen then out of the `r5py TransitNetwork` automatically based on a few heuristics, to pick an arbitray non-special weekday. For this date a departure time was chosen for each hour with a departure time window of 60 minutes, as such covering the entire day. Routing modes were set to walking and public transit to capture a common use case of public transit use, where transit users walk to the first stop of their itinerary, and walk from the last transit stop of their itinerary to their destination. #figure( box( diagram( spacing: (10pt, 20mm), node((0,0), [Study Area], shape: diamond, fill: teal.lighten(50%), stroke: teal, name: <area>), node((1.5,0), [GHS Population data], shape: hexagon, fill: orange.lighten(50%), stroke: orange, name: <ghs>), node((0,1), [GTFS Data], shape: hexagon, fill: orange.lighten(50%), stroke: orange, name:<gtfs>), node((1,1), [pyrosm], shape: pill, fill:red.lighten(50%), stroke: red, name:<pyrosm>), node((2,1), [Geofabrik OSM data], shape: hexagon, fill: orange.lighten(50%), stroke: orange, name: <osm>), edge(<gtfs>, <pyrosm>, "->", "extent"), edge(<pyrosm>, <osm>, "->", "downloads"), edge(<area>, <gtfs>, "->", "location"), node((3,0), [h3pandas], shape: pill, fill: red.lighten(50%), stroke: red, name: <h3pandas>), edge(<area>, <ghs>, "->", "area"), edge(<ghs>, <h3pandas>, "->", "population grid"), node((0,2), [size], shape: diamond, fill: teal.lighten(50%), stroke: teal, name: <gtfssize>), node((0,3), [gtfs-general], shape:pill, fill:red.lighten(50%), stroke: red, name: <gtfscrop>), node((1,3), [r5py network], shape:hexagon, fill:orange.lighten(50%), stroke: orange, name: <transitnetwork>), edge(<gtfs>,<gtfssize>, "->", "schedule"), edge(<gtfssize>, <gtfscrop>, "-->", [*if*: large]), edge(<gtfssize>, <transitnetwork>, "->", "schedule"), edge(<gtfscrop>, <transitnetwork>, "-->", "cropped gtfs"), node((2,2), [size], shape: diamond, fill: blue.lighten(50%), stroke: blue, name: <osmsize>), node((1,2), [osmosis], shape: pill, fill: red.lighten(50%), stroke: red, name: <osmosis>), edge(<osm>, <osmsize>, "->", [_osm.pbf_]), edge(<osmsize>, <osmosis>, "-->", [*if*: large]), edge(<osmosis>, <transitnetwork>, "-->", [cropped _osm.pbf_], label-side: left), edge(<osmsize>, <transitnetwork>, "->", [_osm.pbf_], bend: 30deg), node((1,4), [r5py TravelTimeMatrixCalculator], shape: pill, fill:red.lighten(50%), stroke: red), node((3,4), [h3 dataframe], shape: hexagon, fill: orange.lighten(50%), stroke: orange, name: <cells>), edge(<h3pandas>, <cells>, "->", "cells"), edge(<cells>, (1,4), "->", [destinations & origins]), edge(<transitnetwork>, (1,4), "->", "network", bend:-20deg), edge(<transitnetwork>, (1,4), "->", "departure time", bend:20deg), node((1,5), [dataframe], shape: hexagon, fill: green.lighten(50%), stroke: green, name: <results>), edge((1,4), <results>, "->", "cell to cell travel times"), edge(<cells>, <results>, "->", "cells", bend: 15deg) ) ), caption: [Flowchart describing the data processing done for routing with r5py] ) <processing_chart> For each of these departure times, a travel time matrix was calculated from the approximated centre of each h3pandas cells to all other h3pandas cells. Both the median, as well as the 10th and 90th percentile of travel time were extracted, and then recombined with the geographic data from h3pandas dataframe (see @processing_chart). <end_of_chapter> #locate(loc => bib_state.at(query(<end_of_chapter>, loc).first().location()))
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/005_Modern%20Masters.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Modern Masters", doc) #include "./005 - Modern Masters/001_Preparation.typ"
https://github.com/mvuorre/quarto-preprint
https://raw.githubusercontent.com/mvuorre/quarto-preprint/main/_extensions/preprint/typst-template.typ
typst
Creative Commons Attribution 4.0 International
#let preprint( title: none, running-head: none, authors: none, affiliations: none, abstract: none, keywords: none, wordcount: none, authornote: none, citation: none, date: none, branding: none, leading: 0.6em, spacing: 1em, first-line-indent: 0cm, linkcolor: black, margin: (x: 3.2cm, y: 3cm), paper: "a4", lang: "en", region: "US", font: ("Times", "Times New Roman", "Arial"), fontsize: 11pt, section-numbering: none, toc: false, toc-title: "contents", toc-depth: none, toc-indent: 1.5em, bibliography-title: "References", bibliography-style: "apa", cols: 1, col-gutter: 4.2%, doc, ) = { /* Document settings */ // Set link and cite colors show link: set text(fill: linkcolor) show cite: set text(fill: linkcolor) // Allow custom title for bibliography section set bibliography(title: bibliography-title, style: bibliography-style) // Format author strings here, so can use in author note let author_strings = () if authors != none { for a in authors { let author_string = [ // Solo manuscripts don't have institutional id #a.name#if authors.len() > 1 [#super[#a.affiliation]]#if a.keys().contains("email") {[\*]} #if a.keys().contains("orcid") { box( height: 1em, link( a.orcid, figure( image("orcid.svg", height: 0.9em) ) ) ) } ] if a.keys().contains("email") { authornote = [\*Send correspondence to: #a.name, #a.email.\ #authornote] } author_strings.push(author_string) } } // Page settings (including headers & footers) set page( paper: paper, margin: margin, numbering: "1", header-ascent: 50%, header: locate( // Page 1 header can include citation and branding loc => if [#loc.page()] == [1] { set align(right) set text(size: 0.85em) box( inset: 0.2em, [ #date #if citation != none {linebreak(); link("https://doi.org/" + citation.doi, "https://doi.org/" + citation.doi)} ] ) box( inset: 0.2em, if branding == "psyarxiv" { image("psyarxiv.svg", width: 2.25em) } ) } else { // Page >1 header has running head and page number grid( columns: (1fr, 1fr), align(left)[#running-head], align(right)[#counter(page).display()] ) } ), footer-descent: 24pt, footer: locate( // Page 1 footer has author note loc => if [#loc.page()] == [1] { [#text(size: 0.85em)[#authornote]] } else { [] } ) ) // Paragraph settings set par( justify: true, leading: leading, first-line-indent: first-line-indent ) // Set space between paragraphs show par: set block(spacing: spacing) // Text settings set text( lang: lang, region: region, font: font, size: fontsize ) // Headers set heading( numbering: section-numbering ) show heading.where( level: 1 ): it => block(width: 100%, below: 1em, above: 1.25em)[ #set align(center) #set text(size: fontsize*1.1, weight: "bold") #it ] show heading.where( level: 2 ): it => block(width: 100%, below: 1em, above: 1.25em)[ #set text(size: fontsize*1.05) #it ] show heading.where( level: 3 ): it => block(width: 100%, below: 0.8em, above: 1.2em)[ #set text(size: fontsize, style: "italic") #it ] // Level 4 & 5 headers are in paragraph show heading.where( level: 4 ): it => box( inset: (top: 0em, bottom: 0em, left: 0em, right: 1em), text(size: 1em, weight: "bold", it) ) show heading.where( level: 5 ): it => box( inset: (top: 0em, bottom: 0em, left: 0em, right: 1em), text(size: 1em, weight: "bold", style: "italic", it) ) /* Content front matter */ let titleblock( body, width: 100%, size: 1.5em, weight: "bold", above: 1em, below: 0em ) = [ #align(center)[ #block(width: width, above: above, below: below)[ #text(weight: weight, size: size)[#body] ] ] ] if title != none { titleblock(title) } if authors != none { titleblock( weight: "regular", size: 1.25em, [#author_strings.join(", ", last: " & ")] ) } if affiliations != none { titleblock( weight: "regular", size: 1.1em, below: 2em, for a in affiliations [ #if authors.len() > 1 [#super[#a.id]]#a.name#if a.keys().contains("department") [, #a.department] \ ] ) } // Abstract and keywords block block(inset: (top: 2em, bottom: 0em, left: 2.4em, right: 2.4em))[ #set text(size: 0.92em) #if abstract != none { abstract } #if keywords != none { [#v(0.4em)#text(style: "italic")[Keywords:] #keywords] } #if wordcount != none { [\ #text(style: "italic")[Words:] #wordcount] } ] // Table of contents if toc { let title = if toc-title == none { auto } else { toc-title } block(inset: (top: 2em, bottom: 0em, left: 2.4em, right: 2.4em))[ #outline( title: toc-title, depth: toc-depth, indent: toc-indent ) ] } /* Content */ // Separate content a bit from front matter v(2em) // Show document content with cols if specified if cols == 1 { doc } else { columns( cols, gutter: col-gutter, doc ) } } // Remove gridlines from tables #set table( inset: 6pt, stroke: none )
https://github.com/vEnhance/1802
https://raw.githubusercontent.com/vEnhance/1802/main/src/appendix.typ
typst
MIT License
#import "@local/evan:1.0.0":* = Appendix This entire section is not for exam, obviously. == If you are thinking of majoring in math... <appendix-math-major> During the course, one of the students asked me about academic advice saying they wanted to become a math major at MIT. If that also describes you, here's what I told them. The course numbers here are with respect to MIT, but this advice should hold equally well at other universities. === The two starter topics are algebra and analysis, not calculus It may come as a surprise to you that 18.02 isn't a prerequisite, even indirectly, for most upper-division math classes ($18.x y z$ for $x >= 1$). The two most important areas to take in pure math are *18.100* (real analysis) and *18.701--18.702* (algebra); these are sort of the barrier between the world of pre-university math and serious math. Once you clear these two classes, the floodgates open and the world of modern math is yours to explore (see the dependency chart in the Napkin for more on this). For example, if you take 18.701, the instructor will literally _throw away_ the "definitions" of linear transformations (and others) you learned in 18.02 and replace them with the "correct" ones. You've seen me do this already. Similarly, you will have new rigorous definitions of derivatives and integrals. In some sense, 18.100 is really _redoing_ all of 18.01 and 18.02 with actual proofs. === Proof-writing A prerequisite to both 18.100 (real analysis) and 18.701--18.702 (algebra) isn't any particular theory, but *proof experience*, and that's the biggest priority if you don't have that yet. (And I don't mean two-column proofs in 9th grade geometry. Two-column proofs were something made up for K-12 education and never used again.) At MIT, I've been told in recent years there's a class called 18.090 for this. This class is new enough I don't even have any secondhand accounts, but if Poonen is on the list of instructors who developed the course, I trust him. If you're at a different school, my suggestion would be to ask any of the math professors a question along the lines of "I'd like to major in math, but I don't have proof experience yet. Which class in your department corresponds to learning proof arguments?". They should know exactly what you're talking about. Alternatively, if you are willing to study proof-writing independently, the FAQ #url("https://web.evanchen.cc/faq-contest.html#C-5") on my website has some suggestions. In particular, if you're a textbook kind of person, the book I used growing up was Rotman's _Journey into Math: An Introduction to Proofs_, available at #url("https://store.doverpublications.com/products/9780486453064"); it worked well for me. I'm sure there are other suitable books as well. === The three phases of math education (from Tao's blog) Let me put proof-writing into the bigger framework. <NAME>, on his #link("https://terrytao.wordpress.com/career-advice/theres-more-to-mathematics-than-rigour-and-proofs/")[blog], describes a division of mathematical education into three stages. The descriptions that follows are copied verbatim from that link: 1. The “pre-rigorous” stage, in which mathematics is taught in an informal, intuitive manner, based on examples, fuzzy notions, and hand-waving. (For instance, calculus is usually first introduced in terms of slopes, areas, rates of change, and so forth.) The emphasis is more on computation than on theory. 2. The “rigorous” stage, in which one is now taught that in order to do maths “properly”, one needs to work and think in a much more precise and formal manner (e.g. re-doing calculus by using epsilons and deltas all over the place). The emphasis is now primarily on theory; and one is expected to be able to comfortably manipulate abstract mathematical objects without focusing too much on what such objects actually “mean”. 3. The “post-rigorous” stage, in which one has grown comfortable with all the rigorous foundations of one’s chosen field, and is now ready to revisit and refine one’s pre-rigorous intuition on the subject, but this time with the intuition solidly buttressed by rigorous theory. (For instance, in this stage one would be able to quickly and accurately perform computations in vector calculus by using analogies with scalar calculus, or informal and semi-rigorous use of infinitesimals, big-O notation, and so forth, and be able to convert all such calculations into a rigorous argument whenever required.) The emphasis is now on applications, intuition, and the “big picture”. These notes are still in the first stage. The introduction-to-proofs class at your school will essentially be the beginning of the second stage. #pagebreak() == Proof that the algebraic definition of dot product matches the geometric one <appendix-dotpf> We have two definitions in play and we want to show they coincide, which makes notation awkward. So in what follows, our notation $bf(u) dot bf(v)$ will always refer to the _geometric_ definition; that is $bf(u) dot bf(v) := |bf(u)| |bf(v)| cos theta$. And our goal is to show that it matches the algebraic definition. We will assume that $|bf(u)| = 1$ (i.e. $bf(u)$ is a unit vector) so that $bf(u) dot bf(v)$ is the length of the projection of $bf(v)$ onto $bf(u)$. This is OK to assume because in the general case one just scales everything by $|bf(u)|$. === Easy special case As a warmup, try to show that if $bf(u) = vec(a,b)$ is any vector, then $bf(u) dot bf(e)_1 = a$. (This is easy. The projection of $bf(u)$ onto $bf(e)_1$ is literally $a$.) === Main proof #figure( image("figures/r02-dotproof.png", width: 75%), caption: [Proof that the dot product is given by the projection], ) For concreteness, specialize to $RR^2$ and consider $bf(u) dot bf(v)$ where $bf(u) = vec(a,b)$ is a unit vector (i.e. $bf(u) = 1$), and $bf(v) = vec(x,y)$ is any vector in $RR^2$. Then we want to show that the projection of $bf(v)$ onto $bf(u)$ has length $x a + y b$. The basic idea is to decompose $bf(v) = x bf(e)_1 + y bf(e)_2$. The length of projection of $bf(v)$ onto $bf(u)$ can be decomposed then into the lengths of projections of $x bf(e)_1$ and $y bf(e)_2$. (To see this, tilt your head so the green line is horizontal; recall that the black quadrilateral is a rectangle, hence also a parallelogram). In other words, $ bf(u) dot bf(v) = bf(u) dot (x bf(e)_1 + y bf(e)_2) = x (bf(u) dot bf(e)_1) + y (bf(u) dot bf(e)_2). $ But we already did the special cases before: $ bf(u) dot bf(e)_1 &= a \ bf(u) dot bf(e)_2 &= b. $ Hence, we get the right-hand side is $ bf(u) dot bf(v) = x a + y b, $ as advertised. In summary, by using the black parallelogram, we were able to split $bf(u) dot bf(v)$ into two easy cases we already know how to do. The same idea will work in $RR^3$ if you use $bf(v) = x bf(e)_1 + y bf(e)_2 + z bf(e)_3$ instead, and replace the parallelogram with a parallelepiped, in which case one now has $3$ easy cases. And so on in $n$ dimensions. #pagebreak() == Saddle point simulation code for @sec-saddle-sim <appendix-saddle-sim> #raw(read("include/saddle-demo.py"), lang: "py")
https://github.com/saveriogzz/curriculum-vitae
https://raw.githubusercontent.com/saveriogzz/curriculum-vitae/main/modules/education.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Education") #cvEntry( title: [M.Sc. Industrial Engineering and Management], society: [Politecno di Torino], date: [2016 - 2018], location: [Turin, Italy], logo: "../src/logos/polito_square.png", description: list( [Thesis: Predicting Customer Churn in Telecommunications Industry using Machine Learning Algorithms and Network Analysis], [Course: Big Data Systems and Technologies #hBar() Data Mining and Exploration #hBar() Natural Language Processing] ) ) #cvEntry( title: [B.Sc. Industrial Engineering], society: [Politecno di Torino], date: [2011 - 2016], location: [Turin, Italy], logo: "../src/logos/polito_square.png", description: list( [Thesis: Exploring the Use of Machine Learning Algorithms for Predicting Stock Prices: A Comparative Study of Regression and Time-Series Models], [Course: Database Systems #hBar() Computer Networks #hBar() Software Engineering #hBar() Artificial Intelligence] ) )
https://github.com/tingerrr/hydra
https://raw.githubusercontent.com/tingerrr/hydra/main/tests/regressions/fallback-to-future/test.typ
typst
MIT License
// Synopsis: // - When both last and prev candidates where none hydra would fall back to a heading defined on a future page. // Headings defined after the current page should never be displayed. #import "/src/lib.typ": hydra #set page( paper: "a7", header: context hydra(), ) #set heading(numbering: "1.1") #show heading.where(level: 1): it => pagebreak(weak: true) + it #set par(justify: true) #lorem(100) = Introduction #lorem(100)
https://github.com/ohmycloud/computer-science-notes
https://raw.githubusercontent.com/ohmycloud/computer-science-notes/main/Misc/edits_inprogress.typ
typst
#show heading: it => { set text(red) [#it.body] v(1em) } #show heading.where(level: 1): it => { set text(red) align(center)[#it.body] } #outline( title: "目 录", target: heading.where(level: 2) ) = 记一次因为删除 HDFS 数据导致的集群故障修复历程 == 问题描述 NameNode 重启失败, 重要报错日志如下: ``` FATAL org/apache.hdfs.server.namenode.FSEditLog: Error: revoverUnfinalizedSegments failed for required journal ``` == 问题复盘 导致这个问题的原因是因为集群报了磁盘空间不够。删除了一部分 subdir 目录后, 清理出了一部分磁盘空间, 但是 edits 文件有损坏。 == 问题定位 监听 JOURNALNODE 的日志: ```sh tail -f /var/log/hadoop-hdfs/hadoop-cmf-hdfs-JOURNALNODE-work001.log.out tail -f /var/log/hadoop-hdfs/hadoop-cmf-hdfs-JOURNALNODE-work002.log.out tail -f /var/log/hadoop-hdfs/hadoop-cmf-hdfs-JOURNALNODE-work003.log.out ``` 重启 JOURNALNODE, 看到 work001 和 work002 节点的日志如下: ``` work001: 2023-11-23 11:42:22,809 WARN org.apache.hadoop.hdfs.server.namenode.FSImage: Caught exception after scanning through 0 ops from /mnt/data1/dfs/jn/circue1/current/edits_inprogress_0000000000129404576 while determining its valid length. Position was 176128 work002: 2023-11-23 11:50:07,992 WARN org.apache.hadoop.hdfs.server.namenode.FSImage: Caught exception after scanning through 0 ops from /mnt/data1/dfs/jn/circue1/current/edits_inprogress_0000000000060194739 while determining its valid length. Position was 1044480 ``` 这说明, 文件 edits_inprogress_0000000000129404576 和文件 edits_inprogress_0000000000060194739 损坏了。 而 work003 的日志正常。 这就导致了集群的 master001 和 master002 节点一直无法重启成功。 == 问题修复 解决方法:把正常节点的 /mnt/data1/dfs/jn/circue1/current 目录下的所有文件复制到不正常节点的对应目录。 ```bash # 备份旧的 JOURNALNODE 数据 tar -zcvf jn_current.tar.gz /mnt/data1/dfs/jn/circue1/current # 删除旧的 JOURNALNODE 数据 cd /mnt/data1/dfs/jn/circue1/current rm -rf ./* # 从其它节点拷贝 JOURNALNODE 数据 scp -r root@work003:/mnt/data1/dfs/jn/circue1/current/* . # 修正目录权限 chown -R hdfs:hdfs /mnt/data1/dfs/jn/circue1/current ``` 然后重启 JOURNALNODE 和 master 角色。
https://github.com/Jollywatt/typst-wordometer
https://raw.githubusercontent.com/Jollywatt/typst-wordometer/master/docs/manual.typ
typst
MIT License
#import "@preview/tidy:0.1.0" #import "/src/lib.typ" as wordometer: * #set page(numbering: "1") #set par(justify: true) #show link: underline.with(stroke: blue.lighten(50%)) #let VERSION = toml("/typst.toml").package.version #let show-module(path) = { show heading.where(level: 3): it => { align(center, line(length: 100%, stroke: black.lighten(70%))) block(text(1.3em, raw(it.body.text + "()"))) } tidy.show-module( tidy.parse-module( read(path), scope: (wordometer: wordometer) ), show-outline: false, sort-functions: x => { str(int(not x.name.starts-with("word-count"))) + x.name } ) } #show: word-count #v(.2fr) #align(center)[ #stack( spacing: 12pt, text(2.7em, `wordometer`), [_This manual contains #total-words words._], ) #v(30pt) A small #link("https://typst.app/")[Typst] package for quick and easy in-document word counts. #link("https://github.com/Jollywatt/typst-wordometer")[`github.com/Jollywatt/typst-wordometer`] Version #VERSION ] #set raw(lang: "typc") // bug in typst v0.11.0 // https://github.com/typst/typst/pull/3847 // remove once fixed #show raw.where(block: true): it => { set text(1.25em) block(raw(it.text.replace("\t", " "), lang: it.lang)) } #v(1fr) #[ #show heading: pad.with(y: 10pt) = Basic usage #show "VERSION": VERSION ```typ #import "@preview/wordometer:VERSION": word-count, total-words #show: word-count In this document, there are #total-words words all up. #word-count(total => [ The number of words in this block is #total.words and there are #total.characters letters. ]) ``` = Excluding elements You can exclude elements by function (e.g., `heading`, `table`, `figure.caption`), by where-selector (e.g., `raw.where(block: true)`), or by label (e.g., `<no-wc>`). ```typ #show: word-count.with(exclude: (heading.where(level: 1), strike)) = This Heading Doesn't Count == But I do! In this document #strike[(excluding me)], there are #total-words words all up. #word-count(total => [ You can exclude elements by label, too. #[That was #total.words, excluding this sentence!] <no-wc> ], exclude: <no-wc>) ``` ] #v(1fr) #pagebreak() #let fn(name) = { let text = extract-text(name) link(label(text), raw(text)) } #let scope = ( word-count: word-count, word-count-of: word-count-of, ) #let example-pair(code) = { let result = eval(code.text, mode: "markup", scope: scope) (code, result) } = Details The basic #fn[word-count-of()] function accepts content and returns a dictionary of statistics. The main #fn[word-count()] function wraps this in a more convenient interface, for use in a document show rule: ```typ #show: word-count ``` ...or for scoped word counts: ```typ #word-count(total => [There are #total.words total words.]) ``` The actual word counting works by using #fn[extract-text()] to convert content to a plain string which is split up into words, sentences, and so on. You can specify exactly what is counted via the `counter` argument of most functions. The #fn[extract-text()] function uses #fn[map-tree()] to traverse a content tree and accumulate the text from each leaf node. The #fn[map-tree()] function (and most of the other functions) has an `exclude` parameter, which is used to exclude certain elements from the word count. The following elements have no text content and are always excluded: #IGNORED_ELEMENTS.sorted().map(raw).join([, ], last: [, and ]). == Where this doesn't work Word counting with #fn[extract-text()] occurs *before show rules are applied*, which means content modified by show rules may get counted differently to how it looks finally. == Ways to exclude elements - By element: #table( columns: (2fr, 1fr), ..example-pair(```typ #word-count-of(exclude: strong)[One *not* two.].words ```), ..example-pair(```typ #word-count(exclude: (heading, highlight), total => [ = Not me One two #highlight[me neither] three. \ #total.words words including this line. ]) ```), ) - By label: #table( columns: (2fr, 1fr), ..example-pair(```typ #word-count-of(exclude: <not-me>, [ One #[(not I)] <not-me> two three. ]) ```), ..example-pair(```typ #word-count(exclude: <not-me>, total => [ One, two, three, four. #[That was #total.words words.] <not-me> ]) ```), ) - By `where` selector: #table( columns: (2fr, 1fr), ..example-pair(````typ #word-count-of(exclude: raw.where(lang: "python"))[ ```python print("Hello, World!") ``` Only I count. ] ````), ) #pagebreak() = Functions #show-module("/src/lib.typ")
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/poc/options.typ
typst
#import "../../../style.typ": include_section #import "../../../acronyms.typ": ac = Implementation Options Different implementation options were considered for the #ac("PoC"). The following sections describe the options that were considered and choices that have been made. == Deployment platform <deployment-platform-options> For VisualFP, two possible deployment platforms were considered: A web application or a desktop application. #include_section("design_concept/content/poc/options_deployment_desktopapp.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_deployment_webapp.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_deployment_decision.typ", heading_increase: 2) == UI Frameworks <ui-framework-options> VisualFP requires external technologies to implement a #ac("UI"), especially to achieve cross-platform support without duplication. The following technologies were considered. #include_section("design_concept/content/poc/options_ui_electron.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_ui_haskellgi.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_ui_threepenny.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_ui_ghcjs.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_ui_bolero.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_ui_decision.typ", heading_increase: 2) == Compiler Platform <compiler-platform-options> A compiler platform is a set of tools and libraries that can be used to compile code. VisualFP requires a compiler platform to build the application itself but also as a library to compile programs created by the users in the visual editor. These two use cases pose different requirements on the compiler platform: - To be used as a compiler, the platform must have a set of support tooling available, such as a build tool and a language server. - To be used as a library, the compiler platform must offer a well-defined #ac("API") that can be used to create, parse, and compile an #ac("AST") programmatically. For these two use cases, two different compiler platforms may be used. The compiler used to build the #ac("PoC") itself depends on the language and other frameworks chosen to implement the application. This section focuses on the use of a compiler platform as a library. #include_section("design_concept/content/poc/options_compiler_ghc.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_compiler_other.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_compiler_custom.typ", heading_increase: 2) #include_section("design_concept/content/poc/options_compiler_decision.typ", heading_increase: 2)
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/util/typst.typ
typst
MIT License
// ================================ // = Aliases = // ================================ // // Aliases for some native Typst functions and types #let pagebreak = pagebreak #let measure = measure #let type = type #let stroke = stroke #let document = document #let numbering = numbering #let text = text #let content = content #let align = align #let label = label
https://github.com/Kasci/LiturgicalBooks
https://raw.githubusercontent.com/Kasci/LiturgicalBooks/master/SK/zalmy/Z142.typ
typst
Pane, vyslyš moju modlitbu, pre svoju vernosť vypočuj moju úpenlivú prosbu, \* pre svoju spravodlivosť ma vyslyš. A svojho služobníka na súd nevolaj, \* veď nik, kým žije, nie je spravodlivý pred tebou. Nepriateľ ma prenasleduje, zráža ma k zemi, \* do temnôt ma vrhá ako dávno mŕtveho. Duch sa mi zmieta v úzkostiach; \* v hrudi mi srdce meravie. Spomínam si na uplynulé dni, o všetkých tvojich skutkoch rozmýšľam \* a uvažujem o dielach tvojich rúk. Vystieram k tebe ruky, \* za tebou dychtím ako vyprahnutá zem. Rýchle ma vyslyš, Pane, \* lebo už klesám na duchu. Neskrývaj predo mnou svoju tvár, \* aby som nebol ako tí, čo zostupujú do hrobu. Včasráno mi daj pocítiť, že si sa zmiloval nado mnou, \* lebo sa spolieham na teba. Ukáž mi cestu, po ktorej mám kráčať, \* veď svoju dušu dvíham k tebe. Pred nepriateľmi ma zachráň; \* Pane, k tebe sa utiekam. Nauč ma plniť tvoju vôľu, lebo ty si môj Boh; \* na správnu cestu nech ma vedie tvoj dobrý duch. Pre svoje meno, Pane, zachováš ma nažive; \* pretože si spravodlivý, vyveď ma z úzkosti. Vo svojom milosrdenstve znič mojich nepriateľov, \* zahub všetkých, čo ma sužujú, veď ja som tvoj služobník. Pre svoju spravodlivosť ma vyslyš \* a svojho služobníka na súd nevolaj. Pre svoju spravodlivosť ma vyslyš \* a svojho služobníka na súd nevolaj. Na správnu cestu \* nech ma vedie tvoj dobrý duch.
https://github.com/HarryLuoo/sp24
https://raw.githubusercontent.com/HarryLuoo/sp24/main/math321/hw10.typ
typst
= HW 10 <NAME> <EMAIL> == 1. $ integral_(C) &(y^2 + sin x) dif x+ (3x y + y^(4) )dif y, quad D={(r,theta)| r in [0,2], theta in [0,pi/2]} \ &= integral_D ((diff( 3x y + y^(4) ))/(diff x) - (diff y^2 + sin x)/(diff y)) dif A \ &= integral_D (3y - 2y) dif A \ & = integral_D y dif A quad quad quad "polar transform:" cases(dif A = r dif r dif theta, r in [0,2], theta in [0,pi/2]) \ & = integral_0^(pi/2) integral_0^2 r^2 sin theta dif r dif theta \ & = integral_(0)^(pi/2) sin theta dif theta integral_(0)^(2)r^2 dif r\ & = integral_(0)^(pi/2)8/3 sin theta dif theta \ & = 8/3 \ $ == 2 $ integral_(C)&(x^(5) + y^(3)) d x - (x^(3)+y^(5) ) d y , C: x^2+y^2=4 \ & = integral_(D) (diff (-x^(3) - y^(3) ))/(diff x) - (diff (x^(5) + y^(3) ))/(diff y)) dif A \ & = integral_(D) (-3x^(2) - 3y^(2) ) dif A \ & = integral_(D)-3(x^2+y^2) dif A quad quad T: theta in [0,2pi], r in [0,2] \ & = integral_(0)^(2pi) integral_(0)^(2) -3r^2 r dif r dif theta \ & = integral_(0)^(2) -6pi r^(3) dif r \ & = -24 pi $ == 3 $ (diff M)/(diff x) = (diff (7y + sqrt(y^3 +1) ))/(diff x) = 0 \ (diff N)/(diff y) = (diff (3y - e^(sin(x^2)) ))/(diff y) = 3\ "by greens" integral_(D)(-3) dif A =-3 integral_(0)^(2pi) integral_(0)^(1)r dif r dif theta = -3pi $ == 4 $ integral_(C)(e^(sqrt(x+1))+y^2 +1 ) dif x + sin (y^2 - 1) +x^2 dif y\ (diff (sin (y^2 - 1) +x^2))/(diff x) = 2x\ (diff( e^(sqrt(x+1)))+y^2 +1 )/(diff y) = 2y \ "by greens" integral_(D)(2y - 2x) dif A \ = integral_(0)^(2) integral_(0)^(1-x/2) 2x-2y dif x dif y\ = integral_(0)^(2) -5/4 x^2 + 3x -1 dif x = 2/3 $ == 5 #image("hw101.png") #image("hw102.png") == 6 $ (diff arrow(r))/(diff u)= (1,1,2), quad (diff arrow(r))/(diff v) = (1,-1,1) \ (diff arrow(r))/(diff u) times (diff arrow(r))/(diff v) = (3,1,-2) \ integral_(D)arrow(F) dif S = integral_(D)arrow(F) dot (diff arrow(r))/(diff u) times (diff arrow(r))/(diff v) dif u dif v \ = integral_(D)(u+v,u-v,1+2u+v) dot (3,-1,-2) dif u dif v \ = integral_(D)(3u+3v-u+v-2-4u-2v) d u d v\ = integral_(D)(-2u+2v-2) d u d v\ = integral_(0)^(1) integral_(0)^(1) -2u+2v-2) dif u dif v\ = -2 $ == 7 $ integral_(D) (y,x^2+y^2,x^2) dot (-2x,-2y,1) dif A\ = integral_(0)^(1) integral_(0)^(1) (-2x y -2 x^2y -2y^(3)+x^2 ) dif x dif y\ = integral_(0)^(1)(-5/3y - 2 y^3 + 1/3) dif y\ = -1 $
https://github.com/ShapeLayer/ucpc-solutions__typst
https://raw.githubusercontent.com/ShapeLayer/ucpc-solutions__typst/main/tests/utils_make-prob-meta/test.typ
typst
Other
#import "/lib/lib.typ" as ucpc #import ucpc.utils: make-prob-meta #make-prob-meta( tags: ("a", ), difficulty: "diff", authors: "author", i18n: ucpc.i18n.en-us.make-prob-meta )